Debian Codegraph @

kernel/typeops.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 Names
14 open Univ
15 open Sorts
16 open Term
17 open Constr
18 open Context
19 open Vars
20 open Declarations
21 open Environ
22 open Conversion
23 open Inductive
24 open Type_errors
25
26 module RelDecl = Context.Rel.Declaration
27 module NamedDecl = Context.Named.Declaration
28
29 exception NotConvertible
30 exception NotConvertibleVect of int
31
32 let conv_leq env x y = default_conv CUMUL env x y
33
34 let conv_leq_vecti env v1 v2 =
35 Array.fold_left2_i
36 (fun i _ t1 t2 ->
37 match conv_leq env t1 t2 with
38 | Result.Ok () -> ()
39 | Result.Error () -> raise (NotConvertibleVect i))
40 ()
41 v1
42 v2
43
44 let check_pconstraints (qcst, ucst) env =
45 let check_quality (s1, s2) = Quality.equal s1 s2 in
46 if not (Environ.check_univ_constraints ucst env) then
47 error_unsatisfied_univ_constraints env ucst
48 else if not (UVars.QPairSet.for_all check_quality qcst) then
49 (* XXX a bit ad-hoc, this is only used for case well-formedness, we ought to
50 have a proper generic error. *)
51 raise Type_errors.(TypeError (env, IllFormedCaseParams))
52 else ()
53
54 let check_poly_constraints cst env =
55 if Environ.check_constraints cst env then ()
56 else error_unsatisfied_poly_constraints env cst
57
58 (* This should be a type (a priori without intention to be an assumption) *)
59 let check_type env c t =
60 match kind(Reduction.whd_all env t) with
61 | Sort s -> s
62 | _ -> error_not_type env (make_judge c t)
63
64 (* This should be a type intended to be assumed. The error message is
65 not as useful as for [type_judgment]. *)
66 let infer_assumption env t ty =
67 try
68 let s = check_type env t ty in
69 Sorts.relevance_of_sort s
70 with TypeError _ ->
71 error_assumption env (make_judge t ty)
72
73 let nf_relevance env = function
74 | Sorts.RelevanceVar q as r ->
75 if Environ.Internal.is_above_prop env q ||
76 Inductive.eliminates_to (Environ.qualities env) (Sorts.Quality.QVar q) Sorts.Quality.qprop
77 then Sorts.Relevant
78 else if Inductive.eliminates_to (Environ.qualities env) Sorts.Quality.qsprop (Sorts.Quality.QVar q)
79 then Sorts.Irrelevant
80 else r
81 | (Sorts.Irrelevant | Sorts.Relevant) as r -> r
82
83 let check_relevance env r r' =
84 Sorts.relevance_equal (nf_relevance env r) (nf_relevance env r')
85
86 let check_assumption env x t ty =
87 let r = x.binder_relevance in
88 let r' = infer_assumption env t ty in
89 if check_relevance env r r' then ()
90 else
91 error_bad_binder_relevance env r' (RelDecl.LocalAssum (x, t))
92
93 let check_binding_relevance env na1 na2 =
94 (* Since we know statically the relevance here, we are stricter *)
95 assert (check_relevance env (binder_relevance na1) (binder_relevance na2))
96
97 let esubst u s c =
98 Vars.esubst Vars.lift_substituend s (subst_instance_constr u c)
99
100 exception ArgumentsMismatch
101
102 let instantiate_context env u subst nas ctx =
103 let open Context.Rel.Declaration in
104 let instantiate_relevance na =
105 { na with binder_relevance = UVars.subst_instance_relevance u na.binder_relevance }
106 in
107 let rec instantiate i ctx = match ctx with
108 | [] -> if 0 <= i then raise ArgumentsMismatch else []
109 | LocalAssum (na, ty) :: ctx ->
110 let ctx = instantiate (pred i) ctx in
111 let subst = Esubst.subs_liftn i subst in
112 let na = instantiate_relevance na in
113 let ty = esubst u subst ty in
114 let () = check_binding_relevance env na nas.(i) in
115 LocalAssum (nas.(i), ty) :: ctx
116 | LocalDef (na, ty, bdy) :: ctx ->
117 let ctx = instantiate (pred i) ctx in
118 let subst = Esubst.subs_liftn i subst in
119 let na = instantiate_relevance na in
120 let ty = esubst u subst ty in
121 let bdy = esubst u subst bdy in
122 let () = check_binding_relevance env na nas.(i) in
123 LocalDef (nas.(i), ty, bdy) :: ctx
124 in
125 instantiate (Array.length nas - 1) ctx
126
127 let check_constant env cst =
128 let _, _, can = Environ.lookup_constant_key cst env in
129 if not (KerName.equal can (Constant.canonical cst)) then error_ill_formed_constant env cst can
130
131 let check_mind env mind =
132 let _, _, can = Environ.lookup_mind_key mind env in
133 if not (KerName.equal can (MutInd.canonical mind)) then error_ill_formed_inductive env mind can
134
135 (************************************************)
136 (* Incremental typing rules: builds a typing judgment given the *)
137 (* judgments for the subterms. *)
138
139 (*s Type of sorts *)
140
141 (* Prop and Set *)
142
143 let type1 = mkSort Sorts.type1
144
145 (* Type of Type(i). *)
146
147 let type_of_type u =
148 let uu = Universe.super u in
149 mkType uu
150
151 let type_of_sort = function
152 | SProp | Prop | Set -> type1
153 | Type u -> type_of_type u
154 | QSort (_, u) -> type_of_type u
155
156 (*s Type of a de Bruijn index. *)
157
158 let type_of_relative env n =
159 try
160 env |> lookup_rel n |> RelDecl.get_type |> lift n
161 with Not_found ->
162 error_unbound_rel env n
163
164 (* Type of variables *)
165 let type_of_variable env id =
166 try named_type id env
167 with Not_found ->
168 error_unbound_var env id
169
170 (* Management of context of variables. *)
171
172 (* Checks if a context of variables can be instantiated by the
173 variables of the current env.
174 Order does not have to be checked assuming that all names are distinct *)
175 let check_hyps_inclusion env ?evars c sign =
176 let conv env a b = conv env ?evars a b in
177 Context.Named.fold_outside
178 (fun d1 () ->
179 let open Context.Named.Declaration in
180 let id = NamedDecl.get_id d1 in
181 try
182 let d2 = lookup_named id env in
183 let () = match conv env (get_type d2) (get_type d1) with
184 | Result.Ok () -> ()
185 | Result.Error () -> raise NotConvertible
186 in
187 (match d2,d1 with
188 | LocalAssum _, LocalAssum _ -> ()
189 | LocalAssum _, LocalDef _ ->
190 (* This is wrong, because we don't know if the body is
191 needed or not for typechecking: *) ()
192 | LocalDef _, LocalAssum _ -> raise NotConvertible
193 | LocalDef (_,b2,_), LocalDef (_,b1,_) ->
194 match conv env b2 b1 with
195 | Result.Ok () -> ()
196 | Result.Error () -> raise NotConvertible);
197 with Not_found | NotConvertible | Option.Heterogeneous ->
198 error_reference_variables env id c)
199 sign
200 ~init:()
201
202 (* Instantiation of terms on real arguments. *)
203
204 (* Make a type polymorphic if an arity *)
205
206 (* Type of constants *)
207
208 let type_of_constant env (kn,_u as cst) =
209 let () = check_constant env kn in
210 let cb = lookup_constant kn env in
211 let () = check_hyps_inclusion env (GlobRef.ConstRef kn) cb.const_hyps in
212 let ty, cu = constant_type env cst in
213 let () = check_poly_constraints cu env in
214 ty
215
216 let type_of_constant_in env (kn,_u as cst) =
217 let () = check_constant env kn in
218 let cb = lookup_constant kn env in
219 let () = check_hyps_inclusion env (GlobRef.ConstRef kn) cb.const_hyps in
220 constant_type_in env cst
221
222 (* Type of a lambda-abstraction. *)
223
224 (* [judge_of_abstraction env name var j] implements the rule
225
226 env, name:typ |- j.uj_val:j.uj_type env, |- (name:typ)j.uj_type : s
227 -----------------------------------------------------------------------
228 env |- [name:typ]j.uj_val : (name:typ)j.uj_type
229
230 Since all products are defined in the Calculus of Inductive Constructions
231 and no upper constraint exists on the sort $s$, we don't need to compute $s$
232 *)
233
234 let type_of_abstraction _env name var ty =
235 mkProd (name, var, ty)
236
237 (* Type of an application. *)
238
239 let make_judgev c t =
240 Array.map2 make_judge c t
241
242 let rec check_empty_stack = function
243 | [] -> true
244 | CClosure.Zupdate _ :: s -> check_empty_stack s
245 | _ -> false
246
247 let type_of_apply env func funt argsv argstv =
248 let open CClosure in
249 let len = Array.length argsv in
250 let infos = create_clos_infos RedFlags.all env in
251 let tab = create_tab () in
252 let rec apply_rec i typ =
253 if Int.equal i len then term_of_fconstr typ
254 else
255 let typ, stk = whd_stack infos tab typ [] in
256 match fterm_of typ with
257 | FProd (_, c1, c2, e) ->
258 (** The return stack is known to be empty *)
259 let () = assert (check_empty_stack stk) in
260 let arg = argsv.(i) in
261 let argt = argstv.(i) in
262 let c1 = term_of_fconstr c1 in
263 begin match conv_leq env argt c1 with
264 | Result.Ok () -> apply_rec (i+1) (mk_clos (CClosure.usubs_cons (inject arg) e) c2)
265 | Result.Error () ->
266 error_cant_apply_bad_type env
267 (i+1,c1,argt)
268 (make_judge func funt)
269 (make_judgev argsv argstv)
270 end
271 | _ ->
272 error_cant_apply_not_functional env
273 (make_judge func funt)
274 (make_judgev argsv argstv)
275 in
276 apply_rec 0 (inject funt)
277
278 (* Checks that an array of terms has the type of a telescope. We assume that all
279 inputs are well-typed separately. *)
280 let type_of_parameters env ctx u argsv argstv =
281 let open Context.Rel.Declaration in
282 let ctx = List.rev ctx in
283 let rec apply_rec i subst ctx = match ctx with
284 | [] -> if Int.equal i (Array.length argsv) then subst else raise ArgumentsMismatch
285 | LocalAssum (_, t) :: ctx ->
286 let arg = argsv.(i) in
287 let argt = argstv.(i) in
288 let t = esubst u subst t in
289 begin match conv_leq env argt t with
290 | Result.Ok () -> apply_rec (i + 1) (Esubst.subs_cons (Vars.make_substituend arg) subst) ctx
291 | Result.Error () ->
292 error_actual_type env (make_judge arg argt) t
293 end
294 | LocalDef (_, b, _) :: ctx ->
295 let b = esubst u subst b in
296 apply_rec i (Esubst.subs_cons (Vars.make_substituend b) subst) ctx
297 in
298 apply_rec 0 (Esubst.subs_id 0) ctx
299
300 (* Type of primitive constructs *)
301 let type_of_prim_type _env u (type a) (prim : a CPrimitives.prim_type) = match prim with
302 | CPrimitives.PT_int63 ->
303 assert (UVars.Instance.is_empty u);
304 Constr.mkSet
305 | CPrimitives.PT_float64 ->
306 assert (UVars.Instance.is_empty u);
307 Constr.mkSet
308 | CPrimitives.PT_string ->
309 assert (UVars.Instance.is_empty u);
310 Constr.mkSet
311 | CPrimitives.PT_array ->
312 begin match UVars.Instance.to_array u with
313 | [||], [|u|] ->
314 let ty = Constr.mkType (Univ.Universe.make u) in
315 Constr.mkProd(Context.anonR, ty , ty)
316 | _ -> anomaly Pp.(str"universe instance for array type should have length 1")
317 end
318
319 let type_of_int env =
320 match (Environ.retroknowledge env).Retroknowledge.retro_int63 with
321 | Some c -> UnsafeMonomorphic.mkConst c
322 | None -> CErrors.user_err Pp.(str"The type int must be registered before this construction can be typechecked.")
323
324 let type_of_float env =
325 match (Environ.retroknowledge env).Retroknowledge.retro_float64 with
326 | Some c -> UnsafeMonomorphic.mkConst c
327 | None -> CErrors.user_err Pp.(str"The type float must be registered before this construction can be typechecked.")
328
329 let type_of_string env =
330 match (Environ.retroknowledge env).Retroknowledge.retro_string with
331 | Some c -> UnsafeMonomorphic.mkConst c
332 | None -> CErrors.user_err Pp.(str"The type string must be registered before this construction can be typechecked.")
333
334 let type_of_array env u =
335 assert (UVars.Instance.length u = (0,1));
336 match (Environ.retroknowledge env).Retroknowledge.retro_array with
337 | Some c -> mkConstU (c,u)
338 | None -> CErrors.user_err Pp.(str"The type array must be registered before this construction can be typechecked.")
339
340 (* Type of product *)
341
342 let sort_of_product env domsort rangsort =
343 match (domsort, rangsort) with
344 | (_, SProp) | (SProp, _) -> rangsort
345 (* Product rule (s,Prop,Prop) *)
346 | (_, Prop) -> rangsort
347 (* Product rule (Prop/Set,Set,Set) *)
348 | ((Prop | Set), Set) -> rangsort
349 (* Product rule (Type,Set,?) *)
350 | ((Type u1 | QSort (_, u1)), Set) ->
351 if is_impredicative_set env then
352 (* Rule is (Type,Set,Set) in the Set-impredicative calculus *)
353 rangsort
354 else
355 (* Rule is (Type_i,Set,Type_i) in the Set-predicative calculus *)
356 Sorts.sort_of_univ (Universe.sup Universe.type0 u1)
357 (* Product rule (Prop,Type_i,Type_i) *)
358 | (Set, Type u2) -> Sorts.sort_of_univ (Universe.sup Universe.type0 u2)
359 | (Set, QSort (q, u2)) ->
360 Sorts.qsort q (Universe.sup Universe.type0 u2)
361 (* Product rule (Prop,Type_i,Type_i) *)
362 | (Prop, (Type _ | QSort _)) -> rangsort
363 (* Product rule (Type_i,Type_i,Type_i) *)
364 | ((Type u1 | QSort (_, u1)), Type u2) -> Sorts.sort_of_univ (Universe.sup u1 u2)
365 | ((Type u1 | QSort (_, u1)), (QSort (q, u2))) ->
366 Sorts.qsort q (Universe.sup u1 u2)
367
368 (* [judge_of_product env name (typ1,s1) (typ2,s2)] implements the rule
369
370 env |- typ1:s1 env, name:typ1 |- typ2 : s2
371 -------------------------------------------------------------------------
372 s' >= (s1,s2), env |- (name:typ)j.uj_val : s'
373
374 where j.uj_type is convertible to a sort s2
375 *)
376 let type_of_product env _name s1 s2 =
377 let s = sort_of_product env s1 s2 in
378 mkSort s
379
380 (* Type of a type cast *)
381
382 (* [judge_of_cast env (c,typ1) (typ2,s)] implements the rule
383
384 env |- c:typ1 env |- typ2:s env |- typ1 <= typ2
385 ---------------------------------------------------------------------
386 env |- c:typ2
387 *)
388
389 let check_cast env c ct k expected_type =
390 let ans = match k with
391 | VMcast ->
392 Vconv.vm_conv CUMUL env ct expected_type
393 | DEFAULTcast ->
394 default_conv CUMUL env ct expected_type
395 | NATIVEcast ->
396 let sigma = Genlambda.empty_evars env in
397 Nativeconv.native_conv CUMUL sigma env ct expected_type
398 in
399 match ans with
400 | Result.Ok () -> ()
401 | Result.Error () ->
402 error_actual_type env (make_judge c ct) expected_type
403
404 (* Inductive types. *)
405
406 (* The type is parametric over the uniform parameters whose conclusion
407 is in Type; to enforce the internal constraints between the
408 parameters and the instances of Type occurring in the type of the
409 constructors, we use the level variables _statically_ assigned to
410 the conclusions of the parameters as mediators: e.g. if a parameter
411 has conclusion Type(alpha), static constraints of the form alpha<=v
412 exist between alpha and the Type's occurring in the constructor
413 types; when the parameters is finally instantiated by a term of
414 conclusion Type(u), then the constraints u<=alpha is computed in
415 the App case of execute; from this constraints, the expected
416 dynamic constraints of the form u<=v are enforced *)
417
418 let make_param_univs env indu spec args argtys =
419 Array.to_list @@ Array.mapi (fun i argt ~default ->
420 match (snd (Reduction.dest_arity env argt)) with
421 | SProp | exception Reduction.NotArity ->
422 Type_errors.error_cant_apply_bad_type env
423 (i+1, mkSort default, argt)
424 (make_judge (mkIndU indu) (Inductive.type_of_inductive (spec, snd indu)))
425 (make_judgev args argtys)
426 | Prop -> TemplateProp
427 | Set -> TemplateUniv Universe.type0
428 | Type u -> TemplateUniv u
429 | QSort (q,u) ->
430 assert (Environ.Internal.is_above_prop env q);
431 TemplateAboveProp (q,u))
432 argtys
433
434 let type_of_inductive_knowing_parameters env (ind,u as indu) args argst =
435 let () = check_mind env (fst ind) in
436 let (mib,_mip) as spec = lookup_mind_specif env ind in
437 let () = assert (Option.has_some mib.mind_template) in
438 let () = check_hyps_inclusion env (GlobRef.IndRef ind) mib.mind_hyps in
439 let param_univs = make_param_univs env indu spec args argst in
440 let t, cst = Inductive.type_of_inductive_knowing_parameters (spec,u) param_univs in
441 let () = check_poly_constraints cst env in
442 t
443
444 let type_of_inductive env (ind,u) =
445 let () = check_mind env (fst ind) in
446 let (mib,mip) = lookup_mind_specif env ind in
447 check_hyps_inclusion env (GlobRef.IndRef ind) mib.mind_hyps;
448 let t,cst = Inductive.constrained_type_of_inductive ((mib,mip),u) in
449 check_poly_constraints cst env;
450 t
451
452 (* Constructors. *)
453
454 let type_of_constructor_knowing_parameters env (c, u as cu) args argst =
455 let ind = inductive_of_constructor c in
456 let () = check_mind env (fst ind) in
457 let (mib, _ as spec) = lookup_mind_specif env ind in
458 let () = assert (Option.has_some mib.mind_template) in
459 let () = check_hyps_inclusion env (GlobRef.ConstructRef c) mib.mind_hyps in
460 let param_univs = make_param_univs env (ind, u) spec args argst in
461 let t, cst = Inductive.type_of_constructor_knowing_parameters cu spec param_univs in
462 let () = check_poly_constraints cst env in
463 t
464
465 let type_of_constructor env (c,_u as cu) =
466 let ind = inductive_of_constructor c in
467 let () = check_mind env (fst ind) in
468 let (mib, _ as specif) = lookup_mind_specif env ind in
469 let () = check_hyps_inclusion env (GlobRef.ConstructRef c) mib.mind_hyps in
470 let t,cst = constrained_type_of_constructor cu specif in
471 let () = check_poly_constraints cst env in
472 t
473
474 (* Case. *)
475
476 exception NotConvertibleBranch of int * rel_context * types * types
477
478 let check_branch_types env (_mib, mip) ci u pms c _ct lft (pctx, p) =
479 let open Context.Rel.Declaration in
480 let rec instantiate ctx args subst = match ctx, args with
481 | [], [] -> subst
482 | LocalAssum _ :: ctx, a :: args ->
483 let subst = Esubst.subs_cons (Vars.make_substituend a) subst in
484 instantiate ctx args subst
485 | LocalDef (_, a, _) :: ctx, args ->
486 let a = Vars.esubst Vars.lift_substituend subst a in
487 let subst = Esubst.subs_cons (Vars.make_substituend a) subst in
488 instantiate ctx args subst
489 | _ -> assert false
490 in
491 let iter i (brctx, brt, constrty) =
492 let brenv = push_rel_context brctx env in
493 let nargs = List.length brctx in
494 let pms = Array.map (fun c -> lift nargs c) pms in
495 let cargs = Context.Rel.instance mkRel 0 brctx in
496 let cstr = mkApp (mkConstructU ((ci.ci_ind, i + 1), u), Array.append pms cargs) in
497 let (_, retargs) = find_rectype brenv constrty in
498 let indices = List.lastn mip.mind_nrealargs retargs in
499 let subst = instantiate (List.rev pctx) (indices @ [cstr]) (Esubst.subs_shft (nargs, Esubst.subs_id 0)) in
500 let expbrt = Vars.esubst Vars.lift_substituend subst p in
501 match conv_leq brenv brt expbrt with
502 | Result.Ok () -> ()
503 | Result.Error () -> raise (NotConvertibleBranch (i, brctx, brt, expbrt))
504 in
505 try Array.iteri iter lft
506 with NotConvertibleBranch (i, brctx, brt, expbrt) ->
507 let brt = it_mkLambda_or_LetIn brt brctx in
508 let expbrt = it_mkLambda_or_LetIn expbrt brctx in
509 error_ill_formed_branch env c ((ci.ci_ind, i + 1), u) brt expbrt
510
511 let should_invert_case env r ci =
512 check_relevance env r Sorts.Relevant &&
513 let mib,mip = lookup_mind_specif env ci.ci_ind in
514 (* mind_relevance cannot be a pseudo sort poly variable so don't use check_relevance *)
515 Sorts.relevance_equal mip.mind_relevance Sorts.Irrelevant &&
516 (* NB: it's possible to have 2 ctors or arguments to 1 ctor by unsetting univ checks
517 but we don't do special reduction in such cases
518
519 XXX Someday consider more carefully what happens with letin params and arguments
520 (currently they're squashed, see indtyping)
521 *)
522 match Array.length mip.mind_nf_lc with
523 | 0 -> true
524 | 1 ->
525 List.length (fst mip.mind_nf_lc.(0)) = List.length mib.mind_params_ctxt
526 | _ -> false
527
528 let type_case_scrutinee env (mib, _mip) (u', largs) u pms (pctx, p) c =
529 let (params, realargs) = List.chop mib.mind_nparams largs in
530 (* Check that the type of the scrutinee is <= the expected argument type *)
531 let iter p1 p2 = match Conversion.conv ~l2r:true env p1 p2 with
532 | Result.Ok () -> ()
533 | Result.Error () -> raise NotConvertible
534 in
535 let () = try Array.iter2 iter (Array.of_list params) pms
536 with NotConvertible -> raise Type_errors.(TypeError (env,IllFormedCaseParams))
537 in
538 (* We use l2r:true for compat with old versions which used CONV with arguments
539 flipped. It is relevant for performance eg in bedrock / Kami. *)
540 let qcst, ucst = match mib.mind_variance with
541 | None -> UVars.enforce_eq_instances u u' (UVars.QPairSet.empty, Univ.UnivConstraints.empty)
542 | Some variance -> UVars.enforce_leq_variance_instances variance u' u (UVars.QPairSet.empty, Univ.UnivConstraints.empty)
543 in
544 let () = check_pconstraints (qcst, ucst) env in
545 let subst = Vars.subst_of_rel_context_instance_list pctx (realargs @ [c]) in
546 Vars.substl subst p
547
548 let type_of_case env (mib, mip as specif) ci u pms (pctx, pnas, p, rp, pt) iv c ct lf lft =
549 let ((ind, u'), largs) =
550 try find_rectype env ct
551 with Not_found -> error_case_not_inductive env (make_judge c ct) in
552 (* Various well-formedness conditions *)
553 let () = if Inductive.is_private specif then error_case_on_private_ind env ind in
554 let sp = match destSort (Reduction.whd_all (push_rel_context pctx env) pt) with
555 | sp -> sp
556 | exception DestKO ->
557 error_elim_arity env (ind, u') c None
558 in
559 let () =
560 let expected = Sorts.relevance_of_sort sp in
561 if check_relevance env rp expected then ()
562 else
563 error_bad_case_relevance env expected (ci, u, pms, ((pnas, p), rp), iv, c, lf)
564 in
565 let () = check_case_info env (ind, u') ci in
566 let () =
567 let is_inversion = match iv with
568 | NoInvert -> false
569 | CaseInvert _ -> true (* contents already checked *)
570 in
571 if not (is_inversion = should_invert_case env rp ci)
572 then error_bad_invert env
573 in
574 let () = if not (is_allowed_elimination env (specif,u) sp) then begin
575 let kinds = Some sp in
576 error_elim_arity env (ind, u') c kinds
577 end
578 in
579 (* Check that the scrutinee has the right type *)
580 let rslty = type_case_scrutinee env (mib, mip) (u', largs) u pms (pctx, p) c in
581 (* We return the "higher" inductive universe instance from the predicate,
582 the branches must be typeable using these universes. *)
583 let () = check_branch_types env (mib, mip) ci u pms c ct lft (pctx, p) in
584 rslty
585
586 let type_of_projection env p c ct =
587 let pr, pty = lookup_projection p env in
588 let (ind,u), args =
589 try find_rectype env ct
590 with Not_found -> error_case_not_inductive env (make_judge c ct)
591 in
592 let () =
593 if not (Environ.QInd.equal env (Projection.inductive p) ind) then
594 error_bad_proj_type env (make_judge c ct) p
595 in
596 let pr = UVars.subst_instance_relevance u pr in
597 let ty = Vars.subst_instance_constr u pty in
598 pr, substl (c :: CList.rev args) ty
599
600
601 (* Fixpoints. *)
602
603 (* Checks the type of a general (co)fixpoint, i.e. without checking *)
604 (* the specific guard condition. *)
605
606 let check_fixpoint env lna lar vdef vdeft =
607 let lt = Array.length vdeft in
608 assert (Int.equal (Array.length lar) lt);
609 try
610 conv_leq_vecti env vdeft (Array.map (fun ty -> lift lt ty) lar)
611 with NotConvertibleVect i ->
612 error_ill_typed_rec_body env i lna (make_judgev vdef vdeft) lar
613
614 (* Global references *)
615
616 let type_of_global_in_context env r =
617 let open Names.GlobRef in
618 match r with
619 | VarRef id -> Environ.named_type id env, UVars.AbstractContext.empty
620 | ConstRef c ->
621 let cb = Environ.lookup_constant c env in
622 let univs = Declareops.constant_polymorphic_context cb in
623 cb.Declarations.const_type, univs
624 | IndRef ind ->
625 let (mib,_ as specif) = Inductive.lookup_mind_specif env ind in
626 let univs = Declareops.inductive_polymorphic_context mib in
627 let inst = UVars.make_abstract_instance univs in
628 Inductive.type_of_inductive (specif, inst), univs
629 | ConstructRef cstr ->
630 let (mib,_ as specif) =
631 Inductive.lookup_mind_specif env (inductive_of_constructor cstr)
632 in
633 let univs = Declareops.inductive_polymorphic_context mib in
634 let inst = UVars.make_abstract_instance univs in
635 Inductive.type_of_constructor (cstr,inst) specif, univs
636
637 (************************************************************************)
638 (************************************************************************)
639
640 let check_assum_annot env s x t =
641 let r = x.binder_relevance in
642 let r' = Sorts.relevance_of_sort s in
643 if check_relevance env r' r
644 then ()
645 else error_bad_binder_relevance env r' (RelDecl.LocalAssum (x, t))
646
647
648 let check_let_annot env s x c t =
649 let r = x.binder_relevance in
650 let r' = Sorts.relevance_of_sort s in
651 if check_relevance env r' r
652 then ()
653 else error_bad_binder_relevance env r' (RelDecl.LocalDef (x, c, t))
654
655 let push_rec_types (lna,typarray,_) env =
656 let ctxt = Array.map2_i (fun i na t -> RelDecl.LocalAssum (na, lift i t)) lna typarray in
657 Array.fold_left (fun e assum -> push_rel assum e) env ctxt
658
659 (* The typing machine. *)
660 let rec execute tbl env cstr =
661 if Int.equal (HConstr.refcount cstr) 1 then execute_aux tbl env cstr
662 else begin match HConstr.Tbl.find_opt tbl cstr with
663 | Some v -> v
664 | None ->
665 let v = execute_aux tbl env cstr in
666 HConstr.Tbl.add tbl cstr v;
667 v
668 end
669
670 and execute_aux tbl env cstr =
671 let open Context.Rel.Declaration in
672 let self = HConstr.self in
673 match HConstr.kind cstr with
674 (* Atomic terms *)
675 | Sort s ->
676 let () = match s with
677 | SProp -> if not (Environ.sprop_allowed env) then error_not_allowed_sprop env
678 | QSort _ | Prop | Set | Type _ -> ()
679 in
680 type_of_sort s
681
682 | Rel n ->
683 type_of_relative env n
684
685 | Var id ->
686 type_of_variable env id
687
688 | Const c ->
689 type_of_constant env c
690
691 | Proj (p, r, c) ->
692 let ct = execute tbl env c in
693 let r', ty = type_of_projection env p (self c) ct in
694 assert (check_relevance env r r');
695 ty
696
697 (* Lambda calculus operators *)
698 | App (f,args) ->
699 let argst = execute_array tbl env args in
700 let args = snd @@ destApp (self cstr) in
701 let ft =
702 match HConstr.kind f with
703 | Ind ind when Environ.template_polymorphic_pind ind env ->
704 type_of_inductive_knowing_parameters env ind args argst
705 | Construct ((ind, _), _ as cstr) when Environ.template_polymorphic_ind ind env ->
706 type_of_constructor_knowing_parameters env cstr args argst
707 | _ ->
708 (* No template polymorphism *)
709 execute tbl env f
710 in
711 type_of_apply env (self f) ft args argst
712
713 | Lambda (name,c1,c2) ->
714 let s = execute_is_type tbl env c1 in
715 let () = check_assum_annot env s name (self c1) in
716 let env1 = push_rel (LocalAssum (name,self c1)) env in
717 let c2t = execute tbl env1 c2 in
718 type_of_abstraction env name (self c1) c2t
719
720 | Prod (name,c1,c2) ->
721 let vars = execute_is_type tbl env c1 in
722 let () = check_assum_annot env vars name (self c1) in
723 let env1 = push_rel (LocalAssum (name,self c1)) env in
724 let vars' = execute_is_type tbl env1 c2 in
725 type_of_product env name vars vars'
726
727 | LetIn (name,c1,c2,c3) ->
728 let c1t = execute tbl env c1 in
729 let c2s = execute_is_type tbl env c2 in
730 let c1 = self c1 in
731 let c2 = self c2 in
732 let () = check_let_annot env c2s name c1 c2 in
733 let () = check_cast env c1 c1t DEFAULTcast c2 in
734 let env1 = push_rel (LocalDef (name,c1,c2)) env in
735 let c3t = execute tbl env1 c3 in
736 subst1 c1 c3t
737
738 | Cast (c,k,t) ->
739 let ct = execute tbl env c in
740 let _ts : Sorts.t = execute_is_type tbl env t in
741 let () = check_cast env (self c) ct k (self t) in
742 self t
743
744 (* Inductive types *)
745 | Ind ind ->
746 type_of_inductive env ind
747
748 | Construct c ->
749 type_of_constructor env c
750
751 | Case (ci, u, pms, (p,_), iv, c, lf) ->
752 let ct = execute tbl env c in
753 let () = match iv with
754 | NoInvert -> ()
755 | CaseInvert {indices} ->
756 let args = Array.append pms indices in
757 let ct' =
758 let mk = HConstr.of_kind_nohashcons in
759 mk @@ App (mk @@ Ind (ci.ci_ind,u), args)
760 in
761 let _ : Sorts.t = execute_is_type tbl env ct' in
762 match conv_leq env ct (self ct') with
763 | Result.Ok () -> ()
764 | Result.Error () -> error_bad_invert env (* TODO: more informative message *)
765
766 in
767 let () = check_mind env (fst ci.ci_ind) in
768 let mib, mip = Inductive.lookup_mind_specif env ci.ci_ind in
769 let pmst = execute_array tbl env pms in
770 let pms = Array.map self pms in
771 let cst, params = match mib.mind_template with
772 | None ->
773 let cst = Inductive.instantiate_inductive_constraints mib u in
774 cst, mib.mind_params_ctxt
775 | Some _ ->
776 let args = make_param_univs env (ci.ci_ind, u) (mib, mip) pms pmst in
777 let (cst, params, _) = instantiate_template_universes mib args in
778 cst, params
779 in
780 let () = check_poly_constraints cst env in
781 let paramsubst =
782 try type_of_parameters env params u pms pmst
783 with ArgumentsMismatch -> error_elim_arity env (ci.ci_ind, u) (self c) None
784 in
785 let (pctx, pt) =
786 let (nas, p) = p in
787 let realdecls, _ = List.chop mip.mind_nrealdecls mip.mind_arity_ctxt in
788 let self =
789 let args = Context.Rel.instance mkRel 0 mip.mind_arity_ctxt in
790 let inst = UVars.Instance.(abstract_instance (length u)) in
791 mkApp (mkIndU (ci.ci_ind, inst), args)
792 in
793 let realdecls = LocalAssum (Context.make_annot Anonymous mip.mind_relevance, self) :: realdecls in
794 let realdecls =
795 try instantiate_context env u paramsubst nas realdecls
796 with ArgumentsMismatch -> error_elim_arity env (ci.ci_ind, u) (HConstr.self c) None
797 in
798 let p_env = Environ.push_rel_context realdecls env in
799 let pt = execute tbl p_env p in
800 (realdecls, pt)
801 in
802 let () =
803 let nbranches = Array.length mip.mind_nf_lc in
804 if not (Int.equal (Array.length lf) nbranches) then
805 error_number_branches env (make_judge (self c) ct) nbranches
806 in
807 let build_one_branch i (nas, br) =
808 let (ctx, cty) = mip.mind_nf_lc.(i) in
809 let ctx, _ = List.chop mip.mind_consnrealdecls.(i) ctx in
810 let ctx =
811 try instantiate_context env u paramsubst nas ctx
812 with ArgumentsMismatch ->
813 (* Despite the name, the toplevel message is reasonable *)
814 error_elim_arity env (ci.ci_ind, u) (self c) None
815 in
816 let br_env = Environ.push_rel_context ctx env in
817 let brt = execute tbl br_env br in
818 let cty = esubst u (Esubst.subs_liftn mip.mind_consnrealdecls.(i) paramsubst) cty in
819 (ctx, brt, cty)
820 in
821 let lft = Array.mapi build_one_branch lf in
822 (* easier than mapping self over various shapes of arrays *)
823 let (ci, u, pms, (p,rp), iv, c, lf) = destCase (self cstr) in
824 type_of_case env (mib, mip) ci u pms (pctx, fst p, snd p, rp, pt) iv c ct lf lft
825
826 | Fix ((_,i),recdef) ->
827 let fix_ty = execute_recdef tbl env recdef i in
828 check_fix env (destFix @@ self cstr);
829 fix_ty
830
831 | CoFix (i,recdef) ->
832 let fix_ty = execute_recdef tbl env recdef i in
833 check_cofix env (destCoFix @@ self cstr);
834 fix_ty
835
836 (* Primitive types *)
837 | Int _ -> type_of_int env
838 | Float _ -> type_of_float env
839 | String _ -> type_of_string env
840 | Array(u,t,def,ty) ->
841 (* ty : Type@{u} and all of t,def : ty *)
842 let ulev = match UVars.Instance.to_array u with
843 | [||], [|u|] -> u
844 | _ -> assert false
845 in
846 let tyty = execute tbl env ty in
847 let ty = self ty in
848 check_cast env ty tyty DEFAULTcast (mkType (Universe.make ulev));
849 let def_ty = execute tbl env def in
850 check_cast env (self def) def_ty DEFAULTcast ty;
851 let ta = type_of_array env u in
852 let () = Array.iter (fun x ->
853 let xt = execute tbl env x in
854 check_cast env (self x) xt DEFAULTcast ty)
855 t
856 in
857 mkApp(ta, [|ty|])
858
859 (* Partial proofs: unsupported by the kernel *)
860 | Meta _ ->
861 anomaly (Pp.str "the kernel does not support metavariables.")
862
863 | Evar _ ->
864 anomaly (Pp.str "the kernel does not support existential variables.")
865
866 and execute_is_type tbl env constr =
867 let t = execute tbl env constr in
868 check_type env (HConstr.self constr) t
869
870 and execute_recdef tbl env (names,lar,vdef) i =
871 let lart = execute_array tbl env lar in
872 let lar = Array.map HConstr.self lar in
873 let () = Array.iteri (fun i na -> check_assumption env na lar.(i) lart.(i)) names in
874 let env1 = push_rec_types (names,lar,vdef) env in (* vdef is ignored *)
875 let vdeft = execute_array tbl env1 vdef in
876 let vdef = Array.map HConstr.self vdef in
877 let () = check_fixpoint env1 names lar vdef vdeft in
878 lar.(i)
879
880 and execute_array tbl env cs =
881 Array.map (fun c -> execute tbl env c) cs
882
883 let execute env c =
884 NewProfile.profile "Typeops.execute" (fun () -> execute (HConstr.Tbl.create ()) env c) ()
885
886 (* Derived functions *)
887
888 let check_declared_qualities env qualities =
889 let module S = Sorts.QVar.Set in
890 let unknown = S.diff qualities (Environ.qvars env) in
891 if S.is_empty unknown then ()
892 else error_undeclared_qualities env unknown
893
894 let check_wellformed_universes env c =
895 let qualities, univs = sort_and_universes_of_constr c in
896 check_declared_qualities env qualities;
897 match UGraph.check_declared_universes (universes env) univs
898 with
899 | Ok () -> ()
900 | Error u -> error_undeclared_universes env u
901
902 let check_wellformed_universes env c =
903 NewProfile.profile "check-wf-univs" (fun () -> check_wellformed_universes env c) ()
904
905 let infer_hconstr env hconstr =
906 let constr = HConstr.self hconstr in
907 let () = check_wellformed_universes env constr in
908 let t = execute env hconstr in
909 make_judge constr t
910
911 let infer env c =
912 let c = HConstr.of_constr env c in
913 infer_hconstr env c
914
915 let assumption_of_judgment env {uj_val=c; uj_type=t} =
916 infer_assumption env c t
917
918 let infer_type env constr =
919 let () = check_wellformed_universes env constr in
920 let hconstr = HConstr.of_constr env constr in
921 let constr = HConstr.self hconstr in
922 let t = execute env hconstr in
923 let s = check_type env constr t in
924 {utj_val = constr; utj_type = s}
925
926 (* Typing of several terms. *)
927
928 let check_context env rels =
929 let open Context.Rel.Declaration in
930 Context.Rel.fold_outside (fun d (env,rels) ->
931 match d with
932 | LocalAssum (x,ty) ->
933 let jty = infer_type env ty in
934 let () = check_assum_annot env jty.utj_type x jty.utj_val in
935 push_rel d env, LocalAssum (x,jty.utj_val) :: rels
936 | LocalDef (x,bd,ty) ->
937 let j1 = infer env bd in
938 let jty = infer_type env ty in
939 let () = match conv_leq env j1.uj_type ty with
940 | Result.Ok () -> ()
941 | Result.Error () -> error_actual_type env j1 ty
942 in
943 let () = check_let_annot env jty.utj_type x j1.uj_val jty.utj_val in
944 push_rel d env, LocalDef (x,j1.uj_val,jty.utj_val) :: rels)
945 rels ~init:(env,[])
946
947 let check_cast env cj k tj =
948 check_cast env cj.uj_val cj.uj_type k tj.utj_val
949
950 (* Building type of primitive operators and type *)
951
952 let type_of_prim_const env _u c =
953 let int_ty () = type_of_int env in
954 match c with
955 | CPrimitives.Arraymaxlength ->
956 int_ty ()
957 | CPrimitives.Stringmaxlength ->
958 int_ty ()
959
960 let type_of_prim env u t =
961 let module UM = UnsafeMonomorphic in
962 let int_ty () = type_of_int env in
963 let float_ty () = type_of_float env in
964 let string_ty () = type_of_string env in
965 let array_ty u a = mkApp(type_of_array env u, [|a|]) in
966 let bool_ty () =
967 match (Environ.retroknowledge env).Retroknowledge.retro_bool with
968 | Some ((ind,_),_) -> UM.mkInd ind
969 | None -> CErrors.user_err Pp.(str"The type bool must be registered before this primitive.")
970 in
971 let compare_ty () =
972 match (Environ.retroknowledge env).Retroknowledge.retro_cmp with
973 | Some ((ind,_),_,_) -> UM.mkInd ind
974 | None -> CErrors.user_err Pp.(str"The type compare must be registered before this primitive.")
975 in
976 let f_compare_ty () =
977 match (Environ.retroknowledge env).Retroknowledge.retro_f_cmp with
978 | Some ((ind,_),_,_,_) -> UM.mkInd ind
979 | None -> CErrors.user_err Pp.(str"The type float_comparison must be registered before this primitive.")
980 in
981 let f_class_ty () =
982 match (Environ.retroknowledge env).Retroknowledge.retro_f_class with
983 | Some ((ind,_),_,_,_,_,_,_,_,_) -> UM.mkInd ind
984 | None -> CErrors.user_err Pp.(str"The type float_class must be registered before this primitive.")
985 in
986 let pair_ty fst_ty snd_ty =
987 match (Environ.retroknowledge env).Retroknowledge.retro_pair with
988 | Some (ind,_) -> Constr.mkApp(UM.mkInd ind, [|fst_ty;snd_ty|])
989 | None -> CErrors.user_err Pp.(str"The type pair must be registered before this primitive.")
990 in
991 let carry_ty int_ty =
992 match (Environ.retroknowledge env).Retroknowledge.retro_carry with
993 | Some ((ind,_),_) -> Constr.mkApp(UM.mkInd ind, [|int_ty|])
994 | None -> CErrors.user_err Pp.(str"The type carry must be registered before this primitive.")
995 in
996 let open CPrimitives in
997 let tr_prim_type (tr_type : ind_or_type -> constr) (type a) (ty : a prim_type) (t : a) = match ty with
998 | PT_int63 -> int_ty t
999 | PT_float64 -> float_ty t
1000 | PT_string -> string_ty t
1001 | PT_array -> array_ty (fst t) (tr_type (snd t))
1002 in
1003 let tr_ind (tr_type : ind_or_type -> constr) (type t) (i : t prim_ind) (a : t) = match i, a with
1004 | PIT_bool, () -> bool_ty ()
1005 | PIT_carry, t -> carry_ty (tr_type t)
1006 | PIT_pair, (t1, t2) -> pair_ty (tr_type t1) (tr_type t2)
1007 | PIT_cmp, () -> compare_ty ()
1008 | PIT_f_cmp, () -> f_compare_ty ()
1009 | PIT_f_class, () -> f_class_ty ()
1010 in
1011 let rec tr_type n = function
1012 | PITT_ind (i, a) -> tr_ind (tr_type n) i a
1013 | PITT_type (ty,t) -> tr_prim_type (tr_type n) ty t
1014 | PITT_param i -> Constr.mkRel (n+i)
1015 in
1016 let rec nary_op n ret_ty = function
1017 | [] -> tr_type n ret_ty
1018 | arg_ty :: r ->
1019 Constr.mkProd (Context.nameR (Id.of_string "x"),
1020 tr_type n arg_ty, nary_op (n + 1) ret_ty r)
1021 in
1022 let params, args_ty, ret_ty = types t in
1023 assert (UVars.AbstractContext.size (univs t) = UVars.Instance.length u);
1024 Vars.subst_instance_constr u
1025 (Term.it_mkProd_or_LetIn (nary_op 0 ret_ty args_ty) params)
1026
1027 let type_of_prim_or_type env u = let open CPrimitives in
1028 function
1029 | OT_type t -> type_of_prim_type env u t
1030 | OT_op op -> type_of_prim env u op
1031 | OT_const c -> type_of_prim_const env u c