Skip to content

suryxks/Lox

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

24 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Lox

Two implementations of the Lox programming language from the book Crafting Interpreters by Robert Nystrom.

Lox is a high-level, dynamically-typed language designed for learning about interpreters and compilers.

Project Structure

Lox/
├── src/          # Rust tree-walk interpreter (Part I)
├── vm/           # C bytecode VM/compiler (Part II)
└── README.md
  • src/ - Tree-walk interpreter written in Rust
  • vm/ - Bytecode virtual machine and compiler written in C (clox)

Building & Running

Rust Implementation (Tree-walk Interpreter)

# Run in REPL mode
cargo run

# Run a Lox script
cargo run path/to/script.lox

C Implementation (Bytecode VM)

cd vm
mkdir build && cd build
cmake ..
make
./clox              # REPL mode
./clox script.lox  # Run script

Features Implemented

Rust (Tree-walk Interpreter)

Category Features
Operators +, -, *, /, >, >=, <, <=, ==, !=, !, and, or
Literals Numbers, strings, booleans (true/false), nil
Statements var, print, if/else, while, for, fun, return, blocks
Functions Function declarations, function calls with arity validation, closures
Scope Global and local variables, static resolution for closures

C (Bytecode VM)

Category Features
Operators +, -, *, /, >, >=, <, <=, ==, !=, !
Literals Numbers, strings, booleans (true/false), nil
Statements var, print, expression statements, blocks
Variables Global and local variables
Compilation Bytecode compilation to chunks, precedence-based parsing
VM Stack-based VM with opcode dispatch, constant pool

Example Lox Code

// Fibonacci function
fun fib(n) {
  if (n <= 1) return n;
  return fib(n - 1) + fib(n - 2);
}

// Print first 10 Fibonacci numbers
for (var i = 0; i < 10; i = i + 1) {
  print fib(i);
}

// Variables and arithmetic
var a = 10;
var b = 20;
print a + b;

// String concatenation
var greeting = "Hello, " + "World!";
print greeting;

// Logical operators
var x = true;
var y = false;
print x and y;  // false
print x or y;   // true

Output:

0
1
1
2
3
5
8
13
21
34
30
Hello, World!
false
true

Differences Between Implementations

Feature Rust C
Implementation style Tree-walk AST traversal Bytecode VM
Performance Slower (interpreted) Faster (compiled)
Closures Supported Not implemented
Classes Not implemented Not implemented
For loops Supported Not implemented
and/or keywords Supported Token defined, not parsed

References

  • Crafting Interpreters by Robert Nystrom
  • Part I: A Tree-Walk Interpreter
  • Part II: A Bytecode Virtual Machine

License

MIT

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors