Skip to content

Commit

Permalink
Add Lint/LiteralAssignmentsInExpressions rule
Browse files Browse the repository at this point in the history
  • Loading branch information
Sija committed Nov 15, 2022
1 parent 04b19a6 commit 4029254
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions src/ameba/rule/lint/literal_assignments_in_expressions.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
module Ameba::Rule::Lint
# A rule that disallows assignments with literal values
# in control expressions.
#
# For example, this is considered invalid:
#
# ```
# if foo = 42
# do_something
# end
# ```
#
# And should be replaced by the following:
#
# ```
# if foo == 42
# do_something
# end
# ```
#
# YAML configuration example:
#
# ```
# Lint/LiteralAssignmentsInExpressions:
# Enabled: true
# ```
class LiteralAssignmentsInExpressions < Base
properties do
description "Disallows assignments with literal values in control expressions"
end

MSG = "Detected assignment with a literal value in control expression"

PRIMITIVE_LITERAL_TYPES = {
Crystal::NilLiteral,
Crystal::BoolLiteral,
Crystal::NumberLiteral,
Crystal::CharLiteral,
Crystal::StringLiteral,
Crystal::SymbolLiteral,
Crystal::ProcLiteral,
Crystal::Path,
}

DYNAMIC_LITERAL_TYPES = {
Crystal::RangeLiteral,
Crystal::RegexLiteral,
Crystal::TupleLiteral,
Crystal::NamedTupleLiteral,
Crystal::ArrayLiteral,
Crystal::HashLiteral,
}

LITERAL_TYPES =
PRIMITIVE_LITERAL_TYPES + DYNAMIC_LITERAL_TYPES

def test(source, node : Crystal::If | Crystal::Unless | Crystal::Case | Crystal::While | Crystal::Until)
return unless (cond = node.cond).is_a?(Crystal::Assign)
return unless cond.value.class.in?(LITERAL_TYPES)

issue_for cond, MSG
end
end
end

0 comments on commit 4029254

Please sign in to comment.