From 2c6c7a3dcd968240635affaa128dbce73f6fb567 Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Fri, 9 Oct 2026 14:04:40 +0300 Subject: [PATCH] frontend: provide contextual source repair advice --- .github/workflows/ci.yml | 1 + CONTRIBUTING.md | 1 + docs/agent/quick-reference.md | 15 ++ docs/design/source-diagnostic-repair.md | 10 +- docs/plan/phase-6-source-language.md | 2 +- docs/reference/error-codes.md | 26 +++ .../spec/10-diagnostics-and-agent-protocol.md | 6 +- docs/spec/15-source-language.md | 2 + src/diag.zig | 126 ++++++++++++-- src/frontend.zig | 2 + src/frontend/lower.zig | 14 +- src/frontend/modules.zig | 1 + src/frontend/parse.zig | 120 ++++++++++++- tests/conformance/README.md | 2 + .../repair_advice/annotate_var_type.aji | 5 + .../annotate_var_type.aji.advice | 1 + .../source/repair_advice/boolean_negation.aji | 5 + .../repair_advice/boolean_negation.aji.advice | 1 + .../source/repair_advice/borrow_argument.aji | 6 + .../repair_advice/borrow_argument.aji.advice | 1 + .../source/repair_advice/borrow_binding.aji | 5 + .../repair_advice/borrow_binding.aji.advice | 1 + .../repair_advice/borrow_mut_argument.aji | 6 + .../borrow_mut_argument.aji.advice | 1 + .../source/repair_advice/canonical.aji | 21 +++ .../repair_advice/explicit_range_end.aji | 6 + .../explicit_range_end.aji.advice | 1 + .../repair_advice/numeric_cast_modes.aji | 6 + .../numeric_cast_modes.aji.advice | 1 + .../source/repair_advice/slice_mut_type.aji | 6 + .../repair_advice/slice_mut_type.aji.advice | 1 + .../source/repair_advice/slice_ref_type.aji | 6 + .../repair_advice/slice_ref_type.aji.advice | 1 + .../source/repair_advice/zero_storage.aji | 5 + .../repair_advice/zero_storage.aji.advice | 1 + tests/hosted/source_repair_advice.py | 158 ++++++++++++++++++ tools/conformance.zig | 13 ++ 37 files changed, 562 insertions(+), 24 deletions(-) create mode 100644 tests/conformance/source/repair_advice/annotate_var_type.aji create mode 100644 tests/conformance/source/repair_advice/annotate_var_type.aji.advice create mode 100644 tests/conformance/source/repair_advice/boolean_negation.aji create mode 100644 tests/conformance/source/repair_advice/boolean_negation.aji.advice create mode 100644 tests/conformance/source/repair_advice/borrow_argument.aji create mode 100644 tests/conformance/source/repair_advice/borrow_argument.aji.advice create mode 100644 tests/conformance/source/repair_advice/borrow_binding.aji create mode 100644 tests/conformance/source/repair_advice/borrow_binding.aji.advice create mode 100644 tests/conformance/source/repair_advice/borrow_mut_argument.aji create mode 100644 tests/conformance/source/repair_advice/borrow_mut_argument.aji.advice create mode 100644 tests/conformance/source/repair_advice/canonical.aji create mode 100644 tests/conformance/source/repair_advice/explicit_range_end.aji create mode 100644 tests/conformance/source/repair_advice/explicit_range_end.aji.advice create mode 100644 tests/conformance/source/repair_advice/numeric_cast_modes.aji create mode 100644 tests/conformance/source/repair_advice/numeric_cast_modes.aji.advice create mode 100644 tests/conformance/source/repair_advice/slice_mut_type.aji create mode 100644 tests/conformance/source/repair_advice/slice_mut_type.aji.advice create mode 100644 tests/conformance/source/repair_advice/slice_ref_type.aji create mode 100644 tests/conformance/source/repair_advice/slice_ref_type.aji.advice create mode 100644 tests/conformance/source/repair_advice/zero_storage.aji create mode 100644 tests/conformance/source/repair_advice/zero_storage.aji.advice create mode 100644 tests/hosted/source_repair_advice.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f006ca9..03a9bf0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -38,6 +38,7 @@ jobs: - run: python3 tests/hosted/source_nominal_queries.py - 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_cfg_provenance.py - run: python3 tools/source_reject_twins.py - run: python3 tests/hosted/source_reject_twins.py diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7e9eac8..4456d32 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -34,6 +34,7 @@ python3 tests/hosted/source_store_modes.py # exclusive places, source positions, python3 tests/hosted/source_nominal_queries.py # deep shared types, deterministic limits and package cache indices 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_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 diff --git a/docs/agent/quick-reference.md b/docs/agent/quick-reference.md index 479a855..539e131 100644 --- a/docs/agent/quick-reference.md +++ b/docs/agent/quick-reference.md @@ -4,6 +4,21 @@ Read this first; it covers most programs. Where to find the full rules is at the 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. +**If you know Rust:** use these Aji spellings. Rejected familiar syntax may carry a `repair_candidates` hint; cast alternatives require your choice. + +| Familiar spelling | Aji | +|---|---| +| `!condition` | `not condition` (boolean negation) | +| a narrowing `x as T` | `x as! T` checks/traps; `x as% T` wraps | +| `let mut x = value` / `var x = value` | `var x: T = value;` (type required) | +| immutable `let x = value` | `let x = value;` (type may be inferred) | +| mutable/shared slice type | `slice_mut` / `slice` | +| `s[start..]` | `s[start..end]` (explicit upper bound) | +| `f(&x)` / `f(&mut x)` | `f(ref x)` / `f(mut x)` | +| `let r = &x` / `let r = &mut x` | `ref r = x;` / `mut r = x;` | +| `[zero; N]` | `var storage: [T; N] = zero;` (zeroable T) | +| `-> ()` / implicit effects | `-> void effects [...]` | + ## 1. Skeleton ```aji diff --git a/docs/design/source-diagnostic-repair.md b/docs/design/source-diagnostic-repair.md index 5fda0e2..f3f236f 100644 --- a/docs/design/source-diagnostic-repair.md +++ b/docs/design/source-diagnostic-repair.md @@ -6,7 +6,7 @@ Non-normative work item following the owner's 2026-10-09 proposal. This does not The owner reports 15 GLM-5.3-flash sessions on four public dev tasks: of 52 rejected checks, the first diagnostic was E7001 in 30, E7005 in 10 and E7006 in six. Missing var annotations, lossy casts and Rust-style negation were frequent. These aggregates are supplied observations, not independently audited runs. First-code counts are not counts of all errors; one model family does not establish a language-inference policy. No task implementation, private corpus or frozen experiment is inspected or changed for this investigation. The proposed threefold reduction in E7001 checks is an experiment target, not a demonstrated effect. -Twelve minimal current-language probes confirm: prefix `!`, missing var type, `mut slice`/`ref slice`, an omitted range end, `[zero; N]` and `&` in arguments/bindings reject E7001; a lossy widening cast rejects E7005. Three syntactically invalid functions yield one E7001; two independently invalid casts yield one E7005. Crucially, `let x = 1u64` already accepts: let inference is specified, and its annotation must not be demanded by a repair hint. These are generic syntax probes, not dev-task reproductions. +Twelve minimal current-language probes confirm: prefix `!`, missing var type, `mut slice`/`ref slice`, an omitted range end, `[zero; N]` and `&` in arguments/bindings reject E7001; a non-widening integer cast rejects E7005. Three syntactically invalid functions yield one E7001; two independently invalid casts yield one E7005. Crucially, `let x = 1u64` already accepts: let inference is specified, and its annotation must not be demanded by a repair hint. These are generic syntax probes, not dev-task reproductions. ## First increment: explicit advice without syntax aliases @@ -40,3 +40,11 @@ Preserve one diagnostic per code/source location and the E7900 rule replacing al 4. Have the evaluation owner rerun public dev tasks after the changes; retain both first-code and full diagnostic counts, model/tool settings and frozen input identities. Do not modify a frozen matrix in place. Var inference remains an optional language-policy question. No change is adopted from these aggregates; the first increment can reduce repair burden while retaining explicit var annotations. Contract research and its full P6-6 exit criterion remain open. + +## First increment delivered (2026-10-09) + +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. + +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. diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index 62a1e99..e69da46 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -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 (design/verification) | 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 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-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 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 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. diff --git a/docs/reference/error-codes.md b/docs/reference/error-codes.md index 3ddf62a..874ee1f 100644 --- a/docs/reference/error-codes.md +++ b/docs/reference/error-codes.md @@ -112,6 +112,32 @@ Reported in trap records (spec 01 §6), not by the verifier. | T0009 | trap.unsafe_precondition | Unsafe precondition violated (detected) | | T0010 | trap.foreign_iref | An `iref` was used to access a graph it does not belong to | +## Source repair candidate kinds + +These stable kinds use spec 10 §3. `hint` MUST equal the registered text. Alternatives, when present, MUST use the unit below; hints alone are not replacements. Advice is selected at the rejecting rule, never by parsing diagnostic prose. Existing illustrative/non-source kinds are outside this registry. + +| Kind | Code | Hint | Alternatives unit | +|---|---|---|---| +| `boolean_negation` | E7001 | Aji boolean negation is `not`; integer complement is not boolean negation. | none | +| `annotate_var_type` | E7001 | Write an explicit type: `var name: T = expression;`. `let` may infer its type. | none | +| `slice_mut_type` | E7001 | Write `slice_mut` for a mutable slice type. | complete type | +| `slice_ref_type` | E7001 | Write `slice` for a shared slice type. | complete type | +| `explicit_range_end` | E7001 | Write both slice bounds: `receiver[start..end]`; choose the upper bound explicitly. | none | +| `borrow_argument` | E7001 | Write `ref place` or `mut place` for an inline borrow argument. | prefix | +| `borrow_binding` | E7001 | Bind a borrow with `ref name = place;` or `mut name = place;`, rather than a let/var initializer. | none | +| `zero_storage` | E7001 | `zero` is only a whole var initializer: `var name: T = zero;`; T must be zeroable. | none | +| `numeric_cast_modes` | E7005 | Choose `as!` for a checked conversion (T0006 on overflow) or `as%` for a wrapping conversion. | operator | + +Closed applicability: + +- `boolean_negation`: lone `!` rejected at primary-expression start. Excludes `!=`, `as!` and `!` rejected after an expression (such as `panic!()`). It does not assert that the operand is boolean. +- `annotate_var_type`: `=` found where a `var` declaration requires its type colon. No advice for `let`, a missing name or other found tokens; no initializer type is guessed. +- Slice type kinds: a bare `mut`/`ref` parsed in type position immediately followed by `slice`. Attach at that `slice` token, retaining the caller's expected token. Emit one complete-type alternative only if the following `slice<...>` fragment parses as a single-argument slice type. Keep its token spellings (including nested types), remove comments/whitespace and separate adjacent word/number tokens by one space; replace the outer spelling by `slice_mut`/`slice` respectively. An incomplete/malformed fragment has hint only. Speculative parsing MUST NOT mutate the original tokens, including `>>`. +- `explicit_range_end`: `]` immediately after `..` in index syntax. No advice for an omitted start, inclusive `..=`, missing for-loop bound or another malformed expression. No receiver or `.len` alternative is guessed. +- Borrow kinds: `&` rejected as the first token of a call argument, excluding enum variant payloads (`borrow_argument`) or let/typed-var initializer (`borrow_binding`). Other expression contexts, including the second `&` in `a && b`, have no borrow advice. For an argument whose following token is an ordinary identifier, emit `["ref"]`; for `&mut` followed by an ordinary identifier, emit `["mut"]`. Other operands have hint only, including `&&x`. These prefixes do not imply that the referent/mode verifies; binding advice has no prefix alternative. +- `zero_storage`: keyword `zero` rejected at primary-expression start. Accepted typed-var zero initialization has no advice. +- `numeric_cast_modes`: integer `as` rejected by the lossless-widening rule, with unchanged `from`/`to`. Alternatives MUST be `["as!", "as%"]`. Non-integer casts and other E7005 rules have no such candidate. + ## E7006 reasons These stable categories are part of the diagnostic API (spec 15 §10), not new rejection rules. One reason is selected at the rejection site; messages remain optional explanation. diff --git a/docs/spec/10-diagnostics-and-agent-protocol.md b/docs/spec/10-diagnostics-and-agent-protocol.md index eaa1885..25a6193 100644 --- a/docs/spec/10-diagnostics-and-agent-protocol.md +++ b/docs/spec/10-diagnostics-and-agent-protocol.md @@ -45,7 +45,7 @@ Example: ## 3. Repair candidates -The compiler may emit structured suggestions: +The compiler MAY emit structured suggestions. The following kinds are illustrative: ```json { @@ -58,6 +58,10 @@ The compiler may emit structured suggestions: Suggestions never modify semantics automatically. +Each `repair_candidates` element MUST have string `kind`; it MAY additionally have string `hint` and a nonempty ordered array of strings `alternatives`. Serialization order MUST be `kind`, then `hint`, then `alternatives`; absent optional members MUST be omitted. Existing kind-only objects remain valid. Alternatives are spellings for the construct/unit registered for that kind, not byte edits or a claim that the repaired program verifies. Their order MUST be deterministic and implies no preference. In particular, choosing a checked versus wrapping cast remains the agent's semantic decision. Agents MUST select advice by `kind`, not by parsing `hint` or `message`. + +Source advice kinds, fixed hints, applicability and alternative units are registered in `reference/error-codes.md`. An E7001/E7005 diagnostic MUST NOT carry more than one registered source advice candidate; when a registered trigger applies, it MUST carry exactly that candidate. Advice MUST come from the rejecting parser/type rule, MUST NOT change accepted syntax or inference, and MUST preserve the existing code, location, payload and message. Imported source and formatter syntax failures MUST carry the same applicable advice; E7900 replacement MUST discard it. + ## 4. ajid `ajid` is the long-running machine interface. diff --git a/docs/spec/15-source-language.md b/docs/spec/15-source-language.md index 9835bea..6aaa250 100644 --- a/docs/spec/15-source-language.md +++ b/docs/spec/15-source-language.md @@ -391,6 +391,8 @@ A byte string or array used where a `slice` 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. + | Problem | Code | |---|---| | found by the verifier on the lowered AIR | the AIR code; the diagnostic's `file`, `line` and `col` are the source location of the construct the instruction came from, and `air_line`/`air_col` locate it in the lowered AIR (`aji lower`); the verifier's own fields (`function`, `block`, `inst`) are kept | diff --git a/src/diag.zig b/src/diag.zig index 6824928..8fadf51 100644 --- a/src/diag.zig +++ b/src/diag.zig @@ -157,6 +157,81 @@ pub const Field = struct { }; }; +pub const RepairCandidate = struct { + kind: []const u8, + hint: []const u8 = "", + alternatives: []const []const u8 = &.{}, +}; + +/// Shared serialization for the envelope and conformance advice goldens. +pub fn writeRepairCandidates(candidates: []const RepairCandidate, s: *std.json.Stringify) std.Io.Writer.Error!void { + try s.beginArray(); + for (candidates) |candidate| { + try s.beginObject(); + try s.objectField("kind"); + try s.write(candidate.kind); + if (candidate.hint.len != 0) { + try s.objectField("hint"); + try s.write(candidate.hint); + } + if (candidate.alternatives.len != 0) { + try s.objectField("alternatives"); + try s.write(candidate.alternatives); + } + try s.endObject(); + } + try s.endArray(); +} + +/// Closed source advice registry (reference/error-codes.md). Text is fixed; +/// agents select by kind, never by interpreting the hint. +pub const SourceRepairKind = enum { + boolean_negation, + annotate_var_type, + slice_mut_type, + slice_ref_type, + explicit_range_end, + borrow_argument, + borrow_binding, + zero_storage, + numeric_cast_modes, + + pub fn hint(kind: SourceRepairKind) []const u8 { + return switch (kind) { + .boolean_negation => "Aji boolean negation is `not`; integer complement is not boolean negation.", + .annotate_var_type => "Write an explicit type: `var name: T = expression;`. `let` may infer its type.", + .slice_mut_type => "Write `slice_mut` for a mutable slice type.", + .slice_ref_type => "Write `slice` for a shared slice type.", + .explicit_range_end => "Write both slice bounds: `receiver[start..end]`; choose the upper bound explicitly.", + .borrow_argument => "Write `ref place` or `mut place` for an inline borrow argument.", + .borrow_binding => "Bind a borrow with `ref name = place;` or `mut name = place;`, rather than a let/var initializer.", + .zero_storage => "`zero` is only a whole var initializer: `var name: T = zero;`; T must be zeroable.", + .numeric_cast_modes => "Choose `as!` for a checked conversion (T0006 on overflow) or `as%` for a wrapping conversion.", + }; + } + + pub fn code(kind: SourceRepairKind) []const u8 { + return if (kind == .numeric_cast_modes) "E7005" else "E7001"; + } + + pub fn unit(kind: SourceRepairKind) []const u8 { + return switch (kind) { + .slice_mut_type, .slice_ref_type => "complete type", + .borrow_argument => "prefix", + .numeric_cast_modes => "operator", + else => "none", + }; + } + + pub fn candidate(kind: SourceRepairKind, alternatives: []const []const u8) RepairCandidate { + return .{ .kind = @tagName(kind), .hint = kind.hint(), .alternatives = alternatives }; + } + + pub fn one(comptime kind: SourceRepairKind) []const RepairCandidate { + return comptime &.{kind.candidate(if (kind == .numeric_cast_modes) &.{ "as!", "as%" } else &.{})}; + } +}; + pub const Diagnostic = struct { code: *const Code, severity: Severity = .@"error", @@ -165,7 +240,7 @@ pub const Diagnostic = struct { message: []const u8 = "", fields: []const Field = &.{}, /// Non-binding structured suggestions (spec 10 §3). - repair_candidates: []const []const u8 = &.{}, + repair_candidates: []const RepairCandidate = &.{}, related_locations: []const RelatedLocation = &.{}, /// Writes the diagnostic as a single JSON object (no trailing newline). @@ -199,14 +274,7 @@ pub const Diagnostic = struct { } if (d.repair_candidates.len != 0) { try s.objectField("repair_candidates"); - try s.beginArray(); - for (d.repair_candidates) |kind| { - try s.beginObject(); - try s.objectField("kind"); - try s.write(kind); - try s.endObject(); - } - try s.endArray(); + try writeRepairCandidates(d.repair_candidates, &s); } if (d.related_locations.len != 0) { try s.objectField("related_locations"); @@ -249,7 +317,7 @@ test "writeJson is deterministic and structured" { .{ .name = "value", .value = .{ .str = "%17" } }, .{ .name = "expected_generation", .value = .{ .int = 5 } }, }, - .repair_candidates = &.{"move_reset_after_use"}, + .repair_candidates = &.{.{ .kind = "move_reset_after_use" }}, }; try d.writeJson(&w); try std.testing.expectEqualStrings( @@ -265,7 +333,7 @@ test "related locations are typed, ordered and appended after existing fields" { .span = .{ .file = "main.aji", .line = 9, .col = 5 }, .fields = &.{.{ .name = "conflicts_with", .value = .{ .str = "%view_4" } }}, .message = "conflict", - .repair_candidates = &.{"example"}, + .repair_candidates = &.{.{ .kind = "example" }}, .related_locations = &.{.{ .role = .conflicting_borrow, .value = "%view_4", @@ -335,6 +403,42 @@ test "registry ids are unique" { } } +test "source repair registry mirrors kinds, codes, hints and units" { + const md = @embedFile("error_codes_md"); + const heading = "## Source repair candidate kinds\n"; + const start = (std.mem.indexOf(u8, md, heading) orelse return error.RegistryOutOfSync) + heading.len; + const section = md[start..]; + const end = std.mem.indexOf(u8, section, "\n## ") orelse section.len; + var lines = std.mem.splitScalar(u8, section[0..end], '\n'); + var seen: std.EnumSet(SourceRepairKind) = .empty; + while (lines.next()) |line| { + if (!std.mem.startsWith(u8, line, "| `")) continue; + var cols = std.mem.tokenizeScalar(u8, line, '|'); + const name = std.mem.trim(u8, cols.next().?, " `"); + const kind = std.meta.stringToEnum(SourceRepairKind, name) orelse return error.RegistryOutOfSync; + try std.testing.expect(!seen.contains(kind)); + seen.insert(kind); + try std.testing.expectEqualStrings(kind.code(), std.mem.trim(u8, cols.next().?, " ")); + try std.testing.expectEqualStrings(kind.hint(), std.mem.trim(u8, cols.next().?, " ")); + try std.testing.expectEqualStrings(kind.unit(), std.mem.trim(u8, cols.next().?, " ")); + try std.testing.expect(cols.next() == null); + } + try std.testing.expect(seen.eql(.full)); +} + +test "repair hints and alternatives escape JSON with deterministic member order" { + var out: std.Io.Writer.Allocating = .init(std.testing.allocator); + defer out.deinit(); + const d: Diagnostic = .{ + .code = lookup("E7001").?, + .repair_candidates = &.{.{ .kind = "example", .hint = "quote \" and newline\n", .alternatives = &.{ "a\\b", "c" } }}, + }; + try d.writeJson(&out.writer); + try std.testing.expectEqualStrings( + \\{"code":"E7001","kind":"source.syntax","severity":"error","repair_candidates":[{"kind":"example","hint":"quote \" and newline\n","alternatives":["a\\b","c"]}]} + , out.written()); +} + test "E7006 reason registry mirrors documentation" { const md = @embedFile("error_codes_md"); const heading = "## E7006 reasons\n"; diff --git a/src/frontend.zig b/src/frontend.zig index d8d7d0f..e5d3588 100644 --- a/src/frontend.zig +++ b/src/frontend.zig @@ -52,6 +52,7 @@ pub fn compileWithModules(arena: std.mem.Allocator, file: []const u8, source: [] .span = .{ .file = p.span.file orelse file, .line = p.span.start.line, .col = p.span.start.col }, .message = p.message, .fields = fields, + .repair_candidates = p.repair_candidates, } }; }, .unimplemented => |u| .{ .unimplemented = try std.fmt.allocPrint(arena, "{s}:{d}:{d}: {s}", .{ u.span.file orelse file, u.span.start.line, u.span.start.col, u.construct }) }, @@ -63,6 +64,7 @@ pub fn syntaxDiagnostic(arena: std.mem.Allocator, file: []const u8, f: parse.Fai .code = diag.lookup("E7001").?, .span = .{ .file = file, .line = f.pos.line, .col = f.pos.col }, .message = try std.fmt.allocPrint(arena, "expected {s}", .{f.expected}), + .repair_candidates = f.repair_candidates, .fields = try arena.dupe(diag.Field, &.{ .{ .name = "expected", .value = .{ .str = f.expected } }, .{ .name = "found", .value = .{ .str = f.found } }, diff --git a/src/frontend/lower.zig b/src/frontend/lower.zig index 6a7f914..4c08631 100644 --- a/src/frontend/lower.zig +++ b/src/frontend/lower.zig @@ -150,6 +150,7 @@ pub const Problem = struct { span: Span, message: []const u8, fields: []const Field = &.{}, + repair_candidates: []const @import("../diag.zig").RepairCandidate = &.{}, pub const Field = struct { name: []const u8, value: []const u8 }; }; @@ -364,6 +365,17 @@ const Lowerer = struct { return error.Lower; } + fn invalidWidening(l: *Lowerer, span: Span, fields: []const Problem.Field) Error { + l.problem = .{ + .code = "E7005", + .span = span, + .message = "`as` only widens without loss; use `as!` (checked, traps T0006 when the value does not fit) or `as%` (wrapping)", + .fields = try l.arena.dupe(Problem.Field, fields), + .repair_candidates = @import("../diag.zig").SourceRepairKind.one(.numeric_cast_modes), + }; + return error.Lower; + } + fn notYet(l: *Lowerer, span: Span, construct: []const u8) Error { l.unimpl = .{ .span = span, .construct = construct }; return error.Unimplemented; @@ -1678,7 +1690,7 @@ const Lowerer = struct { const a = std.meta.stringToEnum(air_module.IntType, v.ty.int).?; const b = std.meta.stringToEnum(air_module.IntType, to.int).?; if (a != b and !verifier_types.lossless(a, b)) - return l.fail("E7005", e.span, "`as` only widens without loss; use `as!` (checked, traps T0006 when the value does not fit) or `as%` (wrapping)", &.{ .{ .name = "from", .value = v.ty.int }, .{ .name = "to", .value = to.int } }); + return l.invalidWidening(e.span, &.{ .{ .name = "from", .value = v.ty.int }, .{ .name = "to", .value = to.int } }); } const mode = switch (x.mode) { .widen => "widen", diff --git a/src/frontend/modules.zig b/src/frontend/modules.zig index 230c666..4cbabbe 100644 --- a/src/frontend/modules.zig +++ b/src/frontend/modules.zig @@ -123,6 +123,7 @@ const Graph = struct { .span = .{ .start = failure.pos, .end = failure.pos, .file = source.file, .namespace = source.name }, .message = try std.fmt.allocPrint(g.arena, "expected {s}", .{failure.expected}), .fields = try g.arena.dupe(lower.Problem.Field, &.{ .{ .name = "expected", .value = failure.expected }, .{ .name = "found", .value = failure.found } }), + .repair_candidates = if (std.mem.startsWith(u8, source.name, "std.")) &.{} else failure.repair_candidates, }; return error.InvalidSource; }, diff --git a/src/frontend/parse.zig b/src/frontend/parse.zig index 9988727..42ea3aa 100644 --- a/src/frontend/parse.zig +++ b/src/frontend/parse.zig @@ -5,12 +5,18 @@ const std = @import("std"); const lex = @import("lex.zig"); const ast = @import("ast.zig"); +const diag = @import("../diag.zig"); const Allocator = std.mem.Allocator; const Tag = lex.Tag; const Token = lex.Token; -pub const Failure = struct { pos: lex.Pos, expected: []const u8, found: []const u8 }; +pub const Failure = struct { + pos: lex.Pos, + expected: []const u8, + found: []const u8, + repair_candidates: []const diag.RepairCandidate = &.{}, +}; pub const Result = union(enum) { ok: ast.Module, err: Failure }; @@ -41,6 +47,11 @@ const Parser = struct { module_name: ?[]const u8 = null, /// Struct literals are not allowed where a `{` starts a block (conditions). no_struct: bool = false, + /// Hints are attached only at the exact token where the original parser + /// fails, preserving caller-specific expected/found and source positions. + type_advice: ?struct { at: usize, kind: diag.SourceRepairKind } = null, + borrow_advice: ?struct { at: usize, kind: diag.SourceRepairKind } = null, + speculative: bool = false, fn peek(p: *Parser) Token { return p.tokens[p.pos]; @@ -65,9 +76,96 @@ const Parser = struct { fn fail(p: *Parser, t: Token, expected: []const u8) Error { p.failure = .{ .pos = t.pos, .expected = expected, .found = if (t.tag == .eof) "end of file" else t.text }; + if (p.type_advice) |a| if (a.at == p.pos) { + p.failure.?.repair_candidates = try p.sliceAdvice(a.kind); + }; return error.Syntax; } + fn failAdvice(p: *Parser, t: Token, expected: []const u8, comptime kind: diag.SourceRepairKind) Error { + const err = p.fail(t, expected); + if (err == error.Syntax) p.failure.?.repair_candidates = kind.one(); + return err; + } + + /// The invalid type is already rejected. Copy only its angle-balanced + /// fragment for speculative validation; closeAngle may split >> in place. + /// Never consume or rewrite the real parser's tokens. + fn sliceAdvice(p: *Parser, kind: diag.SourceRepairKind) Error![]const diag.RepairCandidate { + var candidate = kind.candidate(&.{}); + if (p.peekAt(1).tag == .lt) fragment: { + var depth: usize = 0; + var end = p.pos + 1; + var half = false; + while (end < p.tokens.len) : (end += 1) { + switch (p.tokens[end].tag) { + .lt => depth += 1, + .gt, .shr => { + const closes: usize = if (p.tokens[end].tag == .shr) 2 else 1; + if (depth <= closes) { + half = depth == 1 and closes == 2; + break; + } + depth -= closes; + }, + .eof, .l_brace, .r_brace, .eq => break :fragment, + else => {}, + } + } + if (end == p.tokens.len) break :fragment; + const count = end - p.pos + 1; + const tokens = try p.arena.alloc(Token, count + 1); + @memcpy(tokens[0..count], p.tokens[p.pos .. end + 1]); + if (half) { + tokens[count - 1].tag = .gt; + tokens[count - 1].text = tokens[count - 1].text[0..1]; + tokens[count - 1].end.col = tokens[count - 1].pos.col + 1; + } + tokens[count] = .{ .tag = .eof, .text = "", .pos = tokens[count - 1].end, .end = tokens[count - 1].end }; + var q: Parser = .{ .arena = p.arena, .tokens = tokens, .speculative = true }; + const ty = q.typeExpr() catch |err| switch (err) { + error.Syntax => break :fragment, + error.OutOfMemory => return error.OutOfMemory, + }; + if (q.peek().tag != .eof or ty.kind != .wrapped or !std.mem.eql(u8, ty.kind.wrapped.wrapper, "slice")) break :fragment; + // Render from an unmodified fragment: speculative parsing may have + // split its private >> tokens, so use the original token spellings. + var text: std.ArrayList(u8) = .empty; + try text.appendSlice(p.arena, if (kind == .slice_mut_type) "slice_mut" else "slice"); + var previous: Tag = .ident; + for (p.tokens[p.pos + 1 .. end + 1], 0..) |token, i| { + if ((previous == .ident or previous == .int) and (token.tag == .ident or token.tag == .int)) try text.append(p.arena, ' '); + try text.appendSlice(p.arena, if (half and i == count - 2) token.text[0..1] else token.text); + previous = token.tag; + } + candidate.alternatives = try p.arena.dupe([]const u8, &.{text.items}); + } + return try p.arena.dupe(diag.RepairCandidate, &.{candidate}); + } + + fn exprWithBorrowAdvice(p: *Parser, kind: diag.SourceRepairKind) Error!ast.Expr { + const saved = p.borrow_advice; + p.borrow_advice = .{ .at = p.pos, .kind = kind }; + defer p.borrow_advice = saved; + return p.expr(); + } + + fn failPrimary(p: *Parser, t: Token) Error { + if (t.tag == .invalid and std.mem.eql(u8, t.text, "!")) return p.failAdvice(t, "an expression", .boolean_negation); + if (isWord(t, "zero")) return p.failAdvice(t, "an expression", .zero_storage); + if (t.tag == .amp) if (p.borrow_advice) |a| if (a.at == p.pos) { + var alternatives: []const []const u8 = &.{}; + if (a.kind == .borrow_argument) { + const mutable = isWord(p.peekAt(1), "mut"); + const place = p.peekAt(if (mutable) 2 else 1); + if (place.tag == .ident and !isKeyword(place.text)) alternatives = if (mutable) &.{"mut"} else &.{"ref"}; + } + p.failure = .{ .pos = t.pos, .expected = "an expression", .found = t.text, .repair_candidates = try p.arena.dupe(diag.RepairCandidate, &.{a.kind.candidate(alternatives)}) }; + return error.Syntax; + }; + return p.fail(t, "an expression"); + } + fn expect(p: *Parser, tag: Tag, what: []const u8) Error!Token { const t = p.peek(); if (t.tag != tag) return p.fail(t, what); @@ -261,6 +359,8 @@ const Parser = struct { if (t.tag != .ident) return p.fail(t, "a type"); _ = p.next(); const name = if (p.peek().tag == .dot) try p.pathTail(t.text) else t.text; + if (!p.speculative and (isWord(t, "mut") or isWord(t, "ref")) and p.atWord("slice")) + p.type_advice = .{ .at = p.pos, .kind = if (isWord(t, "mut")) .slice_mut_type else .slice_ref_type }; if (p.peek().tag != .lt) return .{ .span = p.span(start), .kind = .{ .name = name } }; if (std.mem.eql(u8, name, "cap") or std.mem.eql(u8, name, "file")) { _ = p.next(); @@ -394,7 +494,7 @@ const Parser = struct { ty = try p.typeExpr(); } _ = try p.expect(.eq, "`=`"); - const e = try p.expr(); + const e = try p.exprWithBorrowAdvice(.borrow_binding); _ = try p.expect(.semicolon, "`;`"); return .{ .span = p.span(start), .kind = .{ .let = .{ .names = names.items, .ty = ty, .e = e, .tuple = tuple } } }; } @@ -411,13 +511,14 @@ const Parser = struct { if (isWord(t, "var")) { _ = p.next(); const name = try p.ident("a name"); + if (p.peek().tag == .eq) return p.failAdvice(p.peek(), "`:` and the variable's type", .annotate_var_type); _ = try p.expect(.colon, "`:` and the variable's type"); const ty = try p.typeExpr(); _ = try p.expect(.eq, "`=`"); var init: ?ast.Expr = null; if (p.atWord("zero")) { _ = p.next(); - } else init = try p.expr(); + } else init = try p.exprWithBorrowAdvice(.borrow_binding); _ = try p.expect(.semicolon, "`;`"); return .{ .span = p.span(start), .kind = .{ .@"var" = .{ .name = name, .ty = ty, .init = init } } }; } @@ -783,7 +884,7 @@ const Parser = struct { _ = p.next(); const ty = try p.typeExpr(); try p.closeAngle(); - const args = try p.callArgs(); + const args = try p.callArgs(true); const callee = try p.box(ast.Expr, e); e = .{ .span = p.span(start), .kind = .{ .call = .{ .callee = callee, .type_arg = ty, .args = args } } }; } @@ -801,7 +902,7 @@ const Parser = struct { .l_paren => { if (e.kind == .variant and p.peekAt(1).tag == .r_paren) return p.fail(p.peek(), "payload values or no parentheses for a payload-free variant"); - const args = try p.callArgs(); + const args = try p.callArgs(e.kind != .variant); const callee = try p.box(ast.Expr, e); e = .{ .span = p.span(start), .kind = .{ .call = .{ .callee = callee, .type_arg = null, .args = args } } }; }, @@ -813,6 +914,7 @@ const Parser = struct { var hi: ?*const ast.Expr = null; if (p.peek().tag == .dot_dot) { _ = p.next(); + if (p.peek().tag == .r_bracket) return p.failAdvice(p.peek(), "an expression", .explicit_range_end); hi = try p.box(ast.Expr, try p.expr()); } p.no_struct = saved; @@ -826,14 +928,14 @@ const Parser = struct { } } - fn callArgs(p: *Parser) Error![]const ast.Expr { + fn callArgs(p: *Parser, borrow_arguments: bool) Error![]const ast.Expr { _ = try p.expect(.l_paren, "`(`"); const saved = p.no_struct; p.no_struct = false; defer p.no_struct = saved; var args: std.ArrayList(ast.Expr) = .empty; while (p.peek().tag != .r_paren) { - try args.append(p.arena, try p.expr()); + try args.append(p.arena, if (borrow_arguments) try p.exprWithBorrowAdvice(.borrow_argument) else try p.expr()); if (p.peek().tag != .comma) break; _ = p.next(); } @@ -950,7 +1052,7 @@ const Parser = struct { }; return .{ .span = p.span(start), .kind = .{ .match_expr = try p.box(ast.Match, .{ .scrutinee = scrut, .arms = as, .span = p.span(start), .kind = kind }) } }; } - if (isKeyword(t.text) and !(isWord(t, "struct") and p.peekAt(1).tag == .dot and isWord(p.peekAt(2), "unpack"))) return p.fail(t, "an expression"); + if (isKeyword(t.text) and !(isWord(t, "struct") and p.peekAt(1).tag == .dot and isWord(p.peekAt(2), "unpack"))) return p.failPrimary(t); _ = p.next(); if (p.peek().tag == .colon_colon and p.peekAt(1).tag != .lt) { _ = p.next(); @@ -962,7 +1064,7 @@ const Parser = struct { } return .{ .span = p.span(start), .kind = .{ .name = t.text } }; }, - else => return p.fail(t, "an expression"), + else => return p.failPrimary(t), } } diff --git a/tests/conformance/README.md b/tests/conformance/README.md index 7bffe15..d242462 100644 --- a/tests/conformance/README.md +++ b/tests/conformance/README.md @@ -42,6 +42,8 @@ A key is a single lowercase word; header lines without a `key:` prefix are free- `reject` compares the exact multiset of error codes. Listing a code twice means two diagnostics with that code are expected. +For a source test, optional `.aji.advice` pins structured repair advice: one compact JSON array of `repair_candidates` per diagnostic, in diagnostic order, each followed by a newline. A diagnostic without advice writes `[]`; a program without diagnostics writes no lines. The golden compares exact kinds, hints, alternatives and member order using the CLI's serializer. Source positions and CLI/package parity are additionally checked by the hosted tests. + ## AIR/source rejection twins (P6-7) `python3 tools/source_reject_twins.py` checks audited pairs declared by free-form `// AIR twin: ` comments in source tests. These comments are separate from `equivalent`, which applies only to runs. `reject-twins.json` records each reviewed rule, governing spec and diagnostic site; a matching code alone does not establish a twin. diff --git a/tests/conformance/source/repair_advice/annotate_var_type.aji b/tests/conformance/source/repair_advice/annotate_var_type.aji new file mode 100644 index 0000000..232ce37 --- /dev/null +++ b/tests/conformance/source/repair_advice/annotate_var_type.aji @@ -0,0 +1,5 @@ +// expect: reject E7001 +// phase: 6 +// spec: docs/spec/15-source-language.md §10; docs/spec/10-diagnostics-and-agent-protocol.md §3 +module advice +fn main() -> u64 effects [] { var x = 1u64; return x; } diff --git a/tests/conformance/source/repair_advice/annotate_var_type.aji.advice b/tests/conformance/source/repair_advice/annotate_var_type.aji.advice new file mode 100644 index 0000000..eeb25a0 --- /dev/null +++ b/tests/conformance/source/repair_advice/annotate_var_type.aji.advice @@ -0,0 +1 @@ +[{"kind":"annotate_var_type","hint":"Write an explicit type: `var name: T = expression;`. `let` may infer its type."}] diff --git a/tests/conformance/source/repair_advice/boolean_negation.aji b/tests/conformance/source/repair_advice/boolean_negation.aji new file mode 100644 index 0000000..9ad1659 --- /dev/null +++ b/tests/conformance/source/repair_advice/boolean_negation.aji @@ -0,0 +1,5 @@ +// expect: reject E7001 +// phase: 6 +// spec: docs/spec/15-source-language.md §10; docs/spec/10-diagnostics-and-agent-protocol.md §3 +module advice +fn main() -> bool effects [] { return !false; } diff --git a/tests/conformance/source/repair_advice/boolean_negation.aji.advice b/tests/conformance/source/repair_advice/boolean_negation.aji.advice new file mode 100644 index 0000000..ed7d104 --- /dev/null +++ b/tests/conformance/source/repair_advice/boolean_negation.aji.advice @@ -0,0 +1 @@ +[{"kind":"boolean_negation","hint":"Aji boolean negation is `not`; integer complement is not boolean negation."}] diff --git a/tests/conformance/source/repair_advice/borrow_argument.aji b/tests/conformance/source/repair_advice/borrow_argument.aji new file mode 100644 index 0000000..598e62c --- /dev/null +++ b/tests/conformance/source/repair_advice/borrow_argument.aji @@ -0,0 +1,6 @@ +// expect: reject E7001 +// phase: 6 +// spec: docs/spec/15-source-language.md §10; docs/spec/10-diagnostics-and-agent-protocol.md §3 +module advice +fn f(s: ref) -> void effects [] {} +fn main() -> void effects [] { var x: u64 = 1u64; f(&x); } diff --git a/tests/conformance/source/repair_advice/borrow_argument.aji.advice b/tests/conformance/source/repair_advice/borrow_argument.aji.advice new file mode 100644 index 0000000..7af88ed --- /dev/null +++ b/tests/conformance/source/repair_advice/borrow_argument.aji.advice @@ -0,0 +1 @@ +[{"kind":"borrow_argument","hint":"Write `ref place` or `mut place` for an inline borrow argument.","alternatives":["ref"]}] diff --git a/tests/conformance/source/repair_advice/borrow_binding.aji b/tests/conformance/source/repair_advice/borrow_binding.aji new file mode 100644 index 0000000..0074b17 --- /dev/null +++ b/tests/conformance/source/repair_advice/borrow_binding.aji @@ -0,0 +1,5 @@ +// expect: reject E7001 +// phase: 6 +// spec: docs/spec/15-source-language.md §10; docs/spec/10-diagnostics-and-agent-protocol.md §3 +module advice +fn main() -> void effects [] { var x: u64 = 1u64; let r = &x; } diff --git a/tests/conformance/source/repair_advice/borrow_binding.aji.advice b/tests/conformance/source/repair_advice/borrow_binding.aji.advice new file mode 100644 index 0000000..698b3fa --- /dev/null +++ b/tests/conformance/source/repair_advice/borrow_binding.aji.advice @@ -0,0 +1 @@ +[{"kind":"borrow_binding","hint":"Bind a borrow with `ref name = place;` or `mut name = place;`, rather than a let/var initializer."}] diff --git a/tests/conformance/source/repair_advice/borrow_mut_argument.aji b/tests/conformance/source/repair_advice/borrow_mut_argument.aji new file mode 100644 index 0000000..a0d30b5 --- /dev/null +++ b/tests/conformance/source/repair_advice/borrow_mut_argument.aji @@ -0,0 +1,6 @@ +// expect: reject E7001 +// phase: 6 +// spec: docs/spec/15-source-language.md §10; docs/spec/10-diagnostics-and-agent-protocol.md §3 +module advice +fn f(s: mut) -> void effects [] {} +fn main() -> void effects [] { var x: u64 = 1u64; f(&mut x); } diff --git a/tests/conformance/source/repair_advice/borrow_mut_argument.aji.advice b/tests/conformance/source/repair_advice/borrow_mut_argument.aji.advice new file mode 100644 index 0000000..95ae187 --- /dev/null +++ b/tests/conformance/source/repair_advice/borrow_mut_argument.aji.advice @@ -0,0 +1 @@ +[{"kind":"borrow_argument","hint":"Write `ref place` or `mut place` for an inline borrow argument.","alternatives":["mut"]}] diff --git a/tests/conformance/source/repair_advice/canonical.aji b/tests/conformance/source/repair_advice/canonical.aji new file mode 100644 index 0000000..ac3067d --- /dev/null +++ b/tests/conformance/source/repair_advice/canonical.aji @@ -0,0 +1,21 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/15-source-language.md §4/§5/§10 +module advice +fn read(x: ref) -> u64 effects [] { return *x; } +fn change(x: mut) -> void effects [] { *x = 42u64; } +fn main() -> u64 effects [] { + var x: u64 = zero; + change(mut x); + let inferred = read(ref x); + let bits = 7u64 & 3u64; + let checked = inferred as! u32; + let wrapped = inferred as% u32; + var bytes: [u8; 3] = zero; + ref part = bytes[0usize..3usize]; + if not false and checked == wrapped and bits == 3u64 and part.len == 3usize { + return inferred; + } + return 0u64; +} diff --git a/tests/conformance/source/repair_advice/explicit_range_end.aji b/tests/conformance/source/repair_advice/explicit_range_end.aji new file mode 100644 index 0000000..b4c5d7f --- /dev/null +++ b/tests/conformance/source/repair_advice/explicit_range_end.aji @@ -0,0 +1,6 @@ +// expect: reject E7001 +// phase: 6 +// spec: docs/spec/15-source-language.md §10; docs/spec/10-diagnostics-and-agent-protocol.md §3 +module advice +fn f(s: slice) -> void effects [] { ref t = s[1usize..]; } +fn main() -> void effects [] {} diff --git a/tests/conformance/source/repair_advice/explicit_range_end.aji.advice b/tests/conformance/source/repair_advice/explicit_range_end.aji.advice new file mode 100644 index 0000000..e6de77a --- /dev/null +++ b/tests/conformance/source/repair_advice/explicit_range_end.aji.advice @@ -0,0 +1 @@ +[{"kind":"explicit_range_end","hint":"Write both slice bounds: `receiver[start..end]`; choose the upper bound explicitly."}] diff --git a/tests/conformance/source/repair_advice/numeric_cast_modes.aji b/tests/conformance/source/repair_advice/numeric_cast_modes.aji new file mode 100644 index 0000000..b00c870 --- /dev/null +++ b/tests/conformance/source/repair_advice/numeric_cast_modes.aji @@ -0,0 +1,6 @@ +// expect: reject E7005 +// phase: 6 +// spec: docs/spec/15-source-language.md §10; docs/spec/10-diagnostics-and-agent-protocol.md §3 +module advice +fn f(n: u64) -> u32 effects [] { return n as u32; } +fn main() -> void effects [] {} diff --git a/tests/conformance/source/repair_advice/numeric_cast_modes.aji.advice b/tests/conformance/source/repair_advice/numeric_cast_modes.aji.advice new file mode 100644 index 0000000..5b66b27 --- /dev/null +++ b/tests/conformance/source/repair_advice/numeric_cast_modes.aji.advice @@ -0,0 +1 @@ +[{"kind":"numeric_cast_modes","hint":"Choose `as!` for a checked conversion (T0006 on overflow) or `as%` for a wrapping conversion.","alternatives":["as!","as%"]}] diff --git a/tests/conformance/source/repair_advice/slice_mut_type.aji b/tests/conformance/source/repair_advice/slice_mut_type.aji new file mode 100644 index 0000000..d4dc843 --- /dev/null +++ b/tests/conformance/source/repair_advice/slice_mut_type.aji @@ -0,0 +1,6 @@ +// expect: reject E7001 +// phase: 6 +// spec: docs/spec/15-source-language.md §10; docs/spec/10-diagnostics-and-agent-protocol.md §3 +module advice +fn f(s: mut slice) -> void effects [] {} +fn main() -> void effects [] {} diff --git a/tests/conformance/source/repair_advice/slice_mut_type.aji.advice b/tests/conformance/source/repair_advice/slice_mut_type.aji.advice new file mode 100644 index 0000000..46275f4 --- /dev/null +++ b/tests/conformance/source/repair_advice/slice_mut_type.aji.advice @@ -0,0 +1 @@ +[{"kind":"slice_mut_type","hint":"Write `slice_mut` for a mutable slice type.","alternatives":["slice_mut"]}] diff --git a/tests/conformance/source/repair_advice/slice_ref_type.aji b/tests/conformance/source/repair_advice/slice_ref_type.aji new file mode 100644 index 0000000..6180616 --- /dev/null +++ b/tests/conformance/source/repair_advice/slice_ref_type.aji @@ -0,0 +1,6 @@ +// expect: reject E7001 +// phase: 6 +// spec: docs/spec/15-source-language.md §10; docs/spec/10-diagnostics-and-agent-protocol.md §3 +module advice +fn f(s: ref slice) -> void effects [] {} +fn main() -> void effects [] {} diff --git a/tests/conformance/source/repair_advice/slice_ref_type.aji.advice b/tests/conformance/source/repair_advice/slice_ref_type.aji.advice new file mode 100644 index 0000000..24ec750 --- /dev/null +++ b/tests/conformance/source/repair_advice/slice_ref_type.aji.advice @@ -0,0 +1 @@ +[{"kind":"slice_ref_type","hint":"Write `slice` for a shared slice type.","alternatives":["slice"]}] diff --git a/tests/conformance/source/repair_advice/zero_storage.aji b/tests/conformance/source/repair_advice/zero_storage.aji new file mode 100644 index 0000000..7a3d065 --- /dev/null +++ b/tests/conformance/source/repair_advice/zero_storage.aji @@ -0,0 +1,5 @@ +// expect: reject E7001 +// phase: 6 +// spec: docs/spec/15-source-language.md §10; docs/spec/10-diagnostics-and-agent-protocol.md §3 +module advice +fn main() -> void effects [] { let xs: [u64; 3] = [zero; 3]; } diff --git a/tests/conformance/source/repair_advice/zero_storage.aji.advice b/tests/conformance/source/repair_advice/zero_storage.aji.advice new file mode 100644 index 0000000..52caba5 --- /dev/null +++ b/tests/conformance/source/repair_advice/zero_storage.aji.advice @@ -0,0 +1 @@ +[{"kind":"zero_storage","hint":"`zero` is only a whole var initializer: `var name: T = zero;`; T must be zeroable."}] diff --git a/tests/hosted/source_repair_advice.py b/tests/hosted/source_repair_advice.py new file mode 100644 index 0000000..28c785b --- /dev/null +++ b/tests/hosted/source_repair_advice.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python3 +"""Structured advice is additive, contextual and identical across source APIs.""" +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/repair_advice' +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[:4000], result.stderr[:4000]) + checks += 1 + return result.stdout + + +registry = {} +section = (REPO / 'docs/reference/error-codes.md').read_text().split( + '## Source repair candidate kinds\n', 1)[1].split('\n## ', 1)[0] +for line in section.splitlines(): + if line.startswith('| `'): + kind, code, hint, unit = [x.strip() for x in line.split('|')[1:-1]] + registry[kind.strip('`')] = (code, hint, unit) + +alternatives = {'slice_mut_type': ['slice_mut'], 'slice_ref_type': ['slice'], + 'borrow_argument': ['ref'], 'borrow_mut_argument': ['mut'], + 'numeric_cast_modes': ['as!', 'as%']} +expected_found = {'boolean_negation': '!', 'annotate_var_type': '=', + 'slice_mut_type': 'slice', 'slice_ref_type': 'slice', + 'explicit_range_end': ']', 'borrow_argument': '&', + 'borrow_mut_argument': '&', 'borrow_binding': '&', 'zero_storage': 'zero'} + + +def advice(error, kind, choices=None): + code, hint, _ = registry[kind] + expected = {'kind': kind, 'hint': hint} + if choices is not None: + expected['alternatives'] = choices + assert error['code'] == code and error['repair_candidates'] == [expected], error + assert list(error['repair_candidates'][0]) == list(expected), error + + +cache = REPO / '.zig-cache/contract-gate' +cache.mkdir(parents=True, exist_ok=True) +with tempfile.TemporaryDirectory(prefix='source-advice-', dir=cache) as directory: + root = Path(directory) + library, entry, manifest = (root / name for name in ('lib.aji', 'main.aji', 'aji.toml')) + manifest.write_text('[package]\nname = "advice"\nversion = "1"\nentry = "main.aji"\n' + '[modules]\nlib.advice = "lib.aji"\n') + entry.write_text('module app\nimport lib.advice;\nfn main() -> void effects [] {}\n') + for path in sorted(CORPUS.glob('*.aji')): + if path.stem == 'canonical': + cli('check', path) + result = json.loads(cli('run', '--fuel', '100000', path)) + assert result['value'] == 42, result + continue + error = json.loads(cli('check', path, code=1)) + kind = 'borrow_argument' if path.stem == 'borrow_mut_argument' else path.stem + advice(error, kind, alternatives.get(path.stem)) + assert error['file'] == str(path) and 'air_line' not in error, error + if kind == 'numeric_cast_modes': + assert (error['from'], error['to']) == ('u64', 'u32'), error + assert error['message'] == ('`as` only widens without loss; use `as!` ' + '(checked, traps T0006 when the value does not fit) or `as%` (wrapping)'), error + else: + assert error['found'] == expected_found[path.stem], error + expected = ('`:` and the variable\'s type' if kind == 'annotate_var_type' + else '`)`' if kind.startswith('slice_') else 'an expression') + assert error['expected'] == expected and error['message'] == 'expected ' + expected, error + # Position is the rejected token, never an invented repair range. + text = path.read_text().splitlines()[error['line'] - 1] + assert text[error['col'] - 1:].startswith(error['found']), error + assert json.loads(cli('fmt', path, code=1)) == error + for command in ('lower', 'run', 'report', 'explore'): + assert json.loads(cli(command, path, code=1)) == error + assert cli('check', path, code=1) == cli('check', path, code=1) + + # Syntax and type advice survive imported/package provenance. + library.write_text(path.read_text().replace('module advice', 'module lib.advice') + .replace('fn main(', 'fn user(')) + package_error = json.loads(cli('check', '--manifest', manifest, code=1)) + assert package_error == dict(error, file='lib.aji'), package_error + for command in ('lower', 'run', 'report', 'explore'): + assert json.loads(cli(command, '--manifest', manifest, code=1)) == package_error + + # Closed triggers: nearby unsupported spellings must not mislead the agent. + negatives = [ + 'fn main() -> void effects [] { panic!(); }', + 'fn main() -> void effects [] { var x; }', + '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: &[u8; 3]) -> void effects [] {}', + 'fn f(s: slice) -> void effects [] { ref t = s[..2usize]; }', + 'fn f(s: slice) -> void effects [] { ref t = s[0usize..=2usize]; }', + 'fn main() -> void effects [] { for i in 0u64.. { } }', + 'fn main() -> bool effects [] { return true && false; }', + 'fn main() -> void effects [] { let x = true && false; }', + 'fn main() -> u64 effects [] { return 1u64 + &x; }', + 'fn main() -> u64 effects [] { return &x; }', + 'fn f(b: bool) -> u32 effects [] { return b as u32; }', + 'enum E { V(u64) }\nfn main() -> void effects [] { let x = 1u64; let e = E::V(&x); }', + ] + probe = root / 'probe.aji' + for body in negatives: + if 'fn main(' not in body: + body += '\nfn main() -> void effects [] {}' + probe.write_text('module probe\n' + body + '\n') + error = json.loads(cli('check', probe, code=1)) + assert error['code'] in ('E7001', 'E7005') and 'repair_candidates' not in error, error + + # Valid complete slice fragments preserve nested token spellings; malformed + # fragments get a hint only. The original >> tokens remain untouched. + for spelling, replacement in [ + ('slice< // comment\n own >', 'slice_mut>'), + ('slice< /*c*/ own >', None), + ('slice<[u8; 4]>', 'slice_mut<[u8;4]>'), + ('slice>', 'slice_mut>'), + ('slice', None), ('slice>', None), + ]: + probe.write_text(f'module probe\nfn f(s: mut {spelling}) -> void effects [] {{}}\n' + 'fn main() -> void effects [] {}\n') + error = json.loads(cli('check', probe, code=1)) + advice(error, 'slice_mut_type', [replacement] if replacement else None) + assert error['found'] == 'slice' and error['expected'] == '`)`', error + + # Same malformed type trigger is recognized at different caller sites. + for body, expected in [ + ('fn main() -> void effects [] { var x: mut slice = zero; }', '`=`'), + ('fn f() -> ref slice effects [] {}', 'effects'), + ('fn f(s: ref>) -> void effects [] {}', '`>`'), + ]: + if 'fn main(' not in body: + body += '\nfn main() -> void effects [] {}' + probe.write_text('module probe\n' + body + '\n') + error = json.loads(cli('check', probe, code=1)) + kind = 'slice_ref_type' if '-> ref slice' in body else 'slice_mut_type' + advice(error, kind, ['slice' if kind == 'slice_ref_type' else 'slice_mut']) + assert error['found'] == 'slice' and error['expected'] == expected, error + + for body, kind in [ + ('fn main() -> void effects [] { f(&&x); }', 'borrow_argument'), + ('fn main() -> void effects [] { var x: u64 = 1u64; let r = &mut x; }', 'borrow_binding'), + ('fn main() -> void effects [] { var r: ref = &x; }', 'borrow_binding'), + ('fn main() -> void effects [] { let x: u64 = zero; }', 'zero_storage'), + ('fn main() -> void effects [] { f(zero); }', 'zero_storage'), + ]: + probe.write_text('module probe\n' + body + '\n') + advice(json.loads(cli('check', probe, code=1)), kind) + +print(f'source repair advice: {checks} checks passed') diff --git a/tools/conformance.zig b/tools/conformance.zig index da0104d..128885f 100644 --- a/tools/conformance.zig +++ b/tools/conformance.zig @@ -162,6 +162,19 @@ fn runSource(arena: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, rel: []const const report = try aji.check.checkWithModules(arena, path, source, modules.items); if (report.status == .unimplemented) return .{ .outcome = .pending, .detail = report.missing_stage }; if (try diagnosticIssue(arena, report.diagnostics)) |issue| return .{ .outcome = .fail, .detail = issue }; + const advice_path = try std.fmt.allocPrint(arena, "{s}.advice", .{rel}); + if (dir.readFileAlloc(io, advice_path, arena, .limited(1 << 20))) |golden| { + var output: std.Io.Writer.Allocating = .init(arena); + for (report.diagnostics) |diagnostic| { + var json: std.json.Stringify = .{ .writer = &output.writer }; + try aji.diag.writeRepairCandidates(diagnostic.repair_candidates, &json); + try output.writer.writeByte('\n'); + } + if (!std.mem.eql(u8, golden, output.written())) return .{ .outcome = .fail, .detail = "source repair advice differs from .advice golden" }; + } else |err| switch (err) { + error.FileNotFound => {}, + else => return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "cannot read advice golden: {t}", .{err}) }, + } if (report.lowered) |lowered| { const again = try aji.frontend.compileWithModules(arena, path, source, modules.items); if (again != .ok or !std.mem.eql(u8, again.ok.air, lowered.air)) return .{ .outcome = .fail, .detail = "lowering is not deterministic" };