Debian Codegraph @

pretyping/evarconv.ml

raw symbols SCIP
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * Copyright INRIA, CNRS and contributors *)
4 (* <O___,, * (see version control and CREDITS file for authors & dates) *)
5 (* \VV/ **************************************************************)
6 (* // * This file is distributed under the terms of the *)
7 (* * GNU Lesser General Public License Version 2.1 *)
8 (* * (see LICENSE file for the text of the license) *)
9 (************************************************************************)
10
11 open CErrors
12 open Util
13 open Names
14 open Constr
15 open Termops
16 open Environ
17 open EConstr
18 open Context
19 open Vars
20 open Conversion
21 open Reductionops
22 open Structures
23 open Evarutil
24 open Evardefine
25 open Evarsolve
26 open Evd
27 open Pretype_errors
28
29 module RelDecl = Context.Rel.Declaration
30 module NamedDecl = Context.Named.Declaration
31
32 type unify_flags = Evarsolve.unify_flags
33
34 type unify_fun = unify_flags ->
35 env -> evar_map -> conv_pb -> EConstr.constr -> EConstr.constr -> Evarsolve.unification_result
36
37 let default_transparent_state env = TransparentState.full
38 (* Conv_oracle.get_transp_state (Environ.oracle env) *)
39
40 let default_flags_of ?(subterm_ts=TransparentState.empty) ts =
41 { modulo_betaiota = true;
42 open_ts = ts; closed_ts = ts; subterm_ts;
43 allowed_evars = AllowedEvars.all; with_cs = true;
44 }
45
46 let default_flags env =
47 let ts = default_transparent_state env in
48 default_flags_of ts
49
50 let debug_unification = CDebug.create ~name:"unification" ()
51
52 let debug_ho_unification = CDebug.create ~name:"ho-unification" ()
53
54 (*******************************************)
55 (* Functions to deal with impossible cases *)
56 (*******************************************)
57
58 (* In case the constants id/ID are not defined *)
59 let unit_judge_fallback =
60 let na1 = make_annot (Name (Id.of_string "A")) ERelevance.relevant in
61 let na2 = make_annot (Name (Id.of_string "H")) ERelevance.relevant in
62 make_judge
63 (mkLambda (na1,mkProp,mkLambda(na2,mkRel 1,mkRel 1)))
64 (mkProd (na1,mkProp,mkArrow (mkRel 1) ERelevance.relevant (mkRel 2)))
65
66 let coq_unit_judge env sigma =
67 match Rocqlib.lib_ref_opt "core.IDProp.idProp" with
68 | Some c ->
69 let sigma, c = Evd.fresh_global env sigma c in
70 let t = Retyping.get_type_of env sigma c in
71 sigma, make_judge c t
72 | None -> sigma, unit_judge_fallback
73
74 let unfold_projection env evd ts p r c =
75 if TransparentState.is_transparent_projection ts (Projection.repr p) then
76 Some (mkProj (Projection.unfold p, r, c))
77 else None
78
79 (* [unfold_projection_under_eta env evd ts n c] checks if [c] is the eta
80 expanded, folded primitive projection of name [n] and unfolds the primitive
81 projection. It respects projection transparency of [ts]. *)
82 let unfold_projection_under_eta env evd ts n c =
83 let rec go c lams =
84 match EConstr.kind evd c with
85 | Lambda (b, t, c) -> go c ((b,t)::lams)
86 | Proj (p, r, c) when QConstant.equal env n (Projection.constant p) ->
87 let c = unfold_projection env evd ts p r c in
88 begin
89 match c with
90 | None -> None
91 | Some c ->
92 let f c (b,t) = mkLambda (b,t,c) in
93 Some (List.fold_left f c lams)
94 end
95 | _ -> None
96 in
97 go c []
98
99 let eval_flexible_term ts env evd c sk =
100 match EConstr.kind evd c with
101 | Const (c, u) ->
102 if Structures.PrimitiveProjections.is_transparent_constant ts c then begin
103 let cb = lookup_constant env evd c in
104 match cb.const_body with
105 | Def l_body ->
106 let def = subst_instance_constr u (EConstr.of_constr l_body) in
107 (* If we are unfolding a compatibility constant we want to return the
108 unfolded primitive projection directly since we would like to pretend
109 that the compatibility constant itself does not count as an unfolding
110 (delta) step. *)
111 let unf = unfold_projection_under_eta env evd ts c def in
112 Some (Option.default def unf, sk)
113 | OpaqueDef _ | Undef _ | Primitive _ -> None
114 | Symbol b ->
115 try
116 let r = match lookup_rewrite_rules c env with r -> r | exception Not_found -> assert false in
117 let rhs_stack = Reductionops.apply_rules
118 (fun ctx -> whd_betaiota_deltazeta_for_iota_state ts (push_rel_context ctx env) evd) env evd u r sk
119 in
120 Some rhs_stack
121 with PatternFailure -> None
122 (* TODO: try unfold fix *)
123 end else None
124 | Rel n ->
125 (try match lookup_rel n env with
126 | RelDecl.LocalAssum _ -> None
127 | RelDecl.LocalDef (_,v,_) -> Some (lift n v, sk)
128 with Not_found -> None)
129 | Var id ->
130 (try
131 if TransparentState.is_transparent_variable ts id then
132 env |> lookup_named id |> NamedDecl.get_value |> Option.map (fun c -> (c, sk))
133 else None
134 with Not_found -> None)
135 | LetIn (_,b,_,c) -> Some (subst1 b c, sk)
136 | Lambda _ -> Some (c, sk)
137 | Proj (p, r, c) ->
138 if Projection.unfolded p then assert false
139 else unfold_projection env evd ts p r c |> Option.map (fun c -> (c, sk))
140 | _ -> assert false
141
142 type flex_kind_of_term =
143 | Rigid
144 | MaybeFlexible of (EConstr.t * Stack.t) (* reducible but not necessarily reduced *)
145 | Flexible of EConstr.existential
146
147 let has_arg s = Option.has_some (Stack.strip_n_app 0 s)
148
149 let flex_kind_of_term flags env evd c sk =
150 match EConstr.kind evd c with
151 | LetIn _ | Rel _ | Const _ | Var _ | Proj _ ->
152 Option.cata (fun x -> MaybeFlexible x) Rigid (eval_flexible_term flags.open_ts env evd c sk)
153 | Lambda _ when has_arg sk ->
154 if flags.modulo_betaiota then MaybeFlexible (c, sk)
155 else Rigid
156 | Evar ev ->
157 if is_evar_allowed flags (fst ev) then Flexible ev else Rigid
158 | Lambda _ | Prod _ | Sort _ | Ind _ | Int _ | Float _ | String _ | Array _ -> Rigid
159 | Construct _ | CoFix _ (* Incorrect: should check only app in sk *) -> Rigid
160 | Meta _ -> Rigid
161 | Fix _ -> Rigid (* happens when the fixpoint is partially applied (should check it?) *)
162 | Cast _ | App _ | Case _ -> assert false
163
164 let apprec_nohdbeta flags env evd c =
165 let (t,sk as appr) = Reductionops.whd_nored_state env evd (c, []) in
166 if flags.modulo_betaiota && Stack.not_purely_applicative sk
167 then Stack.zip evd (whd_betaiota_deltazeta_for_iota_state
168 flags.open_ts env evd appr)
169 else c
170
171 let position_problem l2r = function
172 | CONV -> None
173 | CUMUL -> Some l2r
174
175 (* [occur_rigidly ev evd t] tests if the evar ev occurs in a rigid
176 context in t. Precondition: t has a rigid head and is not reducible.
177
178 That function is an under approximation of occur-check, it can return
179 false even if the occur-check would succeed on the normal form. This
180 means we might postpone unsolvable constraints which will ultimately
181 result in an occur-check after reductions. If it returns true, we
182 know that the occur-check would also return true on the normal form.
183
184 [t] is assumed to have a rigid head, which can
185 appear under a elimination context (e.g. application, match or projection).
186
187 In the inner recursive function, the result indicates if the term is
188 rigid (irreducible), normal (succession of constructors) or
189 potentially reducible. For applications, this means than an
190 occurrence of the evar in arguments should be looked at to find an
191 occur-check if the head is rigid or normal. For inductive
192 eliminations, only an occurrence in a rigid context of the
193 discriminee counts as a rigid occurrence overall, not a normal
194 occurrence which might disappear after reduction. *)
195
196 type result = Rigid of bool | Normal of bool | Reducible
197
198 let rigid_normal_occ = function Rigid b -> b | Normal b -> b | _ -> false
199
200 let occur_rigidly flags env evd (evk,_) t =
201 let rec aux t =
202 match EConstr.kind evd t with
203 | App (f, c) ->
204 (match aux f with
205 | Rigid b -> Rigid (b || Array.exists (fun x -> rigid_normal_occ (aux x)) c)
206 | Normal b -> Normal (b || Array.exists (fun x -> rigid_normal_occ (aux x)) c)
207 | Reducible -> Reducible)
208 | Construct _ -> Normal false
209 | Ind _ | Sort _ -> Rigid false
210 | Proj (p, _, c) ->
211 let rigid =
212 let p = Projection.repr p in
213 not (TransparentState.is_transparent_projection flags.open_ts p)
214 in
215 if rigid then aux c
216 else (* if the evar appears rigidly in c then this elimination
217 cannot reduce and we have a rigid occurrence, otherwise
218 we don't know. *)
219 (match aux c with
220 | Rigid _ as res -> res
221 | Normal b -> Reducible
222 | Reducible -> Reducible)
223 | Evar (evk',l) ->
224 if Evar.equal evk evk' then Rigid true
225 else if is_evar_allowed flags evk' then
226 Reducible
227 else Rigid (SList.Skip.exists (fun x -> rigid_normal_occ (aux x)) l)
228 | Cast (p, _, _) -> aux p
229 | Lambda (na, t, b) -> aux b
230 | LetIn (na, _, _, b) -> aux b
231 | Const (c,_) ->
232 if Structures.PrimitiveProjections.is_transparent_constant flags.open_ts c then Reducible
233 else Rigid false
234 | Prod (_, b, t) ->
235 let b' = aux b and t' = aux t in
236 if rigid_normal_occ b' || rigid_normal_occ t' then Rigid true
237 else Reducible
238 | Rel _ | Var _ -> Reducible
239 | Case (_,_,_,_,_,c,_) ->
240 (match aux c with
241 | Rigid b -> Rigid b
242 | _ -> Reducible)
243 | Meta _ | Fix _ | CoFix _ | Int _ | Float _ | String _ | Array _ -> Reducible
244 in
245 match aux t with
246 | Rigid b -> b
247 | Normal b -> b
248 | Reducible -> false
249
250 type hook = Environ.env -> Evd.evar_map -> ((Names.Constant.t * EConstr.EInstance.t) * EConstr.t list option * EConstr.t) -> (EConstr.t * EConstr.t list) -> (Evd.evar_map * Structures.CanonicalSolution.t) option
251
252 let all_hooks = ref (CString.Map.empty : hook CString.Map.t)
253
254 let register_hook ~name ?(override=false) h =
255 if not override && CString.Map.mem name !all_hooks then
256 CErrors.anomaly ~label:"CanonicalSolution.register_hook"
257 Pp.(str "Hook already registered: \"" ++ str name ++ str "\".");
258 all_hooks := CString.Map.add name h !all_hooks
259
260 let active_hooks = Summary.ref ~name:"canonical_solution_hooks_hacked" ([] : string list)
261
262 let deactivate_hook ~name =
263 active_hooks := List.filter (fun s -> not (String.equal s name)) !active_hooks
264
265 let activate_hook ~name =
266 assert (CString.Map.mem name !all_hooks);
267 deactivate_hook ~name;
268 active_hooks := name :: !active_hooks
269
270 let apply_hooks env sigma proj pat =
271 List.find_map (fun name ->
272 try CString.Map.get name !all_hooks env sigma proj pat
273 with e when CErrors.noncritical e -> anomaly Pp.(str "CS hook " ++ str name ++ str " exploded")) !active_hooks
274
275 let decompose_proj ?metas env sigma (t1, sk1) =
276 (* I only recognize ConstRef projections since these are the only ones for which
277 I know how to obtain the number of parameters. *)
278 let (proji, u), arg =
279 match Termops.global_app_of_constr sigma t1 with
280 | (Names.GlobRef.ConstRef proji, u), arg -> (proji, u), arg
281 | _ -> raise Not_found
282 | exception _ -> raise Not_found in
283 (* Given a ConstRef projection, I obtain the structure it is a projection from. *)
284 let structure = try Structures.Structure.find_from_projection env proji
285 with _ -> raise Not_found in
286 (* Knowing the structure and hence its number of arguments, I can cut sk1 into pieces. *)
287 let params1, c1, extra_args1 =
288 match arg with
289 | Some c -> (* A primitive projection applied to c *)
290 let meta_type mv = match metas with
291 | None -> None
292 | Some metas -> metas mv
293 in
294 let ty =
295 try Retyping.get_type_of ~metas:meta_type ~lax:true env sigma c with
296 | Retyping.RetypeError _ -> raise Not_found
297 in
298 let ind_args =
299 try
300 Some (Inductiveops.find_mrectype env sigma ty |> snd)
301 with Not_found -> None
302 in
303 ind_args, c, sk1
304 | None ->
305 match Reductionops.Stack.strip_n_app structure.nparams sk1 with
306 | Some (params1, c1, extra_args1) -> (Reductionops.Stack.list_of_app_stack params1), c1, extra_args1
307 | _ -> raise Not_found in
308 ((proji, u), (params1, c1, extra_args1))
309
310 (* [check_conv_record env sigma (t1,stack1) (t2,stack2)] tries to decompose
311 the problem (t1 stack1) = (t2 stack2) into a problem
312
313 stack1 = params1@[c1]@extra_args1
314 stack2 = us2@extra_args2
315 t1 params1 c1 = proji params (c xs)
316 t2 us2 = head us
317 extra_args1 = extra_args2
318
319 by finding a record R and an object c := [xs:bs](Build_R params v1..vn)
320 with vi = (head us), for which we know that the i-th projection proji
321 satisfies
322
323 proji params (c xs) = head us
324
325 Rem: such objects, usable for conversion, are defined in the objdef
326 table; practically, it amounts to "canonically" equip t2 into a
327 object c in structure R (since, if c1 were not an evar, the
328 projection would have been reduced) *)
329
330 let check_conv_record env sigma ((proji, u), (params1, c1, extra_args1)) (t2,sk2) =
331 let h2, sk2' = decompose_app sigma (shrink_eta sigma t2) in
332 let sk2 = Stack.append_app sk2' sk2 in
333 let k = Reductionops.Stack.args_size sk2 - Reductionops.Stack.args_size extra_args1 in
334 (* Knowing the shape of extra_args1, I can cut sk2 into pieces, extracting extra_args2 from it. *)
335 let args2, extra_args2 =
336 if k = 0 then [], sk2
337 else if k < 0 then raise Not_found
338 else match Reductionops.Stack.strip_n_app (k-1) sk2 with
339 | None -> raise Not_found
340 | Some (l',el,s') -> ((Option.get @@ Reductionops.Stack.list_of_app_stack l') @ [el], s') in
341 let (pat, _, args2') = try ValuePattern.of_constr sigma h2 with | DestKO -> (Default_cs, None, []) in
342 let (sigma, solution), sk2_effective =
343 (* N.B. In the `Proj` case, the subject needs to be added in args2. *)
344 try begin
345 try
346 let () = if pat = Default_cs then raise Not_found else () in
347 let (sigma, solution) = CanonicalSolution.find env sigma (Names.GlobRef.ConstRef proji, pat) in
348 if List.length solution.cvalue_arguments = k + (List.length args2') then (sigma, solution), args2' @ args2 else raise Not_found
349 with | Not_found ->
350 let (sigma, solution) = CanonicalSolution.find env sigma (Names.GlobRef.ConstRef proji, Default_cs) in
351 (* We have to drop the arguments args2 because the default solution does not have them. *)
352 if List.length solution.cvalue_arguments = 0 then (sigma, solution), [] else raise Not_found
353 end
354 with | Not_found -> (* If we find no solution, we ask the hook if it has any. *)
355 match (apply_hooks env sigma ((proji, u), params1, c1) (t2, args2)) with
356 | Some r -> r, args2' @ args2
357 | None -> raise Not_found
358 in
359 let t2 = Stack.zip sigma (h2, (Stack.append_app_list args2 Stack.empty)) in
360 let h, _ = decompose_app sigma solution.body in
361 sigma,(h, h2),solution.constant,solution.abstractions_ty,(solution.params,params1),
362 (solution.cvalue_arguments, sk2_effective),(extra_args1,extra_args2),c1,
363 (solution.cvalue_abstraction, t2)
364
365
366 (* Precondition: one of the terms of the pb is an uninstantiated evar,
367 * possibly applied to arguments. *)
368
369 let join_failures evd1 evd2 e1 e2 =
370 match e1, e2 with
371 | _, CannotSolveConstraint (_,ProblemBeyondCapabilities) -> (evd1,e1)
372 | _ -> (evd2,e2)
373
374 let rec ise_try evd = function
375 [] -> assert false
376 | [f] -> f evd
377 | f1::l ->
378 match f1 evd with
379 | Success _ as x -> x
380 | UnifFailure (evd1,e1) ->
381 match ise_try evd l with
382 | Success _ as x -> x
383 | UnifFailure (evd2,e2) ->
384 let evd,e = join_failures evd1 evd2 e1 e2 in
385 UnifFailure (evd,e)
386
387 let ise_and evd l =
388 let rec ise_and i = function
389 [] -> assert false
390 | [f] -> f i
391 | f1::l ->
392 match f1 i with
393 | Success i' -> ise_and i' l
394 | UnifFailure _ as x -> x in
395 ise_and evd l
396
397 let ise_list2 evd f l1 l2 =
398 let rec allrec k l1 l2 = match l1, l2 with
399 | [], [] -> k evd
400 | x1 :: l1, x2 :: l2 ->
401 let k evd = match k evd with
402 | Success evd -> f evd x1 x2
403 | UnifFailure _ as x -> x
404 in
405 allrec k l1 l2
406 | ([], _ :: _) | (_ :: _, []) -> UnifFailure (evd, NotSameArgSize)
407 in
408 allrec (fun i -> Success i) l1 l2
409
410 let ise_array2 evd f v1 v2 =
411 let rec allrec i = function
412 | -1 -> Success i
413 | n ->
414 match f i v1.(n) v2.(n) with
415 | Success i' -> allrec i' (n-1)
416 | UnifFailure _ as x -> x in
417 let lv1 = Array.length v1 in
418 if Int.equal lv1 (Array.length v2) then allrec evd (pred lv1)
419 else UnifFailure (evd,NotSameArgSize)
420
421 let rec ise_inst2 evd f l1 l2 = match l1, l2 with
422 | [], [] -> Success evd
423 | [], (_ :: _) | (_ :: _), [] -> assert false
424 | c1 :: l1, c2 :: l2 ->
425 match ise_inst2 evd f l1 l2 with
426 | Success evd' -> f evd' c1 c2
427 | UnifFailure _ as x -> x
428
429 (* Applicative node of stack are read from the outermost to the innermost
430 but are unified the other way. *)
431 let rec ise_app_rev_stack2 env f evd revsk1 revsk2 =
432 match Stack.decomp_rev revsk1, Stack.decomp_rev revsk2 with
433 | Some (t1,revsk1), Some (t2,revsk2) ->
434 begin
435 match ise_app_rev_stack2 env f evd revsk1 revsk2 with
436 | (_, UnifFailure _) as x -> x
437 | x, Success i' -> x, f env i' CONV t1 t2
438 end
439 | _, _ -> (revsk1,revsk2), Success evd
440
441 (* Add equality constraints for covariant/invariant positions. For
442 irrelevant positions, unify universes when flexible. *)
443 let compare_cumulative_instances pbty evd variances u u' =
444 match Evarutil.compare_cumulative_instances pbty variances u u' evd with
445 | Inl evd ->
446 Success evd
447 | Inr p -> UnifFailure (evd, UnifUnivInconsistency p)
448
449 let compare_constructor_instances evd u u' =
450 match Evarutil.compare_constructor_instances evd u u' with
451 | Inl evd ->
452 Success evd
453 | Inr p -> UnifFailure (evd, UnifUnivInconsistency p)
454
455 type application = FullyApplied | NumArgs of int
456
457 let is_applied o n = match o with FullyApplied -> true | NumArgs m -> Int.equal m n
458
459 let compare_heads pbty env evd ~nargs term term' =
460 let check_strict evd u u' =
461 let (qcst, ucst) = UVars.enforce_eq_instances u u' (UVars.QPairSet.empty, Univ.UnivConstraints.empty) in
462 try
463 let evd = Evd.add_univ_constraints evd ucst in
464 let fold (q1, q2) accu = UnivProblem.Set.add (UnivProblem.QEq (q1, q2)) accu in
465 let qcst = UVars.QPairSet.fold fold qcst UnivProblem.Set.empty in
466 let evd = Evd.add_constraints evd qcst in
467 Success evd
468 with UGraph.UniverseInconsistency p -> UnifFailure (evd, UnifUnivInconsistency p)
469 in
470 match EConstr.kind evd term, EConstr.kind evd term' with
471 | Const (c, u), Const (c', u') when QConstant.equal env c c' ->
472 if is_applied nargs 1 && Environ.is_array_type env c
473 then
474 let u = EInstance.kind evd u and u' = EInstance.kind evd u' in
475 compare_cumulative_instances pbty evd [|UVars.Variance.Irrelevant|] u u'
476 else
477 let u = EInstance.kind evd u and u' = EInstance.kind evd u' in
478 check_strict evd u u'
479 | Const _, Const _ -> UnifFailure (evd, NotSameHead)
480 | Ind ((mi,i) as ind , u), Ind (ind', u') when QInd.equal env ind ind' ->
481 if EInstance.is_empty u && EInstance.is_empty u' then Success evd
482 else
483 let u = EInstance.kind evd u and u' = EInstance.kind evd u' in
484 let mind = Environ.lookup_mind mi env in
485 let open Declarations in
486 begin match mind.mind_variance with
487 | None -> check_strict evd u u'
488 | Some variances ->
489 let needed = Conversion.inductive_cumulativity_arguments (mind,i) in
490 if not (is_applied nargs needed)
491 then check_strict evd u u'
492 else
493 compare_cumulative_instances pbty evd variances u u'
494 end
495 | Ind _, Ind _ -> UnifFailure (evd, NotSameHead)
496 | Construct (((mi,ind),ctor as cons), u), Construct (cons', u')
497 when QConstruct.equal env cons cons' ->
498 if EInstance.is_empty u && EInstance.is_empty u' then Success evd
499 else
500 let u = EInstance.kind evd u and u' = EInstance.kind evd u' in
501 let mind = Environ.lookup_mind mi env in
502 let open Declarations in
503 begin match mind.mind_variance with
504 | None -> check_strict evd u u'
505 | Some variances ->
506 let needed = Conversion.constructor_cumulativity_arguments (mind,ind,ctor) in
507 if not (is_applied nargs needed)
508 then check_strict evd u u'
509 else compare_constructor_instances evd u u'
510 end
511 | Construct _, Construct _ -> UnifFailure (evd, NotSameHead)
512 | _, _ -> anomaly (Pp.str "")
513
514 (* This function tries to unify 2 stacks element by element. It works
515 from the end to the beginning. If it unifies a non empty suffix of
516 stacks but not the entire stacks, the first part of the answer is
517 Some(the remaining prefixes to tackle)
518 If [no_app] is set, situations like [match head u1 u2 with ... end]
519 will not try to match [u1] and [u2] (why?); but situations like
520 [match head u1 u2 with ... end v] will try to match [v] (??) *)
521 (* Input: E1[] =? E2[] where the E1, E2 are concatenations of
522 n-ary-app/case/fix/proj elimination rules
523 Output:
524 - either None if E1 = E2 is solved,
525 - or Some (E1'',E2'') such that there is a decomposition of
526 E1[] = E1'[E1''[]] and E2[] = E2'[E2''[]] s.t. E1' = E2' and
527 E1'' cannot be unified with E2''
528 - UnifFailure if no such non-empty E1' = E2' exists *)
529 let rec ise_stack2 no_app env evd f sk1 sk2 =
530 let rec ise_rev_stack2 deep i revsk1 revsk2 =
531 let fail x = if deep then Some (List.rev revsk1, List.rev revsk2), Success i
532 else None, x in
533 match revsk1, revsk2 with
534 | [], [] -> None, Success i
535 | Stack.Case cse1 :: q1, Stack.Case cse2 :: q2 ->
536 let (ci1, u1, pms1, (t1,_), br1) = Stack.expand_case env evd cse1 in
537 let (ci2, u2, pms2, (t2,_), br2) = Stack.expand_case env evd cse2 in
538 let hd1 = mkIndU (ci1.ci_ind, u1) in
539 let hd2 = mkIndU (ci2.ci_ind, u2) in
540 let fctx i (ctx1, t1) (_ctx2, t2) = f (push_rel_context ctx1 env) i CONV t1 t2 in
541 begin
542 match ise_and i [
543 (fun i -> compare_heads CONV env i ~nargs:FullyApplied hd1 hd2);
544 (fun i -> ise_array2 i (fun ii -> f env ii CONV) pms1 pms2);
545 (fun i -> fctx i t1 t2);
546 (fun i -> ise_array2 i fctx br1 br2);
547 ]
548 with
549 | Success i' -> ise_rev_stack2 true i' q1 q2
550 | UnifFailure _ as x -> fail x
551 end
552 | Stack.Proj (p1,_)::q1, Stack.Proj (p2,_)::q2 ->
553 if QProjection.Repr.equal env (Projection.repr p1) (Projection.repr p2)
554 then ise_rev_stack2 true i q1 q2
555 else fail (UnifFailure (i, NotSameHead))
556 | Stack.Fix (((li1, i1),(_,tys1,bds1 as recdef1)),a1)::q1,
557 Stack.Fix (((li2, i2),(_,tys2,bds2)),a2)::q2 ->
558 if Int.equal i1 i2 && Array.equal Int.equal li1 li2 then
559 match ise_and i [
560 (fun i -> ise_array2 i (fun ii -> f env ii CONV) tys1 tys2);
561 (fun i -> ise_array2 i (fun ii -> f (push_rec_types recdef1 env) ii CONV) bds1 bds2);
562 (fun i -> snd (ise_stack2 no_app env i f a1 a2))] with
563 | Success i' -> ise_rev_stack2 true i' q1 q2
564 | UnifFailure _ as x -> fail x
565 else fail (UnifFailure (i,NotSameHead))
566 | Stack.App _ :: _, Stack.App _ :: _ ->
567 if no_app && deep then fail ((*dummy*)UnifFailure(i,NotSameHead)) else
568 begin match ise_app_rev_stack2 env f i revsk1 revsk2 with
569 |_,(UnifFailure _ as x) -> fail x
570 |(l1, l2), Success i' -> ise_rev_stack2 true i' l1 l2
571 end
572 |_, _ -> fail (UnifFailure (i,(* Maybe improve: *) NotSameHead))
573 in ise_rev_stack2 false evd (List.rev sk1) (List.rev sk2)
574
575 (* Make sure that the matching suffix is the all stack *)
576 let rec exact_ise_stack2 env evd f sk1 sk2 =
577 let rec ise_rev_stack2 i revsk1 revsk2 =
578 match revsk1, revsk2 with
579 | [], [] -> Success i
580 | Stack.Case cse1 :: q1, Stack.Case cse2 :: q2 ->
581 let (ci1, u1, pms1, (t1,_), br1) = Stack.expand_case env evd cse1 in
582 let (ci2, u2, pms2, (t2,_), br2) = Stack.expand_case env evd cse2 in
583 let hd1 = mkIndU (ci1.ci_ind, u1) in
584 let hd2 = mkIndU (ci2.ci_ind, u2) in
585 let fctx i (ctx1, t1) (_ctx2, t2) = f (push_rel_context ctx1 env) i CONV t1 t2 in
586 ise_and i [
587 (fun i -> ise_rev_stack2 i q1 q2);
588 (fun i -> compare_heads CONV env i ~nargs:FullyApplied hd1 hd2);
589 (fun i -> ise_array2 i (fun ii -> f env ii CONV) pms1 pms2);
590 (fun i -> fctx i t1 t2);
591 (fun i -> ise_array2 i fctx br1 br2);
592 ]
593 | Stack.Fix (((li1, i1),(_,tys1,bds1 as recdef1)),a1)::q1,
594 Stack.Fix (((li2, i2),(_,tys2,bds2)),a2)::q2 ->
595 if Int.equal i1 i2 && Array.equal Int.equal li1 li2 then
596 ise_and i [
597 (fun i -> ise_rev_stack2 i q1 q2);
598 (fun i -> ise_array2 i (fun ii -> f env ii CONV) tys1 tys2);
599 (fun i -> ise_array2 i (fun ii -> f (push_rec_types recdef1 env) ii CONV) bds1 bds2);
600 (fun i -> exact_ise_stack2 env i f a1 a2)]
601 else UnifFailure (i,NotSameHead)
602 | Stack.Proj (p1,_)::q1, Stack.Proj (p2,_)::q2 ->
603 if QProjection.Repr.equal env (Projection.repr p1) (Projection.repr p2)
604 then ise_rev_stack2 i q1 q2
605 else (UnifFailure (i, NotSameHead))
606 | Stack.App _ :: _, Stack.App _ :: _ ->
607 begin match ise_app_rev_stack2 env f i revsk1 revsk2 with
608 |_,(UnifFailure _ as x) -> x
609 |(l1, l2), Success i' -> ise_rev_stack2 i' l1 l2
610 end
611 |_, _ -> UnifFailure (i,(* Maybe improve: *) NotSameHead)
612 in
613 if Reductionops.Stack.compare_shape sk1 sk2 then
614 ise_rev_stack2 evd (List.rev sk1) (List.rev sk2)
615 else UnifFailure (evd, (* Dummy *) NotSameHead)
616
617 let compare_heads pbty env evd ~nargs term term' =
618 compare_heads pbty env evd ~nargs:(NumArgs nargs) term term'
619
620 let conv_fun f flags on_types =
621 let typefn env evd pbty term1 term2 =
622 let flags = { (default_flags env) with
623 with_cs = flags.with_cs;
624 allowed_evars = flags.allowed_evars }
625 in f flags env evd pbty term1 term2
626 in
627 let termfn env evd pbty term1 term2 =
628 f flags env evd pbty term1 term2
629 in
630 match on_types with
631 | TypeUnification -> typefn
632 | TermUnification -> termfn
633
634 let infer_conv_noticing_evars ~pb ~ts env sigma t1 t2 =
635 let has_evar = ref false in
636 let evar_expand ev =
637 let v = existential_expand_value0 sigma ev in
638 let () = match v with
639 | CClosure.EvarUndefined _ -> has_evar := true
640 | CClosure.EvarDefined _ -> ()
641 in
642 v
643 in
644 let evar_handler = { (Evd.evar_handler sigma) with evar_expand } in
645 let conv = { genconv = fun pb ~l2r sigma -> Conversion.generic_conv pb ~l2r ~evars:evar_handler } in
646 match infer_conv_gen conv ~catch_incon:false ~pb ~ts env sigma t1 t2 with
647 | Some sigma -> Some (Success sigma)
648 | None ->
649 if !has_evar then None
650 else Some (UnifFailure (sigma, ConversionFailed (env,t1,t2)))
651 | exception UGraph.UniverseInconsistency e ->
652 if !has_evar then None
653 else Some (UnifFailure (sigma, UnifUnivInconsistency e))
654
655 module Cs_keys_cache :
656 sig
657 type t
658 val empty : unit -> t
659 val flip : t -> t
660 val add : env -> evar_map -> bool -> state -> t -> t
661 val fold : bool -> ('a -> state -> 'a) -> 'a -> t -> 'a
662 val clear : bool -> t -> unit
663 end =
664 struct
665 type t = (Names.GlobRef.t Queue.t * state Names.GlobRef.Map_env.t) * (Names.GlobRef.t Queue.t * state Names.GlobRef.Map_env.t)
666
667 let empty () : t = ((Queue.create (), Names.GlobRef.Map_env.empty), (Queue.create (), Names.GlobRef.Map_env.empty))
668
669 let flip (c1, c2) = (c2, c1)
670
671 let add_left env sigma appr (((c1, m1), c2) as c) =
672 match fst @@ EConstr.destRef sigma (fst appr) with
673 | k ->
674 let k = QGlobRef.canonize env k in
675 if not (Names.GlobRef.Map_env.mem k m1) then
676 let () = Queue.push k c1 in
677 ((c1, Names.GlobRef.Map_env.add k appr m1), c2)
678 else c
679 | exception DestKO -> c
680
681 let add env sigma l2r appr c =
682 if l2r then add_left env sigma appr c else flip (add_left env sigma appr (flip c))
683
684 let fold_left f acc ((c, m), _) = Queue.fold (fun acc k -> f acc (Names.GlobRef.Map_env.find k m)) acc c
685 let fold l2r f acc c = fold_left f acc (if l2r then c else flip c)
686
687 let clear_left ((c, _), _) = Queue.clear c
688
689 let clear l2r c =
690 if l2r then clear_left c else clear_left (flip c)
691 end
692
693 type orig = { left : state; right : state }
694
695 let rec evar_conv_x flags env evd pbty term1 term2 =
696 let term1 = whd_head_evar evd term1 in
697 let term2 = whd_head_evar evd term2 in
698 (* Maybe convertible but since reducing can erase evars which [evar_apprec]
699 could have found, we do it only if the terms are free of evar.
700 Note: incomplete heuristic... *)
701 let ground_test =
702 if is_ground_term evd term1 && is_ground_term evd term2 then
703 infer_conv_noticing_evars ~pb:pbty ~ts:flags.closed_ts env evd term1 term2
704 else None
705 in
706 match ground_test with
707 | Some result -> result
708 | None ->
709 (* Until pattern-unification is used consistently, use nohdbeta to not
710 destroy beta-redexes that can be used for 1st-order unification *)
711 let term1 = apprec_nohdbeta flags env evd term1 in
712 let term2 = apprec_nohdbeta flags env evd term2 in
713 let default () =
714 let hd1 = (whd_nored_state env evd (term1,Stack.empty)) in
715 let hd2 = (whd_nored_state env evd (term2,Stack.empty)) in
716 match
717 evar_eqappr_x flags env evd pbty (Cs_keys_cache.empty ()) None
718 { left = hd1; right = hd2 } hd1 hd2
719 with
720 | UnifFailure _ as x ->
721 if Retyping.is_term_irrelevant env evd term1 ||
722 Retyping.is_term_irrelevant env evd term2
723 then Success evd
724 else x
725 | Success _ as x -> x
726 in
727 begin match EConstr.kind evd term1, EConstr.kind evd term2 with
728 | Evar ev, _ when Evd.is_undefined evd (fst ev) && is_evar_allowed flags (fst ev) ->
729 (match solve_simple_eqn (conv_fun evar_conv_x) flags env evd
730 (position_problem true pbty,ev,term2) with
731 | UnifFailure (_,(OccurCheck _ | NotClean _)) ->
732 (* Eta-expansion might apply *)
733 (* OccurCheck: eta-expansion could solve
734 ?X = {| foo := ?X.(foo) |}
735 NotClean: pruning in solve_simple_eqn is incomplete wrt
736 Miller patterns *)
737 default ()
738 | x -> x)
739 | _, Evar ev when Evd.is_undefined evd (fst ev) && is_evar_allowed flags (fst ev) ->
740 (match solve_simple_eqn (conv_fun evar_conv_x) flags env evd
741 (position_problem false pbty,ev,term1) with
742 | UnifFailure (_, (OccurCheck _ | NotClean _)) ->
743 (* OccurCheck: eta-expansion could solve
744 ?X = {| foo := ?X.(foo) |}
745 NotClean: pruning in solve_simple_eqn is incomplete wrt
746 Miller patterns *)
747 default ()
748 | x -> x)
749 | _ -> default ()
750 end
751
752 and evar_eqappr_x ?(rhs_is_already_stuck = false) flags env evd pbty
753 keys (* canonical structure keys cache *)
754 lastUnfolded (* tells which side was last unfolded, if any, where `true` means RHS. *)
755 orig (term1, sk1 as appr1) (term2, sk2 as appr2) =
756 let quick_fail i = (* not costly, loses info *)
757 UnifFailure (i, NotSameHead)
758 in
759 let miller_pfenning l2r fallback ev lF tM evd =
760 match is_unification_pattern_evar env evd ev lF tM with
761 | None -> fallback ()
762 | Some l1' -> (* Miller-Pfenning's patterns unification *)
763 let t2 = tM in
764 let t2 = solve_pattern_eqn env evd l1' t2 in
765 solve_simple_eqn (conv_fun evar_conv_x) flags env evd
766 (position_problem l2r pbty,ev,t2)
767 in
768 let consume_stack l2r (termF,skF) (termO,skO) evd =
769 let switch f a b = if l2r then f a b else f b a in
770 let not_only_app = Stack.not_purely_applicative skO in
771 match switch (ise_stack2 not_only_app env evd (evar_conv_x flags)) skF skO with
772 | Some (l,r), Success i' when l2r && (not_only_app || List.is_empty l) ->
773 (* E[?n]=E'[redex] reduces to either l[?n]=r[redex] with
774 case/fix/proj in E' (why?) or ?n=r[redex] *)
775 switch (evar_conv_x flags env i' pbty) (Stack.zip evd (termF,l)) (Stack.zip evd (termO,r))
776 | Some (r,l), Success i' when not l2r && (not_only_app || List.is_empty l) ->
777 (* E'[redex]=E[?n] reduces to either r[redex]=l[?n] with
778 case/fix/proj in E' (why?) or r[redex]=?n *)
779 switch (evar_conv_x flags env i' pbty) (Stack.zip evd (termF,l)) (Stack.zip evd (termO,r))
780 | None, Success i' -> switch (evar_conv_x flags env i' pbty) termF termO
781 | _, (UnifFailure _ as x) -> x
782 | Some _, _ -> UnifFailure (evd,NotSameArgSize) in
783 let eta_lambda env evd onleft term (term',sk') =
784 (* Reduces an equation [env |- <(fun na:c1 => c'1)|empty> = <term'|sk'>] to
785 [env, na:c1 |- c'1 = sk'[term'] (with some additional reduction) *)
786 let (na,c1,c'1) = destLambda evd term in
787 let env' = push_rel (RelDecl.LocalAssum (na,c1)) env in
788 let out1 = whd_betaiota_deltazeta_for_iota_state
789 flags.open_ts env' evd (c'1, Stack.empty) in
790 let out2 = whd_nored_state env' evd
791 (lift 1 (Stack.zip evd (term', sk')), Stack.append_app [|EConstr.mkRel 1|] Stack.empty) in
792 if onleft then evar_eqappr_x flags env' evd CONV keys None { left = out1; right = out2 } out1 out2
793 else evar_eqappr_x flags env' evd CONV (Cs_keys_cache.flip keys) None { left = out2; right = out1 } out2 out1
794 in
795 let rigids env evd sk term sk' term' =
796 let nargs = Stack.args_size sk in
797 let nargs' = Stack.args_size sk' in
798 if not (Int.equal nargs nargs') then UnifFailure (evd, NotSameArgSize)
799 else
800 ise_and evd [(fun i ->
801 try compare_heads pbty env i ~nargs term term'
802 with UGraph.UniverseInconsistency p -> UnifFailure (i, UnifUnivInconsistency p));
803 (fun i -> exact_ise_stack2 env i (evar_conv_x flags) sk sk')]
804 in
805 let consume l2r (_, skF as apprF) (_,skM as apprM) i =
806 if not (Stack.is_empty skF && Stack.is_empty skM) then
807 consume_stack l2r apprF apprM i
808 else quick_fail i
809 in
810 let miller l2r ev (termF,skF as apprF) (termM, skM as apprM) i =
811 let switch f a b = if l2r then f a b else f b a in
812 let not_only_app = Stack.not_purely_applicative skM in
813 match Stack.list_of_app_stack skF with
814 | None -> quick_fail evd
815 | Some lF ->
816 let tM = Stack.zip evd apprM in
817 miller_pfenning l2r
818 (fun () -> if not_only_app then (* Postpone the use of an heuristic *)
819 switch (fun x y -> Success (Evarutil.add_unification_pb (pbty,env,x,y) i)) (Stack.zip evd apprF) tM
820 else quick_fail i)
821 ev lF tM i
822 in
823 let flex_maybeflex l2r ev (termF,skF as apprF) (termM, skM as apprM) vskM =
824 (* Problem: E[?n[inst]] = E'[redex]
825 Strategy, as far as I understand:
826 1. if E[]=[]u1..un and ?n[inst] u1..un = E'[redex] is a Miller pattern: solve it now
827 2a. if E'=E'1[E'2] and E=E'1 unifiable, recursively solve ?n[inst] = E'2[redex]
828 2b. if E'=E'1[E'2] and E=E1[E2] and E=E'1 unifiable and E' contient app/fix/proj,
829 recursively solve E2[?n[inst]] = E'2[redex]
830 3. reduce the redex into M and recursively solve E[?n[inst]] =? E'[M] *)
831 let switch f a b = if l2r then f a b else f b a in
832 let delta i =
833 let vskM = Option.get (eval_flexible_term flags.open_ts env evd (fst vskM) (snd vskM)) in
834 let apprM' = whd_betaiota_deltazeta_for_iota_state flags.open_ts env i vskM in
835 (* We cheat here. Unfolding here means that we should not go back to the heads
836 when rediscovering the problem ?e=t, so we put the unfolded term in place of the
837 head. *)
838 let orig = { left = apprM'; right = apprM' } in
839 switch (evar_eqappr_x flags env i pbty keys None orig) apprF apprM'
840 in
841 let default i = ise_try i [miller l2r ev apprF apprM;
842 consume l2r apprF apprM;
843 delta]
844 in
845 match EConstr.kind evd termM with
846 | Proj (p, _, c) when not (Stack.is_empty skF) ->
847 (* Might be ?X args = p.c args', and we have to eta-expand the
848 primitive projection if |args| >= |args'|+1. *)
849 let nargsF = Stack.args_size skF and nargsM = Stack.args_size skM in
850 begin
851 (* ?X argsF' ~= (p.c ..) argsM' -> ?X ~= (p.c ..), no need to expand *)
852 if nargsF <= nargsM then default evd
853 else
854 let f =
855 try
856 let termM' = Retyping.expand_projection env evd p c [] in
857 let apprM' =
858 whd_betaiota_deltazeta_for_iota_state flags.open_ts env evd (termM',skM)
859 in
860 (* We cheat here. Unfolding here means that we should not go back to the heads
861 when rediscovering the problem ?e=t, so we put the unfolded term in place of the
862 head. *)
863 let orig = if l2r then { left = orig.right; right = apprM' } else { left = apprM'; right = orig.left } in
864 let delta' i =
865 switch (evar_eqappr_x flags env i pbty keys None orig) apprF apprM'
866 in
867 fun i -> ise_try i [miller l2r ev apprF apprM';
868 consume l2r apprF apprM'; delta']
869 with Retyping.RetypeError _ ->
870 (* Happens thanks to w_unify building ill-typed terms *)
871 default
872 in f evd
873 end
874 | _ -> default evd
875 in
876 let flex_rigid l2r ev (termF, skF as apprF) (termR, skR as apprR) =
877 (* Problem: E[?n[inst]] = E'[M] with M blocking computation (in theory)
878 Strategy, as far as I understand:
879 1. if E[]=[]u1..un and ?n[inst] u1..un = E'[M] is a Miller pattern: solve it now
880 2a. if E'=E'1[E'2] and E=E'1 unifiable and E' contient app/fix/proj,
881 recursively solve ?n[inst] = E'2[M]
882 2b. if E'=E'1[E'2] and E=E1[E2] and E=E'1 unifiable and E' contient app/fix/proj,
883 recursively solve E2[?n[inst]] = E'2[M]
884 3a. if M a lambda or a constructor: eta-expand and recursively solve
885 3b. if M a constructor C ..ui..: eta-expand and recursively solve proji[E[?n[inst]]]=ui
886 4. fail if E purely applicative and ?n occurs rigidly in E'[M]
887 5. absorb arguments if purely applicative and postpone *)
888 let switch f a b = if l2r then f a b else f b a in
889 let eta evd =
890 match EConstr.kind evd termR with
891 | Lambda _ when (* if ever problem is ill-typed: *) List.is_empty skR ->
892 eta_lambda env evd false termR apprF
893 | Construct u -> eta_constructor flags env evd u skR apprF
894 | _ -> UnifFailure (evd,NotSameHead)
895 in
896 match Stack.list_of_app_stack skF with
897 | None ->
898 ise_try evd [consume_stack l2r apprF apprR; eta]
899 | Some lF ->
900 let tR = Stack.zip evd apprR in
901 miller_pfenning l2r
902 (fun () ->
903 ise_try evd
904 [eta;(* Postpone the use of an heuristic *)
905 (fun i ->
906 if not (occur_rigidly flags env i ev tR) then
907 let i,tF =
908 if isRel i tR || isVar i tR then
909 (* Optimization so as to generate candidates *)
910 let i,ev = evar_absorb_arguments env i ev lF in
911 i,mkEvar ev
912 else
913 i,Stack.zip evd apprF in
914 switch (fun x y -> Success (Evarutil.add_unification_pb (pbty,env,x,y) i))
915 tF tR
916 else
917 UnifFailure (evd,OccurCheck (fst ev,tR)))])
918 ev lF tR evd
919 in
920 let first_order env i t1 t2 sk1 sk2 orig =
921 (* Try first-order unification *)
922 match ise_stack2 false env i (evar_conv_x flags) sk1 sk2 with
923 | None, Success i' ->
924 (* We do have sk1[] = sk2[]: we now unify ?ev1 and ?ev2 *)
925 (* Note that ?ev1 and ?ev2, may have been instantiated in the meantime *)
926 let ev1' = whd_evar i' t1 in
927 if isEvar i' ev1' then
928 solve_simple_eqn (conv_fun evar_conv_x) flags env i'
929 (position_problem true pbty,destEvar i' ev1',term2)
930 else
931 (* HH: Why not to drop sk1 and sk2 since they unified *)
932 evar_eqappr_x flags env evd pbty keys None orig
933 (ev1', sk1) (term2, sk2)
934 | Some (r,[]), Success i' ->
935 (* We have sk1'[] = sk2[] for some sk1' s.t. sk1[]=sk1'[r[]] *)
936 (* we now unify r[?ev1] and ?ev2 *)
937 let ev2' = whd_evar i' t2 in
938 if isEvar i' ev2' then
939 solve_simple_eqn (conv_fun evar_conv_x) flags env i'
940 (position_problem false pbty,destEvar i' ev2',Stack.zip i' (term1,r))
941 else
942 evar_eqappr_x flags env evd pbty keys None orig
943 (ev2', sk1) (term2, sk2)
944 | Some ([],r), Success i' ->
945 (* Symmetrically *)
946 (* We have sk1[] = sk2'[] for some sk2' s.t. sk2[]=sk2'[r[]] *)
947 (* we now unify ?ev1 and r[?ev2] *)
948 let ev1' = whd_evar i' t1 in
949 if isEvar i' ev1' then
950 solve_simple_eqn (conv_fun evar_conv_x) flags env i'
951 (position_problem true pbty,destEvar i' ev1',Stack.zip i' (term2,r))
952 else
953 (* HH: Why not to drop sk1 and sk2 since they unified *)
954 evar_eqappr_x flags env evd pbty keys None orig
955 (ev1', sk1) (term2, sk2)
956 | None, (UnifFailure _ as x) ->
957 (* sk1 and sk2 have no common outer part *)
958 if Stack.not_purely_applicative sk2 then
959 (* Ad hoc compatibility with 8.4 which treated non-app as rigid *)
960 flex_rigid true (destEvar evd t1) appr1 appr2
961 else
962 if Stack.not_purely_applicative sk1 then
963 (* Ad hoc compatibility with 8.4 which treated non-app as rigid *)
964 flex_rigid false (destEvar evd t2) appr2 appr1
965 else
966 (* We could instead try Miller unification, then
967 postpone to see if other equations help, as in:
968 [Check fun a b : unit => (eqᵣefl : _ a = _ a b)] *)
969 x
970 | Some _, Success _ ->
971 (* sk1 and sk2 have a common outer part *)
972 if Stack.not_purely_applicative sk2 then
973 (* Ad hoc compatibility with 8.4 which treated non-app as rigid *)
974 flex_rigid true (destEvar evd t1) appr1 appr2
975 else
976 if Stack.not_purely_applicative sk1 then
977 (* Ad hoc compatibility with 8.4 which treated non-app as rigid *)
978 flex_rigid false (destEvar evd t2) appr2 appr1
979 else
980 (* We could instead try Miller unification, then
981 postpone to see if other equations help, as in:
982 [Check fun a b c : unit => (eq_refl : _ a b = _ c a b)] *)
983 UnifFailure (i,NotSameArgSize)
984 | _, _ -> anomaly (Pp.str "Unexpected result from ise_stack2.")
985 in
986 let app_empty = match sk1, sk2 with [], [] -> true | _ -> false in
987 (* Evar must be undefined since we have flushed evars *)
988 let keys = Cs_keys_cache.add env evd true appr1 keys in
989 let keys = Cs_keys_cache.add env evd false appr2 keys in
990 let get_cs env sigma l2r keys nokey appr1 appr2 =
991 let appr1, appr2 = if l2r then appr1, appr2 else appr2, appr1 in
992 try
993 let (_, (_, c1, _)) as p1 = decompose_proj env sigma appr1 in
994 let kill, reduce =
995 (* TOTHINK: Should I keep c1 simplified? *)
996 let c1 = whd_all env sigma c1 in
997 (* [proj (ctor ...)]: don't use CS *)
998 match kind sigma c1 with
999 | App (h,_) when isConstruct sigma h -> true, true
1000 | Construct _ -> true, true
1001 | _ -> not (has_undefined_evars_or_metas sigma c1), false in
1002 let x =
1003 let check_key default appr =
1004 try
1005 let s = check_conv_record env sigma p1 appr in
1006 if kill then quick_fail sigma else conv_record flags env s
1007 with Not_found -> default in
1008 if nokey then check_key (UnifFailure (sigma, NoCanonicalStructure)) appr2
1009 else
1010 let x = Cs_keys_cache.fold (not l2r) (fun r appr ->
1011 match r with
1012 | Success _ -> r
1013 | _ -> check_key r appr) (UnifFailure (sigma, NoCanonicalStructure)) keys in
1014 (* If t is not a reference, it was not added to the keys cache, so we take care of it now. *)
1015 match x with
1016 | UnifFailure _ when not (EConstr.isRef sigma (fst appr2)) -> check_key x appr2
1017 | _ -> x in
1018 if kill then Inr (reduce && (match x with | UnifFailure (_, NoCanonicalStructure) -> false | _ -> true)) else
1019 (* The projection constant will not change, so there is no point in keeping the keys anymore. *)
1020 let () = Cs_keys_cache.clear (not l2r) keys in
1021 match x with | Success _ -> Inl x | _ -> Inr false
1022 with _ -> Inr false in
1023 let () = debug_unification (fun () -> Pp.(v 0 (pr_state env evd appr1 ++ cut () ++ pr_state env evd appr2 ++ cut ()))) in
1024 match (flex_kind_of_term flags env evd term1 sk1,
1025 flex_kind_of_term flags env evd term2 sk2) with
1026 | Flexible (sp1,al1), Flexible (sp2,al2) ->
1027 let k1 = if lastUnfolded = Some true && not (Stack.not_purely_applicative sk1) then let (t, sk) = orig.left in flex_kind_of_term flags env evd t sk else Flexible (sp1, al1) in
1028 let k2 = if lastUnfolded = Some false && not (Stack.not_purely_applicative sk2) then let (t, sk) = orig.right in flex_kind_of_term flags env evd t sk else Flexible (sp2, al2) in
1029 begin match (k1, k2) with
1030 | Flexible ev1, MaybeFlexible v2 -> flex_maybeflex true ev1 appr1 orig.right orig.right
1031 | MaybeFlexible v1, Flexible ev2 -> flex_maybeflex false ev2 appr2 orig.left orig.left
1032 | _, Rigid | Rigid, _ -> anomaly (Pp.str "flexible terms cannot fold to rigid ones")
1033 | _ ->
1034 (* Notations:
1035 - "sk" is a stack (or, more abstractly, an evaluation context, written E)
1036 - "ev" is an evar "?ev", more precisely an evar ?n with an instance inst
1037 - "al" is an evar instance
1038 Problem: E₁[?n₁[inst₁]] = E₂[?n₂[inst₂]] (i.e. sk1[?ev1] =? sk2[?ev2]
1039 Strategy is first-order unification
1040 1a. if E₁=E₂ unifiable, solve ?n₁[inst₁] = ?n₂[inst₂]
1041 1b. if E₂=E₂'[E₂''] and E₁=E₂' unifiable, recursively solve ?n₁[inst₁] = E₂''[?n₂[inst₂]]
1042 1b'. if E₁=E₁'[E₁''] and E₁'=E₂ unifiable, recursively solve E₁''[?n₁[inst₁]] = ?n₂[inst₂]
1043 recursively solve E2[?n[inst]] = E'2[redex]
1044 2. fails if neither E₁ nor E₂ is a prefix of the other *)
1045 let f1 i = first_order env i term1 term2 sk1 sk2 orig
1046 and f2 i =
1047 if Evar.equal sp1 sp2 then
1048 match ise_stack2 false env i (evar_conv_x flags) sk1 sk2 with
1049 |None, Success i' ->
1050 Success (solve_refl (fun flags p env i pbty a1 a2 ->
1051 let flags =
1052 match p with
1053 | TypeUnification -> default_flags env
1054 | TermUnification -> flags
1055 in
1056 is_success (evar_conv_x flags env i pbty a1 a2)) flags
1057 env i' (position_problem true pbty) sp1 al1 al2)
1058 |_, (UnifFailure _ as x) -> x
1059 |Some _, _ -> UnifFailure (i,NotSameArgSize)
1060 else UnifFailure (i,NotSameHead)
1061 and f3 i = miller true (sp1,al1) appr1 appr2 i
1062 and f4 i = miller false (sp2,al2) appr2 appr1 i
1063 and f5 i =
1064 (* We ensure failure of consuming the stacks does not
1065 propagate an error about unification of the stacks while
1066 the heads themselves cannot be unified, so we return
1067 NotSameHead. *)
1068 match consume true appr1 appr2 i with
1069 | Success _ as x -> x
1070 | UnifFailure _ -> quick_fail i
1071 in
1072 ise_try evd [f1; f2; f3; f4; f5]
1073 end
1074
1075 | Flexible ev1, MaybeFlexible v2 ->
1076 flex_maybeflex true ev1 appr1 appr2 (if Stack.not_purely_applicative sk1 then appr2 else orig.right)
1077
1078 | MaybeFlexible vsk1, Flexible ev2 ->
1079 flex_maybeflex false ev2 appr2 appr1 (if Stack.not_purely_applicative sk2 then appr1 else orig.left)
1080
1081 | MaybeFlexible (v1', sk1' as vsk1'), MaybeFlexible (v2', sk2' as vsk2') -> begin
1082 match EConstr.kind evd term1, EConstr.kind evd term2 with
1083 | LetIn (na1,b1,t1,c'1), LetIn (na2,b2,t2,c'2) ->
1084 let f1 i = (* FO *)
1085 ise_and i
1086 [(fun i -> ise_try i
1087 [(fun i -> evar_conv_x flags env i CUMUL t1 t2);
1088 (fun i -> evar_conv_x flags env i CUMUL t2 t1)]);
1089 (fun i -> evar_conv_x flags env i CONV b1 b2);
1090 (fun i ->
1091 let b = nf_evar i b1 in
1092 let t = nf_evar i t1 in
1093 let na = Nameops.Name.pick_annot na1 na2 in
1094 evar_conv_x flags (push_rel (RelDecl.LocalDef (na,b,t)) env) i pbty c'1 c'2);
1095 (fun i -> exact_ise_stack2 env i (evar_conv_x flags) sk1 sk2)]
1096 and f2 i =
1097 let out1 = whd_betaiota_deltazeta_for_iota_state flags.open_ts env i vsk1'
1098 and out2 = whd_betaiota_deltazeta_for_iota_state flags.open_ts env i vsk2'
1099 in evar_eqappr_x flags env i pbty keys None orig out1 out2
1100 in
1101 ise_try evd [f1; f2]
1102
1103 | Proj (p, _, c), Proj (p', _, c') when QProjection.Repr.equal env (Projection.repr p) (Projection.repr p') ->
1104 let f1 i =
1105 ise_and i
1106 [(fun i -> evar_conv_x flags env i CONV c c');
1107 (fun i -> exact_ise_stack2 env i (evar_conv_x flags) sk1 sk2)]
1108 and f2 i =
1109 let out1 = whd_betaiota_deltazeta_for_iota_state flags.open_ts env i vsk1'
1110 and out2 = whd_betaiota_deltazeta_for_iota_state flags.open_ts env i vsk2'
1111 in evar_eqappr_x flags env i pbty keys None orig out1 out2
1112 in
1113 ise_try evd [f1; f2]
1114
1115 (* Catch the p.c ~= p c' cases *)
1116 | Proj (p,_,c), Const (p',u) when QConstant.equal env (Projection.constant p) p' ->
1117 let res =
1118 try Some (destApp evd (Retyping.expand_projection env evd p c []))
1119 with Retyping.RetypeError _ -> None
1120 in
1121 (match res with
1122 | Some (f1,args1) ->
1123 evar_eqappr_x flags env evd pbty keys None orig (f1,Stack.append_app args1 sk1)
1124 appr2
1125 | None -> UnifFailure (evd,NotSameHead))
1126
1127 | Const (p,u), Proj (p',_,c') when QConstant.equal env p (Projection.constant p') ->
1128 let res =
1129 try Some (destApp evd (Retyping.expand_projection env evd p' c' []))
1130 with Retyping.RetypeError _ -> None
1131 in
1132 (match res with
1133 | Some (f2,args2) ->
1134 evar_eqappr_x flags env evd pbty keys None orig appr1 (f2,Stack.append_app args2 sk2)
1135 | None -> UnifFailure (evd,NotSameHead))
1136
1137 | _, _ ->
1138 (* We remember if the LHS is a reducible projection to decide if we unfold left first. *)
1139 let no_cs1 = ref false in
1140 let f1 i =
1141 (* Gather the universe constraints that would make term1 and term2 equal.
1142 If these only involve unifications of flexible universes to other universes,
1143 allow this identification (first-order unification of universes). Otherwise
1144 fallback to unfolding.
1145 *)
1146 let univs = EConstr.eq_constr_universes env evd term1 term2 in
1147 match univs with
1148 | Some univs ->
1149 ise_and i [(fun i ->
1150 try Success (Evd.add_constraints i univs)
1151 with UniversesDiffer -> UnifFailure (i,NotSameHead)
1152 | UGraph.UniverseInconsistency p -> UnifFailure (i, UnifUnivInconsistency p));
1153 (fun i -> exact_ise_stack2 env i (evar_conv_x flags) sk1 sk2)]
1154 | None ->
1155 UnifFailure (i,NotSameHead)
1156 and f2 i =
1157 if not flags.with_cs then UnifFailure (i,NoCanonicalStructure)
1158 else
1159 (match get_cs env i true keys (lastUnfolded = Some true) appr1 appr2 with
1160 | Inl x -> x
1161 | Inr b ->
1162 let () = no_cs1 := b in
1163 (match get_cs env i false keys (lastUnfolded = Some false) appr1 appr2 with
1164 | Inl x -> x
1165 | Inr _ -> UnifFailure (i,NoCanonicalStructure)))
1166 and f3 i =
1167 (* heuristic: unfold second argument first, exception made
1168 if the first argument is a beta-redex (expand a constant
1169 only if necessary) or the second argument is potentially
1170 usable as a canonical projection or canonical value *)
1171 let rec is_unnamed (hd, args) = match EConstr.kind i hd with
1172 | (Var _|Construct _|Ind _|Const _|Prod _|Sort _|Int _ |Float _|String _|Array _) ->
1173 Stack.not_purely_applicative args
1174 | (CoFix _|Meta _|Rel _)-> true
1175 | Evar _ -> Stack.not_purely_applicative args
1176 (* false (* immediate solution without Canon Struct *)*)
1177 | Lambda _ -> assert (match args with [] -> true | _ -> false); true
1178 | LetIn (_,b,_,c) -> is_unnamed
1179 (whd_betaiota_deltazeta_for_iota_state
1180 flags.open_ts env i (subst1 b c, args))
1181 | Fix _ -> true (* Partially applied fix can be the result of a whd call *)
1182 | Proj (p, _, _) -> Projection.unfolded p || Stack.not_purely_applicative args
1183 | Case _ | App _| Cast _ -> assert false in
1184 let rhs_is_stuck_and_unnamed () =
1185 let applicative_stack = fst (Stack.strip_app sk2') in
1186 is_unnamed
1187 (whd_betaiota_deltazeta_for_iota_state
1188 flags.open_ts env i (v2', applicative_stack)) in
1189 let rhs_is_already_stuck =
1190 rhs_is_already_stuck || rhs_is_stuck_and_unnamed () in
1191
1192 let b = EConstr.isLambda i term1 || rhs_is_already_stuck
1193 && (not (Stack.not_purely_applicative sk1')) in
1194 ise_try i [
1195 (fun i ->
1196 if b || !no_cs1 then
1197 evar_eqappr_x flags env i pbty keys (Some false) orig
1198 (whd_betaiota_deltazeta_for_iota_state
1199 flags.open_ts env i vsk1')
1200 appr2
1201 else quick_fail i);
1202 fun i ->
1203 if b then quick_fail i else
1204 evar_eqappr_x flags env i pbty keys (Some true) orig appr1
1205 (whd_betaiota_deltazeta_for_iota_state
1206 flags.open_ts env i vsk2')]
1207 in
1208 ise_try evd [f1; f2; f3]
1209 end
1210
1211 | Rigid, Rigid when EConstr.isLambda evd term1 && EConstr.isLambda evd term2 ->
1212 let (na1,c1,c'1) = EConstr.destLambda evd term1 in
1213 let (na2,c2,c'2) = EConstr.destLambda evd term2 in
1214 ise_and evd
1215 [(fun i -> evar_conv_x flags env i CONV c1 c2);
1216 (fun i ->
1217 let c = nf_evar i c1 in
1218 let na = Nameops.Name.pick_annot na1 na2 in
1219 evar_conv_x flags (push_rel (RelDecl.LocalAssum (na,c)) env) i CONV c'1 c'2);
1220 (* When in modulo_betaiota = false case, lambda's are not reduced *)
1221 (fun i -> exact_ise_stack2 env i (evar_conv_x flags) sk1 sk2)]
1222
1223 | Flexible ev1, Rigid ->
1224 if Stack.not_purely_applicative sk1 then flex_rigid true ev1 appr1 appr2 else
1225 let (t2, sk2) as appr2 = orig.right in
1226 begin match flex_kind_of_term flags env evd t2 sk2 with
1227 | Flexible ev2 -> anomaly (Pp.str "rigid terms can not fold to flexible ones")
1228 | MaybeFlexible v2 -> flex_maybeflex true ev1 appr1 appr2 appr2
1229 | Rigid -> flex_rigid true ev1 appr1 appr2
1230 end
1231 | Rigid, Flexible ev2 ->
1232 if Stack.not_purely_applicative sk2 then flex_rigid false ev2 appr2 appr1 else
1233 let (t1, sk1) as appr1 = orig.left in
1234 begin match flex_kind_of_term flags env evd t1 sk1 with
1235 | Flexible ev1 -> anomaly (Pp.str "rigid terms can not fold to flexible ones")
1236 | MaybeFlexible v1 -> flex_maybeflex false ev2 appr2 appr1 appr1
1237 | Rigid -> flex_rigid false ev2 appr2 appr1
1238 end
1239
1240 | MaybeFlexible vsk1', Rigid ->
1241 let f3 i =
1242 if not flags.with_cs then UnifFailure (i,NoCanonicalStructure)
1243 else
1244 match get_cs env i true keys false appr1 appr2 with
1245 | Inl x -> x
1246 | Inr _ -> UnifFailure (i,NoCanonicalStructure)
1247 and f4 i =
1248 evar_eqappr_x flags env i pbty keys (Some false) orig
1249 (whd_betaiota_deltazeta_for_iota_state
1250 flags.open_ts env i vsk1')
1251 appr2
1252 in
1253 ise_try evd [f3; f4]
1254
1255 | Rigid, MaybeFlexible vsk2' ->
1256 let f3 i =
1257 if not flags.with_cs then UnifFailure (i,NoCanonicalStructure)
1258 else
1259 match get_cs env i false keys false appr1 appr2 with
1260 | Inl x -> x
1261 | Inr _ -> UnifFailure (i,NoCanonicalStructure)
1262 and f4 i =
1263 evar_eqappr_x flags env i pbty keys (Some true) orig appr1
1264 (whd_betaiota_deltazeta_for_iota_state
1265 flags.open_ts env i vsk2')
1266 in
1267 ise_try evd [f3; f4]
1268
1269 (* Eta-expansion *)
1270 | Rigid, _ when isLambda evd term1 && (* if ever ill-typed: *) List.is_empty sk1 ->
1271 eta_lambda env evd true term1 (term2,sk2)
1272
1273 | _, Rigid when isLambda evd term2 && (* if ever ill-typed: *) List.is_empty sk2 ->
1274 eta_lambda env evd false term2 (term1,sk1)
1275
1276 | Rigid, Rigid -> begin
1277 match EConstr.kind evd term1, EConstr.kind evd term2 with
1278
1279 | Sort s1, Sort s2 when app_empty ->
1280 (try
1281 let evd' =
1282 if pbty == CONV
1283 then Evd.set_eq_sort evd s1 s2
1284 else Evd.set_leq_sort evd s1 s2
1285 in Success evd'
1286 with UGraph.UniverseInconsistency p ->
1287 UnifFailure (evd,UnifUnivInconsistency p)
1288 | e when CErrors.noncritical e -> UnifFailure (evd,NotSameHead))
1289
1290 | Prod (n1,c1,c'1), Prod (n2,c2,c'2) when app_empty ->
1291 ise_and evd
1292 [(fun i -> evar_conv_x flags env i CONV c1 c2);
1293 (fun i ->
1294 let c = nf_evar i c1 in
1295 let na = Nameops.Name.pick_annot n1 n2 in
1296 evar_conv_x flags (push_rel (RelDecl.LocalAssum (na,c)) env) i pbty c'1 c'2)]
1297
1298 | Rel x1, Rel x2 ->
1299 if Int.equal x1 x2 then
1300 exact_ise_stack2 env evd (evar_conv_x flags) sk1 sk2
1301 else UnifFailure (evd,NotSameHead)
1302
1303 | Var var1, Var var2 ->
1304 if Id.equal var1 var2 then
1305 exact_ise_stack2 env evd (evar_conv_x flags) sk1 sk2
1306 else UnifFailure (evd,NotSameHead)
1307
1308 | Const _, Const _
1309 | Ind _, Ind _
1310 | Construct _, Construct _
1311 | Int _, Int _
1312 | Float _, Float _
1313 | String _, String _
1314 | Array _, Array _ ->
1315 rigids env evd sk1 term1 sk2 term2
1316
1317 | Evar (sp1,al1), Evar (sp2,al2) -> (* Frozen evars *)
1318 if Evar.equal sp1 sp2 then
1319 match ise_stack2 false env evd (evar_conv_x flags) sk1 sk2 with
1320 |None, Success i' ->
1321 let al1 = Evd.expand_existential i' (sp1, al1) in
1322 let al2 = Evd.expand_existential i' (sp2, al2) in
1323 ise_inst2 i' (fun i' -> evar_conv_x flags env i' CONV) al1 al2
1324 |_, (UnifFailure _ as x) -> x
1325 |Some _, _ -> UnifFailure (evd,NotSameArgSize)
1326 else UnifFailure (evd,NotSameHead)
1327
1328 | Construct u, _ ->
1329 eta_constructor flags env evd u sk1 (term2,sk2)
1330
1331 | _, Construct u ->
1332 eta_constructor flags env evd u sk2 (term1,sk1)
1333
1334 | Fix ((li1, i1),(_,tys1,bds1 as recdef1)), Fix ((li2, i2),(_,tys2,bds2)) -> (* Partially applied fixs *)
1335 if Int.equal i1 i2 && Array.equal Int.equal li1 li2 then
1336 ise_and evd [
1337 (fun i -> ise_array2 i (fun i' -> evar_conv_x flags env i' CONV) tys1 tys2);
1338 (fun i -> ise_array2 i (fun i' -> evar_conv_x flags (push_rec_types recdef1 env) i' CONV) bds1 bds2);
1339 (fun i -> exact_ise_stack2 env i (evar_conv_x flags) sk1 sk2)]
1340 else UnifFailure (evd, NotSameHead)
1341
1342 | CoFix (i1,(_,tys1,bds1 as recdef1)), CoFix (i2,(_,tys2,bds2)) ->
1343 if Int.equal i1 i2 then
1344 ise_and evd
1345 [(fun i -> ise_array2 i
1346 (fun i -> evar_conv_x flags env i CONV) tys1 tys2);
1347 (fun i -> ise_array2 i
1348 (fun i -> evar_conv_x flags (push_rec_types recdef1 env) i CONV)
1349 bds1 bds2);
1350 (fun i -> exact_ise_stack2 env i
1351 (evar_conv_x flags) sk1 sk2)]
1352 else UnifFailure (evd,NotSameHead)
1353
1354 | (Meta _, _) | (_, Meta _) ->
1355 begin match ise_stack2 true env evd (evar_conv_x flags) sk1 sk2 with
1356 |_, (UnifFailure _ as x) -> x
1357 |None, Success i' -> evar_conv_x flags env i' CONV term1 term2
1358 |Some (sk1',sk2'), Success i' -> evar_conv_x flags env i' CONV (Stack.zip i' (term1,sk1')) (Stack.zip i' (term2,sk2'))
1359 end
1360
1361 | Proj (p1,_,c1), Proj(p2,_,c2) when QProjection.Repr.equal env (Projection.repr p1) (Projection.repr p2) ->
1362 begin match ise_stack2 true env evd (evar_conv_x flags) sk1 sk2 with
1363 |_, (UnifFailure _ as x) -> x
1364 |None, Success i' -> evar_conv_x flags env i' CONV c1 c2
1365 |Some _, Success _ -> UnifFailure (evd,NotSameHead)
1366 end
1367
1368 (* Catch the c.(p) ~= p c' cases *)
1369 | Proj (p1,_,c1), Const (p2,_) when QConstant.equal env (Projection.constant p1) p2 ->
1370 let c1 =
1371 try Some (destApp evd (Retyping.expand_projection env evd p1 c1 []))
1372 with Retyping.RetypeError _ -> None
1373 in
1374 begin match c1 with
1375 | Some (c1,new_args) ->
1376 rigids env evd (Stack.append_app new_args sk1) c1 sk2 term2
1377 | None -> UnifFailure (evd,NotSameHead)
1378 end
1379
1380 | Const (p1,_), Proj (p2,_,c2) when QConstant.equal env p1 (Projection.constant p2) ->
1381 let c2 =
1382 try Some (destApp evd (Retyping.expand_projection env evd p2 c2 []))
1383 with Retyping.RetypeError _ -> None
1384 in
1385 begin match c2 with
1386 | Some (c2,new_args) ->
1387 rigids env evd sk1 term1 (Stack.append_app new_args sk2) c2
1388 | None -> UnifFailure (evd,NotSameHead)
1389 end
1390
1391 | (Ind _ | Sort _ | Prod _ | CoFix _ | Fix _ | Rel _ | Var _ | Const _ | Int _ | Float _ | String _ | Array _ | Evar _ | Lambda _), _ ->
1392 UnifFailure (evd,NotSameHead)
1393 | _, (Ind _ | Sort _ | Prod _ | CoFix _ | Fix _ | Rel _ | Var _ | Const _ | Int _ | Array _ | Evar _ | Lambda _) ->
1394 UnifFailure (evd,NotSameHead)
1395 | Case _, _ -> UnifFailure (evd,NotSameHead)
1396 | Proj _, _ -> UnifFailure (evd,NotSameHead)
1397 | (App _ | Cast _), _ -> assert false
1398 | LetIn _, _ -> assert false
1399 end
1400
1401 and conv_record flags env (evd,(h,h2),c,bs,(params,params1),(us,us2),(sk1,sk2),c1,(n,t2)) =
1402 (* Tries to unify the states
1403
1404 (proji params1 c1 | sk1) = (proji params2 (c (?xs:bs)) | sk2)
1405
1406 and the terms
1407
1408 h us = h2 us2
1409
1410 where
1411
1412 c = the constant for the canonical structure (i.e. some term of the form
1413 fun (xs:bs) => Build_R params v1 .. vi-1 (h us) vi+1 .. vn)
1414 bs = the types of the parameters of the canonical structure
1415 c1 = the main argument of the canonical projection
1416 sk1, sk2 = the surrounding stacks of the conversion problem
1417 params1, params2 = the params of the projection (empty if a primitive proj)
1418
1419 knowing that
1420
1421 (proji params1 c1 | sk1) = (h2 us2 | sk2)
1422
1423 had to be initially resolved
1424 *)
1425 if Reductionops.Stack.compare_shape sk1 sk2 then
1426 let (evd',ks,_,test) =
1427 List.fold_left
1428 (fun (i,ks,m,test) b ->
1429 if match n with Some n -> Int.equal m n | None -> false then
1430 let ty = Retyping.get_type_of env i t2 in
1431 let test i = evar_conv_x flags env i CUMUL ty (substl ks b) in
1432 (i,t2::ks, m-1, test)
1433 else
1434 let dloc = Loc.tag Evar_kinds.InternalHole in
1435 let ty = substl ks b in
1436 let typeclass_candidate = Typeclasses.is_maybe_class_type env i ty in
1437 let (i', ev) = Evarutil.new_evar ~typeclass_candidate env i ~src:dloc ty in
1438 (i', ev :: ks, m - 1,test))
1439 (evd,[],List.length bs,fun i -> Success i) bs
1440 in
1441 let app = mkApp (c, Array.rev_of_list ks) in
1442 let unif_params =
1443 match params1 with
1444 | None -> []
1445 | Some params1 ->
1446 [(fun i ->
1447 ise_list2 i
1448 (fun i' x1 x -> evar_conv_x flags env i' CONV x1 (substl ks x))
1449 params1 params)] in
1450 ise_and evd' (
1451 unif_params @
1452 [(fun i -> ise_list2 i
1453 (fun i' u1 u -> evar_conv_x flags env i' CONV u1 (substl ks u))
1454 us2 us);
1455 (fun i -> evar_conv_x flags env i CONV c1 app);
1456 (fun i -> exact_ise_stack2 env i (evar_conv_x flags) sk1 sk2);
1457 test;
1458 (fun i -> evar_conv_x flags env i CONV h2
1459 (fst (decompose_app i (substl ks h))))])
1460 else UnifFailure(evd,(*dummy*)NotSameHead)
1461
1462 and eta_constructor flags env evd ((ind, i), u) sk1 (term2,sk2) =
1463 (* reduces an equation <Construct(ind,i)|sk1> == <term2|sk2> to the
1464 equations [arg_i = Proj_i (sk2[term2])] where [sk1] is [params args] *)
1465 let open Declarations in
1466 let mib = lookup_mind (fst ind) env in
1467 match get_projections env ind with
1468 | Some projs when mib.mind_finite == BiFinite ->
1469 let pars = mib.mind_nparams in
1470 begin match Stack.list_of_app_stack sk1 with
1471 | None -> UnifFailure (evd,NotSameHead)
1472 | Some l1 ->
1473 (try
1474 let l1' = List.skipn pars l1 in
1475 let l2' =
1476 let term = Stack.zip evd (term2,sk2) in
1477 List.map (fun (p,r) ->
1478 let r = EConstr.Vars.subst_instance_relevance u (ERelevance.make r) in
1479 EConstr.mkProj (Projection.make p false, r, term))
1480 (Array.to_list projs)
1481 in
1482 let f i t1 t2 = evar_conv_x { flags with with_cs = false } env i CONV t1 t2 in
1483 ise_list2 evd f l1' l2'
1484 with
1485 | Failure _ ->
1486 (* List.skipn: partially applied constructor *)
1487 UnifFailure(evd,NotSameHead))
1488 end
1489 | _ -> UnifFailure (evd,NotSameHead)
1490
1491 let evar_conv_x flags env evd pbty term1 term2 =
1492 debug_unification Pp.(fun () ->
1493 str "Starting unification:" ++ spc() ++
1494 Termops.Internal.print_constr_env env evd term1 ++
1495 (match pbty with CONV -> strbrk " =~= " | CUMUL -> strbrk " <~= ") ++
1496 Termops.Internal.print_constr_env env evd term2);
1497 let res =
1498 evar_conv_x flags env evd pbty term1 term2
1499 in
1500 let () = debug_unification Pp.(fun () ->
1501 let success = match res with
1502 | Success _ -> "success"
1503 | UnifFailure _ -> "failure"
1504 in
1505 str "Leaving unification with " ++ str success)
1506 in
1507 res
1508
1509 let evar_unify = conv_fun evar_conv_x
1510
1511 let evar_conv_hook = ref evar_conv_x
1512
1513 let evar_conv_x flags = !evar_conv_hook flags
1514
1515 let set_evar_conv f = evar_conv_hook := f
1516
1517
1518 (* We assume here |l1| <= |l2| *)
1519
1520 let first_order_unification flags env evd (ev1,l1) (term2,l2) =
1521 let (deb2,rest2) = Array.chop (Array.length l2-Array.length l1) l2 in
1522 ise_and evd
1523 (* First compare extra args for better failure message *)
1524 [(fun i -> ise_array2 i (fun i -> evar_conv_x flags env i CONV) rest2 l1);
1525 (fun i ->
1526 (* Then instantiate evar unless already done by unifying args *)
1527 let t2 = mkApp(term2,deb2) in
1528 if is_defined i (fst ev1) then
1529 evar_conv_x flags env i CONV t2 (mkEvar ev1)
1530 else
1531 solve_simple_eqn ~choose:true ~imitate_defs:false
1532 evar_unify flags env i (None,ev1,t2))]
1533
1534 let choose_less_dependent_instance evd term (evk, args) =
1535 let evi = Evd.find_undefined evd evk in
1536 let rec get_subst accu decls args = match decls, SList.view args with
1537 | [], Some _ | _ :: _, None -> assert false
1538 | [], None -> accu
1539 | decl :: decls, Some (arg, args) ->
1540 let accu = get_subst accu decls args in
1541 let arg = match arg with None -> mkVar (NamedDecl.get_id decl) | Some a -> a in
1542 if EConstr.eq_constr evd arg term then NamedDecl.get_id decl :: accu
1543 else accu
1544 in
1545 let subst = get_subst [] (evar_filtered_context evi) args in
1546 match subst with
1547 | [] -> None
1548 | id :: _ -> Some (Evd.define evk (mkVar id) evd)
1549
1550 type occurrence_match_test =
1551 env -> evar_map -> constr -> constr -> bool * evar_map
1552
1553 type occurrence_selection =
1554 | AtOccurrences of Locus.occurrences
1555 | Unspecified of Abstraction.abstraction
1556
1557 type occurrences_selection =
1558 occurrence_match_test * occurrence_selection list
1559
1560 let default_occurrence_selection = Unspecified Abstraction.Imitate
1561
1562 let default_occurrence_test ~allowed_evars ts env sigma c pat =
1563 let flags = { (default_flags_of ~subterm_ts:ts ts) with allowed_evars } in
1564 match evar_conv_x flags env sigma CONV c pat with
1565 | Success sigma -> true, sigma
1566 | UnifFailure _ -> false, sigma
1567
1568 let default_occurrences_selection ?(allowed_evars=AllowedEvars.all) ts n =
1569 (default_occurrence_test ~allowed_evars ts,
1570 List.init n (fun _ -> default_occurrence_selection))
1571
1572 let occur_evars sigma evs c =
1573 if Evar.Set.is_empty evs then false
1574 else
1575 let rec occur_rec c = match EConstr.kind sigma c with
1576 | Evar (sp, args) ->
1577 if Evar.Set.mem sp evs then raise Occur
1578 else SList.Skip.iter occur_rec args
1579 | _ -> EConstr.iter sigma occur_rec c
1580 in
1581 try occur_rec c; false with Occur -> true
1582
1583 let apply_on_subterm env evd fixed f test c t =
1584 let prc env evd = Termops.Internal.print_constr_env env evd in
1585 let evdref = ref evd in
1586 let fixedref = ref fixed in
1587 let rec applyrec (env,(k,c) as acc) t =
1588 if occur_evars !evdref !fixedref t then
1589 match EConstr.kind !evdref t with
1590 | Evar (evk, args) ->
1591 if Evar.Set.mem evk !fixedref then t
1592 else
1593 let args = Evd.expand_existential !evdref (evk, args) in
1594 let args = List.Smart.map (applyrec acc) args in
1595 EConstr.mkLEvar !evdref (evk, args)
1596 | _ -> map_constr_with_binders_left_to_right env !evdref
1597 (fun d (env,(k,c)) -> (push_rel d env, (k+1,lift 1 c)))
1598 applyrec acc t
1599 else
1600 (debug_ho_unification (fun () ->
1601 Pp.(str"Testing " ++ prc env !evdref c ++ str" against " ++ prc env !evdref t));
1602 let b, evd =
1603 try test env !evdref c t
1604 with e when CErrors.noncritical e -> assert false in
1605 if b then (debug_ho_unification (fun () -> Pp.str "succeeded");
1606 let evd', fixed, t' = f !evdref !fixedref k t in
1607 fixedref := fixed;
1608 evdref := evd'; t')
1609 else (
1610 debug_ho_unification (fun () -> Pp.str "failed");
1611 map_constr_with_binders_left_to_right env !evdref
1612 (fun d (env,(k,c)) -> (push_rel d env, (k+1,lift 1 c)))
1613 applyrec acc t))
1614 in
1615 let t' = applyrec (env,(0,c)) t in
1616 !evdref, !fixedref, t'
1617
1618 let filter_possible_projections evd i0 c ty ctxt args =
1619 (* Since args in the types will be replaced by holes, we count the
1620 fv of args to have a well-typed filter; don't know how necessary
1621 it is however to have a well-typed filter here *)
1622 let args = Array.of_list args in
1623 let fv1 = free_rels evd (mkApp (c,args)) (* Hack: locally untyped *) in
1624 let fv2 = collect_vars evd (mkApp (c,args)) in
1625 let len = Array.length args in
1626 let tyvars = collect_vars evd ty in
1627 List.map_i (fun i decl ->
1628 let () = assert (i < len) in
1629 let a = Array.unsafe_get args i in
1630 (match decl with
1631 | NamedDecl.LocalAssum _ -> false
1632 | NamedDecl.LocalDef (_,c,_) -> not (isRel evd c || isVar evd c)) ||
1633 Int.equal i0 i (* check whether [c] is [args.(i)] *) ||
1634 (* Here we make an approximation, for instance, we could also be *)
1635 (* interested in finding a term u convertible to c such that a occurs *)
1636 (* in u *)
1637 isRel evd a && Int.Set.mem (destRel evd a) fv1 ||
1638 isVar evd a && Id.Set.mem (destVar evd a) fv2 ||
1639 Id.Set.mem (NamedDecl.get_id decl) tyvars)
1640 0 ctxt
1641
1642 let solve_evars = ref (fun _ -> failwith "solve_evars not installed")
1643 let set_solve_evars f = solve_evars := f
1644
1645 (* We solve the problem env_rhs |- ?e[u1..un] = rhs knowing
1646 * x1:T1 .. xn:Tn |- ev : ty
1647 * by looking for a maximal well-typed abtraction over u1..un in rhs
1648 *
1649 * We first build C[e11..e1p1,..,en1..enpn] obtained from rhs by replacing
1650 * all occurrences of u1..un by evars eij of type Ti' where itself Ti' has
1651 * been obtained from the type of ui by also replacing all occurrences of
1652 * u1..ui-1 by evars.
1653 *
1654 * Then, we use typing to infer the relations between the different
1655 * occurrences. If some occurrence is still unconstrained after typing,
1656 * we instantiate successively the unresolved occurrences of un by xn,
1657 * of un-1 by xn-1, etc [the idea comes from Chung-Kil Hur, that he
1658 * used for his Heq plugin; extensions to several arguments based on a
1659 * proposition from Dan Grayson]
1660 *)
1661
1662 let check_selected_occs env sigma c occ occs =
1663 let notfound =
1664 match occs with
1665 | AtOccurrences occs ->
1666 (match occs with
1667 | Locus.AtLeastOneOccurrence -> occ == 1
1668 | Locus.AllOccurrences -> false
1669 | Locus.AllOccurrencesBut l -> List.last l > occ
1670 | Locus.OnlyOccurrences l -> List.last l > occ
1671 | Locus.NoOccurrences -> false)
1672 | Unspecified abstract -> false
1673 in if notfound then
1674 raise (PretypeError (env,sigma,NoOccurrenceFound (c,None)))
1675 else ()
1676
1677 (* Error local to the module *)
1678 exception TypingFailed of evar_map
1679
1680 let set_of_evctx l =
1681 List.fold_left (fun s decl -> Id.Set.add (NamedDecl.get_id decl) s) Id.Set.empty l
1682
1683 (** Weaken the existentials so that they can be typed in sign and raise
1684 an error if the term otherwise mentions variables not bound in sign. *)
1685 let thin_evars env sigma sign c =
1686 let sigma = ref sigma in
1687 let ctx = set_of_evctx sign in
1688 let rec applyrec (env,acc) t =
1689 match kind !sigma t with
1690 | Evar (ev, args) ->
1691 let evi = Evd.find_undefined !sigma ev in
1692 let args = Evd.expand_existential !sigma (ev, args) in
1693 let filter = List.map (fun c -> Id.Set.subset (collect_vars !sigma c) ctx) args in
1694 let filter = Filter.make filter in
1695 let candidates = evar_candidates evi in
1696 let evd, ev = restrict_evar !sigma ev filter candidates in
1697 sigma := evd; whd_evar !sigma t
1698 | Var id ->
1699 if not (Id.Set.mem id ctx) then raise (TypingFailed !sigma)
1700 else t
1701 | _ ->
1702 map_constr_with_binders_left_to_right env !sigma
1703 (fun d (env,acc) -> (push_rel d env, acc+1))
1704 applyrec (env,acc) t
1705 in
1706 let c' = applyrec (env,0) c in
1707 (!sigma, c')
1708
1709 let second_order_matching flags env_rhs evd (evk,args) (test,argoccs) rhs =
1710 try
1711 let evi = Evd.find_undefined evd evk in
1712 let evi = nf_evar_info evd evi in
1713 let env_evar_unf = evar_env env_rhs evi in
1714 let env_evar = evar_filtered_env env_rhs evi in
1715 let sign = named_context_val env_evar in
1716 let ctxt = evar_filtered_context evi in
1717 debug_ho_unification (fun () ->
1718 Pp.(str"rhs env: " ++ Termops.Internal.print_env env_rhs evd ++ fnl () ++
1719 str"evar env: " ++ Termops.Internal.print_env env_evar evd));
1720 let args = Evd.expand_existential evd (evk, args) in
1721 let args = List.map (nf_evar evd) args in
1722 let argsubst = List.map2 (fun decl c -> (NamedDecl.get_id decl, c)) ctxt args in
1723 let rhs = nf_evar evd rhs in
1724 if not (noccur_evar env_rhs evd evk rhs) then raise (TypingFailed evd);
1725 (* Ensure that any progress made by Typing.e_solve_evars will not contradict
1726 the solution we are trying to build here by adding the problem as a constraint. *)
1727 let evd = Evarutil.add_unification_pb (CONV,env_rhs,mkLEvar evd (evk, args),rhs) evd in
1728 let prc env evd c = Termops.Internal.print_constr_env env evd c in
1729 let rec make_subst i = function
1730 | decl'::ctxt', c::l, occs::occsl when isVarId evd (NamedDecl.get_id decl') c ->
1731 begin match occs with
1732 | AtOccurrences loc when not (Locusops.is_all_occurrences loc) ->
1733 user_err Pp.(str "Cannot force abstraction on identity instance.")
1734 | _ ->
1735 make_subst (i + 1) (ctxt',l,occsl)
1736 end
1737 | decl'::ctxt', c::l, occs::occsl ->
1738 let id = NamedDecl.get_annot decl' in
1739 let t = NamedDecl.get_type decl' in
1740 let evs = ref [] in
1741 let c = nf_evar evd c in
1742 (* ty is in env_rhs now *)
1743 let ty = replace_vars evd argsubst t in
1744 let filter' = filter_possible_projections evd i c (nf_evar evd ty) ctxt args in
1745 (id,t,c,ty,evs,Filter.make filter',occs) :: make_subst (i + 1) (ctxt',l,occsl)
1746 | _, _, [] -> []
1747 | _ -> anomaly (Pp.str "Signature or instance are shorter than the occurrences list.")
1748 in
1749 let rec set_holes env_rhs evd fixed rhs = function
1750 | (id,idty,c,cty,evsref,filter,occs)::subst ->
1751 let c = nf_evar evd c in
1752 debug_ho_unification (fun () ->
1753 Pp.(str"set holes for: " ++
1754 prc env_rhs evd (mkVar id.binder_name) ++ spc () ++
1755 prc env_rhs evd c ++ str" in " ++
1756 prc env_rhs evd rhs));
1757 let occ = ref 1 in
1758 let set_var evd fixed k inst =
1759 let oc = !occ in
1760 debug_ho_unification (fun () ->
1761 Pp.(str"Found one occurrence" ++ fnl () ++
1762 str"cty: " ++ prc env_rhs evd c));
1763 incr occ;
1764 match occs with
1765 | AtOccurrences occs ->
1766 if Locusops.is_selected oc occs then evd, fixed, mkVar id.binder_name
1767 else evd, fixed, inst
1768 | Unspecified prefer_abstraction ->
1769 let evd, fixed, evty = set_holes env_rhs evd fixed cty subst in
1770 let evty = nf_evar evd evty in
1771 debug_ho_unification (fun () ->
1772 Pp.(str"abstracting one occurrence " ++ prc env_rhs evd inst ++
1773 str" of type: " ++ prc env_evar evd evty ++
1774 str " for " ++ prc env_rhs evd c));
1775 (* Allow any type lower than the variable's type as the
1776 abstracted subterm might have a smaller type, which could be
1777 crucial to make the surrounding context typecheck. *)
1778 let evd, evty =
1779 if isArity evd evty then
1780 refresh_universes ~status:Evd.univ_flexible (Some true)
1781 env_evar_unf evd evty
1782 else evd, evty in
1783 (* XXX incorrect relevance *)
1784 let typeclass_candidate = Typeclasses.is_maybe_class_type env_evar evd evty in
1785 let (evd, evk) = new_pure_evar ~typeclass_candidate sign evd ~relevance:ERelevance.relevant evty ~filter in
1786 let EvarInfo evi = Evd.find evd evk in
1787 let instance = Evd.evar_identity_subst evi in
1788 let fixed = Evar.Set.add evk fixed in
1789 evsref := (evk,evty,inst,prefer_abstraction)::!evsref;
1790 evd, fixed, mkEvar (evk, instance)
1791 in
1792 let evd, fixed, rhs' = apply_on_subterm env_rhs evd fixed set_var test c rhs in
1793 debug_ho_unification (fun () ->
1794 Pp.(str"abstracted: " ++ prc env_rhs evd rhs'));
1795 let () = check_selected_occs env_rhs evd c !occ occs in
1796 let env_rhs' = push_named (NamedDecl.LocalAssum (id,idty)) env_rhs in
1797 set_holes env_rhs' evd fixed rhs' subst
1798 | [] -> evd, fixed, rhs in
1799
1800 let subst = make_subst 0 (ctxt,args,argoccs) in
1801
1802 let evd, _, rhs' = set_holes env_rhs evd Evar.Set.empty rhs subst in
1803 let rhs' = nf_evar evd rhs' in
1804 (* Thin evars making the term typable in env_evar *)
1805 let evd, rhs' = thin_evars env_evar evd ctxt rhs' in
1806 (* We instantiate the evars of which the value is forced by typing *)
1807 debug_ho_unification (fun () ->
1808 Pp.(str"solve_evars on: " ++ prc env_evar evd rhs' ++ fnl () ++
1809 str"evars: " ++ pr_evar_map (Some 0) env_evar evd));
1810 let evd,rhs' =
1811 try !solve_evars env_evar evd rhs'
1812 with e when Pretype_errors.precatchable_exception e ->
1813 (* Could not revert all subterms *)
1814 raise (TypingFailed evd) in
1815 let rhs' = nf_evar evd rhs' in
1816 (* We instantiate the evars of which the value is forced by typing *)
1817 debug_ho_unification (fun () ->
1818 Pp.(str"after solve_evars: " ++ prc env_evar evd rhs' ++ fnl () ++
1819 str"evars: " ++ pr_evar_map (Some 0) env_evar evd));
1820
1821 let rec abstract_free_holes evd = function
1822 | (id,idty,c,cty,evsref,_,_)::l ->
1823 let id = id.binder_name in
1824 let c = nf_evar evd c in
1825 debug_ho_unification (fun () ->
1826 Pp.(str"abstracting: " ++
1827 prc env_rhs evd (mkVar id) ++ spc () ++
1828 prc env_rhs evd c));
1829 let rec force_instantiation evd = function
1830 | (evk,evty,inst,abstract)::evs ->
1831 let evk = Option.default evk (Evarutil.advance evd evk) in
1832 let evd =
1833 if is_undefined evd evk then
1834 (* We try abstraction or concretisation for *)
1835 (* this unconstrained occurrence *)
1836 (* and we use typing to propagate this instantiation *)
1837 (* We avoid making an arbitrary choice by leaving candidates *)
1838 (* if both can work *)
1839 let evi = Evd.find_undefined evd evk in
1840 let vid = mkVar id in
1841 let candidates = [inst; vid] in
1842 try
1843 let evd, ev = Evarutil.restrict_evar evd evk (Evd.evar_filter evi) (Some candidates) in
1844 let evi = Evd.find_undefined evd ev in
1845 (match evar_candidates evi with
1846 | Some [t] ->
1847 if not (noccur_evar env_rhs evd ev t) then
1848 raise (TypingFailed evd);
1849 instantiate_evar evar_unify flags env_rhs evd ev t
1850 | Some l when abstract = Abstraction.Abstract &&
1851 List.exists (fun c -> isVarId evd id c) l ->
1852 instantiate_evar evar_unify flags env_rhs evd ev vid
1853 | _ -> evd)
1854 with IllTypedInstance _ (* from instantiate_evar *) | TypingFailed _ ->
1855 user_err (Pp.str "Cannot find an instance.")
1856 else
1857 ((debug_ho_unification (fun () ->
1858 let EvarInfo evi = Evd.find evd evk in
1859 let env = Evd.evar_env env_rhs evi in
1860 Pp.(str"evar is defined: " ++
1861 int (Evar.repr evk) ++ spc () ++
1862 prc env evd (match evar_body evi with Evar_defined c -> c
1863 | Evar_empty -> assert false)));
1864 evd))
1865 in force_instantiation evd evs
1866 | [] -> abstract_free_holes evd l
1867 in force_instantiation evd !evsref
1868 | [] ->
1869 if Evd.is_defined evd evk then
1870 (* Can happen due to dependencies: instantiating evars in the arguments of evk might
1871 instantiate evk itself. *)
1872 (debug_ho_unification (fun () ->
1873 begin
1874 let EvarInfo evi = Evd.find evd evk in
1875 let evenv = evar_env env_rhs evi in
1876 let body = match evar_body evi with Evar_empty -> assert false | Evar_defined c -> c in
1877 Pp.(str"evar was defined already as: " ++ prc evenv evd body)
1878 end);
1879 evd)
1880 else
1881 try
1882 let evi = Evd.find_undefined evd evk in
1883 let evenv = evar_env env_rhs evi in
1884 let rhs' = nf_evar evd rhs' in
1885 debug_ho_unification (fun () ->
1886 Pp.(str"abstracted type before second solve_evars: " ++
1887 prc evenv evd rhs'));
1888 (* solve_evars is not commuting with nf_evar, because restricting
1889 an evar might provide a more specific type. *)
1890 let evd, _ = !solve_evars evenv evd rhs' in
1891 debug_ho_unification (fun () ->
1892 Pp.(str"abstracted type: " ++ prc evenv evd (nf_evar evd rhs')));
1893 let flags = default_flags_of TransparentState.full in
1894 Evarsolve.instantiate_evar evar_unify flags env_rhs evd evk rhs'
1895 with IllTypedInstance _ -> raise (TypingFailed evd)
1896 in
1897 let evd = abstract_free_holes evd subst in
1898 evd, true
1899 with TypingFailed evd -> evd, false
1900
1901 let default_evar_selection flags evd (ev,args) =
1902 let evi = Evd.find_undefined evd ev in
1903 let args = Evd.expand_existential evd (ev, args) in
1904 let rec aux args abs =
1905 match args, abs with
1906 | _ :: args, a :: abs ->
1907 let spec = Unspecified a in
1908 spec :: aux args abs
1909 | l, [] -> List.map (fun _ -> default_occurrence_selection) l
1910 | [], _ :: _ -> assert false
1911 in aux args (Evd.evar_abstract_arguments evi)
1912
1913 let second_order_matching_with_args flags env evd with_ho pbty ev l t =
1914 if with_ho then
1915 let evd,ev = evar_absorb_arguments env evd ev (Array.to_list l) in
1916 let argoccs = default_evar_selection flags evd ev in
1917 let test = default_occurrence_test ~allowed_evars:flags.allowed_evars flags.subterm_ts in
1918 let evd, b =
1919 try second_order_matching flags env evd ev (test,argoccs) t
1920 with PretypeError (_, _, NoOccurrenceFound _) -> evd, false
1921 in
1922 if b then Success evd
1923 else
1924 UnifFailure (evd, ConversionFailed (env,mkApp(mkEvar ev,l),t))
1925 else
1926 let pb = (pbty,env,mkApp(mkEvar ev,l),t) in
1927 UnifFailure (evd, CannotSolveConstraint (pb,ProblemBeyondCapabilities))
1928
1929 let is_beyond_capabilities = function
1930 | CannotSolveConstraint (pb,ProblemBeyondCapabilities) -> true
1931 | _ -> false
1932
1933 let is_constant_instance sigma (evk, args) alias =
1934 let args = Evd.expand_existential sigma (evk, args) in
1935 List.for_all (fun a -> EConstr.eq_constr sigma a alias || isEvar sigma a)
1936 (remove_instance_local_defs sigma evk args)
1937
1938 let apply_conversion_problem_heuristic flags env evd with_ho pbty t1 t2 =
1939 let t1 = apprec_nohdbeta flags env evd (whd_head_evar evd t1) in
1940 let t2 = apprec_nohdbeta flags env evd (whd_head_evar evd t2) in
1941 let (term1,l1 as appr1) = try destApp evd t1 with DestKO -> (t1, [||]) in
1942 let (term2,l2 as appr2) = try destApp evd t2 with DestKO -> (t2, [||]) in
1943 let () = debug_unification (fun () ->
1944 Pp.(v 0 (str "Heuristic:" ++ spc () ++
1945 Termops.Internal.print_constr_env env evd t1 ++ cut () ++
1946 Termops.Internal.print_constr_env env evd t2 ++ cut ()))) in
1947 let app_empty = Array.is_empty l1 && Array.is_empty l2 in
1948 match EConstr.kind evd term1, EConstr.kind evd term2 with
1949 | Evar (evk1,args1), (Rel _|Var _) when app_empty
1950 && is_evar_allowed flags evk1
1951 && is_constant_instance evd (evk1, args1) term2 ->
1952 (* The typical kind of constraint coming from pattern-matching return
1953 type inference *)
1954 (match choose_less_dependent_instance evd term2 (evk1, args1) with
1955 | Some evd -> Success evd
1956 | None ->
1957 let reason = ProblemBeyondCapabilities in
1958 UnifFailure (evd, CannotSolveConstraint ((pbty,env,t1,t2),reason)))
1959 | (Rel _|Var _), Evar (evk2,args2) when app_empty
1960 && is_evar_allowed flags evk2
1961 && is_constant_instance evd (evk2, args2) term1 ->
1962 (* The typical kind of constraint coming from pattern-matching return
1963 type inference *)
1964 (match choose_less_dependent_instance evd term1 (evk2, args2) with
1965 | Some evd -> Success evd
1966 | None ->
1967 let reason = ProblemBeyondCapabilities in
1968 UnifFailure (evd, CannotSolveConstraint ((pbty,env,t1,t2),reason)))
1969 | Evar (evk1,args1), Evar (evk2,args2) when Evar.equal evk1 evk2 ->
1970 let f flags ontype env evd pbty x y =
1971 let reds =
1972 match ontype with
1973 | TypeUnification -> TransparentState.full
1974 | TermUnification -> flags.open_ts
1975 in is_fconv ~reds pbty env evd x y
1976 in
1977 Success (solve_refl ~can_drop:true f flags env evd
1978 (position_problem true pbty) evk1 args1 args2)
1979 | Evar (evk1,_ as ev1), Evar ev2 when app_empty ->
1980 (* solve_evar_evar handles the cases ev1 and/or ev2 are frozen *)
1981 (try
1982 Success (solve_evar_evar ~force:true
1983 (evar_define evar_unify flags ~choose:true)
1984 evar_unify flags env evd
1985 (position_problem true pbty) ev1 ev2)
1986 with IllTypedInstance (env,evd,t,u) ->
1987 UnifFailure (evd,InstanceNotSameType (evk1,env,t,u)))
1988 | Evar ev1,_ when is_evar_allowed flags (fst ev1) && Array.length l1 <= Array.length l2 ->
1989 (* On "?n t1 .. tn = u u1 .. u(n+p)", try first-order unification *)
1990 (* and otherwise second-order matching *)
1991 ise_try evd
1992 [(fun evd -> first_order_unification flags env evd (ev1,l1) appr2);
1993 (fun evd ->
1994 second_order_matching_with_args flags env evd with_ho pbty ev1 l1 t2)]
1995 | _,Evar ev2 when is_evar_allowed flags (fst ev2) && Array.length l2 <= Array.length l1 ->
1996 (* On "u u1 .. u(n+p) = ?n t1 .. tn", try first-order unification *)
1997 (* and otherwise second-order matching *)
1998 ise_try evd
1999 [(fun evd -> first_order_unification flags env evd (ev2,l2) appr1);
2000 (fun evd ->
2001 second_order_matching_with_args flags env evd with_ho pbty ev2 l2 t1)]
2002 | Evar ev1,_ when is_evar_allowed flags (fst ev1) ->
2003 (* Try second-order pattern-matching *)
2004 second_order_matching_with_args flags env evd with_ho pbty ev1 l1 t2
2005 | _,Evar ev2 when is_evar_allowed flags (fst ev2) ->
2006 (* Try second-order pattern-matching *)
2007 second_order_matching_with_args flags env evd with_ho pbty ev2 l2 t1
2008 | _ ->
2009 (* Some head evar have been instantiated, or unknown kind of problem *)
2010 evar_conv_x flags env evd pbty t1 t2
2011
2012 let error_cannot_unify env evd pb ?reason t1 t2 =
2013 Pretype_errors.error_cannot_unify
2014 ?loc:(loc_of_conv_pb evd pb) env
2015 evd ?reason (t1, t2)
2016
2017 let check_problems_are_solved ?evars env evd =
2018 match snd (extract_changed_conv_pbs_from evd evars) with
2019 | (pbty,env,t1,t2) as pb::_ -> error_cannot_unify env evd pb t1 t2
2020 | _ -> ()
2021
2022 let rec solve_unconstrained_evars_with_candidates flags env evd =
2023 (* max_undefined is supposed to return the most recent, hence
2024 possibly most dependent evar *)
2025 match Evd.max_undefined_with_candidates evd with
2026 | None -> evd
2027 | Some evk ->
2028 let ev_info = Evd.find_undefined evd evk in
2029 let l = match evar_candidates ev_info with
2030 | None -> assert false
2031 | Some l -> l
2032 in
2033 let rec aux = function
2034 | [] -> user_err Pp.(str "Unsolvable existential variables.")
2035 | a::l ->
2036 (* In case of variables, most recent ones come first *)
2037 try
2038 let evd = instantiate_evar evar_unify flags env evd evk a in
2039 match reconsider_unif_constraints evar_unify flags evd with
2040 | Success evd -> solve_unconstrained_evars_with_candidates flags env evd
2041 | UnifFailure _ -> aux l
2042 with
2043 | IllTypedInstance _ -> aux l
2044 | e when Pretype_errors.precatchable_exception e -> aux l in
2045 (* Expected invariant: most dependent solutions come first *)
2046 (* so as to favor progress when used with the refine tactics *)
2047 let evd = aux l in
2048 solve_unconstrained_evars_with_candidates flags env evd
2049
2050 let solve_unconstrained_impossible_cases env evd =
2051 Evar.Set.fold (fun evk evd' ->
2052 let evd', j = coq_unit_judge env evd' in
2053 let ty = j_type j in
2054 let flags = default_flags env in
2055 instantiate_evar evar_unify flags env evd' evk ty (* should we protect from raising IllTypedInstance? *)
2056 )
2057 (Evd.get_impossible_case_evars evd)
2058 evd
2059
2060 let solve_unif_constraints_with_heuristics env
2061 ?(flags=default_flags env) ?(with_ho=false) evd =
2062 let evd = solve_unconstrained_evars_with_candidates flags env evd in
2063 let rec aux evd pbs progress stuck =
2064 match pbs with
2065 | (pbty,env,t1,t2 as pb) :: pbs ->
2066 (match apply_conversion_problem_heuristic flags env evd with_ho pbty t1 t2 with
2067 | Success evd' ->
2068 let evd' = solve_unconstrained_evars_with_candidates flags env evd' in
2069 let (evd', rest) = extract_all_conv_pbs evd' in
2070 begin match rest with
2071 | [] -> aux evd' pbs true stuck
2072 | l ->
2073 (* Unification got actually stuck, postpone *)
2074 let reason = CannotSolveConstraint (pb,ProblemBeyondCapabilities) in
2075 aux evd pbs progress ((pb, reason):: stuck)
2076 end
2077 | UnifFailure (evd,reason) ->
2078 if is_beyond_capabilities reason then
2079 aux evd pbs progress ((pb,reason) :: stuck)
2080 else aux evd [] false ((pb,reason) :: stuck))
2081 | _ ->
2082 if progress then aux evd (List.map fst stuck) false []
2083 else
2084 match stuck with
2085 | [] -> (* We're finished *) evd
2086 | ((pbty,env,t1,t2 as pb), reason) :: _ ->
2087 (* There remains stuck problems *)
2088 Pretype_errors.error_cannot_unify ?loc:(loc_of_conv_pb evd pb)
2089 env evd ~reason (t1, t2)
2090 in
2091 let (evd,pbs) = extract_all_conv_pbs evd in
2092 let heuristic_solved_evd = aux evd pbs false [] in
2093 check_problems_are_solved env heuristic_solved_evd;
2094 solve_unconstrained_impossible_cases env heuristic_solved_evd
2095
2096 (* Main entry points *)
2097
2098 exception UnableToUnify of evar_map * unification_error
2099
2100 let evar_conv_x flags env evd pb x1 x2 : unification_result =
2101 NewProfile.profile "unification" (fun () ->
2102 evar_conv_x flags env evd pb x1 x2)
2103 ()
2104
2105 let unify_delay ?flags env evd t1 t2 =
2106 let flags =
2107 match flags with
2108 | None -> default_flags_of (default_transparent_state env)
2109 | Some flags -> flags
2110 in
2111 match evar_conv_x flags env evd CONV t1 t2 with
2112 | Success evd' -> evd'
2113 | UnifFailure (evd',e) -> raise (UnableToUnify (evd',e))
2114
2115 let unify_leq_delay ?flags env evd t1 t2 =
2116 let flags =
2117 match flags with
2118 | None -> default_flags_of (default_transparent_state env)
2119 | Some flags -> flags
2120 in
2121 match evar_conv_x flags env evd CUMUL t1 t2 with
2122 | Success evd' -> evd'
2123 | UnifFailure (evd',e) -> raise (UnableToUnify (evd',e))
2124
2125 let unify ?flags ?(with_ho=true) env evd cv_pb ty1 ty2 =
2126 let flags =
2127 match flags with
2128 | None -> default_flags_of (default_transparent_state env)
2129 | Some flags -> flags
2130 in
2131 let res = evar_conv_x flags env evd cv_pb ty1 ty2 in
2132 match res with
2133 | Success evd ->
2134 solve_unif_constraints_with_heuristics ~flags ~with_ho env evd
2135 | UnifFailure (evd, reason) ->
2136 raise (PretypeError (env, evd, CannotUnify (ty1, ty2, Some reason)))
2137
2138 let compare_heads = compare_heads CONV