ImpSimple Imperative Programs
Z ::= X;;
Y ::= 1;;
WHILE ~(Z = 0) DO
Y ::= Y × Z;;
Z ::= Z - 1
END
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 omega.Omega.
From Coq Require Import Lists.List.
From Coq Require Import Strings.String.
Import ListNotations.
From LF Require Import Maps.
Arithmetic and Boolean Expressions
These two definitions specify the abstract syntax of
arithmetic and boolean expressions.
Inductive aexp : Type :=
| ANum (n : nat)
| APlus (a_{1} a_{2} : aexp)
| AMinus (a_{1} a_{2} : aexp)
| AMult (a_{1} a_{2} : aexp).
Inductive bexp : Type :=
| BTrue
| BFalse
| BEq (a_{1} a_{2} : aexp)
| BLe (a_{1} a_{2} : aexp)
| BNot (b : bexp)
| BAnd (b_{1} b_{2} : 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.
APlus (ANum 1) (AMult (ANum 2) (ANum 3)).
a ::= nat
| a + a
| a - a
| a × a
b ::= true
| false
| a = a
| a ≤ a
| ¬b
| b && b
- 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.
- 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.
Fixpoint aeval (a : aexp) : nat :=
match a with
| ANum n ⇒ n
| APlus a_{1} a_{2} ⇒ (aeval a_{1}) + (aeval a_{2})
| AMinus a_{1} a_{2} ⇒ (aeval a_{1}) - (aeval a_{2})
| AMult a_{1} a_{2} ⇒ (aeval a_{1}) × (aeval a_{2})
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 a_{1} a_{2} ⇒ (aeval a_{1}) =? (aeval a_{2})
| BLe a_{1} a_{2} ⇒ (aeval a_{1}) <=? (aeval a_{2})
| BNot b_{1} ⇒ negb (beval b_{1})
| BAnd b_{1} b_{2} ⇒ andb (beval b_{1}) (beval b_{2})
end.
Optimization
Fixpoint optimize_0plus (a:aexp) : aexp :=
match a with
| ANum n ⇒ ANum n
| APlus (ANum 0) e_{2} ⇒ optimize_0plus e_{2}
| APlus e_{1} e_{2} ⇒ APlus (optimize_0plus e_{1}) (optimize_0plus e_{2})
| AMinus e_{1} e_{2} ⇒ AMinus (optimize_0plus e_{1}) (optimize_0plus e_{2})
| AMult e_{1} e_{2} ⇒ AMult (optimize_0plus e_{1}) (optimize_0plus e_{2})
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: ∀ a,
aeval (optimize_0plus a) = aeval a.
Proof.
intros a. induction a.
- (* ANum *) reflexivity.
- (* APlus *) destruct a_{1} eqn:Ea_{1}.
+ (* a_{1} = ANum n *) destruct n eqn:En.
× (* n = 0 *) simpl. apply IHa2.
× (* n <> 0 *) simpl. rewrite IHa2. reflexivity.
+ (* a_{1} = APlus a1_1 a1_2 *)
simpl. simpl in IHa1. rewrite IHa1.
rewrite IHa2. reflexivity.
+ (* a_{1} = AMinus a1_1 a1_2 *)
simpl. simpl in IHa1. rewrite IHa1.
rewrite IHa2. reflexivity.
+ (* a_{1} = AMult a1_1 a1_2 *)
simpl. simpl in IHa1. rewrite IHa1.
rewrite IHa2. reflexivity.
- (* AMinus *)
simpl. rewrite IHa1. rewrite IHa2. reflexivity.
- (* AMult *)
simpl. rewrite IHa1. rewrite IHa2. reflexivity. Qed.
intros a. induction a.
- (* ANum *) reflexivity.
- (* APlus *) destruct a_{1} eqn:Ea_{1}.
+ (* a_{1} = ANum n *) destruct n eqn:En.
× (* n = 0 *) simpl. apply IHa2.
× (* n <> 0 *) simpl. rewrite IHa2. reflexivity.
+ (* a_{1} = APlus a1_1 a1_2 *)
simpl. simpl in IHa1. rewrite IHa1.
rewrite IHa2. reflexivity.
+ (* a_{1} = AMinus a1_1 a1_2 *)
simpl. simpl in IHa1. rewrite IHa1.
rewrite IHa2. reflexivity.
+ (* a_{1} = AMult a1_1 a1_2 *)
simpl. simpl in IHa1. rewrite IHa1.
rewrite IHa2. reflexivity.
- (* AMinus *)
simpl. rewrite IHa1. rewrite IHa2. reflexivity.
- (* AMult *)
simpl. rewrite IHa1. rewrite IHa2. reflexivity. Qed.
Coq Automation
Tacticals
The try Tactical
Theorem silly1 : ∀ ae, aeval ae = aeval ae.
Proof. try reflexivity. (* This just does reflexivity. *) Qed.
Theorem silly2 : ∀ (P : Prop), P → P.
Proof.
intros P HP.
try reflexivity. (* Just reflexivity would have failed. *)
apply HP. (* We can still finish the proof in some other way. *)
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 : ∀ n, 0 <=? n = true.
Proof.
intros.
destruct n.
(* Leaves two subgoals, which are discharged identically... *)
- (* n=0 *) simpl. reflexivity.
- (* n=Sn' *) simpl. reflexivity.
Qed.
We can simplify this proof using the ; tactical:
Lemma foo' : ∀ n, 0 <=? n = true.
Proof.
intros.
(* destruct the current goal *)
destruct n;
(* then simpl each resulting subgoal *)
simpl;
(* and do reflexivity on each resulting subgoal *)
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': ∀ a,
aeval (optimize_0plus a) = aeval a.
Proof.
intros a.
induction a;
(* Most cases follow directly by the IH... *)
try (simpl; rewrite IHa1; rewrite IHa2; reflexivity).
(* ... but the remaining cases -- ANum and APlus --
are different: *)
- (* ANum *) reflexivity.
- (* APlus *)
destruct a_{1} eqn:Ea_{1};
(* Again, most cases follow directly by the IH: *)
try (simpl; simpl in IHa1; rewrite IHa1;
rewrite IHa2; reflexivity).
(* The interesting case, on which the try...
does nothing, is when e_{1} = ANum n. In this
case, we have to destruct n (to see whether
the optimization applies) and rewrite with the
induction hypothesis. *)
+ (* a_{1} = ANum n *) 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:
aeval (optimize_0plus a) = aeval a.
- Suppose a = ANum n for some n. We must show
aeval (optimize_0plus (ANum n)) = aeval (ANum n). - Suppose a = APlus a_{1} a_{2} for some a_{1} and a_{2}. We must
show
aeval (optimize_0plus (APlus a_{1} a_{2})) = aeval (APlus a_{1} a_{2}).
optimize_0plus (APlus a_{1} a_{2}) = optimize_0plus a_{2}
Theorem optimize_0plus_sound'': ∀ a,
aeval (optimize_0plus a) = aeval a.
Proof.
intros a.
induction a;
(* Most cases follow directly by the IH *)
try (simpl; rewrite IHa1; rewrite IHa2; reflexivity);
(* ... or are immediate by definition *)
try reflexivity.
(* The interesting case is when a = APlus a_{1} a_{2}. *)
- (* APlus *)
destruct a_{1}; try (simpl; simpl in IHa1; rewrite IHa1;
rewrite IHa2; reflexivity).
+ (* a_{1} = ANum n *) destruct n;
simpl; rewrite IHa2; reflexivity. Qed.
The ; Tactical (General Form)
T; [T_{1} | T_{2} | ... | Tn]
T; [T' | T' | ... | T']
The repeat Tactical
Theorem In_{10} : 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 In_{10}' : 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 : ∀ (m n : nat),
m + n = n + m.
Proof.
intros m n.
(* Uncomment the next line to see the infinite loop occur.
In Proof General, C-c C-c will break out of the loop. *)
(* repeat rewrite Nat.add_comm. *)
Admitted.
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.
Exercise: 3 stars, standard (optimize_0plus_b_sound)
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.Fixpoint optimize_0plus_b (b : bexp) : bexp
(* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted.
Theorem optimize_0plus_b_sound : ∀ b,
beval (optimize_0plus_b b) = beval b.
Proof.
(* FILL IN HERE *) Admitted.
☐
Exercise: 4 stars, standard, optional (optimize)
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.)(* FILL IN HERE *)
☐
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 : ∀ m n o p,
m + n ≤ n + o ∧ o + 3 = p + 3 →
m ≤ p.
Proof.
intros. omega.
Qed.
Example plus_comm__omega : ∀ m n,
m + n = n + m.
Proof.
intros. omega.
Qed.
Example plus_assoc__omega : ∀ m n p,
m + (n + p) = m + n + p.
Proof.
intros. omega.
Qed.
(Note the From Coq Require Import omega.Omega. 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 (e_{1} e_{2}: aexp) (n_{1} n_{2}: nat) :
aevalR e_{1} n_{1} →
aevalR e_{2} n_{2} →
aevalR (APlus e_{1} e_{2}) (n_{1} + n_{2})
| E_AMinus (e_{1} e_{2}: aexp) (n_{1} n_{2}: nat) :
aevalR e_{1} n_{1} →
aevalR e_{2} n_{2} →
aevalR (AMinus e_{1} e_{2}) (n_{1} - n_{2})
| E_AMult (e_{1} e_{2}: aexp) (n_{1} n_{2}: nat) :
aevalR e_{1} n_{1} →
aevalR e_{2} n_{2} →
aevalR (AMult e_{1} e_{2}) (n_{1} × n_{2}).
Module HypothesisNames.
(* A small notational aside. We could also write the definition of
aevalR as follow, with explicit names for the hypotheses in each
case: *)
Inductive aevalR : aexp → nat → Prop :=
| E_ANum n :
aevalR (ANum n) n
| E_APlus (e_{1} e_{2}: aexp) (n_{1} n_{2}: nat)
(H_{1} : aevalR e_{1} n_{1})
(H_{2} : aevalR e_{2} n_{2}) :
aevalR (APlus e_{1} e_{2}) (n_{1} + n_{2})
| E_AMinus (e_{1} e_{2}: aexp) (n_{1} n_{2}: nat)
(H_{1} : aevalR e_{1} n_{1})
(H_{2} : aevalR e_{2} n_{2}) :
aevalR (AMinus e_{1} e_{2}) (n_{1} - n_{2})
| E_AMult (e_{1} e_{2}: aexp) (n_{1} n_{2}: nat)
(H_{1} : aevalR e_{1} n_{1})
(H_{2} : aevalR e_{2} n_{2}) :
aevalR (AMult e_{1} e_{2}) (n_{1} × n_{2}).
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.
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 (e_{1} e_{2} : aexp) (n_{1} n_{2} : nat) :
(e_{1} ==> n_{1}) → (e_{2} ==> n_{2}) → (APlus e_{1} e_{2}) ==> (n_{1} + n_{2})
| E_AMinus (e_{1} e_{2} : aexp) (n_{1} n_{2} : nat) :
(e_{1} ==> n_{1}) → (e_{2} ==> n_{2}) → (AMinus e_{1} e_{2}) ==> (n_{1} - n_{2})
| E_AMult (e_{1} e_{2} : aexp) (n_{1} n_{2} : nat) :
(e_{1} ==> n_{1}) → (e_{2} ==> n_{2}) → (AMult e_{1} e_{2}) ==> (n_{1} × n_{2})
where "e '==>' n" := (aevalR e n) : type_scope.
Inference Rule Notation
| E_APlus : ∀ (e_{1} e_{2}: aexp) (n_{1} n_{2}: nat),
aevalR e_{1} n_{1} →
aevalR e_{2} n_{2} →
aevalR (APlus e_{1} e_{2}) (n_{1} + n_{2})
e_{1} ==> n_{1} | |
e_{2} ==> n_{2} | (E_APlus) |
APlus e_{1} e_{2} ==> n_{1}+n_{2} |
(E_ANum) | |
ANum n ==> n |
e_{1} ==> n_{1} | |
e_{2} ==> n_{2} | (E_APlus) |
APlus e_{1} e_{2} ==> n_{1}+n_{2} |
e_{1} ==> n_{1} | |
e_{2} ==> n_{2} | (E_AMinus) |
AMinus e_{1} e_{2} ==> n_{1}-n_{2} |
e_{1} ==> n_{1} | |
e_{2} ==> n_{2} | (E_AMult) |
AMult e_{1} e_{2} ==> n_{1}*n_{2} |
Exercise: 1 star, standard, optional (beval_rules)
Here, again, is the Coq definition of the beval function:Fixpoint beval (e : bexp) : bool :=
match e with
| BTrue ⇒ true
| BFalse ⇒ false
| BEq a_{1} a_{2} ⇒ (aeval a_{1}) =? (aeval a_{2})
| BLe a_{1} a_{2} ⇒ (aeval a_{1}) <=? (aeval a_{2})
| BNot b_{1} ⇒ negb (beval b_{1})
| BAnd b_{1} b_{2} ⇒ andb (beval b_{1}) (beval b_{2})
end.
(* FILL IN HERE *)
(* Do not modify the following line: *)
Definition manual_grade_for_beval_rules : option (nat×string) := None.
☐
(* Do not modify the following line: *)
Definition manual_grade_for_beval_rules : option (nat×string) := None.
☐
Equivalence of the Definitions
Theorem aeval_iff_aevalR : ∀ a n,
(a ==> n) ↔ aeval a = n.
Proof.
split.
- (* -> *)
intros H.
induction H; simpl.
+ (* E_ANum *)
reflexivity.
+ (* E_APlus *)
rewrite IHaevalR1. rewrite IHaevalR2. reflexivity.
+ (* E_AMinus *)
rewrite IHaevalR1. rewrite IHaevalR2. reflexivity.
+ (* E_AMult *)
rewrite IHaevalR1. rewrite IHaevalR2. reflexivity.
- (* <- *)
generalize dependent n.
induction a;
simpl; intros; subst.
+ (* ANum *)
apply E_ANum.
+ (* APlus *)
apply E_APlus.
apply IHa1. reflexivity.
apply IHa2. reflexivity.
+ (* AMinus *)
apply E_AMinus.
apply IHa1. reflexivity.
apply IHa2. reflexivity.
+ (* AMult *)
apply E_AMult.
apply IHa1. reflexivity.
apply IHa2. reflexivity.
Qed.
split.
- (* -> *)
intros H.
induction H; simpl.
+ (* E_ANum *)
reflexivity.
+ (* E_APlus *)
rewrite IHaevalR1. rewrite IHaevalR2. reflexivity.
+ (* E_AMinus *)
rewrite IHaevalR1. rewrite IHaevalR2. reflexivity.
+ (* E_AMult *)
rewrite IHaevalR1. rewrite IHaevalR2. reflexivity.
- (* <- *)
generalize dependent n.
induction a;
simpl; intros; subst.
+ (* ANum *)
apply E_ANum.
+ (* APlus *)
apply E_APlus.
apply IHa1. reflexivity.
apply IHa2. reflexivity.
+ (* AMinus *)
apply E_AMinus.
apply IHa1. reflexivity.
apply IHa2. reflexivity.
+ (* AMult *)
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' : ∀ a n,
(a ==> n) ↔ aeval a = n.
Proof.
(* WORKED IN CLASS *)
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)
Write a relation bevalR in the same style as aevalR, and prove that it is equivalent to beval.Reserved Notation "e '==>b' b" (at level 90, left associativity).
Inductive bevalR: bexp → bool → Prop :=
(* FILL IN HERE *)
where "e '==>b' b" := (bevalR e b) : type_scope
.
Lemma beval_iff_bevalR : ∀ b bv,
b ==>b bv ↔ beval b = bv.
Proof.
(* FILL IN HERE *) Admitted.
☐
Computational vs. Relational Definitions
For example, suppose that we wanted to extend the arithmetic
operations with division:
Inductive aexp : Type :=
| ANum (n : nat)
| APlus (a_{1} a_{2} : aexp)
| AMinus (a_{1} a_{2} : aexp)
| AMult (a_{1} a_{2} : aexp)
| ADiv (a_{1} a_{2} : aexp). (* <--- NEW *)
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 (a_{1} a_{2} : aexp) (n_{1} n_{2} : nat) :
(a_{1} ==> n_{1}) → (a_{2} ==> n_{2}) → (APlus a_{1} a_{2}) ==> (n_{1} + n_{2})
| E_AMinus (a_{1} a_{2} : aexp) (n_{1} n_{2} : nat) :
(a_{1} ==> n_{1}) → (a_{2} ==> n_{2}) → (AMinus a_{1} a_{2}) ==> (n_{1} - n_{2})
| E_AMult (a_{1} a_{2} : aexp) (n_{1} n_{2} : nat) :
(a_{1} ==> n_{1}) → (a_{2} ==> n_{2}) → (AMult a_{1} a_{2}) ==> (n_{1} × n_{2})
| E_ADiv (a_{1} a_{2} : aexp) (n_{1} n_{2} n_{3} : nat) : (* <----- NEW *)
(a_{1} ==> n_{1}) → (a_{2} ==> n_{2}) → (n_{2} > 0) →
(mult n_{2} n_{3} = n_{1}) → (ADiv a_{1} a_{2}) ==> n_{3}
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.
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 (* <--- NEW *)
| ANum (n : nat)
| APlus (a_{1} a_{2} : aexp)
| AMinus (a_{1} a_{2} : aexp)
| AMult (a_{1} a_{2} : 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 (* <--- NEW *)
| E_ANum (n : nat) :
(ANum n) ==> n
| E_APlus (a_{1} a_{2} : aexp) (n_{1} n_{2} : nat) :
(a_{1} ==> n_{1}) → (a_{2} ==> n_{2}) → (APlus a_{1} a_{2}) ==> (n_{1} + n_{2})
| E_AMinus (a_{1} a_{2} : aexp) (n_{1} n_{2} : nat) :
(a_{1} ==> n_{1}) → (a_{2} ==> n_{2}) → (AMinus a_{1} a_{2}) ==> (n_{1} - n_{2})
| E_AMult (a_{1} a_{2} : aexp) (n_{1} n_{2} : nat) :
(a_{1} ==> n_{1}) → (a_{2} ==> n_{2}) → (AMult a_{1} a_{2}) ==> (n_{1} × n_{2})
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
Syntax
Inductive aexp : Type :=
| ANum (n : nat)
| AId (x : string) (* <--- NEW *)
| APlus (a_{1} a_{2} : aexp)
| AMinus (a_{1} a_{2} : aexp)
| AMult (a_{1} a_{2} : 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 (a_{1} a_{2} : aexp)
| BLe (a_{1} a_{2} : aexp)
| BNot (b : bexp)
| BAnd (b_{1} b_{2} : bexp).
Notations
Coercion AId : string >-> aexp.
Coercion ANum : nat >-> aexp.
Definition bool_to_bexp (b : bool) : bexp :=
if b then BTrue else BFalse.
Coercion bool_to_bexp : bool >-> bexp.
Bind Scope imp_scope with aexp.
Bind Scope imp_scope with bexp.
Delimit Scope imp_scope with imp.
Notation "x + y" := (APlus x y) (at level 50, left associativity) : imp_scope.
Notation "x - y" := (AMinus x y) (at level 50, left associativity) : imp_scope.
Notation "x * y" := (AMult x y) (at level 40, left associativity) : imp_scope.
Notation "x <= y" := (BLe x y) (at level 70, no associativity) : imp_scope.
Notation "x = y" := (BEq x y) (at level 70, no associativity) : imp_scope.
Notation "x && y" := (BAnd x y) (at level 40, left associativity) : imp_scope.
Notation "'~' b" := (BNot b) (at level 75, right associativity) : imp_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)).
But this only works when we tell Coq to parse our expressions in
the appropriate notation scope by using %imp, or when Coq knows
that the expression has a type (aexp or bexp) that has
been "bound" to use that notation scope.
One downside of these coercions is that they can make it a little
harder for humans to calculate the types of expressions. If you
get confused, try doing Set Printing Coercions to see exactly
what is going on.
Set Printing Coercions.
Print example_bexp.
(* ===> (example_bexp = bool_to_bexp true && ~ (AId X <= ANum 4))*)
Unset Printing Coercions.
Evaluation
Fixpoint aeval (st : state) (a : aexp) : nat :=
match a with
| ANum n ⇒ n
| AId x ⇒ st x (* <--- NEW *)
| APlus a_{1} a_{2} ⇒ (aeval st a_{1}) + (aeval st a_{2})
| AMinus a_{1} a_{2} ⇒ (aeval st a_{1}) - (aeval st a_{2})
| AMult a_{1} a_{2} ⇒ (aeval st a_{1}) × (aeval st a_{2})
end.
Fixpoint beval (st : state) (b : bexp) : bool :=
match b with
| BTrue ⇒ true
| BFalse ⇒ false
| BEq a_{1} a_{2} ⇒ (aeval st a_{1}) =? (aeval st a_{2})
| BLe a_{1} a_{2} ⇒ (aeval st a_{1}) <=? (aeval st a_{2})
| BNot b_{1} ⇒ negb (beval st b_{1})
| BAnd b_{1} b_{2} ⇒ andb (beval st b_{1}) (beval st b_{2})
end.
We specialize our notation for total maps to the specific case of
states, i.e. using (_ !-> 0) as empty state.
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.
Example bexp1 :
beval (X !-> 5) (true && ~(X ≤ 4))
= true.
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
c ::= SKIP | x ::= a | c ;; c | TEST b THEN c ELSE c FI
| WHILE b DO c END
Inductive com : Type :=
| CSkip
| CAss (x : string) (a : aexp)
| CSeq (c_{1} c_{2} : com)
| CIf (b : bexp) (c_{1} c_{2} : 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.
Bind Scope imp_scope with com.
Notation "'SKIP'" :=
CSkip : imp_scope.
Notation "x '::=' a" :=
(CAss x a) (at level 60) : imp_scope.
Notation "c_{1} ;; c_{2}" :=
(CSeq c_{1} c_{2}) (at level 80, right associativity) : imp_scope.
Notation "'WHILE' b 'DO' c 'END'" :=
(CWhile b c) (at level 80, right associativity) : imp_scope.
Notation "'TEST' c_{1} 'THEN' c_{2} 'ELSE' c_{3} 'FI'" :=
(CIf c_{1} c_{2} c_{3}) (at level 80, right associativity) : imp_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.
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.
(* ===>
fact_in_coq =
CSeq (CAss Z X)
(CSeq (CAss Y (S O))
(CWhile (BNot (BEq Z O))
(CSeq (CAss Y (AMult Y Z))
(CAss Z (AMinus Z (S O))))))
: com *)
Set Printing Notations.
Set Printing Coercions.
Print fact_in_coq.
(* ===>
fact_in_coq =
(Z ::= AId X;;
Y ::= ANum 1;;
WHILE ~ (AId Z = ANum 0) DO
Y ::= AId Y * AId Z;;
Z ::= AId Z - ANum 1
END)
: com *)
Unset Printing Coercions.
The Locate command
Finding notations
Locate "&&".
(* ===>
Notation "x && y" := andb x y : bool_scope (default interpretation) *)
Locate ";;".
(* ===>
Notation "c_{1} ;; c_{2}" := CSeq c_{1} c_{2} : imp_scope *)
Locate "WHILE".
(* ===>
Notation "'WHILE' b 'DO' c 'END'" := CWhile b c : imp_scope *)
(* ===>
Notation "x && y" := andb x y : bool_scope (default interpretation) *)
Locate ";;".
(* ===>
Notation "c_{1} ;; c_{2}" := CSeq c_{1} c_{2} : imp_scope *)
Locate "WHILE".
(* ===>
Notation "'WHILE' b 'DO' c 'END'" := CWhile b c : imp_scope *)
Finding identifiers
Locate aexp.
(* ===>
Inductive Top.aexp
Inductive Top.AExp.aexp
(shorter name to refer to it in current context is AExp.aexp)
Inductive Top.aevalR_division.aexp
(shorter name to refer to it in current context is aevalR_division.aexp)
Inductive Top.aevalR_extended.aexp
(shorter name to refer to it in current context is aevalR_extended.aexp)
*)
(* ===>
Inductive Top.aexp
Inductive Top.AExp.aexp
(shorter name to refer to it in current context is AExp.aexp)
Inductive Top.aevalR_division.aexp
(shorter name to refer to it in current context is aevalR_division.aexp)
Inductive Top.aevalR_extended.aexp
(shorter name to refer to it in current context is aevalR_extended.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.
Evaluating Commands
Evaluation as a Function (Failed Attempt)
Open Scope imp_scope.
Fixpoint ceval_fun_no_while (st : state) (c : com)
: state :=
match c with
| SKIP ⇒
st
| x ::= a_{1} ⇒
(x !-> (aeval st a_{1}) ; st)
| c_{1} ;; c_{2} ⇒
let st' := ceval_fun_no_while st c_{1} in
ceval_fun_no_while st' c_{2}
| TEST b THEN c_{1} ELSE c_{2} FI ⇒
if (beval st b)
then ceval_fun_no_while st c_{1}
else ceval_fun_no_while st c_{2}
| WHILE b DO c END ⇒
st (* bogus *)
end.
Close Scope imp_scope.
Fixpoint ceval_fun_no_while (st : state) (c : com)
: state :=
match c with
| SKIP ⇒
st
| x ::= a_{1} ⇒
(x !-> (aeval st a_{1}) ; st)
| c_{1} ;; c_{2} ⇒
let st' := ceval_fun_no_while st c_{1} in
ceval_fun_no_while st' c_{2}
| TEST b THEN c_{1} ELSE c_{2} FI ⇒
if (beval st b)
then ceval_fun_no_while st c_{1}
else ceval_fun_no_while st c_{2}
| WHILE b DO c END ⇒
st (* bogus *)
end.
Close Scope imp_scope.
In a traditional functional programming language like OCaml or
Haskell we could add the WHILE case as follows:
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).
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.
Evaluation as a Relation
Operational Semantics
(E_Skip) | |
st =[ SKIP ]=> st |
aeval st a_{1} = n | (E_Ass) |
st =[ x := a_{1} ]=> (x !-> n ; st) |
st =[ c_{1} ]=> st' | |
st' =[ c_{2} ]=> st'' | (E_Seq) |
st =[ c_{1};;c_{2} ]=> st'' |
beval st b_{1} = true | |
st =[ c_{1} ]=> st' | (E_IfTrue) |
st =[ TEST b_{1} THEN c_{1} ELSE c_{2} FI ]=> st' |
beval st b_{1} = false | |
st =[ c_{2} ]=> st' | (E_IfFalse) |
st =[ TEST b_{1} THEN c_{1} ELSE c_{2} FI ]=> st' |
beval st b = false | (E_WhileFalse) |
st =[ WHILE b DO c END ]=> st |
beval st b = true | |
st =[ c ]=> st' | |
st' =[ WHILE b DO c END ]=> st'' | (E_WhileTrue) |
st =[ WHILE b DO c END ]=> st'' |
Reserved Notation "st '=[' c ']=>' st'"
(at level 40).
Inductive ceval : com → state → state → Prop :=
| E_Skip : ∀ st,
st =[ SKIP ]=> st
| E_Ass : ∀ st a_{1} n x,
aeval st a_{1} = n →
st =[ x ::= a_{1} ]=> (x !-> n ; st)
| E_Seq : ∀ c_{1} c_{2} st st' st'',
st =[ c_{1} ]=> st' →
st' =[ c_{2} ]=> st'' →
st =[ c_{1} ;; c_{2} ]=> st''
| E_IfTrue : ∀ st st' b c_{1} c_{2},
beval st b = true →
st =[ c_{1} ]=> st' →
st =[ TEST b THEN c_{1} ELSE c_{2} FI ]=> st'
| E_IfFalse : ∀ st st' b c_{1} c_{2},
beval st b = false →
st =[ c_{2} ]=> st' →
st =[ TEST b THEN c_{1} ELSE c_{2} FI ]=> st'
| E_WhileFalse : ∀ b st c,
beval st b = false →
st =[ WHILE b DO c END ]=> st
| E_WhileTrue : ∀ 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;;
TEST X ≤ 1
THEN Y ::= 3
ELSE Z ::= 4
FI
]=> (Z !-> 4 ; X !-> 2).
Proof.
(* We must supply the intermediate state *)
apply E_Seq with (X !-> 2).
- (* assignment command *)
apply E_Ass. reflexivity.
- (* if command *)
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.
(* FILL IN HERE *) Admitted.
☐
empty_st =[
X ::= 0;; Y ::= 1;; Z ::= 2
]=> (Z !-> 2 ; Y !-> 1 ; X !-> 0).
Proof.
(* FILL IN HERE *) Admitted.
☐
Exercise: 3 stars, standard, optional (pup_to_n)
Write an Imp program that sums the numbers from 1 to X (inclusive: 1 + 2 + ... + X) in the variable Y. Your program should update the state as shown in theorem pup_to_2_ceval, which you can reverse-engineer to discover the program you should write. The proof of that theorem will be somewhat lengthy.Definition pup_to_n : com
(* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted.
Theorem pup_to_2_ceval :
(X !-> 2) =[
pup_to_n
]=> (X !-> 0 ; Y !-> 3 ; X !-> 1 ; Y !-> 2 ; Y !-> 0 ; X !-> 2).
Proof.
(* FILL IN HERE *) Admitted.
☐
Determinism of Evaluation
Theorem ceval_deterministic: ∀ c st st_{1} st_{2},
st =[ c ]=> st_{1} →
st =[ c ]=> st_{2} →
st_{1} = st_{2}.
Proof.
intros c st st_{1} st_{2} E_{1} E_{2}.
generalize dependent st_{2}.
induction E_{1}; intros st_{2} E_{2}; inversion E_{2}; subst.
- (* E_Skip *) reflexivity.
- (* E_Ass *) reflexivity.
- (* E_Seq *)
assert (st' = st'0) as EQ_{1}.
{ (* Proof of assertion *) apply IHE1_1; assumption. }
subst st'0.
apply IHE1_2. assumption.
- (* E_IfTrue, b evaluates to true *)
apply IHE1. assumption.
- (* E_IfTrue, b evaluates to false (contradiction) *)
rewrite H in H_{5}. discriminate H_{5}.
- (* E_IfFalse, b evaluates to true (contradiction) *)
rewrite H in H_{5}. discriminate H_{5}.
- (* E_IfFalse, b evaluates to false *)
apply IHE1. assumption.
- (* E_WhileFalse, b evaluates to false *)
reflexivity.
- (* E_WhileFalse, b evaluates to true (contradiction) *)
rewrite H in H_{2}. discriminate H_{2}.
- (* E_WhileTrue, b evaluates to false (contradiction) *)
rewrite H in H_{4}. discriminate H_{4}.
- (* E_WhileTrue, b evaluates to true *)
assert (st' = st'0) as EQ_{1}.
{ (* Proof of assertion *) apply IHE1_1; assumption. }
subst st'0.
apply IHE1_2. assumption. Qed.
intros c st st_{1} st_{2} E_{1} E_{2}.
generalize dependent st_{2}.
induction E_{1}; intros st_{2} E_{2}; inversion E_{2}; subst.
- (* E_Skip *) reflexivity.
- (* E_Ass *) reflexivity.
- (* E_Seq *)
assert (st' = st'0) as EQ_{1}.
{ (* Proof of assertion *) apply IHE1_1; assumption. }
subst st'0.
apply IHE1_2. assumption.
- (* E_IfTrue, b evaluates to true *)
apply IHE1. assumption.
- (* E_IfTrue, b evaluates to false (contradiction) *)
rewrite H in H_{5}. discriminate H_{5}.
- (* E_IfFalse, b evaluates to true (contradiction) *)
rewrite H in H_{5}. discriminate H_{5}.
- (* E_IfFalse, b evaluates to false *)
apply IHE1. assumption.
- (* E_WhileFalse, b evaluates to false *)
reflexivity.
- (* E_WhileFalse, b evaluates to true (contradiction) *)
rewrite H in H_{2}. discriminate H_{2}.
- (* E_WhileTrue, b evaluates to false (contradiction) *)
rewrite H in H_{4}. discriminate H_{4}.
- (* E_WhileTrue, b evaluates to true *)
assert (st' = st'0) as EQ_{1}.
{ (* Proof of assertion *) apply IHE1_1; assumption. }
subst st'0.
apply IHE1_2. assumption. Qed.
Reasoning About Imp Programs
Theorem plus2_spec : ∀ 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.
Exercise: 3 stars, standard, optional (XtimesYinZ_spec)
State and prove a specification of XtimesYinZ.(* FILL IN HERE *)
(* Do not modify the following line: *)
Definition manual_grade_for_XtimesYinZ_spec : option (nat×string) := None.
☐
Theorem loop_never_stops : ∀ st st',
~(st =[ loop ]=> st').
Proof.
intros st st' contra. unfold loop in contra.
remember (WHILE true DO SKIP END)%imp as loopdef
eqn:Heqloopdef.
~(st =[ loop ]=> st').
Proof.
intros st st' contra. unfold loop in contra.
remember (WHILE true DO SKIP END)%imp 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).
(* FILL IN HERE *) Admitted.
☐
Open Scope imp_scope.
Fixpoint no_whiles (c : com) : bool :=
match c with
| SKIP ⇒
true
| _ ::= _ ⇒
true
| c_{1} ;; c_{2} ⇒
andb (no_whiles c_{1}) (no_whiles c_{2})
| TEST _ THEN ct ELSE cf FI ⇒
andb (no_whiles ct) (no_whiles cf)
| WHILE _ DO _ END ⇒
false
end.
Close Scope imp_scope.
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 :=
(* FILL IN HERE *)
.
Theorem no_whiles_eqv:
∀ c, no_whiles c = true ↔ no_whilesR c.
Proof.
(* FILL IN HERE *) Admitted.
☐
Exercise: 4 stars, standard (no_whiles_terminating)
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.(* FILL IN HERE *)
(* Do not modify the following line: *)
Definition manual_grade_for_no_whiles_terminating : option (nat×string) := None.
☐
Additional Exercises
Exercise: 3 stars, standard (stack_compiler)
Old HP Calculators, programming languages like Forth and Postscript, and abstract machines like the Java Virtual Machine all evaluate arithmetic expressions using a stack. For instance, the expression(2*3)+(3*(4-2))would be written as
2 3 * 3 4 2 - * +and evaluated like this (where we show the program being evaluated on the right and the contents of the stack on the left):
[ ] | 2 3 * 3 4 2 - * + [2] | 3 * 3 4 2 - * + [3, 2] | * 3 4 2 - * + [6] | 3 4 2 - * + [3, 6] | 4 2 - * + [4, 3, 6] | 2 - * + [2, 4, 3, 6] | - * + [2, 3, 6] | * + [6, 6] | + [12] |The goal of this exercise is to write a small compiler that translates aexps into stack machine instructions.
- 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.
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
(* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted.
Example s_execute1 :
s_execute empty_st []
[SPush 5; SPush 3; SPush 1; SMinus]
= [2; 5].
(* FILL IN HERE *) Admitted.
Example s_execute2 :
s_execute (X !-> 3) [3;4]
[SPush 4; SLoad X; SMult; SPlus]
= [15; 4].
(* FILL IN HERE *) Admitted.
Next, write a function that compiles an aexp into a stack
machine program. The effect of running the program should be the
same as pushing the value of the expression on the stack.
Fixpoint s_compile (e : aexp) : list sinstr
(* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted.
After you've defined s_compile, prove the following to test
that it works.
Example s_compile1 :
s_compile (X - (2 × Y))
= [SLoad X; SPush 2; SLoad Y; SMult; SMinus].
(* FILL IN HERE *) Admitted.
☐
Exercise: 3 stars, standard (execute_app)
Theorem execute_app : ∀ st p_{1} p_{2} stack,
s_execute st stack (p_{1} ++ p_{2}) = s_execute st (s_execute st stack p_{1}) p_{2}.
Proof.
(* FILL IN HERE *) Admitted.
☐
Exercise: 3 stars, standard (stack_compiler_correct)
Lemma s_compile_correct_aux : ∀ st e stack,
s_execute st stack (s_compile e) = aeval st e :: stack.
Proof.
(* FILL IN HERE *) Admitted.
The main theorem should be a very easy corollary of that lemma.
Theorem s_compile_correct : ∀ (st : state) (e : aexp),
s_execute st [] (s_compile e) = [ aeval st e ].
Proof.
(* FILL IN HERE *) Admitted.
☐
Exercise: 3 stars, standard, optional (short_circuit)
Most modern programming languages use a "short-circuit" evaluation rule for boolean and: to evaluate BAnd b_{1} b_{2}, first evaluate b_{1}. If it evaluates to false, then the entire BAnd expression evaluates to false immediately, without evaluating b_{2}. Otherwise, b_{2} is evaluated to determine the result of the BAnd expression.(* FILL IN HERE *)
☐
Exercise: 4 stars, advanced (break_imp)
Imperative languages like C and Java often include a break or similar statement for interrupting the execution of loops. In this exercise we consider how to add break to Imp. First, we need to enrich the language of commands with an additional case.Inductive com : Type :=
| CSkip
| CBreak (* <--- NEW *)
| CAss (x : string) (a : aexp)
| CSeq (c_{1} c_{2} : com)
| CIf (b : bexp) (c_{1} c_{2} : com)
| CWhile (b : bexp) (c : com).
Notation "'SKIP'" :=
CSkip.
Notation "'BREAK'" :=
CBreak.
Notation "x '::=' a" :=
(CAss x a) (at level 60).
Notation "c_{1} ;; c_{2}" :=
(CSeq c_{1} c_{2}) (at level 80, right associativity).
Notation "'WHILE' b 'DO' c 'END'" :=
(CWhile b c) (at level 80, right associativity).
Notation "'TEST' c_{1} 'THEN' c_{2} 'ELSE' c_{3} 'FI'" :=
(CIf c_{1} c_{2} c_{3}) (at level 80, right associativity).
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:
X ::= 0;;
Y ::= 1;;
WHILE ~(0 = Y) DO
WHILE true DO
BREAK
END;;
X ::= 1;;
Y ::= Y - 1
END
Inductive result : Type :=
| SContinue
| SBreak.
Reserved Notation "st '=[' c ']=>' st' '/' s"
(at level 40, st' 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 TEST b THEN c_{1} ELSE c_{2} FI, 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 c_{1} ;; c_{2}, we first execute
c_{1}. If this yields a SBreak, we skip the execution of c_{2}
and propagate the SBreak signal to the surrounding context;
the resulting state is the same as the one obtained by
executing c_{1} alone. Otherwise, we execute c_{2} on the state
obtained after executing c_{1}, 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 : ∀ st,
st =[ CSkip ]=> st / SContinue
(* FILL IN HERE *)
where "st '=[' c ']=>' st' '/' s" := (ceval c st s st').
Now prove the following properties of your definition of ceval:
Theorem break_ignore : ∀ c st st' s,
st =[ BREAK;; c ]=> st' / s →
st = st'.
Proof.
(* FILL IN HERE *) Admitted.
Theorem while_continue : ∀ b c st st' s,
st =[ WHILE b DO c END ]=> st' / s →
s = SContinue.
Proof.
(* FILL IN HERE *) Admitted.
Theorem while_stops_on_break : ∀ b c st st',
beval st b = true →
st =[ c ]=> st' / SBreak →
st =[ WHILE b DO c END ]=> st' / SContinue.
Proof.
(* FILL IN HERE *) Admitted.
☐
Theorem while_break_true : ∀ b c st st',
st =[ WHILE b DO c END ]=> st' / SContinue →
beval st' b = true →
∃ st'', st'' =[ c ]=> st' / SBreak.
Proof.
(* FILL IN HERE *) Admitted.
☐
st =[ WHILE b DO c END ]=> st' / SContinue →
beval st' b = true →
∃ st'', st'' =[ c ]=> st' / SBreak.
Proof.
(* FILL IN HERE *) Admitted.
☐
Theorem ceval_deterministic: ∀ (c:com) st st_{1} st_{2} s_{1} s_{2},
st =[ c ]=> st_{1} / s_{1} →
st =[ c ]=> st_{2} / s_{2} →
st_{1} = st_{2} ∧ s_{1} = s_{2}.
Proof.
(* FILL IN HERE *) Admitted.
☐
st =[ c ]=> st_{1} / s_{1} →
st =[ c ]=> st_{2} / s_{2} →
st_{1} = st_{2} ∧ s_{1} = s_{2}.
Proof.
(* FILL IN HERE *) Admitted.
☐
Exercise: 4 stars, standard, optional (add_for_loop)
Add C-style for loops to the language of commands, update the ceval definition to define the semantics of for loops, and add cases for for loops as needed so that all the proofs in this file are accepted by Coq.(* FILL IN HERE *)
☐
(* 30 Apr 2020 *)