Files
aji/tests/hosted/source_atomic_access.py

141 lines
7.1 KiB
Python

#!/usr/bin/env python3
"""Factual E4202 payloads, early failure, concrete types and source provenance."""
import argparse
import json
from pathlib import Path
import subprocess
import tempfile
ROOT = Path(__file__).resolve().parents[2]
AJI = ROOT / 'zig-out/bin/aji'
CORPUS = ROOT / 'tests/conformance/source/atomic_access'
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--before', type=Path, help='optional previous compiler for comparison')
before = parser.parse_args().before
checks = 0
def cli(*args, status=0, binary=AJI):
global checks
result = subprocess.run([str(binary), *map(str, args)], capture_output=True)
assert result.returncode == status, (args, result.returncode, result.stdout, result.stderr)
checks += 1
return result.stdout
def unique(pairs):
result = {}
for key, value in pairs:
assert key not in result, key
result[key] = value
return result
def reject(path, scalar, *args, file=None, token=None, commands=('check', 'lower')):
text = path.read_text()
lines = text.splitlines()
if token is None:
line = next(i for i, s in enumerate(lines) if '// diagnostic here:' in s)
token = lines[line].split('// diagnostic here: ', 1)[1]
else:
line = next(i for i, s in enumerate(lines) if token in s)
col = len(lines[line][:lines[line].index(token)].encode('utf-8')) + 1
first = None
for command in commands:
extra = ['--fuel', '10000'] if command == 'run' else ['--max-runs', '1'] if command == 'explore' else []
output = cli(command, *extra, *args, status=1) if args else cli(command, *extra, path, status=1)
error = json.loads(output, object_pairs_hook=unique)
assert (error['code'], error['kind']) == ('E4202', 'atomic.ordinary_access'), error
scalars = (scalar,) if isinstance(scalar, str) else scalar
assert error['found'] in {f'ref<atomic<{t}>>' for t in scalars}, error
assert error['use'] == 'atomic.load', error
assert (error['file'], error['line'], error['col']) == (file or str(path), line + 1, col), error
assert not {'operand', 'function', 'block', 'inst', 'air_line', 'air_col'} & error.keys(), error
if first is None:
first = output
assert output == first, (command, error)
if before:
old = json.loads(cli('check', *args, status=1, binary=before) if args else
cli('check', path, status=1, binary=before), object_pairs_hook=unique)
assert {k: v for k, v in error.items() if k not in {'found', 'use'}} == old, (old, error)
return error
for name, scalar in (('parameter', 'u64'), ('u8_cell', 'u8'),
('bool_parenthesized', 'bool'), ('reborrow', 'u64')):
reject(CORPUS / f'{name}.aji', scalar)
reject(CORPUS / 'parameter.aji', 'u64', commands=('check', 'lower', 'report', 'run', 'explore'))
with tempfile.TemporaryDirectory(prefix='aji-atomic-access-') as directory:
root = Path(directory)
source = root / 'read-λ.aji'
source.write_text('module access\nfn read(r: ref<atomic<u64>>) -> u64 effects [] {\n'
' // λ\n return *r;\n}\nfn main() -> u64 effects [] { return 0; }\n')
reject(source, 'u64', token='*r')
# The first read and the selected specialization retain their concrete types.
source.write_text('module access\nfn read(r: ref<atomic<u8>>, other: ref<atomic<u64>>) -> u8 effects [] {\n'
' let first = *r; let second = *other; return first;\n}\n'
'fn main() -> u64 effects [] { return 0; }\n')
reject(source, 'u8', token='*r')
source.write_text('module access\nfn read<T>(r: ref<atomic<T>>) -> T effects [] { return *r; }\n'
'fn call(a: ref<atomic<u8>>, b: ref<atomic<u64>>) -> u8 effects [] {\n'
' let first = read::<u8>(a); let second = read::<u64>(b); return first;\n}\n'
'fn main() -> u64 effects [] { return 0; }\n')
reject(source, ('u8', 'u64'), token='*r')
source.write_text('module access\nfn read<T>(r: ref<atomic<T>>) -> T effects [] { return *r; }\n'
'fn main() -> u64 effects [] { return 42; }\n')
cli('check', source)
if before:
assert cli('lower', source) == cli('lower', source, binary=before)
entry, library, manifest = (root / name for name in ('entry.aji', 'library.aji', 'aji.toml'))
entry.write_text('module app\nimport lib;\n'
'fn call(r: ref<atomic<bool>>) -> bool effects [] { return lib.read::<bool>(r); }\n'
'fn main() -> u64 effects [] { return 42; }\n')
library.write_text('module lib\nfn read<T>(r: ref<atomic<T>>) -> T effects [] { return *r; }\n')
manifest.write_text('[package]\nname = "atomic-access"\nversion = "1"\nentry = "entry.aji"\n'
'[modules]\nlib = "library.aji"\n')
reject(library, 'bool', '--manifest', manifest, file='library.aji', token='*r')
# Other errors and ordinary non-atomic reads retain their established contract.
for body in ('let c = atomic.new(1u64); mut r = c; let x = *r; trap;',
'let c = atomic.new(1u64); mut r = c; *r = 1u64; trap;',
'let c = atomic.new(1u64); ref r = c; let x = r.value; trap;'):
source.write_text('module control\nfn main() -> void effects [] { ' + body + ' }\n')
output = cli('check', source, status=1)
error = json.loads(output)
assert error['code'] == 'E7005' and 'use' not in error, error
if before:
assert output == cli('check', source, status=1, binary=before)
source.write_text('module control\nfn main() -> u64 effects [] { let value = 42u64; ref r = value; return *r; }\n')
assert json.loads(cli('run', '--fuel', '10000', source))['value'] == 42
if before:
assert cli('lower', source) == cli('lower', source, binary=before)
# Existing verifier-origin E4202 carries a real operand and AIR coordinates.
source.write_text('module field\nstruct Holder { cell: atomic<u64> }\n'
'fn read(h: ref<Holder>) -> void effects [] { let value = h.cell; trap; }\n'
'fn main() -> void effects [] {}\n')
output = cli('check', source, status=1)
error = json.loads(output)
assert (error['code'], error['found'], error['use']) == ('E4202', 'ref<atomic<u64>>', 'atomic.load'), error
assert error['operand'].startswith('%') and 'air_line' in error, error
if before:
assert output == cli('check', source, status=1, binary=before)
valid = CORPUS / 'explicit_load.aji'
assert json.loads(cli('run', '--fuel', '10000', valid))['value'] == 42
if before:
assert cli('lower', valid) == cli('lower', valid, binary=before)
record = root / 'run.json'
cli('run', '--profile', 'hosted', '--fuel', '10000', '--result-file', record, valid)
assert json.loads(record.read_bytes())['value'] == 42
formatted = root / 'formatted.aji'
formatted.write_bytes(cli('fmt', valid))
cli('fmt', '--check', formatted)
assert cli('lower', formatted) == cli('lower', valid)
print(f'atomic access CLI integration passed ({checks} checks)')