cli: add initialized buffers and safe owning vectors

Introduce linear_buffers through the specification, AIR parser/serializer,
verifier, deterministic interpreter and source lowering. A buffer owns an
initialized prefix with explicit reserve, bounded push, moving pop/views and
recoverable empty-only free. Growth charges old+new capacity; failed growth,
full push and nonempty free preserve or return complete ownership.

Implement compiler-pinned safe std.vec with nine operations for Copy values,
owners, files and channel endpoints. Permit complete Copy moves inside
specialized generic bodies without weakening monomorphic or borrow rules.
Update RFC 0024, Q-036, STD-6a/b, reference grammar, Quick Reference, bundles,
source coverage and CI. Remaining collections stay STD-6c.

Validation: unit tests and AIR round-trip; 757 conformance cases; 56 dedicated
buffer cases with per-instruction collection and 32-seed schedule stress;
extended memory test; hosted smoke; 36 module, 20 generic, 49 linear and
118 buffer CLI checks; 91/91 source constructs; Zig fmt and reference bundles.
Full source bundle: 49,589 -> 52,384 cl100k tokens (+5.6%); AIR 175,736 bytes.
The reference interpreter's push copies its initialized prefix; no native
performance or empirical MCC benefit is claimed.
This commit is contained in:
dev committed 2026-10-06 23:26:41 +03:00
1 parent 4f084decce
commit 4138a52af6
101 files changed
+2377 -71

No files matched your search

+91 -25
View File
@@ -50,6 +50,7 @@ pub const Ty = union(enum) {
slice_mut: *const Ty,
own: *const Ty,
own_array: *const Ty,
buffer: *const Ty,
region,
/// `cap<K>`: the kind.
cap: []const u8,
@@ -81,7 +82,7 @@ pub const Ty = union(enum) {
/// Linear: consumed exactly once, by `move` (spec 15 §5).
fn isLinear(t: Ty) bool {
return switch (t) {
.own, .own_array, .region, .resource, .task, .sender, .receiver, .scope, .mutex, .guard, .shield, .island, .frozen, .arc, .atomic => true,
.own, .own_array, .buffer, .region, .resource, .task, .sender, .receiver, .scope, .mutex, .guard, .shield, .island, .frozen, .arc, .atomic => true,
else => false,
};
}
@@ -92,7 +93,7 @@ pub const Ty = union(enum) {
.int => |x| std.mem.eql(u8, x, b.int),
.named => |i| i == b.named,
.array => |x| x.len == b.array.len and x.elem.eql(b.array.elem),
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| x.eql(inner(b).?),
.ref, .mut, .slice, .slice_mut, .own, .own_array, .buffer, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| x.eql(inner(b).?),
.cap => |k| std.mem.eql(u8, k, b.cap),
.builtin => |e| e == b.builtin,
.resource => |r| r == b.resource,
@@ -102,7 +103,7 @@ pub const Ty = union(enum) {
fn inner(t: Ty) ?Ty {
return switch (t) {
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| x.*,
.ref, .mut, .slice, .slice_mut, .own, .own_array, .buffer, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| x.*,
.array => |a| a.elem,
else => null,
};
@@ -379,7 +380,7 @@ const Lowerer = struct {
.never => "never",
.named => |i| if (source_names and l.m.types[i].air_name != null) (l.m.types[i].display_name orelse l.m.types[i].name) else l.typeNames[i],
.array => |a| std.fmt.allocPrint(l.arena, "array<{s}, {d}>", .{ l.typeText(a.elem, source_names), a.len }) catch "array",
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| std.fmt.allocPrint(l.arena, "{s}<{s}>", .{ @tagName(t), l.typeText(x.*, source_names) }) catch "borrow",
.ref, .mut, .slice, .slice_mut, .own, .own_array, .buffer, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| std.fmt.allocPrint(l.arena, "{s}<{s}>", .{ @tagName(t), l.typeText(x.*, source_names) }) catch "borrow",
.scope => "scope",
.shield => "shield",
.region => "region",
@@ -487,7 +488,7 @@ const Lowerer = struct {
out.* = .{ .elem = try l.airType(a.elem), .len = a.len };
break :blk .{ .array = out };
},
inline .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |inner, tag| blk: {
inline .ref, .mut, .slice, .slice_mut, .own, .own_array, .buffer, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |inner, tag| blk: {
const out = try l.arena.create(air_module.Type);
out.* = try l.airType(inner.*);
break :blk @unionInit(air_module.Type, @tagName(tag), out);
@@ -579,6 +580,7 @@ const Lowerer = struct {
const rules = [_]Rule{
.{ "arrays", &.{ "array<", "slice", "array.splat", "borrow.index" } },
.{ "ownership", &.{ "local.", "borrow.", " load ", "= load ", "store ", "ref<", "mut<" } },
.{ "linear_buffers", &.{ "buffer<", "buffer." } },
.{ "linear_aggregates", &.{ "array.make ", "struct.unpack ", "array.unpack ", "enum.take ", "value.swap ", "own.pack " } },
.{ "heap", &.{ "own.", "own<", "own_array<", "alloc_error" } },
.{ "regions", &.{"region"} },
@@ -663,7 +665,7 @@ const Lowerer = struct {
},
.array => |a| return l.arrayOf(try l.memberType(a.elem.*), a.len),
.wrapped => |w| {
const Wr = enum { ref, mut, slice, slice_mut, own, own_array, task, sender, receiver, mutex, island, frozen, arc, iref, atomic };
const Wr = enum { ref, mut, slice, slice_mut, own, own_array, buffer, task, sender, receiver, mutex, island, frozen, arc, iref, atomic };
const which = std.meta.stringToEnum(Wr, w.wrapper) orelse return l.notYet(t.span, "this type (later layers)");
const in = try l.typeOf(w.inner.*);
return switch (which) {
@@ -673,6 +675,7 @@ const Lowerer = struct {
.slice_mut => l.wrap(.slice_mut, in),
.own => l.wrap(.own, in),
.own_array => l.wrap(.own_array, in),
.buffer => l.wrap(.buffer, in),
.task => l.wrap(.task, in),
.sender => l.wrap(.sender, in),
.receiver => l.wrap(.receiver, in),
@@ -1082,6 +1085,7 @@ const Lowerer = struct {
const scope_start = l.scopeBindingStart();
for (l.bindings.items[scope_start..]) |b| if (b.kind == .borrow and std.mem.eql(u8, b.name, x.name))
return l.fail("E7006", s.span, "a borrow of this name is already active in this scope", &.{.{ .name = "name", .value = x.name }});
if (x.place.kind == .call) if (pathOf(x.place.kind.call.callee.*)) |p| if (std.mem.eql(u8, p, "buffer.view")) return l.bufferView(s, x.name, x.mutable, x.place);
if (x.place.kind == .call) if (pathOf(x.place.kind.call.callee.*)) |p| if (std.mem.endsWith(u8, p, ".at"))
return l.graphAccess(s, x.name, x.mutable, x.place);
const p = try l.uncheckedPlace(x.place, x.mutable, x.unchecked, s.span);
@@ -1528,7 +1532,8 @@ const Lowerer = struct {
.or_trap => |x| return l.orTrap(e, x.*),
.move => |n| {
const b = l.lookup(n) orelse return l.unknown(e.span, n);
if (!l.isLinear(b.ty)) return l.fail("E7006", e.span, "`move` applies to linear values; copyable values are passed plainly", &.{ .{ .name = "name", .value = n }, .{ .name = "type", .value = l.diagnosticTyText(b.ty) } });
if (!l.isLinear(b.ty) and !(e.generic_transfer and b.ty != .void and b.ty != .never and !b.ty.isBorrow() and b.ty != .task and b.ty != .scope and b.ty != .guard and b.ty != .shield)) return l.fail("E7006", e.span, "`move` applies to linear values; copyable values are passed plainly", &.{ .{ .name = "name", .value = n }, .{ .name = "type", .value = l.diagnosticTyText(b.ty) } });
if (b.kind == .storage) return l.def(n, b.ty, try l.fmt("local.load %{s}", .{b.value}), e.span);
return .{ .name = b.value, .ty = b.ty };
},
}
@@ -1607,6 +1612,14 @@ const Lowerer = struct {
}
fn call(l: *Lowerer, e: ast.Expr, callee: ast.Expr, args: []const ast.Expr) Error!Value {
if (pathOf(callee)) |p| {
if (std.mem.eql(u8, p, "buffer.len") or std.mem.eql(u8, p, "buffer.capacity")) {
if (args.len != 1) return l.fail("E7005", e.span, "buffer metadata read takes one named borrow", &.{});
const b = try l.bufferBorrow(args[0], false);
return l.def("size", .{ .int = "usize" }, try l.fmt("{s} %{s}", .{ p, b.name }), e.span);
}
if (std.mem.eql(u8, p, "buffer.view")) return l.fail("E7006", e.span, "bind a buffer view with ref/mut name = buffer.view(borrow)", &.{});
}
if (pathOf(callee)) |path| if (std.mem.eql(u8, path, "value.swap")) {
if (args.len != 2 or args[0].kind != .borrow or !args[0].kind.borrow.mutable) return l.fail("E7006", e.span, "value.swap requires mut place and replacement", &.{});
const b = args[0].kind.borrow;
@@ -1956,6 +1969,7 @@ const Lowerer = struct {
/// without lowering it.
fn peekPath(l: *Lowerer, p: []const u8, args: []const ast.Expr) ?Ty {
const eq = std.mem.eql;
if (eq(u8, p, "buffer.len") or eq(u8, p, "buffer.capacity")) return .{ .int = "usize" };
if ((eq(u8, p, "own.take") or eq(u8, p, "task.join")) and args.len == 1) return if (l.peekType(args[0])) |t| t.inner() else null;
if (eq(u8, p, "task.cancelled")) return .bool;
if (std.mem.startsWith(u8, p, "atomic.") and args.len >= 1) {
@@ -2139,6 +2153,7 @@ const Lowerer = struct {
.named, .array => if (l.isLinear(b.ty)) (if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty)) else null,
.own => |in| if (mutable) try l.wrap(.mut, in.*) else try l.wrap(.ref, in.*),
.own_array => |in| if (mutable) try l.wrap(.slice_mut, in.*) else try l.wrap(.slice, in.*),
.buffer => if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty),
.region => if (mutable) try l.wrap(.mut, .region) else try l.wrap(.ref, .region),
.resource, .mutex, .sender, .receiver, .task, .island => if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty),
.frozen, .arc => if (mutable) return l.fail("E7005", place.span, "frozen graphs and arcs are immutable: borrow them with `ref`", &.{.{ .name = "name", .value = n }}) else try l.wrap(.ref, b.ty),
@@ -2425,7 +2440,7 @@ const Lowerer = struct {
fn fallible(l: *Lowerer, path: []const u8) ?void {
_ = l;
const ops = [_][]const u8{ "own.new", "own.pack", "own.array", "region.create", "region.new", "region.array", "cap.narrow.budget", "cap.narrow.prefix", "channel.make", "channel.send", "channel.recv", "channel.close_receiver", "task.check_cancel", "task.join_cancel", "island.create", "island.alloc", "arc.new" };
const ops = [_][]const u8{ "buffer.new", "buffer.reserve", "buffer.push", "buffer.pop", "buffer.free", "own.new", "own.pack", "own.array", "region.create", "region.new", "region.array", "cap.narrow.budget", "cap.narrow.prefix", "channel.make", "channel.send", "channel.recv", "channel.close_receiver", "task.check_cancel", "task.join_cancel", "island.create", "island.alloc", "arc.new" };
for (ops) |o| if (std.mem.eql(u8, o, path)) return {};
if (authority.intrinsicIndex(path)) |i| if (authority.intrinsics[i].fallible) return {};
return null;
@@ -2860,7 +2875,7 @@ const Lowerer = struct {
return switch (t) {
.ref, .mut, .slice, .slice_mut, .scope, .task, .shield, .guard => t,
.array => |a| l.forbiddenIn(a.elem, depth + 1),
.own, .own_array, .mutex => |x| l.forbiddenIn(x.*, depth + 1),
.own, .own_array, .buffer, .mutex => |x| l.forbiddenIn(x.*, depth + 1),
.named => |i| blk: {
const d = l.m.types[i];
switch (d.kind) {
@@ -2886,8 +2901,33 @@ const Lowerer = struct {
return .{ .name = b.value, .ty = b.ty };
}
/// `ref x = island.at(g, r);` / `mut x = island.at(g, r);`, and
/// `frozen.at`, `arc.at` (`ref` only): a child borrow of `g`.
/// Buffer operations require an explicit named borrow of the handle.
fn bufferBorrow(l: *Lowerer, e: ast.Expr, mutable: bool) Error!Value {
if (e.kind == .name) if (l.lookup(e.kind.name)) |b| {
if ((b.ty == .mut or (!mutable and b.ty == .ref)) and b.ty.inner().? == .buffer) return .{ .name = b.value, .ty = b.ty };
};
return l.fail("E7005", e.span, if (mutable) "bind a named mut<buffer<T>> first" else "bind a named ref/mut<buffer<T>> first", &.{});
}
fn bufferView(l: *Lowerer, s: ast.Stmt, name_: []const u8, mutable: bool, place: ast.Expr) Error!void {
const args = place.kind.call.args;
if (args.len != 1) return l.fail("E7005", place.span, "buffer.view takes one named buffer borrow", &.{});
const parent = try l.bufferBorrow(args[0], mutable);
// A shared view from a mutable parent uses an explicit shared reborrow.
var borrow = parent;
var shared_end: ?[]const u8 = null;
if (!mutable and parent.ty == .mut) {
borrow = try l.def("buffer_ref", try l.wrap(.ref, parent.ty.inner().?), try l.fmt("borrow.ref %{s}", .{parent.name}), place.span);
shared_end = borrow.name;
}
const ty = if (mutable) try l.wrap(.slice_mut, parent.ty.inner().?.buffer.*) else try l.wrap(.slice, parent.ty.inner().?.buffer.*);
const view = try l.def(name_, ty, try l.fmt("buffer.view %{s}", .{borrow.name}), place.span);
if (shared_end) |n| try l.scopeEnds(&.{n}, s.span);
try l.scopeEnds(&.{view.name}, s.span);
try l.bindings.append(l.arena, .{ .name = name_, .mutable = false, .value = view.name, .ty = ty, .kind = .borrow });
}
/// Graph access binds a child borrow of its named graph borrow.
fn graphAccess(l: *Lowerer, s: ast.Stmt, name: []const u8, mutable: bool, place: ast.Expr) Error!void {
const ac = place.kind.call;
const p = pathOf(ac.callee.*).?;
@@ -2996,6 +3036,38 @@ const Lowerer = struct {
}.n;
const alloc_err: Ty = .{ .builtin = .alloc_error };
const usize_ty: Ty = .{ .int = "usize" };
if (std.mem.eql(u8, path, "buffer.new")) {
try want(l, e.span, args, 2, path);
const source_ty = e.kind.call.type_arg orelse return l.fail("E7005", e.span, "buffer.new needs an explicit content type", &.{});
const ty = try l.typeOf(source_ty);
const n = try l.expr(args[0], usize_ty);
try l.checkTy(args[0].span, n.ty, usize_ty);
const cap = try l.expectCap(args[1], "mem.alloc");
return .{ .text = try l.fmt("buffer.new {s} %{s}, %{s}", .{ l.tyText(ty), n.name, cap.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{try l.wrap(.buffer, ty)} }, .{ .role = "err", .params = &.{alloc_err} } }) };
}
if (std.mem.eql(u8, path, "buffer.free")) {
try want(l, e.span, args, 1, path);
const v = try l.consuming(args[0], null);
if (v.ty != .buffer) return l.fail("E7005", e.span, "buffer.free consumes a buffer<T>", &.{});
return .{ .text = try l.fmt("buffer.free %{s}", .{v.name}), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{} }, .{ .role = "err", .params = &.{v.ty} } }) };
}
if (std.mem.eql(u8, path, "buffer.push") or std.mem.eql(u8, path, "buffer.pop") or std.mem.eql(u8, path, "buffer.reserve")) {
const is_push = std.mem.eql(u8, path, "buffer.push");
const is_pop = std.mem.eql(u8, path, "buffer.pop");
try want(l, e.span, args, if (is_push) 2 else if (is_pop) 1 else 3, path);
const b = try l.bufferBorrow(args[0], true);
const ty = b.ty.inner().?.buffer.*;
if (is_push) {
const v = try l.consuming(args[1], ty);
try l.checkTy(args[1].span, v.ty, ty);
return .{ .text = try l.fmt("buffer.push %{s}, %{s}", .{ b.name, v.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{} }, .{ .role = "err", .params = &.{ty} } }) };
}
if (is_pop) return .{ .text = try l.fmt("buffer.pop %{s}", .{b.name}), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{ty} }, .{ .role = "err", .params = &.{} } }) };
const n = try l.expr(args[1], usize_ty);
try l.checkTy(args[1].span, n.ty, usize_ty);
const cap = try l.expectCap(args[2], "mem.alloc");
return .{ .text = try l.fmt("buffer.reserve %{s}, %{s}, %{s}", .{ b.name, n.name, cap.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{} }, .{ .role = "err", .params = &.{alloc_err} } }) };
}
if (std.mem.eql(u8, path, "own.pack")) {
try want(l, e.span, args, 2, path);
const v = try l.consuming(args[0], null);
@@ -3296,20 +3368,14 @@ fn elemOf(t: Ty) ?Ty {
/// `cap.narrow.budget`; null for anything else.
fn pathOf(e: ast.Expr) ?[]const u8 {
const known = [_][]const u8{
"struct.unpack", "array.unpack", "value.swap", "own.pack",
"slice.copy", "own.new", "own.array", "own.take",
"own.free", "region.create", "region.new", "region.array",
"region.reset", "region.destroy", "cap.narrow.budget", "cap.narrow.prefix",
"task.spawn", "task.join", "task.cancel", "task.cancelled",
"channel.make", "channel.dup", "channel.send", "channel.recv",
"channel.close_sender", "channel.close_receiver", "mutex.make", "mutex.take",
"task.check_cancel", "task.join_cancel", "island.create", "island.alloc",
"island.root", "island.at", "island.freeze", "island.destroy",
"frozen.root", "frozen.at", "frozen.release", "arc.from_frozen",
"arc.new", "arc.clone", "arc.release", "arc.root",
"arc.at", "atomic.new", "atomic.take", "atomic.load",
"atomic.store", "atomic.swap", "atomic.add.wrap", "atomic.sub.wrap",
"atomic.and", "atomic.or", "atomic.xor", "atomic.compare_exchange",
"buffer.new", "buffer.len", "buffer.capacity", "buffer.reserve", "buffer.push", "buffer.pop", "buffer.view", "buffer.free",
"struct.unpack", "array.unpack", "value.swap", "own.pack", "slice.copy", "own.new", "own.array", "own.take",
"own.free", "region.create", "region.new", "region.array", "region.reset", "region.destroy", "cap.narrow.budget", "cap.narrow.prefix",
"task.spawn", "task.join", "task.cancel", "task.cancelled", "channel.make", "channel.dup", "channel.send", "channel.recv",
"channel.close_sender", "channel.close_receiver", "mutex.make", "mutex.take", "task.check_cancel", "task.join_cancel", "island.create", "island.alloc",
"island.root", "island.at", "island.freeze", "island.destroy", "frozen.root", "frozen.at", "frozen.release", "arc.from_frozen",
"arc.new", "arc.clone", "arc.release", "arc.root", "arc.at", "atomic.new", "atomic.take", "atomic.load",
"atomic.store", "atomic.swap", "atomic.add.wrap", "atomic.sub.wrap", "atomic.and", "atomic.or", "atomic.xor", "atomic.compare_exchange",
"atomic.fence",
};
var buf: [64]u8 = undefined;