man python-in-c/tokenizer
lesson 1 of 33 · Reading source
Tokens, and how Python counts indentation
A Python file is a string of bytes. Before minipy can run any of it, something
has to decide that return is one word and not six letters, that <= is one
operator, that a # starts a comment, and which lines belong inside an if.
That is the tokenizer’s job, and it is the first piece of minipy. By the end
of this lesson minipy --tokens file.py prints the same token stream as
CPython 3.15 for the files it accepts, apart from a few differences in line
endings and column counting that we will look at.
The code is minipy at tag lesson-01:
src/tokenizer.c is 369 lines. make test runs 35 tests (33 inputs and
two traces), make compare diffs minipy against python3 -m tokenize, and
make fuzz does the same with random input. Every terminal output below
was recorded from a run of the command shown with it.
Why tokenize first
A parser could read characters directly, but every rule in it would then have
to skip spaces and comments, and recognise that >, >= and >>= are
different things. Splitting the work in two keeps both halves simple. The
tokenizer turns characters into a flat sequence of tokens. Each token has a
kind, its text and its position. The parser only ever looks at tokens.
minipy’s parser, in the next lessons, will pull tokens one at a time with
next_token(). CPython is built the same way: its parser calls
_PyTokenizer_Get() whenever it needs the next token
(pegen.c#L249).
Nothing tokenizes the whole file up front.
The token kinds
minipy’s tokens are a kind and a slice of the source:
typedef struct {
TokenType type;
const char *start; /* into the source buffer; not NUL-terminated */
int len;
int line, col; /* 1-based line, 0-based column, in bytes */
int end_line, end_col;
} Token;
The kinds, in src/token.h, have CPython’s names from
Grammar/Tokens:
NAMEfor identifiers. Keywords are names too:ifandreturncome out asNAME. CPython’s tokenizer does not know about keywords either. Its parser looks eachNAMEup in a keyword table generated from the grammar (pegen.c#L162-L185, parser.c#L20-L21).NUMBERfor7,3.5,.5,1e9. The text is kept as written. Turning it into a value is a later step.STRINGfor'...'and"...", quotes and backslash escapes included.- One kind per operator:
LPARfor(,EQEQUALfor==,DOUBLESLASHEQUALfor//=, and so on, 47 of them. The scanner takes the longest operator that matches, so**=is one token. NEWLINEat the end of each logical line,INDENTandDEDENTwhere the indentation changes, andENDMARKERat the end of the input.
Here is a short function and the tokens minipy makes from it. It has a list that spans two lines, a comment at column 0 inside the function, a blank line, and a file that ends two blocks deep.
def f(n):
if n:
return [n,
n * 2]
# only a comment
if n:
return []
$ ./minipy --tokens examples/indent.py
1,0-1,3: NAME 'def'
1,4-1,5: NAME 'f'
1,5-1,6: LPAR '('
1,6-1,7: NAME 'n'
1,7-1,8: RPAR ')'
1,8-1,9: COLON ':'
1,9-1,10: NEWLINE '\n'
2,0-2,4: INDENT ' '
2,4-2,6: NAME 'if'
2,7-2,8: NAME 'n'
2,8-2,9: COLON ':'
2,9-2,10: NEWLINE '\n'
3,0-3,8: INDENT ' '
3,8-3,14: NAME 'return'
3,15-3,16: LSQB '['
3,16-3,17: NAME 'n'
3,17-3,18: COMMA ','
4,2-4,3: NAME 'n'
4,4-4,5: STAR '*'
4,6-4,7: NUMBER '2'
4,7-4,8: RSQB ']'
4,8-4,9: NEWLINE '\n'
7,4-7,4: DEDENT ''
7,4-7,6: NAME 'if'
7,7-7,8: NAME 'n'
7,8-7,9: COLON ':'
7,9-7,10: NEWLINE '\n'
8,0-8,8: INDENT ' '
8,8-8,14: NAME 'return'
8,15-8,16: LSQB '['
8,16-8,17: RSQB ']'
8,17-8,18: NEWLINE '\n'
9,0-9,0: DEDENT ''
9,0-9,0: DEDENT ''
9,0-9,0: ENDMARKER ''
Each line gives the start and end position as line,column, the kind and the
text. The format is copied from python3 -m tokenize -e, so the two outputs
can be compared with diff. Four things in it are the subject of the rest of
this lesson. Line 3 ends without a NEWLINE. Lines 5 and 6 produce nothing.
The DEDENT that closes the inner if appears on line 7, not on line 5,
where the comment sits at column 0. And the file ends with two DEDENTs
that belong to no line in the file.
Indentation becomes tokens
Python marks a block by indenting it. Nearly every other language marks it
with a pair of symbols, and parsers handle pairs well. The tokenizer bridges
the two by emitting an INDENT where a block opens and a DEDENT where it
closes. CPython’s grammar then treats them exactly like braces. In
python.gram#L266-L267
a block is a NEWLINE, an INDENT, some statements and a DEDENT:
block[asdl_stmt_seq*] (memo):
| NEWLINE INDENT a=statements DEDENT { a }
The tokenizer keeps a stack of the indentation columns of the blocks that are
open. It starts as [0]. At the start of each logical line it counts the
leading spaces and compares the count with the top of the stack:
- Equal: the line continues the current block. No token.
- Greater: a new block opens. Push the column and emit one
INDENT. Never more than one, however far the line is indented: a line can open only one block. - Less: blocks close. Pop every column greater than this line’s and emit
a
DEDENTfor each. After popping, the line must sit exactly at the new top. If it does not, it is an error (covered below).
At the end of the input the tokenizer measures once more, as if there were a
line at column 0, and that pops whatever is still open. That produces the
two DEDENTs at 9,0.
This is minipy’s version. step() reports to --trace and does nothing
otherwise.
/* At the start of a logical line: skip lines holding only spaces and a
comment, measure the indentation of the next one and compare it with the
stack. Deeper: push it and owe one INDENT. Shallower: pop every level
deeper than it, owing a DEDENT for each, and it must then equal the top. */
static bool indentation(Tokenizer *t)
{
int col;
for (;;) {
col = 0;
while (*t->cur == ' ') {
t->cur++;
col++;
}
if (*t->cur == '\t') {
fail_at(t, t->line, col, "tabs in indentation are not supported");
return false;
}
if (*t->cur == '#')
while (t->cur < t->end && *t->cur != '\n')
t->cur++;
if (*t->cur != '\n')
break; /* a token, or the end of the input */
step(t, (Step){ .kind = STEP_BLANK, .line = t->line });
next_line(t);
}
int old_depth = t->depth;
if (col > t->indents[t->depth]) {
if (t->depth + 1 >= MAX_INDENT) {
fail_at(t, t->line, col, "too many levels of indentation");
return false;
}
t->indents[++t->depth] = col;
t->pending = 1;
} else {
while (t->depth > 0 && col < t->indents[t->depth]) {
t->depth--;
t->pending--;
}
}
step(t, (Step){ .kind = STEP_MEASURE, .line = t->line, .col = col,
.old_depth = old_depth });
if (col != t->indents[t->depth]) {
fail_at(t, t->line, col,
"unindent does not match any outer indentation level");
return false;
}
return true;
}
indentation() does not return tokens. It records in pending how many are
owed: +1 for an INDENT, -n for n DEDENTs. next_token() pays them out
one per call before it scans anything else:
Token next_token(Tokenizer *t)
{
if (t->error)
return error_token(t);
if (t->at_line_start) {
t->at_line_start = false;
if (!indentation(t))
return error_token(t);
}
if (t->pending > 0) {
t->pending--;
return emit(t, make(t, TOK_INDENT, t->line_start, t->cur));
}
if (t->pending < 0) {
t->pending++;
return emit(t, make(t, TOK_DEDENT, t->cur, t->cur));
}
An INDENT spans the leading whitespace and a DEDENT is empty, at the
position of the first token of the line that caused it. Those are the
positions CPython reports too.
The figure steps through the tokenizer on the file above. Each frame is one step: a line measured, a token emitted, a line skipped. It shows the source with the current position under a caret, the indentation stack, the open brackets, and the tokens so far.
The tokenizer running over an eight-line Python function: for each step, the source with a caret at the current position, the indentation stack, the open brackets and the tokens emitted so far. (This figure steps through a recorded run; it needs JavaScript.)
Recorded with minipy --trace examples/indent.py at tag lesson-01. The
repository’s make test checks that the trace still comes out identical
(tests/traces/indent.json).
Lines that do not count
A line that holds only spaces, or spaces and a comment, produces no tokens,
and its indentation is not measured. The loop at the top of indentation()
skips such lines before it compares anything. Without that rule a comment at
column 0 inside a function would close the function: in the example, line 5
would pop both 8 and 4. With it, the comment is invisible, and the DEDENT
comes when line 7 starts at column 4.
The same rule explains why a block cannot end with a blank line in a file: blank lines are skipped, so only the next line with code in it can close a block.
CPython calls such a line a blankline
(lexer.c#L507-L528).
It makes two exceptions, both for the interactive prompt, where for example
an empty line ends a compound statement. minipy has no prompt yet.
Inside brackets, newlines do not count
A list, a call or a dict can spread over several lines:
x = {"a": [1, (2,
3)],
"b": 4}
y = 5
Python ignores line breaks while a bracket is open, and the indentation of
the continuation lines along with them. minipy keeps a stack of open brackets
for this, brackets[] and nesting. When the scanner meets a newline while
nesting > 0, it skips the newline and keeps scanning on the next line:
/* Skip spaces and a comment. Inside brackets a newline is skipped too:
the logical line goes on, and the next line's indentation is not
measured. */
for (;;) {
while (*t->cur == ' ' || *t->cur == '\t')
t->cur++;
if (*t->cur == '#')
while (t->cur < t->end && *t->cur != '\n')
t->cur++;
if (*t->cur != '\n' || t->nesting == 0)
break;
step(t, (Step){ .kind = STEP_JOIN, .line = t->line, .col = column(t, t->cur) });
next_line(t);
}
at_line_start is set only by a real NEWLINE, so a continuation line never
reaches indentation(). Three physical lines become one logical line:
$ ./minipy --tokens tests/cases/brackets.py
1,0-1,1: NAME 'x'
1,2-1,3: EQUAL '='
1,4-1,5: LBRACE '{'
1,5-1,8: STRING '"a"'
1,8-1,9: COLON ':'
1,10-1,11: LSQB '['
1,11-1,12: NUMBER '1'
1,12-1,13: COMMA ','
1,14-1,15: LPAR '('
1,15-1,16: NUMBER '2'
1,16-1,17: COMMA ','
2,4-2,5: NUMBER '3'
2,5-2,6: RPAR ')'
2,6-2,7: RSQB ']'
2,7-2,8: COMMA ','
3,8-3,11: STRING '"b"'
3,11-3,12: COLON ':'
3,13-3,14: NUMBER '4'
3,14-3,15: RBRACE '}'
3,15-3,16: NEWLINE '\n'
4,0-4,1: NAME 'y'
4,2-4,3: EQUAL '='
4,4-4,5: NUMBER '5'
4,5-4,6: NEWLINE '\n'
5,0-5,0: ENDMARKER ''
Lines 2 and 3 are indented by 4 and 8, and no INDENT appears. Since the
stack records which bracket is open, the tokenizer can also check that each
closing bracket matches: x = (1] stops with “closing parenthesis ‘]’ does
not match opening parenthesis ‘(’”, and a file that ends with a bracket still
open reports “’(’ was never closed” at the bracket. Both messages are
CPython’s. The first comes from its tokenizer
(lexer.c#L1267-L1328),
the second from the parser’s error handling, which reads the tokenizer’s
bracket stack when the input ends
(pegen_errors.c#L14-L19).
When a dedent lands between levels
Here the second line opens a block at column 8, and the third goes back to column 4:
if x:
a = 1
b = 2
Popping 8 leaves 0 on top, and 4 is not 0. The line closes the block at 8
without returning to any block that is still open, so there is no sequence of
DEDENTs that describes it. Both tokenizers stop there:
$ ./minipy --tokens examples/bad-dedent.py
1,0-1,2: NAME 'if'
1,3-1,4: NAME 'x'
1,4-1,5: COLON ':'
1,5-1,6: NEWLINE '\n'
2,0-2,8: INDENT ' '
2,8-2,9: NAME 'a'
2,10-2,11: EQUAL '='
2,12-2,13: NUMBER '1'
2,13-2,14: NEWLINE '\n'
examples/bad-dedent.py:3:5: error: unindent does not match any outer indentation level
$ python3 - < examples/bad-dedent.py
File "<stdin>", line 3
b = 2
^
IndentationError: unindent does not match any outer indentation level
The tokenizer running over a three-line file whose last line dedents to column 4, between the open levels 0 and 8: the stack pops 8, the top becomes 0, and the tokenizer stops with an error. (This figure steps through a recorded run; it needs JavaScript.)
Recorded with minipy --trace examples/bad-dedent.py at tag lesson-01
(tests/traces/bad-dedent.json).
The message is the same, and the column is not. minipy points at the start
of b (column 5, counting from 1 as Python’s error columns do). CPython
points just past the end of the line. In
lexer.c#L559-L563
it sets the error code E_DEDENT and moves its read position to the end of
the buffered line (tok->cur = tok->inp) before returning. The parser turns
E_DEDENT into the IndentationError in
pegen_errors.c#L45-L47.
With bcd in place of b = 2 the line is 7 characters long and CPython
reports column 8, so the column follows the line’s length rather than the
token.
How CPython’s tokenizer does it
In 3.15 the tokenizer is split into two directories.
Parser/lexer/
does the scanning: lexer.c, with state.h for the state it keeps.
Parser/tokenizer/
feeds it input from a file, a string, UTF-8 text or a readline function
(file_tokenizer.c, string_tokenizer.c, utf8_tokenizer.c,
readline_tokenizer.c). The indentation logic is at the top of
tok_get_normal_mode()
(lexer.c#L459).
Its state is the stack indstack[MAXINDENT] with indent as the index of
the top, and pendin, the number of INDENTs (positive) or DEDENTs
(negative) still owed
(state.h#L89-L93).
minipy’s indents, depth and pending are the same three things.
MAXINDENT is 100 and MAXLEVEL, the limit on open brackets, is 200
(state.h#L6-L7).
minipy uses the same limits.
The comparison reads almost line for line like minipy’s (lexer.c#L538-L567):
else if (col > tok->indstack[tok->indent]) {
/* Indent -- always one */
if (tok->indent+1 >= MAXINDENT) {
tok->done = E_TOODEEP;
tok->cur = tok->inp;
return MAKE_TOKEN(ERRORTOKEN);
}
if (altcol <= tok->altindstack[tok->indent]) {
return MAKE_TOKEN(_PyTokenizer_indenterror(tok));
}
tok->pendin++;
tok->indstack[++tok->indent] = col;
tok->altindstack[tok->indent] = altcol;
}
else /* col < tok->indstack[tok->indent] */ {
/* Dedent -- any number, must be consistent */
while (tok->indent > 0 &&
col < tok->indstack[tok->indent]) {
tok->pendin--;
tok->indent--;
}
if (col != tok->indstack[tok->indent]) {
tok->done = E_DEDENT;
tok->cur = tok->inp;
return MAKE_TOKEN(ERRORTOKEN);
}
if (altcol != tok->altindstack[tok->indent]) {
return MAKE_TOKEN(_PyTokenizer_indenterror(tok));
}
}
The part minipy leaves out is altcol. CPython measures each line twice
(lexer.c#L478-L486).
col treats a tab as a move to the next multiple of 8 (tabsize, set from
TABSIZE in state.c#L9),
and altcol treats it as one column (ALTTABSIZE is 1,
lexer.c#L10).
A second stack, altindstack, holds the altcol of each level. If the two
measures disagree about whether a line is deeper, level or shallower, the
meaning of the file depends on the width of a tab, and CPython reports
TabError instead of guessing
(helpers.c#L110-L116).
minipy rejects tabs in indentation outright; doing it CPython’s way is the
first exercise below.
Newlines inside brackets are handled where the newline is read
(lexer.c#L763-L787).
tok->level is the bracket depth, and blankline is set when the line held
nothing but a comment:
if (c == '\n') {
tok->atbol = 1;
if (blankline || tok->level > 0) {
if (tok->tok_extra_tokens) {
if (tok->comment_newline) {
tok->comment_newline = 0;
}
p_start = tok->start;
p_end = tok->cur;
return MAKE_TOKEN(NL);
}
goto nextline;
}
For the parser, tok_extra_tokens is off and the newline is skipped with
goto nextline. Indentation is measured only when tok->level == 0
(lexer.c#L529),
so a continuation line inside brackets never changes the stack.
Comparing with CPython
python3 -m tokenize runs this same C tokenizer, with tok_extra_tokens
switched on: tokenize() and generate_tokens() both pass
extra_tokens=True
(tokenize.py#L499,
#L507).
In that mode the tokenizer also reports what the parser never sees: every
COMMENT, and an NL for each newline that does not end a logical line.
tokenize() adds an ENCODING token of its own before the first one
(tokenize.py#L493-L499).
On the example file:
$ python3 -m tokenize -e examples/indent.py
0,0-0,0: ENCODING 'utf-8'
1,0-1,3: NAME 'def'
1,4-1,5: NAME 'f'
1,5-1,6: LPAR '('
1,6-1,7: NAME 'n'
1,7-1,8: RPAR ')'
1,8-1,9: COLON ':'
1,9-1,10: NEWLINE '\n'
2,0-2,4: INDENT ' '
2,4-2,6: NAME 'if'
2,7-2,8: NAME 'n'
2,8-2,9: COLON ':'
2,9-2,10: NEWLINE '\n'
3,0-3,8: INDENT ' '
3,8-3,14: NAME 'return'
3,15-3,16: LSQB '['
3,16-3,17: NAME 'n'
3,17-3,18: COMMA ','
3,18-3,19: NL '\n'
4,2-4,3: NAME 'n'
4,4-4,5: STAR '*'
4,6-4,7: NUMBER '2'
4,7-4,8: RSQB ']'
4,8-4,9: NEWLINE '\n'
5,0-5,16: COMMENT '# only a comment'
5,16-5,17: NL '\n'
6,0-6,1: NL '\n'
7,4-7,4: DEDENT ''
7,4-7,6: NAME 'if'
7,7-7,8: NAME 'n'
7,8-7,9: COLON ':'
7,9-7,10: NEWLINE '\n'
8,0-8,8: INDENT ' '
8,8-8,14: NAME 'return'
8,15-8,16: LSQB '['
8,16-8,17: RSQB ']'
8,17-8,18: NEWLINE '\n'
9,0-9,0: DEDENT ''
9,0-9,0: DEDENT ''
9,0-9,0: ENDMARKER ''
Remove the ENCODING, COMMENT and NL lines and what is left is minipy’s
output, byte for byte. make compare does that for all 33 test inputs. Of
the 13 that minipy accepts, 11 come out the same, and the other two differ
on purpose. In its diffs, < lines are CPython’s and > lines minipy’s.
The first:
DIFFERS tests/cases/non-ascii-string.py
3,6c3,6
< 1,4-1,7: STRING '"é"'
< 1,8-1,9: PLUS '+'
< 1,10-1,11: NAME 'x'
< 1,11-1,12: NEWLINE '\n'
---
> 1,4-1,8: STRING '"é"'
> 1,9-1,10: PLUS '+'
> 1,11-1,12: NAME 'x'
> 1,12-1,13: NEWLINE '\n'
The file is s = "é" + x. é is two bytes in UTF-8, and minipy counts
columns in bytes, so everything after it is one column further right. CPython’s
C tokenizer counts bytes too: tok_nextc() adds one to col_offset per
byte (lexer.c#L64-L70),
and the AST stores byte offsets as well
(Python.asdl#L56).
ast.parse on this file gives the name x a col_offset of 11, the same as
minipy. The tokenize module is the one that converts, to character offsets,
in _get_col_offsets()
(Python-tokenize.c#L206-L238).
The second is crlf.py, a file with Windows line endings:
DIFFERS tests/cases/crlf.py
4c4
< 1,5-1,7: NEWLINE '\r\n'
---
> 1,5-1,6: NEWLINE '\n'
8c8
< 2,5-2,7: NEWLINE '\r\n'
---
> 2,5-2,6: NEWLINE '\n'
11c11
< 3,5-3,7: NEWLINE '\r\n'
---
> 3,5-3,6: NEWLINE '\n'
minipy turns each \r\n into \n when it reads the file, so the rest of
the tokenizer only ever sees \n. CPython’s lexer reads a \r before the
newline as part of it
(lexer.c#L759-L761),
and tokenize shows that NEWLINE as '\r\n'
(Python-tokenize.c#L317-L326).
The token kinds and every other position are the same.
Thirteen files are not much evidence for “the same”, so make fuzz also
builds random snippets from the pieces minipy handles: names, numbers,
strings, operators, brackets, spaces, tabs, comments and newlines with
various indentation. For each snippet minipy accepts, it diffs minipy’s
tokens with CPython’s. Most snippets are not valid Python, which is fine: the
point is to find input that the two split differently.
$ make -s fuzz
seed 1: 4000 snippets, minipy accepted 1344, 0 differ
seed 2: 4000 snippets, minipy accepted 1359, 0 differ
seed 3: 4000 snippets, minipy accepted 1348, 0 differ
The snippets are ASCII with \n line endings, so they cannot hit the two
differences above, nor a third that they missed for the same reason: a
carriage return on its own. CPython ends a line there: a file holding
# c\rprint(1) and a newline prints 1, whether it is run as a file, read
from stdin or passed to compile() as bytes. minipy only turns \r\n into
\n, so a lone \r stays an ordinary byte, and minipy reads the whole line
as one comment: its only token is ENDMARKER. The fix is the seventh
exercise.
Extra-tokens mode changes more than the output. It also turns off the
bracket checks: the “unmatched” error is raised only
if (!tok->tok_extra_tokens && !tok->level)
(lexer.c#L1290-L1292),
and a mismatched pair is let through when tok_extra_tokens is set
(lexer.c#L1312-L1314).
So tokenize accepts a file that Python itself rejects:
$ python3 -m tokenize -e tests/cases/err-mismatch.py
0,0-0,0: ENCODING 'utf-8'
1,0-1,1: NAME 'x'
1,2-1,3: EQUAL '='
1,4-1,5: LPAR '('
1,5-1,6: NUMBER '1'
1,6-1,7: RSQB ']'
1,7-1,8: NEWLINE '\n'
2,0-2,0: ENDMARKER ''
$ python3 - < tests/cases/err-mismatch.py
File "<stdin>", line 1
x = (1]
^
SyntaxError: closing parenthesis ']' does not match opening parenthesis '('
minipy reports that error, at the same line and column as compile(). For
error cases, then, make compare sets minipy beside both tokenize and
compile(). A few other details of the tokenize output are adjustments
the module makes, not things the C tokenizer reports to the parser. The
DEDENTs at the end of the file and the ENDMARKER are moved to column 0 of
the line after the last one, and a NEWLINE invented for a file without a
final newline is shown with empty text
(Python-tokenize.c#L277-L327).
minipy prints the same, so the two can be diffed. When the file lacks a final
newline, minipy adds one, as CPython’s input readers do
(readline_tokenizer.c#L84-L91).
The remaining differences are the parts of Python that minipy does not take
yet. Each one is an error rather than a wrong split, so that the tests and
the fuzzer found no such input split differently from CPython. The 20 error
cases in tests/cases/ fall into three groups:
- Same error as CPython: an inconsistent dedent, mismatched or unmatched
brackets, a bracket never closed, an unterminated string,
012,1abc, and more than 99 nested blocks. The messages are CPython’s, minus the hint about0oon leading zeros. - Both reject, with different messages: a lone
!or$. minipy says “invalid character”, and CPython’s parser says “invalid syntax”. - Valid Python that minipy rejects for now: tabs in indentation,
backslash continuation, triple-quoted strings, string prefixes such as
f"...", hexadecimal, octal and binary numbers,1_000,2j, and non-ASCII names.
Try it yourself
Clone the repository, check out lesson-01, and keep make test and
make compare passing as you go.
Tabs, CPython’s way. Measure every line twice, with tab stops of 8 and of 1, keep a second stack, and report
inconsistent use of tabs and spaces in indentationwhen the two comparisons disagree. CPython rejects this file, where line 2 starts with a tab and line 3 with eight spaces:$ printf 'if x:\n\ty = 1\n z = 2\n' > tabs.py $ python3 - < tabs.py File "<stdin>", line 3 z = 2 TabError: inconsistent use of tabs and spaces in indentationWork out by hand why: both lines are at column 8, but at columns 1 and 8 by the second measure.
Backslash continuation. A
\at the end of a line joins it to the next. Decide which line’s indentation counts; CPython’s answer is the comment at lexer.c#L490-L495.Triple-quoted strings. They can span lines, so a
STRINGtoken’send_lineis no longer itsline. Check that the tokens after one keep their line numbers, and that--tracestill marks the right line.More number forms. Add
0x,0oand0bliterals and underscores between digits. Find which placements of_CPython rejects and match its messages.Columns in characters. Add a flag that prints character columns, so that
non-ascii-string.pymatchestokenizetoo. Which of the two should the parser see when it reports an error?Limits.
MAX_INDENTis 100, but both tokenizers accept at most 99 nested blocks: 99 levels pass, andtests/cases/err-too-deep.py, with 100, fails. Where does the hundredth slot of the stack go?Lone carriage returns. Make
read_source()insrc/main.ctreat a\rthat is not followed by\nthe way CPython does, or reject it with an error. Add the two cases# c\rprint(1)ands = "a\rb"totests/cases/, and teachtests/fuzz-cpython.pyto produce them.
Sources
minipy, tag lesson-01:
src/tokenizer.c, src/token.h, src/trace.c, tests/run.sh,
tests/compare-cpython.sh, tests/fuzz-cpython.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/Tokens token names
- Grammar/python.gram#L266-L267
block - Parser/pegen.c#L162-L185 keywords looked up by the parser
- Parser/pegen.c#L249 the parser asks for a token
- Parser/parser.c#L20-L21 the generated keyword table
- Parser/lexer/state.h#L6-L7
MAXINDENT,MAXLEVEL - Parser/lexer/state.h#L89-L108
indstack,pendin,level,altindstack - Parser/lexer/state.c#L9
TABSIZE - Parser/lexer/lexer.c#L10
ALTTABSIZE - Parser/lexer/lexer.c#L59-L96
tok_nextc - Parser/lexer/lexer.c#L459-L592 measuring indentation, blank lines, pending tokens
- Parser/lexer/lexer.c#L759-L787
\r\n,NEWLINEandNL - Parser/lexer/lexer.c#L1267-L1328 the bracket stack
- Parser/tokenizer/helpers.c#L110-L116
_PyTokenizer_indenterror - Parser/tokenizer/readline_tokenizer.c#L84-L91 the added final newline
- Parser/pegen_errors.c#L14-L19 “was never closed”
- Parser/pegen_errors.c#L45-L63
E_DEDENT,E_TABSPACE,E_TOODEEPmessages - Parser/Python.asdl#L56 byte offsets in the AST
- Python/Python-tokenize.c#L206-L238 byte to character columns
- Python/Python-tokenize.c#L277-L327 end-of-file positions and
NEWLINEtext - Lib/tokenize.py#L473-L507
tokenize(), itsENCODINGtoken, andgenerate_tokens()
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.