Debian Codegraph @

toplevel/coqloop.ml

raw symbols SCIP
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * Copyright INRIA, CNRS and contributors *)
4 (* <O___,, * (see version control and CREDITS file for authors & dates) *)
5 (* \VV/ **************************************************************)
6 (* // * This file is distributed under the terms of the *)
7 (* * GNU Lesser General Public License Version 2.1 *)
8 (* * (see LICENSE file for the text of the license) *)
9 (************************************************************************)
10
11 open Pp
12
13 let print_emacs = ref false
14
15 let top_stderr x =
16 Format.fprintf !Topfmt.err_ft "@[%a@]%!" pp_with x
17
18 (* A buffer for the character read from a channel. We store the command
19 * entered to be able to report errors without pretty-printing. *)
20
21 type input_buffer = {
22 mutable prompt : Stm.doc -> string;
23 mutable str : Bytes.t; (* buffer of already read characters *)
24 mutable len : int; (* number of chars in the buffer *)
25 mutable bols : int list; (* offsets in str of beginning of lines *)
26 mutable stream : (unit,char) Gramlib.Stream.t; (* stream of chars *)
27 mutable tokens : Procq.Parsable.t; (* stream of tokens *)
28 mutable start : int } (* stream count of the first char of the buffer *)
29
30 (* Double the size of the buffer. *)
31
32 let resize_buffer ibuf = let open Bytes in
33 let nstr = create (2 * length ibuf.str + 1) in
34 blit ibuf.str 0 nstr 0 (length ibuf.str);
35 ibuf.str <- nstr
36
37 let peek_to_newline ibuf =
38 (* peek to see a newline following the latest command
39 cf #19355 *)
40 let rec aux n =
41 let l = Gramlib.Stream.npeek () n ibuf.stream in
42 if List.length l < n then ()
43 else match CList.last l with
44 | '\n' -> ()
45 | ' ' | '\t' -> aux (n+1)
46 | _ -> (* nonblank character: the latest command is not the last on this line *) ()
47 in
48 aux 1
49
50 (* Delete all irrelevant lines of the input buffer. Keep the last line
51 in the buffer (useful when there are several commands on the same line). *)
52 let resynch_buffer ibuf =
53 let () = peek_to_newline ibuf in
54 match ibuf.bols with
55 | ll::_ ->
56 let new_len = ibuf.len - ll in
57 Bytes.blit ibuf.str ll ibuf.str 0 new_len;
58 ibuf.len <- new_len;
59 ibuf.bols <- [];
60 ibuf.start <- ibuf.start + ll
61 | _ -> ()
62
63
64 (* emacs special prompt tag for easy detection. No special character,
65 to avoid interfering with utf8. Compatibility code removed. *)
66 let emacs_prompt_startstring () = if !print_emacs then "<prompt>" else ""
67 let emacs_prompt_endstring () = if !print_emacs then "</prompt>" else ""
68
69 (* Read a char in an input channel, displaying a prompt at every
70 beginning of line. *)
71 let prompt_char doc ic ibuf () =
72 let bol = match ibuf.bols with
73 | ll::_ -> Int.equal ibuf.len ll
74 | [] -> Int.equal ibuf.len 0
75 in
76 if bol && not !print_emacs then top_stderr (str (ibuf.prompt doc));
77 try
78 let c = input_char ic in
79 if c == '\n' then ibuf.bols <- (ibuf.len+1) :: ibuf.bols;
80 if ibuf.len == Bytes.length ibuf.str then resize_buffer ibuf;
81 Bytes.set ibuf.str ibuf.len c;
82 ibuf.len <- ibuf.len + 1;
83 Some c
84 with End_of_file ->
85 None
86
87 (* Functions to print underlined locations from an input buffer. *)
88 module TopErr = struct
89
90 (* Given a location, returns the list of locations of each line. The last
91 line is returned separately. It also checks the location bounds. *)
92
93 let get_bols_of_loc ibuf (bp,ep) =
94 let add_line (b,e) lines =
95 if b < 0 || e < b then CErrors.anomaly (Pp.str "Bad location.");
96 match lines with
97 | ([],None) -> ([], Some (b,e))
98 | (fl,oe) -> ((b,e)::fl, oe)
99 in
100 let rec lines_rec ba after = function
101 | [] -> add_line (0,ba) after
102 | ll::_ when ll <= bp -> add_line (ll,ba) after
103 | ll::fl ->
104 let nafter = if ll < ep then add_line (ll,ba) after else after in
105 lines_rec ll nafter fl
106 in
107 let bols = match ibuf.bols with
108 | [] -> [ibuf.len+1] (* no newline at the end of the command, pretend there was one *)
109 | _ :: _ as bols -> bols
110 in
111 let (fl,ll) = lines_rec ibuf.len ([],None) bols in
112 (fl,Option.get ll)
113
114 let dotted_location (b,e) =
115 if e-b < 3 then
116 ("", String.make (e-b) ' ')
117 else
118 (String.make (e-b-1) '.', " ")
119
120 let blanch_utf8_string s bp ep = let open Bytes in
121 let s' = make (ep-bp) ' ' in
122 let j = ref 0 in
123 for i = bp to ep - 1 do
124 let n = Char.code (get s i) in
125 (* Heuristic: assume utf-8 chars are printed using a single
126 fixed-size char and therefore contract all utf-8 code into one
127 space; in any case, preserve tabulation so
128 that its effective interpretation in terms of spacing is preserved *)
129 if get s i == '\t' then set s' !j '\t';
130 if n < 0x80 || 0xC0 <= n then incr j
131 done;
132 Bytes.sub_string s' 0 !j
133
134 let adjust_loc_buf ib loc = let open Loc in
135 { loc with ep = loc.ep - ib.start; bp = loc.bp - ib.start }
136
137 let print_highlight_location ib loc =
138 let (bp,ep) = Loc.unloc loc in
139 let highlight_lines =
140 match get_bols_of_loc ib (bp,ep) with
141 | ([],(bl,el)) ->
142 let shift = blanch_utf8_string ib.str bl bp in
143 let span = String.length (blanch_utf8_string ib.str bp ep) in
144 (str"> " ++ str(Bytes.sub_string ib.str bl (el-bl-1)) ++ fnl () ++
145 str"> " ++ str(shift) ++ str(String.make span '^'))
146 | ((b1,e1)::ml,(bn,en)) ->
147 let (d1,s1) = dotted_location (b1,bp) in
148 let (dn,sn) = dotted_location (ep,en) in
149 let l1 = (str"> " ++ str d1 ++ str s1 ++
150 str(Bytes.sub_string ib.str bp (e1-bp))) in
151 let li =
152 prlist (fun (bi,ei) ->
153 (str"> " ++ str(Bytes.sub_string ib.str bi (ei-bi)))) ml in
154 let ln = (str"> " ++ str(Bytes.sub_string ib.str bn (ep-bn)) ++
155 str sn ++ str dn) in
156 (l1 ++ li ++ ln)
157 in
158 highlight_lines
159
160 let valid_buffer_loc ib loc =
161 let (b,e) = Loc.unloc loc in b-ib.start >= 0 && e-ib.start <= ib.len && b<=e
162
163 (* Toplevel error explanation. *)
164 let error_info_for_buffer ?loc buf =
165 match loc with
166 | None -> Topfmt.pr_phase ?loc ()
167 | Some loc ->
168 let fname = loc.Loc.fname in
169 (* We are in the toplevel *)
170 match fname with
171 | Loc.ToplevelInput ->
172 let nloc = adjust_loc_buf buf loc in
173 if valid_buffer_loc buf loc then
174 match Topfmt.pr_phase ~loc:nloc () with
175 | None -> None
176 | Some hd -> Some (hd ++ fnl () ++ print_highlight_location buf nloc)
177 (* in the toplevel, but not a valid buffer *)
178 else Topfmt.pr_phase ~loc ()
179 (* we are in batch mode, don't adjust location *)
180 | Loc.InFile _ -> Topfmt.pr_phase ~loc ()
181
182 (* Actual printing routine *)
183 let print_error_for_buffer ?loc ?qf lvl msg buf =
184 let pre_hdr = error_info_for_buffer ?loc buf in
185 if !print_emacs
186 then Topfmt.emacs_logger ?pre_hdr lvl msg
187 else Topfmt.std_logger ?pre_hdr ?qf lvl msg
188
189 (*
190 let print_toplevel_parse_error (e, info) buf =
191 let loc = Loc.get_loc info in
192 let lvl = Feedback.Error in
193 let msg = CErrors.iprint (e, info) in
194 print_error_for_buffer ?loc lvl msg buf
195 *)
196 end
197
198 (*s The Rocq prompt is the name of the focused proof, if any, and "Rocq"
199 otherwise. We trap all exceptions to prevent the error message printing
200 from cycling. *)
201 let make_prompt () =
202 try
203 (Names.Id.to_string (Vernacstate.Declare.get_current_proof_name ())) ^ " < "
204 with Vernacstate.Declare.NoCurrentProof ->
205 "Rocq < "
206 [@@ocaml.warning "-3"]
207
208 (* the rocq prompt added to the default one when in emacs mode
209 The prompt contains the current state label [n] (for global
210 backtracking) and the current proof state [p] (for proof
211 backtracking) plus the list of open (nested) proofs (for proof
212 aborting when backtracking). It looks like:
213
214 "n |lem1|lem2|lem3| p < "
215 *)
216 let make_emacs_prompt doc =
217 let statnum = Stateid.to_string (Stm.get_current_state ~doc) in
218 let dpth = Stm.current_proof_depth ~doc in
219 let pending = Stm.get_all_proof_names ~doc in
220 let pendingprompt =
221 List.fold_left
222 (fun acc x -> acc ^ (if CString.is_empty acc then "" else "|") ^ Names.Id.to_string x)
223 "" pending in
224 let proof_info = if dpth >= 0 then string_of_int dpth else "0" in
225 if !print_emacs then statnum ^ " |" ^ pendingprompt ^ "| " ^ proof_info ^ " < "
226 else ""
227
228 (* A buffer to store the current command read on stdin. It is
229 * initialized when a vernac command is immediately followed by "\n",
230 * or after a Drop. *)
231 let top_buffer =
232 let pr doc =
233 emacs_prompt_startstring()
234 ^ make_prompt()
235 ^ make_emacs_prompt doc
236 ^ emacs_prompt_endstring()
237 in
238 let stream = Gramlib.Stream.empty () in
239 { prompt = pr;
240 str = Bytes.empty;
241 len = 0;
242 bols = [];
243 stream;
244 tokens = Procq.Parsable.make stream;
245 start = 0 }
246
247 (* Intialize or reinitialize the char stream *)
248 let reset_input_buffer ~state =
249 let stream = Gramlib.Stream.from (prompt_char state.Vernac.State.doc stdin top_buffer) in
250 top_buffer.str <- Bytes.empty;
251 top_buffer.len <- 0;
252 top_buffer.bols <- [];
253 top_buffer.stream <- stream;
254 top_buffer.tokens <- Procq.Parsable.make stream;
255 top_buffer.start <- 0
256
257 let set_prompt prompt =
258 top_buffer.prompt
259 <- (fun doc ->
260 emacs_prompt_startstring()
261 ^ prompt ()
262 ^ emacs_prompt_endstring())
263
264 (* Read the input stream until a dot is encountered *)
265 let parse_to_dot =
266 let rec dot kwstate st = match Gramlib.LStream.next kwstate st with
267 | Some (Tok.KEYWORD ("."|"...")) -> Ok ()
268 | Some Tok.EOI -> Ok ()
269 | Some _ -> dot kwstate st
270 | None -> Error ()
271 in
272 Procq.Entry.(of_parser "Coqtoplevel.dot" { parser_fun = dot })
273
274 (* If an error occurred while parsing, we try to read the input until a dot
275 token is encountered.
276 We assume that when a lexer error occurs, at least one char was eaten *)
277
278 let rec discard_to_dot () =
279 try
280 Procq.Entry.parse parse_to_dot top_buffer.tokens
281 with
282 | CLexer.Error.E _ -> (* Lexer failed *) discard_to_dot ()
283 | e when CErrors.noncritical e -> ()
284
285 let read_sentence ~state input =
286 (* XXX: careful with ignoring the state Eugene!*)
287 let open Vernac.State in
288 try Stm.parse_sentence ~doc:state.doc state.sid ~entry:G_toplevel.vernac_toplevel input
289 with reraise ->
290 let reraise = Exninfo.capture reraise in
291 (* When typing Ctrl-C, two situations may arise:
292 - if a lexer/parsing arrived first, the rest of the ill-formed
293 sentence needs to be discarded, and, if Ctrl-C is found while
294 trying to discarding (in discard_to_dot), let it bypass the
295 reporting of the parsing error and report the Sys.Break
296 instead.
297 - if a Ctrl-C arrives after a valid start of sentence, do not
298 discard_to_dot since Ctrl-C is the last read character and
299 there is nothing left to discard. *)
300 (match fst reraise with
301 | Sys.Break -> Pp.pp_with !Topfmt.err_ft (Pp.fnl ())
302 | _ ->
303 try discard_to_dot ()
304 with Sys.Break ->
305 Pp.pp_with !Topfmt.err_ft (Pp.fnl ());
306 raise Sys.Break);
307 (* The caller of read_sentence does the error printing now, this
308 should be re-enabled once we rely on the feedback error
309 printer again *)
310 (* TopErr.print_toplevel_parse_error reraise top_buffer; *)
311 Exninfo.iraise reraise
312
313 let extract_default_loc loc doc_id sid : Loc.t option =
314 match loc with
315 | Some _ -> loc
316 | None ->
317 try
318 let doc = Stm.get_doc doc_id in
319 Option.cata (fun {CAst.loc} -> loc) None Stm.(get_ast ~doc sid)
320 with _ -> loc
321
322 (** Coqloop Console feedback handler *)
323 let coqloop_feed (fb : Feedback.feedback) = let open Feedback in
324 match fb.contents with
325 | Processed -> ()
326 | Incomplete -> ()
327 | Complete -> ()
328 | ProcessingIn _ -> ()
329 | InProgress _ -> ()
330 | WorkerStatus (_,_) -> ()
331 | AddedAxiom -> ()
332 | GlobRef (_,_,_,_,_) -> ()
333 | GlobDef (_,_,_,_) -> ()
334 | FileDependency (_,_) -> ()
335 | FileLoaded (_,_) -> ()
336 | Custom (_,_,_) -> ()
337 (* Re-enable when we switch back to feedback-based error printing *)
338 | Message (Error,loc,_,msg) -> ()
339 (* TopErr.print_error_for_buffer ?loc lvl msg top_buffer *)
340 | Message (Warning,loc,qf,msg) ->
341 let loc = extract_default_loc loc fb.doc_id fb.span_id in
342 TopErr.print_error_for_buffer ?loc ~qf Warning msg top_buffer
343 | Message (lvl,loc,qf,msg) ->
344 TopErr.print_error_for_buffer ?loc ~qf lvl msg top_buffer
345
346 (** Main rocq loop : read vernacular expressions until Drop is entered.
347 Ctrl-C is handled internally as Sys.Break instead of aborting Rocq.
348 Normally, the only exceptions that can come out of [do_vernac] and
349 exit the loop are Drop and Quit. Any other exception there indicates
350 an issue with [print_toplevel_error] above. *)
351
352 (* Flush in a compatible order with 8.5 *)
353 (* This mimics the semantics of the old Pp.flush_all *)
354 let loop_flush_all () =
355 flush stderr;
356 flush stdout;
357 Format.pp_print_flush !Topfmt.std_ft ();
358 Format.pp_print_flush !Topfmt.err_ft ()
359
360 (* Goal equality heuristic. *)
361 let pequal cmp1 cmp2 (a1,a2) (b1,b2) = cmp1 a1 b1 && cmp2 a2 b2
362 let evleq e1 e2 = CList.equal Evar.equal e1 e2
363 let cproof p1 p2 =
364 let Proof.{goals=a1;stack=a2;sigma=sigma1} = Proof.data p1 in
365 let Proof.{goals=b1;stack=b2;sigma=sigma2} = Proof.data p2 in
366 evleq a1 b1 &&
367 CList.equal (pequal evleq evleq) a2 b2 &&
368 CList.equal Evar.equal (Evd.shelf sigma1) (Evd.shelf sigma2) &&
369 Evar.Set.equal (Evd.given_up sigma1) (Evd.given_up sigma2)
370
371 (* todo: could add other Set/Unset commands, such as "Printing Universes" *)
372 let print_anyway_opts = [
373 [ "Diffs" ];
374 ]
375
376 let print_anyway c =
377 let open Vernacexpr in
378 match c.expr with
379 | VernacSynterp (VernacSetOption (_, opt, _)) -> List.mem opt print_anyway_opts
380 | _ -> false
381
382 (* print the proof step, possibly with diffs highlighted, *)
383 let print_and_diff oldp proof =
384 let output =
385 if Proof_diffs.show_diffs () then
386 try Printer.pr_open_subgoals ~oldp proof
387 with Pp_diff.Diff_Failure msg -> begin
388 (* todo: print the unparsable string (if we know it) *)
389 Feedback.msg_warning Pp.(str ("Diff failure: " ^ msg) ++ cut()
390 ++ str "Showing results without diff highlighting" );
391 Printer.pr_open_subgoals proof
392 end
393 else
394 Printer.pr_open_subgoals proof
395 in
396 Feedback.msg_notice output
397
398 (* We try to behave better when goal printing raises an exception
399 [usually Ctrl-C]
400
401 This is mostly a hack as we should protect printing in a more
402 generic way, but that'll do for now *)
403 let top_goal_print ~doc c oldp newp =
404 try
405 let proof_changed = not (Option.equal cproof oldp (Some newp)) in
406 let print_goals = proof_changed && Vernacstate.Declare.there_are_pending_proofs () ||
407 print_anyway c in
408 if not !Flags.quiet && print_goals then begin
409 let dproof = Stm.get_prev_proof ~doc (Stm.get_current_state ~doc) in
410 print_and_diff (Some dproof) newp
411 end
412 with
413 | exn ->
414 let (e, info) = Exninfo.capture exn in
415 let loc = Loc.get_loc info in
416 let msg = CErrors.iprint (e, info) in
417 TopErr.print_error_for_buffer ?loc Feedback.Error msg top_buffer
418 [@@ocaml.warning "-3"]
419
420 let { Goptions.get = exit_on_error } =
421 let open Goptions in
422 declare_bool_option_and_ref
423 ~key:["Rocqtop";"Exit";"On";"Error"]
424 ~value:false
425 ()
426
427 let show_proof_diff_cmd ~state diff_opt =
428 let open Vernac.State in
429 match state.proof with
430 | None -> CErrors.user_err (str "No proofs to diff.")
431 | Some proof ->
432 let old = Stm.get_prev_proof ~doc:state.doc state.sid in
433 Proof_diffs.diff_proofs ~flags:(PrintingFlags.current()) ~diff_opt ?old proof
434
435 let ml_toplevel_state = ref None
436 let ml_toplevel_include_ran = ref false
437
438 (* Initialises the Ocaml toplevel before launching it, so that it can
439 find the "include" file in the *source* directory *)
440 let init_ocaml_path () =
441 let corelib = Findlib.package_directory "rocq-runtime" in
442 let add_subdir dl = Mltop.add_ml_dir (Filename.concat corelib dl) in
443 List.iter add_subdir ("dev" :: Coq_config.all_src_dirs)
444
445 let init_and_run_ml_toploop () =
446 init_ocaml_path ();
447 Flags.with_option Flags.in_ml_toplevel (Mltop.ocaml_toploop ~init_file:"ml_toplevel/include") ()
448
449 (* We return whether the execution should continue and a new state *)
450 let process_toplevel_command ~state stm =
451 let open Vernac.State in
452 let open G_toplevel in
453 match stm with
454 | VernacDrop ->
455 if Mltop.is_ocaml_top() then begin
456 (* Save the last state for [go ()] *)
457 ml_toplevel_state := Some state;
458 (* Initialise and launch the OCaml toplevel *)
459 init_and_run_ml_toploop ();
460 (* Reinitialize the char stream *)
461 reset_input_buffer ~state;
462 (* [go ()] was potentially executed — get the new state *)
463 let state = Option.get !ml_toplevel_state in
464 true, state
465 end else begin
466 Feedback.msg_warning (str "There is no ML toplevel.");
467 true, state
468 end
469
470 | VernacBackTo bid ->
471 let bid = Stateid.of_int bid in
472 let doc, res = Stm.edit_at ~doc:state.doc bid in
473 assert (res = Stm.NewTip);
474 true, { state with doc; sid = bid }
475
476 | VernacQuit ->
477 false, state
478
479 | VernacControl { CAst.loc; v=c } ->
480 let nstate = Vernac.process_expr ~state (CAst.make ?loc c) in
481 let () = if not !print_emacs then match nstate.proof with
482 | None -> ()
483 | Some proof -> top_goal_print ~doc:state.doc c state.proof proof
484 in
485 true, nstate
486
487 | VernacShowGoalAt { gid; sid } ->
488 let proof = Stm.get_proof ~doc:state.doc (Stateid.of_int sid) in
489 let goal = Printer.pr_goal_emacs ~proof gid sid in
490 let () = Feedback.msg_notice goal in
491 true, state
492
493 | VernacShowGoal goalref ->
494 let open Vernac.State in
495 begin match state.proof with
496 | None -> CErrors.user_err (str "This command requires an open proof.")
497 | Some proof ->
498 let oldp = Stm.get_prev_proof ~doc:state.doc state.sid in
499 Feedback.msg_notice @@ Vernacentries.show_goal goalref proof (Some oldp);
500 end;
501 true, state
502
503 | VernacShowProofDiffs diff_opt ->
504 (* We print nothing if there are no goals left *)
505 if not (Proof_diffs.color_enabled ()) then
506 CErrors.user_err Pp.(str "Show Proof Diffs requires setting the \"-color\" command line argument to \"on\" or \"auto\".")
507 else
508 let out = show_proof_diff_cmd ~state diff_opt in
509 Feedback.msg_notice out;
510 true, state
511
512 let read_and_execute ~state =
513 try
514 let input = top_buffer.tokens in
515 match read_sentence ~state input with
516 | Some stm ->
517 process_toplevel_command ~state stm
518 (* End of file *)
519 | None ->
520 top_stderr (fnl ());
521 false, state
522 with
523 (* Exception printing should be done by the feedback listener,
524 however this is not yet ready so we rely on the exception for
525 now. *)
526 | Sys_blocked_io ->
527 (* the parser doesn't like nonblocking mode, cf #10918 *)
528 let msg =
529 Pp.(strbrk "Coqtop needs the standard input to be in blocking mode." ++ spc()
530 ++ str "One way of clearing the non-blocking flag is through Python:" ++ fnl()
531 ++ str " import os" ++ fnl()
532 ++ str " os.set_blocking(0, True)")
533 in
534 TopErr.print_error_for_buffer Feedback.Error msg top_buffer;
535 exit 1
536 | any ->
537 let (e, info) = Exninfo.capture any in
538 let loc = Loc.get_loc info in
539 let msg = CErrors.iprint (e, info) in
540 TopErr.print_error_for_buffer ?loc Feedback.Error msg top_buffer;
541 if exit_on_error () then exit 1;
542 true, state
543
544 let loop ~state =
545 (* Initialize buffer *)
546 reset_input_buffer ~state;
547 Flags.without_option Flags.in_ml_toplevel (fun () ->
548 (* The main loop, as a tail-recursive function *)
549 let rec aux state =
550 loop_flush_all ();
551 top_stderr (fnl());
552 let open Vernac.State in
553 if !print_emacs then top_stderr (str (top_buffer.prompt state.doc));
554 resynch_buffer top_buffer;
555 let new_running, new_state = read_and_execute ~state:state in
556 if new_running then
557 (aux [@ocaml.tailcall]) new_state
558 else
559 new_state in
560 aux state
561 ) ()
562
563 let run ~opts ~state =
564 let open Coqargs in
565 print_emacs := opts.config.print_emacs;
566 (* We initialize the console only if we run the toploop_run *)
567 let tl_feed = Feedback.add_feeder coqloop_feed in
568 let _ : Vernac.State.t = loop ~state in
569 Feedback.del_feeder tl_feed