adam@398
|
1 (* Copyright (c) 2008-2012, 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@2
|
10
|
adamc@25
|
11 (** %\chapter{Some Quick Examples}% *)
|
adamc@25
|
12
|
adam@447
|
13 (** 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. This chapter is not meant to give full explanations of the features that are employed. Rather, it is meant more as an advertisement of what is possible. Later chapters will introduce all of the concepts in bottom-up fashion. In other words, it is expected that most readers will not understand what exactly is going on here, but I hope this demo will whet your appetite for the remaining chapters!
|
adam@279
|
14
|
adam@419
|
15 As always, you can step through the source file <<StackMachine.v>> 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 <<.v>> file in an Emacs buffer. If you do the latter, include these two lines at the start of the file. *)
|
adam@314
|
16
|
adam@419
|
17 Require Import Bool Arith List CpdtTactics.
|
adam@419
|
18 Set Implicit Arguments.
|
adam@314
|
19
|
adam@419
|
20 (** In general, similar commands will be hidden in the book rendering of each chapter's source code, so you will need to insert them in from-scratch replayings of the code that is presented. To be more specific, every chapter begins with the above two lines, with the import list tweaked as appropriate, considering which definitions the chapter uses. The second command above affects the default behavior of definitions regarding type inference. *)
|
adamc@9
|
21
|
adamc@9
|
22
|
adamc@20
|
23 (** * Arithmetic Expressions Over Natural Numbers *)
|
adamc@2
|
24
|
adamc@40
|
25 (** We will begin with that staple of compiler textbooks, arithmetic expressions over a single type of numbers. *)
|
adamc@9
|
26
|
adamc@20
|
27 (** ** Source Language *)
|
adamc@9
|
28
|
adam@311
|
29 (** We begin with the syntax of the source language.%\index{Vernacular commands!Inductive}% *)
|
adamc@2
|
30
|
adamc@4
|
31 Inductive binop : Set := Plus | Times.
|
adamc@2
|
32
|
adam@447
|
33 (** Our first line of Coq code should be unsurprising to ML and Haskell programmers. We define an %\index{algebraic datatypes}%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 <<data>>, <<datatype>>, or <<type>>. 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 %\index{Gallina terms!Set}%[: 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
|
34
|
adamc@4
|
35 Inductive exp : Set :=
|
adamc@4
|
36 | Const : nat -> exp
|
adamc@4
|
37 | Binop : binop -> exp -> exp -> exp.
|
adamc@2
|
38
|
adamc@9
|
39 (** 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
|
40
|
adam@419
|
41 A note for readers following along in the PDF version: %\index{coqdoc}%coqdoc supports pretty-printing of tokens in %\LaTeX{}%#LaTeX# or HTML. Where you see a right arrow character, the source contains the ASCII text <<->>>. Other examples of this substitution appearing in this chapter are a double right arrow for <<=>>>, the inverted %`%#'#A' symbol for <<forall>>, and the Cartesian product %`%#'#X' for <<*>>. When in doubt about the ASCII version of a symbol, you can consult the chapter source code.
|
adamc@9
|
42
|
adamc@9
|
43 %\medskip%
|
adamc@9
|
44
|
adam@475
|
45 Now we are ready to say what programs in our expression language mean. We will do this by writing an %\index{interpreters}%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.)%\index{Vernacular commands!Definition}% *)
|
adamc@9
|
46
|
adamc@4
|
47 Definition binopDenote (b : binop) : nat -> nat -> nat :=
|
adamc@4
|
48 match b with
|
adamc@4
|
49 | Plus => plus
|
adamc@4
|
50 | Times => mult
|
adamc@4
|
51 end.
|
adamc@2
|
52
|
adam@419
|
53 (** The meaning of a binary operator is a binary function over naturals, defined with pattern-matching notation analogous to the <<case>> and <<match>> 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
|
54 [[
|
adamc@9
|
55 Definition binopDenote : binop -> nat -> nat -> nat := fun (b : binop) =>
|
adamc@9
|
56 match b with
|
adamc@9
|
57 | Plus => plus
|
adamc@9
|
58 | Times => mult
|
adamc@9
|
59 end.
|
adamc@205
|
60 ]]
|
adamc@205
|
61
|
adamc@9
|
62 In this example, we could also omit all of the type annotations, arriving at:
|
adamc@9
|
63 [[
|
adamc@9
|
64 Definition binopDenote := fun b =>
|
adamc@9
|
65 match b with
|
adamc@9
|
66 | Plus => plus
|
adamc@9
|
67 | Times => mult
|
adamc@9
|
68 end.
|
adamc@205
|
69 ]]
|
adamc@205
|
70
|
adam@475
|
71 Languages like Haskell and ML have a convenient%\index{principal types}\index{type inference}% _principal types_ 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 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
|
72
|
adam@475
|
73 This is as good a time as any to mention the profusion of different languages associated with Coq. The theoretical foundation of Coq is a formal system called the%\index{Calculus of Inductive Constructions}\index{CIC|see{Calculus of Inductive Constructions}}% _Calculus of Inductive Constructions_ (CIC)%~\cite{CIC}%, which is an extension of the older%\index{Calculus of Constructions}\index{CoC|see{Calculus of Constructions}}% _Calculus of Constructions_ (CoC)%~\cite{CoC}%. 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%\index{strong normalization}% _strong normalization_ %\cite{CIC}%, meaning that every program (and, more importantly, every proof term) terminates; and%\index{relative consistency}% _relative consistency_ %\cite{SetsInTypes}% with systems like versions of %\index{Zermelo-Fraenkel set theory}%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
|
74
|
adam@475
|
75 Coq is actually based on an extension of CIC called %\index{Gallina}%Gallina. The text after the [:=] and before the period in the last code example is a term of Gallina. Gallina includes several useful features that must be considered as extensions to CIC. The important metatheorems about CIC have not been extended to the full breadth of the features that go beyond the formalized language, but most Coq users do not seem to lose much sleep over this omission.
|
adamc@9
|
76
|
adam@475
|
77 Next, there is %\index{Ltac}%Ltac, 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
|
78
|
adam@475
|
79 Finally, commands like [Inductive] and [Definition] are part of %\index{Vernacular commands}%the Vernacular, which includes all sorts of useful queries and requests to the Coq system. Every Coq source file is a series of vernacular commands, where many command forms take arguments that are Gallina or Ltac programs. (Actually, Coq source files are more like _trees_ of vernacular commands, thanks to various nested scoping constructs.)
|
adamc@9
|
80
|
adamc@9
|
81 %\medskip%
|
adamc@9
|
82
|
adam@311
|
83 We can give a simple definition of the meaning of an expression:%\index{Vernacular commands!Fixpoint}% *)
|
adamc@9
|
84
|
adamc@4
|
85 Fixpoint expDenote (e : exp) : nat :=
|
adamc@4
|
86 match e with
|
adamc@4
|
87 | Const n => n
|
adamc@4
|
88 | Binop b e1 e2 => (binopDenote b) (expDenote e1) (expDenote e2)
|
adamc@4
|
89 end.
|
adamc@2
|
90
|
adamc@9
|
91 (** We declare explicitly that this is a recursive definition, using the keyword [Fixpoint]. The rest should be old hat for functional programmers. *)
|
adamc@2
|
92
|
adam@419
|
93 (** 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, using the command %\index{Vernacular commands!Eval}%[Eval]. This command takes an argument expressing a%\index{reduction strategy}% _reduction strategy_, or an "order of evaluation." Unlike with ML, which hardcodes an _eager_ reduction strategy, or Haskell, which hardcodes a _lazy_ strategy, in Coq we are free to choose between these and many other orders of evaluation, because all Coq programs terminate. In fact, Coq silently checked %\index{termination checking}%termination of our [Fixpoint] definition above, using a simple heuristic based on monotonically decreasing size of arguments across recursive calls. Specifically, recursive calls must be made on arguments that were pulled out of the original recursive argument with [match] expressions. (In Chapter 7, we will see some ways of getting around this restriction, though simply removing the restriction would leave Coq useless as a theorem proving tool, for reasons we will start to learn about in the next chapter.)
|
adam@311
|
94
|
adam@311
|
95 To return to our test evaluations, we run the [Eval] command using the [simpl] evaluation strategy, whose definition is best postponed until we have learned more about Coq's foundations, but which usually gets the job done. *)
|
adamc@16
|
96
|
adamc@16
|
97 Eval simpl in expDenote (Const 42).
|
adamc@205
|
98 (** [= 42 : nat] *)
|
adamc@205
|
99
|
adamc@16
|
100 Eval simpl in expDenote (Binop Plus (Const 2) (Const 2)).
|
adamc@205
|
101 (** [= 4 : nat] *)
|
adamc@205
|
102
|
adamc@16
|
103 Eval simpl in expDenote (Binop Times (Binop Plus (Const 2) (Const 2)) (Const 7)).
|
adamc@205
|
104 (** [= 28 : nat] *)
|
adamc@9
|
105
|
adam@442
|
106 (** %\smallskip{}%Nothing too surprising goes on here, so we are ready to move on to the target language of our compiler. *)
|
adam@442
|
107
|
adam@442
|
108
|
adamc@20
|
109 (** ** Target Language *)
|
adamc@4
|
110
|
adamc@10
|
111 (** We will compile our source programs onto a simple stack machine, whose syntax is: *)
|
adamc@2
|
112
|
adamc@4
|
113 Inductive instr : Set :=
|
adam@311
|
114 | iConst : nat -> instr
|
adam@311
|
115 | iBinop : binop -> instr.
|
adamc@2
|
116
|
adamc@4
|
117 Definition prog := list instr.
|
adamc@4
|
118 Definition stack := list nat.
|
adamc@2
|
119
|
adamc@10
|
120 (** 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
|
121
|
adam@419
|
122 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']. %\index{Gallina operators!::}%The infix operator [::] is "list cons" from the Coq standard library.%\index{Gallina terms!option}% *)
|
adamc@10
|
123
|
adamc@4
|
124 Definition instrDenote (i : instr) (s : stack) : option stack :=
|
adamc@4
|
125 match i with
|
adam@311
|
126 | iConst n => Some (n :: s)
|
adam@311
|
127 | iBinop b =>
|
adamc@4
|
128 match s with
|
adamc@4
|
129 | arg1 :: arg2 :: s' => Some ((binopDenote b) arg1 arg2 :: s')
|
adamc@4
|
130 | _ => None
|
adamc@4
|
131 end
|
adamc@4
|
132 end.
|
adamc@2
|
133
|
adam@311
|
134 (** With [instrDenote] defined, it is easy to define a function [progDenote], which iterates application of [instrDenote] through a whole program. *)
|
adamc@206
|
135
|
adamc@206
|
136 Fixpoint progDenote (p : prog) (s : stack) : option stack :=
|
adamc@206
|
137 match p with
|
adamc@206
|
138 | nil => Some s
|
adamc@206
|
139 | i :: p' =>
|
adamc@206
|
140 match instrDenote i s with
|
adamc@206
|
141 | None => None
|
adamc@206
|
142 | Some s' => progDenote p' s'
|
adamc@206
|
143 end
|
adamc@206
|
144 end.
|
adamc@2
|
145
|
adam@442
|
146 (** With the two programming languages defined, we can turn to the compiler definition. *)
|
adam@442
|
147
|
adamc@4
|
148
|
adamc@9
|
149 (** ** Translation *)
|
adamc@4
|
150
|
adam@471
|
151 (** Our compiler itself is now unsurprising. The list concatenation operator %\index{Gallina operators!++}\coqdocnotation{%#<tt>#++#</tt>#%}% comes from the Coq standard library. *)
|
adamc@2
|
152
|
adamc@4
|
153 Fixpoint compile (e : exp) : prog :=
|
adamc@4
|
154 match e with
|
adam@311
|
155 | Const n => iConst n :: nil
|
adam@311
|
156 | Binop b e1 e2 => compile e2 ++ compile e1 ++ iBinop b :: nil
|
adamc@4
|
157 end.
|
adamc@2
|
158
|
adamc@2
|
159
|
adamc@16
|
160 (** 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
|
161
|
adamc@16
|
162 Eval simpl in compile (Const 42).
|
adam@311
|
163 (** [= iConst 42 :: nil : prog] *)
|
adamc@206
|
164
|
adamc@16
|
165 Eval simpl in compile (Binop Plus (Const 2) (Const 2)).
|
adam@311
|
166 (** [= iConst 2 :: iConst 2 :: iBinop Plus :: nil : prog] *)
|
adamc@206
|
167
|
adamc@16
|
168 Eval simpl in compile (Binop Times (Binop Plus (Const 2) (Const 2)) (Const 7)).
|
adam@311
|
169 (** [= iConst 7 :: iConst 2 :: iConst 2 :: iBinop Plus :: iBinop Times :: nil : prog] *)
|
adamc@16
|
170
|
adam@442
|
171 (** %\smallskip{}%We can also run our compiled programs and check that they give the right results. *)
|
adamc@16
|
172
|
adamc@16
|
173 Eval simpl in progDenote (compile (Const 42)) nil.
|
adamc@206
|
174 (** [= Some (42 :: nil) : option stack] *)
|
adamc@206
|
175
|
adamc@16
|
176 Eval simpl in progDenote (compile (Binop Plus (Const 2) (Const 2))) nil.
|
adamc@206
|
177 (** [= Some (4 :: nil) : option stack] *)
|
adamc@206
|
178
|
adam@311
|
179 Eval simpl in progDenote (compile (Binop Times (Binop Plus (Const 2) (Const 2))
|
adam@311
|
180 (Const 7))) nil.
|
adamc@206
|
181 (** [= Some (28 :: nil) : option stack] *)
|
adamc@16
|
182
|
adam@447
|
183 (** %\smallskip{}%So far so good, but how can we be sure the compiler operates correctly for _all_ input programs? *)
|
adamc@16
|
184
|
adamc@20
|
185 (** ** Translation Correctness *)
|
adamc@4
|
186
|
adam@311
|
187 (** 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:%\index{Vernacular commands!Theorem}% *)
|
adamc@11
|
188
|
adamc@26
|
189 Theorem compile_correct : forall e, progDenote (compile e) nil = Some (expDenote e :: nil).
|
adamc@22
|
190 (* begin thide *)
|
adamc@11
|
191
|
adam@419
|
192 (** 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%\index{strengthening the induction hypothesis}% _strengthening the induction hypothesis_. We do that by proving an auxiliary lemma, using the command [Lemma] that is a synonym for [Theorem], conventionally used for less important theorems that appear in the proofs of primary theorems.%\index{Vernacular commands!Lemma}% *)
|
adamc@2
|
193
|
adam@469
|
194 Abort.
|
adam@469
|
195
|
adamc@206
|
196 Lemma compile_correct' : forall e p s,
|
adamc@206
|
197 progDenote (compile e ++ p) s = progDenote p (expDenote e :: s).
|
adamc@11
|
198
|
adam@399
|
199 (** After the period in the [Lemma] command, we are in%\index{interactive proof-editing mode}% _the interactive proof-editing mode_. We find ourselves staring at this ominous screen of text:
|
adamc@11
|
200
|
adamc@11
|
201 [[
|
adamc@11
|
202 1 subgoal
|
adamc@11
|
203
|
adamc@11
|
204 ============================
|
adamc@15
|
205 forall (e : exp) (p : list instr) (s : stack),
|
adamc@15
|
206 progDenote (compile e ++ p) s = progDenote p (expDenote e :: s)
|
adamc@206
|
207
|
adamc@11
|
208 ]]
|
adamc@11
|
209
|
adam@311
|
210 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 %\index{subgoals}%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
|
211
|
adam@311
|
212 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 %\index{hypotheses}%hypotheses, if we had any. Below the line is the %\index{conclusion}%conclusion, which, in general, is to be proved from the hypotheses.
|
adamc@11
|
213
|
adam@399
|
214 We manipulate the proof state by running commands called%\index{tactics}% _tactics_. Let us start out by running one of the most important tactics:%\index{tactics!induction}%
|
adamc@11
|
215 *)
|
adamc@11
|
216
|
adamc@4
|
217 induction e.
|
adamc@2
|
218
|
adamc@11
|
219 (** 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
|
220
|
adam@439
|
221 [[
|
adam@439
|
222 2 subgoals
|
adam@311
|
223
|
adamc@11
|
224 n : nat
|
adamc@11
|
225 ============================
|
adamc@11
|
226 forall (s : stack) (p : list instr),
|
adamc@11
|
227 progDenote (compile (Const n) ++ p) s =
|
adamc@11
|
228 progDenote p (expDenote (Const n) :: s)
|
adam@439
|
229
|
adam@439
|
230 subgoal 2 is
|
adam@439
|
231
|
adamc@11
|
232 forall (s : stack) (p : list instr),
|
adamc@11
|
233 progDenote (compile (Binop b e1 e2) ++ p) s =
|
adamc@11
|
234 progDenote p (expDenote (Binop b e1 e2) :: s)
|
adamc@206
|
235
|
adamc@11
|
236 ]]
|
adamc@11
|
237
|
adam@311
|
238 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 %\index{free variable}%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 %\index{structural induction}%structural induction.
|
adamc@11
|
239
|
adam@311
|
240 We begin the first case with another very common tactic.%\index{tactics!intros}%
|
adamc@11
|
241 *)
|
adamc@11
|
242
|
adamc@4
|
243 intros.
|
adamc@11
|
244
|
adamc@11
|
245 (** The current subgoal changes to:
|
adamc@11
|
246 [[
|
adamc@11
|
247
|
adamc@11
|
248 n : nat
|
adamc@11
|
249 s : stack
|
adamc@11
|
250 p : list instr
|
adamc@11
|
251 ============================
|
adamc@11
|
252 progDenote (compile (Const n) ++ p) s =
|
adamc@11
|
253 progDenote p (expDenote (Const n) :: s)
|
adamc@206
|
254
|
adamc@11
|
255 ]]
|
adamc@11
|
256
|
adamc@11
|
257 We see that [intros] changes [forall]-bound variables at the beginning of a goal into free variables.
|
adamc@11
|
258
|
adam@311
|
259 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.%\index{tactics!unfold}%
|
adamc@11
|
260 *)
|
adamc@11
|
261
|
adamc@4
|
262 unfold compile.
|
adamc@11
|
263 (** [[
|
adamc@11
|
264 n : nat
|
adamc@11
|
265 s : stack
|
adamc@11
|
266 p : list instr
|
adamc@11
|
267 ============================
|
adam@311
|
268 progDenote ((iConst n :: nil) ++ p) s =
|
adamc@11
|
269 progDenote p (expDenote (Const n) :: s)
|
adamc@206
|
270
|
adam@302
|
271 ]]
|
adam@302
|
272 *)
|
adamc@11
|
273
|
adamc@4
|
274 unfold expDenote.
|
adamc@11
|
275 (** [[
|
adamc@11
|
276 n : nat
|
adamc@11
|
277 s : stack
|
adamc@11
|
278 p : list instr
|
adamc@11
|
279 ============================
|
adam@311
|
280 progDenote ((iConst n :: nil) ++ p) s = progDenote p (n :: s)
|
adamc@206
|
281
|
adamc@11
|
282 ]]
|
adamc@11
|
283
|
adam@311
|
284 We only need to unfold the first occurrence of [progDenote] to prove the goal. An [at] clause used with [unfold] specifies a particular occurrence of an identifier to unfold, where we count occurrences from left to right.%\index{tactics!unfold}% *)
|
adamc@11
|
285
|
adamc@11
|
286 unfold progDenote at 1.
|
adamc@11
|
287 (** [[
|
adamc@11
|
288 n : nat
|
adamc@11
|
289 s : stack
|
adamc@11
|
290 p : list instr
|
adamc@11
|
291 ============================
|
adamc@11
|
292 (fix progDenote (p0 : prog) (s0 : stack) {struct p0} :
|
adamc@11
|
293 option stack :=
|
adamc@11
|
294 match p0 with
|
adamc@11
|
295 | nil => Some s0
|
adamc@11
|
296 | i :: p' =>
|
adamc@11
|
297 match instrDenote i s0 with
|
adamc@11
|
298 | Some s' => progDenote p' s'
|
adamc@11
|
299 | None => None (A:=stack)
|
adamc@11
|
300 end
|
adam@311
|
301 end) ((iConst n :: nil) ++ p) s =
|
adamc@11
|
302 progDenote p (n :: s)
|
adamc@206
|
303
|
adamc@11
|
304 ]]
|
adamc@11
|
305
|
adam@471
|
306 This last [unfold] has left us with an anonymous recursive definition of [progDenote] (similarly to how [fun] or "lambda" constructs in general allow anonymous non-recursive functions), which will generally happen when unfolding recursive definitions. Note that Coq has automatically renamed the [fix] arguments [p] and [s] to [p0] and [s0], to avoid clashes with our local free variables. There is also a subterm [None (A:=stack)], which has an annotation specifying that the type of the term ought to be [option stack]. This is phrased as an explicit instantiation of a named type parameter [A] from the definition of [option].
|
adam@311
|
307
|
adam@311
|
308 Fortunately, in this case, we can eliminate the complications of anonymous recursion 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, which applies the same reduction strategy that we used earlier with [Eval] (and whose details we still postpone).%\index{tactics!simpl}%
|
adamc@11
|
309 *)
|
adamc@11
|
310
|
adamc@4
|
311 simpl.
|
adamc@11
|
312 (** [[
|
adamc@11
|
313 n : nat
|
adamc@11
|
314 s : stack
|
adamc@11
|
315 p : list instr
|
adamc@11
|
316 ============================
|
adamc@11
|
317 (fix progDenote (p0 : prog) (s0 : stack) {struct p0} :
|
adamc@11
|
318 option stack :=
|
adamc@11
|
319 match p0 with
|
adamc@11
|
320 | nil => Some s0
|
adamc@11
|
321 | i :: p' =>
|
adamc@11
|
322 match instrDenote i s0 with
|
adamc@11
|
323 | Some s' => progDenote p' s'
|
adamc@11
|
324 | None => None (A:=stack)
|
adamc@11
|
325 end
|
adamc@11
|
326 end) p (n :: s) = progDenote p (n :: s)
|
adamc@206
|
327
|
adamc@11
|
328 ]]
|
adamc@11
|
329
|
adam@311
|
330 Now we can unexpand the definition of [progDenote]:%\index{tactics!fold}%
|
adamc@11
|
331 *)
|
adamc@11
|
332
|
adamc@11
|
333 fold progDenote.
|
adamc@11
|
334 (** [[
|
adamc@11
|
335 n : nat
|
adamc@11
|
336 s : stack
|
adamc@11
|
337 p : list instr
|
adamc@11
|
338 ============================
|
adamc@11
|
339 progDenote p (n :: s) = progDenote p (n :: s)
|
adamc@206
|
340
|
adamc@11
|
341 ]]
|
adamc@11
|
342
|
adam@311
|
343 It looks like we are at the end of this case, since we have a trivial equality. Indeed, a single tactic finishes us off:%\index{tactics!reflexivity}%
|
adamc@11
|
344 *)
|
adamc@11
|
345
|
adamc@4
|
346 reflexivity.
|
adamc@2
|
347
|
adamc@11
|
348 (** On to the second inductive case:
|
adamc@11
|
349
|
adamc@11
|
350 [[
|
adamc@11
|
351 b : binop
|
adamc@11
|
352 e1 : exp
|
adamc@11
|
353 IHe1 : forall (s : stack) (p : list instr),
|
adamc@11
|
354 progDenote (compile e1 ++ p) s = progDenote p (expDenote e1 :: s)
|
adamc@11
|
355 e2 : exp
|
adamc@11
|
356 IHe2 : forall (s : stack) (p : list instr),
|
adamc@11
|
357 progDenote (compile e2 ++ p) s = progDenote p (expDenote e2 :: s)
|
adamc@11
|
358 ============================
|
adamc@11
|
359 forall (s : stack) (p : list instr),
|
adamc@11
|
360 progDenote (compile (Binop b e1 e2) ++ p) s =
|
adamc@11
|
361 progDenote p (expDenote (Binop b e1 e2) :: s)
|
adamc@206
|
362
|
adamc@11
|
363 ]]
|
adamc@11
|
364
|
adam@311
|
365 We see our first example of %\index{hypotheses}%hypotheses above the double-dashed line. They are the inductive hypotheses [IHe1] and [IHe2] corresponding to the subterms [e1] and [e2], respectively.
|
adamc@11
|
366
|
adam@399
|
367 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. %\index{tactics!intros}\index{tactics!unfold}\index{tactics!fold}% *)
|
adamc@11
|
368
|
adamc@4
|
369 intros.
|
adamc@4
|
370 unfold compile.
|
adamc@4
|
371 fold compile.
|
adamc@4
|
372 unfold expDenote.
|
adamc@4
|
373 fold expDenote.
|
adamc@11
|
374
|
adamc@44
|
375 (** 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
|
376
|
adamc@11
|
377 [[
|
adamc@11
|
378 b : binop
|
adamc@11
|
379 e1 : exp
|
adamc@11
|
380 IHe1 : forall (s : stack) (p : list instr),
|
adamc@11
|
381 progDenote (compile e1 ++ p) s = progDenote p (expDenote e1 :: s)
|
adamc@11
|
382 e2 : exp
|
adamc@11
|
383 IHe2 : forall (s : stack) (p : list instr),
|
adamc@11
|
384 progDenote (compile e2 ++ p) s = progDenote p (expDenote e2 :: s)
|
adamc@11
|
385 s : stack
|
adamc@11
|
386 p : list instr
|
adamc@11
|
387 ============================
|
adam@311
|
388 progDenote ((compile e2 ++ compile e1 ++ iBinop b :: nil) ++ p) s =
|
adamc@11
|
389 progDenote p (binopDenote b (expDenote e1) (expDenote e2) :: s)
|
adamc@206
|
390
|
adamc@11
|
391 ]]
|
adamc@11
|
392
|
adam@471
|
393 What we need is the associative law of list concatenation, which is available as a theorem [app_assoc_reverse] in the standard library.%\index{Vernacular commands!Check}% (Here and elsewhere, it is possible to tell the difference between inputs and outputs to Coq by periods at the ends of the inputs.) *)
|
adamc@11
|
394
|
adam@469
|
395 Check app_assoc_reverse.
|
adam@439
|
396 (** %\vspace{-.15in}%[[
|
adam@311
|
397 app_assoc_reverse
|
adamc@11
|
398 : forall (A : Type) (l m n : list A), (l ++ m) ++ n = l ++ m ++ n
|
adamc@206
|
399
|
adamc@11
|
400 ]]
|
adamc@11
|
401
|
adam@399
|
402 If we did not already know the name of the theorem, we could use the %\index{Vernacular commands!SearchRewrite}%[SearchRewrite] command to find it, based on a pattern that we would like to rewrite: *)
|
adam@277
|
403
|
adam@492
|
404 (* begin hide *)
|
adam@492
|
405 (* begin thide *)
|
adam@492
|
406 Definition bleh := app_assoc.
|
adam@492
|
407 (* end thide *)
|
adam@492
|
408 (* end hide *)
|
adam@492
|
409
|
adam@277
|
410 SearchRewrite ((_ ++ _) ++ _).
|
adam@439
|
411 (** %\vspace{-.15in}%[[
|
adam@311
|
412 app_assoc_reverse:
|
adam@311
|
413 forall (A : Type) (l m n : list A), (l ++ m) ++ n = l ++ m ++ n
|
adam@311
|
414 ]]
|
adam@311
|
415 %\vspace{-.25in}%
|
adam@311
|
416 [[
|
adam@311
|
417 app_assoc: forall (A : Type) (l m n : list A), l ++ m ++ n = (l ++ m) ++ n
|
adam@277
|
418
|
adam@277
|
419 ]]
|
adam@277
|
420
|
adam@311
|
421 We use [app_assoc_reverse] to perform a rewrite: %\index{tactics!rewrite}% *)
|
adamc@11
|
422
|
adam@311
|
423 rewrite app_assoc_reverse.
|
adamc@11
|
424
|
adam@439
|
425 (** %\noindent{}%changing the conclusion to:
|
adamc@11
|
426
|
adamc@206
|
427 [[
|
adam@311
|
428 progDenote (compile e2 ++ (compile e1 ++ iBinop b :: nil) ++ p) s =
|
adamc@11
|
429 progDenote p (binopDenote b (expDenote e1) (expDenote e2) :: s)
|
adamc@206
|
430
|
adamc@11
|
431 ]]
|
adamc@11
|
432
|
adam@311
|
433 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.%\index{tactics!rewrite}% *)
|
adamc@11
|
434
|
adamc@4
|
435 rewrite IHe2.
|
adamc@11
|
436 (** [[
|
adam@311
|
437 progDenote ((compile e1 ++ iBinop b :: nil) ++ p) (expDenote e2 :: s) =
|
adamc@11
|
438 progDenote p (binopDenote b (expDenote e1) (expDenote e2) :: s)
|
adamc@206
|
439
|
adamc@11
|
440 ]]
|
adamc@11
|
441
|
adam@311
|
442 The same process lets us apply the remaining hypothesis.%\index{tactics!rewrite}% *)
|
adamc@11
|
443
|
adam@311
|
444 rewrite app_assoc_reverse.
|
adamc@4
|
445 rewrite IHe1.
|
adamc@11
|
446 (** [[
|
adam@311
|
447 progDenote ((iBinop b :: nil) ++ p) (expDenote e1 :: expDenote e2 :: s) =
|
adamc@11
|
448 progDenote p (binopDenote b (expDenote e1) (expDenote e2) :: s)
|
adamc@206
|
449
|
adamc@11
|
450 ]]
|
adamc@11
|
451
|
adam@311
|
452 Now we can apply a similar sequence of tactics to the one that ended the proof of the first case.%\index{tactics!unfold}\index{tactics!simpl}\index{tactics!fold}\index{tactics!reflexivity}%
|
adamc@11
|
453 *)
|
adamc@11
|
454
|
adamc@11
|
455 unfold progDenote at 1.
|
adamc@4
|
456 simpl.
|
adamc@11
|
457 fold progDenote.
|
adamc@4
|
458 reflexivity.
|
adamc@11
|
459
|
adam@311
|
460 (** And the proof is completed, as indicated by the message: *)
|
adamc@11
|
461
|
adam@399
|
462 (**
|
adam@399
|
463 <<
|
adam@399
|
464 Proof completed.
|
adam@399
|
465 >>
|
adam@399
|
466 *)
|
adamc@11
|
467
|
adam@311
|
468 (** 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.%\index{Vernacular commands!Abort}%
|
adamc@11
|
469 *)
|
adamc@11
|
470
|
adamc@4
|
471 Abort.
|
adamc@2
|
472
|
adam@311
|
473 (** %\index{tactics!induction}\index{tactics!crush}% *)
|
adam@311
|
474
|
adamc@26
|
475 Lemma compile_correct' : forall e s p, progDenote (compile e ++ p) s =
|
adamc@4
|
476 progDenote p (expDenote e :: s).
|
adamc@4
|
477 induction e; crush.
|
adamc@4
|
478 Qed.
|
adamc@2
|
479
|
adam@328
|
480 (** 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 %\index{tactics!semicolon}%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
|
481
|
adam@399
|
482 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
|
483
|
adam@398
|
484 The %\index{Vernacular commands!Qed}%[Qed] command checks that the proof is finished and, if so, saves it. The tactic commands we have written above are an example of a _proof script_, or a series of Ltac programs; while [Qed] uses the result of the script to generate a _proof term_, a well-typed term of Gallina. To believe that a theorem is true, we only need to trust that the (relatively simple) checker for proof terms is correct; the use of proof scripts is immaterial. Part I of this book will introduce the principles behind encoding all proofs as terms of Gallina.
|
adam@311
|
485
|
adam@311
|
486 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.%\index{tactics!intros}% *)
|
adamc@11
|
487
|
adamc@26
|
488 Theorem compile_correct : forall e, progDenote (compile e) nil = Some (expDenote e :: nil).
|
adamc@11
|
489 intros.
|
adamc@11
|
490 (** [[
|
adamc@11
|
491 e : exp
|
adamc@11
|
492 ============================
|
adamc@11
|
493 progDenote (compile e) nil = Some (expDenote e :: nil)
|
adamc@206
|
494
|
adamc@11
|
495 ]]
|
adamc@11
|
496
|
adamc@26
|
497 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
|
498
|
adamc@11
|
499 Check app_nil_end.
|
adamc@11
|
500 (** [[
|
adamc@11
|
501 app_nil_end
|
adamc@11
|
502 : forall (A : Type) (l : list A), l = l ++ nil
|
adam@302
|
503 ]]
|
adam@311
|
504 %\index{tactics!rewrite}% *)
|
adamc@11
|
505
|
adamc@4
|
506 rewrite (app_nil_end (compile e)).
|
adamc@11
|
507
|
adam@417
|
508 (** 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. The [rewrite] tactic might choose the wrong place to rewrite if we did not specify which we want.
|
adamc@11
|
509
|
adamc@11
|
510 [[
|
adamc@11
|
511 e : exp
|
adamc@11
|
512 ============================
|
adamc@11
|
513 progDenote (compile e ++ nil) nil = Some (expDenote e :: nil)
|
adamc@206
|
514
|
adamc@11
|
515 ]]
|
adamc@11
|
516
|
adam@311
|
517 Now we can apply the lemma.%\index{tactics!rewrite}% *)
|
adamc@11
|
518
|
adamc@26
|
519 rewrite compile_correct'.
|
adamc@11
|
520 (** [[
|
adamc@11
|
521 e : exp
|
adamc@11
|
522 ============================
|
adamc@11
|
523 progDenote nil (expDenote e :: nil) = Some (expDenote e :: nil)
|
adamc@206
|
524
|
adamc@11
|
525 ]]
|
adamc@11
|
526
|
adam@311
|
527 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 %\index{tactics!reflexivity}%[reflexivity] does the normalization and checks that the two results are syntactically equal.%\index{tactics!reflexivity}% *)
|
adamc@11
|
528
|
adamc@4
|
529 reflexivity.
|
adamc@4
|
530 Qed.
|
adamc@22
|
531 (* end thide *)
|
adamc@14
|
532
|
adam@475
|
533 (** This proof can be shortened and automated, but we leave that task as an exercise for the reader. *)
|
adam@311
|
534
|
adamc@14
|
535
|
adamc@20
|
536 (** * Typed Expressions *)
|
adamc@14
|
537
|
adamc@14
|
538 (** 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
|
539
|
adamc@20
|
540 (** ** Source Language *)
|
adamc@14
|
541
|
adamc@15
|
542 (** We define a trivial language of types to classify our expressions: *)
|
adamc@15
|
543
|
adamc@14
|
544 Inductive type : Set := Nat | Bool.
|
adamc@14
|
545
|
adam@277
|
546 (** 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
|
547
|
adam@277
|
548 Now we define an expanded set of binary operators. *)
|
adamc@15
|
549
|
adamc@14
|
550 Inductive tbinop : type -> type -> type -> Set :=
|
adamc@14
|
551 | TPlus : tbinop Nat Nat Nat
|
adamc@14
|
552 | TTimes : tbinop Nat Nat Nat
|
adamc@14
|
553 | TEq : forall t, tbinop t t Bool
|
adamc@14
|
554 | TLt : tbinop Nat Nat Bool.
|
adamc@14
|
555
|
adam@398
|
556 (** 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 _indexed type family_. 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
|
557
|
adam@452
|
558 The intuitive explanation of [tbinop] is that a [tbinop t1 t2 t] is a binary operator whose operands should have types [t1] and [t2], and whose result has type [t]. For instance, constructor [TLt] (for less-than comparison of numbers) is assigned type [tbinop Nat Nat Bool], meaning the operator's arguments are naturals and its result is Boolean. The type of [TEq] introduces a small bit of additional complication via polymorphism: we want to allow equality comparison of any two values of any type, as long as they have the _same_ type.
|
adam@312
|
559
|
adamc@15
|
560 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
|
561
|
adam@469
|
562 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]. %\index{generalized algebraic datatypes}\index{GADTs|see{generalized algebraic datatypes}}% _Generalized algebraic datatypes_ (GADTs)%~\cite{GADT}% are a popular feature in %\index{GHC Haskell}%GHC Haskell, OCaml 4, and other languages that removes this first restriction.
|
adamc@15
|
563
|
adam@419
|
564 The second restriction is not lifted by GADTs. In ML and Haskell, indices of types must be types and may not be _expressions_. 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 %\index{Haskell}%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
|
565 *)
|
adamc@15
|
566
|
adam@399
|
567 (** We can define a similar type family for typed expressions, where a term of type [texp t] can be assigned object language type [t]. (It is conventional in the world of interactive theorem proving to call the language of the proof assistant the%\index{meta language}% _meta language_ and a language being formalized the%\index{object language}% _object language_.) *)
|
adamc@15
|
568
|
adamc@14
|
569 Inductive texp : type -> Set :=
|
adamc@14
|
570 | TNConst : nat -> texp Nat
|
adamc@14
|
571 | TBConst : bool -> texp Bool
|
adam@312
|
572 | TBinop : forall t1 t2 t, tbinop t1 t2 t -> texp t1 -> texp t2 -> texp t.
|
adamc@14
|
573
|
adam@447
|
574 (** 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 object language into Coq types: *)
|
adamc@15
|
575
|
adamc@14
|
576 Definition typeDenote (t : type) : Set :=
|
adamc@14
|
577 match t with
|
adamc@14
|
578 | Nat => nat
|
adamc@14
|
579 | Bool => bool
|
adamc@14
|
580 end.
|
adamc@14
|
581
|
adam@448
|
582 (** 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. We can interpret binary operators by relying on standard-library equality test functions [eqb] and [beq_nat] for Booleans and naturals, respectively, along with a less-than test [leb]: *)
|
adamc@15
|
583
|
adamc@207
|
584 Definition tbinopDenote arg1 arg2 res (b : tbinop arg1 arg2 res)
|
adamc@207
|
585 : typeDenote arg1 -> typeDenote arg2 -> typeDenote res :=
|
adamc@207
|
586 match b with
|
adamc@207
|
587 | TPlus => plus
|
adamc@207
|
588 | TTimes => mult
|
adam@277
|
589 | TEq Nat => beq_nat
|
adam@277
|
590 | TEq Bool => eqb
|
adam@312
|
591 | TLt => leb
|
adamc@207
|
592 end.
|
adamc@207
|
593
|
adam@399
|
594 (** 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%\index{dependent pattern matching}% _dependent pattern match_, where the necessary _type_ of each case body depends on the _value_ that has been matched. At this early stage, we will not go into detail on the many subtle aspects of Gallina that support dependent pattern-matching, but the subject is central to Part II of the book.
|
adam@312
|
595
|
adam@471
|
596 The same tricks suffice to define an expression denotation function in an unsurprising way. Note that the [type] arguments to the [TBinop] constructor must be included explicitly in pattern-matching, but here we write underscores because we do not need to refer to those arguments directly. *)
|
adamc@15
|
597
|
adamc@207
|
598 Fixpoint texpDenote t (e : texp t) : typeDenote t :=
|
adamc@207
|
599 match e with
|
adamc@14
|
600 | TNConst n => n
|
adamc@14
|
601 | TBConst b => b
|
adamc@14
|
602 | TBinop _ _ _ b e1 e2 => (tbinopDenote b) (texpDenote e1) (texpDenote e2)
|
adamc@14
|
603 end.
|
adamc@14
|
604
|
adamc@17
|
605 (** We can evaluate a few example programs to convince ourselves that this semantics is correct. *)
|
adamc@17
|
606
|
adamc@17
|
607 Eval simpl in texpDenote (TNConst 42).
|
adamc@207
|
608 (** [= 42 : typeDenote Nat] *)
|
adamc@207
|
609
|
adam@419
|
610 (* begin hide *)
|
adam@419
|
611 Eval simpl in texpDenote (TBConst false).
|
adam@419
|
612 (* end hide *)
|
adamc@17
|
613 Eval simpl in texpDenote (TBConst true).
|
adamc@207
|
614 (** [= true : typeDenote Bool] *)
|
adamc@207
|
615
|
adam@312
|
616 Eval simpl in texpDenote (TBinop TTimes (TBinop TPlus (TNConst 2) (TNConst 2))
|
adam@312
|
617 (TNConst 7)).
|
adamc@207
|
618 (** [= 28 : typeDenote Nat] *)
|
adamc@207
|
619
|
adam@312
|
620 Eval simpl in texpDenote (TBinop (TEq Nat) (TBinop TPlus (TNConst 2) (TNConst 2))
|
adam@312
|
621 (TNConst 7)).
|
adam@399
|
622 (** [= false : typeDenote Bool] *)
|
adamc@207
|
623
|
adam@312
|
624 Eval simpl in texpDenote (TBinop TLt (TBinop TPlus (TNConst 2) (TNConst 2))
|
adam@312
|
625 (TNConst 7)).
|
adamc@207
|
626 (** [= true : typeDenote Bool] *)
|
adamc@17
|
627
|
adam@442
|
628 (** %\smallskip{}%Now we are ready to define a suitable stack machine target for compilation. *)
|
adam@442
|
629
|
adamc@14
|
630
|
adamc@20
|
631 (** ** Target Language *)
|
adamc@14
|
632
|
adam@442
|
633 (** 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
|
634
|
adamc@18
|
635 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
|
636
|
adamc@18
|
637 We start by defining stack types, which classify sets of possible stacks. *)
|
adamc@18
|
638
|
adamc@14
|
639 Definition tstack := list type.
|
adamc@14
|
640
|
adamc@18
|
641 (** 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
|
642
|
adamc@18
|
643 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
|
644
|
adamc@14
|
645 Inductive tinstr : tstack -> tstack -> Set :=
|
adam@312
|
646 | TiNConst : forall s, nat -> tinstr s (Nat :: s)
|
adam@312
|
647 | TiBConst : forall s, bool -> tinstr s (Bool :: s)
|
adam@311
|
648 | TiBinop : forall arg1 arg2 res s,
|
adamc@14
|
649 tbinop arg1 arg2 res
|
adamc@14
|
650 -> tinstr (arg1 :: arg2 :: s) (res :: s).
|
adamc@14
|
651
|
adamc@18
|
652 (** 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
|
653
|
adamc@14
|
654 Inductive tprog : tstack -> tstack -> Set :=
|
adamc@14
|
655 | TNil : forall s, tprog s s
|
adamc@14
|
656 | TCons : forall s1 s2 s3,
|
adamc@14
|
657 tinstr s1 s2
|
adamc@14
|
658 -> tprog s2 s3
|
adamc@14
|
659 -> tprog s1 s3.
|
adamc@14
|
660
|
adamc@18
|
661 (** 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
|
662
|
adamc@14
|
663 Fixpoint vstack (ts : tstack) : Set :=
|
adamc@14
|
664 match ts with
|
adamc@14
|
665 | nil => unit
|
adamc@14
|
666 | t :: ts' => typeDenote t * vstack ts'
|
adamc@14
|
667 end%type.
|
adamc@14
|
668
|
adam@312
|
669 (** 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 [%]%\index{notation scopes}\coqdocvar{%#<tt>#type#</tt>#%}% as an instruction to Coq's extensible parser. In particular, this directive applies to the whole [match] expression, which we ask to be parsed as though it were a type, so that the operator [*] is interpreted as Cartesian product instead of, say, multiplication. (Note that this use of %\coqdocvar{%#<tt>#type#</tt>#%}% has no connection to the inductive type [type] that we have defined.)
|
adamc@18
|
670
|
adam@312
|
671 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. We use a special form of [let] to destructure a multi-level tuple. *)
|
adamc@18
|
672
|
adamc@14
|
673 Definition tinstrDenote ts ts' (i : tinstr ts ts') : vstack ts -> vstack ts' :=
|
adamc@207
|
674 match i with
|
adam@312
|
675 | TiNConst _ n => fun s => (n, s)
|
adam@312
|
676 | TiBConst _ b => fun s => (b, s)
|
adam@311
|
677 | TiBinop _ _ _ _ b => fun s =>
|
adam@312
|
678 let '(arg1, (arg2, s')) := s in
|
adam@312
|
679 ((tbinopDenote b) arg1 arg2, s')
|
adamc@14
|
680 end.
|
adamc@14
|
681
|
adamc@18
|
682 (** 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
|
683 [[
|
adamc@18
|
684 Definition tinstrDenote ts ts' (i : tinstr ts ts') (s : vstack ts) : vstack ts' :=
|
adamc@207
|
685 match i with
|
adam@312
|
686 | TiNConst _ n => (n, s)
|
adam@312
|
687 | TiBConst _ b => (b, s)
|
adam@311
|
688 | TiBinop _ _ _ _ b =>
|
adam@312
|
689 let '(arg1, (arg2, s')) := s in
|
adam@312
|
690 ((tbinopDenote b) arg1 arg2, s')
|
adamc@18
|
691 end.
|
adamc@205
|
692 ]]
|
adamc@205
|
693
|
adam@447
|
694 The Coq type checker complains that:
|
adamc@18
|
695
|
adam@312
|
696 <<
|
adamc@18
|
697 The term "(n, s)" has type "(nat * vstack ts)%type"
|
adamc@207
|
698 while it is expected to have type "vstack ?119".
|
adam@312
|
699 >>
|
adamc@207
|
700
|
adam@465
|
701 This and other mysteries of Coq dependent typing we postpone until Part II of the book. The upshot of our later discussion is that it is often useful to push inside of [match] branches those function parameters whose types depend on the type of the value being matched. Our later, more complete treatment of Gallina's typing rules will explain why this helps.
|
adamc@18
|
702 *)
|
adamc@18
|
703
|
adamc@18
|
704 (** We finish the semantics with a straightforward definition of program denotation. *)
|
adamc@18
|
705
|
adamc@207
|
706 Fixpoint tprogDenote ts ts' (p : tprog ts ts') : vstack ts -> vstack ts' :=
|
adamc@207
|
707 match p with
|
adamc@14
|
708 | TNil _ => fun s => s
|
adamc@14
|
709 | TCons _ _ _ i p' => fun s => tprogDenote p' (tinstrDenote i s)
|
adamc@14
|
710 end.
|
adamc@14
|
711
|
adam@447
|
712 (** The same argument-postponing trick is crucial for this definition. *)
|
adam@447
|
713
|
adamc@14
|
714
|
adamc@14
|
715 (** ** Translation *)
|
adamc@14
|
716
|
adamc@19
|
717 (** To define our compilation, it is useful to have an auxiliary function for concatenating two stack machine programs. *)
|
adamc@19
|
718
|
adamc@207
|
719 Fixpoint tconcat ts ts' ts'' (p : tprog ts ts') : tprog ts' ts'' -> tprog ts ts'' :=
|
adamc@207
|
720 match p with
|
adamc@14
|
721 | TNil _ => fun p' => p'
|
adamc@14
|
722 | TCons _ _ _ i p1 => fun p' => TCons i (tconcat p1 p')
|
adamc@14
|
723 end.
|
adamc@14
|
724
|
adamc@19
|
725 (** With that function in place, the compilation is defined very similarly to how it was before, modulo the use of dependent typing. *)
|
adamc@19
|
726
|
adamc@207
|
727 Fixpoint tcompile t (e : texp t) (ts : tstack) : tprog ts (t :: ts) :=
|
adamc@207
|
728 match e with
|
adam@312
|
729 | TNConst n => TCons (TiNConst _ n) (TNil _)
|
adam@312
|
730 | TBConst b => TCons (TiBConst _ b) (TNil _)
|
adamc@14
|
731 | TBinop _ _ _ b e1 e2 => tconcat (tcompile e2 _)
|
adam@311
|
732 (tconcat (tcompile e1 _) (TCons (TiBinop _ b) (TNil _)))
|
adamc@14
|
733 end.
|
adamc@14
|
734
|
adam@398
|
735 (** 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 _implicit argument_ 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
|
736
|
adamc@19
|
737 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
|
738
|
adamc@14
|
739 Print tcompile.
|
adam@439
|
740 (** %\vspace{-.15in}%[[
|
adamc@19
|
741 tcompile =
|
adamc@19
|
742 fix tcompile (t : type) (e : texp t) (ts : tstack) {struct e} :
|
adamc@19
|
743 tprog ts (t :: ts) :=
|
adamc@19
|
744 match e in (texp t0) return (tprog ts (t0 :: ts)) with
|
adam@312
|
745 | TNConst n => TCons (TiNConst ts n) (TNil (Nat :: ts))
|
adam@312
|
746 | TBConst b => TCons (TiBConst ts b) (TNil (Bool :: ts))
|
adamc@19
|
747 | TBinop arg1 arg2 res b e1 e2 =>
|
adamc@19
|
748 tconcat (tcompile arg2 e2 ts)
|
adamc@19
|
749 (tconcat (tcompile arg1 e1 (arg2 :: ts))
|
adam@311
|
750 (TCons (TiBinop ts b) (TNil (res :: ts))))
|
adamc@19
|
751 end
|
adamc@19
|
752 : forall t : type, texp t -> forall ts : tstack, tprog ts (t :: ts)
|
adam@302
|
753 ]]
|
adam@302
|
754 *)
|
adamc@19
|
755
|
adamc@19
|
756
|
adamc@19
|
757 (** We can check that the compiler generates programs that behave appropriately on our sample programs from above: *)
|
adamc@19
|
758
|
adamc@19
|
759 Eval simpl in tprogDenote (tcompile (TNConst 42) nil) tt.
|
adam@399
|
760 (** [= (42, tt) : vstack (Nat :: nil)] *)
|
adamc@207
|
761
|
adamc@19
|
762 Eval simpl in tprogDenote (tcompile (TBConst true) nil) tt.
|
adam@399
|
763 (** [= (true, tt) : vstack (Bool :: nil)] *)
|
adamc@207
|
764
|
adam@312
|
765 Eval simpl in tprogDenote (tcompile (TBinop TTimes (TBinop TPlus (TNConst 2)
|
adam@312
|
766 (TNConst 2)) (TNConst 7)) nil) tt.
|
adam@399
|
767 (** [= (28, tt) : vstack (Nat :: nil)] *)
|
adamc@207
|
768
|
adam@312
|
769 Eval simpl in tprogDenote (tcompile (TBinop (TEq Nat) (TBinop TPlus (TNConst 2)
|
adam@312
|
770 (TNConst 2)) (TNConst 7)) nil) tt.
|
adam@399
|
771 (** [= (false, tt) : vstack (Bool :: nil)] *)
|
adamc@207
|
772
|
adam@312
|
773 Eval simpl in tprogDenote (tcompile (TBinop TLt (TBinop TPlus (TNConst 2) (TNConst 2))
|
adam@312
|
774 (TNConst 7)) nil) tt.
|
adam@399
|
775 (** [= (true, tt) : vstack (Bool :: nil)] *)
|
adamc@19
|
776
|
adam@442
|
777 (** %\smallskip{}%The compiler seems to be working, so let us turn to proving that it _always_ works. *)
|
adam@442
|
778
|
adamc@14
|
779
|
adamc@20
|
780 (** ** Translation Correctness *)
|
adamc@20
|
781
|
adamc@20
|
782 (** We can state a correctness theorem similar to the last one. *)
|
adamc@20
|
783
|
adamc@207
|
784 Theorem tcompile_correct : forall t (e : texp t),
|
adamc@207
|
785 tprogDenote (tcompile e nil) tt = (texpDenote e, tt).
|
adamc@20
|
786 (* begin hide *)
|
adamc@20
|
787 Abort.
|
adamc@20
|
788 (* end hide *)
|
adamc@22
|
789 (* begin thide *)
|
adamc@20
|
790
|
adam@312
|
791 (** Again, we need to strengthen the theorem statement so that the induction will go through. This time, to provide an excuse to demonstrate different tactics, I will develop an alternative approach to this kind of proof, stating the key lemma as: *)
|
adamc@14
|
792
|
adamc@207
|
793 Lemma tcompile_correct' : forall t (e : texp t) ts (s : vstack ts),
|
adamc@207
|
794 tprogDenote (tcompile e ts) s = (texpDenote e, s).
|
adamc@20
|
795
|
adam@419
|
796 (** While lemma [compile_correct'] quantified over a program that is the "continuation"%~\cite{continuations}% 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
|
797
|
adamc@20
|
798 Let us try to prove this theorem in the same way that we settled on in the last section. *)
|
adamc@20
|
799
|
adamc@14
|
800 induction e; crush.
|
adamc@20
|
801
|
adamc@20
|
802 (** We are left with this unproved conclusion:
|
adamc@20
|
803
|
adamc@20
|
804 [[
|
adamc@20
|
805 tprogDenote
|
adamc@20
|
806 (tconcat (tcompile e2 ts)
|
adamc@20
|
807 (tconcat (tcompile e1 (arg2 :: ts))
|
adam@311
|
808 (TCons (TiBinop ts t) (TNil (res :: ts))))) s =
|
adamc@20
|
809 (tbinopDenote t (texpDenote e1) (texpDenote e2), s)
|
adamc@207
|
810
|
adamc@20
|
811 ]]
|
adamc@20
|
812
|
adam@312
|
813 We need an analogue to the [app_assoc_reverse] 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
|
814 *)
|
adamc@207
|
815
|
adamc@14
|
816 Abort.
|
adamc@14
|
817
|
adamc@26
|
818 Lemma tconcat_correct : forall ts ts' ts'' (p : tprog ts ts') (p' : tprog ts' ts'')
|
adamc@14
|
819 (s : vstack ts),
|
adamc@14
|
820 tprogDenote (tconcat p p') s
|
adamc@14
|
821 = tprogDenote p' (tprogDenote p s).
|
adamc@14
|
822 induction p; crush.
|
adamc@14
|
823 Qed.
|
adamc@14
|
824
|
adamc@20
|
825 (** This one goes through completely automatically.
|
adamc@20
|
826
|
adam@316
|
827 Some code behind the scenes registers [app_assoc_reverse] for use by [crush]. We must register [tconcat_correct] similarly to get the same effect:%\index{Vernacular commands!Hint Rewrite}% *)
|
adamc@20
|
828
|
adam@375
|
829 Hint Rewrite tconcat_correct.
|
adamc@14
|
830
|
adam@419
|
831 (** Here we meet the pervasive concept of a _hint_. Many proofs can be found through exhaustive enumerations of combinations of possible proof steps; hints provide the set of steps to consider. The tactic [crush] is applying such brute force search for us silently, and it will consider more possibilities as we add more hints. This particular hint asks that the lemma be used for left-to-right rewriting.
|
adam@312
|
832
|
adam@312
|
833 Now we are ready to return to [tcompile_correct'], proving it automatically this time. *)
|
adamc@20
|
834
|
adamc@207
|
835 Lemma tcompile_correct' : forall t (e : texp t) ts (s : vstack ts),
|
adamc@207
|
836 tprogDenote (tcompile e ts) s = (texpDenote e, s).
|
adamc@14
|
837 induction e; crush.
|
adamc@14
|
838 Qed.
|
adamc@14
|
839
|
adamc@20
|
840 (** We can register this main lemma as another hint, allowing us to prove the final theorem trivially. *)
|
adamc@20
|
841
|
adam@375
|
842 Hint Rewrite tcompile_correct'.
|
adamc@14
|
843
|
adamc@207
|
844 Theorem tcompile_correct : forall t (e : texp t),
|
adamc@207
|
845 tprogDenote (tcompile e nil) tt = (texpDenote e, tt).
|
adamc@14
|
846 crush.
|
adamc@14
|
847 Qed.
|
adamc@22
|
848 (* end thide *)
|
adam@312
|
849
|
adam@399
|
850 (** It is probably worth emphasizing that we are doing more than building mathematical models. Our compilers are functional programs that can be executed efficiently. One strategy for doing so is based on%\index{program extraction}% _program extraction_, which generates OCaml code from Coq developments. For instance, we run a command to output the OCaml version of [tcompile]:%\index{Vernacular commands!Extraction}% *)
|
adam@312
|
851
|
adam@312
|
852 Extraction tcompile.
|
adam@312
|
853
|
adam@312
|
854 (** <<
|
adam@312
|
855 let rec tcompile t e ts =
|
adam@312
|
856 match e with
|
adam@312
|
857 | TNConst n ->
|
adam@312
|
858 TCons (ts, (Cons (Nat, ts)), (Cons (Nat, ts)), (TiNConst (ts, n)), (TNil
|
adam@312
|
859 (Cons (Nat, ts))))
|
adam@312
|
860 | TBConst b ->
|
adam@312
|
861 TCons (ts, (Cons (Bool, ts)), (Cons (Bool, ts)), (TiBConst (ts, b)),
|
adam@312
|
862 (TNil (Cons (Bool, ts))))
|
adam@312
|
863 | TBinop (t1, t2, t0, b, e1, e2) ->
|
adam@312
|
864 tconcat ts (Cons (t2, ts)) (Cons (t0, ts)) (tcompile t2 e2 ts)
|
adam@312
|
865 (tconcat (Cons (t2, ts)) (Cons (t1, (Cons (t2, ts)))) (Cons (t0, ts))
|
adam@312
|
866 (tcompile t1 e1 (Cons (t2, ts))) (TCons ((Cons (t1, (Cons (t2,
|
adam@312
|
867 ts)))), (Cons (t0, ts)), (Cons (t0, ts)), (TiBinop (t1, t2, t0, ts,
|
adam@312
|
868 b)), (TNil (Cons (t0, ts))))))
|
adam@312
|
869 >>
|
adam@312
|
870
|
adam@312
|
871 We can compile this code with the usual OCaml compiler and obtain an executable program with halfway decent performance.
|
adam@312
|
872
|
adam@312
|
873 This chapter has been a whirlwind tour through two examples of the style of Coq development that I advocate. Parts II and III of the book focus on the key elements of that style, namely dependent types and scripted proof automation, respectively. Before we get there, we will spend some time in Part I on more standard foundational material. Part I may still be of interest to seasoned Coq hackers, since I follow the highly automated proof style even at that early stage. *)
|