Debian Codegraph @

pretyping/evarsolve.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 Sorts
12 open Util
13 open CErrors
14 open Names
15 open Context
16 open Constr
17 open Environ
18 open Termops
19 open Evd
20 open EConstr
21 open Vars
22 open Namegen
23 open Retyping
24 open Reductionops
25 open Evarutil
26 open Pretype_errors
27
28 module AllowedEvars = struct
29
30 type t =
31 | AllowAll
32 | AllowFun of (Evar.t -> bool) * Evar.Set.t
33
34 let mem allowed evk =
35 match allowed with
36 | AllowAll -> true
37 | AllowFun (f,except) -> f evk && not (Evar.Set.mem evk except)
38
39 let remove evk = function
40 | AllowAll -> AllowFun ((fun _ -> true), Evar.Set.singleton evk)
41 | AllowFun (f,except) -> AllowFun (f, Evar.Set.add evk except)
42
43 let all = AllowAll
44
45 let except evars =
46 AllowFun ((fun _ -> true), evars)
47
48 let from_pred f =
49 AllowFun (f, Evar.Set.empty)
50
51 end
52
53 type unify_flags = {
54 modulo_betaiota: bool;
55 open_ts : TransparentState.t;
56 closed_ts : TransparentState.t;
57 subterm_ts : TransparentState.t;
58 allowed_evars : AllowedEvars.t;
59 with_cs : bool
60 }
61
62 let allow_all_but_rrpat_evars evd =
63 AllowedEvars.except (Evd.get_rewrite_rule_evars evd)
64
65 let is_evar_allowed flags evk =
66 AllowedEvars.mem flags.allowed_evars evk
67
68 type unification_kind =
69 | TypeUnification
70 | TermUnification
71
72 (************************)
73 (* Unification results *)
74 (************************)
75
76 type unification_result =
77 | Success of evar_map
78 | UnifFailure of evar_map * unification_error
79
80 let is_success = function Success _ -> true | UnifFailure _ -> false
81
82 let test_success unify flags b env evd c c' rhs =
83 is_success (unify flags b env evd c c' rhs)
84
85 (** A unification function parameterized by:
86 - unification flags
87 - the kind of unification
88 - environment
89 - sigma
90 - conversion problem
91 - the two terms to unify. *)
92
93 type unifier = unify_flags -> unification_kind ->
94 env -> evar_map -> conv_pb -> constr -> constr -> unification_result
95
96 (** A conversion function: parameterized by the kind of unification,
97 environment, sigma, conversion problem and the two terms to convert.
98 Conversion is not allowed to instantiate evars contrary to unification. *)
99 type conversion_check = unify_flags -> unification_kind ->
100 env -> evar_map -> conv_pb -> constr -> constr -> bool
101
102 let normalize_evar evd ev =
103 match EConstr.kind evd (mkEvar ev) with
104 | Evar (evk,args) -> (evk,args)
105 | _ -> assert false
106
107 let get_polymorphic_positions env sigma f =
108 let open Declarations in
109 match EConstr.kind sigma f with
110 | Ind (ind, u) | Construct ((ind, _), u) ->
111 let mib,oib = Inductive.lookup_mind_specif env ind in
112 (match mib.mind_template with
113 | None -> assert false
114 | Some templ -> templ.template_param_arguments)
115 | _ -> assert false
116
117 let refresh_universes ?(allowed_evars=AllowedEvars.all) ?(status=univ_rigid) ?(onlyalg=false) ?(refreshset=false)
118 pbty env evd t =
119 let evdref = ref evd in
120 (* direction: true for fresh universes lower than the existing ones *)
121 let refresh_sort status ~direction s =
122 let sigma, l = new_univ_level_variable status !evdref in
123 let s' = match ESorts.kind sigma s with
124 | QSort (q, _) -> Sorts.qsort q (Univ.Universe.make l)
125 | _ -> Sorts.sort_of_univ @@ Univ.Universe.make l
126 in
127 let s' = ESorts.make s' in
128 evdref := sigma;
129 let evd =
130 if direction then set_leq_sort !evdref s' s
131 else set_leq_sort !evdref s s'
132 in evdref := evd; mkSort s'
133 in
134 let rec refresh ~onlyalg status ~direction t =
135 match EConstr.kind !evdref t with
136 | Sort s ->
137 begin match ESorts.kind !evdref s with
138 | Type u | QSort (_, u) ->
139 (* TODO: check if max(l,u) is not ok as well *)
140 (match Univ.Universe.level u with
141 | None -> refresh_sort status ~direction s
142 | Some l ->
143 (if Univ.Level.Set.mem l (fst @@ Evd.universe_context_set !evdref) then
144 let () = if UState.is_algebraic l (Evd.ustate !evdref) then
145 evdref := Evd.make_nonalgebraic_variable !evdref l
146 in
147 t
148 else if not onlyalg && (not (Univ.Level.is_set l) || (refreshset && not direction))
149 then refresh_sort status ~direction s
150 else t))
151 | Set when refreshset && not direction ->
152 (* Cannot make a universe "lower" than "Set",
153 only refreshing when we want higher universes. *)
154 refresh_sort status ~direction s
155 | Prop | SProp | Set -> t
156 end
157 | Prod (na,u,v) ->
158 let v' = refresh ~onlyalg status ~direction v in
159 if v' == v then t else mkProd (na, u, v')
160 | _ -> t
161 in
162 (* Refresh the types of evars under template polymorphic references *)
163 let rec refresh_term_evars ~onevars ~top t =
164 match EConstr.kind !evdref t with
165 | App (f, args) when Termops.is_template_polymorphic_ref env !evdref f ->
166 let pos = get_polymorphic_positions env !evdref f in
167 refresh_polymorphic_positions args pos; t
168 | App (f, args) when top && isEvar !evdref f ->
169 let f' = refresh_term_evars ~onevars:true ~top:false f in
170 let args' = Array.map (refresh_term_evars ~onevars ~top:false) args in
171 if f' == f && args' == args then t
172 else mkApp (f', args')
173 | Evar (ev, a) when onevars && AllowedEvars.mem allowed_evars ev ->
174 let evi = Evd.find_undefined !evdref ev in
175 let ty = Evd.evar_concl evi in
176 let ty' = refresh ~onlyalg univ_flexible ~direction:true ty in
177 if ty == ty' then t
178 else (evdref := Evd.downcast ev ty' !evdref; t)
179 | Sort s ->
180 (match ESorts.kind !evdref s with
181 | Type u when not (Univ.Universe.is_levels u) ->
182 refresh_sort Evd.univ_flexible ~direction:false s
183 | _ -> t)
184 | _ -> EConstr.map !evdref (refresh_term_evars ~onevars ~top:false) t
185 and refresh_polymorphic_positions args pos =
186 let rec aux i = function
187 | Some _ :: ls ->
188 if i < Array.length args then
189 ignore(refresh_term_evars ~onevars:true ~top:false args.(i));
190 aux (succ i) ls
191 | None :: ls ->
192 if i < Array.length args then
193 ignore(refresh_term_evars ~onevars:false ~top:false args.(i));
194 aux (succ i) ls
195 | [] -> ()
196 in aux 0 pos
197 in
198 let t' =
199 if isArity !evdref t then
200 match pbty with
201 | None ->
202 (* No cumulativity needed, but we still need to refresh the algebraics *)
203 refresh ~onlyalg:true univ_flexible ~direction:false t
204 | Some direction -> refresh ~onlyalg status ~direction t
205 else refresh_term_evars ~onevars:false ~top:true t
206 in !evdref, t'
207
208 let get_type_of_refresh ?(lax=false) env evars t =
209 let tty = Retyping.get_type_of env evars t in
210 let evars', tty = refresh_universes ~onlyalg:true
211 ~status:(Evd.UnivFlexible false) (Some false) env evars tty in
212 evars', tty
213
214 let add_conv_oriented_pb ?(tail=true) (pbty,env,t1,t2) evd =
215 match pbty with
216 | Some true -> add_conv_pb ~tail (Conversion.CUMUL,env,t1,t2) evd
217 | Some false -> add_conv_pb ~tail (Conversion.CUMUL,env,t2,t1) evd
218 | None -> add_conv_pb ~tail (Conversion.CONV,env,t1,t2) evd
219
220 (* We retype applications to ensure the universe constraints are collected *)
221 exception IllTypedInstance of env * evar_map * EConstr.types option * EConstr.types
222 exception IllTypedInstanceFun of env * evar_map * EConstr.constr * EConstr.types
223
224 let checked_appvect, checked_appvect_hook = Hook.make ()
225
226 let recheck_applications unify flags env evdref t =
227 let rec aux env t =
228 (* the order matters: if the sub-applications are incorrect, checked_appvect may fail badly *)
229 iter_with_full_binders env !evdref (fun d env -> push_rel d env) aux env t;
230 match EConstr.kind !evdref t with
231 | App (f, args) ->
232 let evd, _ = Hook.get checked_appvect env !evdref f args in
233 evdref := evd
234 | _ -> ()
235 in
236 try aux env t
237 with PretypeError (env,sigma,e) ->
238 match e with
239 | CantApplyBadTypeExplained (((_,expected,argty),_,_),_) ->
240 raise (IllTypedInstance (env,sigma,Some argty, expected))
241 | TypingError (CantApplyNonFunctional (fj,_)) ->
242 raise (IllTypedInstanceFun (env,sigma,fj.uj_val,fj.uj_type))
243 | _ -> assert false
244
245
246 (*------------------------------------*
247 * Restricting existing evars *
248 *------------------------------------*)
249
250 type 'a update =
251 | UpdateWith of 'a
252 | NoUpdate
253
254 let restrict_evar_key evd evk filter candidates =
255 match filter, candidates with
256 | None, NoUpdate -> evd, evk
257 | _ ->
258 let evi = Evd.find_undefined evd evk in
259 let oldfilter = evar_filter evi in
260 begin match filter, candidates with
261 | Some filter, NoUpdate when Filter.equal oldfilter filter ->
262 evd, evk
263 | _ ->
264 let filter = match filter with
265 | None -> evar_filter evi
266 | Some filter -> filter in
267 let candidates = match candidates with
268 | NoUpdate -> Evd.evar_candidates evi
269 | UpdateWith c -> Some c in
270 restrict_evar evd evk filter candidates
271 end
272
273 (* Restrict an applied evar and returns its restriction in the same context *)
274 (* (the filter is assumed to be at least stronger than the original one) *)
275 let restrict_applied_evar evd (evk,argsv) filter candidates =
276 let evd,newevk = restrict_evar_key evd evk filter candidates in
277 let newargsv = match filter with
278 | None -> (* optim *) argsv
279 | Some filter ->
280 let EvarInfo evi = Evd.find evd evk in
281 let subfilter = Filter.compose (evar_filter evi) filter in
282 Filter.filter_slist subfilter argsv in
283 evd,(newevk,newargsv)
284
285 (* Restrict an evar in the current evar_map *)
286 let restrict_evar evd evk filter candidates =
287 fst (restrict_evar_key evd evk filter candidates)
288
289 (* Restrict an evar in the current evar_map *)
290 let restrict_instance evd evk filter argsv =
291 match filter with None -> argsv | Some filter ->
292 let EvarInfo evi = Evd.find evd evk in
293 Filter.filter_slist (Filter.compose (evar_filter evi) filter) argsv
294
295 open Context.Rel.Declaration
296 let noccur_evar env evd evk c =
297 let cache = ref Int.Set.empty (* cache for let-ins *) in
298 let rec occur_rec check_types (k, env as acc) c =
299 match EConstr.kind evd c with
300 | Evar (evk',args' as ev') ->
301 if Evar.equal evk evk' then raise Occur
302 else (if check_types then
303 occur_rec false acc (existential_type evd ev');
304 SList.Skip.iter (occur_rec check_types acc) args')
305 | Rel i when i > k ->
306 if not (Int.Set.mem (i-k) !cache) then
307 let decl = Environ.lookup_rel i env in
308 if check_types then
309 (cache := Int.Set.add (i-k) !cache; occur_rec false acc (lift i (EConstr.of_constr (get_type decl))));
310 (match decl with
311 | LocalAssum _ -> ()
312 | LocalDef (_,b,_) -> cache := Int.Set.add (i-k) !cache; occur_rec false acc (lift i (EConstr.of_constr b)))
313 | Proj (p,_,c) -> occur_rec true acc c
314 | _ -> iter_with_full_binders env evd (fun rd (k,env) -> (succ k, push_rel rd env))
315 (occur_rec check_types) acc c
316 in
317 try occur_rec false (0,env) c; true with Occur -> false
318
319 (****************************************)
320 (* Managing chains of local definitions *)
321 (****************************************)
322
323 type alias =
324 | RelAlias of int
325 | VarAlias of Id.t
326
327 let of_alias = function
328 | RelAlias n -> mkRel n
329 | VarAlias id -> mkVar id
330
331 let to_alias sigma c = match EConstr.kind sigma c with
332 | Rel n -> Some (RelAlias n)
333 | Var id -> Some (VarAlias id)
334 | _ -> None
335
336 let is_alias sigma c alias = match EConstr.kind sigma c, alias with
337 | Var id, VarAlias id' -> Id.equal id id'
338 | Rel n, RelAlias n' -> Int.equal n n'
339 | _ -> false
340
341 let eq_alias a b = match a, b with
342 | RelAlias n, RelAlias m -> Int.equal m n
343 | VarAlias id1, VarAlias id2 -> Id.equal id1 id2
344 | _ -> false
345
346 let compare_alias a b = match a, b with
347 | RelAlias n, RelAlias m -> Int.compare n m
348 | VarAlias id1, VarAlias id2 -> Id.compare id1 id2
349 | RelAlias _, VarAlias _ -> -1
350 | VarAlias _, RelAlias _ -> 1
351
352 module AlsOrd = struct type t = alias let compare = compare_alias end
353 module AlsMap = Map.Make(AlsOrd)
354
355 (* A chain of let-in ended either by a declared variable or a non-variable term *)
356 (* e.g. [x:=t;y:=x;z:=y] binds [z] to [NonVarAliasChain ([y;x],t)] *)
357 (* and. [a:T;x:=a;y:=x;z:=y] binds [z] to [VarAliasChain ([y;x],a)] *)
358 type 'a alias_chain =
359 | VarAliasChain of alias list * alias
360 | NonVarAliasChain of alias list * 'a
361
362 let init_var_alias_chain x = VarAliasChain ([], x)
363 let init_term_alias_chain c = NonVarAliasChain ([], c)
364
365 let push_alias aliases_chain a =
366 (* most recent variables come first *)
367 match aliases_chain with
368 | VarAliasChain (l, last) -> VarAliasChain (a :: l, last)
369 | NonVarAliasChain (l, last) -> NonVarAliasChain (a :: l, last)
370
371 module Alias =
372 struct
373 type t = { mutable lift : int; mutable data : EConstr.t }
374
375 let make c = { lift = 0; data = c }
376
377 let lift n { lift; data } = { lift = lift + n; data }
378
379 let eval alias =
380 let c = EConstr.Vars.lift alias.lift alias.data in
381 let () = alias.lift <- 0 in
382 let () = alias.data <- c in
383 c
384
385 let repr sigma alias = match EConstr.kind sigma alias.data with
386 | Rel n -> Some (RelAlias (n + alias.lift))
387 | Var id -> Some (VarAlias id)
388 | _ -> None
389
390 end
391
392 let lift_alias_chain n alias_chain =
393 let map a = match a with
394 | VarAlias _ -> a
395 | RelAlias m -> RelAlias (m + n)
396 in
397 match alias_chain with
398 | VarAliasChain (l, alias) -> VarAliasChain (List.map map l, map alias)
399 | NonVarAliasChain (l, alias) -> NonVarAliasChain (List.map map l, Alias.lift n alias)
400
401 let cast_alias_chain = function
402 | VarAliasChain (l, v) -> VarAliasChain (l, v)
403 | NonVarAliasChain (l, c) -> NonVarAliasChain (l, Alias.make c)
404
405 type aliases = {
406 rel_aliases : Alias.t alias_chain Int.Map.t;
407 var_aliases : EConstr.t alias_chain Id.Map.t;
408 (** Only contains [VarAlias] *)
409 }
410
411 (* Expand rels and vars that are bound to other rels or vars so that
412 dependencies in variables are canonically associated to the most ancient
413 variable in its family of aliased variables *)
414
415 let compute_var_aliases sign sigma =
416 let open Context.Named.Declaration in
417 (* push from oldest to more recent variables *)
418 List.fold_right (fun decl aliases ->
419 let id = get_id decl in
420 match decl with
421 | LocalDef (_,t,_) ->
422 let aliases_of_id =
423 match EConstr.kind sigma t with
424 | Var id' ->
425 (try push_alias (Id.Map.find id' aliases) (VarAlias id')
426 with Not_found -> init_var_alias_chain (VarAlias id'))
427 | _ ->
428 init_term_alias_chain t in
429 Id.Map.add id aliases_of_id aliases
430 | LocalAssum _ -> aliases)
431 sign Id.Map.empty
432
433 let compute_rel_aliases var_aliases rels sigma =
434 (* push from oldest to more recent variables *)
435 snd (List.fold_right
436 (fun decl (n,aliases) ->
437 (n-1,
438 match decl with
439 | LocalDef (_,t,u) ->
440 let aliases_of_n =
441 match EConstr.kind sigma t with
442 | Var id' ->
443 (let alias = VarAlias id' in
444 try push_alias (cast_alias_chain (Id.Map.find id' var_aliases)) alias
445 with Not_found -> init_var_alias_chain alias)
446 | Rel p ->
447 (let alias = RelAlias (p+n) in
448 try push_alias (Int.Map.find (p+n) aliases) alias
449 with Not_found -> init_var_alias_chain alias)
450 | _ ->
451 init_term_alias_chain (Alias.lift n (Alias.make @@ mkCast(t,DEFAULTcast, u)))
452 in
453 Int.Map.add n aliases_of_n aliases
454 | LocalAssum _ -> aliases)
455 )
456 rels
457 (List.length rels,Int.Map.empty))
458
459 let make_alias_map env sigma =
460 (* We compute the chain of aliases for each var and rel *)
461 let var_aliases = compute_var_aliases (named_context env) sigma in
462 let rel_aliases = compute_rel_aliases var_aliases (rel_context env) sigma in
463 { var_aliases; rel_aliases }
464
465 let lift_aliases n aliases =
466 if Int.equal n 0 then aliases else
467 let rel_aliases =
468 Int.Map.fold (fun p l -> Int.Map.add (p+n) (lift_alias_chain n l))
469 aliases.rel_aliases Int.Map.empty
470 in
471 { aliases with rel_aliases }
472
473 let get_alias_chain_of aliases x = match x with
474 | RelAlias n -> (try Some (Int.Map.find n aliases.rel_aliases) with Not_found -> None)
475 | VarAlias id -> (try Some (cast_alias_chain (Id.Map.find id aliases.var_aliases)) with Not_found -> None)
476
477 (* Expand an alias as much as possible while remaining a variable *)
478 (* i.e. returns either a declared variable [y], or the last expansion
479 of [x] defined to be [c] and [c] is not a variable *)
480 let normalize_alias aliases x =
481 match get_alias_chain_of aliases x with
482 | None | Some (NonVarAliasChain ([], _)) -> x
483 | Some (NonVarAliasChain (l, _)) -> List.last l
484 | Some (VarAliasChain (_, a)) -> a
485
486 (* Idem, specifically for named variables *)
487 let normalize_alias_var var_aliases id =
488 let aliases = { var_aliases; rel_aliases = Int.Map.empty } in
489 match normalize_alias aliases (VarAlias id) with
490 | VarAlias id -> id
491 | RelAlias _ -> assert false (** var only aliases to variables *)
492
493 let extend_alias sigma decl { var_aliases; rel_aliases } =
494 let rel_aliases =
495 Int.Map.fold (fun n l -> Int.Map.add (n+1) (lift_alias_chain 1 l))
496 rel_aliases Int.Map.empty in
497 let rel_aliases =
498 match decl with
499 | LocalDef(_,t,_) ->
500 let aliases_of_binder =
501 match EConstr.kind sigma t with
502 | Var id' ->
503 let alias = VarAlias id' in
504 (try push_alias (cast_alias_chain (Id.Map.find id' var_aliases)) alias
505 with Not_found -> init_var_alias_chain alias)
506 | Rel p ->
507 let alias = RelAlias (p+1) in
508 (try push_alias (Int.Map.find (p+1) rel_aliases) alias
509 with Not_found -> init_var_alias_chain alias)
510 | _ ->
511 init_term_alias_chain (Alias.lift 1 (Alias.make t))
512 in
513 Int.Map.add 1 aliases_of_binder rel_aliases
514 | LocalAssum _ -> rel_aliases in
515 { var_aliases; rel_aliases }
516
517 let expand_alias_once aliases x =
518 match get_alias_chain_of aliases x with
519 | None -> None
520 | Some (VarAliasChain (x :: _, _) | NonVarAliasChain (x :: _, _) | VarAliasChain ([], x)) -> Some (Alias.make (of_alias x))
521 | Some (NonVarAliasChain ([], a)) -> Some a
522
523 let expansions_of_var aliases x =
524 match get_alias_chain_of aliases x with
525 | None -> [x]
526 | Some (VarAliasChain (l, y)) -> x :: l @ [y]
527 | Some (NonVarAliasChain (l, _)) -> x :: l
528
529 let expansion_of_var sigma aliases x =
530 match get_alias_chain_of aliases x with
531 | None -> (false, Some x, [])
532 | Some (VarAliasChain (l, x)) -> (true, Some x, l)
533 | Some (NonVarAliasChain (l, a)) -> (true, Alias.repr sigma a, l)
534
535 let rec expand_vars_in_term_using env sigma aliases t = match EConstr.kind sigma t with
536 | Rel n -> of_alias (normalize_alias aliases (RelAlias n))
537 | Var id -> of_alias (normalize_alias aliases (VarAlias id))
538 | _ ->
539 let self aliases c = expand_vars_in_term_using env sigma aliases c in
540 map_constr_with_full_binders env sigma (extend_alias sigma) self aliases t
541
542 let expand_vars_in_term env sigma = expand_vars_in_term_using env sigma (make_alias_map env sigma)
543
544 let free_vars_and_rels_up_alias_expansion env sigma aliases c =
545 let fv_rels = ref Int.Set.empty and fv_ids = ref Id.Set.empty in
546 let let_rels = ref Int.Set.empty and let_ids = ref Id.Set.empty in
547 let cache_rel = ref Int.Set.empty and cache_var = ref Id.Set.empty in
548 let is_in_cache depth = function
549 | RelAlias n -> Int.Set.mem (n-depth) !cache_rel
550 | VarAlias s -> Id.Set.mem s !cache_var
551 in
552 let put_in_cache depth = function
553 | RelAlias n -> cache_rel := Int.Set.add (n-depth) !cache_rel
554 | VarAlias s -> cache_var := Id.Set.add s !cache_var
555 in
556 let rec frec (aliases,depth) c =
557 match EConstr.kind sigma c with
558 | Rel _ | Var _ as ck ->
559 let ck = match ck with
560 | Rel n -> RelAlias n
561 | Var id -> VarAlias id
562 | _ -> assert false
563 in
564 if is_in_cache depth ck then () else begin
565 put_in_cache depth ck;
566 let expanded, c', l = expansion_of_var sigma aliases ck in
567 (if expanded then (* expansion, hence a let-in *)
568 List.iter (function
569 | VarAlias id -> let_ids := Id.Set.add id !let_ids
570 | RelAlias n -> if n >= depth+1 then let_rels := Int.Set.add (n-depth) !let_rels)
571 (ck :: l));
572 match c' with
573 | Some (VarAlias id) -> fv_ids := Id.Set.add id !fv_ids
574 | Some (RelAlias n) -> if n >= depth+1 then fv_rels := Int.Set.add (n-depth) !fv_rels
575 | None -> frec (aliases,depth) c end
576 | Const _ | Ind _ | Construct _ ->
577 fv_ids := Id.Set.union (vars_of_global env (fst @@ EConstr.destRef sigma c)) !fv_ids
578 | _ ->
579 iter_with_full_binders env sigma
580 (fun d (aliases,depth) -> (extend_alias sigma d aliases,depth+1))
581 frec (aliases,depth) c
582 in
583 frec (aliases,0) c;
584 (!fv_rels,!fv_ids,!let_rels,!let_ids)
585
586 (********************************)
587 (* Managing pattern-unification *)
588 (********************************)
589
590 let expand_and_check_vars aliases l =
591 let map a = match get_alias_chain_of aliases a with
592 | None -> Some a
593 | Some (VarAliasChain (_, a)) -> Some a
594 | Some (NonVarAliasChain ([], c)) -> None
595 | Some (NonVarAliasChain (l, c)) -> Some (List.last l)
596 in
597 Option.List.map map l
598
599 let alias_distinct l =
600 let rec check (rels, vars) = function
601 | [] -> true
602 | RelAlias n :: l ->
603 not (Int.Set.mem n rels) && check (Int.Set.add n rels, vars) l
604 | VarAlias id :: l ->
605 not (Id.Set.mem id vars) && check (rels, Id.Set.add id vars) l
606 in
607 check (Int.Set.empty, Id.Set.empty) l
608
609 let distinct_actual_deps env evd aliases l t =
610 (* If the aliases are already unique, any subset will also be. *)
611 if alias_distinct l then true
612 (* The instance of a meta can virtually contains any variable of the context *)
613 else if occur_meta evd t then false
614 else
615 (* Probably strong restrictions coming from t being evar-closed *)
616 let (fv_rels,fv_ids,_,_) = free_vars_and_rels_up_alias_expansion env evd aliases t in
617 alias_distinct @@ List.filter (function
618 | VarAlias id -> Id.Set.mem id fv_ids
619 | RelAlias n -> Int.Set.mem n fv_rels
620 ) l
621
622 open Context.Named.Declaration
623 let remove_instance_local_defs evd evk args =
624 let EvarInfo evi = Evd.find evd evk in
625 let rec aux sign args = match sign, args with
626 | [], [] -> []
627 | LocalAssum _ :: sign, c :: args -> c :: aux sign args
628 | LocalDef _ :: sign, _ :: args -> aux sign args
629 | _ -> assert false
630 in
631 aux (evar_filtered_context evi) args
632
633 (* Check if an applied evar "?X[args] l" is a Miller's pattern *)
634
635 let find_unification_pattern_args env evd l t =
636 let aliases = make_alias_map env evd in
637 match expand_and_check_vars aliases l with
638 | Some l as x when distinct_actual_deps env evd aliases l t -> x
639 | _ -> None
640
641 let is_unification_pattern_meta env evd nb m l t =
642 (* Variables from context and rels > nb are implicitly all there *)
643 (* so we need to be a rel <= nb *)
644 let map a = match EConstr.kind evd a with
645 | Rel n -> if n <= nb then Some (RelAlias n) else None
646 | _ -> None
647 in
648 match Option.List.map map l with
649 | Some l ->
650 begin match find_unification_pattern_args env evd l t with
651 | Some _ as x when not (occur_metavariable evd m t) -> x
652 | _ -> None
653 end
654 | None ->
655 None
656
657 let is_unification_pattern_evar env evd (evk,args) l t =
658 match Option.List.map (fun c -> to_alias evd c) l with
659 | Some l when noccur_evar env evd evk t ->
660 let args = Evd.expand_existential evd (evk, args) in
661 let args = remove_instance_local_defs evd evk args in
662 let args = Option.List.map (fun c -> to_alias evd c) args in
663 begin match args with
664 | None -> None
665 | Some args ->
666 let n = List.length args in
667 match find_unification_pattern_args env evd (args @ l) t with
668 | Some l -> Some (List.skipn n l)
669 | _ -> None
670 end
671 | _ -> None
672
673 let is_unification_pattern_pure_evar env evd (evk,args) t =
674 let is_ev = is_unification_pattern_evar env evd (evk,args) [] t in
675 match is_ev with
676 | None -> false
677 | Some _ -> true
678
679 let is_unification_pattern (env,nb) evd f l t =
680 match EConstr.kind evd f with
681 | Meta m -> is_unification_pattern_meta env evd nb m l t
682 | Evar ev -> is_unification_pattern_evar env evd ev l t
683 | _ -> None
684
685 (* From a unification problem "?X l = c", build "\x1...xn.(term1 l2)"
686 (pattern unification). It is assumed that l is made of rel's that
687 are distinct and not bound to aliases. *)
688 (* It is also assumed that c does not contain metas because metas
689 *implicitly* depend on Vars but lambda abstraction will not reflect this
690 dependency: ?X x = ?1 (?1 is a meta) will return \_.?1 while it should
691 return \y. ?1{x\y} (non constant function if ?1 depends on x) (BB) *)
692 let solve_pattern_eqn env sigma l c =
693 let c' = List.fold_right (fun a c ->
694 let c' = subst_term sigma (lift 1 (of_alias a)) (lift 1 c) in
695 match a with
696 (* Rem: if [a] links to a let-in, do as if it were an assumption *)
697 | RelAlias n ->
698 let open Context.Rel.Declaration in
699 let d = map_constr (lift n) (lookup_rel n env) in
700 mkLambda_or_LetIn d c'
701 | VarAlias id ->
702 let d = lookup_named id env in mkNamedLambda_or_LetIn sigma d c'
703 )
704 l c in
705 (* Warning: we may miss some opportunity to eta-reduce more since c'
706 is not in normal form *)
707 shrink_eta sigma c'
708
709 (*****************************************)
710 (* Refining/solving unification problems *)
711 (*****************************************)
712
713 (* Knowing that [Gamma |- ev : T] and that [ev] is applied to [args],
714 * [make_projectable_subst ev args] builds the substitution [Gamma:=args].
715 * If a variable and an alias of it are bound to the same instance, we skip
716 * the alias (we just use eq_constr -- instead of conv --, since anyway,
717 * only instances that are variables -- or evars -- are later considered;
718 * moreover, we can bet that similar instances came at some time from
719 * the very same substitution. The removal of aliased duplicates is
720 * useful to ensure the uniqueness of a projection.
721 *)
722
723 type esubst = {
724 ealias : (alias * Id.t) list Int.Map.t;
725 evalue : (existential * Id.t) Int.Map.t;
726 eindex : Int.Set.t AlsMap.t;
727 (** Reverse map of indices in [ealias] containing the corresponding alias *)
728 }
729
730 let make_constructor_subst sigma sign args =
731 let rec fold decls args accu = match decls, SList.view args with
732 | _ :: _, None | [], Some _ -> assert false
733 | [], None -> accu
734 | LocalAssum ({ binder_name = id }, _) :: decls, Some (Some a, args) ->
735 let accu = fold decls args accu in
736 let a', args = decompose_app sigma a in
737 begin match EConstr.kind sigma a' with
738 | Construct (cstr, _) ->
739 let l = try Constrmap_env.find cstr accu with Not_found -> [] in
740 Constrmap_env.add cstr ((args, id) :: l) accu
741 | _ -> accu
742 end
743 | LocalAssum _ :: decls, Some (None, args) -> fold decls args accu
744 | LocalDef _ :: decls, Some (_, args) -> fold decls args accu
745 in
746 fold sign args Constrmap_env.empty
747
748 let make_projectable_subst aliases sigma sign args =
749 let evar_aliases = compute_var_aliases sign sigma in
750 (* First compute aliasing equivalence classes *)
751 let rec fold accu args decls = match SList.view args, decls with
752 | None, _ :: _ | Some _, [] -> assert false
753 | None, [] -> accu
754 | Some (a, args), decl :: decls ->
755 let (i, all, vals, revmap) = fold accu args decls in
756 let id = get_id decl in
757 let a = match a with None -> mkVar id | Some a -> a in
758 let revmap = Id.Map.add id i revmap in
759 let oldbindings = match decl with
760 | LocalAssum _ -> None
761 | LocalDef (_, c, _) ->
762 match EConstr.kind sigma c with
763 | Var id' ->
764 let idc = normalize_alias_var evar_aliases id' in
765 let ic, sub = match Id.Map.find_opt idc revmap with
766 | Some ic ->
767 let bnd = match Int.Map.find_opt ic all with
768 | None -> []
769 | Some bnd -> bnd
770 in
771 ic, bnd
772 | None ->
773 (* [idc] is a filtered variable: treat [id] as an assumption *)
774 i, []
775 in
776 Some (ic, sub)
777 | _ -> None
778 in
779 let all, vals = match oldbindings with
780 | None ->
781 begin match to_alias sigma a with
782 | Some v -> Int.Map.add i [v, id] all, vals
783 | None ->
784 match destEvar sigma a with
785 | ev -> all, Int.Map.add i (ev, id) vals
786 | exception DestKO -> all, vals
787 end
788 | Some (ic, sub) ->
789 (* Necessarily a let-binding aliasing a variable *)
790 match to_alias sigma a with
791 | None -> all, vals
792 | Some v ->
793 if List.exists (fun (c, _) -> eq_alias v c) sub then all, vals
794 else Int.Map.add ic ((v, id) :: sub) all, vals
795 in
796 (i + 1, all, vals, revmap)
797 in
798 let (_, ealias, evalue, _) = fold (0, Int.Map.empty, Int.Map.empty, Id.Map.empty) args sign in
799 (* Then extract the backpointers. *)
800 let fold i bnd eindex =
801 let fold accu (a, _) = match AlsMap.find a accu with
802 | set -> AlsMap.add a (Int.Set.add i set) accu
803 | exception Not_found -> AlsMap.add a (Int.Set.singleton i) accu
804 in
805 List.fold_left fold eindex bnd
806 in
807 let eindex = Int.Map.fold fold ealias AlsMap.empty in
808 { eindex; ealias; evalue }
809
810 (*------------------------------------*
811 * operations on the evar constraints *
812 *------------------------------------*)
813
814 (* We have a unification problem Σ; Γ |- ?e[u1..uq] = t : s where ?e is not yet
815 * declared in Σ but yet known to be declarable in some context x1:T1..xq:Tq.
816 * [define_evar_from_virtual_equation ... Γ Σ t (x1:T1..xq:Tq) .. (u1..uq) (x1..xq)]
817 * declares x1:T1..xq:Tq |- ?e : s such that ?e[u1..uq] = t holds.
818 *)
819
820 let define_evar_from_virtual_equation define_fun env evd src t_in_env ty_t_in_sign sign filter inst_in_env =
821 assert (EConstr.isSort evd ty_t_in_sign);
822 let (evd, evk) = new_pure_evar sign evd ~relevance:ERelevance.relevant ty_t_in_sign ~filter ~src in
823 let t_in_env = whd_evar evd t_in_env in
824 let evd = define_fun env evd None (evk, inst_in_env) t_in_env in
825 let EvarInfo evi = Evd.find evd evk in
826 let inst_in_sign = evar_identity_subst evi in
827 let evar_in_sign = mkEvar (evk, inst_in_sign) in
828 (evd,whd_evar evd evar_in_sign)
829
830 (* We have x1..xq |- ?e1 : τ and had to solve something like
831 * Σ; Γ |- ?e1[u1..uq] = (...\y1 ... \yk ... c), where c is typically some
832 * ?e2[v1..vn], hence flexible. We had to go through k binders and now
833 * virtually have x1..xq, y1'..yk' | ?e1' : τ' and the equation
834 * Γ, y1..yk |- ?e1'[u1..uq y1..yk] = c.
835 * [materialize_evar Γ evd k (?e1[u1..uq]) τ'] extends Σ with the declaration
836 * of ?e1' and returns both its instance ?e1'[x1..xq y1..yk] in an extension
837 * of the context of e1 so that e1 can be instantiated by
838 * (...\y1' ... \yk' ... ?e1'[x1..xq y1'..yk']),
839 * and the instance ?e1'[u1..uq y1..yk] so that the remaining equation
840 * ?e1'[u1..uq y1..yk] = c can be registered
841 *
842 * Note that, because invert_definition does not check types, we need to
843 * guess the types of y1'..yn' by inverting the types of y1..yn along the
844 * substitution u1..uq.
845 *)
846
847 exception MorePreciseOccurCheckNeeeded
848
849 let materialize_evar define_fun env evd k (evk1,args1) ty_in_env =
850 if Evd.is_defined evd evk1 then
851 (* Some circularity somewhere (see e.g. #3209) *)
852 raise MorePreciseOccurCheckNeeeded;
853 let (evk1,args1) = destEvar evd (mkEvar (evk1,args1)) in
854 let evi1 = Evd.find_undefined evd evk1 in
855 let env1,rel_sign = env_rel_context_chop k env in
856 let sign1 = evar_hyps evi1 in
857 let filter1 = evar_filter evi1 in
858 let src = subterm_source evk1 (Evd.evar_source evi1) in
859 let avoid = Environ.ids_of_named_context_val sign1 in
860 let inst_in_sign = evar_identity_subst evi1 in
861 let open Context.Rel.Declaration in
862 let (sign2,filter2,inst2_in_env,inst2_in_sign,_,evd,_) =
863 List.fold_right (fun d (sign,filter,inst_in_env,inst_in_sign,env,evd,avoid) ->
864 let LocalAssum (na,t_in_env) | LocalDef (na,_,t_in_env) = d in
865 let id = map_annot (fun na -> next_name_away na avoid) na in
866 let evd,t_in_sign =
867 let s = Retyping.get_sort_of env evd t_in_env in
868 let evd,ty_t_in_sign = refresh_universes
869 ~status:univ_flexible (Some false) env evd (mkSort s) in
870 define_evar_from_virtual_equation define_fun env evd src t_in_env
871 ty_t_in_sign sign filter inst_in_env in
872 let evd,d' = match d with
873 | LocalAssum _ -> evd, Context.Named.Declaration.LocalAssum (id,t_in_sign)
874 | LocalDef (_,b,_) ->
875 let evd,b = define_evar_from_virtual_equation define_fun env evd src b
876 t_in_sign sign filter inst_in_env in
877 evd, Context.Named.Declaration.LocalDef (id,b,t_in_sign) in
878 (push_named_context_val d' sign, Filter.extend 1 filter,
879 SList.cons (mkRel 1) (SList.Skip.map (lift 1) inst_in_env),
880 SList.cons (mkRel 1) (SList.Skip.map (lift 1) inst_in_sign),
881 push_rel d env,evd,Id.Set.add id.binder_name avoid))
882 rel_sign
883 (sign1,filter1,args1,inst_in_sign,env1,evd,avoid)
884 in
885 let s = Retyping.get_sort_of env evd ty_in_env in
886 let evd,ev2ty_in_sign =
887 let evd,ty_t_in_sign = refresh_universes
888 ~status:univ_flexible (Some false) env evd (mkSort s) in
889 define_evar_from_virtual_equation define_fun env evd src ty_in_env
890 ty_t_in_sign sign2 filter2 inst2_in_env in
891 let (evd, ev2_in_sign) =
892 let typeclass_candidate = Typeclasses.is_maybe_class_type env evd ev2ty_in_sign in
893 (* XXX is this relevance correct? I don't really understand this code *)
894 new_pure_evar sign2 ~typeclass_candidate evd ~relevance:(ESorts.relevance_of_sort s) ev2ty_in_sign ~filter:filter2 ~src in
895 let ev2_in_env = (ev2_in_sign, inst2_in_env) in
896 (evd, mkEvar (ev2_in_sign, inst2_in_sign), ev2_in_env)
897
898 let restrict_upon_filter evd evk p args =
899 let oldfullfilter = evar_filter (Evd.find_undefined evd evk) in
900 let args = Array.of_list args in
901 let len = Array.length args in
902 Filter.restrict_upon oldfullfilter len (fun i -> p (Array.unsafe_get args i))
903
904 let check_evar_instance_evi unify flags env evd evi body =
905 let evenv = evar_env env evi in
906 (* FIXME: The body might be ill-typed when this is called from w_merge *)
907 (* This happens in practice, cf MathClasses build failure on 2013-3-15 *)
908 match Retyping.get_type_of ~lax:true evenv evd body
909 with
910 | exception Retyping.RetypeError _ ->
911 let loc, _ = Evd.evar_source evi in
912 Loc.raise ?loc (IllTypedInstance (evenv,evd,None, Evd.evar_concl evi))
913 | ty ->
914 match unify flags TypeUnification evenv evd Conversion.CUMUL ty (Evd.evar_concl evi) with
915 | Success evd -> evd
916 | UnifFailure _ -> raise (IllTypedInstance (evenv,evd,Some ty, Evd.evar_concl evi))
917
918 let check_evar_instance unify flags env evd evk body =
919 let evi = try Evd.find_undefined evd evk with Not_found -> assert false in
920 check_evar_instance_evi unify flags env evd evi body
921
922 (***************)
923 (* Unification *)
924
925 (* Inverting constructors in instances (common when inferring type of match) *)
926
927 let find_projectable_constructor env evd cstr k args cstr_subst =
928 try
929 let l = Constrmap_env.find cstr cstr_subst in
930 let args = Array.map (lift (-k)) args in
931 let l =
932 List.filter (fun (args',id) ->
933 (* is_conv is maybe too strong (and source of useless computation) *)
934 (* (at least expansion of aliases is needed) *)
935 Array.for_all2 (fun c1 c2 -> is_conv env evd c1 c2) args args') l in
936 List.map snd l
937 with Not_found ->
938 []
939
940 (* [find_projectable_vars env sigma y subst] finds all vars of [subst]
941 * that project on [y]. It is able to find solutions to the following
942 * two kinds of problems:
943 *
944 * - ?n[...;x:=y;...] = y
945 * - ?n[...;x:=?m[args];...] = y with ?m[args] = y recursively solvable
946 *
947 * (see test-suite/success/Fixpoint.v for an example of application of
948 * the second kind of problem).
949 *
950 * The seek for [y] is up to variable aliasing. In case of solutions that
951 * differ only up to aliasing, the binding that requires the less
952 * steps of alias reduction is kept. At the end, only one solution up
953 * to aliasing is kept.
954 *
955 * [find_projectable_vars] also unifies against evars that themselves mention
956 * [y] and recursively.
957 *
958 * In short, the following situations give the following solutions:
959 *
960 * problem evar ctxt soluce remark
961 * z1; z2:=z1 |- ?ev[z1;z2] = z1 y1:A; y2:=y1 y1 \ thanks to defs kept in
962 * z1; z2:=z1 |- ?ev[z1;z2] = z2 y1:A; y2:=y1 y2 / subst and preferring =
963 * z1; z2:=z1 |- ?ev[z1] = z2 y1:A y1 thanks to expand_var
964 * z1; z2:=z1 |- ?ev[z2] = z1 y1:A y1 thanks to expand_var
965 * z3 |- ?ev[z3;z3] = z3 y1:A; y2:=y1 y2 see make_projectable_subst
966 *
967 * Remark: [find_projectable_vars] assumes that identical instances of
968 * variables in the same set of aliased variables are already removed (see
969 * [make_projectable_subst])
970 *)
971
972 type evar_projection =
973 | ProjectVar
974 | ProjectEvar of EConstr.existential * undefined evar_info * Id.t * evar_projection
975
976 exception NotUnique
977 exception NotUniqueInType of (Id.t * evar_projection) list
978
979 let rec assoc_up_to_alias sigma aliases y = function
980 | [] -> assert false
981 | (c, id)::l ->
982 if eq_alias c y then id
983 else assoc_up_to_alias sigma aliases y l
984
985 let rec find_projectable_vars aliases sigma y subst =
986 let indices = try AlsMap.find y subst.eindex with Not_found -> Int.Set.empty in
987 let is_projectable_var i subst1 =
988 (* First test if some [id] aliased to [idc] is bound to [y] in [subst] *)
989 let idcl = Int.Map.find i subst.ealias in
990 let id = assoc_up_to_alias sigma aliases y idcl in
991 (id, ProjectVar)::subst1
992 in
993 let is_projectable_evar i (c, id) subst2 =
994 (* Then test if [idc] is (indirectly) bound in [subst] to some evar *)
995 (* projectable on [y] *)
996 if Int.Set.mem i indices then subst2 (* already found by is_projectable_var *)
997 else if Evd.is_defined sigma (fst c) then subst2 (* already solved *)
998 else
999 let (evk,argsv as t) = c in
1000 let evi = Evd.find_undefined sigma evk in
1001 let subst = make_projectable_subst aliases sigma (evar_filtered_context evi) argsv in
1002 let l = find_projectable_vars aliases sigma y subst in
1003 match l with
1004 | [id',p] -> (id, ProjectEvar (t, evi, id', p)) :: subst2
1005 | _ -> subst2
1006 in
1007 let subst1 = Int.Set.fold is_projectable_var indices [] in
1008 let subst2 = Int.Map.fold is_projectable_evar subst.evalue [] in
1009 (* We return the substitution with ProjectVar first (from most
1010 recent to oldest var), followed by ProjectEvar (from most recent
1011 to oldest var too) *)
1012 subst1 @ subst2
1013
1014 (* [filter_solution] checks if one and only one possible projection exists
1015 * among a set of solutions to a projection problem *)
1016
1017 let filter_solution = function
1018 | [] -> raise Not_found
1019 | _ :: _ :: _ -> raise NotUnique
1020 | [id] -> mkVar id
1021
1022 let project_with_effects aliases sigma t subst =
1023 let indices = AlsMap.find t subst.eindex in
1024 let is_projectable i accu =
1025 let idcl = Int.Map.find i subst.ealias in
1026 assoc_up_to_alias sigma aliases t idcl :: accu
1027 in
1028 filter_solution (Int.Set.fold is_projectable indices [])
1029
1030 (* In case the solution to a projection problem requires the instantiation of
1031 * subsidiary evars, [do_projection_effects] performs them; it
1032 * also try to instantiate the type of those subsidiary evars if their
1033 * type is an evar too.
1034 *
1035 * Note: typing creates new evar problems, which induces a recursive dependency
1036 * with [define]. To avoid a too large set of recursive functions, we
1037 * pass [define] to [do_projection_effects] as a parameter.
1038 *)
1039
1040 let rec do_projection_effects unify flags define_fun env ty evd = function
1041 | ProjectVar -> evd
1042 | ProjectEvar ((evk,argsv),evi,id,p) ->
1043 let evd = check_evar_instance unify flags env evd evk (mkVar id) in
1044 let evd = Evd.define evk (EConstr.mkVar id) evd in
1045 (* TODO: simplify constraints involving evk *)
1046 let evd = do_projection_effects unify flags define_fun env ty evd p in
1047 let ty = whd_all env evd (Lazy.force ty) in
1048 if not (isSort evd ty) then
1049 (* Don't try to instantiate if a sort because if evar_concl is an
1050 evar it may commit to a univ level which is not the right
1051 one (however, regarding coercions, because t is obtained by
1052 unif, we know that no coercion can be inserted) *)
1053 let ty' = instantiate_evar_array evd evi (Evd.evar_concl evi) argsv in
1054 if isEvar evd ty' then define_fun env evd (Some false) (destEvar evd ty') ty else evd
1055 else
1056 evd
1057
1058 (* Assuming Σ; Γ, y1..yk |- c, [invert_arg_from_subst Γ k Σ [x1:=u1..xn:=un] c]
1059 * tries to return φ(x1..xn) such that equation φ(u1..un) = c is valid.
1060 * The strategy is to imitate the structure of c and then to invert
1061 * the variables of c (i.e. rels or vars of Γ) using the algorithm
1062 * implemented by project_with_effects/find_projectable_vars.
1063 * It returns either a unique solution or says whether 0 or more than
1064 * 1 solutions is found.
1065 *
1066 * Precondition: Σ; Γ, y1..yk |- c /\ Σ; Γ |- u1..un
1067 * Postcondition: if φ(x1..xn) is returned then
1068 * Σ; Γ, y1..yk |- φ(u1..un) = c /\ x1..xn |- φ(x1..xn)
1069 *
1070 * The effects correspond to evars instantiated while trying to project.
1071 *
1072 * [invert_arg_from_subst] is used on instances of evars. Since the
1073 * evars are flexible, these instances are potentially erasable. This
1074 * is why we don't investigate whether evars in the instances of evars
1075 * are unifiable, to the contrary of [invert_definition].
1076 *)
1077
1078 type projectibility_kind =
1079 | NoUniqueProjection
1080 | UniqueProjection of EConstr.constr
1081
1082 type projectibility_status =
1083 | CannotInvert
1084 | Invertible of projectibility_kind
1085
1086 let invert_arg_from_subst evd aliases k0 subst_in_env_extended_with_k_binders c_in_env_extended_with_k_binders =
1087 let rec aux k t =
1088 match EConstr.kind evd t with
1089 | Rel i when i>k0+k -> aux' k (RelAlias (i-k))
1090 | Var id -> aux' k (VarAlias id)
1091 | _ -> map_with_binders evd succ aux k t
1092 and aux' k t =
1093 try project_with_effects aliases evd t subst_in_env_extended_with_k_binders
1094 with Not_found ->
1095 match expand_alias_once aliases t with
1096 | None -> raise Not_found
1097 | Some c -> aux k (Alias.eval (Alias.lift k c)) in
1098 try
1099 let c = aux 0 c_in_env_extended_with_k_binders in
1100 Invertible (UniqueProjection c)
1101 with
1102 | Not_found -> CannotInvert
1103 | NotUnique -> Invertible NoUniqueProjection
1104
1105 let invert_arg fullenv evd aliases k evk subst_in_env_extended_with_k_binders c_in_env_extended_with_k_binders =
1106 let res = invert_arg_from_subst evd aliases k subst_in_env_extended_with_k_binders c_in_env_extended_with_k_binders in
1107 match res with
1108 | Invertible (UniqueProjection c) when not (noccur_evar fullenv evd evk c)
1109 ->
1110 CannotInvert
1111 | _ ->
1112 res
1113
1114 exception NotEnoughInformationToInvert
1115
1116 let extract_unique_projection = function
1117 | Invertible (UniqueProjection c) -> c
1118 | _ ->
1119 (* For instance, there are evars with non-invertible arguments and *)
1120 (* we cannot arbitrarily restrict these evars before knowing if there *)
1121 (* will really be used; it can also be due to some argument *)
1122 (* (typically a rel) that is not inversible and that cannot be *)
1123 (* inverted either because it is needed for typing the conclusion *)
1124 (* of the evar to project *)
1125 raise NotEnoughInformationToInvert
1126
1127 let extract_candidates sols =
1128 try
1129 UpdateWith
1130 (List.map (function (id,ProjectVar) -> mkVar id | _ -> raise_notrace Exit) sols)
1131 with Exit ->
1132 NoUpdate
1133
1134 let invert_invertible_arg fullenv evd aliases k (evk,argsv) args' =
1135 let evi = Evd.find_undefined evd evk in
1136 let subst = make_projectable_subst aliases evd (evar_filtered_context evi) argsv in
1137 let invert arg =
1138 let p = invert_arg fullenv evd aliases k evk subst arg in
1139 extract_unique_projection p
1140 in
1141 List.map invert args'
1142
1143 (* Redefines an evar with a smaller context (i.e. it may depend on less
1144 * variables) such that c becomes closed.
1145 * Example: in "fun (x:?1) (y:list ?2[x]) => x = y :> ?3[x,y] /\ x = nil bool"
1146 * ?3 <-- ?1 no pb: env of ?3 is larger than ?1's
1147 * ?1 <-- list ?2 pb: ?2 may depend on x, but not ?1.
1148 * What we do is that ?2 is defined by a new evar ?4 whose context will be
1149 * a prefix of ?2's env, included in ?1's env.
1150 *
1151 * If "hyps |- ?e : T" and "filter" selects a subset hyps' of hyps then
1152 * [do_restrict_hyps evd ?e filter] sets ?e:=?e'[hyps'] and returns ?e'
1153 * such that "hyps' |- ?e : T"
1154 *)
1155
1156 let set_of_evctx l =
1157 List.fold_left (fun s decl -> Id.Set.add (get_id decl) s) Id.Set.empty l
1158
1159 let filter_effective_candidates evd evi filter candidates =
1160 match filter with
1161 | None -> candidates
1162 | Some filter ->
1163 let ids = set_of_evctx (Filter.filter_list filter (evar_context evi)) in
1164 List.filter (fun a -> Id.Set.subset (collect_vars evd a) ids) candidates
1165
1166 let filter_candidates evd evk filter candidates_update =
1167 let evi = Evd.find_undefined evd evk in
1168 let candidates = match candidates_update with
1169 | NoUpdate -> Evd.evar_candidates evi
1170 | UpdateWith c -> Some c
1171 in
1172 match candidates with
1173 | None -> NoUpdate
1174 | Some l ->
1175 let l' = filter_effective_candidates evd evi filter l in
1176 if List.length l = List.length l' && candidates_update = NoUpdate then
1177 NoUpdate
1178 else
1179 UpdateWith l'
1180
1181 (* Given a filter refinement for the evar [evk], restrict it so that
1182 dependencies are preserved *)
1183
1184 let closure_of_filter ~can_drop evd evk = function
1185 | None -> None
1186 | Some filter ->
1187 let evi = Evd.find_undefined evd evk in
1188 let vars = collect_vars evd (evar_concl evi) in
1189 let test b decl = b || Id.Set.mem (get_id decl) vars ||
1190 match decl with
1191 | LocalAssum _ ->
1192 false
1193 | LocalDef (_,c,_) ->
1194 not (can_drop || isRel evd c || isVar evd c)
1195 in
1196 let newfilter = Filter.map_along test filter (evar_context evi) in
1197 (* Now ensure that restriction is at least what is was originally *)
1198 let newfilter = Option.cata (Filter.map_along (&&) newfilter) newfilter (Filter.repr (evar_filter evi)) in
1199 if Filter.equal newfilter (evar_filter evi) then None else Some newfilter
1200
1201 (* The filter is assumed to be at least stronger than the original one *)
1202 let restrict_hyps ~can_drop evd evk filter candidates =
1203 (* What to do with dependencies?
1204 Assume we have x:A, y:B(x), z:C(x,y) |- ?e:T(x,y,z) and restrict on y.
1205 - If y is in a non-erasable position in C(x,y) (i.e. it is not below an
1206 occurrence of x in the hnf of C), then z should be removed too.
1207 - If y is in a non-erasable position in T(x,y,z) then the problem is
1208 unsolvable.
1209 Computing whether y is erasable or not may be costly and the
1210 interest for this early detection in practice is not obvious. We let
1211 it for future work. In any case, thanks to the use of filters, the whole
1212 (unrestricted) context remains consistent. *)
1213 let candidates = filter_candidates evd evk (Some filter) candidates in
1214 let typablefilter = closure_of_filter ~can_drop evd evk (Some filter) in
1215 (typablefilter,candidates)
1216
1217 exception EvarSolvedWhileRestricting of evar_map * EConstr.constr
1218
1219 let do_restrict_hyps ~can_drop evd (evk,args as ev) filter candidates =
1220 let filter,candidates = match filter with
1221 | None -> None,candidates
1222 | Some filter -> restrict_hyps ~can_drop evd evk filter candidates in
1223 match candidates,filter with
1224 | UpdateWith [], _ -> user_err Pp.(str "Not solvable.")
1225 | UpdateWith [nc],_ ->
1226 let evd = Evd.define evk nc evd in
1227 raise (EvarSolvedWhileRestricting (evd,mkEvar ev))
1228 | NoUpdate, None -> evd,ev
1229 | _ -> restrict_applied_evar evd ev filter candidates
1230
1231 (* [postpone_non_unique_projection] postpones equation of the form ?e[?] = c *)
1232 (* ?e is assumed to have no candidates *)
1233
1234 let postpone_non_unique_projection env evd pbty (evk,argsv as ev) sols rhs =
1235 let rhs = expand_vars_in_term env evd rhs in
1236 let filter a = match EConstr.kind evd a with
1237 | Rel n -> not (noccurn evd n rhs)
1238 | Var id ->
1239 local_occur_var evd id rhs
1240 || List.exists (fun (id', _) -> Id.equal id id') sols
1241 | _ -> true
1242 in
1243 let argsv = Evd.expand_existential evd (evk, argsv) in
1244 let filter = restrict_upon_filter evd evk filter argsv in
1245 (* Keep only variables that occur in rhs *)
1246 (* This is not safe: is the variable is a local def, its body *)
1247 (* may contain references to variables that are removed, leading to *)
1248 (* an ill-formed context. We would actually need a notion of filter *)
1249 (* that says that the body is hidden. Note that expand_vars_in_term *)
1250 (* expands only rels and vars aliases, not rels or vars bound to an *)
1251 (* arbitrary complex term *)
1252 let filter = closure_of_filter ~can_drop:false evd evk filter in
1253 let candidates = extract_candidates sols in
1254 match candidates with
1255 | NoUpdate ->
1256 (* We made an approximation by not expanding a local definition *)
1257 let evd,ev = restrict_applied_evar evd ev filter NoUpdate in
1258 let pb = (pbty,env,mkEvar ev,rhs) in
1259 add_conv_oriented_pb pb evd
1260 | UpdateWith c ->
1261 restrict_evar evd evk filter (UpdateWith c)
1262
1263 (* [solve_evar_evar f Γ Σ ?e1[u1..un] ?e2[v1..vp]] applies an heuristic
1264 * to solve the equation Σ; Γ ⊢ ?e1[u1..un] = ?e2[v1..vp]:
1265 * - if there are at most one φj for each vj s.t. vj = φj(u1..un),
1266 * we first restrict ?e2 to the subset v_k1..v_kq of the vj that are
1267 * inversible and we set ?e1[x1..xn] := ?e2[φk1(x1..xn)..φkp(x1..xn)]
1268 * (this is a case of pattern-unification)
1269 * - symmetrically if there are at most one ψj for each uj s.t.
1270 * uj = ψj(v1..vp),
1271 * - otherwise, each position i s.t. ui does not occur in v1..vp has to
1272 * be restricted and similarly for the vi, and we leave the equation
1273 * as an open equation (performed by [postpone_evar])
1274 *
1275 * Warning: the notion of unique φj is relative to some given class
1276 * of unification problems
1277 *
1278 * Note: argument f is the function used to instantiate evars.
1279 *)
1280
1281 let filter_compatible_candidates unify flags env evd evi args rhs c =
1282 let c' = instantiate_evar_array evd evi c args in
1283 match unify flags TermUnification env evd Conversion.CONV rhs c' with
1284 | Success evd -> Inl (c,evd)
1285 | UnifFailure _ -> Inr c'
1286
1287 (* [restrict_candidates ... filter ev1 ev2] restricts the candidates
1288 of ev1, removing those not compatible with the filter, as well as
1289 those not convertible to some candidate of ev2 *)
1290
1291 exception DoesNotPreserveCandidateRestriction
1292
1293 let restrict_candidates unify flags env evd filter1 (evk1,argsv1) (evk2,argsv2) =
1294 let evi1 = Evd.find_undefined evd evk1 in
1295 let evi2 = Evd.find_undefined evd evk2 in
1296 match Evd.evar_candidates evi1, Evd.evar_candidates evi2 with
1297 | _, None -> filter_candidates evd evk1 filter1 NoUpdate
1298 | None, Some _ -> raise DoesNotPreserveCandidateRestriction
1299 | Some l1, Some l2 ->
1300 let l1 = filter_effective_candidates evd evi1 filter1 l1 in
1301 let l1' = List.filter (fun c1 ->
1302 let c1' = instantiate_evar_array evd evi1 c1 argsv1 in
1303 let filter c2 =
1304 let compatibility = filter_compatible_candidates unify flags env evd evi2 argsv2 c1' c2 in
1305 match compatibility with
1306 | Inl _ -> true
1307 | Inr _ -> false
1308 in
1309 let filtered = List.filter filter l2 in
1310 match filtered with [] -> false | _ -> true) l1 in
1311 if Int.equal (List.length l1) (List.length l1') then NoUpdate
1312 else UpdateWith l1'
1313
1314 exception CannotProject of evar_map * EConstr.existential
1315
1316 (* Assume that FV(?n[x1:=t1..xn:=tn]) belongs to some set U.
1317 Can ?n be instantiated by a term u depending essentially on xi such that the
1318 FV(u[x1:=t1..xn:=tn]) are in the set U?
1319 - If ti is a variable, it has to be in U.
1320 - If ti is a constructor, its parameters cannot be erased even if u
1321 matches on it, so we have to discard ti if the parameters
1322 contain variables not in U.
1323 - If ti is rigid, we have to discard it if it contains variables in U.
1324
1325 Note: when restricting as part of an equation ?n[x1:=t1..xn:=tn] = ?m[...]
1326 then, occurrences of ?m in the ti can be seen, like variables, as occurrences
1327 of subterms to eventually discard so as to be allowed to keep ti.
1328 *)
1329
1330 let rec is_constrainable_in top env evd k (evk,(fv_rels,fv_ids) as g) t =
1331 let f,args = decompose_app evd t in
1332 match EConstr.kind evd f with
1333 | Construct ((ind,_),u) ->
1334 let n = Inductiveops.inductive_nparams env ind in
1335 if n > Array.length args then true (* We don't try to be more clever *)
1336 else
1337 let params = fst (Array.chop n args) in
1338 Array.for_all (is_constrainable_in false env evd k g) params
1339 | Ind _ -> Array.for_all (is_constrainable_in false env evd k g) args
1340 | Prod (na,t1,t2) -> is_constrainable_in false env evd k g t1 && is_constrainable_in false env evd k g t2
1341 | Evar (evk',_ as ev') ->
1342 (*If ev' needed, one may also try to restrict it*)
1343 top || not (Evar.equal evk' evk || occur_evar evd evk (Evd.existential_type evd ev'))
1344 | Var id -> Id.Set.mem id fv_ids
1345 | Rel n -> n <= k || Int.Set.mem n fv_rels
1346 | Sort _ -> true
1347 | _ -> (* We don't try to be more clever *) true
1348
1349 let has_constrainable_free_vars env evd aliases force k ev (fv_rels,fv_ids,let_rels,let_ids) t =
1350 match to_alias evd t with
1351 | Some t ->
1352 let expanded, _, _ = expansion_of_var evd aliases t in
1353 if expanded then
1354 (* t is a local definition, we keep it only if appears in the list *)
1355 (* of let-in variables effectively occurring on the right-hand side, *)
1356 (* which is the only reason to keep it when inverting arguments *)
1357 match t with
1358 | VarAlias id -> Id.Set.mem id let_ids
1359 | RelAlias n -> Int.Set.mem n let_rels
1360 else begin match t with
1361 | VarAlias id -> Id.Set.mem id fv_ids
1362 | RelAlias n -> n <= k || Int.Set.mem n fv_rels
1363 end
1364 | None ->
1365 (* t is an instance for a proper variable; we filter it along *)
1366 (* the free variables allowed to occur *)
1367 (not force || noccur_evar env evd ev t) && is_constrainable_in true env evd k (ev,(fv_rels,fv_ids)) t
1368
1369 exception EvarSolvedOnTheFly of evar_map * EConstr.constr
1370
1371 (* Try to project evk1[argsv1] on evk2[argsv2], if [ev1] is a pattern on
1372 the common domain of definition *)
1373 let project_evar_on_evar force unify flags env evd aliases k2 pbty (evk1,argsv1 as ev1) (evk2,argsv2 as ev2) =
1374 if Option.is_empty pbty && SList.is_default argsv2 &&
1375 (* This ensures that the named context of [evk2] is a permutation of the one
1376 from [env]. In particular its filter must be trivial. *)
1377 Int.equal (SList.length argsv2) (Range.length (Environ.named_context_val env).env_named_idx) &&
1378 SList.Skip.for_all (fun arg -> noccur_evar env evd evk2 arg && closed0 evd arg) argsv1 &&
1379 let evi2 = Evd.find_undefined evd evk2 in Option.is_empty (Evd.evar_candidates evi2)
1380 then
1381 evd, EConstr.mkEvar ev1
1382 else
1383 (* Apply filtering on ev1 so that fvs(ev1) are in fvs(ev2). *)
1384 let fvs2 = free_vars_and_rels_up_alias_expansion env evd aliases (mkEvar ev2) in
1385 let argsv1 = Evd.expand_existential evd ev1 in
1386 let filter1 = restrict_upon_filter evd evk1
1387 (has_constrainable_free_vars env evd aliases force k2 evk2 fvs2)
1388 argsv1 in
1389 let candidates1 =
1390 try restrict_candidates unify flags env evd filter1 ev1 ev2
1391 with DoesNotPreserveCandidateRestriction ->
1392 let evd,ev1' = do_restrict_hyps ~can_drop:force evd ev1 filter1 NoUpdate in
1393 raise (CannotProject (evd,ev1')) in
1394 let evd,(evk1',args1 as ev1') =
1395 try do_restrict_hyps ~can_drop:force evd ev1 filter1 candidates1
1396 with EvarSolvedWhileRestricting (evd,ev1) ->
1397 raise (EvarSolvedOnTheFly (evd,ev1)) in
1398 (* Only try pruning on variable substitutions, postpone otherwise. *)
1399 (* Rules out non-linear instances. *)
1400 if Option.is_empty pbty && is_unification_pattern_pure_evar env evd ev2 (mkEvar ev1) then
1401 try
1402 let args1 = Evd.expand_existential evd ev1' in
1403 evd, EConstr.mkLEvar evd (evk1', invert_invertible_arg env evd aliases k2 ev2 args1)
1404 with NotEnoughInformationToInvert ->
1405 raise (CannotProject (evd,ev1'))
1406 else
1407 raise (CannotProject (evd,ev1'))
1408
1409 let update_evar_info ev1 ev2 evd =
1410 (* We update the source of obligation evars during evar-evar unifications. *)
1411 let EvarInfo evi1 = Evd.find evd ev1 in
1412 let loc, evs1 = evar_source evi1 in
1413 Evd.update_source evd ev2 (loc, evs1)
1414
1415 let solve_evar_evar_l2r force f unify flags env evd aliases pbty ev1 (evk2,_ as ev2) =
1416 try
1417 let evd,body = project_evar_on_evar force unify flags env evd aliases 0 pbty ev1 ev2 in
1418 let evd =
1419 if is_obligation_evar evd evk2 then
1420 update_evar_info evk2 (fst (destEvar evd body)) evd
1421 else evd
1422 in
1423 let evi = Evd.find_undefined evd evk2 in
1424 let evd' = Evd.define_with_evar evk2 body evd in
1425 check_evar_instance_evi unify flags env evd' evi body
1426 with EvarSolvedOnTheFly (evd,c) ->
1427 f env evd pbty ev2 c
1428
1429 let opp_problem = function None -> None | Some b -> Some (not b)
1430
1431 let preferred_orientation evd evk1 evk2 =
1432 if is_obligation_evar evd evk1 then true
1433 else if is_obligation_evar evd evk2 then false
1434 else true
1435
1436 let solve_evar_evar_aux force f unify flags env evd pbty (evk1,args1 as ev1) (evk2,args2 as ev2) =
1437 let aliases = make_alias_map env evd in
1438 let allowed_ev1 = is_evar_allowed flags evk1 in
1439 let allowed_ev2 = is_evar_allowed flags evk2 in
1440 if preferred_orientation evd evk1 evk2 then
1441 try if allowed_ev1 then
1442 solve_evar_evar_l2r force f unify flags env evd aliases (opp_problem pbty) ev2 ev1
1443 else raise (CannotProject (evd,ev2))
1444 with CannotProject (evd,ev2) ->
1445 try if allowed_ev2 then
1446 solve_evar_evar_l2r force f unify flags env evd aliases pbty ev1 ev2
1447 else raise (CannotProject (evd,ev1))
1448 with CannotProject (evd,ev1) ->
1449 add_conv_oriented_pb ~tail:true (pbty,env,mkEvar ev1,mkEvar ev2) evd
1450 else
1451 try if allowed_ev2 then
1452 solve_evar_evar_l2r force f unify flags env evd aliases pbty ev1 ev2
1453 else raise (CannotProject (evd,ev1))
1454 with CannotProject (evd,ev1) ->
1455 try if allowed_ev1 then
1456 solve_evar_evar_l2r force f unify flags env evd aliases (opp_problem pbty) ev2 ev1
1457 else raise (CannotProject (evd,ev2))
1458 with CannotProject (evd,ev2) ->
1459 add_conv_oriented_pb ~tail:true (pbty,env,mkEvar ev1,mkEvar ev2) evd
1460
1461 (** Precondition: evk1 is not frozen *)
1462 let solve_evar_evar ?(force=false) f unify flags env evd pbty (evk1,args1 as ev1) (evk2,args2 as ev2) =
1463 let pbty = if force then None else pbty in
1464 let evi = Evd.find_undefined evd evk1 in
1465 let downcast evk t evd = downcast evk t evd in
1466 let evd =
1467 try
1468 (* ?X : Π Δ. Type i = ?Y : Π Δ'. Type j.
1469 The body of ?X and ?Y just has to be of type Π Δ. Type k for some k <= i, j. *)
1470 let evienv = Evd.evar_env env evi in
1471 let ctx1, i = Reductionops.dest_arity evienv evd (Evd.evar_concl evi) in
1472 let evi2 = Evd.find_undefined evd evk2 in
1473 let evi2env = Evd.evar_env env evi2 in
1474 let ctx2, j = Reductionops.dest_arity evi2env evd (Evd.evar_concl evi2) in
1475 if i == j || Evd.check_eq evd i j
1476 then (* Shortcut, i = j *)
1477 evd
1478 else if Evd.check_leq evd i j then
1479 let t2 = it_mkProd_or_LetIn (mkSort i) ctx2 in
1480 downcast evk2 t2 evd
1481 else if Evd.check_leq evd j i then
1482 let t1 = it_mkProd_or_LetIn (mkSort j) ctx1 in
1483 downcast evk1 t1 evd
1484 else
1485 let evd, k = Evd.new_sort_variable univ_flexible_alg evd in
1486 let t1 = it_mkProd_or_LetIn (mkSort k) ctx1 in
1487 let t2 = it_mkProd_or_LetIn (mkSort k) ctx2 in
1488 let evd = Evd.set_leq_sort (Evd.set_leq_sort evd k i) k j in
1489 downcast evk2 t2 (downcast evk1 t1 evd)
1490 with Reduction.NotArity ->
1491 evd in
1492 solve_evar_evar_aux force f unify flags env evd pbty ev1 ev2
1493
1494 (* Solve pbs ?e[t1..tn] = ?e[u1..un] which arise often in fixpoint
1495 * definitions. We try to unify the ti with the ui pairwise. The pairs
1496 * that don't unify are discarded (i.e. ?e is redefined so that it does not
1497 * depend on these args). *)
1498
1499 let solve_refl ?(can_drop=false) unify flags env evd pbty evk argsv1 argsv2 =
1500 let evdref = ref evd in
1501 let eq_constr c1 c2 = match EConstr.eq_constr_universes env !evdref c1 c2 with
1502 | None -> false
1503 | Some cstr ->
1504 try evdref := Evd.add_constraints !evdref cstr; true
1505 with UniversesDiffer -> false
1506 in
1507 let argsv1e = Evd.expand_existential !evdref (evk, argsv1) in
1508 let argsv2e = Evd.expand_existential !evdref (evk, argsv2) in
1509 if List.equal eq_constr argsv1e argsv2e then !evdref else
1510 (* Filter and restrict if needed *)
1511 let args = List.map2 (fun a1 a2 -> (a1, a2)) argsv1e argsv2e in
1512 let untypedfilter =
1513 restrict_upon_filter evd evk
1514 (fun (a1,a2) -> unify flags TermUnification env evd Conversion.CONV a1 a2) args in
1515 let candidates = filter_candidates evd evk untypedfilter NoUpdate in
1516 let filter = closure_of_filter ~can_drop:false evd evk untypedfilter in
1517 let evd',ev1 = restrict_applied_evar evd (evk, argsv1) filter candidates in
1518 let allowed = is_evar_allowed flags evk in
1519 if Evar.equal (fst ev1) evk && (not allowed || can_drop) then
1520 (* No refinement needed *) evd'
1521 else
1522 (* either progress, or not allowed to drop, e.g. to preserve possibly *)
1523 (* informative equations such as ?e[x:=?y]=?e[x:=?y'] where we don't know *)
1524 (* if e can depend on x until ?y is not resolved, or, conversely, we *)
1525 (* don't know if ?y has to be unified with ?y, until e is resolved *)
1526 if not allowed then
1527 (* We cannot prune a frozen evar *)
1528 add_conv_oriented_pb (pbty,env,mkEvar (evk, argsv1),mkEvar (evk, argsv2)) evd
1529 else
1530 let argsv2 = restrict_instance evd' evk filter argsv2 in
1531 let ev2 = (fst ev1,argsv2) in
1532 (* Leave a unification problem *)
1533 add_conv_oriented_pb (pbty,env,mkEvar ev1,mkEvar ev2) evd'
1534
1535 (* If the evar can be instantiated by a finite set of candidates known
1536 in advance, we check which of them apply *)
1537
1538 exception NoCandidates
1539 exception IncompatibleCandidates of EConstr.t
1540
1541 let solve_candidates unify flags env evd (evk,argsv) rhs =
1542 let evi = Evd.find_undefined evd evk in
1543 match Evd.evar_candidates evi with
1544 | None -> raise NoCandidates
1545 | Some l ->
1546 let rec aux = function
1547 | [] -> [], []
1548 | c::l ->
1549 let compatl, disjointl = aux l in
1550 match filter_compatible_candidates unify flags env evd evi argsv rhs c with
1551 | Inl c -> c::compatl, disjointl
1552 | Inr c -> compatl, c::disjointl in
1553 match aux l with
1554 | [], c::_ -> raise (IncompatibleCandidates c)
1555 | [c,evd], _ ->
1556 (* solve_candidates might have been called recursively in the mean *)
1557 (* time and the evar been solved by the filtering process *)
1558 if Evd.is_undefined evd evk then
1559 let evd = check_evar_instance unify flags env evd evk c in
1560 let evd = Evd.define evk c evd in
1561 evd
1562 else evd
1563 | l, _::_ (* At least one discarded candidate *) ->
1564 let candidates = List.map fst l in
1565 restrict_evar evd evk None (UpdateWith candidates)
1566 | l, [] -> evd
1567
1568 let occur_evar_upto_types sigma n c =
1569 let seen = ref Evar.Set.empty in
1570 let rec occur_rec c = match EConstr.kind sigma c with
1571 | Evar (sp,_) when Evar.equal sp n -> raise Occur
1572 | Evar (sp,args as e) ->
1573 if Evar.Set.mem sp !seen then
1574 SList.Skip.iter occur_rec args
1575 else (
1576 seen := Evar.Set.add sp !seen;
1577 occur_rec (Evd.existential_type sigma e))
1578 | _ -> EConstr.iter sigma occur_rec c
1579 in
1580 try occur_rec c; false with Occur -> true
1581
1582 let instantiate_evar unify flags env evd evk body =
1583 (* Check instance freezing the evar to be defined, as
1584 checking could involve the same evar definition problem again otherwise *)
1585 let allowed_evars = AllowedEvars.remove evk flags.allowed_evars in
1586 let flags = { flags with allowed_evars } in
1587 let evd' = check_evar_instance unify flags env evd evk body in
1588 Evd.define evk body evd'
1589
1590 (* We try to instantiate the evar assuming the body won't depend
1591 * on arguments that are not Rels or Vars, or appearing several times
1592 * (i.e. we tackle a generalization of Miller-Pfenning patterns unification)
1593 *
1594 * 1) Let "env |- ?ev[hyps:=args] = rhs" be the unification problem
1595 * 2) We limit it to a patterns unification problem "env |- ev[subst] = rhs"
1596 * where only Rel's and Var's are relevant in subst
1597 * 3) We recur on rhs, "imitating" the term, and failing if some Rel/Var is
1598 * not in the scope of ?ev. For instance, the problem
1599 * "y:nat |- ?x[] = y" where "|- ?1:nat" is not satisfiable because
1600 * ?1 would be instantiated by y which is not in the scope of ?1.
1601 * 4) We try to "project" the term if the process of imitation fails
1602 * and that only one projection is possible
1603 *
1604 * Note: we don't assume rhs in normal form, it may fail while it would
1605 * have succeeded after some reductions.
1606 *
1607 * This is the work of [invert_definition Γ Σ ?ev[hyps:=args] c]
1608 * Precondition: Σ; Γ, y1..yk |- c /\ Σ; Γ |- u1..un
1609 * Postcondition: if φ(x1..xn) is returned then
1610 * Σ; Γ, y1..yk |- φ(u1..un) = c /\ x1..xn |- φ(x1..xn)
1611 *)
1612
1613 exception NotInvertibleUsingOurAlgorithm of EConstr.constr
1614 exception NotEnoughInformationToProgress of (Id.t * evar_projection) list
1615 exception NotEnoughInformationEvarEvar of EConstr.constr
1616 exception OccurCheckIn of evar_map * EConstr.constr
1617 exception MetaOccurInBodyInternal
1618
1619 let rec invert_definition unify flags choose imitate_defs
1620 env evd pbty (evk,argsv as ev) rhs =
1621 let EvarInfo evi = Evd.find evd evk in
1622 let sign = evar_filtered_context evi in
1623 let rhs = whd_beta env evd rhs (* heuristic *) in
1624 let fast =
1625 let names = ref Id.Set.empty in
1626 let rec is_id_subst ctxt s =
1627 match ctxt, SList.view s with
1628 | (decl :: ctxt'), Some (c, s') ->
1629 let id = get_id decl in
1630 names := Id.Set.add id !names;
1631 (match c with None -> true | Some c -> isVarId evd id c) && is_id_subst ctxt' s'
1632 | [], None -> true
1633 | _ -> false
1634 in
1635 is_id_subst sign argsv &&
1636 closed0 evd rhs &&
1637 Id.Set.subset (collect_vars evd rhs) !names
1638 in
1639
1640 if fast then (evd, nf_evar evd rhs) (* FIXME? *)
1641 else
1642
1643 let evdref = ref evd in
1644 let progress = ref false in
1645 let aliases = make_alias_map env evd in
1646 let subst = make_projectable_subst aliases evd sign argsv in
1647 let cstr_subst = make_constructor_subst evd sign argsv in
1648
1649 (* Projection *)
1650 let project_variable t =
1651 (* Evar/Var problem: unifiable iff variable projectable from ev subst *)
1652 try
1653 let sols = find_projectable_vars aliases !evdref t subst in
1654 let c, p = match sols with
1655 | [] -> raise Not_found
1656 | [id,p] -> (mkVar id, p)
1657 | (id,p)::_ ->
1658 if choose then (mkVar id, p) else raise (NotUniqueInType sols)
1659 in
1660 let ty = lazy (Retyping.get_type_of env !evdref (of_alias t)) in
1661 let evd = do_projection_effects unify flags (evar_define unify flags ~choose) env ty !evdref p in
1662 evdref := evd;
1663 c
1664 with
1665 | Not_found -> raise (NotInvertibleUsingOurAlgorithm (of_alias t))
1666 | NotUniqueInType sols ->
1667 if not !progress then
1668 raise (NotEnoughInformationToProgress sols);
1669 (* No unique projection but still restrict to where it is possible *)
1670 (* materializing is necessary, but is restricting useful? *)
1671 let t' = of_alias t in
1672 let ty = Retyping.get_type_of env !evdref t' in
1673 let (evd,evar,(evk',argsv' as ev')) =
1674 materialize_evar (evar_define unify flags ~choose) env !evdref 0 ev ty in
1675 let ts = expansions_of_var aliases t in
1676 let test c = isEvar evd c || List.exists (is_alias evd c) ts in
1677 let argsv' = Evd.expand_existential evd (evk, argsv') in
1678 let filter = restrict_upon_filter evd evk test argsv' in
1679 let filter = closure_of_filter ~can_drop:choose evd evk' filter in
1680 let candidates = extract_candidates sols in
1681 let evd = match candidates with
1682 | NoUpdate ->
1683 let evd, ev'' = restrict_applied_evar evd ev' filter NoUpdate in
1684 add_conv_oriented_pb ~tail:false (None,env,mkEvar ev'',t') evd
1685 | UpdateWith _ ->
1686 restrict_evar evd evk' filter candidates
1687 in
1688 evdref := evd;
1689 evar in
1690
1691 let rec imitate (env',k as envk) t =
1692 match EConstr.kind !evdref t with
1693 | Rel i when i>k ->
1694 let open Context.Rel.Declaration in
1695 (match Environ.lookup_rel i env' with
1696 | LocalAssum _ -> project_variable (RelAlias (i-k))
1697 | LocalDef (_,b,_) ->
1698 try project_variable (RelAlias (i-k))
1699 with NotInvertibleUsingOurAlgorithm _ when imitate_defs ->
1700 imitate envk (lift i (EConstr.of_constr b)))
1701 | Var id ->
1702 (match Environ.lookup_named id env' with
1703 | LocalAssum _ -> project_variable (VarAlias id)
1704 | LocalDef (_,b,_) ->
1705 try project_variable (VarAlias id)
1706 with NotInvertibleUsingOurAlgorithm _ when imitate_defs ->
1707 imitate envk (EConstr.of_constr b))
1708 | LetIn (na,b,u,c) ->
1709 imitate envk (subst1 b c)
1710 | Evar (evk',args' as ev') ->
1711 if Evar.equal evk evk' then raise (OccurCheckIn (evd,rhs));
1712 (* At this point, we imitated a context say, C[ ], and virtually
1713 instantiated ?evk@{x₁..xn} with C[?evk''@{x₁..xn,y₁..yk}]
1714 for y₁..yk the spine of variables of C[ ], now facing the
1715 equation env, y₁...yk |- ?evk'@{args'} =?= ?evk''@{args,y1:=y1..yk:=yk} *)
1716 (* Assume evk' is defined in context x₁'..xk'.
1717 As a first step, we try to find a restriction ?evk'''@{xᵢ₁'..xᵢⱼ} of
1718 ?evk' and an instance args''' in the environment of ?evk such that
1719 env, y₁..yk |- args'''[args] = args' and thus such that
1720 env, y₁..yk |- ?evk'''@{args'''[args]} = ?evk''@{args,y1:=y1..yk:=yk} *)
1721 (* Note that we don't need to declare ?evk'' yet: it may remain virtual *)
1722 let aliases = lift_aliases k aliases in
1723 (try
1724 let ev = normalize_evar !evdref (evk,SList.Skip.map (lift k) argsv) in
1725 let evd,body = project_evar_on_evar false unify flags env' !evdref aliases k None ev' ev in
1726 evdref := evd;
1727 body
1728 with
1729 | EvarSolvedOnTheFly (evd,t) -> evdref:=evd; imitate envk t
1730 | CannotProject (evd,ev') ->
1731 if not !progress then
1732 raise (NotEnoughInformationEvarEvar t);
1733 (* We could not invert args' in terms of args, so we now make ?evk'' real *)
1734 let ty = get_type_of env' evd t in
1735 let (evd,evar'',ev'') =
1736 materialize_evar (evar_define unify flags ~choose) env' evd k ev ty in
1737 (* materialize_evar may instantiate ev' by another evar; adjust it *)
1738 let (evk',args' as ev') = normalize_evar evd ev' in
1739 let evd =
1740 (* Try now to invert args in terms of args' *)
1741 try
1742 if not @@ is_evar_allowed flags evk' then
1743 raise (CannotProject (evd, ev''));
1744 let evd,body = project_evar_on_evar false unify flags env' evd aliases 0 None ev'' ev' in
1745 let evi = Evd.find_undefined evd evk' in
1746 let evd = Evd.define evk' body evd in
1747 check_evar_instance_evi unify flags env' evd evi body
1748 with
1749 | EvarSolvedOnTheFly _ -> assert false (* ev has no candidates *)
1750 | CannotProject (evd,ev'') ->
1751 (* ... or postpone the problem *)
1752 add_conv_oriented_pb (None,env',mkEvar ev'',mkEvar ev') evd in
1753 evdref := evd;
1754 evar'')
1755 | App (f, args) when EConstr.isLambda !evdref f ->
1756 let p = !progress in
1757 progress := true;
1758 (try
1759 map_constr_with_full_binders env' !evdref (fun d (env,k) -> push_rel d env, k+1)
1760 imitate envk t
1761 with _ -> progress := p; imitate envk (whd_beta env' !evdref t))
1762 | _ ->
1763 progress := true;
1764 match
1765 let c,args = decompose_app !evdref t in
1766 match EConstr.kind !evdref c with
1767 | Construct (cstr,u) when noccur_between !evdref 1 k t ->
1768 (* This is common case when inferring the return clause of match *)
1769 (* (currently rudimentary: we do not treat the case of multiple *)
1770 (* possible inversions; we do not treat overlap with a possible *)
1771 (* alternative inversion of the subterms of the constructor, etc)*)
1772 (match find_projectable_constructor env evd cstr k args cstr_subst with
1773 | _::_ as l -> Some (List.map mkVar l)
1774 | _ -> None)
1775 | _ -> None
1776 with
1777 | Some l ->
1778 let ty = get_type_of env' !evdref t in
1779 let candidates =
1780 try
1781 let t =
1782 map_constr_with_full_binders env' !evdref (fun d (env,k) -> push_rel d env, k+1)
1783 imitate envk t in
1784 (* Less dependent solutions come last *)
1785 l@[t]
1786 with e when CErrors.noncritical e -> l in
1787 (match candidates with
1788 | [x] -> x
1789 | _ ->
1790 let (evd,evar'',ev'') =
1791 materialize_evar (evar_define unify flags ~choose) env' !evdref k ev ty in
1792 evdref := restrict_evar evd (fst ev'') None (UpdateWith candidates);
1793 evar'')
1794 | None ->
1795 (* Evar/Rigid problem (or assimilated if not normal): we "imitate" *)
1796 map_constr_with_full_binders env' !evdref (fun d (env,k) -> push_rel d env, k+1)
1797 imitate envk t
1798 in
1799
1800 let t' = imitate (env, 0) rhs in
1801 let body = if !progress then (recheck_applications unify flags (evar_env env evi) evdref t'; t') else t' in
1802 (!evdref,body)
1803
1804 (* [define] tries to solve the problem "?ev[args] = rhs" when "?ev" is
1805 * an (uninstantiated) evar such that "hyps |- ?ev : typ". Otherwise said,
1806 * [define] tries to find an instance lhs such that
1807 * "lhs [hyps:=args]" unifies to rhs. The term "lhs" must be closed in
1808 * context "hyps" and not referring to itself.
1809 * ev is assumed not to be frozen.
1810 *)
1811
1812 and evar_define unify flags ?(choose=false) ?(imitate_defs=true) env evd pbty (evk,argsv as ev) rhs =
1813 match EConstr.kind evd rhs with
1814 | Evar (evk2,argsv2 as ev2) when is_evar_allowed flags evk2 ->
1815 if Evar.equal evk evk2 then
1816 solve_refl ~can_drop:choose
1817 (test_success unify) flags env evd pbty evk argsv argsv2
1818 else
1819 solve_evar_evar ~force:choose
1820 (evar_define unify flags) unify flags env evd pbty ev ev2
1821 | _ ->
1822 try solve_candidates unify flags env evd ev rhs
1823 with NoCandidates ->
1824 try
1825 let (evd',body) = invert_definition unify flags choose imitate_defs env evd pbty ev rhs in
1826 if occur_meta evd' body then raise MetaOccurInBodyInternal;
1827 (* invert_definition may have instantiate some evars of rhs with evk *)
1828 (* so we recheck acyclicity *)
1829 if occur_evar_upto_types evd' evk body then raise (OccurCheckIn (evd',body));
1830 (* needed only if an inferred type *)
1831 let evd', body = refresh_universes pbty env evd' body in
1832 instantiate_evar unify flags env evd' evk body
1833 with
1834 | NotEnoughInformationToProgress sols ->
1835 postpone_non_unique_projection env evd pbty ev sols rhs
1836 | NotEnoughInformationEvarEvar t ->
1837 add_conv_oriented_pb (pbty,env,mkEvar ev,t) evd
1838 | MorePreciseOccurCheckNeeeded ->
1839 add_conv_oriented_pb (pbty,env,mkEvar ev,rhs) evd
1840 | NotInvertibleUsingOurAlgorithm _ | MetaOccurInBodyInternal as e ->
1841 raise e
1842 | OccurCheckIn (evd,rhs) ->
1843 (* last chance: rhs actually reduces to ev *)
1844 let c = whd_all env evd rhs in
1845 match EConstr.kind evd c with
1846 | Evar (evk',argsv2) when Evar.equal evk evk' ->
1847 solve_refl (fun flags _b env sigma pb c c' -> is_fconv pb env sigma c c') flags
1848 env evd pbty evk argsv argsv2
1849 | _ ->
1850 raise (OccurCheckIn (evd,rhs))
1851
1852 (* This code (i.e. solve_pb, etc.) takes a unification
1853 * problem, and tries to solve it. If it solves it, then it removes
1854 * all the conversion problems, and re-runs conversion on each one, in
1855 * the hopes that the new solution will aid in solving them.
1856 *
1857 * The kinds of problems it knows how to solve are those in which
1858 * the usable arguments of an existential var are all themselves
1859 * universal variables.
1860 * The solution to this problem is to do renaming for the Var's,
1861 * to make them match up with the Var's which are found in the
1862 * hyps of the existential, to do a "pop" for each Rel which is
1863 * not an argument of the existential, and a subst1 for each which
1864 * is, again, with the corresponding variable. This is done by
1865 * define
1866 *
1867 * Thus, we take the arguments of the existential which we are about
1868 * to assign, and zip them with the identifiers in the hypotheses.
1869 * Then, we process all the Var's in the arguments, and sort the
1870 * Rel's into ascending order. Then, we just march up, doing
1871 * subst1's and pop's.
1872 *
1873 * NOTE: We can do this more efficiently for the relative arguments,
1874 * by building a long substituend by hand, but this is a pain in the
1875 * ass.
1876 *)
1877
1878 let reconsider_unif_constraints unify flags evd =
1879 let (evd,pbs) = extract_changed_conv_pbs evd in
1880 List.fold_left
1881 (fun p (pbty,env,t1,t2 as x) ->
1882 match p with
1883 | Success evd ->
1884 (match unify flags TermUnification env evd pbty t1 t2 with
1885 | Success _ as x -> x
1886 | UnifFailure (i,e) -> UnifFailure (i,CannotSolveConstraint (x,e)))
1887 | UnifFailure _ as x -> x)
1888 (Success evd)
1889 pbs
1890
1891 (* Tries to solve problem t1 = t2.
1892 * Precondition: t1 is an uninstantiated evar
1893 * Returns an optional list of evars that were instantiated, or None
1894 * if the problem couldn't be solved. *)
1895
1896 (* Rq: incomplete algorithm if pbty = CONV_X_LEQ ! *)
1897 let solve_simple_eqn unify flags ?(choose=false) ?(imitate_defs=true)
1898 env evd (pbty,(evk1,args1 as ev1),t2) =
1899 try
1900 let t2 = whd_betaiota env evd t2 in (* includes whd_evar *)
1901 let evd = evar_define unify flags ~choose ~imitate_defs env evd pbty ev1 t2 in
1902 reconsider_unif_constraints unify flags evd
1903 with
1904 | NotInvertibleUsingOurAlgorithm t ->
1905 UnifFailure (evd,NotClean (ev1,env,t))
1906 | OccurCheckIn (evd,rhs) ->
1907 UnifFailure (evd,OccurCheck (evk1,rhs))
1908 | MetaOccurInBodyInternal ->
1909 UnifFailure (evd,MetaOccurInBody evk1)
1910 | IllTypedInstance (env,evd,t,u) ->
1911 UnifFailure (evd,InstanceNotSameType (evk1,env,t,u))
1912 | IllTypedInstanceFun (env,evd,f,u) ->
1913 UnifFailure (evd,InstanceNotFunctionalType (evk1,env,f,u))
1914 | IncompatibleCandidates t ->
1915 UnifFailure (evd,IncompatibleInstances (env,ev1,t,t2))
1916