Skip to content

Comprehension clause ignores refutable patterns: [v for Some(v) in opts] binds every element #1403

Closed

Description

@ehartford

A refutable pattern in a comprehension clause is never tested: every element binds, matching or not. A for statement with the same pattern skips the elements it does not match (bind_for_element_or_skip, test/behavior/behav_for_full_patterns.w); the comprehension lowering binds unconditionally.

fn main:
    let opts: Vec[?i32] = [Some(1), None, Some(4)]
    let vs: Vec[i32] = [v for Some(v) in opts]
    print(f"{vs.len()}")
    let ts: Vec[(i32, i32)] = [(0, 1), (2, 3)]
    let bs: Vec[i32] = [b for (0, b) in ts]
    print(f"{bs.len()}")

Actual (stage1 of origin/main 00408eb): 3 and 2 — None binds its (absent) payload as v, and (2, 3) binds b.
Expected, by the for precedent: 2 and 1. (If refutable comprehension patterns should instead be a compile error, that is a ruling; either way silent binding is wrong code.)

Exact line: MirLower.bind_comprehension_element (src/MirLower.w, if self.ast.comprehension_binding_is_pattern(...): let _ = self.lower_pattern(pat_or_sym, item_place)) calls only the binding lowering; it never calls lower_pattern_match, so there is no fail edge. Its five callers each pass a continue block to lower_comprehension_body; the iterator form (lower_comprehension_iter) runs the binding inside a per-iteration scope that joins at iter_join_bb, so a skip edge there must join before the scope pop to keep the D33 per-iteration drop — an ownership/drop change that belongs alone in its batch.

Found while fixing #1388 (struct patterns); the #1388 behavior fixture covers the for statement form only.

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