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