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