src/Pure/Isar/toplevel.ML
author wenzelm
Tue Feb 26 19:58:27 2013 +0100 (2013-02-26 ago)
changeset 51285 0859bd338c9b
parent 51284 59a03019f3bf
child 51318 e6524a89c9e3
permissions -rw-r--r--
tuned signature;
     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_exception: bool -> transition -> state -> state
    98   val command_errors: bool -> transition -> state -> Runtime.error list * state option
    99   val element_result: transition Thy_Syntax.element -> state ->
   100     (transition * state) list future * state
   101 end;
   102 
   103 structure Toplevel: TOPLEVEL =
   104 struct
   105 
   106 (** toplevel state **)
   107 
   108 exception UNDEF = Runtime.UNDEF;
   109 
   110 
   111 (* local theory wrappers *)
   112 
   113 val loc_init = Named_Target.context_cmd;
   114 val loc_exit = Local_Theory.assert_bottom true #> Local_Theory.exit_global;
   115 
   116 fun loc_begin loc (Context.Theory thy) =
   117       (Context.Theory o loc_exit, loc_init (the_default ("-", Position.none) loc) thy)
   118   | loc_begin NONE (Context.Proof lthy) =
   119       (Context.Proof o Local_Theory.restore, lthy)
   120   | loc_begin (SOME loc) (Context.Proof lthy) =
   121       (Context.Proof o Named_Target.reinit lthy, loc_init loc (loc_exit lthy));
   122 
   123 
   124 (* datatype node *)
   125 
   126 datatype node =
   127   Theory of generic_theory * Proof.context option
   128     (*theory with presentation context*) |
   129   Proof of Proof_Node.T * ((Proof.context -> generic_theory) * generic_theory)
   130     (*proof node, finish, original theory*) |
   131   SkipProof of int * (generic_theory * generic_theory);
   132     (*proof depth, resulting theory, original theory*)
   133 
   134 val theory_node = fn Theory (gthy, _) => SOME gthy | _ => NONE;
   135 val proof_node = fn Proof (prf, _) => SOME prf | _ => NONE;
   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 _ (SkipProof (_, (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 (SkipProof (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 (SkipProof _), _)) = "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 
   173 fun node_case f g state = cases_node f g (node_of state);
   174 
   175 fun presentation_context_of state =
   176   (case try node_of state of
   177     SOME (Theory (_, SOME ctxt)) => ctxt
   178   | SOME node => context_node node
   179   | NONE => raise UNDEF);
   180 
   181 fun previous_context_of (State (_, NONE)) = NONE
   182   | previous_context_of (State (_, SOME prev)) = SOME (context_node prev);
   183 
   184 val context_of = node_case Context.proof_of Proof.context_of;
   185 val generic_theory_of = node_case I (Context.Proof o Proof.context_of);
   186 val theory_of = node_case Context.theory_of Proof.theory_of;
   187 val proof_of = node_case (fn _ => raise UNDEF) I;
   188 
   189 fun proof_position_of state =
   190   (case node_of state of
   191     Proof (prf, _) => Proof_Node.position prf
   192   | _ => raise UNDEF);
   193 
   194 fun end_theory _ (State (NONE, SOME (Theory (Context.Theory thy, _)))) = thy
   195   | end_theory pos (State (NONE, _)) = error ("Bad theory" ^ Position.here pos)
   196   | end_theory pos (State (SOME _, _)) = error ("Unfinished theory" ^ Position.here pos);
   197 
   198 
   199 (* print state *)
   200 
   201 val pretty_context = Local_Theory.pretty o Context.cases (Named_Target.theory_init) I;
   202 
   203 fun print_state_context state =
   204   (case try node_of state of
   205     NONE => []
   206   | SOME (Theory (gthy, _)) => pretty_context gthy
   207   | SOME (Proof (_, (_, gthy))) => pretty_context gthy
   208   | SOME (SkipProof (_, (gthy, _))) => pretty_context gthy)
   209   |> Pretty.chunks |> Pretty.writeln;
   210 
   211 fun print_state prf_only state =
   212   (case try node_of state of
   213     NONE => []
   214   | SOME (Theory (gthy, _)) => if prf_only then [] else pretty_context gthy
   215   | SOME (Proof (prf, _)) =>
   216       Proof.pretty_state (Proof_Node.position prf) (Proof_Node.current prf)
   217   | SOME (SkipProof (d, _)) => [Pretty.str ("skipped proof: depth " ^ string_of_int d)])
   218   |> Pretty.markup_chunks Markup.state |> Pretty.writeln;
   219 
   220 fun pretty_abstract state = Pretty.str ("<Isar " ^ str_of_state state ^ ">");
   221 
   222 
   223 
   224 (** toplevel transitions **)
   225 
   226 val quiet = Unsynchronized.ref false;
   227 val debug = Runtime.debug;
   228 val interact = Unsynchronized.ref false;
   229 val timing = Unsynchronized.ref false;
   230 val profiling = Unsynchronized.ref 0;
   231 val skip_proofs = Unsynchronized.ref false;
   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   no_timing: bool,           (*suppress timing*)
   348   timing: Time.time,         (*prescient timing information*)
   349   trans: trans list};        (*primitive transitions (union)*)
   350 
   351 fun make_transition (name, pos, int_only, print, no_timing, timing, trans) =
   352   Transition {name = name, pos = pos, int_only = int_only, print = print,
   353     no_timing = no_timing, timing = timing, trans = trans};
   354 
   355 fun map_transition f (Transition {name, pos, int_only, print, no_timing, timing, trans}) =
   356   make_transition (f (name, pos, int_only, print, no_timing, timing, trans));
   357 
   358 val empty = make_transition ("", Position.none, false, false, false, Time.zeroTime, []);
   359 
   360 
   361 (* diagnostics *)
   362 
   363 fun print_of (Transition {print, ...}) = print;
   364 fun name_of (Transition {name, ...}) = name;
   365 fun pos_of (Transition {pos, ...}) = pos;
   366 
   367 fun command_msg msg tr = msg ^ "command " ^ quote (name_of tr) ^ Position.here (pos_of tr);
   368 fun at_command tr = command_msg "At " tr;
   369 
   370 fun type_error tr state =
   371   ERROR (command_msg "Illegal application of " tr ^ " " ^ str_of_state state);
   372 
   373 
   374 (* modify transitions *)
   375 
   376 fun name name = map_transition (fn (_, pos, int_only, print, no_timing, timing, trans) =>
   377   (name, pos, int_only, print, no_timing, timing, trans));
   378 
   379 fun position pos = map_transition (fn (name, _, int_only, print, no_timing, timing, trans) =>
   380   (name, pos, int_only, print, no_timing, timing, trans));
   381 
   382 fun interactive int_only = map_transition (fn (name, pos, _, print, no_timing, timing, trans) =>
   383   (name, pos, int_only, print, no_timing, timing, trans));
   384 
   385 val no_timing = map_transition (fn (name, pos, int_only, print, _, timing, trans) =>
   386   (name, pos, int_only, print, true, timing, trans));
   387 
   388 fun add_trans tr = map_transition (fn (name, pos, int_only, print, no_timing, timing, trans) =>
   389   (name, pos, int_only, print, no_timing, timing, tr :: trans));
   390 
   391 val reset_trans = map_transition (fn (name, pos, int_only, print, no_timing, timing, _) =>
   392   (name, pos, int_only, print, no_timing, timing, []));
   393 
   394 fun set_print print = map_transition (fn (name, pos, int_only, _, no_timing, timing, trans) =>
   395   (name, pos, int_only, print, no_timing, timing, trans));
   396 
   397 val print = set_print true;
   398 
   399 
   400 (* basic transitions *)
   401 
   402 fun init_theory f = add_trans (Init f);
   403 
   404 fun is_init (Transition {trans = [Init _], ...}) = true
   405   | is_init _ = false;
   406 
   407 fun modify_init f tr = if is_init tr then init_theory f (reset_trans tr) else tr;
   408 
   409 val exit = add_trans Exit;
   410 val keep' = add_trans o Keep;
   411 
   412 fun present_transaction f g = add_trans (Transaction (f, g));
   413 fun transaction f = present_transaction f (K ());
   414 
   415 fun keep f = add_trans (Keep (fn _ => f));
   416 fun imperative f = keep (fn _ => f ());
   417 
   418 fun ignored pos = empty |> name "<ignored>" |> position pos |> imperative I;
   419 fun is_ignored tr = name_of tr = "<ignored>";
   420 
   421 val malformed_name = "<malformed>";
   422 fun malformed pos msg =
   423   empty |> name malformed_name |> position pos |> imperative (fn () => error msg);
   424 fun is_malformed tr = name_of tr = malformed_name;
   425 
   426 val unknown_theory = imperative (fn () => warning "Unknown theory context");
   427 val unknown_proof = imperative (fn () => warning "Unknown proof context");
   428 val unknown_context = imperative (fn () => warning "Unknown context");
   429 
   430 
   431 (* theory transitions *)
   432 
   433 fun generic_theory f = transaction (fn _ =>
   434   (fn Theory (gthy, _) => Theory (f gthy, NONE)
   435     | _ => raise UNDEF));
   436 
   437 fun theory' f = transaction (fn int =>
   438   (fn Theory (Context.Theory thy, _) =>
   439       let val thy' = thy
   440         |> Sign.new_group
   441         |> Theory.checkpoint
   442         |> f int
   443         |> Sign.reset_group;
   444       in Theory (Context.Theory thy', NONE) end
   445     | _ => raise UNDEF));
   446 
   447 fun theory f = theory' (K f);
   448 
   449 fun begin_local_theory begin f = transaction (fn _ =>
   450   (fn Theory (Context.Theory thy, _) =>
   451         let
   452           val lthy = f thy;
   453           val gthy = if begin then Context.Proof lthy else Context.Theory (loc_exit lthy);
   454         in Theory (gthy, SOME lthy) end
   455     | _ => raise UNDEF));
   456 
   457 val end_local_theory = transaction (fn _ =>
   458   (fn Theory (Context.Proof lthy, _) => Theory (Context.Theory (loc_exit lthy), SOME lthy)
   459     | _ => raise UNDEF));
   460 
   461 fun open_target f = transaction (fn _ =>
   462   (fn Theory (gthy, _) =>
   463         let val lthy = f gthy
   464         in Theory (Context.Proof lthy, SOME lthy) end
   465     | _ => raise UNDEF));
   466 
   467 val close_target = transaction (fn _ =>
   468   (fn Theory (Context.Proof lthy, _) =>
   469         (case try Local_Theory.close_target lthy of
   470           SOME ctxt' =>
   471             let
   472               val gthy' =
   473                 if can Local_Theory.assert ctxt'
   474                 then Context.Proof ctxt'
   475                 else Context.Theory (Proof_Context.theory_of ctxt');
   476             in Theory (gthy', SOME lthy) end
   477         | NONE => raise UNDEF)
   478     | _ => raise UNDEF));
   479 
   480 
   481 local
   482 
   483 fun local_theory_presentation loc f = present_transaction (fn int =>
   484   (fn Theory (gthy, _) =>
   485         let
   486           val (finish, lthy) = loc_begin loc gthy;
   487           val lthy' = lthy
   488             |> Local_Theory.new_group
   489             |> f int
   490             |> Local_Theory.reset_group;
   491         in Theory (finish lthy', SOME lthy') end
   492     | _ => raise UNDEF));
   493 
   494 in
   495 
   496 fun local_theory' loc f = local_theory_presentation loc f (K ());
   497 fun local_theory loc f = local_theory' loc (K f);
   498 fun present_local_theory loc = local_theory_presentation loc (K I);
   499 
   500 end;
   501 
   502 
   503 (* proof transitions *)
   504 
   505 fun end_proof f = transaction (fn int =>
   506   (fn Proof (prf, (finish, _)) =>
   507         let val state = Proof_Node.current prf in
   508           if can (Proof.assert_bottom true) state then
   509             let
   510               val ctxt' = f int state;
   511               val gthy' = finish ctxt';
   512             in Theory (gthy', SOME ctxt') end
   513           else raise UNDEF
   514         end
   515     | SkipProof (0, (gthy, _)) => Theory (gthy, NONE)
   516     | _ => raise UNDEF));
   517 
   518 local
   519 
   520 fun begin_proof init = transaction (fn int =>
   521   (fn Theory (gthy, _) =>
   522     let
   523       val (finish, prf) = init int gthy;
   524       val skip = ! skip_proofs;
   525       val (is_goal, no_skip) =
   526         (true, Proof.schematic_goal prf) handle ERROR _ => (false, true);
   527       val _ =
   528         if is_goal andalso skip andalso no_skip then
   529           warning "Cannot skip proof of schematic goal statement"
   530         else ();
   531     in
   532       if skip andalso not no_skip then
   533         SkipProof (0, (finish (Proof.global_skip_proof int prf), gthy))
   534       else Proof (Proof_Node.init prf, (finish, gthy))
   535     end
   536   | _ => raise UNDEF));
   537 
   538 in
   539 
   540 fun local_theory_to_proof' loc f = begin_proof
   541   (fn int => fn gthy =>
   542     let val (finish, lthy) = loc_begin loc gthy
   543     in (finish o Local_Theory.reset_group, f int (Local_Theory.new_group lthy)) end);
   544 
   545 fun local_theory_to_proof loc f = local_theory_to_proof' loc (K f);
   546 
   547 fun theory_to_proof f = begin_proof
   548   (fn _ => fn gthy =>
   549     (Context.Theory o Sign.reset_group o Proof_Context.theory_of,
   550       (case gthy of
   551         Context.Theory thy => f (Theory.checkpoint (Sign.new_group thy))
   552       | _ => raise UNDEF)));
   553 
   554 end;
   555 
   556 val forget_proof = transaction (fn _ =>
   557   (fn Proof (_, (_, orig_gthy)) => Theory (orig_gthy, NONE)
   558     | SkipProof (_, (_, orig_gthy)) => Theory (orig_gthy, NONE)
   559     | _ => raise UNDEF));
   560 
   561 val present_proof = present_transaction (fn _ =>
   562   (fn Proof (prf, x) => Proof (Proof_Node.apply I prf, x)
   563     | skip as SkipProof _ => skip
   564     | _ => raise UNDEF));
   565 
   566 fun proofs' f = transaction (fn int =>
   567   (fn Proof (prf, x) => Proof (Proof_Node.applys (f int) prf, x)
   568     | skip as SkipProof _ => skip
   569     | _ => raise UNDEF));
   570 
   571 fun proof' f = proofs' ((Seq.single o Seq.Result) oo f);
   572 val proofs = proofs' o K;
   573 val proof = proof' o K;
   574 
   575 fun actual_proof f = transaction (fn _ =>
   576   (fn Proof (prf, x) => Proof (f prf, x)
   577     | _ => raise UNDEF));
   578 
   579 fun skip_proof f = transaction (fn _ =>
   580   (fn SkipProof (h, x) => SkipProof (f h, x)
   581     | _ => raise UNDEF));
   582 
   583 fun skip_proof_to_theory pred = transaction (fn _ =>
   584   (fn SkipProof (d, (gthy, _)) => if pred d then Theory (gthy, NONE) else raise UNDEF
   585     | _ => raise UNDEF));
   586 
   587 
   588 
   589 (** toplevel transactions **)
   590 
   591 (* identification *)
   592 
   593 fun get_id (Transition {pos, ...}) = Position.get_id pos;
   594 fun put_id id (tr as Transition {pos, ...}) = position (Position.put_id id pos) tr;
   595 
   596 
   597 (* approximative identification within source file *)
   598 
   599 fun approximative_id tr =
   600   let
   601     val name = name_of tr;
   602     val pos = pos_of tr;
   603   in
   604     (case (Position.file_of pos, Position.offset_of pos) of
   605       (SOME file, SOME offset) => SOME {file = file, offset = offset, name = name}
   606     | _ => NONE)
   607   end;
   608 
   609 
   610 (* thread position *)
   611 
   612 fun setmp_thread_position (Transition {pos, ...}) f x =
   613   Position.setmp_thread_data pos f x;
   614 
   615 fun status tr m =
   616   setmp_thread_position tr (fn () => Output.status (Markup.markup_only m)) ();
   617 
   618 
   619 (* post-transition hooks *)
   620 
   621 local
   622   val hooks = Unsynchronized.ref ([]: (transition -> state -> state -> unit) list);
   623 in
   624 
   625 fun add_hook f = CRITICAL (fn () => Unsynchronized.change hooks (cons f));
   626 fun get_hooks () = ! hooks;
   627 
   628 end;
   629 
   630 
   631 (* apply transitions *)
   632 
   633 fun get_timing (Transition {timing, ...}) = timing;
   634 fun put_timing timing = map_transition (fn (name, pos, int_only, print, no_timing, _, trans) =>
   635   (name, pos, int_only, print, no_timing, timing, trans));
   636 
   637 local
   638 
   639 fun timing_message tr (t: Timing.timing) =
   640   if Timing.is_relevant_time (#elapsed t) then
   641     (case approximative_id tr of
   642       SOME id =>
   643         (Output.protocol_message
   644           (Markup.command_timing :: Markup.command_timing_properties id (#elapsed t)) ""
   645         handle Fail _ => ())
   646     | NONE => ())
   647   else ();
   648 
   649 fun app int (tr as Transition {trans, print, no_timing, ...}) =
   650   setmp_thread_position tr (fn state =>
   651     let
   652       fun do_timing f x = (warning (command_msg "" tr); timeap f x);
   653       fun do_profiling f x = profile (! profiling) f x;
   654 
   655       val start = Timing.start ();
   656 
   657       val (result, status) =
   658          state |>
   659           (apply_trans int trans
   660             |> (! profiling > 0 andalso not no_timing) ? do_profiling
   661             |> (! profiling > 0 orelse ! timing andalso not no_timing) ? do_timing);
   662 
   663       val _ = if int andalso not (! quiet) andalso print then print_state false result else ();
   664 
   665       val _ = timing_message tr (Timing.result start);
   666     in (result, Option.map (fn UNDEF => type_error tr state | exn => exn) status) end);
   667 
   668 in
   669 
   670 fun transition int tr st =
   671   let
   672     val hooks = get_hooks ();
   673     fun apply_hooks st' = hooks |> List.app (fn f => (try (fn () => f tr st st') (); ()));
   674 
   675     val ctxt = try context_of st;
   676     val res =
   677       (case app int tr st of
   678         (_, SOME Runtime.TERMINATE) => NONE
   679       | (st', SOME (Runtime.EXCURSION_FAIL exn_info)) => SOME (st', SOME exn_info)
   680       | (st', SOME exn) => SOME (st', SOME (Runtime.exn_context ctxt exn, at_command tr))
   681       | (st', NONE) => SOME (st', NONE));
   682     val _ = (case res of SOME (st', NONE) => apply_hooks st' | _ => ());
   683   in res end;
   684 
   685 end;
   686 
   687 
   688 (* managed commands *)
   689 
   690 fun command_exception int tr st =
   691   (case transition int tr st of
   692     SOME (st', NONE) => st'
   693   | SOME (_, SOME (exn, info)) =>
   694       if Exn.is_interrupt exn then reraise exn else raise Runtime.EXCURSION_FAIL (exn, info)
   695   | NONE => raise Runtime.EXCURSION_FAIL (Runtime.TERMINATE, at_command tr));
   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 
   704 (* scheduled proof result *)
   705 
   706 structure Result = Proof_Data
   707 (
   708   type T = (transition * state) list future;
   709   val empty: T = Future.value [];
   710   fun init _ = empty;
   711 );
   712 
   713 fun priority trs =
   714   let val estimate = fold (curry Time.+ o get_timing) trs Time.zeroTime in
   715     if estimate = Time.zeroTime then ~1
   716     else Int.min (Real.floor (Real.max (Math.log10 (Time.toReal estimate), ~3.0)) - 3, ~1)
   717   end;
   718 
   719 fun element_result (Thy_Syntax.Element (head_tr, opt_proof)) st =
   720   let
   721     val command = command_exception (! interact);
   722 
   723     fun atom_result tr st =
   724       let
   725         val st' =
   726           if Goal.future_enabled () andalso Keyword.is_diag (name_of tr) then
   727             setmp_thread_position tr (fn () =>
   728               (Goal.fork_name "Toplevel.diag" (priority [tr]) (fn () => command tr st); st)) ()
   729           else command tr st;
   730       in ((tr, st'), st') end;
   731 
   732     val proof_trs =
   733       (case opt_proof of
   734         NONE => []
   735       | SOME (a, b) => (maps Thy_Syntax.flat_element a @ [b]) |> filter_out is_ignored);
   736 
   737     val (_, st') = atom_result head_tr st;
   738   in
   739     if not (Goal.future_enabled ()) orelse is_ignored head_tr orelse
   740       null proof_trs orelse not (can proof_of st') orelse Proof.is_relevant (proof_of st')
   741     then
   742       let val (results, st'') = fold_map atom_result proof_trs st'
   743       in (Future.value (if is_ignored head_tr then results else (head_tr, st') :: results), st'') end
   744     else
   745       let
   746         val (body_trs, end_tr) = split_last proof_trs;
   747         val finish = Context.Theory o Proof_Context.theory_of;
   748 
   749         val future_proof = Proof.global_future_proof
   750           (fn prf =>
   751             setmp_thread_position head_tr (fn () =>
   752               Goal.fork_name "Toplevel.future_proof" (priority proof_trs)
   753                 (fn () =>
   754                   let val (result, result_state) =
   755                     (case st' of State (SOME (Proof (_, (_, orig_gthy))), prev)
   756                       => State (SOME (Proof (Proof_Node.init prf, (finish, orig_gthy))), prev))
   757                     |> fold_map atom_result body_trs ||> command end_tr;
   758                   in (result, presentation_context_of result_state) end)) ())
   759           #-> Result.put;
   760 
   761         val st'' = st'
   762           |> command (head_tr |> set_print false |> reset_trans |> end_proof (K future_proof));
   763         val result =
   764           Result.get (presentation_context_of st'')
   765           |> Future.map (fn body => (head_tr, st') :: body @ [(end_tr, st'')]);
   766 
   767       in (result, st'') end
   768   end;
   769 
   770 end;