cli: lower scalar binary operands iteratively

This commit is contained in:
dev committed 2026-10-10 17:55:46 +03:00
1 parent e3f4695efe
commit 6945b511a4
5 files changed
+572 -117

No files matched your search

+419 -114
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 => return l.unaryExpr(e, want),
.not, .neg, .deref, .cast, .binary => 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
@@ -2032,7 +2032,6 @@ const Lowerer = struct {
},
.bytes => return l.invalid(.invalid_literal, e.span, "a byte string is an array in storage: bind it with `let`/`ref`, or pass it where a slice is expected", &.{}),
.borrow => return l.invalid(.invalid_borrow, e.span, "`ref`/`mut` here: borrows are bound with `ref name = place;` / `mut name = place;` or passed as arguments", &.{}),
.binary => |x| return l.binary(e, x.op, x.l.*, x.r.*, want),
.call => |x| return l.call(e, x.callee.*, x.args, false),
.if_expr => |x| return l.ifExpr(e.span, x.*, want),
.block => |b| {
@@ -2056,122 +2055,160 @@ const Lowerer = struct {
}
}
fn unaryExpr(l: *Lowerer, initial: ast.Expr, initial_want: ?Ty) Error!Value {
const Frame = struct { e: ast.Expr, ty: Ty = .void, zero: ?Value = null };
// Scalar unary and binary operands share one worklist so alternating
// operator trees do not re-enter the native stack through expr.
fn operandExpr(l: *Lowerer, initial: ast.Expr, initial_want: ?Ty) Error!Value {
const Frame = union(enum) {
unary: struct { e: ast.Expr, ty: Ty = .void, zero: ?Value = null },
binary_left: struct { e: ast.Expr, ty: Ty },
binary_right: struct { e: ast.Expr, ty: Ty, left: Value },
boolean_left: ast.Expr,
boolean_right: struct { e: ast.Expr, join: usize, name: []const u8 },
};
var pending: std.ArrayList(Frame) = .empty;
defer pending.deinit(l.arena);
var e = initial;
var want = initial_want;
var v: Value = while (true) {
switch (e.kind) {
.not, .deref => |x| {
try pending.append(l.arena, .{ .e = e });
want = if (e.kind == .not) .bool else null;
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", &.{});
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.
if (x.kind == .int) {
const bits = parse_mod.parseIntText(x.kind.int.text) orelse return l.fail("E7001", e.span, "malformed integer literal", &.{});
if (!isSigned(ty.int)) return l.fail("E7005", e.span, "negative literal of an unsigned type", &.{.{ .name = "type", .value = ty.int }});
const min_mag: u128 = @as(u128, 1) << @intCast(intBits(ty.int) - 1);
if (bits > min_mag) return l.fail("E7005", e.span, "integer literal out of range for its type", &.{.{ .name = "type", .value = ty.int }});
break try l.def("c", ty, try l.fmt("const.{s} -{d}", .{ ty.int, bits }), e.span);
}
// This zero precedes operand lowering, as before. Other
// unary instructions resume after their operand completes.
const zero = try l.def("zero", ty, try l.fmt("const.{s} 0", .{ty.int}), e.span);
try pending.append(l.arena, .{ .e = e, .ty = ty, .zero = zero });
want = ty;
e = x.*;
},
.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;
try pending.append(l.arena, .{ .e = e, .ty = to });
e = x.e.*;
},
else => break try l.expr(e, want),
}
};
while (pending.pop()) |frame| switch (frame.e.kind) {
.not => |x| {
try l.checkOperandTy(x.span, v.ty, .bool);
const t = try l.def("c", .bool, "const.bool true", frame.e.span);
v = try l.def("not", .bool, try l.fmt("xor.bool %{s}, %{s}", .{ v.name, t.name }), frame.e.span);
},
.neg => |x| {
try l.checkOperandTy(x.span, v.ty, frame.ty);
v = try l.def("neg", frame.ty, try l.fmt("sub.checked.{s} %{s}, %{s}", .{ frame.ty.int, frame.zero.?.name, v.name }), frame.e.span);
},
.deref => {
const in = v.ty.inner() orelse return l.fail("E7005", frame.e.span, "`*` reads through a borrow", &.{.{ .name = "found", .value = try l.diagnosticTyText(v.ty) }});
if (v.ty == .slice or v.ty == .slice_mut or in == .array) return l.invalid(.invalid_expression, frame.e.span, "read slice and array elements with `s[i]`, not `*`", &.{});
// Source-prescribed E4202 (spec 15 §12); no load is emitted.
if (in == .atomic) return l.fail("E4202", frame.e.span, "an atomic cell is read only by atomic operations: use `atomic.load(r, ordering)`", &.{
.{ .name = "found", .value = try l.diagnosticTyText(v.ty) },
.{ .name = "use", .value = "atomic.load" },
});
v = try l.def("v", in, try l.fmt("load %{s}", .{v.name}), frame.e.span);
},
.cast => |x| {
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) {
const from = std.meta.stringToEnum(air_module.IntType, v.ty.int).?;
const to = std.meta.stringToEnum(air_module.IntType, frame.ty.int).?;
if (!verifier_types.lossless(from, to)) return l.invalidWidening(frame.e.span, &.{ .{ .name = "from", .value = v.ty.int }, .{ .name = "to", .value = frame.ty.int } });
evaluate: while (true) {
var v: Value = while (true) {
switch (e.kind) {
.not, .deref => |x| {
try pending.append(l.arena, .{ .unary = .{ .e = e } });
want = if (e.kind == .not) .bool else null;
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", &.{});
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.
if (x.kind == .int) {
const bits = parse_mod.parseIntText(x.kind.int.text) orelse return l.fail("E7001", e.span, "malformed integer literal", &.{});
if (!isSigned(ty.int)) return l.fail("E7005", e.span, "negative literal of an unsigned type", &.{.{ .name = "type", .value = ty.int }});
const min_mag: u128 = @as(u128, 1) << @intCast(intBits(ty.int) - 1);
if (bits > min_mag) return l.fail("E7005", e.span, "integer literal out of range for its type", &.{.{ .name = "type", .value = ty.int }});
break try l.def("c", ty, try l.fmt("const.{s} -{d}", .{ ty.int, bits }), e.span);
}
// This zero precedes operand lowering, as before. Other
// unary instructions resume after their operand completes.
const zero = try l.def("zero", ty, try l.fmt("const.{s} 0", .{ty.int}), e.span);
try pending.append(l.arena, .{ .unary = .{ .e = e, .ty = ty, .zero = zero } });
want = ty;
e = x.*;
},
.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;
try pending.append(l.arena, .{ .unary = .{ .e = e, .ty = to } });
e = x.e.*;
},
.binary => |x| {
if (x.op == .@"and" or x.op == .@"or") {
try pending.append(l.arena, .{ .boolean_left = e });
want = .bool;
} else {
const cmp = switch (x.op) {
.eq, .ne, .lt, .le, .gt, .ge => true,
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 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;
}
e = x.l.*;
},
else => break try l.expr(e, want),
}
const mode = switch (x.mode) {
.widen => "widen",
.checked => "checked",
.wrap => "wrap",
};
v = try l.def("cast", frame.ty, try l.fmt("cast.{s}.{s} %{s}", .{ mode, frame.ty.int, v.name }), frame.e.span);
},
else => unreachable,
};
return v;
};
while (pending.pop()) |continuation| switch (continuation) {
.unary => |frame| switch (frame.e.kind) {
.not => |x| {
try l.checkOperandTy(x.span, v.ty, .bool);
const t = try l.def("c", .bool, "const.bool true", frame.e.span);
v = try l.def("not", .bool, try l.fmt("xor.bool %{s}, %{s}", .{ v.name, t.name }), frame.e.span);
},
.neg => |x| {
try l.checkOperandTy(x.span, v.ty, frame.ty);
v = try l.def("neg", frame.ty, try l.fmt("sub.checked.{s} %{s}, %{s}", .{ frame.ty.int, frame.zero.?.name, v.name }), frame.e.span);
},
.deref => {
const in = v.ty.inner() orelse return l.fail("E7005", frame.e.span, "`*` reads through a borrow", &.{.{ .name = "found", .value = try l.diagnosticTyText(v.ty) }});
if (v.ty == .slice or v.ty == .slice_mut or in == .array) return l.invalid(.invalid_expression, frame.e.span, "read slice and array elements with `s[i]`, not `*`", &.{});
// Source-prescribed E4202 (spec 15 §12); no load is emitted.
if (in == .atomic) return l.fail("E4202", frame.e.span, "an atomic cell is read only by atomic operations: use `atomic.load(r, ordering)`", &.{
.{ .name = "found", .value = try l.diagnosticTyText(v.ty) },
.{ .name = "use", .value = "atomic.load" },
});
v = try l.def("v", in, try l.fmt("load %{s}", .{v.name}), frame.e.span);
},
.cast => |x| {
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) {
const from = std.meta.stringToEnum(air_module.IntType, v.ty.int).?;
const to = std.meta.stringToEnum(air_module.IntType, frame.ty.int).?;
if (!verifier_types.lossless(from, to)) return l.invalidWidening(frame.e.span, &.{ .{ .name = "from", .value = v.ty.int }, .{ .name = "to", .value = frame.ty.int } });
}
const mode = switch (x.mode) {
.widen => "widen",
.checked => "checked",
.wrap => "wrap",
};
v = try l.def("cast", frame.ty, try l.fmt("cast.{s}.{s} %{s}", .{ mode, frame.ty.int, v.name }), frame.e.span);
},
else => unreachable,
},
.binary_left => |frame| {
const x = frame.e.kind.binary;
try l.checkOperandTy(x.l.span, v.ty, frame.ty);
try pending.append(l.arena, .{ .binary_right = .{ .e = frame.e, .ty = frame.ty, .left = v } });
e = x.r.*;
want = frame.ty;
continue :evaluate;
},
.binary_right => |frame| {
try l.checkOperandTy(frame.e.kind.binary.r.span, v.ty, frame.ty);
v = try l.binaryValue(frame.e, frame.ty, frame.left, v);
},
.boolean_left => |parent| {
const x = parent.kind.binary;
const lv = v;
try l.checkOperandTy(x.l.span, lv.ty, .bool);
const short = try l.def("c", .bool, if (x.op == .@"and") "const.bool false" else "const.bool true", parent.span);
const rhs_b = try l.newBlock(if (x.op == .@"and") "and_rhs" else "or_rhs", x.r.span);
const join = try l.newBlock(if (x.op == .@"and") "and_end" else "or_end", parent.span);
const rname = try l.freshName(if (x.op == .@"and") "and" else "or");
try l.blocks.items[join].params.append(l.arena, .{ .name = rname, .ty = .bool });
const jn = l.blocks.items[join].name;
if (x.op == .@"and") {
try l.term(try l.fmt("cbr %{s}, @{s}(), @{s}(%{s})", .{ lv.name, l.blocks.items[rhs_b].name, jn, short.name }), parent.span);
} else try l.term(try l.fmt("cbr %{s}, @{s}(%{s}), @{s}()", .{ lv.name, jn, short.name, l.blocks.items[rhs_b].name }), parent.span);
l.cur = rhs_b;
try pending.append(l.arena, .{ .boolean_right = .{ .e = parent, .join = join, .name = rname } });
e = x.r.*;
want = .bool;
continue :evaluate;
},
.boolean_right => |frame| {
try l.checkOperandTy(frame.e.kind.binary.r.span, v.ty, .bool);
try l.term(try l.fmt("br @{s}(%{s})", .{ l.blocks.items[frame.join].name, v.name }), frame.e.span);
l.cur = frame.join;
v = .{ .name = frame.name, .ty = .bool };
},
};
return v;
}
}
fn binary(l: *Lowerer, e: ast.Expr, op: ast.BinOp, a: ast.Expr, b: ast.Expr, want: ?Ty) Error!Value {
switch (op) {
.@"and", .@"or" => {
// Short-circuit: the right operand runs only when needed.
const lv = try l.expr(a, .bool);
try l.checkOperandTy(a.span, lv.ty, .bool);
const short = try l.def("c", .bool, if (op == .@"and") "const.bool false" else "const.bool true", e.span);
const rhs_b = try l.newBlock(if (op == .@"and") "and_rhs" else "or_rhs", b.span);
const join = try l.newBlock(if (op == .@"and") "and_end" else "or_end", e.span);
const rname = try l.freshName(if (op == .@"and") "and" else "or");
try l.blocks.items[join].params.append(l.arena, .{ .name = rname, .ty = .bool });
const jn = l.blocks.items[join].name;
if (op == .@"and") {
try l.term(try l.fmt("cbr %{s}, @{s}(), @{s}(%{s})", .{ lv.name, l.blocks.items[rhs_b].name, jn, short.name }), e.span);
} else try l.term(try l.fmt("cbr %{s}, @{s}(%{s}), @{s}()", .{ lv.name, jn, short.name, l.blocks.items[rhs_b].name }), e.span);
l.cur = rhs_b;
const rv = try l.expr(b, .bool);
try l.checkOperandTy(b.span, rv.ty, .bool);
try l.term(try l.fmt("br @{s}(%{s})", .{ jn, rv.name }), e.span);
l.cur = join;
return .{ .name = rname, .ty = .bool };
},
else => {},
}
// 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;
const cmp = switch (op) {
.eq, .ne, .lt, .le, .gt, .ge => true,
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 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 l.expr(a, ty);
try l.checkOperandTy(a.span, lv.ty, ty);
const rv = try l.expr(b, ty);
try l.checkOperandTy(b.span, rv.ty, ty);
// `iref` identity (spec 03 §22): equal graph and slot; never a trap.
if (ty == .iref) {
if (op != .eq and op != .ne) return l.fail("E7005", e.span, "`iref` handles are compared with `==` and `!=` only", &.{});
@@ -5032,9 +5069,9 @@ test "deep callee paths own one complete string and bounded lookup stays flat" {
try std.testing.expect(!fail.has_induced_failure);
}
// Independent pre-repair unary expression derivation. Non-unary leaves use
// the unchanged expression handlers; this oracle is only for shallow chains.
const ReferenceUnary = struct {
// Independent pre-repair unary/binary expression derivation. Other leaves
// share expression handlers; this oracle is only for shallow operand trees.
const ReferenceOperands = struct {
fn expr(l: *Lowerer, e: ast.Expr, want: ?Ty) Error!Value {
switch (e.kind) {
.not => |x| {
@@ -5086,12 +5123,84 @@ const ReferenceUnary = struct {
};
return l.def("cast", to, try l.fmt("cast.{s}.{s} %{s}", .{ mode, to.int, v.name }), e.span);
},
.binary => |x| return binary(l, e, x.op, x.l.*, x.r.*, want),
else => return l.expr(e, want),
}
}
fn binary(l: *Lowerer, e: ast.Expr, op: ast.BinOp, a: ast.Expr, b: ast.Expr, want: ?Ty) Error!Value {
switch (op) {
.@"and", .@"or" => {
// Short-circuit: the right operand runs only when needed.
const lv = try expr(l, a, .bool);
try l.checkOperandTy(a.span, lv.ty, .bool);
const short = try l.def("c", .bool, if (op == .@"and") "const.bool false" else "const.bool true", e.span);
const rhs_b = try l.newBlock(if (op == .@"and") "and_rhs" else "or_rhs", b.span);
const join = try l.newBlock(if (op == .@"and") "and_end" else "or_end", e.span);
const rname = try l.freshName(if (op == .@"and") "and" else "or");
try l.blocks.items[join].params.append(l.arena, .{ .name = rname, .ty = .bool });
const jn = l.blocks.items[join].name;
if (op == .@"and") {
try l.term(try l.fmt("cbr %{s}, @{s}(), @{s}(%{s})", .{ lv.name, l.blocks.items[rhs_b].name, jn, short.name }), e.span);
} else try l.term(try l.fmt("cbr %{s}, @{s}(%{s}), @{s}()", .{ lv.name, jn, short.name, l.blocks.items[rhs_b].name }), e.span);
l.cur = rhs_b;
const rv = try expr(l, b, .bool);
try l.checkOperandTy(b.span, rv.ty, .bool);
try l.term(try l.fmt("br @{s}(%{s})", .{ jn, rv.name }), e.span);
l.cur = join;
return .{ .name = rname, .ty = .bool };
},
else => {},
}
const cmp = switch (op) {
.eq, .ne, .lt, .le, .gt, .ge => true,
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 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);
const rv = try expr(l, b, ty);
try l.checkOperandTy(b.span, rv.ty, ty);
// `iref` identity (spec 03 §22): equal graph and slot; never a trap.
if (ty == .iref) {
if (op != .eq and op != .ne) return l.fail("E7005", e.span, "`iref` handles are compared with `==` and `!=` only", &.{});
const c = try l.def("cmp", .bool, try l.fmt("iref.eq %{s}, %{s}", .{ lv.name, rv.name }), e.span);
if (op == .eq) return c;
const t = try l.def("c", .bool, "const.bool true", e.span);
return l.def("cmp", .bool, try l.fmt("xor.bool %{s}, %{s}", .{ c.name, t.name }), e.span);
}
if (ty == .bool and !(op == .eq or op == .ne or op == .bit_and or op == .bit_or or op == .bit_xor))
return l.fail("E7005", e.span, "this operation needs integer operands", &.{});
if (ty != .bool and ty != .int) return l.fail("E7005", e.span, "this operation needs integer or boolean operands", &.{});
const t = try l.tyText(ty);
const text = switch (op) {
.add => try l.fmt("add.checked.{s}", .{t}),
.sub => try l.fmt("sub.checked.{s}", .{t}),
.mul => try l.fmt("mul.checked.{s}", .{t}),
.div => try l.fmt("div.checked.{s}", .{t}),
.rem => try l.fmt("rem.checked.{s}", .{t}),
.add_wrap => try l.fmt("add.wrap.{s}", .{t}),
.sub_wrap => try l.fmt("sub.wrap.{s}", .{t}),
.mul_wrap => try l.fmt("mul.wrap.{s}", .{t}),
.bit_and => try l.fmt("and.{s}", .{t}),
.bit_or => try l.fmt("or.{s}", .{t}),
.bit_xor => try l.fmt("xor.{s}", .{t}),
.shl => try l.fmt("shl.{s}", .{t}),
.shr => try l.fmt("shr.{s}", .{t}),
.eq => try l.fmt("eq.{s}", .{t}),
.ne => try l.fmt("ne.{s}", .{t}),
.lt => try l.fmt("lt.{s}", .{t}),
.le => try l.fmt("le.{s}", .{t}),
.gt => try l.fmt("gt.{s}", .{t}),
.ge => try l.fmt("ge.{s}", .{t}),
.@"and", .@"or" => unreachable,
};
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);
}
};
fn expectUnaryMatches(a: Allocator, e: ast.Expr, want: ?Ty, bindings: []const Binding) !void {
fn expectOperandMatches(a: Allocator, e: ast.Expr, want: ?Ty, bindings: []const Binding) !void {
const m: ast.Module = .{ .name = "unary", .types = &.{}, .functions = &.{} };
const parameter: ast.Param = .{ .name = "c_1", .ty = .{ .span = e.span, .kind = .{ .name = "bool" } }, .span = e.span };
var old: Lowerer = .{ .arena = a, .m = m, .params = &.{parameter}, .in_constant = 7 };
@@ -5100,7 +5209,7 @@ fn expectUnaryMatches(a: Allocator, e: ast.Expr, want: ?Ty, bindings: []const Bi
try current.bindings.appendSlice(a, bindings);
old.cur = try old.newBlock("entry", e.span);
current.cur = try current.newBlock("entry", e.span);
const expected = ReferenceUnary.expr(&old, e, want);
const expected = ReferenceOperands.expr(&old, e, want);
const actual = current.expr(e, want);
if (expected) |v| {
const result = try actual;
@@ -5111,6 +5220,7 @@ fn expectUnaryMatches(a: Allocator, e: ast.Expr, want: ?Ty, bindings: []const Bi
try std.testing.expectEqualDeep(old.unimpl, current.unimpl);
try std.testing.expectEqualDeep(old.blocks.items, current.blocks.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);
}
@@ -5134,10 +5244,205 @@ test "unary expression lowering preserves instruction order and diagnostic prior
const parsed = try parse_mod.parseWithFile(a, source, "unary.aji");
try std.testing.expect(parsed == .ok);
const e = parsed.ok.functions[0].body.stmts[0].kind.@"return".?;
for ([_]?Ty{ null, .bool, .{ .int = "i64" }, .{ .int = "u8" } }) |want| try expectUnaryMatches(a, e, want, &bindings);
for ([_]?Ty{ null, .bool, .{ .int = "i64" }, .{ .int = "u8" } }) |want| try expectOperandMatches(a, e, want, &bindings);
};
}
test "binary operand continuations match old typing CFG emission and failure priority" {
var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
const span = unaryTestSpan(1);
var builder: Lowerer = .{ .arena = a, .m = .{ .name = "operands", .types = &.{}, .functions = &.{} } };
const bindings = [_]Binding{
.{ .name = "p", .value = "pointer", .mutable = false, .ty = try builder.wrap(.ref, .{ .int = "i64" }) },
.{ .name = "atomic", .value = "cell", .mutable = false, .ty = try builder.wrap(.ref, try builder.wrap(.atomic, .{ .int = "u64" })) },
.{ .name = "handle", .value = "handle", .mutable = false, .ty = try builder.wrap(.iref, .{ .int = "u8" }) },
};
const p: ast.Expr = .{ .span = unaryTestSpan(4), .kind = .{ .name = "p" } };
const atomic: ast.Expr = .{ .span = unaryTestSpan(4), .kind = .{ .name = "atomic" } };
const trapped: ast.Block = .{ .span = span, .stmts = &.{.{ .span = span, .kind = .trap }}, .tail = null };
const leaves = [_]ast.Expr{
.{ .span = unaryTestSpan(3), .kind = .{ .int = .{ .text = "1i64" } } },
.{ .span = unaryTestSpan(4), .kind = .{ .int = .{ .text = "1u8" } } },
.{ .span = unaryTestSpan(5), .kind = .{ .boolean = true } },
.{ .span = unaryTestSpan(6), .kind = .{ .name = "handle" } },
p,
.{ .span = unaryTestSpan(7), .kind = .{ .int = .{ .text = "1" } } },
.{ .span = unaryTestSpan(8), .kind = .{ .name = "unknown" } },
.{ .span = unaryTestSpan(9), .kind = .{ .block = &trapped } },
.{ .span = unaryTestSpan(10), .kind = .{ .int = .{ .text = "256u8" } } },
.{ .span = unaryTestSpan(11), .kind = .{ .deref = &atomic } },
};
const pairs = [_][2]usize{
.{ 0, 0 }, .{ 1, 1 }, .{ 2, 2 }, .{ 3, 3 }, .{ 4, 4 }, .{ 5, 0 }, .{ 0, 5 }, .{ 6, 7 }, .{ 7, 6 },
.{ 2, 6 }, .{ 0, 2 }, .{ 2, 0 }, .{ 8, 6 }, .{ 6, 8 }, .{ 9, 0 }, .{ 0, 9 }, .{ 5, 5 }, .{ 7, 2 },
};
inline for (std.meta.tags(ast.BinOp)) |op| for (pairs) |pair| {
const base: ast.Expr = .{ .span = span, .kind = .{ .binary = .{ .op = op, .l = &leaves[pair[0]], .r = &leaves[pair[1]] } } };
const neg: ast.Expr = .{ .span = span, .kind = .{ .neg = &base } };
const logical: ast.Expr = .{ .span = span, .kind = .{ .not = &base } };
const cast: ast.Expr = .{ .span = span, .kind = .{ .cast = .{ .mode = .checked, .e = &base, .ty = .{ .span = span, .kind = .{ .name = "u8" } } } } };
// Wrappers exercise shared unary/binary suspension, including a
// target whose expected type differs from the queried operand type.
for ([_]ast.Expr{ base, neg, logical, cast }) |e| for ([_]?Ty{ null, .bool, .{ .int = "i64" }, .{ .int = "u8" } }) |want|
try expectOperandMatches(a, e, want, &bindings);
};
}
test "deep left right and alternating operand trees emit in their original order" {
var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
const m: ast.Module = .{ .name = "deep", .types = &.{}, .functions = &.{} };
const literal: ast.Expr = .{ .span = unaryTestSpan(90_000), .kind = .{ .int = .{ .text = "1i64" } } };
const count = 32_768;
for ([_]enum { left, right, mixed }{ .left, .right, .mixed }) |shape| {
var l: Lowerer = .{ .arena = a, .m = m };
try l.bindings.append(a, .{ .name = "n", .value = "input", .mutable = false, .ty = .{ .int = "i64" } });
l.cur = try l.newBlock("entry", unaryTestSpan(1));
var e: ast.Expr = .{ .span = unaryTestSpan(90_001), .kind = .{ .name = "n" } };
for (0..count) |i| {
const inner = try a.create(ast.Expr);
inner.* = e;
const span = unaryTestSpan(@intCast(i + 1));
var operand = inner;
if (shape == .mixed) {
operand = try a.create(ast.Expr);
operand.* = .{ .span = span, .kind = .{ .neg = inner } };
}
e = .{ .span = span, .kind = .{ .binary = .{ .op = .add, .l = if (shape == .right) &literal else operand, .r = if (shape == .right) operand else &literal } } };
}
const value = try l.expr(e, .{ .int = "i64" });
try std.testing.expect(value.ty.eql(.{ .int = "i64" }));
const insts = l.blocks.items[0].insts.items;
try std.testing.expectEqual(@as(usize, if (shape == .mixed) 4 * count else 2 * count), insts.len);
for (0..count) |i| {
const at = if (shape == .left) 2 * i + 1 else if (shape == .right) count + i else count + 3 * i + 2;
try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(@intCast(i + 1))), insts[at].span);
try std.testing.expect(std.mem.indexOf(u8, insts[at].text, " = add.checked.i64 ") != null);
if (shape == .mixed) {
try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(@intCast(count - i))), insts[i].span);
try std.testing.expect(std.mem.endsWith(u8, insts[i].text, " = const.i64 0"));
} else {
const previous = if (i == 0) "input" else try std.fmt.allocPrint(a, "t_{d}", .{if (shape == .left) 2 * i else count + i});
const expected = if (shape == .left)
try std.fmt.allocPrint(a, "%t_{d} = add.checked.i64 %{s}, %c_{d}", .{ 2 * i + 2, previous, 2 * i + 1 })
else
try std.fmt.allocPrint(a, "%t_{d} = add.checked.i64 %c_{d}, %{s}", .{ count + i + 1, count - i, previous });
try std.testing.expectEqualStrings(expected, insts[at].text);
}
}
try std.testing.expect(l.problem == null);
try std.testing.expectEqual(@as(usize, 0), l.out.items.len);
}
}
test "deep boolean operands retain RHS blocks join parameters and suspended unary parents" {
var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
const m: ast.Module = .{ .name = "deep", .types = &.{}, .functions = &.{} };
const literal: ast.Expr = .{ .span = unaryTestSpan(90_000), .kind = .{ .boolean = true } };
const count = 16_384;
for ([_]bool{ false, true }) |right| {
var l: Lowerer = .{ .arena = a, .m = m };
l.cur = try l.newBlock("entry", unaryTestSpan(1));
var e = literal;
for (0..count) |i| {
const inner = try a.create(ast.Expr);
inner.* = e;
const span = unaryTestSpan(@intCast(i + 1));
const binary = try a.create(ast.Expr);
binary.* = .{ .span = span, .kind = .{ .binary = .{ .op = if (i % 2 == 0) .@"and" else .@"or", .l = if (right) &literal else inner, .r = if (right) inner else &literal } } };
e = .{ .span = span, .kind = .{ .not = binary } };
}
const result = try l.expr(e, .bool);
try std.testing.expect(result.ty == .bool);
try std.testing.expectEqual(@as(usize, 2 * count + 1), l.blocks.items.len);
var cbrs: usize = 0;
var branches: usize = 0;
var inversions: usize = 0;
for (l.blocks.items, 0..) |b, index| {
try std.testing.expectEqual(index != l.cur.?, b.terminated);
if (index != 0 and index % 2 == 0) {
try std.testing.expectEqual(@as(usize, 1), b.params.items.len);
try std.testing.expect(b.params.items[0].ty == .bool);
} else try std.testing.expectEqual(@as(usize, 0), b.params.items.len);
for (b.insts.items) |inst| {
if (std.mem.startsWith(u8, inst.text, "cbr ")) cbrs += 1;
if (std.mem.startsWith(u8, inst.text, "br ")) branches += 1;
if (std.mem.indexOf(u8, inst.text, " = xor.bool ") != null) inversions += 1;
}
}
try std.testing.expectEqual(@as(usize, count), cbrs);
try std.testing.expectEqual(@as(usize, count), branches);
try std.testing.expectEqual(@as(usize, count), inversions);
try std.testing.expect(l.problem == null);
try std.testing.expectEqual(@as(usize, 0), l.out.items.len);
}
}
test "operand continuation OOM retains complete block prefixes and no output" {
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer fixture.deinit();
const a = fixture.allocator();
const span = unaryTestSpan(1);
const m: ast.Module = .{ .name = "oom", .types = &.{}, .functions = &.{} };
const one: ast.Expr = .{ .span = span, .kind = .{ .int = .{ .text = "1i64" } } };
const yes: ast.Expr = .{ .span = span, .kind = .{ .boolean = true } };
for ([_]bool{ false, true }) |logical| {
var e = if (logical) yes else one;
for (0..64) |i| {
const inner = try a.create(ast.Expr);
inner.* = e;
const binary = try a.create(ast.Expr);
binary.* = .{ .span = span, .kind = .{ .binary = .{
.op = if (logical) (if (i % 2 == 0) .@"and" else .@"or") else .add,
.l = if (logical) &yes else inner,
.r = if (logical) inner else &one,
} } };
e = .{ .span = span, .kind = if (logical) .{ .not = binary } else .{ .neg = binary } };
}
const want: Ty = if (logical) .bool else .{ .int = "i64" };
var old: Lowerer = .{ .arena = a, .m = m };
old.cur = try old.newBlock("entry", span);
_ = try ReferenceOperands.expr(&old, e, want);
var fail_index: usize = 0;
while (true) : (fail_index += 1) {
try std.testing.expect(fail_index < 1024);
var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = fail_index });
var arena: std.heap.ArenaAllocator = .init(failing.allocator());
var l: Lowerer = .{ .arena = arena.allocator(), .m = m };
const result: Error!Value = blk: {
l.cur = l.newBlock("entry", span) catch |err| break :blk err;
break :blk l.expr(e, want);
};
if (failing.has_induced_failure) {
try std.testing.expectError(error.OutOfMemory, result);
try std.testing.expect(l.problem == null);
} else {
try std.testing.expect((try result).ty.eql(want));
try std.testing.expectEqualDeep(old.blocks.items, l.blocks.items);
try std.testing.expectEqual(old.cur, l.cur);
}
try std.testing.expect(l.blocks.items.len <= old.blocks.items.len);
for (l.blocks.items, old.blocks.items[0..l.blocks.items.len]) |actual, expected| {
try std.testing.expectEqualStrings(expected.name, actual.name);
try std.testing.expectEqualDeep(expected.span, actual.span);
try std.testing.expect(actual.params.items.len <= expected.params.items.len);
try std.testing.expectEqualDeep(expected.params.items[0..actual.params.items.len], actual.params.items);
try std.testing.expect(actual.insts.items.len <= expected.insts.items.len);
try std.testing.expectEqualDeep(expected.insts.items[0..actual.insts.items.len], actual.insts.items);
}
try std.testing.expectEqual(@as(usize, 0), l.out.items.len);
arena.deinit();
try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes);
if (!failing.has_induced_failure) break;
}
}
}
fn unaryTestSpan(column: u32) Span {
return .{ .file = "deep.aji", .start = .{ .line = 2, .col = column }, .end = .{ .line = 2, .col = 100_000 } };
}
@@ -5407,7 +5712,7 @@ test "unary lowering OOM retains complete instruction prefixes and no output" {
}
var old: Lowerer = .{ .arena = a, .m = m };
old.cur = try old.newBlock("entry", span);
_ = try ReferenceUnary.expr(&old, e, null);
_ = try ReferenceOperands.expr(&old, e, null);
const expected = old.blocks.items[0].insts.items;
var fail_index: usize = 0;
while (true) : (fail_index += 1) {