Skip to content

[]mut T stages 2–3: local bindings, returns, and split_at_mut #604

In progress

Description

@ehartford

Summary

Stage 1 is shipped: mutable collections coerce to []mut T parameters with
call-local exclusivity, and #379's modeled buffer-output wrappers build on it.
This issue now tracks stages 2–3: local bindings, return-position views, and
public split_at_mut APIs.

Current state (revalidated 2026-07-15)

Working:

  • A mutable array/Vec passed to a []mut T parameter is mutated in place.
  • The call checker rejects overlapping read/write arguments while that
    exclusive parameter borrow is active.
  • c_import buf_out overlays for memset/explicit_bzero use the shipped path.

Still rejected:

let s: []mut i32 = a[..]

The compiler intentionally reports that []mut T is parameter-only in this
release and cites #604.

A stage-2 prototype proved the basic view and mutation mechanics, but also
proved why it could not ship: the borrow checker did not keep the exclusive
view live across the binding. Mutation through the source and creation of a
second overlapping mutable slice were both accepted. Local slices therefore
need real place-origin and NLL tracking, not only a type-production tweak.

The maintainer already resolved the earlier spec tension: return-position
slices remain part of the model and are checked by §21.1 Rule 6.

Current split_at_mut surfaces still use internal VecRange-style views; the
specification's ([]mut T, []mut T) example and direct indexed assignment are
not available through the promised public type.

Remaining stages

Stage 2 — local bindings

  • Produce []mut T only from an eligible mutable place.
  • Track its source place and covered range across the binding's NLL lifetime.
  • Reject source reads/writes and overlapping mutable/shared views while live.
  • Release exclusivity at the last use.

Stage 3 — returned views

  • Allow []mut T return positions under §21.1 Rule 6 origin checking.
  • Reject locals, temporaries, and other origins that cannot outlive the return.
  • Preserve source/range provenance through calls.

API convergence

  • Make slice/array/Vec split_at_mut expose disjoint []mut T pairs as specified.
  • Keep the internal VecRange representation behind the public semantic type.

Acceptance criteria

  • Stage 1 parameter coercion and call-local exclusivity remain green.
  • Local mutable slices reject every overlapping source/view access while live
    and allow it after last use.
  • Returned mutable views obey Rule 6 with positive and negative cases.
  • split_at_mut supports the §4.8a indexed-mutation example.
  • No mutable-aliasing hole is opened by type production alone.
  • Full build, fixpoint, ownership audit, and test gates pass.

Traceability

  • Specification §4.8a
  • Specification §21.1 Rule 6

Activity

  1. ehartford commented on Jun 19, 2026

    @ehartford
    ContributorAuthor

    Correction: reconcile the contradiction before designing (intent was not settled)

    My initial analysis proved the mechanics in code but inferred design intent from spec text, and left one fact unreconciled: split_at_mut returns VecRange, not []mut T. That premise is load-bearing — it decides the shape of the fix — so I settled it from code. The earlier "emit d1=1 from slice-creation" recommendation is withdrawn pending the decision below.

    Code evidence

    1. []mut T has no producer and zero usages. grep "[]mut" across lib/std/, examples/, test/ returns 0 files. The only TY_SLICE sites that set the mutability flag (d1) read it from a written type annotation (SemaCheck.w:434, 12674, 13253 → get_data1(typeNode)); every value-producing site — slice/range/subscript expressions — hardcodes d1=0 (SemaCheck.w:8742, MirLower.w:1603). So []mut T is a type you can write but the compiler never constructs, and the compat check (Sema.w:4427) then makes any []mut T parameter unsatisfiable.

    2. VecRange is the working mutable model. VecRange[T] = { data_ptr, offset, len } (CodegenDispatch.w:8057), produced by .range() / split_at_mut, with get/set/len/split_at_mut intrinsics, working on both Vec and fixed arrays: var xs=[10,20,30,40]; xs[1..4].split_at_mut(1); r.set(0,99) mutates successfully. Mutation never flows through []mut T.

    3. The spec's own split_at_mut example comments // left: []mut T but the implementation returns VecRange. So the spec↔impl divergence is real and centered exactly on the contested point.

    Conclusion + the decision (maintainer's call — language/spec, not mine)

    The code says VecRange is the de-facto mutable currency and §4.8's []mut T promise is stale. Two ways to make it consistent:

    • (A) Bless VecRange (matches the implementation). Update §4.8/§4.8a so the mutable-slice currency is VecRange[T] (and split_at_mut officially returns it). Then buf_out is VecRange-shaped: the generated memset/explicit_bzero wrapper takes VecRange[u8] and passes (data_ptr + offset, len) to C. No borrow-checker change; uses the existing, working mutable model. This is the smaller, lower-risk path and is consistent with how all current mutable code is written.
    • (B) Realize []mut T (matches the spec text). Make value-producing slice expressions emit d1=1 under a mutable source + expected []mut T, and wire §21.1 exclusivity for it (the risky part I flagged). Larger, and it introduces a second mutable-view mechanism alongside VecRange unless split_at_mut is also migrated to return []mut T — i.e. it implies reworking the existing mutable model, not just adding a coercion.

    Recommendation: (A). It's what the language actually does today, it's lower risk (no borrow-checker surgery), and VecRange already carries the (ptr, len) shape buf_out needs.

    Stopping here. No []mut T / VecRange / spec semantics changed. Once you pick (A) or (B), I'll land the chosen mutable-slice work as its own unit with adversarial exclusivity/aliasing tests, verify, and only then add the buf_out overlay entries to #379.

  2. ehartford commented on Jun 19, 2026

    @ehartford
    ContributorAuthor

    Correction #2: Option A (VecRange-shaped buf_out) is not viable — and []mut T is NOT stale

    Attempting to implement Option A surfaced facts that reverse my prior "VecRange is the model, §4.8 is stale" conclusion. Reporting before any code/spec change.

    Option A is impossible

    • VecRange is unspellable as a type. fn memset(s: VecRange[u8], ...) → error: unknown type: VecRange. It is compiler-internal (self.syms.vecrange), not a user-facing type name. No function anywhere takes a VecRange parameter (grep across lib/std, src, test, examples: zero).
    • A mutable view cannot cross a function boundary today. Checked every mechanism: mut param: Vec[u8] moves the Vec (use of moved value after the call — ownership transfer, not a borrow); mut self is method-only and type-specific; VecRange is in-scope only. None expresses "mutate the caller's byte buffer in place via a free wrapper function."

    Refined reconciliation (corrects the earlier verdict)

    VecRange and []mut T are not competing models — they serve different roles:

    • VecRange = in-scope mutable view (local, via with/range/split_at_mut). Not passable to functions.
    • []mut T = the spec's intended cross-function mutable-slice parameter (§4.8: "the exclusive borrow ends when the callee returns" — that sentence is specifically about parameter passing).

    So the split_at_mut → VecRange fact does not prove §4.8 is stale. []mut T is the designed-but-unimplemented mechanism for exactly the function-boundary case buf_out needs. My earlier "fix the §4.8 promise / it's stale" was wrong: the promise reflects real, unmet intent — a genuine compiler gap, not decoration. I withdraw the recommendation to edit §4.8.

    Consequence for #379 buf_out

    buf_out's clean surface (memset(buf, c) mutating a caller buffer) genuinely requires []mut T as a real cross-function mutable slice. That is the language-design call the maintainer has reserved to decide on its own merits — it is not a side effect of #379, and there is no viable in-#379 surface that avoids it (VecRange can't be a param; mut Vec moves; raw stays raw).

    Therefore buf_out cannot ship within #379 without that separate []mut T decision. Recommended recording: memset/explicit_bzero stay raw (already the case — no regression); #379 buf_out is blocked on the []mut T mechanism, tracked here. cstr_in + nullable_ptr + buf_in are shipped and complete.

    No code or spec changed. Awaiting your call on how to record buf_out (blocked-on-[]mut T vs out-of-scope), and the separate []mut T decision in your own time.

  3. ehartford commented on Jun 19, 2026

    @ehartford
    ContributorAuthor

    Correction #3 (definitive, fully tested): buf_out is NOT impossible

    My "no mutable buffer can cross a function boundary" rested on the single free-mut Vec move test plus an assumed, never-run Arena in-place behavior. Run, the Arena-style free mut param also moves. In-place mutation across a call is a mut self (method) property, not a free-mut param one. Full tested matrix:

    Mechanism Result Evidence
    free mut param (Vec, struct) moves use of moved value after call
    mut self method in-place, usable after c.bump()×2 → 7; mut self method memset via &raw mut self.data[0] → 65
    move-in / return f(Vec[u8]) -> Vec[u8] works xs = memset_vec(xs, 65) → 65, 65
    []mut T free param unimplemented (no producer) —
    VecRange param unspellable (unknown type) —
    call-site mut xs / &mut xs parse error —

    Reconciliation

    • The §4.8 []mut T parameter promise is genuinely unmet (a real gap) — not stale, but also not the only way to cross a boundary mutably.
    • A Vec-backed buf_out ships today via move-in/return or a mut self method. The clean in-place free-function slice surface (memset(slice, c)) still needs []mut T.

    The (narrowed) decision

    • (A) Ship a Vec-backed buf_out now — generate memset/explicit_bzero as move-in/return (fn memset(buf: Vec[u8], c) -> Vec[u8]). Works today, safe. Cost: Vec-only (no arrays/sub-ranges), move-in/move-out ergonomics (caller rebinds), and it's a real c_import modeling choice (remodeling a C in-place op as consume→return).
    • (B) Hold buf_out for []mut T — the clean in-place free-function surface. memset stays raw meanwhile (no regression). []mut T is the separate language call.

    No code/spec changed. The "impossible" verdict is withdrawn; buf_out is a surface-choice decision, not a hard blocker.

  4. ehartford commented on Jun 19, 2026

    @ehartford
    ContributorAuthor

    Final corner closed: matrix is exhaustive; buf_out held (downstream of []mut T)

    Tested the one remaining corner — a free-function mutable-reference parameter:

    • fn f(buf: &mut Vec[u8]) → rejected (&mut is not a valid parameter type; consistent with "no safe &mut T").
    • &raw mut buf[0] through a shared &Vec param → rejected (no mutable raw pointer from a shared ref).

    So there is no free-function mutable-borrow parameter; in-place mutation across a call is method-only (mut self). The mechanism matrix is now exhaustive.

    Decision: HOLD buf_out (this is not the deferral pattern)

    Every today-viable buf_out surface is worse than the raw fallback for an in-place C buffer op:

    • move-in/return (fn memset(buf: Vec[u8]) -> Vec[u8]) misrepresents memset (a mutation, not consume→return), forces caller rebind, Vec-only.
    • mut self method needs a synthetic receiver type and turns a free C function into a method.

    The overlay exists to provide better surfaces; auto-generating either would degrade the API. memset/explicit_bzero stay raw (callable under unsafe today — no regression).

    buf_out is correctly downstream of the []mut T language decision, not blocked-in-limbo. This issue (#604) is the tracker for the cross-function mutable-slice mechanism ([]mut T realized as a real parameter, per §4.8's intent). It has value beyond buf_out; when it lands, buf_out falls out for free with the clean memset(buf, c) in-place surface. Until then, raw is the right surface.

    The "impossible" verdict is fully withdrawn; this is a surface-quality choice, settled.

  5. ehartford commented on Jul 2, 2026

    @ehartford
    ContributorAuthor

    Ruling: Option A, staged — realize []mut T per spec §4.8, parameter-position first.

    Judged against the mission and the spec taken as a whole:

    • §4.8 already promises mutable slices. Blessing VecRange would regress the surface to an implementation artifact — and the artifact was verified to snapshot (data, offset, len) with no runtime validation, i.e. the same hazard class as a slice. Option B buys nothing.
    • §2.5's runtime-fact model deliberately covers owners (reset-on-move) and handles (per-slot generation) but not borrows — the borrow row is ephemerality + §21.1 Rule 1 view-liveness. Parameter-position []mut T extends that existing, load-bearing machinery; it does not need new invention.
    • The mission test — does this make the user state something the compiler already knows? — condemns routing callers through a named wrapper when fn f(buf: []mut u8) is what they mean.

    Staging (from the decision brief):

    1. Parameter position first: collection→[]mut T coercion at call sites from mutable places, d1=1 slice creation, call-local §21.1 exclusivity (the view is ephemeral; the source is inaccessible for the call's duration). Codegen unchanged — same fat-pointer ABI as []T.
    2. This unblocks Curated libc contract overlay for c_import modeled surfaces #379 buf_out (memset/explicit_bzero) immediately.
    3. Local-binding and return-position []mut T follow as separate increments under the same §21.1 rules, each with its own gates.

    Implementation proceeds under this ruling; VecRange stays internal.

  6. ehartford commented on Jul 2, 2026

    @ehartford
    ContributorAuthor

    Spec tension flagged during campaign planning (needs Eric's ruling before stage 3): §4.8a says slices "cannot be stored in structs or returned from functions", but §21.1 Rule 6 defines returned-view origin tracking, and this issue's staged ruling lists RETURN position as stage 3. Provisional plan: ship stage 2 (local bindings — permitted by both sections) and do not start stage 3 or amend the spec until the contradiction is ruled. Options: (a) Rule 6 governs, amend §4.8a's blanket sentence; (b) §4.8a stands, stage 3 is dropped and Rule 6 is &T-only.

  7. ehartford commented on Jul 2, 2026

    @ehartford
    ContributorAuthor

    Ruling on the §4.8a tension (WWED, mission-derived): Rule 6 governs. Spec amended (§4.8a now: slices can't be stored in structs — handles are for persistence — and RETURNS are checked by §21.1 Rule 6 origin tracking). Stage 3 (return-position []mut T) is unblocked and stays on the roadmap after stage 2 (locals).

  8. ehartford commented on Jul 3, 2026

    @ehartford
    ContributorAuthor

    Stage 2 (local bindings) scoping — ergonomic core verified working, but exclusivity is unenforced; deferred as real borrow-checker work.

    Prototyped stage 2 (widen the in_param_type_position choke point to local binding annotations + make arr[..] yield d1=1 when expected is []mut and the source place is mutable). Verified: let s: []mut i32 = a[..]; s[0] = 9 compiles and the write reaches a (prints 9); []mut returns/fields stay rejected; let-arrays are element-mutable so []mut off a let array is legitimate.

    Blocker: §4.8a exclusivity is not enforced and cannot be cheaply added. var a; let s: []mut i32 = a[..]; a[0]=100; s[1]=200 and two overlapping []mut slices of the same source both check clean today — the aliasing §4.8a forbids ('while a []mut T is live … the range may not be read or written through any other path; a second overlapping []mut T is rejected'). Root cause: slices have NO borrow-tracking at all right now (even let s = a[0..2]; a[0]=9 on an immutable slice isn't tracked). Stage 1's exclusivity was call-LOCAL (single point); a binding needs the exclusive borrow tracked across the binding's NLL lifetime — genuinely new machinery (register the slice as an exclusive view of the source place; reject source read/write and second views while live; release at last use). Shipping the ergonomic core without it would reintroduce the mutable-aliasing hole the #600/#605/#606 work just closed, so it's not shippable as-is. Stage 2 = a focused borrow-checker cycle, not a quick win. Reverted to keep the tree clean.

  9. changed the title [-][]mut T arguments: collection->mutable-slice coercion is missing (blocks #379 buf_out)[/-] [+][]mut T stages 2–3: local bindings, returns, and split_at_mut[/+] on Jul 15, 2026
  10. ehartford commented on Oct 25, 2026

    @ehartford
    ContributorAuthor

    Triage 2026-10-25, with v0.15.3.0 (main a261b65): still reproduces, and the diagnostic regressed. A local []mut binding is refused, but no longer with the targeted "parameter-only in this release" message; it is a bare type mismatch:

    var a = [1, 2, 3]
    let s: []mut i32 = a[..]
    s[0] = 9
    
    error: type mismatch in binding
     --> main.w:2:1
    

    post-release: stages 2–3 need the borrow checker to keep the exclusive view live (the comment of 2026-07 records why the prototype could not ship). The lost diagnostic is small and user-facing; it belongs with the next diagnostics pass.

  11. added this to the post-v0.16.0 milestone on Oct 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions