Crafting Interpreters Cheat Sheet
This article is a quick guide to Crafting Interpreters, with concise explanations and a runnable example for each chapter. Use it to review the main ideas or skip chapters you already know.
The implementations are written in Python. You can run them directly on this page in Pyish, my Python dialect that you can run in the browser.
The example programs use a small subset of Lox syntax.
Runtime data is stored in tuples, dictionaries and lists. Only parts of Lox are implemented. Differences from the book are described beside the code.
Browser notebook usage
Run the examples with Pyish, a Python dialect. Edits are saved in this browser's local storage.
Keyboard shortcuts
Browser notebook usage
Run the examples with Pyish, a Python dialect. Edits are saved in this browser's local storage.
Click Run all to run the notebook, or a cell's ▶ button to run that cell. In Jupyter, use Run All.
Edit mode
- ⌘/Ctrl + ↵
- Run cell
- ⇧ + ↵
- Run & go to next cell
- Esc
- Exit editing
Navigation mode
- A / B
- Add cell above / below
- DD
- Delete cell
- U
- Undo deletion
- ↑ / ↓
- Previous / next cell
- ↵ / click
- Edit cell
- Esc again
- Navigate blog normally
Try the language
Use integer literals and the operators +, -, * and <. Use parentheses to specify expression grouping. You can also declare variables, assign values and use print, if/else and while.
In the tree-walk interpreter, variable values are stored in one dictionary. In the VM, variable values are stored in one indexed list. Functions, strings and classes are implemented in separate chapter examples.
In the examples, we parse programs into a tuple AST, then evaluate the AST directly or compile it to bytecode for a virtual machine. In Chapter 17, we compile expressions directly to bytecode during parsing.
Prerequisites
Run these cells before the examples. Click a title to view its code later in the article.
compare_program("print 10 - 3 - 2 * 2;")
[OUT]:
Tree walk: [3]
Bytecode VM: [3]
compare_program("""
var i = 0;
var total = 0;
while (i < 5) {
total = total + i;
i = i + 1;
}
print total;
""")
[OUT]:
Tree walk: [10]
Bytecode VM: [10]
compare_program("""
var score = 7;
if (score < 10) {
print score * 2;
} else {
print score;
}
""")
[OUT]:
Tree walk: [14]
Bytecode VM: [14]
Chapter 4. Scanning
Split var x=1+2; into tokens for names, numbers and operators. Then parse the tokens. Use a regular expression for scanning here. In the book, implement the scanner with explicit state and lookahead.
def ch4_scanning() -> None:
import re
token = re.compile(r"(?P<NUM>\d+)|(?P<ID>[A-Za-z_]\w*)|(?P<OP>[=+;])|(?P<WS>\s+)|(?P<ERROR>.)")
def scan(s: str):
result = []
for m in token.finditer(s):
if m.lastgroup == "ERROR":
raise SyntaxError(f"unexpected character {m.group()!r} at {m.start()}")
if m.lastgroup != "WS":
result.append((m.lastgroup, m.group()))
return result
print(scan("var x=1+2;"))
ch4_scanning()
[OUT]:
[('ID', 'var'), ('ID', 'x'), ('OP', '='), ('NUM', '1'), ('OP', '+'), ('NUM', '2'), ('OP', ';')]
Chapter 5. Representing Code
Represent 1 + (2 + 3) as nested tuples. Then evaluate the tuples recursively. Evaluate the inner addition before the outer addition.
def ch5_ast() -> None:
def ev(e):
match e:
case ("lit", v): return v
case ("+", a, b): return ev(a) + ev(b)
case _: raise ValueError(e)
expr = ("+", ("lit", 1), ("+", ("lit", 2), ("lit", 3)))
print(ev(expr))
ch5_ast()
[OUT]:
6
Chapter 6. Parsing Expressions
Parse 1+2*3+(4*5) into an AST. Group multiplication before addition. Group consecutive additions from the left. Use a separate parsing function for each precedence level, as in Chapter 6.
def ch6_structure() -> None:
import re
token_re = re.compile(r"\d+|[()+*]|\S")
toks = token_re.findall("1+2*3+(4*5)")
i = 0
def peek():
return toks[i] if i < len(toks) else None
def eat(tok=None):
nonlocal i
t = peek()
if tok is not None and t != tok:
raise SyntaxError((tok, t))
i += 1
return t
def primary():
t = peek()
if t is None:
raise SyntaxError("unexpected EOF")
if t.isdigit():
eat()
return ("lit", int(t))
if t == "(":
eat("(")
e = expr()
eat(")")
return e
raise SyntaxError(t)
def term():
e = primary()
while peek() == "*":
eat("*")
e = ("*", e, primary())
return e
def expr():
e = term()
while peek() == "+":
eat("+")
e = ("+", e, term())
return e
ast = expr()
if peek() is not None:
raise SyntaxError(f"trailing token {peek()}")
def ev(e):
match e:
case ("lit", v): return v
case ("+", a, b): return ev(a) + ev(b)
case ("*", a, b): return ev(a) * ev(b)
case _: raise ValueError(e)
print("Tokens:")
print(toks)
print("Parsed AST:")
print(ast)
print("Evaluation:")
print(ev(ast))
ch6_structure()
[OUT]:
Tokens:
['1', '+', '2', '*', '3', '+', '(', '4', '*', '5', ')']
Parsed AST:
('+', ('+', ('lit', 1), ('*', ('lit', 2), ('lit', 3))), ('*', ('lit', 4), ('lit', 5)))
Evaluation:
27
Chapter 7. Evaluating Expressions
Evaluate both operands of +. Then compare their types. Add 1 and 2 to get 3. Raise TypeError for the operands 1 and "s".
def ch7_eval_semantics() -> None:
def ev(e):
match e:
case ("lit", v): return v
case ("+", a, b):
x, y = ev(a), ev(b)
if type(x) != type(y): raise TypeError("no mixed +")
return x + y
case _: raise ValueError(e)
print("Valid addition:", ev(("+", ("lit", 1), ("lit", 2))))
try: ev(("+", ("lit", 1), ("lit", "s")))
except Exception as ex: print("Mixed-type addition:", type(ex).__name__, str(ex))
ch7_eval_semantics()
[OUT]:
Valid addition: 3
Mixed-type addition: TypeError no mixed +
Chapter 8. Statements and State
Store variable names and values in the dictionary env. Then change env["x"] from 0 to 3. Use one dictionary here. In the book, create nested environments for block scopes.
def ch8_state() -> None:
env: dict[str, object] = {}
def eval_(e):
match e:
case ("lit", v): return v
case ("var", n): return env[n]
case _: raise ValueError(e)
def exec_(s):
match s:
case ("var", n, e): env[n] = eval_(e)
case ("set", n, e): env[n] = eval_(e)
case _: raise ValueError(s)
exec_(("var", "x", ("lit", 0)))
exec_(("set", "x", ("lit", 3)))
print(env)
ch8_state()
[OUT]:
{'x': 3}
Chapter 9. Control Flow
Evaluate the while condition before each iteration. Stop when x reaches 3. Here, execute structured AST nodes as in jlox. In Chapter 23, compile control flow to bytecode jumps.
def ch9_control_flow() -> None:
env = {"x": 0}
def ev(e):
match e:
case ("var", name): return env[name]
case ("lit", value): return value
case ("<", a, b): return ev(a) < ev(b)
case _: raise ValueError(e)
def execute(stmt):
match stmt:
case ("inc", name): env[name] += 1
case ("while", condition, body):
while ev(condition):
for child in body: execute(child)
case _: raise ValueError(stmt)
execute(("while", ("<", ("var", "x"), ("lit", 3)), [("inc", "x")]))
print(env["x"])
assert env["x"] == 3
ch9_control_flow()
[OUT]:
3
Chapter 9. Syntactic Sugar
Rewrite a for loop as an initializer followed by a while loop. Put the increment at the end of the loop body, as in Chapter 9. Perform the rewrite on tuple AST nodes. Execute the result with one dictionary and no block scopes.
def ch9_sugar() -> None:
def desugar(stmt):
match stmt:
case ("for", init, cond, step, body):
return [init, ("while", cond, body + [step])]
case _:
return [stmt]
def run(block):
env = {}
def ev(e):
match e:
case ("lit", v): return v
case ("var", n): return env[n]
case ("+", a, b): return ev(a) + ev(b)
case ("<", a, b): return ev(a) < ev(b)
case _: raise ValueError(e)
def exec_block(xs):
for s in xs:
exec_stmt(s)
def exec_stmt(s):
match s:
case ("var", n, e): env[n] = ev(e)
case ("set", n, e): env[n] = ev(e)
case ("print", e): print(ev(e))
case ("while", c, b):
while ev(c):
exec_block(b)
case _: raise ValueError(s)
exec_block(block)
sugared = (
"for",
("var", "i", ("lit", 0)),
("<", ("var", "i"), ("lit", 3)),
("set", "i", ("+", ("var", "i"), ("lit", 1))),
[("print", ("var", "i"))],
)
core = desugar(sugared)
print("Desugared for loop:")
print(core)
print("Output from running it:")
run(core)
ch9_sugar()
[OUT]:
Desugared for loop:
[('var', 'i', ('lit', 0)), ('while', ('<', ('var', 'i'), ('lit', 3)), [('print', ('var', 'i')), ('set', 'i', ('+', ('var', 'i'), ('lit', 1)))])]
Output from running it:
0
1
2
Chapter 10. Functions
Store the parameter names, body and environment reference in a function tuple. At each call, create a new environment for the arguments. Set its parent to the environment stored in the function tuple.
def ch10_functions() -> None:
class Env(dict):
def __init__(self, parent=None):
super().__init__()
self.parent = parent
def get(self, name):
if name in self:
return self[name]
if self.parent is not None:
return self.parent.get(name)
raise NameError(name)
def ev(e, env):
match e:
case ("lit", v):
return v
case ("var", n):
return env.get(n)
case ("+", a, b):
return ev(a, env) + ev(b, env)
case ("fun", params, body):
return ("closure", params, body, env)
case ("call", fn_expr, arg_exprs):
tag, params, body, closed = ev(fn_expr, env)
call_env = Env(closed)
for p, a in zip(params, arg_exprs):
call_env[p] = ev(a, env)
return ev(body, call_env)
case _:
raise ValueError(e)
env = Env()
env["makeAdder"] = ev(
("fun", ["n"], ("fun", ["x"], ("+", ("var", "x"), ("var", "n")))),
env,
)
env["add5"] = ev(("call", ("var", "makeAdder"), [("lit", 5)]), env)
print(env["add5"][0], ev(("call", ("var", "add5"), [("lit", 2)]), env))
ch10_functions()
[OUT]:
closure 7
Chapter 11. Resolving and Binding
Resolve each variable reference before execution. A later declaration must not change which binding is read. Execute the AST with runtime name lookup. Then resolve the references and execute the AST again. Only the resolved version prints global twice.
def ch11_resolution() -> None:
scopes = []
def resolve_expr(e):
if e[0] != "var": return e
name = e[1]
for depth, scope in enumerate(reversed(scopes)):
if name in scope:
if not scope[name]: raise SyntaxError("read in own initializer")
return ("at", depth, name)
return ("global", name)
def resolve(block):
result = []
for stmt in block:
match stmt:
case ("var", name, init):
if scopes: scopes[-1][name] = False
result.append(("var", name, resolve_expr(init)))
if scopes: scopes[-1][name] = True
case ("fun", name, body):
if scopes: scopes[-1][name] = True
scopes.append({})
result.append(("fun", name, resolve(body)))
scopes.pop()
case ("block", body):
scopes.append({})
result.append(("block", resolve(body)))
scopes.pop()
case ("print", e): result.append(("print", resolve_expr(e)))
case ("call", _): result.append(stmt)
case _: raise ValueError(stmt)
return result
def run(program):
globals_ = {}
output = []
def read(e, envs):
match e:
case ("lit", value): return value
case ("at", depth, name): return envs[-1 - depth][name]
case ("global", name): return globals_[name]
case ("var", name):
for env in reversed(envs):
if name in env: return env[name]
raise NameError(name)
case _: raise ValueError(e)
def execute(block, envs):
for stmt in block:
match stmt:
case ("var", name, init): envs[-1][name] = read(init, envs)
case ("fun", name, body): envs[-1][name] = (body, envs[:])
case ("block", body): execute(body, envs + [{}])
case ("print", e): output.append(read(e, envs))
case ("call", name):
body, captured = read(("var", name), envs)
execute(body, captured + [{}])
case _: raise ValueError(stmt)
execute(program, [globals_])
return output
program = [
("var", "a", ("lit", "global")),
("block", [
("fun", "showA", [("print", ("var", "a"))]),
("call", "showA"),
("var", "a", ("lit", "block")),
("call", "showA"),
]),
]
dynamic, lexical = run(program), run(resolve(program))
print("Runtime lookup:", dynamic)
print("Resolved lookup:", lexical)
assert dynamic == ["global", "block"]
assert lexical == ["global", "global"]
try:
resolve([("block", [("var", "a", ("var", "a"))])])
except SyntaxError as error:
print("Invalid initializer:", str(error))
else:
raise AssertionError("self-initialization was accepted")
ch11_resolution()
[OUT]:
Runtime lookup: ['global', 'block']
Resolved lookup: ['global', 'global']
Invalid initializer: read in own initializer
Chapter 12. Classes
Field values are stored in the instance. Method definitions are stored in the class. Create a Point with x=3 and y=4. Then call norm2 to get 25.
def ch12_classes() -> None:
def lookup_method(cls, name):
methods = cls["methods"]
if name in methods:
return methods[name]
raise KeyError(name)
def bind(method, this):
return lambda *args: method(this, *args)
def new(cls, *args):
obj = {"class": cls, "fields": {}}
init = cls["methods"].get("init")
if init is not None:
bind(init, obj)(*args)
return obj
def getprop(obj, name):
if name in obj["fields"]:
return obj["fields"][name]
return bind(lookup_method(obj["class"], name), obj)
Point = {
"name": "Point",
"methods": {
"init": lambda this, x, y: this["fields"].update({"x": x, "y": y}),
"norm2": lambda this: this["fields"]["x"] ** 2 + this["fields"]["y"] ** 2,
},
}
p = new(Point, 3, 4)
print(getprop(p, "norm2")())
ch12_classes()
[OUT]:
25
Chapter 12 Design Note. Prototypes
Search the object’s dictionary for the property. If the property is absent, search the dictionary referenced by __proto__. Repeat the search along the prototype chain. See the design note after Chapter 12 for this alternative to classes.
def ch12_prototypes() -> None:
proto = {"to_s": lambda self: f"{self['x']},{self['y']}"}
obj = {"__proto__": proto, "x": 1, "y": 2}
def get(o, k): return o[k] if k in o else get(o["__proto__"], k)
print(get(obj, "to_s")(obj))
ch12_prototypes()
[OUT]:
1,2
Chapter 13. Inheritance
Search the class’s method dictionary. If the method is absent, repeat the search in the superclass. Here, call A.m from B.m. Add B-> before the returned string to get B->A.
def ch13_inheritance() -> None:
def lookup_method(cls, name):
if name in cls["methods"]:
return cls["methods"][name]
if cls["super"] is not None:
return lookup_method(cls["super"], name)
raise KeyError(name)
def bind(method, this):
return lambda *args: method(this, *args)
def new(cls):
return {"class": cls, "fields": {}}
def getprop(obj, name):
return bind(lookup_method(obj["class"], name), obj)
A = {
"name": "A",
"super": None,
"methods": {
"m": lambda this: "A",
},
}
B = {
"name": "B",
"super": A,
"methods": {
"m": lambda this: "B->" + lookup_method(B["super"], "m")(this),
},
}
b = new(B)
print(getprop(b, "m")())
ch13_inheritance()
[OUT]:
B->A
End-to-End: Source Parser
Parse the opening source programs into tuple AST nodes. Use these nodes to represent expressions and statements. During execution, store variable values in one dictionary for the tree-walk interpreter or one indexed list for the VM. Neither implementation has block scopes.
import re
class MiniParser:
def __init__(self, source):
self.tokens = re.findall(r"[0-9]+|[A-Za-z_][A-Za-z_0-9]*|[^\s]", source) + ["<eof>"]
self.i = 0
def peek(self): return self.tokens[self.i]
def take(self, expected=None):
token = self.peek()
if expected is not None and token != expected:
raise SyntaxError(f"expected {expected}, got {token}")
if token == "<eof>": raise SyntaxError("unexpected end of program")
self.i += 1
return token
def name(self):
token = self.take()
if re.fullmatch(r"[A-Za-z_][A-Za-z_0-9]*", token) is None or token in ["var", "print", "if", "else", "while"]:
raise SyntaxError(f"expected variable name, got {token}")
return token
def primary(self):
token = self.peek()
if token.isdigit(): self.take(); return ("lit", int(token))
if token == "-": self.take(); return ("neg", self.primary())
if token == "(":
self.take(); result = self.expression(); self.take(")"); return result
return ("var", self.name())
def binary(self, operand, operators):
result = operand()
while self.peek() in operators:
op = self.take()
result = (op, result, operand())
return result
def product(self): return self.binary(self.primary, ["*"])
def sum(self): return self.binary(self.product, ["+", "-"])
def expression(self): return self.binary(self.sum, ["<"])
def block(self):
self.take("{")
body = []
while self.peek() != "}": body.append(self.statement())
self.take("}")
return body
def statement(self):
token = self.peek()
if token in ["if", "while"]:
self.take(); self.take("(")
condition = self.expression(); self.take(")")
body = self.block()
if token == "while": return ("while", condition, body)
other = []
if self.peek() == "else": self.take(); other = self.block()
return ("if", condition, body, other)
if token == "print":
self.take(); result = ("print", self.expression())
else:
declaration = token == "var"
if declaration: self.take()
name = self.name(); self.take("=")
result = ("var" if declaration else "set", name, self.expression())
self.take(";")
return result
def parse(self):
result = []
while self.peek() != "<eof>": result.append(self.statement())
return result
def parse_program(source): return MiniParser(source).parse()
DEMO_PROG = parse_program("""
var i = 0;
var acc = 0;
while (i < 5) {
acc = acc + i;
i = i + 1;
}
if (acc < 10) { print acc; } else { print acc + 100; }
""")
End-to-End: Tree-Walk Interpreter
Evaluate expressions recursively. Execute statements in order. Append each printed value to an output list. Then compare this list with the VM’s output list.
def run_treewalk(prog):
env = {}
output = []
def ev(e):
match e:
case ("lit", v): return v
case ("var", n): return env[n]
case ("+", a, b):
x, y = ev(a), ev(b)
if type(x) != type(y): raise TypeError("no mixed +")
return x + y
case ("-", a, b): return ev(a) - ev(b)
case ("*", a, b): return ev(a) * ev(b)
case ("neg", a): return -ev(a)
case ("<", a, b):
x, y = ev(a), ev(b)
return x < y
case _: raise ValueError(e)
def exec_block(block):
for s in block: exec_stmt(s)
def exec_stmt(s):
match s:
case ("var", n, e): env[n] = ev(e)
case ("set", n, e): env[n] = ev(e)
case ("print", e): output.append(ev(e))
case ("if", c, t, f): exec_block(t if ev(c) else f)
case ("while", c, b):
while ev(c): exec_block(b)
case _: raise ValueError(s)
exec_block(prog)
return output
print(*run_treewalk(DEMO_PROG))
[OUT]:
110
Part III. A Bytecode Virtual Machine
Chapter 14. Chunks of Bytecode
Store instruction tuples in code. Store literal values in const. For each CONST instruction, read the value at the specified index in const. Push that value onto the stack.
def ch14_chunks() -> None:
const = [1, 2]
code = [("CONST", 0), ("CONST", 1), ("ADD",), ("RET",)]
print("Instruction listing:")
for i, ins in enumerate(code):
op, *a = ins
operand = f" {const[a[0]]}" if op == "CONST" else ""
print(f"{i}: {op}{operand}")
ch14_chunks()
[OUT]:
Instruction listing:
0: CONST 1
1: CONST 2
2: ADD
3: RET
Chapter 15. A Virtual Machine
Pop the right operand from the stack. Then pop the left operand. Subtract the right operand from the left operand. For 10 - 3, the result is 7. Use the same VM to execute the bytecode compiled in Chapter 17.
def run_expression_vm(code):
stack = []
for instruction in code:
op = instruction[0]
if op == "CONST": stack.append(instruction[1])
elif op == "NEG": stack.append(-stack.pop())
elif op in ["ADD", "SUB", "MUL"]:
rhs = stack.pop()
lhs = stack.pop()
if op == "ADD": stack.append(lhs + rhs)
elif op == "SUB": stack.append(lhs - rhs)
else: stack.append(lhs * rhs)
elif op == "RET":
assert len(stack) == 1
return stack.pop()
else: raise ValueError(op)
raise ValueError("missing RET")
code = [("CONST", 10), ("CONST", 3), ("SUB",), ("RET",)]
print(run_expression_vm(code))
assert run_expression_vm(code) == 7
[OUT]:
7
Chapter 15 Supplement. Register Sketch
Store the first operand in r[0]. Store the second operand in r[1]. Add the operands and write the result into r[0]. Compare these indexed operations with the stack operations used in the book.
def ch15_register_bytecode() -> None:
const = [1, 2]; r = [0, 0]
r[0] = const[0]; r[1] = const[1]
r[0] = r[0] + r[1]
print(r[0])
ch15_register_bytecode()
[OUT]:
3
Chapter 16. Scanning on Demand
Read one token at a time. Do not build a token list first. In Chapter 17, call this scanner during parsing and bytecode compilation.
def scan_expression(source):
import re
for match in re.finditer(r"[0-9]+|[^\s]", source):
text = match.group()
if not text.isdigit() and text not in "()+-*":
raise SyntaxError(f"unexpected character {text!r} at {match.start()}")
yield text
def ch16_lazy_scan():
tokens = scan_expression("1+(2*3)")
print("First token:", next(tokens))
print("Tokens after the first:", list(tokens))
ch16_lazy_scan()
[OUT]:
First token: 1
Tokens after the first: ['+', '(', '2', '*', '3', ')']
Chapter 17. Compiling Expressions
Emit bytecode during parsing, as in the book’s Pratt compiler. Do not construct an AST. Parse each right operand at precedence p + 1. This groups consecutive operators of precedence p from the left.
def compile_expression(source):
tokens = scan_expression(source)
current = next(tokens, None)
code = []
rules = {"+": (1, "ADD"), "-": (1, "SUB"), "*": (2, "MUL")}
def advance():
nonlocal current
previous = current
current = next(tokens, None)
return previous
def expression(min_precedence=0):
token = advance()
if token is not None and token.isdigit():
code.append(("CONST", int(token)))
elif token == "-":
expression(3)
code.append(("NEG",))
elif token == "(":
expression()
if current != ")": raise SyntaxError("expected closing parenthesis")
advance()
else:
raise SyntaxError(f"expected expression, got {token!r}")
while current in rules:
precedence, instruction = rules[current]
if precedence < min_precedence: break
advance()
expression(precedence + 1)
code.append((instruction,))
expression()
if current is not None: raise SyntaxError(f"trailing token {current!r}")
code.append(("RET",))
return code
for source, expected in [("10 - 3 - 2", 5), ("2 + 3 * 4", 14), ("-(2 + 3)", -5)]:
bytecode = compile_expression(source)
print(source, "=>", bytecode)
result = run_expression_vm(bytecode)
print("Result:", result)
assert result == expected
for invalid in ["1 +", "(1 + 2", "1 2", "1 @ 2"]:
try: compile_expression(invalid)
except SyntaxError: pass
else: raise AssertionError(invalid)
[OUT]:
10 - 3 - 2 => [('CONST', 10), ('CONST', 3), ('SUB',), ('CONST', 2), ('SUB',), ('RET',)]
Result: 5
2 + 3 * 4 => [('CONST', 2), ('CONST', 3), ('CONST', 4), ('MUL',), ('ADD',), ('RET',)]
Result: 14
-(2 + 3) => [('CONST', 2), ('CONST', 3), ('ADD',), ('NEG',), ('RET',)]
Result: -5
Chapter 18. Types of Values
Represent each value as a (type_tag, value) tuple. Compare the type tags before addition. For ("num", 1) and ("num", 2), return ("num", 3).
def ch18_tagged_values() -> None:
def add(a, b):
ta, va = a; tb, vb = b
if ta != tb: raise TypeError("type mismatch")
return (ta, va + vb)
print(add(("num", 1), ("num", 2)))
ch18_tagged_values()
[OUT]:
('num', 3)
Chapter 19. Strings
Allocate two String objects with equal chars values. Compare the contents of the two objects. Then compare their identities. To intern the strings, store one object per string value in a dictionary, as in Chapter 20.
def ch19_interning() -> None:
class String:
def __init__(self, chars): self.chars = chars
a, b = String("lox"), String("lo" + "x")
print("Equal contents:", a.chars == b.chars)
print("Same object before interning:", a is b)
pool = {}
def intern(string):
if string.chars not in pool: pool[string.chars] = string
return pool[string.chars]
print("Same object after interning:", intern(a) is intern(b))
assert a is not b and a.chars == b.chars
assert intern(a) is intern(b)
ch19_interning()
[OUT]:
Equal contents: True
Same object before interning: False
Same object after interning: True
Chapter 20. Hash Tables
Insert the keys 0, 4, 8 and 12 into a four-slot table. The initial index for each key is 0. On a collision, probe the subsequent slots. Limit each search to four probes to prevent an infinite loop. Resizing and deletion are not implemented.
def ch20_hashtable() -> None:
def find(table, key):
start = key % len(table) # integer keys, deliberately simple hash
for offset in range(len(table)):
index = (start + offset) % len(table)
entry = table[index]
if entry is None or entry[0] == key: return index
return None
def hput(table, key, value):
index = find(table, key)
if index is None: raise OverflowError("table is full")
table[index] = (key, value)
def hget(table, key):
index = find(table, key)
return None if index is None or table[index] is None else table[index][1]
table = [None] * 4
for key in [0, 4, 8, 12]: hput(table, key, key + 1)
print("Colliding keys:", table)
print("Lookup 8:", hget(table, 8))
print("Absent key in full table:", hget(table, 16))
assert hget(table, 8) == 9 and hget(table, 16) is None
hput(table, 8, 99)
assert hget(table, 8) == 99
try: hput(table, 16, 17)
except OverflowError as error: print("Insertion:", str(error))
else: raise AssertionError("full-table insertion was accepted")
ch20_hashtable()
[OUT]:
Colliding keys: [(0, 1), (4, 5), (8, 9), (12, 13)]
Lookup 8: 9
Absent key in full table: None
Insertion: table is full
Chapter 21. Global Variables
Store global variable names and values in the dictionary globals_. Set x to 1. Read the value of x. Add 2 to that value. Write the result, 3, back under the key x.
def ch21_globals() -> None:
globals_: dict[str, int] = {}
def setg(k: str, v: int) -> None: globals_[k] = v
def getg(k: str) -> int: return globals_[k]
setg("x", 1); setg("x", getg("x") + 2)
print(getg("x"))
ch21_globals()
[OUT]:
3
Chapter 22. Local Variables
Assign slot 0 to the outer x. Assign slot 1 to the inner x. Resolve each reference to the nearest declaration. On block exit, remove the inner declaration and pop its value. Then assign slot 1 to y.
class LocalCompiler:
def __init__(self):
self.locals = [] # (name, scope depth); index is the slot
self.depth = 0
self.code = []
def begin_scope(self): self.depth += 1
def declare(self, name, value):
self.locals.append((name, self.depth))
self.code.append(("CONST", value))
return len(self.locals) - 1
def resolve(self, name):
for slot in range(len(self.locals) - 1, -1, -1):
if self.locals[slot][0] == name: return slot
raise NameError(name)
def end_scope(self):
while self.locals and self.locals[-1][1] == self.depth:
self.locals.pop()
self.code.append(("POP",))
self.depth -= 1
# These stack operations are also used by the call-frame VM in Chapter 24.
def local_instruction(stack, base, instruction):
op, *args = instruction
if op == "CONST": stack.append(args[0])
elif op == "GET_LOCAL": stack.append(stack[base + args[0]])
elif op == "SET_LOCAL": stack[base + args[0]] = stack[-1]
elif op == "POP": stack.pop()
elif op in ["ADD", "SUB", "LE"]:
rhs = stack.pop(); lhs = stack.pop()
if op == "ADD": stack.append(lhs + rhs)
elif op == "SUB": stack.append(lhs - rhs)
else: stack.append(lhs <= rhs)
else: return False
return True
def ch22_locals():
compiler = LocalCompiler()
print("Outer x slot:", compiler.declare("x", 10))
compiler.begin_scope()
print("Inner x slot:", compiler.declare("x", 20))
assert compiler.resolve("x") == 1
compiler.end_scope()
print("x after block:", compiler.resolve("x"))
print("Reused slot for y:", compiler.declare("y", 30))
compiler.code.append(("GET_LOCAL", compiler.resolve("x")))
stack = ["caller's local"]
base = len(stack)
for instruction in compiler.code:
handled = local_instruction(stack, base, instruction)
assert handled
print("Read outer x:", stack.pop())
print("Stack at base 1:", stack)
assert stack == ["caller's local", 10, 30]
ch22_locals()
[OUT]:
Outer x slot: 0
Inner x slot: 1
x after block: 0
Reused slot for y: 1
Read outer x: 10
Stack at base 1: ["caller's local", 10, 30]
Chapter 23. Jumping Back and Forth
Emit a jump instruction with a placeholder target. Compile the branch. Replace the placeholder with the target instruction index. Execute the code with each condition. Make sure that the results are 10 and 20.
def ch23_patch_jumps() -> None:
def compile_choice(condition):
code = [("CONST", condition), ("JIF_FALSE", None), ("CONST", 10)]
skip_else = len(code)
code.append(("JMP", None))
code[1] = ("JIF_FALSE", len(code))
code.append(("CONST", 20))
code[skip_else] = ("JMP", len(code))
code.append(("RETURN",))
return code
def execute(code):
stack, ip = [], 0
while True:
op, *args = code[ip]; ip += 1
if op == "CONST": stack.append(args[0])
elif op == "JIF_FALSE":
if not stack.pop(): ip = args[0]
elif op == "JMP": ip = args[0]
elif op == "RETURN": return stack.pop()
else: raise ValueError(op)
print("Patched code:", compile_choice(True))
for condition, expected in [(True, 10), (False, 20)]:
result = execute(compile_choice(condition))
print(condition, "=>", result)
assert result == expected
ch23_patch_jumps()
[OUT]:
Patched code: [('CONST', True), ('JIF_FALSE', 4), ('CONST', 10), ('JMP', 5), ('CONST', 20), ('RETURN',)]
True => 10
False => 20
Chapter 24. Calls and Functions
Number local slots from 0 in each function. Store a separate stack base and instruction pointer in each call frame. To read a local variable, add the slot number to the frame’s stack base. Use Chapter 22’s stack operations here. The reserved callee slot from clox is not implemented.
class FrameVM:
def __init__(self, functions, trace=False):
self.functions = functions
self.stack = []
self.frames = []
self.trace = trace
def call(self, target, argc):
closure = {"name": target, "upvalues": []} if isinstance(target, str) else target
function = self.functions[closure["name"]]
if argc != function["arity"]: raise TypeError("wrong argument count")
base = len(self.stack) - argc
frame = {"closure": closure, "code": function["code"], "ip": 0, "base": base}
self.frames.append(frame)
if self.trace:
print("Call", closure["name"], "base", base, "arguments", self.stack[base:])
def close(self, base): pass # Close upvalues before deleting stack slots; implemented below.
def extra(self, frame, op, args): raise ValueError(op)
def run(self, target, args):
assert not self.frames and not self.stack
self.stack.extend(args)
self.call(target, len(args))
while self.frames:
frame = self.frames[-1]
op, *operands = frame["code"][frame["ip"]]
frame["ip"] += 1
if local_instruction(self.stack, frame["base"], (op, *operands)): continue
if op == "CALL": self.call(operands[0], operands[1])
elif op == "JIF_FALSE":
if not self.stack.pop(): frame["ip"] = operands[0]
elif op == "RETURN":
result = self.stack.pop()
self.close(frame["base"])
del self.stack[frame["base"]:]
self.frames.pop()
if not self.frames: return result
self.stack.append(result)
else: self.extra(frame, op, operands)
SUM_FUNCTIONS = {"sum": {"arity": 1, "code": [
("GET_LOCAL", 0), ("CONST", 0), ("LE",), ("JIF_FALSE", 6),
("CONST", 0), ("RETURN",),
("GET_LOCAL", 0), # The caller's n is stored below the recursive call's argument.
("GET_LOCAL", 0), ("CONST", 1), ("SUB",), ("CALL", "sum", 1),
("ADD",), ("RETURN",),
]}}
def ch24_calls_frames():
vm = FrameVM(SUM_FUNCTIONS, trace=True)
result = vm.run("sum", [3])
print("sum(3):", result)
assert result == 6
assert vm.run("sum", [0]) == 0
assert not vm.stack and not vm.frames
ch24_calls_frames()
[OUT]:
Call sum base 0 arguments [3]
Call sum base 2 arguments [2]
Call sum base 4 arguments [1]
Call sum base 6 arguments [0]
sum(3): 6
Call sum base 0 arguments [0]
Chapter 25. Closures
For two closures that reference one local variable, store the same Upvalue reference in both closure dictionaries. Before the function returns, copy the value from the stack slot into the upvalue object. Then delete the stack storage for the frame. See the book’s open and closed upvalues.
class Upvalue:
def __init__(self, stack, index):
self.stack, self.index = stack, index
self.closed = None
def get(self):
return self.closed if self.index is None else self.stack[self.index]
def set(self, value):
if self.index is None: self.closed = value
else: self.stack[self.index] = value
def close(self):
self.closed = self.stack[self.index]
self.index = None
self.stack = None
class ClosureVM(FrameVM):
def __init__(self, functions, trace=False):
super().__init__(functions, trace)
self.open = {} # absolute stack index -> Upvalue object
def capture(self, index):
if index not in self.open:
self.open[index] = Upvalue(self.stack, index)
if self.trace: print("Capture stack slot", index, "value", self.stack[index])
return self.open[index]
def close(self, base):
for index in list(self.open):
if index >= base:
upvalue = self.open.pop(index)
upvalue.close()
if self.trace: print("Close stack slot", index, "value", upvalue.get())
def extra(self, frame, op, args):
upvalues = frame["closure"]["upvalues"]
if op == "CLOSURE":
captures = [self.capture(frame["base"] + slot) for slot in args[1]]
self.stack.append({"name": args[0], "upvalues": captures})
elif op == "GET_UPVALUE": self.stack.append(upvalues[args[0]].get())
elif op == "SET_UPVALUE": upvalues[args[0]].set(self.stack[-1])
elif op == "CALL_VALUE":
target = self.stack.pop(-args[0] - 1)
self.call(target, args[0])
elif op == "PAIR":
right = self.stack.pop(); left = self.stack.pop()
self.stack.append([left, right])
else: raise ValueError(op)
COUNTER_FUNCTIONS = {
"make": {"arity": 1, "code": [
("CLOSURE", "increment", [0]), ("CLOSURE", "read", [0]),
# Read the captured slot while make's frame is active.
("CLOSURE", "read", [0]), ("CALL_VALUE", 0), ("POP",),
("PAIR",), ("RETURN",),
]},
"increment": {"arity": 0, "code": [
("GET_UPVALUE", 0), ("CONST", 1), ("ADD",),
("SET_UPVALUE", 0), ("RETURN",),
]},
"read": {"arity": 0, "code": [("GET_UPVALUE", 0), ("RETURN",)]},
}
def ch25_closures():
vm = ClosureVM(COUNTER_FUNCTIONS, trace=True)
increment, read = vm.run("make", [0])
shared = increment["upvalues"][0]
assert shared is read["upvalues"][0]
assert shared.index is None and not vm.open
vm.trace = False
other, other_read = vm.run("make", [0])
results = [vm.run(increment, []), vm.run(increment, []), vm.run(other, [])]
print("Two counters:", results)
print("Read through the second closure:", vm.run(read, []))
assert results == [1, 2, 1]
assert vm.run(read, []) == 2 and vm.run(other_read, []) == 1
assert other["upvalues"][0] is not shared
ch25_closures()
[OUT]:
Call make base 0 arguments [0]
Capture stack slot 0 value 0
Call read base 3 arguments []
Close stack slot 0 value 0
Two counters: [1, 2, 1]
Read through the second closure: 2
Chapter 25. Loop Variable Capture
Store a reference to one Cell object in all three functions. Each call then returns the final value, 2. Next, use a separate Cell for each iteration. The calls then return 0, 1 and 2. Allocate bindings according to the language’s loop-scope rules.
def ch25_loop_var() -> None:
class Cell:
def __init__(self, value):
self.value = value
shared = Cell(0)
late = []
for i in range(3):
shared.value = i
late.append(lambda cell=shared: cell.value)
snap = []
for i in range(3):
cell = Cell(i)
snap.append(lambda cell=cell: cell.value)
print("References to one Cell:")
print([f() for f in late])
print("References to a separate Cell per iteration:")
print([f() for f in snap])
ch25_loop_var()
[OUT]:
References to one Cell:
[2, 2, 2]
References to a separate Cell per iteration:
[0, 1, 2]
Chapter 26. Garbage Collection
Mark each root object. Follow its object references. Mark each object reached. Then delete the unmarked objects. There is no path from root 1 to object 4. There are two paths from root 1 to object 2.
def ch26_gc_tracing() -> None:
heap, roots = {1: [2, 3], 2: [], 3: [2], 4: []}, [1]
marked: set[int] = set()
def mark(o: int) -> None:
if o in marked: return
marked.add(o)
for r in heap.get(o, []): mark(r)
for r in roots: mark(r)
for o in list(heap):
if o not in marked: del heap[o]
print(sorted(heap))
ch26_gc_tracing()
[OUT]:
[1, 2, 3]
Chapter 27. Classes and Instances
Each instance is a dictionary with field values and a reference to its class. Read norm2 from the class’s method dictionary. Pass the instance as the this argument.
def ch27_instances() -> None:
def new(cls):
return {"class": cls, "fields": {}}
Point = {
"name": "Point",
"super": None,
"methods": {
"norm2": lambda this: this["fields"]["x"] ** 2 + this["fields"]["y"] ** 2,
},
}
p = new(Point)
p["fields"]["x"] = 3
p["fields"]["y"] = 4
print(p["class"]["methods"]["norm2"](p))
ch27_instances()
[OUT]:
25
Chapter 28. Methods and Initializers
Store a reference to instance o in the returned function. Change o["fields"]["x"] to 9. Then call the returned function. During this call, pass o as the method’s first argument. The result is 9.
def ch28_init_bind() -> None:
def bind(method, this):
return lambda *args: method(this, *args)
def new(cls, *args):
obj = {"class": cls, "fields": {}}
init = cls["methods"].get("init")
if init is not None:
bind(init, obj)(*args)
return obj
def getprop(obj, name):
if name in obj["fields"]:
return obj["fields"][name]
return bind(obj["class"]["methods"][name], obj)
C = {
"name": "C",
"super": None,
"methods": {
"init": lambda this, x: this["fields"].update({"x": x}),
"get": lambda this: this["fields"]["x"],
},
}
o = new(C, 7)
method = getprop(o, "get")
o["fields"]["x"] = 9
print(method())
assert method() == 9
ch28_init_bind()
[OUT]:
9
Chapter 29. Superclasses
For super.m in a method defined in B, search from B’s superclass. Use this starting class regardless of the receiver’s runtime class. Here, call lookup_method(B["super"], "m") to find the method in A.
def ch29_super_lookup() -> None:
def lookup_method(cls, name):
if name in cls["methods"]:
return cls["methods"][name]
if cls["super"] is not None:
return lookup_method(cls["super"], name)
raise KeyError(name)
def bind(method, this):
return lambda *args: method(this, *args)
def new(cls):
return {"class": cls, "fields": {}}
A = {
"name": "A",
"super": None,
"methods": {
"m": lambda this: "A",
},
}
B = {
"name": "B",
"super": A,
"methods": {
"m": lambda this: "B->" + lookup_method(B["super"], "m")(this),
},
}
b = new(B)
print(bind(lookup_method(B, "m"), b)())
ch29_super_lookup()
[OUT]:
B->A
Chapter 30. Optimization
Replace 1 + 2 * 3 with one literal. Evaluate the original AST and the modified AST. Make sure that the results are equal. In Chapter 30, study profiling, hash-table probing and NaN boxing.
def ch30_optimize_fold() -> None:
def ev(e):
match e:
case ("lit", v): return v
case ("+", a, b): return ev(a) + ev(b)
case ("*", a, b): return ev(a) * ev(b)
case _: raise ValueError(e)
def fold(e):
match e:
case ("+", a, b):
a, b = fold(a), fold(b)
return ("lit", ev(("+", a, b))) if a[0] == b[0] == "lit" else ("+", a, b)
case ("*", a, b):
a, b = fold(a), fold(b)
return ("lit", ev(("*", a, b))) if a[0] == b[0] == "lit" else ("*", a, b)
case _:
return e
expr = ("+", ("lit", 1), ("*", ("lit", 2), ("lit", 3)))
folded = fold(expr)
print("Before folding:")
print(expr)
print("After folding:")
print(folded)
print("Evaluation before and after:")
print("Original:", ev(expr))
print("Folded:", ev(folded))
ch30_optimize_fold()
[OUT]:
Before folding:
('+', ('lit', 1), ('*', ('lit', 2), ('lit', 3)))
After folding:
('lit', 7)
Evaluation before and after:
Original: 7
Folded: 7
End-to-End: Bytecode VM
Compile the AST to bytecode instructions. Execute the instructions on a stack VM with Python values. During compilation, assign an integer slot to each variable name. During execution, store and read each value at that index in globals_.
# Compile the AST to constants, instructions and variable slots.
def compile_to_bytecode(prog):
consts = []
code = []
slots = {} # name -> int
# Assign one slot per variable name.
def slot(name):
if name not in slots: slots[name] = len(slots)
return slots[name]
# Append an instruction and return its index.
def emit(*ins): code.append(tuple(ins)); return len(code) - 1
# Replace a jump placeholder with the target instruction index.
def patch(at, target):
op, _ = code[at]
code[at] = (op, target)
# Add a literal to consts and emit CONST with its index.
def cconst(v):
consts.append(v)
emit("CONST", len(consts) - 1)
# Emit instructions that leave the expression value on the stack.
def cexpr(e):
match e:
case ("lit", v): cconst(v)
case ("var", n): emit("GET", slot(n))
case ("+", a, b): cexpr(a); cexpr(b); emit("ADD")
case ("-", a, b): cexpr(a); cexpr(b); emit("SUB")
case ("*", a, b): cexpr(a); cexpr(b); emit("MUL")
case ("neg", a): cexpr(a); emit("NEG")
case ("<", a, b): cexpr(a); cexpr(b); emit("LT")
case _: raise ValueError(e)
# Compile each statement in order.
def cblock(block):
for s in block: cstmt(s)
# Emit instructions for a declaration, assignment, print, branch or loop.
def cstmt(s):
match s:
case ("var", n, e):
cexpr(e); emit("SET", slot(n))
case ("set", n, e):
cexpr(e); emit("SET", slot(n))
case ("print", e):
cexpr(e); emit("PRINT")
case ("if", c, t, f):
cexpr(c)
jif = emit("JIF_FALSE", None)
cblock(t)
jmp = emit("JMP", None)
patch(jif, len(code))
cblock(f)
patch(jmp, len(code))
case ("while", c, b):
loop_start = len(code)
cexpr(c)
jif = emit("JIF_FALSE", None)
cblock(b)
emit("JMP", loop_start)
patch(jif, len(code))
case _: raise ValueError(s)
cblock(prog)
emit("HALT")
return consts, code, slots
# Execute the instructions and collect values from PRINT.
def run_vm(consts, code, slots):
stack = []
output = []
globals_ = [None] * len(slots)
ip = 0
while True:
op, *a = code[ip]; ip += 1
if op == "CONST":
stack.append(consts[a[0]])
elif op == "GET":
stack.append(globals_[a[0]])
elif op == "SET":
globals_[a[0]] = stack.pop()
elif op == "ADD":
b = stack.pop(); a0 = stack.pop()
if type(a0) != type(b): raise TypeError("no mixed +")
stack.append(a0 + b)
elif op in ["SUB", "MUL"]:
rhs = stack.pop(); lhs = stack.pop()
stack.append(lhs - rhs if op == "SUB" else lhs * rhs)
elif op == "NEG":
stack.append(-stack.pop())
elif op == "LT":
b = stack.pop(); a0 = stack.pop()
stack.append(a0 < b)
elif op == "JIF_FALSE":
cond = stack.pop()
if not cond: ip = a[0]
elif op == "JMP":
ip = a[0]
elif op == "PRINT":
output.append(stack.pop())
elif op == "HALT":
return output
else:
raise ValueError(op)
# Run the parsed program in both implementations and compare their output.
def compare_program(source):
program = parse_program(source)
interpreted = run_treewalk(program)
compiled = run_vm(*compile_to_bytecode(program))
print("Tree walk:", interpreted)
print("Bytecode VM:", compiled)
assert interpreted == compiled
print(*run_vm(*compile_to_bytecode(DEMO_PROG)))
[OUT]:
110