src/Pure/Isar/toplevel.ML
author wenzelm
Mon Nov 28 22:05:32 2011 +0100 (2011-11-28 ago)
changeset 45666 d83797ef0d2d
parent 45488 6d71d9e52369
child 46959 cdc791910460
permissions -rw-r--r--
separate module for concrete Isabelle markup;
     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 str_of: transition -> string
    41   val name: string -> transition -> transition
    42   val position: Position.T -> transition -> transition
    43   val interactive: bool -> transition -> transition
    44   val set_print: bool -> transition -> transition
    45   val print: transition -> transition
    46   val no_timing: transition -> transition
    47   val init_theory: (unit -> theory) -> transition -> transition
    48   val is_init: transition -> bool
    49   val modify_init: (unit -> theory) -> transition -> transition
    50   val exit: transition -> transition
    51   val keep: (state -> unit) -> transition -> transition
    52   val keep': (bool -> state -> unit) -> transition -> transition
    53   val imperative: (unit -> unit) -> transition -> transition
    54   val ignored: Position.T -> transition
    55   val malformed: Position.T -> string -> transition
    56   val theory: (theory -> theory) -> transition -> transition
    57   val generic_theory: (generic_theory -> generic_theory) -> transition -> transition
    58   val theory': (bool -> theory -> theory) -> transition -> transition
    59   val begin_local_theory: bool -> (theory -> local_theory) -> transition -> transition
    60   val end_local_theory: transition -> transition
    61   val local_theory': (xstring * Position.T) option -> (bool -> local_theory -> local_theory) ->
    62     transition -> transition
    63   val local_theory: (xstring * Position.T) option -> (local_theory -> local_theory) ->
    64     transition -> transition
    65   val present_local_theory: (xstring * Position.T) option -> (state -> unit) ->
    66     transition -> transition
    67   val local_theory_to_proof': (xstring * Position.T) option ->
    68     (bool -> local_theory -> Proof.state) -> transition -> transition
    69   val local_theory_to_proof: (xstring * Position.T) option ->
    70     (local_theory -> Proof.state) -> transition -> transition
    71   val theory_to_proof: (theory -> Proof.state) -> transition -> transition
    72   val end_proof: (bool -> Proof.state -> Proof.context) -> transition -> transition
    73   val forget_proof: transition -> transition
    74   val present_proof: (state -> unit) -> transition -> transition
    75   val proofs': (bool -> Proof.state -> Proof.state Seq.seq) -> transition -> transition
    76   val proof': (bool -> Proof.state -> Proof.state) -> transition -> transition
    77   val proofs: (Proof.state -> Proof.state Seq.seq) -> transition -> transition
    78   val proof: (Proof.state -> Proof.state) -> transition -> transition
    79   val actual_proof: (Proof_Node.T -> Proof_Node.T) -> transition -> transition
    80   val skip_proof: (int -> int) -> transition -> transition
    81   val skip_proof_to_theory: (int -> bool) -> transition -> transition
    82   val get_id: transition -> string option
    83   val put_id: string -> transition -> transition
    84   val unknown_theory: transition -> transition
    85   val unknown_proof: transition -> transition
    86   val unknown_context: transition -> transition
    87   val setmp_thread_position: transition -> ('a -> 'b) -> 'a -> 'b
    88   val status: transition -> Markup.T -> unit
    89   val error_msg: transition -> serial * string -> unit
    90   val add_hook: (transition -> state -> state -> unit) -> unit
    91   val transition: bool -> transition -> state -> (state * (exn * string) option) option
    92   val command: transition -> state -> state
    93   val excursion:
    94     (transition * transition list) list -> (transition * state) list future list * theory
    95 end;
    96 
    97 structure Toplevel: TOPLEVEL =
    98 struct
    99 
   100 (** toplevel state **)
   101 
   102 exception UNDEF = Runtime.UNDEF;
   103 
   104 
   105 (* local theory wrappers *)
   106 
   107 val loc_init = Named_Target.context_cmd;
   108 val loc_exit = Local_Theory.exit_global;
   109 
   110 fun loc_begin loc (Context.Theory thy) = loc_init (the_default ("-", Position.none) loc) thy
   111   | loc_begin NONE (Context.Proof lthy) = lthy
   112   | loc_begin (SOME loc) (Context.Proof lthy) = (loc_init loc o loc_exit) lthy;
   113 
   114 fun loc_finish _ (Context.Theory _) = Context.Theory o loc_exit
   115   | loc_finish NONE (Context.Proof _) = Context.Proof o Local_Theory.restore
   116   | loc_finish (SOME _) (Context.Proof lthy) = Context.Proof o Named_Target.reinit lthy;
   117 
   118 
   119 (* datatype node *)
   120 
   121 datatype node =
   122   Theory of generic_theory * Proof.context option
   123     (*theory with presentation context*) |
   124   Proof of Proof_Node.T * ((Proof.context -> generic_theory) * generic_theory)
   125     (*proof node, finish, original theory*) |
   126   SkipProof of int * (generic_theory * generic_theory);
   127     (*proof depth, resulting theory, original theory*)
   128 
   129 val theory_node = fn Theory (gthy, _) => SOME gthy | _ => NONE;
   130 val proof_node = fn Proof (prf, _) => SOME prf | _ => NONE;
   131 
   132 fun cases_node f _ (Theory (gthy, _)) = f gthy
   133   | cases_node _ g (Proof (prf, _)) = g (Proof_Node.current prf)
   134   | cases_node f _ (SkipProof (_, (gthy, _))) = f gthy;
   135 
   136 val context_node = cases_node Context.proof_of Proof.context_of;
   137 
   138 
   139 (* datatype state *)
   140 
   141 datatype state = State of node option * node option;  (*current, previous*)
   142 
   143 val toplevel = State (NONE, NONE);
   144 
   145 fun is_toplevel (State (NONE, _)) = true
   146   | is_toplevel _ = false;
   147 
   148 fun level (State (NONE, _)) = 0
   149   | level (State (SOME (Theory _), _)) = 0
   150   | level (State (SOME (Proof (prf, _)), _)) = Proof.level (Proof_Node.current prf)
   151   | level (State (SOME (SkipProof (d, _)), _)) = d + 1;   (*different notion of proof depth!*)
   152 
   153 fun str_of_state (State (NONE, _)) = "at top level"
   154   | str_of_state (State (SOME (Theory (Context.Theory _, _)), _)) = "in theory mode"
   155   | str_of_state (State (SOME (Theory (Context.Proof _, _)), _)) = "in local theory mode"
   156   | str_of_state (State (SOME (Proof _), _)) = "in proof mode"
   157   | str_of_state (State (SOME (SkipProof _), _)) = "in skipped proof mode";
   158 
   159 
   160 (* current node *)
   161 
   162 fun node_of (State (NONE, _)) = raise UNDEF
   163   | node_of (State (SOME node, _)) = node;
   164 
   165 fun is_theory state = not (is_toplevel state) andalso is_some (theory_node (node_of state));
   166 fun is_proof state = not (is_toplevel state) andalso is_some (proof_node (node_of state));
   167 
   168 fun node_case f g state = cases_node f g (node_of state);
   169 
   170 fun presentation_context_of state =
   171   (case try node_of state of
   172     SOME (Theory (_, SOME ctxt)) => ctxt
   173   | SOME node => context_node node
   174   | NONE => raise UNDEF);
   175 
   176 fun previous_context_of (State (_, NONE)) = NONE
   177   | previous_context_of (State (_, SOME prev)) = SOME (context_node prev);
   178 
   179 val context_of = node_case Context.proof_of Proof.context_of;
   180 val generic_theory_of = node_case I (Context.Proof o Proof.context_of);
   181 val theory_of = node_case Context.theory_of Proof.theory_of;
   182 val proof_of = node_case (fn _ => raise UNDEF) I;
   183 
   184 fun proof_position_of state =
   185   (case node_of state of
   186     Proof (prf, _) => Proof_Node.position prf
   187   | _ => raise UNDEF);
   188 
   189 fun end_theory _ (State (NONE, SOME (Theory (Context.Theory thy, _)))) = thy
   190   | end_theory pos (State (NONE, _)) = error ("Missing theory" ^ Position.str_of pos)
   191   | end_theory pos (State (SOME _, _)) = error ("Unfinished theory" ^ Position.str_of pos);
   192 
   193 
   194 (* print state *)
   195 
   196 val pretty_context = Local_Theory.pretty o Context.cases (Named_Target.theory_init) I;
   197 
   198 fun print_state_context state =
   199   (case try node_of state of
   200     NONE => []
   201   | SOME (Theory (gthy, _)) => pretty_context gthy
   202   | SOME (Proof (_, (_, gthy))) => pretty_context gthy
   203   | SOME (SkipProof (_, (gthy, _))) => pretty_context gthy)
   204   |> Pretty.chunks |> Pretty.writeln;
   205 
   206 fun print_state prf_only state =
   207   (case try node_of state of
   208     NONE => []
   209   | SOME (Theory (gthy, _)) => if prf_only then [] else pretty_context gthy
   210   | SOME (Proof (prf, _)) =>
   211       Proof.pretty_state (Proof_Node.position prf) (Proof_Node.current prf)
   212   | SOME (SkipProof (d, _)) => [Pretty.str ("skipped proof: depth " ^ string_of_int d)])
   213   |> Pretty.markup_chunks Isabelle_Markup.state |> Pretty.writeln;
   214 
   215 fun pretty_abstract state = Pretty.str ("<Isar " ^ str_of_state state ^ ">");
   216 
   217 
   218 
   219 (** toplevel transitions **)
   220 
   221 val quiet = Unsynchronized.ref false;
   222 val debug = Runtime.debug;
   223 val interact = Unsynchronized.ref false;
   224 val timing = Unsynchronized.ref false;
   225 val profiling = Unsynchronized.ref 0;
   226 val skip_proofs = Unsynchronized.ref false;
   227 
   228 fun program body =
   229  (body
   230   |> Runtime.controlled_execution
   231   |> Runtime.toplevel_error (Output.error_msg o ML_Compiler.exn_message)) ();
   232 
   233 fun thread interrupts body =
   234   Thread.fork
   235     (((fn () => body () handle exn => if Exn.is_interrupt exn then () else reraise exn)
   236         |> Runtime.debugging
   237         |> Runtime.toplevel_error
   238           (fn exn =>
   239             Output.urgent_message ("## INTERNAL ERROR ##\n" ^ ML_Compiler.exn_message exn))),
   240       Simple_Thread.attributes interrupts);
   241 
   242 
   243 (* node transactions -- maintaining stable checkpoints *)
   244 
   245 exception FAILURE of state * exn;
   246 
   247 local
   248 
   249 fun reset_presentation (Theory (gthy, _)) = Theory (gthy, NONE)
   250   | reset_presentation node = node;
   251 
   252 fun is_draft_theory (Theory (gthy, _)) = Context.is_draft (Context.theory_of gthy)
   253   | is_draft_theory _ = false;
   254 
   255 fun is_stale state = Context.is_stale (theory_of state) handle Runtime.UNDEF => false;
   256 
   257 fun stale_error NONE = SOME (ERROR "Stale theory encountered after successful execution!")
   258   | stale_error some = some;
   259 
   260 fun map_theory f (Theory (gthy, ctxt)) =
   261       Theory (Context.mapping f (Local_Theory.raw_theory f) gthy, ctxt)
   262   | map_theory _ node = node;
   263 
   264 in
   265 
   266 fun apply_transaction f g node =
   267   let
   268     val _ = is_draft_theory node andalso error "Illegal draft theory in toplevel state";
   269     val cont_node = reset_presentation node;
   270     val back_node = map_theory (Theory.checkpoint o Theory.copy) cont_node;
   271     fun state_error e nd = (State (SOME nd, SOME node), e);
   272 
   273     val (result, err) =
   274       cont_node
   275       |> Runtime.controlled_execution f
   276       |> map_theory Theory.checkpoint
   277       |> state_error NONE
   278       handle exn => state_error (SOME exn) cont_node;
   279 
   280     val (result', err') =
   281       if is_stale result then state_error (stale_error err) back_node
   282       else (result, err);
   283   in
   284     (case err' of
   285       NONE => tap g result'
   286     | SOME exn => raise FAILURE (result', exn))
   287   end;
   288 
   289 val exit_transaction =
   290   apply_transaction
   291     (fn Theory (Context.Theory thy, _) => Theory (Context.Theory (Theory.end_theory thy), NONE)
   292       | node => node) (K ())
   293   #> (fn State (node', _) => State (NONE, node'));
   294 
   295 end;
   296 
   297 
   298 (* primitive transitions *)
   299 
   300 datatype trans =
   301   Init of unit -> theory |               (*init theory*)
   302   Exit |                                 (*formal exit of theory*)
   303   Keep of bool -> state -> unit |        (*peek at state*)
   304   Transaction of (bool -> node -> node) * (state -> unit);  (*node transaction and presentation*)
   305 
   306 local
   307 
   308 fun apply_tr _ (Init f) (State (NONE, _)) =
   309       State (SOME (Theory (Context.Theory
   310           (Theory.checkpoint (Runtime.controlled_execution f ())), NONE)), NONE)
   311   | apply_tr _ Exit (State (SOME (state as Theory (Context.Theory _, _)), _)) =
   312       exit_transaction state
   313   | apply_tr int (Keep f) state =
   314       Runtime.controlled_execution (fn x => tap (f int) x) state
   315   | apply_tr int (Transaction (f, g)) (State (SOME state, _)) =
   316       apply_transaction (fn x => f int x) g state
   317   | apply_tr _ _ _ = raise UNDEF;
   318 
   319 fun apply_union _ [] state = raise FAILURE (state, UNDEF)
   320   | apply_union int (tr :: trs) state =
   321       apply_union int trs state
   322         handle Runtime.UNDEF => apply_tr int tr state
   323           | FAILURE (alt_state, UNDEF) => apply_tr int tr alt_state
   324           | exn as FAILURE _ => raise exn
   325           | exn => raise FAILURE (state, exn);
   326 
   327 in
   328 
   329 fun apply_trans int trs state = (apply_union int trs state, NONE)
   330   handle FAILURE (alt_state, exn) => (alt_state, SOME exn) | exn => (state, SOME exn);
   331 
   332 end;
   333 
   334 
   335 (* datatype transition *)
   336 
   337 datatype transition = Transition of
   338  {name: string,              (*command name*)
   339   pos: Position.T,           (*source position*)
   340   int_only: bool,            (*interactive-only*)
   341   print: bool,               (*print result state*)
   342   no_timing: bool,           (*suppress timing*)
   343   trans: trans list};        (*primitive transitions (union)*)
   344 
   345 fun make_transition (name, pos, int_only, print, no_timing, trans) =
   346   Transition {name = name, pos = pos, int_only = int_only, print = print, no_timing = no_timing,
   347     trans = trans};
   348 
   349 fun map_transition f (Transition {name, pos, int_only, print, no_timing, trans}) =
   350   make_transition (f (name, pos, int_only, print, no_timing, trans));
   351 
   352 val empty = make_transition ("", Position.none, false, false, false, []);
   353 
   354 
   355 (* diagnostics *)
   356 
   357 fun print_of (Transition {print, ...}) = print;
   358 fun name_of (Transition {name, ...}) = name;
   359 fun pos_of (Transition {pos, ...}) = pos;
   360 fun str_of tr = quote (name_of tr) ^ Position.str_of (pos_of tr);
   361 
   362 fun command_msg msg tr = msg ^ "command " ^ str_of tr;
   363 fun at_command tr = command_msg "At " tr;
   364 
   365 fun type_error tr state =
   366   ERROR (command_msg "Illegal application of " tr ^ " " ^ str_of_state state);
   367 
   368 
   369 (* modify transitions *)
   370 
   371 fun name name = map_transition (fn (_, pos, int_only, print, no_timing, trans) =>
   372   (name, pos, int_only, print, no_timing, trans));
   373 
   374 fun position pos = map_transition (fn (name, _, int_only, print, no_timing, trans) =>
   375   (name, pos, int_only, print, no_timing, trans));
   376 
   377 fun interactive int_only = map_transition (fn (name, pos, _, print, no_timing, trans) =>
   378   (name, pos, int_only, print, no_timing, trans));
   379 
   380 val no_timing = map_transition (fn (name, pos, int_only, print, _, trans) =>
   381   (name, pos, int_only, print, true, trans));
   382 
   383 fun add_trans tr = map_transition (fn (name, pos, int_only, print, no_timing, trans) =>
   384   (name, pos, int_only, print, no_timing, tr :: trans));
   385 
   386 val reset_trans = map_transition (fn (name, pos, int_only, print, no_timing, _) =>
   387   (name, pos, int_only, print, no_timing, []));
   388 
   389 fun set_print print = map_transition (fn (name, pos, int_only, _, no_timing, trans) =>
   390   (name, pos, int_only, print, no_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 malformed pos msg =
   415   empty |> name "<malformed>" |> position pos |> imperative (fn () => error msg);
   416 
   417 val unknown_theory = imperative (fn () => warning "Unknown theory context");
   418 val unknown_proof = imperative (fn () => warning "Unknown proof context");
   419 val unknown_context = imperative (fn () => warning "Unknown context");
   420 
   421 
   422 (* theory transitions *)
   423 
   424 val global_theory_group =
   425   Sign.new_group #>
   426   Global_Theory.begin_recent_proofs #> Theory.checkpoint;
   427 
   428 val local_theory_group =
   429   Local_Theory.new_group #>
   430   Local_Theory.raw_theory (Global_Theory.begin_recent_proofs #> Theory.checkpoint);
   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         |> global_theory_group
   440         |> f int
   441         |> Sign.reset_group;
   442       in Theory (Context.Theory thy', NONE) end
   443     | _ => raise UNDEF));
   444 
   445 fun theory f = theory' (K f);
   446 
   447 fun begin_local_theory begin f = transaction (fn _ =>
   448   (fn Theory (Context.Theory thy, _) =>
   449         let
   450           val lthy = f thy;
   451           val gthy = if begin then Context.Proof lthy else Context.Theory (loc_exit lthy);
   452         in Theory (gthy, SOME lthy) end
   453     | _ => raise UNDEF));
   454 
   455 val end_local_theory = transaction (fn _ =>
   456   (fn Theory (Context.Proof lthy, _) => Theory (Context.Theory (loc_exit lthy), SOME lthy)
   457     | _ => raise UNDEF));
   458 
   459 local
   460 
   461 fun local_theory_presentation loc f = present_transaction (fn int =>
   462   (fn Theory (gthy, _) =>
   463         let
   464           val finish = loc_finish loc gthy;
   465           val lthy' = loc_begin loc gthy
   466             |> local_theory_group
   467             |> f int
   468             |> Local_Theory.reset_group;
   469         in Theory (finish lthy', SOME lthy') end
   470     | _ => raise UNDEF));
   471 
   472 in
   473 
   474 fun local_theory' loc f = local_theory_presentation loc f (K ());
   475 fun local_theory loc f = local_theory' loc (K f);
   476 fun present_local_theory loc = local_theory_presentation loc (K I);
   477 
   478 end;
   479 
   480 
   481 (* proof transitions *)
   482 
   483 fun end_proof f = transaction (fn int =>
   484   (fn Proof (prf, (finish, _)) =>
   485         let val state = Proof_Node.current prf in
   486           if can (Proof.assert_bottom true) state then
   487             let
   488               val ctxt' = f int state;
   489               val gthy' = finish ctxt';
   490             in Theory (gthy', SOME ctxt') end
   491           else raise UNDEF
   492         end
   493     | SkipProof (0, (gthy, _)) => Theory (gthy, NONE)
   494     | _ => raise UNDEF));
   495 
   496 local
   497 
   498 fun begin_proof init finish = transaction (fn int =>
   499   (fn Theory (gthy, _) =>
   500     let
   501       val prf = init int gthy;
   502       val skip = ! skip_proofs;
   503       val (is_goal, no_skip) =
   504         (true, Proof.schematic_goal prf) handle ERROR _ => (false, true);
   505     in
   506       if is_goal andalso skip andalso no_skip then
   507         warning "Cannot skip proof of schematic goal statement"
   508       else ();
   509       if skip andalso not no_skip then
   510         SkipProof (0, (finish gthy (Proof.global_skip_proof int prf), gthy))
   511       else Proof (Proof_Node.init prf, (finish gthy, gthy))
   512     end
   513   | _ => raise UNDEF));
   514 
   515 in
   516 
   517 fun local_theory_to_proof' loc f = begin_proof
   518   (fn int => fn gthy => f int (local_theory_group (loc_begin loc gthy)))
   519   (fn gthy => loc_finish loc gthy o Local_Theory.reset_group);
   520 
   521 fun local_theory_to_proof loc f = local_theory_to_proof' loc (K f);
   522 
   523 fun theory_to_proof f = begin_proof
   524   (K (fn Context.Theory thy => f (global_theory_group thy) | _ => raise UNDEF))
   525   (K (Context.Theory o Sign.reset_group o Proof_Context.theory_of));
   526 
   527 end;
   528 
   529 val forget_proof = transaction (fn _ =>
   530   (fn Proof (_, (_, orig_gthy)) => Theory (orig_gthy, NONE)
   531     | SkipProof (_, (_, orig_gthy)) => Theory (orig_gthy, NONE)
   532     | _ => raise UNDEF));
   533 
   534 val present_proof = present_transaction (fn _ =>
   535   (fn Proof (prf, x) => Proof (Proof_Node.apply I prf, x)
   536     | skip as SkipProof _ => skip
   537     | _ => raise UNDEF));
   538 
   539 fun proofs' f = transaction (fn int =>
   540   (fn Proof (prf, x) => Proof (Proof_Node.applys (f int) prf, x)
   541     | skip as SkipProof _ => skip
   542     | _ => raise UNDEF));
   543 
   544 fun proof' f = proofs' (Seq.single oo f);
   545 val proofs = proofs' o K;
   546 val proof = proof' o K;
   547 
   548 fun actual_proof f = transaction (fn _ =>
   549   (fn Proof (prf, x) => Proof (f prf, x)
   550     | _ => raise UNDEF));
   551 
   552 fun skip_proof f = transaction (fn _ =>
   553   (fn SkipProof (h, x) => SkipProof (f h, x)
   554     | _ => raise UNDEF));
   555 
   556 fun skip_proof_to_theory pred = transaction (fn _ =>
   557   (fn SkipProof (d, (gthy, _)) => if pred d then Theory (gthy, NONE) else raise UNDEF
   558     | _ => raise UNDEF));
   559 
   560 
   561 
   562 (** toplevel transactions **)
   563 
   564 (* identification *)
   565 
   566 fun get_id (Transition {pos, ...}) = Position.get_id pos;
   567 fun put_id id (tr as Transition {pos, ...}) = position (Position.put_id id pos) tr;
   568 
   569 
   570 (* thread position *)
   571 
   572 fun setmp_thread_position (Transition {pos, ...}) f x =
   573   Position.setmp_thread_data pos f x;
   574 
   575 fun status tr m =
   576   setmp_thread_position tr (fn () => Output.status (Markup.markup_only m)) ();
   577 
   578 fun error_msg tr msg =
   579   setmp_thread_position tr (fn () => Output.error_msg' msg) ();
   580 
   581 
   582 (* post-transition hooks *)
   583 
   584 local
   585   val hooks = Unsynchronized.ref ([]: (transition -> state -> state -> unit) list);
   586 in
   587 
   588 fun add_hook f = CRITICAL (fn () => Unsynchronized.change hooks (cons f));
   589 fun get_hooks () = ! hooks;
   590 
   591 end;
   592 
   593 
   594 (* apply transitions *)
   595 
   596 local
   597 
   598 fun app int (tr as Transition {trans, print, no_timing, ...}) =
   599   setmp_thread_position tr (fn state =>
   600     let
   601       fun do_timing f x = (warning (command_msg "" tr); timeap f x);
   602       fun do_profiling f x = profile (! profiling) f x;
   603 
   604       val (result, status) =
   605          state |>
   606           (apply_trans int trans
   607             |> (! profiling > 0 andalso not no_timing) ? do_profiling
   608             |> (! profiling > 0 orelse ! timing andalso not no_timing) ? do_timing);
   609 
   610       val _ = if int andalso not (! quiet) andalso print then print_state false result else ();
   611     in (result, Option.map (fn UNDEF => type_error tr state | exn => exn) status) end);
   612 
   613 in
   614 
   615 fun transition int tr st =
   616   let
   617     val hooks = get_hooks ();
   618     fun apply_hooks st' = hooks |> List.app (fn f => (try (fn () => f tr st st') (); ()));
   619 
   620     val ctxt = try context_of st;
   621     val res =
   622       (case app int tr st of
   623         (_, SOME Runtime.TERMINATE) => NONE
   624       | (st', SOME (Runtime.EXCURSION_FAIL exn_info)) => SOME (st', SOME exn_info)
   625       | (st', SOME exn) => SOME (st', SOME (Runtime.exn_context ctxt exn, at_command tr))
   626       | (st', NONE) => SOME (st', NONE));
   627     val _ = (case res of SOME (st', NONE) => apply_hooks st' | _ => ());
   628   in res end;
   629 
   630 end;
   631 
   632 
   633 (* nested commands *)
   634 
   635 fun command tr st =
   636   (case transition (! interact) tr st of
   637     SOME (st', NONE) => st'
   638   | SOME (_, SOME (exn, info)) =>
   639       if Exn.is_interrupt exn then reraise exn else raise Runtime.EXCURSION_FAIL (exn, info)
   640   | NONE => raise Runtime.EXCURSION_FAIL (Runtime.TERMINATE, at_command tr));
   641 
   642 fun command_result tr st =
   643   let val st' = command tr st
   644   in (st', st') end;
   645 
   646 
   647 (* excursion of units, consisting of commands with proof *)
   648 
   649 structure States = Proof_Data
   650 (
   651   type T = state list future option;
   652   fun init _ = NONE;
   653 );
   654 
   655 fun proof_result immediate (tr, proof_trs) st =
   656   let val st' = command tr st in
   657     if immediate orelse
   658       null proof_trs orelse
   659       Keyword.is_schematic_goal (name_of tr) orelse
   660       exists (Keyword.is_qed_global o name_of) proof_trs orelse
   661       not (can proof_of st') orelse
   662       Proof.is_relevant (proof_of st')
   663     then
   664       let val (states, st'') = fold_map command_result proof_trs st'
   665       in (Future.value ((tr, st') :: (proof_trs ~~ states)), st'') end
   666     else
   667       let
   668         val (body_trs, end_tr) = split_last proof_trs;
   669         val finish = Context.Theory o Proof_Context.theory_of;
   670 
   671         val future_proof = Proof.global_future_proof
   672           (fn prf =>
   673             Goal.fork_name "Toplevel.future_proof"
   674               (fn () =>
   675                 let val (states, result_state) =
   676                   (case st' of State (SOME (Proof (_, (_, orig_gthy))), prev)
   677                     => State (SOME (Proof (Proof_Node.init prf, (finish, orig_gthy))), prev))
   678                   |> fold_map command_result body_trs
   679                   ||> command (end_tr |> set_print false);
   680                 in (states, presentation_context_of result_state) end))
   681           #> (fn (states, ctxt) => States.put (SOME states) ctxt);
   682 
   683         val st'' = st' |> command (end_tr |> reset_trans |> end_proof (K future_proof));
   684 
   685         val states =
   686           (case States.get (presentation_context_of st'') of
   687             NONE => raise Fail ("No future states for " ^ name_of tr ^ Position.str_of (pos_of tr))
   688           | SOME states => states);
   689         val result = states
   690           |> Future.map (fn sts => (tr, st') :: (body_trs ~~ sts) @ [(end_tr, st'')]);
   691 
   692       in (result, st'') end
   693   end;
   694 
   695 fun excursion input =
   696   let
   697     val end_pos = if null input then error "No input" else pos_of (fst (List.last input));
   698     val immediate = not (Goal.future_enabled ());
   699     val (results, end_state) = fold_map (proof_result immediate) input toplevel;
   700     val thy = end_theory end_pos end_state;
   701   in (results, thy) end;
   702 
   703 end;