This repository contains a full-featured Java implementation of the Lox programming language, built by following the guide "Crafting Interpreters" by Robert Nystrom. It features a hand-written scanner, a recursive descent parser, a static resolver for lexical scoping, and a tree-walk interpreter.
Lox is a simple, dynamically-typed, object-oriented scripting language with a C-like syntax. It's designed to be small enough to be implemented from scratch, yet powerful enough to be useful.
This implementation, jlox, brings the language to life on the Java Virtual Machine (JVM).
- A Java Development Kit (JDK), version 8 or higher.
The project is built using the Gradle wrapper, so no manual installation of Gradle is required.
To compile the source code and build the project, run the following command from the root directory:
./gradlew buildYou can run the interpreter in two modes:
-
Interactive REPL (Read-Eval-Print Loop) To start an interactive session where you can type Lox code directly, run:
./gradlew :app:run
> print "Hello, world!"; Hello, world! > 1 + 2 * 3; 7 -
Running a Script File To execute a Lox script from a file (e.g.,
script.lox), use the--argsflag:./gradlew :app:run --args="path/to/your/script.lox"
Here is a sample program in Lox that demonstrates functions, classes, and inheritance.
fun fib(n) {
if (n <= 1) return n;
return fib(n - 2) + fib(n - 1);
}
class Greeter {
greet(person) {
return "Greetings, " + person;
}
}
class LoudGreeter < Greeter {
greet(person) {
var greeting = super.greet(person);
return greeting + "!!!";
}
}
print "Fibonacci(10) is " + fib(10);
var greeter = LoudGreeter();
print greeter.greet("Lox User");