2017-11-17 21:41:30 +00:00
|
|
|
module Ameba::Rule
|
|
|
|
# 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:
|
|
|
|
#
|
|
|
|
# ```
|
|
|
|
# PercentArrays:
|
|
|
|
# Enabled: true
|
|
|
|
# StringArrayUnwantedSymbols: ',"'
|
|
|
|
# SymbolArrayUnwantedSymbols: ',:'
|
|
|
|
# ```
|
|
|
|
#
|
|
|
|
struct PercentArrays < Base
|
2017-11-22 06:44:29 +00:00
|
|
|
properties do
|
2018-05-03 15:57:47 +00:00
|
|
|
description "Disallows some unwanted symbols in percent array literals"
|
|
|
|
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
|
|
|
|
2018-04-17 04:29:43 +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
|
|
|
|
when :STRING_ARRAY_START, :SYMBOL_ARRAY_START
|
|
|
|
start_token = token.dup
|
|
|
|
when :STRING
|
2018-06-10 21:15:12 +00:00
|
|
|
if start_token && issue.nil?
|
|
|
|
issue = array_entry_invalid?(token.value, start_token.not_nil!.raw)
|
2017-11-17 21:41:30 +00:00
|
|
|
end
|
|
|
|
when :STRING_ARRAY_END, :SYMBOL_ARRAY_END
|
2018-06-10 21:15:12 +00:00
|
|
|
if issue
|
|
|
|
issue_for start_token.not_nil!, issue.not_nil!
|
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)
|
|
|
|
return unless entry =~ /[#{symbols}]/
|
2018-06-10 21:15:12 +00:00
|
|
|
MSG % {symbols, literal}
|
2017-11-17 21:41:30 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|