Skip to content

Commit

Permalink
Handle hash patterns and pins in Lint/OutOfRangeRegexpRef cop
Browse files Browse the repository at this point in the history
  • Loading branch information
fatkodima committed Feb 14, 2023
1 parent 493ca2b commit 237f00e
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 10 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#11573](https://github.com/rubocop/rubocop/pull/11573): Handle hash patterns and pins in `Lint/OutOfRangeRegexpRef` cop. ([@fatkodima][])
16 changes: 6 additions & 10 deletions lib/rubocop/cop/lint/out_of_range_regexp_ref.rb
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def on_when(node)
end

def on_in_pattern(node)
regexp_patterns = patterns(node).select(&:regexp_type?)
regexp_patterns = regexp_patterns(node)

@valid_ref = regexp_patterns.map { |pattern| check_regexp(pattern) }.compact.max
end
Expand All @@ -90,16 +90,12 @@ def on_nth_ref(node)

private

def patterns(pattern_node)
pattern = pattern_node.node_parts[0]

case pattern.type
when :array_pattern, :match_alt
pattern.children
when :match_as
patterns(pattern)
else
def regexp_patterns(in_node)
pattern = in_node.pattern
if pattern.regexp_type?
[pattern]
else
pattern.each_descendant(:regexp).to_a
end
end

Expand Down
44 changes: 44 additions & 0 deletions spec/rubocop/cop/lint/out_of_range_regexp_ref_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,50 @@
end
end

context 'matching hashes' do
it 'does not register an offense when in range references are used' do
expect_no_offenses(<<~RUBY)
case hash
in a: /(foo)(bar)/
$2
end
RUBY
end

it 'registers an offense when out of range references are used' do
expect_offense(<<~RUBY)
case hash
in a: /(foo)(bar)/, b: /(bar)baz/
$3
^^ $3 is out of range (2 regexp capture groups detected).
end
RUBY
end
end

context 'matching pins' do
it 'does not register an offense when in range references are used' do
expect_no_offenses(<<~RUBY)
a = 1
case array
in [^a, /(foo)(bar)/]
$2
end
RUBY
end

it 'registers an offense when out of range references are used' do
expect_offense(<<~RUBY)
a = 1
case array
in [^a, /(foo)(bar)/, /(foo)bar/]
$3
^^ $3 is out of range (2 regexp capture groups detected).
end
RUBY
end
end

context 'matching with aliases' do
context 'variable aliases' do
it 'does not register an offense when in range references are used' do
Expand Down

0 comments on commit 237f00e

Please sign in to comment.