ImpSimple Imperative Programs
Set Warnings "-notation-overridden,-parsing".
From Coq Require Import Bool.Bool.
From Coq Require Import Init.Nat.
From Coq Require Import Arith.Arith.
From Coq Require Import Arith.EqNat.
From Coq Require Import Lia.
From Coq Require Import Lists.List.
From Coq Require Import Strings.String.
Import ListNotations.
From LF Require Import Maps.
Arithmetic and Boolean Expressions
Module AExp.
These two definitions specify the abstract syntax of
arithmetic and boolean expressions.
Inductive aexp : Type :=
| ANum (n : nat)
| APlus (a1 a2 : aexp)
| AMinus (a1 a2 : aexp)
| AMult (a1 a2 : aexp).
Inductive bexp : Type :=
| BTrue
| BFalse
| BEq (a1 a2 : aexp)
| BLe (a1 a2 : aexp)
| BNot (b : bexp)
| BAnd (b1 b2 : bexp).
In this chapter, we'll mostly elide the translation from the
concrete syntax that a programmer would actually write to these
abstract syntax trees -- the process that, for example, would
translate the string "1 + 2 * 3" to the AST
APlus (ANum 1) (AMult (ANum 2) (ANum 3)).
The optional chapter ImpParser develops a simple lexical
analyzer and parser that can perform this translation. You do
not need to understand that chapter to understand this one, but
if you haven't already taken a course where these techniques are
covered (e.g., a compilers course) you may want to skim it.
For comparison, here's a conventional BNF (Backus-Naur Form)
grammar defining the same abstract syntax:
a := nat
| a + a
| a - a
| a * a
b := true
| false
| a = a
| a <= a
| ~ b
| b && b
Compared to the Coq version above...
It's good to be comfortable with both sorts of notations: informal
ones for communicating between humans and formal ones for carrying
out implementations and proofs.
- The BNF is more informal -- for example, it gives some
suggestions about the surface syntax of expressions (like the
fact that the addition operation is written with an infix
+) while leaving other aspects of lexical analysis and
parsing (like the relative precedence of +, -, and
*, the use of parens to group subexpressions, etc.)
unspecified. Some additional information -- and human
intelligence -- would be required to turn this description
into a formal definition, e.g., for implementing a compiler.
The Coq version consistently omits all this information and concentrates on the abstract syntax only.
- Conversely, the BNF version is lighter and easier to read.
Its informality makes it flexible, a big advantage in
situations like discussions at the blackboard, where
conveying general ideas is more important than getting every
detail nailed down precisely.
Indeed, there are dozens of BNF-like notations and people switch freely among them, usually without bothering to say which kind of BNF they're using because there is no need to: a rough-and-ready informal understanding is all that's important.
Fixpoint aeval (a : aexp) : nat :=
match a with
| ANum n => n
| APlus a1 a2 => (aeval a1) + (aeval a2)
| AMinus a1 a2 => (aeval a1) - (aeval a2)
| AMult a1 a2 => (aeval a1) * (aeval a2)
end.
Example test_aeval1:
aeval (APlus (ANum 2) (ANum 2)) = 4.
Proof. reflexivity. Qed.
Similarly, evaluating a boolean expression yields a boolean.
Fixpoint beval (b : bexp) : bool :=
match b with
| BTrue => true
| BFalse => false
| BEq a1 a2 => (aeval a1) =? (aeval a2)
| BLe a1 a2 => (aeval a1) <=? (aeval a2)
| BNot b1 => negb (beval b1)
| BAnd b1 b2 => andb (beval b1) (beval b2)
end.
Optimization
Fixpoint optimize_0plus (a:aexp) : aexp :=
match a with
| ANum n => ANum n
| APlus (ANum 0) e2 => optimize_0plus e2
| APlus e1 e2 => APlus (optimize_0plus e1) (optimize_0plus e2)
| AMinus e1 e2 => AMinus (optimize_0plus e1) (optimize_0plus e2)
| AMult e1 e2 => AMult (optimize_0plus e1) (optimize_0plus e2)
end.
To make sure our optimization is doing the right thing we
can test it on some examples and see if the output looks OK.
Example test_optimize_0plus:
optimize_0plus (APlus (ANum 2)
(APlus (ANum 0)
(APlus (ANum 0) (ANum 1))))
= APlus (ANum 2) (ANum 1).
Proof. reflexivity. Qed.
But if we want to be sure the optimization is correct --
i.e., that evaluating an optimized expression gives the same
result as the original -- we should prove it.
Theorem optimize_0plus_sound: forall a,
aeval (optimize_0plus a) = aeval a.
Proof.
intros a. induction a.
- reflexivity.
- destruct a1 eqn:Ea1.
+ destruct n eqn:En.
* simpl. apply IHa2.
* simpl. rewrite IHa2. reflexivity.
+
simpl. simpl in IHa1. rewrite IHa1.
rewrite IHa2. reflexivity.
+
simpl. simpl in IHa1. rewrite IHa1.
rewrite IHa2. reflexivity.
+
simpl. simpl in IHa1. rewrite IHa1.
rewrite IHa2. reflexivity.
-
simpl. rewrite IHa1. rewrite IHa2. reflexivity.
-
simpl. rewrite IHa1. rewrite IHa2. reflexivity. Qed.
Coq Automation
Tacticals
The try Tactical
Theorem silly1 : forall ae, aeval ae = aeval ae.
Proof. try reflexivity. Qed.
Theorem silly2 : forall (P : Prop), P -> P.
Proof.
intros P HP.
try reflexivity. apply HP. Qed.
There is no real reason to use try in completely manual
proofs like these, but it is very useful for doing automated
proofs in conjunction with the ; tactical, which we show
next.
The ; Tactical (Simple Form)
Lemma foo : forall n, 0 <=? n = true.
Proof.
intros.
destruct n.
- simpl. reflexivity.
- simpl. reflexivity.
Qed.
We can simplify this proof using the ; tactical:
Lemma foo' : forall n, 0 <=? n = true.
Proof.
intros.
destruct n;
simpl;
reflexivity.
Qed.
Using try and ; together, we can get rid of the repetition in
the proof that was bothering us a little while ago.
Theorem optimize_0plus_sound': forall a,
aeval (optimize_0plus a) = aeval a.
Proof.
intros a.
induction a;
try (simpl; rewrite IHa1; rewrite IHa2; reflexivity).
- reflexivity.
-
destruct a1 eqn:Ea1;
try (simpl; simpl in IHa1; rewrite IHa1;
rewrite IHa2; reflexivity).
+ destruct n eqn:En;
simpl; rewrite IHa2; reflexivity. Qed.
Coq experts often use this "...; try... " idiom after a tactic
like induction to take care of many similar cases all at once.
Naturally, this practice has an analog in informal proofs. For
example, here is an informal proof of the optimization theorem
that matches the structure of the formal one:
Theorem: For all arithmetic expressions a,
aeval (optimize_0plus a) = aeval a.
Proof: By induction on a. Most cases follow directly from the
IH. The remaining cases are as follows:
However, this proof can still be improved: the first case (for
a = ANum n) is very trivial -- even more trivial than the cases
that we said simply followed from the IH -- yet we have chosen to
write it out in full. It would be better and clearer to drop it
and just say, at the top, "Most cases are either immediate or
direct from the IH. The only interesting case is the one for
APlus..." We can make the same improvement in our formal proof
too. Here's how it looks:
- Suppose a = ANum n for some n. We must show
aeval (optimize_0plus (ANum n)) = aeval (ANum n).This is immediate from the definition of optimize_0plus.
- Suppose a = APlus a1 a2 for some a1 and a2. We must
show
aeval (optimize_0plus (APlus a1 a2)) = aeval (APlus a1 a2).Consider the possible forms of a1. For most of them, optimize_0plus simply calls itself recursively for the subexpressions and rebuilds a new expression of the same form as a1; in these cases, the result follows directly from the IH.The interesting case is when a1 = ANum n for some n. If n = 0, thenoptimize_0plus (APlus a1 a2) = optimize_0plus a2and the IH for a2 is exactly what we need. On the other hand, if n = S n' for some n', then again optimize_0plus simply calls itself recursively, and the result follows from the IH. ☐
Theorem optimize_0plus_sound'': forall a,
aeval (optimize_0plus a) = aeval a.
Proof.
intros a.
induction a;
try (simpl; rewrite IHa1; rewrite IHa2; reflexivity);
try reflexivity.
-
destruct a1; try (simpl; simpl in IHa1; rewrite IHa1;
rewrite IHa2; reflexivity).
+ destruct n;
simpl; rewrite IHa2; reflexivity. Qed.
The ; Tactical (General Form)
The repeat Tactical
Theorem In10 : In 10 [1;2;3;4;5;6;7;8;9;10].
Proof.
repeat (try (left; reflexivity); right).
Qed.
The tactic repeat T never fails: if the tactic T doesn't apply
to the original goal, then repeat still succeeds without changing
the original goal (i.e., it repeats zero times).
Theorem In10' : In 10 [1;2;3;4;5;6;7;8;9;10].
Proof.
repeat simpl.
repeat (left; reflexivity).
repeat (right; try (left; reflexivity)).
Qed.
The tactic repeat T also does not have any upper bound on the
number of times it applies T. If T is a tactic that always
succeeds (and makes progress), then repeat T will loop forever.
Theorem repeat_loop : forall (m n : nat),
m + n = n + m.
Proof.
intros m n.
Abort.
While evaluation in Coq's term language, Gallina, is guaranteed to
terminate, tactic evaluation is not! This does not affect Coq's
logical consistency, however, since the job of repeat and other
tactics is to guide Coq in constructing proofs; if the
construction process diverges (i.e., it does not terminate), this
simply means that we have failed to construct a proof, not that we
have constructed a wrong one.
Since the optimize_0plus transformation doesn't change the value
of aexps, we should be able to apply it to all the aexps that
appear in a bexp without changing the bexp's value. Write a
function that performs this transformation on bexps and prove
it is sound. Use the tacticals we've just seen to make the proof
as elegant as possible.
Exercise: 3 stars, standard (optimize_0plus_b_sound)
Fixpoint optimize_0plus_b (b : bexp) : bexp
:= match b with
| BEq a1 a2 => BEq (optimize_0plus a1) (optimize_0plus a2)
| BLe a1 a2 => BLe (optimize_0plus a1) (optimize_0plus a2)
| BNot b1 => BNot (optimize_0plus_b b1)
| BAnd b1 b2 => BAnd (optimize_0plus_b b1) (optimize_0plus_b b2)
| _ => b
end.
| BEq a1 a2 => BEq (optimize_0plus a1) (optimize_0plus a2)
| BLe a1 a2 => BLe (optimize_0plus a1) (optimize_0plus a2)
| BNot b1 => BNot (optimize_0plus_b b1)
| BAnd b1 b2 => BAnd (optimize_0plus_b b1) (optimize_0plus_b b2)
| _ => b
end.
Theorem optimize_0plus_b_sound : forall b,
beval (optimize_0plus_b b) = beval b.
Proof.
intros b.
induction b.
all: try simpl.
all: repeat try rewrite optimize_0plus_sound.
all: try reflexivity.
- rewrite IHb. reflexivity.
- rewrite IHb1. rewrite IHb2. reflexivity.
Qed.
induction b.
all: try simpl.
all: repeat try rewrite optimize_0plus_sound.
all: try reflexivity.
- rewrite IHb. reflexivity.
- rewrite IHb1. rewrite IHb2. reflexivity.
Qed.
☐
Design exercise: The optimization implemented by our
optimize_0plus function is only one of many possible
optimizations on arithmetic and boolean expressions. Write a more
sophisticated optimizer and prove it correct. (You will probably
find it easiest to start small -- add just a single, simple
optimization and its correctness proof -- and build up to
something more interesting incrementially.)
Exercise: 4 stars, standard, optional (optimize)
Defining New Tactic Notations
- The Tactic Notation idiom illustrated below gives a handy way
to define "shorthand tactics" that bundle several tactics into a
single command.
- For more sophisticated programming, Coq offers a built-in
language called Ltac with primitives that can examine and
modify the proof state. The details are a bit too complicated
to get into here (and it is generally agreed that Ltac is not
the most beautiful part of Coq's design!), but they can be found
in the reference manual and other books on Coq, and there are
many examples of Ltac definitions in the Coq standard library
that you can use as examples.
- There is also an OCaml API, which can be used to build tactics that access Coq's internal structures at a lower level, but this is seldom worth the trouble for ordinary Coq users.
Tactic Notation "simpl_and_try" tactic(c) :=
simpl;
try c.
This defines a new tactical called simpl_and_try that takes one
tactic c as an argument and is defined to be equivalent to the
tactic simpl; try c. Now writing "simpl_and_try reflexivity."
in a proof will be the same as writing "simpl; try reflexivity."
The omega Tactic
- numeric constants, addition (+ and S), subtraction (-
and pred), and multiplication by constants (this is what
makes it Presburger arithmetic),
- equality (= and <>) and ordering (<=), and
- the logical connectives /\, \/, ~, and ->,
Example silly_presburger_example : forall m n o p,
m + n <= n + o /\ o + 3 = p + 3 ->
m <= p.
Proof.
intros. lia.
Qed.
Example plus_comm__omega : forall m n,
m + n = n + m.
Proof.
intros. lia.
Qed.
Example plus_assoc__omega : forall m n p,
m + (n + p) = m + n + p.
Proof.
intros. lia.
Qed.
(Note the From Coq Require Import Lia. at the top of
the file.)
A Few More Handy Tactics
- clear H: Delete hypothesis H from the context.
- subst x: For a variable x, find an assumption x = e or
e = x in the context, replace x with e throughout the
context and current goal, and clear the assumption.
- subst: Substitute away all assumptions of the form x = e
or e = x (where x is a variable).
- rename... into...: Change the name of a hypothesis in the
proof context. For example, if the context includes a variable
named x, then rename x into y will change all occurrences
of x to y.
- assumption: Try to find a hypothesis H in the context that
exactly matches the goal; if one is found, solve the goal.
- contradiction: Try to find a hypothesis H in the current
context that is logically equivalent to False. If one is
found, solve the goal.
- constructor: Try to find a constructor c (from some Inductive definition in the current environment) that can be applied to solve the current goal. If one is found, behave like apply c.
Evaluation as a Relation
Module aevalR_first_try.
Inductive aevalR : aexp -> nat -> Prop :=
| E_ANum n :
aevalR (ANum n) n
| E_APlus (e1 e2: aexp) (n1 n2: nat) :
aevalR e1 n1 ->
aevalR e2 n2 ->
aevalR (APlus e1 e2) (n1 + n2)
| E_AMinus (e1 e2: aexp) (n1 n2: nat) :
aevalR e1 n1 ->
aevalR e2 n2 ->
aevalR (AMinus e1 e2) (n1 - n2)
| E_AMult (e1 e2: aexp) (n1 n2: nat) :
aevalR e1 n1 ->
aevalR e2 n2 ->
aevalR (AMult e1 e2) (n1 * n2).
Module HypothesisNames.
Inductive aevalR : aexp -> nat -> Prop :=
| E_ANum n :
aevalR (ANum n) n
| E_APlus (e1 e2: aexp) (n1 n2: nat)
(H1 : aevalR e1 n1)
(H2 : aevalR e2 n2) :
aevalR (APlus e1 e2) (n1 + n2)
| E_AMinus (e1 e2: aexp) (n1 n2: nat)
(H1 : aevalR e1 n1)
(H2 : aevalR e2 n2) :
aevalR (AMinus e1 e2) (n1 - n2)
| E_AMult (e1 e2: aexp) (n1 n2: nat)
(H1 : aevalR e1 n1)
(H2 : aevalR e2 n2) :
aevalR (AMult e1 e2) (n1 * n2).
This style gives us more control over the names that Coq chooses
during proofs involving aevalR, at the cost of making the
definition a little more verbose.
End HypothesisNames.
It will be convenient to have an infix notation for
aevalR. We'll write e ==> n to mean that arithmetic expression
e evaluates to value n.
Notation "e '==>' n"
:= (aevalR e n)
(at level 90, left associativity)
: type_scope.
End aevalR_first_try.
As we saw in IndProp in our case study of regular
expressions, Coq provides a way to use this notation in the
definition of aevalR itself.
Reserved Notation "e '==>' n" (at level 90, left associativity).
Inductive aevalR : aexp -> nat -> Prop :=
| E_ANum (n : nat) :
(ANum n) ==> n
| E_APlus (e1 e2 : aexp) (n1 n2 : nat) :
(e1 ==> n1) -> (e2 ==> n2) -> (APlus e1 e2) ==> (n1 + n2)
| E_AMinus (e1 e2 : aexp) (n1 n2 : nat) :
(e1 ==> n1) -> (e2 ==> n2) -> (AMinus e1 e2) ==> (n1 - n2)
| E_AMult (e1 e2 : aexp) (n1 n2 : nat) :
(e1 ==> n1) -> (e2 ==> n2) -> (AMult e1 e2) ==> (n1 * n2)
where "e '==>' n" := (aevalR e n) : type_scope.
Inference Rule Notation
(E_APlus) APlus e1 e2 ==> n1+n2
(E_ANum) ANum n ==> n
(E_APlus) APlus e1 e2 ==> n1+n2
(E_AMinus) AMinus e1 e2 ==> n1-n2
(E_AMult) AMult e1 e2 ==> n1*n2
Exercise: 1 star, standard, optional (beval_rules)
Definition manual_grade_for_beval_rules : option (nat*string) := None.
☐
Equivalence of the Definitions
Theorem aeval_iff_aevalR : forall a n,
(a ==> n) <-> aeval a = n.
Proof.
split.
-
intros H.
induction H; simpl.
+
reflexivity.
+
rewrite IHaevalR1. rewrite IHaevalR2. reflexivity.
+
rewrite IHaevalR1. rewrite IHaevalR2. reflexivity.
+
rewrite IHaevalR1. rewrite IHaevalR2. reflexivity.
-
generalize dependent n.
induction a;
simpl; intros; subst.
+
apply E_ANum.
+
apply E_APlus.
apply IHa1. reflexivity.
apply IHa2. reflexivity.
+
apply E_AMinus.
apply IHa1. reflexivity.
apply IHa2. reflexivity.
+
apply E_AMult.
apply IHa1. reflexivity.
apply IHa2. reflexivity.
Qed.
We can make the proof quite a bit shorter by making more
use of tacticals.
Theorem aeval_iff_aevalR' : forall a n,
(a ==> n) <-> aeval a = n.
Proof.
split.
-
intros H; induction H; subst; reflexivity.
-
generalize dependent n.
induction a; simpl; intros; subst; constructor;
try apply IHa1; try apply IHa2; reflexivity.
Qed.
Exercise: 3 stars, standard (bevalR)
Reserved Notation "e '==>b' b" (at level 90, left associativity).
Inductive bevalR: bexp -> bool -> Prop :=
| E_BTrue :
BTrue ==>b true
| E_BFalse :
BFalse ==>b false
| E_BEq (e1 e2 : aexp) (n1 n2 : nat) :
(e1 ==> n1) -> (e2 ==> n2) -> (BEq e1 e2 ==>b (n1 =? n2))
| E_BLe (e1 e2 : aexp) (n1 n2 : nat) :
(e1 ==> n1) -> (e2 ==> n2) -> (BLe e1 e2 ==>b (n1 <=? n2))
| E_BNot (e : bexp) (b : bool) :
(e ==>b b) -> (BNot e ==>b (negb b))
| E_BAnd (e1 e2 : bexp) (b1 b2 : bool) :
(e1 ==>b b1) -> (e2 ==>b b2) -> (BAnd e1 e2 ==>b (b1 && b2))
BTrue ==>b true
| E_BFalse :
BFalse ==>b false
| E_BEq (e1 e2 : aexp) (n1 n2 : nat) :
(e1 ==> n1) -> (e2 ==> n2) -> (BEq e1 e2 ==>b (n1 =? n2))
| E_BLe (e1 e2 : aexp) (n1 n2 : nat) :
(e1 ==> n1) -> (e2 ==> n2) -> (BLe e1 e2 ==>b (n1 <=? n2))
| E_BNot (e : bexp) (b : bool) :
(e ==>b b) -> (BNot e ==>b (negb b))
| E_BAnd (e1 e2 : bexp) (b1 b2 : bool) :
(e1 ==>b b1) -> (e2 ==>b b2) -> (BAnd e1 e2 ==>b (b1 && b2))
where "e '==>b' b" := (bevalR e b) : type_scope
.
Lemma beval_iff_bevalR : forall b bv,
b ==>b bv <-> beval b = bv.
Proof.
.
Lemma beval_iff_bevalR : forall b bv,
b ==>b bv <-> beval b = bv.
Proof.
intros. split.
-
intros H. induction H; try reflexivity.
1,2:
try apply aeval_iff_aevalR in H;
try apply aeval_iff_aevalR in H0;
unfold beval; rewrite H; rewrite H0; reflexivity.
all: subst; reflexivity.
-
intros. subst. induction b; simpl.
+ apply E_BTrue.
+ apply E_BFalse.
+ apply E_BEq; apply aeval_iff_aevalR; reflexivity.
+ apply E_BLe; apply aeval_iff_aevalR; reflexivity.
+ apply E_BNot. apply IHb.
+ apply E_BAnd. apply IHb1. apply IHb2.
Qed.
-
intros H. induction H; try reflexivity.
1,2:
try apply aeval_iff_aevalR in H;
try apply aeval_iff_aevalR in H0;
unfold beval; rewrite H; rewrite H0; reflexivity.
all: subst; reflexivity.
-
intros. subst. induction b; simpl.
+ apply E_BTrue.
+ apply E_BFalse.
+ apply E_BEq; apply aeval_iff_aevalR; reflexivity.
+ apply E_BLe; apply aeval_iff_aevalR; reflexivity.
+ apply E_BNot. apply IHb.
+ apply E_BAnd. apply IHb1. apply IHb2.
Qed.
☐
End AExp.
Computational vs. Relational Definitions
Module aevalR_division.
For example, suppose that we wanted to extend the arithmetic
operations with division:
Inductive aexp : Type :=
| ANum (n : nat)
| APlus (a1 a2 : aexp)
| AMinus (a1 a2 : aexp)
| AMult (a1 a2 : aexp)
| ADiv (a1 a2 : aexp).
Extending the definition of aeval to handle this new
operation would not be straightforward (what should we return as
the result of ADiv (ANum 5) (ANum 0)?). But extending aevalR
is very easy.
Reserved Notation "e '==>' n"
(at level 90, left associativity).
Inductive aevalR : aexp -> nat -> Prop :=
| E_ANum (n : nat) :
(ANum n) ==> n
| E_APlus (a1 a2 : aexp) (n1 n2 : nat) :
(a1 ==> n1) -> (a2 ==> n2) -> (APlus a1 a2) ==> (n1 + n2)
| E_AMinus (a1 a2 : aexp) (n1 n2 : nat) :
(a1 ==> n1) -> (a2 ==> n2) -> (AMinus a1 a2) ==> (n1 - n2)
| E_AMult (a1 a2 : aexp) (n1 n2 : nat) :
(a1 ==> n1) -> (a2 ==> n2) -> (AMult a1 a2) ==> (n1 * n2)
| E_ADiv (a1 a2 : aexp) (n1 n2 n3 : nat) :
(a1 ==> n1) -> (a2 ==> n2) -> (n2 > 0) ->
(mult n2 n3 = n1) -> (ADiv a1 a2) ==> n3
where "a '==>' n" := (aevalR a n) : type_scope.
Notice that the evaluation relation has now become partial:
There are some inputs for which it simply does not specify an
output.
End aevalR_division.
Module aevalR_extended.
Or suppose that we want to extend the arithmetic operations
by a nondeterministic number generator any that, when evaluated,
may yield any number. Note that this is not the same as making a
probabilistic choice among all possible numbers -- we're not
specifying any particular probability distribution for the
results, just saying what results are possible.
Reserved Notation "e '==>' n" (at level 90, left associativity).
Inductive aexp : Type :=
| AAny
| ANum (n : nat)
| APlus (a1 a2 : aexp)
| AMinus (a1 a2 : aexp)
| AMult (a1 a2 : aexp).
Again, extending aeval would be tricky, since now
evaluation is not a deterministic function from expressions to
numbers, but extending aevalR is no problem...
Inductive aevalR : aexp -> nat -> Prop :=
| E_Any (n : nat) :
AAny ==> n
| E_ANum (n : nat) :
(ANum n) ==> n
| E_APlus (a1 a2 : aexp) (n1 n2 : nat) :
(a1 ==> n1) -> (a2 ==> n2) -> (APlus a1 a2) ==> (n1 + n2)
| E_AMinus (a1 a2 : aexp) (n1 n2 : nat) :
(a1 ==> n1) -> (a2 ==> n2) -> (AMinus a1 a2) ==> (n1 - n2)
| E_AMult (a1 a2 : aexp) (n1 n2 : nat) :
(a1 ==> n1) -> (a2 ==> n2) -> (AMult a1 a2) ==> (n1 * n2)
where "a '==>' n" := (aevalR a n) : type_scope.
End aevalR_extended.
At this point you maybe wondering: which style should I use
by default? In the examples we've just seen, relational
definitions turned out to be more useful than functional ones.
For situations like these, where the thing being defined is not
easy to express as a function, or indeed where it is not a
function, there is no real choice. But what about when both
styles are workable?
One point in favor of relational definitions is that they can be
more elegant and easier to understand.
Another is that Coq automatically generates nice inversion and
induction principles from Inductive definitions.
On the other hand, functional definitions can often be more
convenient:
Furthermore, functions can be directly "extracted" from Gallina to
executable code in OCaml or Haskell.
Ultimately, the choice often comes down to either the specifics of
a particular situation or simply a question of taste. Indeed, in
large Coq developments it is common to see a definition given in
both functional and relational styles, plus a lemma stating that
the two coincide, allowing further proofs to switch from one point
of view to the other at will.
- Functions are by definition deterministic and defined on all arguments; for a relation we have to prove these properties explicitly if we need them.
- With functions we can also take advantage of Coq's computation mechanism to simplify expressions during proofs.
Expressions With Variables
States
Definition state := total_map nat.
Syntax
Inductive aexp : Type :=
| ANum (n : nat)
| AId (x : string)
| APlus (a1 a2 : aexp)
| AMinus (a1 a2 : aexp)
| AMult (a1 a2 : aexp).
Defining a few variable names as notational shorthands will make
examples easier to read:
Definition W : string := "W".
Definition X : string := "X".
Definition Y : string := "Y".
Definition Z : string := "Z".
(This convention for naming program variables (X, Y,
Z) clashes a bit with our earlier use of uppercase letters for
types. Since we're not using polymorphism heavily in the chapters
developed to Imp, this overloading should not cause confusion.)
The definition of bexps is unchanged (except that it now refers
to the new aexps):
Inductive bexp : Type :=
| BTrue
| BFalse
| BEq (a1 a2 : aexp)
| BLe (a1 a2 : aexp)
| BNot (b : bexp)
| BAnd (b1 b2 : bexp).
Notations
- The Coercion declaration stipulates that a function (or constructor) can be implicitly used by the type system to coerce a value of the input type to a value of the output type. For instance, the coercion declaration for AId allows us to use plain strings when an aexp is expected; the string will implicitly be wrapped with AId.
- Declare Custom Entry com tells Coq to create a new "custom grammar" for parsing Imp expressions and programs. The first notation declaration after this tells Coq that anything between <{ and }> should be parsed using the Imp grammar. Again, it is not necessary to understand the details, but it is important to recognize that we are defining new interpretations for some familiar operators like +, -, *, =, <=, etc., when they occur between <{ and }>.
Coercion AId : string >-> aexp.
Coercion ANum : nat >-> aexp.
Declare Custom Entry com.
Declare Scope com_scope.
Notation "<{ e }>" := e (at level 0, e custom com at level 99) : com_scope.
Notation "( x )" := x (in custom com, x at level 99) : com_scope.
Notation "x" := x (in custom com at level 0, x constr at level 0) : com_scope.
Notation "f x .. y" := (.. (f x) .. y)
(in custom com at level 0, only parsing,
f constr at level 0, x constr at level 9,
y constr at level 9) : com_scope.
Notation "x + y" := (APlus x y) (in custom com at level 50, left associativity).
Notation "x - y" := (AMinus x y) (in custom com at level 50, left associativity).
Notation "x * y" := (AMult x y) (in custom com at level 40, left associativity).
Notation "'true'" := true (at level 1).
Notation "'true'" := BTrue (in custom com at level 0).
Notation "'false'" := false (at level 1).
Notation "'false'" := BFalse (in custom com at level 0).
Notation "x <= y" := (BLe x y) (in custom com at level 70, no associativity).
Notation "x = y" := (BEq x y) (in custom com at level 70, no associativity).
Notation "x && y" := (BAnd x y) (in custom com at level 80, left associativity).
Notation "'~' b" := (BNot b) (in custom com at level 75, right associativity).
Open Scope com_scope.
We can now write 3 + (X * 2) instead of APlus 3 (AMult X 2),
and true && ~(X <= 4) instead of BAnd true (BNot (BLe X 4)).
Definition example_aexp : aexp := <{ 3 + (X * 2) }>.
Definition example_bexp : bexp := <{ true && ~(X <= 4) }>.
One downside of these and notation tricks -- coercions in
particular -- is that they can make it a little harder for humans
to calculate the types of expressions. If you ever find yourself
confused, try doing Set Printing Coercions to see exactly what
is going on.
Print example_bexp.
Set Printing Coercions.
Print example_bexp.
Unset Printing Coercions.
Evaluation
Fixpoint aeval (st : state) (a : aexp) : nat :=
match a with
| ANum n => n
| AId x => st x
| <{a1 + a2}> => (aeval st a1) + (aeval st a2)
| <{a1 - a2}> => (aeval st a1) - (aeval st a2)
| <{a1 * a2}> => (aeval st a1) * (aeval st a2)
end.
Fixpoint beval (st : state) (b : bexp) : bool :=
match b with
| <{true}> => true
| <{false}> => false
| <{a1 = a2}> => (aeval st a1) =? (aeval st a2)
| <{a1 <= a2}> => (aeval st a1) <=? (aeval st a2)
| <{~ b1}> => negb (beval st b1)
| <{b1 && b2}> => andb (beval st b1) (beval st b2)
end.
We specialize our notation for total maps to the specific case of
states, i.e. using (_ !-> 0) as empty state.
Definition empty_st := (_ !-> 0).
Now we can add a notation for a "singleton state" with just one
variable bound to a value.
Notation "x '!->' v" := (t_update empty_st x v) (at level 100).
Example aexp1 :
aeval (X !-> 5) <{ (3 + (X * 2))}>
= 13.
Proof. reflexivity. Qed.
Example bexp1 :
beval (X !-> 5) <{ true && ~(X <= 4)}>
= true.
Proof. reflexivity. Qed.
Example aexp1 :
aeval (X !-> 5) <{ (3 + (X * 2))}>
= 13.
Proof. reflexivity. Qed.
Example bexp1 :
beval (X !-> 5) <{ true && ~(X <= 4)}>
= true.
Proof. reflexivity. Qed.
Commands
Syntax
Inductive com : Type :=
| CSkip
| CAss (x : string) (a : aexp)
| CSeq (c1 c2 : com)
| CIf (b : bexp) (c1 c2 : com)
| CWhile (b : bexp) (c : com).
As for expressions, we can use a few Notation declarations to
make reading and writing Imp programs more convenient.
Notation "'skip'" :=
CSkip (in custom com at level 0) : com_scope.
Notation "x := y" :=
(CAss x y)
(in custom com at level 0, x constr at level 0,
y at level 85, no associativity) : com_scope.
Notation "x ; y" :=
(CSeq x y)
(in custom com at level 90, right associativity) : com_scope.
Notation "'if' x 'then' y 'else' z 'end'" :=
(CIf x y z)
(in custom com at level 89, x at level 99,
y at level 99, z at level 99) : com_scope.
Notation "'while' x 'do' y 'end'" :=
(CWhile x y)
(in custom com at level 89, x at level 99, y at level 99) : com_scope.
For example, here is the factorial function again, written as a
formal definition to Coq:
Definition fact_in_coq : com :=
<{ Z := X;
Y := 1;
while ~(Z = 0) do
Y := Y * Z;
Z := Z - 1
end }>.
Print fact_in_coq.
Desugaring notations
- Unset Printing Notations (undo with Set Printing Notations)
- Set Printing Coercions (undo with Unset Printing Coercions)
- Set Printing All (undo with Unset Printing All)
Unset Printing Notations.
Print fact_in_coq.
Set Printing Notations.
Set Printing Coercions.
Print fact_in_coq.
Unset Printing Coercions.
Finding notations
Locate "&&".
Locate ";".
Locate "while".
Locate ";".
Locate "while".
Finding identifiers
Locate aexp.
Definition plus2 : com :=
<{ X := X + 2 }>.
Definition XtimesYinZ : com :=
<{ Z := X * Y }>.
Definition subtract_slowly_body : com :=
<{ Z := Z - 1 ;
X := X - 1 }>.
Definition subtract_slowly : com :=
<{ while ~(X = 0) do
subtract_slowly_body
end }>.
Definition subtract_3_from_5_slowly : com :=
<{ X := 3 ;
Z := 5 ;
subtract_slowly }>.
Definition loop : com :=
<{ while true do
skip
end }>.
Evaluating Commands
Evaluation as a Function (Failed Attempt)
Fixpoint ceval_fun_no_while (st : state) (c : com) : state :=
match c with
| <{ skip }> =>
st
| <{ x := a }> =>
(x !-> (aeval st a) ; st)
| <{ c1 ; c2 }> =>
let st' := ceval_fun_no_while st c1 in
ceval_fun_no_while st' c2
| <{ if b then c1 else c2 end}> =>
if (beval st b)
then ceval_fun_no_while st c1
else ceval_fun_no_while st c2
| <{ while b do c end }> =>
st
end.
match c with
| <{ skip }> =>
st
| <{ x := a }> =>
(x !-> (aeval st a) ; st)
| <{ c1 ; c2 }> =>
let st' := ceval_fun_no_while st c1 in
ceval_fun_no_while st' c2
| <{ if b then c1 else c2 end}> =>
if (beval st b)
then ceval_fun_no_while st c1
else ceval_fun_no_while st c2
| <{ while b do c end }> =>
st
end.
In a traditional functional programming language like OCaml or
Haskell we could add the while case as follows:
Fixpoint ceval_fun (st : state) (c : com) : state :=
match c with
...
| while b do c end =>
if (beval st b)
then ceval_fun st (c ; while b do c end)
else st
end.
Coq doesn't accept such a definition ("Error: Cannot guess
decreasing argument of fix") because the function we want to
define is not guaranteed to terminate. Indeed, it doesn't always
terminate: for example, the full version of the ceval_fun
function applied to the loop program above would never
terminate. Since Coq is not just a functional programming
language but also a consistent logic, any potentially
non-terminating function needs to be rejected. Here is
an (invalid!) program showing what would go wrong if Coq
allowed non-terminating recursive functions:
Fixpoint loop_false (n : nat) : False := loop_false n.
That is, propositions like False would become provable
(loop_false 0 would be a proof of False), which
would be a disaster for Coq's logical consistency.
Thus, because it doesn't terminate on all inputs,
of ceval_fun cannot be written in Coq -- at least not without
additional tricks and workarounds (see chapter ImpCEvalFun
if you're curious about what those might be).
Evaluation as a Relation
Operational Semantics
(E_Skip) st = skip => st
(E_Ass) st = x := a => (x !-> n ; st)
(E_Seq) st = c1;c2 => st''
(E_IfTrue) st = if b then c1 else c2 end => st'
(E_IfFalse) st = if b then c1 else c2 end => st'
(E_WhileFalse) st = while b do c end => st
(E_WhileTrue) st = while b do c end => st''
Reserved Notation
"st '=[' c ']=>' st'"
(at level 40, c custom com at level 99,
st constr, st' constr at next level).
Inductive ceval : com -> state -> state -> Prop :=
| E_Skip : forall st,
st =[ skip ]=> st
| E_Ass : forall st a n x,
aeval st a = n ->
st =[ x := a ]=> (x !-> n ; st)
| E_Seq : forall c1 c2 st st' st'',
st =[ c1 ]=> st' ->
st' =[ c2 ]=> st'' ->
st =[ c1 ; c2 ]=> st''
| E_IfTrue : forall st st' b c1 c2,
beval st b = true ->
st =[ c1 ]=> st' ->
st =[ if b then c1 else c2 end]=> st'
| E_IfFalse : forall st st' b c1 c2,
beval st b = false ->
st =[ c2 ]=> st' ->
st =[ if b then c1 else c2 end]=> st'
| E_WhileFalse : forall b st c,
beval st b = false ->
st =[ while b do c end ]=> st
| E_WhileTrue : forall st st' st'' b c,
beval st b = true ->
st =[ c ]=> st' ->
st' =[ while b do c end ]=> st'' ->
st =[ while b do c end ]=> st''
where "st =[ c ]=> st'" := (ceval c st st').
The cost of defining evaluation as a relation instead of a
function is that we now need to construct proofs that some
program evaluates to some result state, rather than just letting
Coq's computation mechanism do it for us.
Example ceval_example1:
empty_st =[
X := 2;
if (X <= 1)
then Y := 3
else Z := 4
end
]=> (Z !-> 4 ; X !-> 2).
Proof.
apply E_Seq with (X !-> 2).
-
apply E_Ass. reflexivity.
-
apply E_IfFalse.
reflexivity.
apply E_Ass. reflexivity.
Qed.
Example ceval_example2:
empty_st =[
X := 0;
Y := 1;
Z := 2
]=> (Z !-> 2 ; Y !-> 1 ; X !-> 0).
Proof.
empty_st =[
X := 0;
Y := 1;
Z := 2
]=> (Z !-> 2 ; Y !-> 1 ; X !-> 0).
Proof.
apply E_Seq with (X !-> 0).
{ apply E_Ass. reflexivity. }
apply E_Seq with (Y !-> 1; X !-> 0).
{ apply E_Ass. reflexivity. }
{ apply E_Ass. reflexivity. }
Qed.
{ apply E_Ass. reflexivity. }
apply E_Seq with (Y !-> 1; X !-> 0).
{ apply E_Ass. reflexivity. }
{ apply E_Ass. reflexivity. }
Qed.
☐
Set Printing Implicit.
Check @ceval_example2.
Exercise: 3 stars, standard, optional (pup_to_n)
Definition pup_to_n : com
:= <{
Y := 0 ;
while ~(X = 0) do
Y := Y + X ;
X := X - 1
end
}>.
Y := 0 ;
while ~(X = 0) do
Y := Y + X ;
X := X - 1
end
}>.
Theorem pup_to_2_ceval :
(X !-> 2) =[
pup_to_n
]=> (X !-> 0 ; Y !-> 3 ; X !-> 1 ; Y !-> 2 ; Y !-> 0 ; X !-> 2).
Proof.
unfold pup_to_n.
apply E_Seq with (Y !-> 0; X !-> 2).
{ apply E_Ass. reflexivity. }
apply E_WhileTrue with (X !-> 1; Y !-> 2; Y !-> 0; X !-> 2).
{ reflexivity. }
{ apply E_Seq with (Y !-> 2; Y !-> 0; X !-> 2).
all: apply E_Ass; reflexivity. }
apply E_WhileTrue with (X !-> 0; Y !-> 3; X !-> 1; Y !-> 2; Y !-> 0; X !-> 2).
{ reflexivity. }
{ apply E_Seq with (Y !-> 3; X !-> 1; Y !-> 2; Y !-> 0; X !-> 2).
all: apply E_Ass; reflexivity. }
apply E_WhileFalse; reflexivity.
Qed.
apply E_Seq with (Y !-> 0; X !-> 2).
{ apply E_Ass. reflexivity. }
apply E_WhileTrue with (X !-> 1; Y !-> 2; Y !-> 0; X !-> 2).
{ reflexivity. }
{ apply E_Seq with (Y !-> 2; Y !-> 0; X !-> 2).
all: apply E_Ass; reflexivity. }
apply E_WhileTrue with (X !-> 0; Y !-> 3; X !-> 1; Y !-> 2; Y !-> 0; X !-> 2).
{ reflexivity. }
{ apply E_Seq with (Y !-> 3; X !-> 1; Y !-> 2; Y !-> 0; X !-> 2).
all: apply E_Ass; reflexivity. }
apply E_WhileFalse; reflexivity.
Qed.
☐
Determinism of Evaluation
Theorem ceval_deterministic: forall c st st1 st2,
st =[ c ]=> st1 ->
st =[ c ]=> st2 ->
st1 = st2.
Proof.
intros c st st1 st2 E1 E2.
generalize dependent st2.
induction E1; intros st2 E2; inversion E2; subst.
- reflexivity.
- reflexivity.
-
rewrite (IHE1_1 st'0 H1) in *.
apply IHE1_2. assumption.
-
apply IHE1. assumption.
-
rewrite H in H5. discriminate.
-
rewrite H in H5. discriminate.
-
apply IHE1. assumption.
-
reflexivity.
-
rewrite H in H2. discriminate.
-
rewrite H in H4. discriminate.
-
rewrite (IHE1_1 st'0 H3) in *.
apply IHE1_2. assumption. Qed.
Reasoning About Imp Programs
Theorem plus2_spec : forall st n st',
st X = n ->
st =[ plus2 ]=> st' ->
st' X = n + 2.
Proof.
intros st n st' HX Heval.
Inverting Heval essentially forces Coq to expand one step of
the ceval computation -- in this case revealing that st'
must be st extended with the new value of X, since plus2
is an assignment.
inversion Heval. subst. clear Heval. simpl.
apply t_update_eq. Qed.
Exercise: 3 stars, standard, optional (XtimesYinZ_spec)
Theorem XtimesYinZ_spec : forall st st' n1 n2,
st X = n1 ->
st Y = n2 ->
st =[ XtimesYinZ ]=> st' ->
st' Z = n1 * n2.
Proof.
intros. inversion H1. subst. clear H1. simpl.
apply t_update_eq.
Qed.
st X = n1 ->
st Y = n2 ->
st =[ XtimesYinZ ]=> st' ->
st' Z = n1 * n2.
Proof.
intros. inversion H1. subst. clear H1. simpl.
apply t_update_eq.
Qed.
Definition manual_grade_for_XtimesYinZ_spec : option (nat*string) := None.
Theorem loop_never_stops : forall st st',
~(st =[ loop ]=> st').
Proof.
intros st st' contra. unfold loop in contra.
remember <{ while true do skip end }> as loopdef
eqn:Heqloopdef.
~(st =[ loop ]=> st').
Proof.
intros st st' contra. unfold loop in contra.
remember <{ while true do skip end }> as loopdef
eqn:Heqloopdef.
Proceed by induction on the assumed derivation showing that
loopdef terminates. Most of the cases are immediately
contradictory (and so can be solved in one step with
discriminate).
induction contra; subst; try discriminate.
all: inversion Heqloopdef; subst.
- discriminate.
- apply IHcontra2. assumption.
Qed.
all: inversion Heqloopdef; subst.
- discriminate.
- apply IHcontra2. assumption.
Qed.
Fixpoint no_whiles (c : com) : bool :=
match c with
| <{ skip }> =>
true
| <{ _ := _ }> =>
true
| <{ c1 ; c2 }> =>
andb (no_whiles c1) (no_whiles c2)
| <{ if _ then ct else cf end }> =>
andb (no_whiles ct) (no_whiles cf)
| <{ while _ do _ end }> =>
false
end.
This predicate yields true just on programs that have no while
loops. Using Inductive, write a property no_whilesR such that
no_whilesR c is provable exactly when c is a program with no
while loops. Then prove its equivalence with no_whiles.
Inductive no_whilesR: com -> Prop :=
| NW_Skip :
no_whilesR <{ skip }>
| NW_Ass (x : string) (a : aexp) :
no_whilesR <{ x := a }>
| NW_Seq (c1 c2 : com) (H1 : no_whilesR c1) (H2 : no_whilesR c2) :
no_whilesR <{ c1; c2 }>
| NW_If (b : bexp) (ct cf : com) (H1 : no_whilesR ct) (H2 : no_whilesR cf) :
no_whilesR <{ if b then ct else cf end }>
no_whilesR <{ skip }>
| NW_Ass (x : string) (a : aexp) :
no_whilesR <{ x := a }>
| NW_Seq (c1 c2 : com) (H1 : no_whilesR c1) (H2 : no_whilesR c2) :
no_whilesR <{ c1; c2 }>
| NW_If (b : bexp) (ct cf : com) (H1 : no_whilesR ct) (H2 : no_whilesR cf) :
no_whilesR <{ if b then ct else cf end }>
.
Theorem no_whiles_eqv:
forall c, no_whiles c = true <-> no_whilesR c.
Proof.
Theorem no_whiles_eqv:
forall c, no_whiles c = true <-> no_whilesR c.
Proof.
split.
- intros. induction c.
all: try apply NW_Skip; try apply NW_Ass.
all: inversion H.
all: rewrite andb_true_iff in H1.
all: destruct H1 as [H1 H2].
all: apply IHc1 in H1.
all: apply IHc2 in H2.
all: try apply NW_Seq; try apply NW_If.
all: try apply H1; try apply H2.
- intros. induction H; try simpl; try reflexivity.
all: rewrite andb_true_iff; split.
all: try apply IHno_whilesR1;
try apply IHno_whilesR2.
Qed.
- intros. induction c.
all: try apply NW_Skip; try apply NW_Ass.
all: inversion H.
all: rewrite andb_true_iff in H1.
all: destruct H1 as [H1 H2].
all: apply IHc1 in H1.
all: apply IHc2 in H2.
all: try apply NW_Seq; try apply NW_If.
all: try apply H1; try apply H2.
- intros. induction H; try simpl; try reflexivity.
all: rewrite andb_true_iff; split.
all: try apply IHno_whilesR1;
try apply IHno_whilesR2.
Qed.
☐
Imp programs that don't involve while loops always terminate.
State and prove a theorem no_whiles_terminating that says this.
Use either no_whiles or no_whilesR, as you prefer.
Exercise: 4 stars, standard (no_whiles_terminating)
Theorem no_whiles_terminating: forall c st,
no_whilesR c -> exists st', st =[ c ]=> st'.
Proof.
intros. generalize dependent st. induction c.
- intros. exists st. apply E_Skip.
- intros. exists (x !-> (aeval st a) ; st).
apply E_Ass. reflexivity.
- intros. inversion H; subst.
apply IHc1 with st in H0; clear IHc1; destruct H0 as [st' H1].
apply IHc2 with st' in H3; clear IHc2; destruct H3 as [st'' H2].
exists st''. apply E_Seq with st'. apply H1. apply H2.
- intros. inversion H; subst. destruct (beval st b) eqn:E.
+ apply IHc1 with st in H0; clear IHc1; destruct H0 as [st' H1].
exists st'. apply E_IfTrue. apply E. apply H1.
+ apply IHc2 with st in H4; clear IHc2; destruct H4 as [st' H2].
exists st'. apply E_IfFalse. apply E. apply H2.
- intros. inversion H.
Qed.
no_whilesR c -> exists st', st =[ c ]=> st'.
Proof.
intros. generalize dependent st. induction c.
- intros. exists st. apply E_Skip.
- intros. exists (x !-> (aeval st a) ; st).
apply E_Ass. reflexivity.
- intros. inversion H; subst.
apply IHc1 with st in H0; clear IHc1; destruct H0 as [st' H1].
apply IHc2 with st' in H3; clear IHc2; destruct H3 as [st'' H2].
exists st''. apply E_Seq with st'. apply H1. apply H2.
- intros. inversion H; subst. destruct (beval st b) eqn:E.
+ apply IHc1 with st in H0; clear IHc1; destruct H0 as [st' H1].
exists st'. apply E_IfTrue. apply E. apply H1.
+ apply IHc2 with st in H4; clear IHc2; destruct H4 as [st' H2].
exists st'. apply E_IfFalse. apply E. apply H2.
- intros. inversion H.
Qed.
Definition manual_grade_for_no_whiles_terminating : option (nat*string) := None.
☐
Additional Exercises
Exercise: 3 stars, standard (stack_compiler)
- SPush n: Push the number n on the stack.
- SLoad x: Load the identifier x from the store and push it on the stack
- SPlus: Pop the two top numbers from the stack, add them, and push the result onto the stack.
- SMinus: Similar, but subtract the first number from the second.
- SMult: Similar, but multiply.
Inductive sinstr : Type :=
| SPush (n : nat)
| SLoad (x : string)
| SPlus
| SMinus
| SMult.
Write a function to evaluate programs in the stack language. It
should take as input a state, a stack represented as a list of
numbers (top stack item is the head of the list), and a program
represented as a list of instructions, and it should return the
stack after executing the program. Test your function on the
examples below.
Note that it is unspecified what to do when encountering an
SPlus, SMinus, or SMult instruction if the stack contains
fewer than two elements. In a sense, it is immaterial what we do,
since a correct compiler will never emit such a malformed program.
But for sake of later exercises, it would be best to skip the
offending instruction and continue with the next one.
Fixpoint s_execute (st : state) (stack : list nat)
(prog : list sinstr)
: list nat
:= match prog, stack with
| [], _ => stack
| (SPush n)::prog', _ =>
s_execute st (n :: stack) prog'
| (SLoad x)::prog', _ =>
s_execute st ((aeval st x) :: stack) prog'
| SPlus::prog', (m::n::t) =>
s_execute st (n + m :: t) prog'
| SMinus::prog', (m::n::t) =>
s_execute st (n - m :: t) prog'
| SMult::prog', (m::n::t) =>
s_execute st (n * m :: t) prog'
| _::prog', _ => s_execute st stack prog'
end.
| [], _ => stack
| (SPush n)::prog', _ =>
s_execute st (n :: stack) prog'
| (SLoad x)::prog', _ =>
s_execute st ((aeval st x) :: stack) prog'
| SPlus::prog', (m::n::t) =>
s_execute st (n + m :: t) prog'
| SMinus::prog', (m::n::t) =>
s_execute st (n - m :: t) prog'
| SMult::prog', (m::n::t) =>
s_execute st (n * m :: t) prog'
| _::prog', _ => s_execute st stack prog'
end.
Check s_execute.
Example s_execute1 :
s_execute empty_st []
[SPush 5; SPush 3; SPush 1; SMinus]
= [2; 5].
Proof. reflexivity. Qed.
Example s_execute2 :
s_execute (X !-> 3) [3;4]
[SPush 4; SLoad X; SMult; SPlus]
= [15; 4].
Proof. reflexivity. Qed.
Fixpoint s_compile (e : aexp) : list sinstr
:= match e with
| ANum a => [ SPush a ]
| AId x => [ SLoad x ]
| APlus a1 a2 => (s_compile a1) ++ (s_compile a2) ++ [ SPlus ]
| AMinus a1 a2 => (s_compile a1) ++ (s_compile a2) ++ [ SMinus ]
| AMult a1 a2 => (s_compile a1) ++ (s_compile a2) ++ [ SMult ]
end.
| ANum a => [ SPush a ]
| AId x => [ SLoad x ]
| APlus a1 a2 => (s_compile a1) ++ (s_compile a2) ++ [ SPlus ]
| AMinus a1 a2 => (s_compile a1) ++ (s_compile a2) ++ [ SMinus ]
| AMult a1 a2 => (s_compile a1) ++ (s_compile a2) ++ [ SMult ]
end.
Example s_compile1 :
s_compile <{ X - (2 * Y) }>
= [SLoad X; SPush 2; SLoad Y; SMult; SMinus].
Proof. reflexivity. Qed.
☐
Execution can be decomposed in the following sense: executing
stack program p1 ++ p2 is the same as executing p1, taking
the resulting stack, and executing p2 from that stack. Prove
that fact.
Exercise: 3 stars, standard (execute_app)
Theorem execute_app : forall st p1 p2 stack,
s_execute st stack (p1 ++ p2) = s_execute st (s_execute st stack p1) p2.
Proof.
intros st p1. induction p1.
- intros. reflexivity.
- intros. destruct a.
1, 2 : try (simpl; apply IHp1).
all: simpl; destruct stack.
1, 3, 5: simpl; apply IHp1.
all: simpl; destruct stack.
all: simpl; apply IHp1.
Qed.
- intros. reflexivity.
- intros. destruct a.
1, 2 : try (simpl; apply IHp1).
all: simpl; destruct stack.
1, 3, 5: simpl; apply IHp1.
all: simpl; destruct stack.
all: simpl; apply IHp1.
Qed.
☐
Now we'll prove the correctness of the compiler implemented in the
previous exercise. Begin by proving the following lemma. If it
becomes difficult, consider whether your implementation of
s_execute or s_compile could be simplified.
Exercise: 3 stars, standard (stack_compiler_correct)
Lemma s_compile_correct_aux : forall st e stack,
s_execute st stack (s_compile e) = aeval st e :: stack.
Proof.
induction e.
1, 2: intros; unfold s_compile; reflexivity.
all: intros; simpl; repeat rewrite execute_app.
all: rewrite IHe1; rewrite IHe2.
all: unfold s_execute; reflexivity.
Qed.
1, 2: intros; unfold s_compile; reflexivity.
all: intros; simpl; repeat rewrite execute_app.
all: rewrite IHe1; rewrite IHe2.
all: unfold s_execute; reflexivity.
Qed.
Theorem s_compile_correct : forall (st : state) (e : aexp),
s_execute st [] (s_compile e) = [ aeval st e ].
Proof.
intros. apply s_compile_correct_aux.
Qed.
Qed.
Exercise: 3 stars, standard, optional (short_circuit)
Fixpoint beval_sc (st : state) (b : bexp) : bool :=
match b with
| <{true}> => true
| <{false}> => false
| <{a1 = a2}> => (aeval st a1) =? (aeval st a2)
| <{a1 <= a2}> => (aeval st a1) <=? (aeval st a2)
| <{~ b1}> => negb (beval_sc st b1)
| <{b1 && b2}> => if (beval_sc st b1) then (beval_sc st b2) else false
end.
Theorem beval_sc_correct: forall st b,
beval st b = beval_sc st b.
Proof.
intros. induction b; try reflexivity.
Qed.
match b with
| <{true}> => true
| <{false}> => false
| <{a1 = a2}> => (aeval st a1) =? (aeval st a2)
| <{a1 <= a2}> => (aeval st a1) <=? (aeval st a2)
| <{~ b1}> => negb (beval_sc st b1)
| <{b1 && b2}> => if (beval_sc st b1) then (beval_sc st b2) else false
end.
Theorem beval_sc_correct: forall st b,
beval st b = beval_sc st b.
Proof.
intros. induction b; try reflexivity.
Qed.
Module BreakImp.
Exercise: 4 stars, advanced (break_imp)
Inductive com : Type :=
| CSkip
| CBreak
| CAss (x : string) (a : aexp)
| CSeq (c1 c2 : com)
| CIf (b : bexp) (c1 c2 : com)
| CWhile (b : bexp) (c : com).
Notation "'break'" := CBreak (in custom com at level 0).
Notation "'skip'" :=
CSkip (in custom com at level 0) : com_scope.
Notation "x := y" :=
(CAss x y)
(in custom com at level 0, x constr at level 0,
y at level 85, no associativity) : com_scope.
Notation "x ; y" :=
(CSeq x y)
(in custom com at level 90, right associativity) : com_scope.
Notation "'if' x 'then' y 'else' z 'end'" :=
(CIf x y z)
(in custom com at level 89, x at level 99,
y at level 99, z at level 99) : com_scope.
Notation "'while' x 'do' y 'end'" :=
(CWhile x y)
(in custom com at level 89, x at level 99, y at level 99) : com_scope.
Next, we need to define the behavior of break. Informally,
whenever break is executed in a sequence of commands, it stops
the execution of that sequence and signals that the innermost
enclosing loop should terminate. (If there aren't any
enclosing loops, then the whole program simply terminates.) The
final state should be the same as the one in which the break
statement was executed.
One important point is what to do when there are multiple loops
enclosing a given break. In those cases, break should only
terminate the innermost loop. Thus, after executing the
following...
X := 0;
Y := 1;
while ~(0 = Y) do
while true do
break
end;
X := 1;
Y := Y - 1
end
... the value of X should be 1, and not 0.
One way of expressing this behavior is to add another parameter to
the evaluation relation that specifies whether evaluation of a
command executes a break statement:
Inductive result : Type :=
| SContinue
| SBreak.
Reserved Notation "st '=[' c ']=>' st' '/' s"
(at level 40, c custom com at level 99, st' constr at next level).
Intuitively, st =[ c ]=> st' / s means that, if c is started in
state st, then it terminates in state st' and either signals
that the innermost surrounding loop (or the whole program) should
exit immediately (s = SBreak) or that execution should continue
normally (s = SContinue).
The definition of the "st =[ c ]=> st' / s" relation is very
similar to the one we gave above for the regular evaluation
relation (st =[ c ]=> st') -- we just need to handle the
termination signals appropriately:
Based on the above description, complete the definition of the
ceval relation.
- If the command is skip, then the state doesn't change and
execution of any enclosing loop can continue normally.
- If the command is break, the state stays unchanged but we
signal a SBreak.
- If the command is an assignment, then we update the binding for
that variable in the state accordingly and signal that execution
can continue normally.
- If the command is of the form if b then c1 else c2 end, then
the state is updated as in the original semantics of Imp, except
that we also propagate the signal from the execution of
whichever branch was taken.
- If the command is a sequence c1 ; c2, we first execute
c1. If this yields a SBreak, we skip the execution of c2
and propagate the SBreak signal to the surrounding context;
the resulting state is the same as the one obtained by
executing c1 alone. Otherwise, we execute c2 on the state
obtained after executing c1, and propagate the signal
generated there.
- Finally, for a loop of the form while b do c end, the semantics is almost the same as before. The only difference is that, when b evaluates to true, we execute c and check the signal that it raises. If that signal is SContinue, then the execution proceeds as in the original semantics. Otherwise, we stop the execution of the loop, and the resulting state is the same as the one resulting from the execution of the current iteration. In either case, since break only terminates the innermost loop, while signals SContinue.
Inductive ceval : com -> state -> result -> state -> Prop :=
| E_Skip : forall st,
st =[ CSkip ]=> st / SContinue
| E_Break : forall st,
st =[ break ]=> st / SBreak
| E_Ass : forall st x a n,
aeval st a = n ->
st =[ x := a ]=> (x !-> n ; st) / SContinue
| E_SeqBreak : forall c1 c2 st st',
st =[ c1 ]=> st' / SBreak ->
st =[ c1; c2 ]=> st' / SBreak
| E_SeqContinue : forall c1 c2 st st' st'' res,
st =[ c1 ]=> st' / SContinue ->
st' =[ c2 ]=> st'' / res ->
st =[ c1; c2 ]=> st'' / res
| E_IfTrue : forall b c1 c2 st st' res,
beval st b = true ->
st =[ c1 ]=> st' / res ->
st =[ if b then c1 else c2 end ]=> st' / res
| E_IfFalse : forall b c1 c2 st st' res,
beval st b = false ->
st =[ c2 ]=> st' / res ->
st =[ if b then c1 else c2 end ]=> st' / res
| E_WhileFalse : forall b c st,
beval st b = false ->
st =[ while b do c end ]=> st / SContinue
| E_WhileTrueContinue : forall b c st st' st'',
beval st b = true ->
st =[ c ]=> st' / SContinue ->
st' =[ while b do c end ]=> st'' / SContinue ->
st =[ while b do c end ]=> st'' / SContinue
| E_WhileTrueBreak : forall b c st st',
beval st b = true ->
st =[ c ]=> st' / SBreak ->
st =[ while b do c end ]=> st' / SContinue
st =[ break ]=> st / SBreak
| E_Ass : forall st x a n,
aeval st a = n ->
st =[ x := a ]=> (x !-> n ; st) / SContinue
| E_SeqBreak : forall c1 c2 st st',
st =[ c1 ]=> st' / SBreak ->
st =[ c1; c2 ]=> st' / SBreak
| E_SeqContinue : forall c1 c2 st st' st'' res,
st =[ c1 ]=> st' / SContinue ->
st' =[ c2 ]=> st'' / res ->
st =[ c1; c2 ]=> st'' / res
| E_IfTrue : forall b c1 c2 st st' res,
beval st b = true ->
st =[ c1 ]=> st' / res ->
st =[ if b then c1 else c2 end ]=> st' / res
| E_IfFalse : forall b c1 c2 st st' res,
beval st b = false ->
st =[ c2 ]=> st' / res ->
st =[ if b then c1 else c2 end ]=> st' / res
| E_WhileFalse : forall b c st,
beval st b = false ->
st =[ while b do c end ]=> st / SContinue
| E_WhileTrueContinue : forall b c st st' st'',
beval st b = true ->
st =[ c ]=> st' / SContinue ->
st' =[ while b do c end ]=> st'' / SContinue ->
st =[ while b do c end ]=> st'' / SContinue
| E_WhileTrueBreak : forall b c st st',
beval st b = true ->
st =[ c ]=> st' / SBreak ->
st =[ while b do c end ]=> st' / SContinue
where "st '=[' c ']=>' st' '/' s" := (ceval c st s st').
Now prove the following properties of your definition of ceval:
Theorem break_ignore : forall c st st' s,
st =[ break; c ]=> st' / s ->
st = st'.
Proof.
intros. inversion H; subst.
- inversion H5. auto.
- inversion H2.
Qed.
- inversion H5. auto.
- inversion H2.
Qed.
Theorem while_continue : forall b c st st' s,
st =[ while b do c end ]=> st' / s ->
s = SContinue.
Proof.
intros. inversion H; subst; reflexivity.
Qed.
Qed.
Theorem while_stops_on_break : forall b c st st',
beval st b = true ->
st =[ c ]=> st' / SBreak ->
st =[ while b do c end ]=> st' / SContinue.
Proof.
intros. apply E_WhileTrueBreak; auto.
Qed.
Qed.
Theorem while_break_true : forall b c st st',
st =[ while b do c end ]=> st' / SContinue ->
beval st' b = true ->
exists st'', st'' =[ c ]=> st' / SBreak.
Proof.
st =[ while b do c end ]=> st' / SContinue ->
beval st' b = true ->
exists st'', st'' =[ c ]=> st' / SBreak.
Proof.
intros. remember (<{ while b do c end }>) as w.
induction H; try inversion Heqw; subst.
- rewrite H in H0. discriminate.
- apply IHceval2; auto.
- exists st. apply H1.
Qed.
induction H; try inversion Heqw; subst.
- rewrite H in H0. discriminate.
- apply IHceval2; auto.
- exists st. apply H1.
Qed.
Theorem ceval_deterministic: forall (c:com) st st1 st2 s1 s2,
st =[ c ]=> st1 / s1 ->
st =[ c ]=> st2 / s2 ->
st1 = st2 /\ s1 = s2.
Proof.
st =[ c ]=> st1 / s1 ->
st =[ c ]=> st2 / s2 ->
st1 = st2 /\ s1 = s2.
Proof.
intros.
generalize dependent st2.
generalize dependent s2.
induction H; subst.
1,2,3: intros; inversion H0; subst; split; auto.
- intros. inversion H0; subst.
+ apply IHceval. apply H6.
+ apply IHceval in H3. inversion H3.
discriminate.
- intros. inversion H1; subst.
+ apply IHceval1 in H7. inversion H7.
discriminate.
+ apply IHceval1 in H4. inversion H4.
rewrite <- H2 in H8.
apply IHceval2 in H8. apply H8.
- intros. inversion H1; subst.
+ apply IHceval in H9. apply H9.
+ rewrite H8 in H. discriminate.
- intros. inversion H1; subst.
+ rewrite H8 in H. discriminate.
+ apply IHceval in H9. apply H9.
- intros. inversion H0; subst.
+ split; reflexivity.
+ rewrite H in H3; discriminate.
+ rewrite H in H3; discriminate.
- intros. inversion H2; subst.
+ rewrite H in H8; discriminate.
+ apply IHceval1 in H6. destruct H6.
rewrite <- H3 in H10.
apply IHceval2 in H10. apply H10.
+ apply IHceval1 in H9.
destruct H9. discriminate.
- intros. inversion H1; subst.
+ rewrite H in H7. discriminate.
+ apply IHceval in H5.
destruct H5. discriminate.
+ apply IHceval in H8. destruct H8.
split; auto.
Qed.
generalize dependent st2.
generalize dependent s2.
induction H; subst.
1,2,3: intros; inversion H0; subst; split; auto.
- intros. inversion H0; subst.
+ apply IHceval. apply H6.
+ apply IHceval in H3. inversion H3.
discriminate.
- intros. inversion H1; subst.
+ apply IHceval1 in H7. inversion H7.
discriminate.
+ apply IHceval1 in H4. inversion H4.
rewrite <- H2 in H8.
apply IHceval2 in H8. apply H8.
- intros. inversion H1; subst.
+ apply IHceval in H9. apply H9.
+ rewrite H8 in H. discriminate.
- intros. inversion H1; subst.
+ rewrite H8 in H. discriminate.
+ apply IHceval in H9. apply H9.
- intros. inversion H0; subst.
+ split; reflexivity.
+ rewrite H in H3; discriminate.
+ rewrite H in H3; discriminate.
- intros. inversion H2; subst.
+ rewrite H in H8; discriminate.
+ apply IHceval1 in H6. destruct H6.
rewrite <- H3 in H10.
apply IHceval2 in H10. apply H10.
+ apply IHceval1 in H9.
destruct H9. discriminate.
- intros. inversion H1; subst.
+ rewrite H in H7. discriminate.
+ apply IHceval in H5.
destruct H5. discriminate.
+ apply IHceval in H8. destruct H8.
split; auto.
Qed.
End BreakImp.
Exercise: 4 stars, standard, optional (add_for_loop)
Module ForIMP.
Inductive com : Type :=
| CSkip
| CAss (x : string) (a : aexp)
| CSeq (c1 c2 : com)
| CIf (b : bexp) (c1 c2 : com)
| CWhile (b : bexp) (c : com)
| CFor (b: bexp) (c1 c2 c : com).
Inductive com : Type :=
| CSkip
| CAss (x : string) (a : aexp)
| CSeq (c1 c2 : com)
| CIf (b : bexp) (c1 c2 : com)
| CWhile (b : bexp) (c : com)
| CFor (b: bexp) (c1 c2 c : com).
Notation "'skip'" :=
CSkip (in custom com at level 0) : com_scope.
Notation "x := y" :=
(CAss x y)
(in custom com at level 0, x constr at level 0,
y at level 85, no associativity) : com_scope.
Notation "x ; y" :=
(CSeq x y)
(in custom com at level 90, right associativity) : com_scope.
Notation "'if' x 'then' y 'else' z 'end'" :=
(CIf x y z)
(in custom com at level 89, x at level 99,
y at level 99, z at level 99) : com_scope.
Notation "'while' x 'do' y 'end'" :=
(CWhile x y)
(in custom com at level 89, x at level 99, y at level 99) : com_scope.
Notation "'for' x ',' y ',' z 'do' w 'end'" :=
(CFor y x z w)
(in custom com at level 89, x at level 99,
y at level 99, z at level 99) : com_scope.
CSkip (in custom com at level 0) : com_scope.
Notation "x := y" :=
(CAss x y)
(in custom com at level 0, x constr at level 0,
y at level 85, no associativity) : com_scope.
Notation "x ; y" :=
(CSeq x y)
(in custom com at level 90, right associativity) : com_scope.
Notation "'if' x 'then' y 'else' z 'end'" :=
(CIf x y z)
(in custom com at level 89, x at level 99,
y at level 99, z at level 99) : com_scope.
Notation "'while' x 'do' y 'end'" :=
(CWhile x y)
(in custom com at level 89, x at level 99, y at level 99) : com_scope.
Notation "'for' x ',' y ',' z 'do' w 'end'" :=
(CFor y x z w)
(in custom com at level 89, x at level 99,
y at level 99, z at level 99) : com_scope.
Reserved Notation
"st '=[' c ']=>' st'"
(at level 40, c custom com at level 99,
st constr, st' constr at next level).
Inductive ceval : com -> state -> state -> Prop :=
| E_Skip : forall st,
st =[ skip ]=> st
| E_Ass : forall st a n x,
aeval st a = n ->
st =[ x := a ]=> (x !-> n ; st)
| E_Seq : forall c1 c2 st st' st'',
st =[ c1 ]=> st' ->
st' =[ c2 ]=> st'' ->
st =[ c1 ; c2 ]=> st''
| E_IfTrue : forall st st' b c1 c2,
beval st b = true ->
st =[ c1 ]=> st' ->
st =[ if b then c1 else c2 end]=> st'
| E_IfFalse : forall st st' b c1 c2,
beval st b = false ->
st =[ c2 ]=> st' ->
st =[ if b then c1 else c2 end]=> st'
| E_WhileFalse : forall b st c,
beval st b = false ->
st =[ while b do c end ]=> st
| E_WhileTrue : forall st st' st'' b c,
beval st b = true ->
st =[ c ]=> st' ->
st' =[ while b do c end ]=> st'' ->
st =[ while b do c end ]=> st''
| E_For : forall st st' st'' b c1 c2 c,
st =[ c1 ]=> st' ->
st' =[ while b do c; c2 end ]=> st'' ->
st =[ for c1, b, c2 do c end ]=> st''
where "st =[ c ]=> st'" := (ceval c st st').
"st '=[' c ']=>' st'"
(at level 40, c custom com at level 99,
st constr, st' constr at next level).
Inductive ceval : com -> state -> state -> Prop :=
| E_Skip : forall st,
st =[ skip ]=> st
| E_Ass : forall st a n x,
aeval st a = n ->
st =[ x := a ]=> (x !-> n ; st)
| E_Seq : forall c1 c2 st st' st'',
st =[ c1 ]=> st' ->
st' =[ c2 ]=> st'' ->
st =[ c1 ; c2 ]=> st''
| E_IfTrue : forall st st' b c1 c2,
beval st b = true ->
st =[ c1 ]=> st' ->
st =[ if b then c1 else c2 end]=> st'
| E_IfFalse : forall st st' b c1 c2,
beval st b = false ->
st =[ c2 ]=> st' ->
st =[ if b then c1 else c2 end]=> st'
| E_WhileFalse : forall b st c,
beval st b = false ->
st =[ while b do c end ]=> st
| E_WhileTrue : forall st st' st'' b c,
beval st b = true ->
st =[ c ]=> st' ->
st' =[ while b do c end ]=> st'' ->
st =[ while b do c end ]=> st''
| E_For : forall st st' st'' b c1 c2 c,
st =[ c1 ]=> st' ->
st' =[ while b do c; c2 end ]=> st'' ->
st =[ for c1, b, c2 do c end ]=> st''
where "st =[ c ]=> st'" := (ceval c st st').
Ltac Ass := (apply E_Ass; reflexivity).
Example ceval_for_example1:
empty_st =[
X := 0 ;
for Y := 0, Y <= 2, Y := Y + 1 do
X := X + Y
end
]=> (
Y !-> 3 ; X !-> 3;
Y !-> 2 ; X !-> 1;
Y !-> 1 ; X !-> 0;
Y !-> 0 ; X !-> 0
).
Proof.
apply E_Seq with (X !-> 0); try Ass.
apply E_For with (Y !-> 0; X !-> 0); try Ass.
apply E_WhileTrue with (Y !-> 1; X !-> 0; Y !-> 0; X !-> 0).
{ reflexivity. }
{ apply E_Seq with (X !-> 0; Y !-> 0; X !-> 0); try Ass. }
apply E_WhileTrue with (Y !-> 2; X !-> 1; Y !-> 1;
X !-> 0; Y !-> 0; X !-> 0).
{ reflexivity. }
{ apply E_Seq with (X !-> 1; Y !-> 1; X !-> 0; Y !-> 0; X !-> 0); try Ass. }
apply E_WhileTrue with (Y !-> 3; X !-> 3; Y !-> 2; X !-> 1;
Y !-> 1; X !-> 0; Y !-> 0; X !-> 0).
{ reflexivity. }
{ apply E_Seq with (X !-> 3; Y !-> 2; X !-> 1; Y !-> 1;
X !-> 0; Y !-> 0; X !-> 0); try Ass. }
apply E_WhileFalse. reflexivity.
Qed.
End ForIMP.
Example ceval_for_example1:
empty_st =[
X := 0 ;
for Y := 0, Y <= 2, Y := Y + 1 do
X := X + Y
end
]=> (
Y !-> 3 ; X !-> 3;
Y !-> 2 ; X !-> 1;
Y !-> 1 ; X !-> 0;
Y !-> 0 ; X !-> 0
).
Proof.
apply E_Seq with (X !-> 0); try Ass.
apply E_For with (Y !-> 0; X !-> 0); try Ass.
apply E_WhileTrue with (Y !-> 1; X !-> 0; Y !-> 0; X !-> 0).
{ reflexivity. }
{ apply E_Seq with (X !-> 0; Y !-> 0; X !-> 0); try Ass. }
apply E_WhileTrue with (Y !-> 2; X !-> 1; Y !-> 1;
X !-> 0; Y !-> 0; X !-> 0).
{ reflexivity. }
{ apply E_Seq with (X !-> 1; Y !-> 1; X !-> 0; Y !-> 0; X !-> 0); try Ass. }
apply E_WhileTrue with (Y !-> 3; X !-> 3; Y !-> 2; X !-> 1;
Y !-> 1; X !-> 0; Y !-> 0; X !-> 0).
{ reflexivity. }
{ apply E_Seq with (X !-> 3; Y !-> 2; X !-> 1; Y !-> 1;
X !-> 0; Y !-> 0; X !-> 0); try Ass. }
apply E_WhileFalse. reflexivity.
Qed.
End ForIMP.
