Phase 2: I/O intrinsics, linear resources, deterministic profile (RFC 0007)
- air: resource types file<read|write|append>, listener, stream; io_error; intrinsic registry (19 intrinsics) synced with reference/intrinsics.md; fallible intrinsics as ok/err terminators; fs prefix narrowing; linear_aggregates gating - verifier: intrinsic form, operand, result and capability-kind checks (E1001, E3201, E5002); intrinsic effects (E3101); resource linearity in the borrow walker with per-edge moves: E3002 leaks and join mismatches, E3001, E2001, E2002, E2101 for close while borrowed; resources as borrow roots - interp: deterministic world (captured console, VFS, loopback TCP, instruction clock, pinned xoshiro256 PRNG), blocked outcome, run record with stdout/stderr/files - CLI: --stdin, --vfs, --seed, --result-file, --profile (hosted: exit 3), exit code 7; runner: stdin/vfs/seed/stdout/stderr/file/blocked headers - conformance: hello, file copy and TCP echo exit programs; 37 new tests; 4000 mutants without a crash
This commit is contained in:
1 parent
571cc6e362
commit
d405d4ea50
49 files changed
+2325
-81
No files matched your search
+120
-2
@@ -45,8 +45,8 @@ pub const Kind = struct {
|
||||
|
||||
pub const kinds = [_]Kind{
|
||||
.{ .name = "clock.read", .scope = .none, .forms = &.{} },
|
||||
.{ .name = "fs.read", .scope = .path_prefix, .forms = &.{} },
|
||||
.{ .name = "fs.write", .scope = .path_prefix, .forms = &.{} },
|
||||
.{ .name = "fs.read", .scope = .path_prefix, .forms = &.{"prefix"} },
|
||||
.{ .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 = &.{} },
|
||||
@@ -63,10 +63,20 @@ pub const kinds = [_]Kind{
|
||||
/// Built-in enums: spelled without `@`, fixed variants, no payloads.
|
||||
pub const Builtin = enum {
|
||||
cap_error,
|
||||
io_error,
|
||||
|
||||
pub fn variants(b: Builtin) []const []const u8 {
|
||||
return switch (b) {
|
||||
.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" },
|
||||
};
|
||||
}
|
||||
|
||||
/// Feature a built-in enum belongs to.
|
||||
pub fn feature(b: Builtin) []const u8 {
|
||||
return switch (b) {
|
||||
.cap_error => "capabilities",
|
||||
.io_error => "resources",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -111,6 +121,94 @@ pub fn validScope(kind: u16, scope: ?[]const u8) bool {
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- intrinsics (reference/intrinsics.md)
|
||||
|
||||
/// Linear resource types (spec 06 §6).
|
||||
pub const Resource = enum {
|
||||
file_read,
|
||||
file_write,
|
||||
file_append,
|
||||
listener,
|
||||
stream,
|
||||
|
||||
pub fn text(r: Resource) []const u8 {
|
||||
return switch (r) {
|
||||
.file_read => "file<read>",
|
||||
.file_write => "file<write>",
|
||||
.file_append => "file<append>",
|
||||
.listener => "listener",
|
||||
.stream => "stream",
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
/// Shape of an intrinsic operand.
|
||||
pub const Operand = union(enum) {
|
||||
/// `cap<kind>`.
|
||||
cap: []const u8,
|
||||
/// `slice<u8>` (read).
|
||||
bytes,
|
||||
/// `slice_mut<u8>` (written).
|
||||
buffer,
|
||||
/// `mut<R>` for one of the listed resources; not consumed.
|
||||
borrowed: []const Resource,
|
||||
/// A resource of one of the listed types, consumed on both edges.
|
||||
consumed: []const Resource,
|
||||
};
|
||||
|
||||
pub const ResultType = union(enum) {
|
||||
usize,
|
||||
u64,
|
||||
resource: Resource,
|
||||
};
|
||||
|
||||
pub const Intrinsic = struct {
|
||||
name: []const u8,
|
||||
operands: []const Operand,
|
||||
/// Fallible: results are `@ok` parameters and `@err` gets an `io_error`.
|
||||
/// Infallible: at most one result, bound with `%r =`.
|
||||
fallible: bool,
|
||||
results: []const ResultType,
|
||||
effect: ?[]const u8,
|
||||
};
|
||||
|
||||
const files_w = &[_]Resource{ .file_write, .file_append };
|
||||
const files_any = &[_]Resource{ .file_read, .file_write, .file_append };
|
||||
|
||||
pub const intrinsics = [_]Intrinsic{
|
||||
.{ .name = "clock.monotonic", .operands = &.{.{ .cap = "clock.read" }}, .fallible = false, .results = &.{.u64}, .effect = "clock.read" },
|
||||
.{ .name = "fs.close", .operands = &.{.{ .consumed = files_any }}, .fallible = true, .results = &.{}, .effect = null },
|
||||
.{ .name = "fs.create", .operands = &.{ .{ .cap = "fs.write" }, .bytes }, .fallible = true, .results = &.{.{ .resource = .file_write }}, .effect = "fs.write" },
|
||||
.{ .name = "fs.open_append", .operands = &.{ .{ .cap = "fs.write" }, .bytes }, .fallible = true, .results = &.{.{ .resource = .file_append }}, .effect = "fs.write" },
|
||||
.{ .name = "fs.open_read", .operands = &.{ .{ .cap = "fs.read" }, .bytes }, .fallible = true, .results = &.{.{ .resource = .file_read }}, .effect = "fs.read" },
|
||||
.{ .name = "fs.read", .operands = &.{ .{ .borrowed = &.{.file_read} }, .buffer }, .fallible = true, .results = &.{.usize}, .effect = "fs.read" },
|
||||
.{ .name = "fs.sync", .operands = &.{.{ .borrowed = files_w }}, .fallible = true, .results = &.{}, .effect = "fs.write" },
|
||||
.{ .name = "fs.write_all", .operands = &.{ .{ .borrowed = files_w }, .bytes }, .fallible = true, .results = &.{}, .effect = "fs.write" },
|
||||
.{ .name = "io.stderr_write", .operands = &.{ .{ .cap = "io.write" }, .bytes }, .fallible = true, .results = &.{}, .effect = "io.write" },
|
||||
.{ .name = "io.stdin_read", .operands = &.{ .{ .cap = "io.read" }, .buffer }, .fallible = true, .results = &.{.usize}, .effect = "io.read" },
|
||||
.{ .name = "io.stdout_write", .operands = &.{ .{ .cap = "io.write" }, .bytes }, .fallible = true, .results = &.{}, .effect = "io.write" },
|
||||
.{ .name = "net.accept", .operands = &.{.{ .borrowed = &.{.listener} }}, .fallible = true, .results = &.{.{ .resource = .stream }}, .effect = "net.listen" },
|
||||
.{ .name = "net.close_listener", .operands = &.{.{ .consumed = &.{.listener} }}, .fallible = true, .results = &.{}, .effect = null },
|
||||
.{ .name = "net.close_stream", .operands = &.{.{ .consumed = &.{.stream} }}, .fallible = true, .results = &.{}, .effect = null },
|
||||
.{ .name = "net.connect", .operands = &.{ .{ .cap = "net.connect" }, .bytes }, .fallible = true, .results = &.{.{ .resource = .stream }}, .effect = "net.connect" },
|
||||
.{ .name = "net.listen", .operands = &.{ .{ .cap = "net.listen" }, .bytes }, .fallible = true, .results = &.{.{ .resource = .listener }}, .effect = "net.listen" },
|
||||
.{ .name = "net.recv", .operands = &.{ .{ .borrowed = &.{.stream} }, .buffer }, .fallible = true, .results = &.{.usize}, .effect = "net.read" },
|
||||
.{ .name = "net.send_all", .operands = &.{ .{ .borrowed = &.{.stream} }, .bytes }, .fallible = true, .results = &.{}, .effect = "net.write" },
|
||||
.{ .name = "random.fill", .operands = &.{ .{ .cap = "random.read" }, .buffer }, .fallible = false, .results = &.{}, .effect = "random.read" },
|
||||
};
|
||||
|
||||
pub fn intrinsicIndex(name: []const u8) ?u16 {
|
||||
for (intrinsics, 0..) |x, i| if (std.mem.eql(u8, x.name, name)) return @intCast(i);
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Whether an intrinsic mentions resource types (needs feature `resources`).
|
||||
pub fn usesResources(x: Intrinsic) bool {
|
||||
for (x.operands) |o| if (o == .borrowed or o == .consumed) return true;
|
||||
for (x.results) |r| if (r == .resource) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Names in the first column of the first table of a reference file whose
|
||||
/// rows start with "| `".
|
||||
fn tableNames(comptime md: []const u8, buf: [][]const u8) usize {
|
||||
@@ -151,3 +249,23 @@ test "instantiation scopes" {
|
||||
try std.testing.expect(!validScope(kindIndex("io.write").?, "/x"));
|
||||
try std.testing.expect(validScope(kindIndex("mem.alloc").?, "1048576"));
|
||||
}
|
||||
|
||||
test "intrinsic registry mirrors reference/intrinsics.md" {
|
||||
const md = @embedFile("intrinsics_md");
|
||||
var n: usize = 0;
|
||||
var lines = std.mem.splitScalar(u8, md, '\n');
|
||||
while (lines.next()) |line| {
|
||||
if (!std.mem.startsWith(u8, line, "| `")) continue;
|
||||
var cols = std.mem.tokenizeScalar(u8, line, '|');
|
||||
const name = std.mem.trim(u8, cols.next().?, " `");
|
||||
// Only intrinsic rows: a single dotted name (the narrowing table lists kinds).
|
||||
if (std.mem.indexOfScalar(u8, name, '.') == null or std.mem.indexOfScalar(u8, name, ',') != null) continue;
|
||||
if (intrinsicIndex(name) == null) {
|
||||
std.debug.print("intrinsic {s} is documented but not registered\n", .{name});
|
||||
return error.RegistryOutOfSync;
|
||||
}
|
||||
n += 1;
|
||||
}
|
||||
try std.testing.expectEqual(intrinsics.len, n);
|
||||
for (intrinsics, 0..) |x, i| if (i > 0) try std.testing.expect(std.mem.lessThan(u8, intrinsics[i - 1].name, x.name));
|
||||
}
|
||||
@@ -30,14 +30,16 @@ pub const registry = [_]Feature{
|
||||
.{ .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 = "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 = "resources", .depends = &.{ "capabilities", "effects", "ownership" }, .status = .published, .phase = 2 },
|
||||
.{ .name = "sync", .depends = &.{"ownership"}, .status = .reserved, .phase = 3 },
|
||||
.{ .name = "tasks", .depends = &.{"ownership"}, .status = .reserved, .phase = 3 },
|
||||
};
|
||||
|
||||
/// Features implemented by this toolchain, sorted.
|
||||
pub const supported = [_][]const u8{ "arrays", "capabilities", "effects", "ownership" };
|
||||
pub const supported = [_][]const u8{ "arrays", "capabilities", "effects", "ownership", "resources" };
|
||||
|
||||
pub const Reason = enum {
|
||||
unknown_feature,
|
||||
|
||||
+15
-1
@@ -77,6 +77,8 @@ pub const Type = union(enum) {
|
||||
/// Index into `authority.kinds`.
|
||||
cap: u16,
|
||||
builtin: authority.Builtin,
|
||||
// Feature `resources` (spec 06 §6).
|
||||
resource: authority.Resource,
|
||||
|
||||
pub const Array = struct { elem: Type, len: u64 };
|
||||
|
||||
@@ -89,6 +91,7 @@ pub const Type = union(enum) {
|
||||
.array => |x| x.len == b.array.len and x.elem.eql(b.array.elem),
|
||||
.cap => |k| b.cap == k,
|
||||
.builtin => |e| b.builtin == e,
|
||||
.resource => |r| b.resource == r,
|
||||
.bool, .void, .never => true,
|
||||
};
|
||||
}
|
||||
@@ -119,9 +122,11 @@ pub const Type = union(enum) {
|
||||
}
|
||||
|
||||
/// Value types may be stored in fields, payloads, elements and locals.
|
||||
/// (A borrowed resource `mut<file<read>>` has a resource as its inner type.)
|
||||
/// 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 => false,
|
||||
.void, .never, .local, .ref, .mut, .slice, .slice_mut, .resource => false,
|
||||
else => true,
|
||||
};
|
||||
}
|
||||
@@ -232,6 +237,9 @@ pub const Op = union(enum) {
|
||||
/// Fallible narrowing (spec 05 §10.4): continues at `ok` with the new
|
||||
/// capability or at `err` with a `cap_error`, as block parameters.
|
||||
cap_narrow: struct { form: []const u8, cap: ValueId, args: []const ValueId, ok: u32, err: u32 },
|
||||
/// 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 },
|
||||
ret: ?ValueId,
|
||||
trap,
|
||||
|
||||
@@ -241,6 +249,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,
|
||||
.intrinsic => |x| x.ok != null,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
@@ -366,6 +375,7 @@ pub fn forEachUse(op: Op, ctx: anytype, comptime f: fn (@TypeOf(ctx), ValueId) v
|
||||
f(ctx, x.cap);
|
||||
for (x.args) |v| f(ctx, v);
|
||||
},
|
||||
.intrinsic => |x| for (x.args) |v| f(ctx, v),
|
||||
.ret => |v| if (v) |x| f(ctx, x),
|
||||
.local_alloc => {},
|
||||
.local_store => |x| {
|
||||
@@ -419,6 +429,10 @@ pub fn successors(op: Op, buf: *std.ArrayList(u32), gpa: std.mem.Allocator) !voi
|
||||
try buf.append(gpa, x.ok);
|
||||
try buf.append(gpa, x.err);
|
||||
},
|
||||
.intrinsic => |x| if (x.ok) |ok| {
|
||||
try buf.append(gpa, ok);
|
||||
try buf.append(gpa, x.err.?);
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
}
|
||||
|
||||
+49
-8
@@ -423,7 +423,9 @@ const Parser = struct {
|
||||
while (p.peek().tag != .r_brace) {
|
||||
const fname = try p.expect(.word, "field name");
|
||||
_ = try p.expect(.colon, "`:`");
|
||||
const ty_span = p.peek().span;
|
||||
const ty = try p.parseType();
|
||||
try p.gateLinearMember(ty, ty_span);
|
||||
for (fields.items) |f| if (std.mem.eql(u8, f.name, fname.text))
|
||||
try p.report("E0003", fname.span, "duplicate field", &.{.{ .name = "name", .value = .{ .str = fname.text } }});
|
||||
try fields.append(p.arena, .{ .name = fname.text, .ty = ty });
|
||||
@@ -442,7 +444,10 @@ const Parser = struct {
|
||||
if (p.peek().tag == .l_paren) {
|
||||
_ = p.next();
|
||||
while (p.peek().tag != .r_paren) {
|
||||
try payload.append(p.arena, try p.parseType());
|
||||
const ty_span = p.peek().span;
|
||||
const ty = try p.parseType();
|
||||
try p.gateLinearMember(ty, ty_span);
|
||||
try payload.append(p.arena, ty);
|
||||
if (p.peek().tag != .comma) break;
|
||||
_ = p.next();
|
||||
}
|
||||
@@ -477,9 +482,13 @@ const Parser = struct {
|
||||
if (std.mem.eql(u8, t.text, "void")) return .void;
|
||||
if (std.mem.eql(u8, t.text, "never")) return .never;
|
||||
if (std.meta.stringToEnum(authority.Builtin, t.text)) |b| {
|
||||
try p.requireFeature("capabilities", t.span, t.text);
|
||||
try p.requireFeature(b.feature(), t.span, t.text);
|
||||
return .{ .builtin = b };
|
||||
}
|
||||
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 };
|
||||
}
|
||||
if (std.mem.eql(u8, t.text, "f32") or std.mem.eql(u8, t.text, "f64")) {
|
||||
try p.report("E0006", t.span, "floating-point types are reserved (spec 07 §8.4)", &.{
|
||||
.{ .name = "reason", .value = .{ .str = "reserved_type" } },
|
||||
@@ -496,6 +505,18 @@ const Parser = struct {
|
||||
|
||||
/// `local<T>`, `ref<T>`, `mut<T>`, `slice<T>`, `slice_mut<T>`, `array<T, N>` (spec 07 §8.8).
|
||||
fn parseCompoundType(p: *Parser, t: Token) Error!air.Type {
|
||||
if (eql(t.text, "file")) {
|
||||
try p.requireFeature("resources", t.span, "file");
|
||||
_ = try p.expect(.lt, "`<`");
|
||||
const mode = try p.expect(.word, "`read`, `write` or `append`");
|
||||
_ = try p.expect(.gt, "`>`");
|
||||
const Mode = enum { read, write, append };
|
||||
return .{ .resource = switch (std.meta.stringToEnum(Mode, mode.text) orelse return p.fail(mode, "`read`, `write` or `append`")) {
|
||||
.read => .file_read,
|
||||
.write => .file_write,
|
||||
.append => .file_append,
|
||||
} };
|
||||
}
|
||||
if (eql(t.text, "cap")) {
|
||||
try p.requireFeature("capabilities", t.span, "cap");
|
||||
_ = try p.expect(.lt, "`<`");
|
||||
@@ -517,8 +538,10 @@ const Parser = struct {
|
||||
.slice, .slice_mut, .array => "arrays",
|
||||
}, t.span, t.text);
|
||||
_ = try p.expect(.lt, "`<`");
|
||||
const inner_span = p.peek().span;
|
||||
const inner = try p.parseType();
|
||||
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;
|
||||
@@ -543,6 +566,11 @@ 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");
|
||||
}
|
||||
|
||||
fn declares(p: *Parser, feature: []const u8) bool {
|
||||
for (p.declared) |d| if (eql(d, feature)) return true;
|
||||
return false;
|
||||
@@ -842,7 +870,7 @@ const Parser = struct {
|
||||
try p.report("E0004", t.span, "unknown enum", &.{.{ .name = "name", .value = .{ .str = t.text } }});
|
||||
return error.SyntaxError;
|
||||
};
|
||||
try p.requireFeature("capabilities", t.span, t.text);
|
||||
try p.requireFeature(b.feature(), t.span, t.text);
|
||||
break :blk .{ .builtin = b };
|
||||
} else .{ .named = try p.typeRef(.@"enum") };
|
||||
const value = try p.useValue();
|
||||
@@ -890,10 +918,23 @@ const Parser = struct {
|
||||
if (eql(op_tok.text, "intrinsic")) {
|
||||
try p.requireFeature("capabilities", op_tok.span, "intrinsic");
|
||||
const name = try p.expect(.word, "intrinsic name");
|
||||
// No intrinsic is registered yet (RFC 0007), so every name is unknown.
|
||||
try p.report("E0004", name.span, "unknown intrinsic", &.{.{ .name = "name", .value = .{ .str = name.text } }});
|
||||
while (p.peek().tag != .nl) _ = p.next();
|
||||
return null;
|
||||
const which = authority.intrinsicIndex(name.text) orelse {
|
||||
try p.report("E0004", name.span, "unknown intrinsic", &.{.{ .name = "name", .value = .{ .str = name.text } }});
|
||||
while (p.peek().tag != .nl) _ = p.next();
|
||||
return null;
|
||||
};
|
||||
if (authority.usesResources(authority.intrinsics[which])) try p.requireFeature("resources", name.span, name.text);
|
||||
const args = try p.valueList();
|
||||
if (p.peek().tag != .comma) break :op .{ .intrinsic = .{ .index = which, .args = args } };
|
||||
_ = p.next();
|
||||
_ = 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, "`->`");
|
||||
const err = try p.blockRef();
|
||||
break :op .{ .intrinsic = .{ .index = which, .args = args, .ok = ok, .err = err } };
|
||||
}
|
||||
return p.unknownOpcode(op_tok);
|
||||
};
|
||||
@@ -905,7 +946,7 @@ const Parser = struct {
|
||||
.array_splat, .borrow_index, .slice_make, .slice_len, .slice_sub, .slice_split => true,
|
||||
else => false,
|
||||
};
|
||||
const may_bind = produces_value or op == .call;
|
||||
const may_bind = produces_value or op == .call or op == .intrinsic;
|
||||
if (result_tok) |rt| {
|
||||
if (!may_bind) return p.fail(rt, "instruction without result binding");
|
||||
} else if (produces_value) {
|
||||
|
||||
@@ -104,6 +104,7 @@ 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()),
|
||||
.bool, .void, .never => try w.writeAll(@tagName(t)),
|
||||
}
|
||||
}
|
||||
@@ -280,6 +281,11 @@ fn printOp(m: air.Module, f: air.Function, op: air.Op, w: *Writer) Writer.Error!
|
||||
.slice_split => |x| try two(f, w, "slice.split", x.slice, x.at),
|
||||
.slice_copy => |x| try two(f, w, "slice.copy", x.dst, x.src),
|
||||
.guard => |v| try one(f, w, "guard", v),
|
||||
.intrinsic => |x| {
|
||||
try w.print("intrinsic {s}", .{air.authority.intrinsics[x.index].name});
|
||||
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 });
|
||||
},
|
||||
.cap_narrow => |x| {
|
||||
try w.print("cap.narrow.{s} ", .{x.form});
|
||||
try value(f, x.cap, w);
|
||||
|
||||
@@ -7,6 +7,8 @@ pub const Trap = machine.Trap;
|
||||
pub const Outcome = machine.Outcome;
|
||||
pub const Options = machine.Options;
|
||||
pub const Grant = machine.Grant;
|
||||
pub const Output = machine.Output;
|
||||
pub const WorldOptions = machine.WorldOptions;
|
||||
pub const run = machine.run;
|
||||
pub const writeOutcome = machine.writeOutcome;
|
||||
pub const writeValue = machine.writeValue;
|
||||
|
||||
+227
-5
@@ -11,6 +11,9 @@
|
||||
const std = @import("std");
|
||||
const air = @import("../air.zig");
|
||||
const diag = @import("../diag.zig");
|
||||
const world_mod = @import("world.zig");
|
||||
|
||||
pub const WorldOptions = world_mod.Options;
|
||||
|
||||
pub const call_depth_limit = 1024;
|
||||
|
||||
@@ -30,6 +33,8 @@ pub const Value = union(enum) {
|
||||
/// `cap<K>`: index into the host's authority table. Never observable
|
||||
/// by the program (spec 05 §10.1).
|
||||
cap: u32,
|
||||
/// Linear resource: index into the world's handle table.
|
||||
resource: u32,
|
||||
/// Value of a built-in enum such as `cap_error`.
|
||||
builtin: struct { which: air.authority.Builtin, variant: u32 },
|
||||
|
||||
@@ -64,8 +69,13 @@ pub const Outcome = union(enum) {
|
||||
limit_exceeded: struct { limit: u64, steps: u64 },
|
||||
/// The host did not start the program (spec 05 §10.2). Not a trap.
|
||||
not_instantiated: NotInstantiated,
|
||||
/// The deterministic runtime found no future event that could complete
|
||||
/// a wait (spec 11 §8). Not a trap and not an I/O error.
|
||||
blocked: Location,
|
||||
};
|
||||
|
||||
pub const Location = struct { function: []const u8, block: []const u8, inst: u32 };
|
||||
|
||||
pub const NotInstantiated = struct {
|
||||
reason: []const u8,
|
||||
parameter: []const u8,
|
||||
@@ -89,6 +99,18 @@ pub const Options = struct {
|
||||
fuel: ?u64 = null,
|
||||
/// Capability grants for the parameters of the entry function.
|
||||
grants: []const Grant = &.{},
|
||||
/// Inputs of the deterministic world (spec 11 §8).
|
||||
world: WorldOptions = .{},
|
||||
/// Receives the run's observable output.
|
||||
output: ?*Output = null,
|
||||
};
|
||||
|
||||
/// Observable output of a run in the deterministic profile.
|
||||
pub const Output = struct {
|
||||
stdout: []const u8,
|
||||
stderr: []const u8,
|
||||
/// Files written during the run, sorted by path.
|
||||
files: []const struct { []const u8, []const u8 },
|
||||
};
|
||||
|
||||
pub const Error = std.mem.Allocator.Error || error{ EntryNotFound, DuplicateGrant };
|
||||
@@ -99,7 +121,10 @@ pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, opti
|
||||
const idx = module.functionIndex(entry) orelse return error.EntryNotFound;
|
||||
const f = module.functions[idx];
|
||||
for (f.params) |p| if (p.ty != .cap) return error.EntryNotFound;
|
||||
var m: Machine = .{ .arena = arena, .module = module, .fuel = options.fuel };
|
||||
var m: Machine = .{ .arena = arena, .module = module, .fuel = options.fuel, .world = try .init(arena, options.world) };
|
||||
defer if (options.output) |o| {
|
||||
o.* = m.output() catch .{ .stdout = "", .stderr = "", .files = &.{} };
|
||||
};
|
||||
|
||||
// Instantiation (spec 05 §10.2): every capability parameter gets exactly
|
||||
// one grant of its kind, and every grant names a parameter.
|
||||
@@ -129,6 +154,7 @@ pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, opti
|
||||
.value => |v| .{ .returned = v },
|
||||
.trap => |t| .{ .trapped = t },
|
||||
.limit_exceeded => .{ .limit_exceeded = .{ .limit = m.fuel.?, .steps = m.steps } },
|
||||
.blocked => |l| .{ .blocked = l },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -168,7 +194,7 @@ fn kindOf(e: TrapError) TrapKind {
|
||||
};
|
||||
}
|
||||
|
||||
const CallResult = union(enum) { value: Value, trap: Trap, limit_exceeded };
|
||||
const CallResult = union(enum) { value: Value, trap: Trap, limit_exceeded, blocked: Location };
|
||||
|
||||
const Machine = struct {
|
||||
arena: std.mem.Allocator,
|
||||
@@ -177,6 +203,7 @@ const Machine = struct {
|
||||
fuel: ?u64,
|
||||
/// Host authority table; capabilities index into it.
|
||||
authorities: std.ArrayList(Authority) = .empty,
|
||||
world: world_mod.World,
|
||||
/// Instructions executed so far.
|
||||
steps: u64 = 0,
|
||||
|
||||
@@ -211,6 +238,8 @@ const Machine = struct {
|
||||
} },
|
||||
.nested_trap => |t| return .{ .trap = t },
|
||||
.limit_exceeded => return .limit_exceeded,
|
||||
.blocked => return .{ .blocked = .{ .function = f.name, .block = b.name, .inst = @intCast(ii) } },
|
||||
.nested_blocked => |l| return .{ .blocked = l },
|
||||
}
|
||||
} else unreachable; // verified blocks end with a terminator
|
||||
}
|
||||
@@ -224,6 +253,8 @@ const Machine = struct {
|
||||
/// A trap raised inside a callee, already located.
|
||||
nested_trap: Trap,
|
||||
limit_exceeded,
|
||||
blocked,
|
||||
nested_blocked: Location,
|
||||
};
|
||||
|
||||
fn exec(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst) std.mem.Allocator.Error!Step {
|
||||
@@ -291,6 +322,7 @@ const Machine = struct {
|
||||
},
|
||||
.trap => |t| return .{ .nested_trap = t },
|
||||
.limit_exceeded => return .limit_exceeded,
|
||||
.blocked => |l| return .{ .nested_blocked = l },
|
||||
}
|
||||
},
|
||||
.br => |t| return m.jump(f, vals, t),
|
||||
@@ -314,7 +346,8 @@ 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 => unreachable,
|
||||
.cap_narrow => |x| return m.narrow(f, vals, x),
|
||||
.intrinsic => |x| return m.intrinsic(f, vals, inst, x),
|
||||
.ret => |v| return .{ .ret = if (v) |x| vals[x] else .void },
|
||||
.trap => return .{ .trap = .explicit },
|
||||
.local_alloc, .local_store, .local_zero, .local_load, .borrow_ref, .borrow_mut, .borrow_field, .borrow_end, .load, .store, .array_splat, .borrow_index, .slice_make, .slice_len, .slice_sub, .slice_split, .slice_copy, .guard => return m.execMemory(vals, inst),
|
||||
@@ -388,6 +421,143 @@ const Machine = struct {
|
||||
};
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ authority and I/O (spec 05 §10–§11, spec 06 §6)
|
||||
|
||||
fn output(m: *Machine) !Output {
|
||||
const keys = try m.arena.dupe([]const u8, m.world.written.keys());
|
||||
std.mem.sort([]const u8, keys, {}, struct {
|
||||
fn lt(_: void, a: []const u8, b: []const u8) bool {
|
||||
return std.mem.lessThan(u8, a, b);
|
||||
}
|
||||
}.lt);
|
||||
const files = try m.arena.alloc(struct { []const u8, []const u8 }, keys.len);
|
||||
for (keys, files) |k, *out| out.* = .{ k, m.world.files.get(k).?.items };
|
||||
return .{ .stdout = m.world.stdout.items, .stderr = m.world.stderr.items, .files = files };
|
||||
}
|
||||
|
||||
/// Bytes of a `slice<u8>` value.
|
||||
fn bytesOf(m: *Machine, v: Value) ![]u8 {
|
||||
const s = v.slice;
|
||||
const items = placePtr(s.place).array[s.start..][0..s.len];
|
||||
const out = try m.arena.alloc(u8, items.len);
|
||||
for (items, out) |x, *o| o.* = @truncate(x.int.bits);
|
||||
return out;
|
||||
}
|
||||
|
||||
/// Writes `bytes` into the start of a `slice_mut<u8>` value.
|
||||
fn fillSlice(v: Value, bytes: []const u8) void {
|
||||
const s = v.slice;
|
||||
const items = placePtr(s.place).array[s.start..][0..s.len];
|
||||
for (bytes, items[0..bytes.len]) |b, *x| x.* = .{ .int = .{ .ty = .u8, .bits = b } };
|
||||
}
|
||||
|
||||
fn resourceOf(v: Value) u32 {
|
||||
return switch (v) {
|
||||
.resource => |hd| hd,
|
||||
.place => |p| p.cell.value.resource,
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
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 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| {
|
||||
vals[f.blocks[x.err].params[0].value] = .{ .builtin = .{ .which = .cap_error, .variant = r } };
|
||||
return .{ .jump = x.err };
|
||||
}
|
||||
try m.authorities.append(m.arena, .{ .kind = a.kind, .scope = path });
|
||||
vals[f.blocks[x.ok].params[0].value] = .{ .cap = @intCast(m.authorities.items.len - 1) };
|
||||
return .{ .jump = x.ok };
|
||||
}
|
||||
|
||||
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 {
|
||||
fn at(v: []Value, xx: @FieldType(air.Op, "intrinsic"), i: usize) Value {
|
||||
return v[xx.args[i]];
|
||||
}
|
||||
}.at;
|
||||
const W = world_mod.World;
|
||||
var results: [1]Value = undefined;
|
||||
var n_results: usize = 0;
|
||||
var failure: ?world_mod.Error = null;
|
||||
const is = struct {
|
||||
fn eq(a: []const u8, b: []const u8) bool {
|
||||
return std.mem.eql(u8, a, b);
|
||||
}
|
||||
}.eq;
|
||||
if (is(name, "clock.monotonic")) {
|
||||
return bind(vals, inst.result, .{ .int = .{ .ty = .u64, .bits = m.steps } });
|
||||
} else if (is(name, "random.fill")) {
|
||||
const buf = try m.arena.alloc(u8, arg(vals, x, 1).slice.len);
|
||||
m.world.fill(buf);
|
||||
fillSlice(arg(vals, x, 1), buf);
|
||||
return .next;
|
||||
} else if (is(name, "io.stdout_write") or is(name, "io.stderr_write")) {
|
||||
try m.world.writeOut(is(name, "io.stderr_write"), try m.bytesOf(arg(vals, x, 1)));
|
||||
} else if (is(name, "io.stdin_read")) {
|
||||
const buf = try m.arena.alloc(u8, arg(vals, x, 1).slice.len);
|
||||
const n = m.world.readIn(buf);
|
||||
fillSlice(arg(vals, x, 1), buf[0..n]);
|
||||
results[0] = .{ .int = .{ .ty = .usize, .bits = n } };
|
||||
n_results = 1;
|
||||
} else if (is(name, "fs.open_read") or is(name, "fs.create") or is(name, "fs.open_append")) {
|
||||
const scope = m.authorities.items[arg(vals, x, 0).cap].scope;
|
||||
const mode: air.authority.Resource = if (is(name, "fs.open_read")) .file_read else if (is(name, "fs.create")) .file_write else .file_append;
|
||||
switch (try m.world.open(scope, try m.bytesOf(arg(vals, x, 1)), mode)) {
|
||||
.ok => |hd| {
|
||||
results[0] = .{ .resource = hd };
|
||||
n_results = 1;
|
||||
},
|
||||
.err => |e| failure = e,
|
||||
}
|
||||
} else if (is(name, "fs.read")) {
|
||||
const buf = try m.arena.alloc(u8, arg(vals, x, 1).slice.len);
|
||||
const n = m.world.fileRead(resourceOf(arg(vals, x, 0)), buf);
|
||||
fillSlice(arg(vals, x, 1), buf[0..n]);
|
||||
results[0] = .{ .int = .{ .ty = .usize, .bits = n } };
|
||||
n_results = 1;
|
||||
} else if (is(name, "fs.write_all")) {
|
||||
try m.world.fileWrite(resourceOf(arg(vals, x, 0)), try m.bytesOf(arg(vals, x, 1)));
|
||||
} else if (is(name, "fs.sync")) {
|
||||
// Durable by construction in the in-memory file system.
|
||||
} else if (is(name, "fs.close") or is(name, "net.close_stream") or is(name, "net.close_listener")) {
|
||||
m.world.close(arg(vals, x, 0).resource);
|
||||
} else if (is(name, "net.listen") or is(name, "net.connect")) {
|
||||
const addr = try m.bytesOf(arg(vals, x, 1));
|
||||
switch (if (is(name, "net.listen")) try m.world.listen(addr) else try m.world.connect(addr)) {
|
||||
.ok => |hd| {
|
||||
results[0] = .{ .resource = hd };
|
||||
n_results = 1;
|
||||
},
|
||||
.err => |e| failure = e,
|
||||
}
|
||||
} else if (is(name, "net.accept")) {
|
||||
const s = m.world.accept(resourceOf(arg(vals, x, 0))) orelse return .blocked;
|
||||
results[0] = .{ .resource = s };
|
||||
n_results = 1;
|
||||
} else if (is(name, "net.recv")) {
|
||||
const buf = try m.arena.alloc(u8, arg(vals, x, 1).slice.len);
|
||||
const n = m.world.recv(resourceOf(arg(vals, x, 0)), buf) orelse return .blocked;
|
||||
fillSlice(arg(vals, x, 1), buf[0..n]);
|
||||
results[0] = .{ .int = .{ .ty = .usize, .bits = n } };
|
||||
n_results = 1;
|
||||
} else if (is(name, "net.send_all")) {
|
||||
failure = try m.world.send(resourceOf(arg(vals, x, 0)), try m.bytesOf(arg(vals, x, 1)));
|
||||
} else unreachable; // every registered intrinsic is handled above
|
||||
_ = W;
|
||||
|
||||
if (failure) |e| {
|
||||
vals[f.blocks[x.err.?].params[0].value] = .{ .builtin = .{ .which = .io_error, .variant = @backingInt(e) } };
|
||||
return .{ .jump = x.err.? };
|
||||
}
|
||||
for (f.blocks[x.ok.?].params, results[0..n_results]) |p, r| vals[p.value] = r;
|
||||
return .{ .jump = x.ok.? };
|
||||
}
|
||||
|
||||
fn usize_(v: Value) u64 {
|
||||
return @truncate(v.int.bits);
|
||||
}
|
||||
@@ -411,6 +581,12 @@ const Machine = struct {
|
||||
.local_load => |v| return bind(vals, inst.result, try m.deepCopy(vals[v].local.value)),
|
||||
.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.
|
||||
.resource => |hd| blk: {
|
||||
const cell = try m.arena.create(Value.Cell);
|
||||
cell.* = .{ .value = .{ .resource = hd }, .ty = .void };
|
||||
break :blk .{ .place = .{ .cell = cell, .path = &.{} } };
|
||||
},
|
||||
else => |x| x,
|
||||
}),
|
||||
.borrow_field => |x| return bind(vals, inst.result, .{ .place = try m.extend(asPlace(vals[x.borrow]), x.field) }),
|
||||
@@ -611,6 +787,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),
|
||||
// A capability is opaque: only its kind is shown, never its identity.
|
||||
.cap => {
|
||||
try s.beginObject();
|
||||
@@ -653,8 +830,23 @@ pub fn writeValue(module: air.Module, v: Value, s: *std.json.Stringify) std.Io.W
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes bytes as a JSON string: printable ASCII as is, every other byte
|
||||
/// as `\u00XX`, so arbitrary output is valid, deterministic JSON.
|
||||
fn writeBytes(w: *std.Io.Writer, bytes: []const u8) std.Io.Writer.Error!void {
|
||||
try w.writeByte('"');
|
||||
for (bytes) |b| switch (b) {
|
||||
'"' => try w.writeAll("\\\""),
|
||||
'\\' => try w.writeAll("\\\\"),
|
||||
'\n' => try w.writeAll("\\n"),
|
||||
0x20...0x21, 0x23...0x5b, 0x5d...0x7e => try w.writeByte(b),
|
||||
else => try w.print("\\u{x:0>4}", .{b}),
|
||||
};
|
||||
try w.writeByte('"');
|
||||
}
|
||||
|
||||
/// Writes the run record for `outcome` as one JSON object (no newline).
|
||||
pub fn writeOutcome(module: air.Module, outcome: Outcome, w: *std.Io.Writer) std.Io.Writer.Error!void {
|
||||
/// `output` is added for modules that declare `capabilities` (spec 07a).
|
||||
pub fn writeOutcome(module: air.Module, outcome: Outcome, out: ?Output, w: *std.Io.Writer) std.Io.Writer.Error!void {
|
||||
var s: std.json.Stringify = .{ .writer = w };
|
||||
try s.beginObject();
|
||||
try s.objectField("status");
|
||||
@@ -677,6 +869,17 @@ pub fn writeOutcome(module: air.Module, outcome: Outcome, w: *std.Io.Writer) std
|
||||
try s.objectField("inst");
|
||||
try s.write(t.inst);
|
||||
},
|
||||
.blocked => |l| {
|
||||
try s.write("blocked");
|
||||
try s.objectField("kind");
|
||||
try s.write("no_future_event");
|
||||
try s.objectField("function");
|
||||
try s.write(l.function);
|
||||
try s.objectField("block");
|
||||
try s.write(l.block);
|
||||
try s.objectField("inst");
|
||||
try s.write(l.inst);
|
||||
},
|
||||
.not_instantiated => |n| {
|
||||
try s.write("not_instantiated");
|
||||
try s.objectField("reason");
|
||||
@@ -706,6 +909,25 @@ pub fn writeOutcome(module: air.Module, outcome: Outcome, w: *std.Io.Writer) std
|
||||
try s.write(l.steps);
|
||||
},
|
||||
}
|
||||
if (out) |o| if (module.declares("capabilities") and outcome != .not_instantiated) {
|
||||
try s.objectField("stdout");
|
||||
try s.beginWriteRaw();
|
||||
try writeBytes(w, o.stdout);
|
||||
s.endWriteRaw();
|
||||
try s.objectField("stderr");
|
||||
try s.beginWriteRaw();
|
||||
try writeBytes(w, o.stderr);
|
||||
s.endWriteRaw();
|
||||
try s.objectField("files");
|
||||
try s.beginObject();
|
||||
for (o.files) |file| {
|
||||
try s.objectField(file[0]);
|
||||
try s.beginWriteRaw();
|
||||
try writeBytes(w, file[1]);
|
||||
s.endWriteRaw();
|
||||
}
|
||||
try s.endObject();
|
||||
};
|
||||
try s.endObject();
|
||||
}
|
||||
|
||||
@@ -728,7 +950,7 @@ fn expectRunFuel(src: []const u8, expected: []const u8, fuel: ?u64) !void {
|
||||
}
|
||||
const outcome = try run(arena, report.module.?, "main", .{ .fuel = fuel });
|
||||
var out: std.Io.Writer.Allocating = .init(arena);
|
||||
try writeOutcome(report.module.?, outcome, &out.writer);
|
||||
try writeOutcome(report.module.?, outcome, null, &out.writer);
|
||||
try std.testing.expectEqualStrings(expected, out.written());
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
//! The `deterministic` execution profile (spec 11 §8): captured console,
|
||||
//! in-memory file system, in-process loopback TCP, logical clock and a
|
||||
//! seeded PRNG. Every result is a function of the run's inputs.
|
||||
|
||||
const std = @import("std");
|
||||
const air = @import("../air.zig");
|
||||
|
||||
const IoError = enum(u32) {
|
||||
not_found,
|
||||
permission_denied,
|
||||
already_exists,
|
||||
invalid_input,
|
||||
no_space,
|
||||
broken_pipe,
|
||||
connection_refused,
|
||||
connection_reset,
|
||||
address_in_use,
|
||||
address_unavailable,
|
||||
timed_out,
|
||||
other,
|
||||
};
|
||||
|
||||
comptime {
|
||||
// Variant indices must match the built-in enum `io_error`.
|
||||
for (air.authority.Builtin.io_error.variants(), 0..) |name, i| {
|
||||
std.debug.assert(std.mem.eql(u8, @tagName(@as(IoError, @fromBackingInt(@intCast(i)))), name));
|
||||
}
|
||||
}
|
||||
|
||||
pub const Error = IoError;
|
||||
|
||||
/// Result of an operation that creates a resource.
|
||||
pub const Opened = union(enum) { ok: u32, err: IoError };
|
||||
|
||||
/// An open resource. Indices are never reused within a run.
|
||||
pub const Handle = union(enum) {
|
||||
file: struct { path: []const u8, mode: air.authority.Resource, pos: usize },
|
||||
listener: struct { addr: []const u8, pending: std.ArrayList(u32) = .empty },
|
||||
stream: struct { peer: ?u32, inbox: std.ArrayList(u8) = .empty, read_pos: usize = 0, peer_closed: bool = false },
|
||||
closed,
|
||||
};
|
||||
|
||||
pub const Options = struct {
|
||||
stdin: []const u8 = "",
|
||||
/// Initial files: path -> contents.
|
||||
files: []const struct { []const u8, []const u8 } = &.{},
|
||||
seed: u64 = 0,
|
||||
};
|
||||
|
||||
pub const World = struct {
|
||||
arena: std.mem.Allocator,
|
||||
stdout: std.ArrayList(u8) = .empty,
|
||||
stderr: std.ArrayList(u8) = .empty,
|
||||
stdin: []const u8,
|
||||
stdin_pos: usize = 0,
|
||||
files: std.StringArrayHashMapUnmanaged(std.ArrayList(u8)) = .empty,
|
||||
written: std.StringArrayHashMapUnmanaged(void) = .empty,
|
||||
handles: std.ArrayList(Handle) = .empty,
|
||||
listeners: std.StringHashMapUnmanaged(u32) = .empty,
|
||||
/// xoshiro256** seeded by SplitMix64 from `--seed` (spec 11 §8); pinned
|
||||
/// explicitly so a toolchain upgrade cannot change deterministic output.
|
||||
prng: std.Random.Xoshiro256,
|
||||
|
||||
pub fn init(arena: std.mem.Allocator, o: Options) !World {
|
||||
var w: World = .{ .arena = arena, .stdin = o.stdin, .prng = .init(o.seed) };
|
||||
for (o.files) |entry| {
|
||||
var contents: std.ArrayList(u8) = .empty;
|
||||
try contents.appendSlice(arena, entry[1]);
|
||||
try w.files.put(arena, entry[0], contents);
|
||||
}
|
||||
return w;
|
||||
}
|
||||
|
||||
fn add(w: *World, h: Handle) !u32 {
|
||||
try w.handles.append(w.arena, h);
|
||||
return @intCast(w.handles.items.len - 1);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ paths
|
||||
|
||||
/// Absolute, no empty, `.` or `..` components (reference/intrinsics.md).
|
||||
pub fn validPath(path: []const u8) bool {
|
||||
if (path.len == 0 or path[0] != '/') return false;
|
||||
if (path.len == 1) return true;
|
||||
var it = std.mem.splitScalar(u8, path[1..], '/');
|
||||
while (it.next()) |part| {
|
||||
if (part.len == 0 or std.mem.eql(u8, part, ".") or std.mem.eql(u8, part, "..")) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Whether `path` lies within `scope` (null scope = whole file system).
|
||||
pub fn within(scope: ?[]const u8, path: []const u8) bool {
|
||||
const s = scope orelse return true;
|
||||
if (std.mem.eql(u8, s, "/")) return true;
|
||||
if (!std.mem.startsWith(u8, path, s)) return false;
|
||||
return path.len == s.len or path[s.len] == '/';
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ console
|
||||
|
||||
pub fn writeOut(w: *World, err_stream: bool, bytes: []const u8) !void {
|
||||
try (if (err_stream) &w.stderr else &w.stdout).appendSlice(w.arena, bytes);
|
||||
}
|
||||
|
||||
pub fn readIn(w: *World, buf: []u8) usize {
|
||||
const n = @min(buf.len, w.stdin.len - w.stdin_pos);
|
||||
@memcpy(buf[0..n], w.stdin[w.stdin_pos..][0..n]);
|
||||
w.stdin_pos += n;
|
||||
return n;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ files
|
||||
|
||||
pub fn open(w: *World, scope: ?[]const u8, path: []const u8, mode: air.authority.Resource) !Opened {
|
||||
if (!validPath(path)) return .{ .err = .invalid_input };
|
||||
if (!within(scope, path)) return .{ .err = .permission_denied };
|
||||
const owned = try w.arena.dupe(u8, path);
|
||||
switch (mode) {
|
||||
.file_read => if (!w.files.contains(owned)) return .{ .err = .not_found },
|
||||
.file_write => {
|
||||
try w.files.put(w.arena, owned, .empty);
|
||||
try w.written.put(w.arena, owned, {});
|
||||
},
|
||||
.file_append => {
|
||||
if (!w.files.contains(owned)) try w.files.put(w.arena, owned, .empty);
|
||||
try w.written.put(w.arena, owned, {});
|
||||
},
|
||||
else => unreachable,
|
||||
}
|
||||
return .{ .ok = try w.add(.{ .file = .{ .path = owned, .mode = mode, .pos = 0 } }) };
|
||||
}
|
||||
|
||||
pub fn fileRead(w: *World, h: u32, buf: []u8) usize {
|
||||
const f = &w.handles.items[h].file;
|
||||
const data = w.files.get(f.path).?.items;
|
||||
const n = @min(buf.len, data.len -| f.pos);
|
||||
@memcpy(buf[0..n], data[f.pos..][0..n]);
|
||||
f.pos += n;
|
||||
return n;
|
||||
}
|
||||
|
||||
pub fn fileWrite(w: *World, h: u32, bytes: []const u8) !void {
|
||||
const f = &w.handles.items[h].file;
|
||||
try w.files.getPtr(f.path).?.appendSlice(w.arena, bytes);
|
||||
}
|
||||
|
||||
pub fn close(w: *World, h: u32) void {
|
||||
switch (w.handles.items[h]) {
|
||||
.stream => |s| if (s.peer) |p| switch (w.handles.items[p]) {
|
||||
.stream => |*ps| ps.peer_closed = true,
|
||||
else => {},
|
||||
},
|
||||
.listener => |l| _ = w.listeners.remove(l.addr),
|
||||
else => {},
|
||||
}
|
||||
w.handles.items[h] = .closed;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ loopback TCP
|
||||
|
||||
/// `host:port` with a numeric IPv4 host.
|
||||
pub fn validAddr(addr: []const u8) bool {
|
||||
const colon = std.mem.lastIndexOfScalar(u8, addr, ':') orelse return false;
|
||||
_ = std.fmt.parseInt(u16, addr[colon + 1 ..], 10) catch return false;
|
||||
var it = std.mem.splitScalar(u8, addr[0..colon], '.');
|
||||
var n: usize = 0;
|
||||
while (it.next()) |part| : (n += 1) {
|
||||
_ = std.fmt.parseInt(u8, part, 10) catch return false;
|
||||
}
|
||||
return n == 4;
|
||||
}
|
||||
|
||||
pub fn listen(w: *World, addr: []const u8) !Opened {
|
||||
if (!validAddr(addr)) return .{ .err = .invalid_input };
|
||||
const owned = try w.arena.dupe(u8, addr);
|
||||
if (w.listeners.contains(owned)) return .{ .err = .address_in_use };
|
||||
const h = try w.add(.{ .listener = .{ .addr = owned } });
|
||||
try w.listeners.put(w.arena, owned, h);
|
||||
return .{ .ok = h };
|
||||
}
|
||||
|
||||
pub fn connect(w: *World, addr: []const u8) !Opened {
|
||||
if (!validAddr(addr)) return .{ .err = .invalid_input };
|
||||
const l = w.listeners.get(addr) orelse return .{ .err = .connection_refused };
|
||||
const client = try w.add(.{ .stream = .{ .peer = null } });
|
||||
const server = try w.add(.{ .stream = .{ .peer = client } });
|
||||
w.handles.items[client].stream.peer = server;
|
||||
try w.handles.items[l].listener.pending.append(w.arena, server);
|
||||
return .{ .ok = client };
|
||||
}
|
||||
|
||||
/// Null: nothing to accept, and nothing else can ever connect (the run
|
||||
/// has a single execution unit): the caller reports `blocked`.
|
||||
pub fn accept(w: *World, h: u32) ?u32 {
|
||||
const l = &w.handles.items[h].listener;
|
||||
if (l.pending.items.len == 0) return null;
|
||||
return l.pending.orderedRemove(0);
|
||||
}
|
||||
|
||||
pub fn send(w: *World, h: u32, bytes: []const u8) !?IoError {
|
||||
const s = w.handles.items[h].stream;
|
||||
if (s.peer_closed) return .broken_pipe;
|
||||
const p = s.peer orelse return .broken_pipe;
|
||||
try w.handles.items[p].stream.inbox.appendSlice(w.arena, bytes);
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Null: no data and the peer is open; nothing else can ever send, so
|
||||
/// the caller reports `blocked`.
|
||||
pub fn recv(w: *World, h: u32, buf: []u8) ?usize {
|
||||
const s = &w.handles.items[h].stream;
|
||||
const avail = s.inbox.items.len - s.read_pos;
|
||||
if (avail == 0) return if (s.peer_closed) 0 else null;
|
||||
const n = @min(buf.len, avail);
|
||||
@memcpy(buf[0..n], s.inbox.items[s.read_pos..][0..n]);
|
||||
s.read_pos += n;
|
||||
return n;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ random
|
||||
|
||||
pub fn fill(w: *World, buf: []u8) void {
|
||||
w.prng.random().bytes(buf);
|
||||
}
|
||||
};
|
||||
|
||||
test "paths and scopes" {
|
||||
try std.testing.expect(World.validPath("/data/a.txt"));
|
||||
try std.testing.expect(!World.validPath("data/a.txt"));
|
||||
try std.testing.expect(!World.validPath("/data/../etc"));
|
||||
try std.testing.expect(!World.validPath("/data//a"));
|
||||
try std.testing.expect(World.within("/data", "/data/a"));
|
||||
try std.testing.expect(!World.within("/data", "/database"));
|
||||
try std.testing.expect(World.within(null, "/x"));
|
||||
}
|
||||
|
||||
test "addresses" {
|
||||
try std.testing.expect(World.validAddr("127.0.0.1:8080"));
|
||||
try std.testing.expect(!World.validAddr("localhost:80"));
|
||||
try std.testing.expect(!World.validAddr("127.0.0.1:99999"));
|
||||
}
|
||||
+44
-8
@@ -7,7 +7,8 @@
|
||||
//! - exit codes: 0 accepted / returned, 1 rejected, 2 usage or I/O error,
|
||||
//! 3 input not decidable yet (pipeline stage unimplemented), 4 trapped,
|
||||
//! 5 execution limit exceeded (`--fuel`, spec 11 §7),
|
||||
//! 6 not instantiated (missing or invalid `--grant`, spec 05 §10.2).
|
||||
//! 6 not instantiated (missing or invalid `--grant`, spec 05 §10.2),
|
||||
//! 7 blocked: no future event can complete a wait (spec 11 §8).
|
||||
|
||||
const std = @import("std");
|
||||
const aji = @import("aji");
|
||||
@@ -20,7 +21,10 @@ const usage =
|
||||
\\ run [--fuel N] [--grant P=KIND[:SCOPE]]... <file.air>
|
||||
\\ verify, then run @main and print the run record;
|
||||
\\ --fuel stops after N executed instructions;
|
||||
\\ --grant binds capability parameter P of @main
|
||||
\\ --grant binds capability parameter P of @main;
|
||||
\\ deterministic world: --stdin TEXT, --vfs PATH=TEXT,
|
||||
\\ --seed N; --result-file PATH also writes the record;
|
||||
\\ --profile hosted is not implemented yet
|
||||
\\ codes list diagnostic codes as JSON Lines
|
||||
\\ features print supported AIR format, language version and features
|
||||
\\ explain <code> show one diagnostic code
|
||||
@@ -28,7 +32,7 @@ const usage =
|
||||
\\
|
||||
;
|
||||
|
||||
const ExitCode = enum(u8) { accepted = 0, rejected = 1, usage = 2, unimplemented = 3, trapped = 4, limit_exceeded = 5, not_instantiated = 6 };
|
||||
const ExitCode = enum(u8) { accepted = 0, rejected = 1, usage = 2, unimplemented = 3, trapped = 4, limit_exceeded = 5, not_instantiated = 6, blocked = 7 };
|
||||
|
||||
pub fn main(init: std.process.Init) !void {
|
||||
const arena = init.arena.allocator();
|
||||
@@ -80,16 +84,36 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
|
||||
if (std.mem.eql(u8, cmd, "check") or std.mem.eql(u8, cmd, "run")) {
|
||||
var options: aji.interp.Options = .{};
|
||||
var grants: std.ArrayList(aji.interp.Grant) = .empty;
|
||||
var files: std.ArrayList(struct { []const u8, []const u8 }) = .empty;
|
||||
var result_file: ?[]const u8 = null;
|
||||
var rest = args[2..];
|
||||
while (std.mem.eql(u8, cmd, "run") and rest.len >= 3) {
|
||||
if (std.mem.eql(u8, rest[0], "--fuel")) {
|
||||
options.fuel = std.fmt.parseInt(u64, rest[1], 10) catch return usageError("--fuel takes a non-negative integer");
|
||||
} else if (std.mem.eql(u8, rest[0], "--grant")) {
|
||||
try grants.append(arena, parseGrant(rest[1]) orelse return usageError("--grant takes <parameter>=<kind>[:<scope>]"));
|
||||
const flag = rest[0];
|
||||
const value = rest[1];
|
||||
if (std.mem.eql(u8, flag, "--fuel")) {
|
||||
options.fuel = std.fmt.parseInt(u64, value, 10) catch return usageError("--fuel takes a non-negative integer");
|
||||
} else if (std.mem.eql(u8, flag, "--grant")) {
|
||||
try grants.append(arena, parseGrant(value) orelse return usageError("--grant takes <parameter>=<kind>[:<scope>]"));
|
||||
} else if (std.mem.eql(u8, flag, "--profile")) {
|
||||
if (std.mem.eql(u8, value, "hosted")) {
|
||||
std.debug.print("aji: not implemented yet: hosted profile\n", .{});
|
||||
return .unimplemented;
|
||||
}
|
||||
if (!std.mem.eql(u8, value, "deterministic")) return usageError("--profile takes deterministic or hosted");
|
||||
} else if (std.mem.eql(u8, flag, "--stdin")) {
|
||||
options.world.stdin = value;
|
||||
} else if (std.mem.eql(u8, flag, "--vfs")) {
|
||||
const eq = std.mem.indexOfScalar(u8, value, '=') orelse return usageError("--vfs takes <path>=<text>");
|
||||
try files.append(arena, .{ value[0..eq], value[eq + 1 ..] });
|
||||
} else if (std.mem.eql(u8, flag, "--seed")) {
|
||||
options.world.seed = std.fmt.parseInt(u64, value, 10) catch return usageError("--seed takes a non-negative integer");
|
||||
} else if (std.mem.eql(u8, flag, "--result-file")) {
|
||||
result_file = value;
|
||||
} else break;
|
||||
rest = rest[2..];
|
||||
}
|
||||
options.grants = grants.items;
|
||||
options.world.files = files.items;
|
||||
if (rest.len != 1) return usageError("check and run take exactly one file");
|
||||
const path = rest[0];
|
||||
const source = std.Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(64 << 20)) catch |err| {
|
||||
@@ -103,18 +127,30 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
|
||||
}
|
||||
if (report.status == .accepted and std.mem.eql(u8, cmd, "run")) {
|
||||
const module = report.module.?;
|
||||
var output: aji.interp.Output = undefined;
|
||||
options.output = &output;
|
||||
const outcome = aji.interp.run(arena, module, "main", options) catch |err| switch (err) {
|
||||
error.EntryNotFound => return usageError("module has no @main whose parameters are all capabilities"),
|
||||
error.DuplicateGrant => return usageError("a parameter is granted more than once"),
|
||||
else => |e| return e,
|
||||
};
|
||||
try aji.interp.writeOutcome(module, outcome, out);
|
||||
try aji.interp.writeOutcome(module, outcome, output, out);
|
||||
try out.writeByte('\n');
|
||||
if (result_file) |rpath| {
|
||||
var rec: std.Io.Writer.Allocating = .init(arena);
|
||||
try aji.interp.writeOutcome(module, outcome, output, &rec.writer);
|
||||
try rec.writer.writeByte('\n');
|
||||
std.Io.Dir.cwd().writeFile(io, .{ .sub_path = rpath, .data = rec.written() }) catch |err| {
|
||||
std.debug.print("aji: cannot write {s}: {t}\n", .{ rpath, err });
|
||||
return .usage;
|
||||
};
|
||||
}
|
||||
return switch (outcome) {
|
||||
.returned => .accepted,
|
||||
.trapped => .trapped,
|
||||
.limit_exceeded => .limit_exceeded,
|
||||
.not_instantiated => .not_instantiated,
|
||||
.blocked => .blocked,
|
||||
};
|
||||
}
|
||||
return switch (report.status) {
|
||||
|
||||
+133
-29
@@ -26,6 +26,9 @@ const Seg = union(enum) {
|
||||
|
||||
const Mode = enum { shared, exclusive };
|
||||
|
||||
/// Why a resource is no longer live (spec 06 §6.3).
|
||||
const Dead = enum { none, closed, moved };
|
||||
|
||||
const Info = struct {
|
||||
/// Owned borrows are created in this function; lent ones are parameters.
|
||||
owned: bool,
|
||||
@@ -55,8 +58,10 @@ const Walker = struct {
|
||||
f: air.Function,
|
||||
types: []const air.Type,
|
||||
info: []?Info,
|
||||
/// Live owned borrows in the current block.
|
||||
/// Live owned borrows and live owned resources at the current point.
|
||||
live: []bool,
|
||||
/// How a resource stopped being live, for diagnostics.
|
||||
dead: []Dead,
|
||||
block: u32 = 0,
|
||||
index: u32 = 0,
|
||||
span: air.Span = .{ .line = 0, .col = 0 },
|
||||
@@ -107,7 +112,7 @@ const Walker = struct {
|
||||
fn access(w: *Walker, root: ValueId, path: []const Seg, mode: Mode, via: ?ValueId, who: ValueId) !void {
|
||||
for (w.live, 0..) |is_live, cv| {
|
||||
if (!is_live) continue;
|
||||
const ci = w.info[cv].?;
|
||||
const ci = w.info[cv] orelse continue; // live resources are not borrows
|
||||
if (ci.root != root) continue;
|
||||
if (via) |t| if (w.isAncestor(@intCast(cv), t)) continue;
|
||||
if (mode == .shared and ci.mode == .shared) continue;
|
||||
@@ -157,6 +162,32 @@ const Walker = struct {
|
||||
fn isLocal(w: *Walker, v: ValueId) bool {
|
||||
return w.types[v] == .local;
|
||||
}
|
||||
|
||||
fn isResource(w: *Walker, v: ValueId) bool {
|
||||
return w.types[v] == .resource;
|
||||
}
|
||||
|
||||
/// 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),
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// 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);
|
||||
}
|
||||
// Consumption is an exclusive access to the whole resource.
|
||||
try w.access(v, &.{}, .exclusive, null, v);
|
||||
w.live[v] = false;
|
||||
w.dead[v] = how;
|
||||
}
|
||||
};
|
||||
|
||||
pub fn overlap(a: []const Seg, b: []const Seg) bool {
|
||||
@@ -177,6 +208,35 @@ pub fn overlap(a: []const Seg, b: []const Seg) bool {
|
||||
return true; // one path is a prefix of the other
|
||||
}
|
||||
|
||||
const Edge = struct { target: u32, args: []const ValueId };
|
||||
|
||||
fn edges(op: air.Op, out: *std.ArrayList(Edge), arena: std.mem.Allocator) !void {
|
||||
switch (op) {
|
||||
.br => |t| try out.append(arena, .{ .target = t.block, .args = t.args }),
|
||||
.cbr => |x| {
|
||||
try out.append(arena, .{ .target = x.then.block, .args = x.then.args });
|
||||
try out.append(arena, .{ .target = x.@"else".block, .args = x.@"else".args });
|
||||
},
|
||||
.@"switch" => |x| {
|
||||
for (x.cases) |c| try out.append(arena, .{ .target = c.target.block, .args = c.target.args });
|
||||
try out.append(arena, .{ .target = x.default.block, .args = x.default.args });
|
||||
},
|
||||
.enum_switch => |x| {
|
||||
for (x.arms) |a| try out.append(arena, .{ .target = a.block, .args = &.{} });
|
||||
if (x.default) |d| try out.append(arena, .{ .target = d.block, .args = d.args });
|
||||
},
|
||||
.cap_narrow => |x| {
|
||||
try out.append(arena, .{ .target = x.ok, .args = &.{} });
|
||||
try out.append(arena, .{ .target = x.err, .args = &.{} });
|
||||
},
|
||||
.intrinsic => |x| if (x.ok) |ok| {
|
||||
try out.append(arena, .{ .target = ok, .args = &.{} });
|
||||
try out.append(arena, .{ .target = x.err.?, .args = &.{} });
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
}
|
||||
|
||||
fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void {
|
||||
var w: Walker = .{
|
||||
.c = c,
|
||||
@@ -184,18 +244,22 @@ fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void {
|
||||
.types = types,
|
||||
.info = try c.arena.alloc(?Info, f.values.len),
|
||||
.live = try c.arena.alloc(bool, f.values.len),
|
||||
.dead = try c.arena.alloc(Dead, f.values.len),
|
||||
};
|
||||
@memset(w.info, null);
|
||||
@memset(w.live, false);
|
||||
for (f.params) |p| if (p.ty.isBorrow()) {
|
||||
w.info[p.value] = .{
|
||||
@memset(w.dead, .none);
|
||||
for (f.params) |p| {
|
||||
if (p.ty.isBorrow()) w.info[p.value] = .{
|
||||
.owned = false,
|
||||
.mode = if (p.ty.isMutBorrow()) .exclusive else .shared,
|
||||
.root = p.value,
|
||||
.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;
|
||||
}
|
||||
|
||||
const dom = try ssa.dominators(c.arena, f);
|
||||
const entry_state = try c.arena.alloc(?[]bool, f.blocks.len);
|
||||
@@ -204,33 +268,51 @@ fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void {
|
||||
var reported_join = try c.arena.alloc(bool, f.blocks.len);
|
||||
@memset(reported_join, false);
|
||||
|
||||
var succ: std.ArrayList(u32) = .empty;
|
||||
var out: std.ArrayList(Edge) = .empty;
|
||||
for (dom.rpo) |b| {
|
||||
@memcpy(w.live, entry_state[b].?);
|
||||
w.block = b;
|
||||
const blk = f.blocks[b];
|
||||
// Resource block parameters own their argument from here on.
|
||||
for (blk.params) |p| if (p.ty == .resource) {
|
||||
w.live[p.value] = true;
|
||||
w.dead[p.value] = .none;
|
||||
};
|
||||
w.block = b;
|
||||
for (blk.insts, 0..) |inst, ii| {
|
||||
w.index = @intCast(ii);
|
||||
w.span = inst.span;
|
||||
try step(&w, inst);
|
||||
}
|
||||
// Propagate the exit state along every edge (§11.4).
|
||||
succ.clearRetainingCapacity();
|
||||
try air.successors(blk.insts[blk.insts.len - 1].op, &succ, c.arena);
|
||||
for (succ.items) |s| {
|
||||
if (entry_state[s]) |expected| {
|
||||
if (!std.mem.eql(bool, expected, w.live) and !reported_join[s]) {
|
||||
reported_join[s] = true;
|
||||
// Propagate along every edge; branch arguments of resource type are
|
||||
// moved on their own edge only (§11.4, spec 06 §6.2).
|
||||
out.clearRetainingCapacity();
|
||||
try edges(blk.insts[blk.insts.len - 1].op, &out, c.arena);
|
||||
const base = try c.arena.dupe(bool, w.live);
|
||||
const base_dead = try c.arena.dupe(Dead, w.dead);
|
||||
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);
|
||||
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) {
|
||||
try c.report("E2105", f.blocks[s].span, "borrow state differs between edges into this block", &.{
|
||||
const is_res = types[v] == .resource;
|
||||
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[s].name } },
|
||||
.{ .name = "borrow", .value = .{ .str = try c.valueName(f, @intCast(v)) } },
|
||||
.{ .name = "block", .value = .{ .str = f.blocks[e.target].name } },
|
||||
.{ .name = if (is_res) "resource" else "borrow", .value = .{ .str = try c.valueName(f, @intCast(v)) } },
|
||||
});
|
||||
break;
|
||||
};
|
||||
}
|
||||
} else entry_state[s] = try c.arena.dupe(bool, w.live);
|
||||
} else entry_state[e.target] = try c.arena.dupe(bool, w.live);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -245,6 +327,13 @@ fn step(w: *Walker, inst: air.Inst) !void {
|
||||
const r = inst.result.?;
|
||||
if (w.isLocal(x)) {
|
||||
try w.create(r, null, x, &.{});
|
||||
} else if (w.isResource(x)) {
|
||||
if (!try w.resourceUsable(x)) {
|
||||
w.info[r] = .{ .owned = true, .mode = .shared, .root = x, .path = &.{}, .parent = null };
|
||||
w.live[r] = true;
|
||||
return;
|
||||
}
|
||||
try w.create(r, null, x, &.{});
|
||||
} else try w.derive(r, x, null);
|
||||
},
|
||||
.borrow_field => |x| try w.derive(inst.result.?, x.borrow, .{ .field = x.field }),
|
||||
@@ -270,12 +359,29 @@ fn step(w: *Walker, inst: air.Inst) !void {
|
||||
// Ended even when rejected, so one mistake yields one diagnostic.
|
||||
defer w.live[v] = false;
|
||||
for (w.live, 0..) |is_live, cv| {
|
||||
if (is_live and w.info[cv].?.parent == v) {
|
||||
if (is_live and w.info[cv] != null and w.info[cv].?.parent == v) {
|
||||
return w.report("E2102", "borrow ended while a borrow derived from it is live", v, .{ "child", @intCast(cv) });
|
||||
}
|
||||
}
|
||||
},
|
||||
.call => |x| try callStep(w, inst, x.callee, x.args),
|
||||
.call => |x| {
|
||||
try lendArgs(w, x.args);
|
||||
const callee = w.c.module.functions[x.callee];
|
||||
for (x.args) |a| if (w.isResource(a)) try w.consume(a, .moved);
|
||||
if (callee.ret_from) |p| {
|
||||
// The result borrows from the argument passed for `from` (§11.3).
|
||||
const a = x.args[p];
|
||||
if (w.types[a].isBorrow() and w.info[a] != null) try w.derive(inst.result.?, a, .elem);
|
||||
}
|
||||
if (inst.result) |r| if (w.isResource(r)) {
|
||||
w.live[r] = true;
|
||||
};
|
||||
},
|
||||
.intrinsic => |x| {
|
||||
try lendArgs(w, x.args);
|
||||
// Closing intrinsics consume on both edges, so before propagation.
|
||||
for (x.args, air.authority.intrinsics[x.index].operands) |a, o| if (o == .consumed) try w.consume(a, .closed);
|
||||
},
|
||||
.ret => |v| try retStep(w, v),
|
||||
// Values of these instructions are not borrows; any borrow operand
|
||||
// here was already rejected by the type stage.
|
||||
@@ -284,8 +390,9 @@ fn step(w: *Walker, inst: air.Inst) !void {
|
||||
_ = f;
|
||||
}
|
||||
|
||||
fn callStep(w: *Walker, inst: air.Inst, callee_index: u32, args: []const ValueId) !void {
|
||||
const callee = w.c.module.functions[callee_index];
|
||||
/// Borrow arguments of a call or intrinsic are lent for its duration and
|
||||
/// must not alias each other when one is exclusive (§11.2).
|
||||
fn lendArgs(w: *Walker, args: []const ValueId) !void {
|
||||
// Arguments already reported; a conflict involving one of them is the
|
||||
// same mistake and is not reported again.
|
||||
const reported = try w.c.arena.alloc(bool, args.len);
|
||||
@@ -314,17 +421,12 @@ fn callStep(w: *Walker, inst: air.Inst, callee_index: u32, args: []const ValueId
|
||||
}
|
||||
}
|
||||
}
|
||||
if (callee.ret_from) |p| {
|
||||
// The result borrows from the argument passed for `from` (§11.3).
|
||||
const a = args[p];
|
||||
if (!w.types[a].isBorrow() or w.info[a] == null) return;
|
||||
try w.derive(inst.result.?, a, .elem);
|
||||
}
|
||||
}
|
||||
|
||||
fn retStep(w: *Walker, value: ?ValueId) !void {
|
||||
const f = w.f;
|
||||
var transferred: ?ValueId = null;
|
||||
if (value) |v| if (w.isResource(v)) try w.consume(v, .moved);
|
||||
if (f.ret_from) |p| {
|
||||
const pv = f.params[p].value;
|
||||
const b = value.?;
|
||||
@@ -342,7 +444,9 @@ fn retStep(w: *Walker, value: ?ValueId) !void {
|
||||
for (w.live, 0..) |is_live, v| {
|
||||
if (!is_live) continue;
|
||||
if (transferred) |t| if (w.isAncestor(@intCast(v), t)) continue;
|
||||
try w.report("E2105", "borrow not ended before return", @intCast(v), null);
|
||||
if (w.isResource(@intCast(v))) {
|
||||
try w.report("E3002", "resource not consumed before return", @intCast(v), null);
|
||||
} else try w.report("E2105", "borrow not ended before return", @intCast(v), null);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ 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 => 8,
|
||||
.ref, .mut, .cap, .resource => 8,
|
||||
.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,
|
||||
|
||||
@@ -77,6 +77,12 @@ 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");
|
||||
},
|
||||
// Fallible intrinsics: `ok` takes the registered results, `err` one `io_error`.
|
||||
.intrinsic => |x| {
|
||||
const reg = air.authority.intrinsics[x.index];
|
||||
try paramCount(c, f, inst.span, x.ok.?, reg.results.len, "intrinsic `ok` target parameters do not match its results");
|
||||
try paramCount(c, f, inst.span, x.err.?, 1, "intrinsic `err` target takes exactly one parameter");
|
||||
},
|
||||
.ret, .trap => {},
|
||||
else => unreachable,
|
||||
}
|
||||
|
||||
@@ -26,6 +26,13 @@ pub fn check(c: *Context) !void {
|
||||
});
|
||||
};
|
||||
},
|
||||
.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 } },
|
||||
.{ .name = "intrinsic", .value = .{ .str = air.authority.intrinsics[x.index].name } },
|
||||
.{ .name = "effect", .value = .{ .str = e } },
|
||||
});
|
||||
},
|
||||
else => {},
|
||||
};
|
||||
}
|
||||
|
||||
+102
-3
@@ -84,7 +84,7 @@ 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 => pos != .member,
|
||||
.ref, .mut, .slice, .slice_mut, .resource => pos != .member,
|
||||
else => true,
|
||||
};
|
||||
if (!ok) try c.report("E1001", span, "type not allowed in this position", &.{
|
||||
@@ -182,11 +182,103 @@ fn resultType(m: air.Module, op: air.Op) ?Type {
|
||||
.enum_make => |x| .{ .named = x.decl },
|
||||
.call => |x| m.functions[x.callee].ret,
|
||||
.slice_len => .{ .int = .usize },
|
||||
.intrinsic => |x| blk: {
|
||||
const reg = air.authority.intrinsics[x.index];
|
||||
if (reg.fallible or reg.results.len == 0) break :blk .void;
|
||||
break :blk intrinsicResult(reg.results[0]);
|
||||
},
|
||||
.array_splat => |x| x.ty,
|
||||
else => null,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn intrinsicResult(r: air.authority.ResultType) Type {
|
||||
return switch (r) {
|
||||
.usize => .{ .int = .usize },
|
||||
.u64 => .{ .int = .u64 },
|
||||
.resource => |res| .{ .resource = res },
|
||||
};
|
||||
}
|
||||
|
||||
fn operandText(arena: std.mem.Allocator, o: air.authority.Operand) ![]const u8 {
|
||||
return switch (o) {
|
||||
.cap => |k| std.fmt.allocPrint(arena, "cap<{s}>", .{k}),
|
||||
.bytes => "slice<u8>",
|
||||
.buffer => "slice_mut<u8>",
|
||||
.borrowed => |rs| blk: {
|
||||
var w: std.Io.Writer.Allocating = .init(arena);
|
||||
for (rs, 0..) |r, i| w.writer.print("{s}mut<{s}>", .{ if (i == 0) "" else " or ", r.text() }) catch return error.OutOfMemory;
|
||||
break :blk w.written();
|
||||
},
|
||||
.consumed => |rs| blk: {
|
||||
var w: std.Io.Writer.Allocating = .init(arena);
|
||||
for (rs, 0..) |r, i| w.writer.print("{s}{s}", .{ if (i == 0) "" else " or ", r.text() }) catch return error.OutOfMemory;
|
||||
break :blk w.written();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
fn operandMatches(o: air.authority.Operand, t: Type) bool {
|
||||
return switch (o) {
|
||||
.cap => t == .cap, // the kind is checked separately (E3201)
|
||||
.bytes => t == .slice and t.slice.* == .int and t.slice.int == .u8,
|
||||
.buffer => t == .slice_mut and t.slice_mut.* == .int and t.slice_mut.int == .u8,
|
||||
.borrowed => |rs| t == .mut and t.mut.* == .resource and std.mem.indexOfScalar(air.authority.Resource, rs, t.mut.resource) != null,
|
||||
.consumed => |rs| t == .resource and std.mem.indexOfScalar(air.authority.Resource, rs, t.resource) != null,
|
||||
};
|
||||
}
|
||||
|
||||
fn checkIntrinsic(fc: *FnCtx, inst: air.Inst, x: @FieldType(air.Op, "intrinsic")) !void {
|
||||
const f = fc.f;
|
||||
const span = inst.span;
|
||||
const reg = air.authority.intrinsics[x.index];
|
||||
if (reg.fallible != (x.ok != null)) {
|
||||
return fc.c.report("E1001", span, if (reg.fallible) "intrinsic is fallible: use the `, ok -> @a, err -> @b` form" else "intrinsic is infallible: it has no `ok`/`err` targets", &.{
|
||||
.{ .name = "function", .value = .{ .str = f.name } },
|
||||
.{ .name = "intrinsic", .value = .{ .str = reg.name } },
|
||||
});
|
||||
}
|
||||
if (x.args.len != reg.operands.len) {
|
||||
return fc.c.report("E1001", span, "wrong number of intrinsic operands", &.{
|
||||
.{ .name = "function", .value = .{ .str = f.name } },
|
||||
.{ .name = "intrinsic", .value = .{ .str = reg.name } },
|
||||
.{ .name = "expected", .value = .{ .int = @intCast(reg.operands.len) } },
|
||||
.{ .name = "found", .value = .{ .int = @intCast(x.args.len) } },
|
||||
});
|
||||
}
|
||||
for (x.args, reg.operands) |a, o| {
|
||||
const t = fc.typeOf(a);
|
||||
if (!operandMatches(o, t)) {
|
||||
try fc.kindError(span, a, try operandText(fc.c.arena, o));
|
||||
continue;
|
||||
}
|
||||
if (o == .cap and !std.mem.eql(u8, air.authority.kinds[t.cap].name, o.cap)) {
|
||||
try fc.c.report("E3201", span, "capability of the wrong kind for this intrinsic", &.{
|
||||
.{ .name = "function", .value = .{ .str = f.name } },
|
||||
.{ .name = "intrinsic", .value = .{ .str = reg.name } },
|
||||
.{ .name = "expected", .value = .{ .str = o.cap } },
|
||||
.{ .name = "found", .value = .{ .str = air.authority.kinds[t.cap].name } },
|
||||
});
|
||||
}
|
||||
}
|
||||
if (x.ok) |ok| {
|
||||
if (inst.result != null) return fc.c.report("E1001", span, "a fallible intrinsic delivers results to its `ok` block parameters", &.{
|
||||
.{ .name = "function", .value = .{ .str = f.name } },
|
||||
});
|
||||
for (f.blocks[ok].params, reg.results) |p, r| {
|
||||
const want = intrinsicResult(r);
|
||||
if (!p.ty.eql(want)) try fc.mismatch(span, try fc.c.valueName(f, p.value), want, p.ty);
|
||||
}
|
||||
const e = f.blocks[x.err.?].params[0];
|
||||
if (!e.ty.eql(.{ .builtin = .io_error })) try fc.mismatch(span, try fc.c.valueName(f, e.value), .{ .builtin = .io_error }, e.ty);
|
||||
} else if (inst.result != null and reg.results.len == 0) {
|
||||
try fc.c.report("E1001", span, "intrinsic has no result to bind", &.{
|
||||
.{ .name = "function", .value = .{ .str = f.name } },
|
||||
.{ .name = "intrinsic", .value = .{ .str = reg.name } },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn boxed(arena: std.mem.Allocator, t: Type) !*const Type {
|
||||
const b = try arena.create(Type);
|
||||
b.* = t;
|
||||
@@ -215,11 +307,13 @@ 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) },
|
||||
.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) },
|
||||
.slice_mut => .{ .slice_mut = try boxed(a, t.inner().?) },
|
||||
else => invalid,
|
||||
},
|
||||
@@ -322,8 +416,8 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
|
||||
});
|
||||
},
|
||||
.local_load => |v| if (fc.typeOf(v) != .local) try fc.kindError(span, v, "local<T>"),
|
||||
.borrow_ref => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "local<T>, ref<T>, mut<T>, slice<T> or slice_mut<T>"),
|
||||
.borrow_mut => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "local<T>, mut<T> or slice_mut<T>"),
|
||||
.borrow_ref => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "local<T>, a resource, ref<T>, mut<T>, slice<T> or slice_mut<T>"),
|
||||
.borrow_mut => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "local<T>, a resource, mut<T> or slice_mut<T>"),
|
||||
.borrow_field => |x| if (resultOf(fc, inst) == .void) try fc.kindError(span, x.borrow, "ref or mut of the named struct"),
|
||||
.borrow_end => |v| if (!fc.typeOf(v).isBorrow()) try fc.kindError(span, v, "a borrow"),
|
||||
.load => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "ref<T> or mut<T>"),
|
||||
@@ -427,6 +521,7 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
|
||||
}
|
||||
if (x.default) |d| try fc.expectTarget(span, d);
|
||||
},
|
||||
.intrinsic => |x| try checkIntrinsic(fc, inst, x),
|
||||
.cap_narrow => |x| {
|
||||
const t = fc.typeOf(x.cap);
|
||||
if (t != .cap) return fc.kindError(span, x.cap, "cap<K>");
|
||||
@@ -437,6 +532,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, "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>");
|
||||
}
|
||||
const ok = f.blocks[x.ok].params[0];
|
||||
if (!ok.ty.eql(t)) try fc.mismatch(span, try fc.c.valueName(f, ok.value), t, ok.ty);
|
||||
const err = f.blocks[x.err].params[0];
|
||||
|
||||
Reference in new issue
Block a user