src/Pure/Isar/toplevel.ML
author wenzelm
Mon Jan 08 15:50:11 2018 +0100 (17 months ago ago)
changeset 67376 d5007d93bcc6
parent 67162 0050cd50936d
child 67381 146757999c8d
permissions -rw-r--r--
more operations;
     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 generic_theory_toplevel: generic_theory -> state
    12   val theory_toplevel: theory -> state
    13   val toplevel: state
    14   val is_toplevel: state -> bool
    15   val is_theory: state -> bool
    16   val is_proof: state -> bool
    17   val is_skipped_proof: state -> bool
    18   val level: state -> int
    19   val presentation_context_of: state -> Proof.context
    20   val previous_context_of: state -> Proof.context option
    21   val context_of: state -> Proof.context
    22   val generic_theory_of: state -> generic_theory
    23   val theory_of: state -> theory
    24   val proof_of: state -> Proof.state
    25   val proof_position_of: state -> int
    26   val end_theory: Position.T -> state -> theory
    27   val pretty_context: state -> Pretty.T list
    28   val pretty_state: state -> Pretty.T list
    29   val string_of_state: state -> string
    30   val pretty_abstract: state -> Pretty.T
    31   type transition
    32   val empty: transition
    33   val name_of: transition -> string
    34   val pos_of: transition -> Position.T
    35   val type_error: transition -> string
    36   val name: string -> transition -> transition
    37   val position: Position.T -> transition -> transition
    38   val init_theory: (unit -> theory) -> transition -> transition
    39   val is_init: transition -> bool
    40   val modify_init: (unit -> theory) -> transition -> transition
    41   val exit: transition -> transition
    42   val keep: (state -> unit) -> transition -> transition
    43   val keep': (bool -> state -> unit) -> transition -> transition
    44   val keep_proof: (state -> unit) -> transition -> transition
    45   val ignored: Position.T -> transition
    46   val is_ignored: transition -> bool
    47   val malformed: Position.T -> string -> transition
    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': (bool * Position.T) option -> (xstring * Position.T) option ->
    56     (bool -> local_theory -> local_theory) -> transition -> transition
    57   val local_theory: (bool * Position.T) option -> (xstring * Position.T) option ->
    58     (local_theory -> local_theory) -> transition -> transition
    59   val present_local_theory: (xstring * Position.T) option -> (state -> unit) ->
    60     transition -> transition
    61   val local_theory_to_proof': (bool * Position.T) option -> (xstring * Position.T) option ->
    62     (bool -> local_theory -> Proof.state) -> transition -> transition
    63   val local_theory_to_proof: (bool * Position.T) option -> (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: (unit -> unit) -> transition -> transition
    74   val skip_proof_open: transition -> transition
    75   val skip_proof_close: transition -> transition
    76   val exec_id: Document_ID.exec -> transition -> transition
    77   val setmp_thread_position: transition -> ('a -> 'b) -> 'a -> 'b
    78   val add_hook: (transition -> state -> state -> unit) -> unit
    79   val get_timing: transition -> Time.time
    80   val put_timing: Time.time -> transition -> transition
    81   val transition: bool -> transition -> state -> state * (exn * string) option
    82   val command_errors: bool -> transition -> state -> Runtime.error list * state option
    83   val command_exception: bool -> transition -> state -> state
    84   val reset_theory: state -> state option
    85   val reset_proof: state -> state option
    86   type result
    87   val join_results: result -> (transition * state) list
    88   val element_result: Keyword.keywords -> transition Thy_Syntax.element -> state -> result * state
    89 end;
    90 
    91 structure Toplevel: TOPLEVEL =
    92 struct
    93 
    94 (** toplevel state **)
    95 
    96 exception UNDEF = Runtime.UNDEF;
    97 
    98 
    99 (* datatype node *)
   100 
   101 datatype node =
   102   Theory of generic_theory * Proof.context option
   103     (*theory with presentation context*) |
   104   Proof of Proof_Node.T * ((Proof.context -> generic_theory) * generic_theory)
   105     (*proof node, finish, original theory*) |
   106   Skipped_Proof of int * (generic_theory * generic_theory);
   107     (*proof depth, resulting theory, original theory*)
   108 
   109 val theory_node = fn Theory (gthy, _) => SOME gthy | _ => NONE;
   110 val proof_node = fn Proof (prf, _) => SOME prf | _ => NONE;
   111 val skipped_proof_node = fn Skipped_Proof _ => true | _ => false;
   112 
   113 fun cases_node f _ (Theory (gthy, _)) = f gthy
   114   | cases_node _ g (Proof (prf, _)) = g (Proof_Node.current prf)
   115   | cases_node f _ (Skipped_Proof (_, (gthy, _))) = f gthy;
   116 
   117 val context_node = cases_node Context.proof_of Proof.context_of;
   118 
   119 
   120 (* datatype state *)
   121 
   122 datatype state = State of node option * node option;  (*current, previous*)
   123 
   124 fun generic_theory_toplevel gthy = State (SOME (Theory (gthy, NONE)), NONE);
   125 val theory_toplevel = generic_theory_toplevel o Context.Theory;
   126 
   127 val toplevel = State (NONE, NONE);
   128 
   129 fun is_toplevel (State (NONE, _)) = true
   130   | is_toplevel _ = false;
   131 
   132 fun level (State (NONE, _)) = 0
   133   | level (State (SOME (Theory _), _)) = 0
   134   | level (State (SOME (Proof (prf, _)), _)) = Proof.level (Proof_Node.current prf)
   135   | level (State (SOME (Skipped_Proof (d, _)), _)) = d + 1;   (*different notion of proof depth!*)
   136 
   137 fun str_of_state (State (NONE, SOME (Theory (Context.Theory thy, _)))) =
   138       "at top level, result theory " ^ quote (Context.theory_name thy)
   139   | str_of_state (State (NONE, _)) = "at top level"
   140   | str_of_state (State (SOME (Theory (Context.Theory _, _)), _)) = "in theory mode"
   141   | str_of_state (State (SOME (Theory (Context.Proof _, _)), _)) = "in local theory mode"
   142   | str_of_state (State (SOME (Proof _), _)) = "in proof mode"
   143   | str_of_state (State (SOME (Skipped_Proof _), _)) = "in skipped proof mode";
   144 
   145 
   146 (* current node *)
   147 
   148 fun node_of (State (NONE, _)) = raise UNDEF
   149   | node_of (State (SOME node, _)) = node;
   150 
   151 fun is_theory state = not (is_toplevel state) andalso is_some (theory_node (node_of state));
   152 fun is_proof state = not (is_toplevel state) andalso is_some (proof_node (node_of state));
   153 fun is_skipped_proof state = not (is_toplevel state) andalso skipped_proof_node (node_of state);
   154 
   155 fun node_case f g state = cases_node f g (node_of state);
   156 
   157 fun presentation_context_of state =
   158   (case try node_of state of
   159     SOME (Theory (_, SOME ctxt)) => ctxt
   160   | SOME node => context_node node
   161   | NONE => raise UNDEF);
   162 
   163 fun previous_context_of (State (_, NONE)) = NONE
   164   | previous_context_of (State (_, SOME prev)) = SOME (context_node prev);
   165 
   166 val context_of = node_case Context.proof_of Proof.context_of;
   167 val generic_theory_of = node_case I (Context.Proof o Proof.context_of);
   168 val theory_of = node_case Context.theory_of Proof.theory_of;
   169 val proof_of = node_case (fn _ => error "No proof state") I;
   170 
   171 fun proof_position_of state =
   172   (case node_of state of
   173     Proof (prf, _) => Proof_Node.position prf
   174   | _ => ~1);
   175 
   176 fun end_theory _ (State (NONE, SOME (Theory (Context.Theory thy, _)))) = thy
   177   | end_theory pos (State (NONE, _)) = error ("Bad theory" ^ Position.here pos)
   178   | end_theory pos (State (SOME _, _)) = error ("Unfinished theory" ^ Position.here pos);
   179 
   180 
   181 (* print state *)
   182 
   183 fun pretty_context state =
   184   (case try node_of state of
   185     NONE => []
   186   | SOME node =>
   187       let
   188         val gthy =
   189           (case node of
   190             Theory (gthy, _) => gthy
   191           | Proof (_, (_, gthy)) => gthy
   192           | Skipped_Proof (_, (_, gthy)) => gthy);
   193         val lthy = Context.cases (Named_Target.theory_init) I gthy;
   194       in Local_Theory.pretty lthy end);
   195 
   196 fun pretty_state state =
   197   (case try node_of state of
   198     NONE => []
   199   | SOME (Theory _) => []
   200   | SOME (Proof (prf, _)) => Proof.pretty_state (Proof_Node.current prf)
   201   | SOME (Skipped_Proof (d, _)) => [Pretty.str ("skipped proof: depth " ^ string_of_int d)]);
   202 
   203 val string_of_state = pretty_state #> Pretty.chunks #> Pretty.string_of;
   204 
   205 fun pretty_abstract state = Pretty.str ("<Isar " ^ str_of_state state ^ ">");
   206 
   207 val _ = ML_system_pp (fn _ => fn _ => Pretty.to_polyml o pretty_abstract);
   208 
   209 
   210 
   211 (** toplevel transitions **)
   212 
   213 (* node transactions -- maintaining stable checkpoints *)
   214 
   215 exception FAILURE of state * exn;
   216 
   217 local
   218 
   219 fun reset_presentation (Theory (gthy, _)) = Theory (gthy, NONE)
   220   | reset_presentation 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,         (*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, Time.zeroTime, []);
   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 keep_proof f =
   349   keep (fn st =>
   350     if is_proof st then f st
   351     else if is_skipped_proof st then ()
   352     else warning "No proof state");
   353 
   354 fun ignored pos = empty |> name "<ignored>" |> position pos |> keep (fn _ => ());
   355 fun is_ignored tr = name_of tr = "<ignored>";
   356 
   357 fun malformed pos msg =
   358   empty |> name "<malformed>" |> position pos |> keep (fn _ => error msg);
   359 
   360 
   361 (* theory transitions *)
   362 
   363 fun generic_theory f = transaction (fn _ =>
   364   (fn Theory (gthy, _) => Theory (f gthy, NONE)
   365     | _ => raise UNDEF));
   366 
   367 fun theory' f = transaction (fn int =>
   368   (fn Theory (Context.Theory thy, _) =>
   369       let val thy' = thy
   370         |> Sign.new_group
   371         |> f int
   372         |> Sign.reset_group;
   373       in Theory (Context.Theory thy', NONE) end
   374     | _ => raise UNDEF));
   375 
   376 fun theory f = theory' (K f);
   377 
   378 fun begin_local_theory begin f = transaction (fn _ =>
   379   (fn Theory (Context.Theory thy, _) =>
   380         let
   381           val lthy = f thy;
   382           val gthy = if begin then Context.Proof lthy else Context.Theory (Named_Target.exit lthy);
   383           val _ =
   384             (case Local_Theory.pretty lthy of
   385               [] => ()
   386             | prts => Output.state (Pretty.string_of (Pretty.chunks prts)));
   387         in Theory (gthy, SOME lthy) end
   388     | _ => raise UNDEF));
   389 
   390 val end_local_theory = transaction (fn _ =>
   391   (fn Theory (Context.Proof lthy, _) => Theory (Context.Theory (Named_Target.exit lthy), SOME lthy)
   392     | _ => raise UNDEF));
   393 
   394 fun open_target f = transaction (fn _ =>
   395   (fn Theory (gthy, _) =>
   396         let val lthy = f gthy
   397         in Theory (Context.Proof lthy, SOME lthy) end
   398     | _ => raise UNDEF));
   399 
   400 val close_target = transaction (fn _ =>
   401   (fn Theory (Context.Proof lthy, _) =>
   402         (case try Local_Theory.close_target lthy of
   403           SOME ctxt' =>
   404             let
   405               val gthy' =
   406                 if can Local_Theory.assert ctxt'
   407                 then Context.Proof ctxt'
   408                 else Context.Theory (Proof_Context.theory_of ctxt');
   409             in Theory (gthy', SOME lthy) end
   410         | NONE => raise UNDEF)
   411     | _ => raise UNDEF));
   412 
   413 fun restricted_context (SOME (strict, scope)) =
   414       Proof_Context.map_naming (Name_Space.restricted strict scope)
   415   | restricted_context NONE = I;
   416 
   417 fun local_theory' restricted target f = present_transaction (fn int =>
   418   (fn Theory (gthy, _) =>
   419         let
   420           val (finish, lthy) = Named_Target.switch target gthy;
   421           val lthy' = lthy
   422             |> restricted_context restricted
   423             |> Local_Theory.new_group
   424             |> f int
   425             |> Local_Theory.reset_group;
   426         in Theory (finish lthy', SOME lthy') end
   427     | _ => raise UNDEF))
   428   (K ());
   429 
   430 fun local_theory restricted target f = local_theory' restricted target (K f);
   431 
   432 fun present_local_theory target = present_transaction (fn _ =>
   433   (fn Theory (gthy, _) =>
   434         let val (finish, lthy) = Named_Target.switch target gthy;
   435         in Theory (finish lthy, SOME lthy) end
   436     | _ => raise UNDEF));
   437 
   438 
   439 (* proof transitions *)
   440 
   441 fun end_proof f = transaction (fn int =>
   442   (fn Proof (prf, (finish, _)) =>
   443         let val state = Proof_Node.current prf in
   444           if can (Proof.assert_bottom true) state then
   445             let
   446               val ctxt' = f int state;
   447               val gthy' = finish ctxt';
   448             in Theory (gthy', SOME ctxt') end
   449           else raise UNDEF
   450         end
   451     | Skipped_Proof (0, (gthy, _)) => Theory (gthy, NONE)
   452     | _ => raise UNDEF));
   453 
   454 local
   455 
   456 fun begin_proof init = transaction (fn int =>
   457   (fn Theory (gthy, _) =>
   458     let
   459       val (finish, prf) = init int gthy;
   460       val document = Options.default_string "document";
   461       val skip = (document = "" orelse document = "false") andalso 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 {trans, ...}) =
   568   setmp_thread_position tr (fn state =>
   569     let
   570       val timing_start = Timing.start ();
   571       val (result, opt_err) = apply_trans int trans state;
   572       val timing_result = Timing.result timing_start;
   573       val timing_props =
   574         Markup.command_timing :: (Markup.nameN, name_of tr) :: Position.properties_of (pos_of tr);
   575       val _ = Timing.protocol_message timing_props timing_result;
   576     in (result, Option.map (fn UNDEF => ERROR (type_error tr) | exn => exn) opt_err) end);
   577 
   578 in
   579 
   580 fun transition int tr st =
   581   let
   582     val (st', opt_err) =
   583       Context.setmp_generic_context (try (Context.Proof o presentation_context_of) st)
   584         (fn () => app int tr st) ();
   585     val opt_err' = opt_err |> Option.map
   586       (fn Runtime.EXCURSION_FAIL exn_info => exn_info
   587         | exn => (Runtime.exn_context (try context_of st) exn, at_command tr));
   588     val _ = get_hooks () |> List.app (fn f => (try (fn () => f tr st st') (); ()));
   589   in (st', opt_err') end;
   590 
   591 end;
   592 
   593 
   594 (* managed commands *)
   595 
   596 fun command_errors int tr st =
   597   (case transition int tr st of
   598     (st', NONE) => ([], SOME st')
   599   | (_, SOME (exn, _)) => (Runtime.exn_messages exn, NONE));
   600 
   601 fun command_exception int tr st =
   602   (case transition int tr st of
   603     (st', NONE) => st'
   604   | (_, SOME (exn, info)) =>
   605       if Exn.is_interrupt exn then Exn.reraise exn
   606       else raise Runtime.EXCURSION_FAIL (exn, info));
   607 
   608 val command = command_exception false;
   609 
   610 
   611 (* reset state *)
   612 
   613 local
   614 
   615 fun reset_state check trans st =
   616   if check st then NONE
   617   else #2 (command_errors false (trans empty) st);
   618 
   619 in
   620 
   621 val reset_theory = reset_state is_theory (forget_proof false);
   622 
   623 val reset_proof =
   624   reset_state is_proof
   625     (transaction (fn _ =>
   626       (fn Theory (gthy, _) => Skipped_Proof (0, (gthy, gthy))
   627         | _ => raise UNDEF)));
   628 
   629 end;
   630 
   631 
   632 (* scheduled proof result *)
   633 
   634 datatype result =
   635   Result of transition * state |
   636   Result_List of result list |
   637   Result_Future of result future;
   638 
   639 fun join_results (Result x) = [x]
   640   | join_results (Result_List xs) = maps join_results xs
   641   | join_results (Result_Future x) = join_results (Future.join x);
   642 
   643 local
   644 
   645 structure Result = Proof_Data
   646 (
   647   type T = result;
   648   fun init _ = Result_List [];
   649 );
   650 
   651 val get_result = Result.get o Proof.context_of;
   652 val put_result = Proof.map_context o Result.put;
   653 
   654 fun timing_estimate elem =
   655   let val trs = tl (Thy_Syntax.flat_element elem)
   656   in fold (fn tr => fn t => get_timing tr + t) trs Time.zeroTime end;
   657 
   658 fun proof_future_enabled estimate st =
   659   (case try proof_of st of
   660     NONE => false
   661   | SOME state =>
   662       not (Proof.is_relevant state) andalso
   663        (if can (Proof.assert_bottom true) state
   664         then Goal.future_enabled 1
   665         else Goal.future_enabled 2 orelse Goal.future_enabled_timing estimate));
   666 
   667 fun atom_result keywords tr st =
   668   let
   669     val st' =
   670       if Goal.future_enabled 1 andalso Keyword.is_diag keywords (name_of tr) then
   671         (Execution.fork
   672           {name = "Toplevel.diag", pos = pos_of tr, pri = ~1}
   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 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 = ~1}
   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;