#!/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(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(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::(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(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', '::::A', 'unknown or inaccessible generic type'), ('generic-struct', ':: { 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>>(', ')'), ('ns.E::::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::('}[kind] expression = prefix * depth + '1i64' + ')' * depth generic = kind == 'generic-call' helper = ('fn id(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::' 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 { 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::::some' if generic else 'Wrap::some' enum = 'enum Wrap { some(T) }\n' if generic else ('enum Wrap { some(i64, i64) }\n' if two else 'enum Wrap { some(i64) }\n') annotation = 'Wrap' 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) # Consuming ownership/region builtin arguments share the driver. Preserve # explicit transfers, destruction/extraction, exact AIR/fuel and failures. for operation in ('own.take', 'own.free', 'region.destroy'): is_region = operation == 'region.destroy' is_free = operation == 'own.free' ty, keep = ('region', 'keep_region') if is_region else ('own', 'keep') for depth in (0, 1, 16, 256, 1024, 16384, 65536): expression = (keep + '(') * depth + 'move x' + ')' * depth invocation = operation + '(' + expression + ')' body = 'return ' + invocation + ';' if operation == 'own.take' else invocation + '; return 42i64;' path = root / f'consuming-builtin-{operation}-{depth}.aji' path.write_text(f'module depth\nfn {keep}(x: {ty}) -> {ty} effects [] {{ return move x; }}\n' 'fn main(heap: cap) -> i64 effects [mem.alloc] { let x = ' + ('region.create(heap)' if is_region else 'own.new(42i64, heap)') + ' or trap; ' + body + ' }\n') assert cli('check', path) == b'' lowered = cli('lower', path) instructions = sum(b' = ' in line or line.strip().startswith((b'ret', b'own.new ', b'own.free ', b'region.create ', b'region.destroy ', b'trap')) for line in lowered.splitlines()) assert instructions == depth + 6 + int(is_free), (operation, depth, instructions) assert sum(operation.encode() in line for line in lowered.splitlines()) == 1 if depth <= 1024: fuel = 2 * depth + 4 + int(is_free) result = cli('run', path, '--fuel', fuel, '--grant', 'heap=mem.alloc:256') assert json.loads(result) == {'status': 'returned', 'value': 42, 'stdout': '', 'stderr': '', 'files': {}} limited = json.loads(cli('run', path, '--fuel', fuel - 1, '--grant', 'heap=mem.alloc:256', code=5)) assert (limited['status'], limited['kind'], limited['limit'], limited['steps']) == ('limit_exceeded', 'fuel', fuel - 1, fuel - 1), limited air = path.with_suffix('.air') air.write_bytes(lowered) assert cli('run', air, '--fuel', fuel, '--grant', 'heap=mem.alloc:256') == 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'consuming builtin accepted depth: {operation}', flush=True) for leaf in ('unknown', 'true', 'missing-arity'): for depth in (16, 1024, 16384, 65536): empty = leaf == 'missing-arity' prefix = 'module depth\nfn main() -> void effects [] { ' expression = (operation + '(') * depth + ('' if empty else leaf) + ')' * depth path = root / f'consuming-builtin-reject-{operation}-{leaf}-{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(operation + '(') * (depth - int(empty)) + 1 assert (error['code'], error['file'], error['line'], error['col']) == ( 'E7002' if leaf == 'unknown' else 'E7005', str(path), 2, col), error if leaf == 'true': assert error['found'] == 'bool', 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 formatted_error = json.loads(cli('check', formatted, code=1)) text = output.decode() at = text.rfind(operation + '(') if empty else text.index(leaf) assert (formatted_error['code'], formatted_error['file'], formatted_error['line'], formatted_error['col']) == ( error['code'], str(formatted), text[:at].count('\n') + 1, at - text.rfind('\n', 0, at)), formatted_error print(f'consuming builtin rejection depth: {operation}', flush=True) # Atomic operand continuations preserve scalar construction/extraction, # cell/order-before-value priority and temporary shared-loan lifetimes. for kind in ('atomic-pair', 'atomic-mixed', 'atomic-swap'): for depth in (0, 1, 16, 256, 1024, 16384, 32768, 65536): if depth == 32768 and kind != 'atomic-mixed': continue path = root / f'{kind}-{depth}.aji' if kind == 'atomic-pair': expression = 'atomic.take(atomic.new(' * depth + '42i64' + '))' * depth program = 'module depth\nfn main() -> i64 effects [] { return ' + expression + '; }\n' instructions, fuel, value = 2 * depth + 2, 2 * depth + 2, 42 elif kind == 'atomic-mixed': expression = 'atomic.take(atomic.new(id(- ' * depth + 'id(42i64)' + ')))' * depth program = 'module depth\nfn id(x: i64) -> i64 effects [] { return x; }\nfn main() -> i64 effects [] { return ' + expression + '; }\n' instructions, fuel, value = 5 * depth + 4, 6 * depth + 4, 42 if depth % 2 == 0 else -42 else: expression = 'atomic.swap(ref ac, ' * depth + '42i64' + ', seq_cst)' * depth program = 'module depth\nfn main() -> i64 effects [atomic] { let ac = atomic.new(0i64); let result = ' + expression + '; return atomic.take(move ac); }\n' instructions, fuel, value = 3 * depth + 5, 3 * depth + 5, 42 if depth % 2 else 0 path.write_text(program) limited = kind == 'atomic-mixed' and depth == 65536 checked = cli('check', path, code=1 if limited else 0) if limited: error = json.loads(checked) assert (error['code'], error['limit'], error['max'], error['found']) == ('E5101', 'instructions per function', 262144, 327683), error for command in ('run', 'report', 'explore'): assert cli(command, path, code=1) == checked else: assert checked == b'' lowered = cli('lower', path) actual = sum(b' = ' in line or line.strip().startswith((b'ret ', b'borrow.end ')) for line in lowered.splitlines()) assert actual == instructions, (kind, depth, actual, instructions) if depth <= 1024: result = cli('run', path, '--fuel', fuel) assert json.loads(result) == {'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) == result formatted = path.with_suffix('.formatted.aji') output = cli('fmt', path) formatted.write_bytes(output) assert cli('fmt', formatted) == output formatted_check = cli('check', formatted, code=1 if limited else 0) if limited: assert json.loads(formatted_check)['code'] == 'E5101' else: assert formatted_check == b'' assert cli('lower', formatted) == lowered print(f'atomic operand accepted depth: {kind}', flush=True) for leaf, code, offset, extra in ( ('unknown', 'E7002', 0, {}), ('atomic.new()', 'E7005', 0, {}), ('atomic.new(1u128)', 'E7005', len('atomic.new('), {'found': 'u128'}), ('atomic.take(true)', 'E7005', len('atomic.take('), {'found': 'bool'}), ('atomic.store(ref ac, unknown, invalid)', 'E7006', len('atomic.store(ref ac, unknown, '), {}), ('atomic.store(ref ac, true, seq_cst)', 'E7005', len('atomic.store(ref ac, '), {'expected': 'i64', 'found': 'bool'}), ): for depth in (16, 1024, 65536): prefix = 'module depth\nfn main() -> i64 effects [atomic] { let ac = atomic.new(0i64); return ' expression = 'atomic.take(atomic.new(' * depth + leaf + '))' * depth path = root / f'atomic-operand-reject-{code}-{offset}-{depth}-{len(leaf)}.aji' path.write_text(prefix + expression + '; }\n') expected = cli('check', path, code=1) error = json.loads(expected) col = len(prefix.split('\n')[-1]) + len('atomic.take(atomic.new(') * depth + offset + 1 assert (error['code'], error['file'], error['line'], error['col']) == (code, str(path), 2, col), error for key, wanted in extra.items(): assert error[key] == wanted, error for command in ('lower', 'run', 'report', 'explore'): assert cli(command, path, code=1) == expected print(f'atomic operand error priority: {leaf}', flush=True) # task.join shares consuming operand continuations. Valid tasks retain their # scope, result/void emission and scheduling; malformed deep joins reject. for void_result in (False, True): for depth in (0, 1, 16, 256, 1024, 16384, 65536): path = root / f'task-join-operand-{void_result}-{depth}.aji' program = 'module depth\nfn id(x: i64) -> i64 effects [] { x }\n' if void_result: program += 'fn work(x: i64) -> void effects [] {}\n' program += 'fn main() -> ' + ('void' if void_result else 'i64') + ' effects [task.spawn] { scope s { ' expression = 'task.join(task.spawn(s, ' + ('work' if void_result else 'id') + ', ' + 'id(' * depth + '42i64' + ')' * depth + '))' program += (expression + ';' if void_result else 'let r = ' + expression + '; return r;') + ' } }\n' path.write_text(program) assert cli('check', path) == b'' lowered = cli('lower', path) actual = sum((line.lstrip().startswith(b'%') and b' = ' in line) or line.strip().startswith((b'ret', b'task.scope.end ', b'task.join ')) for line in lowered.splitlines()) assert actual == depth + 7 + int(void_result), (void_result, depth, actual) if depth <= 1024: fuel = 2 * depth + 7 options = ('--quantum', 1, '--schedule-seed', 7, '--fuel', fuel) result = cli('run', path, *options) assert json.loads(result) == {'status': 'returned', 'value': None if void_result else 42, 'schedule': {'seed': 7, 'quantum': 1, 'choices': 1}}, result assert json.loads(cli('run', path, '--quantum', 1, '--schedule-seed', 7, '--fuel', fuel - 1, code=5)) == {'status': 'limit_exceeded', 'kind': 'fuel', 'limit': fuel - 1, 'steps': fuel - 1, 'schedule': {'seed': 7, 'quantum': 1, 'choices': 1}} air = path.with_suffix('.air') air.write_bytes(lowered) assert cli('run', air, *options) == result if depth <= 16: for seed in (0, 1): options = ('--quantum', 1, '--schedule-seed', seed, '--fuel', fuel) seeded = cli('run', path, *options) assert json.loads(seeded) == {'status': 'returned', 'value': None if void_result else 42, 'schedule': {'seed': seed, 'quantum': 1, 'choices': 1}} assert cli('run', air, *options) == seeded 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'task join accepted operand depth: void={void_result}', flush=True) import re for leaf, code, extra in ( ('unknown', 'E7002', {}), ('true', 'E7005', {'found': 'bool'}), ('1', 'E7007', {}), ('task.join()', 'E7005', {}), ('task.join(unknown, false)', 'E7005', {}), ('task.cancelled()', 'E7005', {'found': 'bool'}), ('t', 'E7003', {'suggestion': 'move t'}), ('move t', 'E7005', {'found': 'i64'}), ): for mixed in (False, True): prefix = 'module depth\nfn id(x: i64) -> i64 effects [] { x }\nfn work() -> i64 effects [] { 42i64 }\nfn main() -> i64 effects [task.spawn] { scope s { let t = task.spawn(s, work); return ' opening, closing = ('id(task.join(', '))') if mixed else ('task.join(', ')') for depth in (16, 1024, 65536): expression = opening * depth + leaf + closing * depth path = root / f'task-join-reject-{code}-{len(leaf)}-{mixed}-{depth}.aji' path.write_text(prefix + expression + '; } }\n') expected = cli('check', path, code=1) error = json.loads(expected) at = len(opening) * (depth - int(leaf == 'move t')) assert (error['code'], error['file'], error['line'], error['col']) == (code, str(path), 4, len(prefix.split('\n')[-1]) + at + 1), error for key, value in extra.items(): assert error[key] == value, 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 formatted_error = json.loads(cli('check', formatted, code=1)) text = output.decode() if leaf == 'move t': pos = text.rfind('id(' if mixed else 'task.join(') elif leaf == 't': pos = list(re.finditer(r'(? i64 effects [] { b }\n' expression = 'task.join(task.spawn(s, pair, 2i64, ' * depth + '42i64' + '))' * depth instructions, fuel, value = 3 * depth + 5, 4 * depth + 4, 42 elif kind == 'spawn-mixed': worker = 'fn id(x: i64) -> i64 effects [] { x }\n' expression = 'task.join(task.spawn(s, id, id(- ' * depth + 'id(42i64)' + ')))' * depth instructions, fuel, value = 5 * depth + 6, 7 * depth + 6, 42 if depth % 2 == 0 else -42 else: worker = 'fn id(x: i64) -> i64 effects [] { x }\n' expression = 'task.join(task.spawn(s, id, ' * depth + '42i64' + '))' * depth instructions, fuel, value = 2 * depth + 5, 3 * depth + 4, 42 path.write_text('module depth\n' + worker + 'fn main() -> i64 effects [task.spawn] { scope s { return ' + expression + '; } }\n') limited = kind == 'spawn-mixed' and depth == 65536 checked = cli('check', path, code=1 if limited else 0) if limited: error = json.loads(checked) assert (error['code'], error['limit'], error['max'], error['found']) == ('E5101', 'instructions per function', 262144, 327685), error for command in ('run', 'report', 'explore'): assert cli(command, path, code=1) == checked else: assert checked == b'' lowered = cli('lower', path) actual = sum((line.lstrip().startswith(b'%') and b' = ' in line) or line.strip().startswith((b'ret', b'task.scope.end ')) for line in lowered.splitlines()) assert actual == instructions, (kind, depth, actual, instructions) if depth <= 1024: options = ('--quantum', 1, '--schedule-seed', 7, '--fuel', fuel) result = cli('run', path, *options) record = {'status': 'returned', 'value': value} exhausted = {'status': 'limit_exceeded', 'kind': 'fuel', 'limit': fuel - 1, 'steps': fuel - 1} if depth: schedule = {'seed': 7, 'quantum': 1, 'choices': depth} record['schedule'] = schedule exhausted['schedule'] = schedule assert json.loads(result) == record, result assert json.loads(cli('run', path, '--quantum', 1, '--schedule-seed', 7, '--fuel', fuel - 1, code=5)) == exhausted air = path.with_suffix('.air') air.write_bytes(lowered) assert cli('run', air, *options) == result if depth <= 16: for seed in (0, 1): options = ('--quantum', 1, '--schedule-seed', seed, '--fuel', fuel) seeded = cli('run', path, *options) if depth: record['schedule'] = {'seed': seed, 'quantum': 1, 'choices': depth} assert json.loads(seeded) == record assert cli('run', air, *options) == seeded formatted = path.with_suffix('.formatted.aji') output = cli('fmt', path) formatted.write_bytes(output) assert cli('fmt', formatted) == output # Exact AIR parity avoids a second expensive deep verifier walk. assert cli('lower', formatted) == lowered if depth <= 1024: assert cli('check', formatted) == b'' print(f'spawn argument accepted depth: {kind}', flush=True) for leaf, code, offset, extra in ( ('unknown', 'E7002', 0, {}), ('true', 'E7005', 0, {'found': 'bool'}), ('ref n', 'E7006', 0, {'reason': 'invalid_borrow'}), ('b"xy"', 'E7006', 0, {'reason': 'invalid_borrow'}), ('task.spawn(s, id)', 'E7005', 0, {'expected': '1', 'found': '0'}), ('task.spawn(s, missing, unknown)', 'E7002', len('task.spawn(s, '), {}), ('task.spawn(n, missing, unknown)', 'E7005', len('task.spawn('), {'found': 'i64'}), ('task.spawn(s, retained)', 'E7006', 0, {'reason': 'invalid_borrow_return'}), ('task.spawn(s, pair, unknown, ref n)', 'E7002', len('task.spawn(s, pair, '), {}), ('task.spawn(s, pair, id(1i64), ref n)', 'E7006', len('task.spawn(s, pair, id(1i64), '), {'reason': 'invalid_borrow'}), ('t', 'E7003', 0, {'suggestion': 'move t'}), ('move t', 'E7005', 0, {'expected': 'i64', 'found': 'task'}), ): for depth in (16, 1024, 65536): prefix = 'module depth\nfn id(x: i64) -> i64 effects [] { x }\nfn pair(a: i64, b: i64) -> i64 effects [] { b }\nfn retained(p: ref) -> ref from p effects [] { p }\nfn main() -> i64 effects [task.spawn] { var n: i64 = 1i64; scope s { let t = task.spawn(s, id, 0i64); return ' opening = 'task.join(task.spawn(s, id, ' expression = opening * depth + leaf + '))' * depth path = root / f'spawn-argument-reject-{code}-{len(leaf)}-{offset}-{depth}.aji' path.write_text(prefix + expression + '; } }\n') expected = cli('check', path, code=1) error = json.loads(expected) assert (error['code'], error['file'], error['line'], error['col']) == (code, str(path), 5, len(prefix.split('\n')[-1]) + len(opening) * depth + offset + 1), error for key, value in extra.items(): assert error[key] == value, 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 formatted_error = json.loads(cli('check', formatted, code=1)) text = output.decode() if leaf == 't': pos = list(re.finditer(r'(? 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 # Mutex operands share consuming continuations; element/loan rules stay unchanged. for mixed in (False, True): for depth in (0, 1, 16, 256, 1024, 16384, 32768, 65536): if depth == 32768 and not mixed: continue opening = 'mutex.take(mutex.make(id(- ' if mixed else 'mutex.take(mutex.make(' expression = opening * depth + ('id(42i64)' if mixed else '42i64') + (')))' if mixed else '))') * depth worker = 'fn id(x: i64) -> i64 effects [] { x }\n' if mixed else '' path = root / f'mutex-operand-{mixed}-{depth}.aji' path.write_text('module depth\n' + worker + 'fn main() -> i64 effects [] { return ' + expression + '; }\n') instructions, fuel = (5 * depth + 4, 6 * depth + 4) if mixed else (2 * depth + 2, 2 * depth + 2) limited = mixed and depth == 65536 checked = cli('check', path, code=1 if limited else 0) if limited: error = json.loads(checked) assert (error['code'], error['limit'], error['max'], error['found']) == ('E5101', 'instructions per function', 262144, 327683), error for command in ('run', 'report', 'explore'): assert cli(command, path, code=1) == checked else: assert checked == b'' lowered = cli('lower', path) actual = sum((line.lstrip().startswith(b'%') and b' = ' in line) or line.strip().startswith(b'ret') for line in lowered.splitlines()) assert actual == instructions, (mixed, depth, actual, instructions) if depth <= 1024: record = {'status': 'returned', 'value': 42 if depth % 2 == 0 or not mixed else -42} options = ('--quantum', 1, '--schedule-seed', 7, '--fuel', fuel) result = cli('run', path, *options) assert json.loads(result) == record, 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, *options) == result formatted = path.with_suffix('.formatted.aji') output = cli('fmt', path) formatted.write_bytes(output) assert cli('fmt', formatted) == output assert cli('lower', formatted) == lowered if depth <= 1024: assert cli('check', formatted) == b'' print(f'mutex operand accepted depth: mixed={mixed}', flush=True) for leaf, code, extra in ( ('unknown', 'E7002', {}), ('p', 'E7005', {'found': 'ref'}), ('m', 'E7003', {'suggestion': 'move m'}), ('empty()', 'E7005', {'position': 'member', 'type_constructor': 'void'}), ('stop()', 'E7005', {'position': 'member', 'type_constructor': 'never'}), ('mutex.take(true)', 'E7005', {'found': 'bool'}), ('mutex.take(unknown, ref n)', 'E7005', {}), ('mutex.make(unknown, ref n)', 'E7005', {}), ): for depth in (16, 1024, 65536): prefix = 'module depth\nfn empty() -> void effects [] {}\nfn stop() -> never effects [] { trap; }\nfn main() -> i64 effects [] { var n: i64 = 1i64; let m = mutex.make(1i64); ref p = n; return ' opening = 'mutex.take(mutex.make(' leaf_name = re.sub(r'[^A-Za-z0-9]+', '-', leaf).strip('-') path = root / f'mutex-reject-{code}-{leaf_name}-{depth}.aji' path.write_text(prefix + opening * depth + leaf + '))' * depth + '; }\n') expected = cli('check', path, code=1) error = json.loads(expected) offset = len('mutex.take(') if leaf == 'mutex.take(true)' else 0 assert (error['code'], error['file'], error['line'], error['col']) == (code, str(path), 4, len(prefix.split('\n')[-1]) + len(opening) * depth + offset + 1), error for key, value in extra.items(): assert error[key] == value, 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 formatted_error = json.loads(cli('check', formatted, code=1)) text = output.decode() if leaf in ('m', 'p'): pos = list(re.finditer(r'(? usize effects [] { x }\n' if mixed else '' path = root / f'index-operand-{mixed}-{depth}.aji' path.write_text('module depth\n' + worker + 'fn main() -> usize effects [] { let a: [usize; 1] = [0usize]; return ' + expression + '; }\n') instructions = (7 * depth + 7 if depth else 5) if mixed else (5 * depth + 6 if depth else 4) fuel = (9 * depth + 6 if depth else 4) if mixed else (5 * depth + 6 if depth else 4) limited = depth == 65536 checked = cli('check', path, code=1 if limited else 0) if limited: error = json.loads(checked) main_instructions = instructions - int(mixed) assert (error['code'], error['limit'], error['max'], error['found']) == ('E5101', 'instructions per function', 262144, main_instructions), error for command in ('run', 'report', 'explore'): assert cli(command, path, code=1) == checked else: assert checked == b'' lowered = cli('lower', path) actual = sum((line.lstrip().startswith(b'%') and b' = ' in line) or line.strip().startswith((b'ret', b'borrow.end ', b'local.store ')) for line in lowered.splitlines()) assert actual == instructions, (mixed, depth, actual, instructions) if depth <= 1024: options = ('--quantum', 1, '--schedule-seed', 7, '--fuel', fuel) result = cli('run', path, *options) assert json.loads(result) == {'status': 'returned', 'value': 0, 'stdout': '', 'stderr': '', 'files': {}}, result exhausted = {'status': 'limit_exceeded', 'kind': 'fuel', 'limit': fuel - 1, 'steps': fuel - 1, 'stdout': '', 'stderr': '', 'files': {}} assert json.loads(cli('run', path, '--quantum', 1, '--schedule-seed', 7, '--fuel', fuel - 1, code=5)) == exhausted air = path.with_suffix('.air') air.write_bytes(lowered) assert cli('run', air, *options) == result assert json.loads(cli('run', air, '--quantum', 1, '--schedule-seed', 7, '--fuel', fuel - 1, code=5)) == exhausted formatted = path.with_suffix('.formatted.aji') output = cli('fmt', path) formatted.write_bytes(output) assert cli('fmt', formatted) == output assert cli('lower', formatted) == lowered if depth <= 1024: assert cli('check', formatted) == b'' print(f'index operand accepted depth: mixed={mixed} depth={depth}', flush=True) # Bounded public CFG/dereference/proven-fact cases complement scalar depth probes. for label, source, proven in ( ('if-child', 'fn main() -> usize effects [] { let a: [usize; 1] = [0usize]; return a[if true { a[0usize] } else { 0usize }]; }', False), ('boolean-child', 'fn main() -> usize effects [] { let a: [usize; 1] = [0usize]; return a[if false or true { 0usize } else { 0usize }]; }', False), ('deref-base', 'fn read(p: ref<[usize; 1]>, i: usize) -> usize effects [] { (*p)[i] }\nfn main() -> usize effects [] { let a: [usize; 1] = [0usize]; return read(ref a, a[0usize]); }', False), ('proven-child', 'fn main() -> usize effects [] { let a: [usize; 1] = [0usize]; ref s = a; let i: usize = 0usize; if i < s.len { return a[s[i]]; } else { return 0usize; } }', True), ): path = root / f'index-context-{label}.aji' path.write_text('module depth\n' + source + '\n') assert cli('check', path) == b'' lowered = cli('lower', path) if proven: assert b' = borrow.index.proven ' in lowered, lowered options = ('--quantum', 1, '--schedule-seed', 7, '--fuel', 128) result = cli('run', path, *options) assert json.loads(result) == {'status': 'returned', 'value': 0, 'stdout': '', 'stderr': '', 'files': {}}, result air = path.with_suffix('.air') air.write_bytes(lowered) assert cli('run', air, *options) == result formatted = path.with_suffix('.formatted.aji') output = cli('fmt', path) formatted.write_bytes(output) assert cli('fmt', formatted) == output assert cli('lower', formatted) == lowered print('index operand bounded CFG/dereference/proven contexts passed', flush=True) for leaf, code, offset, extra in ( ('unknown', 'E7002', 0, {}), ('true', 'E7005', 0, {'found': 'bool', 'expected': 'usize'}), ('1i64', 'E7005', 0, {'found': 'i64', 'expected': 'usize'}), ('ref n', 'E7006', 0, {'reason': 'invalid_borrow'}), ('b"xy"', 'E7006', 0, {'reason': 'invalid_literal'}), ('a[0usize..1usize]', 'E7006', 0, {'reason': 'invalid_borrow'}), ('n[unknown]', 'E7005', 0, {'found': 'ref'}), ('a[stop()]', 'E7005', len('a['), {'found': 'never', 'expected': 'usize'}), ): for depth in (16, 1024, 65536): prefix = 'module depth\nfn stop() -> never effects [] { trap; }\nfn main() -> usize effects [] { let a: [usize; 1] = [0usize]; var n: usize = 0usize; return ' opening = 'a[' leaf_name = re.sub(r'[^A-Za-z0-9]+', '-', leaf).strip('-') path = root / f'index-reject-{code}-{leaf_name}-{depth}.aji' path.write_text(prefix + opening * depth + leaf + ']' * depth + '; }\n') expected = cli('check', path, code=1) error = json.loads(expected) assert (error['code'], error['file'], error['line'], error['col']) == (code, str(path), 3, len(prefix.split('\n')[-1]) + len(opening) * depth + offset + 1), error for key, value in extra.items(): assert error[key] == value, 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 formatted_error = json.loads(cli('check', formatted, code=1)) text = output.decode() pos = text.rfind(leaf) assert pos >= 0, (leaf, depth) pos += offset assert (formatted_error['code'], formatted_error['file'], formatted_error['line'], formatted_error['col']) == (code, str(formatted), text[:pos].count('\n') + 1, pos - text.rfind('\n', 0, pos)), formatted_error for key, value in extra.items(): assert formatted_error[key] == value, formatted_error print(f'index operand rejection depth: {leaf}', flush=True) with tempfile.TemporaryDirectory(prefix='aji-place-base-depth-') as directory: root = Path(directory) for kind in ('array', 'field', 'range'): for depth in (1, 16, 256, 1024): if kind == 'array': ty = '[' * depth + 'usize' + '; 1]' * depth source = f'module depth\nfn main() -> usize effects [] {{ var a: {ty} = zero; return a' + '[0usize]' * depth + '; }\n' elif kind == 'field': declarations = ''.join(f'struct T{i} {{ data: ' + (f'T{i+1}' if i+1 < depth else 'usize') + ' }\n' for i in range(depth)) initial = ''.join(f'T{i} {{ data: ' for i in range(depth)) + '0usize' + ' }' * depth source = 'module depth\n' + declarations + 'fn main() -> usize effects [] { var a: T0 = ' + initial + '; ref r = a; return r' + '.data' * depth + '; }\n' else: source = 'module depth\nfn main() -> usize effects [] { var a: [usize; 1] = zero; ref s = a' + '[0usize..1usize]' * depth + '; return s[0usize]; }\n' path = root / f'place-base-{kind}-{depth}.aji' path.write_text(source) assert cli('check', path) == b'' lowered = cli('lower', path) expected_op = b'borrow.field @' if kind == 'field' else b'slice.sub %' if kind == 'range' else b'borrow.index %' assert sum(expected_op in line for line in lowered.splitlines()) == depth, (kind, depth) formatted = path.with_suffix('.formatted.aji') output = cli('fmt', path) formatted.write_bytes(output) assert cli('fmt', formatted) == output assert cli('lower', formatted) == lowered if depth <= 256: instructions = sum(line.startswith(b' ') and (b' = ' in line or line.strip().startswith((b'ret ', b'borrow.end ', b'local.store ', b'local.zero ', b'store '))) for line in lowered.splitlines()) air = path.with_suffix('.air') air.write_bytes(lowered) options = ('--quantum', 1, '--schedule-seed', 7, '--fuel', instructions) result = cli('run', path, *options) assert json.loads(result) == {'status': 'returned', 'value': 0}, (kind, depth, lowered, result) assert cli('run', air, *options) == result exhaustion = ('--quantum', 1, '--schedule-seed', 7, '--fuel', instructions - 1) limit = cli('run', path, *exhaustion, code=5) assert json.loads(limit) == {'status': 'limit_exceeded', 'kind': 'fuel', 'limit': instructions - 1, 'steps': instructions - 1}, (kind, depth, instructions, limit) assert cli('run', air, *exhaustion, code=5) == limit print(f'place base {kind} {depth} passed', flush=True) # Bound-mode, RHS-first store, ancestor cleanup and a mixed projection spine. for label, source, value, marker in ( ('write', 'struct S { data: [[usize; 1]; 1] }\nfn main() -> usize effects [] { var s: S = S { data: [[0usize]] }; s.data[0usize][0usize] = s.data[0usize][0usize] + 1usize; return s.data[0usize][0usize]; }', 1, b'store %'), ('unchecked', 'struct S { data: [[usize; 1]; 1] }\nfn main() -> usize effects [unsafe] { var s: S = S { data: [[0usize]] }; ref unchecked r = s.data[0usize][0usize]; return *r; }', 0, b'borrow.index.unchecked %'), ('deref', 'struct S { data: [[usize; 1]; 1] }\nfn read(p: ref) -> usize effects [] { (*p).data[0usize][0usize] }\nfn main() -> usize effects [] { var s: S = S { data: [[0usize]] }; return read(ref s); }', 0, b'borrow.field @S.data'), ('proven', 'fn main() -> usize effects [] { var a: [usize; 1] = zero; ref s = a[0usize..1usize]; let i: usize = 0usize; if i < s.len { return s[i]; } else { return 2usize; } }', 0, b'borrow.index.proven %'), ): path = root / f'place-context-{label}.aji' path.write_text('module depth\n' + source + '\n') assert cli('check', path) == b'' lowered = cli('lower', path) assert marker in lowered, (label, lowered) air = path.with_suffix('.air') air.write_bytes(lowered) opts = ('--quantum', 1, '--schedule-seed', 7, '--fuel', 128) result = cli('run', path, *opts) expected = {'status': 'returned', 'value': value} if label != 'proven': expected.update(stdout='', stderr='', files={}) assert json.loads(result) == expected, result assert cli('run', air, *opts) == result formatted = path.with_suffix('.formatted.aji') output = cli('fmt', path) formatted.write_bytes(output) assert cli('fmt', formatted) == output assert cli('lower', formatted) == lowered for expression, code, offending in ( ('s.data[unknown][true]', 'E7002', 'unknown'), ('s.data[true][unknown]', 'E7005', 'true'), ('s.missing[unknown]', 'E7002', 's.missing'), ('a[unknown..true]', 'E7002', 'unknown'), ('a[true..unknown]', 'E7005', 'true'), ('a[0usize..unknown]', 'E7002', 'unknown'), ('a[0usize..true]', 'E7005', 'true'), ): path = root / 'place-error.aji' source = 'module depth\nstruct S { data: [[usize; 1]; 1] }\nfn main() -> usize effects [] { var s: S = S { data: [[0usize]] }; var a: [usize; 1] = zero; ref r = ' + expression + '; return 0usize; }\n' path.write_text(source) diag = cli('check', path, code=1) record = json.loads(diag) assert record['code'] == code, record start = source.index(offending, source.index('ref r =')) assert record['line'] == source.count('\n', 0, start) + 1 assert record['col'] == start - source.rfind('\n', 0, start) for command in ('lower', 'run', 'report', 'explore'): assert cli(command, path, code=1) == diag print('place base contexts and rejection positions passed', flush=True) with tempfile.TemporaryDirectory(prefix='aji-control-parser-depth-') as directory: root = Path(directory) for kind in ('block', 'if', 'else-if'): depths = (1, 16, 256, 1024) if kind != 'else-if' else (1, 16, 256, 1024, 16384, 65536) for depth in depths: if kind == 'block': expression = '{ ' * depth + '0usize' + ' }' * depth elif kind == 'if': expression = 'if true { ' * depth + '0usize' + ' } else { 1usize }' * depth else: expression = 'if false { 1usize } else ' * depth + '{ 0usize }' path = root / f'control-parser-{kind}-{depth}.aji' path.write_text('module depth\nfn main() -> usize effects [] { return ' + expression + '; }\n') formatted = path.with_suffix('.formatted.aji') output = cli('fmt', path) formatted.write_bytes(output) assert cli('fmt', formatted) == output if depth <= 256: assert cli('check', path) == b'' lowered = cli('lower', path) assert cli('lower', formatted) == lowered if depth <= 16: air = path.with_suffix('.air') air.write_bytes(lowered) options = ('--quantum', 1, '--schedule-seed', 7, '--fuel', 4096) result = cli('run', path, *options) assert json.loads(result) == {'status': 'returned', 'value': 0}, (kind, depth, result) assert cli('run', air, *options) == result print(f'control parser {kind} {depth} passed', flush=True) # Syntax-only control contexts avoid conflating parser depth with the # still-open lowering/liveness audit or requiring semantic task fixtures. syntax_forms = ( ('let', '{ let x = ', '; x }'), ('return', '{ return ', '; }'), ('while', '{ while true { ', '; } }'), ('for', '{ for i in 0usize..1usize { ', '; } }'), ('loop', '{ loop { ', '; } }'), ('scope', '{ scope s { ', '; } }'), ('shield', '{ shield { ', '; } }'), ('lock', '{ lock ref m as x { ', '; } cancelled {} }'), ('match', 'match e { _ => ', ' }'), ('select-send', '{ select { send(tx, ', ') { ok => {} } cancelled => {} } }'), ('select-outcome', '{ select { recv(rx) { ok => ', ' } cancelled => {} } }'), ('select-cancelled', '{ select { cancelled => ', ' } }'), ) for label, before, after in syntax_forms: path = root / f'control-syntax-{label}.aji' path.write_text('module depth\nfn main() -> usize effects [] { return ' + before * 256 + '0usize' + after * 256 + '; }\n') output = cli('fmt', path) formatted = path.with_suffix('.formatted.aji') formatted.write_bytes(output) assert cli('fmt', formatted) == output # Six sequential CLI processes at each depth. The 32,768 mixed check # measured 350,804 KiB max RSS on Linux/Debug; this is informational, # environment-dependent evidence, not a CI memory bound. for mixed in (False, True): for depth in (16, 1024, 32768): forms = syntax_forms if mixed else syntax_forms[:1] expression = ''.join(forms[i % len(forms)][1] for i in range(depth)) + '!0usize' + ''.join(forms[i % len(forms)][2] for i in reversed(range(depth))) path = root / f'control-error-{mixed}-{depth}.aji' source = '// UTF-8: λ\r\nmodule depth\r\nfn main() -> usize effects [] { return ' + expression + '; }\r\n' path.write_bytes(source.encode()) rejected = cli('check', path, code=1) record = json.loads(rejected) pos = source.index('!0usize') assert (record['code'], record['line'], record['col']) == ('E7001', 3, pos - source.rfind('\n', 0, pos)), record assert record['expected'] == 'an expression' and record['found'] == '!', record assert record['repair_candidates'][0]['kind'] == 'boolean_negation', record for command in ('lower', 'run', 'report', 'explore', 'fmt'): assert cli(command, path, code=1) == rejected print('control parser syntax and first-error positions passed', flush=True) print(f'source expression depth: {checks} checks passed')