src/Pure/Isar/toplevel.ML
author wenzelm
Sat Aug 13 20:41:29 2011 +0200 (2011-08-13 ago)
changeset 44186 806f0ec1a43d
parent 44185 05641edb5d30
child 44187 88d770052bac
permissions -rw-r--r--
simplified Toplevel.init_theory: discontinued special master argument;
     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 is_init: transition -> bool
    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: string -> (unit -> theory) -> transition -> transition
    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 -> 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 (SOME _, _)) = error ("Unfinished theory " ^ Position.str_of pos)
   189   | end_theory pos (State (NONE, NONE)) = error ("Missing 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 string * (unit -> theory) | (*theory name, init*)
   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 get_init (Transition {trans = [Init args], ...}) = SOME args
   356   | get_init _ = NONE;
   357 
   358 val is_init = is_some o get_init;
   359 
   360 fun print_of (Transition {print, ...}) = print;
   361 fun name_of (Transition {name, ...}) = name;
   362 fun pos_of (Transition {pos, ...}) = pos;
   363 fun str_of tr = quote (name_of tr) ^ Position.str_of (pos_of tr);
   364 
   365 fun command_msg msg tr = msg ^ "command " ^ str_of tr;
   366 fun at_command tr = command_msg "At " tr;
   367 
   368 fun type_error tr state =
   369   ERROR (command_msg "Illegal application of " tr ^ " " ^ str_of_state state);
   370 
   371 
   372 (* modify transitions *)
   373 
   374 fun name name = map_transition (fn (_, pos, int_only, print, no_timing, trans) =>
   375   (name, pos, int_only, print, no_timing, trans));
   376 
   377 fun position pos = map_transition (fn (name, _, int_only, print, no_timing, trans) =>
   378   (name, pos, int_only, print, no_timing, trans));
   379 
   380 fun interactive int_only = map_transition (fn (name, pos, _, print, no_timing, trans) =>
   381   (name, pos, int_only, print, no_timing, trans));
   382 
   383 val no_timing = map_transition (fn (name, pos, int_only, print, _, trans) =>
   384   (name, pos, int_only, print, true, trans));
   385 
   386 fun add_trans tr = map_transition (fn (name, pos, int_only, print, no_timing, trans) =>
   387   (name, pos, int_only, print, no_timing, tr :: trans));
   388 
   389 val reset_trans = map_transition (fn (name, pos, int_only, print, no_timing, _) =>
   390   (name, pos, int_only, print, no_timing, []));
   391 
   392 fun set_print print = map_transition (fn (name, pos, int_only, _, no_timing, trans) =>
   393   (name, pos, int_only, print, no_timing, trans));
   394 
   395 val print = set_print true;
   396 
   397 
   398 (* basic transitions *)
   399 
   400 fun init_theory name f = add_trans (Init (name, f));
   401 
   402 fun modify_init f tr =
   403   (case get_init tr of
   404     SOME (name, _) => init_theory name f (reset_trans tr)
   405   | NONE => tr);
   406 
   407 val exit = add_trans Exit;
   408 val keep' = add_trans o Keep;
   409 
   410 fun present_transaction f g = add_trans (Transaction (f, g));
   411 fun transaction f = present_transaction f (K ());
   412 
   413 fun keep f = add_trans (Keep (fn _ => f));
   414 fun imperative f = keep (fn _ => f ());
   415 
   416 fun ignored pos = empty |> name "<ignored>" |> position pos |> imperative I;
   417 fun malformed pos msg =
   418   empty |> name "<malformed>" |> position pos |> imperative (fn () => error msg);
   419 
   420 val unknown_theory = imperative (fn () => warning "Unknown theory context");
   421 val unknown_proof = imperative (fn () => warning "Unknown proof context");
   422 val unknown_context = imperative (fn () => warning "Unknown context");
   423 
   424 
   425 (* theory transitions *)
   426 
   427 fun generic_theory f = transaction (fn _ =>
   428   (fn Theory (gthy, _) => Theory (f gthy, NONE)
   429     | _ => raise UNDEF));
   430 
   431 fun theory' f = transaction (fn int =>
   432   (fn Theory (Context.Theory thy, _) =>
   433       let val thy' = thy
   434         |> Sign.new_group
   435         |> Theory.checkpoint
   436         |> f int
   437         |> Sign.reset_group;
   438       in Theory (Context.Theory thy', NONE) end
   439     | _ => raise UNDEF));
   440 
   441 fun theory f = theory' (K f);
   442 
   443 fun begin_local_theory begin f = transaction (fn _ =>
   444   (fn Theory (Context.Theory thy, _) =>
   445         let
   446           val lthy = f thy;
   447           val gthy = if begin then Context.Proof lthy else Context.Theory (loc_exit lthy);
   448         in Theory (gthy, SOME lthy) end
   449     | _ => raise UNDEF));
   450 
   451 val end_local_theory = transaction (fn _ =>
   452   (fn Theory (Context.Proof lthy, _) => Theory (Context.Theory (loc_exit lthy), SOME lthy)
   453     | _ => raise UNDEF));
   454 
   455 local
   456 
   457 fun local_theory_presentation loc f = present_transaction (fn int =>
   458   (fn Theory (gthy, _) =>
   459         let
   460           val finish = loc_finish loc gthy;
   461           val lthy' = loc_begin loc gthy
   462             |> Local_Theory.new_group
   463             |> f int
   464             |> Local_Theory.reset_group;
   465         in Theory (finish lthy', SOME lthy') end
   466     | _ => raise UNDEF));
   467 
   468 in
   469 
   470 fun local_theory' loc f = local_theory_presentation loc f (K ());
   471 fun local_theory loc f = local_theory' loc (K f);
   472 fun present_local_theory loc = local_theory_presentation loc (K I);
   473 
   474 end;
   475 
   476 
   477 (* proof transitions *)
   478 
   479 fun end_proof f = transaction (fn int =>
   480   (fn Proof (prf, (finish, _)) =>
   481         let val state = Proof_Node.current prf in
   482           if can (Proof.assert_bottom true) state then
   483             let
   484               val ctxt' = f int state;
   485               val gthy' = finish ctxt';
   486             in Theory (gthy', SOME ctxt') end
   487           else raise UNDEF
   488         end
   489     | SkipProof (0, (gthy, _)) => Theory (gthy, NONE)
   490     | _ => raise UNDEF));
   491 
   492 local
   493 
   494 fun begin_proof init finish = transaction (fn int =>
   495   (fn Theory (gthy, _) =>
   496     let
   497       val prf = init int gthy;
   498       val skip = ! skip_proofs;
   499       val (is_goal, no_skip) =
   500         (true, Proof.schematic_goal prf) handle ERROR _ => (false, true);
   501     in
   502       if is_goal andalso skip andalso no_skip then
   503         warning "Cannot skip proof of schematic goal statement"
   504       else ();
   505       if skip andalso not no_skip then
   506         SkipProof (0, (finish gthy (Proof.global_skip_proof int prf), gthy))
   507       else Proof (Proof_Node.init prf, (finish gthy, gthy))
   508     end
   509   | _ => raise UNDEF));
   510 
   511 in
   512 
   513 fun local_theory_to_proof' loc f = begin_proof
   514   (fn int => fn gthy => f int (Local_Theory.new_group (loc_begin loc gthy)))
   515   (fn gthy => loc_finish loc gthy o Local_Theory.reset_group);
   516 
   517 fun local_theory_to_proof loc f = local_theory_to_proof' loc (K f);
   518 
   519 fun theory_to_proof f = begin_proof
   520   (K (fn Context.Theory thy => f (Theory.checkpoint (Sign.new_group thy)) | _ => raise UNDEF))
   521   (K (Context.Theory o Sign.reset_group o Proof_Context.theory_of));
   522 
   523 end;
   524 
   525 val forget_proof = transaction (fn _ =>
   526   (fn Proof (_, (_, orig_gthy)) => Theory (orig_gthy, NONE)
   527     | SkipProof (_, (_, orig_gthy)) => Theory (orig_gthy, NONE)
   528     | _ => raise UNDEF));
   529 
   530 val present_proof = present_transaction (fn _ =>
   531   (fn Proof (prf, x) => Proof (Proof_Node.apply I prf, x)
   532     | skip as SkipProof _ => skip
   533     | _ => raise UNDEF));
   534 
   535 fun proofs' f = transaction (fn int =>
   536   (fn Proof (prf, x) => Proof (Proof_Node.applys (f int) prf, x)
   537     | skip as SkipProof _ => skip
   538     | _ => raise UNDEF));
   539 
   540 fun proof' f = proofs' (Seq.single oo f);
   541 val proofs = proofs' o K;
   542 val proof = proof' o K;
   543 
   544 fun actual_proof f = transaction (fn _ =>
   545   (fn Proof (prf, x) => Proof (f prf, x)
   546     | _ => raise UNDEF));
   547 
   548 fun skip_proof f = transaction (fn _ =>
   549   (fn SkipProof (h, x) => SkipProof (f h, x)
   550     | _ => raise UNDEF));
   551 
   552 fun skip_proof_to_theory pred = transaction (fn _ =>
   553   (fn SkipProof (d, (gthy, _)) => if pred d then Theory (gthy, NONE) else raise UNDEF
   554     | _ => raise UNDEF));
   555 
   556 
   557 
   558 (** toplevel transactions **)
   559 
   560 (* identification *)
   561 
   562 fun get_id (Transition {pos, ...}) = Position.get_id pos;
   563 fun put_id id (tr as Transition {pos, ...}) = position (Position.put_id id pos) tr;
   564 
   565 
   566 (* thread position *)
   567 
   568 fun setmp_thread_position (Transition {pos, ...}) f x =
   569   Position.setmp_thread_data pos f x;
   570 
   571 fun status tr m =
   572   setmp_thread_position tr (fn () => Output.status (Markup.markup_only m)) ();
   573 
   574 fun error_msg tr msg =
   575   setmp_thread_position tr (fn () => Output.error_msg msg) ();
   576 
   577 
   578 (* post-transition hooks *)
   579 
   580 local
   581   val hooks = Unsynchronized.ref ([]: (transition -> state -> state -> unit) list);
   582 in
   583 
   584 fun add_hook f = CRITICAL (fn () => Unsynchronized.change hooks (cons f));
   585 fun get_hooks () = ! hooks;
   586 
   587 end;
   588 
   589 
   590 (* apply transitions *)
   591 
   592 local
   593 
   594 fun app int (tr as Transition {trans, print, no_timing, ...}) =
   595   setmp_thread_position tr (fn state =>
   596     let
   597       fun do_timing f x = (warning (command_msg "" tr); timeap f x);
   598       fun do_profiling f x = profile (! profiling) f x;
   599 
   600       val (result, status) =
   601          state |>
   602           (apply_trans int trans
   603             |> (! profiling > 0 andalso not no_timing) ? do_profiling
   604             |> (! profiling > 0 orelse ! timing andalso not no_timing) ? do_timing);
   605 
   606       val _ = if int andalso not (! quiet) andalso print then print_state false result else ();
   607     in (result, Option.map (fn UNDEF => type_error tr state | exn => exn) status) end);
   608 
   609 in
   610 
   611 fun transition int tr st =
   612   let
   613     val hooks = get_hooks ();
   614     fun apply_hooks st' = hooks |> List.app (fn f => (try (fn () => f tr st st') (); ()));
   615 
   616     val ctxt = try context_of st;
   617     val res =
   618       (case app int tr st of
   619         (_, SOME Runtime.TERMINATE) => NONE
   620       | (st', SOME (Runtime.EXCURSION_FAIL exn_info)) => SOME (st', SOME exn_info)
   621       | (st', SOME exn) => SOME (st', SOME (Runtime.exn_context ctxt exn, at_command tr))
   622       | (st', NONE) => SOME (st', NONE));
   623     val _ = (case res of SOME (st', NONE) => apply_hooks st' | _ => ());
   624   in res end;
   625 
   626 end;
   627 
   628 
   629 (* nested commands *)
   630 
   631 fun command tr st =
   632   (case transition (! interact) tr st of
   633     SOME (st', NONE) => st'
   634   | SOME (_, SOME (exn, info)) =>
   635       if Exn.is_interrupt exn then reraise exn else raise Runtime.EXCURSION_FAIL (exn, info)
   636   | NONE => raise Runtime.EXCURSION_FAIL (Runtime.TERMINATE, at_command tr));
   637 
   638 fun command_result tr st =
   639   let val st' = command tr st
   640   in (st', st') end;
   641 
   642 
   643 (* excursion of units, consisting of commands with proof *)
   644 
   645 structure States = Proof_Data
   646 (
   647   type T = state list future option;
   648   fun init _ = NONE;
   649 );
   650 
   651 fun proof_result immediate (tr, proof_trs) st =
   652   let val st' = command tr st in
   653     if immediate orelse
   654       null proof_trs orelse
   655       Keyword.is_schematic_goal (name_of tr) orelse
   656       exists (Keyword.is_qed_global o name_of) proof_trs orelse
   657       not (can proof_of st') orelse
   658       Proof.is_relevant (proof_of st')
   659     then
   660       let val (states, st'') = fold_map command_result proof_trs st'
   661       in (Future.value ((tr, st') :: (proof_trs ~~ states)), st'') end
   662     else
   663       let
   664         val (body_trs, end_tr) = split_last proof_trs;
   665         val finish = Context.Theory o Proof_Context.theory_of;
   666 
   667         val future_proof = Proof.global_future_proof
   668           (fn prf =>
   669             Goal.fork_name "Toplevel.future_proof"
   670               (fn () =>
   671                 let val (states, result_state) =
   672                   (case st' of State (SOME (Proof (_, (_, orig_gthy))), prev)
   673                     => State (SOME (Proof (Proof_Node.init prf, (finish, orig_gthy))), prev))
   674                   |> fold_map command_result body_trs
   675                   ||> command (end_tr |> set_print false);
   676                 in (states, presentation_context_of result_state) end))
   677           #> (fn (states, ctxt) => States.put (SOME states) ctxt);
   678 
   679         val st'' = st' |> command (end_tr |> reset_trans |> end_proof (K future_proof));
   680 
   681         val states =
   682           (case States.get (presentation_context_of st'') of
   683             NONE => raise Fail ("No future states for " ^ name_of tr ^ Position.str_of (pos_of tr))
   684           | SOME states => states);
   685         val result = states
   686           |> Future.map (fn sts => (tr, st') :: (body_trs ~~ sts) @ [(end_tr, st'')]);
   687 
   688       in (result, st'') end
   689   end;
   690 
   691 fun excursion input =
   692   let
   693     val end_pos = if null input then error "No input" else pos_of (fst (List.last input));
   694     val immediate = not (Goal.future_enabled ());
   695     val (results, end_state) = fold_map (proof_result immediate) input toplevel;
   696     val thy = end_theory end_pos end_state;
   697   in (results, thy) end;
   698 
   699 end;