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.
This commit is contained in:
dev committed 2026-10-04 11:59:13 +03:00
commit 17a55a7fef
67 files changed
+4197

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
//! AIR — Aji Intermediate Representation (spec 07, RFC 0004).
//!
//! Phase 0 deliverables (docs/roadmap/phase-0.md):
//! - type and value model;
//! - text AIR lexer, parser and canonical serializer;
//! - functions, basic blocks with block parameters, terminators.
//!
//! Text AIR is the canonical interchange until opcode numbering freezes
//! (RFC 0004 "Binary stability").
/// Bumped on any incompatible change to text or binary AIR (spec 00 §5).
pub const format_version: u32 = 0;
+30
View File
@@ -0,0 +1,30 @@
//! Front door used by the CLI, the conformance runner and (later) `ajid`:
//! parse → verify, collecting diagnostics.
const std = @import("std");
const diag = @import("diag.zig");
pub const Status = enum {
/// Module verified; no error diagnostics.
accepted,
/// At least one error diagnostic.
rejected,
/// The pipeline cannot yet decide this input.
unimplemented,
};
pub const Report = struct {
status: Status,
diagnostics: []const diag.Diagnostic,
/// Pipeline stage that is missing when `status == .unimplemented`.
missing_stage: []const u8 = "",
};
/// Checks a text AIR module. All allocations go into `arena`.
pub fn checkAir(arena: std.mem.Allocator, file_name: []const u8, source: []const u8) !Report {
_ = arena;
_ = file_name;
_ = source;
// TODO(phase-0): air.parse → verifier.verify.
return .{ .status = .unimplemented, .diagnostics = &.{}, .missing_stage = "air.parse" };
}
+179
View File
@@ -0,0 +1,179 @@
//! Stable machine-readable diagnostics (spec 10).
//!
//! Diagnostics are an API for automated repair. Codes and kinds are stable
//! once released; `registry` MUST mirror docs/reference/error-codes.md, which
//! is enforced by the test at the bottom of this file.
const std = @import("std");
pub const Code = struct {
/// Stable identifier, e.g. "E2001".
id: []const u8,
/// Stable machine kind, e.g. "ownership.use_after_move".
kind: []const u8,
/// Short human description. Not part of the stable contract.
meaning: []const u8,
};
pub const registry = [_]Code{
// E1xxx — Types and values
.{ .id = "E1001", .kind = "type.mismatch", .meaning = "Operand/result type mismatch" },
.{ .id = "E1002", .kind = "type.invalid_cast", .meaning = "Cast not permitted by safe semantics" },
.{ .id = "E1010", .kind = "init.read_uninitialized", .meaning = "Read from uninitialized storage" },
// E2xxx — Memory and ownership
.{ .id = "E2001", .kind = "ownership.use_after_move", .meaning = "Value used after ownership transfer" },
.{ .id = "E2002", .kind = "ownership.double_consume", .meaning = "Linear value consumed twice" },
.{ .id = "E2101", .kind = "borrow.mutable_alias", .meaning = "Overlapping exclusive/shared borrow violation" },
.{ .id = "E2102", .kind = "borrow.outlives_owner", .meaning = "Borrow may outlive backing storage" },
.{ .id = "E2103", .kind = "memory.out_of_bounds", .meaning = "Access not proven in bounds" },
.{ .id = "E2104", .kind = "memory.region_generation", .meaning = "Reference belongs to invalidated region generation" },
.{ .id = "E2110", .kind = "island.escape", .meaning = "Island-internal reference escapes island" },
.{ .id = "E2111", .kind = "island.foreign_mutable_edge", .meaning = "Island graph points to forbidden foreign mutable storage" },
// E3xxx — Resources/capabilities/effects
.{ .id = "E3001", .kind = "resource.use_after_consume", .meaning = "Closed/joined/released resource reused" },
.{ .id = "E3002", .kind = "resource.leak", .meaning = "Linear resource has no terminal consumption path" },
.{ .id = "E3101", .kind = "effect.undeclared", .meaning = "Callee effect absent from caller contract" },
.{ .id = "E3201", .kind = "capability.missing", .meaning = "Required authority unavailable" },
.{ .id = "E3202", .kind = "capability.widen", .meaning = "Attempt to widen delegated authority" },
// E4xxx — Concurrency
.{ .id = "E4001", .kind = "concurrency.not_send", .meaning = "Non-Send value moved to migratable task/thread" },
.{ .id = "E4002", .kind = "concurrency.not_share", .meaning = "Non-Share value concurrently shared" },
.{ .id = "E4101", .kind = "concurrency.possible_data_race", .meaning = "Conflicting ordinary access not ordered/synchronized" },
.{ .id = "E4201", .kind = "atomic.invalid_order", .meaning = "Memory ordering invalid for atomic operation" },
.{ .id = "E4301", .kind = "task.live_child_escape", .meaning = "Scope exits with live child task" },
.{ .id = "E4302", .kind = "task.borrow_escape", .meaning = "Child task borrow can outlive parent storage" },
.{ .id = "E4303", .kind = "io.buffer_in_flight", .meaning = "Buffer accessed while async operation owns/borrows it" },
// E5xxx — AIR/verifier
.{ .id = "E5001", .kind = "air.invalid_ssa", .meaning = "SSA definition/dominance failure" },
.{ .id = "E5002", .kind = "air.invalid_cfg", .meaning = "Invalid block/terminator structure" },
.{ .id = "E5101", .kind = "verifier.resource_limit", .meaning = "Deterministic verifier resource limit exceeded" },
// E6xxx — Unsafe/ABI
.{ .id = "E6001", .kind = "unsafe.required", .meaning = "Operation requires explicit unsafe boundary" },
.{ .id = "E6101", .kind = "abi.unaligned_reference", .meaning = "Normal reference requested from insufficiently aligned storage" },
};
pub fn lookup(id: []const u8) ?*const Code {
for (&registry) |*c| {
if (std.mem.eql(u8, c.id, id)) return c;
}
return null;
}
pub const Severity = enum { @"error", warning, note };
pub const Span = struct {
file: []const u8,
/// 1-based.
line: u32,
/// 1-based, in bytes.
col: u32,
};
/// Structured, code-specific payload (e.g. "value": "%17").
pub const Field = struct {
name: []const u8,
value: Value,
pub const Value = union(enum) {
int: i64,
str: []const u8,
};
};
pub const Diagnostic = struct {
code: *const Code,
severity: Severity = .@"error",
span: ?Span = null,
/// Optional human explanation. Agents MUST NOT need to parse it.
message: []const u8 = "",
fields: []const Field = &.{},
/// Non-binding structured suggestions (spec 10 §3).
repair_candidates: []const []const u8 = &.{},
/// Writes the diagnostic as a single JSON object (no trailing newline).
/// Key order is fixed so output is byte-for-byte deterministic.
pub fn writeJson(d: Diagnostic, w: *std.Io.Writer) std.Io.Writer.Error!void {
var s: std.json.Stringify = .{ .writer = w };
try s.beginObject();
try s.objectField("code");
try s.write(d.code.id);
try s.objectField("kind");
try s.write(d.code.kind);
try s.objectField("severity");
try s.write(@tagName(d.severity));
if (d.span) |sp| {
try s.objectField("file");
try s.write(sp.file);
try s.objectField("line");
try s.write(sp.line);
try s.objectField("col");
try s.write(sp.col);
}
for (d.fields) |f| {
try s.objectField(f.name);
switch (f.value) {
inline else => |v| try s.write(v),
}
}
if (d.message.len != 0) {
try s.objectField("message");
try s.write(d.message);
}
if (d.repair_candidates.len != 0) {
try s.objectField("repair_candidates");
try s.beginArray();
for (d.repair_candidates) |kind| {
try s.beginObject();
try s.objectField("kind");
try s.write(kind);
try s.endObject();
}
try s.endArray();
}
try s.endObject();
}
};
test "writeJson is deterministic and structured" {
var buf: [512]u8 = undefined;
var w: std.Io.Writer = .fixed(&buf);
const d: Diagnostic = .{
.code = lookup("E2104").?,
.span = .{ .file = "decode.air", .line = 12, .col = 5 },
.fields = &.{
.{ .name = "value", .value = .{ .str = "%17" } },
.{ .name = "expected_generation", .value = .{ .int = 5 } },
},
.repair_candidates = &.{"move_reset_after_use"},
};
try d.writeJson(&w);
try std.testing.expectEqualStrings(
\\{"code":"E2104","kind":"memory.region_generation","severity":"error","file":"decode.air","line":12,"col":5,"value":"%17","expected_generation":5,"repair_candidates":[{"kind":"move_reset_after_use"}]}
, w.buffered());
}
test "registry mirrors docs/reference/error-codes.md" {
const md = @embedFile("error_codes_md");
var seen: usize = 0;
var lines = std.mem.splitScalar(u8, md, '\n');
while (lines.next()) |line| {
// Table rows look like: | E1001 | type.mismatch | Meaning |
if (!std.mem.startsWith(u8, line, "| E")) continue;
var cols = std.mem.tokenizeScalar(u8, line, '|');
const id = std.mem.trim(u8, cols.next().?, " ");
const kind = std.mem.trim(u8, cols.next().?, " ");
const code = lookup(id) orelse {
std.debug.print("code {s} is in error-codes.md but not in diag.registry\n", .{id});
return error.RegistryOutOfSync;
};
try std.testing.expectEqualStrings(kind, code.kind);
seen += 1;
}
try std.testing.expectEqual(registry.len, seen);
}
test "registry ids are unique" {
for (registry, 0..) |a, i| {
for (registry[i + 1 ..]) |b| try std.testing.expect(!std.mem.eql(u8, a.id, b.id));
}
}
+6
View File
@@ -0,0 +1,6 @@
//! 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.
+95
View File
@@ -0,0 +1,95 @@
//! `aji` command-line driver.
//!
//! 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).
const std = @import("std");
const aji = @import("aji");
const usage =
\\usage: aji <command> [args]
\\
\\commands:
\\ check <file.air> parse and verify a text AIR module
\\ 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 };
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);
var stdout_buf: [4096]u8 = undefined;
var stdout_fw: std.Io.File.Writer = .init(.stdout(), io, &stdout_buf);
const out = &stdout_fw.interface;
const code = run(io, arena, args, out) catch |err| switch (err) {
error.WriteFailed => return stdout_fw.err.?,
else => |e| return e,
};
try out.flush();
std.process.exit(@backingInt(code));
}
fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *std.Io.Writer) !ExitCode {
if (args.len < 2) {
std.debug.print("{s}", .{usage});
return .usage;
}
const cmd = args[1];
if (std.mem.eql(u8, cmd, "version")) {
try out.print("aji {s} (air format {d})\n", .{ aji.version, aji.air.format_version });
return .accepted;
}
if (std.mem.eql(u8, cmd, "codes")) {
for (aji.diag.registry) |c| try writeCode(out, c);
return .accepted;
}
if (std.mem.eql(u8, cmd, "explain")) {
if (args.len != 3) return usageError("explain takes exactly one code");
const c = aji.diag.lookup(args[2]) orelse return usageError("unknown diagnostic code");
try writeCode(out, c.*);
return .accepted;
}
if (std.mem.eql(u8, cmd, "check")) {
if (args.len != 3) return usageError("check takes 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 });
return .usage;
};
const report = try aji.check.checkAir(arena, path, source);
for (report.diagnostics) |d| {
try d.writeJson(out);
try out.writeByte('\n');
}
return switch (report.status) {
.accepted => .accepted,
.rejected => .rejected,
.unimplemented => {
std.debug.print("aji: not implemented yet: {s}\n", .{report.missing_stage});
return .unimplemented;
},
};
}
return usageError("unknown command");
}
fn writeCode(out: *std.Io.Writer, c: aji.diag.Code) !void {
var s: std.json.Stringify = .{ .writer = out };
try s.write(.{ .code = c.id, .kind = c.kind, .meaning = c.meaning });
try out.writeByte('\n');
}
fn usageError(msg: []const u8) ExitCode {
std.debug.print("aji: {s}\n\n{s}", .{ msg, usage });
return .usage;
}
+17
View File
@@ -0,0 +1,17 @@
//! Aji reference implementation.
//!
//! Trusted computing base (AGENTS.md): verifier, AIR interpreter semantics,
//! backend, unsafe runtime modules, ABI/platform descriptions. Keep modules
//! small and keep the verifier free of heuristics.
pub const version = "0.0.0-dev";
pub const diag = @import("diag.zig");
pub const air = @import("air.zig");
pub const verifier = @import("verifier.zig");
pub const interp = @import("interp.zig");
pub const check = @import("check.zig");
test {
@import("std").testing.refAllDecls(@This());
}
+8
View File
@@ -0,0 +1,8 @@
//! AIR verifier (spec 08). Part of the language semantics, not a lint.
//!
//! Passes are added in roadmap order. Each normative rejection MUST map to a
//! code in `diag.registry` and MUST have positive and negative conformance
//! tests under tests/conformance/.
//!
//! Phase 0: SSA/dominance (E5001), CFG/terminators (E5002), types (E1001),
//! deterministic resource budget (E5101).