A Python implementation of the Lox programming language.
Lox is a dynamically-typed, high-level scripting language designed by Robert Nystrom for his book Crafting Interpreters. It features C-style syntax with first-class functions, closures, and object-oriented programming support.
This implementation includes:
- Lexical Analysis: Tokenization of Lox source code
- Parsing: Recursive descent parser with precedence handling
- AST Generation: Abstract Syntax Tree representation
- Semantic Analysis: Variable resolution and scope checking
- Interpretation: Tree-walk interpreter with runtime evaluation
- Data Types: Numbers, strings, booleans, nil
- Variables: Declaration and assignment
- Functions: First-class functions with closures
- Classes: Object-oriented programming with inheritance
- Control Flow: if/else, while, for loops, break, return
- Native Functions: Built-in functions like
clock()
// src.lox
fun fibonacci(n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
for (var i = 0; i < 10; i = i + 1) {
print fibonacci(i);
}
Run with:
python3 -m app.main run src.loxThe interpreter follows a traditional compiler pipeline architecture:
scanner.py- Tokenizes source code into tokenstoken.py- Token data structure and typesparser.py- Recursive descent parser producing ASTexpr.py- Expression AST node definitionsstmt.py- Statement AST node definitions
resolver.py- Static variable resolution, scope checking etc.
interpreter.py- Tree-walk interpreter executing ASTenvironment.py- Scope and variable binding managementlox_callable.py- Interface for callable objectslox_function.py- User-defined function implementationlox_class.py- Class and inheritance supportlox_instance.py- Object instance representationnative_fns.py- Built-in standard library functions
main.py- Entry point and command-line interfaceAstPrinter.py- Debug AST visualizationerrors.py- Error handling and reportingruntime_error.py- Runtime exception typesreturn_error.py- Function return control flowbreak_error.py- Loop break control flowutils.py- Helper functions