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 negatives for Style/RedundantReturn #12674

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
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