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