Wednesday, February 15, 2017

I am Writing a Compiler for C in C

First day of the adventure: I really want to finish this work. I started reading ‘A retargetable C compiler: design and implementation’ to learn the tricks of the trade and I will commit to finishing the implementation of a working ISO C compiler. Along the way I will be taking notes and writing about the experience.

In the past, I wrote independent components of compilers but never finished a complete compiler. This was due to lack of motivation/resources and partially because I teamed up with other people without having a clear picture in mind of who was doing what and how. I decided that this project is going to be a solo adventure.

Why learn how to build a C compiler ?

  • Only few programmers know how to build compilers. They are better programmers and better C programmers.
  • The compiler writer must understand even the darkest corners of the C programming language. This reveals much about the language itself.
  • A compiler is one of the best demonstrations of the interactions between theory and practice. Writing a compiler helps understand where these interactions are smooth and elegant and where practical demands strain the theory.

A compiler translates source code to assembler or object code for a target machine. A retargetable compiler has multiple targets.

The book focuses on the implementation of a retargetable compiler for three target machines. I will lower expectations this time and shoot for one target: the x86 architecture. The book also cares less about theory and describes only the bits of theory needed for the actual implementation. I have read a lot about theory so the lack of theory coverage will go unnoticed.

Design goals:

  • Fast scanner and instruction selector.
  • Generate code of reasonable quality.
  • Machine independent optimizer (local optimization).
  • Hand-crafted scanner and parser (recursive).
  • Clean semantic checker.
This is all for this post. I will be sharing code gradually.