comparison src/Match.v @ 328:cbeccef45f4e

Pass over Match
author Adam Chlipala <adam@chlipala.net>
date Sun, 25 Sep 2011 13:20:56 -0400
parents 06d11a6363cd
children d7178fb77321
comparison
equal deleted inserted replaced
327:5cdfbf56afbe 328:cbeccef45f4e
16 (* end hide *) 16 (* end hide *)
17 17
18 18
19 (** %\chapter{Proof Search in Ltac}% *) 19 (** %\chapter{Proof Search in Ltac}% *)
20 20
21 (** We have seen many examples of proof automation so far. This chapter aims to give a principled presentation of the features of Ltac, focusing in particular on the Ltac [match] construct, which supports a novel approach to backtracking search. First, though, we will run through some useful automation tactics that are built into Coq. They are described in detail in the manual, so we only outline what is possible. *) 21 (** We have seen many examples of proof automation so far, some with tantalizing code snippets from Ltac, Coq's domain-specific language for proof search procedures. This chapter aims to give a bottom-up presentation of the features of Ltac, focusing in particular on the Ltac %\index{tactics!match}%[match] construct, which supports a novel approach to backtracking search. First, though, we will run through some useful automation tactics that are built into Coq. They are described in detail in the manual, so we only outline what is possible. *)
22 22
23 (** * Some Built-In Automation Tactics *) 23 (** * Some Built-In Automation Tactics *)
24 24
25 (** A number of tactics are called repeatedly by [crush]. [intuition] simplifies propositional structure of goals. [congruence] applies the rules of equality and congruence closure, plus properties of constructors of inductive types. The [omega] tactic provides a complete decision procedure for a theory that is called quantifier-free linear arithmetic or Presburger arithmetic, depending on whom you ask. That is, [omega] proves any goal that follows from looking only at parts of that goal that can be interpreted as propositional formulas whose atomic formulas are basic comparison operations on natural numbers or integers. 25 (** A number of tactics are called repeatedly by [crush]. The %\index{tactics!intuition}%[intuition] tactic simplifies propositional structure of goals. The %\index{tactics!congruence}%[congruence] tactic applies the rules of equality and congruence closure, plus properties of constructors of inductive types. The %\index{tactics!omega}%[omega] tactic provides a complete decision procedure for a theory that is called %\index{linear arithmetic}%quantifier-free linear arithmetic or %\index{Presburger arithmetic}%Presburger arithmetic, depending on whom you ask. That is, [omega] proves any goal that follows from looking only at parts of that goal that can be interpreted as propositional formulas whose atomic formulas are basic comparison operations on natural numbers or integers.
26 26
27 The [ring] tactic solves goals by appealing to the axioms of rings or semi-rings (as in algebra), depending on the type involved. Coq developments may declare new types to be parts of rings and semi-rings by proving the associated axioms. There is a simlar tactic [field] for simplifying values in fields by conversion to fractions over rings. Both [ring] and [field] can only solve goals that are equalities. The [fourier] tactic uses Fourier's method to prove inequalities over real numbers, which are axiomatized in the Coq standard library. 27 The %\index{tactics!ring}%[ring] tactic solves goals by appealing to the axioms of rings or semi-rings (as in algebra), depending on the type involved. Coq developments may declare new types to be parts of rings and semi-rings by proving the associated axioms. There is a similar tactic %\index{tactics!field}\coqdockw{%#<tt>#field#</tt>#%}% for simplifying values in fields by conversion to fractions over rings. Both [ring] and %\coqdockw{%#<tt>#field#</tt>#%}% can only solve goals that are equalities. The %\index{tactics!fourier}\coqdockw{%#<tt>#fourier#</tt>#%}% tactic uses Fourier's method to prove inequalities over real numbers, which are axiomatized in the Coq standard library.
28 28
29 The %\textit{%#<i>#setoid#</i>#%}% facility makes it possible to register new equivalence relations to be understood by tactics like [rewrite]. For instance, [Prop] is registered as a setoid with the equivalence relation %``%#"#if and only if.#"#%''% The ability to register new setoids can be very useful in proofs of a kind common in math, where all reasoning is done after %``%#"#modding out by a relation.#"#%''% *) 29 The %\index{setoids}\textit{%#<i>#setoid#</i>#%}% facility makes it possible to register new equivalence relations to be understood by tactics like [rewrite]. For instance, [Prop] is registered as a setoid with the equivalence relation %``%#"#if and only if.#"#%''% The ability to register new setoids can be very useful in proofs of a kind common in math, where all reasoning is done after %``%#"#modding out by a relation.#"#%''%
30
31 There are several other built-in %``%#"#black box#"#%''% automation tactics, which one can learn about by perusing the Coq manual. The real promise of Coq, though, is in the coding of problem-specific tactics with Ltac. *)
30 32
31 33
32 (** * Ltac Programming Basics *) 34 (** * Ltac Programming Basics *)
33 35
34 (** We have already seen many examples of Ltac programs. In the rest of this chapter, we attempt to give a more principled introduction to the important features and design patterns. 36 (** We have already seen many examples of Ltac programs. In the rest of this chapter, we attempt to give a thorough introduction to the important features and design patterns.
35 37
36 One common use for [match] tactics is identification of subjects for case analysis, as we see in this tactic definition. *) 38 One common use for [match] tactics is identification of subjects for case analysis, as we see in this tactic definition. *)
37 39
38 (* begin thide *) 40 (* begin thide *)
39 Ltac find_if := 41 Ltac find_if :=
55 (* begin thide *) 57 (* begin thide *)
56 intros; repeat find_if; constructor. 58 intros; repeat find_if; constructor.
57 Qed. 59 Qed.
58 (* end thide *) 60 (* end thide *)
59 61
60 (** The [repeat] that we use here is called a %\textit{%#<i>#tactical#</i>#%}%, or tactic combinator. The behavior of [repeat t] is to loop through running [t], running [t] on all generated subgoals, running [t] on %\textit{%#<i>#their#</i>#%}% generated subgoals, and so on. When [t] fails at any point in this search tree, that particular subgoal is left to be handled by later tactics. Thus, it is important never to use [repeat] with a tactic that always succeeds. 62 (** The %\index{tactics!repeat}%[repeat] that we use here is called a %\index{tactical}\textit{%#<i>#tactical#</i>#%}%, or tactic combinator. The behavior of [repeat t] is to loop through running [t], running [t] on all generated subgoals, running [t] on %\textit{%#<i>#their#</i>#%}% generated subgoals, and so on. When [t] fails at any point in this search tree, that particular subgoal is left to be handled by later tactics. Thus, it is important never to use [repeat] with a tactic that always succeeds.
61 63
62 Another very useful Ltac building block is %\textit{%#<i>#context patterns#</i>#%}%. *) 64 Another very useful Ltac building block is %\index{context patterns}\textit{%#<i>#context patterns#</i>#%}%. *)
63 65
64 (* begin thide *) 66 (* begin thide *)
65 Ltac find_if_inside := 67 Ltac find_if_inside :=
66 match goal with 68 match goal with
67 | [ |- context[if ?X then _ else _] ] => destruct X 69 | [ |- context[if ?X then _ else _] ] => destruct X
105 107
106 | [ H : False |- _ ] => destruct H 108 | [ H : False |- _ ] => destruct H
107 | [ H : _ /\ _ |- _ ] => destruct H 109 | [ H : _ /\ _ |- _ ] => destruct H
108 | [ H : _ \/ _ |- _ ] => destruct H 110 | [ H : _ \/ _ |- _ ] => destruct H
109 111
110 | [ H1 : ?P -> ?Q, H2 : ?P |- _ ] => 112 | [ H1 : ?P -> ?Q, H2 : ?P |- _ ] => specialize (H1 H2)
111 let H := fresh "H" in
112 generalize (H1 H2); clear H1; intro H
113 end. 113 end.
114 (* end thide *) 114 (* end thide *)
115 115
116 (** Since [match] patterns can share unification variables between hypothesis and conclusion patterns, it is easy to figure out when the conclusion matches a hypothesis. The [exact] tactic solves a goal completely when given a proof term of the proper type. 116 (** Since [match] patterns can share unification variables between hypothesis and conclusion patterns, it is easy to figure out when the conclusion matches a hypothesis. The %\index{tactics!exact}%[exact] tactic solves a goal completely when given a proof term of the proper type.
117 117
118 It is also trivial to implement the %``%#"#introduction rules#"#%''% for a few of the connectives. Implementing elimination rules is only a little more work, since we must give a name for a hypothesis to [destruct]. 118 It is also trivial to implement the introduction rules (in the sense of %\index{natural deduction}%natural deduction%~\cite{TAPLNatDed}%) for a few of the connectives. Implementing elimination rules is only a little more work, since we must give a name for a hypothesis to [destruct].
119 119
120 The last rule implements modus ponens. The most interesting part is the use of the Ltac-level [let] with a [fresh] expression. [fresh] takes in a name base and returns a fresh hypothesis variable based on that name. We use the new name variable [H] as the name we assign to the result of modus ponens. The use of [generalize] changes our conclusion to be an implication from [Q]. We clear the original hypothesis and move [Q] into the context with name [H]. *) 120 The last rule implements modus ponens, using a tactic %\index{tactics!specialize}\coqdockw{%#<tt>#specialize#</tt>#%}% which will replace a hypothesis with a version that is specialized to a provided set of arguments (for quantified variables or local hypotheses from implications). *)
121 121
122 Section propositional. 122 Section propositional.
123 Variables P Q R : Prop. 123 Variables P Q R : Prop.
124 124
125 Theorem propositional : (P \/ Q \/ False) /\ (P -> Q) -> True /\ Q. 125 Theorem propositional : (P \/ Q \/ False) /\ (P -> Q) -> True /\ Q.
127 my_tauto. 127 my_tauto.
128 Qed. 128 Qed.
129 (* end thide *) 129 (* end thide *)
130 End propositional. 130 End propositional.
131 131
132 (** It was relatively easy to implement modus ponens, because we do not lose information by clearing every implication that we use. If we want to implement a similarly-complete procedure for quantifier instantiation, we need a way to ensure that a particular proposition is not already included among our hypotheses. To do that effectively, we first need to learn a bit more about the semantics of [match]. 132 (** It was relatively easy to implement modus ponens, because we do not lose information by clearing every implication that we use. If we want to implement a similarly complete procedure for quantifier instantiation, we need a way to ensure that a particular proposition is not already included among our hypotheses. To do that effectively, we first need to learn a bit more about the semantics of [match].
133 133
134 It is tempting to assume that [match] works like it does in ML. In fact, there are a few critical differences in its behavior. One is that we may include arbitrary expressions in patterns, instead of being restricted to variables and constructors. Another is that the same variable may appear multiple times, inducing an implicit equality constraint. 134 It is tempting to assume that [match] works like it does in ML. In fact, there are a few critical differences in its behavior. One is that we may include arbitrary expressions in patterns, instead of being restricted to variables and constructors. Another is that the same variable may appear multiple times, inducing an implicit equality constraint.
135 135
136 There is a related pair of two other differences that are much more important than the others. [match] has a %\textit{%#<i>#backtracking semantics for failure#</i>#%}%. In ML, pattern matching works by finding the first pattern to match and then executing its body. If the body raises an exception, then the overall match raises the same exception. In Coq, failures in case bodies instead trigger continued search through the list of cases. 136 There is a related pair of two other differences that are much more important than the others. The [match] construct has a %\textit{%#<i>#backtracking semantics for failure#</i>#%}%. In ML, pattern matching works by finding the first pattern to match and then executing its body. If the body raises an exception, then the overall match raises the same exception. In Coq, failures in case bodies instead trigger continued search through the list of cases.
137 137
138 For instance, this (unnecessarily verbose) proof script works: *) 138 For instance, this (unnecessarily verbose) proof script works: *)
139 139
140 Theorem m1 : True. 140 Theorem m1 : True.
141 match goal with 141 match goal with
153 Theorem m2 : forall P Q R : Prop, P -> Q -> R -> Q. 153 Theorem m2 : forall P Q R : Prop, P -> Q -> R -> Q.
154 intros; match goal with 154 intros; match goal with
155 | [ H : _ |- _ ] => idtac H 155 | [ H : _ |- _ ] => idtac H
156 end. 156 end.
157 157
158 (** Coq prints %``%#"#[H1]#"#%''%. By applying [idtac] with an argument, a convenient debugging tool for %``%#"#leaking information out of [match]es,#"#%''% we see that this [match] first tries binding [H] to [H1], which cannot be used to prove [Q]. Nonetheless, the following variation on the tactic succeeds at proving the goal: *) 158 (** Coq prints %``%#"#[H1]#"#%''%. By applying %\index{tactics!idtac}%[idtac] with an argument, a convenient debugging tool for %``%#"#leaking information out of [match]es,#"#%''% we see that this [match] first tries binding [H] to [H1], which cannot be used to prove [Q]. Nonetheless, the following variation on the tactic succeeds at proving the goal: *)
159 159
160 (* begin thide *) 160 (* begin thide *)
161 match goal with 161 match goal with
162 | [ H : _ |- _ ] => exact H 162 | [ H : _ |- _ ] => exact H
163 end. 163 end.
178 | _ => idtac 178 | _ => idtac
179 end 179 end
180 end. 180 end.
181 (* end thide *) 181 (* end thide *)
182 182
183 (** We use the equality checking that is built into pattern-matching to see if there is a hypothesis that matches the proposition exactly. If so, we use the [fail] tactic. Without arguments, [fail] signals normal tactic failure, as you might expect. When [fail] is passed an argument [n], [n] is used to count outwards through the enclosing cases of backtracking search. In this case, [fail 1] says %``%#"#fail not just in this pattern-matching branch, but for the whole [match].#"#%''% The second case will never be tried when the [fail 1] is reached. 183 (** We use the equality checking that is built into pattern-matching to see if there is a hypothesis that matches the proposition exactly. If so, we use the %\index{tactics!fail}%[fail] tactic. Without arguments, [fail] signals normal tactic failure, as you might expect. When [fail] is passed an argument [n], [n] is used to count outwards through the enclosing cases of backtracking search. In this case, [fail 1] says %``%#"#fail not just in this pattern-matching branch, but for the whole [match].#"#%''% The second case will never be tried when the [fail 1] is reached.
184 184
185 This second case, used when [P] matches no hypothesis, checks if [P] is a conjunction. Other simplifications may have split conjunctions into their component formulas, so we need to check that at least one of those components is also not represented. To achieve this, we apply the [first] tactical, which takes a list of tactics and continues down the list until one of them does not fail. The [fail 2] at the end says to [fail] both the [first] and the [match] wrapped around it. 185 This second case, used when [P] matches no hypothesis, checks if [P] is a conjunction. Other simplifications may have split conjunctions into their component formulas, so we need to check that at least one of those components is also not represented. To achieve this, we apply the %\index{tactics!first}%[first] tactical, which takes a list of tactics and continues down the list until one of them does not fail. The [fail 2] at the end says to [fail] both the [first] and the [match] wrapped around it.
186 186
187 The body of the [?P1 /\ ?P2] case guarantees that, if it is reached, we either succeed completely or fail completely. Thus, if we reach the wildcard case, [P] is not a conjunction. We use [idtac], a tactic that would be silly to apply on its own, since its effect is to succeed at doing nothing. Nonetheless, [idtac] is a useful placeholder for cases like what we see here. 187 The body of the [?P1 /\ ?P2] case guarantees that, if it is reached, we either succeed completely or fail completely. Thus, if we reach the wildcard case, [P] is not a conjunction. We use %\index{tactics!idtac}%[idtac], a tactic that would be silly to apply on its own, since its effect is to succeed at doing nothing. Nonetheless, [idtac] is a useful placeholder for cases like what we see here.
188 188
189 With the non-presence check implemented, it is easy to build a tactic that takes as input a proof term and adds its conclusion as a new hypothesis, only if that conclusion is not already present, failing otherwise. *) 189 With the non-presence check implemented, it is easy to build a tactic that takes as input a proof term and adds its conclusion as a new hypothesis, only if that conclusion is not already present, failing otherwise. *)
190 190
191 (* begin thide *) 191 (* begin thide *)
192 Ltac extend pf := 192 Ltac extend pf :=
193 let t := type of pf in 193 let t := type of pf in
194 notHyp t; generalize pf; intro. 194 notHyp t; generalize pf; intro.
195 (* end thide *) 195 (* end thide *)
196 196
197 (** We see the useful [type of] operator of Ltac. This operator could not be implemented in Gallina, but it is easy to support in Ltac. We end up with [t] bound to the type of [pf]. We check that [t] is not already present. If so, we use a [generalize]/[intro] combo to add a new hypothesis proved by [pf]. 197 (** We see the useful %\index{tactics!type of}%[type of] operator of Ltac. This operator could not be implemented in Gallina, but it is easy to support in Ltac. We end up with [t] bound to the type of [pf]. We check that [t] is not already present. If so, we use a [generalize]/[intro] combo to add a new hypothesis proved by [pf]. The tactic %\index{tactics!generalize}%[generalize] takes as input a term [t] (for instance, a proof of some proposition) and then changes the conclusion from [G] to [T -> G], where [T] is the type of [t] (for instance, the proposition proved by a proof given as argument).
198 198
199 With these tactics defined, we can write a tactic [completer] for adding to the context all consequences of a set of simple first-order formulas. *) 199 With these tactics defined, we can write a tactic [completer] for adding to the context all consequences of a set of simple first-order formulas. *)
200 200
201 (* begin thide *) 201 (* begin thide *)
202 Ltac completer := 202 Ltac completer :=
203 repeat match goal with 203 repeat match goal with
204 | [ |- _ /\ _ ] => constructor 204 | [ |- _ /\ _ ] => constructor
205 | [ H : _ /\ _ |- _ ] => destruct H 205 | [ H : _ /\ _ |- _ ] => destruct H
206 | [ H : ?P -> ?Q, H' : ?P |- _ ] => 206 | [ H : ?P -> ?Q, H' : ?P |- _ ] => specialize (H H')
207 generalize (H H'); clear H; intro H
208 | [ |- forall x, _ ] => intro 207 | [ |- forall x, _ ] => intro
209 208
210 | [ H : forall x, ?P x -> _, H' : ?P ?X |- _ ] => 209 | [ H : forall x, ?P x -> _, H' : ?P ?X |- _ ] => extend (H X H')
211 extend (H X H')
212 end. 210 end.
213 (* end thide *) 211 (* end thide *)
214 212
215 (** We use the same kind of conjunction and implication handling as previously. Note that, since [->] is the special non-dependent case of [forall], the fourth rule handles [intro] for implications, too. 213 (** We use the same kind of conjunction and implication handling as previously. Note that, since [->] is the special non-dependent case of [forall], the fourth rule handles [intro] for implications, too.
216 214
249 (* begin thide *) 247 (* begin thide *)
250 Ltac completer' := 248 Ltac completer' :=
251 repeat match goal with 249 repeat match goal with
252 | [ |- _ /\ _ ] => constructor 250 | [ |- _ /\ _ ] => constructor
253 | [ H : _ /\ _ |- _ ] => destruct H 251 | [ H : _ /\ _ |- _ ] => destruct H
254 | [ H : ?P -> _, H' : ?P |- _ ] => 252 | [ H : ?P -> _, H' : ?P |- _ ] => specialize (H H')
255 generalize (H H'); clear H; intro H
256 | [ |- forall x, _ ] => intro 253 | [ |- forall x, _ ] => intro
257 254
258 | [ H : forall x, ?P x -> _, H' : ?P ?X |- _ ] => 255 | [ H : forall x, ?P x -> _, H' : ?P ?X |- _ ] => extend (H X H')
259 extend (H X H')
260 end. 256 end.
261 (* end thide *) 257 (* end thide *)
262 258
263 (** The only difference is in the modus ponens rule, where we have replaced an unused unification variable [?Q] with a wildcard. Let us try our example again with this version: *) 259 (** The only difference is in the modus ponens rule, where we have replaced an unused unification variable [?][Q] with a wildcard. Let us try our example again with this version: *)
264 260
265 Section firstorder'. 261 Section firstorder'.
266 Variable A : Set. 262 Variable A : Set.
267 Variables P Q R S : A -> Prop. 263 Variables P Q R S : A -> Prop.
268 264
298 Theorem t1' : forall x : nat, x = x. 294 Theorem t1' : forall x : nat, x = x.
299 (** [[ 295 (** [[
300 match goal with 296 match goal with
301 | [ |- forall x, ?P ] => trivial 297 | [ |- forall x, ?P ] => trivial
302 end. 298 end.
303 299 ]]
300
301 <<
304 User error: No matching clauses for match goal 302 User error: No matching clauses for match goal
305 ]] 303 >>
306 *) 304 *)
307 305
308 Abort. 306 Abort.
309 (* end thide *) 307 (* end thide *)
310 308
311 (** The problem is that unification variables may not contain locally-bound variables. In this case, [?P] would need to be bound to [x = x], which contains the local quantified variable [x]. By using a wildcard in the earlier version, we avoided this restriction. To understand why this applies to the [completer] tactics, recall that, in Coq, implication is shorthand for degenerate universal quantification where the quantified variable is not used. Nonetheless, in an Ltac pattern, Coq is happy to match a wildcard implication against a universal quantification. 309 (** The problem is that unification variables may not contain locally bound variables. In this case, [?][P] would need to be bound to [x = x], which contains the local quantified variable [x]. By using a wildcard in the earlier version, we avoided this restriction. To understand why this applies to the [completer] tactics, recall that, in Coq, implication is shorthand for degenerate universal quantification where the quantified variable is not used. Nonetheless, in an Ltac pattern, Coq is happy to match a wildcard implication against a universal quantification.
312 310
313 The Coq 8.2 release includes a special pattern form for a unification variable with an explicit set of free variables. That unification variable is then bound to a function from the free variables to the %``%#"#real#"#%''% value. In Coq 8.1 and earlier, there is no such workaround. 311 The Coq 8.2 release includes a special pattern form for a unification variable with an explicit set of free variables. That unification variable is then bound to a function from the free variables to the %``%#"#real#"#%''% value. In Coq 8.1 and earlier, there is no such workaround.
314 312
315 No matter which version you use, it is important to be aware of this restriction. As we have alluded to, the restriction is the culprit behind the infinite-looping behavior of [completer']. We unintentionally match quantified facts with the modus ponens rule, circumventing the %``%#"#already present#"#%''% check and leading to different behavior, where the same fact may be added to the context repeatedly in an infinite loop. Our earlier [completer] tactic uses a modus ponens rule that matches the implication conclusion with a variable, which blocks matching against non-trivial universal quantifiers. *) 313 No matter which version you use, it is important to be aware of this restriction. As we have alluded to, the restriction is the culprit behind the infinite-looping behavior of [completer']. We unintentionally match quantified facts with the modus ponens rule, circumventing the %``%#"#already present#"#%''% check and leading to different behavior, where the same fact may be added to the context repeatedly in an infinite loop. Our earlier [completer] tactic uses a modus ponens rule that matches the implication conclusion with a variable, which blocks matching against non-trivial universal quantifiers. *)
316 314
327 Ltac length ls := 325 Ltac length ls :=
328 match ls with 326 match ls with
329 | nil => O 327 | nil => O
330 | _ :: ls' => S (length ls') 328 | _ :: ls' => S (length ls')
331 end. 329 end.
332 330 ]]
331
332 <<
333 Error: The reference ls' was not found in the current environment 333 Error: The reference ls' was not found in the current environment
334 334 >>
335 ]]
336 335
337 At this point, we hopefully remember that pattern variable names must be prefixed by question marks in Ltac. 336 At this point, we hopefully remember that pattern variable names must be prefixed by question marks in Ltac.
338 337
339 [[ 338 [[
340 Ltac length ls := 339 Ltac length ls :=
341 match ls with 340 match ls with
342 | nil => O 341 | nil => O
343 | _ :: ?ls' => S (length ls') 342 | _ :: ?ls' => S (length ls')
344 end. 343 end.
345 344 ]]
345
346 <<
346 Error: The reference S was not found in the current environment 347 Error: The reference S was not found in the current environment
347 348 >>
348 ]] 349
349 350 The problem is that Ltac treats the expression [S (][length ls')] as an invocation of a tactic [S] with argument [length ls']. We need to use a special annotation to %``%#"#escape into#"#%''% the Gallina parsing nonterminal.%\index{tactics!constr}% *)
350 The problem is that Ltac treats the expression [S (length ls')] as an invocation of a tactic [S] with argument [length ls']. We need to use a special annotation to %``%#"#escape into#"#%''% the Gallina parsing nonterminal. *)
351 351
352 (* begin thide *) 352 (* begin thide *)
353 Ltac length ls := 353 Ltac length ls :=
354 match ls with 354 match ls with
355 | nil => O 355 | nil => O
366 ============================ 366 ============================
367 False 367 False
368 368
369 ]] 369 ]]
370 370
371 We use the [pose] tactic, which extends the proof context with a new variable that is set equal to a particular term. We could also have used [idtac n] in place of [pose n], which would have printed the result without changing the context. 371 We use the %\index{tactics!pose}%[pose] tactic, which extends the proof context with a new variable that is set equal to a particular term. We could also have used [idtac n] in place of [pose n], which would have printed the result without changing the context.
372 372
373 [n] only has the length calculation unrolled one step. What has happened here is that, by escaping into the [constr] nonterminal, we referred to the [length] function of Gallina, rather than the [length] Ltac function that we are defining. *) 373 The value of [n] only has the length calculation unrolled one step. What has happened here is that, by escaping into the [constr] nonterminal, we referred to the [length] function of Gallina, rather than the [length] Ltac function that we are defining. *)
374 374
375 Abort. 375 Abort.
376 376
377 (* begin hide *)
377 Reset length. 378 Reset length.
379 (* end hide *)
380 (** %\noindent\coqdockw{%#<tt>#Reset#</tt>#%}% [length.] *)
378 381
379 (** The thing to remember is that Gallina terms built by tactics must be bound explicitly via [let] or a similar technique, rather than inserting Ltac calls directly in other Gallina terms. *) 382 (** The thing to remember is that Gallina terms built by tactics must be bound explicitly via [let] or a similar technique, rather than inserting Ltac calls directly in other Gallina terms. *)
380 383
381 Ltac length ls := 384 Ltac length ls :=
382 match ls with 385 match ls with
413 let ls'' := map' ls' in 416 let ls'' := map' ls' in
414 constr:( x' :: ls'') 417 constr:( x' :: ls'')
415 end in 418 end in
416 map'. 419 map'.
417 420
418 (** Ltac functions can have no implicit arguments. It may seem surprising that we need to pass [T], the carried type of the output list, explicitly. We cannot just use [type of f], because [f] is an Ltac term, not a Gallina term, and Ltac programs are dynamically typed. [f] could use very syntactic methods to decide to return differently typed terms for different inputs. We also could not replace [constr:( @nil T)] with [constr: nil], because we have no strongly-typed context to use to infer the parameter to [nil]. Luckily, we do have sufficient context within [constr:( x' :: ls'')]. 421 (** Ltac functions can have no implicit arguments. It may seem surprising that we need to pass [T], the carried type of the output list, explicitly. We cannot just use [type of f], because [f] is an Ltac term, not a Gallina term, and Ltac programs are dynamically typed. The function [f] could use very syntactic methods to decide to return differently typed terms for different inputs. We also could not replace [constr:( @][nil T)] with [constr: nil], because we have no strongly typed context to use to infer the parameter to [nil]. Luckily, we do have sufficient context within [constr:( x' :: ls'')].
419 422
420 Sometimes we need to employ the opposite direction of %``%#"#nonterminal escape,#"#%''% when we want to pass a complicated tactic expression as an argument to another tactic, as we might want to do in invoking [map]. *) 423 Sometimes we need to employ the opposite direction of %``%#"#nonterminal escape,#"#%''% when we want to pass a complicated tactic expression as an argument to another tactic, as we might want to do in invoking [map]. *)
421 424
422 Goal False. 425 Goal False.
423 let ls := map (nat * nat)%type ltac:(fun x => constr:( x, x)) (1 :: 2 :: 3 :: nil) in 426 let ls := map (nat * nat)%type ltac:(fun x => constr:( x, x)) (1 :: 2 :: 3 :: nil) in
430 *) 433 *)
431 434
432 Abort. 435 Abort.
433 (* end thide *) 436 (* end thide *)
434 437
438 (** One other gotcha shows up when we want to debug our Ltac functional programs. We might expect the following code to work, to give us a version of [length] that prints a debug trace of the arguments it is called with. *)
439
440 (* begin hide *)
441 Reset length.
442 (* end hide *)
443 (** %\noindent\coqdockw{%#<tt>#Reset#</tt>#%}% [length.] *)
444
445 Ltac length ls :=
446 idtac ls;
447 match ls with
448 | nil => O
449 | _ :: ?ls' =>
450 let ls'' := length ls' in
451 constr:(S ls'')
452 end.
453
454 (** Coq accepts the tactic definition, but the code is fatally flawed and will always lead to dynamic type errors. *)
455
456 Goal False.
457 (** %\vspace{-.15in}%[[
458 let n := length (1 :: 2 :: 3 :: nil) in
459 pose n.
460 ]]
461
462 <<
463 Error: variable n should be bound to a term.
464 >> *)
465 Abort.
466
467 (** What is going wrong here? The answer has to do with the dual status of Ltac as both a purely functional and an imperative programming language. The basic programming language is purely functional, but tactic scripts are one %``%#"#datatype#"#%''% that can be returned by such programs, and Coq will run such a script using an imperative semantics that mutates proof states. Readers familiar with %\index{monads}\index{Haskell}%monadic programming in Haskell%~\cite{monads,IO}% may recognize a similarity. Side-effecting Haskell programs can be thought of as pure programs that return %\emph{%#<i>#the code of programs in an imperative language#</i>#%}%, where some out-of-band mechanism takes responsibility for running these derived programs. In this way, Haskell remains pure, while supporting usual input-output side effects and more. Ltac uses the same basic mechanism, but in a dynamically typed setting. Here the embedded imperative language includes all the tactics we have been applying so far.
468
469 Even basic [idtac] is an embedded imperative program, so we may not automatically mix it with purely functional code. In fact, a semicolon operator alone marks a span of Ltac code as an embedded tactic script. This makes some amount of sense, since pure functional languages have no need for sequencing: since they lack side effects, there is no reason to run an expression and then just throw away its value and move on to another expression.
470
471 The solution is like in Haskell: we must %``%#"#monadify#"#%''% our pure program to give it access to side effects. The trouble is that the embedded tactic language has no [return] construct. Proof scripts are about proving theorems, not calculating results. We can apply a somewhat awkward workaround that requires translating our program into %\index{continuation-passing style}\emph{%#<i>#continuation-passing style#</i>#%}%, a program structuring idea popular in functional programming. *)
472
473 (* begin hide *)
474 Reset length.
475 (* end hide *)
476 (** %\noindent\coqdockw{%#<tt>#Reset#</tt>#%}% [length.] *)
477
478 Ltac length ls k :=
479 idtac ls;
480 match ls with
481 | nil => k O
482 | _ :: ?ls' => length ls' ltac:(fun n => k (S n))
483 end.
484
485 (** The new [length] takes a new input: a %\emph{%#<i>#continuation#</i>#%}% [k], which is a function to be called to continue whatever proving process we were in the middle of when we called [length]. The argument passed to [k] may be thought of as the return value of [length]. *)
486
487 Goal False.
488 length (1 :: 2 :: 3 :: nil) ltac:(fun n => pose n).
489 (** [[
490 (1 :: 2 :: 3 :: nil)
491 (2 :: 3 :: nil)
492 (3 :: nil)
493 nil
494 ]]
495 *)
496 Abort.
497
498 (** We see exactly the trace of function arguments that we expected initially, and an examination of the proof state afterward would show that variable [n] has been added with value [3]. *)
499
435 500
436 (** * Recursive Proof Search *) 501 (** * Recursive Proof Search *)
437 502
438 (** Deciding how to instantiate quantifiers is one of the hardest parts of automated first-order theorem proving. For a given problem, we can consider all possible bounded-length sequences of quantifier instantiations, applying only propositional reasoning at the end. This is probably a bad idea for almost all goals, but it makes for a nice example of recursive proof search procedures in Ltac. 503 (** Deciding how to instantiate quantifiers is one of the hardest parts of automated first-order theorem proving. For a given problem, we can consider all possible bounded-length sequences of quantifier instantiations, applying only propositional reasoning at the end. This is probably a bad idea for almost all goals, but it makes for a nice example of recursive proof search procedures in Ltac.
439 504
448 | [ H : forall x : ?T, _, x : ?T |- _ ] => generalize (H x); inster n' 513 | [ H : forall x : ?T, _, x : ?T |- _ ] => generalize (H x); inster n'
449 end 514 end
450 end. 515 end.
451 (* end thide *) 516 (* end thide *)
452 517
453 (** [inster] begins by applying propositional simplification. Next, it checks if any chain length remains. If so, it tries all possible ways of instantiating quantified hypotheses with properly-typed local variables. It is critical to realize that, if the recursive call [inster n'] fails, then the [match goal] just seeks out another way of unifying its pattern against proof state. Thus, this small amount of code provides an elegant demonstration of how backtracking [match] enables exhaustive search. 518 (** The tactic begins by applying propositional simplification. Next, it checks if any chain length remains. If so, it tries all possible ways of instantiating quantified hypotheses with properly typed local variables. It is critical to realize that, if the recursive call [inster n'] fails, then the [match goal] just seeks out another way of unifying its pattern against proof state. Thus, this small amount of code provides an elegant demonstration of how backtracking [match] enables exhaustive search.
454 519
455 We can verify the efficacy of [inster] with two short examples. The built-in [firstorder] tactic (with no extra arguments) is able to prove the first but not the second. *) 520 We can verify the efficacy of [inster] with two short examples. The built-in [firstorder] tactic (with no extra arguments) is able to prove the first but not the second. *)
456 521
457 Section test_inster. 522 Section test_inster.
458 Variable A : Set. 523 Variable A : Set.
460 Variable f : A -> A. 525 Variable f : A -> A.
461 Variable g : A -> A -> A. 526 Variable g : A -> A -> A.
462 527
463 Hypothesis H1 : forall x y, P (g x y) -> Q (f x). 528 Hypothesis H1 : forall x y, P (g x y) -> Q (f x).
464 529
465 Theorem test_inster : forall x y, P (g x y) -> Q (f x). 530 Theorem test_inster : forall x, P (g x x) -> Q (f x).
466 inster 2. 531 inster 2.
467 Qed. 532 Qed.
468 533
469 Hypothesis H3 : forall u v, P u /\ P v /\ u <> v -> P (g u v). 534 Hypothesis H3 : forall u v, P u /\ P v /\ u <> v -> P (g u v).
470 Hypothesis H4 : forall u, Q (f u) -> P u /\ P (f u). 535 Hypothesis H4 : forall u, Q (f u) -> P u /\ P (f u).
472 Theorem test_inster2 : forall x y, x <> y -> P x -> Q (f y) -> Q (f x). 537 Theorem test_inster2 : forall x y, x <> y -> P x -> Q (f y) -> Q (f x).
473 inster 3. 538 inster 3.
474 Qed. 539 Qed.
475 End test_inster. 540 End test_inster.
476 541
477 (** The style employed in the definition of [inster] can seem very counterintuitive to functional programmers. Usually, functional programs accumulate state changes in explicit arguments to recursive functions. In Ltac, the state of the current subgoal is always implicit. Nonetheless, in contrast to general imperative programming, it is easy to undo any changes to this state, and indeed such %``%#"#undoing#"#%''% happens automatically at failures within [match]es. In this way, Ltac programming is similar to programming in Haskell with a stateful failure monad that supports a composition operator along the lines of the [first] tactical. 542 (** The style employed in the definition of [inster] can seem very counterintuitive to functional programmers. Usually, functional programs accumulate state changes in explicit arguments to recursive functions. In Ltac, the state of the current subgoal is always implicit. Nonetheless, in contrast to general imperative programming, it is easy to undo any changes to this state, and indeed such %``%#"#undoing#"#%''% happens automatically at failures within [match]es. In this way, Ltac programming is similar to programming in Haskell with a stateful failure monad that supports a composition operator along the lines of the [first] tactical. The key pieces of state include not only the form of the goal, but also decisions about the values of unification variables. These decisions are rolled back with all the other state after failure.
478 543
479 Functional programming purists may react indignantly to the suggestion of programming this way. Nonetheless, as with other kinds of %``%#"#monadic programming,#"#%''% many problems are much simpler to solve with Ltac than they would be with explicit, pure proof manipulation in ML or Haskell. To demonstrate, we will write a basic simplification procedure for logical implications. 544 Functional programming purists may react indignantly to the suggestion of programming this way. Nonetheless, as with other kinds of %``%#"#monadic programming,#"#%''% many problems are much simpler to solve with Ltac than they would be with explicit, pure proof manipulation in ML or Haskell. To demonstrate, we will write a basic simplification procedure for logical implications.
480 545
481 This procedure is inspired by one for separation logic, where conjuncts in formulas are thought of as %``%#"#resources,#"#%''% such that we lose no completeness by %``%#"#crossing out#"#%''% equal conjuncts on the two sides of an implication. This process is complicated by the fact that, for reasons of modularity, our formulas can have arbitrary nested tree structure (branching at conjunctions) and may include existential quantifiers. It is helpful for the matching process to %``%#"#go under#"#%''% quantifiers and in fact decide how to instantiate existential quantifiers in the conclusion. 546 This procedure is inspired by one for separation logic%~\cite{separation}%, where conjuncts in formulas are thought of as %``%#"#resources,#"#%''% such that we lose no completeness by %``%#"#crossing out#"#%''% equal conjuncts on the two sides of an implication. This process is complicated by the fact that, for reasons of modularity, our formulas can have arbitrary nested tree structure (branching at conjunctions) and may include existential quantifiers. It is helpful for the matching process to %``%#"#go under#"#%''% quantifiers and in fact decide how to instantiate existential quantifiers in the conclusion.
482 547
483 To distinguish the implications that our tactic handles from the implications that will show up as %``%#"#plumbing#"#%''% in various lemmas, we define a wrapper definition, a notation, and a tactic. *) 548 To distinguish the implications that our tactic handles from the implications that will show up as %``%#"#plumbing#"#%''% in various lemmas, we define a wrapper definition, a notation, and a tactic. *)
484 549
485 Definition imp (P1 P2 : Prop) := P1 -> P2. 550 Definition imp (P1 P2 : Prop) := P1 -> P2.
486 Infix "-->" := imp (no associativity, at level 95). 551 Infix "-->" := imp (no associativity, at level 95).
536 imp. 601 imp.
537 Qed. 602 Qed.
538 603
539 (** The first order of business in crafting our [matcher] tactic will be auxiliary support for searching through formula trees. The [search_prem] tactic implements running its tactic argument [tac] on every subformula of an [imp] premise. As it traverses a tree, [search_prem] applies some of the above lemmas to rewrite the goal to bring different subformulas to the head of the goal. That is, for every subformula [P] of the implication premise, we want [P] to %``%#"#have a turn,#"#%''% where the premise is rearranged into the form [P /\ Q] for some [Q]. The tactic [tac] should expect to see a goal in this form and focus its attention on the first conjunct of the premise. *) 604 (** The first order of business in crafting our [matcher] tactic will be auxiliary support for searching through formula trees. The [search_prem] tactic implements running its tactic argument [tac] on every subformula of an [imp] premise. As it traverses a tree, [search_prem] applies some of the above lemmas to rewrite the goal to bring different subformulas to the head of the goal. That is, for every subformula [P] of the implication premise, we want [P] to %``%#"#have a turn,#"#%''% where the premise is rearranged into the form [P /\ Q] for some [Q]. The tactic [tac] should expect to see a goal in this form and focus its attention on the first conjunct of the premise. *)
540 605
541 (* begin thide *)
542 Ltac search_prem tac := 606 Ltac search_prem tac :=
543 let rec search P := 607 let rec search P :=
544 tac 608 tac
545 || (apply and_True_prem; tac) 609 || (apply and_True_prem; tac)
546 || match P with 610 || match P with
552 | [ |- ?P /\ _ --> _ ] => search P 616 | [ |- ?P /\ _ --> _ ] => search P
553 | [ |- _ /\ ?P --> _ ] => apply comm_prem; search P 617 | [ |- _ /\ ?P --> _ ] => apply comm_prem; search P
554 | [ |- _ --> _ ] => progress (tac || (apply and_True_prem; tac)) 618 | [ |- _ --> _ ] => progress (tac || (apply and_True_prem; tac))
555 end. 619 end.
556 620
557 (** To understand how [search_prem] works, we turn first to the final [match]. If the premise begins with a conjunction, we call the [search] procedure on each of the conjuncts, or only the first conjunct, if that already yields a case where [tac] does not fail. [search P] expects and maintains the invariant that the premise is of the form [P /\ Q] for some [Q]. We pass [P] explicitly as a kind of decreasing induction measure, to avoid looping forever when [tac] always fails. The second [match] case calls a commutativity lemma to realize this invariant, before passing control to [search]. The final [match] case tries applying [tac] directly and then, if that fails, changes the form of the goal by adding an extraneous [True] conjunct and calls [tac] again. 621 (** To understand how [search_prem] works, we turn first to the final [match]. If the premise begins with a conjunction, we call the [search] procedure on each of the conjuncts, or only the first conjunct, if that already yields a case where [tac] does not fail. The call [search P] expects and maintains the invariant that the premise is of the form [P /\ Q] for some [Q]. We pass [P] explicitly as a kind of decreasing induction measure, to avoid looping forever when [tac] always fails. The second [match] case calls a commutativity lemma to realize this invariant, before passing control to [search]. The final [match] case tries applying [tac] directly and then, if that fails, changes the form of the goal by adding an extraneous [True] conjunct and calls [tac] again.
558 622
559 [search] itself tries the same tricks as in the last case of the final [match]. Additionally, if neither works, it checks if [P] is a conjunction. If so, it calls itself recursively on each conjunct, first applying associativity lemmas to maintain the goal-form invariant. 623 The [search] function itself tries the same tricks as in the last case of the final [match]. Additionally, if neither works, it checks if [P] is a conjunction. If so, it calls itself recursively on each conjunct, first applying associativity lemmas to maintain the goal-form invariant.
560 624
561 We will also want a dual function [search_conc], which does tree search through an [imp] conclusion. *) 625 We will also want a dual function [search_conc], which does tree search through an [imp] conclusion. *)
562 626
563 Ltac search_conc tac := 627 Ltac search_conc tac :=
564 let rec search P := 628 let rec search P :=
575 | [ |- _ --> _ ] => progress (tac || (apply and_True_conc; tac)) 639 | [ |- _ --> _ ] => progress (tac || (apply and_True_conc; tac))
576 end. 640 end.
577 641
578 (** Now we can prove a number of lemmas that are suitable for application by our search tactics. A lemma that is meant to handle a premise should have the form [P /\ Q --> R] for some interesting [P], and a lemma that is meant to handle a conclusion should have the form [P --> Q /\ R] for some interesting [Q]. *) 642 (** Now we can prove a number of lemmas that are suitable for application by our search tactics. A lemma that is meant to handle a premise should have the form [P /\ Q --> R] for some interesting [P], and a lemma that is meant to handle a conclusion should have the form [P --> Q /\ R] for some interesting [Q]. *)
579 643
644 (* begin thide *)
580 Theorem False_prem : forall P Q, 645 Theorem False_prem : forall P Q,
581 False /\ P --> Q. 646 False /\ P --> Q.
582 imp. 647 imp.
583 Qed. 648 Qed.
584 649
650 ============================ 715 ============================
651 True --> R 716 True --> R
652 717
653 ]] 718 ]]
654 719
655 [matcher] canceled those conjuncts that it was able to cancel, leaving a simplified subgoal for us, much as [intuition] does. *) 720 Our tactic canceled those conjuncts that it was able to cancel, leaving a simplified subgoal for us, much as [intuition] does. *)
656 721
657 Abort. 722 Abort.
658 723
659 (** [matcher] even succeeds at guessing quantifier instantiations. It is the unification that occurs in uses of the [Match] lemma that does the real work here. *) 724 (** The [matcher] tactic even succeeds at guessing quantifier instantiations. It is the unification that occurs in uses of the [Match] lemma that does the real work here. *)
660 725
661 Theorem t4 : forall (P : nat -> Prop) Q, (exists x, P x /\ Q) --> Q /\ (exists x, P x). 726 Theorem t4 : forall (P : nat -> Prop) Q, (exists x, P x /\ Q) --> Q /\ (exists x, P x).
662 matcher. 727 matcher.
663 Qed. 728 Qed.
664 729
682 747
683 (** * Creating Unification Variables *) 748 (** * Creating Unification Variables *)
684 749
685 (** A final useful ingredient in tactic crafting is the ability to allocate new unification variables explicitly. Tactics like [eauto] introduce unification variable internally to support flexible proof search. While [eauto] and its relatives do %\textit{%#<i>#backward#</i>#%}% reasoning, we often want to do similar %\textit{%#<i>#forward#</i>#%}% reasoning, where unification variables can be useful for similar reasons. 750 (** A final useful ingredient in tactic crafting is the ability to allocate new unification variables explicitly. Tactics like [eauto] introduce unification variable internally to support flexible proof search. While [eauto] and its relatives do %\textit{%#<i>#backward#</i>#%}% reasoning, we often want to do similar %\textit{%#<i>#forward#</i>#%}% reasoning, where unification variables can be useful for similar reasons.
686 751
687 For example, we can write a tactic that instantiates the quantifiers of a universally-quantified hypothesis. The tactic should not need to know what the appropriate instantiantiations are; rather, we want these choices filled with placeholders. We hope that, when we apply the specialized hypothesis later, syntactic unification will determine concrete values. 752 For example, we can write a tactic that instantiates the quantifiers of a universally quantified hypothesis. The tactic should not need to know what the appropriate instantiantiations are; rather, we want these choices filled with placeholders. We hope that, when we apply the specialized hypothesis later, syntactic unification will determine concrete values.
688 753
689 Before we are ready to write a tactic, we can try out its ingredients one at a time. *) 754 Before we are ready to write a tactic, we can try out its ingredients one at a time. *)
690 755
691 Theorem t5 : (forall x : nat, S x > x) -> 2 > 1. 756 Theorem t5 : (forall x : nat, S x > x) -> 2 > 1.
692 intros. 757 intros.
696 ============================ 761 ============================
697 2 > 1 762 2 > 1
698 763
699 ]] 764 ]]
700 765
701 To instantiate [H] generically, we first need to name the value to be used for [x]. *) 766 To instantiate [H] generically, we first need to name the value to be used for [x].%\index{tactics!evar}% *)
702 767
703 evar (y : nat). 768 evar (y : nat).
704 769
705 (** [[ 770 (** [[
706 H : forall x : nat, S x > x 771 H : forall x : nat, S x > x
708 ============================ 773 ============================
709 2 > 1 774 2 > 1
710 775
711 ]] 776 ]]
712 777
713 The proof context is extended with a new variable [y], which has been assigned to be equal to a fresh unification variable [?279]. We want to instantiate [H] with [?279]. To get ahold of the new unification variable, rather than just its alias [y], we perform a trivial call-by-value reduction in the expression [y]. In particular, we only request the use of one reduction rule, [delta], which deals with definition unfolding. We pass a flag further stipulating that only the definition of [y] be unfolded. This is a simple trick for getting at the value of a synonym variable. *) 778 The proof context is extended with a new variable [y], which has been assigned to be equal to a fresh unification variable [?279]. We want to instantiate [H] with [?279]. To get ahold of the new unification variable, rather than just its alias [y], we perform a trivial unfolding in the expression [y], using the %\index{tactics!eval}%[eval] Ltac construct, which works with the same reduction strategies that we have seen in tactics (e.g., [simpl], [compute], etc.). *)
714 779
715 let y' := eval cbv delta [y] in y in 780 let y' := eval unfold y in y in
716 clear y; generalize (H y'). 781 clear y; generalize (H y').
717 782
718 (** [[ 783 (** [[
719 H : forall x : nat, S x > x 784 H : forall x : nat, S x > x
720 ============================ 785 ============================
743 Ltac insterU H := 808 Ltac insterU H :=
744 repeat match type of H with 809 repeat match type of H with
745 | forall x : ?T, _ => 810 | forall x : ?T, _ =>
746 let x := fresh "x" in 811 let x := fresh "x" in
747 evar (x : T); 812 evar (x : T);
748 let x' := eval cbv delta [x] in x in 813 let x' := eval unfold x in x in
749 clear x; generalize (H x'); clear H; intro H 814 clear x; specialize (H x')
750 end. 815 end.
751 816
752 Theorem t5' : (forall x : nat, S x > x) -> 2 > 1. 817 Theorem t5' : (forall x : nat, S x > x) -> 2 > 1.
753 intro H; insterU H; apply H. 818 intro H; insterU H; apply H.
754 Qed. 819 Qed.
755 820
756 (** This particular example is somewhat silly, since [apply] by itself would have solved the goal originally. Separate forward reasoning is more useful on hypotheses that end in existential quantifications. Before we go through an example, it is useful to define a variant of [insterU] that does not clear the base hypothesis we pass to it. *) 821 (** This particular example is somewhat silly, since [apply] by itself would have solved the goal originally. Separate forward reasoning is more useful on hypotheses that end in existential quantifications. Before we go through an example, it is useful to define a variant of [insterU] that does not clear the base hypothesis we pass to it. We use the Ltac construct %\index{tactics!fresh}%[fresh] to generate a hypothesis name that is not already used, based on a string suggesting a good name. *)
757 822
758 Ltac insterKeep H := 823 Ltac insterKeep H :=
759 let H' := fresh "H'" in 824 let H' := fresh "H'" in
760 generalize H; intro H'; insterU H'. 825 generalize H; intro H'; insterU H'.
761 826
772 -> P (f v1 v2) (g u1 u2). 837 -> P (f v1 v2) (g u1 u2).
773 838
774 Theorem t6 : forall v1 v2, exists u1, exists u2, P (f v1 v2) (g u1 u2). 839 Theorem t6 : forall v1 v2, exists u1, exists u2, P (f v1 v2) (g u1 u2).
775 intros. 840 intros.
776 841
777 (** Neither [eauto] nor [firstorder] is clever enough to prove this goal. We can help out by doing some of the work with quantifiers ourselves. *) 842 (** Neither [eauto] nor [firstorder] is clever enough to prove this goal. We can help out by doing some of the work with quantifiers ourselves, abbreviating the proof with the %\index{tactics!do}%[do] tactical for repetition of a tactic a set number of times. *)
778 843
779 do 2 insterKeep H1. 844 do 2 insterKeep H1.
780 845
781 (** Our proof state is extended with two generic instances of [H1]. 846 (** Our proof state is extended with two generic instances of [H1].
782 847
786 ============================ 851 ============================
787 exists u1 : B, exists u2 : B, P (f v1 v2) (g u1 u2) 852 exists u1 : B, exists u2 : B, P (f v1 v2) (g u1 u2)
788 853
789 ]] 854 ]]
790 855
791 [eauto] still cannot prove the goal, so we eliminate the two new existential quantifiers. *) 856 [eauto] still cannot prove the goal, so we eliminate the two new existential quantifiers. (Recall that [ex] is the underlying type family to which uses of the [exists] syntax are compiled.) *)
792 857
793 repeat match goal with 858 repeat match goal with
794 | [ H : ex _ |- _ ] => destruct H 859 | [ H : ex _ |- _ ] => destruct H
795 end. 860 end.
796 861
821 | [ H : ex _ |- _ ] => destruct H 886 | [ H : ex _ |- _ ] => destruct H
822 end; eauto. 887 end; eauto.
823 888
824 (** This proof script does not hit any errors until the very end, when an error message like this one is displayed. 889 (** This proof script does not hit any errors until the very end, when an error message like this one is displayed.
825 890
826 [[ 891 <<
827 No more subgoals but non-instantiated existential variables : 892 No more subgoals but non-instantiated existential variables :
828 Existential 1 = 893 Existential 1 =
894 >>
895 [[
829 ?4384 : [A : Type 896 ?4384 : [A : Type
830 B : Type 897 B : Type
831 Q : A -> Prop 898 Q : A -> Prop
832 P : A -> B -> Prop 899 P : A -> B -> Prop
833 f : A -> A -> A 900 f : A -> A -> A
848 The error message shows that [?4384] is meant to be a proof of [Q v2] in a particular proof state, whose variables and hypotheses are displayed. It turns out that [?4384] was created by [insterU], as the value of a proof to pass to [H1]. Recall that, in Gallina, implication is just a degenerate case of [forall] quantification, so the [insterU] code to match against [forall] also matched the implication. Since any proof of [Q v2] is as good as any other in this context, there was never any opportunity to use unification to determine exactly which proof is appropriate. We expect similar problems with any implications in arguments to [insterU]. *) 915 The error message shows that [?4384] is meant to be a proof of [Q v2] in a particular proof state, whose variables and hypotheses are displayed. It turns out that [?4384] was created by [insterU], as the value of a proof to pass to [H1]. Recall that, in Gallina, implication is just a degenerate case of [forall] quantification, so the [insterU] code to match against [forall] also matched the implication. Since any proof of [Q v2] is as good as any other in this context, there was never any opportunity to use unification to determine exactly which proof is appropriate. We expect similar problems with any implications in arguments to [insterU]. *)
849 916
850 Abort. 917 Abort.
851 End t7. 918 End t7.
852 919
920 (* begin hide *)
853 Reset insterU. 921 Reset insterU.
854 922 (* end hide *)
855 (** We can redefine [insterU] to treat implications differently. In particular, we pattern-match on the type of the type [T] in [forall x : ?T, ...]. If [T] has type [Prop], then [x]'s instantiation should be thought of as a proof. Thus, instead of picking a new unification variable for it, we instead apply a user-supplied tactic [tac]. It is important that we end this special [Prop] case with [|| fail 1], so that, if [tac] fails to prove [T], we abort the instantiation, rather than continuing on to the default quantifier handling. *) 923 (** %\noindent\coqdockw{%#<tt>#Reset#</tt>#%}% [insterU.] *)
924
925 (** We can redefine [insterU] to treat implications differently. In particular, we pattern-match on the type of the type [T] in [forall x : ?T, ...]. If [T] has type [Prop], then [x]'s instantiation should be thought of as a proof. Thus, instead of picking a new unification variable for it, we instead apply a user-supplied tactic [tac]. It is important that we end this special [Prop] case with [|| fail 1], so that, if [tac] fails to prove [T], we abort the instantiation, rather than continuing on to the default quantifier handling. Also recall that the tactic form %\index{tactics!solve}%[solve [ t ]] fails if [t] does not completely solve the goal. *)
856 926
857 Ltac insterU tac H := 927 Ltac insterU tac H :=
858 repeat match type of H with 928 repeat match type of H with
859 | forall x : ?T, _ => 929 | forall x : ?T, _ =>
860 match type of T with 930 match type of T with
861 | Prop => 931 | Prop =>
862 (let H' := fresh "H'" in 932 (let H' := fresh "H'" in
863 assert (H' : T); [ 933 assert (H' : T) by solve [ tac ];
864 solve [ tac ] 934 specialize (H H'); clear H')
865 | generalize (H H'); clear H H'; intro H ])
866 || fail 1 935 || fail 1
867 | _ => 936 | _ =>
868 let x := fresh "x" in 937 let x := fresh "x" in
869 evar (x : T); 938 evar (x : T);
870 let x' := eval cbv delta [x] in x in 939 let x' := eval unfold x in x in
871 clear x; generalize (H x'); clear H; intro H 940 clear x; specialize (H x')
872 end 941 end
873 end. 942 end.
874 943
875 Ltac insterKeep tac H := 944 Ltac insterKeep tac H :=
876 let H' := fresh "H'" in 945 let H' := fresh "H'" in
912 econstructor; instantiate (1 := (3, 2)); reflexivity. 981 econstructor; instantiate (1 := (3, 2)); reflexivity.
913 Qed. 982 Qed.
914 983
915 (** The [1] above is identifying an existential variable appearing in the current goal, with the last existential appearing assigned number 1, the second last assigned number 2, and so on. The named existential is replaced everywhere by the term to the right of the [:=]. 984 (** The [1] above is identifying an existential variable appearing in the current goal, with the last existential appearing assigned number 1, the second last assigned number 2, and so on. The named existential is replaced everywhere by the term to the right of the [:=].
916 985
917 The [instantiate] tactic can be convenient for exploratory proving, but it leads to very brittle proof scripts that are unlikely to adapt to changing theorem statements. It is often more helpful to have a tactic that can be used to assign a value to a term that is known to be an existential. By employing a roundabout implementation technique, we can build a tactic that generalizes this functionality. In particular, our tactic [equate] will assert that two terms are equal. If one of the terms happens to be an existential, then it will be replaced everywhere with the other term. *) 986 The %\index{tactics!instantiate}%[instantiate] tactic can be convenient for exploratory proving, but it leads to very brittle proof scripts that are unlikely to adapt to changing theorem statements. It is often more helpful to have a tactic that can be used to assign a value to a term that is known to be an existential. By employing a roundabout implementation technique, we can build a tactic that generalizes this functionality. In particular, our tactic [equate] will assert that two terms are equal. If one of the terms happens to be an existential, then it will be replaced everywhere with the other term. *)
918 987
919 Ltac equate x y := 988 Ltac equate x y :=
920 let H := fresh "H" in 989 let H := fresh "H" in
921 assert (H : x = y); [ reflexivity | clear H ]. 990 assert (H : x = y) by reflexivity; clear H.
922 991
923 (** [equate] fails if it is not possible to prove [x = y] by [reflexivity]. We perform the proof only for its unification side effects, clearing the fact [x = y] afterward. With [equate], we can build a less brittle version of the prior example. *) 992 (** This tactic fails if it is not possible to prove [x = y] by [reflexivity]. We perform the proof only for its unification side effects, clearing the fact [x = y] afterward. With [equate], we can build a less brittle version of the prior example. *)
924 993
925 Theorem t9 : exists p : nat * nat, fst p = 3. 994 Theorem t9 : exists p : nat * nat, fst p = 3.
926 econstructor; match goal with 995 econstructor; match goal with
927 | [ |- fst ?x = 3 ] => equate x (3, 2) 996 | [ |- fst ?x = 3 ] => equate x (3, 2)
928 end; reflexivity. 997 end; reflexivity.