Debian Codegraph @

kernel/indtypes.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 Term
15 open Constr
16 open Vars
17 open Declarations
18 open Declareops
19 open Inductive
20 open Environ
21 open Reduction
22 open Entries
23 open Context.Rel.Declaration
24
25 (* Terminology:
26 paramdecls (ou paramsctxt?)
27 args = params + realargs (called vargs when an array, largs when a list)
28 params = recparams + nonrecparams
29 nonrecargs = nonrecparams + realargs
30 env_ar = initial env + declaration of inductive types
31 env_ar_par = env_ar + declaration of parameters
32 nmr = ongoing computation of recursive parameters
33 *)
34
35 (* [weaker_noccur_between env n nvars t] (defined above), checks that
36 no de Bruijn indices between [n] and [n+nvars] occur in [t]. If
37 some such occurrences are found, then reduction is performed
38 (lazily for efficiency purposes) in order to determine whether
39 these occurrences are occurrences in the normal form. If the
40 occurrences are eliminated a witness reduct [Some t'] of [t] is
41 returned otherwise [None] is returned. *)
42 let weaker_noccur_between env x nvars t =
43 if noccur_between x nvars t then Some t
44 else
45 let t' = whd_all env t in
46 if noccur_between x nvars t' then Some t'
47 else None
48
49 (************************************************************************)
50 (* Various well-formedness check for inductive declarations *)
51
52 exception InductiveError = Type_errors.InductiveError
53
54 (************************************************************************)
55 (************************************************************************)
56 (* Positivity *)
57
58 type ill_formed_ind =
59 | LocalNonPos of int
60 | LocalNotEnoughArgs of int
61 | LocalNotConstructor of Constr.rel_context * int
62 | LocalNonPar of int * int * int
63
64 exception IllFormedInd of ill_formed_ind
65
66 (* [mind_extract_params mie] extracts the params from an inductive types
67 declaration, and checks that they are all present (and all the same)
68 for all the given types. *)
69
70 let mind_extract_params = decompose_prod_n_decls
71
72 let explain_ind_err id ntyp env nparamsctxt c err =
73 let open Type_errors in
74 let (_lparams,c') = mind_extract_params nparamsctxt c in
75 match err with
76 | LocalNonPos kt ->
77 raise (InductiveError (env, NonPos (c',mkRel (kt+nparamsctxt))))
78 | LocalNotEnoughArgs kt ->
79 raise (InductiveError
80 (env, NotEnoughArgs (c',mkRel (kt+nparamsctxt))))
81 | LocalNotConstructor (paramsctxt,nargs)->
82 let nparams = Context.Rel.nhyps paramsctxt in
83 raise (InductiveError
84 (env, NotConstructor (id,c',mkRel (ntyp+nparamsctxt),
85 nparams,nargs)))
86 | LocalNonPar (n,i,l) ->
87 raise (InductiveError
88 (env, NonPar (c',n,mkRel i,mkRel (l+nparamsctxt))))
89
90 let failwith_non_pos n ntypes c =
91 for k = n to n + ntypes - 1 do
92 if not (noccurn k c) then raise (IllFormedInd (LocalNonPos (k-n+1)))
93 done
94
95 let failwith_non_pos_vect n ntypes v =
96 Array.iter (failwith_non_pos n ntypes) v;
97 anomaly ~label:"failwith_non_pos_vect" (Pp.str "some k in [n;n+ntypes-1] should occur.")
98
99 let failwith_non_pos_list n ntypes l =
100 List.iter (failwith_non_pos n ntypes) l;
101 anomaly ~label:"failwith_non_pos_list" (Pp.str "some k in [n;n+ntypes-1] should occur.")
102
103 (* Check the inductive type is called with the expected parameters *)
104 (* [n] is the index of the last inductive type in [env] *)
105 let check_correct_par ~chkpos (env,n,ntypes,_) paramdecls ind_index args =
106 let nparams = Context.Rel.nhyps paramdecls in
107 let args = Array.of_list args in
108 if Array.length args < nparams then
109 raise (IllFormedInd (LocalNotEnoughArgs ind_index));
110 let (params,realargs) = Array.chop nparams args in
111 let nparamdecls = List.length paramdecls in
112 let rec check param_index paramdecl_index = function
113 | [] -> ()
114 | LocalDef _ :: paramdecls ->
115 check param_index (paramdecl_index+1) paramdecls
116 | _::paramdecls ->
117 match kind (whd_all env params.(param_index)) with
118 | Rel w when Int.equal w paramdecl_index ->
119 check (param_index-1) (paramdecl_index+1) paramdecls
120 | _ ->
121 let paramdecl_index_in_env = paramdecl_index-n+nparamdecls+1 in
122 let err =
123 LocalNonPar (param_index+1, paramdecl_index_in_env, ind_index) in
124 raise (IllFormedInd err)
125 in check (nparams-1) (n-nparamdecls) paramdecls;
126 if chkpos && not (Array.for_all (noccur_between n ntypes) realargs) then
127 failwith_non_pos_vect n ntypes realargs
128
129 (* Computes the maximum number of recursive parameters:
130 the first parameters which are constant in recursive arguments
131 [n] is the current depth, [nmr] is the maximum number of possible
132 recursive parameters *)
133
134 let compute_rec_par (env,n,_,_) paramsctxt nmr largs =
135 if Int.equal nmr 0 then 0 else
136 (* start from 0, params will be in reverse order *)
137 let (lpar,_) = List.chop nmr largs in
138 let rec find k index =
139 function
140 ([],_) -> nmr
141 | (_,[]) -> assert false (* |paramsctxt|>=nmr *)
142 | (lp, LocalDef _ :: paramsctxt) -> find k (index-1) (lp,paramsctxt)
143 | (p::lp,_::paramsctxt) ->
144 ( match kind (whd_all env p) with
145 | Rel w when Int.equal w index -> find (k+1) (index-1) (lp,paramsctxt)
146 | _ -> k)
147 in find 0 (n-1) (lpar,List.rev paramsctxt)
148
149 (* [env] is the typing environment
150 [n] is the dB of the last inductive type
151 [ntypes] is the number of inductive types in the definition
152 (i.e. range of inductives is [n; n+ntypes-1])
153 [lra] is the list of recursive tree of each variable
154 *)
155 let ienv_push_var (env, n, ntypes, lra) (x,a,ra) =
156 (push_rel (LocalAssum (x,a)) env, n+1, ntypes, (Norec,ra)::lra)
157
158 let ienv_push_inductive (env, n, ntypes, ra_env) ((mi,u),lrecparams) =
159 let auxntyp = 1 in
160 let specif = (lookup_mind_specif env mi, u) in
161 let ty = type_of_inductive specif in
162 let env' =
163 let r = Inductive.relevance_of_ind_body (snd (fst specif)) u in
164 let anon = Context.make_annot Anonymous r in
165 let decl = LocalAssum (anon, hnf_prod_applist env ty lrecparams) in
166 push_rel decl env in
167 let ra_env' =
168 (Mrec (RecArgInd mi),(Rtree.mk_rec_calls 1).(0)) ::
169 List.map (fun (r,t) -> (r,Rtree.lift 1 t)) ra_env in
170 (* New index of the inductive types *)
171 let newidx = n + auxntyp in
172 (env', newidx, ntypes, ra_env')
173
174 let rec ienv_decompose_prod (env,_,_,_ as ienv) n c =
175 if Int.equal n 0 then (ienv,c) else
176 let c' = whd_all env c in
177 match kind c' with
178 Prod(na,a,b) ->
179 let ienv' = ienv_push_var ienv (na,a,mk_norec) in
180 ienv_decompose_prod ienv' (n-1) b
181 | _ -> assert false
182
183 let array_min nmr a = if Int.equal nmr 0 then 0 else
184 Array.fold_left (fun k (nmri,_) -> min k nmri) nmr a
185
186 (** [check_positivity_one ienv paramsctxt (mind,i) nnonrecargs lcnames indlc]
187 checks the positivity of the [i]-th member of the mutually
188 inductive definition [mind]. It returns an [Rtree.t] which
189 represents the position of the recursive calls of inductive in [i]
190 for use by the guard condition (terms at these positions are
191 considered sub-terms) as well as the number of of non-uniform
192 arguments (used to generate induction schemes, so a priori less
193 relevant to the kernel).
194
195 If [chkpos] is [false] then positivity is assumed, and
196 [check_positivity_one] computes the subterms occurrences in a
197 best-effort fashion. *)
198 let check_positivity_one ~chkpos recursive (env,_,ntypes,_ as ienv) paramsctxt (mind,i as ind) nnonrecargs lcnames indlc =
199 let nparamsctxt = Context.Rel.length paramsctxt in
200 let nmr = Context.Rel.nhyps paramsctxt in
201 (** Positivity of one argument [c] of a constructor (i.e. the
202 constructor [cn] has a type of the shape [… -> c … -> P], where,
203 more generally, the arrows may be dependent). *)
204 let rec check_strict_positivity (env, n, ntypes, ra_env as ienv) nmr c =
205 let x,largs = decompose_app_list (whd_all env c) in
206 match kind x with
207 | Prod (na,b,d) ->
208 let () = assert (List.is_empty largs) in
209 (** If one of the inductives of the mutually inductive
210 block occurs in the left-hand side of a product, then
211 such an occurrence is a non-strictly-positive
212 recursive call. Occurrences in the right-hand side of
213 the product must be strictly positive.*)
214 (match weaker_noccur_between env n ntypes b with
215 | None when chkpos ->
216 failwith_non_pos_list n ntypes [b]
217 | None ->
218 check_strict_positivity (ienv_push_var ienv (na, b, mk_norec)) nmr d
219 | Some b ->
220 check_strict_positivity (ienv_push_var ienv (na, b, mk_norec)) nmr d)
221 | Rel k ->
222 (match List.nth_opt ra_env (k-1) with
223 | Some (ra,rarg) ->
224 let largs = List.map (whd_all env) largs in
225 let nmr1 =
226 (match ra with
227 (* Are we referring to the original block of mutual inductive types? *)
228 | Mrec (RecArgInd (mind',_)) ->
229 if Names.MutInd.CanOrd.equal mind mind'
230 then compute_rec_par ienv paramsctxt nmr largs
231 else nmr
232 | Norec | Mrec (RecArgPrim _) -> nmr)
233 in
234 (** The case where one of the inductives of the mutually
235 inductive block occurs as an argument of another is not
236 known to be safe. So Rocq rejects it. *)
237 if chkpos &&
238 not (List.for_all (noccur_between n ntypes) largs)
239 then failwith_non_pos_list n ntypes largs
240 else (nmr1,rarg)
241 | None -> (nmr,mk_norec))
242 | Ind ind_kn ->
243 (** If one of the inductives of the mutually inductive
244 block being defined appears in a parameter, then we
245 have a nested inductive type. The positivity is then
246 discharged to the [check_positivity_nested] function. *)
247 if List.for_all (noccur_between n ntypes) largs then (nmr,mk_norec)
248 else check_positivity_nested ienv nmr (ind_kn, largs)
249 | Const (c,_) when is_primitive_positive_container env c ->
250 if List.for_all (noccur_between n ntypes) largs then (nmr,mk_norec)
251 else check_positivity_nested_primitive ienv nmr (c, largs)
252 | _err ->
253 (** If an inductive of the mutually inductive block
254 appears in any other way, then the positivy check gives
255 up. *)
256 if not chkpos ||
257 (noccur_between n ntypes x &&
258 List.for_all (noccur_between n ntypes) largs)
259 then (nmr,mk_norec)
260 else failwith_non_pos_list n ntypes (x::largs)
261
262 (** [check_positivity_nested] handles the case of nested inductive
263 calls, that is, when an inductive types from the mutually
264 inductive block is called as an argument of an inductive types
265 (for the moment, this inductive type must be a previously
266 defined types, not one of the types of the mutually inductive
267 block being defined). *)
268 (* accesses to the environment are not factorised, but is it worth? *)
269 and check_positivity_nested (env,n,ntypes,_ra_env as ienv) nmr (((mind,_ as ind),u), largs) =
270 let (mib,mip) = lookup_mind_specif env ind in
271 let auxnrecpar = mib.mind_nparams_rec in
272 let auxnnonrecpar = mib.mind_nparams - auxnrecpar in
273 let (auxrecparams,auxnonrecargs) =
274 try List.chop auxnrecpar largs
275 with Failure _ -> raise (IllFormedInd (LocalNonPos n)) in
276
277 (** Inductives of the inductive block being defined are only
278 allowed to appear nested in the parameters of another inductive
279 type. Not in the proper indices. *)
280 if chkpos && not (List.for_all (noccur_between n ntypes) auxnonrecargs) then
281 failwith_non_pos_list n ntypes auxnonrecargs;
282 (* Nested mutual inductive types are not supported *)
283 let auxntyp = Declareops.mind_ntypes mib in
284 if not (Int.equal auxntyp 1) then raise (IllFormedInd (LocalNonPos n));
285 (* The nested inductive type with parameters removed *)
286 let auxlcvect = abstract_mind_lc auxntyp auxnrecpar mind mip.mind_nf_lc in
287 (* Extends the environment with a variable corresponding to
288 the inductive def *)
289 let (env',_,_,_ as ienv') = ienv_push_inductive ienv ((ind,u),auxrecparams) in
290 (* Parameters expressed in env' *)
291 let auxrecparams' = List.map (lift auxntyp) auxrecparams in
292 let irecargs_nmr =
293 (** Checks that the "nesting" inductive type is covariant in
294 the relevant parameters. In other words, that the
295 (nested) parameters which are instantiated with
296 inductives of the mutually inductive block occur
297 positively in the types of the nested constructors. *)
298 Array.map
299 (function c ->
300 let c' = hnf_prod_applist env' c auxrecparams' in
301 (* skip non-recursive parameters *)
302 let (ienv',c') = ienv_decompose_prod ienv' auxnnonrecpar c' in
303 check_constructors ienv' false nmr c')
304 auxlcvect
305 in
306 let irecargs = Array.map snd irecargs_nmr
307 and nmr' = array_min nmr irecargs_nmr
308 in
309 (nmr',(Rtree.mk_rec [|mk_paths (Mrec (RecArgInd ind)) irecargs|]).(0))
310
311 and check_positivity_nested_primitive (env,n,ntypes,ra_env) nmr (c, largs) =
312 (* We model the primitive type c X1 ... Xn as if it had one constructor
313 C : X1 -> ... -> Xn -> c X1 ... Xn
314 The subterm relation is defined for each primitive in `inductive.ml`. *)
315 let ra_env = List.map (fun (r,t) -> (r,Rtree.lift 1 t)) ra_env in
316 let ienv = (env,n,ntypes,ra_env) in
317 let nmr',recargs = List.fold_left_map (check_strict_positivity ienv) nmr largs in
318 (nmr', (Rtree.mk_rec [| mk_paths (Mrec (RecArgPrim c)) [| recargs |] |]).(0))
319
320 (** [check_constructors ienv check_head nmr c] checks the positivity
321 condition in the type [c] of a constructor (i.e. that recursive
322 calls to the inductives of the mutually inductive definition
323 appear strictly positively in each of the arguments of the
324 constructor, see also [check_strict_positivity]). If [check_head] is [true],
325 then the type of the fully applied constructor (the "head" of
326 the type [c]) is checked to be the right (properly applied)
327 inductive type. *)
328 and check_constructors ienv check_head nmr c =
329 let rec check_constr_rec (env,n,ntypes,_ra_env as ienv) nmr lrec c =
330 let x,largs = decompose_app_list (whd_all env c) in
331 match kind x with
332
333 | Prod (na,b,d) ->
334 let () = assert (List.is_empty largs) in
335 if not recursive && not (noccur_between n ntypes b) then
336 raise (InductiveError (env,Type_errors.BadEntry));
337 let nmr',recarg = check_strict_positivity ienv nmr b in
338 let ienv' = ienv_push_var ienv (na,b,mk_norec) in
339 check_constr_rec ienv' nmr' (recarg::lrec) d
340 | hd ->
341 let () =
342 if check_head then
343 begin match hd with
344 | Rel j when Int.equal j (n + ntypes - i - 1) ->
345 check_correct_par ~chkpos ienv paramsctxt (ntypes - i) largs
346 | _ -> raise (IllFormedInd (LocalNotConstructor(paramsctxt,nnonrecargs)))
347 end
348 else
349 if chkpos &&
350 not (List.for_all (noccur_between n ntypes) largs)
351 then failwith_non_pos_list n ntypes largs
352 in
353 (nmr, List.rev lrec)
354 in check_constr_rec ienv nmr [] c
355 in
356 let irecargs_nmr =
357 Array.map2
358 (fun id c ->
359 let _,rawc = mind_extract_params nparamsctxt c in
360 try
361 check_constructors ienv true nmr rawc
362 with IllFormedInd err ->
363 explain_ind_err id (ntypes-i) env nparamsctxt c err)
364 (Array.of_list lcnames) indlc
365 in
366 let irecargs = Array.map snd irecargs_nmr
367 and nmr' = array_min nmr irecargs_nmr
368 in (nmr', mk_paths (Mrec (RecArgInd ind)) irecargs)
369
370 (** [check_positivity ~chkpos kn env_ar paramsctxt inds] checks that the mutually
371 inductive block [inds] is strictly positive.
372
373 If [chkpos] is [false] then positivity is assumed, and
374 [check_positivity_one] computes the subterms occurrences in a
375 best-effort fashion. *)
376 let check_positivity ~chkpos kn names env_ar_par paramsctxt finite inds =
377 let ntypes = Array.length inds in
378 let recursive = finite != BiFinite in
379 if not recursive && Array.length inds <> 1 then raise (InductiveError (env_ar_par,Type_errors.BadEntry));
380 let rc = Array.mapi (fun j t -> (Mrec (RecArgInd (kn,j)),t)) (Rtree.mk_rec_calls ntypes) in
381 let ra_env_ar = Array.rev_to_list rc in
382 let nparamsctxt = Context.Rel.length paramsctxt in
383 let nmr = Context.Rel.nhyps paramsctxt in
384 let check_one i (_,lcnames) (nindices,lc) =
385 let ra_env_ar_par =
386 List.init nparamsctxt (fun _ -> (Norec,mk_norec)) @ ra_env_ar in
387 let ienv = (env_ar_par, 1+nparamsctxt, ntypes, ra_env_ar_par) in
388 check_positivity_one ~chkpos recursive ienv paramsctxt (kn,i) nindices lcnames lc
389 in
390 let irecargs_nmr = Array.map2_i check_one names inds in
391 let irecargs = Array.map snd irecargs_nmr
392 and nmr' = array_min nmr irecargs_nmr
393 in (nmr',Rtree.mk_rec irecargs)
394
395
396 (************************************************************************)
397 (************************************************************************)
398 (* Build the inductive packet *)
399
400 let fold_inductive_blocks f acc inds =
401 Array.fold_left (fun acc ((arity,lc),_,_) ->
402 f (Array.fold_left f acc lc) arity.IndTyping.user_arity)
403 acc inds
404
405 let used_section_variables env inds =
406 let fold l c = Id.Set.union (Environ.global_vars_set env c) l in
407 let ids = fold_inductive_blocks fold Id.Set.empty inds in
408 keep_hyps env ids
409
410 let rel_vect n m = Array.init m (fun i -> mkRel(n+m-i))
411
412 (** From a rel context describing the constructor arguments,
413 build an expansion function.
414 The term built is expecting to be substituted first by
415 a substitution of the form [params, x : ind params] *)
416 let compute_projections ind ~nparamargs ~nf_lc ~consnrealdecls =
417 let (ctx, _) = nf_lc.(0) in
418 let ctx, paramslet = List.chop consnrealdecls.(0) ctx in
419 (** We build a substitution smashing the lets in the record parameters so
420 that typechecking projections requires just a substitution and not
421 matching with a parameter context. *)
422 let paramsletsubst =
423 (* [Ind inst] is typed in context [params-wo-let] *)
424 let inst' = rel_vect 0 nparamargs in
425 (* {params-wo-let |- subst:params] *)
426 let subst = subst_of_rel_context_instance paramslet inst' in
427 (* {params-wo-let, x:Ind inst' |- subst':(params,x:Ind inst)] *)
428 let subst = (* For the record parameter: *)
429 mkRel 1 :: List.map (lift 1) subst in
430 subst
431 in
432 let projections decl (i, j, labs, rs, pbs, letsubst) =
433 match decl with
434 | LocalDef (_na,c,_t) ->
435 (* From [params, field1,..,fieldj |- c(params,field1,..,fieldj)]
436 to [params, x:I, field1,..,fieldj |- c(params,field1,..,fieldj)] *)
437 let c = liftn 1 j c in
438 (* From [params, x:I, field1,..,fieldj |- c(params,field1,..,fieldj)]
439 to [params-wo-let, x:I |- c(params,proj1 x,..,projj x)] *)
440 let c2 = substl letsubst c in
441 (* From [params-wo-let, x:I |- subst:(params, x:I, field1,..,fieldj)]
442 to [params-wo-let, x:I |- subst:(params, x:I, field1,..,fieldj+1)] *)
443 let letsubst = c2 :: letsubst in
444 (i, j+1, labs, rs, pbs, letsubst)
445 | LocalAssum (na,t) ->
446 match na.Context.binder_name with
447 | Name id ->
448 let r = na.Context.binder_relevance in
449 let kn = Projection.Repr.make ind ~proj_npars:nparamargs ~proj_arg:i id in
450 (* from [params, field1,..,fieldj |- t(params,field1,..,fieldj)]
451 to [params, x:I, field1,..,fieldj |- t(params,field1,..,fieldj] *)
452 let t = liftn 1 j t in
453 (* from [params, x:I, field1,..,fieldj |- t(params,field1,..,fieldj)]
454 to [params-wo-let, x:I |- t(params,proj1 x,..,projj x)] *)
455 let projty = substl letsubst t in
456 (* from [params, x:I, field1,..,fieldj |- t(field1,..,fieldj)]
457 to [params, x:I |- t(proj1 x,..,projj x)] *)
458 let fterm = mkProj (Projection.make kn false, r, mkRel 1) in
459 (i + 1, j + 1, id :: labs, r :: rs, projty :: pbs, fterm :: letsubst)
460 | Anonymous -> assert false (* checked by indTyping *)
461 in
462 let (_, _, labs, rs, pbs, _letsubst) =
463 List.fold_right projections ctx (0, 1, [], [], [], paramsletsubst)
464 in
465 Array.of_list (List.rev labs),
466 Array.of_list (List.rev rs),
467 Array.of_list (List.rev pbs)
468
469 let build_inductive env ~sec_univs names prv univs template variance
470 paramsctxt kn isrecord isfinite inds nmr recargs not_prim_or_has_eta =
471 let ntypes = Array.length inds in
472 (* Compute the set of used section variables *)
473 let hyps = used_section_variables env inds in
474 let nparamargs = Context.Rel.nhyps paramsctxt in
475 let u = UVars.make_abstract_instance (universes_context univs) in
476 let subst = List.init ntypes (fun i -> mkIndU ((kn, ntypes - i - 1), u)) in
477 (* Check one inductive *)
478 let build_one_packet i (id,cnames) ((arity,lc),(indices,splayed_lc),squashed) recarg =
479 let lc = Array.map (substl subst) lc in
480 (* Type of constructors in normal form *)
481 let nf_lc =
482 Array.map (fun (d, b) ->
483 decompose_prod_decls (substl subst (it_mkProd_or_LetIn b (d@paramsctxt))))
484 splayed_lc in
485 let consnrealdecls =
486 Array.map (fun (d,_) -> Context.Rel.length d)
487 splayed_lc in
488 let consnrealargs =
489 Array.map (fun (d,_) -> Context.Rel.nhyps d)
490 splayed_lc in
491 let mind_relevance = Sorts.relevance_of_sort arity.IndTyping.sort in
492 let mind_record = match isrecord with
493 | Some (Some rid) ->
494 (** The elimination criterion ensures that all projections can be defined. *)
495 let (projections, relevances, tys) = compute_projections (kn, i) ~nparamargs ~nf_lc ~consnrealdecls in
496 begin match not_prim_or_has_eta with
497 (* It must have eta information *)
498 | None | Some (Error _) -> assert false
499 | Some Ok has_eta ->
500 PrimRecord { id = rid.(i); projections; relevances; tys; has_eta }
501 end
502 | Some None -> FakeRecord
503 | None -> NotRecord
504 in
505 (* Assigning VM tags to constructors *)
506 let nconst, nblock = ref 0, ref 0 in
507 let transf arity =
508 if Int.equal arity 0 then
509 let p = (!nconst, 0) in
510 incr nconst; p
511 else
512 let p = (!nblock + 1, arity) in
513 incr nblock; p
514 (* les tag des constructeur constant commence a 0,
515 les tag des constructeur non constant a 1 (0 => accumulator) *)
516 in
517 let rtbl = Array.map transf consnrealargs in
518 (* Build the inductive packet *)
519 { mind_typename = id;
520 mind_record;
521 mind_user_arity = arity.IndTyping.user_arity;
522 mind_sort = arity.IndTyping.sort;
523 mind_arity_ctxt = indices @ paramsctxt;
524 mind_nrealargs = Context.Rel.nhyps indices;
525 mind_nrealdecls = Context.Rel.length indices;
526 mind_squashed = squashed;
527 mind_consnames = Array.of_list cnames;
528 mind_consnrealdecls = consnrealdecls;
529 mind_consnrealargs = consnrealargs;
530 mind_user_lc = lc;
531 mind_nf_lc = nf_lc;
532 mind_recargs = recarg;
533 mind_relevance;
534 mind_nb_constant = !nconst;
535 mind_nb_args = !nblock;
536 mind_reloc_tbl = rtbl;
537 } in
538 let packets = Array.map3_i build_one_packet names inds recargs in
539 let variance, sec_variance = match variance with
540 | None -> None, None
541 | Some variance -> match sec_univs with
542 | None -> Some variance, None
543 | Some sec_univs ->
544 (* no variance for qualities *)
545 let _nsecq, nsecu = UVars.Instance.length sec_univs in
546 Some (Array.sub variance nsecu (Array.length variance - nsecu)),
547 Some (Array.sub variance 0 nsecu)
548 in
549 let univ_hyps = match sec_univs with
550 | None -> UVars.Instance.empty
551 | Some univs -> univs
552 in
553 (* Build the mutual inductive *)
554 { mind_finite = isfinite;
555 mind_hyps = hyps;
556 mind_univ_hyps = univ_hyps;
557 mind_nparams = nparamargs;
558 mind_nparams_rec = nmr;
559 mind_params_ctxt = paramsctxt;
560 mind_packets = packets;
561 mind_universes = univs;
562 mind_template = template;
563 mind_variance = variance;
564 mind_sec_variance = sec_variance;
565 mind_private = prv;
566 mind_typing_flags = Environ.typing_flags env;
567 }
568
569 (************************************************************************)
570 (************************************************************************)
571
572 let check_inductive env ~sec_univs kn mie =
573 (* First type-check the inductive definition *)
574 let (env_ar_par, univs, template, variance, record, not_prim_reason_or_has_eta, paramsctxt, inds) =
575 IndTyping.typecheck_inductive env ~sec_univs mie
576 in
577 (* Then check positivity conditions *)
578 let chkpos = (Environ.typing_flags env).check_positive in
579 let names = Array.map_of_list (fun entry -> entry.mind_entry_typename, entry.mind_entry_consnames)
580 mie.mind_entry_inds
581 in
582 let (nmr,recargs) = check_positivity ~chkpos kn names
583 env_ar_par paramsctxt mie.mind_entry_finite
584 (Array.map (fun ((_,lc),(indices,_),_) -> Context.Rel.nhyps indices,lc) inds)
585 in
586 (* Build the inductive packets *)
587 let mib =
588 build_inductive env ~sec_univs names mie.mind_entry_private univs template variance
589 paramsctxt kn record mie.mind_entry_finite
590 inds nmr recargs not_prim_reason_or_has_eta
591 in
592 (* From this point onward, we only care if there is a reason why
593 the primitive projection was not possible *)
594 (* XXX: Why thread this result back and not just warn when getting the reason? *)
595 let why_not_prim_record = match not_prim_reason_or_has_eta with
596 | None | Some (Result.Ok _) -> None
597 | Some (Result.Error reason) -> Some reason
598 in
599 mib, why_not_prim_record