diff --git a/lib/rubocop/cop/performance/regexp_match.rb b/lib/rubocop/cop/performance/regexp_match.rb index d38bdf6..e59ea7f 100644 --- a/lib/rubocop/cop/performance/regexp_match.rb +++ b/lib/rubocop/cop/performance/regexp_match.rb @@ -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 @@ -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 diff --git a/spec/rubocop/cop/performance/regexp_match_spec.rb b/spec/rubocop/cop/performance/regexp_match_spec.rb index 6794840..af6bbe9 100644 --- a/spec/rubocop/cop/performance/regexp_match_spec.rb +++ b/spec/rubocop/cop/performance/regexp_match_spec.rb @@ -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