frontend: collect independent source diagnostics without cascades

This commit is contained in:
dev committed 2026-10-09 16:01:18 +03:00
1 parent 2c6c7a3dcd
commit 4cda44823d
47 files changed
+697 -44

No files matched your search

+1
View File
@@ -39,6 +39,7 @@ jobs:
- run: python3 tests/hosted/source_grammar.py
- run: python3 tests/hosted/source_effect_names.py
- run: python3 tests/hosted/source_repair_advice.py
- run: python3 tests/hosted/source_independent_errors.py
- run: python3 tests/hosted/source_cfg_provenance.py
- run: python3 tools/source_reject_twins.py
- run: python3 tests/hosted/source_reject_twins.py
+1
View File
@@ -35,6 +35,7 @@ python3 tests/hosted/source_nominal_queries.py # deep shared types, deterministi
python3 tests/hosted/source_grammar.py # syntax boundaries, canonical enum lists and formatter/AIR fidelity
python3 tests/hosted/source_effect_names.py # effect-name errors, signature priority and package provenance
python3 tests/hosted/source_repair_advice.py # contextual syntax/cast advice and CLI/package parity
python3 tests/hosted/source_independent_errors.py # bounded source error collection without cascades or partial AIR
python3 tests/hosted/source_cfg_provenance.py # resource handoff, loan origins and source/package/AIR diagnostics
python3 tools/source_reject_twins.py # audited same-code pairs and exhaustive, explicitly incomplete AIR inventory
python3 tests/hosted/source_reject_twins.py # false-pair, mapping and inventory regression probes
+1 -1
View File
@@ -1,6 +1,6 @@
# Aji Quick Reference (`.aji` 0.1)
Read this first; it covers most programs. Where to find the full rules is at the end. Every example below is part of a program the conformance suite checks. `aji check file.aji` verifies, `aji run file.aji` verifies and runs, `aji lower file.aji` prints the AIR it becomes. `aji fmt file.aji` prints formatted source; `--check` checks formatting, `--write` replaces the file. Formatting preserves tokens and comments; it does not verify or repair code. Diagnostics are JSON lines; fix the first one first.
Read this first; it covers most programs. Where to find the full rules is at the end. Every example below is part of a program the conformance suite checks. `aji check file.aji` verifies, `aji run file.aji` verifies and runs, `aji lower file.aji` prints the AIR it becomes. `aji fmt file.aji` prints formatted source; `--check` checks formatting, `--write` replaces the file. Formatting preserves tokens and comments; it does not verify or repair code. Diagnostics are JSON lines; read the complete list and repair independent errors together. Frontend collection is capped at 32 and stops at uncertain boundaries.
Aji makes every significant action explicit — moves, borrows, allocation, closing, authority, effects, tasks, channel transfers, locking, cancellation, every failure outcome — and checks them all before running. The compiler writes the mechanics: SSA, control flow, borrow ends, frame storage, the feature header.
+13 -1
View File
@@ -45,6 +45,18 @@ Var inference remains an optional language-policy question. No change is adopted
Nine registered kinds now provide contextual E7001/E7005 advice through `repair_candidates`; argument and binding borrows are separate. Fixed hints and alternative units are specified in spec 10/15 and the registry. Enum variant payloads, `&&`, unsupported block comments, incomplete types and other nearby spellings have explicit exclusion tests. No syntax alias, var inference, inferred slice end or automatic cast selection was added.
Validation: 1735/1735 conformance, including exact `.advice` JSON goldens for all kinds; 161 CLI/package advice checks; unit/registry tests, grammar, formatter, hosted smoke and format checks. Independent Claude review caught the enum-payload context and confirmed the static candidate lifetime correction. Multi-error collection and the public dev measurement remain pending.
Validation: 1735/1735 conformance, including exact `.advice` JSON goldens for all kinds; 161 CLI/package advice checks; unit/registry tests, grammar, formatter, hosted smoke and format checks. Independent Claude review caught the enum-payload context and confirmed the static candidate lifetime correction. At this increment's boundary, multi-error collection was still pending; its delivery follows below. The public dev measurement remains pending.
Bundle growth versus the pre-increment generated bundle (whose Quick Reference matched HEAD): Quick Reference `cl100k_base` 8955 → 9237 (+282, 3.15%), `o200k_base` 8991 → 9272, Qwen2.5 9233 → 9515. Full Source Reference Bundle excluding AIR: 77358 → 78582 (+1224, 1.58%), 77594 → 78815 and 79315 → 80563 respectively. The table and machine advice registry account for this explicit cost; the proposed reduction in repair rounds has not been measured.
## Second increment delivered (2026-10-09)
Spec 15 §10 now defines delimiter-bounded parser recovery, first-error phase stops, collection across validated function bodies, deterministic order and the fixed 32-diagnostic limit. Every failed item/body contributes only its first error. A broken header/import or uncertain delimiter boundary stops collection; no partial AST/AIR reaches another stage. The first failing imported file carries its recovered list. Bodies start with fresh state; failed constants/features/linearity accumulations are restored. Calls read validated signatures, so a bad callee does not create a caller error. Later instances of a failed template are skipped. E7900 still replaces other diagnostics and carries no advice.
Check/lower/run/report/explore and syntax-only fmt now carry the applicable JSON Lines lists. The 12 original mini-probes preserve acceptance and every prior first-diagnostic field; the three-function syntax probe grows from one to three records, and the two-cast probe from one to two. These are compiler observations, not measurements of model repair rounds.
Validation: full conformance 1760/1760; all 25 independent-error fixtures; 234 CLI/package collection checks, 163 advice checks and 5975 formatter checks over 1442 files (770 accepted AIR outputs remain identical). Unit tests compare the next function's complete output/constant tags with fresh lowering after failed borrow/scope/loop bodies, pin constant/feature rollback and no output on error, and test std failure collapse to E7900. Remaining CI Python hosted/oracle checks passed (38 commands, including examples under 200 schedule seeds); source construct coverage remains 121/121. Evaluation harness self-tests also passed (41 tests, one skipped), using scripted/mocked providers rather than model runs. The reason suite's stale void-parameter expectation now pins the earlier E7005, its registry scan selects only the reason section, and the defensive void/never move guard is unit-tested. Claude found no remaining implementation defects after review.
Combined bundle cost for both increments: Quick Reference `cl100k_base` 8955 → 9255 (+300, 3.35%), `o200k_base` 8991 → 9290 and Qwen2.5 9233 → 9534. Full Source Reference Bundle excluding AIR: 77358 → 79072 (+1714, 2.22%), 77594 → 79306 and 79315 → 81059. The second increment adds 18 Quick Reference and 490 full-source tokens in `cl100k_base`; the cost documents recovery boundaries and the JSON Lines contract instead of adding language syntax.
The implementation is ready for a new pinned public dev condition. Gobang is not installed/exposed in this workspace, so no model runs or claimed threefold improvement are recorded here. The evaluation owner should confirm that its tool wrapper retains every diagnostic JSON line and freeze the new compiler commit, docs hashes, model/settings and tool behavior before rerunning the same four public dev tasks. Compare checks/turns and first-code/full-code counts separately; retain the earlier condition unchanged. Ajieval's inspected single-object readers are for documentation/Gobang tool envelopes, not raw compiler stdout; that does not verify the external Gobang wrapper. P6-12 remains open for this measurement, and P6-6 remains open in full.
+1 -1
View File
@@ -139,7 +139,7 @@ Lowering layers (P6A-3/4), each with accepted (golden AIR), rejected (`E7xxx`) a
| 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 |
| P6-12 | doing (advice delivered; collection/measurement pending) | Structured source repair advice and independent diagnostic collection; owner proposal 2026-10-09 | P6-2/4/7 | [repair plan](../design/source-diagnostic-repair.md), spec 15 §10, parser/lowering and CLI | advice applicability and additive fields specified/tested; independent item/body errors collected without partial AIR or cascades; bundle growth and public dev effect measured |
| P6-12 | doing (advice/collection delivered; dev measurement pending) | Structured source repair advice and independent diagnostic collection; owner proposal 2026-10-09 | P6-2/4/7 | [repair plan](../design/source-diagnostic-repair.md), spec 15 §10, parser/lowering and CLI | advice applicability and additive fields specified/tested; independent item/body errors collected without partial AIR or cascades; bundle growth and public dev effect measured |
| P6-10 | todo | Phase exit review | all | plan status | exit criterion passes |
The [standard-library track](standard-library.md) implements nineteen compiler-pinned modules and qualified standard enum names. STD-3/RFC 0021 completes P6-3 with explicit manifest source mapping, acyclic linking, direct qualified names, imported struct literals and task workers. Dependency fetching/resolution is separate package work; STD-4/RFC 0022 completes explicit generics and structural constraints. STD-5/RFC 0023 adds whole-value linear structs/enums/fixed arrays, complete unpack/match, explicit exchange and ownership-preserving allocation failure through all layers (spec 15 §16). STD-6a/b/RFC 0024 resolves Q-036 with initialized buffer<T> and safe std.vec, explicit growth, returned failure ownership and draining (spec 15 §17). STD-6c/RFC 0025 adds safe owning Deque with existing source primitives. STD-6d.1/RFC 0026 adds pure std.hash; STD-6d.2/RFC 0028 adds safe owning U64Map<V> after the explicit error_values prerequisite (RFC 0027). STD-6d.3/RFC 0029 adds explicit static function parameters for general hash/equality/order operations with existing AIR calls/workers. STD-6d.4/RFC 0030 implements the general owning-key std.hashmap contract; its full GC/stress validation passes and Q-037 is resolved. STD-6d.5/RFC 0031 implements general owning std.hashset with duplicate input return; its conformance, GC/schedule, CLI and documentation checks pass. STD-6d.6/RFC 0032 implements safe owning std.heap with explicit order; conformance, GC/schedule, CLI and documentation checks pass. STD-7a/RFC 0033 implements bounded std.io composition with explicit progress, resource loans and exact effects; conformance, GC/schedule, CLI and documentation checks pass. STD-7b/RFC 0034 implements safe owning buffered file adapters with explicit finish/discard and first-error/no-retry behavior; conformance, GC/schedule, CLI and documentation checks pass. STD-7c/RFC 0035 adds pure caller-buffer lexical paths and Copy component ranges; conformance, GC/schedule, CLI and documentation checks pass. The owner adopts STD-0..7 as an intermediate foundation and resumes language work (2026-10-07); remaining std system/service milestones stay in the backlog. P6-11 implements explicit borrowed returns over the existing AIR; RFC 0036 remains Proposed pending owner adoption (Q-034). These increments do not complete Phase 6.
@@ -43,6 +43,8 @@ Example:
}
```
A rejected source module MAY produce multiple diagnostic JSON lines under spec 15 §10. Each line retains the same envelope; consumers MUST read the complete diagnostic stream rather than treating stdout as one JSON object.
## 3. Repair candidates
The compiler MAY emit structured suggestions. The following kinds are illustrative:
+7 -1
View File
@@ -391,7 +391,13 @@ A byte string or array used where a `slice<u8>` is expected is materialized in f
## 10. Diagnostics
Recognized rejected spellings MUST carry the applicable source advice candidate registered in `reference/error-codes.md`, using spec 10 §3. These candidates describe existing syntax; they MUST NOT accept aliases, infer a missing `var` annotation, invent a slice end, duplicate a receiver expression or select a cast mode. `let` inference remains unchanged. Parser recovery and diagnostic collection are unaffected by this advice requirement.
Recognized rejected spellings MUST carry the applicable source advice candidate registered in `reference/error-codes.md`, using spec 10 §3. These candidates describe existing syntax; they MUST NOT accept aliases, infer a missing `var` annotation, invent a slice end, duplicate a receiver expression or select a cast mode. `let` inference remains unchanged.
**Independent source errors.** A rejected source compilation MUST expose at most 32 frontend diagnostics, in parser declaration order or concrete lowering order. Each failed top-level declaration/body contributes at most its first error. Module/import headers, linking failures, generic specialization, types, signatures and module requirements remain first-error phase stops. A syntax-error module MUST NOT reach linking/lowering; a module with body errors MUST NOT emit AIR or reach the verifier. No recovery placeholder may escape. Existing diagnostic fields and the first diagnostic MUST be preserved; later independent failures MAY add JSON lines. Check/lower/run/report/explore MUST expose the same list, including advice; fmt MUST expose the same syntax list and refuse formatting it.
Parser recovery MUST occur only after an independently bounded `fn`, `struct` or `enum` item: matching `()`, `[]` and `{}` tokens identify a complete outer body, the failure is within that item, and the next token is EOF or another declaration keyword. An unbalanced/mismatched delimiter, missing body, top-level junk or invalid lexical token other than the recognized lone `!` MUST stop recovery. A new function declaration before the first outer body MUST NOT supply the failed declaration's missing body; static `fn` selections/contracts are not declaration boundaries. Header/import failures stop before items. Parsing the next item MUST reset transient expression/advice state. Source import traversal retains its existing deterministic order: the first failing imported module exposes its own recovered list and then stops linking; a std syntax failure remains one E7900 without advice.
Body collection MUST begin only after complete declaration/signature/requirement validation. Bodies read other functions through those validated declarations, not through body outputs; a failed callee MUST NOT manufacture a caller error. Every body MUST start with fresh function state, and failure MUST discard its output and restore module accumulations before continuing. Later instantiations of a failed generic source declaration MUST be skipped, preserving one error per source function. Existing one-per-code/source-location deduplication remains mandatory. An unimplemented body encountered before any collected error retains the unimplemented result; after an error it is skipped and collection continues. At the fixed limit collection stops and the module remains rejected.
| Problem | Code |
|---|---|
+1
View File
@@ -38,6 +38,7 @@ pub fn checkWithModules(arena: std.mem.Allocator, file_name: []const u8, source:
const lowered = switch (try frontend.compileWithModules(arena, file_name, source, sources)) {
.ok => |o| o,
.err => |d| return .{ .status = .rejected, .diagnostics = try arena.dupe(diag.Diagnostic, &.{d}) },
.errors => |ds| return .{ .status = .rejected, .diagnostics = ds },
.unimplemented => |what| return .{ .status = .unimplemented, .diagnostics = &.{}, .missing_stage = what },
};
return checkLowered(arena, file_name, lowered);
+3
View File
@@ -163,6 +163,9 @@ pub const RepairCandidate = struct {
alternatives: []const []const u8 = &.{},
};
/// Fixed source collection bound (spec 15 §10), never a semantic flag.
pub const source_diagnostic_limit = 32;
/// 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();
+50 -12
View File
@@ -18,8 +18,10 @@ pub const Span = ast.Span;
pub const Compiled = union(enum) {
/// Canonical AIR, its line map and the annotated form.
ok: lower_mod.Output,
/// One source diagnostic (`E7xxx`): the first problem only.
/// A single source diagnostic; declaration-wide failures stop the phase.
err: diag.Diagnostic,
/// Independent source diagnostics; no partial AIR is exposed.
errors: []const diag.Diagnostic,
unimplemented: []const u8,
};
@@ -32,6 +34,7 @@ pub fn compileWithModules(arena: std.mem.Allocator, file: []const u8, source: []
const m = switch (parsed) {
.ok => |m| m,
.err => |f| return .{ .err = try syntaxDiagnostic(arena, file, f) },
.errors => |fs| return diagnosticResult(try syntaxDiagnostics(arena, file, fs)),
};
const linked = try modules.link(arena, m, sources);
const result = switch (linked) {
@@ -40,25 +43,60 @@ pub fn compileWithModules(arena: std.mem.Allocator, file: []const u8, source: []
.err => |p| lower_mod.Result{ .err = p },
},
.err => |p| lower_mod.Result{ .err = p },
.errors => |ps| lower_mod.Result{ .errors = ps },
};
return switch (result) {
.ok => |o| .{ .ok = o },
.err => |p| blk: {
const fields = try arena.alloc(diag.Field, p.fields.len + @intFromBool(p.reason != null));
for (p.fields, fields[0..p.fields.len]) |pf, *f| f.* = .{ .name = pf.name, .value = .{ .str = pf.value } };
if (p.reason) |reason| fields[p.fields.len] = .{ .name = "reason", .value = .{ .str = @tagName(reason) } };
break :blk .{ .err = .{
.code = diag.lookup(p.code).?,
.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,
} };
.err => |p| .{ .err = try problemDiagnostic(arena, file, p) },
.errors => |ps| blk: {
const ds = try arena.alloc(diag.Diagnostic, ps.len);
for (ps, ds) |p, *d| d.* = try problemDiagnostic(arena, file, p);
break :blk diagnosticResult(deduplicate(ds));
},
.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 }) },
};
}
fn problemDiagnostic(arena: std.mem.Allocator, file: []const u8, p: lower_mod.Problem) std.mem.Allocator.Error!diag.Diagnostic {
const fields = try arena.alloc(diag.Field, p.fields.len + @intFromBool(p.reason != null));
for (p.fields, fields[0..p.fields.len]) |pf, *f| f.* = .{ .name = pf.name, .value = .{ .str = pf.value } };
if (p.reason) |reason| fields[p.fields.len] = .{ .name = "reason", .value = .{ .str = @tagName(reason) } };
return .{
.code = diag.lookup(p.code).?,
.span = .{ .file = p.span.file orelse file, .line = p.span.start.line, .col = p.span.start.col },
.message = p.message,
.fields = fields,
.repair_candidates = if (std.mem.eql(u8, p.code, "E7900")) &.{} else p.repair_candidates,
};
}
fn diagnosticResult(ds: []const diag.Diagnostic) Compiled {
for (ds) |d| if (std.mem.eql(u8, d.code.id, "E7900")) return .{ .err = d };
return if (ds.len == 1) .{ .err = ds[0] } else .{ .errors = ds };
}
fn deduplicate(ds: []diag.Diagnostic) []const diag.Diagnostic {
var count: usize = 0;
for (ds) |d| {
const duplicate = for (ds[0..count]) |prior| {
const a = d.span.?;
const b = prior.span.?;
if (d.code == prior.code and a.line == b.line and a.col == b.col and std.mem.eql(u8, a.file, b.file)) break true;
} else false;
if (!duplicate) {
ds[count] = d;
count += 1;
}
}
return ds[0..count];
}
pub fn syntaxDiagnostics(arena: std.mem.Allocator, file: []const u8, failures: []const parse.Failure) std.mem.Allocator.Error![]const diag.Diagnostic {
const ds = try arena.alloc(diag.Diagnostic, failures.len);
for (failures, ds) |f, *d| d.* = try syntaxDiagnostic(arena, file, f);
return deduplicate(ds);
}
pub fn syntaxDiagnostic(arena: std.mem.Allocator, file: []const u8, f: parse.Failure) std.mem.Allocator.Error!diag.Diagnostic {
return .{
.code = diag.lookup("E7001").?,
+2 -1
View File
@@ -8,7 +8,7 @@ const Allocator = std.mem.Allocator;
const Tag = lex.Tag;
const Token = lex.Token;
const Error = error{ OutOfMemory, Invariant };
pub const Result = union(enum) { ok: []const u8, err: parse.Failure };
pub const Result = union(enum) { ok: []const u8, err: parse.Failure, errors: []const parse.Failure };
const Curly = enum { block, list, literal };
const Mark = struct { angle: bool = false, prefix: bool = false, curly: Curly = .block, top: bool = false, module_end: bool = false, statement_end: bool = false, mate: usize = 0, multiline: bool = false, layout_scope: usize = 0 };
@@ -17,6 +17,7 @@ const Node = union(enum) { block: *const ast.Block, stmt: *const ast.Stmt, expr:
pub fn format(arena: Allocator, source: []const u8) Error!Result {
const module = switch (try parse.parse(arena, source)) {
.err => |f| return .{ .err = f },
.errors => |fs| return .{ .errors = fs },
.ok => |m| m,
};
const tokens = try lex.tokenize(arena, source);
+142 -2
View File
@@ -175,6 +175,7 @@ pub const Result = union(enum) {
ok: Output,
/// A source problem (`E7xxx`).
err: Problem,
errors: []const Problem,
/// A construct of a layer that is not implemented yet.
unimplemented: struct { span: Span, construct: []const u8 },
};
@@ -184,7 +185,7 @@ const Error = error{ Lower, Unimplemented, OutOfMemory };
pub fn lower(arena: Allocator, m: ast.Module) Allocator.Error!Result {
var l: Lowerer = .{ .arena = arena, .m = m };
l.run() catch |e| switch (e) {
error.Lower => return .{ .err = l.problem.? },
error.Lower => return if (l.problems.items.len > 1) .{ .errors = l.problems.items } else .{ .err = if (l.problems.items.len == 1) l.problems.items[0] else l.problem.? },
error.Unimplemented => return .{ .unimplemented = l.unimpl.? },
error.OutOfMemory => return error.OutOfMemory,
};
@@ -286,6 +287,7 @@ const Lowerer = struct {
/// Set while a byte string is materialized: the tag for its instructions.
in_constant: u32 = 0,
problem: ?Problem = null,
problems: std.ArrayList(Problem) = .empty,
unimpl: ?@FieldType(Result, "unimplemented") = null,
sigs: std.StringHashMapUnmanaged(FnSig) = .empty,
/// `@Name` of each declared type.
@@ -493,7 +495,43 @@ const Lowerer = struct {
var type_lines: std.ArrayList(Inst) = .empty;
for (l.m.types) |t| try type_lines.append(l.arena, .{ .text = try l.typeDeclText(t), .span = t.span });
try l.checkRequirements();
for (l.m.functions) |f| try l.fns.append(l.arena, try l.function(f));
var failed_declarations: std.ArrayList(Span) = .empty;
for (l.m.functions) |f| {
const failed = for (failed_declarations.items) |span| {
if (sameDeclaration(span, f.span)) break true;
} else false;
if (failed) continue;
// Bodies read only validated signatures/declarations. Restore all
// module accumulations on failure, including byte-string constants,
// features and linearity flags; no failed FnOut is ever appended.
const checkpoint = .{ .uses = l.uses, .linear_enabled = l.linear_enabled, .constants_len = l.constants.items.len };
const output = l.function(f) catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
error.Unimplemented => {
if (l.problems.items.len == 0) return error.Unimplemented;
l.uses = checkpoint.uses;
l.linear_enabled = checkpoint.linear_enabled;
l.constants.items.len = checkpoint.constants_len;
l.in_constant = 0;
l.unimpl = null;
continue;
},
error.Lower => {
const problem = l.problem.?;
l.uses = checkpoint.uses;
l.linear_enabled = checkpoint.linear_enabled;
l.constants.items.len = checkpoint.constants_len;
l.in_constant = 0;
l.problem = null;
try l.problems.append(l.arena, problem);
try failed_declarations.append(l.arena, f.span);
if (l.problems.items.len == @import("../diag.zig").source_diagnostic_limit) return error.Lower;
continue;
},
};
try l.fns.append(l.arena, output);
}
if (l.problems.items.len != 0) return error.Lower;
var features: std.ArrayList(u8) = .empty;
const roots = try l.featureRoots(type_lines.items);
@@ -809,6 +847,16 @@ const Lowerer = struct {
l.allocs = .empty;
l.facts = .empty;
l.addressable = .empty;
l.cur = null;
l.rest = .empty;
l.pending_loop = null;
l.pending_bindings = .empty;
l.pending_ends = .empty;
l.unchecked = false;
l.in_constant = 0;
l.scope_binding_start = 0;
l.problem = null;
l.unimpl = null;
l.counter = 0;
l.params = f.params;
try l.findAddressable(f.body);
@@ -3625,6 +3673,12 @@ const Lowerer = struct {
}
};
fn sameDeclaration(a: Span, b: Span) bool {
return a.start.line == b.start.line and a.start.col == b.start.col and
std.mem.eql(u8, a.file orelse "", b.file orelse "") and
std.mem.eql(u8, a.namespace orelse "", b.namespace orelse "");
}
fn elemOf(t: Ty) ?Ty {
return switch (t) {
.array => |a| a.elem,
@@ -4083,3 +4137,89 @@ test "cyclic source diamonds reject before property construction" {
try std.testing.expectEqual(@as(u32, 2), l.problem.?.span.start.line);
try std.testing.expect(l.property_module == null);
}
test "failed body discards constants and features and never emits partial AIR" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const source =
\\module collection
\\fn good() -> void effects [] { let text = b"good"; }
\\fn bad() -> void effects [unsafe] { let text = b"bad"; let x = missing; }
\\fn main() -> void effects [] {}
;
const m = (try parse_mod.parse(a, source)).ok;
var l: Lowerer = .{ .arena = a, .m = m };
try std.testing.expectError(error.Lower, l.run());
try std.testing.expectEqual(@as(usize, 1), l.problems.items.len);
try std.testing.expectEqualStrings("E7002", l.problems.items[0].code);
try std.testing.expectEqual(@as(usize, 2), l.fns.items.len);
try std.testing.expectEqual(@as(usize, 1), l.constants.items.len);
try std.testing.expectEqualStrings("good", l.constants.items[0].bytes);
try std.testing.expect(!l.uses.contains(.unsafe));
try std.testing.expectEqual(@as(usize, 0), l.out.items.len);
try std.testing.expectEqual(@as(usize, 0), l.annotated.items.len);
try std.testing.expectEqual(@as(usize, 0), l.lines.items.len);
try std.testing.expectEqual(@as(usize, 0), l.constant_of.items.len);
}
test "later function output matches fresh lowering after failed borrow and scope bodies" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const stable =
\\fn stable() -> u64 effects [] {
\\ let inferred = 7;
\\ let text = b"ok";
\\ var bytes: [u8; 4] = zero;
\\ var total: u64 = inferred;
\\ for i in 0usize..2usize { total = total + (bytes[i] as u64); }
\\ return total + (text.len as! u64);
\\}
\\fn main() -> void effects [] {}
;
const baseline_source = try std.fmt.allocPrint(a, "module collection\n{s}", .{stable});
const baseline_module = (try parse_mod.parse(a, baseline_source)).ok;
var baseline: Lowerer = .{ .arena = a, .m = baseline_module };
try baseline.run();
var baseline_emission: Lowerer = .{ .arena = a, .m = baseline_module };
try baseline_emission.emitFunction(baseline.fns.items[0]);
for ([_][]const u8{
"fn bad() -> void effects [] { let shadow = 1u64; let x = missing; }",
"fn bad() -> void effects [] { var bytes: [u8; 4] = zero; ref unchecked view = bytes[missing]; }",
"fn bad() -> void effects [unsafe] { scope s { let text = b\"bad\"; loop { let x = missing; } } }",
}) |bad| {
const source = try std.fmt.allocPrint(a, "module collection\n{s}\n{s}", .{ bad, stable });
const m = (try parse_mod.parse(a, source)).ok;
var recovered: Lowerer = .{ .arena = a, .m = m };
try std.testing.expectError(error.Lower, recovered.run());
try std.testing.expectEqual(@as(usize, 1), recovered.problems.items.len);
try std.testing.expectEqualStrings("E7002", recovered.problems.items[0].code);
try std.testing.expectEqual(@as(usize, 2), recovered.fns.items.len);
try std.testing.expectEqual(@as(usize, 0), recovered.out.items.len);
var emission: Lowerer = .{ .arena = a, .m = m };
try emission.emitFunction(recovered.fns.items[0]);
try std.testing.expectEqualStrings(baseline_emission.out.items, emission.out.items);
try std.testing.expectEqualSlices(u32, baseline_emission.constant_of.items, emission.constant_of.items);
try std.testing.expectEqual(@as(usize, 1), recovered.constants.items.len);
try std.testing.expectEqualStrings("ok", recovered.constants.items[0].bytes);
}
}
test "defensive nonmaterializable moves retain invalid_move even in generic transfers" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const span: Span = .{ .start = .{ .line = 2, .col = 3 }, .end = .{ .line = 2, .col = 9 } };
// Annotation/binding checks normally reject these values earlier. Keep
// the lower-level guard stable without inventing accepted void parameters.
for ([_]Ty{ .void, .never }) |ty| for ([_]bool{ false, true }) |generic| {
var l: Lowerer = .{ .arena = a, .m = .{ .name = "defensive", .types = &.{}, .functions = &.{} } };
try l.bindings.append(a, .{ .name = "value", .value = "v", .ty = ty, .mutable = false });
try std.testing.expectError(error.Lower, l.expr(.{ .span = span, .generic_transfer = generic, .kind = .{ .move = "value" } }, null));
try std.testing.expectEqualStrings("E7006", l.problem.?.code);
try std.testing.expectEqual(InvalidReason.invalid_move, l.problem.?.reason.?);
try std.testing.expectEqual(span, l.problem.?.span);
try std.testing.expectEqual(@as(usize, 0), l.out.items.len);
};
}
+37 -12
View File
@@ -7,7 +7,7 @@ const stdlib = @import("stdlib.zig");
const authority = @import("../air/authority.zig");
pub const Source = stdlib.Source;
pub const Result = union(enum) { ok: ast.Module, err: lower.Problem };
pub const Result = union(enum) { ok: ast.Module, err: lower.Problem, errors: []const lower.Problem };
const Error = error{ OutOfMemory, InvalidSource };
const Node = struct { module: ast.Module, active: bool, height: usize = 0 };
@@ -28,7 +28,7 @@ pub fn link(arena: std.mem.Allocator, entry: ast.Module, sources: []const Source
const span: ast.Span = if (entry.functions.len != 0) entry.functions[0].span else .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 1 } };
const combined = g.run(entry, span) catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
error.InvalidSource => return .{ .err = g.problem.? },
error.InvalidSource => return if (g.problems.len > 1) .{ .errors = g.problems } else .{ .err = g.problem.? },
};
return .{ .ok = combined };
}
@@ -38,6 +38,22 @@ const Graph = struct {
sources: []const Source,
nodes: std.ArrayList(Node) = .empty,
problem: ?lower.Problem = null,
problems: []const lower.Problem = &.{},
fn syntaxFailures(g: *Graph, source: Source, failures: []const parse.Failure) Error {
const internal = std.mem.startsWith(u8, source.name, "std.");
const problems = try g.arena.alloc(lower.Problem, if (internal) 1 else failures.len);
for (failures[0..problems.len], problems) |failure, *problem| problem.* = .{
.code = if (internal) "E7900" else "E7001",
.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 (internal) &.{} else failure.repair_candidates,
};
g.problem = problems[0];
g.problems = problems;
return error.InvalidSource;
}
fn fail(g: *Graph, comptime code: []const u8, span: ast.Span, message: []const u8, name: []const u8) Error {
if (comptime std.mem.eql(u8, code, "E7006")) @compileError("E7006 requires an explicit reason via invalid()");
@@ -117,16 +133,8 @@ const Graph = struct {
} else return g.fail("E7002", imp.span, "unknown module in explicit source mapping", imp.path);
const m = switch (try parse.parseWithFile(g.arena, source.source, source.file)) {
.ok => |m| m,
.err => |failure| {
g.problem = .{
.code = if (std.mem.startsWith(u8, source.name, "std.")) "E7900" else "E7001",
.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;
},
.err => |failure| return g.syntaxFailures(source, &.{failure}),
.errors => |failures| return g.syntaxFailures(source, failures),
};
if (!std.mem.eql(u8, m.name, source.name)) return g.invalid(.module_header_mismatch, .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 1 }, .file = source.file, .namespace = source.name }, "module header differs from its mapped name", source.name);
const index = g.nodes.items.len;
@@ -157,3 +165,20 @@ fn used(types: []const ast.TypeDecl, functions: []const ast.FnDecl, name: []cons
for (functions) |f| if (std.mem.eql(u8, f.air_name orelse f.name, name)) return true;
return false;
}
test "std syntax lists become exactly one internal error without advice" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const failures: []const parse.Failure = &.{
.{ .pos = .{ .line = 2, .col = 3 }, .expected = "an expression", .found = "!", .repair_candidates = @import("../diag.zig").SourceRepairKind.one(.boolean_negation) },
.{ .pos = .{ .line = 3, .col = 4 }, .expected = "an expression", .found = "!", .repair_candidates = @import("../diag.zig").SourceRepairKind.one(.boolean_negation) },
};
var g: Graph = .{ .arena = a, .sources = &.{} };
try std.testing.expectEqual(error.InvalidSource, g.syntaxFailures(.{ .name = "std.bytes", .file = "<std.bytes>", .source = "" }, failures));
try std.testing.expectEqual(@as(usize, 1), g.problems.len);
try std.testing.expectEqualStrings("E7900", g.problem.?.code);
try std.testing.expectEqualStrings("<std.bytes>", g.problem.?.span.file.?);
try std.testing.expectEqual(failures[0].pos, g.problem.?.span.start);
try std.testing.expectEqual(@as(usize, 0), g.problem.?.repair_candidates.len);
}
+78 -10
View File
@@ -1,6 +1,6 @@
//! Parser for `.aji` source 0.1 (reference/grammar.ebnf). Recursive
//! descent. On the first error it stops with exactly one `E7001` carrying
//! the span, what was expected and what was found: no recovery, no cascade.
//! descent. At most one E7001 per independently bounded top-level item;
//! malformed boundaries stop collection. No partial AST escapes on error.
const std = @import("std");
const lex = @import("lex.zig");
@@ -18,7 +18,7 @@ pub const Failure = struct {
repair_candidates: []const diag.RepairCandidate = &.{},
};
pub const Result = union(enum) { ok: ast.Module, err: Failure };
pub const Result = union(enum) { ok: ast.Module, err: Failure, errors: []const Failure };
pub fn parse(arena: Allocator, src: []const u8) Allocator.Error!Result {
return parseWithFile(arena, src, null);
@@ -28,7 +28,7 @@ pub fn parseWithFile(arena: Allocator, src: []const u8, file: ?[]const u8) Alloc
const tokens = try lex.tokenize(arena, src);
var p: Parser = .{ .arena = arena, .tokens = try arena.dupe(Token, tokens), .file = file };
const m = p.module() catch |e| switch (e) {
error.Syntax => return .{ .err = p.failure.? },
error.Syntax => return if (p.failures.items.len > 1) .{ .errors = p.failures.items } else .{ .err = if (p.failures.items.len == 1) p.failures.items[0] else p.failure.? },
error.OutOfMemory => return error.OutOfMemory,
};
return .{ .ok = m };
@@ -43,6 +43,7 @@ const Parser = struct {
/// Also tracks a consumed half of `>>` while the other half stays at pos.
last_end: ?lex.Pos = null,
failure: ?Failure = null,
failures: std.ArrayList(Failure) = .empty,
file: ?[]const u8 = null,
module_name: ?[]const u8 = null,
/// Struct literals are not allowed where a `{` starts a block (conditions).
@@ -234,15 +235,82 @@ const Parser = struct {
var types: std.ArrayList(ast.TypeDecl) = .empty;
var fns: std.ArrayList(ast.FnDecl) = .empty;
while (p.peek().tag != .eof) {
if (p.atWord("struct") or p.atWord("enum")) {
try types.append(p.arena, try p.typeDecl());
} else if (p.atWord("fn")) {
try fns.append(p.arena, try p.fnDecl());
} else return p.fail(p.peek(), "`struct`, `enum` or `fn`");
const start = p.pos;
const item = p.declaration() catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
error.Syntax => {
try p.failures.append(p.arena, p.failure.?);
if (p.failures.items.len == diag.source_diagnostic_limit) return error.Syntax;
const end = try p.recoveryEnd(start) orelse return error.Syntax;
p.pos = end;
p.last_end = p.tokens[end - 1].end;
p.failure = null;
p.no_struct = false;
p.type_advice = null;
p.borrow_advice = null;
continue;
},
};
switch (item) {
.type_decl => |t| try types.append(p.arena, t),
.function => |f| try fns.append(p.arena, f),
}
}
if (p.failures.items.len != 0) return error.Syntax;
return .{ .name = name, .imports = imports.items, .types = types.items, .functions = fns.items };
}
fn declaration(p: *Parser) Error!union(enum) { type_decl: ast.TypeDecl, function: ast.FnDecl } {
if (p.atWord("struct") or p.atWord("enum")) return .{ .type_decl = try p.typeDecl() };
if (p.atWord("fn")) return .{ .function = try p.fnDecl() };
return p.fail(p.peek(), "`struct`, `enum` or `fn`");
}
fn itemKeyword(t: Token) bool {
return isWord(t, "fn") or isWord(t, "struct") or isWord(t, "enum");
}
/// This scan proves a delimiter boundary, not the failed item's semantics.
/// It never trusts a keyword's column and never rewinds past a failure.
fn recoveryEnd(p: *Parser, start: usize) Error!?usize {
if (!itemKeyword(p.tokens[start])) return null;
var stack: std.ArrayList(Tag) = .empty;
var body = false;
for (p.tokens[start..], start..) |t, i| {
if (t.tag == .invalid and !std.mem.eql(u8, t.text, "!")) return null;
if (!body and stack.items.len == 0 and i != start and itemKeyword(t)) {
// Static function contracts use fn(...), selections fn path or
// fn path::<...>; neither is a new fn Name(...) declaration.
if (!isWord(t, "fn") or (i + 2 < p.tokens.len and p.tokens[i + 1].tag == .ident and
(p.tokens[i + 2].tag == .l_paren or p.tokens[i + 2].tag == .lt))) return null;
}
switch (t.tag) {
.l_paren, .l_bracket, .l_brace => {
if (t.tag == .l_brace and stack.items.len == 0) body = true;
try stack.append(p.arena, t.tag);
},
.r_paren, .r_bracket, .r_brace => {
const open = stack.pop() orelse return null;
const wanted: Tag = switch (t.tag) {
.r_paren => .l_paren,
.r_bracket => .l_bracket,
else => .l_brace,
};
if (open != wanted) return null;
if (body and stack.items.len == 0) {
const end = i + 1;
if (end <= p.pos or end >= p.tokens.len) return null;
if (p.tokens[end].tag != .eof and !itemKeyword(p.tokens[end])) return null;
return end;
}
},
.eof => return null,
else => {},
}
}
return null;
}
fn path(p: *Parser) Error![]const u8 {
var out: std.ArrayList(u8) = .empty;
try out.appendSlice(p.arena, try p.ident("a name"));
@@ -359,7 +427,7 @@ 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"))
if (!p.speculative and std.mem.eql(u8, name, t.text) 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")) {
+14
View File
@@ -171,6 +171,13 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
try out.writeByte('\n');
return .rejected;
},
.errors => |ds| {
for (ds) |d| {
try d.writeJson(out);
try out.writeByte('\n');
}
return .rejected;
},
.unimplemented => |what| {
std.debug.print("aji: not implemented yet: {s}\n", .{what});
return .unimplemented;
@@ -526,6 +533,13 @@ fn formatCommand(io: std.Io, arena: std.mem.Allocator, arguments: []const [:0]co
try out.writeByte('\n');
return .rejected;
},
.errors => |fs| {
for (try aji.frontend.syntaxDiagnostics(arena, path, fs)) |d| {
try d.writeJson(out);
try out.writeByte('\n');
}
return .rejected;
},
.ok => |text| text,
};
if (mode == .stdout) {
@@ -0,0 +1,7 @@
// expect: reject E7002 E7002
// phase: 6
// spec: docs/spec/15-source-language.md §10
module collection
fn bad() -> u64 effects [] { let shadow = 1u64; return missing; }
fn next() -> u64 effects [] { return shadow; }
fn main() -> void effects [] {}
@@ -0,0 +1,6 @@
// expect: reject E7005
// phase: 6
// spec: docs/spec/15-source-language.md §10
module collection
fn bad(n: u64) -> u32 effects [] { return n as u32; }
fn main() -> u32 effects [] { return bad(1u64); }
@@ -0,0 +1,6 @@
// expect: reject E7005 E7005
// phase: 6
// spec: docs/spec/15-source-language.md §10
module collection
fn bad(n: u64) -> u32 effects [] { return n as u32; }
fn main() -> bool effects [] { return bad(1u64); }
@@ -0,0 +1,6 @@
// expect: reject E7001 E7001
// phase: 6
// spec: docs/spec/15-source-language.md §10
module collection
fn a() -> u64 effects [] { return 1u64 }
fn main() -> bool effects [] { return !true; }
@@ -0,0 +1,6 @@
// expect: reject E7001
// phase: 6
// spec: docs/spec/15-source-language.md §10
module collection
fn a() -> bool effects [] { return !false; }}
fn main() -> bool effects [] { return !true; }
@@ -0,0 +1,6 @@
// expect: reject E7002
// phase: 6
// spec: docs/spec/15-source-language.md §10
module collection
fn bad<T>(x: T) -> T effects [] { return missing; }
fn main() -> void effects [] { let a = bad::<u64>(1u64); let b = bad::<u32>(1u32); }
@@ -0,0 +1,5 @@
// expect: reject E7001
// phase: 6
// spec: docs/spec/15-source-language.md §10
module
fn main() -> bool effects [] { return !true; }
@@ -0,0 +1,6 @@
// expect: reject E7001 E7001
// phase: 6
// spec: docs/spec/15-source-language.md §10
module collection
fn a(s: mut slice<u8>) -> void effects [] {}
fn main() -> bool effects [] { return !true; }
@@ -0,0 +1,6 @@
// expect: reject E7001
// phase: 6
// spec: docs/spec/15-source-language.md §10
module collection
import lib.bad
fn main() -> bool effects [] { return !true; }
@@ -0,0 +1,6 @@
// expect: reject E7001
// phase: 6
// spec: docs/spec/15-source-language.md §10
module collection
fn a() -> bool effects [] { return @false; }
fn main() -> bool effects [] { return !true; }
@@ -0,0 +1,40 @@
// expect: reject E7005 E7005 E7005 E7005 E7005 E7005 E7005 E7005 E7005 E7005 E7005 E7005 E7005 E7005 E7005 E7005 E7005 E7005 E7005 E7005 E7005 E7005 E7005 E7005 E7005 E7005 E7005 E7005 E7005 E7005 E7005 E7005
// phase: 6
// spec: docs/spec/15-source-language.md §10
module collection
fn f0(x: u64) -> u32 effects [] { return x as u32; }
fn f1(x: u64) -> u32 effects [] { return x as u32; }
fn f2(x: u64) -> u32 effects [] { return x as u32; }
fn f3(x: u64) -> u32 effects [] { return x as u32; }
fn f4(x: u64) -> u32 effects [] { return x as u32; }
fn f5(x: u64) -> u32 effects [] { return x as u32; }
fn f6(x: u64) -> u32 effects [] { return x as u32; }
fn f7(x: u64) -> u32 effects [] { return x as u32; }
fn f8(x: u64) -> u32 effects [] { return x as u32; }
fn f9(x: u64) -> u32 effects [] { return x as u32; }
fn f10(x: u64) -> u32 effects [] { return x as u32; }
fn f11(x: u64) -> u32 effects [] { return x as u32; }
fn f12(x: u64) -> u32 effects [] { return x as u32; }
fn f13(x: u64) -> u32 effects [] { return x as u32; }
fn f14(x: u64) -> u32 effects [] { return x as u32; }
fn f15(x: u64) -> u32 effects [] { return x as u32; }
fn f16(x: u64) -> u32 effects [] { return x as u32; }
fn f17(x: u64) -> u32 effects [] { return x as u32; }
fn f18(x: u64) -> u32 effects [] { return x as u32; }
fn f19(x: u64) -> u32 effects [] { return x as u32; }
fn f20(x: u64) -> u32 effects [] { return x as u32; }
fn f21(x: u64) -> u32 effects [] { return x as u32; }
fn f22(x: u64) -> u32 effects [] { return x as u32; }
fn f23(x: u64) -> u32 effects [] { return x as u32; }
fn f24(x: u64) -> u32 effects [] { return x as u32; }
fn f25(x: u64) -> u32 effects [] { return x as u32; }
fn f26(x: u64) -> u32 effects [] { return x as u32; }
fn f27(x: u64) -> u32 effects [] { return x as u32; }
fn f28(x: u64) -> u32 effects [] { return x as u32; }
fn f29(x: u64) -> u32 effects [] { return x as u32; }
fn f30(x: u64) -> u32 effects [] { return x as u32; }
fn f31(x: u64) -> u32 effects [] { return x as u32; }
fn f32(x: u64) -> u32 effects [] { return x as u32; }
fn f33(x: u64) -> u32 effects [] { return x as u32; }
fn f34(x: u64) -> u32 effects [] { return x as u32; }
fn main() -> void effects [] {}
@@ -0,0 +1,40 @@
// expect: reject E7001 E7001 E7001 E7001 E7001 E7001 E7001 E7001 E7001 E7001 E7001 E7001 E7001 E7001 E7001 E7001 E7001 E7001 E7001 E7001 E7001 E7001 E7001 E7001 E7001 E7001 E7001 E7001 E7001 E7001 E7001 E7001
// phase: 6
// spec: docs/spec/15-source-language.md §10
module collection
fn f0() -> bool effects [] { return !false; }
fn f1() -> bool effects [] { return !false; }
fn f2() -> bool effects [] { return !false; }
fn f3() -> bool effects [] { return !false; }
fn f4() -> bool effects [] { return !false; }
fn f5() -> bool effects [] { return !false; }
fn f6() -> bool effects [] { return !false; }
fn f7() -> bool effects [] { return !false; }
fn f8() -> bool effects [] { return !false; }
fn f9() -> bool effects [] { return !false; }
fn f10() -> bool effects [] { return !false; }
fn f11() -> bool effects [] { return !false; }
fn f12() -> bool effects [] { return !false; }
fn f13() -> bool effects [] { return !false; }
fn f14() -> bool effects [] { return !false; }
fn f15() -> bool effects [] { return !false; }
fn f16() -> bool effects [] { return !false; }
fn f17() -> bool effects [] { return !false; }
fn f18() -> bool effects [] { return !false; }
fn f19() -> bool effects [] { return !false; }
fn f20() -> bool effects [] { return !false; }
fn f21() -> bool effects [] { return !false; }
fn f22() -> bool effects [] { return !false; }
fn f23() -> bool effects [] { return !false; }
fn f24() -> bool effects [] { return !false; }
fn f25() -> bool effects [] { return !false; }
fn f26() -> bool effects [] { return !false; }
fn f27() -> bool effects [] { return !false; }
fn f28() -> bool effects [] { return !false; }
fn f29() -> bool effects [] { return !false; }
fn f30() -> bool effects [] { return !false; }
fn f31() -> bool effects [] { return !false; }
fn f32() -> bool effects [] { return !false; }
fn f33() -> bool effects [] { return !false; }
fn f34() -> bool effects [] { return !false; }
fn main() -> void effects [] {}
@@ -0,0 +1,6 @@
// expect: reject E7001
// phase: 6
// spec: docs/spec/15-source-language.md §10
module collection
fn a() -> bool effects [] { return (!false]; }
fn main() -> bool effects [] { return !true; }
@@ -0,0 +1,6 @@
// expect: reject E7001
// phase: 6
// spec: docs/spec/15-source-language.md §10
module collection
fn a() -> bool effects []
fn main() -> bool effects [] { return !true; }
@@ -0,0 +1,6 @@
// expect: reject E7001
// phase: 6
// spec: docs/spec/15-source-language.md §10
module collection
fn a() -> bool effects [] { return !false;
fn main() -> bool effects [] { return !true; }
@@ -0,0 +1,7 @@
// expect: reject E7001 E7001 E7001
// phase: 6
// spec: docs/spec/15-source-language.md §10
module collection
struct A { x: mut slice<u8> }
enum B { C(ref slice<u8>) }
fn main() -> bool effects [] { return !true; }
@@ -0,0 +1,5 @@
// expect: reject E7001
// phase: 6
// spec: docs/spec/15-source-language.md §10
module collection
fn main() -> bool effects [] { return !false and !true; }
@@ -0,0 +1 @@
[{"kind":"boolean_negation","hint":"Aji boolean negation is `not`; integer complement is not boolean negation."}]
@@ -0,0 +1,7 @@
// expect: reject E7002
// phase: 6
// spec: docs/spec/15-source-language.md §10
module collection
fn bad(n: Missing) -> u32 effects [] { return n as u32; }
fn other(n: u64) -> u32 effects [] { return n as u32; }
fn main() -> void effects [] {}
@@ -0,0 +1,7 @@
// expect: reject E7002 E7005
// phase: 6
// spec: docs/spec/15-source-language.md §10
module collection
fn bad() -> void effects [] { for i in 0u64..2u64 { let text = b"abc"; let x = missing; } }
fn next(n: u64) -> u32 effects [] { return n as u32; }
fn main() -> void effects [] {}
@@ -0,0 +1,6 @@
// expect: reject E7001 E7001
// phase: 6
// spec: docs/spec/15-source-language.md §10
module collection
fn a<F: fn(u64) -> u64 effects []>() -> bool effects [] { return !false; }
fn main() -> bool effects [] { return !true; }
@@ -0,0 +1,7 @@
// expect: reject E7001 E7001 E7001
// phase: 6
// spec: docs/spec/15-source-language.md §10
module collection
fn a() -> bool effects [] { return !false; }
fn b() -> u64 effects [] { var x = 1u64; return x; }
fn main() -> void effects [] { let x = [zero; 3]; }
@@ -0,0 +1,3 @@
[{"kind":"boolean_negation","hint":"Aji boolean negation is `not`; integer complement is not boolean negation."}]
[{"kind":"annotate_var_type","hint":"Write an explicit type: `var name: T = expression;`. `let` may infer its type."}]
[{"kind":"zero_storage","hint":"`zero` is only a whole var initializer: `var name: T = zero;`; T must be zeroable."}]
@@ -0,0 +1,6 @@
// expect: reject E7001
// phase: 6
// spec: docs/spec/15-source-language.md §10
module collection
use other;
fn main() -> bool effects [] { return !true; }
@@ -0,0 +1,6 @@
// expect: reject E7001
// phase: 6
// spec: docs/spec/15-source-language.md §10
module collection
fn a() -> bool effects [] { return !false; };
fn main() -> bool effects [] { return !true; }
@@ -0,0 +1,7 @@
// expect: reject E7005 E7005
// phase: 6
// spec: docs/spec/15-source-language.md §10
module collection
fn a(n: u64) -> u32 effects [] { return n as u32; }
fn b(n: u64) -> u16 effects [] { return n as u16; }
fn main() -> void effects [] {}
@@ -0,0 +1,2 @@
[{"kind":"numeric_cast_modes","hint":"Choose `as!` for a checked conversion (T0006 on overflow) or `as%` for a wrapping conversion.","alternatives":["as!","as%"]}]
[{"kind":"numeric_cast_modes","hint":"Choose `as!` for a checked conversion (T0006 on overflow) or `as%` for a wrapping conversion.","alternatives":["as!","as%"]}]
@@ -0,0 +1,7 @@
// expect: reject E7001
// phase: 6
// spec: docs/spec/15-source-language.md §10
module collection
fn a() -> bool effects [] { let text = b"unterminated
return !false; }
fn main() -> bool effects [] { return !true; }
+11 -2
View File
@@ -26,7 +26,6 @@ with tempfile.TemporaryDirectory(prefix='aji-reasons-') as d:
('move_copy', 'struct S{x:u64} fn main()->u64 effects [] {let x=S{x:1u64};let y=move x;return 0u64;}'),
('move_copy', 'fn main()->u64 effects [] {let x=[1u64;2];let y=move x;return 0u64;}'),
('move_borrow', 'fn main()->u64 effects [] {let x=1u64;ref p=x;return move p;}'),
('invalid_move', 'fn f(x:void)->u64 effects [] {return move x;} fn main()->u64 effects [] {0u64}'),
('loop_control_outside_loop', 'fn main()->void effects [] {break;}'),
('zero_not_zeroable', 'fn main()->u64 effects [] {var x:own<u64> = zero;return 0u64;}'),
('value_block_statement', 'fn main()->i64 effects [] {{2i64} -3i64}'),
@@ -48,6 +47,15 @@ with tempfile.TemporaryDirectory(prefix='aji-reasons-') as d:
assert json.loads(invoke('lower', path, code=1)) == error
assert invoke('check', path, code=1) == invoke('check', path, code=1)
# Void parameters are rejected by annotation validation before body
# lowering; this must never be attributed to an invalid_move body error.
invalid_parameter = root / 'void-parameter.aji'
invalid_parameter.write_text('module reasons\nfn f(x:void)->u64 effects [] {return move x;} '
'fn main()->u64 effects [] {0u64}\n')
error = json.loads(invoke('check', invalid_parameter, code=1))
assert (error['code'], error['position'], error['type_constructor']) == ('E7005', 'param', 'void'), error
assert 'reason' not in error and json.loads(invoke('lower', invalid_parameter, code=1)) == error
# Copy substitution in a generic transfer is permitted, not a Copy-move
# diagnostic. Borrowed substitution still rejects with its own reason.
valid = root / 'generic.aji'
@@ -82,7 +90,8 @@ with tempfile.TemporaryDirectory(prefix='aji-reasons-') as d:
# Exercise all public standalone E7006 fixtures, without visiting any
# benchmark corpus or unrelated untracked directory.
registry = (REPO / 'docs/reference/error-codes.md').read_text()
reasons = set(re.findall(r'^\| `([a-z_]+)` \|', registry, re.M))
reason_section = registry.split('## E7006 reasons\n', 1)[1].split('\n## ', 1)[0]
reasons = set(re.findall(r'^\| `([a-z_]+)` \|', reason_section, re.M))
fixtures = 0
for path in sorted((REPO / 'tests/conformance/source').rglob('*.aji')):
if not re.search(r'^// expect: reject E7006\s*$', path.read_text(), re.M):
+4 -1
View File
@@ -212,7 +212,10 @@ with tempfile.TemporaryDirectory(prefix="aji-format-") as directory:
result = subprocess.run([str(AJI), "fmt", str(path)], capture_output=True)
checks += 1
if result.returncode == 1:
assert json.loads(result.stdout)["code"] == "E7001", (path, result.stdout, result.stderr)
diagnostics = [json.loads(line) for line in result.stdout.splitlines()]
assert diagnostics and len(diagnostics) <= 32, (path, result.stdout, result.stderr)
assert all(d["code"] == "E7001" for d in diagnostics), (path, diagnostics)
assert [json.loads(line) for line in cli("lower", path, code=1).splitlines()] == diagnostics, path
syntax_errors += 1
else:
assert result.returncode == 0, (path, result.returncode, result.stdout, result.stderr)
+98
View File
@@ -0,0 +1,98 @@
#!/usr/bin/env python3
"""Independent source errors, conservative boundaries, limits and no partial AIR."""
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/source/independent_errors'
checks = 0
def cli(*args, code=1):
global checks
result = subprocess.run([str(AJI), *map(str, args)], capture_output=True, text=True)
assert result.returncode == code, (args, result.returncode, result.stdout[:4000], result.stderr[:4000])
checks += 1
return result.stdout
def records(output):
return [json.loads(line) for line in output.splitlines()]
cache = REPO / '.zig-cache/contract-gate'
cache.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix='independent-', dir=cache) as directory:
root = Path(directory)
lib, entry, manifest = (root / name for name in ('lib.aji', 'main.aji', 'aji.toml'))
entry.write_text('module app\nimport lib.collection;\nfn main() -> void effects [] {}\n')
manifest.write_text('[package]\nname = "collection"\nversion = "1"\nentry = "main.aji"\n'
'[modules]\nlib.collection = "lib.aji"\n')
for path in sorted(CORPUS.glob('*.aji')):
source = path.read_text()
ds = records(cli('check', path))
wanted = re.search(r'// expect: reject (.+)', source)[1].split()
assert sorted(d['code'] for d in ds) == sorted(wanted), (path, ds)
assert len(ds) <= 32 and ds, ds
assert all(d['file'] == str(path) and 'air_line' not in d and 'air_code' not in d for d in ds), ds
# Exactly one diagnostic per code and source location, in declaration order.
assert len({(d['code'], d['file'], d['line'], d['col']) for d in ds}) == len(ds), ds
assert [(d['line'], d['col']) for d in ds] == sorted((d['line'], d['col']) for d in ds), ds
for command in ('lower', 'run', 'report', 'explore'):
assert records(cli(command, path)) == ds
assert records(cli('check', path)) == ds
if ds[0]['code'] == 'E7001':
for mode in ((), ('--check',), ('--write',)):
assert records(cli('fmt', *mode, path)) == ds
assert path.read_text() == source # failed fmt --write cannot modify input
if path.stem == 'three_syntax':
assert [d['repair_candidates'][0]['kind'] for d in ds] == [
'boolean_negation', 'annotate_var_type', 'zero_storage'], ds
elif path.stem in ('limit_syntax', 'limit_bodies'):
assert len(ds) == 32 and ds[-1]['line'] == 36, ds
elif path.stem == 'generic_body':
assert len(ds) == 1 and ds[0]['name'] == 'missing', ds
# Imported parser/body failures preserve the list, spans and advice.
if path.stem in ('three_syntax', 'two_types', 'callee', 'generic_body', 'state_reset'):
lib.write_text(source.replace('module collection', 'module lib.collection')
.replace('fn main(', 'fn user('))
package = records(cli('check', '--manifest', manifest))
assert package == [dict(d, file='lib.aji') for d in ds], package
for command in ('lower', 'run', 'report', 'explore'):
assert records(cli(command, '--manifest', manifest)) == package
# The first failed imported module stops traversal of siblings. Its syntax
# list is retained; a root syntax failure instead stops before imports.
second = root / 'other.aji'
second.write_text('module lib.other\nfn bad() -> bool effects [] { return !false; }\n')
lib.write_text('module lib.collection\nfn a() -> bool effects [] { return !false; }\n'
'fn b() -> bool effects [] { return !true; }\n')
entry.write_text('module app\nimport lib.collection;\nimport lib.other;\n'
'fn main() -> void effects [] {}\n')
manifest.write_text(manifest.read_text() + 'lib.other = "other.aji"\n')
ds = records(cli('check', '--manifest', manifest))
assert len(ds) == 2 and all(d['file'] == 'lib.aji' for d in ds), ds
entry.write_text(entry.read_text().replace('effects [] {}', 'effects [] { let x = !false; }'))
ds = records(cli('check', '--manifest', manifest))
assert len(ds) == 1 and ds[0]['file'] == str(entry), ds
# Unimplemented preserves the previous phase outcome when first, but does
# not suppress independent errors once body collection has begun.
probe = root / 'probe.aji'
unsupported = 'fn unsupported() -> void effects [] { 1u64(); }\n'
bad = 'fn bad(n: u64) -> u32 effects [] { return n as u32; }\n'
main = 'fn main() -> void effects [] {}\n'
probe.write_text('module probe\n' + unsupported + bad + main)
assert cli('check', probe, code=3) == ''
probe.write_text('module probe\n' + bad + unsupported +
'fn later(n: u64) -> u16 effects [] { return n as u16; }\n' + main)
ds = records(cli('check', probe))
assert [d['code'] for d in ds] == ['E7005', 'E7005'], ds
for command in ('lower', 'run', 'report', 'explore'):
assert records(cli(command, probe)) == ds
print(f'independent source errors: {checks} checks passed')
+2
View File
@@ -96,6 +96,8 @@ with tempfile.TemporaryDirectory(prefix='source-advice-', dir=cache) as director
'fn main() -> void effects [] { let mut x = 1u64; }',
'fn f(s: mut u64) -> void effects [] {}',
'fn f(s: ref [u8; 3]) -> void effects [] {}',
'fn f(s: mut.Other slice<u8>) -> void effects [] {}',
'fn f(s: ref.Other slice<u8>) -> void effects [] {}',
'fn f(s: &[u8; 3]) -> void effects [] {}',
'fn f(s: slice<u8>) -> void effects [] { ref t = s[..2usize]; }',
'fn f(s: slice<u8>) -> void effects [] { ref t = s[0usize..=2usize]; }',