Skip to content

Commit

Permalink
Support Ruby 2.7's in pattern syntax for Lint/LiteralAsCondition
Browse files Browse the repository at this point in the history
This PR supports Ruby 2.7's `in` pattern syntax for `Lint/LiteralAsCondition`.
  • Loading branch information
koic authored and bbatsov committed Jun 14, 2021
1 parent 4fed3f7 commit 2815917
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 1 deletion.
@@ -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

0 comments on commit 2815917

Please sign in to comment.