cli: preserve whole-array arguments for explicit array parameters
This commit is contained in:
1 parent
f733f7c7bb
commit
dde801c653
44 files changed
+397
-9
No files matched your search
@@ -27,6 +27,7 @@ jobs:
|
||||
- run: python3 tests/hosted/source_diagnostic_reasons.py
|
||||
- run: python3 tests/hosted/related_locations.py
|
||||
- run: python3 tests/hosted/source_lifetimes.py
|
||||
- run: python3 tests/hosted/source_array_arguments.py
|
||||
- run: python3 tests/hosted/examples.py --stress 200
|
||||
- run: python3 tests/hosted/source_static_functions.py
|
||||
- run: python3 tests/hosted/source_linear.py
|
||||
|
||||
@@ -23,6 +23,7 @@ python3 tests/hosted/source_format.py # formatter CLI, comments, idempotence and
|
||||
python3 tests/hosted/source_diagnostic_reasons.py # stable E7006 categories and CLI/package provenance
|
||||
python3 tests/hosted/related_locations.py # factual conflict/spawn positions, source mapping and package provenance
|
||||
python3 tests/hosted/source_lifetimes.py # AIR rejection twins and exact lifetime/join diagnostic positions
|
||||
python3 tests/hosted/source_array_arguments.py # array argument shape, cleanup, AIR and package parity
|
||||
python3 tests/hosted/examples.py --stress 200 # all examples/packages, wire bytes, partial I/O and source/AIR schedules
|
||||
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
|
||||
|
||||
@@ -152,3 +152,5 @@ RFC 0037 related positions (cl100k): Quick Reference 8,807 → 8,859 (+52), othe
|
||||
DD-019 unique diagnostic fields (cl100k): Quick Reference stays 8,859; other source docs 66,195 → 66,312 (+117), full source 75,054 → 75,171 (+0.16%). o200k groups are 8,895 / 66,517 / 75,412; Qwen2.5 9,135 / 67,933 / 77,068. AIR grows 47,328 → 47,445 (+117, +0.25%), 184,060 → 184,628 bytes; library/std.md is unchanged. Explicit payload names preserve the stable envelope and both guard/borrow identities. No language concept, syntax, code, verifier/runtime state or repair application is added; clients that previously read a capability payload as `kind` use `capability_kind`. No empirical MCC benefit is claimed.
|
||||
|
||||
Q-041 source scope names (DD-020, cl100k): Quick Reference 8,859 → 8,889 (+30), other source docs 66,312 → 66,484 (+172), full source 75,171 → 75,373 (+0.27%). o200k groups are 8,925 / 66,690 / 75,615; Qwen2.5 9,167 / 68,115 / 77,282. AIR remains 184,628 bytes / 47,445 cl100k tokens; library/std.md is unchanged. One existing lexical block identifier is explicitly excluded from ordinary value expressions, removing ineffective transfers and misleading repair hints. There is no new syntax, diagnostic code/reason, verifier/runtime state or feature. Former source aliases now reject; ordinary shadowing and AIR scope flow remain available. No empirical MCC benefit is claimed.
|
||||
|
||||
Q-023 whole-array arguments (DD-021, cl100k): Quick Reference 8,889 → 8,948 (+59), other source docs 66,484 → 66,669 (+185), full source 75,373 → 75,617 (+0.32%). o200k groups are 8,984 / 66,873 / 75,857; Qwen2.5 9,226 / 68,303 / 77,529. AIR stays 184,628 bytes / 47,445 cl100k tokens; library/std.md is unchanged. One rule follows an explicit ordinary-call signature so existing array-borrow parameters are callable; exact modes, lengths, lexical cleanup, named retained origins and task loans remain checked. No new syntax, diagnostic, feature or verifier/runtime state. Existing primitives suffice; no empirical MCC benefit is claimed.
|
||||
@@ -102,6 +102,7 @@ ref q = p; // shared borrow of a struct; q.a reads a field
|
||||
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.
|
||||
- **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`.
|
||||
|
||||
@@ -123,3 +123,11 @@ The invariant is one retained completion obligation per source scope, with every
|
||||
Valid: `scope s { let t = task.spawn(s, work); let s = 0u64; let n = task.join(move t); }`. Rejected: `scope s { let alias = move s; }` (E7006, existing reason `invalid_expression`, fields `name`/`type: scope`); plain aliases, yields, returns, aggregates and ordinary arguments are rejected likewise. Borrowing keeps `invalid_place`, assigning the immutable identifier keeps `invalid_assignment`, and a moved/non-scope spawn operand keeps E7005. The existing structured reason plus type identifies the category without reading prose; no additional reason is needed.
|
||||
|
||||
Compatibility: formerly accepted scope aliases, spawning through an alias or the apparently moved original, standalone scope names and block/scope tails now reject. Accepted shadowing, nested scope lookup, cleanup at fall-through/return/break/continue, and all AIR format-0 programs retain their meanings. Public source conformance covers accepted/rejected forms, specialized bodies and live children; CLI tests cover exact reasons/locations, packages and deterministic/hosted execution. Scheduler stress and per-instruction collection check cleanup. Source documentation growth is measured in docs/agent/README.md. The change improves explicitness and repairability without an empirical MCC claim; it does not finish P6-2.
|
||||
|
||||
## DD-021 — Whole-array arguments follow explicit parameter types
|
||||
|
||||
Q-023 is resolved in spec 15 §5: a temporary `ref`/`mut` argument preserves its array referent when the known parameter is an array borrow, including explicitly specialized calls. This is the existing small inference from one declared signature, with no overload search. It makes an already expressible parameter callable without hand-written AIR. Array bindings and slice parameters retain their slice behavior; bare byte strings retain their shorthand. Consequently, array-borrow origins and task loans require forwarding an existing array-borrow parameter; a local whole-array binding is still a slice.
|
||||
|
||||
Invariant: temporary children and ancestors remain live through the call, then end child first; no view escapes a temporary origin. Existing AIR type, aliasing, initialization, bounds, origin and task-loan verification remains authoritative. Runtime and deterministic interpreter rules are unchanged. Valid: `fn first(a: ref<[u64; 2]>) -> u64 effects [] { return a[0]; }` called with `first(ref data)` for a two-element array. A different length or explicit mode rejects E7005; overlapping exclusive/shared arguments reject E2101. Returning a view from an inline origin and lending an inline argument to a task retain E7006.
|
||||
|
||||
Compatibility: formerly rejected array-borrow calls become available; accepted source retains canonical AIR. No new syntax, AIR instruction/feature, diagnostic, verifier/runtime state, allocation or cleanup semantics. The frontend selects array versus slice using the parameter, then emits existing borrow/reborrow and end instructions. Source/AIR conformance and CLI checks cover projections, modes, specialization, packages and temporary cleanup. Source budget growth is recorded in docs/agent/README.md; AIR is unchanged. This improves explicitness and completes source access to an existing primitive without a measured MCC claim.
|
||||
@@ -179,6 +179,8 @@ A byte string lowers to one `local.zero`, then a borrow, index, store and end pe
|
||||
|
||||
In `.aji` a borrow of a whole array written as an argument (`f(ref a)`, `a: [u64; 4]`) is always lowered as a slice (`slice<u64>`), so a function declared with a parameter `ref<[u64; 4]>` cannot be called with `ref a` (`E7005`). Spec 15 §5 says that binding a borrow of a whole array (`ref r = a;`) gives a slice. It does not say what an argument borrow gives, so the frontend's choice is not specified. Options: the argument borrow follows the parameter type (array borrow for `ref<[T; N]>`, slice for `slice<T>`), which is a small amount of inference from a known signature; or keep slices only and state it in spec 15. Found while writing the interpreter memory test; not urgent.
|
||||
|
||||
**Resolved (DD-021, spec 15 §5):** an explicit temporary borrow preserves an array when the known ordinary-call parameter is an array borrow. Exact type/length/mode checks remain; slices, bindings, byte-string shorthand, retained origins and task loans keep their existing rules.
|
||||
|
||||
## Q-024 — Memory-model clarifications found by the independent oracle
|
||||
|
||||
The independent author of `tools/litmus/enumerate.py` (P5-1a) worked from spec 04 §20 only. It reported five points the text leaves implicit. For each, the author chose the RC11 reading, and all 20 corpus tests agree with the stated sets under it. Proposed clarifying text for spec 04 §20, for owner approval:
|
||||
|
||||
@@ -123,7 +123,6 @@ Lowering layers (P6A-3/4), each with accepted (golden AIR), rejected (`E7xxx`) a
|
||||
**Open, not blocking:**
|
||||
|
||||
- P6A-7 twins of the remaining conformance tests, added gradually;
|
||||
- Q-023;
|
||||
- harness: documentation accounting for partial reads; where the status fields are recorded.
|
||||
|
||||
## Tasks (full Phase 6)
|
||||
@@ -134,7 +133,7 @@ Lowering layers (P6A-3/4), each with accepted (golden AIR), rejected (`E7xxx`) a
|
||||
| P6-2 | doing | Lexer and parser with spans | P6-1 | `src/frontend/{lex,parse}.zig` | all `examples/` parse; syntax errors are registered diagnostics |
|
||||
| P6-3 | done (RFC 0021 Implemented) | Explicit package modules, direct imports and qualified nominal types | P6-2 | `src/frontend/modules.zig`, spec 15 §14 | deterministic graph/name resolution; source/AIR and CLI tests |
|
||||
| P6-4 | done (RFC 0022 Implemented) | Type checking and monomorphized generics with structural constraints (`Copy`, `Send`, `Share`, `Freeze`, `Local`) | P6-3 | `src/frontend/generics.zig`, spec 15 §15 | generic code instantiates deterministically; constraint violations diagnosed |
|
||||
| P6-5 | todo | Lowering to AIR: control flow, `?`, `defer` cleanup edges, borrow blocks, task scopes | P6-4 | `src/frontend/lower.zig` | lowered AIR verifies; lowering is a pure function (same input ⇒ same AIR bytes) |
|
||||
| P6-5 | doing | Lowering to AIR: control flow, `?`, `defer` cleanup edges, borrow blocks, task scopes | P6-4 | `src/frontend/lower.zig` | lowered AIR verifies; lowering is a pure function (same input ⇒ same AIR bytes) |
|
||||
| P6-6 | todo | Contracts: `requires`/`ensures`/invariants → contract table; status classification | P6-5 | frontend + verifier | each contract reported as PROVEN_STATICALLY / CHECKED_AT_RUNTIME / ASSUMED_UNSAFE / UNPROVEN |
|
||||
| P6-7 | doing | Source spans in diagnostics for verifier errors on lowered AIR | P6-5 | `src/diag.zig`, lowering | every conformance reject test has a source-level twin with the same code |
|
||||
| P6-8 | done | Formatter for implemented source syntax | P6-2 | `aji fmt`, spec 15 §11 | token/comment/declaration preservation; idempotence, identical AIR and CLI write/check tests |
|
||||
@@ -222,3 +221,9 @@ Twelve parser sites now finish parsing their bodies/operands before capturing th
|
||||
Three unit regressions failed before the correction and pass afterwards. They check exact ranges, AST containment, file/namespace provenance, comments, CRLF and nested closers. The existing CI formatter suite also validates nonempty ordered annotation ranges and reconstruction of canonical AIR across successful public lowerings. No normative document, bundle or evaluation input changes; P6-2 remains open for its remaining grammar work.
|
||||
|
||||
Validation: unit tests, formatting checks and full conformance pass, 1,225/1,225. Across 940 public sources, all check/lower outputs and exit codes remain unchanged, including 606 successful canonical lowerings. The formatter passes 4,139 checks; lifetime and related-position CLI suites pass 188/301 checks. Independent read-only Claude review found no remaining issues.
|
||||
|
||||
## P6-5 whole-array argument increment (2026-10-07)
|
||||
|
||||
Q-023 is resolved in spec 15 §5 / DD-021. Explicit temporary arguments preserve the array for a known ref/mut array parameter, including specialized and imported calls; other arguments and borrow bindings retain slice behavior. Shared reborrows and child-first temporary cleanup use existing AIR primitives. Exact types/lengths/modes, aliasing, bounds, named retained origins and task loans remain authoritative. Local whole-array bindings cannot serve as array-borrow origins or task loans; forwarding an existing array-borrow parameter can. No syntax, instruction, code, feature, verifier/runtime state or frozen evaluation input changes. Source bundle growth is recorded in docs/agent/README.md; AIR is unchanged. P6-5 remains open.
|
||||
|
||||
Validation: 32 new conformance cases pass with per-instruction collection and 200 scheduler seeds; full conformance is 1,257/1,257 and unit tests pass. CLI integration passes 85 checks, including deterministic/hosted and package provenance. Formatter checks 971 public files (963 parsed, eight existing syntax errors, 624 identical AIR outputs); source coverage is 121/121. Old/new CLI comparison over the 940 preceding public sources retains all diagnostic outputs and 606 successful canonical lowerings. Independent read-only Claude review passes.
|
||||
@@ -185,6 +185,8 @@ Lowering: structured control flow becomes blocks and terminators. A variable ass
|
||||
| `let (left, right) = s.split_at(k);` | `slice.split`: two disjoint borrows of `s`. Besides `atomic.compare_exchange` (§12), the only multi-result binding. There is no general tuple destructuring. |
|
||||
| `slice.copy(mut dst, ref src)` | primitive `slice.copy`; insufficient capacity traps. Recoverable byte copy is `std.bytes.copy` (spec 16 §2.4). |
|
||||
|
||||
**Whole-array arguments.** In an ordinary function call, `ref place` / `mut place` MUST preserve a whole-array referent when the known parameter is `ref<[T; N]>` / `mut<[T; N]>`; otherwise the existing whole-array-to-slice rule applies. Element type, length and explicit borrow mode MUST match (`E7005`); a slice MUST NOT be converted back to an array borrow. This also applies after explicit generic/static-function specialization and to array fields, elements and dereferenced array borrows (`ref (*a)`). Shared reborrowing of an exclusive parent follows the existing AIR rule. All temporary ancestors end after the call, child first. Borrow bindings still produce slices; bare byte-string arguments still produce `slice<u8>`. The named-origin requirement of §19 and the named-loan requirement of `task.spawn` (§7) remain mandatory.
|
||||
|
||||
**Writes.**
|
||||
|
||||
- `*r = v;` for a scalar or struct referent;
|
||||
|
||||
+17
-7
@@ -1159,7 +1159,7 @@ const Lowerer = struct {
|
||||
if (x.place.kind == .call) if (pathOf(x.place.kind.call.callee.*)) |p| if (std.mem.eql(u8, p, "buffer.view")) return l.bufferView(s, x.name, x.mutable, x.place);
|
||||
if (x.place.kind == .call) if (pathOf(x.place.kind.call.callee.*)) |p| if (std.mem.endsWith(u8, p, ".at"))
|
||||
return l.graphAccess(s, x.name, x.mutable, x.place);
|
||||
const p = try l.uncheckedPlace(x.place, x.mutable, x.unchecked, s.span);
|
||||
const p = try l.uncheckedPlace(x.place, x.mutable, x.unchecked, true, s.span);
|
||||
if (p.ends.len == 0) {
|
||||
// Borrowing a borrow binding: a reborrow, ended at scope end.
|
||||
const rb = try l.defBorrow(x.name, p.v.ty, try l.fmt("{s} %{s}", .{ if (x.mutable) "borrow.mut" else "borrow.ref", p.v.name }), p.v.name, s.span);
|
||||
@@ -2173,7 +2173,10 @@ const Lowerer = struct {
|
||||
fn argument(l: *Lowerer, a: ast.Expr, want: ?Ty, temps: *std.ArrayList([]const u8)) Error!Value {
|
||||
switch (a.kind) {
|
||||
.borrow => |x| {
|
||||
const p = try l.uncheckedPlace(x.place.*, x.mutable, x.unchecked, a.span);
|
||||
// Only a known array-borrow parameter preserves the array
|
||||
// (spec 15 §5). Bindings and all other arguments keep slices.
|
||||
const want_slice = if (want) |t| !(t == .ref or t == .mut) or t.inner().? != .array else true;
|
||||
const p = try l.uncheckedPlace(x.place.*, x.mutable, x.unchecked, want_slice, a.span);
|
||||
if (p.ends.len == 0) {
|
||||
const rb = try l.defBorrow("b", p.v.ty, try l.fmt("{s} %{s}", .{ if (x.mutable) "borrow.mut" else "borrow.ref", p.v.name }), p.v.name, a.span);
|
||||
try temps.append(l.arena, rb.name);
|
||||
@@ -2216,12 +2219,12 @@ const Lowerer = struct {
|
||||
/// `ref unchecked s[i]`: `borrow.index.unchecked` (spec 13 §6). Only an
|
||||
/// element place can be unchecked; the boundary (`effects [unsafe]`) is
|
||||
/// 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);
|
||||
fn uncheckedPlace(l: *Lowerer, place: ast.Expr, mutable: bool, unchecked: bool, want_slice: bool, span: Span) Error!Placed {
|
||||
if (!unchecked) return l.borrowShape(try l.placeRaw(place, mutable, span), mutable, want_slice, span);
|
||||
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);
|
||||
return l.borrowShape(try l.placeRaw(place, mutable, span), mutable, want_slice, span);
|
||||
}
|
||||
|
||||
fn rootBinding(l: *Lowerer, e: ast.Expr) ?*Binding {
|
||||
@@ -2239,10 +2242,17 @@ const Lowerer = struct {
|
||||
/// array becomes a slice. A place that is itself a borrow binding is
|
||||
/// returned as is (`ends` empty).
|
||||
fn placeBorrow(l: *Lowerer, place: ast.Expr, mutable: bool, want_slice: bool, span: Span) Error!Placed {
|
||||
var p = try l.placeRaw(place, mutable, span);
|
||||
const p = try l.placeRaw(place, mutable, span);
|
||||
return if (want_slice) l.borrowShape(p, mutable, true, span) else p;
|
||||
}
|
||||
|
||||
/// Explicit argument/binding modes apply independently of array shape.
|
||||
/// In particular, `ref` through `mut<[T; N]>` still reborrows shared.
|
||||
fn borrowShape(l: *Lowerer, raw: Placed, mutable: bool, want_slice: bool, span: Span) Error!Placed {
|
||||
var p = raw;
|
||||
// `ref place` reached through a `mut` borrow (`ref s.buf` with
|
||||
// `s: mut<S>`) is a shared reborrow of it (spec 07a `borrow.ref`).
|
||||
if (want_slice and !mutable and (p.v.ty == .mut or p.v.ty == .slice_mut)) {
|
||||
if (!mutable and (p.v.ty == .mut or p.v.ty == .slice_mut)) {
|
||||
const t = if (p.v.ty == .mut) try l.wrap(.ref, p.v.ty.inner().?) else try l.wrap(.slice, p.v.ty.inner().?);
|
||||
const r = try l.defBorrow("r", t, try l.fmt("borrow.ref %{s}", .{p.v.name}), p.v.name, span);
|
||||
p = .{ .v = r, .ends = try l.concat(p.ends, r.name) };
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
module test.arrays
|
||||
fn first<T: Copy>(a: ref<[T; 2]>) -> T effects [] { return a[0]; }
|
||||
fn set(a: mut<[u64; 2]>) -> void effects [] { a[0] = 42; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7005
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §5
|
||||
module test.array_arguments
|
||||
fn first(a: ref<[u64; 2]>) -> ref<u64> from a effects [] { ref item = a[0]; return item; }
|
||||
fn main() -> u64 effects [] { let a = [42u64; 2]; ref r = a; ref item = first(r); return *item; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7005
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §5
|
||||
module test.array_arguments
|
||||
fn first(a: ref<[u64; 2]>) -> u64 effects [] { return a[0]; }
|
||||
fn main() -> u64 effects [] { let a = [1u64; 2]; ref s = a; return first(ref s); }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7005
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §5
|
||||
module test.array_arguments
|
||||
fn first(a: ref<[u64; 2]>) -> u64 effects [] { return a[0]; }
|
||||
fn main() -> u64 effects [task.spawn] { let a = [42u64; 2]; ref r = a; scope s { let t = task.spawn(s, first, r); return task.join(move t); } }
|
||||
@@ -0,0 +1,7 @@
|
||||
// expect: run
|
||||
// trap: T0008
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §5
|
||||
module test.array_arguments
|
||||
fn read(a: ref<[u64; 2]>) -> u64 effects [] { return a[2]; }
|
||||
fn main() -> u64 effects [] { let a = [42u64; 2]; return read(ref a); }
|
||||
@@ -0,0 +1,7 @@
|
||||
// expect: run
|
||||
// result: 104
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §5
|
||||
module test.array_arguments
|
||||
fn first(a: ref<[u8; 2]>) -> u8 effects [] { return a[0]; }
|
||||
fn main() -> u8 effects [] { return first(ref b"hi"); }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7005
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §5
|
||||
module test.array_arguments
|
||||
fn first(a: ref<[u8; 2]>) -> u8 effects [] { return a[0]; }
|
||||
fn main() -> u8 effects [] { return first(b"hi"); }
|
||||
@@ -0,0 +1,7 @@
|
||||
// expect: reject E2101 E2101
|
||||
// The conflicting reborrow and its use at the call each reject.
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §5
|
||||
module test.array_arguments
|
||||
fn read(a: mut<[u64; 2]>, b: ref<[u64; 2]>) -> u64 effects [] { return b[0]; }
|
||||
fn main() -> u64 effects [] { var a: [u64; 2] = zero; return read(mut a, ref a); }
|
||||
@@ -0,0 +1,42 @@
|
||||
; expect: run
|
||||
; result: 42
|
||||
; phase: 1
|
||||
; spec: docs/spec/07a-air-instructions.md; docs/spec/15-source-language.md §5
|
||||
; Independent format-0 baseline: temporary borrows end before the next access.
|
||||
module test.array_arguments
|
||||
air 0
|
||||
lang 0.1
|
||||
features [arrays, effects, ownership]
|
||||
|
||||
fn @first(%a: ref<array<u64, 2>>) -> u64
|
||||
effects []
|
||||
entry:
|
||||
%index = const.usize 0
|
||||
%element = borrow.index %a, %index
|
||||
%value = load %element
|
||||
borrow.end %element
|
||||
ret %value
|
||||
|
||||
fn @set(%a: mut<array<u64, 2>>) -> void
|
||||
effects []
|
||||
entry:
|
||||
%answer = const.u64 42
|
||||
%index = const.usize 0
|
||||
%element = borrow.index %a, %index
|
||||
store %element, %answer
|
||||
borrow.end %element
|
||||
ret
|
||||
|
||||
fn @main() -> u64
|
||||
effects []
|
||||
entry:
|
||||
%data = local.alloc array<u64, 2>
|
||||
local.zero %data
|
||||
%writer = borrow.mut %data
|
||||
call @set(%writer)
|
||||
borrow.end %writer
|
||||
%reader = borrow.ref %data
|
||||
%answer = call @first(%reader)
|
||||
borrow.end %reader
|
||||
local.zero %data
|
||||
ret %answer
|
||||
@@ -0,0 +1,9 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// equivalent: source/array_arguments/direct.air
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §5
|
||||
module test.array_arguments
|
||||
fn first(a: ref<[u64; 2]>) -> u64 effects [] { return a[0]; }
|
||||
fn set(a: mut<[u64; 2]>) -> void effects [] { a[0] = 42; }
|
||||
fn main() -> u64 effects [] { var a: [u64; 2] = [1u64; 2]; set(mut a); let n = first(ref a); a[0] = 0; return n; }
|
||||
@@ -0,0 +1,7 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §5
|
||||
module test.array_arguments
|
||||
fn first<T: Copy>(a: ref<[T; 2]>) -> T effects [] { return a[0]; }
|
||||
fn main() -> u64 effects [] { let a = [42u64; 2]; return first::<u64>(ref a); }
|
||||
@@ -0,0 +1,9 @@
|
||||
// expect: run
|
||||
// result: 84
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §5
|
||||
module test.array_arguments
|
||||
fn first(a: ref<[u64; 2]>) -> u64 effects [] { return a[0]; }
|
||||
fn use<T, F: fn(T) -> u64 effects []>(a: T) -> u64 effects [] { return F(a); }
|
||||
fn slice_first(a: slice<u64>) -> u64 effects [] { return a[0]; }
|
||||
fn main() -> u64 effects [] { let a = [42u64; 2]; return use::<ref<[u64; 2]>, fn first>(ref a) + use::<slice<u64>, fn slice_first>(ref a); }
|
||||
@@ -0,0 +1,8 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §5
|
||||
// module: test.arrays=source/array_arguments/arrays.aji.inc
|
||||
module test.array_arguments
|
||||
import test.arrays;
|
||||
fn main() -> u64 effects [] { var a: [u64; 2] = [1u64; 2]; test.arrays.set(mut a); return test.arrays.first::<u64>(ref a); }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7006
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §5
|
||||
module test.array_arguments
|
||||
fn first(a: ref<[u64; 2]>) -> ref<u64> from a effects [] { ref item = a[0]; return item; }
|
||||
fn main() -> u64 effects [] { let a = [42u64; 2]; ref item = first(ref a); return *item; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7006
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §5
|
||||
module test.array_arguments
|
||||
fn first(a: ref<[u64; 2]>) -> u64 effects [] { return a[0]; }
|
||||
fn main() -> u64 effects [task.spawn] { let a = [42u64; 2]; scope s { let t = task.spawn(s, first, ref a); return task.join(move t); } }
|
||||
@@ -0,0 +1,8 @@
|
||||
// expect: reject E2101 E2101
|
||||
// The conflicting reborrow and its use at the call each reject.
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §5
|
||||
module test.array_arguments
|
||||
fn set(a: mut<[u64; 2]>) -> void effects [] { a[0] = 42; }
|
||||
fn forward(a: mut<[u64; 2]>) -> u64 effects [] { ref item = a[0]; set(mut a); return *item; }
|
||||
fn main() -> u64 effects [] { var a: [u64; 2] = zero; return forward(mut a); }
|
||||
@@ -0,0 +1,8 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §5
|
||||
module test.array_arguments
|
||||
fn first(a: ref<[u64; 2]>) -> ref<u64> from a effects [] { ref item = a[0]; return item; }
|
||||
fn forward(a: ref<[u64; 2]>) -> u64 effects [] { ref item = first(a); return *item; }
|
||||
fn main() -> u64 effects [] { let a = [42u64; 2]; return forward(ref a); }
|
||||
@@ -0,0 +1,9 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §5
|
||||
// schedules: 8
|
||||
module test.array_arguments
|
||||
fn first(a: ref<[u64; 2]>) -> u64 effects [] { return a[0]; }
|
||||
fn forward(a: ref<[u64; 2]>) -> u64 effects [task.spawn] { scope s { let t = task.spawn(s, first, a); return task.join(move t); } }
|
||||
fn main() -> u64 effects [task.spawn] { let a = [42u64; 2]; return forward(ref a); }
|
||||
@@ -0,0 +1,9 @@
|
||||
// expect: run
|
||||
// result: 84
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §5
|
||||
module test.array_arguments
|
||||
struct Data { a: [u64; 2] }
|
||||
fn first(a: ref<[u64; 2]>) -> u64 effects [] { return a[0]; }
|
||||
fn set(a: mut<[u64; 2]>) -> void effects [] { a[0] = 42; }
|
||||
fn main() -> u64 effects [] { var d: Data = Data { a: [1u64; 2] }; set(mut d.a); let x = first(ref d.a); var rows: [[u64; 2]; 2] = [[1u64; 2]; 2]; set(mut rows[1]); return x + first(ref rows[1]); }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7005
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §5
|
||||
module test.array_arguments
|
||||
fn first(a: ref<[u64; 2]>) -> u64 effects [] { return a[0]; }
|
||||
fn main() -> u64 effects [] { let a = [1u64; 2]; return first(ref a[0..2]); }
|
||||
@@ -0,0 +1,9 @@
|
||||
// expect: run
|
||||
// result: 43
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §5
|
||||
module test.array_arguments
|
||||
fn first(a: ref<[u64; 2]>) -> u64 effects [] { return a[0]; }
|
||||
fn set(a: mut<[u64; 2]>) -> void effects [] { a[0] = 42; }
|
||||
fn forward(a: mut<[u64; 2]>) -> u64 effects [] { let n = first(ref a); set(mut a); return n + first(ref (*a)); }
|
||||
fn main() -> u64 effects [] { var a: [u64; 2] = [1u64; 2]; return forward(mut a); }
|
||||
@@ -0,0 +1,7 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §5
|
||||
module test.array_arguments
|
||||
fn first(a: slice<u64>, unused: mut<[u64; 2]>) -> ref<u64> from a effects [] { ref item = a[0]; return item; }
|
||||
fn main() -> u64 effects [] { let a = [42u64; 2]; var b: [u64; 2] = zero; ref s = a; ref item = first(s, mut b); b[0] = 1; return *item; }
|
||||
@@ -0,0 +1,9 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §5
|
||||
module test.array_arguments
|
||||
struct Data { a: [u64; 2] }
|
||||
fn first(a: ref<[u64; 2]>) -> u64 effects [] { return a[0]; }
|
||||
fn forward(d: mut<Data>) -> u64 effects [] { let n = first(ref d.a); d.a[0] = 0; return n; }
|
||||
fn main() -> u64 effects [] { var d: Data = Data { a: [42u64; 2] }; return forward(mut d); }
|
||||
@@ -0,0 +1,8 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §5
|
||||
module test.array_arguments
|
||||
fn first(a: ref<[u64; 2]>) -> u64 effects [] { return a[0]; }
|
||||
fn forward(a: ref<[u64; 2]>) -> u64 effects [] { return first(ref a) + first(ref (*a)); }
|
||||
fn main() -> u64 effects [] { let a = [21u64; 2]; return forward(ref a); }
|
||||
@@ -0,0 +1,7 @@
|
||||
// expect: reject E7005
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §5
|
||||
module test.array_arguments
|
||||
fn set(a: mut<[u64; 2]>) -> void effects [] { a[0] = 42; }
|
||||
fn forward(a: ref<[u64; 2]>) -> void effects [] { set(mut a); }
|
||||
fn main() -> void effects [] { var a: [u64; 2] = zero; forward(ref a); }
|
||||
@@ -0,0 +1,9 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §5
|
||||
module test.array_arguments
|
||||
fn first(a: ref<[u64; 2]>) -> u64 effects [] { return a[0]; }
|
||||
fn total(a: slice<u64>) -> u64 effects [] { return a[0] + a[1]; }
|
||||
fn set(a: slice_mut<u64>) -> void effects [] { a[1] = 21; }
|
||||
fn main() -> u64 effects [] { var a: [u64; 2] = [21u64; 2]; set(mut a); ref s = a; return total(s); }
|
||||
@@ -0,0 +1,8 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §5
|
||||
module test.array_arguments
|
||||
fn first(a: ref<[u64; 2]>) -> u64 effects [] { return a[0]; }
|
||||
fn apply<F: fn(ref<[u64; 2]>) -> u64 effects []>(a: ref<[u64; 2]>) -> u64 effects [] { return F(ref a); }
|
||||
fn main() -> u64 effects [] { let a = [42u64; 2]; return apply::<fn first>(ref a); }
|
||||
@@ -0,0 +1,7 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §5
|
||||
module test.array_arguments
|
||||
fn set(a: mut<[u64; 2]>) -> void effects [] { a[0] = 42; }
|
||||
fn main() -> u64 effects [unsafe] { var rows: [[u64; 2]; 2] = zero; set(mut unchecked rows[1]); return rows[1][0]; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E6001
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §5
|
||||
module test.array_arguments
|
||||
fn set(a: mut<[u64; 2]>) -> void effects [] { a[0] = 42; }
|
||||
fn main() -> void effects [] { var rows: [[u64; 2]; 2] = zero; set(mut unchecked rows[1]); }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7005
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §5
|
||||
module test.array_arguments
|
||||
fn first(a: ref<[u64; 2]>) -> u64 effects [] { return a[0]; }
|
||||
fn main() -> u64 effects [] { let a = [1u8; 2]; return first(ref a); }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7005
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §5
|
||||
module test.array_arguments
|
||||
fn first(a: ref<[u64; 2]>) -> u64 effects [] { return a[0]; }
|
||||
fn main() -> u64 effects [] { let a = [1u64; 3]; return first(ref a); }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7005
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §5
|
||||
module test.array_arguments
|
||||
fn set(a: mut<[u64; 2]>) -> void effects [] { a[0] = 42; }
|
||||
fn main() -> void effects [] { var a: [u64; 2] = zero; set(ref a); }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7005
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §5
|
||||
module test.array_arguments
|
||||
fn first(a: ref<[u64; 2]>) -> u64 effects [] { return a[0]; }
|
||||
fn main() -> u64 effects [] { var a: [u64; 2] = zero; return first(mut a); }
|
||||
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Whole-array arguments: CLI/AIR parity, temporary cleanup and package provenance."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
AJI = REPO / 'zig-out/bin/aji'
|
||||
CORPUS = REPO / 'tests/conformance/source/array_arguments'
|
||||
checks = 0
|
||||
|
||||
|
||||
def cli(*args, code=0):
|
||||
global checks
|
||||
result = subprocess.run([str(AJI), *map(str, args)], capture_output=True, text=True)
|
||||
assert result.returncode == code, (args, result.returncode, result.stdout, result.stderr)
|
||||
checks += 1
|
||||
return result.stdout
|
||||
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix='aji-array-arguments-') as directory:
|
||||
root = Path(directory)
|
||||
raw = root / 'lowered.air'
|
||||
for name, value in {'direct': 42, 'projections': 84, 'reborrow': 43,
|
||||
'shared_forward': 42, 'generic': 42, 'static': 42,
|
||||
'bytes_explicit': 104, 'retained_other_temporary': 42,
|
||||
'unchecked': 42, 'slices': 42}.items():
|
||||
source = CORPUS / f'{name}.aji'
|
||||
cli('check', source)
|
||||
air = cli('lower', source)
|
||||
assert cli('lower', source) == air
|
||||
raw.write_text(air)
|
||||
cli('check', raw)
|
||||
result = json.loads(cli('run', '--fuel', '100000', source))
|
||||
assert result['value'] == value, (name, result)
|
||||
assert json.loads(cli('run', '--fuel', '100000', raw)) == result
|
||||
hosted = root / 'hosted.json'
|
||||
assert cli('run', '--profile', 'hosted', '--fuel', '100000',
|
||||
'--result-file', hosted, source) == ''
|
||||
assert json.loads(hosted.read_text())['value'] == value
|
||||
if name == 'slices':
|
||||
assert 'slice.make' in air
|
||||
else:
|
||||
# The unrelated retained origin is intentionally still a slice.
|
||||
main = air.split('fn @main(', 1)[1]
|
||||
if name != 'retained_other_temporary':
|
||||
assert 'slice.make' not in main, (name, main)
|
||||
|
||||
# Real package linking, including a specialized imported signature.
|
||||
entry, library, manifest = (root / name for name in ('main.aji', 'arrays.aji', 'aji.toml'))
|
||||
entry.write_text((CORPUS / 'imported.aji').read_text())
|
||||
library.write_text((CORPUS / 'arrays.aji.inc').read_text())
|
||||
manifest.write_text('[package]\nname = "arrays"\nversion = "1"\nentry = "main.aji"\n'
|
||||
'[modules]\ntest.arrays = "arrays.aji"\n')
|
||||
cli('check', '--manifest', manifest)
|
||||
assert json.loads(cli('run', '--fuel', '100000', '--manifest', manifest))['value'] == 42
|
||||
air = cli('lower', '--manifest', manifest)
|
||||
assert cli('lower', '--manifest', manifest) == air
|
||||
raw.write_text(air)
|
||||
cli('check', raw)
|
||||
assert json.loads(cli('run', '--fuel', '100000', raw))['value'] == 42
|
||||
cli('report', '--manifest', manifest)
|
||||
cli('explore', '--max-runs', '8', '--manifest', manifest)
|
||||
|
||||
# Type mismatch comes from the imported body with its original source position.
|
||||
library.write_text(library.read_text().replace('return a[0];', 'return first::<T>(ref a[0]);'))
|
||||
error = json.loads(cli('check', '--manifest', manifest, code=1))
|
||||
assert error['code'] == 'E7005', error
|
||||
assert error['file'] == 'arrays.aji' and error['line'] == 2, error
|
||||
assert error['expected'] == 'ref<array<u64, 2>>' and error['found'] == 'ref<u64>', error
|
||||
for command in ('run', 'report', 'explore'):
|
||||
assert json.loads(cli(command, '--manifest', manifest, code=1)) == error
|
||||
|
||||
# Aliasing failures retain the AIR verifier code and a useful argument position.
|
||||
source = CORPUS / 'conflict.aji'
|
||||
errors = [json.loads(line) for line in cli('check', source, code=1).splitlines()]
|
||||
assert len(errors) == 2 and all(e['code'] == 'E2101' for e in errors), errors
|
||||
assert all(e['file'] == str(source) and e['line'] == 7 and e['col'] > 1 for e in errors), errors
|
||||
raw.write_text(cli('lower', source))
|
||||
air_errors = [json.loads(line) for line in cli('check', raw, code=1).splitlines()]
|
||||
# Source deduplication collapses the two conflicting call operands at
|
||||
# the same source position; raw AIR retains both factual identities.
|
||||
assert len(air_errors) == 3 and all(e['code'] == 'E2101' for e in air_errors), air_errors
|
||||
|
||||
print(f'array argument CLI integration passed ({checks} checks)')
|
||||
@@ -23,6 +23,7 @@ CHECKLIST = [
|
||||
("block boundaries", "bare block before dereference", r"\}\s*\*", True),
|
||||
("borrow returns", "explicit return origin", r"-> (?:ref|mut|slice|slice_mut)<[^>]+> from ", True),
|
||||
("borrow returns", "returned view binding", r"(?:ref|mut) \w+ = (?:first|view|allocate)(?:::<[^>]+>)?\(", True),
|
||||
("borrows", "fixed-array borrow parameter", r": (?:ref|mut)<\[[^;\n]+; \d+\]>", True),
|
||||
("hashmap", "explicit general key policy and owning insert", r"std\.hashmap\.(insert|contains|get)::<", True),
|
||||
("hashmap", "explicit general growth/extraction/drain", r"std\.hashmap\.(reserve|remove|pop|free)::<", True),
|
||||
("hashset", "explicit membership and duplicate owner return", r"std\.hashset\.(insert|contains)::<", True),
|
||||
|
||||
Reference in new issue
Block a user