Alexito's World

A world of coding 💻, by Alejandro Martinez

Lox interpreter in Swift

A couple of days ago I was reading Crafting Interpreters written by Bob Nystrom and it awoke my passion for programming languages so I decided to implement an interpreter for Lox in Swift!

Programming languages and compilers are one of my biggest interests, following the Swift evolution list and watching Jonathan Blow develop his new language are two of my hobbies. I've played with parsers in the past, and tried to mess around with the missing metaprogramming features in Swift but I've never tried to implement a complete language. Although I understand the theory behind it I was missing the motivation to get my hands dirty, motivation that Bob's book seems to have given me!

The plan here is to follow Bob's work on the book and implement the chapters one by one in Swift. I'm really curious to see how Swift is suited for this kind of work.

One thing to note is that I'm trying to write a mix between idiomatic Swift (whatever that means in this young language) and the code that the book shows in Java. Because I'm not making up the language nor the compiler/interpreter but I'm following the book I don't want to get into a point where in future chapters the book asks for some code changes and they get too complex because I was trying to be too smart. So I take it as a learning exercise and try to implement it as close as possible, except for those occasions where I can't resist using Swift nice features like guard or the powerful switch statements. There will be time to maybe write another compiler that explores different ways of doing things, but this is not it.

This past weekend I implemented the scanner, basically the only coding chapter that is availalbe as of today. I will be waiting for more chapters to be released and keep putting some time in this project.

If you liked this article please consider supporting me