Files
aji/tools/conformance.zig
T
dev 17a55a7fef Initial import: Aji 0.1 draft spec and Zig scaffolding
Draft specification, RFCs, reference registries and examples, plus the
reference-implementation skeleton: build.zig, diagnostic envelope with
error-code registry synced to docs, aji CLI, conformance runner with seed
tests, CI and contributor docs.
2026-10-04 11:59:13 +03:00

216 lines
8.1 KiB
Zig

//! Conformance suite runner. Format: tests/conformance/README.md.
//!
//! usage: aji-conformance <dir> [--json] [--filter <substring>]
//!
//! 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,
};
const Outcome = enum { pass, fail, pending };
const Header = struct {
expect: Expect,
phase: u8,
spec: []const u8,
};
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>]\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 {
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")) 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 = 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);
}
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 = "" };
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}) };
// 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 };
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 },
}
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),
}) };
}
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});
},
}
}
const HeaderError = error{ MissingExpect, MissingPhase, MissingSpec, UnknownKey, UnknownCode, BadExpect, OutOfMemory, InvalidCharacter, Overflow };
fn parseHeader(arena: std.mem.Allocator, source: []const u8) HeaderError!Header {
var expect: ?Expect = null;
var phase: ?u8 = null;
var spec: ?[]const u8 = null;
var lines = std.mem.splitScalar(u8, source, '\n');
while (lines.next()) |line| {
if (!std.mem.startsWith(u8, line, ";")) break;
const content = std.mem.trim(u8, line[1..], " \t\r");
const colon = std.mem.indexOfScalar(u8, content, ':') orelse continue; // free-form comment
const key = content[0..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, "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, "phase")) {
phase = try std.fmt.parseInt(u8, value, 10);
} else if (std.mem.eql(u8, key, "spec")) {
spec = value;
} else return error.UnknownKey;
}
return .{
.expect = expect orelse return error.MissingExpect,
.phase = phase orelse return error.MissingPhase,
.spec = spec orelse return error.MissingSpec,
};
}
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"));
}