Skip to content

Mutating the iterated collection inside for x in xs is accepted (no live-view diagnostic for the loop binding) #1317

Closed

Description

@ehartford

Found while fixing #1297. §21.1 rule 1 / D44: for e in xs is xs.iter() and e is a view into xs; mutating xs while e is live must be rejected as it is for let e = xs.get(0); xs.push(..); use e ("cannot mutate `xs` while `e` is a live view into it"). The for binding registers no borrow, so this compiles and reads through a reallocated buffer:

type KV { key: str, n: i32 }

fn main:
    var xs: Vec[KV] = Vec.new()
    xs.push(KV { key: "a".clone(), n: 1 })
    for e in xs:
        xs.push(KV { key: "b".clone(), n: 2 })   // accepted; `e` dangles after the realloc
        print(e.key)

Expected: cannot mutate \xs` while `e` is a live view into it`. Actual: check passes.

Not folded into #1297 because the borrow registration is whole-root: registering self for for e in self.items would also reject for e in self.items: self.count += 1, which is accepted today and idiomatic across the compiler (today let e = self.items.get(0); self.count += 1 already trips the coarse whole-self borrow). The loop-binding borrow needs the field path (self.items), not the root.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions