shard-ameba/src/ameba/rule/lint/rand_zero.cr

42 lines
776 B
Crystal
Raw Normal View History

module Ameba::Rule::Lint
2018-03-08 16:55:35 +00:00
# A rule that disallows `rand(0)` and `rand(1)` calls.
# Such calls always return `0`.
#
# For example:
#
# ```
# rand(1)
# ```
#
# Should be written as:
#
# ```
# rand
# # or
# rand(2)
# ```
#
# YAML configuration example:
#
# ```
# Lint/RandZero:
2018-03-08 16:55:35 +00:00
# Enabled: true
# ```
2021-01-18 15:45:35 +00:00
class RandZero < Base
2018-03-08 16:55:35 +00:00
properties do
description "Disallows rand zero calls"
2018-03-08 16:55:35 +00:00
end
MSG = "%s always returns 0"
2018-03-08 16:55:35 +00:00
def test(source, node : Crystal::Call)
return unless node.name == "rand" &&
node.args.size == 1 &&
2022-12-08 13:06:16 +00:00
(arg = node.args.first).is_a?(Crystal::NumberLiteral) &&
arg.value.in?("0", "1")
2018-03-08 16:55:35 +00:00
2018-06-10 21:15:12 +00:00
issue_for node, MSG % node
2018-03-08 16:55:35 +00:00
end
end
end