Skip to content

Latest commit

 

History

History
148 lines (128 loc) · 8.46 KB

ARCHITECTURE.md

File metadata and controls

148 lines (128 loc) · 8.46 KB

A7 compiler architecture

A7 compiles .a7 source ahead-of-time to Zig source, then builds a native binary through the host Zig toolchain. The Python compiler is the full implementation; there is no separate runtime.

Pipeline (a7/compile.py: A7Compiler)

  1. a7/tokens.py: Tokenizer. Handles single-token generics ($T), nested block comments, and multiple number formats.
  2. a7/parser.py: Worklist-driven parser with precedence climbing. Produces nodes defined in a7/ast_nodes.py.
  3. a7/passes/: Semantic passes run in order: name_resolution.py -> type_checker.py -> semantic_validator.py -> safety.py. a7/proof_discharge.py defines obligation records, BackendPlan, and the observational discharge ledger (P-PROOF milestones). safety.py collects facts and obligations; discharge records and backend approvals sit on the shared boundary. Shared semantic state lives in a7/semantic_context.py and a7/symbol_table.py. Type resolution and shared integer width/range tables live in a7/types.py. Constant folding lives in a7/exact_constants.py, the compiler's single numeric folder.
  4. a7/ast_preprocessor.py: Sub-passes for stdlib resolution, struct initializer normalization, mutation/usage analysis, inference, shadowing, hoisting, and constant folding. a7/formatters/scope_walk.py provides shared scope-walk helpers.
  5. a7/backends/: Backend registry (__init__.py, base.py) and zig.py, which emits Zig source.

Supporting modules

Module Responsibility
a7/cli.py Argparse CLI entrypoint into A7Compiler, including Zig toolchain discovery
a7/module_resolver.py Resolves registered virtual imports, package-owned sources, and local files
a7/stdlib/ Module aliases, hook signatures, argument policies, declaration resources, and backend mappings
a7/formatters/ Console, JSON, and Markdown dumps for tokens, AST, semantics, and --doc-out
a7/errors.py Typed compiler errors and formatted diagnostics

Package-owned stdlib sources use their own canonical identity domain and containment root. Fixed hooks type-check against parsed declarations in their owner namespace, while explicit policies preserve formatting and numeric-family rules. The Zig backend emits mapped calls alongside only the packaged runtime fragments they use, keeping mapped helper names separate from user bindings. Each compilation installs one canonical Option/Result prelude identity and exposes IoErr through explicit I/O imports.

Safety precision and module lowering

Exact fixed-array slots use declaration-owned paths and allocation identities; array value copies receive independent slot paths. The safety pass drops this precision at uncertain joins and loop boundaries and excludes storage exposed through mutable views or array borrows for the rest of that function. Nested escapes and unknown nested writes invalidate affected descendant facts, while existing loop and interprocedural summaries keep their earlier place-key rules.

File-module scopes and lowering

  • a7/module_resolver.py enforces importer-relative canonical paths and entry-root containment.
  • Name resolution creates one file-root scope per module and records AST-use-to-declaration identity in resolved_uses. Type checking resolves qualified types and values in those scopes, and generic bodies keep the scope of their defining file.
  • After type checking, _lower_file_module_bindings assigns unique emission names to resolved declarations and uses. Semantic validation, safety, and the Zig backend consume those identities, emitting modules in load order followed by the entry file into a single Zig file.
  • Semantic reports retain file and lexical owners (escaping Markdown table separators and HTML characters) without introducing a typed IR. Typed IR remains unfinished.

Call and generic-alias boundaries

  • Known-call safety summaries compose direct reference stores to globals with captured arguments, return origins, and deletion origins. Equivalent positive loop increments can prove at most one loop trip when every backedge crosses the bound without wrapping. General global nil-state and parameter obligations remain incomplete.
  • L76 rejects parsed access through another file's import alias at semantic exit 6 with caller-relative direct-import guidance. Multi-dot type/literal syntax still fails parsing at exit 5, while ordinary exported struct-field chains keep their declaration identity.
  • Unreassigned, unborrowed, uncaptured local aliases of same-file generic declarations keep their concrete body obligations. Imported, module-global, parameter, mutable, selected, and captured origins remain incomplete; general runtime generic dispatch is not implemented.

The combined stage13 source passed the full release gate on 2026-10-07. See the qualification record for its source manifest, and see Status for open gaps.

Iterative traversal and qualification

Compiler internals must use explicit stacks and worklists. Both modes of the static scan in test/test_no_recursion.py (python test/norec_scan.py) report zero recursive groups, deepcopy calls, and recursive generated dataclass methods.

Snapshot 04330ece combined the iterative components below, passing 3,602 tests (with one expected failure) and all native example profiles. Its initial run failed the secrets check because the frozen snapshot lacked Git metadata; adding an exact-manifest index let secrets and all remaining release checks pass on the unchanged source. V1 remains incomplete. See the qualification record and follow-up record.

Component Snapshot SHA256 prefix Verification scope
Parser 58c4448e (9da02ec6 follow-up) 576 focused tests; 462 source comparisons; 111 review cases
Type checker 7b5d91cc (a87ebdfd follow-up) 1,246 focused tests; 648 source comparisons (612 reaching type check)
Zig backend 3aaf327e 184 focused tests; 171 source/profile comparisons; 42 AST checks; 51 examples (debug, release)
AST methods 21c85515 129 focused tests comparing equality, display, and cycles
Safety statement traversal e339c46f (338ecedb follow-up) 258 focused tests; 228 state comparisons; 195 source/profile checks; 40 compile runs

An empty static scan does not prove every dynamic execution path is iterative, and the scan excludes fields annotated Any or object from generated-method analysis.

How each component avoids recursion

  • Parser: Statement, expression, type, and pattern parsing use suspended frames. The driver resumes one child at a time, returns results to the parent, and forwards child exceptions so generic-literal lookahead can recover from a failed type parse. Token order, precedence, header state, and the 256-level nesting limit stay unchanged.
  • Type checker: Statements run on a worklist with continuations for diagnostic order and a region stack that restores scopes and facts. Type resolution uses suspended frames keyed by declaration identity for compound types and aliases. Expression and pattern checking run on a separate worklist preserving initializer fitting, exact-value handling, and match-arm cleanup.
  • Zig backend: Statement, expression, and type emission use separate worklists that preserve lexical names, indentation, loop labels, captures, helper selection, and emission order. The expression driver forwards child errors to parent handlers (including the match-pattern diagnostic wrapper).
  • Safety pass: Expression evaluation uses an explicit event stack preserving left-to-right operand order, applying each argument's borrowing effects before the next, and running callee replay and global effects afterward. Statements use suspended frames with child-error forwarding, verified on deep inputs at Python recursion limit 100. Compact allocation graphs replace enumerated fresh-origin paths (196 nodes for a depth-64 branching factory), though this does not prove a universal complexity bound.
  • AST equality and repr: Worklists walk declared dataclass fields and skip dynamic compiler annotations. repr preserves path-local cycle markers and captures container contents before rendering elements. ASTNode.literal_value remains typed Any, so custom third-party Python callbacks placed there are outside this traversal guarantee.