Debian Codegraph @

pretyping/cbv.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 Util
12 open Names
13 open Constr
14 open Vars
15 open Esubst
16
17 (**** Call by value reduction ****)
18
19 (* The type of terms with closure. The meaning of the constructors and
20 * the invariants of this datatype are the following:
21 * VAL(k,c) represents the constr c with a delayed shift of k. c must be
22 * in normal form and neutral (i.e. not a lambda, a construct or a
23 * (co)fix, because they may produce redexes by applying them,
24 * or putting them in a case)
25 * STACK(k,v,stk) represents an irreductible value [v] in the stack [stk].
26 * [k] is a delayed shift to be applied to both the value and
27 * the stack.
28 * LAMBDA(n,a,b,S) is the term [S]([x:a]b) where [a] is a list of bindings and
29 * [n] is the length of [a]. the environment [S] is propagated
30 * only when the abstraction is applied, and then we use the rule
31 * ([S]([x:a]b) c) --> [S.c]b
32 * This corresponds to the usual strategy of weak reduction
33 * PROD(na,t,u,S) is the term [S](forall na:t, u).
34 * LETIN(na,b,t,S) is the term [S](let na:= b : t in.c).
35 * FIX(op,bd,S,args) is the fixpoint (Fix or Cofix) of bodies bd under
36 * the bindings S, and then applied to args. Here again,
37 * weak reduction.
38 * CONSTRUCT(c,args) is the constructor [c] applied to [args].
39 * PRIMITIVE(cop,args) represent a particial application of
40 * a primitive, or a fully applied primitive
41 * which does not reduce.
42 * cop is the constr representing op.
43 *
44 *)
45 type cbv_value =
46 | VAL of int * constr
47 | STACK of int * cbv_value * cbv_stack
48 | LAMBDA of int * (Name.t Constr.binder_annot * types) list * constr * cbv_value subs
49 | PROD of Name.t Constr.binder_annot * types * types * cbv_value subs
50 | LETIN of Name.t Constr.binder_annot * cbv_value * types * constr * cbv_value subs
51 | FIX of fixpoint * cbv_value subs * cbv_value array
52 | COFIX of cofixpoint * cbv_value subs * cbv_value array
53 | CONSTRUCT of constructor UVars.puniverses * cbv_value array
54 | PRIMITIVE of CPrimitives.t * pconstant * cbv_value array
55 | ARRAY of UVars.Instance.t * cbv_value Parray.t * cbv_value
56 | SYMBOL of { cst: Constant.t UVars.puniverses; unfoldfix: bool; rules: Declarations.machine_rewrite_rule list; stk: cbv_stack }
57
58 (* type of terms with a hole. This hole can appear only under App or Case.
59 * TOP means the term is considered without context
60 * APP(v,stk) means the term is applied to v, and then the context stk
61 * (v.0 is the first argument).
62 * this corresponds to the application stack of the KAM.
63 * The members of l are values: we evaluate arguments before
64 calling the function.
65 * CASE(t,br,pat,S,stk) means the term is in a case (which is himself in stk
66 * t is the type of the case and br are the branches, all of them under
67 * the subs S, pat is information on the patterns of the Case
68 * (Weak reduction: we propagate the sub only when the selected branch
69 * is determined)
70 * PROJ(p,pb,stk) means the term is in a primitive projection p, itself in stk.
71 * pb is the associated projection body
72 *
73 * Important remark: the APPs should be collapsed:
74 * (APP (l,(APP ...))) forbidden
75 *)
76 and cbv_stack =
77 | TOP
78 | APP of cbv_value list * cbv_stack
79 | CASE of UVars.Instance.t * constr array * case_return * case_branch array * Constr.case_invert * case_info * cbv_value subs * cbv_stack
80 | PROJ of Projection.t * Sorts.relevance * cbv_stack
81
82 (* les vars pourraient etre des constr,
83 cela permet de retarder les lift: utile ?? *)
84
85 (* relocation of a value; used when a value stored in a context is expanded
86 * in a larger context. e.g. [%k (S.t)](k+1) --> [^k]t (t is shifted of k)
87 *)
88 let rec shift_value n = function
89 | VAL (k,t) -> VAL (k+n,t)
90 | STACK(k,v,stk) -> STACK(k+n,v,stk)
91 | PROD (na,t,u,s) -> PROD(na,t,u,subs_shft(n,s))
92 | LETIN (na,b,t,c,s) -> LETIN(na,shift_value n b,t,c,subs_shft(n,s))
93 | LAMBDA (nlams,ctxt,b,s) -> LAMBDA (nlams,ctxt,b,subs_shft (n,s))
94 | FIX (fix,s,args) ->
95 FIX (fix,subs_shft (n,s), Array.map (shift_value n) args)
96 | COFIX (cofix,s,args) ->
97 COFIX (cofix,subs_shft (n,s), Array.map (shift_value n) args)
98 | CONSTRUCT (c,args) ->
99 CONSTRUCT (c, Array.map (shift_value n) args)
100 | PRIMITIVE(op,c,args) ->
101 PRIMITIVE(op,c,Array.map (shift_value n) args)
102 | ARRAY (u,t,ty) ->
103 ARRAY(u, Parray.map (shift_value n) t, shift_value n ty)
104 | SYMBOL s -> SYMBOL { s with stk = shift_stack n s.stk }
105
106 and shift_stack n = function (* Slow *)
107 | TOP -> TOP
108 | APP (args, stk) -> APP (List.map (shift_value n) args, shift_stack n stk)
109 | CASE (u,pms,c,b,iv,i,s,stk) -> CASE (u,pms,c,b,iv,i,subs_shft(n,s), shift_stack n stk)
110 | PROJ (p, r, stk) -> PROJ (p, r, shift_stack n stk)
111
112 let shift_value n v =
113 if Int.equal n 0 then v else shift_value n v
114
115 (* Contracts a fixpoint: given a fixpoint and a bindings,
116 * returns the corresponding fixpoint body, and the bindings in which
117 * it should be evaluated: its first variables are the fixpoint bodies
118 * (S, (fix Fi {F0 := T0 .. Fn-1 := Tn-1}))
119 * -> (S. [S]F0 . [S]F1 ... . [S]Fn-1, Ti)
120 *)
121
122 let rec mk_fix_subs make_body n env i =
123 if Int.equal i n then env
124 else mk_fix_subs make_body n (subs_cons (make_body i) env) (i + 1)
125
126 let contract_fixp env ((reci,i),(_,_,bds as bodies)) =
127 let make_body j = FIX(((reci,j),bodies), env, [||]) in
128 let n = Array.length bds in
129 mk_fix_subs make_body n env 0, bds.(i)
130
131 let contract_cofixp env (i,(_,_,bds as bodies)) =
132 let make_body j = COFIX((j,bodies), env, [||]) in
133 let n = Array.length bds in
134 mk_fix_subs make_body n env 0, bds.(i)
135
136 let make_constr_ref n k t =
137 match k with
138 | RelKey p -> mkRel (n+p)
139 | VarKey id -> t
140 | ConstKey cst -> t
141
142 (* Adds an application list. Collapse APPs! *)
143 let stack_vect_app appl stack =
144 if Int.equal (Array.length appl) 0 then stack else
145 match stack with
146 | APP(args,stk) -> APP(Array.fold_right (fun v accu -> v :: accu) appl args,stk)
147 | _ -> APP(Array.to_list appl, stack)
148
149 let stack_app appl stack =
150 if List.is_empty appl then stack else
151 match stack with
152 | APP(args,stk) -> APP(appl @ args,stk)
153 | _ -> APP(appl, stack)
154
155 let rec stack_concat stk1 stk2 =
156 match stk1 with
157 TOP -> stk2
158 | APP(v,stk1') -> APP(v,stack_concat stk1' stk2)
159 | CASE(u,pms,c,b,iv,i,s,stk1') -> CASE(u,pms,c,b,iv,i,s,stack_concat stk1' stk2)
160 | PROJ (p,r,stk1') -> PROJ (p,r,stack_concat stk1' stk2)
161
162 (* merge stacks when there is no shifts in between *)
163 let mkSTACK = function
164 v, TOP -> v
165 | STACK(0,v0,stk0), stk -> STACK(0,v0,stack_concat stk0 stk)
166 | v,stk -> STACK(0,v,stk)
167
168 module KeyTable = Hashtbl.Make(struct
169 type t = Constant.t UVars.puniverses tableKey
170 let equal = Names.eq_table_key (eq_pair eq_constant_key UVars.Instance.equal)
171 let hash = Names.hash_table_key (fun (c, _) -> Constant.UserOrd.hash c)
172 end)
173
174 type cbv_infos = {
175 env : Environ.env;
176 tab : (cbv_value, Empty.t, bool * Declarations.machine_rewrite_rule list) Declarations.constant_def KeyTable.t;
177 reds : RedFlags.reds;
178 sigma : Evd.evar_map;
179 strong : bool;
180 }
181
182 (* Change: zeta reduction cannot be avoided in CBV *)
183
184 open RedFlags
185
186 let red_set_ref flags = function
187 | RelKey _ -> red_set flags fDELTA
188 | VarKey id -> red_set flags (fVAR id)
189 | ConstKey (sp,_) -> red_set flags (fCONST sp)
190
191 (* Transfer application lists from a value to the stack
192 * useful because fixpoints may be totally applied in several times.
193 * On the other hand, irreductible atoms absorb the full stack.
194 *)
195 let strip_appl head stack =
196 match head with
197 | FIX (fix,env,app) -> (FIX(fix,env,[||]), stack_vect_app app stack)
198 | COFIX (cofix,env,app) -> (COFIX(cofix,env,[||]), stack_vect_app app stack)
199 | CONSTRUCT (c,app) -> (CONSTRUCT(c,[||]), stack_vect_app app stack)
200 | PRIMITIVE(op,c,app) -> (PRIMITIVE(op,c,[||]), stack_vect_app app stack)
201 | LETIN _ | VAL _ | STACK _ | PROD _ | LAMBDA _ | ARRAY _ | SYMBOL _ -> (head, stack)
202
203 let destack head stack =
204 match head with
205 | FIX (fix,env,app) -> (FIX(fix,env,[||]), stack_vect_app app stack)
206 | COFIX (cofix,env,app) -> (COFIX(cofix,env,[||]), stack_vect_app app stack)
207 | CONSTRUCT (c,app) -> (CONSTRUCT(c,[||]), stack_vect_app app stack)
208 | PRIMITIVE(op,c,app) -> (PRIMITIVE(op,c,[||]), stack_vect_app app stack)
209 | STACK (k, v, stk) -> (shift_value k v, stack_concat (shift_stack k stk) stack)
210 | SYMBOL ({ stk } as s) -> (SYMBOL { s with stk=TOP }, stack_concat stk stack)
211 | LETIN _ | VAL _ | PROD _ | LAMBDA _ | ARRAY _ -> (head, stack)
212
213 let rec fixp_reducible_symb_stk = function
214 | TOP -> true
215 | APP (_, stk) -> fixp_reducible_symb_stk stk
216 | CASE _ | PROJ _ -> false
217
218 (* Tests if fixpoint reduction is possible. *)
219 let fixp_reducible flgs ((reci,i),_) stk =
220 if red_set flgs fFIX then
221 match stk with
222 | APP(appl,_) ->
223 let rec check n = function
224 | [] -> false
225 | v :: appl ->
226 if Int.equal n 0 then match v with
227 | CONSTRUCT _ -> true
228 | SYMBOL { unfoldfix=true; stk; _ } ->
229 fixp_reducible_symb_stk stk
230 | _ -> false
231 else check (n - 1) appl
232 in
233 check reci.(i) appl
234 | _ -> false
235 else
236 false
237
238 let cofixp_reducible flgs _ stk =
239 if red_set flgs fCOFIX then
240 match stk with
241 | (CASE _ | PROJ _ | APP(_,CASE _) | APP(_,PROJ _)) -> true
242 | _ -> false
243 else
244 false
245
246 let debug_cbv = CDebug.create ~name:"Cbv" ()
247
248 (* Reduction of primitives *)
249
250 open Primred
251
252 module VNativeEntries =
253 struct
254
255 type elem = cbv_value
256 type args = cbv_value array
257 type evd = unit
258 type uinstance = UVars.Instance.t
259
260 let get = Array.get
261
262 let get_int () e =
263 match e with
264 | VAL(_, ci) ->
265 (match kind ci with
266 | Int i -> i
267 | _ -> raise Primred.NativeDestKO)
268 | _ -> raise Primred.NativeDestKO
269
270 let get_float () e =
271 match e with
272 | VAL(_, cf) ->
273 (match kind cf with
274 | Float f -> f
275 | _ -> raise Primred.NativeDestKO)
276 | _ -> raise Primred.NativeDestKO
277
278 let get_string () e =
279 match e with
280 | VAL(_, cf) ->
281 (match kind cf with
282 | String s -> s
283 | _ -> raise Primred.NativeDestKO)
284 | _ -> raise Primred.NativeDestKO
285
286 let get_parray () e =
287 match e with
288 | ARRAY(_u,t,_ty) -> t
289 | _ -> raise Primred.NativeDestKO
290
291 let mkInt env i = VAL(0, mkInt i)
292
293 let mkFloat env f = VAL(0, mkFloat f)
294
295 let mkString env s = VAL(0, mkString s)
296
297 let mkBool env b =
298 let (ct,cf) = get_bool_constructors env in
299 CONSTRUCT(UVars.in_punivs (if b then ct else cf), [||])
300
301 let int_ty env = VAL(0, UnsafeMonomorphic.mkConst @@ get_int_type env)
302
303 let float_ty env = VAL(0, UnsafeMonomorphic.mkConst @@ get_float_type env)
304
305 let mkCarry env b e =
306 let (c0,c1) = get_carry_constructors env in
307 CONSTRUCT(UVars.in_punivs (if b then c1 else c0), [|int_ty env;e|])
308
309 let mkIntPair env e1 e2 =
310 let int_ty = int_ty env in
311 let c = get_pair_constructor env in
312 CONSTRUCT(UVars.in_punivs c, [|int_ty;int_ty;e1;e2|])
313
314 let mkFloatIntPair env f i =
315 let float_ty = float_ty env in
316 let int_ty = int_ty env in
317 let c = get_pair_constructor env in
318 CONSTRUCT(UVars.in_punivs c, [|float_ty;int_ty;f;i|])
319
320 let mkLt env =
321 let (_eq,lt,_gt) = get_cmp_constructors env in
322 CONSTRUCT(UVars.in_punivs lt, [||])
323
324 let mkEq env =
325 let (eq,_lt,_gt) = get_cmp_constructors env in
326 CONSTRUCT(UVars.in_punivs eq, [||])
327
328 let mkGt env =
329 let (_eq,_lt,gt) = get_cmp_constructors env in
330 CONSTRUCT(UVars.in_punivs gt, [||])
331
332 let mkFLt env =
333 let (_eq,lt,_gt,_nc) = get_f_cmp_constructors env in
334 CONSTRUCT(UVars.in_punivs lt, [||])
335
336 let mkFEq env =
337 let (eq,_lt,_gt,_nc) = get_f_cmp_constructors env in
338 CONSTRUCT(UVars.in_punivs eq, [||])
339
340 let mkFGt env =
341 let (_eq,_lt,gt,_nc) = get_f_cmp_constructors env in
342 CONSTRUCT(UVars.in_punivs gt, [||])
343
344 let mkFNotComparable env =
345 let (_eq,_lt,_gt,nc) = get_f_cmp_constructors env in
346 CONSTRUCT(UVars.in_punivs nc, [||])
347
348 let mkPNormal env =
349 let (pNormal,_nNormal,_pSubn,_nSubn,_pZero,_nZero,_pInf,_nInf,_nan) =
350 get_f_class_constructors env in
351 CONSTRUCT(UVars.in_punivs pNormal, [||])
352
353 let mkNNormal env =
354 let (_pNormal,nNormal,_pSubn,_nSubn,_pZero,_nZero,_pInf,_nInf,_nan) =
355 get_f_class_constructors env in
356 CONSTRUCT(UVars.in_punivs nNormal, [||])
357
358 let mkPSubn env =
359 let (_pNormal,_nNormal,pSubn,_nSubn,_pZero,_nZero,_pInf,_nInf,_nan) =
360 get_f_class_constructors env in
361 CONSTRUCT(UVars.in_punivs pSubn, [||])
362
363 let mkNSubn env =
364 let (_pNormal,_nNormal,_pSubn,nSubn,_pZero,_nZero,_pInf,_nInf,_nan) =
365 get_f_class_constructors env in
366 CONSTRUCT(UVars.in_punivs nSubn, [||])
367
368 let mkPZero env =
369 let (_pNormal,_nNormal,_pSubn,_nSubn,pZero,_nZero,_pInf,_nInf,_nan) =
370 get_f_class_constructors env in
371 CONSTRUCT(UVars.in_punivs pZero, [||])
372
373 let mkNZero env =
374 let (_pNormal,_nNormal,_pSubn,_nSubn,_pZero,nZero,_pInf,_nInf,_nan) =
375 get_f_class_constructors env in
376 CONSTRUCT(UVars.in_punivs nZero, [||])
377
378 let mkPInf env =
379 let (_pNormal,_nNormal,_pSubn,_nSubn,_pZero,_nZero,pInf,_nInf,_nan) =
380 get_f_class_constructors env in
381 CONSTRUCT(UVars.in_punivs pInf, [||])
382
383 let mkNInf env =
384 let (_pNormal,_nNormal,_pSubn,_nSubn,_pZero,_nZero,_pInf,nInf,_nan) =
385 get_f_class_constructors env in
386 CONSTRUCT(UVars.in_punivs nInf, [||])
387
388 let mkNaN env =
389 let (_pNormal,_nNormal,_pSubn,_nSubn,_pZero,_nZero,_pInf,_nInf,nan) =
390 get_f_class_constructors env in
391 CONSTRUCT(UVars.in_punivs nan, [||])
392
393 let mkArray env u t ty =
394 ARRAY (u,t,ty)
395 end
396
397 module VredNative = RedNative(VNativeEntries)
398
399 let debug_pr_key = function
400 | ConstKey (sp,_) -> Names.Constant.print sp
401 | VarKey id -> Names.Id.print id
402 | RelKey n -> Pp.(str "REL_" ++ int n)
403
404 let rec reify_stack t = function
405 | TOP -> t
406 | APP (args,st) ->
407 reify_stack (mkApp(t,Array.map_of_list reify_value args)) st
408 | CASE (u,pms,ty,br,iv,ci,env,st) ->
409 reify_stack
410 (apply_env env @@ mkCase (ci, u, pms, ty, iv, t,br))
411 st
412 | PROJ (p, r, st) ->
413 reify_stack (mkProj (p, r, t)) st
414
415 and reify_value = function (* reduction under binders *)
416 | VAL (n,t) -> lift n t
417 | STACK (0,v,stk) ->
418 reify_stack (reify_value v) stk
419 | STACK (n,v,stk) ->
420 lift n (reify_stack (reify_value v) stk)
421 | PROD(na,t,u,env) ->
422 apply_env env (mkProd (na,t,u))
423 | LETIN(na,b,t,c,env) ->
424 apply_env env (mkLetIn (na,reify_value b,t,c))
425 | LAMBDA (k,ctxt,b,env) ->
426 apply_env env @@
427 List.fold_left (fun c (n,t) ->
428 mkLambda (n, t, c)) b ctxt
429 | FIX ((lij,fix),env,args) ->
430 let fix = mkFix (lij, fix) in
431 mkApp (apply_env env fix, Array.map reify_value args)
432 | COFIX ((j,cofix),env,args) ->
433 let cofix = mkCoFix (j, cofix) in
434 mkApp (apply_env env cofix, Array.map reify_value args)
435 | CONSTRUCT (c,args) ->
436 mkApp(mkConstructU c, Array.map reify_value args)
437 | PRIMITIVE(op,c,args) ->
438 mkApp(mkConstU c, Array.map reify_value args)
439 | ARRAY (u,t,ty) ->
440 let t, def = Parray.to_array t in
441 mkArray(u, Array.map reify_value t, reify_value def, reify_value ty)
442 | SYMBOL { cst; stk; _ } ->
443 reify_stack (mkConstU cst) stk
444
445 and apply_env env t =
446 match kind t with
447 | Rel i ->
448 begin match expand_rel i env with
449 | Inl (k, v) ->
450 reify_value (shift_value k v)
451 | Inr (k,_) ->
452 mkRel k
453 end
454 | _ ->
455 map_with_binders subs_lift apply_env env t
456
457 let apply_env_context e ctx =
458 let open Context.Rel.Declaration in
459 let rec subst_context ctx = match ctx with
460 | [] -> e, []
461 | LocalAssum (na, ty) :: ctx ->
462 let e, ctx = subst_context ctx in
463 let ty = apply_env e ty in
464 subs_lift e, LocalAssum (na, ty) :: ctx
465 | LocalDef (na, ty, bdy) :: ctx ->
466 let e, ctx = subst_context ctx in
467 let ty = apply_env e ty in
468 let bdy = apply_env e bdy in
469 subs_lift e, LocalDef (na, ty, bdy) :: ctx
470 in
471 snd @@ subst_context ctx
472
473 let rec strip_app = function
474 | APP (args,st) -> APP (args,strip_app st)
475 | s -> TOP
476
477 (* TODO: share the common parts with EConstr *)
478 let expand_branch env u pms (ind, i) br =
479 let open Declarations in
480 let nas, _br = br.(i - 1) in
481 let (mib, mip) = Inductive.lookup_mind_specif env ind in
482 let paramdecl = Vars.subst_instance_context u mib.mind_params_ctxt in
483 let paramsubst = Vars.subst_of_rel_context_instance paramdecl pms in
484 let (ctx, _) = mip.mind_nf_lc.(i - 1) in
485 let (ctx, _) = List.chop mip.mind_consnrealdecls.(i - 1) ctx in
486 Inductive.instantiate_context u paramsubst nas ctx
487
488 let cbv_subst_of_rel_context_instance_list mkclos sign args env =
489 let rec aux subst sign l =
490 let open Context.Rel.Declaration in
491 match sign, l with
492 | LocalAssum _ :: sign', a::args' -> aux (subs_cons a subst) sign' args'
493 | LocalDef (_,c,_)::sign', args' ->
494 aux (subs_cons (mkclos subst c) subst) sign' args'
495 | [], [] -> subst
496 | _ -> CErrors.anomaly (Pp.str "Instance and signature do not match.")
497 in aux env (List.rev sign) args
498
499 (* The main recursive functions
500 *
501 * Go under applications and cases/projections (pushed in the stack),
502 * expand head constants or substitued de Bruijn, and try to a make a
503 * constructor, a lambda or a fixp appear in the head. If not, it is a value
504 * and is completely computed here. The head redexes are NOT reduced:
505 * the function returns the pair of a cbv_value and its stack. *
506 * Invariant: if the result of norm_head is CONSTRUCT or (CO)FIX, its last
507 * argument is []. Because we must put all the applied terms in the
508 * stack. *)
509
510 exception PatternFailure
511
512 let rec norm_head info env t stack =
513 (* no reduction under binders *)
514 match kind t with
515 (* stack grows (remove casts) *)
516 | App (head,args) -> (* Applied terms are normalized immediately;
517 they could be computed when getting out of the stack *)
518 let fold c accu = cbv_stack_term info TOP env c :: accu in
519 let rem, stack = match stack with
520 | APP (nargs, stack) -> nargs, stack
521 | _ -> [], stack
522 in
523 let stack = APP (Array.fold_right fold args rem, stack) in
524 norm_head info env head stack
525 | Case (ci,u,pms,p,iv,c,v) -> norm_head info env c (CASE(u,pms,p,v,iv,ci,env,stack))
526 | Cast (ct,_,_) -> norm_head info env ct stack
527
528 | Proj (p, r, c) ->
529 let p' =
530 if red_set info.reds (fPROJ (Projection.repr p))
531 then Projection.unfold p
532 else p
533 in
534 norm_head info env c (PROJ (p', r, stack))
535
536 (* constants, axioms
537 * the first pattern is CRUCIAL, n=0 happens very often:
538 * when reducing closed terms, n is always 0 *)
539 | Rel i ->
540 (match expand_rel i env with
541 | Inl (0,v) -> strip_appl v stack
542 | Inl (n,v) -> strip_appl (shift_value n v) stack
543 | Inr (n,None) -> (VAL(0, mkRel n), stack)
544 | Inr (n,Some p) -> norm_head_ref (n-p) info env stack (RelKey p) t)
545
546 | Var id -> norm_head_ref 0 info env stack (VarKey id) t
547
548 | Const sp ->
549 Reductionops.reduction_effect_hook info.env info.sigma
550 (fst sp) (lazy (reify_stack t (strip_app stack)));
551 norm_head_ref 0 info env stack (ConstKey sp) t
552
553 | LetIn (na, b, u, c) ->
554 (* zeta means letin are contracted; delta without zeta means we *)
555 (* allow bindings but leave let's in place *)
556 if red_set info.reds fZETA then
557 (* New rule: for Cbv, Delta does not apply to locally bound variables
558 or red_set info.reds fDELTA
559 *)
560 let env' = subs_cons (cbv_stack_term info TOP env b) env in
561 norm_head info env' c stack
562 else
563 (* Note: we may also consider a commutative cut! *)
564 LETIN(na,cbv_stack_term info TOP env b,u,c,env), stack
565
566 | Evar ((e, _) as ev) ->
567 (match Evd.existential_opt_value0 info.sigma ev with
568 Some c -> norm_head info env c stack
569 | None ->
570 let ev = EConstr.of_existential ev in
571 let map c = EConstr.of_constr @@ apply_env env (EConstr.Unsafe.to_constr c) in
572 let ev' = EConstr.map_existential info.sigma map ev in
573 (VAL(0, EConstr.Unsafe.to_constr @@ EConstr.mkEvar ev'), stack))
574
575 (* non-neutral cases *)
576 | Lambda _ ->
577 let ctxt,b = Term.decompose_lambda t in
578 (LAMBDA(List.length ctxt, List.rev ctxt,b,env), stack)
579 | Fix fix -> (FIX(fix,env,[||]), stack)
580 | CoFix cofix -> (COFIX(cofix,env,[||]), stack)
581 | Construct c -> (CONSTRUCT(c, [||]), stack)
582
583 | Array(u,t,def,ty) ->
584 let ty = cbv_stack_term info TOP env ty in
585 let len = Array.length t in
586 let t =
587 Parray.init (Uint63.of_int len)
588 (fun i -> cbv_stack_term info TOP env t.(i))
589 (cbv_stack_term info TOP env def) in
590 (ARRAY (u,t,ty), stack)
591
592 (* neutral cases *)
593 | (Sort _ | Meta _ | Ind _ | Int _ | Float _ | String _) -> (VAL(0, t), stack)
594 | Prod (na,t,u) -> (PROD(na,t,u,env), stack)
595
596 and norm_head_ref k info env stack normt t =
597 if red_set_ref info.reds normt then
598 match cbv_value_cache info normt with
599 | Declarations.Def body ->
600 debug_cbv (fun () -> Pp.(str "Unfolding " ++ debug_pr_key normt));
601 strip_appl (shift_value k body) stack
602 | Declarations.Primitive op ->
603 let c = match normt with
604 | ConstKey c -> c
605 | RelKey _ | VarKey _ -> assert false
606 in
607 (PRIMITIVE(op,c,[||]),stack)
608 | Declarations.Symbol (unfoldfix, rules) ->
609 assert (k = 0);
610 let cst = match normt with
611 | ConstKey c -> c
612 | RelKey _ | VarKey _ -> assert false
613 in
614 (SYMBOL { cst; unfoldfix; rules; stk=TOP }, stack)
615 | Declarations.OpaqueDef _ | Declarations.Undef _ ->
616 debug_cbv (fun () -> Pp.(str "Not unfolding " ++ debug_pr_key normt));
617 (VAL(0,make_constr_ref k normt t),stack)
618 else
619 begin
620 debug_cbv (fun () -> Pp.(str "Not unfolding " ++ debug_pr_key normt));
621 (VAL(0,make_constr_ref k normt t),stack)
622 end
623
624 (* cbv_stack_term performs weak reduction on constr t under the subs
625 * env, with context stack, i.e. ([env]t stack). First computes weak
626 * head normal form of t and checks if a redex appears with the stack.
627 * If so, recursive call to reach the real head normal form. If not,
628 * we build a value.
629 *)
630 and cbv_stack_term info stack env t =
631 cbv_stack_value info env (norm_head info env t stack)
632
633 and cbv_stack_value info env = function
634 (* a lambda meets an application -> BETA *)
635 | (LAMBDA (nlams,ctxt,b,env), APP (args, stk))
636 when red_set info.reds fBETA ->
637 let rec apply env lams args =
638 if Int.equal lams 0 then
639 let stk = if List.is_empty args then stk else APP (args, stk) in
640 cbv_stack_term info stk env b
641 else match args with
642 | [] ->
643 let ctxt' = List.skipn (nlams - lams) ctxt in
644 LAMBDA (lams, ctxt', b, env)
645 | v :: args ->
646 let env = subs_cons v env in
647 apply env (lams - 1) args
648 in
649 apply env nlams args
650 (* a Fix applied enough -> IOTA *)
651 | (FIX(fix,env,[||]), stk)
652 when fixp_reducible info.reds fix stk ->
653 let (envf,redfix) = contract_fixp env fix in
654 cbv_stack_term info stk envf redfix
655
656 (* constructor guard satisfied or Cofix in a Case -> IOTA *)
657 | (COFIX(cofix,env,[||]), stk)
658 when cofixp_reducible info.reds cofix stk->
659 let (envf,redfix) = contract_cofixp env cofix in
660 cbv_stack_term info stk envf redfix
661
662 (* constructor in a Case -> IOTA *)
663 | (CONSTRUCT(((sp,n),_),[||]), APP(args,CASE(u,pms,_p,br,iv,ci,env,stk)))
664 when red_set info.reds fMATCH ->
665 let cargs = List.skipn ci.ci_npar args in
666 let env =
667 if (Int.equal ci.ci_cstr_ndecls.(n - 1) ci.ci_cstr_nargs.(n - 1)) then (* no lets *)
668 List.fold_left (fun accu v -> subs_cons v accu) env cargs
669 else
670 let mkclos env c = cbv_stack_term info TOP env c in
671 let ctx = expand_branch info.env u pms (sp, n) br in
672 cbv_subst_of_rel_context_instance_list mkclos ctx cargs env
673 in
674 cbv_stack_term info stk env (snd br.(n-1))
675
676 (* constructor of arity 0 in a Case -> IOTA *)
677 | (CONSTRUCT(((sp, n), _),[||]), CASE(u,pms,_,br,_,ci,env,stk))
678 when red_set info.reds fMATCH ->
679 let env =
680 if (Int.equal ci.ci_cstr_ndecls.(n - 1) ci.ci_cstr_nargs.(n - 1)) then (* no lets *)
681 env
682 else
683 let mkclos env c = cbv_stack_term info TOP env c in
684 let ctx = expand_branch info.env u pms (sp, n) br in
685 cbv_subst_of_rel_context_instance_list mkclos ctx [] env
686 in
687 cbv_stack_term info stk env (snd br.(n-1))
688
689 (* constructor in a Projection -> IOTA *)
690 | (CONSTRUCT(((sp,n),u),[||]), APP(args,PROJ(p,_,stk)))
691 when red_set info.reds fMATCH && Projection.unfolded p ->
692 let arg = List.nth args (Projection.npars p + Projection.arg p) in
693 cbv_stack_value info env (strip_appl arg stk)
694
695 (* may be reduced later by application *)
696 | (FIX(fix,env,[||]), APP(appl,TOP)) -> FIX(fix,env,Array.of_list appl)
697 | (COFIX(cofix,env,[||]), APP(appl,TOP)) -> COFIX(cofix,env,Array.of_list appl)
698 | (CONSTRUCT(c,[||]), APP(appl,TOP)) -> CONSTRUCT(c,Array.of_list appl)
699
700 (* primitive apply to arguments *)
701 | (PRIMITIVE(op,(_,u as c),[||]), APP(appl,stk)) ->
702 let nargs = CPrimitives.arity op in
703 begin match List.chop nargs appl with
704 | (args, appl) ->
705 let stk = if List.is_empty appl then stk else stack_app appl stk in
706 begin match VredNative.red_prim info.env () op u (Array.of_list args) with
707 | Some (CONSTRUCT (c, args)) ->
708 (* args must be moved to the stack to allow future reductions *)
709 cbv_stack_value info env (CONSTRUCT(c, [||]), stack_vect_app args stk)
710 | Some v -> cbv_stack_value info env (v,stk)
711 | None -> mkSTACK(PRIMITIVE(op,c,Array.of_list args), stk)
712 end
713 | exception Failure _ ->
714 (* partial application *)
715 (assert (stk = TOP);
716 PRIMITIVE(op,c,Array.of_list appl))
717 end
718 | SYMBOL ({ cst; rules; stk } as s ), stk' ->
719 let stk = stack_concat stk stk' in
720 begin try
721 let rhs, stack = cbv_apply_rules info env (snd cst) rules stk in
722 cbv_stack_value info env (destack rhs stack)
723 with PatternFailure ->
724 SYMBOL { s with stk }
725 end
726
727 (* definitely a value *)
728 | (head,stk) -> mkSTACK(head, stk)
729
730 and cbv_value_cache info ref =
731 try KeyTable.find info.tab ref with
732 Not_found ->
733 let v =
734 try
735 let body = match ref with
736 | RelKey n ->
737 let open Context.Rel.Declaration in
738 begin match Environ.lookup_rel n info.env with
739 | LocalDef (_, c, _) -> lift n c
740 | LocalAssum _ -> raise Not_found
741 end
742 | VarKey id ->
743 let open Context.Named.Declaration in
744 begin match Environ.lookup_named id info.env with
745 | LocalDef (_, c, _) -> c
746 | LocalAssum _ -> raise Not_found
747 end
748 | ConstKey (cst, u) ->
749 EConstr.Unsafe.to_constr @@ EConstr.constant_value_in info.env info.sigma (cst, EConstr.EInstance.make u)
750 in
751 let v = cbv_stack_term info TOP (subs_id 0) body in
752 Declarations.Def v
753 with
754 | Environ.NotEvaluableConst (Environ.IsPrimitive (_u,op)) -> Declarations.Primitive op
755 | Environ.NotEvaluableConst (Environ.HasRules (u, b, r)) -> Declarations.Symbol (b, r)
756 | Not_found | Environ.NotEvaluableConst _ -> Declarations.Undef None
757 in
758 KeyTable.add info.tab ref v; v
759
760
761 and it_mkLambda_or_LetIn info ctx t =
762 let open Context.Rel.Declaration in
763 match List.rev ctx with
764 | [] -> t
765 | LocalAssum (n, ty) :: ctx ->
766 let assums, ctx = List.map_until (function LocalAssum (n, ty) -> Some (n, ty) | LocalDef _ -> None) ctx in
767 let assums = (n, ty) :: assums in
768 LAMBDA (List.length assums, assums, Term.it_mkLambda_or_LetIn (reify_value t) (List.rev ctx), subs_id 0)
769 | LocalDef _ :: _ ->
770 cbv_stack_term info TOP (subs_id 0) (Term.it_mkLambda_or_LetIn (reify_value t) ctx)
771
772 and cbv_match_arg_pattern info env ctx psubst p t =
773 let open Declarations in
774 let t' = it_mkLambda_or_LetIn info ctx t in
775 match p with
776 | EHole i -> Partial_subst.add_term i t' psubst
777 | EHoleIgnored -> psubst
778 | ERigid (ph, es) ->
779 let t, stk = destack t TOP in
780 let psubst = cbv_match_rigid_arg_pattern info env ctx psubst ph t in
781 let psubst, stk = cbv_apply_rule info env ctx psubst es stk in
782 match stk with
783 | TOP -> psubst
784 | APP _| CASE _ | PROJ _ -> raise PatternFailure
785
786 and cbv_match_arg_pattern_lift info env ctx n psubst p t =
787 let env = subs_liftn n env in
788 cbv_match_arg_pattern info env ctx psubst p
789 (cbv_stack_term info TOP env t)
790
791 and match_sort ps s subst =
792 match Sorts.pattern_match ps s subst with
793 | Some subst -> subst
794 | None -> raise PatternFailure
795
796 and match_instance pu u psubst =
797 match UVars.Instance.pattern_match pu u psubst with
798 | Some subst -> subst
799 | None -> raise PatternFailure
800
801
802 and cbv_match_rigid_arg_pattern info env ctx psubst p t =
803 let open Declarations in
804 match [@ocaml.warning "-4"] p, t with
805 | PHInd (ind, pu), VAL(0, t') ->
806 begin match kind t' with Ind (ind', u) when Environ.QInd.equal info.env ind ind' -> match_instance pu u psubst | _ -> raise PatternFailure end
807 | PHConstr (constr, pu), CONSTRUCT ((constr', u), [||]) ->
808 if Environ.QConstruct.equal info.env constr constr' then match_instance pu u psubst else raise PatternFailure
809 | PHRel i, VAL(k, t') ->
810 begin match kind t' with Rel n when Int.equal i (k + n) -> psubst | _ -> raise PatternFailure end
811 | PHSort ps, VAL(0, t') ->
812 begin match kind t' with Sort s -> match_sort ps s psubst | _ -> raise PatternFailure end
813 | PHSymbol (c, pu), SYMBOL { cst = c', u; _ } ->
814 if Environ.QConstant.equal info.env c c' then match_instance pu u psubst else raise PatternFailure
815 | PHInt i, VAL(0, t') ->
816 begin match kind t' with Int i' when Uint63.equal i i' -> psubst | _ -> raise PatternFailure end
817 | PHFloat f, VAL(0, t') ->
818 begin match kind t' with Float f' when Float64.equal f f' -> psubst | _ -> raise PatternFailure end
819 | PHString s, VAL(0, t') ->
820 begin match kind t' with String s' when Pstring.equal s s' -> psubst | _ -> raise PatternFailure end
821 | PHLambda (ptys, pbod), LAMBDA (nlam, ntys, body, env) ->
822 let np = Array.length ptys in
823 if np > nlam then raise PatternFailure;
824 let ntys, body =
825 if np = nlam then ntys, body
826 else (* np < nlam *)
827 let ntys, tys' = List.chop np ntys in
828 ntys, Term.compose_lam (List.rev tys') body
829 in
830 let ctx' = List.rev_map (fun (n, ty) -> Context.Rel.Declaration.LocalAssum (n, ty)) ntys in
831 let ctx' = apply_env_context env ctx' in
832 let tys = Array.of_list ntys in
833 let contexts_upto = Array.init np (fun i -> List.lastn i ctx' @ ctx) in
834 let psubst = Array.fold_left3_i (fun i psubst ctx pty (_, ty) -> cbv_match_arg_pattern_lift info env ctx i psubst pty ty) psubst contexts_upto ptys tys in
835 let psubst = cbv_match_arg_pattern_lift info env (ctx' @ ctx) np psubst (ERigid pbod) body in
836 psubst
837 | PHProd (ptys, pbod), PROD (na, ty, body, env) ->
838 let ntys, _ = Term.decompose_prod body in
839 let np = Array.length ptys in
840 let nprod = 1 + List.length ntys in
841 if np > nprod then raise PatternFailure;
842 let ntys, body = Term.decompose_prod_n (np-1) body in
843 let ctx' = List.map (fun (n, ty) -> Context.Rel.Declaration.LocalAssum (n, ty)) (ntys @ [na, ty]) in
844 let ctx' = apply_env_context env ctx' in
845 let tys = Array.of_list ((na, ty) :: List.rev ntys) in
846 let na = Array.length tys in
847 let contexts_upto = Array.init na (fun i -> List.lastn i ctx' @ ctx) in
848 let psubst = Array.fold_left3_i (fun i psubst ctx pty (_, ty) -> cbv_match_arg_pattern_lift info env ctx i psubst pty ty) psubst contexts_upto ptys tys in
849 let psubst = cbv_match_arg_pattern_lift info env (ctx' @ ctx) na psubst pbod body in
850 psubst
851 | (PHInd _ | PHConstr _ | PHRel _ | PHInt _ | PHFloat _ | PHString _ | PHSort _ | PHSymbol _ | PHLambda _ | PHProd _), _ -> raise PatternFailure
852
853
854 and cbv_apply_rule info env ctx psubst es stk =
855 match [@ocaml.warning "-4"] es, stk with
856 | [], _ -> psubst, stk
857 | Declarations.PEApp pargs :: e, APP (args, s) ->
858 let args = Array.of_list args in
859 let np = Array.length pargs in
860 let na = Array.length args in
861 if np == na then
862 let psubst = Array.fold_left2 (cbv_match_arg_pattern info env ctx) psubst pargs args in
863 cbv_apply_rule info env ctx psubst e s
864 else if np < na then (* more real arguments *)
865 let usedargs, remargs = Array.chop np args in
866 let psubst = Array.fold_left2 (cbv_match_arg_pattern info env ctx) psubst pargs usedargs in
867 cbv_apply_rule info env ctx psubst e (APP (Array.to_list remargs, s))
868 else (* more pattern arguments *)
869 let usedpargs, rempargs = Array.chop na pargs in
870 let psubst = Array.fold_left2 (cbv_match_arg_pattern info env ctx) psubst usedpargs args in
871 cbv_apply_rule info env ctx psubst (PEApp rempargs :: e) s
872 | Declarations.PECase (pind, pret, pbrs) :: e, CASE (u, pms, (p, _), brs, iv, ci, env, s) ->
873 if not @@ Environ.QInd.equal info.env pind ci.ci_ind then raise PatternFailure;
874 let specif = Inductive.lookup_mind_specif info.env ci.ci_ind in
875 let ntys_ret = Inductive.expand_arity specif (ci.ci_ind, u) pms (fst p) in
876 let ntys_ret = apply_env_context env ntys_ret in
877 let ntys_brs = Inductive.expand_branch_contexts specif u pms brs in
878 let brs = Array.map2 (fun ctx' br -> List.length ctx', ctx' @ ctx, (snd br)) ntys_brs brs in
879 let psubst = cbv_match_arg_pattern_lift info env (ntys_ret @ ctx) (List.length ntys_ret) psubst pret (snd p) in
880 let psubst = Array.fold_left2 (fun psubst pat (n, ctx, br) -> cbv_match_arg_pattern_lift info env (apply_env_context env ctx) n psubst pat br) psubst pbrs brs in
881 cbv_apply_rule info env ctx psubst e s
882 | Declarations.PEProj proj :: e, PROJ (proj', r, s) ->
883 if not @@ Environ.QProjection.Repr.equal info.env proj (Projection.repr proj') then raise PatternFailure;
884 cbv_apply_rule info env ctx psubst e s
885 | _, _ -> raise PatternFailure
886
887
888 and cbv_apply_rules info env u r stk =
889 match r with
890 | [] -> raise PatternFailure
891 | { lhs_pat = (pu, elims); nvars; rhs } :: rs ->
892 try
893 let psubst = Partial_subst.make nvars in
894 let psubst = match_instance pu u psubst in
895 let psubst, stk = cbv_apply_rule info env [] psubst elims stk in
896 let subst, qsubst, usubst = Partial_subst.to_arrays psubst in
897 let subst = Array.fold_right subs_cons subst env in
898 let usubst = UVars.Instance.of_array (qsubst, usubst) in
899 let rhsu = Vars.subst_instance_constr usubst rhs in
900 let rhs' = cbv_stack_term info TOP subst rhsu in
901 rhs', stk
902 with PatternFailure -> cbv_apply_rules info env u rs stk
903
904
905
906
907 (* When we are sure t will never produce a redex with its stack, we
908 * normalize (even under binders) the applied terms and we build the
909 * final term
910 *)
911 let rec apply_stack info t = function
912 | TOP -> t
913 | APP (args,st) ->
914 (* Note: should "theoretically" use a right-to-left version of map_of_list *)
915 apply_stack info (mkApp(t,Array.map_of_list (cbv_norm_value info) args)) st
916 | CASE (u,pms,ty,br,iv,ci,env,st) ->
917 (* FIXME: Prevent this expansion by caching whether an inductive contains let-bindings *)
918 let (_, (ty,r), _, _, br) = Inductive.expand_case info.env (ci, u, pms, ty, iv, mkProp, br) in
919 let ty =
920 let (_, mip) = Inductive.lookup_mind_specif info.env ci.ci_ind in
921 Term.decompose_lambda_n_decls (mip.Declarations.mind_nrealdecls + 1) ty
922 in
923 let mk_br c n = Term.decompose_lambda_n_decls n c in
924 let br = Array.map2 mk_br br ci.ci_cstr_ndecls in
925 let aux = if info.strong then cbv_norm_term info else apply_env in
926 let map_ctx (nas, c) =
927 let open Context.Rel.Declaration in
928 let fold decl e = match decl with
929 | LocalAssum _ -> subs_lift e
930 | LocalDef (_, b, _) ->
931 let b = cbv_stack_term info TOP e b in
932 (* The let-binding persists, so we have to shift *)
933 subs_shft (1, subs_cons b e)
934 in
935 let env = List.fold_right fold nas env in
936 let nas = Array.of_list (List.rev_map get_annot nas) in
937 (nas, aux env c)
938 in
939 apply_stack info
940 (mkCase (ci, u, Array.map (aux env) pms, (map_ctx ty,r), iv, t,
941 Array.map map_ctx br))
942 st
943 | PROJ (p, r, st) ->
944 apply_stack info (mkProj (p, r, t)) st
945
946 (* performs the reduction on a constr, and returns a constr *)
947 and cbv_norm_term info env t =
948 (* reduction under binders *)
949 cbv_norm_value info (cbv_stack_term info TOP env t)
950
951 (* reduction of a cbv_value to a constr *)
952 and cbv_norm_value info = function
953 | VAL (n,t) -> lift n t
954 | STACK (0,v,stk) ->
955 apply_stack info (cbv_norm_value info v) stk
956 | STACK (n,v,stk) ->
957 lift n (apply_stack info (cbv_norm_value info v) stk)
958 | PROD(na,t,u,env) ->
959 mkProd (na,cbv_norm_term info env t,cbv_norm_term info (subs_lift env) u)
960 | LETIN (na,b,t,c,env) ->
961 let aux = if info.strong then cbv_norm_term info else apply_env in
962 mkLetIn (na,cbv_norm_value info b,aux env t,aux (subs_lift env) c)
963 | LAMBDA (n,ctxt,b,env) ->
964 let nctxt =
965 List.map_i (fun i (x,ty) ->
966 (x,cbv_norm_term info (subs_liftn i env) ty)) 0 ctxt in
967 let aux = if info.strong then cbv_norm_term info else apply_env in
968 Term.compose_lam (List.rev nctxt) (aux (subs_liftn n env) b)
969 | FIX ((lij,(names,lty,bds)),env,args) ->
970 let aux = if info.strong then cbv_norm_term info else apply_env in
971 mkApp
972 (mkFix (lij,
973 (names,
974 Array.map (aux env) lty,
975 Array.map (aux (subs_liftn (Array.length lty) env)) bds)),
976 Array.map (cbv_norm_value info) args)
977 | COFIX ((j,(names,lty,bds)),env,args) ->
978 mkApp
979 (mkCoFix (j,
980 (names,Array.map (cbv_norm_term info env) lty,
981 Array.map (cbv_norm_term info
982 (subs_liftn (Array.length lty) env)) bds)),
983 Array.map (cbv_norm_value info) args)
984 | CONSTRUCT (c,args) ->
985 mkApp(mkConstructU c, Array.map (cbv_norm_value info) args)
986 | PRIMITIVE(op,c,args) ->
987 mkApp(mkConstU c,Array.map (cbv_norm_value info) args)
988 | ARRAY (u,t,ty) ->
989 let ty = cbv_norm_value info ty in
990 let t, def = Parray.to_array t in
991 let def = cbv_norm_value info def in
992 mkArray(u, Array.map (cbv_norm_value info) t, def, ty)
993 | SYMBOL { cst; stk; _ } -> apply_stack info (mkConstU cst) stk
994
995 (* with profiling *)
996 let cbv_norm infos constr =
997 let constr = EConstr.Unsafe.to_constr constr in
998 EConstr.of_constr (cbv_norm_term infos (subs_id 0) constr)
999
1000 (* constant bodies are normalized at the first expansion *)
1001 let create_cbv_infos reds ~strong env sigma =
1002 { tab = KeyTable.create 91; reds; env; sigma; strong }