Debian Codegraph @

kernel/mod_typing.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 provides the main functions for type-checking module
15 declarations *)
16
17 open Util
18 open Names
19 open Declarations
20 open Mod_declarations
21 open Entries
22 open Environ
23 open Modops
24 open Mod_subst
25
26 let rec mp_from_mexpr = function
27 | MEident mp -> mp
28 | MEapply (expr,_) -> mp_from_mexpr expr
29 | MEwith (expr,_) -> mp_from_mexpr expr
30
31 let is_modular = function
32 | SFBmodule _ | SFBmodtype _ -> true
33 | SFBconst _ | SFBmind _ | SFBrules _ -> false
34
35 (** Split a [structure_body] at some label corresponding to
36 a modular definition or not. *)
37
38 let split_struc k m struc =
39 let rec split rev_before = function
40 | [] -> raise Not_found
41 | (k',b)::after when Id.equal k k' && (is_modular b) == (m : bool) ->
42 List.rev rev_before,b,after
43 | h::tail -> split (h::rev_before) tail
44 in split [] struc
45
46 let discr_resolver mp mtb = match mod_type mtb with
47 | NoFunctor _ -> mod_delta mtb
48 | MoreFunctor _ -> empty_delta_resolver mp
49
50 let rec rebuild_mp mp l =
51 match l with
52 | []-> mp
53 | i::r -> rebuild_mp (MPdot(mp,i)) r
54
55 let infer_gen_conv state env c1 c2 =
56 Conversion.generic_conv Conversion.CONV ~l2r:false TransparentState.full env state c1 c2
57
58 let infer_gen_conv_leq state env c1 c2 =
59 Conversion.generic_conv Conversion.CUMUL ~l2r:false TransparentState.full env state c1 c2
60
61 type with_body = {
62 w_def : Constr.t;
63 w_univs : universes;
64 w_bytecode : Vmlibrary.indirect_code option;
65 }
66
67 let rec check_with_def (cst, ustate) env struc (idl, wth) mp reso =
68 let lab,idl = match idl with
69 | [] -> assert false
70 | id::idl -> id, idl
71 in
72 let error why = error_incorrect_with_constraint lab why in
73 try
74 let modular = not (List.is_empty idl) in
75 let before,spec,after = split_struc lab modular struc in
76 let env' = Modops.add_structure mp before reso env in
77 if List.is_empty idl then
78 (* Toplevel definition *)
79 let cb = match spec with
80 | SFBconst cb -> cb
81 | _ -> error_not_a_constant lab
82 in
83 (* In the spirit of subtyping.check_constant, we accept
84 any implementations of parameters and opaque terms,
85 as long as they have the right type *)
86 let (univs, typ), ctx' =
87 match cb.const_universes, wth.w_univs with
88 | Monomorphic, Monomorphic ->
89 let error_univ_mismatch env t1 t2 = function
90 | Conversion.Univ err -> error (WithSignatureMismatch (IncompatibleUniverses { err; env; t1; t2 }))
91 | Conversion.Qual err -> error (WithSignatureMismatch (IncompatibleQualities { err; env; t1; t2 }))
92 in
93 let j = Typeops.infer env' wth.w_def in
94 begin match cb.const_body with
95 | Undef _ | OpaqueDef _ ->
96 let typ = cb.const_type in
97 begin match infer_gen_conv_leq (cst, ustate) env' j.uj_type typ with
98 | Result.Ok cst -> (cb.const_universes, cb.const_type), cst
99 | Result.Error None -> error (WithSignatureMismatch (NotConvertibleTypeField (env', j.uj_type, typ)))
100 | Result.Error (Some e) -> error_univ_mismatch env' j.uj_type typ e
101 end
102 | Def c' ->
103 begin match infer_gen_conv (cst, ustate) env' wth.w_def c' with
104 | Result.Ok cst -> (cb.const_universes, cb.const_type), cst
105 | Result.Error None -> error (WithSignatureMismatch (NotConvertibleBodyField (Some (env', wth.w_def, c'))))
106 | Result.Error (Some e) -> error_univ_mismatch env' wth.w_def c' e
107 end
108 | Primitive _ -> error WithCannotConstrainPrimitive
109 | Symbol _ -> error WithCannotConstrainSymbol
110 end
111 | Polymorphic uctx, Polymorphic ctx ->
112 let () =
113 if not (Subtyping.check_polymorphic_universes env uctx ctx) then
114 error (WithSignatureMismatch (IncompatibleUnivConstraints { got = ctx; expect = uctx }))
115 in
116 (** Terms are compared in a context with De Bruijn universe indices *)
117 let () = check_ucontext (UVars.AbstractContext.repr uctx) env in
118 let j =
119 (* Use 1. the external environment with 2. the with Definition constraints *)
120 let jenv = Environ.push_context ~strict:false (UVars.AbstractContext.repr ctx) env in
121 Typeops.infer jenv wth.w_def
122 in
123 let env' = Environ.push_context ~strict:false (UVars.AbstractContext.repr uctx) env' in
124 let () = match cb.const_body with
125 | Undef _ | OpaqueDef _ ->
126 let typ = cb.const_type in
127 begin match Conversion.conv_leq env' j.uj_type typ with
128 | Result.Ok () -> ()
129 | Result.Error () -> error (WithSignatureMismatch (NotConvertibleTypeField (env', typ, j.uj_type)))
130 end
131 | Def c' ->
132 begin match Conversion.conv env' wth.w_def c' with
133 | Result.Ok () -> ()
134 | Result.Error () -> error (WithSignatureMismatch (NotConvertibleBodyField (Some (env', wth.w_def, c'))))
135 end
136 | Primitive _ -> error WithCannotConstrainPrimitive
137 | Symbol _ -> error WithCannotConstrainSymbol
138 in
139 (cb.const_universes, cb.const_type), cst
140 | Monomorphic, Polymorphic _ -> error (WithSignatureMismatch (PolymorphicStatusExpected true))
141 | Polymorphic _, Monomorphic -> error (WithSignatureMismatch (PolymorphicStatusExpected false))
142 in
143 (* Here we have two choices for the type of the constant: either pick the
144 type T from module constant or the type U from the with Definition
145 constant, including their universe constraints. In general, we only
146 have U ≤ T, so the corresponding module types will only satisfy
147 MU ≤ MT. In some sense MU is minimal and MT maximal, so both are
148 canonical. Depending on the context, one may be preferred to the
149 other but there is no "best" choice a priori. Some code out there
150 depends on picking MT, so we enshrine this decision here. *)
151 let cb' =
152 { cb with
153 const_body = Def wth.w_def;
154 const_type = typ;
155 const_universes = univs;
156 const_body_code = wth.w_bytecode; }
157 in
158 before@(lab,SFBconst(cb'))::after, ctx'
159 else
160 (* Definition inside a sub-module *)
161 let mb = match spec with
162 | SFBmodule mb -> mb
163 | _ -> error_not_a_module_label lab
164 in
165 begin match Mod_declarations.mod_expr mb with
166 | Abstract ->
167 let struc = Modops.destr_nofunctor (MPdot (mp,lab)) (mod_type mb) in
168 let struc', cst =
169 check_with_def (cst, ustate) env' struc (idl, wth) (MPdot(mp,lab)) (mod_delta mb)
170 in
171 let mb' = replace_module_body struc' (mod_delta mb) mb in
172 before@(lab,SFBmodule mb')::after, cst
173 | _ -> error_generative_module_expected lab
174 end
175 with
176 | Not_found -> error_no_such_label lab mp
177
178 (* [mp] is the ambient modpath of [struc],
179 [new_mp] is the path of the module to replace [idl] with *)
180 let rec check_with_mod (cst, ustate) env struc (idl,new_mp) mp reso =
181 let lab,idl = match idl with
182 | [] -> assert false
183 | id::idl -> id, idl
184 in
185 try
186 let before,spec,after = split_struc lab true struc in
187 let env' = Modops.add_structure mp before reso env in
188 let old = match spec with
189 | SFBmodule mb -> mb
190 | _ -> error_not_a_module_label lab
191 in
192 if List.is_empty idl then
193 (* Toplevel module definition *)
194 let new_mb = lookup_module new_mp env in
195 let cst = match Mod_declarations.mod_expr old with
196 | Abstract ->
197 let mtb_old = module_type_of_module old in
198 let cst = Subtyping.check_subtypes (cst, ustate) env' new_mp (MPdot (mp, lab)) mtb_old in
199 cst
200 | Algebraic (MENoFunctor (MEident(mp'))) ->
201 check_modpath_equiv env' new_mp mp';
202 cst
203 | _ -> error_generative_module_expected lab
204 in
205 let mp' = MPdot (mp,lab) in
206 let new_mb = strengthen_and_subst_module_body new_mp new_mb mp' false in
207 (** TODO: check this is fine when new_mb is a functor *)
208 let new_mb' = strengthen_module_body ~src:new_mp (mod_type new_mb) (mod_delta new_mb) new_mb in
209 let subreso = mod_delta new_mb in
210 (* we propagate the new equality in the rest of the signature
211 with the identity substitution accompanied by the new resolver*)
212 let id_subst = map_mp mp' mp' subreso in
213 let new_after = subst_structure id_subst mp after in
214 before @ (lab, SFBmodule new_mb') :: new_after, subreso, cst
215 else
216 (* Module definition of a sub-module *)
217 let mp' = MPdot (mp,lab) in
218 let old = match spec with
219 | SFBmodule msb -> msb
220 | _ -> error_not_a_module_label lab
221 in
222 begin match Mod_declarations.mod_expr old with
223 | Abstract ->
224 let struc = destr_nofunctor mp' (mod_type old) in
225 let struc', subreso, cst =
226 check_with_mod (cst, ustate) env' struc (idl,new_mp) mp' (mod_delta old)
227 in
228 let reso' = add_delta_resolver (mod_delta old) (upcast_delta_resolver mp' subreso) in
229 let new_mb = replace_module_body struc' reso' old in
230 let id_subst = map_mp mp' mp' reso' in
231 let new_after = subst_structure id_subst mp after in
232 before @ (lab, SFBmodule new_mb) :: new_after, subreso, cst
233 | Algebraic (MENoFunctor (MEident mp0)) ->
234 let mpnew = rebuild_mp mp0 idl in
235 check_modpath_equiv env' mpnew mp;
236 before@(lab,spec)::after, reso, cst
237 | _ -> error_generative_module_expected lab
238 end
239 with
240 | Not_found -> error_no_such_label lab mp
241
242 type 'a vm_handler = { vm_handler : env -> universes -> Constr.t -> 'a -> 'a * Vmlibrary.indirect_code option }
243 type 'a vm_state = 'a * 'a vm_handler
244
245 let check_with ustate vmstate env mp (sign,reso,cst,vm) = function
246 | WithDef(idl, (c, ctx)) ->
247 let struc = destr_nofunctor mp sign in
248 let univs = match ctx with None -> Monomorphic | Some uctx -> Polymorphic uctx in
249 let vm, bcode = vmstate.vm_handler env univs c vm in
250 let body = { w_def = c; w_univs = univs; w_bytecode = bcode } in
251 let struc', cst = check_with_def (cst, ustate) env struc (idl, body) mp reso in
252 NoFunctor struc', reso, cst, vm
253 | WithMod(idl,new_mp) ->
254 let struc = destr_nofunctor mp sign in
255 let struc', subreso, cst = check_with_mod (cst, ustate) env struc (idl, new_mp) mp reso in
256 let reso' = add_delta_resolver reso (upcast_delta_resolver mp subreso) in
257 NoFunctor struc', reso', cst, vm
258
259 let check_with_alg ustate vmstate env mp (sign, alg, reso, cst, vm) wd =
260 let struc, reso, cst, vm = check_with ustate vmstate env mp (sign, reso, cst, vm) wd in
261 struc, MEwith (alg, wd), reso, cst, vm
262
263 let rec translate_apply ustate env inl mp subst (sign, reso, cst) args = match args with
264 | [] ->
265 let sign = subst_signature subst mp sign in
266 let reso = subst_codom_delta_resolver subst reso in
267 (sign, reso, cst)
268 | mp1 :: args ->
269 let farg_id, farg_b, sign = destr_functor sign in
270 let farg_b =
271 if is_empty_subst subst then farg_b
272 else subst_modtype subst_codom subst (MPbound farg_id) farg_b
273 in
274 let cst = Subtyping.check_subtypes (cst, ustate) env mp1 (MPbound farg_id) farg_b in
275 let mp_delta = discr_resolver mp1 (lookup_module mp1 env) in
276 let mp_delta = inline_delta_resolver env inl mp1 farg_id farg_b mp_delta in
277 let nsubst = map_mbid farg_id mp1 mp_delta in
278 let subst = join subst nsubst in
279 translate_apply ustate env inl mp subst (sign, reso, cst) args
280
281 (** Translation of a module struct entry :
282 - We translate to a module when a [module_path] is given,
283 otherwise to a module type.
284 - The first output is the expanded signature
285 - The second output is the algebraic expression, kept for the extraction.
286 *)
287
288 let rec decompose_apply accu = function
289 | MEapply (f, arg) -> decompose_apply (arg :: accu) f
290 | (MEident _ | MEwith _) as f -> f, accu
291
292 let rec translate_mse (cst, ustate) (vm, vmstate) env mpo inl me = match me with
293 | MEident mp1 ->
294 let mb = match mpo with
295 | Some mp -> strengthen_and_subst_module_body mp1 (lookup_module mp1 env) mp false
296 | None ->
297 let mt = lookup_modtype mp1 env in
298 module_body_of_type mt
299 in
300 mod_type mb, me, mod_delta mb, cst, vm
301 | MEapply _ ->
302 let fe, args = decompose_apply [] me in
303 let (sign, alg, reso, cst, vm) = translate_mse (cst, ustate) (vm, vmstate) env mpo inl fe in
304 let mp = match mpo with Some mp -> mp | None -> mp_from_mexpr fe in
305 let (sign, reso, cst) = translate_apply ustate env inl mp empty_subst (sign, reso, cst) args in
306 let alg = List.fold_left (fun accu arg -> MEapply (accu, arg)) alg args in
307 (sign, alg, reso, cst, vm)
308 | MEwith(me, with_decl) ->
309 assert (Option.is_empty mpo); (* No 'with' syntax for modules *)
310 let mp = mp_from_mexpr me in
311 check_with_alg ustate vmstate env mp (translate_mse (cst, ustate) (vm, vmstate) env None inl me) with_decl
312
313 let mk_modtype = Mod_declarations.make_module_type
314
315 let rec translate_mse_funct (cst, ustate) (vm, vmstate) env ~is_mod mp inl mse = function
316 | [] ->
317 let sign,alg,reso,cst,vm = translate_mse (cst, ustate) (vm, vmstate) env (if is_mod then Some mp else None) inl mse in
318 let sign,reso =
319 if is_mod then sign,reso
320 else subst_modtype_signature_and_resolver (mp_from_mexpr mse) mp sign reso in
321 sign, MENoFunctor alg, reso, cst, vm
322 | (mbid, ty, ty_inl) :: params ->
323 let mp_id = MPbound mbid in
324 let mtb, cst, vm = translate_modtype (cst, ustate) (vm, vmstate) env mp_id ty_inl ([],ty) in
325 let env' = add_module_parameter mbid mtb env in
326 let sign,alg,reso,cst,vm = translate_mse_funct (cst, ustate) (vm, vmstate) env' ~is_mod mp inl mse params in
327 let alg' = MEMoreFunctor alg in
328 MoreFunctor (mbid, mtb, sign), alg',reso, cst, vm
329
330 and translate_modtype state vmstate env mp inl (params,mte) =
331 let sign,alg,reso,cst,vm = translate_mse_funct state vmstate env ~is_mod:false mp inl mte params in
332 let mtb = mk_modtype sign reso in
333 set_algebraic_type mtb alg, cst, vm
334
335 (** [finalize_module] :
336 from an already-translated (or interactive) implementation and
337 an (optional) signature entry, produces a final [module_body] *)
338
339 let finalize_module_alg (cst, ustate) (vm, vmstate) env mp (sign,alg,reso) restype = match restype with
340 | None ->
341 let impl = match alg with Some e -> Algebraic e | None -> FullStruct in
342 let mb = make_module_body sign reso [] in
343 let mb = set_implementation impl mb in
344 mb, cst, vm
345 | Some (params_mte,inl) ->
346 let res_mtb, cst, vm = translate_modtype (cst, ustate) (vm, vmstate) env mp inl params_mte in
347 let auto_mtb = Mod_declarations.make_module_body sign reso [] in
348 (* This function is supposed to be called in a state where the current module
349 is about to be closed, so all subcomponents of the module are already
350 part of the environment. We only need to add the toplevel module entry. *)
351 let env = Environ.shallow_add_module mp auto_mtb env in
352 let cst = Subtyping.check_subtypes (cst, ustate) env mp mp res_mtb in
353 let impl = match alg with
354 | Some e -> Algebraic e
355 | None ->
356 let sign = match sign with
357 | NoFunctor s -> s
358 | MoreFunctor _ -> assert false (* All non-algebraic callers enforce this *)
359 in
360 Struct (reso,sign)
361 in
362 let mb = module_body_of_type res_mtb in
363 let mb = set_implementation impl mb in
364 mb,
365 (** constraints from module body typing + subtyping + module type. *)
366 cst,
367 vm
368
369 let finalize_module univs vm env mp (sign, reso) typ =
370 finalize_module_alg univs vm env mp (sign, None, reso) typ
371
372 let translate_module (cst, ustate) (vm, vmstate) env mp inl = function
373 | MType (params,ty) ->
374 let mtb, cst, vm = translate_modtype (cst, ustate) (vm, vmstate) env mp inl (params,ty) in
375 module_body_of_type mtb, cst, vm
376 | MExpr (params,mse,oty) ->
377 let (sg,alg,reso,cst,vm) = translate_mse_funct (cst, ustate) (vm, vmstate) env ~is_mod:true mp inl mse params in
378 let restype = Option.map (fun ty -> ((params,ty),inl)) oty in
379 (* finalize_module_alg expects the subcomponents to be part of the environment *)
380 let env = match sg with
381 | NoFunctor struc -> Modops.add_structure mp struc reso env
382 | MoreFunctor _ -> env
383 in
384 finalize_module_alg (cst, ustate) (vm, vmstate) env mp (sg,Some alg,reso) restype
385
386 (** We now forbid any Include of functors with restricted signatures.
387 Otherwise, we could end with the creation of undesired axioms
388 (see #3746). Note that restricted non-functorized modules are ok,
389 thanks to strengthening. *)
390
391 let rec unfunct = function
392 | MENoFunctor me -> me
393 | MEMoreFunctor me -> unfunct me
394
395 let rec forbid_incl_signed_functor env = function
396 | MEapply(fe,_) -> forbid_incl_signed_functor env fe
397 | MEwith _ -> assert false (* No 'with' syntax for modules *)
398 | MEident mp1 ->
399 let mb = lookup_module mp1 env in
400 match mod_type mb, mod_type_alg mb, Mod_declarations.mod_expr mb with
401 | MoreFunctor _, Some _, _ ->
402 (* functor + restricted signature = error *)
403 error_include_restricted_functor mp1
404 | MoreFunctor _, None, Algebraic me ->
405 (* functor, no signature yet, a definition which may be restricted *)
406 forbid_incl_signed_functor env (unfunct me)
407 | _ -> ()
408
409 let rec translate_mse_include_module (cst, ustate) (vm, vmstate) env mp inl = function
410 | MEident mp1 ->
411 let mb = strengthen_and_subst_module_body mp1 (lookup_module mp1 env) mp true in
412 let sign = clean_bounded_mod_expr (mod_type mb) in
413 sign, (), mod_delta mb, cst, vm
414 | MEapply _ as me ->
415 let fe, args = decompose_apply [] me in
416 let (sign, (), reso, cst, vm) = translate_mse_include_module (cst, ustate) (vm, vmstate) env mp inl fe in
417 let (sign, reso, cst) = translate_apply ustate env inl mp empty_subst (sign, reso, cst) args in
418 (sign, (), reso, cst, vm)
419 | MEwith _ -> assert false (* No 'with' syntax for modules *)
420
421 let translate_mse_include is_mod (cst, ustate) (vm, vmstate) env mp inl me =
422 if is_mod then
423 let () = forbid_incl_signed_functor env me in
424 translate_mse_include_module (cst, ustate) (vm, vmstate) env mp inl me
425 else
426 let mtb, cst, vm = translate_modtype (cst, ustate) (vm, vmstate) env mp inl ([],me) in
427 let sign = clean_bounded_mod_expr (mod_type mtb) in
428 sign, (), mod_delta mtb, cst, vm