Skip to content

Support type inference for pattern-matching capture variables#464

Open
pvcresin wants to merge 1 commit into
ruby:masterfrom
pvcresin:support-pattern-capture-narrowing
Open

Support type inference for pattern-matching capture variables#464
pvcresin wants to merge 1 commit into
ruby:masterfrom
pvcresin:support-pattern-capture-narrowing

Conversation

@pvcresin

Copy link
Copy Markdown
Contributor

Summary

Capture variables in case/in patterns were always inferred as untyped because the matched value was never threaded into the patterns:

case a
in Integer => n
  n + 1        # n was untyped
in [String => s, Symbol => t]
  [s, t]       # s, t were untyped
end

Changes

  • Add an install_pattern / install_pattern0 pair (mirroring install / install0, so @changes is reconciled the same way during incremental analysis) that flows the matched value into each pattern node.
  • Local targets bind to the matched value; Const => var narrows it by the class the same way when Const does (reusing IsAFilter); array / find patterns decompose it into element vertices via splat boxes. CaseMatchNode and the one-line => / in forms pass the subject in.
  • Hash patterns still capture as untyped (extracting a value type per key needs a dedicated box); sub-patterns inside them are still matched.
  • Promote scenario/known-issues/pattern-capture-narrowing.rb into scenario/patterns/capture.rb and update scenario/patterns/var_pat.rb.

All 433 tests pass (bundle exec rake test).

Capture variables in `case/in` patterns were always inferred as
`untyped` because the matched value was never threaded into the
patterns:

    case a
    in Integer => n
      n + 1        # n was untyped
    in [String => s, Symbol => t]
      [s, t]       # s, t were untyped
    end

Add an `install_pattern`/`install_pattern0` pair (mirroring
`install`/`install0`, so @changes is reconciled the same way during
incremental analysis) that flows the matched value into each pattern.
Local targets bind to it, `Const => var` narrows it by the class the
same way `when Const` does, and array/find patterns decompose it into
element vertices. `CaseMatchNode` and the one-line `=>`/`in` forms pass
the subject in.

Hash patterns still capture as untyped (extracting a value type per key
needs a dedicated box); sub-patterns inside them are still matched.

Promote scenario/known-issues/pattern-capture-narrowing.rb into
scenario/patterns/capture.rb and update scenario/patterns/var_pat.rb.

Co-authored-by: Claude Opus 4.8 (1M context) <[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.

1 participant