Going to build a tree-walking interpreter. It will have a lexer, parser, tree represnetation (AST), internal object system and evaluator.
This interpreter will implement a language called Monkey
// Binding values to names
let integer = 1;
let string = "Monkey";
let math_result = 10 * (20 / 2);
let array = [1, 2, 3, 4, 5];
array [0] // => 1
let hash_table = {"name": "Kogul", "age": 29};
hash_table["name"] // => "Kogul"
let add_function = fn(a,b) { return a + b; };
// implicit return
let add_function_2 = fn(a,b) { a + b; };
add_function(1,2) // => 3
//recursive function
let fibonacci = fn(x) {
if (x == 0) {
0
} else {
if (x == 1) {
1
} else {
fibonacci(x - 1) + fibonacci(x - 2);
}
}
};
//higher order functions (function can take other functions as arguments)
let twice = fn(f, x) {
return f(f(x));
}
let addTwo = fn(x) {
return x + 2;
}
twice(addTwo, 2) // => 6Transform source code into tokens so they are easier to work with.
Ex. let x = 5 + 5;
result from lexer will look like:
[
LET,
IDENTIFIER("X"),
EQUAL_SIGN,
INTEGER(5),
PLUS_SIGN,
INTEGER(5),
SEMICOLON
]