//! 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{ // E0xxx — AIR text and module .{ .id = "E0001", .kind = "parse.unexpected_token", .meaning = "Token not allowed by the text AIR grammar here" }, .{ .id = "E0002", .kind = "parse.invalid_literal", .meaning = "Literal malformed or not representable in its type" }, .{ .id = "E0003", .kind = "parse.duplicate_name", .meaning = "Function, type, block, field or variant name defined twice" }, .{ .id = "E0004", .kind = "parse.unknown_name", .meaning = "Unknown opcode, type, function, field or variant" }, .{ .id = "E0005", .kind = "module.unsupported_version", .meaning = "AIR format or language version not implemented" }, .{ .id = "E0006", .kind = "module.unsupported_feature", .meaning = "Feature unknown, unsupported, undeclared or dependency-incomplete, or reserved type used" }, // 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 = "E1003", .kind = "type.recursive", .meaning = "Aggregate type contains itself by value" }, .{ .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 = "E2105", .kind = "borrow.not_ended", .meaning = "Owned borrow live at `ret`, or borrow state differs between edges into a block" }, .{ .id = "E2106", .kind = "borrow.use_after_end", .meaning = "Borrow used or ended after it was ended" }, .{ .id = "E2107", .kind = "borrow.not_owned", .meaning = "Lent (parameter) borrow ended by the callee" }, .{ .id = "E2108", .kind = "borrow.escapes_frame", .meaning = "Borrow derived from frame storage returned from its function" }, .{ .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 = "E4202", .kind = "atomic.ordinary_access", .meaning = "Atomic cell accessed by an ordinary load" }, .{ .id = "E4203", .kind = "atomic.unsupported_width", .meaning = "Atomic width not implemented lock-free by the target" }, .{ .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" }, .{ .id = "E4304", .kind = "sync.wait_while_locked", .meaning = "Suspending operation, spawn, or call of a waiting/spawning function while a lock guard is live" }, .{ .id = "E4305", .kind = "task.shield_order", .meaning = "Shield ended while a more inner shield is live" }, // 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; field `reason`: `outside_boundary`, `trusted_declares_unsafe`" }, .{ .id = "E6101", .kind = "abi.unaligned_reference", .meaning = "Normal reference requested from insufficiently aligned storage" }, .{ .id = "E7001", .kind = "source.syntax", .meaning = "Malformed `.aji` source" }, .{ .id = "E7002", .kind = "source.unknown_name", .meaning = "Undefined variable, function, type, field or variant" }, .{ .id = "E7003", .kind = "source.missing_move", .meaning = "Named linear value consumed without `move`" }, .{ .id = "E7004", .kind = "source.not_exhaustive", .meaning = "`match` misses an outcome, variant or default" }, .{ .id = "E7005", .kind = "source.type_mismatch", .meaning = "Expression has the wrong type in a source position" }, .{ .id = "E7006", .kind = "source.invalid_construct", .meaning = "Construct not allowed here" }, .{ .id = "E7007", .kind = "source.ambiguous", .meaning = "Source meaning cannot be determined" }, .{ .id = "E7900", .kind = "source.internal_compiler_error", .meaning = "The frontend produced invalid AIR for this construct: a compiler bug, not a program error; fields `air_code`, `air_message`" }, // T0xxx — Runtime traps (reported in trap records, not by the verifier) .{ .id = "T0001", .kind = "trap.explicit", .meaning = "`trap` instruction executed" }, .{ .id = "T0002", .kind = "trap.assert", .meaning = "Assertion failed" }, .{ .id = "T0003", .kind = "trap.overflow", .meaning = "Checked arithmetic result not representable" }, .{ .id = "T0004", .kind = "trap.division_by_zero", .meaning = "Division or remainder by zero" }, .{ .id = "T0005", .kind = "trap.shift_out_of_range", .meaning = "Shift amount negative or not less than bit width" }, .{ .id = "T0006", .kind = "trap.cast_out_of_range", .meaning = "Checked cast value not representable in target type" }, .{ .id = "T0007", .kind = "trap.call_depth", .meaning = "Call depth limit (1 024 frames) exceeded" }, .{ .id = "T0008", .kind = "trap.out_of_bounds", .meaning = "Runtime bounds check failed" }, .{ .id = "T0009", .kind = "trap.unsafe_precondition", .meaning = "Unsafe precondition violated (detected)" }, .{ .id = "T0010", .kind = "trap.foreign_iref", .meaning = "An `iref` was used to access a graph it does not belong to" }, }; pub fn lookup(id: []const u8) ?*const Code { for (®istry) |*c| { if (std.mem.eql(u8, c.id, id)) return c; } return null; } /// Stable E7006 categories (spec 15 §10; reference/error-codes.md). pub const SourceInvalidReason = enum { move_copy, move_borrow, invalid_move, loop_control_outside_loop, zero_not_zeroable, value_block_statement, @"unreachable", missing_return, invalid_borrow, invalid_borrow_return, duplicate_declaration, invalid_declaration, invalid_binding, invalid_assignment, invalid_place, invalid_match, invalid_unpack, invalid_expression, invalid_operation, invalid_literal, invalid_generic, invalid_static_function, implementation_limit, invalid_module_mapping, duplicate_import, import_cycle, module_header_mismatch, trusted_unavailable, }; 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") and !std.mem.startsWith(u8, line, "| T")) 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)); } } test "E7006 reason registry mirrors documentation" { const md = @embedFile("error_codes_md"); const heading = "## E7006 reasons\n"; const start = (std.mem.indexOf(u8, md, heading) orelse return error.RegistryOutOfSync) + heading.len; const section = md[start..]; const section_end = std.mem.indexOf(u8, section, "\n## ") orelse section.len; var lines = std.mem.splitScalar(u8, section[0..section_end], '\n'); var seen: std.EnumSet(SourceInvalidReason) = .empty; while (lines.next()) |line| { if (!std.mem.startsWith(u8, line, "| `")) continue; const end = std.mem.indexOfScalarPos(u8, line, 3, '`') orelse return error.RegistryOutOfSync; const reason = std.meta.stringToEnum(SourceInvalidReason, line[3..end]) orelse return error.RegistryOutOfSync; try std.testing.expect(!seen.contains(reason)); seen.insert(reason); } try std.testing.expect(seen.eql(.full)); }