#!/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'], 'slice_ref_type': ['slice'], '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: mut.Other slice) -> void effects [] {}', 'fn f(s: ref.Other slice) -> void effects [] {}', 'fn f(s: &[u8; 3]) -> void effects [] {}', 'fn f(s: slice) -> void effects [] { ref t = s[..2usize]; }', 'fn f(s: slice) -> 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 >', 'slice_mut>'), ('slice< /*c*/ own >', None), ('slice<[u8; 4]>', 'slice_mut<[u8;4]>'), ('slice>', 'slice_mut>'), ('slice', None), ('slice>', 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 = zero; }', '`=`'), ('fn f() -> ref slice effects [] {}', 'effects'), ('fn f(s: ref>) -> 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' if kind == 'slice_ref_type' else 'slice_mut']) 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 = &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) # Pointer-sized widening is rejected independently of target/value range. # Identity casts follow the same source rule instead of leaking AIR E1002. for source_type, target_type in [ ('u8', 'usize'), ('usize', 'u64'), ('i8', 'isize'), ('isize', 'i64'), ('usize', 'usize'), ('isize', 'isize'), ]: base = (f'module probe\nfn f(x: {source_type}) -> {target_type} effects [] ' '{ return x OP ' + target_type + '; }\n' 'fn main() -> void effects [] {}\n') probe.write_text(base.replace('OP', 'as')) error = json.loads(cli('check', probe, code=1)) advice(error, 'numeric_cast_modes', ['as!', 'as%']) assert (error['from'], error['to']) == (source_type, target_type), error assert 'air_line' not in error and 'air_col' not in error, error for command in ('lower', 'run', 'report', 'explore'): assert json.loads(cli(command, probe, code=1)) == error for spelling in ('as!', 'as%'): probe.write_text(base.replace('OP', spelling)) cli('check', probe) for spelling in ('u8', 'u64', 'i64'): probe.write_text(f'module probe\nfn f(x: {spelling}) -> {spelling} effects [] ' f'{{ return x as {spelling}; }}\n' 'fn main() -> void effects [] {}\n') cli('check', probe) # Parameter syntax and ordinary-call array mismatches preserve the # original envelope, across source APIs and imported bodies. call_corpus = REPO / 'tests/conformance/source/call_repair_advice' for path in sorted(call_corpus.glob('*.aji')): if path.stem == 'explicit_contracts': cli('check', path) assert json.loads(cli('run', '--fuel', '100000', path))['value'] == 42 continue error = json.loads(cli('check', path, code=1)) if path.stem == 'parameter_mutability': advice(error, 'parameter_mutability') assert (error['expected'], error['found'], error['message']) == ( 'parameter name', 'mut', 'expected parameter name'), error elif path.stem in ('array_slice_shared', 'array_slice_exclusive'): exclusive = path.stem.endswith('exclusive') advice(error, 'array_slice_argument', ['mut' if exclusive else 'ref']) assert (error['expected'], error['found'], error['message']) == ( 'slice_mut' if exclusive else 'slice', 'array', 'type mismatch'), error else: assert 'repair_candidates' not in error, error assert 'air_line' not in error and 'air_col' not in error, error for command in ('lower', 'run', 'report', 'explore'): assert json.loads(cli(command, path, code=1)) == error if error['code'] == 'E7001': assert json.loads(cli('fmt', path, code=1)) == error library.write_text(path.read_text().replace('module probe', '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 # Generic/static calls use the resolved expected type, without guessing # one from prose. Applying the explicit shared prefix is valid here. for declarations, call in [ ('fn f(s: slice) -> void effects [] {}', 'f::(a)'), ('fn f(s: slice) -> void effects [] {}\n' 'fn apply) -> void effects []>(a: [u8; 7]) ' '-> void effects [] { var b: [u8; 7] = a; F(b); }', 'apply::(a)'), ]: body = ('module probe\n' + declarations + '\nfn main() -> void effects [] ' '{ let a: [u8; 7] = [0u8; 7]; ' + call + '; }\n') probe.write_text(body) error = json.loads(cli('check', probe, code=1)) advice(error, 'array_slice_argument', ['ref']) for command in ('lower', 'run', 'report', 'explore'): assert json.loads(cli(command, probe, code=1)) == error probe.write_text(body.replace('f::(a)', 'f::(ref a)').replace('F(b)', 'F(ref b)')) cli('check', probe) assert json.loads(cli('run', '--fuel', '100000', probe))['status'] == 'returned' # A prefix is advice, not a promise of addressability. Value parameters # need local storage before an explicit borrow can verify. body = ('module probe\nfn f(s: slice) -> void effects [] {}\n' 'fn g(a: [u8; 7]) -> void effects [] { f(a); }\n' 'fn main() -> void effects [] {}\n') probe.write_text(body) advice(json.loads(cli('check', probe, code=1)), 'array_slice_argument', ['ref']) probe.write_text(body.replace('f(a)', 'f(ref a)')) error = json.loads(cli('check', probe, code=1)) assert error['code'] == 'E7006' and error['reason'] == 'invalid_place', error assert 'repair_candidates' not in error, error probe.write_text(body.replace('f(a)', 'var b: [u8; 7] = a; f(ref b)')) cli('check', probe) # Nearby mistakes and contexts without call-scoped loans receive no # array/parameter advice; earlier name/move/arity errors stay earlier. for body in [ 'fn f(mut x u8) -> void effects [] {}', 'fn f(mut ref: u8) -> void effects [] {}', 'fn f(ref x: u8) -> void effects [] {}', 'fn f(mut.x: u8) -> void effects [] {}', 'fn f(s: slice) -> void effects [] {}\n' 'fn main() -> void effects [] { f(missing); }', 'fn f(s: slice) -> void effects [] {}\n' 'fn main() -> void effects [] { let a: [u8; 7] = [0u8; 7]; f(a, a); }', 'fn g(s: slice) -> slice from s effects [] ' '{ let a: [u8; 7] = [0u8; 7]; return a; }', 'struct S { a: [u8; 7] }\nfn f(s: slice) -> void effects [] {}\n' 'fn main() -> void effects [] { let s = S { a: [0u8; 7] }; f(s.a); }', 'fn f(s: slice) -> void effects [] {}\n' 'fn main() -> void effects [] { let a: [u8; 7] = [0u8; 7]; f(move a); }', 'fn f(s: slice) -> void effects [] {}\n' 'fn main() -> void effects [] { let a: [u8; 7] = [0u8; 7]; ' 'scope workers { let t = task.spawn(workers, f, a); task.join(t); } }', ]: 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 'repair_candidates' not in error, error print(f'source repair advice: {checks} checks passed')