super-slim 3.0.0 → 3.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "tempfile"
3
4
  require_relative "../super_slim"
4
5
  require_relative "linter"
5
6
  require_relative "parallel"
@@ -15,6 +16,8 @@ module SuperSlim
15
16
  EX_USAGE = 64
16
17
  HELP_OPTIONS = %w[--help -h].freeze
17
18
  OPTIONS_BY_COMMAND = {"format" => ["--check"], "fmt" => ["--check"]}.freeze
19
+ # File names and template text reach the terminal and CI logs, where escapes and a `::` line are commands.
20
+ CONTROL_CHARACTER = /[\x00-\x08\x0a-\x1f\x7f]/
18
21
 
19
22
  def call(arguments)
20
23
  return puts(USAGE) || 0 if arguments.first == "help" || arguments.intersect?(HELP_OPTIONS)
@@ -23,7 +26,11 @@ module SuperSlim
23
26
  unknown_option = (arguments.grep(/\A-/) - OPTIONS_BY_COMMAND.fetch(command, [])).first
24
27
  return warn("Unknown option #{unknown_option}", USAGE) || EX_USAGE if unknown_option
25
28
 
26
- configuration = Linter.configuration
29
+ begin
30
+ configuration = Linter.configuration
31
+ rescue Error, Psych::Exception => exception
32
+ return warn(exception.message) || EX_USAGE
33
+ end
27
34
  SuperSlim.tailwind_classes = configuration["tailwind_classes"] if configuration.key?("tailwind_classes")
28
35
  case command
29
36
  when "lint" then lint(arguments, configuration)
@@ -36,9 +43,18 @@ module SuperSlim
36
43
  private
37
44
 
38
45
  def lint(paths, configuration)
39
- linter = Linter.new(configuration.fetch("linters", {}))
40
- offenses = Parallel.map(templates(paths)) { |path| linter.call(path, File.read(path)) }.flatten
41
- offenses.each { |offense| puts "#{offense.path}:#{offense.lineno}: [#{offense.rule}] #{offense.message}" }
46
+ begin
47
+ linter = Linter.new(configuration.fetch("linters", {}))
48
+ rescue Error => exception
49
+ return warn(exception.message) || EX_USAGE
50
+ end
51
+ offenses = Parallel.map(templates(paths)) do |path|
52
+ linter.call(path, File.read(path))
53
+ # One template that breaks SuperSlim, a bug or a stack too deep, must not hide the offenses of the others.
54
+ rescue StandardError, SystemStackError => exception
55
+ [Linter::Offense.new(path, 0, "Error", "#{exception.class}: #{exception.message.lines.first&.strip}")]
56
+ end.flatten
57
+ offenses.each { |offense| puts printable("#{offense.path}:#{offense.lineno}: [#{offense.rule}] #{offense.message}") }
42
58
  offenses.empty? ? 0 : 1
43
59
  end
44
60
 
@@ -50,22 +66,42 @@ module SuperSlim
50
66
  formatted = formatter.call(source)
51
67
  next if formatted == source
52
68
 
53
- File.write(path, formatted) unless check
69
+ replace(path, formatted) unless check
54
70
  [:reformatted, path]
55
- rescue Error => exception
56
- [:refused, "#{path}: #{exception.message.lines.first.strip}"]
71
+ rescue StandardError, SystemStackError => exception
72
+ message = exception.message.lines.first&.strip
73
+ [:refused, "#{path}: #{exception.is_a?(Error) ? message : "#{exception.class}: #{message}"}"]
57
74
  end
58
- outcomes.compact.each { |outcome, text| (outcome == :reformatted) ? puts(text) : warn(text) }
75
+ outcomes.compact.each { |outcome, text| (outcome == :reformatted) ? puts(printable(text)) : warn(printable(text)) }
59
76
  (outcomes.any? { |outcome,| outcome == :refused || (outcome == :reformatted && check) }) ? 1 : 0
60
77
  end
61
78
 
79
+ # A template found in a directory is a regular file of its own: a symlink in a checkout could point the
80
+ # formatter at any file the user can write, and a device or a FIFO would never end.
62
81
  def templates(paths)
63
82
  paths = ["."] if paths.empty?
64
83
  paths.flat_map do |path|
65
84
  next [path] unless File.directory?(path)
66
85
 
67
- Dir.glob("**/*.slim", base: path).filter_map { |template| File.join(path, template) unless template.match?(SKIPPED_DIRECTORIES) }
86
+ Dir.glob("**/*.slim", base: path).filter_map do |template|
87
+ template_path = File.join(path, template)
88
+ template_path if !template.match?(SKIPPED_DIRECTORIES) && File.lstat(template_path).file?
89
+ end
68
90
  end.sort
69
91
  end
92
+
93
+ # Written beside the template then renamed over it, so that a full disk or a kill cannot leave it cut short.
94
+ def replace(path, content)
95
+ Tempfile.create([".super-slim-", ".tmp"], File.dirname(path)) do |file|
96
+ file.write(content)
97
+ file.close
98
+ File.chmod(File.stat(path).mode & 0o7777, file.path)
99
+ File.rename(file.path, path)
100
+ end
101
+ end
102
+
103
+ def printable(text)
104
+ text.gsub(CONTROL_CHARACTER) { |character| character.inspect[1...-1] }
105
+ end
70
106
  end
71
107
  end
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "strscan"
4
+
3
5
  module SuperSlim
4
6
  class Compiler
5
7
  include AST
@@ -34,7 +36,9 @@ module SuperSlim
34
36
  CAPTURED_OUTPUT = /\A(if|unless)\b|\bdo\s*(\|[^|]*\|)?\s*$/
35
37
 
36
38
  ESCAPED_INTERPOLATION = /\A\\#\{/
37
- INTERPOLATION = /\A#\{((?>[^{}]|(\{(?>[^{}]|\g<1>)*\}))*)\}/
39
+ INTERPOLATION_START = /#\{/
40
+ OPENING_BRACE = "{".ord
41
+ CLOSING_BRACE = "}".ord
38
42
  UNESCAPED_INTERPOLATION_CODE = /\A\{.*\}\Z/
39
43
  INTERPOLATION_FREE_TEXT = /\A([#\\]?[^#\\]*([#\\][^\\#\{][^#\\]*)*)/ # rubocop:disable Style/RedundantRegexpEscape -- `#{` would open an interpolation
40
44
 
@@ -64,6 +68,21 @@ module SuperSlim
64
68
  @code
65
69
  end
66
70
 
71
+ # Byte offset of each `{` to that of the `}` closing it, in one pass: a regexp of balanced braces backtracks
72
+ # exponentially, and rescans the rest of the text from each `#{` left open.
73
+ def self.closing_braces(text)
74
+ closing_by_opening = {}
75
+ openings = []
76
+ text.each_byte.with_index do |byte, index|
77
+ if byte == OPENING_BRACE
78
+ openings << index
79
+ elsif byte == CLOSING_BRACE && (opening = openings.pop)
80
+ closing_by_opening[opening] = index
81
+ end
82
+ end
83
+ closing_by_opening
84
+ end
85
+
67
86
  private
68
87
 
69
88
  def compile_children(nodes)
@@ -328,20 +347,20 @@ module SuperSlim
328
347
  def interpolation_parts(text)
329
348
  return [[:static, text]] unless text.include?('#{')
330
349
 
350
+ closing_by_opening = Compiler.closing_braces(text)
351
+ scanner = StringScanner.new(text)
331
352
  parts = []
332
- loop do
333
- case text
334
- when ESCAPED_INTERPOLATION
353
+ until scanner.eos?
354
+ if scanner.skip(ESCAPED_INTERPOLATION)
335
355
  parts << [:static, '#{']
336
- when INTERPOLATION
337
- code = $1
356
+ elsif scanner.match?(INTERPOLATION_START) && (closing = closing_by_opening[scanner.pos + 1])
357
+ code = text.byteslice(scanner.pos + 2...closing)
358
+ scanner.pos = closing + 1
338
359
  escape = !code.match?(UNESCAPED_INTERPOLATION_CODE)
339
360
  parts << [:dynamic, escape ? code : code[1..-2], escape]
340
- when INTERPOLATION_FREE_TEXT
341
- parts << [:static, $&]
361
+ else
362
+ parts << [:static, scanner.scan(INTERPOLATION_FREE_TEXT)]
342
363
  end
343
- text = $'
344
- break if text.empty?
345
364
  end
346
365
  parts
347
366
  end
@@ -1,7 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "ripper"
4
-
5
3
  module SuperSlim
6
4
  class Formatter
7
5
  # Breaks the lines of a formatted template longer than max_line_length: a tag's attributes one per line
@@ -10,10 +8,15 @@ module SuperSlim
10
8
  class LineWrapper
11
9
  CODE_LINE = /\A *(?:-|==?[<>]*) /
12
10
  TAG_OUTPUT = /\G\s*==?['<>]*\s*/
13
- OPENINGS = %i[on_lparen on_lbracket on_lbrace on_tlambeg on_embexpr_beg].freeze
14
- CLOSINGS = %i[on_rparen on_rbracket on_rbrace on_embexpr_end].freeze
15
11
  CONTINUATION_KINDS = %i[continuation text text_blank].freeze
16
- MODIFIERS = %w[if unless while until rescue].freeze
12
+ DO_KEYWORDS = %i[KEYWORD_DO KEYWORD_DO_BLOCK KEYWORD_DO_LAMBDA KEYWORD_DO_LOOP].freeze
13
+ MODIFIERS = %i[KEYWORD_IF_MODIFIER KEYWORD_UNLESS_MODIFIER KEYWORD_WHILE_MODIFIER KEYWORD_UNTIL_MODIFIER KEYWORD_RESCUE_MODIFIER].freeze
14
+ # Prism 2 splits some tokens by role (BRACE_LEFT_HASH, PARENTHESIS_LEFT_GROUPING): older ones never emit them.
15
+ OPENING_BRACKETS = %i[
16
+ PARENTHESIS_LEFT PARENTHESIS_LEFT_PARENTHESES PARENTHESIS_LEFT_GROUPING BRACKET_LEFT BRACKET_LEFT_ARRAY
17
+ BRACE_LEFT BRACE_LEFT_HASH BRACE_LEFT_ARGUMENT LAMBDA_BEGIN EMBEXPR_BEGIN
18
+ ].freeze
19
+ CLOSING_BRACKETS = %i[PARENTHESIS_RIGHT BRACKET_RIGHT BRACE_RIGHT EMBEXPR_END].freeze
17
20
 
18
21
  # Templates attach ( and [ to their tag but set { apart, as a Ruby block: 6,097 public templates agree.
19
22
  OPENING_BY_ATTRIBUTE_DELIMITERS = {"()" => "(", "[]" => "[", "{}" => " {"}.freeze
@@ -109,19 +112,17 @@ module SuperSlim
109
112
  def argument_breaks(code)
110
113
  depth = 0
111
114
  offsets = []
112
- Ripper.lex(code).each do |(_, column), type, token|
113
- case type
114
- when :on_heredoc_beg then return []
115
- when :on_kw
116
- break if token == "do"
117
- # RuboCop refuses a modifier that ends a statement spread over several lines (Style/MultilineIfModifier).
118
- return [] if depth.zero? && MODIFIERS.include?(token)
119
- when :on_op
120
- # `a, b = …` assigns several variables: its commas separate no arguments.
121
- return [] if depth.zero? && token == "=" && !offsets.empty?
122
- when :on_comma then offsets << column + 1 if depth.zero?
123
- when *OPENINGS then depth += 1
124
- when *CLOSINGS then depth -= 1
115
+ Prism.lex(code).value.each do |(token, _state)|
116
+ case token.type
117
+ when :COMMA then offsets << token.location.end_offset if depth.zero?
118
+ when :HEREDOC_START then return []
119
+ # `a, b = …` assigns several variables: its commas separate no arguments.
120
+ when :EQUAL then return [] if depth.zero? && !offsets.empty?
121
+ when *DO_KEYWORDS then break
122
+ # RuboCop refuses a modifier that ends a statement spread over several lines (Style/MultilineIfModifier).
123
+ when *MODIFIERS then return [] if depth.zero?
124
+ when *OPENING_BRACKETS then depth += 1
125
+ when *CLOSING_BRACKETS then depth -= 1
125
126
  end
126
127
  end
127
128
  offsets
@@ -1,17 +1,21 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "prism"
3
4
  require_relative "formatter/line_wrapper"
4
5
 
5
6
  module SuperSlim
6
7
  # Rewrites a template in its canonical layout. Text blocks shift as a whole, so the whitespace they render is
7
8
  # kept; and the formatted template must compile to the same Ruby as the original, or nothing is rewritten.
8
- # With max_line_length, longer lines are then wrapped, but only if the Ruby differs by nothing but whitespace.
9
+ # With max_line_length, longer lines are then wrapped, but only if Prism reads the same Ruby, positions aside.
9
10
  class Formatter
10
11
  INDENT_WIDTH = 2
11
12
  CONTROL = /\A-\s*/
12
13
  OUTPUT = /\A(==?)([<>]*)\s*/
13
14
  TAG_OUTPUT = /\A\s*(==?)(['<>]*)\s*/
14
15
  REDUNDANT_DIV = /\Adiv(?=[.#][\p{Word}-])/
16
+ # Prism 1.x counts in a node's flags whether it starts a line.
17
+ NEWLINE_FLAG = defined?(Prism::NodeFlags::NEWLINE) ? Prism::NodeFlags::NEWLINE : 0
18
+ FIELDS_BY_NODE_CLASS = {}
15
19
 
16
20
  def self.call(source, **)
17
21
  new(**).call(source)
@@ -24,7 +28,8 @@ module SuperSlim
24
28
 
25
29
  def call(source)
26
30
  formatted = layout(source)
27
- unless formatted == source || compiled(formatted) == compiled(source)
31
+ formatted_ruby = compiled_ruby(formatted) unless formatted == source
32
+ if formatted_ruby && !same_ruby?(compiled_ruby(source), formatted_ruby)
28
33
  raise UnsafeFormattingError, "Formatting would change how this template renders"
29
34
  end
30
35
  return formatted unless @line_wrapper
@@ -32,8 +37,14 @@ module SuperSlim
32
37
  wrapped = @line_wrapper.call(formatted)
33
38
  return formatted if wrapped == formatted
34
39
 
35
- wrapped_tokens = ruby_tokens(wrapped)
36
- (wrapped_tokens && wrapped_tokens == ruby_tokens(formatted)) ? wrapped : formatted
40
+ wrapped_ruby = compiled_ruby(wrapped)
41
+ # Only Prism's tree vouches for a wrap: a compile error can read the same before and after it.
42
+ return formatted unless wrapped_ruby.is_a?(Prism::ParseResult)
43
+
44
+ same_ruby?(formatted_ruby || compiled_ruby(formatted), wrapped_ruby) ? wrapped : formatted
45
+ # Prism walks code recursively too: code nested thousands deep can't be checked, so it isn't formatted.
46
+ rescue SystemStackError
47
+ raise UnsafeFormattingError, "Code nested too deep to check that formatting changes nothing"
37
48
  end
38
49
 
39
50
  private
@@ -84,10 +95,9 @@ module SuperSlim
84
95
  end
85
96
 
86
97
  def with_output_spacing(line, info)
87
- return line unless info.output_column
98
+ return line unless info.output_column && line[info.output_column..] =~ TAG_OUTPUT
88
99
 
89
100
  before = line[0...info.output_column].rstrip
90
- line[info.output_column..] =~ TAG_OUTPUT
91
101
  $'.empty? ? "#{before} #{$1}#{$2}" : "#{before} #{$1}#{$2} #{$'}"
92
102
  end
93
103
 
@@ -99,27 +109,87 @@ module SuperSlim
99
109
  line.sub(/\A[ \t]*/) { _1.gsub(Parser::TAB, "\\1#{" " * Parser::TAB_SIZE}") }
100
110
  end
101
111
 
102
- def compiled(source)
103
- SuperSlim.compile(source, tailwind_classes: @tailwind_classes, format: :xml).gsub(/(?:\s*[;\n]\s*)+/, ";")
112
+ # Prism's tree of the compiled Ruby; that Ruby with its separators folded when Prism can't read it; the error
113
+ # when the template doesn't compile.
114
+ def compiled_ruby(source)
115
+ code = SuperSlim.compile(source, tailwind_classes: @tailwind_classes, format: :xml)
116
+ # Rails runs a template inside a method, where `yield` is valid.
117
+ parsed = Prism.parse("def template\n#{code}\nend")
118
+ parsed.success? ? parsed : code.gsub(/(?:\s*[;\n]\s*)+/, ";")
104
119
  rescue Error => exception
105
120
  exception.message
106
121
  end
107
122
 
108
- # Whitespace aside, wrapping only turns spaces into newlines that Ruby ignores after a comma, and newlines
109
- # that end statements into semicolons.
110
- def ruby_tokens(source)
111
- code = SuperSlim.compile(source, tailwind_classes: @tailwind_classes, format: :xml)
112
- tokens = Ripper.lex(code).flat_map do |_, type, token|
113
- case type
114
- when :on_sp, :on_ignored_nl then []
115
- when :on_nl, :on_semicolon then [";"]
116
- when :on_comment then [token.strip, ";"]
117
- else [token]
123
+ # Positions aside: line breaks, spaces, a trailing comma and the parentheses of a call change nothing, a
124
+ # different value or operator does.
125
+ def same_ruby?(ruby, other_ruby)
126
+ return ruby == other_ruby if ruby.is_a?(String) || other_ruby.is_a?(String)
127
+
128
+ same_node?(ruby.value, other_ruby.value) && comment_texts(ruby) == comment_texts(other_ruby)
129
+ end
130
+
131
+ # Walks both trees with a stack of its own: deep code or a deep template would exhaust Ruby's.
132
+ def same_node?(node, other_node)
133
+ pairs = [[node, other_node]]
134
+ until pairs.empty?
135
+ value, other_value = pairs.pop
136
+ case value
137
+ when Prism::Node
138
+ return false unless value.instance_of?(other_value.class)
139
+ return false unless same_node_value?(value, other_value)
140
+ when Array
141
+ return false unless other_value.is_a?(Array) && value.size == other_value.size
142
+ else
143
+ return false unless value == other_value
144
+
145
+ next
118
146
  end
147
+ pairs.concat(children_pairs(value, other_value).reverse)
119
148
  end
120
- tokens.chunk_while { |previous, token| previous == ";" && token == ";" }.map(&:first)
121
- rescue Error
122
- nil
149
+ true
150
+ end
151
+
152
+ def same_node_value?(node, other_node)
153
+ # `__LINE__` holds no value in the tree: removing a blank line above it changes what it renders.
154
+ return node.location.start_line == other_node.location.start_line if node.is_a?(Prism::SourceLineNode)
155
+
156
+ field_names, located_names, flagged = node_fields(node)
157
+ return false if flagged && (node.send(:flags) & ~NEWLINE_FLAG) != (other_node.send(:flags) & ~NEWLINE_FLAG)
158
+ # 2026-11: Prism 0.19 (Ruby 3.3) keeps the value of an integer or a float out of its fields.
159
+ return node.value == other_node.value if field_names.empty? && (node.is_a?(Prism::IntegerNode) || node.is_a?(Prism::FloatNode))
160
+
161
+ located_names.all? { |name| same_name?(node.public_send(name), other_node.public_send(name)) }
162
+ end
163
+
164
+ def children_pairs(value, other_value)
165
+ return value.zip(other_value) if value.is_a?(Array)
166
+ return [] if value.is_a?(Prism::SourceLineNode)
167
+
168
+ node_fields(value).first.map { |name| [value.public_send(name), other_value.public_send(name)] }
169
+ end
170
+
171
+ # Beside a location, a field holds either a name or, from Prism 2 on, the source the location covers
172
+ # (`opening` beside `opening_loc`): only the name counts.
173
+ def same_name?(name, other_name)
174
+ return true unless name.is_a?(Symbol) || other_name.is_a?(Symbol)
175
+
176
+ name == other_name
177
+ end
178
+
179
+ # 2026-11: Prism 0.19 (Ruby 3.3) has no reflection API: the field names come from the first node of each
180
+ # class. Prism 1.x keeps flags out of deconstruct_keys.
181
+ def node_fields(node)
182
+ FIELDS_BY_NODE_CLASS[node.class] ||= begin
183
+ keys = node.deconstruct_keys(nil).keys
184
+ located_names, field_names = (keys - %i[node_id flags location])
185
+ .reject { _1.end_with?("_loc") }
186
+ .partition { keys.include?(:"#{_1}_loc") }
187
+ [field_names, located_names, node.respond_to?(:flags, true)]
188
+ end
189
+ end
190
+
191
+ def comment_texts(ruby)
192
+ ruby.comments.map { |comment| comment.location.slice.strip }
123
193
  end
124
194
  end
125
195
  end
@@ -0,0 +1,72 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SuperSlim
4
+ class Linter
5
+ # Bootstrap 4 classes and data attributes that Bootstrap 5.3 renamed, keyed by rule then by option.
6
+ PRESETS = {
7
+ "bootstrap5" => {
8
+ "DeprecatedClasses" => {
9
+ classes: {
10
+ "badge-pill" => "rounded-pill",
11
+ "badge-*" => "text-bg-*",
12
+ "border-left*" => "border-start*",
13
+ "border-right*" => "border-end*",
14
+ "btn-block" => "w-100",
15
+ "card-deck" => "row",
16
+ "close" => "btn-close",
17
+ "custom-checkbox" => "form-check",
18
+ "custom-control" => "form-check",
19
+ "custom-control-inline" => "form-check-inline",
20
+ "custom-control-input" => "form-check-input",
21
+ "custom-control-label" => "form-check-label",
22
+ "custom-file" => "form-control",
23
+ "custom-radio" => "form-check",
24
+ "custom-range" => "form-range",
25
+ "custom-select" => "form-select",
26
+ "custom-select-lg" => "form-select-lg",
27
+ "custom-select-sm" => "form-select-sm",
28
+ "custom-switch" => "form-switch",
29
+ "embed-responsive" => "ratio",
30
+ "embed-responsive-1by1" => "ratio-1x1",
31
+ "embed-responsive-4by3" => "ratio-4x3",
32
+ "embed-responsive-16by9" => "ratio-16x9",
33
+ "embed-responsive-21by9" => "ratio-21x9",
34
+ "font-italic" => "fst-italic",
35
+ "font-weight-*" => "fw-*",
36
+ "form-control-file" => "form-control",
37
+ "form-group" => "mb-3",
38
+ "form-inline" => "d-flex",
39
+ "form-row" => "row",
40
+ "jumbotron" => "p-5",
41
+ "media" => "d-flex",
42
+ "media-body" => "flex-grow-1",
43
+ "ml-*" => "ms-*",
44
+ "mr-*" => "me-*",
45
+ "no-gutters" => "g-0",
46
+ "pl-*" => "ps-*",
47
+ "pr-*" => "pe-*",
48
+ "pre-scrollable" => "overflow-y-scroll",
49
+ "rounded-left*" => "rounded-start*",
50
+ "rounded-lg" => "rounded-3",
51
+ "rounded-right*" => "rounded-end*",
52
+ "rounded-sm" => "rounded-1",
53
+ "sr-only" => "visually-hidden",
54
+ "sr-only-focusable" => "visually-hidden-focusable",
55
+ "text-monospace" => "font-monospace",
56
+ "text-muted" => "text-body-secondary",
57
+ "thead-dark" => "table-dark",
58
+ "thead-light" => "table-light",
59
+ **%w[float text dropdown-menu].product(["", "-sm", "-md", "-lg", "-xl"]).flat_map do |utility, breakpoint|
60
+ [["#{utility}#{breakpoint}-left", "#{utility}#{breakpoint}-start"], ["#{utility}#{breakpoint}-right", "#{utility}#{breakpoint}-end"]]
61
+ end.to_h
62
+ }.freeze
63
+ },
64
+ "DeprecatedAttributes" => {
65
+ # Generic names Bootstrap also renamed (`data-content`, `data-delay`, `data-template`…) stay out: apps read them too.
66
+ attributes: %w[backdrop boundary dismiss interval keyboard parent pause placement ride slide slide-to spy target
67
+ toggle trigger wrap].to_h { ["data-#{_1}", "data-bs-#{_1}"] }.freeze
68
+ }
69
+ }.freeze
70
+ }.freeze
71
+ end
72
+ end
@@ -49,11 +49,7 @@ module SuperSlim
49
49
 
50
50
  # Text nodes carry no line of their own: they take the line of the closest node that does.
51
51
  def line_near(document, node, ancestors)
52
- [node, *ancestors.reverse].each do |candidate|
53
- lineno = document.line_of(candidate)
54
- return lineno if lineno
55
- end
56
- nil
52
+ document.line_of(node) || document.line_of(ancestors.located)
57
53
  end
58
54
 
59
55
  def each_line(document)
@@ -153,7 +149,8 @@ module SuperSlim
153
149
 
154
150
  line = document.lines[lineno - 1]
155
151
  if info.output_column
156
- line[info.output_column..] =~ TAG_OUTPUT
152
+ next unless line[info.output_column..] =~ TAG_OUTPUT
153
+
157
154
  offense(document, lineno, "Put a space before and after `#{$2}`") if $1.empty? || $4.empty?
158
155
  elsif info.kind == :structure
159
156
  case line.lstrip
@@ -235,7 +232,7 @@ module SuperSlim
235
232
 
236
233
  document.enum_for(:each_node).filter_map do |node, ancestors|
237
234
  next unless node.is_a?(AST::Tag) && node.name.match?(/[A-Z]/)
238
- next if ancestors.any? { _1.is_a?(AST::Tag) && _1.name == "svg" }
235
+ next if ancestors.inside_svg
239
236
 
240
237
  offense(document, document.line_of(node), "Write `#{node.name.downcase}` in lowercase")
241
238
  end
@@ -276,7 +273,7 @@ module SuperSlim
276
273
  def offenses(document, _source)
277
274
  branch_by_id = {}
278
275
  enum_for(:each_tag, document).filter_map do |tag, ancestors|
279
- branch = ancestors.reverse.find { _1.is_a?(AST::Control) }
276
+ branch = ancestors.control
280
277
  literal_attributes(tag, "id").filter_map do |attribute|
281
278
  id = literal_value(attribute)
282
279
  if branch_by_id.key?(id) && branch_by_id[id].equal?(branch)
@@ -319,7 +316,7 @@ module SuperSlim
319
316
  class NestedLinks < Rule
320
317
  def offenses(document, _source)
321
318
  enum_for(:each_tag, document, "a").filter_map do |tag, ancestors|
322
- next unless ancestors.any? { _1.is_a?(AST::Tag) && _1.name == "a" }
319
+ next unless ancestors.inside_link
323
320
 
324
321
  offense(document, document.line_of(tag), "Links cannot contain links")
325
322
  end
@@ -402,13 +399,14 @@ module SuperSlim
402
399
  # A key ending in `*` matches every class with that prefix, and carries the rest over: `ml-*: ms-*`.
403
400
  def initialize(options)
404
401
  super
405
- prefixed, exact = options[:classes].partition { |deprecated,| deprecated.end_with?("*") }
402
+ prefixed, exact = Hash(options[:classes]).partition { |deprecated,| deprecated.end_with?("*") }
406
403
  @replacement_by_class = exact.to_h
407
- @prefixed_replacements = prefixed.map { |deprecated, replacement| [deprecated.delete_suffix("*"), replacement] }
404
+ # The longest prefix wins: `badge-light-*` over `badge-*`.
405
+ @prefixed_replacements = prefixed.map { |deprecated, replacement| [deprecated.delete_suffix("*"), replacement] }.sort_by { -_1.first.size }
408
406
  end
409
407
 
410
408
  def offenses(document, _source)
411
- return [] if options[:classes].empty?
409
+ return [] if @replacement_by_class.empty? && @prefixed_replacements.empty?
412
410
 
413
411
  enum_for(:each_tag, document).flat_map do |tag,|
414
412
  literal_attributes(tag, "class").flat_map { literal_value(_1).split }.filter_map do |css_class|
@@ -432,15 +430,19 @@ module SuperSlim
432
430
  class DeprecatedAttributes < Rule
433
431
  DEFAULTS = {enabled: true, attributes: {}}.freeze
434
432
 
433
+ def initialize(options)
434
+ super
435
+ @replacement_by_attribute = Hash(options[:attributes])
436
+ end
437
+
435
438
  def offenses(document, _source)
436
- replacement_by_attribute = options[:attributes]
437
- return [] if replacement_by_attribute.empty?
439
+ return [] if @replacement_by_attribute.empty?
438
440
 
439
441
  enum_for(:each_tag, document).flat_map do |tag,|
440
442
  attribute_names(tag).filter_map do |name|
441
- next unless replacement_by_attribute.key?(name)
443
+ next unless (replacement = @replacement_by_attribute[name])
442
444
 
443
- offense(document, document.line_of(tag), "`#{name}` is deprecated: use `#{replacement_by_attribute[name]}`")
445
+ offense(document, document.line_of(tag), "`#{name}` is deprecated: use `#{replacement}`")
444
446
  end
445
447
  end
446
448
  end
@@ -516,7 +518,7 @@ module SuperSlim
516
518
 
517
519
  def offenses(document, _source)
518
520
  document.enum_for(:each_node).filter_map do |node, ancestors|
519
- next unless node.is_a?(AST::TextBlock) && ancestors.none?(AST::Comment)
521
+ next unless node.is_a?(AST::TextBlock) && !ancestors.inside_comment
520
522
 
521
523
  text = node.children.grep(AST::Text).map(&:text).join(" ").gsub(/\s+/, " ").strip
522
524
  next unless text.gsub(NOT_WORDS, "").match?(/\p{L}/)
@@ -556,7 +558,7 @@ module SuperSlim
556
558
 
557
559
  text = $2
558
560
  lineno = document.line_of(node)
559
- message = if text.match?(READ_AS_SYNTAX_AFTER_TAG) && ancestors.any? && document.line_of(ancestors.last) == lineno
561
+ message = if text.match?(READ_AS_SYNTAX_AFTER_TAG) && ancestors.last && document.line_of(ancestors.last) == lineno
560
562
  "Write the text `| #{text}` on its own line, under the tag: inline, it would read as attributes"
561
563
  else
562
564
  "Write the text `| #{text}` instead of outputting a string"