Debian Codegraph @

printing/proof_diffs.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 (*
12 Displays the differences between successive proof steps in coqtop and RocqIDE.
13 Proof General requires minor changes to make the diffs visible, but this code
14 shouldn't break the existing version of PG. See pp_diff.ml for details on how
15 the diff works.
16
17 Diffs are computed for the hypotheses and conclusion of each goal in the new
18 proof with its matching goal in the old proof.
19
20 Diffs can be enabled in coqtop with 'Set Diffs "on"|"off"|"removed"' or
21 '-diffs on|off|removed' on the OS command line. In RocqIDE, they can be enabled
22 from the View menu. The "on" option shows only the new item with added text,
23 while "removed" shows each modified item twice--once with the old value showing
24 removed text and once with the new value showing added text.
25
26 In RocqIDE, colors and highlights can be set in the Edit/Preferences/Tags panel.
27 For coqtop, these can be set through the ROCQ_COLORS environment variable.
28
29 Limitations/Possible enhancements:
30
31 - coqtop colors were chosen for white text on a black background. They're
32 not the greatest. I didn't want to change the existing green highlight.
33 Suggestions welcome.
34
35 - coqtop underlines removed text because (per Wikipedia) the ANSI escape code
36 for strikeout is not commonly supported (it didn't work on my system). RocqIDE
37 uses strikeout on removed text.
38 *)
39
40 open Pp_diff
41
42 let term_color = ref true
43
44 let write_color_enabled enabled =
45 term_color := enabled
46
47 let color_enabled () = !term_color
48
49 type diffOpt = DiffOff | DiffOn | DiffRemoved
50
51 let diffs_to_string = function
52 | DiffOff -> "off"
53 | DiffOn -> "on"
54 | DiffRemoved -> "removed"
55
56
57 let assert_color_enabled () =
58 if not (color_enabled ()) then
59 CErrors.user_err
60 Pp.(str "Enabling Diffs requires setting the \"-color\" command line argument to \"on\" or \"auto\".")
61
62 let string_to_diffs = function
63 | "off" -> DiffOff
64 | "on" -> assert_color_enabled (); DiffOn
65 | "removed" -> assert_color_enabled (); DiffRemoved
66 | _ -> CErrors.user_err Pp.(str "Diffs option only accepts the following values: \"off\", \"on\", \"removed\".")
67
68 let opt_name = ["Diffs"]
69
70 let { Goptions.get = diff_option } =
71 Goptions.declare_interpreted_string_option_and_ref
72 ~key:opt_name
73 ~value:DiffOff
74 string_to_diffs
75 diffs_to_string
76 ()
77
78 let show_diffs () = match diff_option () with DiffOff -> false | _ -> true
79 let show_removed () = match diff_option () with DiffRemoved -> true | _ -> false
80
81
82 (* DEBUG/UNIT TEST *)
83 let cfprintf oc = Printf.(kfprintf (fun oc -> fprintf oc "") oc)
84 let log_out_ch = ref stdout
85 [@@@ocaml.warning "-32"]
86 let cprintf s = cfprintf !log_out_ch s
87 [@@@ocaml.warning "+32"]
88
89 let tokenize_string s =
90 (* todo: cLexer changes buff as it proceeds. Seems like that should be saved, too.
91 But I don't understand how it's used--it looks like things get appended to it but
92 it never gets cleared. *)
93 let kwstate = Procq.get_keyword_state() in
94 let rec stream_tok acc str =
95 let e = Gramlib.LStream.next kwstate str in
96 match e with
97 | Some Tok.EOI -> List.rev acc
98 | Some e -> stream_tok ((Tok.extract_string true e) :: acc) str
99 | None -> raise Exit
100 in
101 let st = CLexer.Lexer.State.get () in
102 Fun.protect ~finally:(fun () -> CLexer.Lexer.State.set st) @@ fun () ->
103 try
104 let istr = Gramlib.Stream.of_string s in
105 let lex = CLexer.LexerDiff.tok_func istr in
106 stream_tok [] lex
107 with exn when CErrors.noncritical exn ->
108 raise (Diff_Failure "Input string is not lexable")
109
110 type hyp_info = {
111 idents: string list;
112 rhs_pp: Pp.t;
113 }
114
115 (* Diff the old and new hypotheses. The RHS (starting at ":" or ":=") is diffed with
116 the same token-based diff used for goal conclusions. Identifiers in the LHS are
117 handled differently:
118
119 The order and grouping of LHS identifiers in the added/unchanged lines is always
120 the same as when diff is not enabled. Identifiers existing in the old context
121 that are present in the new context with the same RHS are not highlighted. New
122 identifiers are always highlighted.
123
124 If all the existing identifiers in a line have a new RHS, those identifiers are
125 not highlighted (in this case, the RHS will be highlighted, making the change clear).
126
127 Removed and added lines are generated in separate passes. Removed lines appear
128 before the added line that has most identifiers in common with the old. (For
129 a tie, use the first one found. For zero in common, put the removal before
130 the first addition/common line.) This should be a good but not perfect
131 approximation to what a human might do.
132 *)
133 let diff_hyps o_idents_in_lines o_map n_idents_in_lines n_map =
134 let rv : Pp.t list ref = ref [] in
135 let removals = ref CString.Map.empty in
136
137 (* get the first identifier on the new line with the most ids in common
138 with the given old idents *)
139 let best_match old_ids =
140 let rec aux best best_score = function
141 | [] -> best
142 | nl_idents :: tl ->
143 let score = List.fold_left (fun rv ident ->
144 if List.mem ident nl_idents then rv+1 else rv) 0 old_ids in
145 if score > best_score then
146 aux (List.hd nl_idents) score tl
147 else
148 aux best best_score tl
149 in
150 aux "" 0 n_idents_in_lines
151 in
152
153 (* generate the Pp.t for a single line of the hypotheses *)
154 let gen_line old_ids old_rhs new_ids new_rhs otype =
155 let gen_pp ids map hyp =
156 if ids = [] then ("", Pp.mt ()) else begin
157 let open Pp in
158 let pp_ids = List.map (fun x -> str x) ids in
159 let hyp_pp = List.fold_left (fun l1 l2 -> l1 ++ str ", " ++ l2) (List.hd pp_ids) (List.tl pp_ids) ++ hyp in
160 (string_of_ppcmds hyp_pp, hyp_pp)
161 end;
162 in
163
164 let (o_line, o_pp) = gen_pp old_ids o_map old_rhs in
165 let (n_line, n_pp) = gen_pp new_ids n_map new_rhs in
166
167 let hyp_diffs = diff_str ~tokenize_string o_line n_line in
168 if otype = `Added then begin
169 let rems = try CString.Map.find (List.hd new_ids) !removals with Not_found -> [] in
170 rv := add_diff_tags otype n_pp hyp_diffs :: (rems @ !rv)
171 end else begin
172 let (has_added, has_removed) = has_changes hyp_diffs in
173 if has_removed then begin
174 let d_line = add_diff_tags otype o_pp hyp_diffs in
175 let best = best_match old_ids in
176 if best = "" then
177 rv := d_line :: !rv
178 else begin
179 let ent = try CString.Map.find best !removals with Not_found -> [] in
180 removals := CString.Map.add best (d_line :: ent) !removals
181 end
182 end
183 end
184 in
185
186 (* generate only the removals or only the additions for all hypotheses *)
187 let half_diff old_ids o_map n_idents_in_lines n_map otype =
188 let rec do_lines = function
189 | [] -> ()
190 | ids_in_line :: tl ->
191 let nl_idents, new_rhs =
192 try let ent = CString.Map.find (List.hd ids_in_line) n_map in
193 ent.idents, ent.rhs_pp
194 with Not_found -> [], (Pp.mt ()) in
195
196 let rec get_ol_idents ol_idents old_rhs = function
197 | [] -> List.rev ol_idents, old_rhs
198 | ident :: tl ->
199 try
200 let o_ent = CString.Map.find ident o_map in
201 let eq = (o_ent.rhs_pp = new_rhs) in
202 let ol_idents = if eq then ident :: ol_idents else ol_idents in
203 let old_rhs = if eq || old_rhs = None then Some o_ent.rhs_pp else old_rhs in
204 get_ol_idents ol_idents old_rhs tl
205 with Not_found -> get_ol_idents ol_idents old_rhs tl
206 in
207
208 let (ol_idents, old_rhs) = get_ol_idents [] None nl_idents in
209 let old_rhs = Option.default (Pp.mt ()) old_rhs in
210
211 let rhs_eq = old_rhs = new_rhs in
212 (* if RHS differs, only highlight idents new to the context *)
213 let filter_ol () = if rhs_eq then ol_idents else
214 List.filter (fun ident -> CString.Map.mem ident o_map) nl_idents in
215 if otype = `Added then begin
216 let ol_idents = filter_ol () in
217 gen_line ol_idents old_rhs nl_idents new_rhs otype
218 end else if not rhs_eq || List.length nl_idents <> List.length ol_idents then begin
219 let ol_idents = filter_ol () in
220 gen_line nl_idents new_rhs ol_idents old_rhs otype
221 end;
222 do_lines tl
223 in
224 do_lines n_idents_in_lines
225 in
226 if show_removed () then
227 (* note reversal of new and old *)
228 half_diff (List.flatten n_idents_in_lines) n_map o_idents_in_lines o_map `Removed;
229 half_diff (List.flatten o_idents_in_lines) o_map n_idents_in_lines n_map `Added;
230 List.rev !rv
231
232 type goal = { ty: EConstr.t; env : Environ.env; sigma : Evd.evar_map; }
233
234 (* XXX: Port to proofview, one day. *)
235 (* open Proofview *)
236 module CDC = Context.Compacted.Declaration
237
238 let to_tuple : EConstr.compacted_declaration -> (Names.Id.t EConstr.binder_annot list * 'pc option * 'pc) =
239 let open CDC in function
240 | LocalAssum(idl, tm) -> (idl, None, tm)
241 | LocalDef(idl,tdef,tm) -> (idl, Some tdef, tm)
242
243 let make_goal env sigma g =
244 let evi = Evd.find_undefined sigma g in
245 let env = Evd.evar_filtered_env env evi in
246 let ty = Evd.evar_concl evi in
247 { ty; env; sigma }
248
249 let pr_letype_env ?goal_concl_style ~flags env sigma ?impargs t =
250 let ppflags = Ppconstr.of_printing_flags flags in
251 Ppconstr.pr_lconstr_expr ~flags:ppflags env sigma
252 (Constrextern.extern_type ~flags ?goal_concl_style env sigma ?impargs t)
253
254 let pp_of_type ~flags env sigma ty =
255 pr_letype_env ~goal_concl_style:true ~flags env sigma ty
256
257 let pr_leconstr_env ?inctx ?scope ~flags env sigma t =
258 let ppflags = Ppconstr.of_printing_flags flags in
259 Ppconstr.pr_lconstr_expr ~flags:ppflags env sigma
260 (Constrextern.extern_constr ?inctx ?scope ~flags env sigma t)
261
262 let pr_econstr_env ?inctx ?scope ~flags env sigma t =
263 let ppflags = Ppconstr.of_printing_flags flags in
264 Ppconstr.pr_constr_expr ~flags:ppflags env sigma
265 (Constrextern.extern_constr ?inctx ?scope ~flags env sigma t)
266
267 let diff_concl ?og_s ~flags ng =
268 let o_concl_pp = match og_s with
269 | Some { ty = oty; env = oenv; sigma = osigma } -> pp_of_type ~flags oenv osigma oty
270 | None -> Pp.mt()
271 in
272 let { ty = nty; env = nenv; sigma = nsigma } = ng in
273 let n_concl_pp = pp_of_type ~flags nenv nsigma nty in
274
275 let show_removed = Some (show_removed ()) in
276
277 diff_pp_combined ~tokenize_string ?show_removed o_concl_pp n_concl_pp
278
279 (* fetch info from a goal, returning (idents, map, concl_pp) where
280 idents is a list with one entry for each hypothesis, in which each entry
281 is the list of idents on the lhs of the hypothesis. map is a map from
282 ident to hyp_info reoords. For example: for the hypotheses:
283 b : bool
284 n, m : nat
285
286 idents will be [ ["b"]; ["n"; "m"] ]
287
288 map will contain:
289 "b" -> { ["b"], Pp.t for ": bool"; false }
290 "n" -> { ["n"; "m"], Pp.t for ": nat"; false }
291 "m" -> { ["n"; "m"], Pp.t for ": nat"; false }
292 where the last two entries share the idents list.
293
294 concl_pp is the conclusion as a Pp.t
295 *)
296 let goal_info ~flags goal =
297 let map = ref CString.Map.empty in
298 let line_idents = ref [] in
299 let build_hyp_info env sigma hyp =
300 let (names, body, ty) = to_tuple hyp in
301 let open Pp in
302 let idents = List.map (fun x -> Names.Id.to_string x.Context.binder_name) names in
303
304 line_idents := idents :: !line_idents;
305 let mid = match body with
306 | Some c ->
307 let pb = pr_leconstr_env ~flags env sigma c in
308 let pb = if EConstr.isCast sigma c then surround pb else pb in
309 str " := " ++ pb
310 | None -> mt() in
311 let ts = pp_of_type ~flags env sigma ty in
312 let rhs_pp = mid ++ str " : " ++ ts in
313
314 let make_entry () = { idents; rhs_pp } in
315 List.iter (fun ident -> map := (CString.Map.add ident (make_entry ()) !map); ()) idents
316 in
317
318 try
319 let { ty=ty; env=env; sigma } = goal in
320 (* compaction is usually desired [eg for better display] *)
321 let hyps = Termops.compact_named_context sigma (EConstr.named_context env) in
322 let () = List.iter (build_hyp_info env sigma) (List.rev hyps) in
323 let concl_pp = pp_of_type ~flags env sigma ty in
324 ( List.rev !line_idents, !map, concl_pp )
325 with e when CErrors.noncritical e -> ([], !map, Pp.mt ())
326
327 let diff_goal_info ~short o_info n_info =
328 let (o_idents_in_lines, o_hyp_map, o_concl_pp) = o_info in
329 let (n_idents_in_lines, n_hyp_map, n_concl_pp) = n_info in
330 let show_removed = Some (show_removed ()) in
331 let concl_pp = diff_pp_combined ~tokenize_string ?show_removed o_concl_pp n_concl_pp in
332
333 let hyp_diffs_list =
334 if short then [] else diff_hyps o_idents_in_lines o_hyp_map n_idents_in_lines n_hyp_map in
335 (hyp_diffs_list, concl_pp)
336
337 let unwrap ~flags g_s =
338 match g_s with
339 | Some g_s -> goal_info ~flags g_s
340 | None -> ([], CString.Map.empty, Pp.mt ())
341
342 let diff_goal ?(short=false) ?og_s ~flags ng =
343 diff_goal_info ~short (unwrap ~flags og_s) (goal_info ~flags ng)
344
345 (*** Code to determine which calls to compare between the old and new proofs ***)
346
347 module GoalMap = Evar.Map
348
349 let goal_to_evar g sigma = Names.Id.to_string (Termops.evar_suggested_name (Global.env ()) sigma g)
350
351 open Evar.Set
352
353 [@@@ocaml.warning "-32"]
354 let db_goal_map op np ng_to_og =
355 let pr_goals title prf =
356 Printf.printf "%s: " title;
357 let Proof.{goals;sigma} = Proof.data prf in
358 List.iter (fun g -> Printf.printf "%d -> %s " (Evar.repr g) (goal_to_evar g sigma)) goals;
359 let gs = diff (Proof.all_goals prf) (List.fold_left (fun s g -> add g s) empty goals) in
360 List.iter (fun g -> Printf.printf "%d " (Evar.repr g)) (elements gs);
361 in
362
363 pr_goals "New Goals" np;
364 (match op with
365 | Some op ->
366 pr_goals "\nOld Goals" op
367 | None -> ());
368 Printf.printf "\nGoal map: ";
369 GoalMap.iter (fun ng og -> Printf.printf "%d -> %d " (Evar.repr ng) (Evar.repr og)) ng_to_og;
370 let unmapped = ref (Proof.all_goals np) in
371 GoalMap.iter (fun ng _ -> unmapped := Evar.Set.remove ng !unmapped) ng_to_og;
372 if Evar.Set.cardinal !unmapped > 0 then begin
373 Printf.printf "\nUnmapped goals: ";
374 Evar.Set.iter (fun ng -> Printf.printf "%d " (Evar.repr ng)) !unmapped
375 end;
376 Printf.printf "\n"
377 [@@@ocaml.warning "+32"]
378
379 type goal_map = Evd.evar_map * Evar.t Evar.Map.t
380
381 let map_goal g (osigma, map) = match GoalMap.find_opt g map with
382 | None -> None
383 | Some g -> Some (make_goal (Global.env ()) osigma g)
384 (* if not found, returning None treats the goal as new and it will be diff highlighted;
385 returning Some { it = g; sigma = sigma } will compare the new goal
386 to itself and it won't be highlighted *)
387
388 (* Create a map from new goals to old goals for proof diff. *)
389 let make_goal_map op np =
390 let ogs = Proof.all_goals op in
391 let ngs = Proof.all_goals np in
392 let { Proof.sigma } = Proof.data np in
393
394 let fold_old_evar oevk acc =
395 match Evd.find sigma oevk with
396 | exception Not_found -> acc (* evar got deleted, maybe by Optimize Proof? *)
397 | EvarInfo evi -> match Evd.evar_body evi with
398 | Evar_empty ->
399 if Evar.Set.mem oevk ngs then Evar.Map.add oevk oevk acc
400 else
401 (* lost evar, probably a bug but we don't want to assert false in proof diffs *)
402 acc
403 | Evar_defined body ->
404 let evars = Evd.evars_of_term sigma body in
405 let evars =
406 (* remove lost evars (not sure if worth doing) *)
407 Evar.Set.inter evars ngs
408 in
409 Evar.Map.union (fun _ x _ -> Some x)
410 acc
411 (Evar.Map.bind (fun _ -> oevk) evars)
412 in
413 Evar.Set.fold fold_old_evar ogs Evar.Map.empty
414
415 let make_goal_map op np =
416 let map = make_goal_map op np in
417 ((Proof.data op).Proof.sigma, map)
418
419 let notify_proof_diff_failure msg =
420 Feedback.msg_notice Pp.(str "Unable to compute diffs: " ++ str msg)
421
422 let diff_proofs ~diff_opt ?old ~flags proof =
423 let pp_proof p =
424 let sigma, env = Proof.get_proof_context p in
425 let pprf = Proof.partial_proof p in
426 Pp.prlist_with_sep Pp.fnl (pr_econstr_env ~flags env sigma) pprf in
427 match diff_opt with
428 | DiffOff -> pp_proof proof
429 | _ -> begin
430 try
431 let n_pp = pp_proof proof in
432 let o_pp = match old with
433 | None -> Pp.mt()
434 | Some old -> pp_proof old in
435 let show_removed = Some (diff_opt = DiffRemoved) in
436 Pp_diff.diff_pp_combined ~tokenize_string ?show_removed o_pp n_pp
437 with Pp_diff.Diff_Failure msg ->
438 notify_proof_diff_failure msg;
439 pp_proof proof
440 end