Files
aji/tests/hosted/source_expression_depth.py
T

280 lines
17 KiB
Python

#!/usr/bin/env python3
"""Operand/generic depth, exact lowering/CFG/fuel and rejection positions (Q-061)."""
import json
from pathlib import Path
import subprocess
import tempfile
REPO = Path(__file__).resolve().parents[2]
AJI = REPO / 'zig-out/bin/aji'
checks = 0
def cli(command, path, *options, code=0):
global checks
result = subprocess.run([str(AJI), command, *map(str, options), str(path)], capture_output=True)
assert (result.returncode, result.stderr) == (code, b''), (command, path, result.returncode, result.stdout, result.stderr)
checks += 1
return result.stdout
def source(kind, depth):
if kind == 'not':
ty, setup, expression = 'bool', '', 'not ' * depth + 'false'
instructions, expected = 2 * depth + 2, bool(depth % 2)
elif kind in ('neg', 'inferred_neg'):
setup = 'let n = 1; ' if kind == 'inferred_neg' else 'let n: i64 = 1i64; '
ty, expression = 'i64', '- ' * depth + 'n'
instructions, expected = 2 * depth + 2, 1 if depth % 2 == 0 else -1
else:
ty, setup = 'i64', ''
expression = '1i64' + ''.join(' ' + ('as i64', 'as! i64', 'as% i64')[i % 3] for i in range(depth))
instructions, expected = depth + 2, 1
return f'module depth\nfn main() -> {ty} effects [] {{ {setup}return {expression}; }}\n', instructions, expected
with tempfile.TemporaryDirectory(prefix='aji-expression-depth-') as directory:
root = Path(directory)
for depth in (0, 1, 16, 1024, 16384, 65536):
for kind in ('not', 'neg', 'cast', 'inferred_neg'):
path = root / f'{kind}-{depth}.aji'
text, instructions, expected = source(kind, depth)
path.write_text(text)
assert cli('check', path) == b''
lowered = cli('lower', path)
actual = sum(b' = ' in line or line.strip().startswith(b'ret ') for line in lowered.splitlines())
assert actual == instructions, (kind, depth, actual, instructions)
if depth <= 1024:
# Independently count every emitted instruction and ret.
# No wall-clock timeout changes execution or ends a test.
assert json.loads(cli('run', path, '--fuel', instructions)) == {'status': 'returned', 'value': expected}
assert json.loads(cli('run', path, '--fuel', instructions - 1, code=5)) == {
'status': 'limit_exceeded', 'kind': 'fuel', 'limit': instructions - 1, 'steps': instructions - 1}
air = path.with_suffix('.air')
air.write_bytes(lowered)
assert cli('run', air, '--fuel', instructions) == cli('run', path, '--fuel', instructions)
record = root / 'hosted.json'
assert cli('run', path, '--fuel', instructions, '--profile', 'hosted', '--result-file', record) == b''
assert json.loads(record.read_text()) == {'status': 'returned', 'value': expected}
print(f'unary depth: {kind} {depth}', flush=True)
for depth in (0, 1, 16, 1024, 16384, 65536):
path = root / f'add-{depth}.aji'
path.write_text('module depth\nfn main() -> i64 effects [] { return ' + ' + '.join(['1i64'] * (depth + 1)) + '; }\n')
assert cli('check', path) == b''
lowered = cli('lower', path)
instructions = 2 * depth + 2
assert sum(b' = ' in line or line.strip().startswith(b'ret ') for line in lowered.splitlines()) == instructions
if depth <= 1024:
assert json.loads(cli('run', path, '--fuel', instructions)) == {'status': 'returned', 'value': depth + 1}
assert json.loads(cli('run', path, '--fuel', instructions - 1, code=5)) == {
'status': 'limit_exceeded', 'kind': 'fuel', 'limit': instructions - 1, 'steps': instructions - 1}
air = path.with_suffix('.air')
air.write_bytes(lowered)
assert cli('run', air, '--fuel', instructions) == cli('run', path, '--fuel', instructions)
record = root / 'hosted.json'
assert cli('run', path, '--fuel', instructions, '--profile', 'hosted', '--result-file', record) == b''
assert json.loads(record.read_text()) == {'status': 'returned', 'value': depth + 1}
print(f'binary depth: add {depth}', flush=True)
for depth in (0, 1, 16, 256, 1024):
for op in ('and', 'or'):
for short in (False, True):
path = root / f'{op}-{short}-{depth}.aji'
value = (op == 'and') != short
leaf = 'true' if op == 'and' else 'false'
text = ('true' if value else 'false') + (' ' + op + ' ' + leaf) * depth
path.write_text('module depth\nfn main() -> bool effects [] { return ' + text + '; }\n')
assert cli('check', path) == b''
lowered = cli('lower', path)
# Every node emits a short constant, cbr, RHS literal and br.
instructions = sum(b' = ' in line or line.strip().startswith((b'ret ', b'cbr ', b'br ')) for line in lowered.splitlines())
assert instructions == 4 * depth + 2, (op, short, depth, instructions)
if depth <= 256:
fuel = (2 if short else 4) * depth + 2
assert json.loads(cli('run', path, '--fuel', fuel)) == {'status': 'returned', 'value': value}
assert json.loads(cli('run', path, '--fuel', fuel - 1, code=5)) == {
'status': 'limit_exceeded', 'kind': 'fuel', 'limit': fuel - 1, 'steps': fuel - 1}
air = path.with_suffix('.air')
air.write_bytes(lowered)
assert cli('run', air, '--fuel', fuel) == cli('run', path, '--fuel', fuel)
record = root / 'hosted.json'
assert cli('run', path, '--fuel', fuel, '--profile', 'hosted', '--result-file', record) == b''
assert json.loads(record.read_text()) == {'status': 'returned', 'value': value}
print(f'binary depth: {op} short={short} {depth}', flush=True)
# The same lowering reaches the existing normative block limit, not a
# host-stack failure. `lower` emits AIR; verification entry points reject it.
limit_path = root / 'boolean-block-limit.aji'
limit_path.write_text('module depth\nfn main() -> bool effects [] { return ' + ' and '.join(['true'] * 16385) + '; }\n')
error = json.loads(cli('check', limit_path, code=1))
assert (error['code'], error['kind'], error['limit'], error['max'], error['found']) == (
'E5101', 'verifier.resource_limit', 'blocks per function', 16384, 32769), error
assert (error['file'], error['line'], error['col']) == (str(limit_path), 2, 1), error
limit_air = cli('lower', limit_path)
assert limit_air.startswith(b'module depth\n')
assert sum(line.rstrip().endswith(b':') for line in limit_air.splitlines()) == 32769
# The skipped operand still lowers, but its division trap must not execute.
for op in ('and', 'or'):
for short in (False, True):
value = (op == 'and') != short
path = root / f'short-trap-{op}-{short}.aji'
path.write_text('module depth\nfn main() -> bool effects [] { return ' + ('true' if value else 'false') + ' ' + op + ' bad(); }\n'
'fn bad() -> bool effects [] { return (1u64 / 0u64) == 0u64; }\n')
assert cli('check', path) == b''
air = path.with_suffix('.air')
air.write_bytes(cli('lower', path))
if short:
result = cli('run', path, '--fuel', 4)
assert json.loads(result) == {'status': 'returned', 'value': value}
assert cli('run', air, '--fuel', 4) == result
assert json.loads(cli('run', path, '--fuel', 3, code=5)) == {
'status': 'limit_exceeded', 'kind': 'fuel', 'limit': 3, 'steps': 3}
else:
result = cli('run', path, '--fuel', 7, code=4)
trap = json.loads(result)
assert (trap['status'], trap['code'], trap['kind'], trap['function'], trap['inst']) == (
'trapped', 'T0004', 'trap.division_by_zero', 'bad', 2), trap
assert trap.pop('source_location') == {'file': str(path), 'line': 3, 'col': 39}
assert json.loads(cli('run', air, '--fuel', 7, code=4)) == trap
assert json.loads(cli('run', path, '--fuel', 6, code=5)) == {
'status': 'limit_exceeded', 'kind': 'fuel', 'limit': 6, 'steps': 6}
for depth in (1024, 16384, 65536):
# A cast removes the expected-use hint; deep traversal must retain
# E7007 at the original unsuffixed initializer, without new inference.
hint_header = 'module depth\nfn main() -> i64 effects [] { let n = '
path = root / f'inferred-no-hint-{depth}.aji'
path.write_text(hint_header + '1; return (' + '- ' * depth + 'n) as i64; }\n')
error = json.loads(cli('check', path, code=1))
col = len(hint_header.split('\n')[-1]) + 1
assert (error['code'], error['line'], error['col'], error['file']) == ('E7007', 2, col, str(path)), error
for command in ('lower', 'run', 'report', 'explore'):
assert json.loads(cli(command, path, code=1)) == error
header = 'module depth\nfn main() -> i64 effects [] { return '
path = root / f'deref-{depth}.aji'
path.write_text(header + '* ' * depth + '1i64; }\n')
error = json.loads(cli('check', path, code=1))
col = len(header) - len('module depth\n') + 1 + 2 * (depth - 1)
assert (error['code'], error['line'], error['col'], error['file']) == ('E7005', 2, col, str(path)), error
for command in ('lower', 'run', 'report', 'explore'):
assert json.loads(cli(command, path, code=1)) == error
# A cast queries its operand before lowering it. This used to abort
# in peekType even after direct unary lowering had been repaired.
cast_header = header + '('
path = root / f'cast-deref-{depth}.aji'
path.write_text(cast_header + '* ' * depth + '1i64) as i64; }\n')
error = json.loads(cli('check', path, code=1))
col = len(cast_header) - len('module depth\n') + 1 + 2 * (depth - 1)
assert (error['code'], error['line'], error['col'], error['file']) == ('E7005', 2, col, str(path)), error
for command in ('lower', 'run', 'report', 'explore'):
assert json.loads(cli(command, path, code=1)) == error
# Callee lookup and bounded built-in path recognition also stay flat.
for depth in (16384, 65536):
path = root / f'callee-{depth}.aji'
path.write_text('module depth\nfn main() -> i64 effects [] { return ' + 'ns.' * depth + 'unknown() as i64; }\n')
error = json.loads(cli('check', path, code=1))
assert error['code'] == 'E7002' and error['file'] == str(path), error
for command in ('lower', 'run', 'report', 'explore'):
assert json.loads(cli(command, path, code=1)) == error
# Force monomorphization: every body traverses generic AST cloning before
# ordinary lowering. These are full CLI acceptance/fuel tests, separate
# from synthetic mixed-AST helper tests that need not be valid programs.
for depth in (0, 1, 16, 1024, 16384, 65536):
for kind in ('not', 'neg', 'cast', 'add'):
if kind == 'not':
ty, argument = 'bool', 'false'
expression, expected, instructions = 'not ' * depth + 'x', bool(depth % 2), 2 * depth + 4
elif kind == 'neg':
ty, argument = 'i64', '1i64'
expression, expected, instructions = '- ' * depth + 'x', 1 if depth % 2 == 0 else -1, 2 * depth + 4
elif kind == 'cast':
ty, argument = 'i64', '1i64'
expression = 'x' + ''.join(' ' + ('as i64', 'as! i64', 'as% i64')[i % 3] for i in range(depth))
expected, instructions = 1, depth + 4
else:
ty, argument = 'i64', '1i64'
expression, expected, instructions = 'x' + ' + 1i64' * depth, depth + 1, 2 * depth + 4
path = root / f'generic-{kind}-{depth}.aji'
path.write_text('module depth\nfn f<T>(x: T) -> T effects [] { return ' + expression + '; }\n'
f'fn main() -> {ty} effects [] {{ return f::<{ty}>({argument}); }}\n')
assert cli('check', path) == b''
lowered = cli('lower', path)
assert sum(b' = ' in line or line.strip().startswith(b'ret ') for line in lowered.splitlines()) == instructions
if depth <= 1024:
returned = cli('run', path, '--fuel', instructions)
assert json.loads(returned) == {'status': 'returned', 'value': expected}
assert json.loads(cli('run', path, '--fuel', instructions - 1, code=5)) == {
'status': 'limit_exceeded', 'kind': 'fuel', 'limit': instructions - 1, 'steps': instructions - 1}
air = path.with_suffix('.air')
air.write_bytes(lowered)
assert cli('run', air, '--fuel', instructions) == returned
record = root / 'hosted.json'
assert cli('run', path, '--fuel', instructions, '--profile', 'hosted', '--result-file', record) == b''
assert json.loads(record.read_text()) == json.loads(returned)
print(f'generic depth: {kind} {depth}', flush=True)
for depth in (1024, 16384, 65536):
header = 'fn f<T>(x: T) -> T effects [] { return '
path = root / f'generic-deref-{depth}.aji'
path.write_text('module depth\n' + header + '* ' * depth + 'x; }\n'
'fn main() -> i64 effects [] { return f::<i64>(1i64); }\n')
error = json.loads(cli('check', path, code=1))
assert (error['code'], error['line'], error['col'], error['file']) == (
'E7005', 2, len(header) + 1 + 2 * (depth - 1), str(path)), error
for command in ('lower', 'run', 'report', 'explore'):
assert json.loads(cli(command, path, code=1)) == error
for depth in (16384, 65536):
# An unused template still forces transformation of nongeneric bodies.
# Formerly generics.path aborted before unknown-callee diagnostics.
name = 'ns.' * depth + 'unknown'
header = 'fn main() -> i64 effects [] { return '
path = root / f'generic-callee-{depth}.aji'
path.write_text('module depth\nfn unused<T>(x: T) -> T effects [] { return move x; }\n'
+ header + name + '(); }\n')
error = json.loads(cli('check', path, code=1))
assert (error['code'], error['name'], error['file'], error['line'], error['col']) == (
'E7002', name, str(path), 3, len(header) + 1), error
for command in ('lower', 'run', 'report', 'explore'):
assert json.loads(cli(command, path, code=1)) == error
# Parser.exprPath is used by qualified enum/struct constructors, including
# explicit type arguments. Unknown names must reach lowering rather than
# exhausting the native stack, with their full spelling and original span.
for depth in (16, 1024, 16384, 65536):
name = 'ns.' * depth + 'Record'
header = 'fn main() -> i64 effects [] { return '
for kind, suffix, message in (
('variant', '::A', 'unknown enum'),
('struct', ' { field: 1u64 }', 'unknown type'),
('generic-variant', '::<u64>::A', 'unknown or inaccessible generic type'),
('generic-struct', '::<u64> { field: 1u64 }', 'unknown or inaccessible generic type'),
):
path = root / f'qualified-{kind}-{depth}.aji'
path.write_text('module depth\n' + header + name + suffix + '; }\n')
error = json.loads(cli('check', path, code=1))
assert (error['code'], error['name'], error['file'], error['line'], error['col'], error['message']) == (
'E7002', name, str(path), 2, len(header) + 1, message), error
for command in ('lower', 'run', 'report', 'explore'):
assert json.loads(cli(command, path, code=1)) == error
# Signed boundary literal remains one negative constant; the outer
# checked negation traps rather than changing literal acceptance.
minimum = root / 'minimum.aji'
minimum.write_text('module depth\nfn main() -> i8 effects [] { return -128i8; }\n')
assert json.loads(cli('run', minimum, '--fuel', 2)) == {'status': 'returned', 'value': -128}
minimum.write_text('module depth\nfn main() -> i8 effects [] { return - -128i8; }\n')
assert json.loads(cli('run', minimum, '--fuel', 2, code=5)) == {
'status': 'limit_exceeded', 'kind': 'fuel', 'limit': 2, 'steps': 2}
trapped = json.loads(cli('run', minimum, '--fuel', 3, code=4))
assert (trapped['status'], trapped['code'], trapped['kind'], trapped['inst']) == (
'trapped', 'T0003', 'trap.overflow', 2), trapped
print(f'source expression depth: {checks} checks passed')