Debian Codegraph @

plugins/ssrmatching/ssrmatching.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 (* This file is (C) Copyright 2006-2015 Microsoft Corporation and Inria. *)
12
13 open Ltac_plugin
14 open Names
15 open Pp
16 open Genarg
17 open Context
18 module CoqConstr = Constr
19 open CoqConstr
20 open Libnames
21 open Tactics
22 open Termops
23 open Glob_term
24 open Util
25 open Evd
26 open Tacexpr
27 open Tacinterp
28 open Pretyping
29 open Ppconstr
30 open Printer
31 open Evar_kinds
32 open Constrexpr
33 open Constrexpr_ops
34
35 type ssrtermkind = | InParens | WithAt | NoFlag | Cpattern
36
37 let errorstrm = CErrors.user_err
38 let loc_error loc msg = CErrors.user_err ?loc (str msg)
39 let ppnl = Feedback.msg_info
40
41 let pp = CDebug.create ~name:"ssrmatching" ()
42 let pp s = pp (fun () -> Lazy.force s)
43
44 let { Goptions.get = option_LegacyFoUnif } =
45 Goptions.declare_bool_option_and_ref ~key:["SsrMatching";"LegacyFoUnif"]
46 ~depr:{Deprecation.since=Some "9.2";
47 note=Some "Use this flag only to port scripts from 9.1 to 9.2, do not leave it in final scripts." }
48 ~value:false ()
49
50 (** Utils *)(* {{{ *****************************************************************)
51 let env_size env = List.length (Environ.named_context env)
52 let safeDestApp sigma c =
53 match EConstr.kind sigma c with App (f, a) -> f, a | _ -> c, [| |]
54 (* Toplevel constr must be globalized twice ! *)
55 let glob_constr ist genv sigma t = match t, ist with
56 | (_, Some ce), Some ist ->
57 let vars = Id.Map.fold (fun x _ accu -> Id.Set.add x accu) ist.lfun Id.Set.empty in
58 let ltacvars = { Constrintern.empty_ltac_sign with Constrintern.ltac_vars = vars } in
59 Constrintern.intern_gen WithoutTypeConstraint ~ltacvars:ltacvars genv sigma ce
60 | (rc, None), _ -> rc
61 | (_, Some _), None -> CErrors.anomaly Pp.(str"glob_constr: term with no ist")
62
63 (* Term printing utilities functions for deciding bracketing. *)
64 let pr_paren prx x = hov 1 (str "(" ++ prx x ++ str ")")
65 (* String lexing utilities *)
66 let skip_wschars s =
67 let rec loop i = match s.[i] with '\n'..' ' -> loop (i + 1) | _ -> i in loop
68 (* We also guard characters that might interfere with the ssreflect *)
69 (* tactic syntax. *)
70 let guard_term kind s i = match s.[i] with
71 | '(' -> false
72 | '{' | '/' | '=' -> true
73 | _ -> kind = InParens
74 (* The call 'guard s i' should return true if the contents of s *)
75 (* starting at i need bracketing to avoid ambiguities. *)
76 let pr_guarded guard prc c =
77 let s = Pp.string_of_ppcmds (prc c) ^ "$" in
78 if guard s (skip_wschars s 0) then pr_paren prc c else prc c
79 (* More sensible names for constr printers *)
80 let with_global_env_evm f x =
81 let env = Global.env () in
82 let sigma = Evd.from_env env in
83 f ?flags:None env sigma x
84 let prl_glob_constr = with_global_env_evm pr_lglob_constr_env
85 let pr_glob_constr = with_global_env_evm pr_glob_constr_env
86 let prl_constr_expr = pr_lconstr_expr
87 let pr_constr_expr = pr_constr_expr
88 let prl_glob_constr_and_expr env sigma = function
89 | _, Some c -> prl_constr_expr ~flags:(current_flags()) env sigma c
90 | c, None -> prl_glob_constr c
91 let pr_glob_constr_and_expr env sigma = function
92 | _, Some c -> pr_constr_expr ~flags:(current_flags()) env sigma c
93 | c, None -> pr_glob_constr c
94
95 (** Adding a new uninterpreted generic argument type *)
96 let add_genarg tag pr =
97 let wit = Genarg.make0 tag in
98 let tag = Geninterp.Val.create tag in
99 let glob ist x = (ist, x) in
100 let subst _ x = x in
101 let interp ist x = Ftactic.return (Geninterp.Val.Dyn (tag, x)) in
102 let gen_pr env sigma _ _ _ = pr env sigma in
103 let () = Genintern.register_intern0 wit glob in
104 let () = Gensubst.register_subst0 wit subst in
105 let () = Geninterp.register_interp0 wit interp in
106 let () = Geninterp.register_val0 wit (Some (Geninterp.Val.Base tag)) in
107 Pptactic.declare_extra_genarg_pprule wit gen_pr gen_pr gen_pr;
108 wit
109
110 (** Constructors for constr_expr *)
111 let isCVar = function { CAst.v = CRef (qid,_) } -> qualid_is_ident qid | _ -> false
112 let destCVar = function
113 | { CAst.v = CRef (qid,_) } when qualid_is_ident qid ->
114 qualid_basename qid
115 | _ ->
116 CErrors.anomaly (str"not a CRef.")
117 let isGLambda c = match DAst.get c with GLambda (Name _, _, _, _, _) -> true | _ -> false
118 let destGLambda c = match DAst.get c with GLambda (Name id, _, _, _, c) -> (id, c)
119 | _ -> CErrors.anomaly (str "not a GLambda")
120 let isGHole c = match DAst.get c with GHole _ -> true | _ -> false
121 let mkCHole ~loc = CAst.make ?loc @@ CHole (None)
122 let mkCLambda ?loc name ty t = CAst.make ?loc @@
123 CLambdaN ([CLocalAssum([CAst.make ?loc name], None, Default Explicit, ty)], t)
124 let mkCCast ?loc t ty = CAst.make ?loc @@ CCast (t, Some DEFAULTcast, ty)
125
126 (** Constructors for rawconstr *)
127 let mkRHole = DAst.make @@ GHole (GInternalHole)
128 let mkRApp f args = if args = [] then f else DAst.make @@ GApp (f, args)
129 let mkRCast rc rt = DAst.make @@ GCast (rc, Some DEFAULTcast, rt)
130 let mkRLambda n s t = DAst.make @@ GLambda (n, None, Explicit, s, t)
131
132 (* }}} *)
133
134 exception NoProgress
135
136 (** Unification procedures. *)
137
138 (* To enforce the rigidity of the rooted match we always split *)
139 (* top applications, so the unification procedures operate on *)
140 (* arrays of patterns and terms. *)
141 (* We perform three kinds of unification: *)
142 (* EQ: exact conversion check *)
143 (* FO: first-order unification of evars, without conversion *)
144 (* HO: higher-order unification with conversion *)
145 (* The subterm unification strategy is to find the first FO *)
146 (* match, if possible, and the first HO match otherwise, then *)
147 (* compute all the occurrences that are EQ matches for the *)
148 (* relevant subterm. *)
149 (* Additional twists: *)
150 (* - If FO/HO fails then we attempt to fill evars using *)
151 (* typeclasses before raising an outright error. We also *)
152 (* fill typeclasses even after a successful match, since *)
153 (* beta-reduction and canonical instances may leave *)
154 (* undefined evars. *)
155 (* - We do postchecks to rule out matches that are not *)
156 (* closed or that assign to a global evar; these can be *)
157 (* disabled for rewrite or dependent family matches. *)
158 (* - We do a full FO scan before turning to HO, as the FO *)
159 (* comparison can be much faster than the HO one. *)
160
161 let unif_EQ env sigma p c =
162 let env = Environ.set_universes (Evd.universes sigma) env in
163 Reductionops.is_conv env sigma p c
164
165 let unif_EQ_args env sigma pa a =
166 let n = Array.length pa in
167 let rec loop i = (i = n) || unif_EQ env sigma pa.(i) a.(i) && loop (i + 1) in
168 loop 0
169
170 let unif_HO env ise p c =
171 try Evarconv.unify_delay env ise p c
172 with Evarconv.UnableToUnify(ise, err) ->
173 raise Pretype_errors.(PretypeError(env,ise,CannotUnify(p,c,Some err)))
174
175 let unif_HO_args env ise0 pa i ca =
176 let n = Array.length pa in
177 let rec loop ise j =
178 if j = n then ise else loop (unif_HO env ise pa.(j) (ca.(i + j))) (j + 1) in
179 loop ise0 0
180
181 (* FO unification should boil down to calling w_unify with no_delta, but *)
182 (* alas things are not so simple: w_unify does partial type-checking, *)
183 (* which breaks down when the no-delta flag is on (as the Rocq type system *)
184 (* requires full convertibility. The workaround here is to convert all *)
185 (* evars into metas, since 8.2 does not TC metas. This means some lossage *)
186 (* for HO evars, though hopefully Miller patterns can pick up some of *)
187 (* those cases, and HO matching will mop up the rest. *)
188 let flags_FO env =
189 let oracle = Environ.oracle env in
190 let ts = Conv_oracle.get_transp_state oracle in
191 let flags =
192 { (Unification.default_no_delta_unify_flags ts).Unification.core_unify_flags
193 with
194 Unification.modulo_conv_on_closed_terms = None;
195 Unification.modulo_eta = true;
196 Unification.modulo_betaiota = true;
197 Unification.modulo_delta_types = ts }
198 in
199 { Unification.core_unify_flags = flags;
200 Unification.merge_unify_flags = flags;
201 Unification.subterm_unify_flags = flags;
202 Unification.allow_K_in_toplevel_higher_order_unification = false;
203 Unification.resolve_evars =
204 (Unification.default_no_delta_unify_flags ts).Unification.resolve_evars
205 }
206 let legacy_unif_FO env ise metas p c =
207 let _ : _ * Evd.evar_map = Unification.w_unify ~metas env ise Conversion.CONV ~flags:(flags_FO env) p c in
208 ()
209
210 type hd_comparison =
211 | CompareArgs of evar_map * Unification.Meta.t * Impargs.implicit_status list
212 | CanonicalInfRequired
213 | CanonicalRedRequired of Evd.evar_map * EConstr.t * int
214 | Different
215
216 let implicits_for_rewrite_of gr =
217 Impargs.implicits_of_global gr |> List.last |> snd
218
219 let failure_FO () = raise (CErrors.user_err Pp.(mt ()))
220
221 let rec same_hd env ise metas p c =
222 match EConstr.kind ise p, EConstr.kind ise c with
223 | Const(c1,_), Const(c2,_) when Environ.QConstant.equal env c1 c2 ->
224 CompareArgs (ise,metas,implicits_for_rewrite_of (GlobRef.ConstRef c1))
225 | Ind(c1,_), Ind(c2,_) when Environ.QInd.equal env c1 c2 ->
226 CompareArgs (ise,metas,implicits_for_rewrite_of (GlobRef.IndRef c1))
227 | Construct(c1,_), Construct(c2,_) when Environ.QConstruct.equal env c1 c2 ->
228 CompareArgs (ise,metas,implicits_for_rewrite_of (GlobRef.ConstructRef c1))
229 | Const(c1,_), _ when Structures.Structure.is_projection c1 -> CanonicalInfRequired
230 | _, Const(c2,i) when Structures.Structure.is_projection c2 ->
231 let b = Environ.constant_value_in env (c2,EConstr.EInstance.kind ise i) in
232 CanonicalRedRequired (ise, EConstr.of_constr b, Structures.Structure.projection_nparams env c2)
233 | Rel c1,Rel c2 when c1 == c2 -> CompareArgs (ise,metas,[])
234 | Var c1,Var c2 when Id.equal c1 c2 ->
235 CompareArgs (ise,metas,implicits_for_rewrite_of (GlobRef.VarRef c1))
236 | Proj(p1,_,x), Proj(p2,_,y) when Environ.QProjection.equal env p1 p2 ->
237 let metas, ise = unif_FO_skip_impl env ise metas x y in
238 CompareArgs (ise,metas,[])
239 | _ -> Different
240 and unif_FO_skip_impl env ise metas p c =
241 match EConstr.kind ise p, EConstr.kind ise c with
242 | Meta i, _ when Unification.Meta.meta_opt_fvalue metas i = None ->
243 let ise,metas = Unification.Meta.meta_assign i (c,TypeNotProcessed) metas ise in metas, ise
244 | Meta i, _ ->
245 begin match Unification.Meta.meta_opt_fvalue metas i with
246 | None -> assert false
247 | Some { Unification.rebus = p } -> unif_FO_skip_impl env ise metas p c
248 end
249 (* | App(hd,args1), _ when EConstr.isMeta ise hd -> metas, ise *)
250 (* | App(hd,args1), App(f,args2) when EConstr.isMeta ise hd ->
251 if Array.length args1 > Array.length args2 then failure_FO ();
252 let args2, rest = CArray.chop (Array.length args2 - Array.length args1) args2 in
253 let rhs = EConstr.mkApp (f,args2) in
254 pp(lazy(str "HO-FO" ++ pr_econstr_env env ise hd ++ str " = " ++ pr_econstr_env env ise rhs));
255 let metas, ise = unif_FO_skip_impl env ise metas hd rhs in
256 unif_FO_skip_impl3 env ise metas (Array.to_list args1) (Array.to_list rest) [] *)
257 | Proj(p1,_,x), Proj(p2,_,y) when Environ.QProjection.equal env p1 p2 ->
258 unif_FO_skip_impl3 env ise metas [x] [y] []
259 | App(hd1,args1), App(hd2,args2) when not @@ EConstr.isMeta ise hd1 ->
260 begin match same_hd env ise metas hd1 hd2 with
261 | CanonicalRedRequired(ise,proj,narg) when Array.length args2 > narg ->
262 pp(lazy(str "Red in " ++ pr_econstr_env env ise c));
263 let c' =
264 let open Reductionops in
265 let metas = { meta_value = (fun i ->
266 Option.map (fun x -> x.Unification.rebus)
267 (Unification.Meta.meta_opt_fvalue metas i)) } in
268 Stack.zip ise @@
269 whd_betaiota_deltazeta_for_iota_state
270 TransparentState.full env ise ~metas
271 (EConstr.mkApp (proj,args2),Stack.empty) in
272 pp(lazy(str "Red out " ++ pr_econstr_env env ise c'));
273 if EConstr.eq_constr ise c c' then failure_FO ()
274 else unif_FO_skip_impl env ise metas p c'
275 | CanonicalInfRequired ->
276 pp(lazy(str "Skip"));
277 metas, ise
278 | CompareArgs(ise,metas,imp) ->
279 pp(lazy(str "Rec"));
280 unif_FO_skip_impl3 env ise metas (Array.to_list args1) (Array.to_list args2) imp
281 | _ ->
282 pp(lazy(str "Fail"));
283 failure_FO ()
284 end
285 | _ ->
286 let kludge v = EConstr.mkLambda (make_annot Anonymous EConstr.ERelevance.relevant, EConstr.mkProp, v) in
287 Unification.w_unify ~metas env ise Conversion.CONV ~flags:(flags_FO env) (kludge p) (kludge c)
288 and unif_FO_skip_impl3 env ise metas args1 args2 imp =
289 match args1, args2, imp with
290 | a1::args1, a2::args2, Some _ :: imp ->
291 pp(lazy(str"skip impl " ++ pr_econstr_env env ise a1 ++ str " = " ++ pr_econstr_env env ise a2));
292 unif_FO_skip_impl3 env ise metas args1 args2 imp
293 | a1::args1, a2::args2, None :: imp ->
294 pp(lazy(str"do " ++ pr_econstr_env env ise a1 ++ str " = " ++ pr_econstr_env env ise a2));
295 let metas, ise = unif_FO_skip_impl env ise metas a1 a2 in
296 unif_FO_skip_impl3 env ise metas args1 args2 imp
297 | a1::args1, a2::args2, [] ->
298 pp(lazy(str"do " ++ pr_econstr_env env ise a1 ++ str " = " ++ pr_econstr_env env ise a2));
299 let metas, ise = unif_FO_skip_impl env ise metas a1 a2 in
300 unif_FO_skip_impl3 env ise metas args1 args2 []
301 | [], [], _ ->
302 pp(lazy(str"good"));
303 metas, ise
304 | _ ->
305 pp(lazy(str"bad"));
306 failure_FO ()
307
308 let new_unif_FO env ise metas p c =
309 pp(lazy(str"NEW FO " ++ pr_econstr_env env ise p ++ str " = " ++ pr_econstr_env env ise c));
310 let _ : _ * Evd.evar_map = unif_FO_skip_impl env ise metas p c in
311 ()
312
313 let unif_FO env ise metas p c =
314 if option_LegacyFoUnif () then legacy_unif_FO env ise metas p c
315 else new_unif_FO env ise metas p c
316
317 (* Perform evar substitution in main term and prune substitution. *)
318 let nf_open_term sigma0 ise c =
319 let open EConstr in
320 let s' = ref sigma0 in
321 let rec nf c' = match EConstr.kind ise c' with
322 | Evar ex ->
323 let k, a = ex in let a' = SList.Skip.map nf a in
324 if not (Evd.mem !s' k) then
325 s' := Evd.add !s' k (Evarutil.nf_evar_info ise (Evd.find_undefined ise k));
326 mkEvar (k, a')
327 | _ -> map ise nf c' in
328 let copy_def k _ () =
329 let EvarInfo evi = Evd.find ise k in
330 match Evd.evar_body evi with
331 | Evar_defined c' ->
332 let c' = nf c' in
333 s' := Evd.define k c' !s'
334 | _ -> () in
335 let c' = nf c in
336 let _ = Evd.fold_undefined copy_def sigma0 () in
337 let changed = sigma0 != !s' in
338 changed, !s', Evd.ustate ise, c'
339
340 let unif_end ?(solve_TC=true) env sigma0 ise0 pt ok =
341 let ise = Evarconv.solve_unif_constraints_with_heuristics env ise0 in
342 let tcs = Evd.get_typeclass_evars ise in
343 let c, s, uc, t = nf_open_term sigma0 ise pt in
344 let ise1 = create_evar_defs s in
345 let ise1 = Evd.set_typeclass_evars ise1 (Evar.Set.filter (fun ev -> Evd.is_undefined ise1 ev) tcs) in
346 let ise1 = Evd.set_universe_context ise1 uc in
347 let ise2 =
348 if solve_TC then Typeclasses.resolve_typeclasses ~fail:true env ise1
349 else ise1 in
350 if not (ok ise) then raise NoProgress else
351 if ise2 == ise1 then (c, s, uc, t)
352 else
353 let c, s, uc', t = nf_open_term sigma0 ise2 t in
354 c, s, UState.union uc uc', t
355
356 let unify_HO env sigma0 t1 t2 =
357 let sigma = unif_HO env sigma0 t1 t2 in
358 let _, sigma, uc, _ = unif_end ~solve_TC:false env sigma0 sigma t2 (fun _ -> true) in
359 Evd.set_universe_context sigma uc
360
361 (* This is what the definition of iter_constr should be... *)
362 let iter_constr_LR sigma f c = match EConstr.kind sigma c with
363 | Evar (k, a) -> SList.Skip.iter f a
364 | Cast (cc, _, t) -> f cc; f t
365 | Prod (_, t, b) | Lambda (_, t, b) -> f t; f b
366 | LetIn (_, v, t, b) -> f v; f t; f b
367 | App (cf, a) -> f cf; Array.iter f a
368 | Case (_, _, pms, ((_, p), _), iv, v, b) ->
369 f v; Array.iter f pms; f p; iter_invert f iv; Array.iter (fun (_, c) -> f c) b
370 | Fix (_, (_, t, b)) | CoFix (_, (_, t, b)) ->
371 for i = 0 to Array.length t - 1 do f t.(i); f b.(i) done
372 | Proj(_,_,a) -> f a
373 | Array(_u,t,def,ty) -> Array.iter f t; f def; f ty
374 | (Rel _ | Meta _ | Var _ | Sort _ | Const _ | Ind _ | Construct _
375 | Int _ | Float _ | String _) -> ()
376
377 (* The comparison used to determine which subterms matches is KEYED *)
378 (* CONVERSION. This looks for convertible terms that either have the same *)
379 (* same head constant as pat if pat is an application (after beta-iota), *)
380 (* or start with the same constr constructor (esp. for LetIn); this is *)
381 (* disregarded if the head term is let x := ... in x, and casts are always *)
382 (* ignored and removed). *)
383 (* Record projections get special treatment: in addition to the projection *)
384 (* constant itself, ssreflect also recognizes head constants of canonical *)
385 (* projections. *)
386
387 exception NoMatch
388 type ssrdir = L2R | R2L
389 let pr_dir_side = function L2R -> str "LHS" | R2L -> str "RHS"
390 let inv_dir = function L2R -> R2L | R2L -> L2R
391
392
393 type pattern_class =
394 | KpatFixed
395 | KpatConst
396 | KpatEvar of Evar.t
397 | KpatLet
398 | KpatLam
399 | KpatRigid
400 | KpatFlex
401 | KpatProj of Constant.t
402
403 type tpattern = {
404 up_k : pattern_class;
405 up_FO : Unification.Meta.t * EConstr.t;
406 up_f : EConstr.t;
407 up_a : EConstr.t array;
408 up_t : EConstr.t; (* equation proof term or matched term *)
409 up_dir : ssrdir; (* direction of the rule *)
410 up_ok : EConstr.t -> evar_map -> bool; (* progress test for rewrite *)
411 }
412
413 type tpatterns = {
414 tpat_sigma : Evd.evar_map;
415 tpat_pats : tpattern list;
416 }
417
418 let empty_tpatterns sigma = { tpat_sigma = sigma; tpat_pats = [] }
419 (* Technically we only care about the metas of [sigma] in the [tpatterns] type.
420 Should we [create_evar_defs] here? *)
421
422 let all_ok _ _ = true
423
424 let proj_nparams env c =
425 try 1 + Structures.Structure.projection_nparams env c
426 with Not_found -> 0
427
428 let isRigid sigma c = match EConstr.kind sigma c with
429 | (Prod _ | Sort _ | Lambda _ | Case _ | Fix _ | CoFix _| Int _
430 | Float _ | String _ | Array _) -> true
431 | (Rel _ | Var _ | Meta _ | Evar (_, _) | Cast (_, _, _) | LetIn (_, _, _, _)
432 | App (_, _) | Const (_, _) | Ind ((_, _), _) | Construct (((_, _), _), _)
433 | Proj _) -> false
434
435
436 let hole_var = mkVar (Id.of_string "_")
437 let pr_constr_pat env sigma c0 =
438 let rec wipe_evar c =
439 if isEvar c then hole_var else map wipe_evar c in
440 pr_constr_env env sigma (wipe_evar c0)
441
442 let ehole_var = EConstr.mkVar (Id.of_string "_")
443 let pr_econstr_pat env sigma c0 =
444 let rec wipe_evar c = let open EConstr in
445 if isEvar sigma c then ehole_var else map sigma wipe_evar c in
446 let dummy_decl =
447 let dummy_prod = mkProd (make_annot Anonymous Sorts.Relevant,mkProp,mkProp) in
448 let na = make_annot (EConstr.destVar sigma ehole_var) Sorts.Relevant in
449 Context.Named.Declaration.(LocalAssum (na, dummy_prod)) in
450 let env = Environ.push_named dummy_decl env in
451 pr_econstr_env env sigma (wipe_evar c0)
452
453 (* Turn (new) evars into metas *)
454 let evars_for_FO ~hack ~rigid env (ise0:evar_map) c0 =
455 let open EConstr in
456 let metas = ref Unification.Meta.empty in
457 let sigma = ref ise0 in
458 let nenv = env_size env + if hack then 1 else 0 in
459 let rec put c = match EConstr.kind !sigma c with
460 | Evar (k, a) ->
461 if rigid k then map !sigma put c else
462 let evi = Evd.find_undefined !sigma k in
463 let dc = List.firstn (max 0 (SList.length a - nenv)) (evar_filtered_context evi) in
464 let abs_dc (d, c) = function
465 | Context.Named.Declaration.LocalDef (x, b, t) ->
466 d, mkNamedLetIn !sigma x (put b) (put t) c
467 | Context.Named.Declaration.LocalAssum (x, t) ->
468 mkVar x.binder_name :: d, mkNamedProd !sigma x (put t) c in
469 let a, t =
470 Context.Named.fold_inside abs_dc ~init:([], put (Evd.evar_concl evi)) dc
471 in
472 let m = Evarutil.new_meta () in
473 let () = metas := Unification.Meta.meta_declare m t !metas in
474 sigma := Evd.define k (applistc (mkMeta m) a) !sigma;
475 put c
476 | _ -> map !sigma put c in
477 let c1 = put c0 in !metas, c1
478
479 (* Compile a match pattern from a term; t is the term to fill. *)
480 (* p_origin can be passed to obtain a better error message *)
481 let mk_tpattern ?p_origin ?(hack=false) ?(ok = all_ok) ~rigid env t dir p { tpat_sigma = ise; tpat_pats = pats } =
482 let open EConstr in
483 let k, f, a =
484 let f, a = Reductionops.whd_betaiota_stack env ise p in
485 match EConstr.kind ise f with
486 | Const (p,_) ->
487 let np = proj_nparams env p in
488 if np = 0 || np > List.length a then KpatConst, f, a else
489 let a1, a2 = List.chop np a in KpatProj p, (applistc f a1), a2
490 | Proj (p,_,arg) -> KpatProj (Projection.constant p), f, a
491 | Var _ | Ind _ | Construct _ -> KpatFixed, f, a
492 | Evar (k, _) ->
493 if rigid k then KpatEvar k, f, a else
494 if a <> [] then KpatFlex, f, a else
495 (match p_origin with None -> CErrors.user_err Pp.(str "indeterminate pattern")
496 | Some (dir, rule) ->
497 errorstrm (str "indeterminate " ++ pr_dir_side dir
498 ++ str " in " ++ pr_econstr_pat env ise rule))
499 | LetIn (_, v, _, b) ->
500 if b <> mkRel 1 then KpatLet, f, a else KpatFlex, v, a
501 | Lambda _ -> KpatLam, f, a
502 | _ -> KpatRigid, f, a in
503 let aa = Array.of_list a in
504 let p' = evars_for_FO ~hack ~rigid env ise (mkApp (f, aa)) in
505 let pat = { up_k = k; up_FO = p'; up_f = f; up_a = aa; up_ok = ok; up_dir = dir; up_t = t} in
506 { tpat_sigma = ise; tpat_pats = pats @ [pat] }
507
508 (* Specialize a pattern after a successful match: assign a precise head *)
509 (* kind and arity for Proj and Flex patterns. *)
510 let ungen_upat lhs (c, sigma, uc, t) u =
511 let f, a = safeDestApp sigma lhs in
512 let k = match kind (EConstr.Unsafe.to_constr f) with
513 | Var _ | Ind _ | Construct _ -> KpatFixed
514 | Const _ -> KpatConst
515 | Evar (k, _) -> if is_defined sigma k then raise NoMatch else KpatEvar k
516 (* FIXME: why do we observe defined evars here? *)
517 | LetIn _ -> KpatLet
518 | Lambda _ -> KpatLam
519 | _ -> KpatRigid in
520 c, sigma, uc, {u with up_k = k; up_FO = (Unification.Meta.empty, lhs); up_f = f; up_a = a; up_t = t}
521
522 let nb_cs_proj_args env ise pc f u =
523 let open EConstr in
524 let open Structures in
525 let open ValuePattern in
526 let na k =
527 let open CanonicalSolution in
528 let _, { cvalue_arguments } = find env ise (GlobRef.ConstRef pc, k) in
529 List.length cvalue_arguments in
530 let nargs_of_proj t = match EConstr.kind ise t with
531 | App(_,args) -> Array.length args
532 | Proj _ -> 0 (* if splay_app calls expand_projection, this has to be
533 the number of arguments including the projected *)
534 | _ -> assert false in
535 try match EConstr.kind ise f with
536 | Prod _ -> na Prod_cs
537 | Sort s -> na (Sort_cs (ESorts.quality_or_set ise s))
538 | Const (c',_) when Environ.QConstant.equal env c' pc -> nargs_of_proj u.up_f
539 | Proj (c',_,_) when Environ.QConstant.equal env (Names.Projection.constant c') pc -> nargs_of_proj u.up_f
540 | Proj (c',_,_) -> let _ = na (Proj_cs (Names.Projection.repr c')) in 0
541 | Var _ | Ind _ | Construct _ | Const _ -> na (Const_cs (fst @@ destRef ise f))
542 | _ -> -1
543 with Not_found -> -1
544
545 let isEvar_k ise k f =
546 match EConstr.kind ise f with Evar (k', _) -> k = k' | _ -> false
547
548 let nb_args sigma c =
549 match EConstr.kind sigma c with App (_, a) -> Array.length a | _ -> 0
550
551 let mkSubArg i a =
552 if i = Array.length a then a else Array.sub a 0 i
553 let mkSubApp f i a =
554 let open EConstr in
555 if i = 0 then f else mkApp (f, mkSubArg i a)
556
557 let splay_app ise =
558 let rec loop c a = match EConstr.kind ise c with
559 | App (f, a') -> loop f (Array.append a' a)
560 | Cast (c', _, _) -> loop c' a
561 | _ -> c, a in
562 fun c -> match EConstr.kind ise c with
563 | App (f, a) -> loop f a
564 | Cast _ | Evar _ -> loop c [| |]
565 | _ -> c, [| |]
566
567 let filter_upat env sigma i0 f n u fpats =
568 let open EConstr in
569 let na = Array.length u.up_a in
570 if n < na then fpats else
571 let np = match u.up_k with
572 | KpatConst when eq_constr_nounivs sigma u.up_f f -> na
573 | KpatFixed when eq_constr_nounivs sigma u.up_f f -> na
574 | KpatEvar k when isEvar_k sigma k f -> na
575 | KpatLet when isLetIn sigma f -> na
576 | KpatLam when isLambda sigma f -> na
577 | KpatRigid when isRigid sigma f -> na
578 | KpatFlex -> na
579 | KpatProj pc ->
580 let np = na + nb_cs_proj_args env sigma pc f u in if n < np then -1 else np
581 | _ -> -1 in
582 if np < na then fpats else
583 let () = if !i0 < np then i0 := n in (u, np) :: fpats
584
585 let eq_prim_proj env sigma c t = match EConstr.kind sigma t with
586 | Proj(p,_,_) -> Environ.QConstant.equal env (Projection.constant p) c
587 | _ -> false
588
589 let filter_upat_FO env sigma i0 f n u fpats =
590 let open EConstr in
591 let np = nb_args sigma (snd u.up_FO) in
592 if n < np then fpats else
593 let ok = match u.up_k with
594 | KpatConst -> eq_constr_nounivs sigma u.up_f f
595 | KpatFixed -> eq_constr_nounivs sigma u.up_f f
596 | KpatEvar k -> isEvar_k sigma k f
597 | KpatLet -> isLetIn sigma f
598 | KpatLam -> isLambda sigma f
599 | KpatRigid -> isRigid sigma f
600 | KpatProj pc -> isRefX env sigma (ConstRef pc) f || eq_prim_proj env sigma pc f
601 | KpatFlex -> i0 := n; true in
602 if ok then begin if !i0 < np then i0 := np; (u, np) :: fpats end else fpats
603
604 exception FoundUnif of (bool * evar_map * UState.t * tpattern)
605 (* Note: we don't update env as we descend into the term, as the primitive *)
606 (* unification procedure always rejects subterms with bound variables. *)
607
608 let dont_impact_evars_in sigma0 cl =
609 let evs_in_cl = Evd.evars_of_term sigma0 cl in
610 fun sigma -> Evar.Set.for_all (fun k ->
611 try let _ = Evd.find_undefined sigma k in true
612 with Not_found -> false) evs_in_cl
613
614 (* We are forced to duplicate code between the FO/HO matching because we *)
615 (* have to work around several kludges in unify.ml: *)
616 (* - w_unify drops into second-order unification when the pattern is an *)
617 (* application whose head is a meta. *)
618 (* - w_unify tries to unify types without subsumption when the pattern *)
619 (* head is an evar or meta (e.g., it fails on ?1 = nat when ?1 : Type). *)
620 (* - w_unify expands let-in (zeta conversion) eagerly, whereas we want to *)
621 (* match a head let rigidly. *)
622 let match_upats_FO upats env sigma0 ise orig_c =
623 let dont_impact_evars = dont_impact_evars_in sigma0 orig_c in
624 let rec loop c =
625 let f, a = splay_app ise c in let i0 = ref (-1) in
626 let fpats =
627 List.fold_right (filter_upat_FO env ise i0 f (Array.length a)) upats [] in
628 while !i0 >= 0 do
629 let i = !i0 in i0 := -1;
630 let c' = mkSubApp f i a in
631 let one_match (u, np) =
632 let open EConstr in
633 let skip =
634 if i <= np then i < np else
635 if u.up_k == KpatFlex then begin i0 := i - 1; false end else
636 begin if !i0 < np then i0 := np; true end in
637 if skip || not (EConstr.Vars.closed0 ise c') then () else try
638 let () = match u.up_k with
639 | KpatFlex ->
640 let kludge v = mkLambda (make_annot Anonymous ERelevance.relevant, mkProp, v) in
641 let (metas, p_FO) = u.up_FO in
642 unif_FO env ise metas (kludge p_FO) (kludge c')
643 | KpatLet ->
644 let kludge vla =
645 let vl, a = safeDestApp ise vla in
646 let x, v, t, b = destLetIn ise vl in
647 mkApp (mkLambda (x, t, b), Array.cons v a)
648 in
649 let (metas, p_FO) = u.up_FO in
650 unif_FO env ise metas (kludge p_FO) (kludge c')
651 | _ ->
652 let (metas, p_FO) = u.up_FO in
653 unif_FO env ise metas p_FO c'
654 in
655 let ise' = (* Unify again using HO to assign evars *)
656 if u.up_k = KpatConst then
657 try
658 let ise = unif_HO env ise u.up_f f in
659 unif_HO_args env ise u.up_a (i - Array.length u.up_a) a
660 with e when CErrors.noncritical e -> raise NoMatch
661 else
662 let p = mkApp (u.up_f, u.up_a) in
663 try unif_HO env ise p c'
664 with e when CErrors.noncritical e -> raise NoMatch in
665 let lhs = mkSubApp f i a in
666 let pt' = unif_end env sigma0 ise' u.up_t (u.up_ok lhs) in
667 if option_LegacyFoUnif () || Evar.Set.equal
668 (Evd.evars_of_term ise' (mkApp (u.up_f, u.up_a)))
669 (Evd.evars_of_term ise' lhs)
670 then raise (FoundUnif (ungen_upat lhs pt' u))
671 else (pp(lazy(str "not ground" ++ pr_econstr_pat env ise' (mkApp (u.up_f, u.up_a))));raise NoMatch)
672 with FoundUnif (_, s,_,_) as sig_u when dont_impact_evars s -> raise sig_u
673 | Not_found -> CErrors.anomaly (str"incomplete ise in match_upats_FO.")
674 | e when CErrors.noncritical e -> pp(lazy(str"FO fail: " ++ CErrors.print_no_report e)); () in
675 List.iter one_match fpats
676 done;
677 iter_constr_LR ise loop f; Array.iter loop a in
678 try loop orig_c with Invalid_argument _ -> CErrors.anomaly (str"IN FO.")
679
680
681 let match_upats_HO ~on_instance upats env sigma0 ise c =
682 let dont_impact_evars = dont_impact_evars_in sigma0 c in
683 let it_did_match = ref false in
684 let failed_because_of_TC = ref false in
685 let rec aux upats env sigma0 ise c =
686 let f, a = splay_app ise c in let i0 = ref (-1) in
687 let fpats =
688 List.fold_right (filter_upat env ise i0 f (Array.length a)) upats []
689 in
690 while !i0 >= 0 do
691 let i = !i0 in i0 := -1;
692 let one_match (u, np) =
693 let skip =
694 if i <= np then i < np else
695 if u.up_k == KpatFlex then begin i0 := i - 1; false end else
696 begin if !i0 < np then i0 := np; true end in
697 if skip then () else try
698 let ise' = match u.up_k with
699 | KpatFixed | KpatConst -> ise
700 | KpatEvar _ ->
701 let open EConstr in
702 let pka = Evd.expand_existential ise @@ destEvar ise u.up_f in
703 let ka = Evd.expand_existential ise @@ destEvar ise f in
704 let fold ise pk k = unif_HO env ise pk k in
705 List.fold_left2 fold ise pka ka
706 | KpatLet ->
707 let open EConstr in
708 let x, v, t, b = destLetIn ise f in
709 let _, pv, _, pb = destLetIn ise u.up_f in
710 let ise' = unif_HO env ise pv v in
711 unif_HO
712 (EConstr.push_rel (Context.Rel.Declaration.LocalAssum(x, t)) env)
713 ise' pb b
714 | KpatFlex | KpatProj _ ->
715 let fa = mkSubApp f (i - Array.length u.up_a) a in
716 let ise =
717 match EConstr.kind ise f, EConstr.kind ise u.up_f with
718 | Proj _, _ | _, Proj _ ->
719 (* with primitive projections we "lose" parameters so we unify
720 * the type of the arguments to retrieve that information *)
721 let tuf = Retyping.get_type_of ~lax:true env ise u.up_f in
722 let tfa = Retyping.get_type_of ~lax:true env ise fa in
723 unif_HO env ise tuf tfa
724 | _ -> ise in
725 pp(lazy(str"FLEX " ++ pr_econstr_env env ise u.up_f ++ str" = " ++ pr_econstr_env env ise fa));
726 unif_HO env ise u.up_f fa
727 | _ -> unif_HO env ise u.up_f f in
728 let ise'' = unif_HO_args env ise' u.up_a (i - Array.length u.up_a) a in
729 let lhs = mkSubApp f i a in
730 let pt' = unif_end env sigma0 ise'' u.up_t (u.up_ok lhs) in
731 on_instance (ungen_upat lhs pt' u)
732 with FoundUnif (_,s,_,_) as sig_u when dont_impact_evars s -> raise sig_u
733 | NoProgress -> it_did_match := true
734 | Pretype_errors.PretypeError
735 (_,_,Pretype_errors.UnsatisfiableConstraints _) ->
736 failed_because_of_TC:=true
737 | e when CErrors.noncritical e -> () in
738 List.iter one_match fpats
739 done;
740 iter_constr_LR ise (aux upats env sigma0 ise) f;
741 Array.iter (aux upats env sigma0 ise) a
742 in
743 aux upats env sigma0 ise c;
744 if !it_did_match then raise NoProgress;
745 !failed_because_of_TC
746
747
748 let fixed_upat evd = function
749 | {up_k = KpatFlex | KpatEvar _ | KpatProj _} -> false
750 | {up_t = t} -> not (occur_existential evd t)
751
752 let do_once r f = match !r with Some _ -> () | None -> r := Some (f ())
753
754 let assert_done r =
755 match !r with Some x -> x | None -> CErrors.anomaly (str"do_once never called.")
756
757 let assert_done_multires r =
758 match !r with
759 | None -> CErrors.anomaly (str"do_once never called.")
760 | Some (e, n, xs) ->
761 r := Some (e, n+1,xs);
762 try List.nth xs n with Failure _ -> raise NoMatch
763
764 type subst = Environ.env -> EConstr.t -> EConstr.t -> int -> EConstr.t
765 type find_P =
766 Environ.env -> EConstr.t -> int ->
767 k:subst ->
768 EConstr.t
769 type conclude = unit ->
770 EConstr.t * ssrdir * (bool * Evd.evar_map * UState.t * EConstr.t)
771
772 let rec uniquize = function
773 | [] -> []
774 | (_, sigma,_,{ up_f = f; up_a = a; up_t = t } as x) :: xs ->
775 let nf_evar sigma c = EConstr.Unsafe.to_constr (Evarutil.nf_evar sigma c) in
776 let equal sigma1 sigma2 c1 c2 = Constr.equal (nf_evar sigma1 c1) (nf_evar sigma2 c2) in
777 let neq (_, sigma1,_,{ up_f = f1; up_a = a1; up_t = t1 }) =
778 not (equal sigma sigma1 t t1 &&
779 equal sigma sigma1 f f1 && CArray.for_all2 (equal sigma sigma1) a a1) in
780 x :: uniquize (List.filter neq xs)
781
782 type occ_state = {
783 max_occ : int;
784 nocc : int ref;
785 occ_set : bool array;
786 use_occ : bool;
787 skip_occ : bool ref;
788 }
789
790 let create_occ_state occ =
791 let nocc = ref 0 and skip_occ = ref false in
792 let use_occ, occ_list = match occ with
793 | Some (true, ol) -> ol = [], ol
794 | Some (false, ol) -> ol <> [], ol
795 | None -> false, [] in
796 let max_occ = List.fold_right max occ_list 0 in
797 let occ_set = Array.make max_occ (not use_occ) in
798 let _ = List.iter (fun i -> occ_set.(i - 1) <- use_occ) occ_list in
799 let _ = if max_occ = 0 then skip_occ := use_occ in
800 { max_occ; nocc; occ_set; skip_occ; use_occ }
801
802 let subst_occ { nocc; max_occ; occ_set; use_occ; skip_occ } =
803 incr nocc;
804 if !nocc = max_occ then skip_occ := use_occ;
805 if !nocc <= max_occ then occ_set.(!nocc - 1) else not use_occ
806
807 let match_EQ env sigma (ise, u) =
808 let open EConstr in
809 match u.up_k with
810 | KpatLet ->
811 let x, pv, t, pb = destLetIn sigma u.up_f in
812 let env' =
813 EConstr.push_rel (Context.Rel.Declaration.LocalAssum(x, t)) env in
814 let match_let f = match EConstr.kind ise f with
815 | LetIn (_, v, _, b) -> unif_EQ env sigma pv v && unif_EQ env' sigma pb b
816 | _ -> false in match_let
817 | KpatFixed -> fun c -> EConstr.eq_constr_nounivs sigma u.up_f c
818 | KpatConst -> fun c -> EConstr.eq_constr_nounivs sigma u.up_f c
819 | KpatLam -> fun c ->
820 (match EConstr.kind sigma c with
821 | Lambda _ -> unif_EQ env sigma u.up_f c
822 | _ -> false)
823 | _ -> unif_EQ env sigma u.up_f
824
825 let p2t p = EConstr.mkApp(p.up_f,p.up_a)
826
827 let source env ise upats_origin upats = match upats_origin, upats with
828 | None, [p] ->
829 (if fixed_upat ise p then str"term " else str"partial term ") ++
830 pr_econstr_pat env ise (p2t p) ++ spc()
831 | Some (dir,rule), [p] -> str"The " ++ pr_dir_side dir ++ str" of " ++
832 pr_econstr_pat env ise rule ++ fnl() ++ ws 4 ++ pr_econstr_pat env ise (p2t p) ++ fnl()
833 | Some (dir,rule), _ -> str"The " ++ pr_dir_side dir ++ str" of " ++
834 pr_econstr_pat env ise rule ++ spc()
835 | _, [] | None, _::_::_ ->
836 CErrors.anomaly (str"mk_tpattern_matcher with no upats_origin.")
837
838 type ssrmatching_failure =
839 | SsrTCFail
840 | SsrMatchFail
841 | SsrProgressFail
842 | SsrOccMissing of int * int * EConstr.t
843
844 let pr_ssrmatching_failure env sigma upats_origin upats = function
845 | SsrTCFail ->
846 source env sigma upats_origin upats ++ strbrk"matches but type classes inference fails"
847 | SsrMatchFail ->
848 source env sigma upats_origin upats ++ str "does not match any subterm of the goal"
849 | SsrProgressFail ->
850 let dir = match upats_origin with Some (d,_) -> d | _ ->
851 CErrors.anomaly (str"mk_tpattern_matcher with no upats_origin.")
852 in
853 str"all matches of "++ source env sigma upats_origin upats ++ str"are equal to the " ++ pr_dir_side (inv_dir dir)
854 | SsrOccMissing (nocc, max_occ, p') ->
855 str"Only " ++ int nocc ++ str" < " ++ int max_occ ++
856 str(String.plural nocc " occurrence") ++ match upats_origin with
857 | None -> str" of" ++ spc() ++ pr_econstr_pat env sigma p'
858 | Some (dir,rule) -> str" of the " ++ pr_dir_side dir ++ fnl() ++
859 ws 4 ++ pr_econstr_pat env sigma p' ++ fnl () ++
860 str"of " ++ pr_econstr_pat env sigma rule
861
862 exception SsrMatchingFailure of
863 Environ.env * Evd.evar_map * (ssrdir * EConstr.t) option * tpattern list * ssrmatching_failure
864
865 let _ = CErrors.register_handler begin function
866 | SsrMatchingFailure (env, sigma, upats_origin, upats, e) ->
867 Some (pr_ssrmatching_failure env sigma upats_origin upats e)
868 | _ -> None
869 end
870
871 let ssrfail env sigma upats_origin upats e =
872 raise (SsrMatchingFailure (env, sigma, upats_origin, upats, e))
873
874 let has_instances = function
875 | None -> false
876 | Some instances -> not (List.is_empty !instances)
877
878 let find_tpattern ~disable_FO ~raise_NoMatch ~instances ~upat_that_matched ~upats_origin ~upats sigma0 ise occ_state : find_P =
879 fun env c h ~k ->
880 do_once upat_that_matched (fun () ->
881 let failed_because_of_TC = ref false in
882 try
883 let () = match instances with
884 | None when not disable_FO -> match_upats_FO upats env sigma0 ise c
885 | _ -> ()
886 in
887 let on_instance = match instances with
888 | None -> fun x -> raise (FoundUnif x)
889 | Some r -> fun x -> r := !r @ [x]
890 in
891 failed_because_of_TC:=match_upats_HO ~on_instance upats env sigma0 ise c;
892 raise NoMatch
893 with FoundUnif sigma_u -> env,0,[sigma_u]
894 | (NoMatch|NoProgress) when has_instances instances ->
895 env, 0, uniquize (!(Option.get instances))
896 | NoMatch when (not raise_NoMatch) ->
897 if !failed_because_of_TC then ssrfail env ise upats_origin upats SsrTCFail
898 else ssrfail env ise upats_origin upats SsrMatchFail
899 | NoProgress when (not raise_NoMatch) ->
900 ssrfail env ise upats_origin upats SsrProgressFail
901 | NoProgress -> raise NoMatch);
902 let _, sigma, _, ({up_f = pf; up_a = pa} as u) = match instances with
903 | Some _ -> assert_done_multires upat_that_matched
904 | None -> List.hd (pi3(assert_done upat_that_matched))
905 in
906 (* pp(lazy(str"sigma@tmatch=" ++ pr_evar_map None sigma)); *)
907 if !(occ_state.skip_occ) then ((*ignore(k env u.up_t 0);*) c) else
908 let match_EQ = match_EQ env sigma (ise, u) in
909 let pn = Array.length pa in
910 let rec subst_loop (env,h as acc) c' =
911 if !(occ_state.skip_occ) then c' else
912 let f, a = splay_app sigma c' in
913 if Array.length a >= pn && match_EQ f && unif_EQ_args env sigma pa a then
914 let open EConstr in
915 let a1, a2 = Array.chop (Array.length pa) a in
916 let fa1 = mkApp (f, a1) in
917 let f' = if subst_occ occ_state then k env u.up_t fa1 h else fa1 in
918 mkApp (f', Array.map_left (subst_loop acc) a2)
919 else
920 let open EConstr in
921 (* TASSI: clear letin values to avoid unfolding *)
922 let inc_h rd (env,h') =
923 let ctx_item =
924 match rd with
925 | Context.Rel.Declaration.LocalAssum _ as x -> x
926 | Context.Rel.Declaration.LocalDef (x,_,y) ->
927 Context.Rel.Declaration.LocalAssum(x,y) in
928 EConstr.push_rel ctx_item env, h' + 1 in
929 let self acc c = subst_loop acc c in
930 let f' = map_constr_with_binders_left_to_right env sigma inc_h self acc f in
931 mkApp (f', Array.map_left (subst_loop acc) a) in
932 subst_loop (env,h) c
933
934 let conclude_tpattern ~raise_NoMatch ~upat_that_matched ~upats_origin ~upats { max_occ; nocc } : conclude = fun () ->
935 let env, (c, sigma, uc, ({up_f = pf; up_a = pa} as u)) =
936 match !upat_that_matched with
937 | Some (env,_,x) -> env,List.hd x | None when raise_NoMatch -> raise NoMatch
938 | None -> CErrors.anomaly (str"companion function never called.") in
939 let p' = EConstr.mkApp (pf, pa) in
940 if max_occ <= !nocc then p', u.up_dir, (c, sigma, uc, u.up_t)
941 else ssrfail env sigma upats_origin upats (SsrOccMissing (!nocc, max_occ, p'))
942
943 (* upats_origin makes a better error message only *)
944 let mk_tpattern_matcher ?(all_instances=false)
945 ?(raise_NoMatch=false) ?upats_origin sigma0 occ { tpat_sigma = ise; tpat_pats = upats }
946 =
947 let occ_state = create_occ_state occ in
948 let upat_that_matched = ref None in
949 let instances = if all_instances then Some (ref []) else None in
950 let disable_FO = occ = Some(true,[1]) in
951 find_tpattern ~disable_FO ~raise_NoMatch ~instances ~upat_that_matched ~upats_origin ~upats sigma0 ise occ_state,
952 conclude_tpattern ~raise_NoMatch ~upat_that_matched ~upats_origin ~upats occ_state
953
954 type ('inpat, 'term) ssrpattern =
955 | T of 'term
956 | In_T of 'term
957 | X_In_T of 'inpat
958 | In_X_In_T of 'inpat
959 | E_In_X_In_T of 'term * 'inpat
960 | E_As_X_In_T of 'term * 'inpat
961
962 let pr_in_pattern pr_ident pr_term (x, t) =
963 pr_ident x ++ str " in " ++ pr_term t
964
965 let pr_pattern pr_ident pr_term = function
966 | T t -> pr_term t
967 | In_T t -> str "in " ++ pr_term t
968 | X_In_T p -> pr_in_pattern pr_ident pr_term p
969 | In_X_In_T p -> str "in " ++ pr_in_pattern pr_ident pr_term p
970 | E_In_X_In_T (e, p) ->
971 pr_term e ++ str " in " ++ pr_in_pattern pr_ident pr_term p
972 | E_As_X_In_T (e, p) ->
973 pr_term e ++ str " as " ++ pr_in_pattern pr_ident pr_term p
974
975 let pr_hole pr_constr e = pr_constr (EConstr.mkEvar e)
976
977 type in_pattern = {
978 in_hole : EConstr.existential;
979 in_func : EConstr.t;
980 in_patt : EConstr.t; (* in_patt := in_func{#1 := in_hole} *)
981 }
982
983 let pr_in_pattern_aux pr_constr { in_hole = x; in_patt = t} =
984 pr_hole pr_constr x ++ str " in " ++ pr_constr t
985
986 let pr_pattern_aux pr_constr = function
987 | T t -> pr_constr t
988 | In_T t -> str "in " ++ pr_constr t
989 | X_In_T p -> pr_in_pattern_aux pr_constr p
990 | In_X_In_T p -> str "in " ++ pr_in_pattern_aux pr_constr p
991 | E_In_X_In_T (e, p) ->
992 pr_constr e ++ str " in " ++ pr_in_pattern_aux pr_constr p
993 | E_As_X_In_T (e, p) ->
994 pr_constr e ++ str " as " ++ pr_in_pattern_aux pr_constr p
995
996 type pattern = {
997 pat_sigma : Evd.evar_map;
998 pat_pat : (in_pattern, EConstr.t) ssrpattern;
999 }
1000
1001 let pp_pattern env { pat_sigma = sigma; pat_pat = p } =
1002 pr_pattern_aux (fun t -> pr_econstr_pat env sigma t) p
1003
1004 type cpattern =
1005 { kind : ssrtermkind
1006 ; pattern : Genintern.glob_constr_and_expr
1007 ; interpretation : Geninterp.interp_sign option }
1008
1009 let pr_term {kind; pattern; _} =
1010 let env = Global.env () in
1011 let sigma = Evd.from_env env in
1012 pr_guarded (guard_term kind) (pr_glob_constr_and_expr env sigma) pattern
1013 let prl_term {kind; pattern; _} =
1014 let env = Global.env () in
1015 let sigma = Evd.from_env env in
1016 pr_guarded (guard_term kind) (prl_glob_constr_and_expr env sigma) pattern
1017
1018 let pr_cpattern = pr_term
1019
1020 let pr_pattern_w_ids = pr_pattern pr_id prl_term
1021
1022 let mk_term k c ist = {kind=k; pattern=(mkRHole, Some c); interpretation=ist}
1023 let mk_lterm = mk_term NoFlag
1024
1025 let glob_ssrterm gs = function
1026 | {kind; pattern=(_, Some c); interpretation=None} ->
1027 let x = Tacintern.intern_constr gs c in
1028 {kind; pattern=(fst x, Some c); interpretation=None}
1029 | ct -> ct
1030
1031 (* ssrterm conbinators *)
1032 let combineCG t1 t2 f g =
1033 let mk_ist i1 i2 = match i1, i2 with
1034 | None, Some i -> Some i
1035 | Some i, None -> Some i
1036 | None, None -> None
1037 | Some i, Some j when i == j -> Some i
1038 | _ -> CErrors.anomaly (Pp.str "combineCG: different ist") in
1039 match t1, t2 with
1040 | {kind=x; pattern=(t1, None); interpretation=i1}, {pattern=(t2, None); interpretation=i2} ->
1041 {kind=x; pattern=(g t1 t2, None); interpretation = mk_ist i1 i2}
1042 | {kind=x; pattern=(_, Some t1); interpretation=i1}, {pattern=(_, Some t2); interpretation=i2} ->
1043 {kind=x; pattern=(mkRHole, Some (f t1 t2)); interpretation = mk_ist i1 i2}
1044 | _, {pattern=(_, None); _} -> CErrors.anomaly (str"have: mixed C-G constr.")
1045 | _ -> CErrors.anomaly (str"have: mixed G-C constr.")
1046 let loc_ofCG = function
1047 | {pattern = (s, None); _} -> Glob_ops.loc_of_glob_constr s
1048 | {pattern = (_, Some s); _} -> Constrexpr_ops.constr_loc s
1049
1050 (* This piece of code asserts the following notations are reserved *)
1051 (* Reserved Notation "( a 'in' b )" (at level 0). *)
1052 (* Reserved Notation "( a 'as' b )" (at level 0). *)
1053 (* Reserved Notation "( a 'in' b 'in' c )" (at level 0). *)
1054 (* Reserved Notation "( a 'as' b 'in' c )" (at level 0). *)
1055 let glob_cpattern gs p =
1056 pp(lazy(str"globbing pattern: " ++ pr_term p));
1057 let glob x = (glob_ssrterm gs (mk_lterm x None)).pattern in
1058 let encode k s l =
1059 let name = Name (Id.of_string ("_ssrpat_" ^ s)) in
1060 {kind=k; pattern=(mkRCast mkRHole (mkRLambda name mkRHole (mkRApp mkRHole l)), None); interpretation=None} in
1061 let bind_in t1 t2 =
1062 let mkCHole = mkCHole ~loc:None in let n = Name (destCVar t1) in
1063 fst (glob (mkCCast mkCHole (mkCLambda n mkCHole t2))) in
1064 let check_var t2 = if not (isCVar t2) then
1065 loc_error (constr_loc t2) "Only identifiers are allowed here" in
1066 match p with
1067 | {pattern = (_, None); _} as x -> x
1068 | {kind=k; pattern=(v, Some t); _} as orig ->
1069 if k = Cpattern then glob_ssrterm gs {kind=InParens; pattern=(v, Some t); interpretation=None} else
1070 match t.CAst.v with
1071 | CNotation(_,(InConstrEntry,"( _ in _ )"), ([t1; t2], [], [], [])) ->
1072 (try match glob t1, glob t2 with
1073 | (r1, None), (r2, None) -> encode k "In" [r1;r2]
1074 | (r1, Some _), (r2, Some _) when isCVar t1 ->
1075 encode k "In" [r1; r2; bind_in t1 t2]
1076 | (r1, Some _), (r2, Some _) -> encode k "In" [r1; r2]
1077 | _ -> CErrors.anomaly (str"where are we?.")
1078 with e when CErrors.noncritical e && isCVar t1 -> encode k "In" [bind_in t1 t2])
1079 | CNotation(_,(InConstrEntry,"( _ in _ in _ )"), ([t1; t2; t3], [], [], [])) ->
1080 check_var t2; encode k "In" [fst (glob t1); bind_in t2 t3]
1081 | CNotation(_,(InConstrEntry,"( _ as _ )"), ([t1; t2], [], [], [])) ->
1082 encode k "As" [fst (glob t1); fst (glob t2)]
1083 | CNotation(_,(InConstrEntry,"( _ as _ in _ )"), ([t1; t2; t3], [], [], [])) ->
1084 check_var t2; encode k "As" [fst (glob t1); bind_in t2 t3]
1085 | _ -> glob_ssrterm gs orig
1086
1087 let glob_in_pattern s (x, t) =
1088 (x, glob_ssrterm s t)
1089
1090 let glob_rpattern s p =
1091 match p with
1092 | T t -> T (glob_cpattern s t)
1093 | In_T t -> In_T (glob_ssrterm s t)
1094 | X_In_T p -> X_In_T (glob_in_pattern s p)
1095 | In_X_In_T p -> In_X_In_T (glob_in_pattern s p)
1096 | E_In_X_In_T (e, p) -> E_In_X_In_T (glob_ssrterm s e, glob_in_pattern s p)
1097 | E_As_X_In_T (e, p) -> E_As_X_In_T (glob_ssrterm s e, glob_in_pattern s p)
1098
1099 let subst_ssrterm s {kind; pattern; interpretation} =
1100 {kind; pattern=Tacsubst.subst_glob_constr_and_expr s pattern; interpretation}
1101
1102 let subst_in_pattern s (x, t) =
1103 (x, subst_ssrterm s t)
1104
1105 let subst_rpattern s = function
1106 | T t -> T (subst_ssrterm s t)
1107 | In_T t -> In_T (subst_ssrterm s t)
1108 | X_In_T p -> X_In_T (subst_in_pattern s p)
1109 | In_X_In_T p -> In_X_In_T (subst_in_pattern s p)
1110 | E_In_X_In_T (e, p) -> E_In_X_In_T (subst_ssrterm s e, subst_in_pattern s p)
1111 | E_As_X_In_T (e, p) -> E_As_X_In_T (subst_ssrterm s e, subst_in_pattern s p)
1112
1113 let interp_ssrterm ist {kind; pattern; _} = {kind; pattern; interpretation = Some ist}
1114
1115 let interp_inpattern s (x, t) =
1116 (interp_ssrterm s x, interp_ssrterm s t)
1117
1118 let interp_rpattern s = function
1119 | T t -> T (interp_ssrterm s t)
1120 | In_T t -> In_T (interp_ssrterm s t)
1121 | X_In_T p -> X_In_T (interp_inpattern s p)
1122 | In_X_In_T p -> In_X_In_T (interp_inpattern s p)
1123 | E_In_X_In_T (e, p) ->
1124 E_In_X_In_T (interp_ssrterm s e, interp_inpattern s p)
1125 | E_As_X_In_T (e, p) ->
1126 E_As_X_In_T (interp_ssrterm s e, interp_inpattern s p)
1127
1128 let interp_rpattern0 ist _ _ t = interp_rpattern ist t
1129
1130 let tag_of_cpattern p = p.kind
1131 let loc_of_cpattern = loc_ofCG
1132 type occ = (bool * int list) option
1133
1134 type rpattern = (cpattern * cpattern, cpattern) ssrpattern
1135 let pr_rpattern = pr_pattern pr_cpattern pr_cpattern
1136
1137 let wit_rpatternty = add_genarg "rpatternty" (fun env sigma -> pr_pattern pr_cpattern pr_cpattern)
1138
1139 let id_of_cpattern {pattern = (c1, c2); _} =
1140 let open CAst in
1141 match DAst.get c1, c2 with
1142 | _, Some { v = CRef (qid, _) } when qualid_is_ident qid ->
1143 Some (qualid_basename qid)
1144 | _, Some { v = CAppExpl ((qid, _), []) } when qualid_is_ident qid ->
1145 Some (qualid_basename qid)
1146 | GRef (GlobRef.VarRef x, _), None -> Some x
1147 | _ -> None
1148 let id_of_Cterm t = match id_of_cpattern t with
1149 | Some x -> x
1150 | None -> loc_error (loc_of_cpattern t) "Only identifiers are allowed here"
1151
1152 let interp_open_constr ist env sigma gc =
1153 Tacinterp.interp_open_constr ist env sigma gc
1154 let pf_intern_term env sigma {pattern = c; interpretation = ist; _} = glob_constr ist env sigma c
1155
1156 let interp_ssrterm ist env sigma t = interp_ssrterm ist t
1157
1158 let interp_term env sigma = function
1159 | {pattern = c; interpretation = Some ist; _} -> interp_open_constr ist env sigma c
1160 | _ -> errorstrm (str"interpreting a term with no ist")
1161
1162 let thin id sigma goal =
1163 let ids = Id.Set.singleton id in
1164 let evi = Evd.find_undefined sigma goal in
1165 let env = Evd.evar_filtered_env (Global.env ()) evi in
1166 let cl = Evd.evar_concl evi in
1167 let relevance = Evd.evar_relevance evi in
1168 let ans =
1169 try Some (Evarutil.clear_hyps_in_evi env sigma (Environ.named_context_val env) cl ids)
1170 with Evarutil.ClearDependencyError _ -> None
1171 in
1172 match ans with
1173 | None -> sigma
1174 | Some (sigma, hyps, concl) ->
1175 let (sigma, evk) =
1176 Evarutil.new_pure_evar ~src:(Loc.tag Evar_kinds.GoalEvar) ~typeclass_candidate:false hyps sigma ~relevance concl
1177 in
1178 let sigma = Evd.remove_future_goal sigma evk in
1179 let sigma = Evd.transfer_name goal evk sigma in
1180 let proof = EConstr.mkEvar (evk, Evd.evar_identity_subst @@ Evd.find_undefined sigma evk) in
1181 Evd.define goal proof sigma
1182
1183 (*
1184 let pr_ist { lfun= lfun } =
1185 prlist_with_sep spc
1186 (fun (id, Geninterp.Val.Dyn(ty,_)) ->
1187 pr_id id ++ str":" ++ Geninterp.Val.pr ty) (Id.Map.bindings lfun)
1188 *)
1189
1190 let decode_pattern ?wit_ssrpatternarg env sigma0 red =
1191 pp(lazy(str"interpreting: " ++ pr_rpattern red));
1192 let xInT x y = X_In_T(x,y) and inXInT x y = In_X_In_T(x,y) in
1193 let inT x = In_T x and eInXInT e x t = E_In_X_In_T (e, (x, t)) in
1194 let eAsXInT e x t = E_As_X_In_T (e, (x, t)) in
1195 let mkG ?(k=NoFlag) x ist = {kind = k; pattern = (x,None); interpretation = ist } in
1196 let decode ({interpretation=ist; _} as t) ?reccall f g =
1197 try match DAst.get (pf_intern_term env sigma0 t) with
1198 | GCast(t, Some DEFAULTcast, c) when isGHole t && isGLambda c->
1199 let (x, c) = destGLambda c in
1200 f x {kind = NoFlag; pattern = (c,None); interpretation = ist}
1201 | GVar id
1202 when Option.has_some ist && let ist = Option.get ist in
1203 Id.Map.mem id ist.lfun &&
1204 not(Option.is_empty reccall) &&
1205 not(Option.is_empty wit_ssrpatternarg) ->
1206 let v = Id.Map.find id (Option.get ist).lfun in
1207 Option.get reccall
1208 (Value.cast (topwit (Option.get wit_ssrpatternarg)) v)
1209 | it -> g t with e when CErrors.noncritical e -> g t in
1210 let decodeG ist t f g = decode (mkG t ist) f g in
1211 let bad_enc id _ = CErrors.anomaly (str"bad encoding for pattern "++str id++str".") in
1212 let red = let rec decode_red = function
1213 | T {kind=k; pattern=(t,None); interpretation=ist} ->
1214 begin match DAst.get t with
1215 | GCast (c, Some DEFAULTcast, t)
1216 when isGHole c &&
1217 let (id, t) = destGLambda t in
1218 let id = Id.to_string id in let len = String.length id in
1219 (len > 8 && String.sub id 0 8 = "_ssrpat_") ->
1220 let (id, t) = destGLambda t in
1221 let id = Id.to_string id in let len = String.length id in
1222 (match String.sub id 8 (len - 8), DAst.get t with
1223 | "In", GApp( _, [t]) -> decodeG ist t xInT (fun x -> T x)
1224 | "In", GApp( _, [e; t]) -> decodeG ist t (eInXInT (mkG e ist)) (bad_enc id)
1225 | "In", GApp( _, [e; t; e_in_t]) ->
1226 decodeG ist t (eInXInT (mkG e ist))
1227 (fun _ -> decodeG ist e_in_t xInT (fun _ -> assert false))
1228 | "As", GApp(_, [e; t]) -> decodeG ist t (eAsXInT (mkG e ist)) (bad_enc id)
1229 | _ -> bad_enc id ())
1230 | _ ->
1231 decode ~reccall:decode_red (mkG ~k t ist) xInT (fun x -> T x)
1232 end
1233 | T t -> decode ~reccall:decode_red t xInT (fun x -> T x)
1234 | In_T t -> decode t inXInT inT
1235 | X_In_T (e,t) -> decode t (eInXInT e) (fun x -> xInT (id_of_Cterm e) x)
1236 | In_X_In_T (e,t) -> inXInT (id_of_Cterm e) t
1237 | E_In_X_In_T (e, (x, rp)) -> eInXInT e (id_of_Cterm x) rp
1238 | E_As_X_In_T (e, (x, rp)) -> eAsXInT e (id_of_Cterm x) rp in
1239 decode_red red in
1240 pp(lazy(str"decoded as: " ++ pr_pattern_w_ids red));
1241 red
1242
1243 let add_pattern_type env sigma0 red (ty,ist) =
1244 let ist_of x = x.interpretation in
1245 let mkG ?(k=NoFlag) x ist = {kind = k; pattern = (x,None); interpretation = ist } in
1246 let ty = {kind=NoFlag; pattern=ty; interpretation = Some ist} in
1247 let red =
1248 match red with
1249 | T t -> T (combineCG t ty (mkCCast ?loc:(loc_ofCG t)) mkRCast)
1250 | X_In_T (x, t) ->
1251 let gty = pf_intern_term env sigma0 ty in
1252 E_As_X_In_T (mkG (mkRCast mkRHole gty) (ist_of ty), (x, t))
1253 | E_In_X_In_T (e, (x, t)) ->
1254 let ty = mkG (pf_intern_term env sigma0 ty) (ist_of ty) in
1255 E_In_X_In_T (combineCG e ty (mkCCast ?loc:(loc_ofCG t)) mkRCast, (x, t))
1256 | E_As_X_In_T (e, (x, t)) ->
1257 let ty = mkG (pf_intern_term env sigma0 ty) (ist_of ty) in
1258 E_As_X_In_T (combineCG e ty (mkCCast ?loc:(loc_ofCG t)) mkRCast, (x, t))
1259 | red -> red in
1260 pp(lazy(str"typed as: " ++ pr_pattern_w_ids red));
1261 red
1262
1263 let cleanup_XinE env sigma0 (h_k, _) x rp sigma =
1264 let to_clean, update = (* handle rename if x is already used *)
1265 let ctx = Environ.named_context env in
1266 let len = Context.Named.length ctx in
1267 let name = ref None in
1268 try ignore(Context.Named.lookup x ctx); (name, fun k ->
1269 if !name = None then
1270 let EvarInfo evi = Evd.find sigma k in
1271 let nctx = Evd.evar_context evi in
1272 let nlen = Context.Named.length nctx in
1273 if nlen > len then begin
1274 name := Some (Context.Named.Declaration.get_id (List.nth nctx (nlen - len - 1)))
1275 end)
1276 with Not_found -> ref (Some x), fun _ -> () in
1277 let new_evars =
1278 let rec aux acc t = match EConstr.kind sigma t with
1279 | Evar (k,_) ->
1280 if k = h_k || List.mem k acc || Evd.mem sigma0 k then acc else
1281 (update k; k::acc)
1282 | _ -> EConstr.fold sigma aux acc t in
1283 aux [] rp in
1284 let sigma =
1285 List.fold_left (fun sigma e ->
1286 if Evd.is_defined sigma e then sigma else (* clear may be recursive *)
1287 if Option.is_empty !to_clean then sigma else
1288 let name = Option.get !to_clean in
1289 pp(lazy(pr_id name));
1290 thin name sigma e)
1291 sigma new_evars in
1292 sigma
1293
1294 let mk_in_pattern env sigma0 (x, rp) =
1295 let sigma = sigma0 in
1296 let ist = match rp.interpretation with
1297 | None -> CErrors.user_err (Pp.str "interpreting a term with no ist")
1298 | Some ist -> ist
1299 in
1300 let src = Loc.tag (BinderType (Name x)) in
1301 let sigma, (ty, s) = Evarutil.new_type_evar env sigma Evd.univ_flexible_alg in
1302 let na = Context.make_annot (Name x) (Retyping.relevance_of_sort s) in
1303 let nenv = EConstr.push_rel (Context.Rel.Declaration.LocalAssum (na, ty)) env in
1304 let sigma, rp0 = Tacinterp.interp_open_constr ist nenv sigma rp.pattern in
1305 let sigma, h = Evarutil.new_evar env sigma ~src ty in
1306 let h = EConstr.destEvar sigma h in
1307 let sigma = cleanup_XinE env sigma0 h x rp0 sigma in
1308 let rp = EConstr.Vars.subst1 (EConstr.mkEvar h) (Evarutil.nf_evar sigma rp0) in
1309 let in_pat = { in_hole = h; in_patt = rp; in_func = rp0 } in
1310 sigma, in_pat
1311
1312 let interp_pattern ?wit_ssrpatternarg env sigma0 red redty =
1313 pp(lazy(str"interpreting: " ++ pr_rpattern red));
1314 let red = decode_pattern ?wit_ssrpatternarg env sigma0 red in
1315 let red =
1316 match redty with
1317 | None -> red
1318 | Some ty -> add_pattern_type env sigma0 red ty in
1319 match red with
1320 | T t -> let sigma, t = interp_term env sigma0 t in { pat_sigma = sigma; pat_pat = T t }
1321 | In_T t -> let sigma, t = interp_term env sigma0 t in { pat_sigma = sigma; pat_pat = In_T t }
1322 | X_In_T p | In_X_In_T p | E_In_X_In_T (_, p) | E_As_X_In_T (_, p) ->
1323 let sigma, in_pat = mk_in_pattern env sigma0 p in
1324 let sigma, p = match red with
1325 | X_In_T _ -> sigma, X_In_T in_pat
1326 | In_X_In_T _ -> sigma, In_X_In_T in_pat
1327 | E_In_X_In_T (e, _) ->
1328 let sigma, e = interp_term env sigma e in
1329 sigma, E_In_X_In_T (e, in_pat)
1330 | E_As_X_In_T (e, _) ->
1331 let sigma, e = interp_term env sigma e in
1332 sigma, E_As_X_In_T (e, in_pat)
1333 | T _ | In_T _ -> assert false
1334 in
1335 { pat_sigma = sigma; pat_pat = p }
1336
1337 let interp_cpattern env sigma red redty = interp_pattern env sigma (T red) redty;;
1338 let interp_rpattern ~wit_ssrpatternarg env sigma red = interp_pattern ~wit_ssrpatternarg env sigma red None;;
1339
1340 let id_of_pattern sigma p = match p.pat_pat with
1341 | T t -> (match EConstr.kind sigma t with Var id -> Some id | _ -> None)
1342 | _ -> None
1343
1344 (* The full occurrence set *)
1345 let noindex = Some(false,[])
1346
1347 (* calls do_subst on every sub-term identified by (pattern,occ) *)
1348 let eval_pattern ?raise_NoMatch env0 sigma0 concl0 pattern occ (do_subst : subst) =
1349 let rigid ev = Evd.mem sigma0 ev in
1350 let fs sigma x = Reductionops.nf_evar sigma x in
1351 let pop_evar sigma { in_hole = (e, args); in_patt = p; in_func = fp } =
1352 let EvarInfo e_def = Evd.find sigma e in
1353 let e_body = match Evd.evar_body e_def with Evar_defined c -> c
1354 | _ -> errorstrm (str "Matching the pattern " ++ pr_econstr_env env0 sigma0 p ++
1355 str " did not instantiate ?" ++ int (Evar.repr e) ++ spc () ++
1356 str "Does the variable bound by the \"in\" construct occur "++
1357 str "in the pattern?") in
1358 (* This code is very suspect because the returned value is the same as p up to
1359 evar expansion *)
1360 let fp = Reductionops.nf_evar sigma fp in
1361 let fp = EConstr.Vars.subst1 (EConstr.mkEvar (e, args)) fp in
1362 fp, e_body
1363 in
1364 let mk_upat_for ?hack ~rigid (sigma, t) =
1365 mk_tpattern ?hack ~rigid env0 t L2R (fs sigma t) (empty_tpatterns sigma)
1366 in
1367 match pattern with
1368 | None -> do_subst env0 concl0 concl0 1, UState.empty
1369 | Some { pat_sigma = sigma; pat_pat = (T rp | In_T rp) } ->
1370 let rp = fs sigma rp in
1371 let ise = create_evar_defs sigma in
1372 let occ = match pattern with Some { pat_pat = T _ } -> occ | _ -> noindex in
1373 let rp = mk_upat_for ~rigid (ise, rp) in
1374 let find_T, end_T = mk_tpattern_matcher ?raise_NoMatch sigma0 occ rp in
1375 let concl = find_T env0 concl0 1 ~k:do_subst in
1376 let _, _, (_, _, us, _) = end_T () in
1377 concl, us
1378 | Some { pat_sigma = sigma; pat_pat = (X_In_T p | In_X_In_T p) } ->
1379 let { in_hole = hole; in_patt = p } as p0 = p in
1380 let p = fs sigma p in
1381 let occ = match pattern with Some { pat_pat = X_In_T _ } -> occ | _ -> noindex in
1382 let hole = EConstr.mkEvar hole in
1383 let rp = mk_upat_for ~hack:true ~rigid (sigma, p) in
1384 let find_T, end_T = mk_tpattern_matcher sigma0 noindex rp in
1385 (* we start from sigma, so hole is considered a rigid head *)
1386 let holep = mk_upat_for ~rigid:(fun ev -> Evd.mem sigma ev) (sigma, hole) in
1387 let find_X, end_X = mk_tpattern_matcher ?raise_NoMatch sigma occ holep in
1388 let concl = find_T env0 concl0 1 ~k:(fun env c _ h ->
1389 let p_sigma = unify_HO env (create_evar_defs sigma) c p in
1390 let p, e_body = pop_evar p_sigma p0 in
1391 fs p_sigma (find_X env p h
1392 ~k:(fun env _ -> do_subst env e_body))) in
1393 let _ = end_X () in let _, _, (_, _, us, _) = end_T () in
1394 concl, us
1395 | Some { pat_sigma = sigma; pat_pat = E_In_X_In_T (e, p) } ->
1396 let { in_hole = hole; in_patt = p } as p0 = p in
1397 let p, e = fs sigma p, fs sigma e in
1398 let hole = EConstr.mkEvar hole in
1399 let rp = mk_upat_for ~hack:true ~rigid (sigma, p) in
1400 let find_T, end_T = mk_tpattern_matcher sigma0 noindex rp in
1401 let holep = mk_upat_for ~rigid:(fun ev -> Evd.mem sigma ev) (sigma, hole) in
1402 let find_X, end_X = mk_tpattern_matcher sigma noindex holep in
1403 let re = mk_upat_for ~rigid (sigma, e) in
1404 let find_E, end_E = mk_tpattern_matcher ?raise_NoMatch sigma0 occ re in
1405 let concl = find_T env0 concl0 1 ~k:(fun env c _ h ->
1406 let p_sigma = unify_HO env (create_evar_defs sigma) c p in
1407 let p, e_body = pop_evar p_sigma p0 in
1408 fs p_sigma (find_X env p h ~k:(fun env c _ h ->
1409 find_E env e_body h ~k:do_subst))) in
1410 let _, _, (_, _, us, _) = end_E () in
1411 let _ = end_X () in let _ = end_T () in
1412 concl, us
1413 | Some { pat_sigma = sigma; pat_pat = E_As_X_In_T (e, p) } ->
1414 let { in_hole = hole; in_patt = p } as p0 = p in
1415 let p, e = fs sigma p, fs sigma e in
1416 let hole = EConstr.mkEvar hole in
1417 let rp =
1418 let e_sigma = unify_HO env0 sigma hole e in
1419 e_sigma, fs e_sigma p in
1420 let rp = mk_upat_for ~hack:true ~rigid rp in
1421 let find_TE, end_TE = mk_tpattern_matcher sigma0 noindex rp in
1422 let holep = mk_upat_for ~rigid:(fun ev -> Evd.mem sigma ev) (sigma, hole) in
1423 let find_X, end_X = mk_tpattern_matcher sigma occ holep in
1424 let concl = find_TE env0 concl0 1 ~k:(fun env c _ h ->
1425 let p_sigma = unify_HO env (create_evar_defs sigma) c p in
1426 let p, e_body = pop_evar p_sigma p0 in
1427 fs p_sigma (find_X env p h ~k:(fun env c _ h ->
1428 let e_sigma = unify_HO env sigma e_body e in
1429 let e_body = fs e_sigma e in
1430 do_subst env e_body e_body h))) in
1431 let _ = end_X () in let _, _ , (_, _, us, _) = end_TE () in
1432 concl, us
1433
1434 let redex_of_pattern { pat_sigma = sigma; pat_pat = p } = match p with
1435 | In_T _ | In_X_In_T _ -> None
1436 | X_In_T { in_hole = e } -> Some (sigma, EConstr.mkEvar e)
1437 | T e | E_As_X_In_T (e, _) | E_In_X_In_T (e, _) -> Some (sigma, e)
1438
1439 let redex_of_pattern_nf env p =
1440 let sigma, e = match redex_of_pattern p with
1441 | None -> CErrors.anomaly (str"pattern without redex.")
1442 | Some (sigma, e) -> sigma, e
1443 in
1444 Evarutil.nf_evar sigma e, Evd.ustate sigma
1445
1446 let fill_occ_pattern ?raise_NoMatch env sigma cl pat occ h =
1447 let do_make_rel, occ =
1448 if occ = Some(true,[]) then false, Some(false,[1]) else true, occ in
1449 let r = ref None in
1450 let find_R env c _ h' =
1451 let () = do_once r (fun () -> c) in
1452 if do_make_rel then EConstr.mkRel (h'+h-1) else c
1453 in
1454 let cl, us =
1455 eval_pattern ?raise_NoMatch env sigma cl (Some pat) occ find_R in
1456 let e = match !r with None -> fst(redex_of_pattern_nf env pat) | Some x -> x in
1457 (e, us), cl
1458
1459 let fill_rel_occ_pattern env sigma cl pat occ =
1460 let (e, us), cl =
1461 try fill_occ_pattern ~raise_NoMatch:true env sigma cl pat occ 1
1462 with NoMatch -> redex_of_pattern_nf env pat, cl
1463 in
1464 let sigma = Evd.merge_universe_context sigma us in
1465 sigma, e, cl
1466
1467 (* clenup interface for external use *)
1468 let mk_tpattern ?p_origin ?ok ~rigid env sigma_t dir c =
1469 mk_tpattern ?p_origin ?ok ~rigid env sigma_t dir c
1470
1471 let eval_pattern ?raise_NoMatch env0 sigma0 concl0 pattern occ do_subst =
1472 fst (eval_pattern ?raise_NoMatch env0 sigma0 concl0 pattern occ do_subst)
1473
1474 let pf_fill_occ env concl occ sigma0 p (sigma, t) h =
1475 let rigid ev = Evd.mem sigma0 ev in
1476 let u = mk_tpattern ~rigid env t L2R p (empty_tpatterns (create_evar_defs sigma)) in
1477 let find_U, end_U = mk_tpattern_matcher ~raise_NoMatch:true sigma0 occ u in
1478 let concl = find_U env concl h ~k:(fun _ _ _ n -> EConstr.mkRel n) in
1479 let rdx, _, (c, sigma, uc, p) = end_U () in
1480 c, sigma, uc, p, concl, rdx
1481
1482 let fill_occ_term env sigma0 cl occ (sigma, t) =
1483 try
1484 let changed, sigma', uc, t', cl, _= pf_fill_occ env cl occ sigma0 t (sigma, t) 1 in
1485 if changed then CErrors.user_err Pp.(str "matching impacts evars")
1486 else cl, t'
1487 with NoMatch -> try
1488 let changed, sigma', uc, t' =
1489 unif_end env sigma0 (create_evar_defs sigma) t (fun _ -> true) in
1490 if changed then raise NoMatch
1491 else cl, t'
1492 with e when CErrors.noncritical e ->
1493 errorstrm (str "partial term " ++ pr_econstr_pat env sigma t
1494 ++ str " does not match any subterm of the goal")
1495
1496 let cpattern_of_id id =
1497 { kind= NoFlag
1498 ; pattern = DAst.make @@ GRef (GlobRef.VarRef id, None), None
1499 ; interpretation =
1500 Some Geninterp.({ lfun = Id.Map.empty;
1501 poly = PolyFlags.default;
1502 extra = Tacinterp.TacStore.empty })}
1503
1504 let is_wildcard ({pattern = (l, r); _} : cpattern) : bool = match DAst.get l, r with
1505 | _, Some { CAst.v = CHole _ } | GHole _, None -> true
1506 | _ -> false
1507
1508 (* "ssrpattern" *)
1509
1510 (** All the pattern types reuse the same dynamic toplevel tag *)
1511 let wit_ssrpatternarg = wit_rpatternty
1512
1513 let interp_rpattern = interp_rpattern ~wit_ssrpatternarg
1514
1515 let ssrpatterntac arg =
1516 let open Proofview.Notations in
1517 Proofview.Goal.enter begin fun gl ->
1518 let sigma0 = Proofview.Goal.sigma gl in
1519 let concl0 = Proofview.Goal.concl gl in
1520 let env = Proofview.Goal.env gl in
1521 let pat = interp_rpattern env sigma0 arg in
1522 let (t, uc), concl_x =
1523 fill_occ_pattern env sigma0 concl0 pat noindex 1 in
1524 let sigma = Evd.set_universe_context sigma0 uc in
1525 let sigma, tty = Typing.type_of env sigma t in
1526 let concl = EConstr.mkLetIn (make_annot (Name (Id.of_string "selected")) EConstr.ERelevance.relevant, t, tty, concl_x) in
1527 Proofview.Unsafe.tclEVARS sigma <*>
1528 convert_concl ~cast:false ~check:true concl DEFAULTcast
1529 end
1530
1531 (* Register "ssrpattern" tactic *)
1532 let () =
1533 let mltac _ ist =
1534 let arg =
1535 let v = Id.Map.find (Names.Id.of_string "pattern") ist.lfun in
1536 Value.cast (topwit wit_ssrpatternarg) v in
1537 ssrpatterntac arg in
1538 let name = { mltac_plugin = "rocq-runtime.plugins.ssrmatching"; mltac_tactic = "ssrpattern"; } in
1539 let () = Tacenv.register_ml_tactic name [|mltac|] in
1540 let tac =
1541 CAst.make (TacFun ([Name (Id.of_string "pattern")],
1542 CAst.make (TacML ({ mltac_name = name; mltac_index = 0 }, [])))) in
1543 let obj () =
1544 Tacenv.register_ltac true false (Id.of_string "ssrpattern") tac in
1545 Mltop.(declare_cache_obj_full (interp_only_obj obj) "rocq-runtime.plugins.ssrmatching")
1546
1547 let ssrinstancesof arg =
1548 Proofview.Goal.enter begin fun gl ->
1549 let env = Proofview.Goal.env gl in
1550 let sigma = Proofview.Goal.sigma gl in
1551 let concl = Proofview.Goal.concl gl in
1552 let concl = Reductionops.nf_evar sigma concl in
1553 let { pat_sigma = sigma0; pat_pat = cpat } = interp_cpattern env sigma arg None in
1554 let pat = match cpat with T x -> x | _ -> errorstrm (str"Not supported") in
1555 let rigid ev = Evd.mem sigma ev in
1556 let tpat = mk_tpattern ~rigid env pat L2R pat (empty_tpatterns sigma0) in
1557 let find, conclude =
1558 mk_tpattern_matcher ~all_instances:true ~raise_NoMatch:true sigma None tpat
1559 in
1560 let print env p c _ = ppnl (hov 1 (str"instance:" ++ spc() ++ pr_econstr_env env (Proofview.Goal.sigma gl) p ++ spc()
1561 ++ str "matches:" ++ spc() ++ pr_econstr_env env (Proofview.Goal.sigma gl) c)); c in
1562 ppnl (str"BEGIN INSTANCES");
1563 try
1564 while true do
1565 ignore(find env concl 1 ~k:print)
1566 done; raise NoMatch
1567 with NoMatch -> ppnl (str"END INSTANCES"); Tacticals.tclIDTAC
1568 end
1569
1570 module Internal =
1571 struct
1572 let wit_rpatternty = wit_rpatternty
1573 let glob_rpattern = glob_rpattern
1574 let subst_rpattern = subst_rpattern
1575 let interp_rpattern = interp_rpattern0
1576 let pr_rpattern = pr_rpattern
1577 let mk_rpattern x = x
1578 let mk_lterm = mk_lterm
1579 let mk_term = mk_term
1580 let glob_cpattern = glob_cpattern
1581 let subst_ssrterm = subst_ssrterm
1582 let interp_ssrterm = interp_ssrterm
1583 let pr_ssrterm = pr_term
1584 end
1585
1586 (* vim: set filetype=ocaml foldmethod=marker: *)