src/Pure/Isar/toplevel.ML
author wenzelm
Wed Mar 27 16:38:25 2013 +0100 (2013-03-27 ago)
changeset 51553 63327f679cff
parent 51423 e5f9a6d9ca82
child 51555 6aa64925db77
permissions -rw-r--r--
more ambitious Goal.skip_proofs: covers Goal.prove forms as well, and do not insist in quick_and_dirty (for the sake of Isabelle/jEdit);
     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 program: (unit -> 'a) -> 'a
    33   val thread: bool -> (unit -> unit) -> Thread.thread
    34   type transition
    35   val empty: transition
    36   val print_of: transition -> bool
    37   val name_of: transition -> string
    38   val pos_of: transition -> Position.T
    39   val name: string -> transition -> transition
    40   val position: Position.T -> transition -> transition
    41   val interactive: bool -> transition -> transition
    42   val set_print: bool -> transition -> transition
    43   val print: transition -> transition
    44   val no_timing: 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 approximative_id: transition -> {file: string, offset: int, name: string} option
    93   val get_timing: transition -> Time.time option
    94   val put_timing: Time.time option -> transition -> transition
    95   val transition: bool -> transition -> state -> (state * (exn * string) option) option
    96   val command_errors: bool -> transition -> state -> Runtime.error list * state option
    97   val command_exception: bool -> transition -> state -> state
    98   type result
    99   val join_results: result -> (transition * state) list
   100   val element_result: transition Thy_Syntax.element -> state -> result * 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 
   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   no_timing: bool,           (*suppress timing*)
   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, no_timing, timing, trans) =
   351   Transition {name = name, pos = pos, int_only = int_only, print = print,
   352     no_timing = no_timing, timing = timing, trans = trans};
   353 
   354 fun map_transition f (Transition {name, pos, int_only, print, no_timing, timing, trans}) =
   355   make_transition (f (name, pos, int_only, print, no_timing, timing, trans));
   356 
   357 val empty = make_transition ("", Position.none, false, 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, no_timing, timing, trans) =>
   376   (name, pos, int_only, print, no_timing, timing, trans));
   377 
   378 fun position pos = map_transition (fn (name, _, int_only, print, no_timing, timing, trans) =>
   379   (name, pos, int_only, print, no_timing, timing, trans));
   380 
   381 fun interactive int_only = map_transition (fn (name, pos, _, print, no_timing, timing, trans) =>
   382   (name, pos, int_only, print, no_timing, timing, trans));
   383 
   384 val no_timing = map_transition (fn (name, pos, int_only, print, _, timing, trans) =>
   385   (name, pos, int_only, print, true, timing, trans));
   386 
   387 fun add_trans tr = map_transition (fn (name, pos, int_only, print, no_timing, timing, trans) =>
   388   (name, pos, int_only, print, no_timing, timing, tr :: trans));
   389 
   390 val reset_trans = map_transition (fn (name, pos, int_only, print, no_timing, timing, _) =>
   391   (name, pos, int_only, print, no_timing, timing, []));
   392 
   393 fun set_print print = map_transition (fn (name, pos, int_only, _, no_timing, timing, trans) =>
   394   (name, pos, int_only, print, no_timing, timing, trans));
   395 
   396 val print = set_print true;
   397 
   398 
   399 (* basic transitions *)
   400 
   401 fun init_theory f = add_trans (Init f);
   402 
   403 fun is_init (Transition {trans = [Init _], ...}) = true
   404   | is_init _ = false;
   405 
   406 fun modify_init f tr = if is_init tr then init_theory f (reset_trans tr) else tr;
   407 
   408 val exit = add_trans Exit;
   409 val keep' = add_trans o Keep;
   410 
   411 fun present_transaction f g = add_trans (Transaction (f, g));
   412 fun transaction f = present_transaction f (K ());
   413 
   414 fun keep f = add_trans (Keep (fn _ => f));
   415 fun imperative f = keep (fn _ => f ());
   416 
   417 fun ignored pos = empty |> name "<ignored>" |> position pos |> imperative I;
   418 fun is_ignored tr = name_of tr = "<ignored>";
   419 
   420 val malformed_name = "<malformed>";
   421 fun malformed pos msg =
   422   empty |> name malformed_name |> position pos |> imperative (fn () => error msg);
   423 fun is_malformed tr = name_of tr = malformed_name;
   424 
   425 val unknown_theory = imperative (fn () => warning "Unknown theory context");
   426 val unknown_proof = imperative (fn () => warning "Unknown proof context");
   427 val unknown_context = imperative (fn () => warning "Unknown context");
   428 
   429 
   430 (* theory transitions *)
   431 
   432 fun generic_theory f = transaction (fn _ =>
   433   (fn Theory (gthy, _) => Theory (f gthy, NONE)
   434     | _ => raise UNDEF));
   435 
   436 fun theory' f = transaction (fn int =>
   437   (fn Theory (Context.Theory thy, _) =>
   438       let val thy' = thy
   439         |> Sign.new_group
   440         |> Theory.checkpoint
   441         |> f int
   442         |> Sign.reset_group;
   443       in Theory (Context.Theory thy', NONE) end
   444     | _ => raise UNDEF));
   445 
   446 fun theory f = theory' (K f);
   447 
   448 fun begin_local_theory begin f = transaction (fn _ =>
   449   (fn Theory (Context.Theory thy, _) =>
   450         let
   451           val lthy = f thy;
   452           val gthy = if begin then Context.Proof lthy else Context.Theory (loc_exit lthy);
   453         in Theory (gthy, SOME lthy) end
   454     | _ => raise UNDEF));
   455 
   456 val end_local_theory = transaction (fn _ =>
   457   (fn Theory (Context.Proof lthy, _) => Theory (Context.Theory (loc_exit lthy), SOME lthy)
   458     | _ => raise UNDEF));
   459 
   460 fun open_target f = transaction (fn _ =>
   461   (fn Theory (gthy, _) =>
   462         let val lthy = f gthy
   463         in Theory (Context.Proof lthy, SOME lthy) end
   464     | _ => raise UNDEF));
   465 
   466 val close_target = transaction (fn _ =>
   467   (fn Theory (Context.Proof lthy, _) =>
   468         (case try Local_Theory.close_target lthy of
   469           SOME ctxt' =>
   470             let
   471               val gthy' =
   472                 if can Local_Theory.assert ctxt'
   473                 then Context.Proof ctxt'
   474                 else Context.Theory (Proof_Context.theory_of ctxt');
   475             in Theory (gthy', SOME lthy) end
   476         | NONE => raise UNDEF)
   477     | _ => raise UNDEF));
   478 
   479 
   480 local
   481 
   482 fun local_theory_presentation loc f = present_transaction (fn int =>
   483   (fn Theory (gthy, _) =>
   484         let
   485           val (finish, lthy) = loc_begin loc gthy;
   486           val lthy' = lthy
   487             |> Local_Theory.new_group
   488             |> f int
   489             |> Local_Theory.reset_group;
   490         in Theory (finish lthy', SOME lthy') end
   491     | _ => raise UNDEF));
   492 
   493 in
   494 
   495 fun local_theory' loc f = local_theory_presentation loc f (K ());
   496 fun local_theory loc f = local_theory' loc (K f);
   497 fun present_local_theory loc = local_theory_presentation loc (K I);
   498 
   499 end;
   500 
   501 
   502 (* proof transitions *)
   503 
   504 fun end_proof f = transaction (fn int =>
   505   (fn Proof (prf, (finish, _)) =>
   506         let val state = Proof_Node.current prf in
   507           if can (Proof.assert_bottom true) state then
   508             let
   509               val ctxt' = f int state;
   510               val gthy' = finish ctxt';
   511             in Theory (gthy', SOME ctxt') end
   512           else raise UNDEF
   513         end
   514     | SkipProof (0, (gthy, _)) => Theory (gthy, NONE)
   515     | _ => raise UNDEF));
   516 
   517 local
   518 
   519 fun begin_proof init = transaction (fn int =>
   520   (fn Theory (gthy, _) =>
   521     let
   522       val (finish, prf) = init int gthy;
   523       val skip = ! Goal.skip_proofs;
   524       val (is_goal, no_skip) =
   525         (true, Proof.schematic_goal prf) handle ERROR _ => (false, true);
   526       val _ =
   527         if is_goal andalso skip andalso no_skip then
   528           warning "Cannot skip proof of schematic goal statement"
   529         else ();
   530     in
   531       if skip andalso not no_skip then
   532         SkipProof (0, (finish (Proof.global_skip_proof true prf), gthy))
   533       else Proof (Proof_Node.init prf, (finish, gthy))
   534     end
   535   | _ => raise UNDEF));
   536 
   537 in
   538 
   539 fun local_theory_to_proof' loc f = begin_proof
   540   (fn int => fn gthy =>
   541     let val (finish, lthy) = loc_begin loc gthy
   542     in (finish o Local_Theory.reset_group, f int (Local_Theory.new_group lthy)) end);
   543 
   544 fun local_theory_to_proof loc f = local_theory_to_proof' loc (K f);
   545 
   546 fun theory_to_proof f = begin_proof
   547   (fn _ => fn gthy =>
   548     (Context.Theory o Sign.reset_group o Proof_Context.theory_of,
   549       (case gthy of
   550         Context.Theory thy => f (Theory.checkpoint (Sign.new_group thy))
   551       | _ => raise UNDEF)));
   552 
   553 end;
   554 
   555 val forget_proof = transaction (fn _ =>
   556   (fn Proof (_, (_, orig_gthy)) => Theory (orig_gthy, NONE)
   557     | SkipProof (_, (_, orig_gthy)) => Theory (orig_gthy, NONE)
   558     | _ => raise UNDEF));
   559 
   560 val present_proof = present_transaction (fn _ =>
   561   (fn Proof (prf, x) => Proof (Proof_Node.apply I prf, x)
   562     | skip as SkipProof _ => skip
   563     | _ => raise UNDEF));
   564 
   565 fun proofs' f = transaction (fn int =>
   566   (fn Proof (prf, x) => Proof (Proof_Node.applys (f int) prf, x)
   567     | skip as SkipProof _ => skip
   568     | _ => raise UNDEF));
   569 
   570 fun proof' f = proofs' ((Seq.single o Seq.Result) oo f);
   571 val proofs = proofs' o K;
   572 val proof = proof' o K;
   573 
   574 fun actual_proof f = transaction (fn _ =>
   575   (fn Proof (prf, x) => Proof (f prf, x)
   576     | _ => raise UNDEF));
   577 
   578 fun skip_proof f = transaction (fn _ =>
   579   (fn SkipProof (h, x) => SkipProof (f h, x)
   580     | _ => raise UNDEF));
   581 
   582 fun skip_proof_to_theory pred = transaction (fn _ =>
   583   (fn SkipProof (d, (gthy, _)) => if pred d then Theory (gthy, NONE) else raise UNDEF
   584     | _ => raise UNDEF));
   585 
   586 
   587 
   588 (** toplevel transactions **)
   589 
   590 (* identification *)
   591 
   592 fun get_id (Transition {pos, ...}) = Position.get_id pos;
   593 fun put_id id (tr as Transition {pos, ...}) = position (Position.put_id id pos) tr;
   594 
   595 
   596 (* approximative identification within source file *)
   597 
   598 fun approximative_id tr =
   599   let
   600     val name = name_of tr;
   601     val pos = pos_of tr;
   602   in
   603     (case (Position.file_of pos, Position.offset_of pos) of
   604       (SOME file, SOME offset) => SOME {file = file, offset = offset, name = name}
   605     | _ => NONE)
   606   end;
   607 
   608 
   609 (* thread position *)
   610 
   611 fun setmp_thread_position (Transition {pos, ...}) f x =
   612   Position.setmp_thread_data pos f x;
   613 
   614 fun status tr m =
   615   setmp_thread_position tr (fn () => Output.status (Markup.markup_only m)) ();
   616 
   617 
   618 (* post-transition hooks *)
   619 
   620 local
   621   val hooks = Unsynchronized.ref ([]: (transition -> state -> state -> unit) list);
   622 in
   623 
   624 fun add_hook f = CRITICAL (fn () => Unsynchronized.change hooks (cons f));
   625 fun get_hooks () = ! hooks;
   626 
   627 end;
   628 
   629 
   630 (* apply transitions *)
   631 
   632 fun get_timing (Transition {timing, ...}) = timing;
   633 fun put_timing timing = map_transition (fn (name, pos, int_only, print, no_timing, _, trans) =>
   634   (name, pos, int_only, print, no_timing, timing, trans));
   635 
   636 local
   637 
   638 fun timing_message tr (t: Timing.timing) =
   639   (case approximative_id tr of
   640     SOME id =>
   641       (Output.protocol_message
   642         (Markup.command_timing :: Markup.command_timing_properties id (#elapsed t)) ""
   643       handle Fail _ => ())
   644   | NONE => ());
   645 
   646 fun app int (tr as Transition {trans, print, no_timing, ...}) =
   647   setmp_thread_position tr (fn state =>
   648     let
   649       fun do_timing f x = (warning (command_msg "" tr); timeap f x);
   650       fun do_profiling f x = profile (! profiling) f x;
   651 
   652       val start = Timing.start ();
   653 
   654       val (result, status) =
   655          state |>
   656           (apply_trans int trans
   657             |> (! profiling > 0 andalso not no_timing) ? do_profiling
   658             |> (! profiling > 0 orelse ! timing andalso not no_timing) ? do_timing);
   659 
   660       val _ = if int andalso not (! quiet) andalso print then print_state false result else ();
   661 
   662       val _ = timing_message tr (Timing.result start);
   663     in (result, Option.map (fn UNDEF => type_error tr state | exn => exn) status) end);
   664 
   665 in
   666 
   667 fun transition int tr st =
   668   let
   669     val hooks = get_hooks ();
   670     fun apply_hooks st' = hooks |> List.app (fn f => (try (fn () => f tr st st') (); ()));
   671 
   672     val ctxt = try context_of st;
   673     val res =
   674       (case app int tr st of
   675         (_, SOME Runtime.TERMINATE) => NONE
   676       | (st', SOME (Runtime.EXCURSION_FAIL exn_info)) => SOME (st', SOME exn_info)
   677       | (st', SOME exn) => SOME (st', SOME (Runtime.exn_context ctxt exn, at_command tr))
   678       | (st', NONE) => SOME (st', NONE));
   679     val _ = (case res of SOME (st', NONE) => apply_hooks st' | _ => ());
   680   in res end;
   681 
   682 end;
   683 
   684 
   685 (* managed commands *)
   686 
   687 fun command_errors int tr st =
   688   (case transition int tr st of
   689     SOME (st', NONE) => ([], SOME st')
   690   | SOME (_, SOME (exn, _)) => (ML_Compiler.exn_messages_ids exn, NONE)
   691   | NONE => (ML_Compiler.exn_messages_ids Runtime.TERMINATE, NONE));
   692 
   693 fun command_exception int tr st =
   694   (case transition int tr st of
   695     SOME (st', NONE) => st'
   696   | SOME (_, SOME (exn, info)) =>
   697       if Exn.is_interrupt exn then reraise exn else raise Runtime.EXCURSION_FAIL (exn, info)
   698   | NONE => raise Runtime.EXCURSION_FAIL (Runtime.TERMINATE, at_command tr));
   699 
   700 fun command tr = command_exception (! interact) tr;
   701 
   702 
   703 (* scheduled proof result *)
   704 
   705 datatype result =
   706   Result of transition * state |
   707   Result_List of result list |
   708   Result_Future of result future;
   709 
   710 fun join_results (Result x) = [x]
   711   | join_results (Result_List xs) = maps join_results xs
   712   | join_results (Result_Future x) = join_results (Future.join x);
   713 
   714 local
   715 
   716 structure Result = Proof_Data
   717 (
   718   type T = result;
   719   val empty: T = Result_List [];
   720   fun init _ = empty;
   721 );
   722 
   723 val get_result = Result.get o Proof.context_of;
   724 val put_result = Proof.map_context o Result.put;
   725 
   726 fun timing_estimate include_head elem =
   727   let
   728     val trs = Thy_Syntax.flat_element elem |> not include_head ? tl;
   729     val timings = map get_timing trs;
   730   in
   731     if forall is_some timings then
   732       SOME (fold (curry Time.+ o the) timings Time.zeroTime)
   733     else NONE
   734   end;
   735 
   736 fun priority NONE = ~1
   737   | priority (SOME estimate) =
   738       Int.min (Real.floor (Real.max (Math.log10 (Time.toReal estimate), ~3.0)) - 3, ~1);
   739 
   740 fun proof_future_enabled estimate st =
   741   (case try proof_of st of
   742     NONE => false
   743   | SOME state =>
   744       not (Proof.is_relevant state) andalso
   745        (if can (Proof.assert_bottom true) state
   746         then Goal.future_enabled ()
   747         else
   748           (case estimate of
   749             NONE => Goal.future_enabled_nested 2
   750           | SOME t => Goal.future_enabled_timing t)));
   751 
   752 fun atom_result tr st =
   753   let
   754     val st' =
   755       if Goal.future_enabled () andalso Keyword.is_diag (name_of tr) then
   756         setmp_thread_position tr (fn () =>
   757           (Goal.fork_name "Toplevel.diag" (priority (timing_estimate true (Thy_Syntax.atom tr)))
   758             (fn () => command tr st); st)) ()
   759       else command tr st;
   760   in (Result (tr, st'), st') end;
   761 
   762 in
   763 
   764 fun element_result (Thy_Syntax.Element (tr, NONE)) st = atom_result tr st
   765   | element_result (elem as Thy_Syntax.Element (head_tr, SOME element_rest)) st =
   766       let
   767         val (head_result, st') = atom_result head_tr st;
   768         val (body_elems, end_tr) = element_rest;
   769         val estimate = timing_estimate false elem;
   770       in
   771         if not (proof_future_enabled estimate st')
   772         then
   773           let
   774             val proof_trs = maps Thy_Syntax.flat_element body_elems @ [end_tr];
   775             val (proof_results, st'') = fold_map atom_result proof_trs st';
   776           in (Result_List (head_result :: proof_results), st'') end
   777         else
   778           let
   779             val finish = Context.Theory o Proof_Context.theory_of;
   780 
   781             val future_proof = Proof.future_proof
   782               (fn state =>
   783                 setmp_thread_position head_tr (fn () =>
   784                   Goal.fork_name "Toplevel.future_proof"
   785                     (priority estimate)
   786                     (fn () =>
   787                       let
   788                         val State (SOME (Proof (prf, (_, orig_gthy))), prev) = st';
   789                         val prf' = Proof_Node.apply (K state) prf;
   790                         val (result, result_state) =
   791                           State (SOME (Proof (prf', (finish, orig_gthy))), prev)
   792                           |> fold_map element_result body_elems ||> command end_tr;
   793                       in (Result_List result, presentation_context_of result_state) end)) ())
   794               #> (fn (res, state') => state' |> put_result (Result_Future res));
   795 
   796             val forked_proof =
   797               proof (future_proof #>
   798                 (fn state => state |> Proof.local_done_proof |> put_result (get_result state))) o
   799               end_proof (fn _ => future_proof #>
   800                 (fn state => state |> Proof.global_done_proof |> Result.put (get_result state)));
   801 
   802             val st'' = st'
   803               |> command (head_tr |> set_print false |> reset_trans |> forked_proof);
   804             val end_result = Result (end_tr, st'');
   805             val result =
   806               Result_List [head_result, Result.get (presentation_context_of st''), end_result];
   807           in (result, st'') end
   808       end;
   809 
   810 end;
   811 
   812 end;