Skip to content

Iterating a HashMap empties it: for (k, v) in m leaves m.len() == 0 and m.get segfaults (spec §13.5) #1187

Closed

Description

@ehartford

Spec §13.5: "for x in collection: borrows the collection immutably — the collection remains valid after the loop." For HashMap it does not.

use std.collections.HashMap
fn main:
    var m: HashMap[i32, i32] = HashMap.new()
    m.insert(1, 7)
    for (k, v) in m: print(f"{k}")
    print(f"{m.len()}")          // prints 0 — expected 1

Replace the last line with let got = m.get(1) and the program exits 139 (SIGSEGV). Same with HashMap[str, str]. with check reports ok for all of these; no move or borrow diagnostic. The Vec equivalent is correct (v.len() is 1 after the loop).

Related, same area:

  • for (k, v) in &m: and for (k, v) in m where m: &HashMap[K, V] leave k and v unbound: error: undefined variable.
  • Inside for (k, v) in m over HashMap[str, str], k binds as owned str; let a: &str = k is invalid MIR before codegen: use rvalue type is incompatible with assign destination (dest ty=17 kind=14, src ty=16 kind=5).
  • m.keys(), m.values(), m.items() byte-copy their elements (with_hashmap_{keys,values,items}_out, src/CodegenDispatch.w), so for non-Copy elements the Vec and the map both own the same buffers: the compiler's own openssl build double-frees through this (compiler double-frees a HashMap in Zcu.compile_source_frontend_mode on a c_import error path (openssl 4.0.2 evp.h); regression since v0.15.2.1 #1158), and out/with-get-investigation/map_snapshots.w corrupts the map in all three modes under WITH_DEBUG_ALLOC_SCRIBBLE=1 while a plain run prints ok. Map iteration lowers through the same MAP_ITEMS intrinsic (src/MirLower.w ~7595).

Verified on the compiler installed from a91d0bf7. What these operations should yield (views or owned values) is with Eric for a ruling; the emptied map and the unbound pattern variables are defects under any ruling.

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