Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix false negative for Style/RedundantAssignment #12707

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
@@ -0,0 +1 @@
* [#12707](https://github.com/rubocop/rubocop/pull/12707): Fix false negative for `Style/RedundantAssignment` when using pattern matching. ([@koic][])
12 changes: 10 additions & 2 deletions lib/rubocop/cop/style/redundant_assignment.rb
Expand Up @@ -54,25 +54,33 @@ def on_def(node)

private

# rubocop:disable Metrics/CyclomaticComplexity
def check_branch(node)
return unless node

case node.type
when :case then check_case_node(node)
when :if then check_if_node(node)
when :case then check_case_node(node)
when :case_match then check_case_match_node(node)
when :if then check_if_node(node)
when :rescue, :resbody
check_rescue_node(node)
when :ensure then check_ensure_node(node)
when :begin, :kwbegin
check_begin_node(node)
end
end
# rubocop:enable Metrics/CyclomaticComplexity

def check_case_node(node)
node.when_branches.each { |when_node| check_branch(when_node.body) }
check_branch(node.else_branch)
end

def check_case_match_node(node)
node.in_pattern_branches.each { |in_pattern_node| check_branch(in_pattern_node.body) }
check_branch(node.else_branch)
end

def check_if_node(node)
return if node.modifier_form? || node.ternary?

Expand Down
53 changes: 53 additions & 0 deletions spec/rubocop/cop/style/redundant_assignment_spec.rb
Expand Up @@ -180,6 +180,59 @@ def func
RUBY
end

context 'when inside an `in` branch' do
it 'registers an offense and autocorrects' do
expect_offense(<<~RUBY)
def func
some_preceding_statements
case x
in y
res = 1
^^^^^^^ Redundant assignment before returning detected.
res
in z
2
in q
else
res = 3
^^^^^^^ Redundant assignment before returning detected.
res
end
end
RUBY

expect_correction(<<~RUBY)
def func
some_preceding_statements
case x
in y
1
#{trailing_whitespace}
in z
2
in q
else
3
#{trailing_whitespace}
end
end
RUBY
end
end

it 'accepts empty `in` nodes' do
expect_no_offenses(<<~RUBY)
def func
case x
in y then 1
in z # do nothing
else
3
end
end
RUBY
end

it 'accepts empty method body' do
expect_no_offenses(<<~RUBY)
def func
Expand Down