Chapter 1 jlox
jlox is my implementation of the Lox programming language, written in Java. It uses the tree-walk interpreter from the Crafting Interpreters book.
My jlox is currently still a work in progress.
1.1 Motivation
Over time, programming languages have become more and more abstract. As such, the code we write has gotten closer and closer to spoken language.
This is a trend that I believe will only continue in future years, especially with the development of Artificial Intelligence (AI) that is able to process inputs as high-level as natural language. Even the practice of designing and refining the prompts provided to LLMs is somewhat akin to programming (prompt engineering).
It can be easy to take for granted the amount of work that high-level programming languages perform for us behind the scenes. Wanting to know more about how they really work, I took an interest in language interpreters and compilers.
1.2 Language Features
1.2.1 Data Types
Lox features several built-in data types.
1.2.2 Expressions
1.2.2.1 Mathematical Expressions
jlox features common numeric operations and negation:
a + b - a;
a * b / c;
-value;
1.2.3 Control Flow
if and else statements:
if (condition) {
// ...
} else {
// ...
}
while and for loops:
while (num > 0) {
num = num - 1;
}
for (var i = 0; i < 5; i = i + 1) {
print i;
}
1.2.4 Functions
Functions are first class in Lox, and return nil by default.
fun sum(first, second) {
return first + second;
}
sum(1, 2);
1.2.5 Classes
Class methods are declared without the fun keyword.
class Entity {
move() {
print "Entity moved!";
}
}
var myEntity = Entity(); // Created instance of Entity class
We can assign fields, or create them if they don’t already exist:
myEntity.age = 57;
myEntity.name = "Bob";
We can also do this in the init method which is called when the object is constructed:
class Entity {
init(age, name) {
this.age = age;
this.name = name;
}
// ...
}
var myEntity = Entity(57, "Bob");
The arguments passed to the class are forwarded to the init method.
1.2.6 Comments
jlox allows single-line comments with
//or C-style block comments with/**/.