aython

Chapter 11 of 1124 min read

Decisions, and why

The choices that shaped aython, each with the alternative that was rejected and the reason, gathered in one place.

Most of aython's shape follows from a few dozen decisions, each made against a named alternative and recorded in the design documents. The earlier chapters explain the mechanisms one at a time; this one gathers the decisions in one place, so that a choice can be traced from what was decided, through what was rejected and why, to the behaviour you can observe and the chapter that explains it.

Each card below has the same five parts. Decided is the rule as the code implements it today. Instead of names the alternative: the one the repository records as considered or rejected where it records one, otherwise the obvious one, usually what CPython does. Because gives the reason, quoted or paraphrased from where it is recorded. You can see it points at something you can check yourself: a file, a symbol, a command, or a program’s behaviour. Explained in links the chapter with the mechanism. The sources are docs/core-design.md (Principles, Decisions made in review, What changed in the building, Non-goals), docs/bench-design.md, docs/parser-design.md, AGENTS.md and comments in the code.

Correctness #

CPython is the specificationcorrectness

Decided. A program that is meant to run passes when its stdout is byte-identical to python3’s on the same file and both exit 0. Standard error is not compared.

Instead of a written description of the language, or a comparison of error output.

Because Python has no formal specification on paper, so CPython’s behaviour is the only complete one. Stderr is excluded because where CPython prints a traceback, aython prints one line by design (next card).

You can see it in _check_pass in judge.py: three comparisons and the verdict “N stdout bytes match”. aython check runs it over tests/mvp/*.py.

Explained in Proving it right.

Refuse by name, never guesscorrectness

Decided. A program that uses anything outside the subset is refused by the frontend with unsupported: <feature>, and no assembly is written.

Instead of compiling what can be compiled and approximating the rest.

Because a compiler that silently generates wrong code for an unknown construct produces a program that runs and is wrong, which the judge might only catch by luck. A refusal is always visible. The one deliberate leniency is documented as such: docstrings and annotations are skipped silently, because they never change what a program prints.

You can see it in _unsupported in frontend.py, and in the rej_* corpus files, each of which pins one refusal with a # mvp: reject:<feature> marker on its first line.

Explained in From source to a checked program.

Abort with one line, unless a handler is waitingcorrectness

Decided. An uncaught failure (a type error, a division by zero, a bad index) writes one line such as aython: ZeroDivisionError to stderr and exits with status 1. Inside a try, the same failure unwinds to the nearest matching except, carrying only a kind id. There are no tracebacks and no exception objects.

Instead of CPython’s exception objects, chained tracebacks and except ... as e.

Because the design keeps the machinery to what the observable behaviour needs. When try arrived, its only new machinery was, in the design’s words, “the handler stack and the kind id”: unwinding is a jump to a recorded address with the frame restored. The judge compares the error kind on the ELF’s stderr, not the wording.

You can see it in the abort_* helpers and exc_push/exc_raise in runtime.s, and in _check_abort in judge.py. Objects abandoned mid-expression on the throw path leak: the frame is discarded whole.

Explained in The runtime, helper by helper and Emitting assembly.

Divergences are named and pinned, not hiddencorrectness

Decided. Where aython cannot match CPython, the difference is written down in docs/core-design.md and pinned by a corpus program that expects aython’s behaviour, usually an abort: case with the CPython oracle skipped.

Instead of leaving such programs out of the corpus, or widening the comparison until they pass.

Because an unrecorded divergence is a bug nobody knows about. A pinned one cannot drift: if the behaviour changes, the probe fails. Examples: a method on the wrong receiver aborts TypeError where CPython raises AttributeError; printing a self-referential list aborts RecursionError where CPython prints [1, [...]].

You can see it in the Correctness policy section of docs/core-design.md and the probes it names, such as abort_eq_cycle.py.

Explained in Where it differs from CPython.

Leaks are measured by arena growth, not by a live countcorrectness

Decided. The leak probe runs a straight-line program twice in one process and requires the second run to take zero fresh bytes from the arena.

Instead of asserting that no object is alive at exit.

Because freed headers go onto free lists and their bytes stay counted as used, so a live count at exit is never zero, by design. A forgotten decref strands a header, and the rerun then has to bump the arena for a fresh one, which the probe sees.

You can see it with aython check --leak on pass_leakflat.py; leak_check in judge.py reads the exported arena_used helper of runtime.s.

Explained in Proving it right.

Strings hash deterministically, so their set order is kept out of the testscorrectness

Decided. Strings hash with FNV-1a. The corpus and the fuzzer never print or iterate a set that contains strings; membership, length, equality and mutation of such sets are tested.

Instead of porting CPython’s SipHash.

Because CPython seeds its string hash per process, so the order of a string set differs from run to run and CPython disagrees with itself. No oracle exists for that order, so matching it is impossible and testing it meaningless. Every other hash (ints, floats, bools, tuples) is an exact port, so those sets print in CPython’s order.

You can see it at obj_hash_str in runtime.s (the FNV offset basis 0xcbf29ce484222325).

Explained in The runtime, helper by helper.

Object model #

Every value is a boxed object with a reference countobject model

Decided. Every value is a pointer to a block that starts with an 8-byte reference count and an 8-byte type pointer, followed by its payload. An int is 24 bytes.

Instead of fixnums: small integers stored directly in the pointer, with tag bits saying so.

Because the point of the project is to learn the real Python object model (the review table: “to learn the real Python model”). Boxing every value makes every allocation, every incref and every decref visible. docs/bench-design.md traces the cost of call-heavy code to the same choice: every ownership transfer is explicit.

You can see it in the object model comment at the top of runtime.s, and in int_new.

Explained in Objects in memory.

Every ownership transfer is an explicit call in the generated codeobject model

Decided. Runtime helpers borrow their arguments and return a new owned reference. The generated code shows every transfer as a call to aython_incref or aython_decref; an assignment is “release the old value, compute the new one, store it”.

Instead of helpers that consume their arguments, or ownership hidden inside the runtime.

Because of the principle the design calls “no magic”: if you cannot point at a transfer in the listing, it should not exist. The same rule makes branches cheap to add: values travel in stack slots, so two paths that rejoin never disagree about who owns what.

You can see it in any listing in the Assembly reader, and in the ownership rule comment in runtime.s.

Explained in Emitting assembly.

Integers are 64-bit; overflow abortsobject model

Decided. An int holds a signed 64-bit value. An operation that would overflow aborts with OverflowError.

Instead of arbitrary-precision integers as in CPython, or silent wrap-around as in C.

Because big integers need an allocator and arithmetic of their own. Wrapping would print a wrong number and pass for correct; aborting is the honest failure.

You can see it: 2**62 + 1 prints the same as CPython, while 2**62 * 4 aborts where CPython prints a larger number. The helpers test the processor’s overflow flag (jo) after each operation.

Explained in The runtime, helper by helper and Where it differs from CPython.

None, True, False and small ints are immortalobject model

Decided. The singletons live in the executable’s data section with a huge reference count (the SENTINEL, 262); incref and decref see a count at or above it and do nothing. Ints from -5 to 256 are prebuilt the same way, like CPython’s small-int cache.

Instead of allocating and freeing them like any other object.

Because the singletons are shared by every program and never die, so counting them is wasted work; and the small-int cache came from measurement: reading the generated fib showed about six fresh int boxes per call (docs/bench-design.md, first optimization). Immortality also lets the code generator skip a decref it can prove is a no-op: a comparison always returns True or False.

You can see it at SENTINEL and small_ints in runtime.s, and _test_yields_immortal in codegen.py.

Explained in Objects in memory and How fast, and why.

One 64 MiB arena, a bump pointer and free lists by sizeobject model

Decided. At startup the runtime maps one 64 MiB block. Objects are carved from it by moving a pointer; a dead object’s header goes onto the free list for its size class (each object kind has its own pool, except that lists and tuples share one) and is reused. Item and byte buffers are not reused.

Instead of calling malloc and free per object, or a garbage collector.

Because the design wants allocation that is simple to follow: one request to the kernel up front (“like renting one large empty room instead of asking for one drawer at a time”), then bumping a pointer. Buffers are not recycled because straight-line tests never press the ceiling. Running out is a clean MemoryError, never memory corruption.

You can see it at arena_init in runtime.s, and in tests/mvp/abort_oom.py, a 100 MB string that must abort.

Explained in Objects in memory.

Reference cycles leakobject model

Decided. There is no cycle collector. A list that contains itself never reaches a count of zero and is never freed.

Instead of CPython’s cyclic garbage collector.

Because the design accepts the leak “as long as it never crashes” and defers real cycle collection. Printing and comparing a cycle abort cleanly at a depth guard instead of recursing until the stack runs out.

You can see it in the review table of docs/core-design.md (“Leak by design, tested to not crash”).

Explained in Objects in memory and Where it differs from CPython.

Strings are ASCII bytesobject model

Decided. A str is a length and a pointer to bytes, one byte per character. Non-ASCII literals are refused at compile time; non-ASCII file contents and arguments abort ValueError.

Instead of Unicode code points with a variable-width encoding.

Because with bytes equal to characters, indexing, slicing, len and comparison are byte operations, and every one of them matches CPython exactly over the admitted strings.

You can see it in the str layout in runtime.s and docs/core-design.md (“bytes == characters: ASCII only”).

Explained in Objects in memory.

Classes add no heap kind: instances are dicts, methods are resolved at compile timeobject model

Decided. An instance is a plain dict. A method becomes an ordinary function named <Class>__<method>, and c.m(...) is compiled to a direct call of the one function with that short name, which is why method names must be unique across the program and a subclass may not override an inherited method (__init__ excepted).

Instead of class objects with a method table looked up at run time.

Because it needs no change to the runtime and no new object layout, and with unique names the lookup is sound without run-time dispatch. The price is visible and documented: print(c) shows the namespace dict, and a missing attribute aborts KeyError where CPython raises AttributeError.

You can see it in the Classes section of docs/core-design.md.

Explained in From source to a checked program and Where it differs from CPython.

Imports are flattened at compile timeobject model

Decided. import m compiles the sibling m.py into the same program, with its top-level names prefixed (m__fib), and runs its statements at the import point. A module is never a value.

Instead of module objects created and looked up at run time.

Because it needs no new heap object, and mod.attr can be resolved while compiling. It also fixes what “importable” means for the census: a sibling .py file must exist.

You can see it in _expand_imports in frontend.py.

Explained in From source to a checked program.

Toolchain #

One target: x86-64 Linuxtoolchain

Decided. The generated code and the runtime are x86-64 assembly for Linux, nothing else.

Instead of supporting a second architecture or operating system.

Because every register name and every detail of argument passing is specific to one processor and one OS, and supporting two would double the learning for no benefit.

You can see it: the executables only run on x86-64 Linux, and timings are only quoted from native hardware of that kind.

Explained in x86-64 in fifteen minutes.

Link with libc for the kernel crossing, keep everything else hand-writtentoolchain · changed in the building

Decided. Programs are linked with cc against libc. The C startup code calls the runtime’s main, and every crossing into the kernel (write, mmap, open, read, close, _exit) is a call to the libc wrapper. The allocator, the object model and the abort messages stay hand-written assembly.

Instead of the original proposal: no libc, only raw syscall instructions.

Because, as recorded in “What changed in the building”: the hand-rolled syscall stubs had taught what they had to teach, and every new capability (file input, argv, the tokenizer’s arena) paid the system-call interface’s cost again. The question the original rule protected, “where can behaviour hide?”, stays answered by keeping all allocation and printing in hand-written code.

You can see it in the libc list at the top of runtime.s, and in error checks that compare with -1 (libc’s convention) rather than a negative error number.

Explained in x86-64 in fifteen minutes and The runtime, helper by helper.

The frontend is Python on top of asttoolchain

Decided. The compiler runs on the host in Python: CPython’s ast reads the program, frontend.py checks the subset, codegen.py writes the assembly.

Instead of writing a parser first.

Because the design reads programs “using Python’s own ast module, so we don’t have to write a parser yet”, and the review deferred an assembly parser to later work. A consequence worth knowing: ast is CPython’s own grammar, so the frontend and the oracle always agree on what a program says; only the subset check is aython’s.

You can see it: aython run needs CPython on the machine that compiles, but not on the one that runs the executable.

Explained in From source to a checked program.

The self-hosted parser's output is a canonical text, checked against referencestoolchain

Decided. parse.s prints one s-expression per statement, in a fixed spelling; aython sexpdump prints the same from ast, and CI diffs them on every corpus file. The tokenizer is checked the same way against aython tokdump. The sexp is syntactic: semantic checks stay in frontend.py.

Instead of checking the parser by reading it, or making it a second frontend with its own subset rules.

Because a text format is diffable: one byte of difference fails the check, on every new corpus file automatically. Keeping semantics out means the two sides cannot drift apart on rules only one of them implements.

You can see it in the sexp step of ci.yml and in docs/parser-design.md.

Explained in Python without Python.

The self-hosted track grows reader, tokenizer, parser, emittertoolchain

Decided. Each piece was built and checked before the next: a file reader, then a tokenizer, then the parser and tree printer, then a straight-line emitter.

Instead of writing the parser and emitter together and testing the result end to end.

Because, in the design’s words, the reader is libc calls with no decisions in it, so it cannot miscompile anything; the tokenizer needs only the reader plus the arena; the parser needs only tokens. Each slice is verifiable by diffing bytes.

You can see it: dump.s, tok.s, parse.s, emit.s are four separate programs, and parse.s begins with a line-for-line copy of tok.s.

Explained in Python without Python.

The straight-line emitter is checked by behaviour, not by its assemblytoolchain · changed in the building

Decided. emit.s reads the sexp text and lowers only straight-line programs; emitdiff.sh compiles each such corpus program both ways and requires the same stdout and exit status.

Instead of the plan to move the emitter once, whole, after the tree printer was stable, and to compare its assembly with the host’s.

Because the emitter moved in two steps instead, the straight-line subset first, lowered straight from the sexp text; and its frame is laid out differently (a fixed number of temporaries, variables in order of first appearance), so its offsets can never match the host’s byte for byte, while its behaviour must.

You can see it in parser/emitdiff.sh and the Slice 5 section of docs/parser-design.md.

Explained in Python without Python.

Performance #

Correctness first; speed is measured, never assumedperformance

Decided. Speed was not a goal of the first version. It is measured by aython bench on native x86-64 Linux, and CI runs the benchmarks only as a smoke test (--quick) that checks no number.

Instead of optimising as the code was written, or timing in CI.

Because the design’s priorities put matching CPython first and speed third (“Speed comes later. Control flow comes later. Correctness first.”), and timing on shared CI runners is noise. In docs/bench-design.md’s words, the harness exists so the first optimisation has something to move, and to keep every later one honest.

You can see it in the bench step of ci.yml, and in bench/results/, where each file names its machine.

Explained in How fast, and why.

Alternating rounds, best of Nperformance

Decided. Each program is built once, then the executable and python3 are timed in alternating order (even rounds the executable first, odd rounds CPython first), and the best round on each side is reported, with every round in a table underneath.

Instead of timing each side in one block, or reporting the mean.

Because alternation cancels slow drift of the machine, and the minimum discards the rounds in which something else took the core. The per-round table is kept so that a two-peaked run cannot hide behind a minimum.

You can see it in src/aython/bench.py and the per-round tables in bench/results/.

Explained in How fast, and why.

Arguments in registers; the arity check staysperformance · measured

Decided. Calls to user functions pass up to six arguments in rdi, rsi, rdx, rcx, r8, r9, with the count in r10d; the callee compares the count before adopting its arguments.

Instead of passing arguments on the stack (the first layout), and instead of specialised fast paths that skip the arity check.

Because the stack layout cost every call an alignment pad, a push per argument and a cleanup. Skipping the arity check was rejected twice: first on analysis (one compare and one branch), then on measurement. Deleting the check from a call-heavy loop made it slower, while replacing it with the same number of nop bytes timed the same as keeping it, so what moved was code layout, not work.

You can see it in any call fn_... site in the Assembly reader: the count is loaded into r10d just before the call.

Explained in Emitting assembly and How fast, and why.

Remove provably net-zero work, nothing riskierperformance · measured

Decided. return <local> moves the slot’s reference instead of an incref followed by a decref of the same pointer, and a comparison of a local against an int constant (n < 2) calls a helper that takes the bound as a raw number (obj_lt_imm and its siblings) instead of boxing it.

Instead of a frameless fast path for leaf functions, a shortcut that leaves the last argument in rax, or eliding incref/decref pairs in general.

Because the two changes delete calls whose net effect is provably zero, so they cannot change behaviour. The rejected ones either measured flat, or could not be proved: functions containing try need a real rbp because the unwinder restores it, and the hot incref/decref pairs are not provably balanced.

You can see it at obj_lt_imm in runtime.s, and in the “Fourth optimization” section of docs/bench-design.md, which lists what was tried.

Explained in How fast, and why.

Process #

Grow in slices, each with its own proofprocess

Decided. The language grows one construct at a time, and each slice ships with corpus programs proving every path through it. The order was chosen so that each step needed one new idea: if first (two paths that rejoin, no merge logic because values live in slots), while second, def third (a frame with adopted arguments), for fourth (a loop whose test the compiler writes), try fifth (a jump to a recorded address).

Instead of implementing a large part of the language at once.

Because each slice then adds exactly one piece of machinery, which the design names for every step (for try: “the handler stack and the kind id”), and its corpus proves that piece before the next slice leans on it. Principle 5 in the design: grow in slices.

You can see it in the Program contract section of docs/core-design.md, which gives the reason for each step of that order.

Explained in Emitting assembly.

The documentation is part of the changeprocess

Decided. A behaviour change and its documentation ship in the same pull request. docs/ holds proposals and decisions; README.md describes only what exists now. When the building departs from a design, the design says so in a “What changed in the building” section.

Instead of documentation as a follow-up.

Because a statement that was true before a change and false after it is a defect of that change, wherever it is written. That rule is why this chapter can cite the design documents as the record of what was decided.

You can see it in AGENTS.md, “Documentation moves with the change”, and in the “What changed in the building” sections this page quotes.

Explained in this chapter.

A ratchet against regressions in reachprocess

Decided. CI fails when the stdlib census accepts fewer files than a floor, currently 31. A slice that raises the count raises the floor in the same change.

Instead of no check, or an exact count.

Because the corpus is shaped for the subset and cannot notice when a change quietly stops accepting real-world code; an exact count would fail whenever CI’s CPython changed.

You can see it in the stdlib-census --min-accepted step of ci.yml.

Explained in Measuring against the real world.

Numbers only from native hardwareprocess

Decided. A timing or behaviour claim is only reported from native x86-64 Linux. Numbers taken under emulation are never reported.

Instead of accepting numbers from whatever machine is at hand.

Because AGENTS.md states that timings and behaviour claims are only meaningful on native x86-64 Linux hardware: the executables are built for it, and anything else measures the emulator as much as the program.

You can see it in AGENTS.md, and in the rule this site follows: a page may quote only the timings recorded in bench/results/, each file of which names its machine.

Explained in How fast, and why.

The Python is written to one standardprocess

Decided. Command lines use typer; output goes through logging; every module, class and function has a docstring with Args: and Returns:; numbers and strings with meaning are named constants.

Instead of whatever each file’s author preferred.

Because AGENTS.md states the rules without a separate reason. Their effect is that every module reads the same way: a named constant with a comment (BYTE_BACKSLASH = 0x5C in tokdump.py) explains itself where a bare 0x5C would not, and a docstring says what each argument means.

You can see it in AGENTS.md, “Python code standards”, and in any module under src/aython/.

Explained in this chapter.

Non-goals #

The design also lists what the subset does not do, on purpose, and each item is either refused at compile time or a documented divergence. The main ones, from the Non-goals section of docs/core-design.md:

Not done What happens instead Reason recorded in the design
Integers past 64 bits OverflowError Big integers need their own allocator and arithmetic
Cycle collection Cycles leak; printing and comparing them abort at a depth guard The leak is accepted as long as it never crashes; real cycle collection is deferred
Nested def, closures, first-class functions, globals read in functions Refused None beyond the rule: a body may name only its parameters and its own assignments
Generators, generator expressions, with Refused Lazy iterators are out of scope; enumerate, zip and reversed build lists
except ... as, raise ... from, exception objects Refused Principle 3: no tracebacks and no exception objects; a failure carries only its kind id
Bytes, non-ASCII strings Refused or ValueError Strings are ASCII so that bytes always equal characters
Recovery from native stack overflow Deep recursion faults instead of aborting cleanly None: the design records the fault as a known limit
Any target but x86-64 Linux Not built Two targets would double the learning for no benefit

Where this lives #

Decision area Where it is recorded
Principles, subset, object layout, review decisions, libc change, non-goals docs/core-design.md
Benchmark method and each optimisation, with what was rejected docs/bench-design.md
Self-hosted track: slices, order, conventions, what changed docs/parser-design.md
The stdlib census and its floor docs/stdlib-census.md
Workflow, documentation rule, code standards AGENTS.md
Ownership and calling-convention rules as the runtime states them the header comment of runtime.s
The filter on this page docsite/static/widgets/decisions.js

Check yourself #

Check yourself

  1. Why does the judge not compare standard error?

    1. It is too slow to capture
    2. aython deliberately prints one line where CPython prints a traceback, so stderr would always differ; the judge checks the error kind instead
    3. CPython does not write to stderr
    4. Standard error is not deterministic on Linux
    Answeraython deliberately prints one line where CPython prints a traceback, so stderr would always differ; the judge checks the error kind instead. Aborting with one line is a design decision (no tracebacks, no exception objects). The pass check compares stdout bytes and exit status; abort cases check that the ELF’s stderr names the expected kind.
  2. A program runs x = 2**62 * 4. What does aython do, and why?

    1. Prints the same big integer as CPython
    2. Prints a wrapped-around negative number
    3. Aborts with OverflowError, because ints are 64-bit and a wrapped value would be a silent wrong answer
    4. Refuses the program at compile time
    AnswerAborts with OverflowError, because ints are 64-bit and a wrapped value would be a silent wrong answer. Integers are boxed signed 64-bit values with the overflow flag checked after each operation. Wrapping would pass for correct output; aborting is the honest failure, documented as a divergence.
  3. Why does incref on None do nothing?

    1. None is not an object
    2. Its reference count is the SENTINEL, and incref/decref skip any count at or above it
    3. The code generator never emits it
    4. None is copied, not referenced
    AnswerIts reference count is the SENTINEL, and incref/decref skip any count at or above it. The singletons and the small ints are immortal: they live in the data section with a count of 2^62, and the two helpers test refcnt >= SENTINEL first.
  4. The original design said “no libc, only direct system calls”. What changed, and what stayed hand-written?

    1. Everything moved to libc, including malloc
    2. Only the kernel crossing and startup moved to libc; the arena allocator, object model and abort messages stayed hand-written
    3. Nothing changed
    4. Printing moved to printf
    AnswerOnly the kernel crossing and startup moved to libc; the arena allocator, object model and abort messages stayed hand-written. “What changed in the building” records the move: crt calls main, and write, mmap, open, read, close, _exit go through libc wrappers. All allocation and printing remain in runtime.s.
  5. Why is a method name allowed only once across the whole program?

    1. To keep the symbol table small
    2. Because c.m(...) is resolved at compile time by its short name to one flattened function, which is only sound if the name is unique; instances carry no class tag to dispatch on
    3. Because CPython requires it
    4. To make printing faster
    AnswerBecause c.m(...) is resolved at compile time by its short name to one flattened function, which is only sound if the name is unique; instances carry no class tag to dispatch on. Instances are plain dicts with no class pointer, so there is nothing to look a method up in at run time. Unique names (and no overrides of inherited methods) make the compile-time choice the right one.