Skip to content

Commit

Permalink
Report all literals in Lint/LiteralInCondition, except for the `cas…
Browse files Browse the repository at this point in the history
…e` expression
  • Loading branch information
Sija committed Feb 19, 2025
1 parent 62a0ee6 commit 6dde0a9
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
20 changes: 18 additions & 2 deletions spec/ameba/rule/lint/literal_in_condition_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,23 @@ module Ameba::Rule::Lint
subject.catch(s).should be_valid
end

it "fails if there is a predicate in if conditional" do
it "fails if there is a predicate with non-literals" do
s = Source.new %(
:ok if [foo, bar]
:ok unless [foo, bar]
while [foo, bar]
:ok
end
until [foo, bar]
:ok
end
)
subject.catch(s).should_not be_valid
end

it "fails if there is a predicate in `if` conditional" do
s = Source.new %(
if "string"
:ok
Expand All @@ -35,7 +51,7 @@ module Ameba::Rule::Lint
subject.catch(s).should_not be_valid
end

it "fails if there is a predicate in unless conditional" do
it "fails if there is a predicate in `unless` conditional" do
s = Source.new %(
unless true
:ok
Expand Down
11 changes: 8 additions & 3 deletions src/ameba/rule/lint/literal_in_condition.cr
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ module Ameba::Rule::Lint
# in place of a variable or predicate function.
#
# This is because a conditional construct with a literal predicate will
# always result in the same behaviour at run time, meaning it can be
# always result in the same behavior at run time, meaning it can be
# replaced with either the body of the construct, or deleted entirely.
#
# This is considered invalid:
Expand Down Expand Up @@ -31,10 +31,15 @@ module Ameba::Rule::Lint

MSG = "Literal value found in conditional"

def test(source, node : Crystal::If | Crystal::Unless | Crystal::Case)
def test(source, node : Crystal::If | Crystal::Unless)
issue_for node.cond, MSG if literal?(node.cond)
end

def test(source, node : Crystal::Case)
return unless cond = node.cond
return unless static_literal?(cond)

issue_for cond, MSG if static_literal?(cond)
issue_for cond, MSG
end
end
end

0 comments on commit 6dde0a9

Please sign in to comment.