Goal: Build a super tiny compiler

Today we’re going to write a compiler together. But not just any compiler… A super duper teeny tiny compiler! A compiler that is so small that its ~200 lines of actual code.

We’re going to compile some lisp-like function calls into some C-like function calls. If you are not familiar with one or the other then let’s do a quick intro.

If we had two functions add and subtract they would be written like this in LISP and C:

2 + 24 - 22 + (4 - 2))LISP(add 2 2)(subtract 4 2) (add 2 (subtract 4 2)) Csubtract(4, 2)subtract(4, 2)add(2, subtract(4, 2))

Easy peezy right?

Well good, because this is exactly what we are going to compile. While this is neither a complete LISP or C syntax, it will be enough of the syntax to demonstrate many of the major pieces of a modern compiler.

Most compilers break down into three primary stages: Parsing, Transformation, and Code Generation.

%15 node_1 Parsing node_2 Transformation node_1->node_2 node_3 Code generation node_2->node_3
  1. Parsing: is taking raw code and turning it into a more abstract representation of the code.

  2. Transformation: takes this abstract representation and manipulates to do whatever the compiler wants it to.

  3. Code Generation: takes the transformed representation of the code and turns it into new code.