Skip to content

Commit

Permalink
Support alternations in matches
Browse files Browse the repository at this point in the history
This is code like 'a => Integer | String`
  • Loading branch information
herwinw committed Sep 16, 2024
1 parent 73c96c3 commit 584779a
Showing 1 changed file with 13 additions and 3 deletions.
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

0 comments on commit 584779a

Please sign in to comment.