Chapter 9 of 1141 min read
Python without Python
The self-hosted track: a tokenizer and parser written in assembly that read Python source without CPython, checked byte for byte against Python references: a tokenizer that states the same rules, and a tree printer built on CPython's own parser.
aython's compiler reads Python with CPython's own ast module, so translating a program still needs CPython installed. The self-hosted track replaces that reading step with assembly: a tokenizer and a recursive-descent parser that turn source bytes into a syntax tree with no Python involved, plus a first emitter that turns straight-line trees back into assembly. This chapter shows how each piece works, and how CI checks it, byte for byte, against a Python reference on every corpus file.
The track is four assembly programs under parser/, each a standalone executable with its own main:
| File | Lines | Reads | Writes | What it is for |
|---|---|---|---|---|
dump.s |
103 | a file | the same bytes | Proves the file reading: open, a chunked read loop, write and the error exits |
tok.s |
814 | a .py file |
one token per line | The tokenizer: bytes to NAME, INT, STR, OP and layout markers |
parse.s |
9455 | a .py file |
one s-expression per statement | The parser and tree printer: tokens to a tree in memory, printed in a fixed text form |
emit.s |
2368 | that text form | assembly | The emitter for straight-line programs: tree text to a .s file the runtime links with |
Together they are 12740 lines, against 16217 in runtime.s. None of them is part of aython run, which still uses the Python frontend described in From source to a checked program. The track is a second, independent reader of the same programs.
flowchart LR
src["prog.py"]
subgraph host["host frontend (Python)"]
ast["ast.parse"] --> check["frontend.py<br/>subset check"] --> cg["codegen.py"]
end
subgraph self["self-hosted track (assembly)"]
tok["tok.s<br/>tokens"] --> parse["parse.s<br/>tree + sexp"] --> emit["emit.s<br/>straight lines only"]
end
src --> ast
src --> tok
cg --> asm1["prog.s"]
emit --> asm2["prog_emit.s"]
asm1 --> link["as + cc with runtime.s"]
asm2 --> link
class tok,parse,emit accent
class ast py
Why a second parser #
docs/parser-design.md states the goal in one line: the host frontend parses with Python’s ast, so the project still needs CPython to translate anything, and the track removes that. It also states what the track will not do, and those limits shape everything below:
- No error recovery. The first bad byte or token stops the program with one line on stderr and exit status 1, the same policy as the runtime’s aborts.
- Nothing outside the subset’s grammar. The plan said exactly what
frontend.pyaccepts, no more. In the building the tree printer became purely syntactic: it refuses shapes outside the subset’s grammar withunsupported, but prints programs the frontend refuses for semantic reasons, such as a call to an unknown function (see When the parser refuses below). - No general code generation. Only straight-line programs are lowered to assembly. Everything with a branch, a loop or a call still goes through
codegen.py.
The prerequisites were the runtime’s strings (for names) and dicts (for symbol tables), which is why the track could start once those existed. In practice the tokenizer and parser use neither: they keep pointers into the file’s bytes and compare them byte by byte, as the rest of this chapter shows.
The contract: bytes against a Python reference #
Nobody reads ten thousand lines of parser assembly to decide whether it is right. The track uses the same habit as the judge: pick an oracle, then require identical bytes. For the tokenizer and the parser the oracle is a Python program in the repository:
| Implementation under test | Reference | What must match | What the reference is built on |
|---|---|---|---|
parser/tok.s |
aython tokdump (tokdump.py) |
stdout byte for byte, on every corpus file | Hand-written rules that mirror tok.s line for line. Its docstring says any rule change must land in both |
parser/parse.s |
aython sexpdump (sexpdump.py) |
stdout byte for byte when both accept; only the exit status when both refuse | CPython’s ast.parse, then a printer that spells the tree in the canonical form |
parser/emit.s |
codegen.py through parser/emitdiff.sh |
the compiled program’s stdout and exit status, not the assembly | The host compiler itself |
The two references are not alike. tokdump is not CPython’s tokenizer: it implements exactly the rules tok.s implements, so the check proves that the assembly does what the Python says, not that either agrees with CPython. sexpdump does start from CPython (ast.parse), so for the parser the check reaches all the way to CPython’s own grammar, over the files in the corpus.
Reading a file: dump.s #
dump.s is the smallest program in the track and the only one with no decisions in it. It opens argv[1] with libc open, reads it in 8192-byte chunks into a buffer in .bss, writes each chunk to stdout, and closes the file. It can only copy bytes or fail with a message, so it was built first: it settles file descriptors, the read loop, short writes and error exits before anything depends on them. CI checks it by copying dump.s itself, by copying 3000 lines of seq output (several chunks), and by requiring a non-zero exit for a missing file and for no argument at all.
The tokenizer, tok.s #
tok.s reads the whole file into memory, scans it once, line by line, into an array of tokens, then prints the array, one token per line.
Memory: one arena, no copies #
Like the runtime, the tokenizer asks libc mmap for one 64 MiB block of memory (an arena) and hands out pieces of it by moving a pointer forward. The file’s bytes are read straight into the start of the arena. The token array starts at the next 8-byte boundary after the last byte, and grows from there:
arena_base file_end tok_base arena_ptr
| the file's bytes, as read |pad| token 0 | token 1 | token 2 | ... | free ...
32 bytes 32 bytes
A token is four 8-byte words, written by emit_token:
parser/tok.slines 648–667emit_token: # append one 32-byte token: rdi kind, rsi ptr, rdx len
mov rax, [rip + arena_ptr] # rax = free slot for the token
lea rcx, [rax + 32] # rcx = cursor past the slot
cmp rcx, [rip + arena_end] # past the arena?
ja .Lem_oom # yes: out of memory, exit 1
push rdi # save the kind (restored below: args survive the call)
push rsi # save the text pointer (callers keep scanning with it)
push rdx # save the text length (restored below)
mov [rax], rdi # +0 kind id
mov [rax + 8], r14 # +8 source line (caller keeps it in r14)
mov [rax + 16], rdx # +16 text length
mov [rax + 24], rsi # +24 text pointer (into the file image)
mov [rip + arena_ptr], rcx # bump past the new token
inc qword ptr [rip + tok_count] # one more token to replay
pop rdx # restore the text length
pop rsi # restore the text pointer
pop rdi # restore the kind id
ret # back to the scan (rax/rcx clobbered only)
.Lem_oom: # token array overran the arena
jmp .Lno_memory # same message and exit as mmap failure
| Offset | Field | Meaning |
|---|---|---|
| +0 | kind | 1 NAME, 2 INT, 3 STR, 4 OP, 5 NEWLINE, 6 INDENT, 7 DEDENT, 8 EOF |
| +8 | line | The 1-based source line, which r14 carries through the whole scan |
| +16 | length | Bytes of text; 0 for the layout markers |
| +24 | pointer | Where the text starts inside the file image. The text is never copied |
The last row is the important one. A NAME token for fib is a pointer to the three bytes f, i, b where they sit in the file, plus the length 3. The parser later compares names by walking those bytes (.Ptok_is in parse.s), and the tree printer writes them out from the same place. Nothing in the track allocates a string.
emit_token also shows the calling convention at work: the kind arrives in rdi, the text pointer in rsi and the length in rdx, the first three argument registers. The routine pushes and pops those three so that its caller can keep scanning with them, and clobbers only rax and rcx, which a caller may never rely on anyway.
Classifying bytes #
The scan looks at the first byte of each token and jumps on what it is: a letter or _ starts a NAME, a digit starts an INT, a quote starts a STR, and anything in the punctuation set is an OP. Space and tab between tokens are skipped; # ends the line’s code. Every other byte, including any byte at or above 0x80, stops the program.
The rules are deliberately small, and each one leaves work for the parser:
- Keywords are names.
def,ifandreturncome out asNAME def,NAME if,NAME return. The parser tells them apart by comparing bytes. - Digits only. An
INTis a run of digits and nothing else, so1.5is three tokens,INT 1,OP .,INT 5, and1e-300is four. The parser glues adjacent pieces back into one float literal by pointer arithmetic, which works because each token points into the file and “adjacent” means “this token ends where the next one starts”.
parser/tok.slines 309–329.Lint: # INT token starts at rbx
mov r8, rbx # r8 = end hunter m (survives emit_token)
inc r8 # first digit already classified
.Lint_loop: # extend over digits only (dots split, like 3 . 14)
cmp r8, rbp # past the line?
jae .Lint_emit # whole tail is digits
mov cl, [r8] # cl = candidate byte
cmp cl, 0x30 # below 0?
jb .Lint_emit # ends the number
cmp cl, 0x39 # at or below 9?
ja .Lint_emit # ends the number
inc r8 # one more digit
jmp .Lint_loop # check the next byte
.Lint_emit: # digits are [rbx, r8)
mov edi, 2 # INT kind id
mov rsi, rbx # text starts here
mov rdx, r8 # rdx = end hunter
sub rdx, rbx # rdx = byte length
call emit_token # append (r8 survives: only rax/rcx die)
mov rbx, r8 # past the digits
jmp .Ltok # next token
- Strings keep their escapes. A
STRtoken’s text is what is between the quotes, byte for byte, with a backslash and the byte after it skipped as a pair so that\"does not end the string. Both quote styles give the same kind. Strings must end on the line they start, so a triple-quoted string is three tokens (STRempty,STR a,STRempty). - Few two-byte operators. Only
//,==,!=,<=,>=,+=,-=,*=are fused, checked by loading two bytes at once (mov ax, [rbx]) and comparing against one 16-bit constant each. Everything else is single bytes:**is twoOP *tokens,<<=isOP <followed byOP <=, and->isOP -thenOP >. The parser accepts such a pair only when the second token starts exactly where the first ends, so2 * * 3is refused like CPython refuses it. - Brackets pause the layout.
r15counts open(,[and{. While it is above zero, the end of a line is not aNEWLINEand indentation is ignored, as in CPython, so a list may span lines.
Indentation becomes markers #
Python’s blocks are its indentation, and a parser wants explicit block boundaries. The tokenizer converts one into the other with a stack of indentation widths, starting with one entry, 0. At the first code byte of each line it measures the width (the cursor minus the line’s start) and compares it with the top of the stack:
- Deeper: push the new width and emit one
INDENT. - The same: emit nothing.
- Shallower: pop and emit one
DEDENTper level until the width matches. If it falls between two levels, the line is refused withparser: bad dedent.
At the end of the file one DEDENT is emitted for every level still open. Blank lines never reach this code, a comment-only line leaves it at the # check before the stack is touched, and a tab in the indentation is refused outright, because a tab has no fixed width.
Here is that code, stepped through for the program below. Its lines are 0, 4, 8, 4 and 0 spaces deep:
tests/mvp/pass_fn_fib.pylines 1–6# mvp: pass
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(10))
# mvp: pass: the first non-space byte is#, so the line is a comment. It jumps to.Lblankand produces no tokens; the stack is untouched.def fib(n):starts in column 1. The width is the first code byte’s address minus the line’s start (r13): 0.- The top of the stack is the entry at
idepth - 1, read with a scaled index (rcx*8 - 8). 0 equals 0:je .Lscan, no marker, straight on to the tokens of the line. if n < 2:is 4 spaces deep. 4 is greater than the top, 0:jg .Lpush..Lpushchecks there is room (64 levels above the base), stores 4 atindent_stack[idepth], counts it, and emits kind 6,INDENT, with no text.return nis 8 deep, deeper than 4: one more push and one moreINDENT.return fib(n - 1) + ...is 4 deep. 4 is less than the top, 8, so neither jump is taken and execution falls into.Lpop..Lpopsaves the width on the machine stack (the call may clobberrax), emits kind 7,DEDENT, and restores it.- One level is forgotten (
idepth3 to 2), so the new top is 4. 4 equals 4: the line belongs to this level,jmp .Lscan. The 8 is still in memory but no longer counted. print(fib(10))is back at 0: one pop, oneDEDENT, the top is 0, equal. At the end of the file only the base is left, so no moreDEDENTs follow, and the array ends withEOF.
See it on real programs #
The figure below runs the reference over a few corpus programs at build time. Every token is shown with the bytes it came from, and every top-level statement with the tree the parser must print for it. These tokens are aython tokdump’s output, not tok.s’s: this site is built without assembling anything. CI requires the two to be byte-identical on every one of these files.
float_imm for the three-token float and fstring for a NAME f followed by a STR.When the tokenizer refuses #
The tokenizer stops at the first problem, with one line on stderr and exit status 1. These are its messages, read from tok.s’s read-only data:
| Message | When |
|---|---|
parser: cannot open |
open returned -1 (no such file, no permission) |
parser: cannot read |
read returned -1 |
parser: cannot write |
a write to stdout fell short |
parser: out of memory |
mmap failed, or the file or the tokens overran the 64 MiB arena |
parser: bad byte (line N) |
a byte that starts no token, such as a backslash, $, ? or a carriage return (files are LF-only) |
parser: bad string (line N) |
a string still open at the end of its line |
parser: bad dedent (line N) |
a dedent that lands between two open levels |
parser: tab indent (line N) |
a tab in the indentation |
parser: unclosed bracket (line N) |
a bracket still open at the end of the file |
parser: non-ascii byte (line N) |
a byte at or above 0x80, anywhere |
parser: bad indent (line N) |
more than 64 levels of indentation |
The parser, parse.s #
parse.s begins with a copy of tok.s: its first 393 lines are identical, line for line, to tok.s’s. Where tok.s jumps to .Ldump to print the token array, parse.s jumps to .Pparse instead, and parses it.
Nodes in the arena #
The parser builds a tree of nodes in the same arena, after the tokens. Every node has the same header, and its children follow it:
parser/parse.slines 977–1001# Node layout (bump-allocated in the arena, 8-byte aligned):
# +0 tag : u64 node kind (1 BLOCK .. 53 CMPCHAIN, see .Pprint dispatch)
# +8 info : u64 high 32 = aux (op id, or text length for leaves),
# low 32 = source line of the leading token
# +16 nch : u64 child count
# +24 ch[] : u64 child pointers (nch entries); leaves carry text
# pointer/length as ch[0]/ch[1] instead. A zero child marks
# an absent part (slice `_`, bare-except `*`). CLASS carries
# two children (name, body), three with one base (name,
# base, body), or four-plus with N bases (name, base...,
# body: each base a NAME leaf or a nested ATTR). CMPCHAIN
# carries nch operands as children plus its nch-1 op ids as
# raw qwords right after the children (reserved by asking
# .Palloc for 2*nch-1 slots, then narrowing nch back).
# Parser functions take the token cursor in rdi and the array end in
# r12 (threaded through every call, never reloaded), return the node
# in rax (0 = refused, rdx = offending token) and the new cursor in
# rdx. Refusals set err_ptr/err_len, then return 0 up the chain.
# Aux op ids: binop 1+ 2- 3* 4/ 5// 6% 7| 8^ 9& 10** 11<< 12>>;
# unary 1- 2not 3~; boolop 1and
# 2or; cmp 1< 2<= 3== 4!= 5> 6>= 7is 8is-not 9in 10not-in; cmpchain aux is
# the op count (children are the operands, op ids trail them); aug 1+= 2-= 3*= 4**= 5/= 6//= 7%= 8|= 9^= 10&= 11<<= 12>>=.
# from: aux is the leading-dot count (0 for absolute imports, 1 for
# "from .", 2 for "from .."); a missing module ("from . import m")
# spells an empty NAME leaf, so the module slot stays in place.
.Palloc makes one. It is a bump allocation exactly like the runtime’s: the size is 24 + 8 × children, the pointer moves forward, and there is no free. The whole program dies at exit, so nothing is ever released.
parser/parse.slines 1095–1108.Palloc: # bump-allocate one node: rdi tag, rsi line, rdx aux, rcx n
lea rax, [rcx*8 + 24] # rax = header plus children
mov r8, [rip + arena_ptr] # r8 = free node address
lea r9, [r8 + rax] # r9 = cursor past the node
cmp r9, [rip + arena_end] # past the arena?
ja .Lno_memory # yes: spell out-of-memory, exit 1
mov [rip + arena_ptr], r9 # bump past the new node
mov [r8], rdi # +0 tag id
shl rdx, 32 # aux moves to the high half
or rdx, rsi # low half keeps the source line
mov [r8 + 8], rdx # +8 info word
mov [r8 + 16], rcx # +16 child count
mov rax, r8 # rax = the node
ret # back to the builder (r8/r9 clobbered only)
Note how the info word is built: the operator id (the aux) goes into the high 32 bits with shl rdx, 32, and the source line is OR-ed into the low 32. One 8-byte load later gives both. The error path reads the line back out of a token the same way, with a 32-bit load (mov eax, [rax + 8]).
The node kinds, read from the tree printer’s dispatch in .Pprint: 1 BLOCK, 2 ASSIGN, 3 AUG, 4 EXPRST, 5 IF, 6 WHILE, 7 FOR, 8 DEF, 9 RETURN, 10 DEL, 11 TRY, 12 HANDLER, 13 RAISE, 14 NAME, 15 NUM, 16 FLOAT, 17 STR, 18 BOOL, 19 NONE, 20 BINOP, 21 UNARY, 22 BOOLOP, 23 CMP, 24 CALL, 25 ATTR, 26 KW, 27 LIST, 28 TUPLE, 29 DICT, 30 PAIR, 31 INDEX, 32 SLICE, 33 LISTCOMP, 34 DICTCOMP, 35 COMP, 36 FSTR, 37 LIT, 38 FIELD, 39 DOC, 40 DEFAULT, 41 VARARG, 42 STAR, 43 KWONLY, 44 KWDEFAULT, 45 KWARG, 46 DSTAR, 47 AS, 48 IMPORT, 49 FROM, 50 CLASS, 51 ELSE, 52 PASS, 53 CMPCHAIN.
One routine per precedence level #
The parser is recursive descent: one routine per grammar rule, each calling the routine for the rule below it. For expressions, the rules are the precedence levels, loosest first, so a tighter operator is parsed deeper in the recursion and ends up deeper in the tree. The table is read from the code: for each level, the first other level its routine calls or jumps to.
| Level | Routine | Parses | Operands come from |
|---|---|---|---|
| 1 | .Por |
or |
.Pand |
| 2 | .Pand |
and |
.Pnot |
| 3 | .Pnot |
not |
.Pcmp |
| 4 | .Pcmp |
< <= == != > >= is in, chains |
.Pbor |
| 5 | .Pbor |
| |
.Pbxor |
| 6 | .Pbxor |
^ |
.Pband |
| 7 | .Pband |
& |
.Pshift |
| 8 | .Pshift |
<< >> |
.Padd |
| 9 | .Padd |
+ - |
.Pmul |
| 10 | .Pmul |
* / // % |
.Punary |
| 11 | .Punary |
unary - and ~ |
.Ppower |
| 12 | .Ppower |
** |
.Patom |
| 13 | .Patom |
names, literals, displays, then calls, .attr and [...] |
tokens |
The convention every routine follows is written once in parse.s, above .Pparse: the token cursor arrives in rdi, the end of the token array stays in r12 for the whole parse, and a routine returns the node in rax and the new cursor in rdx. A refusal returns 0 in rax with the offending token in rdx, and every caller passes the 0 straight up. Here is the level for + and -, in full:
parser/parse.slines 2317–2375.Padd: # parse +/- chains at rdi (left-associative)
push rbp # save rbp for the frame chain
mov rbp, rsp # rbp marks this frame
push rbx # rbx keeps the cursor
push r13 # r13d keeps the operator id
push r14 # r14 keeps the left node
push r15 # r15 keeps the right node
call .Pmul # rax = left, rdx = cursor past it
test rax, rax # left refused?
jz .Padd_fail # yes: unwind with 0
mov r14, rax # r14 = left node
mov rbx, rdx # rbx = cursor after the left side
.Padd_loop: # check for one more +/- term at rbx
cmp qword ptr [rbx], 4 # OP kind?
jne .Padd_done # no: the chain ends here
cmp qword ptr [rbx + 16], 1 # single-byte operator?
jne .Padd_done # no: the chain ends here
mov rax, [rbx + 24] # rax = operator text pointer
mov al, [rax] # al = the operator byte
cmp al, 0x2b # "+"?
je .Padd_plus # yes: augmented side below
cmp al, 0x2d # "-"?
jne .Padd_done # no: the chain ends here
mov r13d, 2 # r13d = aux id 2 for -
jmp .Padd_term # share the term path
.Padd_plus: # "+" at rbx
mov r13d, 1 # r13d = aux id 1 for +
.Padd_term: # r13d holds the aux id: parse the next term
lea rdi, [rbx + 32] # rdi = cursor past the operator
call .Pmul # rax = right, rdx = cursor past it
test rax, rax # right refused?
jz .Padd_fail # yes: unwind with 0
mov r15, rax # r15 = right node
mov rbx, rdx # rbx = cursor after the right side
mov esi, [r14 + 8] # esi = left line (low half of info)
mov rdi, 20 # rdi = tag BINOP
mov edx, r13d # rdx = aux operator id
mov rcx, 2 # rcx = two children
call .Palloc # rax = BINOP node (clobbers rdi/rsi/rdx/rcx only)
mov [rax + 24], r14 # child 0 = left
mov [rax + 32], r15 # child 1 = right
mov r14, rax # r14 = combined left side
jmp .Padd_loop # check for one more term
.Padd_done: # chain complete: r14 holds the sum, rbx the cursor
mov rax, r14 # rax = the sum node
mov rdx, rbx # rdx = cursor after the last term
pop r15 # restore r15
pop r14 # restore r14
pop r13 # restore r13
pop rbx # restore rbx
pop rbp # restore rbp
ret # back to the caller with the sum
.Padd_fail: # a sub-parse refused: rax = 0, rdx = offending token
pop r15 # restore r15
pop r14 # restore r14
pop r13 # restore r13
pop rbx # restore rbx
pop rbp # restore rbp
ret # back up the chain with 0 (rdx untouched)
Read it as a loop. It parses one term with .Pmul, keeps it in r14, and while the next token is a one-byte OP spelled + or -, parses another term, allocates a BINOP node (tag 20) with the old left side and the new term as children, and makes that the new left side. So a - b - c becomes (a - b) - c: left-associative, as in Python. The four callee-saved registers it uses (rbx, r13, r14, r15) are pushed on entry and popped on both exits, because .Pmul and .Palloc may be called many times in between and must not lose them.
.Ppower is the exception that proves the rule. Power is right-associative and binds tighter than unary minus on its left but not on its right, so its right operand is parsed with .Punary again. That is why -2**2 prints as (unary - (binop ** (num 2) (num 2))), which is -4, while 2**-1 is legal and prints as (binop ** (num 2) (unary - (num 1))).
Children of unknown number #
A block may hold any number of statements, a call any number of arguments. A node’s children are a fixed-size array, so the parser cannot allocate the node before it knows the count. It parks each finished child on a small stack in .bss (tmp_stack, 1024 entries), and when the list ends allocates the node with the right count and copies the pointers in. .Ptmp_mark remembers where a list started, .Ptmp_push parks a pointer, .Ptmp_get reads one back, .Ptmp_reset drops them. Nested lists each take their own mark, so an argument list inside a list display does not disturb it.
Printing the tree #
The tree is printed in a fixed text form, a canonical s-expression (sexp): one line per top-level statement, each node as (head child child ...), names and literals spelled out. .Pparse drives it: parse the whole program into one BLOCK, then print each child statement and a newline.
parser/parse.slines 1002–1029.Pparse: # tokens complete: parse the array, print the sexp, exit
mov rax, [rip + tok_base] # rax = first token
mov rdi, rax # rdi = parse cursor starts at the array
mov rax, [rip + tok_count] # rax = token count
imul rax, rax, 32 # rax = array byte size (32 bytes each)
add rax, [rip + tok_base] # rax = exclusive array end
mov [rip + tok_end], rax # remember the end for clamping errors
mov r12, rax # r12 threads the end through every parse call
call .Pprogram # rax = BLOCK node (0 = refused), rdx = cursor
test rax, rax # parse failed?
jz .Pparse_err # yes: spell err_ptr plus the line, exit 1
mov rbx, rax # rbx keeps the BLOCK node across print calls
mov r13, [rbx + 16] # r13 = statement count
xor r14d, r14d # r14 = statement index
.Pparse_loop: # print one sexp line per top-level statement
cmp r14, r13 # index past the block?
jae .Ldone # yes: exit 0 through the shared success path
mov rax, [rbx + 24 + r14*8] # rax = child statement node
mov rdi, rax # rdi = node to print
call .Pprint # print the inline sexp (preserves rbx/r12-r15)
mov rdi, 1 # stdout fd
lea rsi, [rip + ch_nl] # one newline byte
mov edx, 1 # one byte
call write_all # end the sexp line
test eax, eax # full line landed?
jnz .Lwrite_fail # no: spell cannot-write, exit 1
inc r14 # next statement
jmp .Pparse_loop # print it
The format is the contract with the reference. sexpdump produces the same lines from ast:
src/aython/sexpdump.py · dump_sourcelines 275–303def dump_source(source: str, filename: str) -> list[str]:
"""Parse source text into canonical sexp lines.
Args:
source: Full text of the candidate program.
filename: Name used in syntax-error line numbers only.
Returns:
One sexp string per top-level statement (bare ``x: T``
annotations spell no line and are dropped).
Raises:
SexpError: On the first refusal with its line number.
"""
try:
tree = ast.parse(source, filename=filename)
except SyntaxError as exc:
offender = exc.text or ""
if TRY_FINALLY_ELSE_MSG in (exc.msg or "") and offender.strip().startswith("else"):
raise _unsupported(exc.lineno or 1) from exc
raise _bad_token(exc.lineno or 1) from exc
lines = source.splitlines()
dumper = _Dumper(lines)
out: list[str] = []
for node in tree.body:
rendered = dumper.statement(node, 0)
if rendered is not None:
out.append(rendered)
return out
The sexp spells what is written, not what it means. elif has no node: it is an if inside the else block, exactly as ast represents it. An annotation is parsed and dropped, so x: int = 1 prints as (assign (name x) (num 1)), and a bare x: int prints no line at all. A docstring is (doc "...").
What the tokens leave for the parser #
Because the tokenizer is so plain, the parser does some lexical work:
- Floats are reassembled from adjacent
INT,OP .andNAMEtokens (in1e5, thee5is aNAME) and printed as one(float ...)leaf. - f-strings arrive as
NAME fimmediately followed by aSTR. The parser re-tokenizes the string’s{...}fields from the same file image into a separate small token array (mini_base), and the printer spells(fstr (lit "...") (field ...)). - Multi-byte operators that the tokenizer does not fuse (
**,->,<<=,//=) are recognised as adjacent single tokens, as described above.
When the parser refuses #
The parser refuses with one of two words, bad token for a shape outside the grammar and unsupported for a recognised shape the subset excludes, followed by the line of the offending token. Unlike the tokenizer’s, these words are not compared with the reference’s: sexpdump derives its refusals from ast shapes, so CI checks only that both sides refuse. Over the 290 corpus files CI runs, the reference prints a tree for 227 and refuses 63:
| Corpus kind | Tree printed | Refused | What it shows |
|---|---|---|---|
abort |
18 | 1 | Programs the executable must abort while the CPython oracle is skipped (documented divergences, arena exhaustion): almost all parse |
err |
62 | 12 | Programs that fail at run time: most are syntactically ordinary |
inc |
18 | 0 | Helper modules imported by other corpus programs |
other |
2 | 0 | Files in tests/mvp/inc_dotpkg/, a package the import tests use |
pass |
85 | 21 | Programs the host compiles that the self-hosted parser does not yet read: set displays, finally, a bare raise, comprehensions with two for clauses or nested in another, \x escapes, a name repeated in a chain like x = x = 1 |
rej |
42 | 29 | Programs the frontend refuses: many still print a tree, because their problem is semantic (an unknown call, a global read in a function), not syntactic |
The pass row measures the gap between the two readers: those programs compile and run through the host frontend, but the self-hosted parser refuses them. The rej row shows the other side of “syntactic, not a second frontend”. Checks such as arity, use before assignment and unknown calls stay in frontend.py, so the sexp admits a syntactic superset of what the frontend accepts, and both references admit the same superset.
The straight-line emitter, emit.s #
emit.s reads the sexp text that parse.s prints, one statement per line, and writes assembly for it. It reads the text, not the tree in memory, so it is a separate program, and the two are joined by a file:
./parse.elf prog.py > prog.sexp && ./emit.elf prog.sexp > prog_emit.s
as -o prog.o prog_emit.s && cc -o prog.elf prog.o runtime.s -lm && ./prog.elf
It accepts only the straight-line shapes: assignment to a plain name, int and str literals (a negative number arrives as (unary - ...)), + - * / // % on ints, print, len, list displays and subscript loads. It scans the file once to collect variable names, emits one flat main_main frame, and calls the same runtime helpers with the same ownership discipline the host compiler uses (see Emitting assembly). Anything else ends it here, with the line number of the sexp line, not of the source:
parser/emit.slines 230–242die_unsupported: # noreturn: spell the refusal, exit 1
lea rsi, [rip + pre_unsup] # "parser: unsupported (line " bytes
mov edx, pre_unsup_end - pre_unsup # prefix byte count
call write_stderr # spell the prefix, errors ignored here
mov rax, [rip + stmt_line] # rax = offending line number
call write_u64 # spell the decimal line number
lea rsi, [rip + suf_line] # ")": plus newline
mov edx, suf_line_end - suf_line # suffix byte count
call write_stderr # spell the suffix, errors ignored here
mov edi, 1 # exit status 1: failure
call _exit # leave via libc, never returns
ud2 # crash if _exit ever returned
# ---- stdout writers: looped write, cstring write, decimal write ----
parser/emitdiff.sh is its check. For each program in its list (pass_arith, pass_floor, pass_list, pass_nested, pass_seq_ops, pass_leakflat) it compiles the program twice, once with the host compiler and once through parse.elf and emit.elf, links both with runtime.s, runs both, and requires the same stdout bytes and the same exit status. It then feeds emit.elf 3 hand-written sexp lines (an if, a comparison, a method call) and requires parser: unsupported (line 1) for each.
flowchart LR
py["pass_arith.py"] --> host["frontend.py + codegen.py"] --> a1["host.s"] --> e1["host.elf"] --> o1["stdout, exit status"]
py --> p["parse.elf"] --> sx["prog.sexp"] --> em["emit.elf"] --> a2["emit.s"] --> e2["prog.elf"] --> o2["stdout, exit status"]
o1 --- cmp{"identical?"} --- o2
class p,em,e2 accent
The assembly is not compared, and cannot be. emit.s sizes its frame as the number of variables plus a fixed 1024 temporary slots, where the host sizes it from the tree, and it numbers variables in order of first appearance in the sexp, where the frontend orders values before targets. The slot offsets and comments differ, so the check compares what the programs do.
How CI proves it #
These are the track’s steps in .github/workflows/ci.yml, on an ubuntu-latest runner, the only place the assembly is built and run:
- run: as -o /tmp/dump.o parser/dump.s && cc -o /tmp/dump.elf /tmp/dump.o
- run: /tmp/dump.elf parser/dump.s | diff - parser/dump.s && seq 1 3000 | /tmp/dump.elf /dev/stdin | diff - <(seq 1 3000) && ! /tmp/dump.elf /nonexistent && ! /tmp/dump.elf
- run: as -o /tmp/tok.o parser/tok.s && cc -o /tmp/tok.elf /tmp/tok.o
- run: for f in tests/mvp/*.py tests/mvp/inc_dotpkg/*.py; do uv run aython tokdump "$f" > /tmp/tok_ref.out; /tmp/tok.elf "$f" > /tmp/tok_got.out; diff /tmp/tok_ref.out /tmp/tok_got.out || exit 1; done && printf 'x = 1\n\x01\n' > /tmp/tok_bad.py && ! /tmp/tok.elf /tmp/tok_bad.py && /tmp/tok.elf /tmp/tok_bad.py 2>&1 | grep -q "^parser[:] bad byte (line 2)$"
- run: as -o /tmp/parse.o parser/parse.s && cc -o /tmp/parse.elf /tmp/parse.o
- run: set +e; for f in tests/mvp/*.py tests/mvp/inc_dotpkg/*.py; do uv run aython sexpdump "$f" > /tmp/sexp_ref.out 2>/tmp/sexp_ref.err; ref_code=$?; /tmp/parse.elf "$f" > /tmp/sexp_got.out 2>/tmp/sexp_got.err; got_code=$?; if [ $ref_code -eq 0 ] && [ $got_code -eq 0 ]; then diff /tmp/sexp_ref.out /tmp/sexp_got.out || exit 1; elif [ $ref_code -ne 0 ] && [ $got_code -ne 0 ]; then true; else echo "sexp mismatch on $f (ref=$ref_code got=$got_code)"; exit 1; fi; done; echo SEXP-IDENTICAL
- run: bash parser/emitdiff.sh
In order: build and check dump.s; build tok.s, then for every file in tests/mvp/*.py and tests/mvp/inc_dotpkg/*.py diff tokdump’s output against tok.elf’s, stopping at the first difference, and require the exact message parser: bad byte (line 2) for a planted bad byte; build parse.s and, for the same files, diff the sexp when both accept, accept when both refuse, and fail when only one refuses; finally run emitdiff.sh.
Over the current corpus that is 290 files and 26,205 token lines that tok.s must reproduce exactly (11,122 OP, 7,183 NAME, 3,283 NEWLINE, 2,479 INT, 632 STR, 608 INDENT, 608 DEDENT, 290 EOF), and 227 trees parse.s must print exactly. Every new corpus program, added for any feature, becomes a new test of the tokenizer and parser for free.
Conventions #
The track follows the runtime’s rules, recorded in docs/parser-design.md and AGENTS.md:
| Convention | Why |
|---|---|
.intel_syntax noprefix, .globl + .type + .p2align 4 on main, .L labels for everything local, .note.GNU-stack at the end |
The same assembler dialect and layout as runtime.s, so one reading habit covers both |
Callee-saved registers (rbx, rbp, r12–r15) pushed on entry and popped on exit by the routines that use them; rsp 16-byte aligned at every libc call (six pushes plus sub rsp, 8 in main) |
System V rules: libc may clobber everything else, and some libc routines fault on a misaligned stack |
One parser: <what> (line N) line on stderr and exit 1; the first error wins |
The runtime’s abort policy: no tracebacks, a message a test can grep |
Arena from mmap, same 64 MiB as the runtime; state in .bss |
No allocator to write, and nothing to free in a program that exits after one pass |
| Every slice ships its CI check in the same change | Each piece is verifiable by diffing bytes, the same oracle habit as the judge |
The design document gives the order of the slices the same reason: the reader is libc calls with no decisions in it, so it cannot miscompile anything; the tokenizer needs only the reader and the arena; the parser needs only tokens. Each step could be checked by diffing bytes before the next one depended on it.
Where it differs from CPython’s parser #
- Bytes. ASCII only, LF line endings only, no tab indentation, no backslash line continuation, no string spanning lines.
- Literals. No hex, octal or binary integers (
0x10tokenizes asINT 0,NAME x10, which the parser refuses);\u,\U,\xand\Nescapes in strings are refused on both sexp sides, because a verbatim-escape tokenizer cannot tell whether they decode to ASCII. - Grammar. Only what the subset admits, minus the shapes listed in the
passrow above. - Errors. No recovery and no message beyond
bad tokenorunsupportedwith a line number. CPython names the problem and points at a column. - Limits. At most 64 levels of indentation and 1024 children pending on the temp stack; a 64 MiB arena for the file, its tokens and its tree together.
- Nothing runs it.
aython runandaython checkuse the host frontend. The track is checked in CI, not used to build programs.
Where this lives #
| Concept | Where |
|---|---|
| File reader | parser/dump.s main |
| Tokenizer | parser/tok.s main (.Lnext_line, .Ltok, .Lpop, .Lpush), emit_token |
| Token reference | src/aython/tokdump.py tokenize_bytes; aython tokdump in cli.py |
| Parser and node allocation | parser/parse.s .Pparse, .Pprogram, .Pstmt, .Por … .Ppower, .Patom, .Palloc, .Ptmp_* |
| Tree printer | parser/parse.s .Pprint |
| Sexp reference | src/aython/sexpdump.py dump_source, _Dumper; aython sexpdump |
| Straight-line emitter | parser/emit.s parse_stmt, parse_assign, parse_expr, emit_header, emit_tail, die_unsupported |
| Behaviour check of the emitter | parser/emitdiff.sh |
| CI steps | .github/workflows/ci.yml |
| Design, slices, decisions | docs/parser-design.md, parser/README.md |
| This page’s data | docsite/figures/parser.py, docsite/figures/tokens.py |
Check yourself #
Check yourself
What does
tok.semit for the linex = 1.5?NAME x,OP =,FLOAT 1.5,NEWLINENAME x,OP =,INT 1,OP .,INT 5,NEWLINENAME x,OP =,INT 1.5,NEWLINE- It refuses the line: there is no float token
Answer
NAME x,OP =,INT 1,OP .,INT 5,NEWLINE. AnINTis a run of digits only, and.is a one-byteOP. The parser sees that the three tokens are adjacent in the file and prints one(float 1.5)leaf.The indentation stack holds
[0, 4, 8]and the next code line starts 2 spaces deep. What happens?- One
DEDENT, then the line is scanned at level 4 - Two
DEDENTs, then anINDENTto level 2 parser: bad dedent (line N)on stderr, exit 1, and no tokens on stdout- Nothing: indentation inside a block is free
Answer
parser: bad dedent (line N)on stderr, exit 1, and no tokens on stdout..Lpoppops 8 and emits aDEDENT, finds the new top is 4, and 2 is still smaller, so it pops 4 and emits another; the top is now 0, and 2 is greater than 0, so the width lies between two levels andjg .Lbad_dedentrefuses the line. The token array is only printed after the whole file is scanned (.Ldump), so a refusal prints no tokens at all.- One
Where is the text of a
NAMEtoken stored?- In a fresh runtime
strobject - In the 32-byte token itself
- Nowhere: the token points into the file’s bytes in the arena, with a length
- In a symbol table dict
Answer
Nowhere: the token points into the file’s bytes in the arena, with a length.emit_tokenstores the pointer at+24and the length at+16. The file image stays in the arena for the whole run, so nothing is copied, and names are compared byte by byte with.Ptok_is.- In a fresh runtime
For one corpus file,
sexpdumprefuses withparser: unsupported (line 4)andparse.elfrefuses withparser: bad token (line 7). What does CI do?- Fails: the messages differ
- Fails: the line numbers differ
- Passes: when both sides refuse, only the exit status is compared
- Skips the file
Answer
Passes: when both sides refuse, only the exit status is compared. The sexp step diffs stdout only when both exit 0. When both exit non-zero it accepts; it fails only when exactly one side refuses. The reference spells refusals fromastshapes, so word-for-word parity is not required.Why does
emitdiff.shcompare the programs’ output instead of the assemblyemit.swrites?- Assembly cannot be diffed
emit.slays out the frame differently (variables plus 1024 temporaries, first-appearance order), so offsets and comments differ while behaviour must not- The host compiler’s output changes on every run
- To save CI time
Answer
emit.slays out the frame differently (variables plus 1024 temporaries, first-appearance order), so offsets and comments differ while behaviour must not. The design records the choice: a fixed upper-bound frame and a different variable order mean[rbp-...]offsets cannot match, so the check compares stdout bytes and exit status of the two executables.