Skip to content

Commit

Permalink
[Fix rubocop#10755] Fix a false positive for Lint/LiteralAsCondition
Browse files Browse the repository at this point in the history
Fixes rubocop#10755.

This PR fixes a false positive for `Lint/LiteralAsCondition`
when using a literal in `case-in` condition where the match variable is used in
`in` are accepted as a pattern matching.
  • Loading branch information
koic committed Jun 27, 2022
1 parent 02d0dcf commit 3fe65e9
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 2 deletions.
@@ -0,0 +1 @@
* [#10755](https://github.com/rubocop/rubocop/issues/10755): Fix a false positive for `Lint/LiteralAsCondition` when using a literal in `case-in` condition where the match variable is used in `in` are accepted as a pattern matching. ([@koic][])
5 changes: 5 additions & 0 deletions lib/rubocop/cop/lint/literal_as_condition.rb
Expand Up @@ -7,6 +7,9 @@ module Lint
# operands in and/or expressions serving as the conditions of
# if/while/until/case-when/case-in.
#
# NOTE: Literals in `case-in` condition where the match variable is used in
# `in` are accepted as a pattern matching.
#
# @example
#
# # bad
Expand Down Expand Up @@ -69,6 +72,8 @@ def on_case(case_node)

def on_case_match(case_match_node)
if case_match_node.condition
return if case_match_node.descendants.any?(&:match_var_type?)

check_case(case_match_node)
else
case_match_node.each_in_pattern do |in_pattern_node|
Expand Down
20 changes: 18 additions & 2 deletions spec/rubocop/cop/lint/literal_as_condition_spec.rb
Expand Up @@ -75,11 +75,19 @@
end

context '>= Ruby 2.7', :ruby27 do
it "registers an offense for literal #{lit} in case match" do
it "accepts an offense for literal #{lit} in case match with a match var" do
expect_no_offenses(<<~RUBY, lit: lit)
case %{lit}
in x then top
end
RUBY
end

it "registers an offense for literal #{lit} in case match without a match var" do
expect_offense(<<~RUBY, lit: lit)
case %{lit}
^{lit} Literal `#{lit}` appeared as a condition.
in x then top
in CONST then top
end
RUBY
end
Expand Down Expand Up @@ -219,6 +227,14 @@
RUBY
end

it 'accepts an offense for case match with a match var' do
expect_no_offenses(<<~RUBY)
case { a: 1, b: 2, c: 3 }
in a: Integer => m
end
RUBY
end

it 'accepts dstr literal in case match' do
expect_no_offenses(<<~'RUBY')
case "#{x}"
Expand Down

0 comments on commit 3fe65e9

Please sign in to comment.