650 lines
31 KiB
Zig
650 lines
31 KiB
Zig
//! Conformance suite runner. Format: tests/conformance/README.md.
|
|
//!
|
|
//! usage: aji-conformance <dir> [--json] [--filter <substring>] [--stress <seeds>] [--collect-every-step]
|
|
//!
|
|
//! `--stress N` (P3-12): every test with a `schedules:` header runs schedule
|
|
//! seeds 0 … N-1 under each quantum of `stress_quanta` and its own quantum,
|
|
//! instead of its `schedules:` count. A failure prints the replay command.
|
|
//!
|
|
//! Exit status is 1 if any test FAILs or has a malformed header. PENDING
|
|
//! (pipeline stage not implemented yet) does not fail the run.
|
|
|
|
const std = @import("std");
|
|
const aji = @import("aji");
|
|
|
|
const Expect = union(enum) {
|
|
accept,
|
|
/// Exact multiset of error codes, sorted.
|
|
reject: []const []const u8,
|
|
/// Verify, run `@main` and compare the run record.
|
|
run: Run,
|
|
|
|
const Run = union(enum) {
|
|
/// Expected `value` of a `returned` record, as canonical JSON.
|
|
result: []const u8,
|
|
/// Expected trap code.
|
|
trap: []const u8,
|
|
/// Expected `reason` of a `not_instantiated` record.
|
|
not_instantiated: []const u8,
|
|
/// Expected `blocked` outcome (spec 11 §8).
|
|
blocked,
|
|
/// Expected `limit_exceeded` with this kind (`tasks`, `fuel`).
|
|
limit_exceeded: []const u8,
|
|
};
|
|
};
|
|
|
|
const Outcome = enum { pass, fail, pending };
|
|
|
|
/// Fuel for run tests without a `fuel:` header (spec 11 §7.1: conformance
|
|
/// runs always use a limit).
|
|
const default_fuel: u64 = 1_000_000;
|
|
|
|
const ModuleBinding = struct { name: []const u8, path: []const u8 };
|
|
|
|
const Header = struct {
|
|
expect: Expect,
|
|
fuel: u64,
|
|
/// Run with schedule seeds 0 … schedules-1 (spec 04 §36.5).
|
|
schedules: u64,
|
|
quantum: u64,
|
|
task_limit: u64,
|
|
grants: []const aji.interp.Grant,
|
|
world: aji.interp.WorldOptions,
|
|
/// Expected captured output and written files (all optional).
|
|
stdout: ?[]const u8,
|
|
stderr: ?[]const u8,
|
|
files: []const struct { []const u8, []const u8 },
|
|
phase: u8,
|
|
spec: []const u8,
|
|
/// `.aji` only: a reference AIR program (relative to the conformance
|
|
/// root) whose observable run must equal this one's.
|
|
equivalent: ?[]const u8 = null,
|
|
modules: []const ModuleBinding = &.{},
|
|
};
|
|
|
|
pub fn main(init: std.process.Init) !void {
|
|
const arena = init.arena.allocator();
|
|
const io = init.io;
|
|
const args = try init.minimal.args.toSlice(arena);
|
|
|
|
if (args.len < 2) {
|
|
std.debug.print("usage: aji-conformance <dir> [--json] [--filter <substring>] [--stress <seeds>] [--collect-every-step]\n", .{});
|
|
std.process.exit(2);
|
|
}
|
|
const root = args[1];
|
|
var json = false;
|
|
var filter: []const u8 = "";
|
|
var i: usize = 2;
|
|
while (i < args.len) : (i += 1) {
|
|
if (std.mem.eql(u8, args[i], "--json")) {
|
|
json = true;
|
|
} else if (std.mem.eql(u8, args[i], "--filter") and i + 1 < args.len) {
|
|
i += 1;
|
|
filter = args[i];
|
|
} else if (std.mem.eql(u8, args[i], "--collect-every-step")) {
|
|
collect_every_step = true;
|
|
} else if (std.mem.eql(u8, args[i], "--stress") and i + 1 < args.len) {
|
|
i += 1;
|
|
stress_seeds = std.fmt.parseInt(u64, args[i], 10) catch {
|
|
std.debug.print("aji-conformance: --stress needs a seed count\n", .{});
|
|
std.process.exit(2);
|
|
};
|
|
} else {
|
|
std.debug.print("aji-conformance: unknown argument {s}\n", .{args[i]});
|
|
std.process.exit(2);
|
|
}
|
|
}
|
|
|
|
// Collect and sort paths so that output order is deterministic.
|
|
var paths: std.ArrayList([]const u8) = .empty;
|
|
var dir = try std.Io.Dir.cwd().openDir(io, root, .{ .iterate = true });
|
|
defer dir.close(io);
|
|
var walker = try dir.walk(arena);
|
|
defer walker.deinit();
|
|
while (try walker.next(io)) |entry| {
|
|
if (entry.kind != .file or !(std.mem.endsWith(u8, entry.path, ".air") or std.mem.endsWith(u8, entry.path, ".aji"))) continue;
|
|
if (std.mem.indexOf(u8, entry.path, filter) == null) continue;
|
|
try paths.append(arena, try arena.dupe(u8, entry.path));
|
|
}
|
|
std.mem.sort([]const u8, paths.items, {}, lessThan);
|
|
|
|
var stdout_buf: [4096]u8 = undefined;
|
|
var stdout_fw: std.Io.File.Writer = .init(.stdout(), io, &stdout_buf);
|
|
const out = &stdout_fw.interface;
|
|
|
|
var counts = std.EnumArray(Outcome, usize).initFill(0);
|
|
for (paths.items) |rel| {
|
|
const source = try dir.readFileAlloc(io, rel, arena, .limited(16 << 20));
|
|
const display = try std.fs.path.join(arena, &.{ root, rel });
|
|
const result = if (std.mem.endsWith(u8, rel, ".aji")) try runSource(arena, io, dir, rel, display, source) else try runOne(arena, display, source);
|
|
counts.getPtr(result.outcome).* += 1;
|
|
if (json) {
|
|
var s: std.json.Stringify = .{ .writer = out };
|
|
try s.write(.{ .@"test" = display, .outcome = @tagName(result.outcome), .detail = result.detail });
|
|
try out.writeByte('\n');
|
|
} else {
|
|
try out.print("{s:<8} {s}", .{ label(result.outcome), display });
|
|
if (result.detail.len != 0) try out.print(" ({s})", .{result.detail});
|
|
try out.writeByte('\n');
|
|
}
|
|
}
|
|
if (!json) {
|
|
try out.print("\n{d} passed, {d} failed, {d} pending\n", .{
|
|
counts.get(.pass), counts.get(.fail), counts.get(.pending),
|
|
});
|
|
}
|
|
try out.flush();
|
|
if (counts.get(.fail) != 0) std.process.exit(1);
|
|
}
|
|
|
|
/// Seeds per quantum under `--stress`; null runs each test's `schedules:`.
|
|
var stress_seeds: ?u64 = null;
|
|
/// The second of the two runs of every `run` test collects the execution
|
|
/// heap before every instruction; the run records must still be identical.
|
|
var collect_every_step = false;
|
|
|
|
/// Quanta of the stress mode: forced yield after every instruction, short
|
|
/// and odd slices (spec 04 §36.3); the test's own quantum is added.
|
|
const stress_quanta = [_]u64{ 1, 2, 7 };
|
|
|
|
/// A `.aji` test (spec 15): the same header keys as AIR tests. Every
|
|
/// accepted module must also lower deterministically, survive the round
|
|
/// trip lower → parse → print unchanged, and match `<file>.expected` if
|
|
/// that file exists (golden canonical AIR).
|
|
fn runSource(arena: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, rel: []const u8, path: []const u8, source: []const u8) !Result {
|
|
const header = parseHeader(arena, source) catch |err|
|
|
return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "bad header: {t}", .{err}) };
|
|
var modules: std.ArrayList(aji.frontend.modules.Source) = .empty;
|
|
for (header.modules) |binding| {
|
|
const text = dir.readFileAlloc(io, binding.path, arena, .limited(64 << 20)) catch |err| return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "module {s}: {t}", .{ binding.path, err }) };
|
|
try modules.append(arena, .{ .name = binding.name, .file = binding.path, .source = text });
|
|
}
|
|
const report = try aji.check.checkWithModules(arena, path, source, modules.items);
|
|
if (report.status == .unimplemented) return .{ .outcome = .pending, .detail = report.missing_stage };
|
|
if (try diagnosticIssue(arena, report.diagnostics)) |issue| return .{ .outcome = .fail, .detail = issue };
|
|
const advice_path = try std.fmt.allocPrint(arena, "{s}.advice", .{rel});
|
|
if (dir.readFileAlloc(io, advice_path, arena, .limited(1 << 20))) |golden| {
|
|
var output: std.Io.Writer.Allocating = .init(arena);
|
|
for (report.diagnostics) |diagnostic| {
|
|
var json: std.json.Stringify = .{ .writer = &output.writer };
|
|
try aji.diag.writeRepairCandidates(diagnostic.repair_candidates, &json);
|
|
try output.writer.writeByte('\n');
|
|
}
|
|
if (!std.mem.eql(u8, golden, output.written())) return .{ .outcome = .fail, .detail = "source repair advice differs from .advice golden" };
|
|
} else |err| switch (err) {
|
|
error.FileNotFound => {},
|
|
else => return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "cannot read advice golden: {t}", .{err}) },
|
|
}
|
|
if (report.lowered) |lowered| {
|
|
const again = try aji.frontend.compileWithModules(arena, path, source, modules.items);
|
|
if (again != .ok or !std.mem.eql(u8, again.ok.air, lowered.air)) return .{ .outcome = .fail, .detail = "lowering is not deterministic" };
|
|
const parsed = try aji.air.parse.parse(arena, path, lowered.air);
|
|
if (parsed.module) |m| {
|
|
var w: std.Io.Writer.Allocating = .init(arena);
|
|
try aji.air.print.print(m, &w.writer);
|
|
if (!std.mem.eql(u8, w.written(), lowered.air)) return .{ .outcome = .fail, .detail = "lowered AIR is not canonical (parse → print differs)" };
|
|
}
|
|
const golden_path = try std.fmt.allocPrint(arena, "{s}.expected", .{rel});
|
|
if (dir.readFileAlloc(io, golden_path, arena, .limited(16 << 20))) |golden| {
|
|
if (!std.mem.eql(u8, golden, lowered.air)) return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "lowered AIR differs from {s}", .{golden_path}) };
|
|
} else |_| {}
|
|
}
|
|
var got: std.ArrayList([]const u8) = .empty;
|
|
for (report.diagnostics) |d| if (d.severity == .@"error") try got.append(arena, d.code.id);
|
|
std.mem.sort([]const u8, got.items, {}, lessThan);
|
|
switch (header.expect) {
|
|
.accept => if (report.status == .accepted) return .{ .outcome = .pass },
|
|
.reject => |want| if (report.status == .rejected and eqlCodes(want, got.items)) return .{ .outcome = .pass },
|
|
.run => |want| if (report.status == .accepted) {
|
|
const r = try runModule(arena, path, report.module.?, want, header);
|
|
if (r.outcome != .pass) return r;
|
|
if (header.equivalent) |ref| return equivalentRun(arena, io, dir, ref, report.module.?, header);
|
|
return r;
|
|
},
|
|
}
|
|
return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "expected {f}, got {t} {s}", .{
|
|
fmtExpect(header.expect), report.status, try std.mem.join(arena, " ", got.items),
|
|
}) };
|
|
}
|
|
|
|
/// Source/AIR equivalence: the lowered program and a hand-written reference
|
|
/// AIR program, run with the same world and grants, must give the same run
|
|
/// record byte for byte. The AIR text may differ (the frontend may build
|
|
/// another correct CFG). A trap is compared by its code only, since the
|
|
/// record also carries the AIR location.
|
|
fn equivalentRun(arena: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, ref: []const u8, lowered: aji.air.Module, header: Header) !Result {
|
|
const text = dir.readFileAlloc(io, ref, arena, .limited(16 << 20)) catch
|
|
return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "equivalent: cannot read {s}", .{ref}) };
|
|
const body = try arena.dupe(u8, text);
|
|
var line_start: usize = 0;
|
|
while (line_start < body.len and body[line_start] == ';') {
|
|
const end = std.mem.indexOfScalarPos(u8, body, line_start, '\n') orelse body.len;
|
|
@memset(body[line_start..end], ' ');
|
|
line_start = end + 1;
|
|
}
|
|
const report = try aji.check.checkAir(arena, ref, body);
|
|
if (report.status != .accepted) return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "equivalent: {s} is {t}", .{ ref, report.status }) };
|
|
var records: [2][]const u8 = undefined;
|
|
var codes: [2]?[]const u8 = .{ null, null };
|
|
for ([_]aji.air.Module{ lowered, report.module.? }, &records, &codes) |m, *rec, *code| {
|
|
var output: aji.interp.Output = undefined;
|
|
const outcome = try aji.interp.run(arena, m, "main", .{
|
|
.fuel = header.fuel,
|
|
.grants = header.grants,
|
|
.world = header.world,
|
|
.output = &output,
|
|
.quantum = header.quantum,
|
|
.task_limit = header.task_limit,
|
|
});
|
|
// The number of scheduler choices depends on the instruction stream
|
|
// (the quantum counts AIR instructions), which the frontend may lay
|
|
// out differently; it is trace metadata, not program behaviour. The
|
|
// schedule's seed and quantum are compared.
|
|
var out = output;
|
|
if (out.schedule) |*sch| sch.choices = 0;
|
|
var w: std.Io.Writer.Allocating = .init(arena);
|
|
try aji.interp.writeOutcome(m, outcome, out, &w.writer);
|
|
rec.* = w.written();
|
|
if (outcome == .trapped) code.* = outcome.trapped.code.id;
|
|
}
|
|
const same = if (codes[0] != null or codes[1] != null)
|
|
codes[0] != null and codes[1] != null and std.mem.eql(u8, codes[0].?, codes[1].?)
|
|
else
|
|
std.mem.eql(u8, records[0], records[1]);
|
|
if (same) return .{ .outcome = .pass };
|
|
return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "not equivalent to {s}: {s} vs {s}", .{ ref, records[0], records[1] }) };
|
|
}
|
|
|
|
fn lessThan(_: void, a: []const u8, b: []const u8) bool {
|
|
return std.mem.lessThan(u8, a, b);
|
|
}
|
|
|
|
fn label(o: Outcome) []const u8 {
|
|
return switch (o) {
|
|
.pass => "PASS",
|
|
.fail => "FAIL",
|
|
.pending => "PENDING",
|
|
};
|
|
}
|
|
|
|
const Result = struct { outcome: Outcome, detail: []const u8 = "" };
|
|
|
|
/// Validate the final API records, after frontend fields and source mapping.
|
|
/// This is a conformance assertion, never a program acceptance rule.
|
|
fn diagnosticIssue(arena: std.mem.Allocator, diagnostics: []const aji.diag.Diagnostic) !?[]const u8 {
|
|
for (diagnostics) |d| {
|
|
if (!aji.diag.hasUniqueFields(d)) return try std.fmt.allocPrint(arena, "{s}: duplicate or reserved diagnostic payload field", .{d.code.id});
|
|
var writer: std.Io.Writer.Allocating = .init(arena);
|
|
try d.writeJson(&writer.writer);
|
|
const parsed = std.json.parseFromSlice(std.json.Value, arena, writer.written(), .{ .duplicate_field_behavior = .@"error" }) catch |err|
|
|
return try std.fmt.allocPrint(arena, "{s}: invalid diagnostic JSON: {t}", .{ d.code.id, err });
|
|
parsed.deinit();
|
|
}
|
|
return null;
|
|
}
|
|
|
|
fn runOne(arena: std.mem.Allocator, path: []const u8, source: []const u8) !Result {
|
|
const header = parseHeader(arena, source) catch |err|
|
|
return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "bad header: {t}", .{err}) };
|
|
|
|
// A test is pending only while its phase is unfinished and it needs a
|
|
// feature this toolchain does not support yet.
|
|
if (header.phase > aji.implemented_phase) if (unsupportedFeature(source)) |name|
|
|
return .{ .outcome = .pending, .detail = try std.fmt.allocPrint(arena, "phase {d}: feature {s} not implemented", .{ header.phase, name }) };
|
|
|
|
// Blank header lines (keeping newlines) so spans in diagnostics stay accurate
|
|
// and the AIR grammar does not have to know about test metadata.
|
|
const body = try arena.dupe(u8, source);
|
|
var line_start: usize = 0;
|
|
while (line_start < body.len and body[line_start] == ';') {
|
|
const end = std.mem.indexOfScalarPos(u8, body, line_start, '\n') orelse body.len;
|
|
@memset(body[line_start..end], ' ');
|
|
line_start = end + 1;
|
|
}
|
|
|
|
const report = try aji.check.checkAir(arena, path, body);
|
|
if (report.status == .unimplemented)
|
|
return .{ .outcome = .pending, .detail = report.missing_stage };
|
|
if (try diagnosticIssue(arena, report.diagnostics)) |issue| return .{ .outcome = .fail, .detail = issue };
|
|
|
|
var got: std.ArrayList([]const u8) = .empty;
|
|
for (report.diagnostics) |d| {
|
|
if (d.severity == .@"error") try got.append(arena, d.code.id);
|
|
}
|
|
std.mem.sort([]const u8, got.items, {}, lessThan);
|
|
|
|
switch (header.expect) {
|
|
.accept => if (report.status == .accepted) return .{ .outcome = .pass },
|
|
.reject => |want| if (report.status == .rejected and eqlCodes(want, got.items)) return .{ .outcome = .pass },
|
|
.run => |want| if (report.status == .accepted) return runModule(arena, path, report.module.?, want, header),
|
|
}
|
|
return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "expected {f}, got {t} {s}", .{
|
|
fmtExpect(header.expect), report.status, try std.mem.join(arena, " ", got.items),
|
|
}) };
|
|
}
|
|
|
|
/// Runs the module twice and requires byte-identical run records (spec 11)
|
|
/// before comparing against the expectation.
|
|
/// Runs the module once per schedule seed; every seed must satisfy the
|
|
/// expectation (spec 04 §36.5). The program seed stays unchanged.
|
|
fn runModule(arena: std.mem.Allocator, path: []const u8, module: aji.air.Module, want: Expect.Run, header: Header) !Result {
|
|
if (stress_seeds) |n| if (header.schedules > 1) {
|
|
for (stress_quanta ++ [_]u64{header.quantum}) |q| {
|
|
var h = header;
|
|
h.quantum = q;
|
|
var seed: u64 = 0;
|
|
while (seed < n) : (seed += 1) {
|
|
const r = try runSeed(arena, module, want, h, seed);
|
|
if (r.outcome == .pass) continue;
|
|
var grants: std.Io.Writer.Allocating = .init(arena);
|
|
for (header.grants) |g| try grants.writer.print(" --grant {s}={s}{s}{s}", .{ g.parameter, g.kind, if (g.scope != null) ":" else "", g.scope orelse "" });
|
|
return .{ .outcome = r.outcome, .detail = try std.fmt.allocPrint(arena, "quantum {d}, schedule seed {d}: {s}; replay: aji run --quantum {d} --schedule-seed {d}{s} {s}", .{ q, seed, r.detail, q, seed, grants.written(), path }) };
|
|
}
|
|
}
|
|
return .{ .outcome = .pass };
|
|
};
|
|
var seed: u64 = 0;
|
|
while (seed < header.schedules) : (seed += 1) {
|
|
const r = try runSeed(arena, module, want, header, if (header.schedules > 1) seed else null);
|
|
if (r.outcome != .pass) {
|
|
if (header.schedules == 1) return r;
|
|
return .{ .outcome = r.outcome, .detail = try std.fmt.allocPrint(arena, "schedule seed {d}: {s}", .{ seed, r.detail }) };
|
|
}
|
|
}
|
|
return .{ .outcome = .pass };
|
|
}
|
|
|
|
fn runSeed(arena: std.mem.Allocator, module: aji.air.Module, want: Expect.Run, header: Header, schedule_seed: ?u64) !Result {
|
|
var records: [2][]const u8 = undefined;
|
|
var outcome: aji.interp.Outcome = undefined;
|
|
var output: aji.interp.Output = undefined;
|
|
for (&records, 0..) |*rec, k| {
|
|
outcome = aji.interp.run(arena, module, "main", .{
|
|
.fuel = header.fuel,
|
|
.grants = header.grants,
|
|
.world = header.world,
|
|
.output = &output,
|
|
.quantum = header.quantum,
|
|
.task_limit = header.task_limit,
|
|
.collect_every_step = collect_every_step and k == 1,
|
|
// Every run test also checks the verifier's DRF guarantee (spec 04 §21).
|
|
.detect_races = true,
|
|
.schedule_seed = schedule_seed,
|
|
}) catch |err| switch (err) {
|
|
error.EntryNotFound => return .{ .outcome = .fail, .detail = "module has no @main whose parameters are all capabilities" },
|
|
error.DuplicateGrant => return .{ .outcome = .fail, .detail = "a parameter is granted more than once" },
|
|
else => |e| return e,
|
|
};
|
|
var w: std.Io.Writer.Allocating = .init(arena);
|
|
try aji.interp.writeOutcome(module, outcome, output, &w.writer);
|
|
rec.* = w.written();
|
|
}
|
|
if (!std.mem.eql(u8, records[0], records[1]))
|
|
return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "nondeterministic: {s} vs {s}", .{ records[0], records[1] }) };
|
|
|
|
const ok = switch (want) {
|
|
.trap => |code| outcome == .trapped and std.mem.eql(u8, outcome.trapped.code.id, code),
|
|
.result => |json| outcome == .returned and std.mem.eql(u8, json, try valueJson(arena, module, outcome.returned)),
|
|
.not_instantiated => |reason| outcome == .not_instantiated and std.mem.eql(u8, outcome.not_instantiated.reason, reason),
|
|
.blocked => outcome == .blocked,
|
|
.limit_exceeded => |kind| outcome == .limit_exceeded and std.mem.eql(u8, outcome.limit_exceeded.kind, kind),
|
|
};
|
|
if (ok) {
|
|
if (header.stdout) |expected| if (!std.mem.eql(u8, expected, output.stdout))
|
|
return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "stdout differs: {s}", .{records[0]}) };
|
|
if (header.stderr) |expected| if (!std.mem.eql(u8, expected, output.stderr))
|
|
return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "stderr differs: {s}", .{records[0]}) };
|
|
for (header.files) |expected| {
|
|
const got = for (output.files) |f| {
|
|
if (std.mem.eql(u8, f[0], expected[0])) break f[1];
|
|
} else null;
|
|
if (got == null or !std.mem.eql(u8, got.?, expected[1]))
|
|
return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "file {s} differs: {s}", .{ expected[0], records[0] }) };
|
|
}
|
|
}
|
|
if (ok) return .{ .outcome = .pass };
|
|
return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "got {s}", .{records[0]}) };
|
|
}
|
|
|
|
fn valueJson(arena: std.mem.Allocator, module: aji.air.Module, v: aji.interp.Value) ![]const u8 {
|
|
var w: std.Io.Writer.Allocating = .init(arena);
|
|
var s: std.json.Stringify = .{ .writer = &w.writer };
|
|
try aji.interp.writeValue(module, v, &s);
|
|
return w.written();
|
|
}
|
|
|
|
/// First feature of the module header that this toolchain does not support.
|
|
fn unsupportedFeature(source: []const u8) ?[]const u8 {
|
|
var lines = std.mem.splitScalar(u8, source, '\n');
|
|
while (lines.next()) |line| {
|
|
if (!std.mem.startsWith(u8, line, "features [")) continue;
|
|
const close = std.mem.indexOfScalar(u8, line, ']') orelse return null;
|
|
var names = std.mem.tokenizeAny(u8, line["features [".len..close], ", ");
|
|
while (names.next()) |name| {
|
|
const known = for (aji.air.features.supported) |s| {
|
|
if (std.mem.eql(u8, s, name)) break true;
|
|
} else false;
|
|
if (!known) return name;
|
|
}
|
|
return null;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/// Header values are single lines: `\n`, `\t`, `\\` and `\xHH` escapes.
|
|
fn unescape(arena: std.mem.Allocator, s: []const u8) ![]const u8 {
|
|
var out: std.ArrayList(u8) = .empty;
|
|
var i: usize = 0;
|
|
while (i < s.len) : (i += 1) {
|
|
if (s[i] != '\\' or i + 1 == s.len) {
|
|
try out.append(arena, s[i]);
|
|
continue;
|
|
}
|
|
i += 1;
|
|
switch (s[i]) {
|
|
'n' => try out.append(arena, '\n'),
|
|
't' => try out.append(arena, '\t'),
|
|
'\\' => try out.append(arena, '\\'),
|
|
'x' => {
|
|
if (i + 2 >= s.len) return error.BadExpect;
|
|
try out.append(arena, std.fmt.parseInt(u8, s[i + 1 .. i + 3], 16) catch return error.BadExpect);
|
|
i += 2;
|
|
},
|
|
else => return error.BadExpect,
|
|
}
|
|
}
|
|
return out.items;
|
|
}
|
|
|
|
fn isKey(s: []const u8) bool {
|
|
if (s.len == 0) return false;
|
|
for (s) |ch| if (!std.ascii.isLower(ch) and ch != '_') return false;
|
|
return true;
|
|
}
|
|
|
|
fn eqlCodes(a: []const []const u8, b: []const []const u8) bool {
|
|
if (a.len != b.len) return false;
|
|
for (a, b) |x, y| if (!std.mem.eql(u8, x, y)) return false;
|
|
return true;
|
|
}
|
|
|
|
fn fmtExpect(e: Expect) std.fmt.Alt(Expect, formatExpect) {
|
|
return .{ .data = e };
|
|
}
|
|
|
|
fn formatExpect(e: Expect, w: *std.Io.Writer) std.Io.Writer.Error!void {
|
|
switch (e) {
|
|
.accept => try w.writeAll("accept"),
|
|
.reject => |codes| {
|
|
try w.writeAll("reject");
|
|
for (codes) |c| try w.print(" {s}", .{c});
|
|
},
|
|
.run => |r| switch (r) {
|
|
.result => |j| try w.print("run returning {s}", .{j}),
|
|
.trap => |c| try w.print("run trapping {s}", .{c}),
|
|
.not_instantiated => |reason| try w.print("not_instantiated ({s})", .{reason}),
|
|
.blocked => try w.writeAll("blocked"),
|
|
.limit_exceeded => |k| try w.print("limit_exceeded ({s})", .{k}),
|
|
},
|
|
}
|
|
}
|
|
|
|
const HeaderError = error{ BadModule, BadGrant, MissingExpect, MissingPhase, MissingSpec, MissingRunResult, UnknownKey, UnknownCode, BadExpect, OutOfMemory, InvalidCharacter, Overflow };
|
|
|
|
fn parseHeader(arena: std.mem.Allocator, source: []const u8) HeaderError!Header {
|
|
var expect: ?Expect = null;
|
|
var run_result: ?Expect.Run = null;
|
|
var phase: ?u8 = null;
|
|
var fuel: u64 = default_fuel;
|
|
var schedules: u64 = 1;
|
|
var quantum: u64 = 1000;
|
|
var task_limit: u64 = 1024;
|
|
var grants: std.ArrayList(aji.interp.Grant) = .empty;
|
|
var world: aji.interp.WorldOptions = .{};
|
|
var vfs: std.ArrayList(struct { []const u8, []const u8 }) = .empty;
|
|
var want_files: std.ArrayList(struct { []const u8, []const u8 }) = .empty;
|
|
var want_stdout: ?[]const u8 = null;
|
|
var want_stderr: ?[]const u8 = null;
|
|
var spec: ?[]const u8 = null;
|
|
var equivalent: ?[]const u8 = null;
|
|
var modules: std.ArrayList(ModuleBinding) = .empty;
|
|
|
|
var lines = std.mem.splitScalar(u8, source, '\n');
|
|
while (lines.next()) |line| {
|
|
// `.air` tests use `;` comments, `.aji` tests `//`.
|
|
const prefix: usize = if (std.mem.startsWith(u8, line, "//")) 2 else if (std.mem.startsWith(u8, line, ";")) 1 else break;
|
|
const content = std.mem.trim(u8, line[prefix..], " \t\r");
|
|
const colon = std.mem.indexOfScalar(u8, content, ':') orelse continue; // free-form comment
|
|
const key = content[0..colon];
|
|
if (!isKey(key)) continue; // free-form comment containing a colon
|
|
const value = std.mem.trim(u8, content[colon + 1 ..], " \t");
|
|
if (std.mem.eql(u8, key, "expect")) {
|
|
var it = std.mem.tokenizeScalar(u8, value, ' ');
|
|
const verb = it.next() orelse return error.BadExpect;
|
|
if (std.mem.eql(u8, verb, "run")) {
|
|
if (it.next() != null) return error.BadExpect;
|
|
expect = .{ .run = undefined };
|
|
} else if (std.mem.eql(u8, verb, "accept")) {
|
|
if (it.next() != null) return error.BadExpect;
|
|
expect = .accept;
|
|
} else if (std.mem.eql(u8, verb, "reject")) {
|
|
var codes: std.ArrayList([]const u8) = .empty;
|
|
while (it.next()) |c| {
|
|
if (aji.diag.lookup(c) == null) return error.UnknownCode;
|
|
try codes.append(arena, c);
|
|
}
|
|
if (codes.items.len == 0) return error.BadExpect;
|
|
std.mem.sort([]const u8, codes.items, {}, lessThan);
|
|
expect = .{ .reject = codes.items };
|
|
} else return error.BadExpect;
|
|
} else if (std.mem.eql(u8, key, "result")) {
|
|
if (run_result != null) return error.BadExpect;
|
|
run_result = .{ .result = value };
|
|
} else if (std.mem.eql(u8, key, "trap")) {
|
|
if (run_result != null) return error.BadExpect;
|
|
const code = aji.diag.lookup(value) orelse return error.UnknownCode;
|
|
if (code.id[0] != 'T') return error.UnknownCode;
|
|
run_result = .{ .trap = value };
|
|
} else if (std.mem.eql(u8, key, "not_instantiated")) {
|
|
if (run_result != null) return error.BadExpect;
|
|
run_result = .{ .not_instantiated = value };
|
|
} else if (std.mem.eql(u8, key, "limit_exceeded")) {
|
|
if (run_result != null) return error.BadExpect;
|
|
run_result = .{ .limit_exceeded = value };
|
|
} else if (std.mem.eql(u8, key, "blocked")) {
|
|
if (run_result != null) return error.BadExpect;
|
|
run_result = .blocked;
|
|
} else if (std.mem.eql(u8, key, "stdin")) {
|
|
world.stdin = try unescape(arena, value);
|
|
} else if (std.mem.eql(u8, key, "seed")) {
|
|
world.seed = try std.fmt.parseInt(u64, value, 10);
|
|
} else if (std.mem.eql(u8, key, "stdout")) {
|
|
want_stdout = try unescape(arena, value);
|
|
} else if (std.mem.eql(u8, key, "stderr")) {
|
|
want_stderr = try unescape(arena, value);
|
|
} else if (std.mem.eql(u8, key, "vfs") or std.mem.eql(u8, key, "file")) {
|
|
const eq = std.mem.indexOfScalar(u8, value, '=') orelse return error.BadExpect;
|
|
const entry: struct { []const u8, []const u8 } = .{ value[0..eq], try unescape(arena, value[eq + 1 ..]) };
|
|
try (if (std.mem.eql(u8, key, "vfs")) &vfs else &want_files).append(arena, entry);
|
|
} else if (std.mem.eql(u8, key, "grant")) {
|
|
const eq = std.mem.indexOfScalar(u8, value, '=') orelse return error.BadGrant;
|
|
const rest = value[eq + 1 ..];
|
|
const sep = std.mem.indexOfScalar(u8, rest, ':');
|
|
try grants.append(arena, .{
|
|
.parameter = value[0..eq],
|
|
.kind = if (sep) |c| rest[0..c] else rest,
|
|
.scope = if (sep) |c| rest[c + 1 ..] else null,
|
|
});
|
|
} else if (std.mem.eql(u8, key, "schedules")) {
|
|
schedules = try std.fmt.parseInt(u64, value, 10);
|
|
} else if (std.mem.eql(u8, key, "quantum")) {
|
|
quantum = try std.fmt.parseInt(u64, value, 10);
|
|
} else if (std.mem.eql(u8, key, "task_limit")) {
|
|
task_limit = try std.fmt.parseInt(u64, value, 10);
|
|
} else if (std.mem.eql(u8, key, "fuel")) {
|
|
fuel = try std.fmt.parseInt(u64, value, 10);
|
|
} else if (std.mem.eql(u8, key, "phase")) {
|
|
phase = try std.fmt.parseInt(u8, value, 10);
|
|
} else if (std.mem.eql(u8, key, "spec")) {
|
|
spec = value;
|
|
} else if (std.mem.eql(u8, key, "module")) {
|
|
const eq = std.mem.indexOfScalar(u8, value, '=') orelse return error.BadModule;
|
|
if (eq == 0 or eq + 1 == value.len) return error.BadModule;
|
|
try modules.append(arena, .{ .name = value[0..eq], .path = value[eq + 1 ..] });
|
|
} else if (std.mem.eql(u8, key, "equivalent")) {
|
|
equivalent = value;
|
|
} else return error.UnknownKey;
|
|
}
|
|
if (expect) |*e| switch (e.*) {
|
|
.run => e.* = .{ .run = run_result orelse return error.MissingRunResult },
|
|
else => if (run_result != null) return error.BadExpect,
|
|
};
|
|
return .{
|
|
.expect = expect orelse return error.MissingExpect,
|
|
.fuel = fuel,
|
|
.schedules = schedules,
|
|
.quantum = quantum,
|
|
.task_limit = task_limit,
|
|
.grants = grants.items,
|
|
.world = blk: {
|
|
world.files = vfs.items;
|
|
break :blk world;
|
|
},
|
|
.stdout = want_stdout,
|
|
.stderr = want_stderr,
|
|
.files = want_files.items,
|
|
.phase = phase orelse return error.MissingPhase,
|
|
.spec = spec orelse return error.MissingSpec,
|
|
.equivalent = equivalent,
|
|
.modules = modules.items,
|
|
};
|
|
}
|
|
|
|
test parseHeader {
|
|
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
|
defer arena_state.deinit();
|
|
const h = try parseHeader(arena_state.allocator(),
|
|
\\; Use of %x without a definition.
|
|
\\; expect: reject E5001
|
|
\\; phase: 0
|
|
\\; spec: docs/spec/07-air.md
|
|
\\fn @f() -> u64
|
|
);
|
|
try std.testing.expectEqual(@as(u8, 0), h.phase);
|
|
try std.testing.expectEqualStrings("E5001", h.expect.reject[0]);
|
|
try std.testing.expectError(error.UnknownCode, parseHeader(arena_state.allocator(), "; expect: reject E9999\n"));
|
|
}
|
|
|
|
test "diagnostic API validation rejects collisions after source mapping" {
|
|
var a: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
|
defer a.deinit();
|
|
const arena = a.allocator();
|
|
const valid: aji.diag.Diagnostic = .{ .code = aji.diag.lookup("E7002").?, .fields = &.{.{ .name = "capability_kind", .value = .{ .str = "unknown" } }} };
|
|
try std.testing.expect((try diagnosticIssue(arena, &.{valid})) == null);
|
|
var bad = valid;
|
|
bad.fields = &.{.{ .name = "kind", .value = .{ .str = "unknown" } }};
|
|
try std.testing.expect((try diagnosticIssue(arena, &.{bad})) != null);
|
|
bad.fields = &.{ .{ .name = "air_line", .value = .{ .int = 3 } }, .{ .name = "air_line", .value = .{ .int = 8 } } };
|
|
try std.testing.expect((try diagnosticIssue(arena, &.{bad})) != null);
|
|
}
|