src/Pure/Isar/toplevel.ML
author wenzelm
Thu Jan 13 17:34:45 2011 +0100 (2011-01-13)
changeset 41536 47fef6afe756
parent 40960 9e54eb514a46
child 41673 1c191a39549f
permissions -rw-r--r--
Toplevel.init_theory: maintain optional master directory, to allow bypassing global Thy_Load.master_path;
     1 (*  Title:      Pure/Isar/toplevel.ML
     2     Author:     Markus Wenzel, TU Muenchen
     3 
     4 Isabelle/Isar toplevel transactions.
     5 *)
     6 
     7 signature TOPLEVEL =
     8 sig
     9   exception UNDEF
    10   type state
    11   val toplevel: state
    12   val is_toplevel: state -> bool
    13   val is_theory: state -> bool
    14   val is_proof: state -> bool
    15   val level: state -> int
    16   val presentation_context_of: state -> Proof.context
    17   val previous_context_of: state -> Proof.context option
    18   val context_of: state -> Proof.context
    19   val generic_theory_of: state -> generic_theory
    20   val theory_of: state -> theory
    21   val proof_of: state -> Proof.state
    22   val proof_position_of: state -> int
    23   val end_theory: Position.T -> state -> theory
    24   val print_state_context: state -> unit
    25   val print_state: bool -> state -> unit
    26   val pretty_abstract: state -> Pretty.T
    27   val quiet: bool Unsynchronized.ref
    28   val debug: bool Unsynchronized.ref
    29   val interact: bool Unsynchronized.ref
    30   val timing: bool Unsynchronized.ref
    31   val profiling: int Unsynchronized.ref
    32   val skip_proofs: bool Unsynchronized.ref
    33   val program: (unit -> 'a) -> 'a
    34   val thread: bool -> (unit -> unit) -> Thread.thread
    35   type transition
    36   val empty: transition
    37   val init_of: transition -> string option
    38   val print_of: transition -> bool
    39   val name_of: transition -> string
    40   val pos_of: transition -> Position.T
    41   val str_of: transition -> string
    42   val name: string -> transition -> transition
    43   val position: Position.T -> transition -> transition
    44   val interactive: bool -> transition -> transition
    45   val set_print: bool -> transition -> transition
    46   val print: transition -> transition
    47   val no_timing: transition -> transition
    48   val init_theory: Path.T option -> string -> (Path.T option -> theory) -> transition -> transition
    49   val modify_master: Path.T option -> transition -> transition
    50   val modify_init: (Path.T option -> theory) -> transition -> transition
    51   val exit: transition -> transition
    52   val keep: (state -> unit) -> transition -> transition
    53   val keep': (bool -> state -> unit) -> transition -> transition
    54   val imperative: (unit -> unit) -> transition -> transition
    55   val ignored: Position.T -> transition
    56   val malformed: Position.T -> string -> transition
    57   val theory: (theory -> theory) -> transition -> transition
    58   val generic_theory: (generic_theory -> generic_theory) -> transition -> transition
    59   val theory': (bool -> theory -> theory) -> transition -> transition
    60   val begin_local_theory: bool -> (theory -> local_theory) -> transition -> transition
    61   val end_local_theory: transition -> transition
    62   val local_theory': xstring option -> (bool -> local_theory -> local_theory) ->
    63     transition -> transition
    64   val local_theory: xstring option -> (local_theory -> local_theory) -> transition -> transition
    65   val present_local_theory: xstring option -> (state -> unit) -> transition -> transition
    66   val local_theory_to_proof': xstring option -> (bool -> local_theory -> Proof.state) ->
    67     transition -> transition
    68   val local_theory_to_proof: xstring option -> (local_theory -> Proof.state) ->
    69     transition -> transition
    70   val theory_to_proof: (theory -> Proof.state) -> transition -> transition
    71   val end_proof: (bool -> Proof.state -> Proof.context) -> transition -> transition
    72   val forget_proof: transition -> transition
    73   val present_proof: (state -> unit) -> transition -> transition
    74   val proofs': (bool -> Proof.state -> Proof.state Seq.seq) -> transition -> transition
    75   val proof': (bool -> Proof.state -> Proof.state) -> transition -> transition
    76   val proofs: (Proof.state -> Proof.state Seq.seq) -> transition -> transition
    77   val proof: (Proof.state -> Proof.state) -> transition -> transition
    78   val actual_proof: (Proof_Node.T -> Proof_Node.T) -> transition -> transition
    79   val skip_proof: (int -> int) -> transition -> transition
    80   val skip_proof_to_theory: (int -> bool) -> transition -> transition
    81   val get_id: transition -> string option
    82   val put_id: string -> transition -> transition
    83   val unknown_theory: transition -> transition
    84   val unknown_proof: transition -> transition
    85   val unknown_context: transition -> transition
    86   val setmp_thread_position: transition -> ('a -> 'b) -> 'a -> 'b
    87   val status: transition -> Markup.T -> unit
    88   val error_msg: transition -> string -> unit
    89   val add_hook: (transition -> state -> state -> unit) -> unit
    90   val transition: bool -> transition -> state -> (state * (exn * string) option) option
    91   val command: transition -> state -> state
    92   val excursion: (transition * transition list) list -> (transition * state) list lazy * theory
    93 end;
    94 
    95 structure Toplevel: TOPLEVEL =
    96 struct
    97 
    98 (** toplevel state **)
    99 
   100 exception UNDEF = Runtime.UNDEF;
   101 
   102 
   103 (* local theory wrappers *)
   104 
   105 val loc_init = Named_Target.context_cmd;
   106 val loc_exit = Local_Theory.exit_global;
   107 
   108 fun loc_begin loc (Context.Theory thy) = loc_init (the_default "-" loc) thy
   109   | loc_begin NONE (Context.Proof lthy) = lthy
   110   | loc_begin (SOME loc) (Context.Proof lthy) = (loc_init loc o loc_exit) lthy;
   111 
   112 fun loc_finish _ (Context.Theory _) = Context.Theory o loc_exit
   113   | loc_finish NONE (Context.Proof _) = Context.Proof o Local_Theory.restore
   114   | loc_finish (SOME _) (Context.Proof lthy) = Context.Proof o Named_Target.reinit lthy;
   115 
   116 
   117 (* datatype node *)
   118 
   119 datatype node =
   120   Theory of generic_theory * Proof.context option
   121     (*theory with presentation context*) |
   122   Proof of Proof_Node.T * ((Proof.context -> generic_theory) * generic_theory)
   123     (*proof node, finish, original theory*) |
   124   SkipProof of int * (generic_theory * generic_theory);
   125     (*proof depth, resulting theory, original theory*)
   126 
   127 val theory_node = fn Theory (gthy, _) => SOME gthy | _ => NONE;
   128 val proof_node = fn Proof (prf, _) => SOME prf | _ => NONE;
   129 
   130 fun cases_node f _ (Theory (gthy, _)) = f gthy
   131   | cases_node _ g (Proof (prf, _)) = g (Proof_Node.current prf)
   132   | cases_node f _ (SkipProof (_, (gthy, _))) = f gthy;
   133 
   134 val context_node = cases_node Context.proof_of Proof.context_of;
   135 
   136 
   137 (* datatype state *)
   138 
   139 datatype state = State of node option * node option;  (*current, previous*)
   140 
   141 val toplevel = State (NONE, NONE);
   142 
   143 fun is_toplevel (State (NONE, _)) = true
   144   | is_toplevel _ = false;
   145 
   146 fun level (State (NONE, _)) = 0
   147   | level (State (SOME (Theory _), _)) = 0
   148   | level (State (SOME (Proof (prf, _)), _)) = Proof.level (Proof_Node.current prf)
   149   | level (State (SOME (SkipProof (d, _)), _)) = d + 1;   (*different notion of proof depth!*)
   150 
   151 fun str_of_state (State (NONE, _)) = "at top level"
   152   | str_of_state (State (SOME (Theory (Context.Theory _, _)), _)) = "in theory mode"
   153   | str_of_state (State (SOME (Theory (Context.Proof _, _)), _)) = "in local theory mode"
   154   | str_of_state (State (SOME (Proof _), _)) = "in proof mode"
   155   | str_of_state (State (SOME (SkipProof _), _)) = "in skipped proof mode";
   156 
   157 
   158 (* current node *)
   159 
   160 fun node_of (State (NONE, _)) = raise UNDEF
   161   | node_of (State (SOME node, _)) = node;
   162 
   163 fun is_theory state = not (is_toplevel state) andalso is_some (theory_node (node_of state));
   164 fun is_proof state = not (is_toplevel state) andalso is_some (proof_node (node_of state));
   165 
   166 fun node_case f g state = cases_node f g (node_of state);
   167 
   168 fun presentation_context_of state =
   169   (case try node_of state of
   170     SOME (Theory (_, SOME ctxt)) => ctxt
   171   | SOME node => context_node node
   172   | NONE => raise UNDEF);
   173 
   174 fun previous_context_of (State (_, NONE)) = NONE
   175   | previous_context_of (State (_, SOME prev)) = SOME (context_node prev);
   176 
   177 val context_of = node_case Context.proof_of Proof.context_of;
   178 val generic_theory_of = node_case I (Context.Proof o Proof.context_of);
   179 val theory_of = node_case Context.theory_of Proof.theory_of;
   180 val proof_of = node_case (fn _ => raise UNDEF) I;
   181 
   182 fun proof_position_of state =
   183   (case node_of state of
   184     Proof (prf, _) => Proof_Node.position prf
   185   | _ => raise UNDEF);
   186 
   187 fun end_theory _ (State (NONE, SOME (Theory (Context.Theory thy, _)))) = Theory.end_theory thy
   188   | end_theory pos _ = error ("Unfinished theory at end of input" ^ Position.str_of pos);
   189 
   190 
   191 (* print state *)
   192 
   193 val pretty_context = Local_Theory.pretty o Context.cases (Named_Target.theory_init) I;
   194 
   195 fun print_state_context state =
   196   (case try node_of state of
   197     NONE => []
   198   | SOME (Theory (gthy, _)) => pretty_context gthy
   199   | SOME (Proof (_, (_, gthy))) => pretty_context gthy
   200   | SOME (SkipProof (_, (gthy, _))) => pretty_context gthy)
   201   |> Pretty.chunks |> Pretty.writeln;
   202 
   203 fun print_state prf_only state =
   204   (case try node_of state of
   205     NONE => []
   206   | SOME (Theory (gthy, _)) => if prf_only then [] else pretty_context gthy
   207   | SOME (Proof (prf, _)) =>
   208       Proof.pretty_state (Proof_Node.position prf) (Proof_Node.current prf)
   209   | SOME (SkipProof (d, _)) => [Pretty.str ("skipped proof: depth " ^ string_of_int d)])
   210   |> Pretty.markup_chunks Markup.state |> Pretty.writeln;
   211 
   212 fun pretty_abstract state = Pretty.str ("<Isar " ^ str_of_state state ^ ">");
   213 
   214 
   215 
   216 (** toplevel transitions **)
   217 
   218 val quiet = Unsynchronized.ref false;
   219 val debug = Runtime.debug;
   220 val interact = Unsynchronized.ref false;
   221 val timing = Output.timing;
   222 val profiling = Unsynchronized.ref 0;
   223 val skip_proofs = Unsynchronized.ref false;
   224 
   225 fun program body =
   226  (body
   227   |> Runtime.controlled_execution
   228   |> Runtime.toplevel_error (Output.error_msg o ML_Compiler.exn_message)) ();
   229 
   230 fun thread interrupts body =
   231   Thread.fork
   232     (((fn () => body () handle exn => if Exn.is_interrupt exn then () else reraise exn)
   233         |> Runtime.debugging
   234         |> Runtime.toplevel_error
   235           (fn exn =>
   236             Output.urgent_message ("## INTERNAL ERROR ##\n" ^ ML_Compiler.exn_message exn))),
   237       Simple_Thread.attributes interrupts);
   238 
   239 
   240 (* node transactions -- maintaining stable checkpoints *)
   241 
   242 exception FAILURE of state * exn;
   243 
   244 local
   245 
   246 fun reset_presentation (Theory (gthy, _)) = Theory (gthy, NONE)
   247   | reset_presentation node = node;
   248 
   249 fun is_draft_theory (Theory (gthy, _)) = Context.is_draft (Context.theory_of gthy)
   250   | is_draft_theory _ = false;
   251 
   252 fun is_stale state = Context.is_stale (theory_of state) handle Runtime.UNDEF => false;
   253 
   254 fun stale_error NONE = SOME (ERROR "Stale theory encountered after successful execution!")
   255   | stale_error some = some;
   256 
   257 fun map_theory f (Theory (gthy, ctxt)) =
   258       Theory (Context.mapping f (Local_Theory.raw_theory f) gthy, ctxt)
   259   | map_theory _ node = node;
   260 
   261 in
   262 
   263 fun apply_transaction f g node =
   264   let
   265     val _ = is_draft_theory node andalso error "Illegal draft theory in toplevel state";
   266     val cont_node = reset_presentation node;
   267     val back_node = map_theory (Theory.checkpoint o Theory.copy) cont_node;
   268     fun state_error e nd = (State (SOME nd, SOME node), e);
   269 
   270     val (result, err) =
   271       cont_node
   272       |> Runtime.controlled_execution f
   273       |> map_theory Theory.checkpoint
   274       |> state_error NONE
   275       handle exn => state_error (SOME exn) cont_node;
   276 
   277     val (result', err') =
   278       if is_stale result then state_error (stale_error err) back_node
   279       else (result, err);
   280   in
   281     (case err' of
   282       NONE => tap g result'
   283     | SOME exn => raise FAILURE (result', exn))
   284   end;
   285 
   286 end;
   287 
   288 
   289 (* primitive transitions *)
   290 
   291 datatype trans =
   292   Init of Path.T option * string * (Path.T option -> theory) | (*master dir, theory name, init*)
   293   Exit |                                 (*formal exit of theory*)
   294   Keep of bool -> state -> unit |        (*peek at state*)
   295   Transaction of (bool -> node -> node) * (state -> unit);  (*node transaction and presentation*)
   296 
   297 local
   298 
   299 fun apply_tr _ (Init (master, _, f)) (State (NONE, _)) =
   300       State (SOME (Theory (Context.Theory
   301           (Theory.checkpoint (Runtime.controlled_execution f master)), NONE)), NONE)
   302   | apply_tr _ Exit (State (prev as SOME (Theory (Context.Theory _, _)), _)) =
   303       State (NONE, prev)
   304   | apply_tr int (Keep f) state =
   305       Runtime.controlled_execution (fn x => tap (f int) x) state
   306   | apply_tr int (Transaction (f, g)) (State (SOME state, _)) =
   307       apply_transaction (fn x => f int x) g state
   308   | apply_tr _ _ _ = raise UNDEF;
   309 
   310 fun apply_union _ [] state = raise FAILURE (state, UNDEF)
   311   | apply_union int (tr :: trs) state =
   312       apply_union int trs state
   313         handle Runtime.UNDEF => apply_tr int tr state
   314           | FAILURE (alt_state, UNDEF) => apply_tr int tr alt_state
   315           | exn as FAILURE _ => raise exn
   316           | exn => raise FAILURE (state, exn);
   317 
   318 in
   319 
   320 fun apply_trans int trs state = (apply_union int trs state, NONE)
   321   handle FAILURE (alt_state, exn) => (alt_state, SOME exn) | exn => (state, SOME exn);
   322 
   323 end;
   324 
   325 
   326 (* datatype transition *)
   327 
   328 datatype transition = Transition of
   329  {name: string,              (*command name*)
   330   pos: Position.T,           (*source position*)
   331   int_only: bool,            (*interactive-only*)
   332   print: bool,               (*print result state*)
   333   no_timing: bool,           (*suppress timing*)
   334   trans: trans list};        (*primitive transitions (union)*)
   335 
   336 fun make_transition (name, pos, int_only, print, no_timing, trans) =
   337   Transition {name = name, pos = pos, int_only = int_only, print = print, no_timing = no_timing,
   338     trans = trans};
   339 
   340 fun map_transition f (Transition {name, pos, int_only, print, no_timing, trans}) =
   341   make_transition (f (name, pos, int_only, print, no_timing, trans));
   342 
   343 val empty = make_transition ("", Position.none, false, false, false, []);
   344 
   345 
   346 (* diagnostics *)
   347 
   348 fun get_init (Transition {trans = [Init args], ...}) = SOME args
   349   | get_init _ = NONE;
   350 
   351 val init_of = Option.map #2 o get_init;
   352 fun print_of (Transition {print, ...}) = print;
   353 fun name_of (Transition {name, ...}) = name;
   354 fun pos_of (Transition {pos, ...}) = pos;
   355 fun str_of tr = quote (name_of tr) ^ Position.str_of (pos_of tr);
   356 
   357 fun command_msg msg tr = msg ^ "command " ^ str_of tr;
   358 fun at_command tr = command_msg "At " tr;
   359 
   360 fun type_error tr state =
   361   ERROR (command_msg "Illegal application of " tr ^ " " ^ str_of_state state);
   362 
   363 
   364 (* modify transitions *)
   365 
   366 fun name name = map_transition (fn (_, pos, int_only, print, no_timing, trans) =>
   367   (name, pos, int_only, print, no_timing, trans));
   368 
   369 fun position pos = map_transition (fn (name, _, int_only, print, no_timing, trans) =>
   370   (name, pos, int_only, print, no_timing, trans));
   371 
   372 fun interactive int_only = map_transition (fn (name, pos, _, print, no_timing, trans) =>
   373   (name, pos, int_only, print, no_timing, trans));
   374 
   375 val no_timing = map_transition (fn (name, pos, int_only, print, _, trans) =>
   376   (name, pos, int_only, print, true, trans));
   377 
   378 fun add_trans tr = map_transition (fn (name, pos, int_only, print, no_timing, trans) =>
   379   (name, pos, int_only, print, no_timing, tr :: trans));
   380 
   381 val reset_trans = map_transition (fn (name, pos, int_only, print, no_timing, _) =>
   382   (name, pos, int_only, print, no_timing, []));
   383 
   384 fun set_print print = map_transition (fn (name, pos, int_only, _, no_timing, trans) =>
   385   (name, pos, int_only, print, no_timing, trans));
   386 
   387 val print = set_print true;
   388 
   389 
   390 (* basic transitions *)
   391 
   392 fun init_theory master name f = add_trans (Init (master, name, f));
   393 
   394 fun modify_master master tr =
   395   (case get_init tr of
   396     SOME (_, name, f) => init_theory master name f (reset_trans tr)
   397   | NONE => tr);
   398 
   399 fun modify_init f tr =
   400   (case get_init tr of
   401     SOME (master, name, _) => init_theory master name f (reset_trans tr)
   402   | NONE => tr);
   403 
   404 val exit = add_trans Exit;
   405 val keep' = add_trans o Keep;
   406 
   407 fun present_transaction f g = add_trans (Transaction (f, g));
   408 fun transaction f = present_transaction f (K ());
   409 
   410 fun keep f = add_trans (Keep (fn _ => f));
   411 fun imperative f = keep (fn _ => f ());
   412 
   413 fun ignored pos = empty |> name "<ignored>" |> position pos |> imperative I;
   414 fun malformed pos msg =
   415   empty |> name "<malformed>" |> position pos |> imperative (fn () => error msg);
   416 
   417 val unknown_theory = imperative (fn () => warning "Unknown theory context");
   418 val unknown_proof = imperative (fn () => warning "Unknown proof context");
   419 val unknown_context = imperative (fn () => warning "Unknown context");
   420 
   421 
   422 (* theory transitions *)
   423 
   424 fun generic_theory f = transaction (fn _ =>
   425   (fn Theory (gthy, _) => Theory (f gthy, NONE)
   426     | _ => raise UNDEF));
   427 
   428 fun theory' f = transaction (fn int =>
   429   (fn Theory (Context.Theory thy, _) =>
   430       let val thy' = thy
   431         |> Sign.new_group
   432         |> Theory.checkpoint
   433         |> f int
   434         |> Sign.reset_group;
   435       in Theory (Context.Theory thy', NONE) end
   436     | _ => raise UNDEF));
   437 
   438 fun theory f = theory' (K f);
   439 
   440 fun begin_local_theory begin f = transaction (fn _ =>
   441   (fn Theory (Context.Theory thy, _) =>
   442         let
   443           val lthy = f thy;
   444           val gthy = if begin then Context.Proof lthy else Context.Theory (loc_exit lthy);
   445         in Theory (gthy, SOME lthy) end
   446     | _ => raise UNDEF));
   447 
   448 val end_local_theory = transaction (fn _ =>
   449   (fn Theory (Context.Proof lthy, _) => Theory (Context.Theory (loc_exit lthy), SOME lthy)
   450     | _ => raise UNDEF));
   451 
   452 local
   453 
   454 fun local_theory_presentation loc f = present_transaction (fn int =>
   455   (fn Theory (gthy, _) =>
   456         let
   457           val finish = loc_finish loc gthy;
   458           val lthy' = loc_begin loc gthy
   459             |> Local_Theory.new_group
   460             |> f int
   461             |> Local_Theory.reset_group;
   462         in Theory (finish lthy', SOME lthy') end
   463     | _ => raise UNDEF));
   464 
   465 in
   466 
   467 fun local_theory' loc f = local_theory_presentation loc f (K ());
   468 fun local_theory loc f = local_theory' loc (K f);
   469 fun present_local_theory loc = local_theory_presentation loc (K I);
   470 
   471 end;
   472 
   473 
   474 (* proof transitions *)
   475 
   476 fun end_proof f = transaction (fn int =>
   477   (fn Proof (prf, (finish, _)) =>
   478         let val state = Proof_Node.current prf in
   479           if can (Proof.assert_bottom true) state then
   480             let
   481               val ctxt' = f int state;
   482               val gthy' = finish ctxt';
   483             in Theory (gthy', SOME ctxt') end
   484           else raise UNDEF
   485         end
   486     | SkipProof (0, (gthy, _)) => Theory (gthy, NONE)
   487     | _ => raise UNDEF));
   488 
   489 local
   490 
   491 fun begin_proof init finish = transaction (fn int =>
   492   (fn Theory (gthy, _) =>
   493     let
   494       val prf = init int gthy;
   495       val skip = ! skip_proofs;
   496       val (is_goal, no_skip) =
   497         (true, Proof.schematic_goal prf) handle ERROR _ => (false, true);
   498     in
   499       if is_goal andalso skip andalso no_skip then
   500         warning "Cannot skip proof of schematic goal statement"
   501       else ();
   502       if skip andalso not no_skip then
   503         SkipProof (0, (finish gthy (Proof.global_skip_proof int prf), gthy))
   504       else Proof (Proof_Node.init prf, (finish gthy, gthy))
   505     end
   506   | _ => raise UNDEF));
   507 
   508 in
   509 
   510 fun local_theory_to_proof' loc f = begin_proof
   511   (fn int => fn gthy => f int (Local_Theory.new_group (loc_begin loc gthy)))
   512   (fn gthy => loc_finish loc gthy o Local_Theory.reset_group);
   513 
   514 fun local_theory_to_proof loc f = local_theory_to_proof' loc (K f);
   515 
   516 fun theory_to_proof f = begin_proof
   517   (K (fn Context.Theory thy => f (Theory.checkpoint (Sign.new_group thy)) | _ => raise UNDEF))
   518   (K (Context.Theory o Sign.reset_group o ProofContext.theory_of));
   519 
   520 end;
   521 
   522 val forget_proof = transaction (fn _ =>
   523   (fn Proof (_, (_, orig_gthy)) => Theory (orig_gthy, NONE)
   524     | SkipProof (_, (_, orig_gthy)) => Theory (orig_gthy, NONE)
   525     | _ => raise UNDEF));
   526 
   527 val present_proof = present_transaction (fn _ =>
   528   (fn Proof (prf, x) => Proof (Proof_Node.apply I prf, x)
   529     | skip as SkipProof _ => skip
   530     | _ => raise UNDEF));
   531 
   532 fun proofs' f = transaction (fn int =>
   533   (fn Proof (prf, x) => Proof (Proof_Node.applys (f int) prf, x)
   534     | skip as SkipProof _ => skip
   535     | _ => raise UNDEF));
   536 
   537 fun proof' f = proofs' (Seq.single oo f);
   538 val proofs = proofs' o K;
   539 val proof = proof' o K;
   540 
   541 fun actual_proof f = transaction (fn _ =>
   542   (fn Proof (prf, x) => Proof (f prf, x)
   543     | _ => raise UNDEF));
   544 
   545 fun skip_proof f = transaction (fn _ =>
   546   (fn SkipProof (h, x) => SkipProof (f h, x)
   547     | _ => raise UNDEF));
   548 
   549 fun skip_proof_to_theory pred = transaction (fn _ =>
   550   (fn SkipProof (d, (gthy, _)) => if pred d then Theory (gthy, NONE) else raise UNDEF
   551     | _ => raise UNDEF));
   552 
   553 
   554 
   555 (** toplevel transactions **)
   556 
   557 (* identification *)
   558 
   559 fun get_id (Transition {pos, ...}) = Position.get_id pos;
   560 fun put_id id (tr as Transition {pos, ...}) = position (Position.put_id id pos) tr;
   561 
   562 
   563 (* thread position *)
   564 
   565 fun setmp_thread_position (Transition {pos, ...}) f x =
   566   Position.setmp_thread_data pos f x;
   567 
   568 fun status tr m =
   569   setmp_thread_position tr (fn () => Output.status (Markup.markup m "")) ();
   570 
   571 fun error_msg tr msg =
   572   setmp_thread_position tr (fn () => Output.error_msg msg) ();
   573 
   574 
   575 (* post-transition hooks *)
   576 
   577 local
   578   val hooks = Unsynchronized.ref ([]: (transition -> state -> state -> unit) list);
   579 in
   580 
   581 fun add_hook f = CRITICAL (fn () => Unsynchronized.change hooks (cons f));
   582 fun get_hooks () = ! hooks;
   583 
   584 end;
   585 
   586 
   587 (* apply transitions *)
   588 
   589 local
   590 
   591 fun app int (tr as Transition {trans, print, no_timing, ...}) =
   592   setmp_thread_position tr (fn state =>
   593     let
   594       fun do_timing f x = (warning (command_msg "" tr); timeap f x);
   595       fun do_profiling f x = profile (! profiling) f x;
   596 
   597       val (result, status) =
   598          state |>
   599           (apply_trans int trans
   600             |> (! profiling > 0 andalso not no_timing) ? do_profiling
   601             |> (! profiling > 0 orelse ! timing andalso not no_timing) ? do_timing);
   602 
   603       val _ = if int andalso not (! quiet) andalso print then print_state false result else ();
   604     in (result, Option.map (fn UNDEF => type_error tr state | exn => exn) status) end);
   605 
   606 in
   607 
   608 fun transition int tr st =
   609   let
   610     val hooks = get_hooks ();
   611     fun apply_hooks st' = hooks |> List.app (fn f => (try (fn () => f tr st st') (); ()));
   612 
   613     val ctxt = try context_of st;
   614     val res =
   615       (case app int tr st of
   616         (_, SOME Runtime.TERMINATE) => NONE
   617       | (st', SOME (Runtime.EXCURSION_FAIL exn_info)) => SOME (st', SOME exn_info)
   618       | (st', SOME exn) => SOME (st', SOME (Runtime.exn_context ctxt exn, at_command tr))
   619       | (st', NONE) => SOME (st', NONE));
   620     val _ = (case res of SOME (st', NONE) => apply_hooks st' | _ => ());
   621   in res end;
   622 
   623 end;
   624 
   625 
   626 (* nested commands *)
   627 
   628 fun command tr st =
   629   (case transition (! interact) tr st of
   630     SOME (st', NONE) => st'
   631   | SOME (_, SOME (exn, info)) =>
   632       if Exn.is_interrupt exn then reraise exn else raise Runtime.EXCURSION_FAIL (exn, info)
   633   | NONE => raise Runtime.EXCURSION_FAIL (Runtime.TERMINATE, at_command tr));
   634 
   635 fun command_result tr st =
   636   let val st' = command tr st
   637   in (st', st') end;
   638 
   639 
   640 (* excursion of units, consisting of commands with proof *)
   641 
   642 structure States = Proof_Data
   643 (
   644   type T = state list future option;
   645   fun init _ = NONE;
   646 );
   647 
   648 fun proof_result immediate (tr, proof_trs) st =
   649   let val st' = command tr st in
   650     if immediate orelse
   651       null proof_trs orelse
   652       Keyword.is_schematic_goal (name_of tr) orelse
   653       exists (Keyword.is_qed_global o name_of) proof_trs orelse
   654       not (can proof_of st') orelse
   655       Proof.is_relevant (proof_of st')
   656     then
   657       let val (states, st'') = fold_map command_result proof_trs st'
   658       in (Lazy.value ((tr, st') :: (proof_trs ~~ states)), st'') end
   659     else
   660       let
   661         val (body_trs, end_tr) = split_last proof_trs;
   662         val finish = Context.Theory o ProofContext.theory_of;
   663 
   664         val future_proof = Proof.global_future_proof
   665           (fn prf =>
   666             Future.fork_pri ~1 (fn () =>
   667               let val (states, result_state) =
   668                 (case st' of State (SOME (Proof (_, (_, orig_gthy))), prev)
   669                   => State (SOME (Proof (Proof_Node.init prf, (finish, orig_gthy))), prev))
   670                 |> fold_map command_result body_trs
   671                 ||> command (end_tr |> set_print false);
   672               in (states, presentation_context_of result_state) end))
   673           #> (fn (states, ctxt) => States.put (SOME states) ctxt);
   674 
   675         val st'' = st' |> command (end_tr |> reset_trans |> end_proof (K future_proof));
   676 
   677         val states =
   678           (case States.get (presentation_context_of st'') of
   679             NONE => raise Fail ("No future states for " ^ name_of tr ^ Position.str_of (pos_of tr))
   680           | SOME states => states);
   681         val result = Lazy.lazy
   682           (fn () => (tr, st') :: (body_trs ~~ Future.join states) @ [(end_tr, st'')]);
   683 
   684       in (result, st'') end
   685   end;
   686 
   687 fun excursion input =
   688   let
   689     val end_pos = if null input then error "No input" else pos_of (fst (List.last input));
   690     val immediate = not (Goal.future_enabled ());
   691     val (results, end_state) = fold_map (proof_result immediate) input toplevel;
   692     val thy = end_theory end_pos end_state;
   693   in (Lazy.lazy (fn () => maps Lazy.force results), thy) end;
   694 
   695 end;