diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index a3d966a..738da8b 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -550,3 +550,5 @@ The [struct/value-field increment](source-expression-depth-audit.md#struct-const The [array-continuation increment](source-expression-depth-audit.md#array-list-and-repetition-continuations) preserves list inference/consumption/check priority, repetition bounds/Copy rules, emission/loans and host OOM. Independent comparisons and deep sibling/error/OOM tests pass; the former pure-list failure at 4,096 now accepts. Variant-payload/call alternation still aborts at 256 before and after; remaining native callbacks and liveness/read/assignment walks keep Q-061 open. No new semantic or depth limit changes. All 1,793 ordinary conformance cases, 246 focused depth CLI checks and exact public check/lower parity (1,423/506) pass. Read-only Claude core/follow-up reviews found no production defects; their fixture gaps were corrected. Whole-frontend, loop/liveness and Phase 6 completion are not established. The [enum-payload increment](source-expression-depth-audit.md#enum-payload-continuations) preserves lookup/arity-before-arguments, per-payload type/consumption/check order, empty/built-in construction, spans/loans and OOM. Independent shallow/deep/sibling and direct/public allocation tests pass; exact ordinary conformance coverage and final public check/lower parity (1,423/506) pass. The former enum-payload failure at 256 is repaired; nested assert still aborts at 1,024 before and after. Scoped read-only Claude reviews found no semantic defects; 331 core and 66 final supplementary CLI checks pass. Q-061 and Phase 6 remain open, with no semantic or new depth limit change. + +The [boolean builtin increment](source-expression-depth-audit.md#boolean-builtin-operand-continuations) preserves assert/assume arity, non-consuming operands, type/error spans, unsafe registration and emission order, using shared continuations. All 1,793 ordinary conformance cases, public check/lower parity (1,423/506) and 282 focused depth checks pass. Expanded units and 69 supplemental checks pass; read-only Claude core/follow-up reviews found no production defect. Final span/counter unit checks pass. Own/region argument callbacks still abort at 1,024 before and after; remaining callbacks/walks keep Q-061 and Phase 6 open. No new semantic or depth limit changes. diff --git a/docs/design/source-expression-depth-audit.md b/docs/design/source-expression-depth-audit.md index af23242..333ed53 100644 --- a/docs/design/source-expression-depth-audit.md +++ b/docs/design/source-expression-depth-audit.md @@ -705,6 +705,55 @@ probes still abort at 1,024 before and after (`variant-followup-assert-probes.js in `prepareCall` → `expr`. Builtin/place/control callbacks and liveness/read/ assignment walks keep Q-061 open; Q-060 full GC and Phase 6 gates remain separate. +## Boolean builtin operand continuations + +`assert` and `assume` now evaluate their non-consuming boolean operand in the +shared expression driver (spec 15 §4–§5; unsafe boundary: spec 13 §6). Arity precedes the child; its exact +span/type check precedes unsafe registration, emission and the void result. +Dispatch priority, names, CFG and errors remain unchanged. Stable continuation +states and work buffers retain caller-arena lifetime. Host OOM propagates +separately from source problems, including allocation while rejecting a +program. No normative, format, feature, code, bundle, limit or ownership/runtime +rule changes. The preserved invariant is that only a checked boolean reaches +the instruction. Verifier effect requirements and deterministic runtime rules +remain unchanged: `source/layer6/unchecked.aji` is valid and +`source/nonvalue_operands/assume.aji` rejects E7005; supplemental false-input +runs retain T0002/T0009. Public output parity establishes compatibility. + +The copied old boolean builtin bodies join the shallow oracle, including +scalar/boolean/call, aggregate/field/variant consumers and non-value operands. +Shared control/place/emission/type helpers limit its independence. Deep units +cover 32,768 ordinary-call operands and alternating assert/assume/call errors, +exact spans, counts and unsafe registration. Public recovering/persistent OOM +sweeps cover accepted and rejected programs and arena backing cleanup. +Final expanded unit validation, including distinct-callee spans and exact +counters, passes. + +The ordinary conformance run passes all 1,793 cases with exact coverage +(`boolean-builtin-conformance.jsonl` and its audit). Frozen public check/lower +outputs are exact (1,423/506; `boolean-builtin-public-parity.json`); targeted +nonvalue/linear/independent-error suites pass 635/49/234 checks. The focused CLI +block passes 282 checks: nested void errors and ordinary-call operands through +65,536, exact diagnostic positions and cross-command records, AIR/formatter +parity, and successful values/fuel through 1,024. Supplemental trap/hosted/ +feature and mixed deep arity/type validation passes 69 checks +(`boolean-builtin-supplemental-depth.log`). Trap/hosted/fuel runs are bounded +at 1,024; the larger depths check/lower/format or reject. These focused runs +are not a new full run of `source_expression_depth.py`. + +Claude's read-only core/follow-up reviews found no production defect +(`/tmp/aji-boolean-builtin-review.md` and +`/tmp/aji-boolean-builtin-followup-review.md`). Fixture gaps were corrected; +final distinct-callee-span/counter assertions follow the review. Neither +reviewer ran tests. Dispatch/query shadowing was not separately validated; +mixed deep-error call frames are descended but not all resumed. A repetition +fixture requires the prepared nominal-property module and is tested there. Separate probes of +`own.free`, `own.take` and `region.destroy` retain JSON at 16/256 but abort at +1,024 before and after (`boolean-builtin-callback-probes.json`); the current +trace enters `prepareCall` from `consuming`. Other builtin/place/control +callbacks and liveness/read/assignment walks, Q-060 full GC validation and +Phase 6 exit gates remain open. + ## Remaining work Follow-up checks accept 16 parenthesized/mixed-call levels but abort @@ -719,7 +768,7 @@ includes a confirmed lowerer failure and inspection-only risks: | Production path | Evidence and next scope | |---|---| | Parser `ifExpr`, block/statement and match/arm expression entry | Native callback re-entry remains. Bounded block/if regression probes above pass; arbitrary and alternating control/statement depth is unverified. | -| Lowerer non-scalar `expr` callbacks: builtin/variant calls, fields/indices/places, arrays/structs, if/match/arms and blocks/statements | Ordinary calls, struct/value-field, array and enum-payload descent are repaired above. Nested assert lowering still aborts at 1,024 in both binaries. Other callback depth remains unverified; include alternating scalar/non-scalar expressions. | +| Lowerer non-scalar `expr` callbacks: builtin/variant calls, fields/indices/places, arrays/structs, if/match/arms and blocks/statements | Ordinary calls, struct/value-field, array and enum-payload descent are repaired above. Boolean builtin operands are repaired above; own/region argument callbacks still abort at 1,024 in both binaries. Other callback depth remains unverified; include alternating scalar/non-scalar expressions. | | Lowerer use-after-region/liveness and assignment scans (`After`, first-use/read scans, `blockAssigns`/`stmtAssigns`/`exprAssigns`, match/select helpers) | Recursive AST walks inspected; audit their callers and finite deep inputs separately. | The formatter's expression-marking traversal already uses a worklist, as diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index 9cd5a8b..d393d8f 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -708,3 +708,16 @@ parity pass. Scoped Claude reviews found no semantic defects. The former after. Initial focused CLI checks (331) and final supplementary checks (66) pass. Q-061, Q-060 and Phase 6 remain open. No normative/format/feature/ code/bundle/limit or ownership/runtime change. + +### Boolean builtin operand depth increment + +The [Q-061 boolean builtin increment](../design/source-expression-depth-audit.md#boolean-builtin-operand-continuations) +shares assert/assume operands with the expression driver, preserving arity, +non-consuming evaluation, type/error spans, unsafe registration and emission. +Caller-arena lifetime and host OOM separation remain explicit. Exact ordinary +conformance coverage (1,793), public check/lower parity (1,423/506), targeted +nonvalue/linear/independent-error checks (635/49/234), and 282 focused depth +checks pass. Expanded units and 69 supplemental checks pass; read-only Claude core/follow-up +reviews found no production defect. Final span/counter unit checks pass. Own/region argument callbacks still abort at 1,024 in +both binaries. No semantic/depth-limit change; Q-061, Q-060 full GC validation +and Phase 6 exit gates remain open. diff --git a/src/frontend/lower.zig b/src/frontend/lower.zig index 1a01e6d..2b4cb8f 100644 --- a/src/frontend/lower.zig +++ b/src/frontend/lower.zig @@ -2015,6 +2015,7 @@ const Lowerer = struct { .done => |v| v, .ordinary => |c| l.operandExprPrepared(e, null, .{ .call = c }), .variant => |c| l.operandExprPrepared(e, null, .{ .variant = c }), + .boolean_builtin => |c| l.operandExprPrepared(e, null, .{ .boolean_builtin = c }), }, .if_expr => |x| return l.ifExpr(e.span, x.*, want), .block => |b| { @@ -2038,7 +2039,7 @@ const Lowerer = struct { } } - // Scalar operands, ordinary calls, aggregate initializers and value fields + // Scalar operands, ordinary calls, boolean builtins, aggregates and fields // share one worklist for arbitrary alternation of those expression forms. fn operandExpr(l: *Lowerer, initial: ast.Expr, initial_want: ?Ty) Error!Value { return l.operandExprPrepared(initial, initial_want, .none); @@ -2057,6 +2058,7 @@ const Lowerer = struct { array_element: *ArrayConstruction, array_repeat: ast.Expr, variant_argument: *VariantConstruction, + boolean_builtin: *BooleanBuiltin, }; var pending: std.ArrayList(Frame) = .empty; defer pending.deinit(l.arena); @@ -2127,6 +2129,13 @@ const Lowerer = struct { want = c.current_ty; continue; }, + .boolean_builtin => |c| { + prepared = .none; + try pending.append(l.arena, .{ .boolean_builtin = c }); + e = c.input; + want = .bool; + continue; + }, } switch (e.kind) { .not, .deref => |x| { @@ -2181,6 +2190,7 @@ const Lowerer = struct { .done => |v| break v, .ordinary => |c| prepared = .{ .call = c }, .variant => |c| prepared = .{ .variant = c }, + .boolean_builtin => |c| prepared = .{ .boolean_builtin = c }, }, .variant => |x| switch (try l.prepareVariant(e, x.@"enum", x.name, &.{})) { .done => |v| break v, @@ -2296,6 +2306,12 @@ const Lowerer = struct { prepared = .{ .variant = c }; continue :evaluate; }, + .boolean_builtin => |c| { + try l.checkOperandTy(c.input.span, v.ty, .bool); + if (c.assume) l.uses.insert(.unsafe); + try l.emit(try l.fmt("{s} %{s}", .{ if (c.assume) "assume" else "assert", v.name }), c.span); + v = .{ .name = "", .ty = .void }; + }, .field_value => |f| v = try l.finishField(f, v), .array_element => |c| { const input = c.inputs[c.index]; @@ -2368,6 +2384,7 @@ const Lowerer = struct { field: *FieldRead, array: *ArrayConstruction, variant: *VariantConstruction, + boolean_builtin: *BooleanBuiltin, }; const OrdinaryCall = struct { @@ -2380,13 +2397,15 @@ const Lowerer = struct { names: std.ArrayList(u8) = .empty, temps: std.ArrayList([]const u8) = .empty, }; - const CallDispatch = union(enum) { done: Value, ordinary: *OrdinaryCall, variant: *VariantConstruction }; + const BooleanBuiltin = struct { span: Span, input: ast.Expr, assume: bool }; + const CallDispatch = union(enum) { done: Value, ordinary: *OrdinaryCall, variant: *VariantConstruction, boolean_builtin: *BooleanBuiltin }; fn call(l: *Lowerer, e: ast.Expr, callee: ast.Expr, args: []const ast.Expr, borrow_allowed: bool) Error!Value { return switch (try l.prepareCall(e, callee, args, borrow_allowed)) { .done => |v| v, .ordinary => |c| l.operandExprPrepared(e, null, .{ .call = c }), .variant => |c| l.operandExprPrepared(e, null, .{ .variant = c }), + .boolean_builtin => |c| l.operandExprPrepared(e, null, .{ .boolean_builtin = c }), }; } @@ -2469,20 +2488,12 @@ const Lowerer = struct { return l.invalid(.invalid_unpack, e.span, "`split_at` yields two borrows: `let (left, right) = s.split_at(k);`", &.{}); if (callee.kind != .name) return l.notYet(callee.span, "built-in operations (later layers)"); const name = callee.kind.name; - if (std.mem.eql(u8, name, "assert")) { - if (args.len != 1) return l.fail("E7005", e.span, "`assert` takes one boolean", &.{}); - const v = try l.expr(args[0], .bool); - try l.checkOperandTy(args[0].span, v.ty, .bool); - try l.emit(try l.fmt("assert %{s}", .{v.name}), e.span); - return .{ .done = .{ .name = "", .ty = .void } }; - } - if (std.mem.eql(u8, name, "assume")) { - if (args.len != 1) return l.fail("E7005", e.span, "`assume` takes one boolean", &.{}); - const v = try l.expr(args[0], .bool); - try l.checkOperandTy(args[0].span, v.ty, .bool); - l.uses.insert(.unsafe); - try l.emit(try l.fmt("assume %{s}", .{v.name}), e.span); - return .{ .done = .{ .name = "", .ty = .void } }; + const is_assume = std.mem.eql(u8, name, "assume"); + if (is_assume or std.mem.eql(u8, name, "assert")) { + if (args.len != 1) return l.fail("E7005", e.span, if (is_assume) "`assume` takes one boolean" else "`assert` takes one boolean", &.{}); + const state = try l.arena.create(BooleanBuiltin); + state.* = .{ .span = e.span, .input = args[0], .assume = is_assume }; + return .{ .boolean_builtin = state }; } const sig = l.functionSig(name, callee.span) orelse return l.unknown(callee.span, name); if (args.len != sig.params.len) return l.fail("E7005", e.span, "wrong number of arguments", &.{ .{ .name = "function", .value = sig.display_name }, .{ .name = "expected", .value = try l.fmt("{d}", .{sig.params.len}) }, .{ .name = "found", .value = try l.fmt("{d}", .{args.len}) } }); @@ -8271,3 +8282,137 @@ test "public variant lowering propagates each allocation failure and frees its a } } } + +test "boolean builtin continuations match former arity types CFG and unsafe registration" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const expressions = [_][]const u8{ + "assert(true)", "assume(false)", "assert()", "assume()", + "assert(unknown, false)", "assume(unknown, false)", "assert(unknown)", "assume(unknown)", + "assert(1i64)", "assume(1)", "assert(n)", "assume(p)", + "assert(o)", "assert(move o)", "assume(ref n)", "assert(b\"xy\")", + "assert(bool_id(true) and false)", "assume(false or bool_id(true))", "assert(not bool_id(false))", "assume(bool_id(false) == true)", + "assert(assert(true))", "assert(assume(true))", "assume(assert(true))", "assume(assume(true))", + "assert(bool_id(assert(true)))", "assume(assert(unknown))", "assert(stop(b\"xy\"))", "assume(void_call(b\"xy\"))", + "bool_id(assert(true))", "pair(assert(true), unknown)", "assert(if true { true } else { false })", "assume({ true })", + "assert([true])", "assume(true as! u8)", "assert(1i64 as! u8)", "assert(ns.id(1i64))", + "assume(bool_id(assume(false)))", + }; + const forms = [_][]const u8{ "{s}", "assert({s})", "assume({s})", "not ({s})", "bool_id({s})", "true and ({s})", "({s}) or false", "- ({s})", "({s}) as! u8", "1i64 == ({s})" }; + inline for (forms) |form| for (expressions) |text| { + const parsed = try parse_mod.parse(a, try std.fmt.allocPrint(a, "module calls\nfn f() -> void effects [] {{ return {s}; }}", .{try std.fmt.allocPrint(a, form, .{text})})); + try std.testing.expect(parsed == .ok); + const e = parsed.ok.functions[0].body.stmts[0].kind.@"return".?; + for ([_]?Ty{ null, .bool, .{ .int = "i64" }, .{ .int = "u8" } }) |want| { + try expectCallMatches(a, e, want, false); + if (e.kind == .call) try expectCallMatches(a, e, want, true); + } + }; +} + +test "deep boolean builtin operands and alternating nested errors avoid native descent" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const count = 32_768; + const boolean: ast.Expr = .{ .span = unaryTestSpan(90_000), .kind = .{ .boolean = true } }; + const identity: ast.Expr = .{ .span = unaryTestSpan(70_001), .kind = .{ .name = "bool_id" } }; + const assertion: ast.Expr = .{ .span = unaryTestSpan(70_002), .kind = .{ .name = "assert" } }; + const assumption: ast.Expr = .{ .span = unaryTestSpan(70_003), .kind = .{ .name = "assume" } }; + for ([_]bool{ false, true }) |unsafe_builtin| { + var e = boolean; + for (0..count) |i| { + const args = try a.alloc(ast.Expr, 1); + args[0] = e; + e = .{ .span = unaryTestSpan(@intCast(i + 1)), .kind = .{ .call = .{ .callee = &identity, .type_arg = null, .args = args } } }; + } + const args = try a.alloc(ast.Expr, 1); + args[0] = e; + const span = unaryTestSpan(100_000); + const root: ast.Expr = .{ .span = span, .kind = .{ .call = .{ .callee = if (unsafe_builtin) &assumption else &assertion, .type_arg = null, .args = args } } }; + var l = try callTestLowerer(a, span); + const initial_counter = l.counter; + const v = try l.expr(root, null); + try std.testing.expect(v.ty == .void); + const insts = l.blocks.items[0].insts.items; + try std.testing.expectEqual(count + 2, insts.len); + try std.testing.expectEqual(initial_counter + count + 1, l.counter); + for (0..count) |i| try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(@intCast(i + 1))), insts[i + 1].span); + try std.testing.expect(std.mem.startsWith(u8, insts[count + 1].text, if (unsafe_builtin) "assume %" else "assert %")); + try std.testing.expectEqualDeep(@as(?Span, span), insts[count + 1].span); + try std.testing.expectEqual(unsafe_builtin, l.uses.contains(.unsafe)); + } + for ([_]bool{ false, true }) |innermost_assume| { + var e = boolean; + for (0..count) |i| { + const args = try a.alloc(ast.Expr, 1); + args[0] = e; + e = .{ .span = unaryTestSpan(@intCast(i + 1)), .kind = .{ .call = .{ .callee = if ((i % 2 == 0) == innermost_assume) &assumption else &assertion, .type_arg = null, .args = args } } }; + if (i > 0 and i % 3 == 0) { + const input = try a.alloc(ast.Expr, 1); + input[0] = e; + e = .{ .span = unaryTestSpan(@intCast(i + 1)), .kind = .{ .call = .{ .callee = &identity, .type_arg = null, .args = input } } }; + } + } + var l = try callTestLowerer(a, e.span); + const initial_counter = l.counter; + try std.testing.expectError(error.Lower, l.expr(e, null)); + try std.testing.expectEqualStrings("E7005", l.problem.?.code); + try std.testing.expectEqualDeep(unaryTestSpan(1), l.problem.?.span); + const insts = l.blocks.items[0].insts.items; + try std.testing.expectEqual(@as(usize, 2), insts.len); + try std.testing.expectEqual(initial_counter + 1, l.counter); + try std.testing.expectEqual(innermost_assume, l.uses.contains(.unsafe)); + try std.testing.expect(std.mem.startsWith(u8, insts[1].text, if (innermost_assume) "assume %" else "assert %")); + } +} + +test "public boolean builtin lowering propagates OOM and frees arena backing" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const programs = [_][]const u8{ + "module oom\nfn id(v: bool) -> bool effects [] { return v; }\nfn main() -> void effects [unsafe] { assert(id(true) and false); assume(not id(false)); }\n", + "module oom\nfn main() -> void effects [] { assert(1); }\n", + "module oom\nfn main() -> void effects [] { assert(); }\n", + "module oom\nfn main() -> void effects [unsafe] { assume(assume(true)); }\n", + }; + for (programs, 0..) |program, program_index| { + const parsed = try parse_mod.parse(fixture.allocator(), program); + try std.testing.expect(parsed == .ok); + for ([_]bool{ false, true }) |persistent| { + var fail_at: usize = 0; + while (true) : (fail_at += 1) { + try std.testing.expect(fail_at < 1024); + var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = fail_at }); + var output: std.heap.ArenaAllocator = .init(if (persistent) failing.allocator() else std.testing.allocator); + var recovering: QueryAllocationFailure = .{ .backing = output.allocator(), .fail_at = fail_at }; + const result = lower(if (persistent) output.allocator() else recovering.allocator(), parsed.ok); + output.deinit(); + if (persistent) try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes); + const failed = if (persistent) failing.has_induced_failure else recovering.failed; + if (failed) { + try std.testing.expectError(error.OutOfMemory, result); + if (!persistent) try std.testing.expectEqual(fail_at + 1, recovering.attempts); + } else { + try std.testing.expect(std.meta.activeTag(try result) == @as(std.meta.Tag(Result), if (program_index == 0) .ok else .err)); + break; + } + } + } + } +} + +test "boolean builtin values preserve aggregate and field consumer failures" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const expressions = [_][]const u8{ "assert(true)", "assume(false)", "assert(Box { n: 1i64 }.n)", "assume(sl[0])", "assume([true; 2])" }; + const forms = [_][]const u8{ "[{s}]", "[{s}; 2]", "Bool {{ flag: {s} }}", "({s}).n", "Payload::pair(1i64, {s})", "assert({s})", "assume({s})" }; + inline for (forms) |form| for (expressions) |text| { + const parsed = try parse_mod.parse(a, try std.fmt.allocPrint(a, "{s}fn f() -> void effects [] {{ return {s}; }}", .{ variantTestDeclarations, try std.fmt.allocPrint(a, form, .{text}) })); + try std.testing.expect(parsed == .ok); + const e = parsed.ok.functions[0].body.stmts[0].kind.@"return".?; + for ([_]?Ty{ null, .bool, .{ .int = "u8" } }) |want| try expectFieldMatches(a, parsed.ok, e, want); + }; +} diff --git a/tests/hosted/source_expression_depth.py b/tests/hosted/source_expression_depth.py index 382a2ee..2f8536c 100644 --- a/tests/hosted/source_expression_depth.py +++ b/tests/hosted/source_expression_depth.py @@ -636,16 +636,103 @@ with tempfile.TemporaryDirectory(prefix='aji-expression-depth-') as directory: assert cli('lower', formatted) == lowered print(f'empty variant depth: {depth}', flush=True) - # Builtin callbacks are still native; preserve the prior diagnostic at - # bounded nesting while ordinary calls gain explicit continuations. - for depth in (16, 64, 256): - path = root / f'nested-assert-{depth}.aji' - path.write_text('module depth\nfn main() -> i64 effects [] { ' + - 'assert(' * depth + 'true' + ')' * depth + '; return 1i64; }\n') - expected = cli('check', path, code=1) - assert json.loads(expected)['code'] == 'E7005' - for command in ('lower', 'run', 'report', 'explore'): - assert cli(command, path, code=1) == expected + # 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