diag: add stable source reasons and diagnostic incidence reporting
This commit is contained in:
1 parent
911982dd1c
commit
dbd9763713
21 files changed
+571
-156
No files matched your search
@@ -24,6 +24,7 @@ jobs:
|
||||
- run: python3 tests/hosted/source_generics.py
|
||||
- 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/source_static_functions.py
|
||||
- run: python3 tests/hosted/source_linear.py
|
||||
- run: python3 tests/hosted/source_buffers.py
|
||||
|
||||
@@ -20,6 +20,7 @@ python3 tests/hosted/source_modules.py # explicit package CLI and file-loading c
|
||||
python3 tests/hosted/source_generics.py # explicit generics, constraints and provenance
|
||||
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/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
|
||||
|
||||
@@ -144,3 +144,5 @@ RFC 0036 review fixes clarify reserved task borrow returns and known array bound
|
||||
P6-8 source formatter (cl100k): Quick Reference 8,688 → 8,728 (+40), other source docs 64,214 → 64,677 (+463), full source 72,902 → 73,405 (+0.69%). language/tooling.md is 3,051 tokens. o200k groups are 8,763 / 64,876 / 73,639; Qwen2.5 8,994 / 66,259 / 75,253. AIR stays 179,282 bytes / 46,300 cl100k tokens, and library/std.md stays unchanged. One command with check/write modes reduces whitespace repair and diff noise while preserving tokens, comments and canonical AIR; it adds no language concept, feature, verifier/runtime state or diagnostic code. No empirical MCC benefit is claimed.
|
||||
|
||||
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.
|
||||
@@ -317,6 +317,7 @@ scope s { // every task spawned in s must
|
||||
| E2001, E3001, E2002 | used after move / after consume / twice | restructure so each linear value is consumed once on every path |
|
||||
| E3002 | linear value leaked | consume it (close, free, take, join, send) on every path, including `return` |
|
||||
| E3101 | effect not declared | copy `suggested_effects` into `effects [...]` |
|
||||
| E7006 | invalid source construct | inspect stable `reason`; `move_copy` means an explicit move of a Copy value, `move_borrow` a move of a borrow |
|
||||
| E3201 | wrong capability kind | pass the right `cap<K>` |
|
||||
| E4001, E4002 | not Send / not Share | move owned data into tasks; share only `Share` data by `ref` |
|
||||
| E4101 | data race with a task | lend disjoint parts (`split_at`, fields) or join first |
|
||||
|
||||
@@ -95,3 +95,9 @@ Spec 15 §4 and the grammar resolve Q-040 syntactically: leading bare `if`, `mat
|
||||
Reason: `if true { *p = 2u64; } *p = 3u64;` must denote two statements regardless of spacing. Greedy expression parsing consumed multiplication instead. Merely splitting would silently change `{2i64} -3i64` from −1 to −3; rejecting the undiscarded value avoids that change. Neither line-sensitive syntax nor assignment lookahead is needed. This is a small grammar decision, not a new AIR facility.
|
||||
|
||||
Compatibility: formerly accepted bare continuations in statement/tail position require parentheses around the initial construct. Formerly accepted value-producing bare block statements require explicit `;`, including mixed branches such as `if c { return 1u64; } else { 2u64 }` before another statement. Existing tails, explicit discards and initializer/return/argument/condition/expression-arm continuations retain their meanings. Ownership, lexical borrow ends, verifier transfers and deterministic runtime rules are unchanged. A borrow bound inside a preceding block remains inaccessible afterwards (E7002); aliasing and task rules still come from the existing verifier. No new diagnostic code, source syntax form, feature or verifier/runtime state is added. One frontend statement marker enforces the value guard and gives the formatter an explicit boundary; it never changes tokens or inserts separators. No empirical Model Capability Compression benefit is claimed; source documentation growth is measured in docs/agent/README.md.
|
||||
|
||||
## DD-017 — Stable E7006 reasons before repair-frequency analysis
|
||||
|
||||
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.
|
||||
@@ -33,6 +33,7 @@ Status values: `open`, `resolved`.
|
||||
| Q-036 | resolved | STD-6a | Dynamic initialized linear buffer storage and drain |
|
||||
| Q-038 | resolved | STD-6d.2 | Pure construction of built-in errors |
|
||||
| Q-039 | resolved | STD-6d | Explicit static function parameters |
|
||||
| Q-041 | open | P6-2 task block forms | Source scope-handle value bindings |
|
||||
|
||||
## Q-001 — Text AIR grammar
|
||||
|
||||
@@ -297,3 +298,9 @@ General collections and algorithms need explicit typed hash/equality/order opera
|
||||
P6-8 review found an existing parser ambiguity: `if true { *p = 2u64; } *p = *p + 1u64;` is consumed as an expression continued by multiplication and then rejects E7006 at the assignment. The same failure is reproduced after a standalone block or `match`; `while` dispatches separately and is not affected. Source whitespace is insignificant; spec 15 §4 and the grammar admit both block statements and expressions beginning with block/control-flow forms. The intended disambiguation must be specified before changing which previously parsed expressions are accepted. Decide how a standalone block statement ends before a dereference/other unary-leading statement while preserving block-valued expressions in explicit expression contexts. Add positive/rejected parser and lowering cases for the chosen rule. The formatter preserves the current tokens/AST and MUST NOT insert semicolons or infer the intended statement boundary. This question is separate from P6-8.
|
||||
|
||||
**Resolved (DD-016, spec 15 §4):** leading bare `if`, `match` and `{…}` in statement/tail position stop before outer expression operations. The next `}` selects a tail, `;` an explicit discard, otherwise a block statement must yield `void` or diverge (E7006). Parentheses permit continuation; nested expression contexts retain ordinary parsing. The value guard prevents silent reinterpretation of former expressions such as `{2i64} -3i64`. Parser, lowering, formatter and source conformance cover the boundary and compatibility rules. This resolves one P6-1/P6-2 ambiguity, not the complete grammar tasks.
|
||||
|
||||
## Q-041 — Source scope-handle value bindings
|
||||
|
||||
Independent E7006 review found that `module scope_move fn main()->u64 effects [] { scope sc { let alias = move sc; } 42u64 }` checks and returns 42 with fuel 10,000. Its AIR contains only `task.scope.begin` and `task.scope.end` on the same SSA value; the unused alias introduces no instruction. This observation alone establishes no memory/concurrency safety defect. Spec 15 §3 excludes `scope` from source type spellings, §7 ties scope completion to the block, and spec 04 §33 permits function-local scope flow while preserving linear completion. They do not explicitly say which ordinary source value-binding forms may name that internal handle or how an explicit transfer interacts with the block's retained completion obligation.
|
||||
|
||||
Clarify whether `let`/`move` aliases and rebinding of a scope name are permitted, how their availability relates to the originating block, and which existing diagnostic applies to rejected forms. Keep AIR scope identity, live-child/loan checks, deterministic completion and the no-escape invariant intact; add source acceptance/rejection tests for the chosen contract before changing lowering. This is separate from DD-017's reason field and RFC 0038's proposed repairs; neither adopts a new scope rule.
|
||||
@@ -182,16 +182,16 @@ Updated count after RFC review: **1 concrete RFC candidate** (C5), **1 deferred
|
||||
|
||||
RFC 0038 is therefore retained with a recommendation to defer work, preserving formal Proposed status. Its byte offsets and file hash identify an exact edit for a programmatic applicator, but `expected: "[]"` does not identify a unique string replacement. Context plus edit line/column, or an explicitly invoked application command, remain design alternatives rather than adopted fixes. Resume review only after aggregate eligible per-run incidence with a defined denominator, evidence of material repair cost, and validation of the actual application workflow. No arbitrary N% is set from these reports; any owner-selected threshold and minimum sample size must precede a new cohort's evaluation. M/C may only check regression and cannot select or tune the feature. Frozen evaluation inputs remain untouched.
|
||||
|
||||
**Independent measurement prerequisite: stable E7006 reasons.** Current frontend E7006 diagnostics do not provide a stable `reason` discriminator. The move rejection in [lower.zig](../../src/frontend/lower.zig) exposes `name`/`type`, but the same rejection site can cover Copy values and other non-linear forms, and E7006 also covers unrelated constructs across frontend stages. Parsing `message` would violate the machine-readable intent of spec 14 §3.5 and cannot supply a reliable Copy-move incidence metric.
|
||||
**Independent measurement prerequisite: stable E7006 reasons.** At the review baseline, frontend E7006 diagnostics did not provide a stable `reason` discriminator. The move rejection in [lower.zig](../../src/frontend/lower.zig) exposes `name`/`type`, but the same rejection site can cover Copy values and other non-linear forms, and E7006 also covers unrelated constructs across frontend stages. Parsing `message` would violate the machine-readable intent of spec 14 §3.5 and cannot supply a reliable Copy-move incidence metric.
|
||||
|
||||
Record a separate diagnostic-schema task, independent of RFC 0038's edits or application workflow, for owner routing to a plan task or RFC. Its proposed completion conditions are:
|
||||
The review proposed a separate diagnostic-schema task, independent of RFC 0038's edits or application workflow, with these completion conditions:
|
||||
|
||||
- Specify stable `reason` values and coverage in spec/reference, distinguishing Copy-move rejection from borrowed/non-Copy moves and other covered invalid constructs. Keep E7006's code/kind and the language's accepted/rejected sets unchanged.
|
||||
- Emit reasons from explicit frontend error classification, not message parsing or simply assigning one reason to every use of the shared code. Check JSON serialization, original source provenance and positive/negative examples for each specified reason; valid generic Copy transfer remains accepted.
|
||||
- Keep missing/unclassified reasons explicitly unknown in measurements. Do not relabel historical records or infer their reasons from prose; adding fields to future runs does not recover old data.
|
||||
- Separately extend evaluation reporting to aggregate affected source runs by `(code, reason)`, alongside existing code counts, with the agreed denominator/cutoff. Merely adding `reason` does not change `_diagnostic_codes`, which currently counts codes only. Both changes must precede the relevant future experiment's freeze.
|
||||
|
||||
The reason field improves machine repairability on its own; the reporting follow-up enables the Copy-move branch of 0038's evidence condition. E3101's code-level incidence can already be counted without this prerequisite. No task ID, implementation, new reason name or diagnostic-schema adoption is assigned by this assessment; the owner decides routing and scope.
|
||||
The reason field improves machine repairability on its own; the reporting follow-up enables the Copy-move branch of 0038's evidence condition. E3101's code-level incidence can already be counted without this prerequisite. The assessment itself assigned no implementation or adoption. Subsequent language work implements the independent schema/reporting increment under [DD-017](decisions.md#dd-017--stable-e7006-reasons-before-repair-frequency-analysis) and [P6-7](../plan/phase-6-source-language.md): every E7006 has a registered reason, and ajieval reports observed occurrences and affected runs with unknown reasons/log availability retained. Code totals are unchanged. The reporting covers the entire recorded transcript; a future cohort must still specify its pre-acceptance cutoff, agent/toolchain strata and missing-data policy. No new experiment, repair-cost evidence or application-usability result is supplied; RFC 0038 remains Proposed with the deferral recommendation.
|
||||
|
||||
### C2 — Diagnostic statistics
|
||||
|
||||
|
||||
@@ -47,3 +47,5 @@ Every run test is executed twice by the runner from P0-12 onward and the outputs
|
||||
## Diagnostics as API
|
||||
|
||||
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.
|
||||
@@ -162,3 +162,11 @@ Validation: unit tests and Zig formatting pass, including 10,000-term expression
|
||||
Q-040 is resolved in spec 15 §4 and the grammar (DD-016): leading bare `if`, `match` and `{…}` finish before outer expression operations in statement/tail position. The enclosing `}` selects a tail, `;` an explicit discard, otherwise a block statement must yield `void` or diverge. This E7006 guard prevents silent reinterpretation of former expressions such as `{2i64} -3i64`; parenthesized continuations and nested expression contexts remain available. The parser marks block statements, ordinary/generic lowering checks the guard, and the formatter derives line boundaries from statement spans. No AIR feature, diagnostic code or verifier/runtime state is added. P6-1/P6-2 remain open for the rest of their grammar work.
|
||||
|
||||
Validation: full conformance passes 1,154/1,154 with no failures or pending tests, including 19 focused source cases covering stores, other unary starts, tails, explicit contexts/discards, generic bodies, mixed diverging/value branches and lexical borrow ends. Unit tests, Zig formatting, bundle/example checks and 120/120 construct coverage pass. The formatter/CLI suite passes 3,267 checks over 872 public files: 860 parse idempotently, 12 syntax-error fixtures reject with E7001, and 557 successful lowerings preserve byte-identical AIR. A before/after comparison over the original 853 public files finds no exit-code changes and identical AIR for all 548 successful lowerings. Independent read-only review by Claude found the silent value-discard risk in the initial design; the guard fixes it, and final review found no remaining issues. Budgets are recorded in docs/agent/README.md; frozen evaluation inputs are unchanged.
|
||||
|
||||
## P6-7 E7006 reason increment (2026-10-07)
|
||||
|
||||
DD-017/spec 15 §10 registers 28 stable E7006 categories, explicitly selected at all 130 frontend rejection sites. Borrowed and non-materializable moves cannot be counted as `move_copy`; permitted generic Copy transfers remain accepted. The compiler rejects future unclassified E7006 emissions at compilation. The JSON field follows existing code-specific fields, retaining their values, positions and messages. No code, rejection rule, language/AIR syntax or verifier/runtime state changes. P6-7 remains open for its source-span/twin requirements.
|
||||
|
||||
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.
|
||||
@@ -91,7 +91,7 @@ Only problems that exist because of the frontend. Everything the verifier decide
|
||||
| E7003 | source.missing_move | Named linear value consumed without `move` |
|
||||
| E7004 | source.not_exhaustive | `match` misses an outcome, variant or default |
|
||||
| E7005 | source.type_mismatch | Expression has the wrong type in a source position |
|
||||
| E7006 | source.invalid_construct | Construct not allowed here |
|
||||
| E7006 | source.invalid_construct | Construct not allowed here; stable `reason` below |
|
||||
| E7007 | source.ambiguous | Source meaning cannot be determined |
|
||||
| E7900 | source.internal_compiler_error | The frontend produced invalid AIR for this construct: a compiler bug, not a program error; fields `air_code`, `air_message` |
|
||||
|
||||
@@ -111,3 +111,38 @@ Reported in trap records (spec 01 §6), not by the verifier.
|
||||
| T0008 | trap.out_of_bounds | Runtime bounds check failed |
|
||||
| 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 |
|
||||
|
||||
## 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.
|
||||
|
||||
| Reason | Meaning |
|
||||
|---|---|
|
||||
| `move_copy` | Explicit move of a plain Copy value; excludes borrows, void and never. |
|
||||
| `move_borrow` | Explicit move of a borrow/view. |
|
||||
| `invalid_move` | Move operand is void or never, rather than a materializable value. |
|
||||
| `loop_control_outside_loop` | break or continue without an enclosing loop. |
|
||||
| `zero_not_zeroable` | zero initialization of a type without a zero value. |
|
||||
| `value_block_statement` | A bare block statement would implicitly discard a non-void value. |
|
||||
| `unreachable` | Statement or expression after unconditional divergence. |
|
||||
| `missing_return` | A value-returning function can fall through without a value. |
|
||||
| `invalid_borrow` | A borrow requires an explicit binding, mode, named parent or argument form. |
|
||||
| `invalid_borrow_return` | A borrow return violates source origin, binding, return or worker restrictions. |
|
||||
| `duplicate_declaration` | Duplicate type, function, field, variant or parameter declaration. |
|
||||
| `invalid_declaration` | An otherwise disallowed declaration shape, such as an empty enum. |
|
||||
| `invalid_binding` | Invalid binding shape, rebinding or implicit borrow binding. |
|
||||
| `invalid_assignment` | Assignment requires a mutable variable or a permitted stored element/field. |
|
||||
| `invalid_place` | Expression is not an addressable place or uses an invalid unchecked projection. |
|
||||
| `invalid_match` | Invalid, duplicate or misplaced pattern, outcome or select arm. |
|
||||
| `invalid_unpack` | Invalid complete unpack or multi-result binding form. |
|
||||
| `invalid_expression` | Value expression uses an unavailable form, such as scalar dereference of a slice. |
|
||||
| `invalid_operation` | Invalid intrinsic/call, fallibility handler, multi-result handler or ordering spelling. |
|
||||
| `invalid_literal` | Invalid literal shape, duplicate/missing initializer field or borrowed element. |
|
||||
| `invalid_generic` | Invalid generic parameter, constraint, argument, entry point or application. |
|
||||
| `invalid_static_function` | Static callable contract, parameter use or specialization is disallowed. |
|
||||
| `implementation_limit` | A specified frontend/module/type/specialization size or depth limit is exceeded. |
|
||||
| `invalid_module_mapping` | Invalid reserved, duplicate or excessive package module mapping. |
|
||||
| `duplicate_import` | The same module is imported twice. |
|
||||
| `import_cycle` | Cyclic module import. |
|
||||
| `module_header_mismatch` | Mapped module header differs from its explicit provider name. |
|
||||
| `trusted_unavailable` | A source program/template declares an unavailable trusted boundary. |
|
||||
@@ -13,11 +13,11 @@ The published [native smoke](../evaluation/results/2026-10-05-native-smoke.md),
|
||||
|
||||
Reconsider the proposal only after the following evidence is available:
|
||||
|
||||
1. **Incidence with an explicit denominator.** Publish aggregate counts for an independently chosen `Aji/source` cohort: runs with at least one eligible E3101 or classified Copy-move E7006, divided by all source runs, failures included, with sample size and agent/toolchain strata. Count affected runs separately from repeated diagnostic occurrences. Report unknown E7006 reasons as unknown, not eligible or zero. Current `ajieval profile` counts codes per run but does not classify Copy-move reasons or guarantee a pre-acceptance cutoff; specify that cutoff and missing-data treatment before collecting a new cohort.
|
||||
1. **Incidence with an explicit denominator.** Publish aggregate counts for an independently chosen `Aji/source` cohort: runs with at least one eligible E3101 or classified Copy-move E7006, divided by all source runs, failures included, with sample size and agent/toolchain strata. Count affected runs separately from repeated diagnostic occurrences. Report unknown E7006 reasons as unknown, not eligible or zero. `ajieval summary`, `profile` and `checkpoint` now classify structured code/reason counts (DD-017), retaining unknown reasons and log availability; they cover the entire recorded transcript, without a pre-acceptance cutoff. Specify that cutoff and missing-data treatment before collecting a new cohort.
|
||||
2. **Material repair cost.** Show that the eligible cases cause location/transcription work, failed patches, retries or meaningful tool cost, and compare the proposed workflow against today's `suggested_effects` plus ordinary editing on independent public fixtures/tasks. Frequency alone is insufficient; a syntactically exact edit may cost more to apply than the existing repair.
|
||||
3. **A usable application path.** Resolve the byte-offset workflow objection below and validate the chosen path with the actual editor/tool interface. Application must remain explicit, stale-input checks must hold, and edited source must be rechecked.
|
||||
|
||||
The Copy-move incidence branch has an independent instrumentation prerequisite: E7006 currently has no stable `reason` field, and the harness counts codes only. A separate diagnostic-schema task must specify and emit structured reasons distinguishing Copy moves from other E7006 forms; a reporting follow-up must count affected runs by code/reason without parsing `message`. These tasks are independently useful and do not require implementing this RFC. Their owner routing and completion conditions are recorded in the [assessment](../design/review-2026-10-07-assessment.md). Missing reasons in old records remain unknown. E3101 incidence remains measurable by code without this prerequisite; neither future instrumentation nor existing counts justify relaxing the repair-cost/workflow conditions above.
|
||||
The independent instrumentation prerequisite is implemented by DD-017/spec 15 §10: E7006 carries a stable `reason`, `move_copy` excludes borrowed and non-materializable operands, and ajieval counts occurrences and affected runs by code/reason without parsing `message`. These changes implement no edits or application workflow. The [assessment](../design/review-2026-10-07-assessment.md) records the baseline gap and subsequent follow-up. Missing reasons in old records remain unknown; no historical data is relabeled and no new incidence experiment is supplied. E3101 remains countable by code. This instrumentation does not satisfy the repair-cost/workflow conditions above or change this RFC's Proposed status and recommendation to defer.
|
||||
|
||||
No numeric N% or minimum sample size is justified by the current reports. If the owner chooses an incidence threshold and sample-size gate, record them before evaluating a new cohort rather than selecting them to match observed results. These conditions reopen design review; they do not automatically accept the RFC. Do not change frozen B1 instrumentation or inputs, inspect private held-out material, or use M/C to select or tune the eligible transformations. An authorized independent operator may publish aggregate metadata under the evaluation protocol.
|
||||
|
||||
|
||||
@@ -14,6 +14,8 @@ Every verifier/compiler error has:
|
||||
- optional human explanation;
|
||||
- optional non-binding repair candidates.
|
||||
|
||||
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`.
|
||||
|
||||
Example:
|
||||
|
||||
```json
|
||||
|
||||
@@ -421,6 +421,8 @@ Its diagnostics keep their AIR codes, reported at the source location.
|
||||
| E7007 | source.ambiguous | Source meaning cannot be determined (e.g. an integer literal with no type from context) |
|
||||
| E7900 | source.internal_compiler_error | The frontend produced invalid AIR for this construct (a compiler bug, not a program error) |
|
||||
|
||||
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.
|
||||
|
||||
## 11. Tooling
|
||||
|
||||
| Command | Does |
|
||||
|
||||
@@ -94,6 +94,38 @@ pub fn lookup(id: []const u8) ?*const Code {
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Stable E7006 categories (spec 15 §10; reference/error-codes.md).
|
||||
pub const SourceInvalidReason = enum {
|
||||
move_copy,
|
||||
move_borrow,
|
||||
invalid_move,
|
||||
loop_control_outside_loop,
|
||||
zero_not_zeroable,
|
||||
value_block_statement,
|
||||
@"unreachable",
|
||||
missing_return,
|
||||
invalid_borrow,
|
||||
invalid_borrow_return,
|
||||
duplicate_declaration,
|
||||
invalid_declaration,
|
||||
invalid_binding,
|
||||
invalid_assignment,
|
||||
invalid_place,
|
||||
invalid_match,
|
||||
invalid_unpack,
|
||||
invalid_expression,
|
||||
invalid_operation,
|
||||
invalid_literal,
|
||||
invalid_generic,
|
||||
invalid_static_function,
|
||||
implementation_limit,
|
||||
invalid_module_mapping,
|
||||
duplicate_import,
|
||||
import_cycle,
|
||||
module_header_mismatch,
|
||||
trusted_unavailable,
|
||||
};
|
||||
|
||||
pub const Severity = enum { @"error", warning, note };
|
||||
|
||||
pub const Span = struct {
|
||||
@@ -212,3 +244,21 @@ test "registry ids are unique" {
|
||||
for (registry[i + 1 ..]) |b| try std.testing.expect(!std.mem.eql(u8, a.id, b.id));
|
||||
}
|
||||
}
|
||||
|
||||
test "E7006 reason registry mirrors documentation" {
|
||||
const md = @embedFile("error_codes_md");
|
||||
const heading = "## E7006 reasons\n";
|
||||
const start = (std.mem.indexOf(u8, md, heading) orelse return error.RegistryOutOfSync) + heading.len;
|
||||
const section = md[start..];
|
||||
const section_end = std.mem.indexOf(u8, section, "\n## ") orelse section.len;
|
||||
var lines = std.mem.splitScalar(u8, section[0..section_end], '\n');
|
||||
var seen: std.EnumSet(SourceInvalidReason) = .empty;
|
||||
while (lines.next()) |line| {
|
||||
if (!std.mem.startsWith(u8, line, "| `")) continue;
|
||||
const end = std.mem.indexOfScalarPos(u8, line, 3, '`') orelse return error.RegistryOutOfSync;
|
||||
const reason = std.meta.stringToEnum(SourceInvalidReason, line[3..end]) orelse return error.RegistryOutOfSync;
|
||||
try std.testing.expect(!seen.contains(reason));
|
||||
seen.insert(reason);
|
||||
}
|
||||
try std.testing.expect(seen.eql(.full));
|
||||
}
|
||||
+3
-2
@@ -44,8 +44,9 @@ pub fn compileWithModules(arena: std.mem.Allocator, file: []const u8, source: []
|
||||
return switch (result) {
|
||||
.ok => |o| .{ .ok = o },
|
||||
.err => |p| blk: {
|
||||
const fields = try arena.alloc(diag.Field, p.fields.len);
|
||||
for (p.fields, fields) |pf, *f| f.* = .{ .name = pf.name, .value = .{ .str = pf.value } };
|
||||
const fields = try arena.alloc(diag.Field, p.fields.len + @intFromBool(p.reason != null));
|
||||
for (p.fields, fields[0..p.fields.len]) |pf, *f| f.* = .{ .name = pf.name, .value = .{ .str = pf.value } };
|
||||
if (p.reason) |reason| fields[p.fields.len] = .{ .name = "reason", .value = .{ .str = @tagName(reason) } };
|
||||
break :blk .{ .err = .{
|
||||
.code = diag.lookup(p.code).?,
|
||||
.span = .{ .file = p.span.file orelse file, .line = p.span.start.line, .col = p.span.start.col },
|
||||
|
||||
+49
-43
@@ -27,11 +27,17 @@ const Generator = struct {
|
||||
type_depth: usize = 0,
|
||||
problem: ?lower.Problem = null,
|
||||
|
||||
fn fail(g: *Generator, code: []const u8, span: ast.Span, message: []const u8, name: []const u8) Error {
|
||||
fn fail(g: *Generator, comptime code: []const u8, span: ast.Span, message: []const u8, name: []const u8) Error {
|
||||
if (comptime std.mem.eql(u8, code, "E7006")) @compileError("E7006 requires an explicit reason via invalid()");
|
||||
g.problem = .{ .code = code, .span = span, .message = message, .fields = try g.arena.dupe(lower.Problem.Field, &.{.{ .name = "name", .value = name }}) };
|
||||
return error.InvalidGeneric;
|
||||
}
|
||||
|
||||
fn invalid(g: *Generator, reason: lower.InvalidReason, span: ast.Span, message: []const u8, name: []const u8) Error {
|
||||
g.problem = .{ .code = "E7006", .reason = reason, .span = span, .message = message, .fields = try g.arena.dupe(lower.Problem.Field, &.{.{ .name = "name", .value = name }}) };
|
||||
return error.InvalidGeneric;
|
||||
}
|
||||
|
||||
fn bound(g: *Generator, name: []const u8, span: ast.Span) ?[]const u8 {
|
||||
if (span.resolved) return name;
|
||||
const origin = span.namespace orelse g.m.name;
|
||||
@@ -62,7 +68,7 @@ const Generator = struct {
|
||||
}
|
||||
|
||||
fn checkBinding(g: *Generator, name: []const u8, span: ast.Span, env: Env) Error!void {
|
||||
for (env.params) |p| if (p.callable != null and std.mem.eql(u8, p.name, name)) return g.fail("E7006", span, "runtime binding shadows a static function parameter", name);
|
||||
for (env.params) |p| if (p.callable != null and std.mem.eql(u8, p.name, name)) return g.invalid(.invalid_static_function, span, "runtime binding shadows a static function parameter", name);
|
||||
}
|
||||
|
||||
fn boundFunction(env: Env, name: []const u8) ?ast.Type {
|
||||
@@ -74,14 +80,14 @@ const Generator = struct {
|
||||
const f = arg.kind.function_ref;
|
||||
var out = arg;
|
||||
if (boundFunction(env, f.name)) |bound_arg| {
|
||||
if (f.args.len != 0) return g.fail("E7006", arg.span, "bound static function cannot be specialized again", f.name);
|
||||
if (f.args.len != 0) return g.invalid(.invalid_static_function, arg.span, "bound static function cannot be specialized again", f.name);
|
||||
out.kind = bound_arg.kind;
|
||||
} else {
|
||||
const target = g.function(f.name, arg.span) orelse return g.fail("E7002", arg.span, "unknown or inaccessible static function", f.name);
|
||||
const name = if (target.generics.len != 0)
|
||||
try g.instantiate(false, target, f.args, env, arg.span)
|
||||
else blk: {
|
||||
if (f.args.len != 0) return g.fail("E7006", arg.span, "non-generic function does not take static arguments", f.name);
|
||||
if (f.args.len != 0) return g.invalid(.invalid_static_function, arg.span, "non-generic function does not take static arguments", f.name);
|
||||
break :blk target.name;
|
||||
};
|
||||
out.kind = .{ .function_ref = .{ .name = name } };
|
||||
@@ -132,7 +138,7 @@ const Generator = struct {
|
||||
const name = arg.kind.function_ref.name;
|
||||
const selected = if (g.function(name, arg.span)) |f| f else blk: {
|
||||
for (g.instances.items) |instance| if (std.mem.eql(u8, instance.name, name)) {
|
||||
break :blk instance.signature orelse return g.fail("E7006", arg.span, "cyclic static function contract resolution", parameter);
|
||||
break :blk instance.signature orelse return g.invalid(.invalid_static_function, arg.span, "cyclic static function contract resolution", parameter);
|
||||
};
|
||||
return g.fail("E7002", arg.span, "unknown static function specialization", name);
|
||||
};
|
||||
@@ -150,45 +156,45 @@ const Generator = struct {
|
||||
}
|
||||
|
||||
fn validate(g: *Generator, name: []const u8, params: []const ast.TypeParam, span: ast.Span) Error!void {
|
||||
if (params.len > 8) return g.fail("E7006", span, "generic declaration limit or generic entry", name);
|
||||
if (params.len > 8) return g.invalid(.implementation_limit, span, "generic declaration limit or generic entry", name);
|
||||
for (params, 0..) |p, i| {
|
||||
if (!std.ascii.isUpper(p.name[0]) or g.typeDecl(p.name, p.span) != null or builtin(p.name)) return g.fail("E7006", p.span, "type parameter must be uppercase and not shadow a visible type", p.name);
|
||||
for (params[0..i]) |previous| if (std.mem.eql(u8, p.name, previous.name)) return g.fail("E7006", p.span, "duplicate type parameter", p.name);
|
||||
if (!std.ascii.isUpper(p.name[0]) or g.typeDecl(p.name, p.span) != null or builtin(p.name)) return g.invalid(.invalid_generic, p.span, "type parameter must be uppercase and not shadow a visible type", p.name);
|
||||
for (params[0..i]) |previous| if (std.mem.eql(u8, p.name, previous.name)) return g.invalid(.duplicate_declaration, p.span, "duplicate type parameter", p.name);
|
||||
if (p.callable) |c| {
|
||||
if (p.constraints.len != 0 or g.function(p.name, p.span) != null) return g.fail("E7006", p.span, "invalid static function parameter", p.name);
|
||||
if (p.constraints.len != 0 or g.function(p.name, p.span) != null) return g.invalid(.invalid_static_function, p.span, "invalid static function parameter", p.name);
|
||||
for (c.params) |t| try g.headerType(t, params, 0);
|
||||
try g.headerType(c.ret, params, 0);
|
||||
if (c.ret.kind == .wrapped) {
|
||||
const w = c.ret.kind.wrapped.wrapper;
|
||||
if (std.mem.eql(u8, w, "ref") or std.mem.eql(u8, w, "mut") or std.mem.eql(u8, w, "slice") or std.mem.eql(u8, w, "slice_mut")) return g.fail("E7006", c.ret.span, "static function contracts do not support borrowed returns", p.name);
|
||||
if (std.mem.eql(u8, w, "ref") or std.mem.eql(u8, w, "mut") or std.mem.eql(u8, w, "slice") or std.mem.eql(u8, w, "slice_mut")) return g.invalid(.invalid_static_function, c.ret.span, "static function contracts do not support borrowed returns", p.name);
|
||||
}
|
||||
for (c.effects, 0..) |effect, j| {
|
||||
if (authority.effectIndex(effect) == null) return g.fail("E0006", p.span, "unknown effect in static function contract", effect);
|
||||
for (c.effects[0..j]) |prev| if (std.mem.eql(u8, prev, effect)) return g.fail("E7006", p.span, "duplicate effect in static function contract", effect);
|
||||
for (c.effects[0..j]) |prev| if (std.mem.eql(u8, prev, effect)) return g.invalid(.invalid_static_function, p.span, "duplicate effect in static function contract", effect);
|
||||
}
|
||||
}
|
||||
for (p.constraints, 0..) |c, j| {
|
||||
if (std.meta.stringToEnum(Property, c) == null) return g.fail("E7006", p.span, "unknown structural constraint", c);
|
||||
for (p.constraints[0..j]) |previous| if (std.mem.eql(u8, c, previous)) return g.fail("E7006", p.span, "duplicate structural constraint", c);
|
||||
if (std.meta.stringToEnum(Property, c) == null) return g.invalid(.invalid_generic, p.span, "unknown structural constraint", c);
|
||||
for (p.constraints[0..j]) |previous| if (std.mem.eql(u8, c, previous)) return g.invalid(.invalid_generic, p.span, "duplicate structural constraint", c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn headerType(g: *Generator, t: ast.Type, params: []const ast.TypeParam, depth: usize) Error!void {
|
||||
if (depth >= 64) return g.fail("E7006", t.span, "type traversal exceeds depth 64", "type");
|
||||
if (depth >= 64) return g.invalid(.implementation_limit, t.span, "type traversal exceeds depth 64", "type");
|
||||
switch (t.kind) {
|
||||
.name => |n| {
|
||||
for (params) |p| if (std.mem.eql(u8, n, p.name)) {
|
||||
if (p.callable != null) return g.fail("E7006", t.span, "static function parameter is not a type", n);
|
||||
if (p.callable != null) return g.invalid(.invalid_static_function, t.span, "static function parameter is not a type", n);
|
||||
return;
|
||||
};
|
||||
if (g.typeDecl(n, t.span)) |d| {
|
||||
if (d.generics.len != 0) return g.fail("E7006", t.span, "template type needs explicit arguments", n);
|
||||
if (d.generics.len != 0) return g.invalid(.invalid_generic, t.span, "template type needs explicit arguments", n);
|
||||
} else if (!builtin(n)) return g.fail("E7002", t.span, "unknown template signature type", n);
|
||||
},
|
||||
.applied => |x| {
|
||||
const d = g.typeDecl(x.name, t.span) orelse return g.fail("E7002", t.span, "unknown template signature type", x.name);
|
||||
if (d.generics.len == 0 or d.generics.len != x.args.len) return g.fail("E7006", t.span, "template type argument count mismatch", x.name);
|
||||
if (d.generics.len == 0 or d.generics.len != x.args.len) return g.invalid(.invalid_generic, t.span, "template type argument count mismatch", x.name);
|
||||
for (d.generics, x.args) |p, arg| try g.headerArgument(p, arg, params, depth + 1);
|
||||
},
|
||||
.array => |a| {
|
||||
@@ -198,12 +204,12 @@ const Generator = struct {
|
||||
.wrapped => |w| try g.headerType(w.inner.*, params, depth + 1),
|
||||
.cap => |k| if (authority.kindIndex(k) == null) return g.fail("E7002", t.span, "unknown capability kind", k),
|
||||
.file => |mode| if (!(std.mem.eql(u8, mode, "read") or std.mem.eql(u8, mode, "write") or std.mem.eql(u8, mode, "append"))) return g.fail("E7002", t.span, "unknown file mode", mode),
|
||||
.function_ref => return g.fail("E7006", t.span, "static functions are not runtime types", "fn"),
|
||||
.function_ref => return g.invalid(.invalid_static_function, t.span, "static functions are not runtime types", "fn"),
|
||||
}
|
||||
}
|
||||
|
||||
fn headerArgument(g: *Generator, expected: ast.TypeParam, arg: ast.Type, params: []const ast.TypeParam, depth: usize) Error!void {
|
||||
if (depth >= 64) return g.fail("E7006", arg.span, "generic argument traversal exceeds depth 64", expected.name);
|
||||
if (depth >= 64) return g.invalid(.implementation_limit, arg.span, "generic argument traversal exceeds depth 64", expected.name);
|
||||
if (expected.callable == null) {
|
||||
if (arg.kind == .function_ref) return g.fail("E7005", arg.span, "expected a type argument, found a static function", expected.name);
|
||||
return g.headerType(arg, params, depth);
|
||||
@@ -211,11 +217,11 @@ const Generator = struct {
|
||||
if (arg.kind != .function_ref) return g.fail("E7005", arg.span, "expected an explicit static function argument", expected.name);
|
||||
const f = arg.kind.function_ref;
|
||||
for (params) |parameter| if (std.mem.eql(u8, parameter.name, f.name) and parameter.callable != null) {
|
||||
if (f.args.len != 0) return g.fail("E7006", arg.span, "bound static function cannot be specialized again", f.name);
|
||||
if (f.args.len != 0) return g.invalid(.invalid_static_function, arg.span, "bound static function cannot be specialized again", f.name);
|
||||
return;
|
||||
};
|
||||
const target = g.function(f.name, arg.span) orelse return g.fail("E7002", arg.span, "unknown or inaccessible static function", f.name);
|
||||
if (target.generics.len != f.args.len) return g.fail("E7006", arg.span, "static function argument count mismatch", f.name);
|
||||
if (target.generics.len != f.args.len) return g.invalid(.invalid_static_function, arg.span, "static function argument count mismatch", f.name);
|
||||
for (target.generics, f.args) |p, a| try g.headerArgument(p, a, params, depth + 1);
|
||||
}
|
||||
|
||||
@@ -242,21 +248,21 @@ const Generator = struct {
|
||||
const origin = borrowMode(param.ty, f.generics);
|
||||
if (ret == 0 or origin == 0) return g.fail("E7005", f.span, "from requires a borrow return and a borrow parameter", name);
|
||||
if (ret == 2 and origin == 1) return g.fail("E7005", f.span, "exclusive return requires an exclusive from parameter", name);
|
||||
} else if (ret == 1 or ret == 2) return g.fail("E7006", f.span, "a borrow return requires from parameter", f.name);
|
||||
} else if (ret == 1 or ret == 2) return g.invalid(.invalid_borrow_return, f.span, "a borrow return requires from parameter", f.name);
|
||||
}
|
||||
|
||||
fn run(g: *Generator) Error!ast.Module {
|
||||
var generic = false;
|
||||
for (g.m.types, 0..) |t, i| {
|
||||
for (g.m.types[0..i]) |previous| if (std.mem.eql(u8, t.name, previous.name)) return g.fail("E7006", t.span, "type defined twice", t.name);
|
||||
for (g.m.types[0..i]) |previous| if (std.mem.eql(u8, t.name, previous.name)) return g.invalid(.duplicate_declaration, t.span, "type defined twice", t.name);
|
||||
try g.validate(t.name, t.generics, t.span);
|
||||
switch (t.kind) {
|
||||
.@"struct" => |fs| for (fs, 0..) |f, j| {
|
||||
for (fs[0..j]) |prev| if (std.mem.eql(u8, f.name, prev.name)) return g.fail("E7006", f.span, "duplicate template field", f.name);
|
||||
for (fs[0..j]) |prev| if (std.mem.eql(u8, f.name, prev.name)) return g.invalid(.duplicate_declaration, f.span, "duplicate template field", f.name);
|
||||
},
|
||||
.@"enum" => |vs| {
|
||||
if (vs.len == 0) return g.fail("E7006", t.span, "enum needs a variant", t.name);
|
||||
for (vs, 0..) |v, j| for (vs[0..j]) |prev| if (std.mem.eql(u8, v.name, prev.name)) return g.fail("E7006", v.span, "duplicate template variant", v.name);
|
||||
if (vs.len == 0) return g.invalid(.invalid_declaration, t.span, "enum needs a variant", t.name);
|
||||
for (vs, 0..) |v, j| for (vs[0..j]) |prev| if (std.mem.eql(u8, v.name, prev.name)) return g.invalid(.duplicate_declaration, v.span, "duplicate template variant", v.name);
|
||||
},
|
||||
}
|
||||
if (t.generics.len != 0) switch (t.kind) {
|
||||
@@ -266,15 +272,15 @@ const Generator = struct {
|
||||
generic = generic or t.generics.len != 0;
|
||||
}
|
||||
for (g.m.functions, 0..) |f, i| {
|
||||
for (g.m.functions[0..i]) |previous| if (std.mem.eql(u8, f.name, previous.name)) return g.fail("E7006", f.span, "function defined twice", f.name);
|
||||
if (f.generics.len != 0 and std.mem.eql(u8, f.name, "main")) return g.fail("E7006", f.span, "entry cannot be generic", f.name);
|
||||
for (g.m.functions[0..i]) |previous| if (std.mem.eql(u8, f.name, previous.name)) return g.invalid(.duplicate_declaration, f.span, "function defined twice", f.name);
|
||||
if (f.generics.len != 0 and std.mem.eql(u8, f.name, "main")) return g.invalid(.invalid_generic, f.span, "entry cannot be generic", f.name);
|
||||
try g.validate(f.name, f.generics, f.span);
|
||||
if (f.generics.len != 0) {
|
||||
if (f.trusted != null) return g.fail("E7006", f.span, "trusted is not available in source templates", f.name);
|
||||
if (f.trusted != null) return g.invalid(.trusted_unavailable, f.span, "trusted is not available in source templates", f.name);
|
||||
for (f.effects) |effect| if (authority.effectIndex(effect) == null) return g.fail("E0006", f.span, "unknown effect in template contract", effect);
|
||||
for (f.params, 0..) |p, j| {
|
||||
try g.checkBinding(p.name, p.span, .{ .params = f.generics });
|
||||
for (f.params[0..j]) |prev| if (std.mem.eql(u8, p.name, prev.name)) return g.fail("E7006", p.span, "duplicate value parameter", p.name);
|
||||
for (f.params[0..j]) |prev| if (std.mem.eql(u8, p.name, prev.name)) return g.invalid(.duplicate_declaration, p.span, "duplicate value parameter", p.name);
|
||||
try g.headerType(p.ty, f.generics, 0);
|
||||
}
|
||||
try g.headerType(f.ret, f.generics, 0);
|
||||
@@ -320,10 +326,10 @@ const Generator = struct {
|
||||
}
|
||||
|
||||
fn instantiate(g: *Generator, comptime is_type: bool, template: if (is_type) ast.TypeDecl else ast.FnDecl, raw: []const ast.Type, env: Env, span: ast.Span) Error![]const u8 {
|
||||
if (g.depth >= 64) return g.fail("E7006", span, "generic argument or contract resolution exceeds depth 64", template.name);
|
||||
if (g.depth >= 64) return g.invalid(.implementation_limit, span, "generic argument or contract resolution exceeds depth 64", template.name);
|
||||
g.depth += 1;
|
||||
defer g.depth -= 1;
|
||||
if (template.generics.len == 0 or template.generics.len != raw.len) return g.fail("E7006", span, "explicit type argument count does not match declaration", template.name);
|
||||
if (template.generics.len == 0 or template.generics.len != raw.len) return g.invalid(.invalid_generic, span, "explicit type argument count does not match declaration", template.name);
|
||||
const args = try g.arena.alloc(ast.Type, raw.len);
|
||||
var key: std.ArrayList(u8) = .empty;
|
||||
try key.appendSlice(g.arena, if (is_type) "type:" else "fn:");
|
||||
@@ -344,9 +350,9 @@ const Generator = struct {
|
||||
try g.identity(out.*, &key);
|
||||
}
|
||||
try key.append(g.arena, '>');
|
||||
if (key.items.len > 16384) return g.fail("E7006", span, "canonical specialization key exceeds 16384 bytes", template.name);
|
||||
if (key.items.len > 16384) return g.invalid(.implementation_limit, span, "canonical specialization key exceeds 16384 bytes", template.name);
|
||||
for (g.instances.items) |instance| if (std.mem.eql(u8, instance.key, key.items)) return instance.name;
|
||||
if (g.instances.items.len >= 4096) return g.fail("E7006", span, "generic specialization exceeds fixed compiler limit", template.name);
|
||||
if (g.instances.items.len >= 4096) return g.invalid(.implementation_limit, span, "generic specialization exceeds fixed compiler limit", template.name);
|
||||
const hex = try g.arena.alloc(u8, key.items.len * 2);
|
||||
for (key.items, 0..) |b, i| {
|
||||
hex[2 * i] = "0123456789abcdef"[b >> 4];
|
||||
@@ -450,7 +456,7 @@ const Generator = struct {
|
||||
}
|
||||
},
|
||||
}
|
||||
if (out.items.len > 16384) return g.fail("E7006", t.span, "canonical specialization key exceeds 16384 bytes", "type");
|
||||
if (out.items.len > 16384) return g.invalid(.implementation_limit, t.span, "canonical specialization key exceeds 16384 bytes", "type");
|
||||
}
|
||||
|
||||
fn named(g: *Generator, name: []const u8, args: []const ast.Type, span: ast.Span, env: Env) Error!ast.Type {
|
||||
@@ -458,18 +464,18 @@ const Generator = struct {
|
||||
}
|
||||
|
||||
fn ty(g: *Generator, input: ast.Type, env: Env) Error!ast.Type {
|
||||
if (g.type_depth >= 64) return g.fail("E7006", input.span, "structural type depth exceeds 64", "type");
|
||||
if (g.type_depth >= 64) return g.invalid(.implementation_limit, input.span, "structural type depth exceeds 64", "type");
|
||||
g.type_depth += 1;
|
||||
defer g.type_depth -= 1;
|
||||
var t = input;
|
||||
switch (input.kind) {
|
||||
.name => |name| {
|
||||
for (env.params, env.args) |p, arg| if (std.mem.eql(u8, name, p.name)) {
|
||||
if (p.callable != null) return g.fail("E7006", input.span, "static function parameter is not a type", name);
|
||||
if (p.callable != null) return g.invalid(.invalid_static_function, input.span, "static function parameter is not a type", name);
|
||||
return arg;
|
||||
};
|
||||
if (g.typeDecl(name, input.span)) |d| {
|
||||
if (d.generics.len != 0) return g.fail("E7006", input.span, "generic type needs explicit arguments", name);
|
||||
if (d.generics.len != 0) return g.invalid(.invalid_generic, input.span, "generic type needs explicit arguments", name);
|
||||
t.kind.name = d.name;
|
||||
t.span.resolved = true;
|
||||
} else if (!builtin(name) and !g.generated(name)) return g.fail("E7002", input.span, "unknown or inaccessible type", name);
|
||||
@@ -482,7 +488,7 @@ const Generator = struct {
|
||||
.array => |a| t.kind.array.elem = try g.box(ast.Type, try g.ty(a.elem.*, env)),
|
||||
.wrapped => |w| t.kind.wrapped.inner = try g.box(ast.Type, try g.ty(w.inner.*, env)),
|
||||
.cap, .file => {},
|
||||
.function_ref => return g.fail("E7006", input.span, "static functions are not runtime types", "fn"),
|
||||
.function_ref => return g.invalid(.invalid_static_function, input.span, "static functions are not runtime types", "fn"),
|
||||
}
|
||||
return t;
|
||||
}
|
||||
@@ -496,11 +502,11 @@ const Generator = struct {
|
||||
var out = e;
|
||||
if (e.kind == .move and env.params.len != 0) out.generic_transfer = true;
|
||||
switch (e.kind) {
|
||||
.name => |name| if (boundFunction(env, name) != null) return g.fail("E7006", e.span, "static function parameter is only a call target or named worker", name),
|
||||
.name => |name| if (boundFunction(env, name) != null) return g.invalid(.invalid_static_function, e.span, "static function parameter is only a call target or named worker", name),
|
||||
.specialize => |x| {
|
||||
const name = path(g.arena, x.base.*) catch return error.OutOfMemory;
|
||||
if (name) |n| if (boundFunction(env, n) != null) return g.fail("E7006", e.span, "bound static function cannot be specialized again", n);
|
||||
const d = g.function(name orelse return g.fail("E7006", e.span, "generic worker or call must be named", "function"), e.span) orelse return g.fail("E7002", e.span, "unknown or inaccessible generic function", name.?);
|
||||
if (name) |n| if (boundFunction(env, n) != null) return g.invalid(.invalid_static_function, e.span, "bound static function cannot be specialized again", n);
|
||||
const d = g.function(name orelse return g.invalid(.invalid_generic, e.span, "generic worker or call must be named", "function"), e.span) orelse return g.fail("E7002", e.span, "unknown or inaccessible generic function", name.?);
|
||||
out.kind = .{ .name = try g.instantiate(false, d, x.args, env, e.span) };
|
||||
out.span.resolved = true;
|
||||
return out;
|
||||
@@ -514,7 +520,7 @@ const Generator = struct {
|
||||
return out;
|
||||
};
|
||||
if (x.callee.kind != .specialize and x.callee.kind != .variant) if (try path(g.arena, x.callee.*)) |name| if (g.function(name, x.callee.span)) |d| {
|
||||
if (d.generics.len != 0) return g.fail("E7006", e.span, "generic function needs explicit arguments", name);
|
||||
if (d.generics.len != 0) return g.invalid(.invalid_generic, e.span, "generic function needs explicit arguments", name);
|
||||
};
|
||||
out.kind.call.callee = try g.box(ast.Expr, try g.expression(x.callee.*, env));
|
||||
const args = try g.arena.alloc(ast.Expr, x.args.len);
|
||||
|
||||
+90
-81
@@ -139,7 +139,10 @@ fn intBits(n: []const u8) u16 {
|
||||
return std.fmt.parseInt(u16, n[1..], 10) catch 64;
|
||||
}
|
||||
|
||||
pub const InvalidReason = @import("../diag.zig").SourceInvalidReason;
|
||||
|
||||
pub const Problem = struct {
|
||||
reason: ?InvalidReason = null,
|
||||
code: []const u8,
|
||||
span: Span,
|
||||
message: []const u8,
|
||||
@@ -355,12 +358,18 @@ const Lowerer = struct {
|
||||
};
|
||||
}
|
||||
|
||||
fn fail(l: *Lowerer, code: []const u8, span: Span, message: []const u8, fields: []const Problem.Field) Error {
|
||||
fn fail(l: *Lowerer, comptime code: []const u8, span: Span, message: []const u8, fields: []const Problem.Field) Error {
|
||||
if (comptime std.mem.eql(u8, code, "E7006")) @compileError("E7006 requires an explicit reason via invalid()");
|
||||
// `fields` usually points at a temporary array: keep a copy.
|
||||
l.problem = .{ .code = code, .span = span, .message = message, .fields = try l.arena.dupe(Problem.Field, fields) };
|
||||
return error.Lower;
|
||||
}
|
||||
|
||||
fn invalid(l: *Lowerer, reason: InvalidReason, span: Span, message: []const u8, fields: []const Problem.Field) Error {
|
||||
l.problem = .{ .code = "E7006", .reason = reason, .span = span, .message = message, .fields = try l.arena.dupe(Problem.Field, fields) };
|
||||
return error.Lower;
|
||||
}
|
||||
|
||||
fn notYet(l: *Lowerer, span: Span, construct: []const u8) Error {
|
||||
l.unimpl = .{ .span = span, .construct = construct };
|
||||
return error.Unimplemented;
|
||||
@@ -443,12 +452,12 @@ const Lowerer = struct {
|
||||
fn run(l: *Lowerer) Error!void {
|
||||
const names = try l.arena.alloc([]const u8, l.m.types.len);
|
||||
for (l.m.types, names, 0..) |t, *n, i| {
|
||||
for (l.m.types[0..i]) |prev| if (std.mem.eql(u8, prev.name, t.name)) return l.fail("E7006", t.span, "type defined twice", &.{.{ .name = "name", .value = t.name }});
|
||||
for (l.m.types[0..i]) |prev| if (std.mem.eql(u8, prev.name, t.name)) return l.invalid(.duplicate_declaration, t.span, "type defined twice", &.{.{ .name = "name", .value = t.name }});
|
||||
n.* = try l.fmt("@{s}", .{t.air_name orelse t.name});
|
||||
}
|
||||
l.typeNames = names;
|
||||
for (l.m.functions) |f| {
|
||||
if (l.sigs.contains(f.name)) return l.fail("E7006", f.span, "function defined twice", &.{.{ .name = "name", .value = f.name }});
|
||||
if (l.sigs.contains(f.name)) return l.invalid(.duplicate_declaration, f.span, "function defined twice", &.{.{ .name = "name", .value = f.name }});
|
||||
const ps = try l.arena.alloc(Ty, f.params.len);
|
||||
for (f.params, ps) |p, *t| t.* = try l.typeOf(p.ty);
|
||||
const ret = try l.typeOf(f.ret);
|
||||
@@ -461,8 +470,8 @@ const Lowerer = struct {
|
||||
const i = origin orelse return l.unknown(f.span, name);
|
||||
if (!ret.isBorrow() or !ps[i].isBorrow()) return l.fail("E7005", f.span, "`from` requires a borrow return and a borrow parameter", &.{});
|
||||
if (ret.isMutBorrow() and !ps[i].isMutBorrow()) return l.fail("E7005", f.span, "an exclusive return requires an exclusive `from` parameter", &.{});
|
||||
} else if (ret.isBorrow()) return l.fail("E7006", f.span, "a borrow return requires `from parameter`", &.{});
|
||||
if (std.mem.eql(u8, f.name, "main") and ret.isBorrow()) return l.fail("E7006", f.span, "main cannot return a borrow", &.{});
|
||||
} else if (ret.isBorrow()) return l.invalid(.invalid_borrow_return, f.span, "a borrow return requires `from parameter`", &.{});
|
||||
if (std.mem.eql(u8, f.name, "main") and ret.isBorrow()) return l.invalid(.invalid_borrow_return, f.span, "main cannot return a borrow", &.{});
|
||||
try l.sigs.put(l.arena, f.name, .{ .params = ps, .ret = ret, .from = origin, .air_name = f.air_name orelse f.name, .display_name = f.display_name orelse f.name });
|
||||
}
|
||||
if (!l.sigs.contains("main")) return l.fail("E7002", .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 1 } }, "the module has no `main` function", &.{.{ .name = "name", .value = "main" }});
|
||||
@@ -550,7 +559,7 @@ const Lowerer = struct {
|
||||
for (l.m.requirements) |r| {
|
||||
const ty = try l.typeOf(r.ty);
|
||||
const t = try l.airType(ty);
|
||||
if (!boundedType(m, t, 0)) return l.fail("E7006", r.span, "constraint type traversal is cyclic or exceeds depth 64", &.{});
|
||||
if (!boundedType(m, t, 0)) return l.invalid(.implementation_limit, r.span, "constraint type traversal is cyclic or exceeds depth 64", &.{});
|
||||
if (r.property.len == 0) {
|
||||
var context: @import("../verifier.zig").Context = .{ .arena = l.arena, .file = "<generic>", .module = m };
|
||||
try verifier_types.checkTypeArgument(&context, .{ .line = 1, .col = 1 }, t);
|
||||
@@ -632,17 +641,17 @@ const Lowerer = struct {
|
||||
.@"struct" => |fields| {
|
||||
try w.appendSlice(l.arena, "struct {");
|
||||
for (fields, 0..) |f, i| {
|
||||
for (fields[0..i]) |prev| if (std.mem.eql(u8, prev.name, f.name)) return l.fail("E7006", f.span, "field declared twice", &.{.{ .name = "field", .value = f.name }});
|
||||
for (fields[0..i]) |prev| if (std.mem.eql(u8, prev.name, f.name)) return l.invalid(.duplicate_declaration, f.span, "field declared twice", &.{.{ .name = "field", .value = f.name }});
|
||||
const ft = try l.memberType(f.ty);
|
||||
try w.appendSlice(l.arena, try l.fmt("{s}{s}: {s}", .{ if (i == 0) " " else ", ", f.name, l.tyText(ft) }));
|
||||
}
|
||||
try w.appendSlice(l.arena, if (fields.len == 0) "}" else " }");
|
||||
},
|
||||
.@"enum" => |vs| {
|
||||
if (vs.len == 0) return l.fail("E7006", t.span, "an enum needs at least one variant", &.{.{ .name = "type", .value = t.name }});
|
||||
if (vs.len == 0) return l.invalid(.invalid_declaration, t.span, "an enum needs at least one variant", &.{.{ .name = "type", .value = t.name }});
|
||||
try w.appendSlice(l.arena, "enum { ");
|
||||
for (vs, 0..) |v, i| {
|
||||
for (vs[0..i]) |prev| if (std.mem.eql(u8, prev.name, v.name)) return l.fail("E7006", v.span, "variant declared twice", &.{.{ .name = "variant", .value = v.name }});
|
||||
for (vs[0..i]) |prev| if (std.mem.eql(u8, prev.name, v.name)) return l.invalid(.duplicate_declaration, v.span, "variant declared twice", &.{.{ .name = "variant", .value = v.name }});
|
||||
if (i != 0) try w.appendSlice(l.arena, ", ");
|
||||
try w.appendSlice(l.arena, v.name);
|
||||
if (v.payload.len != 0) {
|
||||
@@ -666,7 +675,7 @@ const Lowerer = struct {
|
||||
fn typeOf(l: *Lowerer, t: ast.Type) Error!Ty {
|
||||
switch (t.kind) {
|
||||
.applied => return l.fail("E7002", t.span, "unknown generic type", &.{}),
|
||||
.function_ref => return l.fail("E7006", t.span, "static functions are not runtime types", &.{}),
|
||||
.function_ref => return l.invalid(.invalid_static_function, t.span, "static functions are not runtime types", &.{}),
|
||||
.name => |n| {
|
||||
if (isIntName(n)) return .{ .int = n };
|
||||
if (std.mem.eql(u8, n, "bool")) return .bool;
|
||||
@@ -735,7 +744,7 @@ const Lowerer = struct {
|
||||
l.borrow_parents = .empty;
|
||||
// `trusted` is the boundary of runtime, std and toolchain modules; an
|
||||
// ordinary program cannot declare its own code trusted (spec 15 §8).
|
||||
if (f.trusted != null) return l.fail("E7006", f.span, "`trusted` is not available in .aji programs; unsafe operations need `effects [unsafe]`, which propagates to callers", &.{});
|
||||
if (f.trusted != null) return l.invalid(.trusted_unavailable, f.span, "`trusted` is not available in .aji programs; unsafe operations need `effects [unsafe]`, which propagates to callers", &.{});
|
||||
for (f.effects) |e| if (std.mem.eql(u8, e, "unsafe")) l.uses.insert(.unsafe);
|
||||
|
||||
var header: std.ArrayList(u8) = .empty;
|
||||
@@ -755,14 +764,14 @@ const Lowerer = struct {
|
||||
const tail = try l.blockBodyWant(f.body, sig.ret);
|
||||
if (l.cur != null) {
|
||||
if (tail != null and tail.?.ty == .void and sig.ret != .void) {
|
||||
return l.fail("E7006", f.body.tail.?.span, "the function can end without returning a value", &.{.{ .name = "function", .value = f.name }});
|
||||
return l.invalid(.missing_return, f.body.tail.?.span, "the function can end without returning a value", &.{.{ .name = "function", .value = f.name }});
|
||||
}
|
||||
if (tail) |v| {
|
||||
try l.checkTy(f.body.tail.?.span, v.ty, sig.ret);
|
||||
try l.term(try l.retText(v), f.body.tail.?.span);
|
||||
} else if (sig.ret == .void) {
|
||||
try l.term("ret", f.body.span);
|
||||
} else return l.fail("E7006", f.body.span, "the function can end without returning a value", &.{.{ .name = "function", .value = f.name }});
|
||||
} else return l.invalid(.missing_return, f.body.span, "the function can end without returning a value", &.{.{ .name = "function", .value = f.name }});
|
||||
}
|
||||
|
||||
var eff: std.ArrayList(u8) = .empty;
|
||||
@@ -979,14 +988,14 @@ const Lowerer = struct {
|
||||
l.pending_ends = .empty;
|
||||
}
|
||||
for (b.stmts, 0..) |s, i| {
|
||||
if (l.cur == null) return l.fail("E7006", s.span, "unreachable statement", &.{});
|
||||
if (l.cur == null) return l.invalid(.@"unreachable", s.span, "unreachable statement", &.{});
|
||||
l.rest.items[l.rest.items.len - 1].stmts = b.stmts[i + 1 ..];
|
||||
l.rest.items[l.rest.items.len - 1].current = s;
|
||||
try l.stmt(s);
|
||||
}
|
||||
var result: ?Value = null;
|
||||
if (b.tail) |t| {
|
||||
if (l.cur == null) return l.fail("E7006", t.span, "unreachable expression", &.{});
|
||||
if (l.cur == null) return l.invalid(.@"unreachable", t.span, "unreachable expression", &.{});
|
||||
l.rest.items[l.rest.items.len - 1].stmts = &.{};
|
||||
l.rest.items[l.rest.items.len - 1].current = null;
|
||||
l.rest.items[l.rest.items.len - 1].tail = null;
|
||||
@@ -995,7 +1004,7 @@ const Lowerer = struct {
|
||||
result = try l.returnValue(t.*);
|
||||
} else {
|
||||
result = try l.expr(t.*, want);
|
||||
if (result.?.ty.isBorrow()) return l.fail("E7006", t.span, "a block cannot yield a borrow", &.{});
|
||||
if (result.?.ty.isBorrow()) return l.invalid(.invalid_borrow_return, t.span, "a block cannot yield a borrow", &.{});
|
||||
}
|
||||
}
|
||||
// The borrows bound in this block end here (lexical scope, spec 15 §9).
|
||||
@@ -1035,7 +1044,7 @@ const Lowerer = struct {
|
||||
}
|
||||
|
||||
fn returnValue(l: *Lowerer, e: ast.Expr) Error!Value {
|
||||
if (l.ret.isBorrow() and e.kind != .name) return l.fail("E7006", e.span, "return a named borrow; bind a returned view or place first", &.{});
|
||||
if (l.ret.isBorrow() and e.kind != .name) return l.invalid(.invalid_borrow_return, e.span, "return a named borrow; bind a returned view or place first", &.{});
|
||||
return l.consuming(e, l.ret);
|
||||
}
|
||||
|
||||
@@ -1056,13 +1065,13 @@ const Lowerer = struct {
|
||||
switch (s.kind) {
|
||||
.let => |x| {
|
||||
if (x.e.kind == .call) if (pathOf(x.e.kind.call.callee.*)) |p| if (std.mem.eql(u8, p, "struct.unpack") or std.mem.eql(u8, p, "array.unpack")) return l.unpackLet(s, x.names, x.e, x.tuple);
|
||||
if (x.tuple and x.names.len == 1) return l.fail("E7006", s.span, "a single parenthesized binding requires aggregate unpack", &.{});
|
||||
if (x.tuple and x.names.len == 1) return l.invalid(.invalid_binding, s.span, "a single parenthesized binding requires aggregate unpack", &.{});
|
||||
if (x.names.len != 1) {
|
||||
if (x.e.kind != .call or x.names.len != 2) return l.fail("E7006", s.span, "this multi-binding requires aggregate unpack", &.{});
|
||||
if (x.e.kind != .call or x.names.len != 2) return l.invalid(.invalid_binding, s.span, "this multi-binding requires aggregate unpack", &.{});
|
||||
if (pathOf(x.e.kind.call.callee.*)) |p| if (std.mem.eql(u8, p, "atomic.compare_exchange")) return l.compareExchangeLet(s, x.names, x.e);
|
||||
return l.splitLet(s, x.names, x.e);
|
||||
}
|
||||
if (x.e.kind == .borrow) return l.fail("E7006", x.e.span, "bind a borrow with `ref name = place;` or `mut name = place;`", &.{});
|
||||
if (x.e.kind == .borrow) return l.invalid(.invalid_binding, x.e.span, "bind a borrow with `ref name = place;` or `mut name = place;`", &.{});
|
||||
if (x.e.kind == .bytes) {
|
||||
const st = try l.materializeBytes(x.e.kind.bytes, x.e.span);
|
||||
try l.bindings.append(l.arena, .{ .name = x.names[0], .mutable = false, .value = st.name, .ty = st.ty, .kind = .storage });
|
||||
@@ -1085,7 +1094,7 @@ const Lowerer = struct {
|
||||
const v = try l.consuming(x.e, want);
|
||||
if (want) |w| try l.checkTy(x.e.span, v.ty, w);
|
||||
if (v.ty == .void or v.ty == .never) return l.fail("E7005", x.e.span, "this expression has no value", &.{});
|
||||
if (v.ty.isBorrow()) return l.fail("E7006", x.e.span, "bind a borrow with `ref name = place;` or `mut name = place;`", &.{});
|
||||
if (v.ty.isBorrow()) return l.invalid(.invalid_binding, x.e.span, "bind a borrow with `ref name = place;` or `mut name = place;`", &.{});
|
||||
// Linear values (owners, regions, resources, endpoints, tasks,
|
||||
// mutexes) are borrowed in place, never moved to frame storage.
|
||||
if (l.addressable.contains(x.names[0]) and !l.isLinear(v.ty)) {
|
||||
@@ -1096,7 +1105,7 @@ const Lowerer = struct {
|
||||
},
|
||||
.@"var" => |x| {
|
||||
const ty = try l.typeOf(x.ty);
|
||||
if (ty.isBorrow()) return l.fail("E7006", s.span, "a `var` holds a value; bind a borrow with `ref` or `mut`", &.{});
|
||||
if (ty.isBorrow()) return l.invalid(.invalid_binding, s.span, "a `var` holds a value; bind a borrow with `ref` or `mut`", &.{});
|
||||
if (l.addressable.contains(x.name) and !l.isLinear(ty)) {
|
||||
const st = try l.storageFor(x.name, ty, s.span);
|
||||
if (x.init) |e| {
|
||||
@@ -1117,8 +1126,8 @@ const Lowerer = struct {
|
||||
.assign => |x| {
|
||||
if (x.place.kind != .name) return l.assignPlace(s.span, x.place, x.e);
|
||||
const b = l.lookup(x.place.kind.name) orelse return l.unknown(x.place.span, x.place.kind.name);
|
||||
if (b.kind == .borrow) return l.fail("E7006", x.place.span, "a borrow cannot be reassigned; write through it with `*r = …`, `r.f = …` or `r[i] = …`", &.{.{ .name = "name", .value = b.name }});
|
||||
if (!b.mutable) return l.fail("E7006", x.place.span, "assignment to an immutable binding; declare it with `var`", &.{.{ .name = "name", .value = b.name }});
|
||||
if (b.kind == .borrow) return l.invalid(.invalid_assignment, x.place.span, "a borrow cannot be reassigned; write through it with `*r = …`, `r.f = …` or `r[i] = …`", &.{.{ .name = "name", .value = b.name }});
|
||||
if (!b.mutable) return l.invalid(.invalid_assignment, x.place.span, "assignment to an immutable binding; declare it with `var`", &.{.{ .name = "name", .value = b.name }});
|
||||
const ty = b.ty;
|
||||
const kind = b.kind;
|
||||
const storage = b.value;
|
||||
@@ -1135,9 +1144,9 @@ const Lowerer = struct {
|
||||
// No shadowing of an active borrow by the same name in the same scope.
|
||||
const scope_start = l.scopeBindingStart();
|
||||
for (l.bindings.items[scope_start..]) |b| if (b.kind == .borrow and std.mem.eql(u8, b.name, x.name))
|
||||
return l.fail("E7006", s.span, "a borrow of this name is already active in this scope", &.{.{ .name = "name", .value = x.name }});
|
||||
return l.invalid(.invalid_binding, s.span, "a borrow of this name is already active in this scope", &.{.{ .name = "name", .value = x.name }});
|
||||
if (x.place.kind == .call) if (l.borrowReturnSig(x.place.kind.call.callee.*)) |sig| if (sig.ret.isBorrow()) {
|
||||
if (x.unchecked) return l.fail("E7006", s.span, "unchecked applies to element places, not calls", &.{});
|
||||
if (x.unchecked) return l.invalid(.invalid_place, s.span, "unchecked applies to element places, not calls", &.{});
|
||||
if (x.mutable != sig.ret.isMutBorrow()) return l.fail("E7005", s.span, "binding mode must match the returned borrow; use ref for shared or mut for exclusive", &.{});
|
||||
const call_expr = x.place.kind.call;
|
||||
const v = try l.call(x.place, call_expr.callee.*, call_expr.args, true);
|
||||
@@ -1175,7 +1184,7 @@ const Lowerer = struct {
|
||||
},
|
||||
.trap => try l.term("trap", s.span),
|
||||
.@"break", .@"continue" => {
|
||||
if (l.loops.items.len == 0) return l.fail("E7006", s.span, "`break` or `continue` outside a loop", &.{});
|
||||
if (l.loops.items.len == 0) return l.invalid(.loop_control_outside_loop, s.span, "`break` or `continue` outside a loop", &.{});
|
||||
const lp = l.loops.items[l.loops.items.len - 1];
|
||||
const vars = if (s.kind == .@"break") lp.exit_vars else lp.header_vars;
|
||||
const target = if (s.kind == .@"break") lp.exit else lp.@"continue";
|
||||
@@ -1184,7 +1193,7 @@ const Lowerer = struct {
|
||||
},
|
||||
.expr => |e| {
|
||||
const v = try l.expr(e, null);
|
||||
if (s.block_statement and v.ty != .void and v.ty != .never) return l.fail("E7006", s.span, "value-producing block statement: use `;` to discard the value or parentheses to continue the expression", &.{});
|
||||
if (s.block_statement and v.ty != .void and v.ty != .never) return l.invalid(.value_block_statement, s.span, "value-producing block statement: use `;` to discard the value or parentheses to continue the expression", &.{});
|
||||
},
|
||||
.@"while" => |x| try l.whileLoop(s.span, x.cond, x.body, null),
|
||||
.loop => |b| try l.whileLoop(s.span, null, b, null),
|
||||
@@ -1486,7 +1495,7 @@ const Lowerer = struct {
|
||||
|
||||
fn expr(l: *Lowerer, e: ast.Expr, want: ?Ty) Error!Value {
|
||||
switch (e.kind) {
|
||||
.specialize => return l.fail("E7006", e.span, "explicit type arguments require a generic function", &.{}),
|
||||
.specialize => return l.invalid(.invalid_generic, e.span, "explicit type arguments require a generic function", &.{}),
|
||||
.int => |x| {
|
||||
const ty: Ty = if (parse_mod.intSuffix(x.text)) |s| .{ .int = s } else want orelse
|
||||
return l.fail("E7007", e.span, "the type of this integer literal cannot be determined; add a suffix such as `0u64` or a type annotation", &.{});
|
||||
@@ -1507,20 +1516,20 @@ const Lowerer = struct {
|
||||
.deref => |x| {
|
||||
const r = try l.expr(x.*, null);
|
||||
const in = r.ty.inner() orelse return l.fail("E7005", e.span, "`*` reads through a borrow", &.{.{ .name = "found", .value = l.diagnosticTyText(r.ty) }});
|
||||
if (r.ty == .slice or r.ty == .slice_mut or in == .array) return l.fail("E7006", e.span, "read slice and array elements with `s[i]`, not `*`", &.{});
|
||||
if (r.ty == .slice or r.ty == .slice_mut or in == .array) return l.invalid(.invalid_expression, e.span, "read slice and array elements with `s[i]`, not `*`", &.{});
|
||||
// The verifier's code (spec 15 §1 rule 2, spec 04 §28).
|
||||
if (in == .atomic) return l.fail("E4202", e.span, "an atomic cell is read only by atomic operations: use `atomic.load(r, ordering)`", &.{});
|
||||
return l.def("v", in, try l.fmt("load %{s}", .{r.name}), e.span);
|
||||
},
|
||||
.index => |x| {
|
||||
if (x.hi != null) return l.fail("E7006", e.span, "a range `s[a..b]` is a borrow: bind it with `ref r = s[a..b];` or pass `ref s[a..b]`", &.{});
|
||||
if (x.hi != null) return l.invalid(.invalid_borrow, e.span, "a range `s[a..b]` is a borrow: bind it with `ref r = s[a..b];` or pass `ref s[a..b]`", &.{});
|
||||
const p = try l.placeBorrow(e, false, false, e.span);
|
||||
const v = try l.def("v", p.v.ty.inner().?, try l.fmt("load %{s}", .{p.v.name}), e.span);
|
||||
try l.endNow(p.ends, e.span);
|
||||
return v;
|
||||
},
|
||||
.array_list => |xs| {
|
||||
if (xs.len == 0 or xs.len > 64) return l.fail("E7006", e.span, "array literal requires 1..64 complete elements", &.{});
|
||||
if (xs.len == 0 or xs.len > 64) return l.invalid(.implementation_limit, e.span, "array literal requires 1..64 complete elements", &.{});
|
||||
var ty: ?Ty = if (want) |w| if (w == .array) w.array.elem else null else null;
|
||||
var names: std.ArrayList(u8) = .empty;
|
||||
for (xs, 0..) |x, i| {
|
||||
@@ -1535,12 +1544,12 @@ const Lowerer = struct {
|
||||
if (x.len == 0 or x.len > (@as(u64, 1) << 32)) return l.fail("E7005", e.span, "array length must be between 1 and 2^32", &.{});
|
||||
const want_elem: ?Ty = if (want) |w| (if (w == .array) w.array.elem else null) else null;
|
||||
const v = try l.expr(x.e.*, want_elem);
|
||||
if (v.ty.isBorrow()) return l.fail("E7006", x.e.span, "an array element cannot be a borrow", &.{});
|
||||
if (v.ty.isBorrow()) return l.invalid(.invalid_literal, x.e.span, "an array element cannot be a borrow", &.{});
|
||||
const at = try l.arrayOf(v.ty, x.len);
|
||||
return l.def("arr", at, try l.fmt("array.splat {s} %{s}", .{ l.tyText(at), v.name }), e.span);
|
||||
},
|
||||
.bytes => return l.fail("E7006", e.span, "a byte string is an array in storage: bind it with `let`/`ref`, or pass it where a slice is expected", &.{}),
|
||||
.borrow => return l.fail("E7006", e.span, "`ref`/`mut` here: borrows are bound with `ref name = place;` / `mut name = place;` or passed as arguments", &.{}),
|
||||
.bytes => return l.invalid(.invalid_literal, e.span, "a byte string is an array in storage: bind it with `let`/`ref`, or pass it where a slice is expected", &.{}),
|
||||
.borrow => return l.invalid(.invalid_borrow, e.span, "`ref`/`mut` here: borrows are bound with `ref name = place;` / `mut name = place;` or passed as arguments", &.{}),
|
||||
.neg => |x| {
|
||||
const ty = want orelse l.peekType(x.*) orelse return l.fail("E7007", e.span, "the type of this negation cannot be determined", &.{});
|
||||
if (ty != .int) return l.fail("E7005", e.span, "negation of a non-integer", &.{});
|
||||
@@ -1600,7 +1609,7 @@ const Lowerer = struct {
|
||||
.or_trap => |x| return l.orTrap(e, x.*),
|
||||
.move => |n| {
|
||||
const b = l.lookup(n) orelse return l.unknown(e.span, n);
|
||||
if (!l.isLinear(b.ty) and !(e.generic_transfer and b.ty != .void and b.ty != .never and !b.ty.isBorrow() and b.ty != .task and b.ty != .scope and b.ty != .guard and b.ty != .shield)) return l.fail("E7006", e.span, "`move` applies to linear values; copyable values are passed plainly", &.{ .{ .name = "name", .value = n }, .{ .name = "type", .value = l.diagnosticTyText(b.ty) } });
|
||||
if (!l.isLinear(b.ty) and !(e.generic_transfer and b.ty != .void and b.ty != .never and !b.ty.isBorrow() and b.ty != .task and b.ty != .scope and b.ty != .guard and b.ty != .shield)) return l.invalid(if (b.ty.isBorrow()) .move_borrow else if (b.ty == .void or b.ty == .never) .invalid_move else .move_copy, e.span, "`move` applies to linear values; copyable values are passed plainly", &.{ .{ .name = "name", .value = n }, .{ .name = "type", .value = l.diagnosticTyText(b.ty) } });
|
||||
if (b.kind == .storage) return l.def(n, b.ty, try l.fmt("local.load %{s}", .{b.value}), e.span);
|
||||
return .{ .name = b.value, .ty = b.ty };
|
||||
},
|
||||
@@ -1686,10 +1695,10 @@ const Lowerer = struct {
|
||||
const b = try l.bufferBorrow(args[0], false);
|
||||
return l.def("size", .{ .int = "usize" }, try l.fmt("{s} %{s}", .{ p, b.name }), e.span);
|
||||
}
|
||||
if (std.mem.eql(u8, p, "buffer.view")) return l.fail("E7006", e.span, "bind a buffer view with ref/mut name = buffer.view(borrow)", &.{});
|
||||
if (std.mem.eql(u8, p, "buffer.view")) return l.invalid(.invalid_borrow, e.span, "bind a buffer view with ref/mut name = buffer.view(borrow)", &.{});
|
||||
}
|
||||
if (pathOf(callee)) |path| if (std.mem.eql(u8, path, "value.swap")) {
|
||||
if (args.len != 2 or args[0].kind != .borrow or !args[0].kind.borrow.mutable) return l.fail("E7006", e.span, "value.swap requires mut place and replacement", &.{});
|
||||
if (args.len != 2 or args[0].kind != .borrow or !args[0].kind.borrow.mutable) return l.invalid(.invalid_operation, e.span, "value.swap requires mut place and replacement", &.{});
|
||||
const b = args[0].kind.borrow;
|
||||
const p = try l.placeBorrow(b.place.*, true, false, e.span);
|
||||
if (p.v.ty != .mut) return l.fail("E7005", e.span, "value.swap requires mut<T>", &.{});
|
||||
@@ -1709,7 +1718,7 @@ const Lowerer = struct {
|
||||
}
|
||||
if (pathOf(callee)) |p| {
|
||||
if (std.mem.eql(u8, p, "slice.copy")) return l.sliceCopy(e, args);
|
||||
if (l.fallible(p) != null) return l.fail("E7006", e.span, "a fallible operation is handled with `match` over its outcomes or with `or trap`", &.{.{ .name = "operation", .value = p }});
|
||||
if (l.fallible(p) != null) return l.invalid(.invalid_operation, e.span, "a fallible operation is handled with `match` over its outcomes or with `or trap`", &.{.{ .name = "operation", .value = p }});
|
||||
if (std.mem.eql(u8, p, "own.take")) {
|
||||
if (args.len != 1) return l.fail("E7005", e.span, "`own.take` takes one owner", &.{});
|
||||
const o = try l.consuming(args[0], null);
|
||||
@@ -1749,7 +1758,7 @@ const Lowerer = struct {
|
||||
return l.notYet(callee.span, "this built-in operation (later layers)");
|
||||
}
|
||||
if (callee.kind == .field and std.mem.eql(u8, callee.kind.field.name, "split_at"))
|
||||
return l.fail("E7006", e.span, "`split_at` yields two borrows: `let (left, right) = s.split_at(k);`", &.{});
|
||||
return l.invalid(.invalid_unpack, e.span, "`split_at` yields two borrows: `let (left, right) = s.split_at(k);`", &.{});
|
||||
if (callee.kind != .name) return l.notYet(callee.span, "built-in operations (later layers)");
|
||||
const name = callee.kind.name;
|
||||
if (std.mem.eql(u8, name, "assert")) {
|
||||
@@ -1769,12 +1778,12 @@ const Lowerer = struct {
|
||||
}
|
||||
const sig = l.functionSig(name, callee.span) orelse return l.unknown(callee.span, name);
|
||||
if (args.len != sig.params.len) return l.fail("E7005", e.span, "wrong number of arguments", &.{ .{ .name = "function", .value = sig.display_name }, .{ .name = "expected", .value = try l.fmt("{d}", .{sig.params.len}) }, .{ .name = "found", .value = try l.fmt("{d}", .{args.len}) } });
|
||||
if (sig.ret.isBorrow() and !borrow_allowed) return l.fail("E7006", e.span, "bind a returned borrow with ref/mut name = call(...) first", &.{});
|
||||
if (sig.ret.isBorrow() and !borrow_allowed) return l.invalid(.invalid_borrow_return, e.span, "bind a returned borrow with ref/mut name = call(...) first", &.{});
|
||||
if (sig.from) |origin| {
|
||||
const a = args[origin];
|
||||
if (a.kind != .name) return l.fail("E7006", a.span, "the from argument must be a named borrow; bind it first", &.{});
|
||||
if (a.kind != .name) return l.invalid(.invalid_borrow_return, a.span, "the from argument must be a named borrow; bind it first", &.{});
|
||||
const b = l.lookup(a.kind.name) orelse return l.unknown(a.span, a.kind.name);
|
||||
if (b.kind != .borrow) return l.fail("E7006", a.span, "the from argument must be a named borrow; bind it first", &.{});
|
||||
if (b.kind != .borrow) return l.invalid(.invalid_borrow_return, a.span, "the from argument must be a named borrow; bind it first", &.{});
|
||||
}
|
||||
var parent: ?[]const u8 = null;
|
||||
var arg_names: std.ArrayList(u8) = .empty;
|
||||
@@ -1810,7 +1819,7 @@ const Lowerer = struct {
|
||||
if (d.kind != .@"struct") return l.fail("E7005", e.span, "`Name { … }` constructs a struct; this is an enum (use `Enum::Variant`)", &.{.{ .name = "type", .value = d.display_name orelse name }});
|
||||
const fields = d.kind.@"struct";
|
||||
for (inits, 0..) |fi, i| {
|
||||
for (inits[0..i]) |prev| if (std.mem.eql(u8, prev.name, fi.name)) return l.fail("E7006", fi.span, "field given twice", &.{.{ .name = "field", .value = fi.name }});
|
||||
for (inits[0..i]) |prev| if (std.mem.eql(u8, prev.name, fi.name)) return l.invalid(.invalid_literal, fi.span, "field given twice", &.{.{ .name = "field", .value = fi.name }});
|
||||
const known = for (fields) |f| {
|
||||
if (std.mem.eql(u8, f.name, fi.name)) break true;
|
||||
} else false;
|
||||
@@ -1820,7 +1829,7 @@ const Lowerer = struct {
|
||||
for (fields, 0..) |f, i| {
|
||||
const fi = for (inits) |x| {
|
||||
if (std.mem.eql(u8, x.name, f.name)) break x;
|
||||
} else return l.fail("E7006", e.span, "missing field", &.{ .{ .name = "type", .value = d.display_name orelse name }, .{ .name = "field", .value = f.name } });
|
||||
} else return l.invalid(.invalid_literal, e.span, "missing field", &.{ .{ .name = "type", .value = d.display_name orelse name }, .{ .name = "field", .value = f.name } });
|
||||
const ft = try l.typeOf(f.ty);
|
||||
const v = try l.consuming(fi.e, ft);
|
||||
try l.checkTy(fi.e.span, v.ty, ft);
|
||||
@@ -1932,7 +1941,7 @@ const Lowerer = struct {
|
||||
try head.appendSlice(l.arena, try l.fmt("{s} {s} %{s}", .{ if (l.isLinear(st)) "enum.take" else "enum.switch", l.tyText(st), sv.name }));
|
||||
for (m.arms, blocks, 0..) |arm, *blk, i| {
|
||||
if (arm.pattern.kind != .ctor or arm.pattern.kind.ctor.qualifier == null)
|
||||
return l.fail("E7006", arm.pattern.span, "an arm of a `match` over an enum names one variant as `Enum::Variant`; `_` is not allowed", &.{.{ .name = "enum", .value = d.display_name orelse d.name }});
|
||||
return l.invalid(.invalid_match, arm.pattern.span, "an arm of a `match` over an enum names one variant as `Enum::Variant`; `_` is not allowed", &.{.{ .name = "enum", .value = d.display_name orelse d.name }});
|
||||
const c = arm.pattern.kind.ctor;
|
||||
const pattern_type = l.enumType(c.qualifier.?, arm.pattern.span);
|
||||
if (std.mem.indexOfScalar(u8, c.qualifier.?, '.') != null and pattern_type == null) return l.unknown(arm.pattern.span, c.qualifier.?);
|
||||
@@ -1940,7 +1949,7 @@ const Lowerer = struct {
|
||||
const vi = for (vs, 0..) |v, k| {
|
||||
if (std.mem.eql(u8, v.name, c.name)) break k;
|
||||
} else return l.fail("E7002", arm.pattern.span, "no such variant", &.{ .{ .name = "enum", .value = d.display_name orelse d.name }, .{ .name = "variant", .value = c.name } });
|
||||
for (m.arms[0..i]) |prev| if (std.mem.eql(u8, prev.pattern.kind.ctor.name, c.name)) return l.fail("E7006", arm.pattern.span, "variant matched twice", &.{.{ .name = "variant", .value = c.name }});
|
||||
for (m.arms[0..i]) |prev| if (std.mem.eql(u8, prev.pattern.kind.ctor.name, c.name)) return l.invalid(.invalid_match, arm.pattern.span, "variant matched twice", &.{.{ .name = "variant", .value = c.name }});
|
||||
if (c.binds.len != vs[vi].payload.len) return l.fail("E7005", arm.pattern.span, "the pattern binds a different number of payload values", &.{ .{ .name = "variant", .value = c.name }, .{ .name = "expected", .value = try l.fmt("{d}", .{vs[vi].payload.len}) } });
|
||||
blk.* = try l.newBlock(try l.fmt("case_{s}", .{c.name}));
|
||||
for (vs[vi].payload, c.binds) |pt, bn| {
|
||||
@@ -1982,7 +1991,7 @@ const Lowerer = struct {
|
||||
for (m.arms, blocks, 0..) |arm, *blk, i| {
|
||||
switch (arm.pattern.kind) {
|
||||
.wildcard => {
|
||||
if (default != null) return l.fail("E7006", arm.pattern.span, "`_` given twice", &.{});
|
||||
if (default != null) return l.invalid(.invalid_match, arm.pattern.span, "`_` given twice", &.{});
|
||||
default = i;
|
||||
blk.* = try l.newBlock("case_default");
|
||||
},
|
||||
@@ -1995,7 +2004,7 @@ const Lowerer = struct {
|
||||
const limit: u128 = if (signed) (@as(u128, 1) << @intCast(width - 1)) - @as(u128, if (negative) 0 else 1) else if (width == 128) std.math.maxInt(u128) else (@as(u128, 1) << @intCast(width)) - 1;
|
||||
if ((negative and !signed) or mag > limit) return l.fail("E7005", arm.pattern.span, "integer pattern out of range for its scrutinee type", &.{ .{ .name = "type", .value = st.int }, .{ .name = "literal", .value = text } });
|
||||
const bits: u128 = if (neg) (0 -% mag) else mag;
|
||||
for (seen.items) |prev| if (prev == bits) return l.fail("E7006", arm.pattern.span, "integer matched twice", &.{.{ .name = "value", .value = text }});
|
||||
for (seen.items) |prev| if (prev == bits) return l.invalid(.invalid_match, arm.pattern.span, "integer matched twice", &.{.{ .name = "value", .value = text }});
|
||||
try seen.append(l.arena, bits);
|
||||
blk.* = try l.newBlock("case");
|
||||
// AIR uses canonical decimal literals without source
|
||||
@@ -2031,11 +2040,11 @@ const Lowerer = struct {
|
||||
try head.appendSlice(l.arena, try l.fmt("enum.switch {s} %{s}", .{ name, sv.name }));
|
||||
for (m.arms, blocks, 0..) |arm, *blk, i| {
|
||||
if (arm.pattern.kind != .ctor or arm.pattern.kind.ctor.qualifier == null or !std.mem.eql(u8, arm.pattern.kind.ctor.qualifier.?, name))
|
||||
return l.fail("E7006", arm.pattern.span, try l.fmt("an arm names one variant as `{s}::variant`; `_` is not allowed", .{name}), &.{});
|
||||
return l.invalid(.invalid_match, arm.pattern.span, try l.fmt("an arm names one variant as `{s}::variant`; `_` is not allowed", .{name}), &.{});
|
||||
const c = arm.pattern.kind.ctor;
|
||||
if (b.variantIndex(c.name) == null) return l.fail("E7002", arm.pattern.span, "no such variant", &.{ .{ .name = "enum", .value = name }, .{ .name = "variant", .value = c.name } });
|
||||
if (c.binds.len != 0) return l.fail("E7005", arm.pattern.span, "built-in error variants have no payload", &.{});
|
||||
for (m.arms[0..i]) |prev| if (std.mem.eql(u8, prev.pattern.kind.ctor.name, c.name)) return l.fail("E7006", arm.pattern.span, "variant matched twice", &.{.{ .name = "variant", .value = c.name }});
|
||||
for (m.arms[0..i]) |prev| if (std.mem.eql(u8, prev.pattern.kind.ctor.name, c.name)) return l.invalid(.invalid_match, arm.pattern.span, "variant matched twice", &.{.{ .name = "variant", .value = c.name }});
|
||||
blk.* = try l.newBlock(try l.fmt("case_{s}", .{c.name}));
|
||||
try head.appendSlice(l.arena, try l.fmt(", {s} -> @{s}", .{ c.name, l.blocks.items[blk.*].name }));
|
||||
}
|
||||
@@ -2122,13 +2131,13 @@ const Lowerer = struct {
|
||||
const z = try l.zeroValue(a.elem, base, span);
|
||||
break :blk l.def(base, ty, try l.fmt("array.splat {s} %{s}", .{ l.tyText(ty), z.name }), span);
|
||||
},
|
||||
else => l.fail("E7006", span, "`zero` needs a zeroable type (integers, booleans, arrays of them)", &.{}),
|
||||
else => l.invalid(.zero_not_zeroable, span, "`zero` needs a zeroable type (integers, booleans, arrays of them)", &.{}),
|
||||
};
|
||||
}
|
||||
|
||||
/// A byte string in frame storage: `[u8; N]`, one store per byte (no heap).
|
||||
fn materializeBytes(l: *Lowerer, bytes: []const u8, span: Span) Error!Value {
|
||||
if (bytes.len == 0) return l.fail("E7006", span, "an empty byte string has no array type", &.{});
|
||||
if (bytes.len == 0) return l.invalid(.invalid_literal, span, "an empty byte string has no array type", &.{});
|
||||
const ty = try l.arrayOf(.{ .int = "u8" }, bytes.len);
|
||||
const st = try l.storageFor("bytes", ty, span);
|
||||
// Everything from here to the final `borrow.end` is the constant's
|
||||
@@ -2189,7 +2198,7 @@ const Lowerer = struct {
|
||||
/// the verifier's (`E6001`).
|
||||
fn uncheckedPlace(l: *Lowerer, place: ast.Expr, mutable: bool, unchecked: bool, span: Span) Error!Placed {
|
||||
if (!unchecked) return l.placeBorrow(place, mutable, true, span);
|
||||
if (place.kind != .index or place.kind.index.hi != null) return l.fail("E7006", place.span, "`unchecked` applies to one element `s[i]`", &.{});
|
||||
if (place.kind != .index or place.kind.index.hi != null) return l.invalid(.invalid_place, place.span, "`unchecked` applies to one element `s[i]`", &.{});
|
||||
l.unchecked = true;
|
||||
defer l.unchecked = false;
|
||||
return l.placeBorrow(place, mutable, true, span);
|
||||
@@ -2254,7 +2263,7 @@ const Lowerer = struct {
|
||||
.atomic => if (mutable) return l.fail("E7005", place.span, "an atomic cell is borrowed with `ref`: every atomic operation goes through a shared borrow", &.{.{ .name = "name", .value = n }}) else try l.wrap(.ref, b.ty),
|
||||
else => null,
|
||||
};
|
||||
const t = bt orelse return l.fail("E7006", place.span, "this value is not addressable here; borrow a variable, a field or an element", &.{.{ .name = "name", .value = n }});
|
||||
const t = bt orelse return l.invalid(.invalid_place, place.span, "this value is not addressable here; borrow a variable, a field or an element", &.{.{ .name = "name", .value = n }});
|
||||
const v = try l.def(n, t, try l.fmt("{s} %{s}", .{ op, b.value }), span);
|
||||
return .{ .v = v, .ends = try l.arena.dupe([]const u8, &.{v.name}) };
|
||||
},
|
||||
@@ -2318,7 +2327,7 @@ const Lowerer = struct {
|
||||
const v = try l.defBorrow("e", if (bt.isMutBorrow()) try l.wrap(.mut, elem) else try l.wrap(.ref, elem), try l.fmt("{s} %{s}, %{s}", .{ index_op, base.v.name, i.name }), base.v.name, span);
|
||||
return .{ .v = v, .ends = try l.concat(base.ends, v.name) };
|
||||
},
|
||||
else => return l.fail("E7006", place.span, "not a place: borrow a variable, a field `x.f`, an element `s[i]` or a range `s[a..b]`", &.{}),
|
||||
else => return l.invalid(.invalid_place, place.span, "not a place: borrow a variable, a field `x.f`, an element `s[i]` or a range `s[a..b]`", &.{}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2333,15 +2342,15 @@ const Lowerer = struct {
|
||||
fn assignPlace(l: *Lowerer, span: Span, place: ast.Expr, value: ast.Expr) Error!void {
|
||||
switch (place.kind) {
|
||||
.deref, .field, .index => {},
|
||||
else => return l.fail("E7006", place.span, "cannot assign to this expression", &.{}),
|
||||
else => return l.invalid(.invalid_assignment, place.span, "cannot assign to this expression", &.{}),
|
||||
}
|
||||
if (place.kind == .index and place.kind.index.hi != null) return l.fail("E7006", place.span, "assign elements one by one, or use `slice.copy(mut dst, ref src)`", &.{});
|
||||
if (place.kind == .index and place.kind.index.hi != null) return l.invalid(.invalid_assignment, place.span, "assign elements one by one, or use `slice.copy(mut dst, ref src)`", &.{});
|
||||
// The value is evaluated first, then the place is borrowed for the
|
||||
// store (spec 15 §4), so `s[i] = s[i] + 1` reads before it writes.
|
||||
const v = try l.expr(value, l.placeType(place));
|
||||
const p = try l.placeBorrow(place, true, false, span);
|
||||
const in = p.v.ty.inner() orelse return l.fail("E7005", place.span, "assignment needs a mutable place", &.{});
|
||||
if (in == .array and place.kind == .deref) return l.fail("E7006", place.span, "write array elements with `s[i] = …`", &.{});
|
||||
if (in == .array and place.kind == .deref) return l.invalid(.invalid_assignment, place.span, "write array elements with `s[i] = …`", &.{});
|
||||
try l.checkTy(value.span, v.ty, in);
|
||||
try l.emit(try l.fmt("store %{s}, %{s}", .{ p.v.name, v.name }), span);
|
||||
try l.endNow(p.ends, span);
|
||||
@@ -2373,20 +2382,20 @@ const Lowerer = struct {
|
||||
/// `let (left, right) = s.split_at(k);`: two disjoint borrows of `s`,
|
||||
/// bound for the rest of the block (spec 15 §5).
|
||||
fn unpackLet(l: *Lowerer, s: ast.Stmt, names: []const []const u8, e: ast.Expr, tuple: bool) Error!void {
|
||||
if (!tuple or s.kind.let.ty != null or e.kind.call.args.len != 1) return l.fail("E7006", s.span, "unpack requires a parenthesized complete binding and one argument", &.{});
|
||||
if (!tuple or s.kind.let.ty != null or e.kind.call.args.len != 1) return l.invalid(.invalid_unpack, s.span, "unpack requires a parenthesized complete binding and one argument", &.{});
|
||||
const v = try l.consuming(e.kind.call.args[0], null);
|
||||
const operation = pathOf(e.kind.call.callee.*).?;
|
||||
var components: std.ArrayList(Ty) = .empty;
|
||||
if (std.mem.eql(u8, operation, "struct.unpack") and v.ty == .named and l.m.types[v.ty.named].kind == .@"struct") {
|
||||
for (l.m.types[v.ty.named].kind.@"struct") |f| try components.append(l.arena, try l.typeOf(f.ty));
|
||||
} else if (std.mem.eql(u8, operation, "array.unpack") and v.ty == .array) {
|
||||
if (v.ty.array.len > 64) return l.fail("E7006", s.span, "unpack exceeds 64 block parameters", &.{});
|
||||
if (v.ty.array.len > 64) return l.invalid(.implementation_limit, s.span, "unpack exceeds 64 block parameters", &.{});
|
||||
for (0..@intCast(v.ty.array.len)) |_| try components.append(l.arena, v.ty.array.elem);
|
||||
} else return l.fail("E7005", e.span, "unpack needs the corresponding struct or array", &.{});
|
||||
if (names.len != components.items.len or names.len > 64) return l.fail("E7005", s.span, "unpack must bind every component", &.{});
|
||||
const next = try l.newBlock("unpacked");
|
||||
for (names, components.items, 0..) |n, t, i| {
|
||||
for (names[0..i]) |previous| if (!std.mem.eql(u8, n, "_") and std.mem.eql(u8, n, previous)) return l.fail("E7006", s.span, "duplicate unpack binding", &.{});
|
||||
for (names[0..i]) |previous| if (!std.mem.eql(u8, n, "_") and std.mem.eql(u8, n, previous)) return l.invalid(.invalid_unpack, s.span, "duplicate unpack binding", &.{});
|
||||
const pn = try l.freshName(if (std.mem.eql(u8, n, "_")) "unused" else n);
|
||||
try l.blocks.items[next].params.append(l.arena, .{ .name = pn, .ty = t });
|
||||
if (!std.mem.eql(u8, n, "_")) try l.bindings.append(l.arena, .{ .name = n, .value = pn, .ty = t, .mutable = false });
|
||||
@@ -2398,7 +2407,7 @@ const Lowerer = struct {
|
||||
|
||||
fn splitLet(l: *Lowerer, s: ast.Stmt, names: []const []const u8, e: ast.Expr) Error!void {
|
||||
if (e.kind != .call or e.kind.call.callee.kind != .field or !std.mem.eql(u8, e.kind.call.callee.kind.field.name, "split_at") or e.kind.call.args.len != 1)
|
||||
return l.fail("E7006", e.span, "`let (a, b) = …` is only for `s.split_at(k)`", &.{});
|
||||
return l.invalid(.invalid_unpack, e.span, "`let (a, b) = …` is only for `s.split_at(k)`", &.{});
|
||||
const base = e.kind.call.callee.kind.field.e.*;
|
||||
const rb = l.rootBinding(base) orelse return l.fail("E7002", base.span, "unknown name", &.{});
|
||||
const mutable = rb.ty.isMutBorrow() or rb.kind == .storage and rb.mutable;
|
||||
@@ -2549,7 +2558,7 @@ const Lowerer = struct {
|
||||
fn ordering(l: *Lowerer, a: ast.Expr) Error![]const u8 {
|
||||
const words = [_][]const u8{ "relaxed", "acquire", "release", "acq_rel", "seq_cst" };
|
||||
if (a.kind == .name) for (words) |w| if (std.mem.eql(u8, a.kind.name, w)) return w;
|
||||
return l.fail("E7006", a.span, "an ordering is one of the words relaxed, acquire, release, acq_rel, seq_cst, written in place", &.{});
|
||||
return l.invalid(.invalid_operation, a.span, "an ordering is one of the words relaxed, acquire, release, acq_rel, seq_cst, written in place", &.{});
|
||||
}
|
||||
|
||||
/// The cell operand of an atomic operation: a `ref<atomic<T>>` binding or
|
||||
@@ -2590,7 +2599,7 @@ const Lowerer = struct {
|
||||
return .{ .name = "", .ty = .void };
|
||||
}
|
||||
if (eq(u8, p, "atomic.compare_exchange"))
|
||||
return l.fail("E7006", e.span, "`atomic.compare_exchange` has two results: `let (old, exchanged) = atomic.compare_exchange(c, expected, desired, success, failure);`", &.{});
|
||||
return l.invalid(.invalid_unpack, e.span, "`atomic.compare_exchange` has two results: `let (old, exchanged) = atomic.compare_exchange(c, expected, desired, success, failure);`", &.{});
|
||||
var temps: std.ArrayList([]const u8) = .empty;
|
||||
const want: usize = if (eq(u8, p, "atomic.load")) 2 else 3;
|
||||
if (args.len != want) return l.fail("E7005", e.span, "wrong number of operands", &.{ .{ .name = "operation", .value = p }, .{ .name = "expected", .value = try l.fmt("{d}", .{want}) } });
|
||||
@@ -2647,7 +2656,7 @@ const Lowerer = struct {
|
||||
/// endpoint by name, borrowed for the operation, or a borrow binding of it.
|
||||
fn endpointOperand(l: *Lowerer, a: ast.Expr, tag: std.meta.Tag(Ty), mutable: bool, temps: *std.ArrayList([]const u8)) Error!Value {
|
||||
const what = if (tag == .sender) "a sender" else "a receiver";
|
||||
if (a.kind == .borrow) return l.fail("E7006", a.span, "an endpoint operand is written by name; the operation borrows it", &.{});
|
||||
if (a.kind == .borrow) return l.invalid(.invalid_borrow, a.span, "an endpoint operand is written by name; the operation borrows it", &.{});
|
||||
const b = try l.bindingOf(a, what);
|
||||
if (std.meta.activeTag(b.ty) == tag) {
|
||||
const bt = if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty);
|
||||
@@ -2674,14 +2683,14 @@ const Lowerer = struct {
|
||||
const scope_name = sb.value;
|
||||
const fname = try expressionPath(l.arena, args[1]) orelse return l.fail("E7005", args[1].span, "the function to spawn is named", &.{});
|
||||
const sig = l.functionSig(fname, args[1].span) orelse return l.unknown(args[1].span, fname);
|
||||
if (sig.ret.isBorrow()) return l.fail("E7006", e.span, "a spawned function cannot return a borrow (reserved: task_borrow_returns)", &.{.{ .name = "function", .value = sig.display_name }});
|
||||
if (sig.ret.isBorrow()) return l.invalid(.invalid_borrow_return, e.span, "a spawned function cannot return a borrow (reserved: task_borrow_returns)", &.{.{ .name = "function", .value = sig.display_name }});
|
||||
const fargs = args[2..];
|
||||
if (fargs.len != sig.params.len) return l.fail("E7005", e.span, "wrong number of arguments", &.{ .{ .name = "function", .value = sig.display_name }, .{ .name = "expected", .value = try l.fmt("{d}", .{sig.params.len}) }, .{ .name = "found", .value = try l.fmt("{d}", .{fargs.len}) } });
|
||||
var names: std.ArrayList(u8) = .empty;
|
||||
for (fargs, sig.params, 0..) |a, pt, i| {
|
||||
// A borrow is lent to the task until its join, so it is bound
|
||||
// by the program, not made for the call (spec 15 §7).
|
||||
if (a.kind == .borrow or a.kind == .bytes) return l.fail("E7006", a.span, "a borrow lent to a task stays lent until the join: bind it first (`mut part = …;`) and pass the name", &.{});
|
||||
if (a.kind == .borrow or a.kind == .bytes) return l.invalid(.invalid_borrow, a.span, "a borrow lent to a task stays lent until the join: bind it first (`mut part = …;`) and pass the name", &.{});
|
||||
const v = try l.consuming(a, pt);
|
||||
try l.checkTy(a.span, v.ty, pt);
|
||||
try names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", v.name }));
|
||||
@@ -2753,7 +2762,7 @@ const Lowerer = struct {
|
||||
return l.fail("E7005", args[0].span, "`arc.clone` takes an `arc<T>`", &.{.{ .name = "found", .value = l.diagnosticTyText(b.ty) }});
|
||||
}
|
||||
if (eq(p, "island.at") or eq(p, "frozen.at") or eq(p, "arc.at"))
|
||||
return l.fail("E7006", e.span, "a graph access is a borrow: bind it with `ref x = island.at(g, r);` or `mut x = island.at(g, r);`", &.{});
|
||||
return l.invalid(.invalid_borrow, e.span, "a graph access is a borrow: bind it with `ref x = island.at(g, r);` or `mut x = island.at(g, r);`", &.{});
|
||||
if (eq(p, "mutex.make")) {
|
||||
if (args.len != 1) return l.fail("E7005", e.span, "`mutex.make` takes the initial value", &.{});
|
||||
const v = try l.consuming(args[0], null);
|
||||
@@ -2828,7 +2837,7 @@ const Lowerer = struct {
|
||||
/// appearance; every edge binds its own value (a received `T`) and then
|
||||
/// the values of `V` not sent on it.
|
||||
fn selectStmt(l: *Lowerer, s: ast.Stmt, sel: ast.Select) Error!void {
|
||||
if (sel.arms.len == 0) return l.fail("E7006", s.span, "a `select` has at least one `recv` or `send` arm", &.{});
|
||||
if (sel.arms.len == 0) return l.invalid(.invalid_match, s.span, "a `select` has at least one `recv` or `send` arm", &.{});
|
||||
const Sent = struct { key: ?[]const u8, v: Value };
|
||||
var values: std.ArrayList(Sent) = .empty;
|
||||
const arm_value = try l.arena.alloc(?usize, sel.arms.len);
|
||||
@@ -2892,10 +2901,10 @@ const Lowerer = struct {
|
||||
// Every outcome of every arm is matched exactly once.
|
||||
for (sel.arms) |a| {
|
||||
for (a.arms, 0..) |arm, k| {
|
||||
if (arm.pattern.kind != .ctor or arm.pattern.kind.ctor.qualifier != null) return l.fail("E7006", arm.pattern.span, "a `select` arm names its outcomes: `ok(…)` and `closed(…)`", &.{});
|
||||
if (arm.pattern.kind != .ctor or arm.pattern.kind.ctor.qualifier != null) return l.invalid(.invalid_match, arm.pattern.span, "a `select` arm names its outcomes: `ok(…)` and `closed(…)`", &.{});
|
||||
const c = arm.pattern.kind.ctor;
|
||||
if (!std.mem.eql(u8, c.name, "ok") and !std.mem.eql(u8, c.name, "closed")) return l.fail("E7002", arm.pattern.span, "a `select` arm has the outcomes `ok` and `closed`; `cancelled` is the `select`'s own arm", &.{.{ .name = "outcome", .value = c.name }});
|
||||
for (a.arms[0..k]) |prev| if (std.mem.eql(u8, prev.pattern.kind.ctor.name, c.name)) return l.fail("E7006", arm.pattern.span, "outcome matched twice", &.{.{ .name = "outcome", .value = c.name }});
|
||||
for (a.arms[0..k]) |prev| if (std.mem.eql(u8, prev.pattern.kind.ctor.name, c.name)) return l.invalid(.invalid_match, arm.pattern.span, "outcome matched twice", &.{.{ .name = "outcome", .value = c.name }});
|
||||
}
|
||||
for ([_][]const u8{ "ok", "closed" }) |role| {
|
||||
const covered = for (a.arms) |arm| {
|
||||
@@ -2987,7 +2996,7 @@ const Lowerer = struct {
|
||||
/// The named borrow binding of a graph owner that `.root`, `.at` and
|
||||
/// `island.alloc` take (spec 15 §8: container borrows are explicit).
|
||||
fn graphBorrow(l: *Lowerer, a: ast.Expr, owner: []const u8, mutable: bool) Error!Value {
|
||||
if (a.kind == .borrow) return l.fail("E7006", a.span, "the graph's borrow is bound first (`mut g = isl;`), so it outlives the borrows taken from it", &.{});
|
||||
if (a.kind == .borrow) return l.invalid(.invalid_borrow, a.span, "the graph's borrow is bound first (`mut g = isl;`), so it outlives the borrows taken from it", &.{});
|
||||
if (a.kind != .name) return l.fail("E7005", a.span, "the graph's borrow binding is expected here, by name", &.{});
|
||||
const b = l.lookup(a.kind.name) orelse return l.unknown(a.span, a.kind.name);
|
||||
const tag = std.meta.stringToEnum(std.meta.Tag(Ty), owner).?;
|
||||
@@ -3082,7 +3091,7 @@ const Lowerer = struct {
|
||||
/// (borrowed `mut` for the operation) or a `mut` borrow binding of one.
|
||||
fn resourceOperand(l: *Lowerer, a: ast.Expr, rs: []const authority.Resource, temps: *std.ArrayList([]const u8)) Error!Value {
|
||||
const expected = try l.resourceList(rs);
|
||||
if (a.kind == .borrow) return l.fail("E7006", a.span, "a resource operand is written by name; the operation borrows it", &.{.{ .name = "expected", .value = expected }});
|
||||
if (a.kind == .borrow) return l.invalid(.invalid_borrow, a.span, "a resource operand is written by name; the operation borrows it", &.{.{ .name = "expected", .value = expected }});
|
||||
if (a.kind != .name) return l.fail("E7005", a.span, "a resource is expected here, by name", &.{.{ .name = "expected", .value = expected }});
|
||||
const b = l.lookup(a.kind.name) orelse return l.unknown(a.span, a.kind.name);
|
||||
const r: ?authority.Resource = switch (b.ty) {
|
||||
@@ -3122,8 +3131,8 @@ const Lowerer = struct {
|
||||
}
|
||||
|
||||
fn lowerFallible(l: *Lowerer, e: ast.Expr) Error!Fallible {
|
||||
if (e.kind != .call) return l.fail("E7006", e.span, "outcome arms (`ok`, `err`, …) belong to a fallible operation", &.{});
|
||||
const path = pathOf(e.kind.call.callee.*) orelse return l.fail("E7006", e.span, "outcome arms (`ok`, `err`, …) belong to a fallible operation", &.{});
|
||||
if (e.kind != .call) return l.invalid(.invalid_match, e.span, "outcome arms (`ok`, `err`, …) belong to a fallible operation", &.{});
|
||||
const path = pathOf(e.kind.call.callee.*) orelse return l.invalid(.invalid_match, e.span, "outcome arms (`ok`, `err`, …) belong to a fallible operation", &.{});
|
||||
const args = e.kind.call.args;
|
||||
const want = struct {
|
||||
fn n(lw: *Lowerer, sp: Span, as: []const ast.Expr, k: usize, op: []const u8) Error!void {
|
||||
@@ -3206,7 +3215,7 @@ const Lowerer = struct {
|
||||
}
|
||||
if (authority.intrinsicIndex(path)) |ix| {
|
||||
const x = authority.intrinsics[ix];
|
||||
if (!x.fallible) return l.fail("E7006", e.span, "this intrinsic cannot fail: call it plainly", &.{.{ .name = "operation", .value = x.name }});
|
||||
if (!x.fallible) return l.invalid(.invalid_operation, e.span, "this intrinsic cannot fail: call it plainly", &.{.{ .name = "operation", .value = x.name }});
|
||||
var temps: std.ArrayList([]const u8) = .empty;
|
||||
const ops = try l.intrinsicOperands(e, x, args, &temps);
|
||||
l.uses.insert(.capabilities);
|
||||
@@ -3293,7 +3302,7 @@ const Lowerer = struct {
|
||||
try l.checkTy(args[1].span, n.ty, usize_ty);
|
||||
return .{ .text = try l.fmt("cap.narrow.budget %{s}, %{s}", .{ c.name, n.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{c.ty} }, .{ .role = "err", .params = &.{.{ .builtin = .cap_error }} } }) };
|
||||
}
|
||||
return l.fail("E7006", e.span, "not a fallible operation", &.{.{ .name = "operation", .value = path }});
|
||||
return l.invalid(.invalid_operation, e.span, "not a fallible operation", &.{.{ .name = "operation", .value = path }});
|
||||
}
|
||||
|
||||
fn outs(l: *Lowerer, o: []const Outcome) Error![]const Outcome {
|
||||
@@ -3332,12 +3341,12 @@ const Lowerer = struct {
|
||||
const f = try l.lowerFallible(m.scrutinee);
|
||||
for (m.arms, 0..) |arm, i| {
|
||||
if (arm.pattern.kind != .ctor or arm.pattern.kind.ctor.qualifier != null)
|
||||
return l.fail("E7006", arm.pattern.span, "every arm of an outcome match names an outcome of the operation (`ok(…)`, `err(e)`, …)", &.{});
|
||||
return l.invalid(.invalid_match, arm.pattern.span, "every arm of an outcome match names an outcome of the operation (`ok(…)`, `err(e)`, …)", &.{});
|
||||
const c = arm.pattern.kind.ctor;
|
||||
const o = for (f.outcomes) |o| {
|
||||
if (std.mem.eql(u8, o.role, c.name)) break o;
|
||||
} else return l.fail("E7002", arm.pattern.span, "this operation has no such outcome", &.{.{ .name = "outcome", .value = c.name }});
|
||||
for (m.arms[0..i]) |prev| if (std.mem.eql(u8, prev.pattern.kind.ctor.name, c.name)) return l.fail("E7006", arm.pattern.span, "outcome matched twice", &.{.{ .name = "outcome", .value = c.name }});
|
||||
for (m.arms[0..i]) |prev| if (std.mem.eql(u8, prev.pattern.kind.ctor.name, c.name)) return l.invalid(.invalid_match, arm.pattern.span, "outcome matched twice", &.{.{ .name = "outcome", .value = c.name }});
|
||||
if (c.binds.len != o.params.len) return l.fail("E7005", arm.pattern.span, "the outcome binds a different number of values", &.{ .{ .name = "outcome", .value = c.name }, .{ .name = "expected", .value = try l.fmt("{d}", .{o.params.len}) } });
|
||||
}
|
||||
var missing: std.ArrayList(u8) = .empty;
|
||||
@@ -3398,7 +3407,7 @@ const Lowerer = struct {
|
||||
l.cur = ok;
|
||||
const ps = l.blocks.items[ok].params.items;
|
||||
if (ps.len == 0) return .{ .name = "", .ty = .void };
|
||||
if (ps.len != 1) return l.fail("E7006", e.span, "`or trap` on an operation with several results: use `match`", &.{});
|
||||
if (ps.len != 1) return l.invalid(.invalid_operation, e.span, "`or trap` on an operation with several results: use `match`", &.{});
|
||||
return .{ .name = ps[0].name, .ty = ps[0].ty };
|
||||
}
|
||||
|
||||
|
||||
@@ -39,16 +39,22 @@ const Graph = struct {
|
||||
nodes: std.ArrayList(Node) = .empty,
|
||||
problem: ?lower.Problem = null,
|
||||
|
||||
fn fail(g: *Graph, code: []const u8, span: ast.Span, message: []const u8, name: []const u8) Error {
|
||||
fn fail(g: *Graph, comptime code: []const u8, span: ast.Span, message: []const u8, name: []const u8) Error {
|
||||
if (comptime std.mem.eql(u8, code, "E7006")) @compileError("E7006 requires an explicit reason via invalid()");
|
||||
g.problem = .{ .code = code, .span = span, .message = message, .fields = g.arena.dupe(lower.Problem.Field, &.{.{ .name = "name", .value = name }}) catch return error.OutOfMemory };
|
||||
return error.InvalidSource;
|
||||
}
|
||||
|
||||
fn invalid(g: *Graph, reason: lower.InvalidReason, span: ast.Span, message: []const u8, name: []const u8) Error {
|
||||
g.problem = .{ .code = "E7006", .reason = reason, .span = span, .message = message, .fields = g.arena.dupe(lower.Problem.Field, &.{.{ .name = "name", .value = name }}) catch return error.OutOfMemory };
|
||||
return error.InvalidSource;
|
||||
}
|
||||
|
||||
fn run(g: *Graph, entry: ast.Module, span: ast.Span) Error!ast.Module {
|
||||
if (g.sources.len > 1024) return g.fail("E7006", span, "more than 1024 mapped modules", entry.name);
|
||||
if (g.sources.len > 1024) return g.invalid(.invalid_module_mapping, span, "more than 1024 mapped modules", entry.name);
|
||||
for (g.sources, 0..) |source, i| {
|
||||
if (reserved(source.name)) return g.fail("E7006", span, "package mapping uses a reserved namespace", source.name);
|
||||
for (g.sources[0..i]) |previous| if (std.mem.eql(u8, previous.name, source.name)) return g.fail("E7006", span, "module mapped twice", source.name);
|
||||
if (reserved(source.name)) return g.invalid(.invalid_module_mapping, span, "package mapping uses a reserved namespace", source.name);
|
||||
for (g.sources[0..i]) |previous| if (std.mem.eql(u8, previous.name, source.name)) return g.invalid(.invalid_module_mapping, span, "module mapped twice", source.name);
|
||||
}
|
||||
try g.nodes.append(g.arena, .{ .module = entry, .active = true });
|
||||
const root_height = try g.imports(entry, 0);
|
||||
@@ -91,7 +97,7 @@ const Graph = struct {
|
||||
fn imports(g: *Graph, m: ast.Module, depth: usize) Error!usize {
|
||||
var height: usize = 0;
|
||||
for (m.imports, 0..) |imp, i| {
|
||||
for (m.imports[0..i]) |previous| if (std.mem.eql(u8, imp.path, previous.path)) return g.fail("E7006", imp.span, "module imported twice", imp.path);
|
||||
for (m.imports[0..i]) |previous| if (std.mem.eql(u8, imp.path, previous.path)) return g.invalid(.duplicate_import, imp.span, "module imported twice", imp.path);
|
||||
height = @max(height, 1 + try g.visit(imp, depth + 1));
|
||||
}
|
||||
return height;
|
||||
@@ -99,11 +105,11 @@ const Graph = struct {
|
||||
|
||||
fn visit(g: *Graph, imp: ast.Import, depth: usize) Error!usize {
|
||||
for (g.nodes.items) |node| if (std.mem.eql(u8, node.module.name, imp.path)) {
|
||||
if (node.active) return g.fail("E7006", imp.span, "cyclic module import", imp.path);
|
||||
if (depth + node.height > 256) return g.fail("E7006", imp.span, "module import depth exceeds 256", imp.path);
|
||||
if (node.active) return g.invalid(.import_cycle, imp.span, "cyclic module import", imp.path);
|
||||
if (depth + node.height > 256) return g.invalid(.implementation_limit, imp.span, "module import depth exceeds 256", imp.path);
|
||||
return node.height;
|
||||
};
|
||||
if (depth > 256) return g.fail("E7006", imp.span, "module import depth exceeds 256", imp.path);
|
||||
if (depth > 256) return g.invalid(.implementation_limit, imp.span, "module import depth exceeds 256", imp.path);
|
||||
const source = for (stdlib.registry) |source| {
|
||||
if (std.mem.eql(u8, source.name, imp.path)) break source;
|
||||
} else for (g.sources) |source| {
|
||||
@@ -121,7 +127,7 @@ const Graph = struct {
|
||||
return error.InvalidSource;
|
||||
},
|
||||
};
|
||||
if (!std.mem.eql(u8, m.name, source.name)) return g.fail("E7006", .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 1 }, .file = source.file, .namespace = source.name }, "module header differs from its mapped name", source.name);
|
||||
if (!std.mem.eql(u8, m.name, source.name)) return g.invalid(.module_header_mismatch, .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 1 }, .file = source.file, .namespace = source.name }, "module header differs from its mapped name", source.name);
|
||||
const index = g.nodes.items.len;
|
||||
try g.nodes.append(g.arena, .{ .module = m, .active = true });
|
||||
const height = try g.imports(m, depth);
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Stable source E7006 categories and canonical CLI/package diagnostics."""
|
||||
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
|
||||
|
||||
|
||||
def invoke(*args, code=0):
|
||||
global checks
|
||||
p = subprocess.run([str(AJI), *map(str, args)], capture_output=True)
|
||||
assert p.returncode == code, (args, p.returncode, p.stdout, p.stderr)
|
||||
checks += 1
|
||||
return p.stdout
|
||||
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix='aji-reasons-') as d:
|
||||
root = Path(d)
|
||||
cases = [
|
||||
('move_copy', 'fn main()->u64 effects [] {let x=1u64;return move x;}'),
|
||||
('move_copy', 'struct S{x:u64} fn main()->u64 effects [] {let x=S{x:1u64};let y=move x;return 0u64;}'),
|
||||
('move_copy', 'fn main()->u64 effects [] {let x=[1u64;2];let y=move x;return 0u64;}'),
|
||||
('move_borrow', 'fn main()->u64 effects [] {let x=1u64;ref p=x;return move p;}'),
|
||||
('invalid_move', 'fn f(x:void)->u64 effects [] {return move x;} fn main()->u64 effects [] {0u64}'),
|
||||
('loop_control_outside_loop', 'fn main()->void effects [] {break;}'),
|
||||
('zero_not_zeroable', 'fn main()->u64 effects [] {var x:own<u64> = zero;return 0u64;}'),
|
||||
('value_block_statement', 'fn main()->i64 effects [] {{2i64} -3i64}'),
|
||||
('unreachable', 'fn main()->void effects [] {return; return;}'),
|
||||
('missing_return', 'fn main()->u64 effects [] {}'),
|
||||
('duplicate_declaration', 'fn main()->u64 effects [] {0u64} fn main()->u64 effects [] {0u64}'),
|
||||
('invalid_generic', 'fn f<T:Unknown>(x:T)->T effects [] {x} fn main()->u64 effects [] {0u64}'),
|
||||
('invalid_borrow_return', 'fn f(x:ref<u64>)->ref<u64> effects [] {x} fn main()->u64 effects [] {0u64}'),
|
||||
]
|
||||
for i, (reason, body) in enumerate(cases):
|
||||
path = root / f'case{i}.aji'
|
||||
path.write_text('module reasons\n' + body + '\n')
|
||||
error = json.loads(invoke('check', path, code=1))
|
||||
assert error['code'] == 'E7006' and error['reason'] == reason, error
|
||||
assert error['file'] == str(path) and error['line'] == 2
|
||||
if i == 0:
|
||||
assert list(error) == ['code', 'kind', 'severity', 'file', 'line', 'col',
|
||||
'name', 'type', 'reason', 'message'], error
|
||||
assert json.loads(invoke('lower', path, code=1)) == error
|
||||
assert invoke('check', path, code=1) == invoke('check', path, code=1)
|
||||
|
||||
# Copy substitution in a generic transfer is permitted, not a Copy-move
|
||||
# diagnostic. Borrowed substitution still rejects with its own reason.
|
||||
valid = root / 'generic.aji'
|
||||
valid.write_text('module generic fn f<T: Copy>(x:T)->T effects [] {move x} '
|
||||
'fn main()->u64 effects [] {f::<u64>(42u64)}')
|
||||
assert json.loads(invoke('run', '--fuel', '10000', valid))['value'] == 42
|
||||
bad = root / 'borrow-generic.aji'
|
||||
bad.write_text('module bg fn f<T>(x:T)->T effects [] {move x} '
|
||||
'fn main()->u64 effects [] {let x=1u64;ref p=x;let y=f::<ref<u64>>(p);return 0u64;}')
|
||||
error = json.loads(invoke('check', bad, code=1))
|
||||
# The missing explicit origin in the specialized signature is diagnosed
|
||||
# before its body, and must never be counted as move_copy.
|
||||
assert error['reason'] == 'invalid_borrow_return', error
|
||||
bad.write_text('module bg fn f<T>(x:ref<T>)->u64 effects [] {let y=move x;return 0u64;} '
|
||||
'fn main()->u64 effects [] {let x=1u64;ref p=x;return f::<u64>(p);}')
|
||||
error = json.loads(invoke('check', bad, code=1))
|
||||
assert error['reason'] == 'move_borrow', error
|
||||
|
||||
entry = root / 'entry.aji'
|
||||
dep = root / 'dep.aji'
|
||||
entry.write_text('module app import dep; fn main()->u64 effects [] {dep.f()}')
|
||||
dep.write_text('module dep fn f()->u64 effects [] {let n=1u64;return move n;}')
|
||||
manifest = root / 'aji.toml'
|
||||
manifest.write_text('[package]\nname = "reasons"\nversion = "1"\nentry = "entry.aji"\n'
|
||||
'[modules]\ndep = "dep.aji"\n')
|
||||
error = json.loads(invoke('check', '--manifest', manifest, code=1))
|
||||
assert error['reason'] == 'move_copy' and error['file'] == dep.name, error
|
||||
dep.write_text('module different fn f()->u64 effects [] {1u64}')
|
||||
error = json.loads(invoke('check', '--manifest', manifest, code=1))
|
||||
assert error['reason'] == 'module_header_mismatch' and error['file'] == dep.name, error
|
||||
|
||||
# Exercise all public standalone E7006 fixtures, without visiting any
|
||||
# benchmark corpus or unrelated untracked directory.
|
||||
registry = (REPO / 'docs/reference/error-codes.md').read_text()
|
||||
reasons = set(re.findall(r'^\| `([a-z_]+)` \|', registry, re.M))
|
||||
fixtures = 0
|
||||
for path in sorted((REPO / 'tests/conformance/source').rglob('*.aji')):
|
||||
if not re.search(r'^// expect: reject E7006\s*$', path.read_text(), re.M):
|
||||
continue
|
||||
p = subprocess.run([str(AJI), 'check', str(path)], capture_output=True)
|
||||
if p.returncode == 1:
|
||||
errors = [json.loads(line) for line in p.stdout.splitlines()]
|
||||
for error in errors:
|
||||
if error['code'] == 'E7006':
|
||||
assert error['reason'] in reasons, (path, error)
|
||||
fixtures += 1
|
||||
checks += 1
|
||||
assert fixtures > 0, fixtures
|
||||
ordinary = root / 'type-error.aji'
|
||||
ordinary.write_text('module ordinary fn main()->u64 effects [] {return true;}')
|
||||
error = json.loads(invoke('check', ordinary, code=1))
|
||||
assert error['code'] == 'E7005' and 'reason' not in error
|
||||
print(f'source diagnostic reasons passed ({checks} checks; {fixtures} public E7006 fixtures)')
|
||||
+101
-15
@@ -10,14 +10,16 @@ import statistics
|
||||
from . import util
|
||||
|
||||
|
||||
def load(paths):
|
||||
runs = []
|
||||
def _run_files(paths):
|
||||
for p in paths:
|
||||
for f in [p] if p.endswith("run.json") else glob.glob(os.path.join(p, "**", "run.json"), recursive=True):
|
||||
if "/superseded/" in f:
|
||||
continue
|
||||
runs.append(util.read_json(f))
|
||||
return runs
|
||||
yield f
|
||||
|
||||
|
||||
def load(paths):
|
||||
return [util.read_json(f) for f in _run_files(paths)]
|
||||
|
||||
|
||||
def mean(xs):
|
||||
@@ -134,6 +136,7 @@ def summary(paths):
|
||||
unc = [((r["metrics"].get("context") or {}).get("provider_input_tokens") or {}).get("uncached") for r in rs]
|
||||
out.append(f"| {k} | {len(rs)} | {acc} | {round(acc / len(rs), 3)} | {mean(cyc)} | {mean([r['metrics'].get('tool_calls') for r in rs])} | {mean([r['metrics'].get('elapsed_seconds') for r in rs])} | {mean(unc)} |")
|
||||
out.append("")
|
||||
out.append(_diagnostic_reason_summary(paths))
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
@@ -151,20 +154,24 @@ def _source_size(run_dir, exts):
|
||||
return files, lines, nbytes
|
||||
|
||||
|
||||
def _diagnostic_codes(r, run_dir):
|
||||
def _command_outputs(r, run_dir):
|
||||
from . import native
|
||||
|
||||
if r.get("track") == "B":
|
||||
return [o for _, _, o in native.command_events(r["agent"]["name"], os.path.join(run_dir, "transcript.jsonl"))]
|
||||
with open(os.path.join(run_dir, "events.jsonl")) as f:
|
||||
return [json.loads(l).get("output") or "" for l in f if '"event": "command"' in l]
|
||||
|
||||
|
||||
def _diagnostic_codes(r, run_dir, outputs=None):
|
||||
"""Counts of verifier/compiler diagnostic codes seen in the run's command
|
||||
outputs (codes only: no message text, no task content)."""
|
||||
import collections
|
||||
import re
|
||||
|
||||
from . import native
|
||||
|
||||
counts = collections.Counter()
|
||||
if r.get("track") == "B":
|
||||
cmds = native.command_events(r["agent"]["name"], os.path.join(run_dir, "transcript.jsonl"))
|
||||
outputs = [o for _, _, o in cmds]
|
||||
else:
|
||||
outputs = [json.loads(l).get("output") or "" for l in open(os.path.join(run_dir, "events.jsonl")) if '"event": "command"' in l]
|
||||
if outputs is None:
|
||||
outputs = _command_outputs(r, run_dir)
|
||||
lang = r["language"]["name"]
|
||||
for o in outputs:
|
||||
if lang in ("aji_air", "aji_source"):
|
||||
@@ -177,6 +184,80 @@ def _diagnostic_codes(r, run_dir):
|
||||
return dict(counts.most_common())
|
||||
|
||||
|
||||
def _diagnostic_reasons(r, run_dir):
|
||||
"""Split the existing Aji code counts using whole JSON diagnostic records.
|
||||
|
||||
Unparsed/historical records retain reason=None. Code totals and their
|
||||
historical extraction are unchanged; no message text supplies a reason.
|
||||
None means unavailable logs or a non-Aji language, not zero observations.
|
||||
"""
|
||||
import collections
|
||||
|
||||
if r["language"]["name"] not in ("aji_air", "aji_source"):
|
||||
return None
|
||||
logfile = "transcript.jsonl" if r.get("track") == "B" else "events.jsonl"
|
||||
if not os.path.isfile(os.path.join(run_dir, logfile)):
|
||||
return None
|
||||
outputs = _command_outputs(r, run_dir)
|
||||
counts = collections.Counter({(c, None): n for c, n in _diagnostic_codes(r, run_dir, outputs).items()})
|
||||
for output in outputs:
|
||||
for line in output.splitlines():
|
||||
try:
|
||||
record = json.loads(line)
|
||||
except (ValueError, TypeError):
|
||||
continue
|
||||
if not isinstance(record, dict):
|
||||
continue
|
||||
code, reason = record.get("code"), record.get("reason")
|
||||
if not isinstance(code, str) or not isinstance(reason, str) or not reason:
|
||||
continue
|
||||
# Only split a record the existing compact-code extractor counted.
|
||||
# A spaced/unrelated record cannot consume another unknown record.
|
||||
if f'"code":"{code}"' not in line or counts[(code, None)] <= 0:
|
||||
continue
|
||||
counts[(code, None)] -= 1
|
||||
counts[(code, reason)] += 1
|
||||
return [{"code": c, "reason": reason, "count": n}
|
||||
for (c, reason), n in sorted(counts.items(), key=lambda x: (x[0][0], x[0][1] or "")) if n]
|
||||
|
||||
|
||||
def _reason_label(reason):
|
||||
return "unknown" if reason is None else reason.replace("|", "\\|").replace("\n", " ")
|
||||
|
||||
|
||||
def _diagnostic_reason_summary(paths):
|
||||
import collections
|
||||
|
||||
totals, available, occurrences, incidence = (collections.Counter() for _ in range(4))
|
||||
for f in _run_files(paths):
|
||||
r = util.read_json(f)
|
||||
lang = r["language"]["name"]
|
||||
if lang not in ("aji_air", "aji_source"):
|
||||
continue
|
||||
totals[lang] += 1
|
||||
pairs = _diagnostic_reasons(r, os.path.dirname(f))
|
||||
if pairs is None:
|
||||
continue
|
||||
available[lang] += 1
|
||||
for pair in pairs:
|
||||
key = lang, pair["code"], pair["reason"]
|
||||
occurrences[key] += pair["count"]
|
||||
incidence[key] += 1
|
||||
if not totals:
|
||||
return ""
|
||||
out = ["### Observed diagnostic reasons\n",
|
||||
"Counts describe observed command outputs. Historical or unparsed reasons are unknown; unavailable logs are excluded from observations.\n",
|
||||
"| language | code | reason | occurrences | runs observed | logs available / runs |",
|
||||
"|---|---|---|---|---|---|"]
|
||||
for lang in sorted(totals):
|
||||
keys = sorted((k for k in occurrences if k[0] == lang), key=lambda k: (k[1], k[2] or ""))
|
||||
for key in keys:
|
||||
out.append(f"| {lang} | {key[1]} | {_reason_label(key[2])} | {occurrences[key]} | {incidence[key]} | {available[lang]}/{totals[lang]} |")
|
||||
if not keys:
|
||||
out.append(f"| {lang} | - | - | - | - | {available[lang]}/{totals[lang]} |")
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
# Diagnostics about the textual form of AIR (syntax, names, module header,
|
||||
# SSA, CFG): the classes the source frontend is meant to remove. Type
|
||||
# mismatches (E1001 from AIR, E7005 from source) are semantic and counted
|
||||
@@ -212,8 +293,8 @@ def profile(paths):
|
||||
Shareable: numbers and diagnostic codes only."""
|
||||
from . import languages
|
||||
|
||||
out = ["| task | language | agent | termination | output tokens | tool calls | source files / lines / bytes | lowered AIR bytes raw / normalized | docs files read | IR-form diagnostics | type mismatches | diagnostic codes (count) |",
|
||||
"|---|---|---|---|---|---|---|---|---|---|---|---|"]
|
||||
out = ["| task | language | agent | termination | output tokens | tool calls | source files / lines / bytes | lowered AIR bytes raw / normalized | docs files read | IR-form diagnostics | type mismatches | diagnostic codes (count) | code / reason (count) |",
|
||||
"|---|---|---|---|---|---|---|---|---|---|---|---|---|"]
|
||||
for p in paths:
|
||||
for f in sorted(glob.glob(os.path.join(p, "**", "run.json"), recursive=True)):
|
||||
if "/superseded/" in f:
|
||||
@@ -223,6 +304,9 @@ def profile(paths):
|
||||
exts = set(languages.load(r["language"]["name"]).get("source_extensions", []))
|
||||
files, lines, nbytes = _source_size(d, exts)
|
||||
codes = _diagnostic_codes(r, d)
|
||||
pairs = _diagnostic_reasons(r, d)
|
||||
reasons = "n/a" if pairs is None else ", ".join(
|
||||
f"{p['code']} / {_reason_label(p['reason'])} {p['count']}" for p in pairs) or "-"
|
||||
m = r["metrics"]
|
||||
lowered = _lowered_size(d) if r["language"]["name"] == "aji_source" else None
|
||||
docs = (m.get("context") or {}).get("docs") or {}
|
||||
@@ -230,7 +314,7 @@ def profile(paths):
|
||||
ty = sum(v for k, v in codes.items() if k in TYPE_MISMATCH)
|
||||
out.append(f"| {r['task']['id']} | {r['language']['name']} | {_agent_key(r)} | {m.get('termination')} | {m.get('output_tokens')} | {m.get('tool_calls')} | "
|
||||
f"{files} / {lines} / {nbytes} | {f'{lowered[0]} / {lowered[1]}' if lowered else '-'} | "
|
||||
f"{docs.get('unique_docs_read', '-')} | {ir} | {ty} | {', '.join(f'{k} {v}' for k, v in codes.items()) or '-'} |")
|
||||
f"{docs.get('unique_docs_read', '-')} | {ir} | {ty} | {', '.join(f'{k} {v}' for k, v in codes.items()) or '-'} | {reasons} |")
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
@@ -489,6 +573,7 @@ def checkpoint_rows(paths):
|
||||
"output_tokens": v(m.get("output_tokens")),
|
||||
"docs": doc_fields,
|
||||
"diagnostics": _diagnostic_buckets(codes),
|
||||
"diagnostic_reasons": _diagnostic_reasons(r, d),
|
||||
"program": program,
|
||||
# B1 §5 (n/a in records without the data).
|
||||
"pretest_static_safety_caught": statically_prevented(r, d, codes),
|
||||
@@ -514,5 +599,6 @@ def checkpoint(paths, as_json=False):
|
||||
out.append(f"- {group}:")
|
||||
for k, x in r[group].items():
|
||||
out.append(f" - {k}: {json.dumps(x) if isinstance(x, (dict, list)) else x}")
|
||||
out.append(f"- diagnostic_reasons: {json.dumps(r['diagnostic_reasons'])}")
|
||||
out.append("")
|
||||
return "\n".join(out)
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Structured reason counts: historical uncertainty and per-run incidence."""
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from ajieval import report
|
||||
|
||||
|
||||
class DiagnosticReasons(unittest.TestCase):
|
||||
def events(self, directory, outputs):
|
||||
with open(os.path.join(directory, 'events.jsonl'), 'w') as f:
|
||||
for output in outputs:
|
||||
f.write(json.dumps({'event': 'command', 'output': output}) + '\n')
|
||||
|
||||
def test_unknown_historical_records_and_code_totals(self):
|
||||
r = {'language': {'name': 'aji_source'}}
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
self.events(d, [
|
||||
'{"code":"E7006","reason":"move_copy","message":"any prose"}\n'
|
||||
'{"reason":"zero_not_zeroable","code":"E7006"}\n'
|
||||
'{"code":"E7006","message":"move applies to Copy"}\n'
|
||||
'prefix {"code":"E7006","reason":"move_copy"} truncated\n'
|
||||
'{"code":"E7006","reason":12}\n'
|
||||
'{"code":"E0006","reason":"future_reason"}\n'
|
||||
'{"code":"E3101"}\n'])
|
||||
pairs = report._diagnostic_reasons(r, d)
|
||||
self.assertEqual(pairs, [
|
||||
{'code': 'E0006', 'reason': 'future_reason', 'count': 1},
|
||||
{'code': 'E3101', 'reason': None, 'count': 1},
|
||||
{'code': 'E7006', 'reason': None, 'count': 3},
|
||||
{'code': 'E7006', 'reason': 'move_copy', 'count': 1},
|
||||
{'code': 'E7006', 'reason': 'zero_not_zeroable', 'count': 1}])
|
||||
totals = {}
|
||||
for row in pairs:
|
||||
totals[row['code']] = totals.get(row['code'], 0) + row['count']
|
||||
self.assertEqual(totals, report._diagnostic_codes(r, d))
|
||||
|
||||
def test_native_outputs_and_unavailable_logs(self):
|
||||
r = {'track': 'B', 'agent': {'name': 'claude'}, 'language': {'name': 'aji_source'}}
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
self.assertIsNone(report._diagnostic_reasons(r, d))
|
||||
open(os.path.join(d, 'transcript.jsonl'), 'w').close()
|
||||
outputs = [(None, None, '{"code":"E7006","reason":"move_borrow"}\n')]
|
||||
with patch('ajieval.native.command_events', return_value=outputs):
|
||||
self.assertEqual(report._diagnostic_reasons(r, d), [
|
||||
{'code': 'E7006', 'reason': 'move_borrow', 'count': 1}])
|
||||
self.assertIsNone(report._diagnostic_reasons({'language': {'name': 'rust'}}, d))
|
||||
|
||||
def test_spaced_records_do_not_change_legacy_code_counts(self):
|
||||
r = {'language': {'name': 'aji_source'}}
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
self.events(d, ['{"code": "E7006", "reason": "move_copy"}\n'
|
||||
'{"code":"E7006"}\n'])
|
||||
# The historical code-count extractor deliberately remains intact.
|
||||
# A spaced record it did not count cannot consume another record's
|
||||
# unknown bucket and manufacture known Copy evidence.
|
||||
self.assertEqual(report._diagnostic_reasons(r, d), [
|
||||
{'code': 'E7006', 'reason': None, 'count': 1}])
|
||||
|
||||
def test_summary_counts_runs_once_and_reports_log_coverage(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
runs = []
|
||||
for i in range(3):
|
||||
d = os.path.join(root, str(i)); os.makedirs(d)
|
||||
r = {'task': {'id': 'synthetic'}, 'language': {'name': 'aji_source'},
|
||||
'model': {'id': 'test', 'class': 'test'}, 'accepted': False,
|
||||
'metrics': {'context': {}}, '_dir': d}
|
||||
runs.append(r)
|
||||
with open(os.path.join(d, 'run.json'), 'w') as f:
|
||||
json.dump(r, f)
|
||||
if i != 2:
|
||||
output = ('{"code":"E7006","reason":"move_copy"}\n' * 2
|
||||
if i == 0 else '{"code":"E7006"}\n')
|
||||
self.events(d, [output])
|
||||
text = report.summary([root])
|
||||
self.assertIn('| aji_source | E7006 | move_copy | 2 | 1 | 2/3 |', text)
|
||||
self.assertIn('| aji_source | E7006 | unknown | 1 | 1 | 2/3 |', text)
|
||||
self.assertIn('observed command outputs', text)
|
||||
rows = report.checkpoint_rows([os.path.join(root, '0'), os.path.join(root, '1')])
|
||||
pairs = [p for row in rows for p in (row['diagnostic_reasons'] or [])]
|
||||
self.assertIn({'code': 'E7006', 'reason': 'move_copy', 'count': 2}, pairs)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user