src/Pure/Isar/toplevel.ML
author wenzelm
Tue Dec 23 20:46:42 2014 +0100 (2014-12-23 ago)
changeset 59184 830bb7ddb3ab
parent 59150 71b416020f42
child 59472 513300fa2d09
permissions -rw-r--r--
explicit message channels for "state", "information";
separate state_message_color;
     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 is_skipped_proof: state -> bool
    16   val level: state -> int
    17   val presentation_context_of: state -> Proof.context
    18   val previous_context_of: state -> Proof.context option
    19   val context_of: state -> Proof.context
    20   val generic_theory_of: state -> generic_theory
    21   val theory_of: state -> theory
    22   val proof_of: state -> Proof.state
    23   val proof_position_of: state -> int
    24   val end_theory: Position.T -> state -> theory
    25   val pretty_context: state -> Pretty.T list
    26   val pretty_state: state -> Pretty.T list
    27   val print_state: state -> unit
    28   val pretty_abstract: state -> Pretty.T
    29   val profiling: int Unsynchronized.ref
    30   type transition
    31   val empty: transition
    32   val name_of: transition -> string
    33   val pos_of: transition -> Position.T
    34   val type_error: transition -> state -> string
    35   val name: string -> transition -> transition
    36   val position: Position.T -> transition -> transition
    37   val init_theory: (unit -> theory) -> transition -> transition
    38   val is_init: transition -> bool
    39   val modify_init: (unit -> theory) -> transition -> transition
    40   val exit: transition -> transition
    41   val keep: (state -> unit) -> transition -> transition
    42   val keep': (bool -> state -> unit) -> transition -> transition
    43   val imperative: (unit -> unit) -> transition -> transition
    44   val ignored: Position.T -> transition
    45   val is_ignored: transition -> bool
    46   val malformed: Position.T -> string -> transition
    47   val is_malformed: transition -> bool
    48   val generic_theory: (generic_theory -> generic_theory) -> transition -> transition
    49   val theory': (bool -> theory -> theory) -> transition -> transition
    50   val theory: (theory -> theory) -> transition -> transition
    51   val begin_local_theory: bool -> (theory -> local_theory) -> transition -> transition
    52   val end_local_theory: transition -> transition
    53   val open_target: (generic_theory -> local_theory) -> transition -> transition
    54   val close_target: transition -> transition
    55   val local_theory': (xstring * Position.T) option -> (bool -> local_theory -> local_theory) ->
    56     transition -> transition
    57   val local_theory: (xstring * Position.T) option -> (local_theory -> local_theory) ->
    58     transition -> transition
    59   val present_local_theory: (xstring * Position.T) option -> (state -> unit) ->
    60     transition -> transition
    61   val local_theory_to_proof': (xstring * Position.T) option ->
    62     (bool -> local_theory -> Proof.state) -> transition -> transition
    63   val local_theory_to_proof: (xstring * Position.T) option ->
    64     (local_theory -> Proof.state) -> transition -> transition
    65   val theory_to_proof: (theory -> Proof.state) -> transition -> transition
    66   val end_proof: (bool -> Proof.state -> Proof.context) -> transition -> transition
    67   val forget_proof: bool -> transition -> transition
    68   val proofs': (bool -> Proof.state -> Proof.state Seq.result Seq.seq) -> transition -> transition
    69   val proof': (bool -> Proof.state -> Proof.state) -> transition -> transition
    70   val proofs: (Proof.state -> Proof.state Seq.result Seq.seq) -> transition -> transition
    71   val proof: (Proof.state -> Proof.state) -> transition -> transition
    72   val actual_proof: (Proof_Node.T -> Proof_Node.T) -> transition -> transition
    73   val skip_proof: (int -> int) -> transition -> transition
    74   val skip_proof_to_theory: (int -> bool) -> transition -> transition
    75   val exec_id: Document_ID.exec -> transition -> transition
    76   val unknown_theory: transition -> transition
    77   val unknown_proof: transition -> transition
    78   val unknown_context: transition -> transition
    79   val setmp_thread_position: transition -> ('a -> 'b) -> 'a -> 'b
    80   val add_hook: (transition -> state -> state -> unit) -> unit
    81   val get_timing: transition -> Time.time option
    82   val put_timing: Time.time option -> transition -> transition
    83   val transition: bool -> transition -> state -> state * (exn * string) option
    84   val command_errors: bool -> transition -> state -> Runtime.error list * state option
    85   val command_exception: bool -> transition -> state -> state
    86   val reset_theory: state -> state option
    87   val reset_proof: state -> state option
    88   type result
    89   val join_results: result -> (transition * state) list
    90   val element_result: Keyword.keywords -> transition Thy_Syntax.element -> state -> result * state
    91 end;
    92 
    93 structure Toplevel: TOPLEVEL =
    94 struct
    95 
    96 (** toplevel state **)
    97 
    98 exception UNDEF = Runtime.UNDEF;
    99 
   100 
   101 (* datatype node *)
   102 
   103 datatype node =
   104   Theory of generic_theory * Proof.context option
   105     (*theory with presentation context*) |
   106   Proof of Proof_Node.T * ((Proof.context -> generic_theory) * generic_theory)
   107     (*proof node, finish, original theory*) |
   108   Skipped_Proof of int * (generic_theory * generic_theory);
   109     (*proof depth, resulting theory, original theory*)
   110 
   111 val theory_node = fn Theory (gthy, _) => SOME gthy | _ => NONE;
   112 val proof_node = fn Proof (prf, _) => SOME prf | _ => NONE;
   113 val skipped_proof_node = fn Skipped_Proof _ => true | _ => false;
   114 
   115 fun cases_node f _ (Theory (gthy, _)) = f gthy
   116   | cases_node _ g (Proof (prf, _)) = g (Proof_Node.current prf)
   117   | cases_node f _ (Skipped_Proof (_, (gthy, _))) = f gthy;
   118 
   119 val context_node = cases_node Context.proof_of Proof.context_of;
   120 
   121 
   122 (* datatype state *)
   123 
   124 datatype state = State of node option * node option;  (*current, previous*)
   125 
   126 val toplevel = State (NONE, NONE);
   127 
   128 fun is_toplevel (State (NONE, _)) = true
   129   | is_toplevel _ = false;
   130 
   131 fun level (State (NONE, _)) = 0
   132   | level (State (SOME (Theory _), _)) = 0
   133   | level (State (SOME (Proof (prf, _)), _)) = Proof.level (Proof_Node.current prf)
   134   | level (State (SOME (Skipped_Proof (d, _)), _)) = d + 1;   (*different notion of proof depth!*)
   135 
   136 fun str_of_state (State (NONE, SOME (Theory (Context.Theory thy, _)))) =
   137       "at top level, result theory " ^ quote (Context.theory_name thy)
   138   | str_of_state (State (NONE, _)) = "at top level"
   139   | str_of_state (State (SOME (Theory (Context.Theory _, _)), _)) = "in theory mode"
   140   | str_of_state (State (SOME (Theory (Context.Proof _, _)), _)) = "in local theory mode"
   141   | str_of_state (State (SOME (Proof _), _)) = "in proof mode"
   142   | str_of_state (State (SOME (Skipped_Proof _), _)) = "in skipped proof mode";
   143 
   144 
   145 (* current node *)
   146 
   147 fun node_of (State (NONE, _)) = raise UNDEF
   148   | node_of (State (SOME node, _)) = node;
   149 
   150 fun is_theory state = not (is_toplevel state) andalso is_some (theory_node (node_of state));
   151 fun is_proof state = not (is_toplevel state) andalso is_some (proof_node (node_of state));
   152 fun is_skipped_proof state = not (is_toplevel state) andalso skipped_proof_node (node_of state);
   153 
   154 fun node_case f g state = cases_node f g (node_of state);
   155 
   156 fun presentation_context_of state =
   157   (case try node_of state of
   158     SOME (Theory (_, SOME ctxt)) => ctxt
   159   | SOME node => context_node node
   160   | NONE => raise UNDEF);
   161 
   162 fun previous_context_of (State (_, NONE)) = NONE
   163   | previous_context_of (State (_, SOME prev)) = SOME (context_node prev);
   164 
   165 val context_of = node_case Context.proof_of Proof.context_of;
   166 val generic_theory_of = node_case I (Context.Proof o Proof.context_of);
   167 val theory_of = node_case Context.theory_of Proof.theory_of;
   168 val proof_of = node_case (fn _ => raise UNDEF) I;
   169 
   170 fun proof_position_of state =
   171   (case node_of state of
   172     Proof (prf, _) => Proof_Node.position prf
   173   | _ => raise UNDEF);
   174 
   175 fun end_theory _ (State (NONE, SOME (Theory (Context.Theory thy, _)))) = thy
   176   | end_theory pos (State (NONE, _)) = error ("Bad theory" ^ Position.here pos)
   177   | end_theory pos (State (SOME _, _)) = error ("Unfinished theory" ^ Position.here pos);
   178 
   179 
   180 (* print state *)
   181 
   182 fun pretty_context state =
   183   (case try node_of state of
   184     NONE => []
   185   | SOME node =>
   186       let
   187         val gthy =
   188           (case node of
   189             Theory (gthy, _) => gthy
   190           | Proof (_, (_, gthy)) => gthy
   191           | Skipped_Proof (_, (gthy, _)) => gthy);
   192         val lthy = Context.cases (Named_Target.theory_init) I gthy;
   193       in Local_Theory.pretty lthy end);
   194 
   195 fun pretty_state state =
   196   (case try node_of state of
   197     NONE => []
   198   | SOME (Theory _) => []
   199   | SOME (Proof (prf, _)) =>
   200       Proof.pretty_state (Proof_Node.position prf) (Proof_Node.current prf)
   201   | SOME (Skipped_Proof (d, _)) => [Pretty.str ("skipped proof: depth " ^ string_of_int d)]);
   202 
   203 val print_state = pretty_state #> Pretty.chunks #> Pretty.string_of #> Output.state;
   204 
   205 fun pretty_abstract state = Pretty.str ("<Isar " ^ str_of_state state ^ ">");
   206 
   207 
   208 
   209 (** toplevel transitions **)
   210 
   211 val profiling = Unsynchronized.ref 0;
   212 
   213 
   214 (* node transactions -- maintaining stable checkpoints *)
   215 
   216 exception FAILURE of state * exn;
   217 
   218 local
   219 
   220 fun reset_presentation (Theory (gthy, _)) = Theory (gthy, NONE)
   221   | reset_presentation node = node;
   222 
   223 fun map_theory f (Theory (gthy, ctxt)) =
   224       Theory (Context.mapping f (Local_Theory.raw_theory f) gthy, ctxt)
   225   | map_theory _ node = node;
   226 
   227 in
   228 
   229 fun apply_transaction f g node =
   230   let
   231     val cont_node = reset_presentation node;
   232     val context = cases_node I (Context.Proof o Proof.context_of) cont_node;
   233     fun state_error e nd = (State (SOME nd, SOME node), e);
   234 
   235     val (result, err) =
   236       cont_node
   237       |> Runtime.controlled_execution (SOME context) f
   238       |> state_error NONE
   239       handle exn => state_error (SOME exn) cont_node;
   240   in
   241     (case err of
   242       NONE => tap g result
   243     | SOME exn => raise FAILURE (result, exn))
   244   end;
   245 
   246 val exit_transaction =
   247   apply_transaction
   248     (fn Theory (Context.Theory thy, _) => Theory (Context.Theory (Theory.end_theory thy), NONE)
   249       | node => node) (K ())
   250   #> (fn State (node', _) => State (NONE, node'));
   251 
   252 end;
   253 
   254 
   255 (* primitive transitions *)
   256 
   257 datatype trans =
   258   Init of unit -> theory |               (*init theory*)
   259   Exit |                                 (*formal exit of theory*)
   260   Keep of bool -> state -> unit |        (*peek at state*)
   261   Transaction of (bool -> node -> node) * (state -> unit);  (*node transaction and presentation*)
   262 
   263 local
   264 
   265 fun apply_tr _ (Init f) (State (NONE, _)) =
   266       State (SOME (Theory (Context.Theory (Runtime.controlled_execution NONE f ()), NONE)), NONE)
   267   | apply_tr _ Exit (State (SOME (state as Theory (Context.Theory _, _)), _)) =
   268       exit_transaction state
   269   | apply_tr int (Keep f) state =
   270       Runtime.controlled_execution (try generic_theory_of state) (fn x => tap (f int) x) state
   271   | apply_tr int (Transaction (f, g)) (State (SOME state, _)) =
   272       apply_transaction (fn x => f int x) g state
   273   | apply_tr _ _ _ = raise UNDEF;
   274 
   275 fun apply_union _ [] state = raise FAILURE (state, UNDEF)
   276   | apply_union int (tr :: trs) state =
   277       apply_union int trs state
   278         handle Runtime.UNDEF => apply_tr int tr state
   279           | FAILURE (alt_state, UNDEF) => apply_tr int tr alt_state
   280           | exn as FAILURE _ => raise exn
   281           | exn => raise FAILURE (state, exn);
   282 
   283 in
   284 
   285 fun apply_trans int trs state = (apply_union int trs state, NONE)
   286   handle FAILURE (alt_state, exn) => (alt_state, SOME exn) | exn => (state, SOME exn);
   287 
   288 end;
   289 
   290 
   291 (* datatype transition *)
   292 
   293 datatype transition = Transition of
   294  {name: string,              (*command name*)
   295   pos: Position.T,           (*source position*)
   296   timing: Time.time option,  (*prescient timing information*)
   297   trans: trans list};        (*primitive transitions (union)*)
   298 
   299 fun make_transition (name, pos, timing, trans) =
   300   Transition {name = name, pos = pos, timing = timing, trans = trans};
   301 
   302 fun map_transition f (Transition {name, pos, timing, trans}) =
   303   make_transition (f (name, pos, timing, trans));
   304 
   305 val empty = make_transition ("", Position.none, NONE, []);
   306 
   307 
   308 (* diagnostics *)
   309 
   310 fun name_of (Transition {name, ...}) = name;
   311 fun pos_of (Transition {pos, ...}) = pos;
   312 
   313 fun command_msg msg tr = msg ^ "command " ^ quote (name_of tr) ^ Position.here (pos_of tr);
   314 fun at_command tr = command_msg "At " tr;
   315 
   316 fun type_error tr state =
   317   command_msg "Illegal application of " tr ^ " " ^ str_of_state state;
   318 
   319 
   320 (* modify transitions *)
   321 
   322 fun name name = map_transition (fn (_, pos, timing, trans) =>
   323   (name, pos, timing, trans));
   324 
   325 fun position pos = map_transition (fn (name, _, timing, trans) =>
   326   (name, pos, timing, trans));
   327 
   328 fun add_trans tr = map_transition (fn (name, pos, timing, trans) =>
   329   (name, pos, timing, tr :: trans));
   330 
   331 val reset_trans = map_transition (fn (name, pos, timing, _) =>
   332   (name, pos, timing, []));
   333 
   334 
   335 (* basic transitions *)
   336 
   337 fun init_theory f = add_trans (Init f);
   338 
   339 fun is_init (Transition {trans = [Init _], ...}) = true
   340   | is_init _ = false;
   341 
   342 fun modify_init f tr = if is_init tr then init_theory f (reset_trans tr) else tr;
   343 
   344 val exit = add_trans Exit;
   345 val keep' = add_trans o Keep;
   346 
   347 fun present_transaction f g = add_trans (Transaction (f, g));
   348 fun transaction f = present_transaction f (K ());
   349 
   350 fun keep f = add_trans (Keep (fn _ => f));
   351 fun imperative f = keep (fn _ => f ());
   352 
   353 fun ignored pos = empty |> name "<ignored>" |> position pos |> imperative I;
   354 fun is_ignored tr = name_of tr = "<ignored>";
   355 
   356 val malformed_name = "<malformed>";
   357 fun malformed pos msg =
   358   empty |> name malformed_name |> position pos |> imperative (fn () => error msg);
   359 fun is_malformed tr = name_of tr = malformed_name;
   360 
   361 val unknown_theory = imperative (fn () => warning "Unknown theory context");
   362 val unknown_proof = imperative (fn () => warning "Unknown proof context");
   363 val unknown_context = imperative (fn () => warning "Unknown context");
   364 
   365 
   366 (* theory transitions *)
   367 
   368 fun generic_theory f = transaction (fn _ =>
   369   (fn Theory (gthy, _) => Theory (f gthy, NONE)
   370     | _ => raise UNDEF));
   371 
   372 fun theory' f = transaction (fn int =>
   373   (fn Theory (Context.Theory thy, _) =>
   374       let val thy' = thy
   375         |> Sign.new_group
   376         |> f int
   377         |> Sign.reset_group;
   378       in Theory (Context.Theory thy', NONE) end
   379     | _ => raise UNDEF));
   380 
   381 fun theory f = theory' (K f);
   382 
   383 fun begin_local_theory begin f = transaction (fn _ =>
   384   (fn Theory (Context.Theory thy, _) =>
   385         let
   386           val lthy = f thy;
   387           val gthy = if begin then Context.Proof lthy else Context.Theory (Named_Target.exit lthy);
   388           val _ =
   389             if begin then
   390               Output.state (Pretty.string_of (Pretty.chunks (Local_Theory.pretty lthy)))
   391             else ();
   392         in Theory (gthy, SOME lthy) end
   393     | _ => raise UNDEF));
   394 
   395 val end_local_theory = transaction (fn _ =>
   396   (fn Theory (Context.Proof lthy, _) => Theory (Context.Theory (Named_Target.exit lthy), SOME lthy)
   397     | _ => raise UNDEF));
   398 
   399 fun open_target f = transaction (fn _ =>
   400   (fn Theory (gthy, _) =>
   401         let val lthy = f gthy
   402         in Theory (Context.Proof lthy, SOME lthy) end
   403     | _ => raise UNDEF));
   404 
   405 val close_target = transaction (fn _ =>
   406   (fn Theory (Context.Proof lthy, _) =>
   407         (case try Local_Theory.close_target lthy of
   408           SOME ctxt' =>
   409             let
   410               val gthy' =
   411                 if can Local_Theory.assert ctxt'
   412                 then Context.Proof ctxt'
   413                 else Context.Theory (Proof_Context.theory_of ctxt');
   414             in Theory (gthy', SOME lthy) end
   415         | NONE => raise UNDEF)
   416     | _ => raise UNDEF));
   417 
   418 fun local_theory' loc f = present_transaction (fn int =>
   419   (fn Theory (gthy, _) =>
   420         let
   421           val (finish, lthy) = Named_Target.switch loc gthy;
   422           val lthy' = lthy
   423             |> Local_Theory.new_group
   424             |> f int
   425             |> Local_Theory.reset_group;
   426         in Theory (finish lthy', SOME lthy') end
   427     | _ => raise UNDEF))
   428   (K ());
   429 
   430 fun local_theory loc f = local_theory' loc (K f);
   431 
   432 fun present_local_theory loc = present_transaction (fn int =>
   433   (fn Theory (gthy, _) =>
   434         let val (finish, lthy) = Named_Target.switch loc gthy;
   435         in Theory (finish lthy, SOME lthy) end
   436     | _ => raise UNDEF));
   437 
   438 
   439 (* proof transitions *)
   440 
   441 fun end_proof f = transaction (fn int =>
   442   (fn Proof (prf, (finish, _)) =>
   443         let val state = Proof_Node.current prf in
   444           if can (Proof.assert_bottom true) state then
   445             let
   446               val ctxt' = f int state;
   447               val gthy' = finish ctxt';
   448             in Theory (gthy', SOME ctxt') end
   449           else raise UNDEF
   450         end
   451     | Skipped_Proof (0, (gthy, _)) => Theory (gthy, NONE)
   452     | _ => raise UNDEF));
   453 
   454 local
   455 
   456 fun begin_proof init = transaction (fn int =>
   457   (fn Theory (gthy, _) =>
   458     let
   459       val (finish, prf) = init int gthy;
   460       val skip = Goal.skip_proofs_enabled ();
   461       val schematic_goal = try Proof.schematic_goal prf;
   462       val _ =
   463         if skip andalso schematic_goal = SOME true then
   464           warning "Cannot skip proof of schematic goal statement"
   465         else ();
   466     in
   467       if skip andalso schematic_goal = SOME false then
   468         Skipped_Proof (0, (finish (Proof.global_skip_proof true prf), gthy))
   469       else Proof (Proof_Node.init prf, (finish, gthy))
   470     end
   471   | _ => raise UNDEF));
   472 
   473 in
   474 
   475 fun local_theory_to_proof' loc f = begin_proof
   476   (fn int => fn gthy =>
   477     let val (finish, lthy) = Named_Target.switch loc gthy
   478     in (finish o Local_Theory.reset_group, f int (Local_Theory.new_group lthy)) end);
   479 
   480 fun local_theory_to_proof loc f = local_theory_to_proof' loc (K f);
   481 
   482 fun theory_to_proof f = begin_proof
   483   (fn _ => fn gthy =>
   484     (Context.Theory o Sign.reset_group o Sign.change_check o Proof_Context.theory_of,
   485       (case gthy of
   486         Context.Theory thy => f (Sign.new_group thy)
   487       | _ => raise UNDEF)));
   488 
   489 end;
   490 
   491 fun forget_proof strict = transaction (fn _ =>
   492   (fn Proof (prf, (_, orig_gthy)) =>
   493         if strict andalso not (Proof.has_bottom_goal (Proof_Node.current prf))
   494         then raise UNDEF else Theory (orig_gthy, NONE)
   495     | Skipped_Proof (_, (_, orig_gthy)) => Theory (orig_gthy, NONE)
   496     | _ => raise UNDEF));
   497 
   498 fun proofs' f = transaction (fn int =>
   499   (fn Proof (prf, x) => Proof (Proof_Node.applys (f int) prf, x)
   500     | skip as Skipped_Proof _ => skip
   501     | _ => raise UNDEF));
   502 
   503 fun proof' f = proofs' ((Seq.single o Seq.Result) oo f);
   504 val proofs = proofs' o K;
   505 val proof = proof' o K;
   506 
   507 fun actual_proof f = transaction (fn _ =>
   508   (fn Proof (prf, x) => Proof (f prf, x)
   509     | _ => raise UNDEF));
   510 
   511 fun skip_proof f = transaction (fn _ =>
   512   (fn Skipped_Proof (h, x) => Skipped_Proof (f h, x)
   513     | _ => raise UNDEF));
   514 
   515 fun skip_proof_to_theory pred = transaction (fn _ =>
   516   (fn Skipped_Proof (d, (gthy, _)) => if pred d then Theory (gthy, NONE) else raise UNDEF
   517     | _ => raise UNDEF));
   518 
   519 
   520 
   521 (** toplevel transactions **)
   522 
   523 (* runtime position *)
   524 
   525 fun exec_id id (tr as Transition {pos, ...}) =
   526   position (Position.put_id (Document_ID.print id) pos) tr;
   527 
   528 fun setmp_thread_position (Transition {pos, ...}) f x =
   529   Position.setmp_thread_data pos f x;
   530 
   531 
   532 (* post-transition hooks *)
   533 
   534 local
   535   val hooks =
   536     Synchronized.var "Toplevel.hooks" ([]: (transition -> state -> state -> unit) list);
   537 in
   538 
   539 fun add_hook hook = Synchronized.change hooks (cons hook);
   540 fun get_hooks () = Synchronized.value hooks;
   541 
   542 end;
   543 
   544 
   545 (* apply transitions *)
   546 
   547 fun get_timing (Transition {timing, ...}) = timing;
   548 fun put_timing timing = map_transition (fn (name, pos, _, trans) => (name, pos, timing, trans));
   549 
   550 local
   551 
   552 fun app int (tr as Transition {name, trans, ...}) =
   553   setmp_thread_position tr (fn state =>
   554     let
   555       val timing_start = Timing.start ();
   556 
   557       val (result, opt_err) =
   558          state |> (apply_trans int trans |> ! profiling > 0 ? profile (! profiling));
   559 
   560       val timing_result = Timing.result timing_start;
   561       val timing_props =
   562         Markup.command_timing :: (Markup.nameN, name_of tr) :: Position.properties_of (pos_of tr);
   563       val _ = Timing.protocol_message timing_props timing_result;
   564     in
   565       (result, Option.map (fn UNDEF => ERROR (type_error tr state) | exn => exn) opt_err)
   566     end);
   567 
   568 in
   569 
   570 fun transition int tr st =
   571   let
   572     val (st', opt_err) = app int tr st;
   573     val opt_err' = opt_err |> Option.map
   574       (fn Runtime.EXCURSION_FAIL exn_info => exn_info
   575         | exn => (Runtime.exn_context (try context_of st) exn, at_command tr));
   576     val _ = get_hooks () |> List.app (fn f => (try (fn () => f tr st st') (); ()));
   577   in (st', opt_err') end;
   578 
   579 end;
   580 
   581 
   582 (* managed commands *)
   583 
   584 fun command_errors int tr st =
   585   (case transition int tr st of
   586     (st', NONE) => ([], SOME st')
   587   | (_, SOME (exn, _)) => (Runtime.exn_messages_ids exn, NONE));
   588 
   589 fun command_exception int tr st =
   590   (case transition int tr st of
   591     (st', NONE) => st'
   592   | (_, SOME (exn, info)) =>
   593       if Exn.is_interrupt exn then reraise exn
   594       else raise Runtime.EXCURSION_FAIL (exn, info));
   595 
   596 val command = command_exception false;
   597 
   598 
   599 (* reset state *)
   600 
   601 local
   602 
   603 fun reset_state check trans st =
   604   if check st then NONE
   605   else #2 (command_errors false (trans empty) st);
   606 
   607 in
   608 
   609 val reset_theory = reset_state is_theory (forget_proof false);
   610 
   611 val reset_proof =
   612   reset_state is_proof
   613     (transaction (fn _ =>
   614       (fn Theory (gthy, _) => Skipped_Proof (0, (gthy, gthy))
   615         | _ => raise UNDEF)));
   616 
   617 end;
   618 
   619 
   620 (* scheduled proof result *)
   621 
   622 datatype result =
   623   Result of transition * state |
   624   Result_List of result list |
   625   Result_Future of result future;
   626 
   627 fun join_results (Result x) = [x]
   628   | join_results (Result_List xs) = maps join_results xs
   629   | join_results (Result_Future x) = join_results (Future.join x);
   630 
   631 local
   632 
   633 structure Result = Proof_Data
   634 (
   635   type T = result;
   636   fun init _ = Result_List [];
   637 );
   638 
   639 val get_result = Result.get o Proof.context_of;
   640 val put_result = Proof.map_context o Result.put;
   641 
   642 fun timing_estimate include_head elem =
   643   let
   644     val trs = Thy_Syntax.flat_element elem |> not include_head ? tl;
   645     val timings = map get_timing trs;
   646   in
   647     if forall is_some timings then
   648       SOME (fold (curry Time.+ o the) timings Time.zeroTime)
   649     else NONE
   650   end;
   651 
   652 fun priority NONE = ~1
   653   | priority (SOME estimate) =
   654       Int.min (Real.floor (Real.max (Math.log10 (Time.toReal estimate), ~3.0)) - 3, ~1);
   655 
   656 fun proof_future_enabled estimate st =
   657   (case try proof_of st of
   658     NONE => false
   659   | SOME state =>
   660       not (Proof.is_relevant state) andalso
   661        (if can (Proof.assert_bottom true) state
   662         then Goal.future_enabled 1
   663         else
   664           (case estimate of
   665             NONE => Goal.future_enabled 2
   666           | SOME t => Goal.future_enabled_timing t)));
   667 
   668 fun atom_result keywords tr st =
   669   let
   670     val st' =
   671       if Goal.future_enabled 1 andalso Keyword.is_diag keywords (name_of tr) then
   672         (Execution.fork
   673           {name = "Toplevel.diag", pos = pos_of tr,
   674             pri = priority (timing_estimate true (Thy_Syntax.atom tr))}
   675           (fn () => command tr st); st)
   676       else command tr st;
   677   in (Result (tr, st'), st') end;
   678 
   679 in
   680 
   681 fun element_result keywords (Thy_Syntax.Element (tr, NONE)) st = atom_result keywords tr st
   682   | element_result keywords (elem as Thy_Syntax.Element (head_tr, SOME element_rest)) st =
   683       let
   684         val (head_result, st') = atom_result keywords head_tr st;
   685         val (body_elems, end_tr) = element_rest;
   686         val estimate = timing_estimate false elem;
   687       in
   688         if not (proof_future_enabled estimate st')
   689         then
   690           let
   691             val proof_trs = maps Thy_Syntax.flat_element body_elems @ [end_tr];
   692             val (proof_results, st'') = fold_map (atom_result keywords) proof_trs st';
   693           in (Result_List (head_result :: proof_results), st'') end
   694         else
   695           let
   696             val finish = Context.Theory o Proof_Context.theory_of;
   697 
   698             val future_proof =
   699               Proof.future_proof (fn state =>
   700                 Execution.fork
   701                   {name = "Toplevel.future_proof", pos = pos_of head_tr, pri = priority estimate}
   702                   (fn () =>
   703                     let
   704                       val State (SOME (Proof (prf, (_, orig_gthy))), prev) = st';
   705                       val prf' = Proof_Node.apply (K state) prf;
   706                       val (result, result_state) =
   707                         State (SOME (Proof (prf', (finish, orig_gthy))), prev)
   708                         |> fold_map (element_result keywords) body_elems ||> command end_tr;
   709                     in (Result_List result, presentation_context_of result_state) end))
   710               #> (fn (res, state') => state' |> put_result (Result_Future res));
   711 
   712             val forked_proof =
   713               proof (future_proof #>
   714                 (fn state => state |> Proof.local_done_proof |> put_result (get_result state))) o
   715               end_proof (fn _ => future_proof #>
   716                 (fn state => state |> Proof.global_done_proof |> Result.put (get_result state)));
   717 
   718             val st'' = st'
   719               |> command (head_tr |> reset_trans |> forked_proof);
   720             val end_result = Result (end_tr, st'');
   721             val result =
   722               Result_List [head_result, Result.get (presentation_context_of st''), end_result];
   723           in (result, st'') end
   724       end;
   725 
   726 end;
   727 
   728 end;