Hacker News new | ask | show | jobs
by ksherlock 2705 days ago
If you're familiar with recursion and basic data structures, that's probably a sufficient background. Toy compilers aren't that difficult when you break them down into parts. (Real world languages end up with warts and special cases).

You have a text file. You break it up into tokens (numbers, strings, keywords, operators, etc) . You assemble the tokens into a structured tree (statements, expressions, etc). Then you walk the tree and generate code (for a compiler) or execute it (for an interpreter). That's it. Really.

Every other week, somebody posts a tutorial to HN about writing a lisp interpreter in javascript. or go. or python. or rust. or lisp. If you can't wait, Let's Build a Compiler by Jack Crenshaw is an oldie but a goodie.

https://compilers.iecc.com/crenshaw/

1 comments

i also heartily recommend Crenshaw's "let's build a compiler" if you want some guidance and motivation to help you just roll up your sleeves and start building a bare-bones but functional compiler.

> Maths, then Automata, maybe OS,

i don't think any of these are a requirement for building a simple compiler.

after reading Crenshaw some years ago, i was motivated to just knuckle down and start building a compiler for brainfuck (yes, a toy compiler, entirely pointless). this was probably one of the most enjoyable periods of programming i can remember.

i think my descent into fun with compilers went something like:

* "let's implement a compiler for a simple language (brainfuck) to something low level (assembler) in a high-level language i am familiar with (python)"

* ok, that was easy, now what?

* "self-hosting compilers are cool. can i write a brainfuck compiler in brainfuck?"

* "this is horrifying"

* "OK, what if i defined a simple language that is much easier to do useful work, but could be readily compiled to brainfuck? i could build a compiler from that new language to brainfuck"

If you have a bit of spare time i heartily recommend (i) learning to implement a basic compiler, and (ii) building the compiler in or for a language that has a radically different concept to languages you are more familiar with.

https://github.com/fcostin/abfc