Files
aji/tests/hosted/source_grammar.py
T

119 lines
6.2 KiB
Python

#!/usr/bin/env python3
"""Grammar boundaries, exact syntax positions and source/AIR/formatter fidelity."""
import json
import re
from pathlib import Path
import subprocess
import tempfile
REPO = Path(__file__).resolve().parents[2]
AJI = REPO / 'zig-out/bin/aji'
CORPUS = REPO / 'tests/conformance/source/grammar_surface'
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 position(source, offset):
return source[:offset].count('\n') + 1, offset - source.rfind('\n', 0, offset)
with tempfile.TemporaryDirectory(prefix='aji-grammar-') as directory:
root = Path(directory)
for path in sorted(CORPUS.glob('*.aji')):
source = path.read_text()
if '// expect: reject' in source:
error = json.loads(cli('check', path, code=1))
assert error['code'] == re.search(r'// expect: reject (E\d+)', source)[1] and error['file'] == str(path), 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
assert json.loads(cli('fmt', '--check', path, code=1)) == error
else:
cli('fmt', path)
if path.name.startswith('empty_'):
# Qualified payload syntax points at the empty list, even
# across comments/newlines; never at a declaration/function.
marker = '::budget_exceeded' if '::budget_exceeded' in source else '::Pair' if 'empty_payload' in path.name else '::Empty'
if 'pattern' in path.name:
start = source.rindex(marker)
else:
start = source.index(marker, source.index('fn '))
offset = source.index('(', start)
assert (error['line'], error['col']) == position(source, offset), error
assert error['found'] == '(' and 'payload' in error['expected'], error
continue
cli('check', path)
formatted = root / path.name
formatted.write_text(cli('fmt', path))
cli('fmt', '--check', formatted)
assert cli('fmt', formatted) == formatted.read_text()
lowered = cli('lower', path)
assert cli('lower', formatted) == lowered
air = root / (path.stem + '.air')
air.write_text(lowered)
cli('check', air)
if '// expect: run' in source:
grants = [value for grant in re.findall(r'// grant: (.+)', source) for value in ('--grant', grant)]
result = json.loads(cli('run', '--fuel', '100000', *grants, path))
assert result == json.loads(cli('run', '--fuel', '100000', *grants, air))
assert result == json.loads(cli('run', '--fuel', '100000', *grants, formatted))
assert result['value'] == 42, result
# Prefix depth is a parser/formatter regression, not an acceptance bound
# or a claim about all lowering paths (Q-061). Unary lowering has separate
# full-pipeline coverage in source_expression_depth.py.
for depth in (1024, 16384, 65536):
prefix = 'module deep\nfn main() -> bool effects [] { return ' + 'not ' * depth
deep = root / f'deep-{depth}.aji'
deep.write_text(prefix + 'false; }\n')
output = cli('fmt', deep)
assert output.count('not ') == depth and output.count('false') == 1
formatted = root / f'deep-{depth}.formatted.aji'
formatted.write_text(output)
assert cli('fmt', formatted) == output
deep.write_text(prefix + '; }\n')
error = json.loads(cli('check', deep, code=1))
assert (error['code'], error['expected'], error['found'], error['file']) == (
'E7001', 'an expression', ';', str(deep)), error
assert (error['line'], error['col']) == position(prefix, len(prefix)), error
for command in ('lower', 'run', 'report', 'explore', 'fmt'):
assert json.loads(cli(command, deep, code=1)) == error
# Imported qualifiers take the same syntax path and retain the actual file.
helper = root / 'model.aji'
helper.write_text('module app.model\nenum Value<T> { Empty, Payload(T), }\n')
main = root / 'main.aji'
main.write_text('module app.main\nimport app.model;\nfn main() -> u64 effects [] { let value = app.model.Value::<u64>::Empty(); return 42u64; }\n')
manifest = root / 'aji.toml'
manifest.write_text('[package]\nname = \"grammar\"\nversion = \"0.1.0\"\nentry = \"main.aji\"\n[modules]\napp.model = \"model.aji\"\n')
error = json.loads(cli('check', '--manifest', manifest, code=1))
assert error['code'] == 'E7001' and error['file'] == str(main), error
offset = main.read_text().index('(', main.read_text().index('::Empty'))
assert (error['line'], error['col']) == position(main.read_text(), offset), error
main.write_text(main.read_text().replace('::Empty()', '::Empty'))
cli('check', '--manifest', manifest)
assert json.loads(cli('run', '--fuel', '100000', '--manifest', manifest))['value'] == 42
main.write_text('module app.main\nimport app.model;\n'
'fn main() -> u64 effects [] { let value = app.model.Value::<u64>::Empty; '
'return match value { app.model.Value::<u64>::Empty() => 42u64, '
'app.model.Value::<u64>::Payload(_) => 0u64 }; }\n')
error = json.loads(cli('check', '--manifest', manifest, code=1))
assert error['code'] == 'E7001' and error['file'] == str(main), error
offset = main.read_text().index('(', main.read_text().rindex('::Empty'))
assert (error['line'], error['col']) == position(main.read_text(), offset), error
for command in ('lower', 'run', 'report', 'explore'):
assert json.loads(cli(command, '--manifest', manifest, code=1)) == error
main.write_text(main.read_text().replace('::Empty()', '::Empty'))
assert json.loads(cli('run', '--fuel', '100000', '--manifest', manifest))['value'] == 42
print(f'source grammar: {checks} checks passed')