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