diag: preserve factual source atomic-access diagnostics
This commit is contained in:
1 parent
ee09a7a290
commit
edfef82cc6
18 files changed
+346
-9
No files matched your search
@@ -25,6 +25,7 @@ jobs:
|
||||
- run: python3 tests/hosted/source_borrow_returns.py
|
||||
- run: python3 tests/hosted/source_format.py
|
||||
- run: python3 tests/hosted/source_diagnostic_reasons.py
|
||||
- run: python3 tests/hosted/source_atomic_access.py
|
||||
- run: python3 tests/hosted/related_locations.py
|
||||
- run: python3 tests/hosted/source_lifetimes.py
|
||||
- run: python3 tests/hosted/source_array_arguments.py
|
||||
|
||||
@@ -21,6 +21,7 @@ python3 tests/hosted/source_generics.py # explicit generics, constraints and pro
|
||||
python3 tests/hosted/source_borrow_returns.py # explicit origins, retained views, packages and profiles
|
||||
python3 tests/hosted/source_format.py # formatter CLI, comments, idempotence and public-corpus AIR fidelity
|
||||
python3 tests/hosted/source_diagnostic_reasons.py # stable E7006 categories and CLI/package provenance
|
||||
python3 tests/hosted/source_atomic_access.py # factual E4202 types, source/package provenance and early failure
|
||||
python3 tests/hosted/related_locations.py # factual conflict/spawn positions, source mapping and package provenance
|
||||
python3 tests/hosted/source_lifetimes.py # AIR rejection twins and exact lifetime/join diagnostic positions
|
||||
python3 tests/hosted/source_array_arguments.py # array argument shape, cleanup, AIR and package parity
|
||||
|
||||
@@ -172,3 +172,5 @@ DD-022 grammar surface (cl100k): Quick Reference stays 8,948; other source docs
|
||||
Q-051 source effect names (DD-023, cl100k): Quick Reference 8,948 → 8,955 (+7); other source docs 68,219 → 68,323 (+104), full source 77,167 → 77,278 (+0.14%). o200k groups are 8,991 / 68,526 / 77,517; Qwen2.5 9,233 / 69,994 / 79,227. The AIR copy in the source bundle grows 47,445 → 47,458 (+13); canonical AIR bundle bytes grow 184,628 → 184,678, through the shared E7002 registry description; library/std.md is unchanged. Unknown effects use existing E7002 with structured `name`/`effect`, replacing erroneous source E7900 or E0006. Accepted canonical AIR and authority/effect semantics are preserved. No new concept, syntax, code/reason, feature or verifier/runtime state is added; no empirical MCC benefit is claimed.
|
||||
|
||||
Q-052 CFG resource provenance (DD-024): Quick Reference and other/full source docs remain 8,955 / 68,323 / 77,278 cl100k (o200k 8,991 / 68,526 / 77,517; Qwen2.5 9,233 / 69,994 / 79,227); std is unchanged. Canonical AIR grows 184,678 → 185,220 bytes and 47,385 → 47,476 cl100k (+91), 47,540 → 47,631 o200k (+91), 48,917 → 49,009 Qwen2.5 (+92). The separately wrapped source-bundle AIR copy grows 47,458 → 47,549 cl100k. The added sentences clarify preservation of existing task/scope, guard and shield obligations through block arguments. No new agent concept, syntax, feature or diagnostic is introduced. Sparse implementation relations replace incomplete SSA metadata; verifier acceptance now enforces existing safety rules. No empirical MCC benefit is claimed.
|
||||
|
||||
P6-7 factual source E4202 fields (cl100k): Quick Reference stays 8,955; other source docs 68,323 → 68,353 (+30), full source 77,278 → 77,308 (+0.04%). o200k groups are 8,991 / 68,556 / 77,547; Qwen2.5 9,233 / 70,024 / 79,257. Only language/concurrency.md grows; AIR and library/std.md are unchanged. Concrete `found` and `use` fields distinguish ordinary atomic reads without message parsing. No new syntax, code, feature or verifier/runtime state is introduced; no empirical MCC benefit is claimed.
|
||||
@@ -388,3 +388,7 @@ P6-7 rejection-twin work reproduced accepted source that returns the cancelled h
|
||||
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.
|
||||
|
||||
2026-10-08 completed public audit: all 199 AIR rejection files are reviewed. The executable check verifies 91 same-code cases and 45 prescribed E7xxx source analogues; 63 cases have an audited source-boundary reason. No rows remain pending. Full conformance passes 1,713/1,713, but `--require-complete` still exits 1 because it requires every row to be same-code.
|
||||
|
||||
Proposed criterion, for owner decision: retain every AIR rejection test; for each source-authorable rule/context, require a compiled source twin with the same code or its spec-prescribed E7xxx translation, stable facts and independent positions. Generated-only contexts require an explicit governing source-policy audit. Every newly discovered public AIR rejection remains pending until audited. This proposal changes no language rule and does not count a matching code alone as a twin. It is not adopted; the literal gate and doing status remain unchanged.
|
||||
@@ -320,8 +320,10 @@ 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 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.
|
||||
Verified same-code coverage is 91/199 across ownership/resources, borrows, effects/capabilities, tasks, graphs, atomics, linear aggregates and buffer operations. The inventory retains 0 pending, 45 prescribed E7xxx analogues and 63 AIR-only cases; those 108 classified cases do not meet the literal same-code 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. 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.
|
||||
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. The final direct cbr/switch arm-argument cases are AIR-only under spec 15 §4, supported by inspection of lowering and every branch argument in the 740 successful lowerings of the preceding 1,352 public source fixtures. Ordinary atomic access now has a full-AIR twin: a shared field read retains the same load/type/use facts; its reported operand must be the actual load operand. 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,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.
|
||||
Validation: full conformance is 1,713/1,713; unit tests, Zig formatting, all 62 checker regressions and the 91-case source/AIR position check pass. All 66 source reject_twins fixtures and five atomic_access fixtures pass collection before every instruction; source coverage remains 121/121. The completion gate still rejects partial same-code coverage. Claude independently reviewed the feature/CFG witnesses, all remaining classifications and the atomic operand checks. New probes reject another scalar or borrow mode, an unrelated borrow reported as the operand, and inconsistent raw/source identities. Existing Git attributes force LF for pinned artifacts.
|
||||
|
||||
The frontend ordinary-dereference E4202 now adds concrete found and use fields, retaining the code, message, primary position and early failure. CLI tests pass 33 checks; comparison with the previous compiler passes 52, including generic/package provenance, first-error selection, untouched alternative errors and identical valid AIR. No SSA identity or AIR location is fabricated for a frontend rejection. Atomic access invariants, verifier/runtime rules and deterministic execution remain unchanged; valid reads use explicit atomic.load orderings. The schema is additive; the source bundle grows by 30 tokens (docs/agent/README.md). Q-053 remains the owner decision on the literal criterion; there are no unaudited public rows.
|
||||
@@ -502,7 +502,7 @@ The orderings:
|
||||
|
||||
Other rules:
|
||||
|
||||
- `*c` and any other ordinary read of a cell is `E4202`.
|
||||
- `*c` and any other ordinary read of a cell is `E4202`. An ordinary source dereference MUST report `found` (the concrete borrow type) and `use: "atomic.load"`, including after generic substitution.
|
||||
- Effects are declared by the programmer (spec 05 §13).
|
||||
|
||||
## 13. Built-in standard modules
|
||||
|
||||
@@ -1607,8 +1607,11 @@ const Lowerer = struct {
|
||||
const r = try l.expr(x.*, null);
|
||||
const in = r.ty.inner() orelse return l.fail("E7005", e.span, "`*` reads through a borrow", &.{.{ .name = "found", .value = l.diagnosticTyText(r.ty) }});
|
||||
if (r.ty == .slice or r.ty == .slice_mut or in == .array) return l.invalid(.invalid_expression, e.span, "read slice and array elements with `s[i]`, not `*`", &.{});
|
||||
// The verifier's code (spec 15 §1 rule 2, spec 04 §28).
|
||||
if (in == .atomic) return l.fail("E4202", e.span, "an atomic cell is read only by atomic operations: use `atomic.load(r, ordering)`", &.{});
|
||||
// Source-prescribed E4202 (spec 15 §12); no load is emitted.
|
||||
if (in == .atomic) return l.fail("E4202", e.span, "an atomic cell is read only by atomic operations: use `atomic.load(r, ordering)`", &.{
|
||||
.{ .name = "found", .value = l.diagnosticTyText(r.ty) },
|
||||
.{ .name = "use", .value = "atomic.load" },
|
||||
});
|
||||
return l.def("v", in, try l.fmt("load %{s}", .{r.name}), e.span);
|
||||
},
|
||||
.index => |x| {
|
||||
|
||||
@@ -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: <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. 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.
|
||||
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. E4202 `operand` is an SSA identity. Its supported ordinary-load form must identify the exact operand on the reported `load` line and resolve to a borrow; `found` and `use` remain exact facts. Source/raw operand names still match exactly. 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 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.
|
||||
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 task arguments to arm targets are AIR-only under spec 15 §4: source if/match arms have no target arguments; changing variables instead reach joins. Loop-exit cbr arguments forward loop-header variables, a different context.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
@@ -1711,6 +1711,27 @@
|
||||
"source/reject_twins/linear_swap_leak.aji": "6f9fa0d8ef40b75951c2a2042d1d171c221268301df18b38775b74a47f606cc7"
|
||||
}
|
||||
}
|
||||
},
|
||||
"phase5/reject/ordinary_load.air": {
|
||||
"kind": "same_code",
|
||||
"site": "instruction",
|
||||
"spec": "docs/spec/04-concurrency-and-atomics.md \u00a728; docs/spec/15-source-language.md \u00a712",
|
||||
"rule": "An ordinary load through ref<atomic<u64>> rejects E4202 with found and use atomic.load. The source wraps the created cell in an explicit linear struct so its shared field read reaches AIR; it unpacks and takes the cell afterwards. The rule does not depend on the carrier. Both actual operands must be the borrow used by the offending load; raw/source identities and positions remain exact.",
|
||||
"required_ops": {
|
||||
"atomic.new": 1,
|
||||
"load": 1,
|
||||
"atomic.take": 1
|
||||
}
|
||||
},
|
||||
"phase3/reject/cfg_provenance_loan_cbr.air": {
|
||||
"kind": "air_only",
|
||||
"spec": "docs/spec/15-source-language.md \u00a74",
|
||||
"rule": "The AIR regression passes the directly spawned lent handle as an argument to both cbr arm targets. Source if arms have no target arguments; loop-exit cbr arguments instead forward loop-header variables. The direct two-arm handoff context has no implemented source spelling."
|
||||
},
|
||||
"phase3/reject/cfg_provenance_loan_switch.air": {
|
||||
"kind": "air_only",
|
||||
"spec": "docs/spec/15-source-language.md \u00a74",
|
||||
"rule": "The AIR regression passes a lent task as switch target arguments. Source integer/enum match arms have no target arguments; changing variables reach a subsequent br join. A later-merge E4302 would discard the switch-handoff context being tested."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// expect: reject E4202
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §12; docs/spec/04-concurrency-and-atomics.md §28
|
||||
module test.atomic_access_bool_parenthesized
|
||||
|
||||
fn main() -> bool effects [] {
|
||||
let cell = atomic.new(true);
|
||||
{
|
||||
ref r = cell;
|
||||
let value = *((r)); // diagnostic here: *((r))
|
||||
}
|
||||
trap;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §12; docs/spec/04-concurrency-and-atomics.md §28
|
||||
module test.atomic_access_explicit_load
|
||||
|
||||
fn read<T>(cell: ref<atomic<T>>) -> T effects [atomic] {
|
||||
return atomic.load(cell, seq_cst);
|
||||
}
|
||||
|
||||
fn main() -> u64 effects [atomic] {
|
||||
let cell = atomic.new(42u64);
|
||||
var result: u64 = 0;
|
||||
{
|
||||
ref r = cell;
|
||||
result = read::<u64>(r);
|
||||
}
|
||||
let last = atomic.take(move cell);
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
// expect: reject E4202
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §12; docs/spec/04-concurrency-and-atomics.md §28
|
||||
module test.atomic_access_parameter
|
||||
|
||||
fn read(cell: ref<atomic<u64>>) -> u64 effects [] {
|
||||
return *cell; // diagnostic here: *cell
|
||||
}
|
||||
|
||||
fn main() -> u64 effects [] {
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// expect: reject E4202
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §12; docs/spec/04-concurrency-and-atomics.md §28
|
||||
module test.atomic_access_reborrow
|
||||
|
||||
fn main() -> u64 effects [] {
|
||||
let cell = atomic.new(1u64);
|
||||
{
|
||||
ref r = cell;
|
||||
ref second = r;
|
||||
let value = *second; // diagnostic here: *second
|
||||
}
|
||||
trap;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// expect: reject E4202
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §12; docs/spec/04-concurrency-and-atomics.md §28
|
||||
module test.atomic_access_u8_cell
|
||||
|
||||
fn main() -> u8 effects [] {
|
||||
let cell = atomic.new(1u8);
|
||||
{
|
||||
ref r = cell;
|
||||
let value = *r; // diagnostic here: *r
|
||||
}
|
||||
trap;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// expect: reject E4202
|
||||
// phase: 6
|
||||
// spec: docs/spec/04-concurrency-and-atomics.md §28; docs/spec/15-source-language.md §12
|
||||
// AIR twin: phase5/reject/ordinary_load.air
|
||||
module test.ordinary_load
|
||||
|
||||
struct Holder {
|
||||
cell: atomic<u64>
|
||||
}
|
||||
|
||||
fn main() -> u64 effects [atomic, atomic.weak] {
|
||||
let initial = 0u64;
|
||||
let cell = atomic.new(initial);
|
||||
var holder: Holder = Holder { cell: move cell };
|
||||
{
|
||||
ref r = holder;
|
||||
let value = r.cell; // diagnostic here: r.cell
|
||||
}
|
||||
let (rest) = struct.unpack(move holder);
|
||||
let value = atomic.take(move rest);
|
||||
return 0u64;
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Factual E4202 payloads, early failure, concrete types and source provenance."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
AJI = ROOT / 'zig-out/bin/aji'
|
||||
CORPUS = ROOT / 'tests/conformance/source/atomic_access'
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--before', type=Path, help='optional previous compiler for comparison')
|
||||
before = parser.parse_args().before
|
||||
checks = 0
|
||||
|
||||
|
||||
def cli(*args, status=0, binary=AJI):
|
||||
global checks
|
||||
result = subprocess.run([str(binary), *map(str, args)], capture_output=True)
|
||||
assert result.returncode == status, (args, result.returncode, result.stdout, result.stderr)
|
||||
checks += 1
|
||||
return result.stdout
|
||||
|
||||
|
||||
def unique(pairs):
|
||||
result = {}
|
||||
for key, value in pairs:
|
||||
assert key not in result, key
|
||||
result[key] = value
|
||||
return result
|
||||
|
||||
|
||||
def reject(path, scalar, *args, file=None, token=None, commands=('check', 'lower')):
|
||||
text = path.read_text()
|
||||
lines = text.splitlines()
|
||||
if token is None:
|
||||
line = next(i for i, s in enumerate(lines) if '// diagnostic here:' in s)
|
||||
token = lines[line].split('// diagnostic here: ', 1)[1]
|
||||
else:
|
||||
line = next(i for i, s in enumerate(lines) if token in s)
|
||||
col = len(lines[line][:lines[line].index(token)].encode('utf-8')) + 1
|
||||
first = None
|
||||
for command in commands:
|
||||
extra = ['--fuel', '10000'] if command == 'run' else ['--max-runs', '1'] if command == 'explore' else []
|
||||
output = cli(command, *extra, *args, status=1) if args else cli(command, *extra, path, status=1)
|
||||
error = json.loads(output, object_pairs_hook=unique)
|
||||
assert (error['code'], error['kind']) == ('E4202', 'atomic.ordinary_access'), error
|
||||
scalars = (scalar,) if isinstance(scalar, str) else scalar
|
||||
assert error['found'] in {f'ref<atomic<{t}>>' for t in scalars}, error
|
||||
assert error['use'] == 'atomic.load', error
|
||||
assert (error['file'], error['line'], error['col']) == (file or str(path), line + 1, col), error
|
||||
assert not {'operand', 'function', 'block', 'inst', 'air_line', 'air_col'} & error.keys(), error
|
||||
if first is None:
|
||||
first = output
|
||||
assert output == first, (command, error)
|
||||
if before:
|
||||
old = json.loads(cli('check', *args, status=1, binary=before) if args else
|
||||
cli('check', path, status=1, binary=before), object_pairs_hook=unique)
|
||||
assert {k: v for k, v in error.items() if k not in {'found', 'use'}} == old, (old, error)
|
||||
return error
|
||||
|
||||
|
||||
for name, scalar in (('parameter', 'u64'), ('u8_cell', 'u8'),
|
||||
('bool_parenthesized', 'bool'), ('reborrow', 'u64')):
|
||||
reject(CORPUS / f'{name}.aji', scalar)
|
||||
reject(CORPUS / 'parameter.aji', 'u64', commands=('check', 'lower', 'report', 'run', 'explore'))
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix='aji-atomic-access-') as directory:
|
||||
root = Path(directory)
|
||||
source = root / 'read-λ.aji'
|
||||
source.write_text('module access\nfn read(r: ref<atomic<u64>>) -> u64 effects [] {\n'
|
||||
' // λ\n return *r;\n}\nfn main() -> u64 effects [] { return 0; }\n')
|
||||
reject(source, 'u64', token='*r')
|
||||
|
||||
# The first read and the selected specialization retain their concrete types.
|
||||
source.write_text('module access\nfn read(r: ref<atomic<u8>>, other: ref<atomic<u64>>) -> u8 effects [] {\n'
|
||||
' let first = *r; let second = *other; return first;\n}\n'
|
||||
'fn main() -> u64 effects [] { return 0; }\n')
|
||||
reject(source, 'u8', token='*r')
|
||||
source.write_text('module access\nfn read<T>(r: ref<atomic<T>>) -> T effects [] { return *r; }\n'
|
||||
'fn call(a: ref<atomic<u8>>, b: ref<atomic<u64>>) -> u8 effects [] {\n'
|
||||
' let first = read::<u8>(a); let second = read::<u64>(b); return first;\n}\n'
|
||||
'fn main() -> u64 effects [] { return 0; }\n')
|
||||
reject(source, ('u8', 'u64'), token='*r')
|
||||
|
||||
source.write_text('module access\nfn read<T>(r: ref<atomic<T>>) -> T effects [] { return *r; }\n'
|
||||
'fn main() -> u64 effects [] { return 42; }\n')
|
||||
cli('check', source)
|
||||
if before:
|
||||
assert cli('lower', source) == cli('lower', source, binary=before)
|
||||
|
||||
entry, library, manifest = (root / name for name in ('entry.aji', 'library.aji', 'aji.toml'))
|
||||
entry.write_text('module app\nimport lib;\n'
|
||||
'fn call(r: ref<atomic<bool>>) -> bool effects [] { return lib.read::<bool>(r); }\n'
|
||||
'fn main() -> u64 effects [] { return 42; }\n')
|
||||
library.write_text('module lib\nfn read<T>(r: ref<atomic<T>>) -> T effects [] { return *r; }\n')
|
||||
manifest.write_text('[package]\nname = "atomic-access"\nversion = "1"\nentry = "entry.aji"\n'
|
||||
'[modules]\nlib = "library.aji"\n')
|
||||
reject(library, 'bool', '--manifest', manifest, file='library.aji', token='*r')
|
||||
|
||||
# Other errors and ordinary non-atomic reads retain their established contract.
|
||||
for body in ('let c = atomic.new(1u64); mut r = c; let x = *r; trap;',
|
||||
'let c = atomic.new(1u64); mut r = c; *r = 1u64; trap;',
|
||||
'let c = atomic.new(1u64); ref r = c; let x = r.value; trap;'):
|
||||
source.write_text('module control\nfn main() -> void effects [] { ' + body + ' }\n')
|
||||
output = cli('check', source, status=1)
|
||||
error = json.loads(output)
|
||||
assert error['code'] == 'E7005' and 'use' not in error, error
|
||||
if before:
|
||||
assert output == cli('check', source, status=1, binary=before)
|
||||
source.write_text('module control\nfn main() -> u64 effects [] { let value = 42u64; ref r = value; return *r; }\n')
|
||||
assert json.loads(cli('run', '--fuel', '10000', source))['value'] == 42
|
||||
if before:
|
||||
assert cli('lower', source) == cli('lower', source, binary=before)
|
||||
|
||||
# Existing verifier-origin E4202 carries a real operand and AIR coordinates.
|
||||
source.write_text('module field\nstruct Holder { cell: atomic<u64> }\n'
|
||||
'fn read(h: ref<Holder>) -> void effects [] { let value = h.cell; trap; }\n'
|
||||
'fn main() -> void effects [] {}\n')
|
||||
output = cli('check', source, status=1)
|
||||
error = json.loads(output)
|
||||
assert (error['code'], error['found'], error['use']) == ('E4202', 'ref<atomic<u64>>', 'atomic.load'), error
|
||||
assert error['operand'].startswith('%') and 'air_line' in error, error
|
||||
if before:
|
||||
assert output == cli('check', source, status=1, binary=before)
|
||||
|
||||
valid = CORPUS / 'explicit_load.aji'
|
||||
assert json.loads(cli('run', '--fuel', '10000', valid))['value'] == 42
|
||||
if before:
|
||||
assert cli('lower', valid) == cli('lower', valid, binary=before)
|
||||
record = root / 'run.json'
|
||||
cli('run', '--profile', 'hosted', '--fuel', '10000', '--result-file', record, valid)
|
||||
assert json.loads(record.read_bytes())['value'] == 42
|
||||
formatted = root / 'formatted.aji'
|
||||
formatted.write_bytes(cli('fmt', valid))
|
||||
cli('fmt', '--check', formatted)
|
||||
assert cli('lower', formatted) == cli('lower', valid)
|
||||
|
||||
print(f'atomic access CLI integration passed ({checks} checks)')
|
||||
@@ -167,6 +167,62 @@ class CoverageFailures(unittest.TestCase):
|
||||
with self.assertRaisesRegex(ValueError, 'missing diagnostic-identity use witness'):
|
||||
self.verify_fake(row)
|
||||
|
||||
def atomic_load_pair(self):
|
||||
row = self.fake_pair(source_path='source/reject_twins/ordinary_atomic_field_load.aji',
|
||||
air_path='phase5/reject/ordinary_load.air')
|
||||
row['required_ops'] = {'atomic.new': 1, 'load': 1, 'atomic.take': 1}
|
||||
return row
|
||||
|
||||
def test_atomic_operand_identity_survives_field_and_ssa_renaming(self):
|
||||
row = self.atomic_load_pair()
|
||||
self.verify_fake(row)
|
||||
p = self.corpus / 's.aji'
|
||||
p.write_text(re.sub(r'\bcell\b', 'item', p.read_text()).replace('Holder', 'Wrapper'))
|
||||
self.verify_fake(row)
|
||||
|
||||
def test_atomic_load_facts_preserve_scalar_and_borrow_mode(self):
|
||||
original = (REAL_CORPUS / 'source/reject_twins/ordinary_atomic_field_load.aji').read_text()
|
||||
for changed in (original.replace('u64', 'u8'),
|
||||
original.replace('u64', 'bool').replace('0bool', 'false'),
|
||||
original.replace('ref r = holder', 'mut r = holder')):
|
||||
with self.subTest(source=changed):
|
||||
row = self.atomic_load_pair()
|
||||
p = self.corpus / 's.aji'
|
||||
p.write_text(changed)
|
||||
with self.assertRaisesRegex(ValueError, 'different offending operation/rule facts'):
|
||||
self.verify_fake(row)
|
||||
|
||||
def test_another_atomic_borrow_cannot_replace_the_offending_operand(self):
|
||||
row = self.atomic_load_pair()
|
||||
p = self.corpus / 'a.air'
|
||||
p.write_text(p.read_text().replace('%r = borrow.ref %c',
|
||||
'%r = borrow.ref %c\n %other = borrow.ref %c\n borrow.end %other'))
|
||||
real_command = twins.command
|
||||
def changed(aji, *args, status):
|
||||
result = real_command(aji, *args, status=status)
|
||||
if args[0] == 'check' and Path(args[1]) == p:
|
||||
ds = [json.loads(line) for line in result.splitlines()]
|
||||
ds[0]['operand'] = '%other'
|
||||
return '\n'.join(json.dumps(d) for d in ds) + '\n'
|
||||
return result
|
||||
with patch.object(twins, 'command', changed):
|
||||
with self.assertRaisesRegex(ValueError, 'atomic operand is not the offending load operand'):
|
||||
self.verify_fake(row)
|
||||
|
||||
def test_atomic_source_raw_identity_mapping_stays_exact(self):
|
||||
row = self.atomic_load_pair()
|
||||
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]['operand'] = '%wrong'
|
||||
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 diagnostic identities'):
|
||||
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')
|
||||
|
||||
@@ -21,7 +21,7 @@ CORPUS = ROOT / 'tests/conformance'
|
||||
MANIFEST = CORPUS / 'reject-twins.json'
|
||||
IDENTITIES = {'function', 'block', 'inst', 'borrow', 'resource', 'task',
|
||||
'conflicts_with', 'scope', 'guard', 'child', 'inner', 'local', 'from',
|
||||
'callee', 'argument', 'task_function'}
|
||||
'callee', 'argument', 'task_function', 'operand'}
|
||||
ENVELOPE = {'code', 'kind', 'severity', 'file', 'line', 'col', 'air_line',
|
||||
'air_col', 'message', 'related_locations'}
|
||||
|
||||
@@ -310,6 +310,19 @@ def swapped_enum_class(air, d, value):
|
||||
|
||||
|
||||
def identity_fact(air, d, field):
|
||||
if field == 'operand':
|
||||
# E4202's operand is an SSA identity, tied to the reported load.
|
||||
# Other ordinary-access forms need their own rule audit.
|
||||
if d['code'] != 'E4202' or d.get('use') != 'atomic.load':
|
||||
raise ValueError('unsupported atomic operand identity rule')
|
||||
line = air.splitlines()[d['line'] - 1].split(';', 1)[0]
|
||||
rhs = line.split('=', 1)[-1].strip()
|
||||
if not re.fullmatch(r'load\s+' + re.escape(d[field]), rhs):
|
||||
raise ValueError('atomic operand is not the offending load operand')
|
||||
root = identity_class(air, d, d[field])
|
||||
if root != 'borrow':
|
||||
raise ValueError('ordinary atomic load operand lacks a borrow definition')
|
||||
return root
|
||||
if field == 'callee':
|
||||
# Parameter/result types do not decide the flat-effect rule.
|
||||
if d['code'] != 'E3101':
|
||||
|
||||
Reference in new issue
Block a user