src/Pure/PIDE/command.ML
author Walther Neuper <walther.neuper@jku.at>
Mon, 01 Mar 2021 12:46:40 +0100
changeset 60161 3c06f59b78d6
parent 60133 83003c700845
child 60162 50f655f2db4f
permissions -rw-r--r--
step 6.8: "Specification" "Model" :: diag ..both work,

but the same error is now at Given: thus provide correct type there.
     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 
   149     val verbatim =
   150       span |> map_filter (fn tok =>
   151         if Token.kind_of tok = Token.Verbatim then SOME (Token.pos_of tok) else NONE);
   152     val _ =
   153       if null verbatim then ()
   154       else legacy_feature ("Old-style {* verbatim *} token -- use \<open>cartouche\<close> instead" ^
   155         Position.here_list verbatim);
   156   in
   157     if exists #1 token_reports then Toplevel.malformed pos "Malformed command syntax"
   158     else Outer_Syntax.parse_span thy init (resolve_files keywords master_dir blobs_info span)
   159   end;
   160 
   161 end;
   162 
   163 
   164 (* eval *)
   165 
   166 type eval_state = {failed: bool, command: Toplevel.transition, state: Toplevel.state};
   167 
   168 fun init_eval_state opt_thy =
   169  {failed = false,
   170   command = Toplevel.empty,
   171   state =
   172     (case opt_thy of
   173       NONE => Toplevel.init_toplevel ()
   174     | SOME thy => Toplevel.theory_toplevel thy)};
   175 
   176 datatype eval =
   177   Eval of
   178     {command_id: Document_ID.command, exec_id: Document_ID.exec, eval_process: eval_state lazy};
   179 
   180 fun eval_command_id (Eval {command_id, ...}) = command_id;
   181 
   182 fun eval_exec_id (Eval {exec_id, ...}) = exec_id;
   183 val eval_eq = op = o apply2 eval_exec_id;
   184 
   185 val eval_running = Execution.is_running_exec o eval_exec_id;
   186 fun eval_finished (Eval {eval_process, ...}) = Lazy.is_finished eval_process;
   187 
   188 fun eval_result (Eval {eval_process, ...}) =
   189   Exn.release (Lazy.finished_result eval_process);
   190 
   191 val eval_result_command = #command o eval_result;
   192 val eval_result_state = #state o eval_result;
   193 
   194 local
   195 
   196 fun reset_state keywords tr st0 = Toplevel.setmp_thread_position tr (fn () =>
   197   let
   198     val name = Toplevel.name_of tr;
   199     val res =
   200       if Keyword.is_theory_body keywords name then (writeln "#### is_theory_body"; Toplevel.reset_theory st0)
   201       else if Keyword.is_proof keywords name then (writeln "#### is_proof"; Toplevel.reset_proof st0)
   202       else if Keyword.is_theory_end keywords name then
   203         (case Toplevel.reset_notepad st0 of
   204           NONE => Toplevel.reset_theory st0
   205         | some => some)
   206       else NONE;
   207     val _ = @{print}{a = "#### reset_state", name = name, res = res, st0 = st0, tr = tr}
   208   in
   209     (case res of
   210       NONE => st0
   211     | SOME st => (Output.error_message (Toplevel.type_error tr ^ " -- using reset state"); st))
   212   end) ();
   213 
   214 fun run keywords int tr st =
   215   if Future.proofs_enabled 1 andalso Keyword.is_diag keywords (Toplevel.name_of tr) then
   216     let
   217       val (tr1, tr2) = Toplevel.fork_presentation tr;
   218       val _ =
   219         Execution.fork {name = "Toplevel.diag", pos = Toplevel.pos_of tr, pri = ~1}
   220           (fn () => Toplevel.command_exception int tr1 st);
   221     in Toplevel.command_errors int tr2 st end
   222   else Toplevel.command_errors int tr st;
   223 
   224 fun check_token_comments ctxt tok =
   225   (Thy_Output.check_comments ctxt (Input.source_explode (Token.input_of tok)); [])
   226     handle exn =>
   227       if Exn.is_interrupt exn then Exn.reraise exn
   228       else Runtime.exn_messages exn;
   229 
   230 fun check_span_comments ctxt span tr =
   231   Toplevel.setmp_thread_position tr (fn () => maps (check_token_comments ctxt) span) ();
   232 
   233 fun report tr m =
   234   Toplevel.setmp_thread_position tr (fn () => Output.report [Markup.markup_only m]) ();
   235 fun report tr m =                     
   236   Toplevel.setmp_thread_position tr (fn () =>
   237     ((**)@{print} {a = "### Command.report: Output.report"};(**)
   238       Output.report [Markup.markup_only m])
   239     ) ();
   240 
   241 fun status tr m =
   242   Toplevel.setmp_thread_position tr (fn () => Output.status [Markup.markup_only m]) ();
   243 
   244 fun command_indent tr st =
   245   (case try Toplevel.proof_of st of
   246     SOME prf =>
   247       let val keywords = Thy_Header.get_keywords (Proof.theory_of prf) in
   248         if Keyword.command_kind keywords (Toplevel.name_of tr) = SOME Keyword.prf_script then
   249           (case try Proof.goal prf of
   250             SOME {goal, ...} =>
   251               let val n = Thm.nprems_of goal
   252               in if n > 1 then report tr (Markup.command_indent (n - 1)) else () end
   253           | NONE => ())
   254         else ()
   255       end
   256   | NONE => ());
   257 
   258 
   259 fun eval_state keywords span tr ({state, ...}: eval_state) =
   260   let
   261     val _ = Thread_Attributes.expose_interrupt ();
   262 
   263     val st = reset_state keywords tr state;
   264 
   265     val _ = command_indent tr st;
   266     val _ = status tr Markup.running;
   267     val (errs1, result) = run keywords true tr st;
   268     val errs2 =
   269       (case result of
   270         NONE => []
   271       | SOME st' => check_span_comments (Toplevel.presentation_context st') span tr);
   272     val errs = errs1 @ errs2;
   273     val _ = List.app (Future.error_message (Toplevel.pos_of tr)) errs;
   274   in
   275     (case result of
   276       NONE =>
   277         let
   278           val _ = status tr Markup.failed;
   279           val _ = status tr Markup.finished;
   280           val _ = if null errs then (status tr Markup.canceled; Exn.interrupt ()) else ();
   281         in {failed = true, command = tr, state = st} end
   282     | SOME st' =>
   283         let
   284           val _ =
   285             if Keyword.is_theory_end keywords (Toplevel.name_of tr) andalso
   286               can (Toplevel.end_theory Position.none) st'
   287             then status tr Markup.finalized else ();
   288           val _ = status tr Markup.finished;
   289         in {failed = false, command = tr, state = st'} end)
   290   end;
   291 
   292 in
   293 
   294 fun eval keywords master_dir init blobs_info command_id span eval0 =
   295   let
   296     val exec_id = Document_ID.make ();
   297     fun process () =
   298       let
   299         val eval_state0 = eval_result eval0;
   300         val thy = read_thy (#state eval_state0);
   301         val tr =
   302           Position.setmp_thread_data (Position.id_only (Document_ID.print exec_id))
   303             (fn () =>
   304               read keywords thy master_dir init blobs_info span |> Toplevel.exec_id exec_id) ();
   305       in eval_state keywords span tr eval_state0 end;
   306   in
   307     Eval {command_id = command_id, exec_id = exec_id,
   308       eval_process = Lazy.lazy_name "Command.eval" process}
   309   end;
   310 
   311 end;
   312 
   313 
   314 (* print *)
   315 
   316 datatype print = Print of
   317  {name: string, args: string list, delay: Time.time option, pri: int, persistent: bool,
   318   exec_id: Document_ID.exec, print_process: unit lazy};
   319 
   320 fun print_exec_id (Print {exec_id, ...}) = exec_id;
   321 val print_eq = op = o apply2 print_exec_id;
   322 
   323 type print_fn = Toplevel.transition -> Toplevel.state -> unit;
   324 
   325 type print_function =
   326   {keywords: Keyword.keywords, command_name: string, args: string list, exec_id: Document_ID.exec} ->
   327     {delay: Time.time option, pri: int, persistent: bool, strict: bool, print_fn: print_fn} option;
   328 
   329 local
   330 
   331 val print_functions =
   332   Synchronized.var "Command.print_functions" ([]: (string * print_function) list);
   333 
   334 fun print_error tr opt_context e =
   335   (Toplevel.setmp_thread_position tr o Runtime.controlled_execution opt_context) e ()
   336     handle exn =>
   337       if Exn.is_interrupt exn then Exn.reraise exn
   338       else List.app (Future.error_message (Toplevel.pos_of tr)) (Runtime.exn_messages exn);
   339 
   340 fun print_finished (Print {print_process, ...}) = Lazy.is_finished print_process;
   341 
   342 fun print_persistent (Print {persistent, ...}) = persistent;
   343 
   344 val overlay_ord = prod_ord string_ord (list_ord string_ord);
   345 
   346 fun make_print (name, args) {delay, pri, persistent, strict, print_fn} eval =
   347   let
   348     val exec_id = Document_ID.make ();
   349     fun process () =
   350       let
   351         val {failed, command, state = st', ...} = eval_result eval;
   352         val tr = Toplevel.exec_id exec_id command;
   353         val opt_context = try Toplevel.generic_theory_of st';
   354       in
   355         if failed andalso strict then ()
   356         else print_error tr opt_context (fn () => print_fn tr st')
   357       end;
   358   in
   359     Print {
   360       name = name, args = args, delay = delay, pri = pri, persistent = persistent,
   361       exec_id = exec_id, print_process = Lazy.lazy_name "Command.print" process}
   362   end;
   363 
   364 fun bad_print name_args exn =
   365   make_print name_args {delay = NONE, pri = 0, persistent = false,
   366     strict = false, print_fn = fn _ => fn _ => Exn.reraise exn};
   367 
   368 in
   369 
   370 fun print0 {pri, print_fn} =
   371   make_print ("", [serial_string ()])
   372     {delay = NONE, pri = pri, persistent = true, strict = true, print_fn = print_fn};
   373 
   374 fun print command_visible command_overlays keywords command_name eval old_prints =
   375   let
   376     val print_functions = Synchronized.value print_functions;
   377 
   378     fun new_print (name, args) get_pr =
   379       let
   380         val params =
   381          {keywords = keywords,
   382           command_name = command_name,
   383           args = args,
   384           exec_id = eval_exec_id eval};
   385       in
   386         (case Exn.capture (Runtime.controlled_execution NONE get_pr) params of
   387           Exn.Res NONE => NONE
   388         | Exn.Res (SOME pr) => SOME (make_print (name, args) pr eval)
   389         | Exn.Exn exn => SOME (bad_print (name, args) exn eval))
   390       end;
   391 
   392     fun get_print (name, args) =
   393       (case find_first (fn Print print => (#name print, #args print) = (name, args)) old_prints of
   394         NONE =>
   395           (case AList.lookup (op =) print_functions name of
   396             NONE =>
   397               SOME (bad_print (name, args) (ERROR ("Missing print function " ^ quote name)) eval)
   398           | SOME get_pr => new_print (name, args) get_pr)
   399       | some => some);
   400 
   401     val retained_prints =
   402       filter (fn print => print_finished print andalso print_persistent print) old_prints;
   403     val visible_prints =
   404       if command_visible then
   405         fold (fn (name, _) => cons (name, [])) print_functions command_overlays
   406         |> sort_distinct overlay_ord
   407         |> map_filter get_print
   408       else [];
   409     val new_prints = visible_prints @ retained_prints;
   410   in
   411     if eq_list print_eq (old_prints, new_prints) then NONE else SOME new_prints
   412   end;
   413 
   414 fun parallel_print (Print {pri, ...}) =
   415   pri <= 0 orelse (Future.enabled () andalso Options.default_bool "parallel_print");
   416 
   417 fun print_function name f =
   418   Synchronized.change print_functions (fn funs =>
   419    (if name = "" then error "Unnamed print function" else ();
   420     if not (AList.defined (op =) funs name) then ()
   421     else warning ("Redefining command print function: " ^ quote name);
   422     AList.update (op =) (name, f) funs));
   423 
   424 fun no_print_function name =
   425   Synchronized.change print_functions (filter_out (equal name o #1));
   426 
   427 end;
   428 
   429 val _ =
   430   print_function "Execution.print"
   431     (fn {args, exec_id, ...} =>
   432       if null args then
   433         SOME {delay = NONE, pri = Task_Queue.urgent_pri + 2, persistent = false, strict = false,
   434           print_fn = fn _ => fn _ => Execution.fork_prints exec_id}
   435       else NONE);
   436 
   437 val _ =
   438   print_function "print_state"
   439     (fn {keywords, command_name, ...} =>
   440       if Options.default_bool "editor_output_state" andalso Keyword.is_printed keywords command_name
   441       then
   442         SOME {delay = NONE, pri = Task_Queue.urgent_pri + 1, persistent = false, strict = false,
   443           print_fn = fn _ => fn st =>
   444             if Toplevel.is_proof st then Output.state (Toplevel.string_of_state st)
   445             else ()}
   446       else NONE);
   447 
   448 
   449 (* combined execution *)
   450 
   451 type exec = eval * print list;
   452 
   453 fun init_exec opt_thy : exec =
   454   (Eval
   455     {command_id = Document_ID.none, exec_id = Document_ID.none,
   456       eval_process = Lazy.value (init_eval_state opt_thy)}, []);
   457 
   458 val no_exec = init_exec NONE;
   459 
   460 fun exec_ids NONE = []
   461   | exec_ids (SOME (eval, prints)) = eval_exec_id eval :: map print_exec_id prints;
   462 
   463 local
   464 
   465 fun run_process execution_id exec_id process =
   466   let val group = Future.worker_subgroup () in
   467     if Execution.running execution_id exec_id [group] then
   468       ignore (task_context group (fn () => Lazy.force_result {strict = true} process) ())
   469     else ()
   470   end;
   471 
   472 fun ignore_process process =
   473   Lazy.is_running process orelse Lazy.is_finished process;
   474 
   475 fun run_eval execution_id (Eval {exec_id, eval_process, ...}) =
   476   if Lazy.is_finished eval_process then ()
   477   else run_process execution_id exec_id eval_process;
   478 
   479 fun fork_print execution_id deps (Print {name, delay, pri, exec_id, print_process, ...}) =
   480   let
   481     val group = Future.worker_subgroup ();
   482     fun fork () =
   483       ignore ((singleton o Future.forks)
   484         {name = name, group = SOME group, deps = deps, pri = pri, interrupts = true}
   485         (fn () =>
   486           if ignore_process print_process then ()
   487           else run_process execution_id exec_id print_process));
   488   in
   489     (case delay of
   490       NONE => fork ()
   491     | SOME d => ignore (Event_Timer.request {physical = true} (Time.now () + d) fork))
   492   end;
   493 
   494 fun run_print execution_id (print as Print {exec_id, print_process, ...}) =
   495   if ignore_process print_process then ()
   496   else if parallel_print print then fork_print execution_id [] print
   497   else run_process execution_id exec_id print_process;
   498 
   499 in
   500 
   501 fun exec execution_id (eval, prints) =
   502   (run_eval execution_id eval; List.app (run_print execution_id) prints);
   503 
   504 fun exec_parallel_prints execution_id deps (exec as (Eval {eval_process, ...}, prints)) =
   505   if Lazy.is_finished eval_process
   506   then (List.app (fork_print execution_id deps) prints; NONE)
   507   else SOME exec;
   508 
   509 end;
   510 
   511 end;