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