Files
aji/tests/hosted/source_cfg_provenance.py

138 lines
5.6 KiB
Python

#!/usr/bin/env python3
"""Resource handoff, exact loan origins and source/package/AIR diagnostics."""
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 records(*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
def unique(pairs):
out = {}
for key, value in pairs:
assert key not in out, ('duplicate diagnostic field', key)
out[key] = value
return out
return [json.loads(line, object_pairs_hook=unique) for line in result.stdout.splitlines()]
def lower(*args):
global checks
result = subprocess.run([str(AJI), 'lower', *map(str, args)], capture_output=True, text=True)
assert result.returncode == 0, result
checks += 1
return result.stdout
def marker(source, text, token):
lines = [(i + 1, line) for i, line in enumerate(source.splitlines()) if text in line]
assert len(lines) == 1, lines
line, contents = lines[0]
return line, contents.index(token) + 1
def rejection(root, path, *args, file=None):
source = path.read_text()
expected = marker(source, '// diagnostic here', 'part')
# Binding diagnostics use the ref/mut keyword, not the bound name.
line = source.splitlines()[expected[0] - 1]
expected = expected[0], len(line) - len(line.lstrip()) + 1
spawn = marker(source, '// task spawn here', 'task.spawn')
ds = records('check', *args, code=1)
assert len(ds) == 1 and ds[0]['code'] == 'E4302', ds
d = ds[0]
assert (d['file'], d['line'], d['col']) == (file or str(path), *expected), d
related, = d['related_locations']
assert (related['file'], related['line'], related['col']) == (file or str(path), *spawn), related
assert related['role'] == 'task_spawn' and related['value'] == d['task'], d
for command in ('run', 'report', 'explore'):
assert records(command, *args, code=1) == ds
canonical = lower(*args)
assert canonical == lower(*args)
lines = canonical.splitlines()
assert lines[d['air_line'] - 1].strip().startswith('borrow.end '), d
assert ' = task.spawn ' in lines[related['air_line'] - 1], related
raw = root / 'lowered.air'
raw.write_text(canonical)
raw_d, = records('check', raw, code=1)
assert (raw_d['line'], raw_d['col']) == (d['air_line'], d['air_col']), raw_d
raw_related, = raw_d['related_locations']
assert (raw_related['line'], raw_related['col']) == (related['air_line'], related['air_col'])
assert raw_d['task'] == d['task'] and raw_related['value'] == d['task']
return ds
with tempfile.TemporaryDirectory(prefix='aji-cfg-provenance-') as directory:
root = Path(directory)
sources = sorted((CORPUS / 'source/cfg_provenance').glob('*.aji'))
rejected = 0
for path in sources:
source = path.read_text()
if '// expect: reject' in source:
rejected += 1
ds = rejection(root, path, path)
twin = re.search(r'^// AIR twin: (.+)$', source, re.MULTILINE)
assert twin, path
expected = records('check', CORPUS / twin[1], code=1)
assert Counter(d['code'] for d in ds) == Counter(d['code'] for d in expected)
else:
assert not records('check', path)
raw = root / 'accepted.air'
raw.write_text(lower(path))
assert not records('check', raw)
for seed in range(8):
for quantum in (1, 7):
options = ('--fuel', 100000, '--schedule-seed', seed, '--quantum', quantum)
result, = records('run', *options, path)
reference, = records('run', *options, raw)
assert result == reference, (path, result, reference)
assert result['value'] == 7, result
# Explicitly execute the other tuple permutation; scheduler seeds alone
# cannot change a constant branch condition.
permuted = root / 'permuted.air'
source = (CORPUS / 'phase3/run/cfg_provenance_correlated_scopes.air').read_text()
permuted.write_text(source.replace('const.bool true', 'const.bool false'))
assert not records('check', permuted)
for seed in range(8):
result, = records('run', '--fuel', 100000, '--schedule-seed', seed, '--quantum', 1, permuted)
assert result['value'] == 21, result
# Package/generic specialization retains the provider's factual positions.
library = root / 'library.aji'
source = (CORPUS / 'source/cfg_provenance/cancel_join_twice_keeps_spawn.aji').read_text()
source = re.sub(r'^module .+$', 'module app.library', source, flags=re.MULTILINE)
library.write_text(source.replace('fn main()', 'fn bad<T: Copy>()'))
(root / 'entry.aji').write_text('''module app.entry
import app.library;
fn main() -> u8 effects [task.spawn, task.wait] {
return app.library.bad::<u8>();
}
''')
manifest = root / 'aji.toml'
manifest.write_text('''[package]
name = "provenance"
version = "1"
entry = "entry.aji"
[modules]
app.library = "library.aji"
''')
rejection(root, library, '--manifest', manifest, file='library.aji')
shield = records('check', CORPUS / 'phase3/reject/cfg_provenance_shield_stack_join.air', code=1)
assert [d['code'] for d in shield] == ['E3002', 'E4305'], shield
assert shield[0]['resource'].startswith('%'), shield
assert rejected == 3, rejected
print(f'source CFG provenance: {checks} CLI checks, {rejected} loan rejection twins')