frontend: provide contextual source repair advice
This commit is contained in:
1 parent
008867fe48
commit
2c6c7a3dcd
37 files changed
+562
-24
No files matched your search
@@ -42,6 +42,8 @@ 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.
|
||||
|
||||
For a source test, optional `<file>.aji.advice` pins structured repair advice: one compact JSON array of `repair_candidates` per diagnostic, in diagnostic order, each followed by a newline. A diagnostic without advice writes `[]`; a program without diagnostics writes no lines. The golden compares exact kinds, hints, alternatives and member order using the CLI's serializer. Source positions and CLI/package parity are additionally checked by the hosted tests.
|
||||
|
||||
## 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.
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
// expect: reject E7001
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §10; docs/spec/10-diagnostics-and-agent-protocol.md §3
|
||||
module advice
|
||||
fn main() -> u64 effects [] { var x = 1u64; return x; }
|
||||
@@ -0,0 +1 @@
|
||||
[{"kind":"annotate_var_type","hint":"Write an explicit type: `var name: T = expression;`. `let` may infer its type."}]
|
||||
@@ -0,0 +1,5 @@
|
||||
// expect: reject E7001
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §10; docs/spec/10-diagnostics-and-agent-protocol.md §3
|
||||
module advice
|
||||
fn main() -> bool effects [] { return !false; }
|
||||
@@ -0,0 +1 @@
|
||||
[{"kind":"boolean_negation","hint":"Aji boolean negation is `not`; integer complement is not boolean negation."}]
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7001
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §10; docs/spec/10-diagnostics-and-agent-protocol.md §3
|
||||
module advice
|
||||
fn f(s: ref<u64>) -> void effects [] {}
|
||||
fn main() -> void effects [] { var x: u64 = 1u64; f(&x); }
|
||||
@@ -0,0 +1 @@
|
||||
[{"kind":"borrow_argument","hint":"Write `ref place` or `mut place` for an inline borrow argument.","alternatives":["ref"]}]
|
||||
@@ -0,0 +1,5 @@
|
||||
// expect: reject E7001
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §10; docs/spec/10-diagnostics-and-agent-protocol.md §3
|
||||
module advice
|
||||
fn main() -> void effects [] { var x: u64 = 1u64; let r = &x; }
|
||||
@@ -0,0 +1 @@
|
||||
[{"kind":"borrow_binding","hint":"Bind a borrow with `ref name = place;` or `mut name = place;`, rather than a let/var initializer."}]
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7001
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §10; docs/spec/10-diagnostics-and-agent-protocol.md §3
|
||||
module advice
|
||||
fn f(s: mut<u64>) -> void effects [] {}
|
||||
fn main() -> void effects [] { var x: u64 = 1u64; f(&mut x); }
|
||||
@@ -0,0 +1 @@
|
||||
[{"kind":"borrow_argument","hint":"Write `ref place` or `mut place` for an inline borrow argument.","alternatives":["mut"]}]
|
||||
@@ -0,0 +1,21 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §4/§5/§10
|
||||
module advice
|
||||
fn read(x: ref<u64>) -> u64 effects [] { return *x; }
|
||||
fn change(x: mut<u64>) -> void effects [] { *x = 42u64; }
|
||||
fn main() -> u64 effects [] {
|
||||
var x: u64 = zero;
|
||||
change(mut x);
|
||||
let inferred = read(ref x);
|
||||
let bits = 7u64 & 3u64;
|
||||
let checked = inferred as! u32;
|
||||
let wrapped = inferred as% u32;
|
||||
var bytes: [u8; 3] = zero;
|
||||
ref part = bytes[0usize..3usize];
|
||||
if not false and checked == wrapped and bits == 3u64 and part.len == 3usize {
|
||||
return inferred;
|
||||
}
|
||||
return 0u64;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7001
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §10; docs/spec/10-diagnostics-and-agent-protocol.md §3
|
||||
module advice
|
||||
fn f(s: slice<u8>) -> void effects [] { ref t = s[1usize..]; }
|
||||
fn main() -> void effects [] {}
|
||||
@@ -0,0 +1 @@
|
||||
[{"kind":"explicit_range_end","hint":"Write both slice bounds: `receiver[start..end]`; choose the upper bound explicitly."}]
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7005
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §10; docs/spec/10-diagnostics-and-agent-protocol.md §3
|
||||
module advice
|
||||
fn f(n: u64) -> u32 effects [] { return n as u32; }
|
||||
fn main() -> void effects [] {}
|
||||
@@ -0,0 +1 @@
|
||||
[{"kind":"numeric_cast_modes","hint":"Choose `as!` for a checked conversion (T0006 on overflow) or `as%` for a wrapping conversion.","alternatives":["as!","as%"]}]
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7001
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §10; docs/spec/10-diagnostics-and-agent-protocol.md §3
|
||||
module advice
|
||||
fn f(s: mut slice<u8>) -> void effects [] {}
|
||||
fn main() -> void effects [] {}
|
||||
@@ -0,0 +1 @@
|
||||
[{"kind":"slice_mut_type","hint":"Write `slice_mut<T>` for a mutable slice type.","alternatives":["slice_mut<u8>"]}]
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7001
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §10; docs/spec/10-diagnostics-and-agent-protocol.md §3
|
||||
module advice
|
||||
fn f(s: ref slice<u8>) -> void effects [] {}
|
||||
fn main() -> void effects [] {}
|
||||
@@ -0,0 +1 @@
|
||||
[{"kind":"slice_ref_type","hint":"Write `slice<T>` for a shared slice type.","alternatives":["slice<u8>"]}]
|
||||
@@ -0,0 +1,5 @@
|
||||
// expect: reject E7001
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §10; docs/spec/10-diagnostics-and-agent-protocol.md §3
|
||||
module advice
|
||||
fn main() -> void effects [] { let xs: [u64; 3] = [zero; 3]; }
|
||||
@@ -0,0 +1 @@
|
||||
[{"kind":"zero_storage","hint":"`zero` is only a whole var initializer: `var name: T = zero;`; T must be zeroable."}]
|
||||
@@ -0,0 +1,158 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Structured advice is additive, contextual and identical across source APIs."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
AJI = REPO / 'zig-out/bin/aji'
|
||||
CORPUS = REPO / 'tests/conformance/source/repair_advice'
|
||||
checks = 0
|
||||
|
||||
|
||||
def cli(*args, code=0):
|
||||
global checks
|
||||
result = subprocess.run([str(AJI), *map(str, args)], capture_output=True, text=True)
|
||||
assert result.returncode == code, (args, result.returncode, result.stdout[:4000], result.stderr[:4000])
|
||||
checks += 1
|
||||
return result.stdout
|
||||
|
||||
|
||||
registry = {}
|
||||
section = (REPO / 'docs/reference/error-codes.md').read_text().split(
|
||||
'## Source repair candidate kinds\n', 1)[1].split('\n## ', 1)[0]
|
||||
for line in section.splitlines():
|
||||
if line.startswith('| `'):
|
||||
kind, code, hint, unit = [x.strip() for x in line.split('|')[1:-1]]
|
||||
registry[kind.strip('`')] = (code, hint, unit)
|
||||
|
||||
alternatives = {'slice_mut_type': ['slice_mut<u8>'], 'slice_ref_type': ['slice<u8>'],
|
||||
'borrow_argument': ['ref'], 'borrow_mut_argument': ['mut'],
|
||||
'numeric_cast_modes': ['as!', 'as%']}
|
||||
expected_found = {'boolean_negation': '!', 'annotate_var_type': '=',
|
||||
'slice_mut_type': 'slice', 'slice_ref_type': 'slice',
|
||||
'explicit_range_end': ']', 'borrow_argument': '&',
|
||||
'borrow_mut_argument': '&', 'borrow_binding': '&', 'zero_storage': 'zero'}
|
||||
|
||||
|
||||
def advice(error, kind, choices=None):
|
||||
code, hint, _ = registry[kind]
|
||||
expected = {'kind': kind, 'hint': hint}
|
||||
if choices is not None:
|
||||
expected['alternatives'] = choices
|
||||
assert error['code'] == code and error['repair_candidates'] == [expected], error
|
||||
assert list(error['repair_candidates'][0]) == list(expected), error
|
||||
|
||||
|
||||
cache = REPO / '.zig-cache/contract-gate'
|
||||
cache.mkdir(parents=True, exist_ok=True)
|
||||
with tempfile.TemporaryDirectory(prefix='source-advice-', dir=cache) as directory:
|
||||
root = Path(directory)
|
||||
library, entry, manifest = (root / name for name in ('lib.aji', 'main.aji', 'aji.toml'))
|
||||
manifest.write_text('[package]\nname = "advice"\nversion = "1"\nentry = "main.aji"\n'
|
||||
'[modules]\nlib.advice = "lib.aji"\n')
|
||||
entry.write_text('module app\nimport lib.advice;\nfn main() -> void effects [] {}\n')
|
||||
for path in sorted(CORPUS.glob('*.aji')):
|
||||
if path.stem == 'canonical':
|
||||
cli('check', path)
|
||||
result = json.loads(cli('run', '--fuel', '100000', path))
|
||||
assert result['value'] == 42, result
|
||||
continue
|
||||
error = json.loads(cli('check', path, code=1))
|
||||
kind = 'borrow_argument' if path.stem == 'borrow_mut_argument' else path.stem
|
||||
advice(error, kind, alternatives.get(path.stem))
|
||||
assert error['file'] == str(path) and 'air_line' not in error, error
|
||||
if kind == 'numeric_cast_modes':
|
||||
assert (error['from'], error['to']) == ('u64', 'u32'), error
|
||||
assert error['message'] == ('`as` only widens without loss; use `as!` '
|
||||
'(checked, traps T0006 when the value does not fit) or `as%` (wrapping)'), error
|
||||
else:
|
||||
assert error['found'] == expected_found[path.stem], error
|
||||
expected = ('`:` and the variable\'s type' if kind == 'annotate_var_type'
|
||||
else '`)`' if kind.startswith('slice_') else 'an expression')
|
||||
assert error['expected'] == expected and error['message'] == 'expected ' + expected, error
|
||||
# Position is the rejected token, never an invented repair range.
|
||||
text = path.read_text().splitlines()[error['line'] - 1]
|
||||
assert text[error['col'] - 1:].startswith(error['found']), error
|
||||
assert json.loads(cli('fmt', path, code=1)) == error
|
||||
for command in ('lower', 'run', 'report', 'explore'):
|
||||
assert json.loads(cli(command, path, code=1)) == error
|
||||
assert cli('check', path, code=1) == cli('check', path, code=1)
|
||||
|
||||
# Syntax and type advice survive imported/package provenance.
|
||||
library.write_text(path.read_text().replace('module advice', 'module lib.advice')
|
||||
.replace('fn main(', 'fn user('))
|
||||
package_error = json.loads(cli('check', '--manifest', manifest, code=1))
|
||||
assert package_error == dict(error, file='lib.aji'), package_error
|
||||
for command in ('lower', 'run', 'report', 'explore'):
|
||||
assert json.loads(cli(command, '--manifest', manifest, code=1)) == package_error
|
||||
|
||||
# Closed triggers: nearby unsupported spellings must not mislead the agent.
|
||||
negatives = [
|
||||
'fn main() -> void effects [] { panic!(); }',
|
||||
'fn main() -> void effects [] { var x; }',
|
||||
'fn main() -> void effects [] { let mut x = 1u64; }',
|
||||
'fn f(s: mut u64) -> void effects [] {}',
|
||||
'fn f(s: ref [u8; 3]) -> void effects [] {}',
|
||||
'fn f(s: &[u8; 3]) -> void effects [] {}',
|
||||
'fn f(s: slice<u8>) -> void effects [] { ref t = s[..2usize]; }',
|
||||
'fn f(s: slice<u8>) -> void effects [] { ref t = s[0usize..=2usize]; }',
|
||||
'fn main() -> void effects [] { for i in 0u64.. { } }',
|
||||
'fn main() -> bool effects [] { return true && false; }',
|
||||
'fn main() -> void effects [] { let x = true && false; }',
|
||||
'fn main() -> u64 effects [] { return 1u64 + &x; }',
|
||||
'fn main() -> u64 effects [] { return &x; }',
|
||||
'fn f(b: bool) -> u32 effects [] { return b as u32; }',
|
||||
'enum E { V(u64) }\nfn main() -> void effects [] { let x = 1u64; let e = E::V(&x); }',
|
||||
]
|
||||
probe = root / 'probe.aji'
|
||||
for body in negatives:
|
||||
if 'fn main(' not in body:
|
||||
body += '\nfn main() -> void effects [] {}'
|
||||
probe.write_text('module probe\n' + body + '\n')
|
||||
error = json.loads(cli('check', probe, code=1))
|
||||
assert error['code'] in ('E7001', 'E7005') and 'repair_candidates' not in error, error
|
||||
|
||||
# Valid complete slice fragments preserve nested token spellings; malformed
|
||||
# fragments get a hint only. The original >> tokens remain untouched.
|
||||
for spelling, replacement in [
|
||||
('slice< // comment\n own<u8> >', 'slice_mut<own<u8>>'),
|
||||
('slice< /*c*/ own<u8> >', None),
|
||||
('slice<[u8; 4]>', 'slice_mut<[u8;4]>'),
|
||||
('slice<Policy<fn key>>', 'slice_mut<Policy<fn key>>'),
|
||||
('slice<u8, u8>', None), ('slice<u8', None),
|
||||
('slice<mut slice<u8>>', None),
|
||||
]:
|
||||
probe.write_text(f'module probe\nfn f(s: mut {spelling}) -> void effects [] {{}}\n'
|
||||
'fn main() -> void effects [] {}\n')
|
||||
error = json.loads(cli('check', probe, code=1))
|
||||
advice(error, 'slice_mut_type', [replacement] if replacement else None)
|
||||
assert error['found'] == 'slice' and error['expected'] == '`)`', error
|
||||
|
||||
# Same malformed type trigger is recognized at different caller sites.
|
||||
for body, expected in [
|
||||
('fn main() -> void effects [] { var x: mut slice<u8> = zero; }', '`=`'),
|
||||
('fn f() -> ref slice<u8> effects [] {}', 'effects'),
|
||||
('fn f(s: ref<mut slice<u8>>) -> void effects [] {}', '`>`'),
|
||||
]:
|
||||
if 'fn main(' not in body:
|
||||
body += '\nfn main() -> void effects [] {}'
|
||||
probe.write_text('module probe\n' + body + '\n')
|
||||
error = json.loads(cli('check', probe, code=1))
|
||||
kind = 'slice_ref_type' if '-> ref slice' in body else 'slice_mut_type'
|
||||
advice(error, kind, ['slice<u8>' if kind == 'slice_ref_type' else 'slice_mut<u8>'])
|
||||
assert error['found'] == 'slice' and error['expected'] == expected, error
|
||||
|
||||
for body, kind in [
|
||||
('fn main() -> void effects [] { f(&&x); }', 'borrow_argument'),
|
||||
('fn main() -> void effects [] { var x: u64 = 1u64; let r = &mut x; }', 'borrow_binding'),
|
||||
('fn main() -> void effects [] { var r: ref<u64> = &x; }', 'borrow_binding'),
|
||||
('fn main() -> void effects [] { let x: u64 = zero; }', 'zero_storage'),
|
||||
('fn main() -> void effects [] { f(zero); }', 'zero_storage'),
|
||||
]:
|
||||
probe.write_text('module probe\n' + body + '\n')
|
||||
advice(json.loads(cli('check', probe, code=1)), kind)
|
||||
|
||||
print(f'source repair advice: {checks} checks passed')
|
||||
Reference in new issue
Block a user