Pa logo v0.1.1 · MIT
Engineering Specification · v0.1.1

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.

01

Design principles

1. Python syntax, zero type noise

Every .pa file parses with ast.parse. Function bodies carry no type noise; types come from bidirectional inference.

2. Contiguous memory, RAII

Lists compile to flat arrays ([N x T], {T*, len, cap}), never PyObject* arrays. Heap memory is freed at scope exit with zero GC.

3. Host-first architecture

Pa owns main(), control flow, and compute. Python libraries live behind a locked boundary as a sandboxed toolbox.

4. First-class boundary customs

Every crossing is typed, checked in both directions, and replayable from a JSON fault snapshot — no silent corruption.

5. AI-native diagnostics

pac check --ai-diagnostic emits self-contained JSON repair tickets with causal chains and deterministic patches.

6. Safe by default, lean on demand

--mode dev bounds-checks and deep-lints; --mode prod removes runtime checks for C++/LLVM-class throughput.

02

Source files & the two-zone architecture

SuffixZoneRules & 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.
Host-First & Batching rule: .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.
Framework-driven apps: Compile @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.
03

The clean Python subset

AspectAllowedRejected (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)
PA_E060
≤ 40 lines / fn
PA_E061
Complexity ≤ 8
PA_E062
Nesting ≤ 3
PA_E051
>2 args: keywords

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).

04

Type system

Pa TypePython Alias / CastSizeNotes
int / int64int(x) (alias: i64)8 BDefault 64-bit signed integer for literals and range. Wraps on 64-bit overflow.
uint / uint64uint(x) (alias: u64)8 BDefault 64-bit unsigned integer with logical right shift (lshr), unsigned //, %, and unsigned comparisons.
float / float64float(x) (alias: f64)8 BDefault 64-bit floating-point type. / is always float division.
int32, float32int32(x), float32(x) (i32, f32)4 BExplicit narrow signed/float types for struct packing, big arrays, or C / .paw ABI.
uint8, uint32uint8(x), uint32(x) (u8, u32)1 / 4 BExplicit narrow unsigned integers (matches NumPy uint8/uint32; short u8/u32 aliases also supported).
boolbool / bool(x)1 BBoolean scalar.
str_view / Stringstr16 / 24 BRead-only {u8*, len} view vs RAII-owned {u8*, len, cap} string from + / +=.
list[T, N][x] * NN × sizeof(T)Flat stack array (≤ 64 KB). Nested 2-D arrays flatten and support m[i, j].
StackVec / Vec[T][], [x] * n, [0] * 024 B header{T*, len, cap} — stack-backed if bounded & non-escaping (≤ 64 KB), else RAII heap.
@structclass S: …C layoutNatural alignment, AoS inside Vec[S], supports nested structs & fixed-list fields.
span[T] / ptr[T]span(a, s, n) / alloc16 / 8 BZero-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.

05

Memory model

Assignment copies

b = a deep-copies arrays, structs, and vecs (llvm.memcpy; stack copies > 4 KB warn PA_W001). Raw pointer aliasing is forbidden (PA_E070).

Calls borrow

Containers and structs pass as zero-copy read-only borrows. Mutating callees require explicit mut(x) at the call site (PA_E050).

No mut() aliasing

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 TierConditionCompiled 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.

06

Runtime semantics, modes & faults

TopicPa BehaviourPython
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 zeroInteger: ZeroDivisionError fault (both modes; INT_MIN // -1 safe). Float /: IEEE inf/nan.Exception
Indexing0 ≤ i < len only; negative indexes are out of range (write a[len(a) - 1])Negative wraps
Ternary IfExpScalar-only (a if c else b); use if / else for structs or listsAny 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 narrowingCheckedChecked
Narrowing on assignments / fields / argsChecked (OverflowError)Removed
.paw static lint & boundary customsDeep 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.

07

The .paw boundary

DirectionPa TypePython SideCopy & OwnershipBoundary 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:

Inbound (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 dev scans every element of float32/float64 buffers for NaN/Inf (--mode prod skips the scan).
  • Zero-copy buffer views (build_arg): contiguous Pa containers (FixedList, Vec, StackVec, Span) are wrapped with PyMemoryView_FromMemory(..., PyBUF_READ) and .cast() to native format codes (i/q/B/I/Q/f/d/?), so np.frombuffer(arr, …) reads Pa memory directly without copying or mutating it.
  • Strings & scalars: str_view decodes as strict UTF-8 str; scalars box to Python int/float/bool.
Outbound (PY_TO_PA_OUT) · .paw → .pa
  • Strict scalar unboxing (unbox): catches Python exceptions, rejects None for non-void returns, blocks bool/int/float type drift, checks exact integer width bounds, and rejects NaN/Inf.
  • Fast-path buffer handoff (unbox_buffer): C-contiguous buffers (numpy.ndarray, array.array, bytes, memoryview) validate format & itemsize via PyObject_GetBuffer, then transfer into a fresh malloc buffer with a single memcpy so Pa owns its RAII lifetime independently of Python GC.
  • Sequence fallback: plain Python list/tuple falls back to PySequence_Fast with per-element None, type, and overflow checks; --mode dev additionally scans returned float Vecs for NaN/Inf.
  • Fault reporting & isolation: any violation or Python exception writes pa_boundary_fault.json with a replayable in_payload_snapshot (up to 1024 buffer elements in dev, 16 in prod). Executables exit with code 70; --shared libraries release the GIL and longjmp cleanly back to the host.
  • Embedded & relocatable: imported .paw sources are embedded into the binary (runtime __file__ is <embedded>/<name>.paw; override with PA_PATH). Pure-native binaries with no .paw link no Python at all.
Runtime Footprint & Isolation (with vs without .paw)
Linux x86-64 · Peak RSS

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.

ExamplePure-Native Pa RSSPa + .paw RSSPython Equivalent RSS
pipeline_demo (NumPy)n/a (uses NumPy RNG)38.57 MB41.79 MB
hashlib_pa (stdlib verify)2.67 MB19.86 MB~21.1 MB
raytracer (PIL PNG save)2.10 MB27.28 MB4.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.

08

Compiler pipeline & modules

.pa + .paw headers → ast.parse → validator.py → infer.py (fixed-point) → codegen.py (llvmlite IR) → LLVM -O2 .o → cc link (+ runtime C) → native bin / shared lib
ModuleResponsibility
pa_lang/types.pyContiguous memory type system (i32/i64/u8/u32/u64/f32/f64/bool, structs, vecs, spans), intrinsics & math registry.
pa_lang/validator.pySubset rules, .paw import isolation, loop batching, mut() checks, definite assignment, readability limits.
pa_lang/infer.pyFixed-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.pyStructured JSON repair tickets and PA_E030 @struct surgery engine.
pa_lang/codegen.pyllvmlite opaque-pointer IR emitter, bounds/div-zero/narrowing guards, RAII free, .paw marshaling stubs.
pa_lang/build.pyLLVM -O2 object emission, cross-platform gcc/clang/cl linking, .paw embedding, guarded @export wrappers.
runtime_core.c / bridge.cAlways-linked core (faults, TLS setjmp guards, Python-repr print) + optional embedded CPython bridge.
doctor.py / skills_cmd.py / lsp_server.pyPure-Python ELF / Mach-O / PE inspector (pac doctor/bundle), pac skill installer, and pygls LSP server.
09

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).

FamilyCodes
Syntax / subsetPA_E000 · PA_E003 · PA_E031
Isolation / .pawPA_E001 · PA_E002 · PA_E080 · PA_E082 · PA_E083 · PA_E084 · PA_E090
AnnotationsPA_E005 · PA_E081 · PA_E085
Layout / inferencePA_E011 · PA_E030 (@struct surgery) · PA_E071 · PA_E086 · PA_E088
Memory safetyPA_E004 · PA_E040 · PA_E070 · PA_E072 · PA_E073 · PA_E087 · PA_E089
Borrow / style / perfPA_E050 · PA_E051 · PA_E060–E062 · PA_W001
10

Tooling, CLI & editor support

CommandPurpose
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 lspLanguage 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.

11

AI skills

pa-coder

New projects: Host-First skeleton, zero-annotation bodies with -> T, contiguous structs/vecs, .paw isolation, self-heal via JSON tickets.

py-to-pa

Port Python repos using a three-colour feasibility gate (green compute / yellow invert control / red keep in Python) + differential verification.

cpp-to-pa

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.

12

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
13

Design choices & roadmap

Design choices (by intent)
  • Native LLVM targets for Linux x86-64, macOS (arm64 / x86-64), and Windows x64 with zero GC pauses.
  • Explicit boundary ownership: .paw returns text as RAII-managed Vec[uint8] (UTF-8 byte buffer) rather than raw str, 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 CSR Vec[Vec[T]], and @struct stays flat POD.
  • Predictable compute: no dict/set/tuple, closures, generators, or try/except in .pa — keep dynamic Python logic in .paw.
Roadmap & Non-goals
  • Standalone ecosystem packages (pa-libs) built on multi-file .pa module imports (-I / PA_PATH / pip packages).
  • (Low priority) Nested Vec fields inside @struct with recursive RAII destructors (flat SoA arrays and CSR Vec[Vec[T]] are preferred).
  • Non-goal: static libpython single-file binaries (incompatible with Windows/macOS CPython distributions and third-party .pyd/.so C extensions; use pac build --bundle --with-stdlib instead).