Debian Codegraph @

vernac/topfmt.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 (** Pp control also belongs here as the terminal is private to the toplevel *)
14
15 type pp_global_params = {
16 margin : int;
17 max_indent : int;
18 max_depth : int;
19 ellipsis : string }
20
21 (* Default parameters of pretty-printing *)
22
23 let dflt_gp = {
24 margin = 78;
25 max_indent = 50;
26 max_depth = 50;
27 ellipsis = "..." }
28
29 (* A deeper pretty-printer to print proof scripts *)
30
31 let deep_gp = {
32 margin = 78;
33 max_indent = 50;
34 max_depth = 10000;
35 ellipsis = "..." }
36
37 (* set_gp : Format.formatter -> pp_global_params -> unit
38 * set the parameters of a formatter *)
39
40 let set_gp ft gp =
41 Format.pp_set_margin ft gp.margin ;
42 Format.pp_set_max_indent ft gp.max_indent ;
43 Format.pp_set_max_boxes ft gp.max_depth ;
44 Format.pp_set_ellipsis_text ft gp.ellipsis
45
46 let set_dflt_gp ft = set_gp ft dflt_gp
47
48 let get_gp ft =
49 { margin = Format.pp_get_margin ft ();
50 max_indent = Format.pp_get_max_indent ft ();
51 max_depth = Format.pp_get_max_boxes ft ();
52 ellipsis = Format.pp_get_ellipsis_text ft () }
53
54 (* with_fp : 'a pp_formatter_params -> Format.formatter
55 * returns of formatter for given formatter functions *)
56
57 let with_fp chan out_function flush_function =
58 let ft = Format.make_formatter out_function flush_function in
59 Format.pp_set_formatter_out_channel ft chan;
60 ft
61
62 (* Output on a channel ch *)
63
64 let with_output_to ch =
65 let ft = with_fp ch (output_substring ch) (fun () -> flush ch) in
66 set_gp ft deep_gp;
67 ft
68
69 let std_ft = ref Format.std_formatter
70 let _ = set_dflt_gp !std_ft
71
72 let err_ft = ref Format.err_formatter
73 let _ = set_gp !err_ft deep_gp
74
75 let deep_ft = ref (with_output_to stdout)
76 let _ = set_gp !deep_ft deep_gp
77
78 (* For parametrization through vernacular *)
79 let default = Format.pp_get_max_boxes !std_ft ()
80 let default_margin = Format.pp_get_margin !std_ft ()
81
82 let get_depth_boxes () = Some (Format.pp_get_max_boxes !std_ft ())
83 let set_depth_boxes v =
84 let v = (match v with None -> default | Some v -> v) in
85 Constrextern.set_max_depth (Some v);
86 Format.pp_set_max_boxes !std_ft v
87
88 let get_margin0 () = Format.pp_get_margin !std_ft ()
89
90 let () = Profile_tactic.set_get_printing_width get_margin0
91
92 let get_margin () = Some (get_margin0())
93 let set_margin v =
94 let v = match v with None -> default_margin | Some v -> v in
95 Format.pp_set_margin Format.str_formatter v;
96 Format.pp_set_margin !std_ft v;
97 Format.pp_set_margin !deep_ft v;
98 Format.pp_set_margin !err_ft v;
99 (* Heuristic, based on usage: the column on the right of max_indent
100 column is 20% of width, capped to 30 characters *)
101 let m = max (64 * v / 100) (v-30) in
102 Format.pp_set_max_indent Format.str_formatter m;
103 Format.pp_set_max_indent !std_ft m;
104 Format.pp_set_max_indent !deep_ft m;
105 Format.pp_set_max_indent !err_ft m
106
107 (** Console display of feedback *)
108
109 (** Default tags *)
110 module Tag = struct
111
112 let error = "message.error"
113 let warning = "message.warning"
114 let debug = "message.debug"
115
116 end
117
118 let msgnl_with fmt strm =
119 pp_with fmt (strm ++ fnl ());
120 Format.pp_print_flush fmt ()
121
122 module Emacs = struct
123
124 (* Special chars for emacs, to detect warnings inside goal output *)
125 let quote_warning_start = "<warning>"
126 let quote_warning_end = "</warning>"
127
128 let quote_info_start = "<infomsg>"
129 let quote_info_end = "</infomsg>"
130
131 let quote_emacs q_start q_end msg =
132 hov 0 (seq [str q_start; brk(0,0); msg; brk(0,0); str q_end])
133
134 let quote_warning = quote_emacs quote_warning_start quote_warning_end
135 let quote_info = quote_emacs quote_info_start quote_info_end
136
137 end
138
139 let dbg_hdr = tag Tag.debug (str "Debug:") ++ spc ()
140 let info_hdr = mt ()
141 let warn_hdr = tag Tag.warning (str "Warning:") ++ spc ()
142 let err_hdr = tag Tag.error (str "Error:") ++ spc ()
143
144 let make_body quoter info ?pre_hdr ?(qf=[]) s =
145 let main = hov 0 (info ++ s) in
146 let main = match qf with
147 | (_ :: _ as qf) when !Flags.test_mode -> v 0 (main ++ cut () ++ Quickfix.print qf)
148 | _ -> main in
149 pr_opt_no_spc (fun x -> x ++ fnl ()) pre_hdr ++ quoter main
150
151 (* The empty quoter *)
152 let noq x = x
153 (* Generic logger *)
154 let gen_logger dbg warn ?qf ?pre_hdr level msg = let open Feedback in match level with
155 | Debug -> msgnl_with !std_ft (make_body dbg dbg_hdr ?pre_hdr ?qf msg)
156 | Info -> msgnl_with !std_ft (make_body dbg info_hdr ?pre_hdr ?qf msg)
157 | Notice -> msgnl_with !std_ft (make_body noq info_hdr ?pre_hdr ?qf msg)
158 | Warning -> msgnl_with !err_ft (make_body warn warn_hdr ?pre_hdr ?qf msg)
159 | Error -> msgnl_with !err_ft (make_body noq err_hdr ?pre_hdr ?qf msg)
160
161 (** Standard loggers *)
162
163 (* We provide a generic clear_log_backend callback for backends
164 wanting to do cleanup after the print.
165 *)
166 let std_logger_cleanup = ref (fun () -> ())
167
168 let std_logger ?qf ?pre_hdr level msg =
169 gen_logger (fun x -> x) (fun x -> x) ?qf ?pre_hdr level msg;
170 !std_logger_cleanup ()
171
172 (** Color logging. Moved from Ppstyle, it may need some more refactoring *)
173
174 (* Tag map for terminal style *)
175 let default_tag_map () = let open Terminal in [
176 (* Local to console toplevel *)
177 "message.error" , make ~bold:true ~fg_color:`WHITE ~bg_color:`RED ()
178 ; "message.warning" , make ~bold:true ~fg_color:`WHITE ~bg_color:`YELLOW ()
179 ; "message.debug" , make ~bold:true ~fg_color:`WHITE ~bg_color:`MAGENTA ()
180 ; "message.prompt" , make ~fg_color:`GREEN ()
181 (* Coming from the printer *)
182 ; "constr.evar" , make ~fg_color:`LIGHT_BLUE ()
183 ; "constr.keyword" , make ~bold:true ()
184 ; "constr.type" , make ~bold:true ~fg_color:`YELLOW ()
185 ; "constr.notation" , make ~fg_color:`WHITE ()
186 (* ["constr"; "variable"] is not assigned *)
187 ; "constr.reference" , make ~fg_color:`LIGHT_GREEN ()
188 ; "constr.path" , make ~fg_color:`LIGHT_MAGENTA ()
189 ; "module.definition", make ~bold:true ~fg_color:`LIGHT_RED ()
190 ; "module.keyword" , make ~bold:true ()
191 ; "tactic.keyword" , make ~bold:true ()
192 ; "tactic.primitive" , make ~fg_color:`LIGHT_GREEN ()
193 ; "tactic.string" , make ~fg_color:`LIGHT_RED ()
194 ; "diff.added" , make ~bg_color:(`RGB(0,141,0)) ~underline:true ()
195 ; "diff.removed" , make ~bg_color:(`RGB(170,0,0)) ~underline:true ()
196 ; "diff.added.bg" , make ~bg_color:(`RGB(0,91,0)) ()
197 ; "diff.removed.bg" , make ~bg_color:(`RGB(91,0,0)) ()
198 ]
199
200 let tag_map = ref CString.Map.empty
201
202 let init_tag_map styles =
203 let set accu (name, st) = CString.Map.add name st accu in
204 tag_map := List.fold_left set !tag_map styles
205
206 let default_styles () =
207 init_tag_map (default_tag_map ())
208
209 let set_emacs_print_strings () =
210 let open Terminal in
211 let diff = "diff." in
212 List.iter (fun b ->
213 let (name, attrs) = b in
214 if CString.is_sub diff name 0 then
215 tag_map := CString.Map.add name
216 { attrs with prefix = Some (Printf.sprintf "<%s>" name);
217 suffix = Some (Printf.sprintf "</%s>" name) }
218 !tag_map)
219 (CString.Map.bindings !tag_map)
220
221 let parse_color_config str =
222 let styles = Terminal.parse str in
223 init_tag_map styles
224
225 let dump_tags () = CString.Map.bindings !tag_map
226
227 let empty = Terminal.make ()
228 let default_style = Terminal.reset_style
229
230 let get_style tag =
231 try CString.Map.find tag !tag_map
232 with Not_found -> empty;;
233
234 let get_open_seq tags =
235 let style = List.fold_left (fun a b -> Terminal.merge a (get_style b)) default_style tags in
236 Terminal.eval (Terminal.diff default_style style);;
237
238 let get_close_seq tags =
239 let style = List.fold_left (fun a b -> Terminal.merge a (get_style b)) default_style tags in
240 Terminal.eval (Terminal.diff style default_style);;
241
242 let diff_tag_stack = ref [] (* global, just like std_ft *)
243
244 (** Not thread-safe. We should put a lock somewhere if we print from
245 different threads. Do we? *)
246 let make_style_stack () =
247 (* Default tag is to reset everything *)
248 let style_stack = ref [] in
249 let peek () = match !style_stack with
250 | [] -> default_style (* Anomalous case, but for robustness *)
251 | st :: _ -> st
252 in
253 let open_tag = function
254 | Format.String_tag tag ->
255 let (tpfx, ttag) = split_tag tag in
256 if tpfx = end_pfx then "" else
257 let style = get_style ttag in
258 (* Merge the current settings and the style being pushed. This
259 allows restoring the previous settings correctly in a pop
260 when both set the same attribute. Example: current settings
261 have red FG, the pushed style has green FG. When popping the
262 style, we should set red FG, not default FG. *)
263 let style = Terminal.merge (peek ()) style in
264 let diff = Terminal.diff (peek ()) style in
265 style_stack := style :: !style_stack;
266 if tpfx = start_pfx then diff_tag_stack := ttag :: !diff_tag_stack;
267 Terminal.eval diff
268 | _ -> Terminal.eval default_style
269 in
270 let close_tag = function
271 | Format.String_tag tag ->
272 let (tpfx, _) = split_tag tag in
273 if tpfx = start_pfx then "" else begin
274 if tpfx = end_pfx then diff_tag_stack := (match !diff_tag_stack with _ :: tl -> tl | [] -> []);
275 match !style_stack with
276 | [] -> (* Something went wrong, we fallback *)
277 Terminal.eval default_style
278 | cur :: rem -> style_stack := rem;
279 if cur = (peek ()) then "" else
280 if rem = [] then Terminal.reset else
281 Terminal.eval (Terminal.diff cur (peek ()))
282 end
283 | _ -> Terminal.eval default_style
284 in
285 let clear () = style_stack := [] in
286 open_tag, close_tag, clear
287
288 let make_printing_functions () =
289 let print_prefix ft = function
290 | Format.String_tag tag ->
291 let (tpfx, ttag) = split_tag tag in
292 if tpfx <> end_pfx then
293 let style = get_style ttag in
294 (match style.Terminal.prefix with Some s -> Format.pp_print_as ft 0 s | None -> ())
295 | _ -> ()
296 in
297 let print_suffix ft = function
298 | Format.String_tag tag ->
299 let (tpfx, ttag) = split_tag tag in
300 if tpfx <> start_pfx then
301 let style = get_style ttag in
302 (match style.Terminal.suffix with Some s -> Format.pp_print_as ft 0 s | None -> ())
303 | _ -> ()
304 in
305 print_prefix, print_suffix
306
307 let init_output_fns () =
308 let reopen_highlight = ref "" in
309 let open Format in
310 let fns = Format.pp_get_formatter_out_functions !std_ft () in
311 let newline () =
312 if !diff_tag_stack <> [] then begin
313 let close = get_close_seq !diff_tag_stack in
314 fns.out_string close 0 (String.length close);
315 reopen_highlight := get_open_seq (List.rev !diff_tag_stack);
316 end;
317 fns.out_string "\n" 0 1 in
318 let string s off n =
319 if !reopen_highlight <> "" && String.trim (String.sub s off n) <> "" then begin
320 fns.out_string !reopen_highlight 0 (String.length !reopen_highlight);
321 reopen_highlight := ""
322 end;
323 fns.out_string s off n in
324 let new_fns = { fns with out_string = string; out_newline = newline } in
325 Format.pp_set_formatter_out_functions !std_ft new_fns;;
326
327 let init_terminal_output ~color =
328 let open_tag, close_tag, clear_tag = make_style_stack () in
329 let print_prefix, print_suffix = make_printing_functions () in
330 let tag_handler ft = {
331 Format.mark_open_stag = open_tag;
332 Format.mark_close_stag = close_tag;
333 Format.print_open_stag = print_prefix ft;
334 Format.print_close_stag = print_suffix ft;
335 } in
336 if color then
337 (* Use 0-length markers *)
338 begin
339 std_logger_cleanup := clear_tag;
340 init_output_fns ();
341 Format.pp_set_mark_tags !std_ft true;
342 Format.pp_set_mark_tags !err_ft true
343 end
344 else
345 (* Use textual markers *)
346 begin
347 Format.pp_set_print_tags !std_ft true;
348 Format.pp_set_print_tags !err_ft true
349 end;
350 Format.pp_set_formatter_stag_functions !std_ft (tag_handler !std_ft);
351 Format.pp_set_formatter_stag_functions !err_ft (tag_handler !err_ft)
352
353 (* Rules for emacs:
354 - Debug/info: emacs_quote_info
355 - Warning/Error: emacs_quote_err
356 - Notice: unquoted
357 *)
358 let emacs_logger = gen_logger Emacs.quote_info Emacs.quote_warning
359
360 (* This is specific to the toplevel *)
361
362 type execution_phase =
363 | ParsingCommandLine
364 | Initialization
365 | LoadingPrelude
366 | LoadingRcFile
367 | InteractiveLoop
368 | CompilationPhase
369
370 let default_phase = ref InteractiveLoop
371
372 let in_phase ~phase f x =
373 let op = !default_phase in
374 default_phase := phase;
375 try
376 let res = f x in
377 default_phase := op;
378 res
379 with exn ->
380 let iexn = Exninfo.capture exn in
381 default_phase := op;
382 Exninfo.iraise iexn
383
384 let pr_loc loc =
385 Loc.pr loc ++ str ":"
386
387 let pr_phase ?loc () =
388 match !default_phase, loc with
389 | LoadingRcFile, loc ->
390 (* For when all errors go through feedback:
391 str "While loading rcfile:" ++
392 Option.cata (fun loc -> fnl () ++ pr_loc loc) (mt ()) loc *)
393 Option.map pr_loc loc
394 | LoadingPrelude, loc ->
395 Some (str "While loading initial state:" ++ Option.cata (fun loc -> fnl () ++ pr_loc loc) (mt ()) loc)
396 | _, Some loc -> Some (pr_loc loc)
397 | ParsingCommandLine, _
398 | Initialization, _
399 | CompilationPhase, _ ->
400 None
401 | InteractiveLoop, _ ->
402 (* Note: interactive messages such as "foo is defined" are not located *)
403 None
404
405 let print_err_exn any =
406 let (e, info) = Exninfo.capture any in
407 let loc = Loc.get_loc info in
408 let pre_hdr = pr_phase ?loc () in
409 let msg = CErrors.iprint (e, info) ++ fnl () in
410 std_logger ?pre_hdr Feedback.Error msg
411
412 let with_output_to_file ~truncate fname func input =
413 let fname = String.concat "." [fname; "out"] in
414 let fullfname = System.get_output_path fname in
415 System.mkdir (Filename.dirname fullfname);
416 let channel =
417 let flags = [Open_wronly; Open_creat; Open_text] in
418 let flags = if truncate then Open_trunc :: flags else flags in
419 open_out_gen flags 0o666 fullfname
420 in
421 let old_fmt = !std_ft, !err_ft, !deep_ft in
422 let new_ft = Format.formatter_of_out_channel channel in
423 set_gp new_ft (get_gp !std_ft);
424 std_ft := new_ft;
425 err_ft := new_ft;
426 deep_ft := new_ft;
427 try
428 let output = func input in
429 std_ft := Util.pi1 old_fmt;
430 err_ft := Util.pi2 old_fmt;
431 deep_ft := Util.pi3 old_fmt;
432 Format.pp_print_flush new_ft ();
433 close_out channel;
434 output
435 with reraise ->
436 let reraise = Exninfo.capture reraise in
437 std_ft := Util.pi1 old_fmt;
438 err_ft := Util.pi2 old_fmt;
439 deep_ft := Util.pi3 old_fmt;
440 Format.pp_print_flush new_ft ();
441 close_out channel;
442 Exninfo.iraise reraise
443
444 (* For coqtop -time, we display the position in the file,
445 and a glimpse of the executed command *)
446
447 let pr_cmd_header com =
448 let shorten s =
449 if Unicode.utf8_length s > 33 then (Unicode.utf8_sub s 0 30) ^ "..." else s
450 in
451 let noblank s = String.map (fun c ->
452 match c with
453 | ' ' | '\n' | '\t' | '\r' -> '~'
454 | x -> x
455 ) s
456 in
457 let (start,stop) = Option.cata Loc.unloc (0,0) com.CAst.loc in
458 let safe_pr_vernac x =
459 try Ppvernac.pr_vernac x
460 with e -> str (Printexc.to_string e) in
461 let cmd = noblank (shorten (string_of_ppcmds (safe_pr_vernac com)))
462 in str "Chars " ++ int start ++ str " - " ++ int stop ++
463 str " [" ++ str cmd ++ str "] "