Debian Codegraph @

pretyping/structures.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 (* Created by Amokrane Saïbi, Dec 1998 *)
12 (* Addition of products and sorts in canonical structures by Pierre
13 Corbineau, Feb 2008 *)
14
15 (* This file registers properties of records: projections and
16 canonical structures *)
17
18 open CErrors
19 open Util
20 open Pp
21 open Names
22 open Constr
23 open Mod_subst
24 open Reductionops
25
26 (*s A structure S is a non recursive inductive type with a single
27 constructor (the name of which defaults to Build_S) *)
28
29 (* Table of structures.
30 It maps to each structure name (of type [inductive]):
31 - the name of its constructor;
32 - the number of parameters;
33 - for each true argument, some data about the corresponding projection:
34 * its name (may be anonymous);
35 * whether it is a true projection (as opposed to a constant function, LetIn);
36 * whether it should be used as a canonical hint;
37 * the constant realizing this projection (if any).
38 *)
39
40 module Structure = struct
41
42 type projection = {
43 proj_name : Names.Name.t;
44 proj_true : bool;
45 proj_canonical : bool;
46 proj_body : Names.Constant.t option;
47 }
48
49 type t = {
50 name : Names.inductive;
51 projections : projection list;
52 nparams : int;
53 }
54
55 let make env name projections =
56 let nparams = Inductiveops.inductive_nparams env name in
57 { name; projections; nparams }
58
59 let structure_table =
60 Summary.ref (Environ.QInd.Map.empty : t Environ.QInd.Map.t) ~name:"record-structs"
61 let projection_table =
62 Summary.ref (Environ.QConstant.Map.empty : t Environ.QConstant.Map.t) ~name:"record-projs"
63
64 let register ({ name; projections; nparams } as s) =
65 let env = Global.env () in
66 structure_table := Environ.QInd.Map.add env name s !structure_table;
67 projection_table :=
68 List.fold_right (fun { proj_body } m ->
69 Option.fold_right (fun proj -> Environ.QConstant.Map.add env proj s) proj_body m)
70 projections !projection_table
71
72 let subst subst ({ name; projections; nparams } as s) =
73 let subst_projection subst ({ proj_body } as p) =
74 let proj_body = Option.Smart.map (subst_constant subst) proj_body in
75 if proj_body == p.proj_body then p else
76 { p with proj_body } in
77 let projections = List.Smart.map (subst_projection subst) projections in
78 let name = Mod_subst.subst_ind subst name in
79 if projections == s.projections &&
80 name == s.name
81 then s
82 else { name; projections; nparams }
83
84 let rebuild env s =
85 let mib = Environ.lookup_mind (fst s.name) env in
86 let nparams = mib.Declarations.mind_nparams in
87 { s with nparams }
88
89 let mem env ind = Environ.QInd.Map.mem env ind !structure_table
90
91 let find env indsp = Environ.QInd.Map.find env indsp !structure_table
92
93 let find_projections env indsp =
94 (find env indsp).projections |>
95 List.map (fun { proj_body } -> proj_body)
96
97 let find_from_projection env cst =
98 Environ.QConstant.Map.find env cst !projection_table
99
100 let projection_nparams env cst =
101 (Environ.QConstant.Map.find env cst !projection_table).nparams
102
103 let is_projection cst =
104 let env = Global.env () in
105 Environ.QConstant.Map.mem env cst !projection_table
106
107 let projection_number env cst =
108 let s = find_from_projection env cst in
109 CList.index0 (Option.equal (Environ.QConstant.equal env)) (Some cst)
110 (List.map (fun x -> x.proj_body) s.projections)
111
112 end
113
114 (************************************************************************)
115 (*s A canonical structure declares "canonical" conversion hints between *)
116 (* the effective components of a structure and the projections of the *)
117 (* structure *)
118
119 (* Table of "object" definitions: for each object c,
120
121 c := [x1:B1]...[xk:Bk](Build_R a1...am t1...t_n)
122
123 If ti has the form (ci ui1...uir) where ci is a global reference (or
124 a sort, or a product or a reference to a parameter) and if the
125 corresponding projection Li of the structure R is defined, one
126 declares a "conversion" between ci and Li.
127
128 x1:B1..xk:Bk |- (Li a1..am (c x1..xk)) =_conv (ci ui1...uir)
129
130 that maps the pair (Li,ci) to the following data
131
132 o_ORIGIN = c (the constant name which this conversion rule is
133 synthesized from)
134 o_DEF = c
135 o_TABS = B1...Bk
136 o_INJ = Some n (when ci is a reference to the parameter xi)
137 o_TPARAMS = a1...am
138 o_NPARAMS = m
139 o_TCOMP = ui1...uir
140
141 *)
142
143 type obj_typ = {
144 o_ORIGIN : GlobRef.t;
145 o_DEF : constr;
146 o_CTX : UVars.AbstractContext.t;
147 o_INJ : int option; (* position of trivial argument if any *)
148 o_TABS : constr list; (* ordered *)
149 o_TPARAMS : constr list; (* ordered *)
150 o_NPARAMS : int;
151 o_TCOMPS : constr list } (* ordered *)
152
153 module ValuePattern = struct
154
155 type t =
156 Const_cs of GlobRef.t
157 | Proj_cs of Names.Projection.Repr.t
158 | Prod_cs
159 | Sort_cs of UnivGen.QualityOrSet.t
160 | Default_cs
161
162 let equal env p1 p2 = match p1, p2 with
163 | Const_cs gr1, Const_cs gr2 -> Environ.QGlobRef.equal env gr1 gr2
164 | Proj_cs p1, Proj_cs p2 -> Environ.QProjection.Repr.equal env p1 p2
165 | Prod_cs, Prod_cs -> true
166 | Sort_cs s1, Sort_cs s2 -> UnivGen.QualityOrSet.equal s1 s2
167 | Default_cs, Default_cs -> true
168 | _ -> false
169
170 let compare p1 p2 = match p1, p2 with
171 | Const_cs gr1, Const_cs gr2 -> GlobRef.UserOrd.compare gr1 gr2
172 | Proj_cs p1, Proj_cs p2 -> Projection.Repr.UserOrd.compare p1 p2
173 | Prod_cs, Prod_cs -> 0
174 | Sort_cs s1, Sort_cs s2 -> UnivGen.QualityOrSet.compare s1 s2
175 | Default_cs, Default_cs -> 0
176 | _ -> Stdlib.compare p1 p2
177
178 let canonize env p = match p with
179 | Const_cs gr -> Const_cs (Environ.QGlobRef.canonize env gr)
180 | Proj_cs p -> Proj_cs (Environ.QProjection.Repr.canonize env p)
181 | Prod_cs | Sort_cs _ | Default_cs -> p
182
183 let rec of_constr sigma t =
184 match EConstr.kind sigma t with
185 | App (f,vargs) ->
186 let patt, n, args = of_constr sigma f in
187 patt, n, args @ Array.to_list vargs
188 | Rel n -> Default_cs, Some n, []
189 | Lambda (_, _, b) -> let patt, _, _ = of_constr sigma b in patt, None, []
190 | Prod (_,_,_) -> Prod_cs, None, [t]
191 | Proj (p, _, c) -> Proj_cs (Names.Projection.repr p), None, [c]
192 | Sort s -> Sort_cs (EConstr.ESorts.quality_or_set sigma s), None, []
193 | _ -> Const_cs (fst @@ EConstr.destRef sigma t) , None, []
194
195 let print = function
196 Const_cs c -> Nametab.pr_global_env Id.Set.empty c
197 | Proj_cs p -> Nametab.pr_global_env Id.Set.empty (GlobRef.ConstRef (Names.Projection.Repr.constant p))
198 | Prod_cs -> str "forall _, _"
199 | Default_cs -> str "_"
200 | Sort_cs s -> UnivGen.QualityOrSet.pr Sorts.QVar.raw_pr s
201
202 end
203
204 module PatMap = Environ.QMap(Map.Make(ValuePattern))(ValuePattern)
205
206 module GlobRefMap = Environ.QGlobRef.Map
207
208 let object_table =
209 Summary.ref (GlobRefMap.empty : (constr * obj_typ) PatMap.t GlobRefMap.t)
210 ~name:"record-canonical-structs"
211
212 let keep_true_projections projs =
213 let filter { Structure.proj_true ; proj_canonical; proj_body } = if proj_true then Some (proj_body, proj_canonical) else None in
214 List.map_filter filter projs
215
216 let warn_projection_no_head_constant =
217 CWarnings.create ~name:"projection-no-head-constant" ~category:CWarnings.CoreCategories.records
218 (fun (sign,env,t,ref,proji_sp) ->
219 let env = Environ.push_rel_context sign env in
220 let con_pp = Nametab.pr_global_env Id.Set.empty ref in
221 let proji_sp_pp = Nametab.pr_global_env Id.Set.empty (GlobRef.ConstRef proji_sp) in
222 let term_pp = Termops.Internal.print_constr_env env (Evd.from_env env) (EConstr.of_constr t) in
223 strbrk "Projection value has no head constant: "
224 ++ term_pp ++ strbrk " in canonical instance "
225 ++ con_pp ++ str " of " ++ proji_sp_pp ++ strbrk ", ignoring it.")
226
227 (* Intended to always succeed *)
228 let compute_canonical_projections env sigma ~warn (gref,ind) =
229 let o_CTX = Environ.universes_of_global env gref in
230 let o_DEF, c =
231 match gref with
232 | GlobRef.ConstRef con ->
233 let u = UVars.make_abstract_instance o_CTX in
234 mkConstU (con, u), Environ.constant_value_in env (con,u)
235 | GlobRef.VarRef id ->
236 mkVar id, Option.get (Environ.named_body id env)
237 | GlobRef.ConstructRef _ | GlobRef.IndRef _ -> assert false
238 in
239 let sign,t = Reduction.whd_decompose_lambda env c in
240 let o_TABS = List.rev_map Context.Rel.Declaration.get_type sign in
241 let args = snd (decompose_app_list t) in
242 let { Structure.nparams = p; projections = lpj } =
243 Structure.find env ind in
244 let o_TPARAMS, projs = List.chop p args in
245 let o_NPARAMS = List.length o_TPARAMS in
246 let lpj = keep_true_projections lpj in
247 List.fold_left2 (fun acc (spopt, canonical) t ->
248 let t = EConstr.Unsafe.to_constr (shrink_eta sigma (EConstr.of_constr t)) in
249 if canonical
250 then
251 Option.cata (fun proji_sp ->
252 match ValuePattern.of_constr sigma (EConstr.of_constr t) with
253 | patt, o_INJ, o_TCOMPS ->
254 ((GlobRef.ConstRef proji_sp, (patt, t)),
255 { o_ORIGIN = gref ; o_DEF ; o_CTX ; o_INJ ; o_TABS ; o_TPARAMS ; o_NPARAMS ; o_TCOMPS = List.map EConstr.Unsafe.to_constr o_TCOMPS })
256 :: acc
257 | exception DestKO ->
258 if warn then warn_projection_no_head_constant (sign, env, t, gref, proji_sp);
259 acc
260 ) acc spopt
261 else acc
262 ) [] lpj projs
263
264 let warn_redundant_canonical_projection =
265 CWarnings.create ~name:"redundant-canonical-projection" ~category:CWarnings.CoreCategories.records
266 (fun (hd_val,prj,new_can_s,old_can_s) ->
267 strbrk "Ignoring canonical projection to " ++ hd_val
268 ++ strbrk " by " ++ prj ++ strbrk " in "
269 ++ new_can_s ++ strbrk ": redundant with " ++ old_can_s)
270
271 module Instance = struct
272
273 type t = GlobRef.t * inductive
274
275 let repr = fst
276
277 let subst subst (gref,ind as obj) =
278 (* invariant: cst is an evaluable reference. Thus we can take *)
279 (* the first component of subst_con. *)
280 match gref with
281 | GlobRef.ConstRef cst ->
282 let cst' = subst_constant subst cst in
283 let ind' = subst_ind subst ind in
284 if cst' == cst && ind' == ind then obj else (GlobRef.ConstRef cst',ind')
285 | _ -> assert false
286
287 (*s High-level declaration of a canonical structure *)
288
289 let error_not_structure ref description =
290 user_err
291 (str"Could not declare a canonical structure " ++
292 (Id.print (Nametab.basename_of_global ref) ++ str"." ++ spc() ++
293 description) ++ str ".")
294
295 let make env sigma ref =
296 let vc =
297 match ref with
298 | GlobRef.ConstRef sp ->
299 let u = UVars.make_abstract_instance (Environ.constant_context env sp) in
300 begin match Environ.constant_opt_value_in env (sp, u) with
301 | Some vc -> vc
302 | None -> error_not_structure ref (str "Could not find its value in the global environment") end
303 | GlobRef.VarRef id ->
304 begin match Environ.named_body id env with
305 | Some b -> b
306 | None -> error_not_structure ref (str "Could not find its value in the global environment") end
307 | GlobRef.IndRef _ | GlobRef.ConstructRef _ ->
308 error_not_structure ref (str "Expected an instance of a record or structure")
309 in
310 let body = snd (whd_decompose_lambda env sigma (EConstr.of_constr vc)) in
311 let body = EConstr.Unsafe.to_constr body in
312 let f,args = match kind body with
313 | App (f,args) -> f,args
314 | _ ->
315 error_not_structure ref (str "Expected a record or structure constructor applied to arguments") in
316 let indsp = match kind f with
317 | Construct ((indsp,1),u) -> indsp
318 | _ -> error_not_structure ref (str "Expected an instance of a record or structure") in
319 let s =
320 try Structure.find env indsp
321 with Not_found ->
322 error_not_structure ref
323 (str "Could not find the record or structure " ++ Termops.pr_global_env env (IndRef indsp)) in
324 let ntrue_projs = List.count (fun { Structure.proj_true = x } -> x) s.Structure.projections in
325 if s.Structure.nparams + ntrue_projs > Array.length args then
326 error_not_structure ref (str "Got too few arguments to the record or structure constructor");
327 (ref,indsp)
328
329 let register ~warn env sigma o =
330 compute_canonical_projections env sigma ~warn o |>
331 List.iter (fun ((proj, (cs_pat, t)), s) ->
332 let l = try GlobRefMap.find env proj !object_table with Not_found -> PatMap.empty in
333 match PatMap.find env cs_pat l with
334 | exception Not_found ->
335 object_table := GlobRefMap.add env proj (PatMap.add env cs_pat (t, s) l) !object_table
336 | _, cs ->
337 if warn
338 then
339 let old_can_s = Termops.Internal.print_constr_env env sigma (EConstr.of_constr cs.o_DEF) in
340 let new_can_s = Termops.Internal.print_constr_env env sigma (EConstr.of_constr s.o_DEF) in
341 let prj = Nametab.pr_global_env Id.Set.empty proj in
342 let hd_val = ValuePattern.print cs_pat in
343 warn_redundant_canonical_projection (hd_val, prj, new_can_s, old_can_s)
344 )
345
346 end
347
348 (** The canonical solution of a problem (proj,val) is a global
349 [constant = fun abs : abstractions_ty => body] and
350 [ body = RecodConstructor params canon_values ] and the canonical value
351 corresponding to val is [val cvalue_arguments].
352 It is possible that val is one of the [abs] abstractions, eg [Default_cs],
353 and in that case [cvalue_abstraction = Some i] *)
354
355 module CanonicalSolution = struct
356 type t = {
357 constant : EConstr.t;
358
359 abstractions_ty : EConstr.t list;
360 body : EConstr.t;
361
362 nparams : int;
363 params : EConstr.t list;
364 cvalue_abstraction : int option;
365 cvalue_arguments : EConstr.t list;
366 }
367
368 let find env sigma (proj,pat) =
369 let t', { o_DEF = c; o_CTX = ctx; o_INJ=n; o_TABS = bs;
370 o_TPARAMS = params; o_NPARAMS = nparams; o_TCOMPS = us } = PatMap.find env pat (GlobRefMap.find env proj !object_table) in
371 let us = List.map EConstr.of_constr us in
372 let params = List.map EConstr.of_constr params in
373 let u, ctx' = UnivGen.fresh_instance_from ctx None in
374 let u = EConstr.EInstance.make u in
375 let c = EConstr.of_constr c in
376 let c' = EConstr.Vars.subst_instance_constr u c in
377 let t' = EConstr.of_constr t' in
378 let t' = EConstr.Vars.subst_instance_constr u t' in
379 let bs' = List.map (EConstr.of_constr %> EConstr.Vars.subst_instance_constr u) bs in
380 let params = List.map (fun c -> EConstr.Vars.subst_instance_constr u c) params in
381 let us = List.map (fun c -> EConstr.Vars.subst_instance_constr u c) us in
382 let sigma = Evd.merge_sort_context_set Evd.univ_flexible ~src:UState.Internal sigma ctx' in
383 sigma, { body = t'; constant = c'; abstractions_ty = bs'; nparams; params; cvalue_arguments = us; cvalue_abstraction = n }
384
385
386 let rec get_nth n = function
387 | [] -> raise Not_found
388 | arg :: args ->
389 let len = Array.length arg in
390 if n < len then arg.(n)
391 else get_nth (n - len) args
392
393 let rec decompose_projection ?metas env sigma c args =
394 match EConstr.kind sigma c with
395 | Meta mv ->
396 begin match metas with
397 | None -> raise Not_found
398 | Some m ->
399 match m.meta_value mv with
400 | None -> raise Not_found
401 | Some v -> decompose_projection ?metas env sigma v args
402 end
403 | Cast (c, _, _) -> decompose_projection ?metas env sigma c args
404 | App (c, arg) -> decompose_projection ?metas env sigma c (arg :: args)
405 | Const (c, u) ->
406 let n = Structure.projection_nparams env c in
407 (* Check if there is some canonical projection attached to this structure *)
408 let _ = GlobRefMap.find env (GlobRef.ConstRef c) !object_table in
409 get_nth n args
410 | Proj (p, _, c) ->
411 let _ = GlobRefMap.find env (GlobRef.ConstRef (Names.Projection.constant p)) !object_table in
412 c
413 | _ -> raise Not_found
414
415 let is_open_canonical_projection ?metas env sigma c =
416 let open EConstr in
417 try
418 let arg = decompose_projection ?metas env sigma c [] in
419 try
420 let arg = whd_all ?metas env sigma arg in
421 let hd = match EConstr.kind sigma arg with App (hd, _) -> hd | _ -> arg in
422 not (isConstruct sigma hd)
423 with Failure _ -> false
424 with Not_found -> false
425
426 let print env sigma s =
427 let pr_econstr = Termops.Internal.debug_print_constr sigma in
428 let pr_econstr_list l = Pp.(str "[ " ++ prlist_with_sep (fun () -> str "; ") pr_econstr l ++ str " ]") in
429 Pp.(str "{ constant = " ++ pr_econstr s.constant ++ cut () ++
430 str "abstractions_ty = " ++ pr_econstr_list s.abstractions_ty ++ cut () ++
431 str "body = " ++ pr_econstr s.body ++ cut () ++
432 str "nparams = " ++ int s.nparams ++ cut () ++
433 str "params = " ++ pr_econstr_list s.params ++ cut () ++
434 str "cvalue_abstractions = " ++ pr_opt int s.cvalue_abstraction ++ cut () ++
435 str "cvalue_arguments = " ++ pr_econstr_list s.cvalue_arguments ++ cut () ++
436 str "}")
437
438 end
439
440 module CSTable = struct
441
442 type entry = {
443 projection : Names.GlobRef.t;
444 value : ValuePattern.t;
445 solution : Names.GlobRef.t;
446 }
447
448 let canonical_entry_of_object projection value (_, { o_ORIGIN = solution }) =
449 { projection; value; solution }
450
451 let entries () =
452 GlobRefMap.fold (fun p ol acc ->
453 PatMap.fold (fun pat o acc -> canonical_entry_of_object p pat o :: acc) ol acc)
454 !object_table []
455
456 let entries_for env ~projection:p =
457 try
458 GlobRefMap.find env p !object_table |>
459 (fun m -> PatMap.fold (fun pat o accu -> canonical_entry_of_object p pat o :: accu) m []) |>
460 List.rev
461 with Not_found -> []
462
463 end
464
465 module PrimitiveProjections = struct
466
467 let prim_table =
468 Summary.ref (Cmap_env.empty : Names.Projection.Repr.t Cmap_env.t) ~name:"record-prim-projs"
469
470 let register p c =
471 prim_table := Cmap_env.add c p !prim_table
472
473 let mem c = Cmap_env.mem c !prim_table
474
475 let find_opt c =
476 try Some (Cmap_env.find c !prim_table) with Not_found -> None
477
478 let find_opt_with_relevance (c,u) =
479 find_opt c |>
480 Option.map (fun p ->
481 let u = EConstr.Unsafe.to_instance u in
482 p, EConstr.ERelevance.make @@ Relevanceops.relevance_of_projection_repr (Global.env()) (p,u))
483
484 let is_transparent_constant ts c =
485 match find_opt c with
486 | None -> TransparentState.is_transparent_constant ts c
487 | Some p -> TransparentState.is_transparent_projection ts p
488
489 end