#!/usr/bin/env python3 """Q-064: CFG loop exits, name collisions, diagnostic priority and packages.""" 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/loop_exit' checks = 0 def cli(*args, code=0): global checks p = subprocess.run([str(AJI), *map(str, args)], capture_output=True) assert p.returncode == code, (args, p.returncode, p.stdout, p.stderr) assert not p.stderr, (args, p.stderr) checks += 1 return p.stdout def diagnostics(path, expected, args=None): arguments = args if args is not None else [path] output = cli('check', *arguments, code=1) records = [json.loads(line) for line in output.splitlines()] assert len(records) == len(expected), records for d, (code, reason, marker) in zip(records, expected): assert (d['code'], d.get('reason')) == (code, reason), d assert 'air_line' not in d and 'air_code' not in d, d line = path.read_text().splitlines()[d['line'] - 1] assert line[d['col'] - 1:].startswith(marker), (d, line, marker) assert d['file'] == (path.name if args is not None else str(path)), d for command in ('lower', 'run', 'report'): assert cli(command, *arguments, code=1) == output, (command, records) assert cli('check', *arguments, code=1) == output return records with tempfile.TemporaryDirectory(prefix='aji-loop-exit-') as directory: root = Path(directory) # Conformance pins acceptance; these assertions additionally pin reason, # source coordinates, stable CLI bytes and canonical formatted lowering. for source in sorted(CORPUS.glob('*.aji')): text = source.read_text() if '// expect: reject E7006' in text: diagnostics(source, [('E7006', 'unreachable', 'return 1u64;')]) continue air = cli('lower', source) air_path = root / (source.stem + '.air') air_path.write_bytes(air) cli('check', source) cli('check', air_path) formatted = root / source.name formatted.write_bytes(cli('fmt', source)) assert cli('fmt', formatted) == formatted.read_bytes() assert cli('lower', formatted) == air expected = int(re.search(r'// result: (\d+)', text)[1]) for fuel in (0, 1, 2, 4, 8, 16, 32, 64, 256): code = None records = [] # Fuel limits may reject at different source/AIR positions only # for traps. These fixtures return or exhaust fuel, so exact bytes # and exits must match between the source and its canonical AIR. for path in (source, air_path): p = subprocess.run([str(AJI), 'run', '--fuel', str(fuel), str(path)], capture_output=True) checks += 1 assert p.returncode in (0, 5) and not p.stderr, (path, p) if code is None: code = p.returncode assert p.returncode == code, (path, fuel, p.stdout) records.append(p.stdout) assert records[0] == records[1], (source, fuel, records) if fuel == 256: assert json.loads(records[0]) == {'status': 'returned', 'value': expected} # Names and name prefixes never replace the syntactic exit edge. Both # branch outcomes remain explicit; constant conditions are not folded. for parameter in ('after_2', 'after_20', 'after_2suffix', 'flag'): source = root / (parameter + '.aji') source.write_text(f'module exits\nfn f({parameter}: bool) -> u64 effects [] {{\n' f' while {parameter} {{ return 7u64; }}\n' ' return 42u64;\n}\n' 'fn main() -> u64 effects [] { f(false) }\n') cli('check', source) assert json.loads(cli('run', '--fuel', '256', source))['value'] == 42 source.write_text(source.read_text().replace('f(false)', 'f(true)')) assert json.loads(cli('run', '--fuel', '256', source))['value'] == 7 source = root / 'syntactic-break.aji' source.write_text('module exits\nfn main() -> u64 effects [] {\n' ' loop { if false { break; } }\n return 42u64;\n}\n') cli('check', source) assert json.loads(cli('run', '--fuel', '256', source, code=5))['status'] == 'limit_exceeded' # The unreachable statement wins over its own unknown name/type error; # earlier body and signature errors keep their existing priority. prefix = 'module priority\nfn after_2() -> void effects [] {}\n' cases = [ ('late_name', prefix + 'fn main() -> u64 effects [] {\n' ' loop { after_2(); return 0u64; }\n missing();\n}\n', [('E7006', 'unreachable', 'missing();')]), ('late_type', prefix + 'fn main() -> u64 effects [] {\n' ' loop { after_2(); return 0u64; }\n return true;\n}\n', [('E7006', 'unreachable', 'return true;')]), ('early_name', prefix + 'fn main() -> u64 effects [] {\n' ' loop { after_2(); missing(); return 0u64; }\n return 1u64;\n}\n', [('E7002', None, 'missing')]), ('early_type', prefix + 'fn main() -> u64 effects [] {\n' ' loop { after_2(); return true; }\n return 1u64;\n}\n', [('E7005', None, 'true')]), ('signature', prefix + 'fn main(x: void) -> u64 effects [] {\n' ' loop { after_2(); return 0u64; }\n return 1u64;\n}\n', [('E7005', None, 'void')]), ('independent', prefix + 'fn first() -> u64 effects [] { missing() }\n' 'fn main() -> u64 effects [] {\n' ' loop { after_2(); return 0u64; }\n return 1u64;\n}\n', [('E7002', None, 'missing'), ('E7006', 'unreachable', 'return 1u64;')]), ('tail', prefix + 'fn main() -> u64 effects [] {\n' ' loop { after_2(); return 0u64; }\n 1u64\n}\n', [('E7006', 'unreachable', '1u64')]), ('never_call', 'module priority\nfn after_2() -> never effects [] { trap; }\n' 'fn main() -> u64 effects [] {\n loop { after_2(); }\n return 1u64;\n}\n', [('E7006', 'unreachable', 'return 1u64;')]), ] for name, text, expected in cases: source = root / (name + '.aji') source.write_text(text) diagnostics(source, expected) # Imported bodies retain source provenance after symbol mangling and # function-local metadata reset, for both corrected acceptance directions. entry, lib, manifest = (root / name for name in ('main.aji', 'lib.aji', 'aji.toml')) entry.write_text('module app\nimport lib;\nfn main() -> u64 effects [] { lib.f(false) }\n') manifest.write_text('[package]\nname = "exits"\nversion = "1"\nentry = "main.aji"\n' '[modules]\nlib = "lib.aji"\n') lib.write_text('module lib\nfn f(after_2: bool) -> u64 effects [] {\n' ' while after_2 { return 7u64; }\n return 42u64;\n}\n') cli('check', '--manifest', manifest) assert json.loads(cli('run', '--fuel', '256', '--manifest', manifest))['value'] == 42 lib.write_text('module lib\nfn after_2() -> void effects [] {}\n' 'fn f(flag: bool) -> u64 effects [] {\n' ' loop { after_2(); return 0u64; }\n return 1u64;\n}\n') diagnostics(lib, [('E7006', 'unreachable', 'return 1u64;')], ['--manifest', manifest]) print(f'source loop exit passed ({checks} CLI checks)')