A compiler for the language of the first chapter in Essentials of Compilation by Jeremy G. Siek.
program := expr
expr := integer | identifier | let | primitive
let := (let ((identifier expr)) expr)
primitive := (primitive-op expr*)
primitive-op := + | - | read
The compiler has the following passes:
parse, takes a s-expression and produces an ASTuniquify, replaces all variables with unique names to make scoping and shadowing explicitremove-complex-operands, simplifies all operands of primitive operations to be atomic, potentially resulting in additional temporary variablestype-check, type checks the program and associates types with all variablesexplicate-control, flattens the AST into a linear sequence of C-like statementsselect-instructions, selects X86 instructions based on said C-like statementsassign-homes, assigns to each variable a stack location and replaces the corresponding variable occurrences with dereferencespatch-instructions, makes sure that all instructions are valid X86 (at most one memory reference per instruction, etc.)prelude-and-conclusion, generates necessary prelude and conclusion to set up for the main code (stashingrbp, adjustingrspetc.)print-x86, takes the program and translates it into a string of valid X86 code, ready to be assembled
The compiler takes either a filename to read from or reads from stdin. It spits out x86 assembly code, which can be redirected to file.
$ echo "(+ 10 32)" | racket main.rkt > program.S
$ gcc program.S runtime.c -o program
$ ./program
$ echo $?
42