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