diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index 18871ee..9fff20e 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -539,6 +539,8 @@ The [generic transformation increment](source-expression-depth-audit.md#generic- The [parser constructor-path increment](source-expression-depth-audit.md#parser-qualified-constructor-paths) repairs Parser.exprPath independently of generic/lowering paths. Frozen baseline probes confirm enum and struct constructor aborts at 16,384 fields; the repaired CLI returns exact E7002 through 65,536. Named-root classification, spelling, type arguments, spans, syntax errors and host OOM propagation are preserved, with one complete string allocation. Q-061 remains open for the confirmed parenthesized/mixed-call parser failures and the remaining lowering/liveness inventory; no new acceptance limit or external review is claimed. -The [shared expression parser increment](source-expression-depth-audit.md#shared-expression-parser-continuations) removes native re-entry through grouping, call arguments, arrays, index bounds and struct fields, sharing binary/cast/unary/postfix/primary continuations. Token/AST/spans, grammar/error priority and scoped advice remain unchanged; host OOM propagates without diagnostics or partial AST. Reused work storage and stable driver frames retain caller-arena lifetime. Block/control callbacks still recurse outside the large dispatch frame; their bounded regression probes pass, without an arbitrary-depth claim. Grouped programs check through 65,536; mixed calls format through 65,536 but now abort in lowerer `call` at 1,024. Q-061 remains open for that confirmed path and remaining control/liveness traversal; no new limit or external review is claimed. +The [shared expression parser increment](source-expression-depth-audit.md#shared-expression-parser-continuations) removes native re-entry through grouping, call arguments, arrays, index bounds and struct fields, sharing binary/cast/unary/postfix/primary continuations. Token/AST/spans, grammar/error priority and scoped advice remain unchanged; host OOM propagates without diagnostics or partial AST. Reused work storage and stable driver frames retain caller-arena lifetime. Block/control callbacks still recurse outside the large dispatch frame; their bounded regression probes pass, without an arbitrary-depth claim. Grouped programs check through 65,536; mixed calls format through 65,536 but checking at that checkpoint still aborted in lowerer `call` at 1,024. Q-061 remains open for that confirmed path and remaining control/liveness traversal; no new limit or external review is claimed. Audit these paths separately with finite public/generated source inputs before claiming whole-frontend bounded native-stack processing. Prefer explicit continuations preserving existing syntax, evaluation/query order, diagnostics and OOM behavior. A new depth rejection requires a normative decision; Q-059's type-traversal resolution does not authorize one. + +The [ordinary-call increment](source-expression-depth-audit.md#ordinary-call-argument-continuations) shares call arguments with scalar continuations, preserving signature/error priority, left-to-right consumption, loans, retained parents, CFG and host OOM behavior. Stable arena-owned states retain bounded builtin/control regression capacity. Build/units/format checks, exact ordinary conformance coverage and call-related CLI suites pass. A separate alternating struct/field program still aborts at 1,024 before and after; builtin/variant/place, aggregate/control and remaining liveness/read/assignment paths keep Q-061 open. No semantic or depth limit changes and no fresh external review are claimed. diff --git a/docs/design/source-expression-depth-audit.md b/docs/design/source-expression-depth-audit.md index 9fc573b..885e157 100644 --- a/docs/design/source-expression-depth-audit.md +++ b/docs/design/source-expression-depth-audit.md @@ -473,7 +473,7 @@ empty work, restored depth/advice/call scopes and no diagnostic; persistent backing failures through public parse check arena cleanup and no partial AST. Final probes accept checks at 65,536 grouped levels and formatting at 65,536 -mixed-call levels. Full mixed-call checking still aborts at 1,024, now in lowerer +mixed-call levels. At this checkpoint mixed-call checking still aborted at 1,024, in lowerer `call` rather than parsing (`expression-parser-final-probes.json` and `expression-parser-*.after.final.*.stdout/.stderr`). Permanent CLI tests separate full accepted grouped/scalar programs with exact AIR/fuel from syntax-only @@ -494,6 +494,52 @@ ownership/runtime rule changes. Q-061 remains open for block/control parsing, non-scalar lowering and the remaining liveness/read/assignment inventory. This increment has no external review yet. +## Ordinary-call argument continuations + +Ordinary local/module/std/generic call arguments now suspend in the scalar +expression driver. Callee normalization, signature/arity and named-`from` +checks still precede arguments; values are consumed left to right, exact type +checks precede the next argument, and temporary loans end after `call` as +before. Returned-borrow provenance, void/never exits, generated names, spans +and short-circuit CFG are unchanged (spec 15 §5, §19). + +Stable call states and worklist backing belong to the caller's arena; they +remain until that arena is destroyed, including after an error. Keeping only +state pointers in continuations avoids large native frame copies. An initial +by-value implementation regressed nested `assert` diagnostics at 256 levels; +final before/after probes retain identical outputs for `assert`, blocks and +`if` at 16/64/256 (`call-continuations-callback-pointer.json`). This is bounded +regression coverage, not arbitrary builtin/control depth safety. + +The copied shallow recursive call/scalar oracle compares emission, CFG, +diagnostic priority, transfers, temporary cleanup and retained parents. Place, +byte-materialization and builtin helpers are shared, outside its independence. +Separate 32,768-level direct/mixed call tests and recovering direct/public plus +persistent backing-OOM tests pass. Host OOM remains an error union, without a +source diagnostic or public partial AIR; output-arena backing is freed. + +Build/unit/format checks and all 1,793 ordinary conformance cases pass with +terminal exit 0 and exact unique coverage (`call-continuations-conformance` +artifacts). Borrow-return/array-argument/generic/static-function/non-value/ +independent-error CLI suites pass 133/85/42/25/635/234 checks. Frozen old/new +CLIs retain exact exit/stdout/stderr for 1,423 public source checks and 506 +accepted lowerings (`call-continuations-cli-compatibility-pointer.json`). + +Full direct/mixed arithmetic/negation and generic call checks, lowerings and +formatting now accept through 65,536 levels; bounded runs retain exact AIR +values and independently counted fuel. All 262 focused call-depth CLI checks +pass against the frozen final binary (`call-continuations-focused-depth.log`), +including exact innermost E7002 records across check/lower/run/report/explore. +The former 1,024-level mixed-call +abort is repaired. A separate alternating +`Box { n: expression }.n` probe still aborts at 1,024 before and after this +increment, while 16 levels accept (`call-followup-field-struct-probes.json`). +Builtin/variant/place callbacks, aggregate/control lowering and remaining +liveness/read/assignment walks are further Q-061 work. No normative, language/ +AIR format, feature, diagnostic, bundle, limit or ownership/runtime change; +Q-060 full per-step GC validation and Phase 6 exit gates remain separate. +This increment has no external review yet. + ## Remaining work Follow-up checks accept 16 parenthesized/mixed-call levels but abort @@ -508,7 +554,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: calls, fields/indices/places, arrays/structs, if/match/arms and blocks/statements | Mixed scalar/call source now has a confirmed native abort in `call` at 1,024 after parsing succeeds. 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-call argument descent is repaired above. Alternating struct/field lowering still aborts 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 be88039..9bdab6f 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -632,7 +632,28 @@ formatter passes 6,078 checks; frozen old/new public checks/lowerings remain exact (1,423/506). Grouped source checks reach 65,536; mixed-call formatting reaches 65,536. Block/if regression probes preserve accepted baseline output, including 256 levels; explicit-return forms improve from baseline aborts to formatting -at 256. These are bounded probes, not a whole-parser depth guarantee. Full -mixed-call checking now confirms a lowerer `call` abort at 1,024; control/block +at 256. These are bounded probes, not a whole-parser depth guarantee. At this +checkpoint, full mixed-call checking confirmed a lowerer `call` abort at 1,024; control/block parsing, remaining expression/statement/liveness walks, Q-060 validation and Phase 6 exit gates remain open. No external review covers this increment yet. + +### Ordinary-call depth increment + +The [Q-061 ordinary-call increment](../design/source-expression-depth-audit.md#ordinary-call-argument-continuations) +shares argument continuations with scalar operands. Signature/arity/origin +checks, left-to-right consumption, exact argument checks, temporary endings, +retained parents and instruction/span/CFG order are preserved. Stable states +live in the caller's arena; recovering/persistent OOM remains a host error and +arena backing is freed. No semantic/bundle/feature/code/limit changes. + +Independent shallow/deep call and OOM tests, build/units/format checks and all +1,793 ordinary conformance cases with exact coverage pass. Call-related CLI +suites pass 133/85/42/25/635/234 checks. Frozen public checks/lowerings remain +exact (1,423/506). Bounded native `assert`/block/if probes +retain exact baseline outputs through 256; this does not claim whole-callback +safety. Direct/mixed/generic call checks and lowerings now reach 65,536 with +exact bounded values/fuel; 262 focused depth CLI checks pass. The mixed-call +abort at 1,024 is repaired, while a separate alternating +struct/field program still aborts there in both binaries. Remaining Q-061 +callbacks/walks, Q-060 validation and Phase 6 exit gates remain open. No fresh +external review covers this increment. diff --git a/src/frontend/lower.zig b/src/frontend/lower.zig index e77e156..6e67040 100644 --- a/src/frontend/lower.zig +++ b/src/frontend/lower.zig @@ -2032,7 +2032,10 @@ const Lowerer = struct { }, .bytes => return l.invalid(.invalid_literal, e.span, "a byte string is an array in storage: bind it with `let`/`ref`, or pass it where a slice is expected", &.{}), .borrow => return l.invalid(.invalid_borrow, e.span, "`ref`/`mut` here: borrows are bound with `ref name = place;` / `mut name = place;` or passed as arguments", &.{}), - .call => |x| return l.call(e, x.callee.*, x.args, false), + .call => |x| return switch (try l.prepareCall(e, x.callee.*, x.args, false)) { + .done => |v| v, + .ordinary => |c| l.operandExprPrepared(e, null, c), + }, .if_expr => |x| return l.ifExpr(e.span, x.*, want), .block => |b| { const v = try l.blockBodyWant(b.*, want); @@ -2055,22 +2058,45 @@ const Lowerer = struct { } } - // Scalar unary and binary operands share one worklist so alternating - // operator trees do not re-enter the native stack through expr. + // Scalar operands and ordinary call arguments share one worklist so + // alternating operator/call trees do not re-enter the native stack. fn operandExpr(l: *Lowerer, initial: ast.Expr, initial_want: ?Ty) Error!Value { + return l.operandExprPrepared(initial, initial_want, null); + } + + fn operandExprPrepared(l: *Lowerer, initial: ast.Expr, initial_want: ?Ty, initial_call: ?*OrdinaryCall) Error!Value { const Frame = union(enum) { unary: struct { e: ast.Expr, ty: Ty = .void, zero: ?Value = null }, binary_left: struct { e: ast.Expr, ty: Ty }, binary_right: struct { e: ast.Expr, ty: Ty, left: Value }, boolean_left: ast.Expr, boolean_right: struct { e: ast.Expr, join: usize, name: []const u8 }, + call_argument: *OrdinaryCall, }; var pending: std.ArrayList(Frame) = .empty; defer pending.deinit(l.arena); var e = initial; var want = initial_want; + var prepared_call = initial_call; evaluate: while (true) { var v: Value = while (true) { + if (prepared_call) |c| { + prepared_call = null; + if (c.index == c.args.len) break try l.finishCall(c); + const a = c.args[c.index]; + const pt = c.sig.params[c.index]; + if (a.kind == .borrow or a.kind == .bytes) { + const argument_value = try l.argument(a, pt, &c.temps); + try l.collectCallArgument(c, argument_value); + prepared_call = c; + continue; + } + try l.checkConsumingName(a); + try pending.append(l.arena, .{ .call_argument = c }); + e = a; + want = pt; + continue; + } switch (e.kind) { .not, .deref => |x| { try pending.append(l.arena, .{ .unary = .{ .e = e } }); @@ -2120,6 +2146,10 @@ const Lowerer = struct { } e = x.l.*; }, + .call => |x| switch (try l.prepareCall(e, x.callee.*, x.args, false)) { + .done => |v| break v, + .ordinary => |c| prepared_call = c, + }, else => break try l.expr(e, want), } }; @@ -2197,6 +2227,13 @@ const Lowerer = struct { l.cur = frame.join; v = .{ .name = frame.name, .ty = .bool }; }, + .call_argument => |c| { + try l.collectCallArgument(c, v); + prepared_call = c; + e = c.e; + want = null; + continue :evaluate; + }, }; return v; } @@ -2246,125 +2283,156 @@ const Lowerer = struct { return l.def(if (cmp) "cmp" else "t", if (cmp) .bool else ty, try l.fmt("{s} %{s}, %{s}", .{ text, lv.name, rv.name }), e.span); } + const OrdinaryCall = struct { + e: ast.Expr, + callee: ast.Expr, + args: []const ast.Expr, + sig: FnSig, + index: usize = 0, + parent: ?[]const u8 = null, + names: std.ArrayList(u8) = .empty, + temps: std.ArrayList([]const u8) = .empty, + }; + const CallDispatch = union(enum) { done: Value, ordinary: *OrdinaryCall }; + fn call(l: *Lowerer, e: ast.Expr, callee: ast.Expr, args: []const ast.Expr, borrow_allowed: bool) Error!Value { - if (pathOf(callee)) |p| { - if (std.mem.eql(u8, p, "buffer.len") or std.mem.eql(u8, p, "buffer.capacity")) { - if (args.len != 1) return l.fail("E7005", e.span, "buffer metadata read takes one named borrow", &.{}); - const b = try l.bufferBorrow(args[0], false); - return l.def("size", .{ .int = "usize" }, try l.fmt("{s} %{s}", .{ p, b.name }), e.span); - } - if (std.mem.eql(u8, p, "buffer.view")) return l.invalid(.invalid_borrow, e.span, "bind a buffer view with ref/mut name = buffer.view(borrow)", &.{}); - } - if (pathOf(callee)) |path| if (std.mem.eql(u8, path, "value.swap")) { - if (args.len != 2 or args[0].kind != .borrow or !args[0].kind.borrow.mutable) return l.invalid(.invalid_operation, e.span, "value.swap requires mut place and replacement", &.{}); - const b = args[0].kind.borrow; - const p = try l.placeBorrow(b.place.*, true, false, e.span); - if (p.v.ty != .mut) return l.fail("E7005", e.span, "value.swap requires mut", &.{}); - const ty = p.v.ty.inner().?; - const replacement = try l.consuming(args[1], ty); - try l.checkOperandTy(args[1].span, replacement.ty, ty); - const result = try l.def("old", ty, try l.fmt("value.swap %{s}, %{s}", .{ p.v.name, replacement.name }), e.span); - try l.endNow(p.ends, e.span); - l.linear_enabled = true; - return result; + return switch (try l.prepareCall(e, callee, args, borrow_allowed)) { + .done => |v| v, + .ordinary => |c| l.operandExprPrepared(e, null, c), }; - if (callee.kind == .variant) return l.variantValue(e, callee.kind.variant.@"enum", callee.kind.variant.name, args); - if (try l.moduleCall(callee)) |name| { - // Reuse ordinary call typing/borrowing/lowering, including E7002. - const owned_name = try l.arena.dupe(u8, name); - return l.call(e, .{ .span = callee.span, .kind = .{ .name = owned_name } }, args, borrow_allowed); - } - if (pathOf(callee)) |p| { - if (std.mem.eql(u8, p, "slice.copy")) return 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 l.def("v", o.ty.own.*, try l.fmt("own.take %{s}", .{o.name}), e.span); + } + + fn prepareCall(l: *Lowerer, e: ast.Expr, initial_callee: ast.Expr, args: []const ast.Expr, borrow_allowed: bool) Error!CallDispatch { + var callee = initial_callee; + while (true) { + if (pathOf(callee)) |p| { + if (std.mem.eql(u8, p, "buffer.len") or std.mem.eql(u8, p, "buffer.capacity")) { + if (args.len != 1) return l.fail("E7005", e.span, "buffer metadata read takes one named borrow", &.{}); + const b = try l.bufferBorrow(args[0], false); + return .{ .done = try l.def("size", .{ .int = "usize" }, try l.fmt("{s} %{s}", .{ p, b.name }), e.span) }; + } + if (std.mem.eql(u8, p, "buffer.view")) return l.invalid(.invalid_borrow, e.span, "bind a buffer view with ref/mut name = buffer.view(borrow)", &.{}); } - 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 .{ .name = "", .ty = .void }; + if (pathOf(callee)) |path| if (std.mem.eql(u8, path, "value.swap")) { + if (args.len != 2 or args[0].kind != .borrow or !args[0].kind.borrow.mutable) return l.invalid(.invalid_operation, e.span, "value.swap requires mut place and replacement", &.{}); + const b = args[0].kind.borrow; + const p = try l.placeBorrow(b.place.*, true, false, e.span); + if (p.v.ty != .mut) return l.fail("E7005", e.span, "value.swap requires mut", &.{}); + const ty = p.v.ty.inner().?; + const replacement = try l.consuming(args[1], ty); + try l.checkOperandTy(args[1].span, replacement.ty, ty); + const result = try l.def("old", ty, try l.fmt("value.swap %{s}, %{s}", .{ p.v.name, replacement.name }), e.span); + try l.endNow(p.ends, e.span); + l.linear_enabled = true; + return .{ .done = result }; + }; + if (callee.kind == .variant) return .{ .done = try l.variantValue(e, callee.kind.variant.@"enum", callee.kind.variant.name, args) }; + if (try l.moduleCall(callee)) |name| { + // Reuse ordinary call typing/borrowing/lowering, including E7002. + const owned_name = try l.arena.dupe(u8, name); + callee = .{ .span = callee.span, .kind = .{ .name = owned_name } }; + continue; } - 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", &.{}); - const r = l.lookup(args[0].kind.name) orelse return l.unknown(args[0].span, args[0].kind.name); - if (r.ty != .region) return l.fail("E7005", args[0].span, "`region.reset` takes a region", &.{.{ .name = "found", .value = try l.diagnosticTyText(r.ty) }}); - try l.emit(try l.fmt("region.reset %{s}", .{r.value}), e.span); - return .{ .name = "", .ty = .void }; + 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 } }; + } + 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", &.{}); + const r = l.lookup(args[0].kind.name) orelse return l.unknown(args[0].span, args[0].kind.name); + if (r.ty != .region) return l.fail("E7005", args[0].span, "`region.reset` takes a region", &.{.{ .name = "found", .value = try l.diagnosticTyText(r.ty) }}); + try l.emit(try l.fmt("region.reset %{s}", .{r.value}), e.span); + return .{ .done = .{ .name = "", .ty = .void } }; + } + if (try l.concurrencyCall(e, p, args)) |v| return .{ .done = v }; + if (std.mem.startsWith(u8, p, "atomic.")) return .{ .done = try l.atomicCall(e, p, args) }; + if (authority.intrinsicIndex(p)) |ix| { + const x = authority.intrinsics[ix]; + var temps: std.ArrayList([]const u8) = .empty; + const ops = try l.intrinsicOperands(e, x, args, &temps); + l.uses.insert(.capabilities); + const text = try l.fmt("intrinsic {s}({s})", .{ x.name, ops }); + const v: Value = if (x.results.len == 0) blk: { + try l.emit(text, e.span); + break :blk .{ .name = "", .ty = .void }; + } else try l.def("r", resultTy(x.results[0]), text, e.span); + try l.endNow(temps.items, e.span); + return .{ .done = v }; + } + return l.notYet(callee.span, "this built-in operation (later layers)"); } - if (try l.concurrencyCall(e, p, args)) |v| return v; - if (std.mem.startsWith(u8, p, "atomic.")) return l.atomicCall(e, p, args); - if (authority.intrinsicIndex(p)) |ix| { - const x = authority.intrinsics[ix]; - var temps: std.ArrayList([]const u8) = .empty; - const ops = try l.intrinsicOperands(e, x, args, &temps); - l.uses.insert(.capabilities); - const text = try l.fmt("intrinsic {s}({s})", .{ x.name, ops }); - const v: Value = if (x.results.len == 0) blk: { - try l.emit(text, e.span); - break :blk .{ .name = "", .ty = .void }; - } else try l.def("r", resultTy(x.results[0]), text, e.span); - try l.endNow(temps.items, e.span); - return v; + if (callee.kind == .field and std.mem.eql(u8, callee.kind.field.name, "split_at")) + 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 } }; } - return l.notYet(callee.span, "this built-in operation (later layers)"); + 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 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}) } }); + if (sig.ret.isBorrow() and !borrow_allowed) return l.invalid(.invalid_borrow_return, e.span, "bind a returned borrow with ref/mut name = call(...) first", &.{}); + if (sig.from) |origin| { + const a = args[origin]; + if (a.kind != .name) return l.invalid(.invalid_borrow_return, a.span, "the from argument must be a named borrow; bind it first", &.{}); + const b = l.lookup(a.kind.name) orelse return l.unknown(a.span, a.kind.name); + if (b.kind != .borrow) return l.invalid(.invalid_borrow_return, a.span, "the from argument must be a named borrow; bind it first", &.{}); + } + const state = try l.arena.create(OrdinaryCall); + state.* = .{ .e = e, .callee = callee, .args = args, .sig = sig }; + return .{ .ordinary = state }; } - if (callee.kind == .field and std.mem.eql(u8, callee.kind.field.name, "split_at")) - 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 .{ .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 .{ .name = "", .ty = .void }; - } - 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}) } }); - if (sig.ret.isBorrow() and !borrow_allowed) return l.invalid(.invalid_borrow_return, e.span, "bind a returned borrow with ref/mut name = call(...) first", &.{}); - if (sig.from) |origin| { - const a = args[origin]; - if (a.kind != .name) return l.invalid(.invalid_borrow_return, a.span, "the from argument must be a named borrow; bind it first", &.{}); - const b = l.lookup(a.kind.name) orelse return l.unknown(a.span, a.kind.name); - if (b.kind != .borrow) return l.invalid(.invalid_borrow_return, a.span, "the from argument must be a named borrow; bind it first", &.{}); - } - var parent: ?[]const u8 = null; - var arg_names: std.ArrayList(u8) = .empty; - var temps: std.ArrayList([]const u8) = .empty; - for (args, sig.params, 0..) |a, pt, i| { - const v = try l.argument(a, pt, &temps); - if (sig.from == i) parent = v.name; - try l.checkCallArgumentTy(a, v.ty, pt); - try arg_names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", v.name })); - } - const text = try l.fmt("call @{s}({s})", .{ sig.air_name, arg_names.items }); + } + + fn collectCallArgument(l: *Lowerer, c: *OrdinaryCall, v: Value) Error!void { + const a = c.args[c.index]; + if (c.sig.from == c.index) c.parent = v.name; + try l.checkCallArgumentTy(a, v.ty, c.sig.params[c.index]); + try c.names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (c.index == 0) "" else ", ", v.name })); + c.index += 1; + } + + fn finishCall(l: *Lowerer, c: *const OrdinaryCall) Error!Value { + const sig = c.sig; + const e = c.e; + const name = c.callee.kind.name; + const text = try l.fmt("call @{s}({s})", .{ sig.air_name, c.names.items }); if (sig.ret == .void or sig.ret == .never) { try l.emit(text, e.span); if (sig.ret == .never) { - try l.term("trap", e.span); // `never` returns do not come back + try l.term("trap", e.span); return .{ .name = "", .ty = .never }; } - try l.endNowIfLive(temps.items, e.span); + try l.endNowIfLive(c.temps.items, e.span); return .{ .name = "", .ty = .void }; } - const result = try l.def(if (callee.span.resolved) "generic_call" else if (std.mem.startsWith(u8, name, "std.")) "std_call" else if (std.mem.indexOfScalar(u8, name, '.') != null) "module_call" else name, sig.ret, text, e.span); - if (parent) |p| try l.borrow_parents.put(l.arena, result.name, p); - try l.endNowIfLive(temps.items, e.span); + const result = try l.def(if (c.callee.span.resolved) "generic_call" else if (std.mem.startsWith(u8, name, "std.")) "std_call" else if (std.mem.indexOfScalar(u8, name, '.') != null) "module_call" else name, sig.ret, text, e.span); + if (c.parent) |parent| try l.borrow_parents.put(l.arena, result.name, parent); + try l.endNowIfLive(c.temps.items, e.span); return result; } @@ -2766,12 +2834,16 @@ const Lowerer = struct { /// An operand that consumes its value: a named linear value must be /// written `move x` (spec 15 §5). Use after move, double consumption and /// leaks are the verifier's (E2001, E2002, E3001, E3002). - fn consuming(l: *Lowerer, e: ast.Expr, want: ?Ty) Error!Value { + fn checkConsumingName(l: *Lowerer, e: ast.Expr) Error!void { if (e.kind == .name) { const b = try l.valueBinding(e.span, e.kind.name); if (l.isLinear(b.ty) and b.kind == .ssa) return l.fail("E7003", e.span, "a linear value is consumed here: write `move` to transfer it, or borrow it with `ref`/`mut`", &.{ .{ .name = "name", .value = e.kind.name }, .{ .name = "suggestion", .value = try l.fmt("move {s}", .{e.kind.name}) } }); } + } + + fn consuming(l: *Lowerer, e: ast.Expr, want: ?Ty) Error!Value { + try l.checkConsumingName(e); return l.expr(e, want); } @@ -5069,6 +5141,146 @@ test "deep callee paths own one complete string and bounded lookup stays flat" { try std.testing.expect(!fail.has_induced_failure); } +// Copied pre-repair ordinary-call descent. Scalar operands recurse through +// ReferenceOperands; builtin, place and byte materialization helpers remain +// shared and are outside this shallow oracle's independence. +const ReferenceCalls = struct { + fn call(l: *Lowerer, e: ast.Expr, callee: ast.Expr, args: []const ast.Expr, borrow_allowed: bool) Error!Value { + if (pathOf(callee)) |p| { + if (std.mem.eql(u8, p, "buffer.len") or std.mem.eql(u8, p, "buffer.capacity")) { + if (args.len != 1) return l.fail("E7005", e.span, "buffer metadata read takes one named borrow", &.{}); + const b = try l.bufferBorrow(args[0], false); + return l.def("size", .{ .int = "usize" }, try l.fmt("{s} %{s}", .{ p, b.name }), e.span); + } + if (std.mem.eql(u8, p, "buffer.view")) return l.invalid(.invalid_borrow, e.span, "bind a buffer view with ref/mut name = buffer.view(borrow)", &.{}); + } + if (pathOf(callee)) |path| if (std.mem.eql(u8, path, "value.swap")) { + if (args.len != 2 or args[0].kind != .borrow or !args[0].kind.borrow.mutable) return l.invalid(.invalid_operation, e.span, "value.swap requires mut place and replacement", &.{}); + const b = args[0].kind.borrow; + const p = try l.placeBorrow(b.place.*, true, false, e.span); + if (p.v.ty != .mut) return l.fail("E7005", e.span, "value.swap requires mut", &.{}); + const ty = p.v.ty.inner().?; + const replacement = try consuming(l, args[1], ty); + try l.checkOperandTy(args[1].span, replacement.ty, ty); + const result = try l.def("old", ty, try l.fmt("value.swap %{s}, %{s}", .{ p.v.name, replacement.name }), e.span); + try l.endNow(p.ends, e.span); + l.linear_enabled = true; + return result; + }; + if (callee.kind == .variant) return l.variantValue(e, callee.kind.variant.@"enum", callee.kind.variant.name, args); + if (try l.moduleCall(callee)) |name| { + // Reuse ordinary call typing/borrowing/lowering, including E7002. + const owned_name = try l.arena.dupe(u8, name); + return call(l, e, .{ .span = callee.span, .kind = .{ .name = owned_name } }, args, borrow_allowed); + } + if (pathOf(callee)) |p| { + if (std.mem.eql(u8, p, "slice.copy")) return 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 consuming(l, 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 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 consuming(l, 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 .{ .name = "", .ty = .void }; + } + 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", &.{}); + const r = l.lookup(args[0].kind.name) orelse return l.unknown(args[0].span, args[0].kind.name); + if (r.ty != .region) return l.fail("E7005", args[0].span, "`region.reset` takes a region", &.{.{ .name = "found", .value = try l.diagnosticTyText(r.ty) }}); + try l.emit(try l.fmt("region.reset %{s}", .{r.value}), e.span); + return .{ .name = "", .ty = .void }; + } + if (try l.concurrencyCall(e, p, args)) |v| return v; + if (std.mem.startsWith(u8, p, "atomic.")) return l.atomicCall(e, p, args); + if (authority.intrinsicIndex(p)) |ix| { + const x = authority.intrinsics[ix]; + var temps: std.ArrayList([]const u8) = .empty; + const ops = try l.intrinsicOperands(e, x, args, &temps); + l.uses.insert(.capabilities); + const text = try l.fmt("intrinsic {s}({s})", .{ x.name, ops }); + const v: Value = if (x.results.len == 0) blk: { + try l.emit(text, e.span); + break :blk .{ .name = "", .ty = .void }; + } else try l.def("r", Lowerer.resultTy(x.results[0]), text, e.span); + try l.endNow(temps.items, e.span); + return v; + } + return l.notYet(callee.span, "this built-in operation (later layers)"); + } + if (callee.kind == .field and std.mem.eql(u8, callee.kind.field.name, "split_at")) + 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 ReferenceOperands.expr(l, 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 .{ .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 ReferenceOperands.expr(l, 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 .{ .name = "", .ty = .void }; + } + 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}) } }); + if (sig.ret.isBorrow() and !borrow_allowed) return l.invalid(.invalid_borrow_return, e.span, "bind a returned borrow with ref/mut name = call(...) first", &.{}); + if (sig.from) |origin| { + const a = args[origin]; + if (a.kind != .name) return l.invalid(.invalid_borrow_return, a.span, "the from argument must be a named borrow; bind it first", &.{}); + const b = l.lookup(a.kind.name) orelse return l.unknown(a.span, a.kind.name); + if (b.kind != .borrow) return l.invalid(.invalid_borrow_return, a.span, "the from argument must be a named borrow; bind it first", &.{}); + } + var parent: ?[]const u8 = null; + var arg_names: std.ArrayList(u8) = .empty; + var temps: std.ArrayList([]const u8) = .empty; + for (args, sig.params, 0..) |a, pt, i| { + const v = try argument(l, a, pt, &temps); + if (sig.from == i) parent = v.name; + try l.checkCallArgumentTy(a, v.ty, pt); + try arg_names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", v.name })); + } + const text = try l.fmt("call @{s}({s})", .{ sig.air_name, arg_names.items }); + if (sig.ret == .void or sig.ret == .never) { + try l.emit(text, e.span); + if (sig.ret == .never) { + try l.term("trap", e.span); // `never` returns do not come back + return .{ .name = "", .ty = .never }; + } + try l.endNowIfLive(temps.items, e.span); + return .{ .name = "", .ty = .void }; + } + const result = try l.def(if (callee.span.resolved) "generic_call" else if (std.mem.startsWith(u8, name, "std.")) "std_call" else if (std.mem.indexOfScalar(u8, name, '.') != null) "module_call" else name, sig.ret, text, e.span); + if (parent) |p| try l.borrow_parents.put(l.arena, result.name, p); + try l.endNowIfLive(temps.items, e.span); + return result; + } + + fn argument(l: *Lowerer, e: ast.Expr, want: ?Ty, temps: *std.ArrayList([]const u8)) Error!Value { + if (e.kind == .borrow or e.kind == .bytes) return l.argument(e, want, temps); + return consuming(l, e, want); + } + fn consuming(l: *Lowerer, e: ast.Expr, want: ?Ty) Error!Value { + if (e.kind == .name) { + const b = try l.valueBinding(e.span, e.kind.name); + if (l.isLinear(b.ty) and b.kind == .ssa) + return l.fail("E7003", e.span, "a linear value is consumed here: write `move` to transfer it, or borrow it with `ref`/`mut`", &.{ .{ .name = "name", .value = e.kind.name }, .{ .name = "suggestion", .value = try l.fmt("move {s}", .{e.kind.name}) } }); + } + return ReferenceOperands.expr(l, e, want); + } +}; + // Independent pre-repair unary/binary expression derivation. Other leaves // share expression handlers; this oracle is only for shallow operand trees. const ReferenceOperands = struct { @@ -5123,6 +5335,7 @@ const ReferenceOperands = struct { }; return l.def("cast", to, try l.fmt("cast.{s}.{s} %{s}", .{ mode, to.int, v.name }), e.span); }, + .call => |x| return ReferenceCalls.call(l, e, x.callee.*, x.args, false), .binary => |x| return binary(l, e, x.op, x.l.*, x.r.*, want), else => return l.expr(e, want), } @@ -7035,6 +7248,7 @@ test "public source lowering propagates each recovering allocation failure" { "module oom\nfn main() -> i64 effects [] { let n = 1; return - (n + 2i64); }\n", "module oom\nstruct S { items: [u8; 7] }\nfn main() -> usize effects [] { let s: S = S { items: [1u8; 7] }; return s.items.len; }\n", "module oom\nfn worker(x: i64) -> i64 effects [] { return - x; }\nfn main() -> i64 effects [] { let n = 1; return worker(n + 1i64); }\n", + "module oom\nfn id(x: i64) -> i64 effects [] { return x; }\nfn read(p: ref) -> i64 effects [] { return *p; }\nfn bytes(s: slice) -> i64 effects [] { return s.len as! i64; }\nfn pair(x: i64, y: i64) -> i64 effects [] { return x + y; }\nfn main() -> i64 effects [] { var n: i64 = 1i64; return pair(id(read(ref n)), id(bytes(b\"xy\"))); }\n", }; for (sources) |source| { var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); @@ -7062,3 +7276,191 @@ test "public source lowering propagates each recovering allocation failure" { } } } + +fn callTestLowerer(a: Allocator, span: Span) !Lowerer { + var l: Lowerer = .{ .arena = a, .m = .{ .name = "calls", .types = &.{}, .functions = &.{} }, .in_constant = 7 }; + const integer: Ty = .{ .int = "i64" }; + const byte: Ty = .{ .int = "u8" }; + const reference = try l.wrap(.ref, integer); + const owner = try l.wrap(.own, integer); + const array = try l.arrayOf(byte, 2); + const names = [_][]const u8{ "id", "pair", "bool_id", "read", "bytes", "array", "take", "retained", "void_call", "stop", "ns.id", "std.test.id" }; + const sigs = [_]FnSig{ + .{ .params = &.{integer}, .ret = integer, .air_name = "id", .display_name = "id" }, + .{ .params = &.{ integer, integer }, .ret = integer, .air_name = "pair", .display_name = "pair" }, + .{ .params = &.{.bool}, .ret = .bool, .air_name = "bool_id", .display_name = "bool_id" }, + .{ .params = &.{reference}, .ret = integer, .air_name = "read", .display_name = "read" }, + .{ .params = &.{try l.wrap(.slice, byte)}, .ret = integer, .air_name = "bytes", .display_name = "bytes" }, + .{ .params = &.{try l.wrap(.ref, array)}, .ret = integer, .air_name = "array", .display_name = "array" }, + .{ .params = &.{owner}, .ret = integer, .air_name = "take", .display_name = "take" }, + .{ .params = &.{reference}, .ret = reference, .from = 0, .air_name = "retained", .display_name = "retained" }, + .{ .params = &.{try l.wrap(.slice, byte)}, .ret = .void, .air_name = "void_call", .display_name = "void_call" }, + .{ .params = &.{try l.wrap(.slice, byte)}, .ret = .never, .air_name = "stop", .display_name = "stop" }, + .{ .params = &.{integer}, .ret = integer, .air_name = "ns__id", .display_name = "ns.id" }, + .{ .params = &.{integer}, .ret = integer, .air_name = "std__id", .display_name = "std.test.id" }, + }; + for (names, sigs) |name, sig| { + var owned = sig; + owned.params = try a.dupe(Ty, sig.params); + try l.sigs.put(a, name, owned); + } + try l.bindings.appendSlice(a, &.{ + .{ .name = "n", .value = "input", .mutable = true, .ty = integer, .kind = .storage }, + .{ .name = "a", .value = "array_input", .mutable = true, .ty = array, .kind = .storage }, + .{ .name = "p", .value = "loan", .mutable = false, .ty = reference, .kind = .borrow }, + .{ .name = "o", .value = "owner", .mutable = false, .ty = owner }, + .{ .name = "sc", .value = "scope_input", .mutable = false, .ty = .scope }, + }); + try l.borrow_parents.put(a, "loan", "input"); + l.cur = try l.newBlock("entry", span); + return l; +} + +fn expectCallMatches(a: Allocator, e: ast.Expr, want: ?Ty, borrow_allowed: bool) !void { + var old = try callTestLowerer(a, e.span); + var current = try callTestLowerer(a, e.span); + const expected = if (borrow_allowed and e.kind == .call) + ReferenceCalls.call(&old, e, e.kind.call.callee.*, e.kind.call.args, true) + else + ReferenceOperands.expr(&old, e, want); + const actual = if (borrow_allowed and e.kind == .call) + current.call(e, e.kind.call.callee.*, e.kind.call.args, true) + else + 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 "ordinary call continuations match former descent consumption cleanup and errors" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const expressions = [_][]const u8{ + "id(1i64)", "id(id(n))", "ns.id(id(n))", "std.test.id(id(n))", + "pair(id(n), id(2i64))", "pair(unknown, true)", "pair(true, unknown)", "pair(id(1i64), id(unknown))", + "pair(id(unknown), id(2i64))", "id()", "id(1i64, unknown)", "unknown(id(unknown))", + "id(sc)", "read(ref n)", "id(read(ref n))", "read(mut n)", + "array(ref a)", "array(ref n)", "bytes(ref a)", "bytes(b\"xy\")", + "id(bytes(b\"xy\"))", "pair(bytes(b\"xy\"), unknown)", "take(o)", "take(move o)", + "id(take(move o))", "retained(p)", "retained(ref n)", "retained(unknown)", + "retained(n)", "void_call(b\"xy\")", "stop(b\"xy\")", "id(stop(b\"xy\"))", + "bool_id(true) and bool_id(false)", "bool_id(false) or bool_id(unknown)", "id(1i64 + id(n))", "id(- id(n))", + "id(id(n) as! u8)", + }; + const forms = [_][]const u8{ "{s}", "id({s})", "pair({s}, id(2i64))", "- ({s})", "not ({s})", "({s}) as! u8" }; + inline for (forms) |form| for (expressions) |text| { + const expression = try std.fmt.allocPrint(a, form, .{text}); + const source_text = try std.fmt.allocPrint(a, "module calls\nfn f() -> void effects [] {{ return {s}; }}", .{expression}); + const parsed = try parse_mod.parse(a, source_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 ordinary calls alternate with scalar continuations without native descent" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const count = 32_768; + for ([_]bool{ false, true }) |mixed| { + const span = unaryTestSpan(1); + var l = try callTestLowerer(a, span); + const callee: ast.Expr = .{ .span = span, .kind = .{ .name = "id" } }; + var e: ast.Expr = .{ .span = unaryTestSpan(90_000), .kind = .{ .int = .{ .text = "1i64" } } }; + for (0..count) |i| { + const args = try a.alloc(ast.Expr, 1); + args[0] = e; + const here = unaryTestSpan(@intCast(i + 1)); + e = .{ .span = here, .kind = .{ .call = .{ .callee = &callee, .type_arg = null, .args = args } } }; + if (mixed) { + const inner = try a.create(ast.Expr); + inner.* = e; + e = .{ .span = here, .kind = .{ .neg = inner } }; + } + } + const v = try l.expr(e, .{ .int = "i64" }); + try std.testing.expect(v.ty.eql(.{ .int = "i64" })); + const insts = l.blocks.items[0].insts.items; + try std.testing.expectEqual(@as(usize, (if (mixed) @as(usize, 3) else 1) * count + 1), insts.len); + const base: usize = if (mixed) count + 1 else 1; + for (0..count) |i| { + const index = base + (if (mixed) @as(usize, 2) else 1) * i; + try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(@intCast(i + 1))), insts[index].span); + try std.testing.expect(std.mem.indexOf(u8, insts[index].text, " = call @id(") != null); + if (mixed) try std.testing.expect(std.mem.indexOf(u8, insts[index + 1].text, " = sub.checked.i64 ") != null); + } + try std.testing.expect(l.problem == null and l.unimpl == null); + } +} + +test "recovering OOM in ordinary call continuations remains a host failure" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const source_text = "module calls\nfn f() -> void effects [] { return pair(id(read(ref n)), id(bytes(b\"xy\"))); }"; + const parsed = try parse_mod.parse(fixture.allocator(), source_text); + try std.testing.expect(parsed == .ok); + const e = parsed.ok.functions[0].body.stmts[0].kind.@"return".?; + var fail_at: usize = 0; + while (true) : (fail_at += 1) { + try std.testing.expect(fail_at < 512); + var output: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer output.deinit(); + var l = try callTestLowerer(output.allocator(), e.span); + var failure: QueryAllocationFailure = .{ .backing = output.allocator(), .fail_at = fail_at }; + l.arena = failure.allocator(); + const result = l.expr(e, .{ .int = "i64" }); + if (failure.failed) { + try std.testing.expectError(error.OutOfMemory, result); + try std.testing.expect(l.problem == null and l.unimpl == null); + try std.testing.expectEqual(fail_at + 1, failure.attempts); + try std.testing.expectEqual(@as(usize, 0), l.out.items.len); + } else { + _ = try result; + break; + } + } +} + +test "persistent backing OOM in public call lowering frees its output arena" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const parsed = try parse_mod.parse(fixture.allocator(), "module oom\nfn id(x: i64) -> i64 effects [] { return x; }\nfn main() -> i64 effects [] { return id(- id(1i64 + id(2i64))); }\n"); + try std.testing.expect(parsed == .ok); + var fail_at: usize = 0; + while (true) : (fail_at += 1) { + try std.testing.expect(fail_at < 128); + var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = fail_at }); + var output: std.heap.ArenaAllocator = .init(failing.allocator()); + const result = lower(output.allocator(), parsed.ok); + output.deinit(); + try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes); + if (failing.has_induced_failure) { + try std.testing.expectError(error.OutOfMemory, result); + } else { + // Only inspect the tag: the returned bytes died with the arena. + try std.testing.expect((try result) == .ok); + break; + } + } +} diff --git a/tests/hosted/source_expression_depth.py b/tests/hosted/source_expression_depth.py index 1ce5d2c..531c720 100644 --- a/tests/hosted/source_expression_depth.py +++ b/tests/hosted/source_expression_depth.py @@ -319,18 +319,69 @@ with tempfile.TemporaryDirectory(prefix='aji-expression-depth-') as directory: assert json.loads(cli(command, path, code=1)) == error print(f'mixed syntax depth: {depth}', flush=True) - for depth in (16, 1024, 16384, 65536): - path = root / f'nested-call-syntax-{depth}.aji' - expression = '1i64 + id(' * depth + '1i64' + ')' * depth - path.write_text('module depth\nfn id(x: i64) -> i64 effects [] { return x; }\n' - 'fn main() -> i64 effects [] { return ' + expression + '; }\n') - output = cli('fmt', path) - formatted = path.with_suffix('.formatted.aji') - formatted.write_bytes(output) - assert cli('fmt', formatted) == output - assert json.loads(cli('fmt', formatted, '--check')) == { - 'file': str(formatted), 'status': 'formatted', 'changed': False} - print(f'nested call 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) + + # 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 # Block/control callbacks remain native. Their existing shallow/deeper # syntax must retain its capacity while expression dispatch is moved out