Debian Codegraph @

vernac/comCoercion.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 Term
16 open Constr
17 open Context
18 open Vars
19 open Environ
20 open Coercionops
21 open Declare
22 open Libobject
23
24 let strength_min l = if List.mem `LOCAL l then `LOCAL else `GLOBAL
25
26 let loc_of_bool b = if b then `LOCAL else `GLOBAL
27
28 (* Errors *)
29
30 type coercion_error_kind =
31 | AlreadyExists
32 | NotAFunction
33 | NoSource of cl_typ option
34 | ForbiddenSourceClass of cl_typ
35 | NoTarget
36 | WrongTarget of cl_typ * cl_typ
37 | NotAClass of GlobRef.t
38
39 exception CoercionError of coercion_error_kind
40
41 let explain_coercion_error g = function
42 | AlreadyExists ->
43 (Printer.pr_global g ++ str" is already a coercion")
44 | NotAFunction ->
45 (Printer.pr_global g ++ str" is not a function")
46 | NoSource (Some cl) ->
47 (str "Cannot recognize " ++ pr_class cl ++ str " as a source class of "
48 ++ Printer.pr_global g)
49 | NoSource None ->
50 (str ": cannot find the source class of " ++ Printer.pr_global g)
51 | ForbiddenSourceClass cl ->
52 pr_class cl ++ str " cannot be a source class"
53 | NoTarget ->
54 (str"Cannot find the target class")
55 | WrongTarget (clt,cl) ->
56 (str"Found target class " ++ pr_class cl ++
57 str " instead of " ++ pr_class clt)
58 | NotAClass ref ->
59 (str "Type of " ++ Printer.pr_global ref ++
60 str " does not end with a sort")
61
62 (* Verifications pour l'ajout d'une classe *)
63
64 let check_reference_arity ref =
65 let env = Global.env () in
66 let c, _ = Typeops.type_of_global_in_context env ref in
67 if not (Reductionops.is_arity env (Evd.from_env env) (EConstr.of_constr c)) (* FIXME *) then
68 raise (CoercionError (NotAClass ref))
69
70 let check_arity = function
71 | CL_FUN | CL_SORT -> ()
72 | CL_CONST cst -> check_reference_arity (GlobRef.ConstRef cst)
73 | CL_PROJ p -> check_reference_arity (GlobRef.ConstRef (Projection.Repr.constant p))
74 | CL_SECVAR id -> check_reference_arity (GlobRef.VarRef id)
75 | CL_IND kn -> check_reference_arity (GlobRef.IndRef kn)
76
77 (* Coercions *)
78
79 (* check that the computed target is the provided one *)
80 let check_target clt = function
81 | Some cl when not (cl_typ_eq cl clt) -> raise (CoercionError (WrongTarget(clt,cl)))
82 | _ -> ()
83
84 (* condition d'heritage uniforme *)
85
86 let uniform_cond sigma ctx lt =
87 List.for_all2eq (EConstr.eq_constr sigma)
88 lt (Context.Rel.instance_list EConstr.mkRel 0 ctx)
89
90 let class_of_global = function
91 | GlobRef.ConstRef sp ->
92 (match Structures.PrimitiveProjections.find_opt sp with
93 | Some p -> CL_PROJ p | None -> CL_CONST sp)
94 | GlobRef.IndRef sp -> CL_IND sp
95 | GlobRef.VarRef id -> CL_SECVAR id
96 | GlobRef.ConstructRef _ as c ->
97 user_err
98 (str "Constructors, such as " ++ Printer.pr_global c ++
99 str ", cannot be used as a class.")
100
101 (*
102 lp est la liste (inverse'e) des arguments de la coercion
103 ids est le nom de la classe source
104 sps_opt est le sp de la classe source dans le cas des structures
105 retourne:
106 la classe source
107 nbre d'arguments de la classe
108 le constr de la class
109 la liste des variables dont depend la classe source
110 l'indice de la classe source dans la liste lp
111 *)
112
113 let get_source env lp source =
114 let open Context.Rel.Declaration in
115 match source with
116 | None ->
117 (* Take the latest non let-in argument *)
118 let rec aux = function
119 | [] -> raise Not_found
120 | LocalDef _ :: lt -> aux lt
121 | LocalAssum (_,t1) :: lt ->
122 let cl1,u1,lv1 = find_class_type (push_rel_context lt env) Evd.empty (EConstr.of_constr t1) in
123 cl1,lt,lv1,1
124 in aux lp
125 | Some cl ->
126 (* Take the first argument that matches *)
127 let rec aux env acc = function
128 | [] -> raise Not_found
129 | LocalDef _ as decl :: lt -> aux (push_rel decl env) (decl::acc) lt
130 | LocalAssum (_,t1) as decl :: lt ->
131 try
132 let cl1,u1,lv1 = find_class_type env Evd.empty (EConstr.of_constr t1) in
133 if cl_typ_eq cl cl1 then cl1,acc,lv1,Context.Rel.nhyps lt+1
134 else raise Not_found
135 with Not_found -> aux (push_rel decl env) (decl::acc) lt
136 in aux env [] (List.rev lp)
137
138 let get_target env lp t ind =
139 if (ind > 1) then
140 CL_FUN
141 else
142 match pi1 (find_class_type (push_rel_context lp env) Evd.empty (EConstr.of_constr t)) with
143 | CL_CONST p when Structures.PrimitiveProjections.mem p ->
144 CL_PROJ (Option.get @@ Structures.PrimitiveProjections.find_opt p)
145 | x -> x
146
147 let strength_of_cl = function
148 | CL_CONST kn -> `GLOBAL
149 | CL_SECVAR id -> `LOCAL
150 | _ -> `GLOBAL
151
152 let strength_of_global = function
153 | GlobRef.VarRef _ -> `LOCAL
154 | _ -> `GLOBAL
155
156 let get_strength stre ref cls clt =
157 let stres = strength_of_cl cls in
158 let stret = strength_of_cl clt in
159 let stref = strength_of_global ref in
160 strength_min [stre;stres;stret;stref]
161
162 let ident_key_of_class = function
163 | CL_FUN -> "Funclass"
164 | CL_SORT -> "Sortclass"
165 | CL_CONST sp -> Id.to_string (Constant.label sp)
166 | CL_PROJ sp -> Id.to_string (Projection.Repr.label sp)
167 | CL_IND (sp,_) -> Id.to_string (MutInd.label sp)
168 | CL_SECVAR id -> Id.to_string id
169
170 (* Identity coercion *)
171
172 let error_not_transparent source =
173 user_err
174 (pr_class source ++ str " must be a transparent constant.")
175
176 let build_id_coercion ?loc idf_opt source poly =
177 let env = Global.env () in
178 let sigma = Evd.from_env env in
179 let sigma, vs = match source with
180 | CL_CONST sp -> Evd.fresh_global env sigma (GlobRef.ConstRef sp)
181 | _ -> error_not_transparent source in
182 let vs = EConstr.Unsafe.to_constr vs in
183 let c = match constant_opt_value_in env (destConst vs) with
184 | Some c -> c
185 | None -> error_not_transparent source in
186 let lams,t = decompose_lambda_decls c in
187 let val_f =
188 Term.it_mkLambda_or_LetIn
189 (mkLambda (make_annot (Name Namegen.default_dependent_ident) Sorts.Relevant,
190 applistc vs (Context.Rel.instance_list mkRel 0 lams),
191 mkRel 1))
192 lams
193 in
194 let typ_f =
195 List.fold_left (fun d c -> Term.mkProd_wo_LetIn c d)
196 (mkProd (make_annot Anonymous Sorts.Relevant, applistc vs (Context.Rel.instance_list mkRel 0 lams), lift 1 t))
197 lams
198 in
199 (* juste pour verification *)
200 let sigma, val_t = Typing.type_of env sigma (EConstr.of_constr val_f) in
201 let () =
202 if not (Reductionops.is_conv_leq env sigma val_t (EConstr.of_constr typ_f))
203 then
204 user_err (strbrk
205 "Cannot be defined as coercion (maybe a bad number of arguments).")
206 in
207 let name =
208 match idf_opt with
209 | Some idf -> idf
210 | None ->
211 let cl,u,_ = find_class_type env sigma (EConstr.of_constr t) in
212 Id.of_string ("Id_"^(ident_key_of_class source)^"_"^
213 (ident_key_of_class cl))
214 in
215 let univs = Evd.univ_entry ~poly sigma in
216 let constr_entry = (* Cast is necessary to express [val_f] is identity *)
217 DefinitionEntry
218 (definition_entry ~types:typ_f ~univs
219 ~inline:true (mkCast (val_f, DEFAULTcast, typ_f)))
220 in
221 let kind = Decls.(IsDefinition IdentityCoercion) in
222 let kn = declare_constant ?loc ~name ~kind constr_entry in
223 GlobRef.ConstRef kn
224
225 let check_source = function
226 | Some (CL_FUN as s) -> raise (CoercionError (ForbiddenSourceClass s))
227 | _ -> ()
228
229 let cache_coercion ?(update=false) c =
230 let env = Global.env () in
231 let sigma = Evd.from_env env in
232 Coercionops.declare_coercion env sigma ~update c
233
234 let discharge_coercion c =
235 if c.coe_local then None
236 else
237 let n =
238 try Array.length (Global.section_instance c.coe_value)
239 with Not_found -> 0
240 in
241 let nc = { c with
242 coe_param = n + c.coe_param;
243 coe_is_projection = Option.map Global.discharge_proj_repr c.coe_is_projection;
244 } in
245 Some nc
246
247 let classify_coercion obj =
248 if obj.coe_local then Dispose else Substitute
249
250 let coe_cat = create_category "coercions"
251
252 let inCoercion : coe_info_typ -> obj =
253 declare_object {(default_object "COERCION") with
254 open_function = simple_open ~cat:coe_cat cache_coercion;
255 cache_function = cache_coercion;
256 subst_function = (fun (subst,c) -> subst_coercion subst c);
257 classify_function = classify_coercion;
258 discharge_function = discharge_coercion;
259 }
260
261 let declare_coercion coef ?(local = false) ~reversible ~isid ~src:cls ~target:clt ~params:ps () =
262 let isproj =
263 match coef with
264 | GlobRef.ConstRef c -> Structures.PrimitiveProjections.find_opt c
265 | _ -> None
266 in
267 let c = {
268 coe_value = coef;
269 coe_local = local;
270 coe_reversible = reversible;
271 coe_is_identity = isid;
272 coe_is_projection = isproj;
273 coe_source = cls;
274 coe_target = clt;
275 coe_param = ps;
276 } in
277 Lib.add_leaf (inCoercion c)
278
279 (*
280 nom de la fonction coercion
281 strength de f
282 nom de la classe source (optionnel)
283 sp de la classe source (dans le cas des structures)
284 nom de la classe target (optionnel)
285 booleen "coercion identite'?"
286
287 lorque source est None alors target est None aussi.
288 *)
289
290 let warn_uniform_inheritance =
291 CWarnings.create ~name:"uniform-inheritance" ~category:CWarnings.CoreCategories.coercions
292 (fun g ->
293 Printer.pr_global g ++
294 strbrk" does not respect the uniform inheritance condition.")
295
296 let add_new_coercion_core coef stre ~reversible source target isid : unit =
297 check_source source;
298 let env = Global.env () in
299 let t, _ = Typeops.type_of_global_in_context env coef in
300 if coercion_exists coef then raise (CoercionError AlreadyExists);
301 let lp,tg = decompose_prod_decls t in
302 let llp = List.length lp in
303 if Int.equal llp 0 then raise (CoercionError NotAFunction);
304 let (cls,ctx,lvs,ind) =
305 try
306 get_source env lp source
307 with Not_found ->
308 raise (CoercionError (NoSource source))
309 in
310 check_source (Some cls);
311 if not (uniform_cond Evd.empty (* FIXME - for when possibly called with unresolved evars in the future *)
312 ctx lvs) then
313 warn_uniform_inheritance coef;
314 let clt =
315 try
316 get_target env lp tg ind
317 with Not_found ->
318 raise (CoercionError NoTarget)
319 in
320 check_target clt target;
321 check_arity cls;
322 check_arity clt;
323 let local = match get_strength stre coef cls clt with
324 | `LOCAL -> true
325 | `GLOBAL -> false
326 in
327 let params = List.length (Context.Rel.instance_list EConstr.mkRel 0 ctx) in
328 declare_coercion coef ~local ~reversible ~isid ~src:cls ~target:clt ~params ()
329
330 let try_add_new_coercion_core ref ~local c ~reversible d e =
331 try add_new_coercion_core ref (loc_of_bool local) c ~reversible d e
332 with CoercionError e ->
333 user_err
334 (explain_coercion_error ref e ++ str ".")
335
336 let try_add_new_coercion ref ~local ~reversible =
337 try_add_new_coercion_core ref ~local ~reversible None None false
338
339 let try_add_new_coercion_subclass ?loc cl ~local ~poly ~reversible =
340 let coe_ref = build_id_coercion ?loc None cl poly in
341 try_add_new_coercion_core coe_ref ~local ~reversible (Some cl) None true
342
343 let try_add_new_coercion_with_target ref ~local ~reversible ~source ~target =
344 try_add_new_coercion_core ref ~local ~reversible
345 (Some source) (Some target) false
346
347 let try_add_new_identity_coercion {CAst.v=id; loc} ~local ~poly ~source ~target =
348 let ref = build_id_coercion ?loc (Some id) source poly in
349 try_add_new_coercion_core ref ~local ~reversible:true
350 (Some source) (Some target) true
351
352 let try_add_new_coercion_with_source ref ~local ~reversible ~source =
353 try_add_new_coercion_core ref ~local ~reversible (Some source) None false
354
355 let coercion_hook ~reversible = Declare.Hook.make @@ fun { scope; dref; _ } ->
356 let open Locality in
357 let local = match scope with
358 | Discharge -> assert false (* Local Coercion in section behaves like Local Definition *)
359 | Global ImportNeedQualified -> true
360 | Global ImportDefaultBehavior -> false
361 in
362 let () = try_add_new_coercion dref ~local ~reversible in
363 let msg = Nametab.pr_global_env Id.Set.empty dref ++ str " is now a coercion" in
364 Flags.if_verbose Feedback.msg_info msg
365
366 let subclass_hook ~poly ~reversible = Declare.Hook.make @@ fun { scope; dref; _ } ->
367 let open Locality in
368 let stre = match scope with
369 | Discharge -> assert false (* Local Subclass in section behaves like Local Definition *)
370 | Global ImportNeedQualified -> true
371 | Global ImportDefaultBehavior -> false
372 in
373 let cl = class_of_global dref in
374 let loc = Nametab.cci_src_loc (TrueGlobal dref) in
375 try_add_new_coercion_subclass ?loc cl ~local:stre ~poly ~reversible
376
377 let nonuniform = Attributes.bool_attribute ~name:"nonuniform"
378
379 let warn_reverse_no_change =
380 CWarnings.create ~name:"reversible-no-change" ~category:CWarnings.CoreCategories.coercions
381 (fun () -> str "The reversible attribute is unchanged.")
382
383 let change_reverse ref ~reversible =
384 if not (coercion_exists ref) then
385 user_err (Printer.pr_global ref ++ str" is not a coercion.");
386 let coe_info = coercion_info ref in
387 if reversible = coe_info.coe_reversible then warn_reverse_no_change ()
388 else cache_coercion ~update:true { coe_info with coe_reversible = reversible }