Files
aji/tests/hosted/source_expression_depth.py
T

772 lines
48 KiB
Python

#!/usr/bin/env python3
"""Expression parsing/lowering depth, exact 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
# Grouping is transparent in the AST; alternating binary/group frames
# also reach ordinary lowering, with independently counted AIR and fuel.
for depth in (0, 1, 16, 1024, 16384, 65536):
for kind in ('group', 'grouped-add'):
expression = ('(' * depth + '1i64' + ')' * depth if kind == 'group'
else '1i64 + (' * depth + '1i64' + ')' * depth)
instructions = 2 if kind == 'group' else 2 * depth + 2
value = 1 if kind == 'group' else depth + 1
path = root / f'{kind}-{depth}.aji'
path.write_text('module depth\nfn main() -> i64 effects [] { return ' + expression + '; }\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:
assert json.loads(cli('run', path, '--fuel', instructions)) == {'status': 'returned', 'value': value}
assert json.loads(cli('run', path, '--fuel', instructions - 1, code=5)) == {
'status': 'limit_exceeded', 'kind': 'fuel', 'limit': instructions - 1, 'steps': instructions - 1}
formatted = path.with_suffix('.formatted.aji')
output = cli('fmt', path)
formatted.write_bytes(output)
assert cli('fmt', formatted) == output
assert json.loads(cli('fmt', formatted, '--check')) == {
'file': str(formatted), 'status': 'formatted', 'changed': False}
assert cli('lower', formatted) == lowered
print(f'grouping depth: {kind} {depth}', flush=True)
forms = (
('(', ')'), ('f(', ', 2u8)'), ('value[', ']'), ('value[0u8..', ']'),
('[', ', 2u8]'), ('[', '; 1]'), ('Record { field: ', ', other: 2u8 }'),
('channel.make<mut<ref<u8>>>(', ')'), ('ns.E::<u8>::A(', ')'),
('not (', ')'), ('1u8 + (', ')'), ('(', ') as u8'), ('ref *(', ')'),
)
header = 'fn f() -> void effects [] { let x = '
for depth in (16, 1024, 16384, 32768):
prefix = ''.join(forms[i % len(forms)][0] for i in range(depth))
suffix = ''.join(forms[i % len(forms)][1] for i in reversed(range(depth)))
path = root / f'mixed-syntax-{depth}.aji'
path.write_text('module depth\n' + header + prefix + 'leaf' + suffix + '; }\n')
# Syntax/formatter coverage only: these synthetic expressions need not
# have compatible types. Other non-scalar lowering remains Q-061 work.
output = cli('fmt', path)
formatted = path.with_suffix('.formatted.aji')
formatted.write_bytes(output)
assert cli('fmt', formatted) == output
assert json.loads(cli('fmt', formatted, '--check')) == {
'file': str(formatted), 'status': 'formatted', 'changed': False}
path.write_text('module depth\n' + header + prefix + '!' + suffix + '; }\n')
error = json.loads(cli('check', path, code=1))
assert (error['code'], error['file'], error['line'], error['col']) == (
'E7001', str(path), 2, len(header) + len(prefix) + 1), error
assert error['repair_candidates'][0]['kind'] == 'boolean_negation', error
for command in ('lower', 'run', 'report', 'explore', 'fmt'):
assert json.loads(cli(command, path, code=1)) == error
print(f'mixed syntax depth: {depth}', flush=True)
# Ordinary calls suspend in the same driver as unary/binary operands.
# Count calls and callee rets independently of the emitted AIR.
for depth in (0, 1, 16, 1024, 16384, 65536):
for kind in ('call', 'add-call', 'neg-call', 'generic-call'):
prefix = {'call': 'id(', 'add-call': '1i64 + id(',
'neg-call': '- id(', 'generic-call': 'id::<i64>('}[kind]
expression = prefix * depth + '1i64' + ')' * depth
generic = kind == 'generic-call'
helper = ('fn id<T>(x: T) -> T effects [] { return move x; }\n' if generic
else 'fn id(x: i64) -> i64 effects [] { return x; }\n')
path = root / f'nested-{kind}-{depth}.aji'
path.write_text('module depth\n' + helper +
'fn main() -> i64 effects [] { return ' + expression + '; }\n')
assert cli('check', path) == b''
lowered = cli('lower', path)
# Generic id is instantiated only if called; ordinary id is always emitted.
helper_instructions = 0 if generic and depth == 0 else 1
main_instructions = (3 if kind in ('add-call', 'neg-call') else 1) * depth + 2
instructions = sum(b' = ' in line or line.strip().startswith(b'ret ') for line in lowered.splitlines())
assert instructions == main_instructions + helper_instructions, (kind, depth, instructions)
if depth <= 1024:
fuel = main_instructions + depth
value = depth + 1 if kind == 'add-call' else (-1 if kind == 'neg-call' and depth % 2 else 1)
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)
output = cli('fmt', path)
formatted = path.with_suffix('.formatted.aji')
formatted.write_bytes(output)
assert cli('fmt', formatted) == output
assert json.loads(cli('fmt', formatted, '--check')) == {
'file': str(formatted), 'status': 'formatted', 'changed': False}
assert cli('check', formatted) == b''
assert cli('lower', formatted) == lowered
print(f'nested call depth: {kind} {depth}', flush=True)
for depth in (1024, 16384, 65536):
path = root / f'nested-call-invalid-{depth}.aji'
header = 'fn main() -> i64 effects [] { return '
prefix = '1i64 + id(' * depth
path.write_text('module depth\nfn id(x: i64) -> i64 effects [] { return x; }\n' +
header + prefix + 'missing()' + ')' * depth + '; }\n')
expected = cli('check', path, code=1)
error = json.loads(expected)
assert (error['code'], error['line'], error['col'], error['file'], error['name']) == (
'E7002', 3, len(header) + len(prefix) + 1, str(path), 'missing'), error
for command in ('lower', 'run', 'report', 'explore'):
assert cli(command, path, code=1) == expected
print(f'nested call invalid depth: {depth}', flush=True)
# Constructors and value-field reads share the scalar/call driver.
for depth in (0, 1, 16, 1024, 16384, 32768, 65536):
for kind in ('field', 'length-field', 'mixed-field', 'generic-field'):
if depth == 32768 and kind != 'mixed-field':
continue
field = 'len' if kind == 'length-field' else 'n'
generic = kind == 'generic-field'
name = 'Box::<i64>' if generic else 'Box'
prefix = name + ' { ' + field + ': '
if kind == 'mixed-field':
prefix += '- id('
suffix = (')' if kind == 'mixed-field' else '') + ' }.' + field
expression = prefix * depth + '1i64' + suffix * depth
declaration = ('struct Box<T> { n: T }\n' if generic else
'struct Box { ' + field + ': i64 }\n')
helper = 'fn id(x: i64) -> i64 effects [] { return x; }\n' if kind == 'mixed-field' else ''
path = root / f'struct-{kind}-{depth}.aji'
path.write_text('module depth\n' + declaration + helper +
'fn main() -> i64 effects [] { return ' + expression + '; }\n')
main_instructions = (5 if kind == 'mixed-field' else 2) * depth + 2
limited = main_instructions > 262144
expected_check = cli('check', path, code=1 if limited else 0)
if limited:
diagnostic = json.loads(expected_check)
assert (diagnostic['code'], diagnostic['limit'], diagnostic['max'], diagnostic['found']) == (
'E5101', 'instructions per function', 262144, main_instructions), diagnostic
for command in ('run', 'report', 'explore'):
assert cli(command, path, code=1) == expected_check
else:
assert expected_check == b''
lowered = cli('lower', path)
instructions = sum((line.lstrip().startswith(b'%') and b' = ' in line) or line.strip().startswith(b'ret ') for line in lowered.splitlines())
assert instructions == main_instructions + (1 if helper else 0), (kind, depth, instructions)
if depth <= 1024:
fuel = main_instructions + (depth if helper else 0)
value = -1 if kind == 'mixed-field' and depth % 2 else 1
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)
formatted = path.with_suffix('.formatted.aji')
output = cli('fmt', path)
formatted.write_bytes(output)
assert cli('fmt', formatted) == output
assert json.loads(cli('fmt', formatted, '--check')) == {
'file': str(formatted), 'status': 'formatted', 'changed': False}
formatted_check = cli('check', formatted, code=1 if limited else 0)
if limited:
diagnostic = json.loads(formatted_check)
assert (diagnostic['code'], diagnostic['limit'], diagnostic['max'], diagnostic['found']) == (
'E5101', 'instructions per function', 262144, main_instructions), diagnostic
else:
assert formatted_check == b''
assert cli('lower', formatted) == lowered
print(f'struct field depth: {kind} {depth}', flush=True)
for depth in (1024, 16384, 65536):
# Exact missing/duplicate/unknown-field priorities at the inner leaf.
for leaf, code, reason in (('Box {}.n', 'E7006', 'invalid_literal'),
('Box { n: 1i64, n: false }.n', 'E7006', 'invalid_literal'),
('Box { missing: unknown }.n', 'E7002', None)):
path = root / f'struct-invalid-{depth}-{code}-{len(leaf)}.aji'
header = 'fn main() -> i64 effects [] { return '
prefix = 'Box { n: ' * depth
path.write_text('module depth\nstruct Box { n: i64 }\n' + header + prefix + leaf + ' }.n' * depth + '; }\n')
expected = cli('check', path, code=1)
error = json.loads(expected)
offset = 0 if 'Box {}' in leaf else (len('Box { n: 1i64, ') if code == 'E7006' else len('Box { '))
assert (error['code'], error['line'], error['col'], error['file']) == (
code, 3, len(header) + len(prefix) + offset + 1, str(path)), error
if reason:
assert error['reason'] == reason, error
for command in ('lower', 'run', 'report', 'explore'):
assert cli(command, path, code=1) == expected
print(f'struct field invalid depth: {depth}', flush=True)
# Lists and repetitions suspend in the same driver as calls/scalars/fields.
for depth in (0, 1, 16, 1024, 16384, 32768, 65536):
for kind in ('list-call', 'repeat-call', 'mixed-array'):
if depth == 32768 and kind != 'mixed-array':
continue
prefix, suffix = ('one([', '; 1])' if kind == 'repeat-call' else '])')
if kind == 'mixed-array':
prefix, suffix = 'Box { n: one([- id(', ')]) }.n'
helper = 'fn one(a: [i64; 1]) -> i64 effects [] { let (x) = array.unpack(a); return x; }\n'
mixed = kind == 'mixed-array'
if mixed:
helper += 'struct Box { n: i64 }\nfn id(x: i64) -> i64 effects [] { return x; }\n'
path = root / f'array-{kind}-{depth}.aji'
path.write_text('module depth\n' + helper + 'fn main() -> i64 effects [] { return ' +
prefix * depth + '1i64' + suffix * depth + '; }\n')
main_instructions = (7 if mixed else 2) * depth + 2
limited = main_instructions > 262144
check = cli('check', path, code=1 if limited else 0)
if limited:
diagnostic = json.loads(check)
assert (diagnostic['code'], diagnostic['limit'], diagnostic['max'], diagnostic['found']) == (
'E5101', 'instructions per function', 262144, main_instructions), diagnostic
for command in ('run', 'report', 'explore'):
assert cli(command, path, code=1) == check
else:
assert check == b''
lowered = cli('lower', path)
instructions = sum((line.lstrip().startswith(b'%') and b' = ' in line) or
line.strip().startswith((b'ret ', b'array.unpack ')) for line in lowered.splitlines())
assert instructions == main_instructions + 2 + int(mixed), (kind, depth, instructions)
if depth <= 1024:
fuel = main_instructions + (3 if mixed else 2) * depth
value = -1 if mixed and depth % 2 else 1
assert json.loads(cli('run', path, '--fuel', fuel)) == {'status': 'returned', 'value': value, 'stdout': '', 'stderr': '', 'files': {}}
assert json.loads(cli('run', path, '--fuel', fuel - 1, code=5)) == {
'status': 'limit_exceeded', 'kind': 'fuel', 'limit': fuel - 1, 'steps': fuel - 1, 'stdout': '', 'stderr': '', 'files': {}}
air = path.with_suffix('.air')
air.write_bytes(lowered)
assert cli('run', air, '--fuel', fuel) == cli('run', path, '--fuel', fuel)
output = cli('fmt', path)
formatted = path.with_suffix('.formatted.aji')
formatted.write_bytes(output)
assert cli('fmt', formatted) == output
assert json.loads(cli('fmt', formatted, '--check')) == {
'file': str(formatted), 'status': 'formatted', 'changed': False}
formatted_check = cli('check', formatted, code=1 if limited else 0)
if limited:
diagnostic = json.loads(formatted_check)
assert (diagnostic['code'], diagnostic['limit'], diagnostic['max'], diagnostic['found']) == (
'E5101', 'instructions per function', 262144, main_instructions), diagnostic
else:
assert formatted_check == b''
assert cli('lower', formatted) == lowered
print(f'array expression depth: {kind} {depth}', flush=True)
# Pure nested arrays produce quadratic AIR type text. Keep success probes
# at the confirmed former native-failure checkpoint instead of 65k output.
for repeated in (False, True):
path = root / f'pure-array-{repeated}-4096.aji'
path.write_text('module depth\nfn main() -> i64 effects [] { let a = ' +
'[' * 4096 + '1i64' + ('; 1]' if repeated else ']') * 4096 + '; return 0i64; }\n')
assert cli('check', path) == b''
print(f'pure array depth: {repeated} 4096', flush=True)
for depth in (1024, 16384, 65536):
for repeated in (False, True):
for leaf, code in (('missing()', 'E7002'), ('[missing(); 0]', 'E7005')):
path = root / f'array-invalid-{depth}-{repeated}-{code}.aji'
header = 'fn main() -> i64 effects [] { let a = '
path.write_text('module depth\n' + header + '[' * depth + leaf +
('; 1]' if repeated else ']') * depth + '; return 0i64; }\n')
expected = cli('check', path, code=1)
error = json.loads(expected)
assert (error['code'], error['line'], error['col'], error['file']) == (
code, 2, len(header) + depth + 1, str(path)), error
for command in ('lower', 'run', 'report', 'explore'):
assert cli(command, path, code=1) == expected
print(f'array invalid depth: {depth}', flush=True)
# Enum payloads share scalar/call/aggregate continuations; validate arity
# before arguments and type/consume/check each payload in source order.
for depth in (0, 1, 16, 256, 1024, 16384, 32768, 65536):
for kind in ('variant-call', 'two-payload', 'generic-variant', 'mixed-variant'):
if depth == 32768 and kind != 'mixed-variant':
continue
generic, two, mixed = kind == 'generic-variant', kind == 'two-payload', kind == 'mixed-variant'
constructor = 'Wrap::<i64>::some' if generic else 'Wrap::some'
enum = 'enum Wrap<T> { some(T) }\n' if generic else ('enum Wrap { some(i64, i64) }\n' if two else 'enum Wrap { some(i64) }\n')
annotation = 'Wrap<i64>' if generic else 'Wrap'
binders = 'x, y' if two else 'x'
helper = enum + f'fn unwrap(w: {annotation}) -> i64 effects [] {{ return match w {{ {constructor}({binders}) => x }}; }}\n'
prefix, suffix = f'unwrap({constructor}(', ', 2))' if two else '))'
if mixed:
helper += 'struct Box { n: i64 }\nfn id(x: i64) -> i64 effects [] { return x; }\n'
prefix, suffix = 'unwrap(Wrap::some(Box { n: - id(', ') }.n))'
path = root / f'enum-{kind}-{depth}.aji'
path.write_text('module depth\n' + helper + 'fn main() -> i64 effects [] { return ' +
prefix * depth + '1i64' + suffix * depth + '; }\n')
main_instructions = (7 if mixed else 3 if two else 2) * depth + 2
limited = main_instructions > 262144
checked = cli('check', path, code=1 if limited else 0)
if limited:
diagnostic = json.loads(checked)
assert (diagnostic['code'], diagnostic['limit'], diagnostic['max'], diagnostic['found']) == (
'E5101', 'instructions per function', 262144, main_instructions), diagnostic
for command in ('run', 'report', 'explore'):
assert cli(command, path, code=1) == checked
else:
assert checked == b''
lowered = cli('lower', path)
instructions = sum((line.lstrip().startswith(b'%') and b' = ' in line) or
line.strip().startswith((b'ret ', b'br ', b'enum.switch ')) for line in lowered.splitlines())
assert instructions == main_instructions + 3 + int(mixed), (kind, depth, instructions)
if depth <= 1024:
fuel = main_instructions + (4 if mixed else 3) * depth
value = -1 if mixed and depth % 2 else 1
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)
output = cli('fmt', path)
formatted = path.with_suffix('.formatted.aji')
formatted.write_bytes(output)
assert cli('fmt', formatted) == output
assert json.loads(cli('fmt', formatted, '--check')) == {
'file': str(formatted), 'status': 'formatted', 'changed': False}
formatted_check = cli('check', formatted, code=1 if limited else 0)
if limited:
diagnostic = json.loads(formatted_check)
assert (diagnostic['code'], diagnostic['limit'], diagnostic['max'], diagnostic['found']) == (
'E5101', 'instructions per function', 262144, main_instructions), diagnostic
else:
assert formatted_check == b''
assert cli('lower', formatted) == lowered
print(f'variant expression depth: {kind} {depth}', flush=True)
for depth in (1024, 16384, 65536):
for leaf, code in (('missing()', 'E7002'), ('Wrap::some(missing(), true)', 'E7005'),
('Wrap::absent(missing())', 'E7002'), ('Wrap::some(true)', 'E7005')):
path = root / f'variant-invalid-{depth}-{code}-{len(leaf)}.aji'
header = 'fn main() -> i64 effects [] { return '
prefix = 'unwrap(Wrap::some(' * depth
path.write_text('module depth\nenum Wrap { some(i64) }\nfn unwrap(w: Wrap) -> i64 effects [] { return match w { Wrap::some(x) => x }; }\n' +
header + prefix + leaf + '))' * depth + '; }\n')
expected = cli('check', path, code=1)
error = json.loads(expected)
assert (error['code'], error['line'], error['col'], error['file']) == (
code, 4, len(header) + len(prefix) + (len('Wrap::some(') if leaf == 'Wrap::some(true)' else 0) + 1, str(path)), error
if code == 'E7005':
assert (error['expected'], error['found']) == (('i64', 'bool') if leaf == 'Wrap::some(true)' else ('1', '2')), error
for command in ('lower', 'run', 'report', 'explore'):
assert cli(command, path, code=1) == expected
print(f'variant invalid depth: {depth}', flush=True)
# Empty named constructors also finish immediately at the deepest leaf.
for depth in (0, 1, 16, 1024, 65536):
path = root / f'empty-variant-{depth}.aji'
path.write_text('module depth\nenum Wrap { some(i64), empty }\n' +
'fn unwrap(w: Wrap) -> i64 effects [] { return match w { Wrap::some(x) => x, Wrap::empty => 1i64 }; }\n' +
'fn main() -> i64 effects [] { return ' + 'unwrap(Wrap::some(' * depth +
'unwrap(Wrap::empty)' + '))' * depth + '; }\n')
assert cli('check', path) == b''
lowered = cli('lower', path)
instructions = sum((line.lstrip().startswith(b'%') and b' = ' in line) or
line.strip().startswith((b'ret ', b'br ', b'enum.switch ')) for line in lowered.splitlines())
assert instructions == 2 * depth + 8, (depth, instructions)
if depth <= 1024:
fuel = 5 * depth + 7
assert json.loads(cli('run', path, '--fuel', fuel)) == {'status': 'returned', 'value': 1}
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)
formatted = path.with_suffix('.formatted.aji')
output = cli('fmt', path)
formatted.write_bytes(output)
assert cli('fmt', formatted) == output
assert json.loads(cli('fmt', formatted, '--check')) == {
'file': str(formatted), 'status': 'formatted', 'changed': False}
assert cli('check', formatted) == b''
assert cli('lower', formatted) == lowered
print(f'empty variant depth: {depth}', flush=True)
# Boolean builtin operands share the expression driver. Void-valued
# nested assertions keep their exact inner diagnostic at arbitrary depth.
for depth in (2, 16, 64, 256, 1024, 16384, 65536):
for kind in ('assert', 'assume', 'alternating'):
names = [kind if kind != 'alternating' else ('assert' if i % 2 == 0 else 'assume')
for i in range(depth)]
prefix = 'module depth\nfn main() -> i64 effects [unsafe] { '
expression = ''.join(name + '(' for name in names) + 'true' + ')' * depth
path = root / f'nested-{kind}-{depth}.aji'
path.write_text(prefix + expression + '; return 1i64; }\n')
expected = cli('check', path, code=1)
error = json.loads(expected)
inner_col = len(prefix.split('\n')[-1]) + sum(len(name) + 1 for name in names[:-1]) + 1
assert (error['code'], error['expected'], error['found'], error['file'], error['line'], error['col']) == (
'E7005', 'bool', 'void', str(path), 2, inner_col), error
for command in ('lower', 'run', 'report', 'explore'):
assert cli(command, path, code=1) == expected
formatted = path.with_suffix('.formatted.aji')
output = cli('fmt', path)
formatted.write_bytes(output)
assert cli('fmt', formatted) == output
assert json.loads(cli('check', formatted, code=1))['code'] == 'E7005'
print(f'boolean builtin rejection depth: {depth}', flush=True)
for name in ('assert', 'assume'):
for depth in (0, 1, 16, 256, 1024, 16384, 65536):
expression = 'bool_id(' * depth + 'true' + ')' * depth
path = root / f'boolean-builtin-{name}-{depth}.aji'
path.write_text('module depth\nfn bool_id(v: bool) -> bool effects [] { return v; }\n'
f'fn main() -> void effects [{"unsafe" if name == "assume" else ""}] {{ '
f'{name}({expression}); }}\n')
assert cli('check', path) == b''
lowered = cli('lower', path)
instructions = sum(b' = ' in line or line.strip().startswith((b'ret', b'assert ', b'assume '))
for line in lowered.splitlines())
assert instructions == depth + 4, (name, depth, instructions)
if depth <= 1024:
fuel = 2 * depth + 3
result = cli('run', path, '--fuel', fuel)
assert json.loads(result) == {'status': 'returned', 'value': None}, result
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) == result
formatted = path.with_suffix('.formatted.aji')
output = cli('fmt', path)
formatted.write_bytes(output)
assert cli('fmt', formatted) == output
assert cli('check', formatted) == b''
assert cli('lower', formatted) == lowered
print(f'boolean builtin accepted depth: {name}', flush=True)
# Final supplemental probes: stable feature/operation spelling, traps,
# hosted run records and inner arity/type priority through mixed calls.
for name in ('assert', 'assume'):
for depth in (0, 16, 1024):
expression = 'bool_id(' * depth + 'false' + ')' * depth
prefix = 'module depth\nfn bool_id(v: bool) -> bool effects [] { return v; }\n'
main = f'fn main() -> void effects [{"unsafe" if name == "assume" else ""}] {{ '
path = root / f'boolean-builtin-trap-{name}-{depth}.aji'
path.write_text(prefix + main + f'{name}({expression}); }}\n')
lowered = cli('lower', path)
header = next(line for line in lowered.splitlines() if line.startswith(b'features ['))
assert (b'unsafe' in header) == (name == 'assume'), header
operations = [line.strip() for line in lowered.splitlines() if line.strip().startswith((b'assert ', b'assume '))]
assert len(operations) == 1 and operations[0].startswith(name.encode() + b' %'), operations
fuel = 2 * depth + 2
trapped = json.loads(cli('run', path, '--fuel', fuel, code=4))
assert (trapped['status'], trapped['code'], trapped['kind'], trapped['inst']) == (
'trapped', 'T0009' if name == 'assume' else 'T0002',
'trap.unsafe_precondition' if name == 'assume' else 'trap.assert', depth + 1), trapped
assert trapped.pop('source_location') == {'file': str(path), 'line': 3, 'col': len(main) + 1}
air = path.with_suffix('.air')
air.write_bytes(lowered)
assert json.loads(cli('run', air, '--fuel', fuel, code=4)) == trapped
record = path.with_suffix('.json')
assert cli('run', path, '--fuel', fuel, '--profile', 'hosted', '--result-file', record, code=4) == b''
hosted = json.loads(record.read_text())
assert hosted == trapped, hosted
for leaf, found in (('assert()', None), ('assume(unknown, false)', None), ('assert(1i64)', 'i64')):
for depth in (16, 1024, 65536):
prefix = 'module depth\nfn bool_id(v: bool) -> bool effects [] { return v; }\nfn main() -> void effects [] { '
expression = 'assert(bool_id(' * depth + leaf + '))' * depth
path = root / f'boolean-builtin-leaf-{leaf.split("(")[0]}-{found}-{depth}.aji'
path.write_text(prefix + expression + '; }\n')
expected = cli('check', path, code=1)
error = json.loads(expected)
col = len(prefix.split('\n')[-1]) + len('assert(bool_id(') * depth + 1
if found is not None:
col += len('assert(')
assert (error['expected'], error['found']) == ('bool', found), error
assert (error['code'], error['line'], error['col'], error['file']) == ('E7005', 3, col, str(path)), error
for command in ('lower', 'run', 'report', 'explore'):
assert cli(command, path, code=1) == expected
print(f'boolean builtin leaf priority: {leaf}', flush=True)
# Block/control callbacks remain native. Their existing shallow/deeper
# syntax must retain its capacity while expression dispatch is moved out
# of the native stack, including explicit-return callback re-entry.
for depth in (64, 256):
for kind in ('block', 'if', 'returned-block', 'returned-if'):
if kind == 'block':
expression = '{' * depth + '1i64' + '}' * depth
elif kind == 'if':
expression = 'if true {' * depth + '1i64' + '} else {1i64}' * depth
elif kind == 'returned-block':
expression = '{return ' * depth + '1i64' + ';}' * depth
else:
expression = 'if true {return ' * depth + '1i64' + ';} else {return 1i64;}' * depth
path = root / f'control-syntax-{kind}-{depth}.aji'
path.write_text('module depth\nfn main() -> i64 effects [] { return ' + expression + '; }\n')
output = cli('fmt', path)
formatted = path.with_suffix('.formatted.aji')
formatted.write_bytes(output)
assert cli('fmt', formatted) == output
assert json.loads(cli('fmt', formatted, '--check')) == {
'file': str(formatted), 'status': 'formatted', 'changed': False}
# 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')