//! 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"); 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, /// 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 }; 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 }; /// 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, }; 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, }; pub const Options = struct { /// 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, /// 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, }; /// 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; 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()); if (options.memory) |st| st.* = m.exec_heap.stats; m.exec_heap.space.deinit(); return result; } /// 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, 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) }, .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) }, .int, .boolean, .void, .cap, .resource, .region, .scope, .task, .builtin, .shield, .sender, .receiver => 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 }; n.value = try c.value(old.value); 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) }; 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, 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").?, }; } }; /// 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 }; /// A channel (spec 04 §38.3). const Channel = struct { capacity: u64, buf: std.ArrayList(Value) = .empty, head: usize = 0, 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 } = null, }; /// Execution heap: collected between instructions (see the file comment). const Heap = struct { space: std.heap.ArenaAllocator = .init(std.heap.page_allocator), threshold: usize = min_threshold, every_step: bool = false, stats: MemoryStats = .{}, const min_threshold = 4 << 20; }; const Machine = struct { arena: std.mem.Allocator, exec_heap: Heap = .{}, 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, // ------------------------------------------------------------ tasks and the scheduler (spec 04 §36) /// Runs task 0 (`@main`) and every task it spawns until the program /// returns, traps, or the environment stops it. fn runProgram(m: *Machine, fn_index: u32, args: []const Value) std.mem.Allocator.Error!Outcome { try m.tasks.append(m.arena, .{}); try m.pushFrame(0, fn_index, args); while (true) { // 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 }; // 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 } }, } 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); } 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)); ch.buf = buf; ch.head = 0; 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) }); ch.send_offers = offers; if (ch.recv_offer) |*o| o.value = try c.value(o.value); } 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(Heap.min_threshold, 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; } const x = m.sched.next(); m.choices += 1; m.current = runnable.items[x % runnable.items.len]; return null; } 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, }; 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 }, .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); }, .enum_switch => |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); try m.tasks.append(m.arena, .{}); try m.pushFrame(id, x.callee, try m.gather(vals, x.args)); vals[inst.result.?] = .{ .task = id }; return .yield; }, .task_join => |v| { const id = vals[v].task; const t = m.tasks.items[id]; if (t.state != .done) return .{ .wait = .{ .join = id } }; m.live_tasks -= 1; if (inst.result) |r| vals[r] = t.result; return .yield; }, .task_cancel => |v| { m.tasks.items[vals[v].task].cancel = true; return .yield; }, .task_cancelled => { vals[inst.result.?] = .{ .boolean = m.tasks.items[m.current].cancel }; return .yield; }, .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), .own_new, .own_array, .own_take, .own_free, .region_create, .region_new, .region_array, .region_reset, .region_destroy => return m.execAlloc(f, vals, {}, inst), .intrinsic => |x| return m.intrinsic(f, vals, inst, x), .ret => |v| return .{ .ret = if (v) |x| vals[x] else .void }, .trap => return .{ .trap = .explicit }, .local_alloc, .local_store, .local_zero, .local_load, .borrow_ref, .borrow_mut, .borrow_field, .borrow_end, .load, .store, .array_splat, .borrow_index, .slice_make, .slice_len, .slice_sub, .slice_split, .slice_copy, .guard, .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| !vals[x.mutex].mutex.locked, else => unreachable, }; } fn endpointOf(v: Value) u32 { return switch (v) { .sender, .receiver => |c| c, .place => |p| endpointOf(p.cell.value), 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) void { m.removeOffers(o.task); const t = &m.tasks.items[o.task]; t.delivered = .{ .arm = o.arm, .value = value }; if (t.state == .waiting) t.state = .runnable; } /// Performs an `ok`-ready send. fn doSend(m: *Machine, id: u32, v: Value) !void { const c = &m.channels.items[id]; if (c.capacity > 0) return c.buf.append(m.heap(), try m.deepCopy(v)); const o = c.recv_offer.?; m.deliver(o, try m.deepCopy(v)); } /// Performs an `ok`-ready receive. fn doRecv(m: *Machine, id: u32) Value { const c = &m.channels.items[id]; if (c.buffered() > 0) { c.head += 1; return c.buf.items[c.head - 1]; } const o = c.send_offers.orderedRemove(0); m.deliver(o, .void); return o.value; } /// 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| return .{ .jump_yield = if (cancelObservable(t)) x.cancelled else x.ok }, .task_join_cancel => |x| { const child = vals[x.task].task; if (m.tasks.items[child].state == .done) { m.live_tasks -= 1; setParams(f, vals, x.ok, &.{m.tasks.items[child].result}); return .{ .jump_yield = x.ok }; } if (cancelObservable(t)) { 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; m.channels.items[id].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)) { 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 }); return .{ .wait = .op }; }, } }, .channel_recv => |x| { const t = &m.tasks.items[self]; if (t.delivered) |d| { t.delivered = null; 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, &.{m.doRecv(id)}); return .{ .jump_yield = x.ok }; }, .closed => return .{ .jump_yield = x.closed }, .none => { if (cancelObservable(t)) 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; 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)) { 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] }); } else c.recv_offer = .{ .task = self, .arm = @intCast(i) }; } return .{ .wait = .op }; } var pick: usize = 0; if (ready_arms.items.len > 1) { pick = m.sched.next() % ready_arms.items.len; m.choices += 1; 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) { 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, 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; setParams(f, vals, x.ok, &.{.{ .guard = mc }}); return .{ .jump_yield = x.ok }; } if (cancelObservable(&m.tasks.items[m.current])) 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; return .yield; }, else => unreachable, } } fn mutexOf(v: Value) *Value.MutexCell { return switch (v) { .mutex => |mc| mc, .place => |p| mutexOf(p.cell.value), 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 = &p.cell.value; for (p.path) |i| v = switch (v.*) { .aggregate => |a| &a.fields[i], .array => |items| &items[i], else => unreachable, }; return v; } 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| p.cell.value.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, else => unreachable, // only value types are allocated (spec 03 §19.2) }; } 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_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 }; 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 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| { vals[x.local].local.value = try m.deepCopy(vals[x.value]); return .next; }, .local_zero => |v| { const cell = vals[v].local; cell.value = try m.zeroValue(cell.ty); return .next; }, .local_load => |v| return bind(vals, inst.result, try m.deepCopy(vals[v].local.value)), .borrow_ref, .borrow_mut => |v| return bind(vals, inst.result, switch (vals[v]) { .local => |c| .{ .place = .{ .cell = c, .path = &.{} } }, // A borrowed resource: a place whose cell holds the handle. // Owners: the heap cell itself; arrays are borrowed as slices. .own => |cell| switch (cell.value) { .array => |items| .{ .slice = .{ .place = .{ .cell = cell, .path = &.{} }, .start = 0, .len = items.len } }, else => .{ .place = .{ .cell = cell, .path = &.{} } }, }, .region => |r| blk: { const cell = try m.heap().create(Value.Cell); cell.* = .{ .value = .{ .region = r }, .ty = .void }; break :blk .{ .place = .{ .cell = cell, .path = &.{} } }; }, .resource => |hd| blk: { const cell = try m.heap().create(Value.Cell); cell.* = .{ .value = .{ .resource = hd }, .ty = .void }; break :blk .{ .place = .{ .cell = cell, .path = &.{} } }; }, else => |x| x, }), .borrow_field => |x| return bind(vals, inst.result, .{ .place = try m.extend(asPlace(vals[x.borrow]), x.field) }), .borrow_end => return .next, .load => |v| return bind(vals, inst.result, try m.deepCopy(placePtr(asPlace(vals[v])).*)), .store => |x| { placePtr(asPlace(vals[x.borrow])).* = try m.deepCopy(vals[x.value]); return .next; }, .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. 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, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard => 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); }, .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. fn memoryOf(comptime body: []const u8, n: u64) !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 }); try std.testing.expect(outcome == .returned); return stats; } 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" { inline for (loop_shapes, 0..) |shape, k| { const small = try memoryOf(shape, 100_000); const mid = try memoryOf(shape, 1_000_000); const large = try memoryOf(shape, 4_000_000); 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 > 0); // Steady state: the live state of 4M iterations is the live state of 1M. try std.testing.expect(large.peak_live <= mid.peak_live + 64 * 1024); // The heap is bounded by a constant (collection threshold plus one growth step). try std.testing.expect(large.peak_heap <= 3 * Heap.min_threshold); } }