man python-in-c/expressions

lesson 2 of 33 · Reading source

Parsing expressions by precedence climbing

lib / Building a Python in C 21 mindraft

checked against: CPython 3.15.2, Apple clang 21.0.0

code: toothywalrus/minipy@lesson-02

The tokenizer from the last lesson turns a - b * c into a list of tokens, in the order they were written. Nothing in that list says that the multiplication happens first. The parser’s job is to build a structure that does say it: a tree in which each operator is a node and its operands are the node’s children. By the end of this lesson minipy --ast file.py reads a file of expressions, one per line, and prints the same tree as CPython’s ast.dump(), positions included.

The code is minipy at tag lesson-02. The parser is src/parser.c, 879 lines; the tree is src/ast.h, and src/ast.c prints it. make test runs 62 tests, make compare-ast diffs minipy’s trees against Python’s ast module, and make fuzz-ast does the same with 6,000 random inputs. Every terminal output below was recorded from a run of the command shown with it.

The tree

Here is a one-line file, examples/precedence.py, and the tree minipy builds from it:

$ ./minipy --ast examples/precedence.py
Module(
  body=[
    Expr(
      value=BinOp(
        left=BinOp(
          left=Name(id='a'),
          op=Sub(),
          right=BinOp(
            left=Name(id='b'),
            op=Mult(),
            right=BinOp(
              left=Name(id='c'),
              op=Pow(),
              right=BinOp(
                left=Constant(value=2),
                op=Pow(),
                right=Name(id='k'))))),
        op=Add(),
        right=Name(id='d')))])

The file was a - b * c ** 2 ** k + d. A Module holds a list of statements, and an expression on a line of its own is an Expr statement. Below that, the operator applied last sits at the top: the +. Its left child is a - (b * ...), and the two ** nest to the right, c ** (2 ** k). Reading the tree from the leaves up gives the order of evaluation, with no parentheses needed.

The names Module, Expr, BinOp, Sub and the field names left, op, right are CPython’s. The format is the one ast.dump(tree, indent=2) prints, so the two can be compared directly:

$ python3 -c 'import ast, sys; print(ast.dump(ast.parse(open(sys.argv[1]).read()), indent=2))' examples/precedence.py | diff - <(./minipy --ast examples/precedence.py) && echo same
same

ast.dump in 3.15 leaves out fields that are None or empty lists, and leaves out ctx=Load(), the marker that says a name is read rather than assigned (ast.py#L168-L185). That is why it prints Name(id='a'). It also puts a node on one line when it has at most three fields and each is a plain value or a node without fields, such as Sub() (ast.py#L207-L209). ast_dump() in src/ast.c follows the same rules.

Nodes in C

A node is one of several kinds, and each kind has different fields. In C that is a tagged union: a kind that says which member of the union is in use, then the union. This is minipy’s, from src/ast.h:

struct Expr {
    ExprKind kind;
    union {
        struct { BoolOperator op; ExprList values; } BoolOp;
        struct { Expr *left; Operator op; Expr *right; } BinOp;
        struct { UnaryOperator op; Expr *operand; } UnaryOp;
        struct { Expr *test, *body, *orelse; } IfExp;
        struct { ExprList keys, values; } Dict;
        struct { ExprList elts; } Set;
        struct { Expr *left; CmpOpList ops; ExprList comparators; } Compare;
        struct { Expr *func; ExprList args; KeywordList keywords; } Call;
        struct { ConstKind kind; const char *s; int len; double f; } Constant;
        struct { Expr *value; const char *attr; ExprContext ctx; } Attribute;
        struct { Expr *value, *slice; ExprContext ctx; } Subscript;
        struct { const char *id; ExprContext ctx; } Name;
        struct { ExprList elts; ExprContext ctx; } List;
        struct { ExprList elts; ExprContext ctx; } Tuple;
        struct { Expr *lower, *upper, *step; } Slice;     /* each may be NULL */
    } v;
    Pos pos;
};

Code that walks the tree switches on e->kind and then reads e->v.BinOp.left or e->v.Name.id. Reading a member other than the one kind names is a bug the compiler will not catch, so every such access sits right under a case.

CPython’s node is the same shape with the same names. Nobody writes it by hand: Parser/asdl_c.py generates Include/internal/pycore_ast.h from Parser/Python.asdl, a description of every node kind and its fields. The start and the end of the generated struct (pycore_ast.h#L370-L387, #L517-L528):

struct _expr {
    enum _expr_kind kind;
    union {
        struct {
            boolop_ty op;
            asdl_expr_seq *values;
        } BoolOp;

        struct {
            expr_ty target;
            expr_ty value;
        } NamedExpr;

        struct {
            expr_ty left;
            operator_ty op;
            expr_ty right;
        } BinOp;
        struct {
            expr_ty lower;
            expr_ty upper;
            expr_ty step;
        } Slice;

    } v;
    int lineno;
    int col_offset;
    int end_lineno;
    int end_col_offset;
};

CPython has 29 kinds of expression; minipy has the 15 it parses so far. One real difference is the Constant. CPython’s holds a Python object: an int, a float, a str. minipy has no objects yet, so a Constant keeps an integer’s digits as text, a float as a C double and a string as its UTF-8 bytes. Integers stay text on purpose: 123456789012345678901234567890 does not fit in any C integer, and the lesson on numbers will give it a home.

Every node, list and string the parser makes comes from an arena (src/arena.c, 55 lines): memory handed out in 64 KB blocks and freed all at once when the tree is no longer needed. The parser never frees a single node, not even on an error. CPython does the same with PyArena, in blocks of 8 KB (pyarena.c#L11).

One rule per level

Python has eight levels of precedence among its arithmetic and bitwise operators alone. CPython’s grammar writes one rule per level, each calling the next tighter one. The bottom four (python.gram#L842-L864):

sum[expr_ty]:
    | a=sum '+' b=term { _PyAST_BinOp(a, Add, b, EXTRA) }
    | a=sum '-' b=term { _PyAST_BinOp(a, Sub, b, EXTRA) }
    | term

term[expr_ty]:
    | a=term '*' b=factor { _PyAST_BinOp(a, Mult, b, EXTRA) }
    | a=term '/' b=factor { _PyAST_BinOp(a, Div, b, EXTRA) }
    | a=term '//' b=factor { _PyAST_BinOp(a, FloorDiv, b, EXTRA) }
    | a=term '%' b=factor { _PyAST_BinOp(a, Mod, b, EXTRA) }
    | a=term '@' b=factor { CHECK_VERSION(expr_ty, 5, "The '@' operator is", _PyAST_BinOp(a, MatMult, b, EXTRA)) }
    | invalid_factor
    | factor

factor[expr_ty] (memo):
    | '+' a=factor { _PyAST_UnaryOp(UAdd, a, EXTRA) }
    | '-' a=factor { _PyAST_UnaryOp(USub, a, EXTRA) }
    | '~' a=factor { _PyAST_UnaryOp(Invert, a, EXTRA) }
    | power

power[expr_ty]:
    | a=await_primary '**' b=factor { _PyAST_BinOp(a, Pow, b, EXTRA) }
    | await_primary

Each alternative is a pattern followed by the C code that builds its node. sum refers to itself on the left, a=sum '+' b=term, which is how the grammar says that a - b - c means (a - b) - c. A plain recursive-descent function cannot do that: sum() would call sum() before reading any token, forever. CPython’s parser generator has a special technique for rules like this, which is part of the lesson after next. A hand-written parser usually turns each such rule into a loop, one function per level: term() calls factor(), then loops while it sees * or /, and so on up.

That is eight functions that differ only in their operators and in which function they call. minipy has one function and a table instead. Higher numbers bind tighter:

precedenceoperatorsCPython’s rule
1|bitwise_or
2^bitwise_xor
3&bitwise_and
4<< >>shift_expr
5+ -sum
6* / // % @term
7unary - + ~factor
8**power
static const struct { TokenType tok; Operator op; int prec; } binary_ops[] = {
    { TOK_VBAR, BitOr, PREC_BITOR },        { TOK_CIRCUMFLEX, BitXor, PREC_BITXOR },
    { TOK_AMPER, BitAnd, PREC_BITAND },     { TOK_LEFTSHIFT, LShift, PREC_SHIFT },
    { TOK_RIGHTSHIFT, RShift, PREC_SHIFT }, { TOK_PLUS, Add, PREC_SUM },
    { TOK_MINUS, Sub, PREC_SUM },           { TOK_STAR, Mult, PREC_TERM },
    { TOK_SLASH, Div, PREC_TERM },          { TOK_DOUBLESLASH, FloorDiv, PREC_TERM },
    { TOK_PERCENT, Mod, PREC_TERM },        { TOK_AT, MatMult, PREC_TERM },
    { TOK_DOUBLESTAR, Pow, PREC_POWER },
};

Precedence climbing

The function that uses the table, binary(p, min_prec), parses one operand and then takes operators for as long as they bind at least as tightly as min_prec. For each operator it takes, the right side is a recursive call with a higher min_prec, so the right side swallows exactly the operators that bind tighter than this one:

static Expr *binary(Parser *p, int min_prec)
{
    if (++p->depth > MAX_PARSE_DEPTH)
        return error_at(p, p->tok.line, p->tok.col, "expression too deeply nested");
    step(p, (PStep){ .kind = PSTEP_ENTER, .min_prec = min_prec });
    Token start = p->tok;
    Expr *left;
    if (at(p, TOK_MINUS) || at(p, TOK_PLUS) || at(p, TOK_TILDE)) {
        Token op = advance(p);
        Expr *operand = binary(p, PREC_UNARY);
        if (!operand)
            return NULL;
        left = new_expr(p, UnaryOp_kind, start);
        left->v.UnaryOp.op = op.type == TOK_MINUS ? USub : op.type == TOK_PLUS ? UAdd : Invert;
        left->v.UnaryOp.operand = operand;
        step(p, (PStep){ .kind = PSTEP_BUILD, .node = left });
    } else {
        left = primary(p);
        if (!left)
            return NULL;
        step(p, (PStep){ .kind = PSTEP_OPERAND, .node = left });
    }
    for (;;) {
        Operator op;
        int prec = binary_op(p->tok.type, &op);
        step(p, (PStep){ .kind = PSTEP_LOOK, .min_prec = min_prec, .prec = prec });
        if (prec == 0 || prec < min_prec)
            break;
        advance(p);
        Expr *right = binary(p, op == Pow ? prec : prec + 1);
        if (!right)
            return NULL;
        Expr *e = new_expr(p, BinOp_kind, start);
        e->v.BinOp.left = left;
        e->v.BinOp.op = op;
        e->v.BinOp.right = right;
        left = e;
        step(p, (PStep){ .kind = PSTEP_BUILD, .node = left });
    }
    p->depth--;
    step(p, (PStep){ .kind = PSTEP_RETURN, .min_prec = min_prec, .node = left });
    return left;
}

step() reports to --trace-expr and does nothing otherwise. The figure steps through binary() on the example. The top row is the tokens, with the current one outlined; below it, the calls of binary() that are running, outermost first; below that, the trees built so far that no larger node has taken as a part yet.

Recorded with minipy --trace-expr examples/precedence.py at tag lesson-02. The repository’s make test checks that the trace still comes out identical (tests/traces/precedence.expr.json).

Two things in the loop decide associativity, and the figure shows both. Operators of equal precedence group to the left because the right side of - is binary(6), one level up. In frame 21 that call meets +, whose precedence 5 is below 6, and returns. Back in binary(1), the loop builds a - ... and goes round again: in frame 23 it takes the + with the whole subtraction as its left side. For ** the right side is binary(8), not binary(9), so a second ** is taken by the inner call: in frames 12 to 18, 2 ** k is built first and becomes the right side of c ** ....

The unary operators sit in the table at 7, between * and **. When binary() meets a - where an operand should be, it parses the operand with binary(7), which takes a ** (8) but not a * (6). So -x ** 2 is the negation of a power, as in CPython:

$ python3 -c 'import ast; print(ast.dump(ast.parse("-x ** 2").body[0].value))'
UnaryOp(op=USub(), operand=BinOp(left=Name(id='x'), op=Pow(), right=Constant(value=2)))

On the other side of ** a minus is allowed, 2 ** -1, because the right side is a fresh call of binary(), which starts by checking for a unary operator. The grammar says the same thing in power: the left of ** is an await_primary, which cannot start with -, and the right is a factor, which can.

Comparisons, not, and, or

Below precedence 1 come comparisons, then not, and, or, and the conditional expression x if c else y. They are not in the table, because they do not build BinOps:

$ python3 -c 'import ast; [print(ast.dump(ast.parse(s).body[0].value)) for s in ("a < b < c", "(a < b) < c", "a or b or c", "(a or b) or c")]'
Compare(left=Name(id='a'), ops=[Lt(), Lt()], comparators=[Name(id='b'), Name(id='c')])
Compare(left=Compare(left=Name(id='a'), ops=[Lt()], comparators=[Name(id='b')]), ops=[Lt()], comparators=[Name(id='c')])
BoolOp(op=Or(), values=[Name(id='a'), Name(id='b'), Name(id='c')])
BoolOp(op=Or(), values=[BoolOp(op=Or(), values=[Name(id='a'), Name(id='b')]), Name(id='c')])

a < b < c is one Compare with two operators, because it means a < b and b < c with b evaluated only once (expressions.rst#L2070-L2072). A nested pair of Compares would mean comparing the result of a < b, a bool, with c. Likewise a or b or c is one BoolOp with a list of three values, while the parenthesized version nests. minipy builds these lists in loops, one function per level as in the grammar. and and or share one:

static Expr *bool_chain(Parser *p, const char *kw, BoolOperator op,
                        Expr *(*operand)(Parser *))
{
    Token start = p->tok;
    Expr *first = operand(p);
    if (!first || !at_keyword(p, kw))
        return first;
    Vec v = { 0 };
    vec_push(&v, first);
    while (at_keyword(p, kw)) {
        advance(p);
        Expr *e = operand(p);
        if (!e) {
            free(v.items);
            return NULL;
        }
        vec_push(&v, e);
    }
    Expr *e = new_expr(p, BoolOp_kind, start);
    e->v.BoolOp.op = op;
    e->v.BoolOp.values = vec_exprs(p, &v);
    return e;
}

The flattening happens in the loop, never by looking inside a child: (a or b) comes back from primary() as a finished BoolOp, and the loop treats it as one value. CPython’s rule has the same shape, a first operand and then one or more 'or' conjunction (python.gram#L763-L768).

The operands of a comparison are binary(1), so not cannot appear there: 1 == not 2 is a syntax error in both parsers, while not 1 == 2 is not (1 == 2). not in and is not are the only operators made of two tokens, and the only place besides keyword arguments where minipy looks one token ahead of the current one, with peek().

Primaries and atoms

At the bottom of the precedence chain, primary() parses an atom (a name, a number, strings, True, a parenthesized expression, a list, a dict) and then loops over what may follow it: .name makes an Attribute, (...) a Call, [...] a Subscript. That loop is why f()(1)[2].x needs no recursion.

A call’s arguments are where two tokens are needed to choose a path. In f(x) the argument is an expression; in f(x=1) it is a keyword argument, and the two start with the same token. minipy peeks:

        if (at(p, TOK_NAME) && !token_is_keyword(&p->tok) && peek(p)->type == TOK_EQUAL) {
            Token name = advance(p);
            advance(p);                 /* the '=' */
            Expr *value = expression(p);
            if (!value)
                goto fail;
            Keyword *k = arena_alloc(p->arena, sizeof *k);
            k->arg = arena_strndup(p->arena, name.start, (size_t)name.len);
            k->value = value;
            k->pos = (Pos){ name.line, name.col, p->end_line, p->end_col };
            vec_push(&kws, k);

CPython’s grammar simply writes a=NAME '=' b=expression (python.gram#L1099-L1103) and lets its parser try that and back out if no = follows. How it can afford to back out is the subject of the lesson after next.

Every node records where it starts and ends. A function notes the current token when it is called, and a node built there runs from that token to the end of the last token consumed. That gives CPython’s positions without any special cases: in (a + b) * c the outer BinOp starts at column 0, on the parenthesis, and the inner one at column 1. A parenthesized expression is just the inner node, with its own position, while a tuple’s position includes its parentheses. minipy --ast-attrs prints the positions the way ast.dump(..., include_attributes=True) does, and make compare-ast checks those too.

Constants have to print as Python prints them. An integer is its digits without leading zeros. A float is the shortest decimal that reads back as the same double, in plain notation from 0.0001 up to 16 digits before the point and with an exponent outside that range, which is CPython’s repr rule (pystrtod.c#L1109-L1117): 1e16 prints as 1e+16 and 1e15 as 1000000000000000.0. Adjacent string literals are joined into one Constant, their escapes decoded, and the result printed with repr’s choice of quotes. float_repr() and str_repr() are in src/literal.c.

Syntax errors

When the input is not Python, the parser has to say where. CPython’s answer for its generic “invalid syntax” is the furthest token the parser has read (pegen.c#L960, pegen_errors.c#L414-L420). minipy remembers the last token it took from the tokenizer, which is the current token, or the next one when peek() has read it:

static void *syntax_error(Parser *p)
{
    if (p->error)
        return NULL;
    Token t = p->last;
    if (t.type == TOK_INDENT)
        return error_at(p, t.line, t.end_col - 1, "unexpected indent");
    return error_at(p, t.line, t.col, "invalid syntax");
}

An INDENT where a statement should start is an “unexpected indent”, as in CPython (pegen_errors.c#L409-L413). One more rule decides which error wins. After a syntax error from the parser, generic or specific, CPython tokenizes the rest of the input, and an error the tokenizer finds there, such as an unterminated string, replaces the syntax error; a bracket left open replaces it only if it was opened on an earlier line (pegen_errors.c#L134-L177). minipy’s check_rest_of_input() does the same.

Comparing with CPython

make compare-ast runs every file in tests/parse/ through both parsers. For a file both accept, the two dumps must be equal, with and without positions. For the rest it prints minipy’s error and the SyntaxError that ast.parse() raises:

$ make -s compare-ast
Python 3.15.2
same    tests/parse/boolean.py
same    tests/parse/compare.py
same    tests/parse/conditional.py
same    tests/parse/constants.py
same    tests/parse/displays.py
same    tests/parse/empty.py
error   tests/parse/err-assignment.py
        minipy:  tests/parse/err-assignment.py:1:3: error: invalid syntax
        CPython: no error
error   tests/parse/err-comprehension.py
        minipy:  tests/parse/err-comprehension.py:1:4: error: comprehensions are not supported
        CPython: no error
error   tests/parse/err-empty-subscript.py
        minipy:  tests/parse/err-empty-subscript.py:1:3: error: invalid syntax
        CPython: tests/parse/err-empty-subscript.py:1:3: SyntaxError: invalid syntax
error   tests/parse/err-if-without-else.py
        minipy:  tests/parse/err-if-without-else.py:1:1: error: expected 'else' after 'if' expression
        CPython: tests/parse/err-if-without-else.py:1:1: SyntaxError: expected 'else' after 'if' expression
error   tests/parse/err-keyword-attribute.py
        minipy:  tests/parse/err-keyword-attribute.py:1:3: error: invalid syntax
        CPython: tests/parse/err-keyword-attribute.py:1:3: SyntaxError: invalid syntax
error   tests/parse/err-lambda.py
        minipy:  tests/parse/err-lambda.py:1:1: error: lambda is not supported
        CPython: no error
error   tests/parse/err-missing-comma.py
        minipy:  tests/parse/err-missing-comma.py:1:4: error: invalid syntax
        CPython: tests/parse/err-missing-comma.py:1:2: SyntaxError: invalid syntax. Perhaps you forgot a comma?
error   tests/parse/err-missing-operand.py
        minipy:  tests/parse/err-missing-operand.py:1:4: error: invalid syntax
        CPython: tests/parse/err-missing-operand.py:1:4: SyntaxError: invalid syntax
error   tests/parse/err-named-escape.py
        minipy:  tests/parse/err-named-escape.py:1:1: error: \N{...} escapes are not supported
        CPython: no error
error   tests/parse/err-not-after-compare.py
        minipy:  tests/parse/err-not-after-compare.py:1:6: error: invalid syntax
        CPython: tests/parse/err-not-after-compare.py:1:6: SyntaxError: invalid syntax
error   tests/parse/err-number-then-keyword.py
        minipy:  tests/parse/err-number-then-keyword.py:1:1: error: invalid decimal literal
        CPython: no error
error   tests/parse/err-positional-after-keyword.py
        minipy:  tests/parse/err-positional-after-keyword.py:1:9: error: positional argument follows keyword argument
        CPython: tests/parse/err-positional-after-keyword.py:1:9: SyntaxError: positional argument follows keyword argument
error   tests/parse/err-starred.py
        minipy:  tests/parse/err-starred.py:1:3: error: unpacking with * and ** is not supported
        CPython: no error
error   tests/parse/err-two-names.py
        minipy:  tests/parse/err-two-names.py:1:3: error: invalid syntax
        CPython: tests/parse/err-two-names.py:1:3: SyntaxError: invalid syntax
error   tests/parse/err-unclosed-earlier.py
        minipy:  tests/parse/err-unclosed-earlier.py:1:1: error: '(' was never closed
        CPython: tests/parse/err-unclosed-earlier.py:1:1: SyntaxError: '(' was never closed
error   tests/parse/err-unclosed-later.py
        minipy:  tests/parse/err-unclosed-later.py:1:3: error: invalid syntax
        CPython: tests/parse/err-unclosed-later.py:1:3: SyntaxError: invalid syntax
error   tests/parse/err-unexpected-indent.py
        minipy:  tests/parse/err-unexpected-indent.py:2:2: error: unexpected indent
        CPython: tests/parse/err-unexpected-indent.py:2:2: IndentationError: unexpected indent
same    tests/parse/precedence.py
same    tests/parse/primary.py
same    tests/parse/unary.py

Every file both accept gives the same tree. Of the 17 error cases, ten get the same message at the same place. One, [1 2], gets a better message from CPython, at a different column: “Perhaps you forgot a comma?” comes from a second pass that CPython makes only after the first has failed, with extra rules that exist to describe errors (python.gram#L1269-L1270). minipy reports column 4, where CPython’s first pass stopped. The other six are valid Python that minipy does not take yet: an assignment (the next lesson), a lambda, a comprehension, a starred argument, a \N{...} escape, and 1if y else 2, of which more below.

Seventeen files are a small sample, so make fuzz-ast generates more. It builds 1,000 random expressions per seed from the constructs minipy parses, with random spacing and redundant parentheses, and requires identical trees with positions. Then it glues 1,000 random sequences of the same tokens, mostly not valid Python, and checks that whatever either parser accepts, both accept with the same tree. For inputs both reject, it counts how often the error lands at the same place:

$ 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, 868 at the same place, 840 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, 891 at the same place, 867 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, 858 at the same place, 829 also with the same message

About nine errors in ten land in the same place. Most of the others are number forms and string prefixes that lesson 1 does not support, statements minipy cannot parse yet, and messages from CPython’s second pass.

The fuzzer also found two things in lesson 1’s tokenizer. CPython reports “invalid decimal literal” at the last character of the number, not the first: x = 12a fails at column 6. That is fixed at lesson-02. And CPython still accepts a number directly followed by one of the keywords and, else, for, if, in, is, not, or, with a warning (lexer.c#L269-L311):

$ python3 -c 'import ast; print(ast.dump(ast.parse(open("tests/parse/err-number-then-keyword.py").read()).body[0].value))'; ./minipy --ast tests/parse/err-number-then-keyword.py
<unknown>:1: SyntaxWarning: invalid decimal literal
IfExp(test=Name(id='y'), body=Constant(value=1), orelse=Constant(value=2))
tests/parse/err-number-then-keyword.py:1:1: error: invalid decimal literal

The comment in the source says that in future releases only the error will remain, so minipy keeps rejecting it.

Where minipy differs

  • Not parsed yet: statements other than expressions, which get “invalid syntax” for now; and lambda, await, yield, :=, * and ** unpacking, comprehensions, f-strings, and \N{...} escapes, each of which gets an error that says “not supported” rather than “invalid syntax”.
  • Error messages: minipy has no second pass, so where CPython gives a specific message, minipy says “invalid syntax”, often at a different column.
  • Printing strings: repr leaves printable characters as they are and escapes the rest, and “printable” comes from the Unicode database. minipy knows the Latin-1 range exactly and a short list of invisible characters above it, and treats every other character as printable.
  • Nesting: minipy stops when its parsing functions nest more than 1,000 deep, as they do for 999 unary minuses in a row, with “expression too deeply nested”. CPython’s limit is on nested rule calls, 6,000 (parser.c#L18), and it raises MemoryError: Parser stack overflowed - Python source too complex to parse (pegen_errors.c#L427-L432). In a run, 3,000 nots in a row parsed and 5,990 did not.

Try it yourself

Clone the repository, check out lesson-02, and keep make test, make compare-ast and make fuzz-ast passing.

  1. Left-associative power. Change binary() so that ** groups to the left. Which test fails, and what does 2 ** 3 ** 2 evaluate to in each version?

    Answer

    Make the right side binary(p, prec + 1) for every operator. Then make test fails twice: on tests/parse/precedence.py, whose lines a - b * c ** 2 ** k + d and a ** b ** c now give different trees, and on the trace of examples/precedence.py, where c ** 2 ** k now groups the other way. make fuzz-ast reports differences as soon as it generates two ** in a row. Python’s 2 ** 3 ** 2 is 2 ** 9 = 512; grouped to the left it would be 8 ** 2 = 64.

  2. Why not is not in the table. Put not in binary() as a unary operator with precedence 0, below |. Which inputs now parse differently from CPython?

    Answer

    not would bind tighter than the comparisons, because comparison() calls binary(1) for its operands: not a == b would become (not a) == b instead of not (a == b). And a == not b, a syntax error in Python, would be accepted. not has to sit between comparison and and, which is where inversion() puts it.

  3. The walrus. Add := inside parentheses, (n := 10), as a NamedExpr node whose target has ctx=Store(). CPython’s rule is assignment_expression, used by named_expression (python.gram#L753-L761). How many tokens of lookahead does it need?

    Answer

    Two, like a keyword argument: a NAME followed by :=. In group_or_tuple(), peek when the current token is a name; if the next is COLONEQUAL, consume both, parse an expression() and build the node, with the Name marked Store so that ast_dump() prints ctx=Store(). ast.dump shows NamedExpr(target=Name(id='n', ctx=Store()), value=Constant(value=10)).

  4. A one-line dump. ast.dump() without indent prints the whole tree on one line, as in the outputs above. Add --ast-line for it.

    Answer

    With no indent, ast.py uses an empty prefix and ", " as the separator everywhere (ast.py#L148-L155). In src/ast.c that means a flag that makes finish() and list_of() join with ", " and never write a newline or indentation. The rule about three simple fields no longer matters, since every node is on one line.

  5. The missing comma. Give [1 2] CPython’s message, “invalid syntax. Perhaps you forgot a comma?”, at CPython’s column. Where exactly does CPython raise it, and when not?

    Answer

    The rule is in invalid_expression: two expressions in a row, not starting with a name followed by a string or with a soft keyword (python.gram#L1269-L1270). _PyPegen_raise_error_for_missing_comma raises it only inside brackets, and points from the start of the first expression to the end of the second (action_helpers.c#L965-L991), so the column is 2, the 1. In minipy, comma_list() can check, when no comma follows an element, whether the next token starts an expression; parse that expression and report from the first element’s position. Outside brackets, a b stays “invalid syntax”.

  6. Starred expressions. Add *a in tuples, lists and call arguments, as a Starred node. Where does CPython allow it, and where does it refuse it with “can’t use starred expression here”?

    Answer

    The grammar allows '*' bitwise_or in star_expression (a bare tuple) and star_named_expression (tuple, list and set elements), and '*' expression in starred_expression (call arguments) (python.gram#L737-L747, #L1094-L1097). An expression statement that is only *a parses: ast.parse("*a") succeeds, and the compiler rejects it later, which is the message above. The comparison scripts take CPython’s errors from ast.parse, so they would show a lone *a as “no error” on CPython’s side. tests/parse/err-starred.py, f(*args), is valid everywhere.

Sources

minipy, tag lesson-02: src/parser.c, src/ast.h, src/ast.c, src/literal.c, src/arena.c, src/ptrace.c, tests/compare-ast.py, 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:

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.