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