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:
dev committed 2026-10-04 14:26:34 +03:00
1 parent b8d4ab4d4c
commit 7f4ce71d44
38 files changed
+1341 -48

No files matched your search

+1 -1
View File
@@ -99,5 +99,5 @@ These run through all phases rather than belonging to one.
|---|---|
| P0 | done; AIR format 0 frozen as the semantic baseline (spec 07 §8.7) |
| P1 | done (exit review in the phase file) |
| P2 | in progress: RFC 0006 (effects, capabilities) and RFC 0007 (I/O, resources, deterministic profile) implemented; next RFC 0008 (heap, regions), hosted profile, unsafe boundaries |
| P2 | in progress: RFCs 0006 (effects, capabilities), 0007 (I/O, resources, deterministic profile) and 0008 (heap, regions, budgets) implemented; next unsafe boundaries, hosted profile, audit reports, `aji.toml` grants |
| P3–P8 | not started |
@@ -23,10 +23,10 @@ Out: tasks, threads, async I/O (P3); FFI to native code (P7).
| P2-1 | done | Resolve Q-011, Q-012, Q-018 (RFC 0006; Q-018 resolved in P0) | — | spec 05, 07, 10 | questions resolved; runtime record format defined |
| P2-2 | done | Formal signatures for fs, io, net, clock, random intrinsics | P2-1 | `reference/intrinsics.md` | each intrinsic lists types, effects, capabilities, ownership, failure, blocking (spec 09 §2) |
| P2-2a | done | Publish features `effects` and `capabilities` (spec text, registry status, `supported`); effect checking applies to modules declaring `effects` | P2-1 | `reference/air-features.md`, `src/air/features.zig` | feature_not_declared / missing_dependency tests; baseline modules unaffected |
| P2-2b | todo | Specify and publish `heap` (`Own<T>`, `own.alloc`, `own.free`, move-only values) and `regions` (static generations per Q-010); contracts in spec 07a | P2-2a | spec 03, 07a, 08; registry | features published |
| P2-2c | todo | Ownership verifier for move-only values: use after move, double consume | P2-2b | `src/verifier/ownership.zig` | E2001, E2002 accept/reject (incl. `phase2/reject/use_after_move.air`) |
| P2-2d | todo | Region verifier: reset/destroy with live borrows, prior-generation use; region-derived borrows as an escapable `from` source | P2-2b | `src/verifier/region.zig` | E2104 accept/reject |
| P2-2e | todo | Interpreter heap and regions | P2-2b | `src/interp/memory.zig` | run tests; file-copy with a heap-backed region buffer |
| P2-2b | done | Specify and publish `heap` (`Own<T>`, `own.alloc`, `own.free`, move-only values) and `regions` (static generations per Q-010); contracts in spec 07a | P2-2a | spec 03, 07a, 08; registry | features published |
| P2-2c | done | Ownership verifier for move-only values: use after move, double consume | P2-2b | `src/verifier/ownership.zig` | E2001, E2002 accept/reject (incl. `phase2/reject/use_after_move.air`) |
| P2-2d | done | Region verifier: reset/destroy with live borrows, prior-generation use; region-derived borrows as an escapable `from` source | P2-2b | `src/verifier/region.zig` | E2104 accept/reject |
| P2-2e | done | Interpreter heap and regions | P2-2b | `src/interp/memory.zig` | run tests; file-copy with a heap-backed region buffer |
| P2-3 | done | Contract tables for `intrinsic.call`, `resource.consume`, `call.indirect` | P2-1 | spec 07 appendix | all spec 07 §4 fields present |
| P2-4 | done | Effect verifier (calls and intrinsics) | P2-1 | `src/verifier/effects.zig` | E3101 accept/reject, including transitive callees |
| P2-5 | done | Capability verifier: unforgeability, narrowing, transfer rules (E3201, E3202, instantiation) | P2-1 | `src/verifier/caps.zig` | E3201, E3202 accept/reject |
+1
View File
@@ -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");
+4 -1
View File
@@ -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",
};
+4 -4
View File
@@ -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
View File
@@ -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
View File
@@ -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 {
+38
View File
@@ -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
View File
@@ -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
View File
@@ -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.
+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 => 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,
+44
View File
@@ -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;
+6
View File
@@ -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
View File
@@ -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>");
@@ -0,0 +1,19 @@
; Allocation requires the effect mem.alloc.
; expect: reject E3101
; phase: 2
; spec: docs/spec/03-memory-model.md
module test.alloc_without_effect
air 0
lang 0.1
features [capabilities, effects, heap, ownership, resources]
fn @f(%heap: cap<mem.alloc>) -> void
effects []
entry:
%v = const.u64 1
own.new %v, %heap, ok -> @have, err -> @nomem
have(%o: own<u64>):
own.free %o
ret
nomem(%e: alloc_error):
ret
@@ -0,0 +1,19 @@
; own.new needs cap<mem.alloc>.
; expect: reject E3201
; phase: 2
; spec: docs/spec/03-memory-model.md
module test.alloc_wrong_capability
air 0
lang 0.1
features [capabilities, effects, heap, ownership, resources]
fn @f(%heap: cap<fs.read>) -> void
effects [mem.alloc]
entry:
%v = const.u64 1
own.new %v, %heap, ok -> @have, err -> @nomem
have(%o: own<u64>):
own.free %o
ret
nomem(%e: alloc_error):
ret
@@ -0,0 +1,25 @@
; A borrow-typed block parameter reached by br still needs borrow_joins.
; expect: reject E0006
; phase: 2
; spec: docs/spec/03-memory-model.md
module test.borrow_parameter_not_from_allocation
air 0
lang 0.1
features [arrays, capabilities, effects, heap, ownership, regions, resources]
fn @f(%heap: cap<mem.alloc>) -> void
effects [mem.alloc]
entry:
region.create %heap, ok -> @have, err -> @nomem
have(%r: region):
%rb = borrow.ref %r
%v = const.u64 1
region.new %rb, %v, ok -> @got, err -> @nomem2
got(%p: mut<u64>):
br @again(%p)
again(%q: mut<u64>):
trap
nomem(%e: alloc_error):
ret
nomem2(%e2: alloc_error):
trap
@@ -0,0 +1,21 @@
; The owner is freed while a borrow of it is live.
; expect: reject E2101
; phase: 2
; spec: docs/spec/03-memory-model.md
module test.own_free_while_borrowed
air 0
lang 0.1
features [capabilities, effects, heap, ownership, resources]
fn @f(%heap: cap<mem.alloc>) -> void
effects [mem.alloc]
entry:
%v = const.u64 1
own.new %v, %heap, ok -> @have, err -> @nomem
have(%o: own<u64>):
%b = borrow.ref %o
own.free %o
borrow.end %b
ret
nomem(%e: alloc_error):
ret
@@ -0,0 +1,18 @@
; The owner is never freed.
; expect: reject E3002
; phase: 2
; spec: docs/spec/03-memory-model.md
module test.own_leak
air 0
lang 0.1
features [capabilities, effects, heap, ownership, resources]
fn @f(%heap: cap<mem.alloc>) -> void
effects [mem.alloc]
entry:
%v = const.u64 1
own.new %v, %heap, ok -> @have, err -> @nomem
have(%o: own<u64>):
ret
nomem(%e: alloc_error):
ret
@@ -0,0 +1,13 @@
; own<own<u64>> nests linear values.
; expect: reject E0006
; phase: 2
; spec: docs/spec/03-memory-model.md
module test.own_nested
air 0
lang 0.1
features [capabilities, effects, heap, ownership, resources]
fn @f(%o: own<own<u64>>) -> void
effects []
entry:
trap
@@ -0,0 +1,13 @@
; own<file<read>> would let own.free drop an open file.
; expect: reject E0006
; phase: 2
; spec: docs/spec/03-memory-model.md
module test.own_of_resource
air 0
lang 0.1
features [capabilities, effects, heap, ownership, resources]
fn @f(%o: own<file<read>>) -> void
effects []
entry:
trap
@@ -0,0 +1,21 @@
; The owner is borrowed after own.free.
; expect: reject E3001
; phase: 2
; spec: docs/spec/03-memory-model.md
module test.own_use_after_free
air 0
lang 0.1
features [capabilities, effects, heap, ownership, resources]
fn @f(%heap: cap<mem.alloc>) -> void
effects [mem.alloc]
entry:
%v = const.u64 1
own.new %v, %heap, ok -> @have, err -> @nomem
have(%o: own<u64>):
own.free %o
%b = borrow.ref %o
borrow.end %b
ret
nomem(%e: alloc_error):
ret
@@ -0,0 +1,26 @@
; The owner is moved into a callee and then borrowed.
; expect: reject E2001
; phase: 2
; spec: docs/spec/03-memory-model.md
module test.own_use_after_move
air 0
lang 0.1
features [capabilities, effects, heap, ownership, resources]
fn @f(%heap: cap<mem.alloc>) -> void
effects [mem.alloc]
entry:
%v = const.u64 1
own.new %v, %heap, ok -> @have, err -> @nomem
have(%o: own<u64>):
call @sink(%o)
%b = borrow.ref %o
borrow.end %b
ret
nomem(%e: alloc_error):
ret
fn @sink(%o: own<u64>) -> void
effects []
entry:
own.free %o
ret
@@ -0,0 +1,26 @@
; The region borrow is ended while one of its allocations is live.
; expect: reject E2102
; phase: 2
; spec: docs/spec/03-memory-model.md
module test.region_allocation_outlives_borrow
air 0
lang 0.1
features [arrays, capabilities, effects, heap, ownership, regions, resources]
fn @f(%heap: cap<mem.alloc>) -> void
effects [mem.alloc]
entry:
region.create %heap, ok -> @have, err -> @nomem
have(%r: region):
%rb = borrow.ref %r
%v = const.u64 1
region.new %rb, %v, ok -> @got, err -> @nomem2
got(%p: mut<u64>):
borrow.end %rb
borrow.end %p
region.destroy %r
ret
nomem(%e: alloc_error):
ret
nomem2(%e2: alloc_error):
trap
@@ -0,0 +1,26 @@
; region.destroy while the region borrow is live.
; expect: reject E2104
; phase: 2
; spec: docs/spec/03-memory-model.md
module test.region_destroy_with_live_reference
air 0
lang 0.1
features [arrays, capabilities, effects, heap, ownership, regions, resources]
fn @f(%heap: cap<mem.alloc>) -> void
effects [mem.alloc]
entry:
region.create %heap, ok -> @have, err -> @nomem
have(%r: region):
%rb = borrow.ref %r
%v = const.u64 1
region.new %rb, %v, ok -> @got, err -> @nomem2
got(%p: mut<u64>):
borrow.end %p
region.destroy %r
borrow.end %rb
ret
nomem(%e: alloc_error):
ret
nomem2(%e2: alloc_error):
trap
@@ -0,0 +1,17 @@
; The region is never destroyed.
; expect: reject E3002
; phase: 2
; spec: docs/spec/03-memory-model.md
module test.region_leak
air 0
lang 0.1
features [arrays, capabilities, effects, heap, ownership, regions, resources]
fn @f(%heap: cap<mem.alloc>) -> void
effects [mem.alloc]
entry:
region.create %heap, ok -> @have, err -> @nomem
have(%r: region):
ret
nomem(%e: alloc_error):
ret
@@ -0,0 +1,27 @@
; region.reset while an allocation is still borrowed would invalidate a live reference.
; expect: reject E2104
; phase: 2
; spec: docs/spec/03-memory-model.md
module test.region_reset_with_live_reference
air 0
lang 0.1
features [arrays, capabilities, effects, heap, ownership, regions, resources]
fn @f(%heap: cap<mem.alloc>) -> void
effects [mem.alloc]
entry:
region.create %heap, ok -> @have, err -> @nomem
have(%r: region):
%rb = borrow.ref %r
%v = const.u64 1
region.new %rb, %v, ok -> @got, err -> @nomem2
got(%p: mut<u64>):
region.reset %r
borrow.end %p
borrow.end %rb
region.destroy %r
ret
nomem(%e: alloc_error):
ret
nomem2(%e2: alloc_error):
trap
@@ -0,0 +1,41 @@
; Two 12-byte children of a 16-byte parent: limits may oversubscribe; the parent bounds the total.
; expect: run
; grant: heap=mem.alloc:16
; result: 1
; phase: 2
; spec: docs/spec/03-memory-model.md
module test.budget_children_compete
air 0
lang 0.1
features [capabilities, effects, heap, ownership, resources]
fn @main(%heap: cap<mem.alloc>) -> u8
effects [mem.alloc]
entry:
%twelve = const.usize 12
cap.narrow.budget %heap, %twelve, ok -> @a, err -> @bad
a(%ca: cap<mem.alloc>):
cap.narrow.budget %heap, %twelve, ok -> @b, err -> @bad2
b(%cb: cap<mem.alloc>):
%v = const.u64 1
own.new %v, %ca, ok -> @x, err -> @nomem
x(%ox: own<u64>):
own.new %v, %cb, ok -> @y, err -> @nomem2
y(%oy: own<u64>):
%small = const.u8 1
own.new %small, %cb, ok -> @z, err -> @parent_full
z(%oz: own<u8>):
trap
parent_full(%e3: alloc_error):
own.free %ox
own.free %oy
%one = const.u8 1
ret %one
bad(%c1: cap_error):
trap
bad2(%c2: cap_error):
trap
nomem2(%e2: alloc_error):
trap
nomem(%e: alloc_error):
trap
@@ -0,0 +1,30 @@
; A second 8-byte object does not fit an 8-byte budget.
; expect: run
; grant: heap=mem.alloc:8
; result: 1
; phase: 2
; spec: docs/spec/03-memory-model.md
module test.budget_exceeded
air 0
lang 0.1
features [capabilities, effects, heap, ownership, resources]
fn @main(%heap: cap<mem.alloc>) -> u8
effects [mem.alloc]
entry:
%v = const.u64 1
own.new %v, %heap, ok -> @first, err -> @nomem
first(%a: own<u64>):
own.new %v, %heap, ok -> @second, err -> @full
second(%b: own<u64>):
trap
full(%e2: alloc_error):
own.free %a
enum.switch alloc_error %e2, budget_exceeded -> @exceeded, out_of_memory -> @oom
exceeded:
%one = const.u8 1
ret %one
oom:
trap
nomem(%e: alloc_error):
trap
@@ -0,0 +1,16 @@
; In the deterministic profile a mem.alloc grant must carry a byte limit.
; expect: run
; grant: heap=mem.alloc
; not_instantiated: invalid_scope
; phase: 2
; spec: docs/spec/03-memory-model.md
module test.budget_mandatory
air 0
lang 0.1
features [capabilities, effects, heap, ownership, resources]
fn @main(%heap: cap<mem.alloc>) -> u8
effects []
entry:
%z = const.u8 0
ret %z
@@ -0,0 +1,25 @@
; A child budget larger than the parent limit is refused with not_subset.
; expect: run
; grant: heap=mem.alloc:16
; result: 1
; phase: 2
; spec: docs/spec/03-memory-model.md
module test.budget_narrow_not_subset
air 0
lang 0.1
features [capabilities, effects, heap, ownership, resources]
fn @main(%heap: cap<mem.alloc>) -> u8
effects []
entry:
%n = const.usize 32
cap.narrow.budget %heap, %n, ok -> @ok, err -> @refused
ok(%c: cap<mem.alloc>):
trap
refused(%e: cap_error):
enum.switch cap_error %e, not_subset -> @ns, default -> @other()
ns:
%one = const.u8 1
ret %one
other:
trap
@@ -0,0 +1,26 @@
; The budget limits live bytes: freeing returns the quota.
; expect: run
; grant: heap=mem.alloc:8
; result: 5
; phase: 2
; spec: docs/spec/03-memory-model.md
module test.budget_returned_on_free
air 0
lang 0.1
features [capabilities, effects, heap, ownership, resources]
fn @main(%heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
entry:
%v = const.u64 5
own.new %v, %heap, ok -> @first, err -> @nomem
first(%a: own<u64>):
own.free %a
own.new %v, %heap, ok -> @second, err -> @nomem2
second(%b: own<u64>):
%r = own.take %b
ret %r
nomem2(%e2: alloc_error):
trap
nomem(%e: alloc_error):
trap
@@ -0,0 +1,27 @@
; Copies of a capability share one budget.
; expect: run
; grant: heap=mem.alloc:8
; result: 1
; phase: 2
; spec: docs/spec/03-memory-model.md
module test.budget_shared_by_copies
air 0
lang 0.1
features [capabilities, effects, heap, ownership, resources]
fn @main(%heap: cap<mem.alloc>) -> u8
effects [mem.alloc]
entry:
%other = copy %heap
%v = const.u64 1
own.new %v, %heap, ok -> @first, err -> @nomem
first(%a: own<u64>):
own.new %v, %other, ok -> @second, err -> @full
second(%b: own<u64>):
trap
full(%e2: alloc_error):
own.free %a
%one = const.u8 1
ret %one
nomem(%e: alloc_error):
trap
@@ -0,0 +1,39 @@
; own.array of runtime length, borrowed as a slice.
; expect: run
; grant: heap=mem.alloc:64
; result: [7,7,9,7,7]
; phase: 2
; spec: docs/spec/03-memory-model.md
module test.own_array_buffer
air 0
lang 0.1
features [arrays, capabilities, effects, heap, ownership, resources]
fn @main(%heap: cap<mem.alloc>) -> array<u8, 5>
effects [mem.alloc]
entry:
%dst = local.alloc array<u8, 5>
local.zero %dst
%n = const.usize 5
%seven = const.u8 7
own.array %n, %seven, %heap, ok -> @have, err -> @nomem
have(%a: own_array<u8>):
%s = borrow.mut %a
%i = const.usize 2
%el = borrow.index %s, %i
%nine = const.u8 9
store %el, %nine
borrow.end %el
%src = borrow.ref %s
%dm = borrow.mut %dst
%ds = slice.make %dm
slice.copy %ds, %src
borrow.end %ds
borrow.end %dm
borrow.end %src
borrow.end %s
own.free %a
%r = local.load %dst
ret %r
nomem(%e: alloc_error):
trap
@@ -0,0 +1,25 @@
; own.new, write through a borrow, own.take: T -> own<T> -> T.
; expect: run
; grant: heap=mem.alloc:64
; result: 43
; phase: 2
; spec: docs/spec/03-memory-model.md
module test.own_roundtrip
air 0
lang 0.1
features [capabilities, effects, heap, ownership, resources]
fn @main(%heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
entry:
%v = const.u64 42
own.new %v, %heap, ok -> @have, err -> @nomem
have(%o: own<u64>):
%m = borrow.mut %o
%w = const.u64 43
store %m, %w
borrow.end %m
%out = own.take %o
ret %out
nomem(%e: alloc_error):
trap
@@ -0,0 +1,214 @@
; File copy with a 64 KiB buffer allocated in a region from a 64 KiB budget.
; expect: run
; grant: src=fs.read:/in
; grant: heap=mem.alloc:65536
; grant: dst=fs.write:/out
; vfs: /in/data.txt=Aji copies files.\n
; result: null
; file: /out/copy.txt=Aji copies files.\n
; phase: 2
; spec: docs/reference/intrinsics.md
module test.region_file_copy
air 0
lang 0.1
features [arrays, capabilities, effects, heap, ownership, regions, resources]
fn @main(%src: cap<fs.read>, %dst: cap<fs.write>, %heap: cap<mem.alloc>) -> void
effects [fs.read, fs.write, mem.alloc]
entry:
%ip = local.alloc array<u8, 12>
local.zero %ip
%ip_m = borrow.mut %ip
%ip_i0 = const.usize 0
%ip_c0 = const.u8 47
%ip_e0 = borrow.index %ip_m, %ip_i0
store %ip_e0, %ip_c0
borrow.end %ip_e0
%ip_i1 = const.usize 1
%ip_c1 = const.u8 105
%ip_e1 = borrow.index %ip_m, %ip_i1
store %ip_e1, %ip_c1
borrow.end %ip_e1
%ip_i2 = const.usize 2
%ip_c2 = const.u8 110
%ip_e2 = borrow.index %ip_m, %ip_i2
store %ip_e2, %ip_c2
borrow.end %ip_e2
%ip_i3 = const.usize 3
%ip_c3 = const.u8 47
%ip_e3 = borrow.index %ip_m, %ip_i3
store %ip_e3, %ip_c3
borrow.end %ip_e3
%ip_i4 = const.usize 4
%ip_c4 = const.u8 100
%ip_e4 = borrow.index %ip_m, %ip_i4
store %ip_e4, %ip_c4
borrow.end %ip_e4
%ip_i5 = const.usize 5
%ip_c5 = const.u8 97
%ip_e5 = borrow.index %ip_m, %ip_i5
store %ip_e5, %ip_c5
borrow.end %ip_e5
%ip_i6 = const.usize 6
%ip_c6 = const.u8 116
%ip_e6 = borrow.index %ip_m, %ip_i6
store %ip_e6, %ip_c6
borrow.end %ip_e6
%ip_i7 = const.usize 7
%ip_c7 = const.u8 97
%ip_e7 = borrow.index %ip_m, %ip_i7
store %ip_e7, %ip_c7
borrow.end %ip_e7
%ip_i8 = const.usize 8
%ip_c8 = const.u8 46
%ip_e8 = borrow.index %ip_m, %ip_i8
store %ip_e8, %ip_c8
borrow.end %ip_e8
%ip_i9 = const.usize 9
%ip_c9 = const.u8 116
%ip_e9 = borrow.index %ip_m, %ip_i9
store %ip_e9, %ip_c9
borrow.end %ip_e9
%ip_i10 = const.usize 10
%ip_c10 = const.u8 120
%ip_e10 = borrow.index %ip_m, %ip_i10
store %ip_e10, %ip_c10
borrow.end %ip_e10
%ip_i11 = const.usize 11
%ip_c11 = const.u8 116
%ip_e11 = borrow.index %ip_m, %ip_i11
store %ip_e11, %ip_c11
borrow.end %ip_e11
borrow.end %ip_m
%ip_r = borrow.ref %ip
%ip_s = slice.make %ip_r
%op = local.alloc array<u8, 13>
local.zero %op
%op_m = borrow.mut %op
%op_i0 = const.usize 0
%op_c0 = const.u8 47
%op_e0 = borrow.index %op_m, %op_i0
store %op_e0, %op_c0
borrow.end %op_e0
%op_i1 = const.usize 1
%op_c1 = const.u8 111
%op_e1 = borrow.index %op_m, %op_i1
store %op_e1, %op_c1
borrow.end %op_e1
%op_i2 = const.usize 2
%op_c2 = const.u8 117
%op_e2 = borrow.index %op_m, %op_i2
store %op_e2, %op_c2
borrow.end %op_e2
%op_i3 = const.usize 3
%op_c3 = const.u8 116
%op_e3 = borrow.index %op_m, %op_i3
store %op_e3, %op_c3
borrow.end %op_e3
%op_i4 = const.usize 4
%op_c4 = const.u8 47
%op_e4 = borrow.index %op_m, %op_i4
store %op_e4, %op_c4
borrow.end %op_e4
%op_i5 = const.usize 5
%op_c5 = const.u8 99
%op_e5 = borrow.index %op_m, %op_i5
store %op_e5, %op_c5
borrow.end %op_e5
%op_i6 = const.usize 6
%op_c6 = const.u8 111
%op_e6 = borrow.index %op_m, %op_i6
store %op_e6, %op_c6
borrow.end %op_e6
%op_i7 = const.usize 7
%op_c7 = const.u8 112
%op_e7 = borrow.index %op_m, %op_i7
store %op_e7, %op_c7
borrow.end %op_e7
%op_i8 = const.usize 8
%op_c8 = const.u8 121
%op_e8 = borrow.index %op_m, %op_i8
store %op_e8, %op_c8
borrow.end %op_e8
%op_i9 = const.usize 9
%op_c9 = const.u8 46
%op_e9 = borrow.index %op_m, %op_i9
store %op_e9, %op_c9
borrow.end %op_e9
%op_i10 = const.usize 10
%op_c10 = const.u8 116
%op_e10 = borrow.index %op_m, %op_i10
store %op_e10, %op_c10
borrow.end %op_e10
%op_i11 = const.usize 11
%op_c11 = const.u8 120
%op_e11 = borrow.index %op_m, %op_i11
store %op_e11, %op_c11
borrow.end %op_e11
%op_i12 = const.usize 12
%op_c12 = const.u8 116
%op_e12 = borrow.index %op_m, %op_i12
store %op_e12, %op_c12
borrow.end %op_e12
borrow.end %op_m
%op_r = borrow.ref %op
%op_s = slice.make %op_r
region.create %heap, ok -> @have_region, err -> @nomem
have_region(%reg: region):
%rb = borrow.ref %reg
%size = const.usize 65536
%zero = const.u8 0
region.array %rb, %size, %zero, ok -> @have_buf, err -> @nomem2
have_buf(%bs: slice_mut<u8>):
intrinsic fs.open_read(%src, %ip_s), ok -> @opened_in, err -> @fail
opened_in(%in: file<read>):
intrinsic fs.create(%dst, %op_s), ok -> @opened_out, err -> @fail_in
opened_out(%out: file<write>):
%fi = borrow.mut %in
%fo = borrow.mut %out
br @loop()
loop:
intrinsic fs.read(%fi, %bs), ok -> @got, err -> @fail_loop
got(%n: usize):
%z = const.usize 0
%eof = eq.usize %n, %z
cbr %eof, @finish(), @write()
write:
%chunk = slice.sub %bs, %z, %n
%cr = borrow.ref %chunk
intrinsic fs.write_all(%fo, %cr), ok -> @wrote, err -> @fail_write
wrote:
borrow.end %cr
borrow.end %chunk
br @loop()
finish:
borrow.end %fo
borrow.end %fi
borrow.end %bs
borrow.end %rb
region.destroy %reg
intrinsic fs.close(%in), ok -> @closed_in, err -> @fail_close_in
closed_in:
intrinsic fs.close(%out), ok -> @done, err -> @fail_close_out
done:
borrow.end %op_s
borrow.end %op_r
borrow.end %ip_s
borrow.end %ip_r
ret
fail(%e: io_error):
trap
nomem(%a1: alloc_error):
trap
nomem2(%a2: alloc_error):
trap
fail_in(%e2: io_error):
trap
fail_loop(%e3: io_error):
trap
fail_write(%e4: io_error):
trap
fail_close_in(%e5: io_error):
trap
fail_close_out(%e6: io_error):
trap
@@ -0,0 +1,38 @@
; Allocate in a region, reset to return the quota, allocate again, destroy.
; expect: run
; grant: heap=mem.alloc:8
; result: 7
; phase: 2
; spec: docs/spec/03-memory-model.md
module test.region_lifecycle
air 0
lang 0.1
features [arrays, capabilities, effects, heap, ownership, regions, resources]
fn @main(%heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
entry:
region.create %heap, ok -> @have, err -> @nomem
have(%r: region):
%rb = borrow.ref %r
%v = const.u64 7
region.new %rb, %v, ok -> @one, err -> @nomem2
one(%p: mut<u64>):
%x = load %p
borrow.end %p
borrow.end %rb
region.reset %r
%rb2 = borrow.ref %r
region.new %rb2, %x, ok -> @two, err -> @nomem3
two(%q: mut<u64>):
%y = load %q
borrow.end %q
borrow.end %rb2
region.destroy %r
ret %y
nomem2(%e2: alloc_error):
trap
nomem3(%e3: alloc_error):
trap
nomem(%e: alloc_error):
trap
@@ -0,0 +1,33 @@
; Ending an allocation borrow does not return region quota: the region still holds the memory.
; expect: run
; grant: heap=mem.alloc:8
; result: 1
; phase: 2
; spec: docs/spec/03-memory-model.md
module test.region_quota_not_returned_on_end
air 0
lang 0.1
features [arrays, capabilities, effects, heap, ownership, regions, resources]
fn @main(%heap: cap<mem.alloc>) -> u8
effects [mem.alloc]
entry:
region.create %heap, ok -> @have, err -> @nomem
have(%r: region):
%rb = borrow.ref %r
%v = const.u64 7
region.new %rb, %v, ok -> @one, err -> @nomem2
one(%p: mut<u64>):
borrow.end %p
region.new %rb, %v, ok -> @two, err -> @full
two(%q: mut<u64>):
trap
full(%e3: alloc_error):
borrow.end %rb
region.destroy %r
%one = const.u8 1
ret %one
nomem2(%e2: alloc_error):
trap
nomem(%e: alloc_error):
trap