diag: preserve factual source atomic-access diagnostics

This commit is contained in:
dev committed 2026-10-09 00:04:12 +03:00
1 parent ee09a7a290
commit edfef82cc6
18 files changed
+346 -9

No files matched your search

+2 -2
View File
@@ -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.
+21
View File
@@ -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;
}
+140
View File
@@ -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)')
+56
View File
@@ -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')