super-slim 3.2.2 → 3.4.0

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.
@@ -12,38 +12,85 @@ module SuperSlim
12
12
  class Formatter
13
13
  INDENT_WIDTH = 2
14
14
  CONTROL = /\A-\s*/
15
+ NEGATED_IF = /\A- if !(?!=)\s*(\S.*)\z/
16
+ COMPOUND_CONDITION = %r{[=<>+*/%&|^~#]|\?\s|\s-\s|:\s|\b(?:and|or|not|then|do)\b}
17
+ ELSE_LINE = /\A\s*-\s*(?:else|elsif)\b/
15
18
  OUTPUT = /\A(==?)([<>]*)\s*/
16
19
  TAG_OUTPUT = /\A\s*(==?)(['<>]*)\s*/
17
20
  REDUNDANT_DIV = /\Adiv(?=[.#][\p{Word}-])/
21
+ LOCALS_HEADER = %r{\A?/#\s*locals:}
22
+ CODE_LINE = /\A(?:-|==?[<>]*) (.+)\z/
23
+ CONTROL_CODE = /\A\s*-\s*(\S.*)/
24
+ # The threshold of the ConsecutiveControlStatements lint rule, plus one.
25
+ RUBY_BLOCK_MIN_LINES = 3
26
+ RUBY_BLOCK = /\A\s*ruby:\s*\z/
27
+ CONTROL_RUN = /^( *)- .*\n\1- .*\n\1- /
28
+ # `while x do` is valid Ruby that nobody writes.
29
+ LOOP = /\A(?:while|until|for)\b/
30
+ END_KEYWORD = /\Aend\b/
18
31
  # Prism 1.x counts in a node's flags whether it starts a line.
19
32
  NEWLINE_FLAG = defined?(Prism::NodeFlags::NEWLINE) ? Prism::NodeFlags::NEWLINE : 0
20
33
  FIELDS_BY_NODE_CLASS = {}
34
+ COMPARATOR_BY_NODE_CLASS = {}
21
35
 
22
36
  def self.call(source, **)
23
37
  new(**).call(source)
24
38
  end
25
39
 
40
+ # Slim's own test for a block: children that render something, a comment alone opens none.
41
+ def self.block_opening_linenos(parser)
42
+ parser.line_by_node.filter_map do |node, lineno|
43
+ lineno if (node.is_a?(AST::Output) || node.is_a?(AST::Control)) && !AST.empty?(node.children)
44
+ end.to_set
45
+ end
46
+
47
+ # Slim opens a block when Ruby code has children, but only `do` shows that the call takes one. A `#` may start a
48
+ # comment, which `do` would land in.
49
+ def self.with_do(content)
50
+ code = content[CODE_LINE, 1]
51
+ return content if code.nil? || code.include?("#") || code.end_with?("{", "|", ",", "\\", ";", "&&", "||")
52
+ return content if code.match?(Compiler::BLOCK_SELF_OPENING) || code.match?(LOOP)
53
+
54
+ "#{content} do"
55
+ end
56
+
26
57
  def initialize(tailwind_classes: SuperSlim.tailwind_classes, max_line_length: nil, attribute_delimiters: "()")
27
58
  @tailwind_classes = tailwind_classes
28
59
  @line_wrapper = LineWrapper.new(max_line_length, tailwind_classes:, attribute_delimiters:) if max_line_length
29
60
  end
30
61
 
31
62
  def call(source)
32
- formatted = layout(source)
33
- formatted_ruby = compiled_ruby(formatted) unless formatted == source
34
- if formatted_ruby && !same_ruby?(compiled_ruby(source), formatted_ruby)
35
- raise UnsafeFormattingError, "Formatting would change how this template renders"
63
+ parser = Parser.new(outline: true, tailwind_classes: @tailwind_classes)
64
+ nodes = parser.call(source)
65
+ formatted = layout(source, parser)
66
+ unless formatted == source
67
+ source_code = compiled_code(nodes)
68
+ nodes, parser = parsed_template(formatted)
69
+ formatted_code = compiled_code(nodes)
70
+ # Most templates the layout changes compile to the very same Ruby: only the others are parsed.
71
+ unless source_code.is_a?(String) && source_code == formatted_code
72
+ formatted_ruby = parsed_ruby(formatted_code)
73
+ raise UnsafeFormattingError, "Formatting would change how this template renders" unless same_ruby?(parsed_ruby(source_code), formatted_ruby)
74
+ end
36
75
  end
37
76
  return formatted unless @line_wrapper
38
77
 
39
- wrapped = @line_wrapper.call(formatted)
78
+ wrapped = @line_wrapper.call(formatted, parser:)
40
79
  return formatted if wrapped == formatted
41
80
 
42
- wrapped_ruby = compiled_ruby(wrapped)
81
+ # `-` code joined by the wrapper may now make a run long enough for a `ruby:` block. A wrap Slim can't read is
82
+ # refused below.
83
+ if wrapped.match?(CONTROL_RUN)
84
+ wrapped_parser = parsed_template(wrapped).last
85
+ wrapped = layout(wrapped, wrapped_parser) if wrapped_parser
86
+ end
87
+
88
+ wrapped_ruby = parsed_ruby(compiled_code(parsed_template(wrapped, outline: false).first))
43
89
  # Only Prism's tree vouches for a wrap: a compile error can read the same before and after it.
44
90
  return formatted unless wrapped_ruby.is_a?(Prism::ParseResult)
45
91
 
46
- same_ruby?(formatted_ruby || compiled_ruby(formatted), wrapped_ruby) ? wrapped : formatted
92
+ formatted_ruby ||= parsed_ruby(formatted_code || compiled_code(nodes))
93
+ same_ruby?(formatted_ruby, wrapped_ruby) ? wrapped : formatted
47
94
  # Prism walks code recursively too: code nested thousands deep can't be checked, so it isn't formatted.
48
95
  rescue SystemStackError
49
96
  raise UnsafeFormattingError, "Code nested too deep to check that formatting changes nothing"
@@ -51,25 +98,71 @@ module SuperSlim
51
98
 
52
99
  private
53
100
 
54
- def layout(source)
55
- parser = Parser.new(outline: true, tailwind_classes: @tailwind_classes)
56
- parser.call(source)
57
- lines = source.delete_prefix("").split(/\r?\n/)
101
+ def layout(source, parser)
102
+ source = source.delete_prefix("")
103
+ lines = Parser.split_lines(source)
58
104
 
105
+ outline = parser.outline
106
+ unformatted_linenos = Parser.unformatted_linenos(lines, outline)
107
+ first_structure_lineno = (1...outline.size).find { outline[_1].kind == :structure }
108
+ # A partial's signature reads like a method's: alone at the top, set apart from the body.
109
+ locals_header_lineno = first_structure_lineno if first_structure_lineno && lines[first_structure_lineno - 1].match?(LOCALS_HEADER)
110
+ block_opening_linenos = Formatter.block_opening_linenos(parser)
59
111
  formatted = []
60
112
  indent_shift_by_lineno = {}
113
+ indent_shift = 0
114
+ previous_structure_lineno = nil
115
+ blank_line_pending = false
116
+ # [depth, levels]: the children of a line whose inline tags were spread go that many levels deeper.
117
+ spread_levels = []
118
+ code_lines_by_lineno, rewritten_linenos = ruby_code_layout(lines, outline, parser, unformatted_linenos)
61
119
  lines.each.with_index(1) do |line, lineno|
62
- info = parser.outline[lineno]
120
+ next if rewritten_linenos.include?(lineno)
121
+
122
+ info = outline[lineno]
123
+ # Unformatted lines move with the directive above them, so that they stay inside its block.
124
+ if unformatted_linenos.include?(lineno)
125
+ blank_line_pending = false
126
+ next formatted << shifted(line, indent_shift)
127
+ end
128
+
63
129
  case info.kind
64
130
  when :blank
65
131
  formatted << "" unless formatted.empty? || formatted.last.empty?
132
+ blank_line_pending = formatted.last == ""
66
133
  when :text_blank
67
134
  formatted << ""
135
+ blank_line_pending = false
68
136
  when :structure
69
- indent = info.depth * INDENT_WIDTH
70
- indent_shift_by_lineno[lineno] = indent - indent_of(line)
71
- formatted << (" " * indent) + structure(line, info)
137
+ previous_info = outline[previous_structure_lineno] if previous_structure_lineno
138
+ # A block's first line comes right after the line that opens it.
139
+ formatted.pop if blank_line_pending && previous_info && info.depth > previous_info.depth
140
+ formatted << "" if previous_structure_lineno && previous_structure_lineno == locals_header_lineno && formatted.last != ""
141
+ spread_levels.pop while spread_levels.last && info.depth <= spread_levels.last[0]
142
+ depth = info.depth + spread_levels.sum { |_depth, levels| levels }
143
+ indent = depth * INDENT_WIDTH
144
+ indent_shift = indent_shift_by_lineno[lineno] = indent - indent_of(line)
145
+ next_info = outline[lineno + 1]
146
+ if (code_lines = code_lines_by_lineno[lineno])
147
+ formatted.concat(code_lines.map { (" " * indent) + _1 })
148
+ elsif info.nested_tag_columns && !(goes_on?(outline, lineno) && next_info.kind != :continuation)
149
+ nested_lines = spread_nested_tags(line, info, depth)
150
+ levels = nested_lines.size - 1
151
+ spread_levels << [info.depth, levels]
152
+ # Attributes going on over the next lines belong to the last tag, and go as many levels deeper.
153
+ indent_shift_by_lineno[lineno] += levels * INDENT_WIDTH
154
+ formatted.concat(nested_lines)
155
+ else
156
+ content = structure(line, info)
157
+ # Code that goes on over more lines takes its `do` once the line wrapper joins it.
158
+ content = Formatter.with_do(content) if block_opening_linenos.include?(lineno) && !info.text && next_info&.kind != :continuation
159
+ content = unless_for_negated_if(content, lines, outline, lineno) if content.start_with?("- if !")
160
+ formatted << (" " * indent) + content
161
+ end
162
+ previous_structure_lineno = lineno
163
+ blank_line_pending = false
72
164
  else
165
+ blank_line_pending = false
73
166
  formatted << continuation(line, info, indent_shift_by_lineno.fetch(info.owner, 0))
74
167
  end
75
168
  end
@@ -77,6 +170,30 @@ module SuperSlim
77
170
  formatted.empty? ? "" : "#{formatted.join("\n")}\n"
78
171
  end
79
172
 
173
+ # `- if !condition` reads as `- unless condition` when the `!` covers the whole condition and no `else` follows,
174
+ # as RuboCop's Style/NegatedIf asks. A condition holding an operator, a ternary or a keyword keeps its `!`:
175
+ # `!a == b` compares `!a`.
176
+ def unless_for_negated_if(content, lines, outline, lineno)
177
+ condition = content[NEGATED_IF, 1]
178
+ return content if condition.nil? || condition.start_with?("(", "!") || condition.match?(COMPOUND_CONDITION)
179
+ return content if else_follows?(lines, outline, lineno)
180
+
181
+ "- unless #{condition}"
182
+ end
183
+
184
+ def else_follows?(lines, outline, lineno)
185
+ depth = outline[lineno].depth
186
+ ((lineno + 1)...outline.size).each do |next_lineno|
187
+ info = outline[next_lineno]
188
+ next unless info.kind == :structure && info.depth <= depth
189
+ # A comment between the `if` and its `else` renders nothing.
190
+ next if lines[next_lineno - 1].match?(Parser::CODE_COMMENT)
191
+
192
+ return info.depth == depth && lines[next_lineno - 1].match?(ELSE_LINE)
193
+ end
194
+ false
195
+ end
196
+
80
197
  def structure(line, info)
81
198
  content = with_output_spacing(line, info).lstrip
82
199
  content = content.rstrip unless info.text
@@ -88,6 +205,78 @@ module SuperSlim
88
205
  end
89
206
  end
90
207
 
208
+ # One threshold, both ways: `-` lines and `ruby:` blocks next to each other, at one depth, make one run of code
209
+ # lines; three lines or more go in a `ruby:` block, fewer go on `-` lines. Only lines of Ruby complete on their
210
+ # own move, with no block and no comment. Returns the lines that replace each run's first line, and the line
211
+ # numbers they replace.
212
+ def ruby_code_layout(lines, outline, parser, unformatted_linenos)
213
+ # [first line number, last line number, depth, code lines]
214
+ code_units = parser.line_by_node.filter_map do |node, lineno|
215
+ case node
216
+ when AST::Control
217
+ code = control_code(lines[lineno - 1]) if AST.empty?(node.children)
218
+ [lineno, lineno, outline[lineno].depth, [code]] if code && movable_code?(code) && !goes_on?(outline, lineno)
219
+ when AST::Embedded
220
+ next unless node.engine == "ruby" && lines[lineno - 1].match?(RUBY_BLOCK)
221
+
222
+ body_linenos = ((lineno + 1)...outline.size).take_while { outline[_1].owner == lineno }
223
+ body = body_linenos.map { lines[_1 - 1].strip }
224
+ [lineno, body_linenos.last, outline[lineno].depth, body] if body.any? && body_linenos.all? { outline[_1].kind == :text } && body.all? { movable_code?(_1) }
225
+ end
226
+ end
227
+ # `format off` keeps its lines as written.
228
+ code_units.reject! { |first_lineno, last_lineno| (first_lineno..last_lineno).any? { unformatted_linenos.include?(_1) } }
229
+ runs = code_units.sort_by!(&:first).chunk_while { |unit, next_unit| next_unit[0] == unit[1] + 1 && next_unit[2] == unit[2] }
230
+ code_lines_by_lineno = {}
231
+ rewritten_linenos = Set.new
232
+ runs.each do |run|
233
+ code_size = run.sum { _1[3].size }
234
+ ruby_blocks = run.count { _1[0] != _1[1] }
235
+ # Already in its layout: a lone `ruby:` block long enough, or `-` lines too few.
236
+ next if (run.size == 1 && ruby_blocks == 1 && code_size >= RUBY_BLOCK_MIN_LINES) || (ruby_blocks.zero? && code_size < RUBY_BLOCK_MIN_LINES)
237
+
238
+ # A line Prism can't read alone stays where it is, and splits the run.
239
+ run.chunk { |unit| unit[3].all? { Prism.parse(_1).success? } }.each do |parsable, units|
240
+ code = units.flat_map(&:last)
241
+ ruby_block = code.size >= RUBY_BLOCK_MIN_LINES
242
+ layout_changes = ruby_block || units.any? { _1[0] != _1[1] }
243
+ next unless parsable && layout_changes
244
+
245
+ code_lines_by_lineno[units.first[0]] = ruby_block ? ["ruby:", *code.map { (" " * INDENT_WIDTH) + _1 }] : code.map { "- #{_1}" }
246
+ rewritten_linenos.merge((units.first[0] + 1)..units.last[1])
247
+ end
248
+ end
249
+ [code_lines_by_lineno, rewritten_linenos]
250
+ end
251
+
252
+ def goes_on?(outline, lineno)
253
+ next_info = outline[lineno + 1]
254
+ next_info&.owner == lineno && next_info.kind != :blank
255
+ end
256
+
257
+ def control_code(line)
258
+ line[CONTROL_CODE, 1]&.rstrip
259
+ end
260
+
261
+ def movable_code?(code)
262
+ !code.include?("#") && !code.match?(Compiler::BLOCK_SELF_OPENING) && !code.match?(END_KEYWORD)
263
+ end
264
+
265
+ # `tr: td = total` nests each tag in the one before: one per line, whatever the line holds. A line whose text goes
266
+ # on over the next ones keeps its inline tags, so that the text stays where it belongs.
267
+ def spread_nested_tags(line, info, depth)
268
+ starts = [0, *info.nested_tag_columns.map(&:last)]
269
+ ends = [*info.nested_tag_columns.map(&:first), line.size]
270
+ starts.zip(ends).each_with_index.map do |(start, finish), level|
271
+ last = level == starts.size - 1
272
+ tag_info = info.dup.tap do |nested_info|
273
+ nested_info.text = nil unless last
274
+ nested_info.output_column = (last && info.output_column) ? info.output_column - start : nil
275
+ end
276
+ (" " * ((depth + level) * INDENT_WIDTH)) + structure(line[start...finish], tag_info)
277
+ end
278
+ end
279
+
91
280
  def continuation(line, info, indent_shift)
92
281
  line = with_output_spacing(expand_tabs(line), info)
93
282
  indent = [line[/\A */].size + indent_shift, 0].max
@@ -96,6 +285,13 @@ module SuperSlim
96
285
  (" " * indent) + content
97
286
  end
98
287
 
288
+ def shifted(line, indent_shift)
289
+ line = expand_tabs(line)
290
+ return "" if line.strip.empty?
291
+
292
+ (" " * [line[/\A */].size + indent_shift, 0].max) + line.lstrip
293
+ end
294
+
99
295
  def with_output_spacing(line, info)
100
296
  return line unless info.output_column && line[info.output_column..] =~ TAG_OUTPUT
101
297
 
@@ -108,18 +304,35 @@ module SuperSlim
108
304
  end
109
305
 
110
306
  def expand_tabs(line)
307
+ return line unless line.include?("\t")
308
+
111
309
  line.sub(/\A[ \t]*/) { _1.gsub(Parser::TAB, "\\1#{" " * Parser::TAB_SIZE}") }
112
310
  end
113
311
 
312
+ # The template's nodes and its parser, which holds the outline; the error when it doesn't parse.
313
+ def parsed_template(template, outline: true)
314
+ parser = Parser.new(outline:, tailwind_classes: @tailwind_classes)
315
+ [parser.call(template), parser]
316
+ rescue Error => exception
317
+ [exception, nil]
318
+ end
319
+
320
+ # The Ruby the nodes compile to, their attributes sorted by name; the error when they don't parse or compile.
321
+ def compiled_code(nodes)
322
+ return nodes if nodes.is_a?(Error)
323
+
324
+ Compiler.new(format: :xml).call(with_attributes_sorted_by_name(nodes))
325
+ rescue Error => exception
326
+ exception
327
+ end
328
+
114
329
  # Prism's tree of the compiled Ruby; that Ruby with its separators folded when Prism can't read it; the error
115
- # when the template doesn't compile.
116
- def compiled_ruby(source)
117
- nodes = Parser.new(tailwind_classes: @tailwind_classes).call(source)
118
- code = Compiler.new(format: :xml).call(with_attributes_sorted_by_name(nodes))
330
+ # message when the template doesn't compile.
331
+ def parsed_ruby(code)
332
+ return code.message if code.is_a?(Error)
333
+
119
334
  parsed = Prism.parse("#{CodeWrapper::TEMPLATE_METHOD}#{code}\nend")
120
335
  parsed.success? ? parsed : code.gsub(/(?:\s*[;\n]\s*)+/, ";")
121
- rescue Error => exception
122
- exception.message
123
336
  end
124
337
 
125
338
  # A tag renders the same whatever the order of its attributes, and with a class shortcut named twice once: both
@@ -149,52 +362,98 @@ module SuperSlim
149
362
  same_node?(ruby.value, other_ruby.value) && comment_texts(ruby) == comment_texts(other_ruby)
150
363
  end
151
364
 
152
- # Walks both trees with a stack of its own: deep code or a deep template would exhaust Ruby's.
365
+ # Walks both trees with a stack of its own, the two values of each pair pushed one after the other: deep code or
366
+ # a deep template would exhaust Ruby's.
153
367
  def same_node?(node, other_node)
154
- pairs = [[node, other_node]]
155
- until pairs.empty?
156
- value, other_value = pairs.pop
368
+ pending_values = [node, other_node]
369
+ until pending_values.empty?
370
+ other_value = pending_values.pop
371
+ value = pending_values.pop
157
372
  case value
158
373
  when Prism::Node
159
- return false unless value.instance_of?(other_value.class)
160
- return false unless same_node_value?(value, other_value)
374
+ if value.instance_of?(other_value.class)
375
+ return false unless node_comparator(value).call(value, other_value, pending_values)
376
+ else
377
+ pairs = negated_if_pairs(value, other_value) or return false
378
+ pending_values.concat(pairs)
379
+ end
161
380
  when Array
162
381
  return false unless other_value.is_a?(Array) && value.size == other_value.size
382
+
383
+ index = 0
384
+ while index < value.size
385
+ pending_values << value[index] << other_value[index]
386
+ index += 1
387
+ end
163
388
  else
164
389
  return false unless value == other_value
165
-
166
- next
167
390
  end
168
- pairs.concat(children_pairs(value, other_value).reverse)
169
391
  end
170
392
  true
171
393
  end
172
394
 
173
- def same_node_value?(node, other_node)
174
- # `__LINE__` holds no value in the tree: removing a blank line above it changes what it renders.
175
- return node.location.start_line == other_node.location.start_line if node.is_a?(Prism::SourceLineNode)
395
+ # `if !x` and `unless x` with no else run the same code, as RuboCop's Style/NegatedIf holds: the condition and the
396
+ # body still have to match. Only an object that redefines `!` tells them apart. Prism 0.19 names the else
397
+ # branch `consequent`.
398
+ def negated_if_pairs(node, other_node)
399
+ if_node, unless_node = node.is_a?(Prism::IfNode) ? [node, other_node] : [other_node, node]
400
+ return unless if_node.is_a?(Prism::IfNode) && unless_node.is_a?(Prism::UnlessNode)
176
401
 
177
- field_names, located_names, flagged = node_fields(node)
178
- return false if flagged && (node.send(:flags) & ~NEWLINE_FLAG) != (other_node.send(:flags) & ~NEWLINE_FLAG)
179
- # 2026-11: Prism 0.19 (Ruby 3.3) keeps the value of an integer or a float out of its fields.
180
- return node.value == other_node.value if field_names.empty? && (node.is_a?(Prism::IntegerNode) || node.is_a?(Prism::FloatNode))
402
+ negation = if_node.predicate
403
+ return unless negation.is_a?(Prism::CallNode) && negation.name == :! && negation.message == "!" && negation.arguments.nil?
404
+ return if if_node.respond_to?(:subsequent) ? if_node.subsequent : if_node.consequent
405
+ return if unless_node.respond_to?(:else_clause) ? unless_node.else_clause : unless_node.consequent
181
406
 
182
- located_names.all? { |name| same_name?(node.public_send(name), other_node.public_send(name)) }
407
+ [negation.receiver, unless_node.predicate, if_node.statements, unless_node.statements]
183
408
  end
184
409
 
185
- def children_pairs(value, other_value)
186
- return value.zip(other_value) if value.is_a?(Array)
187
- return [] if value.is_a?(Prism::SourceLineNode)
188
-
189
- node_fields(value).first.map { |name| [value.public_send(name), other_value.public_send(name)] }
410
+ def node_comparator(node)
411
+ COMPARATOR_BY_NODE_CLASS[node.class] ||= Formatter.send(:comparator_for, node.class, *node_fields(node))
190
412
  end
191
413
 
192
- # Beside a location, a field holds either a name or, from Prism 2 on, the source the location covers
193
- # (`opening` beside `opening_loc`): only the name counts.
194
- def same_name?(name, other_name)
195
- return true unless name.is_a?(Symbol) || other_name.is_a?(Symbol)
414
+ class << self
415
+ private
416
+
417
+ # Compares what two nodes of one class hold besides their children, and pushes their children on `pending_values`.
418
+ def comparator_for(node_class, field_names, located_names, flagged)
419
+ if node_class <= Prism::SourceLineNode
420
+ # `__LINE__` holds no value in the tree: removing a blank line above it changes what it renders.
421
+ ->(source_line, other_source_line, _pending_values) { source_line.location.start_line == other_source_line.location.start_line }
422
+ elsif field_names.empty? && (node_class <= Prism::IntegerNode || node_class <= Prism::FloatNode)
423
+ # 2026-11: Prism 0.19 (Ruby 3.3) keeps the value of an integer or a float out of its fields.
424
+ ->(number, other_number, _pending_values) { (!flagged || same_flags?(number, other_number)) && number.value == other_number.value }
425
+ else
426
+ clauses = []
427
+ clauses << "same_flags?(value, other_value)" if flagged
428
+ located_names.each { |name| clauses << "same_name?(value.#{name}, other_value.#{name})" }
429
+ pushes = field_names.map { |name| "pending_values << value.#{name} << other_value.#{name}" }
430
+ # Fields unrolled, without public_send: 2.5x faster with YJIT. The names come from Prism's own classes.
431
+ lambda_from(<<~LAMBDA)
432
+ ->(value, other_value, pending_values) do
433
+ #{"return false unless #{clauses.join(" && ")}" unless clauses.empty?}
434
+ #{pushes.join("\n")}
435
+ true
436
+ end
437
+ LAMBDA
438
+ end
439
+ end
440
+
441
+ # Evaluated here, the lambda holds no local but its own source.
442
+ def lambda_from(code)
443
+ eval(code, binding, __FILE__, __LINE__) # rubocop:disable Security/Eval
444
+ end
196
445
 
197
- name == other_name
446
+ def same_flags?(node, other_node)
447
+ (node.send(:flags) & ~NEWLINE_FLAG) == (other_node.send(:flags) & ~NEWLINE_FLAG)
448
+ end
449
+
450
+ # Beside a location, a field holds either a name or, from Prism 2 on, the source the location covers
451
+ # (`opening` beside `opening_loc`): only the name counts.
452
+ def same_name?(name, other_name)
453
+ return true unless name.is_a?(Symbol) || other_name.is_a?(Symbol)
454
+
455
+ name == other_name
456
+ end
198
457
  end
199
458
 
200
459
  # 2026-11: Prism 0.19 (Ruby 3.3) has no reflection API: the field names come from the first node of each
@@ -13,13 +13,12 @@ module SuperSlim
13
13
 
14
14
  class Rule
15
15
  DEFAULTS = {enabled: true}.freeze
16
+ GLOB_FLAGS = File::FNM_PATHNAME | File::FNM_EXTGLOB | File::FNM_DOTMATCH
16
17
 
17
18
  def self.rule_name
18
19
  @rule_name ||= name.split("::").last
19
20
  end
20
21
 
21
- GLOB_FLAGS = File::FNM_PATHNAME | File::FNM_EXTGLOB | File::FNM_DOTMATCH
22
-
23
22
  def initialize(options)
24
23
  @options = options
25
24
  end
@@ -218,11 +217,11 @@ module SuperSlim
218
217
  sibling_lists = [document.nodes, *document.visits.filter_map { |node,| Document.children_of(node) }]
219
218
  sibling_lists.select! { |siblings| siblings.count { flat_control?(_1) } > options[:max] }
220
219
  sibling_lists.flat_map do |siblings|
221
- siblings.chunk_while { |control, following| flat_control?(control) && flat_control?(following) }
222
- .filter_map do
223
- next unless _1.size > options[:max] && flat_control?(_1.first)
220
+ siblings.chunk_while { |node, following| flat_control?(node) && flat_control?(following) }
221
+ .filter_map do |run|
222
+ next unless run.size > options[:max] && flat_control?(run.first)
224
223
 
225
- offense(document, document.line_of(_1.first), "Merge these #{_1.size} lines of Ruby into a `ruby:` block")
224
+ offense(document, document.line_of(run.first), "Merge these #{run.size} lines of Ruby into a `ruby:` block")
226
225
  end
227
226
  end
228
227
  end
@@ -280,7 +279,7 @@ module SuperSlim
280
279
  class DuplicateId < Rule
281
280
  def offenses(document, _source)
282
281
  branch_by_id = {}
283
- enum_for(:each_tag, document).filter_map do |tag, ancestors|
282
+ enum_for(:each_tag, document).flat_map do |tag, ancestors|
284
283
  branch = ancestors.control
285
284
  literal_attributes(tag, "id").filter_map do |attribute|
286
285
  id = literal_value(attribute)
@@ -291,7 +290,7 @@ module SuperSlim
291
290
  nil
292
291
  end
293
292
  end
294
- end.flatten
293
+ end
295
294
  end
296
295
  end
297
296
 
@@ -360,6 +359,22 @@ module SuperSlim
360
359
  end
361
360
  end
362
361
 
362
+ # Slim renders `aria-atomic=true` as a bare `aria-atomic` and drops `aria-hidden=false`: ARIA reads the string.
363
+ class AriaBooleanValue < Rule
364
+ BOOLEAN_CODES = %w[true false].freeze
365
+
366
+ def offenses(document, _source)
367
+ enum_for(:each_tag, document).flat_map do |tag,|
368
+ tag.attributes.filter_map do |attribute|
369
+ next unless attribute.is_a?(AST::CodeAttribute) && attribute.name.start_with?("aria-")
370
+ next unless BOOLEAN_CODES.include?(value = attribute.code.strip)
371
+
372
+ offense(document, document.line_of(tag), "Write `#{attribute.name}=\"#{value}\"`: Slim renders `#{attribute.name}=#{value}` #{(value == "true") ? "without a value" : "as no attribute at all"}")
373
+ end
374
+ end
375
+ end
376
+ end
377
+
363
378
  class AriaRole < Rule
364
379
  ROLES = %w[alert alertdialog application article banner blockquote button caption cell checkbox code columnheader
365
380
  combobox complementary contentinfo definition deletion dialog document emphasis feed figure form generic
@@ -537,6 +552,30 @@ module SuperSlim
537
552
  end
538
553
  end
539
554
 
555
+ # Brakeman parses views with Slim, which refuses these lines: it reports the template and checks nothing in it.
556
+ class SlimSyntax < Rule
557
+ MESSAGE = "Slim, and so Brakeman, cannot read"
558
+
559
+ def offenses(document, _source)
560
+ document.enum_for(:each_node).filter_map do |node, ancestors|
561
+ next unless node.is_a?(AST::Output) || node.is_a?(AST::Control)
562
+ next unless (reason = reason_of(node.code))
563
+
564
+ offense(document, line_near(document, node, ancestors), "#{MESSAGE} #{reason}")
565
+ end
566
+ end
567
+
568
+ private
569
+
570
+ def reason_of(code)
571
+ if !Parser.slim_continuation?(code.split("\n"))
572
+ "code continued after an opening bracket: end each line but the last with a comma"
573
+ elsif Parser::RubyBrackets.code_comment_offset(code)
574
+ "a comment after code: move it to a line of its own"
575
+ end
576
+ end
577
+ end
578
+
540
579
  # Ruby that a plainer line of Slim says better, after haml-lint.
541
580
 
542
581
  class UnnecessaryInterpolation < Rule
@@ -46,6 +46,13 @@ module SuperSlim
46
46
  visits
47
47
  end
48
48
 
49
+ def self.children_of(node)
50
+ case node
51
+ when AST::Tag then node.content
52
+ when AST::Control, AST::Output, AST::TextBlock, AST::Comment, AST::InlineHtml, AST::Embedded then node.children
53
+ end
54
+ end
55
+
49
56
  def partial?
50
57
  File.basename(path.to_s).start_with?("_")
51
58
  end
@@ -60,16 +67,12 @@ module SuperSlim
60
67
 
61
68
  def each_node(&) = visits.each(&)
62
69
  def each_tag(&) = tag_visits.each(&)
63
-
64
- def self.children_of(node)
65
- case node
66
- when AST::Tag then node.content
67
- when AST::Control, AST::Output, AST::TextBlock, AST::Comment, AST::InlineHtml, AST::Embedded then node.children
68
- end
69
- end
70
70
  end
71
71
 
72
72
  CONFIG_FILE = ".super-slim.yml"
73
+ DISABLE_DIRECTIVE = %r{\A?\s*/\s*super-slim:disable\s+(\S.*?)\s*\z}
74
+ # The layout rules: what `super-slim format` rewrites.
75
+ LAYOUT_RULE_NAMES = %w[Indentation Tab TrailingWhitespace EmptyLines ControlStatementSpacing RedundantDiv].freeze
73
76
  GLOB_OPTIONS = %w[include exclude].freeze
74
77
 
75
78
  def self.load(directory = Dir.pwd)
@@ -114,11 +117,15 @@ module SuperSlim
114
117
  parser = Parser.new(file: path, outline: true)
115
118
  nodes = parser.call(source)
116
119
  visits = Document.visits_of(nodes, parser.line_by_node)
117
- lines = source.include?("\r") ? source.split(/\r?\n/) : source.split("\n")
120
+ lines = Parser.split_lines(source)
118
121
  document = Document.new(path:, lines:, nodes:, outline: parser.outline, line_by_node: parser.line_by_node,
119
122
  visits:, tag_visits: visits.select { |node,| node.is_a?(AST::Tag) })
120
123
  relative_path = File.expand_path(path).delete_prefix(@root)
121
124
  offenses = @rules.select { _1.applies_to?(relative_path) }.flat_map { _1.offenses(document, source) }
125
+ disabled_rules_by_lineno, directive_offenses = disable_directives(document, source)
126
+ # The layout rules ask for what `super-slim format` would do, which format off turns down.
127
+ Parser.unformatted_linenos(lines, parser.outline).each { disabled_rules_by_lineno[_1].concat(LAYOUT_RULE_NAMES) }
128
+ offenses = offenses.reject { disabled_rules_by_lineno.fetch(_1.lineno, []).include?(_1.rule) } + directive_offenses
122
129
  # sort_by is not stable: the index keeps offenses of one line in rule order.
123
130
  offenses.each_with_index.sort_by { |offense, index| [offense.lineno.to_i, index] }.map(&:first)
124
131
  rescue SyntaxError => exception
@@ -127,6 +134,32 @@ module SuperSlim
127
134
 
128
135
  private
129
136
 
137
+ # `/ super-slim:disable Rule, OtherRule` silences those rules on the next line of the template's structure, comments
138
+ # skipped, and the lines it goes on over: a Slim comment can't share a line with a tag. A directive that silences
139
+ # nothing, for a misspelt rule or at the end of the template, is reported.
140
+ def disable_directives(document, source)
141
+ disabled_rules_by_lineno = Hash.new { |hash, lineno| hash[lineno] = [] }
142
+ offenses = []
143
+ return [disabled_rules_by_lineno, offenses] unless source.include?("super-slim:disable")
144
+
145
+ structure_linenos = (1..document.lines.size).select { document.outline[_1]&.kind == :structure }
146
+ known_rule_names = Rules.all.map(&:rule_name)
147
+ structure_linenos.each_with_index do |lineno, index|
148
+ next unless (rule_names = document.lines[lineno - 1][DISABLE_DIRECTIVE, 1])
149
+
150
+ rule_names = rule_names.scan(/[^\s,]+/)
151
+ (rule_names - known_rule_names).each do |rule_name|
152
+ offenses << Offense.new(document.path, lineno, "Directive", "`#{rule_name}` is not a rule of super-slim lint")
153
+ end
154
+ target_index = (index + 1...structure_linenos.size).find { !document.lines[structure_linenos[_1] - 1].match?(Parser::CODE_COMMENT) }
155
+ next offenses << Offense.new(document.path, lineno, "Directive", "No line follows to silence") unless target_index
156
+
157
+ next_lineno = structure_linenos[target_index + 1] || (document.lines.size + 1)
158
+ (structure_linenos[target_index]...next_lineno).each { disabled_rules_by_lineno[_1].concat(rule_names) }
159
+ end
160
+ [disabled_rules_by_lineno, offenses]
161
+ end
162
+
130
163
  # The preset's table goes under the rule's own entries, where `~` drops one of the preset.
131
164
  def with_preset(rule_name, options)
132
165
  preset_options = PRESETS.dig(options[:preset], rule_name)