Chapter 3 of 1129 min read
From source to a checked program
CPython'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.
Before any assembly is written, something has to decide whether a program is inside the subset at all. A compiler that guesses at a construct it does not understand produces an executable that prints the wrong thing, and with no person reading the assembly that mistake would go unnoticed. The frontend makes the opposite trade: it reads the program with CPython's own parser, walks every statement and expression, and refuses anything it cannot compile with a message that names the construct. This chapter follows a program through that walk, and through the two rewrites the frontend makes on the way: flattening imports into one module, and flattening classes into functions and dictionaries.
The frontend is one file, src/aython/frontend.py. It is ordinary Python that runs on the host machine; nothing in it ends up in the executable. Its output is a checked syntax tree that the code generator turns into assembly.
The pipeline #
aython run prog.py and the judge both build a program the same way, in judge.build_program: frontend, code generator, then the system assembler and C compiler.
flowchart LR src["prog.py"] --> parse["parse_source<br/>(CPython ast)"] parse --> imports["_expand_imports<br/>(one merged module)"] imports --> check["check_program<br/>(subset walk)"] check --> gen["codegen.generate"] gen --> asm["prog.s.gen"] asm --> as1["as"] rt["runtime.s"] --> as2["as"] as1 --> link["cc ... -lm"] as2 --> link link --> elf["prog.elf"] elf --> judge["judge: same stdout<br/>as python3 prog.py"] check -. "aython: unsupported: ..." .-> stop["refused:<br/>nothing assembled"] class parse,imports,check,gen accent class judge py class stop bad
The first three boxes are compile_source, the frontend’s one entry point:
src/aython/frontend.py · compile_sourcelines 172–195def compile_source(source: str, filename: str) -> tuple[ast.Module, list[str], dict[str, list[str]]]:
"""Parse and validate source, collecting frame variables and functions.
Sibling-module imports are flattened before validation (see
:func:`_expand_imports`), so the returned tree is a single merged
module: imported statements are inlined at their import point with
prefixed names, and no ``Import``/``ImportFrom`` node survives.
Args:
source: Full text of the candidate program.
filename: Name used in syntax-error messages only.
Returns:
The validated tree, top-level variable names in first-appearance
order, and a mapping of function name to full slot list (params
first, then assigned locals in first-appearance order).
Raises:
FrontendError: On syntax errors or subset violations.
"""
tree = parse_source(source, filename)
merged = _expand_imports(tree, filename)
variables, funcs = check_program(merged)
return merged, variables, funcs
and the rest is the judge’s build step. The generated prog.s.gen and the hand-written runtime.s are assembled separately and linked by cc against libc and the maths library (-lm, for pow):
src/aython/judge.py · build_programlines 141–175def build_program(source: Path, runtime_src: Path) -> Path:
"""Compile a source file all the way to an ELF executable.
Args:
source: Program ``.py`` file; artifacts land beside it.
runtime_src: Path to ``runtime.s`` providing ``main``/``arena_init``.
Returns:
Path to the linked ``.elf`` executable.
Raises:
frontend.FrontendError: If the program is outside the subset.
subprocess.CalledProcessError: If assembly or linking fails.
"""
# Resolve so artifact paths are absolute: the kernel execs the ELF
# directly, and a bare relative name (no directory component) would
# make execvp search PATH instead of the current directory.
source = source.resolve()
runtime_src = runtime_src.resolve()
text = source.read_text(encoding="utf-8")
tree, variables, funcs = frontend.compile_source(text, str(source))
asm_text = codegen.generate(tree, variables, funcs)
asm_path = source.with_suffix(ASM_SUFFIX)
obj_path = source.with_suffix(OBJ_SUFFIX)
elf_path = source.with_suffix(ELF_SUFFIX)
runtime_obj = elf_path.parent / RUNTIME_OBJ_NAME
asm_path.write_text(asm_text, encoding="utf-8")
log.debug("wrote %s (%d vars)", asm_path, len(variables))
subprocess.run([ASSEMBLER_CMD, "-o", str(obj_path), str(asm_path)], check=True)
subprocess.run([ASSEMBLER_CMD, "-o", str(runtime_obj), str(runtime_src)], check=True)
subprocess.run(
[LINKER_CMD, "-o", str(elf_path), str(obj_path), str(runtime_obj), LINK_MATH_LIB],
check=True,
)
return elf_path
compile_source raises before codegen.generate is called, so a refused program never produces a .s.gen file, let alone an executable. That is the property the rest of the chapter depends on.
CPython’s parser, not our own #
parse_source hands the text to ast.parse, the parser CPython itself uses. Writing a Python parser was not the problem this part of the project set out to solve: the decision table in docs/core-design.md puts the frontend on the host, built on ast. A parser written in assembly exists as a separate track with its own chapter, Python without Python.
Using CPython’s parser has a consequence worth noticing: any program that reaches the subset check is already valid Python, because CPython accepted its syntax. The frontend never has to decide what a program means in a way CPython would not. It only decides whether it can compile what CPython parsed.
src/aython/frontend.py · parse_sourcelines 148–169def parse_source(source: str, filename: str) -> ast.Module:
"""Parse source text into an AST module.
Args:
source: Full text of the candidate program.
filename: Name used in syntax-error messages only.
Returns:
The parsed ``ast.Module``.
Raises:
FrontendError: If the text does not parse as Python, except
that ``else`` on a handler-less ``try`` is reshaped into
an ``unsupported`` refusal naming the clause.
"""
try:
return ast.parse(source, filename=filename)
except SyntaxError as exc:
offender = exc.text or ""
if TRY_FINALLY_ELSE_MSG in (exc.msg or "") and offender.strip().startswith("else"):
raise _unsupported("try-else clause (else needs except)") from exc
raise FrontendError(f"aython: syntax error: {exc}") from exc
The one reshaping is for try: ... else: ... with no except. CPython reports that as a syntax error; the frontend turns that one message into a subset refusal so the corpus can pin it with a reject: marker like every other refusal. A real syntax error comes out as aython: syntax error: ..., which the judge does not accept as a refusal.
What the frontend returns #
A checked program is three things: the merged tree, the top-level variable names in order of first assignment, and a function table mapping each function to its slot list (parameters first, then the locals it assigns). The code generator gives each name one 8-byte stack slot, in that order. For four corpus programs, this is what compile_source returns (computed at build time):
| Program | Top-level variables | Function table |
|---|---|---|
pass_arith.py |
x, y, z, w |
(none) |
pass_fn_fib.py |
(none) | fib: n |
pass_class_basic.py |
c, d |
Counter____init__: self, start; Counter__bump: self, step; Counter__read: self |
pass_import_from.py |
inc_import_from_helper__x, x |
inc_import_from_helper__double: n |
Three things in that table come from rewrites described below: Counter____init__ and Counter__bump are class methods flattened into ordinary functions; inc_import_from_helper__x is a variable of an imported module, renamed into the one merged namespace; and pass_fn_fib.py has no top-level variables at all, because print(fib(10)) assigns nothing.
Two passes over the tree #
check_program walks the module twice.
src/aython/frontend.py · check_programlines 198–234def check_program(tree: ast.Module) -> tuple[list[str], dict[str, list[str]]]:
"""Validate every statement and collect assigned names and functions.
Definitions are registered in a first pass so that mutual recursion
and forward references resolve; bodies are validated in a second
pass with each function's own scope.
Args:
tree: Parsed module, already known to be an ``ast.Module``.
Returns:
Top-level variable names in first-appearance order, plus the
function table described under ``compile_source``.
Raises:
FrontendError: If any statement or expression is unsupported.
"""
global _in_handler_depth
_in_handler_depth = 0
global _classes, _method_owner, _class_base, _class_methods, _class_values, _class_mro
global _class_own_init
global _class_exc_derived
_classes = {}
_method_owner = {}
_class_base = {}
_class_methods = {}
_class_values = {}
_class_mro = {}
_class_own_init = {}
_class_exc_derived = {}
variables: list[str] = []
funcs: dict[str, list[str]] = {}
for node in tree.body:
_register_top_defs(node, funcs)
for node in tree.body:
check_statement(node, variables, funcs, None)
return variables, funcs
The first pass, _register_top_defs, registers every def and class in the module (including ones nested inside a top-level if or try) without looking at their bodies. The second pass validates every statement in order. The split exists for forward references: in pass_fn_mutual.py, is_even calls is_odd before is_odd is defined. A single top-to-bottom pass would refuse that call as unknown; CPython accepts it because the name is only looked up when the call runs.
The tables the walk consults (classes, method owners, the C3 orders) are module globals reset at the start of every check_program, so one compilation cannot leak into the next.
Statements #
check_statement is a dispatch on the node type. Anything it does not name falls to the last line and is refused with the node’s class name:
src/aython/frontend.py · check_statementlines 283–332def check_statement(node: ast.stmt, variables: list[str], funcs: dict[str, list[str]], scope: list[str] | None) -> None:
"""Validate one statement, recording any newly defined name.
Args:
node: The statement node to validate.
variables: Ordered accumulator of variable names; at top level
the module slots, inside a function that function's slots.
Extended in place with names first defined by this statement.
funcs: Function table for call resolution and arity checks.
scope: None at module top level (reads are unchecked legacy
behavior); the function's slot list inside a body, where
every read must resolve to a slot.
Raises:
FrontendError: If the statement form is outside the subset.
"""
if isinstance(node, ast.Assign):
_check_assign(node, variables, funcs, scope)
elif isinstance(node, ast.AnnAssign):
_check_annassign(node, variables, funcs, scope)
elif isinstance(node, ast.AugAssign):
_check_augassign(node, variables, funcs, scope)
elif isinstance(node, ast.Expr):
_check_expr_statement(node, variables, funcs, scope)
elif isinstance(node, ast.If):
_check_if(node, variables, funcs, scope)
elif isinstance(node, ast.While):
_check_while(node, variables, funcs, scope)
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
if scope is not None:
raise _unsupported("nested def (define functions at top level only)")
_check_def(node, funcs, variables, scope)
elif isinstance(node, ast.Return):
_check_return(node, variables, funcs, scope)
elif isinstance(node, (ast.For, ast.AsyncFor)):
_check_for(node, variables, funcs, scope)
elif isinstance(node, ast.Delete):
_check_delete(node, variables, funcs, scope)
elif isinstance(node, ast.Try):
_check_try(node, variables, funcs, scope)
elif isinstance(node, ast.Raise):
_check_raise(node, variables, funcs, scope)
elif isinstance(node, (ast.Import, ast.ImportFrom)):
raise _unsupported("import statement")
elif isinstance(node, ast.Assert):
raise _unsupported("assert statement")
elif isinstance(node, ast.ClassDef):
_check_class(node, variables, funcs, scope)
else:
raise _unsupported(f"statement {type(node).__name__}")
That last else is why pass in a function body, break, continue, with, global and match are all refused: each arrives as an AST node type the dispatch does not list, and the message says statement Pass, statement Break, and so on. assert and a nested def have their own messages. pass is admitted in exactly one place, a class body, where _check_class skips it.
Expressions and the order of checking #
check_expr is the same kind of dispatch for expressions. Most of the subset’s rules are one line in it: if expressions, :=, *x and generator expressions are refused by name, and everything else recurses into its operands.
The order in which a statement is checked carries meaning. _check_assign checks the right-hand side before it records the target name:
src/aython/frontend.py · _check_assignlines 357–401def _check_assign(node: ast.Assign, variables: list[str], funcs: dict[str, list[str]], scope: list[str] | None) -> None:
"""Validate a plain assignment statement.
A multi-target chain (``a = b = value``) binds one shared value
left to right: every target must be a plain ``Name`` in ``Store``
context (names may repeat: ``x = x = v`` binds twice, like
CPython, since each store takes its own shared reference). The
value is validated before any target binds, so ``x = y = x`` with
a fresh ``x`` refuses exactly like the single-target ``x = x + 1``.
Args:
node: The ``Assign`` node; one target of any admitted shape,
or two-plus plain-``Name`` targets.
variables: Ordered accumulator of variable names.
funcs: Function table for validating the value expression.
scope: Enclosing function slots, or None at module top level.
Raises:
FrontendError: On mixed shapes (subscript, attribute, tuple,
or starred targets anywhere in a chain) or on unsupported
target kinds.
"""
if len(node.targets) != 1:
_check_multi_assign(node, variables, funcs, scope)
return
target = node.targets[0]
if isinstance(target, ast.Name) and isinstance(target.ctx, ast.Store):
# Check the value FIRST so `x = x + 1` cannot read the slot the
# target is about to create; CPython raises NameError there.
check_expr(node.value, variables, funcs, scope)
_remember(variables, target.id)
return
elif isinstance(target, ast.Subscript) and isinstance(target.ctx, ast.Store):
_check_subscript_store_target(target, variables, funcs, scope)
elif isinstance(target, ast.Attribute) and isinstance(target.ctx, ast.Store):
_check_attr_store_target(target, variables, funcs, scope)
elif isinstance(target, ast.Tuple) and isinstance(target.ctx, ast.Store):
names = _check_unpack_target(target)
check_expr(node.value, variables, funcs, scope)
for name in names:
_remember(variables, name)
return
else:
raise _unsupported(f"assignment target {type(target).__name__}")
check_expr(node.value, variables, funcs, scope)
So x = x + 1 with no earlier x is refused as use of unassigned name 'x', which is CPython’s NameError moved to compile time. At module level a read must name a variable some earlier statement assigned; inside a function it must name one of the function’s own slots. There are no globals and no closures: in rej_global.py a function reads a module-level x, and the frontend refuses it with name 'x' is not assigned in this function (no globals or closures in MVP).
Calls, builtins and arity #
A call is the most varied expression, and _check_call sorts it by what is being called. A user function accepts positional arguments, keywords, *xs and **d; its arity is checked at run time by the callee, the way CPython does it (Emitting assembly shows the cmp r10d that does it). A builtin or a method accepts positional arguments only, and the frontend checks its count at compile time against a table. These are the builtins with a range of admitted counts (print, len, repr, range, the file builtins, argv, exit and isinstance are checked one by one in _check_call):
| Builtin | Arguments admitted |
|---|---|
set |
0 to 1 |
sorted |
exactly 1 |
min |
exactly 1 |
max |
exactly 1 |
sum |
1 to 2 |
abs |
exactly 1 |
enumerate |
1 to 2 |
zip |
exactly 2 |
reversed |
exactly 1 |
chr |
exactly 1 |
ord |
exactly 1 |
min([3, 1]) compiles; min(3, 1) is refused as min arity (exactly 1 argument), because the runtime’s min_of takes one iterable. That is a subset choice, not a CPython rule, and the corpus pins it (rej_min_multi.py).
Methods work the same way, through METHOD_ARITIES: 37 method names on str, list, dict and set. The receiver’s type is not known at compile time, so the table is keyed by name only. "s".append(1) passes the frontend and aborts TypeError at run time, where CPython raises AttributeError; that divergence is pinned by an abort: program and listed in Where it differs.
isinstance takes a type name as its second argument, and type names are compile-time keywords here, not values. Each admitted name sets one bit of a mask that codegen passes to the runtime helper:
| Type name | Mask bit |
|---|---|
int |
1 |
bool |
2 |
float |
4 |
str |
8 |
list |
16 |
tuple |
32 |
set |
64 |
dict is deliberately missing: class instances are dicts (below), so no run-time test could tell an instance from a dictionary, and isinstance(x, dict) is refused rather than answered wrongly.
How a refusal works #
Every refusal is built by one function and raised as one exception type:
src/aython/frontend.py · _unsupportedlines 136–145def _unsupported(feature: str) -> FrontendError:
"""Build a refusal error naming the offending feature.
Args:
feature: Human-readable feature name, e.g. ``"if statement"``.
Returns:
A ``FrontendError`` prefixed with ``UNSUPPORTED_PREFIX``.
"""
return FrontendError(f"{UNSUPPORTED_PREFIX} {feature}")
The prefix is the contract with the judge. A corpus program marked # mvp: reject:<text> passes when compile_source raises a FrontendError whose message contains aython: unsupported: and <text>; the judge never builds or runs it (judge._check_reject). So every refusal message is part of the tested surface: changing one breaks the corpus program that pins it.
The corpus holds 71 such programs. The figure below runs each one through the real frontend at build time, stage by stage, and shows what comes back.
reject program in tests/mvp/, with the exact message the frontend refuses it with, the substring the judge requires (marked), which stage of compile_source refused it, and the line of frontend.py that raised it. Filter by category; Left and Right step through the list.By stage, the refusals split like this:
| Stage | Refusals | What it catches |
|---|---|---|
| parsing (parse_source) | 1 | The one syntax error reshaped into a refusal (try/else with no except) |
| import flattening (_expand_imports) | 11 | Missing and circular modules, import *, unknown from-names, a module used as a value |
| checking (check_program) | 59 | Every construct outside the subset, and every name read before it is assigned |
Several import programs are refused at the check stage, not the import stage: the import itself is fine, but the flattened result reads a name a function cannot see (rej_import_infn_bare.py) or defines a function inside a function (rej_import_nested.py). The flattening never decides what is allowed; it rewrites, and the ordinary check decides.
Imports: one merged module #
There are no module objects at run time. _expand_imports replaces every import statement with the imported module’s own statements, renamed so they cannot collide, and hands the checker one merged module. The rules, from _ImportJob and _ImportScope:
- The prefix. A name defined at the top level of module
mbecomesm+__+ name. A dotted modulea.b(the filea/b.py) usesa__b__. The entry program’s own names keep no prefix. - Once, at the import point. A module’s statements are inlined where the first
importof it stands and nowhere else, the way CPython’ssys.modulescache makes a second import a no-op. Its top-levelprintcalls therefore run at that point in the program, as they would under CPython. from m import xcopies. For a variable it becomes an ordinary assignmentx = m__x, so rebindingxafterwards leavesm.xalone, exactly as in CPython. For a function it is a call-site rename instead, because functions are not values in the subset.m.xresolves statically tom__x. Usingmitself as a value is refused (bare module name ... modules are not values).__name__is a constant:"__main__"in the entry program and the dotted module name elsewhere, so theif __name__ == "__main__":guard works.- Where modules come from.
mmeansm.pybeside the entry program (CPython’s script-directory rule); relative imports resolve against the importing file’s directory, up to 2 leading dots. There is no standard library:import osis refused as a missing module. - Refused shapes: circular imports (the message spells the cycle),
from m import *, a name the module does not define, two modules that flatten to the same prefix (a__b.pybesidea/b.py).
Here is the effect on a real program. The entry program and the module it imports:
tests/mvp/pass_import_from.pylines 1–13# mvp: pass
import inc_import_from_helper
from inc_import_from_helper import x
from inc_import_from_helper import double as d
from inc_import_from_helper import double
print(x)
x = 2
print(x)
print(inc_import_from_helper.x)
print(d(21))
print(double(21))
print(inc_import_from_helper.double(4))
tests/mvp/inc_import_from_helper.pylines 1–6# mvp: skip
x = 10
def double(n):
return n + n
and the merged module the checker actually sees, printed back as Python with ast.unparse at build time:
inc_import_from_helper__x = 10
def inc_import_from_helper__double(n):
return n + n
x = inc_import_from_helper__x
print(x)
x = 2
print(x)
print(inc_import_from_helper__x)
print(inc_import_from_helper__double(21))
print(inc_import_from_helper__double(21))
print(inc_import_from_helper__double(4))
The helper’s x = 10 and def double came first, where import inc_import_from_helper stood. The from ... import x became the copy x = inc_import_from_helper__x; the two later from lines produced nothing, because the module was already inlined and function names only rename call sites. The # mvp: skip marker keeps the judge from running the helper as a program of its own. CPython prints this for the entry program, and the judge requires the executable to print the same bytes:
10
2
10
42
42
8
Classes: functions and dictionaries #
A class in the subset has no run-time object. _register_class runs during the first pass and does three things to each class statement: it renames every method in place to <Class>__<method> and registers it as an ordinary function whose first parameter happens to be called self; it records the class’s constant values; and it computes the class’s method resolution order. An instance is a plain dictionary: Counter() compiles to a fresh dict, the class’s constants copied into it, and a call to Counter____init__ with that dict as the first argument. (The four underscores are Counter + __ + __init__.)
flowchart LR
subgraph before["class Counter (source)"]
i["def #95;#95;init#95;#95;(self, start=0)"]
b["def bump(self, step=1)"]
end
subgraph after["after the frontend and codegen"]
fi["fn_Counter____init__(self, start)"]
fb["fn_Counter__bump(self, step)"]
mk["Counter(10):<br/>d = dict_new()<br/>fn_Counter____init__(d, 10)"]
cb["c.bump(5):<br/>fn_Counter__bump(c, 5)"]
end
i --> fi
b --> fb
fi -.-> mk
fb -.-> cb
class fi,fb,mk,cb accent
The class program from the reader, after compile_source has renamed its methods:
class Counter:
"""a mutable counter."""
def Counter____init__(self, start=0):
self.n = start
def Counter__bump(self, step: int=1) -> int:
self.n = self.n + step
return self.n
def Counter__read(self):
return self.n
c = Counter()
print(c.read())
print(c.bump(5))
print(c.bump())
print(c.bump(step=2))
d = Counter(10)
print(d.read())
print(c.read())
print(c is d)
print(c is c)
The call sites c.read() and c.bump(5) are untouched in the tree. They resolve at code-generation time, by method name alone: bump is defined by exactly one class in the program, so c.bump(5) can only mean Counter__bump(c, 5). That is why the frontend insists that method names are unique across the whole program (method fetch defined in multiple classes) and refuses overrides (method fetch overrides A.fetch). With either, the right method would depend on the receiver’s class at run time, and an instance is an untyped dict that does not know its class. Refusing both keeps every method call a direct call, with no dispatch code at all.
The method resolution order #
Values and __init__ can come from several places, so their order matters. A class may have any number of bases, and the frontend computes the same C3 linearisation CPython uses:
src/aython/frontend.py · _c3_mergelines 1889–1924def _c3_merge(seqs: list[list[str]]) -> list[str]:
"""Merge linearization sequences into one C3 order.
Repeatedly takes the first head that appears in no other
sequence's tail (leftmost wins), dropping it from every head it
leads. When no head qualifies, the hierarchy is inconsistent (two
orderings disagree with no linearization satisfying both), which
CPython also rejects at class creation.
Args:
seqs: Linearizations to merge (each base's stored MRO plus
the direct base list, leftmost first); empty sequences
are ignored.
Returns:
The merged tail order, without the class itself.
Raises:
FrontendError: On an inconsistent hierarchy.
"""
pending = [list(seq) for seq in seqs if seq]
merged: list[str] = []
while True:
pending = [seq for seq in pending if seq]
if not pending:
return merged
for seq in pending:
head = seq[0]
if not any(head in other[1:] for other in pending):
merged.append(head)
for other in pending:
if other and other[0] == head:
del other[0]
break
else:
raise _unsupported("class bases (inconsistent method resolution order)")
A class’s values are copied into each new instance along the reversed order (base first, so a subclass’s value wins), and construction calls the nearest __init__ in the order. For the classes of pass_multi_bases.py, the frontend’s tables after compiling it read:
| Class | Direct bases | C3 order | Construction calls |
|---|---|---|---|
Left |
(none) | Left | Left____init__ |
Right |
(none) | Right | no __init__: the dict is the instance |
Both |
Left, Right |
Both → Left → Right | Left____init__ |
Chain |
Both |
Chain → Both → Left → Right | Left____init__ |
Erased |
Left |
Erased → Left | Left____init__ |
DiaA |
(none) | DiaA | DiaA____init__ |
DiaB |
DiaA |
DiaB → DiaA | DiaA____init__ |
DiaC |
DiaA |
DiaC → DiaA | DiaC____init__ |
DiaD |
DiaB, DiaC |
DiaD → DiaB → DiaC → DiaA | DiaC____init__ |
Entry |
inc_multi_bases_helper__Base1, inc_multi_bases_helper__Base2 |
Entry → inc_multi_bases_helper__Base1 → inc_multi_bases_helper__Base2 | inc_multi_bases_helper__Base1____init__ |
Mixed |
inc_multi_bases_helper__Sub |
Mixed → inc_multi_bases_helper__Sub → inc_multi_bases_helper__Base1 → inc_multi_bases_helper__Base2 | inc_multi_bases_helper__Base1____init__ |
DiaD is the diamond: DiaB and DiaC both derive from DiaA, and only DiaA and DiaC define __init__. A depth-first search would reach DiaA through DiaB first and call DiaA’s constructor; C3 puts DiaC before DiaA, so DiaD() runs DiaC.__init__, as CPython does. The program prints d.v to pin it.
What a class body may hold #
| In a class body | What happens |
|---|---|
def methods |
Renamed to <Class>__<name> and registered as functions |
NAME = constant (int, float, str, bool, None, or tuples of them) |
Copied into every new instance before __init__ runs |
A docstring, pass, a bare annotation x: int |
Skipped |
__slots__ = ("a", "b") |
Skipped: instances are dicts either way |
A base object, Exception, any supported exception kind, BaseException, EOFError |
Erased: contributes nothing to the order |
| Anything else (a mutable value, a nested class, a decorator, a keyword base) | Refused, naming it |
Exception bases are erased because nothing can observe them: raise admits only the built-in kinds, an except clause matches by kind number, never by class, and an instance of class E(ValueError) can never be raised as itself (constructing one in raise position is refused). The class stays a dict like any other.
Exceptions as kind numbers #
The runtime carries an exception as a small integer, never an object. The frontend’s table of kinds is the shared numbering, mirrored by codegen.EXC_KIND_IDS and the exc_check dispatch in runtime.s:
| Kind | Id | In except |
In raise |
|---|---|---|---|
Exception |
0 | catches every kind | refused: raise kind 'Exception' |
TypeError |
1 | catches this kind | raise TypeError or raise TypeError(...) |
IndexError |
2 | catches this kind | raise IndexError or raise IndexError(...) |
KeyError |
3 | catches this kind | raise KeyError or raise KeyError(...) |
ValueError |
4 | catches this kind | raise ValueError or raise ValueError(...) |
RuntimeError |
5 | catches this kind, and RecursionError and NotImplementedError (its CPython subclasses) |
raise RuntimeError or raise RuntimeError(...) |
ZeroDivisionError |
6 | catches this kind | raise ZeroDivisionError or raise ZeroDivisionError(...) |
OverflowError |
7 | catches this kind | raise OverflowError or raise OverflowError(...) |
MemoryError |
8 | catches this kind | raise MemoryError or raise MemoryError(...) |
RecursionError |
9 | catches this kind | raise RecursionError or raise RecursionError(...) |
FileNotFoundError |
10 | catches this kind | raise FileNotFoundError or raise FileNotFoundError(...) |
NotImplementedError |
11 | catches this kind | raise NotImplementedError or raise NotImplementedError(...) |
Because there is no object, everything that needs one is refused: except E as e (except-as binding), raise ... from ..., and raise Exception. Arguments to raise ValueError("bad") are checked as expressions and then ignored, since the judge compares only the kind word on stderr. A bare raise is admitted only lexically inside an except body, where it re-raises that handler’s kind. And raise x for any other name or call evaluates x and then raises TypeError, which is what CPython does for every value the subset can produce, since none of them is an exception instance.
Where aython differs #
Some differences start here, in what the frontend admits or leaves out; the full list, with the test that pins each, is in Where it differs.
| Construct | CPython | aython |
|---|---|---|
| A comprehension’s loop variable | Local to the comprehension | Shares the enclosing scope and keeps its last value (_check_comp_generators) |
| A name assigned on only one branch, then read | NameError |
Reads None (slots start as None) |
| Annotations | Kept for __annotations__; since 3.14 evaluated only when that is read |
Never evaluated or checked (_check_annassign), and no __annotations__ exists |
c.x for a missing attribute |
AttributeError |
Aborts KeyError (instances are dicts) |
"s".append(1) |
AttributeError |
Aborts TypeError (method names are not tied to types) |
import os |
The standard library | Refused: only sibling .py files exist |
| Integer literals | Unbounded | Refused outside the 64-bit range -9223372036854775808 to 9223372036854775807 (int literal out of range) |
Where this lives #
| Concept | Where |
|---|---|
| The entry point: parse, flatten, check | frontend.compile_source |
| The one reshaped syntax error | frontend.parse_source, TRY_FINALLY_ELSE_MSG |
| Two passes: register, then check | check_program, _register_top_defs, _register_def, _register_class |
| Statement and expression dispatch | check_statement, check_expr |
| Name rules (assigned before use, no globals) | _check_name_load, _remember, _check_assign |
| Builtin and method arities | BUILTIN_ARITIES, METHOD_ARITIES, _check_call, _check_method_call |
| The refusal prefix and error type | UNSUPPORTED_PREFIX, _unsupported, FrontendError |
| How the judge checks a refusal | judge._check_reject |
| Import flattening | _expand_imports, _ImportJob, _ImportScope, MODULE_PREFIX_SEP, MAX_RELATIVE_LEVEL |
| Class flattening and C3 | _register_class, _register_class_bases, _linearize_bases, _c3_merge |
| Exception kinds | EXC_KINDS, EXC_ERASED_BASES, _check_try, _check_raise |
| The reject programs | tests/mvp/rej_*.py |
| The data on this page | docsite/figures/subset.py, docsite/static/widgets/refusals.js |
Check yourself #
Check yourself
A module assigns
x = 10and then definesdef f(): return x. What doesaython rundo with it?- Prints 10 when
f()is called, like CPython - Refuses it before assembling anything: a function may only read its own slots
- Compiles it, and
f()returnsNoneat run time
Answer
Refuses it before assembling anything: a function may only read its own slots. There are no globals or closures._check_name_loadrefuses the read withname 'x' is not assigned in this function (no globals or closures in MVP), andcompile_sourceraises before codegen runs.rej_global.pypins it.- Prints 10 when
After
from m import xand thenx = 2, what doesprint(m.x)print, ifm.pysetx = 10?2:xandm.xare the same slot10: the import compiled to a copyx = m__x, andm.xreadsm__x- Nothing: reading
m.xafter a from-import is refused
Answer
10: the import compiled to a copyx = m__x, andm.xreadsm__x. A from-imported variable becomes an ordinary assignment from the prefixed name. Rebinding the local leavesm__xalone, which is also what CPython does.pass_import_from.pyprints exactly this.Why does the frontend refuse two unrelated classes that both define a method called
fetch?- CPython forbids it too
c.fetch()is resolved at compile time by name alone, and an instance is a dict that does not know its class- The assembler cannot have two functions with the same name
Answer
c.fetch()is resolved at compile time by name alone, and an instance is a dict that does not know its class. The flattened functions would beA__fetchandB__fetch, which the assembler accepts. The problem is the call site: codegen picks the function from the method name, with no receiver type to consult. Unique names (and no overrides) make every method call a direct call.In
class D(B, C)whereB(A)andC(A), onlyAandCdefine__init__. Which one doesD()run?A.__init__, reached first throughBC.__init__, because the C3 order is D, B, C, A- Neither: the frontend refuses diamonds
Answer
C.__init__, because the C3 order is D, B, C, A._c3_mergecomputes CPython’s order, D → B → C → A, and construction takes the nearest class in it that defines__init__.pass_multi_bases.pypins this withDiaD.Which stage refuses
import os?- Parsing: CPython’s parser does not know
os - Import flattening: there is no
os.pynext to the program - Checking:
check_statementrefuses everyimport
Answer
Import flattening: there is noos.pynext to the program._ImportJob.load_modulelooks foros.pybeside the entry file and refuses withimport statement: missing module 'os'. There is no standard library; only sibling files can be imported.- Parsing: CPython’s parser does not know