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

Support Ruby 2.7's in pattern syntax for Lint/LiteralAsCondition #9877

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 @@
* [#9877](https://github.com/rubocop/rubocop/pull/9877): Support Ruby 2.7's `in` pattern syntax for `Lint/LiteralAsCondition`. ([@koic][])
14 changes: 13 additions & 1 deletion lib/rubocop/cop/lint/literal_as_condition.rb
Expand Up @@ -5,7 +5,7 @@ module Cop
module Lint
# This cop checks for literals used as the conditions or as
# operands in and/or expressions serving as the conditions of
# if/while/until.
# if/while/until/case-when/case-in.
#
# @example
#
Expand Down Expand Up @@ -67,6 +67,18 @@ def on_case(case_node)
end
end

def on_case_match(case_match_node)
if case_match_node.condition
check_case(case_match_node)
else
case_match_node.each_in_pattern do |in_pattern_node|
next unless in_pattern_node.condition.literal?

add_offense(in_pattern_node)
end
end
end

def on_send(node)
return unless node.negation_method?

Expand Down
54 changes: 54 additions & 0 deletions spec/rubocop/cop/lint/literal_as_condition_spec.rb
Expand Up @@ -74,6 +74,25 @@
RUBY
end

context '>= Ruby 2.7', :ruby27 do
it "registers an offense for literal #{lit} in case match" do
expect_offense(<<~RUBY, lit: lit)
case %{lit}
^{lit} Literal `#{lit}` appeared as a condition.
in x then top
end
RUBY
end

it "accepts literal #{lit} in a when of a case match" do
expect_no_offenses(<<~RUBY)
case x
in #{lit} then top
end
RUBY
end
end

it "registers an offense for literal #{lit} in &&" do
expect_offense(<<~RUBY, lit: lit)
if x && %{lit}
Expand Down Expand Up @@ -174,6 +193,41 @@
RUBY
end

context '>= Ruby 2.7', :ruby27 do
it 'accepts array literal in case match, if it has non-literal elements' do
expect_no_offenses(<<~RUBY)
case [1, 2, x]
in [1, 2, 5] then top
end
RUBY
end

it 'accepts array literal in case match, if it has nested non-literal element' do
expect_no_offenses(<<~RUBY)
case [1, 2, [x, 1]]
in [1, 2, 5] then top
end
RUBY
end

it 'registers an offense for case match with a primitive array condition' do
expect_offense(<<~RUBY)
case [1, 2, [3, 4]]
^^^^^^^^^^^^^^ Literal `[1, 2, [3, 4]]` appeared as a condition.
in [1, 2, 5] then top
end
RUBY
end

it 'accepts dstr literal in case match' do
expect_no_offenses(<<~'RUBY')
case "#{x}"
in [1, 2, 5] then top
end
RUBY
end
end

it 'accepts `true` literal in `while`' do
expect_no_offenses(<<~RUBY)
while true
Expand Down