Skip to content

Commit

Permalink
Fix a false negative for Style/OperatorMethodCall
Browse files Browse the repository at this point in the history
This PR fixes a false negative for `Style/OperatorMethodCall`
when using `a.+ b.something`.

The following is the difference depending on whether there is the dot or not.

It is the same when the argument is not enclosed in parentheses:

```console
% ruby-parse -e "a.+ b.something"
(send
  (send nil :a) :+
  (send
    (send nil :b) :something))

% ruby-parse -e "a + b.something"
(send
  (send nil :a) :+
  (send
    (send nil :b) :something))
```

It is different when the argument is enclosed in parentheses.

```console
% ruby-parse -e "a.+(b).something"
(send
  (send
    (send nil :a) :+
    (send nil :b)) :something)

% ruby-parse -e "a +(b).something"
(send nil :a
  (send
    (send
      (begin
        (send nil :b)) :something) :+@))
```

So the former should be warned by this cop.
  • Loading branch information
koic committed Jan 3, 2023
1 parent e141670 commit 0c3a67a
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#11379](https://github.com/rubocop/rubocop/pull/11379): Fix a false negative for `Style/OperatorMethodCall` when using `a.+ b.something`. ([@koic][])
6 changes: 5 additions & 1 deletion lib/rubocop/cop/style/operator_method_call.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def on_send(node)
return if node.receiver.const_type?

_lhs, _op, rhs = *node
return if rhs.nil? || rhs.children.first || rhs.forwarded_args_type?
return if rhs.nil? || parenthesized_argument?(rhs) || rhs.forwarded_args_type?

add_offense(dot) do |corrector|
wrap_in_parentheses_if_chained(corrector, node)
Expand All @@ -38,6 +38,10 @@ def on_send(node)

private

def parenthesized_argument?(argument)
argument.children.first && argument.parent.parenthesized?
end

def wrap_in_parentheses_if_chained(corrector, node)
return unless node.parent&.call_type?

Expand Down
15 changes: 13 additions & 2 deletions spec/rubocop/cop/style/operator_method_call_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,20 @@
end
end

it 'does not register an offense when using `foo.+@bar.to_s`' do
it 'registers an offense when using `foo.+ @bar.to_s`' do
expect_offense(<<~RUBY)
foo.+ @bar.to_s
^ Redundant dot detected.
RUBY

expect_correction(<<~RUBY)
foo + @bar.to_s
RUBY
end

it 'does not register an offense when using `foo.+(@bar).to_s`' do
expect_no_offenses(<<~RUBY)
foo.+ bar.to_s
foo.+(@bar).to_s
RUBY
end

Expand Down

0 comments on commit 0c3a67a

Please sign in to comment.