src/Pure/Isar/toplevel.ML
author wenzelm
Tue Apr 09 15:59:02 2013 +0200 (2013-04-09 ago)
changeset 51661 92e58b76dbb1
parent 51658 21c10672633b
child 51662 3391a493f39a
permissions -rw-r--r--
clarified protocol_message undefinedness;
     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 is_skipped_proof: state -> bool
    16   val level: state -> int
    17   val presentation_context_of: state -> Proof.context
    18   val previous_context_of: state -> Proof.context option
    19   val context_of: state -> Proof.context
    20   val generic_theory_of: state -> generic_theory
    21   val theory_of: state -> theory
    22   val proof_of: state -> Proof.state
    23   val proof_position_of: state -> int
    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 program: (unit -> 'a) -> 'a
    34   val thread: bool -> (unit -> unit) -> Thread.thread
    35   type transition
    36   val empty: transition
    37   val print_of: transition -> bool
    38   val name_of: transition -> string
    39   val pos_of: transition -> Position.T
    40   val name: string -> transition -> transition
    41   val position: Position.T -> transition -> transition
    42   val interactive: bool -> transition -> transition
    43   val set_print: bool -> transition -> transition
    44   val print: transition -> transition
    45   val init_theory: (unit -> theory) -> transition -> transition
    46   val is_init: transition -> bool
    47   val modify_init: (unit -> theory) -> transition -> transition
    48   val exit: transition -> transition
    49   val keep: (state -> unit) -> transition -> transition
    50   val keep': (bool -> state -> unit) -> transition -> transition
    51   val imperative: (unit -> unit) -> transition -> transition
    52   val ignored: Position.T -> transition
    53   val is_ignored: transition -> bool
    54   val malformed: Position.T -> string -> transition
    55   val is_malformed: transition -> bool
    56   val generic_theory: (generic_theory -> generic_theory) -> transition -> transition
    57   val theory': (bool -> theory -> theory) -> transition -> transition
    58   val theory: (theory -> theory) -> transition -> transition
    59   val begin_local_theory: bool -> (theory -> local_theory) -> transition -> transition
    60   val end_local_theory: transition -> transition
    61   val open_target: (generic_theory -> local_theory) -> transition -> transition
    62   val close_target: transition -> transition
    63   val local_theory': (xstring * Position.T) option -> (bool -> local_theory -> local_theory) ->
    64     transition -> transition
    65   val local_theory: (xstring * Position.T) option -> (local_theory -> local_theory) ->
    66     transition -> transition
    67   val present_local_theory: (xstring * Position.T) option -> (state -> unit) ->
    68     transition -> transition
    69   val local_theory_to_proof': (xstring * Position.T) option ->
    70     (bool -> local_theory -> Proof.state) -> transition -> transition
    71   val local_theory_to_proof: (xstring * Position.T) option ->
    72     (local_theory -> Proof.state) -> transition -> transition
    73   val theory_to_proof: (theory -> Proof.state) -> transition -> transition
    74   val end_proof: (bool -> Proof.state -> Proof.context) -> transition -> transition
    75   val forget_proof: transition -> transition
    76   val present_proof: (state -> unit) -> transition -> transition
    77   val proofs': (bool -> Proof.state -> Proof.state Seq.result Seq.seq) -> transition -> transition
    78   val proof': (bool -> Proof.state -> Proof.state) -> transition -> transition
    79   val proofs: (Proof.state -> Proof.state Seq.result Seq.seq) -> transition -> transition
    80   val proof: (Proof.state -> Proof.state) -> transition -> transition
    81   val actual_proof: (Proof_Node.T -> Proof_Node.T) -> transition -> transition
    82   val skip_proof: (int -> int) -> transition -> transition
    83   val skip_proof_to_theory: (int -> bool) -> transition -> transition
    84   val get_id: transition -> string option
    85   val put_id: string -> transition -> transition
    86   val unknown_theory: transition -> transition
    87   val unknown_proof: transition -> transition
    88   val unknown_context: transition -> transition
    89   val setmp_thread_position: transition -> ('a -> 'b) -> 'a -> 'b
    90   val status: transition -> Markup.T -> unit
    91   val add_hook: (transition -> state -> state -> unit) -> unit
    92   val approximative_id: transition -> {file: string, offset: int, name: string} option
    93   val get_timing: transition -> Time.time option
    94   val put_timing: Time.time option -> transition -> transition
    95   val transition: bool -> transition -> state -> (state * (exn * string) option) option
    96   val command_errors: bool -> transition -> state -> Runtime.error list * state option
    97   val command_exception: bool -> transition -> state -> state
    98   type result
    99   val join_results: result -> (transition * state) list
   100   val element_result: transition Thy_Syntax.element -> state -> result * state
   101 end;
   102 
   103 structure Toplevel: TOPLEVEL =
   104 struct
   105 
   106 (** toplevel state **)
   107 
   108 exception UNDEF = Runtime.UNDEF;
   109 
   110 
   111 (* local theory wrappers *)
   112 
   113 val loc_init = Named_Target.context_cmd;
   114 val loc_exit = Local_Theory.assert_bottom true #> Local_Theory.exit_global;
   115 
   116 fun loc_begin loc (Context.Theory thy) =
   117       (Context.Theory o loc_exit, loc_init (the_default ("-", Position.none) loc) thy)
   118   | loc_begin NONE (Context.Proof lthy) =
   119       (Context.Proof o Local_Theory.restore, lthy)
   120   | loc_begin (SOME loc) (Context.Proof lthy) =
   121       (Context.Proof o Named_Target.reinit lthy, loc_init loc (loc_exit lthy));
   122 
   123 
   124 (* datatype node *)
   125 
   126 datatype node =
   127   Theory of generic_theory * Proof.context option
   128     (*theory with presentation context*) |
   129   Proof of Proof_Node.T * ((Proof.context -> generic_theory) * generic_theory)
   130     (*proof node, finish, original theory*) |
   131   Skipped_Proof of int * (generic_theory * generic_theory);
   132     (*proof depth, resulting theory, original theory*)
   133 
   134 val theory_node = fn Theory (gthy, _) => SOME gthy | _ => NONE;
   135 val proof_node = fn Proof (prf, _) => SOME prf | _ => NONE;
   136 val skipped_proof_node = fn Skipped_Proof _ => true | _ => false;
   137 
   138 fun cases_node f _ (Theory (gthy, _)) = f gthy
   139   | cases_node _ g (Proof (prf, _)) = g (Proof_Node.current prf)
   140   | cases_node f _ (Skipped_Proof (_, (gthy, _))) = f gthy;
   141 
   142 val context_node = cases_node Context.proof_of Proof.context_of;
   143 
   144 
   145 (* datatype state *)
   146 
   147 datatype state = State of node option * node option;  (*current, previous*)
   148 
   149 val toplevel = State (NONE, NONE);
   150 
   151 fun is_toplevel (State (NONE, _)) = true
   152   | is_toplevel _ = false;
   153 
   154 fun level (State (NONE, _)) = 0
   155   | level (State (SOME (Theory _), _)) = 0
   156   | level (State (SOME (Proof (prf, _)), _)) = Proof.level (Proof_Node.current prf)
   157   | level (State (SOME (Skipped_Proof (d, _)), _)) = d + 1;   (*different notion of proof depth!*)
   158 
   159 fun str_of_state (State (NONE, _)) = "at top level"
   160   | str_of_state (State (SOME (Theory (Context.Theory _, _)), _)) = "in theory mode"
   161   | str_of_state (State (SOME (Theory (Context.Proof _, _)), _)) = "in local theory mode"
   162   | str_of_state (State (SOME (Proof _), _)) = "in proof mode"
   163   | str_of_state (State (SOME (Skipped_Proof _), _)) = "in skipped proof mode";
   164 
   165 
   166 (* current node *)
   167 
   168 fun node_of (State (NONE, _)) = raise UNDEF
   169   | node_of (State (SOME node, _)) = node;
   170 
   171 fun is_theory state = not (is_toplevel state) andalso is_some (theory_node (node_of state));
   172 fun is_proof state = not (is_toplevel state) andalso is_some (proof_node (node_of state));
   173 fun is_skipped_proof state = not (is_toplevel state) andalso skipped_proof_node (node_of state);
   174 
   175 fun node_case f g state = cases_node f g (node_of state);
   176 
   177 fun presentation_context_of state =
   178   (case try node_of state of
   179     SOME (Theory (_, SOME ctxt)) => ctxt
   180   | SOME node => context_node node
   181   | NONE => raise UNDEF);
   182 
   183 fun previous_context_of (State (_, NONE)) = NONE
   184   | previous_context_of (State (_, SOME prev)) = SOME (context_node prev);
   185 
   186 val context_of = node_case Context.proof_of Proof.context_of;
   187 val generic_theory_of = node_case I (Context.Proof o Proof.context_of);
   188 val theory_of = node_case Context.theory_of Proof.theory_of;
   189 val proof_of = node_case (fn _ => raise UNDEF) I;
   190 
   191 fun proof_position_of state =
   192   (case node_of state of
   193     Proof (prf, _) => Proof_Node.position prf
   194   | _ => raise UNDEF);
   195 
   196 fun end_theory _ (State (NONE, SOME (Theory (Context.Theory thy, _)))) = thy
   197   | end_theory pos (State (NONE, _)) = error ("Bad theory" ^ Position.here pos)
   198   | end_theory pos (State (SOME _, _)) = error ("Unfinished theory" ^ Position.here pos);
   199 
   200 
   201 (* print state *)
   202 
   203 val pretty_context = Local_Theory.pretty o Context.cases (Named_Target.theory_init) I;
   204 
   205 fun print_state_context state =
   206   (case try node_of state of
   207     NONE => []
   208   | SOME (Theory (gthy, _)) => pretty_context gthy
   209   | SOME (Proof (_, (_, gthy))) => pretty_context gthy
   210   | SOME (Skipped_Proof (_, (gthy, _))) => pretty_context gthy)
   211   |> Pretty.chunks |> Pretty.writeln;
   212 
   213 fun print_state prf_only state =
   214   (case try node_of state of
   215     NONE => []
   216   | SOME (Theory (gthy, _)) => if prf_only then [] else pretty_context gthy
   217   | SOME (Proof (prf, _)) =>
   218       Proof.pretty_state (Proof_Node.position prf) (Proof_Node.current prf)
   219   | SOME (Skipped_Proof (d, _)) => [Pretty.str ("skipped proof: depth " ^ string_of_int d)])
   220   |> Pretty.markup_chunks Markup.state |> Pretty.writeln;
   221 
   222 fun pretty_abstract state = Pretty.str ("<Isar " ^ str_of_state state ^ ">");
   223 
   224 
   225 
   226 (** toplevel transitions **)
   227 
   228 val quiet = Unsynchronized.ref false;
   229 val debug = Runtime.debug;
   230 val interact = Unsynchronized.ref false;
   231 val timing = Unsynchronized.ref false;
   232 val profiling = Unsynchronized.ref 0;
   233 
   234 fun program body =
   235  (body
   236   |> Runtime.controlled_execution
   237   |> Runtime.toplevel_error (Output.error_msg o ML_Compiler.exn_message)) ();
   238 
   239 fun thread interrupts body =
   240   Thread.fork
   241     (((fn () => body () handle exn => if Exn.is_interrupt exn then () else reraise exn)
   242         |> Runtime.debugging
   243         |> Runtime.toplevel_error
   244           (fn exn =>
   245             Output.urgent_message ("## 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 val exit_transaction =
   296   apply_transaction
   297     (fn Theory (Context.Theory thy, _) => Theory (Context.Theory (Theory.end_theory thy), NONE)
   298       | node => node) (K ())
   299   #> (fn State (node', _) => State (NONE, node'));
   300 
   301 end;
   302 
   303 
   304 (* primitive transitions *)
   305 
   306 datatype trans =
   307   Init of unit -> theory |               (*init theory*)
   308   Exit |                                 (*formal exit of theory*)
   309   Keep of bool -> state -> unit |        (*peek at state*)
   310   Transaction of (bool -> node -> node) * (state -> unit);  (*node transaction and presentation*)
   311 
   312 local
   313 
   314 fun apply_tr _ (Init f) (State (NONE, _)) =
   315       State (SOME (Theory (Context.Theory
   316           (Theory.checkpoint (Runtime.controlled_execution f ())), NONE)), NONE)
   317   | apply_tr _ Exit (State (SOME (state as Theory (Context.Theory _, _)), _)) =
   318       exit_transaction state
   319   | apply_tr int (Keep f) state =
   320       Runtime.controlled_execution (fn x => tap (f int) x) state
   321   | apply_tr int (Transaction (f, g)) (State (SOME state, _)) =
   322       apply_transaction (fn x => f int x) g state
   323   | apply_tr _ _ _ = raise UNDEF;
   324 
   325 fun apply_union _ [] state = raise FAILURE (state, UNDEF)
   326   | apply_union int (tr :: trs) state =
   327       apply_union int trs state
   328         handle Runtime.UNDEF => apply_tr int tr state
   329           | FAILURE (alt_state, UNDEF) => apply_tr int tr alt_state
   330           | exn as FAILURE _ => raise exn
   331           | exn => raise FAILURE (state, exn);
   332 
   333 in
   334 
   335 fun apply_trans int trs state = (apply_union int trs state, NONE)
   336   handle FAILURE (alt_state, exn) => (alt_state, SOME exn) | exn => (state, SOME exn);
   337 
   338 end;
   339 
   340 
   341 (* datatype transition *)
   342 
   343 datatype transition = Transition of
   344  {name: string,              (*command name*)
   345   pos: Position.T,           (*source position*)
   346   int_only: bool,            (*interactive-only*)
   347   print: bool,               (*print result state*)
   348   timing: Time.time option,  (*prescient timing information*)
   349   trans: trans list};        (*primitive transitions (union)*)
   350 
   351 fun make_transition (name, pos, int_only, print, timing, trans) =
   352   Transition {name = name, pos = pos, int_only = int_only, print = print,
   353     timing = timing, trans = trans};
   354 
   355 fun map_transition f (Transition {name, pos, int_only, print, timing, trans}) =
   356   make_transition (f (name, pos, int_only, print, timing, trans));
   357 
   358 val empty = make_transition ("", Position.none, false, false, NONE, []);
   359 
   360 
   361 (* diagnostics *)
   362 
   363 fun print_of (Transition {print, ...}) = print;
   364 fun name_of (Transition {name, ...}) = name;
   365 fun pos_of (Transition {pos, ...}) = pos;
   366 
   367 fun command_msg msg tr = msg ^ "command " ^ quote (name_of tr) ^ Position.here (pos_of tr);
   368 fun at_command tr = command_msg "At " tr;
   369 
   370 fun type_error tr state =
   371   ERROR (command_msg "Illegal application of " tr ^ " " ^ str_of_state state);
   372 
   373 
   374 (* modify transitions *)
   375 
   376 fun name name = map_transition (fn (_, pos, int_only, print, timing, trans) =>
   377   (name, pos, int_only, print, timing, trans));
   378 
   379 fun position pos = map_transition (fn (name, _, int_only, print, timing, trans) =>
   380   (name, pos, int_only, print, timing, trans));
   381 
   382 fun interactive int_only = map_transition (fn (name, pos, _, print, timing, trans) =>
   383   (name, pos, int_only, print, timing, trans));
   384 
   385 fun add_trans tr = map_transition (fn (name, pos, int_only, print, timing, trans) =>
   386   (name, pos, int_only, print, timing, tr :: trans));
   387 
   388 val reset_trans = map_transition (fn (name, pos, int_only, print, timing, _) =>
   389   (name, pos, int_only, print, timing, []));
   390 
   391 fun set_print print = map_transition (fn (name, pos, int_only, _, timing, trans) =>
   392   (name, pos, int_only, print, timing, trans));
   393 
   394 val print = set_print true;
   395 
   396 
   397 (* basic transitions *)
   398 
   399 fun init_theory f = add_trans (Init f);
   400 
   401 fun is_init (Transition {trans = [Init _], ...}) = true
   402   | is_init _ = false;
   403 
   404 fun modify_init f tr = if is_init tr then init_theory f (reset_trans tr) else 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 is_ignored tr = name_of tr = "<ignored>";
   417 
   418 val malformed_name = "<malformed>";
   419 fun malformed pos msg =
   420   empty |> name malformed_name |> position pos |> imperative (fn () => error msg);
   421 fun is_malformed tr = name_of tr = malformed_name;
   422 
   423 val unknown_theory = imperative (fn () => warning "Unknown theory context");
   424 val unknown_proof = imperative (fn () => warning "Unknown proof context");
   425 val unknown_context = imperative (fn () => warning "Unknown context");
   426 
   427 
   428 (* theory transitions *)
   429 
   430 fun generic_theory f = transaction (fn _ =>
   431   (fn Theory (gthy, _) => Theory (f gthy, NONE)
   432     | _ => raise UNDEF));
   433 
   434 fun theory' f = transaction (fn int =>
   435   (fn Theory (Context.Theory thy, _) =>
   436       let val thy' = thy
   437         |> Sign.new_group
   438         |> Theory.checkpoint
   439         |> f int
   440         |> Sign.reset_group;
   441       in Theory (Context.Theory thy', NONE) end
   442     | _ => raise UNDEF));
   443 
   444 fun theory f = theory' (K f);
   445 
   446 fun begin_local_theory begin f = transaction (fn _ =>
   447   (fn Theory (Context.Theory thy, _) =>
   448         let
   449           val lthy = f thy;
   450           val gthy = if begin then Context.Proof lthy else Context.Theory (loc_exit lthy);
   451         in Theory (gthy, SOME lthy) end
   452     | _ => raise UNDEF));
   453 
   454 val end_local_theory = transaction (fn _ =>
   455   (fn Theory (Context.Proof lthy, _) => Theory (Context.Theory (loc_exit lthy), SOME lthy)
   456     | _ => raise UNDEF));
   457 
   458 fun open_target f = transaction (fn _ =>
   459   (fn Theory (gthy, _) =>
   460         let val lthy = f gthy
   461         in Theory (Context.Proof lthy, SOME lthy) end
   462     | _ => raise UNDEF));
   463 
   464 val close_target = transaction (fn _ =>
   465   (fn Theory (Context.Proof lthy, _) =>
   466         (case try Local_Theory.close_target lthy of
   467           SOME ctxt' =>
   468             let
   469               val gthy' =
   470                 if can Local_Theory.assert ctxt'
   471                 then Context.Proof ctxt'
   472                 else Context.Theory (Proof_Context.theory_of ctxt');
   473             in Theory (gthy', SOME lthy) end
   474         | NONE => raise UNDEF)
   475     | _ => raise UNDEF));
   476 
   477 
   478 local
   479 
   480 fun local_theory_presentation loc f = present_transaction (fn int =>
   481   (fn Theory (gthy, _) =>
   482         let
   483           val (finish, lthy) = loc_begin loc gthy;
   484           val lthy' = lthy
   485             |> Local_Theory.new_group
   486             |> f int
   487             |> Local_Theory.reset_group;
   488         in Theory (finish lthy', SOME lthy') end
   489     | _ => raise UNDEF));
   490 
   491 in
   492 
   493 fun local_theory' loc f = local_theory_presentation loc f (K ());
   494 fun local_theory loc f = local_theory' loc (K f);
   495 fun present_local_theory loc = local_theory_presentation loc (K I);
   496 
   497 end;
   498 
   499 
   500 (* proof transitions *)
   501 
   502 fun end_proof f = transaction (fn int =>
   503   (fn Proof (prf, (finish, _)) =>
   504         let val state = Proof_Node.current prf in
   505           if can (Proof.assert_bottom true) state then
   506             let
   507               val ctxt' = f int state;
   508               val gthy' = finish ctxt';
   509             in Theory (gthy', SOME ctxt') end
   510           else raise UNDEF
   511         end
   512     | Skipped_Proof (0, (gthy, _)) => Theory (gthy, NONE)
   513     | _ => raise UNDEF));
   514 
   515 local
   516 
   517 fun begin_proof init = transaction (fn int =>
   518   (fn Theory (gthy, _) =>
   519     let
   520       val (finish, prf) = init int gthy;
   521       val skip = ! Goal.skip_proofs;
   522       val (is_goal, no_skip) =
   523         (true, Proof.schematic_goal prf) handle ERROR _ => (false, true);
   524       val _ =
   525         if is_goal andalso skip andalso no_skip then
   526           warning "Cannot skip proof of schematic goal statement"
   527         else ();
   528     in
   529       if skip andalso not no_skip then
   530         Skipped_Proof (0, (finish (Proof.global_skip_proof true prf), gthy))
   531       else Proof (Proof_Node.init prf, (finish, gthy))
   532     end
   533   | _ => raise UNDEF));
   534 
   535 in
   536 
   537 fun local_theory_to_proof' loc f = begin_proof
   538   (fn int => fn gthy =>
   539     let val (finish, lthy) = loc_begin loc gthy
   540     in (finish o Local_Theory.reset_group, f int (Local_Theory.new_group lthy)) end);
   541 
   542 fun local_theory_to_proof loc f = local_theory_to_proof' loc (K f);
   543 
   544 fun theory_to_proof f = begin_proof
   545   (fn _ => fn gthy =>
   546     (Context.Theory o Theory.checkpoint o Sign.reset_group o Proof_Context.theory_of,
   547       (case gthy of
   548         Context.Theory thy => f (Theory.checkpoint (Sign.new_group thy))
   549       | _ => raise UNDEF)));
   550 
   551 end;
   552 
   553 val forget_proof = transaction (fn _ =>
   554   (fn Proof (_, (_, orig_gthy)) => Theory (orig_gthy, NONE)
   555     | Skipped_Proof (_, (_, orig_gthy)) => Theory (orig_gthy, NONE)
   556     | _ => raise UNDEF));
   557 
   558 val present_proof = present_transaction (fn _ =>
   559   (fn Proof (prf, x) => Proof (Proof_Node.apply I prf, x)
   560     | skip as Skipped_Proof _ => skip
   561     | _ => raise UNDEF));
   562 
   563 fun proofs' f = transaction (fn int =>
   564   (fn Proof (prf, x) => Proof (Proof_Node.applys (f int) prf, x)
   565     | skip as Skipped_Proof _ => skip
   566     | _ => raise UNDEF));
   567 
   568 fun proof' f = proofs' ((Seq.single o Seq.Result) oo f);
   569 val proofs = proofs' o K;
   570 val proof = proof' o K;
   571 
   572 fun actual_proof f = transaction (fn _ =>
   573   (fn Proof (prf, x) => Proof (f prf, x)
   574     | _ => raise UNDEF));
   575 
   576 fun skip_proof f = transaction (fn _ =>
   577   (fn Skipped_Proof (h, x) => Skipped_Proof (f h, x)
   578     | _ => raise UNDEF));
   579 
   580 fun skip_proof_to_theory pred = transaction (fn _ =>
   581   (fn Skipped_Proof (d, (gthy, _)) => if pred d then Theory (gthy, NONE) else raise UNDEF
   582     | _ => raise UNDEF));
   583 
   584 
   585 
   586 (** toplevel transactions **)
   587 
   588 (* identification *)
   589 
   590 fun get_id (Transition {pos, ...}) = Position.get_id pos;
   591 fun put_id id (tr as Transition {pos, ...}) = position (Position.put_id id pos) tr;
   592 
   593 
   594 (* approximative identification within source file *)
   595 
   596 fun approximative_id tr =
   597   let
   598     val name = name_of tr;
   599     val pos = pos_of tr;
   600   in
   601     (case (Position.file_of pos, Position.offset_of pos) of
   602       (SOME file, SOME offset) => SOME {file = file, offset = offset, name = name}
   603     | _ => NONE)
   604   end;
   605 
   606 
   607 (* thread position *)
   608 
   609 fun setmp_thread_position (Transition {pos, ...}) f x =
   610   Position.setmp_thread_data pos f x;
   611 
   612 fun status tr m =
   613   setmp_thread_position tr (fn () => Output.status (Markup.markup_only m)) ();
   614 
   615 
   616 (* post-transition hooks *)
   617 
   618 local
   619   val hooks = Unsynchronized.ref ([]: (transition -> state -> state -> unit) list);
   620 in
   621 
   622 fun add_hook f = CRITICAL (fn () => Unsynchronized.change hooks (cons f));
   623 fun get_hooks () = ! hooks;
   624 
   625 end;
   626 
   627 
   628 (* apply transitions *)
   629 
   630 fun get_timing (Transition {timing, ...}) = timing;
   631 fun put_timing timing = map_transition (fn (name, pos, int_only, print, _, trans) =>
   632   (name, pos, int_only, print, timing, trans));
   633 
   634 local
   635 
   636 fun app int (tr as Transition {trans, print, ...}) =
   637   setmp_thread_position tr (fn state =>
   638     let
   639       val timing_start = Timing.start ();
   640 
   641       val (result, opt_err) =
   642          state |> (apply_trans int trans |> ! profiling > 0 ? profile (! profiling));
   643       val _ = if int andalso not (! quiet) andalso print then print_state false result else ();
   644 
   645       val timing_result = Timing.result timing_start;
   646 
   647       val _ =
   648         if Timing.is_relevant timing_result andalso (! profiling > 0 orelse ! timing)
   649           andalso not (Keyword.is_control (name_of tr))
   650         then tracing (command_msg "" tr ^ ": " ^ Timing.message timing_result)
   651         else ();
   652       val _ =
   653         if Timing.is_relevant timing_result
   654         then status tr (Markup.timing timing_result)
   655         else ();
   656       val _ =
   657         (case approximative_id tr of
   658           SOME id =>
   659             (Output.try_protocol_message
   660               (Markup.command_timing ::
   661                 Markup.command_timing_properties id (#elapsed timing_result)) "")
   662         | NONE => ());
   663     in
   664       (result, Option.map (fn UNDEF => type_error tr state | exn => exn) opt_err)
   665     end);
   666 
   667 in
   668 
   669 fun transition int tr st =
   670   let
   671     val hooks = get_hooks ();
   672     fun apply_hooks st' = hooks |> List.app (fn f => (try (fn () => f tr st st') (); ()));
   673 
   674     val ctxt = try context_of st;
   675     val res =
   676       (case app int tr st of
   677         (_, SOME Runtime.TERMINATE) => NONE
   678       | (st', SOME (Runtime.EXCURSION_FAIL exn_info)) => SOME (st', SOME exn_info)
   679       | (st', SOME exn) => SOME (st', SOME (Runtime.exn_context ctxt exn, at_command tr))
   680       | (st', NONE) => SOME (st', NONE));
   681     val _ = (case res of SOME (st', NONE) => apply_hooks st' | _ => ());
   682   in res end;
   683 
   684 end;
   685 
   686 
   687 (* managed commands *)
   688 
   689 fun command_errors int tr st =
   690   (case transition int tr st of
   691     SOME (st', NONE) => ([], SOME st')
   692   | SOME (_, SOME (exn, _)) => (ML_Compiler.exn_messages_ids exn, NONE)
   693   | NONE => (ML_Compiler.exn_messages_ids Runtime.TERMINATE, NONE));
   694 
   695 fun command_exception int tr st =
   696   (case transition int tr st of
   697     SOME (st', NONE) => st'
   698   | SOME (_, SOME (exn, info)) =>
   699       if Exn.is_interrupt exn then reraise exn else raise Runtime.EXCURSION_FAIL (exn, info)
   700   | NONE => raise Runtime.EXCURSION_FAIL (Runtime.TERMINATE, at_command tr));
   701 
   702 fun command tr = command_exception (! interact) tr;
   703 
   704 
   705 (* scheduled proof result *)
   706 
   707 datatype result =
   708   Result of transition * state |
   709   Result_List of result list |
   710   Result_Future of result future;
   711 
   712 fun join_results (Result x) = [x]
   713   | join_results (Result_List xs) = maps join_results xs
   714   | join_results (Result_Future x) = join_results (Future.join x);
   715 
   716 local
   717 
   718 structure Result = Proof_Data
   719 (
   720   type T = result;
   721   val empty: T = Result_List [];
   722   fun init _ = empty;
   723 );
   724 
   725 val get_result = Result.get o Proof.context_of;
   726 val put_result = Proof.map_context o Result.put;
   727 
   728 fun timing_estimate include_head elem =
   729   let
   730     val trs = Thy_Syntax.flat_element elem |> not include_head ? tl;
   731     val timings = map get_timing trs;
   732   in
   733     if forall is_some timings then
   734       SOME (fold (curry Time.+ o the) timings Time.zeroTime)
   735     else NONE
   736   end;
   737 
   738 fun priority NONE = ~1
   739   | priority (SOME estimate) =
   740       Int.min (Real.floor (Real.max (Math.log10 (Time.toReal estimate), ~3.0)) - 3, ~1);
   741 
   742 fun proof_future_enabled estimate st =
   743   (case try proof_of st of
   744     NONE => false
   745   | SOME state =>
   746       not (Proof.is_relevant state) andalso
   747        (if can (Proof.assert_bottom true) state
   748         then Goal.future_enabled ()
   749         else
   750           (case estimate of
   751             NONE => Goal.future_enabled_nested 2
   752           | SOME t => Goal.future_enabled_timing t)));
   753 
   754 fun atom_result tr st =
   755   let
   756     val st' =
   757       if Goal.future_enabled () andalso Keyword.is_diag (name_of tr) then
   758         (Goal.fork_params
   759           {name = "Toplevel.diag", pos = pos_of tr,
   760             pri = priority (timing_estimate true (Thy_Syntax.atom tr))}
   761           (fn () => command tr st); st)
   762       else command tr st;
   763   in (Result (tr, st'), st') end;
   764 
   765 in
   766 
   767 fun element_result (Thy_Syntax.Element (tr, NONE)) st = atom_result tr st
   768   | element_result (elem as Thy_Syntax.Element (head_tr, SOME element_rest)) st =
   769       let
   770         val (head_result, st') = atom_result head_tr st;
   771         val (body_elems, end_tr) = element_rest;
   772         val estimate = timing_estimate false elem;
   773       in
   774         if not (proof_future_enabled estimate st')
   775         then
   776           let
   777             val proof_trs = maps Thy_Syntax.flat_element body_elems @ [end_tr];
   778             val (proof_results, st'') = fold_map atom_result proof_trs st';
   779           in (Result_List (head_result :: proof_results), st'') end
   780         else
   781           let
   782             val finish = Context.Theory o Proof_Context.theory_of;
   783 
   784             val future_proof =
   785               Proof.future_proof (fn state =>
   786                 Goal.fork_params
   787                   {name = "Toplevel.future_proof", pos = pos_of head_tr, pri = priority estimate}
   788                   (fn () =>
   789                     let
   790                       val State (SOME (Proof (prf, (_, orig_gthy))), prev) = st';
   791                       val prf' = Proof_Node.apply (K state) prf;
   792                       val (result, result_state) =
   793                         State (SOME (Proof (prf', (finish, orig_gthy))), prev)
   794                         |> fold_map element_result body_elems ||> command end_tr;
   795                     in (Result_List result, presentation_context_of result_state) end))
   796               #> (fn (res, state') => state' |> put_result (Result_Future res));
   797 
   798             val forked_proof =
   799               proof (future_proof #>
   800                 (fn state => state |> Proof.local_done_proof |> put_result (get_result state))) o
   801               end_proof (fn _ => future_proof #>
   802                 (fn state => state |> Proof.global_done_proof |> Result.put (get_result state)));
   803 
   804             val st'' = st'
   805               |> command (head_tr |> set_print false |> reset_trans |> forked_proof);
   806             val end_result = Result (end_tr, st'');
   807             val result =
   808               Result_List [head_result, Result.get (presentation_context_of st''), end_result];
   809           in (result, st'') end
   810       end;
   811 
   812 end;
   813 
   814 end;