Pa Architecture & Specification
Inspired by Python, 100% Python-syntax compatible. Written by AI, auditable by humans.
Pa (.pa) compiles clean, zero-annotation Python syntax into contiguous C++-style memory with deterministic RAII, zero GC, and LLVM machine code — while reaching the Python ecosystem through typed, checked, replayable .paw modules.
Design principles
Every .pa file parses with ast.parse. Function bodies carry no type noise; types come from bidirectional inference.
Lists compile to flat arrays ([N x T], {T*, len, cap}), never PyObject* arrays. Heap memory is freed at scope exit with zero GC.
Pa owns main(), control flow, and compute. Python libraries live behind a locked boundary as a sandboxed toolbox.
Every crossing is typed, checked in both directions, and replayable from a JSON fault snapshot — no silent corruption.
pac check --ai-diagnostic emits self-contained JSON repair tickets with causal chains and deterministic patches.
--mode dev bounds-checks and deep-lints; --mode prod removes runtime checks for C++/LLVM-class throughput.
Source files & the two-zone architecture
| Suffix | Zone | Rules & Role |
|---|---|---|
| *.pa | Native zone (LLVM) | 100% compiled to native machine code. May import only pa, pa_lang, and project-local .paw modules (PA_E001 otherwise). |
| *.paw | Crossing zone (CPython) | Standard Python (NumPy, Pandas, PIL, requests, …). Every public function requires a locked static In -> Out signature acting like a C header. |
| *.py | Thin shell (optional) | For frameworks owning the event loop (FastAPI, Flask, Streamlit). Calls @export functions in a compiled .so; holds no business logic. |
.paw modules are stateless adapters — dynamic objects (DataFrame, PIL Image, HTTP Response) are created and consumed inside .paw; only scalars, strings, and flat numeric buffers cross. Calling a .paw function inside any loop is a compile error (PA_E002): pack inputs on the Pa side and cross once.@export entry points with pac build lib.pa --shared -o lib.so. Calls are guarded by setjmp so faults return an error code via pa_error_code() without crashing the host process.The clean Python subset
| Aspect | Allowed | Rejected (Diagnostic) |
|---|---|---|
| Annotations | @struct fields; @export & .paw signatures; -> T return type on any function |
Body or non-export param annotations (PA_E005); Any/Union/Optional; return mismatch (PA_E085) |
| Data | Scalars, str, homogeneous lists, @struct |
Heterogeneous lists (PA_E030), dict / set / tuple (PA_E031) |
| Control flow | if/elif/else, for … in range/list, while, break, continue, guard returns |
try/except, with, yield, await, global, nonlocal, del (PA_E003) |
| Functions | Top-level functions, keyword calls, libm math builtins (sin, cos, sqrt, atan2, exp, log, floor, ceil) |
Closures, lambda, nested functions, *args/**kwargs, eval/exec, reflection (PA_E003) |
| Views & slicing | s[i], span(arr, start, len) |
arr[1:5], list a + b, .extend() (PA_E071) |
Static safety passes also enforce definite assignment (PA_E088), one type per variable (PA_E086), no mutation while iterating (PA_E087), and compile-time checks on constant indexes (PA_E073).
Type system
| Pa Type | Python Alias / Cast | Size | Notes |
|---|---|---|---|
| int / int64 | int(x) (alias: i64) | 8 B | Default 64-bit signed integer for literals and range. Wraps on 64-bit overflow. |
| uint / uint64 | uint(x) (alias: u64) | 8 B | Default 64-bit unsigned integer with logical right shift (lshr), unsigned //, %, and unsigned comparisons. |
| float / float64 | float(x) (alias: f64) | 8 B | Default 64-bit floating-point type. / is always float division. |
| int32, float32 | int32(x), float32(x) (i32, f32) | 4 B | Explicit narrow signed/float types for struct packing, big arrays, or C / .paw ABI. |
| uint8, uint32 | uint8(x), uint32(x) (u8, u32) | 1 / 4 B | Explicit narrow unsigned integers (matches NumPy uint8/uint32; short u8/u32 aliases also supported). |
| bool | bool / bool(x) | 1 B | Boolean scalar. |
| str_view / String | str | 16 / 24 B | Read-only {u8*, len} view vs RAII-owned {u8*, len, cap} string from + / +=. |
| list[T, N] | [x] * N | N × sizeof(T) | Flat stack array (≤ 64 KB). Nested 2-D arrays flatten and support m[i, j]. |
| StackVec / Vec[T] | [], [x] * n, [0] * 0 | 24 B header | {T*, len, cap} — stack-backed if bounded & non-escaping (≤ 64 KB), else RAII heap. |
| @struct | class S: … | C layout | Natural alignment, AoS inside Vec[S], supports nested structs & fixed-list fields. |
| span[T] / ptr[T] | span(a, s, n) / alloc | 16 / 8 B | Zero-copy borrowed view vs manual FFI pointer (alloc/free). |
Bidirectional inference: runs per function and iterates to a fixed point across call sites. Empty lists infer their element type from the first append or a single-level mut() callee; use [0] * 0, [0.0] * 0, or [Node(...)] * 0 for typed empty heap vecs. Module-level scalar/string constants fold at compile time.
Memory model
b = a deep-copies arrays, structs, and vecs (llvm.memcpy; stack copies > 4 KB warn PA_W001). Raw pointer aliasing is forbidden (PA_E070).
Containers and structs pass as zero-copy read-only borrows. Mutating callees require explicit mut(x) at the call site (PA_E050).
Passing the same container twice when one is mut() is rejected (PA_E089). Scalar reads like f(mut(v), v[i]) load by value first and are allowed.
| Storage Tier | Condition | Compiled Representation |
|---|---|---|
| Tier 1 · Stack | Scalars, structs, constant lists (≤ 64 KB), or non-escaping dynamic lists with a known constant append bound | [N x T] or stack-backed StackVec: zero malloc, O(1) stack pointer release. |
| Tier 2 · Heap RAII | Unbounded appends, runtime [x] * n, escapes via return, or > 64 KB |
Vec[T] (cap starts at 16 and doubles); compiler inserts free on every exit path unless returned. |
| Tier 3 · Hard Error | Heterogeneous list (PA_E030), uninferable [] (PA_E011), escaping span (PA_E040), alloc leak/UAF (PA_E004) |
Compilation stops with a structured repair ticket. |
Strings: UTF-8 bytes (len("héllo") == 6, s[i] is u8). Concatenation (a + b, s += x) allocates an RAII-owned String; temporary strings must be bound to a local (PA_E072) so RAII owns and frees them.
Runtime semantics, modes & faults
| Topic | Pa Behaviour | Python |
|---|---|---|
Integer //, % | C semantics: truncates toward zero (-7 // 2 == -3, -7 % 3 == -1) | Floors toward −∞ |
Float % | C fmod (-1.0 % 6.283 == -1.0) | Floored |
| Div / mod by zero | Integer: ZeroDivisionError fault (both modes; INT_MIN // -1 safe). Float /: IEEE inf/nan. | Exception |
| Indexing | 0 ≤ i < len only; negative indexes are out of range (write a[len(a) - 1]) | Negative wraps |
Ternary IfExp | Scalar-only (a if c else b); use if / else for structs or lists | Any value |
print() | Matches Python repr for ints, u64, bools, strs, and floats | — |
| Check | --mode dev (default) | --mode prod |
|---|---|---|
Variable index bounds (a[i], m[i, j], span, str) | Checked (IndexError) | Removed (C-like) |
Div-by-zero, range step 0, .paw narrowing | Checked | Checked |
| Narrowing on assignments / fields / args | Checked (OverflowError) | Removed |
.paw static lint & boundary customs | Deep lint + element NaN scans (1024-elem snapshots) | Signature check + scalar customs (16-elem snapshots) |
Executables write a structured JSON report (pa_runtime_fault.json or pa_boundary_fault.json, override with PA_FAULT_PATH) and exit with code 70. Shared libraries record the fault in TLS and return 0 to the host.
The .paw boundary
| Direction | Pa Type | Python Side | Copy & Ownership | Boundary Customs |
|---|---|---|---|---|
| In (.pa → .paw) | int, uint, float, bool int32, uint8, uint32, float32 |
int / float / bool | Boxed value copy | Rejects NaN/Inf (unless @allow_nan); narrow int OverflowError guard |
| In (.pa → .paw) | str_view / String | str | Strict UTF-8 decode copy | len ≥ 0, non-NULL pointer, strict UTF-8 |
| In (.pa → .paw) | span[T], Vec[T], list[T, N] | read-only memoryview | Zero-copy (borrows Pa memory) | len ≥ 0, non-NULL; dev: element-wise NaN/Inf scan on floats |
| Out (.paw → .pa) | void | None | — | Must return None (any other object faults) |
| Out (.paw → .pa) | int, uint, float, bool int32, uint8, uint32, float32 |
int / float / bool / np.bool_ | Unboxed value copy | Rejects None, type drift (bool ≠ int ≠ float), width overflow, NaN/Inf |
| Out (.paw → .pa) | Vec[T] (text via Vec[uint8]) |
ndarray / array / bytes / list | RAII-owned copy (malloc + memcpy) |
Buffer format & itemsize check (or sequence element checks); dev: float NaN/Inf scan |
When infer.py sees import x and x.paw exists, it reads only the public function signatures as a static header. At codegen time, each call emits a marshaling stub into pa_call_paw() in runtime_bridge.c:
PA_TO_PY_IN) · .pa → .paw- Pre-flight customs (
check_out): validates finite floats (unless@allow_nan), non-negative lengths, and non-NULL pointers; in--mode devscans every element offloat32/float64buffers forNaN/Inf(--mode prodskips the scan). - Zero-copy buffer views (
build_arg): contiguous Pa containers (FixedList,Vec,StackVec,Span) are wrapped withPyMemoryView_FromMemory(..., PyBUF_READ)and.cast()to native format codes (i/q/B/I/Q/f/d/?), sonp.frombuffer(arr, …)reads Pa memory directly without copying or mutating it. - Strings & scalars:
str_viewdecodes as strict UTF-8str; scalars box to Pythonint/float/bool.
PY_TO_PA_OUT) · .paw → .pa- Strict scalar unboxing (
unbox): catches Python exceptions, rejectsNonefor non-voidreturns, blocksbool/int/floattype drift, checks exact integer width bounds, and rejectsNaN/Inf. - Fast-path buffer handoff (
unbox_buffer): C-contiguous buffers (numpy.ndarray,array.array,bytes,memoryview) validate format &itemsizeviaPyObject_GetBuffer, then transfer into a freshmallocbuffer with a singlememcpyso Pa owns its RAII lifetime independently of Python GC. - Sequence fallback: plain Python
list/tuplefalls back toPySequence_Fastwith per-elementNone, type, and overflow checks;--mode devadditionally scans returned floatVecs forNaN/Inf.
- Fault reporting & isolation: any violation or Python exception writes
pa_boundary_fault.jsonwith a replayablein_payload_snapshot(up to 1024 buffer elements indev, 16 inprod). Executables exit with code 70;--sharedlibraries release the GIL andlongjmpcleanly back to the host. - Embedded & relocatable: imported
.pawsources are embedded into the binary (runtime__file__is<embedded>/<name>.paw; override withPA_PATH). Pure-native binaries with no.pawlink no Python at all.
.paw)
Pure-native .pa binaries link zero libpython and run in a 2–3 MB resident footprint. When a program imports a .paw bridge that loads PIL (~25 MB) or NumPy (~38 MB), the process RSS rises to 20–38 MB — that baseline comes from the on-demand embedded CPython runtime and third-party C extensions themselves, not from Pa’s native runtime.
| Example | Pure-Native Pa RSS | Pa + .paw RSS | Python Equivalent RSS |
|---|---|---|---|
| pipeline_demo (NumPy) | n/a (uses NumPy RNG) | 38.57 MB | 41.79 MB |
| hashlib_pa (stdlib verify) | 2.67 MB | 19.86 MB | ~21.1 MB |
| raytracer (PIL PNG save) | 2.10 MB | 27.28 MB | 4.25 MB (g++ -O2, no PIL) |
Engineering best practice: for ultra-lightweight CLIs, edge workers, or high-concurrency micro-processes (2–3 MB RSS), stay pure-native with zero .paw imports. When you need NumPy/PIL/ecosystem libraries, keep large intermediate arrays in Pa’s flat Vec[T] and cross .paw only at the final I/O or export step to avoid Python container bloat.
Compiler pipeline & modules
| Module | Responsibility |
|---|---|
| pa_lang/types.py | Contiguous memory type system (i32/i64/u8/u32/u64/f32/f64/bool, structs, vecs, spans), intrinsics & math registry. |
| pa_lang/validator.py | Subset rules, .paw import isolation, loop batching, mut() checks, definite assignment, readability limits. |
| pa_lang/infer.py | Fixed-point bidirectional type inference, stack-bound escape analysis, Vec promotion, alias & temp-string checks, LSP hints. |
| pa_lang/paw.py | .paw signature header parser and dev-mode deep static lint (PA_E083, PA_E084). |
| pa_lang/diagnostics.py | Structured JSON repair tickets and PA_E030 @struct surgery engine. |
| pa_lang/codegen.py | llvmlite opaque-pointer IR emitter, bounds/div-zero/narrowing guards, RAII free, .paw marshaling stubs. |
| pa_lang/build.py | LLVM -O2 object emission, cross-platform gcc/clang/cl linking, .paw embedding, guarded @export wrappers. |
| runtime_core.c / bridge.c | Always-linked core (faults, TLS setjmp guards, Python-repr print) + optional embedded CPython bridge. |
| doctor.py / skills_cmd.py / lsp_server.py | Pure-Python ELF / Mach-O / PE inspector (pac doctor/bundle), pac skill installer, and pygls LSP server. |
Diagnostics for AI agents
pac check --ai-diagnostic emits a JSON array of self-contained repair tickets (code, category, skill_rule_ref, location, inferred_context, causal_chain, source_context, and repair_plan.suggested_patches).
| Family | Codes |
|---|---|
| Syntax / subset | PA_E000 · PA_E003 · PA_E031 |
Isolation / .paw | PA_E001 · PA_E002 · PA_E080 · PA_E082 · PA_E083 · PA_E084 · PA_E090 |
| Annotations | PA_E005 · PA_E081 · PA_E085 |
| Layout / inference | PA_E011 · PA_E030 (@struct surgery) · PA_E071 · PA_E086 · PA_E088 |
| Memory safety | PA_E004 · PA_E040 · PA_E070 · PA_E072 · PA_E073 · PA_E087 · PA_E089 |
| Borrow / style / perf | PA_E050 · PA_E051 · PA_E060–E062 · PA_W001 |
Tooling, CLI & editor support
| Command | Purpose |
|---|---|
| pac check [--ai-diagnostic] [--mode dev|prod] PATH… | Front-end checks on .pa and .paw files; exits 1 on errors. |
| pac build FILE [-o OUT] [--mode dev|prod] [--shared] [--relocatable] [--emit-ir] | Compile to a native binary, guarded shared library (.so/.dylib/.dll), or LLVM IR. |
| pac doctor [BINARY] | Diagnose host toolchain or ELF / Mach-O / PE loader dependencies & Python home of a built binary. |
| pac bundle BINARY [--dest D] [--with-stdlib] | Copy libpython (and optionally trimmed stdlib) next to a relocatable binary. |
| pac skill [NAME] [--list] [--install TARGET] [--global] [-o FILE] | Print or idempotently install bundled AI SKILL.md files (claude, cursor, codex, copilot, antigravity). |
| pac lsp | Language server over stdio with simple/detailed inlay hints, hover memory audit cards, and auto-reload. |
VS Code extension (vscode-pa/): registers pa and paw languages with TextMate grammars inheriting source.python, highlights Pa intrinsics/decorators/narrow types, and connects to pac lsp.
AI skills
New projects: Host-First skeleton, zero-annotation bodies with -> T, contiguous structs/vecs, .paw isolation, self-heal via JSON tickets.
Port Python repos using a three-colour feasibility gate (green compute / yellow invert control / red keep in Python) + differential verification.
Modernise C++: map std::vector, std::span, structs, and Node* pools into Pa vecs, spans, and index arenas; verify byte-for-byte vs g++ -O3.
Repository layout & verification
pa/
├── pyproject.toml package metadata (entry point: pac = pa_lang.cli:main)
├── pa_lang/ compiler, C runtimes, ELF/Mach-O/PE doctor, LSP, bundled skills
├── skills/ pa-coder · py-to-pa · cpp-to-pa
├── vscode-pa/ VS Code extension (TextMate grammar, client, tests)
├── site/ palang.dev (index, quickstart, architecture)
├── examples/
│ ├── pipeline_demo/ Host-First minimal .pa + .paw demo
│ ├── hashlib_pa/ Python port: CRC-32 + SHA-256 (367x vs pure Python)
│ └── raytracer/ C++ port: Ray Tracing in One Weekend (1.24x g++ -O3, 0 diff)
├── tests/ 150 pytest tests (infer, validator, codegen, LSP, doctor, skill)
└── .github/workflows/ CI (Python 3.11–3.13 + npm test) and PyPI release
Design choices & roadmap
- Native LLVM targets for Linux x86-64, macOS (arm64 / x86-64), and Windows x64 with zero GC pauses.
- Explicit boundary ownership:
.pawreturns text as RAII-managedVec[uint8](UTF-8 byte buffer) rather than rawstr, and structured data crosses as flat SoA arrays instead of opaque structs. - Flat, cache-friendly layouts: helpers are monomorphic over container layouts (unify mixed stack/heap callers via
span[T]), ragged 2-D lists lower to flat CSRVec[Vec[T]], and@structstays flat POD. - Predictable compute: no
dict/set/tuple, closures, generators, ortry/exceptin.pa— keep dynamic Python logic in.paw.
- Standalone ecosystem packages (
pa-libs) built on multi-file.pamodule imports (-I/PA_PATH/ pip packages). - (Low priority) Nested
Vecfields inside@structwith recursive RAII destructors (flat SoA arrays and CSRVec[Vec[T]]are preferred). - Non-goal: static
libpythonsingle-file binaries (incompatible with Windows/macOS CPython distributions and third-party.pyd/.soC extensions; usepac build --bundle --with-stdlibinstead).