Debian Codegraph @

pretyping/constr_matching.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 (*i*)
12 open Pp
13 open CErrors
14 open Util
15 open Names
16 open Constr
17 open Context
18 open Termops
19 open EConstr
20 open Vars
21 open Pattern
22 open Patternops
23 open Context.Rel.Declaration
24 open Ltac_pretype
25 (*i*)
26
27 (* Given a term with second-order variables in it,
28 represented by Meta's, and possibly applied using [SOAPP] to
29 terms, this function will perform second-order, binding-preserving,
30 matching, in the case where the pattern is a pattern in the sense
31 of Dale Miller.
32
33 ALGORITHM:
34
35 Given a pattern, we decompose it, flattening Cast's and apply's,
36 recursing on all operators, and pushing the name of the binder each
37 time we descend a binder.
38
39 When we reach a first-order variable, we ask that the corresponding
40 term's free-rels all be higher than the depth of the current stack.
41
42 When we reach a second-order application, we ask that the
43 intersection of the free-rels of the term and the current stack be
44 contained in the arguments of the application, and in that case, we
45 construct a LAMBDA with the names on the stack.
46
47 *)
48
49 type binding_bound_vars = Id.Set.t
50 type bound_ident_map = Id.t Id.Map.t
51
52 exception PatternMatchingFailure
53
54 let warn_meta_collision =
55 CWarnings.create ~name:"meta-collision" ~category:CWarnings.CoreCategories.ltac
56 (fun name ->
57 strbrk "Collision between bound variable " ++ Id.print name ++
58 strbrk " and a metavariable of same name.")
59
60
61 let constrain sigma n (ids, m) ((names,seen as names_seen), terms as subst) =
62 let open EConstr in
63 try
64 let (ids', m') = Id.Map.find n terms in
65 if List.equal Id.equal ids ids' && eq_constr sigma m m' then subst
66 else raise PatternMatchingFailure
67 with Not_found ->
68 let () = if Id.Map.mem n names then warn_meta_collision n in
69 (names_seen, Id.Map.add n (ids, m) terms)
70
71 let add_binders na1 na2 binding_vars ((names,seen), terms as subst) =
72 match na1, na2.binder_name with
73 | Name id1, Name id2 when Id.Set.mem id1 binding_vars ->
74 if Id.Map.mem id1 names then
75 let () = Glob_ops.warn_variable_collision id1 in
76 subst
77 else
78 let id2 = Namegen.next_ident_away id2 seen in
79 let names = Id.Map.add id1 id2 names in
80 let seen = Id.Set.add id2 seen in
81 let () = if Id.Map.mem id1 terms then
82 warn_meta_collision id1 in
83 ((names,seen), terms)
84 | _ -> subst
85
86 let rec build_lambda sigma vars ctx m = match vars with
87 | [] ->
88 if Vars.closed0 sigma m then m else raise PatternMatchingFailure
89 | n :: vars ->
90 (* change [ x1 ... xn y z1 ... zm |- t ] into
91 [ x1 ... xn z1 ... zm |- lam y. t ] *)
92 let pre, suf = List.chop (pred n) ctx in
93 let (na, t, suf) = match suf with
94 | [] -> assert false
95 | (_, id, t) :: suf ->
96 (map_annot Name.mk_name id, t, suf)
97 in
98 (* Check that the abstraction is legal by generating a transitive closure of
99 its dependencies. *)
100 let is_nondep t clear = match clear with
101 | [] -> true
102 | _ ->
103 let rels = free_rels sigma t in
104 let check i b = b || not (Int.Set.mem i rels) in
105 List.for_all_i check 1 clear
106 in
107 let fold (_, _, t) clear = is_nondep t clear :: clear in
108 (* Produce a list of booleans: true iff we keep the hypothesis *)
109 let clear = List.fold_right fold pre [false] in
110 let clear = List.drop_last clear in
111 (* If the conclusion depends on a variable we cleared, failure *)
112 let () = if not (is_nondep m clear) then raise PatternMatchingFailure in
113 (* Create the abstracted term *)
114 let fold (k, accu) keep =
115 if keep then
116 let k = succ k in
117 (k, Some k :: accu)
118 else (k, None :: accu)
119 in
120 let keep, shift = List.fold_left fold (0, []) clear in
121 let shift = List.rev shift in
122 let map = function
123 | None -> mkProp (* dummy term *)
124 | Some i -> mkRel (i + 1)
125 in
126 (* [x1 ... xn y z1 ... zm] -> [x1 ... xn f(z1) ... f(zm) y] *)
127 let subst =
128 List.map map shift @
129 mkRel 1 ::
130 List.mapi (fun i _ -> mkRel (i + keep + 2)) suf
131 in
132 let map i (na, id, c) =
133 let i = succ i in
134 let subst = List.skipn i subst in
135 let subst = List.map (fun c -> Vars.lift (- i) c) subst in
136 (na, id, substl subst c)
137 in
138 let pre = List.mapi map pre in
139 let pre = List.filter_with clear pre in
140 let m = substl subst m in
141 let map i =
142 if i > n then i - n + keep
143 else match List.nth shift (i - 1) with
144 | None ->
145 (* We cleared a variable that we wanted to abstract! *)
146 raise PatternMatchingFailure
147 | Some k -> k
148 in
149 let vars = List.map map vars in
150 (* Create the abstraction *)
151 let m = mkLambda (na, Vars.lift keep t, m) in
152 build_lambda sigma vars (pre @ suf) m
153
154 let rec extract_bound_aux k accu frels ctx = match ctx with
155 | [] -> accu
156 | (na, _, _) :: ctx ->
157 if Int.Set.mem k frels then
158 begin match na with
159 | Name id ->
160 let () = if Id.Set.mem id accu then raise PatternMatchingFailure in
161 extract_bound_aux (k + 1) (Id.Set.add id accu) frels ctx
162 | Anonymous -> raise PatternMatchingFailure
163 end
164 else extract_bound_aux (k + 1) accu frels ctx
165
166 let extract_bound_vars frels ctx =
167 extract_bound_aux 1 Id.Set.empty frels ctx
168
169 let dummy_constr = EConstr.mkProp
170
171 let make_renaming ids = function
172 | (Name id, _, _) ->
173 begin
174 try EConstr.mkRel (List.index Id.equal id ids)
175 with Not_found -> dummy_constr
176 end
177 | _ -> dummy_constr
178
179 let push_binder na1 na2 t ctx =
180 let id2 = map_annot (function
181 | Name id2 -> id2
182 | Anonymous ->
183 let avoid = Id.Set.of_list (List.map (fun (_,id,_) -> id.binder_name) ctx) in
184 Namegen.next_ident_away Namegen.default_non_dependent_ident avoid) na2
185 in
186 (na1, id2, t) :: ctx
187
188 (* This is an optimization of the main pattern-matching which shares
189 the longest common prefix of the body and type of a fixpoint. The
190 only practical effect at the time of writing is in binding variable
191 names: these variable names must be bound only once since the user
192 view at a fix displays only a (maximal) shared common prefix *)
193
194 let rec match_under_common_fix_binders sorec sigma binding_vars ctx ctx' env env' subst t1 t2 b1 b2 =
195 match t1, EConstr.kind sigma t2, b1, EConstr.kind sigma b2 with
196 | PProd(na1,c1,t1'), Prod(na2,c2,t2'), PLambda (_,c1',b1'), Lambda (na2',c2',b2') ->
197 let ctx = push_binder na1 na2 c2 ctx in
198 let ctx' = push_binder na1 na2' c2' ctx' in
199 let env = EConstr.push_rel (LocalAssum (na2,c2)) env in
200 let subst = sorec ctx env subst c1 c2 in
201 let subst = sorec ctx env subst c1' c2' in
202 let subst = add_binders na1 na2 binding_vars subst in
203 match_under_common_fix_binders sorec sigma binding_vars
204 ctx ctx' env env' subst t1' t2' b1' b2'
205 | PLetIn(na1,c1,u1,t1), LetIn(na2,c2,u2,t2), PLetIn(_,c1',u1',b1), LetIn(na2',c2',u2',b2) ->
206 let ctx = push_binder na1 na2 u2 ctx in
207 let ctx' = push_binder na1 na2' u2' ctx' in
208 let env = EConstr.push_rel (LocalDef (na2,c2,t2)) env in
209 let subst = sorec ctx env subst c1 c2 in
210 let subst = sorec ctx env subst c1' c2' in
211 let subst = Option.fold_left (fun subst u1 -> sorec ctx env subst u1 u2) subst u1 in
212 let subst = Option.fold_left (fun subst u1' -> sorec ctx env subst u1' u2') subst u1' in
213 let subst = add_binders na1 na2 binding_vars subst in
214 match_under_common_fix_binders sorec sigma binding_vars
215 ctx ctx' env env' subst t1 t2 b1 b2
216 | _ ->
217 sorec ctx' env' (sorec ctx env subst t1 t2) b1 b2
218
219 let merge_binding sigma allow_bound_rels ctx n cT subst =
220 let c = match ctx with
221 | [] -> (* Optimization *)
222 ([], cT)
223 | _ ->
224 let frels = free_rels sigma cT in
225 if allow_bound_rels then
226 let vars = extract_bound_vars frels ctx in
227 let ordered_vars = Id.Set.elements vars in
228 let rename binding = make_renaming ordered_vars binding in
229 let renaming = List.map rename ctx in
230 (ordered_vars, Vars.substl renaming cT)
231 else
232 let depth = List.length ctx in
233 let min_elt = try Int.Set.min_elt frels with Not_found -> succ depth in
234 if depth < min_elt then
235 ([], Vars.lift (- depth) cT)
236 else raise PatternMatchingFailure
237 in
238 constrain sigma n c subst
239
240 let matches_core env sigma allow_bound_rels (binding_vars, pat) c =
241 let open EConstr in
242 let rec sorec ctx env subst p t = match p, EConstr.kind sigma t with
243 | _, Cast (t, _, _) -> sorec ctx env subst p t
244 | PSoApp (n, args), _ ->
245 let fold (ans, seen) = function
246 | PRel n ->
247 let () = if Int.Set.mem n seen then user_err (str "Non linear second-order pattern") in
248 (n :: ans, Int.Set.add n seen)
249 | _ -> user_err (str "Only bound indices allowed in second order pattern matching.")
250 in
251 let relargs, relset = List.fold_left fold ([], Int.Set.empty) args in
252 let frels = free_rels sigma t in
253 if Int.Set.subset frels relset then
254 constrain sigma n ([], build_lambda sigma relargs ctx t) subst
255 else
256 raise PatternMatchingFailure
257
258 | PMeta (Some n), _ -> merge_binding sigma allow_bound_rels ctx n t subst
259
260 | PMeta None, _ -> subst
261
262 | PRef (GlobRef.VarRef v1), Var v2 ->
263 if Id.equal v1 v2 then subst
264 else raise PatternMatchingFailure
265
266 | PVar v1, Var v2 ->
267 if Id.equal v1 v2 then subst
268 else raise PatternMatchingFailure
269
270 | PRef (GlobRef.ConstRef cst1), Const (cst2, _) ->
271 if Environ.QConstant.equal env cst1 cst2 then subst
272 else raise PatternMatchingFailure
273
274 | PRef (GlobRef.IndRef ind1), Ind (ind2, _) ->
275 if Environ.QInd.equal env ind1 ind2 then subst
276 else raise PatternMatchingFailure
277
278 | PRef (GlobRef.ConstructRef cst1), Construct (cst2, _) ->
279 if Environ.QConstruct.equal env cst1 cst2 then subst
280 else raise PatternMatchingFailure
281
282 | PRel n1, Rel n2 ->
283 if Int.equal n1 n2 then subst
284 else raise PatternMatchingFailure
285
286 | PSort ps, Sort s ->
287 if UnivGen.QualityOrSet.equal ps (ESorts.quality_or_set sigma s) then subst
288 else raise PatternMatchingFailure
289
290 | PApp (p, [||]), _ -> sorec ctx env subst p t
291
292 | PApp (PApp (h, a1), a2), _ ->
293 sorec ctx env subst (PApp (h, Array.append a1 a2)) t
294
295 | PApp (PMeta meta, args1), App (c2, args2) ->
296 let diff = Array.length args2 - Array.length args1 in
297 if diff >= 0 then
298 let args21, args22 = Array.chop diff args2 in
299 let c = mkApp (c2, args21) in
300 let subst = match meta with
301 | None -> subst
302 | Some n -> merge_binding sigma allow_bound_rels ctx n c subst
303 in
304 Array.fold_left2 (sorec ctx env) subst args1 args22
305 else begin match EConstr.kind sigma c2 with
306 (* Might be a projection on the right *)
307 | Proj (pr, _, c) ->
308 begin match Retyping.expand_projection env sigma pr c (Array.to_list args2) with
309 | term -> sorec ctx env subst p term
310 | exception Retyping.RetypeError _ -> raise PatternMatchingFailure
311 end
312 | _ -> raise PatternMatchingFailure
313 end
314
315 | PApp (c1, arg1), App (c2, arg2) ->
316 begin match c1, EConstr.kind sigma c2 with
317 | PRef (GlobRef.ConstRef r), Proj (pr,_,c) when not (Environ.QConstant.equal env r (Projection.constant pr)) ->
318 raise PatternMatchingFailure
319 | PProj (pr1,c1), Proj (pr,_,c) ->
320 let () = if not (Int.equal (Array.length arg1) (Array.length arg2) && Environ.QProjection.equal env pr1 pr) then raise PatternMatchingFailure in
321 Array.fold_left2 (sorec ctx env) (sorec ctx env subst c1 c) arg1 arg2
322 | _, Proj (pr,_,c) ->
323 begin match Retyping.expand_projection env sigma pr c (Array.to_list arg2) with
324 | term -> sorec ctx env subst p term
325 | exception Retyping.RetypeError _ -> raise PatternMatchingFailure
326 end
327 | _ ->
328 let () = if not (Int.equal (Array.length arg1) (Array.length arg2)) then raise PatternMatchingFailure in
329 Array.fold_left2 (sorec ctx env) (sorec ctx env subst c1 c2) arg1 arg2
330 end
331
332 | PApp (c, args), Proj (pr, _, c2) ->
333 begin match c with
334 | PRef (GlobRef.ConstRef c1) when not (Environ.QConstant.equal env c1 (Projection.constant pr)) ->
335 raise PatternMatchingFailure
336 | _ ->
337 begin match Retyping.expand_projection env sigma pr c2 [] with
338 | term -> sorec ctx env subst p term
339 | exception Retyping.RetypeError _ -> raise PatternMatchingFailure
340 end
341 end
342
343 | PProj (p1, c1), Proj (p2, _, c2) ->
344 if Environ.QProjection.equal env p1 p2 then sorec ctx env subst c1 c2
345 else raise PatternMatchingFailure
346
347 | PProd (na1, c1, d1), Prod (na2, c2, d2) ->
348 sorec (push_binder na1 na2 c2 ctx) (EConstr.push_rel (LocalAssum (na2,c2)) env)
349 (add_binders na1 na2 binding_vars (sorec ctx env subst c1 c2)) d1 d2
350
351 | PLambda (na1, c1, d1), Lambda (na2, c2, d2) ->
352 sorec (push_binder na1 na2 c2 ctx) (EConstr.push_rel (LocalAssum (na2,c2)) env)
353 (add_binders na1 na2 binding_vars (sorec ctx env subst c1 c2)) d1 d2
354
355 | PLetIn (na1, c1, Some t1, d1), LetIn (na2, c2, t2, d2) ->
356 sorec (push_binder na1 na2 t2 ctx) (EConstr.push_rel (LocalDef (na2,c2,t2)) env)
357 (add_binders na1 na2 binding_vars (sorec ctx env (sorec ctx env subst c1 c2) t1 t2)) d1 d2
358
359 | PLetIn (na1, c1, None, d1), LetIn (na2, c2, t2, d2) ->
360 sorec (push_binder na1 na2 t2 ctx) (EConstr.push_rel (LocalDef (na2,c2,t2)) env)
361 (add_binders na1 na2 binding_vars (sorec ctx env subst c1 c2)) d1 d2
362
363 | PIf (a1, b1, b1'), Case (ci, u2, pms2, p2, iv, a2, ([|_; _|] as br2)) ->
364 let (_, _, _, p2, _, _, br2) = EConstr.annotate_case env sigma (ci, u2, pms2, p2, iv, a2, br2) in
365 let ctx_b2,b2 = br2.(0) in
366 let ctx_b2',b2' = br2.(1) in
367 let n = Context.Rel.length ctx_b2 in
368 let n' = Context.Rel.length ctx_b2' in
369 if Vars.noccur_between sigma 1 n b2 && Vars.noccur_between sigma 1 n' b2' then
370 let f l (LocalAssum (na,t) | LocalDef (na,_,t)) = push_binder Anonymous na t l in
371 let ctx_br = List.fold_left f ctx ctx_b2 in
372 let ctx_br' = List.fold_left f ctx ctx_b2' in
373 let b1 = lift_pattern n b1 and b1' = lift_pattern n' b1' in
374 sorec ctx_br' (push_rel_context ctx_b2' env)
375 (sorec ctx_br (push_rel_context ctx_b2 env)
376 (sorec ctx env subst a1 a2) b1 b2) b1' b2'
377 else
378 raise PatternMatchingFailure
379
380 | PCase (ci1, p1, a1, br1), Case (ci2, u2, pms2, p2, iv, a2, br2) ->
381 let (_, _, _, (p2,_), _, _, br2) = EConstr.annotate_case env sigma (ci2, u2, pms2, p2, iv, a2, br2) in
382 let n2 = Array.length br2 in
383 let () = match ci1.cip_ind with
384 | None -> ()
385 | Some ind1 ->
386 (* ppedrot: Something spooky going here. The comparison used to be
387 the generic one, so I may have broken something. *)
388 if not (Environ.QInd.equal env ind1 ci2.ci_ind) then raise PatternMatchingFailure
389 in
390 let () =
391 if not ci1.cip_extensible && not (Int.equal (List.length br1) n2)
392 then raise PatternMatchingFailure
393 in
394 let sorec_under_ctx subst (n, c1) (decls, c2) =
395 let env = push_rel_context decls env in
396 let rec fold (ctx, subst) nas decls = match nas, decls with
397 | [], _ ->
398 (* Historical corner case: less bound variables are allowed in
399 destructuring let-bindings. See #13735. *)
400 (ctx, subst)
401 | na1 :: nas, d :: decls ->
402 let na2 = Context.Rel.Declaration.get_annot d in
403 let t = Context.Rel.Declaration.get_type d in
404 let ctx = push_binder na1 na2 t ctx in
405 let subst = add_binders na1 na2 binding_vars subst in
406 fold (ctx, subst) nas decls
407 | _, [] ->
408 assert false
409 in
410 let ctx, subst = fold (ctx, subst) (Array.to_list n) (List.rev decls) in
411 sorec ctx env subst c1 c2
412 in
413 let chk_branch subst (j,n,c) =
414 (* (ind,j+1) is normally known to be a correct constructor
415 and br2 a correct match over the same inductive *)
416 assert (j < n2);
417 sorec_under_ctx subst (n, c) br2.(j)
418 in
419 let subst = sorec ctx env subst a1 a2 in
420 let subst = match p1 with
421 | None -> subst
422 | Some p1 -> sorec_under_ctx subst p1 p2
423 in
424 List.fold_left chk_branch subst br1
425
426 | PFix ((ln1, i1),(lna1, tl1, bl1)), Fix ((ln2, i2),(lna2, tl2, bl2)) ->
427 let () = if not (Array.equal Int.equal ln1 ln2 && Int.equal i1 i2) then raise PatternMatchingFailure in
428 let ctx' = Array.fold_left3 (fun ctx na1 na2 t2 -> push_binder na1 na2 t2 ctx) ctx lna1 lna2 tl2 in
429 let env' = Array.fold_left2 (fun env na2 c2 -> EConstr.push_rel (LocalAssum (na2,c2)) env) env lna2 tl2 in
430 let subst = Array.fold_left4 (match_under_common_fix_binders sorec sigma binding_vars ctx ctx' env env') subst tl1 tl2 bl1 bl2 in
431 Array.fold_left2 (fun subst na1 na2 -> add_binders na1 na2 binding_vars subst) subst lna1 lna2
432
433 | PCoFix (i1, (lna1, tl1, bl1)), CoFix (i2, (lna2, tl2, bl2)) ->
434 let () = if not (Int.equal i1 i2) then raise PatternMatchingFailure in
435 let ctx' = Array.fold_left3 (fun ctx na1 na2 t2 -> push_binder na1 na2 t2 ctx) ctx lna1 lna2 tl2 in
436 let env' = Array.fold_left2 (fun env na2 c2 -> EConstr.push_rel (LocalAssum (na2,c2)) env) env lna2 tl2 in
437 let subst = Array.fold_left4 (match_under_common_fix_binders sorec sigma binding_vars ctx ctx' env env') subst tl1 tl2 bl1 bl2 in
438 Array.fold_left2 (fun subst na1 na2 -> add_binders na1 na2 binding_vars subst) subst lna1 lna2
439
440 | PEvar (c1, args1), Evar (c2, args2) ->
441 let () = if not (Evar.equal c1 c2) then raise PatternMatchingFailure in
442 let args2 = Evd.expand_existential sigma (c2, args2) in
443 List.fold_left2 (sorec ctx env) subst args1 args2
444
445 | PInt i1, Int i2 ->
446 if Uint63.equal i1 i2 then subst
447 else raise PatternMatchingFailure
448
449 | PFloat f1, Float f2 ->
450 if Float64.equal f1 f2 then subst
451 else raise PatternMatchingFailure
452
453 | PString s1, String s2 ->
454 if Pstring.equal s1 s2 then subst
455 else raise PatternMatchingFailure
456
457 | PArray (pt, pdef, pty), Array (_u, t, def, ty) ->
458 let () = if not (Int.equal (Array.length pt) (Array.length t)) then raise PatternMatchingFailure in
459 sorec ctx env (sorec ctx env (Array.fold_left2 (sorec ctx env) subst pt t) pdef def) pty ty
460
461 | (PRef _ | PVar _ | PRel _ | PApp _ | PProj _ | PLambda _
462 | PProd _ | PLetIn _ | PSort _ | PIf _ | PCase _
463 | PFix _ | PCoFix _| PEvar _ | PInt _ | PFloat _
464 | PString _ | PArray _), _ -> raise PatternMatchingFailure
465
466 | PExtra e, _ -> Util.Empty.abort e
467
468 in
469 sorec [] env ((Id.Map.empty, Id.Set.empty), Id.Map.empty) pat c
470
471 let matches_core_closed env sigma pat c =
472 let names, subst = matches_core env sigma false pat c in
473 (fst names, Id.Map.map snd subst)
474
475 let extended_matches env sigma pat c =
476 let (names,_), subst = matches_core env sigma true pat c in
477 names, subst
478
479 let matches env sigma pat c =
480 snd (matches_core_closed env sigma (Id.Set.empty,pat) c)
481
482 type context = constr Lazy.t
483
484 let special_meta = (-1)
485
486 let empty_context = Lazy.from_val (mkMeta special_meta)
487 let repr_context c = Lazy.force c
488 let instantiate_context ctxt c =
489 let ctxt = EConstr.Unsafe.to_constr (Lazy.force ctxt) in
490 let c = EConstr.Unsafe.to_constr c in
491 EConstr.of_constr (subst_meta [special_meta, c] ctxt)
492
493 type matching_result =
494 { m_sub : bound_ident_map * patvar_map;
495 m_ctx : context; }
496
497 let mkresult s c n = IStream.Cons ( { m_sub=s; m_ctx=c; } , (IStream.thunk n) )
498
499 let isPMeta = function PMeta _ -> true | _ -> false
500
501 let matches_head env sigma pat c =
502 let open EConstr in
503 let head =
504 match pat, EConstr.kind sigma c with
505 | PApp (c1,arg1), App (c2,arg2) ->
506 if isPMeta c1 then c else
507 let n1 = Array.length arg1 in
508 if n1 < Array.length arg2 then mkApp (c2,Array.sub arg2 0 n1) else c
509 | c1, App (c2,arg2) when not (isPMeta c1) -> c2
510 | _ -> c in
511 matches env sigma pat head
512
513 (* Tells if it is an authorized occurrence and if the instance is closed *)
514 let authorized_occ env sigma closed pat c mk_ctx =
515 try
516 let subst = matches_core_closed env sigma pat c in
517 if closed && Id.Map.exists (fun _ c -> not (closed0 sigma c)) (snd subst)
518 then (fun next -> next ())
519 else (fun next -> mkresult subst (lazy (mk_ctx (mkMeta special_meta))) next)
520 with PatternMatchingFailure -> (fun next -> next ())
521
522 let subargs env v = Array.map_to_list (fun c -> (env, c)) v
523
524 (* Tries to match a subterm of [c] with [pat] *)
525 let sub_match ?(closed=true) env sigma pat c =
526 let open EConstr in
527 let rec aux env c mk_ctx next =
528 let here = authorized_occ env sigma closed pat c mk_ctx in
529 let next () = match EConstr.kind sigma c with
530 | Cast (c1,k,c2) ->
531 let next_mk_ctx = function
532 | [c1] -> mk_ctx (mkCast (c1, k, c2))
533 | _ -> assert false
534 in
535 try_aux [env, c1] next_mk_ctx next
536 | Lambda (x,c1,c2) ->
537 let next_mk_ctx = function
538 | [c1; c2] -> mk_ctx (mkLambda (x, c1, c2))
539 | _ -> assert false
540 in
541 let env' = EConstr.push_rel (LocalAssum (x,c1)) env in
542 try_aux [(env, c1); (env', c2)] next_mk_ctx next
543 | Prod (x,c1,c2) ->
544 let next_mk_ctx = function
545 | [c1; c2] -> mk_ctx (mkProd (x, c1, c2))
546 | _ -> assert false
547 in
548 let env' = EConstr.push_rel (LocalAssum (x,c1)) env in
549 try_aux [(env, c1); (env', c2)] next_mk_ctx next
550 | LetIn (x,c1,t,c2) ->
551 let next_mk_ctx = function
552 | [c1; c2] -> mk_ctx (mkLetIn (x, c1, t, c2))
553 | _ -> assert false
554 in
555 let env' = EConstr.push_rel (LocalDef (x,c1,t)) env in
556 try_aux [(env, c1); (env', c2)] next_mk_ctx next
557 | App (c1,lc) ->
558 let lc1 = Array.sub lc 0 (Array.length lc - 1) in
559 let app = mkApp (c1,lc1) in
560 let mk_ctx = function
561 | [app';c] -> mk_ctx (mkApp (app',[|c|]))
562 | _ -> assert false in
563 try_aux [(env, app); (env, Array.last lc)] mk_ctx next
564 | Case (ci,u,pms,hd0,iv,c1,lc0) ->
565 let (mib, mip) = Inductive.lookup_mind_specif env ci.ci_ind in
566 let (_, (hd,hdr), _, _, br) = expand_case env sigma (ci, u, pms, hd0, iv, c1, lc0) in
567 let hd =
568 let (ctx, hd) = decompose_lambda_decls sigma hd in
569 (push_rel_context ctx env, hd)
570 in
571 let map i br =
572 let decls = mip.Declarations.mind_consnrealdecls.(i) in
573 let (ctx, c) = decompose_lambda_n_decls sigma decls br in
574 (push_rel_context ctx env, c)
575 in
576 let lc = Array.to_list (Array.mapi map br) in
577 let next_mk_ctx = function
578 | c1 :: rem ->
579 let pms, rem = List.chop (Array.length pms) rem in
580 let pms = Array.of_list pms in
581 let hd, lc = match rem with [] -> assert false | x :: l -> (x, l) in
582 let hd = (fst (fst hd0), hd) in
583 let map_br (nas, _) br = (nas, br) in
584 mk_ctx (mkCase (ci,u,pms,(hd,hdr),iv,c1,Array.map2 map_br lc0 (Array.of_list lc)))
585 | _ -> assert false
586 in
587 let sub = (env, c1) :: Array.fold_right (fun c accu -> (env, c) :: accu) pms (hd :: lc) in
588 try_aux sub next_mk_ctx next
589 | Fix (indx,(names,types,bodies as recdefs)) ->
590 let nb_fix = Array.length types in
591 let next_mk_ctx le =
592 let (ntypes,nbodies) = CList.chop nb_fix le in
593 mk_ctx (mkFix (indx,(names, Array.of_list ntypes, Array.of_list nbodies))) in
594 let env' = push_rec_types recdefs env in
595 let sub = subargs env types @ subargs env' bodies in
596 try_aux sub next_mk_ctx next
597 | CoFix (i,(names,types,bodies as recdefs)) ->
598 let nb_fix = Array.length types in
599 let next_mk_ctx le =
600 let (ntypes,nbodies) = CList.chop nb_fix le in
601 mk_ctx (mkCoFix (i,(names, Array.of_list ntypes, Array.of_list nbodies))) in
602 let env' = push_rec_types recdefs env in
603 let sub = subargs env types @ subargs env' bodies in
604 try_aux sub next_mk_ctx next
605 | Proj (p,_,c') ->
606 begin match Retyping.expand_projection env sigma p c' [] with
607 | term -> aux env term mk_ctx next
608 | exception Retyping.RetypeError _ -> next ()
609 end
610 | Array(u, t, def, ty) ->
611 let next_mk_ctx = function
612 | def :: ty :: l -> mk_ctx (mkArray(u, Array.of_list l, def, ty))
613 | _ -> assert false
614 in
615 let sub = (env,def) :: (env,ty) :: subargs env t in
616 try_aux sub next_mk_ctx next
617 | Construct _|Ind _|Evar _|Const _|Rel _|Meta _|Var _|Sort _|Int _|Float _|String _ ->
618 next ()
619 in
620 here next
621
622 (* Tries [sub_match] for all terms in the list *)
623 and try_aux lc mk_ctx next =
624 let rec try_sub_match_rec lacc lc =
625 match lc with
626 | [] -> next ()
627 | (env, c) :: tl ->
628 let mk_ctx ce = mk_ctx (List.rev_append lacc (ce :: List.map snd tl)) in
629 let next () = try_sub_match_rec (c :: lacc) tl in
630 aux env c mk_ctx next
631 in
632 try_sub_match_rec [] lc in
633 let lempty () = IStream.Nil in
634 let result () = aux env c (fun x -> x) lempty in
635 IStream.thunk result
636
637 let match_subterm env sigma pat c = sub_match env sigma pat c
638
639 let is_matching env sigma pat c =
640 try let _ = matches env sigma pat c in true
641 with PatternMatchingFailure -> false
642
643 let is_matching_head env sigma pat c =
644 try let _ = matches_head env sigma pat c in true
645 with PatternMatchingFailure -> false
646
647 let is_matching_appsubterm ?(closed=true) env sigma pat c =
648 let pat = (Id.Set.empty,pat) in
649 let results = sub_match ~closed env sigma pat c in
650 not (IStream.is_empty results)