From 402925491c8a56238d0253b7af0ae11781725044 Mon Sep 17 00:00:00 2001 From: Sijawusz Pur Rahnama Date: Tue, 15 Nov 2022 01:26:46 +0100 Subject: [PATCH] Add `Lint/LiteralAssignmentsInExpressions` rule --- .../literal_assignments_in_expressions.cr | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 src/ameba/rule/lint/literal_assignments_in_expressions.cr diff --git a/src/ameba/rule/lint/literal_assignments_in_expressions.cr b/src/ameba/rule/lint/literal_assignments_in_expressions.cr new file mode 100644 index 000000000..c85556afe --- /dev/null +++ b/src/ameba/rule/lint/literal_assignments_in_expressions.cr @@ -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