GitHub - eliasdejong/plox: Python port of the Lox language from the 'Crafting Interpreters' book (www.craftinginterpreters.com/)

GitHub

2 min read Original article ↗

Lox is Bob Nystrom's language described in his Crafting Interpreters book. It is an excellent resource to learn about compilers, huge credit to Bob for publishing the book online for free.

The book consists of 2 parts:

  1. Part 1, writing a jlox compiler in Java (scanner, parser + tree-walking interpreter)
  2. Part 2, writing clox in C with bytecode interpreter

plox implements most of the features from the first part, but in Python instead of Java.

Features:

  • Basic types (int, float, string, bool, null)
  • If-statements (if (x) { ... } else { ... })
  • Variable declaration & assignment (var a = ...; a = 10;)
  • Comparisons, boolean logic and basic math (+ - * / ! >= == || && etc.)
  • While loops (while (cond) { ... })
  • For loops (for (;;) { ... })

This port does not implement:

  • /* multi-line comments */
  • ternary if-statements
  • classes
  • functions
  • time()
  • sleep()

How to run

  1. Clone the repo
git clone https://github.com/eliasdejong/plox
  1. Navigate into the directory
  1. Run the code
python3 src/main.py program.plox --watch

The --watch flag will run a file watcher and re-run when the file is saved.

Example code

print "all fibonnaci numbers under 10,000";

var a = 0;
var temp;

for (var b = 1; a < 10000; b = temp + b) {
	print a;
	temp = a;
	a = b;
}

Output:

all fibonnaci numbers under 10,000
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765