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