src/Pure/Isar/toplevel.ML
author haftmann
Thu Aug 12 13:28:18 2010 +0200 (2010-08-12)
changeset 38389 d7d915bae307
parent 38388 94d5624dd1f7
child 38391 ba1cc1815ce1
permissions -rw-r--r--
Named_Target.init: empty string represents theory target
     1 (*  Title:      Pure/Isar/toplevel.ML
     2     Author:     Markus Wenzel, TU Muenchen
     3 
     4 Isabelle/Isar toplevel transactions.
     5 *)
     6 
     7 signature TOPLEVEL =
     8 sig
     9   exception UNDEF
    10   type state
    11   val toplevel: state
    12   val is_toplevel: state -> bool
    13   val is_theory: state -> bool
    14   val is_proof: state -> bool
    15   val level: state -> int
    16   val presentation_context_of: state -> Proof.context
    17   val previous_context_of: state -> Proof.context option
    18   val context_of: state -> Proof.context
    19   val generic_theory_of: state -> generic_theory
    20   val theory_of: state -> theory
    21   val proof_of: state -> Proof.state
    22   val proof_position_of: state -> int
    23   val end_theory: Position.T -> state -> theory
    24   val print_state_context: state -> unit
    25   val print_state: bool -> state -> unit
    26   val pretty_abstract: state -> Pretty.T
    27   val quiet: bool Unsynchronized.ref
    28   val debug: bool Unsynchronized.ref
    29   val interact: bool Unsynchronized.ref
    30   val timing: bool Unsynchronized.ref
    31   val profiling: int Unsynchronized.ref
    32   val skip_proofs: bool Unsynchronized.ref
    33   exception TERMINATE
    34   exception TOPLEVEL_ERROR
    35   val program: (unit -> 'a) -> 'a
    36   val thread: bool -> (unit -> unit) -> Thread.thread
    37   type transition
    38   val empty: transition
    39   val init_of: transition -> string option
    40   val name_of: transition -> string
    41   val pos_of: transition -> Position.T
    42   val str_of: transition -> string
    43   val name: string -> transition -> transition
    44   val position: Position.T -> transition -> transition
    45   val interactive: bool -> transition -> transition
    46   val print: transition -> transition
    47   val no_timing: transition -> transition
    48   val init_theory: string -> (unit -> theory) -> transition -> transition
    49   val modify_init: (unit -> theory) -> transition -> transition
    50   val exit: transition -> transition
    51   val keep: (state -> unit) -> transition -> transition
    52   val keep': (bool -> state -> unit) -> transition -> transition
    53   val imperative: (unit -> unit) -> transition -> transition
    54   val ignored: Position.T -> transition
    55   val malformed: Position.T -> string -> transition
    56   val theory: (theory -> theory) -> transition -> transition
    57   val generic_theory: (generic_theory -> generic_theory) -> transition -> transition
    58   val theory': (bool -> theory -> theory) -> transition -> transition
    59   val begin_local_theory: bool -> (theory -> local_theory) -> transition -> transition
    60   val end_local_theory: transition -> transition
    61   val local_theory': xstring option -> (bool -> local_theory -> local_theory) ->
    62     transition -> transition
    63   val local_theory: xstring option -> (local_theory -> local_theory) -> transition -> transition
    64   val present_local_theory: xstring option -> (state -> unit) -> transition -> transition
    65   val local_theory_to_proof': xstring option -> (bool -> local_theory -> Proof.state) ->
    66     transition -> transition
    67   val local_theory_to_proof: xstring option -> (local_theory -> Proof.state) ->
    68     transition -> transition
    69   val theory_to_proof: (theory -> Proof.state) -> transition -> transition
    70   val end_proof: (bool -> Proof.state -> Proof.context) -> transition -> transition
    71   val forget_proof: transition -> transition
    72   val present_proof: (state -> unit) -> transition -> transition
    73   val proofs': (bool -> Proof.state -> Proof.state Seq.seq) -> transition -> transition
    74   val proof': (bool -> Proof.state -> Proof.state) -> transition -> transition
    75   val proofs: (Proof.state -> Proof.state Seq.seq) -> transition -> transition
    76   val proof: (Proof.state -> Proof.state) -> transition -> transition
    77   val actual_proof: (Proof_Node.T -> Proof_Node.T) -> transition -> transition
    78   val skip_proof: (int -> int) -> transition -> transition
    79   val skip_proof_to_theory: (int -> bool) -> transition -> transition
    80   val get_id: transition -> string option
    81   val put_id: string -> transition -> transition
    82   val unknown_theory: transition -> transition
    83   val unknown_proof: transition -> transition
    84   val unknown_context: transition -> transition
    85   val setmp_thread_position: transition -> ('a -> 'b) -> 'a -> 'b
    86   val status: transition -> Markup.T -> unit
    87   val error_msg: transition -> exn * string -> unit
    88   val add_hook: (transition -> state -> state -> unit) -> unit
    89   val transition: bool -> transition -> state -> (state * (exn * string) option) option
    90   val run_command: string -> transition -> state -> state option
    91   val command: transition -> state -> state
    92   val excursion: (transition * transition list) list -> (transition * state) list lazy * theory
    93 end;
    94 
    95 structure Toplevel: TOPLEVEL =
    96 struct
    97 
    98 (** toplevel state **)
    99 
   100 exception UNDEF = Runtime.UNDEF;
   101 
   102 
   103 (* local theory wrappers *)
   104 
   105 val loc_init = Named_Target.context_cmd;
   106 val loc_exit = Local_Theory.exit_global;
   107 
   108 fun loc_begin loc (Context.Theory thy) = loc_init (the_default "-" loc) thy
   109   | loc_begin NONE (Context.Proof lthy) = lthy
   110   | loc_begin (SOME loc) (Context.Proof lthy) = loc_init loc (loc_exit lthy);
   111 
   112 fun loc_finish _ (Context.Theory _) = Context.Theory o loc_exit
   113   | loc_finish NONE (Context.Proof _) = Context.Proof o Local_Theory.restore
   114   | loc_finish (SOME _) (Context.Proof lthy) = fn lthy' => let
   115         val target = #target (Named_Target.peek lthy);
   116       in Context.Proof (Named_Target.init target (loc_exit lthy')) end;
   117 
   118 
   119 (* datatype node *)
   120 
   121 datatype node =
   122   Theory of generic_theory * Proof.context option
   123     (*theory with presentation context*) |
   124   Proof of Proof_Node.T * ((Proof.context -> generic_theory) * generic_theory)
   125     (*proof node, finish, original theory*) |
   126   SkipProof of int * (generic_theory * generic_theory);
   127     (*proof depth, resulting theory, original theory*)
   128 
   129 val theory_node = fn Theory (gthy, _) => SOME gthy | _ => NONE;
   130 val proof_node = fn Proof (prf, _) => SOME prf | _ => NONE;
   131 
   132 fun cases_node f _ (Theory (gthy, _)) = f gthy
   133   | cases_node _ g (Proof (prf, _)) = g (Proof_Node.current prf)
   134   | cases_node f _ (SkipProof (_, (gthy, _))) = f gthy;
   135 
   136 val context_node = cases_node Context.proof_of Proof.context_of;
   137 
   138 
   139 (* datatype state *)
   140 
   141 datatype state = State of node option * node option;  (*current, previous*)
   142 
   143 val toplevel = State (NONE, NONE);
   144 
   145 fun is_toplevel (State (NONE, _)) = true
   146   | is_toplevel _ = false;
   147 
   148 fun level (State (NONE, _)) = 0
   149   | level (State (SOME (Theory _), _)) = 0
   150   | level (State (SOME (Proof (prf, _)), _)) = Proof.level (Proof_Node.current prf)
   151   | level (State (SOME (SkipProof (d, _)), _)) = d + 1;   (*different notion of proof depth!*)
   152 
   153 fun str_of_state (State (NONE, _)) = "at top level"
   154   | str_of_state (State (SOME (Theory (Context.Theory _, _)), _)) = "in theory mode"
   155   | str_of_state (State (SOME (Theory (Context.Proof _, _)), _)) = "in local theory mode"
   156   | str_of_state (State (SOME (Proof _), _)) = "in proof mode"
   157   | str_of_state (State (SOME (SkipProof _), _)) = "in skipped proof mode";
   158 
   159 
   160 (* current node *)
   161 
   162 fun node_of (State (NONE, _)) = raise UNDEF
   163   | node_of (State (SOME node, _)) = node;
   164 
   165 fun is_theory state = not (is_toplevel state) andalso is_some (theory_node (node_of state));
   166 fun is_proof state = not (is_toplevel state) andalso is_some (proof_node (node_of state));
   167 
   168 fun node_case f g state = cases_node f g (node_of state);
   169 
   170 fun presentation_context_of state =
   171   (case try node_of state of
   172     SOME (Theory (_, SOME ctxt)) => ctxt
   173   | SOME node => context_node node
   174   | NONE => raise UNDEF);
   175 
   176 fun previous_context_of (State (_, NONE)) = NONE
   177   | previous_context_of (State (_, SOME prev)) = SOME (context_node prev);
   178 
   179 val context_of = node_case Context.proof_of Proof.context_of;
   180 val generic_theory_of = node_case I (Context.Proof o Proof.context_of);
   181 val theory_of = node_case Context.theory_of Proof.theory_of;
   182 val proof_of = node_case (fn _ => raise UNDEF) I;
   183 
   184 fun proof_position_of state =
   185   (case node_of state of
   186     Proof (prf, _) => Proof_Node.position prf
   187   | _ => raise UNDEF);
   188 
   189 fun end_theory _ (State (NONE, SOME (Theory (Context.Theory thy, _)))) = Theory.end_theory thy
   190   | end_theory pos _ = error ("Unfinished theory at end of input" ^ Position.str_of pos);
   191 
   192 
   193 (* print state *)
   194 
   195 val pretty_context = Local_Theory.pretty o Context.cases (Named_Target.theory_init) I;
   196 
   197 fun print_state_context state =
   198   (case try node_of state of
   199     NONE => []
   200   | SOME (Theory (gthy, _)) => pretty_context gthy
   201   | SOME (Proof (_, (_, gthy))) => pretty_context gthy
   202   | SOME (SkipProof (_, (gthy, _))) => pretty_context gthy)
   203   |> Pretty.chunks |> Pretty.writeln;
   204 
   205 fun print_state prf_only state =
   206   (case try node_of state of
   207     NONE => []
   208   | SOME (Theory (gthy, _)) => if prf_only then [] else pretty_context gthy
   209   | SOME (Proof (prf, _)) =>
   210       Proof.pretty_state (Proof_Node.position prf) (Proof_Node.current prf)
   211   | SOME (SkipProof (d, _)) => [Pretty.str ("skipped proof: depth " ^ string_of_int d)])
   212   |> Pretty.markup_chunks Markup.state |> Pretty.writeln;
   213 
   214 fun pretty_abstract state = Pretty.str ("<Isar " ^ str_of_state state ^ ">");
   215 
   216 
   217 
   218 (** toplevel transitions **)
   219 
   220 val quiet = Unsynchronized.ref false;
   221 val debug = Output.debugging;
   222 val interact = Unsynchronized.ref false;
   223 val timing = Output.timing;
   224 val profiling = Unsynchronized.ref 0;
   225 val skip_proofs = Unsynchronized.ref false;
   226 
   227 exception TERMINATE = Runtime.TERMINATE;
   228 exception EXCURSION_FAIL = Runtime.EXCURSION_FAIL;
   229 exception TOPLEVEL_ERROR = Runtime.TOPLEVEL_ERROR;
   230 
   231 fun program body =
   232  (body
   233   |> Runtime.controlled_execution
   234   |> Runtime.toplevel_error (Output.error_msg o ML_Compiler.exn_message)) ();
   235 
   236 fun thread interrupts body =
   237   Thread.fork
   238     (((fn () => body () handle Exn.Interrupt => ())
   239         |> Runtime.debugging
   240         |> Runtime.toplevel_error
   241           (fn exn => priority ("## INTERNAL ERROR ##\n" ^ ML_Compiler.exn_message exn))),
   242       Simple_Thread.attributes interrupts);
   243 
   244 
   245 (* node transactions -- maintaining stable checkpoints *)
   246 
   247 exception FAILURE of state * exn;
   248 
   249 local
   250 
   251 fun reset_presentation (Theory (gthy, _)) = Theory (gthy, NONE)
   252   | reset_presentation node = node;
   253 
   254 fun is_draft_theory (Theory (gthy, _)) = Context.is_draft (Context.theory_of gthy)
   255   | is_draft_theory _ = false;
   256 
   257 fun is_stale state = Context.is_stale (theory_of state) handle Runtime.UNDEF => false;
   258 
   259 fun stale_error NONE = SOME (ERROR "Stale theory encountered after successful execution!")
   260   | stale_error some = some;
   261 
   262 fun map_theory f (Theory (gthy, ctxt)) =
   263       Theory (Context.mapping f (Local_Theory.raw_theory f) gthy, ctxt)
   264   | map_theory _ node = node;
   265 
   266 in
   267 
   268 fun apply_transaction f g node =
   269   let
   270     val _ = is_draft_theory node andalso error "Illegal draft theory in toplevel state";
   271     val cont_node = reset_presentation node;
   272     val back_node = map_theory (Theory.checkpoint o Theory.copy) cont_node;
   273     fun state_error e nd = (State (SOME nd, SOME node), e);
   274 
   275     val (result, err) =
   276       cont_node
   277       |> Runtime.controlled_execution f
   278       |> map_theory Theory.checkpoint
   279       |> state_error NONE
   280       handle exn => state_error (SOME exn) cont_node;
   281 
   282     val (result', err') =
   283       if is_stale result then state_error (stale_error err) back_node
   284       else (result, err);
   285   in
   286     (case err' of
   287       NONE => tap g result'
   288     | SOME exn => raise FAILURE (result', exn))
   289   end;
   290 
   291 end;
   292 
   293 
   294 (* primitive transitions *)
   295 
   296 datatype trans =
   297   Init of string * (unit -> theory) |    (*theory name, init*)
   298   Exit |                                 (*formal exit of theory*)
   299   Keep of bool -> state -> unit |        (*peek at state*)
   300   Transaction of (bool -> node -> node) * (state -> unit);  (*node transaction and presentation*)
   301 
   302 local
   303 
   304 fun apply_tr _ (Init (_, f)) (State (NONE, _)) =
   305       State (SOME (Theory (Context.Theory
   306           (Theory.checkpoint (Runtime.controlled_execution f ())), NONE)), NONE)
   307   | apply_tr _ Exit (State (prev as SOME (Theory (Context.Theory _, _)), _)) =
   308       State (NONE, prev)
   309   | apply_tr int (Keep f) state =
   310       Runtime.controlled_execution (fn x => tap (f int) x) state
   311   | apply_tr int (Transaction (f, g)) (State (SOME state, _)) =
   312       apply_transaction (fn x => f int x) g state
   313   | apply_tr _ _ _ = raise UNDEF;
   314 
   315 fun apply_union _ [] state = raise FAILURE (state, UNDEF)
   316   | apply_union int (tr :: trs) state =
   317       apply_union int trs state
   318         handle Runtime.UNDEF => apply_tr int tr state
   319           | FAILURE (alt_state, UNDEF) => apply_tr int tr alt_state
   320           | exn as FAILURE _ => raise exn
   321           | exn => raise FAILURE (state, exn);
   322 
   323 in
   324 
   325 fun apply_trans int trs state = (apply_union int trs state, NONE)
   326   handle FAILURE (alt_state, exn) => (alt_state, SOME exn) | exn => (state, SOME exn);
   327 
   328 end;
   329 
   330 
   331 (* datatype transition *)
   332 
   333 datatype transition = Transition of
   334  {name: string,              (*command name*)
   335   pos: Position.T,           (*source position*)
   336   int_only: bool,            (*interactive-only*)
   337   print: bool,               (*print result state*)
   338   no_timing: bool,           (*suppress timing*)
   339   trans: trans list};        (*primitive transitions (union)*)
   340 
   341 fun make_transition (name, pos, int_only, print, no_timing, trans) =
   342   Transition {name = name, pos = pos, int_only = int_only, print = print, no_timing = no_timing,
   343     trans = trans};
   344 
   345 fun map_transition f (Transition {name, pos, int_only, print, no_timing, trans}) =
   346   make_transition (f (name, pos, int_only, print, no_timing, trans));
   347 
   348 val empty = make_transition ("", Position.none, false, false, false, []);
   349 
   350 
   351 (* diagnostics *)
   352 
   353 fun init_of (Transition {trans = [Init (name, _)], ...}) = SOME name
   354   | init_of _ = NONE;
   355 
   356 fun name_of (Transition {name, ...}) = name;
   357 fun pos_of (Transition {pos, ...}) = pos;
   358 fun str_of tr = quote (name_of tr) ^ Position.str_of (pos_of tr);
   359 
   360 fun command_msg msg tr = msg ^ "command " ^ str_of tr;
   361 fun at_command tr = command_msg "At " tr ^ ".";
   362 
   363 fun type_error tr state =
   364   ERROR (command_msg "Illegal application of " tr ^ " " ^ str_of_state state);
   365 
   366 
   367 (* modify transitions *)
   368 
   369 fun name name = map_transition (fn (_, pos, int_only, print, no_timing, trans) =>
   370   (name, pos, int_only, print, no_timing, trans));
   371 
   372 fun position pos = map_transition (fn (name, _, int_only, print, no_timing, trans) =>
   373   (name, pos, int_only, print, no_timing, trans));
   374 
   375 fun interactive int_only = map_transition (fn (name, pos, _, print, no_timing, trans) =>
   376   (name, pos, int_only, print, no_timing, trans));
   377 
   378 val no_timing = map_transition (fn (name, pos, int_only, print, _, trans) =>
   379   (name, pos, int_only, print, true, trans));
   380 
   381 fun add_trans tr = map_transition (fn (name, pos, int_only, print, no_timing, trans) =>
   382   (name, pos, int_only, print, no_timing, tr :: trans));
   383 
   384 val reset_trans = map_transition (fn (name, pos, int_only, print, no_timing, _) =>
   385   (name, pos, int_only, print, no_timing, []));
   386 
   387 fun set_print print = map_transition (fn (name, pos, int_only, _, no_timing, trans) =>
   388   (name, pos, int_only, print, no_timing, trans));
   389 
   390 val print = set_print true;
   391 
   392 
   393 (* basic transitions *)
   394 
   395 fun init_theory name f = add_trans (Init (name, f));
   396 
   397 fun modify_init f tr =
   398   (case init_of tr of
   399     SOME name => init_theory name f (reset_trans tr)
   400   | NONE => tr);
   401 
   402 val exit = add_trans Exit;
   403 val keep' = add_trans o Keep;
   404 
   405 fun present_transaction f g = add_trans (Transaction (f, g));
   406 fun transaction f = present_transaction f (K ());
   407 
   408 fun keep f = add_trans (Keep (fn _ => f));
   409 fun imperative f = keep (fn _ => f ());
   410 
   411 fun ignored pos = empty |> name "<ignored>" |> position pos |> imperative I;
   412 fun malformed pos msg =
   413   empty |> name "<malformed>" |> position pos |> imperative (fn () => error msg);
   414 
   415 val unknown_theory = imperative (fn () => warning "Unknown theory context");
   416 val unknown_proof = imperative (fn () => warning "Unknown proof context");
   417 val unknown_context = imperative (fn () => warning "Unknown context");
   418 
   419 
   420 (* theory transitions *)
   421 
   422 fun generic_theory f = transaction (fn _ =>
   423   (fn Theory (gthy, _) => Theory (f gthy, NONE)
   424     | _ => raise UNDEF));
   425 
   426 fun theory' f = transaction (fn int =>
   427   (fn Theory (Context.Theory thy, _) =>
   428       let val thy' = thy
   429         |> Sign.new_group
   430         |> Theory.checkpoint
   431         |> f int
   432         |> Sign.reset_group;
   433       in Theory (Context.Theory thy', NONE) end
   434     | _ => raise UNDEF));
   435 
   436 fun theory f = theory' (K f);
   437 
   438 fun begin_local_theory begin f = transaction (fn _ =>
   439   (fn Theory (Context.Theory thy, _) =>
   440         let
   441           val lthy = f thy;
   442           val gthy = if begin then Context.Proof lthy else Context.Theory (loc_exit lthy);
   443         in Theory (gthy, SOME lthy) end
   444     | _ => raise UNDEF));
   445 
   446 val end_local_theory = transaction (fn _ =>
   447   (fn Theory (Context.Proof lthy, _) => Theory (Context.Theory (loc_exit lthy), SOME lthy)
   448     | _ => raise UNDEF));
   449 
   450 local
   451 
   452 fun local_theory_presentation loc f = present_transaction (fn int =>
   453   (fn Theory (gthy, _) =>
   454         let
   455           val finish = loc_finish loc gthy;
   456           val lthy' = loc_begin loc gthy
   457             |> Local_Theory.new_group
   458             |> f int
   459             |> Local_Theory.reset_group;
   460         in Theory (finish lthy', SOME lthy') end
   461     | _ => raise UNDEF));
   462 
   463 in
   464 
   465 fun local_theory' loc f = local_theory_presentation loc f (K ());
   466 fun local_theory loc f = local_theory' loc (K f);
   467 fun present_local_theory loc = local_theory_presentation loc (K I);
   468 
   469 end;
   470 
   471 
   472 (* proof transitions *)
   473 
   474 fun end_proof f = transaction (fn int =>
   475   (fn Proof (prf, (finish, _)) =>
   476         let val state = Proof_Node.current prf in
   477           if can (Proof.assert_bottom true) state then
   478             let
   479               val ctxt' = f int state;
   480               val gthy' = finish ctxt';
   481             in Theory (gthy', SOME ctxt') end
   482           else raise UNDEF
   483         end
   484     | SkipProof (0, (gthy, _)) => Theory (gthy, NONE)
   485     | _ => raise UNDEF));
   486 
   487 local
   488 
   489 fun begin_proof init finish = transaction (fn int =>
   490   (fn Theory (gthy, _) =>
   491     let
   492       val prf = init int gthy;
   493       val skip = ! skip_proofs;
   494       val schematic = Proof.schematic_goal prf;
   495     in
   496       if skip andalso schematic then
   497         warning "Cannot skip proof of schematic goal statement"
   498       else ();
   499       if skip andalso not schematic then
   500         SkipProof (0, (finish gthy (Proof.global_skip_proof int prf), gthy))
   501       else Proof (Proof_Node.init prf, (finish gthy, gthy))
   502     end
   503   | _ => raise UNDEF));
   504 
   505 in
   506 
   507 fun local_theory_to_proof' loc f = begin_proof
   508   (fn int => fn gthy => f int (Local_Theory.new_group (loc_begin loc gthy)))
   509   (fn gthy => loc_finish loc gthy o Local_Theory.reset_group);
   510 
   511 fun local_theory_to_proof loc f = local_theory_to_proof' loc (K f);
   512 
   513 fun theory_to_proof f = begin_proof
   514   (K (fn Context.Theory thy => f (Theory.checkpoint (Sign.new_group thy)) | _ => raise UNDEF))
   515   (K (Context.Theory o Sign.reset_group o ProofContext.theory_of));
   516 
   517 end;
   518 
   519 val forget_proof = transaction (fn _ =>
   520   (fn Proof (_, (_, orig_gthy)) => Theory (orig_gthy, NONE)
   521     | SkipProof (_, (_, orig_gthy)) => Theory (orig_gthy, NONE)
   522     | _ => raise UNDEF));
   523 
   524 val present_proof = present_transaction (fn _ =>
   525   (fn Proof (prf, x) => Proof (Proof_Node.apply I prf, x)
   526     | skip as SkipProof _ => skip
   527     | _ => raise UNDEF));
   528 
   529 fun proofs' f = transaction (fn int =>
   530   (fn Proof (prf, x) => Proof (Proof_Node.applys (f int) prf, x)
   531     | skip as SkipProof _ => skip
   532     | _ => raise UNDEF));
   533 
   534 fun proof' f = proofs' (Seq.single oo f);
   535 val proofs = proofs' o K;
   536 val proof = proof' o K;
   537 
   538 fun actual_proof f = transaction (fn _ =>
   539   (fn Proof (prf, x) => Proof (f prf, x)
   540     | _ => raise UNDEF));
   541 
   542 fun skip_proof f = transaction (fn _ =>
   543   (fn SkipProof (h, x) => SkipProof (f h, x)
   544     | _ => raise UNDEF));
   545 
   546 fun skip_proof_to_theory pred = transaction (fn _ =>
   547   (fn SkipProof (d, (gthy, _)) => if pred d then Theory (gthy, NONE) else raise UNDEF
   548     | _ => raise UNDEF));
   549 
   550 
   551 
   552 (** toplevel transactions **)
   553 
   554 (* identification *)
   555 
   556 fun get_id (Transition {pos, ...}) = Position.get_id pos;
   557 fun put_id id (tr as Transition {pos, ...}) = position (Position.put_id id pos) tr;
   558 
   559 
   560 (* thread position *)
   561 
   562 fun setmp_thread_position (Transition {pos, ...}) f x =
   563   Position.setmp_thread_data pos f x;
   564 
   565 fun status tr m =
   566   setmp_thread_position tr (fn () => Output.status (Markup.markup m "")) ();
   567 
   568 fun async_state (tr as Transition {print, ...}) st =
   569   if print then
   570     ignore
   571       (Future.fork (fn () =>
   572           setmp_thread_position tr (fn () => Future.status (fn () => print_state false st)) ()))
   573   else ();
   574 
   575 fun error_msg tr exn_info =
   576   setmp_thread_position tr (fn () =>
   577     Output.error_msg (ML_Compiler.exn_message (EXCURSION_FAIL exn_info))) ();
   578 
   579 
   580 (* post-transition hooks *)
   581 
   582 local
   583   val hooks = Unsynchronized.ref ([]: (transition -> state -> state -> unit) list);
   584 in
   585 
   586 fun add_hook f = CRITICAL (fn () => Unsynchronized.change hooks (cons f));
   587 fun get_hooks () = ! hooks;
   588 
   589 end;
   590 
   591 
   592 (* apply transitions *)
   593 
   594 local
   595 
   596 fun app int (tr as Transition {trans, print, no_timing, ...}) =
   597   setmp_thread_position tr (fn state =>
   598     let
   599       fun do_timing f x = (warning (command_msg "" tr); timeap f x);
   600       fun do_profiling f x = profile (! profiling) f x;
   601 
   602       val (result, status) =
   603          state |>
   604           (apply_trans int trans
   605             |> (! profiling > 0 andalso not no_timing) ? do_profiling
   606             |> (! profiling > 0 orelse ! timing andalso not no_timing) ? do_timing);
   607 
   608       val _ = if int andalso not (! quiet) andalso print then print_state false result else ();
   609     in (result, Option.map (fn UNDEF => type_error tr state | exn => exn) status) end);
   610 
   611 in
   612 
   613 fun transition int tr st =
   614   let
   615     val hooks = get_hooks ();
   616     fun apply_hooks st' = hooks |> List.app (fn f => (try (fn () => f tr st st') (); ()));
   617 
   618     val ctxt = try context_of st;
   619     val res =
   620       (case app int tr st of
   621         (_, SOME TERMINATE) => NONE
   622       | (st', SOME (EXCURSION_FAIL exn_info)) => SOME (st', SOME exn_info)
   623       | (st', SOME exn) => SOME (st', SOME (Runtime.exn_context ctxt exn, at_command tr))
   624       | (st', NONE) => SOME (st', NONE));
   625     val _ = (case res of SOME (st', NONE) => apply_hooks st' | _ => ());
   626   in res end;
   627 
   628 end;
   629 
   630 
   631 (* managed execution *)
   632 
   633 fun run_command thy_name tr st =
   634   (case
   635       (case init_of tr of
   636         SOME name => Exn.capture (fn () => Thy_Header.consistent_name thy_name name) ()
   637       | NONE => Exn.Result ()) of
   638     Exn.Result () =>
   639       let val int = is_some (init_of tr) in
   640         (case transition int tr st of
   641           SOME (st', NONE) =>
   642             (status tr Markup.finished; if int then () else async_state tr st'; SOME st')
   643         | SOME (_, SOME (exn as Exn.Interrupt, _)) => reraise exn
   644         | SOME (_, SOME exn_info) => (error_msg tr exn_info; status tr Markup.failed; NONE)
   645         | NONE => (error_msg tr (TERMINATE, at_command tr); status tr Markup.failed; NONE))
   646       end
   647   | Exn.Exn exn => (error_msg tr (exn, at_command tr); status tr Markup.failed; NONE));
   648 
   649 
   650 (* nested commands *)
   651 
   652 fun command tr st =
   653   (case transition (! interact) tr st of
   654     SOME (st', NONE) => st'
   655   | SOME (_, SOME exn_info) => raise EXCURSION_FAIL exn_info
   656   | NONE => raise EXCURSION_FAIL (TERMINATE, at_command tr));
   657 
   658 fun command_result tr st =
   659   let val st' = command tr st
   660   in (st', st') end;
   661 
   662 
   663 (* excursion of units, consisting of commands with proof *)
   664 
   665 structure States = Proof_Data
   666 (
   667   type T = state list future option;
   668   fun init _ = NONE;
   669 );
   670 
   671 fun proof_result immediate (tr, proof_trs) st =
   672   let val st' = command tr st in
   673     if immediate orelse
   674       null proof_trs orelse
   675       Keyword.is_schematic_goal (name_of tr) orelse
   676       exists (Keyword.is_qed_global o name_of) proof_trs orelse
   677       not (can proof_of st') orelse
   678       Proof.is_relevant (proof_of st')
   679     then
   680       let val (states, st'') = fold_map command_result proof_trs st'
   681       in (Lazy.value ((tr, st') :: (proof_trs ~~ states)), st'') end
   682     else
   683       let
   684         val (body_trs, end_tr) = split_last proof_trs;
   685         val finish = Context.Theory o ProofContext.theory_of;
   686 
   687         val future_proof = Proof.global_future_proof
   688           (fn prf =>
   689             Future.fork_pri ~1 (fn () =>
   690               let val (states, result_state) =
   691                 (case st' of State (SOME (Proof (_, (_, orig_gthy))), prev)
   692                   => State (SOME (Proof (Proof_Node.init prf, (finish, orig_gthy))), prev))
   693                 |> fold_map command_result body_trs
   694                 ||> command (end_tr |> set_print false);
   695               in (states, presentation_context_of result_state) end))
   696           #> (fn (states, ctxt) => States.put (SOME states) ctxt);
   697 
   698         val st'' = st' |> command (end_tr |> reset_trans |> end_proof (K future_proof));
   699 
   700         val states =
   701           (case States.get (presentation_context_of st'') of
   702             NONE => raise Fail ("No future states for " ^ name_of tr ^ Position.str_of (pos_of tr))
   703           | SOME states => states);
   704         val result = Lazy.lazy
   705           (fn () => (tr, st') :: (body_trs ~~ Future.join states) @ [(end_tr, st'')]);
   706 
   707       in (result, st'') end
   708   end;
   709 
   710 fun excursion input =
   711   let
   712     val end_pos = if null input then error "No input" else pos_of (fst (List.last input));
   713     val immediate = not (Goal.future_enabled ());
   714     val (results, end_state) = fold_map (proof_result immediate) input toplevel;
   715     val thy = end_theory end_pos end_state;
   716   in (Lazy.lazy (fn () => maps Lazy.force results), thy) end;
   717 
   718 end;