diag: add factual related borrow and task locations

This commit is contained in:
dev committed 2026-10-07 19:12:58 +03:00
1 parent dbd9763713
commit 8ee0f4c2bf
27 files changed
+659 -18

No files matched your search

+101
View File
@@ -153,6 +153,107 @@ test "standard source provenance maps diagnostics to the library file" {
try std.testing.expectEqual(@as(u32, 20), d.span.?.line);
}
test "source dedup keeps the first selected conflict and never merges related positions" {
const src = verifier.test_header[0 .. verifier.test_header.len - "features []\n".len] ++
\\features [ownership]
\\fn @main() -> void
\\effects []
\\entry:
\\ %x = local.alloc u8
\\ local.zero %x
\\ %y = local.alloc u8
\\ local.zero %y
\\ %r = borrow.ref %x
\\ %q = borrow.ref %y
\\ %z = const.u8 0
\\ local.store %x, %z
\\ local.store %y, %z
\\ borrow.end %r
\\ borrow.end %q
\\ ret
\\
;
var a: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer a.deinit();
const arena = a.allocator();
const raw = try checkAir(arena, "t.air", src);
try std.testing.expectEqual(@as(usize, 2), raw.diagnostics.len);
const lines = try arena.alloc(?frontend.Span, std.mem.count(u8, src, "\n") + 1);
@memset(lines, .{ .start = .{ .line = 8, .col = 5 }, .end = .{ .line = 8, .col = 6 } });
const mapped = try checkLowered(arena, "t.aji", .{ .air = src, .annotated = src, .lines = lines, .constant_of = &.{}, .constants = &.{} });
try std.testing.expectEqual(@as(usize, 1), mapped.diagnostics.len);
const related = mapped.diagnostics[0].related_locations;
try std.testing.expectEqual(@as(usize, 1), related.len);
try std.testing.expectEqualStrings("%r", related[0].value);
try std.testing.expectEqual(raw.diagnostics[0].related_locations[0].span.?.line, related[0].air_span.?.line);
}
test "mapped E4302 keeps spawn through repeated cancelled joins and missing mappings" {
const src =
\\module t
\\air 0
\\lang 0.1
\\features [cancellation, effects, ownership, tasks]
\\fn @main() -> u8
\\effects [task.spawn, task.wait]
\\entry:
\\ %x = local.alloc u8
\\ local.zero %x
\\ %r = borrow.ref %x
\\ %s = task.scope.begin
\\ %t = task.spawn %s, @worker(%r)
\\ task.join.cancel %t, ok -> @joined, cancelled -> @retry
\\retry(%back: task<u8>):
\\ task.join.cancel %back, ok -> @joined, cancelled -> @cancelled
\\joined(%v: u8):
\\ task.scope.end %s
\\ borrow.end %r
\\ ret %v
\\cancelled(%back2: task<u8>):
\\ borrow.end %r
\\ %v2 = task.join %back2
\\ task.scope.end %s
\\ ret %v2
\\fn @worker(%p: ref<u8>) -> u8
\\effects []
\\entry:
\\ %v = load %p
\\ ret %v
\\
;
var a: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer a.deinit();
const arena = a.allocator();
const raw = try checkAir(arena, "t.air", src);
try std.testing.expectEqual(@as(usize, 1), raw.diagnostics.len);
try std.testing.expectEqualStrings("E4302", raw.diagnostics[0].code.id);
const origin = raw.diagnostics[0].related_locations[0];
try std.testing.expectEqualStrings("%back2", origin.value);
try std.testing.expectEqual(@as(u32, 12), origin.span.?.line);
try std.testing.expectEqual(@as(u32, 5), origin.span.?.col);
try std.testing.expect(origin.air_span == null);
const lines = try arena.alloc(?frontend.Span, std.mem.count(u8, src, "\n") + 1);
@memset(lines, null);
lines[20] = .{ .file = "entry.aji", .start = .{ .line = 9, .col = 5 }, .end = .{ .line = 9, .col = 6 } };
for (0..2) |i| {
if (i == 1) lines[11] = .{ .file = "dep.aji", .start = .{ .line = 3, .col = 7 }, .end = .{ .line = 3, .col = 8 } };
const mapped = try checkLowered(arena, "t.aji", .{ .air = src, .annotated = src, .lines = lines, .constant_of = &.{}, .constants = &.{} });
const d = mapped.diagnostics[0];
try std.testing.expectEqualStrings("entry.aji", d.span.?.file);
const related = d.related_locations[0];
try std.testing.expectEqualStrings("%back2", related.value);
try std.testing.expectEqual(@as(u32, 12), related.air_span.?.line);
try std.testing.expectEqual(@as(u32, 5), related.air_span.?.col);
if (i == 0) {
try std.testing.expect(related.span == null);
} else {
try std.testing.expectEqualStrings("dep.aji", related.span.?.file);
try std.testing.expectEqual(@as(u32, 3), related.span.?.line);
try std.testing.expectEqual(@as(u32, 7), related.span.?.col);
}
}
}
test "standard type diagnostics use the public source name" {
var a = std.heap.ArenaAllocator.init(std.testing.allocator);
defer a.deinit();
+73
View File
@@ -136,6 +136,16 @@ pub const Span = struct {
col: u32,
};
/// Non-binding factual context (spec 10 §2); no inferred repair or name.
pub const RelatedLocation = struct {
role: enum { conflicting_borrow, task_spawn },
value: []const u8,
/// Null only when a known AIR origin has no source mapping.
span: ?Span,
/// Original AIR position for lowered source; the file is not serialized.
air_span: ?Span = null,
};
/// Structured, code-specific payload (e.g. "value": "%17").
pub const Field = struct {
name: []const u8,
@@ -156,6 +166,7 @@ pub const Diagnostic = struct {
fields: []const Field = &.{},
/// Non-binding structured suggestions (spec 10 §3).
repair_candidates: []const []const u8 = &.{},
related_locations: []const RelatedLocation = &.{},
/// Writes the diagnostic as a single JSON object (no trailing newline).
/// Key order is fixed so output is byte-for-byte deterministic.
@@ -197,6 +208,33 @@ pub const Diagnostic = struct {
}
try s.endArray();
}
if (d.related_locations.len != 0) {
try s.objectField("related_locations");
try s.beginArray();
for (d.related_locations) |related| {
try s.beginObject();
try s.objectField("role");
try s.write(@tagName(related.role));
try s.objectField("value");
try s.write(related.value);
if (related.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);
}
if (related.air_span) |sp| {
try s.objectField("air_line");
try s.write(sp.line);
try s.objectField("air_col");
try s.write(sp.col);
}
try s.endObject();
}
try s.endArray();
}
try s.endObject();
}
};
@@ -219,6 +257,41 @@ test "writeJson is deterministic and structured" {
, w.buffered());
}
test "related locations are typed, ordered and appended after existing fields" {
var buf: [1024]u8 = undefined;
var w: std.Io.Writer = .fixed(&buf);
const d: Diagnostic = .{
.code = lookup("E2101").?,
.span = .{ .file = "main.aji", .line = 9, .col = 5 },
.fields = &.{.{ .name = "conflicts_with", .value = .{ .str = "%view_4" } }},
.message = "conflict",
.repair_candidates = &.{"example"},
.related_locations = &.{.{
.role = .conflicting_borrow,
.value = "%view_4",
.span = .{ .file = "dep.aji", .line = 3, .col = 7 },
.air_span = .{ .file = "main.aji", .line = 12, .col = 5 },
}},
};
try d.writeJson(&w);
try std.testing.expectEqualStrings(
\\{"code":"E2101","kind":"borrow.mutable_alias","severity":"error","file":"main.aji","line":9,"col":5,"conflicts_with":"%view_4","message":"conflict","repair_candidates":[{"kind":"example"}],"related_locations":[{"role":"conflicting_borrow","value":"%view_4","file":"dep.aji","line":3,"col":7,"air_line":12,"air_col":5}]}
, w.buffered());
w = .fixed(&buf);
try (Diagnostic{
.code = lookup("E4302").?,
.related_locations = &.{.{
.role = .task_spawn,
.value = "%back",
.span = null,
.air_span = .{ .file = "main.aji", .line = 17, .col = 5 },
}},
}).writeJson(&w);
try std.testing.expectEqualStrings(
\\{"code":"E4302","kind":"task.borrow_escape","severity":"error","related_locations":[{"role":"task_spawn","value":"%back","air_line":17,"air_col":5}]}
, w.buffered());
}
test "registry mirrors docs/reference/error-codes.md" {
const md = @embedFile("error_codes_md");
var seen: usize = 0;
+41
View File
@@ -74,6 +74,16 @@ pub fn syntaxDiagnostic(arena: std.mem.Allocator, file: []const u8, f: parse.Fai
/// location stays as `air_line`/`air_col` metadata (spec 15 §10).
pub fn mapDiagnostic(arena: std.mem.Allocator, d: diag.Diagnostic, file: []const u8, lines: []const ?Span) std.mem.Allocator.Error!diag.Diagnostic {
var out = d;
if (d.related_locations.len != 0) {
const related = try arena.dupe(diag.RelatedLocation, d.related_locations);
for (related) |*r| {
const origin = r.span orelse continue;
r.air_span = origin;
const source: ?Span = if (origin.line >= 1 and origin.line <= lines.len) lines[origin.line - 1] else null;
r.span = if (source) |s| .{ .file = s.file orelse file, .line = s.start.line, .col = s.start.col } else null;
}
out.related_locations = related;
}
const sp = d.span orelse return out;
const fields = try arena.alloc(diag.Field, d.fields.len + 2);
@memcpy(fields[0..d.fields.len], d.fields);
@@ -92,6 +102,37 @@ test {
_ = format;
}
test "related AIR positions map independently with no guessed source fallback" {
var a: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer a.deinit();
const lines: []const ?Span = &.{
.{ .file = "entry.aji", .start = .{ .line = 8, .col = 9 }, .end = .{ .line = 8, .col = 10 } },
.{ .file = "dep.aji", .start = .{ .line = 3, .col = 5 }, .end = .{ .line = 3, .col = 6 } },
null,
};
const mapped = try mapDiagnostic(a.allocator(), .{
.code = diag.lookup("E2101").?,
.span = .{ .file = "lowered.air", .line = 1, .col = 5 },
.related_locations = &.{
.{ .role = .conflicting_borrow, .value = "%a", .span = .{ .file = "lowered.air", .line = 2, .col = 7 } },
.{ .role = .task_spawn, .value = "%b", .span = .{ .file = "lowered.air", .line = 3, .col = 5 } },
.{ .role = .task_spawn, .value = "%c", .span = .{ .file = "lowered.air", .line = 99, .col = 5 } },
},
}, "fallback.aji", lines);
try std.testing.expectEqualStrings("entry.aji", mapped.span.?.file);
try std.testing.expectEqual(@as(u32, 8), mapped.span.?.line);
const located = mapped.related_locations[0];
try std.testing.expectEqualStrings("dep.aji", located.span.?.file);
try std.testing.expectEqual(@as(u32, 3), located.span.?.line);
try std.testing.expectEqual(@as(u32, 5), located.span.?.col);
try std.testing.expectEqual(@as(u32, 2), located.air_span.?.line);
try std.testing.expectEqual(@as(u32, 7), located.air_span.?.col);
for (mapped.related_locations[1..], [_]u32{ 3, 99 }) |related, line| {
try std.testing.expect(related.span == null);
try std.testing.expectEqual(line, related.air_span.?.line);
}
}
pub const Size = struct { bytes: usize, lines: usize };
/// AIR size with every byte-string materialization (the instructions from
+12
View File
@@ -38,12 +38,24 @@ pub const Context = struct {
span: air.Span,
message: []const u8,
fields: []const diag.Field,
) std.mem.Allocator.Error!void {
return c.reportRelated(id, span, message, fields, &.{});
}
pub fn reportRelated(
c: *Context,
id: []const u8,
span: air.Span,
message: []const u8,
fields: []const diag.Field,
related: []const diag.RelatedLocation,
) std.mem.Allocator.Error!void {
try c.diags.append(c.arena, .{
.code = diag.lookup(id).?,
.span = .{ .file = c.file, .line = span.line, .col = span.col },
.message = message,
.fields = try c.arena.dupe(diag.Field, fields),
.related_locations = try c.arena.dupe(diag.RelatedLocation, related),
});
}
+32 -6
View File
@@ -11,6 +11,7 @@ const std = @import("std");
const air = @import("../air.zig");
const verifier = @import("../verifier.zig");
const ssa = @import("ssa.zig");
const diag = @import("../diag.zig");
const Context = verifier.Context;
const ValueId = air.ValueId;
@@ -29,7 +30,15 @@ const Seg = union(enum) {
const Mode = enum { shared, exclusive };
const Loan = struct { task: ValueId, borrow: ValueId, root: ValueId, path: []const Seg, mode: Mode };
const Loan = struct {
task: ValueId,
borrow: ValueId,
root: ValueId,
path: []const Seg,
mode: Mode,
/// Diagnostic provenance only; never participates in borrow/liveness state.
spawn: air.Span,
};
/// Why a resource is no longer live (spec 06 §6.3).
const Dead = enum { none, closed, moved };
@@ -85,14 +94,27 @@ const Walker = struct {
}
fn report(w: *Walker, code: []const u8, message: []const u8, borrow: ValueId, extra: ?struct { []const u8, ValueId }) !void {
return w.reportWithOrigin(code, message, borrow, extra, null);
}
fn reportWithOrigin(w: *Walker, code: []const u8, message: []const u8, borrow: ValueId, extra: ?struct { []const u8, ValueId }, spawn: ?air.Span) !void {
if (extra) |e| {
try w.c.report(code, w.span, message, &.{
var related: [1]diag.RelatedLocation = undefined;
const context: []const diag.RelatedLocation = if ((std.mem.eql(u8, code, "E2101") or std.mem.eql(u8, code, "E2104")) and std.mem.eql(u8, e[0], "conflicts_with")) blk: {
const sp = w.f.values[e[1]].span;
related[0] = .{ .role = .conflicting_borrow, .value = try w.name(e[1]), .span = .{ .file = w.c.file, .line = sp.line, .col = sp.col } };
break :blk &related;
} else if (spawn) |sp| blk: {
related[0] = .{ .role = .task_spawn, .value = try w.name(e[1]), .span = .{ .file = w.c.file, .line = sp.line, .col = sp.col } };
break :blk &related;
} else &.{};
try w.c.reportRelated(code, w.span, message, &.{
.{ .name = "function", .value = .{ .str = w.f.name } },
.{ .name = "block", .value = .{ .str = w.f.blocks[w.block].name } },
.{ .name = "inst", .value = .{ .int = w.index } },
.{ .name = "borrow", .value = .{ .str = try w.name(borrow) } },
.{ .name = e[0], .value = .{ .str = try w.name(e[1]) } },
});
}, context);
} else {
try w.c.report(code, w.span, message, &.{
.{ .name = "function", .value = .{ .str = w.f.name } },
@@ -411,7 +433,7 @@ fn step(w: *Walker, inst: air.Inst) !void {
// Ended even when rejected, so one mistake yields one diagnostic.
defer w.live[v] = false;
for (w.loans.items) |l| if (w.live[l.task] and (l.borrow == v or w.isAncestor(v, l.borrow))) {
return w.report("E4302", "borrow ended while it is lent to a live task", v, .{ "task", l.task });
return w.reportWithOrigin("E4302", "borrow ended while it is lent to a live task", v, .{ "task", l.task }, l.spawn);
};
for (w.live, 0..) |is_live, g| if (is_live and w.guard_parent[g] != null and w.isAncestor(v, w.guard_parent[g].?)) {
return w.report("E2102", "mutex borrow ended while a guard locked through it is live", v, .{ "guard", @intCast(g) });
@@ -493,7 +515,7 @@ fn step(w: *Walker, inst: air.Inst) !void {
const ai = w.info[a].?;
// The loan must not conflict with live borrows or loans.
try w.accessCode(ai.root, ai.path, ai.mode, a, a, "E4101", "lending a borrow that conflicts with a live borrow");
try w.loans.append(w.c.arena, .{ .task = t, .borrow = a, .root = ai.root, .path = ai.path, .mode = ai.mode });
try w.loans.append(w.c.arena, .{ .task = t, .borrow = a, .root = ai.root, .path = ai.path, .mode = ai.mode, .spawn = inst.span });
} else if (w.isResource(a)) try w.consume(a, .moved);
}
w.live[t] = true;
@@ -557,7 +579,11 @@ fn step(w: *Walker, inst: air.Inst) !void {
const n = w.loans.items.len;
for (0..n) |i| {
const l = w.loans.items[i];
if (l.task == t) try w.loans.append(w.c.arena, .{ .task = back, .borrow = l.borrow, .root = l.root, .path = l.path, .mode = l.mode });
if (l.task == t) {
var transferred = l;
transferred.task = back;
try w.loans.append(w.c.arena, transferred);
}
}
try w.consume(t, .closed);
},