-
Notifications
You must be signed in to change notification settings - Fork 2
/
compiler.lean
55 lines (46 loc) · 1.31 KB
/
compiler.lean
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import tactic
namespace compiler
/- expressions are values and add-expressions -/
inductive Expr
| Val : ℕ -> Expr
| Add : Expr -> Expr -> Expr
open Expr
/-- evaluate an expression directly -/
@[simp] def eval : Expr -> ℕ
| (Val n) := n
| (Add a b) := eval a + eval b
/-
we'll compile our expressions to instructions of a stack machine
which supports push and add operations
-/
inductive Instr
| PUSH : ℕ -> Instr
| ADD : Instr
open Instr
/-- compile an expression to an instruction list -/
@[simp] def compile : Expr -> list Instr
| (Val n) := [PUSH n]
| (Add a b) := compile a ++ compile b ++ [ADD]
/-- execute a list of instructions on a stack -/
@[simp] def exec : list Instr -> list ℕ -> list ℕ
| ((PUSH n) :: rest) s := exec rest (n :: s)
| (ADD :: rest) (a :: b :: s) := exec rest ((a + b) :: s)
| _ s := s
/-- compiled expressions only add to the stack when `exec`d -/
@[simp] lemma exec_compile_concat (e : Expr) : ∀ instrs stack,
exec (compile e ++ instrs) stack = exec instrs (eval e :: stack) :=
begin
induction e with n a b iha ihb,
case Val {
intros,
simp,
},
case Add {
intros,
simp [iha, ihb, add_comm],
}
end
/-- exec (compile e) = eval e -/
theorem exec_compile_eq_eval (e : Expr) : exec (compile e) [] = [eval e] :=
by simpa using exec_compile_concat e [] []
end compiler