diag: add factual related borrow and task locations

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

No files matched your search

+1
View File
@@ -25,6 +25,7 @@ jobs:
- run: python3 tests/hosted/source_borrow_returns.py
- run: python3 tests/hosted/source_format.py
- run: python3 tests/hosted/source_diagnostic_reasons.py
- run: python3 tests/hosted/related_locations.py
- run: python3 tests/hosted/source_static_functions.py
- run: python3 tests/hosted/source_linear.py
- run: python3 tests/hosted/source_buffers.py
+1
View File
@@ -21,6 +21,7 @@ python3 tests/hosted/source_generics.py # explicit generics, constraints and pro
python3 tests/hosted/source_borrow_returns.py # explicit origins, retained views, packages and profiles
python3 tests/hosted/source_format.py # formatter CLI, comments, idempotence and public-corpus AIR fidelity
python3 tests/hosted/source_diagnostic_reasons.py # stable E7006 categories and CLI/package provenance
python3 tests/hosted/related_locations.py # factual conflict/spawn positions, source mapping and package provenance
python3 tests/hosted/source_static_functions.py # explicit operations, effects, nominal policy identity and workers
python3 tests/hosted/source_linear.py # whole-value owners, canonical AIR and CLI errors
python3 tests/hosted/source_buffers.py # initialized storage, owning vectors and CLI contracts
+2
View File
@@ -146,3 +146,5 @@ P6-8 source formatter (cl100k): Quick Reference 8,688 → 8,728 (+40), other sou
Q-040 block boundaries (DD-016, cl100k): Quick Reference 8,728 → 8,769 (+41), other source docs 64,677 → 65,012 (+335), full source 73,405 → 73,781 (+0.51%). o200k groups are 8,805 / 65,212 / 74,017; Qwen2.5 9,037 / 66,603 / 75,640. AIR and library/std.md are unchanged. One syntactic boundary rule and an explicit-discard guard replace an ambiguity; there is no new syntax form, diagnostic code or verifier/runtime state. No empirical MCC benefit is claimed.
DD-017 stable E7006 reasons (cl100k): Quick Reference 8,769 → 8,807 (+38), other source docs 65,012 → 65,799 (+787), full source 73,781 → 74,606 (+1.12%). o200k groups are 8,843 / 66,001 / 74,844; Qwen2.5 9,077 / 67,402 / 76,479. AIR grows 46,300 → 46,937 (+637, +1.38%), 179,282 → 182,254 bytes, because the shared diagnostic registry includes the 28 source categories. library/std.md is unchanged. One structured discriminator replaces prose classification; there is no new code, programming syntax, verifier/runtime state or repair application. Historical reasons remain unknown. No empirical MCC benefit is claimed.
RFC 0037 related positions (cl100k): Quick Reference 8,807 → 8,859 (+52), other source docs 65,799 → 66,195 (+396), full source 74,606 → 75,054 (+0.60%). o200k groups are 8,895 / 66,397 / 75,292; Qwen2.5 9,135 / 67,810 / 76,945. AIR grows 46,937 → 47,328 (+391, +0.83%), 182,254 → 184,060 bytes; library/std.md is unchanged. Two factual roles locate an existing selected conflict or spawn; there is no new programming syntax, diagnostic code, semantic verifier state or runtime rule. One constant-sized origin is carried on each existing task loan. Necessary schema/source-map rules enter the bundles; RFC rationale does not. No empirical MCC benefit is claimed.
+2
View File
@@ -329,6 +329,8 @@ scope s { // every task spawned in s must
| T0010 | `iref` of another graph | use a handle with the graph it came from |
| T0001–T0009 | runtime trap | see `kind` and `source_location` |
E2101/E2104 `related_locations` identifies the selected conflicting borrow; E4302 identifies its task's spawn. Use the source position when present; an unmapped record retains AIR coordinates and the SSA identity. These are facts, not repair instructions.
## 10. Standard library
Import a bundled module after the module header; call its functions by their full path. `std.bytes` and `std.math` are safe source, declare `effects []` and allocate no heap. No grants are needed. Read `/docs/library/std.md` for the API.
+6
View File
@@ -101,3 +101,9 @@ Compatibility: formerly accepted bare continuations in statement/tail position r
Spec 15 §10 requires a registered reason on each E7006. Frontend rejection sites select an enum category explicitly; `move_copy` excludes borrowed and non-materializable operands. ajieval groups observed codes/reasons per run and reports unknown historical reasons separately, without reading message prose. Existing code counts remain compatible; missing logs are unavailable evidence. Counts describe observed command outputs, not the true frequency of all errors.
Reason: a shared code cannot establish whether Copy moves occur often enough to justify RFC 0038. Structured categories also let an agent choose the appropriate rule without classifying prose. This small diagnostic schema extension uses a decision record and a P6-7 plan increment; no new rejection, code, source/AIR syntax, verifier/runtime state or repair application is introduced. Existing locations, payloads, interpreter records, resource/borrow invariants and frozen evaluation inputs remain intact. Enum/registry and CLI/report tests cover serialization, generic/package propagation and historical uncertainty. Bundle growth is recorded in docs/agent/README.md. RFC 0038 remains Proposed with its existing recommendation to defer pending frequency and application-usability data.
## DD-018 — Factual related positions without choosing a repair
RFC 0037's implementation/spec integration is prepared under P6-7; formal RFC status remains Proposed for owner adoption. Spec 10 §2 and spec 15 §10 define one typed related record for each identified E2101/E2104 conflict and E4302 task. Definition lookup retains the selected conflict; loan metadata retains the creating spawn even when a cancelled join replaces its SSA handle. Source mapping is independent, and an absent mapping exposes AIR coordinates without a guessed source position. Primary selection, fields and duplicate suppression are unchanged. There is no enclosing-block inference, conflict enumeration or edit.
The invariant is unchanged acceptance, ownership/loan verification and deterministic interpreter behavior; provenance never participates in liveness or transfer decisions. AIR format 0, syntax, effects/capabilities and diagnostic codes are unchanged. Positive/rejected source/AIR fixtures, repeated cancelled joins, CLI/package mapping and typed serialization tests check the contract. Bundle growth is measured in docs/agent/README.md. This improves factual repair context; no measured repair-cost or MCC claim is made, and RFC 0038 stays deferred pending evidence.
+4 -2
View File
@@ -207,10 +207,12 @@ The reason field improves machine repairability on its own; the reporting follow
### C5 — Related locations
**Truth / existing coverage:** the second source location is missing despite SSA conflict identities. **Consistency:** factual locations are compatible; a suggested enclosing block is not automatically a proven fact about a valid repair. **Mission:** explicitness and repairability. **Payoff:** scope the first RFC to previous borrow origin and outstanding task/spawn locations, preserving primary location, stable codes and deterministic ordering through source/AIR mapping and modules. Test reborrows, call-returned borrows, regions, task loans and merged provenance. Defer block-enclosure analysis until its meaning, feasibility and soundness are specified. A diagnostic extension alone need not change ownership semantics.
**Truth / existing coverage:** at the review baseline, the second source location was missing despite SSA conflict identities. **Consistency:** factual locations are compatible; a suggested enclosing block is not automatically a proven fact about a valid repair. **Mission:** explicitness and repairability. **Payoff:** scope the first RFC to previous borrow origin and outstanding task/spawn locations, preserving primary location, stable codes and deterministic ordering through source/AIR mapping and modules. Test reborrows, call-returned borrows, regions, task loans and merged provenance. Defer block-enclosure analysis until its meaning, feasibility and soundness are specified. A diagnostic extension alone need not change ownership semantics.
The public native smoke reports six E2101 occurrences in AIR command output; P5-0 reports two in a strong agent's source run, repaired in one cycle. These support the relevance of borrow feedback, not a measured economic benefit of related positions. Review supports RFC 0037's bounded scope and the need to carry the original spawn through cancelled-handle transitions. Source variable names may help later; they remain outside scope rather than being inferred from SSA names.
Subsequent language work prepares RFC 0037's implementation and spec integration together under [DD-018](decisions.md#dd-018--factual-related-positions-without-choosing-a-repair)/P6-7. Each identified covered conflict receives one factual record; primary selection and deduplication remain unchanged, and cancelled-join handles retain spawn provenance. Related source mapping never guesses a position. The implementation/tests and measured bundle growth are recorded in the plan; they supply no new empirical repair-cost result. Formal RFC status remains Proposed for owner adoption. This follow-up is authorized language work, not implementation inferred from this assessment.
### C6 — Integer contracts
**Truth / existing coverage:** declaration support remains pending; guard/assert are existing alternatives for local checks. **Consistency:** no unproved predicate may silently gain an unspecified runtime meaning. Define mathematical versus fixed-width arithmetic/overflow, evaluation timing, old-state capture, supported expressions, traps, effect requirements, interprocedural checking and behavior under concurrency/resource obligations. Distinguish decidable proof from executable runtime checking; not every possible contract is executable. Review AIR format-0 extension rules and register any new feature. **Mission:** verifier strength. **Payoff:** high and unknown, including solver/TCB and source/AIR bundle growth. A focused P6-6 RFC should compare existing primitives before recommending a language extension or priority.
@@ -249,6 +251,6 @@ Recommended sequence, subject to the existing owner plan:
The original review identifies a real growth/measurement risk and a concrete diagnostic repair gap. Its strongest immediate contributions are better evidence accounting and related source locations; it does not establish a current floating-point determinism bug, missing diagnostic statistics, or a need for new behavioral abstractions.
Following owner discussion, the bounded C5 and C1 proposals are written as [RFC 0037](../rfcs/0037-borrow-diagnostic-related-locations.md) and [RFC 0038](../rfcs/0038-bounded-diagnostic-edits.md), both **Proposed**, with no implementation or acceptance implied. The three requested documentation clarifications are complete. Generated bundle measurements after the Quick Reference sentence: cl100k Quick 8,688, other source 64,160, full source 72,848; o200k 8,723 / 64,359 / 73,082; Qwen2.5 8,954 / 65,733 / 74,687. AIR and std reference sizes are unchanged. C3/C4/C9 remain owner policy options.
Following owner discussion, the bounded C5 and C1 proposals were written as [RFC 0037](../rfcs/0037-borrow-diagnostic-related-locations.md) and [RFC 0038](../rfcs/0038-bounded-diagnostic-edits.md), both **Proposed**, with no implementation or acceptance implied at drafting. The three requested documentation clarifications are complete. Generated bundle measurements after the Quick Reference sentence: cl100k Quick 8,688, other source 64,160, full source 72,848; o200k 8,723 / 64,359 / 73,082; Qwen2.5 8,954 / 65,733 / 74,687. AIR and std reference sizes were unchanged by those clarifications. Subsequent schema/reporting and related-position increments are recorded above. C3/C4/C9 remain owner policy options.
The subsequent RFC review supports 0037 and recommends deferring 0038 as described above; formal adoption remains the owner's decision. The reviewed drafts had 2,010 and 2,381 words respectively (`wc -w`), disproportionate to the small diagnostic extension. At spec integration, express the schema and code-to-role/eligibility mapping as a few table rows plus indispensable invariants; keep rationale, alternatives and test matrices in RFCs/tests and remeasure bundle growth. Compactness must still preserve source-map fallback, deterministic ordering and task-spawn provenance. The evidence/workflow qualification added to 0038 is outside the bundles and is not itself language growth.
+2
View File
@@ -49,3 +49,5 @@ Every run test is executed twice by the runner from P0-12 onward and the outputs
Diagnostic JSON is a stable interface. Snapshot tests on the full JSON (not only the code) belong in unit tests next to the pass that emits them, so field renames are caught.
`python3 tests/hosted/source_diagnostic_reasons.py` checks stable E7006 categories, generic/package propagation and serialization. From `tools/eval`, `python3 -m unittest discover tests` checks reporting alongside the harness. `ajieval summary` reports observed `(code, reason)` occurrences and affected runs with log coverage; `profile` and `checkpoint` expose per-run pairs. Existing compact code extraction is preserved. Only whole JSON diagnostic lines classify a reason: unparsed or historical records remain unknown; new reason strings are retained. Missing logs are unavailable. These counts cover the recorded command outputs, not a pre-acceptance cutoff or the true frequency of unobserved errors; future cohort methodology must specify those separately.
`python3 tests/hosted/related_locations.py` checks factual E2101/E2104 definitions and E4302 spawns in public AIR/source rejects, exact definition coordinates (including parameters and second split results), independent annotation-map reconstruction, existing source deduplication, generics and explicit packages. Unit tests cover typed JSON/key order, absent related mappings and repeated cancelled-join handle replacement through the lowered-source pipeline. `zig build conformance -- --filter cancel_join --stress 200 --collect-every-step` exercises accepted cancellation counterparts under deterministic schedule seeds and several quanta. These checks add no repair or lifetime inference.
+6
View File
@@ -170,3 +170,9 @@ DD-017/spec 15 §10 registers 28 stable E7006 categories, explicitly selected at
ajieval summary adds occurrences and affected runs by `(code, reason)`, with log availability; profile/checkpoint expose per-run counts. Code totals and the historical compact-code extraction stay intact. Whole JSON records provide reasons; historical, malformed or unparsed records remain unknown and missing logs remain unavailable. These are observed outputs over the entire transcript, without a pre-acceptance cutoff; they do not establish repair cost or justify implementing RFC 0038. New cohort timing, strata and missing-data policy remain evaluation decisions. Frozen evaluation inputs and historical records are unchanged.
Validation: full conformance passes 1,154/1,154; CLI passes 130 checks including 72 public E7006 fixtures, generic/package cases, deterministic serialization and non-E7006 preservation. A comparison over 872 public files finds no changes beyond the new reason: all 557 accepted AIR outputs and every original diagnostic payload remain identical. The 26 ajieval self-tests pass (one environment skip), including historical uncertainty, unknown future reasons, native transcripts, code-total conservation, run incidence and checkpoint JSON. Independent read-only review by Claude found no defects in the extension; its registry-scope suggestion was incorporated. Bundle growth is recorded in docs/agent/README.md. This completes the independent instrumentation prerequisite, not RFC 0038 or Phase 6.
## P6-7 related-position increment (2026-10-07)
RFC 0037/DD-018 prepares spec integration and implementation of one factual `related_locations` record on identified E2101/E2104 conflicts and E4302 tasks. Existing definition positions identify selected borrows; each task loan carries constant-sized spawn metadata through cancelled-join handle replacement. Typed JSON appends the array after the old envelope. Each related position maps independently, including imports and specializations; absent mappings omit source coordinates while retaining AIR coordinates. Primary fields, first-conflict selection and source duplicate suppression are unchanged; no block/repair inference, code, syntax, feature, transfer rule or runtime change is introduced. RFC 0037 remains Proposed for owner adoption; P6-7 remains open for the remaining span/twin work.
Validation: unit tests and full conformance pass, 1,160/1,160 with no failures or pending tests, including six new source/AIR positive/rejected counterparts and repeated cancelled joins. CLI passes 267 checks/161 context records, covering public rejects, function parameters, second split results, call-result definitions, exact source mapping from public annotations, generics and packages. Unit tests cover typed/key-ordered JSON, missing mappings, two cancelled-handle replacements and deduplication retaining the first conflict. Cancellation conformance passes with collection before every instruction and 200 schedule seeds under multiple quanta. Across 1,199 original public AIR/source/std/example files, removal of only the appended metadata recovers byte-identical outputs and exit codes, including all 701 successful check/lower outputs. Source construct coverage remains 120/120. Independent read-only review by Claude found no implementation issues. Bundle measurements are recorded in docs/agent/README.md; frozen evaluation inputs remain untouched. No repair-cost experiment or RFC 0038 implementation is included.
+3 -3
View File
@@ -28,10 +28,10 @@ Draft registry. Codes are stable once released in a tagged compiler version.
|---|---|---|
| E2001 | ownership.use_after_move | Value used after ownership transfer |
| E2002 | ownership.double_consume | Linear value consumed twice |
| E2101 | borrow.mutable_alias | Overlapping exclusive/shared borrow violation |
| E2101 | borrow.mutable_alias | Overlapping exclusive/shared borrow violation; related definition when `conflicts_with` is identified (spec 10 §2) |
| E2102 | borrow.outlives_owner | Borrow may outlive backing storage |
| E2103 | memory.out_of_bounds | Access not proven in bounds |
| E2104 | memory.region_generation | Reference belongs to invalidated region generation |
| E2104 | memory.region_generation | Reference belongs to invalidated region generation; related definition when `conflicts_with` is identified (spec 10 §2) |
| E2110 | island.escape | Island-internal reference escapes island |
| E2105 | borrow.not_ended | Owned borrow live at `ret`, or borrow state differs between edges into a block |
| E2106 | borrow.use_after_end | Borrow used or ended after it was ended |
@@ -60,7 +60,7 @@ Draft registry. Codes are stable once released in a tagged compiler version.
| E4202 | atomic.ordinary_access | Atomic cell accessed by an ordinary load |
| E4203 | atomic.unsupported_width | Atomic width not implemented lock-free by the target |
| E4301 | task.live_child_escape | Scope exits with live child task |
| E4302 | task.borrow_escape | Child task borrow can outlive parent storage |
| E4302 | task.borrow_escape | Child task borrow can outlive parent storage; related spawn when `task` is identified (spec 10 §2) |
| E4303 | io.buffer_in_flight | Buffer accessed while async operation owns/borrows it |
| E4304 | sync.wait_while_locked | Suspending operation, spawn, or call of a waiting/spawning function while a lock guard is live |
| E4305 | task.shield_order | Shield ended while a more inner shield is live |
@@ -5,7 +5,7 @@ Scope: Diagnostic metadata for E2101, E2104 and E4302; AIR format 0 and `.aji` 0
Language version: 0.1\
Supersedes: —
This proposal is ready for owner review. It is not implemented or accepted; the following rule changes enter the specification only on acceptance.
Implementation and spec integration are prepared together for owner adoption (P6-7/DD-018). Formal status remains Proposed; this does not record acceptance. The specification is authoritative for the prepared implementation, while this RFC retains its rationale and bounded scope.
## Motivation
@@ -23,7 +23,7 @@ An earlier position denotes a syntactic origin, not a claim that it ran before t
## Normative rule changes
Proposed addition to spec 10 §2, “Related locations”:
Integrated in spec 10 §2, “Related locations”:
> A diagnostic MAY include `related_locations`, an ordered array of non-binding factual context records. Each record MUST contain `role` and `value`. The identity in `value` uses the existing diagnostic value naming convention. A located record MUST contain `file`, `line` and `col`, using the primary location's conventions. Additional fields MUST NOT change an existing field's meaning.
>
@@ -31,7 +31,7 @@ Proposed addition to spec 10 §2, “Related locations”:
>
> The related record MUST describe the same conflict selected for the primary diagnostic. Implementations MUST NOT enumerate other conflicts as part of this extension. The primary position, existing structured fields, error code, diagnostic ordering and duplicate suppression MUST retain their existing meaning and selection behavior.
Proposed addition to spec 15 §10, “Related source positions”:
Integrated in spec 15 §10, “Related source positions”:
> For a diagnostic from lowered AIR, each related AIR position MUST be mapped independently through the lowering source map, including the source file recorded for imported or specialized code. If mapped, `file`, `line` and `col` MUST denote that source construct, and `air_line`/`air_col` MUST retain its AIR position, as for the primary diagnostic.
>
@@ -101,7 +101,7 @@ Consumers must tolerate optional metadata and an unmapped related source record.
## Spec integration
On acceptance, integrate the rules into:
The prepared change integrates the rules into:
- spec 10 §2: envelope, roles, conditions, identity and serialization contract;
- spec 15 §10: independent related-position source mapping and fallback;
@@ -112,7 +112,7 @@ On acceptance, integrate the rules into:
Spec 10 §2 and spec 15 §10 already enter the AIR and source bundles respectively. Keep the necessary schema text there rather than adding the RFC rationale or repeated examples to every bundle page.
At integration, condense the schema and code-to-role mapping into a few table rows plus the required source-map/determinism invariants. Retain rationale, implementation discussion and test matrices here or in tests rather than expanding normative prose with them.
The integration condenses the schema and code-to-role mapping into a few table rows plus the required source-map/determinism invariants. Rationale, implementation discussion and test matrices remain here or in tests rather than expanding normative prose with them.
## Compatibility and migration
@@ -129,7 +129,7 @@ Preserve current first-conflict selection and source diagnostic deduplication. D
- Repairability: avoids searching for the selected earlier construct; does not promise a unique repair or lower total cost without measurement.
- Existing primitives: sufficient for the programs and verifier; the current JSON envelope lacks structured related positions.
- New diagnostics: no codes; an additive metadata field on three existing codes.
- Bundle budget: proposed normative integration is not included in this draft. Baseline before this RFC, after the floating-point documentation clarification, is AIR 46,300 cl100k tokens; Quick 8,688, other source 64,160, full source 72,848. Implementation MUST measure AIR, Quick and source groups before/after integration. No projected token delta is presented as a measurement.
- Bundle budget: measured integration after DD-017 (cl100k): AIR 46,937 → 47,328 (+391); Quick 8,807 → 8,859 (+52), other source 65,799 → 66,195 (+396), full source 74,606 → 75,054 (+448, +0.60%). Necessary schema/source-map rules enter the bundles, not this RFC. Other tokenizer totals and unchanged std size are recorded in docs/agent/README.md.
This is a diagnostic extension, not a semantic feature with a new source syntax. It still lands through spec, diagnostic API, verifier provenance, source mapping, Quick Reference and AIR/source CLI tests together; interpreter behavior must remain unchanged.
@@ -159,4 +159,4 @@ No semantic decision is delegated to implementation. The owner must decide adopt
## Draft validation
Both `.aji` code blocks were extracted and checked against the current compiler: the valid example returns 2 with fuel 1,000; the negative example rejects with E2101. Its selected `%data_4` definition is AIR line 13, mapping to source line 4, column 5. The JSON addition above is proposed output, not current compiler output. New metadata tests and implementation remain pending.
Both `.aji` code blocks were extracted and checked against the baseline compiler: the valid example returns 2 with fuel 1,000; the negative example rejects with E2101. Its selected `%data_4` definition is AIR line 13, mapping to source line 4, column 5. The JSON addition above now matches the implemented metadata contract. The examples also have source/AIR conformance counterparts under `related_locations` and `related_borrow_*`. Validation results for the prepared implementation are recorded under P6-7; formal adoption remains the owner's decision.
+2
View File
@@ -346,6 +346,8 @@ region.destroy → used -= every allocation of the region
- A region allocation `%p` is an owned borrow whose parent is the shared region borrow `%rb` and whose path is a fresh element unique to that allocation. Allocations are therefore disjoint from each other, and the exclusive borrow `mut<T>` of a fresh object does not conflict with the shared parent (this is the one place where an exclusive child of a shared borrow is permitted, because the storage is new).
- `region.reset %r` and `region.destroy %r` are exclusive accesses to the region value. If a **live reference** into the region exists — any live borrow derived from `%r`, in particular a live borrow of an allocation — the instruction is `E2104` (`memory.region_generation`): reset or destroy would invalidate a live reference. Allocations whose borrows have all ended are not an obstacle; destroying them is what `reset` and `destroy` are for.
An identified E2104 conflict includes the selected reference's definition position (spec 10 §2), without changing generation or borrow rules.
- Ending `%rb` while one of its allocations is live is `E2102`, so no allocation outlives the borrow it came from.
- A function may return a region allocation with `from %rb` when `%rb` is a `ref<region>` parameter (spec 08 §11.3 applies unchanged: the root is the parameter). Frame-derived borrows still never escape (`E2108`).
+1
View File
@@ -542,6 +542,7 @@ While `LOANED`:
- for the verifier it behaves as a live child borrow of the argument, owned by the task handle, with the argument's mode and path;
- ending the argument borrow, or any ancestor of it, while the task is live is `E4302` (`task.borrow_escape`);
an identified task includes its spawn position (spec 10 §2), retained through cancelled-join handle replacement without participating in loan/liveness checks;
- an access or a new borrow that conflicts with a loan of a live task is `E4101` (`concurrency.possible_data_race`) rather than `E2101`, since the other party runs concurrently;
- lending the same exclusive borrow, or overlapping exclusive borrows, to two live tasks is `E4101`; lending disjoint places (different fields, the halves of a `slice.split`, different region allocations) is accepted.
+2
View File
@@ -175,6 +175,8 @@ Normative rules for frame storage and second-class borrows. Decision record: RFC
### 11.2 Places, overlap and access
Identified E2101 conflicts include the selected conflicting value's definition position (spec 10 §2); this metadata changes no overlap or transfer rule.
Every borrow has a **root** (a `local` or a lent parameter), a **path** from the root (field names, a slice range, or an element), a **mode** (`ref`/`mut`) and a **parent** (none for borrows taken directly from a local or a parameter).
- Two paths overlap unless they diverge at different fields of the same struct, at the two results of one `slice.split`, or at two different region allocations (spec 03 §20.2) (and descendants of each).
@@ -16,6 +16,15 @@ Every verifier/compiler error has:
Code-specific `reason` values MUST be registered and stable; consumers MUST NOT derive them from human messages. E7006 requires the categories in spec 15 §10 and `reference/error-codes.md`.
`related_locations` MAY provide ordered, non-binding factual context; the covered forms below MUST provide exactly one record for the already selected conflict. Other forms MUST NOT invent a value or task.
| Diagnostic field | Related `role` | Related `value` | Position |
|---|---|---|---|
| E2101/E2104 `conflicts_with` | `conflicting_borrow` | same as `conflicts_with` | that value's definition |
| E4302 `task` | `task_spawn` | same as `task` | the task's creating spawn, retained through cancelled-join handle replacement |
A record MUST serialize `role`, `value`, then `file`, `line`, `col` when located (the primary position's conventions), then `air_line`, `air_col` for lowered AIR (spec 15 §10). `related_locations` MUST be omitted when empty and otherwise appended after existing envelope fields. Roles and identities MUST be factual; positions identify syntax, not execution order or a repair. Primary positions/fields, first-conflict selection, diagnostic order and duplicate suppression MUST remain unchanged; discarded duplicates MUST NOT contribute related records. No borrow, loan, acceptance rule or runtime behavior changes.
Example:
```json
+2
View File
@@ -423,6 +423,8 @@ Its diagnostics keep their AIR codes, reported at the source location.
Every E7006 MUST include a stable string `reason` from the [reason registry](../reference/error-codes.md#e7006-reasons), chosen directly by the rejecting rule, independently of `message`. `move_copy` denotes an explicit rejected move of a plain Copy value; borrows use `move_borrow`, and non-materializable operands use `invalid_move`. Permitted generic transfers MUST NOT emit these errors. Reason meanings MUST remain stable; extensions MAY add registered reasons. Consumers MUST tolerate new reasons. Codes, rejection rules, primary positions and existing fields are unchanged; `reason` is appended after existing code-specific fields. A historical or incomplete record without a reason is unknown, never evidence of `move_copy` or its absence.
Each related AIR position (spec 10 §2) MUST be mapped independently through the lowering map, including imported/specialized source files, retaining its original coordinates as `air_line`/`air_col`. If absent, the related source `file`/`line`/`col` MUST be omitted together; `role`, `value` and AIR coordinates remain. A guessed related source position MUST NOT be substituted. Primary fallback and duplicate selection remain unchanged.
## 11. Tooling
| Command | Does |
+101
View File
@@ -153,6 +153,107 @@ test "standard source provenance maps diagnostics to the library file" {
try std.testing.expectEqual(@as(u32, 20), d.span.?.line);
}
test "source dedup keeps the first selected conflict and never merges related positions" {
const src = verifier.test_header[0 .. verifier.test_header.len - "features []\n".len] ++
\\features [ownership]
\\fn @main() -> void
\\effects []
\\entry:
\\ %x = local.alloc u8
\\ local.zero %x
\\ %y = local.alloc u8
\\ local.zero %y
\\ %r = borrow.ref %x
\\ %q = borrow.ref %y
\\ %z = const.u8 0
\\ local.store %x, %z
\\ local.store %y, %z
\\ borrow.end %r
\\ borrow.end %q
\\ ret
\\
;
var a: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer a.deinit();
const arena = a.allocator();
const raw = try checkAir(arena, "t.air", src);
try std.testing.expectEqual(@as(usize, 2), raw.diagnostics.len);
const lines = try arena.alloc(?frontend.Span, std.mem.count(u8, src, "\n") + 1);
@memset(lines, .{ .start = .{ .line = 8, .col = 5 }, .end = .{ .line = 8, .col = 6 } });
const mapped = try checkLowered(arena, "t.aji", .{ .air = src, .annotated = src, .lines = lines, .constant_of = &.{}, .constants = &.{} });
try std.testing.expectEqual(@as(usize, 1), mapped.diagnostics.len);
const related = mapped.diagnostics[0].related_locations;
try std.testing.expectEqual(@as(usize, 1), related.len);
try std.testing.expectEqualStrings("%r", related[0].value);
try std.testing.expectEqual(raw.diagnostics[0].related_locations[0].span.?.line, related[0].air_span.?.line);
}
test "mapped E4302 keeps spawn through repeated cancelled joins and missing mappings" {
const src =
\\module t
\\air 0
\\lang 0.1
\\features [cancellation, effects, ownership, tasks]
\\fn @main() -> u8
\\effects [task.spawn, task.wait]
\\entry:
\\ %x = local.alloc u8
\\ local.zero %x
\\ %r = borrow.ref %x
\\ %s = task.scope.begin
\\ %t = task.spawn %s, @worker(%r)
\\ task.join.cancel %t, ok -> @joined, cancelled -> @retry
\\retry(%back: task<u8>):
\\ task.join.cancel %back, ok -> @joined, cancelled -> @cancelled
\\joined(%v: u8):
\\ task.scope.end %s
\\ borrow.end %r
\\ ret %v
\\cancelled(%back2: task<u8>):
\\ borrow.end %r
\\ %v2 = task.join %back2
\\ task.scope.end %s
\\ ret %v2
\\fn @worker(%p: ref<u8>) -> u8
\\effects []
\\entry:
\\ %v = load %p
\\ ret %v
\\
;
var a: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer a.deinit();
const arena = a.allocator();
const raw = try checkAir(arena, "t.air", src);
try std.testing.expectEqual(@as(usize, 1), raw.diagnostics.len);
try std.testing.expectEqualStrings("E4302", raw.diagnostics[0].code.id);
const origin = raw.diagnostics[0].related_locations[0];
try std.testing.expectEqualStrings("%back2", origin.value);
try std.testing.expectEqual(@as(u32, 12), origin.span.?.line);
try std.testing.expectEqual(@as(u32, 5), origin.span.?.col);
try std.testing.expect(origin.air_span == null);
const lines = try arena.alloc(?frontend.Span, std.mem.count(u8, src, "\n") + 1);
@memset(lines, null);
lines[20] = .{ .file = "entry.aji", .start = .{ .line = 9, .col = 5 }, .end = .{ .line = 9, .col = 6 } };
for (0..2) |i| {
if (i == 1) lines[11] = .{ .file = "dep.aji", .start = .{ .line = 3, .col = 7 }, .end = .{ .line = 3, .col = 8 } };
const mapped = try checkLowered(arena, "t.aji", .{ .air = src, .annotated = src, .lines = lines, .constant_of = &.{}, .constants = &.{} });
const d = mapped.diagnostics[0];
try std.testing.expectEqualStrings("entry.aji", d.span.?.file);
const related = d.related_locations[0];
try std.testing.expectEqualStrings("%back2", related.value);
try std.testing.expectEqual(@as(u32, 12), related.air_span.?.line);
try std.testing.expectEqual(@as(u32, 5), related.air_span.?.col);
if (i == 0) {
try std.testing.expect(related.span == null);
} else {
try std.testing.expectEqualStrings("dep.aji", related.span.?.file);
try std.testing.expectEqual(@as(u32, 3), related.span.?.line);
try std.testing.expectEqual(@as(u32, 7), related.span.?.col);
}
}
}
test "standard type diagnostics use the public source name" {
var a = std.heap.ArenaAllocator.init(std.testing.allocator);
defer a.deinit();
+73
View File
@@ -136,6 +136,16 @@ pub const Span = struct {
col: u32,
};
/// Non-binding factual context (spec 10 §2); no inferred repair or name.
pub const RelatedLocation = struct {
role: enum { conflicting_borrow, task_spawn },
value: []const u8,
/// Null only when a known AIR origin has no source mapping.
span: ?Span,
/// Original AIR position for lowered source; the file is not serialized.
air_span: ?Span = null,
};
/// Structured, code-specific payload (e.g. "value": "%17").
pub const Field = struct {
name: []const u8,
@@ -156,6 +166,7 @@ pub const Diagnostic = struct {
fields: []const Field = &.{},
/// Non-binding structured suggestions (spec 10 §3).
repair_candidates: []const []const u8 = &.{},
related_locations: []const RelatedLocation = &.{},
/// Writes the diagnostic as a single JSON object (no trailing newline).
/// Key order is fixed so output is byte-for-byte deterministic.
@@ -197,6 +208,33 @@ pub const Diagnostic = struct {
}
try s.endArray();
}
if (d.related_locations.len != 0) {
try s.objectField("related_locations");
try s.beginArray();
for (d.related_locations) |related| {
try s.beginObject();
try s.objectField("role");
try s.write(@tagName(related.role));
try s.objectField("value");
try s.write(related.value);
if (related.span) |sp| {
try s.objectField("file");
try s.write(sp.file);
try s.objectField("line");
try s.write(sp.line);
try s.objectField("col");
try s.write(sp.col);
}
if (related.air_span) |sp| {
try s.objectField("air_line");
try s.write(sp.line);
try s.objectField("air_col");
try s.write(sp.col);
}
try s.endObject();
}
try s.endArray();
}
try s.endObject();
}
};
@@ -219,6 +257,41 @@ test "writeJson is deterministic and structured" {
, w.buffered());
}
test "related locations are typed, ordered and appended after existing fields" {
var buf: [1024]u8 = undefined;
var w: std.Io.Writer = .fixed(&buf);
const d: Diagnostic = .{
.code = lookup("E2101").?,
.span = .{ .file = "main.aji", .line = 9, .col = 5 },
.fields = &.{.{ .name = "conflicts_with", .value = .{ .str = "%view_4" } }},
.message = "conflict",
.repair_candidates = &.{"example"},
.related_locations = &.{.{
.role = .conflicting_borrow,
.value = "%view_4",
.span = .{ .file = "dep.aji", .line = 3, .col = 7 },
.air_span = .{ .file = "main.aji", .line = 12, .col = 5 },
}},
};
try d.writeJson(&w);
try std.testing.expectEqualStrings(
\\{"code":"E2101","kind":"borrow.mutable_alias","severity":"error","file":"main.aji","line":9,"col":5,"conflicts_with":"%view_4","message":"conflict","repair_candidates":[{"kind":"example"}],"related_locations":[{"role":"conflicting_borrow","value":"%view_4","file":"dep.aji","line":3,"col":7,"air_line":12,"air_col":5}]}
, w.buffered());
w = .fixed(&buf);
try (Diagnostic{
.code = lookup("E4302").?,
.related_locations = &.{.{
.role = .task_spawn,
.value = "%back",
.span = null,
.air_span = .{ .file = "main.aji", .line = 17, .col = 5 },
}},
}).writeJson(&w);
try std.testing.expectEqualStrings(
\\{"code":"E4302","kind":"task.borrow_escape","severity":"error","related_locations":[{"role":"task_spawn","value":"%back","air_line":17,"air_col":5}]}
, w.buffered());
}
test "registry mirrors docs/reference/error-codes.md" {
const md = @embedFile("error_codes_md");
var seen: usize = 0;
+41
View File
@@ -74,6 +74,16 @@ pub fn syntaxDiagnostic(arena: std.mem.Allocator, file: []const u8, f: parse.Fai
/// location stays as `air_line`/`air_col` metadata (spec 15 §10).
pub fn mapDiagnostic(arena: std.mem.Allocator, d: diag.Diagnostic, file: []const u8, lines: []const ?Span) std.mem.Allocator.Error!diag.Diagnostic {
var out = d;
if (d.related_locations.len != 0) {
const related = try arena.dupe(diag.RelatedLocation, d.related_locations);
for (related) |*r| {
const origin = r.span orelse continue;
r.air_span = origin;
const source: ?Span = if (origin.line >= 1 and origin.line <= lines.len) lines[origin.line - 1] else null;
r.span = if (source) |s| .{ .file = s.file orelse file, .line = s.start.line, .col = s.start.col } else null;
}
out.related_locations = related;
}
const sp = d.span orelse return out;
const fields = try arena.alloc(diag.Field, d.fields.len + 2);
@memcpy(fields[0..d.fields.len], d.fields);
@@ -92,6 +102,37 @@ test {
_ = format;
}
test "related AIR positions map independently with no guessed source fallback" {
var a: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer a.deinit();
const lines: []const ?Span = &.{
.{ .file = "entry.aji", .start = .{ .line = 8, .col = 9 }, .end = .{ .line = 8, .col = 10 } },
.{ .file = "dep.aji", .start = .{ .line = 3, .col = 5 }, .end = .{ .line = 3, .col = 6 } },
null,
};
const mapped = try mapDiagnostic(a.allocator(), .{
.code = diag.lookup("E2101").?,
.span = .{ .file = "lowered.air", .line = 1, .col = 5 },
.related_locations = &.{
.{ .role = .conflicting_borrow, .value = "%a", .span = .{ .file = "lowered.air", .line = 2, .col = 7 } },
.{ .role = .task_spawn, .value = "%b", .span = .{ .file = "lowered.air", .line = 3, .col = 5 } },
.{ .role = .task_spawn, .value = "%c", .span = .{ .file = "lowered.air", .line = 99, .col = 5 } },
},
}, "fallback.aji", lines);
try std.testing.expectEqualStrings("entry.aji", mapped.span.?.file);
try std.testing.expectEqual(@as(u32, 8), mapped.span.?.line);
const located = mapped.related_locations[0];
try std.testing.expectEqualStrings("dep.aji", located.span.?.file);
try std.testing.expectEqual(@as(u32, 3), located.span.?.line);
try std.testing.expectEqual(@as(u32, 5), located.span.?.col);
try std.testing.expectEqual(@as(u32, 2), located.air_span.?.line);
try std.testing.expectEqual(@as(u32, 7), located.air_span.?.col);
for (mapped.related_locations[1..], [_]u32{ 3, 99 }) |related, line| {
try std.testing.expect(related.span == null);
try std.testing.expectEqual(line, related.air_span.?.line);
}
}
pub const Size = struct { bytes: usize, lines: usize };
/// AIR size with every byte-string materialization (the instructions from
+12
View File
@@ -38,12 +38,24 @@ pub const Context = struct {
span: air.Span,
message: []const u8,
fields: []const diag.Field,
) std.mem.Allocator.Error!void {
return c.reportRelated(id, span, message, fields, &.{});
}
pub fn reportRelated(
c: *Context,
id: []const u8,
span: air.Span,
message: []const u8,
fields: []const diag.Field,
related: []const diag.RelatedLocation,
) std.mem.Allocator.Error!void {
try c.diags.append(c.arena, .{
.code = diag.lookup(id).?,
.span = .{ .file = c.file, .line = span.line, .col = span.col },
.message = message,
.fields = try c.arena.dupe(diag.Field, fields),
.related_locations = try c.arena.dupe(diag.RelatedLocation, related),
});
}
+32 -6
View File
@@ -11,6 +11,7 @@ const std = @import("std");
const air = @import("../air.zig");
const verifier = @import("../verifier.zig");
const ssa = @import("ssa.zig");
const diag = @import("../diag.zig");
const Context = verifier.Context;
const ValueId = air.ValueId;
@@ -29,7 +30,15 @@ const Seg = union(enum) {
const Mode = enum { shared, exclusive };
const Loan = struct { task: ValueId, borrow: ValueId, root: ValueId, path: []const Seg, mode: Mode };
const Loan = struct {
task: ValueId,
borrow: ValueId,
root: ValueId,
path: []const Seg,
mode: Mode,
/// Diagnostic provenance only; never participates in borrow/liveness state.
spawn: air.Span,
};
/// Why a resource is no longer live (spec 06 §6.3).
const Dead = enum { none, closed, moved };
@@ -85,14 +94,27 @@ const Walker = struct {
}
fn report(w: *Walker, code: []const u8, message: []const u8, borrow: ValueId, extra: ?struct { []const u8, ValueId }) !void {
return w.reportWithOrigin(code, message, borrow, extra, null);
}
fn reportWithOrigin(w: *Walker, code: []const u8, message: []const u8, borrow: ValueId, extra: ?struct { []const u8, ValueId }, spawn: ?air.Span) !void {
if (extra) |e| {
try w.c.report(code, w.span, message, &.{
var related: [1]diag.RelatedLocation = undefined;
const context: []const diag.RelatedLocation = if ((std.mem.eql(u8, code, "E2101") or std.mem.eql(u8, code, "E2104")) and std.mem.eql(u8, e[0], "conflicts_with")) blk: {
const sp = w.f.values[e[1]].span;
related[0] = .{ .role = .conflicting_borrow, .value = try w.name(e[1]), .span = .{ .file = w.c.file, .line = sp.line, .col = sp.col } };
break :blk &related;
} else if (spawn) |sp| blk: {
related[0] = .{ .role = .task_spawn, .value = try w.name(e[1]), .span = .{ .file = w.c.file, .line = sp.line, .col = sp.col } };
break :blk &related;
} else &.{};
try w.c.reportRelated(code, w.span, message, &.{
.{ .name = "function", .value = .{ .str = w.f.name } },
.{ .name = "block", .value = .{ .str = w.f.blocks[w.block].name } },
.{ .name = "inst", .value = .{ .int = w.index } },
.{ .name = "borrow", .value = .{ .str = try w.name(borrow) } },
.{ .name = e[0], .value = .{ .str = try w.name(e[1]) } },
});
}, context);
} else {
try w.c.report(code, w.span, message, &.{
.{ .name = "function", .value = .{ .str = w.f.name } },
@@ -411,7 +433,7 @@ fn step(w: *Walker, inst: air.Inst) !void {
// Ended even when rejected, so one mistake yields one diagnostic.
defer w.live[v] = false;
for (w.loans.items) |l| if (w.live[l.task] and (l.borrow == v or w.isAncestor(v, l.borrow))) {
return w.report("E4302", "borrow ended while it is lent to a live task", v, .{ "task", l.task });
return w.reportWithOrigin("E4302", "borrow ended while it is lent to a live task", v, .{ "task", l.task }, l.spawn);
};
for (w.live, 0..) |is_live, g| if (is_live and w.guard_parent[g] != null and w.isAncestor(v, w.guard_parent[g].?)) {
return w.report("E2102", "mutex borrow ended while a guard locked through it is live", v, .{ "guard", @intCast(g) });
@@ -493,7 +515,7 @@ fn step(w: *Walker, inst: air.Inst) !void {
const ai = w.info[a].?;
// The loan must not conflict with live borrows or loans.
try w.accessCode(ai.root, ai.path, ai.mode, a, a, "E4101", "lending a borrow that conflicts with a live borrow");
try w.loans.append(w.c.arena, .{ .task = t, .borrow = a, .root = ai.root, .path = ai.path, .mode = ai.mode });
try w.loans.append(w.c.arena, .{ .task = t, .borrow = a, .root = ai.root, .path = ai.path, .mode = ai.mode, .spawn = inst.span });
} else if (w.isResource(a)) try w.consume(a, .moved);
}
w.live[t] = true;
@@ -557,7 +579,11 @@ fn step(w: *Walker, inst: air.Inst) !void {
const n = w.loans.items.len;
for (0..n) |i| {
const l = w.loans.items[i];
if (l.task == t) try w.loans.append(w.c.arena, .{ .task = back, .borrow = l.borrow, .root = l.root, .path = l.path, .mode = l.mode });
if (l.task == t) {
var transferred = l;
transferred.task = back;
try w.loans.append(w.c.arena, transferred);
}
}
try w.consume(t, .closed);
},
@@ -0,0 +1,18 @@
; expect: reject E2101
; phase: 1
; spec: docs/spec/10-diagnostics-and-agent-protocol.md §2
module related.rejected
air 0
lang 0.1
features [ownership]
fn @main() -> u64
effects []
entry:
%data = local.alloc u64
local.zero %data
%view = borrow.ref %data
%two = const.u64 2
local.store %data, %two
%result = load %view
borrow.end %view
ret %result
@@ -0,0 +1,23 @@
; expect: run
; result: 2
; phase: 1
; spec: docs/spec/10-diagnostics-and-agent-protocol.md §2
module related.valid
air 0
lang 0.1
features [ownership]
fn @main() -> u64
effects []
entry:
%data = local.alloc u64
%one = const.u64 1
local.store %data, %one
%view = borrow.ref %data
%read = load %view
%same = eq.u64 %read, %one
assert %same
borrow.end %view
%two = const.u64 2
local.store %data, %two
%result = local.load %data
ret %result
@@ -0,0 +1,32 @@
; expect: reject E4302
; phase: 3
; spec: docs/spec/10-diagnostics-and-agent-protocol.md §2
module related.cancel_twice
air 0
lang 0.1
features [cancellation, effects, ownership, tasks]
fn @main() -> u8
effects [task.spawn, task.wait]
entry:
%x = local.alloc u8
local.zero %x
%r = borrow.ref %x
%s = task.scope.begin
%t = task.spawn %s, @worker(%r)
task.join.cancel %t, ok -> @joined, cancelled -> @retry
retry(%back: task<u8>):
task.join.cancel %back, ok -> @joined, cancelled -> @cancelled
joined(%v: u8):
task.scope.end %s
borrow.end %r
ret %v
cancelled(%back2: task<u8>):
borrow.end %r
%v2 = task.join %back2
task.scope.end %s
ret %v2
fn @worker(%p: ref<u8>) -> u8
effects []
entry:
%v = load %p
ret %v
@@ -0,0 +1,34 @@
; expect: run
; result: 0
; schedules: 20
; phase: 3
; spec: docs/spec/04-concurrency-and-atomics.md §34
module related.cancel_twice_joined
air 0
lang 0.1
features [cancellation, effects, ownership, tasks]
fn @main() -> u8
effects [task.spawn, task.wait]
entry:
%x = local.alloc u8
local.zero %x
%r = borrow.ref %x
%s = task.scope.begin
%t = task.spawn %s, @worker(%r)
task.join.cancel %t, ok -> @joined, cancelled -> @retry
retry(%back: task<u8>):
task.join.cancel %back, ok -> @joined, cancelled -> @cancelled
joined(%v: u8):
task.scope.end %s
borrow.end %r
ret %v
cancelled(%back2: task<u8>):
%v2 = task.join %back2
borrow.end %r
task.scope.end %s
ret %v2
fn @worker(%p: ref<u8>) -> u8
effects []
entry:
%v = load %p
ret %v
@@ -0,0 +1,11 @@
// expect: run
// result: 2
// phase: 6
// spec: docs/spec/10-diagnostics-and-agent-protocol.md §2
module related.valid
fn main() -> u64 effects [] {
var data: [u64; 1] = [1u64];
{ ref view = data; assert(view[0] == 1u64); }
data[0] = 2u64;
return data[0];
}
@@ -0,0 +1,10 @@
// expect: reject E2101
// phase: 6
// spec: docs/spec/10-diagnostics-and-agent-protocol.md §2
module related.rejected
fn main() -> u64 effects [] {
var data: [u64; 1] = [1u64];
ref view = data;
data[0] = 2u64;
return view[0];
}
+222
View File
@@ -0,0 +1,222 @@
#!/usr/bin/env python3
"""Factual borrow/spawn context in AIR, source, generics and package CLI."""
import json
from pathlib import Path
import re
import subprocess
import tempfile
REPO = Path(__file__).resolve().parents[2]
AJI = REPO / 'zig-out/bin/aji'
checks = 0
covered = 0
def cli(*args, code=0):
global checks
p = subprocess.run([str(AJI), *map(str, args)], capture_output=True, text=True)
assert p.returncode == code, (args, p.returncode, p.stdout, p.stderr)
checks += 1
return p.stdout
def related(error, source=False):
global covered
field = 'task' if error['code'] == 'E4302' else 'conflicts_with'
if error['code'] not in ('E2101', 'E2104', 'E4302') or field not in error:
assert 'related_locations' not in error, error
return None
records = error['related_locations']
assert len(records) == 1, error
r = records[0]
role = 'task_spawn' if field == 'task' else 'conflicting_borrow'
assert r['role'] == role and r['value'] == error[field], error
assert list(error)[-1] == 'related_locations', error
keys = ['role', 'value']
if 'file' in r:
keys += ['file', 'line', 'col']
assert r['line'] >= 1 and r['col'] >= 1, r
if source:
keys += ['air_line', 'air_col']
assert list(r) == keys, r
covered += 1
return r
def air_origin(text, error):
r = related(error)
if r is None:
return
lines = text.splitlines()
line = lines[r['line'] - 1]
if r['role'] == 'task_spawn':
assert '= task.spawn ' in line and r['col'] == line.index('%') + 1, (line, r)
else:
# The selected value, rather than its backing root, defines context.
assert line[r['col'] - 1:].startswith(r['value']), (line, r)
assert '=' in line or ':' in line, (line, r)
assert r['file'] == error['file'], r
def source_check(root, *args):
errors = [json.loads(line) for line in cli('check', *args, code=1).splitlines()]
assert cli('check', *args, code=1) == cli('check', *args, code=1)
canonical = cli('lower', *args)
annotated = cli('lower', '--annotate', *args)
path = root / 'lowered.air'
path.write_text(canonical)
raw = [json.loads(line) for line in cli('check', path, code=1).splitlines()]
# Independently reconstruct the public annotation map, then use the
# unchanged primary-code/location deduplication to predict source output.
mapping = {}
actual_lines = []
pending = None
for line in annotated.splitlines():
match = re.fullmatch(r'\s*; (?:(.+):)?(\d+):(\d+)-\d+:\d+', line)
if match:
pending = (match[1], int(match[2]), int(match[3]))
continue
actual_lines.append(line)
mapping[len(actual_lines)] = pending
pending = None
assert '\n'.join(actual_lines) + '\n' == canonical
fallback = args[-1] if args[0] != '--manifest' else 'entry.aji'
expected = []
seen = set()
for d in raw:
air_origin(canonical, d)
primary = mapping.get(d['line'])
out = dict(d)
out['air_line'], out['air_col'] = d['line'], d['col']
out['file'], out['line'], out['col'] = (primary[0] or str(fallback), primary[1], primary[2]) if primary else (str(fallback), 1, 1)
if 'related_locations' in d:
r = d['related_locations'][0]
origin = mapping.get(r['line'])
context = {'role': r['role'], 'value': r['value']}
if origin:
context.update(file=origin[0] or str(fallback), line=origin[1], col=origin[2])
context.update(air_line=r['line'], air_col=r['col'])
out['related_locations'] = [context]
key = out['code'], out['file'], out['line'], out['col']
if key not in seen:
seen.add(key)
expected.append(out)
assert errors == expected, (args, errors, expected)
for d in errors:
related(d, source=True)
return errors
with tempfile.TemporaryDirectory(prefix='aji-related-') as directory:
root = Path(directory)
# Call-argument overlap selects the operand itself, exposing definitions
# that an ordinary root-access conflict often masks with an earlier borrow.
direct = [
('%p', '''fn @f(%p: mut<u64>) -> void
effects []
entry:
call @g(%p, %p)
ret
'''),
('%right', '''fn @f() -> void
effects []
entry:
%x = local.alloc array<u64, 2>
local.zero %x
%p = borrow.mut %x
%s = slice.make %p
%one = const.usize 1
%left, %right = slice.split %s, %one
call @h(%right, %right)
borrow.end %left
borrow.end %right
borrow.end %s
borrow.end %p
ret
'''),
('%returned', '''fn @view(%p: mut<u64>) -> mut<u64> from %p
effects []
entry:
%child = borrow.mut %p
ret %child
fn @f() -> void
effects []
entry:
%x = local.alloc u64
local.zero %x
%p = borrow.mut %x
%returned = call @view(%p)
call @g(%returned, %returned)
borrow.end %returned
borrow.end %p
ret
'''),
]
callees = '''fn @g(%a: mut<u64>, %b: mut<u64>) -> void
effects []
entry:
ret
fn @h(%a: slice_mut<u64>, %b: slice_mut<u64>) -> void
effects []
entry:
ret
'''
for identity, body in direct:
text = 'module definitions\nair 0\nlang 0.1\nfeatures [arrays, effects, ownership]\n' + body + callees
path = root / 'definitions.air'
path.write_text(text)
errors = [json.loads(line) for line in cli('check', path, code=1).splitlines()]
assert len(errors) == 1 and errors[0]['code'] == 'E2101', errors
air_origin(text, errors[0])
context = errors[0]['related_locations'][0]
assert context['value'] == identity, errors
definition = next((i, line.index(identity) + 1) for i, line in enumerate(text.splitlines(), 1)
if identity in line and (line.startswith('fn @f(') or identity in line.split('=')[0] and '=' in line))
assert (context['line'], context['col']) == definition, context
corpus = REPO / 'tests/conformance'
for path in sorted(corpus.rglob('*.air')):
text = path.read_text()
if not re.search(r'^; expect: reject .*E(?:2101|2104|4302)', text, re.M):
continue
errors = [json.loads(line) for line in cli('check', path, code=1).splitlines()]
for error in errors:
air_origin(text, error)
for path in sorted((corpus / 'source').rglob('*.aji')):
text = path.read_text()
if not re.search(r'^// expect: reject .*E(?:2101|2104|4302)', text, re.M):
continue
if re.search(r'^// module:', text, re.M):
continue # Explicit package tests below exercise linked provenance.
source_check(root, path)
errors = source_check(root, corpus / 'source/related_locations/borrow_live.aji')
assert errors[0]['line'] == 8 and errors[0]['related_locations'][0]['line'] == 7
assert json.loads(cli('run', '--fuel', '10000', corpus / 'source/related_locations/borrow_ended.aji'))['value'] == 2
# A returned view's definition is the caller's call, not the callee's from.
errors = source_check(root, corpus / 'source/borrow_returns/parent_access.aji')
context = errors[0]['related_locations'][0]
assert context['line'] == 6 and context['col'] == 92, context
entry, library, manifest = root / 'entry.aji', root / 'dep.aji', root / 'aji.toml'
manifest.write_text('[package]\nname = "related"\nversion = "1"\nentry = "entry.aji"\n[modules]\napp.dep = "dep.aji"\n')
entry.write_text('module app.entry\nimport app.dep;\nfn main()->u64 effects [] {app.dep.bad::<u64>()}\n')
library.write_text('module app.dep\nfn bad<T: Copy>()->u64 effects [] {\n'
' var data: [u64; 1] = [1u64];\n'
' ref view = data;\n'
' data[0] = 2u64;\n'
' return view[0];\n}\n')
errors = source_check(root, '--manifest', manifest)
context = errors[0]['related_locations'][0]
assert errors[0]['file'] == 'dep.aji' and errors[0]['line'] == 5
assert context['file'] == 'dep.aji' and context['line'] == 4 and context['col'] == 5
entry.write_text(entry.read_text().replace('bad::<u64>', 'bad'))
library.write_text(library.read_text().replace('bad<T: Copy>', 'bad'))
errors = source_check(root, '--manifest', manifest)
assert errors[0]['related_locations'][0]['file'] == 'dep.aji'
# Codes outside the scope keep the old envelope.
other = root / 'other.aji'
other.write_text('module other fn main()->u64 effects [] {return true;}')
assert 'related_locations' not in json.loads(cli('check', other, code=1))
assert covered > 0
print(f'related location CLI passed ({checks} checks; {covered} context records)')