Skip to content

Commit

Permalink
Report conditions in while and until expressions as well
Browse files Browse the repository at this point in the history
  • Loading branch information
Sija committed Feb 19, 2025
1 parent 6dde0a9 commit d5ec13a
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
36 changes: 36 additions & 0 deletions spec/ameba/rule/lint/literal_in_condition_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,42 @@ module Ameba::Rule::Lint
subject.catch(s).should_not be_valid
end

it "fails if there is a predicate in `while` conditional" do
s = Source.new %(
while 1
:ok
end
)
subject.catch(s).should_not be_valid
end

it "fails if there is a `false` predicate in `while` conditional" do
s = Source.new %(
while false
:ok
end
)
subject.catch(s).should_not be_valid
end

it "passes if there is a `true` predicate in `while` conditional" do
s = Source.new %(
while true
:ok
end
)
subject.catch(s).should be_valid
end

it "fails if there is a predicate in `until` conditional" do
s = Source.new %(
until true
:foo
end
)
subject.catch(s).should_not be_valid
end

describe "range" do
it "reports range with literals" do
s = Source.new %(
Expand Down
10 changes: 9 additions & 1 deletion src/ameba/rule/lint/literal_in_condition.cr
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ module Ameba::Rule::Lint

MSG = "Literal value found in conditional"

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

Expand All @@ -41,5 +41,13 @@ module Ameba::Rule::Lint

issue_for cond, MSG
end

def test(source, node : Crystal::While)
return unless literal?(cond = node.cond)
# allow `while true`
return if cond.is_a?(Crystal::BoolLiteral) && cond.value

issue_for cond, MSG
end
end
end

0 comments on commit d5ec13a

Please sign in to comment.