From 062fce5cfd8ded600f1789048a22be2646a58ae9 Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Sun, 11 Oct 2026 15:09:00 +0300 Subject: [PATCH] cli: lower consuming ownership builtin operands iteratively --- docs/design/open-questions.md | 2 + docs/design/source-expression-depth-audit.md | 46 +++- docs/plan/phase-6-source-language.md | 13 ++ src/frontend/lower.zig | 222 +++++++++++++++++-- tests/hosted/source_expression_depth.py | 65 ++++++ 5 files changed, 333 insertions(+), 15 deletions(-) diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index 738da8b..4c958b7 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -552,3 +552,5 @@ The [array-continuation increment](source-expression-depth-audit.md#array-list-a 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. + +The [consuming ownership builtin increment](source-expression-depth-audit.md#consuming-ownership-builtin-continuations) preserves own.take/free and region.destroy arity, explicit transfers, type/error priority, emission and OOM separation. All 1,793 ordinary conformance cases, public check/lower parity (1,423/506) and 351 frozen-core CLI checks pass; corrected OOM/expanded units pass. 108 formatted-rejection checks pass; read-only Claude core/follow-up reviews found no production defect. Final `own` CFG unit comparisons pass. Atomic-new/take pairs and task.join still abort at 1,024. Q-061, Q-060 full GC and Phase 6 gates remain open; no semantic/depth-limit change. diff --git a/docs/design/source-expression-depth-audit.md b/docs/design/source-expression-depth-audit.md index 333ed53..f71b421 100644 --- a/docs/design/source-expression-depth-audit.md +++ b/docs/design/source-expression-depth-audit.md @@ -754,6 +754,50 @@ 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. +## Consuming ownership builtin continuations + +`own.take`, `own.free` and `region.destroy` now share the expression driver +(spec 15 §5, §8, §16). Arity precedes explicit-name consumption checking and +operand evaluation with no expected-type hint. Exact type/error-span checks +precede extraction/destruction emission. The invariant is unchanged: ownership +is transferred explicitly once; the verifier still checks use-after-move, leaks, +linear content and live region loans. Runtime rules are unchanged, including +whole-value extraction and deterministic destruction. `layer5/own_basic.aji` +and `layer5/region.aji` remain valid; `layer5/reject/missing_move.aji` retains +E7003; `source/linear/free_linear_content.aji` still rejects E1001 at +`own.free`. No new diagnostic/feature/format/bundle/limit or ownership rule. + +The old bodies in `ReferenceCalls` provide shallow comparisons across owners, +arrays, regions, nominal content and scalar/aggregate/CFG consumers. Shared +leaf/type/emission/place helpers limit independence; raw borrowed-content +owners are defensive fixtures, not newly accepted source. Deep units cover +32,768 forwarding calls and invalid nested/mixed descent, exact names/spans +and one completed builtin before rejection. Recovering/persistent public OOM +sweeps cover success and E7003/E7005. The initial missing-main fixture was +corrected and baseline results asserted before sweeping. Arena backing is +released on destruction; worklists retain caller-arena lifetime. Final expanded +units pass, including successful `own` boolean CFG comparisons. + +All 1,793 ordinary conformance cases pass with exact coverage, and frozen +public check/lower outputs are exact (1,423/506). Targeted linear/nonvalue/ +inferred-content suites pass 49/635/302 checks. The frozen core passes 351 +focused CLI checks: forwarding calls and exact cross-command arity/type/name +errors through 65,536, formatter/AIR fidelity, values and fuel through 1,024. +Final formatted-rejection supplementary checks pass 108 cases +(`consuming-builtin-supplemental-depth.log`). This does not +claim a fresh full expression-depth suite run. + +Claude's read-only core/follow-up reviews found no production defect +(`/tmp/aji-consuming-builtin-review.md` and +`/tmp/aji-consuming-builtin-followup-review.md`). Their fixture gaps were +corrected; the final `own` addition follows the review. Neither reviewer +ran tests. Deep mixed errors establish descent and one builtin completion, +not completion of every pending call. Separate atomic-new/take pairs accept 16 in both binaries, abort at +256 only before, and abort at 1,024 in both; task.join chains still abort at +1,024 (`consuming-builtin-next-probes.json`). No frame-size explanation is +established. Other builtin/place/control and liveness callbacks, Q-060 full GC +validation and Phase 6 gates remain open. + ## Remaining work Follow-up checks accept 16 parenthesized/mixed-call levels but abort @@ -768,7 +812,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. 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 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 and consuming own/region builtin operands are repaired above. Atomic-new/take pairs and task.join 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 d393d8f..ca9701a 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -721,3 +721,16 @@ checks pass. Expanded units and 69 supplemental checks pass; read-only Claude co 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. + +### Consuming ownership builtin depth increment + +The [Q-061 consuming builtin increment](../design/source-expression-depth-audit.md#consuming-ownership-builtin-continuations) +shares own.take/free and region.destroy operands with the expression driver. +Arity, explicit-name transfers, type/error priority, emission and host OOM +remain unchanged; buffers retain caller-arena lifetime. Corrected OOM and +expanded units, all 1,793 ordinary conformance cases, public check/lower parity +(1,423/506), targeted linear/nonvalue/inferred-content suites (49/635/302) and +351 frozen-core depth checks pass. 108 formatted-rejection checks pass; read-only Claude core/follow-up reviews +found no production defect. Final `own` CFG unit comparisons pass. Atomic-new/take pairs and task.join +still abort at 1,024. 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 2b4cb8f..b2ac3d3 100644 --- a/src/frontend/lower.zig +++ b/src/frontend/lower.zig @@ -2016,6 +2016,7 @@ const Lowerer = struct { .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 }), + .consuming_builtin => |c| l.operandExprPrepared(e, null, .{ .consuming_builtin = c }), }, .if_expr => |x| return l.ifExpr(e.span, x.*, want), .block => |b| { @@ -2059,6 +2060,7 @@ const Lowerer = struct { array_repeat: ast.Expr, variant_argument: *VariantConstruction, boolean_builtin: *BooleanBuiltin, + consuming_builtin: *ConsumingBuiltin, }; var pending: std.ArrayList(Frame) = .empty; defer pending.deinit(l.arena); @@ -2136,6 +2138,14 @@ const Lowerer = struct { want = .bool; continue; }, + .consuming_builtin => |c| { + prepared = .none; + try l.checkConsumingName(c.input); + try pending.append(l.arena, .{ .consuming_builtin = c }); + e = c.input; + want = null; + continue; + }, } switch (e.kind) { .not, .deref => |x| { @@ -2191,6 +2201,7 @@ const Lowerer = struct { .ordinary => |c| prepared = .{ .call = c }, .variant => |c| prepared = .{ .variant = c }, .boolean_builtin => |c| prepared = .{ .boolean_builtin = c }, + .consuming_builtin => |c| prepared = .{ .consuming_builtin = c }, }, .variant => |x| switch (try l.prepareVariant(e, x.@"enum", x.name, &.{})) { .done => |v| break v, @@ -2312,6 +2323,7 @@ const Lowerer = struct { try l.emit(try l.fmt("{s} %{s}", .{ if (c.assume) "assume" else "assert", v.name }), c.span); v = .{ .name = "", .ty = .void }; }, + .consuming_builtin => |c| v = try l.finishConsumingBuiltin(c, v), .field_value => |f| v = try l.finishField(f, v), .array_element => |c| { const input = c.inputs[c.index]; @@ -2385,6 +2397,7 @@ const Lowerer = struct { array: *ArrayConstruction, variant: *VariantConstruction, boolean_builtin: *BooleanBuiltin, + consuming_builtin: *ConsumingBuiltin, }; const OrdinaryCall = struct { @@ -2398,7 +2411,20 @@ const Lowerer = struct { temps: std.ArrayList([]const u8) = .empty, }; const BooleanBuiltin = struct { span: Span, input: ast.Expr, assume: bool }; - const CallDispatch = union(enum) { done: Value, ordinary: *OrdinaryCall, variant: *VariantConstruction, boolean_builtin: *BooleanBuiltin }; + const ConsumingBuiltin = struct { span: Span, input: ast.Expr, operation: enum { take, free, destroy } }; + const CallDispatch = union(enum) { done: Value, ordinary: *OrdinaryCall, variant: *VariantConstruction, boolean_builtin: *BooleanBuiltin, consuming_builtin: *ConsumingBuiltin }; + + fn finishConsumingBuiltin(l: *Lowerer, c: *ConsumingBuiltin, o: Value) Error!Value { + if (c.operation == .take) { + if (o.ty != .own) return l.fail("E7005", c.input.span, "`own.take` takes an `own`", &.{.{ .name = "found", .value = try l.diagnosticTyText(o.ty) }}); + return l.def("v", o.ty.own.*, try l.fmt("own.take %{s}", .{o.name}), c.span); + } + const free = c.operation == .free; + const ok = if (free) (o.ty == .own or o.ty == .own_array) else o.ty == .region; + if (!ok) return l.fail("E7005", c.input.span, if (free) "`own.free` takes an `own` or `own_array`" else "`region.destroy` takes a region", &.{.{ .name = "found", .value = try l.diagnosticTyText(o.ty) }}); + try l.emit(try l.fmt("{s} %{s}", .{ if (free) "own.free" else "region.destroy", o.name }), c.span); + return .{ .name = "", .ty = .void }; + } 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)) { @@ -2406,6 +2432,7 @@ const Lowerer = struct { .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 }), + .consuming_builtin => |c| l.operandExprPrepared(e, null, .{ .consuming_builtin = c }), }; } @@ -2446,19 +2473,13 @@ const Lowerer = struct { if (pathOf(callee)) |p| { if (std.mem.eql(u8, p, "slice.copy")) return .{ .done = try l.sliceCopy(e, args) }; if (l.fallible(p) != null) return l.invalid(.invalid_operation, e.span, "a fallible operation is handled with `match` over its outcomes or with `or trap`", &.{.{ .name = "operation", .value = p }}); - if (std.mem.eql(u8, p, "own.take")) { - if (args.len != 1) return l.fail("E7005", e.span, "`own.take` takes one owner", &.{}); - const o = try l.consuming(args[0], null); - if (o.ty != .own) return l.fail("E7005", args[0].span, "`own.take` takes an `own`", &.{.{ .name = "found", .value = try l.diagnosticTyText(o.ty) }}); - return .{ .done = try l.def("v", o.ty.own.*, try l.fmt("own.take %{s}", .{o.name}), e.span) }; - } - if (std.mem.eql(u8, p, "own.free") or std.mem.eql(u8, p, "region.destroy")) { - if (args.len != 1) return l.fail("E7005", e.span, "this operation takes one linear value", &.{}); - const o = try l.consuming(args[0], null); - const ok = if (std.mem.eql(u8, p, "own.free")) (o.ty == .own or o.ty == .own_array) else o.ty == .region; - if (!ok) return l.fail("E7005", args[0].span, if (std.mem.eql(u8, p, "own.free")) "`own.free` takes an `own` or `own_array`" else "`region.destroy` takes a region", &.{.{ .name = "found", .value = try l.diagnosticTyText(o.ty) }}); - try l.emit(try l.fmt("{s} %{s}", .{ p, o.name }), e.span); - return .{ .done = .{ .name = "", .ty = .void } }; + const take = std.mem.eql(u8, p, "own.take"); + const free = std.mem.eql(u8, p, "own.free"); + if (take or free or std.mem.eql(u8, p, "region.destroy")) { + if (args.len != 1) return l.fail("E7005", e.span, if (take) "`own.take` takes one owner" else "this operation takes one linear value", &.{}); + const state = try l.arena.create(ConsumingBuiltin); + state.* = .{ .span = e.span, .input = args[0], .operation = if (take) .take else if (free) .free else .destroy }; + return .{ .consuming_builtin = state }; } if (std.mem.eql(u8, p, "region.reset")) { if (args.len != 1 or args[0].kind != .name) return l.fail("E7005", e.span, "`region.reset` takes the region by name", &.{}); @@ -8416,3 +8437,176 @@ test "boolean builtin values preserve aggregate and field consumer failures" { for ([_]?Ty{ null, .bool, .{ .int = "u8" } }) |want| try expectFieldMatches(a, parsed.ok, e, want); }; } + +fn consumingTestLowerer(a: Allocator, m: ast.Module, span: Span) !Lowerer { + var l = try fieldTestLowerer(a, m, span); + const integer: Ty = .{ .int = "i64" }; + const owner = try l.wrap(.own, integer); + const owner_array = try l.wrap(.own_array, .{ .int = "u8" }); + try l.bindings.appendSlice(a, &.{ + .{ .name = "r", .value = "region_input", .mutable = false, .ty = .region }, + .{ .name = "oa", .value = "array_owner", .mutable = false, .ty = owner_array }, + .{ .name = "oo", .value = "nested_owner", .mutable = false, .ty = try l.wrap(.own, owner) }, + .{ .name = "ob", .value = "borrow_owner", .mutable = false, .ty = try l.wrap(.own, try l.wrap(.ref, integer)) }, + .{ .name = "obool", .value = "boolean_owner", .mutable = false, .ty = try l.wrap(.own, .bool) }, + .{ .name = "aggregate_owner", .value = "aggregate_owner", .mutable = false, .ty = try l.wrap(.own, l.enumOrStruct("Owner", span).?) }, + }); + try l.sigs.put(a, "keep", .{ .params = try a.dupe(Ty, &.{owner}), .ret = owner, .air_name = "keep", .display_name = "keep" }); + try l.sigs.put(a, "keep_region", .{ .params = try a.dupe(Ty, &.{.region}), .ret = .region, .air_name = "keep_region", .display_name = "keep_region" }); + return l; +} + +fn expectConsumingMatches(a: Allocator, m: ast.Module, e: ast.Expr, want: ?Ty) !void { + var old = try consumingTestLowerer(a, m, e.span); + var current = try consumingTestLowerer(a, m, e.span); + const expected = ReferenceOperands.expr(&old, e, want); + const actual = current.expr(e, want); + if (expected) |v| { + const result = try actual; + try std.testing.expectEqualStrings(v.name, result.name); + try std.testing.expect(v.ty.eql(result.ty)); + } else |err| try std.testing.expectError(err, actual); + try std.testing.expectEqualDeep(old.problem, current.problem); + try std.testing.expectEqualDeep(old.unimpl, current.unimpl); + try std.testing.expectEqualDeep(old.blocks.items, current.blocks.items); + try std.testing.expectEqualDeep(old.allocs.items, current.allocs.items); + try std.testing.expectEqualDeep(old.constants.items, current.constants.items); + try std.testing.expectEqualDeep(old.bindings.items, current.bindings.items); + try std.testing.expectEqual(old.counter, current.counter); + try std.testing.expectEqual(old.cur, current.cur); + try std.testing.expectEqualDeep(old.uses, current.uses); + try std.testing.expectEqual(old.linear_enabled, current.linear_enabled); + try std.testing.expectEqual(old.in_constant, current.in_constant); + try std.testing.expectEqual(old.borrow_parents.count(), current.borrow_parents.count()); + var parents = old.borrow_parents.iterator(); + while (parents.next()) |item| try std.testing.expectEqualStrings(item.value_ptr.*, current.borrow_parents.get(item.key_ptr.*).?); +} + +test "consuming builtin continuations match former moves types aggregates CFG and errors" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const expressions = [_][]const u8{ + "own.take(move o)", "own.take(o)", "own.take(move oo)", "own.take(move ob)", + "own.take(move oa)", "own.free(move oa)", "own.free(oa)", "own.free(move oo)", + "own.free(move o)", "own.free(o)", "region.destroy(move r)", "region.destroy(r)", + "own.take(keep(move o))", "own.free(keep(move o))", "region.destroy(keep_region(move r))", "own.take()", + "own.free()", "region.destroy()", "own.take(unknown, true)", "own.free(unknown, false)", + "region.destroy(unknown, false)", "own.take(unknown)", "own.free(unknown)", "region.destroy(unknown)", + "own.take(1i64)", "own.free(true)", "region.destroy(false and bool_id(true))", "own.free(ref n)", + "own.take(sc)", "own.free(move n)", "own.take(stop(b\"xy\"))", "region.destroy(void_call(b\"xy\"))", + "own.take(Box { n: 1i64 }.n)", "own.free([1i64; 2])", "own.free(assert(true))", "own.free(own.take(move oo))", + "own.take(own.take(move oo))", "own.take(move aggregate_owner)", "own.free(move aggregate_owner)", "own.take(move obool)", + }; + const forms = [_][]const u8{ "{s}", "id({s})", "own.take({s})", "own.free({s})", "region.destroy({s})", "not ({s})", "({s}) as! u8", "[{s}]", "Box {{ n: {s} }}.n", "Choice::some({s})", "({s}) == 1i64", "1i64 == ({s})", "true and ({s})", "({s}) or false", "- ({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}; }}", .{ fieldTestDeclarations, 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" } }) |want| try expectConsumingMatches(a, parsed.ok, e, want); + }; +} + +fn consumingTestCallee(a: Allocator, name: []const u8) !*const ast.Expr { + const dot = std.mem.indexOfScalar(u8, name, '.').?; + const root = try a.create(ast.Expr); + root.* = .{ .span = unaryTestSpan(70_001), .kind = .{ .name = name[0..dot] } }; + const callee = try a.create(ast.Expr); + callee.* = .{ .span = unaryTestSpan(70_002), .kind = .{ .field = .{ .e = root, .name = name[dot + 1 ..] } } }; + return callee; +} + +test "deep consuming builtin operands and rejected nested operations avoid native descent" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const m = (try parse_mod.parse(a, fieldTestDeclarations)).ok; + const count = 32_768; + for ([_][]const u8{ "own.take", "own.free", "region.destroy" }) |operation| { + const region = std.mem.eql(u8, operation, "region.destroy"); + const callee = try consumingTestCallee(a, operation); + const keep: ast.Expr = .{ .span = unaryTestSpan(70_003), .kind = .{ .name = if (region) "keep_region" else "keep" } }; + var e: ast.Expr = .{ .span = unaryTestSpan(90_000), .kind = .{ .move = if (region) "r" else "o" } }; + for (0..count) |i| { + const args = try a.alloc(ast.Expr, 1); + args[0] = e; + e = .{ .span = unaryTestSpan(@intCast(i + 1)), .kind = .{ .call = .{ .callee = &keep, .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 = callee, .type_arg = null, .args = args } } }; + var l = try consumingTestLowerer(a, m, span); + const initial_counter = l.counter; + const v = try l.expr(root, null); + const take = std.mem.eql(u8, operation, "own.take"); + try std.testing.expect(if (take) v.ty.eql(.{ .int = "i64" }) else v.ty == .void); + const insts = l.blocks.items[0].insts.items; + try std.testing.expectEqual(count + 1, insts.len); + try std.testing.expectEqual(initial_counter + count + @intFromBool(take), l.counter); + for (0..count) |i| try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(@intCast(i + 1))), insts[i].span); + try std.testing.expect(std.mem.indexOf(u8, insts[count].text, operation) != null); + try std.testing.expectEqualDeep(@as(?Span, span), insts[count].span); + + e = .{ .span = unaryTestSpan(90_000), .kind = .{ .move = if (region) "r" else "o" } }; + for (0..count) |i| { + const inputs = try a.alloc(ast.Expr, 1); + inputs[0] = e; + e = .{ .span = unaryTestSpan(@intCast(i + 1)), .kind = .{ .call = .{ .callee = callee, .type_arg = null, .args = inputs } } }; + 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 = &keep, .type_arg = null, .args = input } } }; + } + } + l = try consumingTestLowerer(a, m, e.span); + 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); + try std.testing.expectEqual(@as(usize, 1), l.blocks.items[0].insts.items.len); + try std.testing.expectEqual(@as(usize, @intFromBool(take)), l.counter); + try std.testing.expect(l.unimpl == null); + } +} + +test "public consuming builtin lowering propagates OOM on success and rejection" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const programs = [_][]const u8{ + "module oom\nfn keep(o: own) -> own effects [] { return move o; }\nfn keep_region(r: region) -> region effects [] { return move r; }\nfn get(o: own) -> i64 effects [mem.alloc] { return own.take(keep(move o)); }\nfn release(o: own) -> void effects [mem.alloc] { own.free(keep(move o)); }\nfn kill(r: region) -> void effects [mem.alloc] { region.destroy(keep_region(move r)); }\n", + "module oom\nfn bad(o: own) -> void effects [] { own.free(o); }\n", + "module oom\nfn bad() -> void effects [] { own.take(1i64); }\n", + "module oom\nfn bad() -> void effects [] { region.destroy(); }\n", + }; + for (programs, 0..) |program, program_index| { + const parsed = try parse_mod.parse(fixture.allocator(), try std.fmt.allocPrint(fixture.allocator(), "{s}fn main() -> i64 effects [] {{ return 42i64; }}\n", .{program})); + try std.testing.expect(parsed == .ok); + const baseline = try lower(fixture.allocator(), parsed.ok); + if (program_index == 0) { + try std.testing.expect(baseline == .ok); + } else { + try std.testing.expect(baseline == .err); + try std.testing.expectEqualStrings(if (program_index == 1) "E7003" else "E7005", baseline.err.code); + } + 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; + } + } + } + } +} diff --git a/tests/hosted/source_expression_depth.py b/tests/hosted/source_expression_depth.py index 2f8536c..5cae0af 100644 --- a/tests/hosted/source_expression_depth.py +++ b/tests/hosted/source_expression_depth.py @@ -734,6 +734,71 @@ with tempfile.TemporaryDirectory(prefix='aji-expression-depth-') as directory: 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) + # Block/control callbacks remain native. Their existing shallow/deeper # syntax must retain its capacity while expression dispatch is moved out # of the native stack, including explicit-return callback re-entry.