The lox interpreter is implemented by Rust lang.
Different from Tree-Walking interpreter, lox interpreter is a Single-pass interpreter. This interpreter is also a virtual machine based interpreter.
For this interpreter learning project, we don't strictly obey the official grammar standard. I made some different design choices or some additional features from the original one in Crafting Interpreters book. As the following:
- Change
vartoletfor variable declaration. - Add
switchstatement. - Add
&&and||logical operators. - Add
%operator. - Add
+=、-=、*=、/=、%=assignment operators. - Add support for string escaping.
As using raw pointer in Rust is unsafe, so we use ObjIndex to represent the index of object in the heap. This is a safe way to implement the virtual machine based interpreter.
- Single-pass interpreter which performs better than tree-walk one.
- Virtual machine based interpreter.
- Instruction set based on stack (A better performance one is based on register).
- Support advanced features of closure.
Here, we support:
- variable declaration & assignment
- logical operators
- control flow (if, while, for, switch)
- function statement
let a = 1;
let b = 2;
let c = a + b;
print c + 1; // 4
let a = 2;
if a > 1 and a < 3 {
print "a is greater than 1 and b is less than 3";
}
let a = 0;
if (a > 1) {
print "a is greater than 1";
} else if (a < 1) {
print "a is less than 1";
} else {
print "a is equal to 1";
}
let a = 0;
while (a < 10) {
print a;
a = a + 1;
}
for (let i = 0; i < 10; i = i + 1) {
print i;
}
let a = 1;
switch a {
case 1:
print "a is 1";
case 2:
print "a is 2";
default:
print "a is not 1 or 2";
}
fun fibonacci(n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
print fibonacci(10); // 55
fun makeCounter() {
let count = 0;
fun counter() {
count = count + 1;
return count;
}
return counter;
}
let counter = makeCounter();
print counter(); // 1
print counter(); // 2
print counter(); // 3
Currently supported native functions: clock、print、println.
let start = clock();
// do something
let end = clock();
print("Time taken: " + (end - start) + " seconds");
- Crafting Interpreters: Follow the step of Robert Nystrom to make your own programming language (Implemented by Java and C).
- Pratt Parsers: A better way to parse expression.