Debian Codegraph @

engine/evd.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 Pp
12 open CErrors
13 open Util
14 open Names
15 open Constr
16 open Vars
17 open Environ
18
19 module NamedDecl = Context.Named.Declaration
20
21 type econstr = constr
22 type etypes = types
23 type esorts = Sorts.t
24 type erelevance = Sorts.relevance
25 type einstance = UVars.Instance.t
26 type 'a puniverses = 'a * einstance
27
28 (** Generic filters *)
29 module Filter :
30 sig
31 type t
32 val equal : t -> t -> bool
33 val identity : t
34 val filter_list : t -> 'a list -> 'a list
35 val filter_array : t -> 'a array -> 'a array
36 val filter_slist : t -> 'a SList.t -> 'a SList.t
37 val extend : int -> t -> t
38 val compose : t -> t -> t
39 val apply_subfilter : t -> bool list -> t
40 val restrict_upon : t -> int -> (int -> bool) -> t option
41 val map_along : (bool -> 'a -> bool) -> t -> 'a list -> t
42 val make : bool list -> t
43 val repr : t -> bool list option
44
45 type compact =
46 | Empty
47 | TCons of int * compact
48 | FCons of int * compact
49
50 val unfold : t -> compact option
51
52 end =
53 struct
54
55 type compact =
56 | Empty
57 | TCons of int * compact
58 | FCons of int * compact
59
60 let rec compact l = match l with
61 | [] -> Empty
62 | true :: l ->
63 begin match compact l with
64 | TCons (n, c) -> TCons (n + 1, c)
65 | (Empty | FCons _ as c) -> TCons (1, c)
66 end
67 | false :: l ->
68 begin match compact l with
69 | FCons (n, c) -> FCons (n + 1, c)
70 | (Empty | TCons _ as c) -> FCons (1, c)
71 end
72
73 type t = {
74 data : bool list option;
75 compact : compact;
76 }
77 (** We guarantee through the interface that if a filter is [Some _] then it
78 contains at least one [false] somewhere. *)
79
80 let identity = { data = None; compact = Empty }
81
82 let rec equal l1 l2 = match l1, l2 with
83 | [], [] -> true
84 | h1 :: l1, h2 :: l2 ->
85 (if h1 then h2 else not h2) && equal l1 l2
86 | _ -> false
87
88 let equal l1 l2 = match l1.data, l2.data with
89 | None, None -> true
90 | Some _, None | None, Some _ -> false
91 | Some l1, Some l2 -> equal l1 l2
92
93 let rec is_identity = function
94 | [] -> true
95 | true :: l -> is_identity l
96 | false :: _ -> false
97
98 let normalize f =
99 if is_identity f then identity
100 else { data = Some f; compact = compact f }
101
102 let filter_list f l = match f.data with
103 | None -> l
104 | Some f -> CList.filter_with f l
105
106 let filter_array f v = match f.data with
107 | None -> v
108 | Some f -> CArray.filter_with f v
109
110 let filter_slist f l = match f.data with
111 | None -> l
112 | Some f ->
113 let rec filter f l = match f, SList.view l with
114 | [], None -> SList.empty
115 | true :: f, Some (o, l) -> SList.cons_opt o (filter f l)
116 | false :: f, Some (_, l) -> filter f l
117 | _ :: _, None | [], Some _ -> invalid_arg "List.filter_with"
118 in
119 filter f l
120
121 let rec extend n l =
122 if n = 0 then l
123 else extend (pred n) (true :: l)
124
125 let extend n f = match f.data with
126 | None -> identity
127 | Some f0 ->
128 let compact = match f.compact with
129 | Empty -> assert false
130 | TCons (m, c) -> TCons (n + m, c)
131 | c -> TCons (n, c)
132 in
133 { data = Some (extend n f0); compact }
134
135 let compose f1 f2 = match f1.data with
136 | None -> f2
137 | Some f1 ->
138 match f2.data with
139 | None -> identity
140 | Some f2 -> normalize (CList.filter_with f1 f2)
141
142 let apply_subfilter_array filter subfilter =
143 (* In both cases we statically know that the argument will contain at
144 least one [false] *)
145 match filter.data with
146 | None ->
147 let l = Array.to_list subfilter in
148 { data = Some l; compact = compact l }
149 | Some f ->
150 let len = Array.length subfilter in
151 let fold b (i, ans) =
152 if b then
153 let () = assert (0 <= i) in
154 (pred i, Array.unsafe_get subfilter i :: ans)
155 else
156 (i, false :: ans)
157 in
158 let data = snd (List.fold_right fold f (pred len, [])) in
159 { data = Some data; compact = compact data }
160
161 let apply_subfilter filter subfilter =
162 apply_subfilter_array filter (Array.of_list subfilter)
163
164 let restrict_upon f len p =
165 let newfilter = Array.init len p in
166 if Array.for_all (fun id -> id) newfilter then None
167 else
168 Some (apply_subfilter_array f newfilter)
169
170 let map_along f flt l =
171 let ans = match flt.data with
172 | None -> List.map (fun x -> f true x) l
173 | Some flt -> List.map2 f flt l
174 in
175 normalize ans
176
177 let make l = normalize l
178
179 let repr f = f.data
180
181 let unfold f = match f.data with
182 | None -> None
183 | Some _ -> Some f.compact
184
185 end
186
187 module Abstraction = struct
188
189 type abstraction =
190 | Abstract
191 | Imitate
192
193 type t = abstraction list
194
195 let identity = []
196
197 let abstract_last l = Abstract :: l
198 end
199
200 (* The kinds of existential variables are now defined in [Evar_kinds] *)
201
202 (* The type of mappings for existential variables *)
203
204 module Store = Store.Make ()
205
206 let string_of_existential evk = "?X" ^ string_of_int (Evar.repr evk)
207
208 type defined = [ `defined ]
209 type undefined = [ `undefined ]
210
211 type _ evar_body =
212 | Evar_empty : undefined evar_body
213 | Evar_defined : econstr -> defined evar_body
214
215 type (_, 'a) when_undefined =
216 | Defined : (defined, 'a) when_undefined
217 | Undefined : 'a -> (undefined, 'a) when_undefined
218
219 type 'a evar_info = {
220 evar_concl : ('a, constr) when_undefined;
221 evar_hyps : named_context_val;
222 evar_body : 'a evar_body;
223 evar_filter : Filter.t;
224 evar_abstract_arguments : ('a, Abstraction.t) when_undefined;
225 evar_source : Evar_kinds.t Loc.located;
226 evar_candidates : ('a, constr list option) when_undefined; (* if not None, list of allowed instances *)
227 evar_relevance: Sorts.relevance;
228 }
229
230 type any_evar_info = EvarInfo : 'a evar_info -> any_evar_info
231
232 let instance_mismatch () =
233 anomaly (Pp.str "Signature and its instance do not match.")
234
235 let evar_concl evi = match evi.evar_concl with
236 | Undefined c -> c
237
238 let evar_filter evi = evi.evar_filter
239
240 let evar_body evi = evi.evar_body
241
242 let evar_context evi = named_context_of_val evi.evar_hyps
243
244 let evar_filtered_context evi =
245 Filter.filter_list (evar_filter evi) (evar_context evi)
246
247 let evar_candidates evi = match evi.evar_candidates with
248 | Undefined c -> c
249
250 let evar_abstract_arguments evi = match evi.evar_abstract_arguments with
251 | Undefined c -> c
252
253 let evar_relevance evi = evi.evar_relevance
254
255 let evar_hyps evi = evi.evar_hyps
256
257 let evar_filtered_hyps evi = match Filter.repr (evar_filter evi) with
258 | None -> evar_hyps evi
259 | Some filter ->
260 let rec make_hyps filter ctxt = match filter, ctxt with
261 | [], [] -> empty_named_context_val
262 | false :: filter, _ :: ctxt -> make_hyps filter ctxt
263 | true :: filter, decl :: ctxt ->
264 let hyps = make_hyps filter ctxt in
265 push_named_context_val decl hyps
266 | _ -> instance_mismatch ()
267 in
268 make_hyps filter (evar_context evi)
269
270 let evar_env env evi =
271 Environ.reset_with_named_context evi.evar_hyps env
272
273 let evar_filtered_env env evi = Environ.reset_with_named_context (evar_filtered_hyps evi) env
274
275 let evar_identity_subst evi =
276 let len = match Filter.repr evi.evar_filter with
277 | None -> List.length @@ Environ.named_context_of_val evi.evar_hyps
278 | Some f -> List.count (fun b -> b) f
279 in
280 SList.defaultn len SList.empty
281
282 let map_evar_body (type a) f : a evar_body -> a evar_body = function
283 | Evar_empty -> Evar_empty
284 | Evar_defined d -> Evar_defined (f d)
285
286 let map_when_undefined (type a b) f : (a, b) when_undefined -> (a, b) when_undefined = function
287 | Defined -> Defined
288 | Undefined x -> Undefined (f x)
289
290 let map_evar_info f evi =
291 {evi with
292 evar_body = map_evar_body f evi.evar_body;
293 evar_hyps = map_named_val (fun d -> NamedDecl.map_constr f d) evi.evar_hyps;
294 evar_concl = map_when_undefined f evi.evar_concl;
295 evar_candidates = map_when_undefined (fun c -> Option.map (List.map f) c) evi.evar_candidates }
296
297 (* This exception is raised by *.existential_value *)
298 exception NotInstantiatedEvar
299
300 (* Note: let-in contributes to the instance *)
301 let evar_instance_array empty push info args =
302 let rec instrec pos filter args = match filter with
303 | Filter.Empty -> if SList.is_empty args then empty else instance_mismatch ()
304 | Filter.TCons (n, filter) -> instpush pos n filter args
305 | Filter.FCons (n, filter) -> instrec (pos + n) filter args
306 and instpush pos n filter args =
307 if n <= 0 then instrec pos filter args
308 else match args with
309 | SList.Nil -> assert false
310 | SList.Cons (c, args) ->
311 let d = Range.get info.evar_hyps.env_named_idx pos in
312 let id = NamedDecl.get_id d in
313 push id c (instpush (pos + 1) (n - 1) filter args)
314 | SList.Default (m, args) ->
315 if m <= n then instpush (pos + m) (n - m) filter args
316 else instrec (pos + n) filter (SList.defaultn (m - n) args)
317 in
318 match Filter.unfold (evar_filter info) with
319 | None ->
320 let rec instance pos args = match args with
321 | SList.Nil -> empty
322 | SList.Cons (c, args) ->
323 let d = Range.get info.evar_hyps.env_named_idx pos in
324 let id = NamedDecl.get_id d in
325 push id c (instance (pos + 1) args)
326 | SList.Default (n, args) -> instance (pos + n) args
327 in
328 instance 0 args
329 | Some filter ->
330 instrec 0 filter args
331
332 let make_evar_instance_array info args =
333 if SList.is_default args then []
334 else
335 let push id c l = if isVarId id c then l else (id, c) :: l in
336 evar_instance_array [] push info args
337
338 type 'a in_ustate = 'a * UState.t
339
340 (*************************)
341 (* Unification state *)
342
343 type conv_pb = Conversion.conv_pb
344 type evar_constraint = conv_pb * Environ.env * constr * constr
345
346 (** Exporting from Evarnames. *)
347 let generate_goal_names = Evarnames.generate_goal_names
348
349 module EvMap = Evar.Map
350
351 type evar_flags =
352 { obligation_evars : Evar.Set.t;
353 aliased_evars : Evar.t Evar.Map.t;
354 typeclass_evars : Evar.Set.t;
355 impossible_case_evars : Evar.Set.t;
356 rewrite_rule_evars : Evar.Set.t;
357 }
358
359 type side_effect_role =
360 | Schema of inductive * string
361
362 type side_effects = {
363 seff_safeenv : Safe_typing.safe_environment option;
364 (* If seff_safeenv = Some senv, then senv = Global.safe_env + seff_private *)
365 seff_labels : Id.Set.t;
366 seff_private : Safe_typing.private_constants;
367 seff_roles : side_effect_role Cmap_env.t;
368 seff_univs : UState.named_universes_entry Cmap_env.t;
369 }
370
371 module FutureGoals : sig
372
373 type t
374
375 val comb : t -> Evar.t list
376
377 val map_filter : (Evar.t -> Evar.t option) -> t -> t
378 (** Applies a function on the future goals *)
379
380 val filter : (Evar.t -> bool) -> t -> t
381 (** Applies a filter on the future goals *)
382
383 type stack
384
385 val empty_stack : stack
386
387 val push : stack -> stack
388 val pop : stack -> t * stack
389
390 val add : Evar.t -> stack -> stack
391 val remove : Evar.t -> stack -> stack
392
393 val fold : ('a -> Evar.t -> 'a) -> 'a -> stack -> 'a
394
395 val pr_stack : stack -> Pp.t
396
397 end = struct
398
399 type t = {
400 uid : int;
401 comb : Evar.t Int.Map.t;
402 revmap : int Evar.Map.t;
403 }
404
405 let comb g =
406 (* Keys are reversed, highest number is last introduced *)
407 Int.Map.fold (fun _ evk accu -> evk :: accu) g.comb []
408
409 type stack = t list
410
411 let set f = function
412 | [] -> anomaly Pp.(str"future_goals stack should not be empty")
413 | hd :: tl ->
414 f hd :: tl
415
416 let add evk stack =
417 let add fgl =
418 let comb = Int.Map.add fgl.uid evk fgl.comb in
419 let revmap = Evar.Map.add evk fgl.uid fgl.revmap in
420 let uid = fgl.uid + 1 in
421 let () = assert (0 <= uid) in
422 { comb; revmap; uid }
423 in
424 set add stack
425
426 let remove e stack =
427 let remove fgl =
428 let comb, revmap = match Evar.Map.find e fgl.revmap with
429 | index -> (Int.Map.remove index fgl.comb, Evar.Map.remove e fgl.revmap)
430 | exception Not_found -> fgl.comb, fgl.revmap
431 in
432 { comb; revmap; uid = fgl.uid }
433 in
434 List.map remove stack
435
436 let empty = {
437 uid = 0;
438 comb = Int.Map.empty;
439 revmap = Evar.Map.empty;
440 }
441
442 let empty_stack = [empty]
443
444 let push stack = empty :: stack
445
446 let pop stack =
447 match stack with
448 | [] -> anomaly Pp.(str"future_goals stack should not be empty")
449 | hd :: tl ->
450 hd, tl
451
452 let fold f acc stack =
453 let future_goals = List.hd stack in
454 List.fold_left f acc (comb future_goals)
455
456 let filter f fgl =
457 let fold index evk (comb, revmap) =
458 if f evk then (comb, revmap)
459 else (Int.Map.remove index comb, Evar.Map.remove evk revmap)
460 in
461 let (comb, revmap) = Int.Map.fold fold fgl.comb (fgl.comb, fgl.revmap) in
462 { comb; revmap; uid = fgl.uid }
463
464 let map_filter f fgl =
465 let fold index evk (comb, revmap) = match f evk with
466 | None -> (comb, revmap)
467 | Some evk' ->
468 (Int.Map.add index evk' comb, Evar.Map.add evk' index revmap)
469 in
470 let (comb, revmap) = Int.Map.fold fold fgl.comb (Int.Map.empty, Evar.Map.empty) in
471 { comb; revmap; uid = fgl.uid }
472
473 let pr_stack stack =
474 let open Pp in
475 let pr_future_goals fgl =
476 let comb = comb fgl in
477 prlist_with_sep spc Evar.print comb
478 in
479 if List.is_empty stack then str"(empty stack)"
480 else prlist_with_sep (fun () -> str"||") pr_future_goals stack
481
482 end
483
484 type evar_map = {
485 (* Existential variables *)
486 defn_evars : defined evar_info EvMap.t;
487 undf_evars : undefined evar_info EvMap.t;
488 evar_names : Evarnames.t;
489 candidate_evars : Evar.Set.t; (* The subset of undefined evars with a non-empty candidate list. *)
490 (** Universes *)
491 universes : UState.t;
492 (** Conversion problems *)
493 conv_pbs : evar_constraint list;
494 last_mods : Evar.Set.t;
495 evar_flags : evar_flags;
496 (** Interactive proofs *)
497 effects : side_effects;
498 future_goals : FutureGoals.stack; (** list of newly created evars, to be
499 eventually turned into goals if not solved.*)
500 given_up : Evar.Set.t;
501 shelf : Evar.t list list;
502 extras : Store.t;
503 }
504
505 let find d e =
506 try EvarInfo (EvMap.find e d.undf_evars)
507 with Not_found -> EvarInfo (EvMap.find e d.defn_evars)
508
509 let rec thin_val = function
510 | [] -> []
511 | (id, c) :: tl ->
512 match Constr.kind c with
513 | Constr.Var v ->
514 if Id.equal id v then thin_val tl
515 else (id, make_substituend c) :: (thin_val tl)
516 | _ -> (id, make_substituend c) :: (thin_val tl)
517
518 let rec find_var id = function
519 | [] -> raise_notrace Not_found
520 | (idc, c) :: subst ->
521 if Id.equal id idc then c
522 else find_var id subst
523
524 let replace_vars sigma var_alist x =
525 let var_alist = thin_val var_alist in
526 match var_alist with
527 | [] -> x
528 | _ ->
529 let rec substrec n c = match Constr.kind c with
530 | Constr.Var id ->
531 begin match find_var id var_alist with
532 | var -> (lift_substituend n var)
533 | exception Not_found -> c
534 end
535 | Constr.Evar (evk, args) ->
536 let EvarInfo evi = find sigma evk in
537 let args' = substrec_instance n (evar_filtered_context evi) args in
538 if args' == args then c
539 else Constr.mkEvar (evk, args')
540 | _ -> Constr.map_with_binders succ substrec n c
541
542 and substrec_instance n ctx args = match ctx, SList.view args with
543 | [], None -> SList.empty
544 | decl :: ctx, Some (c, args) ->
545 let c' = match c with
546 | None ->
547 begin match find_var (NamedDecl.get_id decl) var_alist with
548 | var -> Some (lift_substituend n var)
549 | exception Not_found -> None
550 end
551 | Some c ->
552 let c' = substrec n c in
553 if isVarId (NamedDecl.get_id decl) c' then None
554 else Some c'
555 in
556 SList.cons_opt c' (substrec_instance n ctx args)
557 | _ :: _, None | [], Some _ -> instance_mismatch ()
558 in
559 substrec 0 x
560
561 let instantiate_evar_array sigma info c args =
562 let inst = make_evar_instance_array info args in
563 match inst with
564 | [] -> c
565 | _ -> replace_vars sigma inst c
566
567 let expand_existential sigma (evk, args) =
568 let EvarInfo evi = find sigma evk in
569 let rec expand ctx args = match ctx, SList.view args with
570 | [], None -> []
571 | _ :: ctx, Some (Some c, args) -> c :: expand ctx args
572 | decl :: ctx, Some (None, args) -> mkVar (NamedDecl.get_id decl) :: expand ctx args
573 | [], Some _ | _ :: _, None -> instance_mismatch ()
574 in
575 expand (evar_filtered_context evi) args
576
577 let expand_existential0 = expand_existential
578
579 (*** Lifting primitive from Evar.Map. ***)
580
581 let add_name evk basename ?parent evd =
582 { evd with evar_names = Evarnames.add basename evk ?parent evd.evar_names }
583
584 let transfer_name evk evk' evd =
585 { evd with evar_names = Evarnames.transfer_name evk evk' evd.evar_names }
586
587 let add_with_name (type a) ?name ?parent ~typeclass_candidate ~rrpat d e (i : a evar_info) = match i.evar_body with
588 | Evar_empty ->
589 let evar_names =
590 match name with
591 | Some (basename, fresh) ->
592 (* If fresh (i.e. coming from ?[?ident] syntax), we first check for conflicts. *)
593 if fresh then
594 Evarnames.add_fresh basename e ?parent d.evar_names
595 else
596 Evarnames.add basename e ?parent d.evar_names
597 | None -> d.evar_names
598 in
599 let evar_flags =
600 if typeclass_candidate then
601 let flags = d.evar_flags in
602 { flags with typeclass_evars = Evar.Set.add e flags.typeclass_evars }
603 else d.evar_flags
604 in
605 let evar_flags =
606 if rrpat then
607 { evar_flags with rewrite_rule_evars = Evar.Set.add e evar_flags.rewrite_rule_evars }
608 else evar_flags
609 in
610 let evar_flags = match i.evar_source with
611 | _, ImpossibleCase ->
612 { evar_flags with impossible_case_evars = Evar.Set.add e evar_flags.impossible_case_evars }
613 | _ -> evar_flags
614 in
615 let candidate_evars = match i.evar_candidates with
616 | Undefined None -> Evar.Set.remove e d.candidate_evars
617 | Undefined (Some _) -> Evar.Set.add e d.candidate_evars
618 in
619 { d with undf_evars = EvMap.add e i d.undf_evars; evar_names; evar_flags; candidate_evars }
620 | Evar_defined _ ->
621 let evar_names = Evarnames.remove e d.evar_names in
622 { d with defn_evars = EvMap.add e i d.defn_evars; evar_names }
623
624 (** Evd.add is a low-level function mainly used to update the evar_info
625 associated to an evar, so we prevent registering its typeclass status. *)
626 let add d e i = add_with_name ~typeclass_candidate:false ~rrpat:false d e i
627
628 (*** Evar flags: typeclasses, aliased or obligation flag *)
629
630 let get_typeclass_evars evd = evd.evar_flags.typeclass_evars
631
632 let set_typeclass_evars evd tcs =
633 let flags = evd.evar_flags in
634 let tcs = Evar.Set.filter (fun evk -> Evar.Map.mem evk evd.undf_evars) tcs in
635 { evd with evar_flags = { flags with typeclass_evars = tcs } }
636
637 let is_typeclass_evar evd evk =
638 let flags = evd.evar_flags in
639 Evar.Set.mem evk flags.typeclass_evars
640
641 let get_obligation_evars evd = evd.evar_flags.obligation_evars
642
643 let set_obligation_evar evd evk =
644 let flags = evd.evar_flags in
645 let evar_flags = { flags with obligation_evars = Evar.Set.add evk flags.obligation_evars } in
646 { evd with evar_flags }
647
648 let is_obligation_evar evd evk =
649 let flags = evd.evar_flags in
650 Evar.Set.mem evk flags.obligation_evars
651
652 let get_impossible_case_evars evd = evd.evar_flags.impossible_case_evars
653
654 let get_rewrite_rule_evars evd = evd.evar_flags.rewrite_rule_evars
655
656 let is_rewrite_rule_evar evd evk =
657 let flags = evd.evar_flags in
658 Evar.Set.mem evk flags.rewrite_rule_evars
659
660 (** Inheritance of flags: for evar-evar and restriction cases *)
661
662 let inherit_evar_flags evar_flags evk evk' =
663 if Evar.Set.mem evk evar_flags.rewrite_rule_evars then
664 CErrors.anomaly Pp.(str "Tried to define or restrict a rewrite rule evar.");
665 let evk_typeclass = Evar.Set.mem evk evar_flags.typeclass_evars in
666 let evk_obligation = Evar.Set.mem evk evar_flags.obligation_evars in
667 let evk_impossible = Evar.Set.mem evk evar_flags.impossible_case_evars in
668 let aliased_evars = Evar.Map.add evk evk' evar_flags.aliased_evars in
669 let typeclass_evars =
670 if evk_typeclass then
671 let typeclass_evars = Evar.Set.remove evk evar_flags.typeclass_evars in
672 Evar.Set.add evk' typeclass_evars
673 else evar_flags.typeclass_evars
674 in
675 let obligation_evars =
676 if evk_obligation then
677 let obligation_evars = Evar.Set.remove evk evar_flags.obligation_evars in
678 Evar.Set.add evk' obligation_evars
679 else evar_flags.obligation_evars
680 in
681 let impossible_case_evars =
682 if evk_impossible then
683 let impossible_case_evars = Evar.Set.remove evk evar_flags.impossible_case_evars in
684 Evar.Set.add evk' impossible_case_evars
685 else evar_flags.impossible_case_evars
686 in
687 let rewrite_rule_evars = evar_flags.rewrite_rule_evars in
688 { obligation_evars; aliased_evars; typeclass_evars; impossible_case_evars; rewrite_rule_evars }
689
690 (** Removal: in all other cases of definition *)
691
692 let remove_evar_flags evk evar_flags =
693 if Evar.Set.mem evk evar_flags.rewrite_rule_evars then
694 CErrors.anomaly Pp.(str "Tried to define or restrict a rewrite rule evar.");
695 { typeclass_evars = Evar.Set.remove evk evar_flags.typeclass_evars;
696 obligation_evars = Evar.Set.remove evk evar_flags.obligation_evars;
697 impossible_case_evars = Evar.Set.remove evk evar_flags.impossible_case_evars;
698 (* Aliasing information is kept. *)
699 aliased_evars = evar_flags.aliased_evars;
700 (* Cannot be a rewrite rule evar *)
701 rewrite_rule_evars = evar_flags.rewrite_rule_evars
702 }
703
704 (** New evars *)
705
706 let evar_counter_summary_name = "evar counter"
707
708 (* Generator of existential names *)
709 let evar_ctr, evar_counter_summary_tag = Summary.ref_tag 0 ~name:evar_counter_summary_name
710 let new_untyped_evar () = incr evar_ctr; Evar.unsafe_of_int !evar_ctr
711
712 let default_source = Loc.tag @@ Evar_kinds.InternalHole
713
714 let remove d e =
715 let undf_evars = EvMap.remove e d.undf_evars in
716 let defn_evars = EvMap.remove e d.defn_evars in
717 let future_goals = FutureGoals.remove e d.future_goals in
718 let evar_flags = remove_evar_flags e d.evar_flags in
719 let candidate_evars = Evar.Set.remove e d.candidate_evars in
720 { d with undf_evars; defn_evars; future_goals;
721 evar_flags; candidate_evars }
722
723 let find_defined d e = EvMap.find_opt e d.defn_evars
724
725 let find_undefined d e = EvMap.find e d.undf_evars
726
727 let mem d e = EvMap.mem e d.undf_evars || EvMap.mem e d.defn_evars
728
729 let undefined_map d = d.undf_evars
730
731 let defined_map d = d.defn_evars
732
733 let drop_all_defined d = { d with defn_evars = EvMap.empty }
734
735 (* spiwack: not clear what folding over an evar_map, for now we shall
736 simply fold over the inner evar_map. *)
737 let fold f d a =
738 let f evk evi accu = f evk (EvarInfo evi) accu in
739 EvMap.fold f d.defn_evars (EvMap.fold f d.undf_evars a)
740
741 let fold_undefined f d a = EvMap.fold f d.undf_evars a
742
743 type map = { map : 'r. Evar.t -> 'r evar_info -> 'r evar_info }
744
745 let raw_map f d =
746 let defn_evars = EvMap.Smart.mapi f.map d.defn_evars in
747 let undf_evars = EvMap.Smart.mapi f.map d.undf_evars in
748 { d with defn_evars; undf_evars; }
749
750 let raw_map_undefined f d =
751 { d with undf_evars = EvMap.Smart.mapi f d.undf_evars; }
752
753 let is_evar = mem
754
755 let is_defined d e = EvMap.mem e d.defn_evars
756
757 let is_undefined d e = EvMap.mem e d.undf_evars
758
759 let existential_opt_value d (n, args) =
760 match EvMap.find_opt n d.defn_evars with
761 | None -> None
762 | Some info ->
763 let Evar_defined c = evar_body info in
764 Some (instantiate_evar_array d info c args)
765
766 let existential_value d ev = match existential_opt_value d ev with
767 | None -> raise NotInstantiatedEvar
768 | Some v -> v
769
770 let existential_opt_value0 = existential_opt_value
771
772 let existential_expand_value0 sigma (evk, args) = match existential_opt_value sigma (evk, args) with
773 | None ->
774 let args = expand_existential sigma (evk, args) in
775 CClosure.EvarUndefined (evk, args)
776 | Some c -> CClosure.EvarDefined c
777
778 let mkLEvar sigma (evk, args) =
779 let EvarInfo evi = find sigma evk in
780 let fold decl arg accu =
781 if isVarId (NamedDecl.get_id decl) arg then SList.default accu
782 else SList.cons arg accu
783 in
784 let args = List.fold_right2 fold (evar_filtered_context evi) args SList.empty in
785 mkEvar (evk, args)
786
787 let is_relevance_irrelevant sigma r =
788 match UState.nf_relevance sigma.universes r with
789 | Irrelevant -> true
790 | Relevant | RelevanceVar _ -> false
791
792 let get_senv_side_effects eff = match eff.seff_safeenv with
793 | Some senv -> senv
794 | None ->
795 let (_, senv) = Safe_typing.export_private_constants eff.seff_private (Global.safe_env ()) in
796 senv
797
798 let evar_handler sigma =
799 let evar_expand ev = existential_expand_value0 sigma ev in
800 let qvar_irrelevant q = is_relevance_irrelevant sigma (Sorts.RelevanceVar q) in
801 let evar_irrelevant (evk, _) = match find sigma evk with
802 | EvarInfo evi -> is_relevance_irrelevant sigma evi.evar_relevance
803 | exception Not_found -> false (* Should be an anomaly *)
804 in
805 let evar_repack ev = mkLEvar sigma ev in
806 let abstr_const cst =
807 (* XXX: be more efficient *)
808 let open Declarations in
809 let senv = get_senv_side_effects sigma.effects in
810 let env = Safe_typing.env_of_safe_env senv in
811 let cb = Environ.lookup_constant cst env in
812 let drop_opaque = function
813 | OpaqueDef _ -> OpaqueDef ()
814 | Def _ | Undef _ | Primitive _ | Symbol _ as body -> body
815 in
816 let drop_code = function
817 | None -> Vmemitcodes.BCconstant
818 | Some (Vmemitcodes.BCdefined (mask, idx, patch)) ->
819 let code () = Environ.lookup_vm_code idx env in
820 Vmemitcodes.BCdefined (mask, code, patch)
821 | Some (BCalias _ | BCconstant as code) -> code
822 in
823 { cb with const_body = drop_opaque cb.const_body; const_body_code = drop_code cb.const_body_code }
824 in
825 let qual_equal q1 q2 = UState.check_eq_quality sigma.universes q1 q2 in
826 { CClosure.evar_expand; evar_irrelevant; evar_repack; qvar_irrelevant; qual_equal; abstr_const }
827
828 let existential_type_opt d (n, args) =
829 match find_undefined d n with
830 | exception Not_found -> None
831 | info ->
832 Some (instantiate_evar_array d info (evar_concl info) args)
833
834 let existential_type d n = match existential_type_opt d n with
835 | Some t -> t
836 | None -> anomaly (str "Evar " ++ str (string_of_existential (fst n)) ++ str " was not declared.")
837
838 let add_univ_constraints d c =
839 { d with universes = UState.add_univ_constraints d.universes c }
840
841 let add_poly_constraints ?src d c =
842 { d with universes = UState.add_poly_constraints ?src d.universes c }
843
844 let add_constraints d c =
845 { d with universes = UState.add_constraints d.universes c }
846
847 (*** /Lifting... ***)
848
849 (* evar_map are considered empty disregarding histories *)
850 let is_empty d =
851 EvMap.is_empty d.defn_evars &&
852 EvMap.is_empty d.undf_evars &&
853 List.is_empty d.conv_pbs
854
855 let cmap f evd =
856 { evd with
857 defn_evars = EvMap.map (map_evar_info f) evd.defn_evars;
858 undf_evars = EvMap.map (map_evar_info f) evd.undf_evars
859 }
860
861 (* spiwack: deprecated *)
862 let create_evar_defs sigma = { sigma with
863 conv_pbs=[]; last_mods=Evar.Set.empty }
864
865 let empty_evar_flags =
866 { obligation_evars = Evar.Set.empty;
867 aliased_evars = Evar.Map.empty;
868 typeclass_evars = Evar.Set.empty;
869 impossible_case_evars = Evar.Set.empty;
870 rewrite_rule_evars = Evar.Set.empty;
871 }
872
873 let empty_side_effects = {
874 seff_safeenv = None;
875 seff_labels = Id.Set.empty;
876 seff_private = Safe_typing.empty_private_constants;
877 seff_roles = Cmap_env.empty;
878 seff_univs = Cmap_env.empty;
879 }
880
881 let empty = {
882 defn_evars = EvMap.empty;
883 undf_evars = EvMap.empty;
884 universes = UState.empty;
885 conv_pbs = [];
886 last_mods = Evar.Set.empty;
887 evar_flags = empty_evar_flags;
888 candidate_evars = Evar.Set.empty;
889 effects = empty_side_effects;
890 evar_names = Evarnames.empty; (* id<->key for undefined evars *)
891 future_goals = FutureGoals.empty_stack;
892 given_up = Evar.Set.empty;
893 shelf = [[]];
894 extras = Store.empty;
895 }
896
897 let from_env ?binders e = { empty with universes = UState.from_env ?binders e }
898
899 let from_ctx uctx = { empty with universes = uctx }
900
901 let has_undefined evd = not (EvMap.is_empty evd.undf_evars)
902
903 let has_given_up evd = not (Evar.Set.is_empty evd.given_up)
904
905 let has_shelved evd = not (List.for_all List.is_empty evd.shelf)
906
907 let merge_universe_context evd uctx' =
908 { evd with universes = UState.union evd.universes uctx' }
909
910 let set_universe_context evd uctx' =
911 { evd with universes = uctx' }
912
913 (* TODO: make unique *)
914 let add_conv_pb ?(tail=false) pb d =
915 if tail then {d with conv_pbs = d.conv_pbs @ [pb]}
916 else {d with conv_pbs = pb::d.conv_pbs}
917
918 let conv_pbs d = d.conv_pbs
919
920 let evar_source evi = evi.evar_source
921
922 let evar_ident evk evd = Evarnames.name_of evk evd.evar_names
923 let evar_has_name evk evd = Evarnames.has_name evk evd.evar_names
924 let evar_has_unambiguous_name evk evd = Evarnames.has_unambiguous_name evk evd.evar_names
925 let evar_key name evd = Evarnames.resolve name evd.evar_names
926
927 let get_aliased_evars evd = evd.evar_flags.aliased_evars
928
929 let max_undefined_with_candidates evd =
930 try Some (Evar.Set.max_elt evd.candidate_evars) with Not_found -> None
931
932 let is_aliased_evar evd evk =
933 try Some (Evar.Map.find evk evd.evar_flags.aliased_evars)
934 with Not_found -> None
935
936 let downcast evk ccl evd =
937 let evar_info = EvMap.find evk evd.undf_evars in
938 let evar_info' = { evar_info with evar_concl = Undefined ccl } in
939 { evd with undf_evars = EvMap.add evk evar_info' evd.undf_evars }
940
941 let mem_head_evar c evars =
942 (* Note: evar-sensitive code *)
943 let rec hrec c = match kind c with
944 | Evar (evk,_) -> Evar.Set.mem evk evars
945 | Case (_, _, _, _, _, c, _) -> hrec c
946 | App (c,_) -> hrec c
947 | Cast (c,_,_) -> hrec c
948 | Proj (_, _, c) -> hrec c
949 | _ -> false
950 in
951 hrec c
952
953 let has_evar evars (pbty,_,t1,t2) =
954 match evars with
955 | None -> true
956 | Some evars -> mem_head_evar t1 evars || mem_head_evar t2 evars
957
958 (* extracts conversion problems that satisfy predicate p *)
959 (* Note: conv_pbs not satisying p are stored back in reverse order *)
960 let extract_conv_pbs evd p =
961 let (pbs,pbs1) =
962 List.fold_left
963 (fun (pbs,pbs1) pb ->
964 if p pb then
965 (pb::pbs,pbs1)
966 else
967 (pbs,pb::pbs1))
968 ([],[])
969 evd.conv_pbs
970 in
971 {evd with conv_pbs = pbs1; last_mods = Evar.Set.empty},
972 pbs
973
974 let extract_changed_conv_pbs evd =
975 extract_conv_pbs evd (has_evar (Some evd.last_mods))
976
977 let extract_changed_conv_pbs_from evd evars=
978 extract_conv_pbs evd (has_evar evars)
979
980 let extract_all_conv_pbs evd =
981 extract_conv_pbs evd (fun _ -> true)
982
983 let loc_of_conv_pb evd (pbty,env,t1,t2) =
984 match kind (fst (decompose_app t1)) with
985 | Evar (evk1,_) ->
986 let EvarInfo evi = find evd evk1 in
987 fst (evar_source evi)
988 | _ ->
989 match kind (fst (decompose_app t2)) with
990 | Evar (evk2,_) ->
991 let EvarInfo evi = find evd evk2 in
992 fst (evar_source evi)
993 | _ -> None
994
995 (**********************************************************)
996 (* Sort variables *)
997
998 type rigid = UState.rigid =
999 | UnivRigid
1000 | UnivFlexible of bool (** Is substitution by an algebraic ok? *)
1001
1002 let univ_rigid = UnivRigid
1003 let univ_flexible = UnivFlexible false
1004 let univ_flexible_alg = UnivFlexible true
1005
1006 let ustate d = d.universes
1007
1008 let elim_graph d = UState.elim_graph d.universes
1009
1010 let evar_universe_context d = ustate d
1011
1012 let universe_context_set d = UState.universe_context_set d.universes
1013
1014 let sort_context_set d = UState.sort_context_set d.universes
1015
1016 let to_universe_context evd = UState.context evd.universes
1017
1018 let univ_entry ~poly evd = UState.univ_entry ~poly evd.universes
1019
1020 let check_univ_decl ~poly evd decl = UState.check_univ_decl ~poly evd.universes decl
1021
1022 let check_univ_decl_early ~poly ~with_obls sigma udecl terms =
1023 let () =
1024 if with_obls && not @@ PolyFlags.univ_poly poly &&
1025 (not udecl.UState.univdecl_extensible_instance
1026 || not udecl.UState.univdecl_extensible_constraints)
1027 then
1028 CErrors.user_err
1029 Pp.(str "Non extensible universe declaration not supported \
1030 with monomorphic Program definitions.")
1031 in
1032 let vars = List.fold_left (fun acc b -> Univ.Level.Set.union acc (Vars.universes_of_constr b)) Univ.Level.Set.empty terms in
1033 let uctx = ustate sigma in
1034 let uctx = UState.collapse_sort_variables uctx in
1035 let uctx = UState.restrict uctx vars in
1036 ignore (UState.check_univ_decl ~poly uctx udecl)
1037
1038 let restrict_universe_context evd vars =
1039 { evd with universes = UState.restrict evd.universes vars }
1040
1041 let universe_subst evd =
1042 UState.subst evd.universes
1043
1044 let merge_universe_context_set ?loc ?(sideff=false) rigid evd uctx' =
1045 {evd with universes = UState.merge_universe_context ?loc ~sideff rigid evd.universes uctx'}
1046
1047 let merge_sort_context_set ?loc ?sort_rigid ?(sideff=false) ?src rigid evd ctx' =
1048 {evd with universes = UState.merge_sort_context ?loc ?sort_rigid ~sideff rigid ?src evd.universes ctx'}
1049
1050 let with_sort_context_set ?loc ?sort_rigid ?src rigid d (a, ctx) =
1051 (merge_sort_context_set ?loc ?sort_rigid ?src rigid d ctx, a)
1052
1053 let new_univ_level_variable ?loc ?name rigid evd =
1054 let uctx', u = UState.new_univ_variable ?loc rigid name evd.universes in
1055 ({evd with universes = uctx'}, u)
1056
1057 let new_univ_variable ?loc ?name rigid evd =
1058 let uctx', u = UState.new_univ_variable ?loc rigid name evd.universes in
1059 ({evd with universes = uctx'}, Univ.Universe.make u)
1060
1061 let new_quality_variable ?loc ?name evd =
1062 let uctx, q = UState.new_sort_variable ?loc ?name evd.universes in
1063 {evd with universes = uctx}, q
1064
1065 let new_sort_info ?loc ?sort_rigid ?name rigid sigma =
1066 let (sigma, u) = new_univ_variable ?loc rigid sigma in
1067 let uctx, q = UState.new_sort_variable ?sort_rigid ?name sigma.universes in
1068 ({ sigma with universes = uctx }, q, u)
1069
1070 let new_sort_variable ?loc ?sort_rigid ?name rigid sigma =
1071 let (sigma, u) = new_univ_variable ?loc rigid sigma in
1072 let uctx, q = UState.new_sort_variable ?loc ?sort_rigid ?name sigma.universes in
1073 ({ sigma with universes = uctx }, Sorts.qsort q u)
1074
1075 let add_forgotten_univ d u =
1076 { d with universes = UState.add_forgotten_univ d.universes u }
1077
1078 let make_nonalgebraic_variable evd u =
1079 { evd with universes = UState.make_nonalgebraic_variable evd.universes u }
1080
1081 (****************************************)
1082 (* Operations on constants *)
1083 (****************************************)
1084
1085 (* FIXME: do this more cleanly *)
1086 let lookup_constant env sigma c = match Environ.lookup_constant_opt c env with
1087 | Some cb -> cb
1088 | None ->
1089 if Safe_typing.is_empty_private_constants sigma.effects.seff_private then
1090 CErrors.anomaly Pp.(str "Constant " ++ Constant.print c ++ str" does not appear in the environment.")
1091 else
1092 let senv = get_senv_side_effects sigma.effects in
1093 Environ.lookup_constant c (Safe_typing.env_of_safe_env senv)
1094
1095 let fresh_sort_in_quality ?loc ?(rigid=univ_flexible) evd s =
1096 with_sort_context_set ?loc rigid ~src:UState.Internal evd
1097 (UnivGen.fresh_sort_in_quality s)
1098
1099 let fresh_instance ?loc ?names env sigma gr =
1100 let open GlobRef in
1101 let auctx = match gr with
1102 | VarRef _ -> UVars.AbstractContext.empty
1103 | ConstRef c ->
1104 let cb = lookup_constant env sigma c in
1105 Declareops.constant_polymorphic_context cb
1106 | IndRef (mind,_) | ConstructRef ((mind,_),_) ->
1107 let mib = lookup_mind mind env in
1108 Declareops.inductive_polymorphic_context mib
1109 in
1110 let names = Option.map (fun x -> gr, x) names in
1111 let u, ctx = UnivGen.fresh_instance_from ?loc auctx names in
1112 u, ctx
1113
1114 let fresh_constant_instance ?loc ?(rigid=univ_flexible) env evd c =
1115 let (u, ctx) = fresh_instance env evd (GlobRef.ConstRef c) in
1116 with_sort_context_set ?loc rigid ~src:UState.Internal evd ((c, u), ctx)
1117
1118 let fresh_inductive_instance ?loc ?sort_rigid ?(rigid=univ_flexible) env evd i =
1119 with_sort_context_set ?loc ?sort_rigid rigid ~src:UState.Internal evd (UnivGen.fresh_inductive_instance env i)
1120
1121 let fresh_constructor_instance ?loc ?(rigid=univ_flexible) env evd c =
1122 with_sort_context_set ?loc rigid ~src:UState.Internal evd (UnivGen.fresh_constructor_instance env c)
1123
1124 let fresh_array_instance ?loc ?(rigid=univ_flexible) env evd =
1125 with_sort_context_set ?loc rigid ~src:UState.Internal evd (UnivGen.fresh_array_instance env)
1126
1127 let fresh_global ?loc ?(rigid=univ_flexible) ?names env evd gr =
1128 let (u, ctx) = fresh_instance ?loc ?names env evd gr in
1129 with_sort_context_set ?loc rigid ~src:UState.Internal evd (mkRef (gr, u), ctx)
1130
1131 let is_flexible_level evd l =
1132 let uctx = evd.universes in
1133 UnivFlex.mem l (UState.subst uctx)
1134
1135 let is_eq_sort s1 s2 =
1136 if Sorts.equal s1 s2 then None
1137 else Some (s1, s2)
1138
1139 let normalize_universe_instance evd l =
1140 UState.nf_instance evd.universes l
1141
1142 let normalize_sort evars s =
1143 UState.nf_sort evars.universes s
1144
1145 (* FIXME inefficient *)
1146 let set_eq_sort evd s1 s2 =
1147 let s1 = normalize_sort evd s1 and s2 = normalize_sort evd s2 in
1148 match is_eq_sort s1 s2 with
1149 | None -> evd
1150 | Some (u1, u2) ->
1151 if not (UGraph.type_in_type (UState.ugraph evd.universes)) then
1152 add_constraints evd
1153 (UnivProblem.Set.singleton (UnivProblem.UEq (u1,u2)))
1154 else
1155 evd
1156
1157 let set_eq_level d u1 u2 =
1158 add_univ_constraints d (Univ.enforce_eq_level u1 u2 Univ.UnivConstraints.empty)
1159
1160 let set_leq_level d u1 u2 =
1161 add_univ_constraints d (Univ.enforce_leq_level u1 u2 Univ.UnivConstraints.empty)
1162
1163 let set_eq_instances ?(flex=false) d u1 u2 =
1164 add_constraints d
1165 (UnivProblem.enforce_eq_instances_univs flex u1 u2 UnivProblem.Set.empty)
1166
1167 let set_leq_sort evd s1 s2 =
1168 let s1 = normalize_sort evd s1
1169 and s2 = normalize_sort evd s2 in
1170 match is_eq_sort s1 s2 with
1171 | None -> evd
1172 | Some (u1, u2) ->
1173 if not (UGraph.type_in_type (UState.ugraph evd.universes)) then
1174 add_constraints evd @@
1175 UnivProblem.Set.singleton (UnivProblem.ULe (u1,u2))
1176 else evd
1177
1178 let set_eq_qualities evd q1 q2 =
1179 add_constraints evd @@ UnivProblem.Set.singleton (QEq (q1, q2))
1180
1181 let set_above_prop evd q =
1182 add_constraints evd @@
1183 UnivProblem.Set.singleton (QLeq (Sorts.Quality.qprop, q))
1184
1185 let set_elim_to evd q1 q2 =
1186 add_constraints evd @@ UnivProblem.Set.singleton (QElimTo (q1, q2))
1187
1188 let check_eq evd s s' =
1189 let ustate = evd.universes in
1190 let univs = UState.ugraph ustate in
1191 UGraph.check_eq_sort Sorts.Quality.equal univs (UState.nf_sort ustate s) (UState.nf_sort ustate s')
1192
1193 let check_leq evd s s' =
1194 let ustate = evd.universes in
1195 let univs = UState.ugraph ustate in
1196 UGraph.check_leq_sort Sorts.Quality.equal univs (UState.nf_sort ustate s) (UState.nf_sort ustate s')
1197
1198 let check_univ_constraints evd csts =
1199 UGraph.check_constraints csts (UState.ugraph evd.universes)
1200
1201 let check_elim_constraints evd csts =
1202 UState.check_elim_constraints evd.universes csts
1203
1204 let check_poly_constraints evd (qcsts,ucsts) =
1205 check_elim_constraints evd qcsts && check_univ_constraints evd ucsts
1206
1207 let check_quality_constraints evd qcst =
1208 let fold (q1, q2) accu = UnivProblem.Set.add (UnivProblem.QEq (q1, q2)) accu in
1209 let qcst = UVars.QPairSet.fold fold qcst UnivProblem.Set.empty in
1210 UState.check_constraints evd.universes qcst
1211
1212 let fix_undefined_variables evd =
1213 { evd with universes = UState.fix_undefined_variables evd.universes }
1214
1215 let nf_univ_variables evd =
1216 let uctx = UState.normalize_variables evd.universes in
1217 {evd with universes = uctx}
1218
1219 let collapse_sort_variables ?except evd =
1220 let universes = UState.collapse_sort_variables ?except evd.universes in
1221 { evd with universes }
1222
1223 let minimize_universes ?(collapse_sort_variables=true) evd =
1224 let uctx' = if collapse_sort_variables
1225 then UState.collapse_sort_variables evd.universes
1226 else evd.universes
1227 in
1228 let uctx' = UState.normalize_variables uctx' in
1229 let uctx' = UState.minimize uctx' in
1230 {evd with universes = uctx'}
1231
1232 let universe_of_name evd s = UState.universe_of_name evd.universes s
1233
1234 let quality_of_name evd s = UState.quality_of_name evd.universes s
1235
1236 let is_rigid_qvar evd q = UState.is_rigid_qvar evd.universes q
1237
1238 let universe_binders evd = UState.universe_binders evd.universes
1239
1240 let universes evd = UState.ugraph evd.universes
1241
1242 let update_sigma_univs ugraph evd =
1243 { evd with universes = UState.update_sigma_univs evd.universes ugraph }
1244
1245 exception UniversesDiffer = UState.UniversesDiffer
1246
1247 (**********************************************************)
1248 (* Side effects *)
1249
1250 let concat_side_effects eff1 eff2 = {
1251 seff_safeenv = None;
1252 seff_labels = Id.Set.fold Id.Set.add eff1.seff_labels eff2.seff_labels;
1253 seff_private = Safe_typing.concat_private eff1.seff_private eff2.seff_private;
1254 seff_roles = Cmap_env.fold Cmap_env.add eff1.seff_roles eff2.seff_roles;
1255 seff_univs = Cmap_env.fold Cmap_env.add eff1.seff_univs eff2.seff_univs;
1256 }
1257
1258 let emit_side_effects eff evd =
1259 let senv = get_senv_side_effects eff in
1260 let _, senv = Safe_typing.export_private_constants eff.seff_private senv in
1261 let effects = concat_side_effects eff evd.effects in
1262 let effects = { effects with seff_safeenv = Some senv } in
1263 { evd with effects; universes = UState.emit_side_effects eff.seff_private evd.universes }
1264
1265 let set_side_effects eff evd =
1266 { evd with effects = eff }
1267
1268 let eval_side_effects evd = evd.effects
1269
1270 let push_side_effects ?role ?ts name de ctx effs =
1271 let senv = get_senv_side_effects effs in
1272 let senv = match ts with
1273 | None -> senv
1274 | Some ts -> Safe_typing.set_oracle ts senv
1275 in
1276 let (kn, prv), senv = Safe_typing.add_private_constant name ctx de senv in
1277 let seff_univs =
1278 if Univ.Level.Set.is_empty (fst ctx) then effs.seff_univs
1279 else
1280 Cmap_env.add kn (UState.Monomorphic_entry ctx, UnivNames.empty_binders) effs.seff_univs
1281 in
1282 let seff_roles = match role with
1283 | None -> effs.seff_roles
1284 | Some r -> Cmap_env.add kn r effs.seff_roles
1285 in
1286 let effs = {
1287 seff_private = Safe_typing.concat_private prv effs.seff_private;
1288 seff_labels = Id.Set.add (Constant.label kn) effs.seff_labels;
1289 seff_roles = seff_roles;
1290 seff_univs = seff_univs;
1291 seff_safeenv = Some senv;
1292 } in
1293 kn, effs
1294
1295 let seff_mem_label id effs =
1296 Id.Set.mem id effs.seff_labels
1297
1298 let seff_private eff = eff.seff_private
1299 let seff_roles effs = effs.seff_roles
1300 let seff_univs effs = effs.seff_univs
1301
1302 (* Future goals *)
1303 let declare_future_goal evk evd =
1304 let future_goals = FutureGoals.add evk evd.future_goals in
1305 { evd with future_goals }
1306
1307 let push_future_goals evd =
1308 { evd with future_goals = FutureGoals.push evd.future_goals }
1309
1310 let pop_future_goals evd =
1311 let hd, future_goals = FutureGoals.pop evd.future_goals in
1312 hd, { evd with future_goals }
1313
1314 let fold_future_goals f sigma =
1315 FutureGoals.fold f sigma sigma.future_goals
1316
1317 let remove_future_goal evd evk =
1318 { evd with future_goals = FutureGoals.remove evk evd.future_goals }
1319
1320 let pr_future_goals_stack evd =
1321 FutureGoals.pr_stack evd.future_goals
1322
1323 let give_up ev evd =
1324 { evd with given_up = Evar.Set.add ev evd.given_up }
1325
1326 let push_shelf evd =
1327 { evd with shelf = [] :: evd.shelf }
1328
1329 let pop_shelf evd =
1330 match evd.shelf with
1331 | [] -> anomaly Pp.(str"shelf stack should not be empty")
1332 | hd :: tl ->
1333 hd, { evd with shelf = tl }
1334
1335 let filter_shelf f evd =
1336 { evd with shelf = List.map (List.filter f) evd.shelf }
1337
1338 let shelve evd l =
1339 match evd.shelf with
1340 | [] -> anomaly Pp.(str"shelf stack should not be empty")
1341 | hd :: tl ->
1342 { evd with shelf = (hd@l) :: tl }
1343
1344 let unshelve evd l =
1345 { evd with shelf = List.map (List.filter (fun ev -> not (CList.mem_f Evar.equal ev l))) evd.shelf }
1346
1347 let given_up evd = evd.given_up
1348
1349 let shelf evd = List.flatten evd.shelf
1350
1351 let mem_shelf e evd = List.exists (List.exists (fun e' -> Evar.equal e e')) evd.shelf
1352
1353 let pr_shelf evd =
1354 let open Pp in
1355 if List.is_empty evd.shelf then str"(empty stack)"
1356 else prlist_with_sep (fun () -> str"||") (prlist_with_sep spc Evar.print) evd.shelf
1357
1358 let new_pure_evar ?(src=default_source) ?(filter = Filter.identity) ~relevance
1359 ?(abstract_arguments = Abstraction.identity) ?candidates
1360 ?name ?parent ?(typeclass_candidate = false) ?(rrpat = false) sign evd typ =
1361 let evi = {
1362 evar_hyps = sign;
1363 evar_concl = Undefined typ;
1364 evar_body = Evar_empty;
1365 evar_filter = filter;
1366 evar_abstract_arguments = Undefined abstract_arguments;
1367 evar_source = src;
1368 evar_candidates = Undefined candidates;
1369 evar_relevance = relevance;
1370 }
1371 in
1372 let newevk = new_untyped_evar () in
1373 let evd = add_with_name evd ?name ?parent ~typeclass_candidate ~rrpat newevk evi in
1374 let evd = declare_future_goal newevk evd in
1375 (evd, newevk)
1376
1377 let define_aux def undef evk body =
1378 let oldinfo =
1379 try EvMap.find evk undef
1380 with Not_found ->
1381 if EvMap.mem evk def then
1382 anomaly ~label:"Evd.define" (Pp.str "cannot define an evar twice.")
1383 else
1384 anomaly ~label:"Evd.define" (Pp.str "cannot define undeclared evar.")
1385 in
1386 let () = assert (oldinfo.evar_body == Evar_empty) in
1387 let newinfo = { oldinfo with
1388 evar_body = Evar_defined body;
1389 evar_concl = Defined;
1390 evar_candidates = Defined;
1391 evar_abstract_arguments = Defined;
1392 } in
1393 EvMap.add evk newinfo def, EvMap.remove evk undef
1394
1395 (* define the existential of section path sp as the constr body *)
1396 let define_gen evk body evd evar_flags =
1397 let future_goals = FutureGoals.remove evk evd.future_goals in
1398 let evd = { evd with future_goals } in
1399 let (defn_evars, undf_evars) = define_aux evd.defn_evars evd.undf_evars evk body in
1400 let last_mods = match evd.conv_pbs with
1401 | [] -> evd.last_mods
1402 | _ -> Evar.Set.add evk evd.last_mods
1403 in
1404 let evar_names = Evarnames.remove evk evd.evar_names in
1405 let candidate_evars = Evar.Set.remove evk evd.candidate_evars in
1406 { evd with defn_evars; undf_evars; last_mods; evar_names; evar_flags; candidate_evars }
1407
1408 (** By default, the obligation and evar tag of the evar is removed *)
1409 let define evk body evd =
1410 let evar_flags = remove_evar_flags evk evd.evar_flags in
1411 define_gen evk body evd evar_flags
1412
1413 (** In case of an evar-evar solution, the flags are inherited *)
1414 let define_with_evar evk body evd =
1415 let evk' = fst (destEvar body) in
1416 let evar_flags = inherit_evar_flags evd.evar_flags evk evk' in
1417 let evd = unshelve evd [evk] in
1418 define_gen evk body evd evar_flags
1419
1420 (* In case of restriction, we declare the aliasing and inherit the obligation
1421 and typeclass flags. *)
1422
1423 let restrict evk filter ?candidates ?src evd =
1424 let evk' = new_untyped_evar () in
1425 let evar_info = EvMap.find evk evd.undf_evars in
1426 let len = Range.length evar_info.evar_hyps.env_named_idx in
1427 let id_inst = Filter.filter_slist filter (SList.defaultn len SList.empty) in
1428 let evar_info' =
1429 { evar_info with evar_filter = filter;
1430 evar_candidates = Undefined candidates;
1431 evar_source = (match src with None -> evar_info.evar_source | Some src -> src);
1432 } in
1433 let last_mods = match evd.conv_pbs with
1434 | [] -> evd.last_mods
1435 | _ -> Evar.Set.add evk evd.last_mods in
1436 let evar_names = Evarnames.transfer_name evk evk' evd.evar_names in
1437 let body = mkEvar(evk',id_inst) in
1438 let (defn_evars, undf_evars) = define_aux evd.defn_evars evd.undf_evars evk body in
1439 let evar_flags = inherit_evar_flags evd.evar_flags evk evk' in
1440 let evar_flags = match src with
1441 | Some (_,Evar_kinds.ImpossibleCase) ->
1442 { evar_flags with impossible_case_evars = Evar.Set.add evk' evar_flags.impossible_case_evars }
1443 | _ -> evar_flags
1444 in
1445 let candidate_evars = Evar.Set.remove evk evd.candidate_evars in
1446 let candidate_evars = match candidates with
1447 | None -> candidate_evars
1448 | Some _ -> Evar.Set.add evk' candidate_evars
1449 in
1450 let evd = { evd with undf_evars = EvMap.add evk' evar_info' undf_evars;
1451 defn_evars; last_mods; evar_names; evar_flags; candidate_evars }
1452 in
1453 (* Mark new evar as future goal, removing previous one,
1454 circumventing Proofview.advance but making Proof.run_tactic catch these. *)
1455 let evd = unshelve evd [evk] in
1456 let evd = remove_future_goal evd evk in
1457 let evd = declare_future_goal evk' evd in
1458 (evd, evk')
1459
1460 let update_source evd evk src =
1461 let modify _ info = { info with evar_source = src } in
1462 { evd with undf_evars = EvMap.modify evk modify evd.undf_evars }
1463
1464 let dependent_evar_ident ev evd =
1465 let EvarInfo evi = find evd ev in
1466 match evi.evar_source with
1467 | (_,Evar_kinds.VarInstance id) -> id
1468 | _ -> anomaly (str "Not an evar resulting of a dependent binding.")
1469
1470 (**********************************************************)
1471 (* Extra data *)
1472
1473 let get_extra_data evd = evd.extras
1474 let set_extra_data extras evd = { evd with extras }
1475
1476 (*******************************************************************)
1477 (* The state monad with state an evar map. *)
1478
1479 module MonadR =
1480 Monad.Make (struct
1481
1482 type +'a t = evar_map -> evar_map * 'a
1483
1484 let return a = fun s -> (s,a)
1485
1486 let (>>=) x f = fun s ->
1487 let (s',a) = x s in
1488 f a s'
1489
1490 let (>>) x y = fun s ->
1491 let (s',()) = x s in
1492 y s'
1493
1494 let map f x = fun s ->
1495 on_snd f (x s)
1496
1497 end)
1498
1499 module Monad =
1500 Monad.Make (struct
1501
1502 type +'a t = evar_map -> 'a * evar_map
1503
1504 let return a = fun s -> (a,s)
1505
1506 let (>>=) x f = fun s ->
1507 let (a,s') = x s in
1508 f a s'
1509
1510 let (>>) x y = fun s ->
1511 let ((),s') = x s in
1512 y s'
1513
1514 let map f x = fun s ->
1515 on_fst f (x s)
1516
1517 end)
1518
1519 (**********************************************************)
1520 (* Failure explanation *)
1521
1522 type unsolvability_explanation = SeveralInstancesFound of int
1523
1524 module Expand :
1525 sig
1526 type handle
1527 val empty_handle : handle
1528 val liftn_handle : int -> handle -> handle
1529 val kind : evar_map -> handle -> constr ->
1530 handle * (constr, constr, Sorts.t, UVars.Instance.t, Sorts.relevance) kind_of_term
1531 val expand : evar_map -> handle -> constr -> constr
1532 val expand_instance : skip: bool -> undefined evar_info -> handle -> econstr SList.t -> econstr SList.t
1533 end =
1534 struct
1535
1536 type clos = {
1537 evc_map : (int * clos * Constr.t) Id.Map.t;
1538 (* Map each bound ident to its value and the depth it was introduced at *)
1539 evc_lift : int; (* number of binders crossed since last evar *)
1540 evc_stack : int list; (* stack of binders crossed at each evar *)
1541 evc_depth : int; (* length of evc_stack *)
1542 evc_cache : int Int.Map.t ref option; (* Cache get_lift on evc_stack *)
1543 }
1544
1545 let empty_clos = {
1546 evc_lift = 0;
1547 evc_depth = 0;
1548 evc_stack = [];
1549 evc_map = Id.Map.empty;
1550 evc_cache = None;
1551 }
1552
1553 let push_clos info clos args =
1554 let push id c map = Id.Map.add id (clos.evc_depth, clos, c) map in
1555 let nmap = evar_instance_array clos.evc_map push info args in
1556 {
1557 evc_lift = 0;
1558 evc_map = nmap;
1559 evc_depth = clos.evc_depth + 1;
1560 evc_stack = clos.evc_lift :: clos.evc_stack;
1561 evc_cache = Some (ref Int.Map.empty);
1562 }
1563
1564 let find_clos clos id = match Id.Map.find_opt id clos.evc_map with
1565 | None -> None
1566 | Some (depth, nclos, v) ->
1567 let pos = clos.evc_depth - depth - 1 in
1568 let rec get_lift accu n lft =
1569 if Int.equal n 0 then accu
1570 else match lft with
1571 | [] -> assert false
1572 | k :: lft -> get_lift (accu + k) (n - 1) lft
1573 in
1574 let ans = match clos.evc_cache with
1575 | None -> assert false
1576 | Some cache ->
1577 match Int.Map.find_opt pos !cache with
1578 | None ->
1579 let ans = get_lift 0 pos clos.evc_stack in
1580 let () = cache := Int.Map.add pos ans !cache in
1581 ans
1582 | Some ans -> ans
1583 in
1584 let k = clos.evc_lift + ans in
1585 Some (k, nclos, v)
1586
1587 type handle = {
1588 h_clos : clos;
1589 h_lift : Esubst.lift;
1590 }
1591
1592 let empty_handle = {
1593 h_clos = empty_clos;
1594 h_lift = Esubst.el_id;
1595 }
1596
1597 let liftn_clos n s = { s with evc_lift = s.evc_lift + n }
1598
1599 let liftn_handle n h = {
1600 h_clos = liftn_clos n h.h_clos;
1601 h_lift = Esubst.el_liftn n h.h_lift;
1602 }
1603
1604 let rec kind sigma h c = match Constr.kind c with
1605 | Rel n -> h, Rel (Esubst.reloc_rel n h.h_lift)
1606 | Var id as c0 ->
1607 begin match find_clos h.h_clos id with
1608 | None -> (h, c0)
1609 | Some (k, clos, v) ->
1610 let h = { h_clos = clos; h_lift = Esubst.el_shft k h.h_lift } in
1611 kind sigma h v
1612 end
1613 | Evar (evk, args) as c0 ->
1614 begin match EvMap.find_opt evk sigma.defn_evars with
1615 | None -> (h, c0)
1616 | Some info ->
1617 let Evar_defined c = evar_body info in
1618 let nclos = push_clos info h.h_clos args in
1619 kind sigma { h_lift = h.h_lift; h_clos = nclos } c
1620 end
1621 | Meta _ | Sort _ | Cast _ | Prod _ | Lambda _ | LetIn _ | App _
1622 | Const _ | Ind _ | Construct _ | Case _ | Fix _ | CoFix _ | Proj _
1623 | Int _ | Float _ | String _ | Array _ as c0 ->
1624 (h, c0)
1625
1626 let expand0 sigma h c =
1627 let lift h = liftn_handle 1 h in
1628 let rec aux h c = match Constr.kind c with
1629 | Rel n ->
1630 let n' = Esubst.reloc_rel n h.h_lift in
1631 if Int.equal n n' then c else mkRel n'
1632 | Var id ->
1633 begin match find_clos h.h_clos id with
1634 | None -> c
1635 | Some (k, clos, v) ->
1636 let h = { h_clos = clos; h_lift = Esubst.el_shft k h.h_lift } in
1637 aux h v
1638 end
1639 | Evar (evk, args) ->
1640 (* for efficiency do not expand evars, just their instance *)
1641 let EvarInfo evi = find sigma evk in
1642 let push decl c args =
1643 if isVarId (NamedDecl.get_id decl) c then SList.default args
1644 else SList.cons c args
1645 in
1646 let rec expand ctx args = match ctx, SList.view args with
1647 | [], None -> SList.empty
1648 | decl :: ctx, Some (Some c, args) ->
1649 let c = aux h c in
1650 push decl c (expand ctx args)
1651 | decl :: ctx, Some (None, args) ->
1652 let c = aux h (mkVar (NamedDecl.get_id decl)) in
1653 push decl c (expand ctx args)
1654 | [], Some _ | _ :: _, None -> instance_mismatch ()
1655 in
1656 let args = expand (evar_filtered_context evi) args in
1657 mkEvar (evk, args)
1658 | _ -> Constr.map_with_binders lift aux h c
1659 in
1660 aux h c
1661
1662 let expand sigma h c =
1663 if Esubst.is_lift_id h.h_lift && Id.Map.is_empty h.h_clos.evc_map then c
1664 else expand0 sigma h c
1665
1666 let expand_instance ~skip (evi : undefined evar_info) h (args : Constr.t SList.t) =
1667 if skip && Id.Map.is_empty h.h_clos.evc_map then args
1668 else
1669 let rec expand ctx args = match ctx, SList.view args with
1670 | [], None -> SList.empty
1671 | decl :: ctx, Some (None, args) ->
1672 let args = expand ctx args in
1673 let id = NamedDecl.get_id decl in
1674 if Id.Map.mem id h.h_clos.evc_map then
1675 (* Keep the non-default representation as kind will expand it *)
1676 SList.cons (mkVar id) args
1677 else if skip then SList.default args
1678 else SList.cons (mkVar id) args
1679 | decl :: ctx, Some (Some c, args) ->
1680 let args = expand ctx args in
1681 let id = NamedDecl.get_id decl in
1682 (* Same as above *)
1683 if skip && isVarId id c && not (Id.Map.mem id h.h_clos.evc_map) then SList.default args
1684 else SList.cons c args
1685 | [], Some _ | _ :: _, None -> instance_mismatch ()
1686 in
1687 expand (evar_filtered_context evi) args
1688
1689 end
1690
1691 module MiniEConstr = struct
1692
1693 module ERelevance = struct
1694 type t = Sorts.relevance
1695 let make r = r
1696 let unsafe_to_relevance r = r
1697 let kind sigma r = UState.nf_relevance sigma.universes r
1698 end
1699
1700 module ESorts =
1701 struct
1702 type t = Sorts.t
1703 let make s = s
1704 let kind = normalize_sort
1705 let unsafe_to_sorts s = s
1706 end
1707
1708 module EInstance =
1709 struct
1710 type t = UVars.Instance.t
1711 let make i = i
1712 let kind sigma i =
1713 if UVars.Instance.is_empty i then i
1714 else normalize_universe_instance sigma i
1715 let empty = UVars.Instance.empty
1716 let is_empty = UVars.Instance.is_empty
1717 let unsafe_to_instance t = t
1718 end
1719
1720 type t = econstr
1721
1722 let rec whd_evar sigma c =
1723 match Constr.kind c with
1724 | Evar ev ->
1725 let (h, knd) = Expand.kind sigma Expand.empty_handle c in
1726 if Constr.kind c == knd then c
1727 else whd_kind sigma h knd
1728 | App (f, args) when isEvar f ->
1729 (* Enforce smart constructor invariant on applications *)
1730 let (h, knd) = Expand.kind sigma Expand.empty_handle f in
1731 if Constr.kind f == knd then c
1732 else mkApp (whd_kind sigma h knd, args)
1733 | Cast (c0, k, t) when isEvar c0 ->
1734 (* Enforce smart constructor invariant on casts. *)
1735 let (h, knd) = Expand.kind sigma Expand.empty_handle c0 in
1736 if Constr.kind c0 == knd then c
1737 else mkCast (whd_kind sigma h knd, k, t)
1738 | _ -> c
1739 and whd_kind sigma h knd =
1740 (* we need to force the head as Expand.expand does not expand evar subterms *)
1741 whd_evar sigma (Expand.expand sigma h (Constr.of_kind knd))
1742
1743 let mkLEvar = mkLEvar
1744 let replace_vars = replace_vars
1745 let kind sigma c = Constr.kind (whd_evar sigma c)
1746 let kind_upto = kind
1747 let of_kind = Constr.of_kind
1748 let of_constr c = c
1749 let of_constr_array v = v
1750 let unsafe_to_constr c = c
1751 let unsafe_to_constr_array v = v
1752 let unsafe_eq = Refl
1753 let unsafe_relevance_eq = Refl
1754
1755 type evclos = {
1756 evc_map : (int * Vars.substituend Lazy.t) Id.Map.t;
1757 (* Map each bound ident to its value and the depth it was introduced at *)
1758 evc_lift : int; (* number of binders crossed since last evar *)
1759 evc_stack : int list; (* stack of binders crossed at each evar *)
1760 evc_depth : int; (* length of evc_stack *)
1761 evc_cache : int Int.Map.t ref; (* Cache get_lift on evc_stack *)
1762 }
1763
1764 let to_constr_gen ~expand ~ignore_missing sigma c =
1765 let saw_evar = ref false in
1766 let lsubst = universe_subst sigma in
1767 let univ_value l =
1768 UnivFlex.normalize_univ_variable lsubst l
1769 in
1770 let relevance_value r = UState.nf_relevance sigma.universes r in
1771 let qvar_value q = UState.nf_qvar sigma.universes q in
1772 let next s = { s with evc_lift = s.evc_lift + 1 } in
1773 let find clos id = match Id.Map.find_opt id clos.evc_map with
1774 | None -> None
1775 | Some (depth, lazy v) ->
1776 let pos = clos.evc_depth - depth - 1 in
1777 let rec get_lift accu n lft =
1778 if Int.equal n 0 then accu
1779 else match lft with
1780 | [] -> assert false
1781 | k :: lft -> get_lift (accu + k) (n - 1) lft
1782 in
1783 let ans = match Int.Map.find_opt pos clos.evc_cache.contents with
1784 | None ->
1785 let ans = get_lift 0 pos clos.evc_stack in
1786 let () = clos.evc_cache := Int.Map.add pos ans clos.evc_cache.contents in
1787 ans
1788 | Some ans -> ans
1789 in
1790 let k = clos.evc_lift + ans in
1791 Some (lift_substituend k v)
1792 in
1793 let rec self clos c = match Constr.kind c with
1794 | Var id ->
1795 begin match find clos id with
1796 | None -> c
1797 | Some v -> v
1798 end
1799 | Evar (evk, args) ->
1800 begin match EvMap.find_opt evk sigma.defn_evars with
1801 | None ->
1802 let () = saw_evar := true in
1803 begin match EvMap.find_opt evk sigma.undf_evars with
1804 | None ->
1805 if ignore_missing then
1806 let map c = self clos c in
1807 let args' = SList.Smart.map map args in
1808 if args' == args then c else mkEvar (evk, args')
1809 else raise Not_found
1810 | Some evi ->
1811 let rec inst ctx args = match ctx, SList.view args with
1812 | [], None -> SList.empty
1813 | decl :: ctx, Some (c, args) ->
1814 let c = match c with
1815 | None ->
1816 let c = find clos (NamedDecl.get_id decl) in
1817 if expand then match c with
1818 | None -> Some (mkVar (NamedDecl.get_id decl))
1819 | Some _ -> c
1820 else c
1821 | Some c -> Some (self clos c)
1822 in
1823 SList.cons_opt c (inst ctx args)
1824 | _ :: _, None | [], Some _ -> instance_mismatch ()
1825 in
1826 let args' = inst (evar_filtered_context evi) args in
1827 if args == args' then c else mkEvar (evk, args')
1828 end
1829 | Some info ->
1830 let Evar_defined c = evar_body info in
1831 let push id c map = Id.Map.add id (clos.evc_depth, lazy (make_substituend (self clos c))) map in
1832 let nmap = evar_instance_array clos.evc_map push info args in
1833 let nclos = {
1834 evc_lift = 0;
1835 evc_map = nmap;
1836 evc_depth = clos.evc_depth + 1;
1837 evc_stack = clos.evc_lift :: clos.evc_stack;
1838 evc_cache = ref Int.Map.empty;
1839 } in
1840 self nclos c
1841 end
1842 | _ ->
1843 UnivSubst.map_universes_opt_subst_with_binders next self relevance_value qvar_value univ_value clos c
1844 in
1845 let clos = {
1846 evc_lift = 0;
1847 evc_depth = 0;
1848 evc_stack = [];
1849 evc_map = Id.Map.empty;
1850 evc_cache = ref Int.Map.empty;
1851 } in
1852 let c = self clos c in
1853 !saw_evar, c
1854
1855 let check_evar c =
1856 let exception SawEvar in
1857 let rec iter c = match Constr.kind c with
1858 | Evar _ -> raise SawEvar
1859 | _ -> Constr.iter iter c
1860 in
1861 try iter c; false with SawEvar -> true
1862
1863 let to_constr ?(abort_on_undefined_evars=true) sigma c =
1864 let saw_evar, c = to_constr_gen ~expand:true ~ignore_missing:false sigma c in
1865 if abort_on_undefined_evars && saw_evar && check_evar c then
1866 anomaly ~label:"econstr" Pp.(str "grounding a non evar-free term")
1867 else c
1868
1869 let to_constr_opt sigma c =
1870 let saw_evar, c = to_constr_gen ~expand:false ~ignore_missing:false sigma c in
1871 if saw_evar && check_evar c then None else Some c
1872
1873 let nf_evar sigma c =
1874 let _, c = to_constr_gen ~expand:false ~ignore_missing:true sigma c in
1875 c
1876
1877 let of_named_decl d = d
1878 let unsafe_to_named_decl d = d
1879 let of_rel_decl d = d
1880 let unsafe_to_rel_decl d = d
1881
1882 let of_named_context d = d
1883 let of_rel_context d = d
1884
1885 let unsafe_to_case_invert x = x
1886 let of_case_invert x = x
1887
1888 let lookup_constant = lookup_constant
1889 end
1890
1891 (** The following functions return the set of evars immediately
1892 contained in the object *)
1893
1894 (* excluding defined evars *)
1895
1896 let evars_of_term evd c =
1897 let rec evrec acc c =
1898 let c = MiniEConstr.whd_evar evd c in
1899 match kind c with
1900 | Evar (n, l) -> Evar.Set.add n (SList.Skip.fold evrec acc l)
1901 | _ -> Constr.fold evrec acc c
1902 in
1903 evrec Evar.Set.empty c
1904
1905 let evars_of_named_context evd nc =
1906 Context.Named.fold_outside
1907 (NamedDecl.fold_constr (fun constr s -> Evar.Set.union s (evars_of_term evd constr)))
1908 nc
1909 ~init:Evar.Set.empty
1910
1911 let evars_of_filtered_evar_info (type a) evd (evi : a evar_info) =
1912 let concl = match evi.evar_concl with
1913 | Undefined c -> evars_of_term evd c
1914 | Defined -> Evar.Set.empty
1915 in
1916 Evar.Set.union concl
1917 (Evar.Set.union
1918 (match evi.evar_body with
1919 | Evar_empty -> Evar.Set.empty
1920 | Evar_defined b -> evars_of_term evd b)
1921 (evars_of_named_context evd (evar_filtered_context evi)))
1922
1923 let drop_new_defined ~original sigma =
1924 NewProfile.profile "drop_new_defined" (fun () ->
1925 let to_keep, to_drop = Evar.Map.partition (fun ev _ ->
1926 Evar.Map.mem ev original.defn_evars || Evar.Map.mem ev original.undf_evars)
1927 sigma.defn_evars
1928 in
1929 let dummy = { empty with defn_evars = to_drop } in
1930 let nfc c = snd @@ MiniEConstr.to_constr_gen ~expand:true ~ignore_missing:false dummy c in (* FIXME: do we really need to expand? *)
1931 assert (List.is_empty sigma.conv_pbs);
1932 let normalize_changed _ev orig evi =
1933 match orig, evi with
1934 | _, None -> None
1935 | None, Some evi -> Some (map_evar_info nfc evi)
1936 | Some orig, Some evi -> if orig == evi then None else Some (map_evar_info nfc evi)
1937 in
1938 let normalize_against original current =
1939 let normalized = EvMap.merge normalize_changed original current in
1940 EvMap.union (fun _ _ x -> Some x) current normalized
1941 in
1942 let to_keep = normalize_against original.defn_evars to_keep in
1943 let undf_evars = normalize_against original.undf_evars sigma.undf_evars in
1944 { sigma with defn_evars = to_keep; undf_evars })
1945 ()