comparison src/Match.v @ 288:b653e6b19b6d

PC comments for Match
author Adam Chlipala <adam@chlipala.net>
date Wed, 10 Nov 2010 14:46:27 -0500
parents 82eae7bc91ea
children b441010125d4
comparison
equal deleted inserted replaced
287:be571572c088 288:b653e6b19b6d
1 (* Copyright (c) 2008-2009, Adam Chlipala 1 (* Copyright (c) 2008-2010, Adam Chlipala
2 * 2 *
3 * This work is licensed under a 3 * This work is licensed under a
4 * Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 4 * Creative Commons Attribution-Noncommercial-No Derivative Works 3.0
5 * Unported License. 5 * Unported License.
6 * The license text is available at: 6 * The license text is available at:
26 26
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. 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.
28 28
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. 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.
30 30
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." *) 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.#"#%''% *)
32 32
33 33
34 (** * Hint Databases *) 34 (** * Hint Databases *)
35 35
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. 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.
37 37
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. 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.
39 39
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. *) 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. *)
41 41
54 Theorem bool_neq : true <> false. 54 Theorem bool_neq : true <> false.
55 auto. 55 auto.
56 Qed. 56 Qed.
57 (* end thide *) 57 (* end thide *)
58 58
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. 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.
60 60
61 [Extern] hints may be implemented with the full Ltac language. This example shows a case where a hint uses a [match]. *) 61 [Extern] hints may be implemented with the full Ltac language. This example shows a case where a hint uses a [match]. *)
62 62
63 Section forall_and. 63 Section forall_and.
64 Variable A : Set. 64 Variable A : Set.
115 115
116 Lemma f_f_f : forall x, f (f (f x)) = f x. 116 Lemma f_f_f : forall x, f (f (f x)) = f x.
117 intros; autorewrite with my_db; reflexivity. 117 intros; autorewrite with my_db; reflexivity.
118 Qed. 118 Qed.
119 119
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: *) 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: *)
121 121
122 Section garden_path. 122 Section garden_path.
123 Variable g : A -> A. 123 Variable g : A -> A.
124 Hypothesis f_g : forall x, f x = g x. 124 Hypothesis f_g : forall x, f x = g x.
125 Hint Rewrite f_g : my_db. 125 Hint Rewrite f_g : my_db.
131 g (g (g x)) = g x 131 g (g (g x)) = g x
132 ]] *) 132 ]] *)
133 133
134 Abort. 134 Abort.
135 135
136 (** 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. *) 136 (** 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. *)
137 137
138 Reset garden_path. 138 Reset garden_path.
139 139
140 (** [autorewrite] works with quantified equalities that include additional premises, but we must be careful to avoid similar incorrect rewritings. *) 140 (** [autorewrite] also works with quantified equalities that include additional premises, but we must be careful to avoid similar incorrect rewritings. *)
141 141
142 Section garden_path. 142 Section garden_path.
143 Variable P : A -> Prop. 143 Variable P : A -> Prop.
144 Variable g : A -> A. 144 Variable g : A -> A.
145 Hypothesis f_g : forall x, P x -> f x = g x. 145 Hypothesis f_g : forall x, P x -> f x = g x.
164 164
165 (** The inappropriate rule fired the same three times as before, even though we know we will not be able to prove the premises. *) 165 (** The inappropriate rule fired the same three times as before, even though we know we will not be able to prove the premises. *)
166 166
167 Reset garden_path. 167 Reset garden_path.
168 168
169 (** Our final, successful, attempt uses an extra argument to [Hint Rewrite] that specifies a tactic to apply to generated premises. *) 169 (** 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. *)
170 170
171 Section garden_path. 171 Section garden_path.
172 Variable P : A -> Prop. 172 Variable P : A -> Prop.
173 Variable g : A -> A. 173 Variable g : A -> A.
174 Hypothesis f_g : forall x, P x -> f x = g x. 174 Hypothesis f_g : forall x, P x -> f x = g x.
268 (* begin thide *) 268 (* begin thide *)
269 intros; repeat find_if_inside; reflexivity. 269 intros; repeat find_if_inside; reflexivity.
270 Qed. 270 Qed.
271 (* end thide *) 271 (* end thide *)
272 272
273 (** Many decision procedures can be coded in Ltac via "[repeat match] loops." For instance, we can implement a subset of the functionality of [tauto]. *) 273 (** Many decision procedures can be coded in Ltac via %``%#"#[repeat match] loops.#"#%''% For instance, we can implement a subset of the functionality of [tauto]. *)
274 274
275 (* begin thide *) 275 (* begin thide *)
276 Ltac my_tauto := 276 Ltac my_tauto :=
277 repeat match goal with 277 repeat match goal with
278 | [ H : ?P |- ?P ] => exact H 278 | [ H : ?P |- ?P ] => exact H
291 end. 291 end.
292 (* end thide *) 292 (* end thide *)
293 293
294 (** 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. 294 (** 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.
295 295
296 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]. 296 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].
297 297
298 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]. *) 298 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]. *)
299 299
300 Section propositional. 300 Section propositional.
301 Variables P Q R : Prop. 301 Variables P Q R : Prop.
331 Theorem m2 : forall P Q R : Prop, P -> Q -> R -> Q. 331 Theorem m2 : forall P Q R : Prop, P -> Q -> R -> Q.
332 intros; match goal with 332 intros; match goal with
333 | [ H : _ |- _ ] => idtac H 333 | [ H : _ |- _ ] => idtac H
334 end. 334 end.
335 335
336 (** 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: *) 336 (** 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: *)
337 337
338 (* begin thide *) 338 (* begin thide *)
339 match goal with 339 match goal with
340 | [ H : _ |- _ ] => exact H 340 | [ H : _ |- _ ] => exact H
341 end. 341 end.
356 | _ => idtac 356 | _ => idtac
357 end 357 end
358 end. 358 end.
359 (* end thide *) 359 (* end thide *)
360 360
361 (** 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. 361 (** 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.
362 362
363 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. 363 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.
364 364
365 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. 365 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.
366 366
482 ]] *) 482 ]] *)
483 483
484 Abort. 484 Abort.
485 (* end thide *) 485 (* end thide *)
486 486
487 (** 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. 487 (** 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.
488 488
489 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. 489 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.
490 490
491 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. *) 491 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. *)
492 492
493 493
494 (** * Functional Programming in Ltac *) 494 (** * Functional Programming in Ltac *)
495 495
496 (* EX: Write a list length function in Ltac. *) 496 (* EX: Write a list length function in Ltac. *)
521 521
522 Error: The reference S was not found in the current environment 522 Error: The reference S was not found in the current environment
523 523
524 ]] 524 ]]
525 525
526 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. *) 526 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. *)
527 527
528 (* begin thide *) 528 (* begin thide *)
529 Ltac length ls := 529 Ltac length ls :=
530 match ls with 530 match ls with
531 | nil => O 531 | nil => O
580 580
581 (* begin thide *) 581 (* begin thide *)
582 Ltac map T f := 582 Ltac map T f :=
583 let rec map' ls := 583 let rec map' ls :=
584 match ls with 584 match ls with
585 | nil => constr:(@nil T) 585 | nil => constr:( @nil T)
586 | ?x :: ?ls' => 586 | ?x :: ?ls' =>
587 let x' := f x in 587 let x' := f x in
588 let ls'' := map' ls' in 588 let ls'' := map' ls' in
589 constr:(x' :: ls'') 589 constr:( x' :: ls'')
590 end in 590 end in
591 map'. 591 map'.
592 592
593 (** 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'')]. 593 (** 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'')].
594 594
595 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]. *) 595 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]. *)
596 596
597 Goal False. 597 Goal False.
598 let ls := map (nat * nat)%type ltac:(fun x => constr:(x, x)) (1 :: 2 :: 3 :: nil) in 598 let ls := map (nat * nat)%type ltac:(fun x => constr:( x, x)) (1 :: 2 :: 3 :: nil) in
599 pose ls. 599 pose ls.
600 (** [[ 600 (** [[
601 l := (1, 1) :: (2, 2) :: (3, 3) :: nil : list (nat * nat) 601 l := (1, 1) :: (2, 2) :: (3, 3) :: nil : list (nat * nat)
602 ============================ 602 ============================
603 False 603 False
609 609
610 (** * Recursive Proof Search *) 610 (** * Recursive Proof Search *)
611 611
612 (** 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. 612 (** 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.
613 613
614 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]. *) 614 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]. *)
615 615
616 (* begin thide *) 616 (* begin thide *)
617 Ltac inster n := 617 Ltac inster n :=
618 intuition; 618 intuition;
619 match n with 619 match n with
646 Theorem test_inster2 : forall x y, x <> y -> P x -> Q (f y) -> Q (f x). 646 Theorem test_inster2 : forall x y, x <> y -> P x -> Q (f y) -> Q (f x).
647 inster 3. 647 inster 3.
648 Qed. 648 Qed.
649 End test_inster. 649 End test_inster.
650 650
651 (** 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. 651 (** 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.
652 652
653 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. 653 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.
654 654
655 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. 655 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.
656 656
657 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. *) 657 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. *)
658 658
659 Definition imp (P1 P2 : Prop) := P1 -> P2. 659 Definition imp (P1 P2 : Prop) := P1 -> P2.
660 Infix "-->" := imp (no associativity, at level 95). 660 Infix "-->" := imp (no associativity, at level 95).
661 Ltac imp := unfold imp; firstorder. 661 Ltac imp := unfold imp; firstorder.
662 662
708 (R --> P /\ Q) 708 (R --> P /\ Q)
709 -> (R --> Q /\ P). 709 -> (R --> Q /\ P).
710 imp. 710 imp.
711 Qed. 711 Qed.
712 712
713 (** 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. *) 713 (** 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. *)
714 714
715 (* begin thide *) 715 (* begin thide *)
716 Ltac search_prem tac := 716 Ltac search_prem tac :=
717 let rec search P := 717 let rec search P :=
718 tac 718 tac
778 (Q --> P x /\ R) 778 (Q --> P x /\ R)
779 -> (Q --> ex P /\ R). 779 -> (Q --> ex P /\ R).
780 imp. 780 imp.
781 Qed. 781 Qed.
782 782
783 (** We will also want a "base case" lemma for finishing proofs where cancelation has removed every constituent of the conclusion. *) 783 (** We will also want a %``%#"#base case#"#%''% lemma for finishing proofs where cancelation has removed every constituent of the conclusion. *)
784 784
785 Theorem imp_True : forall P, 785 Theorem imp_True : forall P,
786 P --> True. 786 P --> True.
787 imp. 787 imp.
788 Qed. 788 Qed.
789 789
790 (** 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. *) 790 (** 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. *)
791 791
792 Ltac matcher := 792 Ltac matcher :=
793 intros; 793 intros;
794 repeat search_prem ltac:(simple apply False_prem || (simple apply ex_prem; intro)); 794 repeat search_prem ltac:( simple apply False_prem || ( simple apply ex_prem; intro));
795 repeat search_conc ltac:(simple apply True_conc || simple eapply ex_conc 795 repeat search_conc ltac:( simple apply True_conc || simple eapply ex_conc
796 || search_prem ltac:(simple apply Match)); 796 || search_prem ltac:( simple apply Match));
797 try simple apply imp_True. 797 try simple apply imp_True.
798 (* end thide *) 798 (* end thide *)
799 799
800 (** Our tactic succeeds at proving a simple example. *) 800 (** Our tactic succeeds at proving a simple example. *)
801 801
1014 H0 : Q v2 1014 H0 : Q v2
1015 H' : Q v2 -> exists u : B, P v2 u |- Q v2] 1015 H' : Q v2 -> exists u : B, P v2 u |- Q v2]
1016 1016
1017 ]] 1017 ]]
1018 1018
1019 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. 1019 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.
1020 1020
1021 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]. *) 1021 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]. *)
1022 1022
1023 Abort. 1023 Abort.
1024 End t7. 1024 End t7.