Debian Codegraph @

pretyping/reductionops.ml

raw symbols SCIP
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * Copyright INRIA, CNRS and contributors *)
4 (* <O___,, * (see version control and CREDITS file for authors & dates) *)
5 (* \VV/ **************************************************************)
6 (* // * This file is distributed under the terms of the *)
7 (* * GNU Lesser General Public License Version 2.1 *)
8 (* * (see LICENSE file for the text of the license) *)
9 (************************************************************************)
10
11 open CErrors
12 open Util
13 open Names
14 open Constr
15 open Termops
16 open Univ
17 open Evd
18 open Environ
19 open EConstr
20 open Vars
21 open Context.Rel.Declaration
22
23 exception Elimconst
24
25 (** This module implements a call by name reduction used by (at
26 least) evarconv unification. *)
27
28 (** Support for reduction effects *)
29
30 open Mod_subst
31 open Libobject
32
33 type effect_name = string
34
35 (** create a persistent set to store effect functions *)
36
37 (* Table bindings a constant to an effect *)
38 let constant_effect_table = Summary.ref ~name:"reduction-side-effect" Cmap_env.empty
39
40 (* Table bindings function key to effective functions *)
41 let effect_table = ref String.Map.empty
42
43 (** a test to know whether a constant is actually the effect function *)
44 let reduction_effect_hook env sigma con c =
45 try
46 let funkey = Cmap_env.find con !constant_effect_table in
47 let effect_function = String.Map.find funkey !effect_table in
48 effect_function env sigma (Lazy.force c)
49 with Not_found -> ()
50
51 let cache_reduction_effect (con,funkey) =
52 constant_effect_table := Cmap_env.add con funkey !constant_effect_table
53
54 let subst_reduction_effect (subst,(con,funkey)) =
55 (subst_constant subst con,funkey)
56
57 let inReductionEffect : Libobject.locality * (Constant.t * string) -> obj =
58 declare_object @@ object_with_locality "REDUCTION-EFFECT"
59 ~cache:cache_reduction_effect
60 ~subst:(Some subst_reduction_effect)
61 ~discharge:(fun x -> x)
62
63 let declare_reduction_effect funkey f =
64 if String.Map.mem funkey !effect_table then
65 CErrors.anomaly Pp.(str "Cannot redeclare effect function " ++ qstring funkey ++ str ".");
66 effect_table := String.Map.add funkey f !effect_table
67
68 (** A function to set the value of the print function *)
69 let set_reduction_effect local x funkey =
70 Lib.add_leaf (inReductionEffect (local,(x,funkey)))
71
72
73 (** Machinery to custom the behavior of the reduction *)
74 module ReductionBehaviour = struct
75 open Names
76 open Libobject
77
78 type t = NeverUnfold | UnfoldWhen of when_flags | UnfoldWhenNoMatch of when_flags
79 and when_flags = { recargs : int list ; nargs : int option }
80
81 let more_args_when k { recargs; nargs } =
82 { nargs = Option.map ((+) k) nargs;
83 recargs = List.map ((+) k) recargs;
84 }
85
86 let more_args k = function
87 | NeverUnfold -> NeverUnfold
88 | UnfoldWhen x -> UnfoldWhen (more_args_when k x)
89 | UnfoldWhenNoMatch x -> UnfoldWhenNoMatch (more_args_when k x)
90
91 type table = Cpred.t * t Cmap.t
92
93 (* We need to have a fast way to know the set of all constants that
94 have the NeverUnfold flag. Therefore, the table has a distinct subpart
95 that is this set. *)
96 let table =
97 Summary.ref ((Cpred.empty, Cmap.empty)) ~name:"reductionbehaviour"
98
99 let load _ (_,(r, b)) =
100 table := (match b with
101 | None -> Cpred.remove r (fst !table), Cmap.remove r (snd !table)
102 | Some NeverUnfold -> Cpred.add r (fst !table), Cmap.remove r (snd !table)
103 | Some b -> Cpred.remove r (fst !table), Cmap.add r b (snd !table))
104
105 let cache o = load 1 o
106
107 let classify (local,_) = if local then Dispose else Substitute
108
109 let subst (subst, (local, (r,o) as orig)) =
110 let r' = subst_constant subst r in if r==r' then orig
111 else (local,(r',o))
112
113 let discharge = function
114 | false, (gr, b) ->
115 let b =
116 let gr = GlobRef.ConstRef gr in
117 if Global.is_in_section gr then
118 let vars = Global.section_instance gr in
119 let extra = Array.length vars in
120 Option.map (more_args extra) b
121 else b
122 in
123 Some (false, (gr, b))
124 | true, _ -> None
125
126 let inRedBehaviour = declare_object {
127 (default_object "REDUCTIONBEHAVIOUR") with
128 load_function = load;
129 cache_function = cache;
130 classify_function = classify;
131 subst_function = subst;
132 discharge_function = discharge;
133 }
134
135 let set ~local r b =
136 Lib.add_leaf (inRedBehaviour (local, (r, b)))
137
138 let get_from_db table r =
139 if Cpred.mem r (fst table) then
140 Some NeverUnfold
141 else
142 Cmap.find_opt r (snd table)
143
144 let print_from_db table ref =
145 let open Pp in
146 let pr_global c = Nametab.pr_global_env Id.Set.empty (ConstRef c) in
147 match get_from_db table ref with
148 | None -> mt ()
149 | Some b ->
150 let pp_nomatch = spc () ++ str "but avoid exposing match constructs" in
151 let pp_recargs recargs = spc() ++ str "when the " ++
152 pr_enum (fun x -> pr_nth (x+1)) recargs ++ str (String.plural (List.length recargs) " argument") ++
153 str (String.plural (if List.length recargs >= 2 then 1 else 2) " evaluate") ++
154 str " to a constructor" in
155 let pp_nargs nargs =
156 spc() ++ str "when applied to " ++ int nargs ++
157 str (String.plural nargs " argument") in
158 let pp_when = function
159 | { recargs = []; nargs = Some 0 } ->
160 str "always unfold " ++ pr_global ref
161 | { recargs = []; nargs = Some n } ->
162 str "unfold " ++ pr_global ref ++ pp_nargs n
163 | { recargs = []; nargs = None } ->
164 str "unfold " ++ pr_global ref
165 | { recargs; nargs = Some n } when n > List.fold_left max 0 recargs ->
166 str "unfold " ++ pr_global ref ++ pp_recargs recargs ++
167 str " and" ++ pp_nargs n
168 | { recargs; nargs = _ } ->
169 str "unfold " ++ pr_global ref ++ pp_recargs recargs
170 in
171 let pp_behavior = function
172 | NeverUnfold -> str "never unfold " ++ pr_global ref
173 | UnfoldWhen x -> pp_when x
174 | UnfoldWhenNoMatch x -> pp_when x ++ pp_nomatch
175 in
176 hov 2 (str "The reduction tactics " ++ pp_behavior b)
177
178 module Db = struct
179 type t = table
180 let get () = !table
181 let empty = (Cpred.empty, Cmap.empty)
182 let print = print_from_db
183 let all_never_unfold table = fst table
184 end
185
186 let get r = get_from_db (Db.get ()) r
187
188 let print c = print_from_db (Db.get ()) c
189
190 end
191
192 (** The type of (machine) stacks (= lambda-bar-calculus' contexts) *)
193 module Stack :
194 sig
195 open EConstr
196 type app_node
197 val pr_app_node : (EConstr.t -> Pp.t) -> app_node -> Pp.t
198
199 type case_stk = case_info * EInstance.t * EConstr.t array * EConstr.case_return * EConstr.t pcase_invert * EConstr.case_branch array
200
201 val mkCaseStk : case_info * EInstance.t * EConstr.t array * EConstr.case_return * EConstr.t pcase_invert * EConstr.case_branch array -> case_stk
202
203 type member =
204 | App of app_node
205 | Case of case_stk
206 | Proj of Projection.t * ERelevance.t
207 | Fix of fixpoint * t
208 | Primitive of CPrimitives.t * (Constant.t * EInstance.t) * t * CPrimitives.args_red
209
210 and t = member list
211
212 exception IncompatibleFold2
213
214 val pr : (EConstr.t -> Pp.t) -> t -> Pp.t
215 val empty : t
216 val is_empty : t -> bool
217 val append_app : EConstr.t array -> t -> t
218 val decomp : t -> (EConstr.t * t) option
219 val decomp_rev : t -> (EConstr.t * t) option
220 val compare_shape : t -> t -> bool
221 val fold2 : ('a -> constr -> constr -> 'a) -> 'a -> t -> t -> 'a
222 val append_app_list : EConstr.t list -> t -> t
223 val strip_app : t -> t * t
224 val strip_n_app : int -> t -> (t * EConstr.t * t) option
225 val not_purely_applicative : t -> bool
226 val list_of_app_stack : t -> constr list option
227 val args_size : t -> int
228 val tail : int -> t -> t
229 val nth : t -> int -> EConstr.t
230 val zip : evar_map -> constr * t -> constr
231 val check_native_args : CPrimitives.t -> t -> bool
232 val get_next_primitive_args : CPrimitives.args_red -> t -> CPrimitives.args_red * (t * EConstr.t * t) option
233 val expand_case : env -> evar_map -> case_stk -> case_info * EInstance.t * constr array * ((rel_context * constr) * ERelevance.t) * (rel_context * constr) array
234 end =
235 struct
236 open EConstr
237 type app_node = int * EConstr.t array * int
238 (* first relevant position, arguments, last relevant position *)
239
240 (*
241 Invariant that this module must ensure:
242 (beware of direct access to app_node by the rest of Reductionops)
243 - in app_node (i,_,j) i <= j
244 - There is no array reallocation (outside of debug printing)
245 *)
246
247 let pr_app_node pr (i,a,j) =
248 let open Pp in surround (
249 prvect_with_sep pr_comma pr (Array.sub a i (j - i + 1))
250 )
251
252
253 type case_stk =
254 case_info * EInstance.t * EConstr.t array * EConstr.case_return * EConstr.t pcase_invert * EConstr.case_branch array
255
256 let mkCaseStk x = x
257
258 type member =
259 | App of app_node
260 | Case of case_stk
261 | Proj of Projection.t * ERelevance.t
262 | Fix of fixpoint * t
263 | Primitive of CPrimitives.t * (Constant.t * EInstance.t) * t * CPrimitives.args_red
264
265 and t = member list
266
267 (* Debugging printer *)
268 let rec pr_member pr_c member =
269 let open Pp in
270 let pr_c x = hov 1 (pr_c x) in
271 match member with
272 | App app -> str "ZApp" ++ pr_app_node pr_c app
273 | Case (_,_,_,_,_,br) ->
274 str "ZCase(" ++
275 prvect_with_sep (pr_bar) (fun (_, c) -> pr_c c) br
276 ++ str ")"
277 | Proj (p,_) ->
278 str "ZProj(" ++ Projection.debug_print p ++ str ")"
279 | Fix (f,args) ->
280 str "ZFix(" ++ Constr.debug_print_fix pr_c f
281 ++ pr_comma () ++ pr pr_c args ++ str ")"
282 | Primitive (p,c,args,kargs) ->
283 str "ZPrimitive(" ++ str (CPrimitives.to_string p)
284 ++ pr_comma () ++ pr pr_c args ++ str ")"
285 and pr pr_c l =
286 let open Pp in
287 prlist_with_sep pr_semicolon (fun x -> hov 1 (pr_member pr_c x)) l
288
289 let empty = []
290 let is_empty = CList.is_empty
291
292 let append_app v s =
293 let le = Array.length v in
294 if Int.equal le 0 then s else App (0,v,pred le) :: s
295
296 let decomp_rev = function
297 | App (i,l,j) :: sk ->
298 if i < j then Some (l.(j), App (i,l,pred j) :: sk)
299 else Some (l.(j), sk)
300 | _ -> None
301
302 let decomp_node_last (i,l,j) sk =
303 if i < j then (l.(j), App (i,l,pred j) :: sk)
304 else (l.(j), sk)
305
306 let compare_shape stk1 stk2 =
307 let rec compare_rec bal stk1 stk2 =
308 match (stk1,stk2) with
309 ([],[]) -> Int.equal bal 0
310 | (App (i,_,j)::s1, _) -> compare_rec (bal + j + 1 - i) s1 stk2
311 | (_, App (i,_,j)::s2) -> compare_rec (bal - j - 1 + i) stk1 s2
312 | (Case _ :: s1, Case _::s2) ->
313 Int.equal bal 0 (* && c1.ci_ind = c2.ci_ind *) && compare_rec 0 s1 s2
314 | (Proj (p,_)::s1, Proj(p2,_)::s2) ->
315 Int.equal bal 0 && compare_rec 0 s1 s2
316 | (Fix(_,a1)::s1, Fix(_,a2)::s2) ->
317 Int.equal bal 0 && compare_rec 0 a1 a2 && compare_rec 0 s1 s2
318 | (Primitive(_,_,a1,_)::s1, Primitive(_,_,a2,_)::s2) ->
319 Int.equal bal 0 && compare_rec 0 a1 a2 && compare_rec 0 s1 s2
320 | ((Case _ | Proj _ | Fix _ | Primitive _) :: _ | []) ,_ -> false in
321 compare_rec 0 stk1 stk2
322
323 exception IncompatibleFold2
324 let fold2 f o sk1 sk2 =
325 let rec aux o sk1 sk2 =
326 match sk1,sk2 with
327 | [], [] -> o
328 | App n1 :: q1, App n2 :: q2 ->
329 let t1,l1 = decomp_node_last n1 q1 in
330 let t2,l2 = decomp_node_last n2 q2 in
331 aux (f o t1 t2) l1 l2
332 | Case ((_,_,pms1,((_, t1),_),_,a1)) :: q1, Case ((_,_,pms2, ((_, t2),_),_,a2)) :: q2 ->
333 let f' o (_, t1) (_, t2) = f o t1 t2 in
334 aux (Array.fold_left2 f' (f (Array.fold_left2 f o pms1 pms2) t1 t2) a1 a2) q1 q2
335 | Proj (p1,_) :: q1, Proj (p2,_) :: q2 ->
336 aux o q1 q2
337 | Fix ((_,(_,a1,b1)),s1) :: q1, Fix ((_,(_,a2,b2)),s2) :: q2 ->
338 let o' = aux (Array.fold_left2 f (Array.fold_left2 f o b1 b2) a1 a2) (List.rev s1) (List.rev s2) in
339 aux o' q1 q2
340 | (((App _|Case _|Proj _|Fix _|Primitive _) :: _|[]), _) ->
341 raise IncompatibleFold2
342 in aux o (List.rev sk1) (List.rev sk2)
343
344 let append_app_list l s =
345 let a = Array.of_list l in
346 append_app a s
347
348 let rec args_size = function
349 | App (i,_,j) :: s -> j + 1 - i + args_size s
350 | (Case _ | Fix _ | Proj _ | Primitive _) :: _ | [] -> 0
351
352 let strip_app s =
353 let rec aux out = function
354 | ( App _ as e) :: s -> aux (e :: out) s
355 | s -> List.rev out,s
356 in aux [] s
357
358 let strip_n_app n s =
359 let rec aux n out = function
360 | App (i,a,j) as e :: s ->
361 let nb = j - i + 1 in
362 if n >= nb then
363 aux (n - nb) (e :: out) s
364 else
365 let p = i + n in
366 Some (CList.rev
367 (if Int.equal n 0 then out else App (i,a,p-1) :: out),
368 a.(p),
369 if j > p then App (succ p,a,j) :: s else s)
370 | s -> None
371 in aux n [] s
372
373 let decomp s =
374 match strip_n_app 0 s with
375 | Some (_,a,s) -> Some (a,s)
376 | None -> None
377
378 let not_purely_applicative args =
379 List.exists (function (Fix _ | Case _ | Proj _ ) -> true
380 | App _ | Primitive _ -> false) args
381
382 let list_of_app_stack s =
383 let rec aux = function
384 | App (i,a,j) :: s ->
385 let (args',s') = aux s in
386 let a' = Array.sub a i (j - i + 1) in
387 (Array.fold_right (fun x y -> x::y) a' args', s')
388 | s -> ([],s) in
389 let (out,s') = aux s in
390 match s' with [] -> Some out | _ -> None
391
392 let tail n0 s0 =
393 let rec aux n s =
394 if Int.equal n 0 then s else
395 match s with
396 | App (i,a,j) :: s ->
397 let nb = j - i + 1 in
398 if n >= nb then
399 aux (n - nb) s
400 else
401 let p = i+n in
402 if j >= p then App (p,a,j) :: s else s
403 | _ -> raise (Invalid_argument "Reductionops.Stack.tail")
404 in aux n0 s0
405
406 let nth s p =
407 match strip_n_app p s with
408 | Some (_,el,_) -> el
409 | None -> raise Not_found
410
411 let zip sigma s =
412 let rec zip = function
413 | f, [] -> f
414 | f, (App (i,a,j) :: s) ->
415 let a' = if Int.equal i 0 && Int.equal j (Array.length a - 1)
416 then a
417 else Array.sub a i (j - i + 1) in
418 zip (mkApp (f, a'), s)
419 | f, (Case (ci,u,pms,rt,iv,br)::s) -> zip (mkCase (ci,u,pms,rt,iv,f,br), s)
420 | f, (Fix (fix,st)::s) -> zip
421 (mkFix fix, st @ (append_app [|f|] s))
422 | f, (Proj (p,r)::s) -> zip (mkProj (p,r,f),s)
423 | f, (Primitive (p,c,args,kargs)::s) ->
424 zip (mkConstU c, args @ append_app [|f|] s)
425 in
426 zip s
427
428 (* Check if there is enough arguments on [stk] w.r.t. arity of [op] *)
429 let check_native_args op stk =
430 let nargs = CPrimitives.arity op in
431 let rargs = args_size stk in
432 nargs <= rargs
433
434 let get_next_primitive_args kargs stk =
435 let rec nargs = function
436 | [] -> 0
437 | (CPrimitives.Kwhnf | CPrimitives.Karg) :: _ -> 0
438 | CPrimitives.Kparam :: s -> 1 + nargs s
439 in
440 let n = nargs kargs in
441 (List.skipn (n+1) kargs, strip_n_app n stk)
442
443 let expand_case env sigma ((ci, u, pms, t, iv, br) : case_stk) =
444 let dummy = mkProp in
445 let (ci, u, pms, t, _, _, br) = EConstr.annotate_case env sigma (ci, u, pms, t, iv, dummy, br) in
446 (ci, u, pms, t, br)
447
448 end
449
450 (** The type of (machine) states (= lambda-bar-calculus' cuts) *)
451 type state = constr * Stack.t
452
453 type reduction_function = env -> evar_map -> constr -> constr
454 type e_reduction_function = env -> evar_map -> constr -> evar_map * constr
455
456 type stack_reduction_function =
457 env -> evar_map -> constr -> constr * constr list
458
459 type state_reduction_function =
460 env -> evar_map -> state -> state
461
462 let pr_state env sigma (tm,sk) =
463 let open Pp in
464 let pr c = Termops.Internal.print_constr_env env sigma c in
465 h (pr tm ++ str "|" ++ cut () ++ Stack.pr pr sk)
466
467 (*************************************)
468 (*** Reduction Functions Operators ***)
469 (*************************************)
470
471 type meta_handler = { meta_value : metavariable -> EConstr.t option }
472
473 let safe_meta_value metas ev = match metas with
474 | None -> None
475 | Some f -> f.meta_value ev
476
477 (*************************************)
478 (*** Reduction using bindingss ***)
479 (*************************************)
480
481 (* Beta Reduction tools *)
482
483 let apply_subst env sigma t stack =
484 let rec aux env t stack =
485 match (Stack.decomp stack, EConstr.kind sigma t) with
486 | Some (h,stacktl), Lambda (_,_,c) ->
487 aux (h::env) c stacktl
488 | _ -> (substl env t, stack)
489 in
490 aux env t stack
491
492 let beta_applist sigma (c,l) =
493 Stack.zip sigma (apply_subst [] sigma c (Stack.append_app_list l Stack.empty))
494
495 (* Iota reduction tools *)
496
497 let reducible_mind_case sigma c = match EConstr.kind sigma c with
498 | Construct _ | CoFix _ -> true
499 | _ -> false
500
501 let contract_cofix sigma (bodynum,(names,types,bodies as typedbodies)) =
502 let nbodies = Array.length bodies in
503 let make_Fi j =
504 let ind = nbodies-j-1 in
505 mkCoFix (ind,typedbodies)
506 in
507 let closure = List.init nbodies make_Fi in
508 substl closure bodies.(bodynum)
509
510 (** Similar to the "fix" case below *)
511 let reduce_and_refold_cofix env sigma cofix sk =
512 let raw_answer = contract_cofix sigma cofix in
513 apply_subst [] sigma raw_answer sk
514
515 (* contracts fix==FIX[nl;i](A1...Ak;[F1...Fk]{B1....Bk}) to produce
516 Bi[Fj --> FIX[nl;j](A1...Ak;[F1...Fk]{B1...Bk})] *)
517
518 let contract_fix sigma ((recindices,bodynum),(names,types,bodies as typedbodies)) =
519 let nbodies = Array.length recindices in
520 let make_Fi j =
521 let ind = nbodies-j-1 in
522 mkFix ((recindices,ind),typedbodies)
523 in
524 let closure = List.init nbodies make_Fi in
525 substl closure bodies.(bodynum)
526
527 (** First we substitute the Rel bodynum by the fixpoint and then we try to
528 replace the fixpoint by the best constant from [cst_l]
529 Other rels are directly substituted by constants "magically found from the
530 context" in contract_fix *)
531 let reduce_and_refold_fix env sigma fix sk =
532 let raw_answer = contract_fix sigma fix in
533 apply_subst [] sigma raw_answer sk
534
535 open Primred
536
537 module CNativeEntries =
538 struct
539
540 open UnsafeMonomorphic
541
542 type elem = EConstr.t
543 type args = EConstr.t array
544 type evd = evar_map
545 type uinstance = EConstr.EInstance.t
546
547 let get = Array.get
548
549 let get_int evd e =
550 match EConstr.kind evd e with
551 | Int i -> i
552 | _ -> raise Primred.NativeDestKO
553
554 let get_float evd e =
555 match EConstr.kind evd e with
556 | Float f -> f
557 | _ -> raise Primred.NativeDestKO
558
559 let get_string evd e =
560 match EConstr.kind evd e with
561 | String s -> s
562 | _ -> raise Primred.NativeDestKO
563
564 let get_parray evd e =
565 match EConstr.kind evd e with
566 | Array(_u,t,def,_ty) -> Parray.of_array t def
567 | _ -> raise Primred.NativeDestKO
568
569 let mkInt env i =
570 mkInt i
571
572 let mkFloat env f =
573 mkFloat f
574
575 let mkString env s =
576 mkString s
577
578 let mkBool env b =
579 let (ct,cf) = get_bool_constructors env in
580 mkConstruct (if b then ct else cf)
581
582 let mkCarry env b e =
583 let int_ty = mkConst @@ get_int_type env in
584 let (c0,c1) = get_carry_constructors env in
585 mkApp (mkConstruct (if b then c1 else c0),[|int_ty;e|])
586
587 let mkIntPair env e1 e2 =
588 let int_ty = mkConst @@ get_int_type env in
589 let c = get_pair_constructor env in
590 mkApp(mkConstruct c, [|int_ty;int_ty;e1;e2|])
591
592 let mkFloatIntPair env f i =
593 let float_ty = mkConst @@ get_float_type env in
594 let int_ty = mkConst @@ get_int_type env in
595 let c = get_pair_constructor env in
596 mkApp(mkConstruct c, [|float_ty;int_ty;f;i|])
597
598 let mkLt env =
599 let (_eq, lt, _gt) = get_cmp_constructors env in
600 mkConstruct lt
601
602 let mkEq env =
603 let (eq, _lt, _gt) = get_cmp_constructors env in
604 mkConstruct eq
605
606 let mkGt env =
607 let (_eq, _lt, gt) = get_cmp_constructors env in
608 mkConstruct gt
609
610 let mkFLt env =
611 let (_eq, lt, _gt, _nc) = get_f_cmp_constructors env in
612 mkConstruct lt
613
614 let mkFEq env =
615 let (eq, _lt, _gt, _nc) = get_f_cmp_constructors env in
616 mkConstruct eq
617
618 let mkFGt env =
619 let (_eq, _lt, gt, _nc) = get_f_cmp_constructors env in
620 mkConstruct gt
621
622 let mkFNotComparable env =
623 let (_eq, _lt, _gt, nc) = get_f_cmp_constructors env in
624 mkConstruct nc
625
626 let mkPNormal env =
627 let (pNormal,_nNormal,_pSubn,_nSubn,_pZero,_nZero,_pInf,_nInf,_nan) =
628 get_f_class_constructors env in
629 mkConstruct pNormal
630
631 let mkNNormal env =
632 let (_pNormal,nNormal,_pSubn,_nSubn,_pZero,_nZero,_pInf,_nInf,_nan) =
633 get_f_class_constructors env in
634 mkConstruct nNormal
635
636 let mkPSubn env =
637 let (_pNormal,_nNormal,pSubn,_nSubn,_pZero,_nZero,_pInf,_nInf,_nan) =
638 get_f_class_constructors env in
639 mkConstruct pSubn
640
641 let mkNSubn env =
642 let (_pNormal,_nNormal,_pSubn,nSubn,_pZero,_nZero,_pInf,_nInf,_nan) =
643 get_f_class_constructors env in
644 mkConstruct nSubn
645
646 let mkPZero env =
647 let (_pNormal,_nNormal,_pSubn,_nSubn,pZero,_nZero,_pInf,_nInf,_nan) =
648 get_f_class_constructors env in
649 mkConstruct pZero
650
651 let mkNZero env =
652 let (_pNormal,_nNormal,_pSubn,_nSubn,_pZero,nZero,_pInf,_nInf,_nan) =
653 get_f_class_constructors env in
654 mkConstruct nZero
655
656 let mkPInf env =
657 let (_pNormal,_nNormal,_pSubn,_nSubn,_pZero,_nZero,pInf,_nInf,_nan) =
658 get_f_class_constructors env in
659 mkConstruct pInf
660
661 let mkNInf env =
662 let (_pNormal,_nNormal,_pSubn,_nSubn,_pZero,_nZero,_pInf,nInf,_nan) =
663 get_f_class_constructors env in
664 mkConstruct nInf
665
666 let mkNaN env =
667 let (_pNormal,_nNormal,_pSubn,_nSubn,_pZero,_nZero,_pInf,_nInf,nan) =
668 get_f_class_constructors env in
669 mkConstruct nan
670
671 let mkArray env u t ty =
672 let (t,def) = Parray.to_array t in
673 mkArray(u,t,def,ty)
674
675 end
676
677 module CredNative = RedNative(CNativeEntries)
678
679
680
681 (** Generic reduction function with environment
682
683 Here is where unfolded constant are stored in order to be
684 eventually refolded.
685
686 If tactic_mode is true, it uses ReductionBehaviour, prefers
687 refold constant instead of value and tries to infer constants
688 fix and cofix came from.
689
690 It substitutes fix and cofix by the constant they come from in
691 contract_* in any case .
692 *)
693
694 let debug_RAKAM = CDebug.create ~name:"RAKAM" ()
695
696 let apply_branch env sigma (ind, i) args (ci, u, pms, iv, r, lf) =
697 let args = Stack.tail ci.ci_npar args in
698 let args = Option.get (Stack.list_of_app_stack args) in
699 let br = lf.(i - 1) in
700 if Int.equal ci.ci_cstr_nargs.(i - 1) ci.ci_cstr_ndecls.(i - 1) then
701 (* No let-bindings *)
702 let subst = List.rev args in
703 Vars.substl subst (snd br)
704 else
705 (* For backwards compat with unification, we do not reduce the let-bindings
706 upfront. *)
707 let ctx = expand_branch env sigma u pms (ind, i) br in
708 applist (it_mkLambda_or_LetIn (snd br) ctx, args)
709
710
711 exception PatternFailure
712
713 let match_einstance sigma pu u psubst =
714 match UVars.Instance.pattern_match pu (EInstance.kind sigma u) psubst with
715 | Some psubst -> psubst
716 | None -> raise PatternFailure
717
718 let match_sort ps s psubst =
719 match Sorts.pattern_match ps s psubst with
720 | Some psubst -> psubst
721 | None -> raise PatternFailure
722
723 let rec match_arg_pattern whrec env sigma ctx psubst p t =
724 let open Declarations in
725 let t' = EConstr.it_mkLambda_or_LetIn t ctx in
726 match p with
727 | EHole i -> Partial_subst.add_term i t' psubst
728 | EHoleIgnored -> psubst
729 | ERigid (ph, es) ->
730 let t, stk = whrec ctx (t, Stack.empty) in
731 let psubst = match_rigid_arg_pattern whrec env sigma ctx psubst ph t in
732 let psubst, stk = apply_rule whrec env sigma ctx psubst es stk in
733 if Stack.is_empty stk then psubst else raise PatternFailure
734
735 and match_rigid_arg_pattern whrec env sigma ctx psubst p t =
736 match [@ocaml.warning "-4"] p, EConstr.kind sigma t with
737 | PHInd (ind, pu), Ind (ind', u) ->
738 if QInd.equal env ind ind' then match_einstance sigma pu u psubst else raise PatternFailure
739 | PHConstr (constr, pu), Construct (constr', u) ->
740 if QConstruct.equal env constr constr' then match_einstance sigma pu u psubst else raise PatternFailure
741 | PHRel i, Rel n when i = n -> psubst
742 | PHSort ps, Sort s -> match_sort ps (ESorts.kind sigma s) psubst
743 | PHSymbol (c, pu), Const (c', u) ->
744 if QConstant.equal env c c' then match_einstance sigma pu u psubst else raise PatternFailure
745 | PHInt i, Int i' ->
746 if Uint63.equal i i' then psubst else raise PatternFailure
747 | PHFloat f, Float f' ->
748 if Float64.equal f f' then psubst else raise PatternFailure
749 | PHString s, String s' ->
750 if Pstring.equal s s' then psubst else raise PatternFailure
751 | PHLambda (ptys, pbod), _ ->
752 let ntys, _ = EConstr.decompose_lambda sigma t in
753 let na = List.length ntys and np = Array.length ptys in
754 if np > na then raise PatternFailure;
755 let ntys, body = EConstr.decompose_lambda_n sigma np t in
756 let ctx' = List.map (fun (n, ty) -> Context.Rel.Declaration.LocalAssum (n, ty)) ntys in
757 let tys = Array.of_list @@ List.rev_map snd ntys in
758 let na = Array.length tys in
759 let contexts_upto = Array.init na (fun i -> List.skipn (na - i) ctx' @ ctx) in
760 let psubst = Array.fold_left3 (fun psubst ctx -> match_arg_pattern whrec env sigma ctx psubst) psubst contexts_upto ptys tys in
761 let psubst = match_arg_pattern whrec env sigma (ctx' @ ctx) psubst (ERigid pbod) body in
762 psubst
763 | PHProd (ptys, pbod), _ ->
764 let ntys, _ = EConstr.decompose_prod sigma t in
765 let na = List.length ntys and np = Array.length ptys in
766 if np > na then raise PatternFailure;
767 let ntys, body = EConstr.decompose_prod_n sigma np t in
768 let ctx' = List.map (fun (n, ty) -> Context.Rel.Declaration.LocalAssum (n, ty)) ntys in
769 let tys = Array.of_list @@ List.rev_map snd ntys in
770 let na = Array.length tys in
771 let contexts_upto = Array.init na (fun i -> List.skipn (na - i) ctx' @ ctx) in
772 let psubst = Array.fold_left3 (fun psubst ctx -> match_arg_pattern whrec env sigma ctx psubst) psubst contexts_upto ptys tys in
773 let psubst = match_arg_pattern whrec env sigma (ctx' @ ctx) psubst pbod body in
774 psubst
775 | (PHInd _ | PHConstr _ | PHRel _ | PHSort _ | PHSymbol _ | PHInt _ | PHFloat _ | PHString _), _ -> raise PatternFailure
776
777 and extract_n_stack args n s =
778 if n = 0 then List.rev args, s else
779 match Stack.decomp s with
780 | Some (arg, rest) -> extract_n_stack (arg :: args) (n-1) rest
781 | None -> raise PatternFailure
782
783 and apply_rule whrec env sigma ctx psubst es stk =
784 match [@ocaml.warning "-4"] es, stk with
785 | [], _ -> psubst, stk
786 | Declarations.PEApp pargs :: e, s ->
787 let np = Array.length pargs in
788 let pargs = Array.to_list pargs in
789 let args, s = extract_n_stack [] np s in
790 let psubst = List.fold_left2 (match_arg_pattern whrec env sigma ctx) psubst pargs args in
791 apply_rule whrec env sigma ctx psubst e s
792 | Declarations.PECase (pind, pret, pbrs) :: e, Stack.Case (ci, u, pms, p, iv, brs) :: s ->
793 if not @@ QInd.equal env pind ci.ci_ind then raise PatternFailure;
794 let dummy = mkProp in
795 let (_, _, _, ((ntys_ret, ret), _), _, _, brs) = EConstr.annotate_case env sigma (ci, u, pms, p, NoInvert, dummy, brs) in
796 let psubst = match_arg_pattern whrec env sigma (ntys_ret @ ctx) psubst pret ret in
797 let psubst = Array.fold_left2 (fun psubst pat (ctx', br) -> match_arg_pattern whrec env sigma (ctx' @ ctx) psubst pat br) psubst pbrs brs in
798 apply_rule whrec env sigma ctx psubst e s
799 | Declarations.PEProj proj :: e, Stack.Proj (proj', r) :: s ->
800 if not @@ QProjection.Repr.equal env proj (Projection.repr proj') then raise PatternFailure;
801 apply_rule whrec env sigma ctx psubst e s
802 | _, _ -> raise PatternFailure
803
804
805 let rec apply_rules whrec env sigma u r stk =
806 let open Declarations in
807 match r with
808 | [] -> raise PatternFailure
809 | { lhs_pat = (pu, elims); nvars; rhs } :: rs ->
810 try
811 let psubst = Partial_subst.make nvars in
812 let psubst = match_einstance sigma pu u psubst in
813 let psubst, stk = apply_rule whrec env sigma [] psubst elims stk in
814 let subst, qsubst, usubst = Partial_subst.to_arrays psubst in
815 let usubst = UVars.Instance.of_array (qsubst, usubst) in
816 let rhsu = subst_instance_constr (EConstr.EInstance.make usubst) (EConstr.of_constr rhs) in
817 let rhs' = substl (Array.to_list subst) rhsu in
818 (rhs', stk)
819 with PatternFailure -> apply_rules whrec env sigma u rs stk
820
821 let rec whd_state_gen flags ?metas env sigma =
822 let open Context.Named.Declaration in
823 let rec whrec (x, stack) : state =
824 let () =
825 let open Pp in
826 let pr c = Termops.Internal.print_constr_env env sigma c in
827 debug_RAKAM (fun () ->
828 (h (str "<<" ++ pr x ++
829 str "|" ++ cut () ++ Stack.pr pr stack ++
830 str ">>")))
831 in
832 let c0 = EConstr.kind sigma x in
833 let fold () =
834 let () = debug_RAKAM (fun () ->
835 let open Pp in str "<><><><><>") in
836 ((EConstr.of_kind c0, stack))
837 in
838 match c0 with
839 | Rel n when RedFlags.red_set flags RedFlags.fDELTA ->
840 (match lookup_rel n env with
841 | LocalDef (_,body,_) -> whrec (lift n body, stack)
842 | _ -> fold ())
843 | Var id when RedFlags.red_set flags (RedFlags.fVAR id) ->
844 (match lookup_named id env with
845 | LocalDef (_,body,_) ->
846 whrec (body, stack)
847 | _ -> fold ())
848 | Evar ev -> fold ()
849 | Meta ev ->
850 (match safe_meta_value metas ev with
851 | Some body -> whrec (body, stack)
852 | None -> fold ())
853 | Const (c,u as const) ->
854 reduction_effect_hook env sigma c
855 (lazy (EConstr.to_constr sigma (Stack.zip sigma (x,fst (Stack.strip_app stack)))));
856 if RedFlags.red_set flags (RedFlags.fCONST c) then
857 match constant_value_in env sigma (c, u) with
858 | body ->
859 begin
860 whrec (body, stack)
861 end
862 | exception NotEvaluableConst (IsPrimitive (u,p)) when Stack.check_native_args p stack ->
863 let kargs = CPrimitives.kind p in
864 let (kargs,o) = Stack.get_next_primitive_args kargs stack in
865 (* Should not fail thanks to [check_native_args] *)
866 let (before,a,after) = Option.get o in
867 whrec (a,Stack.Primitive(p,const,before,kargs)::after)
868 | exception NotEvaluableConst (HasRules (u', b, r)) ->
869 begin try
870 let red_fun ctx =
871 let env = push_rel_context ctx env in
872 whd_state_gen flags ?metas env sigma
873 in
874 let rhs, stack = apply_rules red_fun env sigma u r stack in
875 whrec (rhs, stack)
876 with PatternFailure ->
877 if not b then fold () else
878 match Stack.strip_app stack with
879 | args, (Stack.Fix (f,s')::s'') when RedFlags.red_set flags RedFlags.fFIX ->
880 let x' = Stack.zip sigma (x, args) in
881 let out_sk = s' @ (Stack.append_app [|x'|] s'') in
882 whrec (reduce_and_refold_fix env sigma f out_sk)
883 | _ -> fold ()
884 end
885 | exception NotEvaluableConst _ -> fold ()
886 else fold ()
887 | Proj (p, r, c) when RedFlags.red_projection flags p ->
888 let stack' = (c, Stack.Proj (p,r) :: stack) in
889 whrec stack'
890
891 | LetIn (_,b,_,c) when RedFlags.red_set flags RedFlags.fZETA ->
892 whrec (apply_subst [b] sigma c stack)
893 | Cast (c,_,_) -> whrec (c, stack)
894 | App (f,cl) ->
895 whrec
896 (f, Stack.append_app cl stack)
897 | Lambda (na,t,c) ->
898 (match Stack.decomp stack with
899 | Some _ when RedFlags.red_set flags RedFlags.fBETA ->
900 whrec (apply_subst [] sigma x stack)
901 | _ -> fold ())
902
903 | Case (ci,u,pms,p,iv,d,lf) ->
904 whrec (d, Stack.Case (ci,u,pms,p,iv,lf) :: stack)
905
906 | Fix ((ri,n),_ as f) ->
907 (match Stack.strip_n_app ri.(n) stack with
908 |None -> fold ()
909 |Some (bef,arg,s') ->
910 whrec (arg, Stack.Fix(f,bef)::s'))
911
912 | Construct (cstr ,u) ->
913 let use_match = RedFlags.red_set flags RedFlags.fMATCH in
914 let use_fix = RedFlags.red_set flags RedFlags.fFIX in
915 if use_match || use_fix then
916 match Stack.strip_app stack with
917 |args, (Stack.Case case::s') when use_match ->
918 let r = apply_branch env sigma cstr args case in
919 whrec (r, s')
920 |args, (Stack.Proj (p,_)::s') when use_match ->
921 whrec (Stack.nth args (Projection.npars p + Projection.arg p), s')
922 |args, (Stack.Fix (f,s')::s'') when use_fix ->
923 let x' = Stack.zip sigma (x, args) in
924 let out_sk = s' @ (Stack.append_app [|x'|] s'') in
925 whrec (reduce_and_refold_fix env sigma f out_sk)
926 |_, (Stack.App _)::_ -> assert false
927 |_, _ -> fold ()
928 else fold ()
929
930 | CoFix cofix ->
931 if RedFlags.red_set flags RedFlags.fCOFIX then
932 match Stack.strip_app stack with
933 |args, ((Stack.Case _ |Stack.Proj _)::s') ->
934 whrec (reduce_and_refold_cofix env sigma cofix stack)
935 |_ -> fold ()
936 else fold ()
937
938 | Int _ | Float _ | String _ | Array _ ->
939 begin match Stack.strip_app stack with
940 | (_, Stack.Primitive(p,(_, u as kn),rargs,kargs)::s) ->
941 let more_to_reduce = List.exists (fun k -> CPrimitives.Kwhnf = k) kargs in
942 if more_to_reduce then
943 let (kargs,o) = Stack.get_next_primitive_args kargs s in
944 (* Should not fail because Primitive is put on the stack only if fully applied *)
945 let (before,a,after) = Option.get o in
946 whrec (a,Stack.Primitive(p,kn,rargs @ Stack.append_app [|x|] before,kargs)::after)
947 else
948 let n = List.length kargs in
949 let (args,s) = Stack.strip_app s in
950 let (args,extra_args) =
951 try List.chop n args
952 with List.IndexOutOfRange -> (args,[]) (* FIXME probably useless *)
953 in
954 let args = Array.of_list (Option.get (Stack.list_of_app_stack (rargs @ Stack.append_app [|x|] args))) in
955 let s = extra_args @ s in
956 begin match CredNative.red_prim env sigma p u args with
957 | Some t -> whrec (t,s)
958 | None -> ((mkApp (mkConstU kn, args), s))
959 end
960 | _ -> fold ()
961 end
962
963 | Rel _ | Var _ | LetIn _ | Proj _ -> fold ()
964 | Sort _ | Ind _ | Prod _ -> fold ()
965 in
966 whrec
967
968 (** reduction machine without global env and refold machinery *)
969 let local_whd_state_gen flags ?metas env sigma =
970 let rec whrec (x, stack) =
971 let c0 = EConstr.kind sigma x in
972 let s = (EConstr.of_kind c0, stack) in
973 match c0 with
974 | LetIn (_,b,_,c) when RedFlags.red_set flags RedFlags.fZETA ->
975 whrec (apply_subst [b] sigma c stack)
976 | Cast (c,_,_) -> whrec (c, stack)
977 | App (f,cl) -> whrec (f, Stack.append_app cl stack)
978 | Lambda (_,_,c) ->
979 (match Stack.decomp stack with
980 | Some (a,m) when RedFlags.red_set flags RedFlags.fBETA ->
981 whrec (apply_subst [a] sigma c m)
982 | _ -> s)
983
984 | Proj (p,r,c) when RedFlags.red_projection flags p ->
985 (whrec (c, Stack.Proj (p,r) :: stack))
986
987 | Case (ci,u,pms,p,iv,d,lf) ->
988 whrec (d, Stack.Case (ci,u,pms,p,iv,lf) :: stack)
989
990 | Fix ((ri,n),_ as f) ->
991 (match Stack.strip_n_app ri.(n) stack with
992 |None -> s
993 |Some (bef,arg,s') -> whrec (arg, Stack.Fix(f,bef)::s'))
994
995 | Evar ev -> s
996 | Meta ev ->
997 (match safe_meta_value metas ev with
998 Some c -> whrec (c,stack)
999 | None -> s)
1000
1001 | Construct (cstr, u) ->
1002 let use_match = RedFlags.red_set flags RedFlags.fMATCH in
1003 let use_fix = RedFlags.red_set flags RedFlags.fFIX in
1004 if use_match || use_fix then
1005 match Stack.strip_app stack with
1006 |args, (Stack.Case case :: s') when use_match ->
1007 let r = apply_branch env sigma cstr args case in
1008 whrec (r, s')
1009 |args, (Stack.Proj (p,_) :: s') when use_match ->
1010 whrec (Stack.nth args (Projection.npars p + Projection.arg p), s')
1011 |args, (Stack.Fix (f,s')::s'') when use_fix ->
1012 let x' = Stack.zip sigma (x,args) in
1013 whrec (contract_fix sigma f, s' @ (Stack.append_app [|x'|] s''))
1014 |_, (Stack.App _)::_ -> assert false
1015 |_, _ -> s
1016 else s
1017
1018 | CoFix cofix ->
1019 if RedFlags.red_set flags RedFlags.fCOFIX then
1020 match Stack.strip_app stack with
1021 |args, ((Stack.Case _ | Stack.Proj _)::s') ->
1022 whrec (contract_cofix sigma cofix, stack)
1023 |_ -> s
1024 else s
1025
1026 | Rel _ | Var _ | Sort _ | Prod _ | LetIn _ | Const _ | Ind _ | Proj _
1027 | Int _ | Float _ | String _ | Array _ -> s
1028
1029 in
1030 whrec
1031
1032 let stack_red_of_state_red f ?metas =
1033 let f env sigma x = EConstr.decompose_app_list sigma (Stack.zip sigma (f ?metas env sigma (x, Stack.empty))) in
1034 f
1035
1036 let red_of_state_red ?metas ~delta f env sigma x =
1037 let rec is_whnf c = match Constr.kind c with
1038 | Const _ | Var _ -> not delta
1039 | Construct _ | Ind _ | Int _ | Float _ | String _
1040 | Sort _ | Prod _ -> true
1041 | App (h,_) -> is_whnf h
1042 | _ -> false
1043 in
1044 (* preserve physical equality if possible
1045 not sure if anything relies on reduction unfolding head evars
1046 for now use Unsafe.to_constr to keep such unfolds *)
1047 if is_whnf (EConstr.Unsafe.to_constr x) then x
1048 else Stack.zip sigma (f ?metas env sigma (x,Stack.empty))
1049
1050 (* 0. No Reduction Functions *)
1051
1052 let whd_nored_state = local_whd_state_gen RedFlags.nored
1053 let whd_nored_stack = stack_red_of_state_red whd_nored_state
1054 let whd_nored ?metas = red_of_state_red ?metas ~delta:false whd_nored_state
1055
1056 (* 1. Beta Reduction Functions *)
1057
1058 let whd_beta_state = local_whd_state_gen RedFlags.beta
1059 let whd_beta_stack = stack_red_of_state_red whd_beta_state
1060 let whd_beta = red_of_state_red ~delta:false whd_beta_state
1061
1062 let whd_betalet_state = local_whd_state_gen RedFlags.betazeta
1063 let whd_betalet_stack = stack_red_of_state_red whd_betalet_state
1064 let whd_betalet = red_of_state_red ~delta:false whd_betalet_state
1065
1066 (* 2. Delta Reduction Functions *)
1067
1068 let whd_const_state c e = whd_state_gen RedFlags.(mkflags [fCONST c]) e
1069 let whd_const c = red_of_state_red ~delta:true (fun ?metas -> whd_const_state c)
1070
1071 let whd_delta_state = whd_state_gen RedFlags.delta
1072 let whd_delta_stack = stack_red_of_state_red whd_delta_state
1073 let whd_delta = red_of_state_red ~delta:true whd_delta_state
1074
1075 let whd_betadeltazeta_state = whd_state_gen RedFlags.betadeltazeta
1076 let whd_betadeltazeta_stack = stack_red_of_state_red whd_betadeltazeta_state
1077 let whd_betadeltazeta = red_of_state_red ~delta:true whd_betadeltazeta_state
1078
1079 (* 3. Iota reduction Functions *)
1080
1081 let whd_betaiota_state = local_whd_state_gen RedFlags.betaiota
1082 let whd_betaiota_stack = stack_red_of_state_red whd_betaiota_state
1083 let whd_betaiota ?metas = red_of_state_red ?metas ~delta:false whd_betaiota_state
1084
1085 let whd_betaiotazeta_state = local_whd_state_gen RedFlags.betaiotazeta
1086 let whd_betaiotazeta_stack = stack_red_of_state_red whd_betaiotazeta_state
1087 let whd_betaiotazeta ?metas = red_of_state_red ?metas ~delta:false whd_betaiotazeta_state
1088
1089 let whd_all_state = whd_state_gen RedFlags.all
1090 let whd_all_stack = stack_red_of_state_red whd_all_state
1091 let whd_all ?metas = red_of_state_red ?metas ~delta:true whd_all_state
1092
1093 let whd_allnolet_state = whd_state_gen RedFlags.allnolet
1094 let whd_allnolet_stack = stack_red_of_state_red whd_allnolet_state
1095 let whd_allnolet = red_of_state_red ~delta:true whd_allnolet_state
1096
1097 let whd_stack_gen reds = stack_red_of_state_red (whd_state_gen reds)
1098
1099 let is_head_evar env sigma c =
1100 let head, _ = whd_all_state env sigma (c,Stack.empty) in
1101 EConstr.isEvar sigma head
1102
1103 (* 4. Ad-hoc eta reduction *)
1104
1105 let shrink_eta sigma c =
1106 let rec whrec x = match EConstr.kind sigma x with
1107 | Cast (c, _, _) -> whrec c
1108 | Lambda (_, _, c) ->
1109 let (f, cl) = decompose_app sigma (whrec c) in
1110 let napp = Array.length cl in
1111 if napp > 0 then
1112 let x' = whrec (Array.last cl) in
1113 match EConstr.kind sigma x' with
1114 | Rel 1 ->
1115 let lc = Array.sub cl 0 (napp-1) in
1116 let u = mkApp (f, lc) in
1117 if noccurn sigma 1 u then pop u else x
1118 | _ -> x
1119 else x
1120 | Meta _ | App _ | Case _ | Fix _ | Construct _ | CoFix _ | Evar _ | Rel _ | Var _ | Sort _ | Prod _
1121 | LetIn _ | Const _ | Ind _ | Proj _ | Int _ | Float _ | String _ | Array _ -> x
1122 in
1123 whrec c
1124
1125 (* 5. Zeta Reduction Functions *)
1126
1127 let whd_zeta_state = local_whd_state_gen RedFlags.zeta
1128 let whd_zeta_stack = stack_red_of_state_red whd_zeta_state
1129 let whd_zeta = red_of_state_red ~delta:false whd_zeta_state
1130
1131 (****************************************************************************)
1132 (* Reduction Functions *)
1133 (****************************************************************************)
1134
1135 (* Replacing defined evars for error messages *)
1136 let whd_evar = Evarutil.whd_evar
1137 let nf_evar = Evarutil.nf_evar
1138
1139 (* lazy reduction functions. The infos must be created for each term *)
1140 (* Note by HH [oct 08] : why would it be the job of clos_norm_flags to add
1141 a [nf_evar] here *)
1142 let clos_norm_flags flgs env sigma t =
1143 try
1144 EConstr.of_constr (CClosure.norm_term
1145 (Evarutil.create_clos_infos env sigma flgs)
1146 (CClosure.create_tab ())
1147 (Esubst.subs_id 0, UVars.Instance.empty) (EConstr.Unsafe.to_constr t))
1148 with e when is_sync_anomaly e ->
1149 user_err Pp.(str "Tried to normalize ill-typed term")
1150
1151 let clos_whd_flags flgs env sigma t =
1152 try
1153 EConstr.of_constr (CClosure.whd_val
1154 (Evarutil.create_clos_infos env sigma flgs)
1155 (CClosure.create_tab ())
1156 (CClosure.inject (EConstr.Unsafe.to_constr t)))
1157 with e when is_sync_anomaly e ->
1158 user_err Pp.(str "Tried to normalize ill-typed term")
1159
1160 let nf_beta = clos_norm_flags RedFlags.beta
1161 let nf_betaiota = clos_norm_flags RedFlags.betaiota
1162 let nf_betaiotazeta = clos_norm_flags RedFlags.betaiotazeta
1163 let nf_zeta = clos_norm_flags RedFlags.zeta
1164 let nf_all env sigma =
1165 clos_norm_flags RedFlags.all env sigma
1166
1167
1168 (********************************************************************)
1169 (* Conversion *)
1170 (********************************************************************)
1171
1172 let is_transparent e k =
1173 match Conv_oracle.get_strategy (Environ.oracle e) (Evaluable.to_kevaluable k) with
1174 | Conv_oracle.Opaque -> false
1175 | _ -> true
1176
1177 (* Conversion utility functions *)
1178
1179 type conversion_test = UnivConstraints.t -> UnivConstraints.t
1180
1181 (* NOTE: We absorb anomalies happening in the conversion tactic, which
1182 is a bit ugly. This is mostly due to efficiency both in tactics and
1183 in the conversion machinery itself. It is not uncommon for a tactic
1184 to send some ill-typed term to the engine.
1185
1186 We would usually say that a tactic that converts ill-typed terms is
1187 buggy, but fixing the tactic could have a very large runtime cost
1188 *)
1189 exception AnomalyInConversion of exn
1190
1191 let _ = CErrors.register_handler (function
1192 | AnomalyInConversion e ->
1193 Some Pp.(str "Conversion test raised an anomaly:" ++
1194 spc () ++ CErrors.print e)
1195 | _ -> None)
1196
1197 let report_anomaly (e, info) =
1198 let e =
1199 if is_sync_anomaly e then AnomalyInConversion e
1200 else e
1201 in
1202 Exninfo.iraise (e, info)
1203
1204 module CheckUnivs =
1205 struct
1206
1207 open Conversion
1208
1209 let check_eq univs u u' =
1210 if Evd.check_eq univs u u' then Result.Ok univs else Result.Error None
1211
1212 let check_leq univs u u' =
1213 if Evd.check_leq univs u u' then Result.Ok univs else Result.Error None
1214
1215 let checked_sort_cmp_universes pb s0 s1 univs =
1216 let s0 = ESorts.make s0 in
1217 let s1 = ESorts.make s1 in
1218 match pb with
1219 | CUMUL -> check_leq univs s0 s1
1220 | CONV -> check_eq univs s0 s1
1221
1222 let check_cumul_contraints sigma (qcst, ucst) =
1223 Evd.check_univ_constraints sigma ucst && Evd.check_quality_constraints sigma qcst
1224
1225 let check_convert_instances ~flex:_ u u' univs =
1226 let cst = UVars.enforce_eq_instances u u' (UVars.QPairSet.empty, UnivConstraints.empty) in
1227 if check_cumul_contraints univs cst then Result.Ok univs else Result.Error None
1228
1229 (* general conversion and inference functions *)
1230 let check_inductive_instances cv_pb variance u1 u2 univs =
1231 let cst = get_cumulativity_constraints cv_pb variance u1 u2 in
1232 if check_cumul_contraints univs cst then Result.Ok univs else Result.Error None
1233
1234 let checked_universes =
1235 { compare_sorts = checked_sort_cmp_universes;
1236 compare_instances = check_convert_instances;
1237 compare_cumul_instances = check_inductive_instances; }
1238
1239 end
1240
1241 let is_fconv ?(reds=TransparentState.full) pb env sigma t1 t2 =
1242 let univs = Evd.universes sigma in
1243 let t1 = EConstr.Unsafe.to_constr t1 in
1244 let t2 = EConstr.Unsafe.to_constr t2 in
1245 let b = match pb with
1246 | Conversion.CUMUL -> leq_constr_univs univs t1 t2
1247 | Conversion.CONV -> eq_constr_univs univs t1 t2
1248 in
1249 if b then true
1250 else
1251 let evars = Evd.evar_handler sigma in
1252 try
1253 let env = Environ.set_universes (Evd.universes sigma) env in
1254 begin match Conversion.generic_conv ~l2r:false pb ~evars reds env (sigma, CheckUnivs.checked_universes) t1 t2 with
1255 | Result.Ok (_ : Evd.evar_map) -> true
1256 | Result.Error None -> false
1257 | Result.Error (Some e) -> Empty.abort e
1258 end
1259 with
1260 | e ->
1261 let e = Exninfo.capture e in
1262 report_anomaly e
1263
1264 let is_conv ?(reds=TransparentState.full) env sigma x y =
1265 is_fconv ~reds Conversion.CONV env sigma x y
1266 let is_conv_leq ?(reds=TransparentState.full) env sigma x y =
1267 is_fconv ~reds Conversion.CUMUL env sigma x y
1268
1269 let sigma_compare_sorts pb s0 s1 sigma =
1270 match pb with
1271 | Conversion.CONV ->
1272 begin
1273 try Result.Ok (Evd.set_eq_sort sigma (ESorts.make s0) (ESorts.make s1))
1274 with UGraph.UniverseInconsistency err -> Result.Error (Some err)
1275 end
1276 | Conversion.CUMUL ->
1277 begin
1278 try Result.Ok (Evd.set_leq_sort sigma (ESorts.make s0) (ESorts.make s1))
1279 with UGraph.UniverseInconsistency err -> Result.Error (Some err)
1280 end
1281
1282 let sigma_compare_instances ~flex i0 i1 sigma =
1283 match Evd.set_eq_instances ~flex sigma (EInstance.make i0) (EInstance.make i1) with
1284 | sigma -> Result.Ok sigma
1285 | exception Evd.UniversesDiffer -> Result.Error None
1286 | exception UGraph.UniverseInconsistency err -> Result.Error (Some err)
1287
1288 let sigma_check_inductive_instances cv_pb variance u1 u2 sigma =
1289 match Evarutil.compare_cumulative_instances cv_pb variance u1 u2 sigma with
1290 | Inl sigma -> Result.Ok sigma
1291 | Inr err -> Result.Error (Some err)
1292
1293 let sigma_univ_state =
1294 let open Conversion in
1295 { compare_sorts = sigma_compare_sorts;
1296 compare_instances = sigma_compare_instances;
1297 compare_cumul_instances = sigma_check_inductive_instances; }
1298
1299 let univproblem_compare_sorts pb s0 s1 uset =
1300 let open UnivProblem in
1301 match pb with
1302 | Conversion.CONV -> Result.Ok (UnivProblem.Set.add (UEq (s0, s1)) uset)
1303 | Conversion.CUMUL -> Result.Ok (UnivProblem.Set.add (ULe (s0, s1)) uset)
1304
1305 let univproblem_compare_instances ~flex i0 i1 uset =
1306 Result.Ok (UnivProblem.enforce_eq_instances_univs flex i0 i1 uset)
1307
1308 let univproblem_check_inductive_instances cv_pb variance u1 u2 sigma =
1309 Result.Ok (UnivProblem.compare_cumulative_instances cv_pb variance u1 u2 sigma)
1310
1311 let univproblem_univ_state =
1312 let open Conversion in
1313 { compare_sorts = univproblem_compare_sorts;
1314 compare_instances = univproblem_compare_instances;
1315 compare_cumul_instances = univproblem_check_inductive_instances; }
1316
1317 type genconv = {
1318 genconv : 'a 'err. conv_pb -> l2r:bool -> Evd.evar_map -> TransparentState.t ->
1319 Environ.env -> ('a, 'err) Conversion.generic_conversion_function
1320 }
1321
1322 let infer_conv_gen conv_fun ?(catch_incon=true) ?(pb=Conversion.CUMUL)
1323 ?(ts=TransparentState.full) env sigma x y =
1324 try
1325 let ans = match pb with
1326 | Conversion.CUMUL ->
1327 EConstr.leq_constr_universes env sigma x y
1328 | Conversion.CONV ->
1329 EConstr.eq_constr_universes env sigma x y
1330 in
1331 let ans = match ans with
1332 | None -> None
1333 | Some cstr ->
1334 try Some (Evd.add_constraints sigma cstr)
1335 with UGraph.UniverseInconsistency _ | Evd.UniversesDiffer | QGraph.EliminationError _ -> None
1336 in
1337 match ans with
1338 | Some sigma -> ans
1339 | None ->
1340 let x = EConstr.Unsafe.to_constr x in
1341 let y = EConstr.Unsafe.to_constr y in
1342 let env = Environ.set_qualities (Evd.elim_graph sigma) env in
1343 let env = Environ.set_universes (Evd.universes sigma) env in
1344 (* First try conversion with postponed universe problems as a kind of FO
1345 approximation. This may result in unsatisfiable constraints even if
1346 some unfoldings of the arguments could have been unified, but this
1347 should be exceedingly rare. *)
1348 let ans = match conv_fun.genconv pb ~l2r:false sigma ts env (UnivProblem.Set.empty, univproblem_univ_state) x y with
1349 | Result.Ok cstr -> Some cstr
1350 | Result.Error None ->
1351 None (* no universe unification can make these terms convertible *)
1352 | Result.Error (Some e) -> Empty.abort e
1353 in
1354 match ans with
1355 | None -> None
1356 | Some cstr ->
1357 match Evd.add_constraints sigma cstr with
1358 | sigma -> Some sigma
1359 | exception UGraph.UniverseInconsistency _ | exception Evd.UniversesDiffer ->
1360 (* Retry with local universe checking, which may imply constant unfolding *)
1361 match conv_fun.genconv pb ~l2r:false sigma ts env (sigma, sigma_univ_state) x y with
1362 | Result.Ok sigma -> Some sigma
1363 | Result.Error None -> None
1364 | Result.Error (Some e) -> raise (UGraph.UniverseInconsistency e)
1365 with
1366 | UGraph.UniverseInconsistency _ when catch_incon -> None
1367 | QGraph.EliminationError _ when catch_incon -> None
1368 | e ->
1369 let e = Exninfo.capture e in
1370 report_anomaly e
1371
1372 let infer_conv = infer_conv_gen { genconv = fun pb ~l2r sigma ->
1373 Conversion.generic_conv pb ~l2r ~evars:(Evd.evar_handler sigma) }
1374
1375 let infer_conv_ustate ?(catch_incon=true) ?(pb=Conversion.CUMUL)
1376 ?(ts=TransparentState.full) env sigma x y =
1377 try
1378 let ans = match pb with
1379 | Conversion.CUMUL ->
1380 EConstr.leq_constr_universes env sigma x y
1381 | Conversion.CONV ->
1382 EConstr.eq_constr_universes env sigma x y
1383 in
1384 match ans with
1385 | Some cstr -> Some cstr
1386 | None ->
1387 let x = EConstr.Unsafe.to_constr x in
1388 let y = EConstr.Unsafe.to_constr y in
1389 let env = Environ.set_universes (Evd.universes sigma) env in
1390 match
1391 Conversion.generic_conv pb ~l2r:false ~evars:(Evd.evar_handler sigma) ts
1392 env (UnivProblem.Set.empty, univproblem_univ_state) x y
1393 with
1394 | Result.Ok cstr -> Some cstr
1395 | Result.Error None -> None
1396 | Result.Error (Some e) -> raise (UGraph.UniverseInconsistency e)
1397 with
1398 | UGraph.UniverseInconsistency _ when catch_incon -> None
1399 | e ->
1400 let e = Exninfo.capture e in
1401 report_anomaly e
1402
1403 let evars_of_evar_map sigma =
1404 { Genlambda.evars_val = Evd.evar_handler sigma }
1405
1406 let vm_infer_conv ?(pb=Conversion.CUMUL) env sigma t1 t2 =
1407 infer_conv_gen { genconv = fun pb ~l2r sigma ts ->
1408 Vconv.vm_conv_gen pb (evars_of_evar_map sigma) }
1409 ~catch_incon:true ~pb env sigma t1 t2
1410
1411 let native_conv_generic pb sigma t =
1412 Nativeconv.native_conv_gen pb (evars_of_evar_map sigma) t
1413
1414 let native_infer_conv ?(pb=Conversion.CUMUL) env sigma t1 t2 =
1415 infer_conv_gen { genconv = fun pb ~l2r sigma ts -> native_conv_generic pb sigma }
1416 ~catch_incon:true ~pb env sigma t1 t2
1417
1418 let check_hyps_inclusion env sigma x hyps =
1419 let env = Environ.set_universes (Evd.universes sigma) env in
1420 let evars = Evd.evar_handler sigma in
1421 Typeops.check_hyps_inclusion env ~evars x hyps
1422
1423 (********************************************************************)
1424 (* Special-Purpose Reduction *)
1425 (********************************************************************)
1426
1427 (* pseudo-reduction rule:
1428 * [hnf_prod_app env s (Prod(_,B)) N --> B[N]
1429 * with an HNF on the first argument to produce a product.
1430 * if this does not work, then we use the string S as part of our
1431 * error message. *)
1432
1433 let hnf_prod_app env sigma t n =
1434 match EConstr.kind sigma (whd_all env sigma t) with
1435 | Prod (_,_,b) -> subst1 n b
1436 | _ -> anomaly ~label:"hnf_prod_app" (Pp.str "Need a product.")
1437
1438 let hnf_prod_appvect env sigma t nl =
1439 Array.fold_left (fun acc t -> hnf_prod_app env sigma acc t) t nl
1440
1441 let hnf_prod_applist env sigma t nl =
1442 List.fold_left (fun acc t -> hnf_prod_app env sigma acc t) t nl
1443
1444 let hnf_lam_app env sigma t n =
1445 match EConstr.kind sigma (whd_all env sigma t) with
1446 | Lambda (_,_,b) -> subst1 n b
1447 | _ -> anomaly ~label:"hnf_lam_app" (Pp.str "Need an abstraction.")
1448
1449 let hnf_lam_appvect env sigma t nl =
1450 Array.fold_left (fun acc t -> hnf_lam_app env sigma acc t) t nl
1451
1452 let hnf_lam_applist env sigma t nl =
1453 List.fold_left (fun acc t -> hnf_lam_app env sigma acc t) t nl
1454
1455 let whd_decompose_prod env sigma =
1456 let rec decrec env hyps c =
1457 let t = whd_all env sigma c in
1458 match EConstr.kind sigma t with
1459 | Prod (n,a,c0) ->
1460 decrec (push_rel (LocalAssum (n,a)) env) ((n,a)::hyps) c0
1461 | _ -> hyps, t
1462 in
1463 decrec env []
1464
1465 let whd_decompose_lambda env sigma =
1466 let rec decrec env hyps c =
1467 let t = whd_all env sigma c in
1468 match EConstr.kind sigma t with
1469 | Lambda (n,a,c0) ->
1470 decrec (push_rel (LocalAssum (n,a)) env) ((n,a)::hyps) c0
1471 | _ -> hyps, t
1472 in
1473 decrec env []
1474
1475 let whd_decompose_prod_n env sigma n =
1476 let rec decrec env m hyps c = if Int.equal m 0 then (hyps,c) else
1477 match EConstr.kind sigma (whd_all env sigma c) with
1478 | Prod (n,a,c0) ->
1479 decrec (push_rel (LocalAssum (n,a)) env) (m-1) ((n,a)::hyps) c0
1480 | _ -> invalid_arg "whd_decompose_prod_n"
1481 in
1482 decrec env n []
1483
1484 let whd_decompose_lambda_n env sigma n =
1485 let rec decrec env m hyps c = if Int.equal m 0 then (hyps,c) else
1486 match EConstr.kind sigma (whd_all env sigma c) with
1487 | Lambda (n,a,c0) ->
1488 decrec (push_rel (LocalAssum (n,a)) env) (m-1) ((n,a)::hyps) c0
1489 | _ -> invalid_arg "whd_decompose_lambda_n"
1490 in
1491 decrec env n []
1492
1493 let whd_decompose_prod_decls env sigma =
1494 let rec prodec_rec env l c =
1495 let t = whd_allnolet env sigma c in
1496 match EConstr.kind sigma t with
1497 | Prod (x,t,c) ->
1498 let d = LocalAssum (x,t) in
1499 prodec_rec (push_rel d env) (Context.Rel.add d l) c
1500 | LetIn (x,b,t,c) ->
1501 (* note: there is a compromise in situations such as
1502 "let x := forall y, P in x": expose the let-in and stop looking
1503 for products or ignore the let and find a new product *)
1504 let d = LocalDef (x,b,t) in
1505 prodec_rec (push_rel d env) (Context.Rel.add d l) c
1506 | _ ->
1507 (* deal with situations of the form "(let x:=t in fun y => u) v", or even
1508 "(let x:=fun y => u in x) v", ...
1509 ideally, shouldn't we move instead the let-ins outside the redexes? *)
1510 let t' = whd_all env sigma t in
1511 if EConstr.eq_constr sigma t t' then l,t
1512 else prodec_rec env l t'
1513 in
1514 prodec_rec env Context.Rel.empty
1515
1516 let splay_arity env sigma c =
1517 let l, c = whd_decompose_prod env sigma c in
1518 match EConstr.kind sigma c with
1519 | Sort s -> l,s
1520 | _ -> raise Reduction.NotArity
1521
1522 let dest_arity env sigma c =
1523 let l, c = whd_decompose_prod_decls env sigma c in
1524 match EConstr.kind sigma c with
1525 | Sort s -> l,s
1526 | _ -> raise Reduction.NotArity
1527
1528 let sort_of_arity env sigma c = snd (dest_arity env sigma c)
1529
1530 let whd_decompose_prod_n_assum env sigma n =
1531 let rec decrec env m ctx c = if Int.equal m 0 then (ctx,c) else
1532 match EConstr.kind sigma (whd_allnolet env sigma c) with
1533 | Prod (n,a,c0) ->
1534 let d = LocalAssum (n,a) in
1535 decrec (push_rel d env) (m-1) (Context.Rel.add d ctx) c0
1536 | LetIn (x,b,t,c) ->
1537 let d = LocalDef (x,b,t) in
1538 decrec (push_rel d env) m (Context.Rel.add d ctx) c
1539 | _ ->
1540 (* deal with situations of the form "(let x:=t in fun y => u) v", or even
1541 "(let x:=fun y => u in x) v", ...
1542 ideally, shouldn't we move instead the let-ins outside the redexes? *)
1543 let c' = whd_all env sigma c in
1544 if EConstr.eq_constr sigma c c' then invalid_arg "whd_decompose_prod_n_assum"
1545 else decrec env m ctx c'
1546 in
1547 decrec env n Context.Rel.empty
1548
1549 let whd_decompose_prod_n_decls env sigma n =
1550 let rec decrec env m ctx c = if Int.equal m 0 then (ctx,c) else
1551 match EConstr.kind sigma (whd_all env sigma c) with
1552 | Prod (n,a,c0) ->
1553 let d = LocalAssum (n,a) in
1554 decrec (push_rel d env) (m-1) (Context.Rel.add d ctx) c0
1555 | LetIn (x,b,t,c) ->
1556 let d = LocalDef (x,b,t) in
1557 decrec (push_rel d env) (m-1) (Context.Rel.add d ctx) c
1558 | _ ->
1559 (* deal with situations of the form "(let x:=t in fun y => u) v", or even
1560 "(let x:=fun y => u in x) v", ...
1561 ideally, shouldn't we move instead the let-ins outside the redexes? *)
1562 let c' = whd_all env sigma c in
1563 if EConstr.eq_constr sigma c c' then invalid_arg "whd_decompose_prod_n_decls"
1564 else decrec env m ctx c'
1565 in
1566 decrec env n Context.Rel.empty
1567
1568 let whd_decompose_lambda_n_assum env sigma n =
1569 let rec decrec env m ctx c = if Int.equal m 0 then (ctx,c) else
1570 match EConstr.kind sigma (whd_allnolet env sigma c) with
1571 | Lambda (n,a,c0) ->
1572 let d = LocalAssum (n,a) in
1573 decrec (push_rel d env) (m-1) (Context.Rel.add d ctx) c0
1574 | LetIn (x,b,t,c) ->
1575 let d = LocalDef (x,b,t) in
1576 decrec (push_rel d env) m (Context.Rel.add d ctx) c
1577 | _ ->
1578 (* deal with situations of the form "(let x:=t in fun y => u) v", or even
1579 "(let x:=fun y => u in x) v", ...
1580 ideally, shouldn't we move instead the let-ins outside the redexes? *)
1581 let c' = whd_all env sigma c in
1582 if EConstr.eq_constr sigma c c' then invalid_arg "whd_decompose_lambda_n_assum"
1583 else decrec env m ctx c'
1584 in
1585 decrec env n Context.Rel.empty
1586
1587 let is_sort env sigma t =
1588 match EConstr.kind sigma (whd_all env sigma t) with
1589 | Sort s -> true
1590 | _ -> false
1591
1592 let is_symbol env sigma c =
1593 let cb = EConstr.lookup_constant env sigma c in
1594 match cb.Declarations.const_body with
1595 | Declarations.Symbol _ -> true
1596 | _ -> false
1597
1598 (* reduction to head-normal-form allowing delta/zeta only in argument
1599 of case/fix (heuristic used by evar_conv) *)
1600
1601 let whd_betaiota_deltazeta_for_iota_state ts ?metas env sigma s =
1602 let all' = RedFlags.red_add_transparent RedFlags.all ts in
1603 (* Unset the sharing flag to get a call-by-name reduction. This matters for
1604 the shape of the generated term. *)
1605 let env' = Environ.set_typing_flags { (Environ.typing_flags env) with Declarations.share_reduction = false } env in
1606 let whd_opt c =
1607 let open CClosure in
1608 let infos = Evarutil.create_clos_infos env' sigma all' in
1609 let tab = create_tab () in
1610 let c = inject (EConstr.Unsafe.to_constr (Stack.zip sigma c)) in
1611 let (c, stk) = whd_stack infos tab c [] in
1612 match fterm_of c with
1613 | (FConstruct _ | FCoFix _) ->
1614 (* Non-neutral normal, can trigger reduction below *)
1615 let c = EConstr.of_constr (term_of_process c stk) in
1616 Some (decompose_app sigma c)
1617 | _ -> None
1618 in
1619 let rec whrec s =
1620 let (t, stack as s) = whd_state_gen RedFlags.betaiota ?metas env sigma s in
1621 let rewrite_step =
1622 match kind sigma t with
1623 | Const (cst, u) when is_symbol env sigma cst ->
1624 let r = Environ.lookup_rewrite_rules cst env in
1625 let red_fun ctx = whd_state_gen RedFlags.all ?metas (push_rel_context ctx env) sigma in
1626 begin match apply_rules red_fun env sigma u r stack with
1627 | r -> Some r
1628 | exception PatternFailure -> None
1629 end
1630 | _ -> None
1631 in
1632 match rewrite_step with
1633 | Some r -> whrec r
1634 | None ->
1635 match Stack.strip_app stack with
1636 |args, (Stack.Case _ :: _ as stack') ->
1637 begin match whd_opt (t, args) with
1638 | Some (t_o, args) when reducible_mind_case sigma t_o -> whrec (t_o, Stack.append_app args stack')
1639 | (Some _ | None) -> s
1640 end
1641 |args, (Stack.Fix _ :: _ as stack') ->
1642 begin match whd_opt (t, args) with
1643 | Some (t_o, args) when isConstruct sigma t_o -> whrec (t_o, Stack.append_app args stack')
1644 | (Some _ | None) -> s
1645 end
1646 |args, (Stack.Proj (p,_) :: stack'') ->
1647 begin match whd_opt (t, args) with
1648 | Some (t_o, args) when isConstruct sigma t_o ->
1649 whrec (args.(Projection.npars p + Projection.arg p), stack'')
1650 | (Some _ | None) -> s
1651 end
1652 |_, ((Stack.App _|Stack.Primitive _) :: _|[]) -> s
1653 in
1654 whrec s
1655
1656 let find_conclusion env sigma =
1657 let rec decrec env c =
1658 let t = whd_all env sigma c in
1659 match EConstr.kind sigma t with
1660 | Prod (x,t,c0) -> decrec (push_rel (LocalAssum (x,t)) env) c0
1661 | Lambda (x,t,c0) -> decrec (push_rel (LocalAssum (x,t)) env) c0
1662 | t -> t
1663 in
1664 decrec env
1665
1666 let is_arity env sigma c =
1667 match find_conclusion env sigma c with
1668 | Sort _ -> true
1669 | _ -> false
1670
1671 module Infer = struct
1672
1673 open Sorts
1674
1675 let get_algebraic = function
1676 | Prop | SProp -> assert false
1677 | Set -> Universe.type0
1678 | QSort (_, u) | Type u -> u
1679
1680 let is_impredicative_sort = function
1681 | Prop | SProp -> true
1682 | _ -> false
1683 (* Only used for universe level comparisons, so impredicative set is still fine *)
1684
1685 let enforce_eq_sort s1 s2 (qcsts, ucsts as cst) = match s1, s2 with
1686 | QSort (q1, u1), s2 ->
1687 let q2 = quality s2 in
1688 let qcsts = UVars.QPairSet.add (QVar q1, q2) qcsts in
1689 let ucsts = if is_impredicative_sort s2 then ucsts else UnivSubst.enforce_eq u1 (get_algebraic s2) ucsts in
1690 (qcsts, ucsts)
1691 | s1, QSort (q2, u2) ->
1692 let q1 = quality s1 in
1693 let qcsts = UVars.QPairSet.add (q1, QVar q2) qcsts in
1694 let ucsts = if is_impredicative_sort s2 then ucsts else UnivSubst.enforce_eq (get_algebraic s1) u2 ucsts in
1695 (qcsts, ucsts)
1696 | (SProp, SProp) | (Prop, Prop) | (Set, Set) -> cst
1697 | (((Prop | Set | Type _) as s1), (Prop | SProp as s2))
1698 | ((Prop | SProp as s1), ((Prop | Set | Type _) as s2)) ->
1699 raise (UGraph.UniverseInconsistency (None, (Eq, s1, s2, None)))
1700 | (Set | Type _), (Set | Type _) ->
1701 let ucsts' = UnivSubst.enforce_eq (get_algebraic s1) (get_algebraic s2) ucsts in
1702 if ucsts == ucsts' then cst else (qcsts, ucsts')
1703
1704 let enforce_leq_alg_sort s1 s2 g = match s1, s2 with
1705 | QSort (q1, u1), s2 ->
1706 let q2 = quality s2 in
1707 let qcsts = UVars.QPairSet.singleton (QVar q1, q2) in
1708 let ucsts, g = if is_impredicative_sort s2 then UnivConstraints.empty, g else UGraph.enforce_leq_alg u1 (get_algebraic s2) g in
1709 (qcsts, ucsts), g
1710 | s1, QSort (q2, u2) ->
1711 let q1 = quality s1 in
1712 let qcsts = UVars.QPairSet.singleton (q1, QVar q2) in
1713 let ucsts, g = if is_impredicative_sort s2 then UnivConstraints.empty, g else UGraph.enforce_leq_alg (get_algebraic s1) u2 g in
1714 (qcsts, ucsts), g
1715 | (SProp, SProp) | (Prop, Prop) | (Set, Set) -> (UVars.QPairSet.empty, Univ.UnivConstraints.empty), g
1716 | (Prop, (Set | Type _)) -> (UVars.QPairSet.empty, Univ.UnivConstraints.empty), g
1717 | (((Prop | Set | Type _) as s1), (Prop | SProp as s2))
1718 | ((SProp as s1), ((Prop | Set | Type _) as s2)) ->
1719 raise (UGraph.UniverseInconsistency (None, (Le, s1, s2, None)))
1720 | (Set | Type _), (Set | Type _) ->
1721 let ucsts, g = UGraph.enforce_leq_alg (get_algebraic s1) (get_algebraic s2) g in
1722 (UVars.QPairSet.empty, ucsts), g
1723
1724 open Conversion
1725
1726 let check_eq_qualities qcst =
1727 let check (q1, q2) = Quality.equal q1 q2 in
1728 UVars.QPairSet.for_all check qcst
1729
1730 let infer_eq (univs, cstrs as cuniv) s s' =
1731 if UGraph.check_eq_sort Sorts.Quality.equal univs s s' then Result.Ok cuniv
1732 else try
1733 let qcsts', ucstrs' as cstrs' = enforce_eq_sort s s' (UVars.QPairSet.empty, Univ.UnivConstraints.empty) in
1734 if check_eq_qualities qcsts' then
1735 Result.Ok (UGraph.merge_constraints ucstrs' univs, UnivConstraints.union cstrs ucstrs')
1736 else Result.Error None
1737 with UGraph.UniverseInconsistency err -> Result.Error (Some (Univ err))
1738
1739 let infer_leq (univs, cstrs as cuniv) s s' =
1740 if UGraph.check_leq_sort Sorts.Quality.equal univs s s' then Result.Ok cuniv
1741 else match enforce_leq_alg_sort s s' univs with
1742 | (qcsts, ucsts), ugraph ->
1743 if check_eq_qualities qcsts then
1744 Result.Ok (univs, UnivConstraints.union cstrs ucsts)
1745 else Result.Error None
1746 | exception UGraph.UniverseInconsistency err -> Result.Error (Some (Univ err))
1747
1748 let infer_cmp_universes pb s0 s1 cuniv =
1749 match pb with
1750 | CUMUL -> infer_leq cuniv s0 s1
1751 | CONV -> infer_eq cuniv s0 s1
1752
1753 let infer_convert_instances ~flex u u' (univs, cstrs as cuniv) =
1754 if flex then
1755 if UGraph.check_eq_instances Sorts.Quality.equal univs u u' then Result.Ok cuniv
1756 else Result.Error None
1757 else try
1758 let qcstrs, ucstrs as cstrs' = UVars.enforce_eq_instances u u' (UVars.QPairSet.empty, Univ.UnivConstraints.empty) in
1759 if check_eq_qualities qcstrs then
1760 Result.Ok (UGraph.merge_constraints ucstrs univs, UnivConstraints.union cstrs ucstrs)
1761 else Result.Error None
1762 with UGraph.UniverseInconsistency err -> Result.Error (Some (Univ err))
1763
1764
1765 let infer_inductive_instances cv_pb variance u1 u2 (univs,csts) =
1766 let qcsts, csts' = get_cumulativity_constraints cv_pb variance u1 u2 in
1767 if check_eq_qualities qcsts then
1768 match UGraph.merge_constraints csts' univs with
1769 | univs -> Result.Ok (univs, Univ.UnivConstraints.union csts csts')
1770 | exception (UGraph.UniverseInconsistency err) -> Result.Error (Some (Univ err))
1771 else Result.Error None
1772
1773 let inferred_universes =
1774 { compare_sorts = infer_cmp_universes;
1775 compare_instances = infer_convert_instances;
1776 compare_cumul_instances = infer_inductive_instances; }
1777
1778 end
1779
1780 let inferred_universes = Infer.inferred_universes
1781
1782 let eta_expand env sigma t ty =
1783 of_constr @@ Reduction.eta_expand ~evars:(Evd.evar_handler sigma) env
1784 (EConstr.Unsafe.to_constr t) (EConstr.Unsafe.to_constr ty)
1785
1786 let eta_expand_instantiation env sigma inst ctxt =
1787 let inst = Array.map (EConstr.Unsafe.to_constr) inst in
1788 let ctxt = List.map (EConstr.Unsafe.to_rel_decl) ctxt in
1789 let eta_inst = Termops.eta_expand_instantiation ~evars:(Evd.evar_handler sigma) env inst ctxt in
1790 Array.map of_constr eta_inst