#!/usr/bin/env python3 """Source/AIR rejection twins and exact lifetime diagnostic provenance.""" from collections import Counter 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' 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, result.stderr) checks += 1 return result.stdout def records(output): def unique(pairs): result = {} for key, value in pairs: assert key not in result, ('duplicate JSON member', key) result[key] = value return result return [json.loads(line, object_pairs_hook=unique) for line in output.splitlines()] def codes(diagnostics): return Counter(d['code'] for d in diagnostics if d['severity'] == 'error') def marked_positions(source): marked = [(i + 1, line) for i, line in enumerate(source.splitlines()) if '// diagnostic here' in line] assert marked, source positions = [] for line, text in marked: if '// diagnostic here: ' in text: start = text.split('// diagnostic here: ', 1)[1] positions.append((line, text.index(start) + 1)) else: positions.append((line, len(text) - len(text.lstrip()) + 1)) return positions def source_rejection(root, path, *args, expected_file=None): source = path.read_text() expected_positions = marked_positions(source) output = cli('check', *args, code=1) errors = records(output) assert [(d['file'], d['line'], d['col']) for d in errors] == [ (expected_file or str(path), *position) for position in expected_positions], errors for command in ('check', 'run', 'report', 'explore'): assert cli(command, *args, code=1) == output, (command, args) canonical = cli('lower', *args) assert cli('lower', *args) == canonical annotated = cli('lower', '--annotate', *args) lines = [] mapping = {} pending = None for line in annotated.splitlines(): match = re.fullmatch(r'\s*; (?:(.+):)?(\d+):(\d+)-\d+:\d+', line) if match: pending = (match[1], int(match[2]), int(match[3])) continue lines.append(line) mapping[len(lines)] = pending if line.endswith(':'): assert pending is not None, ('block label lacks source annotation', line) pending = None assert '\n'.join(lines) + '\n' == canonical lowered = root / 'lowered.air' lowered.write_text(canonical) raw = records(cli('check', lowered, code=1)) assert codes(raw) == codes(errors), (raw, errors) assert len(raw) == len(errors), (raw, errors) for error, air_error in zip(errors, raw): assert (error['air_line'], error['air_col']) == ( air_error['line'], air_error['col']), (raw, error) origin = mapping[error['air_line']] assert origin is not None and origin[1:] == (error['line'], error['col']), error if expected_file: assert origin[0] == expected_file, origin # A control-flow merge error belongs to its generated label. Instruction # errors retain their original instruction positions instead. air_line = canonical.splitlines()[error['air_line'] - 1] if path.name == 'resource_join_mismatch.aji': assert air_line.startswith('endif_') and air_line.endswith(':'), air_line return errors with tempfile.TemporaryDirectory(prefix='aji-lifetimes-') as directory: root = Path(directory) twins = sorted((CORPUS / 'source/lifetimes').glob('*.aji')) paired = 0 for path in twins: source = path.read_text() if '// expect: reject' not in source: continue errors = source_rejection(root, path, path) twin = re.search(r'^// AIR twin: (.+)$', source, re.MULTILINE) if twin is None: continue paired += 1 air_errors = records(cli('check', CORPUS / twin[1], code=1)) expected = re.search(r'^// expect: reject (.+)$', source, re.MULTILINE)[1] assert codes(errors) == codes(air_errors) == Counter(expected.split()), ( path, errors, air_errors) assert paired == 8, paired # Imported specialization keeps the original provider's join position. library = root / 'library.aji' template = (CORPUS / 'source/lifetimes/resource_join_mismatch.aji').read_text() body = template[template.index('fn close_on_one_path'):template.index('fn main')] body = body.replace('close_on_one_path(', 'close_on_one_path(') body = body.replace('close_it: bool)', 'close_it: bool, tag: T)') library.write_text('module app.library\n\n' + body) entry = root / 'entry.aji' entry.write_text('''module app.entry import app.library; fn main(src: cap) -> void effects [fs.read] { app.library.close_on_one_path::(src, true, 1u64); } ''') manifest = root / 'aji.toml' manifest.write_text('''[package] name = "lifetimes" version = "1" entry = "entry.aji" [modules] app.library = "library.aji" ''') source_rejection(root, library, '--manifest', manifest, expected_file='library.aji') print(f'source lifetimes: {checks} CLI checks, {paired} AIR rejection twins')