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