Debian Codegraph @

pretyping/unification.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 Pp
13 open Util
14 open Names
15 open Constr
16 open Context
17 open Termops
18 open Environ
19 open EConstr
20 open Vars
21 open Namegen
22 open Evd
23 open Conversion
24 open Reductionops
25 open Structures
26 open Evarutil
27 open Evardefine
28 open Evarsolve
29 open Pretype_errors
30 open Retyping
31 open Locus
32 open Locusops
33 open Find_subterm
34
35 (*******************************************************************)
36 (* Metamaps *)
37
38 (*******************************************************************)
39 (* Constraints for existential variables *)
40 (*******************************************************************)
41
42 type 'a freelisted = {
43 rebus : 'a;
44 freemetas : Int.Set.t }
45
46 (* Collects all metavars appearing in a constr *)
47 let metavars_of c =
48 let rec collrec acc c =
49 match Constr.kind c with
50 | Meta mv -> Int.Set.add mv acc
51 | _ -> Constr.fold collrec acc c
52 in
53 collrec Int.Set.empty (EConstr.Unsafe.to_constr c)
54
55 let mk_freelisted c =
56 { rebus = c; freemetas = metavars_of c }
57
58 let map_fl f cfl = { cfl with rebus=f cfl.rebus }
59
60 (* Status of an instance found by unification wrt to the meta it solves:
61 - a supertype of the meta (e.g. the solution to ?X <= T is a supertype of ?X)
62 - a subtype of the meta (e.g. the solution to T <= ?X is a supertype of ?X)
63 - a term that can be eta-expanded n times while still being a solution
64 (e.g. the solution [P] to [?X u v = P u v] can be eta-expanded twice)
65 *)
66
67 type instance_constraint = IsSuperType | IsSubType | Conv
68
69 (* Status of the unification of the type of an instance against the type of
70 the meta it instantiates:
71 - CoerceToType means that the unification of types has not been done
72 and that a coercion can still be inserted: the meta should not be
73 substituted freely (this happens for instance given via the
74 "with" binding clause).
75 - TypeProcessed means that the information obtainable from the
76 unification of types has been extracted.
77 - TypeNotProcessed means that the unification of types has not been
78 done but it is known that no coercion may be inserted: the meta
79 can be substituted freely.
80 *)
81
82 type instance_typing_status =
83 CoerceToType | TypeNotProcessed | TypeProcessed
84
85 (* Status of an instance together with the status of its type unification *)
86
87 type instance_status = instance_constraint * instance_typing_status
88
89 (* Clausal environments *)
90
91 type clbinding =
92 | Cltyp of Name.t * constr freelisted
93 | Clval of Name.t * (constr freelisted * instance_status) * constr freelisted
94
95 let map_clb f = function
96 | Cltyp (na,cfl) -> Cltyp (na,map_fl f cfl)
97 | Clval (na,(cfl1,pb),cfl2) -> Clval (na,(map_fl f cfl1,pb),map_fl f cfl2)
98
99 (* name of defined is erased (but it is pretty-printed) *)
100 let clb_name = function
101 Cltyp(na,_) -> (na,false)
102 | Clval (na,_,_) -> (na,true)
103
104 (***********************)
105
106 module Metaset = Int.Set
107
108 module Metamap = Int.Map
109
110 (**********************************************************)
111 (* Accessing metas *)
112
113 module Meta =
114 struct
115
116 type t = clbinding Metamap.t
117 type nonrec instance_typing_status = instance_typing_status =
118 CoerceToType | TypeNotProcessed | TypeProcessed
119
120 let empty = Metamap.empty
121
122 let fold f map accu =
123 Metamap.fold (fun mv _ accu -> f mv accu) map accu
124
125 let map_metas f metas =
126 let map cl = map_clb f cl in
127 Metamap.Smart.map map metas
128
129 let meta_opt_fvalue0 metas mv =
130 match Metamap.find mv metas with
131 | Clval(_,b,_) -> Some b
132 | Cltyp _ -> None
133
134 let meta_opt_fvalue metas mv = match meta_opt_fvalue0 metas mv with
135 | None -> None
136 | Some (b, _) -> Some b
137
138 let meta_value evd mv = match meta_opt_fvalue evd mv with
139 | Some body -> body.rebus
140 | None -> raise Not_found
141
142 let meta_ftype metas mv =
143 match Metamap.find mv metas with
144 | Cltyp (_,b) -> b
145 | Clval(_,_,b) -> b
146
147 let meta_handler metas =
148 let meta_value mv = match meta_opt_fvalue metas mv with
149 | None -> None
150 | Some b -> Some b.rebus
151 in
152 { Reductionops.meta_value }
153
154 (* [instance] is used for [res_pf]; the call to [local_strong whd_betaiota]
155 has (unfortunately) different subtle side effects:
156
157 - ** Order of subgoals **
158 If the lemma is a case analysis with parameters, it will move the
159 parameters as first subgoals (e.g. "case H" applied on
160 "H:D->A/\B|-C" will present the subgoal |-D first while w/o
161 betaiota the subgoal |-D would have come last).
162
163 - ** Betaiota-contraction in statement **
164 If the lemma has a parameter which is a function and this
165 function is applied in the lemma, then the _strong_ betaiota will
166 contract the application of the function to its argument (e.g.
167 "apply (H (fun x => x))" in "H:forall f, f 0 = 0 |- 0=0" will
168 result in applying the lemma 0=0 in which "(fun x => x) 0" has
169 been contracted). A goal to rewrite may then fail or succeed
170 differently.
171
172 - ** Naming of hypotheses **
173 If a lemma is a function of the form "fun H:(forall a:A, P a)
174 => .. F H .." where the expected type of H is "forall b:A, P b",
175 then, without reduction, the application of the lemma will
176 generate a subgoal "forall a:A, P a" (and intro will use name
177 "a"), while with reduction, it will generate a subgoal "forall
178 b:A, P b" (and intro will use name "b").
179
180 - ** First-order pattern-matching **
181 If a lemma has the type "(fun x => p) t" then rewriting t may fail
182 if the type of the lemma is first beta-reduced (this typically happens
183 when rewriting a single variable and the type of the lemma is obtained
184 by meta_instance (with empty map) which itself calls instance with this
185 empty map).
186 *)
187
188 let meta_instance metas env sigma c =
189 (* if s = [] then c else *)
190 (* No need to compute contexts under binders as whd_betaiota is local *)
191 let metas = meta_handler metas in
192 let rec strongrec t = EConstr.map sigma strongrec (whd_betaiota ~metas env sigma t) in
193 strongrec c
194
195 let meta_type metas env evd mv =
196 let ty =
197 try meta_ftype metas mv
198 with Not_found -> anomaly (str "unknown meta ?" ++ str (Nameops.string_of_meta mv) ++ str ".") in
199 if Metaset.is_empty ty.freemetas then ty.rebus
200 else meta_instance metas env evd ty.rebus
201
202 let meta_declare mv v ?(name=Anonymous) metas =
203 let metas = Metamap.add mv (Cltyp(name,mk_freelisted v)) metas in
204 metas
205
206 (* If the meta is defined then forget its name *)
207 let meta_name metas mv =
208 try fst (clb_name (Metamap.find mv metas)) with Not_found -> Anonymous
209
210 let evar_source_of_meta mv metas =
211 match meta_name metas mv with
212 | Anonymous -> Loc.tag Evar_kinds.GoalEvar
213 | Name id -> Loc.tag @@ Evar_kinds.VarInstance id
214
215 let use_meta_source metas evd mv v =
216 let v = EConstr.Unsafe.to_constr v in
217 match Constr.kind v with
218 | Evar (evk,_) ->
219 begin match Evd.find_undefined evd evk with
220 | evi ->
221 begin match evar_source evi with
222 | None, Evar_kinds.GoalEvar -> Evd.update_source evd evk (evar_source_of_meta mv metas)
223 | _ -> evd
224 end
225 | exception Not_found -> evd
226 end
227 | _ -> evd
228
229 let meta_assign0 mv (v, pb) metas evd =
230 let modify _ = function
231 | Cltyp (na, ty) -> Clval (na, (mk_freelisted v, pb), ty)
232 | _ -> anomaly ~label:"meta_assign" (Pp.str "already defined.")
233 in
234 let metas = Metamap.modify mv modify metas in
235 let evd = use_meta_source metas evd mv v in
236 evd, metas
237
238 let meta_assign mv (v, pb) metas evd =
239 meta_assign0 mv (v, (Conv, pb)) metas evd
240
241 let meta_merge metas sigma =
242 Metamap.fold Metamap.add metas sigma
243
244 let meta_reassign mv (v, pb) metas =
245 let modify _ = function
246 | Clval(na, _, ty) -> Clval (na, (mk_freelisted v, pb), ty)
247 | _ -> anomaly ~label:"meta_reassign" (Pp.str "not yet defined.")
248 in
249 Metamap.modify mv modify metas
250
251 let map_metas_fvalue f metas =
252 let map = function
253 | Clval(id,(c,s),typ) -> Clval(id,(mk_freelisted (f c.rebus),s),typ)
254 | x -> x
255 in
256 Metamap.Smart.map map metas
257
258 let retract_coercible_metas metas =
259 let mc = ref [] in
260 let map n v = match v with
261 | Clval (na, (b, (Conv, CoerceToType as s)), typ) ->
262 let () = mc := (n, b.rebus, s) :: !mc in
263 Cltyp (na, typ)
264 | v -> v
265 in
266 let metas = Metamap.Smart.mapi map metas in
267 !mc, metas
268
269 let pr_metaset metas =
270 let open Nameops in
271 str "[" ++ pr_sequence pr_meta (Metaset.elements metas) ++ str "]"
272
273 let pr_instance_status (sc,typ) =
274 begin match sc with
275 | IsSubType -> str " [or a subtype of it]"
276 | IsSuperType -> str " [or a supertype of it]"
277 | Conv -> mt ()
278 end ++
279 begin match typ with
280 | CoerceToType -> str " [up to coercion]"
281 | TypeNotProcessed -> mt ()
282 | TypeProcessed -> str " [type is checked]"
283 end
284
285 let pr_metamap env sigma metas =
286 let open Nameops in
287 let print_constr = Termops.Internal.print_kconstr in
288 let pr_name = function
289 Name id -> str"[" ++ Id.print id ++ str"]"
290 | _ -> mt() in
291 let pr_meta_binding = function
292 | (mv,Cltyp (na,b)) ->
293 hov 0
294 (pr_meta mv ++ pr_name na ++ str " : " ++
295 print_constr env sigma b.rebus ++ fnl ())
296 | (mv,Clval(na,(b,s),t)) ->
297 hov 0
298 (pr_meta mv ++ pr_name na ++ str " := " ++
299 print_constr env sigma b.rebus ++
300 str " : " ++ print_constr env sigma t.rebus ++
301 spc () ++ pr_instance_status s ++ fnl ())
302 in
303 prlist pr_meta_binding (Metamap.bindings metas)
304
305 end
306
307 type metabinding = (metavariable * EConstr.constr * (instance_constraint * instance_typing_status))
308
309 type subst0 = {
310 subst_sigma : evar_map;
311 subst_metas : metabinding list;
312 subst_metam : clbinding Metamap.t;
313 subst_evars : ((Environ.env * int) * EConstr.existential * EConstr.t) list;
314 }
315
316 let push_sigma sigma s = {
317 subst_sigma = sigma;
318 subst_metas = s.subst_metas;
319 subst_metam = s.subst_metam;
320 subst_evars = s.subst_evars;
321 }
322
323 let push_metas sigma m s = {
324 subst_sigma = sigma;
325 subst_metas = m :: s.subst_metas;
326 subst_metam = s.subst_metam;
327 subst_evars = s.subst_evars;
328 }
329
330 let push_evars sigma e s = {
331 subst_sigma = sigma;
332 subst_metas = s.subst_metas;
333 subst_metam = s.subst_metam;
334 subst_evars = e :: s.subst_evars;
335 }
336
337 module NamedDecl = Context.Named.Declaration
338
339 let { Goptions.get = is_keyed_unification } =
340 Goptions.declare_bool_option_and_ref
341 ~key:["Keyed";"Unification"]
342 ~value:false
343 ()
344
345 let debug_tactic_unification = CDebug.create ~name:"tactic-unification" ()
346
347 let occur_meta_or_undefined_evar evd c =
348 (* This is performance-critical. Using the evar-insensitive API changes the
349 resulting heuristic. *)
350 let c = EConstr.Unsafe.to_constr c in
351 let rec occrec c = match Constr.kind c with
352 | Meta _ -> raise Occur
353 | Evar (ev,args) ->
354 let EvarInfo evi = Evd.find evd ev in
355 (match evar_body evi with
356 | Evar_defined c ->
357 occrec (EConstr.Unsafe.to_constr c); SList.Skip.iter occrec args
358 | Evar_empty -> raise Occur)
359 | _ -> Constr.iter occrec c
360 in try occrec c; false with Occur | Not_found -> true
361
362 let whd_meta ~metas sigma c = match EConstr.kind sigma c with
363 | Meta p ->
364 (try Meta.meta_value metas p with Not_found -> c)
365 (* Not recursive, for some reason *)
366 | _ -> c
367
368 let occur_meta_evd ~metas sigma mv c =
369 let rec occrec c =
370 (* Note: evars are not instantiated by terms with metas *)
371 let c = whd_meta ~metas sigma c in
372 match EConstr.kind sigma c with
373 | Meta mv' when Int.equal mv mv' -> raise Occur
374 | Evar (_, args) -> SList.Skip.iter occrec args
375 | _ -> EConstr.iter sigma occrec c
376 in try occrec c; false with Occur -> true
377
378 (* if lname_typ is [xn,An;..;x1,A1] and l is a list of terms,
379 gives [x1:A1]..[xn:An]c' such that c converts to ([x1:A1]..[xn:An]c' l) *)
380
381 let abstract_scheme env evd c l lname_typ =
382 let mkLambda_name env (n,a,b) =
383 mkLambda (map_annot (named_hd env evd a) n, a, b)
384 in
385 List.fold_left2
386 (fun (t,evd) (locc,a) (na,ta) ->
387 let na = match EConstr.kind evd a with Var id -> {na with binder_name=Name id} | _ -> na in
388 (* [occur_meta ta] test removed for support of eelim/ecase but consequences
389 are unclear...
390 if occur_meta ta then error "cannot find a type for the generalisation"
391 else *)
392 if occur_meta evd a then mkLambda_name env (na,ta,t), evd
393 else
394 let t', evd' = Find_subterm.subst_closed_term_occ env evd locc a t in
395 mkLambda_name env (na,ta,t'), evd')
396 (c,evd)
397 (List.rev l)
398 lname_typ
399
400 (* Precondition: resulting abstraction is expected to be of type [typ] *)
401
402 let abstract_list_all env evd typ c l =
403 let ctxt,_ = whd_decompose_prod_n env evd (List.length l) typ in
404 let l_with_all_occs = List.map (function a -> (LikeFirst,a)) l in
405 let p,evd = abstract_scheme env evd c l_with_all_occs ctxt in
406 let evd,typp =
407 try
408 let c = EConstr.it_mkLambda (EConstr.Vars.lift (List.length ctxt) c) ctxt in
409 Typing.recheck_against env evd c p
410 with
411 | UserError _ ->
412 error_cannot_find_well_typed_abstraction env evd p l None
413 | Type_errors.TypeError (env',x) ->
414 (* FIXME: plug back the typing information *)
415 error_cannot_find_well_typed_abstraction env evd p l None
416 | Pretype_errors.PretypeError (env',evd,e) ->
417 error_cannot_find_well_typed_abstraction env evd p l (Some (env',e)) in
418 evd,(p,typp)
419
420 let set_occurrences_of_last_arg n =
421 Evarconv.AtOccurrences AllOccurrences ::
422 List.tl (List.init n (fun _ -> Evarconv.Unspecified Abstraction.Abstract))
423
424 let occurrence_test env sigma c1 c2 =
425 match EConstr.eq_constr_universes env sigma c1 c2 with
426 | None -> false, sigma
427 | Some cstr ->
428 try true, Evd.add_constraints sigma cstr
429 with UniversesDiffer | UGraph.UniverseInconsistency _ -> false, sigma
430
431 let abstract_list_all_with_dependencies env evd typ c l =
432 let typeclass_candidate = Typeclasses.is_maybe_class_type env evd typ in
433 let (evd, ev) = new_evar ~typeclass_candidate env evd typ in
434 let evd,ev' = evar_absorb_arguments env evd (destEvar evd ev) l in
435 let n = List.length l in
436 let () = assert (n <= SList.length (snd ev')) in
437 let argoccs = set_occurrences_of_last_arg n in
438 let evd,b =
439 if occur_meta evd c then evd, false
440 else
441 Evarconv.second_order_matching
442 (Evarconv.default_flags_of TransparentState.empty)
443 env evd ev' (occurrence_test, argoccs) c in
444 if b then
445 let p = nf_evar evd ev in
446 evd, p
447 else error_cannot_find_well_typed_abstraction env evd
448 c l None
449
450 (* A refinement of [conv_pb]: the integers tells how many arguments
451 were applied in the context of the conversion problem; if the number
452 is non zero, steps of eta-expansion will be allowed
453 *)
454
455 let opp_status = function
456 | IsSuperType -> IsSubType
457 | IsSubType -> IsSuperType
458 | Conv -> Conv
459
460 let add_type_status (x,y) = ((x,TypeNotProcessed),(y,TypeNotProcessed))
461
462 let extract_instance_status = function
463 | CUMUL -> add_type_status (IsSubType, IsSuperType)
464 | CONV -> add_type_status (Conv, Conv)
465
466 let rec subst_meta_instances sigma bl c =
467 match EConstr.kind sigma c with
468 | Meta i ->
469 let select (j,_,_) = Int.equal i j in
470 (try pi2 (List.find select bl) with Not_found -> c)
471 | _ -> EConstr.map sigma (subst_meta_instances sigma bl) c
472
473 (** [env] should be the context in which the metas live *)
474
475 let pose_all_metas_as_evars ~metas env evd t =
476 let evdref = ref evd in
477 let metas = ref metas in
478 let rec aux t = match EConstr.kind !evdref t with
479 | Meta mv ->
480 (match Meta.meta_opt_fvalue !metas mv with
481 | Some {rebus=c;freemetas=mvs} ->
482 let c = if Metaset.is_empty mvs then c else aux c in
483 metas := Meta.meta_reassign mv (c,(Conv,TypeNotProcessed)) !metas;
484 c
485 | None ->
486 let {rebus=ty;freemetas=mvs} = Meta.meta_ftype !metas mv in
487 let ty = if Metaset.is_empty mvs then ty else aux ty in
488 let ty = nf_betaiota env !evdref ty in
489 let src = Meta.evar_source_of_meta mv !metas in
490 let typeclass_candidate = Typeclasses.is_maybe_class_type env !evdref ty in
491 let evd, ev = Evarutil.new_evar ~typeclass_candidate env !evdref ~src ty in
492 let evd, nmetas = Meta.meta_assign mv (ev, TypeNotProcessed) !metas evd in
493 let () = evdref := evd in
494 let () = metas := nmetas in
495 ev)
496 | _ ->
497 EConstr.map !evdref aux t in
498 let c = aux t in
499 (* side-effect *)
500 (!evdref, !metas, c)
501
502 let solve_pattern_eqn_array (env,nb) f l c (subst : subst0) =
503 let sigma = subst.subst_sigma in
504 let metas = subst.subst_metam in
505 match EConstr.kind sigma f with
506 | Meta k ->
507 (* We enforce that the Meta does not depend on the [nb]
508 extra assumptions added by unification to the context *)
509 let env' = pop_rel_context nb env in
510 let sigma, metas, c = pose_all_metas_as_evars ~metas env' sigma c in
511 let c = solve_pattern_eqn env sigma l c in
512 let pb = (Conv,TypeNotProcessed) in
513 if noccur_between sigma 1 nb c then
514 let subst = push_metas sigma (k, lift (-nb) c, pb) subst in
515 { subst with subst_metam = metas }
516 else
517 let l = List.map of_alias l in
518 error_cannot_unify_local env sigma (applist (f, l),c,c)
519 | Evar ev ->
520 let env' = pop_rel_context nb env in
521 let sigma, metas, c = pose_all_metas_as_evars ~metas env' sigma c in
522 let subst = push_evars sigma ((env,nb),ev,solve_pattern_eqn env sigma l c) subst in
523 { subst with subst_metam = metas }
524 | _ -> assert false
525
526 let push d (env,n) = (push_rel_assum d env,n+1)
527
528 (*******************************)
529
530 (* Unification à l'ordre 0 de m et n: [unify_0 env sigma cv_pb m n]
531 renvoie deux listes:
532
533 metasubst:(int*constr)list récolte les instances des (Meta k)
534 evarsubst:(constr*constr)list récolte les instances des (Const "?k")
535
536 Attention : pas d'unification entre les différences instances d'une
537 même meta ou evar, il peut rester des doublons *)
538
539 (* Unification order: *)
540 (* Left to right: unifies first argument and then the other arguments *)
541 (*let unify_l2r x = List.rev x
542 (* Right to left: unifies last argument and then the other arguments *)
543 let unify_r2l x = x
544
545 let sort_eqns = unify_r2l
546 *)
547
548 type core_unify_flags = {
549 modulo_conv_on_closed_terms : TransparentState.t option;
550 (* What this flag controls was activated with all constants transparent, *)
551 (* even for auto, since Coq V5.10 *)
552
553 use_metas_eagerly_in_conv_on_closed_terms : bool;
554 (* This refinement of the conversion on closed terms is activable *)
555 (* (and activated for apply, rewrite but not auto since Feb 2008 for 8.2) *)
556
557 use_evars_eagerly_in_conv_on_closed_terms : bool;
558
559 modulo_delta : TransparentState.t;
560 (* This controls which constants are unfoldable; this is on for apply *)
561 (* (but not simple apply) since Feb 2008 for 8.2 *)
562
563 modulo_delta_types : TransparentState.t;
564
565 check_applied_meta_types : bool;
566 (* This controls whether meta's applied to arguments have their *)
567 (* type unified with the type of their instance *)
568
569 use_pattern_unification : bool;
570 (* This solves pattern "?n x1 ... xn = t" when the xi are distinct rels *)
571 (* This says if pattern unification is tried *)
572
573 use_meta_bound_pattern_unification : bool;
574 (* This is implied by use_pattern_unification; has no particular *)
575 (* reasons to be set differently than use_pattern_unification *)
576 (* except for compatibility of "auto". *)
577 (* This was on for all tactics, including auto, since Sep 2006 for 8.1 *)
578 (* This allowed for instance to unify "forall x:?A, ?B x" with "A' -> B'" *)
579 (* when ?B is a Meta. *)
580
581 allowed_evars : AllowedEvars.t;
582 (* Evars that are allowed to be instantiated *)
583 (* Useful e.g. for autorewrite *)
584
585 restrict_conv_on_strict_subterms : bool;
586 (* No conversion at the root of the term; potentially useful for rewrite *)
587
588 modulo_betaiota : bool;
589 (* Support betaiota in the reduction *)
590 (* Note that zeta is always used *)
591
592 modulo_eta : bool;
593 (* Support eta in the reduction *)
594 }
595
596 type unify_flags = {
597 core_unify_flags : core_unify_flags;
598 (* Governs unification of problems of the form "t(?x) = u(?x)" in apply *)
599
600 merge_unify_flags : core_unify_flags;
601 (* These are the flags to be used when trying to unify *)
602 (* several instances of the same metavariable *)
603 (* Typical situation is when we give a pattern to be matched *)
604 (* syntactically against a subterm but we want the metas of the *)
605 (* pattern to be modulo convertibility *)
606
607 subterm_unify_flags : core_unify_flags;
608 (* Governs unification of problems of the form "?X a1..an = u" in apply, *)
609 (* hence in rewrite and elim *)
610
611 allow_K_in_toplevel_higher_order_unification : bool;
612 (* Tells in second-order abstraction over subterms which have not *)
613 (* been found in term are allowed (used for rewrite, elim, or *)
614 (* apply with a lemma whose type has the form "?X a1 ... an") *)
615
616 resolve_evars : bool
617 (* This says if type classes instances resolution must be used to infer *)
618 (* the remaining evars *)
619 }
620
621 (* Default flag for unifying a type against a type (e.g. apply) *)
622 (* We set all conversion flags (no flag should be modified anymore) *)
623 let default_core_unify_flags () =
624 let ts = TransparentState.full in {
625 modulo_conv_on_closed_terms = Some ts;
626 use_metas_eagerly_in_conv_on_closed_terms = true;
627 use_evars_eagerly_in_conv_on_closed_terms = false;
628 modulo_delta = ts;
629 modulo_delta_types = ts;
630 check_applied_meta_types = true;
631 use_pattern_unification = true;
632 use_meta_bound_pattern_unification = true;
633 allowed_evars = AllowedEvars.all;
634 restrict_conv_on_strict_subterms = false;
635 modulo_betaiota = true;
636 modulo_eta = true;
637 }
638
639 let ts_var_full =
640 let open TransparentState in
641 { tr_var = Id.Pred.full; tr_cst = Cpred.empty; tr_prj = PRpred.empty }
642
643 (* Default flag for first-order or second-order unification of a type *)
644 (* against another type (e.g. apply) *)
645 (* We set all conversion flags (no flag should be modified anymore) *)
646 let default_unify_flags () =
647 let flags = default_core_unify_flags () in {
648 core_unify_flags = flags;
649 merge_unify_flags = flags;
650 subterm_unify_flags = { flags with modulo_delta = ts_var_full };
651 allow_K_in_toplevel_higher_order_unification = false; (* Why not? *)
652 resolve_evars = false
653 }
654
655 let set_no_delta_core_flags flags = { flags with
656 modulo_conv_on_closed_terms = None;
657 modulo_delta = TransparentState.empty;
658 check_applied_meta_types = false;
659 use_pattern_unification = false;
660 use_meta_bound_pattern_unification = true;
661 modulo_betaiota = false
662 }
663
664 let set_no_delta_flags flags = {
665 core_unify_flags = set_no_delta_core_flags flags.core_unify_flags;
666 merge_unify_flags = set_no_delta_core_flags flags.merge_unify_flags;
667 subterm_unify_flags = set_no_delta_core_flags flags.subterm_unify_flags;
668 allow_K_in_toplevel_higher_order_unification =
669 flags.allow_K_in_toplevel_higher_order_unification;
670 resolve_evars = flags.resolve_evars
671 }
672
673 (* For the first phase of keyed unification, restrict
674 to conversion (including beta-iota) only on closed terms *)
675 let set_no_delta_open_core_flags flags = { flags with
676 modulo_delta = TransparentState.empty;
677 modulo_betaiota = false;
678 }
679
680 let set_no_delta_open_flags flags = {
681 core_unify_flags = set_no_delta_open_core_flags flags.core_unify_flags;
682 merge_unify_flags = set_no_delta_open_core_flags flags.merge_unify_flags;
683 subterm_unify_flags = set_no_delta_open_core_flags flags.subterm_unify_flags;
684 allow_K_in_toplevel_higher_order_unification =
685 flags.allow_K_in_toplevel_higher_order_unification;
686 resolve_evars = flags.resolve_evars
687 }
688
689 (* Default flag for the "simple apply" version of unification of a *)
690 (* type against a type (e.g. apply) *)
691 (* We set only the flags available at the time the new "apply" extended *)
692 (* out of "simple apply" *)
693 let default_no_delta_core_unify_flags () = { (default_core_unify_flags ()) with
694 modulo_delta = TransparentState.empty;
695 check_applied_meta_types = false;
696 use_pattern_unification = false;
697 use_meta_bound_pattern_unification = true;
698 modulo_betaiota = false;
699 }
700
701 let default_no_delta_unify_flags ts =
702 let flags = default_no_delta_core_unify_flags () in
703 let flags = { flags with
704 modulo_conv_on_closed_terms = Some ts;
705 modulo_delta_types = ts
706 } in
707 {
708 core_unify_flags = flags;
709 merge_unify_flags = flags;
710 subterm_unify_flags = flags;
711 allow_K_in_toplevel_higher_order_unification = false;
712 resolve_evars = false
713 }
714
715 let allow_new_evars sigma =
716 let undefined = Evd.undefined_map sigma in
717 AllowedEvars.from_pred (fun evk -> not (Evar.Map.mem evk undefined))
718
719 (* Default flags for looking for subterms in elimination tactics *)
720 (* Not used in practice at the current date, to the exception of *)
721 (* allow_K) because only closed terms are involved in *)
722 (* induction/destruct/case/elim and w_unify_to_subterm_list does not *)
723 (* call w_unify for induction/destruct/case/elim (13/6/2011) *)
724 let elim_core_flags sigma = { (default_core_unify_flags ()) with
725 modulo_betaiota = false;
726 allowed_evars = allow_new_evars sigma;
727 }
728
729 let elim_flags_evars sigma =
730 let flags = elim_core_flags sigma in {
731 core_unify_flags = flags;
732 merge_unify_flags = flags;
733 subterm_unify_flags = { flags with modulo_delta = TransparentState.empty };
734 allow_K_in_toplevel_higher_order_unification = true;
735 resolve_evars = false
736 }
737
738 let elim_flags () = elim_flags_evars Evd.empty
739
740 let elim_no_delta_core_flags () = { (elim_core_flags Evd.empty) with
741 modulo_delta = TransparentState.empty;
742 check_applied_meta_types = false;
743 use_pattern_unification = false;
744 modulo_betaiota = false;
745 }
746
747 let elim_no_delta_flags () =
748 let flags = elim_no_delta_core_flags () in {
749 core_unify_flags = flags;
750 merge_unify_flags = flags;
751 subterm_unify_flags = flags;
752 allow_K_in_toplevel_higher_order_unification = true;
753 resolve_evars = false
754 }
755
756 (* On types, we don't restrict unification, but possibly for delta *)
757 let set_flags_for_type flags = { flags with
758 modulo_delta = flags.modulo_delta_types;
759 modulo_conv_on_closed_terms = Some flags.modulo_delta_types;
760 use_pattern_unification = true;
761 modulo_betaiota = true;
762 modulo_eta = true;
763 }
764
765 let use_evars_pattern_unification flags =
766 flags.use_pattern_unification
767
768 let use_metas_pattern_unification sigma flags nb l =
769 flags.use_pattern_unification
770 || flags.use_meta_bound_pattern_unification &&
771 Array.for_all (fun c -> isRel sigma c && destRel sigma c <= nb) l
772
773
774 (* [unfold_projection_under_eta env ts n c] checks if [c] is the eta
775 expanded, folded primitive projection of name [n] and unfolds the primitive
776 projection. It respects projection transparency of [ts]. *)
777 let unfold_projection_under_eta env ts n c =
778 let unfold_projection env ts p r c =
779 if TransparentState.is_transparent_projection ts (Projection.repr p) then
780 Some (Constr.mkProj (Projection.unfold p, r, c))
781 else None
782 in
783 let rec go c lams =
784 match Constr.kind c with
785 | Lambda (b, t, c) -> go c ((b,t)::lams)
786 | Proj (p, r, c) when QConstant.equal env n (Projection.constant p) ->
787 let c = unfold_projection env ts p r c in
788 begin
789 match c with
790 | None -> None
791 | Some c ->
792 let f c (b,t) = Constr.mkLambda (b,t,c) in
793 Some (List.fold_left f c lams)
794 end
795 | _ -> None
796 in
797 go c []
798
799
800 type key =
801 | IsKey of CClosure.table_key
802 | IsProj of Projection.t * ERelevance.t * EConstr.constr
803
804 let expand_table_key ~metas ts env sigma args = function
805 | ConstKey (c, u) ->
806 if Structures.PrimitiveProjections.is_transparent_constant ts c then
807 match constant_value_in env sigma (c, EInstance.make u) with
808 (* If we are unfolding a compatibility constant we want to return the
809 unfolded primitive projection directly since we would like to pretend
810 that the compatibility constant itself does not count as an unfolding
811 (delta) step. *)
812 | def ->
813 let def = EConstr.Unsafe.to_constr def in
814 let unf = unfold_projection_under_eta env ts c def in
815 Some (EConstr.of_constr @@ Option.default def unf, args)
816 | exception NotEvaluableConst (HasRules (u, b, r)) ->
817 begin try
818 let metas = Meta.meta_handler metas in
819 let sk = Stack.( append_app args empty ) in
820 let rhs, stack = Reductionops.apply_rules
821 (fun ctx -> whd_betaiota_deltazeta_for_iota_state ts ~metas (push_rel_context ctx env) sigma) env sigma (EInstance.make u) r sk
822 in
823 let args' = Stack.list_of_app_stack stack
824 |> (function Some l -> l | None -> assert false)
825 |> Array.of_list in
826 Some (rhs, args')
827 with PatternFailure -> None
828 (* TODO: try unfold fix *)
829 end
830 | exception NotEvaluableConst _ -> None
831 else None
832 | VarKey id -> (try named_body id env |> Option.map (fun c -> (EConstr.of_constr c, args)) with Not_found -> None)
833 | RelKey _ -> None
834
835 let unfold_projection env p r stk =
836 let s = Stack.Proj (p,r) in
837 s :: stk
838
839 let expand_key ~metas ts env sigma args = function
840 | Some (IsKey k) -> (expand_table_key ~metas ts env sigma args k)
841 | Some (IsProj (p, r, c)) ->
842 let metas = Meta.meta_handler metas in
843 let red = Stack.zip sigma (whd_betaiota_deltazeta_for_iota_state ts ~metas env sigma
844 (c, unfold_projection env p r []))
845 in if EConstr.eq_constr sigma (EConstr.mkProj (p, r, c)) red then None else Some (red, args)
846 | None -> None
847
848 let isApp_or_Proj sigma c =
849 match kind sigma c with
850 | App _ | Proj _ -> true
851 | _ -> false
852
853 type unirec_flags = {
854 at_top: bool;
855 with_types: bool;
856 with_cs : bool;
857 }
858
859 let subterm_restriction opt flags =
860 not opt.at_top && flags.restrict_conv_on_strict_subterms
861
862 let key_of env sigma b flags f =
863 if subterm_restriction b flags then None else
864 match EConstr.kind sigma f with
865 | Const (cst, u) when is_transparent env (Evaluable.EvalConstRef cst) &&
866 (Structures.PrimitiveProjections.is_transparent_constant flags.modulo_delta cst
867 || PrimitiveProjections.mem cst) ->
868 let u = EInstance.kind sigma u in
869 Some (IsKey (ConstKey (cst, u)))
870 | Var id when is_transparent env (Evaluable.EvalVarRef id) &&
871 TransparentState.is_transparent_variable flags.modulo_delta id ->
872 Some (IsKey (VarKey id))
873 | Proj (p, r, c) when Names.Projection.unfolded p
874 || (is_transparent env (Evaluable.EvalProjectionRef (Projection.repr p)) &&
875 (TransparentState.is_transparent_projection flags.modulo_delta (Projection.repr p))) ->
876 Some (IsProj (p, r, c))
877 | _ -> None
878
879
880 let translate_key = function
881 | ConstKey (cst,u) -> Some (Conv_oracle.EvalConstRef cst)
882 | VarKey id -> Some (Conv_oracle.EvalVarRef id)
883 | RelKey _ -> None
884
885 let translate_key = function
886 | IsKey k -> translate_key k
887 | IsProj (p, _, _) -> Some (Conv_oracle.EvalProjectionRef (Projection.repr p))
888
889 let oracle_order env cf1 cf2 =
890 match cf1 with
891 | None ->
892 (match cf2 with
893 | None -> None
894 | Some k2 -> Some false)
895 | Some k1 ->
896 match cf2 with
897 | None -> Some true
898 | Some k2 ->
899 match k1, k2 with
900 | IsProj (p, _, _), IsKey (ConstKey (p',_))
901 when Environ.QConstant.equal env (Projection.constant p) p' ->
902 Some (not (Projection.unfolded p))
903 | IsKey (ConstKey (p,_)), IsProj (p', _, _)
904 when Environ.QConstant.equal env p (Projection.constant p') ->
905 Some (Projection.unfolded p')
906 | _ ->
907 Some (Conv_oracle.oracle_order
908 (Environ.oracle env) false (translate_key k1) (translate_key k2))
909
910 let is_rigid_head sigma flags t =
911 match EConstr.kind sigma t with
912 | Const (cst,u) -> not (Structures.PrimitiveProjections.is_transparent_constant flags.modulo_delta cst)
913 | Ind (i,u) -> true
914 | Construct _ | Int _ | Float _ | String _ | Array _ -> true
915 | Fix _ | CoFix _ -> true
916 | Rel _ | Var _ | Meta _ | Evar _ | Sort _ | Cast (_, _, _) | Prod _
917 | Lambda _ | LetIn _ | App (_, _) | Case _
918 | Proj _ -> false (* Why aren't Prod, Sort rigid heads ? *)
919
920 let constr_cmp pb env sigma flags ?nargs t u =
921 let cstrs =
922 if pb == Conversion.CONV then EConstr.eq_constr_universes env sigma ?nargs t u
923 else EConstr.leq_constr_universes env sigma ?nargs t u
924 in
925 match cstrs with
926 | Some cstrs ->
927 begin try Some (Evd.add_constraints sigma cstrs)
928 with UGraph.UniverseInconsistency _ -> None
929 | Evd.UniversesDiffer ->
930 if is_rigid_head sigma flags t then
931 try Some (Evd.add_constraints sigma (UnivProblem.Set.force cstrs))
932 with UGraph.UniverseInconsistency _ -> None
933 else None
934 end
935 | None ->
936 None
937
938 let do_reduce ~metas ts (env, nb) sigma c =
939 let metas = Meta.meta_handler metas in
940 Stack.zip sigma (whd_betaiota_deltazeta_for_iota_state ~metas
941 ts env sigma (c, Stack.empty))
942
943 let is_evar_allowed flags evk =
944 AllowedEvars.mem flags.allowed_evars evk
945
946 let isAllowedEvar sigma flags c = match EConstr.kind sigma c with
947 | Evar (evk,_) -> is_evar_allowed flags evk
948 | _ -> false
949
950
951 let subst_defined_metas_evars sigma (metas, bl, el) c =
952 (* This seems to be performance-critical, and using the
953 evar-insensitive primitives blow up the time passed in this
954 function. *)
955 if Metamap.is_empty metas && List.is_empty bl && List.is_empty el then
956 Some c
957 else
958 let c = EConstr.Unsafe.to_constr c in
959 let rec substrec c = match Constr.kind c with
960 | Meta i ->
961 let select (j,_,_) = Int.equal i j in
962 substrec (EConstr.Unsafe.to_constr (pi2 (List.find select bl)))
963 | Evar (evk,args) ->
964 let eq c1 c2 = Constr.equal c1 (EConstr.Unsafe.to_constr c2) in
965 let select (_,(evk',args'),_) = Evar.equal evk evk' && SList.equal eq args args' in
966 begin match List.find select el with
967 | (_, _, c) -> substrec (EConstr.Unsafe.to_constr c)
968 | exception Not_found ->
969 let c = EConstr.(Unsafe.to_constr (whd_evar sigma (of_constr c))) in
970 Constr.map substrec c
971 end
972 | _ -> Constr.map substrec c
973 in try Some (EConstr.of_constr (substrec c)) with Not_found -> None
974
975 let check_compatibility env pbty flags subst tyM tyN =
976 let sigma = subst.subst_sigma in
977 match subst_defined_metas_evars sigma (subst.subst_metam, subst.subst_metas, []) tyM with
978 | None -> sigma
979 | Some m ->
980 match subst_defined_metas_evars sigma (subst.subst_metam, subst.subst_metas, []) tyN with
981 | None -> sigma
982 | Some n ->
983 if is_ground_term sigma m && is_ground_term sigma n then
984 match infer_conv ~pb:pbty ~ts:flags.modulo_delta_types env sigma m n with
985 | Some sigma -> sigma
986 | None -> error_cannot_unify env sigma (m,n)
987 else sigma
988
989 let check_compatibility_ustate env pbty flags subst tyM tyN =
990 let sigma = subst.subst_sigma in
991 match subst_defined_metas_evars sigma (subst.subst_metam, subst.subst_metas, []) tyM with
992 | None -> UnivProblem.Set.empty
993 | Some m ->
994 match subst_defined_metas_evars sigma (subst.subst_metam, subst.subst_metas, []) tyN with
995 | None -> UnivProblem.Set.empty
996 | Some n ->
997 if is_ground_term sigma m && is_ground_term sigma n then
998 match infer_conv_ustate ~pb:pbty ~ts:flags.modulo_delta_types env sigma m n with
999 | Some uprob -> uprob
1000 | None -> error_cannot_unify env sigma (m,n)
1001 else UnivProblem.Set.empty
1002
1003 let rec is_neutral env sigma ts t =
1004 let (f, l) = decompose_app sigma t in
1005 match EConstr.kind sigma f with
1006 | Const (c, u) ->
1007 not (Environ.evaluable_constant c env) ||
1008 not (is_transparent env (Evaluable.EvalConstRef c)) ||
1009 not (Structures.PrimitiveProjections.is_transparent_constant ts c)
1010 | Var id ->
1011 not (Environ.evaluable_named id env) ||
1012 not (is_transparent env (Evaluable.EvalVarRef id)) ||
1013 not (TransparentState.is_transparent_variable ts id)
1014 | Rel n -> true
1015 | Evar _ | Meta _ -> true
1016 | Case (_, _, _, _, _, c, _) -> is_neutral env sigma ts c
1017 | Proj (p, _, c) -> is_neutral env sigma ts c
1018 | Lambda _ | LetIn _ | Construct _ | CoFix _ | Int _ | Float _ | String _ | Array _ -> false
1019 | Sort _ | Cast (_, _, _) | Prod (_, _, _) | Ind _ -> false (* Really? *)
1020 | Fix _ -> false (* This is an approximation *)
1021 | App _ -> assert false
1022
1023 let is_eta_constructor_app env sigma ts f l1 term =
1024 match EConstr.kind sigma f with
1025 | Construct (((mind, i), j), u) when j == 1 ->
1026 let open Declarations in
1027 let mib = lookup_mind mind env in
1028 (match mib.mind_packets.(i).mind_record with
1029 | PrimRecord { projections ; _ } when mib.Declarations.mind_finite == Declarations.BiFinite &&
1030 Array.length projections == Array.length l1 - mib.Declarations.mind_nparams ->
1031 (* Check that the other term is neutral *)
1032 is_neutral env sigma ts term
1033 | _ -> false)
1034 | _ -> false
1035
1036 let eta_constructor_app env sigma f l1 term =
1037 match EConstr.kind sigma f with
1038 | Construct (((_, i as ind), j), u) ->
1039 let mib = lookup_mind (fst ind) env in
1040 (match get_projections env ind with
1041 | Some projs ->
1042 let npars = mib.Declarations.mind_nparams in
1043 let pars, l1' = Array.chop npars l1 in
1044 let arg = Array.append pars [|term|] in
1045 let l2 = Array.map (fun (p,_) ->
1046 mkApp (mkConstU (Projection.Repr.constant p,u), arg)) projs in
1047 l1', l2
1048 | _ -> assert false)
1049 | _ -> assert false
1050
1051 let get_type_of_with_metas ~metas ?lax env sigma c =
1052 let metas n =
1053 try Some (Meta.meta_ftype metas n).rebus
1054 with Not_found -> None
1055 in
1056 Retyping.get_type_of ~metas ?lax env sigma c
1057
1058 let expand_projection_with_metas ~metas env sigma pr c args =
1059 let ty = get_type_of_with_metas ~metas ~lax:true env sigma c in
1060 let (i,u), ind_args =
1061 try Inductiveops.find_mrectype env sigma ty
1062 with Not_found -> error_not_allowed_sprop env sigma (* dummy, caught immediately *)
1063 in
1064 mkApp (mkConstU (Projection.constant pr,u),
1065 Array.of_list (ind_args @ (c :: args)))
1066
1067 (* If the terms are irrelevant, check that they have the same type. *)
1068 let careful_infer_conv ~pb ~ts env sigma m n =
1069 if Retyping.is_term_irrelevant env sigma m &&
1070 Retyping.is_term_irrelevant env sigma n
1071 then
1072 let tm = Retyping.get_type_of env sigma m in
1073 let tn = Retyping.get_type_of env sigma n in
1074 Option.bind (infer_conv ~pb:CONV ~ts env sigma tm tn)
1075 (fun sigma -> infer_conv ~pb ~ts env sigma m n)
1076 else infer_conv ~pb ~ts env sigma m n
1077
1078 type maybe_ground = Ground | NotGround | Unknown
1079
1080 let error_cannot_unify_local env sigma (m, n, p) =
1081 error_cannot_unify_local env sigma (fst m, fst n, p)
1082
1083 let fast_occur_meta_or_undefined_evar sigma (c, gnd) = match gnd with
1084 | Unknown -> occur_meta_or_undefined_evar sigma c
1085 | Ground -> false
1086 | NotGround -> true
1087
1088 let rec unify_0_with_initial_metas (subst : subst0) conv_at_top env pb flags m n =
1089 let mk_expand_subst substn =
1090 let metasubst = if flags.use_metas_eagerly_in_conv_on_closed_terms then substn.subst_metas else subst.subst_metas in
1091 let evarsubst = if flags.use_evars_eagerly_in_conv_on_closed_terms then substn.subst_evars else subst.subst_evars in
1092 (substn.subst_metam, metasubst, evarsubst)
1093 in
1094 let rec unirec_rec (curenv,nb as curenvnb) pb opt (substn : subst0) ?(nargs=0) curm curn =
1095 let { subst_sigma = sigma; subst_metas = metasubst; subst_evars = evarsubst } = substn in
1096 let cM = Evarutil.whd_head_evar sigma curm
1097 and cN = Evarutil.whd_head_evar sigma curn in
1098 let () =
1099 debug_tactic_unification (fun () ->
1100 Termops.Internal.print_constr_env curenv sigma cM ++ strbrk" ~= " ++
1101 Termops.Internal.print_constr_env curenv sigma cN)
1102 in
1103 match (EConstr.kind sigma cM, EConstr.kind sigma cN) with
1104 | Meta k1, Meta k2 ->
1105 if Int.equal k1 k2 then substn else
1106 let stM,stN = extract_instance_status pb in
1107 let sigma =
1108 if opt.with_types && flags.check_applied_meta_types then
1109 let tyM = Meta.meta_type substn.subst_metam curenv sigma k1 in
1110 let tyN = Meta.meta_type substn.subst_metam curenv sigma k2 in
1111 let l, r = if k2 < k1 then tyN, tyM else tyM, tyN in
1112 check_compatibility curenv CUMUL flags substn l r
1113 else sigma
1114 in
1115 if k2 < k1 then push_metas sigma (k1, cN, stN) substn
1116 else push_metas sigma (k2, cM, stM) substn
1117 | Meta k, _
1118 when not (occur_metavariable sigma k cN) (* helps early trying alternatives *) ->
1119 let sigma =
1120 if opt.with_types && flags.check_applied_meta_types then
1121 (try
1122 let tyM = Meta.meta_type substn.subst_metam curenv sigma k in
1123 let tyN = get_type_of_with_metas ~metas:substn.subst_metam curenv ~lax:true sigma cN in
1124 check_compatibility curenv CUMUL flags substn tyN tyM
1125 with RetypeError _ ->
1126 (* Renounce, maybe metas/evars prevents typing *) sigma)
1127 else sigma
1128 in
1129 (* Here we check that [cN] does not contain any local variables *)
1130 if Int.equal nb 0 then
1131 push_metas sigma (k, cN, snd (extract_instance_status pb)) substn
1132 else if noccur_between sigma 1 nb cN then
1133 push_metas sigma
1134 (k, lift (-nb) cN, snd (extract_instance_status pb)) substn
1135 else error_cannot_unify_local curenv sigma (m,n,cN)
1136 | _, Meta k
1137 when not (occur_metavariable sigma k cM) (* helps early trying alternatives *) ->
1138 let sigma =
1139 if opt.with_types && flags.check_applied_meta_types then
1140 (try
1141 let tyM = get_type_of_with_metas ~metas:substn.subst_metam curenv ~lax:true sigma cM in
1142 let tyN = Meta.meta_type substn.subst_metam curenv sigma k in
1143 check_compatibility curenv CUMUL flags substn tyM tyN
1144 with RetypeError _ ->
1145 (* Renounce, maybe metas/evars prevents typing *) sigma)
1146 else sigma
1147 in
1148 (* Here we check that [cM] does not contain any local variables *)
1149 if Int.equal nb 0 then
1150 push_metas sigma (k, cM, fst (extract_instance_status pb)) substn
1151 else if noccur_between sigma 1 nb cM
1152 then
1153 push_metas sigma (k, lift (-nb) cM, fst (extract_instance_status pb)) substn
1154 else error_cannot_unify_local curenv sigma (m,n,cM)
1155 | Evar (evk,_ as ev), Evar (evk',_)
1156 when is_evar_allowed flags evk
1157 && Evar.equal evk evk' ->
1158 begin match constr_cmp pb env sigma flags cM cN with
1159 | Some sigma ->
1160 push_sigma sigma substn
1161 | None ->
1162 push_evars sigma (curenvnb, ev, cN) substn
1163 end
1164 | Evar (evk,_ as ev), _
1165 when is_evar_allowed flags evk
1166 && not (occur_evar sigma evk cN) ->
1167 let cmvars = free_rels sigma cM and cnvars = free_rels sigma cN in
1168 if Int.Set.subset cnvars cmvars then
1169 push_evars sigma (curenvnb, ev, cN) substn
1170 else error_cannot_unify_local curenv sigma (m,n,cN)
1171 | _, Evar (evk,_ as ev)
1172 when is_evar_allowed flags evk
1173 && not (occur_evar sigma evk cM) ->
1174 let cmvars = free_rels sigma cM and cnvars = free_rels sigma cN in
1175 if Int.Set.subset cmvars cnvars then
1176 push_evars sigma (curenvnb, ev, cM) substn
1177 else error_cannot_unify_local curenv sigma (m,n,cN)
1178 | Sort s1, Sort s2 ->
1179 (try
1180 let sigma' =
1181 if pb == CUMUL
1182 then Evd.set_leq_sort sigma s1 s2
1183 else Evd.set_eq_sort sigma s1 s2
1184 in push_sigma sigma' substn
1185 with e when CErrors.noncritical e ->
1186 error_cannot_unify curenv sigma (fst m,fst n))
1187
1188 | Lambda (na,t1,c1), Lambda (__,t2,c2) ->
1189 unirec_rec (push (na,t1) curenvnb) CONV {opt with at_top = true}
1190 (unirec_rec curenvnb CONV {opt with at_top = true; with_types = false} substn t1 t2) c1 c2
1191 | Prod (na,t1,c1), Prod (_,t2,c2) ->
1192 unirec_rec (push (na,t1) curenvnb) pb {opt with at_top = true}
1193 (unirec_rec curenvnb CONV {opt with at_top = true; with_types = false} substn t1 t2) c1 c2
1194 | LetIn (_,a,_,c), _ -> unirec_rec curenvnb pb opt substn (subst1 a c) cN
1195 | _, LetIn (_,a,_,c) -> unirec_rec curenvnb pb opt substn cM (subst1 a c)
1196
1197 (* Fast path for projections. *)
1198 | Proj (p1,_,c1), Proj (p2,_,c2) when Environ.QConstant.equal env
1199 (Projection.constant p1) (Projection.constant p2) ->
1200 (try unify_same_proj curenvnb CONV {opt with at_top = true}
1201 substn c1 c2
1202 with ex when precatchable_exception ex ->
1203 unify_not_same_head curenvnb pb opt substn ~nargs cM cN)
1204
1205 (* eta-expansion *)
1206 | Lambda (na,t1,c1), _ when flags.modulo_eta ->
1207 unirec_rec (push (na,t1) curenvnb) CONV {opt with at_top = true} substn
1208 c1 (mkApp (lift 1 cN,[|mkRel 1|]))
1209 | _, Lambda (na,t2,c2) when flags.modulo_eta ->
1210 unirec_rec (push (na,t2) curenvnb) CONV {opt with at_top = true} substn
1211 (mkApp (lift 1 cM,[|mkRel 1|])) c2
1212
1213 (* For records *)
1214 | App (f1, l1), _ when flags.modulo_eta &&
1215 (* This ensures cN is an evar, meta or irreducible constant/variable
1216 and not a constructor. *)
1217 is_eta_constructor_app curenv sigma flags.modulo_delta f1 l1 cN ->
1218 (try
1219 let opt' = {opt with at_top = true; with_cs = false} in
1220 let substn = check_type_eta_constructor_app curenvnb opt' substn cM cN in
1221 let sigma = substn.subst_sigma in
1222 let l1', l2' = eta_constructor_app curenv sigma f1 l1 cN in
1223 Array.fold_left2 (unirec_rec curenvnb CONV opt' ~nargs:0) substn l1' l2'
1224 with ex when precatchable_exception ex ->
1225 match EConstr.kind sigma cN with
1226 | App(f2,l2) when
1227 (isMeta sigma f2 && use_metas_pattern_unification sigma flags nb l2
1228 || use_evars_pattern_unification flags && isAllowedEvar sigma flags f2) ->
1229 unify_app_pattern false curenvnb pb opt substn cM f1 l1 cN f2 l2
1230 | _ -> raise ex)
1231
1232 | _, App (f2, l2) when flags.modulo_eta &&
1233 is_eta_constructor_app curenv sigma flags.modulo_delta f2 l2 cM ->
1234 (try
1235 let opt' = {opt with at_top = true; with_cs = false} in
1236 let substn = check_type_eta_constructor_app curenvnb opt' substn cN cM in
1237 let sigma = substn.subst_sigma in
1238 let l2', l1' = eta_constructor_app curenv sigma f2 l2 cM in
1239 Array.fold_left2 (unirec_rec curenvnb CONV opt' ~nargs:0) substn l1' l2'
1240 with ex when precatchable_exception ex ->
1241 match EConstr.kind sigma cM with
1242 | App(f1,l1) when
1243 (isMeta sigma f1 && use_metas_pattern_unification sigma flags nb l1
1244 || use_evars_pattern_unification flags && isAllowedEvar sigma flags f1) ->
1245 unify_app_pattern true curenvnb pb opt substn cM f1 l1 cN f2 l2
1246 | _ -> raise ex)
1247
1248 | Case (ci1, u1, pms1, p1, iv1, c1, cl1), Case (ci2, u2, pms2, (p2,_), iv2, c2, cl2) ->
1249 (try
1250 let () = if not (QInd.equal curenv ci1.ci_ind ci2.ci_ind) then error_cannot_unify curenv sigma (cM,cN) in
1251 let opt' = {opt with at_top = true; with_types = false} in
1252 let substn = Array.fold_left2 (unirec_rec curenvnb CONV ~nargs:0 opt') substn pms1 pms2 in
1253 let (ci1, _, _, (p1,_), _, c1, cl1) = EConstr.annotate_case env sigma (ci1, u1, pms1, p1, iv1, c1, cl1) in
1254 let unif opt substn (ctx1, c1) (_, c2) =
1255 let curenvnb' = List.fold_right (fun decl (env, n) -> push_rel decl env, n + 1) ctx1 curenvnb in
1256 unirec_rec curenvnb' CONV opt' substn c1 c2
1257 in
1258 let substn = unif opt' substn p1 p2 in
1259 let substn = unirec_rec curenvnb CONV opt' substn c1 c2 in
1260 Array.fold_left2 (unif {opt with at_top = true}) substn cl1 cl2
1261 with ex when precatchable_exception ex ->
1262 reduce curenvnb pb opt substn cM cN)
1263
1264 | Fix ((ln1,i1),(lna1,tl1,bl1)), Fix ((ln2,i2),(_,tl2,bl2)) when
1265 Int.equal i1 i2 && Array.equal Int.equal ln1 ln2 ->
1266 (try
1267 let opt' = {opt with at_top = true; with_types = false} in
1268 let curenvnb' = Array.fold_right2 (fun na t -> push (na,t)) lna1 tl1 curenvnb in
1269 Array.fold_left2 (unirec_rec curenvnb' CONV opt' ~nargs:0)
1270 (Array.fold_left2 (unirec_rec curenvnb CONV opt' ~nargs:0) substn tl1 tl2) bl1 bl2
1271 with ex when precatchable_exception ex ->
1272 reduce curenvnb pb opt substn cM cN)
1273
1274 | CoFix (i1,(lna1,tl1,bl1)), CoFix (i2,(_,tl2,bl2)) when
1275 Int.equal i1 i2 ->
1276 (try
1277 let opt' = {opt with at_top = true; with_types = false} in
1278 let curenvnb' = Array.fold_right2 (fun na t -> push (na,t)) lna1 tl1 curenvnb in
1279 Array.fold_left2 (unirec_rec curenvnb' CONV opt' ~nargs:0)
1280 (Array.fold_left2 (unirec_rec curenvnb CONV opt' ~nargs:0) substn tl1 tl2) bl1 bl2
1281 with ex when precatchable_exception ex ->
1282 reduce curenvnb pb opt substn cM cN)
1283
1284 | App (f1,l1), _ when
1285 (isMeta sigma f1 && use_metas_pattern_unification sigma flags nb l1
1286 || use_evars_pattern_unification flags && isAllowedEvar sigma flags f1) ->
1287 unify_app_pattern true curenvnb pb opt substn cM f1 l1 cN cN [||]
1288
1289 | _, App (f2,l2) when
1290 (isMeta sigma f2 && use_metas_pattern_unification sigma flags nb l2
1291 || use_evars_pattern_unification flags && isAllowedEvar sigma flags f2) ->
1292 unify_app_pattern false curenvnb pb opt substn cM cM [||] cN f2 l2
1293
1294 | App (f1,l1), App (f2,l2) ->
1295 unify_app curenvnb pb opt substn cM f1 l1 cN f2 l2
1296
1297 | App (f1,l1), Proj(p2,_,c2) ->
1298 unify_app curenvnb pb opt substn cM f1 l1 cN cN [||]
1299
1300 | Proj (p1,_,c1), App(f2,l2) ->
1301 unify_app curenvnb pb opt substn cM cM [||] cN f2 l2
1302
1303 | _ ->
1304 unify_not_same_head curenvnb pb opt substn ~nargs cM cN
1305
1306 and check_type_eta_constructor_app (env,nb as curenvnb) opt (substn : subst0) other term =
1307 let sigma = substn.subst_sigma in
1308 let metas = substn.subst_metam in
1309 let (((_, i as ind), j), u) =
1310 EConstr.destConstruct sigma (fst (decompose_app sigma other))
1311 in
1312 (* ensure that we only eta expand if we are at the same inductive
1313 (we accept that univs params and indices may be different) *)
1314 let fail () =
1315 error_cannot_unify env sigma (other, term)
1316 in
1317 let tterm = try get_type_of_with_metas ~metas ~lax:true env sigma term
1318 with RetypeError _ -> fail ()
1319 in
1320 let tterm' = Reductionops.whd_all ~metas:(Meta.meta_handler metas) env sigma tterm in
1321 match EConstr.kind sigma (fst (decompose_app sigma tterm')) with
1322 | Ind (ind',_) when QInd.equal env ind ind' -> substn
1323 | _ ->
1324 let tother = try get_type_of_with_metas ~metas ~lax:true env sigma other
1325 with RetypeError _ ->
1326 fail ()
1327 in
1328 unirec_rec curenvnb CONV opt ~nargs:0 substn tother tterm
1329
1330 and unify_app_pattern dir curenvnb pb opt substn cM f1 l1 cN f2 l2 =
1331 let sigma = substn.subst_sigma in
1332 let f, l, t = if dir then f1, l1, cN else f2, l2, cM in
1333 match is_unification_pattern curenvnb sigma f (Array.to_list l) t with
1334 | None ->
1335 (match EConstr.kind sigma t with
1336 | App (f',l') ->
1337 if dir then unify_app curenvnb pb opt substn cM f1 l1 t f' l'
1338 else unify_app curenvnb pb opt substn t f' l' cN f2 l2
1339 | Proj _ -> unify_app curenvnb pb opt substn cM f1 l1 cN f2 l2
1340 | _ ->
1341 (* XXX nargs could be better? *)
1342 unify_not_same_head curenvnb pb opt substn ~nargs:0 cM cN)
1343 | Some l ->
1344 solve_pattern_eqn_array curenvnb f l t substn
1345
1346 and unify_app (curenv, nb as curenvnb) pb opt (substn : subst0) cM f1 l1 cN f2 l2 =
1347 let sigma = substn.subst_sigma in
1348 try
1349 let needs_expansion p c' =
1350 match EConstr.kind sigma c' with
1351 | Meta _ -> true
1352 | Evar _ -> true
1353 | Const (c, u) -> Environ.QConstant.equal env c (Projection.constant p)
1354 | _ -> false
1355 in
1356 let expand_proj c c' l =
1357 match EConstr.kind sigma c with
1358 | Proj (p, _, t) when not (Projection.unfolded p) && needs_expansion p c' ->
1359 (try destApp sigma (expand_projection_with_metas ~metas:substn.subst_metam curenv sigma p t (Array.to_list l))
1360 with RetypeError _ -> (* Unification can be called on ill-typed terms, due
1361 to FO and eta in particular, fail gracefully in that case *)
1362 (c, l))
1363 | _ -> (c, l)
1364 in
1365 let f1, l1 = expand_proj f1 f2 l1 in
1366 let f2, l2 = expand_proj f2 f1 l2 in
1367 let opta = {opt with at_top = true; with_types = false} in
1368 let optf = {opt with at_top = true; with_types = true} in
1369 let (f1,l1,f2,l2) = adjust_app_array_size f1 l1 f2 l2 in
1370 if Array.length l1 == 0 then error_cannot_unify (fst curenvnb) sigma (cM,cN)
1371 else
1372 Array.fold_left2 (unirec_rec curenvnb CONV opta ~nargs:0)
1373 (unirec_rec curenvnb pb optf substn f1 f2 ~nargs:(Array.length l1)) l1 l2
1374 with ex when precatchable_exception ex ->
1375 try reduce curenvnb pb {opt with with_types = false} substn cM cN
1376 with ex when precatchable_exception ex ->
1377 try canonical_projections curenvnb pb opt cM cN substn
1378 with ex when precatchable_exception ex ->
1379 expand curenvnb pb {opt with with_types = false} substn cM f1 l1 cN f2 l2
1380
1381 and unify_same_proj (curenv, nb as curenvnb) cv_pb opt substn c1 c2 =
1382 let substn = unirec_rec curenvnb CONV opt substn c1 c2 in
1383 let metas = substn.subst_metam in
1384 try (* Force unification of the types to fill in parameters *)
1385 let ty1 = get_type_of_with_metas ~metas curenv ~lax:true substn.subst_sigma c1 in
1386 let ty2 = get_type_of_with_metas ~metas curenv ~lax:true substn.subst_sigma c2 in
1387 unify_0_with_initial_metas substn true curenv cv_pb
1388 { flags with modulo_conv_on_closed_terms = Some TransparentState.full;
1389 modulo_delta = TransparentState.full;
1390 modulo_eta = true;
1391 modulo_betaiota = true }
1392 (ty1, Unknown) (ty2, Unknown)
1393 with RetypeError _ -> substn
1394
1395 and unify_not_same_head curenvnb pb opt (substn : subst0) ~nargs cM cN =
1396 let sigma = substn.subst_sigma in
1397 try canonical_projections curenvnb pb opt cM cN substn
1398 with ex when precatchable_exception ex ->
1399 match constr_cmp pb env sigma flags ~nargs cM cN with
1400 | Some sigma -> push_sigma sigma substn
1401 | None ->
1402 try reduce curenvnb pb opt substn cM cN
1403 with ex when precatchable_exception ex ->
1404 let (f1,l1) =
1405 match EConstr.kind sigma cM with App (f,l) -> (f,l) | _ -> (cM,[||]) in
1406 let (f2,l2) =
1407 match EConstr.kind sigma cN with App (f,l) -> (f,l) | _ -> (cN,[||]) in
1408 expand curenvnb pb opt substn cM f1 l1 cN f2 l2
1409
1410 and reduce curenvnb pb opt substn cM cN =
1411 let sigma = substn.subst_sigma in
1412 let metas = substn.subst_metam in
1413 if flags.modulo_betaiota && not (subterm_restriction opt flags) then
1414 let cM' = do_reduce ~metas flags.modulo_delta curenvnb sigma cM in
1415 if not (EConstr.eq_constr sigma cM cM') then
1416 unirec_rec curenvnb pb opt substn cM' cN
1417 else
1418 let cN' = do_reduce ~metas flags.modulo_delta curenvnb sigma cN in
1419 if not (EConstr.eq_constr sigma cN cN') then
1420 unirec_rec curenvnb pb opt substn cM cN'
1421 else error_cannot_unify (fst curenvnb) sigma (cM,cN)
1422 else error_cannot_unify (fst curenvnb) sigma (cM,cN)
1423
1424 and expand (curenv,_ as curenvnb) pb opt (substn : subst0) cM f1 l1 cN f2 l2 =
1425 let sigma = substn.subst_sigma in
1426 let res =
1427 (* Try full conversion on meta-free terms. *)
1428 (* Back to 1995 (later on called trivial_unify in 2002), the
1429 heuristic was to apply conversion on meta-free (but not
1430 evar-free!) terms in all cases (i.e. for apply but also for
1431 auto and rewrite, even though auto and rewrite did not use
1432 modulo conversion in the rest of the unification
1433 algorithm). By compatibility we need to support this
1434 separately from the main unification algorithm *)
1435 (* The exploitation of known metas has been added in May 2007
1436 (it is used by apply and rewrite); it might now be redundant
1437 with the support for delta-expansion (which is used
1438 essentially for apply)... *)
1439 if subterm_restriction opt flags then None else
1440 match flags.modulo_conv_on_closed_terms with
1441 | None -> None
1442 | Some convflags ->
1443 let subst = mk_expand_subst substn in
1444 match subst_defined_metas_evars sigma subst cM with
1445 | None -> (* some undefined Metas in cM *) None
1446 | Some m1 ->
1447 match subst_defined_metas_evars sigma subst cN with
1448 | None -> (* some undefined Metas in cN *) None
1449 | Some n1 ->
1450 (* No subterm restriction there, too much incompatibilities
1451 don't care about universes from comparing the types
1452 *)
1453 let _ : UnivProblem.Set.t =
1454 if opt.with_types then
1455 try (* Ensure we call conversion on terms of the same type *)
1456 let tyM = get_type_of curenv ~lax:true sigma m1 in
1457 let tyN = get_type_of curenv ~lax:true sigma n1 in
1458 check_compatibility_ustate curenv CUMUL flags substn tyM tyN
1459 with RetypeError _ ->
1460 (* Renounce, maybe metas/evars prevents typing *) UnivProblem.Set.empty
1461 else UnivProblem.Set.empty
1462 in
1463 match infer_conv_ustate ~pb ~ts:convflags curenv sigma m1 n1 with
1464 | Some uprob ->
1465 begin match Evd.add_constraints sigma uprob with
1466 | sigma -> Some (push_sigma sigma substn)
1467 | exception (UGraph.UniverseInconsistency _ | UniversesDiffer) -> None
1468 end
1469 | None ->
1470 if is_ground_term sigma m1 && is_ground_term sigma n1 then
1471 error_cannot_unify curenv sigma (cM,cN)
1472 else None
1473 in
1474 match res with
1475 | Some substn -> substn
1476 | None ->
1477 let metas = substn.subst_metam in
1478 let cf1 = key_of curenv sigma opt flags f1 and cf2 = key_of curenv sigma opt flags f2 in
1479 match oracle_order curenv cf1 cf2 with
1480 | None -> error_cannot_unify curenv sigma (cM,cN)
1481 | Some true ->
1482 (match expand_key ~metas flags.modulo_delta curenv sigma l1 cf1 with
1483 | Some c_l1 ->
1484 let metas = Meta.meta_handler metas in
1485 unirec_rec curenvnb pb opt substn
1486 (whd_betaiotazeta ~metas curenv sigma (mkApp c_l1)) cN
1487 | None ->
1488 (match expand_key ~metas flags.modulo_delta curenv sigma l2 cf2 with
1489 | Some c_l2 ->
1490 let metas = Meta.meta_handler metas in
1491 unirec_rec curenvnb pb opt substn cM
1492 (whd_betaiotazeta ~metas curenv sigma (mkApp c_l2))
1493 | None ->
1494 error_cannot_unify curenv sigma (cM,cN)))
1495 | Some false ->
1496 (match expand_key ~metas flags.modulo_delta curenv sigma l2 cf2 with
1497 | Some c_l2 ->
1498 let metas = Meta.meta_handler metas in
1499 unirec_rec curenvnb pb opt substn cM
1500 (whd_betaiotazeta ~metas curenv sigma (mkApp c_l2))
1501 | None ->
1502 (match expand_key ~metas flags.modulo_delta curenv sigma l1 cf1 with
1503 | Some c_l1 ->
1504 let metas = Meta.meta_handler metas in
1505 unirec_rec curenvnb pb opt substn
1506 (whd_betaiotazeta ~metas curenv sigma (mkApp c_l1)) cN
1507 | None ->
1508 error_cannot_unify curenv sigma (cM,cN)))
1509
1510 and canonical_projections (curenv, _ as curenvnb) pb opt cM cN substn =
1511 let sigma = substn.subst_sigma in
1512 let metas = substn.subst_metam in
1513 let f1 () =
1514 if isApp_or_Proj sigma cM then
1515 if CanonicalSolution.is_open_canonical_projection ~metas:(Meta.meta_handler metas) curenv sigma cM then
1516 solve_canonical_projection curenvnb pb opt cM cN substn
1517 else error_cannot_unify (fst curenvnb) sigma (cM,cN)
1518 else error_cannot_unify (fst curenvnb) sigma (cM,cN)
1519 in
1520 if not opt.with_cs ||
1521 begin match flags.modulo_conv_on_closed_terms with
1522 | None -> true
1523 | Some _ -> subterm_restriction opt flags
1524 end then
1525 error_cannot_unify (fst curenvnb) sigma (cM,cN)
1526 else
1527 try f1 () with e when precatchable_exception e ->
1528 if isApp_or_Proj sigma cN then
1529 if CanonicalSolution.is_open_canonical_projection ~metas:(Meta.meta_handler metas) curenv sigma cN then
1530 solve_canonical_projection curenvnb pb opt cN cM substn
1531 else error_cannot_unify (fst curenvnb) sigma (cM,cN)
1532 else error_cannot_unify (fst curenvnb) sigma (cM,cN)
1533
1534 and solve_canonical_projection curenvnb pb opt cM cN substn =
1535 let sigma = substn.subst_sigma in
1536 let metas = substn.subst_metam in
1537 let f1l1 = whd_nored_state ~metas:(Meta.meta_handler metas) (fst curenvnb) sigma (cM,Stack.empty) in
1538 let f2l2 = whd_nored_state ~metas:(Meta.meta_handler metas) (fst curenvnb) sigma (cN,Stack.empty) in
1539 let metasfn substn mv = match Metamap.find mv substn.subst_metam with
1540 | Cltyp (_, b) -> Some b.rebus
1541 | Clval (_, _, b) -> Some b.rebus
1542 | exception Not_found -> None
1543 in
1544 let (sigma,t,c,bs,(params,params1),(us,us2),(ts,ts1),c1,(n,t2)) =
1545 try Evarconv.check_conv_record (fst curenvnb) sigma (Evarconv.decompose_proj ~metas:(metasfn substn) (fst curenvnb) sigma f1l1) f2l2
1546 with Not_found -> error_cannot_unify (fst curenvnb) sigma (cM,cN)
1547 in
1548 if Reductionops.Stack.compare_shape ts ts1 then
1549 let substn = push_sigma sigma substn in
1550 let (substn,ks,_,test) =
1551 List.fold_left
1552 (fun (substn,ks,m,test) b ->
1553 if match n with Some n -> Int.equal m n | None -> false then
1554 (* Enforce unification of type of the projected parameter and the projection's argument type *)
1555 let t2ty = Retyping.get_type_of ~metas:(metasfn substn) (fst curenvnb) sigma t2 in
1556 let test substn = unirec_rec curenvnb CUMUL opt substn t2ty (substl ks b) in
1557 (substn,t2::ks, m-1, test)
1558 else
1559 let mv = new_meta () in
1560 let metas = Meta.meta_declare mv (substl ks b) substn.subst_metam in
1561 ({ substn with subst_metam = metas }, mkMeta mv :: ks, m - 1, test))
1562 (substn,[],List.length bs, fun s -> s) bs
1563 in
1564 try
1565 let opt' = {opt with with_types = false} in
1566 let fold u1 u s = unirec_rec curenvnb pb opt' s u1 (substl ks u) in
1567 let foldl acc l1 l2 =
1568 try List.fold_right2 fold l1 l2 acc
1569 with Invalid_argument _ -> assert false (* check_conv_record ensures lengths coincide *)
1570 in
1571 let substn = foldl substn us2 us in
1572 let substn = match params1 with None -> substn | Some params1 -> foldl substn params1 params in
1573 let substn = Reductionops.Stack.fold2 (fun s u1 u2 -> unirec_rec curenvnb pb opt' s u1 u2) substn ts ts1 in
1574 let app = mkApp (c, Array.rev_of_list ks) in
1575 let substn = unirec_rec curenvnb pb opt' substn c1 app in
1576 let substn = test substn in
1577 unirec_rec curenvnb pb opt' substn (snd t) (fst (decompose_app substn.subst_sigma (substl ks (fst t))))
1578 with Reductionops.Stack.IncompatibleFold2 ->
1579 error_cannot_unify (fst curenvnb) sigma (cM,cN)
1580 else error_cannot_unify (fst curenvnb) sigma (cM,cN)
1581 in
1582
1583 let sigma = subst.subst_sigma in
1584 debug_tactic_unification (fun () ->
1585 str "Starting unification:" ++ spc() ++
1586 Termops.Internal.print_constr_env env sigma (fst m) ++ strbrk" ~= " ++
1587 Termops.Internal.print_constr_env env sigma (fst n));
1588
1589 let opt = { at_top = conv_at_top; with_types = false; with_cs = true } in
1590 try
1591 let res =
1592 if subterm_restriction opt flags ||
1593 fast_occur_meta_or_undefined_evar sigma m || fast_occur_meta_or_undefined_evar sigma n
1594 then
1595 None
1596 else
1597 let (m, _) = m in
1598 let (n, _) = n in
1599 let ans = match flags.modulo_conv_on_closed_terms with
1600 | Some convflags -> careful_infer_conv ~pb ~ts:convflags env sigma m n
1601 | _ -> constr_cmp pb env sigma flags m n in
1602 match ans with
1603 | Some sigma -> ans
1604 | None ->
1605 if (match flags.modulo_conv_on_closed_terms, flags.modulo_delta with
1606 | Some cv, dl ->
1607 let open TransparentState in
1608 Id.Pred.subset dl.tr_var cv.tr_var && Cpred.subset dl.tr_cst cv.tr_cst
1609 | None, dl -> TransparentState.is_empty dl)
1610 then error_cannot_unify env sigma (m, n) else None
1611 in
1612 let a = match res with
1613 | Some sigma -> push_sigma sigma subst
1614 | None -> unirec_rec (env,0) pb opt subst (fst m) (fst n) in
1615 debug_tactic_unification (fun () -> str "Leaving unification with success");
1616 a
1617 with e ->
1618 let e = Exninfo.capture e in
1619 debug_tactic_unification (fun () -> str "Leaving unification with failure");
1620 Exninfo.iraise e
1621
1622 let unify_0 ~metas env sigma pb flags c1 c2 =
1623 unify_0_with_initial_metas { subst_sigma = sigma; subst_metas = []; subst_evars = []; subst_metam = metas } true env pb flags (c1, Unknown) (c2, Unknown)
1624
1625 let left = true
1626 let right = false
1627
1628 let rec unify_with_eta ~metas keptside flags env sigma c1 c2 =
1629 (* Question: try whd_all on ci if not two lambdas? *)
1630 match EConstr.kind sigma c1, EConstr.kind sigma c2 with
1631 | (Lambda (na,t1,c1'), Lambda (_,t2,c2')) ->
1632 let env' = push_rel_assum (na,t1) env in
1633 let substn = unify_0 ~metas env sigma CONV flags t1 t2 in
1634 let { subst_sigma = sigma; subst_metas = metas; subst_evars = evars; subst_metam = metas0 } = substn in
1635 let side, { subst_sigma = sigma; subst_metas = metas'; subst_evars = evars'; subst_metam = metas0 } =
1636 unify_with_eta ~metas:metas0 keptside flags env' sigma c1' c2'
1637 in (side, { subst_sigma = sigma; subst_metas = metas@metas'; subst_evars = evars@evars'; subst_metam = metas0 })
1638 | (Lambda (na,t,c1'),_)->
1639 let env' = push_rel_assum (na,t) env in
1640 let side = left in (* expansion on the right: we keep the left side *)
1641 unify_with_eta ~metas side flags env' sigma
1642 c1' (mkApp (lift 1 c2,[|mkRel 1|]))
1643 | (_,Lambda (na,t,c2')) ->
1644 let env' = push_rel_assum (na,t) env in
1645 let side = right in (* expansion on the left: we keep the right side *)
1646 unify_with_eta ~metas side flags env' sigma
1647 (mkApp (lift 1 c1,[|mkRel 1|])) c2'
1648 | _ ->
1649 (keptside, unify_0 ~metas env sigma CONV flags c1 c2)
1650
1651 (* We solved problems [?n =_pb u] (i.e. [u =_(opp pb) ?n]) and [?n =_pb' u'],
1652 we now compute the problem on [u =? u'] and decide which of u or u' is kept
1653
1654 Rem: the upper constraint is lost in case u <= ?n <= u' (and symmetrically
1655 in the case u' <= ?n <= u)
1656 *)
1657
1658 let eq_instance_constraint (c1 : instance_constraint) c2 = c1 == c2
1659
1660 let merge_instances ~metas env sigma flags st1 st2 c1 c2 =
1661 match (opp_status st1, st2) with
1662 | (Conv, Conv) ->
1663 let side = left (* arbitrary choice, but agrees with compatibility *) in
1664 let (side,res) = unify_with_eta ~metas side flags env sigma c1 c2 in
1665 (side,Conv,res)
1666 | ((IsSubType | Conv as oppst1),
1667 (IsSubType | Conv)) ->
1668 let res = unify_0 ~metas env sigma CUMUL flags c2 c1 in
1669 if eq_instance_constraint oppst1 st2 then (* arbitrary choice *) (left, st1, res)
1670 else if eq_instance_constraint st2 IsSubType then (left, st1, res)
1671 else (right, st2, res)
1672 | ((IsSuperType | Conv as oppst1),
1673 (IsSuperType | Conv)) ->
1674 let res = unify_0 ~metas env sigma CUMUL flags c1 c2 in
1675 if eq_instance_constraint oppst1 st2 then (* arbitrary choice *) (left, st1, res)
1676 else if eq_instance_constraint st2 IsSuperType then (left, st1, res)
1677 else (right, st2, res)
1678 | (IsSuperType,IsSubType) ->
1679 (try (left, IsSubType, unify_0 ~metas env sigma CUMUL flags c2 c1)
1680 with e when CErrors.noncritical e ->
1681 (right, IsSubType, unify_0 ~metas env sigma CUMUL flags c1 c2))
1682 | (IsSubType,IsSuperType) ->
1683 (try (left, IsSuperType, unify_0 ~metas env sigma CUMUL flags c1 c2)
1684 with e when CErrors.noncritical e ->
1685 (right, IsSuperType, unify_0 ~metas env sigma CUMUL flags c2 c1))
1686
1687 (* Unification
1688 *
1689 * Procedure:
1690 * (1) The function [unify mc wc M N] produces two lists:
1691 * (a) a list of bindings Meta->RHS
1692 * (b) a list of bindings EVAR->RHS
1693 *
1694 * The Meta->RHS bindings cannot themselves contain
1695 * meta-vars, so they get applied eagerly to the other
1696 * bindings. This may or may not close off all RHSs of
1697 * the EVARs. For each EVAR whose RHS is closed off,
1698 * we can just apply it, and go on. For each which
1699 * is not closed off, we need to do a mimic step -
1700 * in general, we have something like:
1701 *
1702 * ?X == (c e1 e2 ... ei[Meta(k)] ... en)
1703 *
1704 * so we need to do a mimic step, converting ?X
1705 * into
1706 *
1707 * ?X -> (c ?z1 ... ?zn)
1708 *
1709 * of the proper types. Then, we can decompose the
1710 * equation into
1711 *
1712 * ?z1 --> e1
1713 * ...
1714 * ?zi --> ei[Meta(k)]
1715 * ...
1716 * ?zn --> en
1717 *
1718 * and keep on going. Whenever we find that a R.H.S.
1719 * is closed, we can, as before, apply the constraint
1720 * directly. Whenever we find an equation of the form:
1721 *
1722 * ?z -> Meta(n)
1723 *
1724 * we can reverse the equation, put it into our metavar
1725 * substitution, and keep going.
1726 *
1727 * The most efficient mimic possible is, for each
1728 * Meta-var remaining in the term, to declare a
1729 * new EVAR of the same type. This is supposedly
1730 * determinable from the clausale form context -
1731 * we look up the metavar, take its type there,
1732 * and apply the metavar substitution to it, to
1733 * close it off. But this might not always work,
1734 * since other metavars might also need to be resolved. *)
1735
1736 let applyHead ~metas env evd c cl =
1737 let rec apprec c cl cty evd =
1738 match cl with
1739 | [] -> (evd, c)
1740 | a::cl ->
1741 match EConstr.kind evd (whd_all ~metas:(Meta.meta_handler metas) env evd cty) with
1742 | Prod ({binder_name},c1,c2) ->
1743 let src =
1744 match EConstr.kind evd a with
1745 | Meta mv -> Meta.evar_source_of_meta mv metas
1746 | _ ->
1747 (* Does not matter, the evar will be later instantiated by [a] *)
1748 Loc.tag Evar_kinds.InternalHole in
1749 let typeclass_candidate = Typeclasses.is_maybe_class_type env evd c1 in
1750 let (evd,evar) = Evarutil.new_evar ~typeclass_candidate env evd ~src c1 in
1751 apprec (mkApp(c,[|evar|])) cl (subst1 evar c2) evd
1752 | _ -> user_err Pp.(str "Apply_Head_Then")
1753 in
1754 let evd, t = Typing.type_of env evd c in
1755 apprec c (Array.to_list cl) t evd
1756
1757 let is_mimick_head sigma ts f =
1758 match EConstr.kind sigma f with
1759 | Const (c,u) -> not (Structures.PrimitiveProjections.is_transparent_constant ts c)
1760 | Var id -> not (TransparentState.is_transparent_variable ts id)
1761 | (Rel _|Construct _|Ind _) -> true
1762 | _ -> false
1763
1764 let try_to_coerce ~metas env evd c cty tycon =
1765 let j = make_judge c cty in
1766 let (evd',j',_trace) = Coercion.inh_conv_coerce_rigid_to ~program_mode:false ~resolve_tc:true env evd j tycon in
1767 let evd' = Evarconv.solve_unif_constraints_with_heuristics env evd' in
1768 let metas = Meta.map_metas_fvalue (fun c -> nf_evar evd' c) metas in
1769 (evd', metas, j'.uj_val)
1770
1771 let w_coerce_to_type ~metas env evd c cty mvty =
1772 let evd, metas, tycon = pose_all_metas_as_evars ~metas env evd mvty in
1773 try try_to_coerce ~metas env evd c cty tycon
1774 with e when precatchable_exception e ->
1775 (* inh_conv_coerce_rigid_to should have reasoned modulo reduction
1776 but there are cases where it though it was not rigid (like in
1777 fst (nat,nat)) and stops while it could have seen that it is rigid *)
1778 let cty = Tacred.hnf_constr env evd cty in
1779 try_to_coerce ~metas env evd c cty tycon
1780
1781 let w_coerce ~metas env evd mv c =
1782 let cty = get_type_of env evd c in
1783 let mvty = Meta.meta_type metas env evd mv in
1784 w_coerce_to_type ~metas env evd c cty mvty
1785
1786 let nf_meta ~metas env sigma c =
1787 let freemetas = metavars_of c in
1788 if Metaset.is_empty freemetas then c else Meta.meta_instance metas env sigma c
1789
1790 let unify_to_type ~metas env sigma flags c status u =
1791 let sigma, c = refresh_universes ~status:Evd.univ_flexible ~onlyalg:true (Some false) env sigma c in
1792 let t = get_type_of_with_metas ~metas env sigma (nf_meta ~metas env sigma c) in
1793 let t = nf_betaiota env sigma (nf_meta ~metas env sigma t) in
1794 unify_0 ~metas env sigma CUMUL flags t u
1795
1796 let unify_type ~metas env sigma flags mv status c =
1797 let mvty = Meta.meta_type metas env sigma mv in
1798 let mvty = nf_meta ~metas env sigma mvty in
1799 unify_to_type ~metas env sigma
1800 (set_flags_for_type flags)
1801 c status mvty
1802
1803 (* Move metas that may need coercion at the end of the list of instances *)
1804
1805 let order_metas metas =
1806 let rec order latemetas = function
1807 | [] -> List.rev latemetas
1808 | (_,_,(_,CoerceToType) as meta)::metas ->
1809 order (meta::latemetas) metas
1810 | (_,_,(_,_) as meta)::metas ->
1811 meta :: order latemetas metas
1812 in order [] metas
1813
1814 (* Solve an equation ?n[x1=u1..xn=un] = t where ?n is an evar *)
1815
1816 let solve_simple_evar_eqn flags env evd ev rhs =
1817 match solve_simple_eqn Evarconv.evar_unify flags env evd (None,ev,rhs) with
1818 | UnifFailure (evd,reason) ->
1819 error_cannot_unify env evd ~reason (mkEvar ev,rhs);
1820 | Success evd -> evd
1821
1822 (* [w_merge env sigma b metas evars] merges common instances in metas
1823 or in evars, possibly generating new unification problems; if [b]
1824 is true, unification of types of metas is required *)
1825
1826 let w_merge env with_types flags (substn : subst0) =
1827 let eflags = Evarconv.default_flags_of flags.modulo_delta_types in
1828 let rec w_merge_rec metas0 evd metas evars eqns =
1829
1830 (* Process evars *)
1831 match evars with
1832 | ((curenv,nb),(evk,_ as ev),rhs)::evars' ->
1833 if Evd.is_defined evd evk then
1834 let v = mkEvar ev in
1835 let { subst_sigma = evd; subst_metas = metas'; subst_evars = evars''; subst_metam = metas0 } =
1836 unify_0 ~metas:metas0 curenv evd CONV flags rhs v in
1837 w_merge_rec metas0 evd (metas'@metas) (evars''@evars') eqns
1838 else begin
1839 (* This can make rhs' ill-typed if metas are *)
1840 let rhs' = subst_meta_instances evd metas rhs in
1841 match EConstr.kind evd rhs with
1842 | App (f,cl) when occur_meta evd rhs' ->
1843 if occur_evar evd evk rhs' then
1844 error_occur_check curenv evd evk rhs';
1845 if is_mimick_head evd flags.modulo_delta f then
1846 let metas0, evd' = mimick_undefined_evar metas0 evd flags f cl evk in
1847 w_merge_rec metas0 evd' metas evars eqns
1848 else
1849 let metas0, evd' =
1850 let env' = pop_rel_context nb curenv in
1851 let evd', metas0, rhs'' = pose_all_metas_as_evars ~metas:metas0 env' evd rhs' in
1852 try metas0, solve_simple_evar_eqn eflags curenv evd' ev rhs''
1853 with Retyping.RetypeError _ ->
1854 error_cannot_unify curenv evd' (mkEvar ev,rhs'')
1855 in
1856 w_merge_rec metas0 evd' metas evars' eqns
1857 | _ ->
1858 let evd', metas0, rhs'' = pose_all_metas_as_evars ~metas:metas0 env evd rhs' in
1859 let evd' =
1860 try solve_simple_evar_eqn eflags curenv evd' ev rhs''
1861 with Retyping.RetypeError _ -> error_cannot_unify curenv evd' (mkEvar ev, rhs'')
1862 in
1863 w_merge_rec metas0 evd' metas evars' eqns
1864 end
1865 | [] ->
1866
1867 (* Process metas *)
1868 match metas with
1869 | (mv,c,(status,to_type))::metas ->
1870 let ((evd,metas0,c),(metas'',evars'')),eqns =
1871 if with_types && to_type != TypeProcessed then
1872 begin match to_type with
1873 | CoerceToType ->
1874 (* Some coercion may have to be inserted *)
1875 (w_coerce ~metas:metas0 env evd mv c,([],[])),eqns
1876 | _ ->
1877 (* No coercion needed: delay the unification of types *)
1878 ((evd,metas0,c),([],[])),(mv,status,c)::eqns
1879 end
1880 else
1881 ((evd,metas0,c),([],[])),eqns
1882 in
1883 begin match Meta.meta_opt_fvalue0 metas0 mv with
1884 | Some ({ rebus = c' }, (status', _)) ->
1885 let (take_left, st, { subst_sigma = evd; subst_metas = metas'; subst_evars = evars'; subst_metam = metas0 }) =
1886 merge_instances ~metas:metas0 env evd flags status' status c' c
1887 in
1888 let metas0 =
1889 if take_left then metas0
1890 else Meta.meta_reassign mv (c,(st,TypeProcessed)) metas0
1891 in
1892 w_merge_rec metas0 evd (metas'@metas@metas'') (evars'@evars'') eqns
1893 | None ->
1894 let evd', metas0 =
1895 if occur_meta_evd ~metas:metas0 evd mv c then
1896 let metas = Meta.meta_handler metas0 in
1897 if isMetaOf evd mv (whd_all ~metas env evd c) then evd, metas0
1898 else error_cannot_unify env evd (mkMeta mv,c)
1899 else
1900 Meta.meta_assign0 mv (c,(status,TypeProcessed)) metas0 evd
1901 in
1902 w_merge_rec metas0 evd' (metas''@metas) evars'' eqns
1903 end
1904 | [] ->
1905 (* Process type eqns *)
1906 let rec process_eqns failures = function
1907 | (mv,status,c)::eqns ->
1908 (match (try Inl (unify_type ~metas:metas0 env evd flags mv status c)
1909 with e when CErrors.noncritical e -> Inr e)
1910 with
1911 | Inr e -> process_eqns (((mv,status,c),e)::failures) eqns
1912 | Inl { subst_sigma = evd; subst_metas = metas; subst_evars = evars; subst_metam = metas0 } ->
1913 w_merge_rec metas0 evd metas evars (List.map fst failures @ eqns))
1914 | [] ->
1915 (match failures with
1916 | [] -> metas0, evd
1917 | ((mv,status,c),e)::_ -> raise e)
1918 in process_eqns [] eqns
1919
1920 and mimick_undefined_evar metas0 evd flags hdc args sp =
1921 let ev = Evd.find_undefined evd sp in
1922 let sp_env = reset_with_named_context (evar_filtered_hyps ev) env in
1923 let (evd', c) = applyHead ~metas:metas0 sp_env evd hdc args in
1924 let { subst_sigma = evd''; subst_metas = mc; subst_evars = ec; subst_metam = metas0 } =
1925 unify_0 ~metas:metas0 sp_env evd' CUMUL flags
1926 (get_type_of sp_env evd' c) (Evd.evar_concl ev) in
1927 let metas0, evd''' = w_merge_rec metas0 evd'' mc ec [] in
1928 if evd' == evd''' (* FIXME ? *)
1929 then metas0, Evd.define sp c evd'''
1930 else metas0, Evd.define sp (Evarutil.nf_evar evd''' c) evd'''
1931
1932 in
1933
1934 let check_types ~metas evd =
1935 let eqns = Metamap.fold (fun mv b acc ->
1936 match b with
1937 | Clval (n, (t, (c, TypeNotProcessed)), v) -> (mv, c, t.rebus) :: acc
1938 | _ -> acc) metas []
1939 in w_merge_rec metas evd [] [] (List.rev eqns)
1940 in
1941 let { subst_sigma = evd; subst_metas = metas; subst_evars = evars; subst_metam = metas0 } = substn in
1942 let metas0, res = (* merge constraints *)
1943 w_merge_rec metas0 evd (order_metas metas)
1944 (* Assign evars in the order of assignments during unification *)
1945 (List.rev evars) []
1946 in
1947 if with_types then check_types ~metas:metas0 res else metas0, res
1948
1949 let w_unify_meta_types ~metas env ?(flags=default_unify_flags ()) evd =
1950 let metas, metas0 = Meta.retract_coercible_metas metas in
1951 w_merge env true flags.merge_unify_flags { subst_sigma = evd; subst_metas = metas; subst_evars = []; subst_metam = metas0 }
1952
1953 (* [w_unify env evd M N]
1954 performs a unification of M and N, generating a bunch of
1955 unification constraints in the process. These constraints
1956 are processed, one-by-one - they may either generate new
1957 bindings, or, if there is already a binding, new unifications,
1958 which themselves generate new constraints. This continues
1959 until we get failure, or we run out of constraints.
1960 [clenv_typed_unify M N clenv] expects in addition that expected
1961 types of metavars are unifiable with the types of their instances *)
1962
1963 let head_app ~metas env sigma m =
1964 let metas = Meta.meta_handler metas in
1965 fst (whd_nored_state ~metas env sigma (m, Stack.empty))
1966
1967 let isEvar_or_Meta sigma c = match EConstr.kind sigma c with
1968 | Evar _ | Meta _ -> true
1969 | _ -> false
1970
1971 let check_types env flags subst m n =
1972 let sigma = subst.subst_sigma in
1973 let metas = subst.subst_metam in
1974 if isEvar_or_Meta sigma (head_app ~metas env sigma m) then
1975 unify_0_with_initial_metas subst true env CUMUL
1976 flags
1977 (get_type_of_with_metas ~metas env sigma n, Unknown)
1978 (get_type_of_with_metas ~metas env sigma m, Unknown)
1979 else if isEvar_or_Meta sigma (head_app ~metas env sigma n) then
1980 unify_0_with_initial_metas subst true env CUMUL
1981 flags
1982 (get_type_of_with_metas ~metas env sigma m, Unknown)
1983 (get_type_of_with_metas ~metas env sigma n, Unknown)
1984 else subst
1985
1986 let try_resolve_typeclasses env evd flag m n =
1987 if flag then
1988 Typeclasses.resolve_typeclasses ~filter:Typeclasses.no_goals ~fail:true env evd
1989 else evd
1990
1991 let w_unify_core_0 ~metas env evd with_types cv_pb flags m n =
1992 let (mc1, metas0) = Meta.retract_coercible_metas metas in
1993 let substn = check_types env (set_flags_for_type flags.core_unify_flags) { subst_sigma = evd; subst_metas = mc1; subst_evars = []; subst_metam = metas0 } (fst m) (fst n) in
1994 let subst2 =
1995 unify_0_with_initial_metas substn false env cv_pb
1996 flags.core_unify_flags m n
1997 in
1998 let metas, evd = w_merge env with_types flags.merge_unify_flags subst2 in
1999 metas, try_resolve_typeclasses env evd flags.resolve_evars m n
2000
2001 let w_typed_unify ~metas env evd = w_unify_core_0 ~metas env evd true
2002
2003 let w_typed_unify_array ~metas env evd flags f1 l1 f2 l2 =
2004 let f1,l1,f2,l2 = adjust_app_array_size f1 l1 f2 l2 in
2005 let (mc1, metas0) = Meta.retract_coercible_metas metas in
2006 let fold_subst subst m n = unify_0_with_initial_metas subst true env CONV flags.core_unify_flags (m, Unknown) (n, Unknown) in
2007 let subst = fold_subst { subst_sigma = evd; subst_metas = []; subst_evars = []; subst_metam = metas0 } f1 f2 in
2008 let subst = Array.fold_left2 fold_subst subst l1 l2 in
2009 let metas, evd = w_merge env true flags.merge_unify_flags subst in
2010 metas, try_resolve_typeclasses env evd flags.resolve_evars
2011 (mkApp(f1,l1)) (mkApp(f2,l2))
2012
2013 (* make_abstraction: a variant of w_unify_to_subterm which works on
2014 contexts, with evars, and possibly with occurrences *)
2015
2016 let indirectly_dependent sigma c d decls =
2017 not (isVar sigma c) &&
2018 (* This test is not needed if the original term is a variable, but
2019 it is needed otherwise, as e.g. when abstracting over "2" in
2020 "forall H:0=2, H=H:>(0=1+1) -> 0=2." where there is now obvious
2021 way to see that the second hypothesis depends indirectly over 2 *)
2022 let open Context.Named.Declaration in
2023 List.exists (fun d' -> exists (fun c -> Termops.local_occur_var sigma (NamedDecl.get_id d') c) d) decls
2024
2025 let default_matching_core_flags sigma =
2026 let ts = TransparentState.full in {
2027 modulo_conv_on_closed_terms = Some TransparentState.empty;
2028 use_metas_eagerly_in_conv_on_closed_terms = false;
2029 use_evars_eagerly_in_conv_on_closed_terms = false;
2030 modulo_delta = TransparentState.empty;
2031 modulo_delta_types = ts;
2032 check_applied_meta_types = true;
2033 use_pattern_unification = false;
2034 use_meta_bound_pattern_unification = false;
2035 allowed_evars = allow_new_evars sigma;
2036 restrict_conv_on_strict_subterms = false;
2037 modulo_betaiota = false;
2038 modulo_eta = false;
2039 }
2040
2041 let default_matching_merge_flags sigma =
2042 let ts = TransparentState.full in
2043 let flags = default_matching_core_flags sigma in {
2044 flags with
2045 modulo_conv_on_closed_terms = Some ts;
2046 modulo_delta = ts;
2047 modulo_betaiota = true;
2048 modulo_eta = true;
2049 use_pattern_unification = true;
2050 }
2051
2052 let default_matching_flags sigma =
2053 let flags = default_matching_core_flags sigma in {
2054 core_unify_flags = flags;
2055 merge_unify_flags = default_matching_merge_flags sigma;
2056 subterm_unify_flags = flags; (* does not matter *)
2057 resolve_evars = false;
2058 allow_K_in_toplevel_higher_order_unification = false;
2059 }
2060
2061 (* This supports search of occurrences of term from a pattern *)
2062 (* from_prefix is useful e.g. for subterms in an inductive type: we can say *)
2063 (* "destruct t" and it finds "t u" *)
2064
2065 exception PatternNotFound
2066
2067 let make_pattern_test from_prefix_of_ind is_correct_type env sigma (pending,c) =
2068 let flags =
2069 if from_prefix_of_ind then
2070 let flags = default_matching_flags (Option.default Evd.empty pending) in
2071 { flags with core_unify_flags = { flags.core_unify_flags with
2072 modulo_conv_on_closed_terms = Some TransparentState.full;
2073 restrict_conv_on_strict_subterms = true } }
2074 else default_matching_flags (Option.default Evd.empty pending) in
2075 let n = Array.length (snd (decompose_app sigma c)) in
2076 let cgnd = if occur_meta_or_undefined_evar sigma c then NotGround else Ground in
2077 let exception NotUnifiable in
2078 let matching_fun k _ t =
2079 (* make_pattern_test is only ever called with an empty rel context *)
2080 if 0 < k && not (EConstr.Vars.closed0 sigma t) then Result.Error ()
2081 else try
2082 let t',l2 =
2083 if from_prefix_of_ind then
2084 (* We check for fully applied subterms of the form "u u1 .. un" *)
2085 (* of inductive type knowing only a prefix "u u1 .. ui" *)
2086 let t,l = decompose_app_list sigma t in
2087 let l1,l2 =
2088 try List.chop n l with Failure _ -> raise NotUnifiable in
2089 if not (List.for_all (fun c -> Vars.closed0 sigma c) l2) then raise NotUnifiable
2090 else applist (t,l1), l2
2091 else t, [] in
2092 let metas = Metamap.empty in (* FIXME ? *)
2093 let _metas, sigma = w_typed_unify ~metas env sigma Conversion.CONV flags (c, cgnd) (t', Unknown) in
2094 let ty = Retyping.get_type_of env sigma t in
2095 if is_correct_type ty then Result.Ok (sigma, t, l2)
2096 else Result.Error ()
2097 with
2098 | PretypeError (_,_,CannotUnify (c1,c2,Some e)) ->
2099 Result.Error ()
2100 | NotUnifiable -> Result.Error ()
2101 (* MS: This is pretty bad, it catches Not_found for example *)
2102 | e when CErrors.noncritical e -> Result.Error ()
2103 in
2104 let merge_fun c1 c2 = match c2 with
2105 | Some (evd, c2, _) ->
2106 let (_, c1, x) = c1 in
2107 begin match infer_conv ~pb:CONV env evd c1 c2 with
2108 | Some evd ->
2109 let t1 = get_type_of env evd c1 in
2110 let t2 = get_type_of env evd c2 in
2111 begin match infer_conv ~pb:CONV env evd t1 t2 with
2112 | Some evd -> Result.Ok (Some (evd, c1, x))
2113 | None -> Result.Error ()
2114 end
2115 | None -> Result.Error ()
2116 end
2117 | None -> Result.Ok (Some c1)
2118 in
2119 { match_fun = matching_fun; merge_fun = merge_fun;
2120 testing_state = None; last_found = None },
2121 (fun test -> match test.testing_state with
2122 | None -> None
2123 | Some (sigma,_,l) ->
2124 let metas = Metamap.empty in (* FIXME ? *)
2125 let rec strong_whd_meta t = EConstr.map sigma strong_whd_meta (whd_meta ~metas sigma t) in
2126 let c = applist (strong_whd_meta c, l) in
2127 Some (sigma, c))
2128
2129 let make_eq_test env evd c =
2130 let out cstr =
2131 match cstr.last_found with None -> None | _ -> Some (cstr.testing_state, c)
2132 in
2133 (make_eq_univs_test env evd c, out)
2134
2135 let get_rigid_evars sigma c =
2136 let rec aux vars c = match EConstr.kind sigma c with
2137 | Var id -> Id.Set.add id vars
2138 | Evar _ -> vars (* do not take evar instances into account *)
2139 | _ -> EConstr.fold sigma aux vars c in
2140 aux Id.Set.empty c
2141
2142 let make_abstraction_core name (test,out) env sigma c ty occs check_occs concl =
2143 let id =
2144 let t = match ty with Some t -> t | None -> get_type_of env sigma c in
2145 let x = id_of_name_using_hdchar env sigma t name in
2146 let ids = Environ.ids_of_named_context_val (named_context_val env) in
2147 if name == Anonymous then next_ident_away_in_goal env x ids else
2148 if mem_named_context_val x (named_context_val env) then
2149 user_err
2150 (str "The variable " ++ Id.print x ++ str " is already declared.")
2151 else
2152 x
2153 in
2154 let likefirst = clause_with_generic_occurrences occs in
2155 let mkvarid () = EConstr.mkVar id in
2156 let compute_dependency _ d (remvars,sign,depdecls) =
2157 let d = EConstr.of_named_decl d in
2158 let hyp = NamedDecl.get_id d in
2159 if Id.Set.is_empty remvars then
2160 match occurrences_of_hyp hyp occs with
2161 | NoOccurrences, InHyp ->
2162 (remvars,push_named_context_val d sign,depdecls)
2163 | (AllOccurrences | AtLeastOneOccurrence), InHyp as occ ->
2164 let occ = if likefirst then LikeFirst else AtOccs occ in
2165 let newdecl = replace_term_occ_decl_modulo env sigma occ test mkvarid d in
2166 if Context.Named.Declaration.equal (ERelevance.equal sigma) (EConstr.eq_constr sigma) d newdecl
2167 && not (indirectly_dependent sigma c d depdecls)
2168 then
2169 if check_occs && not (in_every_hyp occs)
2170 then raise (PretypeError (env,sigma,NoOccurrenceFound (c,Some hyp)))
2171 else (remvars,push_named_context_val d sign, depdecls)
2172 else
2173 (remvars,push_named_context_val newdecl sign, newdecl :: depdecls)
2174 | occ ->
2175 (* There are specific occurrences, hence not like first *)
2176 let newdecl = replace_term_occ_decl_modulo env sigma (AtOccs occ) test mkvarid d in
2177 (remvars,push_named_context_val newdecl sign, newdecl :: depdecls)
2178 else
2179 (* Skip declarations if all rigid variables have not been introduced *)
2180 let remvars = Id.Set.remove hyp remvars in
2181 (remvars,push_named_context_val d sign,depdecls)
2182 in
2183 let vars = get_rigid_evars sigma c in
2184 try
2185 let _,sign,depdecls =
2186 fold_named_context compute_dependency env
2187 ~init:(vars,empty_named_context_val,[]) in
2188 let ccl = match occurrences_of_goal occs with
2189 | NoOccurrences -> concl
2190 | occ ->
2191 let occ = if likefirst then LikeFirst else AtOccs occ in
2192 replace_term_occ_modulo env sigma occ test mkvarid concl
2193 in
2194 let lastlhyp =
2195 if List.is_empty depdecls then None else Some (NamedDecl.get_id (List.last depdecls)) in
2196 let res = match out test with
2197 | None -> None
2198 | Some (sigma, c) -> Some (sigma,c)
2199 in
2200 (id,sign,depdecls,lastlhyp,ccl,res)
2201 with
2202 SubtermUnificationError e ->
2203 raise (PretypeError (env,sigma,CannotUnifyOccurrences e))
2204
2205 (** [make_abstraction] is the main entry point to abstract over a term
2206 or pattern at some occurrences; it returns:
2207 - the id used for the abstraction
2208 - the type of the abstraction
2209 - the declarations from the context which depend on the term or pattern
2210 - the most recent hyp before which there is no dependency in the term of pattern
2211 - the abstracted conclusion
2212 - an evar universe context effect to apply on the goal
2213 - the term or pattern to abstract fully instantiated
2214 *)
2215
2216 type prefix_of_inductive_support_flag = bool
2217
2218 type abstraction_request =
2219 | AbstractPattern of prefix_of_inductive_support_flag * (types -> bool) * Name.t * (evar_map option * constr) * clause
2220 | AbstractExact of Name.t * constr * types option * clause * bool
2221
2222 type 'r abstraction_result =
2223 Names.Id.t * named_context_val *
2224 named_declaration list * Names.Id.t option *
2225 types * (evar_map * constr) option
2226
2227 let make_abstraction env evd ccl abs =
2228 match abs with
2229 | AbstractPattern (from_prefix,check,name,c,occs) ->
2230 make_abstraction_core name
2231 (make_pattern_test from_prefix check env evd c)
2232 env evd (snd c) None occs false ccl
2233 | AbstractExact (name,c,ty,occs,check_occs) ->
2234 make_abstraction_core name
2235 (make_eq_test env evd c)
2236 env evd c ty occs check_occs ccl
2237
2238 let keyed_unify env evd kop =
2239 if not (is_keyed_unification ()) then fun cl -> true
2240 else
2241 match kop with
2242 | None -> fun _ -> true
2243 | Some kop ->
2244 fun cl ->
2245 let kc = Keys.constr_key env (fun c -> EConstr.kind evd c) cl in
2246 match kc with
2247 | None -> false
2248 | Some kc -> Keys.equiv_keys kop kc
2249
2250 type 'aconstr akind =
2251 | AApp of 'aconstr * 'aconstr array
2252 | ACast of 'aconstr (* only the main term *)
2253 | AOther of 'aconstr array
2254
2255 module AConstr :
2256 sig
2257 type t
2258 val proj : t -> EConstr.t
2259 val make : evar_map -> EConstr.t -> t
2260 val kind : t -> t akind
2261 val mkApp : t * t array -> t
2262 val closed0 : t -> bool
2263 end =
2264 struct
2265
2266 type t = {
2267 proj : EConstr.t;
2268 self : t akind;
2269 data : int;
2270 }
2271
2272 let proj c = c.proj
2273
2274 let closed0 c = Int.equal c.data 0
2275
2276 let max (i : int) (j : int) = if i < j then j else i
2277 let max_array f a = Array.fold_left (fun n v -> max (f v) n) 0 a
2278 let lift (i : int) = if Int.equal i 0 then 0 else i - 1
2279 let liftn k (i : int) = if i < k then 0 else i - k
2280
2281 let data v = v.data
2282
2283 let kind v = v.self
2284
2285 let mkApp (c, al) =
2286 if Array.is_empty al then c
2287 else match kind c with
2288 | AApp (c0, al0) ->
2289 { proj = mkApp (c.proj, Array.map proj al); self = AApp (c0, Array.append al0 al); data = max c.data (max_array data al) }
2290 | _ ->
2291 { proj = mkApp (c.proj, Array.map proj al); self = AApp (c, al); data = max c.data (max_array data al) }
2292
2293 let get_max_rel sigma c =
2294 let rec aux n accu c = match EConstr.kind sigma c with
2295 | Rel i -> if i <= n then accu else max accu (i - n)
2296 | _ -> EConstr.fold_with_binders sigma succ aux n accu c
2297 in
2298 aux 0 0 c
2299
2300 let get_max_rel_array sigma v = Array.fold_left (fun accu c -> max accu (get_max_rel sigma c)) 0 v
2301
2302 let anorec = AOther [||]
2303
2304 let rec make sigma c0 = match EConstr.kind sigma c0 with
2305 | (Meta _ | Var _ | Sort _ | Const _ | Ind _ | Construct _ | Int _ | Float _ | String _) ->
2306 { proj = c0; self = anorec; data = 0 }
2307 | Rel n ->
2308 { proj = c0; self = anorec; data = n }
2309 | Cast (c, k, t) ->
2310 let c = make sigma c in
2311 (* unification doesn't recurse in the type *)
2312 let td = get_max_rel sigma t in
2313 { proj = c0; self = ACast c; data = max c.data td }
2314 | Lambda (na, t, c) | Prod (na, t, c) ->
2315 let t = make sigma t in
2316 let c = make sigma c in
2317 { proj = c0; self = AOther [|t; c|]; data = max t.data (lift c.data) }
2318 | LetIn (na, b, t, c) ->
2319 let b = make sigma b in
2320 (* unification doesn't recurse in the type *)
2321 let td = get_max_rel sigma t in
2322 let c = make sigma c in
2323 { proj = c0; self = AOther [|b; c|]; data = max b.data (max td (lift c.data)) }
2324 | App (c, al) ->
2325 let c = make sigma c in
2326 let ald, al = make_array sigma al in
2327 { proj = c0; self = AApp (c, al); data = max c.data ald }
2328 | Proj (p, _, t) ->
2329 let t = make sigma t in
2330 { proj = c0; self = AOther [|t|]; data = t.data }
2331 | Evar (e, al) ->
2332 (* Unification doesn't recurse on the subterms in evar instances *)
2333 let data = SList.Skip.fold (fun accu v -> max accu (get_max_rel sigma v)) 0 al in
2334 { proj = c0; self = AOther [||]; data }
2335 | Case (ci, u, pms, (p,_), iv, c, bl) ->
2336 let pmsd = get_max_rel_array sigma pms in
2337 let pd =
2338 let (nas, p) = p in
2339 let pd = get_max_rel sigma p in
2340 liftn (Array.length nas) pd
2341 in
2342 let ivd = match iv with
2343 | NoInvert -> 0
2344 | CaseInvert { indices } -> get_max_rel_array sigma indices
2345 in
2346 let c = make sigma c in
2347 let fold accu (nas, p) =
2348 let p = make sigma p in
2349 max accu (liftn (Array.length nas) p.data), p
2350 in
2351 let bld, bl = Array.fold_left_map fold 0 bl in
2352 let data = max pmsd @@ max pd @@ max ivd @@ max c.data bld in
2353 (* Unification only recurses on the discriminee and the branches *)
2354 { proj = c0; self = AOther (Array.append [|c|] bl); data }
2355 | Fix (_, (_, tl, bl)) | CoFix(_,(_,tl,bl)) ->
2356 let tld, tl = make_array sigma tl in
2357 let bld, bl = make_array sigma bl in
2358 let data = max tld (liftn (Array.length tl) bld) in
2359 { proj = c0; self = AOther (Array.append tl bl); data }
2360 | Array(u,t,def,ty) ->
2361 let td, t = make_array sigma t in
2362 let def = make sigma def in
2363 let ty = make sigma ty in
2364 let data = max td (max def.data ty.data) in
2365 { proj = c0; self = AOther (Array.append [|def;ty|] t); data }
2366
2367 and make_array sigma v =
2368 let fold accu c =
2369 let c = make sigma c in
2370 max accu c.data, c
2371 in
2372 Array.fold_left_map fold 0 v
2373
2374 end
2375
2376 type head_kind =
2377 | HeadSort
2378 | HeadProd
2379 | HeadInd
2380 | HeadOther
2381
2382 let get_head_kind ~metas env sigma c =
2383 let ty = get_type_of_with_metas ~metas env sigma c in
2384 let hd, _ = decompose_app sigma ty in
2385 match EConstr.kind sigma hd with
2386 | Prod _ -> HeadProd
2387 | Sort _ -> HeadSort
2388 | Ind _ -> HeadInd
2389 | _ ->
2390 (* We try again after reduction, this may be a bit expensive but it also
2391 reduces the subterm search space later on *)
2392 let metas = Meta.meta_handler metas in
2393 let ty = whd_all ~metas env sigma ty in
2394 let hd, _ = decompose_app sigma ty in
2395 match EConstr.kind sigma hd with
2396 | Prod _ -> HeadProd
2397 | Sort _ -> HeadSort
2398 | Ind _ -> HeadInd
2399 | _ -> HeadOther
2400
2401 (* can c have a type of the same shape as knd? *)
2402 let fast_head_check sigma knd c = match EConstr.kind sigma c, knd with
2403 | Lambda _, (HeadInd | HeadSort) -> false
2404 | Sort _, (HeadInd | HeadProd) -> false
2405 | Construct _, HeadSort -> false
2406 | Prod _, (HeadInd | HeadProd) -> false
2407 | Ind _, HeadInd -> false
2408 | App (hd, _), _ ->
2409 begin match EConstr.kind sigma hd, knd with
2410 | Construct _, HeadSort -> false
2411 | Ind _, HeadInd -> false
2412 | _ -> true
2413 end
2414 | _ -> true
2415
2416 (* Tries to find an instance of term [cl] in term [op].
2417 Unifies [cl] to every subterm of [op] until it finds a match.
2418 Fails if no match is found *)
2419 let w_unify_to_subterm ~metas env evd ?(flags=default_unify_flags ()) (op,cl) =
2420 let bestexn = ref None in
2421 let kop = Keys.constr_key env (fun c -> EConstr.kind evd c) op in
2422 let opgnd = if occur_meta_or_undefined_evar evd op then NotGround else Ground in
2423 let knd = get_head_kind ~metas env evd op in
2424 let rec matchrec cl =
2425 let rec strip_outer_cast c = match AConstr.kind c with
2426 | ACast c -> strip_outer_cast c
2427 | _ -> c
2428 in
2429 let cl = strip_outer_cast cl in
2430 let ans =
2431 let is_closed = AConstr.closed0 cl in
2432 let cl = AConstr.proj cl in
2433 if is_closed && not (isEvar evd cl) && keyed_unify env evd kop cl && fast_head_check evd knd cl then
2434 try
2435 if is_keyed_unification () then
2436 let f1, l1 = decompose_app evd op in
2437 let f2, l2 = decompose_app evd cl in
2438 Some (w_typed_unify_array ~metas env evd flags f1 l1 f2 l2, cl)
2439 else
2440 Some (w_typed_unify ~metas env evd CONV flags (op, opgnd) (cl, Unknown), cl)
2441 with ex when precatchable_exception ex ->
2442 let () = if Pretype_errors.unsatisfiable_exception ex then bestexn := Some ex in
2443 None
2444 else
2445 None
2446 in
2447 match ans with
2448 | Some _ as ans -> ans
2449 | None ->
2450 match AConstr.kind cl with
2451 | ACast _ -> assert false (* just got stripped *)
2452 | AApp (f, args) ->
2453 begin match knd with
2454 | HeadInd | HeadSort ->
2455 (* If an application matches, then assuming well-typedness no longer application could match *)
2456 begin match matchrec f with
2457 | Some _ as ans -> ans
2458 | None -> matchrec_array 0 args
2459 end
2460 | HeadProd | HeadOther ->
2461 let n = Array.length args in
2462 let () = assert (n > 0) in
2463 let c1 = AConstr.mkApp (f,Array.sub args 0 (n-1)) in
2464 let c2 = args.(n-1) in
2465 begin match matchrec c1 with
2466 | Some _ as ans -> ans
2467 | None -> matchrec c2
2468 end
2469 end
2470 | AOther a -> matchrec_array 0 a
2471 and matchrec_array i args =
2472 if Array.length args <= i then None
2473 else match matchrec args.(i) with
2474 | Some _ as ans -> ans
2475 | None -> matchrec_array (i + 1) args
2476 in
2477 match matchrec cl with
2478 | Some ans -> ans
2479 | None ->
2480 match !bestexn with
2481 | None -> raise (PretypeError (env,evd,NoOccurrenceFound (op, None)))
2482 | Some e -> raise e
2483
2484 (* Tries to find all instances of term [cl] in term [op].
2485 Unifies [cl] to every subterm of [op] and return all the matches.
2486 Fails if no match is found *)
2487 let w_unify_to_subterm_all ~metas env evd ?(flags=default_unify_flags ()) (op,cl) =
2488 let return a b =
2489 let ((metas, evd), c as a) = a () in
2490 if List.exists (fun ((metas', evd'), c') -> EConstr.eq_constr evd' c c') b then b else a :: b
2491 in
2492 let fail str _ = user_err (Pp.str str) in
2493 let bind f g a =
2494 let a1 = try f a
2495 with ex
2496 when precatchable_exception ex -> a
2497 in try g a1
2498 with ex
2499 when precatchable_exception ex -> a1
2500 in
2501 let bind_iter f a =
2502 let n = Array.length a in
2503 let rec ffail i =
2504 if Int.equal i n then fun a -> a
2505 else bind (f a.(i)) (ffail (i+1))
2506 in ffail 0
2507 in
2508 let opgnd = if occur_meta_or_undefined_evar evd op then NotGround else Ground in
2509 let rec matchrec cl =
2510 let cl = strip_outer_cast evd cl in
2511 (bind
2512 (if closed0 evd cl
2513 then return (fun () -> w_typed_unify ~metas env evd CONV flags (op, opgnd) (cl, Unknown),cl)
2514 else fail "Bound 1")
2515 (match EConstr.kind evd cl with
2516 | App (f,args) ->
2517 let n = Array.length args in
2518 assert (n>0);
2519 let c1 = mkApp (f,Array.sub args 0 (n-1)) in
2520 let c2 = args.(n-1) in
2521 bind (matchrec c1) (matchrec c2)
2522
2523 | Case(_,_,_,_,_,c,lf) -> (* does not search in the predicate *)
2524 bind (matchrec c) (bind_iter matchrec (Array.map snd lf))
2525
2526 | Proj (p,_,c) -> matchrec c
2527
2528 | LetIn(_,c1,_,c2) ->
2529 bind (matchrec c1) (matchrec c2)
2530
2531 | Fix(_,(_,types,terms)) ->
2532 bind (bind_iter matchrec types) (bind_iter matchrec terms)
2533
2534 | CoFix(_,(_,types,terms)) ->
2535 bind (bind_iter matchrec types) (bind_iter matchrec terms)
2536
2537 | Prod (_,t,c) ->
2538 bind (matchrec t) (matchrec c)
2539
2540 | Lambda (_,t,c) ->
2541 bind (matchrec t) (matchrec c)
2542
2543 | Array(_u,t,def,ty) ->
2544 bind (bind (bind_iter matchrec t) (matchrec def)) (matchrec ty)
2545
2546 | Cast (_, _, _) -> fail "Match_subterm" (* Is this expected? *)
2547
2548 | Rel _ | Var _ | Meta _ | Evar _ | Sort _ | Const _ | Ind _
2549 | Construct _ | Int _ | Float _ | String _ -> fail "Match_subterm"))
2550
2551 in
2552 let res = matchrec cl [] in
2553 match res with
2554 | [] ->
2555 raise (PretypeError (env,evd,NoOccurrenceFound (op, None)))
2556 | _ ->
2557 List.map fst res
2558
2559 let w_unify_to_subterm_list ~metas env evd flags hdmeta oplist t =
2560 List.fold_right
2561 (fun op (metas,evd,l) ->
2562 let op = whd_meta ~metas evd op in
2563 if isMeta evd op then
2564 if flags.allow_K_in_toplevel_higher_order_unification then (metas,evd,op::l)
2565 else
2566 let hdname = Meta.meta_name metas hdmeta in
2567 let argname = Meta.meta_name metas (destMeta evd op) in
2568 error_abstraction_over_meta env evd hdname argname
2569 else
2570 let allow_K = flags.allow_K_in_toplevel_higher_order_unification in
2571 let flags =
2572 if is_keyed_unification () || occur_meta_or_existential evd op then
2573 (* This is up to delta for subterms w/o metas ... *)
2574 flags
2575 else
2576 (* up to Nov 2014, unification was bypassed on evar/meta-free terms;
2577 now it is called in a minimalistic way, at least to possibly
2578 unify pre-existing non frozen evars of the goal or of the
2579 pattern *)
2580 set_no_delta_flags flags in
2581 let t' = (strip_outer_cast evd op, AConstr.make evd t) in
2582 let ((metas', evd'), cl) =
2583 try
2584 if is_keyed_unification () then
2585 try (* First try finding a subterm w/o conversion on open terms *)
2586 let flags = set_no_delta_open_flags flags in
2587 w_unify_to_subterm ~metas env evd ~flags t'
2588 with e when CErrors.noncritical e ->
2589 (* If this fails, try with full conversion *)
2590 w_unify_to_subterm ~metas env evd ~flags t'
2591 else w_unify_to_subterm ~metas env evd ~flags t'
2592 with PretypeError (env,_,NoOccurrenceFound _) when
2593 allow_K ||
2594 (* w_unify_to_subterm does not go through evars, so
2595 the next step, which was already in <= 8.4, is
2596 needed at least for compatibility of rewrite *)
2597 dependent evd op t -> ((metas, evd), op)
2598 in
2599 if not allow_K &&
2600 (* ensure we found a different instance *)
2601 List.exists (fun op -> EConstr.eq_constr evd' op cl) l
2602 then
2603 let hdname = Meta.meta_name metas' hdmeta in
2604 error_non_linear_unification env evd hdname cl
2605 else (metas',evd',cl::l))
2606 oplist
2607 (metas,evd,[])
2608
2609 let w_unify_to_subterm env sigma ?flags (c, t) =
2610 w_unify_to_subterm env sigma ?flags (c, AConstr.make sigma t)
2611
2612 let secondOrderAbstraction ~metas env evd flags typ (p, oplist) =
2613 (* Remove delta when looking for a subterm *)
2614 let flags = { flags with core_unify_flags = flags.subterm_unify_flags } in
2615 let (metas,evd',cllist) = w_unify_to_subterm_list ~metas env evd flags p oplist typ in
2616 let typp = Meta.meta_type metas env evd' p in
2617 let evd',(pred,predtyp) = abstract_list_all env evd' typp typ cllist in
2618 match infer_conv ~pb:CUMUL env evd' predtyp typp with
2619 | None ->
2620 error_wrong_abstraction_type env evd'
2621 (Meta.meta_name metas p) pred typp predtyp;
2622 | Some evd' ->
2623 w_merge env false flags.merge_unify_flags
2624 { subst_sigma = evd'; subst_metas = [p,pred,(Conv,TypeProcessed)]; subst_evars = []; subst_metam = metas }
2625
2626 let secondOrderDependentAbstraction ~metas env evd flags typ (p, oplist) =
2627 let typp = Meta.meta_type metas env evd p in
2628 let evd, pred = abstract_list_all_with_dependencies env evd typp typ oplist in
2629 w_merge env false flags.merge_unify_flags
2630 { subst_sigma = evd; subst_metas = [p,pred,(Conv,TypeProcessed)]; subst_evars = []; subst_metam = metas }
2631
2632
2633 let secondOrderAbstractionAlgo dep =
2634 if dep then secondOrderDependentAbstraction else secondOrderAbstraction
2635
2636 let w_unify2 ~metas env evd flags dep cv_pb ty1 ty2 =
2637 let c1, oplist1 = whd_nored_stack ~metas:(Meta.meta_handler metas) env evd ty1 in
2638 let c2, oplist2 = whd_nored_stack ~metas:(Meta.meta_handler metas) env evd ty2 in
2639 match EConstr.kind evd c1, EConstr.kind evd c2 with
2640 | Meta p1, _ ->
2641 (* Find the predicate *)
2642 secondOrderAbstractionAlgo dep ~metas env evd flags ty2 (p1, oplist1)
2643 | _, Meta p2 ->
2644 (* Find the predicate *)
2645 secondOrderAbstractionAlgo dep ~metas env evd flags ty1 (p2, oplist2)
2646 | _ -> user_err Pp.(str "w_unify2")
2647
2648 (* The unique unification algorithm works like this: If the pattern is
2649 flexible, and the goal has a lambda-abstraction at the head, then
2650 we do a first-order unification.
2651
2652 If the pattern is not flexible, then we do a first-order
2653 unification, too.
2654
2655 If the pattern is flexible, and the goal doesn't have a
2656 lambda-abstraction head, then we second-order unification. *)
2657
2658 (* We decide here if first-order or second-order unif is used for Apply *)
2659 (* We apply a term of type (ai:Ai)C and try to solve a goal C' *)
2660 (* The type C is in clenv.templtyp.rebus with a lot of Meta to solve *)
2661
2662 (* 3-4-99 [HH] New fo/so choice heuristic :
2663 In case we have to unify (Meta(1) args) with ([x:A]t args')
2664 we first try second-order unification and if it fails first-order.
2665 Before, second-order was used if the type of Meta(1) and [x:A]t was
2666 convertible and first-order otherwise. But if failed if e.g. the type of
2667 Meta(1) had meta-variables in it. *)
2668 let w_unify ~metas env evd cv_pb ?(flags=default_unify_flags ()) ty1 ty2 =
2669 let hd1,l1 = decompose_app evd (whd_nored ~metas:(Meta.meta_handler metas) env evd ty1) in
2670 let hd2,l2 = decompose_app evd (whd_nored ~metas:(Meta.meta_handler metas) env evd ty2) in
2671 let is_empty1 = Array.is_empty l1 in
2672 let is_empty2 = Array.is_empty l2 in
2673 match EConstr.kind evd hd1, not is_empty1, EConstr.kind evd hd2, not is_empty2 with
2674 (* Pattern case *)
2675 | (Meta _, true, Lambda _, _ | Lambda _, _, Meta _, true)
2676 when Int.equal (Array.length l1) (Array.length l2) ->
2677 (try
2678 w_typed_unify_array ~metas env evd flags hd1 l1 hd2 l2
2679 with ex when precatchable_exception ex ->
2680 try
2681 w_unify2 ~metas env evd flags false cv_pb ty1 ty2
2682 with PretypeError (env,_,NoOccurrenceFound _) as e -> raise e)
2683
2684 (* Second order case *)
2685 | (Meta _, true, _, _ | _, _, Meta _, true) ->
2686 (try
2687 w_unify2 ~metas env evd flags false cv_pb ty1 ty2
2688 with PretypeError (env,_,NoOccurrenceFound _) as e -> raise e
2689 | ex when precatchable_exception ex ->
2690 try
2691 w_typed_unify_array ~metas env evd flags hd1 l1 hd2 l2
2692 with ex' when precatchable_exception ex' ->
2693 (* Last chance, use pattern-matching with typed
2694 dependencies (done late for compatibility) *)
2695 try
2696 w_unify2 ~metas env evd flags true cv_pb ty1 ty2
2697 with ex' when precatchable_exception ex' ->
2698 raise ex)
2699
2700 (* General case: try first order *)
2701 | _ -> w_typed_unify ~metas env evd cv_pb flags (ty1, Unknown) (ty2, Unknown)
2702
2703 let w_unify ?(metas = Metamap.empty) env evd cv_pb ?(flags=default_unify_flags ()) ty1 ty2 =
2704 w_unify ~metas env evd cv_pb ~flags ty1 ty2
2705
2706 let w_unify_to_subterm ?(metas = Metamap.empty) env evd ?flags arg =
2707 w_unify_to_subterm ~metas env evd ?flags arg
2708
2709 let w_unify_to_subterm_all ?(metas = Metamap.empty) env evd ?flags arg =
2710 w_unify_to_subterm_all ~metas env evd ?flags arg
2711
2712 let w_unify_meta_types ?(metas = Metamap.empty) env ?flags evd =
2713 w_unify_meta_types ~metas env ?flags evd
2714
2715 let w_coerce_to_type ?(metas = Metamap.empty) env evd c cty mvty =
2716 w_coerce_to_type ~metas env evd c cty mvty
2717
2718 let pose_all_metas_as_evars ~metas env evd ty =
2719 let metas, sigma, c = pose_all_metas_as_evars ~metas env evd ty in
2720 metas, sigma, c