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