diff --git a/INVARIANTS.md b/INVARIANTS.md index 9bc6035031c..a5110956c5e 100644 --- a/INVARIANTS.md +++ b/INVARIANTS.md @@ -2117,6 +2117,70 @@ Rust uses `Rc`, Go uses `*T`, Python has reference semantics by default. This is ONE cross-language fact with per-language syntax — not three independent implementations in three emitters. +### E-5: Clean-emission contract is satisfied by construction (2026-04-17) + +For every target T and program P, the emission pipeline produces +source code that passes T's declared clean-code verifier without +modification. The verifier is named in the target's +`CleanEmissionContract.post_emit_verifier` (e.g., `rustc --edition=2021 +-D warnings` for Rust). A diagnostic from the verifier is an emission +bug, not a formatting difference — the fix is structural, not +suppression. + +**What "no escape hatches" means.** The contract GROWS by adding +typed rules to `CleanEmissionContract` when new warning categories +surface. It does NOT grow by adding `#[allow(...)]` / `# noqa` / +pragma suppression. E-5's commitment is to CONSTRUCTIVE emission — +"we've covered every category by SHAPE, not by silencing" — so new +targets that surface new warnings (Kotlin's null-safety lints, +Verilog's unused-regs, etc.) land as new typed rules, not as new +suppressed categories. Every rule's dispatch in the emitter removes +(or narrows) a corresponding entry from the test-wrapper +`#[allow(...)]` umbrella; umbrellas only shrink. + +**The contract.** Eight rules cover the warning classes currently +observed. See `docs/design-clean-emission-contract.md` (DB-4) for +the full type table and +`src/v3/std/clean_emission.dag` for the declarations. + +| Rule | Concern (rustc lint) | +|---|---| +| `expression_wrapping` | `unused_parens` on wrapped expressions | +| `pattern_bindings` | `unused_variables` in match arm payloads | +| `imports` | `unused_imports` | +| `block_return` | `unused_parens` around block terminal value | +| `variable_bindings` | `unused_variables` at let bindings | +| `match_arm_body` | `unused_parens` around match arm body | +| `correction_style` | surface-level fix rendering (DB-1) | +| `post_emit_verifier` | declared verifier command + args | + +**Why in INVARIANTS.md.** Once E-5 lands, every emitter change must +justify compliance. A future emitter PR adding a new warning +category without either (a) structurally fixing the cause or (b) +adding a typed rule to the contract is an E-5 violation. The +invariant is the mechanism that prevents "ship now, allow-suppress +later, forget forever." + +**Staged rollout (Lane 1 Stage 1c).** E-5 is declared structurally +(rule type system + per-target contract + invariant entry) at the +same time as the first pilot rule (Rust's `PatternBindingRule:: +EmitUnderscoreWhenUnused`). Remaining rule dispatches land in +Stage 1c PR 2 (Go + Python pilots) and Stage 1d/1e (consolidation +sweep for parens, imports, etc.). Each PR that wires a new rule +removes the matching lint from the test-wrapper allow umbrella. + +**Structural prevention:** the rule dispatch lives inside the +emitter. Emitted text is derived from `contract.` by match, +not by string rewrites over already-emitted source. + +**Test:** each rule's dispatch ships with at least one pilot test +that compiles the emitted code under `#[deny()]` and +asserts compilation succeeds. + +**Origin:** DB-4 + Lane 1 Stage 1c. Replaces the band-aid +`#[allow(warnings)]` approach that accumulated around emitted +wrapper modules through M1. + ### E-6: No target-spec field without a same-PR consumer (2026-04-16) A field declared on a target spec (`CallableRealization`, diff --git a/docs/design-clean-emission-contract.md b/docs/design-clean-emission-contract.md index bb92d3fb183..40c4ddd9c6b 100644 --- a/docs/design-clean-emission-contract.md +++ b/docs/design-clean-emission-contract.md @@ -164,13 +164,22 @@ type PostEmitVerifier { command: String // e.g., "rustc", "gofmt", "black", "verilator" args: List // e.g., ["--edition=2021", "-D", "warnings"] syntax_only: Bool // if true, only syntax-check (don't compile) - expected_exit_code: Int // 0 for pass; some verifiers use 1 for "diffs found" + expected_exit_code: Int // expected process status for the clean case + output_policy: VerifierOutputPolicy } ``` -Rust: `{ command: "rustc", args: ["--edition=2021", "-D", "warnings"], syntax_only: false, expected_exit_code: 0 }`. -Go: `{ command: "gofmt", args: ["-l"], syntax_only: true, expected_exit_code: 0 }` (exit 0 + empty stdout = clean). -Python: `{ command: "python3", args: ["-m", "py_compile"], syntax_only: true, expected_exit_code: 0 }`. +```dag +type VerifierOutputPolicy + = IgnoreVerifierOutput + | RequireEmptyStdout + | RequireEmptyStderr + | RequireEmptyStdoutAndStderr +``` + +Rust: `{ command: "rustc", args: ["--edition=2021", "-D", "warnings"], syntax_only: false, expected_exit_code: 0, output_policy: IgnoreVerifierOutput }`. +Go: `{ command: "gofmt", args: ["-l"], syntax_only: true, expected_exit_code: 0, output_policy: RequireEmptyStdout }`. +Python: `{ command: "python3", args: ["-m", "py_compile"], syntax_only: true, expected_exit_code: 0, output_policy: IgnoreVerifierOutput }`. Additional Shape A targets (Swift, Kotlin, etc.) declare their own `post_emit_verifier`. **Shape B formats** (SPICE, Verilog, English, YAML) are NOT compiler targets per THESIS.md §"Two shapes of omni-emission" — they're produced by `.dag` programs, not emitted by the compiler. ### Per-target declarations @@ -192,6 +201,7 @@ data rust_clean_emission: CleanEmissionContract = { args: ["--edition=2021", "-D", "warnings"] syntax_only: false expected_exit_code: 0 + output_policy: IgnoreVerifierOutput } } ``` @@ -284,6 +294,17 @@ fn run_post_emit_verifier(emitted_source: &str, contract: &CleanEmissionContract stderr: String::from_utf8_lossy(&output.stderr).into(), }); } + match contract.post_emit_verifier.output_policy { + IgnoreVerifierOutput => {} + RequireEmptyStdout if !output.stdout.is_empty() => return Err(...), + RequireEmptyStderr if !output.stderr.is_empty() => return Err(...), + RequireEmptyStdoutAndStderr + if !output.stdout.is_empty() || !output.stderr.is_empty() => + { + return Err(...); + } + _ => {} + } Ok(()) } ``` diff --git a/docs/phase1-lane2-clean-emission-invariant.md b/docs/phase1-lane2-clean-emission-invariant.md index 4e20410dd4a..38be394a6fe 100644 --- a/docs/phase1-lane2-clean-emission-invariant.md +++ b/docs/phase1-lane2-clean-emission-invariant.md @@ -4,8 +4,8 @@ **Lane:** 1 (Emission unification) **Stage:** 1c (after substrate keyed-lookup; before consolidation build plan) -**Size:** M -**Status:** Plan. No code changes yet. +**Size:** M (split across PRs — see §2 Scope split) +**Status:** In progress. PR 1 (Rust pilot + contract type system) in flight. > Role in the plan: establishes E-5 invariant (warnings-by-construction) > as the contract that Stage 1e's consolidation dispatches on. The @@ -42,12 +42,15 @@ the pilot implementation that proves the shape. ## Scope -Three deliverables, plus evaluation of three candidate invariants from Half B audit (see bottom of this doc): +Three deliverables. ### 1. Design doc: the invariant -Output: this file's successor becomes authoritative (`docs/clean-emission-invariant.md`), -plus an `INVARIANTS.md` entry. +Output: this file plus an `INVARIANTS.md` E-5 entry. Concrete contract +shape is pinned in [`design-clean-emission-contract.md`](./design-clean-emission-contract.md) +(DB-4) and is load-bearing for this stage — the 8-rule contract shape +below is authoritative; any drift between this sketch and DB-4 gets +reconciled against DB-4. **The invariant (E-5):** > For every target T and program P, the emission pipeline produces @@ -63,7 +66,8 @@ plus an `INVARIANTS.md` entry. > category" — new targets will surface new categories, and each > lands as a structural rule, not a silenced warning. -Per-target spec extension: +Per-target spec extension (DB-4 carries the full 8-rule field set; +this sketch names the fields, not their rule-variant dispatch): ``` // in spec/rust.dag (analogous for go.dag, python.dag, etc.) @@ -71,27 +75,30 @@ data rust_clean_emission: CleanEmissionContract = { expression_wrapping: WrapOnlyInOperandPosition pattern_bindings: EmitUnderscoreWhenUnused imports: IncludeOnlyReferenced - block_return: NoRedundantWrapping + block_return: NoWrappingOnTerminalExpression + variable_bindings: EmitUnderscoreWhenUnused + match_arm_body: NoWrappingOnNonComplexBody + correction_style: rust_correction_style post_emit_verifier: { command: "rustc" - args: ["--edition=2021", "-D", "warnings", "..."] + args: ["--edition=2021", "-D", "warnings"] + syntax_only: false + expected_exit_code: 0 + output_policy: IgnoreVerifierOutput } } +``` -type CleanEmissionContract { - expression_wrapping: ExpressionWrappingRule - pattern_bindings: PatternBindingRule - imports: ImportRule - block_return: BlockReturnRule - post_emit_verifier: PostEmitVerifier -} +`CleanEmissionContract` itself (8 fields) and the per-rule coproducts +(closed enums with `NotApplicable` variants where relevant) live in +`std/clean_emission.dag`. See DB-4 for the complete type table. -type ExpressionWrappingRule - = WrapEverything // current behavior — rejected - | WrapOnlyInOperandPosition // correct -``` +**Explicitly out of the E-5 surface:** emitted-struct dead-code. +Removed from DB-4 per codex feedback on PR #491 — that's a +publicity/visibility concern, not a clean-emission one. E-5 covers +constructive rendering rules only. -### 2. Pilot implementation: unused pattern bindings +### 2. Pilot implementation: unused pattern bindings (Rust first) Pick **one** clean-code rule and solve it structurally end-to-end. Choice: `pattern_bindings: EmitUnderscoreWhenUnused`. @@ -102,41 +109,68 @@ Choice: `pattern_bindings: EmitUnderscoreWhenUnused`. - No test wrapper changes (imports do) - Clean test: pattern match arms with unused bindings must emit `_` -**Implementation sketch:** -1. Add `CleanEmissionContract` type in `src/v3/spec/clean_emission.dag` (new file) -2. Add `pattern_bindings` field to each target's spec (`rust.dag`, `go.dag`, `python.dag`) -3. In `emit_rust.rs` `render_branch_pattern`: - - Walk the arm body to collect referenced PortIds - - For each payload binding in the pattern: emit `_` if its port is - not in the referenced set, else emit the binding name -4. In `emit_go.rs` / `emit_python.rs`: analogous using Go's `_` and - Python's `_var_name` conventions per each target's rule -5. Add a `render_locals_analysis` helper (target-agnostic) that - computes the referenced-ports set for a body — this is the - "port liveness" primitive P2 will also consume - -### 3. CI gate: post_emit_verifier as a hard check +**Scope split across PRs.** The stage originally sketched "all three +current targets (Rust/Go/Python) in one sweep." Practical scope split: + +- **PR 1 (this PR):** Rust pilot — `std/clean_emission.dag` type + system; `rust_clean_emission` data item in `spec/rust.dag`; + `render_branch_pattern` dispatch; targeted test under + `#[deny(unused_variables)]` proving the rule fires; E-5 entry in + `INVARIANTS.md`. +- **PR 2 (follow-up):** Go + Python pilots — `go_clean_emission` / + `python_clean_emission` data items and per-emitter dispatch. + Deferred because Go's binding surface is `{x} := {expr};` (blank + identifier path) and Python's pattern-bind doesn't emit the binding + as part of the pattern at all — two distinct structural proofs, + separate from Rust's `render_branch_pattern` path. E-6 holds in PR 1 + because each target's spec item lands only when its emitter + consumer lands. +- **PR 3 (follow-up):** Wire `post_emit_verifier` into the test + harness (rustc `-D warnings` hard gate, test-wrapper + `#[allow(unused_variables)]` strike). Deferred because the test + harness change is a distinct chunk that doesn't gate correctness + of the rule dispatch. + +**Implementation sketch (PR 1):** +1. `std/clean_emission.dag` — new file; declares + `CleanEmissionContract` (8 fields per DB-4) and the coproduct + rule types. +2. `spec/rust.dag` — adds `rust_clean_emission` data item with + concrete rule variants. +3. `dag.rs` — caches `rust_clean_emission` in `TargetSyntaxCache` + (name-lookup at bootstrap end, same pattern as `rust_rendering`). +4. `emit_rust.rs` — parses `CleanEmissionContract` into a typed + binding; `render_branch_pattern` dispatches on + `contract.pattern_bindings`. Port-liveness walk answers "is the + binding's payload_port consumed by anything reachable from + `path.output`?" — if not, emit `_`; else emit the binding name. +5. Targeted test — `#[deny(unused_variables)]` on a single fixture + containing a match arm whose payload binding is unused; asserts + compilation succeeds (i.e. emission produced `_`). + +### 3. CI gate: post_emit_verifier as a hard check (follow-up PR) Each emitter test suite adds a step: after emission, invoke the target's -declared `post_emit_verifier`. If it reports any diagnostic (warning or -error), the test fails. +declared `post_emit_verifier` and apply its `output_policy`. If it +reports any diagnostic or output shape the contract marks as failure, +the test fails. **Today's rustc roundtrip tests do this partially** — they invoke rustc -but without `-D warnings`. After L2, `-D warnings` is declared IN THE -SPEC and the test harness reads it from there. +but without `-D warnings`. After Stage 1c's follow-up PR, `-D warnings` +is declared IN THE SPEC and the test harness reads it from there. **Transition plan:** -- Keep `#[allow(warnings)]` attributes in emitted modules during this - lane's pilot implementation -- As each warning category is structurally fixed, remove the - corresponding lint from the allow list -- When the pilot (unused pattern bindings) ships: remove - `unused_variables` from the allow list -- P2 consolidates the remaining categories (parens, imports, etc.) +- Keep `#[allow(warnings)]` attributes in emitted modules during PR 1 + (pilot proves contract dispatch via a narrow `#[deny(unused_variables)]` + test, not by stripping the umbrella allow). +- PR 3 strikes `unused_variables` from the test-wrapper allow list + (once Rust + Go + Python all dispatch the rule). +- Lane 1d/1e consolidates the remaining categories (parens, imports, + etc.) and strikes those as they land. **Do NOT attempt to fix all four warning categories in this lane.** The pilot validates the contract shape. The rest are structural work that -folds into P2's emitter consolidation. +folds into Lane 1d/1e's emitter consolidation. --- @@ -200,21 +234,58 @@ Stop work and surface if: ## Acceptance gates -Lane is done when all four hold: - -- `docs/clean-emission-invariant.md` exists with the E-5 invariant, - `CleanEmissionContract` type definition, per-target rule table, and - the "reject post-emission cleanup" rationale. -- `INVARIANTS.md` has an E-5 entry referencing the design doc. -- `spec/clean_emission.dag` (or equivalent) declares the contract - type; each of `spec/rust.dag`, `spec/go.dag`, `spec/python.dag` has - a populated `clean_emission` field. -- The unused-pattern-binding rule fires end-to-end: a test program - with `match x { Value(v) => 0, ... }` produces Rust with - `Behavior::Value(_) => 0` (not `Value(v)`), and `unused_variables` - is removed from the test-wrapper allow list for that specific case. -- Zero new `#[allow(...)]` attributes added anywhere in the codebase - during this lane. +Stage 1c is done when the following hold across its PRs. + +**PR 1 (Rust pilot + contract type system) — gates:** + +- DB-4 (`docs/design-clean-emission-contract.md`) exists with the + E-5 invariant framing, the 8-rule `CleanEmissionContract` type + table, per-target rule choices, and the "reject post-emission + cleanup" rationale. (Already landed; referenced here.) +- `INVARIANTS.md` has an E-5 entry referencing DB-4 and this stage + doc. +- `std/clean_emission.dag` declares the 8-rule contract type plus + each rule's coproduct (with `NotApplicable` variants where + relevant). +- `spec/rust.dag` declares `rust_clean_emission: CleanEmissionContract` + populated with concrete rule variants per DB-4. +- `dag.rs` caches `rust_clean_emission` in `TargetSyntaxCache` with + an accessor on `Dag`. +- `emit_rust.rs` parses the contract into a typed binding and + dispatches `PatternBindingRule::EmitUnderscoreWhenUnused` in + `render_branch_pattern`. Port-liveness walk determines binding use. +- A targeted test under `#[deny(unused_variables)]` compiles a + match-with-unused-payload and asserts rustc accepts the emitted + code (i.e. the pilot emits `_` and no unused-variable warning + fires). +- Zero new `#[allow(...)]` attributes added in this PR. + +**PR 2 (Go + Python pilots) — gates:** + +- `spec/go.dag` / `spec/python.dag` each declare their + `*_clean_emission` data item. +- `emit_go.rs` / `emit_python.rs` each dispatch their + `pattern_bindings` rule. Per-target surface: Go emits `_` for the + blank-identifier path; Python dispatches + `EmitPrefixedUnderscoreWhenUnused` (`_v` convention). +- Targeted tests per target mirror the Rust pilot. + +**PR 3 (post_emit_verifier CI gate) — gates:** + +- Test harness reads `post_emit_verifier` from each target's + contract and invokes it with its verdict policy (Rust: rustc + with `-D warnings` + `IgnoreVerifierOutput`; Go: `gofmt -l` + + `RequireEmptyStdout`; Python: py_compile + + `IgnoreVerifierOutput`). +- `unused_variables` removed from each test-wrapper + `#[allow(warnings, clippy::all)]` umbrella (replaced with an + explicit residual list naming only the not-yet-structurally-fixed + categories). +- CI fails on any warning diagnostic the verifier emits. + +**Cross-stage gate:** zero new `#[allow(...)]` attributes added +anywhere during Stage 1c. Existing umbrella allow lists narrow +monotonically as each rule lands. --- @@ -260,31 +331,22 @@ designing toward. --- -## Candidate companion invariants (E-6, E-7, E-8) - -Half B's principle audit proposed three additional invariants that -predate Lane 1e consolidation. Evaluate for INVARIANTS.md inclusion -alongside E-5: - -**E-6 — No target-spec field lands without a same-PR consumer.** If -`rust_foo: FooType` is added to `src/v3/spec/rust.dag`, the emitter -change that CONSUMES `rust_foo` lands in the same PR. Prevents -"declared-facts-not-wired" drift (the pattern that produced B-NEW-2 -and B-NEW-3 as Half B follow-up commits). - -**E-7 — No target-private realization schema lands without a -dissolution ratchet.** If a target-specific type (e.g., -`PythonPatternRealization`) is added, the PR lists the path to -dissolve it into a target-agnostic substrate fact. Permanent -per-target types are allowed with explicit receipt. - -**E-8 — Unsupported core behaviors fail closed; never collapse -semantically.** When an emitter encounters a core Behavior variant -it doesn't support, it returns `EmitError::UnsupportedBehavior` — -not a semantic approximation (like rendering `Loop` as its body's -result port). Half B just enforced this for Loop in emit_go / -emit_python. - -Lane 1c evaluates these alongside E-5. Each has a mechanical gate -path (grep / PR-review-checklist / test-based). Adoption -individually decided; the three form a coherent set with E-5. +## Companion invariants (historical — already landed) + +Half B proposed three emission-discipline invariants that were +originally listed here as "candidates to evaluate alongside E-5." +All three landed in `INVARIANTS.md` ahead of this stage: + +- **E-6** — No target-spec field lands without a same-PR consumer. + (PR #493, 2026-04-16.) +- **E-7** — No target-private realization schema lands without a + dissolution ratchet. (PR #493, 2026-04-16.) +- **E-8** — Unsupported core behaviors fail closed; never collapse + semantically. (PR #493, 2026-04-16.) + +**E-9** — External realization lives on `Arrow.body` — landed in +PR #497, 2026-04-17. + +This section is retained as a pointer so readers of the original +stage doc know these invariants are load-bearing and already +enforced; Stage 1c does not re-evaluate them. diff --git a/src/v3/ROADMAP.md b/src/v3/ROADMAP.md index d57a9ca7a95..7f7a7dec8f0 100644 --- a/src/v3/ROADMAP.md +++ b/src/v3/ROADMAP.md @@ -485,6 +485,12 @@ Sub-stage status (as of 2026-04-17): **Deferral: 1b full implementation (M).** 1b's first attempt escalated (PR #495 shipped 1a; 1b code was reverted). Root cause: `.dag` linear-walk bodies for substrate accessors polluted every user DAG. DB-14 codifies the correct pattern (ExternalRealization mirroring pipeline.dag). Unblocked once DB-14 (PR #497) lands. Design: [design-substrate-external-primitives.md](../../docs/design-substrate-external-primitives.md) (DB-14). Acceptance in DB-14 §Acceptance. +### Lane 1 Stage 1c + +**Deferral: 1c Go + Python pilots (S).** Stage 1c PR 1 shipped the Rust pilot (`PatternBindingRule::EmitUnderscoreWhenUnused`), the `CleanEmissionContract` type system (8 rules in `src/v3/std/clean_emission.dag`), `rust_clean_emission` in `spec/rust.dag`, and E-5 in `INVARIANTS.md`. Remaining: add `go_clean_emission` / `python_clean_emission` data items and wire each emitter's `pattern_bindings` dispatch (Go: blank-identifier `_`; Python: prefixed `_v` convention). Separate PR because emit_go and emit_python render bindings on different surface (`{x} := {expr};` and implicit local respectively) — structurally distinct from Rust's `render_branch_pattern`. **Yellow-flag threshold: 1 week.** Design: [phase1-lane2-clean-emission-invariant.md §Scope split](../../docs/phase1-lane2-clean-emission-invariant.md). + +**Deferral: 1c post_emit_verifier CI gate (S).** Wire test harness to read the full `post_emit_verifier` contract (`args`, `expected_exit_code`, `output_policy`) from each target and invoke it as a hard gate (Rust: `rustc -D warnings` + `IgnoreVerifierOutput`; Go: `gofmt -l` + `RequireEmptyStdout`; Python: `python3 -m py_compile` + `IgnoreVerifierOutput`). Also narrow the test-wrapper `#[allow(warnings, clippy::all)]` umbrella to strike `unused_variables` once Rust + Go + Python pilots all dispatch the rule. Separate PR because the harness change is distinct infrastructure; correctness of rule dispatch is already proved by the pilot's `#[deny(unused_variables)]` test. **Yellow-flag threshold: 2 weeks.** Design: [phase1-lane2-clean-emission-invariant.md §Acceptance gates](../../docs/phase1-lane2-clean-emission-invariant.md). + ### Cross-cutting — performance **Deferral: self-compile perf ratchet investigation (M, not on any critical path but compounding).** Self-compile time drifted from ~60s to ~70s in recent cycles (~16% growth). The ratchet keeps getting bumped without a root-cause investigation; each bump normalizes the regression. Scope: (1) profile a single `cargo test -p v3-compiler-tests` run, identify the top hot paths; (2) measure where the 10s came from across recent PRs (bisect across #479, #489, #490 if signal is unclear); (3) either fix the regression or document it as an accepted cost with a new ratchet ceiling. **Yellow-flag threshold: 90s.** If self-compile exceeds that before this deferral is scheduled, it preempts other work. No design doc needed; profiling is a data-gathering exercise. diff --git a/src/v3/compiler/src/dag.rs b/src/v3/compiler/src/dag.rs index 0685b443b4f..4a46ded05f1 100644 --- a/src/v3/compiler/src/dag.rs +++ b/src/v3/compiler/src/dag.rs @@ -1068,6 +1068,13 @@ pub(crate) struct TargetSyntaxCache { /// authority the Rust emitter reads for borrow-vs-construct /// rendering policy at use sites. pub rust_rendering: Option, + /// `rust_clean_emission` CleanEmissionContract declaration + /// loaded from `src/v3/spec/rust.dag`. Lane 1 Stage 1c / E-5: + /// the emitter dispatches on this contract's rule fields to + /// shape emitted code so it passes `rustc -D warnings` by + /// construction. Go / Python cache analogues land when their + /// respective pilots do. + pub rust_clean_emission: Option, /// `rust_execution_model` declaration loaded from /// `src/v3/spec/rust.dag`. Used by emitters to gate the /// ownership stage on the target memory model. @@ -1310,6 +1317,18 @@ impl Dag { self.target_syntax.rust_rendering } + /// Typed accessor for the Rust `CleanEmissionContract` + /// declaration loaded from `src/v3/spec/rust.dag` (E-5). Callers + /// parse the structural fields via + /// `structural_fields_for_decl` and dispatch on the rule + /// variants. `None` before bootstrap completes or when the spec + /// file has been altered so the data item is missing — the + /// latter is a spec-file drift and surfaces at emit time as + /// `EmitError::MissingTargetSyntax`. + pub fn rust_clean_emission_spec(&self) -> Option { + self.target_syntax.rust_clean_emission + } + /// Typed accessor for the Rust target execution model /// declaration loaded from `src/v3/spec/rust.dag`. pub fn rust_execution_model_spec(&self) -> Option { @@ -1664,6 +1683,9 @@ impl Dag { self.target_syntax.rust_language = self.declaration_by_name("rust_language").map(|d| d.id); self.target_syntax.rust_rendering = self.declaration_by_name("rust_rendering").map(|d| d.id); + self.target_syntax.rust_clean_emission = self + .declaration_by_name("rust_clean_emission") + .map(|d| d.id); self.target_syntax.rust_execution_model = self .declaration_by_name("rust_execution_model") .map(|d| d.id); diff --git a/src/v3/compiler/src/emit_rust.rs b/src/v3/compiler/src/emit_rust.rs index 64525103627..41fcf0de079 100644 --- a/src/v3/compiler/src/emit_rust.rs +++ b/src/v3/compiler/src/emit_rust.rs @@ -481,6 +481,25 @@ struct RustLanguageSyntax { values: ValueConstructionSyntaxBinding, } +/// Typed read of `data rust_clean_emission: CleanEmissionContract` +/// from `src/v3/spec/rust.dag` — the portion this pilot consumes +/// (E-5 / Lane 1 Stage 1c PR 1). Other contract rules land here as +/// their consumers wire in. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct CleanEmissionContractBinding { + pattern_bindings: PatternBindingRuleBinding, +} + +/// Rust-valid slice of `std.clean_emission.PatternBindingRule`. +/// Parsed in `CleanEmissionContractBinding::build`, which rejects +/// target-invalid constructors instead of letting the renderer +/// normalize them later. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum PatternBindingRuleBinding { + EmitBindingAlways, + EmitUnderscoreWhenUnused, +} + struct RealizationIndexes { /// `target_decl_id → carrier + field bindings`. Built from /// `data rust_*: TypeRealization` items in rust.dag. @@ -550,6 +569,12 @@ struct RealizationIndexes { /// The target-side Rust execution model loaded from /// `data rust_execution_model: TargetExecutionModel`. execution: TargetExecutionModelBinding, + /// The Rust clean-emission contract loaded from + /// `data rust_clean_emission: CleanEmissionContract` (E-5 / + /// Lane 1 Stage 1c). Rule variants dispatch inside the emitter + /// to shape emitted code so it passes `rustc -D warnings` by + /// construction. + clean_emission: CleanEmissionContractBinding, } #[allow(dead_code)] @@ -820,6 +845,7 @@ impl RealizationIndexes { let rendering = RenderingModelBinding::build(dag)?; let computation = ComputationModelBinding::build(dag)?; let execution = TargetExecutionModelBinding::build(dag)?; + let clean_emission = CleanEmissionContractBinding::build(dag)?; let callable_dispositions = derive_callable_dispositions(dag, &external_callable_dispositions)?; let (substrate_accessors, substrate_accessor_universe) = @@ -837,12 +863,105 @@ impl RealizationIndexes { rendering, computation, execution, + clean_emission, substrate_accessors, substrate_accessor_universe, }) } } +impl CleanEmissionContractBinding { + /// Parse the portion of `data rust_clean_emission: + /// CleanEmissionContract` this emitter consumes. Currently only + /// `pattern_bindings` dispatches (Lane 1 Stage 1c PR 1 pilot); + /// other rules parse when their consumers land. + fn build(dag: &Dag) -> Result { + let declaration = dag + .rust_clean_emission_spec() + .ok_or(EmitError::MissingTargetSyntax("rust_clean_emission"))?; + let fields = structural_fields_for_decl(dag, declaration)?; + let pattern_bindings_value = fields + .iter() + .find(|(label, _)| label == "pattern_bindings") + .map(|(_, value)| value) + .ok_or(EmitError::MalformedTargetSyntax { + declaration, + detail: "rust_clean_emission is missing required `pattern_bindings` field", + })?; + let pattern_bindings = + parse_pattern_binding_rule(dag, pattern_bindings_value, declaration)?; + Ok(Self { pattern_bindings }) + } +} + +fn parse_pattern_binding_rule( + dag: &Dag, + value: &FieldValue, + declaration: DeclarationId, +) -> Result { + let FieldValue::Variant { + constructor, + payload, + } = value + else { + return Err(EmitError::MalformedTargetSyntax { + declaration, + detail: "rust_clean_emission.pattern_bindings must be a PatternBindingRule variant", + }); + }; + if !payload.is_empty() { + return Err(EmitError::MalformedTargetSyntax { + declaration, + detail: "PatternBindingRule variants must not carry payload fields", + }); + } + let emit_always = named_variant_id(dag, "PatternBindingRule", "EmitBindingAlways").ok_or( + EmitError::MalformedTargetSyntax { + declaration, + detail: "PatternBindingRule.EmitBindingAlways declaration was not found", + }, + )?; + let emit_underscore = named_variant_id(dag, "PatternBindingRule", "EmitUnderscoreWhenUnused") + .ok_or(EmitError::MalformedTargetSyntax { + declaration, + detail: "PatternBindingRule.EmitUnderscoreWhenUnused declaration was not found", + })?; + let emit_prefixed = named_variant_id( + dag, + "PatternBindingRule", + "EmitPrefixedUnderscoreWhenUnused", + ) + .ok_or(EmitError::MalformedTargetSyntax { + declaration, + detail: "PatternBindingRule.EmitPrefixedUnderscoreWhenUnused declaration was not found", + })?; + let not_applicable = named_variant_id(dag, "PatternBindingRule", "NotApplicablePatternBinding") + .ok_or(EmitError::MalformedTargetSyntax { + declaration, + detail: "PatternBindingRule.NotApplicablePatternBinding declaration was not found", + })?; + if *constructor == emit_always { + Ok(PatternBindingRuleBinding::EmitBindingAlways) + } else if *constructor == emit_underscore { + Ok(PatternBindingRuleBinding::EmitUnderscoreWhenUnused) + } else if *constructor == emit_prefixed { + Err(EmitError::MalformedTargetSyntax { + declaration, + detail: "rust_clean_emission.pattern_bindings cannot use PatternBindingRule.EmitPrefixedUnderscoreWhenUnused; Rust only supports EmitBindingAlways or EmitUnderscoreWhenUnused", + }) + } else if *constructor == not_applicable { + Err(EmitError::MalformedTargetSyntax { + declaration, + detail: "rust_clean_emission.pattern_bindings cannot use PatternBindingRule.NotApplicablePatternBinding; Rust only supports EmitBindingAlways or EmitUnderscoreWhenUnused", + }) + } else { + Err(EmitError::MalformedTargetSyntax { + declaration, + detail: "rust_clean_emission.pattern_bindings constructor is not a known PatternBindingRule variant", + }) + } +} + /// DB-14: build `(accessor_decl → realization_decl, universe)` for /// the active target language. /// @@ -3313,6 +3432,7 @@ impl<'a> Ctx<'a> { "matched variant `{variant_name}` does not lower to a payload product" ))); }; + let rendered_binding = self.render_payload_binding_name(path, binding); if children.len() != 1 { let wildcard = self.indexes.syntax.patterns.wildcard.clone(); let field_bindings = children @@ -3337,24 +3457,24 @@ impl<'a> Ctx<'a> { ), ], ); - return Ok(format!("{} @ {}", binding.binding_name, inner_pattern)); + if rendered_binding == wildcard { + return Ok(inner_pattern); + } + return Ok(format!("{rendered_binding} @ {inner_pattern}")); } if children[0].label == "_0" && (self.indexes.types.contains_key(&disj_id) || is_optional_match) { return Ok(render_named_template( &self.indexes.syntax.patterns.variant_pattern_positional, - &[ - ("name", &qualified_name), - ("binding", &binding.binding_name), - ], + &[("name", &qualified_name), ("binding", &rendered_binding)], )); } let bindings = render_named_template( &self.indexes.syntax.patterns.field_binding, &[ ("field", &children[0].label), - ("binding", &binding.binding_name), + ("binding", &rendered_binding), ], ); Ok(render_named_template( @@ -3363,6 +3483,84 @@ impl<'a> Ctx<'a> { )) } + /// E-5 / Lane 1 Stage 1c: render the arm's payload binding name + /// per `rust_clean_emission.pattern_bindings`. When the rule is + /// `EmitUnderscoreWhenUnused` and the arm body does not consume + /// `binding.payload_port`, emit `_` so `rustc -D warnings` does + /// not fire `unused_variables`. Rust-invalid contract variants + /// are rejected while building `CleanEmissionContractBinding`, + /// so the renderer only sees Rust-valid states. + fn render_payload_binding_name( + &self, + path: &Path, + binding: &crate::dag::PayloadBinding, + ) -> String { + match self.indexes.clean_emission.pattern_bindings { + PatternBindingRuleBinding::EmitUnderscoreWhenUnused + if !self.port_is_consumed_from(path.output, binding.payload_port) => + { + self.indexes.syntax.patterns.wildcard.clone() + } + PatternBindingRuleBinding::EmitBindingAlways + | PatternBindingRuleBinding::EmitUnderscoreWhenUnused => binding.binding_name.clone(), + } + } + + /// Structural port-liveness walk. Returns true if `target` + /// appears as any port reachable from `root` via + /// producer→input edges. Cost is bounded by the size of the + /// arm's body subgraph; each behavior visits its inputs once. + /// + /// Used to answer "does the arm body actually consume this + /// payload binding?" without textually scanning the rendered + /// body string — the fact is structural, so the check is + /// structural too. Ports with no producer (`produced_by = None`, + /// the shape payload bindings themselves take) are leaves: the + /// walk hits them and either returns true (hit the target) or + /// skips them (unrelated parameter port). + fn port_is_consumed_from(&self, root: PortId, target: PortId) -> bool { + if root == target { + return true; + } + let mut visited: HashSet = HashSet::new(); + let mut queue: Vec = vec![root]; + while let Some(port) = queue.pop() { + if !visited.insert(port) { + continue; + } + if port == target { + return true; + } + let Some(producer) = self.dag.port(port).produced_by else { + continue; + }; + match self.dag.node(producer) { + Behavior::Value(_) => {} + Behavior::Transform(t) => { + for input in t.inputs.iter().copied() { + queue.push(input); + } + } + Behavior::Branch(b) => { + queue.push(b.input); + for path in &b.paths { + queue.push(path.output); + } + } + Behavior::Loop(l) => { + queue.push(l.source); + queue.push(l.init); + queue.push(l.bound.count); + queue.push(behavior_result_port(self.dag.node(l.body))); + } + Behavior::Bind(b) => { + queue.push(b.value); + } + } + } + false + } + fn render_bool_pattern( &self, disj_id: DeclarationId, @@ -4916,6 +5114,51 @@ fn classify(s: Sign) -> Int = match s { Plus => 0, Minus => 1 }", ); } + #[test] + fn clean_emission_rejects_rust_invalid_pattern_binding_variants() { + let assert_rejected = |variant_name: &'static str, expected_detail: &'static str| { + let mut dag = compile_to_dag( + "type Sign = Plus | Minus +fn classify(s: Sign) -> Int = match s { Plus => 0, Minus => 1 }", + "test.v3", + ) + .expect("compiles"); + let clean_decl = dag + .rust_clean_emission_spec() + .expect("rust_clean_emission cached"); + let invalid_ctor = named_variant_id(&dag, "PatternBindingRule", variant_name) + .expect("PatternBindingRule variant exists"); + dag.declaration_mut(clean_decl).value_body = Some(ValueBody::Structural { + fields: vec![( + "pattern_bindings".to_string(), + FieldValue::Variant { + constructor: invalid_ctor, + payload: Vec::new(), + }, + )], + }); + + let err = emit_rust_with_mode(&dag, EmitRustMode::Module) + .expect_err("Rust-invalid pattern binding rule must fail closed"); + assert!(matches!( + err, + EmitError::MalformedTargetSyntax { + declaration, + detail, + } if declaration == clean_decl && detail == expected_detail + )); + }; + + assert_rejected( + "EmitPrefixedUnderscoreWhenUnused", + "rust_clean_emission.pattern_bindings cannot use PatternBindingRule.EmitPrefixedUnderscoreWhenUnused; Rust only supports EmitBindingAlways or EmitUnderscoreWhenUnused", + ); + assert_rejected( + "NotApplicablePatternBinding", + "rust_clean_emission.pattern_bindings cannot use PatternBindingRule.NotApplicablePatternBinding; Rust only supports EmitBindingAlways or EmitUnderscoreWhenUnused", + ); + } + #[test] fn callable_disposition_derives_direct_return_as_consumed() { let dag = compile_to_dag("fn id(x: Int) -> Int = x", "direct_return.v3").expect("compiles"); diff --git a/src/v3/compiler/src/lens_cost_generated.rs b/src/v3/compiler/src/lens_cost_generated.rs index 6950956c848..b64cb119c34 100644 --- a/src/v3/compiler/src/lens_cost_generated.rs +++ b/src/v3/compiler/src/lens_cost_generated.rs @@ -35,10 +35,10 @@ pub fn seed_bind_params(p0: &[Behavior]) -> Vec { } pub fn params_of(p0: &Behavior) -> Vec { match p0 { - Behavior::Value(v) => Vec::new(), - Behavior::Transform(t) => Vec::new(), - Behavior::Branch(b) => Vec::new(), - Behavior::Loop(l) => Vec::new(), + Behavior::Value(_) => Vec::new(), + Behavior::Transform(_) => Vec::new(), + Behavior::Branch(_) => Vec::new(), + Behavior::Loop(_) => Vec::new(), Behavior::Bind(bind) => param_entries(&((bind).params)), } } diff --git a/src/v3/compiler/src/lens_unused_parameters_generated.rs b/src/v3/compiler/src/lens_unused_parameters_generated.rs index 096c6f5d2a4..e4bb64ac774 100644 --- a/src/v3/compiler/src/lens_unused_parameters_generated.rs +++ b/src/v3/compiler/src/lens_unused_parameters_generated.rs @@ -19,10 +19,10 @@ pub fn check(p0: &Dag) -> Vec { } pub fn check_behavior(p0: &Dag, p1: &Behavior) -> Vec { match p1 { - Behavior::Value(v) => Vec::new(), - Behavior::Transform(t) => Vec::new(), - Behavior::Branch(b) => Vec::new(), - Behavior::Loop(l) => Vec::new(), + Behavior::Value(_) => Vec::new(), + Behavior::Transform(_) => Vec::new(), + Behavior::Branch(_) => Vec::new(), + Behavior::Loop(_) => Vec::new(), Behavior::Bind(bind) => { if ((bind).params).is_empty() { Vec::new() @@ -134,7 +134,7 @@ pub fn inputs_for_node(p0: &Dag, p1: &NodeId) -> Vec { } pub fn inputs_for_behavior(p0: &Dag, p1: &Behavior) -> Vec { match p1 { - Behavior::Value(v) => Vec::new(), + Behavior::Value(_) => Vec::new(), Behavior::Transform(t) => ((t).inputs).to_vec(), Behavior::Branch(branch) => { let mut __list = branch_path_outputs(&((branch).paths)); diff --git a/src/v3/compiler/tests/m1_3_emit_rust_test.rs b/src/v3/compiler/tests/m1_3_emit_rust_test.rs index 687f08e01b3..93041ddb798 100644 --- a/src/v3/compiler/tests/m1_3_emit_rust_test.rs +++ b/src/v3/compiler/tests/m1_3_emit_rust_test.rs @@ -352,6 +352,93 @@ let zero: Int = 0", assert!(out.contains("BoxedInt::Empty => 0,"), "got: {out}"); } +/// E-5 / Lane 1 Stage 1c pilot — unused match-arm payload bindings +/// render as `_` under `rust_clean_emission.pattern_bindings = +/// EmitUnderscoreWhenUnused`. Before the pilot the emitter rendered +/// `Boxed { _0: value } => 0`, which fired `unused_variables` under +/// `rustc -D warnings`; after the pilot it renders `Boxed { _0: _ } +/// => 0`, which passes the invariant by construction. +#[test] +fn emit_rust_unused_payload_binding_renders_as_underscore() { + let out = emit( + "type BoxedInt = Boxed(Int) | Empty +fn ignore_payload(b: BoxedInt) -> Int = match b { Boxed(value) => 0, Empty => 1 } +let zero: Int = 0", + ); + assert!( + out.contains("BoxedInt::Boxed { _0: _ } => 0,"), + "expected unused payload to render as `_`, got: {out}" + ); + assert!( + !out.contains("BoxedInt::Boxed { _0: value }"), + "unused binding leaked the identifier name, got: {out}" + ); + assert!(out.contains("BoxedInt::Empty => 1,"), "got: {out}"); +} + +/// Multi-field payloads still need a full variant pattern for type +/// shape, but an unused whole-payload binding must not be rendered +/// as `_ @ Variant { ... }` because Rust only permits identifiers on +/// the left side of `@`. +#[test] +fn emit_rust_unused_multi_field_payload_binding_avoids_wildcard_alias() { + let out = emit( + "type IntList = Empty | Cons { head: Int, tail: IntList } +fn ignore_payload(list: IntList) -> Int = match list { Empty => 0, Cons(payload) => 1 } +let zero: Int = 0", + ); + assert!( + out.contains("IntList::Cons { head: _, tail: _ } => 1,"), + "expected unused multi-field payload to render as a plain variant pattern, got: {out}" + ); + assert!( + !out.contains("_ @ IntList::Cons"), + "unused multi-field payload rendered an invalid wildcard alias, got: {out}" + ); +} + +/// E-5 / Lane 1 Stage 1c pilot (rustc roundtrip) — emitted code with +/// an unused match-arm payload binding passes `rustc -D +/// unused_variables`. Proves the rule fires end-to-end, not just +/// that the emission string looks right. +/// +/// Gated behind `#[ignore]` for the same reason as the other +/// `rustc_roundtrip_*` tests — CI sandboxes don't always carry a +/// toolchain. Run locally: +/// +/// cargo test -p v3-compiler --test m1_3_emit_rust_test \ +/// emit_rust_unused_payload_binding_passes_deny_unused \ +/// -- --ignored --nocapture +#[test] +#[ignore] +fn emit_rust_unused_payload_binding_passes_deny_unused() { + let source = emit( + "type BoxedInt = Boxed(Int) | Empty +fn ignore_payload(b: BoxedInt) -> Int = match b { Boxed(value) => 0, Empty => 1 } +let zero: Int = 0", + ); + let wrapped = format!("#![deny(unused_variables)]\n{source}"); + let tmp_dir = harness().next_child_dir(); + let src_path = tmp_dir.join("main.rs"); + let bin_path = tmp_dir.join("deny_unused_bin"); + std::fs::File::create(&src_path) + .and_then(|mut f| f.write_all(wrapped.as_bytes())) + .expect("write rust source"); + let status = Command::new("rustc") + .arg("--edition=2021") + .arg(&src_path) + .arg("-o") + .arg(&bin_path) + .stdout(Stdio::inherit()) + .stderr(Stdio::inherit()) + .status() + .expect("invoke rustc"); + assert!( + status.success(), + "emitted code tripped #[deny(unused_variables)] — E-5 pilot regression" + ); +} + #[test] fn emit_rust_record_literal_uses_value_construction_syntax() { let out = emit( diff --git a/src/v3/compiler/tests/m1_substrate_test.rs b/src/v3/compiler/tests/m1_substrate_test.rs index d5ee8c79b53..ca1f913b905 100644 --- a/src/v3/compiler/tests/m1_substrate_test.rs +++ b/src/v3/compiler/tests/m1_substrate_test.rs @@ -1045,6 +1045,74 @@ fn m1_3_prb_rust_dag_bootstrap_loads_structurally() { )); } +#[test] +fn rust_clean_emission_verifier_declares_structural_output_policy() { + let dag = Dag::new(); + let verifier_policy = find_named(&dag, "VerifierOutputPolicy"); + let ignore_output = match &dag.declaration(verifier_policy).connective { + TypeConnective::Disj { variants } => { + variants + .iter() + .find(|variant| variant.label == "IgnoreVerifierOutput") + .expect("VerifierOutputPolicy.IgnoreVerifierOutput exists") + .ty + } + other => panic!("VerifierOutputPolicy must be a Disj, got {other:?}"), + }; + let post_emit_verifier = dag + .declaration_by_name("PostEmitVerifier") + .expect("PostEmitVerifier type exists"); + let verifier_fields = match &dag.declaration(post_emit_verifier.id).connective { + TypeConnective::Conj { children } => children, + other => panic!("PostEmitVerifier must be a Conj, got {other:?}"), + }; + assert_eq!( + field(verifier_fields, "output_policy").ty, + verifier_policy, + "PostEmitVerifier.output_policy must point at VerifierOutputPolicy" + ); + + let rust_clean_emission = dag + .declaration_by_name("rust_clean_emission") + .expect("rust_clean_emission exists"); + let clean_fields = match rust_clean_emission + .value_body + .as_ref() + .expect("rust_clean_emission must carry a value_body") + { + v3_compiler::dag::ValueBody::Structural { fields } => fields, + other => panic!("rust_clean_emission must be Structural, got {other:?}"), + }; + let post_emit_value = clean_fields + .iter() + .find(|(label, _)| label == "post_emit_verifier") + .expect("rust_clean_emission.post_emit_verifier field exists"); + let verifier_record = match &post_emit_value.1 { + v3_compiler::dag::FieldValue::Record(fields) => fields, + other => panic!("post_emit_verifier must be a Record, got {other:?}"), + }; + let output_policy = verifier_record + .iter() + .find(|(label, _)| label == "output_policy") + .expect("post_emit_verifier.output_policy field exists"); + match &output_policy.1 { + v3_compiler::dag::FieldValue::Variant { + constructor, + payload, + } => { + assert_eq!( + *constructor, ignore_output, + "rust_clean_emission should declare IgnoreVerifierOutput for rustc" + ); + assert!( + payload.is_empty(), + "IgnoreVerifierOutput must stay payload-free" + ); + } + other => panic!("output_policy must be a Variant, got {other:?}"), + } +} + #[test] fn instantiation_arguments_participate_in_type_shape_equivalence() { let src = "\ diff --git a/src/v3/spec/rust.dag b/src/v3/spec/rust.dag index b4a556dcf2b..b3c0c77d6b2 100644 --- a/src/v3/spec/rust.dag +++ b/src/v3/spec/rust.dag @@ -65,6 +65,17 @@ import v3.std.substrate { SubstrateAccessorRealization, SubstrateAccessorBinding, port, node, resolve_producer } +import v3.std.clean_emission { + CleanEmissionContract, + ExpressionWrappingRule, WrapOnlyInOperandPosition, + PatternBindingRule, EmitUnderscoreWhenUnused, + ImportRule, IncludeOnlyReferenced, + BlockReturnRule, NoWrappingOnTerminalExpression, + VariableBindingRule, EmitLetUnderscoreWhenUnused, + MatchArmBodyRule, NoWrappingOnNonComplexBody, + CorrectionStyle, PostEmitVerifier, + VerifierOutputPolicy, IgnoreVerifierOutput +} data rust_execution_model: TargetExecutionModel = { memory: OwnershipBased @@ -874,6 +885,46 @@ data rust_language: LanguageSpec = { values: rust_value_construction } +// ───────────────────────────────────────────────────────────────── +// Clean-emission contract (E-5 / Lane 1 Stage 1c). +// ───────────────────────────────────────────────────────────────── +// +// Per-target rule choices for the E-5 invariant. Emitters read this +// contract to shape emitted code so it passes `rustc -D warnings` +// by construction. See `docs/design-clean-emission-contract.md` +// (DB-4) for the full contract shape and `INVARIANTS.md §E-5` for +// the "no escape hatches" commitment. +// +// **Dispatch state at this PR (Lane 1 Stage 1c PR 1):** +// - `pattern_bindings` is LIVE — `emit_rust::render_branch_pattern` +// dispatches on it for the unused-payload-binding pilot. +// - Every other field is authored-but-unread. Each field has a +// named rollout: the emitter change that consumes it removes +// the corresponding lint from the test-wrapper allow list in +// the same PR (Lane 1d/1e consolidation). + +data rust_clean_emission: CleanEmissionContract = { + expression_wrapping: WrapOnlyInOperandPosition + pattern_bindings: EmitUnderscoreWhenUnused + imports: IncludeOnlyReferenced + block_return: NoWrappingOnTerminalExpression + variable_bindings: EmitLetUnderscoreWhenUnused + match_arm_body: NoWrappingOnNonComplexBody + correction_style: { + indent_unit: " " + line_ending: "\n" + string_quote: "%Q" + trailing_semicolon: true + } + post_emit_verifier: { + command: "rustc" + args: ["--edition=2021", "-D", "warnings"] + syntax_only: false + expected_exit_code: 0 + output_policy: IgnoreVerifierOutput + } +} + // ───────────────────────────────────────────────────────────────── // DB-14 substrate accessor realizations (Rust target). // ───────────────────────────────────────────────────────────────── diff --git a/src/v3/std/clean_emission.dag b/src/v3/std/clean_emission.dag new file mode 100644 index 00000000000..3d9be093f02 --- /dev/null +++ b/src/v3/std/clean_emission.dag @@ -0,0 +1,109 @@ +module v3.std.clean_emission + +import std.list { List } + +// 🟢 TERMINAL. Per-target emission invariant (E-5). Every rule in +// this contract must be satisfied by construction — emitted code +// passes the target's declared verifier without modification. No +// post-emission cleanup, no `#[allow(...)]` / `# noqa` / pragma +// suppression. The contract GROWS by adding typed rules when new +// warning categories surface; it does NOT grow by admitting +// suppression. See INVARIANTS.md §E-5 and DB-4 for the full table. +type CleanEmissionContract { + expression_wrapping: ExpressionWrappingRule + pattern_bindings: PatternBindingRule + imports: ImportRule + block_return: BlockReturnRule + variable_bindings: VariableBindingRule + match_arm_body: MatchArmBodyRule + correction_style: CorrectionStyle + post_emit_verifier: PostEmitVerifier +} + +// 🟢 TERMINAL. Governs wrapping of expressions with precedence +// parentheses (rustc's `unused_parens`). `WrapEverything` is the +// pre-E-5 default and is rejected by the invariant when the target +// is precedence-capable — it's kept as a variant only so early +// targets could be represented before they migrate to the correct +// rule. +type ExpressionWrappingRule + = WrapEverything + | WrapOnlyInOperandPosition + | NoWrapping + +// 🟢 TERMINAL. Governs how a payload binding in a match arm is +// emitted when the arm body does not reference it (rustc's +// `unused_variables` in match arms). `NotApplicable` covers targets +// without structural pattern matching. +type PatternBindingRule + = EmitBindingAlways + | EmitUnderscoreWhenUnused + | EmitPrefixedUnderscoreWhenUnused + | NotApplicablePatternBinding + +// 🟢 TERMINAL. Governs which declared imports make it into the +// emitted module (rustc's `unused_imports`). +type ImportRule + = ImportEverythingDeclared + | IncludeOnlyReferenced + | ImportPerUsageSite + +// 🟢 TERMINAL. Governs the terminal expression of a block (rustc's +// `unused_parens around block return value`). +type BlockReturnRule + = WrapReturnValue + | NoWrappingOnTerminalExpression + | ExplicitReturnKeyword + +// 🟢 TERMINAL. Governs a `let`-binding whose identifier the body +// does not reference (rustc's `unused_variables` at let-bindings). +type VariableBindingRule + = EmitLetBindingAlways + | EmitLetUnderscoreWhenUnused + | OmitLetBinding + +// 🟢 TERMINAL. Governs wrapping of the arm body expression in a +// match (rustc's `unused_parens around match arm expression`). +// Go uses switch and renders arm bodies differently, so +// `NotApplicable` is a legitimate choice. +type MatchArmBodyRule + = WrapBody + | NoWrappingOnNonComplexBody + | NotApplicableMatchArmBody + +// 🟢 TERMINAL. Per-target rendering style used by diagnostic fix +// generators that surface source-level corrections. DB-1's +// `Correction` type consumes this to know how its inserted text +// composes with the surrounding .dag source. Minimal shape here; +// DB-1 may extend at the point its consumers land. +type CorrectionStyle { + indent_unit: String + line_ending: String + string_quote: String + trailing_semicolon: Bool +} + +// 🟢 TERMINAL. Declares the external verifier that validates +// emitted source for this target. `syntax_only` distinguishes +// shallow checks (gofmt, py_compile) from full compiles (rustc). +// `expected_exit_code` and `output_policy` together define the +// verifier's verdict semantics. Exit code alone is insufficient +// for tools like `gofmt -l`, which report dirty files via stdout +// while still exiting 0. +type PostEmitVerifier { + command: String + args: List + syntax_only: Bool + expected_exit_code: Int + output_policy: VerifierOutputPolicy +} + +// 🟢 TERMINAL. Defines how verifier process output affects the +// pass/fail verdict once `expected_exit_code` matched. Keeps +// verifier-result semantics structural instead of hardcoding +// tool-specific stdout/stderr rules in the harness. +type VerifierOutputPolicy + = IgnoreVerifierOutput + | RequireEmptyStdout + | RequireEmptyStderr + | RequireEmptyStdoutAndStderr