My bytecode VM Lox interpreter | |
2024-10-06 | |
Last edit: 2024-10-06 | |
--------------------- | |
The aim of this post is to describe the general operation of the program and so… | |
So I continued with “Crafting Interpreters” by Robert Nystrom after making … | |
This version is written in C, which means we have to write a lot of code oursel… | |
## Compiler | |
The primary purpose of our compiler is to generate a chunk of code in bytecode … | |
### Scanner | |
The token scanner is very classic, with only one thing to say: the function res… | |
### Parser | |
An interesting point to note is that the author chose not to use a syntax tree … | |
We also implemented a Vaughan Pratt's parser, in our case a “top-down operato… | |
```c | |
typedef enum { | |
PREC_NONE, | |
PREC_ASSIGNMENT, // = | |
PREC_OR, // or | |
PREC_AND, // and | |
PREC_EQUALITY, // == != | |
PREC_COMPARISON, // < > <= >= | |
PREC_TERM, // + - | |
PREC_FACTOR, // * / | |
PREC_UNARY, // ! - | |
PREC_CALL, // . () | |
PREC_PRIMARY | |
} Precedence; | |
``` | |
This precedence is simply used to control the parsing of expressions. A rule wi… | |
## Bytecode | |
To manage conditions, we emit `OP_JUMP` operation code for conditions. If a con… | |
In my implementation, all immediate values are encoded on 8 bits, with the exce… | |
## Virtual Machine | |
The VM is centered on a stack where we push operands, local variables, etc.. | |
Everything at runtime is managed by callframes, even the top-level code is embe… | |
## Example | |
Here is a simple Lox example that can be evaluated by my interpreter. | |
```text | |
fun fib(n) { | |
if (n < 2) { | |
return n; | |
} | |
return fib(n - 2) + fib(n - 1); | |
} | |
print fib(10); | |
``` | |
## Links | |
https://github.com/theobori/lox-virtual-machine | |