spec: single normative source, accept RFC 0004, freeze AIR format 0, fuel

Owner decisions after the Phase 0 review:

- precedence: docs/spec/ is the single normative source; RFCs are
  decision records whose accepted rules are integrated into the spec in
  the same change (AGENTS.md, docs/README.md, rfcs/README.md, DD-011)
- RFC 0004 Accepted (scope: AIR format 0, language 0.1)
- AIR format 0 frozen as the semantic baseline; spec 07 §8.7 defines the
  only permitted additive changes, everything else needs `air 1` (DD-012)
- Q-019 resolved: deterministic instruction fuel (spec 11 §7). Outcome
  `limit_exceeded` is a runner outcome, not a trap; `aji run --fuel N`,
  exit code 5; conformance runs always use fuel (default 1 000 000,
  `fuel:` header); fuel/schedule budget/quantum kept separate for P3
  (DD-013)
This commit is contained in:
dev committed 2026-10-04 12:40:32 +03:00
1 parent dc36b5cfc0
commit 03dda1245a
24 files changed
+268 -63

No files matched your search

+1
View File
@@ -5,6 +5,7 @@ const machine = @import("interp/machine.zig");
pub const Value = machine.Value;
pub const Trap = machine.Trap;
pub const Outcome = machine.Outcome;
pub const Options = machine.Options;
pub const run = machine.run;
pub const writeOutcome = machine.writeOutcome;
pub const writeValue = machine.writeValue;
+71 -4
View File
@@ -39,19 +39,27 @@ pub const Trap = struct {
pub const Outcome = union(enum) {
returned: Value,
trapped: Trap,
/// The runner's fuel ran out (spec 11 §7). Not a trap.
limit_exceeded: struct { limit: u64, steps: u64 },
};
pub const Options = struct {
/// Maximum number of instructions to execute (spec 11 §7.1); null means unlimited.
fuel: ?u64 = null,
};
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 {
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;
if (module.functions[idx].params.len != 0) return error.EntryNotFound;
var m: Machine = .{ .arena = arena, .module = module };
var m: Machine = .{ .arena = arena, .module = module, .fuel = options.fuel };
return switch (try m.call(idx, &.{})) {
.value => |v| .{ .returned = v },
.trap => |t| .{ .trapped = t },
.limit_exceeded => .{ .limit_exceeded = .{ .limit = m.fuel.?, .steps = m.steps } },
};
}
@@ -89,12 +97,15 @@ fn kindOf(e: TrapError) TrapKind {
};
}
const CallResult = union(enum) { value: Value, trap: Trap };
const CallResult = union(enum) { value: Value, trap: Trap, limit_exceeded };
const Machine = struct {
arena: std.mem.Allocator,
module: air.Module,
depth: u32 = 0,
fuel: ?u64,
/// Instructions executed so far.
steps: u64 = 0,
fn call(m: *Machine, fn_index: u32, args: []const Value) std.mem.Allocator.Error!CallResult {
const f = m.module.functions[fn_index];
@@ -108,6 +119,9 @@ const Machine = struct {
while (true) {
const b = f.blocks[block];
for (b.insts, 0..) |inst, ii| {
// Fuel is consumed when an instruction begins (spec 11 §7.1).
if (m.fuel) |limit| if (m.steps >= limit) return .limit_exceeded;
m.steps += 1;
const step = try m.exec(f, vals, inst);
switch (step) {
.next => {},
@@ -123,6 +137,7 @@ const Machine = struct {
.inst = @intCast(ii),
} },
.nested_trap => |t| return .{ .trap = t },
.limit_exceeded => return .limit_exceeded,
}
} else unreachable; // verified blocks end with a terminator
}
@@ -135,6 +150,7 @@ const Machine = struct {
trap: TrapKind,
/// A trap raised inside a callee, already located.
nested_trap: Trap,
limit_exceeded,
};
fn exec(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst) std.mem.Allocator.Error!Step {
@@ -201,6 +217,7 @@ const Machine = struct {
return .next;
},
.trap => |t| return .{ .nested_trap = t },
.limit_exceeded => return .limit_exceeded,
}
},
.br => |t| return m.jump(f, vals, t),
@@ -407,6 +424,15 @@ pub fn writeOutcome(module: air.Module, outcome: Outcome, w: *std.Io.Writer) std
try s.objectField("inst");
try s.write(t.inst);
},
.limit_exceeded => |l| {
try s.write("limit_exceeded");
try s.objectField("kind");
try s.write("fuel");
try s.objectField("limit");
try s.write(l.limit);
try s.objectField("steps");
try s.write(l.steps);
},
}
try s.endObject();
}
@@ -416,6 +442,10 @@ pub fn writeOutcome(module: air.Module, outcome: Outcome, w: *std.Io.Writer) std
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();
@@ -424,7 +454,7 @@ fn expectRun(src: []const u8, expected: []const u8) !void {
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");
const outcome = try run(arena, report.module.?, "main", .{ .fuel = fuel });
var out: std.Io.Writer.Allocating = .init(arena);
try writeOutcome(report.module.?, outcome, &out.writer);
try std.testing.expectEqualStrings(expected, out.written());
@@ -527,3 +557,40 @@ test "block arguments bind simultaneously" {
\\
, "{\"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);
}
+20 -7
View File
@@ -5,7 +5,8 @@
//! - human-oriented notes go to stderr;
//! - `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.
//! 3 input not decidable yet (pipeline stage unimplemented), 4 trapped,
//! 5 execution limit exceeded (`--fuel`, spec 11 §7).
const std = @import("std");
const aji = @import("aji");
@@ -15,14 +16,16 @@ 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
\\ run [--fuel N] <file.air>
\\ verify, then run @main and print the run record;
\\ --fuel stops after N executed instructions
\\ 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, trapped = 4 };
const ExitCode = enum(u8) { accepted = 0, rejected = 1, usage = 2, unimplemented = 3, trapped = 4, limit_exceeded = 5 };
pub fn main(init: std.process.Init) !void {
const arena = init.arena.allocator();
@@ -62,8 +65,14 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
return .accepted;
}
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];
var options: aji.interp.Options = .{};
var rest = args[2..];
if (std.mem.eql(u8, cmd, "run") and rest.len == 3 and std.mem.eql(u8, rest[0], "--fuel")) {
options.fuel = std.fmt.parseInt(u64, rest[1], 10) catch return usageError("--fuel takes a non-negative integer");
rest = rest[2..];
}
if (rest.len != 1) return usageError("check and run take exactly one file");
const path = rest[0];
const source = std.Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(64 << 20)) catch |err| {
std.debug.print("aji: cannot read {s}: {t}\n", .{ path, err });
return .usage;
@@ -75,13 +84,17 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
}
if (report.status == .accepted and std.mem.eql(u8, cmd, "run")) {
const module = report.module.?;
const outcome = aji.interp.run(arena, module, "main") catch |err| switch (err) {
const outcome = aji.interp.run(arena, module, "main", options) 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 (outcome) {
.returned => .accepted,
.trapped => .trapped,
.limit_exceeded => .limit_exceeded,
};
}
return switch (report.status) {
.accepted => .accepted,