Phase 2: heap, regions and allocation budgets (RFC 0008)
- air: own<T>, own_array<T>, region, alloc_error; own.new/array/take/ free, region.create/new/array/reset/destroy; mem.alloc budget form; linear contents of owners gated by linear_aggregates - verifier: allocation types and capability kind (E1001, E3201), mem.alloc effect (E3101), ok/err counts; borrow-typed block params checked in the CFG stage with the region-allocation exception; linear owners and regions (E3002, E3001, E2001, E2002, E2101); region allocations as disjoint exclusive children of the shared region borrow; E2104 when reset/destroy would invalidate a live reference - interp: live-byte budgets charged along the narrowing chain, shared by copies, mandatory in the deterministic profile; heap cells; regions return quota only on reset/destroy - conformance: 25 heap/region tests including a 64 KiB region file copy; 4000 mutants without a crash
This commit is contained in:
1 parent
b8d4ab4d4c
commit
7f4ce71d44
38 files changed
+1341
-48
No files matched your search
@@ -27,6 +27,7 @@ pub const CmpOp = module.CmpOp;
|
||||
pub const CastMode = module.CastMode;
|
||||
pub const forEachUse = module.forEachUse;
|
||||
pub const successors = module.successors;
|
||||
pub const allocTargets = module.allocTargets;
|
||||
|
||||
pub const parse = @import("air/parse.zig");
|
||||
pub const print = @import("air/print.zig");
|
||||
|
||||
@@ -49,7 +49,7 @@ pub const kinds = [_]Kind{
|
||||
.{ .name = "fs.write", .scope = .path_prefix, .forms = &.{"prefix"} },
|
||||
.{ .name = "io.read", .scope = .none, .forms = &.{} },
|
||||
.{ .name = "io.write", .scope = .none, .forms = &.{} },
|
||||
.{ .name = "mem.alloc", .scope = .byte_budget, .forms = &.{} },
|
||||
.{ .name = "mem.alloc", .scope = .byte_budget, .forms = &.{"budget"} },
|
||||
.{ .name = "mem.map", .scope = .none, .forms = &.{} },
|
||||
.{ .name = "net.connect", .scope = .none, .forms = &.{} },
|
||||
.{ .name = "net.listen", .scope = .none, .forms = &.{} },
|
||||
@@ -62,11 +62,13 @@ pub const kinds = [_]Kind{
|
||||
|
||||
/// Built-in enums: spelled without `@`, fixed variants, no payloads.
|
||||
pub const Builtin = enum {
|
||||
alloc_error,
|
||||
cap_error,
|
||||
io_error,
|
||||
|
||||
pub fn variants(b: Builtin) []const []const u8 {
|
||||
return switch (b) {
|
||||
.alloc_error => &.{ "budget_exceeded", "out_of_memory" },
|
||||
.cap_error => &.{ "invalid_restriction", "not_subset", "unsupported_restriction" },
|
||||
.io_error => &.{ "not_found", "permission_denied", "already_exists", "invalid_input", "no_space", "broken_pipe", "connection_refused", "connection_reset", "address_in_use", "address_unavailable", "timed_out", "other" },
|
||||
};
|
||||
@@ -75,6 +77,7 @@ pub const Builtin = enum {
|
||||
/// Feature a built-in enum belongs to.
|
||||
pub fn feature(b: Builtin) []const u8 {
|
||||
return switch (b) {
|
||||
.alloc_error => "heap",
|
||||
.cap_error => "capabilities",
|
||||
.io_error => "resources",
|
||||
};
|
||||
|
||||
@@ -28,11 +28,11 @@ pub const registry = [_]Feature{
|
||||
.{ .name = "capabilities", .depends = &.{ "effects", "ownership" }, .status = .published, .phase = 2 },
|
||||
.{ .name = "channels", .depends = &.{"ownership"}, .status = .reserved, .phase = 3 },
|
||||
.{ .name = "effects", .depends = &.{}, .status = .published, .phase = 2 },
|
||||
.{ .name = "heap", .depends = &.{ "capabilities", "effects", "ownership" }, .status = .reserved, .phase = 2 },
|
||||
.{ .name = "islands", .depends = &.{ "capabilities", "effects", "ownership", "regions" }, .status = .reserved, .phase = 4 },
|
||||
.{ .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 = "linear_aggregates", .depends = &.{ "capabilities", "effects", "ownership", "resources" }, .status = .reserved, .phase = null },
|
||||
.{ .name = "ownership", .depends = &.{}, .status = .published, .phase = 1 },
|
||||
.{ .name = "regions", .depends = &.{ "capabilities", "effects", "ownership" }, .status = .reserved, .phase = 2 },
|
||||
.{ .name = "regions", .depends = &.{ "capabilities", "effects", "heap", "ownership", "resources" }, .status = .published, .phase = 2 },
|
||||
.{ .name = "resource_joins", .depends = &.{ "capabilities", "effects", "ownership", "resources" }, .status = .reserved, .phase = null },
|
||||
.{ .name = "resources", .depends = &.{ "capabilities", "effects", "ownership" }, .status = .published, .phase = 2 },
|
||||
.{ .name = "sync", .depends = &.{"ownership"}, .status = .reserved, .phase = 3 },
|
||||
@@ -40,7 +40,7 @@ pub const registry = [_]Feature{
|
||||
};
|
||||
|
||||
/// Features implemented by this toolchain, sorted.
|
||||
pub const supported = [_][]const u8{ "arrays", "capabilities", "effects", "ownership", "resources" };
|
||||
pub const supported = [_][]const u8{ "arrays", "capabilities", "effects", "heap", "ownership", "regions", "resources" };
|
||||
|
||||
pub const Reason = enum {
|
||||
unknown_feature,
|
||||
|
||||
+60
-3
@@ -79,6 +79,10 @@ pub const Type = union(enum) {
|
||||
builtin: authority.Builtin,
|
||||
// Feature `resources` (spec 06 §6).
|
||||
resource: authority.Resource,
|
||||
// Features `heap` and `regions` (spec 03 §18–§20).
|
||||
own: *const Type,
|
||||
own_array: *const Type,
|
||||
region,
|
||||
|
||||
pub const Array = struct { elem: Type, len: u64 };
|
||||
|
||||
@@ -87,7 +91,8 @@ pub const Type = union(enum) {
|
||||
return switch (a) {
|
||||
.int => |x| b.int == x,
|
||||
.named => |x| b.named == x,
|
||||
.local, .ref, .mut, .slice, .slice_mut => |x| x.eql(b.inner().?),
|
||||
.local, .ref, .mut, .slice, .slice_mut, .own, .own_array => |x| x.eql(b.inner().?),
|
||||
.region => true,
|
||||
.array => |x| x.len == b.array.len and x.elem.eql(b.array.elem),
|
||||
.cap => |k| b.cap == k,
|
||||
.builtin => |e| b.builtin == e,
|
||||
@@ -99,7 +104,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 => |x| x.*,
|
||||
.local, .ref, .mut, .slice, .slice_mut, .own, .own_array => |x| x.*,
|
||||
.array => |a| a.elem,
|
||||
else => null,
|
||||
};
|
||||
@@ -113,6 +118,14 @@ 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 => true,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn isMutBorrow(t: Type) bool {
|
||||
return t == .mut or t == .slice_mut;
|
||||
}
|
||||
@@ -126,7 +139,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 => false,
|
||||
.void, .never, .local, .ref, .mut, .slice, .slice_mut, .resource, .own, .own_array, .region => false,
|
||||
else => true,
|
||||
};
|
||||
}
|
||||
@@ -240,6 +253,17 @@ pub const Op = union(enum) {
|
||||
/// Intrinsic call (spec 05 §11). With `ok`/`err` it is the fallible
|
||||
/// terminator form; without, the infallible form.
|
||||
intrinsic: struct { index: u16, args: []const ValueId, ok: ?u32 = null, err: ?u32 = null },
|
||||
// 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_array: struct { n: ValueId, value: ValueId, cap: ValueId, ok: u32, err: u32 },
|
||||
own_take: ValueId,
|
||||
own_free: ValueId,
|
||||
region_create: struct { cap: ValueId, ok: u32, err: u32 },
|
||||
region_new: struct { region: ValueId, value: ValueId, ok: u32, err: u32 },
|
||||
region_array: struct { region: ValueId, n: ValueId, value: ValueId, ok: u32, err: u32 },
|
||||
region_reset: ValueId,
|
||||
region_destroy: ValueId,
|
||||
ret: ?ValueId,
|
||||
trap,
|
||||
|
||||
@@ -249,6 +273,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,
|
||||
.intrinsic => |x| x.ok != null,
|
||||
else => false,
|
||||
};
|
||||
@@ -376,6 +401,26 @@ 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| {
|
||||
f(ctx, x.value);
|
||||
f(ctx, x.cap);
|
||||
},
|
||||
.own_array => |x| {
|
||||
f(ctx, x.n);
|
||||
f(ctx, x.value);
|
||||
f(ctx, x.cap);
|
||||
},
|
||||
.own_take, .own_free, .region_reset, .region_destroy => |v| f(ctx, v),
|
||||
.region_create => |x| f(ctx, x.cap),
|
||||
.region_new => |x| {
|
||||
f(ctx, x.region);
|
||||
f(ctx, x.value);
|
||||
},
|
||||
.region_array => |x| {
|
||||
f(ctx, x.region);
|
||||
f(ctx, x.n);
|
||||
f(ctx, x.value);
|
||||
},
|
||||
.ret => |v| if (v) |x| f(ctx, x),
|
||||
.local_alloc => {},
|
||||
.local_store => |x| {
|
||||
@@ -410,6 +455,14 @@ pub fn forEachUse(op: Op, ctx: anytype, comptime f: fn (@TypeOf(ctx), ValueId) v
|
||||
}
|
||||
|
||||
/// Successor block indices of a terminator, in source order (may repeat).
|
||||
/// `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 },
|
||||
else => null,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn successors(op: Op, buf: *std.ArrayList(u32), gpa: std.mem.Allocator) !void {
|
||||
switch (op) {
|
||||
.br => |t| try buf.append(gpa, t.block),
|
||||
@@ -433,6 +486,10 @@ pub fn successors(op: Op, buf: *std.ArrayList(u32), gpa: std.mem.Allocator) !voi
|
||||
try buf.append(gpa, ok);
|
||||
try buf.append(gpa, x.err.?);
|
||||
},
|
||||
inline .own_new, .own_array, .region_create, .region_new, .region_array => |x| {
|
||||
try buf.append(gpa, x.ok);
|
||||
try buf.append(gpa, x.err);
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
}
|
||||
|
||||
+75
-6
@@ -485,6 +485,10 @@ const Parser = struct {
|
||||
try p.requireFeature(b.feature(), t.span, t.text);
|
||||
return .{ .builtin = b };
|
||||
}
|
||||
if (eql(t.text, "region")) {
|
||||
try p.requireFeature("regions", t.span, t.text);
|
||||
return .region;
|
||||
}
|
||||
if (eql(t.text, "listener") or eql(t.text, "stream")) {
|
||||
try p.requireFeature("resources", t.span, t.text);
|
||||
return .{ .resource = if (eql(t.text, "listener")) .listener else .stream };
|
||||
@@ -517,6 +521,18 @@ const Parser = struct {
|
||||
.append => .file_append,
|
||||
} };
|
||||
}
|
||||
if (eql(t.text, "own") or eql(t.text, "own_array")) {
|
||||
try p.requireFeature("heap", t.span, t.text);
|
||||
_ = try p.expect(.lt, "`<`");
|
||||
const inner_span = p.peek().span;
|
||||
const inner = try p.parseType();
|
||||
// Nested linear values need `linear_aggregates` (spec 03 §19.2).
|
||||
try p.gateLinearMember(inner, inner_span);
|
||||
_ = try p.expect(.gt, "`>`");
|
||||
const boxed = try p.arena.create(air.Type);
|
||||
boxed.* = inner;
|
||||
return if (eql(t.text, "own")) .{ .own = boxed } else .{ .own_array = boxed };
|
||||
}
|
||||
if (eql(t.text, "cap")) {
|
||||
try p.requireFeature("capabilities", t.span, "cap");
|
||||
_ = try p.expect(.lt, "`<`");
|
||||
@@ -540,8 +556,10 @@ const Parser = struct {
|
||||
_ = try p.expect(.lt, "`<`");
|
||||
const inner_span = p.peek().span;
|
||||
const inner = try p.parseType();
|
||||
// Storage and arrays of linear values need `linear_aggregates`; a
|
||||
// borrow of a linear value (`mut<file<read>>`) is fine.
|
||||
if (kind != .ref and kind != .mut) try p.gateLinearMember(inner, inner_span);
|
||||
if (kind == .array) {
|
||||
try p.gateLinearMember(inner, inner_span);
|
||||
_ = try p.expect(.comma, "`,`");
|
||||
const n_tok = try p.expect(.number, "array length");
|
||||
const n = std.fmt.parseInt(u64, n_tok.text, 0) catch 0;
|
||||
@@ -568,7 +586,7 @@ const Parser = struct {
|
||||
|
||||
/// Resources inside aggregates need the reserved feature `linear_aggregates`.
|
||||
fn gateLinearMember(p: *Parser, t: air.Type, span: Span) Error!void {
|
||||
if (t == .resource) try p.requireFeature("linear_aggregates", span, "resource as a member");
|
||||
if (t.isLinear()) try p.requireFeature("linear_aggregates", span, "linear value as a member");
|
||||
}
|
||||
|
||||
fn declares(p: *Parser, feature: []const u8) bool {
|
||||
@@ -724,11 +742,7 @@ const Parser = struct {
|
||||
while (p.peek().tag != .r_paren) {
|
||||
const v = try p.expect(.local, "block parameter");
|
||||
_ = try p.expect(.colon, "`:`");
|
||||
const ty_span = p.peek().span;
|
||||
const ty = try p.parseType();
|
||||
// Borrow-typed block parameters belong to the reserved feature
|
||||
// `borrow_joins` (spec 08 §11.6).
|
||||
if (ty.isBorrow()) try p.requireFeature("borrow_joins", ty_span, "borrow-typed block parameter");
|
||||
const id = try p.defineValue(v, .{ .block_param = .{ .block = index, .index = @intCast(params.items.len) } });
|
||||
try params.append(p.arena, .{ .value = id, .ty = ty });
|
||||
if (p.peek().tag != .comma) break;
|
||||
@@ -915,6 +929,7 @@ const Parser = struct {
|
||||
const err = try p.blockRef();
|
||||
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 (eql(op_tok.text, "intrinsic")) {
|
||||
try p.requireFeature("capabilities", op_tok.span, "intrinsic");
|
||||
const name = try p.expect(.word, "intrinsic name");
|
||||
@@ -941,6 +956,7 @@ const Parser = struct {
|
||||
_ = try p.expect(.nl, "end of line");
|
||||
|
||||
const produces_value = switch (op) {
|
||||
.own_take => 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,
|
||||
@@ -961,6 +977,59 @@ const Parser = struct {
|
||||
return .{ .result = result, .result2 = result2, .op = op, .span = if (result_tok) |rt| rt.span else op_tok.span };
|
||||
}
|
||||
|
||||
fn okErr(p: *Parser) Error!struct { u32, u32 } {
|
||||
_ = try p.expect(.comma, "`,`");
|
||||
_ = try p.expectWord("ok");
|
||||
_ = try p.expect(.arrow, "`->`");
|
||||
const ok = try p.blockRef();
|
||||
_ = try p.expect(.comma, "`,`");
|
||||
_ = try p.expectWord("err");
|
||||
_ = try p.expect(.arrow, "`->`");
|
||||
return .{ ok, try p.blockRef() };
|
||||
}
|
||||
|
||||
/// 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 = 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" => {
|
||||
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 } };
|
||||
},
|
||||
.@"own.array" => {
|
||||
const n, const v = try p.twoOperands();
|
||||
_ = try p.expect(.comma, "`,`");
|
||||
const c = try p.useValue();
|
||||
const ok, const err = try p.okErr();
|
||||
return .{ .own_array = .{ .n = n, .value = v, .cap = c, .ok = ok, .err = err } };
|
||||
},
|
||||
.@"own.take" => return .{ .own_take = try p.useValue() },
|
||||
.@"own.free" => return .{ .own_free = try p.useValue() },
|
||||
.@"region.create" => {
|
||||
const c = try p.useValue();
|
||||
const ok, const err = try p.okErr();
|
||||
return .{ .region_create = .{ .cap = c, .ok = ok, .err = err } };
|
||||
},
|
||||
.@"region.new" => {
|
||||
const r, const v = try p.twoOperands();
|
||||
const ok, const err = try p.okErr();
|
||||
return .{ .region_new = .{ .region = r, .value = v, .ok = ok, .err = err } };
|
||||
},
|
||||
.@"region.array" => {
|
||||
const r, const n = try p.twoOperands();
|
||||
_ = try p.expect(.comma, "`,`");
|
||||
const v = try p.useValue();
|
||||
const ok, const err = try p.okErr();
|
||||
return .{ .region_array = .{ .region = r, .n = n, .value = v, .ok = ok, .err = err } };
|
||||
},
|
||||
.@"region.reset" => return .{ .region_reset = try p.useValue() },
|
||||
.@"region.destroy" => return .{ .region_destroy = try p.useValue() },
|
||||
}
|
||||
}
|
||||
|
||||
/// Instructions of the features `ownership` and `arrays` (spec 07a).
|
||||
fn parseMemoryOp(p: *Parser, op_tok: Token) Error!?air.Op {
|
||||
const Name = enum {
|
||||
|
||||
@@ -105,6 +105,12 @@ pub fn printType(m: air.Module, t: air.Type, w: *Writer) Writer.Error!void {
|
||||
.cap => |k| try w.print("cap<{s}>", .{air.authority.kinds[k].name}),
|
||||
.builtin => |b| try w.writeAll(@tagName(b)),
|
||||
.resource => |r| try w.writeAll(r.text()),
|
||||
.own, .own_array => |inner| {
|
||||
try w.print("{s}<", .{@tagName(t)});
|
||||
try printType(m, inner.*, w);
|
||||
try w.writeByte('>');
|
||||
},
|
||||
.region => try w.writeAll("region"),
|
||||
.bool, .void, .never => try w.writeAll(@tagName(t)),
|
||||
}
|
||||
}
|
||||
@@ -286,6 +292,34 @@ 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);
|
||||
try okErr(f, w, x.ok, x.err);
|
||||
},
|
||||
.own_array => |x| {
|
||||
try two(f, w, "own.array", x.n, x.value);
|
||||
try w.writeAll(", ");
|
||||
try value(f, x.cap, w);
|
||||
try okErr(f, w, x.ok, x.err);
|
||||
},
|
||||
.own_take => |v| try one(f, w, "own.take", v),
|
||||
.own_free => |v| try one(f, w, "own.free", v),
|
||||
.region_create => |x| {
|
||||
try one(f, w, "region.create", x.cap);
|
||||
try okErr(f, w, x.ok, x.err);
|
||||
},
|
||||
.region_new => |x| {
|
||||
try two(f, w, "region.new", x.region, x.value);
|
||||
try okErr(f, w, x.ok, x.err);
|
||||
},
|
||||
.region_array => |x| {
|
||||
try two(f, w, "region.array", x.region, x.n);
|
||||
try w.writeAll(", ");
|
||||
try value(f, x.value, w);
|
||||
try okErr(f, w, x.ok, x.err);
|
||||
},
|
||||
.region_reset => |v| try one(f, w, "region.reset", v),
|
||||
.region_destroy => |v| try one(f, w, "region.destroy", v),
|
||||
.cap_narrow => |x| {
|
||||
try w.print("cap.narrow.{s} ", .{x.form});
|
||||
try value(f, x.cap, w);
|
||||
@@ -298,6 +332,10 @@ fn printOp(m: air.Module, f: air.Function, op: air.Op, w: *Writer) Writer.Error!
|
||||
}
|
||||
}
|
||||
|
||||
fn okErr(f: air.Function, w: *Writer, ok: u32, err: u32) Writer.Error!void {
|
||||
try w.print(", ok -> @{s}, err -> @{s}", .{ f.blocks[ok].name, f.blocks[err].name });
|
||||
}
|
||||
|
||||
fn one(f: air.Function, w: *Writer, op: []const u8, a: air.ValueId) Writer.Error!void {
|
||||
try w.print("{s} ", .{op});
|
||||
try value(f, a, w);
|
||||
|
||||
+179
-6
@@ -12,6 +12,7 @@ const std = @import("std");
|
||||
const air = @import("../air.zig");
|
||||
const diag = @import("../diag.zig");
|
||||
const world_mod = @import("world.zig");
|
||||
const budget = @import("../verifier/budget.zig");
|
||||
|
||||
pub const WorldOptions = world_mod.Options;
|
||||
|
||||
@@ -35,6 +36,10 @@ pub const Value = union(enum) {
|
||||
cap: u32,
|
||||
/// Linear resource: index into the world's handle table.
|
||||
resource: u32,
|
||||
/// `own<T>` / `own_array<T>`: the heap cell.
|
||||
own: *Cell,
|
||||
/// `region`: index into the machine's region table.
|
||||
region: u32,
|
||||
/// Value of a built-in enum such as `cap_error`.
|
||||
builtin: struct { which: air.authority.Builtin, variant: u32 },
|
||||
|
||||
@@ -92,7 +97,18 @@ pub const Grant = struct {
|
||||
};
|
||||
|
||||
/// An authority object held by the host: copies of a capability share it.
|
||||
pub const Authority = struct { kind: u16, scope: ?[]const u8 };
|
||||
/// For `mem.alloc`: `limit` (null = unlimited), `used` live bytes and the
|
||||
/// `parent` it was narrowed from; charges walk the chain (spec 03 §18.1).
|
||||
pub const Authority = struct {
|
||||
kind: u16,
|
||||
scope: ?[]const u8,
|
||||
limit: ?u64 = null,
|
||||
used: u64 = 0,
|
||||
parent: ?u32 = null,
|
||||
};
|
||||
|
||||
/// A region: its authority and the bytes charged by its current generation.
|
||||
pub const Region = struct { authority: u32, used: u64 };
|
||||
|
||||
pub const Options = struct {
|
||||
/// Maximum number of instructions to execute (spec 11 §7.1); null means unlimited.
|
||||
@@ -139,8 +155,15 @@ pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, opti
|
||||
if (std.mem.eql(u8, g.parameter, pname)) break g;
|
||||
} else return .{ .not_instantiated = .{ .reason = "missing_capability", .parameter = pname, .kind = kind } };
|
||||
if (!std.mem.eql(u8, g.kind, kind)) return .{ .not_instantiated = .{ .reason = "kind_mismatch", .parameter = pname, .kind = kind, .granted = g.kind } };
|
||||
if (!air.authority.validScope(p.ty.cap, g.scope)) return .{ .not_instantiated = .{ .reason = "invalid_scope", .parameter = pname, .kind = kind, .scope = g.scope } };
|
||||
try m.authorities.append(arena, .{ .kind = p.ty.cap, .scope = g.scope });
|
||||
// The deterministic profile requires an explicit allocation budget (spec 03 §18.2).
|
||||
const is_alloc = air.authority.kinds[p.ty.cap].scope == .byte_budget;
|
||||
if (!air.authority.validScope(p.ty.cap, g.scope) or (is_alloc and g.scope == null))
|
||||
return .{ .not_instantiated = .{ .reason = "invalid_scope", .parameter = pname, .kind = kind, .scope = g.scope } };
|
||||
try m.authorities.append(arena, .{
|
||||
.kind = p.ty.cap,
|
||||
.scope = g.scope,
|
||||
.limit = if (is_alloc) std.fmt.parseInt(u64, g.scope.?, 10) catch unreachable else null,
|
||||
});
|
||||
arg.* = .{ .cap = @intCast(m.authorities.items.len - 1) };
|
||||
}
|
||||
for (options.grants) |g| {
|
||||
@@ -204,6 +227,8 @@ const Machine = struct {
|
||||
/// Host authority table; capabilities index into it.
|
||||
authorities: std.ArrayList(Authority) = .empty,
|
||||
world: world_mod.World,
|
||||
owners: std.AutoHashMapUnmanaged(*Value.Cell, OwnInfo) = .empty,
|
||||
regions: std.ArrayList(Region) = .empty,
|
||||
/// Instructions executed so far.
|
||||
steps: u64 = 0,
|
||||
|
||||
@@ -347,6 +372,7 @@ const Machine = struct {
|
||||
// No narrowing form is registered yet, so verified AIR contains
|
||||
// no reachable cap.narrow (spec 05 §10.4; forms arrive with RFC 0007/0008).
|
||||
.cap_narrow => |x| return m.narrow(f, vals, x),
|
||||
.own_new, .own_array, .own_take, .own_free, .region_create, .region_new, .region_array, .region_reset, .region_destroy => return m.execAlloc(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 },
|
||||
@@ -460,8 +486,20 @@ const Machine = struct {
|
||||
}
|
||||
|
||||
fn narrow(m: *Machine, f: air.Function, vals: []Value, x: @FieldType(air.Op, "cap_narrow")) !Step {
|
||||
const a = m.authorities.items[vals[x.cap].cap];
|
||||
// Only `prefix` is registered (reference/capabilities.md).
|
||||
const parent = vals[x.cap].cap;
|
||||
const a = m.authorities.items[parent];
|
||||
if (std.mem.eql(u8, x.form, "budget")) {
|
||||
// A child budget; nothing is reserved (spec 03 §18.3).
|
||||
const n = usize_(vals[x.args[0]]);
|
||||
if (a.limit) |lim| if (n > lim) {
|
||||
vals[f.blocks[x.err].params[0].value] = .{ .builtin = .{ .which = .cap_error, .variant = 1 } };
|
||||
return .{ .jump = x.err };
|
||||
};
|
||||
try m.authorities.append(m.arena, .{ .kind = a.kind, .scope = null, .limit = n, .parent = parent });
|
||||
vals[f.blocks[x.ok].params[0].value] = .{ .cap = @intCast(m.authorities.items.len - 1) };
|
||||
return .{ .jump = x.ok };
|
||||
}
|
||||
// `prefix` (reference/capabilities.md).
|
||||
const path = try m.bytesOf(vals[x.args[0]]);
|
||||
const reason: ?u32 = if (!world_mod.World.validPath(path)) 0 else if (!world_mod.World.within(a.scope, path)) 1 else null;
|
||||
if (reason) |r| {
|
||||
@@ -473,6 +511,131 @@ const Machine = struct {
|
||||
return .{ .jump = x.ok };
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ heap and regions (spec 03 §18–§20)
|
||||
|
||||
/// Charges `bytes` to authority `a` and all its ancestors, or fails
|
||||
/// without charging anything if any limit would be exceeded.
|
||||
fn charge(m: *Machine, a: u32, bytes: ?u64) bool {
|
||||
const b = bytes orelse return false; // size overflow
|
||||
var x: ?u32 = a;
|
||||
while (x) |i| : (x = m.authorities.items[i].parent) {
|
||||
const auth = m.authorities.items[i];
|
||||
if (auth.limit) |lim| if (auth.used > lim or b > lim - auth.used) return false;
|
||||
}
|
||||
x = a;
|
||||
while (x) |i| : (x = m.authorities.items[i].parent) m.authorities.items[i].used += b;
|
||||
return true;
|
||||
}
|
||||
|
||||
fn uncharge(m: *Machine, a: u32, bytes: u64) void {
|
||||
var x: ?u32 = a;
|
||||
while (x) |i| : (x = m.authorities.items[i].parent) m.authorities.items[i].used -= bytes;
|
||||
}
|
||||
|
||||
fn arrayBytes(m: *Machine, element: Value, n: u64) ?u64 {
|
||||
const each = m.valueBytes(element) orelse return null;
|
||||
return std.math.mul(u64, n, each) catch null;
|
||||
}
|
||||
|
||||
/// Accounted size (spec 08 §7.1) of the type of a runtime value; equal
|
||||
/// to `budget.accountedSize` of the value's static type.
|
||||
fn valueBytes(m: *Machine, v: Value) ?u64 {
|
||||
return switch (v) {
|
||||
.int => |x| x.ty.bits() / 8,
|
||||
.boolean => 1,
|
||||
.aggregate => |a| budget.accountedSize(m.module, .{ .named = a.decl }, 0),
|
||||
.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,
|
||||
else => unreachable, // only value types are allocated (spec 03 §19.2)
|
||||
};
|
||||
}
|
||||
|
||||
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 };
|
||||
}
|
||||
|
||||
/// Owner cells remember their charge and authority for `own.free`.
|
||||
const OwnInfo = struct { authority: u32, bytes: u64 };
|
||||
|
||||
fn execAlloc(m: *Machine, f: air.Function, vals: []Value, types_of: anytype, inst: air.Inst) !Step {
|
||||
_ = types_of;
|
||||
switch (inst.op) {
|
||||
.own_new => |x| {
|
||||
const v = vals[x.value];
|
||||
const bytes = m.valueBytes(vals[x.value]);
|
||||
const a = vals[x.cap].cap;
|
||||
if (!m.charge(a, bytes)) return allocFailed(f, vals, x.err);
|
||||
const cell = try m.arena.create(Value.Cell);
|
||||
cell.* = .{ .value = try m.deepCopy(v), .ty = .void };
|
||||
try m.owners.put(m.arena, cell, .{ .authority = a, .bytes = bytes.? });
|
||||
vals[f.blocks[x.ok].params[0].value] = .{ .own = cell };
|
||||
return .{ .jump = x.ok };
|
||||
},
|
||||
.own_array => |x| {
|
||||
const n = usize_(vals[x.n]);
|
||||
const a = vals[x.cap].cap;
|
||||
const bytes = m.arrayBytes(vals[x.value], n);
|
||||
if (!m.charge(a, bytes)) return allocFailed(f, vals, x.err);
|
||||
const items = try m.arena.alloc(Value, n);
|
||||
for (items) |*it| it.* = try m.deepCopy(vals[x.value]);
|
||||
const cell = try m.arena.create(Value.Cell);
|
||||
cell.* = .{ .value = .{ .array = items }, .ty = .void };
|
||||
try m.owners.put(m.arena, cell, .{ .authority = a, .bytes = bytes.? });
|
||||
vals[f.blocks[x.ok].params[0].value] = .{ .own = cell };
|
||||
return .{ .jump = x.ok };
|
||||
},
|
||||
.own_take => |v| {
|
||||
const cell = vals[v].own;
|
||||
const info = m.owners.fetchRemove(cell).?.value;
|
||||
m.uncharge(info.authority, info.bytes);
|
||||
return bind(vals, inst.result, cell.value);
|
||||
},
|
||||
.own_free => |v| {
|
||||
const info = m.owners.fetchRemove(vals[v].own).?.value;
|
||||
m.uncharge(info.authority, info.bytes);
|
||||
return .next;
|
||||
},
|
||||
.region_create => |x| {
|
||||
try m.regions.append(m.arena, .{ .authority = vals[x.cap].cap, .used = 0 });
|
||||
vals[f.blocks[x.ok].params[0].value] = .{ .region = @intCast(m.regions.items.len - 1) };
|
||||
return .{ .jump = x.ok };
|
||||
},
|
||||
.region_new, .region_array => {
|
||||
const rb, const value, const n: ?u64 = switch (inst.op) {
|
||||
.region_new => |x| .{ x.region, x.value, null },
|
||||
.region_array => |x| .{ x.region, x.value, usize_(vals[x.n]) },
|
||||
else => unreachable,
|
||||
};
|
||||
const t = air.allocTargets(inst.op).?;
|
||||
const r = placePtr(asPlace(vals[rb])).region;
|
||||
const region = &m.regions.items[r];
|
||||
const bytes = if (n) |count| m.arrayBytes(vals[value], count) else m.valueBytes(vals[value]);
|
||||
if (!m.charge(region.authority, bytes)) return allocFailed(f, vals, t.err);
|
||||
region.used += bytes.?;
|
||||
const cell = try m.arena.create(Value.Cell);
|
||||
if (n) |count| {
|
||||
const items = try m.arena.alloc(Value, count);
|
||||
for (items) |*it| it.* = try m.deepCopy(vals[value]);
|
||||
cell.* = .{ .value = .{ .array = items }, .ty = .void };
|
||||
vals[f.blocks[t.ok].params[0].value] = .{ .slice = .{ .place = .{ .cell = cell, .path = &.{} }, .start = 0, .len = count } };
|
||||
} else {
|
||||
cell.* = .{ .value = try m.deepCopy(vals[value]), .ty = .void };
|
||||
vals[f.blocks[t.ok].params[0].value] = .{ .place = .{ .cell = cell, .path = &.{} } };
|
||||
}
|
||||
return .{ .jump = t.ok };
|
||||
},
|
||||
.region_reset, .region_destroy => |v| {
|
||||
const region = &m.regions.items[vals[v].region];
|
||||
m.uncharge(region.authority, region.used);
|
||||
region.used = 0;
|
||||
return .next;
|
||||
},
|
||||
else => unreachable,
|
||||
}
|
||||
}
|
||||
|
||||
fn intrinsic(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst, x: @FieldType(air.Op, "intrinsic")) !Step {
|
||||
const name = air.authority.intrinsics[x.index].name;
|
||||
const arg = struct {
|
||||
@@ -582,6 +745,16 @@ 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.arena.create(Value.Cell);
|
||||
cell.* = .{ .value = .{ .region = r }, .ty = .void };
|
||||
break :blk .{ .place = .{ .cell = cell, .path = &.{} } };
|
||||
},
|
||||
.resource => |hd| blk: {
|
||||
const cell = try m.arena.create(Value.Cell);
|
||||
cell.* = .{ .value = .{ .resource = hd }, .ty = .void };
|
||||
@@ -787,7 +960,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 => try s.write(null),
|
||||
.resource, .own, .region => try s.write(null),
|
||||
// A capability is opaque: only its kind is shown, never its identity.
|
||||
.cap => {
|
||||
try s.beginObject();
|
||||
|
||||
+62
-17
@@ -22,6 +22,9 @@ const Seg = union(enum) {
|
||||
split: struct { key: ValueId, side: u1 },
|
||||
/// An element or sub-range; overlaps every sibling.
|
||||
elem,
|
||||
/// A region allocation, keyed by its `ok` parameter; disjoint from
|
||||
/// every other allocation (spec 03 §20.2).
|
||||
alloc: ValueId,
|
||||
};
|
||||
|
||||
const Mode = enum { shared, exclusive };
|
||||
@@ -110,6 +113,10 @@ const Walker = struct {
|
||||
/// `through` (a borrow whose ancestors do not conflict) or directly on a
|
||||
/// local (`through == null`). Reports the first conflict (E2101).
|
||||
fn access(w: *Walker, root: ValueId, path: []const Seg, mode: Mode, via: ?ValueId, who: ValueId) !void {
|
||||
return w.accessCode(root, path, mode, via, who, "E2101", "conflicting borrow or access");
|
||||
}
|
||||
|
||||
fn accessCode(w: *Walker, root: ValueId, path: []const Seg, mode: Mode, via: ?ValueId, who: ValueId, code: []const u8, message: []const u8) !void {
|
||||
for (w.live, 0..) |is_live, cv| {
|
||||
if (!is_live) continue;
|
||||
const ci = w.info[cv] orelse continue; // live resources are not borrows
|
||||
@@ -117,7 +124,7 @@ const Walker = struct {
|
||||
if (via) |t| if (w.isAncestor(@intCast(cv), t)) continue;
|
||||
if (mode == .shared and ci.mode == .shared) continue;
|
||||
if (!overlap(path, ci.path)) continue;
|
||||
try w.report("E2101", "conflicting borrow or access", who, .{ "conflicts_with", @intCast(cv) });
|
||||
try w.report(code, message, who, .{ "conflicts_with", @intCast(cv) });
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -163,17 +170,18 @@ const Walker = struct {
|
||||
return w.types[v] == .local;
|
||||
}
|
||||
|
||||
/// Linear values: resources, owners and regions (spec 06 §6, spec 03 §19–§20).
|
||||
fn isResource(w: *Walker, v: ValueId) bool {
|
||||
return w.types[v] == .resource;
|
||||
return w.types[v].isLinear();
|
||||
}
|
||||
|
||||
/// A non-consuming use of resource `v` (a borrow of it).
|
||||
fn resourceUsable(w: *Walker, v: ValueId) !bool {
|
||||
if (w.live[v]) return true;
|
||||
switch (w.dead[v]) {
|
||||
.closed => try w.report("E3001", "resource used after it was closed", v, null),
|
||||
.moved => try w.report("E2001", "resource used after its ownership was transferred", v, null),
|
||||
.none => try w.report("E3001", "resource used before it is owned", v, null),
|
||||
.closed => try w.report("E3001", "linear value used after it was closed, freed or destroyed", v, null),
|
||||
.moved => try w.report("E2001", "linear value used after its ownership was transferred", v, null),
|
||||
.none => try w.report("E3001", "linear value used before it is owned", v, null),
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -181,7 +189,7 @@ const Walker = struct {
|
||||
/// Consumes resource `v` by closing or by transfer (spec 06 §6.2).
|
||||
fn consume(w: *Walker, v: ValueId, how: Dead) !void {
|
||||
if (!w.live[v]) {
|
||||
return w.report("E2002", "resource consumed twice", v, null);
|
||||
return w.report("E2002", "linear value consumed twice", v, null);
|
||||
}
|
||||
// Consumption is an exclusive access to the whole resource.
|
||||
try w.access(v, &.{}, .exclusive, null, v);
|
||||
@@ -201,6 +209,10 @@ pub fn overlap(a: []const Seg, b: []const Seg) bool {
|
||||
if (sx.side != y.split.side) return false;
|
||||
continue;
|
||||
},
|
||||
.alloc => |ka| if (y == .alloc) {
|
||||
if (ka != y.alloc) return false;
|
||||
continue;
|
||||
},
|
||||
.elem => {},
|
||||
}
|
||||
return true;
|
||||
@@ -233,6 +245,11 @@ 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 => {
|
||||
const t = air.allocTargets(op).?;
|
||||
try out.append(arena, .{ .target = t.ok, .args = &.{} });
|
||||
try out.append(arena, .{ .target = t.err, .args = &.{} });
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
}
|
||||
@@ -257,8 +274,8 @@ fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void {
|
||||
.path = &.{},
|
||||
.parent = null,
|
||||
};
|
||||
// Resource parameters were moved in: the function owns them (spec 06 §6.3).
|
||||
if (p.ty == .resource) w.live[p.value] = true;
|
||||
// Linear parameters were moved in: the function owns them (spec 06 §6.3).
|
||||
if (p.ty.isLinear()) w.live[p.value] = true;
|
||||
}
|
||||
|
||||
const dom = try ssa.dominators(c.arena, f);
|
||||
@@ -272,8 +289,9 @@ fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void {
|
||||
for (dom.rpo) |b| {
|
||||
@memcpy(w.live, entry_state[b].?);
|
||||
const blk = f.blocks[b];
|
||||
// Resource block parameters own their argument from here on.
|
||||
for (blk.params) |p| if (p.ty == .resource) {
|
||||
// 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)) {
|
||||
w.live[p.value] = true;
|
||||
w.dead[p.value] = .none;
|
||||
};
|
||||
@@ -292,18 +310,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] == .resource) try w.consume(a, .moved);
|
||||
// A resource parameter of the target that is still live on this
|
||||
// edge would be overwritten: that instance leaks.
|
||||
for (f.blocks[e.target].params) |p| if (p.ty == .resource) {
|
||||
if (w.live[p.value]) try w.report("E3002", "resource not consumed before it is redefined", p.value, null);
|
||||
for (e.args) |a| if (types[a].isLinear()) 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);
|
||||
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] == .resource;
|
||||
const is_res = types[v].isLinear();
|
||||
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 } },
|
||||
@@ -377,6 +396,32 @@ fn step(w: *Walker, inst: air.Inst) !void {
|
||||
w.live[r] = true;
|
||||
};
|
||||
},
|
||||
.own_free, .own_take => |v| try w.consume(v, .closed),
|
||||
.region_reset => |v| {
|
||||
if (!try w.resourceUsable(v)) return;
|
||||
// Reset invalidates the generation: no reference may be live.
|
||||
try w.accessCode(v, &.{}, .exclusive, null, v, "E2104", "region reset would invalidate a live reference into the region");
|
||||
},
|
||||
.region_destroy => |v| {
|
||||
if (w.live[v]) try w.accessCode(v, &.{}, .exclusive, null, v, "E2104", "region destroy would invalidate a live reference into the region");
|
||||
if (!w.live[v]) return w.report("E2002", "linear value consumed twice", v, null);
|
||||
w.live[v] = false;
|
||||
w.dead[v] = .closed;
|
||||
},
|
||||
.region_new, .region_array => {
|
||||
const rb = switch (inst.op) {
|
||||
.region_new => |x| x.region,
|
||||
.region_array => |x| x.region,
|
||||
else => unreachable,
|
||||
};
|
||||
if (!try w.usable(rb)) return;
|
||||
// The allocation is a fresh exclusive child of the shared region
|
||||
// borrow; it comes alive on the `ok` edge (spec 03 §20.2).
|
||||
const ok = air.allocTargets(inst.op).?.ok;
|
||||
const p = w.f.blocks[ok].params[0].value;
|
||||
const ri = w.info[rb].?;
|
||||
w.info[p] = .{ .owned = true, .mode = .exclusive, .root = ri.root, .path = try w.extend(ri.path, .{ .alloc = p }), .parent = rb };
|
||||
},
|
||||
.intrinsic => |x| {
|
||||
try lendArgs(w, x.args);
|
||||
// Closing intrinsics consume on both edges, so before propagation.
|
||||
|
||||
@@ -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 => 8,
|
||||
.ref, .mut, .cap, .resource, .own, .region => 8,
|
||||
.own_array => 16,
|
||||
.slice, .slice_mut => 16,
|
||||
.builtin => |b| tagSize(b.variants().len),
|
||||
.array => |a| std.math.mul(u64, a.len, accountedSize(m, a.elem, depth + 1) orelse return null) catch null,
|
||||
|
||||
@@ -19,6 +19,8 @@ fn checkFunction(c: *Context, f: air.Function) !void {
|
||||
try invalid(c, f, inst.span, "local.alloc outside the entry block", b.name);
|
||||
};
|
||||
|
||||
try checkBorrowParams(c, f);
|
||||
|
||||
for (f.blocks) |b| {
|
||||
if (b.insts.len == 0) {
|
||||
try invalid(c, f, b.span, "block has no terminator", b.name);
|
||||
@@ -77,6 +79,11 @@ 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 => {
|
||||
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");
|
||||
},
|
||||
// Fallible intrinsics: `ok` takes the registered results, `err` one `io_error`.
|
||||
.intrinsic => |x| {
|
||||
const reg = air.authority.intrinsics[x.index];
|
||||
@@ -88,6 +95,43 @@ fn checkTerminator(c: *Context, f: air.Function, inst: air.Inst) !void {
|
||||
}
|
||||
}
|
||||
|
||||
/// Borrow-typed block parameters belong to the reserved feature
|
||||
/// `borrow_joins`, except the parameter of an `ok` target of `region.new` /
|
||||
/// `region.array` when every edge into the block is such an `ok` edge
|
||||
/// (spec 08 §11.6).
|
||||
fn checkBorrowParams(c: *Context, f: air.Function) !void {
|
||||
var succ: std.ArrayList(u32) = .empty;
|
||||
for (f.blocks, 0..) |b, bi| {
|
||||
const has_borrow = for (b.params) |p| {
|
||||
if (p.ty.isBorrow()) break true;
|
||||
} else false;
|
||||
if (!has_borrow) continue;
|
||||
var allowed = b.params.len == 1;
|
||||
var any_edge = false;
|
||||
for (f.blocks) |pred| {
|
||||
if (pred.insts.len == 0) continue;
|
||||
const term = pred.insts[pred.insts.len - 1].op;
|
||||
succ.clearRetainingCapacity();
|
||||
try air.successors(term, &succ, c.arena);
|
||||
for (succ.items) |s| if (s == bi) {
|
||||
any_edge = true;
|
||||
const is_alloc_ok = switch (term) {
|
||||
.region_new => |x| x.ok == bi and x.err != bi,
|
||||
.region_array => |x| x.ok == bi and x.err != bi,
|
||||
else => false,
|
||||
};
|
||||
if (!is_alloc_ok) allowed = false;
|
||||
};
|
||||
}
|
||||
if (allowed and any_edge) continue;
|
||||
try c.report("E0006", b.span, "construct belongs to a feature the module does not declare", &.{
|
||||
.{ .name = "reason", .value = .{ .str = "feature_not_declared" } },
|
||||
.{ .name = "feature", .value = .{ .str = "borrow_joins" } },
|
||||
.{ .name = "construct", .value = .{ .str = "borrow-typed block parameter" } },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn paramCount(c: *Context, f: air.Function, span: air.Span, block: u32, expected: usize, message: []const u8) !void {
|
||||
const blk = f.blocks[block];
|
||||
if (blk.params.len == expected) return;
|
||||
|
||||
@@ -26,6 +26,12 @@ pub fn check(c: *Context) !void {
|
||||
});
|
||||
};
|
||||
},
|
||||
.own_new, .own_array, .region_create, .region_new, .region_array => 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" } },
|
||||
});
|
||||
},
|
||||
.intrinsic => |x| if (air.authority.intrinsics[x.index].effect) |e| {
|
||||
if (!contains(f.effects, e)) try c.report("E3101", inst.span, "intrinsic effect not declared by the caller", &.{
|
||||
.{ .name = "function", .value = .{ .str = f.name } },
|
||||
|
||||
+76
-5
@@ -72,7 +72,7 @@ fn visitDecl(c: *Context, state: anytype, i: u32) !void {
|
||||
state[i] = .black;
|
||||
}
|
||||
|
||||
const Position = enum { member, param, ret, block_param };
|
||||
const Position = enum { member, param, ret, block_param, borrowed };
|
||||
|
||||
/// Where a type may appear (spec 07 §8.3, §8.8):
|
||||
/// - `void`/`never` only as return types;
|
||||
@@ -84,7 +84,8 @@ fn wellFormed(c: *Context, span: air.Span, t: Type, pos: Position, owner: []cons
|
||||
const ok = switch (t) {
|
||||
.void, .never => pos == .ret,
|
||||
.local => false,
|
||||
.ref, .mut, .slice, .slice_mut, .resource => pos != .member,
|
||||
.ref, .mut, .slice, .slice_mut => pos != .member and pos != .borrowed,
|
||||
.resource, .own, .own_array, .region => pos != .member,
|
||||
else => true,
|
||||
};
|
||||
if (!ok) try c.report("E1001", span, "type not allowed in this position", &.{
|
||||
@@ -92,7 +93,9 @@ 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) } },
|
||||
});
|
||||
if (t.inner()) |inner| try wellFormed(c, span, inner, .member, owner);
|
||||
// The pointee of ref/mut may be a linear value (`mut<file<read>>`);
|
||||
// every other compound holds value types only.
|
||||
if (t.inner()) |inner| try wellFormed(c, span, inner, if (t == .ref or t == .mut) .borrowed else .member, owner);
|
||||
}
|
||||
|
||||
/// `local.alloc` results are checked separately: their own type is storage.
|
||||
@@ -135,6 +138,31 @@ const FnCtx = struct {
|
||||
});
|
||||
}
|
||||
|
||||
/// A `cap<mem.alloc>` operand: wrong kind is E3201, not a capability E1001.
|
||||
fn expectAllocCap(fc: *FnCtx, span: air.Span, v: air.ValueId) !void {
|
||||
const t = fc.typeOf(v);
|
||||
if (t != .cap) return fc.kindError(span, v, "cap<mem.alloc>");
|
||||
const kind = air.authority.kinds[t.cap].name;
|
||||
if (!std.mem.eql(u8, kind, "mem.alloc")) try fc.c.report("E3201", span, "allocation needs cap<mem.alloc>", &.{
|
||||
.{ .name = "function", .value = .{ .str = fc.f.name } },
|
||||
.{ .name = "expected", .value = .{ .str = "mem.alloc" } },
|
||||
.{ .name = "found", .value = .{ .str = kind } },
|
||||
});
|
||||
}
|
||||
|
||||
fn expectRegionRef(fc: *FnCtx, span: air.Span, v: air.ValueId) !void {
|
||||
const t = fc.typeOf(v);
|
||||
if (t != .ref or t.ref.* != .region) try fc.kindError(span, v, "ref<region>");
|
||||
}
|
||||
|
||||
/// `ok` receives `result`, `err` an `alloc_error` (counts checked by the CFG stage).
|
||||
fn expectOkErr(fc: *FnCtx, span: air.Span, ok: u32, err: u32, result: Type) !void {
|
||||
const p = fc.f.blocks[ok].params[0];
|
||||
if (!p.ty.eql(result)) try fc.mismatch(span, try fc.c.valueName(fc.f, p.value), result, p.ty);
|
||||
const e = fc.f.blocks[err].params[0];
|
||||
if (!e.ty.eql(.{ .builtin = .alloc_error })) try fc.mismatch(span, try fc.c.valueName(fc.f, e.value), .{ .builtin = .alloc_error }, e.ty);
|
||||
}
|
||||
|
||||
fn kindError(fc: *FnCtx, span: air.Span, v: air.ValueId, expected: []const u8) !void {
|
||||
try fc.c.report("E1001", span, "operand has the wrong kind of type", &.{
|
||||
.{ .name = "function", .value = .{ .str = fc.f.name } },
|
||||
@@ -299,6 +327,7 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type {
|
||||
.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,
|
||||
.own_take => |v| fc.ty[v] orelse return null,
|
||||
.slice_split => |x| fc.ty[x.slice] orelse return null,
|
||||
else => return null,
|
||||
};
|
||||
@@ -307,13 +336,17 @@ 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 => .{ .ref = try boxed(a, t) },
|
||||
.resource, .region => .{ .ref = try boxed(a, t) },
|
||||
.own => |inner| .{ .ref = inner },
|
||||
.own_array => |inner| .{ .slice = inner },
|
||||
.slice, .slice_mut => .{ .slice = try boxed(a, t.inner().?) },
|
||||
else => invalid,
|
||||
},
|
||||
.borrow_mut => switch (t) {
|
||||
.local, .mut => .{ .mut = try boxed(a, t.inner().?) },
|
||||
.resource => .{ .mut = try boxed(a, t) },
|
||||
.resource, .region => .{ .mut = try boxed(a, t) },
|
||||
.own => |inner| .{ .mut = inner },
|
||||
.own_array => |inner| .{ .slice_mut = inner },
|
||||
.slice_mut => .{ .slice_mut = try boxed(a, t.inner().?) },
|
||||
else => invalid,
|
||||
},
|
||||
@@ -342,6 +375,7 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type {
|
||||
else => invalid,
|
||||
},
|
||||
.slice_sub, .slice_split => if (t.isSlice()) t else invalid,
|
||||
.own_take => if (t == .own) t.own.* else invalid,
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
@@ -522,6 +556,39 @@ 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_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");
|
||||
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");
|
||||
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>"),
|
||||
.region_create => |x| {
|
||||
try fc.expectAllocCap(span, x.cap);
|
||||
try fc.expectOkErr(span, x.ok, x.err, .region);
|
||||
},
|
||||
.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");
|
||||
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");
|
||||
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"),
|
||||
.cap_narrow => |x| {
|
||||
const t = fc.typeOf(x.cap);
|
||||
if (t != .cap) return fc.kindError(span, x.cap, "cap<K>");
|
||||
@@ -532,6 +599,10 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
|
||||
.{ .name = "kind", .value = .{ .str = air.authority.kinds[t.cap].name } },
|
||||
.{ .name = "form", .value = .{ .str = x.form } },
|
||||
});
|
||||
if (std.mem.eql(u8, x.form, "budget")) {
|
||||
if (x.args.len != 1) return fc.c.report("E1001", span, "cap.narrow.budget takes one byte-count operand", &.{.{ .name = "function", .value = .{ .str = f.name } }});
|
||||
try fc.expectValue(span, x.args[0], .{ .int = .usize });
|
||||
}
|
||||
if (std.mem.eql(u8, x.form, "prefix")) {
|
||||
if (x.args.len != 1) return fc.c.report("E1001", span, "cap.narrow.prefix takes one path operand", &.{.{ .name = "function", .value = .{ .str = f.name } }});
|
||||
if (!operandMatches(.bytes, fc.typeOf(x.args[0]))) try fc.kindError(span, x.args[0], "slice<u8>");
|
||||
|
||||
Reference in new issue
Block a user