Debian Codegraph @

interp/notation_ops.ml

raw symbols SCIP
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * Copyright INRIA, CNRS and contributors *)
4 (* <O___,, * (see version control and CREDITS file for authors & dates) *)
5 (* \VV/ **************************************************************)
6 (* // * This file is distributed under the terms of the *)
7 (* * GNU Lesser General Public License Version 2.1 *)
8 (* * (see LICENSE file for the text of the license) *)
9 (************************************************************************)
10
11 open Pp
12 open CErrors
13 open Util
14 open Names
15 open Nameops
16 open Constr
17 open Globnames
18 open Glob_term
19 open Glob_ops
20 open Mod_subst
21 open Notation_term
22
23 (** Constr default entry *)
24
25 let constr_lowest_level =
26 Constrexpr.{notation_entry = InConstrEntry; notation_level = 0}
27
28 let constr_some_level =
29 Constrexpr.{notation_subentry = InConstrEntry; notation_relative_level = LevelSome; notation_position = None}
30
31 (**********************************************************************)
32 (* Utilities *)
33
34 let ldots_var = Id.of_string ".."
35
36 type alpha_conversion_map = {
37 (* the actual binding variables accumulated; e.g. when matching "fun x => t"
38 with "fun '(y,z) => t'", we accumulate y and z; used for avoiding collisions
39 with global names *)
40 actualvars : Id.Set.t;
41 (* the matching between binders of the pattern unbound in the
42 notation and actual binders of the term to match; e.g. when
43 matching term "fun y => t" against pattern "fun x => u" where "x"
44 is not a notation variable, we bind "y" to "x" and compare t and
45 u up to this renaming (note that in this case, "x" is not bound
46 to a notation variable and thus will not occur in any instance of
47 a notation variable in "t"). *)
48 staticbinders : (Name.t * Id.t) list;
49 (* the renaming to do between binder variables bound several times; e.g. if
50 "fun x => t" has to match pattern "fun y => u" and, either "fun z => v"
51 is already known to match pattern "fun y => w" (for the same
52 binder variable "y"), or "y" already occurs also as a term bound,
53 say, to the variable "z", then, when matching "fun x => t"
54 against "fun y => u", "t" is matched against "u" with the
55 constraint that any "x" in "t" has to be renamed into "z" (and in
56 particular any subterm bound by the notation and mentioning "x"
57 must be renamed so as to use "z" instead). *)
58 renaming : (Id.t * Id.t) list;
59 }
60
61 (* Check if [id1], in the actual term, matches [id2], in the pattern,
62 up to the static alpha-renaming obtained by matching the context of
63 the pattern with the actual names of the term *)
64 let rec alpha_var id1 id2 = function
65 | (Name i1,i2)::_ when Id.equal i1 id1 -> Id.equal i2 id2
66 | (i1,i2)::_ when Id.equal i2 id2 -> Name.equal i1 (Name id1)
67 | _::idl -> alpha_var id1 id2 idl
68 | [] -> Id.equal id1 id2
69
70 (* used to update the notation variable with the local variables used
71 in NList and NBinderList, since the iterator has its own variable *)
72 let replace_var i j var = j :: List.remove Id.equal i var
73
74 let eq_rigid a b =
75 let open UState in
76 match a, b with
77 | UnivRigid, UnivRigid -> true
78 | UnivFlexible a, UnivFlexible b -> (a:bool) = b
79 | (UnivRigid | UnivFlexible _), _ -> false
80
81 (* compare_glob_universe_instances true strictly_lt us1 us2 computes us1 <= us2,
82 compare_glob_universe_instances false strictly_lt us1 us2 computes us1 = us2.
83 strictly_lt will be set to true if any part is strictly less. *)
84 let compare_glob_universe_instances lt strictly_lt us1 us2 =
85 match us1, us2 with
86 | None, None -> true
87 | Some _, None -> strictly_lt := true; lt
88 | None, Some _ -> false
89 | Some (ql1,ul1), Some (ql2,ul2) ->
90 let is_anon = function
91 | GQualVar (GLocalQVar {v=Anonymous}) -> true
92 | _ -> false
93 in
94 CList.for_all2eq (fun q1 q2 ->
95 match is_anon q1, is_anon q2 with
96 | true, true -> true
97 | false, true -> strictly_lt := true; lt
98 | true, false -> false
99 | false, false -> glob_quality_eq q1 q2)
100 ql1 ql2
101 && CList.for_all2eq (fun u1 u2 ->
102 match u1, u2 with
103 | UAnonymous {rigid}, UAnonymous {rigid=rigid'} -> eq_rigid rigid rigid'
104 | UNamed _, UAnonymous _ -> strictly_lt := true; lt
105 | UAnonymous _, UNamed _ -> false
106 | UNamed _, UNamed _ -> glob_level_eq u1 u2) ul1 ul2
107
108 (* Compute us1 <= us2, as a boolean *)
109 let compare_glob_universe_instances_le us1 us2 =
110 compare_glob_universe_instances true (ref false) us1 us2
111
112 (* When [lt] is [true], tell if [t1] is a strict refinement of [t2]
113 (this is a partial order, so returning [false] does not mean that
114 [t2] is finer than [t1]); when [lt] is false, tell if [t1] is the
115 same pattern as [t2] *)
116
117 let compare_notation_constr lt var_eq_hole (vars1,vars2) t1 t2 =
118 (* this is used to reason up to order of notation variables *)
119 let alphameta = ref [] in
120 (* this becomes true when at least one subterm is detected as strictly smaller *)
121 let strictly_lt = ref false in
122 (* this is the stack of inner of iter patterns for comparison with a
123 new iteration or the tail of a recursive pattern *)
124 let tail = ref [] in
125 let check_alphameta id1 id2 =
126 try if not (Id.equal (List.assoc id1 !alphameta) id2) then raise_notrace Exit
127 with Not_found ->
128 if (List.mem_assoc id1 !alphameta) then raise_notrace Exit;
129 alphameta := (id1,id2) :: !alphameta in
130 let check_eq_id (vars1,vars2) renaming id1 id2 =
131 let ismeta1 = List.mem_f Id.equal id1 vars1 in
132 let ismeta2 = List.mem_f Id.equal id2 vars2 in
133 match ismeta1, ismeta2 with
134 | true, true -> check_alphameta id1 id2
135 | false, false -> if not (alpha_var id1 id2 renaming) then raise_notrace Exit
136 | false, true ->
137 if not lt then raise_notrace Exit
138 else
139 (* a binder which is not bound in the notation can be
140 considered as strictly more precise since it prevents the
141 notation variables in its scope to be bound by this binder;
142 i.e. it is strictly more precise in the sense that it
143 covers strictly less patterns than a notation where the
144 same binder is bound in the notation; this is hawever
145 disputable *)
146 strictly_lt := true
147 | true, false -> if not lt then raise_notrace Exit in
148 let check_eq_name vars renaming na1 na2 =
149 match na1, na2 with
150 | Name id1, Name id2 -> check_eq_id vars renaming id1 id2; (Name id1,id2)::renaming
151 | Anonymous, Anonymous -> renaming
152 | Anonymous, Name _ when lt -> renaming
153 | _ -> raise_notrace Exit in
154 let rec aux (vars1,vars2 as vars) renaming t1 t2 = match t1, t2 with
155 | NVar id1, NVar id2 when id1 = ldots_var && id2 = ldots_var -> ()
156 | _, NVar id2 when lt && id2 = ldots_var -> tail := t1 :: !tail
157 | NVar id1, _ when lt && id1 = ldots_var -> tail := t2 :: !tail
158 | NVar id1, NVar id2 -> check_eq_id vars renaming id1 id2
159 | NHole _, NVar id2 when lt && List.mem_f Id.equal id2 vars2 -> ()
160 | NVar id1, NHole _ when lt && List.mem_f Id.equal id1 vars1 -> ()
161 | _, NVar id2 when lt && List.mem_f Id.equal id2 vars2 -> strictly_lt := true
162 | NRef (gr1,u1), NRef (gr2,u2) when GlobRef.CanOrd.equal gr1 gr2 && compare_glob_universe_instances lt strictly_lt u1 u2 -> ()
163 | NHole _, NHole _ -> () (* FIXME? *)
164 | _, NHole _ when lt -> strictly_lt := true
165 | NGenarg _, NGenarg _ -> () (* FIXME? *)
166 | NList (i1, j1, iter1, tail1, b1), NList (i2, j2, iter2, tail2, b2)
167 | NBinderList (i1, j1, iter1, tail1, b1), NBinderList (i2, j2, iter2, tail2, b2) ->
168 if b1 <> b2 then raise_notrace Exit;
169 let vars1 = replace_var i1 j1 vars1 in
170 let vars2 = replace_var i2 j2 vars2 in
171 check_alphameta i1 i2; aux (vars1,vars2) renaming iter1 iter2; aux vars renaming tail1 tail2;
172 | NBinderList (i1, j1, iter1, tail1, b1), NList (i2, j2, iter2, tail2, b2)
173 | NList (i1, j1, iter1, tail1, b1), NBinderList (i2, j2, iter2, tail2, b2) ->
174 (* They may overlap on a unique iteration of them *)
175 let vars1 = replace_var i1 j1 vars1 in
176 let vars2 = replace_var i2 j2 vars2 in
177 aux (vars1,vars2) renaming iter1 iter2;
178 aux vars renaming tail1 tail2
179 | t1, NList (i2, j2, iter2, tail2, b2)
180 | t1, NBinderList (i2, j2, iter2, tail2, b2) when lt ->
181 (* checking if t1 is a finite iteration of the pattern *)
182 let vars2 = replace_var i2 j2 vars2 in
183 aux (vars1,vars2) renaming t1 iter2;
184 let t1 = List.hd !tail in
185 tail := List.tl !tail;
186 (* either matching a new iteration, or matching the tail *)
187 (try aux vars renaming t1 tail2 with Exit -> aux vars renaming t1 t2)
188 | NList (i1, j1, iter1, tail1, b1), t2
189 | NBinderList (i1, j1, iter1, tail1, b1), t2 when lt ->
190 (* we see the NList as a single iteration *)
191 let vars1 = replace_var i1 j1 vars1 in
192 aux (vars1,vars2) renaming iter1 t2;
193 let t2 = match !tail with
194 | t::rest -> tail := rest; t
195 | _ -> (* ".." is in a discarded fine-grained position *) raise_notrace Exit in
196 (* it had to be a single iteration of iter1 *)
197 aux vars renaming tail1 t2
198 | NApp (t1, a1), NApp (t2, a2) -> aux vars renaming t1 t2; List.iter2 (aux vars renaming) a1 a2
199 | NProj ((cst1,u1), l1, a1), NProj ((cst2,u2), l2, a2)
200 when GlobRef.CanOrd.equal (GlobRef.ConstRef cst1) (GlobRef.ConstRef cst2) && compare_glob_universe_instances lt strictly_lt u1 u2 ->
201 List.iter2 (aux vars renaming) l1 l2; aux vars renaming a1 a2
202 | NLambda (na1, t1, u1), NLambda (na2, t2, u2)
203 | NProd (na1, t1, u1), NProd (na2, t2, u2) ->
204 (match t1, t2 with
205 | None, None -> ()
206 | Some _, None -> if lt then strictly_lt := true
207 | Some t1, Some t2 -> aux vars renaming t1 t2
208 | None, Some _ -> raise_notrace Exit);
209 let renaming = check_eq_name vars renaming na1 na2 in
210 aux vars renaming u1 u2
211 | NLetIn (na1, b1, t1, u1), NLetIn (na2, b2, t2, u2) ->
212 aux vars renaming b1 b2;
213 Option.iter2 (aux vars renaming) t1 t2;(* TODO : subtyping? *)
214 let renaming = check_eq_name vars renaming na1 na2 in
215 aux vars renaming u1 u2
216 | NCases (_, o1, r1, p1), NCases (_, o2, r2, p2) -> (* FIXME? *)
217 let check_pat (p1, t1) (p2, t2) =
218 if not (List.equal cases_pattern_eq p1 p2) then raise_notrace Exit; (* TODO: subtyping and renaming *)
219 aux vars renaming t1 t2
220 in
221 let eqf renaming (t1, (na1, o1)) (t2, (na2, o2)) =
222 aux vars renaming t1 t2;
223 let renaming = check_eq_name vars renaming na1 na2 in
224 let eq renaming (i1, n1) (i2, n2) =
225 if not (Ind.CanOrd.equal i1 i2) then raise_notrace Exit;
226 List.fold_left2 (check_eq_name vars) renaming n1 n2 in
227 Option.fold_left2 eq renaming o1 o2 in
228 let renaming = List.fold_left2 eqf renaming r1 r2 in
229 Option.iter2 (aux vars renaming) o1 o2;
230 List.iter2 check_pat p1 p2
231 | NLetTuple (nas1, (na1, o1), t1, u1), NLetTuple (nas2, (na2, o2), t2, u2) ->
232 aux vars renaming t1 t2;
233 let renaming = check_eq_name vars renaming na1 na2 in
234 Option.iter2 (aux vars renaming) o1 o2;
235 let renaming' = List.fold_left2 (check_eq_name vars) renaming nas1 nas2 in
236 aux vars renaming' u1 u2
237 | NIf (t1, (na1, o1), u1, r1), NIf (t2, (na2, o2), u2, r2) ->
238 aux vars renaming t1 t2;
239 aux vars renaming u1 u2;
240 aux vars renaming r1 r2;
241 let renaming = check_eq_name vars renaming na1 na2 in
242 Option.iter2 (aux vars renaming) o1 o2
243 | NRec (_, ids1, ts1, us1, rs1), NRec (_, ids2, ts2, us2, rs2) -> (* FIXME? *)
244 let eq renaming (na1, o1, t1) (na2, o2, t2) =
245 Option.iter2 (aux vars renaming) o1 o2;
246 aux vars renaming t1 t2;
247 check_eq_name vars renaming na1 na2
248 in
249 let renaming = Array.fold_left2 (fun r id1 id2 -> check_eq_id vars r id1 id2; (Name id1,id2)::r) renaming ids1 ids2 in
250 let renamings = Array.map2 (List.fold_left2 eq renaming) ts1 ts2 in
251 Array.iter3 (aux vars) renamings us1 us2;
252 Array.iter3 (aux vars) (Array.map ((@) renaming) renamings) rs1 rs2
253 | NSort s1, NSort s2 when glob_sort_eq s1 s2 -> ()
254 | NCast (c1, k1, t1), NCast (c2, k2, t2) ->
255 aux vars renaming c1 c2;
256 if not (Option.equal cast_kind_eq k1 k2) then raise_notrace Exit;
257 aux vars renaming t1 t2
258 | NInt i1, NInt i2 when Uint63.equal i1 i2 -> ()
259 | NFloat f1, NFloat f2 when Float64.equal f1 f2 -> ()
260 | NArray(t1,def1,ty1), NArray(t2,def2,ty2) ->
261 Array.iter2 (aux vars renaming) t1 t2;
262 aux vars renaming def1 def2;
263 aux vars renaming ty1 ty2
264 | (NRef _ | NVar _ | NApp _ | NProj _ | NHole _ | NGenarg _ | NList _ | NLambda _ | NProd _
265 | NBinderList _ | NLetIn _ | NCases _ | NLetTuple _ | NIf _
266 | NRec _ | NSort _ | NCast _ | NInt _ | NFloat _ | NString _ | NArray _), _ -> raise_notrace Exit in
267 try
268 let _ = aux (vars1,vars2) [] t1 t2 in
269 if not lt then
270 (* Check that order of notation metavariables does not matter *)
271 List.iter2 check_alphameta vars1 vars2;
272 not lt || var_eq_hole || !strictly_lt
273 with Exit | (* Option.iter2: *) Option.Heterogeneous | Invalid_argument _ -> false
274
275 let eq_notation_constr vars t1 t2 = t1 == t2 || compare_notation_constr false false vars t1 t2
276
277 (* "strictly finer" is the order generated by constructed-node <= var/hole *)
278 let strictly_finer_notation_constr vars t1 t2 = compare_notation_constr true false vars t1 t2
279
280 (* "finer" is the order also including var = hole and hole = var *)
281 let finer_notation_constr vars t1 t2 = compare_notation_constr true true vars t1 t2
282
283 let adjust_application c1 c2 =
284 match c1, c2 with
285 | NApp (t1, a1), (NList (_,_,NApp (_, a2),_,_) | NBinderList (_,_,NApp (_, a2),_,_) | NApp (_, a2)) when List.length a1 >= List.length a2 ->
286 NApp (t1, List.firstn (List.length a2) a1)
287 | NApp (t1, a1), _ ->
288 t1
289 | _ -> c1
290
291 let strictly_finer_interpretation_than (vars1,c1) (vars2,c2) =
292 let c1 = adjust_application c1 c2 in
293 strictly_finer_notation_constr (List.map fst vars1, List.map fst vars2) c1 c2
294
295 let finer_interpretation_than (vars1,c1) (vars2,c2) =
296 let c1 = adjust_application c1 c2 in
297 finer_notation_constr (List.map fst vars1, List.map fst vars2) c1 c2
298
299 (**********************************************************************)
300 (* Re-interpret a notation as a glob_constr, taking care of binders *)
301
302 let name_to_ident = function
303 | Anonymous -> CErrors.user_err Pp.(str "This expression should be a simple identifier.")
304 | Name id -> id
305
306 let to_id g e id = let e,na = g e (Name id) in e,name_to_ident na
307
308 let product_of_cases_patterns patl =
309 List.fold_right (fun patl restl ->
310 List.flatten (List.map (fun p -> List.map (fun rest -> p::rest) restl) patl))
311 patl [[]]
312
313 let rec cases_pattern_fold_map ?loc g e = DAst.with_val (function
314 | PatVar na ->
315 let e',disjpat,na' = g e na in
316 e', (match disjpat with
317 | None -> [DAst.make ?loc @@ PatVar na']
318 | Some ((_,disjpat),_) -> disjpat)
319 | PatCstr (cstr,patl,na) ->
320 let e',disjpat,na' = g e na in
321 if disjpat <> None then user_err (Pp.str "Unable to instantiate an \"as\" clause with a pattern.");
322 let e',patl' = List.fold_left_map (cases_pattern_fold_map ?loc g) e patl in
323 (* Distribute outwards the inner disjunctive patterns *)
324 let disjpatl' = product_of_cases_patterns patl' in
325 e', List.map (fun patl' -> DAst.make ?loc @@ PatCstr (cstr,patl',na')) disjpatl'
326 )
327
328 let subst_binder_type_vars l = function
329 | GBinderType (Name id) ->
330 let id =
331 try match DAst.get (Id.List.assoc id l) with GVar id' -> id' | _ -> id
332 with Not_found -> id in
333 GBinderType (Name id)
334 | e -> e
335
336 let rec subst_glob_vars l gc = DAst.map (function
337 | GVar id as r -> (try DAst.get (Id.List.assoc id l) with Not_found -> r)
338 | GHole x -> GHole (subst_binder_type_vars l x)
339 | _ ->
340 let g =
341 Name.map (fun id ->
342 try match DAst.get (Id.List.assoc id l) with GVar id' -> id' | _ -> id
343 with Not_found -> id) in
344 DAst.get (map_glob_constr_left_to_right_with_names (subst_glob_vars l) g gc) (* assume: id is not binding *)
345 ) gc
346
347 type 'a binder_status_fun = {
348 no : 'a -> 'a;
349 restart_prod : 'a -> 'a;
350 restart_lambda : 'a -> 'a;
351 switch_prod : 'a -> 'a;
352 switch_lambda : 'a -> 'a;
353 slide : 'a -> 'a;
354 }
355
356 let default_binder_status_fun = {
357 no = (fun x -> x);
358 restart_prod = (fun x -> x);
359 restart_lambda = (fun x -> x);
360 switch_prod = (fun x -> x);
361 switch_lambda = (fun x -> x);
362 slide = (fun x -> x);
363 }
364
365 let test_implicit_argument_mark bk =
366 if not (Glob_ops.binding_kind_eq bk Explicit) then
367 user_err (Pp.str "Unexpected implicit argument mark.")
368
369 let test_pattern_cast = function
370 | None -> ()
371 | Some t -> user_err ?loc:t.CAst.loc (Pp.str "Unsupported pattern cast.")
372
373 let protect g e na =
374 let e',disjpat,na,bk,t = g e na None in
375 if disjpat <> None then user_err (Pp.str "Unsupported substitution of an arbitrary pattern.");
376 test_implicit_argument_mark bk;
377 test_pattern_cast t;
378 e',na
379
380 let set_anonymous_type na = function
381 | None -> DAst.make @@ GHole (GBinderType na)
382 | Some t -> t
383
384 let apply_cases_pattern_term ?loc (ids,disjpat) tm c =
385 let eqns = List.map (fun pat -> (CAst.make ?loc (ids,[pat],c))) disjpat in
386 DAst.make ?loc @@ GCases (Constr.LetPatternStyle, None, [tm,(Anonymous,None)], eqns)
387
388 let apply_cases_pattern ?loc (ids_disjpat,id) c =
389 apply_cases_pattern_term ?loc ids_disjpat (DAst.make ?loc (GVar id)) c
390
391 let glob_constr_of_notation_constr_with_binders ?loc g f ?(h=default_binder_status_fun) e nc =
392 let lt x = DAst.make ?loc x in lt @@ match nc with
393 | NVar id -> GVar id
394 | NApp (a,args) -> let e = h.no e in DAst.get (mkGApp (f e a) (List.map (f e) args))
395 | NProj (p,args,c) -> let e = h.no e in GProj (p, List.map (f e) args, f e c)
396 | NList (x,y,iter,tail,swap) ->
397 let t = f e tail in let it = f e iter in
398 let innerl = (ldots_var,t)::(if swap then [y, lt @@ GVar x] else []) in
399 let inner = lt @@ GApp (lt @@ GVar (ldots_var),[subst_glob_vars innerl it]) in
400 let outerl = (ldots_var,inner)::(if swap then [] else [y, lt @@ GVar x]) in
401 DAst.get (subst_glob_vars outerl it)
402 | NBinderList (x,y,iter,tail,swap) ->
403 let t = f e tail in let it = f e iter in
404 let innerl = (ldots_var,t)::(if swap then [y, lt @@ GVar x] else []) in
405 let inner = lt @@ GApp (lt @@ GVar ldots_var,[subst_glob_vars innerl it]) in
406 let outerl = (ldots_var,inner)::(if swap then [] else [y, lt @@ GVar x]) in
407 DAst.get (subst_glob_vars outerl it)
408 | NLambda (na,ty,c) ->
409 let e = h.switch_lambda e in
410 let ty = Option.map (f (h.restart_prod e)) ty in
411 let e',disjpat,na',bk,ty = g e na ty in
412 GLambda (na',None,bk,set_anonymous_type na ty,Option.fold_right (apply_cases_pattern ?loc) disjpat (f e' c))
413 | NProd (na,ty,c) ->
414 let e = h.switch_prod e in
415 let ty = Option.map (f (h.restart_prod e)) ty in
416 let e',disjpat,na',bk,ty = g e na ty in
417 GProd (na',None,bk,set_anonymous_type na ty,Option.fold_right (apply_cases_pattern ?loc) disjpat (f e' c))
418 | NLetIn (na,b,t,c) ->
419 let t = Option.map (f (h.restart_prod e)) t in
420 let e',disjpat,na,bk,t = g e na t in
421 test_implicit_argument_mark bk;
422 (match disjpat with
423 | None -> GLetIn (na,None, f (h.restart_lambda e) b,t,f e' c)
424 | Some (disjpat,_id) -> test_pattern_cast t; DAst.get (apply_cases_pattern_term ?loc disjpat (f e b) (f e' c)))
425 | NCases (sty,rtntypopt,tml,eqnl) ->
426 let e = h.no e in
427 let e',tml' = List.fold_right (fun (tm,(na,t)) (e',tml') ->
428 let e',t' = match t with
429 | None -> e',None
430 | Some (ind,nal) ->
431 let e',nal' = List.fold_right (fun na (e',nal) ->
432 let e',na' = protect g e' na in
433 e',na'::nal) nal (e',[]) in
434 e',Some (CAst.make ?loc (ind,nal')) in
435 let e',na' = protect g e' na in
436 (e',(f e tm,(na',t'))::tml')) tml (e,[]) in
437 let fold (idl,e) na =
438 let (e,disjpat,na,bk,t) = g e na None in
439 test_implicit_argument_mark bk;
440 test_pattern_cast t;
441 ((Name.cons na idl,e),disjpat,na) in
442 let eqnl' = List.map (fun (patl,rhs) ->
443 let ((idl,e),patl) =
444 List.fold_left_map (cases_pattern_fold_map ?loc fold) ([],e) patl in
445 let disjpatl = product_of_cases_patterns patl in
446 List.map (fun patl -> CAst.make (idl,patl,f e rhs)) disjpatl) eqnl in
447 GCases (sty,Option.map (f e') rtntypopt,tml',List.flatten eqnl')
448 | NLetTuple (nal,(na,po),b,c) ->
449 let e = h.no e in
450 let e',nal = List.fold_left_map (protect g) e nal in
451 let e'',na = protect g e na in
452 GLetTuple (nal,(na,Option.map (f e'') po),f e b,f e' c)
453 | NIf (c,(na,po),b1,b2) ->
454 let e = h.no e in
455 let e',na = protect g e na in
456 GIf (f e c,(na,Option.map (f e') po),f e b1,f e b2)
457 | NRec (fk,idl,dll,tl,bl) ->
458 let e = h.no e in
459 let e,dll = Array.fold_left_map (List.fold_left_map (fun e (na,oc,b) ->
460 let e,na = protect g e na in
461 (e,(na,None,Explicit,Option.map (f e) oc,f e b)))) e dll in
462 let e',idl = Array.fold_left_map (to_id (protect g)) e idl in
463 GRec (fk,idl,dll,Array.map (f e) tl,Array.map (f e') bl)
464 | NCast (c,k,t) -> GCast (f e c, k, f (h.slide e) t)
465 | NSort x -> GSort x
466 | NHole x -> GHole x
467 | NGenarg arg -> GGenarg arg
468 | NRef (x,u) -> GRef (x,u)
469 | NInt i -> GInt i
470 | NFloat f -> GFloat f
471 | NString s -> GString s
472 | NArray (t,def,ty) -> GArray(None, Array.map (f e) t, f e def, f e ty)
473
474 let glob_constr_of_notation_constr ?loc x =
475 let rec aux () x =
476 glob_constr_of_notation_constr_with_binders ?loc (fun () id t -> ((),None,id,Explicit,t)) aux () x
477 in aux () x
478
479 let pr_notation_info prglob ntn c =
480 str (String.quote_coq_string ntn) ++ str " :=" ++ spc() ++
481 prglob (glob_constr_of_notation_constr c)
482
483 (******************************************************************************)
484 (* Translating a glob_constr into a notation, interpreting recursive patterns *)
485
486 type found_variables = {
487 vars : Id.t list;
488 recursive_term_vars : (Id.t * Id.t) list;
489 recursive_binders_vars : (Id.t * Id.t) list;
490 }
491
492 let add_id r id = r := { !r with vars = id :: (!r).vars }
493 let add_name r = function Anonymous -> () | Name id -> add_id r id
494
495 let mkNApp1 (g,a) =
496 match g with
497 (* Ensure flattening of nested applicative nodes *)
498 | NApp (g,args') -> NApp (g,args'@[a])
499 | _ -> NApp (g,[a])
500
501 let is_gvar id c = match DAst.get c with
502 | GVar id' -> Id.equal id id'
503 | _ -> false
504
505 let split_at_recursive_part c =
506 let sub = ref None in
507 let rec aux c =
508 let loc0 = c.CAst.loc in
509 match DAst.get c with
510 | GApp (f, c::l) when is_gvar ldots_var f -> (* *)
511 let loc = f.CAst.loc in
512 begin match !sub with
513 | None ->
514 let () = sub := Some c in
515 begin match l with
516 | [] -> DAst.make ?loc @@ GVar ldots_var
517 | _ :: _ -> DAst.make ?loc:loc0 @@ GApp (DAst.make ?loc @@ GVar ldots_var, l)
518 end
519 | Some _ ->
520 (* Not narrowed enough to find only one recursive part *)
521 raise Not_found
522 end
523 | _ -> map_glob_constr aux c in
524 let outer_iterator = aux c in
525 match !sub with
526 | None -> (* No recursive pattern found *) raise Not_found
527 | Some c ->
528 match DAst.get outer_iterator with
529 | GVar v when Id.equal v ldots_var -> (* Not enough context *) raise Not_found
530 | _ -> outer_iterator, c
531
532 let subtract_loc loc1 loc2 =
533 let l1 = fst (Option.cata Loc.unloc (0,0) loc1) in
534 let l2 = fst (Option.cata Loc.unloc (0,0) loc2) in
535 Some (Loc.make_loc (l1,l2-1))
536
537 let check_is_hole id = function
538 | None -> ()
539 | Some t -> match DAst.get t with GHole _ -> () | _ ->
540 user_err ?loc:(loc_of_glob_constr t)
541 (strbrk "In recursive notation with binders, " ++ Id.print id ++
542 strbrk " is expected to come without type.")
543
544 let check_pair_matching ?loc x y x' y' revert revert' =
545 if not (Id.equal x x' && Id.equal y y' && revert = revert') then
546 let x,y = if revert then y,x else x,y in
547 let x',y' = if revert' then y',x' else x',y' in
548 (* This is a case where one would like to highlight two locations! *)
549 user_err ?loc
550 (strbrk "Found " ++ Id.print x ++ strbrk " matching " ++ Id.print y ++
551 strbrk " while " ++ Id.print x' ++ strbrk " matching " ++ Id.print y' ++
552 strbrk " was first found.")
553
554 let mem_recursive_pair (x,y) l = List.mem_f (eq_pair Id.equal Id.equal) (x,y) l
555
556 type recursive_pattern_kind =
557 | RecursiveTerms of bool (* in reverse order *)
558 | RecursiveBinders of bool (* in reverse order *)
559
560 let compare_recursive_parts recvars found f f' (iterator,subc) =
561 let diff = ref None in
562 let terminator = ref None in
563 let treat_binder ?loc x y t_x t_y =
564 match x, y with
565 | Name x, Name y when mem_recursive_pair (x,y) recvars || mem_recursive_pair (y,x) recvars ->
566 (* We found a binding position where it differs *)
567 check_is_hole x t_x;
568 check_is_hole y t_y;
569 let revert = mem_recursive_pair (y,x) recvars in
570 let x,y = if revert then y,x else x,y in
571 begin match !diff with
572 | None -> diff := Some (x, y, RecursiveBinders revert)
573 | Some (x', y', RecursiveBinders revert') ->
574 check_pair_matching ?loc x y x' y' revert revert'
575 | Some (x', y', RecursiveTerms revert') ->
576 (* Recursive binders have precedence: they can be coerced to
577 terms but not reciprocally *)
578 check_pair_matching ?loc x y x' y' revert revert';
579 diff := Some (x, y, RecursiveBinders revert)
580 end;
581 true
582 | _ -> Name.equal x y
583 in
584 let rec aux c1 c2 = match DAst.get c1, DAst.get c2 with
585 | GVar v, term when Id.equal v ldots_var ->
586 (* We found the pattern *)
587 assert (match !terminator with None -> true | Some _ -> false);
588 terminator := Some c2;
589 true
590 | GApp (f,l1), GApp (term, l2) ->
591 begin match DAst.get f with
592 | GVar v when Id.equal v ldots_var ->
593 (* We found the pattern, but there are extra arguments *)
594 (* (this allows e.g. alternative (recursive) notation of application) *)
595 assert (match !terminator with None -> true | Some _ -> false);
596 terminator := Some term;
597 List.for_all2eq aux l1 l2
598 | _ -> mk_glob_constr_eq aux (treat_binder ?loc:c1.CAst.loc) c1 c2
599 end
600 | GVar x, GVar y
601 when mem_recursive_pair (x,y) recvars || mem_recursive_pair (y,x) recvars ->
602 (* We found the position where it differs *)
603 let revert = mem_recursive_pair (y,x) recvars in
604 let x,y = if revert then y,x else x,y in
605 begin match !diff with
606 | None ->
607 let () = diff := Some (x, y, RecursiveTerms revert) in
608 true
609 | Some (x', y', RecursiveTerms revert')
610 | Some (x', y', RecursiveBinders revert') ->
611 check_pair_matching ?loc:c1.CAst.loc x y x' y' revert revert';
612 true
613 end
614 | _ ->
615 mk_glob_constr_eq aux (treat_binder ?loc:c1.CAst.loc) c1 c2 in
616 if aux iterator subc then
617 match !diff with
618 | None ->
619 let loc1 = loc_of_glob_constr iterator in
620 let loc2 = loc_of_glob_constr (Option.get !terminator) in
621 (* Here, we would need a loc made of several parts ... *)
622 user_err ?loc:(subtract_loc loc1 loc2)
623 (str "Both ends of the recursive pattern are the same.")
624 | Some (x,y,RecursiveTerms revert) ->
625 (* By arbitrary convention, we use the second variable of the pair
626 as the place-holder for the iterator *)
627 let iterator =
628 f' (if revert then iterator else subst_glob_vars [x, DAst.make @@ GVar y] iterator) in
629 (* found variables have been collected by compare_constr *)
630 found := { !found with vars = List.remove Id.equal y (!found).vars;
631 recursive_term_vars = List.add_set (eq_pair Id.equal Id.equal) (x,y) (!found).recursive_term_vars };
632 NList (x,y,iterator,f (Option.get !terminator),revert)
633 | Some (x,y,RecursiveBinders revert) ->
634 let iterator =
635 f' (if revert then iterator else subst_glob_vars [x, DAst.make @@ GVar y] iterator) in
636 (* found have been collected by compare_constr *)
637 found := { !found with vars = List.remove Id.equal y (!found).vars;
638 recursive_binders_vars = List.add_set (eq_pair Id.equal Id.equal) (x,y) (!found).recursive_binders_vars };
639 NBinderList (x,y,iterator,f (Option.get !terminator),revert)
640 else
641 raise Not_found
642
643 let notation_constr_and_vars_of_glob_constr recvars a =
644 let found = ref { vars = []; recursive_term_vars = []; recursive_binders_vars = [] } in
645 let forgetful = ref { forget_ltac = false; forget_volatile_cast = false } in
646 (* Turn a glob_constr into a notation_constr by first trying to find a recursive pattern *)
647 let rec aux c =
648 let keepfound = !found in
649 (* n^2 complexity but small and done only once per notation *)
650 try compare_recursive_parts recvars found aux aux' (split_at_recursive_part c)
651 with Not_found ->
652 found := keepfound;
653 match DAst.get c with
654 | GApp (t, [_]) ->
655 begin match DAst.get t with
656 | GVar f when Id.equal f ldots_var ->
657 (* Fall on the second part of the recursive pattern w/o having
658 found the first part *)
659 let loc = t.CAst.loc in
660 user_err ?loc
661 (str "Cannot find where the recursive pattern starts.")
662 | _ -> aux' c
663 end
664 | _c ->
665 aux' c
666 and aux' x = DAst.with_val (function
667 | GVar id -> if not (Id.equal id ldots_var) then add_id found id; NVar id
668 | GApp (g,[]) -> NApp (aux g,[]) (* Encoding @foo *)
669 | GApp (g,args) ->
670 (* Treat applicative notes as binary nodes *)
671 let a,args = List.sep_last args in mkNApp1 (aux (DAst.make (GApp (g, args))), aux a)
672 | GProj (p,args,c) -> NProj (p, List.map aux args, aux c)
673 | GLambda (na,_,bk,ty,c) -> add_name found na; NLambda (na,aux_type ty,aux c)
674 | GProd (na,_,bk,ty,c) -> add_name found na; NProd (na,aux_type ty,aux c)
675 | GLetIn (na,_,b,t,c) -> add_name found na; NLetIn (na,aux b,Option.map aux t, aux c)
676 | GCases (sty,rtntypopt,tml,eqnl) ->
677 let f {CAst.v=(idl,pat,rhs)} = List.iter (add_id found) idl; (pat,aux rhs) in
678 NCases (sty,Option.map aux rtntypopt,
679 List.map (fun (tm,(na,x)) ->
680 add_name found na;
681 Option.iter
682 (fun {CAst.v=(_,nl)} -> List.iter (add_name found) nl) x;
683 (aux tm,(na,Option.map (fun {CAst.v=(ind,nal)} -> (ind,nal)) x))) tml,
684 List.map f eqnl)
685 | GLetTuple (nal,(na,po),b,c) ->
686 add_name found na;
687 List.iter (add_name found) nal;
688 NLetTuple (nal,(na,Option.map aux po),aux b,aux c)
689 | GIf (c,(na,po),b1,b2) ->
690 add_name found na;
691 NIf (aux c,(na,Option.map aux po),aux b1,aux b2)
692 | GRec (fk,idl,dll,tl,bl) ->
693 Array.iter (add_id found) idl;
694 let dll = Array.map (List.map (fun (na,_,bk,oc,b) ->
695 if bk != Explicit then
696 user_err Pp.(str "Binders marked as implicit not allowed in notations.");
697 add_name found na; (na,Option.map aux oc,aux b))) dll in
698 NRec (fk,idl,dll,Array.map aux tl,Array.map aux bl)
699 | GCast (c,k,t) ->
700 if Option.is_empty k then forgetful := { !forgetful with forget_volatile_cast = true };
701 NCast (aux c, k, aux t)
702 | GSort s -> NSort s
703 | GInt i -> NInt i
704 | GFloat f -> NFloat f
705 | GString s -> NString s
706 | GHole w -> NHole w
707 | GGenarg arg -> forgetful := { !forgetful with forget_ltac = true }; NGenarg arg
708 | GRef (r,u) -> NRef (r,u)
709 | GArray (_u,t,def,ty) -> NArray (Array.map aux t, aux def, aux ty)
710 | GEvar _ | GPatVar _ ->
711 user_err Pp.(str "Existential variables not allowed in notations.")
712 ) x
713 and aux_type t = DAst.with_val (function
714 | GHole (GBinderType _) -> None
715 | _ -> Some (aux t)) t
716 in
717 let t = aux a in
718 (* Side effect *)
719 t, !found, !forgetful
720
721 let check_variables_and_reversibility nenv
722 { vars = found; recursive_term_vars = foundrec; recursive_binders_vars = foundrecbinding } =
723 let injective = ref [] in
724 let recvars = nenv.ninterp_rec_vars in
725 let fold _ y accu = Id.Set.add y accu in
726 let useless_vars = Id.Map.fold fold recvars Id.Set.empty in
727 let filter y _ = not (Id.Set.mem y useless_vars) in
728 let vars = Id.Map.filter filter nenv.ninterp_var_type in
729 let check_recvar x =
730 if Id.List.mem x found then
731 user_err (Id.print x ++
732 strbrk " should only be used in the recursive part of a pattern.") in
733 let check (x, y) = check_recvar x; check_recvar y in
734 let () = List.iter check foundrec in
735 let () = List.iter check foundrecbinding in
736 let check_bound x =
737 if not (Id.List.mem x found) then
738 if Id.List.mem_assoc x foundrec ||
739 Id.List.mem_assoc x foundrecbinding ||
740 Id.List.mem_assoc_sym x foundrec ||
741 Id.List.mem_assoc_sym x foundrecbinding
742 then
743 user_err Pp.(str
744 (Id.to_string x ^
745 " should not be bound in a recursive pattern of the right-hand side."))
746 else injective := x :: !injective
747 in
748 let check_pair s x y where =
749 if not (mem_recursive_pair (x,y) where) then
750 user_err (strbrk "in the right-hand side, " ++ Id.print x ++
751 str " and " ++ Id.print y ++ strbrk " should appear in " ++ str s ++
752 str " position as part of a recursive pattern.") in
753 let check_type x typ =
754 match typ with
755 | NtnInternTypeAny _ ->
756 begin
757 try check_pair "term" x (Id.Map.find x recvars) foundrec
758 with Not_found -> check_bound x
759 end
760 | NtnInternTypeOnlyBinder ->
761 begin
762 try check_pair "binding" x (Id.Map.find x recvars) foundrecbinding
763 with Not_found -> check_bound x
764 end in
765 Id.Map.iter check_type vars;
766 List.rev !injective
767
768 let[@warning "+9"] is_forgetful { forget_ltac; forget_volatile_cast } =
769 forget_ltac || forget_volatile_cast
770
771 let notation_constr_of_glob_constr nenv a =
772 let recvars = Id.Map.bindings nenv.ninterp_rec_vars in
773 let a, found, forgetful = notation_constr_and_vars_of_glob_constr recvars a in
774 let injective = check_variables_and_reversibility nenv found in
775 let status = if is_forgetful forgetful then Forgetful forgetful
776 else match injective with
777 | [] -> APrioriReversible
778 | l -> NonInjective l in
779 a, status
780
781 (**********************************************************************)
782 (* Substitution of kernel names, avoiding a list of bound identifiers *)
783
784 let notation_constr_of_constr ~flags avoid t =
785 let t = EConstr.of_constr t in
786 let env = Global.env () in
787 let evd = Evd.from_env env in
788 let t = Detyping.detype Detyping.Now ~flags ~avoid env evd t in
789 let nenv = {
790 ninterp_var_type = Id.Map.empty;
791 ninterp_rec_vars = Id.Map.empty;
792 } in
793 notation_constr_of_glob_constr nenv t
794
795 let rec subst_pat subst pat =
796 match DAst.get pat with
797 | PatVar _ -> pat
798 | PatCstr (((kn,i),j),cpl,n) ->
799 let kn' = subst_mind subst kn
800 and cpl' = List.Smart.map (subst_pat subst) cpl in
801 if kn' == kn && cpl' == cpl then pat else
802 DAst.make ?loc:pat.CAst.loc @@ PatCstr (((kn',i),j),cpl',n)
803
804 let rec subst_notation_constr subst bound raw =
805 match raw with
806 | NRef (ref,u) ->
807 let ref',t = subst_global subst ref in
808 if ref' == ref then raw else (match t with
809 | None -> NRef (ref',u)
810 | Some t ->
811 let flags = PrintingFlags.Detype.current() in
812 fst (notation_constr_of_constr ~flags bound t.UVars.univ_abstracted_value))
813
814 | NVar _ -> raw
815
816 | NApp (r,rl) ->
817 let r' = subst_notation_constr subst bound r
818 and rl' = List.Smart.map (subst_notation_constr subst bound) rl in
819 if r' == r && rl' == rl then raw else
820 NApp(r',rl')
821
822 | NProj ((cst,u),rl,r) ->
823 let ref = GlobRef.ConstRef cst in
824 let ref',t = subst_global subst ref in
825 assert (t = None);
826 let rl' = List.Smart.map (subst_notation_constr subst bound) rl
827 and r' = subst_notation_constr subst bound r in
828 if ref' == ref && rl' == rl && r' == r then raw else
829 NProj ((destConstRef ref',u),rl',r')
830
831 | NList (id1,id2,r1,r2,b) ->
832 let r1' = subst_notation_constr subst bound r1
833 and r2' = subst_notation_constr subst bound r2 in
834 if r1' == r1 && r2' == r2 then raw else
835 NList (id1,id2,r1',r2',b)
836
837 | NLambda (n,r1,r2) ->
838 let r1' = Option.Smart.map (subst_notation_constr subst bound) r1
839 and r2' = subst_notation_constr subst bound r2 in
840 if r1' == r1 && r2' == r2 then raw else
841 NLambda (n,r1',r2')
842
843 | NProd (n,r1,r2) ->
844 let r1' = Option.Smart.map (subst_notation_constr subst bound) r1
845 and r2' = subst_notation_constr subst bound r2 in
846 if r1' == r1 && r2' == r2 then raw else
847 NProd (n,r1',r2')
848
849 | NBinderList (id1,id2,r1,r2,b) ->
850 let r1' = subst_notation_constr subst bound r1
851 and r2' = subst_notation_constr subst bound r2 in
852 if r1' == r1 && r2' == r2 then raw else
853 NBinderList (id1,id2,r1',r2',b)
854
855 | NLetIn (n,r1,t,r2) ->
856 let r1' = subst_notation_constr subst bound r1 in
857 let t' = Option.Smart.map (subst_notation_constr subst bound) t in
858 let r2' = subst_notation_constr subst bound r2 in
859 if r1' == r1 && t == t' && r2' == r2 then raw else
860 NLetIn (n,r1',t',r2')
861
862 | NCases (sty,rtntypopt,rl,branches) ->
863 let rtntypopt' = Option.Smart.map (subst_notation_constr subst bound) rtntypopt
864 and rl' = List.Smart.map
865 (fun (a,(n,signopt) as x) ->
866 let a' = subst_notation_constr subst bound a in
867 let signopt' = Option.map (fun ((indkn,i),nal as z) ->
868 let indkn' = subst_mind subst indkn in
869 if indkn == indkn' then z else ((indkn',i),nal)) signopt in
870 if a' == a && signopt' == signopt then x else (a',(n,signopt')))
871 rl
872 and branches' = List.Smart.map
873 (fun (cpl,r as branch) ->
874 let cpl' = List.Smart.map (subst_pat subst) cpl
875 and r' = subst_notation_constr subst bound r in
876 if cpl' == cpl && r' == r then branch else
877 (cpl',r'))
878 branches
879 in
880 if rtntypopt' == rtntypopt && rtntypopt == rtntypopt' &&
881 rl' == rl && branches' == branches then raw else
882 NCases (sty,rtntypopt',rl',branches')
883
884 | NLetTuple (nal,(na,po),b,c) ->
885 let po' = Option.Smart.map (subst_notation_constr subst bound) po
886 and b' = subst_notation_constr subst bound b
887 and c' = subst_notation_constr subst bound c in
888 if po' == po && b' == b && c' == c then raw else
889 NLetTuple (nal,(na,po'),b',c')
890
891 | NIf (c,(na,po),b1,b2) ->
892 let po' = Option.Smart.map (subst_notation_constr subst bound) po
893 and b1' = subst_notation_constr subst bound b1
894 and b2' = subst_notation_constr subst bound b2
895 and c' = subst_notation_constr subst bound c in
896 if po' == po && b1' == b1 && b2' == b2 && c' == c then raw else
897 NIf (c',(na,po'),b1',b2')
898
899 | NRec (fk,idl,dll,tl,bl) ->
900 let dll' =
901 Array.Smart.map (List.Smart.map (fun (na,oc,b as x) ->
902 let oc' = Option.Smart.map (subst_notation_constr subst bound) oc in
903 let b' = subst_notation_constr subst bound b in
904 if oc' == oc && b' == b then x else (na,oc',b'))) dll in
905 let tl' = Array.Smart.map (subst_notation_constr subst bound) tl in
906 let bl' = Array.Smart.map (subst_notation_constr subst bound) bl in
907 if dll' == dll && tl' == tl && bl' == bl then raw else
908 NRec (fk,idl,dll',tl',bl')
909
910 | NSort _ -> raw
911 | NInt _ -> raw
912 | NFloat _ -> raw
913 | NString _ -> raw
914
915 | NHole knd ->
916 let nknd = match knd with
917 | GImplicitArg (ref, i, b) ->
918 let nref, _ = subst_global subst ref in
919 if nref == ref then knd else GImplicitArg (nref, i, b)
920 | _ -> knd
921 in
922 if nknd == knd then raw
923 else NHole nknd
924
925 | NGenarg arg ->
926 let arg' = Gensubst.generic_substitute subst arg in
927 if arg' == arg then raw
928 else NGenarg arg'
929
930 | NCast (r1,k,t) ->
931 let r1' = subst_notation_constr subst bound r1 in
932 let t' = subst_notation_constr subst bound t in
933 if r1' == r1 && t' == t then raw else NCast(r1',k,t')
934
935 | NArray (t,def,ty) ->
936 let def' = subst_notation_constr subst bound def
937 and t' = Array.Smart.map (subst_notation_constr subst bound) t
938 and ty' = subst_notation_constr subst bound ty
939 in
940 if def' == def && t' == t && ty' == ty then raw else
941 NArray(t',def',ty')
942
943 let subst_interpretation subst (metas,pat) =
944 let bound = List.fold_left (fun accu (id, _) -> Fresh.add id accu) Fresh.empty metas in
945 (metas,subst_notation_constr subst (Namegen.Generator.fresh, bound) pat)
946
947 (**********************************************************************)
948 (* Pattern-matching a [glob_constr] against a [notation_constr] *)
949
950 let abstract_return_type_context pi mklam tml rtno =
951 Option.map (fun rtn ->
952 let nal =
953 List.flatten (List.map (fun (_,(na,t)) ->
954 match t with Some x -> (pi x)@[na] | None -> [na]) tml) in
955 List.fold_right mklam nal rtn)
956 rtno
957
958 let abstract_return_type_context_glob_constr tml rtn =
959 abstract_return_type_context (fun {CAst.v=(_,nal)} -> nal)
960 (fun na c -> DAst.make @@
961 GLambda(na,None,Explicit,DAst.make @@ GHole (GInternalHole), c)) tml rtn
962
963 let abstract_return_type_context_notation_constr tml rtn =
964 abstract_return_type_context snd
965 (fun na c -> NLambda(na,None,c)) tml rtn
966
967 let rec push_pattern_binders vars pat =
968 match DAst.get pat with
969 | PatVar na -> Termops.add_vname vars na
970 | PatCstr (c, pl, na) -> List.fold_left push_pattern_binders (Termops.add_vname vars na) pl
971
972 let rec push_context_binders vars = function
973 | [] -> vars
974 | b :: bl ->
975 let vars = match DAst.get b with
976 | GLocalAssum (na,_,_,_) -> Termops.add_vname vars na
977 | GLocalPattern ((disjpat,ids),p,bk,t) -> List.fold_right Id.Set.add ids vars
978 | GLocalDef (na,_,_,_) -> Termops.add_vname vars na in
979 push_context_binders vars bl
980
981 let is_term_meta id metas =
982 try match Id.List.assoc id metas with NtnTypeConstr | NtnTypeConstrList -> true | _ -> false
983 with Not_found -> false
984
985 let is_onlybinding_strict_meta id metas =
986 try match Id.List.assoc id metas with NtnTypeBinder (NtnBinderParsedAsSomeBinderKind AsStrictPattern) -> true | _ -> false
987 with Not_found -> false
988
989 let is_onlybinding_meta id metas =
990 try match Id.List.assoc id metas with NtnTypeBinder _ -> true | _ -> false
991 with Not_found -> false
992
993 let is_onlybindinglist_meta id metas =
994 try match Id.List.assoc id metas with NtnTypeBinderList _ -> true | _ -> false
995 with Not_found -> false
996
997 let is_onlybinding_pattern_like_meta isvar id metas =
998 try match Id.List.assoc id metas with
999 | NtnTypeBinder (NtnBinderParsedAsConstr (AsAnyPattern | AsStrictPattern)) -> true
1000 | NtnTypeBinder (NtnBinderParsedAsSomeBinderKind AsStrictPattern | NtnBinderParsedAsBinder) -> not isvar
1001 | NtnTypeBinder (NtnBinderParsedAsSomeBinderKind AsAnyPattern) -> true
1002 | NtnTypeBinder (NtnBinderParsedAsSomeBinderKind (AsIdent | AsName)) -> false
1003 | NtnTypeBinder (NtnBinderParsedAsConstr (AsIdent | AsName)) -> false
1004 | NtnTypeBinderList _ | NtnTypeConstr | NtnTypeConstrList -> false
1005 with Not_found -> false
1006
1007 let is_bindinglist_meta id metas =
1008 try match Id.List.assoc id metas with NtnTypeBinderList _ -> true | _ -> false
1009 with Not_found -> false
1010
1011 exception No_match
1012
1013 let alpha_rename renaming v =
1014 if renaming == [] then (* shortcut: *) v
1015 else try rename_glob_vars renaming v with UnsoundRenaming -> raise No_match
1016
1017 let static_binder_escape staticbinders v =
1018 List.exists (function (Name id,_) -> occur_glob_constr id v | (Anonymous,_) -> false) staticbinders
1019
1020 let add_env {actualvars;staticbinders;renaming} (terms,termlists,binders,binderlists) var v =
1021 (* Check that no capture of binding variables occur *)
1022 (* [staticbinders] is used when matching a pattern "fun x => ... x ... ?var ... x ..."
1023 with an actual term "fun z => ... z ..." when "x" is not bound in the
1024 notation, as in "Notation "'twice_upto' y" := (fun x => x + x + y)". Then
1025 we keep (z,x) in staticbinders, and we have to check that what the [v] which is bound
1026 to [var] does not contain z *)
1027 if not (Id.equal ldots_var var) && static_binder_escape staticbinders v then raise No_match;
1028 (* [renaming] is used when matching a pattern "fun x => ... x ... ?var ... x ..."
1029 with an actual term "fun z => ... z ..." when "x" is bound in the
1030 notation and the name "x" cannot be changed to "z", e.g. because
1031 used at another occurrence, as in "Notation "'lam' y , P & Q" :=
1032 ((fun y => P),(fun y => Q))". Then, we keep (z,y) in renaming, and we
1033 have to check that "fun z => ... z ..." denotes the same term as
1034 "fun x => ... x ... ?var ... x" up to alpha-conversion when [var]
1035 is instantiated by [v];
1036 Currently, we fail, but, eventually, [x] in [v] could be replaced by [x],
1037 and, in match_, when finding "x" in subterm, failing because of a capture,
1038 and, in match_, when finding "z" in subterm, replacing it with "x",
1039 and, in an even further step, being even more robust, independent of the order, so
1040 that e.g. the notation for ex2 works on "x y |- ex2 (fun x => y=x) (fun y => x=y)"
1041 by giving, say, "exists2 x0, y=x0 & x=x0", but this would typically require the
1042 glob_constr_eq in bind_term_env to be postponed in match_notation_constr, and the
1043 choice of exact variable be done there; but again, this would be a non-trivial
1044 refinement *)
1045 let v = alpha_rename renaming v in
1046 (* TODO: handle the case of multiple occs in different scopes *)
1047 ((var,(actualvars,staticbinders,v))::terms,termlists,binders,binderlists)
1048
1049 let add_termlist_env {actualvars;staticbinders;renaming} (terms,termlists,binders,binderlists) var vl =
1050 if List.exists (static_binder_escape staticbinders) vl then raise No_match;
1051 let vl = List.map (alpha_rename renaming) vl in
1052 (terms,(var,(actualvars,vl))::termlists,binders,binderlists)
1053
1054 let add_binding_env {actualvars} (terms,termlists,binders,binderlists) var v =
1055 (* TODO: handle the case of multiple occs in different scopes *)
1056 (terms,termlists,(var,(actualvars,v))::binders,binderlists)
1057
1058 let add_bindinglist_env {actualvars} (terms,termlists,binders,binderlists) var bl =
1059 (terms,termlists,binders,(var,(actualvars,bl))::binderlists)
1060
1061 let rec map_cases_pattern_name_left f = DAst.map (function
1062 | PatVar na -> PatVar (f na)
1063 | PatCstr (c,l,na) -> PatCstr (c,List.map_left (map_cases_pattern_name_left f) l,f na)
1064 )
1065
1066 let rec fold_cases_pattern_eq f x p p' =
1067 let loc = p.CAst.loc in
1068 match DAst.get p, DAst.get p' with
1069 | PatVar na, PatVar na' -> let x,na = f x na na' in x, DAst.make ?loc @@ PatVar na
1070 | PatCstr (c,l,na), PatCstr (c',l',na') when Construct.CanOrd.equal c c' ->
1071 let x,l = fold_cases_pattern_list_eq f x l l' in
1072 let x,na = f x na na' in
1073 x, DAst.make ?loc @@ PatCstr (c,l,na)
1074 | _ -> failwith "Not equal"
1075
1076 and fold_cases_pattern_list_eq f x pl pl' = match pl, pl' with
1077 | [], [] -> x, []
1078 | p::pl, p'::pl' ->
1079 let x, p = fold_cases_pattern_eq f x p p' in
1080 let x, pl = fold_cases_pattern_list_eq f x pl pl' in
1081 x, p :: pl
1082 | _ -> assert false
1083
1084 let rec cases_pattern_eq p1 p2 = match DAst.get p1, DAst.get p2 with
1085 | PatVar na1, PatVar na2 -> Name.equal na1 na2
1086 | PatCstr (c1, pl1, na1), PatCstr (c2, pl2, na2) ->
1087 Construct.CanOrd.equal c1 c2 && List.equal cases_pattern_eq pl1 pl2 &&
1088 Name.equal na1 na2
1089 | _ -> false
1090
1091 let rec pat_binder_of_term t = DAst.map (function
1092 | GVar id -> PatVar (Name id)
1093 | GApp (t, l) ->
1094 begin match DAst.get t with
1095 | GRef (GlobRef.ConstructRef cstr,_) ->
1096 let nparams = Inductiveops.inductive_nparams (Global.env()) (fst cstr) in
1097 let _,l = List.chop nparams l in
1098 PatCstr (cstr, List.map pat_binder_of_term l, Anonymous)
1099 | _ -> raise No_match
1100 end
1101 | _ -> raise No_match
1102 ) t
1103
1104 let unify_name_upto ({actualvars;staticbinders;renaming} as alp) na na' =
1105 match na, na' with
1106 | Anonymous, na' -> {alp with actualvars = Termops.add_vname actualvars na'}, na'
1107 | na, Anonymous -> {alp with actualvars = Termops.add_vname actualvars na}, na
1108 | Name id, Name id' ->
1109 let vars = Termops.add_vname actualvars na' in
1110 if Id.equal id id' then {alp with actualvars = vars}, na'
1111 else {actualvars = vars; staticbinders; renaming = (id,id')::renaming}, na'
1112
1113 let unify_pat_upto alp p p' =
1114 try fold_cases_pattern_eq unify_name_upto alp p p' with Failure _ -> raise No_match
1115
1116 let unify_term renaming v v' =
1117 match DAst.get v, DAst.get v' with
1118 | GHole _, _ -> v'
1119 | _, GHole _ -> v
1120 | _, _ -> let v = alpha_rename renaming v in if glob_constr_eq v v' then v else raise No_match
1121
1122 let unify_opt_term alp v v' =
1123 match v, v' with
1124 | Some t, Some t' -> Some (unify_term alp t t')
1125 | (Some _ as x), None | None, (Some _ as x) -> x
1126 | None, None -> None
1127
1128 let unify_binding_kind bk bk' = if bk == bk' then bk' else raise No_match
1129
1130 let unify_relevance_info r r' = if relevance_info_eq r r' then r else raise No_match
1131
1132 let unify_binder_upto alp b b' =
1133 let loc, loc' = CAst.(b.loc, b'.loc) in
1134 match DAst.get b, DAst.get b' with
1135 | GLocalAssum (na,r,bk,t), GLocalAssum (na',r',bk',t') ->
1136 let alp', na = unify_name_upto alp na na' in
1137 alp', DAst.make ?loc @@
1138 GLocalAssum
1139 (na,
1140 unify_relevance_info r r',
1141 unify_binding_kind bk bk',
1142 unify_term alp.renaming t t')
1143 | GLocalDef (na,r,c,t), GLocalDef (na',r',c',t') ->
1144 let alp', na = unify_name_upto alp na na' in
1145 alp', DAst.make ?loc @@
1146 GLocalDef
1147 (na,
1148 unify_relevance_info r r',
1149 unify_term alp.renaming c c',
1150 unify_opt_term alp.renaming t t')
1151 | GLocalPattern ((disjpat,ids),id,bk,t), GLocalPattern ((disjpat',_),_,bk',t') when List.length disjpat = List.length disjpat' ->
1152 let alp', p = List.fold_left2_map unify_pat_upto alp disjpat disjpat' in
1153 alp', DAst.make ?loc @@ GLocalPattern ((p,ids), id, unify_binding_kind bk bk', unify_term alp.renaming t t')
1154 | _ -> raise No_match
1155
1156 let rec unify_terms alp vl vl' =
1157 match vl, vl' with
1158 | [], [] -> []
1159 | v :: vl, v' :: vl' -> unify_term alp v v' :: unify_terms alp vl vl'
1160 | _ -> raise No_match
1161
1162 let rec unify_binders_upto alp bl bl' =
1163 match bl, bl' with
1164 | [], [] -> alp, []
1165 | b :: bl, b' :: bl' ->
1166 let alp,b = unify_binder_upto alp b b' in
1167 let alp,bl = unify_binders_upto alp bl bl' in
1168 alp, b :: bl
1169 | _ -> raise No_match
1170
1171 let unify_id renaming id na' =
1172 let id = rename_var renaming id in
1173 match na' with
1174 | Anonymous -> Name id
1175 | Name id' -> if Id.equal id id' then na' else raise No_match
1176
1177 let unify_pat renaming p p' =
1178 if cases_pattern_eq (map_cases_pattern_name_left (Name.map (rename_var renaming)) p) p' then p'
1179 else raise No_match
1180
1181 let unify_term_binder renaming c = DAst.(map (fun b' ->
1182 match DAst.get c, b' with
1183 | GVar id, GLocalAssum (na', r', bk', t') ->
1184 GLocalAssum (unify_id renaming id na', r', bk', t')
1185 | _, GLocalPattern (([p'],ids), id, bk', t') ->
1186 let p = pat_binder_of_term c in
1187 GLocalPattern (([unify_pat renaming p p'],ids), id, bk', t')
1188 | _ -> raise No_match))
1189
1190 let rec unify_terms_binders renaming cl bl' =
1191 match cl, bl' with
1192 | [], [] -> []
1193 | c :: cl', b' :: bl' ->
1194 begin match DAst.get b' with
1195 | GLocalDef (_, _, _, t) -> b' :: unify_terms_binders renaming cl bl'
1196 | _ -> unify_term_binder renaming c b' :: unify_terms_binders renaming cl' bl'
1197 end
1198 | _ -> raise No_match
1199
1200 let bind_term_env alp (terms,termlists,binders,binderlists as sigma) var v =
1201 try
1202 (* If already bound to a term, unify with the new term *)
1203 let vars,_alp',v' = Id.List.assoc var terms in
1204 (* Note: at Notation definition time, it should have been checked that v and v' are
1205 in the same static context, i.e. alp.staticbinders = _alp'.staticbinders *)
1206 let v'' = unify_term alp.renaming v v' in
1207 if v'' == v' then sigma else
1208 let sigma = (Id.List.remove_assoc var terms,termlists,binders,binderlists) in
1209 let alp' = {alp with actualvars = Id.Set.union vars alp.actualvars} in
1210 add_env alp' sigma var v
1211 with Not_found -> add_env alp sigma var v
1212
1213 let bind_termlist_env alp (terms,termlists,binders,binderlists as sigma) var vl =
1214 try
1215 (* If already bound to a list of term, unify with the new terms *)
1216 let vars,vl' = Id.List.assoc var termlists in
1217 let vl = unify_terms alp.renaming vl vl' in
1218 let sigma = (terms,Id.List.remove_assoc var termlists,binders,binderlists) in
1219 let alp' = {alp with actualvars = Id.Set.union vars alp.actualvars} in
1220 add_termlist_env alp' sigma var vl
1221 with Not_found -> add_termlist_env alp sigma var vl
1222
1223 let bind_term_as_binding_env alp (terms,termlists,binders,binderlists as sigma) var id =
1224 try
1225 (* If already bound to a term, unify the binder and the term *)
1226 let vars',_alp',v' = Id.List.assoc var terms in
1227 match DAst.get v' with
1228 | GVar id' | GRef (GlobRef.VarRef id',None) ->
1229 let {actualvars;staticbinders;renaming} = alp in
1230 let vars = Id.Set.add id' actualvars in
1231 let renaming = if not (Id.equal id id') then (id,id')::renaming else renaming in
1232 {actualvars = Id.Set.union vars' vars; staticbinders; renaming}, sigma
1233 | t ->
1234 (* The term is a non-variable pattern *)
1235 raise No_match
1236 with Not_found ->
1237 let alp = {alp with actualvars = Id.Set.add id alp.actualvars} in
1238 (* The matching against a term allowing to find the instance has not been found yet *)
1239 (* If it will be a different name, we shall unfortunately fail *)
1240 (* TODO: look at the consequences for alp *)
1241 alp, add_env alp sigma var (DAst.make @@ GVar id)
1242
1243 let bind_singleton_bindinglist_as_term_env alp (terms,termlists,binders,binderlists as sigma) var c =
1244 try
1245 (* If already bound to a binder, unify the term and the binder *)
1246 let vars,patl' = Id.List.assoc var binderlists in
1247 let patl'' = unify_terms_binders alp.renaming [c] patl' in
1248 if patl' == patl'' then sigma
1249 else
1250 let sigma = (terms,termlists,binders,Id.List.remove_assoc var binderlists) in
1251 let alp' = {alp with actualvars = Id.Set.union vars alp.actualvars} in
1252 add_bindinglist_env alp' sigma var patl''
1253 with Not_found ->
1254 (* A term-as-binder occurs in the scope of a binder which is already bound *)
1255 anomaly (Pp.str "Unbound term as binder.")
1256
1257 let bind_binding_as_term_env alp (terms,termlists,binders,binderlists as sigma) var c =
1258 let env = Global.env () in
1259 let pat = try cases_pattern_of_glob_constr env Anonymous c with Not_found -> raise No_match in
1260 try
1261 (* If already bound to a binder, unify the term and the binder *)
1262 let vars,patl' = Id.List.assoc var binders in
1263 let patl'' = List.map2 (unify_pat alp.renaming) [pat] patl' in
1264 if patl' == patl'' then sigma
1265 else
1266 let sigma = (terms,termlists,Id.List.remove_assoc var binders,binderlists) in
1267 let alp' = {alp with actualvars = Id.Set.union vars alp.actualvars} in
1268 add_binding_env alp' sigma var patl''
1269 with Not_found -> add_binding_env alp sigma var [pat]
1270
1271 let bind_binding_env alp (terms,termlists,binders,binderlists as sigma) var disjpat =
1272 try
1273 (* If already bound to a binder possibly *)
1274 (* generating an alpha-renaming from unifying the new binder *)
1275 let vars,disjpat' = Id.List.assoc var binders in
1276 (* if, maybe, there is eventually casts in patterns, the common types have *)
1277 (* to exclude the spine of variable from the two locations they occur *)
1278 let alp' = {alp with actualvars = Id.Set.union vars alp.actualvars} in
1279 let alp, disjpat = List.fold_left2_map unify_pat_upto alp disjpat disjpat' in
1280 let sigma = (terms,termlists,Id.List.remove_assoc var binders,binderlists) in
1281 alp, add_binding_env alp' sigma var disjpat
1282 with Not_found ->
1283 (* Note: all patterns of the disjunction are supposed to have the same
1284 variables, thus one is enough *)
1285 let alp = {alp with actualvars = push_pattern_binders alp.actualvars (List.hd disjpat)} in
1286 alp, add_binding_env alp sigma var disjpat
1287
1288 let bind_bindinglist_env alp (terms,termlists,binders,binderlists as sigma) var bl =
1289 let bl = List.rev bl in
1290 try
1291 (* If already bound to a list of binders possibly *)
1292 (* generating an alpha-renaming from unifying the new binders *)
1293 let vars, bl' = Id.List.assoc var binderlists in
1294 (* The shared subterm can be under two different spines of *)
1295 (* variables (themselves bound in the notation), so we take the *)
1296 (* union of both locations *)
1297 let alp' = {alp with actualvars = Id.Set.union vars alp.actualvars} in
1298 let alp, bl = unify_binders_upto alp bl bl' in
1299 let sigma = (terms,termlists,binders,Id.List.remove_assoc var binderlists) in
1300 alp, add_bindinglist_env alp' sigma var bl
1301 with Not_found ->
1302 let alp = {alp with actualvars = push_context_binders alp.actualvars bl} in
1303 alp, add_bindinglist_env alp sigma var bl
1304
1305 let bind_bindinglist_as_termlist_env alp (terms,termlists,binders,binderlists) var cl =
1306 try
1307 (* If already bound to a list of binders, unify the terms and binders *)
1308 let vars,bl' = Id.List.assoc var binderlists in
1309 let bl = unify_terms_binders alp.renaming cl bl' in
1310 let alp = {alp with actualvars = Id.Set.union vars alp.actualvars} in
1311 let sigma = (terms,termlists,binders,Id.List.remove_assoc var binderlists) in
1312 add_bindinglist_env alp sigma var bl
1313 with Not_found ->
1314 anomaly (str "There should be a binder list bindings this list of terms.")
1315
1316 let match_fix_kind fk1 fk2 =
1317 match (fk1,fk2) with
1318 | GCoFix n1, GCoFix n2 -> Int.equal n1 n2
1319 | GFix (nl1,n1), GFix (nl2,n2) ->
1320 let test n1 n2 = match n1, n2 with
1321 | _, None -> true
1322 | Some id1, Some id2 -> Int.equal id1 id2
1323 | _ -> false
1324 in
1325 Int.equal n1 n2 &&
1326 Array.for_all2 test nl1 nl2
1327 | _ -> false
1328
1329 let match_opt f sigma t1 t2 = match (t1,t2) with
1330 | None, None -> sigma
1331 | Some t1, Some t2 -> f sigma t1 t2
1332 | _ -> raise No_match
1333
1334 let match_names metas (alp,sigma) na1 na2 = match (na1,na2) with
1335 | (na1,Name id2) when is_onlybinding_strict_meta id2 metas ->
1336 raise No_match
1337 | (na1,Name id2) when is_onlybinding_meta id2 metas ->
1338 bind_binding_env alp sigma id2 [DAst.make (PatVar na1)]
1339 | (Name id1,Name id2) when is_term_meta id2 metas ->
1340 (* We let the non-binding occurrence define the rhs and hence reason up to *)
1341 (* alpha-conversion for the given occurrence of the name (see #4592)) *)
1342 bind_term_as_binding_env alp sigma id2 id1
1343 | (Anonymous,Name id2) when is_term_meta id2 metas ->
1344 (* We let the non-binding occurrence define the rhs *)
1345 alp, sigma
1346 | (na1,Name id2) ->
1347 {alp with staticbinders = (na1,id2)::alp.staticbinders},sigma
1348 | (Anonymous,Anonymous) -> alp,sigma
1349 | _ -> raise No_match
1350
1351 let rec match_cases_pattern_binders allow_catchall metas (alp,sigma as acc) pat1 pat2 =
1352 match DAst.get pat1, DAst.get pat2 with
1353 | PatVar _, PatVar (Name id2) when is_onlybinding_pattern_like_meta true id2 metas ->
1354 bind_binding_env alp sigma id2 [pat1]
1355 | PatVar id1, PatVar (Name id2) when is_onlybindinglist_meta id2 metas ->
1356 let t1 = DAst.make @@ GHole(GBinderType id1) in
1357 bind_bindinglist_env alp sigma id2 [DAst.make @@ GLocalAssum (id1,None,Explicit,t1)]
1358 | _, PatVar (Name id2) when is_onlybinding_pattern_like_meta false id2 metas ->
1359 bind_binding_env alp sigma id2 [pat1]
1360 | _, PatVar (Name id2) when is_onlybindinglist_meta id2 metas ->
1361 (* dummy data; should not be used anyway *)
1362 let id1 = Namegen.next_ident_away (Id.of_string "x") Id.Set.empty in
1363 let t1 = DAst.make @@ GHole(GBinderType (Name id1)) in
1364 let ids1 = [] in
1365 bind_bindinglist_env alp sigma id2 [DAst.make @@ GLocalPattern (([pat1],ids1),id1,Explicit,t1)]
1366 | PatVar na1, PatVar na2 -> match_names metas acc na1 na2
1367 | _, PatVar Anonymous when allow_catchall -> acc
1368 | PatCstr (c1,patl1,na1), PatCstr (c2,patl2,na2)
1369 when Construct.CanOrd.equal c1 c2 && Int.equal (List.length patl1) (List.length patl2) ->
1370 List.fold_left2 (match_cases_pattern_binders false metas)
1371 (match_names metas acc na1 na2) patl1 patl2
1372 | _ -> raise No_match
1373
1374 let remove_sigma x (terms,termlists,binders,binderlists) =
1375 (Id.List.remove_assoc x terms,termlists,binders,binderlists)
1376
1377 let remove_bindinglist_sigma x (terms,termlists,binders,binderlists) =
1378 (terms,termlists,binders,Id.List.remove_assoc x binderlists)
1379
1380 let add_ldots_var metas = (ldots_var,NtnTypeConstr)::metas
1381
1382 let add_meta_bindinglist x metas = (x,NtnTypeBinderList (*arbitrary:*) NtnBinderParsedAsBinder)::metas
1383
1384 (* This tells if letins in the middle of binders should be included in
1385 the sequence of binders *)
1386 let glue_inner_letin_with_decls = true
1387
1388 (* This tells if trailing letins (with no further proper binders)
1389 should be included in sequence of binders *)
1390 let glue_trailing_letin_with_decls = false
1391
1392 exception OnlyTrailingLetIns
1393
1394 let match_binderlist match_iter_fun match_termin_fun alp metas sigma rest x y iter termin revert =
1395 let rec aux trailing_letins alp sigma bl rest =
1396 try
1397 let metas = add_ldots_var (add_meta_bindinglist y metas) in
1398 let (terms,_,_,binderlists as sigma) = match_iter_fun alp metas sigma rest iter in
1399 let _,newstaticbinders,rest = Id.List.assoc ldots_var terms in
1400 let b =
1401 match Id.List.assoc y binderlists with _,[b] -> b | _ ->assert false
1402 in
1403 let sigma = remove_bindinglist_sigma y (remove_sigma ldots_var sigma) in
1404 (* In case y is bound not only to a binder but also to a term *)
1405 let sigma = remove_sigma y sigma in
1406 let alp' = {alp with staticbinders = newstaticbinders} in
1407 aux false alp' sigma (b::bl) rest
1408 with No_match ->
1409 match DAst.get rest with
1410 | GLetIn (na,r,c,t,rest') when glue_inner_letin_with_decls ->
1411 let b = DAst.make ?loc:rest.CAst.loc @@ GLocalDef (na,r,c,t) in
1412 (* collect let-in *)
1413 (try aux true alp sigma (b::bl) rest'
1414 with OnlyTrailingLetIns
1415 when not (trailing_letins && not glue_trailing_letin_with_decls) ->
1416 (* renounce to take into account trailing let-ins *)
1417 if not (List.is_empty bl) then alp, bl, rest, sigma else raise No_match)
1418 | _ ->
1419 if trailing_letins && not glue_trailing_letin_with_decls then
1420 (* Backtrack to when we tried to glue letins *)
1421 raise OnlyTrailingLetIns;
1422 if not (List.is_empty bl) then alp, bl, rest, sigma else raise No_match in
1423 let alp,bl,rest,sigma = aux false alp sigma [] rest in
1424 let bl = if revert then List.rev bl else bl in
1425 let alp,sigma = bind_bindinglist_env alp sigma x bl in
1426 match_termin_fun alp metas sigma rest termin
1427
1428 let add_meta_term x metas = (x,NtnTypeConstr)::metas
1429
1430 type match_flags = {
1431 print_parentheses : bool;
1432 factorize_eqns : PrintingFlags.Extern.FactorizeEqns.t;
1433 }
1434
1435 let match_termlist flags match_fun alp metas sigma rest x y iter termin revert =
1436 let rec aux alp sigma acc rest =
1437 try
1438 let metas = add_ldots_var (add_meta_term y metas) in
1439 let (terms,_,_,_ as sigma) = match_fun alp metas sigma rest iter in
1440 let _,newstaticbinders,rest = Id.List.assoc ldots_var terms in
1441 let vars,_,t = Id.List.assoc y terms in
1442 let sigma = remove_sigma y (remove_sigma ldots_var sigma) in
1443 if flags.print_parentheses && not (List.is_empty acc) then raise No_match;
1444 (* The union is overkill at the current time because each term matches *)
1445 (* at worst the same binder metavariable of the same pattern *)
1446 let alp' = {actualvars = Id.Set.union vars alp.actualvars; staticbinders = newstaticbinders; renaming = alp.renaming} in
1447 aux alp' sigma (t::acc) rest
1448 with No_match when not (List.is_empty acc) ->
1449 alp, acc, match_fun alp metas sigma rest termin in
1450 let alp,l,(terms,termlists,binders,binderlists as sigma) = aux alp sigma [] rest in
1451 let l = if revert then l else List.rev l in
1452 if is_bindinglist_meta x metas then
1453 (* This is a recursive pattern for both bindings and terms; it is *)
1454 (* registered for binders *)
1455 bind_bindinglist_as_termlist_env alp sigma x l
1456 else
1457 bind_termlist_env alp sigma x l
1458
1459 let does_not_come_from_already_eta_expanded_var glob =
1460 (* This is hack to avoid looping on a rule with rhs of the form *)
1461 (* "?f (fun ?x => ?g)" since otherwise, matching "F H" expands in *)
1462 (* "F (fun x => H x)" and "H x" is recursively matched against the same *)
1463 (* rule, giving "H (fun x' => x x')" and so on. *)
1464 (* Ideally, we would need the type of the expression to know which of *)
1465 (* the arguments applied to it can be eta-expanded without looping. *)
1466 (* The following test is then an approximation of what can be done *)
1467 (* optimally (whether other looping situations can occur remains to be *)
1468 (* checked). *)
1469 match DAst.get glob with GVar _ -> false | _ -> true
1470
1471 let eta_well_typed pat =
1472 (* A criterion for well-typedness of the eta-expansion
1473 is that the head of the pattern is rigid (see #15221) *)
1474 match pat with NVar _ -> false | _ -> true
1475
1476 let is_var_term = function
1477 (* The kind of expressions allowed to be both a term and a binding variable *)
1478 | GVar _ -> true
1479 | GRef (GlobRef.VarRef _,None) -> true
1480 | _ -> false
1481
1482 let rec match_ inner u alp metas sigma a1 a2 =
1483 let open CAst in
1484 let loc = a1.loc in
1485 match DAst.get a1, a2 with
1486 (* Matching notation variable *)
1487 | r1, NVar id2 when is_term_meta id2 metas -> bind_term_env alp sigma id2 a1
1488 | r1, NVar id2 when is_var_term r1 && is_onlybinding_pattern_like_meta true id2 metas -> bind_binding_as_term_env alp sigma id2 a1
1489 | r1, NVar id2 when is_onlybinding_pattern_like_meta false id2 metas -> bind_binding_as_term_env alp sigma id2 a1
1490 | r1, NVar id2 when is_var_term r1 && is_onlybinding_strict_meta id2 metas -> raise No_match
1491 | r1, NVar id2 when is_var_term r1 && is_onlybinding_meta id2 metas -> bind_binding_as_term_env alp sigma id2 a1
1492 | r1, NVar id2 when is_bindinglist_meta id2 metas -> bind_singleton_bindinglist_as_term_env alp sigma id2 a1
1493
1494 (* Matching recursive notations for terms *)
1495 | r1, NList (x,y,iter,termin,revert) ->
1496 match_termlist u (match_hd u) alp metas sigma a1 x y iter termin revert
1497
1498 (* Matching recursive notations for binders: general case *)
1499 | _r, NBinderList (x,y,iter,termin,revert) ->
1500 (* When revert=true, binders are considered "inner" and thus not cumulative, as e.g. in
1501 Notation "!! x .. y # A #" := (.. (A,(forall x, True)) ..,(forall y, True)) (at level 200, x binder).
1502 This has an impact on the heuristic of preferring using "A -> B" where
1503 a recursive Prod binder on a anonymous would otherwise also be possible *)
1504 match_binderlist (match_ revert u) (match_hd u) alp metas sigma a1 x y iter termin revert
1505
1506 (* Matching a static variable (not bound in the notation) *)
1507 | GVar id1, NVar id2 when alpha_var id1 id2 alp.staticbinders -> sigma
1508
1509 (* Matching compositionally *)
1510 | GRef (r1,u1), NRef (r2,u2) when (GlobRef.CanOrd.equal r1 r2) && compare_glob_universe_instances_le u1 u2 -> sigma
1511 | GApp (f1,l1), NApp (f2,l2) ->
1512 let n1 = List.length l1 and n2 = List.length l2 in
1513 let f1,l1,f2,l2 =
1514 if n1 < n2 then
1515 let l21,l22 = List.chop (n2-n1) l2 in f1,l1, NApp (f2,l21), l22
1516 else if n1 > n2 then
1517 let l11,l12 = List.chop (n1-n2) l1 in DAst.make ?loc @@ GApp (f1,l11),l12, f2,l2
1518 else f1,l1, f2, l2 in
1519 let may_use_eta = does_not_come_from_already_eta_expanded_var f1 && eta_well_typed f2 in
1520 List.fold_left2 (match_ may_use_eta u alp metas)
1521 (match_hd u alp metas sigma f1 f2) l1 l2
1522 | GProj ((cst1,u1),l1,a1), NProj ((cst2,u2),l2,a2) when GlobRef.CanOrd.equal (GlobRef.ConstRef cst1) (GlobRef.ConstRef cst2) && compare_glob_universe_instances_le u1 u2 ->
1523 match_in u alp metas (List.fold_left2 (match_in u alp metas) sigma l1 l2) a1 a2
1524 | GApp (f1,l1), NProj ((cst2,u2),l2,a2) ->
1525 (match DAst.get f1 with
1526 | GRef (r1,u1) when GlobRef.CanOrd.equal r1 (GlobRef.ConstRef cst2) && compare_glob_universe_instances_le u1 u2 &&
1527 List.length l1 = List.length l2 + 1 ->
1528 List.fold_left2 (match_in u alp metas) sigma l1 (l2@[a2])
1529 | _ -> raise No_match)
1530 | GLambda (na1,_,bk1,t1,b1), NLambda (na2,t2,b2) ->
1531 match_extended_binders false u alp metas na1 na2 bk1 t1 (match_in_type u alp metas sigma t1 t2) b1 b2
1532 | GProd (na1,_,bk1,t1,b1), NProd (na2,t2,b2) ->
1533 match_extended_binders (not inner) u alp metas na1 na2 bk1 t1 (match_in_type u alp metas sigma t1 t2) b1 b2
1534 | GLetIn (na1,_,b1,t1,c1), NLetIn (na2,b2,None,c2)
1535 | GLetIn (na1,_,b1,(None as t1),c1), NLetIn (na2,b2,_,c2) ->
1536 let t = match t1 with Some t -> t | None -> DAst.make @@ GHole(GBinderType na1) in
1537 match_extended_binders false u alp metas na1 na2 Explicit t (match_in u alp metas sigma b1 b2) c1 c2
1538 | GLetIn (na1,_,b1,Some t1,c1), NLetIn (na2,b2,Some t2,c2) ->
1539 match_extended_binders false u alp metas na1 na2 Explicit t1
1540 (match_in u alp metas (match_in u alp metas sigma b1 b2) t1 t2) c1 c2
1541 | GCases (sty1,rtno1,tml1,eqnl1), NCases (sty2,rtno2,tml2,eqnl2)
1542 when sty1 == sty2 && Int.equal (List.length tml1) (List.length tml2) ->
1543 let rtno1' = abstract_return_type_context_glob_constr tml1 rtno1 in
1544 let rtno2' = abstract_return_type_context_notation_constr tml2 rtno2 in
1545 let sigma =
1546 try Option.fold_left2 (match_in u alp metas) sigma rtno1' rtno2'
1547 with Option.Heterogeneous -> raise No_match
1548 in
1549 let sigma = List.fold_left2
1550 (fun s (tm1,_) (tm2,_) ->
1551 match_in u alp metas s tm1 tm2) sigma tml1 tml2 in
1552 (* Try two different strategies for matching clauses *)
1553 (try
1554 List.fold_left2_set No_match (match_equations u alp metas) sigma eqnl1 eqnl2
1555 with
1556 No_match ->
1557 List.fold_left2_set No_match (match_disjunctive_equations u alp metas) sigma
1558 (Detyping.factorize_eqns ~flags:u.factorize_eqns eqnl1)
1559 (List.map (fun (patl,rhs) -> ([patl],rhs)) eqnl2))
1560 | GLetTuple (nal1,(na1,to1),b1,c1), NLetTuple (nal2,(na2,to2),b2,c2)
1561 when Int.equal (List.length nal1) (List.length nal2) ->
1562 let sigma = match_opt (match_binders u alp metas na1 na2) sigma to1 to2 in
1563 let sigma = match_in u alp metas sigma b1 b2 in
1564 let (alp,sigma) =
1565 List.fold_left2 (match_names metas) (alp,sigma) nal1 nal2 in
1566 match_in u alp metas sigma c1 c2
1567 | GIf (a1,(na1,to1),b1,c1), NIf (a2,(na2,to2),b2,c2) ->
1568 let sigma = match_opt (match_binders u alp metas na1 na2) sigma to1 to2 in
1569 List.fold_left2 (match_in u alp metas) sigma [a1;b1;c1] [a2;b2;c2]
1570 | GRec (fk1,idl1,dll1,tl1,bl1), NRec (fk2,idl2,dll2,tl2,bl2)
1571 when match_fix_kind fk1 fk2 && Int.equal (Array.length idl1) (Array.length idl2) &&
1572 Array.for_all2 (fun l1 l2 -> Int.equal (List.length l1) (List.length l2)) dll1 dll2
1573 ->
1574 let alp,sigma = Array.fold_left2
1575 (List.fold_left2 (fun (alp,sigma) (na1,_,_,oc1,b1) (na2,oc2,b2) ->
1576 let sigma =
1577 match_in u alp metas
1578 (match_opt (match_in u alp metas) sigma oc1 oc2) b1 b2
1579 in match_names metas (alp,sigma) na1 na2)) (alp,sigma) dll1 dll2 in
1580 let sigma = Array.fold_left2 (match_in u alp metas) sigma tl1 tl2 in
1581 let alp,sigma = Array.fold_right2 (fun id1 id2 alsig ->
1582 match_names metas alsig (Name id1) (Name id2)) idl1 idl2 (alp,sigma) in
1583 Array.fold_left2 (match_in u alp metas) sigma bl1 bl2
1584 | GCast(c1, k1, t1), NCast(c2, k2, t2) ->
1585 let sigma = match_in u alp metas sigma c1 c2 in
1586 if not (Option.equal cast_kind_eq k1 k2) then raise No_match;
1587 match_in u alp metas sigma t1 t2
1588
1589 (* [NSort (None, UAnonymous _)] from "Type" only matches anonymous glob sorts.
1590 This means it never matches the result of detyping a sort when Printing Universes is on.
1591 Is that really what we want?
1592 (Behaviour deliberately introduced in a38fbefca61f3392efe0ba98adfbae138022cce4 AFAICT) *)
1593 | GSort s1, NSort s2 when glob_sort_eq s1 s2 -> sigma
1594
1595 | GInt i1, NInt i2 when Uint63.equal i1 i2 -> sigma
1596 | GFloat f1, NFloat f2 when Float64.equal f1 f2 -> sigma
1597 | GString s1, NString s2 when Pstring.equal s1 s2 -> sigma
1598 | GPatVar _, NHole _ -> (*Don't hide Metas, they bind in ltac*) raise No_match
1599 | a, NHole _ -> sigma
1600
1601 (* On the fly eta-expansion so as to use notations of the form
1602 "exists x, P x" for "ex P"; ensure at least one constructor is
1603 consumed to avoid looping; expects type not given because don't know
1604 otherwise how to ensure it corresponds to a well-typed eta-expansion;
1605 we make an exception for types which are metavariables: this is useful e.g.
1606 to print "{x:_ & P x}" knowing that notation "{x & P x}" is not defined. *)
1607 | _b1, NLambda (Name id as na,(None | Some (NVar _) as t2),b2) when inner ->
1608 let avoid =
1609 Id.Set.union (free_glob_vars a1) (* as in Namegen: *) (glob_visible_short_qualid a1) in
1610 let id' = Namegen.next_ident_away id avoid in
1611 let t1 = DAst.make @@ GHole (GBinderType (Name id')) in
1612 let sigma = match t2 with
1613 | None -> sigma
1614 | Some (NVar id2) -> bind_term_env alp sigma id2 t1
1615 | _ -> assert false in
1616 let (alp,sigma) =
1617 if is_bindinglist_meta id metas then
1618 bind_bindinglist_env alp sigma id [DAst.make @@ GLocalAssum (Name id',None,Explicit,t1)]
1619 else
1620 match_names metas (alp,sigma) (Name id') na in
1621 match_in u alp metas sigma (mkGApp a1 [DAst.make @@ GVar id']) b2
1622
1623 | GArray(_u,t,def,ty), NArray(nt,ndef,nty) ->
1624 if Int.equal (Array.length t) (Array.length nt) then
1625 let sigma = match_in u alp metas sigma def ndef in
1626 let sigma = match_in u alp metas sigma ty nty in
1627 Array.fold_left2 (match_in u alp metas) sigma t nt
1628 else raise No_match
1629
1630 | (GRef _ | GVar _ | GEvar _ | GPatVar _ | GApp _ | GProj _ | GLambda _ | GProd _
1631 | GLetIn _ | GCases _ | GLetTuple _ | GIf _ | GRec _ | GSort _ | GHole _ | GGenarg _
1632 | GCast _ | GInt _ | GFloat _ | GString _ | GArray _), _ -> raise No_match
1633
1634 and match_in_type u alp metas sigma t = function
1635 | None -> sigma
1636 | Some t' -> match_in u alp metas sigma t t'
1637
1638 and match_in u = match_ true u
1639
1640 and match_hd u = match_ false u
1641
1642 and match_binders u alp metas na1 na2 sigma b1 b2 =
1643 (* Match binders which cannot be substituted by a pattern *)
1644 let (alp,sigma) = match_names metas (alp,sigma) na1 na2 in
1645 match_in u alp metas sigma b1 b2
1646
1647 and match_extended_binders ?loc isprod u alp metas na1 na2 bk t sigma b1 b2 =
1648 (* Match binders which can be substituted by a pattern *)
1649 let store, get = set_temporary_memory () in
1650 match na1, DAst.get b1, na2 with
1651 (* Matching individual binders as part of a recursive pattern *)
1652 | Name p, GCases (Constr.LetPatternStyle,None,[(e,_)],(_::_ as eqns)), Name id
1653 when is_gvar p e && is_bindinglist_meta id metas
1654 && List.length (store (Detyping.factorize_eqns ~flags:u.factorize_eqns eqns)) = 1 ->
1655 (match get () with
1656 | [{CAst.v=(ids,disj_of_patl,b1)}] ->
1657 let disjpat = List.map (function [pat] -> pat | _ -> assert false) disj_of_patl in
1658 let disjpat = if occur_glob_constr p b1 then List.map (set_pat_alias p) disjpat else disjpat in
1659 let alp,sigma = bind_bindinglist_env alp sigma id [DAst.make ?loc @@ GLocalPattern ((disjpat,ids),p,bk,t)] in
1660 match_in u alp metas sigma b1 b2
1661 | _ -> assert false)
1662 | Name p, GCases (LetPatternStyle,None,[(e,_)],(_::_ as eqns)), Name id
1663 when is_gvar p e && is_onlybinding_pattern_like_meta false id metas
1664 && List.length (store (Detyping.factorize_eqns ~flags:u.factorize_eqns eqns)) = 1 ->
1665 (match get () with
1666 | [{CAst.v=(ids,disj_of_patl,b1)}] ->
1667 let disjpat = List.map (function [pat] -> pat | _ -> assert false) disj_of_patl in
1668 let disjpat = if occur_glob_constr p b1 then List.map (set_pat_alias p) disjpat else disjpat in
1669 let alp,sigma = bind_binding_env alp sigma id disjpat in
1670 match_in u alp metas sigma b1 b2
1671 | _ -> assert false)
1672 | _, _, Name id when is_bindinglist_meta id metas ->
1673 if (isprod && na1 = Anonymous) then raise No_match (* prefer using "A -> B" for anonymous forall *);
1674 let alp,sigma = bind_bindinglist_env alp sigma id [DAst.make ?loc @@ GLocalAssum (na1,None,bk,t)] in
1675 match_in u alp metas sigma b1 b2
1676 | _, _, _ ->
1677 let (alp,sigma) = match_names metas (alp,sigma) na1 na2 in
1678 match_in u alp metas sigma b1 b2
1679
1680 and match_equations u alp metas sigma {CAst.v=(ids,patl1,rhs1)} (patl2,rhs2) rest1 rest2 =
1681 (* patl1 and patl2 have the same length because they respectively
1682 correspond to some tml1 and tml2 that have the same length *)
1683 let allow_catchall = (rest2 = [] && ids = []) in
1684 let (alp,sigma) =
1685 List.fold_left2 (match_cases_pattern_binders allow_catchall metas)
1686 (alp,sigma) patl1 patl2 in
1687 match_in u alp metas sigma rhs1 rhs2
1688
1689 and match_disjunctive_equations u alp metas sigma {CAst.v=(ids,disjpatl1,rhs1)} (disjpatl2,rhs2) _ _ =
1690 (* patl1 and patl2 have the same length because they respectively
1691 correspond to some tml1 and tml2 that have the same length *)
1692 let (alp,sigma) =
1693 List.fold_left2_set No_match
1694 (fun alp_sigma patl1 patl2 _ _ ->
1695 List.fold_left2 (match_cases_pattern_binders false metas) alp_sigma patl1 patl2)
1696 (alp,sigma) disjpatl1 disjpatl2 in
1697 match_in u alp metas sigma rhs1 rhs2
1698
1699 (* Turning substitution based on binding/term distinction into a
1700 substitution based on entry production: indeed some binders may
1701 have to be seen as terms from the parsing/printing point of view *)
1702 let group_by_type ids (terms,termlists,binders,binderlists) =
1703 List.fold_right (fun (x,(scl,_,typ)) (terms',termlists',binders',binderlists') ->
1704 match typ with
1705 | NtnTypeConstr ->
1706 (* term -> term *)
1707 let vars,_alp',term = try Id.List.assoc x terms with Not_found -> raise No_match in
1708 (((vars,term),scl)::terms',termlists',binders',binderlists')
1709 | NtnTypeBinder (NtnBinderParsedAsConstr _) ->
1710 (* binder -> term *)
1711 (match Id.List.assoc x binders with
1712 | vars,[pat] ->
1713 let v = glob_constr_of_cases_pattern (Global.env()) pat in
1714 (((vars,v),scl)::terms',termlists',binders',binderlists')
1715 | _ -> raise No_match)
1716 | NtnTypeBinder (NtnBinderParsedAsBinder | NtnBinderParsedAsSomeBinderKind _) ->
1717 (* term list -> term list *)
1718 (terms',termlists',(Id.List.assoc x binders,scl)::binders',binderlists')
1719 | NtnTypeConstrList ->
1720 (* term list -> term list *)
1721 (terms',(Id.List.assoc x termlists,scl)::termlists',binders',binderlists')
1722 | NtnTypeBinderList (NtnBinderParsedAsConstr _) ->
1723 (* binder list -> term list *)
1724 let vars,patl = try Id.List.assoc x binderlists with Not_found -> raise No_match in
1725 let v = List.map (fun pat -> match DAst.get pat with
1726 | GLocalPattern ((disjpat,_),_,_,_) ->
1727 List.map (glob_constr_of_cases_pattern (Global.env())) disjpat
1728 | GLocalAssum (Anonymous,_,bk,t) ->
1729 let hole = DAst.make (GHole (GBinderType Anonymous)) in
1730 [DAst.make (GCast (hole, Some DEFAULTcast, t))]
1731 | GLocalAssum (Name id,_,bk,t) ->
1732 [DAst.make (GCast (DAst.make (GVar id), Some DEFAULTcast, t))]
1733 | GLocalDef _ -> raise No_match) patl in
1734 (terms',((vars,List.flatten v),scl)::termlists',binders',binderlists')
1735 | NtnTypeBinderList (NtnBinderParsedAsBinder | NtnBinderParsedAsSomeBinderKind _) ->
1736 (* binder list -> binder list *)
1737 let bl = try Id.List.assoc x binderlists with Not_found -> raise No_match in
1738 (terms',termlists',binders',(bl,scl)::binderlists'))
1739 ids ([],[],[],[])
1740
1741 let match_notation_constr ~print_parentheses ~factorize_eqns c ~vars (metas,pat) =
1742 let metatyps = List.map (fun (id,(_,_,typ)) -> (id,typ)) metas in
1743 let flags = { print_parentheses; factorize_eqns } in
1744 let subst = match_ false flags {actualvars=vars;staticbinders=[];renaming=[]} metatyps ([],[],[],[]) c pat in
1745 group_by_type metas subst
1746
1747 (* Matching cases pattern *)
1748
1749 let bind_env_cases_pattern (terms,x,termlists,y as sigma) var v =
1750 try
1751 let vvar = Id.List.assoc var terms in
1752 if cases_pattern_eq v vvar then sigma else raise No_match
1753 with Not_found ->
1754 (* TODO: handle the case of multiple occs in different scopes *)
1755 (var,v)::terms,x,termlists,y
1756
1757 let match_cases_pattern_list match_fun metas sigma rest x y iter termin revert =
1758 let rec aux sigma acc rest =
1759 try
1760 let metas = add_ldots_var (add_meta_term y metas) in
1761 let (terms,_,_,_ as sigma) = match_fun metas sigma rest iter in
1762 let rest = Id.List.assoc ldots_var terms in
1763 let t = Id.List.assoc y terms in
1764 let sigma = remove_sigma y (remove_sigma ldots_var sigma) in
1765 aux sigma (t::acc) rest
1766 with No_match when not (List.is_empty acc) ->
1767 acc, match_fun metas sigma rest termin in
1768 let l,(terms,termlists,binders,binderlists as sigma) = aux sigma [] rest in
1769 (terms,(x,if revert then l else List.rev l)::termlists,binders,binderlists)
1770
1771 let rec match_cases_pattern metas (terms,termlists,(),() as sigma) a1 a2 =
1772 match DAst.get a1, a2 with
1773 | r1, NVar id2 when Id.List.mem_assoc id2 metas -> (bind_env_cases_pattern sigma id2 a1),(false,0,[])
1774 | PatVar Anonymous, NHole _ -> sigma,(false,0,[])
1775 | PatCstr ((ind,_ as r1),largs,Anonymous), NRef (GlobRef.ConstructRef r2,None) when Construct.CanOrd.equal r1 r2 ->
1776 let l = try add_patterns_for_params_remove_local_defs (Global.env ()) r1 largs with Not_found -> raise No_match in
1777 sigma,(false,0,l)
1778 | PatCstr ((ind,_ as r1),args1,Anonymous), NApp (NRef (GlobRef.ConstructRef r2,None),l2)
1779 when Construct.CanOrd.equal r1 r2 ->
1780 let l1 = try add_patterns_for_params_remove_local_defs (Global.env()) r1 args1 with Not_found -> raise No_match in
1781 let le2 = List.length l2 in
1782 if le2 > List.length l1
1783 then
1784 raise No_match
1785 else
1786 let l1',more_args = Util.List.chop le2 l1 in
1787 (* Convention: notations to @f don't keep implicit arguments *)
1788 let no_implicit = le2 = 0 in
1789 (List.fold_left2 (match_cases_pattern_no_more_args metas) sigma l1' l2),(no_implicit,le2,more_args)
1790 | r1, NList (x,y,iter,termin,revert) ->
1791 (match_cases_pattern_list (match_cases_pattern_no_more_args)
1792 metas (terms,termlists,(),()) a1 x y iter termin revert),(false,0,[])
1793 | _ -> raise No_match
1794
1795 and match_cases_pattern_no_more_args metas sigma a1 a2 =
1796 match match_cases_pattern metas sigma a1 a2 with
1797 | out,(_,_,[]) -> out
1798 | _ -> raise No_match
1799
1800 let match_ind_pattern metas sigma ind pats a2 =
1801 match a2 with
1802 | NRef (GlobRef.IndRef r2,None) when Ind.CanOrd.equal ind r2 ->
1803 sigma,(false,0,pats)
1804 | NApp (NRef (GlobRef.IndRef r2,None),l2)
1805 when Ind.CanOrd.equal ind r2 ->
1806 let le2 = List.length l2 in
1807 if Int.equal le2 0 (* Special case of a notation for a @Cstr *) || le2 > List.length pats
1808 then
1809 raise No_match
1810 else
1811 let l1',more_args = Util.List.chop le2 pats in
1812 let no_implicit = le2 = 0 in
1813 (List.fold_left2 (match_cases_pattern_no_more_args metas) sigma l1' l2),(no_implicit,le2,more_args)
1814 |_ -> raise No_match
1815
1816 let reorder_canonically_substitution terms termlists metas =
1817 List.fold_right (fun (x,(scl,_,typ)) (terms',termlists',binders') ->
1818 match typ with
1819 | NtnTypeConstr | NtnTypeBinder (NtnBinderParsedAsConstr _) -> ((Id.List.assoc x terms, scl)::terms',termlists',binders')
1820 | NtnTypeConstrList -> (terms',(Id.List.assoc x termlists,scl)::termlists',binders')
1821 | NtnTypeBinder (NtnBinderParsedAsBinder | NtnBinderParsedAsSomeBinderKind _) ->
1822 (terms',termlists',(Id.List.assoc x terms, scl)::binders')
1823 | NtnTypeBinderList _ -> anomaly (str "Unexpected binder in pattern notation."))
1824 metas ([],[],[])
1825
1826 let match_notation_constr_cases_pattern c (metas,pat) =
1827 let metatyps = List.map (fun (id,(_,_,typ)) -> (id,typ)) metas in
1828 let (terms,termlists,(),()),more_args = match_cases_pattern metatyps ([],[],(),()) c pat in
1829 reorder_canonically_substitution terms termlists metas, more_args
1830
1831 let match_notation_constr_ind_pattern ind args (metas,pat) =
1832 let metatyps = List.map (fun (id,(_,_,typ)) -> (id,typ)) metas in
1833 let (terms,termlists,(),()),more_args = match_ind_pattern metatyps ([],[],(),()) ind args pat in
1834 reorder_canonically_substitution terms termlists metas, more_args