Phase 4: islands, frozen graphs and arc through every layer (RFC 0014)

AIR: types island<T>, frozen<T>, arc<T>, iref<T>; 16 instructions
(island.create/alloc/root/borrow/freeze/destroy, frozen.root/borrow/
release, arc.from_frozen/new/clone/release/root/borrow, iref.eq); features
islands (depends on heap) and arc (depends on islands) published.
Verifier: IslandSafe/ArcSafe (E2111 at the owner type), container child
borrows (one mut access per island), Send/Share rows (island not Share),
linear owners, mem.alloc effect, element rules (recursion through iref).
Interpreter: graphs with never-reused identities, T0010 for a foreign
iref, O(1) freeze/conversion/transfer, arc counts in a trace hook
(Options.arc_events), budgets per the quota table, collector support.
.aji layer 9: types, operations, island.at/frozen.at/arc.at as borrow
places with explicit container borrows, iref ==/!=.
Frontend fix: joins carry only variables the construct assigns (and that
are read again), so an unchanged linear value is never a block argument
while borrowed.

Tests: 10 AIR (phase4), 6 .aji run + 12 rejects (layer9), the reference
program island-pipeline in .aji, equivalent to an independently
hand-written AIR program (36 on 30 schedule seeds); unit tests for the
arc count trace and O(1) transfer. Quick Reference §7 graphs (checked
excerpt of quickref/graphs.aji); coverage 61/61. Bundle growth: AIR
+7.0%, Quick Reference +0.6k, source docs +4.2k (recorded).
Spec: quota rows match the header-reserved count; idioms and iref
recursion in spec 03 §22; P4-11 (air-text.ebnf gaps) recorded.
This commit is contained in:
dev committed 2026-10-05 22:14:05 +03:00
1 parent ca84ab4348
commit c699529fec
58 files changed
+2189 -98

No files matched your search

+3 -2
View File
@@ -22,6 +22,7 @@ pub const Feature = struct {
};
pub const registry = [_]Feature{
.{ .name = "arc", .depends = &.{ "capabilities", "effects", "heap", "islands", "ownership", "resources" }, .status = .published, .phase = 4 },
.{ .name = "arrays", .depends = &.{"ownership"}, .status = .published, .phase = 1 },
.{ .name = "atomics", .depends = &.{"ownership"}, .status = .reserved, .phase = 5 },
.{ .name = "borrow_joins", .depends = &.{"ownership"}, .status = .reserved, .phase = null },
@@ -32,7 +33,7 @@ pub const registry = [_]Feature{
.{ .name = "effects", .depends = &.{}, .status = .published, .phase = 2 },
.{ .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", "regions", "resources" }, .status = .reserved, .phase = 4 },
.{ .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 = "ownership", .depends = &.{}, .status = .published, .phase = 1 },
.{ .name = "receiver_dup", .depends = &.{ "cancellation", "capabilities", "channels", "effects", "heap", "ownership", "resources", "tasks" }, .status = .reserved, .phase = null },
@@ -48,7 +49,7 @@ pub const registry = [_]Feature{
};
/// Features implemented by this toolchain, sorted.
pub const supported = [_][]const u8{ "arrays", "cancellation", "capabilities", "channels", "effects", "heap", "ownership", "regions", "resources", "sync", "tasks", "unsafe" };
pub const supported = [_][]const u8{ "arc", "arrays", "cancellation", "capabilities", "channels", "effects", "heap", "islands", "ownership", "regions", "resources", "sync", "tasks", "unsafe" };
pub const Reason = enum {
unknown_feature,
+51 -7
View File
@@ -94,6 +94,11 @@ pub const Type = union(enum) {
// Feature `sync` (spec 04 §40).
mutex: *const Type,
guard: *const Type,
// Features `islands` and `arc` (spec 03 §22–§24): graph owners and handles.
island: *const Type,
frozen: *const Type,
arc: *const Type,
iref: *const Type,
pub const Array = struct { elem: Type, len: u64 };
@@ -102,7 +107,7 @@ pub const Type = union(enum) {
return switch (a) {
.int => |x| b.int == x,
.named => |x| b.named == x,
.local, .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard => |x| x.eql(b.inner().?),
.local, .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref => |x| x.eql(b.inner().?),
.region, .scope, .shield => true,
.array => |x| x.len == b.array.len and x.elem.eql(b.array.elem),
.cap => |k| b.cap == k,
@@ -115,7 +120,7 @@ pub const Type = union(enum) {
/// Element or pointee type of storage, borrow and slice types.
pub fn inner(t: Type) ?Type {
return switch (t) {
.local, .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard => |x| x.*,
.local, .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref => |x| x.*,
.array => |a| a.elem,
else => null,
};
@@ -132,11 +137,16 @@ pub const Type = union(enum) {
/// Linear values: consumed exactly once (spec 06 §6.2–§6.3).
pub fn isLinear(t: Type) bool {
return switch (t) {
.resource, .own, .own_array, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard => true,
.resource, .own, .own_array, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc => true,
else => false,
};
}
/// Graph owners (spec 03 §22–§24).
pub fn isGraphOwner(t: Type) bool {
return t == .island or t == .frozen or t == .arc;
}
/// Function-bound types (spec 04 §33.1, §37.3): never parameters, results
/// or members. `guard<T>` is function-bound too, under its own feature.
pub fn isTaskBound(t: Type) bool {
@@ -161,7 +171,7 @@ pub const Type = union(enum) {
/// Linear resources are neither values nor borrows: they are moved.
pub fn isValue(t: Type) bool {
return switch (t) {
.void, .never, .local, .ref, .mut, .slice, .slice_mut, .resource, .own, .own_array, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard => false,
.void, .never, .local, .ref, .mut, .slice, .slice_mut, .resource, .own, .own_array, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc => false,
else => true,
};
}
@@ -314,6 +324,23 @@ pub const Op = union(enum) {
mutex_lock: struct { mutex: ValueId, ok: u32, cancelled: u32 },
mutex_borrow: ValueId,
mutex_unlock: ValueId,
// Features `islands` and `arc` (spec 03 §22–§24).
island_create: struct { value: ValueId, cap: ValueId, ok: u32, err: u32 },
island_alloc: struct { island: ValueId, value: ValueId, ok: u32, err: u32 },
island_root: ValueId,
island_borrow: struct { owner: ValueId, iref: ValueId },
island_freeze: ValueId,
island_destroy: ValueId,
frozen_root: ValueId,
frozen_borrow: struct { owner: ValueId, iref: ValueId },
frozen_release: ValueId,
arc_from_frozen: ValueId,
arc_new: struct { value: ValueId, cap: ValueId, ok: u32, err: u32 },
arc_clone: ValueId,
arc_release: ValueId,
arc_root: ValueId,
arc_borrow: struct { owner: ValueId, iref: ValueId },
iref_eq: struct { a: ValueId, b: ValueId },
ret: ?ValueId,
trap,
@@ -338,7 +365,7 @@ 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 => true,
.own_new, .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,
@@ -481,6 +508,23 @@ pub fn forEachUse(op: Op, ctx: anytype, comptime f: fn (@TypeOf(ctx), ValueId) v
.own_take, .own_free, .region_reset, .region_destroy, .task_join, .task_cancel, .task_scope_end => |v| f(ctx, v),
.task_scope_begin, .task_cancelled, .task_check_cancel, .task_shield_begin => {},
.task_shield_end, .channel_dup, .channel_close_sender, .mutex_make, .mutex_take, .mutex_borrow, .mutex_unlock => |v| f(ctx, v),
.island_root, .island_freeze, .island_destroy, .frozen_root, .frozen_release, .arc_from_frozen, .arc_clone, .arc_release, .arc_root => |v| f(ctx, v),
inline .island_create, .arc_new => |x| {
f(ctx, x.value);
f(ctx, x.cap);
},
.island_alloc => |x| {
f(ctx, x.island);
f(ctx, x.value);
},
inline .island_borrow, .frozen_borrow, .arc_borrow => |x| {
f(ctx, x.owner);
f(ctx, x.iref);
},
.iref_eq => |x| {
f(ctx, x.a);
f(ctx, x.b);
},
.task_join_cancel => |x| f(ctx, x.task),
.channel_make => |x| {
f(ctx, x.cap);
@@ -548,7 +592,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 => |x| .{ .ok = x.ok, .err = x.err },
inline .own_new, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => |x| .{ .ok = x.ok, .err = x.err },
else => null,
};
}
@@ -576,7 +620,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 => |x| {
inline .own_new, .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);
},
+58 -1
View File
@@ -560,12 +560,14 @@ const Parser = struct {
boxed.* = inner;
return if (eql(t.text, "own")) .{ .own = boxed } else .{ .own_array = boxed };
}
const Wrapper = enum { task, sender, receiver, mutex, guard };
const Wrapper = enum { task, sender, receiver, mutex, guard, island, frozen, arc, iref };
if (std.meta.stringToEnum(Wrapper, t.text)) |which| {
try p.requireFeature(switch (which) {
.task => "tasks",
.sender, .receiver => "channels",
.mutex, .guard => "sync",
.island, .frozen, .iref => "islands",
.arc => "arc",
}, t.span, t.text);
_ = try p.expect(.lt, "`<`");
// Element rules (spec 04 §38.1) are checked by the type stage.
@@ -579,6 +581,10 @@ const Parser = struct {
.receiver => .{ .receiver = boxed },
.mutex => .{ .mutex = boxed },
.guard => .{ .guard = boxed },
.island => .{ .island = boxed },
.frozen => .{ .frozen = boxed },
.arc => .{ .arc = boxed },
.iref => .{ .iref = boxed },
};
}
if (eql(t.text, "cap")) {
@@ -1008,6 +1014,7 @@ const Parser = struct {
break :op .{ .cap_narrow = .{ .form = parts[2], .cap = c, .args = args.items, .ok = ok, .err = err } };
}
if (try p.parseAllocOp(op_tok)) |aop| break :op aop;
if (try p.parseGraphOp(op_tok)) |gop| break :op gop;
if (try p.parseTaskOp(op_tok)) |top| break :op top;
if (try p.parseCoordinationOp(op_tok)) |cop| break :op cop;
if (eql(op_tok.text, "intrinsic")) {
@@ -1038,6 +1045,7 @@ const Parser = struct {
const produces_value = switch (op) {
.own_take, .task_scope_begin, .task_spawn, .task_cancelled => true,
.task_shield_begin, .channel_dup, .mutex_make, .mutex_take, .mutex_borrow => true,
.island_root, .island_borrow, .island_freeze, .frozen_root, .frozen_borrow, .arc_from_frozen, .arc_clone, .arc_root, .arc_borrow, .iref_eq => 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,
@@ -1197,6 +1205,55 @@ const Parser = struct {
}
}
/// Instructions of the features `islands` and `arc` (spec 03 §22–§24).
fn parseGraphOp(p: *Parser, op_tok: Token) Error!?air.Op {
const Name = enum { @"island.create", @"island.alloc", @"island.root", @"island.borrow", @"island.freeze", @"island.destroy", @"frozen.root", @"frozen.borrow", @"frozen.release", @"iref.eq", @"arc.from_frozen", @"arc.new", @"arc.clone", @"arc.release", @"arc.root", @"arc.borrow" };
const name = std.meta.stringToEnum(Name, op_tok.text) orelse return null;
try p.requireFeature(if (std.mem.startsWith(u8, op_tok.text, "arc.")) "arc" else "islands", op_tok.span, op_tok.text);
switch (name) {
.@"island.create" => {
const v, const c = try p.twoOperands();
const ok, const err = try p.okErr();
return .{ .island_create = .{ .value = v, .cap = c, .ok = ok, .err = err } };
},
.@"island.alloc" => {
const i, const v = try p.twoOperands();
const ok, const err = try p.okErr();
return .{ .island_alloc = .{ .island = i, .value = v, .ok = ok, .err = err } };
},
.@"arc.new" => {
const v, const c = try p.twoOperands();
const ok, const err = try p.okErr();
return .{ .arc_new = .{ .value = v, .cap = c, .ok = ok, .err = err } };
},
.@"island.root" => return .{ .island_root = try p.useValue() },
.@"island.freeze" => return .{ .island_freeze = try p.useValue() },
.@"island.destroy" => return .{ .island_destroy = try p.useValue() },
.@"frozen.root" => return .{ .frozen_root = try p.useValue() },
.@"frozen.release" => return .{ .frozen_release = try p.useValue() },
.@"arc.from_frozen" => return .{ .arc_from_frozen = try p.useValue() },
.@"arc.clone" => return .{ .arc_clone = try p.useValue() },
.@"arc.release" => return .{ .arc_release = try p.useValue() },
.@"arc.root" => return .{ .arc_root = try p.useValue() },
.@"island.borrow" => {
const o, const r = try p.twoOperands();
return .{ .island_borrow = .{ .owner = o, .iref = r } };
},
.@"frozen.borrow" => {
const o, const r = try p.twoOperands();
return .{ .frozen_borrow = .{ .owner = o, .iref = r } };
},
.@"arc.borrow" => {
const o, const r = try p.twoOperands();
return .{ .arc_borrow = .{ .owner = o, .iref = r } };
},
.@"iref.eq" => {
const a, const b = try p.twoOperands();
return .{ .iref_eq = .{ .a = a, .b = b } };
},
}
}
/// 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" };
+26 -1
View File
@@ -122,7 +122,7 @@ pub fn printType(m: air.Module, t: air.Type, w: *Writer) Writer.Error!void {
},
.region => try w.writeAll("region"),
.scope => try w.writeAll("scope"),
.task, .sender, .receiver, .mutex, .guard => |inner| {
.task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref => |inner| {
try w.print("{s}<", .{@tagName(t)});
try printType(m, inner.*, w);
try w.writeByte('>');
@@ -397,6 +397,31 @@ fn printOp(m: air.Module, f: air.Function, op: air.Op, w: *Writer) Writer.Error!
},
.mutex_borrow => |v| try one(f, w, "mutex.borrow", v),
.mutex_unlock => |v| try one(f, w, "mutex.unlock", v),
.island_create => |x| {
try two(f, w, "island.create", x.value, x.cap);
try okErr(f, w, x.ok, x.err);
},
.island_alloc => |x| {
try two(f, w, "island.alloc", x.island, x.value);
try okErr(f, w, x.ok, x.err);
},
.arc_new => |x| {
try two(f, w, "arc.new", x.value, x.cap);
try okErr(f, w, x.ok, x.err);
},
.island_root => |v| try one(f, w, "island.root", v),
.island_freeze => |v| try one(f, w, "island.freeze", v),
.island_destroy => |v| try one(f, w, "island.destroy", v),
.frozen_root => |v| try one(f, w, "frozen.root", v),
.frozen_release => |v| try one(f, w, "frozen.release", v),
.arc_from_frozen => |v| try one(f, w, "arc.from_frozen", v),
.arc_clone => |v| try one(f, w, "arc.clone", v),
.arc_release => |v| try one(f, w, "arc.release", v),
.arc_root => |v| try one(f, w, "arc.root", v),
.island_borrow => |x| try two(f, w, "island.borrow", x.owner, x.iref),
.frozen_borrow => |x| try two(f, w, "frozen.borrow", x.owner, x.iref),
.arc_borrow => |x| try two(f, w, "arc.borrow", x.owner, x.iref),
.iref_eq => |x| try two(f, w, "iref.eq", x.a, x.b),
.cap_narrow => |x| {
try w.print("cap.narrow.{s} ", .{x.form});
try value(f, x.cap, w);
+229 -19
View File
@@ -21,7 +21,8 @@
//! 6. intrinsics (I/O, files, TCP, clock, random), resources, capability
//! narrowing, unsafe operations;
//! 7. task scopes, spawn and join, channels;
//! 8. `lock` and mutexes, `select`, cancellation points, shields.
//! 8. `lock` and mutexes, `select`, cancellation points, shields;
//! 9. islands, frozen graphs, arcs and `iref` handles (spec 03 §22–§24).
const std = @import("std");
const ast = @import("ast.zig");
@@ -67,13 +68,18 @@ pub const Ty = union(enum) {
guard: *const Ty,
/// A shield (`shield { … }`, never a source value).
shield,
/// Graph owners and handles (spec 03 §22–§24).
island: *const Ty,
frozen: *const Ty,
arc: *const Ty,
iref: *const Ty,
pub const Arr = struct { elem: Ty, len: u64 };
/// Linear: consumed exactly once, by `move` (spec 15 §5).
fn isLinear(t: Ty) bool {
return switch (t) {
.own, .own_array, .region, .resource, .task, .sender, .receiver, .scope, .mutex, .guard, .shield => true,
.own, .own_array, .region, .resource, .task, .sender, .receiver, .scope, .mutex, .guard, .shield, .island, .frozen, .arc => true,
else => false,
};
}
@@ -84,7 +90,7 @@ pub const Ty = union(enum) {
.int => |x| std.mem.eql(u8, x, b.int),
.named => |i| i == b.named,
.array => |x| x.len == b.array.len and x.elem.eql(b.array.elem),
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard => |x| x.eql(inner(b).?),
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref => |x| x.eql(inner(b).?),
.cap => |k| std.mem.eql(u8, k, b.cap),
.builtin => |e| e == b.builtin,
.resource => |r| r == b.resource,
@@ -94,7 +100,7 @@ pub const Ty = union(enum) {
fn inner(t: Ty) ?Ty {
return switch (t) {
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard => |x| x.*,
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref => |x| x.*,
.array => |a| a.elem,
else => null,
};
@@ -321,7 +327,7 @@ const Lowerer = struct {
.never => "never",
.named => |i| l.typeNames[i],
.array => |a| std.fmt.allocPrint(l.arena, "array<{s}, {d}>", .{ l.tyText(a.elem), a.len }) catch "array",
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard => |x| std.fmt.allocPrint(l.arena, "{s}<{s}>", .{ @tagName(t), l.tyText(x.*) }) catch "borrow",
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref => |x| std.fmt.allocPrint(l.arena, "{s}<{s}>", .{ @tagName(t), l.tyText(x.*) }) catch "borrow",
.scope => "scope",
.shield => "shield",
.region => "region",
@@ -441,6 +447,8 @@ const Lowerer = struct {
.{ "channels", &.{ "channel.", "sender<", "receiver<", "select [" } },
.{ "sync", &.{ "mutex.", "mutex<", "guard<" } },
.{ "cancellation", &.{ "task.shield", "task.check_cancel", "task.join.cancel" } },
.{ "islands", &.{ "island.", "island<", "frozen.", "frozen<", "iref.", "iref<" } },
.{ "arc", &.{ "arc.", "arc<" } },
};
for (rules) |r| {
const used = for (texts.items) |t| {
@@ -511,7 +519,7 @@ const Lowerer = struct {
},
.array => |a| return l.arrayOf(try l.memberType(a.elem.*), a.len),
.wrapped => |w| {
const Wr = enum { ref, mut, slice, slice_mut, own, own_array, task, sender, receiver, mutex };
const Wr = enum { ref, mut, slice, slice_mut, own, own_array, task, sender, receiver, mutex, island, frozen, arc, iref };
const which = std.meta.stringToEnum(Wr, w.wrapper) orelse return l.notYet(t.span, "this type (later layers)");
const in = try l.typeOf(w.inner.*);
return switch (which) {
@@ -525,6 +533,10 @@ const Lowerer = struct {
.sender => l.wrap(.sender, in),
.receiver => l.wrap(.receiver, in),
.mutex => l.wrap(.mutex, in),
.island => l.wrap(.island, in),
.frozen => l.wrap(.frozen, in),
.arc => l.wrap(.arc, in),
.iref => l.wrap(.iref, in),
};
},
.cap => |k| {
@@ -682,9 +694,12 @@ const Lowerer = struct {
/// that may be read after it (pruned SSA, spec 15 §4). A variable that is
/// not read again is not passed on, so a linear value consumed before the
/// join does not travel to it.
fn carriedLive(l: *Lowerer, depth: usize, construct: Span) Error![]const usize {
fn carriedLive(l: *Lowerer, depth: usize, construct: Span, region: Region) Error![]const usize {
var out: std.ArrayList(usize) = .empty;
for (try l.carried(depth)) |i| if (l.liveAfter(l.bindings.items[i].name, construct)) try out.append(l.arena, i);
for (try l.carried(depth)) |i| {
const n = l.bindings.items[i].name;
if (region.assigns(n) and l.liveAfter(n, construct)) try out.append(l.arena, i);
}
return out.items;
}
@@ -692,9 +707,10 @@ const Lowerer = struct {
/// itself reads (they flow around the back edge).
fn carriedLoop(l: *Lowerer, depth: usize, construct: Span, lp: LoopAst) Error![]const usize {
var out: std.ArrayList(usize) = .empty;
const region: Region = .{ .loop = lp };
for (try l.carried(depth)) |i| {
const n = l.bindings.items[i].name;
if (loopReads(lp, n) or l.liveAfter(n, construct)) try out.append(l.arena, i);
if (region.assigns(n) and (loopReads(lp, n) or l.liveAfter(n, construct))) try out.append(l.arena, i);
}
return out.items;
}
@@ -915,6 +931,8 @@ const Lowerer = struct {
const scope_start = l.scopeBindingStart();
for (l.bindings.items[scope_start..]) |b| if (b.kind == .borrow and std.mem.eql(u8, b.name, x.name))
return l.fail("E7006", s.span, "a borrow of this name is already active in this scope", &.{.{ .name = "name", .value = x.name }});
if (x.place.kind == .call) if (pathOf(x.place.kind.call.callee.*)) |p| if (std.mem.endsWith(u8, p, ".at"))
return l.graphAccess(s, x.name, x.mutable, x.place);
const p = try l.uncheckedPlace(x.place, x.mutable, x.unchecked, s.span);
if (p.ends.len == 0) {
// Borrowing a borrow binding: a reborrow, ended at scope end.
@@ -991,7 +1009,7 @@ const Lowerer = struct {
const depth = l.bindings.items.len;
const lp_ast: LoopAst = .{ .cond = cond, .body = body, .step = if (step) |st| st.name else null };
const vars = try l.carriedLoop(depth, span, lp_ast);
const exit_vars = try l.carriedLive(depth, span);
const exit_vars = try l.carriedLive(depth, span, .{ .loop = lp_ast });
const header = try l.newBlock(if (cond == null) "loop" else "while");
const exit = try l.newBlock("after");
const cont = if (step != null) try l.newBlock("step") else header;
@@ -1339,6 +1357,14 @@ const Lowerer = struct {
try l.checkTy(a.span, lv.ty, ty);
const rv = try l.expr(b, ty);
try l.checkTy(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", &.{});
@@ -1565,7 +1591,7 @@ const Lowerer = struct {
if (st == .builtin) return l.builtinMatch(m, st.builtin, want);
const sv = try l.expr(m.scrutinee, st);
const depth = l.bindings.items.len;
const vars = try l.carriedLive(depth, m.span);
const vars = try l.carriedLive(depth, m.span, .{ .match = m });
const before = try l.snapshot();
var ends: std.ArrayList(ArmEnd) = .empty;
@@ -1659,7 +1685,7 @@ const Lowerer = struct {
const name = @tagName(b);
const sv = try l.expr(m.scrutinee, .{ .builtin = b });
const depth = l.bindings.items.len;
const vars = try l.carriedLive(depth, m.span);
const vars = try l.carriedLive(depth, m.span, .{ .match = m });
const before = try l.snapshot();
const blocks = try l.arena.alloc(usize, m.arms.len);
var head: std.ArrayList(u8) = .empty;
@@ -1699,6 +1725,11 @@ const Lowerer = struct {
const eq = std.mem.eql;
if ((eq(u8, p, "own.take") or eq(u8, p, "task.join")) and args.len == 1) return if (l.peekType(args[0])) |t| t.inner() else null;
if (eq(u8, p, "task.cancelled")) return .bool;
if ((eq(u8, p, "island.root") or eq(u8, p, "frozen.root") or eq(u8, p, "arc.root")) and args.len == 1)
return if (l.peekType(args[0])) |t| (if (t.inner()) |o| (if (o.inner()) |root| l.wrap(.iref, root) catch null else null) else null) else null;
if (eq(u8, p, "island.freeze") and args.len == 1) return if (l.peekType(args[0])) |t| (if (t == .island) l.wrap(.frozen, t.inner().?) catch null else null) else null;
if (eq(u8, p, "arc.from_frozen") and args.len == 1) return if (l.peekType(args[0])) |t| (if (t == .frozen) l.wrap(.arc, t.inner().?) catch null else null) else null;
if (eq(u8, p, "arc.clone") and args.len == 1) return if (l.peekType(args[0])) |t| (if (t == .arc) t else if (t.inner()) |in| (if (in == .arc) in else null) else null) else null;
if (eq(u8, p, "channel.dup") and args.len == 1) return if (l.peekType(args[0])) |t| (if (t == .sender) t else if (t.inner()) |in| (if (in == .sender) in else null) else null) else null;
if (eq(u8, p, "task.spawn") and args.len >= 2 and args[1].kind == .name) {
const sig = l.sigs.get(args[1].kind.name) orelse return null;
@@ -1860,7 +1891,8 @@ const Lowerer = struct {
.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),
.resource, .mutex, .sender, .receiver, .task => if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty),
.resource, .mutex, .sender, .receiver, .task, .island => if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty),
.frozen, .arc => if (mutable) return l.fail("E7005", place.span, "frozen graphs and arcs are immutable: borrow them with `ref`", &.{.{ .name = "name", .value = n }}) else try l.wrap(.ref, b.ty),
else => null,
};
const t = bt orelse return l.fail("E7006", place.span, "this value is not addressable here; borrow a variable, a field or an element", &.{.{ .name = "name", .value = n }});
@@ -2117,7 +2149,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" };
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" };
for (ops) |o| if (std.mem.eql(u8, o, path)) return {};
if (authority.intrinsicIndex(path)) |i| if (authority.intrinsics[i].fallible) return {};
return null;
@@ -2206,6 +2238,41 @@ const Lowerer = struct {
try l.endNow(temps.items, e.span);
return v;
}
if (eq(p, "island.root") or eq(p, "frozen.root") or eq(p, "arc.root")) {
if (args.len != 1) return l.fail("E7005", e.span, "`.root` takes the graph's borrow binding", &.{});
const g = try l.graphBorrow(args[0], p[0..std.mem.indexOfScalar(u8, p, '.').?], false);
return try l.def("root", try l.wrap(.iref, g.ty.inner().?.inner().?), try l.fmt("{s} %{s}", .{ p, g.name }), e.span);
}
if (eq(p, "island.freeze") or eq(p, "arc.from_frozen")) {
if (args.len != 1) return l.fail("E7005", e.span, "this operation takes one graph owner", &.{});
const o = try l.consuming(args[0], null);
const want: std.meta.Tag(Ty) = if (eq(p, "island.freeze")) .island else .frozen;
if (std.meta.activeTag(o.ty) != want) return l.fail("E7005", args[0].span, if (want == .island) "`island.freeze` takes an `island<T>`" else "`arc.from_frozen` takes a `frozen<T>`", &.{.{ .name = "found", .value = l.tyText(o.ty) }});
const out = if (want == .island) try l.wrap(.frozen, o.ty.inner().?) else try l.wrap(.arc, o.ty.inner().?);
return try l.def(if (want == .island) "frozen" else "arc", out, try l.fmt("{s} %{s}", .{ p, o.name }), e.span);
}
if (eq(p, "island.destroy") or eq(p, "frozen.release") or eq(p, "arc.release")) {
if (args.len != 1) return l.fail("E7005", e.span, "this operation takes one graph owner", &.{});
const o = try l.consuming(args[0], null);
const want: std.meta.Tag(Ty) = if (eq(p, "island.destroy")) .island else if (eq(p, "frozen.release")) .frozen else .arc;
if (std.meta.activeTag(o.ty) != want) return l.fail("E7005", args[0].span, "this operation takes another graph owner", &.{ .{ .name = "operation", .value = p }, .{ .name = "found", .value = l.tyText(o.ty) } });
try l.emit(try l.fmt("{s} %{s}", .{ p, o.name }), e.span);
return .{ .name = "", .ty = .void };
}
if (eq(p, "arc.clone")) {
if (args.len != 1 or args[0].kind != .name) return l.fail("E7005", e.span, "`arc.clone` takes an arc by name", &.{});
const b = l.lookup(args[0].kind.name) orelse return l.unknown(args[0].span, args[0].kind.name);
if (b.ty == .arc) {
const r = try l.def(args[0].kind.name, try l.wrap(.ref, b.ty), try l.fmt("borrow.ref %{s}", .{b.value}), args[0].span);
const v = try l.def("arc", b.ty, try l.fmt("arc.clone %{s}", .{r.name}), e.span);
try l.emit(try l.fmt("borrow.end %{s}", .{r.name}), e.span);
return v;
}
if (b.ty == .ref and b.ty.inner().? == .arc) return try l.def("arc", b.ty.inner().?, try l.fmt("arc.clone %{s}", .{b.value}), e.span);
return l.fail("E7005", args[0].span, "`arc.clone` takes an `arc<T>`", &.{.{ .name = "found", .value = l.tyText(b.ty) }});
}
if (eq(p, "island.at") or eq(p, "frozen.at") or eq(p, "arc.at"))
return l.fail("E7006", e.span, "a graph access is a borrow: bind it with `ref x = island.at(g, r);` or `mut x = island.at(g, r);`", &.{});
if (eq(p, "mutex.make")) {
if (args.len != 1) return l.fail("E7005", e.span, "`mutex.make` takes the initial value", &.{});
const v = try l.consuming(args[0], null);
@@ -2248,7 +2315,7 @@ const Lowerer = struct {
};
const elem = mr.ty.ref.mutex.*;
const depth = l.bindings.items.len;
const vars = try l.carriedLive(depth, s.span);
const vars = try l.carriedLive(depth, s.span, .{ .lock = .{ body, cancelled } });
const before = try l.snapshot();
const locked = try l.newBlock("locked");
const guard = try l.freshName("guard");
@@ -2358,7 +2425,7 @@ const Lowerer = struct {
}
const depth = l.bindings.items.len;
const vars = try l.carriedLive(depth, s.span);
const vars = try l.carriedLive(depth, s.span, .{ .select = sel });
const before = try l.snapshot();
var text: std.ArrayList(u8) = .empty;
try text.appendSlice(l.arena, "select ");
@@ -2436,6 +2503,37 @@ const Lowerer = struct {
};
}
/// The named borrow binding of a graph owner that `.root`, `.at` and
/// `island.alloc` take (spec 15 §8: container borrows are explicit).
fn graphBorrow(l: *Lowerer, a: ast.Expr, owner: []const u8, mutable: bool) Error!Value {
if (a.kind == .borrow) return l.fail("E7006", a.span, "the graph's borrow is bound first (`mut g = isl;`), so it outlives the borrows taken from it", &.{});
if (a.kind != .name) return l.fail("E7005", a.span, "the graph's borrow binding is expected here, by name", &.{});
const b = l.lookup(a.kind.name) orelse return l.unknown(a.span, a.kind.name);
const tag = std.meta.stringToEnum(std.meta.Tag(Ty), owner).?;
if (std.meta.activeTag(b.ty) == tag) return l.fail("E7005", a.span, try l.fmt("this takes a borrow of the {s}, not the owner: bind `{s} g = {s};` in an enclosing block and pass `g`", .{ owner, if (mutable) "mut" else "ref", a.kind.name }), &.{.{ .name = "name", .value = a.kind.name }});
const ok = (b.ty == .ref or (b.ty == .mut and !mutable) or (b.ty == .mut and mutable)) and std.meta.activeTag(b.ty.inner().?) == tag;
if (!ok or (mutable and b.ty != .mut)) return l.fail("E7005", a.span, try l.fmt("a {s} borrow of an `{s}<T>` is expected here", .{ if (mutable) "`mut`" else "`ref` or `mut`", owner }), &.{.{ .name = "found", .value = l.tyText(b.ty) }});
return .{ .name = b.value, .ty = b.ty };
}
/// `ref x = island.at(g, r);` / `mut x = island.at(g, r);`, and
/// `frozen.at`, `arc.at` (`ref` only): a child borrow of `g`.
fn graphAccess(l: *Lowerer, s: ast.Stmt, name: []const u8, mutable: bool, place: ast.Expr) Error!void {
const ac = place.kind.call;
const p = pathOf(ac.callee.*).?;
const owner = p[0..std.mem.indexOfScalar(u8, p, '.').?];
if (mutable and !std.mem.eql(u8, owner, "island")) return l.fail("E7005", s.span, "frozen graphs and arcs give `ref` access only", &.{});
if (ac.args.len != 2) return l.fail("E7005", place.span, "`.at` takes the graph's borrow binding and an `iref`", &.{});
const g = try l.graphBorrow(ac.args[0], owner, mutable);
const r = try l.expr(ac.args[1], null);
if (r.ty != .iref) return l.fail("E7005", ac.args[1].span, "an `iref` is expected here", &.{.{ .name = "found", .value = l.tyText(r.ty) }});
const op = if (std.mem.eql(u8, owner, "island")) "island.borrow" else if (std.mem.eql(u8, owner, "frozen")) "frozen.borrow" else "arc.borrow";
const target = r.ty.inner().?;
const v = try l.def(name, if (mutable) try l.wrap(.mut, target) else try l.wrap(.ref, target), try l.fmt("{s} %{s}, %{s}", .{ op, g.name, r.name }), s.span);
try l.scopeEnds(&.{v.name}, s.span);
try l.bindings.append(l.arena, .{ .name = name, .mutable = false, .value = v.name, .ty = v.ty, .kind = .borrow });
}
fn resultTy(r: authority.ResultType) Ty {
return switch (r) {
.usize => .{ .int = "usize" },
@@ -2575,6 +2673,19 @@ const Lowerer = struct {
.temps = temps.items,
};
}
if (std.mem.eql(u8, path, "island.create") or std.mem.eql(u8, path, "arc.new")) {
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");
const owner = if (std.mem.eql(u8, path, "arc.new")) try l.wrap(.arc, v.ty) else try l.wrap(.island, v.ty);
return .{ .text = try l.fmt("{s} %{s}, %{s}", .{ path, v.name, c.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{owner} }, .{ .role = "err", .params = &.{alloc_err} } }) };
}
if (std.mem.eql(u8, path, "island.alloc")) {
try want(l, e.span, args, 2, path);
const g = try l.graphBorrow(args[0], "island", true);
const v = try l.consuming(args[1], null);
return .{ .text = try l.fmt("island.alloc %{s}, %{s}", .{ g.name, v.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{try l.wrap(.iref, v.ty)} }, .{ .role = "err", .params = &.{alloc_err} } }) };
}
if (std.mem.eql(u8, path, "task.check_cancel")) {
try want(l, e.span, args, 0, path);
return .{ .text = "task.check_cancel", .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{} }, .{ .role = "cancelled", .params = &.{} } }) };
@@ -2690,7 +2801,7 @@ const Lowerer = struct {
if (missing.items.len != 0) return l.fail("E7004", m.span, "the match does not handle every outcome of the operation", &.{.{ .name = "missing", .value = missing.items }});
const depth = l.bindings.items.len;
const vars = try l.carriedLive(depth, m.span);
const vars = try l.carriedLive(depth, m.span, .{ .match = m });
const before = try l.snapshot();
const blocks = try l.outcomeBlocks(f, m.scrutinee.span);
var ends: std.ArrayList(ArmEnd) = .empty;
@@ -2763,7 +2874,7 @@ const Lowerer = struct {
};
try l.checkTy(x.cond.span, cv.ty, .bool);
const depth = l.bindings.items.len;
const vars = try l.carriedLive(depth, span);
const vars = try l.carriedLive(depth, span, .{ .@"if" = x });
const then_b = try l.newBlock("then");
const else_b = try l.newBlock("else");
try l.term(try l.fmt("cbr %{s}, @{s}(), @{s}()", .{ cv.name, l.blocks.items[then_b].name, l.blocks.items[else_b].name }), x.cond.span);
@@ -2813,7 +2924,10 @@ fn pathOf(e: ast.Expr) ?[]const u8 {
"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",
"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",
};
var buf: [64]u8 = undefined;
const text = dotted(e, &buf) orelse return null;
@@ -3077,3 +3191,99 @@ const After = struct {
};
}
};
/// The code of a branching construct, for deciding which variables it
/// assigns: a join carries only variables that may change inside.
const Region = union(enum) {
loop: LoopAst,
@"if": ast.If,
match: ast.Match,
lock: struct { ast.Block, ast.Block },
select: ast.Select,
fn assigns(r: Region, name: []const u8) bool {
return switch (r) {
.loop => |lp| (if (lp.step) |st| std.mem.eql(u8, st, name) else false) or (if (lp.cond) |c| exprAssigns(c, name) else false) or blockAssigns(lp.body, name),
.@"if" => |x| ifAssigns(x, name),
.match => |m| matchAssigns(m, name),
.lock => |b| blockAssigns(b[0], name) or blockAssigns(b[1], name),
.select => |x| selectAssigns(x, name),
};
}
};
/// Whether code assigns variable `name`: `name = e;`, or a pattern of an
/// outcome or `select` edge rebinding it (spec 15 §6).
fn blockAssigns(b: ast.Block, name: []const u8) bool {
for (b.stmts) |st| if (stmtAssigns(st, name)) return true;
if (b.tail) |t| if (exprAssigns(t.*, name)) return true;
return false;
}
fn stmtAssigns(st: ast.Stmt, name: []const u8) bool {
return switch (st.kind) {
.assign => |x| (x.place.kind == .name and std.mem.eql(u8, x.place.kind.name, name)) or exprAssigns(x.e, name),
.let => |x| exprAssigns(x.e, name),
.@"var" => |x| if (x.init) |e| exprAssigns(e, name) else false,
.borrow => |x| exprAssigns(x.place, name),
.@"return" => |e| if (e) |x| exprAssigns(x, name) else false,
.expr => |e| exprAssigns(e, name),
.@"while" => |x| exprAssigns(x.cond, name) or blockAssigns(x.body, name),
.@"for" => |x| std.mem.eql(u8, x.name, name) or blockAssigns(x.body, name),
.loop, .shield => |b| blockAssigns(b, name),
.scope => |x| blockAssigns(x.body, name),
.lock => |x| blockAssigns(x.body, name) or blockAssigns(x.cancelled, name),
.select => |x| selectAssigns(x, name),
.@"break", .@"continue", .trap => false,
};
}
fn exprAssigns(e: ast.Expr, name: []const u8) bool {
return switch (e.kind) {
.if_expr => |x| ifAssigns(x.*, name),
.match_expr => |x| matchAssigns(x.*, name),
.block => |b| blockAssigns(b.*, name),
.neg, .not, .deref, .or_trap => |x| exprAssigns(x.*, name),
.binary => |x| exprAssigns(x.l.*, name) or exprAssigns(x.r.*, name),
.cast => |x| exprAssigns(x.e.*, name),
.call => |x| blk: {
for (x.args) |a| if (exprAssigns(a, name)) break :blk true;
break :blk false;
},
.struct_lit => |x| blk: {
for (x.fields) |f| if (exprAssigns(f.e, name)) break :blk true;
break :blk false;
},
.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),
else => false,
};
}
fn ifAssigns(x: ast.If, name: []const u8) bool {
if (exprAssigns(x.cond, name) or blockAssigns(x.then, name)) return true;
if (x.@"else") |els| return switch (els) {
.block => |b| blockAssigns(b, name),
.@"if" => |inner| ifAssigns(inner.*, name),
};
return false;
}
fn matchAssigns(m: ast.Match, name: []const u8) bool {
if (exprAssigns(m.scrutinee, name)) return true;
for (m.arms) |a| {
if (a.pattern.kind == .ctor) for (a.pattern.kind.ctor.binds) |b| if (std.mem.eql(u8, b, name)) return true;
if (exprAssigns(a.body, name)) return true;
}
return false;
}
fn selectAssigns(x: ast.Select, name: []const u8) bool {
for (x.arms) |a| for (a.arms) |arm| {
if (arm.pattern.kind == .ctor) for (arm.pattern.kind.ctor.binds) |b| if (std.mem.eql(u8, b, name)) return true;
if (exprAssigns(arm.body, name)) return true;
};
for (x.cancelled_binds) |b| if (std.mem.eql(u8, b, name)) return true;
return exprAssigns(x.cancelled, name);
}
+261 -2
View File
@@ -67,11 +67,28 @@ pub const Value = union(enum) {
/// `mutex<T>` and the `guard<T>` that holds it.
mutex: *MutexCell,
guard: *MutexCell,
/// `island<T>`, `frozen<T>`, `arc<T>`: the graph (spec 03 §22–§24). The
/// ownership mode is the static type; the graph is the same object.
graph: *Graph,
/// `iref<T>`: graph identity and slot; opaque to programs.
iref: struct { id: u64, slot: u32 },
/// The guarded value is a separate cell, so a place borrowed through a
/// guard points at an ordinary cell.
pub const MutexCell = struct { locked: bool, cell: *Cell };
/// A graph: object cells addressed by slot, an identity never reused in
/// the execution, the authority it charges and the bytes it holds.
pub const Graph = struct {
id: u64,
objects: std.ArrayList(*Cell) = .empty,
authority: u32,
bytes: u64,
/// `arc` handles alive (0 while unique: island or frozen).
count: u64 = 0,
frozen: bool = false,
};
pub const Aggregate = struct {
decl: u32,
/// Active variant for enums; 0 for structs.
@@ -148,9 +165,16 @@ pub const MemoryStats = struct {
peak_live: usize = 0,
/// Largest execution heap before a collection, in heap bytes.
peak_heap: usize = 0,
/// Instructions executed.
steps: u64 = 0,
};
/// One `arc` count change (spec 03 §24: every change appears in the trace).
pub const ArcEvent = struct { op: enum { new, from_frozen, clone, release }, graph: u64, count: u64 };
pub const Options = struct {
/// Trace mode for `arc` counts: every change is appended (spec 11 §2).
arc_events: ?*std.ArrayList(ArcEvent) = null,
/// Filled with execution-heap statistics when set.
memory: ?*MemoryStats = null,
/// Collect before every instruction (tests: a missed root then fails).
@@ -237,6 +261,7 @@ pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, opti
}
m.exec_heap.every_step = options.collect_every_step;
m.arc_events = options.arc_events;
if (options.collect_threshold) |t| {
m.exec_heap.floor = t;
m.exec_heap.threshold = t;
@@ -251,6 +276,7 @@ pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, opti
result = .{ .returned = try c.value(outcome.returned) };
}
m.exec_heap.stats.peak_heap = @max(m.exec_heap.stats.peak_heap, m.exec_heap.space.queryCapacity());
m.exec_heap.stats.steps = m.steps;
if (options.memory) |st| st.* = m.exec_heap.stats;
m.exec_heap.space.deinit();
return result;
@@ -264,6 +290,7 @@ const Copier = struct {
cells: std.AutoHashMapUnmanaged(*Value.Cell, *Value.Cell) = .empty,
mutexes: std.AutoHashMapUnmanaged(*Value.MutexCell, *Value.MutexCell) = .empty,
payloads: std.AutoHashMapUnmanaged([*]Value, []Value) = .empty,
graphs: std.AutoHashMapUnmanaged(*Value.Graph, *Value.Graph) = .empty,
fn value(c: *Copier, v: Value) std.mem.Allocator.Error!Value {
return switch (v) {
@@ -275,7 +302,8 @@ const Copier = struct {
.slice => |sl| .{ .slice = .{ .place = try c.place(sl.place), .start = sl.start, .len = sl.len } },
.mutex => |mc| .{ .mutex = try c.mutex(mc) },
.guard => |mc| .{ .guard = try c.mutex(mc) },
.int, .boolean, .void, .cap, .resource, .region, .scope, .task, .builtin, .shield, .sender, .receiver => v,
.graph => |g| .{ .graph = try c.graph(g) },
.int, .boolean, .void, .cap, .resource, .region, .scope, .task, .builtin, .shield, .sender, .receiver, .iref => v,
};
}
@@ -308,6 +336,17 @@ const Copier = struct {
return n;
}
fn graph(c: *Copier, old: *Value.Graph) std.mem.Allocator.Error!*Value.Graph {
if (c.graphs.get(old)) |n| return n;
const n = try c.to.create(Value.Graph);
try c.graphs.put(c.tmp, old, n);
n.* = old.*;
n.objects = .empty;
try n.objects.ensureTotalCapacity(c.to, old.objects.items.len);
for (old.objects.items) |cl| n.objects.appendAssumeCapacity(try c.cell(cl));
return n;
}
fn place(c: *Copier, p: Value.Place) std.mem.Allocator.Error!Value.Place {
return .{ .cell = try c.cell(p.cell), .path = if (p.path.len == 0) &.{} else try c.to.dupe(u32, p.path) };
}
@@ -323,6 +362,7 @@ const TrapKind = enum {
call_depth,
out_of_bounds,
unsafe_precondition,
foreign_iref,
fn code(k: TrapKind) *const diag.Code {
return switch (k) {
@@ -335,6 +375,7 @@ const TrapKind = enum {
.call_depth => diag.lookup("T0007").?,
.out_of_bounds => diag.lookup("T0008").?,
.unsafe_precondition => diag.lookup("T0009").?,
.foreign_iref => diag.lookup("T0010").?,
};
}
};
@@ -422,6 +463,9 @@ pub const Heap = struct {
const Machine = struct {
arena: std.mem.Allocator,
exec_heap: Heap = .{},
/// Next graph identity; identities are never reused (spec 03 §22).
next_graph: u64 = 1,
arc_events: ?*std.ArrayList(ArcEvent) = null,
module: air.Module,
fuel: ?u64,
tasks: std.ArrayList(Task) = .empty,
@@ -750,6 +794,7 @@ const Machine = struct {
.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),
.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),
.intrinsic => |x| return m.intrinsic(f, vals, inst, x),
.ret => |v| return .{ .ret = if (v) |x| vals[x] else .void },
.trap => return .{ .trap = .explicit },
@@ -1259,10 +1304,124 @@ const Machine = struct {
.array => |items| std.math.mul(u64, items.len, m.valueBytes(items[0]) orelse return null) catch null,
.builtin => |b| budget.accountedSize(m.module, .{ .builtin = b.which }, 0),
.cap => 8,
.iref => 16,
else => unreachable, // only value types are allocated (spec 03 §19.2)
};
}
// ------------------------------------------------------------ graphs (spec 03 §22–§24)
/// A graph's header, charged once at creation; it includes room for an
/// `arc` count, so converting to an `arc` charges nothing (spec 03 §24).
const graph_header = 16;
/// The graph behind an owner or a borrow of one.
fn graphOf(v: Value) *Value.Graph {
return switch (v) {
.graph => |g| g,
.place => |p| placePtr(p).graph,
else => unreachable,
};
}
fn arcEvent(m: *Machine, op: @FieldType(ArcEvent, "op"), g: *Value.Graph) !void {
if (m.arc_events) |list| try list.append(m.arena, .{ .op = op, .graph = g.id, .count = g.count });
}
fn newGraph(m: *Machine, a: u32, bytes: u64, root: Value) !*Value.Graph {
const g = try m.heap().create(Value.Graph);
g.* = .{ .id = m.next_graph, .authority = a, .bytes = bytes };
m.next_graph += 1;
const cell = try m.heap().create(Value.Cell);
cell.* = .{ .value = try m.deepCopy(root), .ty = .void };
try g.objects.append(m.heap(), cell);
return g;
}
/// Frees a graph's objects and returns its bytes to its authority.
fn releaseGraph(m: *Machine, g: *Value.Graph) void {
m.uncharge(g.authority, g.bytes);
g.bytes = 0;
g.objects = .empty;
}
/// The object an `iref` names in graph `g`, or `T0010`.
fn objectOf(g: *Value.Graph, r: Value) ?*Value.Cell {
if (r.iref.id != g.id or r.iref.slot >= g.objects.items.len) return null;
return g.objects.items[r.iref.slot];
}
fn execGraph(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst) !Step {
switch (inst.op) {
inline .island_create, .arc_new => |x| {
const v = vals[x.value];
const a = vals[x.cap].cap;
const bytes = if (m.valueBytes(v)) |b| (std.math.add(u64, b, graph_header) catch null) else null;
if (!m.charge(a, bytes)) return allocFailed(f, vals, x.err);
const g = try m.newGraph(a, bytes.?, v);
if (inst.op == .arc_new) {
g.frozen = true;
g.count = 1;
try m.arcEvent(.new, g);
}
vals[f.blocks[x.ok].params[0].value] = .{ .graph = g };
return .{ .jump = x.ok };
},
.island_alloc => |x| {
const g = graphOf(vals[x.island]);
const v = vals[x.value];
const bytes = m.valueBytes(v);
if (!m.charge(g.authority, bytes)) return allocFailed(f, vals, x.err);
g.bytes += bytes.?;
const cell = try m.heap().create(Value.Cell);
cell.* = .{ .value = try m.deepCopy(v), .ty = .void };
try g.objects.append(m.heap(), cell);
vals[f.blocks[x.ok].params[0].value] = .{ .iref = .{ .id = g.id, .slot = @intCast(g.objects.items.len - 1) } };
return .{ .jump = x.ok };
},
.island_root, .frozen_root, .arc_root => |v| return bind(vals, inst.result, .{ .iref = .{ .id = graphOf(vals[v]).id, .slot = 0 } }),
inline .island_borrow, .frozen_borrow, .arc_borrow => |x| {
const g = graphOf(vals[x.owner]);
const cell = objectOf(g, vals[x.iref]) orelse return .{ .trap = .foreign_iref };
return bind(vals, inst.result, .{ .place = .{ .cell = cell, .path = &.{} } });
},
.island_freeze => |v| {
const g = vals[v].graph;
g.frozen = true;
return bind(vals, inst.result, .{ .graph = g });
},
.island_destroy, .frozen_release => |v| {
m.releaseGraph(vals[v].graph);
return .next;
},
.arc_from_frozen => |v| {
const g = vals[v].graph;
g.count = 1;
try m.arcEvent(.from_frozen, g);
return bind(vals, inst.result, .{ .graph = g });
},
.arc_clone => |v| {
const g = graphOf(vals[v]);
g.count += 1;
try m.arcEvent(.clone, g);
return bind(vals, inst.result, .{ .graph = g });
},
.arc_release => |v| {
const g = vals[v].graph;
g.count -= 1;
try m.arcEvent(.release, g);
if (g.count == 0) m.releaseGraph(g);
return .next;
},
.iref_eq => |x| {
const a = vals[x.a].iref;
const b = vals[x.b].iref;
return bind(vals, inst.result, .{ .boolean = a.id == b.id and a.slot == b.slot });
},
else => unreachable,
}
}
fn allocFailed(f: air.Function, vals: []Value, err: u32) Step {
vals[f.blocks[err].params[0].value] = .{ .builtin = .{ .which = .alloc_error, .variant = 0 } };
return .{ .jump = err };
@@ -1698,7 +1857,7 @@ pub fn writeValue(module: air.Module, v: Value, s: *std.json.Stringify) std.Io.W
},
// Storage and borrows cannot be returned from `@main` (spec 08 §11.3).
.local, .place, .slice => try s.write(null),
.resource, .own, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard => try s.write(null),
.resource, .own, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .graph, .iref => try s.write(null),
// A capability is opaque: only its kind is shown, never its identity.
.cap => {
try s.beginObject();
@@ -2159,3 +2318,103 @@ test "execution memory is bounded by live state, not by the iteration count" {
try std.testing.expect(large.peak_heap <= 3 * floor + 64 * 1024);
}
}
test "arc count changes appear in the trace, and the last release frees the graph" {
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
const src =
\\module t
\\fn main(heap: cap<mem.alloc>) -> u64
\\effects [mem.alloc]
\\{
\\ let isl = island.create(7u64, heap) or trap;
\\ let a = arc.from_frozen(island.freeze(move isl));
\\ let b = arc.clone(a);
\\ arc.release(move a);
\\ var v: u64 = 0;
\\ {
\\ ref br = b;
\\ let r = arc.root(br);
\\ ref x = arc.at(br, r);
\\ v = *x;
\\ }
\\ arc.release(move b);
\\ // The budget (16 + 8 bytes) is free again: the same graph fits once more.
\\ let again = arc.new(5u64, heap) or trap;
\\ arc.release(move again);
\\ v
\\}
;
const report = try check.checkFile(arena, "t.aji", src);
if (report.status != .accepted) {
for (report.diagnostics) |d| std.debug.print("{s} {s}\n", .{ d.code.id, d.message });
return error.NotAccepted;
}
var events: std.ArrayList(ArcEvent) = .empty;
const outcome = try run(arena, report.module.?, "main", .{
.grants = &.{.{ .parameter = "heap", .kind = "mem.alloc", .scope = "24" }},
.arc_events = &events,
});
try std.testing.expect(outcome == .returned);
try std.testing.expectEqual(@as(u128, 7), outcome.returned.int.bits);
const Op = @FieldType(ArcEvent, "op");
const want = [_]struct { Op, u64 }{ .{ .from_frozen, 1 }, .{ .clone, 2 }, .{ .release, 1 }, .{ .release, 0 }, .{ .new, 1 }, .{ .release, 0 } };
try std.testing.expectEqual(want.len, events.items.len);
for (want, events.items) |w, e| {
try std.testing.expectEqual(w[0], e.op);
try std.testing.expectEqual(w[1], e.count);
}
// One graph identity through island → frozen → arc; the second graph is new.
try std.testing.expectEqual(events.items[0].graph, events.items[3].graph);
try std.testing.expect(events.items[4].graph != events.items[0].graph);
}
// Transfer is O(1) in the graph size (spec 03 §22): moving an island through
// a channel K times costs the same number of instructions for a graph of 10
// nodes as for one of 1000.
fn transferSteps(nodes: u64, sends: u64) !u64 {
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
const src = try std.fmt.allocPrint(arena,
\\module t
\\fn main(heap: cap<mem.alloc>) -> u64
\\effects [mem.alloc, task.wait]
\\{{
\\ var isl: island<u64> = island.create(0u64, heap) or trap;
\\ {{
\\ mut g = isl;
\\ for i in 0..{d}u64 {{ let r = island.alloc(g, i) or trap; }}
\\ }}
\\ match channel.make<island<u64>>(1, heap) {{
\\ ok(tx, rx) => {{
\\ for k in 0..{d}u64 {{
\\ channel.send(tx, move isl) or trap;
\\ isl = channel.recv(rx) or trap;
\\ }}
\\ channel.close_sender(move tx);
\\ channel.close_receiver(move rx) or trap;
\\ }}
\\ err(e) => {{ trap; }}
\\ }}
\\ island.destroy(move isl);
\\ 0
\\}}
, .{ nodes, sends });
const report = try check.checkFile(arena, "t.aji", src);
if (report.status != .accepted) {
for (report.diagnostics) |d| std.debug.print("{s} {s}\n", .{ d.code.id, d.message });
return error.NotAccepted;
}
var stats: MemoryStats = .{};
const outcome = try run(arena, report.module.?, "main", .{ .grants = &.{.{ .parameter = "heap", .kind = "mem.alloc", .scope = "1000000" }}, .memory = &stats });
try std.testing.expect(outcome == .returned);
return stats.steps;
}
test "moving an island costs the same for any graph size" {
const small = try transferSteps(10, 10) - try transferSteps(10, 0);
const large = try transferSteps(1000, 10) - try transferSteps(1000, 0);
try std.testing.expectEqual(small, large);
}
+1 -1
View File
@@ -61,7 +61,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 => {
.own_new, .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");
},
+15 -1
View File
@@ -264,7 +264,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 => {
.own_new, .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 = &.{} });
@@ -585,6 +585,20 @@ fn step(w: *Walker, inst: air.Inst) !void {
w.live[g] = false;
w.dead[g] = .closed;
},
// Graphs (spec 03 §22–§24). An access is a child borrow of the
// container borrow; a `mut` child is exclusive for the whole island.
.island_alloc => |x| try w.useThrough(x.island, .exclusive),
.island_root, .frozen_root, .arc_root => |v| _ = try w.usable(v),
inline .island_borrow, .frozen_borrow, .arc_borrow => |x| try w.derive(inst.result.?, x.owner, .elem),
.island_freeze, .arc_from_frozen => |v| {
try w.consume(v, .moved);
w.live[inst.result.?] = true;
},
.island_destroy, .frozen_release, .arc_release => |v| try w.consume(v, .closed),
.arc_clone => |v| {
try lendArgs(w, &.{v});
w.live[inst.result.?] = true;
},
// Values of these instructions are not borrows; any borrow operand
// here was already rejected by the type stage.
else => {},
+2 -1
View File
@@ -28,7 +28,8 @@ pub fn accountedSize(m: air.Module, t: air.Type, depth: usize) ?u64 {
return switch (t) {
.int => |it| it.bits() / 8,
.bool => 1,
.ref, .mut, .cap, .resource, .own, .region, .scope, .task, .shield, .sender, .receiver, .guard => 8,
.ref, .mut, .cap, .resource, .own, .region, .scope, .task, .shield, .sender, .receiver, .guard, .island, .frozen, .arc => 8,
.iref => 16,
.mutex => |inner| std.math.add(u64, 8, accountedSize(m, inner.*, depth + 1) orelse return null) catch null,
.own_array => 16,
.slice, .slice_mut => 16,
+1 -1
View File
@@ -79,7 +79,7 @@ fn checkTerminator(c: *Context, f: air.Function, inst: air.Inst) !void {
try paramCount(c, f, inst.span, x.ok, 1, "cap.narrow `ok` target takes exactly one parameter");
try paramCount(c, f, inst.span, x.err, 1, "cap.narrow `err` target takes exactly one parameter");
},
.own_new, .own_array, .region_create, .region_new, .region_array => {
.own_new, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => {
const t = air.allocTargets(inst.op).?;
try paramCount(c, f, inst.span, t.ok, 1, "allocation `ok` target takes exactly one parameter");
try paramCount(c, f, inst.span, t.err, 1, "allocation `err` target takes exactly one parameter");
+1 -1
View File
@@ -50,7 +50,7 @@ pub fn check(c: *Context) !void {
.task_join => if (m.declares("cancellation")) try need(c, f, inst, "task.wait"),
.task_join_cancel, .channel_send, .channel_recv, .select, .mutex_lock => try need(c, f, inst, "task.wait"),
.channel_make => try need(c, f, inst, "mem.alloc"),
.own_new, .own_array, .region_create, .region_new, .region_array => if (!contains(f.effects, "mem.alloc")) {
.own_new, .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" } },
+107 -3
View File
@@ -85,7 +85,7 @@ 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 => pos != .member,
.resource, .own, .own_array, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc => pos != .member,
else => true,
};
if (!ok) try c.report("E1001", span, "type not allowed in this position", &.{
@@ -93,6 +93,15 @@ fn wellFormed(c: *Context, span: air.Span, t: Type, pos: Position, owner: []cons
.{ .name = "position", .value = .{ .str = @tagName(pos) } },
.{ .name = "found", .value = .{ .str = try c.typeName(t) } },
});
// A graph holds IslandSafe values only (spec 03 §22–§24): reported once,
// as E2111, at the type.
if (t.isGraphOwner()) {
if (!isIslandSafe(c.module, t.inner().?)) try c.report("E2111", span, "a graph holds only plain data and iref handles", &.{
.{ .name = "in", .value = .{ .str = owner } },
.{ .name = "found", .value = .{ .str = try c.typeName(t.inner().?) } },
});
return;
}
// The pointee of ref/mut may be a linear value (`mut<file<read>>`), and
// a task may return one; every other compound holds value types only.
// Channel elements and mutex contents may be linear (spec 04 §38.1);
@@ -226,6 +235,7 @@ fn resultType(m: air.Module, op: air.Op) ?Type {
.task_scope_begin => .scope,
.task_cancelled => .bool,
.task_shield_begin => .shield,
.iref_eq => .bool,
.intrinsic => |x| blk: {
const reg = air.authority.intrinsics[x.index];
if (reg.fallible or reg.results.len == 0) break :blk .void;
@@ -327,6 +337,8 @@ fn checkIntrinsic(fc: *FnCtx, inst: air.Inst, x: @FieldType(air.Op, "intrinsic")
pub fn isSend(m: air.Module, t: Type) bool {
return switch (t) {
.int, .bool, .builtin, .cap, .resource, .region, .sender, .receiver => true,
// Graph contents are IslandSafe plain data (spec 03 §22–§24).
.island, .frozen, .arc, .iref => true,
.own, .own_array, .mutex => |inner| isSend(m, inner.*),
.ref, .slice => |inner| isShare(m, inner.*),
.mut, .slice_mut => |inner| isSend(m, inner.*),
@@ -340,6 +352,9 @@ pub fn isSend(m: air.Module, t: Type) bool {
pub fn isShare(m: air.Module, t: Type) bool {
return switch (t) {
.int, .bool, .builtin, .cap => true,
.frozen, .arc, .iref => true,
// Its owner may mutate it: freeze to share (spec 04 §35).
.island => false,
.resource, .region, .mut, .slice_mut, .scope, .task, .shield, .guard, .sender, .receiver, .local, .void, .never => false,
.own, .own_array, .ref, .slice => |inner| isShare(m, inner.*),
// The lock synchronizes access (spec 04 §35, §40).
@@ -349,6 +364,17 @@ pub fn isShare(m: air.Module, t: Type) bool {
};
}
/// `IslandSafe` (spec 02 §6): plain data and `iref` handles, at any depth.
/// `ArcSafe` is the same set in format 0.
pub fn isIslandSafe(m: air.Module, t: Type) bool {
return switch (t) {
.int, .bool, .builtin, .iref => true,
.array => |a| isIslandSafe(m, a.elem),
.named => |i| aggregateAll(m, i, isIslandSafe),
else => false,
};
}
fn aggregateAll(m: air.Module, i: u32, comptime pred: fn (air.Module, Type) bool) bool {
return switch (m.types[i].kind) {
.@"struct" => |fs| for (fs) |f| {
@@ -425,6 +451,8 @@ fn contains(m: air.Module, t: Type, comptime what: enum { endpoint, forbidden })
.forbidden => t.isBorrow() or t.isTaskBound() or t == .guard,
};
if (here) return true;
// An `iref<T>` holds no `T`: types may recurse through it (spec 03 §22).
if (t == .iref) return false;
if (t.inner()) |inner| if (t != .ref and t != .mut and t != .slice and t != .slice_mut) return contains(m, inner, what);
return switch (t) {
.named => |i| switch (m.types[i].kind) {
@@ -497,6 +525,8 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type {
.channel_dup, .mutex_take, .mutex_borrow => |v| fc.ty[v] orelse return null,
.mutex_make => |v| return .{ .mutex = try boxed(a, fc.ty[v] orelse return null) },
.slice_split => |x| fc.ty[x.slice] orelse return null,
.island_root, .frozen_root, .arc_root, .island_freeze, .arc_from_frozen, .arc_clone => |v| fc.ty[v] orelse return null,
inline .island_borrow, .frozen_borrow, .arc_borrow => |x| fc.ty[x.owner] orelse return null,
else => return null,
};
const invalid: Type = .void;
@@ -504,7 +534,7 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type {
.local_load => if (t == .local) t.local.* else invalid,
.borrow_ref => switch (t) {
.local, .ref, .mut => .{ .ref = try boxed(a, t.inner().?) },
.resource, .region, .task, .scope, .sender, .receiver, .mutex => .{ .ref = try boxed(a, t) },
.resource, .region, .task, .scope, .sender, .receiver, .mutex, .island, .frozen, .arc => .{ .ref = try boxed(a, t) },
.own => |inner| .{ .ref = inner },
.own_array => |inner| .{ .slice = inner },
.slice, .slice_mut => .{ .slice = try boxed(a, t.inner().?) },
@@ -512,7 +542,7 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type {
},
.borrow_mut => switch (t) {
.local, .mut => .{ .mut = try boxed(a, t.inner().?) },
.resource, .region, .task, .scope, .sender, .receiver => .{ .mut = try boxed(a, t) },
.resource, .region, .task, .scope, .sender, .receiver, .island => .{ .mut = try boxed(a, t) },
.own => |inner| .{ .mut = inner },
.own_array => |inner| .{ .slice_mut = inner },
.slice_mut => .{ .slice_mut = try boxed(a, t.inner().?) },
@@ -548,10 +578,44 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type {
.channel_dup => if (t == .ref and t.ref.* == .sender) t.ref.* else invalid,
.mutex_take => if (t == .mutex) t.mutex.* else invalid,
.mutex_borrow => if (t == .guard) Type{ .mut = t.guard } else invalid,
// Graph roots and handles (spec 03 §22–§24).
.island_root => graphRoot(t, .island),
.frozen_root => graphRoot(t, .frozen),
.arc_root => graphRoot(t, .arc),
.island_freeze => if (t == .island) Type{ .frozen = t.island } else invalid,
.arc_from_frozen => if (t == .frozen) Type{ .arc = t.frozen } else invalid,
.arc_clone => if (t == .ref and t.ref.* == .arc) t.ref.* else invalid,
inline .island_borrow, .frozen_borrow, .arc_borrow => |x| blk: {
const owner: std.meta.Tag(Type) = switch (op) {
.island_borrow => .island,
.frozen_borrow => .frozen,
else => .arc,
};
const r = fc.ty[x.iref] orelse return null;
if (r != .iref) break :blk invalid;
const target = try boxed(a, r.iref.*);
if (t == .ref and std.meta.activeTag(t.ref.*) == owner) break :blk Type{ .ref = target };
if (owner == .island and t == .mut and t.mut.* == .island) break :blk Type{ .mut = target };
break :blk invalid;
},
else => unreachable,
};
}
/// `iref<T>` of the root of a graph reached through `ref`/`mut` of its owner.
fn graphRoot(t: Type, owner: std.meta.Tag(Type)) Type {
const inner = switch (t) {
.ref, .mut => |x| x.*,
else => return .void,
};
if (std.meta.activeTag(inner) != owner) return .void;
if (t == .mut and owner != .island) return .void;
return .{ .iref = switch (inner) {
.island, .frozen, .arc => |x| x,
else => unreachable,
} };
}
fn checkFunction(c: *Context, f: air.Function) ![]const Type {
const m = c.module;
var fc: FnCtx = .{ .c = c, .f = f, .ty = try c.arena.alloc(?Type, f.values.len) };
@@ -817,6 +881,37 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
try fc.expectParams(span, x.ok, &.{.{ .guard = t.ref.mutex }});
},
.mutex_borrow, .mutex_unlock => |v| if (fc.typeOf(v) != .guard) try fc.kindError(span, v, "guard<T>"),
inline .island_create, .arc_new => |x| {
try fc.expectAllocCap(span, x.cap);
const t = fc.typeOf(x.value);
// A non-IslandSafe content is reported at the owner type (E2111).
if (!isIslandSafe(m, t)) return;
const b = try boxed(fc.c.arena, t);
try fc.expectOkErr(span, x.ok, x.err, if (inst.op == .arc_new) Type{ .arc = b } else Type{ .island = b });
},
.island_alloc => |x| {
const g = fc.typeOf(x.island);
if (g != .mut or g.mut.* != .island) return fc.kindError(span, x.island, "mut<island<T>>");
const t = fc.typeOf(x.value);
if (!isIslandSafe(m, t)) return graphContent(fc, span, t, "IslandSafe");
try fc.expectOkErr(span, x.ok, x.err, .{ .iref = try boxed(fc.c.arena, t) });
},
.island_root => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "ref<island<T>> or mut<island<T>>"),
.frozen_root => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "ref<frozen<T>>"),
.arc_root => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "ref<arc<T>>"),
.island_borrow => |x| if (resultOf(fc, inst) == .void) try fc.kindError(span, x.owner, "ref<island<T>> or mut<island<T>>, and an iref<U>"),
.frozen_borrow => |x| if (resultOf(fc, inst) == .void) try fc.kindError(span, x.owner, "ref<frozen<T>> and an iref<U>"),
.arc_borrow => |x| if (resultOf(fc, inst) == .void) try fc.kindError(span, x.owner, "ref<arc<T>> and an iref<U>"),
.island_freeze => |v| if (fc.typeOf(v) != .island) try fc.kindError(span, v, "island<T>"),
.island_destroy => |v| if (fc.typeOf(v) != .island) try fc.kindError(span, v, "island<T>"),
.frozen_release, .arc_from_frozen => |v| if (fc.typeOf(v) != .frozen) try fc.kindError(span, v, "frozen<T>"),
.arc_clone => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "ref<arc<T>>"),
.arc_release => |v| if (fc.typeOf(v) != .arc) try fc.kindError(span, v, "arc<T>"),
.iref_eq => |x| {
const a = fc.typeOf(x.a);
if (a != .iref) return fc.kindError(span, x.a, "iref<T>");
try fc.expectValue(span, x.b, a);
},
.cap_narrow => |x| {
const t = fc.typeOf(x.cap);
if (t != .cap) return fc.kindError(span, x.cap, "cap<K>");
@@ -852,6 +947,15 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
}
}
/// A graph's content that is not `IslandSafe`/`ArcSafe` (spec 03 §22, §24).
fn graphContent(fc: *FnCtx, span: air.Span, t: Type, property: []const u8) !void {
try fc.c.report("E2111", span, "a graph holds only plain data and iref handles", &.{
.{ .name = "function", .value = .{ .str = fc.f.name } },
.{ .name = "property", .value = .{ .str = property } },
.{ .name = "found", .value = .{ .str = try fc.c.typeName(t) } },
});
}
fn resultOf(fc: *FnCtx, inst: air.Inst) Type {
return fc.typeOf(inst.result.?);
}