src/Pure/PIDE/command.ML
author wenzelm
Sat Sep 01 20:20:50 2018 +0200 (10 months ago)
changeset 68871 f5c76072db55
parent 68868 5f44ad150ed8
child 68874 cca5ca811714
permissions -rw-r--r--
more explicit status for "canceled" command within theory node;
     1 (*  Title:      Pure/PIDE/command.ML
     2     Author:     Makarius
     3 
     4 Prover command execution: read -- eval -- print.
     5 *)
     6 
     7 signature COMMAND =
     8 sig
     9   type blob = (string * (SHA1.digest * string list) option) Exn.result
    10   val read_file: Path.T -> Position.T -> Path.T -> Token.file
    11   val read_thy: Toplevel.state -> theory
    12   val read: Keyword.keywords -> theory -> Path.T-> (unit -> theory) ->
    13     blob list * int -> Token.T list -> Toplevel.transition
    14   type eval
    15   val eval_command_id: eval -> Document_ID.command
    16   val eval_exec_id: eval -> Document_ID.exec
    17   val eval_eq: eval * eval -> bool
    18   val eval_running: eval -> bool
    19   val eval_finished: eval -> bool
    20   val eval_result_command: eval -> Toplevel.transition
    21   val eval_result_state: eval -> Toplevel.state
    22   val eval: Keyword.keywords -> Path.T -> (unit -> theory) ->
    23     blob list * int -> Document_ID.command -> Token.T list -> eval -> eval
    24   type print
    25   type print_fn = Toplevel.transition -> Toplevel.state -> unit
    26   val print0: {pri: int, print_fn: print_fn} -> eval -> print
    27   val print: bool -> (string * string list) list -> Keyword.keywords -> string ->
    28     eval -> print list -> print list option
    29   val parallel_print: print -> bool
    30   type print_function =
    31     {keywords: Keyword.keywords, command_name: string, args: string list, exec_id: Document_ID.exec} ->
    32       {delay: Time.time option, pri: int, persistent: bool, strict: bool, print_fn: print_fn} option
    33   val print_function: string -> print_function -> unit
    34   val no_print_function: string -> unit
    35   type exec = eval * print list
    36   val init_exec: theory option -> exec
    37   val no_exec: exec
    38   val exec_ids: exec option -> Document_ID.exec list
    39   val exec: Document_ID.execution -> exec -> unit
    40   val exec_parallel_prints: Document_ID.execution -> Future.task list -> exec -> exec option
    41 end;
    42 
    43 structure Command: COMMAND =
    44 struct
    45 
    46 (** main phases of execution **)
    47 
    48 fun task_context group f =
    49   f
    50   |> Future.interruptible_task
    51   |> Future.task_context "Command.run_process" group;
    52 
    53 
    54 (* read *)
    55 
    56 type blob =
    57   (string * (SHA1.digest * string list) option) Exn.result;  (*file node name, digest, lines*)
    58 
    59 fun read_file_node file_node master_dir pos src_path =
    60   let
    61     val _ = Position.report pos Markup.language_path;
    62     val _ =
    63       (case try Url.explode file_node of
    64         NONE => ()
    65       | SOME (Url.File _) => ()
    66       | _ =>
    67           error ("Prover cannot load remote file " ^
    68             Markup.markup (Markup.path file_node) (quote file_node)));
    69     val full_path = File.check_file (File.full_path master_dir src_path);
    70     val text = File.read full_path;
    71     val lines = split_lines text;
    72     val digest = SHA1.digest text;
    73     val file_pos = Position.copy_id pos (Path.position full_path);
    74   in {src_path = src_path, lines = lines, digest = digest, pos = file_pos} end
    75   handle ERROR msg => error (msg ^ Position.here pos);
    76 
    77 val read_file = read_file_node "";
    78 
    79 local
    80 
    81 fun blob_file src_path lines digest file_node =
    82   let
    83     val file_pos =
    84       Position.file file_node |>
    85       (case Position.get_id (Position.thread_data ()) of
    86         NONE => I
    87       | SOME exec_id => Position.put_id exec_id);
    88   in {src_path = src_path, lines = lines, digest = digest, pos = file_pos} end
    89 
    90 fun resolve_files keywords master_dir (blobs, blobs_index) toks =
    91   (case Outer_Syntax.parse_spans toks of
    92     [Command_Span.Span (Command_Span.Command_Span (cmd, _), _)] =>
    93       (case try (nth toks) blobs_index of
    94         SOME tok =>
    95           let
    96             val pos = Token.pos_of tok;
    97             val path = Path.explode (Token.content_of tok)
    98               handle ERROR msg => error (msg ^ Position.here pos);
    99             fun make_file src_path (Exn.Res (file_node, NONE)) =
   100                   Exn.interruptible_capture (fn () =>
   101                     read_file_node file_node master_dir pos src_path) ()
   102               | make_file src_path (Exn.Res (file_node, SOME (digest, lines))) =
   103                   (Position.report pos Markup.language_path;
   104                     Exn.Res (blob_file src_path lines digest file_node))
   105               | make_file _ (Exn.Exn e) = Exn.Exn e;
   106             val src_paths = Keyword.command_files keywords cmd path;
   107             val files =
   108               if null blobs then
   109                 map2 make_file src_paths (map (K (Exn.Res ("", NONE))) src_paths)
   110               else if length src_paths = length blobs then
   111                 map2 make_file src_paths blobs
   112               else error ("Misalignment of inlined files" ^ Position.here pos);
   113           in
   114             toks |> map_index (fn (i, tok) =>
   115               if i = blobs_index then Token.put_files files tok else tok)
   116           end
   117       | NONE => toks)
   118   | _ => toks);
   119 
   120 fun reports_of_token keywords tok =
   121   let
   122     val malformed_symbols =
   123       Input.source_explode (Token.input_of tok)
   124       |> map_filter (fn (sym, pos) =>
   125           if Symbol.is_malformed sym
   126           then SOME ((pos, Markup.bad ()), "Malformed symbolic character") else NONE);
   127     val is_malformed = Token.is_error tok orelse not (null malformed_symbols);
   128     val reports = Token.reports keywords tok @ Token.completion_report tok @ malformed_symbols;
   129   in (is_malformed, reports) end;
   130 
   131 in
   132 
   133 fun read_thy st = Toplevel.theory_of st
   134   handle Toplevel.UNDEF => Pure_Syn.bootstrap_thy;
   135 
   136 fun read keywords thy master_dir init blobs_info span =
   137   let
   138     val command_reports = Outer_Syntax.command_reports thy;
   139 
   140     val core_range = Token.range_of (drop_suffix Token.is_ignored span);
   141     val pos =
   142       (case find_first Token.is_command span of
   143         SOME tok => Token.pos_of tok
   144       | NONE => #1 core_range);
   145 
   146     val token_reports = map (reports_of_token keywords) span;
   147     val _ = Position.reports_text (maps #2 token_reports @ maps command_reports span);
   148   in
   149     if exists #1 token_reports then Toplevel.malformed pos "Malformed command syntax"
   150     else
   151       (case Outer_Syntax.parse_tokens thy (resolve_files keywords master_dir blobs_info span) of
   152         [tr] => Toplevel.modify_init init tr
   153       | [] => Toplevel.ignored (#1 (Token.range_of span))
   154       | _ => Toplevel.malformed (#1 core_range) "Exactly one command expected")
   155       handle ERROR msg => Toplevel.malformed (#1 core_range) msg
   156   end;
   157 
   158 end;
   159 
   160 
   161 (* eval *)
   162 
   163 type eval_state = {failed: bool, command: Toplevel.transition, state: Toplevel.state};
   164 
   165 fun init_eval_state opt_thy =
   166  {failed = false,
   167   command = Toplevel.empty,
   168   state = (case opt_thy of NONE => Toplevel.toplevel | SOME thy => Toplevel.theory_toplevel thy)};
   169 
   170 datatype eval =
   171   Eval of
   172     {command_id: Document_ID.command, exec_id: Document_ID.exec, eval_process: eval_state lazy};
   173 
   174 fun eval_command_id (Eval {command_id, ...}) = command_id;
   175 
   176 fun eval_exec_id (Eval {exec_id, ...}) = exec_id;
   177 val eval_eq = op = o apply2 eval_exec_id;
   178 
   179 val eval_running = Execution.is_running_exec o eval_exec_id;
   180 fun eval_finished (Eval {eval_process, ...}) = Lazy.is_finished eval_process;
   181 
   182 fun eval_result (Eval {eval_process, ...}) =
   183   Exn.release (Lazy.finished_result eval_process);
   184 
   185 val eval_result_command = #command o eval_result;
   186 val eval_result_state = #state o eval_result;
   187 
   188 local
   189 
   190 fun reset_state keywords tr st0 = Toplevel.setmp_thread_position tr (fn () =>
   191   let
   192     val name = Toplevel.name_of tr;
   193     val res =
   194       if Keyword.is_theory_body keywords name then Toplevel.reset_theory st0
   195       else if Keyword.is_proof keywords name then Toplevel.reset_proof st0
   196       else NONE;
   197   in
   198     (case res of
   199       NONE => st0
   200     | SOME st => (Output.error_message (Toplevel.type_error tr ^ " -- using reset state"); st))
   201   end) ();
   202 
   203 fun run keywords int tr st =
   204   if Future.proofs_enabled 1 andalso Keyword.is_diag keywords (Toplevel.name_of tr) then
   205     (Execution.fork {name = "Toplevel.diag", pos = Toplevel.pos_of tr, pri = ~1}
   206       (fn () => Toplevel.command_exception int tr st); ([], SOME st))
   207   else Toplevel.command_errors int tr st;
   208 
   209 fun check_token_comments ctxt tok =
   210   (Thy_Output.check_comments ctxt (Input.source_explode (Token.input_of tok)); [])
   211     handle exn =>
   212       if Exn.is_interrupt exn then Exn.reraise exn
   213       else Runtime.exn_messages exn;
   214 
   215 fun check_span_comments ctxt span tr =
   216   Toplevel.setmp_thread_position tr (fn () => maps (check_token_comments ctxt) span) ();
   217 
   218 fun report tr m =
   219   Toplevel.setmp_thread_position tr (fn () => Output.report [Markup.markup_only m]) ();
   220 
   221 fun status tr m =
   222   Toplevel.setmp_thread_position tr (fn () => Output.status (Markup.markup_only m)) ();
   223 
   224 fun command_indent tr st =
   225   (case try Toplevel.proof_of st of
   226     SOME prf =>
   227       let val keywords = Thy_Header.get_keywords (Proof.theory_of prf) in
   228         if Keyword.command_kind keywords (Toplevel.name_of tr) = SOME Keyword.prf_script then
   229           (case try Proof.goal prf of
   230             SOME {goal, ...} =>
   231               let val n = Thm.nprems_of goal
   232               in if n > 1 then report tr (Markup.command_indent (n - 1)) else () end
   233           | NONE => ())
   234         else ()
   235       end
   236   | NONE => ());
   237 
   238 
   239 fun eval_state keywords span tr ({state, ...}: eval_state) =
   240   let
   241     val _ = Thread_Attributes.expose_interrupt ();
   242 
   243     val st = reset_state keywords tr state;
   244 
   245     val _ = command_indent tr st;
   246     val _ = status tr Markup.running;
   247     val (errs1, result) = run keywords true tr st;
   248     val errs2 =
   249       (case result of
   250         NONE => []
   251       | SOME st' =>
   252           (case try Toplevel.presentation_context st' of
   253             NONE => []
   254           | SOME ctxt' => check_span_comments ctxt' span tr));
   255     val errs = errs1 @ errs2;
   256     val _ = List.app (Future.error_message (Toplevel.pos_of tr)) errs;
   257   in
   258     (case result of
   259       NONE =>
   260         let
   261           val _ = status tr Markup.failed;
   262           val _ = status tr Markup.finished;
   263           val _ = if null errs then (status tr Markup.canceled; Exn.interrupt ()) else ();
   264         in {failed = true, command = tr, state = st} end
   265     | SOME st' =>
   266         let
   267           val _ = status tr Markup.finished;
   268         in {failed = false, command = tr, state = st'} end)
   269   end;
   270 
   271 in
   272 
   273 fun eval keywords master_dir init blobs_info command_id span eval0 =
   274   let
   275     val exec_id = Document_ID.make ();
   276     fun process () =
   277       let
   278         val eval_state0 = eval_result eval0;
   279         val thy = read_thy (#state eval_state0);
   280         val tr =
   281           Position.setmp_thread_data (Position.id_only (Document_ID.print exec_id))
   282             (fn () =>
   283               read keywords thy master_dir init blobs_info span |> Toplevel.exec_id exec_id) ();
   284       in eval_state keywords span tr eval_state0 end;
   285   in
   286     Eval {command_id = command_id, exec_id = exec_id, eval_process = Lazy.lazy_name "Command.eval" process}
   287   end;
   288 
   289 end;
   290 
   291 
   292 (* print *)
   293 
   294 datatype print = Print of
   295  {name: string, args: string list, delay: Time.time option, pri: int, persistent: bool,
   296   exec_id: Document_ID.exec, print_process: unit lazy};
   297 
   298 fun print_exec_id (Print {exec_id, ...}) = exec_id;
   299 val print_eq = op = o apply2 print_exec_id;
   300 
   301 type print_fn = Toplevel.transition -> Toplevel.state -> unit;
   302 
   303 type print_function =
   304   {keywords: Keyword.keywords, command_name: string, args: string list, exec_id: Document_ID.exec} ->
   305     {delay: Time.time option, pri: int, persistent: bool, strict: bool, print_fn: print_fn} option;
   306 
   307 local
   308 
   309 val print_functions =
   310   Synchronized.var "Command.print_functions" ([]: (string * print_function) list);
   311 
   312 fun print_error tr opt_context e =
   313   (Toplevel.setmp_thread_position tr o Runtime.controlled_execution opt_context) e ()
   314     handle exn =>
   315       if Exn.is_interrupt exn then Exn.reraise exn
   316       else List.app (Future.error_message (Toplevel.pos_of tr)) (Runtime.exn_messages exn);
   317 
   318 fun print_finished (Print {print_process, ...}) = Lazy.is_finished print_process;
   319 
   320 fun print_persistent (Print {persistent, ...}) = persistent;
   321 
   322 val overlay_ord = prod_ord string_ord (list_ord string_ord);
   323 
   324 fun make_print (name, args) {delay, pri, persistent, strict, print_fn} eval =
   325   let
   326     val exec_id = Document_ID.make ();
   327     fun process () =
   328       let
   329         val {failed, command, state = st', ...} = eval_result eval;
   330         val tr = Toplevel.exec_id exec_id command;
   331         val opt_context = try Toplevel.generic_theory_of st';
   332       in
   333         if failed andalso strict then ()
   334         else print_error tr opt_context (fn () => print_fn tr st')
   335       end;
   336   in
   337     Print {
   338       name = name, args = args, delay = delay, pri = pri, persistent = persistent,
   339       exec_id = exec_id, print_process = Lazy.lazy_name "Command.print" process}
   340   end;
   341 
   342 fun bad_print name_args exn =
   343   make_print name_args {delay = NONE, pri = 0, persistent = false,
   344     strict = false, print_fn = fn _ => fn _ => Exn.reraise exn};
   345 
   346 in
   347 
   348 fun print0 {pri, print_fn} =
   349   make_print ("", [serial_string ()])
   350     {delay = NONE, pri = pri, persistent = true, strict = true, print_fn = print_fn};
   351 
   352 fun print command_visible command_overlays keywords command_name eval old_prints =
   353   let
   354     val print_functions = Synchronized.value print_functions;
   355 
   356     fun new_print (name, args) get_pr =
   357       let
   358         val params =
   359          {keywords = keywords,
   360           command_name = command_name,
   361           args = args,
   362           exec_id = eval_exec_id eval};
   363       in
   364         (case Exn.capture (Runtime.controlled_execution NONE get_pr) params of
   365           Exn.Res NONE => NONE
   366         | Exn.Res (SOME pr) => SOME (make_print (name, args) pr eval)
   367         | Exn.Exn exn => SOME (bad_print (name, args) exn eval))
   368       end;
   369 
   370     fun get_print (name, args) =
   371       (case find_first (fn Print print => (#name print, #args print) = (name, args)) old_prints of
   372         NONE =>
   373           (case AList.lookup (op =) print_functions name of
   374             NONE =>
   375               SOME (bad_print (name, args) (ERROR ("Missing print function " ^ quote name)) eval)
   376           | SOME get_pr => new_print (name, args) get_pr)
   377       | some => some);
   378 
   379     val retained_prints =
   380       filter (fn print => print_finished print andalso print_persistent print) old_prints;
   381     val visible_prints =
   382       if command_visible then
   383         fold (fn (name, _) => cons (name, [])) print_functions command_overlays
   384         |> sort_distinct overlay_ord
   385         |> map_filter get_print
   386       else [];
   387     val new_prints = visible_prints @ retained_prints;
   388   in
   389     if eq_list print_eq (old_prints, new_prints) then NONE else SOME new_prints
   390   end;
   391 
   392 fun parallel_print (Print {pri, ...}) =
   393   pri <= 0 orelse (Future.enabled () andalso Options.default_bool "parallel_print");
   394 
   395 fun print_function name f =
   396   Synchronized.change print_functions (fn funs =>
   397    (if name = "" then error "Unnamed print function" else ();
   398     if not (AList.defined (op =) funs name) then ()
   399     else warning ("Redefining command print function: " ^ quote name);
   400     AList.update (op =) (name, f) funs));
   401 
   402 fun no_print_function name =
   403   Synchronized.change print_functions (filter_out (equal name o #1));
   404 
   405 end;
   406 
   407 val _ =
   408   print_function "Execution.print"
   409     (fn {args, exec_id, ...} =>
   410       if null args then
   411         SOME {delay = NONE, pri = Task_Queue.urgent_pri + 2, persistent = false, strict = false,
   412           print_fn = fn _ => fn _ => Execution.fork_prints exec_id}
   413       else NONE);
   414 
   415 val _ =
   416   print_function "print_state"
   417     (fn {keywords, command_name, ...} =>
   418       if Options.default_bool "editor_output_state" andalso Keyword.is_printed keywords command_name
   419       then
   420         SOME {delay = NONE, pri = Task_Queue.urgent_pri + 1, persistent = false, strict = false,
   421           print_fn = fn _ => fn st =>
   422             if Toplevel.is_proof st then Output.state (Toplevel.string_of_state st)
   423             else ()}
   424       else NONE);
   425 
   426 
   427 (* combined execution *)
   428 
   429 type exec = eval * print list;
   430 
   431 fun init_exec opt_thy : exec =
   432   (Eval
   433     {command_id = Document_ID.none, exec_id = Document_ID.none,
   434       eval_process = Lazy.value (init_eval_state opt_thy)}, []);
   435 
   436 val no_exec = init_exec NONE;
   437 
   438 fun exec_ids NONE = []
   439   | exec_ids (SOME (eval, prints)) = eval_exec_id eval :: map print_exec_id prints;
   440 
   441 local
   442 
   443 fun run_process execution_id exec_id process =
   444   let val group = Future.worker_subgroup () in
   445     if Execution.running execution_id exec_id [group] then
   446       ignore (task_context group Lazy.force_result {strict = true} process)
   447     else ()
   448   end;
   449 
   450 fun ignore_process process =
   451   Lazy.is_running process orelse Lazy.is_finished process;
   452 
   453 fun run_eval execution_id (Eval {exec_id, eval_process, ...}) =
   454   if Lazy.is_finished eval_process then ()
   455   else run_process execution_id exec_id eval_process;
   456 
   457 fun fork_print execution_id deps (Print {name, delay, pri, exec_id, print_process, ...}) =
   458   let
   459     val group = Future.worker_subgroup ();
   460     fun fork () =
   461       ignore ((singleton o Future.forks)
   462         {name = name, group = SOME group, deps = deps, pri = pri, interrupts = true}
   463         (fn () =>
   464           if ignore_process print_process then ()
   465           else run_process execution_id exec_id print_process));
   466   in
   467     (case delay of
   468       NONE => fork ()
   469     | SOME d => ignore (Event_Timer.request (Time.now () + d) fork))
   470   end;
   471 
   472 fun run_print execution_id (print as Print {exec_id, print_process, ...}) =
   473   if ignore_process print_process then ()
   474   else if parallel_print print then fork_print execution_id [] print
   475   else run_process execution_id exec_id print_process;
   476 
   477 in
   478 
   479 fun exec execution_id (eval, prints) =
   480   (run_eval execution_id eval; List.app (run_print execution_id) prints);
   481 
   482 fun exec_parallel_prints execution_id deps (exec as (Eval {eval_process, ...}, prints)) =
   483   if Lazy.is_finished eval_process
   484   then (List.app (fork_print execution_id deps) prints; NONE)
   485   else SOME exec;
   486 
   487 end;
   488 
   489 end;