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

49 lines
1.0 KiB
Crystal
Raw Normal View History

2020-03-26 09:31:08 +00:00
module Ameba::Rule::Lint
# A rule that disallows string conversion in string interpolation,
# which is redundant.
#
# For example, this is considered invalid:
#
# ```
# "Hello, #{name.to_s}"
# ```
#
# And this is valid:
#
# ```
# "Hello, #{name}"
# ```
#
# YAML configuration example:
#
# ```
2022-12-08 13:06:16 +00:00
# Lint/RedundantStringCoercion
2020-03-26 09:31:08 +00:00
# Enabled: true
# ```
2021-01-18 15:45:35 +00:00
class RedundantStringCoercion < Base
2020-03-26 09:31:08 +00:00
include AST::Util
properties do
description "Disallows redundant string conversions in interpolation"
end
MSG = "Redundant use of `Object#to_s` in interpolation"
def test(source, node : Crystal::StringInterpolation)
2023-11-11 18:03:28 +00:00
string_coercion_nodes(node).each do |expr|
issue_for expr.name_location, expr.end_location, MSG
2021-01-17 12:25:50 +00:00
end
2020-03-26 09:31:08 +00:00
end
private def string_coercion_nodes(node)
2022-11-25 03:00:15 +00:00
node.expressions.select do |exp|
exp.is_a?(Crystal::Call) &&
exp.name == "to_s" &&
exp.args.size.zero? &&
exp.named_args.nil? &&
exp.obj
2020-03-26 09:31:08 +00:00
end
end
end
end