4 ms·
As I wrote elsewhere, I use this tiny compiler as an introduction to the course, which goes into much more details and of course covers how to compile realistic
by p4bl0 4y ago
As I wrote elsewhere, I use this tiny compiler as an introduction to the course, which goes into much more details and of course covers how to compile realistic programming languages (with multiple types of data, variables, conditional and loop control structures, functions, pointers, list and arbitrary structures, etc.) down to assembly code.
Thanks for all your interesting links :).
- kragen 4y agoOh, of course I didn't mean to imply that that was all you were teaching! I was just thinking that maybe a compiler that did something a little more impressive (for the effort required to understand it) might arouse more interest and provoke less No-True-Scotsman criticism. Though, honestly, stupid criticism is the vast majority of what HN is capable of, and you shouldn't take the uninformed criticism of HN commenters too seriously. Of course the compilers you teach later on with variables, conditionals, loops, multiple types, pointers, etc., are more capable and thus more impressive. But presumably they also require even more effort to understand than the "tiny" compiler you're presenting in this gist. I hope you find many things you enjoy in the links! Even if they aren't directly useful as pedagogical examples, they do demonstrate, for example, that a plain recursive-descent parser is already "two-pass" enough to handle assignment to variables, contra the statement in your gist, "In a more complex language (e.g., adding support for assignment to variables), we would need an additional front-end pass after the parser." Indeed, StoneKnifeForth is a single-pass compiler in less code than your tiny compiler that supports not only assignment to variables, but also arrays, I/O, conditionals, loops, defining and calling subroutines with arguments, pointers, ELF output, and i386 machine code generation with peephole optimization. And it's not because it's written in a more powerful language than OCaml; it's written in the profoundly substandard dialect of Forth that it implements, which lacks Forth's compile-time metaprogramming facilities and in which only one character is significant in identifiers. I was wondering if maybe my memory of StoneKnifeForth was wrong and it wasn't actually 132 lines of code, because that sure sounds like a lot of functionality in 132 lines of code. It turns out it's 117 lines of code, not 132. (The build process builds a version with comments stripped out, called trimmed.tbf1, and verifies that it compiles identically, to find this out.) So maybe you can learn some things from them that will enable you to write better compilers!
- supportlocal4h 4y agoOh, you should see the 128-line compiler OP unveils in the second hour of the class, now that students have the gist. And by the end of third hour...
- kragen 4y agoI'd love to!