Phase 3: structured tasks and the deterministic scheduler (RFC 0011)

- interpreter core rewritten around explicit per-task frame stacks so a
  task can be suspended at any instruction; behavior of all existing
  tests unchanged
- tasks: scope and task<T> (function-bound; task_transfer and
  task_borrow_returns reserved), spawn/join/cancel/cancelled/scope.end;
  cooperative scheduler with seeded choice rule, separate schedule seed,
  quantum = fuel unit, task limit (limit_exceeded kind tasks), global
  quiescence over waiting tasks; schedule field in the run record
- verifier: Send/Share table (E4001, E4002), loans as task-owned borrows
  (E4302 on early end, E4101 on conflicts), E4301 at scope end, task
  effects (E3101)
- CLI --quantum, --task-limit, --schedule-seed; runner schedules:,
  quantum:, task_limit:, limit_exceeded:
- fixed: schedule seed default used orelse/^ precedence wrongly
- 15 phase-3 conformance tests; 4000 mutants without a crash
- Agent Reference Bundle +10.9 % tokens (recorded)
This commit is contained in:
dev committed 2026-10-04 16:02:03 +03:00
1 parent 2289917af3
commit ab5814a7bb
31 files changed
+1252 -94

No files matched your search

+4 -3
View File
@@ -36,12 +36,14 @@ pub const registry = [_]Feature{
.{ .name = "resource_joins", .depends = &.{ "capabilities", "effects", "ownership", "resources" }, .status = .reserved, .phase = null },
.{ .name = "resources", .depends = &.{ "capabilities", "effects", "ownership" }, .status = .published, .phase = 2 },
.{ .name = "sync", .depends = &.{"ownership"}, .status = .reserved, .phase = 3 },
.{ .name = "tasks", .depends = &.{"ownership"}, .status = .reserved, .phase = 3 },
.{ .name = "task_borrow_returns", .depends = &.{ "ownership", "tasks" }, .status = .reserved, .phase = null },
.{ .name = "task_transfer", .depends = &.{ "ownership", "tasks" }, .status = .reserved, .phase = null },
.{ .name = "tasks", .depends = &.{"ownership"}, .status = .published, .phase = 3 },
.{ .name = "unsafe", .depends = &.{ "arrays", "effects", "ownership" }, .status = .published, .phase = 2 },
};
/// Features implemented by this toolchain, sorted.
pub const supported = [_][]const u8{ "arrays", "capabilities", "effects", "heap", "ownership", "regions", "resources", "unsafe" };
pub const supported = [_][]const u8{ "arrays", "capabilities", "effects", "heap", "ownership", "regions", "resources", "tasks", "unsafe" };
pub const Reason = enum {
unknown_feature,
@@ -119,7 +121,6 @@ const test_registry = [_]Feature{
.{ .name = "regions", .depends = &.{"ownership"}, .status = .published, .phase = 1 },
.{ .name = "islands", .depends = &.{ "ownership", "regions" }, .status = .published, .phase = 4 },
.{ .name = "tasks", .depends = &.{"ownership"}, .status = .reserved, .phase = 3 },
.{ .name = "unsafe", .depends = &.{ "arrays", "effects", "ownership" }, .status = .published, .phase = 2 },
};
fn expectProblems(declared: []const []const u8, sup: []const []const u8, want: []const Reason) !void {
+26 -6
View File
@@ -83,6 +83,9 @@ pub const Type = union(enum) {
own: *const Type,
own_array: *const Type,
region,
// Feature `tasks` (spec 04 §33).
scope,
task: *const Type,
pub const Array = struct { elem: Type, len: u64 };
@@ -91,8 +94,8 @@ pub const Type = union(enum) {
return switch (a) {
.int => |x| b.int == x,
.named => |x| b.named == x,
.local, .ref, .mut, .slice, .slice_mut, .own, .own_array => |x| x.eql(b.inner().?),
.region => true,
.local, .ref, .mut, .slice, .slice_mut, .own, .own_array, .task => |x| x.eql(b.inner().?),
.region, .scope => true,
.array => |x| x.len == b.array.len and x.elem.eql(b.array.elem),
.cap => |k| b.cap == k,
.builtin => |e| b.builtin == e,
@@ -104,7 +107,7 @@ pub const Type = union(enum) {
/// Element or pointee type of storage, borrow and slice types.
pub fn inner(t: Type) ?Type {
return switch (t) {
.local, .ref, .mut, .slice, .slice_mut, .own, .own_array => |x| x.*,
.local, .ref, .mut, .slice, .slice_mut, .own, .own_array, .task => |x| x.*,
.array => |a| a.elem,
else => null,
};
@@ -121,11 +124,16 @@ pub const Type = union(enum) {
/// Linear values: consumed exactly once (spec 06 §6.2–§6.3).
pub fn isLinear(t: Type) bool {
return switch (t) {
.resource, .own, .own_array, .region => true,
.resource, .own, .own_array, .region, .scope, .task => true,
else => false,
};
}
/// Function-bound types (spec 04 §33.1): never parameters, results or members.
pub fn isTaskBound(t: Type) bool {
return t == .scope or t == .task;
}
pub fn isMutBorrow(t: Type) bool {
return t == .mut or t == .slice_mut;
}
@@ -139,7 +147,7 @@ pub const Type = union(enum) {
/// Linear resources are neither values nor borrows: they are moved.
pub fn isValue(t: Type) bool {
return switch (t) {
.void, .never, .local, .ref, .mut, .slice, .slice_mut, .resource, .own, .own_array, .region => false,
.void, .never, .local, .ref, .mut, .slice, .slice_mut, .resource, .own, .own_array, .region, .scope, .task => false,
else => true,
};
}
@@ -266,6 +274,13 @@ pub const Op = union(enum) {
region_array: struct { region: ValueId, n: ValueId, value: ValueId, ok: u32, err: u32 },
region_reset: ValueId,
region_destroy: ValueId,
// Feature `tasks` (spec 04 §33).
task_scope_begin,
task_spawn: struct { scope: ValueId, callee: u32, args: []const ValueId },
task_join: ValueId,
task_cancel: ValueId,
task_cancelled,
task_scope_end: ValueId,
ret: ?ValueId,
trap,
@@ -414,7 +429,12 @@ pub fn forEachUse(op: Op, ctx: anytype, comptime f: fn (@TypeOf(ctx), ValueId) v
f(ctx, x.value);
f(ctx, x.cap);
},
.own_take, .own_free, .region_reset, .region_destroy => |v| f(ctx, v),
.own_take, .own_free, .region_reset, .region_destroy, .task_join, .task_cancel, .task_scope_end => |v| f(ctx, v),
.task_scope_begin, .task_cancelled => {},
.task_spawn => |x| {
f(ctx, x.scope);
for (x.args) |v| f(ctx, v);
},
.region_create => |x| f(ctx, x.cap),
.region_new => |x| {
f(ctx, x.region);
+45 -2
View File
@@ -499,6 +499,10 @@ const Parser = struct {
try p.requireFeature(b.feature(), t.span, t.text);
return .{ .builtin = b };
}
if (eql(t.text, "scope")) {
try p.requireFeature("tasks", t.span, t.text);
return .scope;
}
if (eql(t.text, "region")) {
try p.requireFeature("regions", t.span, t.text);
return .region;
@@ -547,6 +551,15 @@ const Parser = struct {
boxed.* = inner;
return if (eql(t.text, "own")) .{ .own = boxed } else .{ .own_array = boxed };
}
if (eql(t.text, "task")) {
try p.requireFeature("tasks", t.span, "task");
_ = try p.expect(.lt, "`<`");
const inner = try p.parseType();
_ = try p.expect(.gt, "`>`");
const boxed = try p.arena.create(air.Type);
boxed.* = inner;
return .{ .task = boxed };
}
if (eql(t.text, "cap")) {
try p.requireFeature("capabilities", t.span, "cap");
_ = try p.expect(.lt, "`<`");
@@ -600,6 +613,7 @@ const Parser = struct {
/// Resources inside aggregates need the reserved feature `linear_aggregates`.
fn gateLinearMember(p: *Parser, t: air.Type, span: Span) Error!void {
if (t.isTaskBound()) return p.requireFeature("task_transfer", span, "task handle or scope as a member");
if (t.isLinear()) try p.requireFeature("linear_aggregates", span, "linear value as a member");
}
@@ -633,7 +647,9 @@ const Parser = struct {
while (p.peek().tag != .r_paren) {
const v = try p.expect(.local, "parameter");
_ = try p.expect(.colon, "`:`");
const ty_span = p.peek().span;
const ty = try p.parseType();
if (ty.isTaskBound()) try p.requireFeature("task_transfer", ty_span, "task handle or scope as a parameter");
const id = try p.defineValue(v, .{ .param = @intCast(params.items.len) });
try params.append(p.arena, .{ .value = id, .ty = ty });
if (p.peek().tag != .comma) break;
@@ -641,7 +657,9 @@ const Parser = struct {
}
_ = try p.expect(.r_paren, "`)`");
_ = try p.expect(.arrow, "`->`");
const ret_span = p.peek().span;
const ret = try p.parseType();
if (ret.isTaskBound()) try p.requireFeature("task_transfer", ret_span, "task handle or scope as a result");
var ret_from: ?u32 = null;
if (p.atWord("from")) {
const from_tok = p.next();
@@ -955,6 +973,7 @@ const Parser = struct {
break :op .{ .cap_narrow = .{ .form = parts[2], .cap = c, .args = args.items, .ok = ok, .err = err } };
}
if (try p.parseAllocOp(op_tok)) |aop| break :op aop;
if (try p.parseTaskOp(op_tok)) |top| break :op top;
if (eql(op_tok.text, "intrinsic")) {
try p.requireFeature("capabilities", op_tok.span, "intrinsic");
const name = try p.expect(.word, "intrinsic name");
@@ -981,13 +1000,13 @@ const Parser = struct {
_ = try p.expect(.nl, "end of line");
const produces_value = switch (op) {
.own_take => true,
.own_take, .task_scope_begin, .task_spawn, .task_cancelled => true,
.@"const", .copy, .arith, .bit, .cmp, .cast, .struct_make, .struct_get, .enum_make => true,
.local_alloc, .local_load, .borrow_ref, .borrow_mut, .borrow_field, .load => true,
.array_splat, .borrow_index, .slice_make, .slice_len, .slice_sub, .slice_split => true,
else => false,
};
const may_bind = produces_value or op == .call or op == .intrinsic;
const may_bind = produces_value or op == .call or op == .intrinsic or op == .task_join;
if (result_tok) |rt| {
if (!may_bind) return p.fail(rt, "instruction without result binding");
} else if (produces_value) {
@@ -1013,6 +1032,30 @@ const Parser = struct {
return .{ ok, try p.blockRef() };
}
/// Instructions of the feature `tasks` (spec 04 §33).
fn parseTaskOp(p: *Parser, op_tok: Token) Error!?air.Op {
const Name = enum { @"task.scope.begin", @"task.spawn", @"task.join", @"task.cancel", @"task.cancelled", @"task.scope.end" };
const name = std.meta.stringToEnum(Name, op_tok.text) orelse return null;
try p.requireFeature("tasks", op_tok.span, op_tok.text);
return switch (name) {
.@"task.scope.begin" => .task_scope_begin,
.@"task.spawn" => blk: {
const s = try p.useValue();
_ = try p.expect(.comma, "`,`");
const callee_tok = try p.expect(.global, "function name");
const callee = indexOf(p.fn_names.items, callee_tok.text) orelse c: {
try p.report("E0004", callee_tok.span, "unknown function", &.{.{ .name = "name", .value = .{ .str = callee_tok.text } }});
break :c 0;
};
break :blk .{ .task_spawn = .{ .scope = s, .callee = @intCast(callee), .args = try p.valueList() } };
},
.@"task.join" => .{ .task_join = try p.useValue() },
.@"task.cancel" => .{ .task_cancel = try p.useValue() },
.@"task.cancelled" => .task_cancelled,
.@"task.scope.end" => .{ .task_scope_end = try p.useValue() },
};
}
/// Instructions of the features `heap` and `regions` (spec 03 §19–§20).
fn parseAllocOp(p: *Parser, op_tok: Token) Error!?air.Op {
const Name = enum { @"own.new", @"own.array", @"own.take", @"own.free", @"region.create", @"region.new", @"region.array", @"region.reset", @"region.destroy" };
+17
View File
@@ -121,6 +121,12 @@ pub fn printType(m: air.Module, t: air.Type, w: *Writer) Writer.Error!void {
try w.writeByte('>');
},
.region => try w.writeAll("region"),
.scope => try w.writeAll("scope"),
.task => |inner| {
try w.writeAll("task<");
try printType(m, inner.*, w);
try w.writeByte('>');
},
.bool, .void, .never => try w.writeAll(@tagName(t)),
}
}
@@ -330,6 +336,17 @@ fn printOp(m: air.Module, f: air.Function, op: air.Op, w: *Writer) Writer.Error!
try okErr(f, w, x.ok, x.err);
},
.region_reset => |v| try one(f, w, "region.reset", v),
.task_scope_begin => try w.writeAll("task.scope.begin"),
.task_spawn => |x| {
try w.writeAll("task.spawn ");
try value(f, x.scope, w);
try w.print(", @{s}", .{m.functions[x.callee].name});
try values(f, x.args, w);
},
.task_join => |v| try one(f, w, "task.join", v),
.task_cancel => |v| try one(f, w, "task.cancel", v),
.task_cancelled => try w.writeAll("task.cancelled"),
.task_scope_end => |v| try one(f, w, "task.scope.end", v),
.region_destroy => |v| try one(f, w, "region.destroy", v),
.cap_narrow => |x| {
try w.print("cap.narrow.{s} ", .{x.form});
+233 -63
View File
@@ -41,6 +41,9 @@ pub const Value = union(enum) {
own: *Cell,
/// `region`: index into the machine's region table.
region: u32,
/// `scope` (no runtime state) and `task<T>` (index into the task table).
scope,
task: u32,
/// Value of a built-in enum such as `cap_error`.
builtin: struct { which: air.authority.Builtin, variant: u32 },
@@ -72,7 +75,7 @@ pub const Outcome = union(enum) {
returned: Value,
trapped: Trap,
/// The runner's fuel ran out (spec 11 §7). Not a trap.
limit_exceeded: struct { limit: u64, steps: u64 },
limit_exceeded: struct { kind: []const u8, 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
@@ -122,6 +125,11 @@ pub const Options = struct {
output: ?*Output = null,
/// Non-null selects the `hosted` profile (spec 11 §8): real I/O through `io`.
hosted: ?std.Io = null,
/// Scheduler (spec 04 §36): instructions per quantum, task slots, and the
/// schedule seed (default: program seed XOR "SCHEDULE").
quantum: u64 = 1000,
task_limit: u64 = 1024,
schedule_seed: ?u64 = null,
};
/// Observable output of a run in the deterministic profile.
@@ -130,6 +138,8 @@ pub const Output = struct {
stderr: []const u8,
/// Files written during the run, sorted by path.
files: []const struct { []const u8, []const u8 },
/// Present when the run spawned tasks (spec 04 §36.4).
schedule: ?struct { seed: u64, quantum: u64, choices: u64 } = null,
};
pub const Error = std.mem.Allocator.Error || error{ EntryNotFound, DuplicateGrant };
@@ -142,6 +152,11 @@ pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, opti
for (f.params) |p| if (p.ty != .cap) return error.EntryNotFound;
var m: Machine = .{ .arena = arena, .module = module, .fuel = options.fuel, .world = try .init(arena, options.world) };
if (options.hosted) |io| m.host = .{ .arena = arena, .io = io };
m.quantum = @max(options.quantum, 1);
m.task_limit = options.task_limit;
// Parenthesized: `orelse` binds tighter than `^`.
m.schedule_seed = options.schedule_seed orelse (options.world.seed ^ 0x5343484544554c45);
m.sched = .init(m.schedule_seed);
defer if (m.host) |*hs| hs.deinit();
defer if (options.output) |o| {
o.* = m.output() catch .{ .stdout = "", .stderr = "", .files = &.{} };
@@ -178,12 +193,7 @@ pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, opti
if (!known) return .{ .not_instantiated = .{ .reason = "unknown_parameter", .parameter = g.parameter } };
}
return switch (try m.call(idx, args)) {
.value => |v| .{ .returned = v },
.trap => |t| .{ .trapped = t },
.limit_exceeded => .{ .limit_exceeded = .{ .limit = m.fuel.?, .steps = m.steps } },
.blocked => |l| .{ .blocked = l },
};
return m.runProgram(idx, args);
}
const TrapKind = enum {
@@ -224,13 +234,39 @@ fn kindOf(e: TrapError) TrapKind {
};
}
const CallResult = union(enum) { value: Value, trap: Trap, limit_exceeded, blocked: Location };
pub const Wait = union(enum) {
join: u32,
accept: u32,
recv: u32,
};
const Frame = struct { func: u32, vals: []Value, block: u32, inst: u32 };
const Task = struct {
frames: std.ArrayList(Frame) = .empty,
state: enum { runnable, waiting, done } = .runnable,
result: Value = .void,
cancel: bool = false,
wait: Wait = .{ .join = 0 },
wait_at: Location = .{ .function = "", .block = "", .inst = 0 },
fuel_paid: bool = false,
};
const Machine = struct {
arena: std.mem.Allocator,
module: air.Module,
depth: u32 = 0,
fuel: ?u64,
tasks: std.ArrayList(Task) = .empty,
current: u32 = 0,
quantum: u64 = 1000,
quantum_used: u64 = 0,
task_limit: u64 = 1024,
sched: world_mod.Prng = .init(0),
schedule_seed: u64 = 0,
choices: u64 = 0,
/// Live task slots (spawned and not yet joined).
live_tasks: u64 = 0,
spawned: bool = false,
/// Host authority table; capabilities index into it.
authorities: std.ArrayList(Authority) = .empty,
world: world_mod.World,
@@ -240,42 +276,120 @@ const Machine = struct {
/// Instructions executed so far.
steps: u64 = 0,
fn call(m: *Machine, fn_index: u32, args: []const Value) std.mem.Allocator.Error!CallResult {
const f = m.module.functions[fn_index];
m.depth += 1;
defer m.depth -= 1;
// ------------------------------------------------------------ tasks and the scheduler (spec 04 §36)
/// Runs task 0 (`@main`) and every task it spawns until the program
/// returns, traps, or the environment stops it.
fn runProgram(m: *Machine, fn_index: u32, args: []const Value) std.mem.Allocator.Error!Outcome {
try m.tasks.append(m.arena, .{});
try m.pushFrame(0, fn_index, args);
while (true) {
const t = &m.tasks.items[m.current];
if (t.state != .runnable) {
if (try m.schedule()) |o| return o;
continue;
}
const frame = &t.frames.items[t.frames.items.len - 1];
const f = m.module.functions[frame.func];
const b = f.blocks[frame.block];
const inst = b.insts[frame.inst];
const here: Location = .{ .function = f.name, .block = b.name, .inst = frame.inst };
// Fuel is consumed when an instruction begins (spec 11 §7.1); a
// blocked instruction paid when it first began (spec 04 §36.3).
if (!t.fuel_paid) {
if (m.fuel) |limit| if (m.steps >= limit) return .{ .limit_exceeded = .{ .kind = "fuel", .limit = limit, .steps = m.steps } };
m.steps += 1;
m.quantum_used += 1;
}
t.fuel_paid = false;
switch (try m.exec(f, frame.vals, inst)) {
.next => frame.inst += 1,
.jump => |target| {
frame.block = target;
frame.inst = 0;
},
.call => |c| {
if (t.frames.items.len >= call_depth_limit) return .{ .trapped = .{ .code = TrapKind.call_depth.code(), .function = here.function, .block = here.block, .inst = here.inst } };
try m.pushFrame(m.current, c.callee, c.args);
},
.ret => |v| {
_ = t.frames.pop();
if (t.frames.items.len == 0) {
t.state = .done;
t.result = v;
if (m.current == 0) return .{ .returned = v };
if (try m.schedule()) |o| return o;
continue;
}
const caller = &t.frames.items[t.frames.items.len - 1];
const call_inst = m.module.functions[caller.func].blocks[caller.block].insts[caller.inst];
if (call_inst.result) |r| caller.vals[r] = v;
caller.inst += 1;
},
.trap => |k| return .{ .trapped = .{ .code = k.code(), .function = here.function, .block = here.block, .inst = here.inst } },
.wait => |w| {
t.state = .waiting;
t.wait = w;
t.wait_at = here;
t.fuel_paid = true;
if (try m.schedule()) |o| return o;
continue;
},
.yield => {
frame.inst += 1;
if (try m.schedule()) |o| return o;
continue;
},
.task_limit => return .{ .limit_exceeded = .{ .kind = "tasks", .limit = m.task_limit, .steps = m.steps } },
}
if (m.quantum_used >= m.quantum) {
if (try m.schedule()) |o| return o;
}
}
}
fn pushFrame(m: *Machine, task: u32, fn_index: u32, args: []const Value) !void {
const f = m.module.functions[fn_index];
const vals = try m.arena.alloc(Value, f.values.len);
for (f.params, args) |p, a| vals[p.value] = a;
try m.tasks.items[task].frames.append(m.arena, .{ .func = fn_index, .vals = vals, .block = 0, .inst = 0 });
}
var block: u32 = 0;
while (true) {
const b = f.blocks[block];
for (b.insts, 0..) |inst, ii| {
// Fuel is consumed when an instruction begins (spec 11 §7.1).
if (m.fuel) |limit| if (m.steps >= limit) return .limit_exceeded;
m.steps += 1;
const step = try m.exec(f, vals, inst);
switch (step) {
.next => {},
.jump => |t| {
block = t;
break;
},
.ret => |v| return .{ .value = v },
.trap => |k| return .{ .trap = .{
.code = k.code(),
.function = f.name,
.block = b.name,
.inst = @intCast(ii),
} },
.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
/// Whether a waiting task's condition holds now.
fn ready(m: *Machine, w: Wait) bool {
return switch (w) {
.join => |id| m.tasks.items[id].state == .done,
.accept => |hd| m.world.handles.items[hd].listener.pending.items.len != 0,
.recv => |hd| blk: {
const st = m.world.handles.items[hd].stream;
break :blk st.inbox.items.len > st.read_pos or st.peer_closed;
},
};
}
/// A scheduling point (spec 04 §36.2): wakes ready waiters and picks the
/// next runnable task. Returns an outcome only at global quiescence.
fn schedule(m: *Machine) !?Outcome {
m.quantum_used = 0;
for (m.tasks.items) |*t| if (t.state == .waiting and m.ready(t.wait)) {
t.state = .runnable;
};
var runnable: std.ArrayList(u32) = .empty;
for (m.tasks.items, 0..) |t, i| if (t.state == .runnable) try runnable.append(m.arena, @intCast(i));
if (runnable.items.len == 0) {
// Global quiescence (spec 11 §8): unfinished tasks, none runnable,
// no known future event. Report the oldest waiting task.
for (m.tasks.items) |t| if (t.state == .waiting) return .{ .blocked = t.wait_at };
unreachable; // task 0 finishing returns before scheduling
}
if (runnable.items.len == 1) {
m.current = runnable.items[0]; // no choice to make: no draw
return null;
}
const x = m.sched.next();
m.choices += 1;
m.current = runnable.items[x % runnable.items.len];
return null;
}
const Step = union(enum) {
@@ -283,11 +397,15 @@ const Machine = struct {
jump: u32,
ret: Value,
trap: TrapKind,
/// A trap raised inside a callee, already located.
nested_trap: Trap,
limit_exceeded,
blocked,
nested_blocked: Location,
/// Push a frame; the call instruction completes when it returns.
call: struct { callee: u32, args: []const Value },
/// The instruction cannot complete now; the task waits and the
/// instruction is resumed later without paying fuel again.
wait: Wait,
/// The instruction completed and is a scheduling point.
yield,
/// `task.spawn` would exceed the deterministic task limit.
task_limit,
};
fn exec(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst) std.mem.Allocator.Error!Step {
@@ -345,19 +463,7 @@ const Machine = struct {
.variant = x.variant,
.fields = try m.gatherMut(vals, x.args),
} }),
.call => |x| {
if (m.depth >= call_depth_limit) return .{ .trap = .call_depth };
const args = try m.gather(vals, x.args);
switch (try m.call(x.callee, args)) {
.value => |v| {
if (inst.result) |r| vals[r] = v;
return .next;
},
.trap => |t| return .{ .nested_trap = t },
.limit_exceeded => return .limit_exceeded,
.blocked => |l| return .{ .nested_blocked = l },
}
},
.call => |x| return .{ .call = .{ .callee = x.callee, .args = try m.gather(vals, x.args) } },
.br => |t| return m.jump(f, vals, t),
.cbr => |x| return m.jump(f, vals, if (vals[x.cond].boolean) x.then else x.@"else"),
.@"switch" => |x| {
@@ -380,6 +486,34 @@ const Machine = struct {
// No narrowing form is registered yet, so verified AIR contains
// no reachable cap.narrow (spec 05 §10.4; forms arrive with RFC 0007/0008).
.cap_narrow => |x| return m.narrow(f, vals, x),
.task_scope_begin => return bind(vals, inst.result, .scope),
.task_scope_end => return .next,
.task_spawn => |x| {
if (m.live_tasks >= m.task_limit) return .task_limit;
m.live_tasks += 1;
m.spawned = true;
const id: u32 = @intCast(m.tasks.items.len);
try m.tasks.append(m.arena, .{});
try m.pushFrame(id, x.callee, try m.gather(vals, x.args));
vals[inst.result.?] = .{ .task = id };
return .yield;
},
.task_join => |v| {
const id = vals[v].task;
const t = m.tasks.items[id];
if (t.state != .done) return .{ .wait = .{ .join = id } };
m.live_tasks -= 1;
if (inst.result) |r| vals[r] = t.result;
return .yield;
},
.task_cancel => |v| {
m.tasks.items[vals[v].task].cancel = true;
return .yield;
},
.task_cancelled => {
vals[inst.result.?] = .{ .boolean = m.tasks.items[m.current].cancel };
return .yield;
},
.own_new, .own_array, .own_take, .own_free, .region_create, .region_new, .region_array, .region_reset, .region_destroy => return m.execAlloc(f, vals, {}, inst),
.intrinsic => |x| return m.intrinsic(f, vals, inst, x),
.ret => |v| return .{ .ret = if (v) |x| vals[x] else .void },
@@ -466,7 +600,12 @@ const Machine = struct {
}.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 };
return .{
.stdout = m.world.stdout.items,
.stderr = m.world.stderr.items,
.files = files,
.schedule = if (m.spawned) .{ .seed = m.schedule_seed, .quantum = m.quantum, .choices = m.choices } else null,
};
}
/// Bytes of a `slice<u8>` value.
@@ -727,7 +866,7 @@ const Machine = struct {
if (m.host) |*hs| switch (try hs.accept(hd)) {
.ok => |s| result = .{ .resource = s },
.err => |e| failure = e,
} else result = .{ .resource = m.world.accept(hd) orelse return .blocked };
} else result = .{ .resource = m.world.accept(hd) orelse return .{ .wait = .{ .accept = hd } } };
} else if (is(name, "net.recv")) {
const buf = try m.arena.alloc(u8, arg(vals, x, 1).slice.len);
const hd = resourceOf(arg(vals, x, 0));
@@ -737,7 +876,7 @@ const Machine = struct {
failure = e;
break :blk 0;
},
} else m.world.recv(hd, buf) orelse return .blocked;
} else m.world.recv(hd, buf) orelse return .{ .wait = .{ .recv = hd } };
fillSlice(arg(vals, x, 1), buf[0..n]);
result = .{ .int = .{ .ty = .usize, .bits = n } };
} else if (is(name, "net.send_all")) {
@@ -996,7 +1135,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, .own, .region => try s.write(null),
.resource, .own, .region, .scope, .task => try s.write(null),
// A capability is opaque: only its kind is shown, never its identity.
.cap => {
try s.beginObject();
@@ -1125,7 +1264,7 @@ pub fn writeOutcome(module: air.Module, outcome: Outcome, out: ?Output, w: *std.
.limit_exceeded => |l| {
try s.write("limit_exceeded");
try s.objectField("kind");
try s.write("fuel");
try s.write(l.kind);
try s.objectField("limit");
try s.write(l.limit);
try s.objectField("steps");
@@ -1145,6 +1284,10 @@ pub fn writeOutcome(module: air.Module, outcome: Outcome, out: ?Output, w: *std.
}
try s.endObject();
};
if (out) |o| if (o.schedule) |sch| {
try s.objectField("schedule");
try s.write(sch);
};
try s.endObject();
}
@@ -1317,3 +1460,30 @@ test "canonical byte strings in the run record" {
try s.endArray();
try std.testing.expectEqualStrings("[\"h\u{e9}\\n\",{\"encoding\":\"base64\",\"data\":\"/w==\"},{\"encoding\":\"base64\",\"data\":\"QWpp\"}]", w.buffered());
}
test "schedule seed: explicit value is used as is, default derives from the program seed" {
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
const src = "module t\nair 0\nlang 0.1\nfeatures [ownership, tasks]\n" ++
\\fn @main() -> void
\\effects []
\\entry:
\\ %sc = task.scope.begin
\\ %t = task.spawn %sc, @noop()
\\ task.join %t
\\ task.scope.end %sc
\\ ret
\\fn @noop() -> void
\\effects []
\\entry:
\\ ret
\\
;
const report = try check.checkAir(arena, "t.air", src);
var out: Output = undefined;
_ = try run(arena, report.module.?, "main", .{ .schedule_seed = 3, .output = &out });
try std.testing.expectEqual(@as(u64, 3), out.schedule.?.seed);
_ = try run(arena, report.module.?, "main", .{ .world = .{ .seed = 3 }, .output = &out });
try std.testing.expectEqual(@as(u64, 3 ^ 0x5343484544554c45), out.schedule.?.seed);
}
+9 -1
View File
@@ -26,7 +26,8 @@ const usage =
\\ --grant binds capability parameter P of @main
\\ (and replaces the manifest's grant for P);
\\ deterministic world: --stdin TEXT, --vfs PATH=TEXT,
\\ --seed N; --profile hosted uses the real OS and
\\ --seed N; scheduler: --quantum N, --task-limit N,
\\ --schedule-seed N; --profile hosted uses the real OS and
\\ writes the record only to --result-file PATH
\\ report <file.air> verify, then print the audit report (spec 10 §6.1)
\\ codes list diagnostic codes as JSON Lines
@@ -133,6 +134,13 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
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, "--quantum")) {
options.quantum = std.fmt.parseInt(u64, value, 10) catch return usageError("--quantum takes a positive integer");
if (options.quantum == 0) return usageError("--quantum takes a positive integer");
} else if (std.mem.eql(u8, flag, "--task-limit")) {
options.task_limit = std.fmt.parseInt(u64, value, 10) catch return usageError("--task-limit takes a non-negative integer");
} else if (std.mem.eql(u8, flag, "--schedule-seed")) {
options.schedule_seed = std.fmt.parseInt(u64, value, 10) catch return usageError("--schedule-seed takes a non-negative integer");
} else if (std.mem.eql(u8, flag, "--result-file")) {
result_file = value;
} else if (std.mem.eql(u8, flag, "--manifest")) {
+52
View File
@@ -29,6 +29,8 @@ const Seg = union(enum) {
const Mode = enum { shared, exclusive };
const Loan = struct { task: ValueId, borrow: ValueId, root: ValueId, path: []const Seg, mode: Mode };
/// Why a resource is no longer live (spec 06 §6.3).
const Dead = enum { none, closed, moved };
@@ -65,6 +67,11 @@ const Walker = struct {
live: []bool,
/// How a resource stopped being live, for diagnostics.
dead: []Dead,
/// Borrows lent to tasks (spec 04 §34). A loan is active while its task
/// handle is live, so it is part of the per-path state through `live`.
loans: std.ArrayList(Loan) = .empty,
/// Scope of each task handle value.
task_scope: []?ValueId,
block: u32 = 0,
index: u32 = 0,
span: air.Span = .{ .line = 0, .col = 0 },
@@ -127,6 +134,14 @@ const Walker = struct {
try w.report(code, message, who, .{ "conflicts_with", @intCast(cv) });
return;
}
// Borrows lent to live tasks are accessed concurrently (spec 04 §34).
for (w.loans.items) |l| {
if (!w.live[l.task] or l.root != root) continue;
if (mode == .shared and l.mode == .shared) continue;
if (!overlap(path, l.path)) continue;
try w.report("E4101", "conflicts with a borrow lent to a live task", who, .{ "task", l.task });
return;
}
}
/// Records a new owned borrow and checks it against live borrows.
@@ -262,7 +277,9 @@ fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void {
.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),
.task_scope = try c.arena.alloc(?ValueId, f.values.len),
};
@memset(w.task_scope, null);
@memset(w.info, null);
@memset(w.live, false);
@memset(w.dead, .none);
@@ -377,6 +394,9 @@ fn step(w: *Walker, inst: air.Inst) !void {
if (!w.live[v]) return w.report("E2106", "borrow ended twice", v, null);
// Ended even when rejected, so one mistake yields one diagnostic.
defer w.live[v] = false;
for (w.loans.items) |l| if (w.live[l.task] and (l.borrow == v or w.isAncestor(v, l.borrow))) {
return w.report("E4302", "borrow ended while it is lent to a live task", v, .{ "task", l.task });
};
for (w.live, 0..) |is_live, cv| {
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) });
@@ -397,6 +417,38 @@ fn step(w: *Walker, inst: air.Inst) !void {
};
},
.own_free, .own_take => |v| try w.consume(v, .closed),
.task_scope_begin => w.live[inst.result.?] = true,
.task_spawn => |x| {
const t = inst.result.?;
w.task_scope[t] = x.scope;
for (x.args) |a| {
if (w.types[a].isBorrow()) {
if (!try w.usable(a)) continue;
const ai = w.info[a].?;
// The loan must not conflict with live borrows or loans.
try w.accessCode(ai.root, ai.path, ai.mode, a, a, "E4101", "lending a borrow that conflicts with a live borrow");
try w.loans.append(w.c.arena, .{ .task = t, .borrow = a, .root = ai.root, .path = ai.path, .mode = ai.mode });
} else if (w.isResource(a)) try w.consume(a, .moved);
}
w.live[t] = true;
},
.task_join => |t| {
// Joining ends the task's loans (they are active only while `t` lives).
try w.consume(t, .closed);
if (inst.result) |r| if (w.isResource(r)) {
w.live[r] = true;
};
},
.task_cancel => |t| _ = try w.resourceUsable(t),
.task_scope_end => |s| {
for (w.live, 0..) |is_live, v| {
if (is_live and w.task_scope[v] != null and w.task_scope[v].? == s) {
try w.report("E4301", "scope ends while a task spawned from it is not joined", @intCast(v), .{ "scope", s });
w.live[v] = false; // reported once, in preference to E3002
}
}
try w.consume(s, .closed);
},
.region_reset => |v| {
if (!try w.resourceUsable(v)) return;
// Reset invalidates the generation: no reference may be live.
+1 -1
View File
@@ -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, .resource, .own, .region => 8,
.ref, .mut, .cap, .resource, .own, .region, .scope, .task => 8,
.own_array => 16,
.slice, .slice_mut => 16,
.builtin => |b| tagSize(b.variants().len),
+14
View File
@@ -16,6 +16,20 @@ pub fn check(c: *Context) !void {
if (!m.declares("effects")) return;
for (m.functions) |f| {
for (f.blocks) |b| for (b.insts) |inst| switch (inst.op) {
.task_spawn => |x| {
if (!contains(f.effects, "task.spawn")) try c.report("E3101", inst.span, "task.spawn requires the effect task.spawn", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "effect", .value = .{ .str = "task.spawn" } },
});
const callee = m.functions[x.callee];
for (callee.effects) |e| if (!std.mem.eql(u8, e, "unsafe") and !contains(f.effects, e)) {
try c.report("E3101", inst.span, "task function effect not declared by the spawning function", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "callee", .value = .{ .str = callee.name } },
.{ .name = "effect", .value = .{ .str = e } },
});
};
},
.call => |x| {
const callee = m.functions[x.callee];
// `unsafe` is checked by the unsafe stage, which knows about
+96 -6
View File
@@ -85,7 +85,7 @@ fn wellFormed(c: *Context, span: air.Span, t: Type, pos: Position, owner: []cons
.void, .never => pos == .ret,
.local => false,
.ref, .mut, .slice, .slice_mut => pos != .member and pos != .borrowed,
.resource, .own, .own_array, .region => pos != .member,
.resource, .own, .own_array, .region, .scope, .task => pos != .member,
else => true,
};
if (!ok) try c.report("E1001", span, "type not allowed in this position", &.{
@@ -93,9 +93,9 @@ fn wellFormed(c: *Context, span: air.Span, t: Type, pos: Position, owner: []cons
.{ .name = "position", .value = .{ .str = @tagName(pos) } },
.{ .name = "found", .value = .{ .str = try c.typeName(t) } },
});
// The pointee of ref/mut may be a linear value (`mut<file<read>>`);
// every other compound holds value types only.
if (t.inner()) |inner| try wellFormed(c, span, inner, if (t == .ref or t == .mut) .borrowed else .member, owner);
// The pointee of ref/mut may be a linear value (`mut<file<read>>`), and
// a task may return one; every other compound holds value types only.
if (t.inner()) |inner| try wellFormed(c, span, inner, if (t == .ref or t == .mut or t == .task) .borrowed else .member, owner);
}
/// `local.alloc` results are checked separately: their own type is storage.
@@ -210,6 +210,8 @@ 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 },
.task_scope_begin => .scope,
.task_cancelled => .bool,
.intrinsic => |x| blk: {
const reg = air.authority.intrinsics[x.index];
if (reg.fallible or reg.results.len == 0) break :blk .void;
@@ -307,6 +309,80 @@ fn checkIntrinsic(fc: *FnCtx, inst: air.Inst, x: @FieldType(air.Op, "intrinsic")
}
}
/// `Send` (spec 04 §35): may move to another task.
pub fn isSend(m: air.Module, t: Type) bool {
return switch (t) {
.int, .bool, .builtin, .cap, .resource, .region => true,
.own, .own_array => |inner| isSend(m, inner.*),
.ref, .slice => |inner| isShare(m, inner.*),
.mut, .slice_mut => |inner| isSend(m, inner.*),
.array => |a| isSend(m, a.elem),
.named => |i| aggregateAll(m, i, isSend),
.scope, .task, .local, .void, .never => false,
};
}
/// `Share` (spec 04 §35): may be observed concurrently through shared borrows.
pub fn isShare(m: air.Module, t: Type) bool {
return switch (t) {
.int, .bool, .builtin, .cap => true,
.resource, .region, .mut, .slice_mut, .scope, .task, .local, .void, .never => false,
.own, .own_array, .ref, .slice => |inner| isShare(m, inner.*),
.array => |a| isShare(m, a.elem),
.named => |i| aggregateAll(m, i, isShare),
};
}
fn aggregateAll(m: air.Module, i: u32, comptime pred: fn (air.Module, Type) bool) bool {
return switch (m.types[i].kind) {
.@"struct" => |fs| for (fs) |f| {
if (!pred(m, f.ty)) break false;
} else true,
.@"enum" => |vs| {
for (vs) |v| for (v.payload) |p| if (!pred(m, p)) return false;
return true;
},
};
}
/// `task.spawn` (spec 04 §33.2, §35): arguments like a call, Send/Share
/// rules per argument, and a borrow-free, Send result.
fn checkSpawn(fc: *FnCtx, inst: air.Inst, x: @FieldType(air.Op, "task_spawn")) !void {
const m = fc.c.module;
const f = fc.f;
const span = inst.span;
if (fc.typeOf(x.scope) != .scope) try fc.kindError(span, x.scope, "scope");
const callee = m.functions[x.callee];
const tys = try fc.c.arena.alloc(Type, callee.params.len);
for (callee.params, tys) |p, *t| t.* = p.ty;
try fc.expectArgs(span, x.args, tys);
if (x.args.len == tys.len) for (x.args, tys) |a, pt| {
const shared = pt == .ref or pt == .slice;
const ok = if (shared) isShare(m, pt.inner().?) else isSend(m, pt);
if (!ok) try fc.c.report(if (shared) "E4002" else "E4001", span, if (shared) "data lent to a task through a shared borrow must be Share" else "a value moved or exclusively lent to a task must be Send", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "task_function", .value = .{ .str = callee.name } },
.{ .name = "argument", .value = .{ .str = try fc.c.valueName(f, a) } },
.{ .name = "type", .value = .{ .str = try fc.c.typeName(pt) } },
});
};
const r = callee.ret;
if (callee.ret_from != null or r.isBorrow()) {
try fc.c.report("E0006", span, "construct belongs to a feature the module does not declare", &.{
.{ .name = "reason", .value = .{ .str = "feature_not_declared" } },
.{ .name = "feature", .value = .{ .str = "task_borrow_returns" } },
.{ .name = "construct", .value = .{ .str = "spawned function returning a borrow" } },
});
} else if (r.isTaskBound()) {
try fc.c.report("E1001", span, "a task result must not contain a scope or task handle", &.{.{ .name = "function", .value = .{ .str = f.name } }});
} else if (r != .void and r != .never and !isSend(m, r)) {
try fc.c.report("E4001", span, "a task result must be Send", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "task_function", .value = .{ .str = callee.name } },
});
}
}
fn boxed(arena: std.mem.Allocator, t: Type) !*const Type {
const b = try arena.create(Type);
b.* = t;
@@ -328,6 +404,8 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type {
.borrow_index => |x| fc.ty[x.borrow] orelse return null,
.slice_sub => |x| fc.ty[x.slice] orelse return null,
.own_take => |v| fc.ty[v] orelse return null,
.task_join => |v| fc.ty[v] orelse return null,
.task_spawn => |x| return .{ .task = try boxed(a, m.functions[x.callee].ret) },
.slice_split => |x| fc.ty[x.slice] orelse return null,
else => return null,
};
@@ -336,7 +414,7 @@ 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, .region => .{ .ref = try boxed(a, t) },
.resource, .region, .task, .scope => .{ .ref = try boxed(a, t) },
.own => |inner| .{ .ref = inner },
.own_array => |inner| .{ .slice = inner },
.slice, .slice_mut => .{ .slice = try boxed(a, t.inner().?) },
@@ -344,7 +422,7 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type {
},
.borrow_mut => switch (t) {
.local, .mut => .{ .mut = try boxed(a, t.inner().?) },
.resource, .region => .{ .mut = try boxed(a, t) },
.resource, .region, .task, .scope => .{ .mut = try boxed(a, t) },
.own => |inner| .{ .mut = inner },
.own_array => |inner| .{ .slice_mut = inner },
.slice_mut => .{ .slice_mut = try boxed(a, t.inner().?) },
@@ -376,6 +454,7 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type {
},
.slice_sub, .slice_split => if (t.isSlice()) t else invalid,
.own_take => if (t == .own) t.own.* else invalid,
.task_join => if (t == .task) t.task.* else invalid,
else => unreachable,
};
}
@@ -589,6 +668,17 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
try fc.expectOkErr(span, x.ok, x.err, .{ .slice_mut = try boxed(fc.c.arena, t) });
},
.region_reset, .region_destroy => |v| if (fc.typeOf(v) != .region) try fc.kindError(span, v, "region"),
.task_scope_begin, .task_cancelled => {},
.task_scope_end => |v| if (fc.typeOf(v) != .scope) try fc.kindError(span, v, "scope"),
.task_cancel => |v| if (fc.typeOf(v) != .task) try fc.kindError(span, v, "task<T>"),
.task_join => |v| {
const t = fc.typeOf(v);
if (t != .task) return fc.kindError(span, v, "task<T>");
const r = t.task.*;
if (inst.result != null and r == .void) try fc.c.report("E1001", span, "joining a void task must not bind a result", &.{.{ .name = "function", .value = .{ .str = f.name } }});
if (inst.result == null and r != .void and r != .never) try fc.c.report("E1001", span, "the result of task.join must be bound", &.{.{ .name = "function", .value = .{ .str = f.name } }});
},
.task_spawn => |x| try checkSpawn(fc, inst, x),
.cap_narrow => |x| {
const t = fc.typeOf(x.cap);
if (t != .cap) return fc.kindError(span, x.cap, "cap<K>");