src/Pure/Isar/toplevel.ML
author wenzelm
Thu Nov 13 23:45:15 2014 +0100 (2014-11-13 ago)
changeset 59000 ed09ae4ea2d8
parent 58923 cb9b69cca999
child 59032 f36496364ce1
permissions -rw-r--r--
uniform treatment of all document markup commands: 'text' and 'txt' merely differ in LaTeX style;
discontinued obsolete 'txt_raw' (superseded by 'text_raw');
eliminated obsolete Outer_Syntax.markup (superseded by keyword kinds);
'text' and 'txt' no longer appear in Sidekick tree due to change of keyword kind;
changed tagging of diagnostic commands within proof;
     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) 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.markup_chunks Markup.state #> Pretty.writeln;
   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               Pretty.writeln (Pretty.mark Markup.state (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 
   419 local
   420 
   421 fun local_theory_presentation loc f = present_transaction (fn int =>
   422   (fn Theory (gthy, _) =>
   423         let
   424           val (finish, lthy) = Named_Target.switch loc gthy;
   425           val lthy' = lthy
   426             |> Local_Theory.new_group
   427             |> f int
   428             |> Local_Theory.reset_group;
   429         in Theory (finish lthy', SOME lthy') end
   430     | _ => raise UNDEF));
   431 
   432 in
   433 
   434 fun local_theory' loc f = local_theory_presentation loc f (K ());
   435 fun local_theory loc f = local_theory' loc (K f);
   436 fun present_local_theory loc = local_theory_presentation loc (K I);
   437 
   438 end;
   439 
   440 
   441 (* proof transitions *)
   442 
   443 fun end_proof f = transaction (fn int =>
   444   (fn Proof (prf, (finish, _)) =>
   445         let val state = Proof_Node.current prf in
   446           if can (Proof.assert_bottom true) state then
   447             let
   448               val ctxt' = f int state;
   449               val gthy' = finish ctxt';
   450             in Theory (gthy', SOME ctxt') end
   451           else raise UNDEF
   452         end
   453     | Skipped_Proof (0, (gthy, _)) => Theory (gthy, NONE)
   454     | _ => raise UNDEF));
   455 
   456 local
   457 
   458 fun begin_proof init = transaction (fn int =>
   459   (fn Theory (gthy, _) =>
   460     let
   461       val (finish, prf) = init int gthy;
   462       val skip = Goal.skip_proofs_enabled ();
   463       val schematic_goal = try Proof.schematic_goal prf;
   464       val _ =
   465         if skip andalso schematic_goal = SOME true then
   466           warning "Cannot skip proof of schematic goal statement"
   467         else ();
   468     in
   469       if skip andalso schematic_goal = SOME false then
   470         Skipped_Proof (0, (finish (Proof.global_skip_proof true prf), gthy))
   471       else Proof (Proof_Node.init prf, (finish, gthy))
   472     end
   473   | _ => raise UNDEF));
   474 
   475 in
   476 
   477 fun local_theory_to_proof' loc f = begin_proof
   478   (fn int => fn gthy =>
   479     let val (finish, lthy) = Named_Target.switch loc gthy
   480     in (finish o Local_Theory.reset_group, f int (Local_Theory.new_group lthy)) end);
   481 
   482 fun local_theory_to_proof loc f = local_theory_to_proof' loc (K f);
   483 
   484 fun theory_to_proof f = begin_proof
   485   (fn _ => fn gthy =>
   486     (Context.Theory o Sign.reset_group o Sign.change_check o Proof_Context.theory_of,
   487       (case gthy of
   488         Context.Theory thy => f (Sign.new_group thy)
   489       | _ => raise UNDEF)));
   490 
   491 end;
   492 
   493 fun forget_proof strict = transaction (fn _ =>
   494   (fn Proof (prf, (_, orig_gthy)) =>
   495         if strict andalso not (Proof.has_bottom_goal (Proof_Node.current prf))
   496         then raise UNDEF else Theory (orig_gthy, NONE)
   497     | Skipped_Proof (_, (_, orig_gthy)) => Theory (orig_gthy, NONE)
   498     | _ => raise UNDEF));
   499 
   500 fun proofs' f = transaction (fn int =>
   501   (fn Proof (prf, x) => Proof (Proof_Node.applys (f int) prf, x)
   502     | skip as Skipped_Proof _ => skip
   503     | _ => raise UNDEF));
   504 
   505 fun proof' f = proofs' ((Seq.single o Seq.Result) oo f);
   506 val proofs = proofs' o K;
   507 val proof = proof' o K;
   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 Skipped_Proof (h, x) => Skipped_Proof (f h, x)
   515     | _ => raise UNDEF));
   516 
   517 fun skip_proof_to_theory pred = transaction (fn _ =>
   518   (fn Skipped_Proof (d, (gthy, _)) => if pred d then Theory (gthy, NONE) else raise UNDEF
   519     | _ => raise UNDEF));
   520 
   521 
   522 
   523 (** toplevel transactions **)
   524 
   525 (* runtime position *)
   526 
   527 fun exec_id id (tr as Transition {pos, ...}) =
   528   position (Position.put_id (Document_ID.print id) pos) tr;
   529 
   530 fun setmp_thread_position (Transition {pos, ...}) f x =
   531   Position.setmp_thread_data pos f x;
   532 
   533 
   534 (* post-transition hooks *)
   535 
   536 local
   537   val hooks =
   538     Synchronized.var "Toplevel.hooks" ([]: (transition -> state -> state -> unit) list);
   539 in
   540 
   541 fun add_hook hook = Synchronized.change hooks (cons hook);
   542 fun get_hooks () = Synchronized.value hooks;
   543 
   544 end;
   545 
   546 
   547 (* apply transitions *)
   548 
   549 fun get_timing (Transition {timing, ...}) = timing;
   550 fun put_timing timing = map_transition (fn (name, pos, _, trans) => (name, pos, timing, trans));
   551 
   552 local
   553 
   554 fun app int (tr as Transition {name, trans, ...}) =
   555   setmp_thread_position tr (fn state =>
   556     let
   557       val timing_start = Timing.start ();
   558 
   559       val (result, opt_err) =
   560          state |> (apply_trans int trans |> ! profiling > 0 ? profile (! profiling));
   561 
   562       val timing_result = Timing.result timing_start;
   563       val timing_props =
   564         Markup.command_timing :: (Markup.nameN, name_of tr) :: Position.properties_of (pos_of tr);
   565       val _ = Timing.protocol_message timing_props timing_result;
   566     in
   567       (result, Option.map (fn UNDEF => ERROR (type_error tr state) | exn => exn) opt_err)
   568     end);
   569 
   570 in
   571 
   572 fun transition int tr st =
   573   let
   574     val hooks = get_hooks ();
   575     fun apply_hooks st' = hooks |> List.app (fn f => (try (fn () => f tr st st') (); ()));
   576 
   577     val ctxt = try context_of st;
   578     val res =
   579       (case app int tr st of
   580         (_, SOME Runtime.TERMINATE) => NONE
   581       | (st', SOME (Runtime.EXCURSION_FAIL exn_info)) => SOME (st', SOME exn_info)
   582       | (st', SOME exn) => SOME (st', SOME (Runtime.exn_context ctxt exn, at_command tr))
   583       | (st', NONE) => SOME (st', NONE));
   584     val _ = (case res of SOME (st', NONE) => apply_hooks st' | _ => ());
   585   in res end;
   586 
   587 end;
   588 
   589 
   590 (* managed commands *)
   591 
   592 fun command_errors int tr st =
   593   (case transition int tr st of
   594     SOME (st', NONE) => ([], SOME st')
   595   | SOME (_, SOME (exn, _)) => (Runtime.exn_messages_ids exn, NONE)
   596   | NONE => (Runtime.exn_messages_ids Runtime.TERMINATE, NONE));
   597 
   598 fun command_exception int tr st =
   599   (case transition int tr st of
   600     SOME (st', NONE) => st'
   601   | SOME (_, SOME (exn, info)) =>
   602       if Exn.is_interrupt exn then reraise exn else raise Runtime.EXCURSION_FAIL (exn, info)
   603   | NONE => raise Runtime.EXCURSION_FAIL (Runtime.TERMINATE, at_command tr));
   604 
   605 val command = command_exception false;
   606 
   607 
   608 (* reset state *)
   609 
   610 local
   611 
   612 fun reset_state check trans st =
   613   if check st then NONE
   614   else #2 (command_errors false (trans empty) st);
   615 
   616 in
   617 
   618 val reset_theory = reset_state is_theory (forget_proof false);
   619 
   620 val reset_proof =
   621   reset_state is_proof
   622     (transaction (fn _ =>
   623       (fn Theory (gthy, _) => Skipped_Proof (0, (gthy, gthy))
   624         | _ => raise UNDEF)));
   625 
   626 end;
   627 
   628 
   629 (* scheduled proof result *)
   630 
   631 datatype result =
   632   Result of transition * state |
   633   Result_List of result list |
   634   Result_Future of result future;
   635 
   636 fun join_results (Result x) = [x]
   637   | join_results (Result_List xs) = maps join_results xs
   638   | join_results (Result_Future x) = join_results (Future.join x);
   639 
   640 local
   641 
   642 structure Result = Proof_Data
   643 (
   644   type T = result;
   645   val empty: T = Result_List [];
   646   fun init _ = empty;
   647 );
   648 
   649 val get_result = Result.get o Proof.context_of;
   650 val put_result = Proof.map_context o Result.put;
   651 
   652 fun timing_estimate include_head elem =
   653   let
   654     val trs = Thy_Syntax.flat_element elem |> not include_head ? tl;
   655     val timings = map get_timing trs;
   656   in
   657     if forall is_some timings then
   658       SOME (fold (curry Time.+ o the) timings Time.zeroTime)
   659     else NONE
   660   end;
   661 
   662 fun priority NONE = ~1
   663   | priority (SOME estimate) =
   664       Int.min (Real.floor (Real.max (Math.log10 (Time.toReal estimate), ~3.0)) - 3, ~1);
   665 
   666 fun proof_future_enabled estimate st =
   667   (case try proof_of st of
   668     NONE => false
   669   | SOME state =>
   670       not (Proof.is_relevant state) andalso
   671        (if can (Proof.assert_bottom true) state
   672         then Goal.future_enabled 1
   673         else
   674           (case estimate of
   675             NONE => Goal.future_enabled 2
   676           | SOME t => Goal.future_enabled_timing t)));
   677 
   678 fun atom_result keywords tr st =
   679   let
   680     val st' =
   681       if Goal.future_enabled 1 andalso Keyword.is_diag keywords (name_of tr) then
   682         (Execution.fork
   683           {name = "Toplevel.diag", pos = pos_of tr,
   684             pri = priority (timing_estimate true (Thy_Syntax.atom tr))}
   685           (fn () => command tr st); st)
   686       else command tr st;
   687   in (Result (tr, st'), st') end;
   688 
   689 in
   690 
   691 fun element_result keywords (Thy_Syntax.Element (tr, NONE)) st = atom_result keywords tr st
   692   | element_result keywords (elem as Thy_Syntax.Element (head_tr, SOME element_rest)) st =
   693       let
   694         val (head_result, st') = atom_result keywords head_tr st;
   695         val (body_elems, end_tr) = element_rest;
   696         val estimate = timing_estimate false elem;
   697       in
   698         if not (proof_future_enabled estimate st')
   699         then
   700           let
   701             val proof_trs = maps Thy_Syntax.flat_element body_elems @ [end_tr];
   702             val (proof_results, st'') = fold_map (atom_result keywords) proof_trs st';
   703           in (Result_List (head_result :: proof_results), st'') end
   704         else
   705           let
   706             val finish = Context.Theory o Proof_Context.theory_of;
   707 
   708             val future_proof =
   709               Proof.future_proof (fn state =>
   710                 Execution.fork
   711                   {name = "Toplevel.future_proof", pos = pos_of head_tr, pri = priority estimate}
   712                   (fn () =>
   713                     let
   714                       val State (SOME (Proof (prf, (_, orig_gthy))), prev) = st';
   715                       val prf' = Proof_Node.apply (K state) prf;
   716                       val (result, result_state) =
   717                         State (SOME (Proof (prf', (finish, orig_gthy))), prev)
   718                         |> fold_map (element_result keywords) body_elems ||> command end_tr;
   719                     in (Result_List result, presentation_context_of result_state) end))
   720               #> (fn (res, state') => state' |> put_result (Result_Future res));
   721 
   722             val forked_proof =
   723               proof (future_proof #>
   724                 (fn state => state |> Proof.local_done_proof |> put_result (get_result state))) o
   725               end_proof (fn _ => future_proof #>
   726                 (fn state => state |> Proof.global_done_proof |> Result.put (get_result state)));
   727 
   728             val st'' = st'
   729               |> command (head_tr |> reset_trans |> forked_proof);
   730             val end_result = Result (end_tr, st'');
   731             val result =
   732               Result_List [head_result, Result.get (presentation_context_of st''), end_result];
   733           in (result, st'') end
   734       end;
   735 
   736 end;
   737 
   738 end;