Debian Codegraph @

kernel/subtyping.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 Jacek Chrzaszcz, Aug 2002 as part of the implementation of
12 the Coq module system *)
13
14 (* This module checks subtyping of module types *)
15
16 (*i*)
17 open Names
18 open UVars
19 open Util
20 open Constr
21 open Declarations
22 open Mod_declarations
23 open Declareops
24 open Conversion
25 open Inductive
26 open Modops
27 open Context
28 open Mod_subst
29 (*i*)
30
31 (* This local type is used to subtype a constant with a constructor or
32 an inductive type. It can also be useful to allow reorderings in
33 inductive types *)
34 type namedobject =
35 | Constant of constant_body
36 | IndType of inductive * mutual_inductive_body
37 | IndConstr of constructor * mutual_inductive_body
38 | Rules
39
40 type namedmodule =
41 | Module of module_body
42 | Modtype of module_type_body
43
44 (* adds above information about one mutual inductive: all types and
45 constructors *)
46
47 let add_mib_nameobjects mp l mib map =
48 let ind = MutInd.make2 mp l in
49 let add_mip_nameobjects j oib map =
50 let ip = (ind,j) in
51 let map =
52 Array.fold_right_i
53 (fun i id map ->
54 Id.Map.add id (IndConstr((ip,i+1), mib)) map)
55 oib.mind_consnames
56 map
57 in
58 Id.Map.add oib.mind_typename (IndType (ip, mib)) map
59 in
60 Array.fold_right_i add_mip_nameobjects mib.mind_packets map
61
62
63 (* creates (namedobject/namedmodule) map for the whole signature *)
64
65 type labmap = { objs : namedobject Id.Map.t; mods : namedmodule Id.Map.t }
66
67 let empty_labmap = { objs = Id.Map.empty; mods = Id.Map.empty }
68
69 let get_obj mp map l =
70 try Id.Map.find l map.objs
71 with Not_found -> error_no_such_label_sub l (ModPath.to_string mp)
72
73 let get_mod mp map l =
74 try Id.Map.find l map.mods
75 with Not_found -> error_no_such_label_sub l (ModPath.to_string mp)
76
77 let make_labmap mp list =
78 let add_one (l,e) map =
79 match e with
80 | SFBconst cb -> { map with objs = Id.Map.add l (Constant cb) map.objs }
81 | SFBrules _ -> { map with objs = Id.Map.add l Rules map.objs }
82 | SFBmind mib -> { map with objs = add_mib_nameobjects mp l mib map.objs }
83 | SFBmodule mb -> { map with mods = Id.Map.add l (Module mb) map.mods }
84 | SFBmodtype mtb -> { map with mods = Id.Map.add l (Modtype mtb) map.mods }
85 in
86 CList.fold_right add_one list empty_labmap
87
88 let check_conv_error error why state poly pb env a1 a2 =
89 if poly then match Conversion.default_conv pb env a1 a2 with
90 | Result.Ok () -> fst state
91 | Result.Error () -> error (IncompatiblePolymorphism (env, a1, a2))
92 else match Conversion.generic_conv pb ~l2r:false TransparentState.full env state a1 a2 with
93 | Result.Ok state -> state
94 | Result.Error None -> error why
95 | Result.Error (Some (Univ e)) -> error (IncompatibleUniverses { err = e; env; t1 = a1; t2 = a2 })
96 | Result.Error (Some (Qual e)) -> error (IncompatibleQualities { err = e; env; t1 = a1; t2 = a2 })
97
98 (** Subtyping of polymorphic contexts *)
99
100 let check_polymorphic_universes env ctxT ctx =
101 if not @@ eq_sizes (AbstractContext.size ctxT) (AbstractContext.size ctx) then false
102 else
103 let uctxT = AbstractContext.repr ctxT in
104 let () = Environ.check_ucontext uctxT env in
105 let env = Environ.push_context ~strict:false uctxT env in
106 let qcst, ucst = UContext.constraints (AbstractContext.repr ctx) in
107 UGraph.check_constraints ucst (Environ.universes env) &&
108 QGraph.check_constraints qcst (Environ.qualities env)
109
110 let check_universes error env u1 u2 =
111 match u1, u2 with
112 | Monomorphic, Monomorphic -> env
113 | Polymorphic auctx1, Polymorphic auctx2 ->
114 if not (check_polymorphic_universes env auctx2 auctx1) then
115 error (IncompatibleUnivConstraints { got = auctx1; expect = auctx2; } )
116 else
117 let () = Environ.check_ucontext (UVars.AbstractContext.repr auctx2) env in
118 let env = Environ.push_context ~strict:false (UVars.AbstractContext.repr auctx2) env in
119 env
120 | Monomorphic, Polymorphic _ -> error (PolymorphicStatusExpected true)
121 | Polymorphic _, Monomorphic -> error (PolymorphicStatusExpected false)
122
123 let check_variance error v1 v2 =
124 match v1, v2 with
125 | None, None -> ()
126 | Some v1, Some v2 ->
127 if not (Array.for_all2 Variance.check_subtype v2 v1) then
128 error IncompatibleVariance
129 | None, Some _ -> error (CumulativeStatusExpected true)
130 | Some _, None -> error (CumulativeStatusExpected false)
131
132 let squash_info_equal s1 s2 = match s1, s2 with
133 | AlwaysSquashed, AlwaysSquashed -> true
134 | SometimesSquashed s1, SometimesSquashed s2 -> Sorts.Quality.Set.equal s1 s2
135 | (AlwaysSquashed | SometimesSquashed _), _ -> false
136
137 (* for now we do not allow reorderings *)
138
139 let check_inductive (cst, ustate) trace env mp1 l info1 mp2 mib2 subst1 subst2 reso1 reso2=
140 let kn1 = KerName.make mp1 l in
141 let kn2 = KerName.make mp2 l in
142 let error why = error_signature_mismatch trace l why in
143 let check_conv why cst poly pb = check_conv_error error why (cst, ustate) poly pb in
144 let mib1 =
145 match info1 with
146 | IndType ((_,0), mib) -> Declareops.subst_mind_body subst1 mib
147 | _ -> error (InductiveFieldExpected mib2)
148 in
149 let env = check_universes error env mib1.mind_universes mib2.mind_universes in
150 let () = check_variance error mib1.mind_variance mib2.mind_variance in
151 let inst = make_abstract_instance (Declareops.inductive_polymorphic_context mib1) in
152 let mib2 = Declareops.subst_mind_body subst2 mib2 in
153 let check_inductive_type cst name t1 t2 =
154 check_conv (NotConvertibleInductiveField (name, Some (env, t1, t2)))
155 cst (inductive_is_polymorphic mib1) CUMUL env t1 t2
156 in
157
158 let check_packet cst p1 p2 =
159 let check f test why = let fp2 = f p2 in if not (test (f p1) fp2) then error (why fp2) in
160 if not (Array.equal Id.equal p1.mind_consnames p2.mind_consnames) then
161 error (NotSameConstructorNamesField (p1.mind_consnames, p2.mind_consnames));
162 if not (Id.equal p1.mind_typename p2.mind_typename) then
163 error (NotSameInductiveNameInBlockField (p1.mind_typename, p2.mind_typename));
164 check (fun p -> p.mind_squashed) (Option.equal squash_info_equal)
165 (fun _ -> NotConvertibleInductiveField (p2.mind_typename, None));
166 (* nf_lc later *)
167 (* nf_arity later *)
168 (* user_lc ignored *)
169 (* user_arity ignored *)
170 check (fun p -> p.mind_nrealargs) Int.equal (fun _ -> NotConvertibleInductiveField (p2.mind_typename, None)); (* How can it fail since the type of inductive are checked below? [HH] *)
171 (* listrec ignored *)
172 (* finite done *)
173 (* nparams done *)
174 (* params_ctxt done because part of the inductive types *)
175 let ty1 = type_of_inductive ((mib1, p1), inst) in
176 let ty2 = type_of_inductive ((mib2, p2), inst) in
177 let cst = check_inductive_type cst p2.mind_typename ty1 ty2 in
178 (* we check that records and their field names are preserved. *)
179 (** FIXME: this check looks nonsense *)
180 check (fun p -> p.mind_record <> NotRecord) (==) (fun x -> RecordFieldExpected x);
181 if p1.mind_record <> NotRecord then begin
182 let rec names_prod_letin t = match kind t with
183 | Prod(n,_,t) -> n.binder_name::(names_prod_letin t)
184 | LetIn(n,_,_,t) -> n.binder_name::(names_prod_letin t)
185 | Cast(t,_,_) -> names_prod_letin t
186 | _ -> []
187 in
188 assert (Int.equal (Array.length p1.mind_user_lc) 1);
189 assert (Int.equal (Array.length p2.mind_user_lc) 1);
190 let get_proj_names p =
191 (* can nparamdecls depend on which mib we look at? *)
192 let nparamdecls = List.length mib1.mind_params_ctxt in
193 let names = names_prod_letin (p.mind_user_lc.(0)) in
194 snd (List.chop nparamdecls names)
195 in
196 (* p1 is implementation, p2 is signature (expected) *)
197 let expected = get_proj_names p2 in
198 let got = get_proj_names p1 in
199 if not (List.equal Name.equal expected got) then
200 error (RecordProjectionsExpected { expected; got });
201 end;
202 cst
203 in
204 let mind = MutInd.make1 kn1 in
205 let check_cons_types i cst p1 p2 =
206 Array.fold_left3
207 (fun cst id t1 t2 -> check_conv (NotConvertibleConstructorField (id, Some (env, t1, t2))) cst
208 (inductive_is_polymorphic mib1) CONV env t1 t2)
209 cst
210 p2.mind_consnames
211 (arities_of_constructors ((mind,i), inst) (mib1, p1))
212 (arities_of_constructors ((mind,i), inst) (mib2, p2))
213 in
214 let check f test why = if not (test (f mib1) (f mib2)) then error (why (f mib2)) in
215 check (fun mib -> mib.mind_finite<>CoFinite) (==) (fun x -> FiniteInductiveFieldExpected x);
216 if not (Int.equal (Declareops.mind_ntypes mib1) (Declareops.mind_ntypes mib2)) then
217 error (InductiveNumbersFieldExpected { got = Declareops.mind_ntypes mib1; expected = Declareops.mind_ntypes mib2 });
218 assert (List.is_empty mib1.mind_hyps && List.is_empty mib2.mind_hyps);
219 assert (Array.length mib1.mind_packets >= 1
220 && Array.length mib2.mind_packets >= 1);
221
222 (* Check that the expected numbers of uniform parameters are the same *)
223 (* No need to check the contexts of parameters: it is checked *)
224 (* at the time of checking the inductive arities in check_packet. *)
225 (* Notice that we don't expect the local definitions to match: only *)
226 (* the inductive types and constructors types have to be convertible *)
227 if not (Int.equal mib1.mind_nparams mib2.mind_nparams) then
228 error (InductiveParamsNumberField { got = mib1.mind_nparams; expected = mib2.mind_nparams });
229
230 begin
231 let kn2' = kn_of_delta reso2 kn2 in
232 let mind1 = mind_of_delta_kn reso1 kn1 in
233 let mind2 = subst_mind subst2 (MutInd.make kn2 kn2') in
234 if KerName.equal kn2 kn2' || MutInd.CanOrd.equal mind1 mind2
235 then ()
236 else error (NotEqualInductiveAliases (mind1, mind2))
237 end;
238 (* we first check simple things *)
239 let cst =
240 Array.fold_left2 check_packet cst mib1.mind_packets mib2.mind_packets
241 in
242 (* and constructor types in the end *)
243 let cst =
244 Array.fold_left2_i check_cons_types cst mib1.mind_packets mib2.mind_packets
245 in
246 cst
247
248
249 let check_constant (cst, ustate) trace env l info1 cb2 subst1 subst2 =
250 let error why = error_signature_mismatch trace l why in
251 let check_conv why cst poly pb = check_conv_error error why (cst, ustate) poly pb in
252 let check_type poly cst env t1 t2 =
253 let err = NotConvertibleTypeField (env, t1, t2) in
254 check_conv err cst poly CUMUL env t1 t2
255 in
256 match info1 with
257 | IndType _ | IndConstr _ | Rules -> error DefinitionFieldExpected
258 | Constant cb1 ->
259 let () = assert (List.is_empty cb1.const_hyps && List.is_empty cb2.const_hyps) in
260 let cb1 = Declareops.subst_const_body subst1 cb1 in
261 let cb2 = Declareops.subst_const_body subst2 cb2 in
262 (* Start by checking universes *)
263 let env = check_universes error env cb1.const_universes cb2.const_universes in
264 let poly = Declareops.constant_is_polymorphic cb1 in
265 (* Now check types *)
266 let typ1 = cb1.const_type in
267 let typ2 = cb2.const_type in
268 let cst = check_type poly cst env typ1 typ2 in
269 (* Now we check the bodies:
270 - A transparent constant can only be implemented by a compatible
271 transparent constant.
272 - A primitive cannot be implemented.
273 (We could try to allow implementing with the same primitive,
274 but for some reason we get cb1.const_body = Def,
275 without some use case there is no motivation to solve this.)
276 - In the signature, an opaque is handled just as a parameter:
277 anything of the right type can implement it, even if bodies differ.
278 *)
279 (match cb2.const_body with
280 | Undef _ | OpaqueDef _ -> cst
281 | Primitive _ | Symbol _ -> error (NotConvertibleBodyField None)
282 | Def c2 ->
283 (match cb1.const_body with
284 | Primitive _ | Undef _ | OpaqueDef _ | Symbol _ -> error (NotConvertibleBodyField None)
285 | Def c1 ->
286 (* NB: cb1 might have been strengthened and appear as transparent.
287 Anyway [check_conv] will handle that afterwards. *)
288 check_conv (NotConvertibleBodyField (Some (env, c1, c2))) cst poly CONV env c1 c2))
289
290 let rec check_modules state trace env mp1 msb1 mp2 msb2 subst1 subst2 =
291 let mty1 = module_type_of_module msb1 in
292 let mty2 = module_type_of_module msb2 in
293 check_modtypes state trace env mp1 mty1 mp2 mty2 subst1 subst2
294
295 and check_signatures (cst, ustate) trace env mp1 sig1 mp2 sig2 subst1 subst2 reso1 reso2 =
296 let map1 = make_labmap mp1 sig1 in
297 let check_one_body cst (l,spec2) =
298 match spec2 with
299 | SFBconst cb2 ->
300 check_constant (cst, ustate) trace env l (get_obj mp1 map1 l)
301 cb2 subst1 subst2
302 | SFBmind mib2 ->
303 check_inductive (cst, ustate) trace env mp1 l (get_obj mp1 map1 l)
304 mp2 mib2 subst1 subst2 reso1 reso2
305 | SFBrules _ ->
306 error_signature_mismatch trace l NoRewriteRulesSubtyping
307 | SFBmodule msb2 ->
308 let mp1' = MPdot (mp1, l) in
309 let mp2' = MPdot (mp2, l) in
310 begin match get_mod mp1 map1 l with
311 | Module msb1 -> check_modules (cst, ustate) (Submodule l :: trace) env mp1' msb1 mp2' msb2 subst1 subst2
312 | _ -> error_signature_mismatch trace l ModuleFieldExpected
313 end
314 | SFBmodtype mtb2 ->
315 let mtb1 = match get_mod mp1 map1 l with
316 | Modtype mtb -> mtb
317 | _ -> error_signature_mismatch trace l ModuleTypeFieldExpected
318 in
319 let mp1' = MPdot (mp1, l) in
320 let mp2' = MPdot (mp2, l) in
321 (* Check for equivalence via subtyping in both directions *)
322 let cst =
323 let env = add_module mp1' (module_body_of_type mtb1) env in
324 check_modtypes (cst, ustate) (Submodule l :: trace) env mp1' mtb1 mp2' mtb2 subst1 subst2
325 in
326 let env = add_module mp2' (module_body_of_type mtb2) env in
327 check_modtypes (cst, ustate) (Submodule l :: trace) env mp2' mtb2 mp1' mtb1 subst2 subst1
328 in
329 List.fold_left check_one_body cst sig2
330
331 and check_modtypes (cst, ustate) trace env mp1 mtb1 mp2 mtb2 subst1 subst2 =
332 if mtb1==mtb2 || mod_type mtb1 == mod_type mtb2 then cst
333 else
334 let rec check_structure cst ~nargs env struc1 struc2 subst1 subst2 =
335 match struc1,struc2 with
336 | NoFunctor list1,
337 NoFunctor list2 ->
338 let env =
339 if Int.equal nargs 0 then
340 (* Not a functor, so the body and all its subcomponents should
341 already be in the environment *)
342 env
343 else
344 (* We only add the subcomponents, the functor per se is already
345 part of the environment but the subtyping check will never access
346 it directly *)
347 Modops.add_structure mp1 (subst_structure subst1 mp1 list1) (mod_delta mtb1) env
348 in
349 let delta_mtb1 = mod_delta mtb1 in
350 let delta_mtb2 = mod_delta mtb2 in
351 check_signatures (cst, ustate) trace env
352 mp1 list1 mp2 list2 subst1 subst2
353 delta_mtb1 delta_mtb2
354 | MoreFunctor (arg_id1,arg_t1,body_t1),
355 MoreFunctor (arg_id2,arg_t2,body_t2) ->
356 let mparg1 = MPbound arg_id1 in
357 let mparg2 = MPbound arg_id2 in
358 let subst1 = join (map_mbid arg_id1 mparg2 (mod_delta arg_t2)) subst1 in
359 let env = add_module_parameter arg_id2 arg_t2 env in
360 let cst = check_modtypes (cst, ustate) (FunctorArgument (nargs+1) :: trace) env mparg2 arg_t2 mparg1 arg_t1 subst2 subst1 in
361 (* contravariant *)
362 check_structure cst ~nargs:(nargs + 1) env body_t1 body_t2 subst1 subst2
363 | _ , _ -> error_incompatible_modtypes mtb1 mtb2
364 in
365 check_structure cst ~nargs:0 env (mod_type mtb1) (mod_type mtb2) subst1 subst2
366
367 let check_subtypes state env mp_sup mp_super super =
368 let sup = match Environ.lookup_module mp_sup env with
369 | mb -> module_type_of_module mb
370 | exception Not_found -> assert false
371 in
372 check_modtypes state [] env
373 mp_sup (strengthen sup mp_sup) mp_super super empty_subst
374 (map_mp mp_super mp_sup (mod_delta sup))