Skip to content

IR and Equivalence Criteria ​

This document describes L3's IR/SSA structure, validation, and snapshots, as well as how a change proves that it has not broken existing behavior. For type representations, see 02-frontend.md; for layering and stages, see 01-architecture.md.

Structure ​

src/middle/ir/ir.rs defines:

  • ModuleIR: function table, module initialization sequence, type table, etc.
  • FunctionIR: name, binding identity def: Option<DefId>, params, return_type, generic_params, body.
  • FunctionBody:
    • Code { blocks, entry, locals, values, value_slots }—ordinary function body;
    • TypeDecl { body: TypeDeclBody }—type declaration body, retaining only the field table, field types, and type table entries consumed by the IR.
  • BasicBlock: linear instruction sequence + terminating instruction.
  • Instruction: IR instruction; operands are Operand.
  • Operand: Const(ConstValue) / Value(ValueId) / Local(usize) / Arg(usize) / Global(usize); the values and value_slots tables use the same ValueId indexing.

IR type annotations may only use the resolved subset of MonoType (TypeVar, MetaType, Literal, and ConstExpr must not appear; see 02-frontend).

SSA Discipline ​

verify (src/middle/ir/verify.rs) checks by pattern:

InvariantDescription
Single definitionEach ValueId is defined only once; Phi does not count as a duplicate ordinary definition
DominanceA definition at a use site must dominate that use site; every predecessor of a Phi must have a corresponding incoming edge
Predecessor consistencyThe number of incoming edges for a Phi equals the number of predecessors, and they come from the correct basic blocks
Jump targetsBranch/jump targets must be existing blocks or labels
Slot boundsSlot numbers must be within the function frame; exceeding the limit is an error rather than a truncation
Type consistencyInstruction operands and result types must agree with the MonoType annotations
Inner isolationTypeDecl and code bodies, and closure environment slots and function parameter slots, must not contaminate one another

Two entry points:

  • verify_loose: must pass on existing IR; a failure means the IR depends on writing the same slot multiple times, so the defect must be fixed first.
  • verify_ssa: strict SSA mode, requiring single definitions and dominance.

The validator is integrated into CI and covers the entire corpus; new instructions or IR shapes must also be covered by validation.

Snapshots ​

src/middle/ir/tests/snapshots/ stores normalized IR snapshots. Normalization rules (normalize.rs):

  • Strip Span;
  • Rename temporary values in order of appearance;
  • Relativize global slots;
  • Sort predecessors stably.

Snapshots are committed to the repository; updates require manual review of the diff. Snapshots are used only for equivalence criteria C1/C4 and are not runtime inputs.

Lowering Boundaries ​

  • The only construction path from AST → IR is src/middle/lower/ (module_ir.rs / expr/ / stmt.rs / scope.rs, etc.). Other modules under middle/ must not construct IR directly from the AST.
  • src/middle/lower/synth.rs is the only place in L3 production code permitted to construct ast::Expr / ast::Stmt / ast::Type; the boundary between synthesized and real ASTs is explicit, and implicit callbacks must not bypass it.
  • Call-expression generation has already been split by responsibility; new branches should be placed in the corresponding phase of expr/call.rs, rather than piling logic back into a single function.
  • Type information for local lambda bindings and returned closures is completed once within lowering; downstream stages must not infer closure body types again.

Register Allocation ​

src/middle/lower/regalloc.rs implements linear-scan allocation:

  • The inputs are SSA values and live intervals; the outputs are value_slots and frame slots;
  • codegen only reads value_slots and does not perform allocation itself;
  • After allocation, the slot limit must be satisfied; if everything does not fit, report E3014 (with the function body span), and do not silently truncate;
  • Statement-level reclamation has been removed; reclamation is handled uniformly by the allocator and RAII.

Bytecode Format ​

src/middle/bytecode/file.rs:

  • VERSION = 5; function records carry upvalue_count and globals.
  • The reader validates by version; cross-version compatibility is not a goal.
  • No exception table is written: TRY_BEGIN / TRY_END / THROW are undefined, and the language has no throw/try/catch.
  • The debug section has an independent version; a missing debug section is treated as empty.

Equivalence Criteria ​

CategoryChangeCriterion
C1Pure relocation (splitting files, changing directories, extracting submodules)Zero diff in normalized IR snapshots
C2Orchestration changes (staging, unified Driver)Same diagnostic set at each entry point + same corpus behavior
C3Type-representation convergenceSame diagnostic codes and messages (order may be normalized)
C4IR shape changes (SSA conversion)Behavioral equivalence + IR structural invariants
C5Frontend paradigm changesAST snapshot + diagnostic code/span + behavior, all three used
C6Pure deletionConfirm that there are no references; no equivalence criterion applies

Criteria are selected according to the layer actually touched by a change, not its size. When a change spans multiple layers, take the union of the applicable criteria.

Three-Layer Criteria ​

  1. IR static validator (src/middle/ir/verify.rs)

    • verify_loose: must pass on existing IR, with no exemptions.
    • verify_ssa: strict SSA mode.
    • Checks: single definitions, dominance, Phi predecessor consistency, jump targets, slot bounds, type consistency, and inner isolation.
  2. Normalized IR snapshots (src/middle/ir/tests/snapshots/)

    • Normalization: strip Span, rename temporary values in order of appearance, relativize global slots, and sort predecessors.
    • Snapshots are committed to the repository; updates require manual review of the diff.
  3. End-to-end corpus diff (tests/baselines/corpus-parity.jsonl)

    • Compare diagnostic lists, exit codes, stdout, and stderr item by item.
    • Covers single-file and multi-file corpora; new corpus cases must be added to the baseline.

Semantic Correction Routing ​

Equivalence criteria only prove that “behavior remains unchanged.” When behavior needs to be changed, use semantic correction routing; the entry criterion is “whether the old behavior is consistent with the written provisions,” not “whether the compiler previously accepted it.”

A/B/C categories may be corrected along with a change, and all five requirements are indispensable:

  1. A failing criterion must exist first and must currently genuinely fail.
  2. Programs that originally complied with the specification must behave identically externally (diagnostic codes, wording, exit codes); paths that originally violated the specification failing or becoming more explicit is the correction itself.
  3. Correct the affected body text in place in the same commit (the body describes only the current state), and annotate it on the PR's “Error Type” line.
  4. Regenerate the baseline in the same commit and manually review the diff.
  5. The commit message and PR must state the RFC/SPEC section number and the minimal counterexample for the behavior.

D/E/F categories—D user-visible semantics, E external contract tables, and F RFC-level design changes—must first go through user adjudication. If the specification is silent or ambiguous, always fall back to D/E/F; “I think it is more correct” is not an entry criterion.

Categorize a change by its primary error type; list incidental behavior changes within the same root cause separately on the PR's “D3 patch determination” line.

Regression Gates ​

GatePurpose
verify_loose / verify_ssaIR structure and SSA invariants
Snapshot comparisonZero drift in IR text
Corpus diffZero drift in diagnostics/exit codes/stdout/stderr
Direct-drive testsEvery mechanism's producer and consumer are exercised through real entry points
check-obligations.pyObligation-field delivery matches actual consumption

Baseline regeneration commands:

bash
UPDATE_SNAPSHOTS=1 cargo test --lib snapshot -- --ignored
cargo run --quiet --example corpus_probe > tests/baselines/corpus-parity.jsonl

Baseline changes must be committed in the same commit; what gets reviewed is the diff, not the fact that “the gate is green.”

Two Disciplines ​

  • Criteria before refactoring: establish a failing criterion first, then change the implementation; “green followed by red” cannot distinguish a fix from a regression.
  • Do not relax criteria to get a green light: a failing criterion indicates an implementation defect and must be reported truthfully; do not delete tests, add allowlists, or grant exemptions. If it cannot be done, then it cannot be done.