tests: inventory and verify source rejection twins

This commit is contained in:
dev committed 2026-10-08 18:01:58 +03:00
1 parent 09fbf8a5bc
commit e4aacef48c
28 files changed
+1092 -8

No files matched your search

+2
View File
@@ -38,6 +38,8 @@ jobs:
- run: python3 tests/hosted/source_grammar.py
- run: python3 tests/hosted/source_effect_names.py
- run: python3 tests/hosted/source_cfg_provenance.py
- run: python3 tools/source_reject_twins.py
- run: python3 tests/hosted/source_reject_twins.py
- run: python3 tests/hosted/examples.py --stress 200
- run: python3 tests/hosted/source_static_functions.py
- run: python3 tests/hosted/source_linear.py
+2
View File
@@ -34,6 +34,8 @@ python3 tests/hosted/source_nominal_queries.py # deep shared types, deterministi
python3 tests/hosted/source_grammar.py # syntax boundaries, canonical enum lists and formatter/AIR fidelity
python3 tests/hosted/source_effect_names.py # effect-name errors, signature priority and package provenance
python3 tests/hosted/source_cfg_provenance.py # resource handoff, loan origins and source/package/AIR diagnostics
python3 tools/source_reject_twins.py # audited same-code pairs and exhaustive, explicitly incomplete AIR inventory
python3 tests/hosted/source_reject_twins.py # false-pair, mapping and inventory regression probes
python3 tests/hosted/examples.py --stress 200 # all examples/packages, wire bytes, partial I/O and source/AIR schedules
python3 tests/hosted/source_static_functions.py # explicit operations, effects, nominal policy identity and workers
python3 tests/hosted/source_linear.py # whole-value owners, canonical AIR and CLI errors
+6
View File
@@ -380,3 +380,9 @@ An ordinary function declaring `effects [bogus.effect]` reaches AIR and reports
P6-7 rejection-twin work reproduced accepted source that returns the cancelled handle from an inner block, ends its lent borrow at that block's exit, then joins the renamed handle. Ordinary AIR `br` has the same defect: loans and creating scopes remain attached to the moved SSA value. Review also reproduced lost guard parents and shield order. These violate existing spec 04 §33–§34, §37.3 and §40; they are verifier bugs, not missing transfer semantics.
**Resolved (DD-024):** resource relations follow simultaneous edge renaming, with a finite worklist covering later predecessors and backedges. Loans retain the creating spawn; tasks retain scope associations even when only the scope is passed. Guard parents and ordered shield relations survive handoff. Task/guard facts merge by union; shield stacks retain their existing exact join requirement. Existing codes E4302/E4101/E4301/E2102/E4305/E3002 apply. Valid correlated scope/task permutations and joins remain accepted. Runtime, source lowering and AIR format-0 meanings are unchanged; previously accepted violations now reject.
## Q-053 — P6-7's literal same-code exit criterion and the source boundary
P6-7 requires every conformance rejection to have a source twin with the same code. Spec 15 §10 instead requires fully source-decided type errors to use E7xxx, and malformed generated AIR/SSA/CFG to report E7900 as compiler defects. Spec 15 §1/§9 also makes SSA, CFG, local placement, lexical borrow ends and feature headers generated mechanics. Examples: AIR lossy widening is E1002 but source is E7005; missing borrow-return `from` is E2102 in AIR but E7006 in source (§19); explicit branch arity, unsupported AIR versions and duplicate feature headers have no source operation. Uninitialized locals and deliberately invalid proven-index fact forms likewise have no implemented source spelling.
The exhaustive inventory in `tools/source_reject_twins.py` keeps these rows visible: same-code pairs, audited source-error analogues, AIR-only cases and pending audits. Only verified same-code pairs satisfy the current criterion; the other categories are not exclusions or completion evidence. The owner needs to decide how the final phase review should account for mandatory E7xxx translation and generated-only AIR defects, without weakening existing AIR tests, exposing raw mechanics in source, or changing diagnostics solely to satisfy coverage. Until then the original criterion and P6-7's doing status remain unchanged; unreviewed and authorable twins can still be completed.
+8
View File
@@ -309,3 +309,11 @@ Validation: units and Zig formatting pass; full conformance is 1,618/1,618, and
Rejection-twin work exposed accepted source that ended a task loan after cancelled-handle transfer through a block parameter. DD-024 resolves Q-052: task loans/scopes, guard parents and shield order now follow simultaneous CFG transfers, with a fixed point for later predecessors and backedges. Existing concurrency invariants and diagnostic codes apply; interpreter behavior and valid source lowering are unchanged. This enforces existing AIR format-0 rules, with no new source concept, syntax or feature.
Validation: units and Zig formatting pass; full conformance is 1,642/1,642. All 24 new AIR/source fixtures pass schedule stress and collection before every instruction. A counted 63-handle rotation test verifies convergence and retained spawn provenance. CLI integration passes 146 checks, including exact source/package/generic positions, three loan rejection twins and both correlated scope/task permutations; existing related-location and lifetime suites pass 349/188 checks. Old/new comparison changes zero diagnostics on 1,327 existing public sources and 338 AIR files, preserving all 715 old source lowerings. Claude wrote independent regressions and reviewed the implementation with additional loop/permutation/cancellation probes. Source bundle size is unchanged; AIR growth is recorded in docs/agent/README.md. The exhaustive rejection-twin inventory and P6-7 remain open.
## P6-7 exhaustive rejection inventory (2026-10-08)
`tools/source_reject_twins.py` discovers all 199 public AIR rejection files, including new tests without manual metadata. The audited manifest verifies 27 same-code pairs: 13 new source fixtures, three existing source links and 11 existing lifetime/CFG pairs. It also records four mandatory E7xxx analogues and 15 cases without an implemented source spelling; these remain unmet rows alongside 153 pending audits. Q-053 records the conflict between the literal same-code criterion and spec 15's source boundary. The criterion and P6-7's doing status are unchanged; `--require-complete` fails.
Pairs compare operation/site, resource family, identity roles and stable rule facts, then independently check marked primary/related source positions against canonical AIR annotations. Early declaration errors and function budget sites have explicit checks; raw errors use spec 15 §10's exact duplicate projection. Cancellation witnesses preserve the reviewed regression context. Manual rule audits remain necessary. CI runs both the partial checker and 21 negative/positive checker regressions, including wrong operation, ordering, resource family, source position, related role and cancellation context. No compiler, verifier, runtime, normative rule, diagnostic code or reference bundle changes.
Validation: unit tests and Zig formatting pass; full conformance is 1,655/1,655. All 13 new source fixtures pass collection before every instruction. The pair checker verifies 27/199 and reports incomplete coverage; its completion gate rejects that inventory. Existing borrow-return, related-position and source-coverage checks pass (133, 355 and 121/121 respectively). Claude independently audited Phase 0–1 cases and reviewed the checker; its false-pair findings are covered by regression probes.
+12
View File
@@ -42,6 +42,18 @@ A key is a single lowercase word; header lines without a `key:` prefix are free-
`reject` compares the exact multiset of error codes. Listing a code twice means two diagnostics with that code are expected.
## AIR/source rejection twins (P6-7)
`python3 tools/source_reject_twins.py` checks audited pairs declared by free-form `// AIR twin: <path>` 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. The small declaration/producer lookup fails closed on unsupported forms; it 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. Several raw diagnostics at one source construct use the first-per-code/location projection required by spec 15 §10. Budget headers use the marked source declaration and matching canonical function name, since `--annotate` exposes block/instruction spans. 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. 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.
`--inventory` emits every current AIR rejection as JSON, including newly added unreviewed tests. Its `verification: metadata_only` output does not claim compiled verification. Rows are `same_code`, `source_error` (an audited E7xxx analogue), `air_only` (not authorable in the implemented source) or `pending`. The latter three remain unmet same-code rows. A successful ordinary check verifies the audited pairs against these checks; it does not prove P6-7 complete. `--require-complete` additionally fails until every AIR rejection has a verified same-code twin. Classification is a documented manual audit, not an automatic proof that a rule is inexpressible in source; the phase's literal exit criterion remains unchanged pending Q-053.
`python3 tests/hosted/source_reject_twins.py` exercises false-pair detection, independent source markers, raw diagnostic projection, early declarations and automatic discovery of pending cases.
## Outcomes
| Outcome | Meaning |
+313
View File
@@ -0,0 +1,313 @@
{
"version": 1,
"cases": {
"phase0/reject/block_argument_type.air": {
"kind": "air_only",
"spec": "docs/spec/15-source-language.md \u00a71",
"rule": "Explicit block arguments are generated mechanics. A wrong generated argument type is a compiler defect, not authorable source."
},
"phase0/reject/branch_arity.air": {
"kind": "air_only",
"spec": "docs/spec/15-source-language.md \u00a71",
"rule": "Explicit target argument arity is generated mechanics; malformed lowered targets are compiler defects."
},
"phase0/reject/call_argument_type.air": {
"kind": "source_error",
"spec": "docs/spec/15-source-language.md \u00a710",
"rule": "The source type/signature rule rejects before AIR verification, using its prescribed E7xxx code; this does not satisfy the same-code criterion.",
"analogues": [
{
"source": "source/typecheck/call_argument.aji",
"codes": [
"E7005"
],
"fields": {
"expected": "u64",
"found": "bool"
}
}
]
},
"phase0/reject/double_definition.air": {
"kind": "air_only",
"spec": "docs/spec/15-source-language.md \u00a71",
"rule": "SSA definition identity is generated; source shadowing is a different name rule."
},
"phase0/reject/duplicate_feature.air": {
"kind": "air_only",
"spec": "docs/spec/15-source-language.md \u00a79",
"rule": "Source does not declare an AIR features header; lowering generates its closure."
},
"phase0/reject/lossy_widen.air": {
"kind": "source_error",
"spec": "docs/spec/15-source-language.md \u00a710",
"rule": "The source type/signature rule rejects before AIR verification, using its prescribed E7xxx code; this does not satisfy the same-code criterion.",
"analogues": [
{
"source": "source/typecheck/lossy_widen.aji",
"codes": [
"E7005"
],
"fields": {}
}
]
},
"phase0/reject/missing_dependency.air": {
"kind": "air_only",
"spec": "docs/spec/15-source-language.md \u00a79",
"rule": "Source does not declare an AIR features header; lowering generates its closure."
},
"phase0/reject/missing_terminator.air": {
"kind": "air_only",
"spec": "docs/spec/15-source-language.md \u00a71",
"rule": "Block terminators are generated, and malformed lowered CFG is a compiler defect."
},
"phase0/reject/operand_type_mismatch.air": {
"kind": "source_error",
"spec": "docs/spec/15-source-language.md \u00a710",
"rule": "The source type/signature rule rejects before AIR verification, using its prescribed E7xxx code; this does not satisfy the same-code criterion.",
"analogues": [
{
"source": "source/typecheck/binary_mixed_widths.aji",
"codes": [
"E7005"
],
"fields": {
"expected": "u64",
"found": "u8"
}
}
]
},
"phase0/reject/recursive_type.air": {
"kind": "same_code",
"site": "declaration",
"spec": "docs/spec/15-source-language.md \u00a71",
"rule": "Node contains itself by value; source declaration validation retains E1003 (Q-043/Q-044).",
"lowering": "rejected"
},
"phase0/reject/terminator_mid_block.air": {
"kind": "air_only",
"spec": "docs/spec/15-source-language.md \u00a71",
"rule": "Instruction placement after an AIR terminator is generated CFG structure."
},
"phase0/reject/too_many_params.air": {
"kind": "same_code",
"site": "function",
"spec": "docs/spec/08-verifier.md",
"rule": "The same deterministic budget is exceeded, with identical limit/max/found/type facts."
},
"phase0/reject/unknown_block.air": {
"kind": "air_only",
"spec": "docs/spec/15-source-language.md \u00a71",
"rule": "Source has no named AIR block targets; generated resolution failure is a compiler defect."
},
"phase0/reject/unknown_feature.air": {
"kind": "air_only",
"spec": "docs/spec/15-source-language.md \u00a79",
"rule": "Source does not declare an AIR features header; lowering generates its closure."
},
"phase0/reject/unsupported_version.air": {
"kind": "air_only",
"spec": "docs/spec/15-source-language.md \u00a71",
"rule": "Source has no AIR format-version header."
},
"phase0/reject/use_not_dominated.air": {
"kind": "air_only",
"spec": "docs/spec/15-source-language.md \u00a71",
"rule": "Source has no explicit SSA dominance edges; malformed generated uses are compiler defects."
},
"phase1/reject/alloc_outside_entry.air": {
"kind": "air_only",
"spec": "docs/spec/15-source-language.md \u00a71",
"rule": "local.alloc placement is chosen by lowering; source has no instruction-placement operation."
},
"phase1/reject/borrow_return_without_from.air": {
"kind": "source_error",
"spec": "docs/spec/15-source-language.md \u00a719",
"rule": "The source type/signature rule rejects before AIR verification, using its prescribed E7xxx code; this does not satisfy the same-code criterion.",
"analogues": [
{
"source": "source/borrow_returns/missing_from.aji",
"codes": [
"E7006"
],
"fields": {
"reason": "invalid_borrow_return"
}
}
]
},
"phase1/reject/feature_not_declared.air": {
"kind": "air_only",
"spec": "docs/spec/15-source-language.md \u00a79",
"rule": "Source does not declare an AIR features header; lowering generates its closure."
},
"phase1/reject/frame_escape.air": {
"kind": "same_code",
"site": "instruction",
"spec": "docs/spec/08-verifier.md \u00a711.3",
"rule": "A returned borrow points into local frame storage, despite the declared parameter origin."
},
"phase1/reject/frame_too_large.air": {
"kind": "same_code",
"site": "function",
"spec": "docs/spec/08-verifier.md",
"rule": "The same deterministic budget is exceeded, with identical limit/max/found/type facts."
},
"phase1/reject/le_is_not_a_fact.air": {
"kind": "air_only",
"spec": "docs/spec/15-source-language.md \u00a75",
"rule": "A source <= condition uses checked indexing; only the specified strict < bounds form requests proven indexing."
},
"phase1/reject/mut_and_shared.air": {
"kind": "same_code",
"site": "instruction",
"spec": "docs/spec/08-verifier.md \u00a711.2",
"rule": "A shared whole-place borrow is created while an exclusive whole-place borrow is live."
},
"phase1/reject/read_uninitialized.air": {
"kind": "air_only",
"spec": "docs/spec/15-source-language.md \u00a74",
"rule": "Source local declarations require an initializer; there is no uninitialized frame-local declaration."
},
"phase1/reject/size_overflow.air": {
"kind": "same_code",
"site": "function",
"spec": "docs/spec/08-verifier.md",
"rule": "The same deterministic budget is exceeded, with identical limit/max/found/type facts."
},
"phase1/reject/value_too_large.air": {
"kind": "same_code",
"site": "function",
"spec": "docs/spec/08-verifier.md",
"rule": "The same deterministic budget is exceeded, with identical limit/max/found/type facts."
},
"phase2/reject/own_free_while_borrowed.air": {
"kind": "same_code",
"site": "instruction",
"spec": "docs/spec/03-memory-model.md",
"rule": "The same owning-resource consumption or whole-place borrow conflicts with a live borrow."
},
"phase2/reject/own_use_after_free.air": {
"kind": "same_code",
"site": "instruction",
"spec": "docs/spec/03-memory-model.md",
"rule": "A closed/freed resource is borrowed again."
},
"phase2/reject/region_destroy_with_live_reference.air": {
"kind": "same_code",
"site": "instruction",
"spec": "docs/spec/03-memory-model.md",
"rule": "The same region operation would invalidate a live allocation reference."
},
"phase2/reject/region_leak.air": {
"kind": "same_code",
"site": "instruction",
"spec": "docs/spec/06-resources-and-errors.md \u00a76.3",
"rule": "An owned region reaches return without region.destroy."
},
"phase2/reject/region_reset_with_live_reference.air": {
"kind": "same_code",
"site": "instruction",
"spec": "docs/spec/03-memory-model.md",
"rule": "The same region operation would invalidate a live allocation reference."
},
"phase2/reject/resource_close_twice_after_error.air": {
"kind": "same_code",
"site": "instruction",
"spec": "docs/spec/06-resources-and-errors.md",
"rule": "The same resource is consumed twice."
},
"phase2/reject/resource_close_while_borrowed.air": {
"kind": "same_code",
"site": "instruction",
"spec": "docs/spec/06-resources-and-errors.md",
"rule": "The same owning-resource consumption or whole-place borrow conflicts with a live borrow."
},
"phase2/reject/resource_join_mismatch.air": {
"kind": "same_code",
"site": "block",
"spec": "docs/spec/08-verifier.md \u00a711.4",
"rule": "The same file is closed on one incoming edge and still live on another."
},
"phase2/reject/resource_use_after_close.air": {
"kind": "same_code",
"site": "instruction",
"spec": "docs/spec/06-resources-and-errors.md",
"rule": "A closed/freed resource is borrowed again."
},
"phase3/reject/cancel_join_keeps_loans.air": {
"kind": "same_code",
"site": "instruction",
"spec": "docs/spec/04-concurrency-and-atomics.md",
"rule": "The lent borrow is ended while its task remains unjoined; the creating spawn is retained.",
"required_ops": {
"task.join.cancel": 1
}
},
"phase3/reject/cancel_join_twice_keeps_spawn.air": {
"kind": "same_code",
"site": "instruction",
"spec": "docs/spec/04-concurrency-and-atomics.md",
"rule": "The lent borrow is ended while its task remains unjoined; the creating spawn is retained.",
"required_ops": {
"task.join.cancel": 2
}
},
"phase3/reject/tasks_end_lent_borrow.air": {
"kind": "same_code",
"site": "instruction",
"spec": "docs/spec/04-concurrency-and-atomics.md",
"rule": "The lent borrow is ended while its task remains unjoined; the creating spawn is retained."
},
"phase4/reject/arc_release_twice.air": {
"kind": "same_code",
"site": "instruction",
"spec": "docs/spec/03-memory-model.md",
"rule": "The same resource is consumed twice."
},
"phase4/reject/frozen_leak.air": {
"kind": "same_code",
"site": "instruction",
"spec": "docs/spec/03-memory-model.md \u00a723",
"rule": "An owned frozen graph reaches return without frozen.release."
},
"phase4/reject/island_use_after_freeze.air": {
"kind": "same_code",
"site": "instruction",
"spec": "docs/spec/03-memory-model.md",
"rule": "An island is borrowed after freezing transferred its ownership."
},
"phase5/reject/cmpxchg_failure_release.air": {
"kind": "same_code",
"site": "instruction",
"spec": "docs/spec/04-concurrency-and-atomics.md",
"rule": "The same atomic operation rejects the same ordering and allowed set."
},
"phase5/reject/fence_relaxed.air": {
"kind": "same_code",
"site": "instruction",
"spec": "docs/spec/04-concurrency-and-atomics.md",
"rule": "The same atomic operation rejects the same ordering and allowed set."
},
"phase5/reject/load_release.air": {
"kind": "same_code",
"site": "instruction",
"spec": "docs/spec/04-concurrency-and-atomics.md",
"rule": "The same atomic operation rejects the same ordering and allowed set."
},
"phase5/reject/store_acquire.air": {
"kind": "same_code",
"site": "instruction",
"spec": "docs/spec/04-concurrency-and-atomics.md",
"rule": "The same atomic operation rejects the same ordering and allowed set."
},
"phase5/reject/take_while_borrowed.air": {
"kind": "same_code",
"site": "instruction",
"spec": "docs/spec/04-concurrency-and-atomics.md",
"rule": "The same owning-resource consumption or whole-place borrow conflicts with a live borrow."
}
}
}
@@ -1,6 +1,7 @@
// expect: reject E2108
// phase: 6
// spec: docs/spec/15-source-language.md §19
// AIR twin: phase1/reject/frame_escape.air
module test.returned_views
fn bad(p: ref<u64>) -> ref<u64> from p effects [] { let n = 1u64; ref r = n; return r; }
fn bad(p: ref<u64>) -> ref<u64> from p effects [] { let n = 1u64; ref r = n; return r; } // diagnostic here: return
fn main() -> u64 effects [] { return 0u64; }
@@ -2,5 +2,5 @@
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn bad(p: ref<u64>) -> ref<u64> effects [] { return p; }
fn bad(p: ref<u64>) -> ref<u64> effects [] { return p; } // diagnostic here: fn bad
fn main() -> u64 effects [] { return 0u64; }
@@ -1,10 +1,11 @@
// The verifier, not the frontend, rejects a struct that contains itself by value (E1003).
// A by-value cycle retains E1003 in source declaration validation.
// expect: reject E1003
// phase: 6
// spec: docs/spec/15-source-language.md
// AIR twin: phase0/reject/recursive_type.air
module demo.recursive
struct Node {
struct Node { // diagnostic here
value: u64,
next: Node,
}
@@ -2,6 +2,7 @@
// expect: reject E2101
// phase: 6
// spec: docs/spec/15-source-language.md
// AIR twin: phase1/reject/mut_and_shared.air
module demo.conflict
fn main() -> u64
@@ -9,6 +10,6 @@ effects []
{
var buf: [u64; 2] = zero;
mut a = buf;
ref b = buf;
ref b = buf; // diagnostic here: ref
return 0;
}
@@ -0,0 +1,13 @@
// expect: reject E2002
// phase: 6
// spec: docs/spec/03-memory-model.md §24
// AIR twin: phase4/reject/arc_release_twice.air
module test.twins.arc_release_twice
fn main(heap: cap<mem.alloc>) -> void effects [mem.alloc] {
let i = island.create(1u64, heap) or trap;
let f = island.freeze(move i);
let a = arc.from_frozen(move f);
arc.release(move a);
arc.release(move a); // diagnostic here: arc.release
}
@@ -0,0 +1,12 @@
// expect: reject E4201
// phase: 6
// spec: docs/spec/04-concurrency-and-atomics.md
// AIR twin: phase5/reject/cmpxchg_failure_release.air
// The historical AIR filename says release; its rejected failure order is acq_rel.
module test.twins.cmpxchg_failure_acq_rel
fn main() -> void effects [atomic, atomic.weak] {
let c = atomic.new(1u64);
let (old, changed) = atomic.compare_exchange(ref c, 1u64, 2u64, acq_rel, acq_rel); // diagnostic here: let
let n = atomic.take(move c);
}
@@ -0,0 +1,9 @@
// expect: reject E4201
// phase: 6
// spec: docs/spec/04-concurrency-and-atomics.md
// AIR twin: phase5/reject/fence_relaxed.air
module test.twins.fence_relaxed
fn main() -> void effects [atomic, atomic.weak] {
atomic.fence(relaxed); // diagnostic here: atomic.fence
}
@@ -0,0 +1,16 @@
// expect: reject E5101
// phase: 6
// spec: docs/spec/08-verifier.md §3
// AIR twin: phase1/reject/frame_too_large.air
module test.twins.frame_too_large
fn unused() -> void effects [] { // diagnostic here: fn unused
var a: [u8; 409600] = zero;
var b: [u8; 409600] = zero;
var c: [u8; 409600] = zero;
ref av = a;
ref bv = b;
ref cv = c;
}
fn main() -> void effects [] {}
@@ -0,0 +1,11 @@
// expect: reject E3002
// phase: 6
// spec: docs/spec/03-memory-model.md §23
// AIR twin: phase4/reject/frozen_leak.air
module test.twins.frozen_leak
fn main(heap: cap<mem.alloc>) -> void effects [mem.alloc] {
let i = island.create(1u64, heap) or trap;
let f = island.freeze(move i);
return; // diagnostic here: return
}
@@ -0,0 +1,14 @@
// expect: reject E2001
// phase: 6
// spec: docs/spec/03-memory-model.md §23
// AIR twin: phase4/reject/island_use_after_freeze.air
module test.twins.island_use_after_freeze
fn main(heap: cap<mem.alloc>) -> void effects [mem.alloc] {
let i = island.create(1u64, heap) or trap;
let f = island.freeze(move i);
{
ref view = i; // diagnostic here: ref
}
frozen.release(move f);
}
@@ -0,0 +1,11 @@
// expect: reject E4201
// phase: 6
// spec: docs/spec/04-concurrency-and-atomics.md
// AIR twin: phase5/reject/load_release.air
module test.twins.load_release
fn main() -> void effects [atomic, atomic.weak] {
let c = atomic.new(1u64);
atomic.load(ref c, release); // diagnostic here: atomic.load
let n = atomic.take(move c);
}
@@ -0,0 +1,10 @@
// expect: reject E3002
// phase: 6
// spec: docs/spec/03-memory-model.md §8
// AIR twin: phase2/reject/region_leak.air
module test.twins.region_leak
fn main(heap: cap<mem.alloc>) -> void effects [mem.alloc] {
let r = region.create(heap) or trap;
return; // diagnostic here: return
}
@@ -0,0 +1,9 @@
// expect: reject E5101
// phase: 6
// spec: docs/spec/08-verifier.md §3
// AIR twin: phase1/reject/size_overflow.air
module test.twins.size_overflow
fn unused(data: [[u64; 4294967296]; 4294967296]) -> void effects [] {} // diagnostic here: fn unused
fn main() -> void effects [] {}
@@ -0,0 +1,11 @@
// expect: reject E4201
// phase: 6
// spec: docs/spec/04-concurrency-and-atomics.md
// AIR twin: phase5/reject/store_acquire.air
module test.twins.store_acquire
fn main() -> void effects [atomic, atomic.weak] {
let c = atomic.new(1u64);
atomic.store(ref c, 2u64, acquire); // diagnostic here: atomic.store
let n = atomic.take(move c);
}
@@ -0,0 +1,11 @@
// expect: reject E2101
// phase: 6
// spec: docs/spec/04-concurrency-and-atomics.md
// AIR twin: phase5/reject/take_while_borrowed.air
module test.twins.take_while_borrowed
fn main() -> void effects [atomic] {
let c = atomic.new(1u64);
ref view = c;
let n = atomic.take(move c); // diagnostic here: atomic.take
}
@@ -0,0 +1,9 @@
// expect: reject E5101
// phase: 6
// spec: docs/spec/08-verifier.md §3
// AIR twin: phase0/reject/too_many_params.air
module test.twins.too_many_params
fn unused(x0: u64, x1: u64, x2: u64, x3: u64, x4: u64, x5: u64, x6: u64, x7: u64, x8: u64, x9: u64, x10: u64, x11: u64, x12: u64, x13: u64, x14: u64, x15: u64, x16: u64, x17: u64, x18: u64, x19: u64, x20: u64, x21: u64, x22: u64, x23: u64, x24: u64, x25: u64, x26: u64, x27: u64, x28: u64, x29: u64, x30: u64, x31: u64, x32: u64, x33: u64, x34: u64, x35: u64, x36: u64, x37: u64, x38: u64, x39: u64, x40: u64, x41: u64, x42: u64, x43: u64, x44: u64, x45: u64, x46: u64, x47: u64, x48: u64, x49: u64, x50: u64, x51: u64, x52: u64, x53: u64, x54: u64, x55: u64, x56: u64, x57: u64, x58: u64, x59: u64, x60: u64, x61: u64, x62: u64, x63: u64, x64: u64) -> void effects [] {} // diagnostic here: fn unused
fn main() -> void effects [] {}
@@ -0,0 +1,9 @@
// expect: reject E5101
// phase: 6
// spec: docs/spec/08-verifier.md §3
// AIR twin: phase1/reject/value_too_large.air
module test.twins.value_too_large
fn unused(data: [u8; 1048577]) -> void effects [] {} // diagnostic here: fn unused
fn main() -> void effects [] {}
@@ -9,5 +9,5 @@ effects []
{
let a = 1u8;
let b = 2u64;
b + a
b + a // diagnostic here: a
}
@@ -13,5 +13,5 @@ effects []
fn main() -> u64
effects []
{
f(true)
f(true) // diagnostic here: true)
}
@@ -8,5 +8,5 @@ fn main() -> u8
effects []
{
let big: u64 = 1;
return big as u8;
return big as u8; // diagnostic here: big as u8
}
+187
View File
@@ -0,0 +1,187 @@
#!/usr/bin/env python3
"""Independent failure probes for the rejection-twin coverage check."""
import importlib.util
import json
import re
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[2]
spec = importlib.util.spec_from_file_location('source_reject_twins', ROOT / 'tools/source_reject_twins.py')
twins = importlib.util.module_from_spec(spec)
spec.loader.exec_module(twins)
AJI = ROOT / 'zig-out/bin/aji'
REAL_CORPUS = twins.CORPUS
class CoverageFailures(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory(prefix='aji-twin-oracle-')
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.corpus = self.root / 'corpus'
self.corpus.mkdir()
self.manifest = self.corpus / 'reject-twins.json'
def fake_pair(self, source_name='fence_relaxed', air_name='fence_relaxed', source_path=None, air_path=None):
air = REAL_CORPUS / (air_path or f'phase5/reject/{air_name}.air')
source = REAL_CORPUS / (source_path or f'source/reject_twins/{source_name}.aji')
(self.corpus / 'a.air').write_text(air.read_text())
source_text = source.read_text()
source_text = re.sub(r'^// AIR twin: .+$', '// AIR twin: a.air', source_text, flags=re.MULTILINE)
(self.corpus / 's.aji').write_text(source_text)
rule = {'kind': 'same_code', 'site': 'instruction',
'spec': 'docs/spec/04-concurrency-and-atomics.md §24',
'rule': 'Test audit; the executable check must still reject mismatched rules.'}
self.manifest.write_text(json.dumps({'version': 1, 'cases': {'a.air': rule}}))
return {'air': 'a.air', 'sources': ['s.aji'], 'codes': twins.codes(air), **rule}
def verify_fake(self, row):
with patch.object(twins, 'CORPUS', self.corpus):
twins.verify_pair(AJI, self.root, row, 's.aji')
def test_valid_pair_survives_changed_file_and_ssa_identity(self):
self.verify_fake(self.fake_pair())
def test_same_code_different_atomic_operation_is_not_a_twin(self):
row = self.fake_pair(air_name='load_release')
with self.assertRaisesRegex(ValueError, 'different offending operation/rule facts'):
self.verify_fake(row)
def test_same_operation_different_invalid_order_is_not_a_twin(self):
row = self.fake_pair(air_name='load_release', source_name='load_release')
p = self.corpus / 's.aji'
p.write_text(p.read_text().replace('ref c, release', 'ref c, acq_rel'))
with self.assertRaisesRegex(ValueError, 'different offending operation/rule facts'):
self.verify_fake(row)
def test_comment_cannot_spoof_a_leaked_resources_type(self):
row = self.fake_pair(source_path='source/reject_twins/frozen_leak.aji',
air_path='phase2/reject/region_leak.air')
p = self.corpus / 'a.air'
d, = twins.errors(AJI, p)
p.write_text(p.read_text().replace('entry:', 'entry:\n ; ' + d['borrow'] + ': frozen<u64>', 1))
with self.assertRaisesRegex(ValueError, 'different offending operation/rule facts'):
self.verify_fake(row)
def test_changed_related_role_cannot_survive_source_mapping(self):
row = self.fake_pair(source_path='source/layer34/reject/borrow_conflict.aji',
air_path='phase1/reject/mut_and_shared.air')
real_command = twins.command
def changed(aji, *args, status):
result = real_command(aji, *args, status=status)
if args[0] == 'check' and Path(args[1]) == self.corpus / 's.aji':
ds = [json.loads(line) for line in result.splitlines()]
ds[0]['related_locations'][0]['role'] = 'task_spawn'
return '\n'.join(json.dumps(d) for d in ds) + '\n'
return result
with patch.object(twins, 'command', changed):
with self.assertRaisesRegex(ValueError, 'mapping changed related roles'):
self.verify_fake(row)
def test_a_plain_loan_error_cannot_replace_a_cancelled_join_regression(self):
rows = twins.inventory()
row = next(r for r in rows if r['air'] == 'phase3/reject/cancel_join_keeps_loans.air')
with self.assertRaisesRegex(ValueError, 'missing required operation witness'):
twins.verify_pair(AJI, self.root, row, 'source/cfg_provenance/tasks_end_lent_borrow.aji')
def test_changed_analogue_reason_is_detected_independently(self):
rows = twins.inventory()
row = next(r for r in rows if r['air'] == 'phase1/reject/borrow_return_without_from.air')
analogue = {**row['analogues'][0], 'fields': {'reason': 'move_copy'}}
with self.assertRaisesRegex(ValueError, 'analogue rule facts changed'):
twins.verify_analogue(AJI, analogue)
def test_same_ret_and_leak_code_different_resource_family_is_not_a_twin(self):
row = self.fake_pair(source_path='source/reject_twins/frozen_leak.aji',
air_path='phase2/reject/region_leak.air')
with self.assertRaisesRegex(ValueError, 'different offending operation/rule facts'):
self.verify_fake(row)
def test_two_source_locations_cannot_be_dropped_as_one_raw_error(self):
row = self.fake_pair()
p = self.corpus / 's.aji'
text = p.read_text()
line = next(line for line in text.splitlines() if 'atomic.fence(relaxed)' in line)
p.write_text(text.replace(line, line + '\n' + line).replace('reject E4201', 'reject E4201 E4201'))
with self.assertRaisesRegex(ValueError, 'different offending operation/rule facts'):
self.verify_fake(row)
def test_block_site_cannot_pass_an_instruction_twin(self):
row = self.fake_pair()
row['site'] = 'block'
with self.assertRaisesRegex(ValueError, 'expected block label'):
self.verify_fake(row)
def test_ambiguous_marker_is_rejected_instead_of_selecting_first_token(self):
with self.assertRaisesRegex(ValueError, 'unique code fragment'):
twins.positions(' let x = x; // diagnostic here: x')
def test_markers_in_comments_are_not_source_sites(self):
self.assertEqual(twins.positions('// note // diagnostic here: note'), [])
def test_wrong_independent_source_marker_is_rejected(self):
row = self.fake_pair()
p = self.corpus / 's.aji'
p.write_text(p.read_text().replace('here: atomic.fence', 'here: relaxed'))
with self.assertRaisesRegex(ValueError, 'marked source positions'):
self.verify_fake(row)
def test_new_rejection_is_pending_without_any_manual_inventory_update(self):
self.fake_pair()
(self.corpus / 'new.air').write_text((self.corpus / 'a.air').read_text())
with patch.object(twins, 'CORPUS', self.corpus), patch.object(twins, 'MANIFEST', self.manifest):
rows = twins.inventory()
self.assertEqual([(r['air'], r['kind']) for r in rows], [('a.air', 'same_code'), ('new.air', 'pending')])
def test_air_only_cannot_hide_a_declared_source_twin(self):
self.fake_pair()
data = json.loads(self.manifest.read_text())
data['cases']['a.air']['kind'] = 'air_only'
self.manifest.write_text(json.dumps(data))
with patch.object(twins, 'CORPUS', self.corpus), patch.object(twins, 'MANIFEST', self.manifest):
with self.assertRaisesRegex(ValueError, 'lacks a same-code rule audit'):
twins.inventory()
def test_manual_review_cannot_override_discovered_pair_identity(self):
self.fake_pair()
data = json.loads(self.manifest.read_text())
data['cases']['a.air']['sources'] = []
self.manifest.write_text(json.dumps(data))
with patch.object(twins, 'CORPUS', self.corpus), patch.object(twins, 'MANIFEST', self.manifest):
with self.assertRaisesRegex(ValueError, 'reserved review keys'):
twins.inventory()
def test_deleted_air_rejection_is_not_silently_removed(self):
self.fake_pair()
(self.corpus / 'a.air').unlink()
with patch.object(twins, 'CORPUS', self.corpus), patch.object(twins, 'MANIFEST', self.manifest):
with self.assertRaisesRegex(ValueError, 'invalid corpus path'):
twins.inventory()
def test_duplicate_json_fields_do_not_survive_last_key_wins(self):
with self.assertRaisesRegex(ValueError, 'duplicate JSON member'):
twins.load_json('{"code":"E4201","code":"E7005"}')
def test_early_recursive_declaration_is_checked_without_claiming_lowered_air(self):
rows = twins.inventory()
row = next(r for r in rows if r['air'] == 'phase0/reject/recursive_type.air')
self.assertEqual(row['lowering'], 'rejected')
twins.verify_pair(AJI, self.root, row, row['sources'][0])
def test_one_source_array_borrow_keeps_first_raw_error_per_location(self):
rows = twins.inventory()
row = next(r for r in rows if r['air'] == 'phase1/reject/mut_and_shared.air')
twins.verify_pair(AJI, self.root, row, row['sources'][0])
def test_budget_header_uses_marked_function_not_instruction_annotation(self):
rows = twins.inventory()
row = next(r for r in rows if r['air'] == 'phase1/reject/frame_too_large.air')
self.assertEqual(row['site'], 'function')
twins.verify_pair(AJI, self.root, row, row['sources'][0])
if __name__ == '__main__':
unittest.main()
+406
View File
@@ -0,0 +1,406 @@
#!/usr/bin/env python3
"""Inventory every public AIR rejection and verify audited source twins.
Pending, source-error analogues and AIR-only cases remain unmet P6-7 rows.
Default: verify declared pairs and report incomplete coverage. --inventory:
JSON inventory without running the compiler. --require-complete: also fail
unless every AIR rejection has a verified same-code source twin.
"""
import argparse
from collections import Counter
import json
from pathlib import Path
import re
import subprocess
import sys
import tempfile
ROOT = Path(__file__).resolve().parents[1]
CORPUS = ROOT / 'tests/conformance'
MANIFEST = CORPUS / 'reject-twins.json'
IDENTITIES = {'function', 'block', 'inst', 'borrow', 'resource', 'task',
'conflicts_with', 'scope', 'guard', 'child', 'inner', 'local', 'from'}
ENVELOPE = {'code', 'kind', 'severity', 'file', 'line', 'col', 'air_line',
'air_col', 'message', 'related_locations'}
def unique(pairs):
out = {}
for key, value in pairs:
if key in out:
raise ValueError(f'duplicate JSON member: {key}')
out[key] = value
return out
def load_json(text):
return json.loads(text, object_pairs_hook=unique)
def codes(path):
prefix = ';' if path.suffix == '.air' else '//'
found = re.findall(r'^' + re.escape(prefix) + r' expect: reject (.+)$',
path.read_text(), re.MULTILINE)
if not found:
return None
if len(found) != 1:
raise ValueError(f'{path}: duplicate rejection header')
return found[0].split()
def corpus_path(name, suffix):
p = (CORPUS / name).resolve()
if not p.is_relative_to(CORPUS.resolve()) or p.suffix != suffix or not p.is_file():
raise ValueError(f'invalid corpus path: {name}')
return p
def inventory():
manifest = load_json(MANIFEST.read_text())
if manifest['version'] != 1:
raise ValueError('unsupported rejection-twin manifest version')
air = {str(p.relative_to(CORPUS)): codes(p) for p in sorted(CORPUS.rglob('*.air')) if codes(p)}
declared = {}
for p in sorted(CORPUS.rglob('*.aji')):
links = re.findall(r'^// AIR twin: (.+)$', p.read_text(), re.MULTILINE)
if len(links) != len(set(links)):
raise ValueError(f'{p}: duplicate AIR twin link')
for target in links:
corpus_path(target, '.air')
if target not in air or not codes(p):
raise ValueError(f'{p}: twin must name an AIR rejection and reject itself')
if Counter(air[target]) != Counter(codes(p)):
raise ValueError(f'{p}: declared source/AIR rejection codes differ')
declared.setdefault(target, []).append(str(p.relative_to(CORPUS)))
unknown = set(manifest['cases']) - set(air)
if unknown:
raise ValueError(f'manifest has missing/non-reject AIR cases: {sorted(unknown)}')
rows = []
for name, expected in air.items():
review = manifest['cases'].get(name)
sources = declared.get(name, [])
if sources and (review is None or review['kind'] != 'same_code'):
raise ValueError(f'{name}: declared twin lacks a same-code rule audit')
if review is None:
row = {'air': name, 'codes': expected, 'kind': 'pending', 'sources': []}
else:
allowed = {'kind', 'rule', 'spec', 'site', 'lowering', 'analogues', 'required_ops'}
if set(review) - allowed:
raise ValueError(f'{name}: unknown/reserved review keys: {sorted(set(review) - allowed)}')
witnesses = review.get('required_ops', {})
if not isinstance(witnesses, dict) or any(
not isinstance(op, str) or not op or
not isinstance(n, int) or isinstance(n, bool) or n < 1
for op, n in witnesses.items()):
raise ValueError(f'{name}: operation witness counts must be positive integers')
if review.get('lowering') not in {None, 'rejected'}:
raise ValueError(f'{name}: invalid lowering mode')
if review['kind'] not in {'same_code', 'source_error', 'air_only'}:
raise ValueError(f'{name}: invalid classification')
if not review.get('rule') or not review.get('spec'):
raise ValueError(f'{name}: missing rule/spec evidence')
spec = (ROOT / review['spec'].split(' §')[0]).resolve()
if not spec.is_relative_to((ROOT / 'docs/spec').resolve()) or not spec.is_file():
raise ValueError(f'{name}: invalid governing spec')
if review['kind'] == 'same_code':
if not sources or review.get('site') not in {'instruction', 'block', 'function', 'declaration'}:
raise ValueError(f'{name}: missing source/site')
elif sources:
raise ValueError(f'{name}: analogue/inexpressible case cannot count as a twin')
if review['kind'] == 'source_error' and not review.get('analogues'):
raise ValueError(f'{name}: source-error classification needs an analogue')
for analogue in review.get('analogues', []):
if not analogue.get('codes') or any(not re.fullmatch(r'E7[0-9]{3}', c) for c in analogue['codes']):
raise ValueError(f'{name}: source-error analogue must use E7xxx')
p = corpus_path(analogue['source'], '.aji')
if Counter(codes(p) or []) != Counter(analogue['codes']):
raise ValueError(f'{name}: analogue header does not match')
row = {'air': name, 'codes': expected, 'sources': sources, **review}
rows.append(row)
return rows
def command(aji, *args, status):
p = subprocess.run([str(aji), *map(str, args)], capture_output=True, text=True)
if p.returncode != status:
raise ValueError(f'{args}: expected exit {status}, got {p.returncode}: {p.stdout} {p.stderr}')
return p.stdout
def errors(aji, path):
ds = [load_json(line) for line in command(aji, 'check', path, status=1).splitlines()]
if not ds or any(d.get('severity') != 'error' for d in ds):
raise ValueError(f'{path}: expected error records only')
if Counter(d['code'] for d in ds) != Counter(codes(path) or []):
raise ValueError(f'{path}: diagnostics do not match rejection header')
return ds
def payload(d):
# Compare stable rule facts independently of spelling, prose and locations.
return {k: v for k, v in d.items() if k not in ENVELOPE | IDENTITIES}
def operation(line):
line = line.strip()
if '=' in line and line.startswith('%'):
line = line.split('=', 1)[1].strip()
op = line.split()[0]
if op == 'intrinsic':
op += ' ' + line.split()[1].split('(', 1)[0]
return op
def site_key(source, d, site):
lines = source.splitlines()
if not (1 <= d['line'] <= len(lines)) or d['col'] < 1:
raise ValueError('diagnostic coordinates outside AIR')
line = lines[d['line'] - 1].strip()
if site == 'instruction':
if line.endswith(':') or line.startswith(('fn ', 'type ', ';')):
raise ValueError(f'expected instruction, got {line}')
return operation(line)
if site == 'block':
if not line.endswith(':'):
raise ValueError(f'expected block label, got {line}')
return 'block'
if site == 'function':
if not line.startswith('fn '):
raise ValueError(f'expected function declaration, got {line}')
return 'function'
if not line.startswith('type '):
raise ValueError(f'expected type declaration, got {line}')
return 'declaration'
def identity_class(air, d, value):
"""Root constructor/producer class, not a second AIR type checker.
This also intentionally merges the same exclusive-alias rule against
shared or exclusive borrows. Content types do not distinguish the same
whole-resource/loan rule:
own<u8>/own<u64> are owners, and ref/slice forms are borrows. Resource
families (region/frozen/own/file<read>/...) must remain distinct.
Unsupported producers fail closed and need a reviewed extension.
"""
function = re.search(r'^fn @' + re.escape(d['function']) + r'\(.*?(?=^fn @|\Z)', air, re.MULTILINE | re.DOTALL)
if not function or not isinstance(value, str) or not value.startswith('%'):
raise ValueError('identity has no defining function/value')
text = function[0]
for line in text.splitlines():
line = line.split(';', 1)[0].strip()
if not (line.startswith('fn @') or re.fullmatch(r'[^\s(]+\(.*\):', line)):
continue
typed = re.search(re.escape(value) + r':\s*([@A-Za-z_][\w.]*)(<[^\s,)]*>)?', line)
if typed:
root, suffix = typed.groups()
if root in {'ref', 'mut', 'slice', 'slice_mut'}:
return 'borrow'
return root + (suffix or '') if root in {'file', 'cap'} else root
producers = {'local.alloc': 'local', 'atomic.new': 'atomic', 'mutex.make': 'mutex',
'island.freeze': 'frozen', 'arc.from_frozen': 'arc', 'arc.clone': 'arc',
'task.spawn': 'task', 'task.scope.begin': 'scope', 'task.shield.begin': 'shield'}
for line in text.splitlines():
definition = re.match(r'\s*(%[^=]+?)\s*=\s*([\w.]+)', line)
if definition and value in [x.strip() for x in definition[1].split(',')]:
op = definition[2]
if op.startswith('borrow.') or op in {'slice.make', 'slice.sub', 'slice.split', 'buffer.view'}:
return 'borrow'
if op in producers:
return producers[op]
raise ValueError(f'unsupported identity producer: {op}')
raise ValueError(f'identity has no audited definition: {value}')
def positions(source):
marked = []
for line_no, line in enumerate(source.splitlines(), 1):
match = re.fullmatch(r'(.+?)\s+// diagnostic here(?:: (.+))?', line)
if not match or match[1].lstrip().startswith('//'):
continue
code, token = match.groups()
if token:
matches = [m.start() for m in re.finditer(re.escape(token), code)]
if len(matches) != 1:
raise ValueError('position marker must identify a unique code fragment')
index = matches[0]
else:
index = len(code) - len(code.lstrip())
marked.append((line_no, len(line[:index].encode('utf-8')) + 1))
return marked
def signature(air, d, site):
return (d['code'], d['kind'], site_key(air, d, site),
tuple(sorted((k, identity_class(air, d, d[k])) for k in (IDENTITIES - {'function', 'block', 'inst'}) & d.keys())),
tuple(x['role'] for x in d.get('related_locations', [])),
json.dumps(payload(d), sort_keys=True))
def annotation_map(annotated):
lines, mapping, pending = [], {}, None
for line in annotated.splitlines():
match = re.fullmatch(r'\s*; (?:(.+):)?(\d+):(\d+)-\d+:\d+', line)
if match:
pending = (match[1], int(match[2]), int(match[3]))
else:
lines.append(line)
mapping[len(lines)] = pending
pending = None
return '\n'.join(lines) + '\n', mapping
def operation_witnesses(air, diagnostics, required):
for d in diagnostics:
function = re.search(r'^fn @' + re.escape(d['function']) + r'\(.*?(?=^fn @|\Z)', air, re.MULTILINE | re.DOTALL)
if not function:
raise ValueError('operation witness has no diagnostic function')
counts = Counter()
for line in function[0].splitlines():
line = line.split(';', 1)[0].strip()
if line and not line.startswith(('fn ', 'effects ')) and not line.endswith(':'):
counts[operation(line)] += 1
if any(counts[op] < minimum for op, minimum in required.items()):
raise ValueError('missing required operation witness in diagnostic function')
def verify_pair(aji, root, row, source):
air_path = CORPUS / row['air']
src_path = CORPUS / source
original = air_path.read_text()
air_ds = errors(aji, air_path)
ds = errors(aji, src_path)
source_text = src_path.read_text()
expected_positions = positions(source_text)
if not expected_positions or [(d['line'], d['col']) for d in ds] != expected_positions:
raise ValueError(f'{source}: diagnostics differ from marked source positions')
if row.get('lowering') == 'rejected':
if row['site'] != 'declaration':
raise ValueError('early rejection mode requires a declaration-site audit')
lowered = [load_json(x) for x in command(aji, 'lower', src_path, status=1).splitlines()]
if lowered != ds:
raise ValueError(f'{source}: lower/check early errors differ')
for d in ds:
line = source_text.splitlines()[d['line'] - 1].strip()
if not line.startswith(('struct ', 'enum ')) or d['file'] != str(src_path):
raise ValueError(f'{source}: early type error lacks a declaration position')
expected = Counter(signature(original, d, 'declaration') for d in air_ds)
found = Counter((d['code'], d['kind'], 'declaration',
(),
tuple(x['role'] for x in d.get('related_locations', [])),
json.dumps(payload(d), sort_keys=True)) for d in ds)
if expected != found:
raise ValueError(f'{source}: early type error has different rule facts')
return
canonical = command(aji, 'lower', src_path, status=0)
if command(aji, 'lower', src_path, status=0) != canonical:
raise ValueError(f'{source}: nondeterministic lowering')
annotated, mapping = annotation_map(command(aji, 'lower', '--annotate', src_path, status=0))
if annotated != canonical:
raise ValueError(f'{source}: annotations changed AIR')
raw = root / 'twin.air'
raw.write_text(canonical)
raw_ds = [load_json(line) for line in command(aji, 'check', raw, status=1).splitlines()]
# Spec 15 §10 keeps the first code per source location. Array bindings
# may emit both borrow.ref and slice.make for one invalid source borrow.
# Verify that exact projection; do not silently discard arbitrary extras.
projected, seen = [], set()
for rd in raw_ds:
origin = mapping[rd['line']]
if origin is None and row['site'] == 'function':
raw_name = re.match(r'fn @(\w+)', canonical.splitlines()[rd['line'] - 1])
declarations = [(i, line) for i, line in enumerate(source_text.splitlines(), 1)
if raw_name and re.match(r'\s*fn ' + re.escape(raw_name[1]) + r'\(', line)]
if len(declarations) != 1:
raise ValueError(f'{source}: budget header lacks a source declaration')
i, line = declarations[0]
origin = (str(src_path), i, len(line) - len(line.lstrip()) + 1)
if origin is None:
raise ValueError(f'{source}: raw diagnostic lacks a source mapping')
key = rd['code'], origin[0] or str(src_path), origin[1], origin[2]
if key not in seen:
projected.append(rd)
seen.add(key)
if len(projected) != len(ds):
raise ValueError(f'{source}: source/raw projected diagnostic counts differ')
for d, rd in zip(ds, projected):
if (d['air_line'], d['air_col'], d['code']) != (rd['line'], rd['col'], rd['code']):
raise ValueError(f'{source}: incorrect primary AIR position')
origin = mapping[d['air_line']]
if row['site'] == 'function':
# --annotate exposes block/instruction spans, not header spans.
# Budget sites instead have an independent marked declaration
# and must identify that same function in canonical AIR.
raw_line = canonical.splitlines()[d['air_line'] - 1]
source_line = source_text.splitlines()[d['line'] - 1]
raw_name = re.match(r'fn @(\w+)', raw_line)
source_name = re.match(r'\s*fn (\w+)', source_line)
if not raw_name or not source_name or raw_name[1] != source_name[1]:
raise ValueError(f'{source}: budget error names a different function')
elif origin is None or (d['line'], d['col']) != origin[1:]:
raise ValueError(f'{source}: missing/incorrect source position')
if d['file'] != str(src_path):
raise ValueError(f'{source}: wrong source file')
if payload(d) != payload(rd):
raise ValueError(f'{source}: mapping changed rule facts')
if [x['role'] for x in d.get('related_locations', [])] != [x['role'] for x in rd.get('related_locations', [])]:
raise ValueError(f'{source}: mapping changed related roles')
for related, rr in zip(d.get('related_locations', []), rd.get('related_locations', [])):
origin = mapping[related['air_line']]
if origin is None or (related['line'], related['col']) != origin[1:]:
raise ValueError(f'{source}: incorrect related source position')
if (related['air_line'], related['air_col']) != (rr['line'], rr['col']):
raise ValueError(f'{source}: incorrect related AIR position')
if row.get('required_ops'):
operation_witnesses(original, air_ds, row['required_ops'])
operation_witnesses(canonical, projected, row['required_ops'])
if Counter(signature(original, d, row['site']) for d in air_ds) != Counter(signature(canonical, d, row['site']) for d in projected):
raise ValueError(f'{source}: same codes but different offending operation/rule facts')
if row['site'] == 'function' and any('limit' not in d or 'max' not in d for d in ds):
raise ValueError(f'{source}: budget twin lacks stable limit facts')
def verify_analogue(aji, analogue):
p = CORPUS / analogue['source']
ds = errors(aji, p)
if [(d['line'], d['col']) for d in ds] != positions(p.read_text()):
raise ValueError(f"{analogue['source']}: analogue position changed")
for d in ds:
if any(d.get(k) != v for k, v in analogue.get('fields', {}).items()):
raise ValueError(f"{analogue['source']}: analogue rule facts changed")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--inventory', action='store_true')
parser.add_argument('--require-complete', action='store_true')
parser.add_argument('--aji', type=Path, default=ROOT / 'zig-out/bin/aji')
args = parser.parse_args()
try:
rows = inventory()
counts = Counter(row['kind'] for row in rows)
report = {'air_rejections': len(rows), 'counts': dict(counts),
'complete': counts['same_code'] == len(rows) and not args.inventory,
'verification': 'metadata_only' if args.inventory else 'compiled_pairs', 'cases': rows}
if args.inventory:
print(json.dumps(report, indent=2))
else:
with tempfile.TemporaryDirectory(prefix='aji-reject-twins-') as directory:
for row in rows:
for source in row['sources']:
verify_pair(args.aji, Path(directory), row, source)
for analogue in row.get('analogues', []):
verify_analogue(args.aji, analogue)
print(f"AIR rejection twins: {counts['same_code']}/{len(rows)} same-code cases verified; "
f"{counts['pending']} pending, {counts['source_error']} source-error analogues, "
f"{counts['air_only']} AIR-only. P6-7 complete: {report['complete']}.")
if args.require_complete and not report['complete']:
return 1
return 0
except (ValueError, KeyError, OSError, TypeError) as e:
print(f'rejection-twin check failed: {e}', file=sys.stderr)
return 1
if __name__ == '__main__':
sys.exit(main())