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