interp: deterministic interpreter, aji run, run tests (P0-11, P0-12)

- src/interp/machine.zig: format-0 interpreter on the air64 target;
  checked/wrapping arithmetic, shifts, casts, aggregates, calls with a
  1024-frame limit, traps as records with T0xxx codes
- aji run: prints one JSON run record; exit code 4 on trap
- conformance runner: `expect: run` with `result:`/`trap:`, every run
  executed twice and compared byte-for-byte; header keys must be single
  lowercase words
- Phase 0 corpus: 3 accept, 19 reject, 15 run tests (41 total)
This commit is contained in:
dev committed 2026-10-04 12:28:27 +03:00
1 parent 50bf990355
commit 1f5008bb37
45 files changed
+1463 -23

No files matched your search

+5
View File
@@ -20,6 +20,11 @@ pub const ValueId = module.ValueId;
pub const Span = module.Span;
pub const Param = module.Param;
pub const Target = module.Target;
pub const ArithOp = module.ArithOp;
pub const ArithMode = module.ArithMode;
pub const BitOp = module.BitOp;
pub const CmpOp = module.CmpOp;
pub const CastMode = module.CastMode;
pub const forEachUse = module.forEachUse;
pub const successors = module.successors;
+15 -6
View File
@@ -1,6 +1,15 @@
//! AIR interpreter (spec 07, spec 11). Defines observable semantics.
//!
//! Requirements:
//! - executes only verified AIR;
//! - deterministic: identical input and seed give identical output and trace;
//! - traps are explicit values, never host panics or unwinding.
//! AIR interpreter (spec 07a, spec 11). Defines observable semantics.
const machine = @import("interp/machine.zig");
pub const Value = machine.Value;
pub const Trap = machine.Trap;
pub const Outcome = machine.Outcome;
pub const run = machine.run;
pub const writeOutcome = machine.writeOutcome;
pub const writeValue = machine.writeValue;
pub const call_depth_limit = machine.call_depth_limit;
test {
_ = machine;
}
+529
View File
@@ -0,0 +1,529 @@
//! 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). All memory comes from the arena
//! passed to `run` and is released by the caller as a whole.
const std = @import("std");
const air = @import("../air.zig");
const diag = @import("../diag.zig");
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,
pub const Aggregate = struct {
decl: u32,
/// Active variant for enums; 0 for structs.
variant: u32,
fields: []const Value,
};
};
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,
};
pub const Error = std.mem.Allocator.Error || error{EntryNotFound};
/// 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) Error!Outcome {
const idx = module.functionIndex(entry) orelse return error.EntryNotFound;
if (module.functions[idx].params.len != 0) return error.EntryNotFound;
var m: Machine = .{ .arena = arena, .module = module };
return switch (try m.call(idx, &.{})) {
.value => |v| .{ .returned = v },
.trap => |t| .{ .trapped = t },
};
}
const TrapKind = enum {
explicit,
assert,
overflow,
division_by_zero,
shift_out_of_range,
cast_out_of_range,
call_depth,
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").?,
};
}
};
/// 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,
};
}
const CallResult = union(enum) { value: Value, trap: Trap };
const Machine = struct {
arena: std.mem.Allocator,
module: air.Module,
depth: u32 = 0,
fn call(m: *Machine, fn_index: u32, args: []const Value) std.mem.Allocator.Error!CallResult {
const f = m.module.functions[fn_index];
m.depth += 1;
defer m.depth -= 1;
const vals = try m.arena.alloc(Value, f.values.len);
for (f.params, args) |p, a| vals[p.value] = a;
var block: u32 = 0;
while (true) {
const b = f.blocks[block];
for (b.insts, 0..) |inst, ii| {
const step = try m.exec(f, vals, inst);
switch (step) {
.next => {},
.jump => |t| {
block = t;
break;
},
.ret => |v| return .{ .value = v },
.trap => |k| return .{ .trap = .{
.code = k.code(),
.function = f.name,
.block = b.name,
.inst = @intCast(ii),
} },
.nested_trap => |t| return .{ .trap = t },
}
} else unreachable; // verified blocks end with a terminator
}
}
const Step = union(enum) {
next,
jump: u32,
ret: Value,
trap: TrapKind,
/// A trap raised inside a callee, already located.
nested_trap: Trap,
};
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.gather(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.gather(vals, x.args),
} }),
.call => |x| {
if (m.depth >= call_depth_limit) return .{ .trap = .call_depth };
const args = try m.gather(vals, x.args);
switch (try m.call(x.callee, args)) {
.value => |v| {
if (inst.result) |r| vals[r] = v;
return .next;
},
.trap => |t| return .{ .nested_trap = t },
}
},
.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 agg = vals[x.value].aggregate;
for (x.arms) |arm| if (arm.variant == agg.variant) {
for (f.blocks[arm.block].params, agg.fields) |p, fv| vals[p.value] = fv;
return .{ .jump = arm.block };
};
return m.jump(f, vals, x.default.?);
},
.ret => |v| return .{ .ret = if (v) |x| vals[x] else .void },
.trap => return .{ .trap = .explicit },
}
}
fn bind(vals: []Value, result: ?air.ValueId, v: Value) Step {
vals[result.?] = v;
return .next;
}
fn gather(m: *Machine, vals: []const Value, ids: []const air.ValueId) ![]const Value {
const out = try m.arena.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),
.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();
},
}
},
}
}
/// Writes the run record for `outcome` as one JSON object (no newline).
pub fn writeOutcome(module: air.Module, outcome: Outcome, w: *std.Io.Writer) std.Io.Writer.Error!void {
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);
},
}
try s.endObject();
}
// ---------------------------------------------------------------- tests
const check = @import("../check.zig");
fn expectRun(src: []const u8, expected: []const u8) !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");
var out: std.Io.Writer.Allocating = .init(arena);
try writeOutcome(report.module.?, outcome, &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}}");
}
+17 -5
View File
@@ -3,8 +3,9 @@
//! Output contract (stable, consumed by agents):
//! - diagnostics go to stdout as JSON Lines, one object per line;
//! - human-oriented notes go to stderr;
//! - exit codes: 0 accepted, 1 rejected, 2 usage or I/O error,
//! 3 input not decidable yet (pipeline stage unimplemented).
//! - `aji run` writes one run record (spec 07a "Run result") to stdout;
//! - exit codes: 0 accepted / returned, 1 rejected, 2 usage or I/O error,
//! 3 input not decidable yet (pipeline stage unimplemented), 4 trapped.
const std = @import("std");
const aji = @import("aji");
@@ -14,13 +15,14 @@ const usage =
\\
\\commands:
\\ check <file.air> parse and verify a text AIR module
\\ run <file.air> verify, then run @main and print the run record
\\ codes list diagnostic codes as JSON Lines
\\ explain <code> show one diagnostic code
\\ version print toolchain version
\\
;
const ExitCode = enum(u8) { accepted = 0, rejected = 1, usage = 2, unimplemented = 3 };
const ExitCode = enum(u8) { accepted = 0, rejected = 1, usage = 2, unimplemented = 3, trapped = 4 };
pub fn main(init: std.process.Init) !void {
const arena = init.arena.allocator();
@@ -59,8 +61,8 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
try writeCode(out, c.*);
return .accepted;
}
if (std.mem.eql(u8, cmd, "check")) {
if (args.len != 3) return usageError("check takes exactly one file");
if (std.mem.eql(u8, cmd, "check") or std.mem.eql(u8, cmd, "run")) {
if (args.len != 3) return usageError("check and run take exactly one file");
const path = args[2];
const source = std.Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(64 << 20)) catch |err| {
std.debug.print("aji: cannot read {s}: {t}\n", .{ path, err });
@@ -71,6 +73,16 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
try d.writeJson(out);
try out.writeByte('\n');
}
if (report.status == .accepted and std.mem.eql(u8, cmd, "run")) {
const module = report.module.?;
const outcome = aji.interp.run(arena, module, "main") catch |err| switch (err) {
error.EntryNotFound => return usageError("module has no parameterless @main"),
else => |e| return e,
};
try aji.interp.writeOutcome(module, outcome, out);
try out.writeByte('\n');
return if (outcome == .trapped) .trapped else .accepted;
}
return switch (report.status) {
.accepted => .accepted,
.rejected => .rejected,