Why I want to build a compiler
What happens between writing return 42 and seeing a program exit with status 42?
When I compile a C program at work, I usually care whether the build succeeded and whether the program behaves as I expect. I know the broad steps involved in compiling and running it. I want to understand those steps well enough to explain why a particular instruction is there, where a value is stored, and how a running program asks the operating system to do something.
I want to study those details by building a compiler for AvaLang, an experimental language I named after Ava from Ex Machina. A small language gives me a way to follow one program through every step. If I change the program, I can look at the compiler’s output and work out why it changed.
One small program
fn main() -> i32 {
return 42
}
The function returns an integer. We will arrange for that integer to become the process exit status on Linux x86-64. Then we can change 42 to 7, compile the program again, and check that its exit status changes too.
I will write the first compiler in C so we can see how it stores its data and when it releases that memory. The longer journey will take us to a compiler written in Ava that can build itself. For the first hands-on piece, we will begin with the source file. How do we read its bytes, keep them available to the rest of the compiler, and report what happened if the file cannot be opened?