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