Debian Codegraph @

tactics/cbn.ml

raw symbols SCIP
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * INRIA, CNRS and contributors - Copyright 1999-2019 *)
4 (* <O___,, * (see CREDITS file for the list of authors) *)
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 Util
12 open Names
13 open Constr
14 open Context
15 open Termops
16 open Univ
17 open Environ
18 open EConstr
19 open Vars
20 open Context.Rel.Declaration
21
22 (** This module implements a call by name reduction used by the cbn tactic.
23
24 It has an ability to "refold" constants by storing constants and
25 their parameters in its stack.
26 *)
27
28 (** Machinery to custom the behavior of the reduction *)
29 module ReductionBehaviour = Reductionops.ReductionBehaviour
30
31 type volatile = { volatile : bool } [@@unboxed]
32
33 (** Machinery about stack of unfolded constants *)
34 module Cst_stack = struct
35 open EConstr
36
37 (** constant * params * args
38
39 - constant applied to params = term in head applied to args
40 - there is at most one arguments with an empty list of args, it must be the first.
41 - in args, the int represents the indice of the first arg to consider *)
42 type t = (constr * constr list * (int * constr array) list * volatile) list
43
44 let empty = []
45 let all_volatile = CList.for_all (fun (_,_,_,{volatile}) -> volatile)
46
47 let drop_useless = function
48 | _ :: ((_,_,[],_)::_ as q) -> q
49 | l -> l
50
51 let add_param h cst_l =
52 let append2cst = function
53 | (c,params,[],vol) -> (c, h::params, [], vol)
54 | (c,params,((i,t)::q),vol) when i = pred (Array.length t) ->
55 (c, params, q, vol)
56 | (c,params,(i,t)::q, vol) ->
57 (c, params, (succ i,t)::q, vol)
58 in
59 drop_useless (List.map append2cst cst_l)
60
61 let add_args cl =
62 List.map (fun (a,b,args,vol) -> (a,b,(0,cl)::args,vol))
63
64 let add_cst ?(volatile=false) cst = function
65 | (_,_,[],_) :: q as l -> l
66 | l -> (cst,[],[],{volatile})::l
67
68 let best_cst = function
69 | (cst,params,[],_)::_ -> Some(cst,params)
70 | _ -> None
71
72 let reference sigma t = match best_cst t with
73 | Some (c, params) when isConst sigma c -> Some (fst (destConst sigma c), params)
74 | _ -> None
75
76 (** [best_replace d cst_l c] makes the best replacement for [d]
77 by [cst_l] in [c] *)
78 let best_replace sigma d cst_l c =
79 let reconstruct_head = List.fold_left
80 (fun t (i,args) -> mkApp (t,Array.sub args i (Array.length args - i))) in
81 List.fold_right
82 (fun (cst,params,args,_) t -> Termops.replace_term sigma
83 (reconstruct_head d args)
84 (applist (cst, List.rev params))
85 t) cst_l c
86
87 let pr env sigma l =
88 let open Pp in
89 let p_c c = Termops.Internal.print_constr_env env sigma c in
90 prlist_with_sep pr_semicolon
91 (fun (c,params,args,{volatile}) ->
92 hov 1 (str"(" ++ p_c c ++ str ")" ++ spc () ++ pr_sequence p_c params ++ spc () ++ str "(args:" ++
93 pr_sequence (fun (i,el) -> prvect_with_sep spc p_c (Array.sub el i (Array.length el - i))) args ++
94 str ")" ++
95 (if volatile then str " (volatile)" else mt()))) l
96 end
97
98
99 (** The type of (machine) stacks (= lambda-bar-calculus' contexts) *)
100 module Stack :
101 sig
102 open EConstr
103 type 'a app_node
104
105 type cst_member =
106 | Cst_const of pconstant
107 | Cst_proj of Projection.t * ERelevance.t
108
109 type 'a case_stk =
110 case_info * EInstance.t * 'a array * ('a,ERelevance.t) pcase_return * 'a pcase_invert * ('a,ERelevance.t) pcase_branch array
111 type 'a member =
112 | App of 'a app_node
113 | Case of 'a case_stk * Cst_stack.t
114 | Proj of Projection.t * ERelevance.t * Cst_stack.t
115 | Fix of ('a, 'a, ERelevance.t) pfixpoint * 'a t * Cst_stack.t
116 | Primitive of CPrimitives.t * (Constant.t * EInstance.t) * 'a t * CPrimitives.args_red * Cst_stack.t
117 | Cst of { const : cst_member;
118 curr : int;
119 remains : int list;
120 params : 'a t;
121 volatile : bool;
122 cst_l : Cst_stack.t;
123 }
124
125 and 'a t = 'a member list
126
127 val pr : ('a -> Pp.t) -> 'a t -> Pp.t
128 val empty : 'a t
129 val append_app : 'a array -> 'a t -> 'a t
130 val decomp : 'a t -> ('a * 'a t) option
131 val equal : env -> ('a -> 'a -> bool) -> (('a, 'a, ERelevance.t) pfixpoint -> ('a, 'a, ERelevance.t) pfixpoint -> bool)
132 -> ('a case_stk -> 'a case_stk -> bool) -> 'a t -> 'a t -> bool
133 val strip_app : 'a t -> 'a t * 'a t
134 val strip_n_app : int -> 'a t -> ('a t * 'a * 'a t) option
135 val will_expose_iota : 'a t -> bool
136 val list_of_app_stack : constr t -> constr list option
137 val args_size : 'a t -> int
138 val tail : int -> 'a t -> 'a t
139 val nth : 'a t -> int -> 'a
140 val best_state : Evd.evar_map -> constr * constr t -> Cst_stack.t -> constr * constr t
141 val zip : ?refold:bool -> Evd.evar_map -> constr * constr t -> constr
142 val check_native_args : CPrimitives.t -> 'a t -> bool
143 val get_next_primitive_args : CPrimitives.args_red -> 'a t -> CPrimitives.args_red * ('a t * 'a * 'a t) option
144 end =
145 struct
146 open EConstr
147 type 'a app_node = int * 'a array * int
148 (* first releavnt position, arguments, last relevant position *)
149
150 (*
151 Invariant that this module must ensure :
152 (behare of direct access to app_node by the rest of Reductionops)
153 - in app_node (i,_,j) i <= j
154 - There is no array realocation (outside of debug printing)
155 *)
156
157 let pr_app_node pr (i,a,j) =
158 let open Pp in surround (
159 prvect_with_sep pr_comma pr (Array.sub a i (j - i + 1))
160 )
161
162
163 type cst_member =
164 | Cst_const of pconstant
165 | Cst_proj of Projection.t * ERelevance.t
166
167 type 'a case_stk =
168 case_info * EInstance.t * 'a array * ('a,ERelevance.t) pcase_return * 'a pcase_invert * ('a,ERelevance.t) pcase_branch array
169 type 'a member =
170 | App of 'a app_node
171 | Case of 'a case_stk * Cst_stack.t
172 | Proj of Projection.t * ERelevance.t * Cst_stack.t
173 | Fix of ('a, 'a, ERelevance.t) pfixpoint * 'a t * Cst_stack.t
174 | Primitive of CPrimitives.t * (Constant.t * EInstance.t) * 'a t * CPrimitives.args_red * Cst_stack.t
175 | Cst of { const : cst_member;
176 curr : int;
177 remains : int list;
178 params : 'a t;
179 volatile : bool;
180 cst_l : Cst_stack.t;
181 }
182
183 and 'a t = 'a member list
184
185 (* Debugging printer *)
186 let rec pr_member pr_c member =
187 let open Pp in
188 let pr_c x = hov 1 (pr_c x) in
189 match member with
190 | App app -> str "ZApp" ++ pr_app_node pr_c app
191 | Case ((_,_,_,_,_,br),cst) ->
192 str "ZCase(" ++
193 prvect_with_sep (pr_bar) (fun (_, b) -> pr_c b) br
194 ++ str ")"
195 | Proj (p,_,cst) ->
196 str "ZProj(" ++ Projection.debug_print p ++ str ")"
197 | Fix (f,args,cst) ->
198 str "ZFix(" ++ Constr.debug_print_fix pr_c f
199 ++ pr_comma () ++ pr pr_c args ++ str ")"
200 | Primitive (p,c,args,kargs,cst_l) ->
201 str "ZPrimitive(" ++ str (CPrimitives.to_string p)
202 ++ pr_comma () ++ pr pr_c args ++ str ")"
203 | Cst {const=mem;curr;remains;params;cst_l} ->
204 str "ZCst(" ++ pr_cst_member pr_c mem ++ pr_comma () ++ int curr
205 ++ pr_comma () ++
206 prlist_with_sep pr_semicolon int remains ++
207 pr_comma () ++ pr pr_c params ++ str ")"
208 and pr pr_c l =
209 let open Pp in
210 prlist_with_sep pr_semicolon (fun x -> hov 1 (pr_member pr_c x)) l
211
212 and pr_cst_member pr_c c =
213 let open Pp in
214 match c with
215 | Cst_const (c, u) ->
216 if UVars.Instance.is_empty u then Constant.debug_print c
217 else str"(" ++ Constant.debug_print c ++ str ", " ++
218 UVars.Instance.pr Sorts.QVar.raw_pr Univ.Level.raw_pr u ++ str")"
219 | Cst_proj (p,r) ->
220 str".(" ++ Projection.debug_print p ++ str")"
221
222 let empty = []
223
224 let append_app v s =
225 let le = Array.length v in
226 if Int.equal le 0 then s else App (0,v,pred le) :: s
227
228 let decomp_node (i,l,j) sk =
229 if i < j then (l.(i), App (succ i,l,j) :: sk)
230 else (l.(i), sk)
231
232 let decomp = function
233 | App node::s -> Some (decomp_node node s)
234 | _ -> None
235
236 let decomp_node_last (i,l,j) sk =
237 if i < j then (l.(j), App (i,l,pred j) :: sk)
238 else (l.(j), sk)
239
240 let equal env f f_fix f_case sk1 sk2 =
241 let equal_cst_member x y =
242 match x, y with
243 | Cst_const (c1,u1), Cst_const (c2, u2) ->
244 QConstant.equal env c1 c2 && UVars.Instance.equal u1 u2
245 | Cst_proj (p1,_), Cst_proj (p2,_) -> QProjection.Repr.equal env (Projection.repr p1) (Projection.repr p2)
246 | _, _ -> false
247 in
248 let rec equal_rec sk1 sk2 =
249 match sk1,sk2 with
250 | [],[] -> true
251 | App a1 :: s1, App a2 :: s2 ->
252 let t1,s1' = decomp_node_last a1 s1 in
253 let t2,s2' = decomp_node_last a2 s2 in
254 (f t1 t2) && (equal_rec s1' s2')
255 | Case ((ci1,pms1,p1,t1,iv1,a1),_) :: s1, Case ((ci2,pms2,p2,iv2,t2,a2),_) :: s2 ->
256 f_case (ci1,pms1,p1,t1,iv1,a1) (ci2,pms2,p2,iv2,t2,a2) && equal_rec s1 s2
257 | (Proj (p,_,_)::s1, Proj(p2,_,_)::s2) ->
258 QProjection.Repr.equal env (Projection.repr p) (Projection.repr p2)
259 && equal_rec s1 s2
260 | Fix (f1,s1,_) :: s1', Fix (f2,s2,_) :: s2' ->
261 f_fix f1 f2
262 && equal_rec (List.rev s1) (List.rev s2)
263 && equal_rec s1' s2'
264 | Cst c1::s1', Cst c2::s2' ->
265 equal_cst_member c1.const c2.const
266 && equal_rec (List.rev c1.params) (List.rev c2.params)
267 && equal_rec s1' s2'
268 | ((App _|Case _|Proj _|Fix _|Cst _|Primitive _)::_|[]), _ -> false
269 in equal_rec (List.rev sk1) (List.rev sk2)
270
271 let append_app_list l s =
272 let a = Array.of_list l in
273 append_app a s
274
275 let rec args_size = function
276 | App (i,_,j)::s -> j + 1 - i + args_size s
277 | (Case _|Fix _|Proj _|Cst _|Primitive _)::_ | [] -> 0
278
279 let strip_app s =
280 let rec aux out = function
281 | ( App _ as e) :: s -> aux (e :: out) s
282 | s -> List.rev out,s
283 in aux [] s
284 let strip_n_app n s =
285 let rec aux n out = function
286 | App (i,a,j) as e :: s ->
287 let nb = j - i + 1 in
288 if n >= nb then
289 aux (n - nb) (e::out) s
290 else
291 let p = i+n in
292 Some (CList.rev
293 (if Int.equal n 0 then out else App (i,a,p-1) :: out),
294 a.(p),
295 if j > p then App(succ p,a,j)::s else s)
296 | s -> None
297 in aux n [] s
298
299 let will_expose_iota args =
300 List.exists
301 (function (Fix (_,_,l) | Case (_,l) |
302 Proj (_,_,l) | Cst {cst_l=l}) when Cst_stack.all_volatile l -> true | _ -> false)
303 args
304
305 let list_of_app_stack s =
306 let rec aux = function
307 | App (i,a,j) :: s ->
308 let (args',s') = aux s in
309 let a' = Array.sub a i (j - i + 1) in
310 (Array.fold_right (fun x y -> x::y) a' args', s')
311 | s -> ([],s) in
312 let (out,s') = aux s in
313 let init = match s' with [] -> true | _ -> false in
314 Option.init init out
315
316 let tail n0 s0 =
317 let rec aux n s =
318 if Int.equal n 0 then s else
319 match s with
320 | App (i,a,j) :: s ->
321 let nb = j - i + 1 in
322 if n >= nb then
323 aux (n - nb) s
324 else
325 let p = i+n in
326 if j >= p then App(p,a,j)::s else s
327 | _ -> raise (Invalid_argument "Reductionops.Stack.tail")
328 in aux n0 s0
329
330 let nth s p =
331 match strip_n_app p s with
332 | Some (_,el,_) -> el
333 | None -> raise Not_found
334
335 (** This function breaks the abstraction of Cst_stack ! *)
336 let best_state sigma (_,sk as s) l =
337 let rec aux sk def = function
338 |(_,_,_,{volatile=true}) -> def
339 |(cst, params, [], _) -> (cst, append_app_list (List.rev params) sk)
340 |(cst, params, (i,t)::q, vol) -> match decomp sk with
341 | Some (el,sk') when EConstr.eq_constr sigma el t.(i) ->
342 if i = pred (Array.length t)
343 then aux sk' def (cst, params, q, vol)
344 else aux sk' def (cst, params, (succ i,t)::q, vol)
345 | _ -> def
346 in List.fold_left (aux sk) s l
347
348 let constr_of_cst_member f sk =
349 match f with
350 | Cst_const (c, u) -> mkConstU (c, EInstance.make u), sk
351 | Cst_proj (p,r) ->
352 match decomp sk with
353 | Some (hd, sk) -> mkProj (p, r, hd), sk
354 | None -> assert false
355
356 let zip ?(refold=false) sigma s =
357 let rec zip = function
358 | f, [] -> f
359 | f, (App (i,a,j) :: s) ->
360 let a' = if Int.equal i 0 && Int.equal j (Array.length a - 1)
361 then a
362 else Array.sub a i (j - i + 1) in
363 zip (mkApp (f, a'), s)
364 | f, (Case ((ci,u,pms,rt,iv,br),cst_l)::s) when refold ->
365 zip (best_state sigma (mkCase (ci,u,pms,rt,iv,f,br), s) cst_l)
366 | f, (Case ((ci,u,pms,rt,iv,br),_)::s) -> zip (mkCase (ci,u,pms,rt,iv,f,br), s)
367 | f, (Fix (fix,st,cst_l)::s) when refold ->
368 zip (best_state sigma (mkFix fix, st @ (append_app [|f|] s)) cst_l)
369 | f, (Fix (fix,st,_)::s) -> zip
370 (mkFix fix, st @ (append_app [|f|] s))
371 | f, (Cst {const;params;cst_l}::s) when refold ->
372 zip (best_state sigma (constr_of_cst_member const (params @ (append_app [|f|] s))) cst_l)
373 | f, (Cst {const;params}::s) ->
374 zip (constr_of_cst_member const (params @ (append_app [|f|] s)))
375 | f, (Proj (p,r,cst_l)::s) when refold ->
376 zip (best_state sigma (mkProj (p,r,f),s) cst_l)
377 | f, (Proj (p,r,_)::s) -> zip (mkProj (p,r,f),s)
378 | f, (Primitive (p,c,args,kargs,cst_l)::s) ->
379 zip (mkConstU c, args @ append_app [|f|] s)
380 in
381 zip s
382
383 (* Check if there is enough arguments on [stk] w.r.t. arity of [op] *)
384 let check_native_args op stk =
385 let nargs = CPrimitives.arity op in
386 let rargs = args_size stk in
387 nargs <= rargs
388
389 let get_next_primitive_args kargs stk =
390 let rec nargs = function
391 | [] -> 0
392 | CPrimitives.Kwhnf :: _ -> 0
393 | _ :: s -> 1 + nargs s
394 in
395 let n = nargs kargs in
396 (List.skipn (n+1) kargs, strip_n_app n stk)
397
398 end
399
400 (** The type of (machine) states (= lambda-bar-calculus' cuts) *)
401
402 (*************************************)
403 (*** Reduction Functions Operators ***)
404 (*************************************)
405
406 (*************************************)
407 (*** Reduction using bindingss ***)
408 (*************************************)
409
410 (* Beta Reduction tools *)
411
412 let apply_subst env sigma cst_l t stack =
413 let rec aux env cst_l t stack =
414 match (Stack.decomp stack, EConstr.kind sigma t) with
415 | Some (h,stacktl), Lambda (_,_,c) ->
416 let cst_l' = Cst_stack.add_param h cst_l in
417 aux (h::env) cst_l' c stacktl
418 | _ -> (cst_l, (substl env t, stack))
419 in
420 aux env cst_l t stack
421
422 (* Iota reduction tools *)
423
424 (** @return c if there is a constant c whose body is bd
425 @return bd else.
426
427 It has only a meaning because internal representation of "Fixpoint f x
428 := t" is Definition f := fix f x => t
429
430 Even more fragile that we could hope because do Module M. Fixpoint
431 f x := t. End M. Definition f := u. and say goodbye to any hope
432 of refolding M.f this way ...
433 *)
434 let magically_constant_of_fixbody env sigma (reference, params) bd = function
435 | Name.Anonymous -> bd
436 | Name.Name id ->
437 let open UnivProblem in
438 let cst = Constant.change_label reference id in
439 if not (Environ.mem_constant cst env) then bd
440 else
441 let (cst, u), ctx = UnivGen.fresh_constant_instance env cst in
442 match constant_opt_value_in env (cst,u) with
443 | None -> bd
444 | Some t ->
445 let csts = EConstr.eq_constr_universes env sigma (Reductionops.beta_applist sigma (EConstr.of_constr t, params)) bd in
446 begin match csts with
447 | Some csts ->
448 let addqs l r (qs,us) = Sorts.QVar.Map.add l r qs, us in
449 let addus l r (qs,us) = qs, Univ.Level.Map.add l r us in
450 let subst = Set.fold (fun cst acc ->
451 match cst with
452 | QLeq _ | QElimTo _ -> assert false (* eq_constr_universes cannot produce QLeq nor QElimTo constraints *)
453 | QEq (a, b) ->
454 let a = match a with
455 | QVar q -> q
456 | _ -> assert false
457 in
458 addqs a b acc
459 | ULub (u, v) | UWeak (u, v) -> addus u v acc
460 | UEq (u, v) | ULe (u, v) ->
461 (* XXX add something when qsort? *)
462 let get u = match u with
463 | Sorts.SProp | Sorts.Prop -> assert false
464 | Sorts.Set -> Level.set
465 | Sorts.Type u | Sorts.QSort (_, u) -> Option.get (Universe.level u)
466 in
467 addus (get u) (get v) acc)
468 csts UVars.empty_sort_subst
469 in
470 let inst = UVars.subst_sort_level_instance subst u in
471 applist (mkConstU (cst, EInstance.make inst), params)
472 | None -> bd
473 end
474
475 let contract_cofix env sigma ?reference (bodynum,(names,types,bodies as typedbodies)) =
476 let nbodies = Array.length bodies in
477 let make_Fi j =
478 let ind = nbodies-j-1 in
479 if Int.equal bodynum ind then mkCoFix (ind,typedbodies)
480 else
481 let bd = mkCoFix (ind,typedbodies) in
482 match reference with
483 | None -> bd
484 | Some r -> magically_constant_of_fixbody env sigma r bd names.(ind).binder_name in
485 let closure = List.init nbodies make_Fi in
486 substl closure bodies.(bodynum)
487
488 (** Similar to the "fix" case below *)
489 let reduce_and_refold_cofix recfun env sigma cst_l cofix sk =
490 let raw_answer =
491 contract_cofix env sigma ?reference:(Cst_stack.reference sigma cst_l) cofix in
492 let (x, (t, sk')) = apply_subst [] sigma Cst_stack.empty raw_answer sk in
493 let t' = Cst_stack.best_replace sigma (mkCoFix cofix) cst_l t in
494 recfun x (t', sk')
495
496 (* contracts fix==FIX[nl;i](A1...Ak;[F1...Fk]{B1....Bk}) to produce
497 Bi[Fj --> FIX[nl;j](A1...Ak;[F1...Fk]{B1...Bk})] *)
498
499 let contract_fix env sigma ?reference ((recindices,bodynum),(names,types,bodies as typedbodies)) =
500 let nbodies = Array.length recindices in
501 let make_Fi j =
502 let ind = nbodies-j-1 in
503 if Int.equal bodynum ind then mkFix ((recindices,ind),typedbodies)
504 else
505 let bd = mkFix ((recindices,ind),typedbodies) in
506 match reference with
507 | None -> bd
508 | Some r -> magically_constant_of_fixbody env sigma r bd names.(ind).binder_name in
509 let closure = List.init nbodies make_Fi in
510 substl closure bodies.(bodynum)
511
512 (** First we substitute the Rel bodynum by the fixpoint and then we try to
513 replace the fixpoint by the best constant from [cst_l]
514 Other rels are directly substituted by constants "magically found from the
515 context" in contract_fix *)
516 let reduce_and_refold_fix recfun env sigma cst_l fix sk =
517 let raw_answer =
518 contract_fix env sigma ?reference:(Cst_stack.reference sigma cst_l) fix in
519 let (x, (t, sk')) = apply_subst [] sigma Cst_stack.empty raw_answer sk in
520 let t' = Cst_stack.best_replace sigma (mkFix fix) cst_l t in
521 recfun x (t', sk')
522
523 module CredNative = Reductionops.CredNative
524
525 (** Generic reduction function with environment
526
527 Here is where unfolded constant are stored in order to be
528 eventually refolded.
529
530 It uses ReductionBehaviour, prefers
531 refold constant instead of value and tries to infer constants
532 fix and cofix came from.
533
534 It substitutes fix and cofix by the constant they come from in
535 contract_* in any case .
536 *)
537
538 let debug_RAKAM = Reductionops.debug_RAKAM
539
540 let equal_stacks env sigma (x, l) (y, l') =
541 let f_equal x y = eq_constr sigma x y in
542 let eq_fix a b = f_equal (mkFix a) (mkFix b) in
543 let eq_case (ci1, u1, pms1, (p1,_), _, br1) (ci2, u2, pms2, (p2,_), _, br2) =
544 Array.equal f_equal pms1 pms2 &&
545 f_equal (snd p1) (snd p2) &&
546 Array.equal (fun (_, c1) (_, c2) -> f_equal c1 c2) br1 br2
547 in
548 Stack.equal env f_equal eq_fix eq_case l l' && f_equal x y
549
550 let apply_branch env sigma (ind, i) args (ci, u, pms, iv, r, lf) =
551 let args = Stack.tail ci.ci_npar args in
552 let args = Option.get (Stack.list_of_app_stack args) in
553 let br = lf.(i - 1) in
554 let subst =
555 if Int.equal ci.ci_cstr_nargs.(i - 1) ci.ci_cstr_ndecls.(i - 1) then
556 (* No let-bindings *)
557 List.rev args
558 else
559 let ctx = expand_branch env sigma u pms (ind, i) br in
560 subst_of_rel_context_instance_list ctx args
561 in
562 Vars.substl subst (snd br)
563
564
565 exception PatternFailure
566
567 let match_einstance sigma pu u psubst =
568 match UVars.Instance.pattern_match pu (EInstance.kind sigma u) psubst with
569 | Some psubst -> psubst
570 | None -> raise PatternFailure
571
572 let match_sort ps s psubst =
573 match Sorts.pattern_match ps s psubst with
574 | Some psubst -> psubst
575 | None -> raise PatternFailure
576
577 let rec match_arg_pattern whrec env sigma ctx psubst p t =
578 let open Declarations in
579 let t' = EConstr.it_mkLambda_or_LetIn t ctx in
580 match p with
581 | EHole i -> Partial_subst.add_term i t' psubst
582 | EHoleIgnored -> psubst
583 | ERigid (ph, es) ->
584 let t, stk = whrec ctx (t, Stack.empty) in
585 let psubst = match_rigid_arg_pattern whrec env sigma ctx psubst ph t in
586 let psubst, stk = apply_rule whrec env sigma ctx psubst es stk in
587 match stk with
588 | [] -> psubst
589 | _ :: _ -> raise PatternFailure
590
591 and match_rigid_arg_pattern whrec env sigma ctx psubst p t =
592 match [@ocaml.warning "-4"] p, EConstr.kind sigma t with
593 | PHInd (ind, pu), Ind (ind', u) ->
594 if QInd.equal env ind ind' then match_einstance sigma pu u psubst else raise PatternFailure
595 | PHConstr (constr, pu), Construct (constr', u) ->
596 if QConstruct.equal env constr constr' then match_einstance sigma pu u psubst else raise PatternFailure
597 | PHRel i, Rel n when i = n -> psubst
598 | PHSort ps, Sort s -> match_sort ps (ESorts.kind sigma s) psubst
599 | PHSymbol (c, pu), Const (c', u) ->
600 if QConstant.equal env c c' then match_einstance sigma pu u psubst else raise PatternFailure
601 | PHInt i, Int i' ->
602 if Uint63.equal i i' then psubst else raise PatternFailure
603 | PHFloat f, Float f' ->
604 if Float64.equal f f' then psubst else raise PatternFailure
605 | PHString s, String s' ->
606 if Pstring.equal s s' then psubst else raise PatternFailure
607 | PHLambda (ptys, pbod), _ ->
608 let ntys, _ = EConstr.decompose_lambda sigma t in
609 let na = List.length ntys and np = Array.length ptys in
610 if np > na then raise PatternFailure;
611 let ntys, body = EConstr.decompose_lambda_n sigma np t in
612 let ctx' = List.map (fun (n, ty) -> Context.Rel.Declaration.LocalAssum (n, ty)) ntys in
613 let tys = Array.of_list @@ List.rev_map snd ntys in
614 let na = Array.length tys in
615 let contexts_upto = Array.init na (fun i -> List.skipn (na - i) ctx' @ ctx) in
616 let psubst = Array.fold_left3 (fun psubst ctx -> match_arg_pattern whrec env sigma ctx psubst) psubst contexts_upto ptys tys in
617 let psubst = match_arg_pattern whrec env sigma (ctx' @ ctx) psubst (ERigid pbod) body in
618 psubst
619 | PHProd (ptys, pbod), _ ->
620 let ntys, _ = EConstr.decompose_prod sigma t in
621 let na = List.length ntys and np = Array.length ptys in
622 if np > na then raise PatternFailure;
623 let ntys, body = EConstr.decompose_prod_n sigma np t in
624 let ctx' = List.map (fun (n, ty) -> Context.Rel.Declaration.LocalAssum (n, ty)) ntys in
625 let tys = Array.of_list @@ List.rev_map snd ntys in
626 let na = Array.length tys in
627 let contexts_upto = Array.init na (fun i -> List.skipn (na - i) ctx' @ ctx) in
628 let psubst = Array.fold_left3 (fun psubst ctx -> match_arg_pattern whrec env sigma ctx psubst) psubst contexts_upto ptys tys in
629 let psubst = match_arg_pattern whrec env sigma (ctx' @ ctx) psubst pbod body in
630 psubst
631 | (PHInd _ | PHConstr _ | PHRel _ | PHInt _ | PHFloat _ | PHString _ | PHSort _ | PHSymbol _), _ -> raise PatternFailure
632
633 and extract_n_stack args n s =
634 if n = 0 then List.rev args, s else
635 match Stack.decomp s with
636 | Some (arg, rest) -> extract_n_stack (arg :: args) (n-1) rest
637 | None -> raise PatternFailure
638
639 and apply_rule whrec env sigma ctx psubst es stk =
640 match [@ocaml.warning "-4"] es, stk with
641 | [], _ -> psubst, stk
642 | Declarations.PEApp pargs :: e, s ->
643 let np = Array.length pargs in
644 let pargs = Array.to_list pargs in
645 let args, s = extract_n_stack [] np s in
646 let psubst = List.fold_left2 (match_arg_pattern whrec env sigma ctx) psubst pargs args in
647 apply_rule whrec env sigma ctx psubst e s
648 | Declarations.PECase (pind, pret, pbrs) :: e, Stack.Case ((ci, u, pms, p, iv, brs), cst_l) :: s ->
649 if not @@ QInd.equal env pind ci.ci_ind then raise PatternFailure;
650 let dummy = mkProp in
651 let (_, _, _, ((ntys_ret, ret), _), _, _, brs) = EConstr.annotate_case env sigma (ci, u, pms, p, NoInvert, dummy, brs) in
652 let psubst = match_arg_pattern whrec env sigma (ntys_ret @ ctx) psubst pret ret in
653 let psubst = Array.fold_left2 (fun psubst pat (ctx', br) -> match_arg_pattern whrec env sigma (ctx' @ ctx) psubst pat br) psubst pbrs brs in
654 apply_rule whrec env sigma ctx psubst e s
655 | Declarations.PEProj proj :: e, Stack.Proj (proj', r, cst_l') :: s ->
656 if not @@ QProjection.Repr.equal env proj (Projection.repr proj') then raise PatternFailure;
657 apply_rule whrec env sigma ctx psubst e s
658 | _, _ -> raise PatternFailure
659
660
661 let rec apply_rules whrec env sigma u r stk =
662 let open Declarations in
663 match r with
664 | [] -> raise PatternFailure
665 | { lhs_pat = (pu, elims); nvars; rhs } :: rs ->
666 try
667 let psubst = Partial_subst.make nvars in
668 let psubst = match_einstance sigma pu u psubst in
669 let psubst, stk = apply_rule whrec env sigma [] psubst elims stk in
670 let subst, qsubst, usubst = Partial_subst.to_arrays psubst in
671 let usubst = UVars.Instance.of_array (qsubst, usubst) in
672 let rhsu = subst_instance_constr (EConstr.EInstance.make usubst) (EConstr.of_constr rhs) in
673 let rhs' = substl (Array.to_list subst) rhsu in
674 (rhs', stk)
675 with PatternFailure -> apply_rules whrec env sigma u rs stk
676
677
678
679
680 let rec whd_state_gen ?csts flags env sigma =
681 let open Context.Named.Declaration in
682 let open ReductionBehaviour in
683 let rec whrec cst_l (x, stack) =
684 let () = debug_RAKAM (fun () ->
685 let open Pp in
686 let pr c = Termops.Internal.print_constr_env env sigma c in
687 (h (str "<<" ++ pr x ++
688 str "|" ++ cut () ++ Cst_stack.pr env sigma cst_l ++
689 str "|" ++ cut () ++ Stack.pr pr stack ++
690 str ">>")))
691 in
692 let c0 = EConstr.kind sigma x in
693 let fold () =
694 let () = debug_RAKAM (fun () ->
695 Pp.(str "<><><><><>")) in
696 ((EConstr.of_kind c0, stack),cst_l)
697 in
698 match c0 with
699 | Rel n when RedFlags.red_set flags RedFlags.fDELTA ->
700 (match lookup_rel n env with
701 | LocalDef (_,body,_) -> whrec Cst_stack.empty (lift n body, stack)
702 | _ -> fold ())
703 | Var id when RedFlags.red_set flags (RedFlags.fVAR id) ->
704 (match lookup_named id env with
705 | LocalDef (_,body,_) ->
706 whrec (Cst_stack.add_cst (mkVar id) cst_l) (body, stack)
707 | _ -> fold ())
708 | Evar _ | Meta _ -> fold ()
709 | Const (c,u as const) ->
710 Reductionops.reduction_effect_hook env sigma c
711 (lazy (EConstr.to_constr sigma (Stack.zip sigma (x,fst (Stack.strip_app stack)))));
712 if RedFlags.red_set flags (RedFlags.fCONST c) then
713 let u' = EInstance.kind sigma u in
714 match constant_value_in env sigma (c, u) with
715 | body ->
716 begin
717 (* Looks for ReductionBehaviour *)
718 match ReductionBehaviour.get c with
719 | None -> whrec (Cst_stack.add_cst (mkConstU const) cst_l) (body, stack)
720 | Some behavior ->
721 begin match behavior with
722 | NeverUnfold -> fold ()
723 | (UnfoldWhen { nargs = Some n } |
724 UnfoldWhenNoMatch { nargs = Some n } )
725 when Stack.args_size stack < n ->
726 fold ()
727 | UnfoldWhenNoMatch { recargs; nargs } -> (* maybe unfolds *)
728 let app_sk,sk = Stack.strip_app stack in
729 let volatile = Option.has_some nargs in
730 let (tm',sk'),cst_l' =
731 match recargs with
732 | [] ->
733 whrec (Cst_stack.add_cst ~volatile (mkConstU const) cst_l) (body, app_sk)
734 | curr :: remains -> match Stack.strip_n_app curr app_sk with
735 | None -> (x,app_sk), cst_l
736 | Some (bef,arg,app_sk') ->
737 let cst_l = Stack.Cst
738 { const = Stack.Cst_const (fst const, u');
739 volatile;
740 curr; remains; params=bef; cst_l;
741 }
742 in
743 whrec Cst_stack.empty (arg,cst_l :: app_sk')
744 in
745 let rec is_case x = match EConstr.kind sigma x with
746 | Lambda (_,_, x) | LetIn (_,_,_, x) | Cast (x, _,_) -> is_case x
747 | App (hd, _) -> is_case hd
748 | Case _ -> true
749 | _ -> false in
750 if equal_stacks env sigma (x, app_sk) (tm', sk')
751 || Stack.will_expose_iota sk'
752 || is_case tm'
753 then fold ()
754 else whrec cst_l' (tm', sk' @ sk)
755 | UnfoldWhen { recargs; nargs } -> (* maybe unfolds *)
756 begin match recargs with
757 | [] -> (* if nargs has been specified *)
758 (* CAUTION : the constant is NEVER refolded (even when it hides a (co)fix) *)
759 whrec cst_l (body, stack)
760 | curr :: remains -> match Stack.strip_n_app curr stack with
761 | None -> fold ()
762 | Some (bef,arg,s') ->
763 let cst_l = Stack.Cst
764 { const = Stack.Cst_const (fst const, u');
765 volatile = Option.has_some nargs;
766 curr; remains; params=bef; cst_l;
767 }
768 in
769 whrec Cst_stack.empty (arg,cst_l::s')
770 end
771 end
772 end
773 | exception NotEvaluableConst (IsPrimitive (u,p)) when Stack.check_native_args p stack ->
774 let kargs = CPrimitives.kind p in
775 let (kargs,o) = Stack.get_next_primitive_args kargs stack in
776 (* Should not fail thanks to [check_native_args] *)
777 let (before,a,after) = Option.get o in
778 whrec Cst_stack.empty (a,Stack.Primitive(p,const,before,kargs,cst_l)::after)
779 | exception NotEvaluableConst (HasRules (u', b, r)) ->
780 begin try
781 let red_fun ctx =
782 let env = push_rel_context ctx env in
783 whd_state_gen flags env sigma
784 in
785 let rhs_stack = apply_rules red_fun env sigma u r stack in
786 whrec Cst_stack.empty rhs_stack
787 with PatternFailure ->
788 if not b then fold () else
789 match Stack.strip_app stack with
790 | args, (Stack.Fix (f,s',cst_l)::s'') when RedFlags.red_set flags RedFlags.fFIX ->
791 let x' = Stack.zip sigma (x, args) in
792 let out_sk = s' @ (Stack.append_app [|x'|] s'') in
793 reduce_and_refold_fix whrec env sigma cst_l f out_sk
794 | _ -> fold ()
795 end
796 | exception NotEvaluableConst _ -> fold ()
797 else fold ()
798 | Proj (p, r, c) when RedFlags.red_projection flags p ->
799 (let npars = Projection.npars p in
800 match ReductionBehaviour.get (Projection.constant p) with
801 | None ->
802 let stack' = (c, Stack.Proj (p, r, cst_l) :: stack) in
803 let stack'', csts = whrec Cst_stack.empty stack' in
804 if equal_stacks env sigma stack' stack'' then fold ()
805 else stack'', csts
806 | Some behavior ->
807 begin match behavior with
808 | NeverUnfold -> fold ()
809 | (UnfoldWhen { nargs = Some n }
810 | UnfoldWhenNoMatch { nargs = Some n })
811 when Stack.args_size stack < n - (npars + 1) -> fold ()
812 | UnfoldWhen { recargs }
813 | UnfoldWhenNoMatch { recargs }-> (* maybe unfolds *)
814 let recargs = List.map_filter (fun x ->
815 let idx = x - npars in
816 if idx < 0 then None else Some idx) recargs
817 in
818 let volatile = match behavior with
819 | UnfoldWhen {nargs} -> Option.has_some nargs
820 | UnfoldWhenNoMatch _ | NeverUnfold -> false
821 in
822 match recargs with
823 | [] -> (* if nargs has been specified *)
824 (* CAUTION : the constant is NEVER refold
825 (even when it hides a (co)fix) *)
826 let stack' = (c, Stack.Proj (p, r, cst_l) :: stack) in
827 whrec Cst_stack.empty(* cst_l *) stack'
828 | curr :: remains ->
829 match Stack.strip_n_app curr (Stack.append_app [|c|] stack) with
830 | None -> fold ()
831 | Some (bef,arg,s') ->
832 let cst_l = Stack.Cst
833 { const=Stack.Cst_proj (p,r);
834 curr;
835 remains;
836 volatile;
837 params=bef;
838 cst_l;
839 }
840 in
841 whrec Cst_stack.empty (arg,cst_l::s')
842 end)
843
844 | LetIn (_,b,_,c) when RedFlags.red_set flags RedFlags.fZETA ->
845 let (cst_l, p) = apply_subst [b] sigma cst_l c stack in
846 whrec cst_l p
847 | Cast (c,_,_) -> whrec cst_l (c, stack)
848 | App (f,cl) ->
849 whrec
850 (Cst_stack.add_args cl cst_l)
851 (f, Stack.append_app cl stack)
852 | Lambda (na,t,c) ->
853 (match Stack.decomp stack with
854 | Some _ when RedFlags.red_set flags RedFlags.fBETA ->
855 let (cst_l, p) = apply_subst [] sigma cst_l x stack in
856 whrec cst_l p
857 | _ -> fold ())
858
859 | Case (ci,u,pms,p,iv,d,lf) ->
860 whrec Cst_stack.empty (d, Stack.Case ((ci,u,pms,p,iv,lf),cst_l) :: stack)
861
862 | Fix ((ri,n),_ as f) ->
863 (match Stack.strip_n_app ri.(n) stack with
864 |None -> fold ()
865 |Some (bef,arg,s') ->
866 whrec Cst_stack.empty (arg, Stack.Fix(f,bef,cst_l)::s'))
867
868 | Construct (cstr ,u) ->
869 let use_match = RedFlags.red_set flags RedFlags.fMATCH in
870 let use_fix = RedFlags.red_set flags RedFlags.fFIX in
871 if use_match || use_fix then
872 match Stack.strip_app stack with
873 |args, (Stack.Case(case,_)::s') when use_match ->
874 let r = apply_branch env sigma cstr args case in
875 whrec Cst_stack.empty (r, s')
876 |args, (Stack.Proj (p,_,_)::s') when use_match ->
877 whrec Cst_stack.empty (Stack.nth args (Projection.npars p + Projection.arg p), s')
878 |args, (Stack.Fix (f,s',cst_l)::s'') when use_fix ->
879 let x' = Stack.zip sigma (x, args) in
880 let out_sk = s' @ (Stack.append_app [|x'|] s'') in
881 reduce_and_refold_fix whrec env sigma cst_l f out_sk
882 |args, (Stack.Cst {const;curr;remains;volatile;params=s';cst_l} :: s'') ->
883 let x' = Stack.zip sigma (x, args) in
884 begin match remains with
885 | [] ->
886 (match const with
887 | Stack.Cst_const const ->
888 (match constant_opt_value_in env const with
889 | None -> fold ()
890 | Some body ->
891 let const = (fst const, EInstance.make (snd const)) in
892 let body = EConstr.of_constr body in
893 let cst_l = Cst_stack.add_cst ~volatile (mkConstU const) cst_l in
894 whrec cst_l (body, s' @ (Stack.append_app [|x'|] s'')))
895 | Stack.Cst_proj (p,r) ->
896 let stack = s' @ (Stack.append_app [|x'|] s'') in
897 match Stack.strip_n_app 0 stack with
898 | None -> assert false
899 | Some (_,arg,s'') ->
900 whrec Cst_stack.empty (arg, Stack.Proj (p,r,cst_l) :: s''))
901 | next :: remains' -> match Stack.strip_n_app (next-curr-1) s'' with
902 | None -> fold ()
903 | Some (bef,arg,s''') ->
904 let cst_l = Stack.Cst
905 { const;
906 curr=next;
907 volatile;
908 remains=remains';
909 params=s' @ (Stack.append_app [|x'|] bef);
910 cst_l;
911 }
912 in
913 whrec Cst_stack.empty (arg, cst_l :: s''')
914 end
915 |_, (Stack.App _)::_ -> assert false
916 |_, _ -> fold ()
917 else fold ()
918
919 | CoFix cofix ->
920 if RedFlags.red_set flags RedFlags.fCOFIX then
921 match Stack.strip_app stack with
922 |args, ((Stack.Case _ |Stack.Proj _)::s') ->
923 reduce_and_refold_cofix whrec env sigma cst_l cofix stack
924 |_ -> fold ()
925 else fold ()
926
927 | Int _ | Float _ | String _ | Array _ ->
928 begin match Stack.strip_app stack with
929 | (_, Stack.Primitive(p,(_,u as kn),rargs,kargs,cst_l')::s) ->
930 let more_to_reduce = List.exists (fun k -> CPrimitives.Kwhnf = k) kargs in
931 if more_to_reduce then
932 let (kargs,o) = Stack.get_next_primitive_args kargs s in
933 (* Should not fail because Primitive is put on the stack only if fully applied *)
934 let (before,a,after) = Option.get o in
935 whrec Cst_stack.empty (a,Stack.Primitive(p,kn,rargs @ Stack.append_app [|x|] before,kargs,cst_l')::after)
936 else
937 let n = List.length kargs in
938 let (args,s) = Stack.strip_app s in
939 let (args,extra_args) =
940 try List.chop n args
941 with List.IndexOutOfRange -> (args,[]) (* FIXME probably useless *)
942 in
943 let s = extra_args @ s in
944 let args = Array.of_list (Option.get (Stack.list_of_app_stack (rargs @ Stack.append_app [|x|] args))) in
945 begin match CredNative.red_prim env sigma p u args with
946 | Some t -> whrec cst_l' (t,s)
947 | None -> ((mkApp (mkConstU kn, args), s), cst_l)
948 end
949 |args, (Stack.Cst {const;curr;remains;volatile;params=s';cst_l} :: s'') ->
950 let x' = Stack.zip sigma (x, args) in
951 begin match remains with
952 | [] ->
953 (match const with
954 | Stack.Cst_const const ->
955 (match constant_opt_value_in env const with
956 | None -> fold ()
957 | Some body ->
958 let const = (fst const, EInstance.make (snd const)) in
959 let body = EConstr.of_constr body in
960 let cst_l = Cst_stack.add_cst ~volatile (mkConstU const) cst_l in
961 whrec cst_l (body, s' @ (Stack.append_app [|x'|] s'')))
962 | Stack.Cst_proj (p,r) ->
963 let stack = s' @ (Stack.append_app [|x'|] s'') in
964 match Stack.strip_n_app 0 stack with
965 | None -> assert false
966 | Some (_,arg,s'') ->
967 whrec Cst_stack.empty (arg, Stack.Proj (p,r,cst_l) :: s''))
968 | next :: remains' -> match Stack.strip_n_app (next-curr-1) s'' with
969 | None -> fold ()
970 | Some (bef,arg,s''') ->
971 let cst_l = Stack.Cst
972 { const;
973 curr=next;
974 volatile;
975 remains=remains';
976 params=s' @ (Stack.append_app [|x'|] bef);
977 cst_l;
978 }
979 in
980 whrec Cst_stack.empty (arg, cst_l :: s''')
981 end
982 | _ -> fold ()
983 end
984
985 | Rel _ | Var _ | LetIn _ | Proj _ -> fold ()
986 | Sort _ | Ind _ | Prod _ -> fold ()
987 in
988 fun xs ->
989 let (s,cst_l as res) = whrec (Option.default Cst_stack.empty csts) xs in
990 (Stack.best_state sigma s cst_l)
991
992 let whd_cbn flags env sigma t =
993 let state = whd_state_gen flags env sigma (t, Stack.empty) in
994 Stack.zip ~refold:true sigma state
995
996 let norm_cbn flags env sigma t =
997 let push_rel_check_zeta d env =
998 let open RedFlags in
999 let d = match d with
1000 | LocalDef (na,c,t) when not (red_set flags fZETA) -> LocalAssum (na,t)
1001 | d -> d in
1002 push_rel d env in
1003 let rec strongrec env t =
1004 map_constr_with_full_binders env sigma
1005 push_rel_check_zeta strongrec env (whd_cbn flags env sigma t) in
1006 strongrec env t