Debian Codegraph @

pretyping/inductiveops.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 EConstr
15 open Vars
16 open Context
17 open Declarations
18 open Declareops
19 open Environ
20 open Reductionops
21 open Context.Rel.Declaration
22
23 (* The following three functions are similar to the ones defined in
24 Inductive, but they expect an env *)
25
26 let type_of_inductive env (ind,u) =
27 let u = EConstr.Unsafe.to_instance u in
28 let (mib,_ as specif) = Inductive.lookup_mind_specif env ind in
29 Typeops.check_hyps_inclusion env (GlobRef.IndRef ind) mib.mind_hyps;
30 let t = Inductive.type_of_inductive (specif,u) in
31 EConstr.of_constr @@ Arguments_renaming.rename_type env t (IndRef ind)
32
33 let e_type_of_inductive env sigma (ind,u) =
34 let (mib,_ as specif) = Inductive.lookup_mind_specif env ind in
35 Reductionops.check_hyps_inclusion env sigma (GlobRef.IndRef ind) mib.mind_hyps;
36 let t = Inductive.type_of_inductive (specif, EConstr.Unsafe.to_instance u) in
37 EConstr.of_constr (Arguments_renaming.rename_type env t (IndRef ind))
38
39 (* Return type as quoted by the user *)
40 let type_of_constructor env (cstr,u) =
41 let u = EConstr.Unsafe.to_instance u in
42 let (mib,_ as specif) =
43 Inductive.lookup_mind_specif env (inductive_of_constructor cstr) in
44 Typeops.check_hyps_inclusion env (GlobRef.ConstructRef cstr) mib.mind_hyps;
45 let t = Inductive.type_of_constructor (cstr,u) specif in
46 EConstr.of_constr @@ Arguments_renaming.rename_type env t (ConstructRef cstr)
47
48 let e_type_of_constructor env sigma (cstr,u) =
49 let (mib,_ as specif) =
50 Inductive.lookup_mind_specif env (inductive_of_constructor cstr) in
51 Reductionops.check_hyps_inclusion env sigma (GlobRef.ConstructRef cstr) mib.mind_hyps;
52 let t = Inductive.type_of_constructor (cstr,EConstr.Unsafe.to_instance u) specif in
53 EConstr.of_constr (Arguments_renaming.rename_type env t (ConstructRef cstr))
54
55 (* Return constructor types in user form *)
56 let type_of_constructors env (ind,u as indu) =
57 let indu = on_snd EConstr.Unsafe.to_instance indu in
58 let specif = Inductive.lookup_mind_specif env ind in
59 Array.map EConstr.of_constr (Inductive.type_of_constructors indu specif)
60
61 (* Return constructor types in normal form *)
62 let arities_of_constructors env (ind,u as indu) =
63 let indu = on_snd EConstr.Unsafe.to_instance indu in
64 let specif = Inductive.lookup_mind_specif env ind in
65 Array.map EConstr.of_constr (Inductive.arities_of_constructors indu specif)
66
67 (* [inductive_family] = [inductive_instance] applied to global parameters *)
68 type inductive_family = inductive puniverses * constr list
69
70 let make_ind_family (mis, params) = (mis,params)
71 let dest_ind_family (mis,params) : inductive_family = (mis,params)
72
73 let map_ind_family f (mis,params) = (mis, List.map f params)
74
75 let liftn_inductive_family n d = map_ind_family (liftn n d)
76 let lift_inductive_family n = liftn_inductive_family n 1
77
78 let substnl_ind_family l n = map_ind_family (substnl l n)
79
80 let relevance_of_inductive env ind =
81 let ind = on_snd EConstr.Unsafe.to_instance ind in
82 ERelevance.make @@ Inductive.relevance_of_inductive env ind
83
84 let relevance_of_inductive_family env (ind,_ : inductive_family) =
85 relevance_of_inductive env ind
86
87 type inductive_type = IndType of inductive_family * EConstr.constr list
88
89 let ind_of_ind_type = function IndType (((ind,_),_),_) -> ind
90
91 let make_ind_type (indf, realargs) = IndType (indf,realargs)
92 let dest_ind_type (IndType (indf,realargs)) = (indf,realargs)
93
94 let map_inductive_type f (IndType (indf, realargs)) =
95 IndType (map_ind_family f indf, List.map f realargs)
96
97 let liftn_inductive_type n d = map_inductive_type (EConstr.Vars.liftn n d)
98 let lift_inductive_type n = liftn_inductive_type n 1
99
100 let substnl_ind_type l n = map_inductive_type (EConstr.Vars.substnl l n)
101
102 let relevance_of_inductive_type env (IndType (indf, _)) =
103 relevance_of_inductive_family env indf
104
105 let mkAppliedInd (IndType ((ind,params), realargs)) =
106 applist (mkIndU ind, params @ realargs)
107
108 let dest_recarg p = match Rtree.Kind.kind p with
109 | Rtree.Kind.Node (ra, _) -> ra
110 | Rtree.Kind.Var _ -> assert false
111
112 let dest_subterms p = match Rtree.Kind.kind p with
113 | Rtree.Kind.Node (ra, cstrs) ->
114 let () = assert (match ra with Norec -> false | _ -> true) in
115 cstrs
116 | Rtree.Kind.Var _ -> assert false
117
118 let mis_is_recursive mip =
119 let one_is_rec rvec =
120 Array.exists (fun ra ->
121 match dest_recarg ra with
122 | Mrec (RecArgInd ind) -> true
123 | Mrec (RecArgPrim _) | Norec -> false
124 ) rvec
125 in
126 Array.exists one_is_rec (dest_subterms @@ Rtree.Kind.make mip.mind_recargs)
127
128 let mis_is_nested kn mib =
129 Array.exists (fun mip ->
130 Array.exists (fun rvec ->
131 Array.exists (fun ra ->
132 match dest_recarg ra with
133 | Mrec (RecArgInd (kni, _)) -> not @@ MutInd.CanOrd.equal kn kni
134 | Mrec (RecArgPrim _) | Norec -> false
135 ) rvec
136 ) (dest_subterms @@ Rtree.Kind.make mip.mind_recargs)
137 ) mib.mind_packets
138
139 let mis_nf_constructor_type ((_,j),u) (mib,mip) =
140 let nconstr = Array.length mip.mind_consnames in
141 if j > nconstr then user_err Pp.(str "Not enough constructors in the type.");
142 let (ctx, cty) = mip.mind_nf_lc.(j - 1) in
143 subst_instance_constr u (EConstr.it_mkProd_or_LetIn (EConstr.of_constr cty) (EConstr.of_rel_context ctx))
144
145 (* Number of constructors *)
146
147 let nconstructors env ind =
148 let (_,mip) = Inductive.lookup_mind_specif env ind in
149 Array.length mip.mind_consnames
150
151 (* Arity of constructors excluding parameters, excluding local defs *)
152
153 let constructors_nrealargs env ind =
154 let (_,mip) = Inductive.lookup_mind_specif env ind in
155 mip.mind_consnrealargs
156
157 (* Arity of constructors excluding parameters, including local defs *)
158
159 let constructors_nrealdecls env ind =
160 let (_,mip) = Inductive.lookup_mind_specif env ind in
161 mip.mind_consnrealdecls
162
163 (* Arity of constructors including parameters, excluding local defs *)
164
165 let constructor_nallargs env (ind,j) =
166 let (mib,mip) = Inductive.lookup_mind_specif env ind in
167 mip.mind_consnrealargs.(j-1) + mib.mind_nparams
168
169 (* Arity of constructors including params, including local defs *)
170
171 let constructor_nalldecls env (ind,j) = (* TOCHANGE en decls *)
172 let (mib,mip) = Inductive.lookup_mind_specif env ind in
173 mip.mind_consnrealdecls.(j-1) + Context.Rel.length (mib.mind_params_ctxt)
174
175 (* Arity of constructors excluding params, excluding local defs *)
176
177 let constructor_nrealargs env (ind,j) =
178 let (_,mip) = Inductive.lookup_mind_specif env ind in
179 mip.mind_consnrealargs.(j-1)
180
181 (* Arity of constructors excluding params, including local defs *)
182
183 let constructor_nrealdecls env (ind,j) = (* TOCHANGE en decls *)
184 let (_,mip) = Inductive.lookup_mind_specif env ind in
185 mip.mind_consnrealdecls.(j-1)
186
187 (* Length of arity, excluding params, excluding local defs *)
188
189 let inductive_nrealargs env ind =
190 let (_,mip) = Inductive.lookup_mind_specif env ind in
191 mip.mind_nrealargs
192
193 (* Length of arity, excluding params, including local defs *)
194
195 let inductive_nrealdecls env ind =
196 let (_,mip) = Inductive.lookup_mind_specif env ind in
197 mip.mind_nrealdecls
198
199 (* Full length of arity (w/o local defs) *)
200
201 let inductive_nallargs env ind =
202 let (mib,mip) = Inductive.lookup_mind_specif env ind in
203 mib.mind_nparams + mip.mind_nrealargs
204
205 (* Length of arity (w/o local defs) *)
206
207 let inductive_nparams env ind =
208 let (mib,mip) = Inductive.lookup_mind_specif env ind in
209 mib.mind_nparams
210
211 (* Length of arity (with local defs) *)
212
213 let inductive_nparamdecls env ind =
214 let (mib,mip) = Inductive.lookup_mind_specif env ind in
215 Context.Rel.length mib.mind_params_ctxt
216
217 (* Full length of arity (with local defs) *)
218
219 let inductive_nalldecls env ind =
220 let (mib,mip) = Inductive.lookup_mind_specif env ind in
221 Context.Rel.length (mib.mind_params_ctxt) + mip.mind_nrealdecls
222
223 (* Others *)
224
225 let inductive_paramdecls env (ind,u) =
226 let u = EConstr.Unsafe.to_instance u in
227 let (mib,mip) = Inductive.lookup_mind_specif env ind in
228 EConstr.of_rel_context @@ Inductive.inductive_paramdecls (mib,u)
229
230 let inductive_alldecls env (ind,u) =
231 let (mib,mip) = Inductive.lookup_mind_specif env ind in
232 Vars.subst_instance_context u (EConstr.of_rel_context mip.mind_arity_ctxt)
233
234 let inductive_alltags env ind =
235 let (mib,mip) = Inductive.lookup_mind_specif env ind in
236 Context.Rel.to_tags mip.mind_arity_ctxt
237
238 let constructor_alltags env (ind,j) =
239 let (mib,mip) = Inductive.lookup_mind_specif env ind in
240 Context.Rel.to_tags (fst mip.mind_nf_lc.(j-1))
241
242 let constructor_has_local_defs env (indsp,j) =
243 let (mib,mip) = Inductive.lookup_mind_specif env indsp in
244 let l1 = mip.mind_consnrealdecls.(j-1) + Context.Rel.length (mib.mind_params_ctxt) in
245 let l2 = recarg_length mip.mind_recargs j + mib.mind_nparams in
246 not (Int.equal l1 l2)
247
248 let inductive_has_local_defs env ind =
249 let (mib,mip) = Inductive.lookup_mind_specif env ind in
250 let l1 = Context.Rel.length (mib.mind_params_ctxt) + mip.mind_nrealdecls in
251 let l2 = mib.mind_nparams + mip.mind_nrealargs in
252 not (Int.equal l1 l2)
253
254 let squash_elim_sort sigma squash rtnsort =
255 let open Inductive in
256 let add_unif_if_cannot_elim_into pb starget =
257 let q = Sorts.quality starget in
258 let q' = ESorts.quality sigma rtnsort in
259 if Inductive.eliminates_to (Evd.elim_graph sigma) q q'
260 then sigma
261 else pb sigma (ESorts.make starget) rtnsort in
262 match squash with
263 | SquashToSet ->
264 add_unif_if_cannot_elim_into Evd.set_eq_sort Sorts.set
265 (* Squashed inductive in Set, only happens with impredicative Set *)
266 | SquashToQuality (QConstant QProp) ->
267 add_unif_if_cannot_elim_into Evd.set_eq_sort Sorts.prop
268 (* Squashed inductive in Prop, return sort must be Prop or SProp *)
269 | SquashToQuality (QConstant QSProp) ->
270 add_unif_if_cannot_elim_into Evd.set_eq_sort Sorts.sprop
271 (* Squashed inductive in SProp, return sort must be SProp. *)
272 | SquashToQuality (QConstant QType) ->
273 add_unif_if_cannot_elim_into Evd.set_leq_sort Sorts.set
274 (* Sort poly squash to type *)
275 | SquashToQuality (QVar q) ->
276 add_unif_if_cannot_elim_into Evd.set_leq_sort (Sorts.qsort q Univ.Universe.type0)
277
278 let is_squashed sigma (specif,u) =
279 Inductive.is_squashed_gen
280 (Evd.elim_graph sigma)
281 (UState.nf_quality (Evd.ustate sigma))
282 (specif,EConstr.Unsafe.to_instance u)
283
284 let is_allowed_elimination sigma ((_,mip) as specif,u) s =
285 match mip.mind_record with
286 | PrimRecord _ -> true
287 | NotRecord | FakeRecord ->
288 let s = EConstr.ESorts.kind sigma s in
289 let g = Evd.elim_graph sigma in
290 Inductive.allowed_elimination_gen g
291 (UState.nf_quality (Evd.ustate sigma))
292 (Inductive.is_allowed_elimination_actions g s)
293 (specif,EConstr.Unsafe.to_instance u)
294 s
295
296 let make_allowed_elimination_actions sigma s =
297 Inductive.{
298 not_squashed = Some sigma
299 ; squashed_to_set_below = Some sigma
300 ; squashed_to_set_above = (
301 try Some (Evd.set_leq_sort sigma s ESorts.set)
302 with UGraph.UniverseInconsistency _ -> None)
303 ; squashed_to_quality = fun indq ->
304 let sq = EConstr.ESorts.quality sigma s in
305 if Inductive.eliminates_to (Evd.elim_graph sigma) indq sq
306 then Some sigma
307 else
308 try Some (Evd.set_elim_to sigma indq sq)
309 with QGraph.EliminationError _ | UGraph.UniverseInconsistency _ -> None }
310
311 let make_allowed_elimination sigma ((_,mip) as specif,u) s =
312 match mip.mind_record with
313 | PrimRecord _ -> Some sigma
314 | NotRecord | FakeRecord ->
315 Inductive.allowed_elimination_gen
316 (Evd.elim_graph sigma)
317 (UState.nf_quality (Evd.ustate sigma))
318 (make_allowed_elimination_actions sigma s)
319 (specif,EConstr.Unsafe.to_instance u)
320 (EConstr.ESorts.kind sigma s)
321
322 (* XXX questionable for sort poly inductives *)
323 let elim_sort (mib,mip) =
324 let is_record =
325 match mip.mind_record with
326 | NotRecord | FakeRecord -> false
327 | PrimRecord _ -> true in
328 let has_args mip =
329 let rec types_prod t = match Constr.kind t with
330 | Prod(_,ct,t) -> ct::(types_prod t)
331 | _ -> []
332 in
333 let field_types =
334 List.skipn mib.mind_nparams (types_prod mip.mind_user_lc.(0)) in
335 List.exists (fun t -> List.length (types_prod t) > 1) field_types in
336 (* Allow large elimination on non-squashed inductives except when it's
337 a primitive record in SProp such that any of its "subconstructors" has
338 arguments. We'd wish for a more uniform management of this case in the
339 future. *)
340 if Option.is_empty mip.mind_squashed &&
341 not (is_record && has_args mip && Sorts.is_sprop mip.mind_sort)
342 then Sorts.Quality.qtype
343 else Sorts.quality mip.mind_sort
344
345 let top_allowed_sort env (kn,i as ind) =
346 let specif = Inductive.lookup_mind_specif env ind in
347 elim_sort specif
348
349 let constant_sorts_below top =
350 let top = UnivGen.QualityOrSet.of_quality top in
351 List.filter
352 (UnivGen.QualityOrSet.eliminates_to top)
353 (UnivGen.QualityOrSet.all_constants)
354
355 let sorts_for_schemes specif =
356 constant_sorts_below (elim_sort specif)
357
358 let has_dependent_elim (mib,mip) =
359 match mip.mind_record with
360 | PrimRecord r ->
361 mip.mind_relevance == Irrelevant ||
362 (mib.mind_finite == BiFinite && match r.has_eta with AlwaysEta -> true | NoEta -> false)
363 | NotRecord | FakeRecord -> true
364
365 (* Annotation for cases *)
366 let make_case_info env ind style =
367 let (mib,mip) = Inductive.lookup_mind_specif env ind in
368 let print_info = { Constr.style } in
369 { Constr.ci_ind = ind;
370 ci_npar = mib.mind_nparams;
371 ci_cstr_ndecls = mip.mind_consnrealdecls;
372 ci_cstr_nargs = mip.mind_consnrealargs;
373 ci_pp_info = print_info }
374
375 (*s Useful functions *)
376
377 type constructor_summary = {
378 cs_name : Id.t;
379 cs_cstr : constructor puniverses;
380 cs_params : constr list;
381 cs_nargs : int;
382 cs_args : EConstr.rel_context;
383 cs_concl_realargs : constr array
384 }
385
386 let lift_constructor n cs = {
387 cs_name = cs.cs_name;
388 cs_cstr = cs.cs_cstr;
389 cs_params = List.map (lift n) cs.cs_params;
390 cs_nargs = cs.cs_nargs;
391 cs_args = Vars.lift_rel_context n cs.cs_args;
392 cs_concl_realargs = Array.map (liftn n (cs.cs_nargs+1)) cs.cs_concl_realargs
393 }
394
395 (* Accept either all parameters or only recursively uniform ones *)
396 let instantiate_params t params sign =
397 let nnonrecpar = Context.Rel.nhyps sign - List.length params in
398 (* Adjust the signature if recursively non-uniform parameters are not here *)
399 let _,sign = Context.Rel.chop_nhyps nnonrecpar sign in
400 let _,t = Term.decompose_prod_n_decls (Context.Rel.length sign) t in
401 let subst = subst_of_rel_context_instance_list sign params in
402 substl subst (EConstr.of_constr t)
403
404 let instantiate_constructor_params (_,u as cstru) (mib,_ as mind_specif) params =
405 let typi = mis_nf_constructor_type cstru mind_specif in
406 let ctx = Vars.subst_instance_context u (EConstr.of_rel_context mib.mind_params_ctxt) in
407 instantiate_params (EConstr.Unsafe.to_constr typi) params ctx
408
409 let get_constructor ((ind,u),mib,mip,params) j =
410 assert (j <= Array.length mip.mind_consnames);
411 let typi = instantiate_constructor_params ((ind,j),u) (mib,mip) params in
412 let typi = EConstr.Unsafe.to_constr typi in
413 let (args,ccl) = Term.decompose_prod_decls typi in
414 let (_,allargs) = Constr.decompose_app_list ccl in
415 let vargs = List.skipn (List.length params) allargs in
416 let name = mip.mind_consnames.(j-1) in
417 { cs_name = name;
418 cs_cstr = (ith_constructor_of_inductive ind j,u);
419 cs_params = params;
420 cs_nargs = Context.Rel.length args;
421 cs_args = EConstr.of_rel_context args;
422 cs_concl_realargs = Array.map_of_list EConstr.of_constr vargs }
423
424 let get_constructors env (ind,params) =
425 let (mib,mip) = Inductive.lookup_mind_specif env (fst ind) in
426 Array.init (Array.length mip.mind_consnames)
427 (fun j -> get_constructor (ind,mib,mip,params) (j+1))
428
429 let get_projections = Environ.get_projections
430
431 (* ************************************* *)
432 module Internal = struct
433 (* FIXME temporary copy of [Typeops] functions: previously, there was an hack in
434 place to make the kernel aware of [QVar]s eliminating to [Prop]. It's not
435 working anymore with the [QGraph], so we redefine [nf_relevance] and
436 [should_invert_case] to work with the [QGraph] in [sigma] (which knows the
437 relevant [QVar]s *)
438 let nf_relevance sigma = function
439 | Sorts.RelevanceVar q as r ->
440 if UState.is_above_prop (Evd.ustate sigma) q
441 then Sorts.Relevant
442 else r
443 | (Sorts.Irrelevant | Sorts.Relevant) as r -> r
444
445 let should_invert_case env sigma r (ci : Constr.case_info) =
446 Sorts.relevance_equal (nf_relevance sigma r) Sorts.Relevant &&
447 let mib,mip = Inductive.lookup_mind_specif env ci.ci_ind in
448 (* mind_relevance cannot be a pseudo sort poly variable so don't use check_relevance *)
449 Sorts.relevance_equal mip.mind_relevance Sorts.Irrelevant &&
450 match Array.length mip.mind_nf_lc with
451 | 0 -> true
452 | 1 ->
453 List.length (fst mip.mind_nf_lc.(0)) = List.length mib.mind_params_ctxt
454 | _ -> false
455 end
456 (* ************************************* *)
457
458 let make_case_invert env sigma (IndType (((ind,u),params),indices)) ~case_relevance:r ci =
459 let r = ERelevance.kind sigma r in
460 if Internal.should_invert_case env sigma r ci
461 then Constr.CaseInvert {indices=Array.of_list indices}
462 else Constr.NoInvert
463
464 let make_project env sigma ind pred c branches ps =
465 assert(Array.length branches == 1);
466 let na, ty, t = destLambda sigma pred in
467 let mib, mip as specif = Inductive.lookup_mind_specif env ind in
468 let () =
469 if (* dependent *) not (Vars.noccurn sigma 1 t) &&
470 not (has_dependent_elim specif) then
471 Pretype_errors.error_not_allowed_dependent_elimination env sigma false ind
472 in
473 let branch = branches.(0) in
474 let ctx, br = decompose_lambda_n_decls sigma mip.mind_consnrealdecls.(0) branch in
475 let _, u = destInd sigma (fst (decompose_app sigma ty)) in
476 let u = Unsafe.to_instance u in
477 let mkProj i c =
478 let p, r = ps.(i) in
479 let r = UVars.subst_instance_relevance u r in
480 mkProj (Projection.make p true, ERelevance.make r, c)
481 in
482 let proj = match EConstr.destRel sigma br with
483 | exception Constr.DestKO -> None
484 | i ->
485 begin match List.skipn (i-1) ctx with
486 | exception Failure _ -> None
487 | ctx -> match ctx with
488 | [] -> None
489 | LocalDef _ :: _ ->
490 (* XXX Maybe we should produce the applied constant for this letin pseudoprojection?
491 We would have to get the params etc*)
492 None
493 | LocalAssum _ :: ctx ->
494 (* This match is just a projection *)
495 Some (mkProj (Context.Rel.nhyps ctx) c)
496 end
497 in
498 match proj with
499 | Some proj -> proj
500 | None ->
501 let n, len, ctx =
502 List.fold_right
503 (fun decl (i, j, ctx) ->
504 match decl with
505 | LocalAssum (na, ty) ->
506 let t = mkProj i (mkRel j) in
507 (i + 1, j + 1, LocalDef (na, t, Vars.liftn 1 j ty) :: ctx)
508 | LocalDef (na, b, ty) ->
509 (i, j + 1, LocalDef (na, Vars.liftn 1 j b, Vars.liftn 1 j ty) :: ctx))
510 ctx (0, 1, [])
511 in
512 mkLetIn (na, c, ty, it_mkLambda_or_LetIn (Vars.liftn 1 (mip.mind_consnrealdecls.(0) + 1) br) ctx)
513
514 let simple_make_case_or_project env sigma ci pred invert c branches =
515 let ind = ci.Constr.ci_ind in
516 let projs = get_projections env ind in
517 match projs with
518 | None -> mkCase (EConstr.contract_case env sigma (ci, pred, invert, c, branches))
519 | Some ps -> make_project env sigma ind (fst pred) c branches ps
520
521 let make_case_or_project env sigma indt ci pred c branches =
522 let IndType (((ind,_),_),_) = indt in
523 let projs = get_projections env ind in
524 match projs with
525 | None ->
526 let invert = make_case_invert env sigma indt ~case_relevance:(snd pred) ci in
527 mkCase (EConstr.contract_case env sigma (ci, pred, invert, c, branches))
528 | Some ps -> make_project env sigma ind (fst pred) c branches ps
529
530 (* substitution in a signature *)
531
532 let substnl_rel_context subst n sign =
533 let rec aux n = function
534 | d::sign -> substnl_decl subst n d :: aux (n+1) sign
535 | [] -> []
536 in List.rev (aux n (List.rev sign))
537
538 let substl_rel_context subst = substnl_rel_context subst 0
539
540 let get_arity env ((ind,u),params) =
541 let (mib,mip) = Inductive.lookup_mind_specif env ind in
542 let parsign =
543 (* Dynamically detect if called with an instance of recursively
544 uniform parameter only or also of recursively non-uniform
545 parameters *)
546 let u = EConstr.Unsafe.to_instance u in
547 let nparams = List.length params in
548 if Int.equal nparams mib.mind_nparams then
549 Inductive.inductive_paramdecls (mib,u)
550 else begin
551 assert (Int.equal nparams mib.mind_nparams_rec);
552 snd (Inductive.inductive_nonrec_rec_paramdecls (mib,u))
553 end in
554 let parsign = EConstr.of_rel_context parsign in
555 let arproperlength = List.length mip.mind_arity_ctxt - List.length parsign in
556 let arsign,_ = List.chop arproperlength mip.mind_arity_ctxt in
557 let arsign = EConstr.of_rel_context arsign in
558 let subst = subst_of_rel_context_instance_list parsign params in
559 let arsign = Vars.subst_instance_context u arsign in
560 substl_rel_context subst arsign
561
562 (* Functions to build standard types related to inductive *)
563 let build_dependent_constructor cs =
564 applist
565 (mkConstructU cs.cs_cstr,
566 (List.map (lift cs.cs_nargs) cs.cs_params)
567 @(Context.Rel.instance_list mkRel 0 cs.cs_args))
568
569 let build_dependent_inductive env ((ind, params) as indf) =
570 let arsign = get_arity env indf in
571 let nrealargs = List.length arsign in
572 applist
573 (mkIndU ind,
574 (List.map (lift nrealargs) params)@(Context.Rel.instance_list mkRel 0 arsign))
575
576 (* builds the arity of an elimination predicate in sort [s] *)
577
578 let make_arity_signature env sigma dep (ind, _ as indf) =
579 let arsign = get_arity env indf in
580 let r = relevance_of_inductive env ind in
581 let anon = make_annot Anonymous r in
582 if dep then
583 (* We need names everywhere *)
584 Namegen.name_context env sigma
585 ((LocalAssum (anon, build_dependent_inductive env indf)) :: arsign)
586 (* Costly: would be better to name once for all at definition time *)
587 else
588 (* No need to enforce names *)
589 arsign
590
591 let make_arity env sigma dep indf s =
592 it_mkProd_or_LetIn (mkSort s) (make_arity_signature env sigma dep indf)
593
594 (**************************************************)
595
596 (** From a rel context describing the constructor arguments,
597 build an expansion function.
598 The term built is expecting to be substituted first by
599 a substitution of the form [params, x : ind params] *)
600 let compute_projections env (kn, i as ind) =
601 let mib = Environ.lookup_mind kn env in
602 let u = UVars.make_abstract_instance (Declareops.inductive_polymorphic_context mib) in
603 let u = EInstance.make u in
604 let x = match mib.mind_packets.(i).mind_record with
605 | NotRecord | FakeRecord ->
606 anomaly Pp.(str "Trying to build primitive projections for a non-primitive record")
607 | PrimRecord { id ; _ } ->
608 make_annot (Name id) (ERelevance.make mib.mind_packets.(i).mind_relevance)
609 in
610 let pkt = mib.mind_packets.(i) in
611 let { mind_nparams = nparamargs; mind_params_ctxt = params } = mib in
612 let params = EConstr.of_rel_context params in
613 let ctx, _ = pkt.mind_nf_lc.(0) in
614 let ctx, paramslet = List.chop pkt.mind_consnrealdecls.(0) ctx in
615 let ctx = EConstr.of_rel_context ctx in
616 (* We build a substitution smashing the lets in the record parameters so
617 that typechecking projections requires just a substitution and not
618 matching with a parameter context. *)
619 let indty =
620 (* [ty] = [Ind inst] is typed in context [params] *)
621 let inst = Context.Rel.instance mkRel 0 paramslet in
622 let indu = mkIndU (ind, u) in
623 let ty = mkApp (indu, inst) in
624 (* [Ind inst] is typed in context [params-wo-let] *)
625 ty
626 in
627 let projections decl (proj_arg, j, pbs, subst) =
628 match decl with
629 | LocalDef (na,c,t) ->
630 (* From [params, field1,..,fieldj |- c(params,field1,..,fieldj)]
631 to [params, x:I, field1,..,fieldj |- c(params,field1,..,fieldj)] *)
632 let c = liftn 1 j c in
633 (* From [params, x:I, field1,..,fieldj |- c(params,field1,..,fieldj)]
634 to [params, x:I |- c(params,proj1 x,..,projj x)] *)
635 let c1 = substl subst c in
636 (* From [params, x:I |- subst:field1,..,fieldj]
637 to [params, x:I |- subst:field1,..,fieldj+1] where [subst]
638 is represented with instance of field1 last *)
639 let subst = c1 :: subst in
640 (proj_arg, j+1, pbs, subst)
641 | LocalAssum (na,t) ->
642 match na.binder_name with
643 | Name lab ->
644 let proj_relevant = na.binder_relevance in
645 let kn = Projection.Repr.make ind ~proj_npars:mib.mind_nparams ~proj_arg lab in
646 (* from [params, field1,..,fieldj |- t(params,field1,..,fieldj)]
647 to [params, x:I, field1,..,fieldj |- t(params,field1,..,fieldj] *)
648 let t = liftn 1 j t in
649 (* from [params, x:I, field1,..,fieldj |- t(params,field1,..,fieldj)]
650 to [params-wo-let, x:I |- t(params,proj1 x,..,projj x)] *)
651 (* from [params, x:I, field1,..,fieldj |- t(field1,..,fieldj)]
652 to [params, x:I |- t(proj1 x,..,projj x)] *)
653 let ty = substl subst t in
654 let term = mkProj (Projection.make kn true, proj_relevant, mkRel 1) in
655 let fterm = mkProj (Projection.make kn false, proj_relevant, mkRel 1) in
656 let etab = it_mkLambda_or_LetIn (mkLambda (x, indty, term)) params in
657 let etat = it_mkProd_or_LetIn (mkProd (x, indty, ty)) params in
658 let body = (etab, etat) in
659 (proj_arg + 1, j + 1, body :: pbs, fterm :: subst)
660 | Anonymous ->
661 anomaly Pp.(str "Trying to build primitive projections for a non-primitive record")
662 in
663 let (_, _, pbs, subst) =
664 List.fold_right projections ctx (0, 1, [], [])
665 in
666 Array.rev_of_list pbs
667
668 (**************************************************)
669
670 let extract_mrectype sigma t =
671 let open EConstr in
672 let (t, l) = decompose_app_list sigma t in
673 match EConstr.kind sigma t with
674 | Ind ind -> (ind, l)
675 | _ -> raise Not_found
676
677 let find_mrectype_vect env sigma c =
678 let (t, l) = EConstr.decompose_app sigma (whd_all env sigma c) in
679 match EConstr.kind sigma t with
680 | Ind ind -> (ind, l)
681 | _ -> raise Not_found
682
683 let find_mrectype env sigma c =
684 let (ind, v) = find_mrectype_vect env sigma c in (ind, Array.to_list v)
685
686 let find_rectype env sigma c =
687 let open EConstr in
688 let (t, l) = decompose_app_list sigma (whd_all env sigma c) in
689 match EConstr.kind sigma t with
690 | Ind (ind,u) ->
691 let (mib,mip) = Inductive.lookup_mind_specif env ind in
692 if mib.mind_nparams > List.length l then raise Not_found;
693 let (par,rargs) = List.chop mib.mind_nparams l in
694 let indu = (ind, u) in
695 IndType ((indu, par), rargs)
696 | _ -> raise Not_found
697
698 let find_inductive env sigma c =
699 let open EConstr in
700 let (t, l) = decompose_app_list sigma (whd_all env sigma c) in
701 match EConstr.kind sigma t with
702 | Ind ind
703 when (fst (Inductive.lookup_mind_specif env (fst ind))).mind_finite <> CoFinite ->
704 (ind, l)
705 | _ -> raise Not_found
706
707 let find_coinductive env sigma c =
708 let open EConstr in
709 let (t, l) = decompose_app_list sigma (whd_all env sigma c) in
710 match EConstr.kind sigma t with
711 | Ind ind
712 when (fst (Inductive.lookup_mind_specif env (fst ind))).mind_finite == CoFinite ->
713 (ind, l)
714 | _ -> raise Not_found
715
716
717 (* Type of Case predicates *)
718 let arity_of_case_predicate env (ind,params) dep k =
719 let arsign = get_arity env (ind,params) in
720 let r = relevance_of_inductive env ind in
721 let mind = build_dependent_inductive env (ind,params) in
722 let concl = if dep then mkArrow mind r (mkSort k) else mkSort k in
723 it_mkProd_or_LetIn concl arsign
724
725 let type_of_projection_constant env (p,u) =
726 let _, pty = lookup_projection p env in
727 EConstr.Vars.subst_instance_constr u (EConstr.of_constr pty)
728
729 let type_of_projection_knowing_arg env sigma p c ty =
730 let open EConstr.Vars in
731 let IndType(pars,realargs) =
732 try find_rectype env sigma ty
733 with Not_found ->
734 raise (Invalid_argument "type_of_projection_knowing_arg_type: not an inductive type")
735 in
736 let (_,u), pars = dest_ind_family pars in
737 substl (c :: List.rev pars) (type_of_projection_constant env (p,u))
738
739 (***********************************************)
740 (* Guard condition *)
741
742 (* A function which checks that a term well typed verifies both
743 syntactic conditions *)
744
745 let control_only_guard env sigma c =
746 let evars = Evd.evar_handler sigma in
747 let c = Evarutil.nf_evar sigma c in
748 let check_fix_cofix e c =
749 (* [c] has already been normalized upfront *)
750 let c = EConstr.Unsafe.to_constr c in
751 match Constr.kind c with
752 | CoFix (_,(_,_,_) as cofix) ->
753 Inductive.check_cofix ~evars e cofix
754 | Fix fix ->
755 Inductive.check_fix ~evars e fix
756 | _ -> ()
757 in
758 let rec iter env c =
759 check_fix_cofix env c;
760 EConstr.iter_with_full_binders env sigma EConstr.push_rel iter env c
761 in
762 try iter env c
763 with Type_errors.TypeError (env, e) ->
764 raise (Pretype_errors.PretypeError
765 (env, sigma,
766 TypingError (Pretype_errors.of_type_error e)))
767
768 (** Generalize template polymorphic universe variables, subtitute the instance,
769 and returns the context of parameters, the new evar_map, and the
770 substitution for the template variable if there is one. *)
771 let paramdecls_fresh_template sigma (mib,u) =
772 match mib.mind_template with
773 | None ->
774 let params = Inductive.inductive_paramdecls (mib, EConstr.Unsafe.to_instance u) in
775 sigma, EConstr.of_rel_context params, None
776 | Some templ ->
777 assert (EConstr.EInstance.is_empty u);
778 let sigma, univs = List.fold_left_map (fun sigma -> function
779 | None -> sigma, (fun ~default -> assert false)
780 | Some s ->
781 let sigma, u = match snd (Inductive.Template.bind_kind s) with
782 | None -> sigma, Univ.Universe.type0
783 | Some _ ->
784 let sigma, u = Evd.new_univ_level_variable UState.univ_rigid sigma in
785 sigma, Univ.Universe.make u
786 in
787 sigma, fun ~default -> Inductive.TemplateUniv u)
788 sigma
789 templ.template_param_arguments
790 in
791 let csts, params, sub = Inductive.instantiate_template_universes mib univs in
792 let sigma = Evd.add_poly_constraints ~src:UState.Internal sigma csts in
793 (sigma, EConstr.of_rel_context params, Some sub)