Debian Codegraph @

proofs/clenv.ml

raw symbols SCIP
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * Copyright INRIA, CNRS and contributors *)
4 (* <O___,, * (see version control and CREDITS file for authors & dates) *)
5 (* \VV/ **************************************************************)
6 (* // * This file is distributed under the terms of the *)
7 (* * GNU Lesser General Public License Version 2.1 *)
8 (* * (see LICENSE file for the text of the license) *)
9 (************************************************************************)
10
11 open CErrors
12 open Util
13 open Names
14 open Nameops
15 open Termops
16 open Constr
17 open Context
18 open Environ
19 open Evd
20 open EConstr
21 open Vars
22 open Reductionops
23 open Tacred
24 open Pretype_errors
25 open Evarutil
26 open Unification
27 open Tactypes
28 open Logic
29
30 (******************************************************************)
31 (* Clausal environments *)
32
33 type meta_arg = {
34 marg_meta : metavariable;
35 marg_chain : metavariable list option;
36 marg_dep : bool;
37 marg_templ : (rel_context * Univ.Level.t) option;
38 }
39 (* List of clenv meta arguments with the submetas of the clenv it has been
40 possibly chained with. We never need to chain more than two clenvs, so there
41 is no need to make the type recursive. *)
42
43 type clausenv = {
44 env : env;
45 evd : evar_map;
46 metam : Unification.Meta.t;
47 metas : meta_arg list;
48 templval : constr;
49 metaset : Metaset.t;
50 templtyp : (constr * Metaset.t);
51 }
52
53 let mk_clausenv env evd metam metas templval metaset templtyp = {
54 env; evd; metam; metas; templval; metaset; templtyp;
55 }
56
57 let merge_fsorts evd clenv =
58 let usubst = Evd.universe_subst evd in
59 (* Hackish check: the level is considered to be already fresh when it is not
60 part of the evarmap substitution. Other heuristics are more broken because
61 some parts of the UState API are not very clear about their invariants and
62 this is relied upon by e.g. Program. *)
63 let filter l = not (UnivFlex.mem l usubst) in
64 let fold accu marg = match marg.marg_templ with
65 | None -> accu
66 | Some (ctx, l) -> Univ.Level.Set.add l accu
67 in
68 let fsorts = List.fold_left fold Univ.Level.Set.empty clenv.metas in
69 let fsorts = Univ.Level.Set.filter filter fsorts in
70 let uctx = (fsorts, Univ.UnivConstraints.empty) in
71 Evd.merge_universe_context_set Evd.univ_flexible evd uctx
72
73 let update_clenv_evd clenv evd metam =
74 let evd = merge_fsorts evd clenv in
75 mk_clausenv clenv.env evd metam clenv.metas clenv.templval clenv.metaset clenv.templtyp
76
77 let strip_params env sigma c =
78 match EConstr.kind sigma c with
79 | App (f, args) ->
80 (match EConstr.kind sigma f with
81 | Const cst ->
82 (match Structures.PrimitiveProjections.find_opt_with_relevance cst with
83 | Some (p,r) ->
84 let p = Projection.make p false in
85 let npars = Projection.npars p in
86 if Array.length args > npars then
87 mkApp (mkProj (p, r, args.(npars)),
88 Array.sub args (npars+1) (Array.length args - (npars + 1)))
89 else c
90 | None -> c)
91 | _ -> c)
92 | _ -> c
93
94 let meta_handler sigma =
95 let meta_value mv = match Unification.Meta.meta_opt_fvalue sigma mv with
96 | None -> None
97 | Some b -> Some b.rebus
98 in
99 { Reductionops.meta_value }
100
101 let clenv_strip_proj_params clenv =
102 let templval = strip_params clenv.env clenv.evd clenv.templval in
103 mk_clausenv clenv.env clenv.evd clenv.metam clenv.metas templval clenv.metaset clenv.templtyp
104
105 let get_template env sigma c =
106 let (hd, args) = EConstr.decompose_app sigma c in
107 match EConstr.destRef sigma hd with
108 | ConstructRef (ind, i), u when Environ.template_polymorphic_ind ind env ->
109 let (mib, mip) = Inductive.lookup_mind_specif env ind in
110 let templ = match mib.Declarations.mind_template with
111 | None -> assert false
112 | Some t -> t.template_param_arguments
113 in
114 Some (ind, List.skipn_at_best (Array.length args) templ)
115 | _ -> None
116 | exception DestKO -> None
117
118 let get_type_of_with_metas ~metas env sigma c =
119 let metas n =
120 try Some (Unification.Meta.meta_ftype metas n).Unification.rebus
121 with Not_found -> None
122 in
123 Retyping.get_type_of ~metas env sigma c
124
125 let refresh_template_constraints ~metas env sigma ind c =
126 let mib = Environ.lookup_mind (fst ind) env in
127 let ctx = (Option.get mib.mind_template).template_context in
128 let cstrs0 = UVars.UContext.constraints @@ UVars.AbstractContext.repr ctx in
129 if PConstraints.is_empty cstrs0 then sigma
130 else
131 let _, allargs = decompose_app sigma c in
132 let map c = { uj_val = c; uj_type = get_type_of_with_metas ~metas env sigma c } in
133 let allargs = Array.map map allargs in
134 let sigma, univs = Typing.get_template_parameters env sigma ind allargs in
135 let cstrs, _, _ = Inductive.instantiate_template_universes mib univs in
136 Evd.add_univ_constraints sigma (PConstraints.univs cstrs)
137
138 let clenv_refresh env sigma ctx clenv =
139 match ctx with
140 | Some ctx ->
141 let (subst, ctx) = UnivGen.fresh_sort_context_instance ctx in
142 let emap c = Vars.subst_univs_level_constr subst c in
143 let sigma = Evd.merge_sort_context_set Evd.univ_flexible ~src:UState.Internal sigma ctx in
144 (* Only metas are mentioning the old universes. *)
145 mk_clausenv env sigma (Unification.Meta.map_metas emap clenv.metam) clenv.metas
146 (emap clenv.templval)
147 clenv.metaset
148 (emap (fst clenv.templtyp), snd clenv.templtyp)
149 | None ->
150 (* We also refresh template arguments. This assumes that callers of
151 {!clenv_refresh} use a freshly minted clenv, but this is the case as this
152 function is only used by auto-like tactics for hint refresh. *)
153 let fold (metas, sigma) marg = match marg.marg_templ with
154 | None -> (metas, sigma), marg
155 | Some (decls, _) ->
156 let sigma, s = Evd.new_univ_level_variable Evd.univ_flexible_alg sigma in
157 let t = it_mkProd_or_LetIn (mkType (Univ.Universe.make s)) decls in
158 let name = Meta.meta_name clenv.metam marg.marg_meta in
159 let metas = Meta.meta_declare marg.marg_meta t ~name metas in
160 (metas, sigma), { marg with marg_templ = Some (decls, s) }
161 in
162 let (metam, evd), metas = List.fold_left_map fold (clenv.metam, sigma) clenv.metas in
163 let evd = match get_template env sigma clenv.templval with
164 | None -> evd
165 | Some (ind, _) -> refresh_template_constraints ~metas:metam env evd ind clenv.templval
166 in
167 mk_clausenv env evd metam metas clenv.templval clenv.metaset clenv.templtyp
168
169 let clenv_evd ce = ce.evd
170 let clenv_arguments c = List.map (fun arg -> arg.marg_meta) c.metas
171 let clenv_meta_list c = c.metam
172
173 let clenv_meta_type ~metas env sigma mv =
174 let ty =
175 try Unification.Meta.meta_ftype metas mv
176 with Not_found -> anomaly Pp.(str "unknown meta ?" ++ str (Nameops.string_of_meta mv) ++ str ".") in
177 if Metaset.is_empty ty.freemetas then ty.rebus else Meta.meta_instance metas env sigma ty.rebus
178 let clenv_value clenv =
179 if Metaset.is_empty clenv.metaset then clenv.templval
180 else Meta.meta_instance clenv.metam clenv.env clenv.evd clenv.templval
181 let clenv_type clenv =
182 if Metaset.is_empty (snd clenv.templtyp) then fst clenv.templtyp
183 else Meta.meta_instance clenv.metam clenv.env clenv.evd (fst clenv.templtyp)
184
185 let clenv_push_prod cl =
186 let metas = meta_handler cl.metam in
187 let typ = whd_all ~metas cl.env (clenv_evd cl) (clenv_type cl) in
188 let rec clrec typ = match EConstr.kind cl.evd typ with
189 | Cast (t,_,_) -> clrec t
190 | Prod (na,t,u) ->
191 let mv = new_meta () in
192 let dep = not (noccurn (clenv_evd cl) 1 u) in
193 let na' = if dep then na.binder_name else Anonymous in
194 let e' = Meta.meta_declare mv t ~name:na' cl.metam in
195 let concl = if dep then subst1 (mkMeta mv) u else u in
196 let templval = applist (cl.templval, [mkMeta mv]) in
197 let metaset = Metaset.add mv cl.metaset in
198 let marg = {
199 marg_meta = mv;
200 marg_chain = None;
201 marg_dep = dep;
202 marg_templ = None; (* We could refresh here but probably not worth it *)
203 } in
204 Some (mv, dep, { templval; metaset;
205 templtyp = (concl, metavars_of concl);
206 evd = cl.evd;
207 metam = e';
208 env = cl.env;
209 metas = cl.metas @ [marg]; })
210 | _ -> None
211 in clrec typ
212
213 (* Instantiate the first [bound] products of [t] with metas (all products if
214 [bound] is [None]; unfold local defs *)
215
216 (** [clenv_environments sigma n t] returns [sigma',lmeta,ccl] where
217 [lmetas] is a list of metas to be applied to a proof of [t] so that
218 it produces the unification pattern [ccl]; [sigma'] is [sigma]
219 extended with [lmetas]; if [n] is defined, it limits the size of
220 the list even if [ccl] is still a product; otherwise, it stops when
221 [ccl] is not a product; example: if [t] is [forall x y, x=y -> y=x]
222 and [n] is [None], then [lmetas] is [Meta n1;Meta n2;Meta n3] and
223 [ccl] is [Meta n1=Meta n2]; if [n] is [Some 1], [lmetas] is [Meta n1]
224 and [ccl] is [forall y, Meta n1=y -> y=Meta n1] *)
225
226 let clenv_environments env sigma template bound t =
227 let open EConstr in
228 let open Vars in
229 let rec clrec templ sigma metam metas n t =
230 match n, EConstr.kind sigma t with
231 | (Some 0, _) -> (metam, sigma, List.rev metas, t)
232 | (n, Cast (t,_,_)) -> clrec templ sigma metam metas n t
233 | (n, Prod (na,t1,t2)) ->
234 let mv = new_meta () in
235 let dep = not (noccurn sigma 1 t2) in
236 let sigma, t1, templ, tmpl = match templ with
237 | [] -> sigma, t1, templ, None
238 | None :: templ -> sigma, t1, templ, None
239 | Some _ :: templ ->
240 let decls, _ = Reductionops.dest_arity env sigma t1 in
241 let sigma, s = Evd.new_univ_level_variable Evd.univ_flexible_alg sigma in
242 let t1 = EConstr.it_mkProd_or_LetIn (EConstr.mkType (Univ.Universe.make s)) decls in
243 sigma, t1, templ, Some (decls, s)
244 in
245 let metam = Meta.meta_declare mv t1 ~name:na.binder_name metam in
246 let t2 = if dep then (subst1 (mkMeta mv) t2) else t2 in
247 clrec templ sigma metam ((mv, dep, tmpl) :: metas) (Option.map ((+) (-1)) n) t2
248 | (n, LetIn (na,b,_,t)) -> clrec templ sigma metam metas n (subst1 b t)
249 | (n, _) -> (metam, sigma, List.rev metas, t)
250 in
251 clrec template sigma Meta.empty [] bound t
252
253 let mk_clenv_from_env env sigma n (c,cty) =
254 let evd = sigma in
255 let template = get_template env sigma c in
256 let template_args = match template with Some (_, args) -> args | None -> [] in
257 let (metas, evd, args, concl) = clenv_environments env evd template_args n cty in
258 let map (mv, _, _) = mkMeta mv in
259 let templval = mkApp (c, Array.map_of_list map args) in
260 let evd = match template with
261 | None -> evd
262 | Some (ind, _) -> refresh_template_constraints ~metas env evd ind templval
263 in
264 let metaset = Metaset.of_list (List.map pi1 args) in
265 let map (mv, dep, tmpl) = { marg_meta = mv; marg_chain = None; marg_dep = dep; marg_templ = tmpl } in
266 { templval; metaset;
267 templtyp = (concl, metavars_of concl);
268 metam = metas;
269 evd = evd;
270 env = env;
271 metas = List.map map args;
272 }
273
274 let mk_clenv_from env sigma c = mk_clenv_from_env env sigma None c
275 let mk_clenv_from_n env sigma n c = mk_clenv_from_env env sigma (Some n) c
276
277 (******************************************************************)
278
279 (* [mentions clenv mv0 mv1] is true if mv1 is defined and mentions
280 * mv0, or if one of the free vars on mv1's freelist mentions
281 * mv0 *)
282
283 let mentions sigma mv0 =
284 let rec menrec mv1 =
285 Int.equal mv0 mv1 ||
286 let mlist =
287 try match Meta.meta_opt_fvalue sigma mv1 with
288 | Some b -> b.freemetas
289 | None -> Metaset.empty
290 with Not_found -> Metaset.empty in
291 Metaset.exists menrec mlist
292 in menrec
293
294 let error_incompatible_inst sigma mv =
295 let na = Meta.meta_name sigma mv in
296 match na with
297 | Name id ->
298 user_err
299 Pp.(str "An incompatible instantiation has already been found for " ++
300 Id.print id)
301 | _ ->
302 anomaly ~label:"clenv_assign" (Pp.str "non dependent metavar already assigned.")
303
304 (* TODO: replace by clenv_unify (mkMeta mv) rhs ? *)
305 let clenv_assign ~metas env sigma mv rhs =
306 let rhs_metas = metavars_of rhs in
307 if Metaset.exists (mentions metas mv) rhs_metas then
308 user_err Pp.(str "clenv_assign: circularity in unification");
309 try
310 begin match Meta.meta_opt_fvalue metas mv with
311 | Some body ->
312 if not (EConstr.eq_constr sigma body.rebus rhs) then
313 error_incompatible_inst metas mv
314 else
315 sigma, metas
316 | None ->
317 Meta.meta_assign mv (rhs, Meta.TypeNotProcessed) metas sigma
318 end
319 with Not_found ->
320 user_err Pp.(str "clenv_assign: undefined meta")
321
322
323
324 (* [clenv_dependent hyps_only clenv]
325 * returns a list of the metavars which appear in the template of clenv,
326 * and which are dependent, This is computed by taking the metavars of the
327 * template in right-to-left order, and collecting the metavars which appear
328 * in their types, and adding in all the metavars appearing in the
329 * type of clenv.
330 * If [hyps_only] then metavariables occurring in the concl are _excluded_
331 * If [iter] is also set then all metavariables *recursively* occurring
332 * in the concl are _excluded_
333
334 Details of the strategies used for computing the set of unresolved
335 dependent metavariables
336
337 We typically have a clause of the form
338
339 lem(?T:Type,?T,?U:Type,?V:Type,?x:?T,?y:?U,?z:?V,?H:hyp(?x,?z)) :concl(?y,?z)
340
341 Then, we compute:
342 A = the set of all unresolved metas
343 C = the set of metas occurring in concl (here ?y, ?z)
344 C* = the recursive closure of C wrt types (here ?y, ?z, ?U, ?V)
345 D = the set of metas occurring in a type of meta (here ?x, ?T, ?z, ?U, ?V)
346 NL = the set of duplicated metas even if non dependent (here ?T)
347 (we make the assumption that duplicated metas have internal dependencies)
348
349 Then, for the "apply"-style tactic (hyps_only), missing metas are
350 A inter ((D minus C) union NL)
351
352 for the optimized "apply"-style tactic (taking in care, f_equal style
353 lemma, from 2/8/10, Coq > 8.3), missing metas are
354 A inter (( D minus C* ) union NL)
355
356 for the "elim"-style tactic, missing metas are
357 A inter (D union C union NL)
358
359 In any case, we respect the order given in A.
360 *)
361
362 let clenv_metas_in_type_of_meta ~metas env sigma mv =
363 let typ = Meta.meta_ftype metas mv in
364 let typ = if Metaset.is_empty typ.freemetas then typ.rebus else Meta.meta_instance metas env sigma typ.rebus in
365 metavars_of typ
366
367 let dependent_in_type_of_metas ~metas env sigma mvs =
368 List.fold_right
369 (fun mv -> Metaset.union (clenv_metas_in_type_of_meta ~metas env sigma mv))
370 mvs Metaset.empty
371
372 let dependent_closure ~metas env sigma mvs =
373 let rec aux mvs acc =
374 Metaset.fold
375 (fun mv deps ->
376 let metas_of_meta_type = clenv_metas_in_type_of_meta ~metas env sigma mv in
377 aux metas_of_meta_type (Metaset.union deps metas_of_meta_type))
378 mvs acc in
379 aux mvs mvs
380
381 let undefined_metas metas =
382 let fold n accu = match Unification.Meta.meta_opt_fvalue metas n with
383 | Some _ -> accu
384 | None -> n :: accu
385 in
386 let m = Unification.Meta.fold fold metas [] in
387 List.sort Int.compare m
388
389 let clenv_dependent_gen hyps_only ?(iter=true) ~metas env sigma concl =
390 let all_undefined = undefined_metas metas in
391 let deps_in_concl = metavars_of concl in
392 let deps_in_hyps = dependent_in_type_of_metas ~metas env sigma all_undefined in
393 let deps_in_concl =
394 if hyps_only && iter then dependent_closure ~metas env sigma deps_in_concl
395 else deps_in_concl in
396 List.filter
397 (fun mv ->
398 if hyps_only then
399 Metaset.mem mv deps_in_hyps && not (Metaset.mem mv deps_in_concl)
400 else
401 Metaset.mem mv deps_in_hyps || Metaset.mem mv deps_in_concl)
402 all_undefined
403
404 let clenv_missing ce =
405 let miss = clenv_dependent_gen ~metas:ce.metam true ce.env ce.evd (clenv_type ce) in
406 let miss = List.map (Unification.Meta.meta_name ce.metam) miss in
407 (miss, List.count (fun arg -> not arg.marg_dep) ce.metas)
408
409 (******************************************************************)
410
411 let rec subst_meta sigma s c =
412 match kind sigma c with
413 | Meta i -> (try Int.Map.find i s with Not_found -> c)
414 | _ -> EConstr.map sigma (subst_meta sigma s) c
415
416 let replace_clenv_metas env sigma clnv =
417 let module Metas = Unification.Meta in
418 let metam = clenv_meta_list clnv in
419 let sigma, metamap = List.fold_left (fun (sigma, metamap) mv ->
420 let tymeta = Metas.meta_ftype metam mv in
421 let ty = subst_meta sigma metamap tymeta.rebus in
422 let naming = match Metas.meta_name metam mv with
423 | Name na -> Namegen.IntroIdentifier na
424 | Anonymous -> Namegen.IntroAnonymous
425 in
426 let sigma, ev = Evarutil.new_evar ~naming env sigma ty in
427 sigma, Int.Map.add mv ev metamap)
428 (sigma, Int.Map.empty) (clenv_arguments clnv)
429 in
430 sigma, subst_meta sigma metamap
431
432 exception ClenvCannotUnify of env * evar_map * clausenv * econstr * econstr * unification_error option
433
434 let clenv_unify ?(flags=default_unify_flags ()) cv_pb t1 t2 clenv =
435 try
436 let metas = clenv.metam in
437 let metas, sigma = w_unify ~metas ~flags clenv.env clenv.evd cv_pb t1 t2 in
438 update_clenv_evd clenv sigma metas
439 with Pretype_errors.(PretypeError (env, sigma, CannotUnify (t1, t2, reason))) as exn ->
440 let _, info = Exninfo.capture exn in
441 Exninfo.iraise (ClenvCannotUnify (env, sigma, clenv, t1, t2, reason), info)
442
443
444 let clenv_unify_meta_types ?(flags=default_unify_flags ()) clenv =
445 try
446 let metas = clenv.metam in
447 let metas, sigma = w_unify_meta_types ~metas ~flags:flags clenv.env clenv.evd in
448 update_clenv_evd clenv sigma metas
449 with Pretype_errors.(PretypeError (env, sigma, CannotUnify (t1, t2, reason))) as exn ->
450 let _, info = Exninfo.capture exn in
451 Exninfo.iraise (ClenvCannotUnify (env, sigma, clenv, t1, t2, reason), info)
452
453 let clenv_unique_resolver ?(flags=default_unify_flags ()) clenv concl =
454 let metas = meta_handler clenv.metam in
455 let (hd, _) = decompose_app clenv.evd (whd_nored ~metas clenv.env clenv.evd (fst clenv.templtyp)) in
456 let clenv = if isMeta clenv.evd hd then clenv_unify_meta_types ~flags clenv else clenv in
457 clenv_unify CUMUL ~flags (clenv_type clenv) concl clenv
458
459 let adjust_meta_source ~metas evd mv = function
460 | loc,Evar_kinds.VarInstance id ->
461 let rec match_name c l =
462 match EConstr.kind evd c, l with
463 | Lambda ({binder_name=Name id},_,c), a::l when EConstr.eq_constr evd a (mkMeta mv) -> Some id
464 | Lambda (_,_,c), a::l -> match_name c l
465 | _ -> None in
466 (* This is very ad hoc code so that an evar inherits the name of the binder
467 in situations like "ex_intro (fun x => P) ?ev p" *)
468 let f mv' =
469 let t = Unification.Meta.meta_ftype metas mv' in
470 if Metaset.mem mv t.freemetas then
471 let f,l = decompose_app_list evd t.rebus in
472 match EConstr.kind evd f with
473 | Meta mv'' ->
474 (match Meta.meta_opt_fvalue metas mv'' with
475 | Some c -> match_name c.rebus l
476 | None -> None)
477 | _ -> None
478 else None in
479 let metas = List.rev @@ Unification.Meta.fold (fun mv accu -> mv :: accu) metas [] in
480 let id = Option.default id (List.find_map f metas) in
481 loc,Evar_kinds.VarInstance id
482 | src -> src
483
484 (* [clenv_pose_metas_as_evars clenv dep_mvs]
485 * For each dependent evar in the clause-env which does not have a value,
486 * pose a value for it by constructing a fresh evar. We do this in
487 * left-to-right order, so that every evar's type is always closed w.r.t.
488 * metas.
489
490 * Node added 14/4/08 [HH]: before this date, evars were collected in
491 clenv_dependent by collect_metas in the fold_constr order which is
492 (almost) the left-to-right order of dependencies in term. However,
493 due to K-redexes, collect_metas was sometimes missing some metas.
494 The call to collect_metas has been replaced by a call to
495 undefined_metas, but then the order was the one of definition of
496 the metas (numbers in increasing order) which is _not_ the
497 dependency order when a clenv_fchain occurs (because clenv_fchain
498 plugs a term with a list of consecutive metas in place of a - a priori -
499 arbitrary metavariable belonging to another sequence of consecutive metas:
500 e.g., clenv_fchain may plug (H ?1 ?2) at the position ?6 of
501 (nat_ind ?3 ?4 ?5 ?6), leading to a dependency order 3<4<5<1<2).
502 To ensure the dependency order, we check that the type of each meta
503 to pose is already meta-free, otherwise we postpone the transformation,
504 hoping that no cycle may happen.
505
506 Another approach could have been to use decimal numbers for metas so that
507 in the example above, (H ?1 ?2) would have been renumbered (H ?6.1 ?6.2)
508 then making the numeric order match the dependency order.
509 *)
510
511 let clenv_pose_metas_as_evars ~metas env sigma dep_mvs =
512 let rec fold metas sigma = function
513 | [] -> metas, sigma
514 | mv::mvs ->
515 let ty = clenv_meta_type ~metas env sigma mv in
516 (* Postpone the evar-ization if dependent on another meta *)
517 (* This assumes no cycle in the dependencies - is it correct ? *)
518 if occur_meta sigma ty then fold metas sigma (mvs@[mv])
519 else
520 let src = Meta.evar_source_of_meta mv metas in
521 let src = adjust_meta_source ~metas sigma mv src in
522 (* Add a name to the evar if the meta comes from a variable to make the
523 goal focusable. *)
524 let naming =
525 begin match src with
526 | _, Evar_kinds.VarInstance id when Evd.generate_goal_names() -> Namegen.IntroIdentifier id
527 | _ -> Namegen.IntroAnonymous
528 end in
529 let typeclass_candidate = Typeclasses.is_maybe_class_type env sigma ty in
530 let (sigma, evar) = new_evar ~typeclass_candidate env sigma ~src ~naming ty in
531 let sigma, metas = clenv_assign ~metas env sigma mv evar in
532 fold metas sigma mvs in
533 fold metas sigma dep_mvs
534
535 (******************************************************************)
536
537 (* [clenv_fchain mv clenv clenv']
538 *
539 * Resolves the value of "mv" (which must be undefined) in clenv to be
540 * the template of clenv' be the value "c", applied to "n" fresh
541 * metavars, whose types are chosen by destructing "clf", which should
542 * be a clausale forme generated from the type of "c". The process of
543 * resolution can cause unification of already-existing metavars, and
544 * of the fresh ones which get created. This operation is a composite
545 * of operations which pose new metavars, perform unification on
546 * terms, and make bindings.
547
548 Otherwise said, from
549
550 [clenv] = [env;sigma;metas |- c:T]
551 [clenv'] = [env';sigma';metas' |- d:U]
552 [mv] = [mi] of type [Ti] in [metas]
553
554 then, if the unification of [Ti] and [U] produces map [rho], the
555 chaining is [env';sigma';rho'(metas),rho(metas') |- c:rho'(T)] for
556 [rho'] being [rho;mi:=d].
557
558 In particular, it assumes that [env'] and [sigma'] extend [env] and [sigma].
559 *)
560
561 let fchain_flags () =
562 { (default_unify_flags ()) with
563 allow_K_in_toplevel_higher_order_unification = true }
564
565 let clenv_instantiate ?(flags=fchain_flags ()) ?submetas mv clenv (c, ty) =
566 let clenv, c = match submetas with
567 | None -> clenv, c
568 | Some (metas, metam) ->
569 let metam = Unification.Meta.meta_merge metam clenv.metam in
570 let clenv = update_clenv_evd clenv clenv.evd metam in
571 let c = applist (c, List.map mkMeta metas) in
572 let map arg =
573 if Int.equal mv arg.marg_meta then
574 (* we never chain more than 2 clenvs *)
575 let () = assert (Option.is_empty arg.marg_chain) in
576 { arg with marg_chain = Some metas }
577 else arg
578 in
579 let metas = List.map map clenv.metas in
580 { clenv with metas = metas }, c
581 in
582 (* unify the type of the template of [nextclenv] with the type of [mv] *)
583 let clenv = clenv_unify ~flags CUMUL ty (clenv_meta_type ~metas:clenv.metam clenv.env clenv.evd mv) clenv in
584 let evd, metam = clenv_assign ~metas:clenv.metam clenv.env clenv.evd mv c in
585 update_clenv_evd clenv evd metam
586
587 (***************************************************************)
588 (* Bindings *)
589
590 (* [clenv_independent clenv]
591 * returns a list of metavariables which appear in the term cval,
592 * and which are not dependent. That is, they do not appear in
593 * the types of other metavars which are in cval, nor in the type
594 * of cval, ctyp. *)
595
596 let clenv_independent clenv =
597 let mvs = collect_metas clenv.evd (clenv_value clenv) in
598 let ctyp_mvs = metavars_of (clenv_type clenv) in
599 let deps = Metaset.union (dependent_in_type_of_metas ~metas:clenv.metam clenv.env clenv.evd mvs) ctyp_mvs in
600 List.filter (fun mv -> not (Metaset.mem mv deps)) mvs
601
602 let qhyp_eq h1 h2 = match h1, h2 with
603 | NamedHyp n1, NamedHyp n2 -> lident_eq n1 n2
604 | AnonHyp i1, AnonHyp i2 -> Int.equal i1 i2
605 | _ -> false
606
607 let check_bindings bl =
608 match List.duplicates qhyp_eq (List.map (fun {CAst.v=x} -> fst x) bl) with
609 | NamedHyp s :: _ ->
610 user_err ?loc:s.CAst.loc
611 Pp.(str "The variable " ++ Id.print s.CAst.v ++
612 str " occurs more than once in binding list.");
613 | AnonHyp n :: _ ->
614 user_err
615 Pp.(str "The position " ++ int n ++
616 str " occurs more than once in binding list.")
617 | [] -> ()
618
619 let explain_no_such_bound_variable mvl {CAst.v=id;loc} =
620 let open Pp in
621 let expl = match mvl with
622 | [] -> str "(no bound variables at all in the expression)."
623 | [id] -> str "(possible name is: " ++ Id.print id ++ str ")."
624 | _ -> str "(possible names are: " ++ pr_enum Id.print mvl ++ str ")."
625 in
626 user_err ?loc (str "No such bound variable " ++ Id.print id ++ spc () ++ expl)
627
628 let meta_with_name metas ({CAst.v=id} as lid) =
629 let na = Name id in
630 let fold n (l1, l2 as l) =
631 let na' = Unification.Meta.meta_name metas n in
632 let def = Option.has_some (Unification.Meta.meta_opt_fvalue metas n) in
633 if Name.equal na na' then if def then (n::l1,l2) else (n::l1,n::l2)
634 else l
635 in
636 let (mvl, mvnodef) = Unification.Meta.fold fold metas ([], []) in
637 match List.rev mvnodef, List.rev mvl with
638 | _,[] ->
639 let fold n l =
640 let na = Unification.Meta.meta_name metas n in
641 if na != Anonymous then Name.get_id na :: l else l
642 in
643 let mvl = List.rev (Unification.Meta.fold fold metas []) in
644 explain_no_such_bound_variable mvl lid
645 | (n::_,_|_,n::_) ->
646 n
647
648 let meta_of_binder clause loc mvs = function
649 | NamedHyp s -> meta_with_name clause.metam s
650 | AnonHyp n ->
651 try List.nth mvs (n-1)
652 with (Failure _|Invalid_argument _) ->
653 user_err Pp.(str "No such binder.")
654
655 let error_already_defined b =
656 match b with
657 | NamedHyp id ->
658 user_err ?loc:id.CAst.loc
659 Pp.(str "Binder name \"" ++ Id.print id.CAst.v ++
660 str"\" already defined with incompatible value.")
661 | AnonHyp n ->
662 anomaly
663 Pp.(str "Position " ++ int n ++ str" already defined.")
664
665 let clenv_unify_binding_type ~metas env sigma c t u =
666 if isMeta sigma (fst (decompose_app sigma (whd_nored ~metas:(meta_handler metas) env sigma u))) then
667 (* Not enough information to know if some subtyping is needed *)
668 Meta.CoerceToType, metas, sigma, c
669 else
670 (* Enough information so as to try a coercion now *)
671 try
672 let sigma, metas, c = w_coerce_to_type ~metas env sigma c t u in
673 Meta.TypeProcessed, metas, sigma, c
674 with
675 | PretypeError (_,_,ActualTypeNotCoercible (_,_,
676 (NotClean _ | ConversionFailed _))) as e ->
677 raise e
678 | e when precatchable_exception e ->
679 Meta.TypeNotProcessed, metas, sigma, c
680
681 let clenv_assign_binding clenv k c =
682 let k_typ = hnf_constr clenv.env clenv.evd (clenv_meta_type ~metas:clenv.metam clenv.env clenv.evd k) in
683 let c_typ = nf_betaiota clenv.env clenv.evd (Retyping.get_type_of clenv.env clenv.evd c) in
684 let status, metas, sigma, c = clenv_unify_binding_type ~metas:clenv.metam clenv.env clenv.evd c c_typ k_typ in
685 let sigma, metas = Meta.meta_assign k (c, status) metas sigma in
686 update_clenv_evd clenv sigma metas
687
688 let clenv_match_args bl clenv =
689 if List.is_empty bl then
690 clenv
691 else
692 let mvs = clenv_independent clenv in
693 check_bindings bl;
694 List.fold_left
695 (fun clenv {CAst.loc;v=(b,c)} ->
696 let k = meta_of_binder clenv loc mvs b in
697 match Meta.meta_opt_fvalue clenv.metam k with
698 | Some body ->
699 if EConstr.eq_constr clenv.evd body.rebus c then clenv
700 else error_already_defined b
701 | None ->
702 clenv_assign_binding clenv k c)
703 clenv bl
704
705 let error_not_right_number_missing_arguments n =
706 user_err
707 Pp.(strbrk "Not the right number of missing arguments (expected " ++
708 int n ++ str ").")
709
710 let clenv_constrain_dep_args hyps_only bl clenv =
711 if List.is_empty bl then
712 clenv
713 else
714 let occlist = clenv_dependent_gen ~metas:clenv.metam hyps_only clenv.env clenv.evd (clenv_type clenv) in
715 if Int.equal (List.length occlist) (List.length bl) then
716 List.fold_left2 clenv_assign_binding clenv occlist bl
717 else
718 if hyps_only then
719 (* Tolerance for compatibility <= 8.3 *)
720 let occlist' = clenv_dependent_gen ~metas:clenv.metam hyps_only ~iter:false clenv.env clenv.evd (clenv_type clenv) in
721 if Int.equal (List.length occlist') (List.length bl) then
722 List.fold_left2 clenv_assign_binding clenv occlist' bl
723 else
724 error_not_right_number_missing_arguments (List.length occlist)
725 else
726 error_not_right_number_missing_arguments (List.length occlist)
727
728 let pose_dependent_evars ?(with_evars=false) ~metas env sigma concl =
729 let dep_mvs = clenv_dependent_gen ~metas false env sigma concl in
730 if not (List.is_empty dep_mvs) && not with_evars then
731 raise
732 (RefinerError (env, sigma, UnresolvedBindings (List.map (Meta.meta_name metas) dep_mvs)));
733 clenv_pose_metas_as_evars ~metas env sigma dep_mvs
734
735 let clenv_pose_dependent_evars ?with_evars clenv =
736 let metas, sigma = pose_dependent_evars ?with_evars ~metas:clenv.metam clenv.env clenv.evd (clenv_type clenv) in
737 update_clenv_evd clenv sigma metas
738
739 type case_node = (case_info * EInstance.t * EConstr.t array * EConstr.case_return * EConstr.case_invert * EConstr.t)
740
741 module Internal =
742 struct
743
744 open Pp
745 open Constr
746 open Termops
747 open Retyping
748
749 let error_unsupported_deep_meta () =
750 user_err (strbrk "Application of lemmas whose beta-iota normal " ++
751 strbrk "form contains metavariables deep inside the term is not " ++
752 strbrk "supported; try \"refine\" instead.")
753
754 type proof =
755 | RfHole of metavariable
756 | RfGround of EConstr.t
757 | RfApp of proof * proof list
758 | RfProj of Projection.t * ERelevance.t * proof
759
760 exception NonLinear
761
762 let is_ground = function
763 | RfGround _ -> true
764 | RfHole _ | RfApp _ | RfProj _ -> false
765
766 let make_proof env sigma c =
767 let metas = ref Metaset.empty in
768 let rec make c = match EConstr.kind sigma c with
769 | Meta mv ->
770 if Metaset.mem mv !metas then raise NonLinear
771 else
772 let () = metas := Metaset.add mv !metas in
773 RfHole mv
774 | App (f, args) ->
775 let f = make f in
776 let args = Array.map_to_list (fun c -> make c) args in
777 if is_ground f && List.for_all is_ground args then RfGround c
778 else RfApp (f, args)
779 | Proj (p, r, a) ->
780 let a = make a in
781 if is_ground a then RfGround c else RfProj (p, r, a)
782 | _ ->
783 if occur_meta sigma c then error_unsupported_deep_meta ()
784 else RfGround c
785 in
786 try make c
787 with NonLinear -> raise (RefinerError (env, sigma, NonLinearProof c))
788
789 let rec as_constr = function
790 | RfHole mv -> EConstr.mkMeta mv
791 | RfGround c -> c
792 | RfApp (f, args) -> EConstr.mkApp (as_constr f, Array.map_of_list as_constr args)
793 | RfProj (p, r, c) -> EConstr.mkProj (p, r, as_constr c)
794
795 (* Old style mk_goal primitive *)
796 let mk_goal env evars ?name ?parent hyps concl =
797 (* A goal created that way will not be used by refine and will not
798 be shelved. It must not appear as a future_goal, so the future
799 goals are restored to their initial value after the evar is
800 created. *)
801 let evars = Evd.push_future_goals evars in
802 let inst = EConstr.identity_subst_val hyps in
803 let relevance = Retyping.relevance_of_type env evars concl in
804 let name = match name with
805 | Some name when Evd.generate_goal_names() -> Evarutil.next_evar_name (Namegen.IntroIdentifier name)
806 | _ -> None
807 in
808 let (evars,evk) =
809 Evarutil.new_pure_evar ~src:(Loc.tag Evar_kinds.GoalEvar) ?name ?parent ~typeclass_candidate:false hyps evars ~relevance concl
810 in
811 let _, evars = Evd.pop_future_goals evars in
812 let ev = EConstr.mkEvar (evk,inst) in
813 (evk, ev, evars)
814
815 let rec mk_refgoals ~metas env sigma goalacc ?parent conclty trm = match trm with
816 | RfGround trm ->
817 let ty = Retyping.get_type_of env sigma trm in
818 (goalacc, ty, sigma, trm)
819 | RfHole mv ->
820 let conclty = match conclty with
821 | None -> Unification.Meta.meta_type metas env sigma mv
822 | Some conclty -> conclty
823 in
824 let conclty = nf_betaiota env sigma conclty in
825 let hyps = Environ.named_context_val env in
826 (* Add a name to the goal if the metavariable itself has a name *)
827 let name = match Meta.meta_name metas mv with
828 | Name name -> Some name
829 | Anonymous -> None
830 in
831 let (gl,ev,sigma) = mk_goal env sigma ?name ?parent hyps conclty in
832 gl::goalacc, conclty, sigma, ev
833 | RfApp (f, l) ->
834 let (acc',hdty,sigma,applicand) = match f with
835 | RfGround f when Termops.is_template_polymorphic_ref env sigma f ->
836 let ty =
837 (* Template polymorphism of definitions and inductive types *)
838 let args, _ = List.split_when (fun p -> not (is_ground p)) l in
839 let args = Array.map_of_list as_constr args in
840 type_of_global_reference_knowing_parameters env sigma f args
841 in
842 goalacc, ty, sigma, f
843 | _ -> mk_refgoals ~metas env sigma goalacc ?parent None f
844 in
845 let ((acc'',conclty',sigma), args) = mk_arggoals ~metas env sigma acc' ?parent hdty l in
846 let ans = EConstr.applist (applicand, args) in
847 (acc'', conclty', sigma, ans)
848 | RfProj (p, r, c) ->
849 let (acc',cty,sigma,c') = mk_refgoals ~metas env sigma goalacc ?parent None c in
850 let c = EConstr.mkProj (p, r, c') in
851 let ty = get_type_of env sigma c in
852 (acc',ty,sigma,c)
853
854 and mk_arggoals ~metas env sigma goalacc ?parent funty allargs =
855 let foldmap (goalacc, funty, sigma) harg =
856 let t = whd_all ~metas:(meta_handler metas) env sigma funty in
857 match EConstr.kind sigma t with
858 | Prod (_, c1, b) ->
859 let (acc, hargty, sigma, arg) = mk_refgoals ~metas env sigma ?parent goalacc (Some c1) harg in
860 (acc, EConstr.Vars.subst1 arg b, sigma), arg
861 | _ ->
862 raise (RefinerError (env,sigma,CannotApply (t, as_constr harg)))
863 in
864 List.fold_left_map foldmap (goalacc, funty, sigma) allargs
865
866 let treat_case env sigma ci lbrty accu ~parent =
867 let open EConstr in
868 let fold (sigma, accu) (name, ctx, ty) =
869 let open Context.Rel.Declaration in
870 let brctx = Array.of_list (List.rev_map get_annot ctx) in
871 let args = Context.Rel.instance mkRel 0 ctx in
872 (* TODO: tweak this to prevent dummy β-cuts *)
873 let ty = nf_betaiota env sigma (it_mkProd_or_LetIn ty ctx) in
874 let hyps = Environ.named_context_val env in
875 let (gl, ev, sigma) = mk_goal env sigma ~name ~parent hyps ty in
876 let br' = mkApp (ev, args) in
877 (sigma, gl :: accu), (brctx, br')
878 in
879 Array.fold_left_map fold (sigma, accu) lbrty
880
881 let std_refine ~metas env sigma ?parent cl r =
882 let r = make_proof env sigma r in
883 let (sgl, _, sigma, trm) = mk_refgoals ~metas env sigma [] (Some cl) r ?parent in
884 (sigma, sgl, trm)
885
886 (***********************************************)
887 (* find appropriate names for pattern variables. Useful in the Case
888 and Inversion (case_then_using et case_nodep_then_using) tactics. *)
889
890 type refiner_kind =
891 | Std of Meta.t * EConstr.t
892 | Case of case_node * (Id.t * EConstr.rel_context * EConstr.t) array
893
894 let refiner_gen is_case =
895 let open Proofview.Notations in
896 Proofview.Goal.enter begin fun gl ->
897 let sigma = Proofview.Goal.sigma gl in
898 let env = Proofview.Goal.env gl in
899 let st = Proofview.Goal.state gl in
900 let cl = Proofview.Goal.concl gl in
901 let evk = Proofview.Goal.goal gl in
902 let (sigma, sgl, c) = match is_case with
903 | Case ((ci, u, pms, p, iv, c), branches) ->
904 let ((sigma, accu), lf) = treat_case env sigma ~parent:evk ci branches [] in
905 let ans = EConstr.mkCase (ci, u, pms, p, iv, c, lf) in
906 (sigma, accu, ans)
907 | Std (metas, r) ->
908 std_refine ~metas env sigma ~parent:evk cl r
909 in
910 let map gl = Proofview.goal_with_state gl st in
911 let sgl = List.rev_map map sgl in
912 (* Check that the goal itself does not appear in the refined term *)
913 let _ =
914 if not (Evarutil.occur_evar_upto sigma evk c) then ()
915 else Pretype_errors.error_occur_check env sigma evk c
916 in
917 let sigma = Evd.define evk c sigma in
918 Proofview.Unsafe.tclEVARS sigma <*>
919 Proofview.Unsafe.tclSETGOALS sgl
920 end
921
922 let refiner clenv =
923 let r = clenv_value clenv in
924 refiner_gen (Std (clenv.metam, r))
925
926 end
927
928 open Unification
929
930 let dft = default_unify_flags
931
932 let res_pf ?(with_evars=false) ?(with_classes=true) ?(flags=dft ()) clenv =
933 Proofview.Goal.enter begin fun gl ->
934 let concl = Proofview.Goal.concl gl in
935 let clenv = clenv_unique_resolver ~flags clenv concl in
936 let metas, sigma = pose_dependent_evars ~with_evars ~metas:clenv.metam clenv.env clenv.evd (clenv_type clenv) in
937 let sigma =
938 if with_classes then
939 let sigma =
940 Typeclasses.resolve_typeclasses ~filter:Typeclasses.all_evars
941 ~fail:(not with_evars) clenv.env sigma
942 in
943 (* After an apply, all the subgoals including those dependent shelved ones are in
944 the hands of the user and resolution won't be called implicitely on them. *)
945 Typeclasses.make_unresolvables (fun x -> true) sigma
946 else sigma
947 in
948 let clenv = update_clenv_evd clenv sigma metas in
949 let r = clenv_value clenv in
950 Proofview.tclTHEN
951 (Proofview.Unsafe.tclEVARS sigma)
952 (Internal.refiner_gen (Std (metas, r)))
953 end
954
955 type case_analysis =
956 | RealCase of case_node
957 | PrimitiveEta of EConstr.t array
958
959 let build_case_analysis env sigma (ind, u) params pred indices indarg dep knd =
960 let open Inductiveops in
961 let open Context.Rel.Declaration in
962 (* Assumes that the arguments do not contain free rels *)
963 let indf = make_ind_family ((ind, u), Array.to_list params) in
964 let projs = get_projections env ind in
965 let relevance = Retyping.relevance_of_sort knd in
966
967 let pnas, deparsign =
968 let arsign = get_arity env indf in
969 let r = Inductiveops.relevance_of_inductive_family env indf in
970 let depind = build_dependent_inductive env indf in
971 let deparsign = LocalAssum (make_annot Anonymous r,depind)::arsign in
972 let set_names env l =
973 let ident_hd env ids t na =
974 let na = Namegen.named_hd env (Evd.from_env env) t na in
975 Namegen.next_name_away na ids
976 in
977 let fold d (ids, l) =
978 let id = ident_hd env ids (get_type d) (get_name d) in
979 (Id.Set.add id ids, set_name (Name id) d :: l)
980 in
981 snd (List.fold_right fold l (Id.Set.empty,[]))
982 in
983 let pctx =
984 let deparsign = set_names env deparsign in
985 if dep then deparsign
986 else LocalAssum (make_annot Anonymous r, depind) :: List.tl deparsign
987 in
988 let pnas = Array.of_list (List.rev_map get_annot pctx) in
989 pnas, deparsign
990 in
991
992 match projs with
993 | None ->
994 let ci = make_case_info env ind RegularStyle in
995 let pbody =
996 mkApp
997 (pred,
998 if dep then Context.Rel.instance mkRel 0 deparsign
999 else Context.Rel.instance mkRel 1 (List.tl deparsign)) in
1000 let iv =
1001 if Inductiveops.Internal.should_invert_case env sigma (ERelevance.kind sigma relevance) ci
1002 then CaseInvert { indices = indices }
1003 else NoInvert
1004 in
1005 RealCase (ci, u, params, ((pnas, pbody), relevance), iv, indarg)
1006 | Some ps ->
1007 let args = Array.map (fun (p,r) ->
1008 let r = EConstr.Vars.subst_instance_relevance u (ERelevance.make r) in
1009 mkProj (Projection.make p true, r, indarg))
1010 ps
1011 in
1012 PrimitiveEta args
1013
1014 let case_pf ?(with_evars=false) ~dep (indarg, typ) =
1015 Proofview.Goal.enter begin fun gl ->
1016 let env = Proofview.Goal.env gl in
1017 let sigma = Proofview.Goal.sigma gl in
1018 let concl = Proofview.Goal.concl gl in
1019 (* Extract inductive data from the argument. *)
1020 let hd, args = decompose_app sigma typ in
1021 (* Workaround to #5645: reduce_to_atomic_ind produces ill-typed terms *)
1022 let sigma, _ = Typing.checked_appvect env sigma hd args in
1023 let ind, u = destInd sigma hd in
1024 let s = Retyping.get_sort_of env sigma concl in
1025 let (mib, mip) = Inductive.lookup_mind_specif env ind in
1026 let params, indices = Array.chop mib.mind_nparams args in
1027
1028 (* check private *)
1029 let () = if Inductive.is_private (mib, mip) then
1030 user_err Pp.(str "case analysis on a private type is not allowed.") in
1031 (* check dep elim *)
1032 let () = if dep && not (Inductiveops.has_dependent_elim (mib, mip)) then
1033 raise (Pretype_errors.error_not_allowed_dependent_elimination env sigma true ind) in
1034 (* check elim *)
1035 let sigma =
1036 match Inductiveops.make_allowed_elimination sigma ((mib,mip),u) s with
1037 | Some sigma -> sigma
1038 | None -> Pretype_errors.error_not_allowed_elimination env sigma true s (ind, u)
1039 in
1040
1041 let indf = Inductiveops.make_ind_family ((ind, u), Array.to_list params) in
1042
1043 (* Extract the return clause using unification with the conclusion *)
1044 let typP = Inductiveops.make_arity env sigma dep indf s in
1045 let mvP = new_meta () in
1046 let metas = Meta.meta_declare mvP typP Meta.empty in
1047 let depargs = Array.append indices [|indarg|] in
1048 let templtyp = if dep then mkApp (mkMeta mvP, depargs) else mkApp (mkMeta mvP, indices) in
1049 let flags = elim_flags () in
1050 let metas, sigma = w_unify_meta_types ~metas ~flags env sigma in
1051 let metas, sigma = w_unify ~metas ~flags env sigma CUMUL templtyp concl in
1052 let pred = Meta.meta_instance metas env sigma (mkMeta mvP) in
1053
1054 (* Create the branch types *)
1055 let branches =
1056 let open Inductiveops in
1057 let constrs = get_constructors env indf in
1058 let get_branch cs =
1059 let base = mkApp (pred, cs.cs_concl_realargs) in
1060 let argctx = cs.cs_args in
1061 let name = cs.cs_name in
1062 if dep then
1063 let argctx = Namegen.name_context env sigma argctx in
1064 (name, argctx, applist (base, [build_dependent_constructor cs]))
1065 else
1066 (name, argctx, base)
1067 in
1068 Array.map get_branch constrs
1069 in
1070
1071 (* Build the case node proper *)
1072 let body = build_case_analysis env sigma (ind, u) params pred indices indarg dep s in
1073
1074 (* After an apply, all the subgoals including those dependent shelved ones are in
1075 the hands of the user and resolution won't be called implicitely on them. *)
1076 let sigma =
1077 Typeclasses.resolve_typeclasses ~filter:Typeclasses.all_evars
1078 ~fail:(not with_evars) env sigma
1079 in
1080 let sigma = Typeclasses.make_unresolvables (fun x -> true) sigma in
1081 (* Note that the environment rel context does not matter for betaiota *)
1082 let rec nf_betaiota c = EConstr.map sigma nf_betaiota (whd_betaiota ~metas:(meta_handler metas) env sigma c) in
1083 (* Call the legacy refiner on the result *)
1084 let arg = match body with
1085 | RealCase (ci, u, pms, (p,r), iv, c) ->
1086 let c = nf_betaiota c in
1087 let pms = Array.map nf_betaiota pms in
1088 let p = on_snd nf_betaiota p in
1089 Internal.Case ((ci, u, pms, (p,r), iv, c), branches)
1090 | PrimitiveEta args ->
1091 let mv = new_meta () in
1092 let (_, ctx, t) = branches.(0) in
1093 let metas = Meta.meta_declare mv (it_mkProd_or_LetIn t ctx) metas in
1094 Internal.Std (metas, mkApp (mkMeta mv, Array.map nf_betaiota args))
1095 in
1096 Proofview.tclTHEN
1097 (Proofview.Unsafe.tclEVARS sigma)
1098 (Internal.refiner_gen arg)
1099 end
1100
1101 (* [unifyTerms] et [unify] ne semble pas gérer les Meta, en
1102 particulier ne semblent pas vérifier que des instances différentes
1103 d'une même Meta sont compatibles. D'ailleurs le "fst" jette les metas
1104 provenant de w_Unify. (Utilisé seulement dans prolog.ml) *)
1105
1106 let fail_quick_core_unif_flags = {
1107 modulo_conv_on_closed_terms = Some TransparentState.full;
1108 use_metas_eagerly_in_conv_on_closed_terms = false;
1109 use_evars_eagerly_in_conv_on_closed_terms = false;
1110 modulo_delta = TransparentState.empty;
1111 modulo_delta_types = TransparentState.full;
1112 check_applied_meta_types = false;
1113 use_pattern_unification = false;
1114 use_meta_bound_pattern_unification = true; (* ? *)
1115 allowed_evars = Evarsolve.AllowedEvars.all;
1116 restrict_conv_on_strict_subterms = false; (* ? *)
1117 modulo_betaiota = false;
1118 modulo_eta = true;
1119 }
1120
1121 let fail_quick_unif_flags = {
1122 core_unify_flags = fail_quick_core_unif_flags;
1123 merge_unify_flags = fail_quick_core_unif_flags;
1124 subterm_unify_flags = fail_quick_core_unif_flags;
1125 allow_K_in_toplevel_higher_order_unification = false;
1126 resolve_evars = false
1127 }
1128
1129 (* let unifyTerms m n = walking (fun wc -> fst (w_Unify CONV m n [] wc)) *)
1130 let unify ?(flags=fail_quick_unif_flags) ~cv_pb m =
1131 Proofview.Goal.enter begin fun gl ->
1132 let env = Proofview.Goal.env gl in
1133 let sigma = Proofview.Goal.sigma gl in
1134 let concl = Proofview.Goal.concl gl in
1135 try
1136 let _, sigma = w_unify ~metas:Meta.empty env sigma cv_pb ~flags m concl in
1137 Proofview.Unsafe.tclEVARSADVANCE sigma
1138 with e when CErrors.noncritical e ->
1139 let info = Exninfo.reify () in
1140 Proofview.tclZERO ~info e
1141 end
1142
1143 (****************************************************************)
1144 (* Clausal environment for an application *)
1145
1146 let make_clenv_binding_gen hyps_only n env sigma (c,t) = function
1147 | ImplicitBindings largs ->
1148 let clause = mk_clenv_from_env env sigma n (c,t) in
1149 clenv_constrain_dep_args hyps_only largs clause
1150 | ExplicitBindings lbind ->
1151 let clause = mk_clenv_from_env env sigma n (c, t) in clenv_match_args lbind clause
1152 | NoBindings ->
1153 mk_clenv_from_env env sigma n (c,t)
1154
1155 let make_clenv_binding_apply env sigma n = make_clenv_binding_gen true n env sigma
1156 let make_clenv_binding env sigma = make_clenv_binding_gen false None env sigma
1157
1158 (****************************************************************)
1159 (* Pretty-print *)
1160
1161 let pr_clenv clenv =
1162 let prc = Termops.Internal.print_constr_env clenv.env clenv.evd in
1163 Pp.(h (str"TEMPL: " ++ prc clenv.templval ++
1164 str" : " ++ prc (fst clenv.templtyp) ++ fnl () ++
1165 pr_evar_map (Some 2) clenv.env clenv.evd))