From ee09a7a29018ed2822249a03aea9ed93f671d2fe Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Thu, 8 Oct 2026 22:25:42 +0300 Subject: [PATCH] tests: audit swap leak and remaining source rule boundaries --- docs/plan/phase-6-source-language.md | 6 +- tests/conformance/README.md | 4 +- tests/conformance/reject-twins.json | 165 ++++++++++++++++++ .../reject_twins/analogue_atomic_add_bool.aji | 14 ++ .../reject_twins/analogue_iref_eq_types.aji | 10 ++ .../analogue_island_alloc_ref.aji | 14 ++ .../reject_twins/analogue_nominal_call.aji | 21 +++ .../analogue_select_closed_arity.aji | 16 ++ .../reject_twins/channel_endpoint_element.aji | 18 ++ .../source/reject_twins/linear_swap_leak.aji | 41 +++++ tests/hosted/source_reject_twins.py | 78 ++++++++- tools/source_reject_twins.py | 31 +++- 12 files changed, 408 insertions(+), 10 deletions(-) create mode 100644 tests/conformance/source/reject_twins/analogue_atomic_add_bool.aji create mode 100644 tests/conformance/source/reject_twins/analogue_iref_eq_types.aji create mode 100644 tests/conformance/source/reject_twins/analogue_island_alloc_ref.aji create mode 100644 tests/conformance/source/reject_twins/analogue_nominal_call.aji create mode 100644 tests/conformance/source/reject_twins/analogue_select_closed_arity.aji create mode 100644 tests/conformance/source/reject_twins/channel_endpoint_element.aji create mode 100644 tests/conformance/source/reject_twins/linear_swap_leak.aji diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index 7c9f5bb..0fd1004 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -320,8 +320,8 @@ Validation: unit tests and Zig formatting pass; full conformance is 1,655/1,655. ## P6-7 public rejection-twin audit (2026-10-08) -Verified same-code coverage is 88/199 across ownership/resources, borrows, effects/capabilities, tasks, graphs, atomics, linear aggregates and buffer operations. The inventory retains 22 pending, 40 prescribed E7xxx analogues and 49 AIR-only cases; all three categories remain unmet under the literal exit criterion (Q-053). P6-7 remains doing. +Verified same-code coverage is 90/199 across ownership/resources, borrows, effects/capabilities, tasks, graphs, atomics, linear aggregates and buffer operations. The inventory retains 3 pending, 45 prescribed E7xxx analogues and 61 AIR-only cases; all three categories remain unmet under the literal exit criterion (Q-053). P6-7 remains doing. -The [checker documentation](../../tests/conformance/README.md) records the diagnostic-fact, independent-position and context witnesses. Named type tables preserve the nominal diamond; early cycle pairs pin the two artifacts that exist before lowering. Five CFG loan pairs pin original AIR, source and canonical lowering after a manual shape review: single br handoff, lend/plain merge, loop-carried loans, cancelled-handle forwarding and parent access after handoff. Direct cbr/switch arm-parameter cases remain pending: the tested source expressions instead pass handles to a later br merge. The task-parameter feature pair validates each full repair header before comparing its missing closure; unrelated declared features do not decide that rule. Six more source-boundary analogues retain exact fields and independent markers. The guard-unlock pair retains the returned view's mutex.borrow ancestor through the generated unlock. Fingerprints attest unchanged artifacts, not audit correctness, and introduce no provenance or lifetime analysis. +The [checker documentation](../../tests/conformance/README.md) records the diagnostic-fact, independent-position and context witnesses. Named type tables preserve the nominal diamond; early cycle pairs pin the two artifacts that exist before lowering. Five CFG loan pairs pin original AIR, source and canonical lowering after a manual shape review: single br handoff, lend/plain merge, loop-carried loans, cancelled-handle forwarding and parent access after handoff. Three cases remain pending: direct cbr/switch arm parameters are not preserved by the tested source merges, while ordinary atomic access produces E4202 before lowering, without AIR's structured found/use/operand facts. A code-only early match would weaken verification; it remains pending. The current early mode covers declarations only. The task-parameter feature pair validates each full repair header before comparing its missing closure; unrelated declared features do not decide that rule. Reserved channel endpoint elements retain their feature/construct at channel.make. The linear swap pair compares named enum tables and pins the array/unpack and specific arm where the old value leaks. Source-boundary analogues retain exact fields and independent markers; the nominal-call analogue records its local rather than linked declarations. The guard-unlock pair retains the returned view's mutex.borrow ancestor through the generated unlock. Fingerprints attest unchanged artifacts, not audit correctness, and introduce no provenance or lifetime analysis. -Validation: full conformance is 1,700/1,700; unit tests, Zig formatting, all 53 checker regressions and the 88-pair source/AIR position check pass. All 58 source reject_twins fixtures pass collection before every instruction; source coverage remains 121/121. The completion gate still rejects partial coverage. Claude independently reviewed the CFG fingerprints and shape regressions, and the feature-header witness, two new pairs, six analogues and two AIR-only classifications. Corrupted repair headers, larger missing closures, task results substituted for parameters and relaxed source/raw payloads are rejected by independent probes. Existing Git attributes already force LF for pinned AIR/source files. No compiler, verifier, runtime, normative rule, diagnostic code or reference bundle changes. +Validation: full conformance is 1,707/1,707; unit tests, Zig formatting, all 58 checker regressions and the 90-pair source/AIR position check pass. All 65 source reject_twins fixtures pass collection before every instruction; source coverage remains 121/121. The completion gate still rejects partial coverage. Claude independently reviewed the feature/CFG witnesses and the remaining public rule boundaries, including the swap fingerprints and nominal family. New probes reject mutex creation substituted for channel creation, another swapped enum, a replacement call needing further identity review, omitted array/unpack and a leak on the other arm. The atomic bool analogue marks the source value operand; its AIR error instead marks the cell. Existing Git attributes already force LF for pinned AIR/source files. No compiler, verifier, runtime, normative rule, diagnostic code or reference bundle changes. diff --git a/tests/conformance/README.md b/tests/conformance/README.md index 77c6da3..05ef292 100644 --- a/tests/conformance/README.md +++ b/tests/conformance/README.md @@ -46,13 +46,13 @@ A key is a single lowercase word; header lines without a `key:` prefix are free- `python3 tools/source_reject_twins.py` checks audited pairs declared by free-form `// AIR twin: ` comments in source tests. These comments are separate from `equivalent`, which applies only to runs. `reject-twins.json` records each reviewed rule, governing spec and diagnostic site; a matching code alone does not establish a twin. -The check compares code multisets, diagnostic kinds, offending AIR operations, identity-field roles, root resource families and stable rule facts (including atomic orderings and budget limits). Resource families distinguish region/frozen/own/file modes; content types and ref/mut/slice forms do not distinguish these generic ownership/loan rules. For E3101, callee names resolve to their explicit flat effect sets; parameter/result types do not decide this effect rule. For E4001/E4002 argument errors, worker/SSA names are identities, while the complete rejected parameter type remains a fact. The worker must resolve to a declaration; its body/result does not decide the argument rule. Result-only E4001 retains the worker result contract and a distinct role. Unsupported identity rules fail closed. Guard-derived `mutex.borrow` results retain the borrow class; guard identities and the offending opcode remain distinct. The small declaration/producer lookup is not a second type checker. Source diagnostics and E7xxx analogues must hit independent `// diagnostic here` markers. Lowered pairs also agree with canonical AIR and its annotations, including related positions. Source/raw identity fields and related values must agree exactly before original/source spellings are normalized. Several raw diagnostics at one source construct use the first-per-code/location projection required by spec 15 §10. Function/type budget headers use the marked source declaration and exact canonical name, since `--annotate` exposes block/instruction spans; generic/imported headers without a matching declaration fail closed. A by-value cycle rejected before lowering uses an explicit declaration mode; it does not claim generated AIR. +The check compares code multisets, diagnostic kinds, offending AIR operations, identity-field roles, root resource families and stable rule facts (including atomic orderings and budget limits). Resource families distinguish region/frozen/own/file modes; content types and ref/mut/slice forms do not distinguish these generic ownership/loan rules. For E3101, callee names resolve to their explicit flat effect sets; parameter/result types do not decide this effect rule. For E4001/E4002 argument errors, worker/SSA names are identities, while the complete rejected parameter type remains a fact. The worker must resolve to a declaration; its body/result does not decide the argument rule. Result-only E4001 retains the worker result contract and a distinct role. Unsupported identity rules fail closed. Guard-derived `mutex.borrow` results retain the borrow class; guard identities and the offending opcode remain distinct. For an E3002 `borrow` identity produced by `value.swap`, only a unique direct enum.make replacement with a named enum declaration is supported. Its nominal family remains distinct from other enum, owner or resource families; unsupported replacement producers fail closed. The small declaration/producer lookup is not a second type checker. Source diagnostics and E7xxx analogues must hit independent `// diagnostic here` markers. Lowered pairs also agree with canonical AIR and its annotations, including related positions. Source/raw identity fields and related values must agree exactly before original/source spellings are normalized. Several raw diagnostics at one source construct use the first-per-code/location projection required by spec 15 §10. Function/type budget headers use the marked source declaration and exact canonical name, since `--annotate` exposes block/instruction spans; generic/imported headers without a matching declaration fail closed. A by-value cycle rejected before lowering uses an explicit declaration mode; it does not claim generated AIR. Case-specific `required_ops` optionally checks minimum operation counts in the diagnostic's function in both original and generated AIR. Cancelled-join regressions require their cancellation operations, so a plain task-loan error cannot replace them. `exact_ops: true` instead requires the full opcode count table of that function to match `required_ops`. The shared-view push case uses it to reject ended decoy views and additional plain borrows; it preserves the reviewed straight-line shape without computing lifetimes. `required_identity_uses` additionally requires the reported SSA identity to occur as an operand of the named opcode. The shared-view case links `conflicts_with` to `buffer.view`, excluding a view of another buffer. These strict witnesses retain both trap continuations; otherwise valid twins may need a separate audit. `match_type_declarations: true` additionally compares the complete named type-declaration tables, ignoring only comments/whitespace. The nominal diamond regression uses it so flat arrays of the same byte size cannot replace its shared type graph. AIR witnesses require a lowered same-code pair. These witnesses and diagnostic facts supplement the manual rule audit; they do not prove full dataflow equivalence. An analogue without structured rule fields relies on the reviewed construct and exact code/position; the check does not infer facts from message prose. For a single E0006 `feature_not_declared` pair, `feature_header_context: true` permits different unrelated declared features. Each diagnostic's `canonical_header` must first equal the sorted union of its module's unique feature header and the verifier-provided `closure`. The comparison then replaces only that repair header with the missing closure set; feature, reason, construct and all other facts remain exact. Invalid/missing closures, dependency errors and malformed repair headers fail closed. Source/raw payload mapping stays exact, including the repair header. This witness does not infer dependencies or support other E0006 reasons. -For lowered CFG cases whose diagnostic facts omit the handoff shape, `audited_context` pins three manually reviewed artifacts: the original AIR (`air`), each source file (`sources`) and its canonical UTF-8 lowering (`lowered`). Both maps must name exactly the declared twins; every value is a lowercase SHA-256 digest. Byte changes, including source comments/line endings and harmless lowering renames, require a fresh context review before updating the fingerprints. The regular compiled diagnostics, markers, raw mapping, related positions and lowering determinism remain checked. The five task-loan rows record their reviewed br/merge/back-edge/cancelled-handle contexts in `rule`; a straight-line error cannot replace them. These fingerprints attest unchanged artifacts, not the correctness of the manual audit, and add no provenance or lifetime analysis. Direct cbr/switch target-argument cases remain pending: source arm joins do not preserve those reviewed AIR shapes. +For lowered CFG cases whose diagnostic facts omit the handoff shape, `audited_context` pins three manually reviewed artifacts: the original AIR (`air`), each source file (`sources`) and its canonical UTF-8 lowering (`lowered`). Both maps must name exactly the declared twins; every value is a lowercase SHA-256 digest. Byte changes, including source comments/line endings and harmless lowering renames, require a fresh context review before updating the fingerprints. The regular compiled diagnostics, markers, raw mapping, related positions and lowering determinism remain checked. The linear swap-leak row also compares its named type table and pins the array/unpack plus the specific enum arm that leaks; another arm with the same diagnostic and operation counts cannot replace it. The five task-loan rows record their reviewed br/merge/back-edge/cancelled-handle contexts in `rule`; a straight-line error cannot replace them. These fingerprints attest unchanged artifacts, not the correctness of the manual audit, and add no provenance or lifetime analysis. Direct cbr/switch target-argument cases remain pending: source arm joins do not preserve those reviewed AIR shapes. Early rejection produces no canonical AIR. Its mandatory `early_context` records SHA-256 fingerprints of both manually audited AIR/source files, alongside the rule audit; compiled code/kind/type and independent source positions still have to match. The fingerprints preserve the reviewed cycle shape, including long nominal chains and recursive arrays. They attest unchanged bytes, not the correctness of the audit. Any edit, including comments or line endings, requires a fresh context review before updating these fingerprints; do not regenerate them just to make a failed check pass. diff --git a/tests/conformance/reject-twins.json b/tests/conformance/reject-twins.json index 5abd88b..2dfa751 100644 --- a/tests/conformance/reject-twins.json +++ b/tests/conformance/reject-twins.json @@ -1546,6 +1546,171 @@ "kind": "air_only", "spec": "docs/spec/15-source-language.md \u00a78", "rule": "Only registered intrinsic names emit AIR intrinsic calls. An undeclared io.teleport in source is ordinary E7002 name resolution, not an unknown AIR intrinsic; user functions are emitted as ordinary calls." + }, + "phase3/reject/channels_endpoint_element.air": { + "kind": "same_code", + "site": "instruction", + "spec": "docs/spec/04-concurrency-and-atomics.md \u00a738.1; docs/spec/15-source-language.md \u00a710", + "rule": "channel.make has sender elements, requiring reserved channel_transfer. Both sides retain that feature/construct at channel.make; this diagnostic supplies no closure or canonical repair header." + }, + "phase3/reject/select_target_arity.air": { + "kind": "source_error", + "spec": "docs/spec/15-source-language.md \u00a77", + "rule": "A select send closed edge omits its unsent value binding. Source checks the authored binding list before emitting a continuation, with outcome closed and expected 1.", + "analogues": [ + { + "source": "source/reject_twins/analogue_select_closed_arity.aji", + "codes": [ + "E7005" + ], + "fields": { + "outcome": "closed", + "expected": "1" + } + } + ] + }, + "phase4/reject/iref_eq_types.air": { + "kind": "source_error", + "spec": "docs/spec/15-source-language.md \u00a78; \u00a710", + "rule": "Equality compares iref and iref. Source checks operand types before emitting iref.eq.", + "analogues": [ + { + "source": "source/reject_twins/analogue_iref_eq_types.aji", + "codes": [ + "E7005" + ], + "fields": { + "expected": "iref", + "found": "iref" + } + } + ] + }, + "phase4/reject/island_alloc_via_ref.air": { + "kind": "source_error", + "spec": "docs/spec/15-source-language.md \u00a78; \u00a710", + "rule": "island.alloc receives a named shared ref> binding; allocation requires a named exclusive binding. Source rejects before AIR with found; it supplies no expected field.", + "analogues": [ + { + "source": "source/reject_twins/analogue_island_alloc_ref.aji", + "codes": [ + "E7005" + ], + "fields": { + "found": "ref>" + } + } + ] + }, + "phase3/reject/cancel_shield_order.air": { + "kind": "air_only", + "spec": "docs/spec/15-source-language.md \u00a73; \u00a77", + "rule": "Source shields nest by construction and end in reverse order on every normal exit. Shield handles are not source values and cannot be block arguments. The reversed ending/renamed-stack context of this AIR cannot be authored." + }, + "phase3/reject/cfg_provenance_shield_order.air": { + "kind": "air_only", + "spec": "docs/spec/15-source-language.md \u00a73; \u00a77", + "rule": "Source shields nest by construction and end in reverse order on every normal exit. Shield handles are not source values and cannot be block arguments. The reversed ending/renamed-stack context of this AIR cannot be authored." + }, + "phase3/reject/cfg_provenance_shield_stack_join.air": { + "kind": "air_only", + "spec": "docs/spec/15-source-language.md \u00a73; \u00a77", + "rule": "Source shields nest by construction and end in reverse order on every normal exit. Shield handles are not source values and cannot be block arguments. The reversed ending/renamed-stack context of this AIR cannot be authored." + }, + "phase3/reject/cfg_provenance_scope_alone.air": { + "kind": "air_only", + "spec": "docs/spec/15-source-language.md \u00a74; \u00a77", + "rule": "A source scope name is only a lexical identifier for task.spawn, never an ordinary assigned or yielded value. The renamed scope block parameter that is the subject of this AIR regression cannot be emitted. A plain unjoined-child E4301 would drop that context." + }, + "phase3/reject/cfg_provenance_scope_task.air": { + "kind": "air_only", + "spec": "docs/spec/15-source-language.md \u00a74; \u00a77", + "rule": "A source scope name is only a lexical identifier for task.spawn, never an ordinary assigned or yielded value. The renamed scope block parameter that is the subject of this AIR regression cannot be emitted. A plain unjoined-child E4301 would drop that context." + }, + "phase3/reject/cfg_provenance_guard_parent.air": { + "kind": "air_only", + "spec": "docs/spec/15-source-language.md \u00a73; \u00a77", + "rule": "The lock guard is never a source value; source branches inside the lock use the originating guard rather than transferring it as a block argument. This AIR regression explicitly forwards the guard through br before ending its parent, a context with no implemented source spelling." + }, + "modules/nominal_call.air": { + "kind": "source_error", + "spec": "docs/spec/15-source-language.md \u00a75; \u00a710; \u00a714.2", + "rule": "A function receives a structurally identical but nominally distinct struct. The source analogue uses two local nominal declarations rather than package linking; the checked argument-type mismatch precedes AIR.", + "analogues": [ + { + "source": "source/reject_twins/analogue_nominal_call.aji", + "codes": [ + "E7005" + ], + "fields": { + "expected": "@PairA", + "found": "@PairB" + } + } + ] + }, + "phase0/reject/syntax_error.air": { + "kind": "air_only", + "spec": "docs/spec/15-source-language.md \u00a710", + "rule": "The missing comma is in the AIR text operand grammar, which source does not expose. A source syntax error uses a different grammar and E7001; malformed generated AIR instead reports E7900 as a compiler bug." + }, + "phase2/reject/no_capability_comparison.air": { + "kind": "air_only", + "spec": "docs/spec/15-source-language.md \u00a78; \u00a710", + "rule": "eq.cap is not an AIR opcode and its undefined result adds E5001. Source equality on capabilities rejects by its operand type rule, before AIR; it cannot emit this absent opcode and invalid SSA context." + }, + "phase5/reject/add_bool.air": { + "kind": "source_error", + "spec": "docs/spec/15-source-language.md \u00a710; \u00a712", + "rule": "atomic.add.wrap is used on a bool cell with a bool operand. Source checks its integer-cell requirement before emitting the operation; found remains bool. Source anchors this at the bool value operand; AIR anchors it at the ref> cell operand.", + "analogues": [ + { + "source": "source/reject_twins/analogue_atomic_add_bool.aji", + "codes": [ + "E7005" + ], + "fields": { + "found": "bool" + } + } + ] + }, + "linear/builtin_take.air": { + "kind": "air_only", + "spec": "docs/spec/15-source-language.md \u00a75; \u00a716", + "rule": "alloc_error is a Copy built-in enum. Ordinary Copy matches emit enum.switch, and move of a Copy value outside specialization is rejected; even specialized Copy matches remain non-consuming. Source cannot emit enum.take for this built-in." + }, + "linear/copy.air": { + "kind": "air_only", + "spec": "docs/spec/15-source-language.md \u00a75; \u00a716", + "rule": "An aggregate containing own is linear. Plain named use in a consuming initializer requires move (E7003); move transfers rather than duplicates the aggregate. The source frontend cannot emit AIR copy of this linear struct." + }, + "phase0/reject/unknown_opcode.air": { + "kind": "air_only", + "spec": "docs/spec/15-source-language.md \u00a78; \u00a710", + "rule": "Source has no spelling for arbitrary AIR opcodes. An unknown function name rejects in name resolution; the frontend emits only registered operations, so frobnicate plus the resulting undefined SSA value is an AIR-only malformed module." + }, + "phase2/reject/borrow_parameter_not_from_allocation.air": { + "kind": "air_only", + "spec": "docs/spec/15-source-language.md \u00a74; \u00a75; \u00a719", + "rule": "The regression passes a borrow through br as a block parameter, requiring reserved borrow_joins. A source borrow is bound lexically by ref/mut, cannot be assigned as a variable or yielded by a nested block, if or match, and cannot reach the generated join as an ordinary value. No source spelling preserves this borrow-parameter context." + }, + "linear/swap_leak.air": { + "kind": "same_code", + "site": "instruction", + "spec": "docs/spec/03-memory-model.md \u00a725; docs/spec/15-source-language.md \u00a716", + "rule": "The array.make/unpack owner enters Maybe::some; value.swap replaces it with none. The original complete value is consumed only on the slot some arm and leaks at ret on the slot none arm. Full type tables and pinned AIR/source/lowering preserve that branch context; operation counts alone would allow leaking on the other arm.", + "match_type_declarations": true, + "audited_context": { + "air": "ffd1b3ae7fd6462601c7dd9044322d9d430ef798fa645b67763d0316df44c831", + "sources": { + "source/reject_twins/linear_swap_leak.aji": "c675d231336f17eadb39d7e63138a1c1b67500c464c59b09f31cb7ea1ff66ed5" + }, + "lowered": { + "source/reject_twins/linear_swap_leak.aji": "6f9fa0d8ef40b75951c2a2042d1d171c221268301df18b38775b74a47f606cc7" + } + } } } } diff --git a/tests/conformance/source/reject_twins/analogue_atomic_add_bool.aji b/tests/conformance/source/reject_twins/analogue_atomic_add_bool.aji new file mode 100644 index 0000000..daf6c54 --- /dev/null +++ b/tests/conformance/source/reject_twins/analogue_atomic_add_bool.aji @@ -0,0 +1,14 @@ +// expect: reject E7005 +// phase: 6 +// spec: docs/spec/15-source-language.md §10; §12 +module test.bool + +fn main() -> bool effects [atomic] { + let t = true; + let c = atomic.new(t); + { + ref r = c; + let x = atomic.add.wrap(r, t, seq_cst); // diagnostic here: t, seq_cst + } + return atomic.take(move c); +} diff --git a/tests/conformance/source/reject_twins/analogue_iref_eq_types.aji b/tests/conformance/source/reject_twins/analogue_iref_eq_types.aji new file mode 100644 index 0000000..df68f07 --- /dev/null +++ b/tests/conformance/source/reject_twins/analogue_iref_eq_types.aji @@ -0,0 +1,10 @@ +// expect: reject E7005 +// phase: 6 +// spec: docs/spec/15-source-language.md §8; §10 +module test.iref_eq_types + +fn same(a: iref, b: iref) -> bool effects [] { + return a == b; // diagnostic here: b; +} + +fn main() -> void effects [] {} diff --git a/tests/conformance/source/reject_twins/analogue_island_alloc_ref.aji b/tests/conformance/source/reject_twins/analogue_island_alloc_ref.aji new file mode 100644 index 0000000..602e8da --- /dev/null +++ b/tests/conformance/source/reject_twins/analogue_island_alloc_ref.aji @@ -0,0 +1,14 @@ +// expect: reject E7005 +// phase: 6 +// spec: docs/spec/15-source-language.md §8; §10 +module test.island_alloc_via_ref + +fn main(heap: cap) -> u64 effects [mem.alloc] { + let i = island.create(1u64, heap) or trap; + { + ref g = i; + let r = island.alloc(g, 1u64) or trap; // diagnostic here: g, 1u64 + } + island.destroy(move i); + return 1; +} diff --git a/tests/conformance/source/reject_twins/analogue_nominal_call.aji b/tests/conformance/source/reject_twins/analogue_nominal_call.aji new file mode 100644 index 0000000..2b18f06 --- /dev/null +++ b/tests/conformance/source/reject_twins/analogue_nominal_call.aji @@ -0,0 +1,21 @@ +// expect: reject E7005 +// phase: 6 +// spec: docs/spec/15-source-language.md §5; §10; §14.2 +module test.nominal + +struct PairA { + value: u64 +} + +struct PairB { + value: u64 +} + +fn total(pair: PairA) -> u64 effects [] { + return pair.value; +} + +fn main() -> u64 effects [] { + let pair = PairB { value: 42u64 }; + return total(pair); // diagnostic here: pair); +} diff --git a/tests/conformance/source/reject_twins/analogue_select_closed_arity.aji b/tests/conformance/source/reject_twins/analogue_select_closed_arity.aji new file mode 100644 index 0000000..6728417 --- /dev/null +++ b/tests/conformance/source/reject_twins/analogue_select_closed_arity.aji @@ -0,0 +1,16 @@ +// expect: reject E7005 +// phase: 6 +// spec: docs/spec/15-source-language.md §7 +module test.select_target_arity + +fn f(tx: sender, x: u64) -> sender effects [task.wait] { + select { + send(tx, x) { + ok => {} + closed => {} // diagnostic here: closed => + } cancelled(v) => {} + } + return move tx; +} + +fn main() -> void effects [] {} diff --git a/tests/conformance/source/reject_twins/channel_endpoint_element.aji b/tests/conformance/source/reject_twins/channel_endpoint_element.aji new file mode 100644 index 0000000..ff73ff6 --- /dev/null +++ b/tests/conformance/source/reject_twins/channel_endpoint_element.aji @@ -0,0 +1,18 @@ +// expect: reject E0006 +// phase: 6 +// spec: docs/spec/04-concurrency-and-atomics.md §38.1; docs/spec/15-source-language.md §10 +// AIR twin: phase3/reject/channels_endpoint_element.air +module test.channels_endpoint_element + +fn f(heap: cap) -> void effects [mem.alloc] { + match channel.make>(1, heap) { // diagnostic here: channel.make + ok(tx, rx) => { + trap; + } + err(e) => { + trap; + } + } +} + +fn main() -> void effects [] {} diff --git a/tests/conformance/source/reject_twins/linear_swap_leak.aji b/tests/conformance/source/reject_twins/linear_swap_leak.aji new file mode 100644 index 0000000..435d4ce --- /dev/null +++ b/tests/conformance/source/reject_twins/linear_swap_leak.aji @@ -0,0 +1,41 @@ +// expect: reject E3002 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25; docs/spec/15-source-language.md §16 +// AIR twin: linear/swap_leak.air +module test.linear + +enum Maybe { + some(own), + none +} + +fn main(heap: cap) -> u64 effects [mem.alloc] { + let n = 42u64; + match own.new(n, heap) { + ok(owner) => { + let items = [move owner]; + let (part) = array.unpack(move items); + var slot: Maybe = Maybe::some(move part); + let old = value.swap(mut slot, Maybe::none); + match move slot { + Maybe::some(extra_owner) => { + own.free(move extra_owner); + match move old { + Maybe::some(answer_owner) => { + return own.take(move answer_owner); + } + Maybe::none => { + return n; + } + } + } + Maybe::none => { + return n; // diagnostic here + } + } + } + err(e) => { + return n; + } + } +} diff --git a/tests/hosted/source_reject_twins.py b/tests/hosted/source_reject_twins.py index 3304d6e..1f4bd18 100644 --- a/tests/hosted/source_reject_twins.py +++ b/tests/hosted/source_reject_twins.py @@ -167,6 +167,19 @@ class CoverageFailures(unittest.TestCase): with self.assertRaisesRegex(ValueError, 'missing diagnostic-identity use witness'): self.verify_fake(row) + def test_endpoint_rule_cannot_substitute_mutex_for_channel_creation(self): + row = self.fake_pair(source_path='source/reject_twins/channel_endpoint_element.aji', + air_path='phase3/reject/channels_endpoint_element.air') + self.verify_fake(row) + p = self.corpus / 's.aji' + p.write_text('// expect: reject E0006\n// AIR twin: a.air\n' + 'module test.endpoint_mutex\n' + 'fn f(tx: sender) -> void effects [] {\n' + ' let m = mutex.make(move tx); // diagnostic here: mutex.make\n' + ' trap;\n}\nfn main() -> void effects [] {}\n') + with self.assertRaisesRegex(ValueError, 'different offending operation/rule facts'): + self.verify_fake(row) + def task_parameter_pair(self): row = self.fake_pair(source_path='source/reject_twins/task_handle_parameter.aji', air_path='phase3/reject/tasks_handle_as_parameter.air') @@ -256,9 +269,7 @@ class CoverageFailures(unittest.TestCase): with self.assertRaisesRegex(ValueError, 'mapping changed rule facts'): self.verify_fake(row) - def audited_cfg_pair(self, source='cfg_provenance_loan_br', air='cfg_provenance_loan_br'): - row = self.fake_pair(source_path=f'source/reject_twins/{source}.aji', - air_path=f'phase3/reject/{air}.air') + def pin_pair_context(self, row): p = self.corpus / 's.aji' canonical = twins.command(AJI, 'lower', p, status=0) row['audited_context'] = { @@ -268,6 +279,67 @@ class CoverageFailures(unittest.TestCase): } return row + def audited_cfg_pair(self, source='cfg_provenance_loan_br', air='cfg_provenance_loan_br'): + return self.pin_pair_context(self.fake_pair( + source_path=f'source/reject_twins/{source}.aji', + air_path=f'phase3/reject/{air}.air')) + + def swap_pair(self): + return self.fake_pair(source_path='source/reject_twins/linear_swap_leak.aji', + air_path='linear/swap_leak.air') + + def test_swapped_enum_nominal_family_cannot_change(self): + row = self.swap_pair() + self.verify_fake(row) + p = self.corpus / 's.aji' + p.write_text(p.read_text().replace('Maybe', 'OtherEnum')) + with self.assertRaisesRegex(ValueError, 'different offending operation/rule facts'): + self.verify_fake(row) + + def test_swap_replacement_call_needs_a_separate_identity_audit(self): + row = self.swap_pair() + p = self.corpus / 's.aji' + text = p.read_text().replace('value.swap(mut slot, Maybe::none)', + 'value.swap(mut slot, replacement())') + p.write_text(text + '\nfn replacement() -> Maybe effects [] { return Maybe::none; }\n') + self.assertEqual([d['code'] for d in twins.errors(AJI, p)], ['E3002']) + with self.assertRaisesRegex(ValueError, 'swapped enum replacement lacks a named enum declaration'): + self.verify_fake(row) + + def test_swap_leak_cannot_omit_audited_array_unpack(self): + row = self.swap_pair() + row['match_type_declarations'] = True + self.pin_pair_context(row) + self.verify_fake(row) + p = self.corpus / 's.aji' + text = p.read_text() + text = text.replace(' let items = [move owner];\n', '') + text = text.replace(' let (part) = array.unpack(move items);\n', '') + p.write_text(text.replace('Maybe::some(move part)', 'Maybe::some(move owner)')) + self.assertEqual([d['code'] for d in twins.errors(AJI, p)], ['E3002']) + with self.assertRaisesRegex(ValueError, 'audited source changed'): + self.verify_fake(row) + + def test_same_swap_leak_on_other_arm_cannot_replace_audited_branch(self): + row = self.swap_pair() + row['match_type_declarations'] = True + self.pin_pair_context(row) + self.verify_fake(row) + p = self.corpus / 's.aji' + text = p.read_text() + start = text.index(' match move old {') + end = text.index('\n }\n Maybe::none', start) + consuming = text[start:end] + text = text[:start] + ' return n; // diagnostic here' + text[end:] + leaking = ' return n; // diagnostic here\n }' + # Put the existing consumption on the none arm instead of the some arm. + index = text.index(' Maybe::none => {\n' + leaking) + text = text[:index] + text[index:].replace(leaking, consuming + '\n }', 1) + p.write_text(text) + self.assertEqual([d['code'] for d in twins.errors(AJI, p)], ['E3002']) + with self.assertRaisesRegex(ValueError, 'audited source changed'): + self.verify_fake(row) + def test_straight_line_loan_cannot_replace_audited_handoff(self): row = self.audited_cfg_pair() self.verify_fake(row) diff --git a/tools/source_reject_twins.py b/tools/source_reject_twins.py index a319363..addd4c1 100644 --- a/tools/source_reject_twins.py +++ b/tools/source_reject_twins.py @@ -215,7 +215,7 @@ def site_key(source, d, site): return 'declaration' -def identity_class(air, d, value): +def identity_class(air, d, value, allow_swapped_enum=False): """Root constructor/producer class, not a second AIR type checker. This also intentionally merges the same exclusive-alias rule against @@ -252,6 +252,8 @@ def identity_class(air, d, value): return 'borrow' if op in producers: return producers[op] + if op == 'value.swap' and allow_swapped_enum: + return swapped_enum_class(air, d, value) raise ValueError(f'unsupported identity producer: {op}') raise ValueError(f'identity has no audited definition: {value}') @@ -283,6 +285,30 @@ def function_declaration(air, name): return parameters, result.strip(), tuple(sorted({x.strip() for x in effects.split(',') if x.strip()})) +def swapped_enum_class(air, d, value): + # Only the reviewed E3002 value.swap result role is supported. Resolve a + # direct enum constructor; this is not a type/property derivation. + function = re.search(r'^fn @' + re.escape(d['function']) + r'\(.*?(?=^fn @|\Z)', + air, re.MULTILINE | re.DOTALL) + if not function: + raise ValueError('swapped enum lacks a defining function') + text = re.sub(r';[^\n]*', '', function[0]) + def definition(name): + definitions = re.findall(r'^\s*' + re.escape(name) + r'\s*=\s*([^\n]+)', + text, re.MULTILINE) + if len(definitions) != 1: + raise ValueError('swapped enum lacks a unique direct definition') + return definitions[0].strip() + swap = re.fullmatch(r'value\.swap (%[A-Za-z0-9_]+), (%[A-Za-z0-9_]+)', definition(value)) + if not swap: + raise ValueError('unsupported swapped enum result') + replacement = re.fullmatch(r'enum\.make (@[A-Za-z][A-Za-z0-9_]*)\.[A-Za-z0-9_]+\([^\n]*\)', + definition(swap[2])) + if not replacement or not re.search(r'^type ' + re.escape(replacement[1]) + r' = enum \{', air, re.MULTILINE): + raise ValueError('swapped enum replacement lacks a named enum declaration') + return 'swap_enum ' + replacement[1] + + def identity_fact(air, d, field): if field == 'callee': # Parameter/result types do not decide the flat-effect rule. @@ -304,7 +330,8 @@ def identity_fact(air, d, field): return 'result_Send', result if field == 'argument' and d['code'] not in {'E4001', 'E4002'}: raise ValueError('unsupported argument identity rule') - return identity_class(air, d, d[field]) + return identity_class(air, d, d[field], + allow_swapped_enum=field == 'borrow' and d['code'] == 'E3002') def feature_header_facts(air, d):