man python-in-c/statements
lesson 3 of 33 · Reading source
Statements and blocks
At the end of the last lesson minipy could parse one expression per line. A
program is more than that: assignments, loops, functions, and blocks of
statements inside other statements. In C a block is delimited by { and
}. In Python it is delimited by indentation, and lesson 1 already turned
indentation into tokens: an INDENT where a line goes deeper, a DEDENT
for each level it comes back out. This lesson is about the parser that reads
those tokens as the braces they are.
The code is minipy at tag lesson-03.
The statement parser is the second half of src/parser.c, now 1,386 lines.
make test runs 76 tests, and make fuzz-ast now also generates 3,000
random programs. Every terminal output below was recorded from a run of
the command shown with it.
A program as tokens
Here is the example for this lesson, examples/countdown.py:
def countdown(n):
while n > 0:
n -= 1
if n == 2:
break
return n
And here is what the tokenizer hands the parser:
$ ./minipy --tokens examples/countdown.py
1,0-1,3: NAME 'def'
1,4-1,13: NAME 'countdown'
1,13-1,14: LPAR '('
1,14-1,15: NAME 'n'
1,15-1,16: RPAR ')'
1,16-1,17: COLON ':'
1,17-1,18: NEWLINE '\n'
2,0-2,4: INDENT ' '
2,4-2,9: NAME 'while'
2,10-2,11: NAME 'n'
2,12-2,13: GREATER '>'
2,14-2,15: NUMBER '0'
2,15-2,16: COLON ':'
2,16-2,17: NEWLINE '\n'
3,0-3,8: INDENT ' '
3,8-3,9: NAME 'n'
3,10-3,12: MINEQUAL '-='
3,13-3,14: NUMBER '1'
3,14-3,15: NEWLINE '\n'
4,8-4,10: NAME 'if'
4,11-4,12: NAME 'n'
4,13-4,15: EQEQUAL '=='
4,16-4,17: NUMBER '2'
4,17-4,18: COLON ':'
4,18-4,19: NEWLINE '\n'
5,0-5,12: INDENT ' '
5,12-5,17: NAME 'break'
5,17-5,18: NEWLINE '\n'
6,4-6,4: DEDENT ''
6,4-6,4: DEDENT ''
6,4-6,10: NAME 'return'
6,11-6,12: NAME 'n'
6,12-6,13: NEWLINE '\n'
7,0-7,0: DEDENT ''
7,0-7,0: ENDMARKER ''
Read only the NEWLINE, INDENT and DEDENT lines and the structure is
all there. Each INDENT opens a block and each DEDENT closes one. The line
return n goes from column 12 back to column 4, past two open blocks, so it
gets two DEDENTs, and the end of the file closes the last block with a
third. Every INDENT has its DEDENT, as every { has its }. That work
is done before the parser starts: the parser never looks at a column.
Statement nodes
The tree minipy builds from that file:
$ ./minipy --ast examples/countdown.py
Module(
body=[
FunctionDef(
name='countdown',
args=arguments(
args=[
arg(arg='n')]),
body=[
While(
test=Compare(
left=Name(id='n'),
ops=[
Gt()],
comparators=[
Constant(value=0)]),
body=[
AugAssign(
target=Name(id='n', ctx=Store()),
op=Sub(),
value=Constant(value=1)),
If(
test=Compare(
left=Name(id='n'),
ops=[
Eq()],
comparators=[
Constant(value=2)]),
body=[
Break()])]),
Return(
value=Name(id='n'))])])
It is the same as CPython’s:
$ python3 -c 'import ast, sys; print(ast.dump(ast.parse(open(sys.argv[1]).read()), indent=2))' examples/countdown.py | diff - <(./minipy --ast examples/countdown.py) && echo same
same
A block is a list of statements: body in FunctionDef, While and If,
and orelse for an else part. There is no node for the block itself and
none for the indentation. elif has no node either: it is an If inside
the orelse of the If before it. Statements are a second tagged union
next to the expressions, in src/ast.h:
struct Stmt {
StmtKind kind;
union {
struct { const char *name; Arguments *args; StmtList body; } FunctionDef;
struct { Expr *value; } Return; /* value may be NULL */
struct { ExprList targets; Expr *value; } Assign; /* a = b = value */
struct { Expr *target; Operator op; Expr *value; } AugAssign;
struct { Expr *test; StmtList body, orelse; } While;
struct { Expr *test; StmtList body, orelse; } If; /* elif: an If in orelse */
struct { Expr *value; } Expr;
} v; /* Pass, Break, Continue: nothing */
Pos pos;
};
CPython’s statement node, struct _stmt, is generated from the stmt
lines of
Python.asdl#L11-L56
into
pycore_ast.h#L187-L359,
with 28 kinds where minipy has 10. Its FunctionDef also has decorators, a
return annotation, a type comment and type parameters, which minipy does not
parse, and its arguments has room for *args, keyword-only parameters and
**kwargs.
The grammar of blocks
CPython’s grammar for statements fits in a few rules (python.gram#L97-L103, #L115-L117, #L266-L269):
statements[asdl_stmt_seq*]: a=statement+ { (asdl_stmt_seq*)_PyPegen_seq_flatten(p, a) }
statement[asdl_stmt_seq*]:
| a=compound_stmt { _PyPegen_register_stmts(p ,
(asdl_stmt_seq*)_PyPegen_singleton_seq(p, a)
) }
| a[asdl_stmt_seq*]=simple_stmts { a }
simple_stmts[asdl_stmt_seq*]:
| a=simple_stmt !';' NEWLINE { (asdl_stmt_seq*)_PyPegen_singleton_seq(p, a) } # Not needed, there for speedup
| a[asdl_stmt_seq*]=';'.simple_stmt+ [';'] NEWLINE { a }
block[asdl_stmt_seq*] (memo):
| NEWLINE INDENT a=statements DEDENT { a }
| simple_stmts
| invalid_block
A statement is either compound (def, if, while and the others that end
in a block) or a line of simple statements separated by ;. A block is
either a NEWLINE, an INDENT, one or more statements and a DEDENT, or
simple statements on the header’s own line, as in if x: y = 1. The braces
of C are the INDENT and DEDENT of the first alternative. Because the
rule says statements, one or more, a block cannot be empty, which is why
Python has pass.
minipy’s block() is that rule written out:
static bool block(Parser *p, const char *after, int line, StmtList *out)
{
rule(p, "block");
Vec body = { 0 };
if (at(p, TOK_NEWLINE)) {
layout(p);
if (!at(p, TOK_INDENT)) {
error_at_token(p, &p->tok, "expected an indented block after %s on line %d",
after, line);
return false;
}
layout(p);
while (!at(p, TOK_DEDENT))
if (!statement(p, &body)) {
free(body.items);
return false;
}
layout(p);
} else if (!simple_stmts(p, &body)) {
free(body.items);
return false;
}
*out = vec_stmts(p, &body);
rule_end(p, "block");
return true;
}
layout() consumes a NEWLINE, INDENT or DEDENT and tells the trace;
rule() and rule_end() only tell the trace. The loop while (!at(p, TOK_DEDENT)) is all there is to block structure: statements until the
token that closes the block. A nested block is a statement whose parsing
calls block() again, so the C call stack holds one block() for every
open INDENT.
if_stmt(), while_stmt() and function_def() are each a header followed
by block(). Here is the parser going through the example. The top rows
are the source lines, with each line’s INDENT and DEDENT tokens in a
column on the left and its NEWLINE after it; below them, the functions
running (file() is parse_module(), under the name of CPython’s start
rule); at the bottom, the statements built that no block has collected
yet.
minipy's statement parser on the countdown function: frame by frame, the source lines with their INDENT, DEDENT and NEWLINE tokens, the running calls from file() down through function_def(), block(), while_stmt() and if_stmt(), and the statements built so far, which end as one FunctionDef holding a While and a Return. (This figure steps through a recorded run; it needs JavaScript.)
Recorded with minipy --trace-stmt examples/countdown.py at tag
lesson-03; make test checks that the trace still comes out identical
(tests/traces/countdown.stmt.json).
Two things in the figure are worth stepping back and forth over. In frames
13 to 16 the two DEDENTs before return n each end one block(): the
first returns the if’s body, and if_stmt() builds the If; the second
returns the loop’s body, and while_stmt() builds the While with the
AugAssign and the If in it. And the statements of a block pile up in the
bottom row until the DEDENT, then disappear into their parent. That is
also when a compound statement is built: only after its whole block has
been read.
Targets
An assignment starts like an expression. In a.b[i], c = f(x) the parser
cannot know it is reading a target until it reaches the =, and by then it
has read the whole of a.b[i], c. minipy does the simple thing: it parses
an expression, and if an = follows, it checks that what it parsed can be
assigned to and marks it as a target. In CPython’s tree a target has
ctx=Store(), which ast.dump prints (it leaves out only Load()):
$ python3 -c 'import ast; print(ast.dump(ast.parse("a.b[i], c = f(x)").body[0]))'
Assign(targets=[Tuple(elts=[Subscript(value=Attribute(value=Name(id='a'), attr='b'), slice=Name(id='i'), ctx=Store()), Name(id='c', ctx=Store())], ctx=Store())], value=Call(func=Name(id='f'), args=[Name(id='x')]))
The tuple and its two elements are Store, but a.b inside the subscript
is not: to assign to a.b[i] Python reads a.b and i, and stores only
into the subscript. A name, an attribute and a subscript can be assigned to;
a tuple or a list can if all its elements can. Anything else is an error,
and the check finds the first part that is wrong:
static Expr *invalid_target(Expr *e)
{
switch (e->kind) {
case Name_kind: case Attribute_kind: case Subscript_kind:
return NULL;
case List_kind: case Tuple_kind: {
ExprList l = e->kind == List_kind ? e->v.List.elts : e->v.Tuple.elts;
for (int i = 0; i < l.n; i++) {
Expr *bad = invalid_target(l.items[i]);
if (bad)
return bad;
}
return NULL;
}
default:
return e;
}
}
assignment() loops over the = signs, so a = b = 1 has two targets and
one value, as in CPython’s Assign:
static Stmt *assignment(Parser *p, Token start, Expr *first)
{
Vec targets = { 0 };
Expr *e = first;
while (at(p, TOK_EQUAL)) {
Expr *bad = invalid_target(e);
if (bad) {
free(targets.items);
return error_at(p, bad->pos.lineno, bad->pos.col_offset,
"cannot assign to %s", expr_name(bad));
}
set_store(e);
vec_push(&targets, e);
advance(p);
e = star_expressions(p);
if (!e) {
free(targets.items);
return NULL;
}
}
Stmt *s = new_stmt(p, Assign_kind, start);
s->v.Assign.targets = vec_exprs(p, &targets);
s->v.Assign.value = e;
return s;
}
set_store() walks the target and sets ctx to Store on the name,
attribute or subscript, and on every tuple and list down to them. An
augmented assignment like n -= 1 takes exactly one target, and only a
name, an attribute or a subscript.
CPython does this differently. Its grammar has separate rules for targets, and the assignment rule tries them first (python.gram#L162-L165):
| a[asdl_expr_seq*]=(z=star_targets '=' { z })+ b=annotated_rhs !'=' tc=[TYPE_COMMENT] {
_PyAST_Assign(a, b, NEW_TYPE_COMMENT(p, tc), EXTRA) }
| a=single_target b=augassign ~ c=annotated_rhs {
_PyAST_AugAssign(a, b->kind, c, EXTRA) }
star_targets builds nodes with Store from the start
(python.gram#L1118-L1142).
If no = follows, the parser goes back to the start of the line and tries
the next alternative, an expression statement. It can go back because it
keeps every token it has read; how it avoids paying twice for the same work
is in the next lesson. The checks minipy makes are CPython’s too, but
CPython makes them only after the parse has failed, in its error rules:
invalid_target() is _PyPegen_get_invalid_target
(action_helpers.c#L1215-L1270),
and expr_name() copies the words of _PyPegen_get_expr_name
(#L1084-L1159).
Where a statement ends
Every statement records its position, and for the compound ones the end
is not obvious. A While ends where the last statement of its body ends,
not at the DEDENT after it, and in if x: pass; the If ends after the
;. CPython computes the end of every node from the last token consumed,
skipping NEWLINE, INDENT and DEDENT
(pegen.c#L480-L492).
minipy’s advance() does the same: it does not move the end position for
those three token types. make compare-ast checks every position against
ast.dump(..., include_attributes=True).
Errors
A parser that only accepts valid programs is half done. CPython’s messages for broken statements come from its error rules, and minipy reproduces the common ones:
$ for f in tests/parse/err-{expected-colon,indented-block,invalid-target,augassign-target}.py; do cat $f; ./minipy --ast $f; done
if x
pass
tests/parse/err-expected-colon.py:1:5: error: expected ':'
while x:
y = 1
tests/parse/err-indented-block.py:2:1: error: expected an indented block after 'while' statement on line 1
x, f() = 1, 2
tests/parse/err-invalid-target.py:1:4: error: cannot assign to function call
a, b += 1
tests/parse/err-augassign-target.py:1:1: error: 'tuple' is an illegal expression for augmented assignment
Where each message is placed follows a rule in CPython, and getting the
column right means following it. “expected ‘:’” after if x comes from a
rule that matches the condition followed directly by NEWLINE
(python.gram#L1531-L1534),
and is reported at the last token read, the NEWLINE. After else the
grammar writes &&':', a token that must be there
(python.gram#L396-L398),
and so does the error rule for def
(#L1554),
and if it is not, the message is reported at whatever token is
(pegen.c#L435-L454):
else x: pass fails at the x.
The missing block is reported at the token after the NEWLINE. That token
can be one without a column. CPython’s INDENT, DEDENT and ENDMARKER
have none, and an error at one of them is placed where the tokenizer
stopped reading
(pegen_errors.c#L215-L229).
For an if on the last line of a file, that is just past the end of
that line.
minipy’s token_location() reproduces this. The same rule moves one error
from lesson 1. There, “unindent does not match any outer indentation level”
was reported at the start of the offending line, and CPython just past its
end. As a parser error, minipy now reports it where CPython does; --tokens
still prints lesson 1’s column. Comparing these cases with CPython:
$ make -s compare-ast | grep -A2 -E 'err-(assignment|def-paren|else-colon|expected-colon|indented-block|unindent)'
error tests/parse/err-assignment.py
minipy: tests/parse/err-assignment.py:1:1: error: cannot assign to function call
CPython: tests/parse/err-assignment.py:1:1: SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='?
error tests/parse/err-augassign-target.py
minipy: tests/parse/err-augassign-target.py:1:1: error: 'tuple' is an illegal expression for augmented assignment
--
error tests/parse/err-def-paren.py
minipy: tests/parse/err-def-paren.py:1:6: error: expected '('
CPython: tests/parse/err-def-paren.py:1:6: SyntaxError: expected '('
error tests/parse/err-default-order.py
minipy: tests/parse/err-default-order.py:1:12: error: parameter without a default follows parameter with a default
--
error tests/parse/err-else-colon.py
minipy: tests/parse/err-else-colon.py:2:6: error: expected ':'
CPython: tests/parse/err-else-colon.py:2:6: SyntaxError: expected ':'
error tests/parse/err-empty-subscript.py
minipy: tests/parse/err-empty-subscript.py:1:3: error: invalid syntax
--
error tests/parse/err-expected-colon.py
minipy: tests/parse/err-expected-colon.py:1:5: error: expected ':'
CPython: tests/parse/err-expected-colon.py:1:5: SyntaxError: expected ':'
error tests/parse/err-for.py
minipy: tests/parse/err-for.py:1:1: error: 'for' statements are not supported
--
error tests/parse/err-indented-block-eof.py
minipy: tests/parse/err-indented-block-eof.py:2:10: error: expected an indented block after 'if' statement on line 2
CPython: tests/parse/err-indented-block-eof.py:2:10: IndentationError: expected an indented block after 'if' statement on line 2
error tests/parse/err-indented-block.py
minipy: tests/parse/err-indented-block.py:2:1: error: expected an indented block after 'while' statement on line 1
CPython: tests/parse/err-indented-block.py:2:1: IndentationError: expected an indented block after 'while' statement on line 1
error tests/parse/err-invalid-target.py
minipy: tests/parse/err-invalid-target.py:1:4: error: cannot assign to function call
--
error tests/parse/err-unindent.py
minipy: tests/parse/err-unindent.py:3:8: error: unindent does not match any outer indentation level
CPython: tests/parse/err-unindent.py:3:8: IndentationError: unindent does not match any outer indentation level
same tests/parse/precedence.py
same tests/parse/primary.py
(grep -A2 cuts some entries after two lines.) The first case differs. For
f() = 1 CPython adds “here. Maybe you meant ‘==’ instead of ‘=’?”, from a
rule that guesses the = was meant as a comparison
(python.gram#L1287-L1295).
Whether that rule fires depends on which rules CPython’s second pass tries
at that point of the line, and minipy, which has no second pass, does not
imitate it.
Comparing with CPython
make fuzz-ast now has two more kinds of input. “Programs” are random
statements with blocks: assignments to random targets, augmented
assignments, if/elif/else, while/else, def with defaults, nested
at random indentation, with comments, blank lines, semicolons and one-line
blocks. Both parsers must accept them with the same tree, positions
included. “Line soups” are random lines of statement keywords, targets,
=, : and brackets, indented at random, almost never valid:
$ make -s fuzz-ast
seed 1: 1000 expressions, 1000 same, 0 differ
1000 soups: 50 accepted by both or by one, 0 differ, 0 not supported by minipy;
950 rejected by both, 874 at the same place, 845 also with the same message
1000 programs, 1000 same, 0 differ
1000 line soups: 12 accepted by both or by one, 0 differ, 0 not supported by minipy;
988 rejected by both, 968 at the same place, 963 also with the same message
seed 2: 1000 expressions, 1000 same, 0 differ
1000 soups: 35 accepted by both or by one, 0 differ, 0 not supported by minipy;
965 rejected by both, 893 at the same place, 868 also with the same message
1000 programs, 1000 same, 0 differ
1000 line soups: 11 accepted by both or by one, 0 differ, 0 not supported by minipy;
989 rejected by both, 971 at the same place, 970 also with the same message
seed 3: 1000 expressions, 1000 same, 0 differ
1000 soups: 45 accepted by both or by one, 0 differ, 3 not supported by minipy;
952 rejected by both, 868 at the same place, 838 also with the same message
1000 programs, 1000 same, 0 differ
1000 line soups: 9 accepted by both or by one, 0 differ, 0 not supported by minipy;
991 rejected by both, 968 at the same place, 964 also with the same message
All 3,000 programs give the same tree. Of the broken lines, about 98 in 100
fail at the same place, almost all with the same message. The expression
soups did slightly better than in the last lesson: a soup that starts with
if is now parsed as an if statement, as CPython parses it.
Where minipy differs
- Not parsed yet:
for,with,try,class,async,del,global,nonlocal,import,raise,assert, decorators, annotations, and*,**and/in parameter lists. Each is an error that says “not supported”.matchandtypeare soft keywords in CPython, names everywhere else; minipy treats them as names always. - Messages: where CPython’s second pass has a message minipy does not reproduce, such as the “Maybe you meant ‘==’” above, minipy gives the plainer one or “invalid syntax”.
returnandbreakoutside a function or loop are accepted, asast.parseaccepts them. CPython rejects them later, when it compiles the tree to bytecode (codegen.c#L2270, #L2311), and so will minipy when it has a compiler.- Long
elifchains: eachelifis anIfbuilt by a recursive call, so minipy stops at 1,000 of them with “too many ’elif’ clauses”. In a run, CPython parsed 5,000 and failed at 200,000 with “Parser stack overflowed”. Blocks need no such limit, since the tokenizer allows at most 100 levels of indentation.
Try it yourself
Check out lesson-03 and keep make test and make fuzz-ast passing.
Counting DEDENTs. Move
return ninexamples/countdown.pyto column 0. How manyDEDENTtokens come before it, what doesminipy --astprint, and what does CPython say when it runs the file?Answer
Three, all at line 6, column 0: the line leaves the
if, thewhileand thedef. The tree is aModulewith two statements, theFunctionDefand aReturn.ast.parseaccepts that too, and compiling it fails with “‘return’ outside function”, raised by the compiler, not the parser.Why
pass. What happens with anifwhose body is only a comment,if x:then# nothing yettheny = 1?Answer
A comment line produces no tokens, so after the
NEWLINEofif x:the next token isy, with noINDENT. Both parsers say “expected an indented block after ‘if’ statement on line 1” at line 3, column 1. A block needs at least one statement, andpassis the statement that does nothing.One line, two headers. Why is
if x: if y: passa syntax error, whenif x: y = 1; z = 2is not?Answer
A block on the header’s line is
simple_stmts, andifis a compound statement. Inblock(), the secondifreachessimple_stmts(), which parses an expression and fails on the keyword. Both parsers report “invalid syntax” at column 7, the secondif.del. Adddel a, b[0]. CPython’s node isDelete(targets=[...])with a new context,ctx=Del(). What does CPython say fordel f(), and which of minipy’s functions can you reuse?Answer
CPython prints
Delete(targets=[Name(id='a', ctx=Del()), Subscript(value=Name(id='b'), slice=Constant(value=0), ctx=Del())]). AddDeltoExprContextand toctx()insrc/ast.c, and aset_del()likeset_store().invalid_target()works unchanged: the targets ofdelare the same kinds as those of=, and CPython reuses its function withDEL_TARGETS. Fordel f()CPython reports “cannot delete function call” at column 5, thef.forloops. Why can’tfor x in y:parse its target withstar_expressions(), the wayassignment()does?Answer
star_expressions()would readx in yas one comparison:minipy --aston a linex in yprints aComparewithops=[In()]. The target has to stop beforein. One way is to parse the target withbinary(p, PREC_BITOR), comma-separated, sinceinis not one ofbinary()’s operators, then require the keywordin. CPython’s_PyPegen_get_invalid_targethas a special case for this,FOR_TARGETS, which looks inside a comparison whose first operator isin(action_helpers.c#L1250-L1261).Where an
Ifends. Inif x: pass;, where does CPython say theIfends, and thePass?Answer
The
Passends at column 10, afterpass, and theIfat column 11, after the;: the last token of theIfthat is notNEWLINE,INDENTorDEDENTis the semicolon, which belongs to the line of simple statements, not topass.
Sources
minipy, tag lesson-03:
src/parser.c (the statements section), src/ast.h, src/ast.c,
src/strace.c, tests/fuzz-ast.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:
- Grammar/python.gram#L97-L117
statements,statement,simple_stmts - Grammar/python.gram#L162-L165 assignment and augmented assignment
- Grammar/python.gram#L266-L269
block - Grammar/python.gram#L386-L405
if_stmt,elif_stmt,else_block,while_stmt - Grammar/python.gram#L1118-L1142 targets
- Grammar/python.gram#L1287-L1295
invalid_named_expression - Grammar/python.gram#L1531-L1554 errors for
if,elif,else,while,def - Parser/Python.asdl#L11-L56 statement nodes
- Include/internal/pycore_ast.h#L187-L359
struct _stmt - Parser/pegen.c#L435-L454 forced tokens
- Parser/pegen.c#L480-L492 where a node ends
- Parser/pegen_errors.c#L198-L238 where an error is placed
- Parser/action_helpers.c#L1084-L1270
_PyPegen_get_expr_name,_PyPegen_get_invalid_target - Python/codegen.c#L2270, #L2311
returnandbreakoutside a function or loop
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 plannedRun the AST directly, with C integers as the only values: enough for loops, conditions and print.
Objects
- 06 Everything is an object plannedThe object header, a reference count and a type pointer, and why a type is an object too.
- 07 Operators through type slots plannedHow 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.