Debian Codegraph @

kernel/inductive.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 UVars
16 open Constr
17 open Vars
18 open Declarations
19 open Declareops
20 open Environ
21 open Reduction
22 open Type_errors
23 open Context.Rel.Declaration
24 open Sorts
25
26 (* raises an anomaly if not an inductive type *)
27 let lookup_mind_specif env (kn,tyi) =
28 let mib = Environ.lookup_mind kn env in
29 if tyi >= Array.length mib.mind_packets then
30 user_err Pp.(str "Inductive.lookup_mind_specif: invalid inductive index");
31 (mib, mib.mind_packets.(tyi))
32
33 let find_rectype ?evars env c =
34 let (t, l) = decompose_app_list (whd_all ?evars env c) in
35 match kind t with
36 | Ind ind -> (ind, l)
37 | _ -> raise Not_found
38
39 let find_inductive ?evars env c =
40 let (t, l) = decompose_app_list (whd_all ?evars env c) in
41 match kind t with
42 | Ind ind
43 when (fst (lookup_mind_specif env (out_punivs ind))).mind_finite <> CoFinite -> (ind, l)
44 | _ -> raise Not_found
45
46 let find_coinductive ?evars env c =
47 let (t, l) = decompose_app_list (whd_all ?evars env c) in
48 match kind t with
49 | Ind ind
50 when (fst (lookup_mind_specif env (out_punivs ind))).mind_finite == CoFinite -> (ind, l)
51 | _ -> raise Not_found
52
53 let inductive_params (mib,_) = mib.mind_nparams
54
55 let inductive_paramdecls (mib,u) =
56 Vars.subst_instance_context u mib.mind_params_ctxt
57
58 let inductive_nnonrecparams mib = mib.mind_nparams - mib.mind_nparams_rec
59
60 let inductive_nonrec_rec_paramdecls (mib,u) =
61 let nnonrecparamdecls = inductive_nnonrecparams mib in
62 let paramdecls = inductive_paramdecls (mib,u) in
63 Context.Rel.chop_nhyps nnonrecparamdecls paramdecls
64
65 let instantiate_inductive_constraints mib u =
66 UVars.AbstractContext.instantiate u (Declareops.inductive_polymorphic_context mib)
67
68 (************************************************************************)
69
70 let instantiate_params t u args sign =
71 let fail () =
72 anomaly ~label:"instantiate_params" (Pp.str "type, ctxt and args mismatch.") in
73 let (rem_args, subs, ty) =
74 Context.Rel.fold_outside
75 (fun decl (largs,subs,ty) ->
76 match (decl, largs, kind ty) with
77 | (LocalAssum _, a::args, Prod(_,_,t)) -> (args, a::subs, t)
78 | (LocalDef (_,b,_), _, LetIn(_,_,_,t)) ->
79 (largs, (substl subs (subst_instance_constr u b))::subs, t)
80 | _ -> fail ())
81 sign
82 ~init:(args,[],t)
83 in
84 let () = if not (List.is_empty rem_args) then fail () in
85 substl subs ty
86
87 let full_constructor_instantiate (_,u,(mib,_),params) t =
88 let inst_ind = subst_instance_constr u t in
89 instantiate_params inst_ind u params mib.mind_params_ctxt
90
91 (************************************************************************)
92 (************************************************************************)
93
94 (* Functions to build standard types related to inductive *)
95
96 (*
97 Computing the actual sort of an applied or partially applied inductive type:
98
99 I_i: forall uniformparams:utyps, forall otherparams:otyps, Type(a)
100 uniformargs : utyps
101 otherargs : otyps
102 I_1:forall ...,s_1;...I_n:forall ...,s_n |- sort(C_kj(uniformargs)) = s_kj
103 s'_k = max(..s_kj..)
104 merge(..s'_k..) = ..s''_k..
105 --------------------------------------------------------------------
106 Gamma |- I_i uniformargs otherargs : phi(s''_i)
107
108 where
109
110 - if p=0, phi() = Prop
111 - if p=1, phi(s) = s
112 - if p<>1, phi(s) = sup(Set,s)
113
114 Remark: Set (predicative) is encoded as Type(0)
115 *)
116
117 (* Template polymorphism *)
118
119 type template_univ =
120 | TemplateProp
121 | TemplateAboveProp of Sorts.QVar.t * Universe.t
122 | TemplateUniv of Universe.t
123
124 type template_subst = Sorts.Quality.t Int.Map.t * Universe.t Int.Map.t
125
126 let template_univ_quality = function
127 | TemplateProp -> Sorts.Quality.qprop
128 | TemplateUniv _ -> Sorts.Quality.qtype
129 | TemplateAboveProp (q,_) -> Sorts.Quality.QVar q
130
131 (* this requires TemplateAboveProp to really be above prop *)
132 let max_template_quality a b =
133 let open Sorts.Quality in
134 match a, b with
135 | QConstant QSProp, _ | _, QConstant QSProp -> assert false
136 | QConstant QProp, q | q, QConstant QProp -> q
137 | (QConstant QType as q), _ | _, (QConstant QType as q) -> q
138 | QVar a', QVar b' ->
139 if Sorts.QVar.equal a' b' then a
140 else qtype
141
142 let template_univ_universe = function
143 | TemplateProp -> Universe.type0
144 | TemplateAboveProp (_,u) | TemplateUniv u -> u
145
146 let univ_bind_kind u =
147 match Universe.level u with
148 | None -> None
149 | Some l -> Level.var_index l
150
151 let bind_kind = let open Sorts in function
152 | SProp | Prop | Set -> assert false
153 | Type u ->
154 let u = univ_bind_kind u in
155 assert (Option.has_some u);
156 None, u
157 | QSort (q,u) ->
158 let q = Sorts.QVar.var_index q in
159 let u = univ_bind_kind u in
160 assert (Option.has_some q || Option.has_some u);
161 q, u
162
163 (* Add a binding for a parameter binding qbind and ubind to su. *)
164 let cons_subst bind su (qsubst,usubst) =
165 let qbind, ubind = bind_kind bind in
166 let qsubst = match qbind with
167 | None -> qsubst
168 | Some qbind ->
169 let sq = template_univ_quality su in
170 Int.Map.update qbind (function
171 | None -> Some sq
172 | Some q0 -> Some (max_template_quality q0 sq))
173 qsubst
174 in
175 let usubst = match ubind with
176 | None -> usubst
177 | Some ubind ->
178 let u = template_univ_universe su in
179 Int.Map.update ubind (function
180 | None -> Some u
181 | Some _ -> CErrors.anomaly Pp.(str "cons_subst found non linear template level."))
182 usubst
183 in
184 qsubst, usubst
185
186 (* cons_default_subst adds the binding to the default universe to the substitution. *)
187 let cons_default_subst bind defaults (qsubst,usubst) =
188 let qbind, ubind = bind_kind bind in
189 let qsubst = match qbind with
190 | None -> qsubst
191 | Some qbind -> Int.Map.add qbind Sorts.Quality.qtype qsubst
192 in
193 let usubst = match ubind with
194 | None -> usubst
195 | Some ubind ->
196 let u = UVars.subst_instance_universe defaults (Universe.make (Level.var ubind)) in
197 Int.Map.update ubind (function
198 | None -> Some u
199 | Some _ -> CErrors.anomaly Pp.(str "cons_default_subst found non linear template level."))
200 usubst
201 in
202 qsubst, usubst
203
204 type param_univs = (default:Sorts.t -> template_univ) list
205
206 (* Bind expected levels of parameters to actual levels *)
207 (* Propagate the new levels in the signature *)
208 let make_subst defaults =
209 let rec make subst = function
210 | LocalDef _ :: sign, exp, args ->
211 make subst (sign, exp, args)
212 | _d::sign, None::exp, args ->
213 let args = match args with _::args -> args | [] -> [] in
214 make subst (sign, exp, args)
215 | LocalAssum (_,t)::sign, Some bind::exp, a::args ->
216 (* [default] is used in error messages (e.g. when the user gave SProp) *)
217 let _, default = Term.destArity t in
218 let s = a ~default in
219 make (cons_subst bind s subst) (sign, exp, args)
220 | LocalAssum _ :: sign, Some bind::exp, [] ->
221 make (cons_default_subst bind defaults subst) (sign, exp, [])
222 | _sign, [], _ ->
223 (* Uniform parameters are exhausted *)
224 subst
225 | [], _, _ ->
226 assert false
227 in
228 make (Int.Map.empty,Int.Map.empty)
229
230 let template_subst_universe (_,usubst) u =
231 let supern u n = iterate Universe.super n u in
232 let map (u,n) =
233 match Level.var_index u with
234 | None -> Universe.maken u n
235 | Some u ->
236 let u = Int.Map.get u usubst in
237 supern u n
238 in
239 match List.map map (Universe.repr u) with
240 | [] -> assert false
241 | u :: rest ->
242 List.fold_left Universe.sup u rest
243
244 let template_subst_sort (subst : template_subst) = function
245 | Sorts.Prop | Sorts.Set | Sorts.SProp as s -> s
246 | Sorts.Type u ->
247 Sorts.sort_of_univ (template_subst_universe subst u)
248 | Sorts.QSort (q,u) ->
249 let q = match Sorts.QVar.var_index q with
250 | None -> Sorts.Quality.QVar q
251 | Some q -> Int.Map.get q (fst subst)
252 in
253 (* shortcut for impredicative quality *)
254 if Sorts.Quality.(equal qprop q) then Sorts.prop
255 else Sorts.make q (template_subst_universe subst u)
256
257 let rec template_subst_ctx accu subs ctx params = match ctx, params with
258 | [], [] -> accu
259 | (LocalDef _ as decl) :: ctx, params ->
260 template_subst_ctx (decl :: accu) subs ctx params
261 | (LocalAssum _ as decl) :: ctx, None :: params ->
262 template_subst_ctx (decl :: accu) subs ctx params
263 | LocalAssum (na, t) :: ctx, Some s :: params ->
264 let (decls, _) = Term.destArity t in
265 let s = template_subst_sort subs s in
266 let decl = LocalAssum (na, Term.it_mkProd_or_LetIn (mkSort s) decls) in
267 template_subst_ctx (decl :: accu) subs ctx params
268 | _, [] | [], _ -> assert false
269
270 let template_subst_ctx subst ctx params = template_subst_ctx [] subst ctx params
271
272 let instantiate_template_constraints subst templ =
273 let cstrs = UVars.UContext.constraints (UVars.AbstractContext.repr templ.template_context) in
274 let foldq (q, cst, q') accq =
275 let substq q = match q with
276 | Quality.QConstant _ -> q
277 | Quality.QVar q' ->
278 begin
279 match QVar.var_index q' with
280 | None -> q
281 | Some q' -> Int.Map.get q' (fst subst)
282 end in
283 ElimConstraints.add (substq q, cst, substq q') accq in
284 let foldu (u, cst, v) accu =
285 (* v is not a local universe by the unbounded from below property *)
286 let u = match Level.var_index u with
287 | None -> Universe.make u
288 | Some u -> Int.Map.get u (snd subst)
289 in
290 (* if qsort, it is above prop *)
291 let fold accu (u, n) = match n, cst with
292 | 0, _ -> UnivConstraints.add (u, cst, v) accu
293 | 1, UnivConstraint.Le -> UnivConstraints.add (u, UnivConstraint.Lt, v) accu
294 | 1, (UnivConstraint.Eq | UnivConstraint.Lt) -> assert false (* FIXME? *)
295 | _ -> assert false
296 in
297 List.fold_left fold accu (Univ.Universe.repr u)
298 in
299 PConstraints.fold (foldq, foldu) cstrs PConstraints.empty
300
301 let instantiate_template_universes mib args =
302 let templ = match mib.mind_template with
303 | None -> assert false
304 | Some t -> t
305 in
306 let ctx = List.rev mib.mind_params_ctxt in
307 let subst = make_subst templ.template_defaults (ctx,templ.template_param_arguments,args) in
308 let ctx = template_subst_ctx subst ctx templ.template_param_arguments in
309 let cstrs = instantiate_template_constraints subst templ in
310 (cstrs, ctx, subst)
311
312 (* Type of an inductive type *)
313
314 let relevance_of_ind_body mip u =
315 UVars.subst_instance_relevance u mip.mind_relevance
316
317 let relevance_of_inductive env (ind,u) =
318 let _, mip = lookup_mind_specif env ind in
319 relevance_of_ind_body mip u
320
321 let check_instance mib u =
322 if not (match mib.mind_universes with
323 | Monomorphic -> Instance.is_empty u
324 | Polymorphic uctx -> Instance.length u = AbstractContext.size uctx)
325 then CErrors.anomaly Pp.(str "bad instance length on mutind.")
326
327 let type_of_inductive_gen ((mib,mip),u) paramtyps =
328 check_instance mib u;
329 match mib.mind_template with
330 | None ->
331 let cst = instantiate_inductive_constraints mib u in
332 subst_instance_constr u mip.mind_user_arity, cst
333 | Some templ ->
334 let cst, params, subst = instantiate_template_universes mib paramtyps in
335 let ctx = (List.firstn mip.mind_nrealdecls mip.mind_arity_ctxt) @ params in
336 let s = template_subst_sort subst templ.template_concl in
337 Term.mkArity (ctx, s), cst
338
339 let type_of_inductive pind =
340 let (ty, _cst) = type_of_inductive_gen pind [] in
341 ty
342
343 let constrained_type_of_inductive pind =
344 type_of_inductive_gen pind []
345
346 let type_of_inductive_knowing_parameters mip args =
347 type_of_inductive_gen mip args
348
349 (************************************************************************)
350 (* Type of a constructor *)
351
352 let type_of_constructor_gen (cstr, u) (mib,mip) paramtyps =
353 check_instance mib u;
354 let i = index_of_constructor cstr in
355 let nconstr = Array.length mip.mind_consnames in
356 if i > nconstr then user_err Pp.(str "Not enough constructors in the type.");
357 match mib.mind_template with
358 | None ->
359 let cst = instantiate_inductive_constraints mib u in
360 subst_instance_constr u mip.mind_user_lc.(i-1), cst
361 | Some _ ->
362 let cst, params, _ = instantiate_template_universes mib paramtyps in
363 let _, typ = Term.decompose_prod_n_decls (List.length mib.mind_params_ctxt) mip.mind_user_lc.(i - 1) in
364 let typ = Term.it_mkProd_or_LetIn typ params in
365 typ, cst
366
367 let type_of_constructor pcstr ind =
368 let (ty, _cst) = type_of_constructor_gen pcstr ind [] in
369 ty
370
371 let constrained_type_of_constructor cstru ind =
372 type_of_constructor_gen cstru ind []
373
374 let type_of_constructor_knowing_parameters cstr specif args =
375 type_of_constructor_gen cstr specif args
376
377 let arities_of_constructors (_,u) (_,mip) =
378 let map (ctx, c) =
379 let cty = Term.it_mkProd_or_LetIn c ctx in
380 subst_instance_constr u cty
381 in
382 Array.map map mip.mind_nf_lc
383
384 let type_of_constructors (_,u) (_,mip) =
385 Array.map (subst_instance_constr u) mip.mind_user_lc
386
387 let abstract_constructor_type_relatively_to_inductive_types_context ntyps mind t =
388 let rec replace_ind k c =
389 let hd, args = decompose_app c in
390 match kind hd with
391 | Ind ((mind',i),_) when MutInd.CanOrd.equal mind mind' ->
392 mkApp (mkRel (ntyps+k-i), Array.map (replace_ind k) args)
393 | _ -> map_with_binders succ replace_ind k c
394 in
395 replace_ind 0 t
396
397 (************************************************************************)
398
399 (** Elimination functions *)
400
401 let raw_eliminates_to = QGraph.ElimTable.eliminates_to
402
403 let eliminates_to g = QGraph.eliminates_to g
404
405 let sort_eliminates_to g s s' = eliminates_to g (Sorts.quality s) (Sorts.quality s')
406
407 type squash = SquashToSet | SquashToQuality of Quality.t
408
409 type 'a allow_elimination_actions =
410 { not_squashed : 'a
411 ; squashed_to_set_below : 'a
412 ; squashed_to_set_above : 'a
413 ; squashed_to_quality : Quality.t -> 'a }
414
415 let is_squashed_gen g nf_quality ((_,mip),u) =
416 let s = mip.mind_sort in
417 match mip.mind_squashed with
418 | None -> None
419 | Some squash ->
420 let indq = nf_quality (UVars.subst_instance_quality u @@ Sorts.quality s) in
421 match squash with
422 | AlwaysSquashed ->
423 begin match s with
424 | Set -> Some SquashToSet
425 | _ -> Some (SquashToQuality indq)
426 end
427 | SometimesSquashed squash ->
428 (* impredicative set squashes are always quashed,
429 so here if inds=Set it is a sort poly squash (see "foo6" in test sort_poly.v) *)
430 if Quality.Set.for_all
431 (fun q -> eliminates_to g indq (nf_quality (UVars.subst_instance_quality u q)))
432 squash && not @@ Quality.is_qvar indq
433 then None
434 else Some (SquashToQuality indq)
435
436 let allowed_elimination_gen g nf_quality actions specifu s =
437 match is_squashed_gen g nf_quality specifu with
438 | None -> actions.not_squashed
439 | Some SquashToSet ->
440 begin match s with
441 | SProp|Prop|Set -> actions.squashed_to_set_below
442 | QSort _ | Type _ -> actions.squashed_to_set_above
443 end
444 | Some (SquashToQuality indq) -> actions.squashed_to_quality indq
445
446 let is_squashed env specif =
447 is_squashed_gen (Environ.qualities env) Fun.id specif
448
449 let is_allowed_elimination_actions g s =
450 { not_squashed = true
451 ; squashed_to_set_below = true
452 (* XXX in [Type u] case, should we check [u == set] in the ugraph? *)
453 ; squashed_to_set_above = false
454 ; squashed_to_quality
455 = fun indq -> eliminates_to g indq (Sorts.quality s)}
456
457 let is_allowed_elimination env specifu s =
458 let g = Environ.qualities env in
459 allowed_elimination_gen g
460 Fun.id
461 (is_allowed_elimination_actions g s)
462 specifu s
463
464 (* We always allow fixpoints on values in Prop (for the accessibility predicate for instance). *)
465 let is_allowed_fixpoint elim_to sind star =
466 elim_to (Sorts.quality sind) Quality.qprop ||
467 elim_to (Sorts.quality sind) (Sorts.quality star)
468
469 (************************************************************************)
470
471 let is_private (mib,_) = mib.mind_private = Some true
472 let is_primitive_record (_,mip) =
473 match mip.mind_record with
474 | PrimRecord _ -> true
475 | NotRecord | FakeRecord -> false
476
477 (** {6 Changes of representation of Case nodes} *)
478
479 (** Provided:
480 - a universe instance [u]
481 - a term substitution [subst]
482 - name replacements [nas]
483 [instantiate_context u subst nas ctx] applies both [u] and [subst] to [ctx]
484 while replacing names using [nas] (order reversed)
485 *)
486 let instantiate_context = Environ.instantiate_context
487
488 let expand_arity = Environ.expand_arity
489
490 let expand_branch_contexts = Environ.expand_branch_contexts
491
492 type ('constr,'types,'r) pexpanded_case =
493 (case_info * ('constr * 'r) * 'constr pcase_invert * 'constr * 'constr array)
494
495 type expanded_case = (constr,types,Sorts.relevance) pexpanded_case
496
497 let expand_case_specif mib (ci, u, params, (p,rp), iv, c, br) =
498 (* Γ ⊢ c : I@{u} params args *)
499 (* Γ, indices, self : I@{u} params indices ⊢ p : Type *)
500 let mip = mib.mind_packets.(snd ci.ci_ind) in
501 let paramdecl = Vars.subst_instance_context u mib.mind_params_ctxt in
502 let paramsubst = Vars.subst_of_rel_context_instance paramdecl params in
503 (* Expand the return clause *)
504 let ep =
505 let (nas, p) = p in
506 let realdecls = expand_arity (mib, mip) (ci.ci_ind, u) params nas in
507 Term.it_mkLambda_or_LetIn p realdecls
508 in
509 (* Expand the branches *)
510 let ebr =
511 let build_one_branch i (nas, br) (ctx, _) =
512 let ctx, _ = List.chop mip.mind_consnrealdecls.(i) ctx in
513 let ctx = instantiate_context u paramsubst nas ctx in
514 Term.it_mkLambda_or_LetIn br ctx
515 in
516 Array.map2_i build_one_branch br mip.mind_nf_lc
517 in
518 (ci, (ep,rp), iv, c, ebr)
519
520 let expand_case env (ci, _, _, _, _, _, _ as case) =
521 let specif = Environ.lookup_mind (fst ci.ci_ind) env in
522 expand_case_specif specif case
523
524 let contract_case env (ci, (p,rp), iv, c, br) =
525 let (mib, mip) = lookup_mind_specif env ci.ci_ind in
526 let (arity, p) = Term.decompose_lambda_n_decls (mip.mind_nrealdecls + 1) p in
527 let (u, pms) = match arity with
528 | LocalAssum (_, ty) :: _ ->
529 (** Last binder is the self binder for the term being eliminated *)
530 let (ind, args) = decompose_app ty in
531 let (ind, u) = destInd ind in
532 let () = assert (QInd.equal env ind ci.ci_ind) in
533 let pms = Array.sub args 0 mib.mind_nparams in
534 (** Unlift the parameters from under the index binders *)
535 let dummy = List.make mip.mind_nrealdecls mkProp in
536 let pms = Array.map (fun c -> Vars.substl dummy c) pms in
537 (u, pms)
538 | _ -> assert false
539 in
540 let p =
541 let nas = Array.of_list (List.rev_map get_annot arity) in
542 ((nas, p),rp)
543 in
544 let map i br =
545 let (ctx, br) = Term.decompose_lambda_n_decls mip.mind_consnrealdecls.(i) br in
546 let nas = Array.of_list (List.rev_map get_annot ctx) in
547 (nas, br)
548 in
549 (ci, u, pms, p, iv, c, Array.mapi map br)
550
551 (************************************************************************)
552 (* Type of case branches *)
553
554 (* [p] is the predicate, [i] is the constructor number (starting from 0),
555 and [cty] is the type of the constructor (params not instantiated) *)
556 let build_branches_type (ind,u) (_,mip as specif) params p =
557 let build_one_branch i (ctx, c) =
558 let cty = Term.it_mkProd_or_LetIn c ctx in
559 let typi = full_constructor_instantiate (ind,u,specif,params) cty in
560 let (cstrsign,ccl) = Term.decompose_prod_decls typi in
561 let nargs = Context.Rel.length cstrsign in
562 let (_,allargs) = decompose_app_list ccl in
563 let (lparams,vargs) = List.chop (inductive_params specif) allargs in
564 let cargs =
565 let cstr = ith_constructor_of_inductive ind (i+1) in
566 let dep_cstr = Term.applist (mkConstructU (cstr,u),lparams@(Context.Rel.instance_list mkRel 0 cstrsign)) in
567 vargs @ [dep_cstr] in
568 let base = Term.lambda_appvect_decls (mip.mind_nrealdecls+1) (lift nargs p) (Array.of_list cargs) in
569 Term.it_mkProd_or_LetIn base cstrsign in
570 Array.mapi build_one_branch mip.mind_nf_lc
571
572 (************************************************************************)
573 (* Checking the case annotation is relevant *)
574
575 let check_case_info env (indsp,u) ci =
576 let (mib,mip as spec) = lookup_mind_specif env indsp in
577 if
578 not (QInd.equal env indsp ci.ci_ind) ||
579 not (Int.equal mib.mind_nparams ci.ci_npar) ||
580 not (Array.equal Int.equal mip.mind_consnrealdecls ci.ci_cstr_ndecls) ||
581 not (Array.equal Int.equal mip.mind_consnrealargs ci.ci_cstr_nargs) ||
582 is_primitive_record spec
583 then raise (TypeError(env,WrongCaseInfo((indsp,u),ci)))
584
585
586 (************************************************************************)
587 (************************************************************************)
588
589 let apply_branch ((_, i), _u) args ci lf =
590 let args = List.skipn ci.ci_npar args in
591 let br = lf.(i - 1) in
592 let ctx, br = Term.decompose_lambda_n_decls ci.ci_cstr_ndecls.(i - 1) br in
593 let subst = subst_of_rel_context_instance_list ctx args in
594 Vars.substl subst br
595
596 let contract_fix ((recindices,bodynum),(_,_,bodies as typedbodies)) =
597 let nbodies = Array.length bodies in
598 let make_Fi j =
599 let ind = nbodies-j-1 in
600 mkFix ((recindices,ind),typedbodies)
601 in
602 let closure = List.init nbodies make_Fi in
603 substl closure bodies.(bodynum)
604
605 let contract_cofix (bodynum,(_,_,bodies as typedbodies)) =
606 let nbodies = Array.length bodies in
607 let make_Fi j =
608 let coind = nbodies-j-1 in
609 mkCoFix (coind,typedbodies)
610 in
611 let closure = List.init nbodies make_Fi in
612 substl closure bodies.(bodynum)
613
614 (************************************************************************)
615 (************************************************************************)
616
617 (* Guard conditions for fix and cofix-points *)
618
619 (* Check if t is a subterm of Rel n, and gives its specification,
620 assuming lst already gives index of
621 subterms with corresponding specifications of recursive arguments *)
622
623 (* A powerful notion of subterm *)
624
625 (* To each inductive definition corresponds an array describing the
626 structure of recursive arguments for each constructor, we call it
627 the recursive spec of the type (it has type recargs vect). For
628 checking the guard, we start from the decreasing argument (Rel n)
629 with its recursive spec. During checking the guardness condition,
630 we collect patterns variables corresponding to subterms of n, each
631 of them with its recursive spec. They are organised in a list lst
632 of type (int * recargs) list which is sorted with respect to the
633 first argument.
634 *)
635
636 (*************************************************************)
637 (* Environment annotated with marks on recursive arguments *)
638
639 (* tells whether it is a strict or loose subterm *)
640 type size = Large | Strict
641
642 (* merging information *)
643 let size_glb s1 s2 =
644 match s1,s2 with
645 Strict, Strict -> Strict
646 | _ -> Large
647
648 (* possible specifications for a term:
649 - Not_subterm: when the size of a term is not related to the
650 recursive argument of the fixpoint
651 - Internally_bound_subterm: when the recursive call is in a subterm
652 of a redex and the recursive argument is bound to a variable
653 which will be instantiated by reducing the redex; the integers
654 refer to the number of redexes stacked, with 1 counting for the
655 variables bound at head in the body of the fix (as e.g. [x] in
656 [fix f n := fun x => f x]); there may be several such indices
657 because [match] subterms may have combine several results;
658 - Subterm: when the term is a subterm of the recursive argument
659 the wf_paths argument specifies which subterms are recursive;
660 the [int list] is used in the [match] case where one branch of
661 the [match] might be a subterm but (an arbitrary number of)
662 others are calls to bound variables
663 - Dead_code: when the term has been built by elimination over an
664 empty type
665 *)
666
667 type subterm_spec =
668 Subterm of (Int.Set.t * size * wf_paths)
669 | Dead_code
670 | Not_subterm
671 | Internally_bound_subterm of Int.Set.t
672
673 let is_norec_path t = match Rtree.dest_head t with
674 | Norec -> true
675 | Mrec _ -> false
676 | exception (Failure _) -> false
677
678 let inter_recarg r1 r2 = if eq_recarg r1 r2 then Some r1 else None
679
680 let inter_wf_paths = Rtree.inter Declareops.eq_recarg inter_recarg Norec
681
682 let incl_wf_paths = Rtree.incl Declareops.eq_recarg inter_recarg Norec
683
684 let spec_of_tree internal t =
685 if is_norec_path t
686 then Not_subterm
687 else Subterm (internal, Strict, t)
688
689 let merge_internal_subterms l1 l2 =
690 Int.Set.union l1 l2
691
692 let inter_spec s1 s2 =
693 match s1, s2 with
694 | _, Dead_code -> s1
695 | Dead_code, _ -> s2
696 | Not_subterm, _ -> s1
697 | _, Not_subterm -> s2
698 | Internally_bound_subterm l1, Internally_bound_subterm l2 -> Internally_bound_subterm (merge_internal_subterms l1 l2)
699 | Subterm (l1,a1,t1), Internally_bound_subterm l2 -> Subterm (merge_internal_subterms l1 l2,a1,t1)
700 | Internally_bound_subterm l1, Subterm (l2,a2,t2) -> Subterm (merge_internal_subterms l1 l2,a2,t2)
701 | Subterm (l1,a1,t1), Subterm (l2,a2,t2) ->
702 Subterm (merge_internal_subterms l1 l2, size_glb a1 a2, inter_wf_paths t1 t2)
703
704 let subterm_spec_glb =
705 Array.fold_left inter_spec Dead_code
706
707 type guard_env =
708 { env : env;
709 (* dB of last fixpoint *)
710 rel_min : int;
711 (* dB of variables denoting subterms *)
712 genv : subterm_spec Lazy.t list;
713 }
714
715 let make_renv env recarg tree =
716 { env = env;
717 rel_min = recarg+2; (* recarg = 0 ==> Rel 1 -> recarg; Rel 2 -> fix *)
718 genv = [Lazy.from_val(Subterm(Int.Set.empty, Large,tree))] }
719
720 let push_var renv (x,ty,spec) =
721 { env = push_rel (LocalAssum (x,ty)) renv.env;
722 rel_min = renv.rel_min+1;
723 genv = spec:: renv.genv }
724
725 let push_let renv (x,c,ty,spec) =
726 { env = push_rel (LocalDef (x,c,ty)) renv.env;
727 rel_min = renv.rel_min+1;
728 genv = spec:: renv.genv }
729
730 let assign_var_spec renv (i,spec) =
731 { renv with genv = List.assign renv.genv (i-1) spec }
732
733 let push_var_renv renv n (x,ty) =
734 let spec = Lazy.from_val (if n >= 1 then Internally_bound_subterm (Int.Set.singleton n) else Not_subterm) in
735 push_var renv (x,ty,spec)
736
737 (* Fetch recursive information about a variable p *)
738 let subterm_var p renv =
739 try Lazy.force (List.nth renv.genv (p-1))
740 with Failure _ | Invalid_argument _ -> (* outside context of the fixpoint *) Not_subterm
741
742 let push_ctxt_renv renv ctxt =
743 let n = Context.Rel.length ctxt in
744 { env = push_rel_context ctxt renv.env;
745 rel_min = renv.rel_min+n;
746 genv = iterate (fun ge -> lazy Not_subterm::ge) n renv.genv }
747
748 let push_fix_renv renv (_,v,_ as recdef) =
749 let n = Array.length v in
750 { env = push_rec_types recdef renv.env;
751 rel_min = renv.rel_min+n;
752 genv = iterate (fun ge -> lazy Not_subterm::ge) n renv.genv }
753
754 type fix_check_result =
755 | NeedReduce of env * fix_guard_error
756 | NoNeedReduce
757
758 (* Definition and manipulation of the stack *)
759 type stack_element =
760 (* arguments in the evaluation stack *)
761 (* [constr] is typed in [guard_env] and [int] is the number of
762 binders added in the current env on top of [guard_env.env] *)
763 | SClosure of fix_check_result * guard_env * int * constr
764 (* arguments applied to a "match": only their spec traverse the match *)
765 | SArg of subterm_spec Lazy.t
766
767 let (|||) x y = match x with
768 | NeedReduce _ -> x
769 | NoNeedReduce -> y
770
771 let rec needreduce_of_stack = function
772 | [] -> NoNeedReduce
773 | SArg _ :: l -> needreduce_of_stack l
774 | SClosure (needreduce,_,_,_) :: l -> needreduce ||| needreduce_of_stack l
775
776 let redex_level rs = List.length rs
777
778 let push_stack_closure renv needreduce c stack =
779 (SClosure (needreduce, renv, 0, c)) :: stack
780
781 let push_stack_closures renv l stack =
782 List.fold_right (push_stack_closure renv NoNeedReduce) l stack
783
784 let push_stack_args l stack =
785 List.fold_right (fun spec stack -> SArg spec :: stack) l stack
786
787 let lift_stack k =
788 List.map (function
789 | SClosure (needreduce,s,n,c) -> SClosure (needreduce,s,n+k,c)
790 | x -> x)
791
792 let lift1_stack = lift_stack 1
793
794 (******************************)
795 (* {6 Computing the recursive subterms of a term (propagation of size
796 information through Cases).} *)
797
798 let lookup_subterms env ind =
799 let (_,mip) = lookup_mind_specif env ind in
800 mip.mind_recargs
801
802 let match_inductive ind ra =
803 match ra with
804 | Mrec (RecArgInd i) -> Ind.CanOrd.equal ind i
805 | Norec | Mrec (RecArgPrim _) -> false
806
807 (* In {match c as z in ci y_s return P with | C_i x_s => t end}
808 [branches_specif renv c_spec ci] returns an array of x_s specs knowing
809 c_spec. *)
810 let branches_specif renv c_spec ci =
811 let car =
812 (* We fetch the regular tree associated to the inductive of the match.
813 This is just to get the number of constructors (and constructor
814 arities) that fit the match branches without forcing c_spec.
815 Note that c_spec might be more precise than [v] below, because of
816 nested inductive types. *)
817 let (_,mip) = lookup_mind_specif renv.env ci.ci_ind in
818 let tree = Rtree.Kind.make mip.mind_recargs in
819 match Rtree.Kind.kind tree with
820 | Rtree.Kind.Node (_, v) -> Array.map Array.length v
821 | Rtree.Kind.Var _ -> assert false
822 in
823 let subterms = lazy begin match Lazy.force c_spec with
824 | Subterm (_, _, t) -> dest_subterms t
825 | Dead_code | Internally_bound_subterm _ | Not_subterm -> assert false
826 end in
827 Array.mapi
828 (fun i nca -> (* i+1-th cstructor has arity nca *)
829 let lvra = lazy
830 (match Lazy.force c_spec with
831 Subterm (internal,_,t) when match_inductive ci.ci_ind (dest_recarg t) ->
832 let vra = Array.of_list (Lazy.force subterms).(i) in
833 assert (Int.equal nca (Array.length vra));
834 Array.map (spec_of_tree internal) vra
835 | Dead_code -> Array.make nca Dead_code
836 | Internally_bound_subterm _ as x -> Array.make nca x
837 | Subterm _ | Not_subterm -> Array.make nca Not_subterm) in
838 List.init nca (fun j -> lazy (Lazy.force lvra).(j)))
839 car
840
841 let check_inductive_codomain ?evars env p =
842 let absctx, ar = whd_decompose_lambda_decls ?evars env p in
843 let env = push_rel_context absctx env in
844 let arctx, s = whd_decompose_prod_decls ?evars env ar in
845 let env = push_rel_context arctx env in
846 let i,_l' = decompose_app (whd_all ?evars env s) in
847 isInd i
848
849 (* The following functions are almost duplicated from indtypes.ml, except
850 that they carry here a poorer environment (containing less information). *)
851 let ienv_push_var (env, lra) (x,a,ra) =
852 (push_rel (LocalAssum (x,a)) env, (Norec,ra)::lra)
853
854 let ienv_push_inductive ?evars (env, ra_env) ((mind,u),lpar) =
855 let mib = Environ.lookup_mind mind env in
856 let ntypes = Declareops.mind_ntypes mib in
857 let push_ind mip env =
858 let r = relevance_of_ind_body mip u in
859 let anon = Context.make_annot Anonymous r in
860 let decl = LocalAssum (anon, hnf_prod_applist ?evars env (type_of_inductive ((mib,mip),u)) lpar) in
861 push_rel decl env
862 in
863 let env = Array.fold_right push_ind mib.mind_packets env in
864 let rc = Array.mapi (fun j t -> Mrec (RecArgInd (mind,j)),t) (Rtree.mk_rec_calls ntypes) in
865 let lra_ind = Array.rev_to_list rc in
866 let ra_env = List.map (fun (r,t) -> (r,Rtree.lift ntypes t)) ra_env in
867 (env, lra_ind @ ra_env)
868
869 let rec ienv_decompose_prod ?evars (env,_ as ienv) n c =
870 if Int.equal n 0 then (ienv,c) else
871 let c' = whd_all ?evars env c in
872 match kind c' with
873 Prod(na,a,b) ->
874 let ienv' = ienv_push_var ienv (na,a,mk_norec) in
875 ienv_decompose_prod ?evars ienv' (n-1) b
876 | _ -> assert false
877
878 (* This removes global parameters of the inductive types in lc (for
879 nested inductive types only ) *)
880 let dummy_univ = Level.(make (UGlobal.make (DirPath.make [Id.of_string "implicit"]) "" 0))
881 let dummy_implicit_sort = mkType (Universe.make dummy_univ)
882 let lambda_implicit n a =
883 let anon = Context.make_annot Anonymous Sorts.Relevant in
884 let lambda_implicit a = mkLambda (anon, dummy_implicit_sort, a) in
885 iterate lambda_implicit n a
886
887 let abstract_mind_lc ntyps npars mind lc =
888 let lc = Array.map (fun (ctx, c) -> Term.it_mkProd_or_LetIn c ctx) lc in
889 let rec replace_ind k c =
890 let hd, args = decompose_app_list c in
891 match kind hd with
892 | Ind ((mind',i),_) when MutInd.CanOrd.equal mind mind' ->
893 let rec drop_params n = function
894 | _ :: args when n > 0 -> drop_params (n-1) args
895 | args -> lambda_implicit n (Term.applist (mkRel (ntyps+n+k-i), List.Smart.map (replace_ind (n+k)) args))
896 in
897 drop_params npars args
898 | _ -> map_with_binders succ replace_ind k c
899 in
900 Array.map (replace_ind 0) lc
901
902 let is_primitive_positive_container env c =
903 match (Environ.retroknowledge env).Retroknowledge.retro_array with
904 | Some c' when QConstant.equal env c c' -> true
905 | _ -> false
906
907 module Cache :
908 sig
909 type t
910 val create : unit -> t
911 val get_inductive_subterms : MutInd.t -> mutual_inductive_body -> t -> wf_paths list array array
912 end =
913 struct
914 type ans = wf_paths list array array
915 type t = ans Mindmap_env.t ref
916 let create () = ref Mindmap_env.empty
917 let get_inductive_subterms mind mib cache = match Mindmap_env.find_opt mind !cache with
918 | None ->
919 let ans = Array.map (fun mip -> dest_subterms mip.mind_recargs) mib.mind_packets in
920 let () = cache := Mindmap_env.add mind ans !cache in
921 ans
922 | Some ans -> ans
923 end
924
925 (* [get_recargs_approx env tree ind args] builds an approximation of the recargs
926 tree for ind, knowing args. The argument tree is used to know when candidate
927 nested types should be traversed, pruning the tree otherwise. This code is very
928 close to check_positive in indtypes.ml, but does no positivity check and does not
929 compute the number of recursive arguments. *)
930 let get_recargs_approx cache ?evars env tree ind args =
931 let rec build_recargs (env, ra_env as ienv) tree c =
932 let x,largs = decompose_app_list (whd_all ?evars env c) in
933 match kind x with
934 | Prod (na,b,d) ->
935 assert (List.is_empty largs);
936 build_recargs (ienv_push_var ienv (na, b, mk_norec)) tree d
937 | Rel k ->
938 (* Free variables are allowed and assigned Norec *)
939 (try snd (List.nth ra_env (k-1))
940 with Failure _ | Invalid_argument _ -> mk_norec)
941 | Ind ind_kn ->
942 (* When the inferred tree allows it, we consider that we have a potential
943 nested inductive type *)
944 begin match dest_recarg tree with
945 | Mrec (RecArgInd ind') when QInd.equal env (fst ind_kn) ind' ->
946 build_recargs_nested ienv tree (ind_kn, largs)
947 | Norec | Mrec _ -> mk_norec
948 end
949 | Const (c,_) when is_primitive_positive_container env c ->
950 begin match dest_recarg tree with
951 | Mrec (RecArgPrim c') when QConstant.equal env c c' ->
952 build_recargs_nested_primitive ienv tree (c, largs)
953 | Norec | Mrec _ -> mk_norec
954 end
955 | _err ->
956 mk_norec
957
958 and build_recargs_nested (env,_ra_env as ienv) tree (((mind,i),u), largs) =
959 (* If the inferred tree already disallows recursion, no need to go further *)
960 if is_norec_path tree then tree
961 else
962 let mib = Environ.lookup_mind mind env in
963 let nonrecpar = mib.mind_nparams - mib.mind_nparams_rec in
964 let (lpar,_) = List.chop mib.mind_nparams_rec largs in
965 let auxntyp = Declareops.mind_ntypes mib in
966 (* Extends the environment with a variable corresponding to
967 the inductive def *)
968 let (env',_ as ienv') = ienv_push_inductive ?evars ienv ((mind,u),lpar) in
969 (* Parameters expressed in env' *)
970 let lpar' = List.map (lift auxntyp) lpar in
971 (* In case of mutual inductive types, we use the recargs tree which was
972 computed statically. This is fine because nested inductive types with
973 mutually recursive containers are not supported. *)
974 let trees =
975 if Int.equal auxntyp 1 then [|dest_subterms tree|]
976 else Cache.get_inductive_subterms mind mib cache
977 in
978 let mk_irecargs j mip =
979 (* The nested inductive type with parameters removed *)
980 let auxlcvect = abstract_mind_lc auxntyp mib.mind_nparams_rec mind mip.mind_nf_lc in
981 let paths = Array.mapi
982 (fun k c ->
983 let c' = hnf_prod_applist ?evars env' c lpar' in
984 (* skip non-recursive parameters *)
985 let (ienv',c') = ienv_decompose_prod ?evars ienv' nonrecpar c' in
986 build_recargs_constructors ienv' trees.(j).(k) c')
987 auxlcvect
988 in
989 mk_paths (Mrec (RecArgInd (mind,j))) paths
990 in
991 let irecargs = Array.mapi mk_irecargs mib.mind_packets in
992 (Rtree.mk_rec irecargs).(i)
993
994 and build_recargs_nested_primitive (env, ra_env) tree (c, largs) =
995 if is_norec_path tree then tree
996 else
997 let ntypes = 1 in (* Primitive types are modelled by non-mutual inductive types *)
998 let ra_env = List.map (fun (r,t) -> (r,Rtree.lift ntypes t)) ra_env in
999 let ienv = (env, ra_env) in
1000 let paths = List.map2 (build_recargs ienv) (dest_subterms tree).(0) largs in
1001 let recargs = [| mk_paths (Mrec (RecArgPrim c)) [| paths |] |] in
1002 (Rtree.mk_rec recargs).(0)
1003
1004 and build_recargs_constructors ienv trees c =
1005 let rec recargs_constr_rec (env,_ra_env as ienv) trees lrec c =
1006 let x,largs = decompose_app_list (whd_all ?evars env c) in
1007 match kind x with
1008
1009 | Prod (na,b,d) ->
1010 let () = assert (List.is_empty largs) in
1011 let recarg = build_recargs ienv (List.hd trees) b in
1012 let ienv' = ienv_push_var ienv (na,b,mk_norec) in
1013 recargs_constr_rec ienv' (List.tl trees) (recarg::lrec) d
1014 | _hd ->
1015 List.rev lrec
1016 in
1017 recargs_constr_rec ienv trees [] c
1018 in
1019 (* starting with ra_env = [] seems safe because any unbounded Rel will be
1020 assigned Norec *)
1021 build_recargs_nested (env,[]) tree (ind, args)
1022
1023 (* Check that the parameter arguments of an inductive type do not mention some
1024 variable range. This is used as a fast-path when casting recursive trees
1025 against a commutative cut: indices are irrelevant for the tree
1026 computation in {!get_recargs_approx}. *)
1027 let has_constant_parameters env nvars k ((mind, _), _) args =
1028 let mib = Environ.lookup_mind mind env in
1029 let auxnpar = mib.mind_nparams_rec in
1030 let (lpar, _) = List.chop auxnpar args in
1031 List.for_all (fun c -> noccur_with_meta (1 + k) (nvars + k) c) lpar
1032
1033 (* [restrict_spec env spec p] restricts the size information in spec to what is
1034 allowed to flow out of a match with predicate p in environment env. *)
1035 let restrict_spec cache ?evars env spec p =
1036 match spec with
1037 | Not_subterm | Internally_bound_subterm _ -> spec
1038 | _ ->
1039 let absctx, ar = whd_decompose_lambda_decls ?evars env p in
1040 let absctxlen = Context.Rel.length absctx in
1041 (* Optimization: if the predicate is not dependent, no restriction is needed
1042 and we avoid building the recargs tree. *)
1043 if noccur_with_meta 1 absctxlen ar then spec
1044 else
1045 let env = push_rel_context absctx env in
1046 let arctx, s = whd_decompose_prod ?evars env ar in
1047 let env = push_rel_context arctx env in
1048 let i,args = decompose_app_list (whd_all ?evars env s) in
1049 match kind i with
1050 | Ind i ->
1051 if has_constant_parameters env absctxlen (List.length arctx) i args then spec
1052 else begin match spec with
1053 | Dead_code -> spec
1054 | Subterm (l, st, tree) ->
1055 let recargs = get_recargs_approx cache ?evars env tree i args in
1056 let tree = inter_wf_paths tree recargs in
1057 Subterm (l, st, tree)
1058 | _ -> assert false
1059 end
1060 | _ -> Not_subterm
1061
1062 (* [filter_stack_domain env spec p] restricts the size information in stack to
1063 what is allowed to enter under a match with predicate p in environment env. *)
1064 let filter_stack_domain cache stack_element_specif set_iota_specif ?evars env p stack =
1065 let absctx, ar = Term.decompose_lambda_decls p in
1066 let absctxlen = Context.Rel.length absctx in
1067 (* Optimization: if the predicate is not dependent, no restriction is needed
1068 and we avoid building the recargs tree. *)
1069 if noccur_with_meta 1 absctxlen ar then stack
1070 else
1071 let env = push_rel_context absctx env in
1072 let rec filter_stack env k ar stack = match stack with
1073 | [] -> []
1074 | elt :: stack' ->
1075 let t = whd_all ?evars env ar in
1076 match kind t with
1077 | Prod (n, a, c0) ->
1078 let d = LocalAssum (n, a) in
1079 let ctx, a = whd_decompose_prod ?evars env a in
1080 let env = push_rel_context ctx env in
1081 let ty, args = decompose_app_list (whd_all ?evars env a) in
1082 let elt = match kind ty with
1083 | Ind ind ->
1084 let spec = stack_element_specif cache ?evars elt in
1085 if has_constant_parameters env absctxlen (k + List.length ctx) ind args then SArg spec
1086 else
1087 let sarg = lazy begin match Lazy.force spec with
1088 | Not_subterm | Dead_code | Internally_bound_subterm _ as spec -> spec
1089 | Subterm (l, s, tree) ->
1090 let recargs = get_recargs_approx cache ?evars env tree ind args in
1091 let tree = inter_wf_paths tree recargs in
1092 Subterm (l, s, tree)
1093 end in
1094 SArg sarg
1095 | _ -> SArg (set_iota_specif (lazy Not_subterm))
1096 in
1097 elt :: filter_stack (push_rel d env) (k + 1) c0 stack'
1098 | _ ->
1099 List.map (fun _ -> SArg (set_iota_specif (lazy Not_subterm))) stack
1100 in
1101 filter_stack env 0 ar stack
1102
1103 (* [subterm_specif renv t] computes the recursive structure of [t] and
1104 compare its size with the size of the initial recursive argument of
1105 the fixpoint we are checking. [renv] collects such information
1106 about variables.
1107 *)
1108
1109 let rec subterm_specif cache ?evars renv stack t =
1110 (* maybe reduction is not always necessary! *)
1111 let f,l = decompose_app_list (whd_all ?evars renv.env t) in
1112 match kind f with
1113 | Rel k -> subterm_var k renv
1114 | Case (ci, u, pms, p, iv, c, lbr) -> (* iv ignored: it's just a cache *)
1115 let (ci, (p,_), _iv, c, lbr) = expand_case renv.env (ci, u, pms, p, iv, c, lbr) in
1116 let stack' = push_stack_closures renv l stack in
1117 let stack' = filter_stack_domain cache stack_element_specif Fun.id ?evars renv.env p stack' in
1118 let cases_spec =
1119 branches_specif renv (lazy_subterm_specif cache ?evars renv [] c) ci
1120 in
1121 let stl =
1122 Array.mapi (fun i br' ->
1123 let stack_br = push_stack_args (cases_spec.(i)) stack' in
1124 subterm_specif cache ?evars renv stack_br br')
1125 lbr in
1126 let spec = subterm_spec_glb stl in
1127 restrict_spec cache ?evars renv.env spec p
1128
1129 | Fix ((recindxs,i),(_,typarray,bodies as recdef)) ->
1130 (* when proving that the fixpoint f(x)=e is less than n, it is enough
1131 to prove that e is less than n assuming f is less than n
1132 furthermore when f is applied to a term which is strictly less than
1133 n, one may assume that x itself is strictly less than n
1134 *)
1135 if not (check_inductive_codomain ?evars renv.env typarray.(i)) then Not_subterm
1136 else
1137 let (ctxt,clfix) = whd_decompose_prod ?evars renv.env typarray.(i) in
1138 let oind =
1139 let env' = push_rel_context ctxt renv.env in
1140 try Some(fst (find_inductive ?evars env' clfix))
1141 with Not_found -> None in
1142 (match oind with
1143 None -> Not_subterm (* happens if fix is polymorphic *)
1144 | Some (ind, _) ->
1145 let nbfix = Array.length typarray in
1146 let recargs = lookup_subterms renv.env ind in
1147 (* pushing the fixpoints *)
1148 let renv' = push_fix_renv renv recdef in
1149 let renv' =
1150 (* Why Strict here ? To be general, it could also be
1151 Large... *)
1152 assign_var_spec renv'
1153 (nbfix-i, lazy (Subterm(Int.Set.empty,Strict,recargs))) in
1154 let decrArg = recindxs.(i) in
1155 let theBody = bodies.(i) in
1156 let nbOfAbst = decrArg+1 in
1157 let sign,strippedBody = whd_decompose_lambda_n_assum ?evars renv.env nbOfAbst theBody in
1158 (* pushing the fix parameters *)
1159 let stack' = push_stack_closures renv l stack in
1160 let renv'' = push_ctxt_renv renv' sign in
1161 let renv'' =
1162 if List.length stack' < nbOfAbst then renv''
1163 else
1164 let decrArg = List.nth stack' decrArg in
1165 let arg_spec = stack_element_specif cache ?evars decrArg in
1166 assign_var_spec renv'' (1, arg_spec) in
1167 subterm_specif cache ?evars renv'' [] strippedBody)
1168
1169 | Lambda (x,a,b) ->
1170 let () = assert (List.is_empty l) in
1171 let spec,stack' = extract_stack cache ?evars stack in
1172 subterm_specif cache ?evars (push_var renv (x,a,spec)) stack' b
1173
1174 (* Metas and evars are considered OK *)
1175 | (Meta _|Evar _) -> Dead_code
1176
1177 | Proj (p, _, c) ->
1178 let subt = subterm_specif cache ?evars renv stack c in
1179 (match subt with
1180 | Subterm (internal, _s, wf) ->
1181 (* We take the subterm specs of the constructor of the record *)
1182 let wf_args = (dest_subterms wf).(0) in
1183 (* We extract the tree of the projected argument *)
1184 let n = Projection.arg p in
1185 spec_of_tree internal (List.nth wf_args n)
1186 | Dead_code -> Dead_code
1187 | Not_subterm -> Not_subterm
1188 | Internally_bound_subterm n -> Internally_bound_subterm n)
1189
1190 | Const c ->
1191 begin try
1192 let _ = Environ.constant_value_in renv.env c in Not_subterm
1193 with
1194 | NotEvaluableConst (IsPrimitive (_u,op)) when List.length l >= CPrimitives.arity op ->
1195 primitive_specif cache ?evars renv op l
1196 | NotEvaluableConst _ -> Not_subterm
1197 end
1198
1199 | Var _ | Sort _ | Cast _ | Prod _ | LetIn _ | App _ | Ind _
1200 | Construct _ | CoFix _ | Int _ | Float _ | String _
1201 | Array _ -> Not_subterm
1202
1203
1204 (* Other terms are not subterms *)
1205
1206 and lazy_subterm_specif cache ?evars renv stack t =
1207 lazy (subterm_specif cache ?evars renv stack t)
1208
1209 and stack_element_specif cache ?evars = function
1210 | SClosure (_, h_renv, _, h) -> lazy_subterm_specif cache ?evars h_renv [] h
1211 | SArg x -> x
1212
1213 and extract_stack cache ?evars = function
1214 | [] -> Lazy.from_val Not_subterm, []
1215 | elt :: l -> stack_element_specif cache ?evars elt, l
1216
1217 and primitive_specif cache ?evars renv op args =
1218 let open CPrimitives in
1219 match op with
1220 | Arrayget | Arraydefault ->
1221 (* t.[i] and default t can be seen as strict subterms of t, with a
1222 potentially nested rectree. *)
1223 let arg = List.nth args 1 in (* the result is a strict subterm of the second argument *)
1224 let subt = subterm_specif cache ?evars renv [] arg in
1225 begin match subt with
1226 | Subterm (internal, _s, wf) ->
1227 let wf_args = (dest_subterms wf).(0) in
1228 spec_of_tree internal (List.nth wf_args 0) (* first and only parameter of `array` *)
1229 | Dead_code -> Dead_code
1230 | Not_subterm -> Not_subterm
1231 | Internally_bound_subterm n -> Internally_bound_subterm n
1232 end
1233 | _ -> Not_subterm
1234
1235 let set_iota_specif nr spec =
1236 lazy (match Lazy.force spec with
1237 | Not_subterm -> if nr >= 1 then Internally_bound_subterm (Int.Set.singleton nr) else Not_subterm
1238 | spec -> spec)
1239
1240 (************************************************************************)
1241
1242 exception FixGuardError of env * fix_guard_error
1243
1244 let illegal_rec_call renv fx = function
1245 | SClosure (_,arg_renv,_,arg) ->
1246 let le_lt_vars =
1247 lazy (let (_,le_vars,lt_vars) =
1248 List.fold_left
1249 (fun (i,le,lt) sbt ->
1250 match Lazy.force sbt with
1251 (Subterm(_,Strict,_) | Dead_code) -> (i+1, le, i::lt)
1252 | (Subterm(_,Large,_)) -> (i+1, i::le, lt)
1253 | _ -> (i+1, le ,lt))
1254 (1,[],[]) renv.genv in
1255 (le_vars,lt_vars)) in
1256 RecursionOnIllegalTerm(fx,(arg_renv.env, arg),le_lt_vars)
1257 | SArg _ ->
1258 (* Typically the case of a recursive call encapsulated under a
1259 rewriting before been applied to the parameter of a constructor *)
1260 NotEnoughArgumentsForFixCall fx
1261
1262 let set_need_reduce_one env nr err rs =
1263 let mr = List.length rs in
1264 let rs1, rs2 = List.chop (mr-nr) rs in
1265 let _, rs2 = List.sep_first rs2 in
1266 rs1 @ NeedReduce (env, err) :: rs2
1267
1268 let set_need_reduce env l err rs =
1269 Int.Set.fold (fun n -> set_need_reduce_one env n err) l rs
1270
1271 let set_need_reduce_top env err rs =
1272 set_need_reduce_one env (List.length rs) err rs
1273
1274 type check_subterm_result =
1275 | InvalidSubterm
1276 | NeedReduceSubterm of Int.Set.t (* empty = NoNeedReduce *)
1277
1278 (* Check term c can be applied to one of the mutual fixpoints. *)
1279 let check_is_subterm x tree =
1280 match Lazy.force x with
1281 | Subterm (need_reduce,Strict,tree') ->
1282 if incl_wf_paths tree tree' then NeedReduceSubterm need_reduce
1283 else InvalidSubterm
1284 | Dead_code -> NeedReduceSubterm Int.Set.empty
1285 | Not_subterm | Subterm (_,Large,_) -> InvalidSubterm
1286 | Internally_bound_subterm l -> NeedReduceSubterm l
1287
1288 let find_uniform_parameters recindx nargs bodies =
1289 let nbodies = Array.length bodies in
1290 (* Ensure that the structural argument is not uniform,
1291 so that it stays in [non_absorbed_stack] *)
1292 let min_indx = Array.fold_left min nargs recindx in
1293 (* We work only on the i-th body but are in the context of n bodies *)
1294 let rec aux i k nuniformparams c =
1295 let f, l = decompose_app_list c in
1296 match kind f with
1297 | Rel n ->
1298 let fold accu c = fold_constr_with_binders succ (aux i) k accu c in
1299 let nuniformparams = List.fold_left fold nuniformparams l in
1300 (* A recursive reference to any one of the mutual fixpoints *)
1301 if n > k && n <= k + nbodies then
1302 List.fold_left_until (fun j arg ->
1303 if j >= nuniformparams then Stop nuniformparams else
1304 match kind arg with
1305 | Rel m when Int.equal m (k - j) ->
1306 (* a reference to the j-th parameter *)
1307 Cont (j+1)
1308 | _ ->
1309 (* not a parameter: this puts a bound on the size of an extrudable prefix of uniform arguments *)
1310 Stop j
1311 ) 0 l
1312 else
1313 nuniformparams
1314 | _ -> fold_constr_with_binders succ (aux i) k nuniformparams c
1315 in
1316 Array.fold_left_i (fun i -> aux i 0) min_indx bodies
1317
1318 (** Given a fixpoint [fix f x y z n {struct n} := phi(f x y u t, ..., f x y u' t')]
1319 with [z] not uniform we build in context [x:A, y:B(x), z:C(x,y)] a term
1320 [fix f z n := phi(f u t, ..., f u' t')], say [psi], of some type
1321 [forall (z:C(x,y)) (n:I(x,y,z)), T(x,y,z,n)], so that
1322 [fun x y z => psi z] is of same type as the original term *)
1323
1324 let drop_uniform_parameters nuniformparams bodies =
1325 let nbodies = Array.length bodies in
1326 let rec aux i k c =
1327 let f, l = decompose_app_list c in
1328 match kind f with
1329 | Rel n ->
1330 let l = List.map (fun c -> aux i k c) l in
1331 (* A recursive reference to the i-th body *)
1332 if Int.equal n (nbodies + k - i) then
1333 let new_args = List.skipn nuniformparams l in
1334 Term.applist (f, new_args)
1335 else Term.applist (f, l)
1336 | _ -> map_with_binders succ (aux i) k c
1337 in
1338 Array.mapi (fun i -> aux i 0) bodies
1339
1340 let filter_fix_stack_domain cache ?evars nr decrarg stack nuniformparams =
1341 let rec aux i nuniformparams stack =
1342 match stack with
1343 | [] -> []
1344 | a :: stack ->
1345 let uniform, nuniformparams = if nuniformparams = 0 then false, 0 else true, nuniformparams -1 in
1346 let a =
1347 if uniform then a
1348 else if Int.equal i decrarg then SArg (stack_element_specif cache ?evars a)
1349 (* We forget the needreduce status of the structural argument here,
1350 since it's checked in [non_absorbed_stack]. *)
1351 else
1352 (* deactivate the status of non-uniform parameters since we
1353 cannot guarantee that they are preserve in the recursive
1354 calls *)
1355 SArg (set_iota_specif nr (lazy Not_subterm)) in
1356 a :: aux (i+1) nuniformparams stack
1357 in aux 0 nuniformparams stack
1358
1359 let pop_argument cache ?evars needreduce renv elt stack x a b =
1360 match needreduce, elt with
1361 | NoNeedReduce, SClosure (NoNeedReduce, _, n, c) ->
1362 (* Neither function nor args have rec calls on internally bound variables *)
1363 let spec = stack_element_specif cache ?evars elt in
1364 (* Thus, args do not a priori require to be rechecked, so we push a let *)
1365 (* maybe the body of the let will have to be locally expanded though, see Rel case *)
1366 push_let renv (x,lift n c,a,spec), lift1_stack stack, b
1367 | _, SClosure (_, _, n, c) ->
1368 (* Either function or args have rec call on internally bound variables *)
1369 renv, stack, subst1 (lift n c) b
1370 | _, SArg spec ->
1371 (* Going down a case branch *)
1372 push_var renv (x,a,spec), lift1_stack stack, b
1373
1374 let judgment_of_fixpoint (_, types, bodies) =
1375 Array.map2 (fun typ body -> { uj_val = body ; uj_type = typ }) types bodies
1376
1377 let rec reduce_and_contract_cofix ?evars env c =
1378 let c = whd_all ?evars env c in
1379 let hd, args = decompose_app c in
1380 match kind hd with
1381 | CoFix cofix ->
1382 reduce_and_contract_cofix ?evars env (mkApp (contract_cofix cofix, args))
1383 | _ -> hd, args
1384
1385 (* Check if [def] is a guarded fixpoint body with decreasing arg.
1386 given [recpos], the decreasing arguments of each mutually defined
1387 fixpoint. *)
1388 let check_one_fix cache ?evars renv recpos trees def =
1389 let nfi = Array.length recpos in
1390
1391 (* Checks if [t] only make valid recursive calls
1392 [stack] is the list of constructor's argument specification and
1393 arguments that will be applied after reduction.
1394 example u in t where we have (match .. with |.. => t end) u;
1395 [rs] is the stack of redexes traversed w/o having been triggered *)
1396 let rec check_rec_call_stack renv stack rs t =
1397 match kind t with
1398 | App (f,args) ->
1399 begin
1400 let rs, stack =
1401 Array.fold_right (fun a (rs,stack) ->
1402 let needreduce,rs = check_rec_call renv rs a in
1403 let stack = push_stack_closure renv needreduce a stack in
1404 (rs,stack)) args (rs,stack)
1405 in
1406 check_rec_call_stack renv stack rs f
1407 end
1408
1409 | Rel p ->
1410 let rs =
1411 (* Test if [p] is a fixpoint (recursive call) *)
1412 if renv.rel_min <= p && p < renv.rel_min+nfi then
1413 (* the position of the invoked fixpoint: *)
1414 let glob = renv.rel_min+nfi-1-p in
1415 (* the decreasing arg of the rec call: *)
1416 let np = recpos.(glob) in
1417 if List.length stack <= np then
1418 set_need_reduce_top renv.env (NotEnoughArgumentsForFixCall glob) rs
1419 else
1420 (* Retrieve the expected tree for the argument *)
1421 (* Check the decreasing arg is smaller *)
1422 let z = List.nth stack np in
1423 match check_is_subterm (stack_element_specif cache ?evars z) trees.(glob) with
1424 | NeedReduceSubterm l -> set_need_reduce renv.env l (illegal_rec_call renv glob z) rs
1425 | InvalidSubterm -> raise (FixGuardError (renv.env, illegal_rec_call renv glob z))
1426 else rs
1427 in
1428 check_rec_call_state renv NoNeedReduce stack rs (fun () ->
1429 match lookup_rel p renv.env with
1430 | LocalAssum _ -> None
1431 | LocalDef (_,c,_) -> Some (lift p c, []))
1432
1433 | Case (ci, u, pms, ret, iv, c_0, br) -> (* iv ignored: it's just a cache *)
1434 let (ci, (p,_), _iv, c_0, brs) = expand_case renv.env (ci, u, pms, ret, iv, c_0, br) in
1435 let needreduce_c_0, rs = check_rec_call renv rs c_0 in
1436 let rs = check_inert_subterm_rec_call renv rs p in
1437 (* compute the recarg info for the arguments of each branch *)
1438 let rs' = NoNeedReduce::rs in
1439 let nr = redex_level rs' in
1440 let case_spec =
1441 branches_specif renv (set_iota_specif nr (lazy_subterm_specif cache ?evars renv [] c_0)) ci in
1442 let stack' = filter_stack_domain cache stack_element_specif (set_iota_specif nr) ?evars renv.env p stack in
1443 let rs' =
1444 Array.fold_left_i (fun k rs' br' ->
1445 let stack_br = push_stack_args case_spec.(k) stack' in
1446 check_rec_call_stack renv stack_br rs' br') rs' brs in
1447 let needreduce_br, rs = List.sep_first rs' in
1448 check_rec_call_state renv (needreduce_br ||| needreduce_c_0) stack rs (fun () ->
1449 (* we try hard to reduce the match away by looking for a
1450 constructor in c_0 (we unfold definitions too) *)
1451 let hd, args = reduce_and_contract_cofix ?evars renv.env c_0 in
1452 match kind hd with
1453 | Construct cstr -> Some (apply_branch cstr (Array.to_list args) ci brs, [])
1454 | CoFix _ | Ind _ | Lambda _ | Prod _ | LetIn _
1455 | Sort _ | Int _ | Float _ | String _ | Array _ -> assert false
1456 | Rel _ | Var _ | Const _ | App _ | Case _ | Fix _
1457 | Proj _ | Cast _ | Meta _ | Evar _ -> None)
1458
1459 (* Enables to traverse Fixpoint definitions in a more intelligent
1460 way, ie, the rule :
1461 if - g = fix g (y1:T1)...(yp:Tp) {struct yp} := e &
1462 - f is guarded with respect to the set of pattern variables S
1463 in a1 ... am &
1464 - f is guarded with respect to the set of pattern variables S
1465 in T1 ... Tp &
1466 - ap is a sub-term of the formal argument of f &
1467 - f is guarded with respect to the set of pattern variables
1468 S+{yp} in e
1469 then f is guarded with respect to S in (g a1 ... am).
1470 Eduardo 7/9/98 *)
1471 | Fix ((recindxs,i),(_,typarray,bodies as recdef) as fix) ->
1472 let decrArg = recindxs.(i) in
1473 let nbodies = Array.length bodies in
1474 let rs' = Array.fold_left (check_inert_subterm_rec_call renv) (NoNeedReduce::rs) typarray in
1475 let renv' = push_fix_renv renv recdef in
1476 let nuniformparams = find_uniform_parameters recindxs (List.length stack) bodies in
1477 let bodies = drop_uniform_parameters nuniformparams bodies in
1478 let fix_stack = filter_fix_stack_domain cache ?evars (redex_level rs) decrArg stack nuniformparams in
1479 let fix_stack = if List.length stack > decrArg then List.firstn (decrArg+1) fix_stack else fix_stack in
1480 let stack_this = lift_stack nbodies fix_stack in
1481 let stack_others = lift_stack nbodies (List.firstn nuniformparams fix_stack) in
1482 (* Check guard in the expanded fix *)
1483 let illformed () =
1484 error_ill_formed_rec_body renv.env (Type_errors.FixGuardError (NotEnoughAbstractionInFixBody recindxs.(i)))
1485 (pi1 recdef) i (push_rec_types recdef renv.env)
1486 (judgment_of_fixpoint recdef) in
1487 let rs' = Array.fold_left2_i (fun j rs' recindx body ->
1488 let fix_stack = if Int.equal i j then stack_this else stack_others in
1489 check_nested_fix_body illformed renv' (recindx+1) fix_stack rs' body) rs' recindxs bodies in
1490 let needreduce_fix, rs = List.sep_first rs' in
1491 let absorbed_stack, non_absorbed_stack = List.chop nuniformparams stack in
1492 check_rec_call_state renv needreduce_fix non_absorbed_stack rs (fun () ->
1493 (* we try hard to reduce the fix away by looking for a
1494 constructor in [decrArg] (we unfold definitions too) *)
1495 if List.length stack <= decrArg then None else
1496 match List.nth stack decrArg with
1497 | SArg _ -> (* A match on the way *) None
1498 | SClosure (_,_,n,recArg) ->
1499 let c = whd_all ?evars renv.env (lift n recArg) in
1500 let hd, _ = decompose_app_list c in
1501 match kind hd with
1502 | Construct _ -> Some (contract_fix fix, absorbed_stack)
1503 | CoFix _ | Ind _ | Lambda _ | Prod _ | LetIn _
1504 | Sort _ | Int _ | Float _ | String _
1505 | Array _ -> assert false
1506 | Rel _ | Var _ | Const _ | App _ | Case _ | Fix _
1507 | Proj _ | Cast _ | Meta _ | Evar _ -> None)
1508
1509 | Const (kn,_u as cu) ->
1510 check_rec_call_state renv NoNeedReduce stack rs (fun () ->
1511 if evaluable_constant kn renv.env then Some (constant_value_in renv.env cu, [])
1512 else None)
1513
1514 | Lambda (x,a,b) ->
1515 begin
1516 let needreduce, rs = check_rec_call renv rs a in
1517 match stack with
1518 | elt :: stack ->
1519 let renv, stack, b = pop_argument cache ?evars needreduce renv elt stack x a b in
1520 check_rec_call_stack renv stack rs b
1521 | [] ->
1522 check_rec_call_stack (push_var_renv renv (redex_level rs) (x,a)) [] rs b
1523 end
1524
1525 | Prod (x,a,u) ->
1526 (* Note: we cannot ensure that the stack is empty because
1527 non-accessible branches of "match" expressions can have
1528 arbitrary types (see #17073) *)
1529 let rs = check_inert_subterm_rec_call renv rs a in
1530 (* Note: can recursive calls on [x] be else than inert "dead code"? *)
1531 check_rec_call_stack (push_var_renv renv (redex_level rs) (x,a)) [] rs u
1532
1533 | CoFix (_i,(_,typarray,bodies as recdef)) ->
1534 let rs = Array.fold_left (check_inert_subterm_rec_call renv) rs typarray in
1535 let renv' = push_fix_renv renv recdef in
1536 Array.fold_left (fun rs body ->
1537 let needreduce', rs = check_rec_call renv' rs body in
1538 check_rec_call_state renv needreduce' stack rs (fun _ -> None))
1539 rs bodies
1540
1541 | Ind _ | Construct _ ->
1542 check_rec_call_state renv NoNeedReduce stack rs (fun () -> None)
1543
1544 | Proj (p, _, c) ->
1545 begin
1546 let needreduce', rs = check_rec_call renv rs c in
1547 check_rec_call_state renv needreduce' stack rs (fun () ->
1548 (* we try hard to reduce the proj away by looking for a
1549 constructor in c (we unfold definitions too) *)
1550 let hd, args = reduce_and_contract_cofix ?evars renv.env c in
1551 match kind hd with
1552 | Construct _ -> Some (args.(Projection.npars p + Projection.arg p), [])
1553 | CoFix _ | Ind _ | Lambda _ | Prod _ | LetIn _
1554 | Sort _ | Int _ | Float _ | String _ | Array _ -> assert false
1555 | Rel _ | Var _ | Const _ | App _ | Case _ | Fix _
1556 | Proj _ | Cast _ | Meta _ | Evar _ -> None)
1557 end
1558
1559 | Var id ->
1560 check_rec_call_state renv NoNeedReduce stack rs (fun () ->
1561 let open! Context.Named.Declaration in
1562 match lookup_named id renv.env with
1563 | LocalAssum _ -> None
1564 | LocalDef (_,c,_) -> Some (c, []))
1565
1566 | LetIn (x,c,t,b) ->
1567 let needreduce_c, rs = check_rec_call renv rs c in
1568 let needreduce_t, rs = check_rec_call renv rs t in
1569 begin
1570 match needreduce_of_stack stack ||| needreduce_c ||| needreduce_t with
1571 | NoNeedReduce ->
1572 (* Stack do not require to beta-reduce; let's look if the body of the let needs *)
1573 let spec = lazy_subterm_specif cache ?evars renv [] c in
1574 let stack = lift1_stack stack in
1575 check_rec_call_stack (push_let renv (x,c,t,spec)) stack rs b
1576 | NeedReduce _ -> check_rec_call_stack renv stack rs (subst1 c b)
1577 end
1578
1579 | Cast (c,_,t) ->
1580 let rs = check_inert_subterm_rec_call renv rs t in
1581 let rs = check_rec_call_stack renv stack rs c in
1582 rs
1583
1584 | Sort _ | Int _ | Float _ | String _ ->
1585 (* See [Prod]: we cannot ensure that the stack is empty *)
1586 rs
1587
1588 | Array (_u,t,def,ty) ->
1589 (* See [Prod]: we cannot ensure that the stack is empty *)
1590 let rs = Array.fold_left (check_inert_subterm_rec_call renv) rs t in
1591 let rs = check_inert_subterm_rec_call renv rs def in
1592 let rs = check_inert_subterm_rec_call renv rs ty in
1593 rs
1594
1595 (* l is not checked because it is considered as the meta's context *)
1596 | (Evar _ | Meta _) ->
1597 rs
1598
1599 and check_nested_fix_body illformed renv decr stack rs body =
1600 if Int.equal decr 0 then
1601 check_inert_subterm_rec_call renv rs body
1602 else
1603 match kind (whd_all ?evars renv.env body) with
1604 | Lambda (x,a,body) ->
1605 begin
1606 match stack with
1607 | elt :: stack ->
1608 let rs = check_inert_subterm_rec_call renv rs a in
1609 let renv', stack', body' = pop_argument cache NoNeedReduce renv elt stack x a body in
1610 check_nested_fix_body illformed renv' (decr-1) stack' rs body'
1611 | [] ->
1612 let renv' = push_var_renv renv (redex_level rs) (x,a) in
1613 check_nested_fix_body illformed renv' (decr-1) [] rs body
1614 end
1615 | _ -> illformed ()
1616
1617 and check_rec_call_state renv needreduce_of_head stack rs expand_head =
1618 (* Test if either the head or the stack of a state
1619 needs the state to be reduced before continuing checking *)
1620 match needreduce_of_head ||| needreduce_of_stack stack with
1621 | NoNeedReduce -> rs
1622 | NeedReduce _ as e ->
1623 (* Expand if possible, otherwise, last chance, propagate need
1624 for expansion, in the hope to be eventually erased *)
1625 match expand_head () with
1626 | None -> e :: List.tl rs
1627 | Some (c, stack') -> check_rec_call_stack renv (stack'@stack) rs c
1628
1629 and check_inert_subterm_rec_call renv rs c =
1630 (* Check rec calls of a term which does not interact with its
1631 immediate context and which can be possibly erased at higher
1632 level of the redex stack *)
1633 let need_reduce, rs = check_rec_call renv rs c in
1634 check_rec_call_state renv need_reduce [] rs (fun () -> None)
1635
1636 and check_rec_call renv rs c =
1637 (* either fails if a non guarded call occurs or tells if there is
1638 rec call on a variable bound at the top of [c] and update the
1639 need for reduction in the redex stack with rec calls on
1640 variables bound at higher levels of the redex stack *)
1641 List.sep_first (check_rec_call_stack renv [] (NoNeedReduce::rs) c)
1642
1643 in
1644 let need_reduce, rs = check_rec_call renv [] def in
1645 assert (List.is_empty rs);
1646 match need_reduce with
1647 | NeedReduce (env,err) -> raise (FixGuardError (env,err))
1648 | NoNeedReduce -> ()
1649
1650 let inductive_of_mutfix ?evars ?elim_to env ((nvect,bodynum),(names,types,bodies as recdef)) =
1651 let nbfix = Array.length bodies in
1652 if Int.equal nbfix 0
1653 || not (Int.equal (Array.length nvect) nbfix)
1654 || not (Int.equal (Array.length types) nbfix)
1655 || not (Int.equal (Array.length names) nbfix)
1656 || bodynum < 0
1657 || bodynum >= nbfix
1658 then anomaly (Pp.str "Ill-formed fix term.");
1659 let fixenv = push_rec_types recdef env in
1660 let vdefj = judgment_of_fixpoint recdef in
1661 let raise_err env i err =
1662 error_ill_formed_rec_body env (Type_errors.FixGuardError err) names i fixenv vdefj in
1663 (* Check the i-th definition with recarg k *)
1664 let find_ind i k def =
1665 (* check fi does not appear in the k+1 first abstractions,
1666 gives the type of the k+1-eme abstraction (must be an inductive) *)
1667 let rec check_occur env n def =
1668 match kind (whd_all ?evars env def) with
1669 | Lambda (x,a,b) ->
1670 if noccur_with_meta n nbfix a then
1671 let env' = push_rel (LocalAssum (x,a)) env in
1672 if Int.equal n (k + 1) then
1673 (* get the inductive type of the fixpoint *)
1674 let (mind, _) =
1675 try find_inductive ?evars env a
1676 with Not_found ->
1677 raise_err env i (RecursionNotOnInductiveType a) in
1678 let mib,_ = lookup_mind_specif env (out_punivs mind) in
1679 if mib.mind_finite != Finite then
1680 raise_err env i (RecursionNotOnInductiveType a);
1681 (mind, (env', b))
1682 else check_occur env' (n+1) b
1683 else anomaly ~label:"check_one_fix" (Pp.str "Bad occurrence of recursive call.")
1684 | _ -> raise_err env i (NotEnoughAbstractionInFixBody k)
1685 in
1686 let ((ind, inst), _) as res = check_occur fixenv 1 def in
1687 let _, mip = lookup_mind_specif env ind in
1688 (* recursive sprop means non record with projections -> squashed *)
1689 let () =
1690 if Environ.is_type_in_type env (GlobRef.IndRef ind) then ()
1691 else
1692 let sind = UVars.subst_instance_sort inst mip.mind_sort in
1693 let u = Sorts.univ_of_sort sind in
1694 (* This is an approximation: a [Relevant] variable might be of sort [Prop]
1695 or [Type]. As we only care about the quality, we have to be conservative
1696 here, i.e., every relevant sort (so, [Prop] or above) can be eliminated
1697 into any other relevant sort. *)
1698 let bsort = match names.(i).Context.binder_relevance with
1699 | Irrelevant -> Sorts.sprop
1700 | Relevant -> Sorts.prop
1701 | RelevanceVar q -> Sorts.qsort q u in
1702 let elim_to = match elim_to with
1703 | Some f -> f
1704 | None -> eliminates_to (Environ.qualities env) in
1705 if not (is_allowed_fixpoint elim_to sind bsort) then
1706 raise_err env i @@ FixpointOnNonEliminable (sind, bsort)
1707 in
1708 res
1709 in
1710 (* Do it on every fixpoint *)
1711 let rv = Array.map2_i find_ind nvect bodies in
1712 (Array.map fst rv, Array.map snd rv)
1713
1714
1715 let check_fix ?evars ?elim_to env ((nvect,_),(names,_,bodies as recdef) as fix) =
1716 let cache = Cache.create () in
1717 let (minds, rdef) = inductive_of_mutfix ?evars ?elim_to env fix in
1718 let flags = Environ.typing_flags env in
1719 if flags.check_guarded then
1720 let get_tree (kn,i) =
1721 let mib = Environ.lookup_mind kn env in
1722 mib.mind_packets.(i).mind_recargs
1723 in
1724 let trees = Array.map (fun (mind,_) -> get_tree mind) minds in
1725 for i = 0 to Array.length bodies - 1 do
1726 let (fenv,body) = rdef.(i) in
1727 let renv = make_renv fenv nvect.(i) trees.(i) in
1728 try check_one_fix cache ?evars renv nvect trees body
1729 with FixGuardError (fixenv,err) ->
1730 error_ill_formed_rec_body fixenv (Type_errors.FixGuardError err) names i
1731 (push_rec_types recdef env) (judgment_of_fixpoint recdef)
1732 done
1733 else
1734 ()
1735
1736 (************************************************************************)
1737 (* Co-fixpoints. *)
1738
1739 exception CoFixGuardError of env * cofix_guard_error
1740
1741 let anomaly_ill_typed () =
1742 anomaly ~label:"check_one_cofix" (Pp.str "too many arguments applied to constructor.")
1743
1744 let rec codomain_is_coind ?evars env c =
1745 let b = whd_all ?evars env c in
1746 match kind b with
1747 | Prod (x,a,b) ->
1748 codomain_is_coind ?evars (push_rel (LocalAssum (x,a)) env) b
1749 | _ ->
1750 (try find_coinductive ?evars env b
1751 with Not_found ->
1752 raise (CoFixGuardError (env, CodomainNotInductiveType b)))
1753
1754 let check_one_cofix cache ?evars env nbfix def deftype =
1755 let rec check_rec_call env alreadygrd n tree vlra t =
1756 if not (noccur_with_meta n nbfix t) then
1757 let c,args = decompose_app_list (whd_all ?evars env t) in
1758 match kind c with
1759 | Rel p when n <= p && p < n+nbfix ->
1760 (* recursive call: must be guarded and no nested recursive
1761 call allowed *)
1762 if not alreadygrd then
1763 raise (CoFixGuardError (env,UnguardedRecursiveCall t))
1764 else if not(List.for_all (noccur_with_meta n nbfix) args) then
1765 raise (CoFixGuardError (env,NestedRecursiveOccurrences))
1766 | Construct ((_,i as cstr_kn),_u) ->
1767 let lra = vlra.(i-1) in
1768 let mI = inductive_of_constructor cstr_kn in
1769 let (mib,_mip) = lookup_mind_specif env mI in
1770 let realargs = List.skipn mib.mind_nparams args in
1771 let rec process_args_of_constr = function
1772 | (t::lr), (rar::lrar) ->
1773 if is_norec_path rar then
1774 if noccur_with_meta n nbfix t
1775 then process_args_of_constr (lr, lrar)
1776 else raise (CoFixGuardError
1777 (env,RecCallInNonRecArgOfConstructor t))
1778 else begin
1779 check_rec_call env true n rar (dest_subterms rar) t;
1780 process_args_of_constr (lr, lrar)
1781 end
1782 | [],_ -> ()
1783 | _ -> anomaly_ill_typed ()
1784 in process_args_of_constr (realargs, lra)
1785
1786 | Lambda (x,a,b) ->
1787 let () = assert (List.is_empty args) in
1788 if noccur_with_meta n nbfix a then
1789 let env' = push_rel (LocalAssum (x,a)) env in
1790 check_rec_call env' alreadygrd (n+1) tree vlra b
1791 else
1792 raise (CoFixGuardError (env,RecCallInTypeOfAbstraction a))
1793
1794 | CoFix (_j,(_,varit,vdefs as recdef)) ->
1795 if List.for_all (noccur_with_meta n nbfix) args
1796 then
1797 if Array.for_all (noccur_with_meta n nbfix) varit then
1798 let nbfix = Array.length vdefs in
1799 let env' = push_rec_types recdef env in
1800 (Array.iter (check_rec_call env' alreadygrd (n+nbfix) tree vlra) vdefs;
1801 List.iter (check_rec_call env alreadygrd n tree vlra) args)
1802 else
1803 raise (CoFixGuardError (env,RecCallInTypeOfDef c))
1804 else
1805 raise (CoFixGuardError (env,UnguardedRecursiveCall c))
1806
1807 | Case (ci, u, pms, p, iv, tm, br) -> (* iv ignored: just a cache *)
1808 begin
1809 let (_, (p,_), _iv, tm, vrest) = expand_case env (ci, u, pms, p, iv, tm, br) in
1810 let tree = match restrict_spec cache ?evars env (Subterm (Int.Set.empty, Strict, tree)) p with
1811 | Dead_code -> assert false
1812 | Subterm (_, _, tree') -> tree'
1813 | _ -> raise (CoFixGuardError (env, ReturnPredicateNotCoInductive c))
1814 in
1815 if (noccur_with_meta n nbfix p) then
1816 if (noccur_with_meta n nbfix tm) then
1817 if (List.for_all (noccur_with_meta n nbfix) args) then
1818 let vlra = dest_subterms tree in
1819 Array.iter (check_rec_call env alreadygrd n tree vlra) vrest
1820 else
1821 raise (CoFixGuardError (env,RecCallInCaseFun c))
1822 else
1823 raise (CoFixGuardError (env,RecCallInCaseArg c))
1824 else
1825 raise (CoFixGuardError (env,RecCallInCasePred c))
1826 end
1827
1828 | Meta _ -> ()
1829 | Evar _ ->
1830 List.iter (check_rec_call env alreadygrd n tree vlra) args
1831 | Rel _ | Var _ | Sort _ | Cast _ | Prod _ | LetIn _ | App _ | Const _
1832 | Ind _ | Fix _ | Proj _ | Int _ | Float _ | String _
1833 | Array _ ->
1834 raise (CoFixGuardError (env,NotGuardedForm t)) in
1835
1836 let ((mind, _),_) = codomain_is_coind ?evars env deftype in
1837 let vlra = lookup_subterms env mind in
1838 check_rec_call env false 1 vlra (dest_subterms vlra) def
1839
1840 (* The function which checks that the whole block of definitions
1841 satisfies the guarded condition *)
1842
1843 let check_cofix ?evars env (_bodynum,(names,types,bodies as recdef)) =
1844 let cache = Cache.create () in
1845 let flags = Environ.typing_flags env in
1846 if flags.check_guarded then
1847 let nbfix = Array.length bodies in
1848 for i = 0 to nbfix-1 do
1849 let fixenv = push_rec_types recdef env in
1850 try check_one_cofix cache ?evars fixenv nbfix bodies.(i) types.(i)
1851 with CoFixGuardError (errenv,err) ->
1852 error_ill_formed_rec_body errenv (Type_errors.CoFixGuardError err) names i
1853 fixenv (judgment_of_fixpoint recdef)
1854 done
1855 else
1856 ()
1857
1858 module Template = struct
1859 let bind_kind = bind_kind
1860 let template_subst_sort = template_subst_sort
1861 let max_template_quality = max_template_quality
1862 end