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