Skip to content

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 ​

RuleCheck
Dependencies may only point downward: L1 → L2/L3/L4, L2 → data domain, L3 → data domain, and L4 is independentscripts/ci/check-boundary.py
L2 (lexer/parser) must not use L3/L4check-boundary.py B2
L3/L4 must not use L2’s lexer/parsercheck-boundary.py B3
include! is prohibitedcheck-boundary.py B1
Opcode constants may only be defined in src/middle/bytecode/opcode.rscheck-boundary.py B5
Peripheral tools (formatter / lsp / repl / package / util) may only consume the pub APIs of L1–L4check-boundary.py
Cross-layer pub(crate) leakage may only decrease, never increasecheck-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 ​

DirectoryResponsibilityExcluded
src/ast/Sole carrier of the AST and syntactic types; constructed by L2 and consumed by L3Type checking, evaluation, IR
src/driver/L1: Stage / Program / Driver / obligation settlement / diagnostic aggregationConcrete language semantics
src/frontend/core/lexer/Lexing: tokens, literals, spansSyntactic structures, types
src/frontend/core/parser/Syntax: Pratt expressions, statements/declarations, error recovery, Type syntaxType checking, name resolution
src/frontend/core/types/Working representation of MonoType, substitution/solving, constant evaluation, type tablesParser/AST construction
src/frontend/core/sema/Type checking, inference, checkers, refinement/termination/ownership layers, proofsIR construction
src/frontend/module/Module discovery, registries, role classification, import/export resolutionType semantics
src/middle/ir/SSA IR definitions, validators, snapshotsAST semantics
src/middle/lower/Sole construction path from AST to ModuleIRType checking
src/middle/passes/Monomorphization, DCE, codegenIR definitions
src/middle/bytecode/Bytecode format, opcode tables, .42 serializationExecution strategy
src/backends/Interpreter, runtime, FFICompile-time semantics
src/std/Standard library source and interface tablesCompiler internal representations
src/util/Diagnostic code tables, diagnostic emission, logging, and other shared infrastructureCompilation-stage logic
src/lsp/, src/formatter/, src/repl/, src/package/Peripheral toolsCompilation-stage implementations
tools/Standalone gate/generation tools (type-tables, code-tables, etc.)Compiler runtime

Feature Routing Table ​

Item to Add/ChangePrimary Change SiteRelated ChangesCriteria
An operator or precedence levelSingle table in parser/pratt/precedence.rsLexer token, ast::BinOp, SPEC, parser/tests/associativity.rsC5 (snapshot + diagnostics + behavior)
A literal kindlexer/literals.rs and tokenParser consumption sites, diagnostic codes, corpusC5
A syntactic constructparser/statements/ or pratt/ast node, sema consumer, formatter, LSP syntax treeC5
A type formast::Type + parser type syntaxtypes/mono.rs (→ MonoType), sema, 02-frontendC3 or C5
A type-checking rulesema/inference/ or sema/checker/MonoType, diagnostic codes, direct-drive testsC3/C4
A diagnostic codesrc/util/diagnostic/codes/locales/*.json, RFC-013, generated pages, test assertionsPer RFC-013
A compilation stage or stage orderingdriver/stage.rs + driver/arms.rsExhaustive Driver match, obligation ledger, this document’s §Obligation LedgerC2
A cross-stage obligationTypeCheckResult + driver/obligations.rs + this document’s §Obligation FieldsDelivery point in driver/arms.rs, consumption point, check-obligations.pyC2
An IR instruction/structuremiddle/ir/ir.rslower, codegen, verify, snapshotsC4
A bytecode format fieldmiddle/bytecode/file.rscodegen, interpreter, .42 versionC4
A standard library functionsrc/std/ source + std/yx_sources.rsInterface table, documentation, corpusBehavior tests
An LSP capabilitysrc/lsp/DriverOutcome.semantic_db, this document’s §Stage ModelDirect-drive tests
A gate/generatorscripts/ci/ or tools/CI, criteria wording in this document and 03-ir-and-criteriaGate 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:

text
VendorConsistency → Discovery → Parsing → Registry → RoleClassification
→ Typecheck → DeadCodeAnalysis → ProofExecution → GlobalSlotAlloc
→ IrGeneration → Linking → Monomorphization

StageScope declares the execution granularity of each stage:

  • PerModule: Executed once per compilation unit.
  • Project: Executed once per project; dispatch structurally 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:

ProgramKindUse
SingleFileSingle-file run
MultiFileMulti-file project run
Checkyaoxiang check (diagnostics only; no execution)
LspCompilation for LSP requests
EmbeddedInternal compilation, such as embedded std
WasmPlaygroundWASM 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:

  1. Cross-stage obligation fields: The producer must deliver them, and the consumer must read them.
  2. 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 INVENTORY in src/driver/obligations.rs;
  • The TypeCheckResult field definitions in src/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 ​

FieldProducer → Consumer
proof_callstypecheck → ProofExecution
release_planownership → IrGeneration (PlanId-keyed)
escaped_refsownership → IrGeneration
instantiation_requeststypecheck → Monomorphization
existential_coercionstypecheck → IrGeneration
implementation_proofstypecheck → IrGeneration
sum_typestypecheck → IrGeneration
sum_type_param_namestypecheck → IrGeneration
operator_dispatchestypecheck → IrGeneration (span-keyed)
overload_resolutionstypecheck → IrGeneration (PlanId-keyed)
try_expr_implstypecheck → IrGeneration (span-keyed)
match_scrutinee_typestypecheck → IrGeneration (span-keyed)
module_namespacestypecheck → IrGeneration
record_modelstypecheck → IrGeneration (quantifier propagation)
type_identity_by_local_keytypecheck → lower (written name → type identity)
expr_result_typestypecheck → IrGeneration (PlanId-keyed)

Non-Obligation Fields ​

FieldWhy It Is Not a Cross-Stage Obligation
module_nameCompilation-unit identity metadata; zero hits in src/middle
diagnosticsError diagnostic channel; not a “production-as-contract” field
bindingsRead across stages, but no contract is declared
local_var_typesLocal type table used for diagnostic rendering
semantic_dbConsumed by the LSP and exported through DriverOutcome.semantic_db
trait_tableCross-stage reads exist, but the documentation declares no contract
warningsWarning diagnostic channel
method_def_ir_namesPer-declaration mapping; a miss produces E3005, with no silent path
interface_impl_registryIn-tree fact, consumed within the phase
type_identity_indexIdentity-index snapshot with no cross-stage consumers in production

Diagnostics and Exit Codes ​

  • Error diagnostics come from the Diagnostic collections of each stage and are aggregated by driver/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::Error produces a nonzero exit code; W1090 has 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.