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

70 lines
1.7 KiB
Crystal
Raw Normal View History

module Ameba::Rule::Lint
2017-11-17 21:41:30 +00:00
# A rule that disallows some unwanted symbols in percent array literals.
#
# For example, this is usually written by mistake:
#
# ```
# %i(:one, :two)
# %w("one", "two")
# ```
#
# And the expected example is:
#
# ```
# %i(one two)
# %w(one two)
# ```
#
# YAML configuration example:
#
# ```
# Lint/PercentArrays:
2017-11-17 21:41:30 +00:00
# Enabled: true
# StringArrayUnwantedSymbols: ',"'
# SymbolArrayUnwantedSymbols: ',:'
# ```
2021-01-18 15:45:35 +00:00
class PercentArrays < Base
2017-11-22 06:44:29 +00:00
properties do
description "Disallows some unwanted symbols in percent array literals"
2021-01-17 17:12:10 +00:00
2021-01-17 12:25:50 +00:00
string_array_unwanted_symbols %(,")
symbol_array_unwanted_symbols %(,:)
2017-11-22 06:44:29 +00:00
end
2017-11-17 21:41:30 +00:00
MSG = "Symbols `%s` may be unwanted in %s array literals"
2017-11-17 21:41:30 +00:00
def test(source)
2018-06-10 21:15:12 +00:00
issue = start_token = nil
2017-11-17 21:41:30 +00:00
Tokenizer.new(source).run do |token|
case token.type
2022-03-11 12:15:05 +00:00
when .string_array_start?, .symbol_array_start?
2017-11-17 21:41:30 +00:00
start_token = token.dup
2022-03-11 12:15:05 +00:00
when .string?
if (_start = start_token) && !issue
2023-11-14 02:40:14 +00:00
issue = array_entry_invalid?(token.value.to_s, _start.raw)
2017-11-17 21:41:30 +00:00
end
2022-03-11 12:15:05 +00:00
when .string_array_end?
if (_start = start_token) && (_issue = issue)
issue_for _start, _issue
2017-11-17 21:41:30 +00:00
end
2018-06-10 21:15:12 +00:00
issue = start_token = nil
2017-11-17 21:41:30 +00:00
end
end
end
private def array_entry_invalid?(entry, array_type)
case array_type
when .starts_with? "%w"
check_array_entry entry, string_array_unwanted_symbols, "%w"
when .starts_with? "%i"
check_array_entry entry, symbol_array_unwanted_symbols, "%i"
end
end
private def check_array_entry(entry, symbols, literal)
2023-11-14 02:40:14 +00:00
MSG % {symbols, literal} if entry.matches?(/[#{Regex.escape(symbols)}]/)
2017-11-17 21:41:30 +00:00
end
end
end