//! Reference interpreter for format version 0 (spec 07a, spec 11 §1). //! //! Requirements: //! - executes only verified AIR; //! - deterministic: no host time, randomness or address-dependent behavior; //! - traps are values (`Outcome.trapped`), never host panics or unwinding. //! //! Target description: `air64` (spec 09 §9). //! //! Memory: use is bounded by the program's live state, not by the number //! of instructions executed. //! - long-lived state comes from the arena passed to `run` and is released //! by the caller: the module, the world, the authority, task, channel and //! region tables, and the result; //! - execution state lives in a collectable heap: frames, block and call //! arguments, frame storage and heap cells, aggregate and array payloads, //! place paths, channel buffers, per-instruction scratch. Between //! instructions, when the heap has grown past a threshold, the live part //! is copied into a fresh heap (`collect`) and the old one is released. //! Copying preserves sharing, and nothing observable depends on //! addresses, so collection never changes fuel, scheduling, PRNG draws, //! values, traps or the run record. const std = @import("std"); const air = @import("../air.zig"); const diag = @import("../diag.zig"); const world_mod = @import("world.zig"); const host_mod = @import("host.zig"); const budget = @import("../verifier/budget.zig"); const weak = @import("weak.zig"); const race = @import("race.zig"); pub const WorldOptions = world_mod.Options; pub const call_depth_limit = 1024; pub const Value = union(enum) { /// Bit pattern of the integer, zero-extended to 128 bits. int: struct { ty: air.IntType, bits: u128 }, boolean: bool, void, aggregate: Aggregate, array: []Value, /// Frame storage (`local`). local: *Cell, /// `ref` / `mut`: a place inside frame storage. place: Place, /// `slice` / `slice_mut`. slice: Slice, /// `cap`: 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, /// `own` / `own_array`: the heap cell. own: *Cell, /// `region`: index into the machine's region table. region: u32, /// `scope` (no runtime state) and `task` (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 }, /// `shield` (the depth lives in the task). shield, /// `sender` / `receiver`: index into the machine's channel table. sender: u32, receiver: u32, /// `mutex` and the `guard` that holds it. mutex: *MutexCell, guard: *MutexCell, /// `island`, `frozen`, `arc`: the graph (spec 03 §22–§24). The /// ownership mode is the static type; the graph is the same object. graph: *Graph, /// `iref`: graph identity and slot; opaque to programs. iref: struct { id: u64, slot: u32 }, /// `atomic`: index into the machine's atomic cells (spec 04 §42). atomic: u32, buffer: *Buffer, pub const Buffer = struct { // The interpreter stores only the initialized prefix. Capacity is // charged to Aji authority independently of this host representation; // push's Value-array bookkeeping does not allocate from that authority. cell: *Cell, capacity: u64, elem: air.Type, }; /// The guarded value is a separate cell, so a place borrowed through a /// guard points at an ordinary cell. pub const MutexCell = struct { locked: bool, cell: *Cell, /// The view of the last unlock (spec 04 §20.3: unlock → next lock). view: weak.View = .{}, }; /// A graph: object cells addressed by slot, an identity never reused in /// the execution, the authority it charges and the bytes it holds. pub const Graph = struct { id: u64, objects: std.ArrayList(*Cell) = .empty, authority: u32, bytes: u64, /// `arc` handles alive (0 while unique: island or frozen). count: u64 = 0, frozen: bool = false, }; pub const Aggregate = struct { decl: u32, /// Active variant for enums; 0 for structs. variant: u32, fields: []Value, }; /// Frame storage. `value` is `.void` while uninitialized. pub const Cell = struct { value: Value, ty: air.Type, /// An SSA root borrowed in place; its frame outlives every loan. backing: ?struct { values: []Value, index: u32 } = null, owner_array: bool = false, /// Accesses seen by the race detector (`Options.detect_races`). shadow: ?*race.Shadow = null, }; /// Path of field or element indices from the cell's value. pub const Place = struct { cell: *Cell, path: []const u32 }; /// Range `[start, start + len)` of the array at `place`. pub const Slice = struct { place: Place, start: u64, len: u64 }; }; pub const Trap = struct { code: *const diag.Code, function: []const u8, block: []const u8, inst: u32, }; pub const Outcome = union(enum) { returned: Value, trapped: Trap, /// The runner's fuel ran out (spec 11 §7). Not a trap. 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 /// a wait (spec 11 §8). Not a trap and not an I/O error. blocked: Location, /// The race detector (`Options.detect_races`) found two unordered /// conflicting accesses to ordinary memory: a verifier defect (spec 04 §21). race_detected: struct { at: Location, other_task: u32 }, }; pub const Location = struct { function: []const u8, block: []const u8, inst: u32 }; pub const NotInstantiated = struct { reason: []const u8, parameter: []const u8, kind: ?[]const u8 = null, granted: ?[]const u8 = null, scope: ?[]const u8 = null, }; /// One `--grant =[:]`. pub const Grant = struct { parameter: []const u8, kind: []const u8, scope: ?[]const u8 = null, }; /// An authority object held by the host: copies of a capability share it. /// For `mem.alloc`: `limit` (null = unlimited), `used` live bytes and the /// `parent` it was narrowed from; charges walk the chain (spec 03 §18.1). pub const Authority = struct { kind: u16, scope: ?[]const u8, limit: ?u64 = null, used: u64 = 0, parent: ?u32 = null, }; /// A region: its authority and the bytes charged by its current generation. pub const Region = struct { authority: u32, used: u64 }; const OwnInfo = struct { authority: u32, bytes: u64 }; /// Execution-heap statistics (`Options.memory`), for tests and tooling. pub const MemoryStats = struct { collections: u64 = 0, /// Largest live execution state after a collection, in heap bytes. peak_live: usize = 0, /// Largest execution heap before a collection, in heap bytes. peak_heap: usize = 0, /// Instructions executed. steps: u64 = 0, }; /// One `arc` count change (spec 03 §24: every change appears in the trace). pub const ArcEvent = struct { op: enum { new, from_frozen, clone, release }, graph: u64, count: u64 }; pub const Options = struct { /// Trace mode for `arc` counts: every change is appended (spec 11 §2). arc_events: ?*std.ArrayList(ArcEvent) = null, /// Filled with execution-heap statistics when set. memory: ?*MemoryStats = null, /// Collect before every instruction (tests: a missed root then fails). collect_every_step: bool = false, /// Smallest heap size that triggers a collection (default 4 MiB); a /// small value makes short test programs collect often. collect_threshold: ?usize = null, /// Maximum number of instructions to execute (spec 11 §7.1); null means unlimited. 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 (deterministic profile). 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, /// Exhaustive exploration: choices come from `Explore` instead of the /// schedule generator (spec 04 §20.5). explore: ?*Explore = null, /// Check every ordinary access for data races (spec 04 §21; a test tool). detect_races: bool = false, }; /// 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 }, /// 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 }; /// Runs `entry`, which must take no parameters. `module` must have passed /// verification. pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, options: Options) Error!Outcome { 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, .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 = &.{} }; }; // Instantiation (spec 05 §10.2): every capability parameter gets exactly // one grant of its kind, and every grant names a parameter. for (options.grants, 0..) |g, i| { for (options.grants[0..i]) |prev| if (std.mem.eql(u8, prev.parameter, g.parameter)) return error.DuplicateGrant; } const args = try arena.alloc(Value, f.params.len); for (f.params, args) |p, *arg| { const pname = f.values[p.value].name; const kind = air.authority.kinds[p.ty.cap].name; const g = for (options.grants) |g| { if (std.mem.eql(u8, g.parameter, pname)) break g; } else return .{ .not_instantiated = .{ .reason = "missing_capability", .parameter = pname, .kind = kind } }; if (!std.mem.eql(u8, g.kind, kind)) return .{ .not_instantiated = .{ .reason = "kind_mismatch", .parameter = pname, .kind = kind, .granted = g.kind } }; // The deterministic profile requires an explicit allocation budget (spec 03 §18.2). const is_alloc = air.authority.kinds[p.ty.cap].scope == .byte_budget; if (!air.authority.validScope(p.ty.cap, g.scope) or (is_alloc and g.scope == null)) return .{ .not_instantiated = .{ .reason = "invalid_scope", .parameter = pname, .kind = kind, .scope = g.scope } }; try m.authorities.append(arena, .{ .kind = p.ty.cap, .scope = g.scope, .limit = if (is_alloc) std.fmt.parseInt(u64, g.scope.?, 10) catch unreachable else null, }); arg.* = .{ .cap = @intCast(m.authorities.items.len - 1) }; } for (options.grants) |g| { const known = for (f.params) |p| { if (std.mem.eql(u8, f.values[p.value].name, g.parameter)) break true; } else false; if (!known) return .{ .not_instantiated = .{ .reason = "unknown_parameter", .parameter = g.parameter } }; } m.exec_heap.every_step = options.collect_every_step; m.arc_events = options.arc_events; m.explore = options.explore; m.detect_races = options.detect_races; m.mem.weak_reads = hasWeakReads(module); if (options.collect_threshold) |t| { m.exec_heap.floor = t; m.exec_heap.threshold = t; } const outcome = try m.runProgram(idx, args); // The result outlives the execution heap. var result = outcome; if (outcome == .returned) { var tmp: std.heap.ArenaAllocator = .init(std.heap.page_allocator); defer tmp.deinit(); var c: Copier = .{ .to = arena, .tmp = tmp.allocator() }; result = .{ .returned = try c.value(outcome.returned) }; } m.exec_heap.stats.peak_heap = @max(m.exec_heap.stats.peak_heap, m.exec_heap.space.queryCapacity()); m.exec_heap.stats.steps = m.steps; if (options.memory) |st| st.* = m.exec_heap.stats; m.exec_heap.space.deinit(); return result; } /// Operations whose order between tasks can change an outcome: atomic /// memory operations and the synchronization of channels, mutexes and /// cancellation. `task.spawn` and `task.join` commute with them. fn isVisibleOp(op: air.Op) bool { return switch (op) { .atomic_load, .atomic_store, .atomic_rmw, .atomic_cmpxchg, .atomic_fence => true, .channel_send, .channel_recv, .channel_close_sender, .channel_close_receiver, .select => true, .mutex_lock, .mutex_unlock => true, .task_cancel, .task_cancelled, .task_check_cancel, .task_join_cancel => true, else => false, }; } /// Whether a read may read an older message: a non-`seq_cst` load or /// compare-exchange failure (spec 04 §42). Without one, cells keep only their /// latest message. fn hasWeakReads(module: air.Module) bool { for (module.functions) |f| for (f.blocks) |b| for (b.insts) |inst| switch (inst.op) { .atomic_load => |x| if (x.ord != .seq_cst) return true, .atomic_cmpxchg => |x| if (x.failure != .seq_cst) return true, else => {}, }; return false; } /// Copies values into another heap, preserving sharing: a cell, a mutex or /// a payload reached twice is copied once. const Copier = struct { to: std.mem.Allocator, tmp: std.mem.Allocator, cells: std.AutoHashMapUnmanaged(*Value.Cell, *Value.Cell) = .empty, mutexes: std.AutoHashMapUnmanaged(*Value.MutexCell, *Value.MutexCell) = .empty, payloads: std.AutoHashMapUnmanaged([*]Value, []Value) = .empty, graphs: std.AutoHashMapUnmanaged(*Value.Graph, *Value.Graph) = .empty, buffers: std.AutoHashMapUnmanaged(*Value.Buffer, *Value.Buffer) = .empty, fn value(c: *Copier, v: Value) std.mem.Allocator.Error!Value { return switch (v) { .aggregate => |a| .{ .aggregate = .{ .decl = a.decl, .variant = a.variant, .fields = try c.items(a.fields) } }, .array => |xs| .{ .array = try c.items(xs) }, .local => |cl| .{ .local = try c.cell(cl) }, .own => |cl| .{ .own = try c.cell(cl) }, .buffer => |b| .{ .buffer = try c.buffer(b) }, .place => |p| .{ .place = try c.place(p) }, .slice => |sl| .{ .slice = .{ .place = try c.place(sl.place), .start = sl.start, .len = sl.len } }, .mutex => |mc| .{ .mutex = try c.mutex(mc) }, .guard => |mc| .{ .guard = try c.mutex(mc) }, .graph => |g| .{ .graph = try c.graph(g) }, .int, .boolean, .void, .cap, .resource, .region, .scope, .task, .builtin, .shield, .sender, .receiver, .iref, .atomic => v, }; } fn items(c: *Copier, xs: []Value) std.mem.Allocator.Error![]Value { if (xs.len == 0) return &.{}; if (c.payloads.get(xs.ptr)) |n| { std.debug.assert(n.len == xs.len); return n; } const out = try c.to.alloc(Value, xs.len); try c.payloads.put(c.tmp, xs.ptr, out); for (xs, out) |x, *o| o.* = try c.value(x); return out; } fn cell(c: *Copier, old: *Value.Cell) std.mem.Allocator.Error!*Value.Cell { if (c.cells.get(old)) |n| return n; const n = try c.to.create(Value.Cell); try c.cells.put(c.tmp, old, n); n.* = .{ .value = .void, .ty = old.ty, .shadow = if (old.shadow) |sh| try sh.copy(c.to) else null }; n.owner_array = old.owner_array; if (old.backing) |b| n.backing = .{ .values = try c.items(b.values), .index = b.index }; n.value = try c.value(old.value); return n; } fn buffer(c: *Copier, old: *Value.Buffer) std.mem.Allocator.Error!*Value.Buffer { if (c.buffers.get(old)) |n| return n; const n = try c.to.create(Value.Buffer); try c.buffers.put(c.tmp, old, n); n.* = .{ .cell = try c.cell(old.cell), .capacity = old.capacity, .elem = old.elem }; return n; } fn mutex(c: *Copier, old: *Value.MutexCell) std.mem.Allocator.Error!*Value.MutexCell { if (c.mutexes.get(old)) |n| return n; const n = try c.to.create(Value.MutexCell); try c.mutexes.put(c.tmp, old, n); n.* = .{ .locked = old.locked, .cell = try c.cell(old.cell), .view = try old.view.copy(c.to) }; return n; } fn graph(c: *Copier, old: *Value.Graph) std.mem.Allocator.Error!*Value.Graph { if (c.graphs.get(old)) |n| return n; const n = try c.to.create(Value.Graph); try c.graphs.put(c.tmp, old, n); n.* = old.*; n.objects = .empty; try n.objects.ensureTotalCapacity(c.to, old.objects.items.len); for (old.objects.items) |cl| n.objects.appendAssumeCapacity(try c.cell(cl)); return n; } fn place(c: *Copier, p: Value.Place) std.mem.Allocator.Error!Value.Place { return .{ .cell = try c.cell(p.cell), .path = if (p.path.len == 0) &.{} else try c.to.dupe(u32, p.path) }; } }; const TrapKind = enum { explicit, assert, overflow, division_by_zero, shift_out_of_range, cast_out_of_range, call_depth, out_of_bounds, unsafe_precondition, foreign_iref, fn code(k: TrapKind) *const diag.Code { return switch (k) { .explicit => diag.lookup("T0001").?, .assert => diag.lookup("T0002").?, .overflow => diag.lookup("T0003").?, .division_by_zero => diag.lookup("T0004").?, .shift_out_of_range => diag.lookup("T0005").?, .cast_out_of_range => diag.lookup("T0006").?, .call_depth => diag.lookup("T0007").?, .out_of_bounds => diag.lookup("T0008").?, .unsafe_precondition => diag.lookup("T0009").?, .foreign_iref => diag.lookup("T0010").?, }; } }; /// Traps raised by integer operations. const TrapError = error{ overflow, division_by_zero, shift_out_of_range, cast_out_of_range }; fn kindOf(e: TrapError) TrapKind { return switch (e) { error.overflow => .overflow, error.division_by_zero => .division_by_zero, error.shift_out_of_range => .shift_out_of_range, error.cast_out_of_range => .cast_out_of_range, }; } pub const Wait = union(enum) { join: u32, accept: u32, recv: u32, /// A waiting operation of spec 04 §37.1: the current instruction is /// re-evaluated when it becomes ready or cancellation becomes observable. op, }; /// A rendezvous offer: a task waiting to send or receive on a capacity-0 /// channel, in arm `arm` of its instruction (0 outside `select`). const Offer = struct { task: u32, arm: u32, value: Value = .void, view: weak.View = .{} }; /// A channel (spec 04 §38.3). const Channel = struct { capacity: u64, buf: std.ArrayList(Value) = .empty, /// The sender's view of each buffered value (spec 04 §20.3: send → the /// receive that obtains the value). Parallel to `buf`. views: std.ArrayList(weak.View) = .empty, head: usize = 0, /// Joined views of the senders' closes (close → the `closed` outcome). close_view: weak.View = .{}, senders: u64 = 1, receiver: enum { open, closing, closed } = .open, authority: u32, bytes: u64, released: bool = false, /// Waiting rendezvous senders, in the order they began to wait. send_offers: std.ArrayList(Offer) = .empty, /// The receiver, while it waits on this rendezvous channel. recv_offer: ?Offer = null, fn buffered(c: *const Channel) usize { return c.buf.items.len - c.head; } /// No future value can arrive (`DRAINED` once the buffer is empty). fn noMore(c: *const Channel) bool { return c.senders == 0 or c.receiver != .open; } }; const Readiness = enum { none, ok, closed }; 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, /// Shield depth (spec 04 §37.3). shield: u32 = 0, /// Set by a peer that completed a rendezvous against this waiting task. delivered: ?struct { arm: u32, value: Value, view: weak.View = .{} } = null, /// Weak-memory views (spec 04 §42). views: weak.TaskViews = .{}, /// Joined views of the cancellers (cancel → the `cancelled` outcome). cancel_view: weak.View = .{}, /// Exploration: the scheduler already chose this task to perform the /// atomic operation it is at. chosen: bool = false, }; /// Exhaustive exploration (spec 04 §20.5): replays a prefix of choices, /// then takes choice 0, and records the number of options at every choice. pub const Explore = struct { prefix: []const u32 = &.{}, widths: std.ArrayList(u32) = .empty, }; /// Execution heap: collected between instructions (see the file comment). pub const Heap = struct { space: std.heap.ArenaAllocator = .init(std.heap.page_allocator), threshold: usize = min_threshold, /// Smallest collection threshold (`Options.collect_threshold`). floor: usize = min_threshold, every_step: bool = false, stats: MemoryStats = .{}, pub const min_threshold = 4 << 20; }; const Machine = struct { arena: std.mem.Allocator, exec_heap: Heap = .{}, /// Next graph identity; identities are never reused (spec 03 §22). next_graph: u64 = 1, arc_events: ?*std.ArrayList(ArcEvent) = null, module: air.Module, 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, host: ?host_mod.Host = null, owners: std.AutoHashMapUnmanaged(*Value.Cell, OwnInfo) = .empty, regions: std.ArrayList(Region) = .empty, channels: std.ArrayList(Channel) = .empty, /// A `select` drew among ready arms (spec 04 §36.4). drew: bool = false, /// Instructions executed so far. steps: u64 = 0, /// Atomic cells and the `seq_cst` view (spec 04 §42). mem: weak.Memory = .{}, explore: ?*Explore = null, detect_races: bool = false, // ------------------------------------------------------------ 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, .{}); if (m.detect_races) m.tasks.items[0].views.cur = try m.tasks.items[0].views.cur.with(race.clockKey(0), 1, m.heap()); try m.pushFrame(0, fn_index, args); while (true) { // Safe point: between instructions no Zig local holds heap values. if (m.exec_heap.every_step or m.exec_heap.space.queryCapacity() > m.exec_heap.threshold) try m.collect(); 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 }; // Exploration branches only before visible operations: what a // task does between two of them is local to it and commutes with // every other task (spec 04 §20.5). The task parks there; the // scheduler chooses once every runnable task is parked. if (m.explore != null and isVisibleOp(inst.op) and !t.chosen) { t.chosen = true; if (try m.schedule()) |o| return o; continue; } t.chosen = false; // 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; }, .jump_yield => |target| { frame.block = target; frame.inst = 0; if (try m.schedule()) |o| return o; continue; }, .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 } }, .race => |other| return .{ .race_detected = .{ .at = here, .other_task = other } }, } if (m.quantum_used >= m.quantum) { if (try m.schedule()) |o| return o; } } } fn heap(m: *Machine) std.mem.Allocator { return m.exec_heap.space.allocator(); } /// Copies the live execution state into a fresh heap and releases the /// old one. Roots: every task's frames, result and delivered value; the /// channels' buffered values and offers; the heap cells of live owners. fn collect(m: *Machine) std.mem.Allocator.Error!void { const before = m.exec_heap.space.queryCapacity(); var next: std.heap.ArenaAllocator = .init(std.heap.page_allocator); errdefer next.deinit(); var tmp: std.heap.ArenaAllocator = .init(std.heap.page_allocator); defer tmp.deinit(); var c: Copier = .{ .to = next.allocator(), .tmp = tmp.allocator() }; for (m.tasks.items) |*t| { for (t.frames.items) |*fr| fr.vals = try c.items(fr.vals); t.result = try c.value(t.result); if (t.delivered) |*d| { d.value = try c.value(d.value); d.view = try d.view.copy(c.to); } t.views = try t.views.copy(c.to); t.cancel_view = try t.cancel_view.copy(c.to); } for (m.channels.items) |*ch| { var buf: std.ArrayList(Value) = .empty; try buf.ensureTotalCapacity(c.to, ch.buf.items.len - ch.head); for (ch.buf.items[ch.head..]) |v| buf.appendAssumeCapacity(try c.value(v)); var views: std.ArrayList(weak.View) = .empty; try views.ensureTotalCapacity(c.to, ch.views.items.len - ch.head); for (ch.views.items[ch.head..]) |v| views.appendAssumeCapacity(try v.copy(c.to)); ch.buf = buf; ch.views = views; ch.head = 0; ch.close_view = try ch.close_view.copy(c.to); var offers: std.ArrayList(Offer) = .empty; try offers.ensureTotalCapacity(c.to, ch.send_offers.items.len); for (ch.send_offers.items) |o| offers.appendAssumeCapacity(.{ .task = o.task, .arm = o.arm, .value = try c.value(o.value), .view = try o.view.copy(c.to) }); ch.send_offers = offers; if (ch.recv_offer) |*o| { o.value = try c.value(o.value); o.view = try o.view.copy(c.to); } } // Atomic messages no live task can read any more are dropped. const floor = try tmp.allocator().alloc(u64, m.mem.cells.items.len); @memset(floor, std.math.maxInt(u64)); for (m.tasks.items) |t| if (t.state != .done) for (floor, 0..) |*fl, i| { fl.* = @min(fl.*, t.views.cur.get(@intCast(i))); }; try m.mem.compact(c.to, floor); var owners: std.AutoHashMapUnmanaged(*Value.Cell, OwnInfo) = .empty; try owners.ensureTotalCapacity(c.to, m.owners.count()); var it = m.owners.iterator(); while (it.next()) |e| owners.putAssumeCapacityNoClobber(try c.cell(e.key_ptr.*), e.value_ptr.*); m.owners = owners; m.exec_heap.space.deinit(); m.exec_heap.space = next; const live = m.exec_heap.space.queryCapacity(); const st = &m.exec_heap.stats; st.collections += 1; st.peak_heap = @max(st.peak_heap, before); st.peak_live = @max(st.peak_live, live); m.exec_heap.threshold = @max(m.exec_heap.floor, 2 * live); } fn pushFrame(m: *Machine, task: u32, fn_index: u32, args: []const Value) !void { const f = m.module.functions[fn_index]; const vals = try m.heap().alloc(Value, f.values.len); // Slots not yet defined are read by `collect`: they start as void. @memset(vals, .void); 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 }); } /// Whether a waiting task's condition holds now. fn ready(m: *Machine, id: u32) bool { const t = &m.tasks.items[id]; return switch (t.wait) { .op => t.delivered != null or m.opReady(id) or cancelObservable(t), .join => |child| m.tasks.items[child].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, 0..) |*t, i| if (t.state == .waiting and m.ready(@intCast(i))) { t.state = .runnable; }; var runnable: std.ArrayList(u32) = .empty; for (m.tasks.items, 0..) |t, i| if (t.state == .runnable) try runnable.append(m.heap(), @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; } // Exploration: tasks with local work run first, without a choice. if (m.explore != null) for (runnable.items) |id| if (!m.tasks.items[id].chosen) { m.current = id; return null; }; m.current = runnable.items[try m.choose(runnable.items.len)]; return null; } /// Exhaustive exploration does not branch after `task.spawn` and a /// completed `task.join`: they commute with every operation of every /// other task, so branching there would only repeat outcomes. Ordinary /// runs keep them as scheduling points (spec 04 §36.1). fn yieldUnlessExploring(m: *Machine) Step { return if (m.explore != null) .next else .yield; } /// One choice among `n > 1` options (spec 04 §36.2): a draw from the /// schedule generator, or the next choice of an exhaustive exploration. fn choose(m: *Machine, n: usize) !usize { m.choices += 1; if (m.explore) |e| { const i = e.widths.items.len; try e.widths.append(m.arena, @intCast(n)); return if (i < e.prefix.len) e.prefix[i] else 0; } return m.sched.next() % n; } const Step = union(enum) { next, jump: u32, ret: Value, trap: TrapKind, /// 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, /// Continue at a block; the completed instruction is a scheduling point. jump_yield: u32, /// The race detector found a racing access by this task. race: u32, }; fn exec(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst) std.mem.Allocator.Error!Step { switch (inst.op) { .@"const" => |c| return bind(vals, inst.result, switch (c.ty) { .int => |it| .{ .int = .{ .ty = it, .bits = c.bits } }, .bool => .{ .boolean = c.bits != 0 }, else => unreachable, }), .copy => |v| return bind(vals, inst.result, vals[v]), .arith => |x| { const bits = arith(x.op, x.mode, x.ty, vals[x.a].int.bits, vals[x.b].int.bits) catch |e| return .{ .trap = kindOf(e) }; return bind(vals, inst.result, .{ .int = .{ .ty = x.ty, .bits = bits } }); }, .bit => |x| switch (x.ty) { .bool => { const a = vals[x.a].boolean; const b = vals[x.b].boolean; return bind(vals, inst.result, .{ .boolean = switch (x.op) { .@"and" => a and b, .@"or" => a or b, .xor => a != b, else => unreachable, } }); }, .int => |it| { const bits = bitop(x.op, it, vals[x.a].int.bits, vals[x.b].int.bits) catch |e| return .{ .trap = kindOf(e) }; return bind(vals, inst.result, .{ .int = .{ .ty = it, .bits = bits } }); }, else => unreachable, }, .cmp => |x| return bind(vals, inst.result, .{ .boolean = switch (x.ty) { .bool => switch (x.op) { .eq => vals[x.a].boolean == vals[x.b].boolean, .ne => vals[x.a].boolean != vals[x.b].boolean, else => unreachable, }, .int => |it| compare(x.op, it, vals[x.a].int.bits, vals[x.b].int.bits), else => unreachable, } }), .cast => |x| { const from = vals[x.a].int; const bits = cast(x.mode, from.ty, x.to, from.bits) catch |e| return .{ .trap = kindOf(e) }; return bind(vals, inst.result, .{ .int = .{ .ty = x.to, .bits = bits } }); }, .assert => |v| return if (vals[v].boolean) .next else .{ .trap = .assert }, .buffer_new, .buffer_len, .buffer_capacity, .buffer_view, .buffer_reserve, .buffer_push, .buffer_pop, .buffer_free => return m.execBuffer(f, vals, inst), .array_make => |x| return bind(vals, inst.result, .{ .array = try m.gatherMut(vals, x.args) }), .aggregate_unpack => |x| { const fields = if (x.ty == .array) vals[x.value].array else vals[x.value].aggregate.fields; for (f.blocks[x.next].params, fields) |p, v| vals[p.value] = v; return .{ .jump = x.next }; }, .struct_make => |x| return bind(vals, inst.result, .{ .aggregate = .{ .decl = x.decl, .variant = 0, .fields = try m.gatherMut(vals, x.args), } }), .struct_get => |x| return bind(vals, inst.result, vals[x.a].aggregate.fields[x.field]), .enum_make => |x| return bind(vals, inst.result, .{ .aggregate = .{ .decl = x.decl, .variant = x.variant, .fields = try m.gatherMut(vals, x.args), } }), .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| { const v = vals[x.value].int.bits; for (x.cases) |c| if (c.bits == v) return m.jump(f, vals, c.target); return m.jump(f, vals, x.default); }, inline .enum_switch, .enum_take => |x| { const variant: u32, const fields: []const Value = switch (vals[x.value]) { .aggregate => |agg| .{ agg.variant, agg.fields }, .builtin => |b| .{ b.variant, &.{} }, else => unreachable, }; for (x.arms) |arm| if (arm.variant == variant) { for (f.blocks[arm.block].params, fields) |p, fv| vals[p.value] = fv; return .{ .jump = arm.block }; }; return m.jump(f, vals, x.default.?); }, // 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); // spawn → the child's first event (spec 04 §20.3). var parent = m.tasks.items[m.current].views.cur; if (m.detect_races) parent = try parent.with(race.clockKey(id), 1, m.heap()); try m.tasks.append(m.arena, .{ .views = .{ .cur = parent, .acq = parent } }); try m.tick(); try m.pushFrame(id, x.callee, try m.gather(vals, x.args)); vals[inst.result.?] = .{ .task = id }; return m.yieldUnlessExploring(); }, .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; // The child's last event → join (spec 04 §20.3). try m.tasks.items[m.current].views.acquire(t.views.cur, m.heap()); if (inst.result) |r| vals[r] = t.result; return m.yieldUnlessExploring(); }, .task_cancel => |v| { const target = &m.tasks.items[vals[v].task]; target.cancel = true; target.cancel_view = try target.cancel_view.join(m.tasks.items[m.current].views.cur, m.heap()); try m.tick(); return .yield; }, .task_cancelled => { const cancelled = m.tasks.items[m.current].cancel; if (cancelled) try m.observeCancel(); vals[inst.result.?] = .{ .boolean = cancelled }; return .yield; }, .task_check_cancel, .task_join_cancel, .task_shield_begin, .task_shield_end => return m.execCancellation(f, vals, inst), .channel_make, .channel_dup, .channel_send, .channel_recv, .channel_close_sender, .channel_close_receiver, .select => return m.execChannel(f, vals, inst), .mutex_make, .mutex_take, .mutex_lock, .mutex_borrow, .mutex_unlock => return m.execMutex(f, vals, inst), inline .own_new, .own_pack, .own_array, .own_take, .own_free, .region_create, .region_new, .region_array, .region_reset, .region_destroy => return m.execAlloc(f, vals, {}, inst), .island_create, .island_alloc, .island_root, .island_borrow, .island_freeze, .island_destroy, .frozen_root, .frozen_borrow, .frozen_release, .arc_from_frozen, .arc_new, .arc_clone, .arc_release, .arc_root, .arc_borrow, .iref_eq => return m.execGraph(f, vals, inst), .atomic_new, .atomic_take, .atomic_load, .atomic_store, .atomic_rmw, .atomic_cmpxchg, .atomic_fence => return m.execAtomic(vals, inst), .intrinsic => |x| return m.intrinsic(f, vals, inst, x), .ret => |v| return .{ .ret = if (v) |x| vals[x] else .void }, .trap => return .{ .trap = .explicit }, .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, .value_swap, .guard, .assume => return m.execMemory(vals, inst), } } // ------------------------------------------------------------ waiting, channels, mutex (spec 04 §37–§41) fn cancelObservable(t: *const Task) bool { return t.cancel and t.shield == 0; } /// The instruction a task is executing. fn currentOf(m: *Machine, id: u32) struct { air.Function, []Value, air.Inst } { const fr = m.tasks.items[id].frames.items[m.tasks.items[id].frames.items.len - 1]; const f = m.module.functions[fr.func]; return .{ f, fr.vals, f.blocks[fr.block].insts[fr.inst] }; } /// Whether the waiting operation of task `id` is ready (spec 04 §38.3). fn opReady(m: *Machine, id: u32) bool { _, const vals, const inst = m.currentOf(id); return switch (inst.op) { .task_join_cancel => |x| m.tasks.items[vals[x.task].task].state == .done, .channel_send => |x| m.sendState(endpointOf(vals[x.sender])) != .none, .channel_recv => |x| m.recvState(endpointOf(vals[x.receiver])) != .none, .select => |x| for (x.arms) |arm| { const ch = endpointOf(vals[arm.endpoint]); if ((if (arm.value == null) m.recvState(ch) else m.sendState(ch)) != .none) break true; } else false, .mutex_lock => |x| !mutexOf(vals[x.mutex]).locked, else => unreachable, }; } fn endpointOf(v: Value) u32 { return switch (v) { .sender, .receiver => |c| c, .place => |p| endpointOf(placePtr(p).*), else => unreachable, }; } fn sendState(m: *Machine, id: u32) Readiness { const c = &m.channels.items[id]; if (c.receiver != .open) return .closed; if (c.capacity > 0) return if (c.buffered() < c.capacity) .ok else .none; return if (c.recv_offer != null) .ok else .none; } fn recvState(m: *Machine, id: u32) Readiness { const c = &m.channels.items[id]; if (c.buffered() > 0) return .ok; if (c.capacity == 0 and c.receiver == .open and c.send_offers.items.len > 0) return .ok; return if (c.noMore()) .closed else .none; } /// Withdraws every rendezvous offer of task `id`. fn removeOffers(m: *Machine, id: u32) void { for (m.channels.items) |*c| { if (c.recv_offer) |o| if (o.task == id) { c.recv_offer = null; }; var i: usize = 0; while (i < c.send_offers.items.len) { if (c.send_offers.items[i].task == id) { _ = c.send_offers.orderedRemove(i); } else i += 1; } } } /// Completes the peer of a rendezvous: it resumes on arm `arm`. fn deliver(m: *Machine, o: Offer, value: Value, view: weak.View) void { m.removeOffers(o.task); const t = &m.tasks.items[o.task]; t.delivered = .{ .arm = o.arm, .value = value, .view = view }; if (t.state == .waiting) t.state = .runnable; } /// Performs an `ok`-ready send. /// The sender's view travels with the value (spec 04 §20.3). fn doSend(m: *Machine, id: u32, v: Value) !void { const c = &m.channels.items[id]; const view = m.tasks.items[m.current].views.cur; try m.tick(); if (c.capacity > 0) { try c.views.append(m.heap(), view); return c.buf.append(m.heap(), try m.deepCopy(v)); } const o = c.recv_offer.?; m.deliver(o, try m.deepCopy(v), view); } /// Performs an `ok`-ready receive. fn doRecv(m: *Machine, id: u32) !Value { const c = &m.channels.items[id]; const views = &m.tasks.items[m.current].views; if (c.buffered() > 0) { c.head += 1; try views.acquire(c.views.items[c.head - 1], m.heap()); return c.buf.items[c.head - 1]; } const o = c.send_offers.orderedRemove(0); m.deliver(o, .void, .{}); try views.acquire(o.view, m.heap()); return o.value; } /// Advances the current task's clock after a releasing operation, so its /// later accesses are not ordered before what others acquired. fn tick(m: *Machine) !void { if (!m.detect_races) return; const t = &m.tasks.items[m.current]; const key = race.clockKey(m.current); t.views.cur = try t.views.cur.with(key, t.views.cur.get(key) + 1, m.heap()); } /// An ordinary access by the current task (spec 04 §21). fn raceCheck(m: *Machine, cell: *Value.Cell, path: []const u32, write: bool) !?Step { if (!m.detect_races) return null; if (cell.shadow == null) { cell.shadow = try m.heap().create(race.Shadow); cell.shadow.?.* = .{}; } const other = try race.access(m.heap(), cell.shadow.?, path, write, m.current, m.tasks.items[m.current].views.cur) orelse return null; return .{ .race = other }; } /// The `cancelled` outcome synchronizes with the cancels (spec 04 §20.3). fn observeCancel(m: *Machine) !void { const t = &m.tasks.items[m.current]; try t.views.acquire(t.cancel_view, m.heap()); } /// The `closed` outcome of a receive synchronizes with the closes. fn observeClose(m: *Machine, id: u32) !void { try m.tasks.items[m.current].views.acquire(m.channels.items[id].close_view, m.heap()); } /// Returns the channel's bytes once it is `CLOSED` with no sender. fn maybeRelease(m: *Machine, id: u32) void { const c = &m.channels.items[id]; if (c.released or c.receiver != .closed or c.senders != 0) return; c.released = true; m.uncharge(c.authority, c.bytes); } fn setParams(f: air.Function, vals: []Value, block: u32, values: []const Value) void { for (f.blocks[block].params, values) |p, v| vals[p.value] = v; } fn execCancellation(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst) !Step { const t = &m.tasks.items[m.current]; switch (inst.op) { .task_check_cancel => |x| { if (!cancelObservable(t)) return .{ .jump_yield = x.ok }; try m.observeCancel(); return .{ .jump_yield = x.cancelled }; }, .task_join_cancel => |x| { const child = vals[x.task].task; if (m.tasks.items[child].state == .done) { m.live_tasks -= 1; try t.views.acquire(m.tasks.items[child].views.cur, m.heap()); setParams(f, vals, x.ok, &.{m.tasks.items[child].result}); return .{ .jump_yield = x.ok }; } if (cancelObservable(t)) { try m.observeCancel(); setParams(f, vals, x.cancelled, &.{vals[x.task]}); return .{ .jump_yield = x.cancelled }; } return .{ .wait = .op }; }, .task_shield_begin => { t.shield += 1; return bind(vals, inst.result, .shield); }, .task_shield_end => { t.shield -= 1; return .next; }, else => unreachable, } } fn execChannel(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst) !Step { const self = m.current; switch (inst.op) { .channel_make => |x| { const n = usize_(vals[x.cap]); const each = budget.accountedSize(m.module, x.elem, 0); const bytes: ?u64 = if (each) |e| std.math.mul(u64, n, e) catch null else null; const a = vals[x.mem].cap; if (!m.charge(a, bytes)) return allocFailed(f, vals, x.err); try m.channels.append(m.arena, .{ .capacity = n, .authority = a, .bytes = bytes.? }); const id: u32 = @intCast(m.channels.items.len - 1); setParams(f, vals, x.ok, &.{ .{ .sender = id }, .{ .receiver = id } }); return .{ .jump = x.ok }; }, .channel_dup => |v| { const id = endpointOf(vals[v]); m.channels.items[id].senders += 1; return bind(vals, inst.result, .{ .sender = id }); }, .channel_close_sender => |v| { const id = vals[v].sender; const ch = &m.channels.items[id]; ch.close_view = try ch.close_view.join(m.tasks.items[self].views.cur, m.heap()); try m.tick(); ch.senders -= 1; m.maybeRelease(id); return .yield; }, .channel_close_receiver => |x| { const id = vals[x.receiver].receiver; const c = &m.channels.items[id]; if (c.buffered() == 0) { c.receiver = .closed; m.maybeRelease(id); return .{ .jump_yield = x.ok }; } c.receiver = .closing; setParams(f, vals, x.pending, &.{vals[x.receiver]}); return .{ .jump_yield = x.pending }; }, .channel_send => |x| { const t = &m.tasks.items[self]; const v = vals[x.value]; if (t.delivered) |_| { t.delivered = null; return .{ .jump_yield = x.ok }; } m.removeOffers(self); const id = endpointOf(vals[x.sender]); switch (m.sendState(id)) { .ok => { try m.doSend(id, v); return .{ .jump_yield = x.ok }; }, .closed => { setParams(f, vals, x.closed, &.{v}); return .{ .jump_yield = x.closed }; }, .none => { if (cancelObservable(t)) { try m.observeCancel(); setParams(f, vals, x.cancelled, &.{v}); return .{ .jump_yield = x.cancelled }; } const c = &m.channels.items[id]; if (c.capacity == 0) try c.send_offers.append(m.heap(), .{ .task = self, .arm = 0, .value = v, .view = t.views.cur }); return .{ .wait = .op }; }, } }, .channel_recv => |x| { const t = &m.tasks.items[self]; if (t.delivered) |d| { t.delivered = null; try t.views.acquire(d.view, m.heap()); setParams(f, vals, x.ok, &.{d.value}); return .{ .jump_yield = x.ok }; } m.removeOffers(self); const id = endpointOf(vals[x.receiver]); switch (m.recvState(id)) { .ok => { setParams(f, vals, x.ok, &.{try m.doRecv(id)}); return .{ .jump_yield = x.ok }; }, .closed => { try m.observeClose(id); return .{ .jump_yield = x.closed }; }, .none => { if (cancelObservable(t)) { try m.observeCancel(); return .{ .jump_yield = x.cancelled }; } const c = &m.channels.items[id]; if (c.capacity == 0) c.recv_offer = .{ .task = self, .arm = 0 }; return .{ .wait = .op }; }, } }, .select => |x| return m.execSelect(f, vals, x), else => unreachable, } } /// `select` (spec 04 §39). fn execSelect(m: *Machine, f: air.Function, vals: []Value, x: @FieldType(air.Op, "select")) !Step { const self = m.current; const t = &m.tasks.items[self]; const ids = try m.heap().alloc(air.ValueId, x.arms.len); const vs = air.Op.selectValues(x.arms, ids); const v_vals = try m.heap().alloc(Value, vs.len); for (vs, v_vals) |v, *o| o.* = vals[v]; if (t.delivered) |d| { t.delivered = null; try t.views.acquire(d.view, m.heap()); return m.selectOk(f, vals, x, d.arm, d.value, vs, v_vals); } m.removeOffers(self); var ready_arms: std.ArrayList(struct { u32, Readiness }) = .empty; for (x.arms, 0..) |arm, i| { const ch = endpointOf(vals[arm.endpoint]); const st = if (arm.value == null) m.recvState(ch) else m.sendState(ch); if (st != .none) try ready_arms.append(m.heap(), .{ @intCast(i), st }); } if (ready_arms.items.len == 0) { if (cancelObservable(t)) { try m.observeCancel(); setParams(f, vals, x.cancelled, v_vals); return .{ .jump_yield = x.cancelled }; } for (x.arms, 0..) |arm, i| { const c = &m.channels.items[endpointOf(vals[arm.endpoint])]; if (c.capacity != 0) continue; if (arm.value) |v| { try c.send_offers.append(m.heap(), .{ .task = self, .arm = @intCast(i), .value = vals[v], .view = t.views.cur }); } else c.recv_offer = .{ .task = self, .arm = @intCast(i) }; } return .{ .wait = .op }; } var pick: usize = 0; if (ready_arms.items.len > 1) { pick = try m.choose(ready_arms.items.len); m.drew = true; } const arm_i, const st = ready_arms.items[pick]; const arm = x.arms[arm_i]; const ch = endpointOf(vals[arm.endpoint]); if (st == .closed) { if (arm.value == null) try m.observeClose(ch); setParams(f, vals, arm.closed, v_vals); return .{ .jump_yield = arm.closed }; } if (arm.value) |v| { try m.doSend(ch, vals[v]); return m.selectOk(f, vals, x, arm_i, .void, vs, v_vals); } return m.selectOk(f, vals, x, arm_i, try m.doRecv(ch), vs, v_vals); } /// Continues at the `ok` target of arm `i`: the received value (for a /// receive arm), then the send values not sent on this edge. fn selectOk(m: *Machine, f: air.Function, vals: []Value, x: @FieldType(air.Op, "select"), i: u32, received: Value, vs: []const air.ValueId, v_vals: []const Value) !Step { const arm = x.arms[i]; var params: std.ArrayList(Value) = .empty; if (arm.value == null) try params.append(m.heap(), received); for (vs, v_vals) |v, val| if (arm.value == null or arm.value.? != v) try params.append(m.heap(), val); setParams(f, vals, arm.ok, params.items); return .{ .jump_yield = arm.ok }; } fn execMutex(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst) !Step { switch (inst.op) { .mutex_make => |v| { const mc = try m.heap().create(Value.MutexCell); const cell = try m.heap().create(Value.Cell); cell.* = .{ .value = try m.deepCopy(vals[v]), .ty = .void }; mc.* = .{ .locked = false, .cell = cell }; return bind(vals, inst.result, .{ .mutex = mc }); }, .mutex_take => |v| return bind(vals, inst.result, vals[v].mutex.cell.value), .mutex_lock => |x| { const mc = mutexOf(vals[x.mutex]); if (!mc.locked) { mc.locked = true; // unlock → the next lock (spec 04 §20.3). try m.tasks.items[m.current].views.acquire(mc.view, m.heap()); setParams(f, vals, x.ok, &.{.{ .guard = mc }}); return .{ .jump_yield = x.ok }; } if (cancelObservable(&m.tasks.items[m.current])) { try m.observeCancel(); return .{ .jump_yield = x.cancelled }; } return .{ .wait = .op }; }, .mutex_borrow => |g| return bind(vals, inst.result, .{ .place = .{ .cell = vals[g].guard.cell, .path = &.{} } }), .mutex_unlock => |g| { vals[g].guard.locked = false; vals[g].guard.view = m.tasks.items[m.current].views.cur; try m.tick(); return .yield; }, else => unreachable, } } // ------------------------------------------------------------ atomics (spec 04 §20–§30, §42) fn cellOf(v: Value) u32 { return switch (v) { .atomic => |id| id, .place => |p| cellOf(placePtr(p).*), else => unreachable, }; } fn scalarBits(v: Value) u128 { return switch (v) { .int => |x| x.bits, .boolean => |b| @intFromBool(b), else => unreachable, }; } fn scalarValue(ty: air.Type, bits: u128) Value { return switch (ty) { .int => |it| .{ .int = .{ .ty = it, .bits = bits } }, .bool => .{ .boolean = bits != 0 }, else => unreachable, }; } /// A weak-memory choice among `n` readable messages (spec 04 §42). fn weakChoice(m: *Machine, n: u64) !u64 { if (n == 1) return 0; m.drew = true; return try m.choose(@intCast(n)); } fn execAtomic(m: *Machine, vals: []Value, inst: air.Inst) !Step { const gpa = m.heap(); // A write or fence may release: later accesses get a new clock. defer if (m.detect_races) switch (inst.op) { .atomic_store, .atomic_rmw, .atomic_cmpxchg, .atomic_fence => m.tick() catch {}, else => {}, }; const views = &m.tasks.items[m.current].views; switch (inst.op) { .atomic_new => |v| { const ty: air.Type = switch (vals[v]) { .int => |x| .{ .int = x.ty }, else => .bool, }; return bind(vals, inst.result, .{ .atomic = try m.mem.create(gpa, m.arena, ty, scalarBits(vals[v])) }); }, .atomic_take => |v| { const c = &m.mem.cells.items[vals[v].atomic]; const value = scalarValue(c.ty, c.at(c.latest()).bits); c.taken = true; return bind(vals, inst.result, value); }, .atomic_load => |x| { const id = cellOf(vals[x.cell]); const first, const last = m.mem.readRange(views, id, x.ord); const ts = first + try m.weakChoice(last - first + 1); const bits = try m.mem.read(gpa, views, id, ts, x.ord); vals[inst.result.?] = scalarValue(m.mem.cells.items[id].ty, bits); return m.yieldUnlessExploring(); }, .atomic_store => |x| { try m.mem.write(gpa, views, cellOf(vals[x.cell]), scalarBits(vals[x.value]), x.ord, .{}); return m.yieldUnlessExploring(); }, .atomic_rmw => |x| { const id = cellOf(vals[x.cell]); const ty = m.mem.cells.items[id].ty; const old, const carried = try m.mem.rmwRead(gpa, views, id, x.ord); const operand = scalarBits(vals[x.value]); const new: u128 = switch (x.op) { .xchg => operand, .add_wrap => arith(.add, .wrap, ty.int, old, operand) catch unreachable, .sub_wrap => arith(.sub, .wrap, ty.int, old, operand) catch unreachable, .@"and" => old & operand, .@"or" => old | operand, .xor => old ^ operand, }; try m.mem.write(gpa, views, id, new, x.ord, carried); vals[inst.result.?] = scalarValue(ty, old); return m.yieldUnlessExploring(); }, .atomic_cmpxchg => |x| { const id = cellOf(vals[x.cell]); const c = &m.mem.cells.items[id]; const expected = scalarBits(vals[x.expected]); // Readable messages: the latest (a success when it equals // the expected value), and older ones that differ from it // (failures; a strong CAS cannot fail on an equal value). const first, const last = m.mem.readRange(views, id, x.failure); var options: std.ArrayList(u64) = .empty; var ts = first; while (ts < last) : (ts += 1) if (c.at(ts).bits != expected) try options.append(gpa, ts); try options.append(gpa, c.latest()); const pick = options.items[@intCast(try m.weakChoice(options.items.len))]; const ty = c.ty; if (pick == c.latest() and c.at(pick).bits == expected) { const old, const carried = try m.mem.rmwRead(gpa, views, id, x.success); try m.mem.write(gpa, views, id, scalarBits(vals[x.desired]), x.success, carried); vals[inst.result.?] = scalarValue(ty, old); vals[inst.result2.?] = .{ .boolean = true }; } else { const bits = try m.mem.read(gpa, views, id, pick, x.failure); vals[inst.result.?] = scalarValue(ty, bits); vals[inst.result2.?] = .{ .boolean = false }; } return m.yieldUnlessExploring(); }, .atomic_fence => |o| { try m.mem.fence(gpa, views, o); return m.yieldUnlessExploring(); }, else => unreachable, } } fn mutexOf(v: Value) *Value.MutexCell { return switch (v) { .mutex => |mc| mc, .place => |p| mutexOf(placePtr(p).*), else => unreachable, }; } fn bind(vals: []Value, result: ?air.ValueId, v: Value) Step { vals[result.?] = v; return .next; } // ------------------------------------------------------------ memory (spec 07a, features ownership/arrays) /// Values in storage never share structure with SSA values, so every /// transfer between the two copies aggregates and arrays. fn deepCopy(m: *Machine, v: Value) std.mem.Allocator.Error!Value { return switch (v) { .aggregate => |a| .{ .aggregate = .{ .decl = a.decl, .variant = a.variant, .fields = try m.copyAll(a.fields) } }, .array => |items| .{ .array = try m.copyAll(items) }, else => v, }; } fn copyAll(m: *Machine, items: []const Value) std.mem.Allocator.Error![]Value { const out = try m.heap().alloc(Value, items.len); for (items, out) |x, *o| o.* = try m.deepCopy(x); return out; } fn zeroValue(m: *Machine, t: air.Type) std.mem.Allocator.Error!Value { return switch (t) { .int => |it| .{ .int = .{ .ty = it, .bits = 0 } }, .bool => .{ .boolean = false }, .array => |a| blk: { const items = try m.heap().alloc(Value, a.len); for (items) |*x| x.* = try m.zeroValue(a.elem); break :blk .{ .array = items }; }, .named => |i| blk: { const fields = m.module.types[i].kind.@"struct"; const out = try m.heap().alloc(Value, fields.len); for (fields, out) |fd, *o| o.* = try m.zeroValue(fd.ty); break :blk .{ .aggregate = .{ .decl = i, .variant = 0, .fields = out } }; }, else => unreachable, // verified zeroable }; } fn placePtr(p: Value.Place) *Value { var v = if (p.cell.backing) |b| &b.values[b.index] else &p.cell.value; for (p.path) |i| v = switch (v.*) { .aggregate => |a| &a.fields[i], .array => |items| &items[i], else => unreachable, }; return v; } fn pathTo(m: *Machine, p: Value.Place, i: u64) ![]const u32 { return (try m.extend(p, i)).path; } fn extend(m: *Machine, p: Value.Place, i: u64) !Value.Place { const path = try m.heap().alloc(u32, p.path.len + 1); @memcpy(path[0..p.path.len], p.path); path[p.path.len] = @intCast(i); return .{ .cell = p.cell, .path = path }; } fn asPlace(v: Value) Value.Place { return switch (v) { .local => |c| .{ .cell = c, .path = &.{} }, .place => |p| p, else => unreachable, }; } // ------------------------------------------------------------ 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, .schedule = if (m.spawned or m.drew) .{ .seed = m.schedule_seed, .quantum = m.quantum, .choices = m.choices } else null, }; } /// Bytes of a `slice` 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.heap().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` 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| placePtr(p).resource, else => unreachable, }; } fn narrow(m: *Machine, f: air.Function, vals: []Value, x: @FieldType(air.Op, "cap_narrow")) !Step { const parent = vals[x.cap].cap; const a = m.authorities.items[parent]; if (std.mem.eql(u8, x.form, "budget")) { // A child budget; nothing is reserved (spec 03 §18.3). const n = usize_(vals[x.args[0]]); if (a.limit) |lim| if (n > lim) { vals[f.blocks[x.err].params[0].value] = .{ .builtin = .{ .which = .cap_error, .variant = 1 } }; return .{ .jump = x.err }; }; try m.authorities.append(m.arena, .{ .kind = a.kind, .scope = null, .limit = n, .parent = parent }); vals[f.blocks[x.ok].params[0].value] = .{ .cap = @intCast(m.authorities.items.len - 1) }; return .{ .jump = x.ok }; } // `prefix` (reference/capabilities.md). const path = try m.bytesOf(vals[x.args[0]]); const reason: ?u32 = if (!world_mod.World.validPath(path)) 0 else if (!world_mod.World.within(a.scope, path)) 1 else null; if (reason) |r| { 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 = try m.arena.dupe(u8, path) }); vals[f.blocks[x.ok].params[0].value] = .{ .cap = @intCast(m.authorities.items.len - 1) }; return .{ .jump = x.ok }; } // ------------------------------------------------------------ heap and regions (spec 03 §18–§20) /// Charges `bytes` to authority `a` and all its ancestors, or fails /// without charging anything if any limit would be exceeded. fn charge(m: *Machine, a: u32, bytes: ?u64) bool { const b = bytes orelse return false; // size overflow var x: ?u32 = a; while (x) |i| : (x = m.authorities.items[i].parent) { const auth = m.authorities.items[i]; if (auth.limit) |lim| if (auth.used > lim or b > lim - auth.used) return false; } x = a; while (x) |i| : (x = m.authorities.items[i].parent) m.authorities.items[i].used += b; return true; } fn uncharge(m: *Machine, a: u32, bytes: u64) void { var x: ?u32 = a; while (x) |i| : (x = m.authorities.items[i].parent) m.authorities.items[i].used -= bytes; } fn arrayBytes(m: *Machine, element: Value, n: u64) ?u64 { const each = m.valueBytes(element) orelse return null; return std.math.mul(u64, n, each) catch null; } /// Accounted size (spec 08 §7.1) of the type of a runtime value; equal /// to `budget.accountedSize` of the value's static type. fn valueBytes(m: *Machine, v: Value) ?u64 { return switch (v) { .int => |x| x.ty.bits() / 8, .boolean => 1, .aggregate => |a| budget.accountedSize(m.module, .{ .named = a.decl }, 0), .array => |items| std.math.mul(u64, items.len, m.valueBytes(items[0]) orelse return null) catch null, .builtin => |b| budget.accountedSize(m.module, .{ .builtin = b.which }, 0), .cap => 8, .iref => 16, else => unreachable, // only value types are allocated (spec 03 §19.2) }; } // ------------------------------------------------------------ graphs (spec 03 §22–§24) /// A graph's header, charged once at creation; it includes room for an /// `arc` count, so converting to an `arc` charges nothing (spec 03 §24). const graph_header = 16; /// The graph behind an owner or a borrow of one. fn graphOf(v: Value) *Value.Graph { return switch (v) { .graph => |g| g, .place => |p| placePtr(p).graph, else => unreachable, }; } fn arcEvent(m: *Machine, op: @FieldType(ArcEvent, "op"), g: *Value.Graph) !void { if (m.arc_events) |list| try list.append(m.arena, .{ .op = op, .graph = g.id, .count = g.count }); } fn newGraph(m: *Machine, a: u32, bytes: u64, root: Value) !*Value.Graph { const g = try m.heap().create(Value.Graph); g.* = .{ .id = m.next_graph, .authority = a, .bytes = bytes }; m.next_graph += 1; const cell = try m.heap().create(Value.Cell); cell.* = .{ .value = try m.deepCopy(root), .ty = .void }; try g.objects.append(m.heap(), cell); return g; } /// Frees a graph's objects and returns its bytes to its authority. fn releaseGraph(m: *Machine, g: *Value.Graph) void { m.uncharge(g.authority, g.bytes); g.bytes = 0; g.objects = .empty; } /// The object an `iref` names in graph `g`, or `T0010`. fn objectOf(g: *Value.Graph, r: Value) ?*Value.Cell { if (r.iref.id != g.id or r.iref.slot >= g.objects.items.len) return null; return g.objects.items[r.iref.slot]; } fn execGraph(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst) !Step { switch (inst.op) { inline .island_create, .arc_new => |x| { const v = vals[x.value]; const a = vals[x.cap].cap; const bytes = if (m.valueBytes(v)) |b| (std.math.add(u64, b, graph_header) catch null) else null; if (!m.charge(a, bytes)) return allocFailed(f, vals, x.err); const g = try m.newGraph(a, bytes.?, v); if (inst.op == .arc_new) { g.frozen = true; g.count = 1; try m.arcEvent(.new, g); } vals[f.blocks[x.ok].params[0].value] = .{ .graph = g }; return .{ .jump = x.ok }; }, .island_alloc => |x| { const g = graphOf(vals[x.island]); const v = vals[x.value]; const bytes = m.valueBytes(v); if (!m.charge(g.authority, bytes)) return allocFailed(f, vals, x.err); g.bytes += bytes.?; const cell = try m.heap().create(Value.Cell); cell.* = .{ .value = try m.deepCopy(v), .ty = .void }; try g.objects.append(m.heap(), cell); vals[f.blocks[x.ok].params[0].value] = .{ .iref = .{ .id = g.id, .slot = @intCast(g.objects.items.len - 1) } }; return .{ .jump = x.ok }; }, .island_root, .frozen_root, .arc_root => |v| return bind(vals, inst.result, .{ .iref = .{ .id = graphOf(vals[v]).id, .slot = 0 } }), inline .island_borrow, .frozen_borrow, .arc_borrow => |x| { const g = graphOf(vals[x.owner]); const cell = objectOf(g, vals[x.iref]) orelse return .{ .trap = .foreign_iref }; return bind(vals, inst.result, .{ .place = .{ .cell = cell, .path = &.{} } }); }, .island_freeze => |v| { const g = vals[v].graph; g.frozen = true; return bind(vals, inst.result, .{ .graph = g }); }, .island_destroy, .frozen_release => |v| { m.releaseGraph(vals[v].graph); return .next; }, .arc_from_frozen => |v| { const g = vals[v].graph; g.count = 1; try m.arcEvent(.from_frozen, g); return bind(vals, inst.result, .{ .graph = g }); }, .arc_clone => |v| { const g = graphOf(vals[v]); g.count += 1; try m.arcEvent(.clone, g); return bind(vals, inst.result, .{ .graph = g }); }, .arc_release => |v| { const g = vals[v].graph; g.count -= 1; try m.arcEvent(.release, g); if (g.count == 0) m.releaseGraph(g); return .next; }, .iref_eq => |x| { const a = vals[x.a].iref; const b = vals[x.b].iref; return bind(vals, inst.result, .{ .boolean = a.id == b.id and a.slot == b.slot }); }, else => unreachable, } } fn bufferOf(v: Value) *Value.Buffer { return switch (v) { .buffer => |b| b, .place => |p| bufferOf(placePtr(p).*), else => unreachable, }; } fn execBuffer(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst) !Step { switch (inst.op) { .buffer_new => |x| { const capacity = usize_(vals[x.n]); const size = budget.accountedSize(m.module, x.ty, 0).?; const bytes = std.math.mul(u64, capacity, size) catch null; const authority_ = vals[x.cap].cap; if (!m.charge(authority_, bytes)) return allocFailed(f, vals, x.err); const cell = try m.heap().create(Value.Cell); cell.* = .{ .value = .{ .array = &.{} }, .ty = .void }; const b = try m.heap().create(Value.Buffer); b.* = .{ .cell = cell, .capacity = capacity, .elem = x.ty }; try m.owners.put(m.heap(), cell, .{ .authority = authority_, .bytes = bytes.? }); vals[f.blocks[x.ok].params[0].value] = .{ .buffer = b }; return .{ .jump = x.ok }; }, .buffer_len, .buffer_capacity => |v| { const b = bufferOf(vals[v]); if (try m.raceCheck(b.cell, &.{}, false)) |r| return r; return bind(vals, inst.result, .{ .int = .{ .ty = .usize, .bits = if (inst.op == .buffer_len) b.cell.value.array.len else b.capacity } }); }, .buffer_view => |v| { const b = bufferOf(vals[v]); if (try m.raceCheck(b.cell, &.{}, false)) |r| return r; return bind(vals, inst.result, .{ .slice = .{ .place = .{ .cell = b.cell, .path = &.{} }, .start = 0, .len = b.cell.value.array.len } }); }, .buffer_reserve => |x| { const b = bufferOf(vals[x.borrow]); if (try m.raceCheck(b.cell, &.{}, true)) |r| return r; const capacity = usize_(vals[x.n]); if (capacity <= b.capacity) return .{ .jump = x.ok }; const size = budget.accountedSize(m.module, b.elem, 0).?; const bytes = std.math.mul(u64, capacity, size) catch null; const authority_ = vals[x.cap].cap; if (!m.charge(authority_, bytes)) return allocFailed(f, vals, x.err); const old = m.owners.get(b.cell).?; m.uncharge(old.authority, old.bytes); try m.owners.put(m.heap(), b.cell, .{ .authority = authority_, .bytes = bytes.? }); b.capacity = capacity; return .{ .jump = x.ok }; }, .buffer_push => |x| { const b = bufferOf(vals[x.borrow]); if (try m.raceCheck(b.cell, &.{}, true)) |r| return r; const old = b.cell.value.array; if (old.len == b.capacity) { vals[f.blocks[x.err].params[0].value] = vals[x.value]; return .{ .jump = x.err }; } const items = try m.heap().alloc(Value, old.len + 1); @memcpy(items[0..old.len], old); items[old.len] = try m.deepCopy(vals[x.value]); b.cell.value = .{ .array = items }; return .{ .jump = x.ok }; }, .buffer_pop => |x| { const b = bufferOf(vals[x.value]); if (try m.raceCheck(b.cell, &.{}, true)) |r| return r; const old = b.cell.value.array; if (old.len == 0) return .{ .jump = x.err }; vals[f.blocks[x.ok].params[0].value] = old[old.len - 1]; b.cell.value = .{ .array = old[0 .. old.len - 1] }; return .{ .jump = x.ok }; }, .buffer_free => |x| { const b = bufferOf(vals[x.value]); if (try m.raceCheck(b.cell, &.{}, true)) |r| return r; if (b.cell.value.array.len != 0) { vals[f.blocks[x.err].params[0].value] = vals[x.value]; return .{ .jump = x.err }; } const allocation = m.owners.fetchRemove(b.cell).?.value; m.uncharge(allocation.authority, allocation.bytes); return .{ .jump = x.ok }; }, else => unreachable, } } fn allocFailed(f: air.Function, vals: []Value, err: u32) Step { vals[f.blocks[err].params[0].value] = .{ .builtin = .{ .which = .alloc_error, .variant = 0 } }; return .{ .jump = err }; } /// Owner cells remember their charge and authority for `own.free`. fn execAlloc(m: *Machine, f: air.Function, vals: []Value, types_of: anytype, inst: air.Inst) !Step { _ = types_of; switch (inst.op) { .own_pack => |x| { const a = vals[x.cap].cap; const bytes = budget.accountedSize(m.module, x.ty, 0); if (!m.charge(a, bytes)) { vals[f.blocks[x.err].params[1].value] = vals[x.value]; return allocFailed(f, vals, x.err); } const cell = try m.heap().create(Value.Cell); cell.* = .{ .value = try m.deepCopy(vals[x.value]), .ty = x.ty }; try m.owners.put(m.heap(), cell, .{ .authority = a, .bytes = bytes.? }); vals[f.blocks[x.ok].params[0].value] = .{ .own = cell }; return .{ .jump = x.ok }; }, .own_new => |x| { const v = vals[x.value]; const bytes = m.valueBytes(vals[x.value]); const a = vals[x.cap].cap; if (!m.charge(a, bytes)) return allocFailed(f, vals, x.err); const cell = try m.heap().create(Value.Cell); cell.* = .{ .value = try m.deepCopy(v), .ty = .void }; try m.owners.put(m.heap(), cell, .{ .authority = a, .bytes = bytes.? }); vals[f.blocks[x.ok].params[0].value] = .{ .own = cell }; return .{ .jump = x.ok }; }, .own_array => |x| { const n = usize_(vals[x.n]); const a = vals[x.cap].cap; const bytes = m.arrayBytes(vals[x.value], n); if (!m.charge(a, bytes)) return allocFailed(f, vals, x.err); const items = try m.heap().alloc(Value, n); for (items) |*it| it.* = try m.deepCopy(vals[x.value]); const cell = try m.heap().create(Value.Cell); cell.* = .{ .value = .{ .array = items }, .ty = .void, .owner_array = true }; try m.owners.put(m.heap(), cell, .{ .authority = a, .bytes = bytes.? }); vals[f.blocks[x.ok].params[0].value] = .{ .own = cell }; return .{ .jump = x.ok }; }, .own_take => |v| { const cell = vals[v].own; const info = m.owners.fetchRemove(cell).?.value; m.uncharge(info.authority, info.bytes); return bind(vals, inst.result, cell.value); }, .own_free => |v| { const info = m.owners.fetchRemove(vals[v].own).?.value; m.uncharge(info.authority, info.bytes); return .next; }, .region_create => |x| { try m.regions.append(m.arena, .{ .authority = vals[x.cap].cap, .used = 0 }); vals[f.blocks[x.ok].params[0].value] = .{ .region = @intCast(m.regions.items.len - 1) }; return .{ .jump = x.ok }; }, .region_new, .region_array => { const rb, const value, const n: ?u64 = switch (inst.op) { .region_new => |x| .{ x.region, x.value, null }, .region_array => |x| .{ x.region, x.value, usize_(vals[x.n]) }, else => unreachable, }; const t = air.allocTargets(inst.op).?; const r = placePtr(asPlace(vals[rb])).region; const region = &m.regions.items[r]; const bytes = if (n) |count| m.arrayBytes(vals[value], count) else m.valueBytes(vals[value]); if (!m.charge(region.authority, bytes)) return allocFailed(f, vals, t.err); region.used += bytes.?; const cell = try m.heap().create(Value.Cell); if (n) |count| { const items = try m.heap().alloc(Value, count); for (items) |*it| it.* = try m.deepCopy(vals[value]); cell.* = .{ .value = .{ .array = items }, .ty = .void }; vals[f.blocks[t.ok].params[0].value] = .{ .slice = .{ .place = .{ .cell = cell, .path = &.{} }, .start = 0, .len = count } }; } else { cell.* = .{ .value = try m.deepCopy(vals[value]), .ty = .void }; vals[f.blocks[t.ok].params[0].value] = .{ .place = .{ .cell = cell, .path = &.{} } }; } return .{ .jump = t.ok }; }, .region_reset, .region_destroy => |v| { const region = &m.regions.items[vals[v].region]; m.uncharge(region.authority, region.used); region.used = 0; return .next; }, else => unreachable, } } fn intrinsic(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst, x: @FieldType(air.Op, "intrinsic")) !Step { const name = air.authority.intrinsics[x.index].name; const arg = struct { fn at(v: []Value, xx: @FieldType(air.Op, "intrinsic"), i: usize) Value { return v[xx.args[i]]; } }.at; var result: ?Value = null; 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; // `m.host` is the hosted profile; otherwise the deterministic world. if (is(name, "clock.monotonic")) { const now = if (m.host) |*hs| hs.monotonic() else m.steps; return bind(vals, inst.result, .{ .int = .{ .ty = .u64, .bits = now } }); } else if (is(name, "random.fill")) { const buf = try m.heap().alloc(u8, arg(vals, x, 1).slice.len); if (m.host) |*hs| hs.fill(buf) else 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")) { const bytes = try m.bytesOf(arg(vals, x, 1)); const err_stream = is(name, "io.stderr_write"); if (m.host) |*hs| failure = hs.writeOut(err_stream, bytes) else try m.world.writeOut(err_stream, bytes); } else if (is(name, "io.stdin_read")) { const buf = try m.heap().alloc(u8, arg(vals, x, 1).slice.len); const n: usize = if (m.host) |*hs| switch (hs.readIn(buf)) { .ok => |k| k, .err => |e| blk: { failure = e; break :blk 0; }, } else m.world.readIn(buf); fillSlice(arg(vals, x, 1), buf[0..n]); result = .{ .int = .{ .ty = .usize, .bits = n } }; } 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; const path = try m.bytesOf(arg(vals, x, 1)); switch (if (m.host) |*hs| try hs.open(scope, path, mode) else try m.world.open(scope, path, mode)) { .ok => |hd| result = .{ .resource = hd }, .err => |e| failure = e, } } else if (is(name, "fs.read")) { const buf = try m.heap().alloc(u8, arg(vals, x, 1).slice.len); const hd = resourceOf(arg(vals, x, 0)); const n: usize = if (m.host) |*hs| switch (hs.fileRead(hd, buf)) { .ok => |k| k, .err => |e| blk: { failure = e; break :blk 0; }, } else m.world.fileRead(hd, buf); fillSlice(arg(vals, x, 1), buf[0..n]); result = .{ .int = .{ .ty = .usize, .bits = n } }; } else if (is(name, "fs.write_all")) { const hd = resourceOf(arg(vals, x, 0)); const bytes = try m.bytesOf(arg(vals, x, 1)); if (m.host) |*hs| failure = hs.fileWrite(hd, bytes) else try m.world.fileWrite(hd, bytes); } else if (is(name, "fs.sync")) { // The in-memory file system is durable by construction. if (m.host) |*hs| failure = hs.sync(resourceOf(arg(vals, x, 0))); } else if (is(name, "fs.close") or is(name, "net.close_stream") or is(name, "net.close_listener")) { if (m.host) |*hs| hs.close(arg(vals, x, 0).resource) else 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)); const listen = is(name, "net.listen"); const r = if (m.host) |*hs| (if (listen) try hs.listen(addr) else try hs.connect(addr)) else (if (listen) try m.world.listen(addr) else try m.world.connect(addr)); switch (r) { .ok => |hd| result = .{ .resource = hd }, .err => |e| failure = e, } } else if (is(name, "net.accept")) { const hd = resourceOf(arg(vals, x, 0)); 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 .{ .wait = .{ .accept = hd } } }; } else if (is(name, "net.recv")) { const buf = try m.heap().alloc(u8, arg(vals, x, 1).slice.len); const hd = resourceOf(arg(vals, x, 0)); const n: usize = if (m.host) |*hs| switch (hs.recv(hd, buf)) { .ok => |k| k, .err => |e| blk: { failure = e; break :blk 0; }, } 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")) { const hd = resourceOf(arg(vals, x, 0)); const bytes = try m.bytesOf(arg(vals, x, 1)); failure = if (m.host) |*hs| hs.send(hd, bytes) else try m.world.send(hd, bytes); } else unreachable; // every registered intrinsic is handled above if (failure) |e| { vals[f.blocks[x.err.?].params[0].value] = .{ .builtin = .{ .which = .io_error, .variant = @backingInt(e) } }; return .{ .jump = x.err.? }; } if (result) |r| vals[f.blocks[x.ok.?].params[0].value] = r; return .{ .jump = x.ok.? }; } fn usize_(v: Value) u64 { return @truncate(v.int.bits); } fn ssaCell(m: *Machine, vals: []Value, index: u32) !*Value.Cell { for (vals) |v| { const cell: ?*Value.Cell = switch (v) { .place => |p| p.cell, .slice => |s| s.place.cell, else => null, }; if (cell) |c| if (c.backing) |b| if (b.values.ptr == vals.ptr and b.index == index) return c; } const cell = try m.heap().create(Value.Cell); cell.* = .{ .value = .void, .ty = .void, .backing = .{ .values = vals, .index = index } }; return cell; } fn execMemory(m: *Machine, vals: []Value, inst: air.Inst) std.mem.Allocator.Error!Step { switch (inst.op) { .local_alloc => |t| { const cell = try m.heap().create(Value.Cell); cell.* = .{ .value = .void, .ty = t }; return bind(vals, inst.result, .{ .local = cell }); }, .local_store => |x| { if (try m.raceCheck(vals[x.local].local, &.{}, true)) |r| return r; vals[x.local].local.value = try m.deepCopy(vals[x.value]); return .next; }, .local_zero => |v| { const cell = vals[v].local; if (try m.raceCheck(cell, &.{}, true)) |r| return r; cell.value = try m.zeroValue(cell.ty); return .next; }, .local_load => |v| { if (try m.raceCheck(vals[v].local, &.{}, false)) |r| return r; 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 = &.{} } }, .own => |cell| if (cell.owner_array) .{ .slice = .{ .place = .{ .cell = cell, .path = &.{} }, .start = 0, .len = cell.value.array.len } } else .{ .place = .{ .cell = cell, .path = &.{} } }, .aggregate, .array, .resource, .region => .{ .place = .{ .cell = try m.ssaCell(vals, v), .path = &.{} } }, .graph => if (inst.op == .borrow_mut) .{ .place = .{ .cell = try m.ssaCell(vals, v), .path = &.{} } } else vals[v], else => |x| x, }), .borrow_field => |x| return bind(vals, inst.result, .{ .place = try m.extend(asPlace(vals[x.borrow]), x.field) }), .borrow_end => return .next, .load => |v| { const p = asPlace(vals[v]); if (try m.raceCheck(p.cell, p.path, false)) |r| return r; return bind(vals, inst.result, try m.deepCopy(placePtr(p).*)); }, .store => |x| { const p = asPlace(vals[x.borrow]); if (try m.raceCheck(p.cell, p.path, true)) |r| return r; placePtr(p).* = try m.deepCopy(vals[x.value]); return .next; }, .value_swap => |x| { const p = asPlace(vals[x.borrow]); if (try m.raceCheck(p.cell, p.path, true)) |r| return r; const old = placePtr(p).*; placePtr(p).* = try m.deepCopy(vals[x.value]); return bind(vals, inst.result, old); }, .array_splat => |x| { const items = try m.heap().alloc(Value, x.ty.array.len); for (items) |*it| it.* = try m.deepCopy(vals[x.value]); return bind(vals, inst.result, .{ .array = items }); }, .borrow_index => |x| { const i = usize_(vals[x.index]); const place: Value.Place, const start: u64, const len: u64 = switch (vals[x.borrow]) { .slice => |s| .{ s.place, s.start, s.len }, else => |b| .{ asPlace(b), 0, placePtr(asPlace(b)).array.len }, }; // `.proven` was verified in bounds; the check is kept as a // defensive assertion that can never fire on verified AIR. // The reference interpreter detects violated unsafe // preconditions (spec 13 §6.1). if (i >= len) return .{ .trap = if (x.unchecked) .unsafe_precondition else .out_of_bounds }; return bind(vals, inst.result, .{ .place = try m.extend(place, start + i) }); }, .slice_make => |v| { const p = asPlace(vals[v]); return bind(vals, inst.result, .{ .slice = .{ .place = p, .start = 0, .len = placePtr(p).array.len } }); }, .slice_len => |v| return bind(vals, inst.result, .{ .int = .{ .ty = .usize, .bits = vals[v].slice.len } }), .slice_sub => |x| { const s = vals[x.slice].slice; const start = usize_(vals[x.start]); const len = usize_(vals[x.len]); if (start > s.len or len > s.len - start) return .{ .trap = .out_of_bounds }; return bind(vals, inst.result, .{ .slice = .{ .place = s.place, .start = s.start + start, .len = len } }); }, .slice_split => |x| { const s = vals[x.slice].slice; const at = usize_(vals[x.at]); if (at > s.len) return .{ .trap = .out_of_bounds }; vals[inst.result.?] = .{ .slice = .{ .place = s.place, .start = s.start, .len = at } }; vals[inst.result2.?] = .{ .slice = .{ .place = s.place, .start = s.start + at, .len = s.len - at } }; return .next; }, .slice_copy => |x| { const d = vals[x.dst].slice; const s = vals[x.src].slice; if (d.len < s.len) return .{ .trap = .out_of_bounds }; const dst = placePtr(d.place).array; const src = placePtr(s.place).array; // Operands never overlap (spec 08 §11.2), so a forward copy is exact. if (m.detect_races) for (0..s.len) |k| { if (try m.raceCheck(s.place.cell, try m.pathTo(s.place, s.start + k), false)) |r| return r; if (try m.raceCheck(d.place.cell, try m.pathTo(d.place, d.start + k), true)) |r| return r; }; for (0..s.len) |k| dst[d.start + k] = try m.deepCopy(src[s.start + k]); return .next; }, .guard => |v| return if (vals[v].boolean) .next else .{ .trap = .assert }, .assume => |v| return if (vals[v].boolean) .next else .{ .trap = .unsafe_precondition }, else => unreachable, } } fn gather(m: *Machine, vals: []const Value, ids: []const air.ValueId) ![]const Value { return m.gatherMut(vals, ids); } fn gatherMut(m: *Machine, vals: []const Value, ids: []const air.ValueId) ![]Value { const out = try m.heap().alloc(Value, ids.len); for (ids, out) |id, *o| o.* = vals[id]; return out; } /// Block arguments are bound simultaneously (spec 07 §8.2). fn jump(m: *Machine, f: air.Function, vals: []Value, t: air.Target) !Step { const tmp = try m.gather(vals, t.args); for (f.blocks[t.block].params, tmp) |p, v| vals[p.value] = v; return .{ .jump = t.block }; } }; // ---------------------------------------------------------------- integer semantics (spec 02 §2.1) fn Unsigned(comptime T: type) type { return @Int(.unsigned, @bitSizeOf(T)); } fn decode(comptime T: type, bits: u128) T { return @bitCast(@as(Unsigned(T), @truncate(bits))); } fn encode(comptime T: type, v: T) u128 { return @as(Unsigned(T), @bitCast(v)); } fn arith(op: air.ArithOp, mode: air.ArithMode, ty: air.IntType, a: u128, b: u128) TrapError!u128 { switch (ty) { inline else => |t| { const T = air.IntType.Zig(t); const x = decode(T, a); const y = decode(T, b); const r: T = switch (mode) { .wrap => switch (op) { .add => x +% y, .sub => x -% y, .mul => x *% y, .div, .rem => unreachable, // not in the grammar }, .checked => switch (op) { .add => try noOverflow(T, @addWithOverflow(x, y)), .sub => try noOverflow(T, @subWithOverflow(x, y)), .mul => try noOverflow(T, @mulWithOverflow(x, y)), .div, .rem => r: { if (y == 0) return error.division_by_zero; if (comptime t.signed()) { if (x == std.math.minInt(T) and y == -1) return error.overflow; } break :r if (op == .div) @divTrunc(x, y) else @rem(x, y); }, }, }; return encode(T, r); }, } } fn noOverflow(comptime T: type, r: struct { T, u1 }) TrapError!T { if (r[1] != 0) return error.overflow; return r[0]; } fn bitop(op: air.BitOp, ty: air.IntType, a: u128, b: u128) TrapError!u128 { switch (ty) { inline else => |t| { const T = air.IntType.Zig(t); const x = decode(T, a); const y = decode(T, b); const r: T = switch (op) { .@"and" => x & y, .@"or" => x | y, .xor => x ^ y, .shl, .shr => r: { if (y < 0 or y >= @bitSizeOf(T)) return error.shift_out_of_range; const n: std.math.Log2Int(T) = @intCast(y); break :r if (op == .shl) x << n else x >> n; }, }; return encode(T, r); }, } } fn compare(op: air.CmpOp, ty: air.IntType, a: u128, b: u128) bool { switch (ty) { inline else => |t| { const T = air.IntType.Zig(t); const x = decode(T, a); const y = decode(T, b); return switch (op) { .eq => x == y, .ne => x != y, .lt => x < y, .le => x <= y, .gt => x > y, .ge => x >= y, }; }, } } fn cast(mode: air.CastMode, from: air.IntType, to: air.IntType, bits: u128) TrapError!u128 { // Every integer type fits in i129, so the numeric value is exact here. const v: i129 = switch (from) { inline else => |t| decode(air.IntType.Zig(t), bits), }; switch (to) { inline else => |t| { const T = air.IntType.Zig(t); const r: T = switch (mode) { .checked, .widen => std.math.cast(T, v) orelse return error.cast_out_of_range, .wrap => @bitCast(@as(Unsigned(T), @truncate(@as(u129, @bitCast(v))))), }; return encode(T, r); }, } } // ---------------------------------------------------------------- run records (spec 07a "Run result") pub fn writeValue(module: air.Module, v: Value, s: *std.json.Stringify) std.Io.Writer.Error!void { switch (v) { .int => |x| switch (x.ty) { inline else => |t| try s.print("{d}", .{decode(air.IntType.Zig(t), x.bits)}), }, .boolean => |b| try s.write(b), .void => try s.write(null), .array => |items| { try s.beginArray(); for (items) |x| try writeValue(module, x, s); try s.endArray(); }, // Storage and borrows cannot be returned from `@main` (spec 08 §11.3). .local, .place, .slice => try s.write(null), .resource, .own, .buffer, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .graph, .iref, .atomic => try s.write(null), // A capability is opaque: only its kind is shown, never its identity. .cap => { try s.beginObject(); try s.objectField("capability"); try s.write("opaque"); try s.endObject(); }, .builtin => |b| { try s.beginObject(); try s.objectField("variant"); try s.write(b.which.variants()[b.variant]); try s.objectField("payload"); try s.beginArray(); try s.endArray(); try s.endObject(); }, .aggregate => |agg| { const d = module.types[agg.decl]; switch (d.kind) { .@"struct" => |fields| { try s.beginObject(); for (fields, agg.fields) |fd, fv| { try s.objectField(fd.name); try writeValue(module, fv, s); } try s.endObject(); }, .@"enum" => |variants| { try s.beginObject(); try s.objectField("variant"); try s.write(variants[agg.variant].name); try s.objectField("payload"); try s.beginArray(); for (agg.fields) |fv| try writeValue(module, fv, s); try s.endArray(); try s.endObject(); }, } }, } } /// Byte strings in the run record (spec 07a "Run result"): a JSON string /// when the bytes are valid UTF-8, otherwise {"encoding":"base64","data":…}. fn writeText(s: *std.json.Stringify, bytes: []const u8) std.Io.Writer.Error!void { if (std.unicode.utf8ValidateSlice(bytes)) return s.write(bytes); try writeBase64(s, bytes); } /// Binary data: always {"encoding":"base64","data":…} (RFC 4648, padded). fn writeBase64(s: *std.json.Stringify, bytes: []const u8) std.Io.Writer.Error!void { try s.beginObject(); try s.objectField("encoding"); try s.write("base64"); try s.objectField("data"); var buf: [4096]u8 = undefined; try s.beginWriteRaw(); try s.writer.writeByte('"'); var i: usize = 0; // Encode in chunks of 3-byte groups so no padding appears mid-string. while (i < bytes.len) { const n = @min(bytes.len - i, 3 * 1024); try s.writer.writeAll(std.base64.standard.Encoder.encode(&buf, bytes[i..][0..n])); i += n; } try s.writer.writeByte('"'); s.endWriteRaw(); try s.endObject(); } /// Writes the run record for `outcome` as one JSON object (no newline). /// `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"); switch (outcome) { .returned => |v| { try s.write("returned"); try s.objectField("value"); try writeValue(module, v, &s); }, .trapped => |t| { try s.write("trapped"); try s.objectField("code"); try s.write(t.code.id); try s.objectField("kind"); try s.write(t.code.kind); try s.objectField("function"); try s.write(t.function); try s.objectField("block"); try s.write(t.block); try s.objectField("inst"); try s.write(t.inst); }, .race_detected => |r| { try s.write("race_detected"); try s.objectField("function"); try s.write(r.at.function); try s.objectField("block"); try s.write(r.at.block); try s.objectField("inst"); try s.write(r.at.inst); try s.objectField("other_task"); try s.write(r.other_task); }, .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"); try s.write(n.reason); try s.objectField("parameter"); try s.write(n.parameter); if (n.kind) |k| { try s.objectField("kind"); try s.write(k); } if (n.granted) |g| { try s.objectField("granted"); try s.write(g); } if (n.scope) |sc| { try s.objectField("scope"); try s.write(sc); } }, .limit_exceeded => |l| { try s.write("limit_exceeded"); try s.objectField("kind"); try s.write(l.kind); try s.objectField("limit"); try s.write(l.limit); try s.objectField("steps"); try s.write(l.steps); }, } if (out) |o| if (module.declares("capabilities") and outcome != .not_instantiated) { try s.objectField("stdout"); try writeText(&s, o.stdout); try s.objectField("stderr"); try writeText(&s, o.stderr); try s.objectField("files"); try s.beginObject(); for (o.files) |file| { try s.objectField(file[0]); try writeBase64(&s, file[1]); } try s.endObject(); }; if (out) |o| if (o.schedule) |sch| { try s.objectField("schedule"); try s.write(sch); }; try s.endObject(); } // ---------------------------------------------------------------- tests const check = @import("../check.zig"); fn expectRun(src: []const u8, expected: []const u8) !void { return expectRunFuel(src, expected, null); } fn expectRunFuel(src: []const u8, expected: []const u8, fuel: ?u64) !void { var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); const report = try check.checkAir(arena, "t.air", src); if (report.status != .accepted) { for (report.diagnostics) |d| std.debug.print("{s} {s}\n", .{ d.code.id, d.message }); return error.NotAccepted; } const outcome = try run(arena, report.module.?, "main", .{ .fuel = fuel }); var out: std.Io.Writer.Allocating = .init(arena); try writeOutcome(report.module.?, outcome, null, &out.writer); try std.testing.expectEqualStrings(expected, out.written()); } const h = "module t\nair 0\nlang 0.1\nfeatures []\n"; fn main1(comptime ret: []const u8, comptime insts: []const u8) []const u8 { return h ++ "fn @main() -> " ++ ret ++ "\neffects []\nentry:\n" ++ insts; } test "checked arithmetic and traps" { try expectRun(comptime main1("u8", " %a = const.u8 200\n %b = const.u8 55\n %c = add.checked.u8 %a, %b\n ret %c\n"), "{\"status\":\"returned\",\"value\":255}"); try expectRun(comptime main1("u8", " %a = const.u8 200\n %b = const.u8 56\n %c = add.checked.u8 %a, %b\n ret %c\n"), "{\"status\":\"trapped\",\"code\":\"T0003\",\"kind\":\"trap.overflow\",\"function\":\"main\",\"block\":\"entry\",\"inst\":2}"); try expectRun(comptime main1("u8", " %a = const.u8 200\n %b = const.u8 56\n %c = add.wrap.u8 %a, %b\n ret %c\n"), "{\"status\":\"returned\",\"value\":0}"); try expectRun(comptime main1("i32", " %a = const.i32 -7\n %b = const.i32 2\n %c = rem.checked.i32 %a, %b\n ret %c\n"), "{\"status\":\"returned\",\"value\":-1}"); try expectRun(comptime main1("i32", " %a = const.i32 -7\n %b = const.i32 2\n %c = div.checked.i32 %a, %b\n ret %c\n"), "{\"status\":\"returned\",\"value\":-3}"); try expectRun(comptime main1("i8", " %a = const.i8 -128\n %b = const.i8 -1\n %c = div.checked.i8 %a, %b\n ret %c\n"), "{\"status\":\"trapped\",\"code\":\"T0003\",\"kind\":\"trap.overflow\",\"function\":\"main\",\"block\":\"entry\",\"inst\":2}"); try expectRun(comptime main1("u32", " %a = const.u32 1\n %b = const.u32 0\n %c = div.checked.u32 %a, %b\n ret %c\n"), "{\"status\":\"trapped\",\"code\":\"T0004\",\"kind\":\"trap.division_by_zero\",\"function\":\"main\",\"block\":\"entry\",\"inst\":2}"); try expectRun(comptime main1("u128", " %a = const.u128 0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff\n ret %a\n"), "{\"status\":\"returned\",\"value\":340282366920938463463374607431768211455}"); } test "shifts and casts" { try expectRun(comptime main1("u8", " %a = const.u8 0x81\n %b = const.u8 1\n %c = shl.u8 %a, %b\n ret %c\n"), "{\"status\":\"returned\",\"value\":2}"); try expectRun(comptime main1("i8", " %a = const.i8 -128\n %b = const.i8 7\n %c = shr.i8 %a, %b\n ret %c\n"), "{\"status\":\"returned\",\"value\":-1}"); try expectRun(comptime main1("u8", " %a = const.u8 1\n %b = const.u8 8\n %c = shl.u8 %a, %b\n ret %c\n"), "{\"status\":\"trapped\",\"code\":\"T0005\",\"kind\":\"trap.shift_out_of_range\",\"function\":\"main\",\"block\":\"entry\",\"inst\":2}"); try expectRun(comptime main1("u8", " %a = const.i32 -1\n %c = cast.wrap.u8 %a\n ret %c\n"), "{\"status\":\"returned\",\"value\":255}"); try expectRun(comptime main1("i64", " %a = const.i8 -3\n %c = cast.widen.i64 %a\n ret %c\n"), "{\"status\":\"returned\",\"value\":-3}"); try expectRun(comptime main1("u8", " %a = const.i32 300\n %c = cast.checked.u8 %a\n ret %c\n"), "{\"status\":\"trapped\",\"code\":\"T0006\",\"kind\":\"trap.cast_out_of_range\",\"function\":\"main\",\"block\":\"entry\",\"inst\":1}"); try expectRun(comptime main1("i16", " %a = const.u8 255\n %c = cast.wrap.i16 %a\n ret %c\n"), "{\"status\":\"returned\",\"value\":255}"); } test "control flow, aggregates, calls and call depth" { try expectRun(h ++ \\type @P = struct { x: i32, ok: bool } \\type @O = enum { None, Some(@P) } \\fn @main() -> @O \\effects [] \\entry: \\ %n = const.u64 10 \\ %r = call @sum(%n) \\ %t = cast.checked.i32 %r \\ %b = const.bool true \\ %p = struct.make @P(%t, %b) \\ %o = enum.make @O.Some(%p) \\ ret %o \\fn @sum(%n: u64) -> u64 \\effects [] \\entry: \\ %z = const.u64 0 \\ br @loop(%z, %z) \\loop(%i: u64, %acc: u64): \\ %d = gt.u64 %i, %n \\ cbr %d, @exit(), @body() \\body: \\ %acc2 = add.checked.u64 %acc, %i \\ %one = const.u64 1 \\ %i2 = add.checked.u64 %i, %one \\ br @loop(%i2, %acc2) \\exit: \\ ret %acc \\ , "{\"status\":\"returned\",\"value\":{\"variant\":\"Some\",\"payload\":[{\"x\":55,\"ok\":true}]}}"); try expectRun(h ++ \\fn @main() -> void \\effects [] \\entry: \\ call @rec() \\ ret \\fn @rec() -> void \\effects [] \\entry: \\ call @rec() \\ ret \\ , "{\"status\":\"trapped\",\"code\":\"T0007\",\"kind\":\"trap.call_depth\",\"function\":\"rec\",\"block\":\"entry\",\"inst\":0}"); } test "block arguments bind simultaneously" { // Swapping through block parameters must not observe a half-updated state. try expectRun(h ++ \\type @Pair = struct { a: u8, b: u8 } \\fn @main() -> @Pair \\effects [] \\entry: \\ %x = const.u8 1 \\ %y = const.u8 2 \\ %k = const.u8 0 \\ br @swap(%x, %y, %k) \\swap(%a: u8, %b: u8, %n: u8): \\ %one = const.u8 1 \\ %done = eq.u8 %n, %one \\ cbr %done, @out(), @again() \\again: \\ br @swap(%b, %a, %one) \\out: \\ %p = struct.make @Pair(%a, %b) \\ ret %p \\ , "{\"status\":\"returned\",\"value\":{\"a\":2,\"b\":1}}"); } test "fuel counts every instruction, including call and ret" { const src = h ++ \\fn @main() -> u8 \\effects [] \\entry: \\ %a = call @one() \\ ret %a \\fn @one() -> u8 \\effects [] \\entry: \\ %x = const.u8 1 \\ ret %x \\ ; // call, const, ret (callee), ret (main) = 4 instructions. try expectRunFuel(src, "{\"status\":\"returned\",\"value\":1}", 4); try expectRunFuel(src, "{\"status\":\"limit_exceeded\",\"kind\":\"fuel\",\"limit\":3,\"steps\":3}", 3); try expectRunFuel(src, "{\"status\":\"limit_exceeded\",\"kind\":\"fuel\",\"limit\":0,\"steps\":0}", 0); } test "fuel stops an infinite loop deterministically" { try expectRunFuel(h ++ \\fn @main() -> void \\effects [] \\entry: \\ br @spin() \\spin: \\ br @spin() \\ , "{\"status\":\"limit_exceeded\",\"kind\":\"fuel\",\"limit\":1000,\"steps\":1000}", 1000); } test "a trap at the last unit of fuel is still a trap" { // const, const, add (traps) = the add begins with the third unit. try expectRunFuel(comptime main1("u8", " %a = const.u8 255\n %b = const.u8 1\n %c = add.checked.u8 %a, %b\n ret %c\n"), "{\"status\":\"trapped\",\"code\":\"T0003\",\"kind\":\"trap.overflow\",\"function\":\"main\",\"block\":\"entry\",\"inst\":2}", 3); } test "canonical byte strings in the run record" { var buf: [256]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); var s: std.json.Stringify = .{ .writer = &w }; try s.beginArray(); try writeText(&s, "h\u{e9}\n"); try writeText(&s, "\xff"); try writeBase64(&s, "Aji"); 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); } // Memory use is bounded by live state, not by the number of instructions // executed. Measured with the interpreter's own heap counters, // not host RSS: for each loop shape, the live execution state after a // collection must not grow with the iteration count, and the heap stays // under a fixed bound. pub fn memoryOf(comptime body: []const u8, n: u64, threshold: ?usize) !MemoryStats { var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); const src = try std.fmt.allocPrint(arena, body, .{n}); const report = try check.checkFile(arena, "t.aji", src); if (report.status != .accepted) { for (report.diagnostics) |d| std.debug.print("{s} {s}\n", .{ d.code.id, d.message }); return error.NotAccepted; } var stats: MemoryStats = .{}; const outcome = try run(arena, report.module.?, "main", .{ .grants = &.{.{ .parameter = "heap", .kind = "mem.alloc", .scope = "4096" }}, .memory = &stats, .collect_threshold = threshold }); try std.testing.expect(outcome == .returned); return stats; } pub const loop_shapes = [_][]const u8{ // scalar state carried in block arguments \\module t \\fn main(heap: cap) -> u64 \\effects [] \\{{ \\ var i: u64 = 0; \\ var s: u64 = 0; \\ while i < {d} {{ s = s +% i; i = i + 1; }} \\ s \\}} , // element access through borrows (places and paths) \\module t \\fn main(heap: cap) -> u64 \\effects [] \\{{ \\ var a: [u64; 8] = zero; \\ var i: u64 = 0; \\ while i < {d} {{ a[i as! usize % 8] = a[(i as! usize + 1) % 8] +% i; i = i + 1; }} \\ a[0] \\}} , // a call per iteration (frames) \\module t \\fn step(x: u64, b: slice) -> u64 \\effects [] \\{{ \\ x +% b[x as! usize % 4] \\}} \\fn main(heap: cap) -> u64 \\effects [] \\{{ \\ var b: [u64; 4] = [3; 4]; \\ var i: u64 = 0; \\ var s: u64 = 0; \\ while i < {d} {{ s = step(s, ref b); i = i + 1; }} \\ s \\}} , // aggregate and array values built and copied every iteration \\module t \\struct P {{ a: u64, b: [u64; 4] }} \\fn main(heap: cap) -> u64 \\effects [] \\{{ \\ var p: P = P {{ a: 0, b: [1; 4] }}; \\ var i: u64 = 0; \\ while i < {d} {{ p = P {{ a: p.a +% i, b: [i; 4] }}; i = i + 1; }} \\ p.a \\}} , // heap allocation and free every iteration \\module t \\fn main(heap: cap) -> u64 \\effects [mem.alloc] \\{{ \\ var i: u64 = 0; \\ var s: u64 = 0; \\ while i < {d} {{ \\ let o = own.new(i, heap) or trap; \\ s = s +% own.take(move o); \\ i = i + 1; \\ }} \\ s \\}} , }; test "execution memory is bounded by live state, not by the iteration count" { // Fast form: a 256 KiB threshold makes 20k-320k iterations collect many // times. The full form (100k/1M/4M iterations, default threshold) is // tests/extended/memory.zig, run by `zig build test-extended`. const floor = 256 << 10; inline for (loop_shapes, 0..) |shape, k| { const small = try memoryOf(shape, 20_000, floor); const mid = try memoryOf(shape, 80_000, floor); const large = try memoryOf(shape, 320_000, floor); errdefer std.debug.print("shape {d}: live {d}/{d}/{d} heap {d}/{d}/{d} collections {d}/{d}/{d}\n", .{ k, small.peak_live, mid.peak_live, large.peak_live, small.peak_heap, mid.peak_heap, large.peak_heap, small.collections, mid.collections, large.collections, }); try std.testing.expect(large.collections > mid.collections); try std.testing.expect(large.peak_live <= mid.peak_live + 64 * 1024); try std.testing.expect(large.peak_heap <= 3 * floor + 64 * 1024); } } test "arc count changes appear in the trace, and the last release frees the graph" { var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); const src = \\module t \\fn main(heap: cap) -> u64 \\effects [mem.alloc] \\{ \\ let isl = island.create(7u64, heap) or trap; \\ let a = arc.from_frozen(island.freeze(move isl)); \\ let b = arc.clone(a); \\ arc.release(move a); \\ var v: u64 = 0; \\ { \\ ref br = b; \\ let r = arc.root(br); \\ ref x = arc.at(br, r); \\ v = *x; \\ } \\ arc.release(move b); \\ // The budget (16 + 8 bytes) is free again: the same graph fits once more. \\ let again = arc.new(5u64, heap) or trap; \\ arc.release(move again); \\ v \\} ; const report = try check.checkFile(arena, "t.aji", src); if (report.status != .accepted) { for (report.diagnostics) |d| std.debug.print("{s} {s}\n", .{ d.code.id, d.message }); return error.NotAccepted; } var events: std.ArrayList(ArcEvent) = .empty; const outcome = try run(arena, report.module.?, "main", .{ .grants = &.{.{ .parameter = "heap", .kind = "mem.alloc", .scope = "24" }}, .arc_events = &events, }); try std.testing.expect(outcome == .returned); try std.testing.expectEqual(@as(u128, 7), outcome.returned.int.bits); const Op = @FieldType(ArcEvent, "op"); const want = [_]struct { Op, u64 }{ .{ .from_frozen, 1 }, .{ .clone, 2 }, .{ .release, 1 }, .{ .release, 0 }, .{ .new, 1 }, .{ .release, 0 } }; try std.testing.expectEqual(want.len, events.items.len); for (want, events.items) |w, e| { try std.testing.expectEqual(w[0], e.op); try std.testing.expectEqual(w[1], e.count); } // One graph identity through island → frozen → arc; the second graph is new. try std.testing.expectEqual(events.items[0].graph, events.items[3].graph); try std.testing.expect(events.items[4].graph != events.items[0].graph); } // Transfer is O(1) in the graph size (spec 03 §22): moving an island through // a channel K times costs the same number of instructions for a graph of 10 // nodes as for one of 1000. fn transferSteps(nodes: u64, sends: u64) !u64 { var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); const src = try std.fmt.allocPrint(arena, \\module t \\fn main(heap: cap) -> u64 \\effects [mem.alloc, task.wait] \\{{ \\ var isl: island = island.create(0u64, heap) or trap; \\ {{ \\ mut g = isl; \\ for i in 0..{d}u64 {{ let r = island.alloc(g, i) or trap; }} \\ }} \\ match channel.make>(1, heap) {{ \\ ok(tx, rx) => {{ \\ for k in 0..{d}u64 {{ \\ channel.send(tx, move isl) or trap; \\ isl = channel.recv(rx) or trap; \\ }} \\ channel.close_sender(move tx); \\ channel.close_receiver(move rx) or trap; \\ }} \\ err(e) => {{ trap; }} \\ }} \\ island.destroy(move isl); \\ 0 \\}} , .{ nodes, sends }); const report = try check.checkFile(arena, "t.aji", src); if (report.status != .accepted) { for (report.diagnostics) |d| std.debug.print("{s} {s}\n", .{ d.code.id, d.message }); return error.NotAccepted; } var stats: MemoryStats = .{}; const outcome = try run(arena, report.module.?, "main", .{ .grants = &.{.{ .parameter = "heap", .kind = "mem.alloc", .scope = "1000000" }}, .memory = &stats }); try std.testing.expect(outcome == .returned); return stats.steps; } test "moving an island costs the same for any graph size" { const small = try transferSteps(10, 10) - try transferSteps(10, 0); const large = try transferSteps(1000, 10) - try transferSteps(1000, 0); try std.testing.expectEqual(small, large); } test "the race detector catches an unordered write the verifier would reject" { // Not verified on purpose: main writes the local while a mut borrow of it // is lent to a running task (E4101 for the verifier, spec 04 §34). const src = \\module test.race \\air 0 \\lang 0.1 \\features [ownership, tasks] \\ \\fn @poke(%p: mut) -> u64 \\effects [] \\entry: \\ %one = const.u64 1 \\ store %p, %one \\ ret %one \\ \\fn @main() -> u64 \\effects [task.spawn] \\entry: \\ %x = local.alloc u64 \\ %z = const.u64 0 \\ local.store %x, %z \\ %b = borrow.mut %x \\ %s = task.scope.begin \\ %t = task.spawn %s, @poke(%b) \\ %two = const.u64 2 \\ local.store %x, %two \\ %r = task.join %t \\ task.scope.end %s \\ borrow.end %b \\ ret %r \\ ; var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); const parsed = try @import("../air/parse.zig").parse(arena, "race.air", src); try std.testing.expectEqual(@as(usize, 0), parsed.diagnostics.len); // On every schedule the two writes are unordered: one of them is caught. var seed: u64 = 0; while (seed < 20) : (seed += 1) { const outcome = try run(arena, parsed.module.?, "main", .{ .detect_races = true, .quantum = 1, .schedule_seed = seed }); try std.testing.expect(outcome == .race_detected); } // Without the detector the program just runs. const plain = try run(arena, parsed.module.?, "main", .{ .quantum = 1 }); try std.testing.expect(plain == .returned); }