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