annotate src/Match.v @ 309:8cb9e31f86e7

Front page tweaks
author Adam Chlipala <adam@chlipala.net>
date Thu, 25 Aug 2011 15:22:20 -0400
parents 7b38729be069
children d5787b70cf48
rev   line source
adam@297 1 (* Copyright (c) 2008-2011, Adam Chlipala
adamc@132 2 *
adamc@132 3 * This work is licensed under a
adamc@132 4 * Creative Commons Attribution-Noncommercial-No Derivative Works 3.0
adamc@132 5 * Unported License.
adamc@132 6 * The license text is available at:
adamc@132 7 * http://creativecommons.org/licenses/by-nc-nd/3.0/
adamc@132 8 *)
adamc@132 9
adamc@132 10 (* begin hide *)
adamc@132 11 Require Import List.
adamc@132 12
adamc@132 13 Require Import Tactics.
adamc@132 14
adamc@132 15 Set Implicit Arguments.
adamc@132 16 (* end hide *)
adamc@132 17
adamc@132 18
adamc@132 19 (** %\part{Proof Engineering}
adamc@132 20
adamc@132 21 \chapter{Proof Search in Ltac}% *)
adamc@132 22
adamc@132 23 (** 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. *)
adamc@132 24
adamc@132 25 (** * Some Built-In Automation Tactics *)
adamc@132 26
adamc@132 27 (** 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.
adamc@132 28
adamc@132 29 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.
adamc@132 30
adam@288 31 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.#"#%''% *)
adamc@132 32
adamc@132 33
adamc@133 34 (** * Hint Databases *)
adamc@132 35
adam@288 36 (** Another class of built-in tactics includes [auto], [eauto], and [autorewrite]. These are based on %\textit{%#<i>#hint databases#</i>#%}%, which we have seen extended in many examples so far. These tactics are important, because, in Ltac programming, we cannot create %``%#"#global variables#"#%''% whose values can be extended seamlessly by different modules in different source files. We have seen the advantages of hints so far, where [crush] can be defined once and for all, while still automatically applying the hints we add throughout developments.
adamc@133 37
adamc@220 38 The basic hints for [auto] and [eauto] are [Hint Immediate lemma], asking to try solving a goal immediately by applying a lemma and discharging any hypotheses with a single proof step each; [Resolve lemma], which does the same but may add new premises that are themselves to be subjects of nested proof search; [Constructor type], which acts like [Resolve] applied to every constructor of an inductive type; and [Unfold ident], which tries unfolding [ident] when it appears at the head of a proof goal. Each of these [Hint] commands may be used with a suffix, as in [Hint Resolve lemma : my_db]. This adds the hint only to the specified database, so that it would only be used by, for instance, [auto with my_db]. An additional argument to [auto] specifies the maximum depth of proof trees to search in depth-first order, as in [auto 8] or [auto 8 with my_db]. The default depth is 5.
adamc@133 39
adamc@133 40 All of these [Hint] commands can be issued alternatively with a more primitive hint kind, [Extern]. A few examples should do best to explain how [Hint Extern] works. *)
adamc@133 41
adamc@133 42 Theorem bool_neq : true <> false.
adamc@141 43 (* begin thide *)
adamc@133 44 auto.
adamc@220 45
adamc@133 46 (** [crush] would have discharged this goal, but the default hint database for [auto] contains no hint that applies. *)
adamc@220 47
adamc@133 48 Abort.
adamc@133 49
adamc@133 50 (** It is hard to come up with a [bool]-specific hint that is not just a restatement of the theorem we mean to prove. Luckily, a simpler form suffices. *)
adamc@133 51
adamc@133 52 Hint Extern 1 (_ <> _) => congruence.
adamc@133 53
adamc@133 54 Theorem bool_neq : true <> false.
adamc@133 55 auto.
adamc@133 56 Qed.
adamc@141 57 (* end thide *)
adamc@133 58
adam@288 59 (** Our hint says: %``%#"#whenever the conclusion matches the pattern [_ <> _], try applying [congruence].#"#%''% The [1] is a cost for this rule. During proof search, whenever multiple rules apply, rules are tried in increasing cost order, so it pays to assign high costs to relatively expensive [Extern] hints.
adamc@133 60
adamc@133 61 [Extern] hints may be implemented with the full Ltac language. This example shows a case where a hint uses a [match]. *)
adamc@133 62
adamc@133 63 Section forall_and.
adamc@133 64 Variable A : Set.
adamc@133 65 Variables P Q : A -> Prop.
adamc@133 66
adamc@133 67 Hypothesis both : forall x, P x /\ Q x.
adamc@133 68
adamc@133 69 Theorem forall_and : forall z, P z.
adamc@141 70 (* begin thide *)
adamc@133 71 crush.
adamc@220 72
adamc@133 73 (** [crush] makes no progress beyond what [intros] would have accomplished. [auto] will not apply the hypothesis [both] to prove the goal, because the conclusion of [both] does not unify with the conclusion of the goal. However, we can teach [auto] to handle this kind of goal. *)
adamc@133 74
adamc@133 75 Hint Extern 1 (P ?X) =>
adamc@133 76 match goal with
adamc@133 77 | [ H : forall x, P x /\ _ |- _ ] => apply (proj1 (H X))
adamc@133 78 end.
adamc@133 79
adamc@133 80 auto.
adamc@133 81 Qed.
adamc@141 82 (* end thide *)
adamc@133 83
adamc@133 84 (** We see that an [Extern] pattern may bind unification variables that we use in the associated tactic. [proj1] is a function from the standard library for extracting a proof of [R] from a proof of [R /\ S]. *)
adamc@220 85
adamc@133 86 End forall_and.
adamc@133 87
adamc@133 88 (** After our success on this example, we might get more ambitious and seek to generalize the hint to all possible predicates [P].
adamc@133 89
adamc@133 90 [[
adamc@133 91 Hint Extern 1 (?P ?X) =>
adamc@133 92 match goal with
adamc@220 93 | [ H : forall x, P x /\ _ |- _ ] => apply (proj1 (H X))
adamc@133 94 end.
adamc@133 95
adamc@133 96 User error: Bound head variable
adamc@220 97
adamc@134 98 ]]
adamc@133 99
adamc@134 100 Coq's [auto] hint databases work as tables mapping %\textit{%#<i>#head symbols#</i>#%}% to lists of tactics to try. Because of this, the constant head of an [Extern] pattern must be determinable statically. In our first [Extern] hint, the head symbol was [not], since [x <> y] desugars to [not (eq x y)]; and, in the second example, the head symbol was [P].
adamc@133 101
adamc@134 102 This restriction on [Extern] hints is the main limitation of the [auto] mechanism, preventing us from using it for general context simplifications that are not keyed off of the form of the conclusion. This is perhaps just as well, since we can often code more efficient tactics with specialized Ltac programs, and we will see how in later sections of the chapter.
adamc@134 103
adamc@134 104 We have used [Hint Rewrite] in many examples so far. [crush] uses these hints by calling [autorewrite]. Our rewrite hints have taken the form [Hint Rewrite lemma : cpdt], adding them to the [cpdt] rewrite database. This is because, in contrast to [auto], [autorewrite] has no default database. Thus, we set the convention that [crush] uses the [cpdt] database.
adamc@134 105
adamc@134 106 This example shows a direct use of [autorewrite]. *)
adamc@134 107
adamc@134 108 Section autorewrite.
adamc@134 109 Variable A : Set.
adamc@134 110 Variable f : A -> A.
adamc@134 111
adamc@134 112 Hypothesis f_f : forall x, f (f x) = f x.
adamc@134 113
adamc@134 114 Hint Rewrite f_f : my_db.
adamc@134 115
adamc@134 116 Lemma f_f_f : forall x, f (f (f x)) = f x.
adamc@134 117 intros; autorewrite with my_db; reflexivity.
adamc@134 118 Qed.
adamc@134 119
adam@288 120 (** There are a few ways in which [autorewrite] can lead to trouble when insufficient care is taken in choosing hints. First, the set of hints may define a nonterminating rewrite system, in which case invocations to [autorewrite] may not terminate. Second, we may add hints that %``%#"#lead [autorewrite] down the wrong path.#"#%''% For instance: *)
adamc@134 121
adamc@134 122 Section garden_path.
adamc@134 123 Variable g : A -> A.
adamc@134 124 Hypothesis f_g : forall x, f x = g x.
adamc@134 125 Hint Rewrite f_g : my_db.
adamc@134 126
adamc@134 127 Lemma f_f_f' : forall x, f (f (f x)) = f x.
adamc@134 128 intros; autorewrite with my_db.
adamc@134 129 (** [[
adamc@134 130 ============================
adamc@134 131 g (g (g x)) = g x
adam@302 132 ]]
adam@302 133 *)
adamc@220 134
adamc@134 135 Abort.
adamc@134 136
adam@288 137 (** Our new hint was used to rewrite the goal into a form where the old hint could no longer be applied. This %``%#"#non-monotonicity#"#%''% of rewrite hints contrasts with the situation for [auto], where new hints may slow down proof search but can never %``%#"#break#"#%''% old proofs. The key difference is that [auto] either solves a goal or makes no changes to it, while [autorewrite] may change goals without solving them. The situation for [eauto] is slightly more complicated, as changes to hint databases may change the proof found for a particular goal, and that proof may influence the settings of unification variables that appear elsewhere in the proof state. *)
adamc@134 138
adamc@134 139 Reset garden_path.
adamc@134 140
adam@288 141 (** [autorewrite] also works with quantified equalities that include additional premises, but we must be careful to avoid similar incorrect rewritings. *)
adamc@134 142
adamc@134 143 Section garden_path.
adamc@134 144 Variable P : A -> Prop.
adamc@134 145 Variable g : A -> A.
adamc@134 146 Hypothesis f_g : forall x, P x -> f x = g x.
adamc@134 147 Hint Rewrite f_g : my_db.
adamc@134 148
adamc@134 149 Lemma f_f_f' : forall x, f (f (f x)) = f x.
adamc@134 150 intros; autorewrite with my_db.
adamc@134 151 (** [[
adamc@134 152
adamc@134 153 ============================
adamc@134 154 g (g (g x)) = g x
adamc@134 155
adamc@134 156 subgoal 2 is:
adamc@134 157 P x
adamc@134 158 subgoal 3 is:
adamc@134 159 P (f x)
adamc@134 160 subgoal 4 is:
adamc@134 161 P (f x)
adam@302 162 ]]
adam@302 163 *)
adamc@220 164
adamc@134 165 Abort.
adamc@134 166
adamc@134 167 (** The inappropriate rule fired the same three times as before, even though we know we will not be able to prove the premises. *)
adamc@134 168
adamc@134 169 Reset garden_path.
adamc@134 170
adam@288 171 (** Our final, successful, attempt uses an extra argument to [Hint Rewrite] that specifies a tactic to apply to generated premises. Such a hint is only used when the tactic succeeds for all premises, possibly leaving further subgoals for some premises. *)
adamc@134 172
adamc@134 173 Section garden_path.
adamc@134 174 Variable P : A -> Prop.
adamc@134 175 Variable g : A -> A.
adamc@134 176 Hypothesis f_g : forall x, P x -> f x = g x.
adamc@141 177 (* begin thide *)
adamc@134 178 Hint Rewrite f_g using assumption : my_db.
adamc@141 179 (* end thide *)
adamc@134 180
adamc@134 181 Lemma f_f_f' : forall x, f (f (f x)) = f x.
adamc@141 182 (* begin thide *)
adamc@134 183 intros; autorewrite with my_db; reflexivity.
adamc@134 184 Qed.
adamc@141 185 (* end thide *)
adamc@134 186
adamc@134 187 (** [autorewrite] will still use [f_g] when the generated premise is among our assumptions. *)
adamc@134 188
adamc@134 189 Lemma f_f_f_g : forall x, P x -> f (f x) = g x.
adamc@141 190 (* begin thide *)
adamc@134 191 intros; autorewrite with my_db; reflexivity.
adamc@141 192 (* end thide *)
adamc@134 193 Qed.
adamc@134 194 End garden_path.
adamc@134 195
adamc@220 196 (** remove printing * *)
adamc@220 197
adamc@134 198 (** It can also be useful to use the [autorewrite with db in *] form, which does rewriting in hypotheses, as well as in the conclusion. *)
adamc@134 199
adamc@220 200 (** printing * $*$ *)
adamc@220 201
adamc@134 202 Lemma in_star : forall x y, f (f (f (f x))) = f (f y)
adamc@134 203 -> f x = f (f (f y)).
adamc@141 204 (* begin thide *)
adamc@134 205 intros; autorewrite with my_db in *; assumption.
adamc@141 206 (* end thide *)
adamc@134 207 Qed.
adamc@134 208
adamc@134 209 End autorewrite.
adamc@135 210
adamc@135 211
adamc@135 212 (** * Ltac Programming Basics *)
adamc@135 213
adamc@135 214 (** 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.
adamc@135 215
adamc@135 216 One common use for [match] tactics is identification of subjects for case analysis, as we see in this tactic definition. *)
adamc@135 217
adamc@141 218 (* begin thide *)
adamc@135 219 Ltac find_if :=
adamc@135 220 match goal with
adamc@135 221 | [ |- if ?X then _ else _ ] => destruct X
adamc@135 222 end.
adamc@141 223 (* end thide *)
adamc@135 224
adamc@135 225 (** The tactic checks if the conclusion is an [if], [destruct]ing the test expression if so. Certain classes of theorem are trivial to prove automatically with such a tactic. *)
adamc@135 226
adamc@135 227 Theorem hmm : forall (a b c : bool),
adamc@135 228 if a
adamc@135 229 then if b
adamc@135 230 then True
adamc@135 231 else True
adamc@135 232 else if c
adamc@135 233 then True
adamc@135 234 else True.
adamc@141 235 (* begin thide *)
adamc@135 236 intros; repeat find_if; constructor.
adamc@135 237 Qed.
adamc@141 238 (* end thide *)
adamc@135 239
adamc@135 240 (** 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.
adamc@135 241
adamc@135 242 Another very useful Ltac building block is %\textit{%#<i>#context patterns#</i>#%}%. *)
adamc@135 243
adamc@141 244 (* begin thide *)
adamc@135 245 Ltac find_if_inside :=
adamc@135 246 match goal with
adamc@135 247 | [ |- context[if ?X then _ else _] ] => destruct X
adamc@135 248 end.
adamc@141 249 (* end thide *)
adamc@135 250
adamc@135 251 (** The behavior of this tactic is to find any subterm of the conclusion that is an [if] and then [destruct] the test expression. This version subsumes [find_if]. *)
adamc@135 252
adamc@135 253 Theorem hmm' : forall (a b c : bool),
adamc@135 254 if a
adamc@135 255 then if b
adamc@135 256 then True
adamc@135 257 else True
adamc@135 258 else if c
adamc@135 259 then True
adamc@135 260 else True.
adamc@141 261 (* begin thide *)
adamc@135 262 intros; repeat find_if_inside; constructor.
adamc@135 263 Qed.
adamc@141 264 (* end thide *)
adamc@135 265
adamc@135 266 (** We can also use [find_if_inside] to prove goals that [find_if] does not simplify sufficiently. *)
adamc@135 267
adamc@141 268 Theorem hmm2 : forall (a b : bool),
adamc@135 269 (if a then 42 else 42) = (if b then 42 else 42).
adamc@141 270 (* begin thide *)
adamc@135 271 intros; repeat find_if_inside; reflexivity.
adamc@135 272 Qed.
adamc@141 273 (* end thide *)
adamc@135 274
adam@288 275 (** Many decision procedures can be coded in Ltac via %``%#"#[repeat match] loops.#"#%''% For instance, we can implement a subset of the functionality of [tauto]. *)
adamc@135 276
adamc@141 277 (* begin thide *)
adamc@135 278 Ltac my_tauto :=
adamc@135 279 repeat match goal with
adamc@135 280 | [ H : ?P |- ?P ] => exact H
adamc@135 281
adamc@135 282 | [ |- True ] => constructor
adamc@135 283 | [ |- _ /\ _ ] => constructor
adamc@135 284 | [ |- _ -> _ ] => intro
adamc@135 285
adamc@135 286 | [ H : False |- _ ] => destruct H
adamc@135 287 | [ H : _ /\ _ |- _ ] => destruct H
adamc@135 288 | [ H : _ \/ _ |- _ ] => destruct H
adamc@135 289
adamc@135 290 | [ H1 : ?P -> ?Q, H2 : ?P |- _ ] =>
adamc@135 291 let H := fresh "H" in
adamc@135 292 generalize (H1 H2); clear H1; intro H
adamc@135 293 end.
adamc@141 294 (* end thide *)
adamc@135 295
adamc@135 296 (** 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.
adamc@135 297
adam@288 298 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].
adamc@135 299
adamc@135 300 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]. *)
adamc@135 301
adamc@135 302 Section propositional.
adamc@135 303 Variables P Q R : Prop.
adamc@135 304
adamc@138 305 Theorem propositional : (P \/ Q \/ False) /\ (P -> Q) -> True /\ Q.
adamc@141 306 (* begin thide *)
adamc@135 307 my_tauto.
adamc@135 308 Qed.
adamc@141 309 (* end thide *)
adamc@135 310 End propositional.
adamc@135 311
adamc@135 312 (** 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].
adamc@135 313
adamc@135 314 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.
adamc@135 315
adamc@135 316 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.
adamc@135 317
adamc@135 318 For instance, this (unnecessarily verbose) proof script works: *)
adamc@135 319
adamc@135 320 Theorem m1 : True.
adamc@135 321 match goal with
adamc@135 322 | [ |- _ ] => intro
adamc@135 323 | [ |- True ] => constructor
adamc@135 324 end.
adamc@141 325 (* begin thide *)
adamc@135 326 Qed.
adamc@141 327 (* end thide *)
adamc@135 328
adamc@135 329 (** The first case matches trivially, but its body tactic fails, since the conclusion does not begin with a quantifier or implication. In a similar ML match, that would mean that the whole pattern-match fails. In Coq, we backtrack and try the next pattern, which also matches. Its body tactic succeeds, so the overall tactic succeeds as well.
adamc@135 330
adamc@135 331 The example shows how failure can move to a different pattern within a [match]. Failure can also trigger an attempt to find %\textit{%#<i>#a different way of matching a single pattern#</i>#%}%. Consider another example: *)
adamc@135 332
adamc@135 333 Theorem m2 : forall P Q R : Prop, P -> Q -> R -> Q.
adamc@135 334 intros; match goal with
adamc@220 335 | [ H : _ |- _ ] => idtac H
adamc@135 336 end.
adamc@135 337
adam@288 338 (** 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: *)
adamc@135 339
adamc@141 340 (* begin thide *)
adamc@135 341 match goal with
adamc@135 342 | [ H : _ |- _ ] => exact H
adamc@135 343 end.
adamc@135 344 Qed.
adamc@141 345 (* end thide *)
adamc@135 346
adamc@135 347 (** The tactic first unifies [H] with [H1], as before, but [exact H] fails in that case, so the tactic engine searches for more possible values of [H]. Eventually, it arrives at the correct value, so that [exact H] and the overall tactic succeed. *)
adamc@135 348
adamc@135 349 (** Now we are equipped to implement a tactic for checking that a proposition is not among our hypotheses: *)
adamc@135 350
adamc@141 351 (* begin thide *)
adamc@135 352 Ltac notHyp P :=
adamc@135 353 match goal with
adamc@135 354 | [ _ : P |- _ ] => fail 1
adamc@135 355 | _ =>
adamc@135 356 match P with
adamc@135 357 | ?P1 /\ ?P2 => first [ notHyp P1 | notHyp P2 | fail 2 ]
adamc@135 358 | _ => idtac
adamc@135 359 end
adamc@135 360 end.
adamc@141 361 (* end thide *)
adamc@135 362
adam@288 363 (** 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.
adamc@135 364
adamc@135 365 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.
adamc@135 366
adamc@135 367 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.
adamc@135 368
adamc@135 369 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. *)
adamc@135 370
adamc@141 371 (* begin thide *)
adamc@135 372 Ltac extend pf :=
adamc@135 373 let t := type of pf in
adamc@135 374 notHyp t; generalize pf; intro.
adamc@141 375 (* end thide *)
adamc@135 376
adamc@135 377 (** 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].
adamc@135 378
adamc@135 379 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. *)
adamc@135 380
adamc@141 381 (* begin thide *)
adamc@135 382 Ltac completer :=
adamc@135 383 repeat match goal with
adamc@135 384 | [ |- _ /\ _ ] => constructor
adamc@135 385 | [ H : _ /\ _ |- _ ] => destruct H
adamc@135 386 | [ H : ?P -> ?Q, H' : ?P |- _ ] =>
adamc@135 387 generalize (H H'); clear H; intro H
adamc@135 388 | [ |- forall x, _ ] => intro
adamc@135 389
adamc@135 390 | [ H : forall x, ?P x -> _, H' : ?P ?X |- _ ] =>
adamc@135 391 extend (H X H')
adamc@135 392 end.
adamc@141 393 (* end thide *)
adamc@135 394
adamc@135 395 (** 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.
adamc@135 396
adamc@135 397 In the fifth rule, when we find a [forall] fact [H] with a premise matching one of our hypotheses, we add the appropriate instantiation of [H]'s conclusion, if we have not already added it.
adamc@135 398
adamc@135 399 We can check that [completer] is working properly: *)
adamc@135 400
adamc@135 401 Section firstorder.
adamc@135 402 Variable A : Set.
adamc@135 403 Variables P Q R S : A -> Prop.
adamc@135 404
adamc@135 405 Hypothesis H1 : forall x, P x -> Q x /\ R x.
adamc@135 406 Hypothesis H2 : forall x, R x -> S x.
adamc@135 407
adamc@135 408 Theorem fo : forall x, P x -> S x.
adamc@141 409 (* begin thide *)
adamc@135 410 completer.
adamc@135 411 (** [[
adamc@135 412 x : A
adamc@135 413 H : P x
adamc@135 414 H0 : Q x
adamc@135 415 H3 : R x
adamc@135 416 H4 : S x
adamc@135 417 ============================
adamc@135 418 S x
adam@302 419 ]]
adam@302 420 *)
adamc@135 421
adamc@135 422 assumption.
adamc@135 423 Qed.
adamc@141 424 (* end thide *)
adamc@135 425 End firstorder.
adamc@135 426
adamc@135 427 (** We narrowly avoided a subtle pitfall in our definition of [completer]. Let us try another definition that even seems preferable to the original, to the untrained eye. *)
adamc@135 428
adamc@141 429 (* begin thide *)
adamc@135 430 Ltac completer' :=
adamc@135 431 repeat match goal with
adamc@135 432 | [ |- _ /\ _ ] => constructor
adamc@135 433 | [ H : _ /\ _ |- _ ] => destruct H
adamc@135 434 | [ H : ?P -> _, H' : ?P |- _ ] =>
adamc@135 435 generalize (H H'); clear H; intro H
adamc@135 436 | [ |- forall x, _ ] => intro
adamc@135 437
adamc@135 438 | [ H : forall x, ?P x -> _, H' : ?P ?X |- _ ] =>
adamc@135 439 extend (H X H')
adamc@135 440 end.
adamc@141 441 (* end thide *)
adamc@135 442
adamc@135 443 (** 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: *)
adamc@135 444
adamc@135 445 Section firstorder'.
adamc@135 446 Variable A : Set.
adamc@135 447 Variables P Q R S : A -> Prop.
adamc@135 448
adamc@135 449 Hypothesis H1 : forall x, P x -> Q x /\ R x.
adamc@135 450 Hypothesis H2 : forall x, R x -> S x.
adamc@135 451
adamc@135 452 Theorem fo' : forall x, P x -> S x.
adamc@141 453 (* begin thide *)
adamc@135 454 (** [[
adamc@135 455 completer'.
adamc@220 456
adamc@205 457 ]]
adamc@205 458
adamc@135 459 Coq loops forever at this point. What went wrong? *)
adamc@220 460
adamc@135 461 Abort.
adamc@141 462 (* end thide *)
adamc@135 463 End firstorder'.
adamc@136 464
adamc@136 465 (** A few examples should illustrate the issue. Here we see a [match]-based proof that works fine: *)
adamc@136 466
adamc@136 467 Theorem t1 : forall x : nat, x = x.
adamc@136 468 match goal with
adamc@136 469 | [ |- forall x, _ ] => trivial
adamc@136 470 end.
adamc@141 471 (* begin thide *)
adamc@136 472 Qed.
adamc@141 473 (* end thide *)
adamc@136 474
adamc@136 475 (** This one fails. *)
adamc@136 476
adamc@141 477 (* begin thide *)
adamc@136 478 Theorem t1' : forall x : nat, x = x.
adamc@136 479 (** [[
adamc@136 480 match goal with
adamc@136 481 | [ |- forall x, ?P ] => trivial
adamc@136 482 end.
adamc@136 483
adamc@136 484 User error: No matching clauses for match goal
adam@302 485 ]]
adam@302 486 *)
adamc@220 487
adamc@136 488 Abort.
adamc@141 489 (* end thide *)
adamc@136 490
adam@288 491 (** 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.
adamc@136 492
adam@288 493 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.
adamc@136 494
adam@288 495 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. *)
adamc@137 496
adamc@137 497
adamc@137 498 (** * Functional Programming in Ltac *)
adamc@137 499
adamc@141 500 (* EX: Write a list length function in Ltac. *)
adamc@141 501
adamc@137 502 (** Ltac supports quite convenient functional programming, with a Lisp-with-syntax kind of flavor. However, there are a few syntactic conventions involved in getting programs to be accepted. The Ltac syntax is optimized for tactic-writing, so one has to deal with some inconveniences in writing more standard functional programs.
adamc@137 503
adamc@137 504 To illustrate, let us try to write a simple list length function. We start out writing it just like in Gallina, simply replacing [Fixpoint] (and its annotations) with [Ltac].
adamc@137 505
adamc@137 506 [[
adamc@137 507 Ltac length ls :=
adamc@137 508 match ls with
adamc@137 509 | nil => O
adamc@137 510 | _ :: ls' => S (length ls')
adamc@137 511 end.
adamc@137 512
adamc@137 513 Error: The reference ls' was not found in the current environment
adamc@220 514
adamc@137 515 ]]
adamc@137 516
adamc@137 517 At this point, we hopefully remember that pattern variable names must be prefixed by question marks in Ltac.
adamc@137 518
adamc@137 519 [[
adamc@137 520 Ltac length ls :=
adamc@137 521 match ls with
adamc@137 522 | nil => O
adamc@137 523 | _ :: ?ls' => S (length ls')
adamc@137 524 end.
adamc@137 525
adamc@137 526 Error: The reference S was not found in the current environment
adamc@220 527
adamc@137 528 ]]
adamc@137 529
adam@288 530 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. *)
adamc@137 531
adamc@141 532 (* begin thide *)
adamc@137 533 Ltac length ls :=
adamc@137 534 match ls with
adamc@137 535 | nil => O
adamc@137 536 | _ :: ?ls' => constr:(S (length ls'))
adamc@137 537 end.
adamc@137 538
adamc@137 539 (** This definition is accepted. It can be a little awkward to test Ltac definitions like this. Here is one method. *)
adamc@137 540
adamc@137 541 Goal False.
adamc@137 542 let n := length (1 :: 2 :: 3 :: nil) in
adamc@137 543 pose n.
adamc@137 544 (** [[
adamc@137 545 n := S (length (2 :: 3 :: nil)) : nat
adamc@137 546 ============================
adamc@137 547 False
adamc@220 548
adamc@137 549 ]]
adamc@137 550
adam@301 551 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.
adamc@220 552
adamc@220 553 [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. *)
adamc@220 554
adamc@220 555 Abort.
adamc@137 556
adamc@137 557 Reset length.
adamc@137 558
adamc@137 559 (** 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. *)
adamc@137 560
adamc@137 561 Ltac length ls :=
adamc@137 562 match ls with
adamc@137 563 | nil => O
adamc@137 564 | _ :: ?ls' =>
adamc@137 565 let ls'' := length ls' in
adamc@137 566 constr:(S ls'')
adamc@137 567 end.
adamc@137 568
adamc@137 569 Goal False.
adamc@137 570 let n := length (1 :: 2 :: 3 :: nil) in
adamc@137 571 pose n.
adamc@137 572 (** [[
adamc@137 573 n := 3 : nat
adamc@137 574 ============================
adamc@137 575 False
adam@302 576 ]]
adam@302 577 *)
adamc@220 578
adamc@137 579 Abort.
adamc@141 580 (* end thide *)
adamc@141 581
adamc@141 582 (* EX: Write a list map function in Ltac. *)
adamc@137 583
adamc@137 584 (** We can also use anonymous function expressions and local function definitions in Ltac, as this example of a standard list [map] function shows. *)
adamc@137 585
adamc@141 586 (* begin thide *)
adamc@137 587 Ltac map T f :=
adamc@137 588 let rec map' ls :=
adamc@137 589 match ls with
adam@288 590 | nil => constr:( @nil T)
adamc@137 591 | ?x :: ?ls' =>
adamc@137 592 let x' := f x in
adamc@137 593 let ls'' := map' ls' in
adam@288 594 constr:( x' :: ls'')
adamc@137 595 end in
adamc@137 596 map'.
adamc@137 597
adam@288 598 (** 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'')].
adamc@137 599
adam@288 600 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]. *)
adamc@137 601
adamc@137 602 Goal False.
adam@288 603 let ls := map (nat * nat)%type ltac:(fun x => constr:( x, x)) (1 :: 2 :: 3 :: nil) in
adamc@137 604 pose ls.
adamc@137 605 (** [[
adamc@137 606 l := (1, 1) :: (2, 2) :: (3, 3) :: nil : list (nat * nat)
adamc@137 607 ============================
adamc@137 608 False
adam@302 609 ]]
adam@302 610 *)
adamc@220 611
adamc@137 612 Abort.
adamc@141 613 (* end thide *)
adamc@137 614
adamc@138 615
adamc@139 616 (** * Recursive Proof Search *)
adamc@139 617
adamc@139 618 (** 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.
adamc@139 619
adam@288 620 We can consider the maximum %``%#"#dependency chain#"#%''% length for a first-order proof. We define the chain length for a hypothesis to be 0, and the chain length for an instantiation of a quantified fact to be one greater than the length for that fact. The tactic [inster n] is meant to try all possible proofs with chain length at most [n]. *)
adamc@139 621
adamc@141 622 (* begin thide *)
adamc@139 623 Ltac inster n :=
adamc@139 624 intuition;
adamc@139 625 match n with
adamc@139 626 | S ?n' =>
adamc@139 627 match goal with
adamc@139 628 | [ H : forall x : ?T, _, x : ?T |- _ ] => generalize (H x); inster n'
adamc@139 629 end
adamc@139 630 end.
adamc@141 631 (* end thide *)
adamc@139 632
adamc@139 633 (** [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.
adamc@139 634
adamc@139 635 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. *)
adamc@139 636
adamc@139 637 Section test_inster.
adamc@139 638 Variable A : Set.
adamc@139 639 Variables P Q : A -> Prop.
adamc@139 640 Variable f : A -> A.
adamc@139 641 Variable g : A -> A -> A.
adamc@139 642
adamc@139 643 Hypothesis H1 : forall x y, P (g x y) -> Q (f x).
adamc@139 644
adamc@139 645 Theorem test_inster : forall x y, P (g x y) -> Q (f x).
adamc@220 646 inster 2.
adamc@139 647 Qed.
adamc@139 648
adamc@139 649 Hypothesis H3 : forall u v, P u /\ P v /\ u <> v -> P (g u v).
adamc@139 650 Hypothesis H4 : forall u, Q (f u) -> P u /\ P (f u).
adamc@139 651
adamc@139 652 Theorem test_inster2 : forall x y, x <> y -> P x -> Q (f y) -> Q (f x).
adamc@220 653 inster 3.
adamc@139 654 Qed.
adamc@139 655 End test_inster.
adamc@139 656
adam@288 657 (** 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.
adamc@140 658
adam@288 659 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.
adamc@140 660
adam@288 661 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.
adamc@140 662
adam@288 663 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. *)
adamc@138 664
adamc@138 665 Definition imp (P1 P2 : Prop) := P1 -> P2.
adamc@140 666 Infix "-->" := imp (no associativity, at level 95).
adamc@140 667 Ltac imp := unfold imp; firstorder.
adamc@138 668
adamc@140 669 (** These lemmas about [imp] will be useful in the tactic that we will write. *)
adamc@138 670
adamc@138 671 Theorem and_True_prem : forall P Q,
adamc@138 672 (P /\ True --> Q)
adamc@138 673 -> (P --> Q).
adamc@138 674 imp.
adamc@138 675 Qed.
adamc@138 676
adamc@138 677 Theorem and_True_conc : forall P Q,
adamc@138 678 (P --> Q /\ True)
adamc@138 679 -> (P --> Q).
adamc@138 680 imp.
adamc@138 681 Qed.
adamc@138 682
adamc@138 683 Theorem assoc_prem1 : forall P Q R S,
adamc@138 684 (P /\ (Q /\ R) --> S)
adamc@138 685 -> ((P /\ Q) /\ R --> S).
adamc@138 686 imp.
adamc@138 687 Qed.
adamc@138 688
adamc@138 689 Theorem assoc_prem2 : forall P Q R S,
adamc@138 690 (Q /\ (P /\ R) --> S)
adamc@138 691 -> ((P /\ Q) /\ R --> S).
adamc@138 692 imp.
adamc@138 693 Qed.
adamc@138 694
adamc@138 695 Theorem comm_prem : forall P Q R,
adamc@138 696 (P /\ Q --> R)
adamc@138 697 -> (Q /\ P --> R).
adamc@138 698 imp.
adamc@138 699 Qed.
adamc@138 700
adamc@138 701 Theorem assoc_conc1 : forall P Q R S,
adamc@138 702 (S --> P /\ (Q /\ R))
adamc@138 703 -> (S --> (P /\ Q) /\ R).
adamc@138 704 imp.
adamc@138 705 Qed.
adamc@138 706
adamc@138 707 Theorem assoc_conc2 : forall P Q R S,
adamc@138 708 (S --> Q /\ (P /\ R))
adamc@138 709 -> (S --> (P /\ Q) /\ R).
adamc@138 710 imp.
adamc@138 711 Qed.
adamc@138 712
adamc@138 713 Theorem comm_conc : forall P Q R,
adamc@138 714 (R --> P /\ Q)
adamc@138 715 -> (R --> Q /\ P).
adamc@138 716 imp.
adamc@138 717 Qed.
adamc@138 718
adam@288 719 (** 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. *)
adamc@140 720
adamc@141 721 (* begin thide *)
adamc@138 722 Ltac search_prem tac :=
adamc@138 723 let rec search P :=
adamc@138 724 tac
adamc@138 725 || (apply and_True_prem; tac)
adamc@138 726 || match P with
adamc@138 727 | ?P1 /\ ?P2 =>
adamc@138 728 (apply assoc_prem1; search P1)
adamc@138 729 || (apply assoc_prem2; search P2)
adamc@138 730 end
adamc@138 731 in match goal with
adamc@138 732 | [ |- ?P /\ _ --> _ ] => search P
adamc@138 733 | [ |- _ /\ ?P --> _ ] => apply comm_prem; search P
adamc@138 734 | [ |- _ --> _ ] => progress (tac || (apply and_True_prem; tac))
adamc@138 735 end.
adamc@138 736
adamc@140 737 (** 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.
adamc@140 738
adamc@140 739 [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.
adamc@140 740
adamc@140 741 We will also want a dual function [search_conc], which does tree search through an [imp] conclusion. *)
adamc@140 742
adamc@138 743 Ltac search_conc tac :=
adamc@138 744 let rec search P :=
adamc@138 745 tac
adamc@138 746 || (apply and_True_conc; tac)
adamc@138 747 || match P with
adamc@138 748 | ?P1 /\ ?P2 =>
adamc@138 749 (apply assoc_conc1; search P1)
adamc@138 750 || (apply assoc_conc2; search P2)
adamc@138 751 end
adamc@138 752 in match goal with
adamc@138 753 | [ |- _ --> ?P /\ _ ] => search P
adamc@138 754 | [ |- _ --> _ /\ ?P ] => apply comm_conc; search P
adamc@138 755 | [ |- _ --> _ ] => progress (tac || (apply and_True_conc; tac))
adamc@138 756 end.
adamc@138 757
adamc@140 758 (** 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]. *)
adamc@140 759
adamc@138 760 Theorem False_prem : forall P Q,
adamc@138 761 False /\ P --> Q.
adamc@138 762 imp.
adamc@138 763 Qed.
adamc@138 764
adamc@138 765 Theorem True_conc : forall P Q : Prop,
adamc@138 766 (P --> Q)
adamc@138 767 -> (P --> True /\ Q).
adamc@138 768 imp.
adamc@138 769 Qed.
adamc@138 770
adamc@138 771 Theorem Match : forall P Q R : Prop,
adamc@138 772 (Q --> R)
adamc@138 773 -> (P /\ Q --> P /\ R).
adamc@138 774 imp.
adamc@138 775 Qed.
adamc@138 776
adamc@138 777 Theorem ex_prem : forall (T : Type) (P : T -> Prop) (Q R : Prop),
adamc@138 778 (forall x, P x /\ Q --> R)
adamc@138 779 -> (ex P /\ Q --> R).
adamc@138 780 imp.
adamc@138 781 Qed.
adamc@138 782
adamc@138 783 Theorem ex_conc : forall (T : Type) (P : T -> Prop) (Q R : Prop) x,
adamc@138 784 (Q --> P x /\ R)
adamc@138 785 -> (Q --> ex P /\ R).
adamc@138 786 imp.
adamc@138 787 Qed.
adamc@138 788
adam@288 789 (** We will also want a %``%#"#base case#"#%''% lemma for finishing proofs where cancelation has removed every constituent of the conclusion. *)
adamc@140 790
adamc@138 791 Theorem imp_True : forall P,
adamc@138 792 P --> True.
adamc@138 793 imp.
adamc@138 794 Qed.
adamc@138 795
adamc@220 796 (** Our final [matcher] tactic is now straightforward. First, we [intros] all variables into scope. Then we attempt simple premise simplifications, finishing the proof upon finding [False] and eliminating any existential quantifiers that we find. After that, we search through the conclusion. We remove [True] conjuncts, remove existential quantifiers by introducing unification variables for their bound variables, and search for matching premises to cancel. Finally, when no more progress is made, we see if the goal has become trivial and can be solved by [imp_True]. In each case, we use the tactic [simple apply] in place of [apply] to use a simpler, less expensive unification algorithm. *)
adamc@140 797
adamc@138 798 Ltac matcher :=
adamc@138 799 intros;
adam@288 800 repeat search_prem ltac:( simple apply False_prem || ( simple apply ex_prem; intro));
adam@288 801 repeat search_conc ltac:( simple apply True_conc || simple eapply ex_conc
adam@288 802 || search_prem ltac:( simple apply Match));
adamc@204 803 try simple apply imp_True.
adamc@141 804 (* end thide *)
adamc@140 805
adamc@140 806 (** Our tactic succeeds at proving a simple example. *)
adamc@138 807
adamc@138 808 Theorem t2 : forall P Q : Prop,
adamc@138 809 Q /\ (P /\ False) /\ P --> P /\ Q.
adamc@138 810 matcher.
adamc@138 811 Qed.
adamc@138 812
adamc@140 813 (** In the generated proof, we find a trace of the workings of the search tactics. *)
adamc@140 814
adamc@140 815 Print t2.
adamc@220 816 (** %\vspace{-.15in}% [[
adamc@140 817 t2 =
adamc@140 818 fun P Q : Prop =>
adamc@140 819 comm_prem (assoc_prem1 (assoc_prem2 (False_prem (P:=P /\ P /\ Q) (P /\ Q))))
adamc@140 820 : forall P Q : Prop, Q /\ (P /\ False) /\ P --> P /\ Q
adamc@220 821
adamc@220 822 ]]
adamc@140 823
adamc@220 824 We can also see that [matcher] is well-suited for cases where some human intervention is needed after the automation finishes. *)
adamc@140 825
adamc@138 826 Theorem t3 : forall P Q R : Prop,
adamc@138 827 P /\ Q --> Q /\ R /\ P.
adamc@138 828 matcher.
adamc@140 829 (** [[
adamc@140 830 ============================
adamc@140 831 True --> R
adamc@220 832
adamc@140 833 ]]
adamc@140 834
adamc@140 835 [matcher] canceled those conjuncts that it was able to cancel, leaving a simplified subgoal for us, much as [intuition] does. *)
adamc@220 836
adamc@138 837 Abort.
adamc@138 838
adamc@140 839 (** [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. *)
adamc@140 840
adamc@138 841 Theorem t4 : forall (P : nat -> Prop) Q, (exists x, P x /\ Q) --> Q /\ (exists x, P x).
adamc@138 842 matcher.
adamc@138 843 Qed.
adamc@138 844
adamc@140 845 Print t4.
adamc@220 846 (** %\vspace{-.15in}% [[
adamc@140 847 t4 =
adamc@140 848 fun (P : nat -> Prop) (Q : Prop) =>
adamc@140 849 and_True_prem
adamc@140 850 (ex_prem (P:=fun x : nat => P x /\ Q)
adamc@140 851 (fun x : nat =>
adamc@140 852 assoc_prem2
adamc@140 853 (Match (P:=Q)
adamc@140 854 (and_True_conc
adamc@140 855 (ex_conc (fun x0 : nat => P x0) x
adamc@140 856 (Match (P:=P x) (imp_True (P:=True))))))))
adamc@140 857 : forall (P : nat -> Prop) (Q : Prop),
adamc@140 858 (exists x : nat, P x /\ Q) --> Q /\ (exists x : nat, P x)
adam@302 859 ]]
adam@302 860 *)
adamc@234 861
adamc@234 862
adamc@234 863 (** * Creating Unification Variables *)
adamc@234 864
adamc@234 865 (** 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.
adamc@234 866
adamc@234 867 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.
adamc@234 868
adamc@234 869 Before we are ready to write a tactic, we can try out its ingredients one at a time. *)
adamc@234 870
adamc@234 871 Theorem t5 : (forall x : nat, S x > x) -> 2 > 1.
adamc@234 872 intros.
adamc@234 873
adamc@234 874 (** [[
adamc@234 875 H : forall x : nat, S x > x
adamc@234 876 ============================
adamc@234 877 2 > 1
adamc@234 878
adamc@234 879 ]]
adamc@234 880
adamc@234 881 To instantiate [H] generically, we first need to name the value to be used for [x]. *)
adamc@234 882
adamc@234 883 evar (y : nat).
adamc@234 884
adamc@234 885 (** [[
adamc@234 886 H : forall x : nat, S x > x
adamc@234 887 y := ?279 : nat
adamc@234 888 ============================
adamc@234 889 2 > 1
adamc@234 890
adamc@234 891 ]]
adamc@234 892
adamc@234 893 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. *)
adamc@234 894
adamc@234 895 let y' := eval cbv delta [y] in y in
adamc@234 896 clear y; generalize (H y').
adamc@234 897
adamc@234 898 (** [[
adamc@234 899 H : forall x : nat, S x > x
adamc@234 900 ============================
adamc@234 901 S ?279 > ?279 -> 2 > 1
adamc@234 902
adamc@234 903 ]]
adamc@234 904
adamc@234 905 Our instantiation was successful. We can finish by using the refined formula to replace the original. *)
adamc@234 906
adamc@234 907 clear H; intro H.
adamc@234 908
adamc@234 909 (** [[
adamc@234 910 H : S ?281 > ?281
adamc@234 911 ============================
adamc@234 912 2 > 1
adamc@234 913
adamc@234 914 ]]
adamc@234 915
adamc@234 916 We can finish the proof by using [apply]'s unification to figure out the proper value of [?281]. (The original unification variable was replaced by another, as often happens in the internals of the various tactics' implementations.) *)
adamc@234 917
adamc@234 918 apply H.
adamc@234 919 Qed.
adamc@234 920
adamc@234 921 (** Now we can write a tactic that encapsulates the pattern we just employed, instantiating all quantifiers of a particular hypothesis. *)
adamc@234 922
adamc@234 923 Ltac insterU H :=
adamc@234 924 repeat match type of H with
adamc@234 925 | forall x : ?T, _ =>
adamc@234 926 let x := fresh "x" in
adamc@234 927 evar (x : T);
adamc@234 928 let x' := eval cbv delta [x] in x in
adamc@234 929 clear x; generalize (H x'); clear H; intro H
adamc@234 930 end.
adamc@234 931
adamc@234 932 Theorem t5' : (forall x : nat, S x > x) -> 2 > 1.
adamc@234 933 intro H; insterU H; apply H.
adamc@234 934 Qed.
adamc@234 935
adamc@234 936 (** 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. *)
adamc@234 937
adamc@234 938 Ltac insterKeep H :=
adamc@234 939 let H' := fresh "H'" in
adamc@234 940 generalize H; intro H'; insterU H'.
adamc@234 941
adamc@234 942 Section t6.
adamc@234 943 Variables A B : Type.
adamc@234 944 Variable P : A -> B -> Prop.
adamc@234 945 Variable f : A -> A -> A.
adamc@234 946 Variable g : B -> B -> B.
adamc@234 947
adamc@234 948 Hypothesis H1 : forall v, exists u, P v u.
adamc@234 949 Hypothesis H2 : forall v1 u1 v2 u2,
adamc@234 950 P v1 u1
adamc@234 951 -> P v2 u2
adamc@234 952 -> P (f v1 v2) (g u1 u2).
adamc@234 953
adamc@234 954 Theorem t6 : forall v1 v2, exists u1, exists u2, P (f v1 v2) (g u1 u2).
adamc@234 955 intros.
adamc@234 956
adamc@234 957 (** Neither [eauto] nor [firstorder] is clever enough to prove this goal. We can help out by doing some of the work with quantifiers ourselves. *)
adamc@234 958
adamc@234 959 do 2 insterKeep H1.
adamc@234 960
adamc@234 961 (** Our proof state is extended with two generic instances of [H1].
adamc@234 962
adamc@234 963 [[
adamc@234 964 H' : exists u : B, P ?4289 u
adamc@234 965 H'0 : exists u : B, P ?4288 u
adamc@234 966 ============================
adamc@234 967 exists u1 : B, exists u2 : B, P (f v1 v2) (g u1 u2)
adamc@234 968
adamc@234 969 ]]
adamc@234 970
adamc@234 971 [eauto] still cannot prove the goal, so we eliminate the two new existential quantifiers. *)
adamc@234 972
adamc@234 973 repeat match goal with
adamc@234 974 | [ H : ex _ |- _ ] => destruct H
adamc@234 975 end.
adamc@234 976
adamc@234 977 (** Now the goal is simple enough to solve by logic programming. *)
adamc@234 978
adamc@234 979 eauto.
adamc@234 980 Qed.
adamc@234 981 End t6.
adamc@234 982
adamc@234 983 (** Our [insterU] tactic does not fare so well with quantified hypotheses that also contain implications. We can see the problem in a slight modification of the last example. We introduce a new unary predicate [Q] and use it to state an additional requirement of our hypothesis [H1]. *)
adamc@234 984
adamc@234 985 Section t7.
adamc@234 986 Variables A B : Type.
adamc@234 987 Variable Q : A -> Prop.
adamc@234 988 Variable P : A -> B -> Prop.
adamc@234 989 Variable f : A -> A -> A.
adamc@234 990 Variable g : B -> B -> B.
adamc@234 991
adamc@234 992 Hypothesis H1 : forall v, Q v -> exists u, P v u.
adamc@234 993 Hypothesis H2 : forall v1 u1 v2 u2,
adamc@234 994 P v1 u1
adamc@234 995 -> P v2 u2
adamc@234 996 -> P (f v1 v2) (g u1 u2).
adamc@234 997
adam@297 998 Theorem t7 : forall v1 v2, Q v1 -> Q v2 -> exists u1, exists u2, P (f v1 v2) (g u1 u2).
adamc@234 999 intros; do 2 insterKeep H1;
adamc@234 1000 repeat match goal with
adamc@234 1001 | [ H : ex _ |- _ ] => destruct H
adamc@234 1002 end; eauto.
adamc@234 1003
adamc@234 1004 (** This proof script does not hit any errors until the very end, when an error message like this one is displayed.
adamc@234 1005
adamc@234 1006 [[
adamc@234 1007 No more subgoals but non-instantiated existential variables :
adamc@234 1008 Existential 1 =
adamc@234 1009 ?4384 : [A : Type
adamc@234 1010 B : Type
adamc@234 1011 Q : A -> Prop
adamc@234 1012 P : A -> B -> Prop
adamc@234 1013 f : A -> A -> A
adamc@234 1014 g : B -> B -> B
adamc@234 1015 H1 : forall v : A, Q v -> exists u : B, P v u
adamc@234 1016 H2 : forall (v1 : A) (u1 : B) (v2 : A) (u2 : B),
adamc@234 1017 P v1 u1 -> P v2 u2 -> P (f v1 v2) (g u1 u2)
adamc@234 1018 v1 : A
adamc@234 1019 v2 : A
adamc@234 1020 H : Q v1
adamc@234 1021 H0 : Q v2
adamc@234 1022 H' : Q v2 -> exists u : B, P v2 u |- Q v2]
adamc@234 1023
adamc@234 1024 ]]
adamc@234 1025
adam@288 1026 There is another similar line about a different existential variable. Here, %``%#"#existential variable#"#%''% means what we have also called %``%#"#unification variable.#"#%''% In the course of the proof, some unification variable [?4384] was introduced but never unified. Unification variables are just a device to structure proof search; the language of Gallina proof terms does not include them. Thus, we cannot produce a proof term without instantiating the variable.
adamc@234 1027
adamc@234 1028 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]. *)
adamc@234 1029
adamc@234 1030 Abort.
adamc@234 1031 End t7.
adamc@234 1032
adamc@234 1033 Reset insterU.
adamc@234 1034
adamc@234 1035 (** 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. *)
adamc@234 1036
adamc@234 1037 Ltac insterU tac H :=
adamc@234 1038 repeat match type of H with
adamc@234 1039 | forall x : ?T, _ =>
adamc@234 1040 match type of T with
adamc@234 1041 | Prop =>
adamc@234 1042 (let H' := fresh "H'" in
adamc@234 1043 assert (H' : T); [
adamc@234 1044 solve [ tac ]
adamc@234 1045 | generalize (H H'); clear H H'; intro H ])
adamc@234 1046 || fail 1
adamc@234 1047 | _ =>
adamc@234 1048 let x := fresh "x" in
adamc@234 1049 evar (x : T);
adamc@234 1050 let x' := eval cbv delta [x] in x in
adamc@234 1051 clear x; generalize (H x'); clear H; intro H
adamc@234 1052 end
adamc@234 1053 end.
adamc@234 1054
adamc@234 1055 Ltac insterKeep tac H :=
adamc@234 1056 let H' := fresh "H'" in
adamc@234 1057 generalize H; intro H'; insterU tac H'.
adamc@234 1058
adamc@234 1059 Section t7.
adamc@234 1060 Variables A B : Type.
adamc@234 1061 Variable Q : A -> Prop.
adamc@234 1062 Variable P : A -> B -> Prop.
adamc@234 1063 Variable f : A -> A -> A.
adamc@234 1064 Variable g : B -> B -> B.
adamc@234 1065
adamc@234 1066 Hypothesis H1 : forall v, Q v -> exists u, P v u.
adamc@234 1067 Hypothesis H2 : forall v1 u1 v2 u2,
adamc@234 1068 P v1 u1
adamc@234 1069 -> P v2 u2
adamc@234 1070 -> P (f v1 v2) (g u1 u2).
adamc@234 1071
adamc@234 1072 Theorem t6 : forall v1 v2, Q v1 -> Q v2 -> exists u1, exists u2, P (f v1 v2) (g u1 u2).
adamc@234 1073
adamc@234 1074 (** We can prove the goal by calling [insterKeep] with a tactic that tries to find and apply a [Q] hypothesis over a variable about which we do not yet know any [P] facts. We need to begin this tactic code with [idtac; ] to get around a strange limitation in Coq's proof engine, where a first-class tactic argument may not begin with a [match]. *)
adamc@234 1075
adamc@234 1076 intros; do 2 insterKeep ltac:(idtac; match goal with
adamc@234 1077 | [ H : Q ?v |- _ ] =>
adamc@234 1078 match goal with
adamc@234 1079 | [ _ : context[P v _] |- _ ] => fail 1
adamc@234 1080 | _ => apply H
adamc@234 1081 end
adamc@234 1082 end) H1;
adamc@234 1083 repeat match goal with
adamc@234 1084 | [ H : ex _ |- _ ] => destruct H
adamc@234 1085 end; eauto.
adamc@234 1086 Qed.
adamc@234 1087 End t7.
adamc@234 1088
adamc@234 1089 (** It is often useful to instantiate existential variables explicitly. A built-in tactic provides one way of doing so. *)
adamc@234 1090
adamc@234 1091 Theorem t8 : exists p : nat * nat, fst p = 3.
adamc@234 1092 econstructor; instantiate (1 := (3, 2)); reflexivity.
adamc@234 1093 Qed.
adamc@234 1094
adamc@234 1095 (** 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 [:=].
adamc@234 1096
adamc@234 1097 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. *)
adamc@234 1098
adamc@234 1099 Ltac equate x y :=
adamc@234 1100 let H := fresh "H" in
adamc@234 1101 assert (H : x = y); [ reflexivity | clear H ].
adamc@234 1102
adamc@234 1103 (** [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. *)
adamc@234 1104
adamc@234 1105 Theorem t9 : exists p : nat * nat, fst p = 3.
adamc@234 1106 econstructor; match goal with
adamc@234 1107 | [ |- fst ?x = 3 ] => equate x (3, 2)
adamc@234 1108 end; reflexivity.
adamc@234 1109 Qed.