Building a language and an interpreter for it from scratch
đź“ť Note
Currently in early stage all language design decisions will follow the tutorial and examples from here.
// This is a comment
print "Hello, World!";
Current Lox
will follow syntax of C-like languages, but with some differences. It will have the following features:
Lox
will have the following data types:
Booleans
true;
false;
Numbers
123;
123.456;
Strings
"Hello, World!";
""; // Empty string
Nil
nil;
Lox
will have the following expressions:
Arithmetic
1 + 2;
3 - 4;
5 * 6;
7 / 8;
-9; // prefix
Comparison
1 > 2;
3 < 4;
5 >= 6;
7 <= 8;
123 == 456;
123 != 456;
Logical
true and false;
true or false;
!true;
Grouping
(1 + 2) * 3;
A statement’s job is to produce some effect. They are executed for their side effects such as output, input, or assignment and modification of variables.
Variables are used to store values. They are created with the var
keyword.
var a = 1;
var b; // Uninitialized variable defaults to `nil`
Lox
will have the following control flow statements:
if
if (true) {
print "true";
} else {
print "false";
}
while
while (true) {
print "true";
}
for
for (var i = 0; i < 10; i = i + 1) {
print i;
}
Functions are used to group statements together to perform some task. They are created with the fun
keyword.
fun add(a, b) {
return a + b;
}
fun main() {
print add(1, 2); // returns `nil` since main() doesn't return anything
}
Functions are considered first-class citizens in Lox
. This means that they can be passed around like any other value.
fun add(a, b) {
return a + b;
}
fun main() {
var adder = add;
print adder(1, 2);
}
fun wrapper()
{
fun inner()
{
print "Hello, World!";
}
}
There are two ways to approach objects in OOP
:
In class-based languages, classes are the blueprints for objects. They define what properties and methods an object will have. Objects are instances of classes. Instances store state in fields, and behavior is defined by methods.
In prototype-based languages, objects are the blueprints for objects. They define what properties and methods an object will have. Objects are instances of other objects.
Lox
ApproachLox
will follow the class-based approach.
class Person {
init(name) {
this.name = name;
}
greet() {
print "Hello, my name is " + this.name + ".";
}
}
var person = Person("John");
person.greet();
Lox
class Person {
init(name) {
this.name = name;
}
greet() {
print "Hello, my name is " + this.name + ".";
}
}
class Student < Person {
init(name, id) {
super.init(name);
this.id = id;
}
greet() {
super.greet();
print "My student ID is " + this.id + ".";
}
}
For now standard libraries in Lox
will be limited to the default clock()
method. I will slowly add other methods to give it basic functionality.
Look for the complete list of methods here
PyLox
our InterpreterPyLox
is a tree walk interpreter written in Python
. It will be used as the default interpreter for Lox
.