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