Skip to content

Commit

Permalink
Fix a false positive for Style/RedundantParentheses
Browse files Browse the repository at this point in the history
This PR fixes a false positive for `Style/RedundantParentheses`
when regexp literal attempts to match against a parenthesized condition.

The presence or absence of parentheses here changes the meaning of the syntax,
so the parentheses are not redundant:

```console
$ ruby-parse -e '/regexp/ =~ (foo || bar)'
(match-with-lvasgn
  (regexp
    (str "regexp")
    (regopt))
  (begin
    (or
      (send nil :foo)
      (send nil :bar))))

$ ruby-parse -e '/regexp/ =~ foo || bar'
(or
  (match-with-lvasgn
    (regexp
      (str "regexp")
      (regopt))
    (send nil :foo))
  (send nil :bar))
```
  • Loading branch information
koic committed Jan 10, 2024
1 parent 5cd23f8 commit 476a58b
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#12606](https://github.com/rubocop/rubocop/pull/12606): Fix a false positive for `Style/RedundantParentheses` when regexp literal attempts to match against a parenthesized condition. ([@koic][])
2 changes: 1 addition & 1 deletion lib/rubocop/cop/style/redundant_parentheses.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def parens_allowed?(node)
def ignore_syntax?(node)
return false unless (parent = node.parent)

parent.while_post_type? || parent.until_post_type? ||
parent.while_post_type? || parent.until_post_type? || parent.match_with_lvasgn_type? ||
like_method_argument_parentheses?(parent)
end

Expand Down
8 changes: 8 additions & 0 deletions spec/rubocop/cop/style/redundant_parentheses_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -574,6 +574,14 @@ def x
expect_no_offenses('a...(b || c)')
end

it 'accepts regexp literal attempts to match against a parenthesized condition' do
expect_no_offenses('/regexp/ =~ (b || c)')
end

it 'accepts variable attempts to match against a parenthesized condition' do
expect_no_offenses('regexp =~ (b || c)')
end

it 'registers parentheses around `||` logical operator keywords in method definition' do
expect_offense(<<~RUBY)
def foo
Expand Down

0 comments on commit 476a58b

Please sign in to comment.