cli: lower scalar index operands iteratively

This commit is contained in:
dev committed 2026-10-11 19:15:23 +03:00
1 parent 7ccded2b59
commit 29c1928aa1
5 files changed
+557 -14

No files matched your search

+352 -8
View File
@@ -1983,7 +1983,7 @@ const Lowerer = struct {
fn expr(l: *Lowerer, e: ast.Expr, want: ?Ty) Error!Value {
switch (e.kind) {
.not, .neg, .deref, .cast, .binary, .array_list, .array_rep => return l.operandExpr(e, want),
.not, .neg, .deref, .cast, .binary, .array_list, .array_rep, .index => return l.operandExpr(e, want),
.specialize => return l.invalid(.invalid_generic, e.span, "explicit type arguments require a generic function", &.{}),
.int => |x| {
const ty: Ty = if (parse_mod.intSuffix(x.text)) |s| .{ .int = s } else want orelse
@@ -2002,13 +2002,6 @@ const Lowerer = struct {
if (b.kind == .storage) return l.def(n, b.ty, try l.fmt("local.load %{s}", .{b.value}), e.span);
return .{ .name = b.value, .ty = b.ty };
},
.index => |x| {
if (x.hi != null) return l.invalid(.invalid_borrow, e.span, "a range `s[a..b]` is a borrow: bind it with `ref r = s[a..b];` or pass `ref s[a..b]`", &.{});
const p = try l.placeBorrow(e, false, false, e.span);
const v = try l.def("v", p.v.ty.inner().?, try l.fmt("load %{s}", .{p.v.name}), e.span);
try l.endNow(p.ends, e.span);
return v;
},
.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 switch (try l.prepareCall(e, x.callee.*, x.args, false)) {
@@ -2058,6 +2051,7 @@ const Lowerer = struct {
call_argument: *OrdinaryCall,
struct_field: *StructConstruction,
field_value: *FieldRead,
index_value: IndexRead,
array_element: *ArrayConstruction,
array_repeat: ast.Expr,
variant_argument: *VariantConstruction,
@@ -2245,6 +2239,12 @@ const Lowerer = struct {
.done => |v| break v,
.read => |f| prepared = .{ .field = f },
},
.index => {
const c = try l.prepareIndexRead(e);
try pending.append(l.arena, .{ .index_value = c });
e = c.input;
want = .{ .int = "usize" };
},
else => break try l.expr(e, want),
}
};
@@ -2360,6 +2360,7 @@ const Lowerer = struct {
.consuming_builtin => |c| v = try l.finishConsumingBuiltin(c, v),
.atomic => |c| v = try l.finishAtomic(c, v),
.field_value => |f| v = try l.finishField(f, v),
.index_value => |c| v = try l.finishIndexRead(c, v),
.array_element => |c| {
const input = c.inputs[c.index];
try l.arrayElement(input.span, v.ty, false);
@@ -2380,6 +2381,34 @@ const Lowerer = struct {
}
}
const IndexRead = struct { span: Span, input: ast.Expr, base: Placed, elem: Ty, unchecked: bool };
fn prepareIndexRead(l: *Lowerer, e: ast.Expr) Error!IndexRead {
const x = e.kind.index;
if (x.hi != null) return l.invalid(.invalid_borrow, e.span, "a range `s[a..b]` is a borrow: bind it with `ref r = s[a..b];` or pass `ref s[a..b]`", &.{});
const outer_unchecked = l.unchecked;
l.unchecked = false;
const base = try l.placeRaw(x.e.*, false, e.span);
l.unchecked = outer_unchecked;
const elem = elemOf(base.v.ty) orelse return l.fail("E7005", e.span, "indexing needs an array or a slice", &.{.{ .name = "found", .value = try l.diagnosticTyText(base.v.ty) }});
l.unchecked = false;
return .{ .span = e.span, .input = x.lo.*, .base = base, .elem = elem, .unchecked = outer_unchecked };
}
fn finishIndexRead(l: *Lowerer, c: IndexRead, i: Value) Error!Value {
try l.checkOperandTy(c.input.span, i.ty, .{ .int = "usize" });
const proven = for (l.facts.items) |f| {
if (std.mem.eql(u8, f.index, i.name) and std.mem.eql(u8, f.slice, c.base.v.name)) break true;
} else false;
if (c.unchecked) l.uses.insert(.unsafe);
const index_op = if (c.unchecked) "borrow.index.unchecked" else if (proven) "borrow.index.proven" else "borrow.index";
const v = try l.defBorrow("e", if (c.base.v.ty.isMutBorrow()) try l.wrap(.mut, c.elem) else try l.wrap(.ref, c.elem), try l.fmt("{s} %{s}, %{s}", .{ index_op, c.base.v.name, i.name }), c.base.v.name, c.span);
const ends = try l.concat(c.base.ends, v.name);
const result = try l.def("v", c.elem, try l.fmt("load %{s}", .{v.name}), c.span);
try l.endNow(ends, c.span);
return result;
}
// Both operands and their type checks are complete before this step.
fn binaryValue(l: *Lowerer, e: ast.Expr, ty: Ty, lv: Value, rv: Value) Error!Value {
const op = e.kind.binary.op;
@@ -5744,6 +5773,7 @@ const ReferenceOperands = struct {
};
return l.def("cast", to, try l.fmt("cast.{s}.{s} %{s}", .{ mode, to.int, v.name }), e.span);
},
.index => return ReferenceIndexPlaces.value(l, e),
.variant => |v| return ReferenceVariants.value(l, e, v.@"enum", v.name, &.{}),
.array_list, .array_rep => return ReferenceArrays.expr(l, e, want),
.call => |x| return ReferenceCalls.call(l, e, x.callee.*, x.args, false),
@@ -9447,3 +9477,317 @@ test "public mutex continuations propagate host OOM and free arena backing" {
}
}
}
// Copied pre-continuation place descent; type/borrow/emission helpers remain shared.
const ReferenceIndexPlaces = struct {
fn placeRaw(l: *Lowerer, place: ast.Expr, mutable: bool, span: Span) Error!Placed {
const op = if (mutable) "borrow.mut" else "borrow.ref";
switch (place.kind) {
.name => |n| {
const b = l.lookup(n) orelse return l.unknown(place.span, n);
switch (b.kind) {
.storage => {
const v = try l.def(n, if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty), try l.fmt("{s} %{s}", .{ op, b.value }), span);
return .{ .v = v, .ends = try l.arena.dupe([]const u8, &.{v.name}) };
},
.borrow => return .{ .v = .{ .name = b.value, .ty = b.ty }, .ends = &.{} },
.ssa => {
// A linear value (owner, region) is borrowed in place.
const bt: ?Ty = switch (b.ty) {
.named, .array => if (l.isLinear(b.ty)) (if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty)) else null,
.own => |in| if (mutable) try l.wrap(.mut, in.*) else try l.wrap(.ref, in.*),
.own_array => |in| if (mutable) try l.wrap(.slice_mut, in.*) else try l.wrap(.slice, in.*),
.buffer => if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty),
.region => if (mutable) try l.wrap(.mut, .region) else try l.wrap(.ref, .region),
.resource, .mutex, .sender, .receiver, .task, .island => if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty),
.frozen, .arc => if (mutable) return l.fail("E7005", place.span, "frozen graphs and arcs are immutable: borrow them with `ref`", &.{.{ .name = "name", .value = n }}) else try l.wrap(.ref, b.ty),
// Atomic operations go through a shared borrow (spec 04 §23).
.atomic => if (mutable) return l.fail("E7005", place.span, "an atomic cell is borrowed with `ref`: every atomic operation goes through a shared borrow", &.{.{ .name = "name", .value = n }}) else try l.wrap(.ref, b.ty),
else => null,
};
const t = bt orelse return l.invalid(.invalid_place, place.span, "this value is not addressable here; borrow a variable, a field or an element", &.{.{ .name = "name", .value = n }});
const v = try l.def(n, t, try l.fmt("{s} %{s}", .{ op, b.value }), span);
return .{ .v = v, .ends = try l.arena.dupe([]const u8, &.{v.name}) };
},
}
},
.bytes => |bytes| {
const st = try l.materializeBytes(bytes, place.span);
const v = try l.def("b", if (mutable) try l.wrap(.mut, st.ty) else try l.wrap(.ref, st.ty), try l.fmt("{s} %{s}", .{ op, st.name }), span);
return .{ .v = v, .ends = try l.arena.dupe([]const u8, &.{v.name}) };
},
.deref => |d| {
const r = try ReferenceOperands.expr(l, d.*, null);
if (!r.ty.isBorrow()) return l.fail("E7005", place.span, "`*` needs a borrow", &.{});
return .{ .v = r, .ends = &.{} };
},
.field => |f| {
const base = try placeRaw(l, f.e.*, mutable, span);
const st = base.v.ty.inner() orelse return l.fail("E7005", place.span, "field of a value that is not a struct", &.{});
const d = l.decl(st) orelse return l.fail("E7005", place.span, "field of a value that is not a struct", &.{.{ .name = "found", .value = try l.diagnosticTyText(st) }});
if (d.kind != .@"struct") return l.fail("E7005", place.span, "field of an enum; use `match`", &.{});
const fd = for (d.kind.@"struct") |x| {
if (std.mem.eql(u8, x.name, f.name)) break x;
} else return l.fail("E7002", place.span, "no such field", &.{ .{ .name = "type", .value = d.display_name orelse d.name }, .{ .name = "field", .value = f.name } });
const ft = try l.typeOf(fd.ty);
const v = try l.defBorrow(f.name, if (base.v.ty.isMutBorrow()) try l.wrap(.mut, ft) else try l.wrap(.ref, ft), try l.fmt("borrow.field @{s}.{s}, %{s}", .{ d.air_name orelse d.name, f.name, base.v.name }), base.v.name, span);
return .{ .v = v, .ends = try l.concat(base.ends, v.name) };
},
.index => |x| {
const outer_unchecked = l.unchecked;
l.unchecked = false;
const base = try placeRaw(l, x.e.*, mutable, span);
l.unchecked = outer_unchecked;
const bt = base.v.ty;
const elem = elemOf(bt) orelse return l.fail("E7005", place.span, "indexing needs an array or a slice", &.{.{ .name = "found", .value = try l.diagnosticTyText(bt) }});
if (x.hi) |hi| {
// `s[a..b]`: slice.sub with start a and length b - a (checked).
var sl = base.v;
var ends = base.ends;
if (bt == .ref or bt == .mut) {
sl = try l.defBorrow("s", (if (bt == .mut) try l.wrap(.slice_mut, elem) else try l.wrap(.slice, elem)), try l.fmt("slice.make %{s}", .{base.v.name}), base.v.name, span);
ends = try l.concat(ends, sl.name);
}
const a = try ReferenceOperands.expr(l, x.lo.*, .{ .int = "usize" });
try l.checkOperandTy(x.lo.span, a.ty, .{ .int = "usize" });
const b = try ReferenceOperands.expr(l, hi.*, .{ .int = "usize" });
try l.checkOperandTy(hi.span, b.ty, .{ .int = "usize" });
const len = try l.def("len", .{ .int = "usize" }, try l.fmt("sub.checked.usize %{s}, %{s}", .{ b.name, a.name }), span);
const sub_ = try l.defBorrow("s", sl.ty, try l.fmt("slice.sub %{s}, %{s}, %{s}", .{ sl.name, a.name, len.name }), sl.name, span);
return .{ .v = sub_, .ends = try l.concat(ends, sub_.name) };
}
// Only the outermost index of an unchecked place is unchecked.
const unchecked = l.unchecked;
l.unchecked = false;
const i = try ReferenceOperands.expr(l, x.lo.*, .{ .int = "usize" });
try l.checkOperandTy(x.lo.span, i.ty, .{ .int = "usize" });
const proven = for (l.facts.items) |f| {
if (std.mem.eql(u8, f.index, i.name) and std.mem.eql(u8, f.slice, base.v.name)) break true;
} else false;
if (unchecked) l.uses.insert(.unsafe);
const index_op = if (unchecked) "borrow.index.unchecked" else if (proven) "borrow.index.proven" else "borrow.index";
const v = try l.defBorrow("e", if (bt.isMutBorrow()) try l.wrap(.mut, elem) else try l.wrap(.ref, elem), try l.fmt("{s} %{s}, %{s}", .{ index_op, base.v.name, i.name }), base.v.name, span);
return .{ .v = v, .ends = try l.concat(base.ends, v.name) };
},
else => return l.invalid(.invalid_place, place.span, "not a place: borrow a variable, a field `x.f`, an element `s[i]` or a range `s[a..b]`", &.{}),
}
}
fn value(l: *Lowerer, e: ast.Expr) Error!Value {
if (e.kind.index.hi != null) return l.invalid(.invalid_borrow, e.span, "a range `s[a..b]` is a borrow: bind it with `ref r = s[a..b];` or pass `ref s[a..b]`", &.{});
const p = try placeRaw(l, e, false, e.span);
const v = try l.def("v", p.v.ty.inner().?, try l.fmt("load %{s}", .{p.v.name}), e.span);
try l.endNow(p.ends, e.span);
return v;
}
};
const indexTestDeclarations = fieldTestDeclarations ++ "struct Indexed { data: [usize; 1] }\nstruct Matrix { data: [[usize; 1]; 1] }\n";
fn indexTestLowerer(a: Allocator, m: ast.Module, span: Span) !Lowerer {
var l = try consumingTestLowerer(a, m, span);
const integer: Ty = .{ .int = "usize" };
const array = try l.arrayOf(integer, 1);
const indexed = l.enumOrStruct("Indexed", span).?;
try l.bindings.appendSlice(a, &.{
.{ .name = "ra", .value = "array_loan", .mutable = false, .ty = try l.wrap(.ref, array), .kind = .borrow },
.{ .name = "xs", .value = "index_storage", .mutable = false, .ty = array, .kind = .storage },
.{ .name = "ss", .value = "shared_slice", .mutable = false, .ty = try l.wrap(.slice, integer), .kind = .borrow },
.{ .name = "sm", .value = "exclusive_slice", .mutable = false, .ty = try l.wrap(.slice_mut, integer), .kind = .borrow },
.{ .name = "ix", .value = "known_index", .mutable = false, .ty = integer },
.{ .name = "indexed", .value = "indexed_storage", .mutable = false, .ty = indexed, .kind = .storage },
.{ .name = "matrix", .value = "matrix_storage", .mutable = false, .ty = l.enumOrStruct("Matrix", span).?, .kind = .storage },
.{ .name = "ir", .value = "indexed_loan", .mutable = false, .ty = try l.wrap(.ref, indexed), .kind = .borrow },
});
try l.sigs.put(a, "idx", .{ .params = try a.dupe(Ty, &.{integer}), .ret = integer, .air_name = "idx", .display_name = "idx" });
try l.facts.appendSlice(a, &.{ .{ .index = "known_index", .slice = "shared_slice" }, .{ .index = "known_index", .slice = "exclusive_slice" } });
try l.borrow_parents.put(a, "indexed_loan", "indexed_storage");
return l;
}
fn expectIndexMatches(a: Allocator, m: ast.Module, e: ast.Expr, want: ?Ty, unchecked: bool) !void {
var old = try indexTestLowerer(a, m, e.span);
var current = try indexTestLowerer(a, m, e.span);
old.unchecked = unchecked;
current.unchecked = unchecked;
const expected = ReferenceOperands.expr(&old, e, want);
const actual = current.expr(e, want);
if (expected) |v| {
const result = try actual;
try std.testing.expectEqualStrings(v.name, result.name);
try std.testing.expect(v.ty.eql(result.ty));
} else |err| try std.testing.expectError(err, actual);
try std.testing.expectEqualDeep(old.problem, current.problem);
try std.testing.expectEqualDeep(old.unimpl, current.unimpl);
try std.testing.expectEqualDeep(old.blocks.items, current.blocks.items);
try std.testing.expectEqualDeep(old.allocs.items, current.allocs.items);
try std.testing.expectEqualDeep(old.constants.items, current.constants.items);
try std.testing.expectEqualDeep(old.bindings.items, current.bindings.items);
try std.testing.expectEqual(old.unchecked, current.unchecked);
try std.testing.expectEqualDeep(old.facts.items, current.facts.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 "index continuations preserve former place priority loans facts unchecked and CFG" {
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer fixture.deinit();
const a = fixture.allocator();
const expressions = [_][]const u8{
"xs[o]", "(*ra)[xs[0]]", "(*ra)[unknown]", "(*ra)[o]",
"xs[0]", "xs[xs[0]]", "xs[idx(0usize)]", "xs[id(0i64)]",
"ss[ix]", "sm[ix]", "ss[0usize]", "sm[0usize]",
"indexed.data[0usize]", "ir.data[0usize]", "matrix.data[0usize][0usize]", "xs[ss[ix]]",
"ss[xs[sm[ix]]]", "xs[{ let ix: usize = 0usize; idx(ix) }]", "xs[if true { 0usize } else { 0usize }]", "xs[true and bool_id(false)]",
"xs[unknown]", "unknown[unknown]", "n[unknown]", "o[unknown]",
"p[unknown]", "indexed.data[true]", "xs[1i64]", "xs[ref n]",
"xs[b\"xy\"]", "xs[void_call(b\"xy\")]", "xs[stop(b\"xy\")]", "xs[move o]",
"xs[0usize..1usize]", "unknown[unknown..unknown]", "box.n[unknown]", "box.missing[unknown]",
"xs[xs[unknown]]", "xs[xs[true]]", "oa[0usize]", "xs[mutex.take(mutex.make(0usize))]",
"xs[[0usize][0usize]]",
};
const forms = [_][]const u8{ "{s}", "xs[{s}]", "idx({s})", "-{s}", "{s} as usize", "true and ({s})", "Box {{ n: {s} }}.n", "[{s}]" };
inline for (forms) |form| for (expressions) |text| {
const parsed = try parse_mod.parse(a, try std.fmt.allocPrint(a, "{s}fn f() -> void effects [] {{ return {s}; }}", .{ indexTestDeclarations, try std.fmt.allocPrint(a, form, .{text}) }));
try std.testing.expect(parsed == .ok);
const e = parsed.ok.functions[0].body.stmts[0].kind.@"return".?;
for ([_]?Ty{ null, .bool, .{ .int = "usize" } }) |want| for ([_]bool{ false, true }) |unchecked| try expectIndexMatches(a, parsed.ok, e, want, unchecked);
};
}
test "deep index operands keep borrow load end spans and partial error emission" {
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer fixture.deinit();
const a = fixture.allocator();
const m = (try parse_mod.parse(a, indexTestDeclarations)).ok;
const count = 32_768;
for (0..3) |leaf| {
var e: ast.Expr = .{ .span = unaryTestSpan(90_000), .kind = switch (leaf) {
0 => .{ .int = .{ .text = "0usize" } },
1 => .{ .name = "unknown" },
else => .{ .int = .{ .text = "0i64" } },
} };
for (0..count) |i| {
const base: ast.Expr = .{ .span = unaryTestSpan(@intCast(100_000 + i)), .kind = .{ .name = "xs" } };
const items = try a.dupe(ast.Expr, &.{ base, e });
e = .{ .span = unaryTestSpan(@intCast(i + 1)), .kind = .{ .index = .{ .e = &items[0], .lo = &items[1], .hi = null } } };
}
var l = try indexTestLowerer(a, m, e.span);
const counter = l.counter;
if (leaf != 0) {
try std.testing.expectError(error.Lower, l.expr(e, null));
try std.testing.expectEqualStrings(if (leaf == 1) "E7002" else "E7005", l.problem.?.code);
try std.testing.expectEqualDeep(unaryTestSpan(90_000), l.problem.?.span);
try std.testing.expectEqual(count + @as(usize, if (leaf == 1) 0 else 1), l.blocks.items[0].insts.items.len);
} else {
const v = try l.expr(e, null);
try std.testing.expect(v.ty.eql(.{ .int = "usize" }));
const insts = l.blocks.items[0].insts.items;
try std.testing.expectEqual(5 * count + 1, insts.len);
try std.testing.expectEqual(counter + 3 * count + 1, l.counter);
for (insts[0..count], 0..) |inst, i| {
try std.testing.expect(std.mem.indexOf(u8, inst.text, " = borrow.ref %index_storage") != null);
try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(@intCast(count - i))), inst.span);
}
try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(90_000)), insts[count].span);
for (0..count) |i| {
const start = count + 1 + 4 * i;
try std.testing.expect(std.mem.indexOf(u8, insts[start].text, " = borrow.index %") != null);
try std.testing.expect(std.mem.indexOf(u8, insts[start + 1].text, " = load %") != null);
try std.testing.expect(std.mem.startsWith(u8, insts[start + 2].text, "borrow.end %"));
try std.testing.expect(std.mem.startsWith(u8, insts[start + 3].text, "borrow.end %"));
for (insts[start .. start + 4]) |inst| try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(@intCast(i + 1))), inst.span);
}
}
}
}
test "public index operand continuation OOM stays host error with arena cleanup" {
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer fixture.deinit();
const programs = [_][]const u8{
"module oom\nfn main() -> usize effects [] { let a: [usize; 1] = [0usize]; return a[a[0usize]]; }\n",
"module oom\nfn main() -> usize effects [] { var a: [usize; 1] = [0usize]; mut s = a; return s[s[0usize]]; }\n",
"module oom\nfn main() -> usize effects [] { let a: [usize; 1] = [0usize]; return a[a[unknown]]; }\n",
"module oom\nfn main() -> usize effects [] { let a: [usize; 1] = [0usize]; return a[a[true]]; }\n",
"module oom\nfn main() -> usize effects [] { let n: usize = 0usize; return n[unknown]; }\n",
"module oom\nfn main() -> usize effects [] { let a: [usize; 1] = [0usize]; return a[0usize..1usize]; }\n",
};
for (programs, 0..) |program, index| {
const parsed = try parse_mod.parse(fixture.allocator(), program);
try std.testing.expect(parsed == .ok);
const baseline = try lower(fixture.allocator(), parsed.ok);
if (index < 2) try std.testing.expect(baseline == .ok) else {
try std.testing.expect(baseline == .err);
try std.testing.expectEqualStrings(switch (index) {
2 => "E7002",
5 => "E7006",
else => "E7005",
}, baseline.err.code);
}
for ([_]bool{ false, true }) |persistent| {
var fail_at: usize = 0;
while (true) : (fail_at += 1) {
try std.testing.expect(fail_at < 1024);
var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = fail_at });
var output: std.heap.ArenaAllocator = .init(if (persistent) failing.allocator() else std.testing.allocator);
var recovering: QueryAllocationFailure = .{ .backing = output.allocator(), .fail_at = fail_at };
const result = lower(if (persistent) output.allocator() else recovering.allocator(), parsed.ok);
output.deinit();
if (persistent) try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes);
const failed = if (persistent) failing.has_induced_failure else recovering.failed;
if (failed) {
try std.testing.expectError(error.OutOfMemory, result);
if (!persistent) try std.testing.expectEqual(fail_at + 1, recovering.attempts);
} else {
try std.testing.expect(std.meta.activeTag(try result) == std.meta.activeTag(baseline));
break;
}
}
}
}
}
test "grown index continuation stack propagates every allocation failure" {
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer fixture.deinit();
const a = fixture.allocator();
const m = (try parse_mod.parse(a, indexTestDeclarations)).ok;
const count = 64;
var e: ast.Expr = .{ .span = unaryTestSpan(90_000), .kind = .{ .int = .{ .text = "0usize" } } };
for (0..count) |i| {
const base: ast.Expr = .{ .span = unaryTestSpan(@intCast(100_000 + i)), .kind = .{ .name = "xs" } };
const items = try a.dupe(ast.Expr, &.{ base, e });
e = .{ .span = unaryTestSpan(@intCast(i + 1)), .kind = .{ .index = .{ .e = &items[0], .lo = &items[1], .hi = null } } };
}
var fail_at: usize = 0;
var later_prefix_failures: usize = 0;
while (true) : (fail_at += 1) {
try std.testing.expect(fail_at < 4096);
var backing: std.testing.FailingAllocator = .init(std.testing.allocator, .{});
var output: std.heap.ArenaAllocator = .init(backing.allocator());
var l = try indexTestLowerer(output.allocator(), m, e.span);
var failing: QueryAllocationFailure = .{ .backing = output.allocator(), .fail_at = fail_at };
l.arena = failing.allocator();
const result = l.expr(e, null);
if (failing.failed) {
try std.testing.expectError(error.OutOfMemory, result);
try std.testing.expectEqual(fail_at + 1, failing.attempts);
try std.testing.expect(l.problem == null and l.unimpl == null);
try std.testing.expectEqual(@as(usize, 0), l.out.items.len);
const emitted = l.blocks.items[0].insts.items.len;
if (emitted > 16 and emitted < count) later_prefix_failures += 1;
} else {
try std.testing.expect((try result).ty.eql(.{ .int = "usize" }));
}
output.deinit();
try std.testing.expectEqual(backing.allocated_bytes, backing.freed_bytes);
if (!failing.failed) break;
}
try std.testing.expect(later_prefix_failures > 0);
}