Files
aji/tests/hosted/source_repair_advice.py
T

159 lines
8.1 KiB
Python

#!/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')