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