Debian Codegraph @

pretyping/tacred.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 Constr
15 open Context
16 open Termops
17 open Environ
18 open EConstr
19 open Reductionops
20
21 module RelDecl = Context.Rel.Declaration
22 module NamedDecl = Context.Named.Declaration
23
24 (* Errors *)
25
26 type reduction_tactic_error =
27 InvalidAbstraction of env * Evd.evar_map * EConstr.constr * (env * Type_errors.type_error)
28
29 type 'a change = NoChange | Changed of 'a
30 type change_function = env -> Evd.evar_map -> constr -> (Evd.evar_map * constr) change
31
32 exception ReductionTacticError of reduction_tactic_error
33
34 (* Evaluable reference *)
35
36 exception Elimconst
37
38 (* Here the semantics is completely unclear.
39 What does "Hint Unfold t" means when "t" is a parameter?
40 Does the user mean "Unfold X.t" or does she mean "Unfold y"
41 where X.t is later on instantiated with y? I choose the first
42 interpretation (i.e. an evaluable reference is never expanded). *)
43 let subst_evaluable_reference subst =
44 Evaluable.map (fun id -> id) (Mod_subst.subst_constant subst)
45 (Mod_subst.subst_proj_repr subst)
46
47 exception NotEvaluableRef of GlobRef.t
48
49 let () = CErrors.register_handler (function
50 | NotEvaluableRef r ->
51 Some Pp.(str "Cannot coerce" ++ spc () ++ Nametab.pr_global_env Id.Set.empty r ++
52 spc () ++ str "to an evaluable reference.")
53 | _ -> None)
54
55 let error_not_evaluable ?loc r = Loc.raise ?loc (NotEvaluableRef r)
56
57 let evaluable_constant env sigma kn =
58 let cb = lookup_constant env sigma kn in
59 match cb.const_body with
60 | Def _ -> true
61 | OpaqueDef _ -> false
62 | Undef _ | Primitive _ | Symbol _ -> false
63
64 let is_evaluable_const env sigma cst =
65 is_transparent env (Evaluable.EvalConstRef cst) && evaluable_constant env sigma cst
66
67 let is_evaluable_var env id =
68 is_transparent env (Evaluable.EvalVarRef id) && evaluable_named id env
69
70 let is_evaluable_projection env p =
71 is_transparent env (Evaluable.EvalProjectionRef p)
72
73 let is_evaluable env sigma = function
74 | Evaluable.EvalConstRef cst -> is_evaluable_const env sigma cst
75 | Evaluable.EvalVarRef id -> is_evaluable_var env id
76 | Evaluable.EvalProjectionRef p -> is_evaluable_projection env p
77
78 let value_of_evaluable_ref env sigma evref u =
79 match evref with
80 | Evaluable.EvalConstRef con ->
81 constant_value_in env sigma (con, u)
82 | Evaluable.EvalVarRef id ->
83 env |> lookup_named id |> NamedDecl.get_value |> Option.get
84 | Evaluable.EvalProjectionRef _ ->
85 assert false (* TODO *)
86
87 let soft_evaluable_of_global_reference ?loc = function
88 | GlobRef.ConstRef cst ->
89 begin
90 match Structures.PrimitiveProjections.find_opt cst with
91 | None -> Evaluable.EvalConstRef cst
92 | Some p -> Evaluable.EvalProjectionRef p
93 end
94 | GlobRef.VarRef id -> Evaluable.EvalVarRef id
95 | r -> error_not_evaluable ?loc r
96
97 let evaluable_of_global_reference env = function
98 | GlobRef.ConstRef cst when not (Environ.mem_constant cst env) || is_evaluable_const env (Evd.from_env env) cst (* FIXME *) ->
99 begin
100 match Structures.PrimitiveProjections.find_opt cst with
101 | None -> Evaluable.EvalConstRef cst
102 | Some p -> Evaluable.EvalProjectionRef p
103 end
104 | GlobRef.VarRef id when is_evaluable_var env id -> Evaluable.EvalVarRef id
105 | r -> error_not_evaluable r
106
107 let global_of_evaluable_reference = function
108 | Evaluable.EvalConstRef cst -> GlobRef.ConstRef cst
109 | Evaluable.EvalVarRef id -> GlobRef.VarRef id
110 | Evaluable.EvalProjectionRef p -> GlobRef.ConstRef (Projection.Repr.constant p)
111
112 type evaluable_reference =
113 | EvalConst of Constant.t
114 | EvalVar of Id.t
115 | EvalRel of int
116 | EvalEvar of EConstr.existential
117
118 let evaluable_reference_eq env sigma r1 r2 = match r1, r2 with
119 | EvalConst c1, EvalConst c2 -> QConstant.equal env c1 c2
120 | EvalVar id1, EvalVar id2 -> Id.equal id1 id2
121 | EvalRel i1, EvalRel i2 -> Int.equal i1 i2
122 | EvalEvar (e1, ctx1), EvalEvar (e2, ctx2) ->
123 EConstr.eq_constr sigma (mkEvar (e1, ctx1)) (mkEvar (e2, ctx2))
124 | (EvalConst _ | EvalVar _ | EvalRel _ | EvalEvar _), _ -> false
125
126 let mkEvalRef ref u =
127 match ref with
128 | EvalConst cst -> mkConstU (cst,u)
129 | EvalVar id -> mkVar id
130 | EvalRel n -> mkRel n
131 | EvalEvar ev -> EConstr.mkEvar ev
132
133 let isEvalRef env sigma c = match EConstr.kind sigma c with
134 | Const (sp,_) -> is_evaluable env sigma (EvalConstRef sp)
135 | Var id -> is_evaluable env sigma (EvalVarRef id)
136 | Rel _ | Evar _ -> true
137 | _ -> false
138
139 let isTransparentEvalRef env sigma ts c = match EConstr.kind sigma c with
140 | Const (cst,_) -> is_evaluable env sigma (EvalConstRef cst) && Structures.PrimitiveProjections.is_transparent_constant ts cst
141 | Var id -> is_evaluable env sigma (EvalVarRef id) && TransparentState.is_transparent_variable ts id
142 | Rel _ -> true
143 | Evar _ -> false (* undefined *)
144 | _ -> false
145
146 let destEvalRefU sigma c = match EConstr.kind sigma c with
147 | Const (cst,u) -> EvalConst cst, u
148 | Var id -> (EvalVar id, EInstance.empty)
149 | Rel n -> (EvalRel n, EInstance.empty)
150 | Evar ev -> (EvalEvar ev, EInstance.empty)
151 | _ -> anomaly (Pp.str "Not an unfoldable reference.")
152
153 module CacheTable = Hashtbl.Make(struct
154 type t = Constant.t * UVars.Instance.t
155
156 (* WARNING if we use CanOrd and we have [M.x := N.x] unfolding M.x
157 first will put [M.x -> N.x] in the cache, then trying to unfold
158 N.x will return N.x ie loop. *)
159 let equal (c,u) (c',u') =
160 Constant.UserOrd.equal c c' && UVars.Instance.equal u u'
161
162 let hash (c,u) =
163 Hashset.Combine.combine (Constant.UserOrd.hash c) (UVars.Instance.hash u)
164 end)
165
166 let constant_opt_value_in env sigma cst =
167 try Some (EConstr.constant_value_in env sigma cst)
168 with NotEvaluableConst _ -> None
169
170 let reference_opt_value cache env sigma eval u =
171 match eval with
172 | EvalConst cst ->
173 let cu = (cst, EInstance.kind sigma u) in
174 begin match CacheTable.find_opt cache cu with
175 | Some v -> v
176 | None ->
177 let v = constant_opt_value_in env sigma (cst, u) in
178 CacheTable.add cache cu v;
179 v
180 end
181 | EvalVar id ->
182 env |> lookup_named id |> NamedDecl.get_value
183 | EvalRel n ->
184 env |> lookup_rel n |> RelDecl.get_value |> Option.map (Vars.lift n)
185 | EvalEvar ev ->
186 match EConstr.kind sigma (mkEvar ev) with
187 | Evar _ -> None
188 | c -> Some (EConstr.of_kind c)
189
190 exception NotEvaluable
191 let reference_value cache env sigma c u =
192 match reference_opt_value cache env sigma c u with
193 | None -> raise NotEvaluable
194 | Some d -> d
195
196 (************************************************************************)
197 (* Reduction of constants hiding a fixpoint (e.g. for "simpl" tactic). *)
198 (* One reuses the name of the function after reduction of the fixpoint *)
199
200 type fix_refolding = {
201 refolding_names : (evaluable_reference * EInstance.t) option array;
202 refolding_wrapper_data : (int * constr) list;
203 expected_args : int;
204 }
205
206 type fix_evaluation_data = {
207 trigger_min_args : int;
208 refolding_target : evaluable_reference;
209 refolding_data : fix_refolding;
210 }
211
212 type constant_elimination =
213 | EliminationFix of fix_evaluation_data
214 | EliminationCases of constr * int
215 | EliminationProj of constr * int
216 | NotAnElimination of constr
217 | NotAnEliminationConstant
218
219 type constant_coelimination =
220 | CoEliminationCoFix of fix_evaluation_data
221 | CoEliminationConstruct of constr
222 | CoEliminationPrimitive of constr
223 | NotACoElimination of constr
224 | NotACoEliminationConstant
225
226 (************************************************************************)
227
228 type simpl_infos = {
229 constant_body_cache : EConstr.t option CacheTable.t;
230 elim_cache : constant_elimination CacheTable.t;
231 coelim_cache : constant_coelimination CacheTable.t;
232 red_behavior : ReductionBehaviour.Db.t;
233 main_reds : RedFlags.reds;
234 construct_reds : RedFlags.reds;
235 }
236
237 let make_simpl_infos (red_behavior, main_reds, construct_reds) = {
238 constant_body_cache = CacheTable.create 12;
239 elim_cache = CacheTable.create 12;
240 coelim_cache = CacheTable.create 12;
241 red_behavior;
242 main_reds;
243 construct_reds;
244 }
245
246 (* [compute_constant_elimination] determines whether f is an "elimination constant"
247
248 either [yn:Tn]..[y1:T1](match yi with f1..fk end g1 ..gp)
249
250 or [yn:Tn]..[y1:T1](Fix(m0,..) yi1..yip)
251 with yi1..yip distinct variables among the yi, not occurring in t
252
253 In the second case, [check_fix_reversibility [T1;...;Tn] args fix]
254 checks that [args] is a subset of disjoint variables in y1..yn (a necessary
255 condition for reversibility). Assuming a constant f_m naming
256 Fix(m,..), with f := f_m0, it also returns for each m the relevant
257 information ([i1,Ti1;..;ip,Tip],n) in order to compute an
258 equivalent g_m of Fix(m,..) such that
259
260 g_m := [xp:Tip']..[x1:Ti1'](f_m a1..an)
261 == [xp:Tip']..[x1:Ti1'](Fix(f|t) yi1..yip)
262
263 with a_k:=y_k if k<>i_j and (but only in the case m_0), a_k:=args_k
264 otherwise, as well as Tij':=Tij[x1..xi(j-1) <- a1..ai(j-1)]
265
266 Note that the types Tk, when no i_j=k, must not be dependent on
267 the xp..x1.
268 *)
269
270 let compute_constant_reversibility sigma labs args fix =
271 let nlam = List.length labs in
272 let nargs = List.length args in
273 if nargs > nlam then
274 (* Necessary non-linear, thus not reversible *)
275 raise Elimconst;
276 (* Check that arguments are bound by the lambdas, up to a
277 substitution, and that they do not occur elsewhere *)
278 let typed_reversible_args =
279 List.map
280 (function d -> match EConstr.kind sigma d with
281 | Rel k ->
282 if Vars.noccurn sigma k fix && k <= nlam then
283 (* Bound in labs and occurring only in args *)
284 (k, snd (List.nth labs (k-1)))
285 else
286 raise Elimconst
287 | _ ->
288 raise Elimconst) args in
289 let reversible_rels = List.map fst typed_reversible_args in
290 if not (List.distinct_f Int.compare reversible_rels) then
291 raise Elimconst;
292 (* Lambda's that are not used should not depend on those that are
293 used and that will thus be different in the recursive calls *)
294 List.iteri (fun i (_,t_i) ->
295 if not (Int.List.mem (i+1) reversible_rels) then
296 let fvs = List.map ((+) (i+1)) (Int.Set.elements (free_rels sigma t_i)) in
297 match List.intersect Int.equal fvs reversible_rels with
298 | [] -> ()
299 | _ -> raise Elimconst)
300 labs;
301 typed_reversible_args, nlam, nargs
302
303 let check_fix_reversibility env sigma ref u labs args minarg refs ((lv,i),_ as fix) =
304 let li, nlam, nargs = compute_constant_reversibility sigma labs args (mkFix fix) in
305 let k = lv.(i) in
306 let refolding_data = {
307 refolding_names = refs;
308 refolding_wrapper_data = li;
309 expected_args = nlam;
310 } in
311 if k < nargs then
312 (* Such an optimisation would need eta-expansion
313 let p = destRel (List.nth args k) in
314 EliminationFix (n-p+1,(li,n))
315 *)
316 {
317 trigger_min_args = max minarg nlam;
318 refolding_target = ref;
319 refolding_data;
320 }
321 else
322 {
323 trigger_min_args = max minarg (nlam - nargs + k + 1);
324 refolding_target = ref;
325 refolding_data;
326 }
327
328 let check_cofix_reversibility env sigma ref u labs args minarg refs (i,_ as cofix) =
329 let li, nlam, nargs = compute_constant_reversibility sigma labs args (mkCoFix cofix) in
330 let refolding_data = {
331 refolding_names = refs;
332 refolding_wrapper_data = li;
333 expected_args = nlam;
334 } in
335 {
336 trigger_min_args = max minarg nlam; (* Does not matter; will be maximally applied anyway *)
337 refolding_target = ref;
338 refolding_data;
339 }
340
341 let compute_recursive_wrapper infos env sigma ref u =
342 try match reference_opt_value infos.constant_body_cache env sigma ref u with
343 | None -> None
344 | Some c ->
345 let labs, ccl = whd_decompose_lambda env sigma c in
346 let c, l = whd_stack_gen infos.main_reds env sigma ccl in
347 Some (labs, l)
348 with Not_found (* Undefined ref *) -> None
349
350 (* Heuristic to look if global names are associated to other
351 components of a mutual fixpoint *)
352
353 let invert_recursive_names infos env sigma ref u names i =
354 let labs, l =
355 match compute_recursive_wrapper infos env sigma ref u with
356 | None -> assert false
357 | Some (labs, l) -> labs, l in
358 let make_name j =
359 if Int.equal i j then Some (ref, u) else
360 match names.(j).binder_name with
361 | Anonymous -> None (* should not happen *)
362 | Name id ->
363 let refi = match ref with
364 | EvalRel _ | EvalEvar _ -> None
365 | EvalVar id' -> Some (EvalVar id)
366 | EvalConst kn ->
367 let kn = Constant.change_label kn id in
368 if Environ.mem_constant kn env then Some (EvalConst kn) else None
369 in
370 match refi with
371 | None -> None
372 | Some ref ->
373 match compute_recursive_wrapper infos env sigma ref u with
374 | None -> None
375 | Some (labs', l') ->
376 let eq_constr c1 c2 = EConstr.eq_constr sigma c1 c2 in
377 if List.equal (fun (_,t) (_,t') -> eq_constr t t') labs' labs &&
378 List.equal eq_constr l l' then Some (ref, u)
379 else None in
380 labs, l, Array.init (Array.length names) make_name
381
382 let deactivate_delta allowed_reds =
383 (* Act both on Delta and transparent state as not all reduction functions work the same *)
384 RedFlags.(red_add_transparent (red_sub allowed_reds fDELTA) TransparentState.empty)
385
386 (* [compute_constant_elimination] stepwise expands an arbitrary long sequence of
387 reversible constants, eventually refolding to the initial constant
388 for unary fixpoints and to the last constant encapsulating the Fix
389 for mutual fixpoints *)
390
391 let compute_constant_elimination infos env sigma ref u =
392 let allowed_reds_no_delta = deactivate_delta infos.main_reds in
393 let rec srec env all_abs lastref lastu onlyproj c stk =
394 let c', args = whd_stack_gen allowed_reds_no_delta env sigma c in
395 (* We now know that the initial [ref] evaluates to [fun all_abs => c' args] *)
396 (* and that the last visited name in the evaluation is [lastref] *)
397 match EConstr.kind sigma c' with
398 | Lambda (id,t,g) ->
399 assert (List.is_empty args && Stack.is_empty stk);
400 let open Context.Rel.Declaration in
401 srec (push_rel (LocalAssum (id,t)) env) ((id,t)::all_abs) lastref lastu onlyproj g Stack.empty
402 | Fix ((lv,i),(names,_,_) as fix) when not onlyproj ->
403 let n_all_abs = List.length all_abs in
404 let nbfix = Array.length lv in
405 (if nbfix = 1 then
406 (* Try to refold to [ref] *)
407 let refs = [|Some (ref,u)|] in
408 try EliminationFix (check_fix_reversibility env sigma ref u all_abs args n_all_abs refs fix)
409 with Elimconst -> NotAnEliminationConstant
410 else
411 (* Try to refold to [lastref] *)
412 let last_labs, last_args, names = invert_recursive_names infos env sigma lastref lastu names i in
413 try EliminationFix (check_fix_reversibility env sigma lastref lastu last_labs last_args n_all_abs names fix)
414 with Elimconst -> NotAnEliminationConstant)
415 | Case (_,_,_,_,_,d,_) when isRel sigma d && not onlyproj ->
416 EliminationCases (it_mkLambda (Stack.zip sigma (c',Stack.append_app_list args stk)) all_abs, List.length all_abs)
417 | Case (ci,u,pms,p,iv,d,lf) -> srec env all_abs lastref lastu true d Stack.(Case (mkCaseStk (ci,u,pms,p,iv,lf)) :: append_app_list args stk)
418 | Proj (p, _, d) when isRel sigma d ->
419 EliminationProj (it_mkLambda (Stack.zip sigma (c',Stack.append_app_list args stk)) all_abs, List.length all_abs)
420 | _ when isTransparentEvalRef env sigma (RedFlags.red_transparent infos.main_reds) c' ->
421 (* Continue stepwise unfolding from [c' args] *)
422 let ref, u = destEvalRefU sigma c' in
423 (match reference_opt_value infos.constant_body_cache env sigma ref u with
424 | None -> NotAnEliminationConstant (* e.g. if a rel *)
425 | Some c -> srec env all_abs ref u onlyproj (applist (c, args)) stk)
426 | _ -> NotAnEliminationConstant
427 in
428 match reference_opt_value infos.constant_body_cache env sigma ref u with
429 | None -> NotAnEliminationConstant
430 | Some c -> match srec env [] ref u false c Stack.empty with NotAnEliminationConstant -> NotAnElimination c | e -> e
431
432 (* [compute_constant_coelimination] stepwise expands an arbitrary long sequence of
433 reversible constants, eventually refolding to the initial constant
434 for unary cofixpoints and to the last constant encapsulating the CoFix
435 for mutual cofixpoints *)
436
437 let compute_constant_coelimination infos env sigma ref u =
438 let allowed_reds_no_delta = deactivate_delta infos.construct_reds in
439 let rec srec env all_abs lastref lastu c =
440 let c', args = whd_stack_gen allowed_reds_no_delta env sigma c in
441 (* We now know that the initial [ref] evaluates to [fun all_abs => c' args] *)
442 (* and that the last visited name in the evaluation is [lastref] *)
443 match EConstr.kind sigma c' with
444 | Lambda (id,t,g) ->
445 assert (List.is_empty args);
446 let open Context.Rel.Declaration in
447 srec (push_rel (LocalAssum (id,t)) env) ((id,t)::all_abs) lastref lastu g
448 | Construct _ ->
449 let c = it_mkLambda (applist (c', args)) all_abs in
450 CoEliminationConstruct c
451 | Int _ | Float _ | String _ | Array _ (* reduced by primitives *) ->
452 let c = it_mkLambda (applist (c', args)) all_abs in
453 CoEliminationPrimitive c
454 | CoFix (i,(names,_,_) as cofix) ->
455 let n_all_abs = List.length all_abs in
456 let nbfix = Array.length names in
457 (if nbfix = 1 then
458 (* Try to refold to [ref] *)
459 let refs = [|Some (ref,u)|] in
460 try CoEliminationCoFix (check_cofix_reversibility env sigma ref u all_abs args n_all_abs refs cofix)
461 with Elimconst -> NotACoEliminationConstant
462 else
463 (* Try to refold to [lastref] *)
464 let last_labs, last_args, names = invert_recursive_names infos env sigma lastref lastu names i in
465 try CoEliminationCoFix (check_cofix_reversibility env sigma lastref lastu last_labs last_args n_all_abs names cofix)
466 with Elimconst -> NotACoEliminationConstant)
467 | _ when isTransparentEvalRef env sigma (RedFlags.red_transparent infos.construct_reds) c' ->
468 (* Continue stepwise unfolding from [c' args] *)
469 let ref, u = destEvalRefU sigma c' in
470 (match reference_opt_value infos.constant_body_cache env sigma ref u with
471 | None -> NotACoEliminationConstant (* e.g. if a rel *)
472 | Some c -> srec env all_abs ref u (applist (c, args)))
473 | _ -> NotACoEliminationConstant
474 in
475 match reference_opt_value infos.constant_body_cache env sigma ref u with
476 | None -> NotACoEliminationConstant
477 | Some c -> match srec env [] ref u c with NotACoEliminationConstant -> NotACoElimination c | e -> e
478
479 let compute_reference_elimination infos env sigma ref u =
480 match ref with
481 | EvalConst cst as ref ->
482 let cu = cst, EInstance.kind sigma u in
483 (match CacheTable.find_opt infos.elim_cache cu with
484 | Some v -> v
485 | None ->
486 let v = compute_constant_elimination infos env sigma ref u in
487 CacheTable.add infos.elim_cache cu v;
488 v)
489 | ref -> compute_constant_elimination infos env sigma ref u
490
491 let compute_reference_coelimination infos env sigma ref u =
492 match ref with
493 | EvalConst cst as ref ->
494 let cu = cst, EInstance.kind sigma u in
495 (match CacheTable.find_opt infos.coelim_cache cu with
496 | Some v -> v
497 | None ->
498 let v = compute_constant_coelimination infos env sigma ref u in
499 CacheTable.add infos.coelim_cache cu v;
500 v)
501 | ref -> compute_constant_coelimination infos env sigma ref u
502
503 (* If f is bound to EliminationFix (n',refs,infos), then n' is the minimal
504 number of args for triggering the reduction and infos is
505 ([(yi1,Ti1);...;(yip,Tip)],n) indicating that f converts
506 to some [y1:T1,...,yn:Tn](Fix(..) yip .. yi1) where the y_{i_j} consist in a
507 disjoint subset of the yi, i.e. 1 <= ij <= n and the ij are disjoint (in
508 particular, p <= n).
509
510 f is applied to largs := arg1 .. argn and we need for recursive
511 calls to build the function
512
513 g := [xp:Tip',...,x1:Ti1'](f a1 ... an)
514
515 s.t. any (Fix(..) u1 ... up) can be re-expanded to (g u1 ... up)
516
517 This is made possible by setting
518 a_k:=x_j if k=i_j for some j
519 a_k:=arg_k otherwise
520
521 The type Tij' is Tij[yi(j-1)..y1 <- ai(j-1)..a1]
522
523 In the case of a mutual fix and f is the m-th component, this is
524 the same for the components different from m except that for the
525 f_l associated to component l, and f_l is convertible to
526 [y1:U1,...,yn:Un](Fix(..,l,..) yip .. yi1), we need i_j to be a
527 bijection (since we have no more arg_k at our disposal to fill a
528 position k not in the image of i_j).
529 *)
530
531 let xname = Name Namegen.default_dependent_ident
532
533 (* [f] is convertible to [Fix(recindices,bodynum),bodyvect)]:
534 do so that the reduction uses this extra information *)
535
536 let substl_with_function subst sigma constr =
537 let v = Array.of_list subst in
538 let rec subst_total k c = match EConstr.kind sigma c with
539 | Rel i when k < i ->
540 if i <= k + Array.length v then
541 (* A recursive call *)
542 Vars.lift k v.(i-k-1)
543 else
544 (* A variable bound beyond the scope of the fix *)
545 mkRel (i - Array.length v)
546 | _ ->
547 map_with_binders sigma succ subst_total k c in
548 subst_total 0 constr
549
550 type 'a fix_reduction_result = NotReducible | Reduced of 'a
551
552 let[@ocaml.inline] (let*) m f = match m with
553 | NotReducible -> NotReducible
554 | Reduced x -> f x
555
556 let mkLambda_with_eta sigma x t c =
557 let f, args = decompose_app_list sigma c in
558 if List.is_empty args then mkLambda (x, t, c)
559 else
560 let b, args = List.sep_last args in
561 if isRelN sigma 1 b then applist (f, List.map (Vars.lift (-1)) args)
562 else mkLambda (x, t, c)
563
564 let contract_rec env sigma f nbodies mk_rec contract body =
565 match f with
566 | None -> contract ()
567 | Some f ->
568 let {refolding_names; refolding_wrapper_data = lv; expected_args = n}, largs = f in
569 let lu = List.firstn n largs in
570 let p = List.length lv in
571 let lyi = List.map fst lv in
572 let la =
573 List.map_i (fun q aq ->
574 (* k from the comment is q+1 *)
575 try mkRel (p+1-(List.index Int.equal (n-q) lyi))
576 with Not_found -> Vars.lift p aq)
577 0 lu
578 in
579 let make_Fi i = match refolding_names.(i) with
580 | None -> mk_rec i
581 | Some (ref, u) ->
582 let body = applist (mkEvalRef ref u, la) in
583 List.fold_left_i (fun q (* j = n+1-q *) c (ij,tij) ->
584 let subst = List.map (Vars.lift (-q)) (List.firstn (n-ij) la) in
585 let tij' = Vars.substl (List.rev subst) tij in
586 let x = make_annot xname ERelevance.relevant in (* TODO relevance *)
587 mkLambda_with_eta sigma x tij' c)
588 1 body (List.rev lv)
589 in
590 let lbodies = List.init nbodies make_Fi in
591 let c = substl_with_function (List.rev lbodies) sigma (nf_beta env sigma body) in
592 nf_beta env sigma c
593
594 let contract_fix env sigma f ((recindices,bodynum),(_names,_types,bodies as typedbodies) as fixp) =
595 contract_rec env sigma f
596 (Array.length bodies)
597 (fun i -> mkFix((recindices,i),typedbodies))
598 (fun () -> contract_fix sigma fixp)
599 bodies.(bodynum)
600
601 let contract_cofix env sigma f (bodynum,(_names,_types,bodies as typedbodies) as cofixp) =
602 contract_rec env sigma f
603 (Array.length bodies)
604 (fun i -> mkCoFix(i,typedbodies))
605 (fun () -> contract_cofix sigma cofixp)
606 bodies.(bodynum)
607
608 let reducible_construct sigma c = match EConstr.kind sigma c with
609 | Construct _ | CoFix _ (* reduced by case *)
610 | Int _ | Float _ | String _ | Array _ (* reduced by primitives *) -> true
611 | _ -> false
612
613 type eval_kind =
614 | EvEval of evaluable_reference * EInstance.t
615 | EvPrim of Constant.t
616 | EvSymbol
617 | EvNone
618
619 let match_eval_ref env sigma constr stack =
620 match EConstr.kind sigma constr with
621 | Const (sp, u) ->
622 let () = reduction_effect_hook env sigma sp
623 (lazy (EConstr.to_constr sigma (applist (constr,stack)))) in
624 let cb = lookup_constant env sigma sp in
625 begin match cb.const_body with
626 | Def _ -> if is_transparent env (Evaluable.EvalConstRef sp) then EvEval (EvalConst sp, u) else EvNone
627 | Undef _ | OpaqueDef _ -> EvNone
628 | Primitive _ -> EvPrim sp
629 | Symbol _ -> EvSymbol
630 end
631 | Var id when is_evaluable_var env id -> EvEval (EvalVar id, EInstance.empty)
632 | Rel i -> EvEval (EvalRel i, EInstance.empty)
633 | Evar ev -> EvEval (EvalEvar ev, EInstance.empty)
634 | _ -> EvNone
635
636 let match_eval_ref_value env sigma constr stack =
637 match EConstr.kind sigma constr with
638 | Const (sp, u) ->
639 reduction_effect_hook env sigma sp
640 (lazy (EConstr.to_constr sigma (applist (constr,stack))));
641 if is_evaluable env sigma (EvalConstRef sp) then
642 Some (constant_value_in env sigma (sp, u))
643 else
644 None
645 | Proj (p, r, c) when not (Projection.unfolded p) ->
646 if is_evaluable env sigma (EvalProjectionRef (Projection.repr p)) then
647 Some (mkProj (Projection.unfold p, r, c))
648 else None
649 | Var id when is_evaluable env sigma (EvalVarRef id) ->
650 env |> lookup_named id |> NamedDecl.get_value
651 | Rel n ->
652 env |> lookup_rel n |> RelDecl.get_value |> Option.map (Vars.lift n)
653 | _ -> None
654
655 let push_app sigma (hd, stk as p) = match EConstr.kind sigma hd with
656 | App (hd, args) ->
657 (hd, Array.fold_right (fun x accu -> x :: accu) args stk)
658 | _ -> p
659
660 let recargs behavior = function
661 | EvalVar _ | EvalRel _ | EvalEvar _ -> None
662 | EvalConst c -> ReductionBehaviour.get_from_db behavior c
663
664 let fix_recarg ((recindices,bodynum),_) stack =
665 assert (0 <= bodynum && bodynum < Array.length recindices);
666 let recargnum = Array.get recindices bodynum in
667 try
668 Some (recargnum, List.nth stack recargnum)
669 with Failure _ ->
670 None
671
672 let contract_projection env sigma f (p,r) ~npars (hd, args) =
673 match EConstr.kind sigma hd with
674 | Construct _ ->
675 let proj_narg = npars + Projection.arg p in
676 Reduced (List.nth args proj_narg)
677 | CoFix cofix ->
678 let cofix_def = contract_cofix env sigma f cofix in
679 (* If the cofix_def does not reduce to a constructor, do we
680 really want to say it is Reduced? Consider e.g.:
681 CoInductive stream := cons { hd : bool; tl : stream }.
682 CoFixpoint const (x : bool) := if x then cons x (const x) else cons x (const x).
683 Eval simpl in fun x => (const x).(tl) *)
684 Reduced (mkProj (p, r, applist(cofix_def, args)))
685 | _ -> NotReducible
686
687 let rec beta_applist sigma accu c stk = match EConstr.kind sigma c, stk with
688 | Lambda (_, _, c), arg :: stk -> beta_applist sigma (arg :: accu) c stk
689 | _ -> Vars.substl accu c, stk
690
691 let whd_nothing_for_iota env sigma s =
692 let rec whrec (x, stack as s) =
693 match EConstr.kind sigma x with
694 | Rel n ->
695 let open Context.Rel.Declaration in
696 (match lookup_rel n env with
697 | LocalDef (_,body,_) -> whrec (Vars.lift n body, stack)
698 | _ -> s)
699 | Var id ->
700 let open Context.Named.Declaration in
701 (match lookup_named id env with
702 | LocalDef (_,body,_) -> whrec (body, stack)
703 | _ -> s)
704 | Evar _ | Meta _ -> s
705 | Const (const, u) ->
706 (match constant_opt_value_in env sigma (const, u) with
707 | Some body -> whrec (body, stack)
708 | None -> s)
709 | LetIn (_,b,_,c) -> whrec (beta_applist sigma [b] c stack)
710 | Cast (c,_,_) -> whrec (c, stack)
711 | App (f,cl) -> whrec (f, Array.fold_right (fun c accu -> c :: accu) cl stack)
712 | Lambda (na,t,c) ->
713 (match stack with
714 | a :: stack -> whrec (beta_applist sigma [a] c stack)
715 | _ -> s)
716
717 | x -> s
718 in
719 whrec s
720
721 (* The reductions that should be performed as part of the simpl and hnf tactic *)
722 let make_reds env behavior =
723 let open RedFlags in
724 let open ReductionBehaviour.Db in
725 let simpl_never = all_never_unfold behavior in
726 let transparent_state = Conv_oracle.get_transp_state (Environ.oracle env) in
727 let transparent_state_never =
728 { transparent_state with
729 tr_cst = Cpred.diff transparent_state.tr_cst simpl_never
730 }
731 in
732 let reds = no_red in
733 let reds = red_add reds fDELTA in
734 let reds = red_add reds fZETA in
735 let reds = red_add reds fBETA in
736 let reds = red_add_transparent reds transparent_state in
737 let reds_never = red_add_transparent reds transparent_state_never in
738 behavior, reds_never, reds
739
740 let rec descend cache env sigma target (ref,u) args =
741 let c = reference_value cache env sigma ref u in
742 if evaluable_reference_eq env sigma ref target then
743 (c,args)
744 else
745 let c', lrest = whd_betalet_stack env sigma (applist (c, args)) in
746 descend cache env sigma target (destEvalRefU sigma c') lrest
747
748 (* The reductions that should be performed as part of the simpl tactic,
749 excluding symbols that have the NeverUnfold flag. *)
750 let make_simpl_reds env =
751 make_reds env (ReductionBehaviour.Db.get ())
752
753 (* The reductions that should be performed as part of the hnf tactic *)
754 let make_hnf_reds env =
755 make_reds env ReductionBehaviour.Db.empty
756
757 (* [red_elim_const] contracts iota/fix/cofix redexes hidden behind
758 constants by keeping the name of the constants in the recursive calls;
759 it fails if no redex is around *)
760
761 let rec red_elim_const infos env sigma ref u largs =
762 let open ReductionBehaviour in
763 let nargs = List.length largs in
764 let* largs, unfold_anyway, unfold_nonelim, nocase =
765 match recargs infos.red_behavior ref with
766 | None -> Reduced (largs, false, false, false)
767 | Some NeverUnfold -> NotReducible
768 | Some (UnfoldWhen { nargs = Some n } | UnfoldWhenNoMatch { nargs = Some n })
769 when nargs < n -> NotReducible
770 | Some (UnfoldWhen { recargs = x::l } | UnfoldWhenNoMatch { recargs = x::l })
771 when nargs <= List.fold_left max x l -> NotReducible
772 | Some (UnfoldWhen { recargs; nargs = None }) ->
773 let* params = reduce_params infos env sigma largs recargs in
774 Reduced (params,
775 false,
776 false,
777 false)
778 | Some (UnfoldWhenNoMatch { recargs; nargs = None }) ->
779 let* params = reduce_params infos env sigma largs recargs in
780 Reduced (params,
781 false,
782 false,
783 true)
784 | Some (UnfoldWhen { recargs; nargs = Some n }) ->
785 let is_empty = List.is_empty recargs in
786 let* params = reduce_params infos env sigma largs recargs in
787 Reduced (params,
788 is_empty && nargs >= n,
789 not is_empty && nargs >= n,
790 false)
791 | Some (UnfoldWhenNoMatch { recargs; nargs = Some n }) ->
792 let is_empty = List.is_empty recargs in
793 let* params = reduce_params infos env sigma largs recargs in
794 Reduced (params,
795 is_empty && nargs >= n,
796 not is_empty && nargs >= n,
797 true)
798 in
799 let ans = match compute_reference_elimination infos env sigma ref u with
800 | EliminationCases (c,n) when nargs >= n ->
801 let c', stack = whd_nothing_for_iota env sigma (c, largs) in
802 let* ans = reduce_case infos env sigma (EConstr.destCase sigma c') in
803 Reduced ((ans, stack), nocase)
804 | EliminationProj (c,n) when nargs >= n ->
805 let c', stack = whd_nothing_for_iota env sigma (c, largs) in
806 let* ans = reduce_nested_projection infos env sigma c' in
807 Reduced ((ans, stack), nocase)
808 | EliminationFix {trigger_min_args; refolding_target; refolding_data}
809 when nargs >= trigger_min_args ->
810 let (_, midargs as s) = descend infos.constant_body_cache env sigma refolding_target (ref,u) largs in
811 let d, stack = whd_nothing_for_iota env sigma s in
812 let f = refolding_data, midargs in
813 let* c = reduce_fix infos env sigma (Some f) (destFix sigma d) stack in
814 Reduced (c, nocase)
815 | NotAnElimination c when unfold_nonelim ->
816 Reduced ((whd_betaiotazeta env sigma (applist (c, largs)), []), nocase)
817 | _ -> NotReducible
818 in
819 match ans with
820 | NotReducible when unfold_anyway ->
821 let c = reference_value infos.constant_body_cache env sigma ref u in
822 Reduced ((whd_betaiotazeta env sigma (applist (c, largs)), []), nocase)
823 | _ -> ans
824
825 and reduce_params infos env sigma stack l =
826 let len = List.length stack in
827 let rec redp stack l = match l with
828 | [] -> Reduced stack
829 | i :: l ->
830 if len <= i then NotReducible
831 else
832 let arg = List.nth stack i in
833 let* rarg = whd_construct_stack infos env sigma arg in
834 match EConstr.kind sigma (fst rarg) with
835 | Construct _ | Int _ | Float _ | String _ | Array _ ->
836 redp (List.assign stack i (applist rarg)) l
837 | _ -> NotReducible
838 in
839 redp stack l
840
841 (* reduce to whd normal form or to an applied constant that does not hide
842 a reducible iota/fix/cofix redex (the "simpl" tactic) *)
843
844 and whd_simpl_stack infos env sigma =
845 let rec redrec s =
846 let s' = push_app sigma s in
847 let (x, stack) = s' in
848 match EConstr.kind sigma x with
849 | Lambda (na,t,c) ->
850 (match stack with
851 | [] -> s'
852 | a :: rest -> redrec (beta_applist sigma [a] c rest))
853 | LetIn (n,b,t,c) -> redrec (Vars.substl [b] c, stack)
854 | App (f,cl) -> assert false (* see push_app above *)
855 | Cast (c,_,_) -> redrec (c, stack)
856 | Case (ci,u,pms,p,iv,c,lf) ->
857 begin match reduce_case infos env sigma (ci,u,pms,p,iv,c,lf) with
858 | Reduced c -> redrec (c, stack)
859 | NotReducible -> s'
860 end
861 | Fix fix ->
862 begin match reduce_fix infos env sigma None fix stack with
863 | Reduced s' -> redrec s'
864 | NotReducible -> s'
865 end
866 | Proj (p, r, c) ->
867 let ans =
868 let unf = Projection.unfolded p in
869 if unf || is_evaluable env sigma (EvalProjectionRef (Projection.repr p)) then
870 let npars = Projection.npars p in
871 match unf, ReductionBehaviour.get_from_db infos.red_behavior (Projection.constant p) with
872 | false, Some NeverUnfold -> NotReducible
873 | false, Some (UnfoldWhen { recargs } | UnfoldWhenNoMatch { recargs })
874 when not (List.is_empty recargs) ->
875 let l' = List.map_filter (fun i ->
876 let idx = (i - (npars + 1)) in
877 if idx < 0 then None else Some idx) recargs in
878 let* stack = reduce_params infos env sigma stack l' in
879 let* c = reduce_projection infos env sigma (p,r) ~npars c in
880 Reduced (c, stack)
881 | _ ->
882 let* c = reduce_projection infos env sigma (p,r) ~npars c in
883 Reduced (c, stack)
884 else NotReducible
885 in
886 begin match ans with
887 | Reduced s' -> redrec s'
888 | NotReducible -> s'
889 end
890
891 | _ ->
892 match match_eval_ref env sigma x stack with
893 | EvEval (ref, u) ->
894 let ans =
895 let* sapp, nocase = red_elim_const infos env sigma ref u stack in
896 let hd, _ as s'' = redrec sapp in
897 let rec is_case x = match EConstr.kind sigma x with
898 | Lambda (_,_, x) | LetIn (_,_,_, x) | Cast (x, _,_) -> is_case x
899 | App (hd, _) -> is_case hd
900 | Case _ -> true
901 | _ -> false in
902 if nocase && is_case hd then NotReducible else Reduced s''
903 in
904 begin match ans with
905 | Reduced s' -> s'
906 | NotReducible -> s'
907 end
908 | EvSymbol ->
909 whd_all env sigma (applist s'), []
910 | EvPrim cst ->
911 let args =
912 List.map_filter_i (fun i a ->
913 match a with CPrimitives.Kwhnf -> Some i | _ -> None)
914 (CPrimitives.kind (Option.get (get_primitive env cst))) in
915 let ans =
916 let* stack = reduce_params infos env sigma stack args in
917 Reduced (whd_const cst env sigma (applist (x, stack)), [])
918 in
919 begin match ans with
920 | Reduced s' -> s'
921 | NotReducible -> s'
922 end
923 | EvNone -> s'
924 in
925 redrec
926
927 and reduce_fix infos env sigma f fix stack =
928 match fix_recarg fix stack with
929 | None -> NotReducible
930 | Some (recargnum,recarg) ->
931 let* (recarg'hd,_ as recarg') = whd_construct_stack infos env sigma recarg in
932 match EConstr.kind sigma recarg'hd with
933 | Construct _ ->
934 let stack' = List.assign stack recargnum (applist recarg') in
935 Reduced (contract_fix env sigma f fix, stack')
936 | _ -> NotReducible
937
938 and reduce_nested_projection infos env sigma c =
939 let rec redrec c =
940 match EConstr.kind sigma c with
941 | Proj (p, r, c) ->
942 let c' = match redrec c with NotReducible -> c | Reduced c -> c in
943 let npars = Projection.npars p in
944 reduce_projection infos env sigma (p,r) ~npars c'
945 | Case (n,u,pms,p,iv,c,brs) ->
946 let* c' = redrec c in
947 let p = (n,u,pms,p,iv,c',brs) in
948 begin match reduce_case infos env sigma p with
949 | Reduced c -> Reduced c
950 | NotReducible -> Reduced (mkCase p) (* Why not NotReducible *)
951 end
952 | _ -> NotReducible
953 in redrec c
954
955 and reduce_projection infos env sigma p ~npars c =
956 let* f, s = whd_construct infos env sigma (c, []) in
957 contract_projection env sigma f p ~npars s
958
959 and reduce_case infos env sigma (ci, u, pms, p, iv, c, lf) =
960 let* f, (hd, args) = whd_construct infos env sigma (c, []) in
961 match EConstr.kind sigma hd with
962 | Construct ((_, i as cstr),u) ->
963 let real_cargs = List.skipn ci.ci_npar args in
964 let br = lf.(i - 1) in
965 let ctx = EConstr.expand_branch env sigma u pms cstr br in
966 let br = it_mkLambda_or_LetIn (snd br) ctx in
967 Reduced (applist (br, real_cargs))
968 | CoFix (bodynum,(names,_,_) as cofix) ->
969 let cofix_def = contract_cofix env sigma f cofix in
970 (* If the cofix_def does not reduce to a constructor, do we
971 really want to say it is Reduced? Consider e.g.:
972 CoInductive stream := cons { hd : bool; tl : stream }.
973 CoFixpoint const (x : bool) := if x then cons x (const x) else cons x (const x).
974 Eval simpl in fun x => (const x).(tl) *)
975 Reduced (mkCase (ci, u, pms, p, iv, applist(cofix_def, args), lf))
976 | Int _ | Float _ | String _ | Array _ -> NotReducible (* TODO: assert false? *)
977 | _ -> assert false
978
979 and whd_construct_stack infos env sigma s =
980 let* _, s = whd_construct infos env sigma (s, []) in
981 Reduced s
982
983 (* reduce until finding an applied constructor (or primitive value) or fail *)
984
985 and whd_construct infos env sigma c =
986 let (constr, cargs) =
987 let construct_infos = { infos with red_behavior = ReductionBehaviour.Db.empty; main_reds = infos.construct_reds } in
988 whd_simpl_stack construct_infos env sigma c in
989 match match_eval_ref env sigma constr cargs with
990 | EvEval (ref, u) ->
991 (match compute_reference_coelimination infos env sigma ref u with
992 | CoEliminationConstruct c -> Reduced (None, whd_stack_gen infos.main_reds env sigma (applist (c, cargs)))
993 | CoEliminationPrimitive c -> Reduced (None, whd_stack_gen infos.main_reds env sigma (applist (c, cargs)))
994 | CoEliminationCoFix {refolding_target; refolding_data} ->
995 let (_, midargs as s) = descend infos.constant_body_cache env sigma refolding_target (ref,u) cargs in
996 let s = whd_nothing_for_iota env sigma s in
997 let f = refolding_data, midargs in
998 Reduced (Some f, s)
999 | NotACoElimination c ->
1000 (* Now try to get a construct/cofix/prim using the arguments of the constant
1001 so that possible internal iota-redexes are triggered *)
1002 whd_construct infos env sigma (c, cargs)
1003 | NotACoEliminationConstant -> NotReducible)
1004 | EvSymbol | EvPrim _ | EvNone ->
1005 if reducible_construct sigma constr then Reduced (None, (constr, cargs))
1006 else NotReducible
1007
1008 (************************************************************************)
1009 (* Special Purpose Reduction Strategies *)
1010
1011 (* Red reduction tactic: one step of delta reduction + full
1012 beta-iota-fix-cofix-zeta-cast at the head of the conclusion of a
1013 sequence of products; fails if no delta redex is around
1014 *)
1015
1016 let try_red_product env sigma c =
1017 let simpfun c = clos_norm_flags RedFlags.betaiotazeta env sigma c in
1018 let cache = CacheTable.create 12 in
1019 let rec redrec env x =
1020 let x = whd_betaiota env sigma x in
1021 match EConstr.kind sigma x with
1022 | App (f,l) ->
1023 (match EConstr.kind sigma f with
1024 | Fix fix ->
1025 (match fix_recarg fix (Array.to_list l) with
1026 | None -> NotReducible
1027 | Some (recargnum,recarg) ->
1028 let* recarg' = redrec env recarg in
1029 let l = Array.copy l in
1030 let () = Array.set l recargnum recarg' in
1031 Reduced (simpfun (mkApp (f, l))))
1032 | _ ->
1033 let* r = redrec env f in
1034 Reduced (simpfun (mkApp (r, l))))
1035 | Cast (c,_,_) -> redrec env c
1036 | Prod (x,a,b) ->
1037 let open Context.Rel.Declaration in
1038 let* b = redrec (push_rel (LocalAssum (x, a)) env) b in
1039 Reduced (mkProd (x, a, b))
1040 | LetIn (x,a,b,t) -> redrec env (Vars.subst1 a t)
1041 | Case (ci,u,pms,p,iv,d,lf) ->
1042 let* d = redrec env d in
1043 Reduced (simpfun (mkCase (ci,u,pms,p,iv,d,lf)))
1044 | Proj (p, r, c) ->
1045 let* c' =
1046 match EConstr.kind sigma c with
1047 | Construct _ | CoFix _ -> Reduced c
1048 | _ -> redrec env c
1049 in
1050 let npars = Projection.npars p in
1051 let* c = contract_projection env sigma None (p,r) ~npars (whd_betaiotazeta_stack env sigma c') in
1052 Reduced (simpfun c)
1053 | _ ->
1054 (match match_eval_ref env sigma x [] with
1055 | EvEval (ref, u) ->
1056 (* TO DO: re-fold fixpoints after expansion *)
1057 (* to get true one-step reductions *)
1058 (match reference_opt_value cache env sigma ref u with
1059 | None -> NotReducible
1060 | Some c -> Reduced c)
1061 | EvSymbol | EvPrim _ | EvNone -> NotReducible)
1062 in redrec env c
1063
1064 let red_product env sigma c = match try_red_product env sigma c with
1065 | Reduced c -> Some c
1066 | NotReducible -> None
1067
1068 (*
1069 (* This old version of hnf uses betadeltaiota instead of itself (resp
1070 whd_construct_state) to reduce the argument of Case (resp Fix);
1071 The new version uses the "simpl" strategy instead. For instance,
1072
1073 Variable n:nat.
1074 Eval hnf in match (plus (S n) O) with S n => n | _ => O end.
1075
1076 returned
1077
1078 (fix plus (n m : nat) {struct n} : nat :=
1079 match n with
1080 | O => m
1081 | S p => S (plus p m)
1082 end) n 0
1083
1084 while the new version returns (plus n O)
1085 *)
1086
1087 let whd_simpl_orelse_delta_but_fix_old env sigma c =
1088 let whd_all = whd_all_state env sigma in
1089 let rec redrec (x, stack as s) =
1090 match kind_of_term x with
1091 | Lambda (na,t,c) ->
1092 (match decomp_stack stack with
1093 | None -> s
1094 | Some (a,rest) -> stacklam redrec [a] c rest)
1095 | LetIn (n,b,t,c) -> stacklam redrec [b] c stack
1096 | App (f,cl) -> redrec (f, append_stack cl stack)
1097 | Cast (c,_,_) -> redrec (c, stack)
1098 | Case (ci,p,d,lf) ->
1099 (try
1100 redrec (reduce_case env sigma whd_all (ci,p,d,lf), stack)
1101 with Redelimination ->
1102 s)
1103 | Fix fix ->
1104 (match reduce_fix whd_all fix stack with
1105 | Reduced s' -> redrec s'
1106 | NotReducible -> s)
1107 | _ when isEvalRef env x ->
1108 let ref = destEvalRef x in
1109 (try
1110 redrec (red_elim_const env sigma ref stack)
1111 with Redelimination ->
1112 match reference_opt_value env sigma ref with
1113 | Some c ->
1114 (match kind_of_term (strip_lam c) with
1115 | CoFix _ | Fix _ -> s
1116 | _ -> redrec (c, stack))
1117 | None -> s)
1118 | _ -> s
1119 in app_stack (redrec (c, empty_stack))
1120 *)
1121
1122 (* Same as [whd_simpl] but also reduces constants that do not hide a
1123 reducible fix, but does this reduction of constants only until it
1124 immediately hides a non reducible fix or a cofix *)
1125
1126 let whd_simpl_orelse_delta_but_fix env sigma c =
1127 let infos = make_simpl_infos (make_hnf_reds env) in
1128 let rec redrec s =
1129 let (constr, stack as s') = whd_simpl_stack infos env sigma s in
1130 match match_eval_ref_value env sigma constr stack with
1131 | Some c ->
1132 (match EConstr.kind sigma (snd (decompose_lambda sigma c)) with
1133 | CoFix _ | Fix _ -> s'
1134 | Proj (p,_,t) when
1135 (match EConstr.kind sigma constr with
1136 | Const (c', _) -> QConstant.equal env (Projection.constant p) c'
1137 | _ -> false) ->
1138 let npars = Projection.npars p in
1139 if List.length stack <= npars then
1140 (* Do not show the eta-expanded form *)
1141 s'
1142 else redrec (c, stack)
1143 | _ -> redrec (c, stack))
1144 | None -> s'
1145 in
1146 applist (redrec c)
1147
1148 let hnf_constr0 env sigma c =
1149 whd_simpl_orelse_delta_but_fix env sigma (c, [])
1150
1151 let hnf_constr env sigma c =
1152 let c = whd_simpl_orelse_delta_but_fix env sigma (c, []) in
1153 clos_norm_flags RedFlags.betaiota env sigma c
1154
1155 (* The "simpl" reduction tactic *)
1156
1157 let whd_simpl_with_reds infos env sigma c =
1158 applist (whd_simpl_stack infos env sigma (c, []))
1159
1160 let whd_simpl env sigma x =
1161 let infos = make_simpl_infos (make_simpl_reds env) in
1162 whd_simpl_with_reds infos env sigma x
1163
1164 let simpl env sigma c =
1165 let infos = make_simpl_infos (make_simpl_reds env) in
1166 let rec strongrec env t =
1167 map_constr_with_full_binders env sigma push_rel strongrec env
1168 (whd_simpl_with_reds infos env sigma t) in
1169 strongrec env c
1170
1171 (* Reduction at specific subterms *)
1172
1173 let matches_head env sigma c t =
1174 let t, l = decompose_app sigma t in
1175 match EConstr.kind sigma t, Array.is_empty l with
1176 | Proj (p, _, _), _ -> Constr_matching.matches env sigma c (mkConstU (Projection.constant p, EInstance.empty))
1177 | _, false -> Constr_matching.matches env sigma c t
1178 | _ -> raise Constr_matching.PatternMatchingFailure
1179
1180 (** FIXME: Specific function to handle projections: it ignores what happens on the
1181 parameters. This is a temporary fix while rewrite etc... are not up to equivalence
1182 of the projection and its eta expanded form.
1183 *)
1184 let change_map_constr_with_binders_left_to_right changed g f (env, l as acc) sigma c =
1185 match EConstr.kind sigma c with
1186 | Proj (p, r, v) -> (* Treat specially for partial applications *)
1187 let t = Retyping.expand_projection env sigma p v [] in
1188 let hdf, al = destApp sigma t in
1189 let a = al.(Array.length al - 1) in
1190 let app = (mkApp (hdf, Array.sub al 0 (Array.length al - 1))) in
1191 let app' = f acc app in
1192 let a' = f acc a in
1193 let hdf', _ = decompose_app sigma app' in
1194 if hdf' == hdf then
1195 (* Still the same projection, we ignore the change in parameters *)
1196 mkProj (p, r, a')
1197 else
1198 let () = changed := true in
1199 mkApp (app', [| a' |])
1200 | _ -> map_constr_with_binders_left_to_right env sigma g f acc c
1201
1202 let e_contextually byhead (occs,c) f = begin fun env sigma t ->
1203 let count = ref (Locusops.initialize_occurrence_counter occs) in
1204 (* FIXME: we do suspicious things with this evarmap *)
1205 let evd = ref sigma in
1206 let changed = ref false in
1207 let rec traverse nested (env,c as envc) t =
1208 if Locusops.occurrences_done !count then (* Shortcut *) t
1209 else
1210 try
1211 let subst =
1212 if byhead then matches_head env sigma c t
1213 else Constr_matching.matches env sigma c t in
1214 let ok, count' = Locusops.update_occurrence_counter !count in count := count';
1215 if ok then begin
1216 if Option.has_some nested then
1217 user_err Pp.(str "The subterm at occurrence " ++ int (Option.get nested) ++ str " overlaps with the subterm at occurrence " ++ int (Locusops.current_occurrence !count) ++ str ".");
1218 (* Skip inner occurrences for stable counting of occurrences *)
1219 let () = if Locusops.more_specific_occurrences !count then
1220 ignore (traverse_below (Some (Locusops.current_occurrence !count)) envc t)
1221 in
1222 match (f subst) env !evd t with
1223 | NoChange -> t
1224 | Changed (evm, t) ->
1225 let () = changed := true in
1226 let () = evd := evm in
1227 t
1228 end
1229 else
1230 traverse_below nested envc t
1231 with Constr_matching.PatternMatchingFailure ->
1232 traverse_below nested envc t
1233 and traverse_below nested envc t =
1234 (* when byhead, find other occurrences without matching again partial
1235 application with same head *)
1236 match EConstr.kind !evd t with
1237 | App (f,l) when byhead -> mkApp (f, Array.map_left (traverse nested envc) l)
1238 | Proj (p,r,c) when byhead -> mkProj (p,r,traverse nested envc c)
1239 | _ ->
1240 change_map_constr_with_binders_left_to_right changed
1241 (fun d (env,c) -> (push_rel d env, Patternops.lift_pattern 1 c))
1242 (traverse nested) envc sigma t
1243 in
1244 let t' = traverse None (env,c) t in
1245 let () = Locusops.check_used_occurrences !count in
1246 if !changed then Changed (!evd, t') else NoChange
1247 end
1248
1249 let contextually byhead occs f env sigma t =
1250 let f' subst env sigma t = Changed (sigma, f subst env sigma t) in
1251 match e_contextually byhead occs f' env sigma t with
1252 | Changed (_, t) -> t
1253 | NoChange -> t
1254
1255 (* linear bindings (following pretty-printer) of the value of name in c.
1256 * n is the number of the next occurrence of name.
1257 * ol is the occurrence list to find. *)
1258
1259 let match_constr_evaluable_ref env sigma c evref =
1260 match EConstr.kind sigma c, evref with
1261 | Const (c,u), Evaluable.EvalConstRef c' when QConstant.equal env c c' -> Some u
1262 | Proj (p,_,_), Evaluable.EvalProjectionRef p' when QProjection.Repr.equal env (Projection.repr p) p' -> Some EInstance.empty
1263 | Var id, Evaluable.EvalVarRef id' when Id.equal id id' -> Some EInstance.empty
1264 | _, _ -> None
1265
1266 let substlin env sigma evalref occs c =
1267 let count = ref (Locusops.initialize_occurrence_counter occs) in
1268 let value u = value_of_evaluable_ref env sigma evalref u in
1269 let rec substrec () c =
1270 if Locusops.occurrences_done !count then c
1271 else
1272 match match_constr_evaluable_ref env sigma c evalref with
1273 | Some u ->
1274 let ok, count' = Locusops.update_occurrence_counter !count in
1275 count := count';
1276 if ok then value u else c
1277 | None ->
1278 map_constr_with_binders_left_to_right env sigma
1279 (fun _ () -> ())
1280 substrec () c
1281 in
1282 let t' = substrec () c in
1283 Locusops.check_used_occurrences !count;
1284 (Locusops.current_occurrence !count, t')
1285
1286 let string_of_evaluable_ref env = function
1287 | Evaluable.EvalVarRef id -> Id.to_string id
1288 | Evaluable.EvalConstRef kn ->
1289 Libnames.string_of_qualid
1290 (Nametab.shortest_qualid_of_global (vars_of_env env) (GlobRef.ConstRef kn))
1291 | Evaluable.EvalProjectionRef p ->
1292 Projection.Repr.to_string p
1293
1294 (* Removing fZETA for finer behaviour would break many developments *)
1295 let unfold_side_flags = RedFlags.[fBETA;fMATCH;fFIX;fCOFIX;fZETA]
1296 let unfold_side_red = RedFlags.(mkflags [fBETA;fMATCH;fFIX;fCOFIX;fZETA])
1297 let unfold_red kn =
1298 let open RedFlags in
1299 let flags = fDELTA :: unfold_side_flags in
1300 let flags = match kn with
1301 | Evaluable.EvalVarRef id -> fVAR id :: flags
1302 | Evaluable.EvalConstRef sp ->
1303 begin
1304 match Structures.PrimitiveProjections.find_opt sp with
1305 | None -> fCONST sp :: flags
1306 | Some p -> fCONST sp :: fPROJ p :: flags
1307 end
1308 | Evaluable.EvalProjectionRef p ->
1309 fPROJ p :: fCONST (Projection.Repr.constant p) :: flags
1310 in
1311 mkflags flags
1312
1313 let unfold env sigma name c =
1314 if is_evaluable env sigma name then
1315 clos_norm_flags (unfold_red name) env sigma c
1316 else
1317 user_err Pp.(str (string_of_evaluable_ref env name^" is opaque."))
1318
1319 (** [unfoldoccs : (readable_constraints -> (int list * full_path) -> constr -> constr)]
1320 unfolds the constant name in a term c following a list of occurrences occl.
1321 at the occurrences of occ_list. If occ_list is empty, unfold all occurrences.
1322 Performs a betaiota reduction after unfolding. *)
1323 let unfoldoccs env sigma (occs,name) c =
1324 let open Locus in
1325 match occs with
1326 | NoOccurrences -> c
1327 | AllOccurrences -> unfold env sigma name c
1328 | OnlyOccurrences _ | AllOccurrencesBut _ | AtLeastOneOccurrence ->
1329 let (occ,uc) = substlin env sigma name occs c in
1330 if Int.equal occ 0 then
1331 user_err Pp.(str ((string_of_evaluable_ref env name)^" does not occur."));
1332 nf_betaiotazeta env sigma uc
1333
1334 (** Unfold reduction tactic. *)
1335 let unfoldn loccname env sigma c =
1336 List.fold_left (fun c occname -> unfoldoccs env sigma occname c) c loccname
1337
1338 (*** Re-folding constants tactics: refold com in term c. *)
1339 let fold_one_com com env sigma c =
1340 let rcom = match red_product env sigma com with
1341 | None -> user_err Pp.(str "No head constant to reduce.")
1342 | Some c -> c
1343 in
1344 (* Reason first on the beta-iota-zeta normal form of the constant as
1345 unfold produces it, so that the "unfold f; fold f" configuration works
1346 to refold fix expressions *)
1347 let a = subst_term sigma (clos_norm_flags unfold_side_red env sigma rcom) c in
1348 if not (EConstr.eq_constr sigma a c) then
1349 Vars.subst1 com a
1350 else
1351 (* Then reason on the non beta-iota-zeta form for compatibility -
1352 even if it is probably a useless configuration *)
1353 let a = subst_term sigma rcom c in
1354 Vars.subst1 com a
1355
1356 let fold_commands cl env sigma c =
1357 List.fold_right (fun com c -> fold_one_com com env sigma c) (List.rev cl) c
1358
1359
1360 (* call by value reduction functions *)
1361 let cbv_norm_flags flags ~strong env sigma t =
1362 Cbv.(cbv_norm (create_cbv_infos flags ~strong env sigma) t)
1363
1364 let cbv_beta = cbv_norm_flags RedFlags.beta ~strong:true
1365 let cbv_betaiota = cbv_norm_flags RedFlags.betaiota ~strong:true
1366 let cbv_betadeltaiota env sigma = cbv_norm_flags RedFlags.all env sigma ~strong:true
1367 let whd_cbv_betadeltaiota env sigma = cbv_norm_flags RedFlags.all env sigma ~strong:false
1368
1369 let whd_compute = whd_cbv_betadeltaiota
1370 let compute = cbv_betadeltaiota
1371
1372 (* Pattern *)
1373
1374 (* gives [na:ta]c' such that c converts to ([na:ta]c' a), abstracting only
1375 * the specified occurrences. *)
1376
1377 let abstract_scheme env (locc,a) (c, sigma) =
1378 let ta = Retyping.get_type_of env sigma a in
1379 let r = Retyping.relevance_of_term env sigma a in
1380 let sigma, ta = Evarsolve.refresh_universes ~onlyalg:true (Some false) env sigma ta in
1381 let na = Namegen.named_hd env sigma ta Anonymous in
1382 let na = make_annot na r in
1383 if occur_meta sigma ta then user_err Pp.(str "Cannot find a type for the generalisation.");
1384 if occur_meta sigma a then
1385 mkLambda (na,ta,c), sigma
1386 else
1387 let c', sigma = Find_subterm.subst_closed_term_occ env sigma (Locus.AtOccs locc) a c in
1388 mkLambda (na,ta,c'), sigma
1389
1390 let pattern_occs loccs_trm = begin fun env sigma c ->
1391 let abstr_trm, sigma = List.fold_right (abstract_scheme env) loccs_trm (c,sigma) in
1392 try
1393 let sigma, _ = Typing.type_of env sigma abstr_trm in
1394 Changed (sigma, applist(abstr_trm, List.map snd loccs_trm)) (* TODO: fast path *)
1395 with Type_errors.TypeError (env',t) ->
1396 raise (ReductionTacticError (InvalidAbstraction (env,sigma,abstr_trm,(env',t))))
1397 end
1398
1399 (* Used in several tactics. *)
1400
1401 let check_privacy env ind =
1402 let spec = Inductive.lookup_mind_specif env ind in
1403 if Inductive.is_private spec then
1404 user_err Pp.(str "case analysis on a private type is not allowed.")
1405
1406 (* put t as t'=(x1:A1)..(xn:An)B with B an inductive definition of name name
1407 return name, B and t' *)
1408
1409 let reduce_to_ind_gen allow_product env sigma t =
1410 let rec elimrec env t l =
1411 let t = hnf_constr0 env sigma t in
1412 match EConstr.kind sigma (fst (decompose_app sigma t)) with
1413 | Ind (ind, _ as indu) ->
1414 let t = nf_betaiota env sigma t in
1415 check_privacy env ind; (Some indu, it_mkProd_or_LetIn t l)
1416 | Prod (n,ty,t') ->
1417 let open Context.Rel.Declaration in
1418 if allow_product then
1419 let ty = nf_betaiota env sigma ty in
1420 elimrec (push_rel (LocalAssum (n,ty)) env) t' ((LocalAssum (n,ty))::l)
1421 else
1422 None, it_mkProd_or_LetIn t l
1423 | _ ->
1424 (* Last chance: we allow to bypass the Opaque flag (as it
1425 was partially the case between V5.10 and V8.1 *)
1426 let t' = whd_all env sigma t in
1427 match EConstr.kind sigma (fst (decompose_app sigma t')) with
1428 | Ind (ind, _ as indu) -> check_privacy env ind; (Some indu, it_mkProd_or_LetIn t' l)
1429 | _ -> None, it_mkProd_or_LetIn t l
1430
1431 in
1432 elimrec env t []
1433
1434 let reduce_to_quantified_ind env sigma c =
1435 match reduce_to_ind_gen true env sigma c with
1436 | None, _ -> user_err Pp.(str"Not an inductive definition.")
1437 | Some i, t -> i, t
1438 let reduce_to_atomic_ind env sigma c =
1439 match reduce_to_ind_gen false env sigma c with
1440 | None, _ -> user_err Pp.(str"Not an inductive definition.")
1441 | Some i, t -> i, t
1442
1443 let eval_to_quantified_ind env sigma t =
1444 let rec elimrec env t =
1445 let t = hnf_constr0 env sigma t in
1446 match EConstr.kind sigma (fst (decompose_app sigma t)) with
1447 | Ind (ind, _ as indu) ->
1448 let () = check_privacy env ind in
1449 indu
1450 | Prod (n,ty,t') ->
1451 elimrec (push_rel (Context.Rel.Declaration.LocalAssum (n,ty)) env) t'
1452 | _ ->
1453 (* Last chance: we allow to bypass the Opaque flag (as it
1454 was partially the case between V5.10 and V8.1 *)
1455 let t' = whd_all env sigma t in
1456 match EConstr.kind sigma (fst (decompose_app sigma t')) with
1457 | Ind (ind, _ as indu) -> check_privacy env ind; indu
1458 | _ -> user_err Pp.(str"Not an inductive product.")
1459 in
1460 elimrec env t
1461
1462 let find_hnf_rectype env sigma t =
1463 let ind,t = reduce_to_atomic_ind env sigma t in
1464 ind, snd (decompose_app_list sigma t)
1465
1466 (* Reduce the weak-head redex [beta,iota/fix/cofix[all],cast,zeta,simpl/delta]
1467 or raise [NotStepReducible] if not a weak-head redex *)
1468
1469 exception NotStepReducible
1470
1471 let one_step_reduce env sigma c =
1472 let infos = make_simpl_infos (ReductionBehaviour.Db.empty, RedFlags.betadeltazeta, RedFlags.betadeltazeta) in
1473 let rec redrec (x, stack) =
1474 match EConstr.kind sigma x with
1475 | Lambda (n,t,c) ->
1476 (match stack with
1477 | [] -> raise NotStepReducible
1478 | a :: rest -> (Vars.subst1 a c, rest))
1479 | App (f,cl) -> redrec (f, (Array.to_list cl)@stack)
1480 | LetIn (_,f,_,cl) -> (Vars.subst1 f cl,stack)
1481 | Cast (c,_,_) -> redrec (c,stack)
1482 | Case (ci,u,pms,p,iv,c,lf) ->
1483 begin match reduce_case infos env sigma (ci,u,pms,p,iv,c,lf) with
1484 | Reduced c -> (c, stack)
1485 | NotReducible -> raise NotStepReducible
1486 end
1487 | Fix fix ->
1488 begin match reduce_fix infos env sigma None fix stack with
1489 | Reduced s' -> s'
1490 | NotReducible -> raise NotStepReducible
1491 end
1492 (* Why not treating Proj? *)
1493 | _ when isEvalRef env sigma x ->
1494 let ref,u = destEvalRefU sigma x in
1495 begin match red_elim_const infos env sigma ref u stack with
1496 | Reduced (c, _) -> c
1497 | NotReducible ->
1498 match reference_opt_value infos.constant_body_cache env sigma ref u with
1499 | Some d -> (d, stack)
1500 | None -> raise NotStepReducible
1501 end
1502
1503 | _ -> raise NotStepReducible
1504 in
1505 applist (redrec (c,[]))
1506
1507 let error_cannot_recognize ref =
1508 user_err
1509 Pp.(str "Cannot recognize a statement based on " ++
1510 Nametab.pr_global_env Id.Set.empty ref ++ str".")
1511
1512 let reduce_to_ref_gen allow_failure allow_product env sigma ref t =
1513 match ref with
1514 | GlobRef.IndRef mind' ->
1515 let (i,t) = reduce_to_ind_gen allow_product env sigma t in
1516 if allow_failure then t else
1517 (match i with
1518 | Some (mind,u) when QInd.equal env mind mind' -> t
1519 | _ -> error_cannot_recognize ref)
1520 | _ -> (* lazily reduces to match the head of [t] with the expected [ref] *)
1521 let rec elimrec env t l =
1522 let c, _ = decompose_app sigma t in
1523 match EConstr.kind sigma c with
1524 | Prod (n,ty,t') ->
1525 if allow_product then
1526 let open Context.Rel.Declaration in
1527 elimrec (push_rel (LocalAssum (n,ty)) env) t' ((LocalAssum (n,ty))::l)
1528 else if allow_failure then
1529 it_mkProd_or_LetIn t l
1530 else
1531 error_cannot_recognize ref
1532 | _ ->
1533 if isRefX env sigma ref c
1534 then it_mkProd_or_LetIn t l
1535 else
1536 try
1537 let t' = nf_betaiota env sigma (one_step_reduce env sigma t) in
1538 elimrec env t' l
1539 with NotStepReducible ->
1540 if allow_failure then
1541 it_mkProd_or_LetIn t l
1542 else
1543 error_cannot_recognize ref
1544 in
1545 elimrec env t []
1546
1547 let reduce_to_quantified_ref ?(allow_failure=false) = reduce_to_ref_gen allow_failure true
1548 let reduce_to_atomic_ref ?(allow_failure=false) = reduce_to_ref_gen allow_failure false