https://github.com/jdan/compiler.lean
A formally verified compiler for a simple language with numbers and sums
https://github.com/jdan/compiler.lean
Last synced: 8 months ago
JSON representation
A formally verified compiler for a simple language with numbers and sums
- Host: GitHub
- URL: https://github.com/jdan/compiler.lean
- Owner: jdan
- Created: 2020-11-29T04:01:03.000Z (over 5 years ago)
- Default Branch: main
- Last Pushed: 2020-11-29T17:33:04.000Z (over 5 years ago)
- Last Synced: 2025-01-01T02:41:37.682Z (over 1 year ago)
- Language: Lean
- Size: 7.81 KB
- Stars: 26
- Watchers: 4
- Forks: 2
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
## compiler.lean
Inspired by the wonderful [Program Correctness](https://www.youtube.com/watch?v=T_IINWzQhow) video over on [Computerphile](https://www.youtube.com/channel/UC9-y-6csu5WGm29I7JiwpnA), this repo contains a formally verified "compiler" for a language with natural number values and add expressions. It is written using the [Lean theorem prover](https://leanprover-community.github.io/).
We define an expression type for our language and an instruction type for the stack machine which our compiler targets.
```
inductive Expr
| Val : ℕ -> Expr
| Add : Expr -> Expr -> Expr
inductive Instr
| PUSH : ℕ -> Instr
| ADD : Instr
```
### `exec_compile_eq_eval (e : Expr) : exec (compile e) [] = [eval e]`
[[Source]](/src/compiler.lean)
All expressions `e` when compiled and executed on an empty stack produce the same value as `eval`.
I'm still new to lean so my proofs aren't great. Suggestions welcome!
### `eval : Expr -> ℕ`
Evaluates an `Expr` to produce a natural number
```
eval (Val 5)
=> 5
eval (Add (Add (Val 10) (Val 20))
(Val 30))
=> 60
```
### `compile : Expr -> list Instr`
Compiles an `Expr` to produce a list of instructions
```
compile (Val 42)
=> [PUSH 42]
compile (Add (Add (Val 10) (Val 20))
(Val 30))
=> [PUSH 10, PUSH 20, ADD, PUSH 30, ADD]
```
### `exec : list Instr -> list ℕ -> list ℕ`
Executes a list of instructions on a stack
```
exec [PUSH 42] []
=> [42]
exec [PUSH 10, PUSH 20, ADD, PUSH 30, ADD][]
=> [60]
```