Skip to content

Commit

Permalink
Fix an error for Performance/RegexpMatch
Browse files Browse the repository at this point in the history
Follow up rubocop/rubocop-performance#73 (comment).

This commit fixes an error for `Performance/RegexpMatch` when
a regexp used independently with a regexp used in `if` are mixed.
  • Loading branch information
renawatson68 committed Jul 29, 2019
1 parent 47748d7 commit 3127b87
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 10 deletions.
18 changes: 8 additions & 10 deletions lib/rubocop/cop/performance/regexp_match.rb
Expand Up @@ -183,27 +183,21 @@ def last_match_used?(match_node)
end

def range_to_search_for_last_matches(match_node, body, scope_root)
expression = if (modifier_form = modifier_form?(match_node))
expression = if modifier_form?(match_node)
match_node.parent.if_branch.loc.expression
else
match_node.loc.expression
end

match_node_pos = expression.begin_pos
next_match_pos = next_match_pos(
body, match_node_pos, scope_root, modifier_form
)
next_match_pos = next_match_pos(body, match_node_pos, scope_root)

match_node_pos..next_match_pos
end

def modifier_form?(match_node)
match_node.parent.if_type? && match_node.parent.modifier_form?
end

def next_match_pos(body, match_node_pos, scope_root, modifier_form)
def next_match_pos(body, match_node_pos, scope_root)
node = search_match_nodes(body).find do |match|
begin_pos = if modifier_form
begin_pos = if modifier_form?(match)
match.parent.if_branch.loc.expression.begin_pos
else
match.loc.expression.begin_pos
Expand All @@ -215,6 +209,10 @@ def next_match_pos(body, match_node_pos, scope_root, modifier_form)
node ? node.loc.expression.begin_pos : Float::INFINITY
end

def modifier_form?(match_node)
match_node.parent.if_type? && match_node.parent.modifier_form?
end

def find_last_match(body, range, scope_root)
last_matches(body).find do |ref|
ref_pos = ref.loc.expression.begin_pos
Expand Down
12 changes: 12 additions & 0 deletions spec/rubocop/cop/performance/regexp_match_spec.rb
Expand Up @@ -432,5 +432,17 @@ def foo
end
RUBY
end

it 'registers an offense when a regexp used independently ' \
'with a regexp used in `if` are mixed' do
expect_offense(<<-RUBY)
def foo
/re/ === re # A regexp used independently is not yet supported.
do_something if /re/ === re
^^^^^^^^^^^ Use `match?` instead of `===` when `MatchData` is not used.
end
RUBY
end
end
end

0 comments on commit 3127b87

Please sign in to comment.