Debian Codegraph @

plugins/ltac/tactic_matching.ml

raw symbols SCIP
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * Copyright INRIA, CNRS and contributors *)
4 (* <O___,, * (see version control and CREDITS file for authors & dates) *)
5 (* \VV/ **************************************************************)
6 (* // * This file is distributed under the terms of the *)
7 (* * GNU Lesser General Public License Version 2.1 *)
8 (* * (see LICENSE file for the text of the license) *)
9 (************************************************************************)
10
11 (** This file extends Matching with the main logic for Ltac's
12 (lazy)match and (lazy)match goal. *)
13
14 open Names
15 open Context
16 open Tacexpr
17 open Context.Named.Declaration
18
19 module NamedDecl = Context.Named.Declaration
20
21 (** [t] is the type of matching successes. It ultimately contains a
22 {!Tacexpr.glob_tactic_expr} representing the left-hand side of the
23 corresponding matching rule, a matching substitution to be
24 applied, a context substitution mapping identifier to context like
25 those of {!Matching.matching_result}), and a {!Term.constr}
26 substitution mapping corresponding to matched hypotheses. *)
27 type 'a t = {
28 subst : Constr_matching.bound_ident_map * Ltac_pretype.extended_patvar_map ;
29 context : Constr_matching.context Id.Map.t;
30 terms : EConstr.constr Id.Map.t;
31 lhs : 'a;
32 }
33
34
35
36 (** {6 Utilities} *)
37
38
39 (** Some of the functions of {!Matching} return the substitution with a
40 [patvar_map] instead of an [extended_patvar_map]. [adjust] coerces
41 substitution of the former type to the latter. *)
42 let adjust : Constr_matching.bound_ident_map * Ltac_pretype.patvar_map ->
43 Constr_matching.bound_ident_map * Ltac_pretype.extended_patvar_map =
44 fun (l, lc) -> (l, Id.Map.map (fun c -> [], c) lc)
45
46
47 (** Adds a binding to a {!Id.Map.t} if the identifier is [Some id] *)
48 let id_map_try_add id x m =
49 match id with
50 | Some id -> Id.Map.add id x m
51 | None -> m
52
53 (** Adds a binding to a {!Id.Map.t} if the name is [Name id] *)
54 let id_map_try_add_name id x m =
55 match id with
56 | Name id -> Id.Map.add id x m
57 | Anonymous -> m
58
59 (** Takes the union of two {!Id.Map.t}. If there is conflict,
60 the binding of the right-hand argument shadows that of the left-hand
61 argument. *)
62 let id_map_right_biased_union m1 m2 =
63 if Id.Map.is_empty m1 then m2 (* Don't reconstruct the whole map *)
64 else Id.Map.fold Id.Map.add m2 m1
65
66 (** Tests whether the substitution [s] is empty. *)
67 let is_empty_subst (ln,lm) =
68 Id.Map.(is_empty ln && is_empty lm)
69
70 (** {6 Non-linear patterns} *)
71
72
73 (** The patterns of Ltac are not necessarily linear. Non-linear
74 pattern are partially handled by the {!Matching} module, however
75 goal patterns are not primitive to {!Matching}, hence we must deal
76 with non-linearity between hypotheses and conclusion. Subterms are
77 considered equal up to the equality implemented in
78 [equal_instances]. *)
79 (* spiwack: it doesn't seem to be quite the same rule for non-linear
80 term patterns and non-linearity between hypotheses and/or
81 conclusion. Indeed, in [Matching], matching is made modulo
82 syntactic equality, and here we merge modulo conversion. It may be
83 a good idea to have an entry point of [Matching] with a partial
84 substitution as argument instead of merging substitution here. That
85 would ensure consistency. *)
86 let equal_instances env sigma (ctx',c') (ctx,c) =
87 (* How to compare instances? Do we want the terms to be convertible?
88 unifiable? Do we want the universe levels to be relevant?
89 (historically, conv_x is used) *)
90 CList.equal Id.equal ctx ctx' && Reductionops.is_conv env sigma c' c
91
92
93 (** Merges two substitutions. Raises [Not_coherent_metas] when
94 encountering two instances of the same metavariable which are not
95 equal according to {!equal_instances}. *)
96 exception Not_coherent_metas
97 let verify_metas_coherence env sigma (ln1,lcm) (ln,lm) =
98 let merge id oc1 oc2 = match oc1, oc2 with
99 | None, None -> None
100 | None, Some c | Some c, None -> Some c
101 | Some c1, Some c2 ->
102 if equal_instances env sigma c1 c2 then Some c1
103 else raise Not_coherent_metas
104 in
105 let (+++) lfun1 lfun2 = Id.Map.fold Id.Map.add lfun1 lfun2 in
106 (* ppedrot: Is that even correct? *)
107 let merged = ln +++ ln1 in
108 (merged, Id.Map.merge merge lcm lm)
109
110 let matching_error =
111 CErrors.UserError Pp.(str "No matching clauses for match.")
112
113 let imatching_error = (matching_error, Exninfo.null)
114
115 (** A functor is introduced to share the environment and the
116 evar_map. They do not change and it would be a pity to introduce
117 closures everywhere just for the occasional calls to
118 {!equal_instances}. *)
119 module type StaticEnvironment = sig
120 val env : Environ.env
121 val sigma : Evd.evar_map
122 end
123 module PatternMatching (E:StaticEnvironment) = struct
124
125
126 (** {6 The pattern-matching monad } *)
127
128
129 (** To focus on the algorithmic portion of pattern-matching, the
130 bookkeeping is relegated to a monad: the composition of the
131 backtracking monad of {!IStream.t} with a "writer" effect. *)
132 (* spiwack: as we don't benefit from the various stream optimisations
133 of Haskell, it may be costly to give the monad in direct style such as
134 here. We may want to use some continuation passing style. *)
135 type 'a tac = 'a Proofview.tactic
136 type 'a m = { stream : 'r. ('a -> unit t -> 'r tac) -> unit t -> 'r tac }
137
138 (** The empty substitution. *)
139 let empty_subst = Id.Map.empty , Id.Map.empty
140
141 (** Composes two substitutions using {!verify_metas_coherence}. It
142 must be a monoid with neutral element {!empty_subst}. Raises
143 [Not_coherent_metas] when composition cannot be achieved. *)
144 let subst_prod s1 s2 =
145 if is_empty_subst s1 then s2
146 else if is_empty_subst s2 then s1
147 else verify_metas_coherence E.env E.sigma s1 s2
148
149 (** The empty context substitution. *)
150 let empty_context_subst = Id.Map.empty
151
152 (** Compose two context substitutions, in case of conflict the
153 right hand substitution shadows the left hand one. *)
154 let context_subst_prod = id_map_right_biased_union
155
156 (** The empty term substitution. *)
157 let empty_term_subst = Id.Map.empty
158
159 (** Compose two terms substitutions, in case of conflict the
160 right hand substitution shadows the left hand one. *)
161 let term_subst_prod = id_map_right_biased_union
162
163 (** Merge two writers (and ignore the first value component). *)
164 let merge m1 m2 =
165 try Some {
166 subst = subst_prod m1.subst m2.subst;
167 context = context_subst_prod m1.context m2.context;
168 terms = term_subst_prod m1.terms m2.terms;
169 lhs = m2.lhs;
170 }
171 with Not_coherent_metas -> None
172
173 (** Monadic [return]: returns a single success with empty substitutions. *)
174 let return (type a) (lhs:a) : a m =
175 { stream = fun k ctx -> k lhs ctx }
176
177 (** Monadic bind: each success of [x] is replaced by the successes
178 of [f x]. The substitutions of [x] and [f x] are composed,
179 dropping the apparent successes when the substitutions are not
180 coherent. *)
181 let (>>=) (type a) (type b) (m:a m) (f:a -> b m) : b m =
182 { stream = fun k ctx -> m.stream (fun x ctx -> (f x).stream k ctx) ctx }
183
184 (** A variant of [(>>=)] when the first argument returns [unit]. *)
185 let (<*>) (type a) (m:unit m) (y:a m) : a m =
186 { stream = fun k ctx -> m.stream (fun () ctx -> y.stream k ctx) ctx }
187
188 (** Failure of the pattern-matching monad: no success. *)
189 let fail (type a) : a m = { stream = fun _ _ ->
190 let info = Exninfo.reify () in
191 Proofview.tclZERO ~info matching_error }
192
193 let run (m : 'a m) =
194 let ctx = {
195 subst = empty_subst ;
196 context = empty_context_subst ;
197 terms = empty_term_subst ;
198 lhs = ();
199 } in
200 let eval lhs ctx = Proofview.tclUNIT { ctx with lhs } in
201 m.stream eval ctx
202
203 (** Chooses in a list, in the same order as the list *)
204 let rec pick (l:'a list) (e, info) : 'a m = match l with
205 | [] -> { stream = fun _ _ -> Proofview.tclZERO ~info e }
206 | x :: l ->
207 { stream = fun k ctx -> Proofview.tclOR (k x ctx) (fun e -> (pick l e).stream k ctx) }
208
209 let pick l = pick l imatching_error
210
211 (** Declares a substitution, a context substitution and a term substitution. *)
212 let put subst context terms : unit m =
213 let s = { subst ; context ; terms ; lhs = () } in
214 { stream = fun k ctx -> match merge s ctx with
215 | None ->
216 let info = Exninfo.reify () in
217 Proofview.tclZERO ~info matching_error
218 | Some s -> k () s }
219
220 (** Declares a substitution. *)
221 let put_subst subst : unit m = put subst empty_context_subst empty_term_subst
222
223 (** Declares a term substitution. *)
224 let put_terms terms : unit m = put empty_subst empty_context_subst terms
225
226
227
228 (** {6 Pattern-matching} *)
229
230
231 (** [wildcard_match_term lhs] matches a term against a wildcard
232 pattern ([_ => lhs]). It has a single success with an empty
233 substitution. *)
234 let wildcard_match_term = return
235
236 (** [pattern_match_term pat term lhs] returns the possible
237 matchings of [term] with the pattern [pat => lhs]. *)
238 let pattern_match_term pat term lhs =
239 match pat with
240 | Term p ->
241 begin
242 try
243 put_subst (Constr_matching.extended_matches E.env E.sigma p term) <*>
244 return lhs
245 with Constr_matching.PatternMatchingFailure -> fail
246 end
247 | Subterm (id_ctxt,p) ->
248
249 let rec map s (e, info) =
250 { stream = fun k ctx -> match IStream.peek s with
251 | IStream.Nil -> Proofview.tclZERO ~info e
252 | IStream.Cons ({ Constr_matching.m_sub ; m_ctx }, s) ->
253 let subst = adjust m_sub in
254 let context = id_map_try_add id_ctxt m_ctx Id.Map.empty in
255 let terms = empty_term_subst in
256 let nctx = { subst ; context ; terms ; lhs = () } in
257 match merge ctx nctx with
258 | None -> (map s (e, info)).stream k ctx
259 | Some nctx -> Proofview.tclOR (k lhs nctx) (fun e -> (map s e).stream k ctx)
260 }
261 in
262 map (Constr_matching.match_subterm E.env E.sigma p term) imatching_error
263
264
265 (** [rule_match_term term rule] matches the term [term] with the
266 matching rule [rule]. *)
267 let rule_match_term term = function
268 | All lhs -> wildcard_match_term lhs
269 | Pat ([],pat,lhs) -> pattern_match_term pat term lhs
270 | Pat _ ->
271 (* Rules with hypotheses, only work in match goal. *)
272 fail
273
274 (** [match_term term rules] matches the term [term] with the set of
275 matching rules [rules].*)
276 let rec match_term (e, info) term rules = match rules with
277 | [] -> { stream = fun _ _ -> Proofview.tclZERO ~info e }
278 | r :: rules ->
279 { stream = fun k ctx ->
280 let head = rule_match_term term r in
281 let tail e = match_term e term rules in
282 Proofview.tclOR (head.stream k ctx) (fun e -> (tail e).stream k ctx)
283 }
284
285 (** [hyp_match_type hypname pat hyps] matches a single
286 hypothesis pattern [hypname:pat] against the hypotheses in
287 [hyps]. Tries the hypotheses in order. For each success returns
288 the name of the matched hypothesis. *)
289 let hyp_match_type except hypname pat hyps =
290 pick hyps >>= fun decl ->
291 let id = NamedDecl.get_id decl in
292 if Id.Set.mem id except then fail
293 else
294 pattern_match_term pat (NamedDecl.get_type decl) () <*>
295 put_terms (id_map_try_add_name hypname (EConstr.mkVar id) empty_term_subst) <*>
296 return id
297
298 (** [hyp_match_type hypname bodypat typepat hyps] matches a single
299 hypothesis pattern [hypname := bodypat : typepat] against the
300 hypotheses in [hyps].Tries the hypotheses in order. For each
301 success returns the name of the matched hypothesis. *)
302 let hyp_match_body_and_type except hypname bodypat typepat hyps =
303 pick hyps >>= function
304 | LocalDef (id,body,hyp) ->
305 if Id.Set.mem id.binder_name except then fail
306 else
307 pattern_match_term bodypat body () <*>
308 pattern_match_term typepat hyp () <*>
309 put_terms (id_map_try_add_name hypname (EConstr.mkVar id.binder_name) empty_term_subst) <*>
310 return id.binder_name
311 | LocalAssum (id,hyp) -> fail
312
313 (** [hyp_match pat hyps] dispatches to
314 {!hyp_match_type} or {!hyp_match_body_and_type} depending on whether
315 [pat] is [Hyp _] or [Def _]. *)
316 let hyp_match except pat hyps =
317 match pat with
318 | Hyp ({CAst.v=hypname},typepat) ->
319 hyp_match_type except hypname typepat hyps
320 | Def ({CAst.v=hypname},bodypat,typepat) ->
321 hyp_match_body_and_type except hypname bodypat typepat hyps
322
323 (** [hyp_pattern_list_match pats hyps lhs], matches the list of
324 patterns [pats] against the hypotheses in [hyps], and eventually
325 returns [lhs]. *)
326 let rec hyp_pattern_list_match except pats hyps lhs =
327 match pats with
328 | pat::pats ->
329 hyp_match except pat hyps >>= fun matched_hyp ->
330 let except = Id.Set.add matched_hyp except in
331 hyp_pattern_list_match except pats hyps lhs
332 | [] -> return lhs
333
334 (** [rule_match_goal hyps concl rule] matches the rule [rule]
335 against the goal [hyps|-concl]. *)
336 let rule_match_goal hyps concl = function
337 | All lhs -> wildcard_match_term lhs
338 | Pat (hyppats,conclpat,lhs) ->
339 (* the rules are applied from the topmost one (in the concrete
340 syntax) to the bottommost. *)
341 let hyppats = List.rev hyppats in
342 pattern_match_term conclpat concl () <*>
343 hyp_pattern_list_match Id.Set.empty hyppats hyps lhs
344
345 (** [match_goal hyps concl rules] matches the goal [hyps|-concl]
346 with the set of matching rules [rules]. *)
347 let rec match_goal (e, info) hyps concl rules = match rules with
348 | [] -> { stream = fun _ _ -> Proofview.tclZERO ~info e }
349 | r :: rules ->
350 { stream = fun k ctx ->
351 let head = rule_match_goal hyps concl r in
352 let tail e = match_goal e hyps concl rules in
353 Proofview.tclOR (head.stream k ctx) (fun e -> (tail e).stream k ctx)
354 }
355
356 end
357
358 (** [match_term env sigma term rules] matches the term [term] with the
359 set of matching rules [rules]. The environment [env] and the
360 evar_map [sigma] are not currently used, but avoid code
361 duplication. *)
362 let match_term env sigma term rules =
363 let module E = struct
364 let env = env
365 let sigma = sigma
366 end in
367 let module M = PatternMatching(E) in
368 M.run (M.match_term imatching_error term rules)
369
370
371 (** [match_goal env sigma hyps concl rules] matches the goal
372 [hyps|-concl] with the set of matching rules [rules]. The
373 environment [env] and the evar_map [sigma] are used to check
374 convertibility for pattern variables shared between hypothesis
375 patterns or the conclusion pattern. *)
376 let match_goal env sigma hyps concl rules =
377 let module E = struct
378 let env = env
379 let sigma = sigma
380 end in
381 let module M = PatternMatching(E) in
382 M.run (M.match_goal imatching_error hyps concl rules)