adamc@269
|
1 (* Copyright (c) 2008-2010, Adam Chlipala
|
adamc@2
|
2 *
|
adamc@2
|
3 * This work is licensed under a
|
adamc@2
|
4 * Creative Commons Attribution-Noncommercial-No Derivative Works 3.0
|
adamc@2
|
5 * Unported License.
|
adamc@2
|
6 * The license text is available at:
|
adamc@2
|
7 * http://creativecommons.org/licenses/by-nc-nd/3.0/
|
adamc@2
|
8 *)
|
adamc@2
|
9
|
adamc@3
|
10 (* begin hide *)
|
adam@277
|
11 Require Import Arith Bool List.
|
adamc@2
|
12
|
adamc@2
|
13 Require Import Tactics.
|
adamc@14
|
14
|
adamc@14
|
15 Set Implicit Arguments.
|
adamc@3
|
16 (* end hide *)
|
adamc@2
|
17
|
adamc@2
|
18
|
adamc@25
|
19 (** %\chapter{Some Quick Examples}% *)
|
adamc@25
|
20
|
adamc@25
|
21
|
adam@278
|
22 (** I will start off by jumping right in to a fully-worked set of examples, building certified compilers from increasingly complicated source languages to stack machines. We will meet a few useful tactics and see how they can be used in manual proofs, and we will also see how easily these proofs can be automated instead. I assume that you have installed Coq and Proof General. The code in this book is tested with Coq version 8.2pl2, though parts may work with other versions.
|
adamc@9
|
23
|
adam@278
|
24 To set up your Proof General environment to process the source to this chapter, a few simple steps are required.
|
adamc@25
|
25
|
adam@278
|
26 %\begin{enumerate}%#<ol>#
|
adam@278
|
27
|
adam@278
|
28 %\item %#<li>#Get the book source from
|
adam@278
|
29 %\begin{center}\url{http://adam.chlipala.net/cpdt/cpdt.tgz}\end{center}%#<blockquote><tt><a href="http://adam.chlipala.net/cpdt/cpdt.tgz">http://adam.chlipala.net/cpdt/cpdt.tgz</a></tt></blockquote></li>#
|
adam@278
|
30
|
adam@278
|
31 %\item %#<li>#Unpack the tarball to some directory %\texttt{%#<tt>#DIR#</tt>#%}%.#</li>#
|
adam@278
|
32
|
adam@278
|
33 %\item %#<li>#Run %\texttt{%#<tt>#make#</tt>#%}% in %\texttt{%#<tt>#DIR#</tt>#%}%.#</li>#
|
adam@278
|
34
|
adam@278
|
35 %\item %#<li>#There are some minor headaches associated with getting Proof General to pass the proper command line arguments to the %\texttt{%#<tt>#coqtop#</tt>#%}% program, which provides the interactive Coq toplevel. The best way to add settings that will be shared by many source files is to add a custom variable setting to your %\texttt{%#<tt>#.emacs#</tt>#%}% file, like this:
|
adamc@25
|
36 %\begin{verbatim}%#<pre>#(custom-set-variables
|
adamc@25
|
37 ...
|
adam@278
|
38 '(coq-prog-args '("-I" "DIR/src"))
|
adamc@25
|
39 ...
|
adamc@25
|
40 )#</pre>#%\end{verbatim}%
|
adam@278
|
41 The extra arguments demonstrated here are the proper choices for working with the code for this book. The ellipses stand for other Emacs customization settings you may already have. It can be helpful to save several alternate sets of flags in your %\texttt{%#<tt>#.emacs#</tt>#%}% file, with all but one commented out within the %\texttt{%#<tt>#custom-set-variables#</tt>#%}% block at any given time.#</li>#
|
adam@278
|
42
|
adam@278
|
43 #</ol>#%\end{enumerate}%
|
adam@278
|
44
|
adam@278
|
45 As always, you can step through the source file %\texttt{%#<tt>#StackMachine.v#</tt>#%}% for this chapter interactively in Proof General. Alternatively, to get a feel for the whole lifecycle of creating a Coq development, you can enter the pieces of source code in this chapter in a new %\texttt{%#<tt>#.v#</tt>#%}% file in an Emacs buffer. If you do the latter, include two lines [Require Import Arith Bool List Tactics.] and [Set Implicit Arguments.] at the start of the file, to match some code hidden in this rendering of the chapter source, and be sure to run the Coq binary %\texttt{%#<tt>#coqtop#</tt>#%}% with the command-line argument %\texttt{%#<tt>#-I DIR/src#</tt>#%}%. If you have installed Proof General properly, it should start automatically when you visit a %\texttt{%#<tt>#.v#</tt>#%}% buffer in Emacs.
|
adamc@11
|
46
|
adamc@11
|
47 With Proof General, the portion of a buffer that Coq has processed is highlighted in some way, like being given a blue background. You step through Coq source files by positioning the point at the position you want Coq to run to and pressing C-C C-RET. This can be used both for normal step-by-step coding, by placing the point inside some command past the end of the highlighted region; and for undoing, by placing the point inside the highlighted region. *)
|
adamc@9
|
48
|
adamc@9
|
49
|
adamc@20
|
50 (** * Arithmetic Expressions Over Natural Numbers *)
|
adamc@2
|
51
|
adamc@40
|
52 (** We will begin with that staple of compiler textbooks, arithmetic expressions over a single type of numbers. *)
|
adamc@9
|
53
|
adamc@20
|
54 (** ** Source Language *)
|
adamc@9
|
55
|
adamc@9
|
56 (** We begin with the syntax of the source language. *)
|
adamc@2
|
57
|
adamc@4
|
58 Inductive binop : Set := Plus | Times.
|
adamc@2
|
59
|
adamc@9
|
60 (** Our first line of Coq code should be unsurprising to ML and Haskell programmers. We define an algebraic datatype [binop] to stand for the binary operators of our source language. There are just two wrinkles compared to ML and Haskell. First, we use the keyword [Inductive], in place of %\texttt{%#<tt>#data#</tt>#%}%, %\texttt{%#<tt>#datatype#</tt>#%}%, or %\texttt{%#<tt>#type#</tt>#%}%. This is not just a trivial surface syntax difference; inductive types in Coq are much more expressive than garden variety algebraic datatypes, essentially enabling us to encode all of mathematics, though we begin humbly in this chapter. Second, there is the [: Set] fragment, which declares that we are defining a datatype that should be thought of as a constituent of programs. Later, we will see other options for defining datatypes in the universe of proofs or in an infinite hierarchy of universes, encompassing both programs and proofs, that is useful in higher-order constructions. *)
|
adamc@9
|
61
|
adamc@4
|
62 Inductive exp : Set :=
|
adamc@4
|
63 | Const : nat -> exp
|
adamc@4
|
64 | Binop : binop -> exp -> exp -> exp.
|
adamc@2
|
65
|
adamc@9
|
66 (** Now we define the type of arithmetic expressions. We write that a constant may be built from one argument, a natural number; and a binary operation may be built from a choice of operator and two operand expressions.
|
adamc@9
|
67
|
adam@277
|
68 A note for readers following along in the PDF version: coqdoc supports pretty-printing of tokens in LaTeX or HTML. Where you see a right arrow character, the source contains the ASCII text %\texttt{%#<tt>#->#</tt>#%}%. Other examples of this substitution appearing in this chapter are a double right arrow for %\texttt{%#<tt>#=>#</tt>#%}%, the inverted 'A' symbol for %\texttt{%#<tt>#forall#</tt>#%}%, and the Cartesian product 'X' for %\texttt{%#<tt>#*#</tt>#%}%. When in doubt about the ASCII version of a symbol, you can consult the chapter source code.
|
adamc@9
|
69
|
adamc@9
|
70 %\medskip%
|
adamc@9
|
71
|
adamc@9
|
72 Now we are ready to say what these programs mean. We will do this by writing an interpreter that can be thought of as a trivial operational or denotational semantics. (If you are not familiar with these semantic techniques, no need to worry; we will stick to "common sense" constructions.) *)
|
adamc@9
|
73
|
adamc@4
|
74 Definition binopDenote (b : binop) : nat -> nat -> nat :=
|
adamc@4
|
75 match b with
|
adamc@4
|
76 | Plus => plus
|
adamc@4
|
77 | Times => mult
|
adamc@4
|
78 end.
|
adamc@2
|
79
|
adamc@9
|
80 (** The meaning of a binary operator is a binary function over naturals, defined with pattern-matching notation analogous to the %\texttt{%#<tt>#case#</tt>#%}% and %\texttt{%#<tt>#match#</tt>#%}% of ML and Haskell, and referring to the functions [plus] and [mult] from the Coq standard library. The keyword [Definition] is Coq's all-purpose notation for binding a term of the programming language to a name, with some associated syntactic sugar, like the notation we see here for defining a function. That sugar could be expanded to yield this definition:
|
adamc@9
|
81
|
adamc@9
|
82 [[
|
adamc@9
|
83 Definition binopDenote : binop -> nat -> nat -> nat := fun (b : binop) =>
|
adamc@9
|
84 match b with
|
adamc@9
|
85 | Plus => plus
|
adamc@9
|
86 | Times => mult
|
adamc@9
|
87 end.
|
adamc@9
|
88
|
adamc@205
|
89 ]]
|
adamc@205
|
90
|
adamc@9
|
91 In this example, we could also omit all of the type annotations, arriving at:
|
adamc@9
|
92
|
adamc@9
|
93 [[
|
adamc@9
|
94 Definition binopDenote := fun b =>
|
adamc@9
|
95 match b with
|
adamc@9
|
96 | Plus => plus
|
adamc@9
|
97 | Times => mult
|
adamc@9
|
98 end.
|
adamc@9
|
99
|
adamc@205
|
100 ]]
|
adamc@205
|
101
|
adamc@9
|
102 Languages like Haskell and ML have a convenient %\textit{%#<i>#principal typing#</i>#%}% property, which gives us strong guarantees about how effective type inference will be. Unfortunately, Coq's type system is so expressive that any kind of "complete" type inference is impossible, and the task even seems to be hard heuristically in practice. Nonetheless, Coq includes some very helpful heuristics, many of them copying the workings of Haskell and ML type-checkers for programs that fall in simple fragments of Coq's language.
|
adamc@9
|
103
|
adamc@9
|
104 This is as good a time as any to mention the preponderance of different languages associated with Coq. The theoretical foundation of Coq is a formal system called the %\textit{%#<i>#Calculus of Inductive Constructions (CIC)#</i>#%}%, which is an extension of the older %\textit{%#<i>#Calculus of Constructions (CoC)#</i>#%}%. CIC is quite a spartan foundation, which is helpful for proving metatheory but not so helpful for real development. Still, it is nice to know that it has been proved that CIC enjoys properties like %\textit{%#<i>#strong normalization#</i>#%}%, meaning that every program (and, more importantly, every proof term) terminates; and %\textit{%#<i>#relative consistency#</i>#%}% with systems like versions of Zermelo Fraenkel set theory, which roughly means that you can believe that Coq proofs mean that the corresponding propositions are "really true," if you believe in set theory.
|
adamc@9
|
105
|
adamc@40
|
106 Coq is actually based on an extension of CIC called %\textit{%#<i>#Gallina#</i>#%}%. The text after the [:=] and before the period in the last code example is a term of Gallina. Gallina adds many useful features that are not compiled internally to more primitive CIC features. The important metatheorems about CIC have not been extended to the full breadth of these features, but most Coq users do not seem to lose much sleep over this omission.
|
adamc@9
|
107
|
adamc@9
|
108 Commands like [Inductive] and [Definition] are part of %\textit{%#<i>#the vernacular#</i>#%}%, which includes all sorts of useful queries and requests to the Coq system.
|
adamc@9
|
109
|
adamc@9
|
110 Finally, there is %\textit{%#<i>#Ltac#</i>#%}%, Coq's domain-specific language for writing proofs and decision procedures. We will see some basic examples of Ltac later in this chapter, and much of this book is devoted to more involved Ltac examples.
|
adamc@9
|
111
|
adamc@9
|
112 %\medskip%
|
adamc@9
|
113
|
adamc@9
|
114 We can give a simple definition of the meaning of an expression: *)
|
adamc@9
|
115
|
adamc@4
|
116 Fixpoint expDenote (e : exp) : nat :=
|
adamc@4
|
117 match e with
|
adamc@4
|
118 | Const n => n
|
adamc@4
|
119 | Binop b e1 e2 => (binopDenote b) (expDenote e1) (expDenote e2)
|
adamc@4
|
120 end.
|
adamc@2
|
121
|
adamc@9
|
122 (** We declare explicitly that this is a recursive definition, using the keyword [Fixpoint]. The rest should be old hat for functional programmers. *)
|
adamc@2
|
123
|
adamc@16
|
124 (** It is convenient to be able to test definitions before starting to prove things about them. We can verify that our semantics is sensible by evaluating some sample uses. *)
|
adamc@16
|
125
|
adamc@16
|
126 Eval simpl in expDenote (Const 42).
|
adamc@205
|
127 (** [= 42 : nat] *)
|
adamc@205
|
128
|
adamc@16
|
129 Eval simpl in expDenote (Binop Plus (Const 2) (Const 2)).
|
adamc@205
|
130 (** [= 4 : nat] *)
|
adamc@205
|
131
|
adamc@16
|
132 Eval simpl in expDenote (Binop Times (Binop Plus (Const 2) (Const 2)) (Const 7)).
|
adamc@205
|
133 (** [= 28 : nat] *)
|
adamc@9
|
134
|
adamc@20
|
135 (** ** Target Language *)
|
adamc@4
|
136
|
adamc@10
|
137 (** We will compile our source programs onto a simple stack machine, whose syntax is: *)
|
adamc@2
|
138
|
adamc@4
|
139 Inductive instr : Set :=
|
adamc@4
|
140 | IConst : nat -> instr
|
adamc@4
|
141 | IBinop : binop -> instr.
|
adamc@2
|
142
|
adamc@4
|
143 Definition prog := list instr.
|
adamc@4
|
144 Definition stack := list nat.
|
adamc@2
|
145
|
adamc@10
|
146 (** An instruction either pushes a constant onto the stack or pops two arguments, applies a binary operator to them, and pushes the result onto the stack. A program is a list of instructions, and a stack is a list of natural numbers.
|
adamc@10
|
147
|
adamc@10
|
148 We can give instructions meanings as functions from stacks to optional stacks, where running an instruction results in [None] in case of a stack underflow and results in [Some s'] when the result of execution is the new stack [s']. [::] is the "list cons" operator from the Coq standard library. *)
|
adamc@10
|
149
|
adamc@4
|
150 Definition instrDenote (i : instr) (s : stack) : option stack :=
|
adamc@4
|
151 match i with
|
adamc@4
|
152 | IConst n => Some (n :: s)
|
adamc@4
|
153 | IBinop b =>
|
adamc@4
|
154 match s with
|
adamc@4
|
155 | arg1 :: arg2 :: s' => Some ((binopDenote b) arg1 arg2 :: s')
|
adamc@4
|
156 | _ => None
|
adamc@4
|
157 end
|
adamc@4
|
158 end.
|
adamc@2
|
159
|
adamc@206
|
160 (** With [instrDenote] defined, it is easy to define a function [progDenote], which iterates application of [instrDenote] through a whole program.
|
adamc@10
|
161
|
adamc@206
|
162 [[
|
adamc@4
|
163 Fixpoint progDenote (p : prog) (s : stack) {struct p} : option stack :=
|
adamc@4
|
164 match p with
|
adamc@4
|
165 | nil => Some s
|
adamc@4
|
166 | i :: p' =>
|
adamc@4
|
167 match instrDenote i s with
|
adamc@4
|
168 | None => None
|
adamc@4
|
169 | Some s' => progDenote p' s'
|
adamc@4
|
170 end
|
adamc@4
|
171 end.
|
adamc@2
|
172
|
adamc@206
|
173 ]]
|
adamc@206
|
174
|
adamc@206
|
175 There is one interesting difference compared to our previous example of a [Fixpoint]. This recursive function takes two arguments, [p] and [s]. It is critical for the soundness of Coq that every program terminate, so a shallow syntactic termination check is imposed on every recursive function definition. One of the function parameters must be designated to decrease monotonically across recursive calls. That is, every recursive call must use a version of that argument that has been pulled out of the current argument by some number of [match] expressions. [expDenote] has only one argument, so we did not need to specify which of its arguments decreases. For [progDenote], we resolve the ambiguity by writing [{struct p}] to indicate that argument [p] decreases structurally.
|
adamc@206
|
176
|
adamc@206
|
177 Recent versions of Coq will also infer a termination argument, so that we may write simply: *)
|
adamc@206
|
178
|
adamc@206
|
179 Fixpoint progDenote (p : prog) (s : stack) : option stack :=
|
adamc@206
|
180 match p with
|
adamc@206
|
181 | nil => Some s
|
adamc@206
|
182 | i :: p' =>
|
adamc@206
|
183 match instrDenote i s with
|
adamc@206
|
184 | None => None
|
adamc@206
|
185 | Some s' => progDenote p' s'
|
adamc@206
|
186 end
|
adamc@206
|
187 end.
|
adamc@2
|
188
|
adamc@4
|
189
|
adamc@9
|
190 (** ** Translation *)
|
adamc@4
|
191
|
adamc@10
|
192 (** Our compiler itself is now unsurprising. [++] is the list concatenation operator from the Coq standard library. *)
|
adamc@2
|
193
|
adamc@4
|
194 Fixpoint compile (e : exp) : prog :=
|
adamc@4
|
195 match e with
|
adamc@4
|
196 | Const n => IConst n :: nil
|
adamc@4
|
197 | Binop b e1 e2 => compile e2 ++ compile e1 ++ IBinop b :: nil
|
adamc@4
|
198 end.
|
adamc@2
|
199
|
adamc@2
|
200
|
adamc@16
|
201 (** Before we set about proving that this compiler is correct, we can try a few test runs, using our sample programs from earlier. *)
|
adamc@16
|
202
|
adamc@16
|
203 Eval simpl in compile (Const 42).
|
adamc@206
|
204 (** [= IConst 42 :: nil : prog] *)
|
adamc@206
|
205
|
adamc@16
|
206 Eval simpl in compile (Binop Plus (Const 2) (Const 2)).
|
adamc@206
|
207 (** [= IConst 2 :: IConst 2 :: IBinop Plus :: nil : prog] *)
|
adamc@206
|
208
|
adamc@16
|
209 Eval simpl in compile (Binop Times (Binop Plus (Const 2) (Const 2)) (Const 7)).
|
adamc@206
|
210 (** [= IConst 7 :: IConst 2 :: IConst 2 :: IBinop Plus :: IBinop Times :: nil : prog] *)
|
adamc@16
|
211
|
adamc@40
|
212 (** We can also run our compiled programs and check that they give the right results. *)
|
adamc@16
|
213
|
adamc@16
|
214 Eval simpl in progDenote (compile (Const 42)) nil.
|
adamc@206
|
215 (** [= Some (42 :: nil) : option stack] *)
|
adamc@206
|
216
|
adamc@16
|
217 Eval simpl in progDenote (compile (Binop Plus (Const 2) (Const 2))) nil.
|
adamc@206
|
218 (** [= Some (4 :: nil) : option stack] *)
|
adamc@206
|
219
|
adamc@16
|
220 Eval simpl in progDenote (compile (Binop Times (Binop Plus (Const 2) (Const 2)) (Const 7))) nil.
|
adamc@206
|
221 (** [= Some (28 :: nil) : option stack] *)
|
adamc@16
|
222
|
adamc@16
|
223
|
adamc@20
|
224 (** ** Translation Correctness *)
|
adamc@4
|
225
|
adamc@11
|
226 (** We are ready to prove that our compiler is implemented correctly. We can use a new vernacular command [Theorem] to start a correctness proof, in terms of the semantics we defined earlier: *)
|
adamc@11
|
227
|
adamc@26
|
228 Theorem compile_correct : forall e, progDenote (compile e) nil = Some (expDenote e :: nil).
|
adamc@11
|
229 (* begin hide *)
|
adamc@11
|
230 Abort.
|
adamc@11
|
231 (* end hide *)
|
adamc@22
|
232 (* begin thide *)
|
adamc@11
|
233
|
adamc@11
|
234 (** Though a pencil-and-paper proof might clock out at this point, writing "by a routine induction on [e]," it turns out not to make sense to attack this proof directly. We need to use the standard trick of %\textit{%#<i>#strengthening the induction hypothesis#</i>#%}%. We do that by proving an auxiliary lemma:
|
adamc@11
|
235 *)
|
adamc@2
|
236
|
adamc@206
|
237 Lemma compile_correct' : forall e p s,
|
adamc@206
|
238 progDenote (compile e ++ p) s = progDenote p (expDenote e :: s).
|
adamc@11
|
239
|
adamc@11
|
240 (** After the period in the [Lemma] command, we are in %\textit{%#<i>#the interactive proof-editing mode#</i>#%}%. We find ourselves staring at this ominous screen of text:
|
adamc@11
|
241
|
adamc@11
|
242 [[
|
adamc@11
|
243 1 subgoal
|
adamc@11
|
244
|
adamc@11
|
245 ============================
|
adamc@15
|
246 forall (e : exp) (p : list instr) (s : stack),
|
adamc@15
|
247 progDenote (compile e ++ p) s = progDenote p (expDenote e :: s)
|
adamc@206
|
248
|
adamc@11
|
249 ]]
|
adamc@11
|
250
|
adamc@11
|
251 Coq seems to be restating the lemma for us. What we are seeing is a limited case of a more general protocol for describing where we are in a proof. We are told that we have a single subgoal. In general, during a proof, we can have many pending subgoals, each of which is a logical proposition to prove. Subgoals can be proved in any order, but it usually works best to prove them in the order that Coq chooses.
|
adamc@11
|
252
|
adamc@11
|
253 Next in the output, we see our single subgoal described in full detail. There is a double-dashed line, above which would be our free variables and hypotheses, if we had any. Below the line is the conclusion, which, in general, is to be proved from the hypotheses.
|
adamc@11
|
254
|
adamc@11
|
255 We manipulate the proof state by running commands called %\textit{%#<i>#tactics#</i>#%}%. Let us start out by running one of the most important tactics:
|
adamc@11
|
256 *)
|
adamc@11
|
257
|
adamc@4
|
258 induction e.
|
adamc@2
|
259
|
adamc@11
|
260 (** We declare that this proof will proceed by induction on the structure of the expression [e]. This swaps out our initial subgoal for two new subgoals, one for each case of the inductive proof:
|
adamc@11
|
261
|
adamc@11
|
262 [[
|
adamc@11
|
263 2 subgoals
|
adamc@11
|
264
|
adamc@11
|
265 n : nat
|
adamc@11
|
266 ============================
|
adamc@11
|
267 forall (s : stack) (p : list instr),
|
adamc@11
|
268 progDenote (compile (Const n) ++ p) s =
|
adamc@11
|
269 progDenote p (expDenote (Const n) :: s)
|
adamc@11
|
270 ]]
|
adamc@11
|
271 [[
|
adamc@11
|
272 subgoal 2 is:
|
adamc@11
|
273 forall (s : stack) (p : list instr),
|
adamc@11
|
274 progDenote (compile (Binop b e1 e2) ++ p) s =
|
adamc@11
|
275 progDenote p (expDenote (Binop b e1 e2) :: s)
|
adamc@206
|
276
|
adamc@11
|
277 ]]
|
adamc@11
|
278
|
adamc@11
|
279 The first and current subgoal is displayed with the double-dashed line below free variables and hypotheses, while later subgoals are only summarized with their conclusions. We see an example of a free variable in the first subgoal; [n] is a free variable of type [nat]. The conclusion is the original theorem statement where [e] has been replaced by [Const n]. In a similar manner, the second case has [e] replaced by a generalized invocation of the [Binop] expression constructor. We can see that proving both cases corresponds to a standard proof by structural induction.
|
adamc@11
|
280
|
adamc@11
|
281 We begin the first case with another very common tactic.
|
adamc@11
|
282 *)
|
adamc@11
|
283
|
adamc@4
|
284 intros.
|
adamc@11
|
285
|
adamc@11
|
286 (** The current subgoal changes to:
|
adamc@11
|
287 [[
|
adamc@11
|
288
|
adamc@11
|
289 n : nat
|
adamc@11
|
290 s : stack
|
adamc@11
|
291 p : list instr
|
adamc@11
|
292 ============================
|
adamc@11
|
293 progDenote (compile (Const n) ++ p) s =
|
adamc@11
|
294 progDenote p (expDenote (Const n) :: s)
|
adamc@206
|
295
|
adamc@11
|
296 ]]
|
adamc@11
|
297
|
adamc@11
|
298 We see that [intros] changes [forall]-bound variables at the beginning of a goal into free variables.
|
adamc@11
|
299
|
adamc@11
|
300 To progress further, we need to use the definitions of some of the functions appearing in the goal. The [unfold] tactic replaces an identifier with its definition.
|
adamc@11
|
301 *)
|
adamc@11
|
302
|
adamc@4
|
303 unfold compile.
|
adamc@11
|
304 (** [[
|
adamc@11
|
305 n : nat
|
adamc@11
|
306 s : stack
|
adamc@11
|
307 p : list instr
|
adamc@11
|
308 ============================
|
adamc@11
|
309 progDenote ((IConst n :: nil) ++ p) s =
|
adamc@11
|
310 progDenote p (expDenote (Const n) :: s)
|
adamc@206
|
311
|
adamc@11
|
312 ]] *)
|
adamc@11
|
313
|
adamc@4
|
314 unfold expDenote.
|
adamc@11
|
315 (** [[
|
adamc@11
|
316 n : nat
|
adamc@11
|
317 s : stack
|
adamc@11
|
318 p : list instr
|
adamc@11
|
319 ============================
|
adamc@11
|
320 progDenote ((IConst n :: nil) ++ p) s = progDenote p (n :: s)
|
adamc@206
|
321
|
adamc@11
|
322 ]]
|
adamc@11
|
323
|
adamc@11
|
324 We only need to unfold the first occurrence of [progDenote] to prove the goal: *)
|
adamc@11
|
325
|
adamc@11
|
326 unfold progDenote at 1.
|
adamc@11
|
327
|
adamc@11
|
328 (** [[
|
adamc@11
|
329
|
adamc@11
|
330 n : nat
|
adamc@11
|
331 s : stack
|
adamc@11
|
332 p : list instr
|
adamc@11
|
333 ============================
|
adamc@11
|
334 (fix progDenote (p0 : prog) (s0 : stack) {struct p0} :
|
adamc@11
|
335 option stack :=
|
adamc@11
|
336 match p0 with
|
adamc@11
|
337 | nil => Some s0
|
adamc@11
|
338 | i :: p' =>
|
adamc@11
|
339 match instrDenote i s0 with
|
adamc@11
|
340 | Some s' => progDenote p' s'
|
adamc@11
|
341 | None => None (A:=stack)
|
adamc@11
|
342 end
|
adamc@11
|
343 end) ((IConst n :: nil) ++ p) s =
|
adamc@11
|
344 progDenote p (n :: s)
|
adamc@206
|
345
|
adamc@11
|
346 ]]
|
adamc@11
|
347
|
adamc@11
|
348 This last [unfold] has left us with an anonymous fixpoint version of [progDenote], which will generally happen when unfolding recursive definitions. Fortunately, in this case, we can eliminate such complications right away, since the structure of the argument [(IConst n :: nil) ++ p] is known, allowing us to simplify the internal pattern match with the [simpl] tactic:
|
adamc@11
|
349 *)
|
adamc@11
|
350
|
adamc@4
|
351 simpl.
|
adamc@11
|
352 (** [[
|
adamc@11
|
353 n : nat
|
adamc@11
|
354 s : stack
|
adamc@11
|
355 p : list instr
|
adamc@11
|
356 ============================
|
adamc@11
|
357 (fix progDenote (p0 : prog) (s0 : stack) {struct p0} :
|
adamc@11
|
358 option stack :=
|
adamc@11
|
359 match p0 with
|
adamc@11
|
360 | nil => Some s0
|
adamc@11
|
361 | i :: p' =>
|
adamc@11
|
362 match instrDenote i s0 with
|
adamc@11
|
363 | Some s' => progDenote p' s'
|
adamc@11
|
364 | None => None (A:=stack)
|
adamc@11
|
365 end
|
adamc@11
|
366 end) p (n :: s) = progDenote p (n :: s)
|
adamc@206
|
367
|
adamc@11
|
368 ]]
|
adamc@11
|
369
|
adamc@11
|
370 Now we can unexpand the definition of [progDenote]:
|
adamc@11
|
371 *)
|
adamc@11
|
372
|
adamc@11
|
373 fold progDenote.
|
adamc@11
|
374
|
adamc@11
|
375 (** [[
|
adamc@11
|
376
|
adamc@11
|
377 n : nat
|
adamc@11
|
378 s : stack
|
adamc@11
|
379 p : list instr
|
adamc@11
|
380 ============================
|
adamc@11
|
381 progDenote p (n :: s) = progDenote p (n :: s)
|
adamc@206
|
382
|
adamc@11
|
383 ]]
|
adamc@11
|
384
|
adamc@11
|
385 It looks like we are at the end of this case, since we have a trivial equality. Indeed, a single tactic finishes us off:
|
adamc@11
|
386 *)
|
adamc@11
|
387
|
adamc@4
|
388 reflexivity.
|
adamc@2
|
389
|
adamc@11
|
390 (** On to the second inductive case:
|
adamc@11
|
391
|
adamc@11
|
392 [[
|
adamc@11
|
393 b : binop
|
adamc@11
|
394 e1 : exp
|
adamc@11
|
395 IHe1 : forall (s : stack) (p : list instr),
|
adamc@11
|
396 progDenote (compile e1 ++ p) s = progDenote p (expDenote e1 :: s)
|
adamc@11
|
397 e2 : exp
|
adamc@11
|
398 IHe2 : forall (s : stack) (p : list instr),
|
adamc@11
|
399 progDenote (compile e2 ++ p) s = progDenote p (expDenote e2 :: s)
|
adamc@11
|
400 ============================
|
adamc@11
|
401 forall (s : stack) (p : list instr),
|
adamc@11
|
402 progDenote (compile (Binop b e1 e2) ++ p) s =
|
adamc@11
|
403 progDenote p (expDenote (Binop b e1 e2) :: s)
|
adamc@206
|
404
|
adamc@11
|
405 ]]
|
adamc@11
|
406
|
adamc@11
|
407 We see our first example of hypotheses above the double-dashed line. They are the inductive hypotheses [IHe1] and [IHe2] corresponding to the subterms [e1] and [e2], respectively.
|
adamc@11
|
408
|
adamc@11
|
409 We start out the same way as before, introducing new free variables and unfolding and folding the appropriate definitions. The seemingly frivolous [unfold]/[fold] pairs are actually accomplishing useful work, because [unfold] will sometimes perform easy simplifications. *)
|
adamc@11
|
410
|
adamc@4
|
411 intros.
|
adamc@4
|
412 unfold compile.
|
adamc@4
|
413 fold compile.
|
adamc@4
|
414 unfold expDenote.
|
adamc@4
|
415 fold expDenote.
|
adamc@11
|
416
|
adamc@44
|
417 (** Now we arrive at a point where the tactics we have seen so far are insufficient. No further definition unfoldings get us anywhere, so we will need to try something different.
|
adamc@11
|
418
|
adamc@11
|
419 [[
|
adamc@11
|
420 b : binop
|
adamc@11
|
421 e1 : exp
|
adamc@11
|
422 IHe1 : forall (s : stack) (p : list instr),
|
adamc@11
|
423 progDenote (compile e1 ++ p) s = progDenote p (expDenote e1 :: s)
|
adamc@11
|
424 e2 : exp
|
adamc@11
|
425 IHe2 : forall (s : stack) (p : list instr),
|
adamc@11
|
426 progDenote (compile e2 ++ p) s = progDenote p (expDenote e2 :: s)
|
adamc@11
|
427 s : stack
|
adamc@11
|
428 p : list instr
|
adamc@11
|
429 ============================
|
adamc@11
|
430 progDenote ((compile e2 ++ compile e1 ++ IBinop b :: nil) ++ p) s =
|
adamc@11
|
431 progDenote p (binopDenote b (expDenote e1) (expDenote e2) :: s)
|
adamc@206
|
432
|
adamc@11
|
433 ]]
|
adamc@11
|
434
|
adam@277
|
435 What we need is the associative law of list concatenation, which is available as a theorem [app_ass] in the standard library. *)
|
adamc@11
|
436
|
adamc@11
|
437 Check app_ass.
|
adamc@11
|
438 (** [[
|
adamc@11
|
439 app_ass
|
adamc@11
|
440 : forall (A : Type) (l m n : list A), (l ++ m) ++ n = l ++ m ++ n
|
adamc@206
|
441
|
adamc@11
|
442 ]]
|
adamc@11
|
443
|
adam@277
|
444 If we did not already know the name of the theorem, we could use the [SearchRewrite] command to find it, based on a pattern that we would like to rewrite: *)
|
adam@277
|
445
|
adam@277
|
446 SearchRewrite ((_ ++ _) ++ _).
|
adam@277
|
447 (** [[
|
adam@277
|
448 app_ass: forall (A : Type) (l m n : list A), (l ++ m) ++ n = l ++ m ++ n
|
adam@277
|
449 ass_app: forall (A : Type) (l m n : list A), l ++ m ++ n = (l ++ m) ++ n
|
adam@277
|
450
|
adam@277
|
451 ]]
|
adam@277
|
452
|
adamc@11
|
453 We use it to perform a rewrite: *)
|
adamc@11
|
454
|
adamc@4
|
455 rewrite app_ass.
|
adamc@11
|
456
|
adamc@206
|
457 (** changing the conclusion to:
|
adamc@11
|
458
|
adamc@206
|
459 [[
|
adamc@11
|
460 progDenote (compile e2 ++ (compile e1 ++ IBinop b :: nil) ++ p) s =
|
adamc@11
|
461 progDenote p (binopDenote b (expDenote e1) (expDenote e2) :: s)
|
adamc@206
|
462
|
adamc@11
|
463 ]]
|
adamc@11
|
464
|
adamc@11
|
465 Now we can notice that the lefthand side of the equality matches the lefthand side of the second inductive hypothesis, so we can rewrite with that hypothesis, too: *)
|
adamc@11
|
466
|
adamc@4
|
467 rewrite IHe2.
|
adamc@11
|
468 (** [[
|
adamc@11
|
469 progDenote ((compile e1 ++ IBinop b :: nil) ++ p) (expDenote e2 :: s) =
|
adamc@11
|
470 progDenote p (binopDenote b (expDenote e1) (expDenote e2) :: s)
|
adamc@206
|
471
|
adamc@11
|
472 ]]
|
adamc@11
|
473
|
adamc@11
|
474 The same process lets us apply the remaining hypothesis. *)
|
adamc@11
|
475
|
adamc@4
|
476 rewrite app_ass.
|
adamc@4
|
477 rewrite IHe1.
|
adamc@11
|
478 (** [[
|
adamc@11
|
479 progDenote ((IBinop b :: nil) ++ p) (expDenote e1 :: expDenote e2 :: s) =
|
adamc@11
|
480 progDenote p (binopDenote b (expDenote e1) (expDenote e2) :: s)
|
adamc@206
|
481
|
adamc@11
|
482 ]]
|
adamc@11
|
483
|
adamc@11
|
484 Now we can apply a similar sequence of tactics to that that ended the proof of the first case.
|
adamc@11
|
485 *)
|
adamc@11
|
486
|
adamc@11
|
487 unfold progDenote at 1.
|
adamc@4
|
488 simpl.
|
adamc@11
|
489 fold progDenote.
|
adamc@4
|
490 reflexivity.
|
adamc@11
|
491
|
adamc@11
|
492 (** And the proof is completed, as indicated by the message:
|
adamc@11
|
493
|
adamc@11
|
494 [[
|
adamc@11
|
495 Proof completed.
|
adamc@11
|
496
|
adamc@205
|
497 ]]
|
adamc@205
|
498
|
adamc@11
|
499 And there lies our first proof. Already, even for simple theorems like this, the final proof script is unstructured and not very enlightening to readers. If we extend this approach to more serious theorems, we arrive at the unreadable proof scripts that are the favorite complaints of opponents of tactic-based proving. Fortunately, Coq has rich support for scripted automation, and we can take advantage of such a scripted tactic (defined elsewhere) to make short work of this lemma. We abort the old proof attempt and start again.
|
adamc@11
|
500 *)
|
adamc@11
|
501
|
adamc@4
|
502 Abort.
|
adamc@2
|
503
|
adamc@26
|
504 Lemma compile_correct' : forall e s p, progDenote (compile e ++ p) s =
|
adamc@4
|
505 progDenote p (expDenote e :: s).
|
adamc@4
|
506 induction e; crush.
|
adamc@4
|
507 Qed.
|
adamc@2
|
508
|
adamc@11
|
509 (** We need only to state the basic inductive proof scheme and call a tactic that automates the tedious reasoning in between. In contrast to the period tactic terminator from our last proof, the semicolon tactic separator supports structured, compositional proofs. The tactic [t1; t2] has the effect of running [t1] and then running [t2] on each remaining subgoal. The semicolon is one of the most fundamental building blocks of effective proof automation. The period terminator is very useful for exploratory proving, where you need to see intermediate proof states, but final proofs of any serious complexity should have just one period, terminating a single compound tactic that probably uses semicolons.
|
adamc@11
|
510
|
adamc@210
|
511 The [crush] tactic comes from the library associated with this book and is not part of the Coq standard library. The book's library contains a number of other tactics that are especially helpful in highly-automated proofs.
|
adamc@210
|
512
|
adamc@11
|
513 The proof of our main theorem is now easy. We prove it with four period-terminated tactics, though separating them with semicolons would work as well; the version here is easier to step through. *)
|
adamc@11
|
514
|
adamc@26
|
515 Theorem compile_correct : forall e, progDenote (compile e) nil = Some (expDenote e :: nil).
|
adamc@11
|
516 intros.
|
adamc@11
|
517 (** [[
|
adamc@11
|
518 e : exp
|
adamc@11
|
519 ============================
|
adamc@11
|
520 progDenote (compile e) nil = Some (expDenote e :: nil)
|
adamc@206
|
521
|
adamc@11
|
522 ]]
|
adamc@11
|
523
|
adamc@26
|
524 At this point, we want to massage the lefthand side to match the statement of [compile_correct']. A theorem from the standard library is useful: *)
|
adamc@11
|
525
|
adamc@11
|
526 Check app_nil_end.
|
adamc@11
|
527 (** [[
|
adamc@11
|
528 app_nil_end
|
adamc@11
|
529 : forall (A : Type) (l : list A), l = l ++ nil
|
adamc@11
|
530 ]] *)
|
adamc@11
|
531
|
adamc@4
|
532 rewrite (app_nil_end (compile e)).
|
adamc@11
|
533
|
adamc@11
|
534 (** This time, we explicitly specify the value of the variable [l] from the theorem statement, since multiple expressions of list type appear in the conclusion. [rewrite] might choose the wrong place to rewrite if we did not specify which we want.
|
adamc@11
|
535
|
adamc@11
|
536 [[
|
adamc@11
|
537 e : exp
|
adamc@11
|
538 ============================
|
adamc@11
|
539 progDenote (compile e ++ nil) nil = Some (expDenote e :: nil)
|
adamc@206
|
540
|
adamc@11
|
541 ]]
|
adamc@11
|
542
|
adamc@11
|
543 Now we can apply the lemma. *)
|
adamc@11
|
544
|
adamc@26
|
545 rewrite compile_correct'.
|
adamc@11
|
546 (** [[
|
adamc@11
|
547 e : exp
|
adamc@11
|
548 ============================
|
adamc@11
|
549 progDenote nil (expDenote e :: nil) = Some (expDenote e :: nil)
|
adamc@206
|
550
|
adamc@11
|
551 ]]
|
adamc@11
|
552
|
adamc@11
|
553 We are almost done. The lefthand and righthand sides can be seen to match by simple symbolic evaluation. That means we are in luck, because Coq identifies any pair of terms as equal whenever they normalize to the same result by symbolic evaluation. By the definition of [progDenote], that is the case here, but we do not need to worry about such details. A simple invocation of [reflexivity] does the normalization and checks that the two results are syntactically equal. *)
|
adamc@11
|
554
|
adamc@4
|
555 reflexivity.
|
adamc@4
|
556 Qed.
|
adamc@22
|
557 (* end thide *)
|
adamc@14
|
558
|
adamc@14
|
559
|
adamc@20
|
560 (** * Typed Expressions *)
|
adamc@14
|
561
|
adamc@14
|
562 (** In this section, we will build on the initial example by adding additional expression forms that depend on static typing of terms for safety. *)
|
adamc@14
|
563
|
adamc@20
|
564 (** ** Source Language *)
|
adamc@14
|
565
|
adamc@15
|
566 (** We define a trivial language of types to classify our expressions: *)
|
adamc@15
|
567
|
adamc@14
|
568 Inductive type : Set := Nat | Bool.
|
adamc@14
|
569
|
adam@277
|
570 (** Like most programming languages, Coq uses case-sensitive variable names, so that our user-defined type [type] is distinct from the [Type] keyword that we have already seen appear in the statement of a polymorphic theorem (and that we will meet in more detail later), and our constructor names [Nat] and [Bool] are distinct from the types [nat] and [bool] in the standard library.
|
adam@277
|
571
|
adam@277
|
572 Now we define an expanded set of binary operators. *)
|
adamc@15
|
573
|
adamc@14
|
574 Inductive tbinop : type -> type -> type -> Set :=
|
adamc@14
|
575 | TPlus : tbinop Nat Nat Nat
|
adamc@14
|
576 | TTimes : tbinop Nat Nat Nat
|
adamc@14
|
577 | TEq : forall t, tbinop t t Bool
|
adamc@14
|
578 | TLt : tbinop Nat Nat Bool.
|
adamc@14
|
579
|
adamc@15
|
580 (** The definition of [tbinop] is different from [binop] in an important way. Where we declared that [binop] has type [Set], here we declare that [tbinop] has type [type -> type -> type -> Set]. We define [tbinop] as an %\textit{%#<i>#indexed type family#</i>#%}%. Indexed inductive types are at the heart of Coq's expressive power; almost everything else of interest is defined in terms of them.
|
adamc@15
|
581
|
adamc@15
|
582 ML and Haskell have indexed algebraic datatypes. For instance, their list types are indexed by the type of data that the list carries. However, compared to Coq, ML and Haskell 98 place two important restrictions on datatype definitions.
|
adamc@15
|
583
|
adamc@15
|
584 First, the indices of the range of each data constructor must be type variables bound at the top level of the datatype definition. There is no way to do what we did here, where we, for instance, say that [TPlus] is a constructor building a [tbinop] whose indices are all fixed at [Nat]. %\textit{%#<i>#Generalized algebraic datatypes (GADTs)#</i>#%}% are a popular feature in GHC Haskell and other languages that removes this first restriction.
|
adamc@15
|
585
|
adamc@40
|
586 The second restriction is not lifted by GADTs. In ML and Haskell, indices of types must be types and may not be %\textit{%#<i>#expressions#</i>#%}%. In Coq, types may be indexed by arbitrary Gallina terms. Type indices can live in the same universe as programs, and we can compute with them just like regular programs. Haskell supports a hobbled form of computation in type indices based on multi-parameter type classes, and recent extensions like type functions bring Haskell programming even closer to "real" functional programming with types, but, without dependent typing, there must always be a gap between how one programs with types and how one programs normally.
|
adamc@15
|
587 *)
|
adamc@15
|
588
|
adamc@15
|
589 (** We can define a similar type family for typed expressions. *)
|
adamc@15
|
590
|
adamc@14
|
591 Inductive texp : type -> Set :=
|
adamc@14
|
592 | TNConst : nat -> texp Nat
|
adamc@14
|
593 | TBConst : bool -> texp Bool
|
adamc@14
|
594 | TBinop : forall arg1 arg2 res, tbinop arg1 arg2 res -> texp arg1 -> texp arg2 -> texp res.
|
adamc@14
|
595
|
adamc@15
|
596 (** Thanks to our use of dependent types, every well-typed [texp] represents a well-typed source expression, by construction. This turns out to be very convenient for many things we might want to do with expressions. For instance, it is easy to adapt our interpreter approach to defining semantics. We start by defining a function mapping the types of our languages into Coq types: *)
|
adamc@15
|
597
|
adamc@14
|
598 Definition typeDenote (t : type) : Set :=
|
adamc@14
|
599 match t with
|
adamc@14
|
600 | Nat => nat
|
adamc@14
|
601 | Bool => bool
|
adamc@14
|
602 end.
|
adamc@14
|
603
|
adamc@15
|
604 (** It can take a few moments to come to terms with the fact that [Set], the type of types of programs, is itself a first-class type, and that we can write functions that return [Set]s. Past that wrinkle, the definition of [typeDenote] is trivial, relying on the [nat] and [bool] types from the Coq standard library.
|
adamc@15
|
605
|
adam@277
|
606 We need to define one auxiliary function, implementing a boolean binary "less-than" operator, which only appears in the standard library with a type fancier than what we are prepared to deal with here. The code is entirely standard and ML-like, with the one caveat being that the Coq [nat] type uses a unary representation, where [O] is zero and [S n] is the successor of [n].
|
adamc@15
|
607 *)
|
adamc@15
|
608
|
adamc@207
|
609 Fixpoint lt (n1 n2 : nat) : bool :=
|
adamc@14
|
610 match n1, n2 with
|
adamc@14
|
611 | O, S _ => true
|
adamc@14
|
612 | S n1', S n2' => lt n1' n2'
|
adamc@14
|
613 | _, _ => false
|
adamc@14
|
614 end.
|
adamc@14
|
615
|
adam@277
|
616 (** Now we can interpret binary operators, relying on standard-library equality test functions [eqb] and [beq_nat] for booleans and naturals, respectively: *)
|
adamc@15
|
617
|
adamc@14
|
618 Definition tbinopDenote arg1 arg2 res (b : tbinop arg1 arg2 res)
|
adamc@14
|
619 : typeDenote arg1 -> typeDenote arg2 -> typeDenote res :=
|
adamc@207
|
620 match b in (tbinop arg1 arg2 res)
|
adamc@207
|
621 return (typeDenote arg1 -> typeDenote arg2 -> typeDenote res) with
|
adamc@14
|
622 | TPlus => plus
|
adamc@14
|
623 | TTimes => mult
|
adam@277
|
624 | TEq Nat => beq_nat
|
adam@277
|
625 | TEq Bool => eqb
|
adamc@14
|
626 | TLt => lt
|
adamc@14
|
627 end.
|
adamc@14
|
628
|
adamc@207
|
629 (** This function has just a few differences from the denotation functions we saw earlier. First, [tbinop] is an indexed type, so its indices become additional arguments to [tbinopDenote]. Second, we need to perform a genuine %\textit{%#<i>#dependent pattern match#</i>#%}% to come up with a definition of this function that type-checks. In each branch of the [match], we need to use branch-specific information about the indices to [tbinop]. General type inference that takes such information into account is undecidable, so it is often necessary to write annotations, like we see above on the line with [match].
|
adamc@15
|
630
|
adamc@273
|
631 The [in] annotation restates the type of the term being case-analyzed. Though we use the same names for the indices as we use in the type of the original argument binder, these are actually fresh variables, and they are %\textit{%#<i>#binding occurrences#</i>#%}%. Their scope is the [return] clause. That is, [arg1], [arg2], and [res] are new bound variables bound only within the return clause [typeDenote arg1 -> typeDenote arg2 -> typeDenote res]. By being explicit about the functional relationship between the type indices and the match result, we regain decidable type inference.
|
adamc@15
|
632
|
adamc@207
|
633 In fact, recent Coq versions use some heuristics that can save us the trouble of writing [match] annotations, and those heuristics get the job done in this case. We can get away with writing just: *)
|
adamc@207
|
634
|
adamc@207
|
635 (* begin hide *)
|
adamc@207
|
636 Reset tbinopDenote.
|
adamc@207
|
637 (* end hide *)
|
adamc@207
|
638 Definition tbinopDenote arg1 arg2 res (b : tbinop arg1 arg2 res)
|
adamc@207
|
639 : typeDenote arg1 -> typeDenote arg2 -> typeDenote res :=
|
adamc@207
|
640 match b with
|
adamc@207
|
641 | TPlus => plus
|
adamc@207
|
642 | TTimes => mult
|
adam@277
|
643 | TEq Nat => beq_nat
|
adam@277
|
644 | TEq Bool => eqb
|
adamc@207
|
645 | TLt => lt
|
adamc@207
|
646 end.
|
adamc@207
|
647
|
adamc@207
|
648 (**
|
adamc@15
|
649 The same tricks suffice to define an expression denotation function in an unsurprising way:
|
adamc@15
|
650 *)
|
adamc@15
|
651
|
adamc@207
|
652 Fixpoint texpDenote t (e : texp t) : typeDenote t :=
|
adamc@207
|
653 match e with
|
adamc@14
|
654 | TNConst n => n
|
adamc@14
|
655 | TBConst b => b
|
adamc@14
|
656 | TBinop _ _ _ b e1 e2 => (tbinopDenote b) (texpDenote e1) (texpDenote e2)
|
adamc@14
|
657 end.
|
adamc@14
|
658
|
adamc@17
|
659 (** We can evaluate a few example programs to convince ourselves that this semantics is correct. *)
|
adamc@17
|
660
|
adamc@17
|
661 Eval simpl in texpDenote (TNConst 42).
|
adamc@207
|
662 (** [= 42 : typeDenote Nat] *)
|
adamc@207
|
663
|
adamc@17
|
664 Eval simpl in texpDenote (TBConst true).
|
adamc@207
|
665 (** [= true : typeDenote Bool] *)
|
adamc@207
|
666
|
adamc@17
|
667 Eval simpl in texpDenote (TBinop TTimes (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7)).
|
adamc@207
|
668 (** [= 28 : typeDenote Nat] *)
|
adamc@207
|
669
|
adamc@17
|
670 Eval simpl in texpDenote (TBinop (TEq Nat) (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7)).
|
adamc@207
|
671 (** [= false : typeDenote Bool] *)
|
adamc@207
|
672
|
adamc@17
|
673 Eval simpl in texpDenote (TBinop TLt (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7)).
|
adamc@207
|
674 (** [= true : typeDenote Bool] *)
|
adamc@17
|
675
|
adamc@14
|
676
|
adamc@20
|
677 (** ** Target Language *)
|
adamc@14
|
678
|
adamc@18
|
679 (** Now we want to define a suitable stack machine target for compilation. In the example of the untyped language, stack machine programs could encounter stack underflows and "get stuck." This was unfortunate, since we had to deal with this complication even though we proved that our compiler never produced underflowing programs. We could have used dependent types to force all stack machine programs to be underflow-free.
|
adamc@18
|
680
|
adamc@18
|
681 For our new languages, besides underflow, we also have the problem of stack slots with naturals instead of bools or vice versa. This time, we will use indexed typed families to avoid the need to reason about potential failures.
|
adamc@18
|
682
|
adamc@18
|
683 We start by defining stack types, which classify sets of possible stacks. *)
|
adamc@18
|
684
|
adamc@14
|
685 Definition tstack := list type.
|
adamc@14
|
686
|
adamc@18
|
687 (** Any stack classified by a [tstack] must have exactly as many elements, and each stack element must have the type found in the same position of the stack type.
|
adamc@18
|
688
|
adamc@18
|
689 We can define instructions in terms of stack types, where every instruction's type tells us what initial stack type it expects and what final stack type it will produce. *)
|
adamc@18
|
690
|
adamc@14
|
691 Inductive tinstr : tstack -> tstack -> Set :=
|
adamc@14
|
692 | TINConst : forall s, nat -> tinstr s (Nat :: s)
|
adamc@14
|
693 | TIBConst : forall s, bool -> tinstr s (Bool :: s)
|
adamc@14
|
694 | TIBinop : forall arg1 arg2 res s,
|
adamc@14
|
695 tbinop arg1 arg2 res
|
adamc@14
|
696 -> tinstr (arg1 :: arg2 :: s) (res :: s).
|
adamc@14
|
697
|
adamc@18
|
698 (** Stack machine programs must be a similar inductive family, since, if we again used the [list] type family, we would not be able to guarantee that intermediate stack types match within a program. *)
|
adamc@18
|
699
|
adamc@14
|
700 Inductive tprog : tstack -> tstack -> Set :=
|
adamc@14
|
701 | TNil : forall s, tprog s s
|
adamc@14
|
702 | TCons : forall s1 s2 s3,
|
adamc@14
|
703 tinstr s1 s2
|
adamc@14
|
704 -> tprog s2 s3
|
adamc@14
|
705 -> tprog s1 s3.
|
adamc@14
|
706
|
adamc@18
|
707 (** Now, to define the semantics of our new target language, we need a representation for stacks at runtime. We will again take advantage of type information to define types of value stacks that, by construction, contain the right number and types of elements. *)
|
adamc@18
|
708
|
adamc@14
|
709 Fixpoint vstack (ts : tstack) : Set :=
|
adamc@14
|
710 match ts with
|
adamc@14
|
711 | nil => unit
|
adamc@14
|
712 | t :: ts' => typeDenote t * vstack ts'
|
adamc@14
|
713 end%type.
|
adamc@14
|
714
|
adamc@210
|
715 (** This is another [Set]-valued function. This time it is recursive, which is perfectly valid, since [Set] is not treated specially in determining which functions may be written. We say that the value stack of an empty stack type is any value of type [unit], which has just a single value, [tt]. A nonempty stack type leads to a value stack that is a pair, whose first element has the proper type and whose second element follows the representation for the remainder of the stack type. We write [%type] so that Coq knows to interpret [*] as Cartesian product rather than multiplication.
|
adamc@18
|
716
|
adamc@207
|
717 This idea of programming with types can take a while to internalize, but it enables a very simple definition of instruction denotation. Our definition is like what you might expect from a Lisp-like version of ML that ignored type information. Nonetheless, the fact that [tinstrDenote] passes the type-checker guarantees that our stack machine programs can never go wrong. *)
|
adamc@18
|
718
|
adamc@14
|
719 Definition tinstrDenote ts ts' (i : tinstr ts ts') : vstack ts -> vstack ts' :=
|
adamc@207
|
720 match i with
|
adamc@14
|
721 | TINConst _ n => fun s => (n, s)
|
adamc@14
|
722 | TIBConst _ b => fun s => (b, s)
|
adamc@14
|
723 | TIBinop _ _ _ _ b => fun s =>
|
adamc@14
|
724 match s with
|
adamc@14
|
725 (arg1, (arg2, s')) => ((tbinopDenote b) arg1 arg2, s')
|
adamc@14
|
726 end
|
adamc@14
|
727 end.
|
adamc@14
|
728
|
adamc@18
|
729 (** Why do we choose to use an anonymous function to bind the initial stack in every case of the [match]? Consider this well-intentioned but invalid alternative version:
|
adamc@18
|
730
|
adamc@18
|
731 [[
|
adamc@18
|
732 Definition tinstrDenote ts ts' (i : tinstr ts ts') (s : vstack ts) : vstack ts' :=
|
adamc@207
|
733 match i with
|
adamc@18
|
734 | TINConst _ n => (n, s)
|
adamc@18
|
735 | TIBConst _ b => (b, s)
|
adamc@18
|
736 | TIBinop _ _ _ _ b =>
|
adamc@18
|
737 match s with
|
adamc@18
|
738 (arg1, (arg2, s')) => ((tbinopDenote b) arg1 arg2, s')
|
adamc@18
|
739 end
|
adamc@18
|
740 end.
|
adamc@18
|
741
|
adamc@205
|
742 ]]
|
adamc@205
|
743
|
adamc@18
|
744 The Coq type-checker complains that:
|
adamc@18
|
745
|
adamc@18
|
746 [[
|
adamc@18
|
747 The term "(n, s)" has type "(nat * vstack ts)%type"
|
adamc@207
|
748 while it is expected to have type "vstack ?119".
|
adamc@207
|
749
|
adamc@207
|
750 ]]
|
adamc@207
|
751
|
adamc@207
|
752 The text [?119] stands for a unification variable. We can try to help Coq figure out the value of this variable with an explicit annotation on our [match] expression.
|
adamc@207
|
753
|
adamc@207
|
754 [[
|
adamc@207
|
755 Definition tinstrDenote ts ts' (i : tinstr ts ts') (s : vstack ts) : vstack ts' :=
|
adamc@207
|
756 match i in tinstr ts ts' return vstack ts' with
|
adamc@207
|
757 | TINConst _ n => (n, s)
|
adamc@207
|
758 | TIBConst _ b => (b, s)
|
adamc@207
|
759 | TIBinop _ _ _ _ b =>
|
adamc@207
|
760 match s with
|
adamc@207
|
761 (arg1, (arg2, s')) => ((tbinopDenote b) arg1 arg2, s')
|
adamc@207
|
762 end
|
adamc@207
|
763 end.
|
adamc@207
|
764
|
adamc@207
|
765 ]]
|
adamc@207
|
766
|
adamc@207
|
767 Now the error message changes.
|
adamc@207
|
768
|
adamc@207
|
769 [[
|
adamc@207
|
770 The term "(n, s)" has type "(nat * vstack ts)%type"
|
adamc@207
|
771 while it is expected to have type "vstack (Nat :: t)".
|
adamc@207
|
772
|
adamc@18
|
773 ]]
|
adamc@18
|
774
|
adamc@18
|
775 Recall from our earlier discussion of [match] annotations that we write the annotations to express to the type-checker the relationship between the type indices of the case object and the result type of the [match]. Coq chooses to assign to the wildcard [_] after [TINConst] the name [t], and the type error is telling us that the type checker cannot prove that [t] is the same as [ts]. By moving [s] out of the [match], we lose the ability to express, with [in] and [return] clauses, the relationship between the shared index [ts] of [s] and [i].
|
adamc@18
|
776
|
adamc@18
|
777 There %\textit{%#<i>#are#</i>#%}% reasonably general ways of getting around this problem without pushing binders inside [match]es. However, the alternatives are significantly more involved, and the technique we use here is almost certainly the best choice, whenever it applies.
|
adamc@18
|
778
|
adamc@18
|
779 *)
|
adamc@18
|
780
|
adamc@18
|
781 (** We finish the semantics with a straightforward definition of program denotation. *)
|
adamc@18
|
782
|
adamc@207
|
783 Fixpoint tprogDenote ts ts' (p : tprog ts ts') : vstack ts -> vstack ts' :=
|
adamc@207
|
784 match p with
|
adamc@14
|
785 | TNil _ => fun s => s
|
adamc@14
|
786 | TCons _ _ _ i p' => fun s => tprogDenote p' (tinstrDenote i s)
|
adamc@14
|
787 end.
|
adamc@14
|
788
|
adamc@14
|
789
|
adamc@14
|
790 (** ** Translation *)
|
adamc@14
|
791
|
adamc@19
|
792 (** To define our compilation, it is useful to have an auxiliary function for concatenating two stack machine programs. *)
|
adamc@19
|
793
|
adamc@207
|
794 Fixpoint tconcat ts ts' ts'' (p : tprog ts ts') : tprog ts' ts'' -> tprog ts ts'' :=
|
adamc@207
|
795 match p with
|
adamc@14
|
796 | TNil _ => fun p' => p'
|
adamc@14
|
797 | TCons _ _ _ i p1 => fun p' => TCons i (tconcat p1 p')
|
adamc@14
|
798 end.
|
adamc@14
|
799
|
adamc@19
|
800 (** With that function in place, the compilation is defined very similarly to how it was before, modulo the use of dependent typing. *)
|
adamc@19
|
801
|
adamc@207
|
802 Fixpoint tcompile t (e : texp t) (ts : tstack) : tprog ts (t :: ts) :=
|
adamc@207
|
803 match e with
|
adamc@14
|
804 | TNConst n => TCons (TINConst _ n) (TNil _)
|
adamc@14
|
805 | TBConst b => TCons (TIBConst _ b) (TNil _)
|
adamc@14
|
806 | TBinop _ _ _ b e1 e2 => tconcat (tcompile e2 _)
|
adamc@14
|
807 (tconcat (tcompile e1 _) (TCons (TIBinop _ b) (TNil _)))
|
adamc@14
|
808 end.
|
adamc@14
|
809
|
adamc@40
|
810 (** One interesting feature of the definition is the underscores appearing to the right of [=>] arrows. Haskell and ML programmers are quite familiar with compilers that infer type parameters to polymorphic values. In Coq, it is possible to go even further and ask the system to infer arbitrary terms, by writing underscores in place of specific values. You may have noticed that we have been calling functions without specifying all of their arguments. For instance, the recursive calls here to [tcompile] omit the [t] argument. Coq's %\textit{%#<i>#implicit argument#</i>#%}% mechanism automatically inserts underscores for arguments that it will probably be able to infer. Inference of such values is far from complete, though; generally, it only works in cases similar to those encountered with polymorphic type instantiation in Haskell and ML.
|
adamc@19
|
811
|
adamc@19
|
812 The underscores here are being filled in with stack types. That is, the Coq type inferencer is, in a sense, inferring something about the flow of control in the translated programs. We can take a look at exactly which values are filled in: *)
|
adamc@19
|
813
|
adamc@14
|
814 Print tcompile.
|
adamc@19
|
815 (** [[
|
adamc@19
|
816 tcompile =
|
adamc@19
|
817 fix tcompile (t : type) (e : texp t) (ts : tstack) {struct e} :
|
adamc@19
|
818 tprog ts (t :: ts) :=
|
adamc@19
|
819 match e in (texp t0) return (tprog ts (t0 :: ts)) with
|
adamc@19
|
820 | TNConst n => TCons (TINConst ts n) (TNil (Nat :: ts))
|
adamc@19
|
821 | TBConst b => TCons (TIBConst ts b) (TNil (Bool :: ts))
|
adamc@19
|
822 | TBinop arg1 arg2 res b e1 e2 =>
|
adamc@19
|
823 tconcat (tcompile arg2 e2 ts)
|
adamc@19
|
824 (tconcat (tcompile arg1 e1 (arg2 :: ts))
|
adamc@19
|
825 (TCons (TIBinop ts b) (TNil (res :: ts))))
|
adamc@19
|
826 end
|
adamc@19
|
827 : forall t : type, texp t -> forall ts : tstack, tprog ts (t :: ts)
|
adamc@19
|
828 ]] *)
|
adamc@19
|
829
|
adamc@19
|
830
|
adamc@19
|
831 (** We can check that the compiler generates programs that behave appropriately on our sample programs from above: *)
|
adamc@19
|
832
|
adamc@19
|
833 Eval simpl in tprogDenote (tcompile (TNConst 42) nil) tt.
|
adamc@207
|
834 (** [= (42, tt) : vstack (Nat :: nil)] *)
|
adamc@207
|
835
|
adamc@19
|
836 Eval simpl in tprogDenote (tcompile (TBConst true) nil) tt.
|
adamc@207
|
837 (** [= (true, tt) : vstack (Bool :: nil)] *)
|
adamc@207
|
838
|
adamc@19
|
839 Eval simpl in tprogDenote (tcompile (TBinop TTimes (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7)) nil) tt.
|
adamc@207
|
840 (** [= (28, tt) : vstack (Nat :: nil)] *)
|
adamc@207
|
841
|
adamc@19
|
842 Eval simpl in tprogDenote (tcompile (TBinop (TEq Nat) (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7)) nil) tt.
|
adamc@207
|
843 (** [= (false, tt) : vstack (Bool :: nil)] *)
|
adamc@207
|
844
|
adamc@19
|
845 Eval simpl in tprogDenote (tcompile (TBinop TLt (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7)) nil) tt.
|
adamc@207
|
846 (** [= (true, tt) : vstack (Bool :: nil)] *)
|
adamc@19
|
847
|
adamc@14
|
848
|
adamc@20
|
849 (** ** Translation Correctness *)
|
adamc@20
|
850
|
adamc@20
|
851 (** We can state a correctness theorem similar to the last one. *)
|
adamc@20
|
852
|
adamc@207
|
853 Theorem tcompile_correct : forall t (e : texp t),
|
adamc@207
|
854 tprogDenote (tcompile e nil) tt = (texpDenote e, tt).
|
adamc@20
|
855 (* begin hide *)
|
adamc@20
|
856 Abort.
|
adamc@20
|
857 (* end hide *)
|
adamc@22
|
858 (* begin thide *)
|
adamc@20
|
859
|
adamc@20
|
860 (** Again, we need to strengthen the theorem statement so that the induction will go through. This time, I will develop an alternative approach to this kind of proof, stating the key lemma as: *)
|
adamc@14
|
861
|
adamc@207
|
862 Lemma tcompile_correct' : forall t (e : texp t) ts (s : vstack ts),
|
adamc@207
|
863 tprogDenote (tcompile e ts) s = (texpDenote e, s).
|
adamc@20
|
864
|
adamc@26
|
865 (** While lemma [compile_correct'] quantified over a program that is the "continuation" for the expression we are considering, here we avoid drawing in any extra syntactic elements. In addition to the source expression and its type, we also quantify over an initial stack type and a stack compatible with it. Running the compilation of the program starting from that stack, we should arrive at a stack that differs only in having the program's denotation pushed onto it.
|
adamc@20
|
866
|
adamc@20
|
867 Let us try to prove this theorem in the same way that we settled on in the last section. *)
|
adamc@20
|
868
|
adamc@14
|
869 induction e; crush.
|
adamc@20
|
870
|
adamc@20
|
871 (** We are left with this unproved conclusion:
|
adamc@20
|
872
|
adamc@20
|
873 [[
|
adamc@20
|
874 tprogDenote
|
adamc@20
|
875 (tconcat (tcompile e2 ts)
|
adamc@20
|
876 (tconcat (tcompile e1 (arg2 :: ts))
|
adamc@20
|
877 (TCons (TIBinop ts t) (TNil (res :: ts))))) s =
|
adamc@20
|
878 (tbinopDenote t (texpDenote e1) (texpDenote e2), s)
|
adamc@207
|
879
|
adamc@20
|
880 ]]
|
adamc@20
|
881
|
adamc@20
|
882 We need an analogue to the [app_ass] theorem that we used to rewrite the goal in the last section. We can abort this proof and prove such a lemma about [tconcat].
|
adamc@20
|
883 *)
|
adamc@207
|
884
|
adamc@14
|
885 Abort.
|
adamc@14
|
886
|
adamc@26
|
887 Lemma tconcat_correct : forall ts ts' ts'' (p : tprog ts ts') (p' : tprog ts' ts'')
|
adamc@14
|
888 (s : vstack ts),
|
adamc@14
|
889 tprogDenote (tconcat p p') s
|
adamc@14
|
890 = tprogDenote p' (tprogDenote p s).
|
adamc@14
|
891 induction p; crush.
|
adamc@14
|
892 Qed.
|
adamc@14
|
893
|
adamc@20
|
894 (** This one goes through completely automatically.
|
adamc@20
|
895
|
adamc@26
|
896 Some code behind the scenes registers [app_ass] for use by [crush]. We must register [tconcat_correct] similarly to get the same effect: *)
|
adamc@20
|
897
|
adamc@26
|
898 Hint Rewrite tconcat_correct : cpdt.
|
adamc@14
|
899
|
adamc@26
|
900 (** We ask that the lemma be used for left-to-right rewriting, and we ask for the hint to be added to the hint database called [cpdt], which is the database used by [crush]. Now we are ready to return to [tcompile_correct'], proving it automatically this time. *)
|
adamc@20
|
901
|
adamc@207
|
902 Lemma tcompile_correct' : forall t (e : texp t) ts (s : vstack ts),
|
adamc@207
|
903 tprogDenote (tcompile e ts) s = (texpDenote e, s).
|
adamc@14
|
904 induction e; crush.
|
adamc@14
|
905 Qed.
|
adamc@14
|
906
|
adamc@20
|
907 (** We can register this main lemma as another hint, allowing us to prove the final theorem trivially. *)
|
adamc@20
|
908
|
adamc@26
|
909 Hint Rewrite tcompile_correct' : cpdt.
|
adamc@14
|
910
|
adamc@207
|
911 Theorem tcompile_correct : forall t (e : texp t),
|
adamc@207
|
912 tprogDenote (tcompile e nil) tt = (texpDenote e, tt).
|
adamc@14
|
913 crush.
|
adamc@14
|
914 Qed.
|
adamc@22
|
915 (* end thide *)
|