cli: map block diagnostics to their source constructs

This commit is contained in:
dev committed 2026-10-07 21:45:57 +03:00
1 parent 1495650587
commit 1a80c42289
30 files changed
+555 -27

No files matched your search

+1
View File
@@ -26,6 +26,7 @@ jobs:
- run: python3 tests/hosted/source_format.py
- run: python3 tests/hosted/source_diagnostic_reasons.py
- run: python3 tests/hosted/related_locations.py
- run: python3 tests/hosted/source_lifetimes.py
- run: python3 tests/hosted/examples.py --stress 200
- run: python3 tests/hosted/source_static_functions.py
- run: python3 tests/hosted/source_linear.py
+1
View File
@@ -22,6 +22,7 @@ python3 tests/hosted/source_borrow_returns.py # explicit origins, retained views
python3 tests/hosted/source_format.py # formatter CLI, comments, idempotence and public-corpus AIR fidelity
python3 tests/hosted/source_diagnostic_reasons.py # stable E7006 categories and CLI/package provenance
python3 tests/hosted/related_locations.py # factual conflict/spawn positions, source mapping and package provenance
python3 tests/hosted/source_lifetimes.py # AIR rejection twins and exact lifetime/join diagnostic positions
python3 tests/hosted/examples.py --stress 200 # all examples/packages, wire bytes, partial I/O and source/AIR schedules
python3 tests/hosted/source_static_functions.py # explicit operations, effects, nominal policy identity and workers
python3 tests/hosted/source_linear.py # whole-value owners, canonical AIR and CLI errors
+11 -1
View File
@@ -136,7 +136,7 @@ Lowering layers (P6A-3/4), each with accepted (golden AIR), rejected (`E7xxx`) a
| P6-4 | done (RFC 0022 Implemented) | Type checking and monomorphized generics with structural constraints (`Copy`, `Send`, `Share`, `Freeze`, `Local`) | P6-3 | `src/frontend/generics.zig`, spec 15 §15 | generic code instantiates deterministically; constraint violations diagnosed |
| P6-5 | todo | Lowering to AIR: control flow, `?`, `defer` cleanup edges, borrow blocks, task scopes | P6-4 | `src/frontend/lower.zig` | lowered AIR verifies; lowering is a pure function (same input ⇒ same AIR bytes) |
| P6-6 | todo | Contracts: `requires`/`ensures`/invariants → contract table; status classification | P6-5 | frontend + verifier | each contract reported as PROVEN_STATICALLY / CHECKED_AT_RUNTIME / ASSUMED_UNSAFE / UNPROVEN |
| P6-7 | todo | Source spans in diagnostics for verifier errors on lowered AIR | P6-5 | `src/diag.zig`, lowering | every conformance reject test has a source-level twin with the same code |
| P6-7 | doing | Source spans in diagnostics for verifier errors on lowered AIR | P6-5 | `src/diag.zig`, lowering | every conformance reject test has a source-level twin with the same code |
| P6-8 | done | Formatter for implemented source syntax | P6-2 | `aji fmt`, spec 15 §11 | token/comment/declaration preservation; idempotence, identical AIR and CLI write/check tests |
| P6-9 | done | Port reference programs and examples to `.aji` | P6-5 | `tests/conformance/source/programs/`, `examples/` | all five source/AIR reference pairs and every example source/package pass |
| P6-11 | done (implementation; RFC 0036 Proposed) | Source functions/calls returning borrows with explicit `from` origin; Q-034 | P6-3/4 | spec 15, binding/call/return lowering, Quick Reference and source/AIR conformance | origin/lifetime and temporary-end rules specified; valid/rejected returned views use existing verifier/interpreter semantics |
@@ -204,3 +204,13 @@ The implementation follow-up from P6-9 is resolved: nominal values and `ref`/`mu
Existing borrow/load/end and whole-value ownership rules remain authoritative: reading a Copy field succeeds, conflicting borrows reject E2101, and projecting a linear field rejects E1001. Missing struct fields now produce E7002 with `type` and `field`, replacing the misleading array/slice E7005. Enum field access and type mismatches retain E7005. A struct length field does not prove slice bounds: the out-of-bounds regression still traps T0008. This restores specified source behavior without changing accepted AIR semantics or runtime state.
Validation: full conformance passes 1,201/1,201, including all 15 new cases; the new cases also pass with collection before every instruction. Unit tests, generic CLI integration (32 checks), formatting checks and coverage (120/120) pass. The formatter passes 3,437 checks over 916 public files, with 582 identical successful AIR outputs. Imported generic fields preserve declared types, source locations and source/AIR run-record parity. Across 1,233 original public files, all 2,134 check/lower results agree after normalizing absolute versus relative diagnostic file paths; all 570 successful source lowerings are byte-identical. Independent read-only Claude review found no remaining issues. P6-5 remains open for its other source-layer work.
## P6-7 block positions and lifetime twins (2026-10-07)
Generated block labels now carry the explicit source span of their creating construct, including branch joins, loop headers/exits/steps and short-circuit expressions. E3002 at a resource-state join therefore identifies the source construct instead of falling back to 1:1. Annotations expose label positions; canonical AIR and verifier/runtime rules are unchanged. Existing source-location deduplication now preserves errors on distinct constructs. The borrowed-buffer-element fixture consequently expects both allocation and destruction diagnostics.
Eight Phase 2 AIR rejection twins and five successful source runs cover owner/region/resource lifetimes and explicit release. Eleven further rejects cover every join form and distinct diagnostics. The CI CLI suite checks exact primary/AIR positions, label annotations, code parity and imported generic provenance. Existing ownership and borrow invariants, explicit cleanup and deterministic execution remain authoritative; no spec, diagnostic code, bundle or evaluation input changes. P6-7 remains open for the remaining twins.
Validation: unit tests and full conformance pass, 1,225/1,225; all 24 new cases pass with per-instruction collection. Lifetime CLI checks pass 188 assertions, related-location checks 301, coverage 120/120 and formatting checks pass. The formatter checks 940 public files with 606 identical AIR outputs. Across 916 original public sources, check outcomes and all 421 accepted canonical AIR outputs are unchanged; four diagnostic outputs gain source positions, one also recovering a previously suppressed error. Independent read-only Claude review found no remaining issues.
Next P6-2 follow-up: capture full parser spans after parsing block/unary operands. Current annotated ranges can end before an `if` starts; this is separate from the primary-position correction above.
+27 -25
View File
@@ -156,7 +156,7 @@ pub const Output = struct {
/// `lines[i]` is the source span of AIR line `i + 1`, if any.
lines: []const ?Span,
/// The same AIR with `; line:col-line:col` comments before each
/// instruction (not canonical; `aji lower --annotate`).
/// instruction and block label (not canonical; `aji lower --annotate`).
annotated: []const u8,
/// Byte-string materializations, for the normalized size metric
/// (spec 15 §11): `constant_of[i]` is 0, or `k` when AIR line `i + 1`
@@ -193,6 +193,8 @@ const Inst = struct { text: []const u8, span: ?Span, constant: u32 = 0 };
const Block = struct {
name: []const u8,
/// The source construct that creates this block (including joins).
span: Span,
params: std.ArrayList(Param) = .empty,
insts: std.ArrayList(Inst) = .empty,
terminated: bool = false,
@@ -438,7 +440,7 @@ const Lowerer = struct {
try l.out.appendSlice(l.arena, text);
try l.out.append(l.arena, '\n');
try l.lines.append(l.arena, span);
if (span) |s| if (std.mem.startsWith(u8, text, " ")) {
if (span) |s| if (std.mem.startsWith(u8, text, " ") or std.mem.endsWith(u8, text, ":")) {
if (s.file) |file| {
try l.annotated.appendSlice(l.arena, try l.fmt(" ; {s}:{d}:{d}-{d}:{d}\n", .{ file, s.start.line, s.start.col, s.end.line, s.end.col }));
} else try l.annotated.appendSlice(l.arena, try l.fmt(" ; {d}:{d}-{d}:{d}\n", .{ s.start.line, s.start.col, s.end.line, s.end.col }));
@@ -759,7 +761,7 @@ const Lowerer = struct {
try header.appendSlice(l.arena, try l.fmt(") -> {s}", .{l.tyText(sig.ret)}));
if (f.from) |origin| try header.appendSlice(l.arena, try l.fmt(" from %{s}", .{origin}));
_ = try l.newBlock("entry");
_ = try l.newBlock("entry", f.span);
l.cur = 0;
const tail = try l.blockBodyWant(f.body, sig.ret);
if (l.cur != null) {
@@ -798,7 +800,7 @@ const Lowerer = struct {
try head.append(l.arena, ')');
}
try head.appendSlice(l.arena, ":");
try l.line(head.items, null);
try l.line(head.items, b.span);
for (b.insts.items) |inst| try l.lineTagged(try l.fmt(" {s}", .{inst.text}), inst.span, inst.constant);
}
}
@@ -821,12 +823,12 @@ const Lowerer = struct {
}
}
fn newBlock(l: *Lowerer, kind: []const u8) Error!usize {
fn newBlock(l: *Lowerer, kind: []const u8, span: Span) Error!usize {
const name = if (l.blocks.items.len == 0) kind else blk: {
l.counter += 1;
break :blk try l.fmt("{s}_{d}", .{ kind, l.counter });
};
try l.blocks.append(l.arena, .{ .name = name });
try l.blocks.append(l.arena, .{ .name = name, .span = span });
return l.blocks.items.len - 1;
}
@@ -1234,9 +1236,9 @@ const Lowerer = struct {
const lp_ast: LoopAst = .{ .cond = cond, .body = body, .step = if (step) |st| st.name else null };
const vars = try l.carriedLoop(depth, span, lp_ast);
const exit_vars = try l.carriedLive(depth, span, .{ .loop = lp_ast });
const header = try l.newBlock(if (cond == null) "loop" else "while");
const exit = try l.newBlock("after");
const cont = if (step != null) try l.newBlock("step") else header;
const header = try l.newBlock(if (cond == null) "loop" else "while", span);
const exit = try l.newBlock("after", span);
const cont = if (step != null) try l.newBlock("step", span) else header;
try l.joinParams(header, vars);
try l.joinParams(exit, exit_vars);
if (step != null) try l.joinParams(cont, vars);
@@ -1247,7 +1249,7 @@ const Lowerer = struct {
if (cond) |c| {
const cv = try l.expr(c, .bool);
try l.checkTy(c.span, cv.ty, .bool);
const body_b = try l.newBlock("body");
const body_b = try l.newBlock("body", body.span);
try l.term(try l.fmt("cbr %{s}, @{s}(), @{s}{s}", .{ cv.name, l.blocks.items[body_b].name, l.blocks.items[exit].name, try l.argsOf(exit_vars, null) }), c.span);
l.cur = body_b;
}
@@ -1630,8 +1632,8 @@ const Lowerer = struct {
const lv = try l.expr(a, .bool);
try l.checkTy(a.span, lv.ty, .bool);
const short = try l.def("c", .bool, if (op == .@"and") "const.bool false" else "const.bool true", e.span);
const rhs_b = try l.newBlock(if (op == .@"and") "and_rhs" else "or_rhs");
const join = try l.newBlock(if (op == .@"and") "and_end" else "or_end");
const rhs_b = try l.newBlock(if (op == .@"and") "and_rhs" else "or_rhs", b.span);
const join = try l.newBlock(if (op == .@"and") "and_end" else "or_end", e.span);
const rname = try l.freshName(if (op == .@"and") "and" else "or");
try l.blocks.items[join].params.append(l.arena, .{ .name = rname, .ty = .bool });
const jn = l.blocks.items[join].name;
@@ -1893,7 +1895,7 @@ const Lowerer = struct {
/// Joins branches that reach the end: one block with a parameter for
/// the result (if any) and one per carried variable (spec 15 §4).
fn mergeArms(l: *Lowerer, _: Span, what: []const u8, arms: []const ArmEnd, vars: []const usize, before: []const []const u8, join_kind: []const u8) Error!Value {
fn mergeArms(l: *Lowerer, span: Span, what: []const u8, arms: []const ArmEnd, vars: []const usize, before: []const []const u8, join_kind: []const u8) Error!Value {
l.restore(before);
var result_ty: ?Ty = null;
for (arms) |a| if (a.block != null) {
@@ -1907,7 +1909,7 @@ const Lowerer = struct {
l.cur = null;
return .{ .name = "", .ty = .never };
}
const join = try l.newBlock(join_kind);
const join = try l.newBlock(join_kind, span);
const has_value = result_ty.? != .void;
var result_name: []const u8 = "";
if (has_value) {
@@ -1958,7 +1960,7 @@ const Lowerer = struct {
} else return l.fail("E7002", arm.pattern.span, "no such variant", &.{ .{ .name = "enum", .value = d.display_name orelse d.name }, .{ .name = "variant", .value = c.name } });
for (m.arms[0..i]) |prev| if (std.mem.eql(u8, prev.pattern.kind.ctor.name, c.name)) return l.invalid(.invalid_match, arm.pattern.span, "variant matched twice", &.{.{ .name = "variant", .value = c.name }});
if (c.binds.len != vs[vi].payload.len) return l.fail("E7005", arm.pattern.span, "the pattern binds a different number of payload values", &.{ .{ .name = "variant", .value = c.name }, .{ .name = "expected", .value = try l.fmt("{d}", .{vs[vi].payload.len}) } });
blk.* = try l.newBlock(try l.fmt("case_{s}", .{c.name}));
blk.* = try l.newBlock(try l.fmt("case_{s}", .{c.name}), arm.body.span);
for (vs[vi].payload, c.binds) |pt, bn| {
const pname = try l.freshName(if (std.mem.eql(u8, bn, "_")) "unused" else bn);
try l.blocks.items[blk.*].params.append(l.arena, .{ .name = pname, .ty = try l.typeOf(pt) });
@@ -2000,7 +2002,7 @@ const Lowerer = struct {
.wildcard => {
if (default != null) return l.invalid(.invalid_match, arm.pattern.span, "`_` given twice", &.{});
default = i;
blk.* = try l.newBlock("case_default");
blk.* = try l.newBlock("case_default", arm.body.span);
},
.int => |text| {
const neg = text[0] == '-';
@@ -2013,7 +2015,7 @@ const Lowerer = struct {
const bits: u128 = if (neg) (0 -% mag) else mag;
for (seen.items) |prev| if (prev == bits) return l.invalid(.invalid_match, arm.pattern.span, "integer matched twice", &.{.{ .name = "value", .value = text }});
try seen.append(l.arena, bits);
blk.* = try l.newBlock("case");
blk.* = try l.newBlock("case", arm.body.span);
// AIR uses canonical decimal literals without source
// suffixes/separators. Validate range before formatting
// rather than truncating a pattern's bit representation.
@@ -2052,7 +2054,7 @@ const Lowerer = struct {
if (b.variantIndex(c.name) == null) return l.fail("E7002", arm.pattern.span, "no such variant", &.{ .{ .name = "enum", .value = name }, .{ .name = "variant", .value = c.name } });
if (c.binds.len != 0) return l.fail("E7005", arm.pattern.span, "built-in error variants have no payload", &.{});
for (m.arms[0..i]) |prev| if (std.mem.eql(u8, prev.pattern.kind.ctor.name, c.name)) return l.invalid(.invalid_match, arm.pattern.span, "variant matched twice", &.{.{ .name = "variant", .value = c.name }});
blk.* = try l.newBlock(try l.fmt("case_{s}", .{c.name}));
blk.* = try l.newBlock(try l.fmt("case_{s}", .{c.name}), arm.body.span);
try head.appendSlice(l.arena, try l.fmt(", {s} -> @{s}", .{ c.name, l.blocks.items[blk.*].name }));
}
var missing: std.ArrayList(u8) = .empty;
@@ -2418,7 +2420,7 @@ const Lowerer = struct {
for (0..@intCast(v.ty.array.len)) |_| try components.append(l.arena, v.ty.array.elem);
} else return l.fail("E7005", e.span, "unpack needs the corresponding struct or array", &.{});
if (names.len != components.items.len or names.len > 64) return l.fail("E7005", s.span, "unpack must bind every component", &.{});
const next = try l.newBlock("unpacked");
const next = try l.newBlock("unpacked", s.span);
for (names, components.items, 0..) |n, t, i| {
for (names[0..i]) |previous| if (!std.mem.eql(u8, n, "_") and std.mem.eql(u8, n, previous)) return l.invalid(.invalid_unpack, s.span, "duplicate unpack binding", &.{});
const pn = try l.freshName(if (std.mem.eql(u8, n, "_")) "unused" else n);
@@ -2832,10 +2834,10 @@ const Lowerer = struct {
const depth = l.bindings.items.len;
const vars = try l.carriedLive(depth, s.span, .{ .lock = .{ body, cancelled } });
const before = try l.snapshot();
const locked = try l.newBlock("locked");
const locked = try l.newBlock("locked", s.span);
const guard = try l.freshName("guard");
try l.blocks.items[locked].params.append(l.arena, .{ .name = guard, .ty = try l.wrap(.guard, elem) });
const canc = try l.newBlock("lock_cancelled");
const canc = try l.newBlock("lock_cancelled", cancelled.span);
try l.term(try l.fmt("mutex.lock %{s}, ok -> @{s}, cancelled -> @{s}", .{ mr.name, l.blocks.items[locked].name, l.blocks.items[canc].name }), s.span);
var ends: std.ArrayList(ArmEnd) = .empty;
@@ -2945,7 +2947,7 @@ const Lowerer = struct {
var text: std.ArrayList(u8) = .empty;
try text.appendSlice(l.arena, "select ");
for (edges.items) |*ed| {
ed.block = try l.newBlock(ed.role);
ed.block = try l.newBlock(ed.role, s.span);
for (ed.params) |pt| try l.blocks.items[ed.block].params.append(l.arena, .{ .name = try l.freshName(ed.role), .ty = pt });
for (ed.values) |vi| try l.blocks.items[ed.block].params.append(l.arena, .{ .name = try l.freshName(ed.role), .ty = values.items[vi].v.ty });
}
@@ -3343,7 +3345,7 @@ const Lowerer = struct {
var text: std.ArrayList(u8) = .empty;
try text.appendSlice(l.arena, f.text);
for (f.outcomes, blocks) |o, *b| {
b.* = try l.newBlock(o.role);
b.* = try l.newBlock(o.role, span);
for (o.params) |pt| {
const name = try l.freshName(o.role);
try l.blocks.items[b.*].params.append(l.arena, .{ .name = name, .ty = pt });
@@ -3458,8 +3460,8 @@ const Lowerer = struct {
try l.checkTy(x.cond.span, cv.ty, .bool);
const depth = l.bindings.items.len;
const vars = try l.carriedLive(depth, span, .{ .@"if" = x });
const then_b = try l.newBlock("then");
const else_b = try l.newBlock("else");
const then_b = try l.newBlock("then", x.then.span);
const else_b = try l.newBlock("else", span);
try l.term(try l.fmt("cbr %{s}, @{s}(), @{s}()", .{ cv.name, l.blocks.items[then_b].name, l.blocks.items[else_b].name }), x.cond.span);
const before = try l.snapshot();
var ends: [2]ArmEnd = undefined;
@@ -1,4 +1,5 @@
// expect: reject E1001
// Allocation and destruction each reject the borrow element at their own source construct.
// expect: reject E1001 E1001
// grant: heap=mem.alloc:128
// phase: 6
// spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17
@@ -0,0 +1,12 @@
// expect: reject E3002
// phase: 6
// spec: docs/spec/06-resources-and-errors.md
module test.source_and_join
fn close_file(file: file<read>) -> bool effects [fs.read] { fs.close(move file) or trap; true }
fn test(src: cap<fs.read>, condition: bool) -> void effects [fs.read] {
let file = fs.open_read(src, b"/input") or trap;
let ignored = condition and close_file(move file); // diagnostic here: condition
trap;
}
fn main(src: cap<fs.read>) -> void effects [fs.read] { test(src, true); }
@@ -0,0 +1,20 @@
// expect: run
// result: 42
// grant: src=fs.read:/
// vfs: /input=*
// phase: 6
// spec: docs/spec/15-source-language.md
module test.source_balanced_close
fn close_on_both_paths(src: cap<fs.read>, first: bool) -> u64 effects [fs.read] {
let file = fs.open_read(src, b"/input") or trap;
if first {
fs.close(move file) or trap;
} else {
fs.close(move file) or trap;
}
21u64
}
fn main(src: cap<fs.read>) -> u64 effects [fs.read] {
close_on_both_paths(src, true) + close_on_both_paths(src, false)
}
@@ -0,0 +1,15 @@
// expect: run
// result: 42
// grant: src=fs.read:/
// vfs: /input=*
// phase: 6
// spec: docs/spec/15-source-language.md
module test.source_close_outcomes
fn main(src: cap<fs.read>) -> u64 effects [fs.read] {
let file = fs.open_read(src, b"/input") or trap;
match fs.close(move file) {
ok => { 42u64 }
err(error) => { 0u64 }
}
}
@@ -0,0 +1,24 @@
// expect: reject E3002 E3002
// phase: 6
// spec: docs/spec/15-source-language.md
module test.source_distinct_joins
fn first(src: cap<fs.read>, close_it: bool) -> void effects [fs.read] {
let file = fs.open_read(src, b"/input") or trap;
if close_it { // diagnostic here
fs.close(move file) or trap;
}
trap;
}
fn second(src: cap<fs.read>, close_it: bool) -> void effects [fs.read] {
let file = fs.open_read(src, b"/input") or trap;
if close_it { // diagnostic here
fs.close(move file) or trap;
}
trap;
}
fn main(src: cap<fs.read>) -> void effects [fs.read] {
first(src, true);
second(src, false);
}
@@ -0,0 +1,15 @@
// expect: reject E3002
// phase: 6
// spec: docs/spec/06-resources-and-errors.md
module test.source_enum_match_join
enum Choice { Close, Keep }
fn test(src: cap<fs.read>, condition: Choice) -> void effects [fs.read] {
let file = fs.open_read(src, b"/input") or trap;
match condition { // diagnostic here
Choice::Close => { fs.close(move file) or trap; }
Choice::Keep => {}
}
trap;
}
fn main(src: cap<fs.read>) -> void effects [fs.read] { test(src, Choice::Keep); }
@@ -0,0 +1,18 @@
// expect: run
// result: 42
// grant: src=fs.read:/
// vfs: /input=*
// phase: 6
// spec: docs/spec/15-source-language.md
module test.source_file_release
fn main(src: cap<fs.read>) -> u64 effects [fs.read] {
let file = fs.open_read(src, b"/input") or trap;
var bytes: [u8; 1] = zero;
{
ref handle = file;
}
assert(fs.read(file, mut bytes) or trap == 1usize);
fs.close(move file) or trap;
bytes[0] as u64
}
@@ -0,0 +1,16 @@
// expect: reject E3002
// phase: 6
// spec: docs/spec/06-resources-and-errors.md
module test.source_for_step
fn test(src: cap<fs.read>, condition: bool) -> void effects [fs.read] {
let file = fs.open_read(src, b"/input") or trap;
for i in 0usize..2usize { // diagnostic here
if condition {
fs.close(move file) or trap;
continue;
}
}
trap;
}
fn main(src: cap<fs.read>) -> void effects [fs.read] { test(src, true); }
@@ -0,0 +1,18 @@
// expect: run
// result: 42
// grant: heap=mem.alloc:8
// phase: 6
// spec: docs/spec/15-source-language.md
module test.source_heap_release
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
let owner = own.new(40u64, heap) or trap;
var result: u64 = 0;
{
mut view = owner;
*view = *view + 2;
result = *view;
}
own.free(move owner);
result
}
@@ -0,0 +1,14 @@
// expect: reject E3002
// phase: 6
// spec: docs/spec/06-resources-and-errors.md
module test.source_integer_match_join
fn test(src: cap<fs.read>, condition: u64) -> void effects [fs.read] {
let file = fs.open_read(src, b"/input") or trap;
match condition { // diagnostic here
0 => { fs.close(move file) or trap; }
_ => {}
}
trap;
}
fn main(src: cap<fs.read>) -> void effects [fs.read] { test(src, 0u64); }
@@ -0,0 +1,12 @@
// expect: reject E3002
// phase: 6
// spec: docs/spec/03-memory-model.md
module test.source_lock_join
fn main(heap: cap<mem.alloc>) -> void effects [mem.alloc, task.wait] {
let owner = own.new(1u64, heap) or trap;
let mutex_owner = mutex.make(1u64);
lock ref mutex_owner as data { // diagnostic here
own.free(move owner);
} cancelled {}
trap;
}
@@ -0,0 +1,16 @@
// expect: reject E3002
// phase: 6
// spec: docs/spec/06-resources-and-errors.md
module test.source_loop_exit
fn test(src: cap<fs.read>, condition: bool) -> void effects [fs.read] {
let file = fs.open_read(src, b"/input") or trap;
loop { // diagnostic here
if condition {
fs.close(move file) or trap;
break;
} else { break; }
}
trap;
}
fn main(src: cap<fs.read>) -> void effects [fs.read] { test(src, true); }
@@ -0,0 +1,12 @@
// expect: reject E3002
// phase: 6
// spec: docs/spec/06-resources-and-errors.md
module test.source_or_join
fn close_file(file: file<read>) -> bool effects [fs.read] { fs.close(move file) or trap; true }
fn test(src: cap<fs.read>, condition: bool) -> void effects [fs.read] {
let file = fs.open_read(src, b"/input") or trap;
let ignored = condition or close_file(move file); // diagnostic here: condition
trap;
}
fn main(src: cap<fs.read>) -> void effects [fs.read] { test(src, true); }
@@ -0,0 +1,15 @@
// expect: reject E3002
// phase: 6
// spec: docs/spec/06-resources-and-errors.md
module test.source_outcome_match_join
fn test(src: cap<fs.read>, condition: bool) -> void effects [fs.read] {
let file = fs.open_read(src, b"/input") or trap;
var bytes: [u8; 1] = zero;
match fs.read(file, mut bytes) { // diagnostic here
ok(count) => { fs.close(move file) or trap; }
err(error) => {}
}
trap;
}
fn main(src: cap<fs.read>) -> void effects [fs.read] { test(src, true); }
@@ -0,0 +1,11 @@
// expect: reject E2101
// phase: 6
// spec: docs/spec/03-memory-model.md
// AIR twin: phase2/reject/own_free_while_borrowed.air
module test.source_own_free_while_borrowed
fn main(heap: cap<mem.alloc>) -> void effects [mem.alloc] {
let owner = own.new(1u64, heap) or trap;
ref view = owner;
own.free(move owner); // diagnostic here
}
@@ -0,0 +1,11 @@
// expect: reject E3001
// phase: 6
// spec: docs/spec/03-memory-model.md
// AIR twin: phase2/reject/own_use_after_free.air
module test.source_own_use_after_free
fn main(heap: cap<mem.alloc>) -> void effects [mem.alloc] {
let owner = own.new(1u64, heap) or trap;
own.free(move owner);
ref view = owner; // diagnostic here
}
@@ -0,0 +1,14 @@
// expect: reject E2104
// phase: 6
// spec: docs/spec/03-memory-model.md
// AIR twin: phase2/reject/region_destroy_with_live_reference.air
module test.source_region_destroy_with_live_reference
fn main(heap: cap<mem.alloc>) -> void effects [mem.alloc] {
let region_owner = region.create(heap) or trap;
ref arena = region_owner;
{
let item = region.new(arena, 1u64) or trap;
}
region.destroy(move region_owner); // diagnostic here
}
@@ -0,0 +1,24 @@
// expect: run
// result: 42
// grant: heap=mem.alloc:8
// phase: 6
// spec: docs/spec/15-source-language.md
module test.source_region_generations
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
let region_owner = region.create(heap) or trap;
var result: u64 = 0;
{
ref arena = region_owner;
let item = region.new(arena, 20u64) or trap;
result = *item;
}
region.reset(region_owner);
{
ref arena = region_owner;
let item = region.new(arena, 22u64) or trap;
result = result + *item;
}
region.destroy(move region_owner);
result
}
@@ -0,0 +1,15 @@
// expect: reject E2104
// phase: 6
// spec: docs/spec/03-memory-model.md
// AIR twin: phase2/reject/region_reset_with_live_reference.air
module test.source_region_reset_with_live_reference
fn main(heap: cap<mem.alloc>) -> void effects [mem.alloc] {
let region_owner = region.create(heap) or trap;
{
ref arena = region_owner;
let item = region.new(arena, 1u64) or trap;
region.reset(region_owner); // diagnostic here
}
region.destroy(move region_owner);
}
@@ -0,0 +1,15 @@
// expect: reject E2002
// phase: 6
// spec: docs/spec/06-resources-and-errors.md
// AIR twin: phase2/reject/resource_close_twice_after_error.air
module test.source_resource_close_twice_after_error
fn main(src: cap<fs.read>) -> void effects [fs.read] {
let file = fs.open_read(src, b"/input") or trap;
match fs.close(move file) {
ok => {}
err(error) => {
fs.close(move file) or trap; // diagnostic here
}
}
}
@@ -0,0 +1,11 @@
// expect: reject E2101
// phase: 6
// spec: docs/spec/06-resources-and-errors.md
// AIR twin: phase2/reject/resource_close_while_borrowed.air
module test.source_resource_close_while_borrowed
fn main(src: cap<fs.read>) -> void effects [fs.read] {
let file = fs.open_read(src, b"/input") or trap;
mut handle = file;
fs.close(move file) or trap; // diagnostic here
}
@@ -0,0 +1,16 @@
// expect: reject E3002
// phase: 6
// spec: docs/spec/06-resources-and-errors.md
// AIR twin: phase2/reject/resource_join_mismatch.air
module test.source_resource_join_mismatch
fn close_on_one_path(src: cap<fs.read>, close_it: bool) -> void effects [fs.read] {
let file = fs.open_read(src, b"/input") or trap;
if close_it { // diagnostic here
fs.close(move file) or trap;
}
trap;
}
fn main(src: cap<fs.read>) -> void effects [fs.read] {
close_on_one_path(src, true);
}
@@ -0,0 +1,15 @@
// expect: reject E3001
// phase: 6
// spec: docs/spec/06-resources-and-errors.md
// AIR twin: phase2/reject/resource_use_after_close.air
module test.source_resource_use_after_close
fn main(src: cap<fs.read>) -> void effects [fs.read] {
let file = fs.open_read(src, b"/input") or trap;
match fs.close(move file) {
ok => {
mut handle = file; // diagnostic here
}
err(error) => {}
}
}
@@ -0,0 +1,20 @@
// expect: reject E3002
// phase: 6
// spec: docs/spec/06-resources-and-errors.md
module test.source_select_join
fn main(src: cap<fs.read>, heap: cap<mem.alloc>) -> void effects [fs.read, mem.alloc, task.wait] {
let file = fs.open_read(src, b"/input") or trap;
match channel.make<u64>(1usize, heap) {
ok(tx, rx) => {
select { // diagnostic here
recv(rx) {
ok(value) => { fs.close(move file) or trap; }
closed => {}
}
cancelled => {}
}
trap;
}
err(error) => { trap; }
}
}
@@ -0,0 +1,13 @@
// expect: reject E3002
// phase: 6
// spec: docs/spec/06-resources-and-errors.md
module test.source_while_join
fn test(src: cap<fs.read>, condition: bool) -> void effects [fs.read] {
let file = fs.open_read(src, b"/input") or trap;
while condition { // diagnostic here
fs.close(move file) or trap;
}
trap;
}
fn main(src: cap<fs.read>) -> void effects [fs.read] { test(src, true); }
+141
View File
@@ -0,0 +1,141 @@
#!/usr/bin/env python3
"""Source/AIR rejection twins and exact lifetime diagnostic provenance."""
from collections import Counter
import json
from pathlib import Path
import re
import subprocess
import tempfile
REPO = Path(__file__).resolve().parents[2]
AJI = REPO / 'zig-out/bin/aji'
CORPUS = REPO / 'tests/conformance'
checks = 0
def cli(*args, code=0):
global checks
result = subprocess.run([str(AJI), *map(str, args)], capture_output=True, text=True)
assert result.returncode == code, (args, result.returncode, result.stdout, result.stderr)
checks += 1
return result.stdout
def records(output):
def unique(pairs):
result = {}
for key, value in pairs:
assert key not in result, ('duplicate JSON member', key)
result[key] = value
return result
return [json.loads(line, object_pairs_hook=unique) for line in output.splitlines()]
def codes(diagnostics):
return Counter(d['code'] for d in diagnostics if d['severity'] == 'error')
def marked_positions(source):
marked = [(i + 1, line) for i, line in enumerate(source.splitlines())
if '// diagnostic here' in line]
assert marked, source
positions = []
for line, text in marked:
if '// diagnostic here: ' in text:
start = text.split('// diagnostic here: ', 1)[1]
positions.append((line, text.index(start) + 1))
else:
positions.append((line, len(text) - len(text.lstrip()) + 1))
return positions
def source_rejection(root, path, *args, expected_file=None):
source = path.read_text()
expected_positions = marked_positions(source)
output = cli('check', *args, code=1)
errors = records(output)
assert [(d['file'], d['line'], d['col']) for d in errors] == [
(expected_file or str(path), *position) for position in expected_positions], errors
for command in ('check', 'run', 'report', 'explore'):
assert cli(command, *args, code=1) == output, (command, args)
canonical = cli('lower', *args)
assert cli('lower', *args) == canonical
annotated = cli('lower', '--annotate', *args)
lines = []
mapping = {}
pending = None
for line in annotated.splitlines():
match = re.fullmatch(r'\s*; (?:(.+):)?(\d+):(\d+)-\d+:\d+', line)
if match:
pending = (match[1], int(match[2]), int(match[3]))
continue
lines.append(line)
mapping[len(lines)] = pending
if line.endswith(':'):
assert pending is not None, ('block label lacks source annotation', line)
pending = None
assert '\n'.join(lines) + '\n' == canonical
lowered = root / 'lowered.air'
lowered.write_text(canonical)
raw = records(cli('check', lowered, code=1))
assert codes(raw) == codes(errors), (raw, errors)
assert len(raw) == len(errors), (raw, errors)
for error, air_error in zip(errors, raw):
assert (error['air_line'], error['air_col']) == (
air_error['line'], air_error['col']), (raw, error)
origin = mapping[error['air_line']]
assert origin is not None and origin[1:] == (error['line'], error['col']), error
if expected_file:
assert origin[0] == expected_file, origin
# A control-flow merge error belongs to its generated label. Instruction
# errors retain their original instruction positions instead.
air_line = canonical.splitlines()[error['air_line'] - 1]
if path.name == 'resource_join_mismatch.aji':
assert air_line.startswith('endif_') and air_line.endswith(':'), air_line
return errors
with tempfile.TemporaryDirectory(prefix='aji-lifetimes-') as directory:
root = Path(directory)
twins = sorted((CORPUS / 'source/lifetimes').glob('*.aji'))
paired = 0
for path in twins:
source = path.read_text()
if '// expect: reject' not in source:
continue
errors = source_rejection(root, path, path)
twin = re.search(r'^// AIR twin: (.+)$', source, re.MULTILINE)
if twin is None:
continue
paired += 1
air_errors = records(cli('check', CORPUS / twin[1], code=1))
expected = re.search(r'^// expect: reject (.+)$', source, re.MULTILINE)[1]
assert codes(errors) == codes(air_errors) == Counter(expected.split()), (
path, errors, air_errors)
assert paired == 8, paired
# Imported specialization keeps the original provider's join position.
library = root / 'library.aji'
template = (CORPUS / 'source/lifetimes/resource_join_mismatch.aji').read_text()
body = template[template.index('fn close_on_one_path'):template.index('fn main')]
body = body.replace('close_on_one_path(', 'close_on_one_path<T: Copy>(')
body = body.replace('close_it: bool)', 'close_it: bool, tag: T)')
library.write_text('module app.library\n\n' + body)
entry = root / 'entry.aji'
entry.write_text('''module app.entry
import app.library;
fn main(src: cap<fs.read>) -> void effects [fs.read] {
app.library.close_on_one_path::<u64>(src, true, 1u64);
}
''')
manifest = root / 'aji.toml'
manifest.write_text('''[package]
name = "lifetimes"
version = "1"
entry = "entry.aji"
[modules]
app.library = "library.aji"
''')
source_rejection(root, library, '--manifest', manifest, expected_file='library.aji')
print(f'source lifetimes: {checks} CLI checks, {paired} AIR rejection twins')