Skip to content

Commit

Permalink
Fix a false positive for Style/MethodCallWithoutArgsParentheses
Browse files Browse the repository at this point in the history
This PR fixes the following false positive for `Style/MethodCallWithoutArgsParentheses`
when assigning to a default argument with the same name.

```console
% cat example.rb
def foo(test = test())
end

% ruby -c example.rb
Syntax OK

% rubocop --only Style/MethodCallWithoutArgsParentheses -a example.rb
Inspecting 1 file
C

Offenses:

example.rb:1:20: C: [Corrected] Style/MethodCallWithoutArgsParentheses:
Do not use parentheses for method calls with no arguments.
def foo(test = test())
                   ^^

1 file inspected, 1 offense detected, 1 offense corrected

% cat example.rb
def foo(test = test)
end

% ruby -c example.rb
example.rb:1: circular argument reference - test
```

It prevents `example.rb:1: circular argument reference - test`.
  • Loading branch information
koic authored and bbatsov committed Nov 28, 2020
1 parent 0186487 commit 695710e
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
@@ -0,0 +1 @@
* [#9113](https://github.com/rubocop-hq/rubocop/pull/9113): Fix a false positive for `Style/MethodCallWithoutArgsParentheses` when assigning to a default argument with the same name. ([@koic][])
13 changes: 11 additions & 2 deletions lib/rubocop/cop/style/method_call_without_args_parentheses.rb
Expand Up @@ -21,21 +21,30 @@ class MethodCallWithoutArgsParentheses < Base
def on_send(node)
return unless !node.arguments? && node.parenthesized?
return if ineligible_node?(node)
return if default_argument?(node)
return if ignored_method?(node.method_name)
return if same_name_assignment?(node)

register_offense(node)
end

private

def register_offense(node)
add_offense(offense_range(node)) do |corrector|
corrector.remove(node.loc.begin)
corrector.remove(node.loc.end)
end
end

private

def ineligible_node?(node)
node.camel_case_method? || node.implicit_call? || node.prefix_not?
end

def default_argument?(node)
node.parent&.optarg_type?
end

def same_name_assignment?(node)
any_assignment?(node) do |asgn_node|
next variable_in_mass_assignment?(node.method_name, asgn_node) if asgn_node.masgn_type?
Expand Down
Expand Up @@ -56,6 +56,13 @@
expect_no_offenses('test = test()')
end

it 'accepts parens in default argument assignment' do
expect_no_offenses(<<~RUBY)
def foo(test = test())
end
RUBY
end

it 'accepts parens in shorthand assignment' do
expect_no_offenses('test ||= test()')
end
Expand Down

0 comments on commit 695710e

Please sign in to comment.