cli: lower struct fields iteratively
This commit is contained in:
1 parent
0791a50eb9
commit
6d2c4d40a8
5 files changed
+557
-53
No files matched your search
+391
-51
@@ -2034,7 +2034,7 @@ const Lowerer = struct {
|
||||
.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)) {
|
||||
.done => |v| v,
|
||||
.ordinary => |c| l.operandExprPrepared(e, null, c),
|
||||
.ordinary => |c| l.operandExprPrepared(e, null, .{ .call = c }),
|
||||
},
|
||||
.if_expr => |x| return l.ifExpr(e.span, x.*, want),
|
||||
.block => |b| {
|
||||
@@ -2044,9 +2044,9 @@ const Lowerer = struct {
|
||||
.match_expr => |x| return l.matchExpr(x.*, want),
|
||||
.struct_lit => |x| return l.structLit(e, x.name, x.fields),
|
||||
.variant => |v| return l.variantValue(e, v.@"enum", v.name, &.{}),
|
||||
.field => |x| {
|
||||
if (std.mem.eql(u8, x.name, "len")) return l.lenOf(e, x.e.*);
|
||||
return l.fieldValue(e, x.e.*, x.name);
|
||||
.field => |x| return switch (try l.prepareFieldExpression(e, x.e.*, x.name)) {
|
||||
.done => |v| v,
|
||||
.read => |f| l.operandExprPrepared(e, null, .{ .field = f }),
|
||||
},
|
||||
.or_trap => |x| return l.orTrap(e, x.*),
|
||||
.move => |n| {
|
||||
@@ -2058,13 +2058,13 @@ const Lowerer = struct {
|
||||
}
|
||||
}
|
||||
|
||||
// Scalar operands and ordinary call arguments share one worklist so
|
||||
// alternating operator/call trees do not re-enter the native stack.
|
||||
// Scalar operands, ordinary calls, struct initializers and value fields
|
||||
// share one worklist for arbitrary alternation of those expression forms.
|
||||
fn operandExpr(l: *Lowerer, initial: ast.Expr, initial_want: ?Ty) Error!Value {
|
||||
return l.operandExprPrepared(initial, initial_want, null);
|
||||
return l.operandExprPrepared(initial, initial_want, .none);
|
||||
}
|
||||
|
||||
fn operandExprPrepared(l: *Lowerer, initial: ast.Expr, initial_want: ?Ty, initial_call: ?*OrdinaryCall) Error!Value {
|
||||
fn operandExprPrepared(l: *Lowerer, initial: ast.Expr, initial_want: ?Ty, initial_prepared: PreparedExpr) 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 },
|
||||
@@ -2072,30 +2072,57 @@ const Lowerer = struct {
|
||||
boolean_left: ast.Expr,
|
||||
boolean_right: struct { e: ast.Expr, join: usize, name: []const u8 },
|
||||
call_argument: *OrdinaryCall,
|
||||
struct_field: *StructConstruction,
|
||||
field_value: *FieldRead,
|
||||
};
|
||||
var pending: std.ArrayList(Frame) = .empty;
|
||||
defer pending.deinit(l.arena);
|
||||
var e = initial;
|
||||
var want = initial_want;
|
||||
var prepared_call = initial_call;
|
||||
var prepared = initial_prepared;
|
||||
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;
|
||||
switch (prepared) {
|
||||
.none => {},
|
||||
.call => |c| {
|
||||
prepared = .none;
|
||||
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;
|
||||
}
|
||||
try l.checkConsumingName(a);
|
||||
try pending.append(l.arena, .{ .call_argument = c });
|
||||
e = a;
|
||||
want = pt;
|
||||
continue;
|
||||
},
|
||||
.structure => |c| {
|
||||
prepared = .none;
|
||||
if (c.index == c.fields.len) break try l.finishStruct(c);
|
||||
const f = c.fields[c.index];
|
||||
const fi = for (c.inits) |*x| {
|
||||
if (std.mem.eql(u8, x.name, f.name)) break x;
|
||||
} else return l.invalid(.invalid_literal, c.span, "missing field", &.{ .{ .name = "type", .value = c.display_name }, .{ .name = "field", .value = f.name } });
|
||||
c.current_ty = try l.typeOf(f.ty);
|
||||
c.current_span = fi.e.span;
|
||||
try l.checkConsumingName(fi.e);
|
||||
try pending.append(l.arena, .{ .struct_field = c });
|
||||
e = fi.e;
|
||||
want = c.current_ty;
|
||||
continue;
|
||||
},
|
||||
.field => |f| {
|
||||
prepared = .none;
|
||||
try pending.append(l.arena, .{ .field_value = f });
|
||||
e = f.base;
|
||||
want = f.want;
|
||||
continue;
|
||||
},
|
||||
}
|
||||
switch (e.kind) {
|
||||
.not, .deref => |x| {
|
||||
@@ -2148,7 +2175,12 @@ const Lowerer = struct {
|
||||
},
|
||||
.call => |x| switch (try l.prepareCall(e, x.callee.*, x.args, false)) {
|
||||
.done => |v| break v,
|
||||
.ordinary => |c| prepared_call = c,
|
||||
.ordinary => |c| prepared = .{ .call = c },
|
||||
},
|
||||
.struct_lit => |x| prepared = .{ .structure = try l.prepareStruct(e, x.name, x.fields) },
|
||||
.field => |x| switch (try l.prepareFieldExpression(e, x.e.*, x.name)) {
|
||||
.done => |v| break v,
|
||||
.read => |f| prepared = .{ .field = f },
|
||||
},
|
||||
else => break try l.expr(e, want),
|
||||
}
|
||||
@@ -2229,11 +2261,19 @@ const Lowerer = struct {
|
||||
},
|
||||
.call_argument => |c| {
|
||||
try l.collectCallArgument(c, v);
|
||||
prepared_call = c;
|
||||
prepared = .{ .call = c };
|
||||
e = c.e;
|
||||
want = null;
|
||||
continue :evaluate;
|
||||
},
|
||||
.struct_field => |c| {
|
||||
try l.checkOperandTy(c.current_span, v.ty, c.current_ty);
|
||||
try c.names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (c.index == 0) "" else ", ", v.name }));
|
||||
c.index += 1;
|
||||
prepared = .{ .structure = c };
|
||||
continue :evaluate;
|
||||
},
|
||||
.field_value => |f| v = try l.finishField(f, v),
|
||||
};
|
||||
return v;
|
||||
}
|
||||
@@ -2283,6 +2323,13 @@ 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 PreparedExpr = union(enum) {
|
||||
none,
|
||||
call: *OrdinaryCall,
|
||||
structure: *StructConstruction,
|
||||
field: *FieldRead,
|
||||
};
|
||||
|
||||
const OrdinaryCall = struct {
|
||||
e: ast.Expr,
|
||||
callee: ast.Expr,
|
||||
@@ -2298,7 +2345,7 @@ const Lowerer = struct {
|
||||
fn call(l: *Lowerer, e: ast.Expr, callee: ast.Expr, args: []const ast.Expr, borrow_allowed: bool) Error!Value {
|
||||
return switch (try l.prepareCall(e, callee, args, borrow_allowed)) {
|
||||
.done => |v| v,
|
||||
.ordinary => |c| l.operandExprPrepared(e, null, c),
|
||||
.ordinary => |c| l.operandExprPrepared(e, null, .{ .call = c }),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2436,10 +2483,26 @@ const Lowerer = struct {
|
||||
return result;
|
||||
}
|
||||
|
||||
const StructConstruction = struct {
|
||||
span: Span,
|
||||
ty: Ty,
|
||||
display_name: []const u8,
|
||||
fields: []const ast.Field,
|
||||
inits: []const ast.FieldInit,
|
||||
index: usize = 0,
|
||||
current_ty: Ty = .void,
|
||||
current_span: Span = undefined,
|
||||
names: std.ArrayList(u8) = .empty,
|
||||
};
|
||||
|
||||
/// `Name { f: e, … }`: every field exactly once; initializers are
|
||||
/// evaluated in declaration order, so the AIR does not depend on the
|
||||
/// order the fields are written in (spec 15 §5).
|
||||
fn structLit(l: *Lowerer, e: ast.Expr, name: []const u8, inits: []const ast.FieldInit) Error!Value {
|
||||
return l.operandExprPrepared(e, null, .{ .structure = try l.prepareStruct(e, name, inits) });
|
||||
}
|
||||
|
||||
fn prepareStruct(l: *Lowerer, e: ast.Expr, name: []const u8, inits: []const ast.FieldInit) Error!*StructConstruction {
|
||||
const t = l.enumOrStruct(name, e.span) orelse return l.fail("E7002", e.span, "unknown type", &.{.{ .name = "name", .value = name }});
|
||||
const d = l.m.types[t.named];
|
||||
if (d.kind != .@"struct") return l.fail("E7005", e.span, "`Name { … }` constructs a struct; this is an enum (use `Enum::Variant`)", &.{.{ .name = "type", .value = d.display_name orelse name }});
|
||||
@@ -2451,17 +2514,13 @@ const Lowerer = struct {
|
||||
} else false;
|
||||
if (!known) return l.fail("E7002", fi.span, "no such field", &.{ .{ .name = "type", .value = d.display_name orelse name }, .{ .name = "field", .value = fi.name } });
|
||||
}
|
||||
var args: std.ArrayList(u8) = .empty;
|
||||
for (fields, 0..) |f, i| {
|
||||
const fi = for (inits) |x| {
|
||||
if (std.mem.eql(u8, x.name, f.name)) break x;
|
||||
} else return l.invalid(.invalid_literal, e.span, "missing field", &.{ .{ .name = "type", .value = d.display_name orelse name }, .{ .name = "field", .value = f.name } });
|
||||
const ft = try l.typeOf(f.ty);
|
||||
const v = try l.consuming(fi.e, ft);
|
||||
try l.checkOperandTy(fi.e.span, v.ty, ft);
|
||||
try args.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", v.name }));
|
||||
}
|
||||
return l.def("s", t, try l.fmt("struct.make {s}({s})", .{ try l.tyText(t), args.items }), e.span);
|
||||
const c = try l.arena.create(StructConstruction);
|
||||
c.* = .{ .span = e.span, .ty = t, .display_name = d.display_name orelse name, .fields = fields, .inits = inits };
|
||||
return c;
|
||||
}
|
||||
|
||||
fn finishStruct(l: *Lowerer, c: *const StructConstruction) Error!Value {
|
||||
return l.def("s", c.ty, try l.fmt("struct.make {s}({s})", .{ try l.tyText(c.ty), c.names.items }), c.span);
|
||||
}
|
||||
|
||||
fn variantValue(l: *Lowerer, e: ast.Expr, enum_name: []const u8, variant: []const u8, args: []const ast.Expr) Error!Value {
|
||||
@@ -2486,8 +2545,23 @@ const Lowerer = struct {
|
||||
return l.def("e", t, try l.fmt("enum.make {s}.{s}({s})", .{ try l.tyText(t), variant, names.items }), e.span);
|
||||
}
|
||||
|
||||
/// `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 {
|
||||
const FieldRead = struct {
|
||||
span: Span,
|
||||
base: ast.Expr,
|
||||
want: Ty,
|
||||
kind: union(enum) {
|
||||
nominal: struct { name: []const u8, declaration: []const u8, annotation: ast.Type },
|
||||
slice_length,
|
||||
},
|
||||
};
|
||||
const FieldDispatch = union(enum) { done: Value, read: *FieldRead };
|
||||
|
||||
fn prepareFieldExpression(l: *Lowerer, e: ast.Expr, base: ast.Expr, name: []const u8) Error!FieldDispatch {
|
||||
return if (std.mem.eql(u8, name, "len")) l.prepareLength(e, base) else l.prepareFieldValue(e, base, name);
|
||||
}
|
||||
|
||||
/// Field lookup precedes value lowering; borrow places finish immediately.
|
||||
fn prepareFieldValue(l: *Lowerer, e: ast.Expr, base: ast.Expr, name: []const u8) Error!FieldDispatch {
|
||||
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) }});
|
||||
@@ -2500,10 +2574,18 @@ const Lowerer = struct {
|
||||
const p = try l.placeBorrow(e, false, false, e.span);
|
||||
const v = try l.def(name, p.v.ty.inner().?, try l.fmt("load %{s}", .{p.v.name}), e.span);
|
||||
try l.endNow(p.ends, e.span);
|
||||
return v;
|
||||
return .{ .done = v };
|
||||
};
|
||||
const state = try l.arena.create(FieldRead);
|
||||
state.* = .{ .span = e.span, .base = base, .want = bt, .kind = .{ .nominal = .{ .name = name, .declaration = d.air_name orelse d.name, .annotation = f.ty } } };
|
||||
return .{ .read = state };
|
||||
}
|
||||
|
||||
fn finishField(l: *Lowerer, f: *const FieldRead, v: Value) Error!Value {
|
||||
return switch (f.kind) {
|
||||
.nominal => |n| l.def(n.name, try l.typeOf(n.annotation), try l.fmt("struct.get @{s}.{s}, %{s}", .{ n.declaration, n.name, v.name }), f.span),
|
||||
.slice_length => l.def("len", .{ .int = "usize" }, try l.fmt("slice.len %{s}", .{v.name}), f.span),
|
||||
};
|
||||
const v = try l.expr(base, bt);
|
||||
return l.def(name, try l.typeOf(f.ty), try l.fmt("struct.get @{s}.{s}, %{s}", .{ d.air_name orelse d.name, name, v.name }), e.span);
|
||||
}
|
||||
|
||||
/// One branch of a conditional or `match`: where it ended (null if it
|
||||
@@ -3043,19 +3125,20 @@ const Lowerer = struct {
|
||||
return t == .named or ((t == .ref or t == .mut) and t.inner().? == .named);
|
||||
}
|
||||
|
||||
/// `x.len`: a nominal field, `slice.len`, or the static array length.
|
||||
fn lenOf(l: *Lowerer, e: ast.Expr, base: ast.Expr) Error!Value {
|
||||
/// Nominal length fields, static array lengths and slice metadata reads.
|
||||
fn prepareLength(l: *Lowerer, e: ast.Expr, base: ast.Expr) Error!FieldDispatch {
|
||||
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");
|
||||
if (isNominalFieldBase(bt)) return l.prepareFieldValue(e, base, "len");
|
||||
const arr: ?u64 = switch (bt) {
|
||||
.array => |a| a.len,
|
||||
.ref, .mut => |x| if (x.* == .array) x.array.len else null,
|
||||
else => null,
|
||||
};
|
||||
if (arr) |n| return l.def("len", .{ .int = "usize" }, try l.fmt("const.usize {d}", .{n}), e.span);
|
||||
if (arr) |n| return .{ .done = try l.def("len", .{ .int = "usize" }, try l.fmt("const.usize {d}", .{n}), e.span) };
|
||||
if (bt != .slice and bt != .slice_mut) return l.fail("E7005", e.span, "`.len` needs an array or a slice", &.{.{ .name = "found", .value = try l.diagnosticTyText(bt) }});
|
||||
const s_ = try l.expr(base, bt);
|
||||
return l.def("len", .{ .int = "usize" }, try l.fmt("slice.len %{s}", .{s_.name}), e.span);
|
||||
const state = try l.arena.create(FieldRead);
|
||||
state.* = .{ .span = e.span, .base = base, .want = bt, .kind = .slice_length };
|
||||
return .{ .read = state };
|
||||
}
|
||||
|
||||
/// `let (left, right) = s.split_at(k);`: two disjoint borrows of `s`,
|
||||
@@ -5283,6 +5366,69 @@ const ReferenceCalls = struct {
|
||||
|
||||
// Independent pre-repair unary/binary expression derivation. Other leaves
|
||||
// share expression handlers; this oracle is only for shallow operand trees.
|
||||
// Copied former struct/field/length descent, linked to the independent
|
||||
// shallow scalar/call oracle. Borrow-place and array/variant helpers remain
|
||||
// shared and are outside this oracle's independence.
|
||||
const ReferenceFields = struct {
|
||||
fn structLit(l: *Lowerer, e: ast.Expr, name: []const u8, inits: []const ast.FieldInit) Error!Value {
|
||||
const t = l.enumOrStruct(name, e.span) orelse return l.fail("E7002", e.span, "unknown type", &.{.{ .name = "name", .value = name }});
|
||||
const d = l.m.types[t.named];
|
||||
if (d.kind != .@"struct") return l.fail("E7005", e.span, "`Name { … }` constructs a struct; this is an enum (use `Enum::Variant`)", &.{.{ .name = "type", .value = d.display_name orelse name }});
|
||||
const fields = d.kind.@"struct";
|
||||
for (inits, 0..) |fi, i| {
|
||||
for (inits[0..i]) |prev| if (std.mem.eql(u8, prev.name, fi.name)) return l.invalid(.invalid_literal, fi.span, "field given twice", &.{.{ .name = "field", .value = fi.name }});
|
||||
const known = for (fields) |f| {
|
||||
if (std.mem.eql(u8, f.name, fi.name)) break true;
|
||||
} else false;
|
||||
if (!known) return l.fail("E7002", fi.span, "no such field", &.{ .{ .name = "type", .value = d.display_name orelse name }, .{ .name = "field", .value = fi.name } });
|
||||
}
|
||||
var args: std.ArrayList(u8) = .empty;
|
||||
for (fields, 0..) |f, i| {
|
||||
const fi = for (inits) |x| {
|
||||
if (std.mem.eql(u8, x.name, f.name)) break x;
|
||||
} else return l.invalid(.invalid_literal, e.span, "missing field", &.{ .{ .name = "type", .value = d.display_name orelse name }, .{ .name = "field", .value = f.name } });
|
||||
const ft = try l.typeOf(f.ty);
|
||||
const v = try ReferenceCalls.consuming(l, fi.e, ft);
|
||||
try l.checkOperandTy(fi.e.span, v.ty, ft);
|
||||
try args.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", v.name }));
|
||||
}
|
||||
return l.def("s", t, try l.fmt("struct.make {s}({s})", .{ try l.tyText(t), args.items }), e.span);
|
||||
}
|
||||
|
||||
fn fieldValue(l: *Lowerer, e: ast.Expr, base: ast.Expr, name: []const u8) Error!Value {
|
||||
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 }});
|
||||
const f = for (d.kind.@"struct") |x| {
|
||||
if (std.mem.eql(u8, x.name, name)) break x;
|
||||
} else return l.fail("E7002", e.span, "no such field", &.{ .{ .name = "type", .value = d.display_name orelse d.name }, .{ .name = "field", .value = name } });
|
||||
// Through a borrow: borrow the field and load it.
|
||||
if (l.rootBinding(base)) |rb| if (rb.kind == .borrow) {
|
||||
const p = try l.placeBorrow(e, false, false, e.span);
|
||||
const v = try l.def(name, p.v.ty.inner().?, try l.fmt("load %{s}", .{p.v.name}), e.span);
|
||||
try l.endNow(p.ends, e.span);
|
||||
return v;
|
||||
};
|
||||
const v = try ReferenceOperands.expr(l, base, bt);
|
||||
return l.def(name, try l.typeOf(f.ty), try l.fmt("struct.get @{s}.{s}, %{s}", .{ d.air_name orelse d.name, name, v.name }), e.span);
|
||||
}
|
||||
|
||||
fn lenOf(l: *Lowerer, e: ast.Expr, base: ast.Expr) Error!Value {
|
||||
const bt = (try l.peekType(base)) orelse return l.fail("E7007", base.span, "the type of this expression cannot be determined", &.{});
|
||||
if (Lowerer.isNominalFieldBase(bt)) return fieldValue(l, e, base, "len");
|
||||
const arr: ?u64 = switch (bt) {
|
||||
.array => |a| a.len,
|
||||
.ref, .mut => |x| if (x.* == .array) x.array.len else null,
|
||||
else => null,
|
||||
};
|
||||
if (arr) |n| return l.def("len", .{ .int = "usize" }, try l.fmt("const.usize {d}", .{n}), e.span);
|
||||
if (bt != .slice and bt != .slice_mut) return l.fail("E7005", e.span, "`.len` needs an array or a slice", &.{.{ .name = "found", .value = try l.diagnosticTyText(bt) }});
|
||||
const s_ = try ReferenceOperands.expr(l, base, bt);
|
||||
return l.def("len", .{ .int = "usize" }, try l.fmt("slice.len %{s}", .{s_.name}), e.span);
|
||||
}
|
||||
};
|
||||
|
||||
const ReferenceOperands = struct {
|
||||
fn expr(l: *Lowerer, e: ast.Expr, want: ?Ty) Error!Value {
|
||||
switch (e.kind) {
|
||||
@@ -5336,6 +5482,8 @@ 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),
|
||||
.struct_lit => |x| return ReferenceFields.structLit(l, e, x.name, x.fields),
|
||||
.field => |x| return if (std.mem.eql(u8, x.name, "len")) ReferenceFields.lenOf(l, e, x.e.*) else ReferenceFields.fieldValue(l, e, x.e.*, x.name),
|
||||
.binary => |x| return binary(l, e, x.op, x.l.*, x.r.*, want),
|
||||
else => return l.expr(e, want),
|
||||
}
|
||||
@@ -7147,13 +7295,15 @@ test "recovering host OOM escapes query callers without language diagnostics or
|
||||
.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;
|
||||
_ = l.expr(field, null) 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;
|
||||
var length = field;
|
||||
length.kind.field.name = "len";
|
||||
_ = l.expr(length, null) catch |err| break :blk err;
|
||||
},
|
||||
.assignment => l.assignPlace(span, field, unsuffixed),
|
||||
};
|
||||
@@ -7249,6 +7399,7 @@ test "public source lowering propagates each recovering allocation failure" {
|
||||
"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>) -> i64 effects [] { return *p; }\nfn bytes(s: slice<u8>) -> 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",
|
||||
"module oom\nstruct Box { n: i64, len: i64 }\nfn main() -> i64 effects [] { var b: Box = Box { len: 2i64, n: 1i64 }; ref p = b; return (Box { len: p.len, n: p.n }).n; }\n",
|
||||
};
|
||||
for (sources) |source| {
|
||||
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
@@ -7464,3 +7615,192 @@ test "persistent backing OOM in public call lowering frees its output arena" {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn fieldTestLowerer(a: Allocator, m: ast.Module, span: Span) !Lowerer {
|
||||
var l = try callTestLowerer(a, span);
|
||||
l.m = m;
|
||||
const names = try a.alloc([]const u8, m.types.len);
|
||||
for (m.types, names) |decl, *name| name.* = try l.fmt("@{s}", .{decl.air_name orelse decl.name});
|
||||
l.typeNames = names;
|
||||
try l.checkRequirements();
|
||||
const box_ty: Ty = .{ .named = 0 };
|
||||
try l.bindings.appendSlice(a, &.{
|
||||
.{ .name = "box", .value = "box_value", .mutable = false, .ty = box_ty },
|
||||
.{ .name = "stored", .value = "box_storage", .mutable = true, .ty = box_ty, .kind = .storage },
|
||||
.{ .name = "borrowed", .value = "box_loan", .mutable = false, .ty = try l.wrap(.ref, box_ty), .kind = .borrow },
|
||||
.{ .name = "mutable", .value = "box_mut", .mutable = false, .ty = try l.wrap(.mut, box_ty), .kind = .borrow },
|
||||
.{ .name = "sl", .value = "slice_value", .mutable = false, .ty = try l.wrap(.slice, .{ .int = "u8" }), .kind = .borrow },
|
||||
});
|
||||
try l.borrow_parents.put(a, "box_loan", "box_storage");
|
||||
try l.sigs.put(a, "box_id", .{ .params = try a.dupe(Ty, &.{box_ty}), .ret = box_ty, .air_name = "box_id", .display_name = "box_id" });
|
||||
return l;
|
||||
}
|
||||
|
||||
const fieldTestDeclarations =
|
||||
"module fields\n" ++
|
||||
"struct Box { n: i64 }\n" ++
|
||||
"struct Length { len: i64 }\n" ++
|
||||
"struct Pair { first: i64, second: i64 }\n" ++
|
||||
"struct Nested { inner: Box }\n" ++
|
||||
"struct Owner { item: own<i64> }\n" ++
|
||||
"struct Empty {}\n" ++
|
||||
"enum Choice { some(i64), none }\n" ++
|
||||
"struct Bool { flag: bool }\n";
|
||||
|
||||
fn expectFieldMatches(a: Allocator, m: ast.Module, e: ast.Expr, want: ?Ty) !void {
|
||||
var old = try fieldTestLowerer(a, m, e.span);
|
||||
var current = try fieldTestLowerer(a, m, e.span);
|
||||
const expected = ReferenceOperands.expr(&old, e, want);
|
||||
const actual = current.expr(e, want);
|
||||
if (expected) |v| {
|
||||
const result = try actual;
|
||||
try std.testing.expectEqualStrings(v.name, result.name);
|
||||
try std.testing.expect(v.ty.eql(result.ty));
|
||||
} else |err| try std.testing.expectError(err, actual);
|
||||
try std.testing.expectEqualDeep(old.problem, current.problem);
|
||||
try std.testing.expectEqualDeep(old.unimpl, current.unimpl);
|
||||
try std.testing.expectEqualDeep(old.blocks.items, current.blocks.items);
|
||||
try std.testing.expectEqualDeep(old.allocs.items, current.allocs.items);
|
||||
try std.testing.expectEqualDeep(old.constants.items, current.constants.items);
|
||||
try std.testing.expectEqualDeep(old.bindings.items, current.bindings.items);
|
||||
try std.testing.expectEqual(old.counter, current.counter);
|
||||
try std.testing.expectEqual(old.cur, current.cur);
|
||||
try std.testing.expectEqualDeep(old.uses, current.uses);
|
||||
try std.testing.expectEqual(old.linear_enabled, current.linear_enabled);
|
||||
try std.testing.expectEqual(old.in_constant, current.in_constant);
|
||||
try std.testing.expectEqual(old.borrow_parents.count(), current.borrow_parents.count());
|
||||
var parents = old.borrow_parents.iterator();
|
||||
while (parents.next()) |item| try std.testing.expectEqualStrings(item.value_ptr.*, current.borrow_parents.get(item.key_ptr.*).?);
|
||||
}
|
||||
|
||||
test "struct field continuations match former declaration order and diagnostic priority" {
|
||||
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer fixture.deinit();
|
||||
const a = fixture.allocator();
|
||||
const expressions = [_][]const u8{
|
||||
"Box { n: 1i64 }", "Box { n: id(1i64) }.n", "Box { n: Box { n: n }.n }.n",
|
||||
"Nested { inner: Box { n: 1i64 } }.inner.n", "box.n", "stored.n",
|
||||
"borrowed.n", "mutable.n", "box_id(Box { n: 1i64 }).n",
|
||||
"Length { len: 2i64 }.len", "Length { len: unknown }.len", "Pair { second: id(2i64), first: id(1i64) }",
|
||||
"Pair { second: false, first: unknown }", "Pair { second: unknown, first: false }", "Pair { first: unknown, first: false, second: 1i64 }",
|
||||
"Pair { first: unknown, extra: false }", "Pair { first: 1i64 }", "Pair { second: unknown }",
|
||||
"Pair { second: 1i64 }", "Pair { first: unknown }.missing", "Box { n: unknown }.missing",
|
||||
"Empty {}", "Empty {}.n", "Choice {}",
|
||||
"Missing { n: unknown }", "unknown.n", "1i64.n",
|
||||
"Owner { item: o }", "Owner { item: move o }", "Owner { item: unknown }",
|
||||
"Box { n: void_call(b\"xy\") }", "Box { n: stop(b\"xy\") }", "Box { n: move n }",
|
||||
"Box { n: true }.n", "Box {}.n", "Choice::none.n",
|
||||
"Box { n: 1 }.n", "sl.len", "sl.n",
|
||||
"a.len", "[id(unknown); 2].len", "Box { n: 1 }.len",
|
||||
"not (Box { n: 1i64 }.n == id(1i64))", "Box { n: id(- (2i64 + Box { n: 1i64 }.n)) }.n", "bool_id(Box { n: 1i64 }.n == 1i64 and Box { n: 2i64 }.n == 2i64)",
|
||||
"Bool { flag: bool_id(true) and bool_id(false) }.flag", "Bool { flag: true }.flag or Bool { flag: bool_id(unknown) }.flag", "Bool { flag: Box { n: id(1i64) }.n == 1i64 or false }.flag",
|
||||
};
|
||||
const forms = [_][]const u8{ "{s}", "id({s})", "Box {{ n: {s} }}.n", "- ({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, "{s}fn f() -> void effects [] {{ return {s}; }}", .{ fieldTestDeclarations, expression });
|
||||
const parsed = try parse_mod.parse(a, source_text);
|
||||
if (parsed != .ok) std.debug.print("field test did not parse: {s}\n", .{expression});
|
||||
try std.testing.expect(parsed == .ok);
|
||||
const e = parsed.ok.functions[0].body.stmts[0].kind.@"return".?;
|
||||
for ([_]?Ty{ null, .{ .int = "i64" }, .{ .named = 0 } }) |want| try expectFieldMatches(a, parsed.ok, e, want);
|
||||
};
|
||||
}
|
||||
|
||||
test "deep struct fields share scalar and call continuations with exact emission spans" {
|
||||
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer fixture.deinit();
|
||||
const a = fixture.allocator();
|
||||
const m = (try parse_mod.parse(a, fieldTestDeclarations)).ok;
|
||||
const count = 32_768;
|
||||
for ([_]bool{ false, true }) |mixed| {
|
||||
const span = unaryTestSpan(1);
|
||||
var l = try fieldTestLowerer(a, m, 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 here = unaryTestSpan(@intCast(i + 1));
|
||||
if (mixed) {
|
||||
const args = try a.alloc(ast.Expr, 1);
|
||||
args[0] = e;
|
||||
const call = try a.create(ast.Expr);
|
||||
call.* = .{ .span = here, .kind = .{ .call = .{ .callee = &callee, .type_arg = null, .args = args } } };
|
||||
e = .{ .span = here, .kind = .{ .neg = call } };
|
||||
}
|
||||
const inits = try a.alloc(ast.FieldInit, 1);
|
||||
inits[0] = .{ .name = "n", .span = here, .e = e };
|
||||
const constructor = try a.create(ast.Expr);
|
||||
constructor.* = .{ .span = here, .kind = .{ .struct_lit = .{ .name = "Box", .fields = inits } } };
|
||||
e = .{ .span = here, .kind = .{ .field = .{ .e = constructor, .name = "n" } } };
|
||||
}
|
||||
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, 5) else 2) * count + 1), insts.len);
|
||||
const base: usize = if (mixed) count + 1 else 1;
|
||||
for (0..count) |i| {
|
||||
const index = base + (if (mixed) @as(usize, 4) else 2) * i;
|
||||
const make_index = index + (if (mixed) @as(usize, 2) else 0);
|
||||
try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(@intCast(i + 1))), insts[make_index].span);
|
||||
try std.testing.expect(std.mem.indexOf(u8, insts[make_index].text, " = struct.make @Box(") != null);
|
||||
try std.testing.expectEqualDeep(insts[make_index].span, insts[make_index + 1].span);
|
||||
try std.testing.expect(std.mem.indexOf(u8, insts[make_index + 1].text, " = struct.get @Box.n, ") != null);
|
||||
if (mixed) {
|
||||
try std.testing.expect(std.mem.indexOf(u8, insts[index].text, " = call @id(") != null);
|
||||
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 struct field continuations is never a source diagnosis" {
|
||||
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer fixture.deinit();
|
||||
const source_text = fieldTestDeclarations ++ "fn f() -> void effects [] { return Box { n: id(Box { n: n }.n) }.n; }";
|
||||
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 fieldTestLowerer(output.allocator(), parsed.ok, 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 struct field lowering frees output arena" {
|
||||
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer fixture.deinit();
|
||||
const parsed = try parse_mod.parse(fixture.allocator(), "module oom\nstruct Box { n: i64 }\nfn id(x: i64) -> i64 effects [] { return x; }\nfn main() -> i64 effects [] { return Box { n: id(- Box { n: 1i64 }.n) }.n; }\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 {
|
||||
// Returned bytes are dead; inspect only the result tag.
|
||||
try std.testing.expect((try result) == .ok);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user