Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support alternations in matches #2223

Merged
merged 2 commits into from
Sep 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions lib/natalie/compiler/transformers/match_required_node.rb
Original file line number Diff line number Diff line change
Expand Up @@ -102,12 +102,22 @@ def transform_array_pattern_node(node, value)

def transform_eqeqeq_check(node, value)
# Transform `expr => var` into `->(res, var) { res === var }.call(expr, var)`
alternations = []
alternation_handler = lambda do |n|
if n.is_a?(Prism::AlternationPatternNode)
alternation_handler.call(n.left)
alternation_handler.call(n.right)
else
alternations << n.location.slice
end
end
alternation_handler.call(node)
<<~RUBY
lambda do |result, expect|
unless expect === result
raise ::NoMatchingPatternError, "\#{result}: \#{expect} === \#{result} does not return true"
if expect.none? { |e| e === result }
raise ::NoMatchingPatternError, "\#{result}: \#{expect.last} === \#{result} does not return true"
end
end.call(#{value.location.slice}, #{node.location.slice})
end.call(#{value.location.slice}, [#{alternations.join(', ')}])
RUBY
end

Expand Down
14 changes: 14 additions & 0 deletions test/natalie/pattern_matching_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,20 @@ def self.one = 1
[1, 2] => *, ^a
}.should raise_error(NoMatchingPatternError, '[1, 2]: 1 === 2 does not return true')
end

it 'can handle alternation' do
1 => String | Integer
end

it 'can handle more than 2 alternations' do
1 => String | Symbol | Integer
end

it 'can fail with missing alternation' do
-> {
1 => String | Symbol
}.should raise_error(NoMatchingPatternError, '1: Symbol === 1 does not return true')
end
end

describe 'NoMatchingPatternError' do
Expand Down
Loading