Debian Codegraph @

pretyping/patternops.ml

raw symbols SCIP
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * Copyright INRIA, CNRS and contributors *)
4 (* <O___,, * (see version control and CREDITS file for authors & dates) *)
5 (* \VV/ **************************************************************)
6 (* // * This file is distributed under the terms of the *)
7 (* * GNU Lesser General Public License Version 2.1 *)
8 (* * (see LICENSE file for the text of the license) *)
9 (************************************************************************)
10
11 open CErrors
12 open Util
13 open Names
14 open Globnames
15 open Nameops
16 open Constr
17 open Context
18 open Glob_term
19 open Pp
20 open Mod_subst
21 open Pattern
22 open Environ
23
24 let case_info_pattern_eq env i1 i2 =
25 i1.cip_style == i2.cip_style &&
26 Option.equal (fun i1 i2 -> QInd.equal env i1 i2) i1.cip_ind i2.cip_ind &&
27 i1.cip_extensible == i2.cip_extensible
28
29 let rec constr_pattern_eq env (p1:constr_pattern) p2 = match p1, p2 with
30 | PRef r1, PRef r2 -> QGlobRef.equal env r1 r2
31 | PVar v1, PVar v2 -> Id.equal v1 v2
32 | PEvar (ev1, ctx1), PEvar (ev2, ctx2) ->
33 Evar.equal ev1 ev2 && List.equal (fun c1 c2 -> constr_pattern_eq env c1 c2) ctx1 ctx2
34 | PRel i1, PRel i2 ->
35 Int.equal i1 i2
36 | PApp (t1, arg1), PApp (t2, arg2) ->
37 constr_pattern_eq env t1 t2 && Array.equal (fun c1 c2 -> constr_pattern_eq env c1 c2) arg1 arg2
38 | PSoApp (id1, arg1), PSoApp (id2, arg2) ->
39 Id.equal id1 id2 && List.equal (fun c1 c2 -> constr_pattern_eq env c1 c2) arg1 arg2
40 | PLambda (v1, t1, b1), PLambda (v2, t2, b2) ->
41 Name.equal v1 v2 && constr_pattern_eq env t1 t2 && constr_pattern_eq env b1 b2
42 | PProd (v1, t1, b1), PProd (v2, t2, b2) ->
43 Name.equal v1 v2 && constr_pattern_eq env t1 t2 && constr_pattern_eq env b1 b2
44 | PLetIn (v1, b1, t1, c1), PLetIn (v2, b2, t2, c2) ->
45 Name.equal v1 v2 && constr_pattern_eq env b1 b2 &&
46 Option.equal (fun c1 c2 -> constr_pattern_eq env c1 c2) t1 t2 && constr_pattern_eq env c1 c2
47 | PSort s1, PSort s2 -> UnivGen.QualityOrSet.equal s1 s2
48 | PMeta m1, PMeta m2 -> Option.equal Id.equal m1 m2
49 | PIf (t1, l1, r1), PIf (t2, l2, r2) ->
50 constr_pattern_eq env t1 t2 && constr_pattern_eq env l1 l2 && constr_pattern_eq env r1 r2
51 | PCase (info1, p1, r1, l1), PCase (info2, p2, r2, l2) ->
52 case_info_pattern_eq env info1 info2 &&
53 Option.equal (fun (nas1, p1) (nas2, p2) -> Array.equal Name.equal nas1 nas2 && constr_pattern_eq env p1 p2) p1 p2 &&
54 constr_pattern_eq env r1 r2 &&
55 List.equal (fun p1 p2 -> pattern_eq env p1 p2) l1 l2
56 | PFix ((ln1,i1),f1), PFix ((ln2,i2),f2) ->
57 Array.equal Int.equal ln1 ln2 && Int.equal i1 i2 && rec_declaration_eq env f1 f2
58 | PCoFix (i1,f1), PCoFix (i2,f2) ->
59 Int.equal i1 i2 && rec_declaration_eq env f1 f2
60 | PProj (p1, t1), PProj (p2, t2) ->
61 QProjection.equal env p1 p2 && constr_pattern_eq env t1 t2
62 | PInt i1, PInt i2 ->
63 Uint63.equal i1 i2
64 | PFloat f1, PFloat f2 ->
65 Float64.equal f1 f2
66 | PString s1, PString s2 ->
67 Pstring.equal s1 s2
68 | PArray (t1, def1, ty1), PArray (t2, def2, ty2) ->
69 Array.equal (fun c1 c2 -> constr_pattern_eq env c1 c2) t1 t2 && constr_pattern_eq env def1 def2
70 && constr_pattern_eq env ty1 ty2
71 | PExtra e, _ -> Util.Empty.abort e
72 | (PRef _ | PVar _ | PEvar _ | PRel _ | PApp _ | PSoApp _
73 | PLambda _ | PProd _ | PLetIn _ | PSort _ | PMeta _
74 | PIf _ | PCase _ | PFix _ | PCoFix _ | PProj _ | PInt _
75 | PFloat _ | PString _ | PArray _), _ -> false
76 (** FIXME: fixpoint and cofixpoint should be relativized to pattern *)
77
78 and pattern_eq env (i1, j1, p1) (i2, j2, p2) =
79 Int.equal i1 i2 && Array.equal Name.equal j1 j2 && constr_pattern_eq env p1 p2
80
81 and rec_declaration_eq env (n1, c1, r1) (n2, c2, r2) =
82 Array.equal Name.equal n1 n2 &&
83 Array.equal (fun c1 c2 -> constr_pattern_eq env c1 c2) c1 c2 &&
84 Array.equal (fun c1 c2 -> constr_pattern_eq env c1 c2) r1 r2
85
86 let rec occurn_pattern : 'a. _ -> 'a constr_pattern_r -> _
87 = fun (type a) n (p:a constr_pattern_r) -> match p with
88 | PRel p -> Int.equal n p
89 | PApp (f,args) ->
90 (occurn_pattern n f) || (Array.exists (occurn_pattern n) args)
91 | PProj (_,arg) -> occurn_pattern n arg
92 | PLambda (na,t,c) -> (occurn_pattern n t) || (occurn_pattern (n+1) c)
93 | PProd (na,t,c) -> (occurn_pattern n t) || (occurn_pattern (n+1) c)
94 | PLetIn (na,b,t,c) ->
95 Option.fold_left (fun b t -> b || occurn_pattern n t) (occurn_pattern n b) t ||
96 (occurn_pattern (n+1) c)
97 | PIf (c,c1,c2) ->
98 (occurn_pattern n c) ||
99 (occurn_pattern n c1) || (occurn_pattern n c2)
100 | PCase(_, p, c, br) ->
101 Option.cata (fun (nas, p) -> occurn_pattern (Array.length nas + n) p) false p ||
102 (occurn_pattern n c) ||
103 (List.exists (fun (_, nas, p) -> occurn_pattern (Array.length nas + n) p) br)
104 | PMeta _ | PSoApp _ -> true
105 | PEvar (_,args) -> List.exists (occurn_pattern n) args
106 | PVar _ | PRef _ | PSort _ | PInt _ | PFloat _ | PString _ -> false
107 | PFix (_,(_,tl,bl)) ->
108 Array.exists (occurn_pattern n) tl || Array.exists (occurn_pattern (n+Array.length tl)) bl
109 | PCoFix (_,(_,tl,bl)) ->
110 Array.exists (occurn_pattern n) tl || Array.exists (occurn_pattern (n+Array.length tl)) bl
111 | PArray (t,def,ty) ->
112 Array.exists (occurn_pattern n) t || occurn_pattern n def || occurn_pattern n ty
113 | PExtra _ -> false (* XXX dubious behaviour *)
114
115 let noccurn_pattern n c = not (occurn_pattern n c)
116
117 exception BoundPattern;;
118
119 let rec head_pattern_bound (t:constr_pattern) =
120 match t with
121 | PProd (_,_,b) -> head_pattern_bound b
122 | PLetIn (_,_,_,b) -> head_pattern_bound b
123 | PApp (c,args) -> head_pattern_bound c
124 | PIf (c,_,_) -> head_pattern_bound c
125 | PCase (_,p,c,br) -> head_pattern_bound c
126 | PRef r -> r
127 | PVar id -> GlobRef.VarRef id
128 | PEvar _ | PRel _ | PMeta _ | PSoApp _ | PSort _ | PFix _ | PProj _
129 -> raise BoundPattern
130 (* Perhaps they were arguments, but we don't beta-reduce *)
131 | PLambda _ -> raise BoundPattern
132 | PCoFix _ | PInt _ | PFloat _ | PString _ | PArray _ ->
133 anomaly ~label:"head_pattern_bound" (Pp.str "not a type.")
134 | PExtra e -> Util.Empty.abort e
135
136 let mkPRef env gr =
137 PRef (Environ.QGlobRef.canonize env gr)
138
139 let pattern_of_constr ~broken env sigma t =
140 let t = EConstr.Unsafe.to_constr t in
141 let kind = if broken then Constr.kind else fun c -> EConstr.kind_upto sigma c in
142 let rec pattern_of_constr env t =
143 let open Context.Rel.Declaration in
144 match kind t with
145 | Rel n -> PRel n
146 | Meta n -> PMeta (Some (Id.of_string ("META" ^ string_of_int n)))
147 | Var id -> PVar id
148 | Sort s -> PSort (EConstr.ESorts.quality_or_set sigma (EConstr.ESorts.make s))
149 | Cast (c,_,_) -> pattern_of_constr env c
150 | LetIn (na,c,t,b) -> PLetIn (na.binder_name,
151 pattern_of_constr env c,Some (pattern_of_constr env t),
152 pattern_of_constr (push_rel (LocalDef (na,c,t)) env) b)
153 | Prod (na,c,b) -> PProd (na.binder_name,
154 pattern_of_constr env c,
155 pattern_of_constr (push_rel (LocalAssum (na, c)) env) b)
156 | Lambda (na,c,b) -> PLambda (na.binder_name,
157 pattern_of_constr env c,
158 pattern_of_constr (push_rel (LocalAssum (na, c)) env) b)
159 | App (f,a) ->
160 (match
161 match kind f with
162 | Evar (evk,args) ->
163 let EvarInfo evi = Evd.find sigma evk in
164 (match snd (Evd.evar_source evi) with
165 Evar_kinds.MatchingVar (Evar_kinds.SecondOrderPatVar id) -> Some id
166 | _ -> None)
167 | _ -> None
168 with
169 | Some n -> PSoApp (n,Array.to_list (Array.map (pattern_of_constr env) a))
170 | None -> PApp (pattern_of_constr env f,Array.map (pattern_of_constr env) a))
171 | Const (sp,u) -> mkPRef env (GlobRef.ConstRef sp)
172 | Ind (sp,u) -> mkPRef env (GlobRef.IndRef sp)
173 | Construct (sp,u) -> mkPRef env (GlobRef.ConstructRef sp)
174 | Proj (p, _, c) ->
175 pattern_of_constr env (EConstr.Unsafe.to_constr (Retyping.expand_projection env sigma p (EConstr.of_constr c) []))
176 | Evar (evk,ctxt as ev) ->
177 let EvarInfo evi = Evd.find sigma evk in
178 (match snd (Evd.evar_source evi) with
179 | Evar_kinds.MatchingVar (Evar_kinds.FirstOrderPatVar id) ->
180 PMeta (Some id)
181 | Evar_kinds.GoalEvar | Evar_kinds.VarInstance _ ->
182 (* These are the two evar kinds used for existing goals *)
183 (* see Proofview.mark_in_evm *)
184 begin match Evd.existential_opt_value0 sigma ev with
185 | Some v -> pattern_of_constr env v
186 | None ->
187 let ctxt = Evd.expand_existential sigma (EConstr.of_existential ev) in
188 PEvar (evk,List.map (fun c -> pattern_of_constr env (EConstr.Unsafe.to_constr c)) ctxt)
189 end
190 | Evar_kinds.MatchingVar (Evar_kinds.SecondOrderPatVar ido) -> assert false
191 | _ ->
192 PMeta None)
193 | Case (ci, u, pms, p0, iv, a, br0) ->
194 let (ci, (p,_), iv, a, br) = Inductive.expand_case env (ci, u, pms, p0, iv, a, br0) in
195 let pattern_of_ctx c (nas, c0) =
196 let ctx, c = Term.decompose_lambda_n_decls (Array.length nas) c in
197 let env = push_rel_context ctx env in
198 let c = pattern_of_constr env c in
199 (Array.map Context.binder_name nas, c)
200 in
201 let p = pattern_of_ctx p (fst p0) in
202 let cip =
203 { cip_style = ci.ci_pp_info.style;
204 cip_ind = Some ci.ci_ind;
205 cip_extensible = false }
206 in
207 let branch_of_constr i c =
208 let nas, c = pattern_of_ctx c br0.(i) in
209 (i, nas, c)
210 in
211 PCase (cip, Some p, pattern_of_constr env a,
212 Array.to_list (Array.mapi branch_of_constr br))
213 | Fix (lni,(lna,tl,bl)) ->
214 let push env na2 c2 = push_rel (LocalAssum (na2,c2)) env in
215 let env' = Array.fold_left2 push env lna tl in
216 PFix (lni,(Array.map binder_name lna,Array.map (pattern_of_constr env) tl,
217 Array.map (pattern_of_constr env') bl))
218 | CoFix (ln,(lna,tl,bl)) ->
219 let push env na2 c2 = push_rel (LocalAssum (na2,c2)) env in
220 let env' = Array.fold_left2 push env lna tl in
221 PCoFix (ln,(Array.map binder_name lna,Array.map (pattern_of_constr env) tl,
222 Array.map (pattern_of_constr env') bl))
223 | Int i -> PInt i
224 | Float f -> PFloat f
225 | String s -> PString s
226 | Array (_u, t, def, ty) ->
227 PArray (Array.map (pattern_of_constr env) t, pattern_of_constr env def, pattern_of_constr env ty)
228 in
229 pattern_of_constr env t
230
231 let legacy_bad_pattern_of_constr env sigma c : constr_pattern = pattern_of_constr ~broken:true env sigma c
232 let pattern_of_constr env sigma c = pattern_of_constr ~broken:false env sigma c
233
234 (* To process patterns, we need a translation without typing at all. *)
235
236 let map_pattern_with_binders_gen (type a b) g f fgen l : a constr_pattern_r -> b constr_pattern_r = function
237 | PApp (p,pl) -> PApp (f l p, Array.map (f l) pl)
238 | PSoApp (n,pl) -> PSoApp (n, List.map (f l) pl)
239 | PLambda (n,a,b) -> PLambda (n,f l a,f (g n l) b)
240 | PProd (n,a,b) -> PProd (n,f l a,f (g n l) b)
241 | PLetIn (n,a,t,b) -> PLetIn (n,f l a,Option.map (f l) t,f (g n l) b)
242 | PIf (c,b1,b2) -> PIf (f l c,f l b1,f l b2)
243 | PCase (ci,po,p,pl) ->
244 let fold nas l = Array.fold_left (fun l na -> g na l) l nas in
245 let map_branch (i, n, c) = (i, n, f (fold n l) c) in
246 let po = Option.map (fun (nas, po) -> nas, (f (fold nas l) po)) po in
247 PCase (ci,po,f l p, List.map map_branch pl)
248 | PProj (p,pc) -> PProj (p, f l pc)
249 | PFix (lni,(lna,tl,bl)) ->
250 let l' = Array.fold_left (fun l na -> g na l) l lna in
251 PFix (lni,(lna,Array.map (f l) tl,Array.map (f l') bl))
252 | PCoFix (ln,(lna,tl,bl)) ->
253 let l' = Array.fold_left (fun l na -> g na l) l lna in
254 PCoFix (ln,(lna,Array.map (f l) tl,Array.map (f l') bl))
255 | PArray (t,def,ty) -> PArray (Array.map (f l) t, f l def, f l ty)
256 | PEvar (ev,ps) -> PEvar (ev, List.map (f l) ps)
257 | PExtra x -> fgen l x
258 (* Non recursive *)
259 | (PVar _ | PRel _ | PRef _ | PSort _ | PMeta _ | PInt _
260 | PFloat _ | PString _ as x) -> x
261
262 let map_pattern_with_binders (type a) g f l (p:a constr_pattern_r) : a constr_pattern_r =
263 let fgen _ : a -> a constr_pattern_r = function
264 | x -> PExtra x
265 in
266 map_pattern_with_binders_gen g f fgen l p
267
268 let rec liftn_pattern k n = function
269 | PRel i as x -> if i >= n then PRel (i+k) else x
270 | c -> map_pattern_with_binders (fun _ -> succ) (liftn_pattern k) n c
271
272 let lift_pattern k = liftn_pattern k 1
273
274 let rec subst_pattern_gen
275 : 'a. (_ -> 'a -> 'a) -> _ -> _ -> _ -> 'a constr_pattern_r -> 'a constr_pattern_r
276 = fun (type a) gsubst env sigma subst (pat: a constr_pattern_r) ->
277 match pat with
278 | PRef ref ->
279 let ref',t = subst_global subst ref in
280 if ref' == ref then pat else (match t with
281 | None -> PRef ref'
282 | Some t ->
283 pattern_of_constr env sigma (EConstr.of_constr t.UVars.univ_abstracted_value))
284 | PVar _
285 | PEvar _
286 | PRel _
287 | PInt _
288 | PFloat _
289 | PString _ -> pat
290 | PExtra g -> PExtra (gsubst subst g)
291 | PProj (p,c) ->
292 let p' = Projection.map (subst_mind subst) p in
293 let c' = subst_pattern_gen gsubst env sigma subst c in
294 if p' == p && c' == c then pat else
295 PProj(p',c')
296 | PApp (f,args) ->
297 let f' = subst_pattern_gen gsubst env sigma subst f in
298 let args' = Array.Smart.map (subst_pattern_gen gsubst env sigma subst) args in
299 if f' == f && args' == args then pat else
300 PApp (f',args')
301 | PSoApp (i,args) ->
302 let args' = List.Smart.map (subst_pattern_gen gsubst env sigma subst) args in
303 if args' == args then pat else
304 PSoApp (i,args')
305 | PLambda (name,c1,c2) ->
306 let c1' = subst_pattern_gen gsubst env sigma subst c1 in
307 let c2' = subst_pattern_gen gsubst env sigma subst c2 in
308 if c1' == c1 && c2' == c2 then pat else
309 PLambda (name,c1',c2')
310 | PProd (name,c1,c2) ->
311 let c1' = subst_pattern_gen gsubst env sigma subst c1 in
312 let c2' = subst_pattern_gen gsubst env sigma subst c2 in
313 if c1' == c1 && c2' == c2 then pat else
314 PProd (name,c1',c2')
315 | PLetIn (name,c1,t,c2) ->
316 let c1' = subst_pattern_gen gsubst env sigma subst c1 in
317 let t' = Option.Smart.map (subst_pattern_gen gsubst env sigma subst) t in
318 let c2' = subst_pattern_gen gsubst env sigma subst c2 in
319 if c1' == c1 && t' == t && c2' == c2 then pat else
320 PLetIn (name,c1',t',c2')
321 | PSort _
322 | PMeta _ -> pat
323 | PIf (c,c1,c2) ->
324 let c' = subst_pattern_gen gsubst env sigma subst c in
325 let c1' = subst_pattern_gen gsubst env sigma subst c1 in
326 let c2' = subst_pattern_gen gsubst env sigma subst c2 in
327 if c' == c && c1' == c1 && c2' == c2 then pat else
328 PIf (c',c1',c2')
329 | PCase (cip,typ,c,branches) ->
330 let ind = cip.cip_ind in
331 let ind' = Option.Smart.map (subst_ind subst) ind in
332 let cip' = if ind' == ind then cip else { cip with cip_ind = ind' } in
333 let map ((nas, typ) as t) =
334 let typ' = subst_pattern_gen gsubst env sigma subst typ in
335 if typ' == typ then t else (nas, typ')
336 in
337 let typ' = Option.Smart.map map typ in
338 let c' = subst_pattern_gen gsubst env sigma subst c in
339 let subst_branch ((i,n,c) as br) =
340 let c' = subst_pattern_gen gsubst env sigma subst c in
341 if c' == c then br else (i,n,c')
342 in
343 let branches' = List.Smart.map subst_branch branches in
344 if cip' == cip && typ' == typ && c' == c && branches' == branches
345 then pat
346 else PCase(cip', typ', c', branches')
347 | PFix (lni,(lna,tl,bl)) ->
348 let tl' = Array.Smart.map (subst_pattern_gen gsubst env sigma subst) tl in
349 let bl' = Array.Smart.map (subst_pattern_gen gsubst env sigma subst) bl in
350 if bl' == bl && tl' == tl then pat
351 else PFix (lni,(lna,tl',bl'))
352 | PCoFix (ln,(lna,tl,bl)) ->
353 let tl' = Array.Smart.map (subst_pattern_gen gsubst env sigma subst) tl in
354 let bl' = Array.Smart.map (subst_pattern_gen gsubst env sigma subst) bl in
355 if bl' == bl && tl' == tl then pat
356 else PCoFix (ln,(lna,tl',bl'))
357 | PArray (t,def,ty) ->
358 let t' = Array.Smart.map (subst_pattern_gen gsubst env sigma subst) t in
359 let def' = subst_pattern_gen gsubst env sigma subst def in
360 let ty' = subst_pattern_gen gsubst env sigma subst ty in
361 if def' == def && t' == t && ty' == ty then pat
362 else PArray (t',def',ty')
363
364 let subst_pattern env sigma subst p =
365 subst_pattern_gen (fun _ e -> Util.Empty.abort e) env sigma subst p
366
367 let subst_uninstantiated_pattern env sigma subst p =
368 subst_pattern_gen Gensubst.generic_substitute env sigma subst p
369
370 let mkPLetIn na b t c = PLetIn(na,b,t,c)
371 let mkPProd na t u = PProd(na,t,u)
372 let mkPLambda na t b = PLambda(na,t,b)
373
374 let mkPProd_or_LetIn (na,_,bo,t) c =
375 match bo with
376 | None -> mkPProd na t c
377 | Some b -> mkPLetIn na b (Some t) c
378
379 let mkPLambda_or_LetIn (na,_,bo,t) c =
380 match bo with
381 | None -> mkPLambda na t c
382 | Some b -> mkPLetIn na b (Some t) c
383
384 let it_mkPProd_or_LetIn x y = List.fold_left (fun c d -> mkPProd_or_LetIn d c) x y
385 let it_mkPLambda_or_LetIn x y = List.fold_left (fun c d -> mkPLambda_or_LetIn d c) x y
386
387 type 'a pat_interp_fun = Environ.env -> Evd.evar_map -> Ltac_pretype.ltac_var_map
388 -> 'a -> Pattern.constr_pattern
389
390 module InterpPatObj =
391 struct
392 type (_, 'g, _) obj = 'g pat_interp_fun
393 let name = "interp_pat"
394 let default _ = None
395 end
396
397 module InterpPat = Genarg.Register(InterpPatObj)
398
399 let interp_pat = InterpPat.obj
400
401 let register_interp_pat = InterpPat.register0
402
403 let error_instantiate_pattern id l =
404 let is = match l with
405 | [_] -> "is"
406 | _ -> "are"
407 in
408 user_err (str "Cannot substitute the term bound to " ++ Id.print id
409 ++ strbrk " in pattern because the term refers to " ++ pr_enum Id.print l
410 ++ strbrk " which " ++ str is ++ strbrk " not bound in the pattern.")
411
412 let interp_pattern env sigma ist p =
413 let fgen vars = function
414 | Genarg.GenArg (Glbwit tag,g) -> interp_pat tag env sigma ist g
415 in
416 let rec aux vars = function
417 | PVar id as x ->
418 (try
419 let ctx,c = Id.Map.find id ist.Ltac_pretype.ltac_constrs in
420 try
421 let inst =
422 List.map
423 (fun id -> EConstr.mkRel (List.index Name.equal (Name id) vars))
424 ctx
425 in
426 let c = EConstr.Vars.substl inst c in
427 pattern_of_constr env sigma c
428 with Not_found (* List.index failed *) ->
429 let vars =
430 List.map_filter (function Name id -> Some id | _ -> None) vars in
431 error_instantiate_pattern id (List.subtract Id.equal ctx vars)
432 with Not_found (* Map.find failed *) ->
433 x)
434 | p ->
435 map_pattern_with_binders_gen (fun id vars -> id :: vars) (fun vars p -> aux vars p) fgen vars p
436 in
437 aux [] p
438
439 let err ?loc pp = user_err ?loc pp
440
441 let warn_cast_in_pattern =
442 CWarnings.create ~name:"cast-in-pattern" ~category:CWarnings.CoreCategories.automation
443 (fun () -> Pp.strbrk "Cast types are ignored in patterns")
444
445 type meta_accu =
446 | Metas of Id.Set.t ref
447 | InCastType of Loc.t option
448
449 let push_meta metas n = match metas with
450 | Metas metas -> metas := Id.Set.add n !metas
451 | InCastType loc ->
452 CErrors.user_err ?loc
453 Pp.(str "Cannot bind pattern variable in cast type:"
454 ++ spc() ++ str "cast types are ignored in patterns.")
455
456 let in_cast_type loc = function
457 | Metas _ -> InCastType loc
458 | InCastType _ as v ->
459 (* We report the error with the loc of the outermost cast
460 Alternatively we could use the loc of the meta, or the loc of the innermost cast. *)
461 v
462
463 let pat_of_raw env metas vars p =
464
465 let rec pat_of_raw metas vars : _ -> _ constr_pattern_r = DAst.with_loc_val (fun ?loc -> function
466 | GVar id ->
467 (try PRel (List.index Name.equal (Name id) vars)
468 with Not_found -> PVar id)
469 | GPatVar (Evar_kinds.FirstOrderPatVar n) ->
470 push_meta metas n; PMeta (Some n)
471 | GRef (gr,_) ->
472 PRef (Environ.QGlobRef.canonize env gr)
473 (* Hack to avoid rewriting a complete interpretation of patterns *)
474 | GApp (c, cl) ->
475 begin match DAst.get c with
476 | GPatVar (Evar_kinds.SecondOrderPatVar n) ->
477 push_meta metas n; PSoApp (n, List.map (pat_of_raw metas vars) cl)
478 | _ ->
479 PApp (pat_of_raw metas vars c,
480 Array.of_list (List.map (pat_of_raw metas vars) cl))
481 end
482 | GProj ((p,_), cl, c) ->
483 if Structures.PrimitiveProjections.mem p then
484 let p = Option.get @@ Structures.PrimitiveProjections.find_opt p in
485 let p = Projection.make p false in
486 PProj (p, pat_of_raw metas vars c)
487 else
488 PApp (PRef (GlobRef.ConstRef p), Array.map_of_list (pat_of_raw metas vars) (cl @ [c]))
489 | GLambda (na,_,bk,c1,c2) ->
490 Name.iter (fun n -> push_meta metas n) na;
491 PLambda (na, pat_of_raw metas vars c1,
492 pat_of_raw metas (na::vars) c2)
493 | GProd (na,_,bk,c1,c2) ->
494 Name.iter (fun n -> push_meta metas n) na;
495 PProd (na, pat_of_raw metas vars c1,
496 pat_of_raw metas (na::vars) c2)
497 | GLetIn (na,_,c1,t,c2) ->
498 Name.iter (fun n -> push_meta metas n) na;
499 PLetIn (na, pat_of_raw metas vars c1,
500 Option.map (pat_of_raw metas vars) t,
501 pat_of_raw metas (na::vars) c2)
502 | GSort gs ->
503 (try PSort (Glob_ops.glob_sort_quality gs)
504 with Glob_ops.ComplexSort -> user_err ?loc (str "Unexpected universe in pattern."))
505 | GHole _ -> PMeta None
506 | GGenarg (GenArg (Glbwit tag, _) as g) ->
507 let () = if not (InterpPat.mem tag) then
508 let name = Genarg.(ArgT.repr (get_arg_tag tag)) in
509 user_err ?loc (str "This quotation is not supported in patterns (" ++ str name ++ str ").")
510 in
511 PExtra g
512 | GCast (c,_,t) ->
513 let () =
514 (* Checks that there are no pattern variables in the type *)
515 let _ : _ constr_pattern_r = pat_of_raw (in_cast_type t.loc metas) vars t in
516 ()
517 in
518 warn_cast_in_pattern ?loc ();
519 pat_of_raw metas vars c
520 | GIf (c,(_,None),b1,b2) ->
521 PIf (pat_of_raw metas vars c,
522 pat_of_raw metas vars b1,pat_of_raw metas vars b2)
523 | GLetTuple (nal,(_,None),b,c) ->
524 let cip =
525 { cip_style = LetStyle;
526 cip_ind = None;
527 cip_extensible = false }
528 in
529 let tags = Array.of_list nal (* Approximation which can be without let-ins... *) in
530 PCase (cip, None, pat_of_raw metas vars b,
531 [0,tags,pat_of_raw metas (List.rev_append (Array.to_list tags) vars) c])
532 | GCases (sty,p,[c,(na,indnames)],brs) ->
533 let get_ind p = match DAst.get p with
534 | PatCstr((ind,_),_,_) -> Some ind
535 | _ -> None
536 in
537 let get_ind = function
538 | {CAst.v=(_,[p],_)}::_ -> get_ind p
539 | _ -> None
540 in
541 let ind_tags,ind = match indnames with
542 | Some {CAst.v=(ind,nal)} -> Some (List.length nal), Some ind
543 | None -> None, get_ind brs
544 in
545 let ext,brs = pats_of_glob_branches loc metas vars ind brs
546 in
547 let pred = match p,indnames with
548 | Some p, Some {CAst.v=(_,nal)} ->
549 let nvars = na :: List.rev nal @ vars in
550 Some (Array.rev_of_list (na :: List.rev nal), pat_of_raw metas nvars p)
551 | None, _ -> None
552 | Some p, None ->
553 match DAst.get p with
554 | GHole _ -> None
555 | _ ->
556 user_err ?loc (strbrk "Clause \"in\" expected in patterns over \"match\" expressions with an explicit \"return\" clause.")
557 in
558 let info =
559 { cip_style = sty;
560 cip_ind = ind;
561 cip_extensible = ext }
562 in
563 (* Nota : when we have a non-trivial predicate,
564 the inductive type is known. Same when we have at least
565 one non-trivial branch. These facts are used in [Constrextern]. *)
566 PCase (info, pred, pat_of_raw metas vars c, brs)
567
568 | GRec (GFix (ln,n), ids, decls, tl, cl) ->
569 let get_struct_arg = function
570 | Some n -> n
571 | None -> err ?loc (Pp.str "\"struct\" annotation is expected.")
572 (* TODO why can't the annotation be omitted? *)
573 in
574 let ln = Array.map get_struct_arg ln in
575 let ctxtl = Array.map2 (pat_of_glob_in_context metas vars) decls tl in
576 let tl = Array.map (fun (ctx,tl) -> it_mkPProd_or_LetIn tl ctx) ctxtl in
577 let vars = Array.fold_left (fun vars na -> Name na::vars) vars ids in
578 let ctxtl = Array.map2 (pat_of_glob_in_context metas vars) decls cl in
579 let cl = Array.map (fun (ctx,cl) -> it_mkPLambda_or_LetIn cl ctx) ctxtl in
580 let names = Array.map (fun id -> Name id) ids in
581 PFix ((ln,n), (names, tl, cl))
582
583 | GRec (GCoFix n, ids, decls, tl, cl) ->
584 let ctxtl = Array.map2 (pat_of_glob_in_context metas vars) decls tl in
585 let tl = Array.map (fun (ctx,tl) -> it_mkPProd_or_LetIn tl ctx) ctxtl in
586 let vars = Array.fold_left (fun vars na -> Name na::vars) vars ids in
587 let ctxtl = Array.map2 (pat_of_glob_in_context metas vars) decls cl in
588 let cl = Array.map (fun (ctx,cl) -> it_mkPLambda_or_LetIn cl ctx) ctxtl in
589 let names = Array.map (fun id -> Name id) ids in
590 PCoFix (n, (names, tl, cl))
591
592 | GInt i -> PInt i
593 | GFloat f -> PFloat f
594 | GString s -> PString s
595 | GPatVar _ | GIf _ | GLetTuple _ | GCases _ | GEvar _ | GArray _ ->
596 err ?loc (Pp.str "Non supported pattern."))
597
598 and pat_of_glob_in_context metas vars decls c =
599 let rec aux acc vars = function
600 | (na,_,bk,b,t) :: decls ->
601 let decl = (na,bk,Option.map (pat_of_raw metas vars) b,pat_of_raw metas vars t) in
602 aux (decl::acc) (na::vars) decls
603 | [] ->
604 acc, pat_of_raw metas vars c
605 in aux [] vars decls
606
607 and pats_of_glob_branches loc metas vars ind brs =
608 let get_arg p = match DAst.get p with
609 | PatVar na ->
610 Name.iter (fun n -> push_meta metas n) na;
611 na
612 | PatCstr(_,_,_) -> err ?loc:p.CAst.loc (Pp.str "Non supported pattern.")
613 in
614 let rec get_pat indexes = function
615 | [] -> false, []
616 | {CAst.loc=loc';v=(_,[p], br)} :: brs ->
617 begin match DAst.get p, DAst.get br, brs with
618 | PatVar Anonymous, GHole _, [] ->
619 true, [] (* ends with _ => _ *)
620 | PatCstr((indsp,j),lv,_), _, _ ->
621 let () = match ind with
622 | Some sp when Ind.UserOrd.equal sp indsp -> ()
623 | _ ->
624 err ?loc (Pp.str "All constructors must be in the same inductive type.")
625 in
626 if Int.Set.mem (j-1) indexes then
627 err ?loc
628 (str "No unique branch for " ++ int j ++ str"-th constructor.");
629 let lna = List.map get_arg lv in
630 let vars' = List.rev_append lna vars in
631 let tags = Array.of_list lna in
632 let pat = pat_of_raw metas vars' br in
633 let ext,pats = get_pat (Int.Set.add (j-1) indexes) brs in
634 ext, ((j-1, tags, pat) :: pats)
635 | _ ->
636 err ?loc:loc' (Pp.str "Non supported pattern.")
637 end
638 | {CAst.loc;v=(_,_,_)} :: _ -> err ?loc (Pp.str "Non supported pattern.")
639 in
640 get_pat Int.Set.empty brs
641
642 in pat_of_raw metas vars p
643
644 let pattern_of_glob_constr env c =
645 let metas = ref Id.Set.empty in
646 let p = pat_of_raw env (Metas metas) [] c in
647 (!metas, p)