src/Pure/Isar/toplevel.ML
author wenzelm
Fri Apr 08 16:34:14 2011 +0200 (2011-04-08)
changeset 42290 b1f544c84040
parent 42129 c17508a61f49
child 42360 da8817d01e7c
permissions -rw-r--r--
discontinued special treatment of structure Lexicon;
     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 init_of: transition -> string option
    38   val print_of: transition -> bool
    39   val name_of: transition -> string
    40   val pos_of: transition -> Position.T
    41   val str_of: transition -> string
    42   val name: string -> transition -> transition
    43   val position: Position.T -> transition -> transition
    44   val interactive: bool -> transition -> transition
    45   val set_print: bool -> transition -> transition
    46   val print: transition -> transition
    47   val no_timing: transition -> transition
    48   val init_theory: Path.T option -> string -> (Path.T option -> theory) -> transition -> transition
    49   val modify_master: Path.T option -> transition -> transition
    50   val modify_init: (Path.T option -> theory) -> transition -> transition
    51   val exit: transition -> transition
    52   val keep: (state -> unit) -> transition -> transition
    53   val keep': (bool -> state -> unit) -> transition -> transition
    54   val imperative: (unit -> unit) -> transition -> transition
    55   val ignored: Position.T -> transition
    56   val malformed: Position.T -> string -> transition
    57   val theory: (theory -> theory) -> transition -> transition
    58   val generic_theory: (generic_theory -> generic_theory) -> transition -> transition
    59   val theory': (bool -> theory -> theory) -> transition -> transition
    60   val begin_local_theory: bool -> (theory -> local_theory) -> transition -> transition
    61   val end_local_theory: transition -> transition
    62   val local_theory': xstring option -> (bool -> local_theory -> local_theory) ->
    63     transition -> transition
    64   val local_theory: xstring option -> (local_theory -> local_theory) -> transition -> transition
    65   val present_local_theory: xstring option -> (state -> unit) -> transition -> transition
    66   val local_theory_to_proof': xstring option -> (bool -> local_theory -> Proof.state) ->
    67     transition -> transition
    68   val local_theory_to_proof: xstring option -> (local_theory -> Proof.state) ->
    69     transition -> transition
    70   val theory_to_proof: (theory -> Proof.state) -> transition -> transition
    71   val end_proof: (bool -> Proof.state -> Proof.context) -> transition -> transition
    72   val forget_proof: transition -> transition
    73   val present_proof: (state -> unit) -> transition -> transition
    74   val proofs': (bool -> Proof.state -> Proof.state Seq.seq) -> transition -> transition
    75   val proof': (bool -> Proof.state -> Proof.state) -> transition -> transition
    76   val proofs: (Proof.state -> Proof.state Seq.seq) -> transition -> transition
    77   val proof: (Proof.state -> Proof.state) -> transition -> transition
    78   val actual_proof: (Proof_Node.T -> Proof_Node.T) -> transition -> transition
    79   val skip_proof: (int -> int) -> transition -> transition
    80   val skip_proof_to_theory: (int -> bool) -> transition -> transition
    81   val get_id: transition -> string option
    82   val put_id: string -> transition -> transition
    83   val unknown_theory: transition -> transition
    84   val unknown_proof: transition -> transition
    85   val unknown_context: transition -> transition
    86   val setmp_thread_position: transition -> ('a -> 'b) -> 'a -> 'b
    87   val status: transition -> Markup.T -> unit
    88   val error_msg: transition -> string -> unit
    89   val add_hook: (transition -> state -> state -> unit) -> unit
    90   val transition: bool -> transition -> state -> (state * (exn * string) option) option
    91   val command: transition -> state -> state
    92   val excursion:
    93     (transition * transition list) list -> (transition * state) list future list * theory
    94 end;
    95 
    96 structure Toplevel: TOPLEVEL =
    97 struct
    98 
    99 (** toplevel state **)
   100 
   101 exception UNDEF = Runtime.UNDEF;
   102 
   103 
   104 (* local theory wrappers *)
   105 
   106 val loc_init = Named_Target.context_cmd;
   107 val loc_exit = Local_Theory.exit_global;
   108 
   109 fun loc_begin loc (Context.Theory thy) = loc_init (the_default "-" loc) thy
   110   | loc_begin NONE (Context.Proof lthy) = lthy
   111   | loc_begin (SOME loc) (Context.Proof lthy) = (loc_init loc o loc_exit) lthy;
   112 
   113 fun loc_finish _ (Context.Theory _) = Context.Theory o loc_exit
   114   | loc_finish NONE (Context.Proof _) = Context.Proof o Local_Theory.restore
   115   | loc_finish (SOME _) (Context.Proof lthy) = Context.Proof o Named_Target.reinit lthy;
   116 
   117 
   118 (* datatype node *)
   119 
   120 datatype node =
   121   Theory of generic_theory * Proof.context option
   122     (*theory with presentation context*) |
   123   Proof of Proof_Node.T * ((Proof.context -> generic_theory) * generic_theory)
   124     (*proof node, finish, original theory*) |
   125   SkipProof of int * (generic_theory * generic_theory);
   126     (*proof depth, resulting theory, original theory*)
   127 
   128 val theory_node = fn Theory (gthy, _) => SOME gthy | _ => NONE;
   129 val proof_node = fn Proof (prf, _) => SOME prf | _ => NONE;
   130 
   131 fun cases_node f _ (Theory (gthy, _)) = f gthy
   132   | cases_node _ g (Proof (prf, _)) = g (Proof_Node.current prf)
   133   | cases_node f _ (SkipProof (_, (gthy, _))) = f gthy;
   134 
   135 val context_node = cases_node Context.proof_of Proof.context_of;
   136 
   137 
   138 (* datatype state *)
   139 
   140 datatype state = State of node option * node option;  (*current, previous*)
   141 
   142 val toplevel = State (NONE, NONE);
   143 
   144 fun is_toplevel (State (NONE, _)) = true
   145   | is_toplevel _ = false;
   146 
   147 fun level (State (NONE, _)) = 0
   148   | level (State (SOME (Theory _), _)) = 0
   149   | level (State (SOME (Proof (prf, _)), _)) = Proof.level (Proof_Node.current prf)
   150   | level (State (SOME (SkipProof (d, _)), _)) = d + 1;   (*different notion of proof depth!*)
   151 
   152 fun str_of_state (State (NONE, _)) = "at top level"
   153   | str_of_state (State (SOME (Theory (Context.Theory _, _)), _)) = "in theory mode"
   154   | str_of_state (State (SOME (Theory (Context.Proof _, _)), _)) = "in local theory mode"
   155   | str_of_state (State (SOME (Proof _), _)) = "in proof mode"
   156   | str_of_state (State (SOME (SkipProof _), _)) = "in skipped proof mode";
   157 
   158 
   159 (* current node *)
   160 
   161 fun node_of (State (NONE, _)) = raise UNDEF
   162   | node_of (State (SOME node, _)) = node;
   163 
   164 fun is_theory state = not (is_toplevel state) andalso is_some (theory_node (node_of state));
   165 fun is_proof state = not (is_toplevel state) andalso is_some (proof_node (node_of state));
   166 
   167 fun node_case f g state = cases_node f g (node_of state);
   168 
   169 fun presentation_context_of state =
   170   (case try node_of state of
   171     SOME (Theory (_, SOME ctxt)) => ctxt
   172   | SOME node => context_node node
   173   | NONE => raise UNDEF);
   174 
   175 fun previous_context_of (State (_, NONE)) = NONE
   176   | previous_context_of (State (_, SOME prev)) = SOME (context_node prev);
   177 
   178 val context_of = node_case Context.proof_of Proof.context_of;
   179 val generic_theory_of = node_case I (Context.Proof o Proof.context_of);
   180 val theory_of = node_case Context.theory_of Proof.theory_of;
   181 val proof_of = node_case (fn _ => raise UNDEF) I;
   182 
   183 fun proof_position_of state =
   184   (case node_of state of
   185     Proof (prf, _) => Proof_Node.position prf
   186   | _ => raise UNDEF);
   187 
   188 fun end_theory _ (State (NONE, SOME (Theory (Context.Theory thy, _)))) = Theory.end_theory thy
   189   | end_theory pos _ = error ("Unfinished theory at end of input" ^ 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 end;
   288 
   289 
   290 (* primitive transitions *)
   291 
   292 datatype trans =
   293   Init of Path.T option * string * (Path.T option -> theory) | (*master dir, theory name, init*)
   294   Exit |                                 (*formal exit of theory*)
   295   Keep of bool -> state -> unit |        (*peek at state*)
   296   Transaction of (bool -> node -> node) * (state -> unit);  (*node transaction and presentation*)
   297 
   298 local
   299 
   300 fun apply_tr _ (Init (master, _, f)) (State (NONE, _)) =
   301       State (SOME (Theory (Context.Theory
   302           (Theory.checkpoint (Runtime.controlled_execution f master)), NONE)), NONE)
   303   | apply_tr _ Exit (State (prev as SOME (Theory (Context.Theory _, _)), _)) =
   304       State (NONE, prev)
   305   | apply_tr int (Keep f) state =
   306       Runtime.controlled_execution (fn x => tap (f int) x) state
   307   | apply_tr int (Transaction (f, g)) (State (SOME state, _)) =
   308       apply_transaction (fn x => f int x) g state
   309   | apply_tr _ _ _ = raise UNDEF;
   310 
   311 fun apply_union _ [] state = raise FAILURE (state, UNDEF)
   312   | apply_union int (tr :: trs) state =
   313       apply_union int trs state
   314         handle Runtime.UNDEF => apply_tr int tr state
   315           | FAILURE (alt_state, UNDEF) => apply_tr int tr alt_state
   316           | exn as FAILURE _ => raise exn
   317           | exn => raise FAILURE (state, exn);
   318 
   319 in
   320 
   321 fun apply_trans int trs state = (apply_union int trs state, NONE)
   322   handle FAILURE (alt_state, exn) => (alt_state, SOME exn) | exn => (state, SOME exn);
   323 
   324 end;
   325 
   326 
   327 (* datatype transition *)
   328 
   329 datatype transition = Transition of
   330  {name: string,              (*command name*)
   331   pos: Position.T,           (*source position*)
   332   int_only: bool,            (*interactive-only*)
   333   print: bool,               (*print result state*)
   334   no_timing: bool,           (*suppress timing*)
   335   trans: trans list};        (*primitive transitions (union)*)
   336 
   337 fun make_transition (name, pos, int_only, print, no_timing, trans) =
   338   Transition {name = name, pos = pos, int_only = int_only, print = print, no_timing = no_timing,
   339     trans = trans};
   340 
   341 fun map_transition f (Transition {name, pos, int_only, print, no_timing, trans}) =
   342   make_transition (f (name, pos, int_only, print, no_timing, trans));
   343 
   344 val empty = make_transition ("", Position.none, false, false, false, []);
   345 
   346 
   347 (* diagnostics *)
   348 
   349 fun get_init (Transition {trans = [Init args], ...}) = SOME args
   350   | get_init _ = NONE;
   351 
   352 val init_of = Option.map #2 o get_init;
   353 fun print_of (Transition {print, ...}) = print;
   354 fun name_of (Transition {name, ...}) = name;
   355 fun pos_of (Transition {pos, ...}) = pos;
   356 fun str_of tr = quote (name_of tr) ^ Position.str_of (pos_of tr);
   357 
   358 fun command_msg msg tr = msg ^ "command " ^ str_of tr;
   359 fun at_command tr = command_msg "At " tr;
   360 
   361 fun type_error tr state =
   362   ERROR (command_msg "Illegal application of " tr ^ " " ^ str_of_state state);
   363 
   364 
   365 (* modify transitions *)
   366 
   367 fun name name = map_transition (fn (_, pos, int_only, print, no_timing, trans) =>
   368   (name, pos, int_only, print, no_timing, trans));
   369 
   370 fun position pos = map_transition (fn (name, _, int_only, print, no_timing, trans) =>
   371   (name, pos, int_only, print, no_timing, trans));
   372 
   373 fun interactive int_only = map_transition (fn (name, pos, _, print, no_timing, trans) =>
   374   (name, pos, int_only, print, no_timing, trans));
   375 
   376 val no_timing = map_transition (fn (name, pos, int_only, print, _, trans) =>
   377   (name, pos, int_only, print, true, trans));
   378 
   379 fun add_trans tr = map_transition (fn (name, pos, int_only, print, no_timing, trans) =>
   380   (name, pos, int_only, print, no_timing, tr :: trans));
   381 
   382 val reset_trans = map_transition (fn (name, pos, int_only, print, no_timing, _) =>
   383   (name, pos, int_only, print, no_timing, []));
   384 
   385 fun set_print print = map_transition (fn (name, pos, int_only, _, no_timing, trans) =>
   386   (name, pos, int_only, print, no_timing, trans));
   387 
   388 val print = set_print true;
   389 
   390 
   391 (* basic transitions *)
   392 
   393 fun init_theory master name f = add_trans (Init (master, name, f));
   394 
   395 fun modify_master master tr =
   396   (case get_init tr of
   397     SOME (_, name, f) => init_theory master name f (reset_trans tr)
   398   | NONE => tr);
   399 
   400 fun modify_init f tr =
   401   (case get_init tr of
   402     SOME (master, name, _) => init_theory master name f (reset_trans tr)
   403   | NONE => tr);
   404 
   405 val exit = add_trans Exit;
   406 val keep' = add_trans o Keep;
   407 
   408 fun present_transaction f g = add_trans (Transaction (f, g));
   409 fun transaction f = present_transaction f (K ());
   410 
   411 fun keep f = add_trans (Keep (fn _ => f));
   412 fun imperative f = keep (fn _ => f ());
   413 
   414 fun ignored pos = empty |> name "<ignored>" |> position pos |> imperative I;
   415 fun malformed pos msg =
   416   empty |> name "<malformed>" |> position pos |> imperative (fn () => error msg);
   417 
   418 val unknown_theory = imperative (fn () => warning "Unknown theory context");
   419 val unknown_proof = imperative (fn () => warning "Unknown proof context");
   420 val unknown_context = imperative (fn () => warning "Unknown context");
   421 
   422 
   423 (* theory transitions *)
   424 
   425 fun generic_theory f = transaction (fn _ =>
   426   (fn Theory (gthy, _) => Theory (f gthy, NONE)
   427     | _ => raise UNDEF));
   428 
   429 fun theory' f = transaction (fn int =>
   430   (fn Theory (Context.Theory thy, _) =>
   431       let val thy' = thy
   432         |> Sign.new_group
   433         |> Theory.checkpoint
   434         |> f int
   435         |> Sign.reset_group;
   436       in Theory (Context.Theory thy', NONE) end
   437     | _ => raise UNDEF));
   438 
   439 fun theory f = theory' (K f);
   440 
   441 fun begin_local_theory begin f = transaction (fn _ =>
   442   (fn Theory (Context.Theory thy, _) =>
   443         let
   444           val lthy = f thy;
   445           val gthy = if begin then Context.Proof lthy else Context.Theory (loc_exit lthy);
   446         in Theory (gthy, SOME lthy) end
   447     | _ => raise UNDEF));
   448 
   449 val end_local_theory = transaction (fn _ =>
   450   (fn Theory (Context.Proof lthy, _) => Theory (Context.Theory (loc_exit lthy), SOME lthy)
   451     | _ => raise UNDEF));
   452 
   453 local
   454 
   455 fun local_theory_presentation loc f = present_transaction (fn int =>
   456   (fn Theory (gthy, _) =>
   457         let
   458           val finish = loc_finish loc gthy;
   459           val lthy' = loc_begin loc gthy
   460             |> Local_Theory.new_group
   461             |> f int
   462             |> Local_Theory.reset_group;
   463         in Theory (finish lthy', SOME lthy') end
   464     | _ => raise UNDEF));
   465 
   466 in
   467 
   468 fun local_theory' loc f = local_theory_presentation loc f (K ());
   469 fun local_theory loc f = local_theory' loc (K f);
   470 fun present_local_theory loc = local_theory_presentation loc (K I);
   471 
   472 end;
   473 
   474 
   475 (* proof transitions *)
   476 
   477 fun end_proof f = transaction (fn int =>
   478   (fn Proof (prf, (finish, _)) =>
   479         let val state = Proof_Node.current prf in
   480           if can (Proof.assert_bottom true) state then
   481             let
   482               val ctxt' = f int state;
   483               val gthy' = finish ctxt';
   484             in Theory (gthy', SOME ctxt') end
   485           else raise UNDEF
   486         end
   487     | SkipProof (0, (gthy, _)) => Theory (gthy, NONE)
   488     | _ => raise UNDEF));
   489 
   490 local
   491 
   492 fun begin_proof init finish = transaction (fn int =>
   493   (fn Theory (gthy, _) =>
   494     let
   495       val prf = init int gthy;
   496       val skip = ! skip_proofs;
   497       val (is_goal, no_skip) =
   498         (true, Proof.schematic_goal prf) handle ERROR _ => (false, true);
   499     in
   500       if is_goal andalso skip andalso no_skip then
   501         warning "Cannot skip proof of schematic goal statement"
   502       else ();
   503       if skip andalso not no_skip then
   504         SkipProof (0, (finish gthy (Proof.global_skip_proof int prf), gthy))
   505       else Proof (Proof_Node.init prf, (finish gthy, gthy))
   506     end
   507   | _ => raise UNDEF));
   508 
   509 in
   510 
   511 fun local_theory_to_proof' loc f = begin_proof
   512   (fn int => fn gthy => f int (Local_Theory.new_group (loc_begin loc gthy)))
   513   (fn gthy => loc_finish loc gthy o Local_Theory.reset_group);
   514 
   515 fun local_theory_to_proof loc f = local_theory_to_proof' loc (K f);
   516 
   517 fun theory_to_proof f = begin_proof
   518   (K (fn Context.Theory thy => f (Theory.checkpoint (Sign.new_group thy)) | _ => raise UNDEF))
   519   (K (Context.Theory o Sign.reset_group o ProofContext.theory_of));
   520 
   521 end;
   522 
   523 val forget_proof = transaction (fn _ =>
   524   (fn Proof (_, (_, orig_gthy)) => Theory (orig_gthy, NONE)
   525     | SkipProof (_, (_, orig_gthy)) => Theory (orig_gthy, NONE)
   526     | _ => raise UNDEF));
   527 
   528 val present_proof = present_transaction (fn _ =>
   529   (fn Proof (prf, x) => Proof (Proof_Node.apply I prf, x)
   530     | skip as SkipProof _ => skip
   531     | _ => raise UNDEF));
   532 
   533 fun proofs' f = transaction (fn int =>
   534   (fn Proof (prf, x) => Proof (Proof_Node.applys (f int) prf, x)
   535     | skip as SkipProof _ => skip
   536     | _ => raise UNDEF));
   537 
   538 fun proof' f = proofs' (Seq.single oo f);
   539 val proofs = proofs' o K;
   540 val proof = proof' o K;
   541 
   542 fun actual_proof f = transaction (fn _ =>
   543   (fn Proof (prf, x) => Proof (f prf, x)
   544     | _ => raise UNDEF));
   545 
   546 fun skip_proof f = transaction (fn _ =>
   547   (fn SkipProof (h, x) => SkipProof (f h, x)
   548     | _ => raise UNDEF));
   549 
   550 fun skip_proof_to_theory pred = transaction (fn _ =>
   551   (fn SkipProof (d, (gthy, _)) => if pred d then Theory (gthy, NONE) else raise UNDEF
   552     | _ => raise UNDEF));
   553 
   554 
   555 
   556 (** toplevel transactions **)
   557 
   558 (* identification *)
   559 
   560 fun get_id (Transition {pos, ...}) = Position.get_id pos;
   561 fun put_id id (tr as Transition {pos, ...}) = position (Position.put_id id pos) tr;
   562 
   563 
   564 (* thread position *)
   565 
   566 fun setmp_thread_position (Transition {pos, ...}) f x =
   567   Position.setmp_thread_data pos f x;
   568 
   569 fun status tr m =
   570   setmp_thread_position tr (fn () => Output.status (Markup.markup m "")) ();
   571 
   572 fun error_msg tr msg =
   573   setmp_thread_position tr (fn () => Output.error_msg msg) ();
   574 
   575 
   576 (* post-transition hooks *)
   577 
   578 local
   579   val hooks = Unsynchronized.ref ([]: (transition -> state -> state -> unit) list);
   580 in
   581 
   582 fun add_hook f = CRITICAL (fn () => Unsynchronized.change hooks (cons f));
   583 fun get_hooks () = ! hooks;
   584 
   585 end;
   586 
   587 
   588 (* apply transitions *)
   589 
   590 local
   591 
   592 fun app int (tr as Transition {trans, print, no_timing, ...}) =
   593   setmp_thread_position tr (fn state =>
   594     let
   595       fun do_timing f x = (warning (command_msg "" tr); timeap f x);
   596       fun do_profiling f x = profile (! profiling) f x;
   597 
   598       val (result, status) =
   599          state |>
   600           (apply_trans int trans
   601             |> (! profiling > 0 andalso not no_timing) ? do_profiling
   602             |> (! profiling > 0 orelse ! timing andalso not no_timing) ? do_timing);
   603 
   604       val _ = if int andalso not (! quiet) andalso print then print_state false result else ();
   605     in (result, Option.map (fn UNDEF => type_error tr state | exn => exn) status) end);
   606 
   607 in
   608 
   609 fun transition int tr st =
   610   let
   611     val hooks = get_hooks ();
   612     fun apply_hooks st' = hooks |> List.app (fn f => (try (fn () => f tr st st') (); ()));
   613 
   614     val ctxt = try context_of st;
   615     val res =
   616       (case app int tr st of
   617         (_, SOME Runtime.TERMINATE) => NONE
   618       | (st', SOME (Runtime.EXCURSION_FAIL exn_info)) => SOME (st', SOME exn_info)
   619       | (st', SOME exn) => SOME (st', SOME (Runtime.exn_context ctxt exn, at_command tr))
   620       | (st', NONE) => SOME (st', NONE));
   621     val _ = (case res of SOME (st', NONE) => apply_hooks st' | _ => ());
   622   in res end;
   623 
   624 end;
   625 
   626 
   627 (* nested commands *)
   628 
   629 fun command tr st =
   630   (case transition (! interact) tr st of
   631     SOME (st', NONE) => st'
   632   | SOME (_, SOME (exn, info)) =>
   633       if Exn.is_interrupt exn then reraise exn else raise Runtime.EXCURSION_FAIL (exn, info)
   634   | NONE => raise Runtime.EXCURSION_FAIL (Runtime.TERMINATE, at_command tr));
   635 
   636 fun command_result tr st =
   637   let val st' = command tr st
   638   in (st', st') end;
   639 
   640 
   641 (* excursion of units, consisting of commands with proof *)
   642 
   643 structure States = Proof_Data
   644 (
   645   type T = state list future option;
   646   fun init _ = NONE;
   647 );
   648 
   649 fun proof_result immediate (tr, proof_trs) st =
   650   let val st' = command tr st in
   651     if immediate orelse
   652       null proof_trs orelse
   653       Keyword.is_schematic_goal (name_of tr) orelse
   654       exists (Keyword.is_qed_global o name_of) proof_trs orelse
   655       not (can proof_of st') orelse
   656       Proof.is_relevant (proof_of st')
   657     then
   658       let val (states, st'') = fold_map command_result proof_trs st'
   659       in (Future.value ((tr, st') :: (proof_trs ~~ states)), st'') end
   660     else
   661       let
   662         val (body_trs, end_tr) = split_last proof_trs;
   663         val finish = Context.Theory o ProofContext.theory_of;
   664 
   665         val future_proof = Proof.global_future_proof
   666           (fn prf =>
   667             Goal.fork_name "Toplevel.future_proof"
   668               (fn () =>
   669                 let val (states, result_state) =
   670                   (case st' of State (SOME (Proof (_, (_, orig_gthy))), prev)
   671                     => State (SOME (Proof (Proof_Node.init prf, (finish, orig_gthy))), prev))
   672                   |> fold_map command_result body_trs
   673                   ||> command (end_tr |> set_print false);
   674                 in (states, presentation_context_of result_state) end))
   675           #> (fn (states, ctxt) => States.put (SOME states) ctxt);
   676 
   677         val st'' = st' |> command (end_tr |> reset_trans |> end_proof (K future_proof));
   678 
   679         val states =
   680           (case States.get (presentation_context_of st'') of
   681             NONE => raise Fail ("No future states for " ^ name_of tr ^ Position.str_of (pos_of tr))
   682           | SOME states => states);
   683         val result = states
   684           |> Future.map (fn sts => (tr, st') :: (body_trs ~~ sts) @ [(end_tr, st'')]);
   685 
   686       in (result, st'') end
   687   end;
   688 
   689 fun excursion input =
   690   let
   691     val end_pos = if null input then error "No input" else pos_of (fst (List.last input));
   692     val immediate = not (Goal.future_enabled ());
   693     val (results, end_state) = fold_map (proof_result immediate) input toplevel;
   694     val thy = end_theory end_pos end_state;
   695   in (results, thy) end;
   696 
   697 end;