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