annotate src/Match.v @ 545:4f6e7bab0d45

Make a theorem name more consistent
author Adam Chlipala <adam@chlipala.net>
date Tue, 08 Mar 2016 11:50:53 -0500
parents ed829eaa91b2
children 2c8c693ddaba
rev   line source
adam@534 1 (* Copyright (c) 2008-2012, 2015, 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
adam@534 13 Require Import Cpdt.CpdtTactics.
adamc@132 14
adamc@132 15 Set Implicit Arguments.
adam@534 16 Set Asymmetric Patterns.
adamc@132 17 (* end hide *)
adamc@132 18
adamc@132 19
adam@324 20 (** %\chapter{Proof Search in Ltac}% *)
adamc@132 21
adam@328 22 (** 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. *)
adamc@132 23
adamc@132 24 (** * Some Built-In Automation Tactics *)
adamc@132 25
adam@386 26 (** 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, with operands built from constants, variables, addition, and subtraction (with multiplication by a constant available as a shorthand for addition or subtraction).
adamc@132 27
adam@411 28 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 [field] for simplifying values in fields by conversion to fractions over rings. Both [ring] and [field] can only solve goals that are equalities. The %\index{tactics!fourier}%[fourier] tactic uses Fourier's method to prove inequalities over real numbers, which are axiomatized in the Coq standard library.
adamc@132 29
adam@431 30 The%\index{setoids}% _setoid_ 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."
adam@328 31
adam@431 32 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. *)
adamc@132 33
adamc@132 34
adamc@135 35 (** * Ltac Programming Basics *)
adamc@135 36
adam@328 37 (** 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.
adamc@135 38
adamc@135 39 One common use for [match] tactics is identification of subjects for case analysis, as we see in this tactic definition. *)
adamc@135 40
adamc@141 41 (* begin thide *)
adamc@135 42 Ltac find_if :=
adamc@135 43 match goal with
adamc@135 44 | [ |- if ?X then _ else _ ] => destruct X
adamc@135 45 end.
adamc@141 46 (* end thide *)
adamc@135 47
adamc@135 48 (** 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 49
adamc@135 50 Theorem hmm : forall (a b c : bool),
adamc@135 51 if a
adamc@135 52 then if b
adamc@135 53 then True
adamc@135 54 else True
adamc@135 55 else if c
adamc@135 56 then True
adamc@135 57 else True.
adamc@141 58 (* begin thide *)
adamc@135 59 intros; repeat find_if; constructor.
adamc@135 60 Qed.
adamc@141 61 (* end thide *)
adamc@135 62
adam@411 63 (** The %\index{tactics!repeat}%[repeat] that we use here is called a%\index{tactical}% _tactical_, or tactic combinator. The behavior of [repeat t] is to loop through running [t], running [t] on all generated subgoals, running [t] on _their_ 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 64
adam@411 65 Another very useful Ltac building block is%\index{context patterns}% _context patterns_. *)
adamc@135 66
adamc@141 67 (* begin thide *)
adamc@135 68 Ltac find_if_inside :=
adamc@135 69 match goal with
adamc@135 70 | [ |- context[if ?X then _ else _] ] => destruct X
adamc@135 71 end.
adamc@141 72 (* end thide *)
adamc@135 73
adamc@135 74 (** 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 75
adamc@135 76 Theorem hmm' : forall (a b c : bool),
adamc@135 77 if a
adamc@135 78 then if b
adamc@135 79 then True
adamc@135 80 else True
adamc@135 81 else if c
adamc@135 82 then True
adamc@135 83 else True.
adamc@141 84 (* begin thide *)
adamc@135 85 intros; repeat find_if_inside; constructor.
adamc@135 86 Qed.
adamc@141 87 (* end thide *)
adamc@135 88
adamc@135 89 (** We can also use [find_if_inside] to prove goals that [find_if] does not simplify sufficiently. *)
adamc@135 90
adamc@141 91 Theorem hmm2 : forall (a b : bool),
adamc@135 92 (if a then 42 else 42) = (if b then 42 else 42).
adamc@141 93 (* begin thide *)
adamc@135 94 intros; repeat find_if_inside; reflexivity.
adamc@135 95 Qed.
adamc@141 96 (* end thide *)
adamc@135 97
adam@431 98 (** 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 99
adamc@141 100 (* begin thide *)
adamc@135 101 Ltac my_tauto :=
adamc@135 102 repeat match goal with
adamc@135 103 | [ H : ?P |- ?P ] => exact H
adamc@135 104
adamc@135 105 | [ |- True ] => constructor
adamc@135 106 | [ |- _ /\ _ ] => constructor
adamc@135 107 | [ |- _ -> _ ] => intro
adamc@135 108
adamc@135 109 | [ H : False |- _ ] => destruct H
adamc@135 110 | [ H : _ /\ _ |- _ ] => destruct H
adamc@135 111 | [ H : _ \/ _ |- _ ] => destruct H
adamc@135 112
adam@328 113 | [ H1 : ?P -> ?Q, H2 : ?P |- _ ] => specialize (H1 H2)
adamc@135 114 end.
adamc@141 115 (* end thide *)
adamc@135 116
adam@328 117 (** 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.
adamc@135 118
adam@328 119 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].
adamc@135 120
adam@484 121 The last rule implements modus ponens, using a tactic %\index{tactics!specialize}%[specialize] 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). By convention, when the argument to [specialize] is an application of a hypothesis [H] to a set of arguments, the result of the specialization replaces [H]. For other terms, the outcome is the same as with [generalize]. *)
adamc@135 122
adamc@135 123 Section propositional.
adamc@135 124 Variables P Q R : Prop.
adamc@135 125
adamc@138 126 Theorem propositional : (P \/ Q \/ False) /\ (P -> Q) -> True /\ Q.
adamc@141 127 (* begin thide *)
adamc@135 128 my_tauto.
adamc@135 129 Qed.
adamc@141 130 (* end thide *)
adamc@135 131 End propositional.
adamc@135 132
adam@328 133 (** 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 134
adamc@135 135 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 136
adam@398 137 There is a related pair of two other differences that are much more important than the others. The [match] construct has a _backtracking semantics for failure_. 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 138
adamc@135 139 For instance, this (unnecessarily verbose) proof script works: *)
adamc@135 140
adamc@135 141 Theorem m1 : True.
adamc@135 142 match goal with
adamc@135 143 | [ |- _ ] => intro
adamc@135 144 | [ |- True ] => constructor
adamc@135 145 end.
adamc@141 146 (* begin thide *)
adamc@135 147 Qed.
adamc@141 148 (* end thide *)
adamc@135 149
adam@460 150 (** 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, the whole pattern-match would fail. 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 151
adam@398 152 The example shows how failure can move to a different pattern within a [match]. Failure can also trigger an attempt to find _a different way of matching a single pattern_. Consider another example: *)
adamc@135 153
adamc@135 154 Theorem m2 : forall P Q R : Prop, P -> Q -> R -> Q.
adamc@135 155 intros; match goal with
adamc@220 156 | [ H : _ |- _ ] => idtac H
adamc@135 157 end.
adamc@135 158
adam@431 159 (** 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: *)
adamc@135 160
adamc@141 161 (* begin thide *)
adamc@135 162 match goal with
adamc@135 163 | [ H : _ |- _ ] => exact H
adamc@135 164 end.
adamc@135 165 Qed.
adamc@141 166 (* end thide *)
adamc@135 167
adamc@135 168 (** 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 169
adamc@135 170 (** Now we are equipped to implement a tactic for checking that a proposition is not among our hypotheses: *)
adamc@135 171
adamc@141 172 (* begin thide *)
adamc@135 173 Ltac notHyp P :=
adamc@135 174 match goal with
adamc@135 175 | [ _ : P |- _ ] => fail 1
adamc@135 176 | _ =>
adamc@135 177 match P with
adamc@135 178 | ?P1 /\ ?P2 => first [ notHyp P1 | notHyp P2 | fail 2 ]
adamc@135 179 | _ => idtac
adamc@135 180 end
adamc@135 181 end.
adamc@141 182 (* end thide *)
adamc@135 183
adam@431 184 (** 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.
adamc@135 185
adam@328 186 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.
adamc@135 187
adam@328 188 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.
adamc@135 189
adamc@135 190 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 191
adamc@141 192 (* begin thide *)
adamc@135 193 Ltac extend pf :=
adamc@135 194 let t := type of pf in
adamc@135 195 notHyp t; generalize pf; intro.
adamc@141 196 (* end thide *)
adamc@135 197
adam@386 198 (** 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 the proof [t]).
adamc@135 199
adam@484 200 With these tactics defined, we can write a tactic [completer] for, among other things, adding to the context all consequences of a set of simple first-order formulas. *)
adamc@135 201
adamc@141 202 (* begin thide *)
adamc@135 203 Ltac completer :=
adamc@135 204 repeat match goal with
adamc@135 205 | [ |- _ /\ _ ] => constructor
adamc@135 206 | [ H : _ /\ _ |- _ ] => destruct H
adam@328 207 | [ H : ?P -> ?Q, H' : ?P |- _ ] => specialize (H H')
adamc@135 208 | [ |- forall x, _ ] => intro
adamc@135 209
adam@328 210 | [ H : forall x, ?P x -> _, H' : ?P ?X |- _ ] => extend (H X H')
adamc@135 211 end.
adamc@141 212 (* end thide *)
adamc@135 213
adamc@135 214 (** 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 215
adamc@135 216 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 217
adam@483 218 We can check that [completer] is working properly, with a theorem that introduces a spurious variable whose didactic purpose we will come to shortly. *)
adamc@135 219
adamc@135 220 Section firstorder.
adamc@135 221 Variable A : Set.
adamc@135 222 Variables P Q R S : A -> Prop.
adamc@135 223
adamc@135 224 Hypothesis H1 : forall x, P x -> Q x /\ R x.
adamc@135 225 Hypothesis H2 : forall x, R x -> S x.
adamc@135 226
adam@483 227 Theorem fo : forall (y x : A), P x -> S x.
adamc@141 228 (* begin thide *)
adamc@135 229 completer.
adamc@135 230 (** [[
adam@483 231 y : A
adamc@135 232 x : A
adamc@135 233 H : P x
adamc@135 234 H0 : Q x
adamc@135 235 H3 : R x
adamc@135 236 H4 : S x
adamc@135 237 ============================
adamc@135 238 S x
adam@302 239 ]]
adam@302 240 *)
adamc@135 241
adamc@135 242 assumption.
adamc@135 243 Qed.
adamc@141 244 (* end thide *)
adamc@135 245 End firstorder.
adamc@135 246
adam@483 247 (** 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. (We change the second [match] case a bit to make the tactic smart enough to handle some subtleties of Ltac behavior that had not been exercised previously.) *)
adamc@135 248
adamc@141 249 (* begin thide *)
adamc@135 250 Ltac completer' :=
adamc@135 251 repeat match goal with
adamc@135 252 | [ |- _ /\ _ ] => constructor
adam@483 253 | [ H : ?P /\ ?Q |- _ ] => destruct H;
adam@483 254 repeat match goal with
adam@483 255 | [ H' : P /\ Q |- _ ] => clear H'
adam@483 256 end
adam@328 257 | [ H : ?P -> _, H' : ?P |- _ ] => specialize (H H')
adamc@135 258 | [ |- forall x, _ ] => intro
adamc@135 259
adam@328 260 | [ H : forall x, ?P x -> _, H' : ?P ?X |- _ ] => extend (H X H')
adamc@135 261 end.
adamc@141 262 (* end thide *)
adamc@135 263
adam@483 264 (** The only other 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 265
adamc@135 266 Section firstorder'.
adamc@135 267 Variable A : Set.
adamc@135 268 Variables P Q R S : A -> Prop.
adamc@135 269
adamc@135 270 Hypothesis H1 : forall x, P x -> Q x /\ R x.
adamc@135 271 Hypothesis H2 : forall x, R x -> S x.
adamc@135 272
adam@483 273 Theorem fo' : forall (y x : A), P x -> S x.
adamc@135 274 completer'.
adam@483 275 (** [[
adam@483 276 y : A
adam@483 277 H1 : P y -> Q y /\ R y
adam@483 278 H2 : R y -> S y
adam@483 279 x : A
adam@483 280 H : P x
adam@483 281 ============================
adam@483 282 S x
adam@483 283 ]]
adam@483 284 The quantified theorems have been instantiated with [y] instead of [x], reducing a provable goal to one that is unprovable. Our code in the last [match] case for [completer'] is careful only to instantiate quantifiers along with suitable hypotheses, so why were incorrect choices made?
adam@483 285 *)
adamc@220 286
adamc@135 287 Abort.
adamc@141 288 (* end thide *)
adamc@135 289 End firstorder'.
adamc@136 290
adamc@136 291 (** A few examples should illustrate the issue. Here we see a [match]-based proof that works fine: *)
adamc@136 292
adamc@136 293 Theorem t1 : forall x : nat, x = x.
adamc@136 294 match goal with
adamc@136 295 | [ |- forall x, _ ] => trivial
adamc@136 296 end.
adamc@141 297 (* begin thide *)
adamc@136 298 Qed.
adamc@141 299 (* end thide *)
adamc@136 300
adamc@136 301 (** This one fails. *)
adamc@136 302
adamc@141 303 (* begin thide *)
adamc@136 304 Theorem t1' : forall x : nat, x = x.
adam@445 305 (** %\vspace{-.25in}%[[
adamc@136 306 match goal with
adamc@136 307 | [ |- forall x, ?P ] => trivial
adamc@136 308 end.
adam@328 309 ]]
adamc@136 310
adam@328 311 <<
adamc@136 312 User error: No matching clauses for match goal
adam@328 313 >>
adam@328 314 *)
adamc@220 315
adamc@136 316 Abort.
adamc@141 317 (* end thide *)
adamc@136 318
adam@507 319 (** 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 restriction affects the behavior of the [completer] tactic, 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 320
adam@484 321 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. We will see an example of this fancier binding form in Section 15.5.
adamc@136 322
adam@483 323 No matter which Coq version you use, it is important to be aware of this restriction. As we have alluded to, the restriction is the culprit behind the surprising behavior of [completer']. We unintentionally match quantified facts with the modus ponens rule, circumventing the check that a suitably matching hypothesis is available and leading to different behavior, where wrong quantifier instantiations are chosen. 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.
adam@483 324
adam@483 325 Actually, the behavior demonstrated here applies to Coq version 8.4, but not 8.4pl1. The latter version will allow regular Ltac pattern variables to match terms that contain locally bound variables, but a tactic failure occurs if that variable is later used as a Gallina term. *)
adamc@137 326
adamc@137 327
adamc@137 328 (** * Functional Programming in Ltac *)
adamc@137 329
adamc@141 330 (* EX: Write a list length function in Ltac. *)
adamc@141 331
adamc@137 332 (** 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 333
adam@475 334 To illustrate, let us try to write a simple list length function. We start out writing it just as in Gallina, simply replacing [Fixpoint] (and its annotations) with [Ltac].
adamc@137 335 [[
adamc@137 336 Ltac length ls :=
adamc@137 337 match ls with
adamc@137 338 | nil => O
adamc@137 339 | _ :: ls' => S (length ls')
adamc@137 340 end.
adam@328 341 ]]
adamc@137 342
adam@328 343 <<
adamc@137 344 Error: The reference ls' was not found in the current environment
adam@328 345 >>
adamc@137 346
adamc@137 347 At this point, we hopefully remember that pattern variable names must be prefixed by question marks in Ltac.
adamc@137 348 [[
adamc@137 349 Ltac length ls :=
adamc@137 350 match ls with
adamc@137 351 | nil => O
adamc@137 352 | _ :: ?ls' => S (length ls')
adamc@137 353 end.
adamc@137 354 ]]
adamc@137 355
adam@328 356 <<
adam@328 357 Error: The reference S was not found in the current environment
adam@328 358 >>
adam@328 359
adam@431 360 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}% *)
adamc@137 361
adamc@141 362 (* begin thide *)
adam@534 363 (* begin hide *)
adam@534 364 Definition red_herring := O.
adam@534 365 (* end hide *)
adamc@137 366 Ltac length ls :=
adamc@137 367 match ls with
adamc@137 368 | nil => O
adamc@137 369 | _ :: ?ls' => constr:(S (length ls'))
adamc@137 370 end.
adamc@137 371
adam@445 372 (** This definition is accepted. It can be a little awkward to test Ltac definitions like this one. Here is one method. *)
adamc@137 373
adamc@137 374 Goal False.
adamc@137 375 let n := length (1 :: 2 :: 3 :: nil) in
adamc@137 376 pose n.
adamc@137 377 (** [[
adamc@137 378 n := S (length (2 :: 3 :: nil)) : nat
adamc@137 379 ============================
adamc@137 380 False
adamc@137 381 ]]
adamc@137 382
adam@328 383 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.
adamc@220 384
adam@328 385 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. *)
adamc@220 386
adamc@220 387 Abort.
adamc@137 388
adamc@137 389 Reset length.
adam@534 390 (* begin hide *)
adam@534 391 Reset red_herring.
adam@534 392 (* end hide *)
adamc@137 393
adamc@137 394 (** 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 395
adam@534 396 (* begin hide *)
adam@534 397 Definition red_herring := O.
adam@534 398 (* end hide *)
adamc@137 399 Ltac length ls :=
adamc@137 400 match ls with
adamc@137 401 | nil => O
adamc@137 402 | _ :: ?ls' =>
adamc@137 403 let ls'' := length ls' in
adamc@137 404 constr:(S ls'')
adamc@137 405 end.
adamc@137 406
adamc@137 407 Goal False.
adamc@137 408 let n := length (1 :: 2 :: 3 :: nil) in
adamc@137 409 pose n.
adamc@137 410 (** [[
adamc@137 411 n := 3 : nat
adamc@137 412 ============================
adamc@137 413 False
adam@302 414 ]]
adam@302 415 *)
adamc@220 416
adamc@137 417 Abort.
adamc@141 418 (* end thide *)
adamc@141 419
adamc@141 420 (* EX: Write a list map function in Ltac. *)
adamc@137 421
adam@431 422 (* begin hide *)
adam@437 423 (* begin thide *)
adam@431 424 Definition mapp := (map, list).
adam@437 425 (* end thide *)
adam@431 426 (* end hide *)
adam@431 427
adamc@137 428 (** 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 429
adamc@141 430 (* begin thide *)
adamc@137 431 Ltac map T f :=
adamc@137 432 let rec map' ls :=
adamc@137 433 match ls with
adam@411 434 | nil => constr:(@nil T)
adamc@137 435 | ?x :: ?ls' =>
adamc@137 436 let x' := f x in
adamc@137 437 let ls'' := map' ls' in
adam@411 438 constr:(x' :: ls'')
adamc@137 439 end in
adamc@137 440 map'.
adamc@137 441
adam@411 442 (** 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'')].
adamc@137 443
adam@431 444 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 %\coqdocvar{%#<tt>#map#</tt>#%}%. *)
adamc@137 445
adamc@137 446 Goal False.
adam@411 447 let ls := map (nat * nat)%type ltac:(fun x => constr:(x, x)) (1 :: 2 :: 3 :: nil) in
adamc@137 448 pose ls.
adamc@137 449 (** [[
adamc@137 450 l := (1, 1) :: (2, 2) :: (3, 3) :: nil : list (nat * nat)
adamc@137 451 ============================
adamc@137 452 False
adam@302 453 ]]
adam@302 454 *)
adamc@220 455
adamc@137 456 Abort.
adamc@141 457 (* end thide *)
adamc@137 458
adam@431 459 (** Each position within an Ltac script has a default applicable non-terminal, where [constr] and [ltac] are the main options worth thinking about, standing respectively for terms of Gallina and Ltac. The explicit colon notation can always be used to override the default non-terminal choice, though code being parsed as Gallina can no longer use such overrides. Within the [ltac] non-terminal, top-level function applications are treated as applications in Ltac, not Gallina; but the _arguments_ to such functions are parsed with [constr] by default. This choice may seem strange, until we realize that we have been relying on it all along in all the proof scripts we write! For instance, the [apply] tactic is an Ltac function, and it is natural to interpret its argument as a term of Gallina, not Ltac. We use an [ltac] prefix to parse Ltac function arguments as Ltac terms themselves, as in the call to %\coqdocvar{%#<tt>#map#</tt>#%}% above. For some simple cases, Ltac terms may be passed without an extra prefix. For instance, an identifier that has an Ltac meaning but no Gallina meaning will be interpreted in Ltac automatically.
adam@386 460
adam@431 461 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 %\coqdocvar{%#<tt>#length#</tt>#%}% that prints a debug trace of the arguments it is called with. *)
adam@328 462
adam@334 463 (* begin thide *)
adam@328 464 Reset length.
adam@534 465 (* begin hide *)
adam@534 466 Reset red_herring.
adam@534 467 (* end hide *)
adam@328 468
adam@534 469 (* begin hide *)
adam@534 470 Definition red_herring := O.
adam@534 471 (* end hide *)
adam@328 472 Ltac length ls :=
adam@328 473 idtac ls;
adam@328 474 match ls with
adam@328 475 | nil => O
adam@328 476 | _ :: ?ls' =>
adam@328 477 let ls'' := length ls' in
adam@328 478 constr:(S ls'')
adam@328 479 end.
adam@328 480
adam@328 481 (** Coq accepts the tactic definition, but the code is fatally flawed and will always lead to dynamic type errors. *)
adam@328 482
adam@328 483 Goal False.
adam@328 484 (** %\vspace{-.15in}%[[
adam@328 485 let n := length (1 :: 2 :: 3 :: nil) in
adam@328 486 pose n.
adam@328 487 ]]
adam@328 488
adam@328 489 <<
adam@328 490 Error: variable n should be bound to a term.
adam@328 491 >> *)
adam@328 492 Abort.
adam@328 493
adam@475 494 (** 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{monad}\index{Haskell}%monadic programming in Haskell%~\cite{Monads,IO}% may recognize a similarity. Haskell programs with side effects can be thought of as pure programs that return _the code of programs in an imperative language_, 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.
adam@328 495
adam@328 496 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.
adam@328 497
adam@484 498 An alternate explanation that avoids an analogy to Haskell monads (admittedly a tricky concept in its own right) is: An Ltac tactic program returns a function that, when run later, will perform the desired proof modification. These functions are distinct from other types of data, like numbers or Gallina terms. The prior, correctly working version of [length] computed solely with Gallina terms, but the new one is implicitly returning a tactic function, as indicated by the use of [idtac] and semicolon. However, the new version's recursive call to [length] is structured to expect a Gallina term, not a tactic function, as output. As a result, we have a basic dynamic type error, perhaps obscured by the involvement of first-class tactic scripts.
adam@484 499
adam@431 500 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}% _continuation-passing style_ %\cite{continuations}%, a program structuring idea popular in functional programming. *)
adam@328 501
adam@328 502 Reset length.
adam@534 503 (* begin hide *)
adam@534 504 Reset red_herring.
adam@534 505 (* end hide *)
adam@328 506
adam@328 507 Ltac length ls k :=
adam@328 508 idtac ls;
adam@328 509 match ls with
adam@328 510 | nil => k O
adam@328 511 | _ :: ?ls' => length ls' ltac:(fun n => k (S n))
adam@328 512 end.
adam@334 513 (* end thide *)
adam@328 514
adam@431 515 (** The new [length] takes a new input: a _continuation_ [k], which is a function to be called to continue whatever proving process we were in the middle of when we called %\coqdocvar{%#<tt>#length#</tt>#%}%. The argument passed to [k] may be thought of as the return value of %\coqdocvar{%#<tt>#length#</tt>#%}%. *)
adam@328 516
adam@334 517 (* begin thide *)
adam@328 518 Goal False.
adam@328 519 length (1 :: 2 :: 3 :: nil) ltac:(fun n => pose n).
adam@328 520 (** [[
adam@328 521 (1 :: 2 :: 3 :: nil)
adam@328 522 (2 :: 3 :: nil)
adam@328 523 (3 :: nil)
adam@328 524 nil
adam@328 525 ]]
adam@328 526 *)
adam@328 527 Abort.
adam@334 528 (* end thide *)
adam@328 529
adam@386 530 (** 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].
adam@386 531
adam@431 532 Considering the comparison with Haskell's IO monad, there is an important subtlety that deserves to be mentioned. A Haskell IO computation represents (theoretically speaking, at least) a transformer from one state of the real world to another, plus a pure value to return. Some of the state can be very specific to the program, as in the case of heap-allocated mutable references, but some can be along the lines of the favorite example "launch missile," where the program has a side effect on the real world that is not possible to undo.
adam@386 533
adam@398 534 In contrast, Ltac scripts can be thought of as controlling just two simple kinds of mutable state. First, there is the current sequence of proof subgoals. Second, there is a partial assignment of discovered values to unification variables introduced by proof search (for instance, by [eauto], as we saw in the previous chapter). Crucially, _every mutation of this state can be undone_ during backtracking introduced by [match], [auto], and other built-in Ltac constructs. Ltac proof scripts have state, but it is purely local, and all changes to it are reversible, which is a very useful semantics for proof search. *)
adam@328 535
adamc@138 536
adamc@139 537 (** * Recursive Proof Search *)
adamc@139 538
adamc@139 539 (** 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 540
adam@431 541 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 542
adamc@141 543 (* begin thide *)
adamc@139 544 Ltac inster n :=
adamc@139 545 intuition;
adamc@139 546 match n with
adamc@139 547 | S ?n' =>
adamc@139 548 match goal with
adam@460 549 | [ H : forall x : ?T, _, y : ?T |- _ ] => generalize (H y); inster n'
adamc@139 550 end
adamc@139 551 end.
adamc@141 552 (* end thide *)
adamc@139 553
adam@507 554 (** The tactic begins by applying propositional simplification. Next, it checks if any chain length remains, failing if not. Otherwise, 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 555
adamc@139 556 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 557
adamc@139 558 Section test_inster.
adamc@139 559 Variable A : Set.
adamc@139 560 Variables P Q : A -> Prop.
adamc@139 561 Variable f : A -> A.
adamc@139 562 Variable g : A -> A -> A.
adamc@139 563
adamc@139 564 Hypothesis H1 : forall x y, P (g x y) -> Q (f x).
adamc@139 565
adam@328 566 Theorem test_inster : forall x, P (g x x) -> Q (f x).
adamc@220 567 inster 2.
adamc@139 568 Qed.
adamc@139 569
adamc@139 570 Hypothesis H3 : forall u v, P u /\ P v /\ u <> v -> P (g u v).
adamc@139 571 Hypothesis H4 : forall u, Q (f u) -> P u /\ P (f u).
adamc@139 572
adamc@139 573 Theorem test_inster2 : forall x y, x <> y -> P x -> Q (f y) -> Q (f x).
adamc@220 574 inster 3.
adamc@139 575 Qed.
adamc@139 576 End test_inster.
adamc@139 577
adam@431 578 (** 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, recalling the discussion at the end of the last section, 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 579
adam@431 580 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 581
adam@431 582 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.
adamc@140 583
adam@431 584 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 585
adamc@138 586 Definition imp (P1 P2 : Prop) := P1 -> P2.
adamc@140 587 Infix "-->" := imp (no associativity, at level 95).
adamc@140 588 Ltac imp := unfold imp; firstorder.
adamc@138 589
adamc@140 590 (** These lemmas about [imp] will be useful in the tactic that we will write. *)
adamc@138 591
adamc@138 592 Theorem and_True_prem : forall P Q,
adamc@138 593 (P /\ True --> Q)
adamc@138 594 -> (P --> Q).
adamc@138 595 imp.
adamc@138 596 Qed.
adamc@138 597
adamc@138 598 Theorem and_True_conc : forall P Q,
adamc@138 599 (P --> Q /\ True)
adamc@138 600 -> (P --> Q).
adamc@138 601 imp.
adamc@138 602 Qed.
adamc@138 603
adam@488 604 Theorem pick_prem1 : forall P Q R S,
adamc@138 605 (P /\ (Q /\ R) --> S)
adamc@138 606 -> ((P /\ Q) /\ R --> S).
adamc@138 607 imp.
adamc@138 608 Qed.
adamc@138 609
adam@488 610 Theorem pick_prem2 : forall P Q R S,
adamc@138 611 (Q /\ (P /\ R) --> S)
adamc@138 612 -> ((P /\ Q) /\ R --> S).
adamc@138 613 imp.
adamc@138 614 Qed.
adamc@138 615
adamc@138 616 Theorem comm_prem : forall P Q R,
adamc@138 617 (P /\ Q --> R)
adamc@138 618 -> (Q /\ P --> R).
adamc@138 619 imp.
adamc@138 620 Qed.
adamc@138 621
adam@488 622 Theorem pick_conc1 : forall P Q R S,
adamc@138 623 (S --> P /\ (Q /\ R))
adamc@138 624 -> (S --> (P /\ Q) /\ R).
adamc@138 625 imp.
adamc@138 626 Qed.
adamc@138 627
adam@488 628 Theorem pick_conc2 : forall P Q R S,
adamc@138 629 (S --> Q /\ (P /\ R))
adamc@138 630 -> (S --> (P /\ Q) /\ R).
adamc@138 631 imp.
adamc@138 632 Qed.
adamc@138 633
adamc@138 634 Theorem comm_conc : forall P Q R,
adamc@138 635 (R --> P /\ Q)
adamc@138 636 -> (R --> Q /\ P).
adamc@138 637 imp.
adamc@138 638 Qed.
adamc@138 639
adam@431 640 (** 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 641
adamc@138 642 Ltac search_prem tac :=
adamc@138 643 let rec search P :=
adamc@138 644 tac
adamc@138 645 || (apply and_True_prem; tac)
adamc@138 646 || match P with
adamc@138 647 | ?P1 /\ ?P2 =>
adam@488 648 (apply pick_prem1; search P1)
adam@488 649 || (apply pick_prem2; search P2)
adamc@138 650 end
adamc@138 651 in match goal with
adamc@138 652 | [ |- ?P /\ _ --> _ ] => search P
adamc@138 653 | [ |- _ /\ ?P --> _ ] => apply comm_prem; search P
adamc@138 654 | [ |- _ --> _ ] => progress (tac || (apply and_True_prem; tac))
adamc@138 655 end.
adamc@138 656
adam@460 657 (** 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. The %\index{tactics!progress}%[progress] tactical fails when its argument tactic succeeds without changing the current subgoal.
adamc@140 658
adam@507 659 The [search] function itself tries the same tricks as in the last case of the final [match], using the [||] operator as a shorthand for trying one tactic and then, if the first fails, trying another. Additionally, if neither works, it checks if [P] is a conjunction. If so, it calls itself recursively on each conjunct, first applying associativity/commutativity lemmas to maintain the goal-form invariant.
adamc@140 660
adamc@140 661 We will also want a dual function [search_conc], which does tree search through an [imp] conclusion. *)
adamc@140 662
adamc@138 663 Ltac search_conc tac :=
adamc@138 664 let rec search P :=
adamc@138 665 tac
adamc@138 666 || (apply and_True_conc; tac)
adamc@138 667 || match P with
adamc@138 668 | ?P1 /\ ?P2 =>
adam@488 669 (apply pick_conc1; search P1)
adam@488 670 || (apply pick_conc2; search P2)
adamc@138 671 end
adamc@138 672 in match goal with
adamc@138 673 | [ |- _ --> ?P /\ _ ] => search P
adamc@138 674 | [ |- _ --> _ /\ ?P ] => apply comm_conc; search P
adamc@138 675 | [ |- _ --> _ ] => progress (tac || (apply and_True_conc; tac))
adamc@138 676 end.
adamc@138 677
adamc@140 678 (** 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 679
adam@328 680 (* begin thide *)
adamc@138 681 Theorem False_prem : forall P Q,
adamc@138 682 False /\ P --> Q.
adamc@138 683 imp.
adamc@138 684 Qed.
adamc@138 685
adamc@138 686 Theorem True_conc : forall P Q : Prop,
adamc@138 687 (P --> Q)
adamc@138 688 -> (P --> True /\ Q).
adamc@138 689 imp.
adamc@138 690 Qed.
adamc@138 691
adamc@138 692 Theorem Match : forall P Q R : Prop,
adamc@138 693 (Q --> R)
adamc@138 694 -> (P /\ Q --> P /\ R).
adamc@138 695 imp.
adamc@138 696 Qed.
adamc@138 697
adamc@138 698 Theorem ex_prem : forall (T : Type) (P : T -> Prop) (Q R : Prop),
adamc@138 699 (forall x, P x /\ Q --> R)
adamc@138 700 -> (ex P /\ Q --> R).
adamc@138 701 imp.
adamc@138 702 Qed.
adamc@138 703
adamc@138 704 Theorem ex_conc : forall (T : Type) (P : T -> Prop) (Q R : Prop) x,
adamc@138 705 (Q --> P x /\ R)
adamc@138 706 -> (Q --> ex P /\ R).
adamc@138 707 imp.
adamc@138 708 Qed.
adamc@138 709
adam@465 710 (** We will also want a "base case" lemma for finishing proofs where cancellation has removed every constituent of the conclusion. *)
adamc@140 711
adamc@138 712 Theorem imp_True : forall P,
adamc@138 713 P --> True.
adamc@138 714 imp.
adamc@138 715 Qed.
adamc@138 716
adam@386 717 (** 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 %\index{tactics!simple apply}%[simple apply] in place of [apply] to use a simpler, less expensive unification algorithm. *)
adamc@140 718
adamc@138 719 Ltac matcher :=
adamc@138 720 intros;
adam@411 721 repeat search_prem ltac:(simple apply False_prem || (simple apply ex_prem; intro));
adam@411 722 repeat search_conc ltac:(simple apply True_conc || simple eapply ex_conc
adam@411 723 || search_prem ltac:(simple apply Match));
adamc@204 724 try simple apply imp_True.
adamc@141 725 (* end thide *)
adamc@140 726
adamc@140 727 (** Our tactic succeeds at proving a simple example. *)
adamc@138 728
adamc@138 729 Theorem t2 : forall P Q : Prop,
adamc@138 730 Q /\ (P /\ False) /\ P --> P /\ Q.
adamc@138 731 matcher.
adamc@138 732 Qed.
adamc@138 733
adamc@140 734 (** In the generated proof, we find a trace of the workings of the search tactics. *)
adamc@140 735
adamc@140 736 Print t2.
adamc@220 737 (** %\vspace{-.15in}% [[
adamc@140 738 t2 =
adamc@140 739 fun P Q : Prop =>
adam@488 740 comm_prem (pick_prem1 (pick_prem2 (False_prem (P:=P /\ P /\ Q) (P /\ Q))))
adamc@140 741 : forall P Q : Prop, Q /\ (P /\ False) /\ P --> P /\ Q
adamc@220 742 ]]
adamc@140 743
adam@460 744 %\smallskip{}%We can also see that [matcher] is well-suited for cases where some human intervention is needed after the automation finishes. *)
adamc@140 745
adamc@138 746 Theorem t3 : forall P Q R : Prop,
adamc@138 747 P /\ Q --> Q /\ R /\ P.
adamc@138 748 matcher.
adamc@140 749 (** [[
adamc@140 750 ============================
adamc@140 751 True --> R
adamc@220 752
adamc@140 753 ]]
adamc@140 754
adam@328 755 Our tactic canceled those conjuncts that it was able to cancel, leaving a simplified subgoal for us, much as [intuition] does. *)
adamc@220 756
adamc@138 757 Abort.
adamc@138 758
adam@328 759 (** 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. *)
adamc@140 760
adamc@138 761 Theorem t4 : forall (P : nat -> Prop) Q, (exists x, P x /\ Q) --> Q /\ (exists x, P x).
adamc@138 762 matcher.
adamc@138 763 Qed.
adamc@138 764
adamc@140 765 Print t4.
adamc@220 766 (** %\vspace{-.15in}% [[
adamc@140 767 t4 =
adamc@140 768 fun (P : nat -> Prop) (Q : Prop) =>
adamc@140 769 and_True_prem
adamc@140 770 (ex_prem (P:=fun x : nat => P x /\ Q)
adamc@140 771 (fun x : nat =>
adam@488 772 pick_prem2
adamc@140 773 (Match (P:=Q)
adamc@140 774 (and_True_conc
adamc@140 775 (ex_conc (fun x0 : nat => P x0) x
adamc@140 776 (Match (P:=P x) (imp_True (P:=True))))))))
adamc@140 777 : forall (P : nat -> Prop) (Q : Prop),
adamc@140 778 (exists x : nat, P x /\ Q) --> Q /\ (exists x : nat, P x)
adam@302 779 ]]
adam@386 780
adam@386 781 This proof term is a mouthful, and we can be glad that we did not build it manually! *)
adamc@234 782
adamc@234 783
adamc@234 784 (** * Creating Unification Variables *)
adamc@234 785
adam@398 786 (** A final useful ingredient in tactic crafting is the ability to allocate new unification variables explicitly. Tactics like [eauto] introduce unification variables internally to support flexible proof search. While [eauto] and its relatives do _backward_ reasoning, we often want to do similar _forward_ reasoning, where unification variables can be useful for similar reasons.
adamc@234 787
adam@465 788 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 instantiations 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 789
adamc@234 790 Before we are ready to write a tactic, we can try out its ingredients one at a time. *)
adamc@234 791
adamc@234 792 Theorem t5 : (forall x : nat, S x > x) -> 2 > 1.
adamc@234 793 intros.
adamc@234 794
adamc@234 795 (** [[
adamc@234 796 H : forall x : nat, S x > x
adamc@234 797 ============================
adamc@234 798 2 > 1
adamc@234 799
adamc@234 800 ]]
adamc@234 801
adam@328 802 To instantiate [H] generically, we first need to name the value to be used for [x].%\index{tactics!evar}% *)
adamc@234 803
adamc@234 804 evar (y : nat).
adamc@234 805
adamc@234 806 (** [[
adamc@234 807 H : forall x : nat, S x > x
adamc@234 808 y := ?279 : nat
adamc@234 809 ============================
adamc@234 810 2 > 1
adamc@234 811
adamc@234 812 ]]
adamc@234 813
adam@328 814 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.). *)
adamc@234 815
adam@328 816 let y' := eval unfold y in y in
adam@386 817 clear y; specialize (H y').
adamc@234 818
adamc@234 819 (** [[
adam@386 820 H : S ?279 > ?279
adamc@234 821 ============================
adam@386 822 2 > 1
adamc@234 823
adamc@234 824 ]]
adamc@234 825
adam@386 826 Our instantiation was successful. We can finish the proof by using [apply]'s unification to figure out the proper value of [?279]. *)
adamc@234 827
adamc@234 828 apply H.
adamc@234 829 Qed.
adamc@234 830
adamc@234 831 (** Now we can write a tactic that encapsulates the pattern we just employed, instantiating all quantifiers of a particular hypothesis. *)
adamc@234 832
adam@534 833 (* begin hide *)
adam@534 834 Definition red_herring := O.
adam@534 835 (* end hide *)
adamc@234 836 Ltac insterU H :=
adamc@234 837 repeat match type of H with
adamc@234 838 | forall x : ?T, _ =>
adamc@234 839 let x := fresh "x" in
adamc@234 840 evar (x : T);
adam@328 841 let x' := eval unfold x in x in
adam@328 842 clear x; specialize (H x')
adamc@234 843 end.
adamc@234 844
adamc@234 845 Theorem t5' : (forall x : nat, S x > x) -> 2 > 1.
adamc@234 846 intro H; insterU H; apply H.
adamc@234 847 Qed.
adamc@234 848
adam@328 849 (** 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. *)
adamc@234 850
adamc@234 851 Ltac insterKeep H :=
adamc@234 852 let H' := fresh "H'" in
adamc@234 853 generalize H; intro H'; insterU H'.
adamc@234 854
adamc@234 855 Section t6.
adamc@234 856 Variables A B : Type.
adamc@234 857 Variable P : A -> B -> Prop.
adamc@234 858 Variable f : A -> A -> A.
adamc@234 859 Variable g : B -> B -> B.
adamc@234 860
adamc@234 861 Hypothesis H1 : forall v, exists u, P v u.
adamc@234 862 Hypothesis H2 : forall v1 u1 v2 u2,
adamc@234 863 P v1 u1
adamc@234 864 -> P v2 u2
adamc@234 865 -> P (f v1 v2) (g u1 u2).
adamc@234 866
adamc@234 867 Theorem t6 : forall v1 v2, exists u1, exists u2, P (f v1 v2) (g u1 u2).
adamc@234 868 intros.
adamc@234 869
adam@328 870 (** 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. *)
adamc@234 871
adamc@234 872 do 2 insterKeep H1.
adamc@234 873
adamc@234 874 (** Our proof state is extended with two generic instances of [H1].
adamc@234 875
adamc@234 876 [[
adamc@234 877 H' : exists u : B, P ?4289 u
adamc@234 878 H'0 : exists u : B, P ?4288 u
adamc@234 879 ============================
adamc@234 880 exists u1 : B, exists u2 : B, P (f v1 v2) (g u1 u2)
adamc@234 881
adamc@234 882 ]]
adamc@234 883
adam@386 884 Normal [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.) *)
adamc@234 885
adamc@234 886 repeat match goal with
adamc@234 887 | [ H : ex _ |- _ ] => destruct H
adamc@234 888 end.
adamc@234 889
adamc@234 890 (** Now the goal is simple enough to solve by logic programming. *)
adamc@234 891
adamc@234 892 eauto.
adamc@234 893 Qed.
adamc@234 894 End t6.
adamc@234 895
adamc@234 896 (** 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 897
adamc@234 898 Section t7.
adamc@234 899 Variables A B : Type.
adamc@234 900 Variable Q : A -> Prop.
adamc@234 901 Variable P : A -> B -> Prop.
adamc@234 902 Variable f : A -> A -> A.
adamc@234 903 Variable g : B -> B -> B.
adamc@234 904
adamc@234 905 Hypothesis H1 : forall v, Q v -> exists u, P v u.
adamc@234 906 Hypothesis H2 : forall v1 u1 v2 u2,
adamc@234 907 P v1 u1
adamc@234 908 -> P v2 u2
adamc@234 909 -> P (f v1 v2) (g u1 u2).
adamc@234 910
adam@297 911 Theorem t7 : forall v1 v2, Q v1 -> Q v2 -> exists u1, exists u2, P (f v1 v2) (g u1 u2).
adamc@234 912 intros; do 2 insterKeep H1;
adamc@234 913 repeat match goal with
adamc@234 914 | [ H : ex _ |- _ ] => destruct H
adamc@234 915 end; eauto.
adamc@234 916
adamc@234 917 (** This proof script does not hit any errors until the very end, when an error message like this one is displayed.
adamc@234 918
adam@328 919 <<
adamc@234 920 No more subgoals but non-instantiated existential variables :
adamc@234 921 Existential 1 =
adam@328 922 >>
adam@445 923 %\vspace{-.35in}%[[
adamc@234 924 ?4384 : [A : Type
adamc@234 925 B : Type
adamc@234 926 Q : A -> Prop
adamc@234 927 P : A -> B -> Prop
adamc@234 928 f : A -> A -> A
adamc@234 929 g : B -> B -> B
adamc@234 930 H1 : forall v : A, Q v -> exists u : B, P v u
adamc@234 931 H2 : forall (v1 : A) (u1 : B) (v2 : A) (u2 : B),
adamc@234 932 P v1 u1 -> P v2 u2 -> P (f v1 v2) (g u1 u2)
adamc@234 933 v1 : A
adamc@234 934 v2 : A
adamc@234 935 H : Q v1
adamc@234 936 H0 : Q v2
adamc@234 937 H' : Q v2 -> exists u : B, P v2 u |- Q v2]
adamc@234 938 ]]
adamc@234 939
adam@431 940 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 941
adamc@234 942 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 943
adamc@234 944 Abort.
adamc@234 945 End t7.
adamc@234 946
adamc@234 947 Reset insterU.
adam@534 948 (* begin hide *)
adam@534 949 Reset red_herring.
adam@534 950 (* end hide *)
adamc@234 951
adam@328 952 (** 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. *)
adamc@234 953
adamc@234 954 Ltac insterU tac H :=
adamc@234 955 repeat match type of H with
adamc@234 956 | forall x : ?T, _ =>
adamc@234 957 match type of T with
adamc@234 958 | Prop =>
adamc@234 959 (let H' := fresh "H'" in
adam@328 960 assert (H' : T) by solve [ tac ];
adam@328 961 specialize (H H'); clear H')
adamc@234 962 || fail 1
adamc@234 963 | _ =>
adamc@234 964 let x := fresh "x" in
adamc@234 965 evar (x : T);
adam@328 966 let x' := eval unfold x in x in
adam@328 967 clear x; specialize (H x')
adamc@234 968 end
adamc@234 969 end.
adamc@234 970
adamc@234 971 Ltac insterKeep tac H :=
adamc@234 972 let H' := fresh "H'" in
adamc@234 973 generalize H; intro H'; insterU tac H'.
adamc@234 974
adamc@234 975 Section t7.
adamc@234 976 Variables A B : Type.
adamc@234 977 Variable Q : A -> Prop.
adamc@234 978 Variable P : A -> B -> Prop.
adamc@234 979 Variable f : A -> A -> A.
adamc@234 980 Variable g : B -> B -> B.
adamc@234 981
adamc@234 982 Hypothesis H1 : forall v, Q v -> exists u, P v u.
adamc@234 983 Hypothesis H2 : forall v1 u1 v2 u2,
adamc@234 984 P v1 u1
adamc@234 985 -> P v2 u2
adamc@234 986 -> P (f v1 v2) (g u1 u2).
adamc@234 987
adam@545 988 Theorem t7 : forall v1 v2, Q v1 -> Q v2 -> exists u1, exists u2, P (f v1 v2) (g u1 u2).
adamc@234 989
adamc@234 990 (** 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 991
adamc@234 992 intros; do 2 insterKeep ltac:(idtac; match goal with
adamc@234 993 | [ H : Q ?v |- _ ] =>
adamc@234 994 match goal with
adamc@234 995 | [ _ : context[P v _] |- _ ] => fail 1
adamc@234 996 | _ => apply H
adamc@234 997 end
adamc@234 998 end) H1;
adamc@234 999 repeat match goal with
adamc@234 1000 | [ H : ex _ |- _ ] => destruct H
adamc@234 1001 end; eauto.
adamc@234 1002 Qed.
adamc@234 1003 End t7.
adamc@234 1004
adamc@234 1005 (** It is often useful to instantiate existential variables explicitly. A built-in tactic provides one way of doing so. *)
adamc@234 1006
adamc@234 1007 Theorem t8 : exists p : nat * nat, fst p = 3.
adamc@234 1008 econstructor; instantiate (1 := (3, 2)); reflexivity.
adamc@234 1009 Qed.
adamc@234 1010
adam@460 1011 (** 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 1012
adam@328 1013 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. *)
adamc@234 1014
adamc@234 1015 Ltac equate x y :=
adam@460 1016 let dummy := constr:(eq_refl x : x = y) in idtac.
adamc@234 1017
adam@460 1018 (** This tactic fails if it is not possible to prove [x = y] by [eq_refl]. We check the proof only for its unification side effects, ignoring the associated variable [dummy]. With [equate], we can build a less brittle version of the prior example. *)
adamc@234 1019
adamc@234 1020 Theorem t9 : exists p : nat * nat, fst p = 3.
adamc@234 1021 econstructor; match goal with
adamc@234 1022 | [ |- fst ?x = 3 ] => equate x (3, 2)
adamc@234 1023 end; reflexivity.
adamc@234 1024 Qed.
adam@386 1025
adam@386 1026 (** This technique is even more useful within recursive and iterative tactics that are meant to solve broad classes of goals. *)