src/Pure/Isar/toplevel.ML
author haftmann
Fri Nov 02 18:53:00 2007 +0100 (2007-11-02)
changeset 25269 f9090ae5cec9
parent 25219 084f468145e3
child 25292 f082e59551b0
permissions -rw-r--r--
clarified theory target interface
     1 (*  Title:      Pure/Isar/toplevel.ML
     2     ID:         $Id$
     3     Author:     Markus Wenzel, TU Muenchen
     4 
     5 The Isabelle/Isar toplevel.
     6 *)
     7 
     8 signature TOPLEVEL =
     9 sig
    10   exception UNDEF
    11   type generic_theory
    12   type node
    13   val theory_node: node -> generic_theory option
    14   val proof_node: node -> ProofHistory.T option
    15   val cases_node: (generic_theory -> 'a) -> (Proof.state -> 'a) -> node -> 'a
    16   val presentation_context: node option -> xstring option -> Proof.context
    17   type state
    18   val is_toplevel: state -> bool
    19   val is_theory: state -> bool
    20   val is_proof: state -> bool
    21   val level: state -> int
    22   val node_history_of: state -> node History.T
    23   val node_of: state -> node
    24   val node_case: (generic_theory -> 'a) -> (Proof.state -> 'a) -> state -> 'a
    25   val context_of: state -> Proof.context
    26   val generic_theory_of: state -> generic_theory
    27   val theory_of: state -> theory
    28   val proof_of: state -> Proof.state
    29   val proof_position_of: state -> int
    30   val enter_proof_body: state -> Proof.state
    31   val print_state_context: state -> unit
    32   val print_state: bool -> state -> unit
    33   val quiet: bool ref
    34   val debug: bool ref
    35   val interact: bool ref
    36   val timing: bool ref
    37   val profiling: int ref
    38   val skip_proofs: bool ref
    39   exception TERMINATE
    40   exception RESTART
    41   exception TOPLEVEL_ERROR
    42   val exn_message: exn -> string
    43   val program: (unit -> 'a) -> 'a
    44   type transition
    45   val undo_limit: bool -> int option
    46   val empty: transition
    47   val name_of: transition -> string
    48   val source_of: transition -> OuterLex.token list option
    49   val name: string -> transition -> transition
    50   val position: Position.T -> transition -> transition
    51   val source: OuterLex.token list -> transition -> transition
    52   val interactive: bool -> transition -> transition
    53   val print: transition -> transition
    54   val print': string -> transition -> transition
    55   val three_buffersN: string
    56   val print3: transition -> transition
    57   val no_timing: transition -> transition
    58   val init_theory: (bool -> theory) -> (theory -> unit) -> (theory -> unit) ->
    59     transition -> transition
    60   val init_empty: (unit -> unit) -> transition -> transition
    61   val exit: transition -> transition
    62   val undo_exit: transition -> transition
    63   val kill: transition -> transition
    64   val history: (node History.T -> node History.T) -> transition -> transition
    65   val keep: (state -> unit) -> transition -> transition
    66   val keep': (bool -> state -> unit) -> transition -> transition
    67   val imperative: (unit -> unit) -> transition -> transition
    68   val theory: (theory -> theory) -> transition -> transition
    69   val theory': (bool -> theory -> theory) -> transition -> transition
    70   val begin_local_theory: bool -> (theory -> local_theory) -> transition -> transition
    71   val end_local_theory: transition -> transition
    72   val local_theory: xstring option -> (local_theory -> local_theory) -> transition -> transition
    73   val present_local_theory: xstring option -> (bool -> node -> unit) -> transition -> transition
    74   val local_theory_to_proof': xstring option -> (bool -> local_theory -> Proof.state) ->
    75     transition -> transition
    76   val local_theory_to_proof: xstring option -> (local_theory -> Proof.state) ->
    77     transition -> transition
    78   val theory_to_proof: (theory -> Proof.state) -> transition -> transition
    79   val end_proof: (bool -> Proof.state -> Proof.context) -> transition -> transition
    80   val forget_proof: transition -> transition
    81   val present_proof: (bool -> node -> unit) -> transition -> transition
    82   val proofs': (bool -> Proof.state -> Proof.state Seq.seq) -> transition -> transition
    83   val proof': (bool -> Proof.state -> Proof.state) -> transition -> transition
    84   val proofs: (Proof.state -> Proof.state Seq.seq) -> transition -> transition
    85   val proof: (Proof.state -> Proof.state) -> transition -> transition
    86   val actual_proof: (ProofHistory.T -> ProofHistory.T) -> transition -> transition
    87   val skip_proof: (int History.T -> int History.T) -> transition -> transition
    88   val skip_proof_to_theory: (int -> bool) -> transition -> transition
    89   val unknown_theory: transition -> transition
    90   val unknown_proof: transition -> transition
    91   val unknown_context: transition -> transition
    92   val present_excursion: (transition * (state -> state -> 'a -> 'a)) list -> 'a -> 'a
    93   val excursion: transition list -> unit
    94   val set_state: state -> unit
    95   val get_state: unit -> state
    96   val exn: unit -> (exn * string) option
    97   val >> : transition -> bool
    98   val >>> : transition list -> unit
    99   val init_state: unit -> unit
   100   type 'a isar
   101   val loop: 'a isar -> unit
   102 end;
   103 
   104 structure Toplevel: TOPLEVEL =
   105 struct
   106 
   107 
   108 (** toplevel state **)
   109 
   110 exception UNDEF;
   111 
   112 
   113 (* local theory wrappers *)
   114 
   115 type generic_theory = Context.generic;    (*theory or local_theory*)
   116 
   117 val loc_init = TheoryTarget.init_cmd;
   118 
   119 val loc_exit = ProofContext.theory_of o LocalTheory.exit;
   120 
   121 fun loc_begin NONE (Context.Theory thy) = loc_init "-" thy
   122   | loc_begin (SOME loc) (Context.Theory thy) = loc_init loc thy
   123   | loc_begin NONE (Context.Proof lthy) = lthy
   124   | loc_begin (SOME loc) (Context.Proof lthy) = loc_init loc (loc_exit lthy);
   125 
   126 fun loc_finish _ (Context.Theory _) = Context.Theory o loc_exit
   127   | loc_finish NONE (Context.Proof _) = Context.Proof o LocalTheory.restore
   128   | loc_finish (SOME _) (Context.Proof lthy) = Context.Proof o LocalTheory.reinit lthy o loc_exit;
   129 
   130 
   131 (* datatype node *)
   132 
   133 datatype node =
   134   Theory of generic_theory * Proof.context option | (*theory with presentation context*)
   135   Proof of ProofHistory.T * ((Proof.context -> generic_theory) * generic_theory) |
   136     (*history of proof states, finish, original theory*)
   137   SkipProof of int History.T * (generic_theory * generic_theory);
   138     (*history of proof depths, resulting theory, original theory*)
   139 
   140 val the_global_theory = fn Theory (Context.Theory thy, _) => thy | _ => raise UNDEF;
   141 val theory_node = fn Theory (gthy, _) => SOME gthy | _ => NONE;
   142 val proof_node = fn Proof (prf, _) => SOME prf | _ => NONE;
   143 
   144 fun cases_node f _ (Theory (gthy, _)) = f gthy
   145   | cases_node _ g (Proof (prf, _)) = g (ProofHistory.current prf)
   146   | cases_node f _ (SkipProof (_, (gthy, _))) = f gthy;
   147 
   148 fun presentation_context (SOME (Theory (_, SOME ctxt))) NONE = ctxt
   149   | presentation_context (SOME node) NONE = cases_node Context.proof_of Proof.context_of node
   150   | presentation_context (SOME node) (SOME loc) =
   151       loc_init loc (cases_node Context.theory_of Proof.theory_of node)
   152   | presentation_context NONE _ = raise UNDEF;
   153 
   154 
   155 (* datatype state *)
   156 
   157 type state_info = node History.T * ((theory -> unit) * (theory -> unit));
   158 
   159 datatype state =
   160   Toplevel of state_info option |  (*outer toplevel, leftover end state*)
   161   State of state_info;
   162 
   163 val toplevel = Toplevel NONE;
   164 
   165 fun is_toplevel (Toplevel _) = true
   166   | is_toplevel _ = false;
   167 
   168 fun level (Toplevel _) = 0
   169   | level (State (node, _)) =
   170       (case History.current node of
   171         Theory _ => 0
   172       | Proof (prf, _) => Proof.level (ProofHistory.current prf)
   173       | SkipProof (h, _) => History.current h + 1);   (*different notion of proof depth!*)
   174 
   175 fun str_of_state (Toplevel _) = "at top level"
   176   | str_of_state (State (node, _)) =
   177       (case History.current node of
   178         Theory (Context.Theory _, _) => "in theory mode"
   179       | Theory (Context.Proof _, _) => "in local theory mode"
   180       | Proof _ => "in proof mode"
   181       | SkipProof _ => "in skipped proof mode");
   182 
   183 
   184 (* top node *)
   185 
   186 fun node_history_of (Toplevel _) = raise UNDEF
   187   | node_history_of (State (node, _)) = node;
   188 
   189 val node_of = History.current o node_history_of;
   190 
   191 fun is_theory state = not (is_toplevel state) andalso is_some (theory_node (node_of state));
   192 fun is_proof state = not (is_toplevel state) andalso is_some (proof_node (node_of state));
   193 
   194 fun node_case f g state = cases_node f g (node_of state);
   195 
   196 val context_of = node_case Context.proof_of Proof.context_of;
   197 val generic_theory_of = node_case I (Context.Proof o Proof.context_of);
   198 val theory_of = node_case Context.theory_of Proof.theory_of;
   199 val proof_of = node_case (fn _ => raise UNDEF) I;
   200 
   201 fun proof_position_of state =
   202   (case node_of state of
   203     Proof (prf, _) => ProofHistory.position prf
   204   | _ => raise UNDEF);
   205 
   206 val enter_proof_body = node_case (Proof.init o Context.proof_of) Proof.enter_forward;
   207 
   208 
   209 (* print state *)
   210 
   211 val pretty_context = LocalTheory.pretty o Context.cases (loc_init "-") I;
   212 
   213 fun print_state_context state =
   214   (case try node_of state of
   215     NONE => []
   216   | SOME (Theory (gthy, _)) => pretty_context gthy
   217   | SOME (Proof (_, (_, gthy))) => pretty_context gthy
   218   | SOME (SkipProof (_, (gthy, _))) => pretty_context gthy)
   219   |> Pretty.chunks |> Pretty.writeln;
   220 
   221 fun print_state prf_only state =
   222   (case try node_of state of
   223     NONE => []
   224   | SOME (Theory (gthy, _)) => if prf_only then [] else pretty_context gthy
   225   | SOME (Proof (prf, _)) =>
   226       Proof.pretty_state (ProofHistory.position prf) (ProofHistory.current prf)
   227   | SOME (SkipProof (h, _)) =>
   228       [Pretty.str ("skipped proof: depth " ^ string_of_int (History.current h))])
   229   |> Pretty.markup_chunks Markup.state |> Pretty.writeln;
   230 
   231 
   232 
   233 (** toplevel transitions **)
   234 
   235 val quiet = ref false;
   236 val debug = Output.debugging;
   237 val interact = ref false;
   238 val timing = Output.timing;
   239 val profiling = ref 0;
   240 val skip_proofs = ref false;
   241 
   242 exception TERMINATE;
   243 exception RESTART;
   244 exception EXCURSION_FAIL of exn * string;
   245 exception FAILURE of state * exn;
   246 exception TOPLEVEL_ERROR;
   247 
   248 
   249 (* print exceptions *)
   250 
   251 local
   252 
   253 fun with_context f xs =
   254   (case ML_Context.get_context () of NONE => []
   255   | SOME context => map (f (Context.proof_of context)) xs);
   256 
   257 fun raised name [] = "exception " ^ name ^ " raised"
   258   | raised name [msg] = "exception " ^ name ^ " raised: " ^ msg
   259   | raised name msgs = cat_lines (("exception " ^ name ^ " raised:") :: msgs);
   260 
   261 fun exn_msg _ TERMINATE = "Exit."
   262   | exn_msg _ RESTART = "Restart."
   263   | exn_msg _ Interrupt = "Interrupt."
   264   | exn_msg _ TOPLEVEL_ERROR = "Error."
   265   | exn_msg _ (SYS_ERROR msg) = "## SYSTEM ERROR ##\n" ^ msg
   266   | exn_msg _ (ERROR msg) = msg
   267   | exn_msg detailed (Exn.EXCEPTIONS (exns, "")) = cat_lines (map (exn_msg detailed) exns)
   268   | exn_msg detailed (Exn.EXCEPTIONS (exns, msg)) = cat_lines (map (exn_msg detailed) exns @ [msg])
   269   | exn_msg detailed (EXCURSION_FAIL (exn, msg)) = cat_lines [exn_msg detailed exn, msg]
   270   | exn_msg false (THEORY (msg, _)) = msg
   271   | exn_msg true (THEORY (msg, thys)) = raised "THEORY" (msg :: map Context.str_of_thy thys)
   272   | exn_msg false (Syntax.AST (msg, _)) = raised "AST" [msg]
   273   | exn_msg true (Syntax.AST (msg, asts)) =
   274       raised "AST" (msg :: map (Pretty.string_of o Syntax.pretty_ast) asts)
   275   | exn_msg false (TYPE (msg, _, _)) = raised "TYPE" [msg]
   276   | exn_msg true (TYPE (msg, Ts, ts)) = raised "TYPE" (msg ::
   277         with_context Syntax.string_of_typ Ts @ with_context Syntax.string_of_term ts)
   278   | exn_msg false (TERM (msg, _)) = raised "TERM" [msg]
   279   | exn_msg true (TERM (msg, ts)) =
   280       raised "TERM" (msg :: with_context Syntax.string_of_term ts)
   281   | exn_msg false (THM (msg, _, _)) = raised "THM" [msg]
   282   | exn_msg true (THM (msg, i, thms)) =
   283       raised ("THM " ^ string_of_int i) (msg :: with_context ProofContext.string_of_thm thms)
   284   | exn_msg _ Option.Option = raised "Option" []
   285   | exn_msg _ Library.UnequalLengths = raised "UnequalLengths" []
   286   | exn_msg _ Empty = raised "Empty" []
   287   | exn_msg _ Subscript = raised "Subscript" []
   288   | exn_msg _ (Fail msg) = raised "Fail" [msg]
   289   | exn_msg _ exn = General.exnMessage exn;
   290 
   291 in
   292 
   293 fun exn_message exn = exn_msg (! debug) exn;
   294 
   295 fun print_exn NONE = ()
   296   | print_exn (SOME (exn, s)) = Output.error_msg (cat_lines [exn_message exn, s]);
   297 
   298 end;
   299 
   300 
   301 (* controlled execution *)
   302 
   303 local
   304 
   305 fun debugging f x =
   306   if ! debug then exception_trace (fn () => f x)
   307   else f x;
   308 
   309 fun interruptible f x =
   310   let val y = ref NONE
   311   in raise_interrupt (fn () => y := SOME (f x)) (); the (! y) end;
   312 
   313 fun toplevel_error f x = f x
   314   handle exn => (Output.error_msg (exn_message exn); raise TOPLEVEL_ERROR);
   315 
   316 in
   317 
   318 fun controlled_execution f =
   319   f
   320   |> debugging
   321   |> interruptible;
   322 
   323 fun program f =
   324  (f
   325   |> debugging
   326   |> toplevel_error) ();
   327 
   328 end;
   329 
   330 
   331 (* node transactions and recovery from stale theories *)
   332 
   333 (*NB: proof commands should be non-destructive!*)
   334 
   335 local
   336 
   337 fun is_stale state = Context.is_stale (theory_of state) handle UNDEF => false;
   338 
   339 val stale_theory = ERROR "Stale theory encountered after succesful execution!";
   340 
   341 fun map_theory f = History.map_current
   342   (fn Theory (gthy, _) => Theory (Context.mapping f (LocalTheory.raw_theory f) gthy, NONE)
   343     | node => node);
   344 
   345 fun context_position pos = History.map_current
   346   (fn Theory (gthy, ctxt) => Theory (ContextPosition.put pos gthy, ctxt)
   347     | Proof (prf, x) =>
   348         Proof (ProofHistory.map_current (Proof.map_context (ContextPosition.put_ctxt pos)) prf, x)
   349     | node => node);
   350 
   351 fun return (result, NONE) = result
   352   | return (result, SOME exn) = raise FAILURE (result, exn);
   353 
   354 in
   355 
   356 fun transaction hist pos f (node, term) =
   357   let
   358     val cont_node = map_theory Theory.checkpoint node;
   359     val back_node = map_theory Theory.copy cont_node;
   360     fun state nd = State (nd, term);
   361     fun normal_state nd = (state nd, NONE);
   362     fun error_state nd exn = (state nd, SOME exn);
   363 
   364     val (result, err) =
   365       cont_node
   366       |> context_position pos
   367       |> map_theory Theory.checkpoint
   368       |> (f
   369           |> (if hist then History.apply' (History.current back_node) else History.map_current)
   370           |> controlled_execution)
   371       |> context_position Position.none
   372       |> normal_state
   373       handle exn => error_state cont_node exn;
   374   in
   375     if is_stale result
   376     then return (error_state back_node (the_default stale_theory err))
   377     else return (result, err)
   378   end;
   379 
   380 end;
   381 
   382 
   383 (* primitive transitions *)
   384 
   385 (*Note: Recovery from stale theories is provided only for theory-level
   386   operations via Transaction.  Other node or state operations should
   387   not touch theories at all.  Interrupts are enabled only for Keep and
   388   Transaction.*)
   389 
   390 datatype trans =
   391   Init of (bool -> theory) * ((theory -> unit) * (theory -> unit)) |
   392                                                     (*init node; with exit/kill operation*)
   393   InitEmpty of unit -> unit |                       (*init empty toplevel*)
   394   Exit |                                            (*conclude node -- deferred until init*)
   395   UndoExit |                                        (*continue after conclusion*)
   396   Kill |                                            (*abort node*)
   397   History of node History.T -> node History.T |     (*history operation (undo etc.)*)
   398   Keep of bool -> state -> unit |                   (*peek at state*)
   399   Transaction of bool * (bool -> node -> node);     (*node transaction*)
   400 
   401 fun undo_limit int = if int then NONE else SOME 0;
   402 
   403 fun safe_exit (Toplevel (SOME (node, (exit, _)))) =
   404     (case try the_global_theory (History.current node) of
   405       SOME thy => controlled_execution exit thy
   406     | NONE => ())
   407   | safe_exit _ = ();
   408 
   409 local
   410 
   411 fun keep_state int f = controlled_execution (fn x => tap (f int) x);
   412 
   413 fun apply_tr int _ (Init (f, term)) (state as Toplevel _) =
   414       let val node = Theory (Context.Theory (f int), NONE)
   415       in safe_exit state; State (History.init (undo_limit int) node, term) end
   416   | apply_tr int _ (InitEmpty f) (state as Toplevel _) =
   417       (safe_exit state; keep_state int (fn _ => fn _ => f ()) toplevel)
   418   | apply_tr _ _ Exit (State (node, term)) =
   419       (the_global_theory (History.current node); Toplevel (SOME (node, term)))
   420   | apply_tr _ _ UndoExit (Toplevel (SOME state_info)) = State state_info
   421   | apply_tr _ _ Kill (State (node, (_, kill))) =
   422       (kill (the_global_theory (History.current node)); toplevel)
   423   | apply_tr _ _ (History f) (State (node, term)) = State (f node, term)
   424   | apply_tr int _ (Keep f) state = keep_state int f state
   425   | apply_tr int pos (Transaction (hist, f)) (State state) =
   426       transaction hist pos (fn x => f int x) state
   427   | apply_tr _ _ _ _ = raise UNDEF;
   428 
   429 fun apply_union _ _ [] state = raise FAILURE (state, UNDEF)
   430   | apply_union int pos (tr :: trs) state =
   431       apply_tr int pos tr state
   432         handle UNDEF => apply_union int pos trs state
   433           | FAILURE (alt_state, UNDEF) => apply_union int pos trs alt_state
   434           | exn as FAILURE _ => raise exn
   435           | exn => raise FAILURE (state, exn);
   436 
   437 in
   438 
   439 fun apply_trans int pos trs state = (apply_union int pos trs state, NONE)
   440   handle FAILURE (alt_state, exn) => (alt_state, SOME exn) | exn => (state, SOME exn);
   441 
   442 end;
   443 
   444 
   445 (* datatype transition *)
   446 
   447 datatype transition = Transition of
   448  {name: string,                        (*command name*)
   449   pos: Position.T,                     (*source position*)
   450   source: OuterLex.token list option,  (*source text*)
   451   int_only: bool,                      (*interactive-only*)
   452   print: string list,                  (*print modes (union)*)
   453   no_timing: bool,                     (*suppress timing*)
   454   trans: trans list};                  (*primitive transitions (union)*)
   455 
   456 fun make_transition (name, pos, source, int_only, print, no_timing, trans) =
   457   Transition {name = name, pos = pos, source = source,
   458     int_only = int_only, print = print, no_timing = no_timing, trans = trans};
   459 
   460 fun map_transition f (Transition {name, pos, source, int_only, print, no_timing, trans}) =
   461   make_transition (f (name, pos, source, int_only, print, no_timing, trans));
   462 
   463 val empty = make_transition ("<unknown>", Position.none, NONE, false, [], false, []);
   464 
   465 fun name_of (Transition {name, ...}) = name;
   466 fun source_of (Transition {source, ...}) = source;
   467 
   468 
   469 (* diagnostics *)
   470 
   471 fun str_of_transition (Transition {name, pos, ...}) = quote name ^ Position.str_of pos;
   472 
   473 fun command_msg msg tr = msg ^ "command " ^ str_of_transition tr;
   474 fun at_command tr = command_msg "At " tr ^ ".";
   475 
   476 fun type_error tr state =
   477   ERROR (command_msg "Illegal application of " tr ^ " " ^ str_of_state state);
   478 
   479 
   480 (* modify transitions *)
   481 
   482 fun name nm = map_transition (fn (_, pos, source, int_only, print, no_timing, trans) =>
   483   (nm, pos, source, int_only, print, no_timing, trans));
   484 
   485 fun position pos = map_transition (fn (name, _, source, int_only, print, no_timing, trans) =>
   486   (name, pos, source, int_only, print, no_timing, trans));
   487 
   488 fun source src = map_transition (fn (name, pos, _, int_only, print, no_timing, trans) =>
   489   (name, pos, SOME src, int_only, print, no_timing, trans));
   490 
   491 fun interactive int_only = map_transition (fn (name, pos, source, _, print, no_timing, trans) =>
   492   (name, pos, source, int_only, print, no_timing, trans));
   493 
   494 val no_timing = map_transition (fn (name, pos, source, int_only, print, _, trans) =>
   495   (name, pos, source, int_only, print, true, trans));
   496 
   497 fun add_trans tr = map_transition (fn (name, pos, source, int_only, print, no_timing, trans) =>
   498   (name, pos, source, int_only, print, no_timing, trans @ [tr]));
   499 
   500 fun print' mode = map_transition (fn (name, pos, source, int_only, print, no_timing, trans) =>
   501   (name, pos, source, int_only, insert (op =) mode print, no_timing, trans));
   502 
   503 val print = print' "";
   504 
   505 val three_buffersN = "three_buffers";
   506 val print3 = print' three_buffersN;
   507 
   508 
   509 (* basic transitions *)
   510 
   511 fun init_theory f exit kill = add_trans (Init (f, (exit, kill)));
   512 val init_empty = add_trans o InitEmpty;
   513 val exit = add_trans Exit;
   514 val undo_exit = add_trans UndoExit;
   515 val kill = add_trans Kill;
   516 val history = add_trans o History;
   517 val keep' = add_trans o Keep;
   518 fun map_current f = add_trans (Transaction (false, f));
   519 fun app_current f = add_trans (Transaction (true, f));
   520 
   521 fun keep f = add_trans (Keep (fn _ => f));
   522 fun imperative f = keep (fn _ => f ());
   523 
   524 val unknown_theory = imperative (fn () => warning "Unknown theory context");
   525 val unknown_proof = imperative (fn () => warning "Unknown proof context");
   526 val unknown_context = imperative (fn () => warning "Unknown context");
   527 
   528 
   529 (* theory transitions *)
   530 
   531 fun theory' f = app_current (fn int =>
   532   (fn Theory (Context.Theory thy, _) => Theory (Context.Theory (f int thy), NONE)
   533     | _ => raise UNDEF));
   534 
   535 fun theory f = theory' (K f);
   536 
   537 fun begin_local_theory begin f = app_current (fn _ =>
   538   (fn Theory (Context.Theory thy, _) =>
   539         let
   540           val lthy = f thy;
   541           val gthy = if begin then Context.Proof lthy else Context.Theory (loc_exit lthy);
   542         in Theory (gthy, SOME lthy) end
   543     | _ => raise UNDEF));
   544 
   545 val end_local_theory = app_current (fn _ =>
   546   (fn Theory (Context.Proof lthy, _) => Theory (Context.Theory (loc_exit lthy), SOME lthy)
   547     | _ => raise UNDEF));
   548 
   549 local
   550 
   551 fun local_theory_presentation loc f g = app_current (fn int =>
   552   (fn Theory (gthy, _) =>
   553         let
   554           val pos = ContextPosition.get (Context.proof_of gthy);
   555           val finish = loc_finish loc gthy;
   556           val lthy' = f (ContextPosition.put_ctxt pos (loc_begin loc gthy));
   557         in Theory (finish lthy', SOME lthy') end
   558     | _ => raise UNDEF) #> tap (g int));
   559 
   560 in
   561 
   562 fun local_theory loc f = local_theory_presentation loc f (K I);
   563 fun present_local_theory loc g = local_theory_presentation loc I g;
   564 
   565 end;
   566 
   567 
   568 (* proof transitions *)
   569 
   570 fun end_proof f = map_current (fn int =>
   571   (fn Proof (prf, (finish, _)) =>
   572         let val state = ProofHistory.current prf in
   573           if can (Proof.assert_bottom true) state then
   574             let
   575               val ctxt' = f int state;
   576               val gthy' = finish ctxt';
   577             in Theory (gthy', SOME ctxt') end
   578           else raise UNDEF
   579         end
   580     | SkipProof (h, (gthy, _)) =>
   581         if History.current h = 0 then Theory (gthy, NONE) else raise UNDEF
   582     | _ => raise UNDEF));
   583 
   584 local
   585 
   586 fun begin_proof init finish = app_current (fn int =>
   587   (fn Theory (gthy, _) =>
   588     let
   589       val prf = init int gthy;
   590       val schematic = Proof.schematic_goal prf;
   591     in
   592       if ! skip_proofs andalso schematic then
   593         warning "Cannot skip proof of schematic goal statement"
   594       else ();
   595       if ! skip_proofs andalso not schematic then
   596         SkipProof
   597           (History.init (undo_limit int) 0, (finish gthy (Proof.global_skip_proof int prf), gthy))
   598       else Proof (ProofHistory.init (undo_limit int) prf, (finish gthy, gthy))
   599     end
   600   | _ => raise UNDEF));
   601 
   602 in
   603 
   604 fun local_theory_to_proof' loc f = begin_proof
   605   (fn int => fn gthy =>
   606     f int (ContextPosition.put_ctxt (ContextPosition.get (Context.proof_of gthy))
   607       (loc_begin loc gthy)))
   608   (loc_finish loc);
   609 
   610 fun local_theory_to_proof loc f = local_theory_to_proof' loc (K f);
   611 
   612 fun theory_to_proof f = begin_proof
   613   (K (fn Context.Theory thy => f thy | _ => raise UNDEF))
   614   (K (Context.Theory o ProofContext.theory_of));
   615 
   616 end;
   617 
   618 val forget_proof = map_current (fn _ =>
   619   (fn Proof (_, (_, orig_gthy)) => Theory (orig_gthy, NONE)
   620     | SkipProof (_, (_, orig_gthy)) => Theory (orig_gthy, NONE)
   621     | _ => raise UNDEF));
   622 
   623 fun present_proof f = map_current (fn int =>
   624   (fn Proof (prf, x) => Proof (ProofHistory.apply I prf, x)
   625     | SkipProof (h, x) => SkipProof (History.apply I h, x)
   626     | _ => raise UNDEF) #> tap (f int));
   627 
   628 fun proofs' f = map_current (fn int =>
   629   (fn Proof (prf, x) => Proof (ProofHistory.applys (f int) prf, x)
   630     | SkipProof (h, x) => SkipProof (History.apply I h, x)
   631     | _ => raise UNDEF));
   632 
   633 fun proof' f = proofs' (Seq.single oo f);
   634 val proofs = proofs' o K;
   635 val proof = proof' o K;
   636 
   637 fun actual_proof f = map_current (fn _ =>
   638   (fn Proof (prf, x) => Proof (f prf, x)
   639     | _ => raise UNDEF));
   640 
   641 fun skip_proof f = map_current (fn _ =>
   642   (fn SkipProof (h, x) => SkipProof (f h, x)
   643     | _ => raise UNDEF));
   644 
   645 fun skip_proof_to_theory p = map_current (fn _ =>
   646   (fn SkipProof (h, (gthy, _)) =>
   647     if p (History.current h) then Theory (gthy, NONE)
   648     else raise UNDEF
   649   | _ => raise UNDEF));
   650 
   651 
   652 
   653 (** toplevel transactions **)
   654 
   655 (* apply transitions *)
   656 
   657 local
   658 
   659 fun app int (tr as Transition {trans, pos, int_only, print, no_timing, ...}) state =
   660   let
   661     val _ =
   662       if not int andalso int_only then warning (command_msg "Interactive-only " tr)
   663       else ();
   664 
   665     fun do_timing f x = (warning (command_msg "" tr); timeap f x);
   666     fun do_profiling f x = profile (! profiling) f x;
   667 
   668     val (result, opt_exn) =
   669        state |> (apply_trans int pos trans
   670         |> (if ! profiling > 0 andalso not no_timing then do_profiling else I)
   671         |> (if ! profiling > 0 orelse ! timing andalso not no_timing then do_timing else I));
   672     val _ =
   673       if int andalso not (! quiet) andalso exists (member (op =) print) ("" :: print_mode_value ())
   674       then print_state false result else ();
   675   in (result, Option.map (fn UNDEF => type_error tr state | exn => exn) opt_exn) end;
   676 
   677 in
   678 
   679 fun apply int tr st =
   680   (case app int tr st of
   681     (_, SOME TERMINATE) => NONE
   682   | (_, SOME RESTART) => SOME (toplevel, NONE)
   683   | (state', SOME (EXCURSION_FAIL exn_info)) => SOME (state', SOME exn_info)
   684   | (state', SOME exn) => SOME (state', SOME (exn, at_command tr))
   685   | (state', NONE) => SOME (state', NONE));
   686 
   687 end;
   688 
   689 
   690 (* excursion: toplevel -- apply transformers/presentation -- toplevel *)
   691 
   692 local
   693 
   694 fun excur [] x = x
   695   | excur ((tr, pr) :: trs) (st, res) =
   696       (case apply (! interact) tr st of
   697         SOME (st', NONE) =>
   698           excur trs (st', pr st st' res handle exn =>
   699             raise EXCURSION_FAIL (exn, "Presentation failed\n" ^ at_command tr))
   700       | SOME (st', SOME exn_info) => raise EXCURSION_FAIL exn_info
   701       | NONE => raise EXCURSION_FAIL (TERMINATE, at_command tr));
   702 
   703 fun no_pr _ _ _ = ();
   704 
   705 in
   706 
   707 fun present_excursion trs res =
   708   (case excur trs (toplevel, res) of
   709     (state as Toplevel _, res') => (safe_exit state; res')
   710   | _ => error "Unfinished development at end of input")
   711   handle exn => error (exn_message exn);
   712 
   713 fun excursion trs = present_excursion (map (rpair no_pr) trs) ();
   714 
   715 end;
   716 
   717 
   718 
   719 (** interactive transformations **)
   720 
   721 (* the global state reference *)
   722 
   723 val global_state = ref (toplevel, NONE: (exn * string) option);
   724 
   725 fun set_state state = global_state := (state, NONE);
   726 fun get_state () = fst (! global_state);
   727 fun exn () = snd (! global_state);
   728 
   729 
   730 (* apply transformers to global state --- NOT THREAD-SAFE! *)
   731 
   732 nonfix >> >>>;
   733 
   734 fun >> tr =
   735   (case apply true tr (get_state ()) of
   736     NONE => false
   737   | SOME (state', exn_info) =>
   738       (global_state := (state', exn_info);
   739         print_exn exn_info;
   740         true));
   741 
   742 fun >>> [] = ()
   743   | >>> (tr :: trs) = if >> tr then >>> trs else ();
   744 
   745 fun init_state () = (>> (init_empty (K ()) empty); ());
   746 
   747 
   748 (* the Isar source of transitions *)
   749 
   750 type 'a isar =
   751   (transition, (transition option,
   752     (OuterLex.token, (OuterLex.token option, (OuterLex.token, (OuterLex.token,
   753       Position.T * (Symbol.symbol, (string, 'a) Source.source) Source.source)
   754           Source.source) Source.source) Source.source) Source.source) Source.source) Source.source;
   755 
   756 (*Spurious interrupts ahead!  Race condition?*)
   757 fun get_interrupt src = SOME (Source.get_single src) handle Interrupt => NONE;
   758 
   759 fun warn_secure () =
   760   let val secure = Secure.is_secure ()
   761   in if secure then warning "Cannot exit to ML in secure mode" else (); secure end;
   762 
   763 fun raw_loop src =
   764   let val prompt = Output.escape (Markup.enclose Markup.prompt Source.default_prompt) in
   765     (case get_interrupt (Source.set_prompt prompt src) of
   766       NONE => (writeln "\nInterrupt."; raw_loop src)
   767     | SOME NONE => if warn_secure () then quit () else ()
   768     | SOME (SOME (tr, src')) =>
   769         if >> tr orelse warn_secure () then raw_loop src'
   770         else ())
   771   end;
   772 
   773 fun loop src = ignore_interrupt raw_loop src;
   774 
   775 end;