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