man python-in-c/tree-walker
lesson 5 of 33 · Reading source
A first evaluator: walking the tree
For four lessons minipy has read programs without running any of them. It
turns a file into tokens and the tokens into a syntax tree, the same tree
CPython’s ast module builds. This lesson makes it run that tree. The
simplest way is to walk it: a function looks at a node, works out the
values of the node’s children by calling itself on them, and combines the
results. That is a tree-walking evaluator, and by the end of the lesson
minipy file.py runs loops, conditions and print().
The code is minipy at tag lesson-05.1,
which is lesson-05 with one fix to the figure’s trace (below).
The evaluator is src/eval.c, 561 lines, and src/etrace.c draws its
steps for the figure below. make test runs 104 tests, 26 of them programs
in tests/run/ with their expected output. make compare-run runs those
programs with CPython too, and make fuzz-eval checks 3,000 random
expressions against CPython. Every terminal output below was recorded from
a run of the command shown with it.
A program, run
Here is the example for this lesson, examples/squares.py:
n = 2
while n > 0:
print(n * n)
n -= 1
$ ./minipy examples/squares.py
4
1
$ python3 examples/squares.py
4
1
The only values minipy has at this lesson are C integers, int64_t. There
are no strings, no lists, no functions, not even None: those need
objects, which are the next part of the course. Before writing the
evaluator I had to decide what happens where a 64-bit integer and a Python
int behave differently, and those decisions shape the code, so here they
are first.
Decisions about integers
Overflow. A Python int has no fixed size. 2 ** 100 is an int with 31
digits, and CPython gives each int as many digits as its value needs. It
does have a limit, but far beyond 64 bits: 1 << 2 ** 63 fails with
OverflowError: too many digits in integer. A C int64_t holds values from
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, and in C an
operation on signed integers whose result is outside that range is
undefined behaviour: the compiler may assume it never happens. minipy
checks before every operation that could overflow, and if the result
would not fit, it stops with an error:
$ ./minipy tests/run/err-overflow-add.py; python3 tests/run/err-overflow-add.py
9223372036854775807
tests/run/err-overflow-add.py:3:7: error: OverflowError: result does not fit in 64 bits
9223372036854775807
9223372036854775808
OverflowError is a real Python exception, but CPython does not raise it
for results of this size; it is the nearest name for what minipy does. Lesson 8 replaces
int64_t with integers of any size, and the error goes away. A literal
that does not fit, like 9223372036854775808, is refused before the
program runs.
Division by zero is a ZeroDivisionError with CPython’s message,
division by zero, for both // and %. 0 ** -1 gives CPython’s
zero to a negative power, and a negative shift count its ValueError: negative shift count.
Results that would be floats are refused. 7 / 2 is 3.5 in Python,
and 2 ** -1 is 0.5. minipy has no floats until lesson 8, so / is
refused before the program runs, and a negative power stops it when it
is reached.
Bools are ints. In Python, True and False are the ints 1 and 0 with
a type of their own, bool, which prints them by name. minipy has no
types yet, so True is 1, 2 > 1 is 1, and that is how they print:
$ cat tests/run/bools.py; ./minipy tests/run/bools.py; python3 tests/run/bools.py
print(True, False, 2 > 1, not 0, True + True)
1 0 1 1 2
True False True True 2
Arithmetic gives the same results, since bool is a subclass of int in
CPython and True + True is 2 there too. Only printing differs. CPython
prints a bool through bool_repr(), a function attached to the type
(boolobject.c#L11-L17):
/* We define bool_repr to return "False" or "True" */
static PyObject *
bool_repr(PyObject *self)
{
return self == Py_True ? &_Py_ID(True) : &_Py_ID(False);
}
To call it, a value has to know its type. Giving it one is the subject of the next lesson.
Two functions and a switch
The evaluator is two mutually recursive functions. exec_stmt() runs a
statement and eval() computes the value of an expression. Each is a
switch on the node’s kind, like ast_dump() in lesson 2; the switches
themselves are in exec_inner() and eval_inner(), which exec_stmt()
and eval() wrap to report each call to the trace. Here is part of the
expression side:
case Name_kind: {
Var *v = lookup(ev, e->v.Name.id);
if (!v)
return fail(ev, e->pos, "NameError: name '%s' is not defined", e->v.Name.id);
*out = v->value;
return true;
}
case BinOp_kind:
return eval(ev, e->v.BinOp.left, &a) && eval(ev, e->v.BinOp.right, &b) &&
binop(ev, e->pos, e->v.BinOp.op, a, b, out);
A BinOp evaluates its left child, then its right child, then hands both
values to binop(), which applies the operator. The result goes back
through out, and the return value says whether there was an error. An
error stops everything: each caller sees false and returns false in
turn, up to the top. Variables are a list of names and values, searched
from the start; CPython keeps a module’s variables in a dict, and minipy
will have dicts in lesson 11.
Comparisons follow Python’s rule for chains: a < b < c means a < b and b < c, with b evaluated once, and the chain stops at the first
comparison that fails:
case Compare_kind:
/* a < b < c is a < b and b < c, with b evaluated once. */
if (!eval(ev, e->v.Compare.left, &a))
return false;
for (int i = 0; i < e->v.Compare.ops.n; i++) {
if (!eval(ev, e->v.Compare.comparators.items[i], &b))
return false;
if (!compare(e->v.Compare.ops.items[i], a, b)) {
*out = 0;
return true;
}
a = b;
}
*out = 1;
return true;
Statements need one thing expressions do not: a way to leave a loop in the
middle. exec_stmt() returns a Flow, which is FLOW_NEXT normally,
FLOW_BREAK or FLOW_CONTINUE after those statements, and FLOW_ERROR.
exec_body() runs a block’s statements in order and stops at the first
one that does not return FLOW_NEXT, passing its Flow up to the loop
that can act on it:
case While_kind:
for (;;) {
if (!eval(ev, s->v.While.test, &v))
return FLOW_ERROR;
step(ev, (EStep){ .kind = ESTEP_BRANCH, .stmt = s, .value = v });
if (!v) /* the loop ended without break: run the else part */
return exec_body(ev, s->v.While.orelse);
Flow f = exec_body(ev, s->v.While.body);
if (f == FLOW_BREAK)
return FLOW_NEXT;
if (f == FLOW_ERROR)
return FLOW_ERROR;
}
step() reports to the trace and does nothing otherwise. A break ends
the loop, and the while statement itself then finishes normally. A
continue needs no case of its own: it ends the body early, and the for
goes back to the test. The else part runs only when the test turns false,
so a break skips it, as in Python.
The figure steps through examples/squares.py. The top rows are the
program, with the line being run marked, and the calls to exec_stmt() and
eval() that are running. Below them are the variables and what has been
printed. At the bottom is the statement being run, as a tree with the
statement at the root, and the value of each node beside it once eval()
has computed it.
minipy's evaluator running a four-line program that prints n * n while n counts down from 2: frame by frame, the program with the current line marked, the exec_stmt() and eval() calls running, the variables and printed lines, and the tree of the current statement with each node's value as it is computed. (This figure steps through a recorded run; it needs JavaScript.)
Recorded with minipy --trace-eval examples/squares.py at tag
lesson-05.1, which fixes a trace bug in lesson-05: on the second pass
through the loop it still showed the first pass’s values. make test
checks that the trace still comes out identical
(tests/traces/squares.eval.json).
Frames 9 to 13 are the first print(n * n). The calls row grows to four,
exec_stmt(While), exec_stmt(Expr), eval(BinOp *), eval(Name n), and
the tree fills in from the leaves: both Name n nodes get their value,
then the BinOp, and only then does print() write. That order, children
before parents, is what walking the tree means. It is also why the C stack
grows with the depth of the expression: each nested operator is one more
eval() call waiting for its children.
Arithmetic that C does differently
Python’s // rounds the quotient down, toward minus infinity. C’s /
rounds it toward zero. They agree when both operands have the same sign
and differ when they do not: in Python -7 // 2 is -4, in C -7 / 2 is
-3. The remainder follows the quotient, so Python’s % takes the sign of
the divisor (-7 % 3 is 2) and C’s the sign of the dividend (-1). Here is
how binop() gets Python’s answers from C’s operators:
case FloorDiv:
case Mod:
if (b == 0)
return fail(ev, pos, "ZeroDivisionError: division by zero");
if (b == -1) { /* INT64_MIN / -1 overflows in C */
if (op == Mod) {
*out = 0;
return true;
}
if (a == INT64_MIN)
return overflow(ev, pos);
*out = -a;
return true;
}
/* C rounds the quotient toward zero; Python rounds it down, and
gives the remainder the sign of the divisor. */
r = a % b;
if (op == Mod) {
*out = r != 0 && (r < 0) != (b < 0) ? r + b : r;
} else {
*out = a / b - (r != 0 && (r < 0) != (b < 0));
}
return true;
When the division is not exact and the remainder’s sign differs from the
divisor’s, C’s quotient is one too high and its remainder is off by one
divisor; the fix subtracts one and adds b. b == -1 is a special case
because INT64_MIN / -1 would be , one more than the
largest int64_t, and in C even INT64_MIN % -1 is undefined for that
reason. >> has a similar problem: Python rounds -5 >> 1 down to -3,
while C leaves the result of shifting a negative number right to the
compiler, so binop() shifts -1 - a, which is not negative, and turns
the result back. << of a negative number is undefined in C, so minipy
multiplies by a power of two instead, after checking that the product fits.
The overflow checks come before the operation, because after it is too late. For addition:
case Add:
if ((b > 0 && a > INT64_MAX - b) || (b < 0 && a < INT64_MIN - b))
return overflow(ev, pos);
*out = a + b;
return true;
INT64_MAX - b cannot overflow when b is positive, so the test itself is
safe. What does going without it cost? In a scratch copy of lesson-05
with those two lines deleted, the optimized build carried on with a wrong
answer, and the sanitizer build stopped:
$ ./minipy tests/run/err-overflow-add.py
9223372036854775807
-9223372036854775808
$ ./minipy-asan tests/run/err-overflow-add.py > /dev/null; echo "exit status $?"
src/eval.c:257:18: runtime error: signed integer overflow: 9223372036854775807 + 1 cannot be represented in type 'int64_t' (aka 'long long')
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior src/eval.c:257:18
bash: line 1: 35242 Abort trap: 6 ./minipy-asan tests/run/err-overflow-add.py > /dev/null
exit status 134
The wrap to a negative number is one possible result of undefined
behaviour, the one this compiler produced here, not something C promises.
make check runs every test with that sanitizer build, and as of this
lesson the Makefile passes -fno-sanitize-recover=undefined, so that
undefined behaviour stops the program and fails the test instead of
printing a warning that nobody reads.
tests/run/arithmetic.py covers the cases above with both signs, and
gives the same output as CPython:
$ cat tests/run/arithmetic.py; ./minipy tests/run/arithmetic.py
# Floor division and remainder round down, unlike C's / and %.
print(7 // 2, -7 // 2, 7 // -2, -7 // -2)
print(7 % 3, -7 % 3, 7 % -3, -7 % -3)
print(2 ** 10, (-2) ** 3, -2 ** 2, 3 ** 0, 0 ** 0)
print(2 ** 62, (-2) ** 63)
print(1 << 62, -1 << 63, 5 >> 1, -5 >> 1, -1 >> 100, 7 >> 64)
print(6 & 3, 6 | 3, 6 ^ 3, ~0, ~-1, -(-3), +4)
print(9223372036854775807, -9223372036854775807 - 1)
3 -4 -4 3
1 2 -2 -1
1024 -8 -4 1 1
4611686018427387904 -9223372036854775808
4611686018427387904 -9223372036854775808 2 -3 -1 0
2 7 5 -1 0 3 4
9223372036854775807 -9223372036854775808
$ diff <(./minipy tests/run/arithmetic.py) <(python3 tests/run/arithmetic.py) && echo same
same
A few hand-picked cases are not much, so make fuzz-eval builds random
expressions from every operator the evaluator runs, comparisons, and,
or, not and conditionals, fully parenthesized so that only evaluation
is tested. A small reference evaluator in the script walks each one with
Python’s own ints and notes where minipy has to stop: a value past 64
bits, or a negative power. Everywhere else the reference must agree with
CPython’s eval(), and minipy must print the same value, or stop with the
same exception and message. Where minipy has to stop, it must stop with
its own error:
$ make -s fuzz-eval
seed 1: 1000 expressions: 884 values, 24 ZeroDivisionError, 9 ValueError, 76 past 64 bits, 7 negative powers; 0 differ
seed 2: 1000 expressions: 876 values, 34 ZeroDivisionError, 14 ValueError, 74 past 64 bits, 2 negative powers; 0 differ
seed 3: 1000 expressions: 884 values, 40 ZeroDivisionError, 8 ValueError, 62 past 64 bits, 6 negative powers; 0 differ
To check that it can fail, I changed % in a scratch copy to C’s plain
r: the first seed then reported 4 differences, among them
((~2) % (2 * 19)), which should be 35 and came out as -3.
Errors before and during a run
An error can stop a program in two ways. NameError, ZeroDivisionError
and the others above happen while it runs, and whatever was printed before
stays printed:
$ cat tests/run/err-zero-division.py; ./minipy tests/run/err-zero-division.py
x = 10
print(x)
print(x - 1, x // (x - 10))
print(x)
10
tests/run/err-zero-division.py:3:14: error: ZeroDivisionError: division by zero
$ python3 - < tests/run/err-zero-division.py
10
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
ZeroDivisionError: division by zero
Neither printed 9: print() evaluates all its arguments before it
writes anything, and so does minipy’s. The position minipy reports, column
14, is the start of the BinOp; CPython’s traceback names only the line
when it reads the program from stdin.
The other kind of error is found before anything runs. eval_check()
walks the whole tree first and refuses what the evaluator cannot run:
def, strings, calls other than print(), /, and so on. It also makes
three checks that CPython makes when it compiles, with CPython’s messages:
'break' outside loop, 'continue' not properly in loop and 'return' outside function. The parser accepts all three, as ast.parse does,
because they are about where a statement is, not how it is written. Since
the check covers the whole file, a program that fails it prints nothing,
the same as in CPython:
$ cat tests/run/err-break.py; ./minipy tests/run/err-break.py; python3 - < tests/run/err-break.py
print(1)
break
tests/run/err-break.py:2:1: error: 'break' outside loop
File "<stdin>", line 2
SyntaxError: 'break' outside loop
CPython reports it from codegen_break(), which looks for an enclosing
loop on its stack of blocks
(codegen.c#L2302-L2316):
static int
codegen_break(compiler *c, location loc)
{
fblockinfo *loop = NULL;
location origin_loc = loc;
/* Emit instruction with line number */
ADDOP(c, loc, NOP);
RETURN_IF_ERROR(codegen_unwind_fblock_stack(c, &loc, 0, &loop));
if (loop == NULL) {
return _PyCompile_Error(c, origin_loc, "'break' outside loop");
}
RETURN_IF_ERROR(codegen_unwind_fblock(c, &loc, loop, 0));
ADDOP_JUMP(c, loc, JUMP, loop->fb_exit);
return SUCCESS;
}
minipy’s version counts the loops it is inside while it walks the tree, which comes to the same thing.
How CPython runs the same program
CPython does not walk the tree to run it. It compiles the tree to
bytecode, a flat list of instructions for a stack machine, and a loop in
Python/ceval.c runs the instructions. The compiler is itself a tree
walker. Here is the start of its expression function
(codegen.c#L5407-L5426):
static int
codegen_visit_expr(compiler *c, expr_ty e)
{
if (Py_EnterRecursiveCall(" during compilation")) {
return ERROR;
}
location loc = LOC(e);
switch (e->kind) {
case NamedExpr_kind:
VISIT(c, expr, e->v.NamedExpr.value);
ADDOP_I(c, loc, COPY, 1);
VISIT(c, expr, e->v.NamedExpr.target);
break;
case BoolOp_kind:
return codegen_boolop(c, e);
case BinOp_kind:
VISIT(c, expr, e->v.BinOp.left);
VISIT(c, expr, e->v.BinOp.right);
ADDOP_BINARY(c, loc, e->v.BinOp.op);
break;
The BinOp case has the shape of minipy’s: left child, right child, then
the operator. VISIT(c, expr, ...) is a macro that calls
codegen_visit_expr() again
(codegen.c#L455-L456).
The difference is what each step produces. minipy’s eval() computes a
value and returns it; codegen_visit_expr() appends instructions that
will compute the value later, when they run. The walk happens once, when
the program is compiled, and a loop that runs a million times runs the
instructions a million times without visiting the tree again. dis prints
what the compiler made of examples/squares.py:
$ python3 -m dis examples/squares.py
0 RESUME 0
1 LOAD_SMALL_INT 2
STORE_NAME 0 (n)
2 L1: LOAD_NAME 0 (n)
LOAD_SMALL_INT 0
COMPARE_OP 148 (bool(>))
POP_JUMP_IF_FALSE 27 (to L2)
NOT_TAKEN
3 LOAD_NAME 1 (print)
PUSH_NULL
LOAD_NAME 0 (n)
LOAD_NAME 0 (n)
BINARY_OP 5 (*)
CALL 1
POP_TOP
4 LOAD_NAME 0 (n)
LOAD_SMALL_INT 1
BINARY_OP 23 (-=)
STORE_NAME 0 (n)
JUMP_BACKWARD 33 (to L1)
2 L2: LOAD_COMMON_CONSTANT 7 (None)
RETURN_VALUE
Line 3 is the tree of print(n * n) turned inside out. After print
itself is loaded, both ns are loaded, then BINARY_OP multiplies them,
then CALL calls: the children’s instructions come before their parent’s,
the order in which minipy’s eval() finishes the nodes. The while loop has become two jumps:
POP_JUMP_IF_FALSE leaves it, and JUMP_BACKWARD goes back to the test.
There is no Flow value: break and continue become jumps too. This is
where the course goes in its fourth part, from lesson 20; minipy’s
tree-walker comes first because it is the shortest way from a tree to a
running program.
CPython’s ints have the same rounding rule as minipy’s, applied to numbers
of any size. l_divmod() divides with truncation, then corrects the pair
if the remainder and the divisor have different signs
(longobject.c#L4523-L4541):
if (long_divrem(v, w, &div, &mod) < 0)
return -1;
if ((_PyLong_IsNegative(mod) && _PyLong_IsPositive(w)) ||
(_PyLong_IsPositive(mod) && _PyLong_IsNegative(w))) {
PyLongObject *temp;
temp = long_add(mod, w);
Py_SETREF(mod, temp);
if (mod == NULL) {
Py_DECREF(div);
return -1;
}
temp = long_sub(div, (PyLongObject *)_PyLong_GetOne());
if (temp == NULL) {
Py_DECREF(mod);
Py_DECREF(div);
return -1;
}
Py_SETREF(div, temp);
}
That is minipy’s r + b and - 1, with every intermediate result an
object that can fail to allocate. For operands of one internal digit,
long_div() takes a shorter path, fast_floor_div()
(longobject.c#L4398-L4418),
which works on the magnitudes and computes -1 - (left - 1) / right when
the signs differ. The “division by zero” message comes from
long_divrem() for // and from long_rem() for %, each of which
checks for a divisor with no digits
(longobject.c#L3223-L3226,
#L3285-L3289).
Digits are lesson 8.
Comparing with CPython
make compare-run runs every program in tests/run/ with both and
compares the output and, where there is an error, the exception, its
message and its line. Two parts of CPython’s messages are ignored: the
SyntaxError: in front of errors found before running, which minipy’s
parser has never printed, and the “Did you mean” suggestion CPython adds
to some NameErrors. The differences minipy makes on purpose are listed
in the script with their reasons:
$ make -s compare-run | grep -v "^ "
same tests/run/arithmetic.py
same tests/run/assign.py
expected tests/run/bools.py
same tests/run/collatz.py
same tests/run/compare.py
same tests/run/err-augassign-name.py
same tests/run/err-break.py
expected tests/run/err-call.py
expected tests/run/err-def.py
expected tests/run/err-literal.py
same tests/run/err-name.py
expected tests/run/err-negative-power.py
expected tests/run/err-overflow-add.py
expected tests/run/err-overflow-floordiv.py
expected tests/run/err-overflow-mul.py
expected tests/run/err-overflow-negate.py
expected tests/run/err-overflow-power.py
expected tests/run/err-overflow-shift.py
expected tests/run/err-print-value.py
same tests/run/err-return.py
same tests/run/err-shift.py
expected tests/run/err-string.py
expected tests/run/err-true-division.py
same tests/run/err-zero-division.py
same tests/run/err-zero-power.py
same tests/run/loops.py
12 same, 14 differ on purpose, 0 differ otherwise
The grep hides the detail lines. One of them in full:
$ make -s compare-run | grep -A4 err-overflow-mul
expected tests/run/err-overflow-mul.py
CPython stdout: '9223372037000250000'
minipy stdout: ''
CPython: no error
minipy: OverflowError: result does not fit in 64 bits
Where minipy differs
- Ints are 64-bit. A result outside the range stops the program with
an
OverflowErrorthat CPython would not raise, and a literal outside it is refused before running. - No bools.
True,False, comparisons andnotgive 1 and 0, and print that way.~Trueis -2 in both, but only CPython 3.15 warns that~on a bool is deprecated. - No floats:
/is refused, and a negative power stops the program. print()is the only call, and only as a statement of its own: its value would beNone, which minipy does not have.- Assignment is to names only: no
a, b = b, a, which needs tuples. - Errors name the exception and print
file:line:column, with the column of the node; CPython prints a traceback. - Running is a walk over the tree each time a statement runs. CPython compiles the tree to bytecode once and runs that.
Try it yourself
Check out lesson-05.1 and keep make test, make check and
make compare-run passing.
The smallest int.
print(-9223372036854775808)prints that number in CPython. What does minipy say, and why, when the value fits in anint64_t?Answer
minipy stops before running with “this int does not fit in 64 bits” at column 8, the first digit. The tree is
UnaryOp(op=USub(), operand=Constant(value=9223372036854775808)): the minus is an operator applied to the literal, and the literal alone is , one too many. CPython’s ints are not limited to 64 bits, and its compiler even folds the minus into a single constant when it optimizes the bytecode (fold_const_unaryop()in flowgraph.c#L2035):disshows oneLOAD_CONSTof -9223372036854775808 forx = -9223372036854775808.-9223372036854775807 - 1, as intests/run/arithmetic.py, works in both.Short circuits. What does
print(0 and 1 // 0, 1 or 1 // 0)print?Answer
0 1in both minipy and CPython, with no error.andstops at the first false operand andorat the first true one, so neither1 // 0is evaluated: the loop in theBoolOpcase returns before it reaches them.Which loop? A
breakin theelsepart of an innerwhile: which loop does it leave? Work it out fromexec_inner(), then run this in both interpreters:i = 0 while i < 3: i += 1 j = 0 while j < 1: j += 1 else: break print(i, j)Answer
The outer one; both print
1 1. The inner loop’s test turns false, so itsWhilecase returnsexec_body()of theelsepart, which returnsFLOW_BREAK. The innerWhilepasses that up unchanged, and the outer loop’sexec_body()returns it to the outerWhile, which acts on it.eval_check()agrees: it checks theelsepart with the loop count of the code around the inner loop, not the count inside it.C’s remainder. In C,
-7 / 3is -2 and-7 % 3is -1. Followbinop()to Python’s answers.Answer
ris -1: not zero, and negative whilebis positive. So//gives-2 - 1 = -3, and%gives-1 + 3 = 2. Python’s-7 // 3is -3 and-7 % 3is 2, the second line oftests/run/arithmetic.py.Squaring too early? The
**loop squaresawhile bits of the exponent remain. Can that square overflow when the final result would fit?Answer
No.
ais squared only whenbis still positive after the shift, so at least one more bit is set, and the result will be multiplied by a positive power of the newa, so the final result is at leasta * ain magnitude. Ifa * ais more thanINT64_MAX, the result could then fit only as exactly . Then every number involved is a power of two in magnitude,aamong them: say . Its square is more than , so , and the result is at least in magnitude, too large after all.(-2) ** 63, where the squares stay small, is intests/run/arithmetic.py, andmake fuzz-evalfound no case where minipy stops while CPython’s value fits.
Sources
minipy, tag lesson-05.1:
src/eval.c, src/eval.h, src/etrace.c, tests/run/,
tests/compare-run.py, tests/fuzz-eval.py. Built with cc (Apple clang
21.0.0) on macOS; the outputs above were recorded with that build and
Python 3.15.2.
CPython v3.15.2:
- Objects/boolobject.c#L11-L17
bool_repr - Python/codegen.c#L455-L456 the
VISITmacro - Python/codegen.c#L2302-L2316
codegen_break - Python/codegen.c#L5407-L5426
codegen_visit_expr - Python/flowgraph.c#L2035
fold_const_unaryop - Objects/longobject.c#L3223-L3226 “division by zero” in
long_divrem - Objects/longobject.c#L3285-L3289 “division by zero” in
long_rem - Objects/longobject.c#L4398-L4418
fast_floor_div - Objects/longobject.c#L4523-L4541 the sign correction in
l_divmod
ls python-in-c/
Reading source
- 01 Tokens, and how Python counts indentation draftSource text to tokens, and the indentation stack that turns leading spaces into INDENT and DEDENT.
- 02 Parsing expressions by precedence climbing draftRecursive descent for operators of different strengths, and the first AST nodes as tagged unions in C.
- 03 Statements and blocks draftParsing assignment, if, while and def, with INDENT and DEDENT standing where other languages put braces.
- 04 How CPython parses: a PEG grammar draftSince 3.9 CPython's parser is generated from Grammar/python.gram. What a PEG parser does that ours does not.
- 05 A first evaluator: walking the tree draftRun the AST directly, with C integers as the only values: enough for loops, conditions and print.
Objects
- 06 Everything is an object draftThe object header, a reference count and a type pointer, and why a type is an object too.
- 07 Operators through type slots draftHow a + b finds the code to run: function pointers on the type, like CPython's tp_ and nb_ slots.
- 08 Integers of any size, and floats plannedInts as arrays of digits (30 bits each in CPython's default build), and floats as C doubles.
- 09 Strings plannedImmutable text with a cached hash, and CPython's choice of one, two or four bytes per character.
- 10 Lists and tuples plannedA growable array that over-allocates, and a fixed one.
- 11 Dicts: a hash table that keeps order plannedOpen addressing over a small index table and a dense array of entries, the layout CPython has used since 3.6.
- 12 The evaluator, on objects plannedThe tree-walker again, now with every value a pointer to an object.
Memory
- 13 Reference counting plannedWho owns a reference, when to increment, when to decrement, and what happens at zero.
- 14 Finding reference counting bugs plannedLeaks and use-after-free, caught by a debug mode that counts live references and by AddressSanitizer.
- 15 What reference counting cannot free plannedA list that contains itself, and why its count never reaches zero.
- 16 A cycle collector plannedFind unreachable cycles by subtracting the references objects hold to each other, as CPython's gc does with gc_refs.
- 17 Generations plannedCollect young objects often and old ones rarely. CPython 3.14.0 to 3.14.4 shipped an incremental collector; 3.14.5 and 3.15 went back to generations.
- 18 Small ints, interning and immortal objects plannedObjects made once and shared: CPython 3.15 preallocates the ints from -5 to 1024, interns strings, and since 3.12 has objects it never counts.
- 19 A small-object allocator plannedPools and arenas for the many small blocks an interpreter asks for, after CPython's obmalloc.
Bytecode
- 20 From trees to bytecode plannedWhy interpreters compile to a flat list of instructions, and the instruction set of a stack machine.
- 21 The compiler plannedExpressions, assignments, jumps for if and while, and a code object to hold the result.
- 22 The evaluation loop plannedA loop over instructions with a value stack. CPython generates its loop from Python/bytecodes.c.
- 23 Functions, frames and calls plannedA frame per call, arguments on the stack, and returning a value.
- 24 Scopes: locals, globals, builtins plannedA symbol table decides where each name lives before any code runs.
- 25 Closures and cells plannedVariables that outlive the call that made them.
- 26 Exceptions plannedRaising and unwinding, and the exception table CPython has used since 3.11, which costs nothing until something is raised.
- 27 Generators plannedA frame that stops in the middle and resumes: yield, send and the generator object.
- 28 Classes and instances plannedA class is an object that makes objects. minipy keeps instance attributes in a dict; CPython does something more compact.
- 29 Attribute lookup plannedThe method resolution order, descriptors and bound methods: what obj.name does.
The C boundary and speed
- 30 The C API boundary plannedBuiltin functions written in C, and what CPython's C API promises extension modules.
- 31 Dispatch: switch, computed gotos, tail calls plannedHow the loop gets to the next instruction. CPython uses computed gotos where the compiler allows, and 3.14 added an opt-in tail-calling interpreter.
- 32 Inline caches and specialization plannedRewriting instructions at run time for the types they meet, as CPython has done since 3.11, in a small version for minipy.
- 33 minipy against CPython plannedMeasuring both on the same programs, and what accounts for the difference.