man python-in-c/peg-parser

lesson 4 of 33 · Reading source

How CPython parses: a PEG grammar

lib / Building a Python in C 18 mindraft

checked against: CPython 3.15.2, Apple clang 21.0.0

code: toothywalrus/minipy@lesson-04

minipy’s parser and CPython’s build the same trees, as the last two lessons checked thousands of times. They get there in different ways. minipy’s is written by hand and decides what comes next from the token in front of it. CPython’s is generated from a grammar file, tries alternatives in order, and backs up when one fails. This lesson is about that machinery: what it is, what it costs, and how CPython keeps the cost down.

The code is minipy at tag lesson-04. It parses nothing new. What it adds is a way to see the parser’s choices: --decisions prints each choice and the tokens it looked at, and --trace-decide writes the same as frames for the figure below. CPython has a counterpart in its debug builds, and most of this lesson reads the two side by side on one line of Python.

The grammar is the source

Python 3.9 replaced CPython’s old LL(1) parser with one based on PEG, a parsing expression grammar (PEP 617, and What’s New in 3.9). The grammar is Grammar/python.gram, 1,653 lines, and the parser is generated from it: a generator written in Python, in Tools/peg_generator, turns each rule into a C function and writes them all to Parser/parser.c, 39,572 lines whose first line is // @generated by pegen from python.gram. Changing Python’s syntax means editing the grammar and running make regen-pegen (Makefile.pre.in#L2032-L2040).

The previous lessons quoted rules from that file. Its header lists the notation (python.gram#L54-L83), and most of it is what any grammar has: sequence, |, optional [e], repetition e* and e+. The last four operators are where PEG differs:

# &e
#   Succeed if e can be parsed, without consuming any input.
# !e
#   Fail if e can be parsed, without consuming any input.
# ~
#   Commit to the current alternative, even if it fails to parse.
# &&e
#   Eager parse e. The parser will not backtrack and will immediately
#   fail with SyntaxError if e cannot be parsed.

Each of them is about backtracking, so that comes first.

Ordered choice

In a PEG, e1 | e2 means: try e1; if it fails, go back to where it started and try e2. The first alternative that matches wins, even if a later one would have matched more. To go back, the parser must still have the tokens it has read, so CPython keeps them all in an array and moves an index, mark, over it (pegen.h#L70-L74):

typedef struct {
    struct tok_state *tok;
    Token **tokens;
    int mark;
    int fill, size;

fill is how many tokens have been read so far. The tokenizer is asked for the next one only when mark reaches fill, as in the function that matches one token (pegen.c#L404-L419):

Token *
_PyPegen_expect_token(Parser *p, int type)
{
    if (p->mark == p->fill) {
        if (_PyPegen_fill_token(p) < 0) {
            p->error_indicator = 1;
            return NULL;
        }
    }
    Token *t = p->tokens[p->mark];
    if (t->type != type) {
       return NULL;
    }
    p->mark += 1;
    return t;
}

Backing up is setting p->mark back. Here is one alternative of the assignment rule, single_target augassign ~ annotated_rhs, as the generator wrote it (parser.c#L2276-L2284):

        if (
            (a = single_target_rule(p))  // single_target
            &&
            (b = augassign_rule(p))  // augassign
            &&
            (_cut_var = 1)
            &&
            (c = annotated_rhs_rule(p))  // annotated_rhs
        )

If the condition holds, the action builds an AugAssign and the function returns it. If not (#L2304-L2310):

        p->mark = _mark;
        D(fprintf(stderr, "%*c%s assignment[%d-%d]: %s failed!\n", p->level, ' ',
                  p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "single_target augassign ~ annotated_rhs"));
        if (_cut_var) {
            p->level--;
            return NULL;
        }

the mark goes back to where the alternative started, and the next alternative is tried from there. _cut_var is the ~: once augassign has matched, the rule commits, and if the right-hand side then fails, the whole rule fails instead of trying the alternatives after this one.

minipy keeps two tokens: the current one and, after peek(), the next. It cannot go back, so every choice has to be made from what is in front of it.

Watching it

The D(...) around that fprintf is the debug log. It is compiled in only in a debug build (parser.c#L5-L9), and switched on by python -d (pegen.c#L853-L855; the documentation calls it “for expert only”). For this lesson I built v3.15.2 with ./configure --with-pydebug, and $PYDEBUG below is that build:

$ $PYDEBUG -c "import sys, sysconfig; print(sys.version.split()[0], sysconfig.get_config_var(\"Py_DEBUG\"))"
3.15.2 1

The line to parse is examples/assign.py:

x.y[0] = f(b, a=1)

Running it with -d prints the parse to stderr, and then the program fails with a NameError, since f is not defined; the parse itself succeeds. The commands below keep the log up to the line where the rule file succeeds, so only this file’s parse is counted. Its start:

$ $PYDEBUG -d examples/assign.py 2>&1 | sed -n "1,/ file\[.*succeeded/p" | head -20
 > file[0-0]: statements? $
  > statements[0-0]: statement+
   > _loop1_2[0-0]: statement
    > statement[0-0]: compound_stmt
     > compound_stmt[0-0]: &('def' | '@' | 'async') function_def
      > _tmp_6[0-0]: 'def'
line[1] = "x.y[0] = f(b, a=1)\n"  tok->done = 10
      - _tmp_6[0-0]: 'def' failed!
      > _tmp_6[0-0]: '@'
      - _tmp_6[0-0]: '@' failed!
      > _tmp_6[0-0]: 'async'
      - _tmp_6[0-0]: 'async' failed!
     - compound_stmt[0-0]: &('def' | '@' | 'async') function_def failed!
     > compound_stmt[0-0]: &'if' if_stmt
     - compound_stmt[0-0]: &'if' if_stmt failed!
     > compound_stmt[0-0]: &('class' | '@') class_def
      > _tmp_7[0-0]: 'class'
      - _tmp_7[0-0]: 'class' failed!
      > _tmp_7[0-0]: '@'
      - _tmp_7[0-0]: '@' failed!

> is an alternative being tried, + one that matched and - one that failed; the numbers in brackets are the token positions where it started and where the mark is now. _loop1_2 and _tmp_6 are helper rules the generator made for statement+ and for the group ('def' | '@' | 'async'). The line[1] in the middle is the tokenizer, reading the line the first time a token is needed.

compound_stmt is the rule from the last lesson, and all its alternatives but the last start with a lookahead (python.gram#L137-L145): &'if' if_stmt checks that the next token is if without consuming it, and only then calls if_stmt. The last, match_stmt, starts with the soft keyword match and fails on the first token too. Each check looks at one token, so going through the eight alternatives before trying a simple statement is cheap. A single token check like &'if' does not show in the log; only the rule alternatives do. minipy makes the same decision with at_keyword(p, "if"): here the grammar’s lookahead does what minipy’s one token of lookahead does.

One line, two parsers

Here is minipy on the same line:

$ ./minipy --decisions examples/assign.py
token  function     looked at        chose
    0  statement    x                a line of simple statements
    0  simple_stmt  x                an expression; what follows it decides the rest
    0  atom         x                a Name
    1  primary      .                an Attribute
    3  primary      [                a Subscript
    4  atom         0                a Constant
    5  primary      ]                nothing more: return
    6  primary      =                nothing more: return
    6  simple_stmt  =                an Assign: the expression was a target
    7  atom         f                a Name
    8  primary      (                a Call
    9  arguments    b, then ,        a positional argument
    9  atom         b                a Name
   10  primary      ,                nothing more: return
   11  arguments    a, then =        a keyword argument
   13  atom         1                a Constant
   14  primary      )                nothing more: return
   15  primary      NEWLINE          nothing more: return
17 tokens, each read once; 18 choices, 2 of them after looking one token further.

The trace covers the choices of statement(), simple_stmt(), atom(), primary() and arguments(), the functions that decide what kind of node comes next. The operator loop in binary() makes choices too, one per operator it looks at, and they are left out. Two of the choices looked at a second token: a name in an argument list is a keyword argument only if an = follows. The other places that call peek() are the comparison operators is not and not in, which this line does not have.

The key choice is the ninth. simple_stmt() parsed x.y[0] as an ordinary expression, then found = and turned that expression into a target, as lesson 3 described. It never needed to know in advance.

Recorded with minipy --trace-decide examples/assign.py at tag lesson-04; make test checks that the trace still comes out identical (tests/traces/assign.decide.json).

Now CPython. Counting the log’s lines:

$ $PYDEBUG -d examples/assign.py 2>&1 | sed -n "1,/ file\[.*succeeded/p" | awk "/^ *> /{t++} /^ *[+] /{s++} /^ *- /{f++} END{print t, \"tried,\", s, \"succeeded,\", f, \"failed\"}"
816 tried, 177 succeeded, 639 failed

816 alternatives tried for a line of 17 tokens, and almost four in five of them failed. By the token where each one started:

$ $PYDEBUG -d examples/assign.py 2>&1 | sed -n "1,/ file\[.*succeeded/p" | grep -oE "^ *> [a-z_0-9]+\[[0-9]+" | sed "s/.*\[//" | sort -n | uniq -c
  52 0
   6 1
   3 3
 101 4
  27 5
   9 6
  99 7
   4 8
  82 9
  37 10
  79 11
  27 12
  83 13
  29 14
  32 15
 146 16

Most of it is not backtracking. Token 4 is the 0 inside [0], and 101 alternatives start there because an operand is reached through one rule per precedence level: expression, disjunction, conjunction, inversion, comparison, bitwise_or and on down to atom, each trying its operator alternative before its plain one. minipy’s binary() reaches the same 0 with one call, since the precedence is a number, not a rule. Token 16 is the ENDMARKER: statement+ tries for one more statement there, and every kind of statement fails on it.

The backtracking is in the assignment rule:

$ $PYDEBUG -d examples/assign.py 2>&1 | sed -n "1,/ file\[.*succeeded/p" | grep -n -E "[>+-] (assignment|single_subscript_attribute_target|star_targets|annotated_rhs)\[" | sed "/+ assignment/q"
46:       > assignment[0-0]: NAME ':' expression ['=' annotated_rhs]
47:       - assignment[0-0]: NAME ':' expression ['=' annotated_rhs] failed!
48:       > assignment[0-0]: ('(' single_target ')' | single_subscript_attribute_target) ':' expression ['=' annotated_rhs]
52:         > single_subscript_attribute_target[0-0]: t_primary '.' NAME !t_lookahead
335:         - single_subscript_attribute_target[0-0]: t_primary '.' NAME !t_lookahead failed!
336:         > single_subscript_attribute_target[0-0]: t_primary '[' slices ']' !t_lookahead
355:         + single_subscript_attribute_target[0-6]: t_primary '[' slices ']' !t_lookahead succeeded!
357:       - assignment[0-0]: ('(' single_target ')' | single_subscript_attribute_target) ':' expression ['=' annotated_rhs] failed!
358:       > assignment[0-0]: ((star_targets '='))+ annotated_rhs !'=' TYPE_COMMENT?
361:          > star_targets[0-0]: star_target !','
388:          + star_targets[0-6]: star_target !',' succeeded!
391:          > star_targets[7-7]: star_target !','
1100:          + star_targets[7-8]: star_target !',' succeeded!
1103:        > annotated_rhs[7-7]: yield_expr
1108:        - annotated_rhs[7-7]: yield_expr failed!
1109:        > annotated_rhs[7-7]: star_expressions
1334:        + annotated_rhs[7-15]: star_expressions succeeded!
1335:       + assignment[0-15]: ((star_targets '='))+ annotated_rhs !'=' TYPE_COMMENT? succeeded!

The first alternatives are annotated assignments, x: int = 1. The second one parses x.y[0] as an attribute-or-subscript target (log lines 52 to 355, about 300 lines, most of them for the 0), then needs a :, finds =, and fails. The mark goes back to 0. The third alternative parses x.y[0] again, now as one of star_targets, and this time it takes 28 lines. Then the + in (star_targets '=')+ tries for a second target: it parses f(b, a=1) as a target, arguments and all, finds no . or [ after the ), falls back to the name f, and fails on the ( where it wanted =. Lines 391 to 1100 are that attempt. Finally annotated_rhs parses f(b, a=1) again, as a value.

So CPython parsed x.y[0] twice and f(b, a=1) twice, and that is how a PEG parser handles an assignment: it tries the target first, and if that does not work out, it goes back. minipy parsed each once and decided at the =. The price is that minipy’s grammar has to be one that can be decided that way. The second parse of x.y[0] took 28 lines instead of 300 for a reason, which is the next section.

Memoization

Going back and trying again can repeat the same work many times over, when the same rule is tried again at the same position from different alternatives. A PEG parser can avoid that by remembering, for each token position and rule, what the rule returned there. CPython hangs a list of these on each token (pegen.h#L32-L37):

typedef struct _memo {
    int type;
    void *node;
    int mark;
    struct _memo *next;
} Memo;

type is the rule, node its result (NULL for a failure, which is worth remembering too) and mark where the parse continued after it. A memoized rule starts by looking for its entry on the current token (pegen.c#L341-L373), and if there is one, it moves the mark and returns the node without parsing anything. CPython does not memoize every rule. 20 rules in the grammar carry the flag (memo), among them expression, block and arguments (python.gram#L1077), and left-recursive rules are memoized because they need it, as the next section shows.

That is why the second x.y[0] was cheap. t_primary, the rule for the x.y in front of the [, is left-recursive, and its result at position 0 was remembered; expression, for the 0, was remembered too. A memo hit returns before the D(...) call, so it leaves no line in the log, and lines 361 to 388 skip straight past both. The same happened to the arguments: arguments is memoized, and the log shows it starting only once, inside the attempt to read f(b, a=1) as a target. When annotated_rhs needed them again, they were already there.

Left recursion

Here is how the grammar writes | (python.gram#L821-L823):

bitwise_or[expr_ty]:
    | a=bitwise_or '|' b=bitwise_xor { _PyAST_BinOp(a, BitOr, b, EXTRA) }
    | bitwise_xor

The rule starts with itself. A recursive descent function that calls itself first, at the same position, never returns. The generator detects such rules and wraps them in a loop that grows the result (parser.c#L13554-L13573):

    int _mark = p->mark;
    int _resmark = p->mark;
    while (1) {
        int tmpvar_2 = _PyPegen_update_memo(p, _mark, bitwise_or_type, _res);
        if (tmpvar_2) {
            p->level--;
            return _res;
        }
        p->mark = _mark;
        void *_raw = bitwise_or_raw(p);
        if (p->error_indicator) {
            p->level--;
            return NULL;
        }
        if (_raw == NULL || p->mark <= _resmark)
            break;
        _resmark = p->mark;
        _res = _raw;
    }
    p->mark = _resmark;

bitwise_or_raw() is the rule as written. The first time round, the memo says bitwise_or fails at this position, so inside _raw the self-call fails at once, the first alternative fails, and the second parses a bitwise_xor: for a | b | c, that is a. That result goes into the memo, and the loop runs _raw again from the same start. Now the self-call returns a from the memo, and the first alternative matches a | b. Next time round, (a | b) | c. When a round consumes no more tokens than the one before, the loop stops and the longest result stands. The tree comes out left-associative, as it should.

The generator’s code for this is in c_generator.py#L564-L599, and the generated parser.c marks 22 rules as // Left-recursive. minipy has no left-recursive functions. Lesson 2’s binary() reads an operand and then loops over the operators, building to the left; it does with a loop what the grammar does with a left-recursive rule and the generator does with a memo.

Cut and forced tokens

~ commits to an alternative, as the generated code above showed with _cut_var. In single_target augassign ~ annotated_rhs (python.gram#L164-L165), once x += has been read, nothing else in assignment can match, so there is no point in trying. &&':', from the last lesson, goes further: not only no other alternative, but an error at once, “expected ‘:’”. Both make a PEG parser behave, at that point, the way minipy behaves everywhere: once it has decided, it does not go back.

Two passes

When the first pass fails, CPython does not report the error straight away. It throws away the memo, sets the mark back to 0 and parses again, this time with the rules whose names start with invalid_ switched on (pegen.c#L960-L966):

        Token *last_token = p->tokens[p->fill - 1];
        reset_parser_state_for_error_pass(p);
        _PyPegen_parse(p);

        // Set SyntaxErrors accordingly depending on the parser/tokenizer status at the failure
        // point.
        _Pypegen_set_syntax_error(p, last_token);

Those rules match common mistakes and raise the specific messages, like the “expected ‘:’” and “cannot assign to function call” of lesson 3. last_token is the furthest token the first pass read; if the second pass finds nothing specific, the generic “invalid syntax” is reported there (python.gram#L35-L41).

minipy has one pass. Its “invalid syntax” usually lands where CPython’s does because, for a parser that never goes back, the furthest token read is the one it stopped at. Its specific messages are checks in the code paths where the mistake shows up, like invalid_target() in lesson 3. That covers the common cases, but the messages that come from CPython trying a second set of rules, like the “Maybe you meant ‘==’” of the last lesson, have no place in a one-pass parser.

Where minipy differs

  • How it decides: by the current token, and in three places (keyword arguments, is not, not in) the one after it. CPython tries alternatives and backs up, and can look as far ahead as it likes.
  • What it keeps: two tokens. CPython keeps every token of the input, with the memo entries hanging off them.
  • Errors: one pass, with the specific checks written into the code. CPython parses a second time with the invalid_ rules.
  • What it can parse: only a grammar that can be decided that way. The soft keywords are the clearest case it cannot handle as it stands: in CPython, match (x) is a call and match (x): followed by case lines is a match statement, and the difference is the : at the end of the line.

Try it yourself

Check out lesson-04. The questions that use the debug log need a --with-pydebug build of CPython.

  1. Positions with no rule. In the table of positions, token 2 (y) is missing, and token 8 (() has only 4. Why?

    Answer

    No alternative starts at token 2. The y is matched as the NAME in t_primary '.' NAME, inside an alternative that started at token 0. Only rules have lines in the log; a token matched inside a rule does not. At token 8 the ( is mostly matched inside rules that started earlier, like t_primary '(' arguments? ')'; the 4 that start there are t_lookahead, checking for a (, and genexp, for a call whose only argument is a generator expression, each tried twice.

  2. The memo is invisible. Find the evidence in the log that t_primary at position 0 came from the memo the second time.

    Answer

    In the full log, from line 361 on, target_with_star_atom[0-0] tries t_primary '[' slices ']' and the next line is already slices[4-4]: no t_primary line in between, though t_primary must have matched x.y for the alternative to reach [. _PyPegen_is_memoized returns before the D(...) call, so a hit prints nothing.

  3. t_lookahead. f(x).y = 1 is a valid assignment and f(x) = 1 is not. Which part of the target rules makes the difference?

    Answer

    t_primary only matches where (, [ or . follows (&t_lookahead), and single_subscript_attribute_target and target_with_star_atom end with '.' NAME or '[' slices ']' and nothing of that kind after (!t_lookahead). In f(x).y the call is a t_primary followed by ., and .y ends the target. In f(x) the last part is a call, and no target rule accepts a call as the whole target, so the assignment fails and the second pass reports “cannot assign to function call here. Maybe you meant ‘==’ instead of ‘=’?”

  4. Peeking less. Could arguments() avoid its peek() by parsing an expression first and checking for = afterwards, as simple_stmt() does?

    Answer

    Almost. The expression would have to be a bare name, and the tree does not say whether it was: a and (a) both give Name(id='a'). So f((a)=1) would be accepted, where CPython reports “expression cannot contain assignment, perhaps you meant “==”?”. arguments() would have to remember whether the expression was parenthesized, which is more code than one peek().

  5. The second pass. Run the debug build on tests/parse/err-expected-colon.py (if x without the colon). Where do the invalid_ rules appear?

    Answer

    The log starts > file[0-0] twice for this file, at line 1 and line 504. No invalid_ rule appears before the second start. After it, invalid_if_stmt ('if' named_expression NEWLINE) matches and raises “expected ‘:’”, which shows as ERROR! on the lines after it. More > file[0-0] lines follow, for other code CPython compiles while it reports the error; the line[1] after each start shows what.

  6. match. What would minipy need to parse match statements, given that match is also an ordinary name?

    Answer

    After match, an expression that could be a match subject could also be the rest of an expression statement: match (x) is a call, match [1] a subscript and match * 2 a multiplication, all valid. It becomes a match statement only at the : at the end of the line. A one-pass parser would have to read the line and then decide what it had read, as simple_stmt() does for =, or keep the tokens and go back, which is what CPython does: match_stmt is tried first, and if it fails, the parser backs up and reads the line as an expression.

Sources

minipy, tag lesson-04: src/parser.c (decide() and its calls), src/dtrace.c, examples/assign.py. Built with cc (Apple clang 21.0.0) on macOS. The CPython logs come from v3.15.2 built with --with-pydebug on the same machine.

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.