Skip to content

Commit

Permalink
Fix false negatives for Lint/UnreachableCode
Browse files Browse the repository at this point in the history
This PR fixes false negatives for `Lint/UnreachableCode`
when using pattern matching.
  • Loading branch information
koic authored and bbatsov committed Apr 20, 2024
1 parent c30838d commit f1a748b
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 2 deletions.
@@ -0,0 +1 @@
* [#12857](https://github.com/rubocop/rubocop/pull/12857): Fix false negatives for `Lint/UnreachableCode` when using pattern matching. ([@koic][])
6 changes: 4 additions & 2 deletions lib/rubocop/cop/lint/unreachable_code.rb
Expand Up @@ -71,7 +71,7 @@ def flow_expression?(node)
expressions.any? { |expr| flow_expression?(expr) }
when :if
check_if(node)
when :case
when :case, :case_match
check_case(node)
else
false
Expand All @@ -89,7 +89,9 @@ def check_case(node)
return false unless else_branch
return false unless flow_expression?(else_branch)

node.when_branches.all? { |branch| branch.body && flow_expression?(branch.body) }
branches = node.case_type? ? node.when_branches : node.in_pattern_branches

branches.all? { |branch| branch.body && flow_expression?(branch.body) }
end
end
end
Expand Down
32 changes: 32 additions & 0 deletions spec/rubocop/cop/lint/unreachable_code_spec.rb
Expand Up @@ -97,6 +97,24 @@ def something
RUBY
end

it "registers an offense for `#{t}` in all `case` pattern branches" do
expect_offense(wrap(<<~RUBY))
case cond
in 1
something
#{t}
in 2
something2
#{t}
else
something3
#{t}
end
bar
^^^ Unreachable code detected.
RUBY
end

it "accepts code with conditional `#{t}`" do
expect_no_offenses(wrap(<<~RUBY))
#{t} if cond
Expand Down Expand Up @@ -182,5 +200,19 @@ def something
bar
RUBY
end

it "accepts `#{t}` is in `case` pattern branch without else" do
expect_no_offenses(wrap(<<~RUBY))
case cond
in 1
something
#{t}
in 2
something2
#{t}
end
bar
RUBY
end
end
end

0 comments on commit f1a748b

Please sign in to comment.