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