Phase 6A: .aji layer 6 (intrinsics, resources, narrowing, unsafe operations)

- intrinsics from the registry as plain calls: fallible ones are outcome
  matches or `or trap` (E7006 otherwise), infallible ones plain calls
- resource operands by name, borrowed mut for the one operation and ended
  on every edge; a mut binding/parameter passes as is; `mut f` is E7006
- closes consume with `move` (E7003); no inserted closes (E3002/E3001)
- data operands explicit (ref/mut/byte string, E7005 otherwise)
- file<…>, stream, listener types; cap.narrow.prefix with cap_error edges
- ref/mut unchecked s[i] (also as a binding) and assume(c) under
  effects [unsafe]; boundary left to the verifier (E6001)
- trusted is reserved and rejected (E7006)
- parameter names preserved; generated names avoid them (normative)
- parser: >> closes two type arguments
- conformance: `equivalent:` compares the run record with a reference
  AIR program (hello, file_copy, tcp_echo, narrow ok/not_subset/invalid,
  random)
- spec 15, grammar, quick reference (io_error match fixed), plan, examples
This commit is contained in:
dev committed 2026-10-05 12:16:54 +03:00
1 parent bdcf871e5d
commit c18fb7acc1
39 files changed
+1309 -69

No files matched your search

+179 -15
View File
@@ -17,7 +17,9 @@
//! 3–4. addressable values (frame storage chosen by lowering), lexical
//! borrows, places, arrays, slices, byte strings;
//! 5. linear values with explicit `move`, `own`, regions, `cap<mem.alloc>`,
//! outcome matches and `or trap`.
//! outcome matches and `or trap`;
//! 6. intrinsics (I/O, files, TCP, clock, random), resources, capability
//! narrowing, unsafe operations.
const std = @import("std");
const ast = @import("ast.zig");
@@ -48,12 +50,14 @@ pub const Ty = union(enum) {
cap: []const u8,
/// A built-in enum (`alloc_error`, `cap_error`, `io_error`).
builtin: authority.Builtin,
/// `file<read|write|append>`, `stream`, `listener`.
resource: authority.Resource,
pub const Arr = struct { elem: Ty, len: u64 };
/// Linear: consumed exactly once, by `move` (spec 15 §5).
fn isLinear(t: Ty) bool {
return t == .own or t == .own_array or t == .region;
return t == .own or t == .own_array or t == .region or t == .resource;
}
fn eql(a: Ty, b: Ty) bool {
@@ -65,6 +69,7 @@ pub const Ty = union(enum) {
.ref, .mut, .slice, .slice_mut, .own, .own_array => |x| x.eql(inner(b).?),
.cap => |k| std.mem.eql(u8, k, b.cap),
.builtin => |e| e == b.builtin,
.resource => |r| r == b.resource,
else => true,
};
}
@@ -220,6 +225,10 @@ const Lowerer = struct {
bindings: std.ArrayList(Binding) = .empty,
loops: std.ArrayList(Loop) = .empty,
counter: u32 = 0,
/// Features found while lowering rather than by scanning the text.
uses: std.EnumSet(UseFeature) = .empty,
/// Set while lowering a `ref unchecked …` place: its index is unchecked.
unchecked: bool = false,
/// The current function's parameter names, which generated names avoid.
params: []const ast.Param = &.{},
ret: Ty = .void,
@@ -259,7 +268,14 @@ const Lowerer = struct {
.ref, .mut, .slice, .slice_mut, .own, .own_array => |x| std.fmt.allocPrint(l.arena, "{s}<{s}>", .{ @tagName(t), l.tyText(x.*) }) catch "borrow",
.region => "region",
.cap => |k| std.fmt.allocPrint(l.arena, "cap<{s}>", .{k}) catch "cap",
.builtin => |b| @tagName(b),
.builtin => |b| blk: {
if (b == .io_error) l.uses.insert(.resources);
break :blk @tagName(b);
},
.resource => |r| blk: {
l.uses.insert(.resources);
break :blk r.text();
},
};
}
@@ -337,6 +353,8 @@ const Lowerer = struct {
/// The features the lowered AIR uses directly; the header is their
/// dependency closure (spec 15 §9). `effects` is always declared.
const UseFeature = enum { capabilities, resources, unsafe };
fn featureRoots(l: *Lowerer, type_lines: []const Inst) Error![]const []const u8 {
var texts: std.ArrayList([]const u8) = .empty;
for (type_lines) |t| try texts.append(l.arena, t.text);
@@ -366,6 +384,8 @@ const Lowerer = struct {
} else false;
if (used) try roots.append(l.arena, r[0]);
}
var it = l.uses.iterator();
while (it.next()) |u| try roots.append(l.arena, @tagName(u));
return roots.items;
}
@@ -418,8 +438,8 @@ const Lowerer = struct {
for (l.m.types, 0..) |d, i| if (std.mem.eql(u8, d.name, n)) return .{ .named = @intCast(i) };
if (std.mem.eql(u8, n, "region")) return .region;
if (std.meta.stringToEnum(authority.Builtin, n)) |b| return .{ .builtin = b };
const later = [_][]const u8{ "listener", "stream" };
for (later) |x| if (std.mem.eql(u8, x, n)) return l.notYet(t.span, "this type (layer 6)");
if (std.mem.eql(u8, n, "stream")) return .{ .resource = .stream };
if (std.mem.eql(u8, n, "listener")) return .{ .resource = .listener };
return l.fail("E7002", t.span, "unknown type", &.{.{ .name = "name", .value = n }});
},
.array => |a| return l.arrayOf(try l.memberType(a.elem.*), a.len),
@@ -440,7 +460,10 @@ const Lowerer = struct {
if (authority.kindIndex(k) == null) return l.fail("E7002", t.span, "unknown capability kind", &.{.{ .name = "kind", .value = k }});
return .{ .cap = k };
},
else => return l.notYet(t.span, "this type (later layers)"),
.file => |m| {
const r: authority.Resource = if (std.mem.eql(u8, m, "read")) .file_read else if (std.mem.eql(u8, m, "write")) .file_write else if (std.mem.eql(u8, m, "append")) .file_append else return l.fail("E7002", t.span, "unknown file mode (read, write, append)", &.{.{ .name = "mode", .value = m }});
return .{ .resource = r };
},
}
}
@@ -460,7 +483,10 @@ const Lowerer = struct {
const sig = l.sigs.get(f.name).?;
l.ret = sig.ret;
if (f.from != null) return l.notYet(f.span, "borrow returns (layer 4)");
if (f.trusted != null) return l.notYet(f.span, "trusted functions (layer 5)");
// `trusted` is the boundary of runtime, std and toolchain modules; an
// ordinary program cannot declare its own code trusted (spec 15 §8).
if (f.trusted != null) return l.fail("E7006", f.span, "`trusted` is not available in .aji programs; unsafe operations need `effects [unsafe]`, which propagates to callers", &.{});
for (f.effects) |e| if (std.mem.eql(u8, e, "unsafe")) l.uses.insert(.unsafe);
var header: std.ArrayList(u8) = .empty;
try header.appendSlice(l.arena, try l.fmt("fn @{s}(", .{f.name}));
@@ -752,7 +778,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 }});
const p = try l.placeBorrow(x.place, x.mutable, true, s.span);
const p = try l.uncheckedPlace(x.place, x.mutable, x.unchecked, s.span);
if (p.ends.len == 0) {
// Borrowing a borrow binding: a reborrow, ended at scope end.
const rb = try l.def(x.name, p.v.ty, try l.fmt("{s} %{s}", .{ if (x.mutable) "borrow.mut" else "borrow.ref", p.v.name }), s.span);
@@ -1205,6 +1231,19 @@ const Lowerer = struct {
try l.emit(try l.fmt("region.reset %{s}", .{r.value}), e.span);
return .{ .name = "", .ty = .void };
}
if (authority.intrinsicIndex(p)) |ix| {
const x = authority.intrinsics[ix];
var temps: std.ArrayList([]const u8) = .empty;
const ops = try l.intrinsicOperands(e, x, args, &temps);
l.uses.insert(.capabilities);
const text = try l.fmt("intrinsic {s}({s})", .{ x.name, ops });
const v: Value = if (x.results.len == 0) blk: {
try l.emit(text, e.span);
break :blk .{ .name = "", .ty = .void };
} else try l.def("r", resultTy(x.results[0]), text, e.span);
try l.endNow(temps.items, e.span);
return v;
}
return l.notYet(callee.span, "this built-in operation (later layers)");
}
if (callee.kind == .field and std.mem.eql(u8, callee.kind.field.name, "split_at"))
@@ -1218,6 +1257,14 @@ const Lowerer = struct {
try l.emit(try l.fmt("assert %{s}", .{v.name}), e.span);
return .{ .name = "", .ty = .void };
}
if (std.mem.eql(u8, name, "assume")) {
if (args.len != 1) return l.fail("E7005", e.span, "`assume` takes one boolean", &.{});
const v = try l.expr(args[0], .bool);
try l.checkTy(args[0].span, v.ty, .bool);
l.uses.insert(.unsafe);
try l.emit(try l.fmt("assume %{s}", .{v.name}), e.span);
return .{ .name = "", .ty = .void };
}
const sig = l.sigs.get(name) orelse return l.unknown(callee.span, name);
if (args.len != sig.params.len) return l.fail("E7005", e.span, "wrong number of arguments", &.{ .{ .name = "function", .value = name }, .{ .name = "expected", .value = try l.fmt("{d}", .{sig.params.len}) }, .{ .name = "found", .value = try l.fmt("{d}", .{args.len}) } });
var arg_names: std.ArrayList(u8) = .empty;
@@ -1546,7 +1593,7 @@ const Lowerer = struct {
fn argument(l: *Lowerer, a: ast.Expr, want: ?Ty, temps: *std.ArrayList([]const u8)) Error!Value {
switch (a.kind) {
.borrow => |x| {
const p = try l.placeBorrow(x.place.*, x.mutable, true, a.span);
const p = try l.uncheckedPlace(x.place.*, x.mutable, x.unchecked, a.span);
if (p.ends.len == 0) {
const rb = try l.def("b", p.v.ty, try l.fmt("{s} %{s}", .{ if (x.mutable) "borrow.mut" else "borrow.ref", p.v.name }), a.span);
try temps.append(l.arena, rb.name);
@@ -1575,6 +1622,17 @@ const Lowerer = struct {
return l.expr(e, want);
}
/// `ref unchecked s[i]`: `borrow.index.unchecked` (spec 13 §6). Only an
/// element place can be unchecked; the boundary (`effects [unsafe]`) is
/// the verifier's (`E6001`).
fn uncheckedPlace(l: *Lowerer, place: ast.Expr, mutable: bool, unchecked: bool, span: Span) Error!Placed {
if (!unchecked) return l.placeBorrow(place, mutable, true, span);
if (place.kind != .index or place.kind.index.hi != null) return l.fail("E7006", place.span, "`unchecked` applies to one element `s[i]`", &.{});
l.unchecked = true;
defer l.unchecked = false;
return l.placeBorrow(place, mutable, true, span);
}
fn rootBinding(l: *Lowerer, e: ast.Expr) ?*Binding {
var x = e;
while (true) switch (x.kind) {
@@ -1619,6 +1677,7 @@ const Lowerer = struct {
.own => |in| if (mutable) try l.wrap(.mut, in.*) else try l.wrap(.ref, in.*),
.own_array => |in| if (mutable) try l.wrap(.slice_mut, in.*) else try l.wrap(.slice, in.*),
.region => if (mutable) try l.wrap(.mut, .region) else try l.wrap(.ref, .region),
.resource => if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty),
else => null,
};
const t = bt orelse return l.fail("E7006", place.span, "this value is not addressable here; borrow a variable, a field or an element", &.{.{ .name = "name", .value = n }});
@@ -1650,7 +1709,10 @@ const Lowerer = struct {
return .{ .v = v, .ends = try l.concat(base.ends, v.name) };
},
.index => |x| {
const outer_unchecked = l.unchecked;
l.unchecked = false;
const base = try l.placeRaw(x.e.*, mutable, span);
l.unchecked = outer_unchecked;
const bt = base.v.ty;
const elem = elemOf(bt) orelse return l.fail("E7005", place.span, "indexing needs an array or a slice", &.{.{ .name = "found", .value = l.tyText(bt) }});
if (x.hi) |hi| {
@@ -1669,12 +1731,17 @@ const Lowerer = struct {
const sub_ = try l.def("s", sl.ty, try l.fmt("slice.sub %{s}, %{s}, %{s}", .{ sl.name, a.name, len.name }), span);
return .{ .v = sub_, .ends = try l.concat(ends, sub_.name) };
}
// Only the outermost index of an unchecked place is unchecked.
const unchecked = l.unchecked;
l.unchecked = false;
const i = try l.expr(x.lo.*, .{ .int = "usize" });
try l.checkTy(x.lo.span, i.ty, .{ .int = "usize" });
const proven = for (l.facts.items) |f| {
if (std.mem.eql(u8, f.index, i.name) and std.mem.eql(u8, f.slice, base.v.name)) break true;
} else false;
const v = try l.def("e", if (bt.isMutBorrow()) try l.wrap(.mut, elem) else try l.wrap(.ref, elem), try l.fmt("{s} %{s}, %{s}", .{ if (proven) "borrow.index.proven" else "borrow.index", base.v.name, i.name }), span);
if (unchecked) l.uses.insert(.unsafe);
const index_op = if (unchecked) "borrow.index.unchecked" else if (proven) "borrow.index.proven" else "borrow.index";
const v = try l.def("e", if (bt.isMutBorrow()) try l.wrap(.mut, elem) else try l.wrap(.ref, elem), try l.fmt("{s} %{s}, %{s}", .{ index_op, base.v.name, i.name }), span);
return .{ .v = v, .ends = try l.concat(base.ends, v.name) };
},
else => return l.fail("E7006", place.span, "not a place: borrow a variable, a field `x.f`, an element `s[i]` or a range `s[a..b]`", &.{}),
@@ -1858,15 +1925,82 @@ const Lowerer = struct {
/// A lowered fallible operation: its AIR text before the targets and its
/// outcomes in AIR order.
const Fallible = struct { text: []const u8, outcomes: []const Outcome };
/// `temps`: borrows made for the operation, ended at the start of every
/// outcome block.
const Fallible = struct { text: []const u8, outcomes: []const Outcome, temps: []const []const u8 = &.{} };
fn fallible(l: *Lowerer, path: []const u8) ?void {
_ = l;
const ops = [_][]const u8{ "own.new", "own.array", "region.create", "region.new", "region.array", "cap.narrow.budget" };
const ops = [_][]const u8{ "own.new", "own.array", "region.create", "region.new", "region.array", "cap.narrow.budget", "cap.narrow.prefix" };
for (ops) |o| if (std.mem.eql(u8, o, path)) return {};
if (authority.intrinsicIndex(path)) |i| if (authority.intrinsics[i].fallible) return {};
return null;
}
fn resultTy(r: authority.ResultType) Ty {
return switch (r) {
.usize => .{ .int = "usize" },
.u64 => .{ .int = "u64" },
.resource => |x| .{ .resource = x },
};
}
/// Operands of an intrinsic in registry order (`reference/intrinsics.md`).
/// A capability is passed plainly; a resource operand that is borrowed
/// is named and borrowed for the operation; a consumed one is `move`d;
/// data borrows are written (`ref`/`mut`, or a byte string).
fn intrinsicOperands(l: *Lowerer, e: ast.Expr, x: authority.Intrinsic, args: []const ast.Expr, temps: *std.ArrayList([]const u8)) Error![]const u8 {
if (args.len != x.operands.len) return l.fail("E7005", e.span, "wrong number of operands", &.{ .{ .name = "operation", .value = x.name }, .{ .name = "expected", .value = try l.fmt("{d}", .{x.operands.len}) } });
var text: std.ArrayList(u8) = .empty;
for (x.operands, args, 0..) |o, a, i| {
const v: Value = switch (o) {
.cap => |k| try l.expectCap(a, k),
.bytes, .buffer => blk: {
const want: Ty = if (o == .bytes) try l.wrap(.slice, .{ .int = "u8" }) else try l.wrap(.slice_mut, .{ .int = "u8" });
if (o == .buffer and a.kind == .bytes) return l.fail("E7005", a.span, "this operand is a buffer the operation writes: pass `mut buf`", &.{});
const v = try l.argument(a, want, temps);
if (!v.ty.eql(want)) return l.fail("E7005", a.span, if (o == .bytes) "bytes are passed as a borrow: `ref buf`, `ref buf[a..b]` or a byte string `b\"…\"`" else "a buffer is passed as `mut buf` or `mut buf[a..b]`", &.{ .{ .name = "expected", .value = l.tyText(want) }, .{ .name = "found", .value = l.tyText(v.ty) } });
break :blk v;
},
.borrowed => |rs| try l.resourceOperand(a, rs, temps),
.consumed => |rs| blk: {
const v = try l.consuming(a, null);
if (v.ty != .resource or std.mem.indexOfScalar(authority.Resource, rs, v.ty.resource) == null)
return l.fail("E7005", a.span, "this operation consumes a resource of another type", &.{ .{ .name = "operation", .value = x.name }, .{ .name = "found", .value = l.tyText(v.ty) } });
break :blk v;
},
};
try text.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", v.name }));
}
return text.items;
}
/// A resource operand the operation borrows: the resource by name
/// (borrowed `mut` for the operation) or a `mut` borrow binding of one.
fn resourceOperand(l: *Lowerer, a: ast.Expr, rs: []const authority.Resource, temps: *std.ArrayList([]const u8)) Error!Value {
const expected = try l.resourceList(rs);
if (a.kind == .borrow) return l.fail("E7006", a.span, "a resource operand is written by name; the operation borrows it", &.{.{ .name = "expected", .value = expected }});
if (a.kind != .name) return l.fail("E7005", a.span, "a resource is expected here, by name", &.{.{ .name = "expected", .value = expected }});
const b = l.lookup(a.kind.name) orelse return l.unknown(a.span, a.kind.name);
const r: ?authority.Resource = switch (b.ty) {
.resource => |r| r,
.mut => |in| if (in.* == .resource) in.resource else null,
else => null,
};
if (r == null or std.mem.indexOfScalar(authority.Resource, rs, r.?) == null)
return l.fail("E7005", a.span, "this operation needs a resource of another type", &.{ .{ .name = "expected", .value = expected }, .{ .name = "found", .value = l.tyText(b.ty) } });
if (b.ty == .mut) return .{ .name = b.value, .ty = b.ty };
const v = try l.def(a.kind.name, try l.wrap(.mut, b.ty), try l.fmt("borrow.mut %{s}", .{b.value}), a.span);
try temps.append(l.arena, v.name);
return v;
}
fn resourceList(l: *Lowerer, rs: []const authority.Resource) Error![]const u8 {
var out: std.ArrayList(u8) = .empty;
for (rs, 0..) |r, i| try out.appendSlice(l.arena, try l.fmt("{s}{s}", .{ if (i == 0) "" else " or ", r.text() }));
return out.items;
}
fn expectCap(l: *Lowerer, a: ast.Expr, kind: []const u8) Error!Value {
const c = try l.expr(a, null);
if (c.ty != .cap) return l.fail("E7005", a.span, "a capability is expected here", &.{ .{ .name = "expected", .value = try l.fmt("cap<{s}>", .{kind}) }, .{ .name = "found", .value = l.tyText(c.ty) } });
@@ -1928,6 +2062,30 @@ const Lowerer = struct {
const v = try l.consuming(args[2], null);
return .{ .text = try l.fmt("region.array %{s}, %{s}, %{s}", .{ rb.name, n.name, v.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{try l.wrap(.slice_mut, v.ty)} }, .{ .role = "err", .params = &.{alloc_err} } }) };
}
if (authority.intrinsicIndex(path)) |ix| {
const x = authority.intrinsics[ix];
if (!x.fallible) return l.fail("E7006", e.span, "this intrinsic cannot fail: call it plainly", &.{.{ .name = "operation", .value = x.name }});
var temps: std.ArrayList([]const u8) = .empty;
const ops = try l.intrinsicOperands(e, x, args, &temps);
l.uses.insert(.capabilities);
const ok = try l.arena.alloc(Ty, x.results.len);
for (x.results, ok) |r, *t| t.* = resultTy(r);
return .{
.text = try l.fmt("intrinsic {s}({s})", .{ x.name, ops }),
.outcomes = try l.outs(&.{ .{ .role = "ok", .params = ok }, .{ .role = "err", .params = &.{.{ .builtin = .io_error }} } }),
.temps = temps.items,
};
}
if (std.mem.eql(u8, path, "cap.narrow.prefix")) {
try want(l, e.span, args, 2, path);
const c = try l.expr(args[0], null);
if (c.ty != .cap) return l.fail("E7005", args[0].span, "a capability is expected here", &.{.{ .name = "found", .value = l.tyText(c.ty) }});
var temps: std.ArrayList([]const u8) = .empty;
const bytes = try l.wrap(.slice, .{ .int = "u8" });
const p = try l.argument(args[1], bytes, &temps);
if (!p.ty.eql(bytes)) return l.fail("E7005", args[1].span, "the path is a byte string or a `ref` borrow of bytes", &.{.{ .name = "found", .value = l.tyText(p.ty) }});
return .{ .text = try l.fmt("cap.narrow.prefix %{s}, %{s}", .{ c.name, p.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{c.ty} }, .{ .role = "err", .params = &.{.{ .builtin = .cap_error }} } }), .temps = temps.items };
}
if (std.mem.eql(u8, path, "cap.narrow.budget")) {
try want(l, e.span, args, 2, path);
const c = try l.expr(args[0], null);
@@ -1957,6 +2115,11 @@ const Lowerer = struct {
try text.appendSlice(l.arena, try l.fmt(", {s} -> @{s}", .{ o.role, l.blocks.items[b.*].name }));
}
try l.term(text.items, span);
// The operation's temporary borrows end on every edge.
for (blocks) |b| {
l.cur = b;
try l.endNow(f.temps, span);
}
return blocks;
}
@@ -2095,13 +2258,14 @@ fn elemOf(t: Ty) ?Ty {
/// `cap.narrow.budget`; null for anything else.
fn pathOf(e: ast.Expr) ?[]const u8 {
const known = [_][]const u8{
"slice.copy", "own.new", "own.array", "own.take", "own.free",
"region.create", "region.new", "region.array", "region.reset", "region.destroy",
"cap.narrow.budget",
"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",
};
var buf: [64]u8 = undefined;
const text = dotted(e, &buf) orelse return null;
for (known) |k| if (std.mem.eql(u8, k, text)) return k;
if (authority.intrinsicIndex(text)) |i| return authority.intrinsics[i].name;
return null;
}