Debian Codegraph @

pretyping/coercionops.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 CErrors
12 open Util
13 open Pp
14 open Names
15 open Constr
16 open Libnames
17 open Globnames
18 open Mod_subst
19
20 (* usage qque peu general: utilise aussi dans record *)
21
22 (* A class is a type constructor, its type is an arity whose number of
23 arguments is cl_param (0 for CL_SORT and CL_FUN) *)
24
25 type cl_typ =
26 | CL_SORT
27 | CL_FUN
28 | CL_SECVAR of variable
29 | CL_CONST of Constant.t
30 | CL_IND of inductive
31 | CL_PROJ of Projection.Repr.t
32
33 let cl_typ_ord t1 t2 = match t1, t2 with
34 | CL_SECVAR v1, CL_SECVAR v2 -> Id.compare v1 v2
35 | CL_CONST c1, CL_CONST c2 -> Constant.CanOrd.compare c1 c2
36 | CL_PROJ c1, CL_PROJ c2 -> Projection.Repr.CanOrd.compare c1 c2
37 | CL_IND i1, CL_IND i2 -> Ind.CanOrd.compare i1 i2
38 | _ -> Stdlib.compare t1 t2 (** OK *)
39
40 let cl_typ_eq t1 t2 = Int.equal (cl_typ_ord t1 t2) 0
41
42 module ClTyp = struct
43 type t = cl_typ
44 let compare = cl_typ_ord
45 end
46
47 module ClTypSet = Set.Make(ClTyp)
48 module ClTypMap = Map.Make(ClTyp)
49
50 type cl_info_typ = {
51 (* The number of parameters of the coercion class. *)
52 cl_param : int;
53 (* The sets of coercion classes respectively reachable from and to the
54 coercion class. *)
55 cl_reachable_from : ClTypSet.t;
56 cl_reachable_to : ClTypSet.t;
57 (* The representative class of the strongly connected component. *)
58 cl_repr : cl_typ;
59 }
60
61 type coe_typ = GlobRef.t
62
63 module CoeTypMap = GlobRef.Map_env
64
65 type coe_info_typ = {
66 coe_value : GlobRef.t;
67 coe_local : bool;
68 coe_reversible : bool;
69 coe_is_identity : bool;
70 coe_is_projection : Projection.Repr.t option;
71 coe_source : cl_typ;
72 coe_target : cl_typ;
73 coe_param : int;
74 }
75
76 type inheritance_path = coe_info_typ list
77
78 let init_class_tab =
79 let open ClTypMap in
80 let cl_info params cl =
81 let cl_singleton = ClTypSet.singleton cl in
82 { cl_param = params;
83 cl_reachable_from = cl_singleton;
84 cl_reachable_to = cl_singleton;
85 cl_repr = cl }
86 in
87 add CL_FUN (cl_info 0 CL_FUN) (add CL_SORT (cl_info 0 CL_SORT) empty)
88
89 let class_tab =
90 Summary.ref ~name:"class_tab" (init_class_tab : cl_info_typ ClTypMap.t)
91
92 let coercion_tab =
93 Summary.ref ~name:"coercion_tab" (CoeTypMap.empty : coe_info_typ CoeTypMap.t)
94
95 let reachable_from cl =
96 try (ClTypMap.find cl !class_tab).cl_reachable_from
97 with Not_found -> ClTypSet.empty
98
99 module ClGraph :
100 sig
101 type t
102 val empty : t
103 val add : cl_typ -> cl_typ -> inheritance_path -> t -> t
104 val find : cl_typ -> cl_typ -> t -> inheritance_path
105 val src : cl_typ -> t -> inheritance_path ClTypMap.t
106 val dst : cl_typ -> t -> inheritance_path ClTypMap.t
107 val bindings : t -> ((cl_typ * cl_typ) * inheritance_path) list
108 end =
109 struct
110 type map = inheritance_path ClTypMap.t ClTypMap.t
111 type t = map * map
112 (* Doubly-indexed map in both directions *)
113 let empty = ClTypMap.empty, ClTypMap.empty
114 let add0 x y p m =
115 let n = try ClTypMap.find x m with Not_found -> ClTypMap.empty in
116 ClTypMap.add x (ClTypMap.add y p n) m
117 let add x y p (ml, mr) = (add0 x y p ml, add0 y x p mr)
118 let find x y (m, _) = ClTypMap.find y (ClTypMap.find x m)
119 let src x (m, _) = try ClTypMap.find x m with Not_found -> ClTypMap.empty
120 let dst x (_, m) = try ClTypMap.find x m with Not_found -> ClTypMap.empty
121
122 let bindings (m, _) =
123 let fold s n accu =
124 let fold t p accu = ((s, t), p) :: accu in
125 ClTypMap.fold fold n accu
126 in
127 List.rev (ClTypMap.fold fold m [])
128 end
129
130 let inheritance_graph =
131 Summary.ref ~name:"inheritance_graph" ClGraph.empty
132
133 (* ajout de nouveaux "objets" *)
134
135 let add_new_class cl s =
136 class_tab := ClTypMap.add cl s !class_tab
137
138 let add_coercion coe s =
139 coercion_tab := CoeTypMap.add coe s !coercion_tab
140
141 let add_path (x, y) p =
142 inheritance_graph := ClGraph.add x y p !inheritance_graph
143
144 (* class_info : cl_typ -> int * cl_info_typ *)
145
146 let class_info cl = ClTypMap.find cl !class_tab
147
148 let class_nparams cl = (class_info cl).cl_param
149
150 let class_exists cl = ClTypMap.mem cl !class_tab
151
152 let coercion_info coe = CoeTypMap.find coe !coercion_tab
153
154 let coercion_type env sigma (coe,u) =
155 Retyping.get_type_of env sigma (EConstr.mkRef (coe.coe_value,u))
156
157 let coercion_exists coe = CoeTypMap.mem coe !coercion_tab
158
159 (* find_class_type : evar_map -> constr -> cl_typ * universe_list * constr list *)
160
161 let find_class_type env sigma t =
162 let open EConstr in
163 let t', args = Reductionops.whd_betaiotazeta_stack env sigma t in
164 match EConstr.kind sigma t' with
165 | Var id -> CL_SECVAR id, EInstance.empty, args
166 | Const (sp,u) -> CL_CONST sp, u, args
167 | Proj (p, _, c) when not (Projection.unfolded p) ->
168 let revparams =
169 let open Inductiveops in
170 let t = Retyping.get_type_of env sigma c in
171 let IndType (fam,_) = find_rectype env sigma t in
172 let _, params = dest_ind_family fam in
173 List.rev params
174 in
175 CL_PROJ (Projection.repr p), EInstance.empty, (List.rev_append revparams (c :: args))
176 | Ind (ind_sp,u) -> CL_IND ind_sp, u, args
177 | Prod _ -> CL_FUN, EInstance.empty, []
178 | Sort _ -> CL_SORT, EInstance.empty, []
179 | _ -> raise Not_found
180
181 let class_of_global_reference = function
182 | GlobRef.VarRef id -> CL_SECVAR id
183 | GlobRef.ConstRef kn -> CL_CONST kn
184 | GlobRef.IndRef ind -> CL_IND ind
185 | GlobRef.ConstructRef _ -> raise Not_found
186
187 let find_class_glob_type c = match DAst.get c with
188 | Glob_term.GRef (ref,_) -> class_of_global_reference ref
189 | Glob_term.GProd _ -> CL_FUN
190 | Glob_term.GSort _ -> CL_SORT
191 | _ -> raise Not_found
192
193 let subst_cl_typ env subst ct = match ct with
194 CL_SORT
195 | CL_FUN
196 | CL_SECVAR _ -> ct
197 | CL_PROJ c ->
198 let c' = subst_proj_repr subst c in
199 if c' == c then ct else CL_PROJ c'
200 | CL_CONST c ->
201 let c',t = subst_con subst c in
202 if c' == c then ct else (match t with
203 | None -> CL_CONST c'
204 | Some t ->
205 pi1 (find_class_type env Evd.empty (EConstr.of_constr t.UVars.univ_abstracted_value)))
206 | CL_IND i ->
207 let i' = subst_ind subst i in
208 if i' == i then ct else CL_IND i'
209
210 (*CSC: here we should change the datatype for coercions: it should be possible
211 to declare any term as a coercion *)
212 let subst_coe_typ subst t = subst_global_reference subst t
213
214 (* class_of : Term.constr -> int *)
215
216 let class_of env sigma t =
217 let (t, n1, cl, u, args) =
218 try
219 let (cl, u, args) = find_class_type env sigma t in
220 let { cl_param = n1 } = class_info cl in
221 (t, n1, cl, u, args)
222 with Not_found ->
223 let t = Tacred.hnf_constr0 env sigma t in
224 let (cl, u, args) = find_class_type env sigma t in
225 let { cl_param = n1 } = class_info cl in
226 (t, n1, cl, u, args)
227 in
228 if Int.equal (List.length args) n1 then t, cl else raise Not_found
229
230 let class_args_of env sigma c = pi3 (find_class_type env sigma c)
231
232 let string_of_class = function
233 | CL_FUN -> "Funclass"
234 | CL_SORT -> "Sortclass"
235 | CL_CONST sp ->
236 string_of_qualid (Nametab.shortest_qualid_of_global Id.Set.empty (GlobRef.ConstRef sp))
237 | CL_PROJ sp ->
238 let sp = Projection.Repr.constant sp in
239 string_of_qualid (Nametab.shortest_qualid_of_global Id.Set.empty (GlobRef.ConstRef sp))
240 | CL_IND sp ->
241 string_of_qualid (Nametab.shortest_qualid_of_global Id.Set.empty (GlobRef.IndRef sp))
242 | CL_SECVAR sp ->
243 string_of_qualid (Nametab.shortest_qualid_of_global Id.Set.empty (GlobRef.VarRef sp))
244
245 let pr_class x = str (string_of_class x)
246
247 (* lookup paths *)
248
249 let lookup_path_between_class (s,t) =
250 ClGraph.find s t !inheritance_graph
251
252 let lookup_path_to_fun_from_class s =
253 lookup_path_between_class (s, CL_FUN)
254
255 let lookup_path_to_sort_from_class s =
256 lookup_path_between_class (s, CL_SORT)
257
258 (* advanced path lookup *)
259
260 let apply_on_class_of env sigma t cont =
261 try
262 let (cl,u,args) = find_class_type env sigma t in
263 let { cl_param = n1 } = class_info cl in
264 if not (Int.equal (List.length args) n1) then raise Not_found;
265 cont cl
266 with Not_found ->
267 (* Is it worth to be more incremental on the delta steps? *)
268 let t = Tacred.hnf_constr0 env sigma t in
269 let (cl, u, args) = find_class_type env sigma t in
270 let { cl_param = n1 } = class_info cl in
271 if not (Int.equal (List.length args) n1) then raise Not_found;
272 cont cl
273
274 let lookup_path_between env sigma ~src:s ~tgt:t =
275 apply_on_class_of env sigma s (fun i ->
276 apply_on_class_of env sigma t (fun j ->
277 lookup_path_between_class (i,j)))
278
279 let lookup_path_to_fun_from env sigma s =
280 apply_on_class_of env sigma s lookup_path_to_fun_from_class
281
282 let lookup_path_to_sort_from env sigma s =
283 apply_on_class_of env sigma s lookup_path_to_sort_from_class
284
285 let get_coercion_constructor env coe =
286 let evd = Evd.from_env env in
287 let evd, c = Evd.fresh_global env evd coe.coe_value in
288 let c = fst (Reductionops.whd_all_stack env evd c) in
289 match EConstr.kind evd c with
290 | Constr.Construct (c, _) ->
291 (* we don't return the modified evd as we drop the universes *)
292 c, Inductiveops.constructor_nrealargs env c -1
293 | _ -> raise Not_found
294
295 let lookup_pattern_path_between env (s,t) =
296 List.map (get_coercion_constructor env)
297 (ClGraph.find (CL_IND s) (CL_IND t) !inheritance_graph)
298
299 let path_is_reversible p =
300 List.for_all (fun c -> c.coe_reversible) p
301
302 (* rajouter une coercion dans le graphe *)
303
304 let path_printer : ((cl_typ * cl_typ) * inheritance_path -> Pp.t) ref =
305 ref (fun _ -> str "<a class path>")
306
307 let install_path_printer f = path_printer := f
308
309 let print_path x = !path_printer x
310
311 let path_comparator :
312 (Environ.env -> Evd.evar_map -> cl_typ -> inheritance_path -> inheritance_path -> bool) ref =
313 ref (fun _ _ _ _ _ -> false)
314
315 let install_path_comparator f = path_comparator := f
316
317 let compare_path env sigma cl p q = !path_comparator env sigma cl p q
318
319 let warning_ambiguous_path = "ambiguous-paths"
320
321 let warn_ambiguous_path =
322 CWarnings.create ~name:warning_ambiguous_path ~category:CWarnings.CoreCategories.coercions
323 (fun l -> prlist_with_sep fnl (fun (c,p,q) ->
324 str"New coercion path " ++ print_path (c,p) ++
325 if List.is_empty q then
326 str" is not definitionally an identity function."
327 else
328 str" is ambiguous with existing " ++ print_path (c, q) ++ str".") l)
329
330 (* add_coercion_in_graph : coe_index * cl_typ * cl_typ -> unit
331 coercion,source,target *)
332
333 let different_class_params env ci =
334 if (class_info ci).cl_param > 0 then true
335 else
336 match ci with
337 | CL_IND i -> Environ.is_polymorphic env (GlobRef.IndRef i)
338 | CL_CONST c -> Environ.is_polymorphic env (GlobRef.ConstRef c)
339 | _ -> false
340
341 let add_coercion_in_graph env sigma ?(update=false) ic =
342 let source = ic.coe_source in
343 let target = ic.coe_target in
344 let source_info = class_info source in
345 let target_info = class_info target in
346 let old_inheritance_graph = !inheritance_graph in
347 let ambig_paths :
348 ((cl_typ * cl_typ) * inheritance_path * inheritance_path) list ref =
349 ref [] in
350 let warn = match CWarnings.get_warning warning_ambiguous_path with
351 | There w ->
352 begin match CWarnings.warning_status w with
353 | Disabled -> false
354 | Enabled | AsError -> true
355 end
356 | NotThere | OtherType -> assert false
357 in
358 let check_coherence (i, j as ij) p q =
359 if warn then
360 let i_info = class_info i in
361 let j_info = class_info j in
362 let between_ij = ClTypSet.inter i_info.cl_reachable_from j_info.cl_reachable_to in
363 if cl_typ_eq i_info.cl_repr i &&
364 cl_typ_eq j_info.cl_repr j &&
365 ClTypSet.is_empty
366 (ClTypSet.diff (ClTypSet.inter between_ij source_info.cl_reachable_to)
367 i_info.cl_reachable_to) &&
368 ClTypSet.is_empty
369 (ClTypSet.diff
370 (ClTypSet.inter between_ij target_info.cl_reachable_from)
371 j_info.cl_reachable_from) &&
372 not (compare_path env sigma i p q)
373 then
374 ambig_paths := (ij, p, q) :: !ambig_paths
375 in
376 let try_add_new_path (i,j as ij) p =
377 let () = if cl_typ_eq i j then check_coherence ij p [] in
378 if not (cl_typ_eq i j) || different_class_params env i then
379 if update then let () = add_path ij p in true else
380 match lookup_path_between_class ij with
381 | q -> (if not (cl_typ_eq i j) then check_coherence ij p q); false
382 | exception Not_found -> add_path ij p; true
383 else
384 false
385 in
386 if try_add_new_path (source, target) [ic] then begin
387 let rev = ClGraph.dst source old_inheritance_graph in
388 let dir = ClGraph.src target old_inheritance_graph in
389 let iter s p =
390 if not (cl_typ_eq s source) then
391 let _ = try_add_new_path (s, target) (p@[ic]) in
392 let iter v q =
393 if not (cl_typ_eq target v) then
394 ignore (try_add_new_path (s,v) (p@[ic]@q))
395 in
396 ClTypMap.iter iter dir
397 in
398 let () = ClTypMap.iter iter rev in
399 let iter t p =
400 if not (cl_typ_eq t target) then
401 ignore (try_add_new_path (source, t) (ic::p))
402 in
403 ClTypMap.iter iter dir
404 end;
405 class_tab := ClTypMap.mapi (fun k k_info ->
406 let reachable_k_source = ClTypSet.mem k source_info.cl_reachable_to in
407 let reachable_target_k = ClTypSet.mem k target_info.cl_reachable_from in
408 { k_info with
409 cl_reachable_from =
410 if reachable_k_source then
411 ClTypSet.union
412 k_info.cl_reachable_from target_info.cl_reachable_from
413 else
414 k_info.cl_reachable_from;
415 cl_reachable_to =
416 if reachable_target_k then
417 ClTypSet.union k_info.cl_reachable_to source_info.cl_reachable_to
418 else
419 k_info.cl_reachable_to;
420 cl_repr =
421 if reachable_k_source && reachable_target_k then
422 target_info.cl_repr
423 else
424 k_info.cl_repr
425 }) !class_tab;
426 match !ambig_paths with [] -> () | _ -> warn_ambiguous_path !ambig_paths
427
428 let subst_coercion subst c =
429 let env = Global.env () in
430 let coe = subst_coe_typ subst c.coe_value in
431 let cls = subst_cl_typ env subst c.coe_source in
432 let clt = subst_cl_typ env subst c.coe_target in
433 let clp = Option.Smart.map (subst_proj_repr subst) c.coe_is_projection in
434 if c.coe_value == coe && c.coe_source == cls && c.coe_target == clt &&
435 c.coe_is_projection == clp
436 then c
437 else { c with coe_value = coe; coe_source = cls; coe_target = clt;
438 coe_is_projection = clp; }
439
440 (* Computation of the class arity *)
441
442 let reference_arity_length env sigma ref =
443 let t, _ = Typeops.type_of_global_in_context env ref in
444 List.length (fst (Reductionops.splay_arity env sigma (EConstr.of_constr t)))
445
446 let projection_arity_length env sigma p =
447 reference_arity_length env sigma (GlobRef.ConstRef (Projection.Repr.constant p))
448
449 let class_params env sigma = function
450 | CL_FUN | CL_SORT -> 0
451 | CL_CONST sp -> reference_arity_length env sigma (GlobRef.ConstRef sp)
452 | CL_PROJ sp -> projection_arity_length env sigma sp
453 | CL_SECVAR sp -> reference_arity_length env sigma (GlobRef.VarRef sp)
454 | CL_IND sp -> reference_arity_length env sigma (GlobRef.IndRef sp)
455
456 (* add_class : cl_typ -> locality_flag option -> bool -> unit *)
457
458 let add_class env sigma cl =
459 if not (class_exists cl) then
460 let cl_singleton = ClTypSet.singleton cl in
461 add_new_class cl {
462 cl_param = class_params env sigma cl;
463 cl_reachable_from = cl_singleton;
464 cl_reachable_to = cl_singleton;
465 cl_repr = cl }
466
467 let declare_coercion env sigma ?update c =
468 let () = add_class env sigma c.coe_source in
469 let () = add_class env sigma c.coe_target in
470 let () = add_coercion c.coe_value c in
471 add_coercion_in_graph env sigma ?update c
472
473 (* For printing purpose *)
474 let classes () =
475 List.rev (ClTypMap.fold (fun x _ acc -> x :: acc) !class_tab [])
476 let coercions () =
477 List.rev (CoeTypMap.fold (fun _ y acc -> y::acc) !coercion_tab [])
478
479 let inheritance_graph () =
480 ClGraph.bindings !inheritance_graph
481
482 let coercion_of_reference env r =
483 let ref = Nametab.global r in
484 let ref = Environ.QGlobRef.canonize env ref in
485 if not (coercion_exists ref) then
486 user_err
487 (Nametab.pr_global_env Id.Set.empty ref ++ str" is not a coercion.");
488 ref
489
490 module CoercionPrinting =
491 struct
492 type t = coe_typ
493 module Set = GlobRef.Set_env
494 let encode = coercion_of_reference
495 let subst = subst_coe_typ
496
497 let check_local local = let open GlobRef in function
498 | ConstRef _ | ConstructRef _ | IndRef _ -> ()
499 | VarRef x -> match local with
500 | Libobject.Local -> ()
501 | Export | SuperGlobal ->
502 let local = if local = Export then "export" else "global" in
503 CErrors.user_err
504 Pp.(Id.print x ++ str " cannot be added with locality " ++ str local ++ str ".")
505
506 let discharge = let open GlobRef in function
507 | ConstRef _ | ConstructRef _ | IndRef _ as x -> x
508 | VarRef _ as x -> assert (not (Global.is_in_section x)); x
509
510 let printer x = Nametab.pr_global_env Id.Set.empty x
511 let key = ["Printing";"Coercion"]
512 let title = "Explicitly printed coercions: "
513 let member_message x b =
514 str "Explicit printing of coercion " ++ printer x ++
515 str (if b then " is set" else " is unset")
516 end
517
518 module PrintingCoercion = Goptions.MakeRefTable(CoercionPrinting)
519
520 let hide_coercion coe =
521 if not (PrintingCoercion.active coe) then
522 let coe_info = coercion_info coe in
523 Some coe_info.coe_param
524 else None