Skip to content

Commit

Permalink
Fix false negative for Style/RedundantAssignment
Browse files Browse the repository at this point in the history
This PR fixes false negative for `Style/RedundantAssignment`
when using pattern matching.
  • Loading branch information
koic committed Feb 24, 2024
1 parent 1d43035 commit 9d32b62
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 2 deletions.
@@ -0,0 +1 @@
* [#12706](https://github.com/rubocop/rubocop/pull/12706): 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

0 comments on commit 9d32b62

Please sign in to comment.