diag: guide parameter mutability and explicit array slice arguments

This commit is contained in:
dev committed 2026-10-09 21:12:26 +03:00
1 parent 6a02659f31
commit 9549a3dec6
22 files changed
+197 -4

No files matched your search

+1 -1
View File
@@ -34,7 +34,7 @@ python3 tests/hosted/source_store_modes.py # exclusive places, source positions,
python3 tests/hosted/source_nominal_queries.py # deep shared types, deterministic limits and package cache indices
python3 tests/hosted/source_grammar.py # syntax boundaries, canonical enum lists and formatter/AIR fidelity
python3 tests/hosted/source_effect_names.py # effect-name errors, signature priority and package provenance
python3 tests/hosted/source_repair_advice.py # contextual syntax/cast advice and CLI/package parity
python3 tests/hosted/source_repair_advice.py # contextual syntax/cast/array-call advice and CLI/package parity
python3 tests/hosted/source_independent_errors.py # bounded source error collection without cascades or partial AIR
python3 tests/hosted/source_cfg_provenance.py # resource handoff, loan origins and source/package/AIR diagnostics
python3 tools/source_reject_twins.py # audited same-code pairs and exhaustive, explicitly incomplete AIR inventory
+2
View File
@@ -178,3 +178,5 @@ P6-7 factual source E4202 fields (cl100k): Quick Reference stays 8,955; other so
Spec 15 scope corrections (cl100k): Quick Reference stays 8,955 tokens despite the E1002 → E7005 correction; other source docs 68,353 → 68,403 (+50), full source 77,308 → 77,358 (+0.06%). o200k full source grows 77,547 → 77,594 (+47); Qwen2.5 79,257 → 79,315 (+58). AIR and std are unchanged. Existing source diagnostics, unpacking, escapes, buffers and borrow returns replace obsolete baseline descriptions; no semantic or implementation change.
Pointer-sized cast guidance (2026-10-09): Quick Reference grows 9,255 → 9,276 cl100k (+21); other source docs 69,817 → 69,863 (+46), full source 79,072 → 79,139 (+67, +0.085%). o200k grows by the same +21/+46/+67 (full 79,373); Qwen2.5 by +21/+47/+68 (full 81,127). AIR grows 188,993 → 189,078 bytes and +22 tokens for each tokenizer (48,398 cl100k / 48,551 o200k / 49,956 Qwen2.5). The existing target-independent ban on usize/isize widening is explained in the registered numeric-cast hint and source cast table. No new concept, syntax, feature, diagnostic code/kind or verifier/runtime state is introduced. Pointer identity casts now reject with source E7005/advice before AIR E1002; the accepted set is unchanged. No empirical reduction in repair rounds is claimed.
Parameter/array-call advice (2026-10-09): Quick Reference grows 9,276 → 9,360 cl100k (+84); other source docs 69,863 → 70,167 (+304), full source 79,139 → 79,527 (+388, +0.49%). o200k grows +84/+303/+387 (full 79,760); Qwen2.5 +84/+308/+392 (full 81,519). AIR grows 189,078 → 190,503 bytes, +304/+303/+308 tokens respectively (48,702 cl100k / 48,854 o200k / 50,264 Qwen2.5). Two registered advice kinds distinguish parameter ownership choices and explicit array-to-slice argument borrows; applicability and fixed prefix units account for the growth. No new syntax, semantic concept, code, feature or verifier/runtime state is added; existing envelopes/rejection priority and accepted lowerings remain unchanged. No empirical repair-round benefit is claimed.
+2
View File
@@ -12,6 +12,7 @@ Aji makes every significant action explicit — moves, borrows, allocation, clos
| a narrowing `x as T` | `x as! T` checks/traps; `x as% T` wraps |
| `let mut x = value` / `var x = value` | `var x: T = value;` (type required) |
| immutable `let x = value` | `let x = value;` (type may be inferred) |
| `fn f(mut x: T)` | `fn f(x: T)` with a local `var`, or `fn f(x: mut<T>)` for an exclusive borrow; choose the ownership contract |
| mutable/shared slice type | `slice_mut<T>` / `slice<T>` |
| `s[start..]` | `s[start..end]` (explicit upper bound) |
| `f(&x)` / `f(&mut x)` | `f(ref x)` / `f(mut x)` |
@@ -118,6 +119,7 @@ Rules (checked by the verifier):
- **A borrow lives until the end of the block where it was bound** (`ref r = …;` / `mut r = …;`). A borrow written as an argument (`f(mut buf)`) lives for that call. To end one early, put it in an inner `{ … }` block.
- A whole-array argument `f(ref a)` / `f(mut a)` preserves the array for a `ref<[T; N]>` / `mut<[T; N]>` parameter; otherwise it becomes a slice. Length and mode must match. Bound array borrows remain slices.
- An array value is not a slice argument: use `f(ref a)` for `slice<T>` or `f(mut a)` for `slice_mut<T>`; the place and loan must verify.
- **Exclusive XOR shared.** While a `mut` borrow of a place is live, no other borrow of the same place, and no direct use of it, is allowed (`E2101`). Disjoint fields and `split_at` halves are independent.
- A borrow cannot outlive what it borrows from (`E2102`). A function returns a borrow only with explicit `from param`. Bind returned views with `ref`/`mut`; the `from` argument must be a named borrow. Return the bound name without `move`; a local-frame view cannot escape (`E2108`).
- **Moves are explicit:** a named linear value is consumed only as `move x` (otherwise `E7003`). A fresh temporary needs no `move`: `consume(make())`. Copyable values are passed plainly; `move` on them is `E7006`.
+10
View File
@@ -394,3 +394,13 @@ The [source rejection/compatibility audit](../design/contract-source-errors-and-
Public development feedback identifies u8 → usize and usize → u64 casts rejected without explaining the target-independent rule. Spec 02 §2 already excludes usize/isize from widen, including conversions that fit under every current target. The registered numeric_cast_modes hint now states that rule, keeping the original E7005 message/fields and checked/wrapping alternatives. Source/Quick Reference cast tables explain it too; no semantic widening extension is adopted. Pointer identity as casts now follow the same source rejection instead of leaking AIR E1002 without advice. Six rejection fixtures and an explicit checked/wrapping runtime case cover the rule; hosted advice tests pass 208 checks including source API parity and fixed-width identities. Bundle growth is measured in agent/README.md. Parameter-mutability and array-to-slice advice from the same feedback remain open work; no new dev/model experiment or repair-round benefit is claimed.
Validation of cast guidance: units/format checks and all 1,776 conformance cases pass. Comparison of 1,403 pre-existing source files changes only the registered hint; all 500 accepted lowerings remain byte-identical.
## P6-12 parameter and array-call advice (2026-10-09)
Public development feedback now has two narrowly registered candidates. E7001 at `mut name:` in a function parameter distinguishes value/local storage from an exclusive `mut<T>` contract, without choosing for the agent. An ordinary-call E7005 for a bare named, non-linear array with matching slice elements suggests the explicit `ref` or `mut` prefix required by the known parameter. Array expressions/projections, unlike elements, intrinsic/task operands and earlier name/move/arity failures are excluded. Generic/static specializations and imported calls retain the same rule and source provenance. Existing messages, payloads, code/location, accepted syntax/inference and loan lifetime remain unchanged. Prefix advice is not a verification claim: by-value parameter arrays still require an addressable local place.
The exclusivity/lifetime invariants, verifier transfer rules, explicit borrow creation/end and deterministic runtime are unchanged (spec 03; spec 15 §5). A positive source run covers mutable local copies, exclusive parameters and shared/exclusive slices; six rejection cases cover the triggers and nearby exclusions. Hosted advice tests pass 299 checks, including source API/package parity and generic/static repaired programs; whole-array integration passes 85 checks. Bundle growth is measured in agent/README.md. No language synonym, automatic conversion, semantic adoption or new dev/model experiment is introduced; the external repair-round measurement remains pending.
Validation: units/format checks and all 1,783 conformance cases pass; independent source-error collection passes 234 CLI checks. The six original trigger/exclusion diagnostics retain their complete envelopes after removing only the new candidate field.
Old/new comparison of 1,410 pre-existing source files preserves every diagnostic envelope after removing only the two new registered candidates, and all 501 accepted lowerings remain byte-identical. Advice is additionally emitted for the existing std/implicit_borrow rejection; its E7005 facts are unchanged. No fresh Claude review was available. P6-12 still awaits external development-run measurements.
+4
View File
@@ -127,6 +127,8 @@ These stable kinds use spec 10 §3. `hint` MUST equal the registered text. Alter
| `borrow_binding` | E7001 | Bind a borrow with `ref name = place;` or `mut name = place;`, rather than a let/var initializer. | none |
| `zero_storage` | E7001 | `zero` is only a whole var initializer: `var name: T = zero;`; T must be zeroable. | none |
| `numeric_cast_modes` | E7005 | The target-independent `as` rule excludes `usize`/`isize`, even when the value fits. Choose `as!` for a checked conversion (T0006 on overflow) or `as%` for a wrapping conversion. | operator |
| `parameter_mutability` | E7001 | Write `name: T` for a value parameter; use a local `var` for mutable storage, or `name: mut<T>` for an exclusive borrowed parameter. Choose the intended ownership contract. | none |
| `array_slice_argument` | E7005 | Pass an array as an explicit borrow: `ref array` for `slice<T>` or `mut array` for `slice_mut<T>`. The place and loan must still verify. | prefix |
Closed applicability:
@@ -137,6 +139,8 @@ Closed applicability:
- Borrow kinds: `&` rejected as the first token of a call argument, excluding enum variant payloads (`borrow_argument`) or let/typed-var initializer (`borrow_binding`). Other expression contexts, including the second `&` in `a && b`, have no borrow advice. For an argument whose following token is an ordinary identifier, emit `["ref"]`; for `&mut` followed by an ordinary identifier, emit `["mut"]`. Other operands have hint only, including `&&x`. These prefixes do not imply that the referent/mode verifies; binding advice has no prefix alternative.
- `zero_storage`: keyword `zero` rejected at primary-expression start. Accepted typed-var zero initialization has no advice.
- `numeric_cast_modes`: integer `as` rejected by the lossless-widening rule, with unchanged `from`/`to`. Alternatives MUST be `["as!", "as%"]`. Non-integer casts and other E7005 rules have no such candidate.
- `parameter_mutability`: `mut` rejected where a function parameter name is required, immediately followed by an ordinary identifier and `:`. Hint only: value storage and an exclusive borrow have different ownership contracts. Other malformed parameter prefixes and incomplete `mut` spellings have no such advice.
- `array_slice_argument`: ordinary function-call argument type mismatch for a bare named, non-linear array whose element type equals the expected `slice<T>` or `slice_mut<T>` element type. Alternatives MUST be `["ref"]` for a shared slice and `["mut"]` for an exclusive slice. This is an explicit borrow prefix, not an implicit conversion or a guarantee that the place/loan verifies. Excludes other element types, array expressions/projections, existing borrow arguments, bindings/returns, intrinsics and task spawning (which requires a retained named loan). Earlier name/move/operand errors retain priority. The same rule applies to explicitly specialized generic/static functions and imported ordinary calls.
## E7006 reasons
+9 -2
View File
@@ -198,6 +198,8 @@ pub const SourceRepairKind = enum {
borrow_binding,
zero_storage,
numeric_cast_modes,
parameter_mutability,
array_slice_argument,
pub fn hint(kind: SourceRepairKind) []const u8 {
return switch (kind) {
@@ -210,17 +212,22 @@ pub const SourceRepairKind = enum {
.borrow_binding => "Bind a borrow with `ref name = place;` or `mut name = place;`, rather than a let/var initializer.",
.zero_storage => "`zero` is only a whole var initializer: `var name: T = zero;`; T must be zeroable.",
.numeric_cast_modes => "The target-independent `as` rule excludes `usize`/`isize`, even when the value fits. Choose `as!` for a checked conversion (T0006 on overflow) or `as%` for a wrapping conversion.",
.parameter_mutability => "Write `name: T` for a value parameter; use a local `var` for mutable storage, or `name: mut<T>` for an exclusive borrowed parameter. Choose the intended ownership contract.",
.array_slice_argument => "Pass an array as an explicit borrow: `ref array` for `slice<T>` or `mut array` for `slice_mut<T>`. The place and loan must still verify.",
};
}
pub fn code(kind: SourceRepairKind) []const u8 {
return if (kind == .numeric_cast_modes) "E7005" else "E7001";
return switch (kind) {
.numeric_cast_modes, .array_slice_argument => "E7005",
else => "E7001",
};
}
pub fn unit(kind: SourceRepairKind) []const u8 {
return switch (kind) {
.slice_mut_type, .slice_ref_type => "complete type",
.borrow_argument => "prefix",
.borrow_argument, .array_slice_argument => "prefix",
.numeric_cast_modes => "operator",
else => "none",
};
+18 -1
View File
@@ -1945,7 +1945,7 @@ const Lowerer = struct {
for (args, sig.params, 0..) |a, pt, i| {
const v = try l.argument(a, pt, &temps);
if (sig.from == i) parent = v.name;
try l.checkOperandTy(a.span, v.ty, pt);
try l.checkCallArgumentTy(a, v.ty, pt);
try arg_names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", v.name }));
}
const text = try l.fmt("call @{s}({s})", .{ sig.air_name, arg_names.items });
@@ -2313,6 +2313,23 @@ const Lowerer = struct {
return .{ .name = st, .ty = ty };
}
/// Advice belongs to the existing ordinary-call mismatch, after argument
/// lowering. Never change earlier name/move errors or infer a borrow.
fn checkCallArgumentTy(l: *Lowerer, a: ast.Expr, found: Ty, want: Ty) Error!void {
l.checkOperandTy(a.span, found, want) catch |err| {
if (err == error.Lower and a.kind == .name and found == .array and
(want == .slice or want == .slice_mut) and found.array.elem.eql(want.inner().?) and !l.isLinear(found))
{
const kind = @import("../diag.zig").SourceRepairKind.array_slice_argument;
l.problem.?.repair_candidates = if (want == .slice)
comptime &.{kind.candidate(&.{"ref"})}
else
comptime &.{kind.candidate(&.{"mut"})};
}
return err;
};
}
/// A call argument: `ref place` / `mut place` and byte strings are
/// borrowed for the call (`temps` end after it); anything else is a value.
fn argument(l: *Lowerer, a: ast.Expr, want: ?Ty, temps: *std.ArrayList([]const u8)) Error!Value {
+2
View File
@@ -374,6 +374,8 @@ const Parser = struct {
var params: std.ArrayList(ast.Param) = .empty;
while (p.peek().tag != .r_paren) {
const ps = p.peek().pos;
if (p.atWord("mut") and p.peekAt(1).tag == .ident and !isKeyword(p.peekAt(1).text) and p.peekAt(2).tag == .colon)
return p.failAdvice(p.peek(), "parameter name", .parameter_mutability);
const pname = try p.ident("parameter name");
_ = try p.expect(.colon, "`:`");
const ty = try p.typeExpr();
@@ -0,0 +1,6 @@
// expect: reject E7005
// phase: 6
// spec: docs/spec/15-source-language.md §4/§5/§10; docs/reference/error-codes.md
module probe
fn f(a: slice<u16>) -> void effects [] {}
fn main() -> void effects [] { let a: [u8; 7] = [0u8; 7]; f(a); }
@@ -0,0 +1,6 @@
// expect: reject E7005
// phase: 6
// spec: docs/spec/15-source-language.md §4/§5/§10; docs/reference/error-codes.md
module probe
fn f(a: slice_mut<u8>) -> void effects [] {}
fn main() -> void effects [] { var a: [u8; 7] = zero; f(a); }
@@ -0,0 +1 @@
[{"kind":"array_slice_argument","hint":"Pass an array as an explicit borrow: `ref array` for `slice<T>` or `mut array` for `slice_mut<T>`. The place and loan must still verify.","alternatives":["mut"]}]
@@ -0,0 +1,6 @@
// expect: reject E7005
// phase: 6
// spec: docs/spec/15-source-language.md §4/§5/§10; docs/reference/error-codes.md
module probe
fn f(a: slice<u8>) -> void effects [] {}
fn main() -> void effects [] { f([0u8; 7]); }
@@ -0,0 +1,6 @@
// expect: reject E7005
// phase: 6
// spec: docs/spec/15-source-language.md §4/§5/§10; docs/reference/error-codes.md
module probe
fn f(a: slice<u8>) -> void effects [] {}
fn main() -> void effects [] { let a: [u8; 7] = [0u8; 7]; f(a); }
@@ -0,0 +1 @@
[{"kind":"array_slice_argument","hint":"Pass an array as an explicit borrow: `ref array` for `slice<T>` or `mut array` for `slice_mut<T>`. The place and loan must still verify.","alternatives":["ref"]}]
@@ -0,0 +1,15 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/15-source-language.md §4/§5/§10
module advice.canonical
fn local(x: u8) -> u8 effects [] { var y: u8 = x; y = y + 1; return y; }
fn update(x: mut<u8>) -> void effects [] { *x = local(*x); }
fn read(a: slice<u8>) -> u8 effects [] { return a[0]; }
fn set(a: slice_mut<u8>) -> void effects [] { a[0] = 41; }
fn main() -> u8 effects [] {
var a: [u8; 7] = zero;
set(mut a);
update(mut a[0usize]);
return read(ref a);
}
@@ -0,0 +1,6 @@
// expect: reject E7001
// phase: 6
// spec: docs/spec/15-source-language.md §4/§5/§10; docs/reference/error-codes.md
module probe
fn f(mut) -> void effects [] {}
fn main() -> void effects [] {}
@@ -0,0 +1,6 @@
// expect: reject E7001
// phase: 6
// spec: docs/spec/15-source-language.md §4/§5/§10; docs/reference/error-codes.md
module probe
fn f(mut x: u8) -> void effects [] {}
fn main() -> void effects [] {}
@@ -0,0 +1 @@
[{"kind":"parameter_mutability","hint":"Write `name: T` for a value parameter; use a local `var` for mutable storage, or `name: mut<T>` for an exclusive borrowed parameter. Choose the intended ownership contract."}]
+92
View File
@@ -182,4 +182,96 @@ with tempfile.TemporaryDirectory(prefix='source-advice-', dir=cache) as director
'fn main() -> void effects [] {}\n')
cli('check', probe)
# Parameter syntax and ordinary-call array mismatches preserve the
# original envelope, across source APIs and imported bodies.
call_corpus = REPO / 'tests/conformance/source/call_repair_advice'
for path in sorted(call_corpus.glob('*.aji')):
if path.stem == 'explicit_contracts':
cli('check', path)
assert json.loads(cli('run', '--fuel', '100000', path))['value'] == 42
continue
error = json.loads(cli('check', path, code=1))
if path.stem == 'parameter_mutability':
advice(error, 'parameter_mutability')
assert (error['expected'], error['found'], error['message']) == (
'parameter name', 'mut', 'expected parameter name'), error
elif path.stem in ('array_slice_shared', 'array_slice_exclusive'):
exclusive = path.stem.endswith('exclusive')
advice(error, 'array_slice_argument', ['mut' if exclusive else 'ref'])
assert (error['expected'], error['found'], error['message']) == (
'slice_mut<u8>' if exclusive else 'slice<u8>', 'array<u8, 7>', 'type mismatch'), error
else:
assert 'repair_candidates' not in error, error
assert 'air_line' not in error and 'air_col' not in error, error
for command in ('lower', 'run', 'report', 'explore'):
assert json.loads(cli(command, path, code=1)) == error
if error['code'] == 'E7001':
assert json.loads(cli('fmt', path, code=1)) == error
library.write_text(path.read_text().replace('module probe', 'module lib.advice')
.replace('fn main(', 'fn user('))
package_error = json.loads(cli('check', '--manifest', manifest, code=1))
assert package_error == dict(error, file='lib.aji'), package_error
for command in ('lower', 'run', 'report', 'explore'):
assert json.loads(cli(command, '--manifest', manifest, code=1)) == package_error
# Generic/static calls use the resolved expected type, without guessing
# one from prose. Applying the explicit shared prefix is valid here.
for declarations, call in [
('fn f<T: Copy>(s: slice<T>) -> void effects [] {}', 'f::<u8>(a)'),
('fn f(s: slice<u8>) -> void effects [] {}\n'
'fn apply<F: fn(slice<u8>) -> void effects []>(a: [u8; 7]) '
'-> void effects [] { var b: [u8; 7] = a; F(b); }', 'apply::<fn f>(a)'),
]:
body = ('module probe\n' + declarations + '\nfn main() -> void effects [] '
'{ let a: [u8; 7] = [0u8; 7]; ' + call + '; }\n')
probe.write_text(body)
error = json.loads(cli('check', probe, code=1))
advice(error, 'array_slice_argument', ['ref'])
for command in ('lower', 'run', 'report', 'explore'):
assert json.loads(cli(command, probe, code=1)) == error
probe.write_text(body.replace('f::<u8>(a)', 'f::<u8>(ref a)').replace('F(b)', 'F(ref b)'))
cli('check', probe)
assert json.loads(cli('run', '--fuel', '100000', probe))['status'] == 'returned'
# A prefix is advice, not a promise of addressability. Value parameters
# need local storage before an explicit borrow can verify.
body = ('module probe\nfn f(s: slice<u8>) -> void effects [] {}\n'
'fn g(a: [u8; 7]) -> void effects [] { f(a); }\n'
'fn main() -> void effects [] {}\n')
probe.write_text(body)
advice(json.loads(cli('check', probe, code=1)), 'array_slice_argument', ['ref'])
probe.write_text(body.replace('f(a)', 'f(ref a)'))
error = json.loads(cli('check', probe, code=1))
assert error['code'] == 'E7006' and error['reason'] == 'invalid_place', error
assert 'repair_candidates' not in error, error
probe.write_text(body.replace('f(a)', 'var b: [u8; 7] = a; f(ref b)'))
cli('check', probe)
# Nearby mistakes and contexts without call-scoped loans receive no
# array/parameter advice; earlier name/move/arity errors stay earlier.
for body in [
'fn f(mut x u8) -> void effects [] {}',
'fn f(mut ref: u8) -> void effects [] {}',
'fn f(ref x: u8) -> void effects [] {}',
'fn f(mut.x: u8) -> void effects [] {}',
'fn f(s: slice<u8>) -> void effects [] {}\n'
'fn main() -> void effects [] { f(missing); }',
'fn f(s: slice<u8>) -> void effects [] {}\n'
'fn main() -> void effects [] { let a: [u8; 7] = [0u8; 7]; f(a, a); }',
'fn g(s: slice<u8>) -> slice<u8> from s effects [] '
'{ let a: [u8; 7] = [0u8; 7]; return a; }',
'struct S { a: [u8; 7] }\nfn f(s: slice<u8>) -> void effects [] {}\n'
'fn main() -> void effects [] { let s = S { a: [0u8; 7] }; f(s.a); }',
'fn f(s: slice<u8>) -> void effects [] {}\n'
'fn main() -> void effects [] { let a: [u8; 7] = [0u8; 7]; f(move a); }',
'fn f(s: slice<u8>) -> void effects [] {}\n'
'fn main() -> void effects [] { let a: [u8; 7] = [0u8; 7]; '
'scope workers { let t = task.spawn(workers, f, a); task.join(t); } }',
]:
if 'fn main(' not in body:
body += '\nfn main() -> void effects [] {}'
probe.write_text('module probe\n' + body + '\n')
error = json.loads(cli('check', probe, code=1))
assert 'repair_candidates' not in error, error
print(f'source repair advice: {checks} checks passed')