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