Writing a Javascript to C compiler
I’m writing a JavaScript to C compiler, and I'd like to share the journey. Why? Figuring out how things ‘really work’ is a deep itch for me. I’m a self-taught developer. Throughout my infatuation with coding I’ve been slowly digging deeper and deeper into the magic of how our code actually runs.
Way back in 2011 I started hacking around with the Coffeescript transpiler, for example seeing what it took to add Ruby’s overridable comparison operator to the language:
I ran a meet up group that made a speedy journey through SICP. The final two chapters of that book always felt like they required a lot more time than was easy to give them. So earlier this year I took a week out to stay in a beautiful house in the Austrian alps with SICP, pen and paper, and a goal: read chapters four and five of SICP and do the exercises!
After that week I felt I’d cracked the book, and had got a good idea of how compilers can be implemented. However, the challenge set by SICP’s final exercise wouldn't get out of my head:
As a counterpoint to exercise 5.51, modify the compiler so that it compiles Scheme procedures into sequences of C instructions.
This exercises exemplifies why I love SICP - it's a mentor that shows sets you genuinely challenging tasks, which you can rely on giving you insights you'll find useful for as long as you write code.
Lots of people have completed this exercise for Scheme, which requires you to change the target language for the book's compiler from the book's own register machine to C. Instead, I was interested to see how it’d work out for Javascript, which'd require writing a compiler from scratch.
I’ve got a lot out of the process so far, and I want to share it. To say the least it’s way too much for a single post. So I’m going to blog it every two weeks, going retrospectively over the first steps. I’ll introduce parsing and compiling bit by bit, without any required computer-science or C background: just the way I learned it!
I’ll cover the following:
- Compiling an interpreted, dynamic language. HUH?
- Compiler basics
- Representing values at runtime
- Compiling statements
- Compiling operators
- Compiling functions
- Compiling exceptions
- Garbage collection
- Event driven runtime
If you’d like to read the series, follow me on RSS.
Leave a comment via Github 💬