Working through 'Writing A C Compiler'

3 hours ago 3

Some time ago I decided I wanted to create a c compiler for the Hack processor in the nand2tetris book. After several dead end attempts that I might describe later I found this book : Writing a C Compiler | No Starch Press

I decided to work my way through it. I plan to do blog posts as I progress through it, probably chapter by chapter.

I have emailed the author a couple of times and have got helpful timely replies! – thank you

What makes the book so good?

Step by step

By the end of chapter 1 you have a working compiler. Each subsequent chapter adds more features. The chapter 1 compiler can only handle

int main(void){ return <constant>; }

But it works producing a complete executable

Chapter 2 adds unary operators so we can now do something like.

int main(void){ return ~3; }

This contrasts with most other books I have worked with on compilers like the also excellent Crafting Interpreters and Home | nand2tetris

The fact that we are building a real language as opposed to a made up one is great too.

Side note: Some c features are not implemented in the book but are suggested as ‘extra credit’. I intend to implement all those. Some features are not implemented and are not covered. More on those later.

Test suite

The other great thing is that there is a large test suite provided. For each chapter tests are added so running the , say, chapter 5 tests runs the tests for 1,2,3 and 4 as well.

You can say if you want to test:

  • extra credit features
  • just the lexer pass
  • the lex and parser pass
  • semantic analysis
  • everything

Even the simple compiler in chapter 1 has 24 tests

This is a tremendous resource and seeing the test suite say

PS C:\work\forks\writing-a-c-compiler-tests> python .\test_compiler C:\work\mycc\target\debug\mycc.exe --chapter 1 --extra-credit ---------------------------------------------------------------------- Ran 24 tests in 2.843s OK

is a real pleasure. Time to fire up gitui (gitui-org/gitui: Blazing 💥 fast terminal-ui for git written in rust 🦀) and commit

Repos

Nora has two github repos for this book

I have two as well

Posts

I will probably do one blog post per chapter, including one for the introduction. I got to the extra credit section of chapter 8 before I thought of blogging the process. So there will be a bunch of posts in a rush, that cover completed work and will be in the past tense. As I move forward, they will be chattier as I debate with myself how to do things, and spread out to the pace of my progress

Final Note

This is a great book. Any comments I make in later chapter regarding things that I think are missing, wrong, confusing etc. should not take away from the fact that this is an extremely good book.

Read Entire Article