Hacker News new | ask | show | jobs
by ashleyn 2008 days ago
Write a toy compiler for a basic like language, you'll learn about what your languages are actually doing.
8 comments

Author here. I agree! That was one of the projects from the original project list that I posted a year ago (https://web.eecs.utk.edu/~azh/blog/challengingprojects.html).

In fact, this summer I wrote a 3-part tutorial series on implementing a BASIC compiler: Let's make a Teeny Tiny compiler (https://web.eecs.utk.edu/~azh/blog/teenytinycompiler1.html)

Hey! Be more careful when you call things fictitious!

My first program ran on a CHIP-8 machine (COSMAC VIP), though I didn’t realize I was targeting an interpreter and not machine code.

Great series of articles!

I think, interestingly, that writing the middle of a compiler is actually the best learning as a programmer.

Parsing (should be) easy, the backend is hard but well documented and trodden, but the semantic analysis and error handling is where the real murky water is (Especially when you start trying t optimize it, like adding caching or threading or deferred execution)

I could not agree more. Also, most textbooks and resources on compilers always spend a lot of time on grammars, lexing and parsing. Finding good stuff about intermediate representations, optimization passes and static analysis is harder than it should.
One of the best free resources on making interpreters (with VM, OOP and garbage collection support): https://craftinginterpreters.com
Yes! nand2tetris.org has this. (Also available on Coursera.)

You write a compiler for a Java-like language in several steps: a parser that organizes the raw code, then a compiler that emits the virtual machine code, then a translator between the virtual machine code and assembly (and then, between assembly and binary).

I would recommend starting with a Forth-like and building from there once you have a clue:

https://github.com/codr7/alang

recursion became second nature to me after a lot of hand coded parsing. "crafting interpreters" has really been a rewarding educational trip! "writing a interpreter/compiler in go" is also excellent complementary material.
I wrote a BASIC interpreter somewhat recently, in golang, and found it very nostalgic.

I've considered reworking it into a compiler, but never quite gotten around to it. Perhaps a challenge for the near year.

Don't forget to implement a garbage collector.