Skip to content

Commit

Permalink
Merge pull request #8863 from koic/fix_error_for_ambiguous_regexp_lit…
Browse files Browse the repository at this point in the history
…eral

[Fix #8862] Fix an error for `Lint/AmbiguousRegexpLiteral`
  • Loading branch information
koic committed Oct 9, 2020
2 parents 8c58d5e + e36f120 commit f79e1c0
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -7,6 +7,7 @@
* [#8782](https://github.com/rubocop-hq/rubocop/issues/8782): Fix incorrect autocorrection for `Style/TernaryParentheses` with `defined?`. ([@dvandersluis][])
* [#8864](https://github.com/rubocop-hq/rubocop/issues/8864): Fix false positive for `Style/RedundantBegin` with a postfix `while` or `until`. ([@dvandersluis][])
* [#8869](https://github.com/rubocop-hq/rubocop/issues/8869): Fix a false positive for `Style/RedundantBegin` when using `begin` for or assignment and method call. ([@koic][])
* [#8862](https://github.com/rubocop-hq/rubocop/issues/8862): Fix an error for `Lint/AmbiguousRegexpLiteral` when using regexp without method calls in nested structure. ([@koic][])

## 0.93.0 (2020-10-08)

Expand Down
9 changes: 6 additions & 3 deletions lib/rubocop/cop/lint/ambiguous_regexp_literal.rb
Expand Up @@ -53,15 +53,18 @@ def find_offense_node_by(diagnostic)
def find_offense_node(node, regexp_receiver)
return node unless node.parent

if node.parent.send_type? || method_chain_to_regexp_receiver?(node)
if node.parent.send_type? || method_chain_to_regexp_receiver?(node, regexp_receiver)
node = find_offense_node(node.parent, regexp_receiver)
end

node
end

def method_chain_to_regexp_receiver?(node)
node.parent.parent && node.parent.receiver.receiver == regexp_receiver
def method_chain_to_regexp_receiver?(node, regexp_receiver)
return false unless (parent = node.parent)
return false unless (parent_receiver = parent.receiver)

parent.parent && parent_receiver.receiver == regexp_receiver
end
end
end
Expand Down
19 changes: 19 additions & 0 deletions spec/rubocop/cop/lint/ambiguous_regexp_literal_spec.rb
Expand Up @@ -60,6 +60,25 @@
RUBY
end

it 'registers an offense and corrects when using regexp without method call in a nested structure' do
expect_offense(<<~RUBY)
class MyTest
test '#foo' do
assert_match /expected/, actual
^ Ambiguous regexp literal. Parenthesize the method arguments if it's surely a regexp literal, or add a whitespace to the right of the `/` if it should be a division.
end
end
RUBY

expect_correction(<<~RUBY)
class MyTest
test '#foo' do
assert_match(/expected/, actual)
end
end
RUBY
end

it 'registers an offense and corrects when using block argument' do
expect_offense(<<~RUBY)
p /pattern/, foo do |arg|
Expand Down

0 comments on commit f79e1c0

Please sign in to comment.