Compiler Architecture and Routing
This document describes the compiler’s current layering, directory responsibilities, feature routing, and L1 stage contract. See 02-frontend.md for frontend details and 03-ir-and-criteria.md for the IR and acceptance criteria. The four-layer model itself is described in RFC-039.
Dependency Direction
| Rule | Check |
|---|---|
| Dependencies may only point downward: L1 → L2/L3/L4, L2 → data domain, L3 → data domain, and L4 is independent | scripts/ci/check-boundary.py |
L2 (lexer/parser) must not use L3/L4 | check-boundary.py B2 |
L3/L4 must not use L2’s lexer/parser | check-boundary.py B3 |
include! is prohibited | check-boundary.py B1 |
Opcode constants may only be defined in src/middle/bytecode/opcode.rs | check-boundary.py B5 |
Peripheral tools (formatter / lsp / repl / package / util) may only consume the pub APIs of L1–L4 | check-boundary.py |
Cross-layer pub(crate) leakage may only decrease, never increase | check-boundary.py baseline |
The only legitimate interface from L2 to L3 is injection: the parser depends only on the TypeEnvProbe trait in parser/probe.rs, whose implementation is supplied by L3 at the entry point.
Directory Responsibilities
| Directory | Responsibility | Excluded |
|---|---|---|
src/ast/ | Sole carrier of the AST and syntactic types; constructed by L2 and consumed by L3 | Type checking, evaluation, IR |
src/driver/ | L1: Stage / Program / Driver / obligation settlement / diagnostic aggregation | Concrete language semantics |
src/frontend/core/lexer/ | Lexing: tokens, literals, spans | Syntactic structures, types |
src/frontend/core/parser/ | Syntax: Pratt expressions, statements/declarations, error recovery, Type syntax | Type checking, name resolution |
src/frontend/core/types/ | Working representation of MonoType, substitution/solving, constant evaluation, type tables | Parser/AST construction |
src/frontend/core/sema/ | Type checking, inference, checkers, refinement/termination/ownership layers, proofs | IR construction |
src/frontend/module/ | Module discovery, registries, role classification, import/export resolution | Type semantics |
src/middle/ir/ | SSA IR definitions, validators, snapshots | AST semantics |
src/middle/lower/ | Sole construction path from AST to ModuleIR | Type checking |
src/middle/passes/ | Monomorphization, DCE, codegen | IR definitions |
src/middle/bytecode/ | Bytecode format, opcode tables, .42 serialization | Execution strategy |
src/backends/ | Interpreter, runtime, FFI | Compile-time semantics |
src/std/ | Standard library source and interface tables | Compiler internal representations |
src/util/ | Diagnostic code tables, diagnostic emission, logging, and other shared infrastructure | Compilation-stage logic |
src/lsp/, src/formatter/, src/repl/, src/package/ | Peripheral tools | Compilation-stage implementations |
tools/ | Standalone gate/generation tools (type-tables, code-tables, etc.) | Compiler runtime |
Feature Routing Table
| Item to Add/Change | Primary Change Site | Related Changes | Criteria |
|---|---|---|---|
| An operator or precedence level | Single table in parser/pratt/precedence.rs | Lexer token, ast::BinOp, SPEC, parser/tests/associativity.rs | C5 (snapshot + diagnostics + behavior) |
| A literal kind | lexer/literals.rs and token | Parser consumption sites, diagnostic codes, corpus | C5 |
| A syntactic construct | parser/statements/ or pratt/ | ast node, sema consumer, formatter, LSP syntax tree | C5 |
| A type form | ast::Type + parser type syntax | types/mono.rs (→ MonoType), sema, 02-frontend | C3 or C5 |
| A type-checking rule | sema/inference/ or sema/checker/ | MonoType, diagnostic codes, direct-drive tests | C3/C4 |
| A diagnostic code | src/util/diagnostic/codes/ | locales/*.json, RFC-013, generated pages, test assertions | Per RFC-013 |
| A compilation stage or stage ordering | driver/stage.rs + driver/arms.rs | Exhaustive Driver match, obligation ledger, this document’s §Obligation Ledger | C2 |
| A cross-stage obligation | TypeCheckResult + driver/obligations.rs + this document’s §Obligation Fields | Delivery point in driver/arms.rs, consumption point, check-obligations.py | C2 |
| An IR instruction/structure | middle/ir/ir.rs | lower, codegen, verify, snapshots | C4 |
| A bytecode format field | middle/bytecode/file.rs | codegen, interpreter, .42 version | C4 |
| A standard library function | src/std/ source + std/yx_sources.rs | Interface table, documentation, corpus | Behavior tests |
| An LSP capability | src/lsp/ | DriverOutcome.semantic_db, this document’s §Stage Model | Direct-drive tests |
| A gate/generator | scripts/ci/ or tools/ | CI, criteria wording in this document and 03-ir-and-criteria | Gate self-test |
Stage Model
Compilation stages are an exhaustive enum: adding a stage requires adding a Stage variant, and the exhaustive match in Driver::dispatch enforces handling at compile time.
src/driver/stage.rs defines 12 stages, with Stage::ALL arranged in topological order based on data dependencies:
VendorConsistency → Discovery → Parsing → Registry → RoleClassification
→ Typecheck → DeadCodeAnalysis → ProofExecution → GlobalSlotAlloc
→ IrGeneration → Linking → MonomorphizationStageScope declares the execution granularity of each stage:
PerModule: Executed once per compilation unit.Project: Executed once per project;dispatchstructurally guarantees that it runs only once.
Implementations for individual stages are dispatched by stage name in src/driver/arms.rs; Driver is responsible only for ordering, skipping, and failure propagation.
Program and Entry Point
src/driver/program.rs describes a compilation as a Program:
ProgramKind | Use |
|---|---|
SingleFile | Single-file run |
MultiFile | Multi-file project run |
Check | yaoxiang check (diagnostics only; no execution) |
Lsp | Compilation for LSP requests |
Embedded | Internal compilation, such as embedded std |
WasmPlayground | WASM playground |
ProgramKind::stages() is the sole source of the stage table; callers cannot pass arbitrary arrays. Aggregation determines how diagnostics are aggregated: FailFast is used for compilation paths, while CollectAll is used for check and LSP.
Driver is the only place where Program is interpreted; cross-stage diagnostic aggregation and exit-code determination are handled in src/driver/diagnostics.rs.
Skipping and Failure
A stage may be skipped because an upstream stage failed or because configuration disabled it. The reason is recorded in SkipReason:
UpstreamFailed: The upstream stage failed, so this stage did not run.ConfigDisabled: Configuration disabled the stage (such as mono depth/switches).NoObligations: There was no data requiring processing (skipping does not mean discarding).
Skipping must be explicitly recorded; it is forbidden to pass off an empty result as though the stage had run.
Obligation Ledger
The fields of TypeCheckResult fall into two categories:
- Cross-stage obligation fields: The producer must deliver them, and the consumer must read them.
- Non-obligation fields: They do not constitute cross-stage contracts, and a rationale must be registered for each one (diagnostic channels, in-tree facts, existing reads of undeclared contracts, etc.).
The union of the two categories must exactly equal all fields in the structure. The following three locations must match verbatim:
- The
INVENTORYinsrc/driver/obligations.rs; - The
TypeCheckResultfield definitions insrc/frontend/core/sema/types.rs; - The §Obligation Fields table in this document (whose header declares the count).
scripts/ci/check-obligations.py performs bidirectional reconciliation: adding a field without registering it, removing a field without synchronizing it, or any drift between the table and the code causes an immediate failure. The criteria are anchored to the field set and actual reads, not to line numbers.
Delivery and Settlement
Obligations are delivered at the producer (deliver) and read at the consumer. Driver::run calls assert_drained once at the end of the stage table. The following cases pass:
- There are no obligations.
- The consumer stage is not in this
ProgramKind’s stage table. - The consumer stage was skipped (
UpstreamFailed/ConfigDisabled). - The obligations have been delivered, and the consumption ledger contains no unconsumed keys.
All other cases produce W1090, emitted at Severity::Error. The code remains in the W family: the same fact must not be assigned two codes, and the severity is explicitly specified at the settlement point.
ReleasePlan and overload_resolutions also carry a consumption ledger (ConsumptionLedger). It is keyed by PlanId (the structural identity of a statement/call site), and retrieving an entry records it as consumed; if any unconsumed keys remain after a compilation run, W1090 is produced. The audit surface DriverOutcome.obligations provides settlement details on every run.
Obligation Fields: 16 “Production-as-Contract” Fields
| Field | Producer → Consumer |
|---|---|
proof_calls | typecheck → ProofExecution |
release_plan | ownership → IrGeneration (PlanId-keyed) |
escaped_refs | ownership → IrGeneration |
instantiation_requests | typecheck → Monomorphization |
existential_coercions | typecheck → IrGeneration |
implementation_proofs | typecheck → IrGeneration |
sum_types | typecheck → IrGeneration |
sum_type_param_names | typecheck → IrGeneration |
operator_dispatches | typecheck → IrGeneration (span-keyed) |
overload_resolutions | typecheck → IrGeneration (PlanId-keyed) |
try_expr_impls | typecheck → IrGeneration (span-keyed) |
match_scrutinee_types | typecheck → IrGeneration (span-keyed) |
module_namespaces | typecheck → IrGeneration |
record_models | typecheck → IrGeneration (quantifier propagation) |
type_identity_by_local_key | typecheck → lower (written name → type identity) |
expr_result_types | typecheck → IrGeneration (PlanId-keyed) |
Non-Obligation Fields
| Field | Why It Is Not a Cross-Stage Obligation |
|---|---|
module_name | Compilation-unit identity metadata; zero hits in src/middle |
diagnostics | Error diagnostic channel; not a “production-as-contract” field |
bindings | Read across stages, but no contract is declared |
local_var_types | Local type table used for diagnostic rendering |
semantic_db | Consumed by the LSP and exported through DriverOutcome.semantic_db |
trait_table | Cross-stage reads exist, but the documentation declares no contract |
warnings | Warning diagnostic channel |
method_def_ir_names | Per-declaration mapping; a miss produces E3005, with no silent path |
interface_impl_registry | In-tree fact, consumed within the phase |
type_identity_index | Identity-index snapshot with no cross-stage consumers in production |
Diagnostics and Exit Codes
- Error diagnostics come from the
Diagnosticcollections of each stage and are aggregated bydriver/diagnostics.rs. Aggregation::FailFast: The first error immediately aborts subsequent stages;CollectAll: All errors are collected before deciding what to do.- Exit codes are determined by diagnostic severity: the presence of
Severity::Errorproduces a nonzero exit code;W1090has error severity and counts toward the error total when triggered. - Warnings do not change the exit code, but they are included in the diagnostic surface of LSP /
check.
Extension Checklist
- For a new concept, first prove that it cannot be expressed using existing concepts + parameters (coding-rules prohibition one).
- The same behavior must not have a second implementation or a second set of synonymous tables; when parallel representations already exist, converge them before adding functionality.
- When adding a cross-layer data flow, ask “Who produces it, who consumes it, and at which layer is it consumed?”; if it is produced without a consumer, it is an obligation or a dead field.
- Before changing a table (error codes/opcodes/types/stages), first write down the authoritative source module name; if you cannot, you have not done the research.
- Add new tests according to test-specification; when changing IR/corpus behavior, update the baseline in the same commit.
- Documentation should state only current facts; leave design rationale and rejected alternatives in commit messages or discussions.
