Skip to content

Architecture

postpile turns a typed Python subset into native code (a shared library / extension module from a module of functions, or a self-contained executable from a whole script (ppc build --exe, ADR 0003)) by driving one source program through a fixed sequence of stages. The central decision is in the middle of that sequence: the frontend lowers Python AST into a single backend-agnostic typed SSA IR; the backends consume that IR unchanged. This is why postpile can be multi-backend where AST-directed transpilers stall. A backend does not work out types, control flow or array addressing from Python syntax again; it only walks IR that already has all of that pinned down.

The pipeline

  foo.py  (POST Python source)
     │
     ▼
 ┌───────────────┐   check_source()          reject anything outside the
 │   checker     │ ─────────────────────►    compilable subset → Violation (PPxxx)
 └───────────────┘
     │  zero violations
     ▼
 ┌───────────────┐   ast.parse → FunctionLifter
 │   frontend    │   declare()  then  lower()
 │  (lowering)   │ ─────────────────────►    typed SSA IR
 └───────────────┘
     │
     ▼
 ┌───────────────┐   verify_module()         IR01–IR19: definitions precede uses,
 │  IR verifier  │ ─────────────────────►    handles stay out of arithmetic, every
 └───────────────┘                           call matches the C it will link to
     │  raises IRVerificationError — a compiler bug, never a diagnostic
     │  compile_program: dependencies first, entry module last
     ▼
 ╔═══════════════════════════════════╗
 ║   typed SSA IR  —  Module(s)      ║   ONE IR, backend-agnostic
 ╚═══════════════════════════════════╝
     │  get_backend(name)   "c" │ "qbe" │ "llvm" │ plugin
     ▼
 ┌───────────────┐   emit(module)             IR → backend source (.c / .ssa / .ll)
 │   backend     │   compile_object(src,obj)  source → .o
 └───────────────┘
     │  + runtime_sources (always C)  + pp_<export> ABI wrappers (always C)
     ▼
   cc -shared -lm   →   foo.so / foo.dylib
   cc -lm (+ a C main)  →  foo        (whole-script --exe path, build_executable)
Stage Entry point Output
Subset check checker.check_source list[Violation] (empty = valid POST Python)
Lowering compiler.frontend.compile_source / compile_program typed SSA IR Module objects
IR verification compiler.verify.verify_module nothing, or IRVerificationError
Backend selection compiler.backends.get_backend a Backend implementation
Emit + assemble Backend.emit / Backend.compile_object backend source, then object files
Link build.build_source / build.build_file / build.build_executable one native shared library, or one executable (whole-script mode)

1. Subset check

check_source parses the file with ast.parse and walks it, reporting the constructs that fall outside the compilable subset as Violations, each with a PPxxx code and a source location. A syntax error becomes PP000. Banned dynamic builtins, such as eval, exec and getattr, get codes of their own, as do the other out-of-subset forms. A file with zero violations is a valid POST Python translation unit. The build drivers refuse to proceed if any violation is reported, so nothing past this gate has to defend against un-typeable Python.

2. Frontend lowering (AST → typed SSA IR)

The frontend re-runs the checker, parses to AST, then lifts each def into an IR Function (or a UFunc when it has a @vectorize / @guvectorize layout signature). Lifting is two-phase, driven by FunctionLifter:

  • declare() builds the typed function shell from the signature: parameter dtypes, array-ness, shapes, and core-dimension parameters.
  • lower() fills in the body only after all the functions in the module (and its imported POST dependencies) has been declared.

With that ordering, a call resolves against forward references and against functions imported from other POST modules, using the callee's declared signature as the source of truth for the result type. Type inference (infer_function) runs over the body, and statements/expressions lower into basic blocks of typed SSA Values: range loops become explicit condition/body/step/after blocks, if/while become CondBranch, subscripts become stride-scaled ArrayLoad/ArrayStore. Anything valid-but-not-yet-lowered is reported as PP900, never silently dropped.

Two container types, and [a, b, c] builds one of them

This compiler has two container types with two spellings, which are not interchangeable: ADR 0027, "Two types" is the one place that decision lives; read it before writing either.

  • Array[T] is a layout: a fixed-shape contiguous buffer of T's own itemsize, without header or growth, describable by the buffer protocol, and what a NumPy ufunc receives. Indexing lowers to a stride-scaled ArrayLoad/ArrayStore, and len of a literal folds to a constant.
  • list[T] is an object: a header with a reference count, a length and a capacity, plus a separately allocated element buffer that append may move. It owns its elements and releases them when it dies. Its operations are calls into the list runtime, and len is a field read.

The literal [a, b, c] builds a list, because that is what it builds in CPython. It builds an Array[T] only where the binding it initialises is annotated Array[T], which is how numeric programs already write it (examples/nbody, the @guvectorize kernels).

Which of the two a value is, is asked once, as Value.is_aggregate (does this value hold elements), and never as is_array at a call site. An Array[T] is container-shaped on the Value (a scalar dtype plus a flag) and a list[T] on the dtype, so a guard written over either half covers one container and silently admits the other: +xs on a list was accepted and returned the container for exactly that reason. The dtype half is aggregate-by-default, so a third container is refused by those guards on the day its class statement is written. See ADR 0028, "The predicate" and arbitration A74.

The sugar over an aggregate

Printing a whole container, list comprehensions, and sum/min/max/ sorted are ADR 0028. Three of the four are lowered in the frontend, as loops over operators that already exist, so sum inherits the checked-Int64 overflow trap and min inherits CPython's tie and NaN behaviour. sorted is the exception, for a reason: it produces a new list, so it is the one with a runtime helper.

A reader will meet two facts from it. print(xs) writes repr of each element, which for a list[str] is answered exactly on the ASCII domain and traps above it (A12: Unicode printability is not shipped, and a wrong escape would be a wrong answer nothing would catch). min([]) raises a catchable ValueError, and an out-of-range list index likewise raises IndexError since [ADR 0030] (adr/0030-dict-and-set.md) put IndexError/KeyError in the exception vocabulary (it trapped before).

Definite assignment

compiler.definite.check_definite_assignment runs over the same tree the lifters lower, and answers one question the IR cannot: is every read of a local reached by a binding? A compiler that gives each local a frame slot has no moment at which the name does not exist, so if c: y = 1 followed by return y has to be asked about statically or it is silently accepted. Before ADR 0033 that case was refused, crashed on, or silently accepted depending on the value's type and its number of bindings.

It is a source pass and not part of the lowering: the lowering has flattened the branches into blocks by the time it could ask. The rule is the standard conservative one. A read it cannot prove bound is not refused: since ADR 0033's amendment it compiles as a checked read, a hidden flag per name that each binding sets and the read tests, raising CPython's UnboundLocalError (or NameError at a script's top level). A read it proves bound costs nothing, so a function whose locals are all bound has the IR it had before. while True: binds what every break bound, because its body always runs, and that rule is shared with _lower_while through one predicate, so the analysis and the code generator cannot disagree about which loops those are.

compile_source produces one Module from text. compile_program resolves POST imports (narrowly: the entry file's source root plus explicit search_paths; site-packages is never searched), compiles each dependency once depth-first, diagnoses import cycles as PP500, and returns the modules dependency-ordered with the entry module last. It also enforces that public function names are unique across the linked program (PP501), since the publics of all units become extern C symbols in one artifact.

3. The IR: one representation, every backend

The IR is a typed, SSA-inspired three-address form: a Module (one translation unit) holds Function/UFunc definitions, each a list of BasicBlocks ending in a Return/Branch/CondBranch terminator. A Value has a DType, plus shape, layout, and array/output flags. Types, control flow, array addressing, and cross-module linkage are all resolved here, once.

This is the architectural thesis. Because the IR is complete and backend-neutral, a backend is a pure IR→text lowering with no Python knowledge. Adding a backend costs a single emit walk. A differential test oracle can hold the backends to the same semantics because they consume identical IR.

Why AST-directed compilers stall here

When each backend lowers straight from Python AST, the backends each re-implement type inference, promotion, and array indexing, so the second backend is nearly as expensive as the first, and they drift. Concentrating that work in one typed IR makes the N-th backend cheap and keeps them in agreement.

The IR verifier

compiler.verify.verify_module runs at the end of compile_source, on clean compiles, in release builds as well as debug, before any backend sees the module. It checks twenty invariants, IR01–IR20 (ADR 0014, extended since), among them:

  • definitions precede uses in emission order;
  • opaque handles stay out of arithmetic, casts and conditions;
  • array bases are arrays and indices are integers;
  • values only land in slots that can hold them;
  • an emitted call matches the C definition it will link to.

The runtime helpers' signatures are parsed out of the C that defines them (compiler/abisig.py), so there is no second list to drift.

It raises IRVerificationError and reports no diagnostic, because no POST program can cause one of these: it is a compiler bug. A diagnostic would invite the author to change code that is not wrong. Cost is about 3.5% of frontend time: one linear pass per function, no dominator tree.

4. Backend registry and selection

Backends live in a name-keyed registry (compiler.backends). The built-ins, CBackend ("c"), QBEBackend ("qbe"), and LLVMBackend ("llvm"), register on import; third parties ship a backend as a separate package via the postpile.backends entry-point group (a broken plugin is skipped with a warning, never breaking import postpile).

from postpile.compiler.backends import get_backend, available_backends

backend = get_backend("qbe")  # UnknownBackendError if not registered
available_backends()  # names whose external tools are present

A backend satisfies the Backend protocol: a name, a source_ext (".c", ".ssa", …), a Capabilities descriptor (complex, ext_module, float16), and three methods: emit(module) -> str, compile_object(source, obj, tc), and runtime_sources(modules). The driver reads capabilities before building; for example, build_file(..., ext_module=True) is rejected up front unless the chosen backend reports ext_module.

The driver (build.py) ties it together. build_source compiles a single translation unit from text; build_file compiles an entry file and the POST modules it imports. Both funnel into _link_modules, which, for the selected backend be:

  1. writes be.emit(module) for each IR module to a file with suffix be.source_ext, then calls be.compile_object(src, obj, tc) to produce an object file;
  2. compiles each be.runtime_sources(modules) unit (backend runtime helpers are always C, e.g. QBE's integer-** helper);
  3. compiles the pp_<export> stable-ABI wrapper translation unit, also always C;
  4. links the objects into one shared library with cc -shared -lm (a -bundle with dynamic lookup on macOS for CPython extension modules).

Each POST module becomes its own object file, so cross-module calls resolve to the compiled POST functions at link time, ahead of any same-named libm symbol. The result is a .so/.dylib you load with ctypes.CDLL, or, with ext_module=True, an importable CPython extension whose public ufuncs register as real numpy.ufuncs; build_executable takes the third path, wrapping a whole script's top-level code in a generated C main and linking a self-contained binary (ppc build --exe, ADR 0003). The Toolchain dataclass holds the compiler command, the qbe command and the composed cflags, so the same driver serves all the backends.

This document describes the pipeline skeleton. The ADR index records the language surface built on it decision by decision (ADRs 0023–0049): classes and instance refcounting, the container and str runtimes, exceptions, the CPython FFI and the pygo concurrency lowering.

The C backend's export wrappers and the CPython-extension glue are intentionally always C: they are the ABI boundary, shared by all backends, and don't belong in a backend's per-target lowering. See the backend protocol for the full contract and writing a backend to add your own.