Skip to content

Commit

Permalink
Merge pull request #12674 from koic/fix_false_negative_for_style_redu…
Browse files Browse the repository at this point in the history
…ndant_return

Fix false negatives for `Style/RedundantReturn`
  • Loading branch information
koic committed Feb 7, 2024
2 parents 1488e1f + 42e4680 commit 9b87c88
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
1 change: 1 addition & 0 deletions changelog/fix_false_negative_for_style_redundant_return.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#12674](https://github.com/rubocop/rubocop/pull/12674): Fix false negatives for `Style/RedundantReturn` when using pattern matching. ([@koic][])
6 changes: 6 additions & 0 deletions lib/rubocop/cop/style/redundant_return.rb
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ def check_branch(node)
case node.type
when :return then check_return_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 then check_rescue_node(node)
when :resbody then check_resbody_node(node)
Expand Down Expand Up @@ -140,6 +141,11 @@ def check_case_node(node)
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.ternary?

Expand Down
48 changes: 48 additions & 0 deletions spec/rubocop/cop/style/redundant_return_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -601,4 +601,52 @@ def func
RUBY
end
end

context 'when return is inside a in-branch' do
it 'registers an offense and autocorrects' do
expect_offense(<<~RUBY)
def func
some_preceding_statements
case x
in y then return 1
^^^^^^ Redundant `return` detected.
in z then return 2
^^^^^^ Redundant `return` detected.
in q
else
return 3
^^^^^^ Redundant `return` detected.
end
end
RUBY

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

context 'when case match nodes are empty' do
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
end
end

0 comments on commit 9b87c88

Please sign in to comment.