Tiger Programming Language Compiler in Ocaml
So I began, well at least trying to eventually, write a compiler. I am reading Modern Compilers Implementation in ML by Andrew Appel. I find it to be a very great read. I am only a couple chapters in, but I think this will a great read, and a very fun project to try to finish by the end of the summer Currently I am working on I believe to be ASTs, abstract syntax trees. I have some stuff that looks like, the entire thing should be findable at Tiger Ocaml.
type id = string
type binop = Plus
| Subt
| Mult
| Div
type stm = CompoundStm of stm * stm
| AssignStm of id * exp
| PrintStm of exp list
and exp = IdExp of id
| NumExp of int
| OpExp of exp * binop * exp
| EseqExp of stm * exp
let prog =
CompoundStm(
AssignStm("a",
OpExp(NumExp 5, Plus, NumExp 3)),
CompoundStm(
AssignStm("b",
EseqExp(PrintStm([IdExp "a";
OpExp(IdExp "a", Subt, NumExp 1)
]),
OpExp(NumExp 10, Mult, IdExp "a"))),
PrintStm([IdExp "b"])
)
)
So now we have programs that will hopefully be exectable in this structure. The other part I have done is the first exercise.
let max: int -> int -> int = fun (a: int) -> fun (b: int) ->
match (a > b) with
| true -> a
| false -> b
let rec maxArgs: stm -> int = fun (statement: stm) ->
match statement with
| CompoundStm(stm1, stm2) ->
max ((maxArgs stm1)) ((maxArgs stm2))
| PrintStm(stms) ->
maxArgsPrint(stms)
| _AssignStm ->
0
and maxArgsPrint = List.length
(* I did not realize our PrintStm didn't take a list
of statements... *)
(*maxArgsPrint: stm list -> int =
fun (statements: stm list) ->
List.fold_left (fun acc x ->
acc + (maxArgs x)) 0 statements
*)
Currently that is where I am, and I am hoping I have a really cool Tiger Compiler written in Ocaml by the end of the summer. It was also a little steep, because I had to first learn the syntax to Ocaml. I usually write in ReasonML.