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 #10755] Fix a false positive for Lint/LiteralAsCondition #10756

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