4 ms·
Semi-related: in the nand2tetris course, they teach you enough so they can add a keyword in their (admittedly toy) system -- the course involves implementing th
by SilasX 5y ago
Semi-related: in the nand2tetris course, they teach you enough so they can add a keyword in their (admittedly toy) system -- the course involves implementing the entire toolchain, including the high-level language[1] compiler, which emits VM code, and the VM code's translator into assembly.
By the time you've implemented a compiler that "just works" for the language, you notice that you have really inefficient code for those times when all you need to do is increment a variable by 1, given that the hardware has an opcode for that! In order to have nice, general compilation across all use cases, you've programmed the compiler to implement any case of "add X to variable" via the VM commands for "push X's value onto stack, push variable's value onto stack, call add, pop stack into X".
So, I figured I could add "inc" as a keyword. You have the compiler recognize that keyword and translate "inc <var>" into a VM instruction, and then tell the translator how to turn that VM instruction into something that makes use of the opcode.
(Alternatively, you can have it just recognize when it's doing something of the form "<variable> = <variable> + 1", but that's trickier once you've written the whole VM emission step as a single-pass operation.)
I know, pretty basic stuff from the standpoint of a professional compiler programmer, but pretty neat to be able to make an addition to the language like that!
[1] It uses "Jack", a syntactic-sugar-free Java-like language