Debian Codegraph @

kernel/cClosure.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 (* Created by Bruno Barras with Benjamin Werner's account to implement
12 a call-by-value conversion algorithm and a lazy reduction machine
13 with sharing, Nov 1996 *)
14 (* Addition of zeta-reduction (let-in contraction) by Hugo Herbelin, Oct 2000 *)
15 (* Call-by-value machine moved to cbv.ml, Mar 01 *)
16 (* Additional tools for module subtyping by Jacek Chrzaszcz, Aug 2002 *)
17 (* Extension with closure optimization by Bruno Barras, Aug 2003 *)
18 (* Support for evar reduction by Bruno Barras, Feb 2009 *)
19 (* Miscellaneous other improvements by Bruno Barras, 1997-2009 *)
20
21 (* This file implements a lazy reduction for the Calculus of Inductive
22 Constructions *)
23
24 [@@@ocaml.warning "+4"]
25
26 open CErrors
27 open Util
28 open Names
29 open Constr
30 open Declarations
31 open Context
32 open Environ
33 open Vars
34 open Esubst
35 open RedFlags
36
37 module RelDecl = Context.Rel.Declaration
38 module NamedDecl = Context.Named.Declaration
39
40 type mode = Conversion | Reduction
41 (* In conversion mode we can introduce FIrrelevant terms.
42 Invariants of the conversion mode:
43 - the only irrelevant terms as returned by [knr] are either [FIrrelevant],
44 [FLambda], [FFlex] or [FRel].
45 - the stack never contains irrelevant-producing nodes i.e. [Zproj], [ZFix]
46 and [ZcaseT] are all relevant
47 *)
48
49 (**********************************************************************)
50 (* Lazy reduction: the one used in kernel operations *)
51
52 (* type of shared terms. fconstr and frterm are mutually recursive.
53 * Clone of the constr structure, but completely mutable, and
54 * annotated with reduction state (reducible or not).
55 * - FLIFT is a delayed shift; allows sharing between 2 lifted copies
56 * of a given term.
57 * - FCLOS is a delayed substitution applied to a constr
58 * - FLOCKED is used to erase the content of a reference that must
59 * be updated. This is to allow the garbage collector to work
60 * before the term is computed.
61 *)
62
63 (* Ntrl means the term is in βιδζ head normal form and cannot create a redex
64 when substituted
65 Cstr means the term is in βιδζ head normal form and that it can
66 create a redex when substituted (i.e. constructor, fix, lambda)
67 Red is used for terms that might be reduced
68 *)
69 type red_state = Ntrl | Cstr | Red
70
71 let neutr = function Ntrl -> Ntrl | Red | Cstr -> Red
72 let is_red = function Red -> true | Ntrl | Cstr -> false
73
74 type table_key = Constant.t UVars.puniverses tableKey
75
76 type evar_repack = Evar.t * constr list -> constr
77
78 type fconstr = {
79 mutable mark : red_state;
80 mutable term: fterm;
81 }
82
83 and fterm =
84 | FRel of int
85 | FAtom of constr (* Metas and Sorts *)
86 | FFlex of table_key
87 | FInd of pinductive
88 | FConstruct of pconstructor * fconstr array
89 | FApp of fconstr * fconstr array
90 | FProj of Projection.t * Sorts.relevance * fconstr
91 | FFix of fixpoint * usubs
92 | FCoFix of cofixpoint * usubs
93 | FCaseT of case_info * UVars.Instance.t * constr array * case_return * fconstr * case_branch array * usubs (* predicate and branches are closures *)
94 | FCaseInvert of case_info * UVars.Instance.t * constr array * case_return * finvert * fconstr * case_branch array * usubs
95 | FLambda of int * (Name.t binder_annot * constr) list * constr * usubs
96 | FProd of Name.t binder_annot * fconstr * constr * usubs
97 | FLetIn of Name.t binder_annot * fconstr * fconstr * constr * usubs
98 | FEvar of Evar.t * constr list * usubs * evar_repack
99 | FInt of Uint63.t
100 | FFloat of Float64.t
101 | FString of Pstring.t
102 | FArray of UVars.Instance.t * fconstr Parray.t * fconstr
103 | FLIFT of int * fconstr
104 | FCLOS of constr * usubs
105 | FIrrelevant
106 | FLOCKED
107
108 and usubs = fconstr subs UVars.puniverses
109
110 and finvert = fconstr array
111
112 let get_invert fiv = fiv
113
114 let fterm_of v = v.term
115 let set_ntrl v = v.mark <- Ntrl
116
117 (* Could issue a warning if no is still Red, pointing out that we loose
118 sharing. *)
119 let update v1 mark t =
120 v1.mark <- mark; v1.term <- t
121
122 type 'a evar_expansion =
123 | EvarDefined of 'a
124 | EvarUndefined of Evar.t * 'a list
125
126 type evar_handler = {
127 evar_expand : constr pexistential -> constr evar_expansion;
128 evar_repack : Evar.t * constr list -> constr;
129 evar_irrelevant : constr pexistential -> bool;
130 qvar_irrelevant : Sorts.QVar.t -> bool;
131 qual_equal : Sorts.Quality.t -> Sorts.Quality.t -> bool;
132 abstr_const : Constant.t -> (unit, (unit -> Vmemitcodes.to_patch) Vmemitcodes.pbody_code) Declarations.pconstant_body;
133 }
134
135 let default_evar_handler env = {
136 evar_expand = (fun _ -> assert false);
137 evar_repack = (fun _ -> assert false);
138 evar_irrelevant = (fun _ -> assert false);
139 qvar_irrelevant = (fun q ->
140 assert (Sorts.QVar.Set.mem q (Environ.qvars env));
141 false);
142 qual_equal = Sorts.Quality.equal;
143 abstr_const = fun _ -> assert false;
144 }
145
146 let drop_opaque = function
147 | OpaqueDef _ -> OpaqueDef ()
148 | Def _ | Undef _ | Primitive _ | Symbol _ as body -> body
149
150 let drop_code env = function
151 | None -> Vmemitcodes.BCconstant
152 | Some (Vmemitcodes.BCdefined (mask, idx, patch)) ->
153 let code () = Environ.lookup_vm_code idx env in
154 Vmemitcodes.BCdefined (mask, code, patch)
155 | Some (BCalias _ | BCconstant as code) -> code
156
157 let lookup_constant_handler env sigma cst = match lookup_constant_opt cst env with
158 | None -> sigma.abstr_const cst
159 | Some cb ->
160 let const_body = drop_opaque cb.const_body in
161 let const_body_code = drop_code env cb.const_body_code in
162 { cb with const_body; const_body_code }
163
164 (** Reduction cache *)
165 type infos_cache = {
166 i_env : env;
167 i_sigma : evar_handler;
168 i_share : bool;
169 i_univs : UGraph.t;
170 i_mode : mode;
171 }
172
173 type clos_infos = {
174 i_flags : reds;
175 i_relevances : Sorts.relevance Range.t;
176 i_cache : infos_cache }
177
178 let info_flags info = info.i_flags
179 let info_env info = info.i_cache.i_env
180 let info_univs info = info.i_cache.i_univs
181
182 let push_relevance infos x =
183 { infos with i_relevances = Range.cons x.binder_relevance infos.i_relevances }
184
185 let push_relevances infos nas =
186 { infos with
187 i_relevances =
188 Array.fold_left (fun l x -> Range.cons x.binder_relevance l)
189 infos.i_relevances nas }
190
191 let set_info_relevances info r = { info with i_relevances = r }
192
193 let info_relevances info = info.i_relevances
194
195 (**********************************************************************)
196 (* The type of (machine) stacks (= lambda-bar-calculus' contexts) *)
197 type 'a next_native_args = (CPrimitives.arg_kind * 'a) list
198
199 type stack_member =
200 | Zapp of fconstr array
201 | ZcaseT of case_info * UVars.Instance.t * constr array * case_return * case_branch array * usubs
202 | Zproj of Projection.Repr.t * Sorts.relevance
203 | Zfix of fconstr * stack
204 | Zprimitive of CPrimitives.t * pconstant * fconstr list * fconstr next_native_args
205 (* operator, constr def, arguments already seen (in rev order), next arguments *)
206 | Zshift of int
207 | Zupdate of fconstr
208
209 and stack = stack_member list
210
211 let empty_stack = []
212 let append_stack v s =
213 if Int.equal (Array.length v) 0 then s else
214 match s with
215 | Zapp l :: s -> Zapp (Array.append v l) :: s
216 | (ZcaseT _ | Zproj _ | Zfix _ | Zshift _ | Zupdate _ | Zprimitive _) :: _ | [] ->
217 Zapp v :: s
218
219 (* Collapse the shifts in the stack *)
220 let zshift n s =
221 match (n,s) with
222 (0,_) -> s
223 | (_,Zshift(k)::s) -> Zshift(n+k)::s
224 | (_,(ZcaseT _ | Zproj _ | Zfix _ | Zapp _ | Zupdate _ | Zprimitive _) :: _) | _,[] -> Zshift(n)::s
225
226 let rec stack_args_size = function
227 | Zapp v :: s -> Array.length v + stack_args_size s
228 | Zshift(_)::s -> stack_args_size s
229 | Zupdate(_)::s -> stack_args_size s
230 | (ZcaseT _ | Zproj _ | Zfix _ | Zprimitive _) :: _ | [] -> 0
231
232 let usubs_shft (n,(e,u)) = subs_shft (n, e), u
233
234 (* Lifting. Preserves sharing (useful only for cell with norm=Red).
235 lft_fconstr always create a new cell, while lift_fconstr avoids it
236 when the lift is 0. *)
237 let rec lft_fconstr n ft =
238 match ft.term with
239 | (FInd _|FConstruct (_,[||])|FFlex(ConstKey _|VarKey _)|FInt _|FFloat _|FString _|FIrrelevant) -> ft
240 | FRel i -> {mark=ft.mark;term=FRel(i+n)}
241 | FLambda(k,tys,f,e) -> {mark=Cstr; term=FLambda(k,tys,f,usubs_shft(n,e))}
242 | FFix(fx,e) ->
243 {mark=Cstr; term=FFix(fx,usubs_shft(n,e))}
244 | FCoFix(cfx,e) ->
245 {mark=Cstr; term=FCoFix(cfx,usubs_shft(n,e))}
246 | FLIFT(k,m) -> lft_fconstr (n+k) m
247 | FConstruct (c,args) -> {mark=Cstr; term=FConstruct(c,Array.Fun1.map lft_fconstr n args)}
248 | FLOCKED -> assert false
249 | FFlex (RelKey _) | FAtom _ | FApp _ | FProj _ | FCaseT _ | FCaseInvert _ | FProd _
250 | FLetIn _ | FEvar _ | FCLOS _ | FArray _ -> {mark=ft.mark; term=FLIFT(n,ft)}
251 let lift_fconstr k f =
252 if Int.equal k 0 then f else lft_fconstr k f
253
254 let clos_rel e i =
255 match expand_rel i e with
256 | Inl(n,mt) -> lift_fconstr n mt
257 | Inr(k,None) -> {mark=Ntrl; term= FRel k}
258 | Inr(k,Some p) ->
259 lift_fconstr (k-p) {mark=Red;term=FFlex(RelKey p)}
260
261 (* since the head may be reducible, we might introduce lifts of 0 *)
262 let compact_stack head stk =
263 let rec strip_rec depth = function
264 | Zshift(k)::s -> strip_rec (depth+k) s
265 | Zupdate(m)::s ->
266 (* Be sure to create a new cell otherwise sharing would be
267 lost by the update operation *)
268 let h' = lft_fconstr depth head in
269 (** The stack contains [Zupdate] marks only if in sharing mode *)
270 let () = update m h'.mark h'.term in
271 strip_rec depth s
272 | ((ZcaseT _ | Zproj _ | Zfix _ | Zapp _ | Zprimitive _) :: _ | []) as stk -> zshift depth stk
273 in
274 strip_rec 0 stk
275
276 (* Put an update mark in the stack, only if needed *)
277 let zupdate info m s =
278 let share = info.i_cache.i_share in
279 if share && is_red m.mark then
280 let s' = compact_stack m s in
281 let _ = m.term <- FLOCKED in
282 Zupdate(m)::s'
283 else s
284
285 (* We use empty as a special identity value, if we don't check
286 subst_instance_instance will raise array out of bounds. *)
287 let usubst_instance (_,u) u' =
288 if UVars.Instance.is_empty u then u'
289 else UVars.subst_instance_instance u u'
290
291 let usubst_punivs (_,u) (v,u' as orig) =
292 if UVars.Instance.is_empty u then orig
293 else v, UVars.subst_instance_instance u u'
294
295 let usubst_sort (_,u) s =
296 if UVars.Instance.is_empty u then s
297 else UVars.subst_instance_sort u s
298
299 let usubst_relevance (_,u) r =
300 if UVars.Instance.is_empty u then r
301 else UVars.subst_instance_relevance u r
302
303 let usubst_binder e x =
304 let r = x.binder_relevance in
305 let r' = usubst_relevance e r in
306 if r == r' then x else { x with binder_relevance = r' }
307
308 let mk_lambda env t =
309 let (rvars,t') = Term.decompose_lambda t in
310 FLambda(List.length rvars, List.rev rvars, t', env)
311
312 let usubs_lift (e,u) = subs_lift e, u
313
314 let usubs_liftn n (e,u) = subs_liftn n e, u
315
316 (* t must be a FLambda and binding list cannot be empty *)
317 let destFLambda clos_fun t =
318 match [@ocaml.warning "-4"] t.term with
319 | FLambda(_,[(na,ty)],b,e) ->
320 (usubst_binder e na,clos_fun e ty,clos_fun (usubs_lift e) b)
321 | FLambda(n,(na,ty)::tys,b,e) ->
322 (usubst_binder e na,clos_fun e ty,{mark=t.mark;term=FLambda(n-1,tys,b,usubs_lift e)})
323 | _ -> assert false
324
325 (* Optimization: do not enclose variables in a closure.
326 Makes variable access much faster *)
327 let mk_clos (e:usubs) t =
328 match kind t with
329 | Rel i -> clos_rel (fst e) i
330 | Var x -> {mark = Red; term = FFlex (VarKey x) }
331 | Const c -> {mark = Red; term = FFlex (ConstKey (usubst_punivs e c)) }
332 | Sort s ->
333 let s = usubst_sort e s in
334 {mark = Ntrl; term = FAtom (mkSort s) }
335 | Meta _ -> {mark = Ntrl; term = FAtom t }
336 | Ind kn -> {mark = Ntrl; term = FInd (usubst_punivs e kn) }
337 | Construct kn -> {mark = Cstr; term = FConstruct (usubst_punivs e kn,[||]) }
338 | Int i -> {mark = Cstr; term = FInt i}
339 | Float f -> {mark = Cstr; term = FFloat f}
340 | String s -> {mark = Cstr; term = FString s}
341 | (CoFix _|Lambda _|Fix _|Prod _|Evar _|App _|Case _|Cast _|LetIn _|Proj _|Array _) ->
342 {mark = Red; term = FCLOS(t,e)}
343
344 let injectu c u = mk_clos (subs_id 0, u) c
345
346 let inject c = injectu c UVars.Instance.empty
347
348 let mk_irrelevant = { mark = Cstr; term = FIrrelevant }
349
350 let is_irrelevant info r = match info.i_cache.i_mode with
351 | Reduction -> false
352 | Conversion -> match r with
353 | Sorts.Irrelevant -> true
354 | Sorts.RelevanceVar q -> info.i_cache.i_sigma.qvar_irrelevant q
355 | Sorts.Relevant -> false
356
357 let eq_quality info q1 q2 =
358 info.i_cache.i_sigma.qual_equal q1 q2
359
360 (************************************************************************)
361
362 type table_val = (fconstr * bool array, Empty.t, UVars.Instance.t * bool * machine_rewrite_rule list) constant_def
363
364 module Table : sig
365 type t
366 val create : unit -> t
367 val lookup : clos_infos -> t -> table_key -> table_val
368 end = struct
369 module Table = Hashtbl.Make(struct
370 type t = table_key
371 let equal = eq_table_key (eq_pair eq_constant_key UVars.Instance.equal)
372 let hash = hash_table_key (fun (c, _) -> Constant.UserOrd.hash c)
373 end)
374
375 type t = table_val Table.t
376
377 let create () = Table.create 17
378
379 exception Irrelevant
380
381 let shortcut_irrelevant info r =
382 if is_irrelevant info r then raise Irrelevant
383
384 let assoc_defined d =
385 match d with
386 | NamedDecl.LocalDef (_, c, _) -> inject c
387 | NamedDecl.LocalAssum (_, _) -> raise Not_found
388
389 let constant_value_in u = function
390 | Def b -> injectu b u
391 | OpaqueDef _ -> raise (NotEvaluableConst Opaque)
392 | Undef _ -> raise (NotEvaluableConst NoBody)
393 | Primitive p -> raise (NotEvaluableConst (IsPrimitive (u,p)))
394 | Symbol _ -> assert false
395 (* Should already be dealt with *)
396
397 let value_of info ref =
398 try
399 let env = info.i_cache.i_env in
400 match ref with
401 | RelKey n ->
402 let i = n - 1 in
403 let d =
404 try Range.get (Environ.rel_context_val env).env_rel_map i
405 with Invalid_argument _ -> raise Not_found
406 in
407 shortcut_irrelevant info (RelDecl.get_relevance d);
408 let body =
409 match d with
410 | RelDecl.LocalAssum _ -> raise Not_found
411 | RelDecl.LocalDef (_, t, _) -> lift n t
412 in
413 Def (inject body, [||])
414 | VarKey id ->
415 let def = Environ.lookup_named id env in
416 shortcut_irrelevant info
417 (binder_relevance (NamedDecl.get_annot def));
418 let ts = RedFlags.red_transparent info.i_flags in
419 if TransparentState.is_transparent_variable ts id then
420 Def (assoc_defined def, [||])
421 else
422 raise Not_found
423 | ConstKey (cst,u) ->
424 let cb = match lookup_constant_opt cst env with
425 | Some cb -> { cb with const_body = drop_opaque cb.const_body; const_body_code = drop_code env cb.const_body_code }
426 | None -> info.i_cache.i_sigma.abstr_const cst
427 in
428 shortcut_irrelevant info (UVars.subst_instance_relevance u cb.const_relevance);
429 let ts = RedFlags.red_transparent info.i_flags in
430 if TransparentState.is_transparent_constant ts cst then match cb.const_body with
431 | Undef _ | Def _ | OpaqueDef _ | Primitive _ ->
432 let mask = match cb.const_body_code with
433 | (Vmemitcodes.BCalias _ | Vmemitcodes.BCconstant) -> [||]
434 | (Vmemitcodes.BCdefined (mask, _, _)) -> mask
435 in
436 Def (constant_value_in u cb.const_body, mask)
437 | Symbol b ->
438 let r = match lookup_rewrite_rules cst env with
439 | exception Not_found -> assert false
440 | r -> r
441 in
442 raise (NotEvaluableConst (HasRules (u, b, r)))
443 else
444 raise Not_found
445 with
446 | Irrelevant -> Def (mk_irrelevant, [||])
447 | NotEvaluableConst (IsPrimitive (_u,op)) (* Const *) -> Primitive op
448 | NotEvaluableConst (HasRules (u, b, r)) -> Symbol (u, b, r)
449 | Not_found (* List.assoc *)
450 | NotEvaluableConst _ (* Const *) -> Undef None
451
452 let lookup info tab ref =
453 try Table.find tab ref with Not_found ->
454 let v = value_of info ref in
455 Table.add tab ref v; v
456 end
457
458 type clos_tab = Table.t
459
460 let create_tab = Table.create
461
462 (************************************************************************)
463
464 (** Hand-unrolling of the map function to bypass the call to the generic array
465 allocation *)
466 let mk_clos_vect env v = match v with
467 | [||] -> [||]
468 | [|v0|] -> [|mk_clos env v0|]
469 | [|v0; v1|] -> [|mk_clos env v0; mk_clos env v1|]
470 | [|v0; v1; v2|] -> [|mk_clos env v0; mk_clos env v1; mk_clos env v2|]
471 | [|v0; v1; v2; v3|] ->
472 [|mk_clos env v0; mk_clos env v1; mk_clos env v2; mk_clos env v3|]
473 | v -> Array.Fun1.map mk_clos env v
474
475 let rec subst_constr (subst,usubst as e) c =
476 let c = Vars.map_constr_relevance (usubst_relevance e) c in
477 match [@ocaml.warning "-4"] Constr.kind c with
478 | Rel i ->
479 begin match expand_rel i subst with
480 | Inl (k, lazy v) -> Vars.lift_substituend k v
481 | Inr (m, _) -> mkRel m
482 end
483 | Const _ | Ind _ | Construct _ | Sort _ -> subst_instance_constr usubst c
484 | Case (ci, u, pms, p, iv, discr, br) ->
485 let u' = usubst_instance e u in
486 let c = if u == u' then c else mkCase (ci, u', pms, p, iv, discr, br) in
487 Constr.map_with_binders usubs_lift subst_constr e c
488 | Array (u,elems,def,ty) ->
489 let u' = usubst_instance e u in
490 let c = if u == u' then c else mkArray (u',elems,def,ty) in
491 Constr.map_with_binders usubs_lift subst_constr e c
492 | _ ->
493 Constr.map_with_binders usubs_lift subst_constr e c
494
495 let subst_context e ctx =
496 let open Context.Rel.Declaration in
497 let rec subst_context ctx = match ctx with
498 | [] -> e, []
499 | LocalAssum (na, ty) :: ctx ->
500 let e, ctx = subst_context ctx in
501 let ty = subst_constr e ty in
502 usubs_lift e, LocalAssum (na, ty) :: ctx
503 | LocalDef (na, ty, bdy) :: ctx ->
504 let e, ctx = subst_context ctx in
505 let ty = subst_constr e ty in
506 let bdy = subst_constr e bdy in
507 usubs_lift e, LocalDef (na, ty, bdy) :: ctx
508 in
509 snd @@ subst_context ctx
510
511 (** The inverse of mk_clos: move back to constr
512 Assuming [Γ ⊢ lfts : Δ] and [Δ ⊢ v],
513 we get [Γ ⊢ to_constr lfts v]
514
515 Crucially, in the case of [FLIFT]s which are the sole reason
516 why lifts are needed here, we have the following:
517 assuming [Γ ⊢ lfts : Δ, Δ'] and [Δ, Δ' ⊢ FLIFT(|Δ'|, v)] (i.e. [Δ ⊢ v])
518 we get [Γ ⊢ el_shft n lfts : Δ]; so [Γ ⊢ to_constr (el_shftn n lfts) v]
519
520 In cases like [FCLOS(t, σ)] where substitutions happen,
521 we have [Γ ⊢ lfts : Δ], [Δ ⊢ σ : Ξ] and [Ξ ⊢ v]
522 so we compute [Γ ⊢ comp_subs lfts σ : Ξ]
523 where [comp_subs lfts σ] returns a constr substitution,
524 that can be applied to [v] *)
525 let rec to_constr lfts v =
526 match v.term with
527 | FRel i -> mkRel (reloc_rel i lfts)
528 | FFlex (RelKey p) -> mkRel (reloc_rel p lfts)
529 | FFlex (VarKey x) -> mkVar x
530 | FAtom c -> exliftn lfts c
531 | FFlex (ConstKey op) -> mkConstU op
532 | FInd op -> mkIndU op
533 | FConstruct (op,args) -> mkApp (mkConstructU op, Array.Fun1.map to_constr lfts args)
534 | FCaseT (ci, u, pms, p, c, ve, env) ->
535 to_constr_case lfts ci u pms p NoInvert c ve env
536 | FCaseInvert (ci, u, pms, p, indices, c, ve, env) ->
537 let iv = CaseInvert {indices=Array.Fun1.map to_constr lfts indices} in
538 to_constr_case lfts ci u pms p iv c ve env
539 | FFix ((op,(lna,tys,bds)) as fx, e) ->
540 if is_subs_id (fst e) && is_lift_id lfts then
541 subst_instance_constr (snd e) (mkFix fx)
542 else
543 let n = Array.length bds in
544 let subs_ty = comp_subs lfts e in
545 let subs_bd = comp_subs (el_liftn n lfts) (on_fst (subs_liftn n) e) in
546 let lna = Array.Fun1.map usubst_binder subs_ty lna in
547 let tys = Array.Fun1.map subst_constr subs_ty tys in
548 let bds = Array.Fun1.map subst_constr subs_bd bds in
549 mkFix (op, (lna, tys, bds))
550 | FCoFix ((op,(lna,tys,bds)) as cfx, e) ->
551 if is_subs_id (fst e) && is_lift_id lfts then
552 subst_instance_constr (snd e) (mkCoFix cfx)
553 else
554 let n = Array.length bds in
555 let subs_ty = comp_subs lfts e in
556 let subs_bd = comp_subs (el_liftn n lfts) (on_fst (subs_liftn n) e) in
557 let lna = Array.Fun1.map usubst_binder subs_ty lna in
558 let tys = Array.Fun1.map subst_constr subs_ty tys in
559 let bds = Array.Fun1.map subst_constr subs_bd bds in
560 mkCoFix (op, (lna, tys, bds))
561 | FApp (f,ve) ->
562 mkApp (to_constr lfts f,
563 Array.Fun1.map to_constr lfts ve)
564 | FProj (p,r,c) ->
565 mkProj (p,r,to_constr lfts c)
566
567 | FLambda (len, tys, f, e) ->
568 if is_subs_id (fst e) && is_lift_id lfts then
569 subst_instance_constr (snd e) (Term.compose_lam (List.rev tys) f)
570 else
571 let subs = comp_subs lfts e in
572 let tys = List.mapi (fun i (na, c) ->
573 usubst_binder subs na, subst_constr (usubs_liftn i subs) c)
574 tys
575 in
576 let f = subst_constr (usubs_liftn len subs) f in
577 Term.compose_lam (List.rev tys) f
578 | FProd (n, t, c, e) ->
579 if is_subs_id (fst e) && is_lift_id lfts then
580 mkProd (usubst_binder e n, to_constr lfts t, subst_instance_constr (snd e) c)
581 else
582 let subs' = comp_subs lfts e in
583 mkProd (usubst_binder subs' n,
584 to_constr lfts t,
585 subst_constr (usubs_lift subs') c)
586 | FLetIn (n,b,t,f,e) ->
587 let subs = comp_subs (el_lift lfts) (usubs_lift e) in
588 mkLetIn (usubst_binder subs n,
589 to_constr lfts b,
590 to_constr lfts t,
591 subst_constr subs f)
592 | FEvar (ev, args, env, repack) ->
593 let subs = comp_subs lfts env in
594 repack (ev, List.map (fun a -> subst_constr subs a) args)
595 | FLIFT (k,a) -> to_constr (el_shft k lfts) a
596
597 | FInt i ->
598 Constr.mkInt i
599 | FFloat f ->
600 Constr.mkFloat f
601 | FString s ->
602 Constr.mkString s
603
604 | FArray (u,t,ty) ->
605 let def = to_constr lfts (Parray.default t) in
606 let t = Array.init (Parray.length_int t) (fun i ->
607 to_constr lfts (Parray.get t (Uint63.of_int i)))
608 in
609 let ty = to_constr lfts ty in
610 mkArray(u, t, def,ty)
611
612 | FCLOS (t,env) ->
613 if is_subs_id (fst env) && is_lift_id lfts then
614 subst_instance_constr (snd env) t
615 else
616 let subs = comp_subs lfts env in
617 subst_constr subs t
618
619 | FIrrelevant -> assert (!Flags.in_debugger); mkVar(Id.of_string"_IRRELEVANT_")
620 | FLOCKED -> assert (!Flags.in_debugger); mkVar(Id.of_string"_LOCKED_")
621
622 and to_constr_case lfts ci u pms (p,r) iv c ve env =
623 let subs = comp_subs lfts env in
624 let r = usubst_relevance subs r in
625 if is_subs_id (fst env) && is_lift_id lfts then
626 mkCase (ci, usubst_instance subs u, pms, (p,r), iv, to_constr lfts c, ve)
627 else
628 let f_ctx (nas, c) =
629 let nas = Array.map (usubst_binder subs) nas in
630 let c = subst_constr (usubs_liftn (Array.length nas) subs) c in
631 (nas, c)
632 in
633 mkCase (ci,
634 usubst_instance subs u,
635 Array.map (fun c -> subst_constr subs c) pms,
636 (f_ctx p,r),
637 iv,
638 to_constr lfts c,
639 Array.map f_ctx ve)
640
641 and comp_subs el (s,u') =
642 Esubst.lift_subst (fun el c -> lazy (Vars.make_substituend @@ to_constr el c)) el s, u'
643
644 (* This function defines the correspondence between constr and
645 fconstr. When we find a closure whose substitution is the identity,
646 then we directly return the constr to avoid possibly huge
647 reallocation. *)
648 let term_of_fconstr c = to_constr el_id c
649
650 let subst_context env ctx =
651 if is_subs_id (fst env) then
652 subst_instance_context (snd env) ctx
653 else
654 let subs = comp_subs el_id env in
655 subst_context subs ctx
656
657 let it_mkLambda_or_LetIn infos ctx t =
658 let l = Range.length (info_relevances infos) in
659 let open Context.Rel.Declaration in
660 match List.rev ctx with
661 | [] -> t
662 | LocalAssum (n, ty) :: ctx ->
663 let assums, ctx = List.map_until (function LocalAssum (n, ty) -> Some (n, ty) | LocalDef _ -> None) ctx in
664 let assums = (n, ty) :: assums in
665 { term = FLambda(List.length assums, assums, Term.it_mkLambda_or_LetIn (term_of_fconstr t) (List.rev ctx), (subs_id l, UVars.Instance.empty)); mark = t.mark }
666 | LocalDef _ :: _ ->
667 mk_clos (subs_id l, UVars.Instance.empty) (Term.it_mkLambda_or_LetIn (term_of_fconstr t) ctx)
668
669 (* fstrong applies unfreeze_fun recursively on the (freeze) term and
670 * yields a term. Assumes that the unfreeze_fun never returns a
671 * FCLOS term.
672 let rec fstrong unfreeze_fun lfts v =
673 to_constr (fstrong unfreeze_fun) lfts (unfreeze_fun v)
674 *)
675
676 let mkFApp h args =
677 if CArray.is_empty args then h
678 else match[@warning "-4"] h.term with
679 | FConstruct (c, args0) ->
680 let args = if CArray.is_empty args0 then args else Array.append args0 args in
681 {mark=Cstr; term=FConstruct(c, args)}
682 | _ ->
683 (* don't bother collapsing FApp nodes *)
684 {mark=neutr h.mark; term=FApp(h,args)}
685
686 let rec zip m stk =
687 match stk with
688 | [] -> m
689 | Zapp args :: s -> zip (mkFApp m args) s
690 | ZcaseT(ci, u, pms, p, br, e)::s ->
691 let t = FCaseT(ci, u, pms, p, m, br, e) in
692 let mark = (neutr m.mark) in
693 zip {mark; term=t} s
694 | Zproj (p,r) :: s ->
695 let mark = (neutr m.mark) in
696 zip {mark; term=FProj(Projection.make p true,r,m)} s
697 | Zfix(fx,par)::s ->
698 zip fx (par @ append_stack [|m|] s)
699 | Zshift(n)::s ->
700 zip (lift_fconstr n m) s
701 | Zupdate(rf)::s ->
702 (** The stack contains [Zupdate] marks only if in sharing mode *)
703 let () = update rf m.mark m.term in
704 zip rf s
705 | Zprimitive(_op,c,rargs,kargs)::s ->
706 let args = List.rev_append rargs (m::List.map snd kargs) in
707 let f = {mark = Red; term = FFlex (ConstKey c)} in
708 (* don't need to mkFApp because not a constructor *)
709 zip {mark=(neutr m.mark); term = FApp (f, Array.of_list args)} s
710
711 let fapp_stack (m,stk) = zip m stk
712
713 let term_of_process c stk = term_of_fconstr (zip c stk)
714
715 (*********************************************************************)
716
717 (* The assertions in the functions below are granted because they are
718 called only when m is a constructor, a cofix
719 (strip_update_shift_app), a fix (get_nth_arg) or an abstraction
720 (strip_update_shift, through get_arg). *)
721
722 (* when we don't need to return the depth & initial part of the stack,
723 with only the rebuilt term sufficing
724 (typically head is a fconstruct so we return a fconstruct with added args) *)
725 let strip_update_shift_absorb_app head stk =
726 let rec strip_rec h = function
727 | Zshift(k) :: s ->
728 strip_rec (lift_fconstr k h) s
729 | (Zapp args :: s) ->
730 strip_rec (mkFApp h args) s
731 | Zupdate(m)::s ->
732 (** The stack contains [Zupdate] marks only if in sharing mode *)
733 let () = update m h.mark h.term in
734 strip_rec m s
735 | ((ZcaseT _ | Zproj _ | Zfix _ | Zprimitive _) :: _ | []) as stk ->
736 (* depth and rstk only matter for cofix *)
737 (h, stk)
738 in
739 strip_rec head stk
740
741 (* optimised for the case where there are no shifts... *)
742 let strip_update_shift_app_red head stk =
743 let rec strip_rec rstk h depth = function
744 | Zshift(k) as e :: s ->
745 strip_rec (e::rstk) (lift_fconstr k h) (depth+k) s
746 | (Zapp args :: s) ->
747 strip_rec (Zapp args :: rstk) (mkFApp h args) depth s
748 | Zupdate(m)::s ->
749 (** The stack contains [Zupdate] marks only if in sharing mode *)
750 let () = update m h.mark h.term in
751 strip_rec rstk m depth s
752 | ((ZcaseT _ | Zproj _ | Zfix _ | Zprimitive _) :: _ | []) as stk ->
753 (* depth and rstk only matter for cofix *)
754 (depth,h,List.rev rstk, stk)
755 in
756 strip_rec [] head 0 stk
757
758 let strip_update_shift_app head stack =
759 assert (not (is_red head.mark));
760 strip_update_shift_app_red head stack
761
762 let get_nth_arg head n stk =
763 assert (not (is_red head.mark));
764 let rec strip_rec rstk h n = function
765 | Zshift(k) as e :: s ->
766 strip_rec (e::rstk) (lift_fconstr k h) n s
767 | Zapp args::s' ->
768 let q = Array.length args in
769 if n >= q
770 then
771 strip_rec (Zapp args::rstk) (mkFApp h args) (n-q) s'
772 else
773 let bef = Array.sub args 0 n in
774 let aft = Array.sub args (n+1) (q-n-1) in
775 let stk' =
776 List.rev (if Int.equal n 0 then rstk else (Zapp bef :: rstk)) in
777 (Some (stk', args.(n)), append_stack aft s')
778 | Zupdate(m)::s ->
779 (** The stack contains [Zupdate] mark only if in sharing mode *)
780 let () = update m h.mark h.term in
781 strip_rec rstk m n s
782 | ((ZcaseT _ | Zproj _ | Zfix _ | Zprimitive _) :: _ | []) as s -> (None, List.rev rstk @ s) in
783 strip_rec [] head n stk
784
785 let usubs_cons x (s,u) = subs_cons x s, u
786
787 let rec subs_consn v i n s =
788 if Int.equal i n then s
789 else subs_consn v (i + 1) n (subs_cons v.(i) s)
790
791 let usubs_consn v i n s = on_fst (subs_consn v i n) s
792
793 let usubs_consv v s =
794 usubs_consn v 0 (Array.length v) s
795
796 (* Beta reduction: look for an applied argument in the stack.
797 Since the encountered update marks are removed, h must be a whnf *)
798 let rec get_args n tys f e = function
799 | Zupdate r :: s ->
800 (** The stack contains [Zupdate] mark only if in sharing mode *)
801 let () = update r Cstr (FLambda(n,tys,f,e)) in
802 get_args n tys f e s
803 | Zshift k :: s ->
804 get_args n tys f (usubs_shft (k,e)) s
805 | Zapp l :: s ->
806 let na = Array.length l in
807 if n == na then (Inl (usubs_consn l 0 na e), s)
808 else if n < na then (* more arguments *)
809 let eargs = Array.sub l n (na-n) in
810 (Inl (usubs_consn l 0 n e), Zapp eargs :: s)
811 else (* more lambdas *)
812 let etys = List.skipn na tys in
813 get_args (n-na) etys f (usubs_consn l 0 na e) s
814 | ((ZcaseT _ | Zproj _ | Zfix _ | Zprimitive _) :: _ | []) as stk ->
815 (Inr {mark=Cstr; term=FLambda(n,tys,f,e)}, stk)
816
817 (* Eta expansion: add a reference to implicit surrounding lambda at end of stack *)
818 let rec eta_expand_stack info na = function
819 | (Zapp _ | Zfix _ | ZcaseT _ | Zproj _
820 | Zshift _ | Zupdate _ | Zprimitive _ as e) :: s ->
821 e :: eta_expand_stack info na s
822 | [] ->
823 let arg =
824 if is_irrelevant info na.binder_relevance then mk_irrelevant
825 else {mark = Ntrl; term = FRel 1}
826 in
827 [Zshift 1; Zapp [|arg|]]
828
829 (* Get the arguments of a native operator *)
830 let rec skip_native_args rargs nargs =
831 match nargs with
832 | (kd, a) :: nargs' ->
833 if kd = CPrimitives.Kwhnf then rargs, nargs
834 else skip_native_args (a::rargs) nargs'
835 | [] -> rargs, []
836
837 let get_native_args op c stk =
838 let kargs = CPrimitives.kind op in
839 let rec get_args rnargs kargs args =
840 match kargs, args with
841 | kd::kargs, a::args -> get_args ((kd,a)::rnargs) kargs args
842 | _, _ -> rnargs, kargs, args in
843 let rec strip_rec rnargs h depth kargs = function
844 | Zshift k :: s ->
845 strip_rec (List.map (fun (kd,f) -> kd,lift_fconstr k f) rnargs)
846 (lift_fconstr k h) (depth+k) kargs s
847 | Zapp args :: s' ->
848 begin match get_args rnargs kargs (Array.to_list args) with
849 | rnargs, [], [] ->
850 (skip_native_args [] (List.rev rnargs), s')
851 | rnargs, [], eargs ->
852 (skip_native_args [] (List.rev rnargs),
853 Zapp (Array.of_list eargs) :: s')
854 | rnargs, kargs, _ ->
855 (* head of h is not constructor -> no need to mkFApp *)
856 strip_rec rnargs {mark = h.mark;term=FApp(h, args)} depth kargs s'
857 end
858 | Zupdate(m) :: s ->
859 let () = update m h.mark h.term in
860 strip_rec rnargs m depth kargs s
861 | (Zprimitive _ | ZcaseT _ | Zproj _ | Zfix _) :: _ | [] -> assert false
862 in strip_rec [] {mark = Red; term = FFlex(ConstKey c)} 0 kargs stk
863
864 let get_native_args1 op c stk =
865 match get_native_args op c stk with
866 | ((rargs, (kd,a):: nargs), stk) ->
867 assert (kd = CPrimitives.Kwhnf);
868 (rargs, a, nargs, stk)
869 | _ -> assert false
870
871 let check_native_args op stk =
872 let nargs = CPrimitives.arity op in
873 let rargs = stack_args_size stk in
874 nargs <= rargs
875
876
877 let try_drop_parameters n m = match[@warning "-4"] m.term with
878 | FConstruct (_, args) ->
879 let q = Array.length args in
880 if n > q then raise Not_found
881 else if q = 0 then [||]
882 else Array.sub args n (q - n)
883 | _ -> assert false
884
885 let drop_parameters n m =
886 try try_drop_parameters n m
887 with Not_found ->
888 (* we know that n < stack_args_size(argstk) (if well-typed term) *)
889 anomaly (Pp.str "ill-typed term: found a match on a partially applied constructor.")
890
891 let inductive_subst mib u pms =
892 let rec mk_pms i ctx = match ctx with
893 | [] -> subs_id 0
894 | RelDecl.LocalAssum _ :: ctx ->
895 let subs = mk_pms (i - 1) ctx in
896 subs_cons pms.(i) subs
897 | RelDecl.LocalDef (_, c, _) :: ctx ->
898 let subs = mk_pms i ctx in
899 subs_cons (mk_clos (subs,u) c) subs
900 in
901 mk_pms (Array.length pms - 1) mib.mind_params_ctxt, u
902
903 (* Iota-reduction: feed the arguments of the constructor to the branch *)
904 let get_branch infos ci pms cterm br e =
905 let ((ind, c), u) = match[@warning "-4"] cterm.term with
906 | FConstruct (c, _) -> c
907 | _ -> assert false
908 in
909 let i = c - 1 in
910 let args = drop_parameters ci.ci_npar cterm in
911 let (_nas, br) = br.(i) in
912 if Int.equal ci.ci_cstr_ndecls.(i) ci.ci_cstr_nargs.(i) then
913 (* No let-bindings in the constructor, we don't have to fetch the
914 environment to know the value of the branch. *)
915 let e = usubs_consv args e in
916 (br, e)
917 else
918 (* The constructor contains let-bindings, but they are not physically
919 present in the match, so we fetch them in the environment. *)
920 let env = info_env infos in
921 let mib = Environ.lookup_mind (fst ind) env in
922 let mip = mib.mind_packets.(snd ind) in
923 let (ctx, _) = mip.mind_nf_lc.(i) in
924 let ctx, _ = List.chop mip.mind_consnrealdecls.(i) ctx in
925 let ind_subst = inductive_subst mib u (Array.map (mk_clos e) pms) in
926 let rec push i e = function
927 | [] -> []
928 | RelDecl.LocalAssum _ :: ctx ->
929 let ans = push (pred i) e ctx in
930 args.(i) :: ans
931 | RelDecl.LocalDef (_, b, _) :: ctx ->
932 let ans = push i e ctx in
933 let b = subst_instance_constr u b in
934 let s = Array.rev_of_list ans in
935 let e = usubs_consv s ind_subst in
936 let v = mk_clos e b in
937 v :: ans
938 in
939 let ext = push (Array.length args - 1) [] ctx in
940 (br, usubs_consv (Array.rev_of_list ext) e)
941
942 (** [eta_expand_ind_stack env ind c s t] computes stacks corresponding
943 to the conversion of the eta expansion of t, considered as an inhabitant
944 of ind, and the Constructor c of this inductive type applied to arguments
945 s.
946 @assumes [t] is an irreducible term, and not a constructor. [ind] is the inductive
947 of the constructor term [c]
948 @raise Not_found if the inductive is not a primitive record, or if the
949 constructor is partially applied.
950 *)
951 let eta_expand_ind_stack env (ind,u) m (f, s') =
952 let open Declarations in
953 let mib = lookup_mind (fst ind) env in
954 (* disallow eta-exp for non-primitive records *)
955 if not (mib.mind_finite == BiFinite) then raise Not_found;
956 match Declareops.inductive_make_projections ind mib with
957 | Some (projs, has_eta) ->
958 let () =
959 match has_eta with
960 | NoEta -> raise Not_found
961 | AlwaysEta -> ()
962 in
963 (* (Construct, pars1 .. parsm :: arg1...argn :: []) ~= (f, s') ->
964 arg1..argn ~= (proj1 t...projn t) where t = zip (f,s') *)
965 let pars = mib.Declarations.mind_nparams in
966 let right = fapp_stack (f, s') in
967 (** Try to drop the params, might fail on partially applied constructors. *)
968 let argss = try_drop_parameters pars m in
969 let () = if not @@ Int.equal (Array.length projs) (Array.length argss)
970 then raise Not_found (* partially applied constructor (missing non-param arguments) *)
971 in
972 let hstack = Array.map (fun (p,r) ->
973 { mark = Red; (* right can't be a constructor though *)
974 term = FProj (Projection.make p true, UVars.subst_instance_relevance u r, right) })
975 projs
976 in
977 [Zapp argss], [Zapp hstack]
978 | None -> raise Not_found (* disallow eta-exp for non-primitive records *)
979
980 (* Iota reduction: expansion of a fixpoint.
981 * Given a fixpoint and a substitution, returns the corresponding
982 * fixpoint body, and the substitution in which it should be
983 * evaluated: its first variables are the fixpoint bodies
984 *
985 * FCLOS(fix Fi {F0 := T0 .. Fn-1 := Tn-1}, S)
986 * -> (S. FCLOS(F0,S) . ... . FCLOS(Fn-1,S), Ti)
987 *)
988 (* does not deal with FLIFT *)
989 let contract_fix_vect fix =
990 let (thisbody, make_body, env, nfix) =
991 match [@ocaml.warning "-4"] fix with
992 | FFix (((reci,i),(_,_,bds as rdcl)),env) ->
993 (bds.(i),
994 (fun j -> { mark = Cstr;
995 term = FFix (((reci,j),rdcl),env) }),
996 env, Array.length bds)
997 | FCoFix ((i,(_,_,bds as rdcl)),env) ->
998 (bds.(i),
999 (fun j -> { mark = Cstr;
1000 term = FCoFix ((j,rdcl),env) }),
1001 env, Array.length bds)
1002 | _ -> assert false
1003 in
1004 let rec mk_subs env i =
1005 if Int.equal i nfix then env
1006 else mk_subs (subs_cons (make_body i) env) (i + 1)
1007 in
1008 (on_fst (fun env -> mk_subs env 0) env, thisbody)
1009
1010 let unfold_projection info p r =
1011 if red_projection info.i_flags p
1012 then
1013 Some (Zproj (Projection.repr p, r))
1014 else None
1015
1016 (************************************************************************)
1017 (* Reduction of Native operators *)
1018
1019 open Primred
1020
1021 module FNativeEntries =
1022 struct
1023 type elem = fconstr
1024 type args = fconstr array
1025 type evd = unit
1026 type uinstance = UVars.Instance.t
1027
1028 let mk_construct c =
1029 (* All constructors used in primitive functions are relevant *)
1030 { mark = Cstr; term = FConstruct (UVars.in_punivs c, [||]) }
1031
1032 let get = Array.get
1033
1034 let get_int () e =
1035 match [@ocaml.warning "-4"] e.term with
1036 | FInt i -> i
1037 | _ -> assert false
1038
1039 let get_float () e =
1040 match [@ocaml.warning "-4"] e.term with
1041 | FFloat f -> f
1042 | _ -> assert false
1043
1044 let get_string () e =
1045 match [@ocaml.warning "-4"] e.term with
1046 | FString s -> s
1047 | _ -> assert false
1048
1049 let get_parray () e =
1050 match [@ocaml.warning "-4"] e.term with
1051 | FArray (_u,t,_ty) -> t
1052 | _ -> assert false
1053
1054 let dummy = {mark = Ntrl; term = FRel 0}
1055
1056 let current_retro = ref Retroknowledge.empty
1057 let defined_int = ref false
1058 let fint = ref dummy
1059
1060 let init_int retro =
1061 match retro.Retroknowledge.retro_int63 with
1062 | Some c ->
1063 defined_int := true;
1064 fint := { mark = Ntrl; term = FFlex (ConstKey (UVars.in_punivs c)) }
1065 | None -> defined_int := false
1066
1067 let defined_float = ref false
1068 let ffloat = ref dummy
1069
1070 let init_float retro =
1071 match retro.Retroknowledge.retro_float64 with
1072 | Some c ->
1073 defined_float := true;
1074 ffloat := { mark = Ntrl; term = FFlex (ConstKey (UVars.in_punivs c)) }
1075 | None -> defined_float := false
1076
1077 let defined_string = ref false
1078 let fstring = ref dummy
1079
1080 let init_string retro =
1081 match retro.Retroknowledge.retro_string with
1082 | Some c ->
1083 defined_string := true;
1084 fstring := { mark = Ntrl; term = FFlex (ConstKey (UVars.in_punivs c)) }
1085 | None -> defined_string := false
1086
1087 let defined_bool = ref false
1088 let ftrue = ref dummy
1089 let ffalse = ref dummy
1090
1091 let init_bool retro =
1092 match retro.Retroknowledge.retro_bool with
1093 | Some (ct,cf) ->
1094 defined_bool := true;
1095 ftrue := mk_construct ct;
1096 ffalse := mk_construct cf;
1097 | None -> defined_bool :=false
1098
1099 let defined_carry = ref false
1100 let fC0 = ref dummy
1101 let fC1 = ref dummy
1102
1103 let init_carry retro =
1104 match retro.Retroknowledge.retro_carry with
1105 | Some(c0,c1) ->
1106 defined_carry := true;
1107 fC0 := mk_construct c0;
1108 fC1 := mk_construct c1;
1109 | None -> defined_carry := false
1110
1111 let defined_pair = ref false
1112 let fPair = ref dummy
1113
1114 let init_pair retro =
1115 match retro.Retroknowledge.retro_pair with
1116 | Some c ->
1117 defined_pair := true;
1118 fPair := mk_construct c;
1119 | None -> defined_pair := false
1120
1121 let defined_cmp = ref false
1122 let fEq = ref dummy
1123 let fLt = ref dummy
1124 let fGt = ref dummy
1125 let fcmp = ref dummy
1126
1127 let init_cmp retro =
1128 match retro.Retroknowledge.retro_cmp with
1129 | Some (cEq, cLt, cGt) ->
1130 defined_cmp := true;
1131 fEq := mk_construct cEq;
1132 fLt := mk_construct cLt;
1133 fGt := mk_construct cGt;
1134 let (icmp, _) = cEq in
1135 fcmp := { mark = Ntrl; term = FInd (UVars.in_punivs icmp) }
1136 | None -> defined_cmp := false
1137
1138 let defined_f_cmp = ref false
1139 let fFEq = ref dummy
1140 let fFLt = ref dummy
1141 let fFGt = ref dummy
1142 let fFNotComparable = ref dummy
1143
1144 let init_f_cmp retro =
1145 match retro.Retroknowledge.retro_f_cmp with
1146 | Some (cFEq, cFLt, cFGt, cFNotComparable) ->
1147 defined_f_cmp := true;
1148 fFEq := mk_construct cFEq;
1149 fFLt := mk_construct cFLt;
1150 fFGt := mk_construct cFGt;
1151 fFNotComparable := mk_construct cFNotComparable;
1152 | None -> defined_f_cmp := false
1153
1154 let defined_f_class = ref false
1155 let fPNormal = ref dummy
1156 let fNNormal = ref dummy
1157 let fPSubn = ref dummy
1158 let fNSubn = ref dummy
1159 let fPZero = ref dummy
1160 let fNZero = ref dummy
1161 let fPInf = ref dummy
1162 let fNInf = ref dummy
1163 let fNaN = ref dummy
1164
1165 let init_f_class retro =
1166 match retro.Retroknowledge.retro_f_class with
1167 | Some (cPNormal, cNNormal, cPSubn, cNSubn, cPZero, cNZero,
1168 cPInf, cNInf, cNaN) ->
1169 defined_f_class := true;
1170 fPNormal := mk_construct cPNormal;
1171 fNNormal := mk_construct cNNormal;
1172 fPSubn := mk_construct cPSubn;
1173 fNSubn := mk_construct cNSubn;
1174 fPZero := mk_construct cPZero;
1175 fNZero := mk_construct cNZero;
1176 fPInf := mk_construct cPInf;
1177 fNInf := mk_construct cNInf;
1178 fNaN := mk_construct cNaN;
1179 | None -> defined_f_class := false
1180
1181 let defined_array = ref false
1182
1183 let init_array retro =
1184 defined_array := Option.has_some retro.Retroknowledge.retro_array
1185
1186 let init env =
1187 current_retro := Environ.retroknowledge env;
1188 init_int !current_retro;
1189 init_float !current_retro;
1190 init_string !current_retro;
1191 init_bool !current_retro;
1192 init_carry !current_retro;
1193 init_pair !current_retro;
1194 init_cmp !current_retro;
1195 init_f_cmp !current_retro;
1196 init_f_class !current_retro;
1197 init_array !current_retro
1198
1199 let check_env env =
1200 if not (!current_retro == Environ.retroknowledge env) then init env
1201
1202 let check_int env =
1203 check_env env;
1204 assert (!defined_int)
1205
1206 let check_float env =
1207 check_env env;
1208 assert (!defined_float)
1209
1210 let check_string env =
1211 check_env env;
1212 assert (!defined_string)
1213
1214 let check_bool env =
1215 check_env env;
1216 assert (!defined_bool)
1217
1218 let check_carry env =
1219 check_env env;
1220 assert (!defined_carry && !defined_int)
1221
1222 let check_pair env =
1223 check_env env;
1224 assert (!defined_pair && !defined_int)
1225
1226 let check_cmp env =
1227 check_env env;
1228 assert (!defined_cmp)
1229
1230 let check_f_cmp env =
1231 check_env env;
1232 assert (!defined_f_cmp)
1233
1234 let check_f_class env =
1235 check_env env;
1236 assert (!defined_f_class)
1237
1238 let check_array env =
1239 check_env env;
1240 assert (!defined_array)
1241
1242 let mkInt env i =
1243 check_int env;
1244 { mark = Cstr; term = FInt i }
1245
1246 let mkFloat env f =
1247 check_float env;
1248 { mark = Cstr; term = FFloat f }
1249
1250 let mkString env s =
1251 check_string env;
1252 { mark = Cstr; term = FString s }
1253
1254 let mkBool env b =
1255 check_bool env;
1256 if b then !ftrue else !ffalse
1257
1258 let mkCarry env b e =
1259 check_carry env;
1260 mkFApp (if b then !fC1 else !fC0) [|!fint;e|]
1261
1262 let mkIntPair env e1 e2 =
1263 check_pair env;
1264 mkFApp !fPair [|!fint;!fint;e1;e2|]
1265
1266 let mkFloatIntPair env f i =
1267 check_pair env;
1268 check_float env;
1269 mkFApp !fPair [|!ffloat;!fint;f;i|]
1270
1271 let mkLt env =
1272 check_cmp env;
1273 !fLt
1274
1275 let mkEq env =
1276 check_cmp env;
1277 !fEq
1278
1279 let mkGt env =
1280 check_cmp env;
1281 !fGt
1282
1283 let mkFLt env =
1284 check_f_cmp env;
1285 !fFLt
1286
1287 let mkFEq env =
1288 check_f_cmp env;
1289 !fFEq
1290
1291 let mkFGt env =
1292 check_f_cmp env;
1293 !fFGt
1294
1295 let mkFNotComparable env =
1296 check_f_cmp env;
1297 !fFNotComparable
1298
1299 let mkPNormal env =
1300 check_f_class env;
1301 !fPNormal
1302
1303 let mkNNormal env =
1304 check_f_class env;
1305 !fNNormal
1306
1307 let mkPSubn env =
1308 check_f_class env;
1309 !fPSubn
1310
1311 let mkNSubn env =
1312 check_f_class env;
1313 !fNSubn
1314
1315 let mkPZero env =
1316 check_f_class env;
1317 !fPZero
1318
1319 let mkNZero env =
1320 check_f_class env;
1321 !fNZero
1322
1323 let mkPInf env =
1324 check_f_class env;
1325 !fPInf
1326
1327 let mkNInf env =
1328 check_f_class env;
1329 !fNInf
1330
1331 let mkNaN env =
1332 check_f_class env;
1333 !fNaN
1334
1335 let mkArray env u t ty =
1336 check_array env;
1337 { mark = Cstr; term = FArray (u,t,ty)}
1338
1339 end
1340
1341 module FredNative = RedNative(FNativeEntries)
1342
1343 let rec skip_irrelevant_stack info stk = match stk with
1344 | [] -> []
1345 | (Zshift _ | Zapp _) :: s -> skip_irrelevant_stack info s
1346 | (Zfix _ | Zproj _) :: s ->
1347 (* Typing rules ensure that fix / proj over SProp is irrelevant *)
1348 skip_irrelevant_stack info s
1349 | ZcaseT (_, _, _, (_,r), _, e) :: s ->
1350 let r = usubst_relevance e r in
1351 if is_irrelevant info r then skip_irrelevant_stack info s
1352 else stk
1353 | Zprimitive _ :: _ -> assert false (* no irrelevant primitives so far *)
1354 | Zupdate m :: s ->
1355 (** The stack contains [Zupdate] marks only if in sharing mode *)
1356 let () = update m mk_irrelevant.mark mk_irrelevant.term in
1357 skip_irrelevant_stack info s
1358
1359 let is_irrelevant_constructor infos ((ind,_),u) =
1360 is_irrelevant infos @@ UVars.subst_instance_relevance u @@ ind_relevance ind (info_env infos)
1361
1362 (*********************************************************************)
1363 (* A machine that inspects the head of a term until it finds an
1364 atom or a subterm that may produce a redex (abstraction,
1365 constructor, cofix, letin, constant), or a neutral term (product,
1366 inductive) *)
1367 let rec knh info m stk =
1368 match m.term with
1369 | FLIFT(k,a) -> knh info a (zshift k stk)
1370 | FCLOS(t,e) -> knht info e t (zupdate info m stk)
1371 | FLOCKED -> assert false
1372 | FApp(a,b) -> knh info a (append_stack b (zupdate info m stk))
1373 | FCaseT(ci,u,pms,(_,r as p),t,br,e) ->
1374 let r' = usubst_relevance e r in
1375 if is_irrelevant info r' then
1376 (mk_irrelevant, skip_irrelevant_stack info stk)
1377 else
1378 knh info t (ZcaseT(ci,u,pms,p,br,e)::zupdate info m stk)
1379 | FFix (((ri, n), (lna, _, _)), e) ->
1380 if is_irrelevant info (usubst_relevance e (lna.(n)).binder_relevance) then
1381 (mk_irrelevant, skip_irrelevant_stack info stk)
1382 else
1383 (match get_nth_arg m ri.(n) stk with
1384 (Some(pars,arg),stk') -> knh info arg (Zfix(m,pars)::stk')
1385 | (None, stk') -> (m,stk'))
1386 | FProj (p,r,c) ->
1387 if is_irrelevant info r then
1388 (mk_irrelevant, skip_irrelevant_stack info stk)
1389 else
1390 (match unfold_projection info p r with
1391 | None -> (m, stk)
1392 | Some s -> knh info c (s :: zupdate info m stk))
1393 | FConstruct _ -> strip_update_shift_absorb_app m stk
1394
1395 (* cases where knh stops *)
1396 | (FFlex _|FLetIn _|FEvar _|FCaseInvert _|FIrrelevant|
1397 FCoFix _|FLambda _|FRel _|FAtom _|FInd _|FProd _|FInt _|FFloat _|
1398 FString _|FArray _) ->
1399 (m, stk)
1400
1401 (* The same for pure terms *)
1402 and knht info e t stk =
1403 match kind t with
1404 | App(a,b) ->
1405 knht info e a (append_stack (mk_clos_vect e b) stk)
1406 | Case(ci,u,pms,(_,r as p),NoInvert,t,br) ->
1407 if is_irrelevant info (usubst_relevance e r) then
1408 (mk_irrelevant, skip_irrelevant_stack info stk)
1409 else
1410 knht info e t (ZcaseT(ci, u, pms, p, br, e)::stk)
1411 | Case(ci,u,pms,(_,r as p),CaseInvert{indices},t,br) ->
1412 if is_irrelevant info (usubst_relevance e r) then
1413 (mk_irrelevant, skip_irrelevant_stack info stk)
1414 else
1415 let term = FCaseInvert (ci, u, pms, p, (Array.map (mk_clos e) indices), mk_clos e t, br, e) in
1416 { mark = Red; term }, stk
1417 | Fix (((_, n), (lna, _, _)) as fx) ->
1418 if is_irrelevant info (usubst_relevance e (lna.(n)).binder_relevance) then
1419 (mk_irrelevant, skip_irrelevant_stack info stk)
1420 else
1421 knh info { mark = Cstr; term = FFix (fx, e) } stk
1422 | Cast(a,_,_) -> knht info e a stk
1423 | Rel n -> knh info (clos_rel (fst e) n) stk
1424 | Proj (p, r, c) ->
1425 let r = usubst_relevance e r in
1426 if is_irrelevant info r then
1427 (mk_irrelevant, skip_irrelevant_stack info stk)
1428 else begin match unfold_projection info p r with
1429 | None -> ({ mark = Red; term = FProj (p, r, mk_clos e c) }, stk)
1430 | Some s -> knht info e c (s :: stk)
1431 end
1432 | Construct _ -> knh info (mk_clos e t) stk
1433 | (Ind _|Const _|Var _|Meta _ | Sort _ | Int _|Float _|String _) -> (mk_clos e t, stk)
1434 | CoFix cfx ->
1435 { mark = Cstr; term = FCoFix (cfx,e) }, stk
1436 | Lambda _ -> { mark = Cstr ; term = mk_lambda e t }, stk
1437 | Prod (n, t, c) ->
1438 { mark = Ntrl; term = FProd (n, mk_clos e t, c, e) }, stk
1439 | LetIn (n,b,t,c) ->
1440 { mark = Red; term = FLetIn (n, mk_clos e b, mk_clos e t, c, e) }, stk
1441 | Evar ev ->
1442 begin match info.i_cache.i_sigma.evar_expand ev with
1443 | EvarDefined c -> knht info e c stk
1444 | EvarUndefined (evk, args) ->
1445 assert (UVars.Instance.is_empty (snd e));
1446 if info.i_cache.i_mode = Conversion && info.i_cache.i_sigma.evar_irrelevant ev then
1447 (mk_irrelevant, skip_irrelevant_stack info stk)
1448 else
1449 let repack = info.i_cache.i_sigma.evar_repack in
1450 { mark = Ntrl; term = FEvar (evk, args, e, repack) }, stk
1451 end
1452 | Array(u,t,def,ty) ->
1453 let u = usubst_instance e u in
1454 let len = Array.length t in
1455 let ty = mk_clos e ty in
1456 let t = Parray.init (Uint63.of_int len) (fun i -> mk_clos e t.(i)) (mk_clos e def) in
1457 let term = FArray (u,t,ty) in
1458 knh info { mark = Cstr; term } stk
1459
1460 (************************************************************************)
1461
1462 let conv : (clos_infos -> clos_tab -> fconstr -> fconstr -> bool) ref
1463 = ref (fun _ _ _ _ -> (assert false : bool))
1464 let set_conv f = conv := f
1465
1466 type ('a, 'b) reduction = {
1467 red_ret : clos_infos -> Table.t -> pat_state:'b -> ?failed:bool -> (fconstr * stack) -> 'a;
1468 red_kni : clos_infos -> Table.t -> pat_state:'b -> fconstr -> stack -> 'a;
1469 red_knit : clos_infos -> Table.t -> pat_state:'b -> (fconstr Esubst.subs * UVars.Instance.t) -> Constr.t -> stack -> 'a;
1470 }
1471
1472 type (_, _) escape =
1473 | No: ('i, 'i) escape
1474 | Yes: ('a, 'a option) escape
1475
1476 module RedPattern :
1477 sig
1478
1479 type ('constr, 'stack, 'context) resume_state
1480
1481 type ('constr, 'stack, 'context, _) depth =
1482 | Nil: ('constr * 'stack, 'ret) escape -> ('constr, 'stack, 'context, 'ret) depth
1483 | Cons: ('constr, 'stack, 'context) resume_state * ('constr, 'stack, 'context, 'ret) depth -> ('constr, 'stack, 'context, 'ret) depth
1484
1485 type 'a patstate = (fconstr, stack, rel_context, 'a) depth
1486
1487 val match_symbol : ('a, 'a patstate) reduction -> clos_infos -> Table.t ->
1488 pat_state:(fconstr, stack, rel_context, 'a) depth -> table_key -> UVars.Instance.t * bool * machine_rewrite_rule list -> stack -> 'a
1489
1490 val match_head : ('a, 'a patstate) reduction -> clos_infos -> Table.t ->
1491 pat_state:(fconstr, stack, rel_context, 'a) depth -> (fconstr, stack, rel_context) resume_state -> fconstr -> stack -> 'a
1492
1493 end =
1494 struct
1495
1496 type 'constr partial_subst = {
1497 subst: ('constr, Sorts.Quality.t, Univ.Level.t) Partial_subst.t;
1498 rhs: constr;
1499 }
1500
1501 type 'constr subst_status = Dead | Live of 'constr partial_subst
1502
1503 type 'a status =
1504 | Check of 'a
1505 | Ignore
1506
1507 module Status = struct
1508 let split_array n = function
1509 | Check a when Array.length a <> n -> invalid_arg "Status.split_array"
1510 | Check a -> Array.init n (fun i -> Check (Array.unsafe_get a i))
1511 | Ignore as p -> Array.make n p
1512
1513 let fold_left f a = function Check b -> f a b | Ignore -> a
1514 end
1515
1516 type ('a, 'b) next =
1517 | Continue of 'a
1518 | Return of 'b
1519
1520 type ('constr, 'stack, 'context) state =
1521 | LocStart of { elims: pattern_elimination list status array; context: 'context; head: 'constr; stack: 'stack; next: ('constr, 'stack, 'context) state_next }
1522 | LocArg of { patterns: pattern_argument status array; context: 'context; arg: 'constr; next: ('constr, 'stack, 'context) state }
1523
1524 and ('constr, 'stack, 'context) state_next = (('constr, 'stack, 'context) state, bool * 'constr * 'stack) next
1525
1526 type ('constr, 'stack, 'context) resume_state =
1527 { states: 'constr subst_status array; context: 'context; patterns: head_elimination status array; next: ('constr, 'stack, 'context) state }
1528
1529 type ('constr, 'stack, 'context, _) depth =
1530 | Nil: ('constr * 'stack, 'ret) escape -> ('constr, 'stack, 'context, 'ret) depth
1531 | Cons: ('constr, 'stack, 'context) resume_state * ('constr, 'stack, 'context, 'ret) depth -> ('constr, 'stack, 'context, 'ret) depth
1532
1533 type 'a patstate = (fconstr, stack, rel_context, 'a) depth
1534
1535 let extract_or_kill filter a status =
1536 let step elim status =
1537 match elim, status with
1538 | Ignore, s -> s
1539 | _, Dead -> Dead
1540 | Check e, Live s -> match filter (e, s) with
1541 | None -> Dead
1542 | Some s -> Live s
1543 in
1544 Array.map2 step a status
1545
1546 let extract_or_kill2 filter a status =
1547 let step elim status =
1548 match elim, status with
1549 | Ignore, s -> Ignore, s
1550 | _, Dead -> Ignore, Dead
1551 | Check e, Live s -> match filter (e, s) with
1552 | None -> Ignore, Dead
1553 | Some (p, s) -> Check p, Live s
1554 in
1555 Array.split @@ Array.map2 step a status
1556
1557 let extract_or_kill3 filter a status =
1558 let step elim status =
1559 match elim, status with
1560 | Ignore, s -> Ignore, Ignore, s
1561 | _, Dead -> Ignore, Ignore, Dead
1562 | Check e, Live s -> match filter (e, s) with
1563 | None -> Ignore, Ignore, Dead
1564 | Some (p1, p2, s) -> Check p1, Check p2, Live s
1565 in
1566 Array.split3 @@ Array.map2 step a status
1567
1568 let extract_or_kill4 filter a status =
1569 let step elim status =
1570 match elim, status with
1571 | Ignore, s -> Ignore, Ignore, Ignore, s
1572 | _, Dead -> Ignore, Ignore, Ignore, Dead
1573 | Check e, Live s -> match filter (e, s) with
1574 | None -> Ignore, Ignore, Ignore, Dead
1575 | Some (p1, p2, p3, s) -> Check p1, Check p2, Check p3, Live s
1576 in
1577 Array.split4 @@ Array.map2 step a status
1578
1579 let rec match_main : type a. (a, a patstate) reduction -> _ -> _ -> pat_state:(fconstr, stack, _, a) depth -> _ -> _ -> a =
1580 fun red info tab ~pat_state states loc ->
1581 if Array.for_all (function Dead -> true | Live _ -> false) states then match_kill red info tab ~pat_state loc else
1582 match [@ocaml.warning "-4"] loc with
1583 | LocStart { elims; context; head; stack; next = Return _ as next } ->
1584 begin match Array.find2_map (fun state elim -> match state, elim with Live s, Check [] -> Some s | _ -> None) states elims with
1585 | Some { subst; rhs } ->
1586 let subst, qsubst, usubst = Partial_subst.to_arrays subst in
1587 let subst = Array.fold_right subs_cons subst (subs_id 0) in
1588 let usubst = UVars.Instance.of_array (qsubst, usubst) in
1589 let m' = mk_clos (subst, usubst) rhs in
1590 begin match pat_state with
1591 | Nil Yes -> Some (m', stack)
1592 | _ -> red.red_kni info tab ~pat_state m' stack
1593 end
1594 | None -> match_elim red info tab ~pat_state next context states elims head stack
1595 end
1596 | LocArg { patterns; context; arg; next } ->
1597 match_arg red info tab ~pat_state next context states patterns arg
1598 | LocStart { elims; context; head; stack; next } ->
1599 match_elim red info tab ~pat_state next context states elims head stack
1600
1601 and match_kill : 'a. ('a, 'a patstate) reduction -> _ -> _ -> pat_state:(fconstr, stack, _, 'a) depth -> _ -> 'a =
1602 fun red info tab ~pat_state -> function
1603 | LocArg { next; _ } -> match_kill red info tab ~pat_state next
1604 | LocStart { head; stack; next; _ } ->
1605 ignore (zip head stack);
1606 match next with
1607 | Continue next -> match_kill red info tab ~pat_state next
1608 | Return k -> try_unfoldfix red info tab ~pat_state k
1609
1610 and match_endstack : 'a. ('a, 'a patstate) reduction -> _ -> _ -> pat_state:(_, _, _, 'a) depth -> _ -> _ -> 'a =
1611 fun red info tab ~pat_state states next ->
1612 match next with
1613 | Continue next -> match_main red info tab ~pat_state states next
1614 | Return k ->
1615 assert (Array.for_all (function Dead -> true | Live _ -> false) states);
1616 try_unfoldfix red info tab ~pat_state k
1617
1618 and try_unfoldfix : 'a. ('a, 'a patstate) reduction -> _ -> _ -> pat_state:(_, _, _, 'a) depth -> _ -> 'a =
1619 fun red info tab ~pat_state (b, m, stk) ->
1620 if not b then red.red_ret info tab ~pat_state ~failed:true (m, stk) else
1621 let rarg, stack = strip_update_shift_absorb_app m stk in
1622 match [@ocaml.warning "-4"] stack with
1623 | Zfix (fx, par) :: s ->
1624 let stk' = par @ append_stack [|rarg|] s in
1625 let (fxe,fxbd) = contract_fix_vect fx.term in
1626 red.red_knit info tab ~pat_state fxe fxbd stk'
1627 | _ -> red.red_ret info tab ~pat_state ~failed:true (m, stk)
1628
1629 and match_elim : 'a. ('a, 'a patstate) reduction -> _ -> _ -> pat_state:(fconstr, stack, _, 'a) depth -> _ -> _ -> _ -> _ -> _ -> _ -> 'a =
1630 fun red info tab ~pat_state next context states elims head stk ->
1631 match stk with
1632 | Zapp args :: s ->
1633 let pargselims, states = extract_or_kill2 (function [@ocaml.warning "-4"] PEApp pargs :: es, subst -> Some ((pargs, es), subst) | _ -> None) elims states in
1634 let na = Array.length args in
1635 let np = Array.fold_left (Status.fold_left (fun a (pargs, _) -> min a (Array.length pargs))) na pargselims in
1636 let pargs, elims, states =
1637 extract_or_kill3 (fun ((pargs, elims), subst) ->
1638 let npp = Array.length pargs in
1639 if npp == np then Some (pargs, elims, subst) else
1640 let fst, lst = Array.chop np pargs in
1641 Some (fst, PEApp lst :: elims, subst))
1642 pargselims states
1643 in
1644 let args, rest = Array.chop np args in
1645 let head = mkFApp head args in
1646 let stack = if Array.length rest > 0 then Zapp rest :: s else s in
1647 let loc = LocStart { elims; context; head; stack; next } in
1648 let loc = Array.fold_right2 (fun patterns arg next -> LocArg { patterns; context; arg; next }) (Array.transpose (Array.map (Status.split_array np) pargs)) args loc in
1649 match_main red info tab ~pat_state states loc
1650 | Zshift k :: s -> match_elim red info tab ~pat_state next context states elims (lift_fconstr k head) s
1651 | Zupdate m :: s ->
1652 let () = update m head.mark head.term in
1653 match_elim red info tab ~pat_state next context states elims head s
1654 | ZcaseT (ci, u, pms, (p, r), brs, e) :: s ->
1655 let t = FCaseT(ci, u, pms, (p, r), head, brs, e) in
1656 let mark = neutr head.mark in
1657 let head = {mark; term=t} in
1658 let specif = Environ.lookup_mind (fst ci.ci_ind) info.i_cache.i_env in
1659 let specif = (specif, specif.mind_packets.(snd ci.ci_ind)) in
1660 let ntys_ret = Environ.expand_arity specif (ci.ci_ind, u) pms (fst p) in
1661 let ntys_brs = Environ.expand_branch_contexts specif u pms brs in
1662 let prets, pbrss, elims, states = extract_or_kill4 (function [@ocaml.warning "-4"]
1663 | PECase (pind, pret, pbrs) :: es, subst ->
1664 if not @@ Ind.CanOrd.equal pind ci.ci_ind then None else
1665 Some (pret, pbrs, es, subst)
1666 | _ -> None)
1667 elims states
1668 in
1669 let loc = LocStart { elims; context; head; stack=s; next } in
1670 let ntys_ret = subst_context e ntys_ret in
1671 let ret = mk_clos (usubs_liftn (Context.Rel.length ntys_ret) e) (snd p) in
1672 let brs = Array.map2 (fun ctx br -> subst_context e ctx, mk_clos (usubs_liftn (Context.Rel.length ctx) e) (snd br)) ntys_brs brs in
1673 let loc = Array.fold_right2 (fun patterns (ctx, arg) next -> LocArg { patterns; context = ctx @ context; arg; next }) (Array.transpose (Array.map (Status.split_array (Array.length brs)) pbrss)) brs loc in
1674 let loc = LocArg { patterns = prets; context = ntys_ret @ context; arg = ret; next = loc } in
1675 match_main red info tab ~pat_state states loc
1676 | Zproj (proj', r) :: s ->
1677 let mark = (neutr head.mark) in
1678 let head = {mark; term=FProj(Projection.make proj' true, r, head)} in
1679 let elims, states = extract_or_kill2 (function [@ocaml.warning "-4"]
1680 | PEProj proj :: es, subst ->
1681 if not @@ Projection.Repr.CanOrd.equal proj proj' then None else
1682 Some (es, subst)
1683 | _ -> None) elims states
1684 in
1685 let loc = LocStart { elims; context; head; stack=s; next } in
1686 match_main red info tab ~pat_state states loc
1687 | Zfix _ :: _ | Zprimitive _ :: _ ->
1688 let states = extract_or_kill (fun _ -> None) elims states in
1689 ignore (zip head stk);
1690 match_endstack red info tab ~pat_state states next
1691 | [] ->
1692 let states = extract_or_kill (function [], subst -> Some subst | _ -> None) elims states in
1693 match_endstack red info tab ~pat_state states next
1694
1695 and match_arg : 'a. ('a, 'a patstate) reduction -> _ -> _ -> pat_state:(fconstr, stack, _, 'a) depth -> _ -> _ -> _ -> _ -> _ -> 'a =
1696 fun red info tab ~pat_state next context states patterns t ->
1697 let match_deeper = ref false in
1698 let t' = it_mkLambda_or_LetIn info context t in
1699 let patterns, states = Array.split @@ Array.map2
1700 (function Dead -> fun _ -> Ignore, Dead | (Live ({ subst; _ } as psubst) as state) -> function
1701 | Ignore -> Ignore, state
1702 | Check EHole i -> Ignore, Live { psubst with subst = Partial_subst.add_term i t' subst }
1703 | Check EHoleIgnored -> Ignore, state
1704 | Check ERigid p -> match_deeper := true; Check p, state
1705 ) states patterns in
1706 if !match_deeper then
1707 let pat_state = Cons ({ states; context; patterns; next }, pat_state) in
1708 red.red_kni info tab ~pat_state t []
1709 else
1710 match_main red info tab ~pat_state states next
1711
1712 and match_head : 'a. ('a, 'a patstate) reduction -> _ -> _ -> pat_state:(fconstr, stack, _, 'a) depth -> _ -> _ -> _ -> _ -> _ -> _ -> 'a =
1713 fun red info tab ~pat_state next context states patterns t stk ->
1714 match [@ocaml.warning "-4"] t.term with
1715 | FInd (ind', u) ->
1716 let elims, states = extract_or_kill2 (function [@ocaml.warning "-4"]
1717 | (PHInd (ind, pu), elims), psubst ->
1718 if not @@ Ind.CanOrd.equal ind ind' then None else
1719 let subst = UVars.Instance.pattern_match pu u psubst.subst in
1720 Option.map (fun subst -> elims, { psubst with subst }) subst
1721 | _ -> None) patterns states
1722 in
1723 let loc = LocStart { elims; context; head=t; stack=stk; next=Continue next } in
1724 match_main red info tab ~pat_state states loc
1725 | FConstruct ((constr', u), args) ->
1726 let elims, states = extract_or_kill2 (function [@ocaml.warning "-4"]
1727 | (PHConstr (constr, pu), elims), psubst ->
1728 if not @@ Construct.CanOrd.equal constr constr' then None else
1729 let subst = UVars.Instance.pattern_match pu u psubst.subst in
1730 Option.map (fun subst -> elims, { psubst with subst }) subst
1731 | _ -> None) patterns states
1732 in
1733 let loc = LocStart { elims; context; head=t; stack=append_stack args stk; next=Continue next } in
1734 match_main red info tab ~pat_state states loc
1735 | FAtom t' -> begin match [@ocaml.warning "-4"] kind t' with
1736 | Sort s ->
1737 let elims, states = extract_or_kill2 (function [@ocaml.warning "-4"]
1738 | (PHSort ps, elims), psubst ->
1739 let subst = Sorts.pattern_match ps s psubst.subst in
1740 Option.map (fun subst -> elims, { psubst with subst }) subst
1741 | _ -> None) patterns states
1742 in
1743 let loc = LocStart { elims; context; head=t; stack=stk; next=Continue next } in
1744 match_main red info tab ~pat_state states loc
1745 | Meta _ ->
1746 let elims, states = extract_or_kill2 (fun _ -> None) patterns states in
1747 let loc = LocStart { elims; context; head=t; stack=stk; next=Continue next } in
1748 match_main red info tab ~pat_state states loc
1749 | _ -> assert false
1750 end
1751 | FFlex (ConstKey (c', u)) ->
1752 let elims, states = extract_or_kill2 (function [@ocaml.warning "-4"]
1753 | (PHSymbol (c, pu), elims), psubst ->
1754 if not @@ Constant.CanOrd.equal c c' then None else
1755 let subst = UVars.Instance.pattern_match pu u psubst.subst in
1756 Option.map (fun subst -> elims, { psubst with subst }) subst
1757 | _ -> None) patterns states
1758 in
1759 let loc = LocStart { elims; context; head=t; stack=stk; next=Continue next } in
1760 match_main red info tab ~pat_state states loc
1761 | FRel n ->
1762 let elims, states = extract_or_kill2 (function [@ocaml.warning "-4"]
1763 | (PHRel n', elims), psubst ->
1764 if not @@ Int.equal n n' then None else
1765 Some (elims, psubst)
1766 | _ -> None) patterns states
1767 in
1768 let loc = LocStart { elims; context; head=t; stack=stk; next=Continue next } in
1769 match_main red info tab ~pat_state states loc
1770 | FInt i' ->
1771 let elims, states = extract_or_kill2 (function [@ocaml.warning "-4"]
1772 | (PHInt i, elims), psubst ->
1773 if not @@ Uint63.equal i i' then None else
1774 Some (elims, psubst)
1775 | _ -> None) patterns states
1776 in
1777 let loc = LocStart { elims; context; head=t; stack=stk; next=Continue next } in
1778 match_main red info tab ~pat_state states loc
1779 | FFloat f' ->
1780 let elims, states = extract_or_kill2 (function [@ocaml.warning "-4"]
1781 | (PHFloat f, elims), psubst ->
1782 if not @@ Float64.equal f f' then None else
1783 Some (elims, psubst)
1784 | _ -> None) patterns states
1785 in
1786 let loc = LocStart { elims; context; head=t; stack=stk; next=Continue next } in
1787 match_main red info tab ~pat_state states loc
1788 | FString s' ->
1789 let elims, states = extract_or_kill2 (function [@ocaml.warning "-4"]
1790 | (PHString s, elims), psubst ->
1791 if not @@ Pstring.equal s s' then None else
1792 Some (elims, psubst)
1793 | _ -> None) patterns states
1794 in
1795 let loc = LocStart { elims; context; head=t; stack=stk; next=Continue next } in
1796 match_main red info tab ~pat_state states loc
1797 | FProd (n, ty, body, e) ->
1798 let ntys, _ = Term.decompose_prod body in
1799 let na = 1 + List.length ntys in
1800 let tysbodyelims, states = extract_or_kill2 (function [@ocaml.warning "-4"] (PHProd (ptys, pbod), es), psubst when Array.length ptys <= na -> Some ((ptys, pbod, es), psubst) | _ -> None) patterns states in
1801 let na = Array.fold_left (Status.fold_left (fun a (p1, _, _) -> min a (Array.length p1))) na tysbodyelims in
1802 assert (na > 0);
1803 let ptys, pbody, elims, states = extract_or_kill4 (fun ((ptys, pbod, elims), psubst) ->
1804 let npp = Array.length ptys in
1805 if npp == na then Some (ptys, pbod, elims, psubst) else
1806 let fst, lst = Array.chop na ptys in
1807 Some (fst, ERigid (PHProd (lst, pbod), []), elims, psubst)
1808 ) tysbodyelims states
1809 in
1810
1811 let ntys, body = Term.decompose_prod_n (na-1) body in
1812 let ctx1 = List.map (fun (n, ty) -> Context.Rel.Declaration.LocalAssum (n, ty)) ntys |> subst_context e in
1813 let ctx = ctx1 @ [Context.Rel.Declaration.LocalAssum (n, term_of_fconstr ty)] in
1814 let ntys'' = List.mapi (fun n (_, t) -> mk_clos (usubs_liftn n e) t) (List.rev ntys) in
1815 let tys = Array.of_list (ty :: ntys'') in
1816 let contexts_upto = Array.init na (fun i -> List.lastn i ctx @ context) in
1817 let loc = LocStart { elims; context; head=t; stack=stk; next=Continue next } in
1818 let loc = LocArg { patterns = pbody; context = ctx @ context; arg = mk_clos (usubs_liftn na e) body; next = loc } in
1819 let loc = Array.fold_right3 (fun patterns arg context next -> LocArg { patterns; context; arg; next }) (Array.transpose (Array.map (Status.split_array na) ptys)) tys contexts_upto loc in
1820 match_main red info tab ~pat_state states loc
1821 | FLambda (na, ntys, body, e) ->
1822 let tysbodyelims, states = extract_or_kill2 (function [@ocaml.warning "-4"] (PHLambda (ptys, pbod), es), psubst when Array.length ptys <= na -> Some ((ptys, pbod, es), psubst) | _ -> None) patterns states in
1823 let na = Array.fold_left (Status.fold_left (fun a (p1, _, _) -> min a (Array.length p1))) na tysbodyelims in
1824 assert (na > 0);
1825 let ptys, pbody, elims, states = extract_or_kill4 (fun ((ptys, pbod, elims), psubst) ->
1826 let np = Array.length ptys in
1827 if np == na then Some (ptys, ERigid pbod, elims, psubst) else
1828 let fst, lst = Array.chop na ptys in
1829 Some (fst, ERigid (PHLambda (lst, pbod), []), elims, psubst)
1830 ) tysbodyelims states
1831 in
1832 let ntys, tys' = List.chop na ntys in
1833 let body = Term.compose_lam (List.rev tys') body in
1834 let ctx = List.rev_map (fun (n, ty) -> Context.Rel.Declaration.LocalAssum (n, ty)) ntys |> subst_context e in
1835 let tys = Array.of_list ntys in
1836 let tys = Array.mapi (fun n (_, t) -> mk_clos (usubs_liftn n e) t) tys in
1837 let contexts_upto = Array.init na (fun i -> List.lastn i ctx @ context) in
1838 let loc = LocStart { elims; context; head=t; stack=stk; next=Continue next } in
1839 let loc = LocArg { patterns = pbody; context = ctx @ context; arg = mk_clos (usubs_liftn na e) body; next = loc } in
1840 let loc = Array.fold_right3 (fun patterns arg context next -> LocArg { patterns; context; arg; next }) (Array.transpose (Array.map (Status.split_array na) ptys)) tys contexts_upto loc in
1841 match_main red info tab ~pat_state states loc
1842 | _ ->
1843 let states = extract_or_kill (fun _ -> None) patterns states in
1844 ignore (zip t stk);
1845 match_main red info tab ~pat_state states next
1846
1847 let match_symbol red info tab ~pat_state fl (u, b, r) stk =
1848 let unfold_fix = b && red_set info.i_flags fFIX in
1849 let states, elims = Array.split @@ Array.map
1850 (fun r ->
1851 let pu, es = r.lhs_pat in
1852 let subst = Partial_subst.make r.nvars in
1853 let subst = UVars.Instance.pattern_match pu u subst in
1854 match subst with
1855 | Some subst -> Live { subst; rhs = r.Declarations.rhs }, Check es
1856 | None -> Dead, Ignore
1857 ) (Array.of_list r)
1858 in
1859 let m = { mark = Red; term = FFlex fl } in
1860 let loc = LocStart { elims; context=[]; head = m; stack = stk; next = Return (unfold_fix, m, stk) } in
1861 match_main red info tab ~pat_state states loc
1862
1863 let match_head red info tab ~pat_state { states; context; patterns; next } m stk =
1864 match_head red info tab ~pat_state next context states patterns m stk
1865
1866 end
1867
1868 type 'a depth = 'a RedPattern.patstate
1869
1870 (* Computes a weak head normal form from the result of knh. *)
1871 let rec knr : 'a. _ -> _ -> pat_state: 'a depth -> _ -> _ -> 'a =
1872 fun info tab ~pat_state m stk ->
1873 match m.term with
1874 | FLambda(n,tys,f,e) when red_set info.i_flags fBETA ->
1875 (match get_args n tys f e stk with
1876 Inl e', s -> knit info tab ~pat_state e' f s
1877 | Inr lam, s -> knr_ret info tab ~pat_state (lam,s))
1878 | FFlex fl when red_set info.i_flags fDELTA ->
1879 (match Table.lookup info tab fl with
1880 | Def (v, _) -> kni info tab ~pat_state v stk
1881 | Primitive op ->
1882 if check_native_args op stk then
1883 let c = match fl with ConstKey c -> c | RelKey _ | VarKey _ -> assert false in
1884 let rargs, a, nargs, stk = get_native_args1 op c stk in
1885 kni info tab ~pat_state a (Zprimitive(op,c,rargs,nargs)::stk)
1886 else
1887 (* Similarly to fix, partially applied primitives are not Ntrl! *)
1888 knr_ret info tab ~pat_state (m, stk)
1889 | Symbol (u, b, r) ->
1890 let red = {
1891 red_kni = kni;
1892 red_knit = knit;
1893 red_ret = knr_ret;
1894 } in
1895 RedPattern.match_symbol red info tab ~pat_state fl (u, b, r) stk
1896 | Undef _ | OpaqueDef _ -> (set_ntrl m; knr_ret info tab ~pat_state (m,stk)))
1897 | FConstruct (c,_) ->
1898 let use_match = red_set info.i_flags fMATCH in
1899 let use_fix = red_set info.i_flags fFIX in
1900 if use_match || use_fix then
1901 (match [@ocaml.warning "-4"] m, stk with
1902 | (_, Zapp _ :: _) -> assert false (* knh *)
1903 | (c, ZcaseT(ci,_,pms,_,br,e)::s) when use_match ->
1904 assert (ci.ci_npar>=0);
1905 (* instance on the case and instance on the constructor are compatible by typing *)
1906 let (br, e) = get_branch info ci pms c br e in
1907 knit info tab ~pat_state e br s
1908 | (rarg, Zfix(fx,par)::s) when use_fix ->
1909 let stk' = par @ append_stack [|rarg|] s in
1910 let (fxe,fxbd) = contract_fix_vect fx.term in
1911 knit info tab ~pat_state fxe fxbd stk'
1912 | (m, Zproj (p,_)::s) when use_match ->
1913 let rargs = drop_parameters (Projection.Repr.npars p) m in
1914 let rarg = rargs.(Projection.Repr.arg p) in
1915 kni info tab ~pat_state rarg s
1916 | (m, s) ->
1917 if is_irrelevant_constructor info c then
1918 knr_ret info tab ~pat_state (mk_irrelevant, skip_irrelevant_stack info stk)
1919 else
1920 knr_ret info tab ~pat_state (m,s))
1921 else if is_irrelevant_constructor info c then
1922 knr_ret info tab ~pat_state (mk_irrelevant, skip_irrelevant_stack info stk)
1923 else
1924 knr_ret info tab ~pat_state (m, stk)
1925 | FCoFix ((i, (lna, _, _)), e) ->
1926 if is_irrelevant info (usubst_relevance e (lna.(i)).binder_relevance) then
1927 knr_ret info tab ~pat_state (mk_irrelevant, skip_irrelevant_stack info stk)
1928 else if red_set info.i_flags fCOFIX then
1929 (match strip_update_shift_app m stk with
1930 | (_, _, args, (((ZcaseT _|Zproj _)::_) as stk')) ->
1931 let (fxe,fxbd) = contract_fix_vect m.term in
1932 knit info tab ~pat_state fxe fxbd (args@stk')
1933 | (_, _, args, ((Zapp _ | Zfix _ | Zshift _ | Zupdate _ | Zprimitive _) :: _ | [] as s)) ->
1934 knr_ret info tab ~pat_state (m,args@s))
1935 else knr_ret info tab ~pat_state (m, stk)
1936 | FLetIn (_,v,_,bd,e) when red_set info.i_flags fZETA ->
1937 knit info tab ~pat_state (on_fst (subs_cons v) e) bd stk
1938 | FInt _ | FFloat _ | FString _ | FArray _ ->
1939 (match [@ocaml.warning "-4"] strip_update_shift_app m stk with
1940 | (_, _, _, Zprimitive(op,(_,u as c),rargs,nargs)::s) ->
1941 let (rargs, nargs) = skip_native_args (m::rargs) nargs in
1942 begin match nargs with
1943 | [] ->
1944 let args = match rargs with
1945 | [] -> [||]
1946 | [a] -> [|a|]
1947 | [a; b] -> [|b; a|]
1948 | [a; b; c] -> [|c; b; a|]
1949 | [a; b; c; d] -> [|d; c; b; a|]
1950 | _ -> Array.rev_of_list rargs
1951 in
1952 begin match FredNative.red_prim (info_env info) () op u args with
1953 | Some m -> kni info tab ~pat_state m s
1954 | None -> assert false
1955 end
1956 | (kd,a)::nargs ->
1957 assert (kd = CPrimitives.Kwhnf);
1958 kni info tab ~pat_state a (Zprimitive(op,c,rargs,nargs)::s)
1959 end
1960 | (depth, _, _, stk) -> knr_ret info tab ~pat_state (m,zshift depth stk))
1961 | FCaseInvert (ci, u, pms, _p,iv,_c,v,env) when red_set info.i_flags fMATCH ->
1962 let pms = mk_clos_vect env pms in
1963 let u = usubst_instance env u in
1964 begin match case_inversion info tab ci u pms iv v with
1965 | Some c -> knit info tab ~pat_state env c stk
1966 | None -> knr_ret info tab ~pat_state (m, stk)
1967 end
1968 | FIrrelevant ->
1969 let stk = skip_irrelevant_stack info stk in
1970 knr_ret info tab ~pat_state (m, stk)
1971 | FProd _ | FAtom _ | FInd _ (* relevant statically *)
1972 | FCaseInvert _ | FProj _ | FFix _ | FEvar _ (* relevant because of knh(t) *)
1973 | FLambda _ | FFlex _ | FRel _ (* irrelevance handled by conversion *)
1974 | FLetIn _ (* only happens in reduction mode *) ->
1975 knr_ret info tab ~pat_state (m, stk)
1976 | FLOCKED | FCLOS _ | FApp _ | FCaseT _ | FLIFT _ ->
1977 (* ruled out by knh(t) *)
1978 assert false
1979
1980 and knr_ret : type a. _ -> _ -> pat_state: a depth -> ?failed: _ -> _ -> a =
1981 fun info tab ~pat_state ?(failed=false) i ->
1982 match pat_state with
1983 | RedPattern.Cons (patt, pat_state) ->
1984 let m, stk = i in
1985 let red = {
1986 red_kni = kni;
1987 red_knit = knit;
1988 red_ret = knr_ret;
1989 } in
1990 RedPattern.match_head red info tab ~pat_state patt m stk
1991 | RedPattern.Nil b ->
1992 match b with No -> i | Yes -> if failed then None else Some i
1993
1994 (* Computes the weak head normal form of a term *)
1995 and kni : 'a. _ -> _ -> pat_state: 'a depth -> _ -> _ -> 'a =
1996 fun info tab ~pat_state m stk ->
1997 let (hm,s) = knh info m stk in
1998 knr info tab ~pat_state hm s
1999 and knit : 'a. _ -> _ -> pat_state: 'a depth -> _ -> _ -> _ -> 'a =
2000 fun info tab ~pat_state e t stk ->
2001 let (ht,s) = knht info e t stk in
2002 knr info tab ~pat_state ht s
2003
2004 and case_inversion info tab ci u params indices v = match v with
2005 | [||] -> None (* empty type *)
2006 | [| [||], v |] ->
2007 (* No binders / lets at all in the unique branch *)
2008 let open Declarations in
2009 if Array.is_empty indices then Some v
2010 else
2011 let env = info_env info in
2012 let ind = ci.ci_ind in
2013 let psubst = subs_consn params 0 ci.ci_npar (subs_id 0) in
2014 let mib = Environ.lookup_mind (fst ind) env in
2015 let mip = mib.mind_packets.(snd ind) in
2016 (* indtyping enforces 1 ctor with no letins in the context *)
2017 let _, expect = mip.mind_nf_lc.(0) in
2018 let _ind, expect_args = destApp expect in
2019 let tab = if info.i_cache.i_mode == Conversion then tab else Table.create () in
2020 let info = {info with i_cache = { info.i_cache with i_mode = Conversion}; i_flags=all} in
2021 let check_index i index =
2022 let expected = expect_args.(ci.ci_npar + i) in
2023 let expected = mk_clos (psubst,u) expected in
2024 !conv info tab expected index
2025 in
2026 if Array.for_all_i check_index 0 indices
2027 then Some v else None
2028 | _ -> assert false
2029
2030 let knred = {
2031 red_kni = kni;
2032 red_knit = knit;
2033 red_ret = knr_ret;
2034 }
2035
2036 let kni info tab v stk = kni info tab ~pat_state:(RedPattern.Nil No) v stk
2037 let knit info tab v stk = knit info tab ~pat_state:(RedPattern.Nil No) v stk
2038 let kh info tab v stk = fapp_stack(kni info tab v stk)
2039
2040 (************************************************************************)
2041
2042 (* Computes the strong normal form of a term.
2043 1- Calls kni
2044 2- tries to rebuild the term. If a closure still has to be computed,
2045 calls itself recursively. *)
2046
2047 let is_val v = match v.term with
2048 | FAtom _ | FRel _ | FInd _ | FConstruct (_,[||]) | FInt _ | FFloat _ | FString _ -> true
2049 | FFlex _ -> v.mark == Ntrl
2050 | FConstruct _ | FApp _ | FProj _ | FFix _ | FCoFix _ | FCaseT _ | FCaseInvert _ | FLambda _
2051 | FProd _ | FLetIn _ | FEvar _ | FArray _ | FLIFT _ | FCLOS _ -> false
2052 | FIrrelevant | FLOCKED -> assert false
2053
2054 let rec kl info tab m =
2055 let share = info.i_cache.i_share in
2056 if is_val m then term_of_fconstr m
2057 else
2058 let (nm,s) = kni info tab m [] in
2059 let () = if share then ignore (fapp_stack (nm, s)) in (* to unlock Zupdates! *)
2060 zip_term info tab (norm_head info tab nm) s
2061
2062 and klt info tab e t = match kind t with
2063 | Rel i ->
2064 begin match expand_rel i (fst e) with
2065 | Inl (n, mt) -> kl info tab @@ lift_fconstr n mt
2066 | Inr (k, None) -> if Int.equal k i then t else mkRel k
2067 | Inr (k, Some p) -> kl info tab @@ lift_fconstr (k-p) {mark=Red;term=FFlex(RelKey p)}
2068 end
2069 | App (hd, args) ->
2070 begin match kind hd with
2071 | Ind _ | Construct _ ->
2072 let args' = Array.Smart.map (fun c -> klt info tab e c) args in
2073 let hd' = subst_instance_constr (snd e) hd in
2074 if hd' == hd && args' == args then t
2075 else mkApp (hd', args')
2076 | Var _ | Const _ | CoFix _ | Lambda _ | Fix _ | Prod _ | Evar _ | Case _
2077 | Cast _ | LetIn _ | Proj _ | Array _ | Rel _ | Meta _ | Sort _ | Int _
2078 | Float _ | String _ ->
2079 let share = info.i_cache.i_share in
2080 let (nm,s) = knit info tab e t [] in
2081 let () = if share then ignore (fapp_stack (nm, s)) in (* to unlock Zupdates! *)
2082 zip_term info tab (norm_head info tab nm) s
2083 | App _ -> assert false
2084 end
2085 | Lambda (na, u, c) ->
2086 let na' = usubst_binder e na in
2087 let u' = klt info tab e u in
2088 let c' = klt (push_relevance info na') tab (usubs_lift e) c in
2089 if na' == na && u' == u && c' == c then t
2090 else mkLambda (na', u', c')
2091 | Prod (na, u, v) ->
2092 let na' = usubst_binder e na in
2093 let u' = klt info tab e u in
2094 let v' = klt (push_relevance info na') tab (usubs_lift e) v in
2095 if na' == na && u' == u && v' == v then t
2096 else mkProd (na', u', v')
2097 | Cast (t, _, _) -> klt info tab e t
2098 | Var _ | Const _ | CoFix _ | Fix _ | Evar _ | Case _ | LetIn _ | Proj _ | Array _ ->
2099 let share = info.i_cache.i_share in
2100 let (nm,s) = knit info tab e t [] in
2101 let () = if share then ignore (fapp_stack (nm, s)) in (* to unlock Zupdates! *)
2102 zip_term info tab (norm_head info tab nm) s
2103 | Meta _ | Sort _ | Ind _ | Construct _ | Int _ | Float _ | String _ ->
2104 subst_instance_constr (snd e) t
2105
2106 (* no redex: go up for atoms and already normalized terms, go down
2107 otherwise. *)
2108 and norm_head info tab m =
2109 if is_val m then term_of_fconstr m else
2110 match m.term with
2111 | FLambda(_n,tys,f,e) ->
2112 let fold (e, info, ctxt) (na, ty) =
2113 let na = usubst_binder e na in
2114 let ty = klt info tab e ty in
2115 let info = push_relevance info na in
2116 (usubs_lift e, info, (na, ty) :: ctxt)
2117 in
2118 let (e', info, rvtys) = List.fold_left fold (e,info,[]) tys in
2119 let bd = klt info tab e' f in
2120 List.fold_left (fun b (na,ty) -> mkLambda(na,ty,b)) bd rvtys
2121 | FLetIn(na,a,b,f,e) ->
2122 let na = usubst_binder e na in
2123 let c = klt (push_relevance info na) tab (usubs_lift e) f in
2124 mkLetIn(na, kl info tab a, kl info tab b, c)
2125 | FProd(na,dom,rng,e) ->
2126 let na = usubst_binder e na in
2127 let rng = klt (push_relevance info na) tab (usubs_lift e) rng in
2128 mkProd(na, kl info tab dom, rng)
2129 | FCoFix((n,(na,tys,bds)),e) ->
2130 let na = Array.Smart.map (usubst_binder e) na in
2131 let infobd = push_relevances info na in
2132 let ftys = Array.map (fun ty -> klt info tab e ty) tys in
2133 let fbds = Array.map (fun bd -> klt infobd tab (usubs_liftn (Array.length na) e) bd) bds in
2134 mkCoFix (n, (na, ftys, fbds))
2135 | FFix((n,(na,tys,bds)),e) ->
2136 let na = Array.Smart.map (usubst_binder e) na in
2137 let infobd = push_relevances info na in
2138 let ftys = Array.map (fun ty -> klt info tab e ty) tys in
2139 let fbds = Array.map (fun bd -> klt infobd tab (usubs_liftn (Array.length na) e) bd) bds in
2140 mkFix (n, (na, ftys, fbds))
2141 | FEvar(ev, args, env, repack) ->
2142 repack (ev, List.map (fun a -> klt info tab env a) args)
2143 | FProj (p,r,c) ->
2144 mkProj (p, r, kl info tab c)
2145 | FArray (u, a, ty) ->
2146 let a, def = Parray.to_array a in
2147 let a = Array.map (kl info tab) a in
2148 let def = kl info tab def in
2149 let ty = kl info tab ty in
2150 mkArray (u, a, def, ty)
2151 | FConstruct (c,args) -> mkApp (mkConstructU c, Array.map (kl info tab) args)
2152 | FLOCKED | FRel _ | FAtom _ | FFlex _ | FInd _
2153 | FApp _ | FCaseT _ | FCaseInvert _ | FLIFT _ | FCLOS _ | FInt _
2154 | FFloat _ | FString _ -> term_of_fconstr m
2155 | FIrrelevant -> assert false (* only introduced when converting *)
2156
2157 and zip_term info tab m stk = match stk with
2158 | [] -> m
2159 | Zapp args :: s ->
2160 zip_term info tab (mkApp(m, Array.map (kl info tab) args)) s
2161 | ZcaseT(ci, u, pms, (p,r), br, e) :: s ->
2162 let zip_ctx (nas, c) =
2163 let nas = Array.map (usubst_binder e) nas in
2164 let e = usubs_liftn (Array.length nas) e in
2165 (nas, klt info tab e c)
2166 in
2167 let r = usubst_relevance e r in
2168 let u = usubst_instance e u in
2169 let t = mkCase(ci, u, Array.map (fun c -> klt info tab e c) pms, (zip_ctx p, r),
2170 NoInvert, m, Array.map zip_ctx br) in
2171 zip_term info tab t s
2172 | Zproj (p,r)::s ->
2173 let t = mkProj (Projection.make p true, r, m) in
2174 zip_term info tab t s
2175 | Zfix(fx,par)::s ->
2176 let h = mkApp(zip_term info tab (kl info tab fx) par,[|m|]) in
2177 zip_term info tab h s
2178 | Zshift(n)::s ->
2179 zip_term info tab (lift n m) s
2180 | Zupdate(_rf)::s ->
2181 zip_term info tab m s
2182 | Zprimitive(_,c,rargs, kargs)::s ->
2183 let kargs = List.map (fun (_,a) -> kl info tab a) kargs in
2184 let args =
2185 List.fold_left (fun args a -> kl info tab a ::args) (m::kargs) rargs in
2186 let h = mkApp (mkConstU c, Array.of_list args) in
2187 zip_term info tab h s
2188
2189 (* Initialization and then normalization *)
2190
2191 (* weak reduction *)
2192 let whd_val info tab v = term_of_fconstr (kh info tab v [])
2193
2194 (* strong reduction *)
2195 let norm_val info tab v = kl info tab v
2196 let norm_term info tab e t = klt info tab e t
2197
2198 let whd_stack infos tab m stk = match m.mark with
2199 | Ntrl ->
2200 (** No need to perform [kni] nor to unlock updates because
2201 every head subterm of [m] is [Ntrl] *)
2202 knh infos m stk
2203 | Red | Cstr ->
2204 let k = kni infos tab m stk in
2205 let () =
2206 if infos.i_cache.i_share then
2207 (* to unlock Zupdates! *)
2208 let (m', stk') = k in
2209 if not (m == m' && stk == stk') then ignore (zip m' stk')
2210 in
2211 k
2212
2213 let create_infos i_mode ?univs ?evars i_flags i_env =
2214 let evars = Option.default (default_evar_handler i_env) evars in
2215 let i_univs = Option.default (Environ.universes i_env) univs in
2216 let i_share = (Environ.typing_flags i_env).Declarations.share_reduction in
2217 let i_cache = {i_env; i_sigma = evars; i_share; i_univs; i_mode} in
2218 {i_flags; i_relevances = Range.empty; i_cache}
2219
2220 let create_conv_infos = create_infos Conversion
2221 let create_clos_infos = create_infos Reduction
2222
2223 let oracle_of_infos infos = Environ.oracle infos.i_cache.i_env
2224
2225 let infos_with_reds infos reds =
2226 { infos with i_flags = reds }
2227
2228 let unfold_ref_with_args infos tab fl v =
2229 match Table.lookup infos tab fl with
2230 | Def (def, _) -> Some (def, v)
2231 | Primitive op when check_native_args op v ->
2232 let c = match [@ocaml.warning "-4"] fl with ConstKey c -> c | _ -> assert false in
2233 let rargs, a, nargs, v = get_native_args1 op c v in
2234 Some (a, (Zupdate a::(Zprimitive(op,c,rargs,nargs)::v)))
2235 | Symbol (u, b, r) ->
2236 RedPattern.match_symbol knred (infos_with_reds infos all) tab ~pat_state:(RedPattern.Nil Yes) fl (u, b, r) v
2237 | Undef _ | OpaqueDef _ | Primitive _ -> None
2238
2239 let get_ref_mask info tab fl = match Table.lookup info tab fl with
2240 | Def (_, mask) -> mask
2241 | Primitive _ | Symbol _ | Undef _ | OpaqueDef _ -> [||]