DEV Community

Rahul Jha
Rahul Jha

Posted on

Day 003: Crafting Interpreters

In the winter of 2019, protests erupted across my city when an anti-Muslim bill (now act) – CAA – was proposed in the Indian parliament. To stop the protestors from organizing, the city was cut off from the Internet. The shutdown (which would last for 8 days) didn't stop the protestors, but in a strange turn of events, it helped me finally pick up and start reading Bob Nystrom's Crafting Interpreters, wherein he walked us through the design and development of a language he called "Lox".

In the first half, we created "jlox", a Java implementation of the language. He in fact walked us through every line of Java code required to build the language from the ground up.

Partly, because I didn't want to do a copy-paste job with the code, but to be engaged with the material, and partly – em, mostly – because I don't know Java, I decided I would write it in Python. I got started, and one word at a time, I fell in love with it (and Bob and his writing). I got hard at work, borderline maniac, cranking at my computer screen almost every waking moment. And it took me exactly 8 days, and plox was finally there. It was very rewarding, seeing it alive and breathing.

The next half of the book discussed the implementation of the same language in C. It was called, you guessed it .. "clox". It wasn't just jlox written in c instead of Java, but it followed another execution model, the Bytecode virtual machine.

You see, jlox and plox were both "interpreters" for Lox. They worked by what's called "walking the tree", that is to say, they parse the user's program into a tree structure (which is very similar to ASTs I talk about in my other post) and then executed a block of code in Java/Python corresponding to each node in that tree. This made them heavily reliant on the machinery provided by the source language.

clox, on the other hand, would compile the program to bytecode (a series of instructions, many of which are one byte long, hence the name) and this bytecode would then be fed to a virtual machine which will execute those instructions and run the program.

I found this interesting and planned to finish the other half the next week, and that plan never got to C the light of the day.

But, I've scratched this itch to go, complete that part enough times for me to commit to it, and what better time than this 100-day challenge. This should hopefully also solve the problem of me spending way more time thinking about what to write for the challenge, instead of, you know, writing it.

Top comments (0)