cli: propagate host allocation errors from source queries

This commit is contained in:
dev committed 2026-10-10 18:32:23 +03:00
1 parent 6945b511a4
commit 50a7575efb
6 files changed
+401 -127

No files matched your search

+292 -97
View File
@@ -465,13 +465,13 @@ const Lowerer = struct {
return out.toOwnedSlice(l.arena);
}
fn wrap(l: *Lowerer, comptime tag: std.meta.Tag(Ty), t: Ty) Error!Ty {
fn wrap(l: *Lowerer, comptime tag: std.meta.Tag(Ty), t: Ty) Allocator.Error!Ty {
const b = try l.arena.create(Ty);
b.* = t;
return @unionInit(Ty, @tagName(tag), b);
}
fn arrayOf(l: *Lowerer, elem: Ty, len: u64) Error!Ty {
fn arrayOf(l: *Lowerer, elem: Ty, len: u64) Allocator.Error!Ty {
const a = try l.arena.create(Ty.Arr);
a.* = .{ .elem = elem, .len = len };
return .{ .array = a };
@@ -1287,7 +1287,7 @@ const Lowerer = struct {
var want: ?Ty = annotation;
// An untyped `let` takes its type from how the name is used
// later (`return`, arguments, operations, annotations).
if (want == null and l.peekType(x.e) == null) want = l.inferUses(x.names[0]);
if (want == null and (try l.peekType(x.e)) == null) want = (try l.inferUses(x.names[0]));
if (x.e.kind == .or_trap) {
const v = try l.expr(x.e, want);
if (want) |w| try l.checkTy(x.e.span, v.ty, w);
@@ -1354,7 +1354,7 @@ const Lowerer = struct {
const scope_start = l.scopeBindingStart();
for (l.bindings.items[scope_start..]) |b| if (b.kind == .borrow and std.mem.eql(u8, b.name, x.name))
return l.invalid(.invalid_binding, s.span, "a borrow of this name is already active in this scope", &.{.{ .name = "name", .value = x.name }});
if (x.place.kind == .call) if (l.borrowReturnSig(x.place.kind.call.callee.*)) |sig| if (sig.ret.isBorrow()) {
if (x.place.kind == .call) if ((try l.borrowReturnSig(x.place.kind.call.callee.*))) |sig| if (sig.ret.isBorrow()) {
if (x.unchecked) return l.invalid(.invalid_place, s.span, "unchecked applies to element places, not calls", &.{});
if (x.mutable != sig.ret.isMutBorrow()) return l.fail("E7005", s.span, "binding mode must match the returned borrow; use ref for shared or mut for exclusive", &.{});
const call_expr = x.place.kind.call;
@@ -1505,7 +1505,7 @@ const Lowerer = struct {
fn forLoop(l: *Lowerer, span: Span, name: []const u8, lo: ast.Expr, hi: ast.Expr, body: ast.Block) Error!void {
const depth = l.bindings.items.len;
defer l.bindings.shrinkRetainingCapacity(depth);
const ty = l.peekType(lo) orelse l.peekType(hi) orelse return l.fail("E7007", lo.span, "the type of the range cannot be determined; add a suffix such as `0usize`", &.{});
const ty = (try l.peekType(lo)) orelse (try l.peekType(hi)) orelse return l.fail("E7007", lo.span, "the type of the range cannot be determined; add a suffix such as `0usize`", &.{});
if (ty != .int) return l.fail("E7005", lo.span, "a range needs an integer type", &.{.{ .name = "found", .value = try l.diagnosticTyText(ty) }});
const a = try l.expr(lo, ty);
try l.checkOperandTy(lo.span, a.ty, ty);
@@ -1561,12 +1561,12 @@ const Lowerer = struct {
return l.sigs.get(l.boundName(name, span) orelse return null);
}
fn calleeSig(l: *Lowerer, e: ast.Expr) ?FnSig {
const name = expressionPath(l.arena, e) catch return null;
fn calleeSig(l: *Lowerer, e: ast.Expr) Allocator.Error!?FnSig {
const name = try expressionPath(l.arena, e);
return l.functionSig(name orelse return null, e.span);
}
fn borrowReturnSig(l: *Lowerer, e: ast.Expr) ?FnSig {
fn borrowReturnSig(l: *Lowerer, e: ast.Expr) Allocator.Error!?FnSig {
if (pathOf(e) != null) return null;
if (e.kind == .name and (std.mem.eql(u8, e.kind.name, "assert") or std.mem.eql(u8, e.kind.name, "assume"))) return null;
return l.calleeSig(e);
@@ -1586,10 +1586,10 @@ const Lowerer = struct {
return null;
}
// Best-effort query: output construction already treats host OOM as
// unknown. Continuation OOM follows that contract without a diagnostic.
fn peekType(l: *Lowerer, e: ast.Expr) ?Ty {
return l.queryType(.{ .expr = e }) catch null;
// Unknown types return null; host allocation failure propagates separately
// so callers cannot mistake OOM for a source inference error.
fn peekType(l: *Lowerer, e: ast.Expr) Allocator.Error!?Ty {
return l.queryType(.{ .expr = e });
}
const TypeRequest = union(enum) { expr: ast.Expr, path: struct { name: []const u8, args: []const ast.Expr } };
@@ -1640,7 +1640,7 @@ const Lowerer = struct {
request = .{ .expr = xs[0] };
continue :query;
},
.cast => |x| l.typeOfNoFail(x.ty),
.cast => |x| (try l.queryAnnotation(x.ty)),
.binary => |x| switch (x.op) {
.eq, .ne, .lt, .le, .gt, .ge, .@"and", .@"or" => .bool,
else => {
@@ -1653,7 +1653,7 @@ const Lowerer = struct {
.name => |n| if (l.functionSig(n, e.span)) |sig| sig.ret else null,
.variant => |v| l.enumType(v.@"enum", e.span),
else => blk: {
if (l.calleeSig(x.callee.*)) |sig| break :blk sig.ret;
if ((try l.calleeSig(x.callee.*))) |sig| break :blk sig.ret;
const name = pathOf(x.callee.*) orelse break :blk null;
request = .{ .path = .{ .name = name, .args = x.args } };
continue :query;
@@ -1689,8 +1689,8 @@ const Lowerer = struct {
if (eq(u8, p.name, "buffer.len") or eq(u8, p.name, "buffer.capacity")) break :blk Ty{ .int = "usize" };
if (eq(u8, p.name, "task.cancelled")) break :blk Ty.bool;
if (eq(u8, p.name, "task.spawn") and p.args.len >= 2) {
const sig = l.calleeSig(p.args[1]) orelse break :blk null;
break :blk l.wrap(.task, sig.ret) catch null;
const sig = (try l.calleeSig(p.args[1])) orelse break :blk null;
break :blk (try l.wrap(.task, sig.ret));
}
if ((eq(u8, p.name, "own.take") or eq(u8, p.name, "task.join")) and p.args.len == 1) {
try pending.append(l.arena, .inner);
@@ -1718,7 +1718,7 @@ const Lowerer = struct {
while (pending.pop()) |frame| switch (frame) {
.inner => result = if (result) |t| t.inner() else null,
.element => result = if (result) |t| elemOf(t) else null,
.array => |len| result = if (result) |t| l.arrayOf(t, len) catch null else null,
.array => |len| result = if (result) |t| (try l.arrayOf(t, len)) else null,
.alternative => |e| if (result == null) {
request = .{ .expr = e };
continue :query;
@@ -1728,14 +1728,14 @@ const Lowerer = struct {
request = .{ .expr = arms[0].body };
continue :query;
},
.field => |name| result = l.queryField(result, name),
.field => |name| result = (try l.queryField(result, name)),
.operation => |op| result = if (result) |t| switch (op) {
.atomic_new => l.wrap(.atomic, t) catch null,
.atomic_new => (try l.wrap(.atomic, t)),
.atomic_load_inline => if (t == .atomic) t.inner() else null,
.atomic_load_borrow => if (t.inner()) |c| (if (c == .atomic) c.inner() else null) else null,
.graph_root => if (t.inner()) |o| (if (o.inner()) |r| l.wrap(.iref, r) catch null else null) else null,
.freeze => if (t == .island) l.wrap(.frozen, t.inner().?) catch null else null,
.arc_from => if (t == .frozen) l.wrap(.arc, t.inner().?) catch null else null,
.graph_root => if (t.inner()) |o| (if (o.inner()) |r| (try l.wrap(.iref, r)) else null) else null,
.freeze => if (t == .island) (try l.wrap(.frozen, t.inner().?)) else null,
.arc_from => if (t == .frozen) (try l.wrap(.arc, t.inner().?)) else null,
.arc_clone => if (t == .arc) t else if (t.inner()) |in| (if (in == .arc) in else null) else null,
.channel_dup => if (t == .sender) t else if (t.inner()) |in| (if (in == .sender) in else null) else null,
} else null,
@@ -1744,44 +1744,44 @@ const Lowerer = struct {
}
}
fn queryField(l: *Lowerer, known: ?Ty, name: []const u8) ?Ty {
fn queryField(l: *Lowerer, known: ?Ty, name: []const u8) Allocator.Error!?Ty {
if (std.mem.eql(u8, name, "len") and (known == null or !isNominalFieldBase(known.?))) return .{ .int = "usize" };
var base = known orelse return null;
if (base.isBorrow()) base = base.inner().?;
const d = l.decl(base) orelse return null;
if (d.kind != .@"struct") return null;
for (d.kind.@"struct") |f| if (std.mem.eql(u8, f.name, name)) return l.typeOfNoFail(f.ty);
for (d.kind.@"struct") |f| if (std.mem.eql(u8, f.name, name)) return l.queryAnnotation(f.ty);
return null;
}
/// The type the following code expects for the name `n`, if any use
/// determines one. Stops at a rebinding of `n`.
fn inferUses(l: *Lowerer, n: []const u8) ?Ty {
fn inferUses(l: *Lowerer, n: []const u8) Allocator.Error!?Ty {
var i = l.rest.items.len;
while (i > 0) {
i -= 1;
const r = l.rest.items[i];
for (r.stmts) |s| {
if (l.usesInStmt(n, s)) |t| return t;
if ((try l.usesInStmt(n, s))) |t| return t;
if (s.kind == .let) for (s.kind.let.names) |bn| if (std.mem.eql(u8, bn, n)) return null;
}
if (r.tail) |t| if (l.useIn(n, t.*, if (i == 0) l.ret else null)) |ty| return ty;
if (r.tail) |t| if ((try l.useIn(n, t.*, if (i == 0) l.ret else null))) |ty| return ty;
}
return null;
}
fn usesInStmt(l: *Lowerer, n: []const u8, s: ast.Stmt) ?Ty {
return l.queryUse(n, .{ .statement = s }) catch null;
fn usesInStmt(l: *Lowerer, n: []const u8, s: ast.Stmt) Allocator.Error!?Ty {
return l.queryUse(n, .{ .statement = s });
}
fn usesInBlock(l: *Lowerer, n: []const u8, b: ast.Block) ?Ty {
return l.queryUse(n, .{ .block = b }) catch null;
fn usesInBlock(l: *Lowerer, n: []const u8, b: ast.Block) Allocator.Error!?Ty {
return l.queryUse(n, .{ .block = b });
}
/// The expected type of `n` inside `e`, evaluated where `e` is expected
/// to have type `want`. Like peekType, this is a best-effort query.
fn useIn(l: *Lowerer, n: []const u8, e: ast.Expr, want: ?Ty) ?Ty {
return l.queryUse(n, .{ .expression = .{ .e = e, .want = .{ .known = want } } }) catch null;
/// to have type `want`. Unknown is null; host OOM propagates separately.
fn useIn(l: *Lowerer, n: []const u8, e: ast.Expr, want: ?Ty) Allocator.Error!?Ty {
return l.queryUse(n, .{ .expression = .{ .e = e, .want = .{ .known = want } } });
}
// Right-hand hints are resolved only after an earlier use was unknown.
@@ -1809,8 +1809,8 @@ const Lowerer = struct {
const e = x.e;
const want: ?Ty = switch (x.want) {
.known => |t| t,
.peek => |other| l.peekType(other),
.peek_or => |other| l.peekType(other.e) orelse other.fallback,
.peek => |other| (try l.peekType(other)),
.peek_or => |other| (try l.peekType(other.e)) orelse other.fallback,
};
switch (e.kind) {
.name => |name| if (std.mem.eql(u8, name, n)) {
@@ -1835,9 +1835,9 @@ const Lowerer = struct {
.binary => |b| {
const left: ?Ty = switch (b.op) {
.@"and", .@"or" => .bool,
.eq, .ne, .lt, .le, .gt, .ge => l.peekType(b.r.*),
.eq, .ne, .lt, .le, .gt, .ge => (try l.peekType(b.r.*)),
.shl, .shr => want,
else => want orelse l.peekType(b.l.*) orelse l.peekType(b.r.*),
else => want orelse (try l.peekType(b.l.*)) orelse (try l.peekType(b.r.*)),
};
const right: UseExpected = switch (b.op) {
.eq, .ne, .lt, .le, .gt, .ge => .{ .peek = b.l.* },
@@ -1849,7 +1849,7 @@ const Lowerer = struct {
continue :search;
},
.call => |c| {
const sig = l.calleeSig(c.callee.*) orelse {
const sig = (try l.calleeSig(c.callee.*)) orelse {
request = pending.pop() orelse return null;
continue :search;
};
@@ -1877,11 +1877,11 @@ const Lowerer = struct {
},
.statement => |s| switch (s.kind) {
.let => |x| {
request = .{ .expression = .{ .e = x.e, .want = .{ .known = if (x.ty) |t| l.typeOfNoFail(t) else null } } };
request = .{ .expression = .{ .e = x.e, .want = .{ .known = if (x.ty) |t| (try l.queryAnnotation(t)) else null } } };
continue :search;
},
.@"var" => |x| if (x.init) |e| {
request = .{ .expression = .{ .e = e, .want = .{ .known = l.typeOfNoFail(x.ty) } } };
request = .{ .expression = .{ .e = e, .want = .{ .known = (try l.queryAnnotation(x.ty)) } } };
continue :search;
},
.assign => |x| {
@@ -1938,9 +1938,9 @@ const Lowerer = struct {
}
}
fn typeOfNoFail(l: *Lowerer, annotation: ast.Type) ?Ty {
fn queryAnnotation(l: *Lowerer, annotation: ast.Type) Allocator.Error!?Ty {
// Validate before allocating, as the old postorder query did. This
// best-effort lookup recognizes only names and fixed array chains.
// optional lookup recognizes only names and fixed array chains.
var t = annotation;
while (t.kind == .array) {
const a = t.kind.array;
@@ -1959,7 +1959,7 @@ const Lowerer = struct {
const a = t.kind.array;
// Only fresh output nodes are writable; no source AST is borrowed
// or changed. The caller arena retains partial nodes on OOM.
const node = l.arena.create(Ty.Arr) catch return null;
const node = try l.arena.create(Ty.Arr);
node.len = a.len;
target.* = .{ .array = node };
target = &node.elem;
@@ -2078,7 +2078,7 @@ const Lowerer = struct {
e = x.*;
},
.neg => |x| {
const ty = want orelse l.peekType(x.*) orelse return l.fail("E7007", e.span, "the type of this negation cannot be determined", &.{});
const ty = want orelse (try l.peekType(x.*)) orelse return l.fail("E7007", e.span, "the type of this negation cannot be determined", &.{});
if (ty != .int) return l.fail("E7005", e.span, "negation of a non-integer", &.{});
// Negative literals retain the boundary magnitude rule
// and bypass ordinary positive-literal lowering.
@@ -2099,7 +2099,7 @@ const Lowerer = struct {
.cast => |x| {
const to = try l.typeOf(x.ty);
if (to != .int) return l.fail("E7005", x.ty.span, "casts convert between integer types", &.{});
want = l.peekType(x.e.*) orelse to;
want = (try l.peekType(x.e.*)) orelse to;
try pending.append(l.arena, .{ .unary = .{ .e = e, .ty = to } });
e = x.e.*;
},
@@ -2113,7 +2113,7 @@ const Lowerer = struct {
else => false,
};
const shift = x.op == .shl or x.op == .shr;
const operand: ?Ty = if (cmp) (l.peekType(x.l.*) orelse l.peekType(x.r.*)) else if (shift) (want orelse l.peekType(x.l.*)) else (want orelse l.peekType(x.l.*) orelse l.peekType(x.r.*));
const operand: ?Ty = if (cmp) ((try l.peekType(x.l.*)) orelse (try l.peekType(x.r.*))) else if (shift) (want orelse (try l.peekType(x.l.*))) else (want orelse (try l.peekType(x.l.*)) orelse (try l.peekType(x.r.*)));
const ty = operand orelse return l.fail("E7007", e.span, "the type of this operation cannot be determined; add a suffix or annotation", &.{});
try pending.append(l.arena, .{ .binary_left = .{ .e = e, .ty = ty } });
want = ty;
@@ -2420,7 +2420,7 @@ const Lowerer = struct {
/// `v.f` on a struct value: `struct.get` (borrows come in layer 4).
fn fieldValue(l: *Lowerer, e: ast.Expr, base: ast.Expr, name: []const u8) Error!Value {
var bt = l.peekType(base) orelse return l.fail("E7007", base.span, "the type of this expression cannot be determined", &.{});
var bt = (try l.peekType(base)) orelse return l.fail("E7007", base.span, "the type of this expression cannot be determined", &.{});
if (bt.isBorrow()) bt = bt.inner().?;
const d = l.decl(bt) orelse return l.fail("E7005", e.span, "field access on a value that is not a struct", &.{.{ .name = "found", .value = try l.diagnosticTyText(bt) }});
if (d.kind != .@"struct") return l.fail("E7005", e.span, "field access on an enum; use `match`", &.{.{ .name = "type", .value = d.display_name orelse d.name }});
@@ -2483,7 +2483,7 @@ const Lowerer = struct {
/// integer (`switch`; `_` required). Payload names live in their arm.
fn matchExpr(l: *Lowerer, m: ast.Match, want: ?Ty) Error!Value {
if (m.kind == .outcome) return l.outcomeMatch(m, want);
const st = l.peekType(m.scrutinee) orelse return l.fail("E7007", m.scrutinee.span, "the type of this value cannot be determined", &.{});
const st = (try l.peekType(m.scrutinee)) orelse return l.fail("E7007", m.scrutinee.span, "the type of this value cannot be determined", &.{});
if (st == .builtin) return l.builtinMatch(m, st.builtin, want);
const sv = try l.consuming(m.scrutinee, st);
const depth = l.bindings.items.len;
@@ -2944,7 +2944,7 @@ const Lowerer = struct {
if (place.kind == .index and place.kind.index.hi != null) return l.invalid(.invalid_assignment, place.span, "assign elements one by one, or use `slice.copy(mut dst, ref src)`", &.{});
// The value is evaluated first, then the place is borrowed for the
// store (spec 15 §4), so `s[i] = s[i] + 1` reads before it writes.
const target_type = l.placeType(place);
const target_type = (try l.placeType(place));
const v = try l.expr(value, target_type);
if (v.ty == .never) return l.noOperandValue(value.span, if (target_type) |t| try l.diagnosticTyText(t) else "a stored value");
const p = try l.placeBorrow(place, true, false, span);
@@ -2957,10 +2957,10 @@ const Lowerer = struct {
}
/// The type stored at a place, without lowering it.
fn placeType(l: *Lowerer, place: ast.Expr) ?Ty {
fn placeType(l: *Lowerer, place: ast.Expr) Allocator.Error!?Ty {
return switch (place.kind) {
.deref => |d| if (l.peekType(d.*)) |t| t.inner() else null,
.field, .index => l.peekType(place),
.deref => |d| if ((try l.peekType(d.*))) |t| t.inner() else null,
.field, .index => (try l.peekType(place)),
else => null,
};
}
@@ -2973,7 +2973,7 @@ const Lowerer = struct {
/// `x.len`: a nominal field, `slice.len`, or the static array length.
fn lenOf(l: *Lowerer, e: ast.Expr, base: ast.Expr) Error!Value {
const bt = l.peekType(base) orelse return l.fail("E7007", base.span, "the type of this expression cannot be determined", &.{});
const bt = (try l.peekType(base)) orelse return l.fail("E7007", base.span, "the type of this expression cannot be determined", &.{});
if (isNominalFieldBase(bt)) return l.fieldValue(e, base, "len");
const arr: ?u64 = switch (bt) {
.array => |a| a.len,
@@ -4065,7 +4065,7 @@ const Lowerer = struct {
const cv = blk: {
const c = x.cond;
if (c.kind == .binary and c.kind.binary.op == .lt and c.kind.binary.r.kind == .field and std.mem.eql(u8, c.kind.binary.r.kind.field.name, "len")) {
const st = l.peekType(c.kind.binary.r.kind.field.e.*);
const st = (try l.peekType(c.kind.binary.r.kind.field.e.*));
if (st != null and (st.? == .slice or st.? == .slice_mut)) {
const iv = try l.expr(c.kind.binary.l.*, .{ .int = "usize" });
try l.checkOperandTy(c.kind.binary.l.span, iv.ty, .{ .int = "usize" });
@@ -4576,13 +4576,13 @@ const ReferenceUseQuery = struct {
fn statement(l: *Lowerer, n: []const u8, s: ast.Stmt) ?Ty {
return switch (s.kind) {
.let => |x| expression(l, n, x.e, if (x.ty) |t| l.typeOfNoFail(t) else null),
.@"var" => |x| if (x.init) |e| expression(l, n, e, l.typeOfNoFail(x.ty)) else null,
.let => |x| expression(l, n, x.e, if (x.ty) |t| (l.queryAnnotation(t) catch null) else null),
.@"var" => |x| if (x.init) |e| expression(l, n, e, (l.queryAnnotation(x.ty) catch null)) else null,
.assign => |x| expression(l, n, x.e, if (x.place.kind == .name) (if (l.lookup(x.place.kind.name)) |b| b.ty else null) else null),
.@"return" => |e| if (e) |x| expression(l, n, x, l.ret) else null,
.expr => |e| expression(l, n, e, null),
.@"while" => |x| expression(l, n, x.cond, .bool) orelse block(l, n, x.body),
.@"for" => |x| expression(l, n, x.lo, l.peekType(x.hi)) orelse expression(l, n, x.hi, l.peekType(x.lo)) orelse block(l, n, x.body),
.@"for" => |x| expression(l, n, x.lo, (l.peekType(x.hi) catch null)) orelse expression(l, n, x.hi, (l.peekType(x.lo) catch null)) orelse block(l, n, x.body),
.loop, .shield => |b| block(l, n, b),
.scope => |x| block(l, n, x.body),
else => null,
@@ -4605,15 +4605,15 @@ const ReferenceUseQuery = struct {
.cast => |x| expression(l, n, x.e.*, null),
.binary => |x| switch (x.op) {
.@"and", .@"or" => expression(l, n, x.l.*, .bool) orelse expression(l, n, x.r.*, .bool),
.eq, .ne, .lt, .le, .gt, .ge => expression(l, n, x.l.*, l.peekType(x.r.*)) orelse expression(l, n, x.r.*, l.peekType(x.l.*)),
.shl, .shr => expression(l, n, x.l.*, want) orelse expression(l, n, x.r.*, l.peekType(x.l.*) orelse want),
.eq, .ne, .lt, .le, .gt, .ge => expression(l, n, x.l.*, (l.peekType(x.r.*) catch null)) orelse expression(l, n, x.r.*, (l.peekType(x.l.*) catch null)),
.shl, .shr => expression(l, n, x.l.*, want) orelse expression(l, n, x.r.*, (l.peekType(x.l.*) catch null) orelse want),
else => blk: {
const t = want orelse l.peekType(x.l.*) orelse l.peekType(x.r.*);
const t = want orelse (l.peekType(x.l.*) catch null) orelse (l.peekType(x.r.*) catch null);
break :blk expression(l, n, x.l.*, t) orelse expression(l, n, x.r.*, t);
},
},
.call => |x| blk: {
const sig = l.calleeSig(x.callee.*) orelse break :blk null;
const sig = (l.calleeSig(x.callee.*) catch null) orelse break :blk null;
for (x.args, 0..) |a, i| {
const pt: ?Ty = if (i < sig.params.len) sig.params[i] else null;
if (expression(l, n, a, pt)) |t| break :blk t;
@@ -4658,7 +4658,7 @@ test "expected-use queries match independent shallow expression and statement de
const parsed = try parse_mod.parse(a, source);
try std.testing.expect(parsed == .ok);
const e = parsed.ok.functions[0].body.stmts[0].kind.@"return".?;
for ([_]?Ty{ null, .bool, .{ .int = "u64" } }) |want| try expectUseQueryEqual(ReferenceUseQuery.expression(&l, "n", e, want), l.useIn("n", e, want));
for ([_]?Ty{ null, .bool, .{ .int = "u64" } }) |want| try expectUseQueryEqual(ReferenceUseQuery.expression(&l, "n", e, want), (try l.useIn("n", e, want)));
};
const statements = [_][]const u8{
"let y: u8 = n;", "let y = n;", "let n: u8 = n;", "let (n, y) = f(n);", "var y: u32 = n;", "var y: u32 = zero;",
@@ -4673,8 +4673,8 @@ test "expected-use queries match independent shallow expression and statement de
if (parsed != .ok) std.debug.print("failed expected-use fixture: {s}\n", .{text});
try std.testing.expect(parsed == .ok);
const body = parsed.ok.functions[0].body;
try expectUseQueryEqual(ReferenceUseQuery.block(&l, "n", body), l.usesInBlock("n", body));
for (body.stmts) |stmt| try expectUseQueryEqual(ReferenceUseQuery.statement(&l, "n", stmt), l.usesInStmt("n", stmt));
try expectUseQueryEqual(ReferenceUseQuery.block(&l, "n", body), (try l.usesInBlock("n", body)));
for (body.stmts) |stmt| try expectUseQueryEqual(ReferenceUseQuery.statement(&l, "n", stmt), (try l.usesInStmt("n", stmt)));
}
try std.testing.expect(l.problem == null);
try std.testing.expectEqual(@as(usize, 0), l.blocks.items.len);
@@ -4700,7 +4700,7 @@ test "expected-use rest queries preserve scope order tails and top-level let reb
const b = parsed.ok.functions[0].body;
try l.rest.append(a, .{ .stmts = b.stmts, .tail = b.tail });
}
try expectUseQueryEqual(ReferenceUseQuery.infer(&l, "n"), l.inferUses("n"));
try expectUseQueryEqual(ReferenceUseQuery.infer(&l, "n"), (try l.inferUses("n")));
};
}
@@ -4715,7 +4715,7 @@ test "expected-use queries do not evaluate deferred right-hand type hints after
var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 1 });
var l: Lowerer = .{ .arena = failing.allocator(), .m = .{ .name = "uses", .types = &.{}, .functions = &.{} } };
const e: ast.Expr = .{ .span = span, .kind = .{ .binary = .{ .op = op, .l = &left, .r = &right } } };
try expectUseQueryEqual(.{ .int = "u16" }, l.useIn("n", e, .{ .int = "u16" }));
try expectUseQueryEqual(.{ .int = "u16" }, (try l.useIn("n", e, .{ .int = "u16" })));
// One worklist allocation is allowed. An eager peekType(left) would
// construct the array type on a second request and induce host OOM.
try std.testing.expect(!failing.has_induced_failure);
@@ -4729,7 +4729,7 @@ test "expected-use queries do not evaluate deferred right-hand type hints after
.hi = right,
.body = .{ .span = span, .stmts = &.{}, .tail = null },
} } };
try expectUseQueryEqual(.{ .int = "u16" }, l.usesInStmt("n", loop));
try expectUseQueryEqual(.{ .int = "u16" }, (try l.usesInStmt("n", loop)));
try std.testing.expect(!failing.has_induced_failure);
try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes);
}
@@ -4770,12 +4770,12 @@ test "expected-use queries handle deep unary branches calls and statement blocks
},
}
}
try expectUseQueryEqual(.{ .int = "u16" }, l.useIn("n", unary, .{ .int = "u16" }));
try expectUseQueryEqual(.bool, l.useIn("n", mixed, null));
try expectUseQueryEqual(.{ .int = "u16" }, (try l.useIn("n", unary, .{ .int = "u16" })));
try expectUseQueryEqual(.bool, (try l.useIn("n", mixed, null)));
// Plain unary traversal does not need host metadata allocation.
var none: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 0 });
var no_alloc: Lowerer = .{ .arena = none.allocator(), .m = m };
try expectUseQueryEqual(.bool, no_alloc.useIn("n", unary, .bool));
try expectUseQueryEqual(.bool, (try no_alloc.useIn("n", unary, .bool)));
try std.testing.expect(!none.has_induced_failure);
var body: ast.Block = .{ .span = span, .stmts = &.{.{ .span = span, .kind = .{ .@"return" = name } }}, .tail = null };
for (0..32_768) |_| {
@@ -4788,13 +4788,13 @@ test "expected-use queries handle deep unary branches calls and statement blocks
tail.* = .{ .span = span, .kind = .{ .not = &name } };
body = .{ .span = span, .stmts = stmts, .tail = tail };
}
try expectUseQueryEqual(.{ .int = "u64" }, l.usesInBlock("n", body));
try expectUseQueryEqual(.{ .int = "u64" }, (try l.usesInBlock("n", body)));
try std.testing.expect(l.problem == null);
try std.testing.expectEqual(@as(usize, 0), l.out.items.len);
try std.testing.expectEqual(@as(usize, 0), l.blocks.items.len);
}
test "expected-use worklist OOM is unknown and releases all backing allocations" {
test "expected-use worklist propagates OOM and releases all backing allocations" {
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer fixture.deinit();
const a = fixture.allocator();
@@ -4815,7 +4815,7 @@ test "expected-use worklist OOM is unknown and releases all backing allocations"
var arena: std.heap.ArenaAllocator = .init(failing.allocator());
var l: Lowerer = .{ .arena = arena.allocator(), .m = .{ .name = "uses", .types = &.{}, .functions = &.{} } };
const result = l.useIn("n", e, null);
if (failing.has_induced_failure) try std.testing.expect(result == null) else try expectUseQueryEqual(.bool, result);
if (failing.has_induced_failure) try std.testing.expectError(error.OutOfMemory, result) else try expectUseQueryEqual(.bool, try result);
try std.testing.expect(l.problem == null);
try std.testing.expectEqual(@as(usize, 0), l.out.items.len);
try std.testing.expectEqual(@as(usize, 0), l.blocks.items.len);
@@ -4844,7 +4844,7 @@ const ReferenceExpressionQuery = struct {
.array_list => |xs| if (xs.len != 0) (if (query(l, xs[0])) |t| (l.arrayOf(t, xs.len) catch null) else null) else null,
.neg => unreachable,
.not => .bool,
.cast => |x| l.typeOfNoFail(x.ty),
.cast => |x| (l.queryAnnotation(x.ty) catch null),
.binary => |x| switch (x.op) {
.eq, .ne, .lt, .le, .gt, .ge, .@"and", .@"or" => .bool,
.shl, .shr => query(l, x.l.*),
@@ -4853,7 +4853,7 @@ const ReferenceExpressionQuery = struct {
.call => |x| switch (x.callee.kind) {
.name => |n| if (l.functionSig(n, e.span)) |sig| sig.ret else null,
.variant => |v| l.enumType(v.@"enum", e.span),
else => if (l.calleeSig(x.callee.*)) |sig| sig.ret else if (pathOf(x.callee.*)) |p| path(l, p, x.args) else null,
else => if ((l.calleeSig(x.callee.*) catch null)) |sig| sig.ret else if (pathOf(x.callee.*)) |p| path(l, p, x.args) else null,
},
.move => |n| if (l.lookup(n)) |b| b.ty else null,
.variant => |v| l.enumType(v.@"enum", e.span),
@@ -4865,7 +4865,7 @@ const ReferenceExpressionQuery = struct {
if (base.isBorrow()) base = base.inner().?;
const d = l.decl(base) orelse break :blk null;
if (d.kind != .@"struct") break :blk null;
for (d.kind.@"struct") |f| if (std.mem.eql(u8, f.name, x.name)) break :blk l.typeOfNoFail(f.ty);
for (d.kind.@"struct") |f| if (std.mem.eql(u8, f.name, x.name)) break :blk (l.queryAnnotation(f.ty) catch null);
break :blk null;
},
.if_expr => |x| if (x.then.tail) |t| query(l, t.*) else null,
@@ -4897,7 +4897,7 @@ const ReferenceExpressionQuery = struct {
if (eq(u8, p, "arc.clone") and args.len == 1) return if (query(l, args[0])) |t| (if (t == .arc) t else if (t.inner()) |in| (if (in == .arc) in else null) else null) else null;
if (eq(u8, p, "channel.dup") and args.len == 1) return if (query(l, args[0])) |t| (if (t == .sender) t else if (t.inner()) |in| (if (in == .sender) in else null) else null) else null;
if (eq(u8, p, "task.spawn") and args.len >= 2) {
const sig = l.calleeSig(args[1]) orelse return null;
const sig = (l.calleeSig(args[1]) catch null) orelse return null;
return l.wrap(.task, sig.ret) catch null;
}
return null;
@@ -4952,7 +4952,7 @@ test "expression type queries match the independent shallow derivation" {
try std.testing.expect(r == .ok);
const e = r.ok.functions[0].body.stmts[0].kind.@"return".?;
const expected = ReferenceExpressionQuery.query(&l, e);
const actual = l.peekType(e);
const actual = (try l.peekType(e));
if (expected) |ty| try std.testing.expect(actual != null and ty.eql(actual.?)) else try std.testing.expect(actual == null);
try std.testing.expect(l.problem == null);
try std.testing.expectEqual(@as(usize, 0), l.blocks.items.len);
@@ -4993,14 +4993,14 @@ test "expression queries suspend deep structural, branch and builtin requests" {
},
}
}
const result = l.peekType(e);
const result = (try l.peekType(e));
try std.testing.expect(result != null and result.?.eql(.{ .int = "u8" }));
try std.testing.expect(l.problem == null);
try std.testing.expectEqual(@as(usize, 0), l.blocks.items.len);
}
}
test "best-effort expression query OOM releases all backing blocks without diagnostics" {
test "expression query propagates OOM and releases all backing blocks without diagnostics" {
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer fixture.deinit();
const a = fixture.allocator();
@@ -5019,8 +5019,8 @@ test "best-effort expression query OOM releases all backing blocks without diagn
var arena: std.heap.ArenaAllocator = .init(failing.allocator());
var l: Lowerer = .{ .arena = arena.allocator(), .m = m };
const result = l.peekType(e);
if (failing.has_induced_failure) try std.testing.expect(result == null) else {
var t = result.?;
if (failing.has_induced_failure) try std.testing.expectError(error.OutOfMemory, result) else {
var t = (try result).?;
for (0..128) |_| {
try std.testing.expect(t == .array and t.array.len == 1);
t = t.array.elem;
@@ -5036,7 +5036,7 @@ test "best-effort expression query OOM releases all backing blocks without diagn
var none: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 0 });
var l: Lowerer = .{ .arena = none.allocator(), .m = m };
const leaf: ast.Expr = .{ .span = span, .kind = .{ .boolean = false } };
try std.testing.expect(l.peekType(leaf).? == .bool);
try std.testing.expect((try l.peekType(leaf)).? == .bool);
try std.testing.expect(!none.has_induced_failure);
}
@@ -5081,7 +5081,7 @@ const ReferenceOperands = struct {
return l.def("not", .bool, try l.fmt("xor.bool %{s}, %{s}", .{ v.name, t.name }), e.span);
},
.neg => |x| {
const ty = want orelse l.peekType(x.*) orelse return l.fail("E7007", e.span, "the type of this negation cannot be determined", &.{});
const ty = want orelse (try l.peekType(x.*)) orelse return l.fail("E7007", e.span, "the type of this negation cannot be determined", &.{});
if (ty != .int) return l.fail("E7005", e.span, "negation of a non-integer", &.{});
if (x.kind == .int) {
const v = parse_mod.parseIntText(x.kind.int.text) orelse return l.fail("E7001", e.span, "malformed integer literal", &.{});
@@ -5108,7 +5108,7 @@ const ReferenceOperands = struct {
.cast => |x| {
const to = try l.typeOf(x.ty);
if (to != .int) return l.fail("E7005", x.ty.span, "casts convert between integer types", &.{});
const from = l.peekType(x.e.*) orelse to;
const from = (try l.peekType(x.e.*)) orelse to;
const v = try expr(l, x.e.*, from);
if (v.ty != .int) return l.fail("E7005", x.e.span, "casts convert between integer types", &.{.{ .name = "found", .value = try l.diagnosticTyText(v.ty) }});
if (x.mode == .widen) {
@@ -5156,7 +5156,7 @@ const ReferenceOperands = struct {
else => false,
};
const shift = op == .shl or op == .shr;
const operand: ?Ty = if (cmp) (l.peekType(a) orelse l.peekType(b)) else if (shift) (want orelse l.peekType(a)) else (want orelse l.peekType(a) orelse l.peekType(b));
const operand: ?Ty = if (cmp) ((try l.peekType(a)) orelse (try l.peekType(b))) else if (shift) (want orelse (try l.peekType(a))) else (want orelse (try l.peekType(a)) orelse (try l.peekType(b)));
const ty = operand orelse return l.fail("E7007", e.span, "the type of this operation cannot be determined; add a suffix or annotation", &.{});
const lv = try expr(l, a, ty);
try l.checkOperandTy(a.span, lv.ty, ty);
@@ -6424,7 +6424,7 @@ fn referenceTypeHint(l: *Lowerer, t: ast.Type) ?Ty {
fn expectTypeHintMatches(l: *Lowerer, t: ast.Type) !void {
const before = referenceTypeHint(l, t);
const after = l.typeOfNoFail(t);
const after = (try l.queryAnnotation(t));
try std.testing.expectEqual(before == null, after == null);
if (before) |b| try std.testing.expect(b.eql(after.?));
try std.testing.expect(l.problem == null and l.unimpl == null);
@@ -6477,7 +6477,7 @@ test "deep best-effort source type lookup owns output and rejects without alloca
for (nodes[1..], 1..) |*node, i| node.* = .{ .span = span, .kind = .{ .array = .{ .elem = &nodes[i - 1], .len = i } } };
var allocations: std.testing.FailingAllocator = .init(std.testing.allocator, .{});
var l: Lowerer = .{ .arena = allocations.allocator(), .m = m };
var current = l.typeOfNoFail(nodes[count]).?;
var current = (try l.queryAnnotation(nodes[count])).?;
var remaining: usize = count;
while (remaining != 0) : (remaining -= 1) {
try std.testing.expect(current == .array);
@@ -6494,18 +6494,18 @@ test "deep best-effort source type lookup owns output and rejects without alloca
var invalid: Lowerer = .{ .arena = no_alloc.allocator(), .m = m };
for ([_][]const u8{ "missing", "void", "never" }) |name| {
nodes[0].kind = .{ .name = name };
try std.testing.expect(invalid.typeOfNoFail(nodes[count]) == null);
try std.testing.expect((try invalid.queryAnnotation(nodes[count])) == null);
}
nodes[0].kind = .{ .name = "u8" };
nodes[1].kind.array.len = 0;
try std.testing.expect(invalid.typeOfNoFail(nodes[count]) == null);
try std.testing.expect((try invalid.queryAnnotation(nodes[count])) == null);
nodes[1].kind.array.len = (@as(u64, 1) << 32) + 1;
try std.testing.expect(invalid.typeOfNoFail(nodes[count]) == null);
try std.testing.expect((try invalid.queryAnnotation(nodes[count])) == null);
try std.testing.expect(!no_alloc.has_induced_failure);
try std.testing.expect(invalid.problem == null and invalid.unimpl == null);
}
test "best-effort source type lookup preserves null on every allocation failure" {
test "optional source type lookup propagates every allocation failure" {
var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
@@ -6522,10 +6522,11 @@ test "best-effort source type lookup preserves null on every allocation failure"
var before: Lowerer = .{ .arena = before_nodes.allocator(), .m = m };
var after: Lowerer = .{ .arena = after_nodes.allocator(), .m = m };
const original = referenceTypeHint(&before, nodes[64]);
const current = after.typeOfNoFail(nodes[64]);
try std.testing.expectEqual(original == null, current == null);
try std.testing.expectEqual(fail_index < 64, current == null);
if (original) |ty| try std.testing.expect(ty.eql(current.?));
const current = after.queryAnnotation(nodes[64]);
if (fail_index < 64) {
try std.testing.expect(original == null);
try std.testing.expectError(error.OutOfMemory, current);
} else try std.testing.expect(original.?.eql((try current).?));
try std.testing.expectEqual(before_nodes.count, after_nodes.count);
for (before_nodes.nodes[0..before_nodes.count], after_nodes.nodes[0..after_nodes.count]) |old, new| {
try std.testing.expectEqual(old.length, new.length);
@@ -6867,3 +6868,197 @@ test "source SSA zero OOM propagates with complete instruction prefixes and aren
if (!failing.has_induced_failure) break;
}
}
// Fails exactly one allocation, then recovers. A persistent failure could
// mask a false E7007 because allocating the diagnostic would fail as well.
const QueryAllocationFailure = struct {
backing: Allocator,
attempts: usize = 0,
fail_at: usize = 0,
failed: bool = false,
fn allocator(self: *@This()) Allocator {
return .{ .ptr = self, .vtable = &.{ .alloc = alloc, .resize = resize, .remap = remap, .free = free } };
}
fn alloc(raw: *anyopaque, len: usize, alignment: std.mem.Alignment, ra: usize) ?[*]u8 {
const self: *@This() = @ptrCast(@alignCast(raw));
self.attempts += 1;
if (!self.failed and self.attempts == self.fail_at + 1) {
self.failed = true;
return null;
}
return self.backing.rawAlloc(len, alignment, ra);
}
fn resize(_: *anyopaque, _: []u8, _: std.mem.Alignment, _: usize, _: usize) bool {
return false;
}
fn remap(_: *anyopaque, _: []u8, _: std.mem.Alignment, _: usize, _: usize) ?[*]u8 {
return null;
}
fn free(raw: *anyopaque, memory: []u8, alignment: std.mem.Alignment, ra: usize) void {
const self: *@This() = @ptrCast(@alignCast(raw));
self.backing.rawFree(memory, alignment, ra);
}
};
test "recovering host OOM escapes query callers without language diagnostics or AIR" {
for ([_]enum { negation, binary, cast, let_peek, let_use, range, field, match, length, assignment }{
.negation, .binary, .cast, .let_peek, .let_use, .range, .field, .match, .length, .assignment,
}) |mode| {
var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
const span = unaryTestSpan(19);
const literal: ast.Expr = .{ .span = span, .kind = .{ .int = .{ .text = "1i64" } } };
const unsuffixed: ast.Expr = .{ .span = span, .kind = .{ .int = .{ .text = "1" } } };
const name: ast.Expr = .{ .span = span, .kind = .{ .name = "n" } };
const sum: ast.Expr = .{ .span = span, .kind = .{ .binary = .{ .op = .add, .l = &literal, .r = &literal } } };
const hint: ast.Expr = .{ .span = span, .kind = .{ .binary = .{ .op = .add, .l = &name, .r = &literal } } };
const field: ast.Expr = .{ .span = span, .kind = .{ .field = .{ .e = &sum, .name = "x" } } };
const empty: ast.Block = .{ .span = span, .stmts = &.{}, .tail = null };
var l: Lowerer = .{ .arena = a, .m = .{ .name = "oom", .types = &.{}, .functions = &.{} }, .ret = .{ .int = "i64" } };
l.cur = try l.newBlock("entry", span);
try l.rest.append(a, .{ .stmts = &.{}, .tail = &hint });
var failure: QueryAllocationFailure = .{ .backing = a };
l.arena = failure.allocator();
const result: Error!void = switch (mode) {
.negation => blk: {
_ = l.expr(.{ .span = span, .kind = .{ .neg = &sum } }, null) catch |err| break :blk err;
},
.binary => blk: {
_ = l.expr(.{ .span = span, .kind = .{ .binary = .{ .op = .add, .l = &sum, .r = &literal } } }, null) catch |err| break :blk err;
},
.cast => blk: {
_ = l.expr(.{ .span = span, .kind = .{ .cast = .{ .mode = .checked, .e = &sum, .ty = .{ .span = span, .kind = .{ .name = "i64" } } } } }, null) catch |err| break :blk err;
},
.let_peek, .let_use => l.stmt(.{ .span = span, .kind = .{ .let = .{ .names = &.{"n"}, .ty = null, .e = if (mode == .let_use) unsuffixed else sum } } }),
.range => l.forLoop(span, "i", sum, unsuffixed, empty),
.field => blk: {
_ = l.fieldValue(field, sum, "x") catch |err| break :blk err;
},
.match => blk: {
_ = l.matchExpr(.{ .scrutinee = sum, .arms = &.{}, .span = span, .kind = .integer }, null) catch |err| break :blk err;
},
.length => blk: {
_ = l.lenOf(field, sum) catch |err| break :blk err;
},
.assignment => l.assignPlace(span, field, unsuffixed),
};
try std.testing.expect(failure.failed);
try std.testing.expectError(error.OutOfMemory, result);
try std.testing.expect(l.problem == null and l.unimpl == null);
try std.testing.expectEqual(@as(usize, 0), l.out.items.len);
try std.testing.expectEqual(@as(usize, 0), l.blocks.items[0].insts.items.len);
try std.testing.expectEqual(@as(usize, 1), failure.attempts);
}
}
test "query callback OOM stops annotations signatures and builtin output without fallback" {
for ([_]enum { annotation, field, callee, borrow_signature, call, use_signature, use_annotation, spawn, atomic, graph, freeze, arc }{
.annotation, .field, .callee, .borrow_signature, .call, .use_signature, .use_annotation, .spawn, .atomic, .graph, .freeze, .arc,
}) |mode| {
var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
const span = unaryTestSpan(23);
const byte: ast.Type = .{ .span = span, .kind = .{ .name = "u8" } };
const annotation: ast.Type = .{ .span = span, .kind = .{ .array = .{ .elem = &byte, .len = 7 } } };
const root: ast.Expr = .{ .span = span, .kind = .{ .name = "ns" } };
const qualified: ast.Expr = .{ .span = span, .kind = .{ .field = .{ .e = &root, .name = "worker" } } };
const worker: ast.Expr = .{ .span = span, .kind = .{ .name = "worker" } };
const name: ast.Expr = .{ .span = span, .kind = .{ .name = "n" } };
const scalar: ast.Expr = .{ .span = span, .kind = .{ .int = .{ .text = "1u8" } } };
const call: ast.Expr = .{ .span = span, .kind = .{ .call = .{ .callee = &qualified, .type_arg = null, .args = &.{name} } } };
var l: Lowerer = .{ .arena = a, .m = .{ .name = "oom", .types = &.{.{ .name = "S", .span = span, .kind = .{ .@"struct" = &.{.{ .name = "items", .span = span, .ty = annotation }} } }}, .functions = &.{} } };
const sig: FnSig = .{ .params = &.{.{ .int = "u8" }}, .ret = .{ .int = "u8" }, .air_name = "worker", .display_name = "worker" };
try l.sigs.put(a, "worker", sig);
try l.sigs.put(a, "ns.worker", sig);
const owned = try l.wrap(.own, .{ .int = "u8" });
try l.bindings.appendSlice(a, &.{
.{ .name = "graph", .value = "g", .mutable = false, .ty = try l.wrap(.mut, try l.wrap(.island, owned)) },
.{ .name = "island", .value = "i", .mutable = false, .ty = try l.wrap(.island, owned) },
.{ .name = "frozen", .value = "f", .mutable = false, .ty = try l.wrap(.frozen, owned) },
});
const output_failure = mode == .atomic or mode == .graph or mode == .freeze or mode == .arc;
var failure: QueryAllocationFailure = .{ .backing = a, .fail_at = if (output_failure) 1 else 0 };
l.arena = failure.allocator();
const result: Allocator.Error!void = switch (mode) {
.annotation => blk: {
_ = l.queryAnnotation(annotation) catch |err| break :blk err;
},
.field => blk: {
_ = l.queryField(.{ .named = 0 }, "items") catch |err| break :blk err;
},
.callee, .borrow_signature => blk: {
_ = (if (mode == .callee) l.calleeSig(qualified) else l.borrowReturnSig(qualified)) catch |err| break :blk err;
},
.call => blk: {
_ = l.peekType(call) catch |err| break :blk err;
},
.use_signature => blk: {
_ = l.useIn("n", call, null) catch |err| break :blk err;
},
.use_annotation => blk: {
_ = l.usesInStmt("n", .{ .span = span, .kind = .{ .@"var" = .{ .name = "v", .ty = annotation, .init = name } } }) catch |err| break :blk err;
},
.spawn => blk: {
_ = l.queryType(.{ .path = .{ .name = "task.spawn", .args = &.{ scalar, worker } } }) catch |err| break :blk err;
},
.atomic, .graph, .freeze, .arc => blk: {
const operation = switch (mode) {
.atomic => "atomic.new",
.graph => "island.root",
.freeze => "island.freeze",
.arc => "arc.from_frozen",
else => unreachable,
};
const argument: ast.Expr = if (mode == .atomic) scalar else .{ .span = span, .kind = .{ .name = switch (mode) {
.graph => "graph",
.freeze => "island",
.arc => "frozen",
else => unreachable,
} } };
_ = l.queryType(.{ .path = .{ .name = operation, .args = &.{argument} } }) catch |err| break :blk err;
},
};
try std.testing.expect(failure.failed);
try std.testing.expectError(error.OutOfMemory, result);
try std.testing.expectEqual(failure.fail_at + 1, failure.attempts);
try std.testing.expect(l.problem == null and l.unimpl == null);
try std.testing.expectEqual(@as(usize, 0), l.out.items.len);
try std.testing.expectEqual(@as(usize, 0), l.blocks.items.len);
}
}
test "public source lowering propagates each recovering allocation failure" {
const sources = [_][]const u8{
"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",
};
for (sources) |source| {
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer fixture.deinit();
const parsed = try parse_mod.parse(fixture.allocator(), source);
try std.testing.expect(parsed == .ok);
var fail_at: usize = 0;
while (true) : (fail_at += 1) {
try std.testing.expect(fail_at < 1024);
var output: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer output.deinit();
var failure: QueryAllocationFailure = .{ .backing = output.allocator(), .fail_at = fail_at };
const result = lower(failure.allocator(), parsed.ok);
if (failure.failed) {
// An error union carries no source Problem or public partial
// Output. The caller owns and destroys the output arena.
try std.testing.expectError(error.OutOfMemory, result);
try std.testing.expectEqual(fail_at + 1, failure.attempts);
} else {
const accepted = try result;
try std.testing.expect(accepted == .ok);
try std.testing.expect(accepted.ok.air.len != 0);
break;
}
}
}
}