frontend: provide contextual source repair advice

This commit is contained in:
dev committed 2026-10-09 14:04:40 +03:00
1 parent 008867fe48
commit 2c6c7a3dcd
37 files changed
+562 -24

No files matched your search

+115 -11
View File
@@ -157,6 +157,81 @@ pub const Field = struct {
};
};
pub const RepairCandidate = struct {
kind: []const u8,
hint: []const u8 = "",
alternatives: []const []const u8 = &.{},
};
/// Shared serialization for the envelope and conformance advice goldens.
pub fn writeRepairCandidates(candidates: []const RepairCandidate, s: *std.json.Stringify) std.Io.Writer.Error!void {
try s.beginArray();
for (candidates) |candidate| {
try s.beginObject();
try s.objectField("kind");
try s.write(candidate.kind);
if (candidate.hint.len != 0) {
try s.objectField("hint");
try s.write(candidate.hint);
}
if (candidate.alternatives.len != 0) {
try s.objectField("alternatives");
try s.write(candidate.alternatives);
}
try s.endObject();
}
try s.endArray();
}
/// Closed source advice registry (reference/error-codes.md). Text is fixed;
/// agents select by kind, never by interpreting the hint.
pub const SourceRepairKind = enum {
boolean_negation,
annotate_var_type,
slice_mut_type,
slice_ref_type,
explicit_range_end,
borrow_argument,
borrow_binding,
zero_storage,
numeric_cast_modes,
pub fn hint(kind: SourceRepairKind) []const u8 {
return switch (kind) {
.boolean_negation => "Aji boolean negation is `not`; integer complement is not boolean negation.",
.annotate_var_type => "Write an explicit type: `var name: T = expression;`. `let` may infer its type.",
.slice_mut_type => "Write `slice_mut<T>` for a mutable slice type.",
.slice_ref_type => "Write `slice<T>` for a shared slice type.",
.explicit_range_end => "Write both slice bounds: `receiver[start..end]`; choose the upper bound explicitly.",
.borrow_argument => "Write `ref place` or `mut place` for an inline borrow argument.",
.borrow_binding => "Bind a borrow with `ref name = place;` or `mut name = place;`, rather than a let/var initializer.",
.zero_storage => "`zero` is only a whole var initializer: `var name: T = zero;`; T must be zeroable.",
.numeric_cast_modes => "Choose `as!` for a checked conversion (T0006 on overflow) or `as%` for a wrapping conversion.",
};
}
pub fn code(kind: SourceRepairKind) []const u8 {
return if (kind == .numeric_cast_modes) "E7005" else "E7001";
}
pub fn unit(kind: SourceRepairKind) []const u8 {
return switch (kind) {
.slice_mut_type, .slice_ref_type => "complete type",
.borrow_argument => "prefix",
.numeric_cast_modes => "operator",
else => "none",
};
}
pub fn candidate(kind: SourceRepairKind, alternatives: []const []const u8) RepairCandidate {
return .{ .kind = @tagName(kind), .hint = kind.hint(), .alternatives = alternatives };
}
pub fn one(comptime kind: SourceRepairKind) []const RepairCandidate {
return comptime &.{kind.candidate(if (kind == .numeric_cast_modes) &.{ "as!", "as%" } else &.{})};
}
};
pub const Diagnostic = struct {
code: *const Code,
severity: Severity = .@"error",
@@ -165,7 +240,7 @@ pub const Diagnostic = struct {
message: []const u8 = "",
fields: []const Field = &.{},
/// Non-binding structured suggestions (spec 10 §3).
repair_candidates: []const []const u8 = &.{},
repair_candidates: []const RepairCandidate = &.{},
related_locations: []const RelatedLocation = &.{},
/// Writes the diagnostic as a single JSON object (no trailing newline).
@@ -199,14 +274,7 @@ pub const Diagnostic = struct {
}
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 writeRepairCandidates(d.repair_candidates, &s);
}
if (d.related_locations.len != 0) {
try s.objectField("related_locations");
@@ -249,7 +317,7 @@ test "writeJson is deterministic and structured" {
.{ .name = "value", .value = .{ .str = "%17" } },
.{ .name = "expected_generation", .value = .{ .int = 5 } },
},
.repair_candidates = &.{"move_reset_after_use"},
.repair_candidates = &.{.{ .kind = "move_reset_after_use" }},
};
try d.writeJson(&w);
try std.testing.expectEqualStrings(
@@ -265,7 +333,7 @@ test "related locations are typed, ordered and appended after existing fields" {
.span = .{ .file = "main.aji", .line = 9, .col = 5 },
.fields = &.{.{ .name = "conflicts_with", .value = .{ .str = "%view_4" } }},
.message = "conflict",
.repair_candidates = &.{"example"},
.repair_candidates = &.{.{ .kind = "example" }},
.related_locations = &.{.{
.role = .conflicting_borrow,
.value = "%view_4",
@@ -335,6 +403,42 @@ test "registry ids are unique" {
}
}
test "source repair registry mirrors kinds, codes, hints and units" {
const md = @embedFile("error_codes_md");
const heading = "## Source repair candidate kinds\n";
const start = (std.mem.indexOf(u8, md, heading) orelse return error.RegistryOutOfSync) + heading.len;
const section = md[start..];
const end = std.mem.indexOf(u8, section, "\n## ") orelse section.len;
var lines = std.mem.splitScalar(u8, section[0..end], '\n');
var seen: std.EnumSet(SourceRepairKind) = .empty;
while (lines.next()) |line| {
if (!std.mem.startsWith(u8, line, "| `")) continue;
var cols = std.mem.tokenizeScalar(u8, line, '|');
const name = std.mem.trim(u8, cols.next().?, " `");
const kind = std.meta.stringToEnum(SourceRepairKind, name) orelse return error.RegistryOutOfSync;
try std.testing.expect(!seen.contains(kind));
seen.insert(kind);
try std.testing.expectEqualStrings(kind.code(), std.mem.trim(u8, cols.next().?, " "));
try std.testing.expectEqualStrings(kind.hint(), std.mem.trim(u8, cols.next().?, " "));
try std.testing.expectEqualStrings(kind.unit(), std.mem.trim(u8, cols.next().?, " "));
try std.testing.expect(cols.next() == null);
}
try std.testing.expect(seen.eql(.full));
}
test "repair hints and alternatives escape JSON with deterministic member order" {
var out: std.Io.Writer.Allocating = .init(std.testing.allocator);
defer out.deinit();
const d: Diagnostic = .{
.code = lookup("E7001").?,
.repair_candidates = &.{.{ .kind = "example", .hint = "quote \" and newline\n", .alternatives = &.{ "a\\b", "c" } }},
};
try d.writeJson(&out.writer);
try std.testing.expectEqualStrings(
\\{"code":"E7001","kind":"source.syntax","severity":"error","repair_candidates":[{"kind":"example","hint":"quote \" and newline\n","alternatives":["a\\b","c"]}]}
, out.written());
}
test "E7006 reason registry mirrors documentation" {
const md = @embedFile("error_codes_md");
const heading = "## E7006 reasons\n";
+2
View File
@@ -52,6 +52,7 @@ pub fn compileWithModules(arena: std.mem.Allocator, file: []const u8, source: []
.span = .{ .file = p.span.file orelse file, .line = p.span.start.line, .col = p.span.start.col },
.message = p.message,
.fields = fields,
.repair_candidates = p.repair_candidates,
} };
},
.unimplemented => |u| .{ .unimplemented = try std.fmt.allocPrint(arena, "{s}:{d}:{d}: {s}", .{ u.span.file orelse file, u.span.start.line, u.span.start.col, u.construct }) },
@@ -63,6 +64,7 @@ pub fn syntaxDiagnostic(arena: std.mem.Allocator, file: []const u8, f: parse.Fai
.code = diag.lookup("E7001").?,
.span = .{ .file = file, .line = f.pos.line, .col = f.pos.col },
.message = try std.fmt.allocPrint(arena, "expected {s}", .{f.expected}),
.repair_candidates = f.repair_candidates,
.fields = try arena.dupe(diag.Field, &.{
.{ .name = "expected", .value = .{ .str = f.expected } },
.{ .name = "found", .value = .{ .str = f.found } },
+13 -1
View File
@@ -150,6 +150,7 @@ pub const Problem = struct {
span: Span,
message: []const u8,
fields: []const Field = &.{},
repair_candidates: []const @import("../diag.zig").RepairCandidate = &.{},
pub const Field = struct { name: []const u8, value: []const u8 };
};
@@ -364,6 +365,17 @@ const Lowerer = struct {
return error.Lower;
}
fn invalidWidening(l: *Lowerer, span: Span, fields: []const Problem.Field) Error {
l.problem = .{
.code = "E7005",
.span = span,
.message = "`as` only widens without loss; use `as!` (checked, traps T0006 when the value does not fit) or `as%` (wrapping)",
.fields = try l.arena.dupe(Problem.Field, fields),
.repair_candidates = @import("../diag.zig").SourceRepairKind.one(.numeric_cast_modes),
};
return error.Lower;
}
fn notYet(l: *Lowerer, span: Span, construct: []const u8) Error {
l.unimpl = .{ .span = span, .construct = construct };
return error.Unimplemented;
@@ -1678,7 +1690,7 @@ const Lowerer = struct {
const a = std.meta.stringToEnum(air_module.IntType, v.ty.int).?;
const b = std.meta.stringToEnum(air_module.IntType, to.int).?;
if (a != b and !verifier_types.lossless(a, b))
return l.fail("E7005", e.span, "`as` only widens without loss; use `as!` (checked, traps T0006 when the value does not fit) or `as%` (wrapping)", &.{ .{ .name = "from", .value = v.ty.int }, .{ .name = "to", .value = to.int } });
return l.invalidWidening(e.span, &.{ .{ .name = "from", .value = v.ty.int }, .{ .name = "to", .value = to.int } });
}
const mode = switch (x.mode) {
.widen => "widen",
+1
View File
@@ -123,6 +123,7 @@ const Graph = struct {
.span = .{ .start = failure.pos, .end = failure.pos, .file = source.file, .namespace = source.name },
.message = try std.fmt.allocPrint(g.arena, "expected {s}", .{failure.expected}),
.fields = try g.arena.dupe(lower.Problem.Field, &.{ .{ .name = "expected", .value = failure.expected }, .{ .name = "found", .value = failure.found } }),
.repair_candidates = if (std.mem.startsWith(u8, source.name, "std.")) &.{} else failure.repair_candidates,
};
return error.InvalidSource;
},
+111 -9
View File
@@ -5,12 +5,18 @@
const std = @import("std");
const lex = @import("lex.zig");
const ast = @import("ast.zig");
const diag = @import("../diag.zig");
const Allocator = std.mem.Allocator;
const Tag = lex.Tag;
const Token = lex.Token;
pub const Failure = struct { pos: lex.Pos, expected: []const u8, found: []const u8 };
pub const Failure = struct {
pos: lex.Pos,
expected: []const u8,
found: []const u8,
repair_candidates: []const diag.RepairCandidate = &.{},
};
pub const Result = union(enum) { ok: ast.Module, err: Failure };
@@ -41,6 +47,11 @@ const Parser = struct {
module_name: ?[]const u8 = null,
/// Struct literals are not allowed where a `{` starts a block (conditions).
no_struct: bool = false,
/// Hints are attached only at the exact token where the original parser
/// fails, preserving caller-specific expected/found and source positions.
type_advice: ?struct { at: usize, kind: diag.SourceRepairKind } = null,
borrow_advice: ?struct { at: usize, kind: diag.SourceRepairKind } = null,
speculative: bool = false,
fn peek(p: *Parser) Token {
return p.tokens[p.pos];
@@ -65,9 +76,96 @@ const Parser = struct {
fn fail(p: *Parser, t: Token, expected: []const u8) Error {
p.failure = .{ .pos = t.pos, .expected = expected, .found = if (t.tag == .eof) "end of file" else t.text };
if (p.type_advice) |a| if (a.at == p.pos) {
p.failure.?.repair_candidates = try p.sliceAdvice(a.kind);
};
return error.Syntax;
}
fn failAdvice(p: *Parser, t: Token, expected: []const u8, comptime kind: diag.SourceRepairKind) Error {
const err = p.fail(t, expected);
if (err == error.Syntax) p.failure.?.repair_candidates = kind.one();
return err;
}
/// The invalid type is already rejected. Copy only its angle-balanced
/// fragment for speculative validation; closeAngle may split >> in place.
/// Never consume or rewrite the real parser's tokens.
fn sliceAdvice(p: *Parser, kind: diag.SourceRepairKind) Error![]const diag.RepairCandidate {
var candidate = kind.candidate(&.{});
if (p.peekAt(1).tag == .lt) fragment: {
var depth: usize = 0;
var end = p.pos + 1;
var half = false;
while (end < p.tokens.len) : (end += 1) {
switch (p.tokens[end].tag) {
.lt => depth += 1,
.gt, .shr => {
const closes: usize = if (p.tokens[end].tag == .shr) 2 else 1;
if (depth <= closes) {
half = depth == 1 and closes == 2;
break;
}
depth -= closes;
},
.eof, .l_brace, .r_brace, .eq => break :fragment,
else => {},
}
}
if (end == p.tokens.len) break :fragment;
const count = end - p.pos + 1;
const tokens = try p.arena.alloc(Token, count + 1);
@memcpy(tokens[0..count], p.tokens[p.pos .. end + 1]);
if (half) {
tokens[count - 1].tag = .gt;
tokens[count - 1].text = tokens[count - 1].text[0..1];
tokens[count - 1].end.col = tokens[count - 1].pos.col + 1;
}
tokens[count] = .{ .tag = .eof, .text = "", .pos = tokens[count - 1].end, .end = tokens[count - 1].end };
var q: Parser = .{ .arena = p.arena, .tokens = tokens, .speculative = true };
const ty = q.typeExpr() catch |err| switch (err) {
error.Syntax => break :fragment,
error.OutOfMemory => return error.OutOfMemory,
};
if (q.peek().tag != .eof or ty.kind != .wrapped or !std.mem.eql(u8, ty.kind.wrapped.wrapper, "slice")) break :fragment;
// Render from an unmodified fragment: speculative parsing may have
// split its private >> tokens, so use the original token spellings.
var text: std.ArrayList(u8) = .empty;
try text.appendSlice(p.arena, if (kind == .slice_mut_type) "slice_mut" else "slice");
var previous: Tag = .ident;
for (p.tokens[p.pos + 1 .. end + 1], 0..) |token, i| {
if ((previous == .ident or previous == .int) and (token.tag == .ident or token.tag == .int)) try text.append(p.arena, ' ');
try text.appendSlice(p.arena, if (half and i == count - 2) token.text[0..1] else token.text);
previous = token.tag;
}
candidate.alternatives = try p.arena.dupe([]const u8, &.{text.items});
}
return try p.arena.dupe(diag.RepairCandidate, &.{candidate});
}
fn exprWithBorrowAdvice(p: *Parser, kind: diag.SourceRepairKind) Error!ast.Expr {
const saved = p.borrow_advice;
p.borrow_advice = .{ .at = p.pos, .kind = kind };
defer p.borrow_advice = saved;
return p.expr();
}
fn failPrimary(p: *Parser, t: Token) Error {
if (t.tag == .invalid and std.mem.eql(u8, t.text, "!")) return p.failAdvice(t, "an expression", .boolean_negation);
if (isWord(t, "zero")) return p.failAdvice(t, "an expression", .zero_storage);
if (t.tag == .amp) if (p.borrow_advice) |a| if (a.at == p.pos) {
var alternatives: []const []const u8 = &.{};
if (a.kind == .borrow_argument) {
const mutable = isWord(p.peekAt(1), "mut");
const place = p.peekAt(if (mutable) 2 else 1);
if (place.tag == .ident and !isKeyword(place.text)) alternatives = if (mutable) &.{"mut"} else &.{"ref"};
}
p.failure = .{ .pos = t.pos, .expected = "an expression", .found = t.text, .repair_candidates = try p.arena.dupe(diag.RepairCandidate, &.{a.kind.candidate(alternatives)}) };
return error.Syntax;
};
return p.fail(t, "an expression");
}
fn expect(p: *Parser, tag: Tag, what: []const u8) Error!Token {
const t = p.peek();
if (t.tag != tag) return p.fail(t, what);
@@ -261,6 +359,8 @@ const Parser = struct {
if (t.tag != .ident) return p.fail(t, "a type");
_ = p.next();
const name = if (p.peek().tag == .dot) try p.pathTail(t.text) else t.text;
if (!p.speculative and (isWord(t, "mut") or isWord(t, "ref")) and p.atWord("slice"))
p.type_advice = .{ .at = p.pos, .kind = if (isWord(t, "mut")) .slice_mut_type else .slice_ref_type };
if (p.peek().tag != .lt) return .{ .span = p.span(start), .kind = .{ .name = name } };
if (std.mem.eql(u8, name, "cap") or std.mem.eql(u8, name, "file")) {
_ = p.next();
@@ -394,7 +494,7 @@ const Parser = struct {
ty = try p.typeExpr();
}
_ = try p.expect(.eq, "`=`");
const e = try p.expr();
const e = try p.exprWithBorrowAdvice(.borrow_binding);
_ = try p.expect(.semicolon, "`;`");
return .{ .span = p.span(start), .kind = .{ .let = .{ .names = names.items, .ty = ty, .e = e, .tuple = tuple } } };
}
@@ -411,13 +511,14 @@ const Parser = struct {
if (isWord(t, "var")) {
_ = p.next();
const name = try p.ident("a name");
if (p.peek().tag == .eq) return p.failAdvice(p.peek(), "`:` and the variable's type", .annotate_var_type);
_ = try p.expect(.colon, "`:` and the variable's type");
const ty = try p.typeExpr();
_ = try p.expect(.eq, "`=`");
var init: ?ast.Expr = null;
if (p.atWord("zero")) {
_ = p.next();
} else init = try p.expr();
} else init = try p.exprWithBorrowAdvice(.borrow_binding);
_ = try p.expect(.semicolon, "`;`");
return .{ .span = p.span(start), .kind = .{ .@"var" = .{ .name = name, .ty = ty, .init = init } } };
}
@@ -783,7 +884,7 @@ const Parser = struct {
_ = p.next();
const ty = try p.typeExpr();
try p.closeAngle();
const args = try p.callArgs();
const args = try p.callArgs(true);
const callee = try p.box(ast.Expr, e);
e = .{ .span = p.span(start), .kind = .{ .call = .{ .callee = callee, .type_arg = ty, .args = args } } };
}
@@ -801,7 +902,7 @@ const Parser = struct {
.l_paren => {
if (e.kind == .variant and p.peekAt(1).tag == .r_paren)
return p.fail(p.peek(), "payload values or no parentheses for a payload-free variant");
const args = try p.callArgs();
const args = try p.callArgs(e.kind != .variant);
const callee = try p.box(ast.Expr, e);
e = .{ .span = p.span(start), .kind = .{ .call = .{ .callee = callee, .type_arg = null, .args = args } } };
},
@@ -813,6 +914,7 @@ const Parser = struct {
var hi: ?*const ast.Expr = null;
if (p.peek().tag == .dot_dot) {
_ = p.next();
if (p.peek().tag == .r_bracket) return p.failAdvice(p.peek(), "an expression", .explicit_range_end);
hi = try p.box(ast.Expr, try p.expr());
}
p.no_struct = saved;
@@ -826,14 +928,14 @@ const Parser = struct {
}
}
fn callArgs(p: *Parser) Error![]const ast.Expr {
fn callArgs(p: *Parser, borrow_arguments: bool) Error![]const ast.Expr {
_ = try p.expect(.l_paren, "`(`");
const saved = p.no_struct;
p.no_struct = false;
defer p.no_struct = saved;
var args: std.ArrayList(ast.Expr) = .empty;
while (p.peek().tag != .r_paren) {
try args.append(p.arena, try p.expr());
try args.append(p.arena, if (borrow_arguments) try p.exprWithBorrowAdvice(.borrow_argument) else try p.expr());
if (p.peek().tag != .comma) break;
_ = p.next();
}
@@ -950,7 +1052,7 @@ const Parser = struct {
};
return .{ .span = p.span(start), .kind = .{ .match_expr = try p.box(ast.Match, .{ .scrutinee = scrut, .arms = as, .span = p.span(start), .kind = kind }) } };
}
if (isKeyword(t.text) and !(isWord(t, "struct") and p.peekAt(1).tag == .dot and isWord(p.peekAt(2), "unpack"))) return p.fail(t, "an expression");
if (isKeyword(t.text) and !(isWord(t, "struct") and p.peekAt(1).tag == .dot and isWord(p.peekAt(2), "unpack"))) return p.failPrimary(t);
_ = p.next();
if (p.peek().tag == .colon_colon and p.peekAt(1).tag != .lt) {
_ = p.next();
@@ -962,7 +1064,7 @@ const Parser = struct {
}
return .{ .span = p.span(start), .kind = .{ .name = t.text } };
},
else => return p.fail(t, "an expression"),
else => return p.failPrimary(t),
}
}