Chapter 5 of 1156 min read
The runtime, helper by helper
The hand-written assembly the generated code calls: integers, floats and their printing, strings, lists, dicts, sets, print, and the clean abort.
The assembly the frontend emits does almost nothing by itself: it boxes literals, moves pointers between stack slots, and calls helpers. Everything a Python program means, from 7 // -2 to the order a set prints in, is decided inside runtime.s, one hand-written file of 16217 lines. This chapter walks through it family by family, showing the instructions that make each result match CPython byte for byte, and the few places where it does not.
How the file is laid out #
runtime.s exports 177 symbols with .globl. Generated code may call only those; everything else in the file is internal. The regions follow each other in this order, each opened by a banner comment:
| Region | Lines of runtime.s | Exported symbols | For example |
|---|---|---|---|
| Type tags, singletons, the small-int cache, globals | 53–280 (228) | 19 | type_none, type_bool, type_int, type_list |
| Abort stubs and try/except unwinding | 281–495 (215) | 19 | abort_msg, abort_type, abort_index, abort_key |
| Operand checks, the allocator, the write loop, reference counts | 496–752 (257) | 3 | arena_used, aython_incref, aython_decref |
| Integer arithmetic, and the operator dispatch to other types | 753–1769 (1017) | 14 | int_new, int_add, int_sub, int_or |
| Strings: build, concatenate, repeat, slice, index | 1770–2102 (333) | 5 | str_new, str_concat, str_repeat, str_substr |
| Truthiness and comparisons | 2103–3605 (1503) | 15 | aython_not, obj_lt, obj_le, obj_gt |
| len, lists, tuples | 3606–3841 (236) | 5 | obj_len, list_new, list_append, tuple_new |
| Dicts: hash, lookup, insert, grow | 3842–4145 (304) | 1 | dict_new |
| Ranges, subscripts and slices | 4146–6500 (2355) | 14 | range_new, obj_getitem, unpack_getitem, obj_setitem |
| Printing and repr() | 6501–8220 (1720) | 5 | aython_print_space, aython_print_newline, aython_print_obj, print_repr |
| Methods of str, list and dict | 8221–10374 (2154) | 25 | str_split, str_join, str_find, str_replace |
| Sets | 10375–12542 (2168) | 23 | set_new, set_add, set_discard, set_remove |
| Files, argv, exit | 12543–12934 (392) | 5 | file_read_all, file_write_all, file_append_all, argv_list |
| Everyday builtins (sum, sorted, min, chr, isinstance, …) | 12935–13776 (842) | 12 | str_of_value, int_abs, sum_of, min_of |
| Process entry: arena_init and main | 13777–13817 (41) | 2 | arena_init, main |
| Floats: arithmetic, comparison, hashing, Ryu printing | 13818–16217 (2400) | 10 | DOUBLE_POW5_SPLIT, DOUBLE_POW5_INV_SPLIT, float_new, float_add |
Every helper keeps the same three promises, and the rest of this chapter takes them for granted:
- Arguments are borrowed, results are owned. A helper never consumes the objects it is given. What it returns is a new reference the caller must release. Objects in memory states this rule and the refcounts that follow from it.
- The System V calling convention. Arguments arrive in
rdi,rsi,rdx,rcx; the result leaves inrax. A helper savesrbx,rbpandr12tor15before using them, and most open by pushing all six whether they need them or not, so every helper’s frame looks the same. x86-64 in fifteen minutes explains the convention. Six pushes after the return address leaversp8 bytes off a multiple of 16; that matters only for calls into libc, andwrite_all, the helper that callswrite, subtracts 8 more first. That pad is right whenwrite_allis itself called with an aligned stack; the machine chapter shows the caller,aython_print_newline, that does not. - Failure never returns. A helper that finds a bad operand jumps to an
abort_*stub. With notryactive the process prints one line to stderr and exits; inside atrythe stub unwinds to the handler. How that works is near the end of this chapter.
A typical helper: int_add #
a + b in Python can mean integer addition, float addition, list, tuple or string concatenation, or a TypeError. The emitted code does not know which, because it does not track types. It calls int_add every time, and int_add decides by reading each operand’s type pointer at offset 8:
flowchart TD
start["int_add(rdi = a, rsi = b)"] --> fast{"both tags int or bool?"}
fast -- yes --> add["add rax, [r12 + 16]"] --> ovf{"overflow flag?"}
ovf -- no --> box["int_new(sum)"]
ovf -- yes --> abortO["abort_overflow"]
fast -- no --> flt{"either side a float?"}
flt -- yes --> fadd["float_add"]
flt -- no --> seq{"left is list, tuple or str?"}
seq -- list --> lc["list_concat"]
seq -- tuple --> tc["tuple_concat"]
seq -- str --> sc["str_concat (right must be str)"]
seq -- no --> abortT["abort_type"]
class add,box accent
class abortO,abortT bad
The integer case is tested first because loops such as fib and running sums spend nearly all their time there. A bool passes the same test: True and False carry 1 and 0 at offset 16, exactly where an int keeps its value, so True + 1 needs no special case. The excerpt keeps the fast path and the addition itself:
runtime.s · int_addlines 791–911 mov r12, rsi # r12 keeps right borrowed object
# Fast path first: both int-like goes straight to the add, skipping
# the six sequence-tag compares below (fib/sum loops live here).
...
jne .Ladd_seq # left is neither: sequence/error path
.Ladd_lint: # left int-like; same test for the right operand
mov rax, [r12 + 8] # rax = right tag at offset 8
...
je .Ladd_compute # both int-like: add at once
.Ladd_seq: # at least one side is not int-like: float, concat, or TypeError
mov rax, [rbx + 8] # rax = left tag at offset 8
...
call check_intlike_rbx_r12 # both operands must be int-like; bools count as 1/0
.Ladd_compute: # both sides int-like (fast path or validated slow path)
mov rax, [rbx + 16] # rax gets left boxed value
add rax, [r12 + 16] # add right boxed value, sets flags
jo abort_overflow # abort OverflowError on signed overflow
mov rdi, rax # rdi gets raw sum for int_new
call int_new # box sum as new owned int
pop r15 # restore r15
The add instruction sets the processor’s overflow flag when the true sum does not fit in 64 signed bits, and jo (“jump if overflow”) reads it. sub and imul set the same flag, so int_sub and int_mul end the same way. An aython int is a 64-bit value in a box, not CPython’s arbitrary-precision integer: the decision table in docs/core-design.md records “Boxed i64, abort OverflowError on overflow. No bigint in MVP”, because big integers would need an allocator and arithmetic of their own. 2 ** 63 is therefore an OverflowError here and a 19-digit number in CPython. The corpus pins that difference with abort:OverflowError programs, and Where it differs from CPython lists it.
Boxing the result goes through int_new, which never allocates for small values. Ints from -5 to 256 are a table of immortal boxes in .data, the same range CPython caches:
runtime.s · int_newlines 753–789# ---- int_new ----------------------------------------------------------
# Input: rdi = i64 value. Output: rax = new owned int.
.p2align 4 # align function to 16 bytes
.globl int_new # make int_new visible to linker
.type int_new, @function # declare int_new as function
int_new: # entry, rdi holds raw int64 value
cmp rdi, -5 # below the cached range?
jl intnew_alloc # uncached negatives allocate fresh below
cmp rdi, 256 # above the cached range?
jg intnew_alloc # uncached positives allocate fresh below
lea rax, [rdi + 5] # rax = cache index 0..261 for value -5..256
imul rax, rax, 24 # rax = byte offset into the table (24 bytes each)
lea rcx, [rip + small_ints] # rcx = cache base (rip+index is illegal)
add rax, rcx # rax = cached immortal int, no alloc and no free ever
ret # return the shared singleton, like CPython's small-int cache
intnew_alloc: # uncached value: fall into the bump/free-list path
push rbp # save rbp for frame chain
mov rbp, rsp # rbp marks this frame
push rbx # save rbx, holds value (the only callee-saved reg this path uses; two pushes keep 16-alignment)
mov rbx, rdi # rbx keeps value across alloc
mov rax, [rip + free_int_head] # rax gets int free list head
test rax, rax # check if a recycled header is waiting
jz intnew_bump # bump-allocate when the free list is empty
mov rcx, [rax + 16] # rcx gets next free link from payload slot
mov [rip + free_int_head], rcx # pop the head off the free list
jmp intnew_fill # skip bump path, fill the recycled block
intnew_bump: # bump path for fresh 24 bytes
mov rdi, 24 # rdi gets 24 byte int size
call alloc_raw # get fresh bytes from arena
intnew_fill: # fill reused or fresh block
mov qword ptr [rax], 1 # set refcnt 1, one owned reference
lea rcx, [rip + type_int] # rcx gets address of int tag
mov [rax + 8], rcx # store int type at offset 8
mov [rax + 16], rbx # store boxed value at offset 16
pop rbx # restore rbx
pop rbp # restore rbp
ret # return new owned int in rax
lea rax, [rdi + 5] turns the value into a table index, and imul rax, rax, 24 multiplies by the box size. Everything outside the range takes a 24-byte block from the int free list, or from the arena when the list is empty.
Floor division and modulo #
C and the x86 idiv instruction divide by truncating toward zero: -7 / 2 is -3, remainder -1. Python floors toward minus infinity: -7 // 2 is -4, and -7 % 2 is 1, so that a == (a // b) * b + a % b holds and the remainder takes the divisor’s sign. int_floordiv runs idiv and then repairs the result:
runtime.s · int_floordivlines 1430–1498# Zero divisor aborts before touching idiv (which would trap as #DE).
# INT64_MIN // -1 would overflow: abort OverflowError.
.p2align 4 # align code to 16 bytes for fast fetch
...
mov rcx, [r12 + 16] # rcx loads divisor value at offset 16
test rcx, rcx # test divisor for zero
jz abort_zero # abort ZeroDivisionError before idiv would trap
movabs rdx, 0x8000000000000000 # rdx holds INT64_MIN for overflow check
cmp rax, rdx # check whether dividend equals INT64_MIN
jne floordiv_ok # skip overflow test unless dividend is INT64_MIN
cmp rcx, -1 # check whether divisor equals -1
je abort_overflow # INT64_MIN // -1 overflows, abort OverflowError
floordiv_ok: # inputs validated, safe to divide
...
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
...
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
The repair needs one test. If the remainder is zero, truncating and flooring agree. Otherwise xor r8, rcx sets the sign flag exactly when the remainder and the divisor have different signs, and only then was the truncated quotient one too high. Two cases are handled before idiv because the instruction itself would fault on them: a zero divisor, and INT64_MIN // -1, whose true result does not fit in 64 bits.
int_mod uses the same sign test and, when the signs disagree, adds the divisor to the remainder:
runtime.s · int_modlines 1500–1564 mov rcx, [r12 + 16] # rcx loads divisor value at offset 16
test rcx, rcx # test divisor for zero
jz abort_zero # abort ZeroDivisionError before idiv would trap
...
cqo # sign-extend rax into rdx:rax for signed divide
idiv rcx # rax=C quotient, rdx=C remainder, rcx=divisor kept
test rdx, rdx # test whether C remainder is zero
...
mov r8, rdx # r8 copies remainder for sign test
xor r8, rcx # xor sign bits of remainder and divisor
jns mod_have # same sign means C remainder already has divisor sign
add rdx, rcx # signs disagree, shift remainder by one divisor
jo abort_overflow # adding divisor overflowed, abort OverflowError
The judge holds both helpers to CPython’s output on tests/mvp/pass_floor.py:
tests/mvp/pass_floor.pylines 1–12# mvp: pass
a = 7 // 2
b = 0 - 7
c = b // 2
d = b % 2
e = 7 // (0 - 2)
f = 7 % (0 - 2)
print(a)
print(c)
print(d)
print(e)
print(f)
3
-4
1
-4
-1
Floats: boxes, promotion, and printing the shortest digits #
A float is a 24-byte box like an int: refcount, a pointer to type_float, and the double’s 64 bits at offset 16. float_new stores the bits exactly as it receives them, and a literal’s bits are computed by the code generator with Python’s own float parsing, so 0.1 in the source is the same double in aython as in CPython. Floats have their own free list and no small-value cache, because CPython caches none.
runtime.s · float_newlines 14545–14611float_new: # entry, rdi holds raw double bits
...
mov rax, [rip + free_float_head] # rax gets float free list head
...
mov [rip + free_float_head], rcx # pop the head off the free list
...
call alloc_raw # get fresh bytes from arena
...
mov qword ptr [rax], 1 # set refcnt 1, one owned reference
lea rcx, [rip + type_float] # rcx gets address of float tag
...
mov [rax + 16], rbx # store f64 payload bits at offset 16
...
lea rcx, [rip + type_float] # float tag?
...
lea rcx, [rip + type_float] # float tag?
Arithmetic with a float on either side goes through num_arith_setup, which converts both operands to doubles in xmm0 and xmm1, and then one SSE instruction (addsd, subsd, mulsd, divsd). These are the IEEE-754 operations CPython’s float type also uses, so the results agree to the bit. Overflow rounds to inf instead of aborting, and a zero divisor aborts ZeroDivisionError, both as in CPython. / always calls float_div. With two ints, converting each to a double first could round twice, so float_div hands them to int_true_div_exact, which computes the exact quotient with integer instructions and rounds it once, as CPython’s long_true_divide does.
Why printing a float is hard #
The double nearest to 0.1 is 0.1000000000000000055511151231257827. Python prints 0.1 because it prints the shortest decimal string that reads back as the same double: no fewer digits would identify it, and more would be noise. Finding that string is a real algorithm. CPython uses David Gay’s dtoa.c. aython ports Ryu, a later algorithm that needs only 64- and 128-bit integer arithmetic and two precomputed tables of powers of five, which suits hand-written assembly with no floating-point library:
runtime.slines 15586–15594# ---- ryu_d2d (Ryu shortest-digits core, ported from ryu/d2s.c) -------------------
# Input: rdi = abs bits of a nonzero finite double. Output: rax = M, rdx = e
# with value = M * 10^e, the shortest decimal that round-trips (matching
# CPython repr digits exactly; formatting happens in print_float). The port
# follows d2d() op for op: decode, power-of-5/10 scaling through the split
# tables, the q<=21 / q<=1 / q<63 trailing-zero refinements, then the digit
# loop (general ~0.7% path plus the specialized two-at-a-time fast path).
# All arithmetic is integer (mul/div/shift); doubles never appear here.
ryu_d2d: # entry: rdi holds abs bits (nonzero, finite)
Before Ryu runs, print_float sorts out the values that have no digits to find. It splits the 64 bits into sign, exponent field and mantissa with shifts and masks:
runtime.slines 15921–15935 mov rax, [rbx + 16] # rax = f64 payload bits
mov r12, rax # r12 = bits for the sign math
shr r12, 63 # r12d = sign (0/1, zero-extended)
mov rcx, rax # rcx = bits for the exponent math
shr rcx, 52 # shift the exponent field down
and ecx, 0x7FF # ecx = biased exponent field E2
cmp ecx, 0x7FF # infinite or nan?
je .Lpf_special # spelled by kind below
test ecx, ecx # zero exponent field?
jnz .Lpf_ryu # normal: Ryu digits below
mov rdx, rax # subnormal or zero: isolate the mantissa
shl rdx, 12 # drop the sign and exponent fields
shr rdx, 12 # rdx = M (low 52 bits)
test rdx, rdx # zero mantissa?
jz .Lpf_zero # +/-0.0: fixed "0.0" spelling below
An exponent field of all ones means inf (mantissa zero) or nan (anything else; CPython prints nan without a sign, and so does this). An exponent and mantissa both zero means a zero, printed 0.0 or -0.0. Everything else, including the subnormals below 2−1022, goes to ryu_d2d, which returns the digits as an integer M and an exponent e with value = M × 10e.
Fixed or scientific #
format_float then lays the digits out the way CPython’s repr does. Let decpt be where the decimal point falls: e plus the number of digits in M. CPython writes fixed notation when decpt is above -4 and at most 16, and scientific notation otherwise, with at least two exponent digits. The two comparisons are these:
runtime.slines 16043–16048.Lff_nosign: # cursor in r8: fixed when -4 < decpt <= 16, like CPython
cmp r10, 16 # decpt > 16?
jg .Lff_sci # yes: scientific (1e16 is "1e+16")
cmp r10, -4 # decpt <= -4?
jle .Lff_sci # yes: scientific (1e-05 is "1e-05", but 0.0001 is fixed)
jmp .Lff_fixed # otherwise fixed notation
These are the float lines of tests/mvp/pass_repr.py, with what CPython prints for them at build time. It is a pass program, so the judge requires aython’s output to be the same bytes:
| Literal | Printed |
|---|---|
1.5 |
1.5 |
-0.0 |
-0.0 |
0.0 |
0.0 |
1e16 |
1e+16 |
1000000000000000.0 |
1000000000000000.0 |
0.0001 |
0.0001 |
1e-05 |
1e-05 |
1e400 |
inf |
-1e400 |
-inf |
1e400 - 1e400 |
nan |
1e16 has one digit and decpt 17, one past the limit, so it prints as 1e+16; 1000000000000000.0 has decpt 16 and stays fixed. JavaScript draws the same line at 21 digits instead, which is why the figure below shows both.
float_new fills, and the text print_float writes. Type any float literal or 64 bits in hex. The examples each land on a different rule: try 1e15 against 1e16, 0.0001 against 1e-05, and 5e-324, the smallest subnormal.Hashing floats #
A float used as a dict key or set member is hashed by obj_hash_float, a port of CPython’s _Py_HashDouble:
runtime.slines 15359–15368# ---- obj_hash_float: CPython _Py_HashDouble, exactly --------------------------------
# Input: rdi = borrowed float. Output: rax = u64 hash. Leaf (no calls).
# frexp splits the value (bit ops, identical to C frexp), then the mantissa
# folds 28 bits at a time with a 61-bit rotate (P = 2**61 - 1), matching
# CPython op for op. Integral floats hash like their int, so {1: 'a'}[1.0]
# hits and True maps with 1.0, like CPython. NaN hashes to 0 (CPython 3.14
# uses a nondeterministic pointer hash instead; observably equivalent here
# because nan != nan, so only identical objects hit, via the identity fast
# path before hashing, and distinct objects miss either way).
obj_hash_float: # entry: rdi holds borrowed float pointer
Because an integral float hashes like the int it equals, {1: "a"}[1.0] finds its key, as in CPython. That holds only for magnitudes below 261 − 1. obj_hash_float reduces modulo 261 − 1, as CPython does for floats and ints alike, but the int case of obj_hash (below) returns the value unreduced. Reading the two, {2**61: 1}[2.0**61] hashes the float to 1 and the int to 261, misses, and aborts KeyError, where CPython prints 1. The NaN case is where the comment’s argument is narrower than it sounds. For lookups it holds. For iteration order it does not: CPython 3.14 hashes each NaN by its address, and a set’s print order depends on its members’ hashes. aython puts every NaN in the bucket for hash 0, so a set holding NaNs and other numbers prints the NaNs where CPython would not, and CPython’s own order changes with where its objects happen to sit in memory. No corpus program depends on it.
Strings #
A str is a 32-byte header (refcount, type, length, data pointer) and a separate buffer holding exactly len bytes, with no terminating zero. The frontend refuses any literal that is not ASCII, and at run time read_file and argv() abort ValueError on any byte of 128 or more, while chr refuses any code above 127. So a byte is always a character, len is the byte count, and s[i] is one load.
runtime.s · str_newlines 1770–1837# A str is a 32-byte header (refcnt/type/len/data-ptr) plus an exact-size
# byte buffer. ASCII-only by frontend validation, so byte length equals
# character length and indexing needs no decoding. Buffers leak by design
# (same rule as list item buffers); 32-byte headers recycle through
# free_str_hdr.
...
str_new: # rdi = byte pointer (borrowed), rsi = byte length -> new owned str
...
call alloc_raw # rax = fresh byte buffer (or aborts MemoryError)
...
rep movsb # copy the literal bytes into the new buffer
...
call str_from_buf # rax = new owned str wrapping the buffer
...
str_from_buf: # rdi = filled byte buffer (adopted), rsi = length -> new owned str
...
call alloc_raw # rax = fresh header (or aborts MemoryError)
...
mov [rax + 16], r13 # store length at offset 16
mov [rax + 24], r12 # store data pointer at offset 24
str_new copies bytes into a fresh buffer and wraps it; str_from_buf wraps a buffer that is already filled. Concatenation sizes the new buffer exactly and copies both operands with rep movsb, the x86 string-copy instruction that moves rcx bytes from [rsi] to [rdi]:
runtime.s · str_concatlines 1839–1892 add r13, [r12 + 16] # r13 = total length
jo abort_overflow # absurd sizes overflow instead of wrapping
...
call alloc_raw # rax = fresh buffer (or aborts MemoryError)
...
rep movsb # copy left bytes into the new buffer
...
rep movsb # copy right bytes after the left run
...
call str_from_buf # rax = new owned str wrapping the buffer
str_repeat multiplies the length by the count with imul and aborts OverflowError if that overflows, before allocating; a count of zero or less gives an empty string. Every result is a new object, including a one-character s[i]. Old buffers are never freed. The headers return to a free list when their refcount reaches zero, but a byte buffer has no size class to go back to, so it leaks by design, as list and dict buffers do. A program has 64 MiB of arena before MemoryError.
Strings compare by unsigned bytes, which for ASCII is the same order as CPython’s comparison by code point.
The repr of a string #
Inside a container, and under repr(), a string is printed with quotes. CPython’s choice of quote has a rule, and both print_quoted (for printing) and repr_quoted_new (for repr(), which must build a str) apply it:
runtime.slines 7210–7217# ---- print_quoted: one str in quotes with backslash escapes ----------------
# CPython repr rules for ASCII, shared with repr_quoted_new: a string
# holding a single quote but no double quote wraps in double quotes,
# everything else wraps in single quotes. Backslash and the wrapping
# quote double up with a backslash, \n \r \t use letter escapes, other
# bytes below 32 or at/over 127 use \xNN, everything else prints bare
# (the non-wrapping quote included).
print_quoted: # rdi = borrowed str
The string lines of tests/mvp/pass_repr.py and what CPython prints for each:
| Literal in the source | Printed by print(repr(...)) |
|---|---|
"" |
'' |
"a" |
'a' |
"'" |
"'" |
'"' |
'"' |
"'\"" |
'\'"' |
"it's" |
"it's" |
'say "hi"' |
'say "hi"' |
"a\\b" |
'a\\b' |
"a\\\"b" |
'a\\"b' |
"\t" |
'\t' |
"\n" |
'\n' |
"\r" |
'\r' |
"\x00" |
'\x00' |
"\x07" |
'\x07' |
"\x08" |
'\x08' |
"\x0b" |
'\x0b' |
"\x0c" |
'\x0c' |
"\x1b" |
'\x1b' |
"\x7f" |
'\x7f' |
"\x1f" |
'\x1f' |
"a\x01b" |
'a\x01b' |
"\\" |
'\\' |
"\\n" |
'\\n' |
Printing #
print(a, b) compiles to one aython_print_obj per argument, aython_print_space between them and aython_print_newline at the end. Each writes straight to file descriptor 1 through write_all, a loop around libc’s write that retries until every byte is out. Nothing is buffered, so output and an abort message can never be reordered, and the process can leave through _exit without flushing anything.
aython_print_obj is str() and print_repr is repr(). They differ in one place: a str at the top level prints bare, while a str inside a container prints quoted. Both dispatch the same way, singletons by address first and then the type pointer:
runtime.s · aython_print_objlines 6618–6888aython_print_obj: # entry: rdi holds borrowed object pointer
...
lea rcx, [rip + aython_none] # load immortal None address
...
je po_none # print None word if same object
lea rcx, [rip + aython_true] # load immortal True address
...
je po_true # spells True, not 1
lea rcx, [rip + aython_false] # load immortal False address
...
je po_false # spells False, not 0
...
lea rcx, [rip + type_int] # int type marker address
...
je po_int # jump to int payload path
lea rcx, [rip + type_float] # float type marker address
...
je po_float # jump to float payload path
lea rcx, [rip + type_list] # list type marker address
...
je po_list # jump to list path
lea rcx, [rip + type_tuple] # tuple type marker address
...
je po_tuple # jump to tuple path
lea rcx, [rip + type_str] # str type marker address
...
je po_str # jump to str spelling path
lea rcx, [rip + type_dict] # dict type marker address
...
je po_dict # jump to dict path
lea rcx, [rip + type_set] # set type marker address
...
je po_set # jump to set path
lea rcx, [rip + type_range] # range type marker address
...
je po_range # jump to range path
jmp abort_type # unknown type aborts with error
...
je po_set_next # dummy: skip
None, True and False are recognised by their addresses before any tag is read. They are the only objects of their types a program can hold, so the dispatch has no case for the type_bool or type_none tags at all; a bool’s payload, 1 or 0, is never read here, which is how True prints as True and not 1. An int is written by print_int_value, which divides by 10 into a buffer from the right. -9223372036854775808 is the one value whose negation does not fit in 64 bits, so it is written from a fixed string:
runtime.slines 6551–6567print_int_value: # entry: rdi holds signed 64-bit value
push rbp # save caller frame pointer
mov rbp, rsp # start our stack frame anchor
push rbx # save callee-saved rbx
push r12 # save callee-saved r12
push r13 # save callee-saved r13
push r14 # save callee-saved r14
push r15 # save callee-saved r15
mov rbx, rdi # keep number in callee-saved rbx
movabs rcx, 0x8000000000000000 # load INT64_MIN which cannot be negated
cmp rbx, rcx # check for that edge case
jne piv_normal # skip fixed-string path if different
mov rdi, 1 # stdout fd for INT64_MIN write
lea rsi, [rip + str_int64min] # point at pre-spelled minus 9223372036854775808
mov rdx, 20 # that spelling is 20 bytes long
call write_all # write the edge-case digits
jmp piv_ret # skip normal path to cleanup
A dict prints its dense entries front to back, in insertion order; a set prints its table slots in order, and an empty set prints set(), never {}. Nesting deeper than 100 levels aborts RecursionError instead of overflowing the native stack.
Lists and tuples #
A list is a 40-byte header and a separate array of pointers. list_new starts it at 8 slots, and list_append doubles the array when it is full:
runtime.s · list_appendlines 3694–3745 cmp r13, r14 # compare len against cap for room
...
shl r15, 1 # r15 holds newcap, old cap times 2
...
call alloc_raw # rax holds fresh bigger buffer
...
rep movsq # copy len slots from old buffer to new buffer
mov [rbx + 32], r10 # publish new buffer, old buffer leaks by design
...
call aython_incref # incref item, list now owns one reference
inc qword ptr [rbx + 16] # len grows by one
When len reaches cap, the new capacity is cap shifted left by one, a new array is taken from the arena, the len pointers are copied with rep movsq (eight bytes at a time), and the old array is abandoned. Doubling makes appending cost a constant amount per element on average: the copies after n appends add up to fewer than 2n pointers. CPython over-allocates by about an eighth instead, to waste less memory; the growth pattern is invisible to a program, so the simpler rule costs nothing in correctness. The appended item is increfed because the list now holds a reference of its own.
list_concat and list_repeat size their result exactly (cap == len), except that an empty result comes from list_new, so append always finds a capacity of at least one to double.
A tuple uses the same 40-byte header and the same free list. It is built with tuple_new and tuple_append while its display is evaluated, and nothing can change it afterwards: obj_setitem aborts TypeError on a tuple. Every empty tuple is one immortal object in .data, empty_tuple, so () is () is True, as in CPython.
Dicts #
A dict is a 48-byte header and two buffers:
| Offset | Field | Holds |
|---|---|---|
| +16 | len |
live entries |
| +24 | cap |
slots in each buffer, a power of two, 8 at first |
| +32 | indices |
cap 8-byte slots: 0 for empty, otherwise the number of an entry plus one |
| +40 | entries |
cap 24-byte slots of (hash, key, value), dense, in insertion order |
This is the layout CPython has used since 3.6, the “compact dict”. A lookup hashes the key, uses the hash to pick a slot in indices, and follows the number it finds there to an entry. Iteration and printing ignore indices altogether and walk entries from the front, so they see keys in the order they were inserted, which is what the Python language has guaranteed since 3.7.
The hash function #
obj_hash dispatches on the type:
runtime.slines 3901–3932obj_hash: # rdi = borrowed hashable -> rax = u64 hash (aborts TypeError)
mov rax, [rdi + 8] # rax = ob_type at offset 8
lea rcx, [rip + type_int] # int tag?
cmp rax, rcx # compare tag against int
je obj_hash_int # ints hash to their own value
lea rcx, [rip + type_bool] # bool tag?
cmp rax, rcx # compare tag against bool
je obj_hash_bool # True/False hash to 1/0, like CPython
lea rcx, [rip + type_none] # None tag?
cmp rax, rcx # compare tag against None
je obj_hash_none # None hashes to a fixed constant
lea rcx, [rip + type_str] # str tag?
cmp rax, rcx # compare tag against str
je obj_hash_str # strings hash by FNV-1a over their bytes
lea rcx, [rip + type_tuple] # tuple tag?
cmp rax, rcx # compare tag against tuple
je obj_hash_tuple # tuples hash by combining element hashes
lea rcx, [rip + type_float] # float tag?
cmp rax, rcx # compare tag against float
je obj_hash_float # floats hash like CPython (ints stay consistent)
jmp abort_type # lists, dicts, and sets are unhashable, like CPython
obj_hash_int: # int payload is already a good hash
mov rax, [rdi + 16] # rax = boxed value at offset 16
cmp rax, -1 # CPython reserves -1 as the error sentinel (never a hash)
jne obj_hash_int_done # any other value hashes to itself
mov rax, -2 # hash(-1) is -2 in CPython; doubles as the set dummy guard
obj_hash_int_done: # rax = hash
ret # return hash in rax
obj_hash_bool: # bool payload is 0/1, matching CPython hash(True) == 1
mov rax, [rdi + 16] # rax = boxed value at offset 16
ret # return hash in rax
obj_hash_none: # None hashes by CPython's pointer hash of the singleton
Ints hash to themselves and bools to 0 and 1. CPython first reduces an int modulo 261 − 1, so the two agree for every int of magnitude below that, about 2.3 × 1018, and differ above it. -1 becomes -2 because CPython reserves -1 to mean “error” in its C API; copying that keeps the hashes of ordinary ints equal to CPython’s, which matters for sets below. None hashes to the constant CPython 3.14 gives it (0xfca86420). Tuples combine their elements’ hashes with the xxHash-based scheme of CPython’s tuple_hash, and floats use obj_hash_float from above. Lists, dicts and sets abort TypeError, because they are mutable.
Strings are the exception. CPython hashes them with SipHash and a key chosen at random when the process starts, so that an attacker cannot pick strings that collide. aython uses 64-bit FNV-1a, which xors in a byte and multiplies by a prime, byte after byte:
runtime.slines 3935–3954obj_hash_str: # FNV-1a over the string bytes (order-sensitive, stable)
push rbx # save callee-saved rbx (leaf body, keeps frame aligned)
push r12 # save callee-saved r12
mov rbx, [rdi + 24] # rbx = string data pointer
mov r12, [rdi + 16] # r12 = byte length
movabs rax, 0xcbf29ce484222325 # FNV offset basis for 64-bit
test r12, r12 # empty string hashes to the basis itself
jz obj_hash_str_done # skip the loop for ""
obj_hash_str_loop: # one xor-multiply per byte
xor al, [rbx] # fold the next byte into the low byte
mov rcx, 0x100000001b3 # FNV prime for 64-bit (wraps mod 2^64, by design)
imul rax, rcx # multiply by the prime
inc rbx # advance byte pointer
dec r12 # count down remaining bytes
jnz obj_hash_str_loop # hash the next byte
obj_hash_str_done: # rax = FNV-1a of the bytes
cmp rax, -1 # CPython reserves -1 as the error sentinel (never a hash)
jne obj_hash_str_ret # any other value is the hash
mov rax, -2 # -1 maps to -2, exactly like CPython's unicode hash
obj_hash_str_ret: # rax = hash
For dicts the choice is invisible: their order is insertion order whatever the hashes are. For sets of strings it is not, but there CPython disagrees with itself from one run to the next, so there is no fixed output to match. The corpus keeps order-dependent output of string sets out of its programs for that reason (docs/core-design.md, Program contract).
Lookup, insert, grow #
The probe is linear: start at bucket hash & (cap - 1) and step forward one bucket at a time, wrapping at the end, until the slot is empty (a miss) or holds an entry with the same key. The pointer comparison comes first, because the same object is always equal to itself and small ints and singletons are shared; then the stored hash; only then a call to obj_eq:
runtime.slines 4026–4051dict_lookup_probe: # linear probing: an empty slot ends the search
mov [rsp], rax # spill bucket index (the eq call below clobbers rax)
mov rcx, [r12 + rax*8] # rcx = index slot (0 = empty)
test rcx, rcx # empty bucket?
jz dict_lookup_miss # key is not in the dict
dec rcx # rcx = 0-based entry number
imul rcx, rcx, 24 # rcx = byte offset of the entry
lea rcx, [r13 + rcx] # rcx = entry address
mov rdx, [rcx + 8] # rdx = stored key object (borrowed)
cmp rdx, r15 # identical pointers are always equal (small-int singletons hit here, as does `for k in d: d[k]`)
je dict_lookup_hit # same object: skip the eq call entirely
cmp qword ptr [rcx], r14 # compare stored hash against search hash
jne dict_lookup_next # different hash cannot be our key
mov rdi, rdx # rdi = stored key object (borrowed for eq)
mov rsi, r15 # rsi = search key object (borrowed for eq)
call obj_eq # rax = owned immortal bool (eq_true/eq_false only ever return True/False singletons)
# No decref, spill, or reload: the result is provably immortal, so
# releasing it would be a no-op call and the pointer survives whole.
lea rcx, [rip + aython_true] # rcx = immortal True
cmp rax, rcx # check whether the keys compared equal
je dict_lookup_hit # equal keys: the spilled bucket is ours
dict_lookup_next: # advance one bucket, wrapping with the mask
mov rax, [rsp] # rax reloads spilled bucket index
inc rax # next bucket index
and rax, [rsp + 8] # wrap around the table with the parked mask
jmp dict_lookup_probe # test the next bucket
d[k] = v is obj_setitem. Its dict path grows the table first if it is full, then looks the key up; a hit replaces the value in place, which keeps the key’s position in the order, and a miss appends a new entry:
runtime.slines 4419–4439obj_setitem_dict: # dict path: hash, grow if full, replace or insert
mov rdi, r12 # arg = borrowed key for hashing
call obj_hash # rax = u64 hash (aborts TypeError if unhashable)
mov r14, rax # r14 keeps hash (survives the calls below)
mov rax, [rbx + 16] # rax = current length
cmp rax, [rbx + 24] # full? (len == cap)
jne obj_setitem_nogrow # room left, no rehash needed
mov rdi, rbx # arg = borrowed dict to grow
call dict_grow # double capacity, rehash in place (no-op when empty)
obj_setitem_nogrow: # capacity guaranteed, probe for the key
mov rdi, rbx # arg1 = borrowed dict for the lookup
mov rsi, r14 # arg2 = hash for the lookup
mov rdx, r12 # arg3 = borrowed key for the lookup
call dict_lookup # rax = entry address or NULL
test rax, rax # hit?
jnz obj_setitem_replace # key exists: swap the value in place
mov rdi, rbx # arg1 = borrowed dict for the insert
mov rsi, r14 # arg2 = hash for the insert
mov rdx, r12 # arg3 = borrowed key (dict takes its own incref)
mov rcx, r13 # arg4 = borrowed value (dict takes its own incref)
call dict_insert_fresh # insert; assumes absent with room
dict_grow doubles cap, takes two new buffers from the arena, and re-inserts every entry in order with the same linear probe. CPython’s dict probes differently: it mixes the higher bits of the hash into each step (perturb) and grows when two thirds of the table is used. Neither choice can change what a dict prints, because printing does not look at indices. Linear probing is the simplest rule that finds every key, so it is the one used here.
Delete #
del d[k] and d.pop(k) go to dict_remove_at:
runtime.slines 9796–9801# ---- internal: dict_remove_at ----------------------------------------------
# Inputs: rdi = borrowed dict, rsi = 0-based dense entry index.
# Releases the entry's key and value, memmoves later entries shut, and
# rebuilds the index table from the dense run (no tombstones, so later
# probes still terminate at an empty slot). Used by pop and `del`.
dict_remove_at: # entry: dict and dense index -> void
Removing an entry would leave a gap in a probe chain, and a later lookup that reaches the gap would stop too early. CPython solves this by leaving a marker (a “dummy”) in the index and a hole in the entries until the next resize. aython closes the gap in entries by moving the later entries down one, and then clears indices and rebuilds it from scratch, so there are never any markers:
runtime.slines 9839–9871dict_remove_shrunk: # dense run compacted: shrink and rebuild the index
dec qword ptr [rbx + 16] # len shrinks by one
mov rdi, [rbx + 32] # rdi = index buffer to clear
mov rcx, [rbx + 24] # rcx = capacity slot count
xor eax, eax # zero register for stosq
cld # store moves forward
rep stosq # 0 means empty in every index slot
xor r15d, r15d # r15d zeroes the reinsert cursor
jmp dict_remove_test # enter the reinsert loop
dict_remove_reinsert: # publish entry r15 into the fresh index
mov rax, r15 # rax = entry number
imul rax, rax, 24 # rax = byte offset
add rax, r13 # rax = entry address
mov rsi, [rax] # rsi = stored hash
mov rax, [rbx + 24] # rax reloads capacity for the mask
dec rax # mask = cap - 1 (cap is always a power of two)
and rax, rsi # rax = start bucket = hash & mask
mov rdi, [rbx + 32] # rdi = index base (no calls below: stays put)
dict_remove_probe: # linear probe in the fresh (emptier) table
cmp qword ptr [rdi + rax*8], 0 # empty slot?
je dict_remove_place # found the new home
inc rax # next bucket
mov r10, [rbx + 24] # r10 reloads capacity (caller-saved: no calls here)
dec r10 # mask = cap - 1
and rax, r10 # wrap around the table
jmp dict_remove_probe # test the next bucket
dict_remove_place: # winning bucket in rax: publish 1-based slot
lea r10, [r15 + 1] # 1-based slot value for the index
mov [rdi + rax*8], r10 # publish index: bucket -> slot
inc r15 # advance reinsert cursor
dict_remove_test: # loop while cursor < live length
cmp r15, [rbx + 16] # compare cursor against shrunk length
jl dict_remove_reinsert # reinsert the next entry
That makes a deletion cost time in proportion to the size of the dict instead of a constant, and it keeps every probe loop simple. The order is the same as CPython’s either way: the remaining keys keep their relative order, and a deleted key inserted again goes to the end.
obj_setitem, dict_lookup, dict_grow and dict_remove_at as written in runtime.s, with the same hash for every key. Insert keys, delete them, look them up. "Collide" fills one home bucket; "Fill to 8" builds a full table, and a lookup of a missing key then shows the problem described below.for k in d reads entries by position with dict_key_at. The generated loop compares the dict’s length with its length at the start on every pass and aborts RuntimeError when they differ, which is what CPython raises for a dict resized during iteration (tests/mvp/err_dict_resize.py).
Sets #
Sets are where hash order becomes visible. CPython prints and iterates a set in the order of its hash table’s slots, not in insertion order: print({3, 1, 2}) prints {1, 2, 3}. To print the same thing, aython has to put every element into the same slot CPython would, which means the same hashes, the same table size, the same probe sequence, the same handling of deleted slots and the same growth rule. The set helpers are therefore a transliteration of CPython 3.14’s setobject.c, and the dict’s simpler probe is not reused. The comment that opens the region says so:
runtime.slines 10375–10390# ---- Goal 3: sets (CPython's setobject.c, transliterated) --------------------
# A set is a 56-byte header (refcnt/type/used/fill/mask/table/finger) plus
# one combined table of (hash, key) entries, 16 bytes each, at mask+1
# slots. The algorithm mirrors CPython 3.14's setobject.c op for op, so
# iteration and printing (both walk table slots 0..mask, skipping virgin
# and dummy entries) land byte-identical with CPython on every element
# whose hash CPython keeps stable (int/float/bool/None/tuples thereof):
# start bucket hash & mask, runs of LINEAR_PROBES (9) consecutive entries
# then the perturbed jump i = (i*5+1+perturb) & mask with perturb >>= 5,
# virgin slots (key NULL, hash 0) ending a probe, dummy tombstones (key
# set_dummy, hash -1) probed through and reused by later inserts, growth
# when fill*5 >= mask*3 to the smallest power of two above used*4
# (used*2 past 50000 elements), and pop scanning from the finger with
# wraparound. Dicts stay insertion-ordered on both sides, so none of this
# shows for them; sets are the first hash-order-observable type, which is
# why the dict's simpler linear probe is not reused here.
A set’s 56-byte header holds used (live members), fill (slots ever taken, deleted ones included), mask (slots minus one) and a table of 16-byte (hash, key) entries. A probe reads up to 10 consecutive slots, which are cheap to read because they sit next to each other in memory, and then jumps:
runtime.slines 10460–10467set_lookup_outer: # one probe step: a linear run, then the perturbed jump
mov rax, [rsp] # rax = current bucket (the run start)
mov [rsp + 24], rax # park the run start: the jump counts from here
lea rcx, [rax + 9] # rcx = bucket + LINEAR_PROBES
cmp rcx, r13 # does the 10-entry run stay inside the table?
ja set_lookup_one # near the end: check this entry only, then jump
add rax, 10 # end = bucket + 10 (entries bucket..bucket+9)
mov [rsp + 8], rax # park the run end
runtime.slines 10501–10511set_lookup_jump: # run exhausted: perturbed jump, CPython's (i*5+1+perturb)
mov rax, [rsp + 16] # rax = perturb
shr rax, 5 # perturb >>= PERTURB_SHIFT (5), like CPython
mov [rsp + 16], rax # park the shifted perturb
mov rcx, [rsp + 24] # rcx = run START bucket (the inner walk moved the cursor)
imul rcx, rcx, 5 # rcx = bucket * 5 (wraps mod 2^64, like C size_t)
lea rcx, [rcx + 1] # rcx = bucket * 5 + 1
add rcx, rax # rcx = bucket * 5 + 1 + perturb
and rcx, r13 # wrap around the table with the mask
mov [rsp], rcx # park the next bucket
jmp set_lookup_outer # test the next run
The jump is i = (i * 5 + 1 + perturb) & mask, with perturb starting as the full hash and shifted right by 5 bits at every jump. On its own, i * 5 + 1 modulo a power of two visits every slot; adding perturb brings in the hash’s high bits, which hash & mask ignored, so keys that agree in their low bits soon part ways.
A removed member leaves set_dummy in its slot, with hash −1. Probes pass over a dummy, because something may have been placed beyond it; an insert reuses the last dummy it passed. A table grows when an insert into an empty slot makes fill × 5 ≥ mask × 3, to the smallest power of two above four times used (twice used above 50000 members), and the rebuild drops every dummy:
runtime.slines 10749–10768 inc qword ptr [rbx + 24] # fill grows by one
mov rax, [rbx + 24] # rax = fill for the resize test
imul rax, rax, 5 # rax = fill * 5 (wraps, like C size_t)
mov rcx, [rbx + 32] # rcx = mask (stable: no calls since the probe)
imul rcx, rcx, 3 # rcx = mask * 3 (wraps, like C size_t)
cmp rax, rcx # fill * 5 against mask * 3?
jb set_add_ret # room left: done, like CPython
mov rax, [rbx + 16] # rax = used for the growth size
cmp rax, 50000 # huge tables double instead of quadrupling, like CPython
ja set_add_double # past 50000: minused = used * 2
shl rax, 2 # minused = used * 4
jo abort_overflow # absurd sizes overflow instead of wrapping
jmp set_add_grow # resize with minused
set_add_double: # past 50000 elements: minused = used * 2
shl rax, 1 # minused = used * 2
jo abort_overflow # absurd sizes overflow instead of wrapping
set_add_grow: # rax = minused: regrow and rehash
mov rsi, rax # arg2 = minused for the resize
mov rdi, rbx # arg1 = borrowed set to regrow
call set_table_resize # double capacity, rehash in place
The corpus program tests/mvp/pass_set_basic.py adds, removes and iterates; aython must print what CPython prints:
tests/mvp/pass_set_basic.pylines 1–25# mvp: pass
s = {3, 1, 2}
print(s)
print(len(s))
print(2 in s)
print(9 in s)
print(s == {1, 2, 3})
print(s != {1})
s.add(5)
print(s)
s.remove(1)
print(s)
s.discard(9)
print(len(s))
e = {7}
e.remove(7)
print(e)
print(len(e))
for x in s:
print(x)
t = {1, 2} - {2, 3}
print(t)
print({1, 2} < {1, 2, 3})
print({1, 2} <= {1, 2})
print({3, 1} == {1, 3})
{1, 2, 3}
3
True
False
True
True
{1, 2, 3, 5}
{2, 3, 5}
3
set()
0
2
3
5
{1}
True
True
True
For bools, None, floats, ints of magnitude below 261 − 1, and tuples of them, the hashes equal CPython’s, so the orders match. Above that the int hashes differ. Reading the code, print({2**61 + 2, 3}) puts 2**61 + 2 in slot 2 and 3 in slot 3, so it prints {2305843009213693954, 3}; CPython hashes 2**61 + 2 to 3, moves the colliding 3 to slot 0, and prints {3, 2305843009213693954}. For strings they do not, as the dict section explained, and for NaNs see Hashing floats.
Exceptions without exception objects #
aython has no exception objects. An exception is a small integer, its kind, read from these stubs and messages at build time:
| Kind | Exception | Stub | stderr when nothing catches it |
|---|---|---|---|
| 1 | TypeError |
abort_type |
aython: TypeError |
| 2 | IndexError |
abort_index |
aython: IndexError |
| 3 | KeyError |
abort_key |
aython: KeyError |
| 4 | ValueError |
abort_value |
aython: ValueError |
| 5 | RuntimeError |
abort_runtime |
aython: RuntimeError |
| 6 | ZeroDivisionError |
abort_zero |
aython: ZeroDivisionError |
| 7 | OverflowError |
abort_overflow |
aython: OverflowError |
| 8 | MemoryError |
abort_memory |
aython: MemoryError |
| 9 | RecursionError |
abort_recursion |
aython: RecursionError |
| 10 | FileNotFoundError |
abort_file |
aython: FileNotFoundError |
| 11 | NotImplementedError |
abort_notimpl |
aython: NotImplementedError |
Every helper that fails jumps to its stub, which loads the kind into eax and jumps to exc_check. raise KeyError("m") in a program calls exc_raise with the kind in rdi, which does the same; the message "m" is never stored anywhere.
The handler stack #
Entering a try calls exc_push with the handler’s address. It records three things in parallel arrays: the frame base rbp of the function that contains the try, its stack pointer rsp as it was before the call, and the handler address. Up to 64 try blocks can be active at once.
runtime.s · exc_pushlines 354–393# ---- try/except machinery: handler stack plus kind-tagged unwind ----------------
# Exception kinds are small integers so generated dispatch is a compare:
# 1 TypeError, 2 IndexError, 3 KeyError, 4 ValueError, 5 RuntimeError,
# 6 ZeroDivisionError, 7 OverflowError, 8 MemoryError, 9 RecursionError,
# 10 FileNotFoundError, 11 NotImplementedError.
# `except Exception` (or bare `except:`) matches every kind, like CPython.
# Unwinding restores the try-entry rbp/rsp and jumps to its handler with
# the kind in exc_kind. Locals and temporaries abandoned mid-expression
# leak by design on the exceptional path (documented): the frame is
# discarded whole, so nothing double-frees, but nothing is released either.
.globl exc_depth # generated code never touches this directly (helpers do)
.globl exc_kind # generated handler dispatch reads the in-flight kind
.globl exc_push # make handler-push visible to generated code
.type exc_push, @function
.globl exc_pop # make handler-pop visible to generated code
.type exc_pop, @function
.globl exc_raise # make explicit raise visible to generated code
.type exc_raise, @function
.globl exc_check # abort_* entries jump here with the kind in eax
.type exc_check, @function
.globl exc_propagate # handler mismatch jumps here to keep unwinding
.type exc_propagate, @function
exc_push: # rdi = handler rip: record caller rbp/rsp plus handler
mov rax, [rip + exc_depth] # rax = active handler count
cmp rax, 64 # room for one more?
jae exc_push_full # 64 nested trys is a state violation, abort directly
mov rcx, rbp # rcx = caller frame base (call preserves rbp)
lea rdx, [rip + exc_stack_rbp] # rdx = rbp-slot base (rip+index is illegal)
mov [rdx + rax*8], rcx # save rbp at slot depth
lea rcx, [rsp + 8] # rcx = caller rsp (skip our return address)
lea rdx, [rip + exc_stack_rsp] # rdx = rsp-slot base
mov [rdx + rax*8], rcx # save rsp at slot depth
lea rdx, [rip + exc_stack_rip] # rdx = rip-slot base
mov [rdx + rax*8], rdi # save handler rip at slot depth
inc qword ptr [rip + exc_depth] # one more active handler
ret # return to the try entry
exc_push_full: # handler stack overflow: abort without unwinding (no recursion)
lea rdi, [rip + msg_runtime] # rdi points to RuntimeError message
mov rsi, msg_runtime_end - msg_runtime # rsi gets RuntimeError message length
jmp abort_msg # exit directly; routing via exc_check would recurse
exc_check is the other half. With no handler active it prints the kind’s message and exits with status 1. Otherwise it pops the top record, puts back rbp and rsp, and jumps:
- A function
fcalled inside atryinmain_maincomputed1 // 0.int_floordivfound the zero divisor and jumped toabort_zero, which seteax = 6and jumped here.rspandrbpstill belong toint_floordiv’s frame, three calls deep. - One handler is active, so this is not the uncaught path. With
exc_depth0 the jump would go toexc_abort_uncaught, which writesaython: ZeroDivisionErrorand exits. - The kind is stored where the handler’s dispatch code will read it.
- Printing, equality and
repr()keep depth counters for their recursion guards. The frames that were counting are about to disappear, so the counters go back to zero; otherwise a later print could abort for nesting that no longer exists. - The top record is popped before it is used, so if the handler itself fails, the next
exc_checksees the next handler out and cannot loop. rbpbecomes the frame baseexc_pushsaved:main_main’s. Its local slots are addressed fromrbp, so the handler can read them again.rspgoes back to its value at thetry. The frames offandint_floordiv, and everything they pushed, are below the stack pointer now: discarded in one instruction, with nothing run on the way out.- An indirect jump to the handler’s label in
main_main. The generated code there comparesexc_kindwith eachexceptclause’s kind and either runs that clause or jumps toexc_propagate, which re-entersexc_checkfor the next handler out.
On the generated side, a try is an exc_push before the body, an exc_pop after it when it finished normally, and a handler label that dispatches on the kind. From tests/mvp/pass_try_basic.py, whose first try catches ZeroDivisionError:
tests/mvp/pass_try_basic.py · emitted · main_mainmov rax, [rip + exc_kind] # in-flight kind for handler 0
cmp rax, 6 # is it ZeroDivisionError?
je .Ltry_h1_0 # match: run handler 0
sequenceDiagram participant M as main_main participant F as f() participant H as int_floordiv participant R as exc_check M->>R: exc_push(handler): save rbp, rsp, handler M->>F: call f F->>H: call int_floordiv(1, 0) H->>R: jmp abort_zero (eax = 6), jmp exc_check R->>M: restore rbp and rsp, jmp handler M->>M: exc_kind == 6? run the except body Note over M: the frames of f and int_floordiv are gone, and nothing in them was released
This design is cheap: a try costs one call on entry and one on exit, and a raise costs a few loads. What it gives up is cleanup. The frames between the failure and the handler are dropped without running anything, so references held by temporaries in them are never released. The runtime’s comment calls this a leak by design: the frame is discarded whole, so nothing is freed twice, and nothing is freed at all. CPython would decref every frame’s locals on the way out.
exit(n) does not go through this at all. aython_exit masks the status to its low byte (255) and calls _exit, so no handler runs. That matches except Exception, which never catches SystemExit in CPython, and differs from a bare except:, which would.
Files and argv #
The program’s own I/O builtins are thin layers over libc:
read_file(path)(file_read_all) opens the path read-only, reads it in chunks of 8192 bytes into a buffer that doubles as needed, and abortsValueErroron any byte that is not ASCII.write_file(path, s)andappend_file(path, s)open withO_TRUNCorO_APPENDand mode0666, like CPython’sopen(path, "w")andopen(path, "a"), write throughwrite_all, and return the byte count.- A path is copied to a zero-terminated scratch buffer first, because aython strings have no terminator and libc’s
openneeds one. Any failure to open abortsFileNotFoundError, whatever the cause, because there is noOSErrorkind. argv()(argv_list) builds a list of strs from theargcandargvthat the C runtime passes tomaininrdiandrsi.main_maintakes no arguments, soarena_initsaves both in globals forargv_listto read later:
runtime.s · arena_initlines 13777–13805# ---- entry: arena_init + main ---------------------------------------------------------------
# crt calls main(argc, argv); both it and the leak probe's custom entry
# share arena_init, which stashes the args and mmaps the 64 MiB arena.
# main then calls the generated main_main and returns 0 to libc.
# main_main takes no arguments and returns nothing; generated code reads
# argv through the stashed globals instead of an argument.
.p2align 4 # align entry code
.globl arena_init # shared entry helper, export it
.type arena_init, @function # mark it as code for the linker
arena_init: # entry: rdi = argc, rsi = argv (0, NULL when none)
push rbp # save the frame base (also aligns for mmap below)
mov rbp, rsp # frame base, restored before returning
mov [rip + saved_argc], rdi # stash argc for argv()
mov [rip + saved_argv], rsi # stash argv base for argv()
xor edi, edi # mmap hint address 0 lets libc choose
mov rsi, 67108864 # ask for 64 MiB arena
mov edx, 3 # prot read plus write
mov ecx, 0x22 # private anonymous memory, no file behind it (4th libc arg)
mov r8, -1 # no file descriptor for anonymous mmap
xor r9d, r9d # offset 0
call mmap # reserve the arena via libc; -1 (MAP_FAILED) on error
cmp rax, -1 # libc signals failure with exactly -1, unlike raw -errno
je abort_memory # abort if mmap failed (noreturn: realigns itself)
mov [rip + arena_base], rax # remember arena start
mov [rip + arena_ptr], rax # bump pointer starts empty at base
add rax, 67108864 # compute arena end as base plus size
mov [rip + arena_end], rax # remember arena limit
pop rbp # restore the caller's frame base
ret # back to main (or the probe entry) with the arena ready
The same call maps the 64 MiB arena every allocation comes from. main then calls main_main, the generated program, and returns 0.
Where it differs from CPython #
Everything above matches CPython except the following. Where it differs from CPython has the full list across the project.
| Behaviour | aython | CPython | Seen in the corpus |
|---|---|---|---|
| Int overflow | Aborts OverflowError past 64 bits |
Grows the integer | abort:OverflowError programs |
| Error output | One line, aython: <Kind>, exit status 1; the message argument is dropped |
A traceback and the message | The judge compares only the kind |
print of a self-containing container |
Aborts RecursionError |
Prints [...] |
abort_recursion_print.py |
| Order of a set of strings | Fixed, from FNV-1a | Changes from run to run | Kept out of the corpus |
| Hash of an int of magnitude 261 − 1 or more | The value itself, from reading obj_hash |
The value modulo 261 − 1 | Not exercised: set order and float-key lookups differ |
| Order of a set with NaN members | NaNs sit in the bucket for hash 0 | NaNs sit by address | Not exercised |
exit() inside a bare except: |
Exits | Caught | Documented in docs/core-design.md |
An open that fails for a reason other than a missing file |
FileNotFoundError |
The specific OSError subclass |
Not exercised (err_io_missing.py covers the missing file, where both agree) |
| Missing key in a dict of exactly 8, 16, 32… keys | Never returns, from reading dict_lookup |
False or KeyError |
Not exercised |
INT64_MIN % -1 |
Killed by SIGFPE, from reading int_mod |
0 |
Not exercised |
Where this lives #
| Concept | File | Symbol |
|---|---|---|
| Type tags, singletons, small-int cache | runtime.s | type_int, aython_none, small_ints, empty_tuple |
| Int arithmetic and operator dispatch | runtime.s | int_add, int_sub, int_mul, int_new |
| Floor division and modulo | runtime.s | int_floordiv, int_mod |
| Float boxes and arithmetic | runtime.s | float_new, num_arith_setup, float_add, int_true_div_exact |
| Shortest float printing | runtime.s | print_float, ryu_d2d, format_float, DOUBLE_POW5_SPLIT |
| Strings | runtime.s | str_new, str_from_buf, str_concat, str_repeat, str_compare |
Printing and repr() |
runtime.s | aython_print_obj, print_repr, print_int_value, print_quoted, repr_of |
| Lists and tuples | runtime.s | list_new, list_append, list_concat, tuple_new, tuple_append |
| Hashing | runtime.s | obj_hash, obj_hash_str, obj_hash_tuple, obj_hash_float |
| Dicts | runtime.s | dict_new, dict_lookup, obj_setitem, dict_grow, dict_insert_fresh, dict_remove_at, dict_key_at |
| Sets | runtime.s | set_new, set_lookup, set_add_entry, set_table_resize, set_dummy |
| Exceptions | runtime.s | abort_*, exc_push, exc_pop, exc_raise, exc_check, exc_propagate |
| Files, argv, exit, entry | runtime.s | file_read_all, file_write_all, file_append_all, argv_list, aython_exit, arena_init, main |
| The decisions (i64 ints, abort format) | docs/core-design.md | Decisions made in review |
| This chapter’s numbers and cut points | docsite/figures/runtime_tour.py | collect |
| The two figures | docsite/static/widgets/dict.js, floatbits.js | setItem, lookup, delItem; reprBits |
Check yourself #
Check yourself
For
-7 // 2,idivleaves quotient-3and remainder-1inraxandrdx. What doesint_floordivbox?-3: the remainder’s sign does not matter-4: the remainder is nonzero and its sign differs from the divisor’s-3, thenint_modcorrects it
Answer
-4: the remainder is nonzero and its sign differs from the divisor’s.xor r8, rcxof remainder-1and divisor2is negative, sojnsdoes not jump anddec raxturns-3into-4, the floor of -3.5.A fresh dict has had the keys 0 to 7 inserted. Which of these never returns in
runtime.s?d[8] = 08 in dd[3]len(d)
Answer
8 in d. All eight index slots are taken.d[8] = 0grows the table first becauselen == cap;d[3]finds its key.8 in dprobes every slot, never meets an empty one, anddict_lookuphas no other exit.Which of these does aython print in scientific notation?
1000000000000000.00.00011e16123.456
Answer
1e16.1e16has the single digit 1 anddecpt17, above the limit of 16, soformat_floatwrites1e+16.1e15hasdecpt16 and0.0001hasdecpt-3, both inside the fixed range.Why do sets copy CPython’s perturbed probe while dicts use plain linear probing?
- Linear probing is faster for sets
- A set prints in table order, so its slots must be CPython’s; a dict prints in insertion order whatever its probe does
- Dicts cannot have collisions
Answer
A set prints in table order, so its slots must be CPython’s; a dict prints in insertion order whatever its probe does. Dict iteration walks the denseentriesarray, which is in insertion order on both sides. Set iteration walks the table, so every element must land in the slot CPython would put it in.A
tryinmain_maincallsf(), andffails while it owns a temporary list. What happens to that list whenexc_checkunwinds?exc_checkdecrefs it- The handler frees it
- Nothing:
rspjumps pastf’s frame, and the list is never released
Answer
Nothing:rspjumps pastf’s frame, and the list is never released. Unwinding restoresrbpandrspand jumps. No code runs for the abandoned frames, so their references leak, by design; nothing can be freed twice either.