Technical report15 min read
How aython works
A technical report on turning Python into a native executable by hand: the machine, the objects, the frontend, the emitted assembly, the runtime, and how all of it is proven to print what CPython prints.
A Python program normally runs inside an interpreter: a large C program that reads your code and does what it says, one step at a time. aython removes the interpreter. It turns a small subset of Python into x86-64 machine code that runs on its own, and it proves each translation right by running the same program under CPython and demanding the same output, byte for byte. This report explains how every part of that works, and why it was built the way it was.
It is written for a strong Python programmer who has never written assembly, a compiler or a language runtime. Nothing is assumed below the level of Python itself. The report teaches the registers, the stack, the calling convention and the memory layout of an object at the point each one is first needed, and every listing is cut from the real repository when the site is built: the generated assembly by running the real frontend and code generator, the runtime helpers from the real runtime.s, the Python from the real source files. If the code changes, the pages change with it, or the build fails.
The short version #
- The machine is small. A processor has sixteen 64-bit general-purpose registers, a stack in memory, and instructions that move, add, compare and jump. A function call follows one fixed contract, System V AMD64: arguments in
rdi,rsi,rdx,rcx,r8,r9, the result inrax. Everything this report shows rests on a few dozen instructions and that one contract. Chapter 1. - Every Python value is a pointer to a box. Each box starts with a 16-byte header, a reference count at offset 0 and a type pointer at offset 8, followed by its payload: an int is 24 bytes, a list 40 plus a separate buffer for its items.
None,True,Falseand the integers from -5 to 256 are immortal and never freed. Everything else comes from one 64 MiB arena obtained with a singlemmap. Chapter 2. - CPython parses, aython decides. The frontend reads the program with Python’s own
astmodule, so no parser had to be written, and then checks it construct by construct. Anything outside the subset is refused by name (aython: unsupported: assert statement) and never reaches assembly; 71 corpus programs exist only to be refused. Chapter 3. - The generated code is deliberately plain. Every variable and every intermediate value has its own 8-byte slot on the stack, almost every operation is a
callinto the runtime, and every change of ownership is an explicitaython_increforaython_decref. Slow, but each line can be checked by eye, and control flow needs no merge logic. Chapter 4. - The runtime is the language. 16,217 lines of hand-written assembly export 177 symbols: integer arithmetic that aborts on overflow instead of wrapping, floats printed exactly as CPython prints them, dicts in insertion order, sets in CPython’s own table order, and one clean abort path. libc provides only process start-up and the calls into the kernel. Chapter 5.
- CPython is the specification. The judge checks every one of the 270 corpus programs: its standard output byte for byte against CPython’s, or its error kind against CPython’s, or its refusal message against the expected one. A leak probe, a seeded fuzzer that checks 250 generated programs on every push, and CI stand behind that. Chapter 6.
- Speed is measured, not promised. On the one native machine recorded, a ten-million-step loop (
sum10m.py) takes 0.68x CPython’s time, while recursivefib(30)takes 1.48x, because every call pays for explicit ownership. Small programs mostly measure CPython’s start-up. Chapter 7. - The differences are few, and each is pinned by a test. Integers stop at 64 bits, strings are ASCII, instances are dicts, cycles leak. Beyond the core, a parser written in assembly reads Python without CPython (chapter 9), a census counts how much of CPython’s own standard library the frontend accepts, 31 of 637 files (chapter 10), and every significant decision is collected with its rejected alternative (chapter 11). Chapter 8.
The whole system on one page #
flowchart TD fuzz["<b>Fuzzer</b><br/>seeded in-subset programs"] src["<b>prog.py</b><br/>and the sibling modules it imports"] census["<b>Stdlib census</b><br/>637 real files, frontend only"] fe["<b>Frontend</b><br/>ast.parse, then admit or refuse"] refuse["<b>Refused</b><br/>aython: unsupported: feature"] cg["<b>Code generator</b><br/>prog.s.gen: main_main, fn_name"] rt["<b>runtime.s</b><br/>16,217 lines, by hand"] link["<b>as, then cc</b><br/>with libc and libm"] elf["<b>prog.elf</b><br/>native executable"] cpy["<b>CPython</b><br/>python3 prog.py"] judge["<b>Judge</b><br/>same bytes, same error kind,<br/>or the expected refusal"] ptrack["<b>Parser track</b><br/>tok.s, parse.s, emit.s"] fuzz --> src src --> fe census --> fe fe -->|"outside the subset"| refuse fe -->|"checked tree"| cg cg --> link rt --> link link --> elf elf -.-> judge cpy -.->|"the specification"| judge src --> cpy refuse -.-> judge src --> ptrack ptrack -.->|"against tokdump, sexpdump<br/>and the code generator"| judge class fe,cg,rt,link,elf,ptrack accent class cpy py class refuse bad class judge good
Read it from the top. A program passes the frontend or is refused, becomes assembly, is linked with the runtime into an executable, and the judge compares what the executable does with what CPython does. Everything off that main line tests it from another angle: the fuzzer feeds it programs nobody wrote by hand, the census feeds the frontend the real-world code of CPython’s standard library, and the parser track rebuilds the front of the pipeline in assembly and is checked against the Python it replaces: its tokens against aython tokdump, its trees against aython sexpdump, and the programs it emits against the code generator’s.
Three things carry the weight #
- The ownership rule. Every runtime helper borrows its inputs, meaning it does not keep or release them, and returns a new owned reference that the caller must eventually release. The generated code makes every transfer explicit: a value stored into a slot is owned by the slot, the old value is released first, temporaries are released as soon as they are used. With one rule applied everywhere, the generated code and 16,217 lines of runtime manage memory without a garbage collector, and a forgotten release is visible as a missing line. Objects in memory and Emitting assembly take it apart.
- The subset boundary. The frontend refuses rather than guesses. A construct is either admitted, which means the code generator and the runtime handle every case of it, or refused with its name, before any assembly exists. That keeps the runtime free of half-supported features and gives the corpus a whole category of tests: each refusal is itself a test, so a construct cannot slip in by accident. From source to a checked program.
- The oracle. Python has no written specification precise enough to test against; CPython is the specification. A program passes only if the executable prints exactly what CPython prints. Nobody reads the generated assembly line by line, so the judge, its corpus and the fuzzer are the only reviewers it has, and most of the care in the project went into making them strict. Proving it right.
Reading guide #
The chapters build on each other in order, but each says at the start what it relies on, so you can also go straight to the one you care about.
- Foundations: the machine and the objects. Read these first if assembly is new to you; everything after quotes registers and offsets without explaining them again.
- The pipeline: the frontend, the code generator and the runtime, in the order a program passes through them.
- Trust: how correctness is established, how fast the result is, and exactly where it differs from CPython.
- Reaching further: the parser in assembly, the census of the standard library, and the decision log.
- 1x86-64 in fifteen minutesThe registers, instructions, stack and calling convention the rest of the report leans on, taught from the assembly aython actually emits.
- 2Objects in memoryEvery value is a pointer to a small block with a reference count and a type tag. The layout, the ownership rules, and the allocator that hands the blocks out.
- 3From source to a checked programCPython's own parser reads the program; the frontend then decides, construct by construct, whether it is inside the subset, and refuses everything else by name.
- 4Emitting assemblyHow a checked tree becomes one assembly function per Python function: stack slots for every value, an explicit call for every ownership transfer, and jumps for control flow and exceptions.
- 5The runtime, helper by helperThe hand-written assembly the generated code calls: integers, floats and their printing, strings, lists, dicts, sets, print, and the clean abort.
- 6Proving it rightNobody reads the emitted assembly line by line. A differential judge runs every program under the ELF and under CPython and requires the same bytes, backed by leak probes, a fuzzer and CI.
- 7How fast, and whyHow aython's executables are timed against CPython, what the recorded ratios are, and which design choices make them what they are.
- 8Where it differs from CPythonEvery known place where an aython program behaves differently from CPython, why it does, and which test pins it down.
- 9Python without PythonThe 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.
- 10Measuring against the real worldHow many files of CPython's own standard library the subset accepts as they are, and what each new construct moved.
- 11Decisions, and whyThe choices that shaped aython, each with the alternative that was rejected and the reason, gathered in one place.
The glossary defines every term with a link to where it is explained, and the assembly reader puts a program, its assembly and the runtime helpers it calls side by side.
Ground rules for the code and the numbers #
- Listings are generated. A block of assembly headed by a file name was produced by running
frontend.compile_sourceandcodegen.generateon that file when the site was built, exactly asaython rundoes; a runtime helper was cut fromruntime.sat its label. Comments in those listings are the code generator’s and the runtime’s own. - Outputs are CPython’s. Where a page shows what a program prints, it is CPython’s output for that corpus program, produced at build time. The site is built on machines that cannot run x86-64 executables, so no output on these pages comes from running one. For a
passprogram the judge requires the executable to print the same bytes, and CI checks that on Linux on every push. - Counts are read from the repository. Corpus sizes, the runtime’s line count, the census figures and the fuzzer’s CI counts are computed when the site is built, so they are never older than the code beside them.
- Timings come from one machine. The only timings quoted are those recorded in
bench/results/, measured on native x86-64 Linux. Numbers taken under emulation are never quoted.
How to learn from this #
A suggested route, if the goal is to understand the whole thing rather than look something up:
- Read the machine and objects in memory slowly. They are short, and every later chapter assumes them.
- Open the assembly reader on the arithmetic example and follow one line of Python through its assembly and into the helper it calls, using the glossary when a word is new.
- Read the frontend, emitting assembly and the runtime in order, with
src/aython/codegen.pyandruntime.sopen beside them. - Read proving it right, then where it differs: together they say exactly what “works” means here.
- Leave the parser track, the census and the decisions until the core makes sense.
Reading is not enough to learn a runtime; changing one is. These exercises need Linux on x86-64 for anything that assembles, and nothing else:
Write a program and read what it became. Write a few lines inside the subset in mine.py, then:
uv run aython run mine.py # writes mine.s.gen, mine.o, runtime.o and mine.elf, then runs it
uv run aython tokdump mine.py # the tokens the parser track's tok.s must produce (any machine)
uv run aython sexpdump mine.py # the tree, as S-expressions, that parse.s must produce (any machine)
Open mine.s.gen. The code generator writes a # line N: comment before the code for each statement; find yours, and name every call in it.
Get refused on purpose. Add assert x > 0 to your program and run it again. The frontend refuses it before anything is assembled. Find the refusal in src/aython/frontend.py (search for "assert statement") and the corpus file that pins it, tests/mvp/rej_assert.py.
Break the runtime and watch the judge catch it. Python’s // rounds toward negative infinity, while the processor’s idiv instruction truncates toward zero, so -7 // 2 is -4 in Python and -3 in C. int_floordiv corrects the quotient after idiv: when the remainder is not zero and its sign differs from the divisor’s, one dec rax moves the quotient down by one:
runtime.s · int_floordivlines 1430–1498 mov rax, [rbx + 16] # reload dividend value for idiv
mov rcx, [r12 + 16] # reload divisor value for idiv
cqo # sign-extend rax into rdx:rax for signed divide
idiv rcx # rax=C-truncated quotient, rdx=C remainder
test rdx, rdx # test whether remainder is zero
jz floordiv_done # exact division needs no floor fix-up
mov r8, rdx # r8 copies remainder for sign test
xor r8, rcx # xor sign bits of remainder and divisor
jns floordiv_done # same sign means C quotient already floors
dec rax # signs disagree, decrement quotient toward -inf
floordiv_done: # rax holds Python-floored quotient
mov rdi, rax # rdi passes quotient value to boxing helper
call int_new # rax returns new owned int box
In a scratch copy of the repository, delete the dec rax line and judge the program that pins floor division:
uv run aython check tests/mvp/pass_floor.py
The judge fails it, because the executable no longer prints what CPython prints. Put dec rax back, and this time make the code generator forget a release: in _emit_binary in src/aython/codegen.py, delete the line that emits # release left operand and the call line after it. Then:
uv run aython check tests/mvp/pass_leakflat.py # passes: every output is still right
uv run aython check --leak tests/mvp/pass_leakflat.py # the leak probe
The second command runs the program’s body twice in one process. Objects the first run never released cannot be reused, so the second run has to take fresh memory from the arena, and the probe reports it.
Generate programs. Run aython fuzz --count 20 --seed 1 and read a few of the programs it wrote under build/fuzz/. Each was judged against CPython like a corpus file. The header of src/aython/fuzz.py explains why every one of them is guaranteed to terminate.
Where this lives #
| Part | Where | What to read first |
|---|---|---|
| Command line | src/aython/cli.py | run and check: the whole pipeline in two functions |
| Frontend | src/aython/frontend.py | compile_source, the entry point; UNSUPPORTED_PREFIX and the refusals |
| Code generator | src/aython/codegen.py | generate, which emits main_main and one fn_<name> per function |
| Runtime | runtime.s | The header comment: the object layouts, the ownership rule, the calling convention |
| Judge | src/aython/judge.py | build_program (assemble and link) and check_file (the verdict) |
| Corpus | tests/mvp/ | Any file’s # mvp: line, then the file |
| Fuzzer | src/aython/fuzz.py | The module docstring: what is generated and why it terminates |
| Benchmarks | src/aython/bench.py, bench/ | bench/results/ for the recorded numbers |
| Stdlib census | src/aython/stdlib.py, docs/stdlib-census.md | The census log, newest entry last |
| Parser track | parser/ | parser/README.md, then tok.s |
| Design | docs/core-design.md | The program contract and the decisions made in review |
Check yourself #
Check yourself
A program uses
assert. What happens when you runaython runon it?- It compiles, and the assertion is skipped at run time
- It compiles, and the executable aborts with
AssertionError - The frontend refuses it with
aython: unsupported: assert statement, and nothing is assembled
Answer
The frontend refuses it withaython: unsupported: assert statement, and nothing is assembled. The frontend admits a construct only when the code generator and runtime handle all of it. Everything else is refused by name before any assembly exists, andtests/mvp/rej_assert.pypins that refusal.What decides whether the executable for a
# mvp: passprogram is correct?- Its standard output is byte-identical to CPython’s for the same file, and both exit 0
- A person reviews the generated assembly
- It exits 0 within the time limit
Answer
Its standard output is byte-identical to CPython’s for the same file, and both exit 0. CPython is the specification. The judge runs both and compares the bytes. Standard error is not compared, because CPython prints a traceback where aython prints one line.In the recorded benchmark results, recursive
fib(30)ran slower as an aython executable than under CPython, while a ten-million-step flat loop ran faster. Why?- The executable is interpreted after all
- CPython compiles
fibto machine code - Each call pays explicit bookkeeping, checking arity, adopting arguments and releasing every local, and nothing is inlined
Answer
Each call pays explicit bookkeeping, checking arity, adopting arguments and releasing every local, and nothing is inlined. A flat loop becomes a short native loop with no interpreter dispatch. A call pays for a frame, an arity check and a release of each slot on return, every transfer an explicitcall. How fast, and why takes it apart.Where does the int object for
x = 1000live, and how big is it?- In a register, 8 bytes
- In the 64 MiB arena, 24 bytes: reference count, type pointer, value
- On the stack, 16 bytes
Answer
In the 64 MiB arena, 24 bytes: reference count, type pointer, value. Every value is a pointer to a box with a 16-byte header, and an int adds its 8-byte value. 1000 is outside the immortal range -5 to 256, soint_newallocates it from the arena (or reuses a freed int header). The stack slot holds only the pointer. Objects in memory draws the layout.