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