Files
aji/tests/hosted/source_nominal_queries.py

112 lines
6.0 KiB
Python

#!/usr/bin/env python3
"""Deep shared types: CLI/format/profile parity and imported cache indices."""
import json
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/nominal_queries'
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
with tempfile.TemporaryDirectory(prefix='aji-nominal-queries-') as directory:
root = Path(directory)
for source in sorted(CORPUS.glob('*.aji')):
formatted = root / source.name
formatted.write_text(cli('fmt', source))
cli('fmt', '--check', formatted)
assert cli('fmt', formatted) == formatted.read_text()
if '// expect: reject' in source.read_text():
diagnostics = cli('check', source, code=1)
for command in ('run', 'report', 'explore'):
assert cli(command, source, code=1) == diagnostics
records = [json.loads(line) for line in diagnostics.splitlines()]
assert all(d['file'] == str(source) for d in records), records
if source.stem == 'cycle':
assert (records[0]['code'], records[0]['type'], records[0]['line']) == ('E1003', 'N0', 6)
elif source.stem == 'constraint_depth':
assert records[0]['reason'] == 'implementation_limit'
elif source.stem == 'diamond_21_u64':
assert [d['found'] for d in records] == [16777216, 8388608, 4194304, 2097152]
# Lowering emits AIR; the subsequent budget stage rejects it.
raw = root / 'oversized.air'
raw.write_text(cli('lower', source))
raw_records = [json.loads(line) for line in cli('check', raw, code=1).splitlines()]
assert [(d['code'], d['found']) for d in raw_records] == [(d['code'], d['found']) for d in records]
if source.stem != 'diamond_21_u64':
assert cli('lower', source, code=1) == diagnostics
continue
air = cli('lower', source)
assert cli('lower', formatted) == air
raw = root / f'{source.stem}.air'
raw.write_text(air)
cli('check', raw)
expected = json.loads(cli('run', '--fuel', '100000', source))
assert expected['value'] == 42, expected
assert json.loads(cli('run', '--fuel', '100000', raw)) == expected
result = root / f'{source.stem}.json'
cli('run', '--profile', 'hosted', '--fuel', '100000', '--result-file', result, source)
assert json.loads(result.read_text())['value'] == 42
library, entry, manifest = (root / name for name in ('nodes.aji', 'main.aji', 'aji.toml'))
library.write_text('module lib.nodes\n' + '\n'.join(
f'struct N{i} {{ a: N{i + 1} }}' for i in range(40)) + '\nstruct N40 { x: u64 }\n')
entry.write_text('module app\nimport lib.nodes;\n'
'fn marker<T: Copy + Send + Share + Freeze>() -> u64 effects [] { return 42; }\n'
'fn main() -> u64 effects [] { return marker::<lib.nodes.N0>(); }\n')
manifest.write_text('[package]\nname = "nodes"\nversion = "1"\nentry = "main.aji"\n'
'[modules]\nlib.nodes = "nodes.aji"\n')
assert json.loads(cli('run', '--manifest', manifest))['value'] == 42
# Actual allocation accounting reads a verified nominal cache at runtime.
allocated = root / 'allocated.aji'
declarations = library.read_text().replace('module lib.nodes', 'module app')
bindings = 'let n40 = N40 { x: 42u64 };\n' + '\n'.join(
f'let n{i} = N{i} {{ a: n{i + 1} }};' for i in reversed(range(40)))
allocated.write_text(declarations + '\nfn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {\n' +
bindings + '\nlet p = own.new(n0, heap) or trap; let n = own.take(move p);\nreturn n' + '.a' * 40 + '.x; }\n')
raw = root / 'allocated.air'
raw.write_text(cli('lower', allocated))
grants = ['--grant', 'heap=mem.alloc:8']
result = json.loads(cli('run', '--fuel', '100000', *grants, allocated))
assert result['value'] == 42, result
assert json.loads(cli('run', '--fuel', '100000', *grants, raw)) == result
library.write_text(library.read_text().replace('struct N40 { x: u64 }', 'struct N40 { x: N0 }'))
record = json.loads(cli('check', '--manifest', manifest, code=1))
assert (record['code'], record['file'], record['line']) == ('E1003', 'nodes.aji', 2), record
assert record['type'].endswith('N0'), record
# A shallow field expression must not recursively walk its deep annotation
# in the best-effort type query used by `.len`. Main executes only a scalar;
# these probes exercise compiler paths, not materialization of deep values.
for depth in (16384, 65536):
annotation = '[' * depth + 'u8' + ';1]' * depth
source = root / f'field-type-{depth}.aji'
source.write_text('module field.types\nstruct Record { x: ' + annotation + ' }\n'
'fn size(r: Record) -> usize effects [] { r.x.len }\n'
'fn main() -> u64 effects [] { 42u64 }\n')
cli('check', source)
lowered = cli('lower', source)
assert 'const.usize 1' in lowered, lowered[-200:]
raw = root / f'field-type-{depth}.air'
raw.write_text(lowered)
cli('check', raw)
formatted = root / f'field-type-{depth}-formatted.aji'
formatted.write_text(cli('fmt', source))
cli('fmt', '--check', formatted)
assert cli('lower', formatted) == lowered
assert json.loads(cli('run', '--fuel', '100', source))['value'] == 42
assert json.loads(cli('run', '--fuel', '100', raw))['value'] == 42
assert json.loads(cli('report', source)) == json.loads(cli('report', raw))
print(f'nominal query CLI integration passed ({checks} checks)')