cli: add whole-value linear aggregates

Implement STD-5 through source, AIR, verifier and deterministic interpreter.
Constructors consume nested owners; exhaustive unpack/take, explicit swap and
own.pack preserve ownership on success and failure. Support owning Option and
Result while keeping classification helpers Copy-only. Preserve borrow identity
across whole replacement and collection; distinguish individual owned arrays
from repeated heap arrays.

Specify feature contracts, invariants, diagnostics, compatibility and measured
source/AIR budgets in RFC 0023 and normative docs. Add canonical round trips,
AIR/source acceptance and rejection fixtures, CLI integration and CI checks.

Validate build, unit/extended tests, full conformance, forced-collection schedule
stress (32 seeds per quantum), hosted smoke, CLI suites, source coverage (88/88),
formatting and reference bundle generation. Source bundle grows 3.2%; Quick
Reference grows 4.0%. No MCC improvement is claimed.

Dynamic initialized linear buffers and explicit drain remain Q-036/STD-6;
frame/region/repeated heap storage is Copy-only. RFC remains Proposed.
This commit is contained in:
dev committed 2026-10-06 21:23:52 +03:00
1 parent 7eea31518d
commit 4f084decce
109 files changed
+1814 -142

No files matched your search

+2 -2
View File
@@ -34,7 +34,7 @@ pub const registry = [_]Feature{
.{ .name = "guard_transfer", .depends = &.{ "cancellation", "effects", "ownership", "sync", "tasks" }, .status = .reserved, .phase = null },
.{ .name = "heap", .depends = &.{ "capabilities", "effects", "ownership", "resources" }, .status = .published, .phase = 2 },
.{ .name = "islands", .depends = &.{ "capabilities", "effects", "heap", "ownership", "resources" }, .status = .published, .phase = 4 },
.{ .name = "linear_aggregates", .depends = &.{ "capabilities", "effects", "ownership", "resources" }, .status = .reserved, .phase = null },
.{ .name = "linear_aggregates", .depends = &.{ "capabilities", "effects", "ownership", "resources" }, .status = .published, .phase = 6 },
.{ .name = "ownership", .depends = &.{}, .status = .published, .phase = 1 },
.{ .name = "receiver_dup", .depends = &.{ "cancellation", "capabilities", "channels", "effects", "heap", "ownership", "resources", "tasks" }, .status = .reserved, .phase = null },
.{ .name = "regions", .depends = &.{ "capabilities", "effects", "heap", "ownership", "resources" }, .status = .published, .phase = 2 },
@@ -49,7 +49,7 @@ pub const registry = [_]Feature{
};
/// Features implemented by this toolchain, sorted.
pub const supported = [_][]const u8{ "arc", "arrays", "atomics", "cancellation", "capabilities", "channels", "effects", "heap", "islands", "ownership", "regions", "resources", "sync", "tasks", "unsafe" };
pub const supported = [_][]const u8{ "arc", "arrays", "atomics", "cancellation", "capabilities", "channels", "effects", "heap", "islands", "linear_aggregates", "ownership", "regions", "resources", "sync", "tasks", "unsafe" };
pub const Reason = enum {
unknown_feature,
+37 -7
View File
@@ -290,6 +290,9 @@ pub const Op = union(enum) {
store: struct { borrow: ValueId, value: ValueId },
// Feature `arrays`.
array_splat: struct { ty: Type, value: ValueId },
array_make: struct { ty: Type, args: []const ValueId },
aggregate_unpack: struct { ty: Type, value: ValueId, next: u32 },
value_swap: struct { borrow: ValueId, value: ValueId },
borrow_index: struct { borrow: ValueId, index: ValueId, proven: bool, unchecked: bool = false },
slice_make: ValueId,
slice_len: ValueId,
@@ -318,6 +321,7 @@ pub const Op = union(enum) {
@"switch": struct { ty: IntType, value: ValueId, cases: []const Case, default: Target },
/// `ty` is a declared enum (`.named`) or a built-in enum (`.builtin`).
enum_switch: struct { ty: Type, value: ValueId, arms: []const Arm, default: ?Target },
enum_take: struct { ty: Type, value: ValueId, arms: []const Arm, default: ?Target },
/// Fallible narrowing (spec 05 §10.4): continues at `ok` with the new
/// capability or at `err` with a `cap_error`, as block parameters.
cap_narrow: struct { form: []const u8, cap: ValueId, args: []const ValueId, ok: u32, err: u32 },
@@ -327,6 +331,7 @@ pub const Op = union(enum) {
// Features `heap` and `regions` (spec 03 §19–§20). Allocations are
// fallible terminators delivering to `ok`/`err` block parameters.
own_new: struct { value: ValueId, cap: ValueId, ok: u32, err: u32 },
own_pack: struct { ty: Type, value: ValueId, cap: ValueId, ok: u32, err: u32 },
own_array: struct { n: ValueId, value: ValueId, cap: ValueId, ok: u32, err: u32 },
own_take: ValueId,
own_free: ValueId,
@@ -410,8 +415,8 @@ pub const Op = union(enum) {
pub fn isTerminator(op: Op) bool {
return switch (op) {
.br, .cbr, .@"switch", .enum_switch, .cap_narrow, .ret, .trap => true,
.own_new, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => true,
inline .br, .cbr, .@"switch", .enum_switch, .enum_take, .aggregate_unpack, .cap_narrow, .ret, .trap => true,
inline .own_new, .own_pack, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => true,
.task_check_cancel, .task_join_cancel, .channel_make, .channel_send, .channel_recv, .channel_close_receiver, .select, .mutex_lock => true,
.intrinsic => |x| x.ok != null,
else => false,
@@ -461,6 +466,24 @@ pub const Module = struct {
return false;
}
/// Whole-value linearity; well-formed nominal ownership graphs are acyclic.
pub fn isLinearType(m: Module, t: Type) bool {
if (t.isLinear()) return true;
return switch (t) {
.array => |a| m.isLinearType(a.elem),
.named => |i| switch (m.types[i].kind) {
.@"struct" => |fs| for (fs) |f| {
if (m.isLinearType(f.ty)) break true;
} else false,
.@"enum" => |vs| blk: {
for (vs) |v| for (v.payload) |p| if (m.isLinearType(p)) break :blk true;
break :blk false;
},
},
else => false,
};
}
/// Variant names and payloads of a declared or built-in enum type.
pub fn variantCount(m: Module, t: Type) usize {
return switch (t) {
@@ -533,7 +556,7 @@ pub fn forEachUse(op: Op, ctx: anytype, comptime f: fn (@TypeOf(ctx), ValueId) v
for (x.cases) |c| for (c.target.args) |v| f(ctx, v);
for (x.default.args) |v| f(ctx, v);
},
.enum_switch => |x| {
inline .enum_switch, .enum_take => |x| {
f(ctx, x.value);
if (x.default) |d| for (d.args) |v| f(ctx, v);
},
@@ -542,7 +565,7 @@ pub fn forEachUse(op: Op, ctx: anytype, comptime f: fn (@TypeOf(ctx), ValueId) v
for (x.args) |v| f(ctx, v);
},
.intrinsic => |x| for (x.args) |v| f(ctx, v),
.own_new => |x| {
inline .own_new, .own_pack => |x| {
f(ctx, x.value);
f(ctx, x.cap);
},
@@ -630,6 +653,12 @@ pub fn forEachUse(op: Op, ctx: anytype, comptime f: fn (@TypeOf(ctx), ValueId) v
f(ctx, x.value);
},
.array_splat => |x| f(ctx, x.value),
.array_make => |x| for (x.args) |v| f(ctx, v),
.aggregate_unpack => |x| f(ctx, x.value),
.value_swap => |x| {
f(ctx, x.borrow);
f(ctx, x.value);
},
.borrow_index => |x| {
f(ctx, x.borrow);
f(ctx, x.index);
@@ -654,7 +683,7 @@ pub fn forEachUse(op: Op, ctx: anytype, comptime f: fn (@TypeOf(ctx), ValueId) v
/// `ok`/`err` targets of a fallible allocation terminator.
pub fn allocTargets(op: Op) ?struct { ok: u32, err: u32 } {
return switch (op) {
inline .own_new, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => |x| .{ .ok = x.ok, .err = x.err },
inline .own_new, .own_pack, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => |x| .{ .ok = x.ok, .err = x.err },
else => null,
};
}
@@ -670,10 +699,11 @@ pub fn successors(op: Op, buf: *std.ArrayList(u32), gpa: std.mem.Allocator) std.
for (x.cases) |c| try buf.append(gpa, c.target.block);
try buf.append(gpa, x.default.block);
},
.enum_switch => |x| {
inline .enum_switch, .enum_take => |x| {
for (x.arms) |a| try buf.append(gpa, a.block);
if (x.default) |d| try buf.append(gpa, d.block);
},
.aggregate_unpack => |x| try buf.append(gpa, x.next),
.cap_narrow => |x| {
try buf.append(gpa, x.ok);
try buf.append(gpa, x.err);
@@ -682,7 +712,7 @@ pub fn successors(op: Op, buf: *std.ArrayList(u32), gpa: std.mem.Allocator) std.
try buf.append(gpa, ok);
try buf.append(gpa, x.err.?);
},
inline .own_new, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => |x| {
inline .own_new, .own_pack, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => |x| {
try buf.append(gpa, x.ok);
try buf.append(gpa, x.err);
},
+31 -7
View File
@@ -640,7 +640,7 @@ const Parser = struct {
};
}
/// Resources inside aggregates need the reserved feature `linear_aggregates`.
/// Resources inside aggregates need the feature `linear_aggregates`.
fn gateLinearMember(p: *Parser, t: air.Type, span: Span) Error!void {
if (t == .guard) return p.requireFeature("guard_transfer", span, "lock guard as a member");
if (t.isTaskBound()) return p.requireFeature("task_transfer", span, "task handle or scope as a member");
@@ -909,6 +909,26 @@ const Parser = struct {
const it = std.meta.stringToEnum(air.IntType, parts[2]) orelse return p.unknownOpcode(op_tok);
break :op .{ .cast = .{ .mode = mode, .to = it, .a = try p.useValue() } };
}
if (eql(op_tok.text, "array.make")) {
try p.requireFeature("linear_aggregates", op_tok.span, op_tok.text);
const ty = try p.parseType();
break :op .{ .array_make = .{ .ty = ty, .args = try p.valueList() } };
}
if (eql(op_tok.text, "struct.unpack") or eql(op_tok.text, "array.unpack")) {
try p.requireFeature("linear_aggregates", op_tok.span, op_tok.text);
const ty: air.Type = if (eql(op_tok.text, "struct.unpack")) .{ .named = try p.typeRef(.@"struct") } else try p.parseType();
if (eql(op_tok.text, "array.unpack") and ty != .array) try p.report("E1001", op_tok.span, "array.unpack requires an array type", &.{});
const v = try p.useValue();
_ = try p.expect(.comma, "`,`");
_ = try p.expectWord("next");
_ = try p.expect(.arrow, "`->`");
break :op .{ .aggregate_unpack = .{ .ty = ty, .value = v, .next = try p.blockRef() } };
}
if (eql(op_tok.text, "value.swap")) {
try p.requireFeature("linear_aggregates", op_tok.span, op_tok.text);
const a, const b = try p.twoOperands();
break :op .{ .value_swap = .{ .borrow = a, .value = b } };
}
if (eql(op_tok.text, "struct.make")) {
const decl = try p.typeRef(.@"struct");
break :op .{ .struct_make = .{ .decl = decl, .args = try p.valueList() } };
@@ -962,7 +982,9 @@ const Parser = struct {
_ = try p.expect(.arrow, "`->`");
break :op .{ .@"switch" = .{ .ty = it, .value = value, .cases = cases.items, .default = try p.target() } };
}
if (eql(op_tok.text, "enum.switch")) {
if (eql(op_tok.text, "enum.switch") or eql(op_tok.text, "enum.take")) {
const taking = eql(op_tok.text, "enum.take");
if (taking) try p.requireFeature("linear_aggregates", op_tok.span, op_tok.text);
// A declared enum (`@E`) or a built-in enum (`cap_error`).
const ety: air.Type = if (p.peek().tag == .word) blk: {
const t = p.next();
@@ -990,7 +1012,7 @@ const Parser = struct {
const blk = try p.blockRef();
try arms.append(p.arena, .{ .variant = variant, .block = blk, .span = span });
}
break :op .{ .enum_switch = .{ .ty = ety, .value = value, .arms = arms.items, .default = default } };
break :op if (taking) .{ .enum_take = .{ .ty = ety, .value = value, .arms = arms.items, .default = default } } else .{ .enum_switch = .{ .ty = ety, .value = value, .arms = arms.items, .default = default } };
}
if (eql(op_tok.text, "ret")) {
break :op .{ .ret = if (p.peek().tag == .local) try p.useValue() else null };
@@ -1055,7 +1077,7 @@ const Parser = struct {
.atomic_new, .atomic_take, .atomic_load, .atomic_rmw, .atomic_cmpxchg => true,
.@"const", .copy, .arith, .bit, .cmp, .cast, .struct_make, .struct_get, .enum_make => true,
.local_alloc, .local_load, .borrow_ref, .borrow_mut, .borrow_field, .load => true,
.array_splat, .borrow_index, .slice_make, .slice_len, .slice_sub, .slice_split => true,
.array_splat, .array_make, .value_swap, .borrow_index, .slice_make, .slice_len, .slice_sub, .slice_split => true,
else => false,
};
const may_bind = produces_value or op == .call or op == .intrinsic or op == .task_join;
@@ -1333,14 +1355,16 @@ const Parser = struct {
/// Instructions of the features `heap` and `regions` (spec 03 §19–§20).
fn parseAllocOp(p: *Parser, op_tok: Token) Error!?air.Op {
const Name = enum { @"own.new", @"own.array", @"own.take", @"own.free", @"region.create", @"region.new", @"region.array", @"region.reset", @"region.destroy" };
const Name = enum { @"own.new", @"own.pack", @"own.array", @"own.take", @"own.free", @"region.create", @"region.new", @"region.array", @"region.reset", @"region.destroy" };
const name = std.meta.stringToEnum(Name, op_tok.text) orelse return null;
try p.requireFeature(if (std.mem.startsWith(u8, op_tok.text, "own.")) "heap" else "regions", op_tok.span, op_tok.text);
switch (name) {
.@"own.new" => {
.@"own.new", .@"own.pack" => {
if (name == .@"own.pack") try p.requireFeature("linear_aggregates", op_tok.span, op_tok.text);
const pack_ty: air.Type = if (name == .@"own.pack") try p.parseType() else .void;
const v, const c = try p.twoOperands();
const ok, const err = try p.okErr();
return .{ .own_new = .{ .value = v, .cap = c, .ok = ok, .err = err } };
return if (name == .@"own.pack") .{ .own_pack = .{ .ty = pack_ty, .value = v, .cap = c, .ok = ok, .err = err } } else .{ .own_new = .{ .value = v, .cap = c, .ok = ok, .err = err } };
},
.@"own.array" => {
const n, const v = try p.twoOperands();
+61 -4
View File
@@ -209,6 +209,19 @@ fn printOp(m: air.Module, f: air.Function, op: air.Op, w: *Writer) Writer.Error!
try w.print("cast.{s}.{s} ", .{ @tagName(x.mode), @tagName(x.to) });
try value(f, x.a, w);
},
.array_make => |x| {
try w.writeAll("array.make ");
try printType(m, x.ty, w);
try values(f, x.args, w);
},
.aggregate_unpack => |x| {
try w.writeAll(if (x.ty == .array) "array.unpack " else "struct.unpack ");
try printType(m, x.ty, w);
try w.writeByte(' ');
try value(f, x.value, w);
try w.print(", next -> @{s}", .{f.blocks[x.next].name});
},
.value_swap => |x| try two(f, w, "value.swap", x.borrow, x.value),
.struct_make => |x| {
try w.print("struct.make @{s}", .{m.types[x.decl].name});
try values(f, x.args, w);
@@ -251,8 +264,8 @@ fn printOp(m: air.Module, f: air.Function, op: air.Op, w: *Writer) Writer.Error!
try w.writeAll(", default -> ");
try target(f, x.default, w);
},
.enum_switch => |x| {
try w.writeAll("enum.switch ");
inline .enum_switch, .enum_take => |x| {
try w.writeAll(if (op == .enum_take) "enum.take " else "enum.switch ");
try printType(m, x.ty, w);
try w.writeByte(' ');
try value(f, x.value, w);
@@ -310,8 +323,15 @@ fn printOp(m: air.Module, f: air.Function, op: air.Op, w: *Writer) Writer.Error!
try values(f, x.args, w);
if (x.ok) |ok| try w.print(", ok -> @{s}, err -> @{s}", .{ f.blocks[ok].name, f.blocks[x.err.?].name });
},
.own_new => |x| {
try two(f, w, "own.new", x.value, x.cap);
inline .own_new, .own_pack => |x, tag| {
if (tag == .own_pack) {
try w.writeAll("own.pack ");
try printType(m, x.ty, w);
try w.writeByte(' ');
try value(f, x.value, w);
try w.writeAll(", ");
try value(f, x.cap, w);
} else try two(f, w, "own.new", x.value, x.cap);
try okErr(f, w, x.ok, x.err);
},
.own_array => |x| {
@@ -635,3 +655,40 @@ test "round-trip of ownership and arrays forms" {
\\
);
}
test "round-trip whole-value linear operations" {
try roundTrip(
\\module test.linear
\\air 0
\\lang 0.1
\\features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]
\\type @Maybe = enum { some(own<u64>), none }
\\fn @main(%heap: cap<mem.alloc>) -> u64
\\effects [mem.alloc]
\\entry:
\\ %n = const.u64 42
\\ own.pack u64 %n, %heap, ok -> @got, err -> @failed
\\got(%owner: own<u64>):
\\ %items = array.make array<own<u64>,1>(%owner)
\\ array.unpack array<own<u64>,1> %items, next -> @element
\\element(%part: own<u64>):
\\ %slot = enum.make @Maybe.some(%part)
\\ %empty = enum.make @Maybe.none()
\\ %borrow = borrow.mut %slot
\\ %old = value.swap %borrow, %empty
\\ borrow.end %borrow
\\ enum.take @Maybe %slot, some -> @extra, none -> @replaced
\\extra(%extra_owner: own<u64>):
\\ own.free %extra_owner
\\ enum.take @Maybe %old, some -> @answer, none -> @no_answer
\\replaced:
\\ enum.take @Maybe %old, some -> @answer, none -> @no_answer
\\answer(%answer_owner: own<u64>):
\\ %value = own.take %answer_owner
\\ ret %value
\\no_answer:
\\ ret %n
\\failed(%e: alloc_error, %original: u64):
\\ ret %n
);
}
+2 -1
View File
@@ -79,6 +79,7 @@ pub const Expr = struct {
index: struct { e: *const Expr, lo: *const Expr, hi: ?*const Expr },
struct_lit: struct { name: []const u8, fields: []const FieldInit, type_args: []const Type = &.{} },
array_rep: struct { e: *const Expr, len: u64 },
array_list: []const Expr,
or_trap: *const Expr,
if_expr: *const If,
match_expr: *const Match,
@@ -141,7 +142,7 @@ pub const Select = struct {
pub const Stmt = struct {
span: Span,
kind: union(enum) {
let: struct { names: []const []const u8, ty: ?Type, e: Expr },
let: struct { names: []const []const u8, ty: ?Type, e: Expr, tuple: bool = false },
/// `init == null` is `= zero`.
@"var": struct { name: []const u8, ty: Type, init: ?Expr },
assign: struct { place: Expr, e: Expr },
+146 -23
View File
@@ -315,6 +315,43 @@ const Lowerer = struct {
scope_binding_start: usize = 0,
fns: std.ArrayList(FnOut) = .empty,
linear_enabled: bool = false,
fn probeType(l: *Lowerer, t: ast.Type) ?Ty {
const previous = l.problem;
defer l.problem = previous;
return l.typeOf(t) catch null;
}
fn needsLinearType(l: *Lowerer, t: Ty, depth: usize) bool {
if (depth > l.m.types.len + 32) return false;
if (t == .named) return l.isLinear(t);
if (t.inner()) |inner| {
if ((t == .array or t == .own or t == .own_array or t == .slice or t == .slice_mut) and l.isLinear(inner)) return true;
return l.needsLinearType(inner, depth + 1);
}
return false;
}
fn isLinear(l: *Lowerer, t: Ty) bool {
return l.linearAt(t, 0);
}
fn linearAt(l: *Lowerer, t: Ty, depth: usize) bool {
if (t.isLinear()) return true;
if (depth > l.m.types.len + 32) return false;
return switch (t) {
.array => |a| l.linearAt(a.elem, depth + 1),
.named => |i| switch (l.m.types[i].kind) {
.@"struct" => |fs| for (fs) |f| {
if (l.probeType(f.ty)) |ty| if (l.linearAt(ty, depth + 1)) break true;
} else false,
.@"enum" => |vs| blk: {
for (vs) |v| for (v.payload) |p| if (l.probeType(p)) |ty| if (l.linearAt(ty, depth + 1)) break :blk true;
break :blk false;
},
},
else => false,
};
}
fn fail(l: *Lowerer, code: []const u8, span: Span, message: []const u8, fields: []const Problem.Field) Error {
// `fields` usually points at a temporary array: keep a copy.
l.problem = .{ .code = code, .span = span, .message = message, .fields = try l.arena.dupe(Problem.Field, fields) };
@@ -465,7 +502,6 @@ const Lowerer = struct {
}
fn checkRequirements(l: *Lowerer) Error!void {
if (l.m.requirements.len == 0) return;
const types = try l.arena.alloc(air_module.TypeDecl, l.m.types.len);
for (l.m.types, types, 0..) |d, *out, index| {
out.* = .{ .name = d.air_name orelse d.name, .span = .{ .line = @intCast(index + 1), .col = 1 }, .kind = undefined };
@@ -486,7 +522,10 @@ const Lowerer = struct {
},
}
}
const m: air_module.Module = .{ .name = l.m.name, .format_version = 0, .lang = .{ 0, 1 }, .features = &.{}, .types = types, .functions = &.{} };
for (l.m.types, 0..) |_, i| if (l.isLinear(.{ .named = @intCast(i) })) {
l.linear_enabled = true;
};
const m: air_module.Module = .{ .name = l.m.name, .format_version = 0, .lang = .{ 0, 1 }, .features = &.{"linear_aggregates"}, .types = types, .functions = &.{} };
var layout_context: @import("../verifier.zig").Context = .{ .arena = l.arena, .file = "<generic>", .module = m };
try verifier_types.checkFiniteLayouts(&layout_context);
if (layout_context.diags.items.len != 0) {
@@ -528,10 +567,19 @@ const Lowerer = struct {
}
var roots: std.ArrayList([]const u8) = .empty;
try roots.append(l.arena, "effects");
var signatures = l.sigs.valueIterator();
while (signatures.next()) |f| {
for (f.params) |t| if (l.needsLinearType(t, 0)) {
l.linear_enabled = true;
};
if (l.needsLinearType(f.ret, 0)) l.linear_enabled = true;
}
if (l.linear_enabled) try roots.append(l.arena, "linear_aggregates");
const Rule = struct { []const u8, []const []const u8 };
const rules = [_]Rule{
.{ "arrays", &.{ "array<", "slice", "array.splat", "borrow.index" } },
.{ "ownership", &.{ "local.", "borrow.", " load ", "= load ", "store ", "ref<", "mut<" } },
.{ "linear_aggregates", &.{ "array.make ", "struct.unpack ", "array.unpack ", "enum.take ", "value.swap ", "own.pack " } },
.{ "heap", &.{ "own.", "own<", "own_array<", "alloc_error" } },
.{ "regions", &.{"region"} },
.{ "capabilities", &.{ "cap<", "cap.narrow", "cap_error" } },
@@ -953,7 +1001,10 @@ const Lowerer = struct {
fn stmt(l: *Lowerer, s: ast.Stmt) Error!void {
switch (s.kind) {
.let => |x| {
if (x.names.len == 2) {
if (x.e.kind == .call) if (pathOf(x.e.kind.call.callee.*)) |p| if (std.mem.eql(u8, p, "struct.unpack") or std.mem.eql(u8, p, "array.unpack")) return l.unpackLet(s, x.names, x.e, x.tuple);
if (x.tuple and x.names.len == 1) return l.fail("E7006", s.span, "a single parenthesized binding requires aggregate unpack", &.{});
if (x.names.len != 1) {
if (x.e.kind != .call or x.names.len != 2) return l.fail("E7006", s.span, "this multi-binding requires aggregate unpack", &.{});
if (pathOf(x.e.kind.call.callee.*)) |p| if (std.mem.eql(u8, p, "atomic.compare_exchange")) return l.compareExchangeLet(s, x.names, x.e);
return l.splitLet(s, x.names, x.e);
}
@@ -983,7 +1034,7 @@ const Lowerer = struct {
if (v.ty.isBorrow()) return l.fail("E7006", x.e.span, "bind a borrow with `ref name = place;` or `mut name = place;`", &.{});
// Linear values (owners, regions, resources, endpoints, tasks,
// mutexes) are borrowed in place, never moved to frame storage.
if (l.addressable.contains(x.names[0]) and !v.ty.isLinear()) {
if (l.addressable.contains(x.names[0]) and !l.isLinear(v.ty)) {
const st = try l.storageFor(x.names[0], v.ty, s.span);
try l.emit(try l.fmt("local.store %{s}, %{s}", .{ st, v.name }), s.span);
try l.bindings.append(l.arena, .{ .name = x.names[0], .mutable = false, .value = st, .ty = v.ty, .kind = .storage });
@@ -992,7 +1043,7 @@ const Lowerer = struct {
.@"var" => |x| {
const ty = try l.typeOf(x.ty);
if (ty.isBorrow()) return l.fail("E7006", s.span, "a `var` holds a value; bind a borrow with `ref` or `mut`", &.{});
if (l.addressable.contains(x.name) and !ty.isLinear()) {
if (l.addressable.contains(x.name) and !l.isLinear(ty)) {
const st = try l.storageFor(x.name, ty, s.span);
if (x.init) |e| {
const v = try l.consuming(e, ty);
@@ -1238,6 +1289,7 @@ const Lowerer = struct {
.deref => |x| if (l.peekType(x.*)) |t| t.inner() else null,
.index => |x| if (x.hi == null) (if (l.peekType(x.e.*)) |t| elemOf(t) else null) else null,
.array_rep => |x| if (l.peekType(x.e.*)) |t| (l.arrayOf(t, x.len) catch null) else null,
.array_list => |xs| if (xs.len != 0) (if (l.peekType(xs[0])) |t| (l.arrayOf(t, xs.len) catch null) else null) else null,
.neg => |x| l.peekType(x.*),
.not => .bool,
.cast => |x| l.typeOfNoFail(x.ty),
@@ -1396,6 +1448,18 @@ const Lowerer = struct {
try l.endNow(p.ends, e.span);
return v;
},
.array_list => |xs| {
if (xs.len == 0 or xs.len > 64) return l.fail("E7006", e.span, "array literal requires 1..64 complete elements", &.{});
var ty: ?Ty = if (want) |w| if (w == .array) w.array.elem else null else null;
var names: std.ArrayList(u8) = .empty;
for (xs, 0..) |x, i| {
const v = try l.consuming(x, ty);
if (ty) |t| try l.checkTy(x.span, v.ty, t) else ty = v.ty;
try names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", v.name }));
}
const at = try l.arrayOf(ty.?, xs.len);
return l.def("arr", at, try l.fmt("array.make {s}({s})", .{ l.tyText(at), names.items }), e.span);
},
.array_rep => |x| {
const want_elem: ?Ty = if (want) |w| (if (w == .array) w.array.elem else null) else null;
const v = try l.expr(x.e.*, want_elem);
@@ -1464,7 +1528,7 @@ const Lowerer = struct {
.or_trap => |x| return l.orTrap(e, x.*),
.move => |n| {
const b = l.lookup(n) orelse return l.unknown(e.span, n);
if (!b.ty.isLinear()) return l.fail("E7006", e.span, "`move` applies to linear values; copyable values are passed plainly", &.{ .{ .name = "name", .value = n }, .{ .name = "type", .value = l.diagnosticTyText(b.ty) } });
if (!l.isLinear(b.ty)) return l.fail("E7006", e.span, "`move` applies to linear values; copyable values are passed plainly", &.{ .{ .name = "name", .value = n }, .{ .name = "type", .value = l.diagnosticTyText(b.ty) } });
return .{ .name = b.value, .ty = b.ty };
},
}
@@ -1543,6 +1607,19 @@ const Lowerer = struct {
}
fn call(l: *Lowerer, e: ast.Expr, callee: ast.Expr, args: []const ast.Expr) Error!Value {
if (pathOf(callee)) |path| if (std.mem.eql(u8, path, "value.swap")) {
if (args.len != 2 or args[0].kind != .borrow or !args[0].kind.borrow.mutable) return l.fail("E7006", e.span, "value.swap requires mut place and replacement", &.{});
const b = args[0].kind.borrow;
const p = try l.placeBorrow(b.place.*, true, false, e.span);
if (p.v.ty != .mut) return l.fail("E7005", e.span, "value.swap requires mut<T>", &.{});
const ty = p.v.ty.inner().?;
const replacement = try l.consuming(args[1], ty);
try l.checkTy(args[1].span, replacement.ty, ty);
const result = try l.def("old", ty, try l.fmt("value.swap %{s}, %{s}", .{ p.v.name, replacement.name }), e.span);
try l.endNow(p.ends, e.span);
l.linear_enabled = true;
return result;
};
if (callee.kind == .variant) return l.variantValue(e, callee.kind.variant.@"enum", callee.kind.variant.name, args);
if (try l.moduleCall(callee)) |name| {
// Reuse ordinary call typing/borrowing/lowering, including E7002.
@@ -1652,7 +1729,7 @@ const Lowerer = struct {
if (std.mem.eql(u8, x.name, f.name)) break x;
} else return l.fail("E7006", 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.expr(fi.e, ft);
const v = try l.consuming(fi.e, ft);
try l.checkTy(fi.e.span, v.ty, ft);
try args.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", v.name }));
}
@@ -1669,7 +1746,7 @@ const Lowerer = struct {
var names: std.ArrayList(u8) = .empty;
for (args, v.payload, 0..) |a, pt, i| {
const ty = try l.typeOf(pt);
const av = try l.expr(a, ty);
const av = try l.consuming(a, ty);
try l.checkTy(a.span, av.ty, ty);
try names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", av.name }));
}
@@ -1743,7 +1820,7 @@ const Lowerer = struct {
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", &.{});
if (st == .builtin) return l.builtinMatch(m, st.builtin, want);
const sv = try l.expr(m.scrutinee, st);
const sv = try l.consuming(m.scrutinee, st);
const depth = l.bindings.items.len;
const vars = try l.carriedLive(depth, m.span, .{ .match = m });
const before = try l.snapshot();
@@ -1754,7 +1831,7 @@ const Lowerer = struct {
const vs = d.kind.@"enum";
const blocks = try l.arena.alloc(usize, m.arms.len);
var head: std.ArrayList(u8) = .empty;
try head.appendSlice(l.arena, try l.fmt("enum.switch {s} %{s}", .{ l.tyText(st), sv.name }));
try head.appendSlice(l.arena, try l.fmt("{s} {s} %{s}", .{ if (l.isLinear(st)) "enum.take" else "enum.switch", l.tyText(st), sv.name }));
for (m.arms, blocks, 0..) |arm, *blk, i| {
if (arm.pattern.kind != .ctor or arm.pattern.kind.ctor.qualifier == null)
return l.fail("E7006", arm.pattern.span, "an arm of a `match` over an enum names one variant as `Enum::Variant`; `_` is not allowed", &.{.{ .name = "enum", .value = d.display_name orelse d.name }});
@@ -1995,7 +2072,7 @@ const Lowerer = struct {
/// written `move x` (spec 15 §5). Use after move, double consumption and
/// leaks are the verifier's (E2001, E2002, E3001, E3002).
fn consuming(l: *Lowerer, e: ast.Expr, want: ?Ty) Error!Value {
if (e.kind == .name) if (l.lookup(e.kind.name)) |b| if (b.ty.isLinear() and b.kind == .ssa)
if (e.kind == .name) if (l.lookup(e.kind.name)) |b| if (l.isLinear(b.ty) and b.kind == .ssa)
return l.fail("E7003", e.span, "a linear value is consumed here: write `move` to transfer it, or borrow it with `ref`/`mut`", &.{ .{ .name = "name", .value = e.kind.name }, .{ .name = "suggestion", .value = try l.fmt("move {s}", .{e.kind.name}) } });
return l.expr(e, want);
}
@@ -2059,6 +2136,7 @@ const Lowerer = struct {
.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.*),
.region => if (mutable) try l.wrap(.mut, .region) else try l.wrap(.ref, .region),
@@ -2186,6 +2264,30 @@ const Lowerer = struct {
/// `let (left, right) = s.split_at(k);`: two disjoint borrows of `s`,
/// bound for the rest of the block (spec 15 §5).
fn unpackLet(l: *Lowerer, s: ast.Stmt, names: []const []const u8, e: ast.Expr, tuple: bool) Error!void {
if (!tuple or s.kind.let.ty != null or e.kind.call.args.len != 1) return l.fail("E7006", s.span, "unpack requires a parenthesized complete binding and one argument", &.{});
const v = try l.consuming(e.kind.call.args[0], null);
const operation = pathOf(e.kind.call.callee.*).?;
var components: std.ArrayList(Ty) = .empty;
if (std.mem.eql(u8, operation, "struct.unpack") and v.ty == .named and l.m.types[v.ty.named].kind == .@"struct") {
for (l.m.types[v.ty.named].kind.@"struct") |f| try components.append(l.arena, try l.typeOf(f.ty));
} else if (std.mem.eql(u8, operation, "array.unpack") and v.ty == .array) {
if (v.ty.array.len > 64) return l.fail("E7006", s.span, "unpack exceeds 64 block parameters", &.{});
for (0..@intCast(v.ty.array.len)) |_| try components.append(l.arena, v.ty.array.elem);
} else return l.fail("E7005", e.span, "unpack needs the corresponding struct or array", &.{});
if (names.len != components.items.len or names.len > 64) return l.fail("E7005", s.span, "unpack must bind every component", &.{});
const next = try l.newBlock("unpacked");
for (names, components.items, 0..) |n, t, i| {
for (names[0..i]) |previous| if (!std.mem.eql(u8, n, "_") and std.mem.eql(u8, n, previous)) return l.fail("E7006", s.span, "duplicate unpack binding", &.{});
const pn = try l.freshName(if (std.mem.eql(u8, n, "_")) "unused" else n);
try l.blocks.items[next].params.append(l.arena, .{ .name = pn, .ty = t });
if (!std.mem.eql(u8, n, "_")) try l.bindings.append(l.arena, .{ .name = n, .value = pn, .ty = t, .mutable = false });
}
try l.term(try l.fmt("{s} {s} %{s}, next -> @{s}", .{ operation, l.tyText(v.ty), v.name, l.blocks.items[next].name }), s.span);
l.cur = next;
l.linear_enabled = true;
}
fn splitLet(l: *Lowerer, s: ast.Stmt, names: []const []const u8, e: ast.Expr) Error!void {
if (e.kind != .call or e.kind.call.callee.kind != .field or !std.mem.eql(u8, e.kind.call.callee.kind.field.name, "split_at") or e.kind.call.args.len != 1)
return l.fail("E7006", e.span, "`let (a, b) = …` is only for `s.split_at(k)`", &.{});
@@ -2293,6 +2395,7 @@ const Lowerer = struct {
.field => |x| try l.markExpr(x.e.*),
.struct_lit => |x| for (x.fields) |f| try l.markExpr(f.e),
.array_rep => |x| try l.markExpr(x.e.*),
.array_list => |xs| for (xs) |x| try l.markExpr(x),
.if_expr => |x| {
try l.markExpr(x.cond);
try l.markBlock(x.then);
@@ -2322,7 +2425,7 @@ const Lowerer = struct {
fn fallible(l: *Lowerer, path: []const u8) ?void {
_ = l;
const ops = [_][]const u8{ "own.new", "own.array", "region.create", "region.new", "region.array", "cap.narrow.budget", "cap.narrow.prefix", "channel.make", "channel.send", "channel.recv", "channel.close_receiver", "task.check_cancel", "task.join_cancel", "island.create", "island.alloc", "arc.new" };
const ops = [_][]const u8{ "own.new", "own.pack", "own.array", "region.create", "region.new", "region.array", "cap.narrow.budget", "cap.narrow.prefix", "channel.make", "channel.send", "channel.recv", "channel.close_receiver", "task.check_cancel", "task.join_cancel", "island.create", "island.alloc", "arc.new" };
for (ops) |o| if (std.mem.eql(u8, o, path)) return {};
if (authority.intrinsicIndex(path)) |i| if (authority.intrinsics[i].fallible) return {};
return null;
@@ -2893,6 +2996,13 @@ const Lowerer = struct {
}.n;
const alloc_err: Ty = .{ .builtin = .alloc_error };
const usize_ty: Ty = .{ .int = "usize" };
if (std.mem.eql(u8, path, "own.pack")) {
try want(l, e.span, args, 2, path);
const v = try l.consuming(args[0], null);
const c = try l.expectCap(args[1], "mem.alloc");
l.linear_enabled = true;
return .{ .text = try l.fmt("own.pack {s} %{s}, %{s}", .{ l.tyText(v.ty), v.name, c.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{try l.wrap(.own, v.ty)} }, .{ .role = "err", .params = &.{ alloc_err, v.ty } } }) };
}
if (std.mem.eql(u8, path, "own.new")) {
try want(l, e.span, args, 2, path);
const v = try l.consuming(args[0], null);
@@ -3186,17 +3296,21 @@ fn elemOf(t: Ty) ?Ty {
/// `cap.narrow.budget`; null for anything else.
fn pathOf(e: ast.Expr) ?[]const u8 {
const known = [_][]const u8{
"slice.copy", "own.new", "own.array", "own.take", "own.free",
"region.create", "region.new", "region.array", "region.reset", "region.destroy",
"cap.narrow.budget", "cap.narrow.prefix", "task.spawn", "task.join", "task.cancel",
"task.cancelled", "channel.make", "channel.dup", "channel.send", "channel.recv",
"channel.close_sender", "channel.close_receiver", "mutex.make", "mutex.take", "task.check_cancel",
"task.join_cancel", "island.create", "island.alloc", "island.root", "island.at",
"island.freeze", "island.destroy", "frozen.root", "frozen.at", "frozen.release",
"arc.from_frozen", "arc.new", "arc.clone", "arc.release", "arc.root",
"arc.at", "atomic.new", "atomic.take", "atomic.load", "atomic.store",
"atomic.swap", "atomic.add.wrap", "atomic.sub.wrap", "atomic.and", "atomic.or",
"atomic.xor", "atomic.compare_exchange", "atomic.fence",
"struct.unpack", "array.unpack", "value.swap", "own.pack",
"slice.copy", "own.new", "own.array", "own.take",
"own.free", "region.create", "region.new", "region.array",
"region.reset", "region.destroy", "cap.narrow.budget", "cap.narrow.prefix",
"task.spawn", "task.join", "task.cancel", "task.cancelled",
"channel.make", "channel.dup", "channel.send", "channel.recv",
"channel.close_sender", "channel.close_receiver", "mutex.make", "mutex.take",
"task.check_cancel", "task.join_cancel", "island.create", "island.alloc",
"island.root", "island.at", "island.freeze", "island.destroy",
"frozen.root", "frozen.at", "frozen.release", "arc.from_frozen",
"arc.new", "arc.clone", "arc.release", "arc.root",
"arc.at", "atomic.new", "atomic.take", "atomic.load",
"atomic.store", "atomic.swap", "atomic.add.wrap", "atomic.sub.wrap",
"atomic.and", "atomic.or", "atomic.xor", "atomic.compare_exchange",
"atomic.fence",
};
var buf: [64]u8 = undefined;
const text = dotted(e, &buf) orelse return null;
@@ -3314,6 +3428,9 @@ fn exprReads(e: ast.Expr, name: []const u8, skip: ?Span) bool {
break :blk false;
},
.array_rep => |x| exprReads(x.e.*, name, skip),
.array_list => |xs| for (xs) |x| {
if (exprReads(x, name, skip)) break true;
} else false,
.if_expr => |x| ifReads(x.*, name, skip),
.match_expr => |x| blk: {
if (exprReads(x.scrutinee, name, skip)) break :blk true;
@@ -3375,6 +3492,9 @@ const After = struct {
break :blk false;
},
.array_rep => |x| w.expr(x.e.*),
.array_list => |xs| for (xs) |x| {
if (w.expr(x)) break true;
} else false,
.if_expr => |x| w.ifExpr(x.*),
.match_expr => |x| blk: {
if (w.expr(x.scrutinee)) break :blk true;
@@ -3533,6 +3653,9 @@ fn exprAssigns(e: ast.Expr, name: []const u8) bool {
.field => |x| exprAssigns(x.e.*, name),
.index => |x| exprAssigns(x.e.*, name) or exprAssigns(x.lo.*, name) or (if (x.hi) |h| exprAssigns(h.*, name) else false),
.array_rep => |x| exprAssigns(x.e.*, name),
.array_list => |xs| for (xs) |x| {
if (exprAssigns(x, name)) break true;
} else false,
else => false,
};
}
+20 -6
View File
@@ -331,11 +331,14 @@ const Parser = struct {
if (isWord(t, "let")) {
_ = p.next();
var names: std.ArrayList([]const u8) = .empty;
if (p.peek().tag == .l_paren) {
const tuple = p.peek().tag == .l_paren;
if (tuple) {
_ = p.next();
try names.append(p.arena, try p.ident("a name"));
_ = try p.expect(.comma, "`,`");
try names.append(p.arena, try p.ident("a name"));
while (p.peek().tag != .r_paren) {
try names.append(p.arena, if (p.peek().tag == .underscore) p.next().text else try p.ident("a name"));
if (p.peek().tag != .comma) break;
_ = p.next();
}
_ = try p.expect(.r_paren, "`)`");
} else try names.append(p.arena, try p.ident("a name"));
var ty: ?ast.Type = null;
@@ -346,7 +349,7 @@ const Parser = struct {
_ = try p.expect(.eq, "`=`");
const e = try p.expr();
_ = try p.expect(.semicolon, "`;`");
return .{ .span = p.span(start), .kind = .{ .let = .{ .names = names.items, .ty = ty, .e = e } } };
return .{ .span = p.span(start), .kind = .{ .let = .{ .names = names.items, .ty = ty, .e = e, .tuple = tuple } } };
}
const unchecked_borrow = isWord(p.peekAt(1), "unchecked") and p.peekAt(2).tag == .ident and p.peekAt(3).tag == .eq;
if ((isWord(t, "ref") or isWord(t, "mut")) and ((p.peekAt(1).tag == .ident and p.peekAt(2).tag == .eq) or unchecked_borrow)) {
@@ -822,6 +825,17 @@ const Parser = struct {
.l_bracket => {
_ = p.next();
const e = try p.expr();
if (p.peek().tag != .semicolon) {
var items: std.ArrayList(ast.Expr) = .empty;
try items.append(p.arena, e);
while (p.peek().tag == .comma) {
_ = p.next();
if (p.peek().tag == .r_bracket) break;
try items.append(p.arena, try p.expr());
}
_ = try p.expect(.r_bracket, "`]`");
return .{ .span = p.span(start), .kind = .{ .array_list = items.items } };
}
_ = try p.expect(.semicolon, "`;` in `[e; N]`");
const n = try p.expect(.int, "array length");
_ = try p.expect(.r_bracket, "`]`");
@@ -853,7 +867,7 @@ const Parser = struct {
};
return .{ .span = p.span(start), .kind = .{ .match_expr = try p.box(ast.Match, .{ .scrutinee = scrut, .arms = as, .span = p.span(start), .kind = kind }) } };
}
if (isKeyword(t.text)) return p.fail(t, "an expression");
if (isKeyword(t.text) and !(isWord(t, "struct") and p.peekAt(1).tag == .dot and isWord(p.peekAt(2), "unpack"))) return p.fail(t, "an expression");
_ = p.next();
if (p.peek().tag == .colon_colon and p.peekAt(1).tag != .lt) {
_ = p.next();
+57 -25
View File
@@ -109,6 +109,9 @@ pub const Value = union(enum) {
pub const Cell = struct {
value: Value,
ty: air.Type,
/// An SSA root borrowed in place; its frame outlives every loan.
backing: ?struct { values: []Value, index: u32 } = null,
owner_array: bool = false,
/// Accesses seen by the race detector (`Options.detect_races`).
shadow: ?*race.Shadow = null,
};
@@ -374,6 +377,8 @@ const Copier = struct {
const n = try c.to.create(Value.Cell);
try c.cells.put(c.tmp, old, n);
n.* = .{ .value = .void, .ty = old.ty, .shadow = if (old.shadow) |sh| try sh.copy(c.to) else null };
n.owner_array = old.owner_array;
if (old.backing) |b| n.backing = .{ .values = try c.items(b.values), .index = b.index };
n.value = try c.value(old.value);
return n;
}
@@ -858,6 +863,12 @@ const Machine = struct {
return bind(vals, inst.result, .{ .int = .{ .ty = x.to, .bits = bits } });
},
.assert => |v| return if (vals[v].boolean) .next else .{ .trap = .assert },
.array_make => |x| return bind(vals, inst.result, .{ .array = try m.gatherMut(vals, x.args) }),
.aggregate_unpack => |x| {
const fields = if (x.ty == .array) vals[x.value].array else vals[x.value].aggregate.fields;
for (f.blocks[x.next].params, fields) |p, v| vals[p.value] = v;
return .{ .jump = x.next };
},
.struct_make => |x| return bind(vals, inst.result, .{ .aggregate = .{
.decl = x.decl,
.variant = 0,
@@ -877,7 +888,7 @@ const Machine = struct {
for (x.cases) |c| if (c.bits == v) return m.jump(f, vals, c.target);
return m.jump(f, vals, x.default);
},
.enum_switch => |x| {
inline .enum_switch, .enum_take => |x| {
const variant: u32, const fields: []const Value = switch (vals[x.value]) {
.aggregate => |agg| .{ agg.variant, agg.fields },
.builtin => |b| .{ b.variant, &.{} },
@@ -934,13 +945,13 @@ const Machine = struct {
.task_check_cancel, .task_join_cancel, .task_shield_begin, .task_shield_end => return m.execCancellation(f, vals, inst),
.channel_make, .channel_dup, .channel_send, .channel_recv, .channel_close_sender, .channel_close_receiver, .select => return m.execChannel(f, vals, inst),
.mutex_make, .mutex_take, .mutex_lock, .mutex_borrow, .mutex_unlock => return m.execMutex(f, vals, inst),
.own_new, .own_array, .own_take, .own_free, .region_create, .region_new, .region_array, .region_reset, .region_destroy => return m.execAlloc(f, vals, {}, inst),
inline .own_new, .own_pack, .own_array, .own_take, .own_free, .region_create, .region_new, .region_array, .region_reset, .region_destroy => return m.execAlloc(f, vals, {}, inst),
.island_create, .island_alloc, .island_root, .island_borrow, .island_freeze, .island_destroy, .frozen_root, .frozen_borrow, .frozen_release, .arc_from_frozen, .arc_new, .arc_clone, .arc_release, .arc_root, .arc_borrow, .iref_eq => return m.execGraph(f, vals, inst),
.atomic_new, .atomic_take, .atomic_load, .atomic_store, .atomic_rmw, .atomic_cmpxchg, .atomic_fence => return m.execAtomic(vals, inst),
.intrinsic => |x| return m.intrinsic(f, vals, inst, x),
.ret => |v| return .{ .ret = if (v) |x| vals[x] else .void },
.trap => return .{ .trap = .explicit },
.local_alloc, .local_store, .local_zero, .local_load, .borrow_ref, .borrow_mut, .borrow_field, .borrow_end, .load, .store, .array_splat, .borrow_index, .slice_make, .slice_len, .slice_sub, .slice_split, .slice_copy, .guard, .assume => return m.execMemory(vals, inst),
.local_alloc, .local_store, .local_zero, .local_load, .borrow_ref, .borrow_mut, .borrow_field, .borrow_end, .load, .store, .array_splat, .borrow_index, .slice_make, .slice_len, .slice_sub, .slice_split, .slice_copy, .value_swap, .guard, .assume => return m.execMemory(vals, inst),
}
}
@@ -968,7 +979,7 @@ const Machine = struct {
const ch = endpointOf(vals[arm.endpoint]);
if ((if (arm.value == null) m.recvState(ch) else m.sendState(ch)) != .none) break true;
} else false,
.mutex_lock => |x| !vals[x.mutex].mutex.locked,
.mutex_lock => |x| !mutexOf(vals[x.mutex]).locked,
else => unreachable,
};
}
@@ -976,7 +987,7 @@ const Machine = struct {
fn endpointOf(v: Value) u32 {
return switch (v) {
.sender, .receiver => |c| c,
.place => |p| endpointOf(p.cell.value),
.place => |p| endpointOf(placePtr(p).*),
else => unreachable,
};
}
@@ -1453,7 +1464,7 @@ const Machine = struct {
fn mutexOf(v: Value) *Value.MutexCell {
return switch (v) {
.mutex => |mc| mc,
.place => |p| mutexOf(p.cell.value),
.place => |p| mutexOf(placePtr(p).*),
else => unreachable,
};
}
@@ -1501,7 +1512,7 @@ const Machine = struct {
}
fn placePtr(p: Value.Place) *Value {
var v = &p.cell.value;
var v = if (p.cell.backing) |b| &b.values[b.index] else &p.cell.value;
for (p.path) |i| v = switch (v.*) {
.aggregate => |a| &a.fields[i],
.array => |items| &items[i],
@@ -1567,7 +1578,7 @@ const Machine = struct {
fn resourceOf(v: Value) u32 {
return switch (v) {
.resource => |hd| hd,
.place => |p| p.cell.value.resource,
.place => |p| placePtr(p).resource,
else => unreachable,
};
}
@@ -1761,6 +1772,19 @@ const Machine = struct {
fn execAlloc(m: *Machine, f: air.Function, vals: []Value, types_of: anytype, inst: air.Inst) !Step {
_ = types_of;
switch (inst.op) {
.own_pack => |x| {
const a = vals[x.cap].cap;
const bytes = budget.accountedSize(m.module, x.ty, 0);
if (!m.charge(a, bytes)) {
vals[f.blocks[x.err].params[1].value] = vals[x.value];
return allocFailed(f, vals, x.err);
}
const cell = try m.heap().create(Value.Cell);
cell.* = .{ .value = try m.deepCopy(vals[x.value]), .ty = x.ty };
try m.owners.put(m.heap(), cell, .{ .authority = a, .bytes = bytes.? });
vals[f.blocks[x.ok].params[0].value] = .{ .own = cell };
return .{ .jump = x.ok };
},
.own_new => |x| {
const v = vals[x.value];
const bytes = m.valueBytes(vals[x.value]);
@@ -1780,7 +1804,7 @@ const Machine = struct {
const items = try m.heap().alloc(Value, n);
for (items) |*it| it.* = try m.deepCopy(vals[x.value]);
const cell = try m.heap().create(Value.Cell);
cell.* = .{ .value = .{ .array = items }, .ty = .void };
cell.* = .{ .value = .{ .array = items }, .ty = .void, .owner_array = true };
try m.owners.put(m.heap(), cell, .{ .authority = a, .bytes = bytes.? });
vals[f.blocks[x.ok].params[0].value] = .{ .own = cell };
return .{ .jump = x.ok };
@@ -1949,6 +1973,20 @@ const Machine = struct {
return @truncate(v.int.bits);
}
fn ssaCell(m: *Machine, vals: []Value, index: u32) !*Value.Cell {
for (vals) |v| {
const cell: ?*Value.Cell = switch (v) {
.place => |p| p.cell,
.slice => |s| s.place.cell,
else => null,
};
if (cell) |c| if (c.backing) |b| if (b.values.ptr == vals.ptr and b.index == index) return c;
}
const cell = try m.heap().create(Value.Cell);
cell.* = .{ .value = .void, .ty = .void, .backing = .{ .values = vals, .index = index } };
return cell;
}
fn execMemory(m: *Machine, vals: []Value, inst: air.Inst) std.mem.Allocator.Error!Step {
switch (inst.op) {
.local_alloc => |t| {
@@ -1973,22 +2011,9 @@ const Machine = struct {
},
.borrow_ref, .borrow_mut => |v| return bind(vals, inst.result, switch (vals[v]) {
.local => |c| .{ .place = .{ .cell = c, .path = &.{} } },
// A borrowed resource: a place whose cell holds the handle.
// Owners: the heap cell itself; arrays are borrowed as slices.
.own => |cell| switch (cell.value) {
.array => |items| .{ .slice = .{ .place = .{ .cell = cell, .path = &.{} }, .start = 0, .len = items.len } },
else => .{ .place = .{ .cell = cell, .path = &.{} } },
},
.region => |r| blk: {
const cell = try m.heap().create(Value.Cell);
cell.* = .{ .value = .{ .region = r }, .ty = .void };
break :blk .{ .place = .{ .cell = cell, .path = &.{} } };
},
.resource => |hd| blk: {
const cell = try m.heap().create(Value.Cell);
cell.* = .{ .value = .{ .resource = hd }, .ty = .void };
break :blk .{ .place = .{ .cell = cell, .path = &.{} } };
},
.own => |cell| if (cell.owner_array) .{ .slice = .{ .place = .{ .cell = cell, .path = &.{} }, .start = 0, .len = cell.value.array.len } } else .{ .place = .{ .cell = cell, .path = &.{} } },
.aggregate, .array, .resource, .region => .{ .place = .{ .cell = try m.ssaCell(vals, v), .path = &.{} } },
.graph => if (inst.op == .borrow_mut) .{ .place = .{ .cell = try m.ssaCell(vals, v), .path = &.{} } } else vals[v],
else => |x| x,
}),
.borrow_field => |x| return bind(vals, inst.result, .{ .place = try m.extend(asPlace(vals[x.borrow]), x.field) }),
@@ -2004,6 +2029,13 @@ const Machine = struct {
placePtr(p).* = try m.deepCopy(vals[x.value]);
return .next;
},
.value_swap => |x| {
const p = asPlace(vals[x.borrow]);
if (try m.raceCheck(p.cell, p.path, true)) |r| return r;
const old = placePtr(p).*;
placePtr(p).* = try m.deepCopy(vals[x.value]);
return bind(vals, inst.result, old);
},
.array_splat => |x| {
const items = try m.heap().alloc(Value, x.ty.array.len);
for (items) |*it| it.* = try m.deepCopy(vals[x.value]);
+1 -1
View File
@@ -64,7 +64,7 @@ fn analyze(arena: std.mem.Allocator, m: air.Module, f: air.Function) !FnInfo {
_ = try addOnce(arena, &info.intrinsics, reg.name);
if (reg.effect) |e| _ = try addOnce(arena, &info.direct, e);
},
.own_new, .own_array, .region_new, .region_array, .region_create, .channel_make, .island_create, .island_alloc, .arc_new => {
.own_new, .own_pack, .own_array, .region_new, .region_array, .region_create, .channel_make, .island_create, .island_alloc, .arc_new => {
info.allocations += 1;
_ = try addOnce(arena, &info.direct, "mem.alloc");
},
+43 -9
View File
@@ -191,7 +191,7 @@ const Walker = struct {
/// Linear values: resources, owners and regions (spec 06 §6, spec 03 §19–§20).
fn isResource(w: *Walker, v: ValueId) bool {
return w.types[v].isLinear();
return w.c.module.isLinearType(w.types[v]);
}
/// A non-consuming use of resource `v` (a borrow of it).
@@ -252,10 +252,11 @@ fn edges(op: air.Op, out: *std.ArrayList(Edge), arena: std.mem.Allocator) !void
for (x.cases) |c| try out.append(arena, .{ .target = c.target.block, .args = c.target.args });
try out.append(arena, .{ .target = x.default.block, .args = x.default.args });
},
.enum_switch => |x| {
inline .enum_switch, .enum_take => |x| {
for (x.arms) |a| try out.append(arena, .{ .target = a.block, .args = &.{} });
if (x.default) |d| try out.append(arena, .{ .target = d.block, .args = d.args });
},
.aggregate_unpack => |x| try out.append(arena, .{ .target = x.next, .args = &.{} }),
.cap_narrow => |x| {
try out.append(arena, .{ .target = x.ok, .args = &.{} });
try out.append(arena, .{ .target = x.err, .args = &.{} });
@@ -264,7 +265,7 @@ fn edges(op: air.Op, out: *std.ArrayList(Edge), arena: std.mem.Allocator) !void
try out.append(arena, .{ .target = ok, .args = &.{} });
try out.append(arena, .{ .target = x.err.?, .args = &.{} });
},
.own_new, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => {
inline .own_new, .own_pack, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => {
const t = air.allocTargets(op).?;
try out.append(arena, .{ .target = t.ok, .args = &.{} });
try out.append(arena, .{ .target = t.err, .args = &.{} });
@@ -302,7 +303,7 @@ fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void {
.parent = null,
};
// Linear parameters were moved in: the function owns them (spec 06 §6.3).
if (p.ty.isLinear()) w.live[p.value] = true;
if (c.module.isLinearType(p.ty)) w.live[p.value] = true;
}
const dom = try ssa.dominators(c.arena, f);
@@ -318,7 +319,7 @@ fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void {
const blk = f.blocks[b];
// Linear block parameters own their argument from here on; the
// parameter of a region allocation's `ok` target is a live borrow.
for (blk.params) |p| if (p.ty.isLinear() or (p.ty.isBorrow() and w.info[p.value] != null)) {
for (blk.params) |p| if (c.module.isLinearType(p.ty) or (p.ty.isBorrow() and w.info[p.value] != null)) {
w.live[p.value] = true;
w.dead[p.value] = .none;
};
@@ -337,19 +338,19 @@ fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void {
for (out.items) |e| {
@memcpy(w.live, base);
@memcpy(w.dead, base_dead);
for (e.args) |a| if (types[a].isLinear()) try w.consume(a, .moved);
for (e.args) |a| if (c.module.isLinearType(types[a])) try w.consume(a, .moved);
// A linear parameter of the target that is still live on this
// edge would be overwritten: that instance leaks. Parameters are
// not part of the incoming state; they come alive in the block.
for (f.blocks[e.target].params) |p| {
if (p.ty.isLinear() and w.live[p.value]) try w.report("E3002", "linear value not consumed before it is redefined", p.value, null);
if (c.module.isLinearType(p.ty) and w.live[p.value]) try w.report("E3002", "linear value not consumed before it is redefined", p.value, null);
w.live[p.value] = false;
}
if (entry_state[e.target]) |expected| {
if (!std.mem.eql(bool, expected, w.live) and !reported_join[e.target]) {
reported_join[e.target] = true;
for (expected, w.live, 0..) |a, x, v| if (a != x) {
const is_res = types[v].isLinear();
const is_res = c.module.isLinearType(types[v]);
try c.report(if (is_res) "E3002" else "E2105", f.blocks[e.target].span, if (is_res) "resource state differs between edges into this block" else "borrow state differs between edges into this block", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "block", .value = .{ .str = f.blocks[e.target].name } },
@@ -433,7 +434,40 @@ fn step(w: *Walker, inst: air.Inst) !void {
w.live[r] = true;
};
},
.own_free, .own_take => |v| try w.consume(v, .closed),
inline .struct_make, .enum_make, .array_make => |x| {
for (x.args) |v| if (w.isResource(v)) try w.consume(v, .moved);
if (inst.result) |r| {
if (w.isResource(r)) w.live[r] = true;
}
},
.struct_get => |x| {
if (w.isResource(x.a)) {
_ = try w.resourceUsable(x.a);
try w.access(x.a, &.{.{ .field = x.field }}, .shared, null, x.a);
}
},
.aggregate_unpack => |x| {
if (w.isResource(x.value)) try w.consume(x.value, .moved);
},
.enum_take => |x| {
if (w.isResource(x.value)) try w.consume(x.value, .moved);
},
.own_pack => |x| {
if (w.isResource(x.value)) try w.consume(x.value, .moved);
},
.value_swap => |x| {
try w.useThrough(x.borrow, .exclusive);
if (w.isResource(x.value)) try w.consume(x.value, .moved);
if (inst.result) |r| {
if (w.isResource(r)) w.live[r] = true;
}
},
.own_free, .own_take => |v| {
try w.consume(v, .closed);
if (inst.result) |r| {
if (w.isResource(r)) w.live[r] = true;
}
},
.task_scope_begin => w.live[inst.result.?] = true,
.task_spawn => |x| {
try noWaitUnderLock(w, "task.spawn");
+2 -1
View File
@@ -87,6 +87,7 @@ pub fn check(c: *verifier.Context) !void {
for (b.insts) |inst| switch (inst.op) {
.call => |x| try limit(c, inst.span, "arguments per call", Limits.params, x.args.len),
.struct_make => |x| try limit(c, inst.span, "arguments per call", Limits.params, x.args.len),
.array_make => |x| try limit(c, inst.span, "arguments per call", Limits.params, x.args.len),
.enum_make => |x| try limit(c, inst.span, "arguments per call", Limits.params, x.args.len),
.@"switch" => |x| try limit(c, inst.span, "cases per switch", Limits.cases, x.cases.len),
else => {},
@@ -150,7 +151,7 @@ fn checkValueSizes(c: *verifier.Context) !void {
for (b.params) |p| try v.visit(b.span, p.ty);
for (b.insts) |inst| switch (inst.op) {
.local_alloc => |t| try v.visit(inst.span, t),
.array_splat => |x| try v.visit(inst.span, x.ty),
inline .array_splat, .array_make, .aggregate_unpack, .own_pack => |x| try v.visit(inst.span, x.ty),
else => {},
};
}
+14 -1
View File
@@ -53,7 +53,8 @@ fn checkTerminator(c: *Context, f: air.Function, inst: air.Inst) !void {
}
try arity(c, f, inst.span, x.default);
},
.enum_switch => |x| {
inline .enum_switch, .enum_take => |x| {
if (inst.op == .enum_take and x.default != null) try invalid(c, f, inst.span, "enum.take cannot have a default", null);
const m = c.module;
for (x.arms, 0..) |arm, i| {
for (x.arms[0..i]) |prev| if (prev.variant == arm.variant)
@@ -74,6 +75,18 @@ fn checkTerminator(c: *Context, f: air.Function, inst: air.Inst) !void {
}
}
},
.aggregate_unpack => |x| {
const n: usize = switch (x.ty) {
.array => |a| @intCast(a.len),
.named => |i| if (c.module.types[i].kind == .@"struct") c.module.types[i].kind.@"struct".len else 0,
else => 0,
};
try paramCount(c, f, inst.span, x.next, n, "unpack target must receive every component");
},
.own_pack => |x| {
try paramCount(c, f, inst.span, x.ok, 1, "own.pack success takes owner");
try paramCount(c, f, inst.span, x.err, 2, "own.pack failure takes error and original value");
},
// `ok` receives the narrowed capability, `err` the `cap_error` (spec 05 §10.4).
.cap_narrow => |x| {
try paramCount(c, f, inst.span, x.ok, 1, "cap.narrow `ok` target takes exactly one parameter");
+1 -1
View File
@@ -57,7 +57,7 @@ pub fn check(c: *Context) !void {
.atomic_store => |x| try needAtomic(c, f, inst, x.ord != .seq_cst),
.atomic_rmw => |x| try needAtomic(c, f, inst, x.ord != .seq_cst),
.atomic_cmpxchg => |x| try needAtomic(c, f, inst, x.success != .seq_cst or x.failure != .seq_cst),
.own_new, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => if (!contains(f.effects, "mem.alloc")) {
.own_new, .own_pack, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => if (!contains(f.effects, "mem.alloc")) {
try c.report("E3101", inst.span, "allocation requires the effect mem.alloc", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "effect", .value = .{ .str = "mem.alloc" } },
+75 -13
View File
@@ -23,6 +23,10 @@ pub fn check(c: *Context) !void {
fn checkDeclarations(c: *Context) !void {
const m = c.module;
if (m.declares("linear_aggregates")) {
try checkFiniteLayouts(c);
if (c.diags.items.len != 0) return;
}
for (m.types) |d| switch (d.kind) {
.@"struct" => |fs| for (fs) |fld| try wellFormed(c, d.span, fld.ty, .member, d.name),
.@"enum" => |vs| for (vs) |v| for (v.payload) |t| try wellFormed(c, d.span, t, .member, d.name),
@@ -44,7 +48,7 @@ fn checkDeclarations(c: *Context) !void {
for (b.params) |p| try wellFormed(c, b.span, p.ty, .block_param, f.name);
for (b.insts) |inst| switch (inst.op) {
.local_alloc => |t| try wellFormed(c, inst.span, t, .member, f.name),
.array_splat => |x| try wellFormed(c, inst.span, x.ty, .member, f.name),
inline .array_splat, .array_make, .aggregate_unpack, .own_pack => |x| try wellFormed(c, inst.span, x.ty, .param, f.name),
else => {},
};
}
@@ -81,6 +85,7 @@ fn visitValue(c: *Context, state: anytype, t: Type) std.mem.Allocator.Error!void
switch (t) {
.named => |i| try visitDecl(c, state, i),
.array => |a| try visitValue(c, state, a.elem),
.own, .own_array, .sender, .receiver, .mutex, .ref, .mut, .slice, .slice_mut, .guard, .task, .local => |inner| if (c.module.declares("linear_aggregates")) try visitValue(c, state, inner.*),
else => {},
}
}
@@ -98,9 +103,11 @@ fn wellFormed(c: *Context, span: air.Span, t: Type, pos: Position, owner: []cons
.void, .never => pos == .ret,
.local => false,
.ref, .mut, .slice, .slice_mut => pos != .member and pos != .borrowed,
.resource, .own, .own_array, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .atomic => pos != .member,
.scope, .task, .shield, .guard => pos != .member,
.resource, .own, .own_array, .region, .sender, .receiver, .mutex, .island, .frozen, .arc, .atomic => pos != .member or c.module.declares("linear_aggregates"),
else => true,
};
if (t == .own_array and c.module.declares("linear_aggregates") and c.module.isLinearType(t.own_array.*)) try c.report("E1001", span, "dynamic heap arrays require Copy content", &.{});
// An atomic cell holds an AtomicScalar (spec 04 §23).
if (t == .atomic and !isAtomicScalar(t.atomic.*)) try c.report("E1001", span, "atomic<T> needs bool or an integer of at most 64 bits", &.{
.{ .name = "in", .value = .{ .str = owner } },
@@ -269,7 +276,7 @@ fn resultType(m: air.Module, op: air.Op) ?Type {
if (reg.fallible or reg.results.len == 0) break :blk .void;
break :blk intrinsicResult(reg.results[0]);
},
.array_splat => |x| x.ty,
inline .array_splat, .array_make => |x| x.ty,
else => null,
};
}
@@ -595,6 +602,10 @@ fn checkSelect(fc: *FnCtx, inst: air.Inst, x: @FieldType(air.Op, "select")) !voi
_ = f;
}
pub fn complete(t: Type) bool {
return t != .void and t != .never and t != .local and !t.isBorrow() and !t.isTaskBound() and t != .guard;
}
fn boxed(arena: std.mem.Allocator, t: Type) !*const Type {
const b = try arena.create(Type);
b.* = t;
@@ -612,6 +623,7 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type {
.local_alloc => |inner| return .{ .local = try boxed(a, inner) },
.local_load => |v| fc.ty[v] orelse return null,
.borrow_ref, .borrow_mut, .load, .slice_make => |v| fc.ty[v] orelse return null,
.value_swap => |x| fc.ty[x.borrow] orelse return null,
.borrow_field => |x| fc.ty[x.borrow] orelse return null,
.borrow_index => |x| fc.ty[x.borrow] orelse return null,
.slice_sub => |x| fc.ty[x.slice] orelse return null,
@@ -632,9 +644,11 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type {
};
const invalid: Type = .void;
return switch (op) {
.value_swap => if (t == .mut) t.mut.* else invalid,
.local_load => if (t == .local) t.local.* else invalid,
.borrow_ref => switch (t) {
.local, .ref, .mut => .{ .ref = try boxed(a, t.inner().?) },
.named, .array => if (m.isLinearType(t)) .{ .ref = try boxed(a, t) } else invalid,
.resource, .region, .task, .scope, .sender, .receiver, .mutex, .island, .frozen, .arc, .atomic => .{ .ref = try boxed(a, t) },
.own => |inner| .{ .ref = inner },
.own_array => |inner| .{ .slice = inner },
@@ -643,6 +657,7 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type {
},
.borrow_mut => switch (t) {
.local, .mut => .{ .mut = try boxed(a, t.inner().?) },
.named, .array => if (m.isLinearType(t)) .{ .mut = try boxed(a, t) } else invalid,
.resource, .region, .task, .scope, .sender, .receiver, .island => .{ .mut = try boxed(a, t) },
.own => |inner| .{ .mut = inner },
.own_array => |inner| .{ .slice_mut = inner },
@@ -771,11 +786,12 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
const span = inst.span;
switch (inst.op) {
.@"const", .trap => {},
.copy => |v| if (!fc.typeOf(v).isValue()) try fc.c.report("E1001", span, "only value types can be copied", &.{
.copy => |v| if (!fc.typeOf(v).isValue() or m.isLinearType(fc.typeOf(v))) try fc.c.report("E1001", span, "only value types can be copied", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "found", .value = .{ .str = try fc.c.typeName(fc.typeOf(v)) } },
}),
.local_alloc, .slice_len => {},
.local_alloc => |t| if (m.isLinearType(t)) try fc.c.report("E1001", span, "frame storage requires Copy content", &.{}),
.slice_len => {},
.local_store => |x| {
const t = fc.typeOf(x.local);
if (t != .local) return fc.kindError(span, x.local, "local<T>");
@@ -789,7 +805,9 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
.{ .name = "found", .value = .{ .str = try fc.c.typeName(t.local.*) } },
});
},
.local_load => |v| if (fc.typeOf(v) != .local) try fc.kindError(span, v, "local<T>"),
.local_load => |v| {
if (fc.typeOf(v) != .local) try fc.kindError(span, v, "local<T>");
},
.borrow_ref => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "local<T>, a resource, ref<T>, mut<T>, slice<T> or slice_mut<T>"),
.borrow_mut => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "local<T>, a resource, mut<T> or slice_mut<T>"),
.borrow_field => |x| if (resultOf(fc, inst) == .void) try fc.kindError(span, x.borrow, "ref or mut of the named struct"),
@@ -797,12 +815,38 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
.load => |v| {
if (atomicPointee(fc.typeOf(v))) return ordinaryAtomicAccess(fc, span, v, "atomic.load");
if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "ref<T> or mut<T>");
if (m.isLinearType(resultOf(fc, inst))) try fc.c.report("E1001", span, "load cannot copy linear content; exchange or unpack", &.{});
},
.store => |x| {
const t = fc.typeOf(x.borrow);
if (atomicPointee(t)) return ordinaryAtomicAccess(fc, span, x.borrow, "atomic.store");
if (t != .mut) return fc.kindError(span, x.borrow, "mut<T>");
try fc.expectValue(span, x.value, t.mut.*);
if (m.isLinearType(t.mut.*)) try fc.c.report("E1001", span, "store cannot overwrite linear content; use value.swap", &.{});
},
.value_swap => |x| {
const t = fc.typeOf(x.borrow);
if (atomicPointee(t)) return ordinaryAtomicAccess(fc, span, x.borrow, "atomic operations");
if (t != .mut) return fc.kindError(span, x.borrow, "mut<T>");
try fc.expectValue(span, x.value, t.mut.*);
if (!complete(t.mut.*)) try fc.kindError(span, x.value, "a complete value");
},
.array_make => |x| {
if (x.ty != .array) return fc.c.report("E1001", span, "array.make needs an array type", &.{});
if (x.args.len != x.ty.array.len) return fc.c.report("E1001", span, "array.make requires every element", &.{});
for (x.args) |arg| try fc.expectValue(span, arg, x.ty.array.elem);
},
.aggregate_unpack => |x| {
try fc.expectValue(span, x.value, x.ty);
switch (x.ty) {
.array => |a| for (f.blocks[x.next].params) |p| {
if (!p.ty.eql(a.elem)) try fc.mismatch(span, try fc.c.valueName(f, p.value), a.elem, p.ty);
},
.named => |i| if (m.types[i].kind == .@"struct") {
for (f.blocks[x.next].params, m.types[i].kind.@"struct") |p, field| if (!p.ty.eql(field.ty)) try fc.mismatch(span, try fc.c.valueName(f, p.value), field.ty, p.ty);
} else try fc.c.report("E1001", span, "unpack requires a struct or array", &.{}),
else => try fc.c.report("E1001", span, "unpack requires a struct or array", &.{}),
}
},
.array_splat => |x| {
if (x.ty != .array) return fc.c.report("E1001", span, "array.splat needs an array type", &.{
@@ -810,6 +854,7 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
.{ .name = "found", .value = .{ .str = try fc.c.typeName(x.ty) } },
});
try fc.expectValue(span, x.value, x.ty.array.elem);
if (m.isLinearType(x.ty.array.elem)) try fc.c.report("E1001", span, "array.splat cannot duplicate linear elements", &.{});
},
.borrow_index => |x| {
if (resultOf(fc, inst) == .void) return fc.kindError(span, x.borrow, "a borrow of an array, or a slice");
@@ -827,6 +872,7 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
},
.slice_copy => |x| {
const d = fc.typeOf(x.dst);
if (d == .slice_mut and m.isLinearType(d.inner().?)) return fc.c.report("E1001", span, "slice.copy cannot copy linear elements", &.{});
if (d != .slice_mut) return fc.kindError(span, x.dst, "slice_mut<T>");
const s = fc.typeOf(x.src);
if (!s.isSlice() or !s.inner().?.eql(d.inner().?)) return fc.kindError(span, x.src, try std.fmt.allocPrint(fc.c.arena, "slice<{s}> or slice_mut<{s}>", .{ try fc.c.typeName(d.inner().?), try fc.c.typeName(d.inner().?) }));
@@ -859,7 +905,10 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
for (fields, tys) |fld, *t| t.* = fld.ty;
try fc.expectArgs(span, x.args, tys);
},
.struct_get => |x| try fc.expectValue(span, x.a, .{ .named = x.decl }),
.struct_get => |x| {
try fc.expectValue(span, x.a, .{ .named = x.decl });
if (m.isLinearType(m.types[x.decl].kind.@"struct"[x.field].ty)) try fc.c.report("E1001", span, "linear fields require whole unpack or borrowed exchange", &.{});
},
.enum_make => |x| try fc.expectArgs(span, x.args, m.types[x.decl].kind.@"enum"[x.variant].payload),
.call => |x| {
const callee = m.functions[x.callee];
@@ -889,7 +938,9 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
for (x.cases) |case| try fc.expectTarget(case.span, case.target);
try fc.expectTarget(span, x.default);
},
.enum_switch => |x| {
inline .enum_switch, .enum_take => |x| {
if (inst.op == .enum_take and x.ty != .named) try fc.c.report("E1001", span, "enum.take requires a declared enum", &.{});
if (inst.op == .enum_switch and m.isLinearType(x.ty)) try fc.c.report("E1001", span, "linear enums require enum.take", &.{});
try fc.expectValue(span, x.value, x.ty);
for (x.arms) |arm| {
const params = f.blocks[arm.block].params;
@@ -900,21 +951,32 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
if (x.default) |d| try fc.expectTarget(span, d);
},
.intrinsic => |x| try checkIntrinsic(fc, inst, x),
.own_pack => |x| {
try fc.expectAllocCap(span, x.cap);
try fc.expectValue(span, x.value, x.ty);
if (!complete(x.ty)) return fc.kindError(span, x.value, "a complete value");
try fc.expectParams(span, x.ok, &.{.{ .own = try boxed(fc.c.arena, x.ty) }});
try fc.expectParams(span, x.err, &.{ .{ .builtin = .alloc_error }, x.ty });
},
.own_new => |x| {
try fc.expectAllocCap(span, x.cap);
const t = fc.typeOf(x.value);
if (!t.isValue()) return fc.kindError(span, x.value, "a value type");
if (!t.isValue() or m.isLinearType(t)) return fc.kindError(span, x.value, "a Copy value type");
try fc.expectOkErr(span, x.ok, x.err, .{ .own = try boxed(fc.c.arena, t) });
},
.own_array => |x| {
try fc.expectValue(span, x.n, .{ .int = .usize });
try fc.expectAllocCap(span, x.cap);
const t = fc.typeOf(x.value);
if (!t.isValue()) return fc.kindError(span, x.value, "a value type");
if (!t.isValue() or m.isLinearType(t)) return fc.kindError(span, x.value, "a Copy value type");
try fc.expectOkErr(span, x.ok, x.err, .{ .own_array = try boxed(fc.c.arena, t) });
},
.own_take => |v| if (fc.typeOf(v) != .own) try fc.kindError(span, v, "own<T>"),
.own_free => |v| if (fc.typeOf(v) != .own and fc.typeOf(v) != .own_array) try fc.kindError(span, v, "own<T> or own_array<T>"),
.own_free => |v| {
const t = fc.typeOf(v);
if (t != .own and t != .own_array) return fc.kindError(span, v, "own<T> or own_array<T>");
if (m.isLinearType(t.inner().?)) try fc.c.report("E1001", span, "own.free cannot destroy linear content; use own.take", &.{});
},
.region_create => |x| {
try fc.expectAllocCap(span, x.cap);
try fc.expectOkErr(span, x.ok, x.err, .region);
@@ -922,14 +984,14 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
.region_new => |x| {
try fc.expectRegionRef(span, x.region);
const t = fc.typeOf(x.value);
if (!t.isValue()) return fc.kindError(span, x.value, "a value type");
if (!t.isValue() or m.isLinearType(t)) return fc.kindError(span, x.value, "a Copy value type");
try fc.expectOkErr(span, x.ok, x.err, .{ .mut = try boxed(fc.c.arena, t) });
},
.region_array => |x| {
try fc.expectRegionRef(span, x.region);
try fc.expectValue(span, x.n, .{ .int = .usize });
const t = fc.typeOf(x.value);
if (!t.isValue()) return fc.kindError(span, x.value, "a value type");
if (!t.isValue() or m.isLinearType(t)) return fc.kindError(span, x.value, "a Copy value type");
try fc.expectOkErr(span, x.ok, x.err, .{ .slice_mut = try boxed(fc.c.arena, t) });
},
.region_reset, .region_destroy => |v| if (fc.typeOf(v) != .region) try fc.kindError(span, v, "region"),