Skip to content

Sema: a field view of a borrowed collection element keeps its origin — &entry.value from for/.get(i) over a &Vec may be returned (#1297) - #1327

Merged
ehartford merged 2 commits into
mainfrom
fix-1297-field-view-origin
Sep 22, 2026
Merged

ehartford merged 2 commits into
mainfrom
fix-1297-field-view-origin

Conversation

@ehartford

Copy link
Copy Markdown
Contributor

Fixes #1297.

return Some(&entry.value) with entry bound by for entry in entries or let entry = entries.get(i) over a borrowed parameter's collection was rejected ("returned ephemeral value may outlive its origin 'entry'") while Some(entries.get(i)) was accepted. §3.4 / §21.1 rule 10 / D22: projecting a field out of a view preserves the view's origin set.

Two commits, one mechanism each:

  1. &view.field keeps the view's origin set. collect_expr_view_deps' UOP_REF branch (and the four direct &place root checks in check_returned_view_origins / check_yielded_view_origins) named place_root_sym(operand) as an origin of every &place. With e: &KV, e.value projects through the reference: its storage is the pointee, whose origins e already carries (deps + parameter mask). New ref_storage_root_sym: the root's own storage is borrowed unless the place projects through a reference-typed root; a bare &e still roots at e. Exact line from lldb on the baseline stage1 (Sema.view_origin_is_stack_local(sym e) ← check_returned_ephemeral_value_origins ← check_return, then emit_error at SemaCheck.w:10488) is in the commit message; --trace-place/--explain-mir-origin/analyze explain:node cannot reach this defect because the check fails before MIR exists.
  2. A for binding is a view of the iterated place. check_for gave the plain loop binding no provenance (the pattern path already did), so it became its own origin. record_for_binding_view_origins records it as record_view_producer_origins does for the spelled .iter() call (mask, deps, else the iterated place's root) without registering a whole-root borrow (which would reject the idiomatic for e in self.items: self.count += 1). for_iterable_yields_views also now peels the reference for Vec/HashMap as it already did for slices, so a &Vec[KV] iterable's binding is view-bound.

Matrix (rebuilt stage1): accepted — for e in v, let e = v.get(i), &v[i].value, &v.get(i).value, the match-bound entries forms, for (k, v) in m: &v.n, the self-receiver forms; rejected, naming the local — &kv.value, &xs.get(0).value, &xs[0].value, let e = xs.get(0); &e.value, for e in xs: return &e.value. Borrow behavior unchanged (let e = self.items.get(0); self.count += 1 still rejected; for e in self.items: self.count += 1 still accepted).

Tests: behav_field_view_of_borrowed_collection_returns (runs every accepted form and checks the values), err_field_view_of_local_escape, err_field_view_of_local_element_escape, err_field_view_of_local_element_binding_escape. Under stage1: the 4 new fixtures, the 60 existing view/origin/escape fixtures, the six D44 map debug-allocator cells (zero leaks), and 837/838 test/compile_errors pass; the one failure (err_c_import_raw_call_requires_unsafe) fails identically on a baseline stage1 built from origin/main, as do vec_map_it/vec_map_basic/behav_d44_map_ownership (p7 runner) / examples/json-parser under the bootstrap stage1. with check src/main.w passes at each commit.

Filed separately: #1317 — for e in xs: xs.push(..) is accepted (no live-view borrow for the loop binding; a whole-root borrow would be a false positive on self, it needs the field path).

Battery (:fixpoint/:test) not run per the task; to be driven by the pinned seed before merge.

Eric Hartford added 2 commits September 22, 2026 13:11
…oot is not the borrowed storage (#1297)

`return Some(&entry.value)` with `let entry = entries.get(i)` over a
borrowed parameter's collection (and `for (k, v) in m: return &v.n`)
was rejected as "returned ephemeral value may outlive its origin
'entry'", while `Some(entries.get(i))` itself was accepted. §3.4 and
§21.1 rule 10: projecting out of a value that contains views preserves
the origin set; D22: patterns and projections are structural and never
erase a borrow.

Exact line (baseline stage1, lldb, `breakpoint set -n
Sema.view_origin_is_stack_local` + `-n Sema.emit_error` on the repro
`let e = v.get(i); return Some(&e.value)` with `v: &Vec[KV]`):

  Sema.view_origin_is_stack_local(x1 = 13306 /* sym `e` */)
    from Sema.check_returned_ephemeral_value_origins
    from Sema.check_return
  Sema.emit_error("returned ephemeral value may outlive its origin 'e'")
    from Sema.check_returned_ephemeral_value_origins (SemaCheck.w:10488)

`e` reached the dep list from collect_expr_view_deps' UOP_REF branch
(SemaCheck.w:10024), which pushed `place_root_sym(operand)` for every
`&place`. `e` is `&KV`: `e.value` is a projection through the
reference, so its storage is the pointee, whose origins `e` already
carries (deps [v], parameter mask of v). Naming the root pinned the
field view to the binding, and the binding is a stack local.
`--trace-place`/`--explain-mir-origin`/`analyze explain:node` cannot
reach this: the check fails before MIR exists.

Fix: `ref_storage_root_sym(place)` — the binding whose OWN storage
`&place` borrows: the place root, unless the place projects through a
reference-typed root, in which case none (the root's collected deps
and mask are the origins). A bare `&e` still borrows the reference's
slot and stays rooted at `e`. Used at the UOP_REF dep collection and at
the four direct `&place` root checks in check_returned_view_origins /
check_yielded_view_origins. A view of a local's storage is rejected
exactly as before (`&kv.value`, `&xs.get(0).value`, `&xs[0].value`;
err_field_view_of_local_escape, err_field_view_of_local_element_escape).
… origins; a `&Vec`/`&HashMap` iterable yields views (#1297)

`for entry in entries: return Some(&entry.value)` with `entries` a
`&Vec[KV]` parameter or a match-bound payload of one was rejected as
"returned ephemeral value may outlive its origin 'entry'". check_for
put the plain loop binding in scope with no provenance at all (the
pattern path already recorded it through record_pattern_view_bindings),
so collect_expr_view_deps' NK_IDENT branch fell through to "a
reference-typed local with no origins is its own origin" and
view_origin_is_stack_local said yes: the binding, not the parameter,
was named. D44: `for x in xs` is `xs.iter()`; the binding is a view
produced from the iterated place.

record_for_binding_view_origins records the binding the way
record_view_producer_origins records the spelled call: the iterable's
parameter mask and collected deps, else the iterated place's root (an
owned local collection, so `&x.field` cannot escape and the diagnostic
names `xs`). It registers no borrow of that root: a whole-root borrow of
`self` would reject `for e in self.items: self.count += 1`, accepted
today and idiomatic; the missing live-view check on the iterated
collection is #1317.

for_iterable_yields_views peeled the reference for arrays and slices
but tested the Vec/HashMap shape on the unpeeled type, so a `&Vec[KV]`
iterable never marked its binding view-bound although the binding is
`&KV`; it now tests the peeled type, and the provenance recording is
gated on the binding's own type (a reference is a view) rather than on
that predicate.

Matrix under the rebuilt stage1 (scratch matrix.w / method.w / pat.w):
`for e in v`, `let e = v.get(i)`, `&v[i].value`, `&v.get(i).value`,
the match-bound `entries` forms, `for (k, v) in m: &v.n`, and the
`self` receiver forms all return their field view; `&kv.value`,
`&xs.get(0).value`, `&xs[0].value`, `let e = xs.get(0); &e.value` and
`for e in xs: return &e.value` over a local are rejected naming the
local. behav_field_view_of_borrowed_collection_returns runs the
accepted forms and checks the values; err_field_view_of_local_element_binding_escape
pins the two binding forms over a local.
@ehartford

Copy link
Copy Markdown
Contributor Author

Battery on cfc902e6 (rebased on main 980474c; seed-driven): build, :fixpoint, :move-audit rc=0; :test red only in main's own remaining reds — behav_distinct_compat (#1319 gap, fix forward pending), da_match_place_observes (#1322), fizzbuzz (#1325) — none in this change's paths (its 4 new fixtures and the 60 view/origin/escape fixtures pass). Mergeable on its own.

@ehartford
ehartford merged commit 5ea0dde into main Sep 22, 2026
@ehartford
ehartford deleted the fix-1297-field-view-origin branch September 22, 2026 19:45
ehartford added a commit that referenced this pull request Sep 22, 2026
…mpiler defects (#1338)

* examples: ephemerality-and-lowering stores the element directly, store(order[2], ...) (#1287 fixed in #1311)

The typed-binding detour around #1287 (Atomic intrinsics passed an element view's address as the value) is gone with its comment. Package test output unchanged on a release compiler built from ae609cd.

* examples: json-parser matches byte literals as patterns and returns &entry.value inline (#1295, #1297 fixed)

Byte arms are Some(b'{') patterns, not guards (#1295, fixed in #1312); json_get_field returns Some(&entry.value) from a for loop over the entries, and the kv_value helper is gone (#1297, fixed in #1327). Workaround comments removed. Demo and package test output unchanged on a release compiler built from ae609cd.

* examples: nebula's Status and Telemetry carry @[derive(Debug, Clone)] again (§11.8; #1288, #1289 fixed in #1311)

The parking comment is removed. Demo and package test output unchanged on a release compiler built from ae609cd.

* examples: service builds its change list and SET clause with the §7.2 builder (#1298 fixed in #1319)

describe_changes and PgUserRepo.update spell with Vec.new() as mut ...: with a trailing if; the var desugaring and its comments are gone. Demo and package test output unchanged on a release compiler built from ae609cd (neither function is reached by the demo; the same shape was run separately under --debug-alloc: correct result, zero leaks).

* examples: ecs cites D43 for DenseStorage.insert's -> Unit, not #1296

insert's tail if has an assignment arm (a value of type T) and a push arm (Unit): two meanings remain, so -> Unit is the spelling D43 requires, not a workaround. The compiler currently infers Unit without it because the assignment arm is a multi-statement block (#1337); the one-statement spellings of the same arm are rejected as D43 requires.

---------

Co-authored-by: Eric Hartford <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Returned-origin tracking pins a field view to the loop/element binding instead of the borrowed parameter it came from

1 participant