super-slim 3.5.0 → 3.6.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 2a4173bef747a6dd40e852a6247cbe0060838b637edb0268faaaaa6c2ba047f0
4
- data.tar.gz: 12c36082a6c21e85e2021e892ff89b9d974c460bf63adf9a591f2b0ae71e09f6
3
+ metadata.gz: d1568a882b755a5b9ca670180181b338cae76cac844ba48f4dc8261fe7e34b9a
4
+ data.tar.gz: 82880eb76f27282dfe0a0ce6bdf0537f499542fd7a34b930cc7edf5053a83a85
5
5
  SHA512:
6
- metadata.gz: dbc8c86e31f77f5eb938395563215410dc339fda9dc08114961ee8c371ff60171094ac2fb0df9be277d5b5c073ba69c4cc5b29914738ee53e21021b5dfcbff7c
7
- data.tar.gz: 2f89d6ca844580be8eb7ae0b7ffe1b8568c8757c6d1f7fe57f0e0106e8a6e954ecab1f9a72f6278005767514d433df8b6242656ca8f6b13db79dee417e237943
6
+ metadata.gz: f8f4f4de4d758739431959ad1957e258cf4771bb25f366a88b5588aed634d04c34982538d340e1a7e26530e2b0ed1279d1710eae37440a5bdc661806caf652f7
7
+ data.tar.gz: 1bf1391bd1ba59fc6879ab4159b236f2a393caee9983db47d3b07b9ff949b38d356cd85ebfa86bbae71f2a791088b15b4f7c803f29ca3e57517ae510e8d86b18
data/CHANGELOG.md CHANGED
@@ -2,6 +2,48 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [3.6.1] — 2026-11-11
6
+
7
+ One fix: `InstanceVariables` no longer reports an `@` that no name follows.
8
+
9
+ **Fixed**
10
+ - `InstanceVariables` no longer reports ``Pass `@` to the partial as a local`` on an `@` that no name follows, as in
11
+ the `_form.html.slim` scaffold template simple_form installs, `= simple_form_for(@<%= singular_table_name %>)`. 3.6.0
12
+ did, 3.5.0 did not.
13
+
14
+ ## [3.6.0] — 2026-11-11
15
+
16
+ The linter reads all the Ruby of a template and `.super-slim.yml` is checked when it is read: `super-slim lint` may
17
+ report lines it passed before, and a configuration with a misspelt name or a wrong value now stops with an error.
18
+
19
+ **New**
20
+ - A rule, an option or a setting that `.super-slim.yml` misspells stops `lint` and `format` with a usage error that
21
+ names it and lists the known ones, instead of being ignored: `LineLenght:` left the limit at 120, and a rule carried
22
+ over from slim-lint, such as `RuboCop:`, did nothing. Rename or remove the entry.
23
+ - A wrong value in `.super-slim.yml` is reported with the setting it belongs to. `max: "120"`, `classes: [close]`,
24
+ `enabled: "false"`, `tailwind_classes: maybe`, `max_line_length: 0` and `attribute_delimiters: "<>"` failed on
25
+ every template, ended in a backtrace or were taken at their word.
26
+
27
+ **Fixed**
28
+ - `InstanceVariables` reads interpolated text, quoted attributes, inline HTML and `ruby:` blocks, not only `-` and `=`
29
+ lines and code attributes, and reports each variable on its own line when code spreads over several. An `@` in a
30
+ string, as in `"npm/@scope/package"`, is no longer taken for one.
31
+ - `UnusedLocals` no longer reports a local read in inline HTML, in an interpolation holding braces such as
32
+ `#{tags.map { |tag| tag.name }}`, in an attribute of `javascript:` or `css:`, or through
33
+ `binding.local_variable_get`.
34
+ - `UnescapedOutput` reports `href=="#{url}"`, `#{{}}` in a quoted attribute or in inline HTML, and `html_safe` or
35
+ `raw` inside an interpolation. `DatabaseQueries` and `UnnecessaryInterpolation` read interpolations holding braces,
36
+ and `HardcodedText` no longer takes their code for text.
37
+ - An offense inside an HTML comment (`/!`) at the top of a template is reported on its line, not without one.
38
+ - With `max_line_length`, `super-slim format` writes a template that `format --check` accepts. A second run could
39
+ rewrite a hash the first had spread, a call with two spaces before its first argument, the children of an output
40
+ moved onto its tag, or a `-` line joined beside a `ruby:` block. A template the wrapper changes takes about 30%
41
+ longer to format; one already formatted takes the same time.
42
+ - With `max_line_length`, a `- rescue` or `- ensure` line longer than the limit no longer makes `super-slim format`
43
+ refuse the template with a `NoMethodError`.
44
+ - Outside Rails, a dynamic tag with content, `*{tag: "section"} Hello`, no longer compiles to Ruby that warns under
45
+ `ruby -w`.
46
+
5
47
  ## [3.5.0] — 2026-11-08
6
48
 
7
49
  Six lint rules and a page that documents every rule. Four of the new rules are on by default, so `super-slim lint` may
@@ -266,7 +308,9 @@ renders what Slim 5 renders with `format: :html, sort_attrs: false`, byte for by
266
308
  - Ruby 3.3 or later, every Ruby still maintained, Rails 8.0 or 8.1 for the railtie, and strscan 3.1.1 or later,
267
309
  newer than the one Ruby 3.3 ships.
268
310
 
269
- [Unreleased]: https://github.com/levups/super-slim/compare/v3.5.0...HEAD
311
+ [Unreleased]: https://github.com/levups/super-slim/compare/v3.6.1...HEAD
312
+ [3.6.1]: https://github.com/levups/super-slim/compare/v3.6.0...v3.6.1
313
+ [3.6.0]: https://github.com/levups/super-slim/compare/v3.5.0...v3.6.0
270
314
  [3.5.0]: https://github.com/levups/super-slim/compare/v3.4.1...v3.5.0
271
315
  [3.4.1]: https://github.com/levups/super-slim/compare/v3.4.0...v3.4.1
272
316
  [3.4.0]: https://github.com/levups/super-slim/compare/v3.3.0...v3.4.0
data/README.md CHANGED
@@ -254,7 +254,8 @@ linters:
254
254
  ```
255
255
 
256
256
  Every rule accepts `include:` and `exclude:`, lists of glob patterns matched against paths relative to
257
- `.super-slim.yml` (`**/` matches any number of directories).
257
+ `.super-slim.yml` (`**/` matches any number of directories). A rule, an option or a setting the file misspells
258
+ stops `lint` and `format` with an error that names it, rather than being ignored.
258
259
 
259
260
  A comment silences rules on the next tag or code line, blank lines and comments skipped, and on the lines it goes on
260
261
  over. The linter reports a rule name it doesn't know:
@@ -83,6 +83,29 @@ module SuperSlim
83
83
  closing_by_opening
84
84
  end
85
85
 
86
+ # The text cut at its interpolations, as [:static, text] and [:dynamic, code, escape] parts: `#{{code}}` is not
87
+ # escaped, and its code comes without the inner braces.
88
+ def self.interpolation_parts(text)
89
+ return [[:static, text]] unless text.include?('#{')
90
+
91
+ closing_by_opening = closing_braces(text)
92
+ scanner = StringScanner.new(text)
93
+ parts = []
94
+ until scanner.eos?
95
+ if scanner.skip(ESCAPED_INTERPOLATION)
96
+ parts << [:static, '#{']
97
+ elsif scanner.match?(INTERPOLATION_START) && (closing = closing_by_opening[scanner.pos + 1])
98
+ code = text.byteslice(scanner.pos + 2...closing)
99
+ scanner.pos = closing + 1
100
+ escape = !code.match?(UNESCAPED_INTERPOLATION_CODE)
101
+ parts << [:dynamic, escape ? code : code[1..-2], escape]
102
+ else
103
+ parts << [:static, scanner.scan(INTERPOLATION_FREE_TEXT)]
104
+ end
105
+ end
106
+ parts
107
+ end
108
+
86
109
  private
87
110
 
88
111
  def compile_children(nodes)
@@ -142,7 +165,10 @@ module SuperSlim
142
165
  if @rails
143
166
  compile_children(output.children)
144
167
  else
145
- capture_into(new_variable) { compile_children(output.children) }
168
+ # The block returns what its children render.
169
+ captured = new_variable
170
+ capture_into(captured) { compile_children(output.children) }
171
+ emit_code(captured)
146
172
  end
147
173
  emit_code("end")
148
174
  emit_output(returned_value, output.escape)
@@ -307,7 +333,7 @@ module SuperSlim
307
333
  emit_code("#{value} = #{attribute.code}")
308
334
  [[:raw, "::SuperSlim::Runtime.class_value(#{value}, #{attribute.escape}, #{@html_safe})"]]
309
335
  when QuotedAttribute
310
- interpolation_parts(attribute.text).map do |kind, value, escape|
336
+ Compiler.interpolation_parts(attribute.text).map do |kind, value, escape|
311
337
  (kind == :static && attribute.escape) ? [:static, ERB::Escape.html_escape(value)] : [kind, value, escape]
312
338
  end
313
339
  end
@@ -351,28 +377,7 @@ module SuperSlim
351
377
  end
352
378
 
353
379
  def emit_interpolated(text)
354
- emit_parts(interpolation_parts(text))
355
- end
356
-
357
- def interpolation_parts(text)
358
- return [[:static, text]] unless text.include?('#{')
359
-
360
- closing_by_opening = Compiler.closing_braces(text)
361
- scanner = StringScanner.new(text)
362
- parts = []
363
- until scanner.eos?
364
- if scanner.skip(ESCAPED_INTERPOLATION)
365
- parts << [:static, '#{']
366
- elsif scanner.match?(INTERPOLATION_START) && (closing = closing_by_opening[scanner.pos + 1])
367
- code = text.byteslice(scanner.pos + 2...closing)
368
- scanner.pos = closing + 1
369
- escape = !code.match?(UNESCAPED_INTERPOLATION_CODE)
370
- parts << [:dynamic, escape ? code : code[1..-2], escape]
371
- else
372
- parts << [:static, scanner.scan(INTERPOLATION_FREE_TEXT)]
373
- end
374
- end
375
- parts
380
+ emit_parts(Compiler.interpolation_parts(text))
376
381
  end
377
382
 
378
383
  def compile_embedded(embedded)
@@ -401,7 +406,7 @@ module SuperSlim
401
406
 
402
407
  placeholder = "%#{object_id.abs.to_s(36)}%"
403
408
  dynamic_parts = []
404
- markdown = children.grep(Text).flat_map { interpolation_parts(_1.text) }.map do |part|
409
+ markdown = children.grep(Text).flat_map { Compiler.interpolation_parts(_1.text) }.map do |part|
405
410
  next part[1] if part.first == :static
406
411
 
407
412
  dynamic_parts << part
@@ -437,7 +442,7 @@ module SuperSlim
437
442
  @buffer = StringBuffer.new(variable, @escape_function)
438
443
  emit_code(@buffer.open)
439
444
  yield
440
- emit_code(@buffer.close)
445
+ flush_static
441
446
  @buffer = outer_buffer
442
447
  end
443
448
  end
@@ -51,7 +51,11 @@ module SuperSlim
51
51
  parsed = Prism.parse("#{TEMPLATE_METHOD}#{code}\nend")
52
52
  opens_block = !parsed.success?
53
53
  parsed = Prism.parse("#{TEMPLATE_METHOD}#{code}\nend\nend") if opens_block
54
- [parsed.value.statements.body.first.body&.body || [], opens_block] if parsed.success? && parsed.comments.empty?
54
+ return unless parsed.success? && parsed.comments.empty?
55
+
56
+ # `- rescue` and `- ensure` belong to the method itself: they leave it no statements to spread.
57
+ body = parsed.value.statements.body.first.body
58
+ [body.is_a?(Prism::StatementsNode) ? body.body : [], opens_block]
55
59
  end
56
60
 
57
61
  # Positional and keyword arguments, then the block argument; nil when the call takes none.
@@ -25,7 +25,10 @@ module SuperSlim
25
25
  RUBY_BLOCK_MIN_LINES = 3
26
26
  SKIPPED_KINDS = %i[blank continuation].freeze
27
27
  RUBY_BLOCK = /\A\s*ruby:\s*\z/
28
- CONTROL_RUN = /^( *)- .*\n\1- .*\n\1- /
28
+ # Three `-` lines, or one beside a `ruby:` block.
29
+ CODE_RUN = /^( *)- .*\n\1- .*\n\1- |^( *)- .*\n\2ruby:$|^( *)ruby:\n(?:\3 .*\n)+\3- /
30
+ # Two passes settle every template of the corpus, and a third sees that nothing changes: the rest is margin.
31
+ MAX_PASSES = 5
29
32
  # `while x do` is valid Ruby that nobody writes.
30
33
  LOOP = /\A(?:while|until|for)\b/
31
34
  END_KEYWORD = /\Aend\b/
@@ -60,7 +63,31 @@ module SuperSlim
60
63
  @line_wrapper = LineWrapper.new(max_line_length, tailwind_classes:, attribute_delimiters:) if max_line_length
61
64
  end
62
65
 
66
+ # With max_line_length, a pass can leave work for the next: brackets it spread fit once joined back without the
67
+ # spaces inside them, and the children of an output it moved onto its tag stand one level too deep. Formatted
68
+ # until nothing changes, so that `format --check` passes right after `format`.
63
69
  def call(source)
70
+ formatted = format_once(source)
71
+ return formatted if @line_wrapper.nil? || formatted == source
72
+
73
+ (MAX_PASSES - 1).times do
74
+ previous = formatted
75
+ formatted = format_again(previous)
76
+ break if formatted == previous
77
+ end
78
+ formatted
79
+ end
80
+
81
+ private
82
+
83
+ # Each pass is checked against the template it reads: one that can't be leaves the pass before it.
84
+ def format_again(formatted)
85
+ format_once(formatted)
86
+ rescue UnsafeFormattingError
87
+ formatted
88
+ end
89
+
90
+ def format_once(source)
64
91
  parser = Parser.new(outline: true, tailwind_classes: @tailwind_classes)
65
92
  nodes = parser.call(source)
66
93
  formatted = layout(source, parser)
@@ -79,9 +106,9 @@ module SuperSlim
79
106
  wrapped = @line_wrapper.call(formatted, parser:)
80
107
  return formatted if wrapped == formatted
81
108
 
82
- # `-` code joined by the wrapper may now make a run long enough for a `ruby:` block. A wrap Slim can't read is
83
- # refused below.
84
- if wrapped.match?(CONTROL_RUN)
109
+ # `-` code joined by the wrapper may now make a run long enough for a `ruby:` block, or stand beside one. A wrap
110
+ # Slim can't read is refused below.
111
+ if wrapped.match?(CODE_RUN)
85
112
  wrapped_parser = parsed_template(wrapped).last
86
113
  wrapped = layout(wrapped, wrapped_parser) if wrapped_parser
87
114
  end
@@ -97,8 +124,6 @@ module SuperSlim
97
124
  raise UnsafeFormattingError, "Code nested too deep to check that formatting changes nothing"
98
125
  end
99
126
 
100
- private
101
-
102
127
  def layout(source, parser)
103
128
  source = source.delete_prefix("")
104
129
  lines = Parser.split_lines(source)
@@ -79,33 +79,46 @@ module SuperSlim
79
79
  tag.attributes.select { _1.respond_to?(:name) && _1.name == name && literal_value(_1) }
80
80
  end
81
81
 
82
- INTERPOLATION = /#\{\{?([^{}]*)\}?\}/
83
-
84
82
  # Each piece of Ruby in the template, with the line it starts on: `-` and `=` lines, attribute values, splats,
85
- # `ruby:` blocks, and the interpolations of text and quoted attributes.
83
+ # `ruby:` blocks, and the interpolations of text, inline HTML and quoted attributes.
86
84
  def each_ruby(document)
87
85
  document.each_node do |node, ancestors|
88
86
  case node
89
87
  when AST::Control, AST::Output then yield node.code, document.line_of(node)
90
- when AST::Tag
91
- node.attributes.each do |attribute|
92
- case attribute
93
- when AST::CodeAttribute, AST::Splat then yield attribute.code, document.line_of(node)
94
- when AST::QuotedAttribute then attribute.text.scan(INTERPOLATION) { yield $1, document.line_of(node) }
95
- end
96
- end
88
+ when AST::Tag then each_attribute_ruby(node.attributes) { |code| yield code, document.line_of(node) }
89
+ when AST::InlineHtml then each_interpolation(node.text) { |code| yield code, document.line_of(node) }
97
90
  when AST::Embedded
98
- next unless node.engine == "ruby"
99
-
100
- yield node.children.grep(AST::Text).map(&:text).join, document.line_of(node) + 1
91
+ each_attribute_ruby(node.attributes) { |code| yield code, document.line_of(node) }
92
+ yield ruby_block_code(node), document.line_of(node) + 1 if ruby_block?(node)
101
93
  when AST::Text
102
- next if ancestors.last.is_a?(AST::Embedded) && ancestors.last.engine == "ruby"
94
+ next if ruby_block?(ancestors.last)
95
+
96
+ each_interpolation(node.text) { |code| yield code, line_near(document, node, ancestors) }
97
+ end
98
+ end
99
+ end
103
100
 
104
- node.text.scan(INTERPOLATION) { yield $1, line_near(document, node, ancestors) }
101
+ def each_attribute_ruby(attributes, &)
102
+ attributes.each do |attribute|
103
+ case attribute
104
+ when AST::CodeAttribute, AST::Splat then yield attribute.code
105
+ when AST::QuotedAttribute then each_interpolation(attribute.text, &)
105
106
  end
106
107
  end
107
108
  end
108
109
 
110
+ def each_interpolation(text)
111
+ Compiler.interpolation_parts(text).each { |kind, code| yield code if kind == :dynamic }
112
+ end
113
+
114
+ def ruby_block?(node)
115
+ node.is_a?(AST::Embedded) && node.engine == "ruby"
116
+ end
117
+
118
+ def ruby_block_code(embedded)
119
+ embedded.children.grep(AST::Text).map(&:text).join
120
+ end
121
+
109
122
  # Prism reads a `- if` or `- each do` line without its `end`, as it reads code with errors: the tree it gives
110
123
  # holds the calls written.
111
124
  def each_prism_node(code_or_node)
@@ -287,20 +300,31 @@ module SuperSlim
287
300
  end
288
301
 
289
302
  class InstanceVariables < Rule
290
- INSTANCE_VARIABLE = /(?<![\w@])@[a-z_]\w*/
291
-
292
303
  def offenses(document, _source)
293
304
  return [] unless document.partial?
294
305
 
295
- document.enum_for(:each_node).filter_map do |node,|
296
- code = case node
297
- when AST::Control, AST::Output then node.code
298
- when AST::Tag then node.attributes.filter_map { _1.code if _1.respond_to?(:code) }.join(" ")
306
+ # One offense a line of Ruby, for its first variable: a tag may read the same one in two attributes.
307
+ enum_for(:each_ruby, document).flat_map do |code, lineno|
308
+ first_variable_by_line(code).map do |line, variable|
309
+ offense(document, lineno + line - 1, "Pass `#{variable}` to the partial as a local")
299
310
  end
300
- next unless code && (variable = code[INSTANCE_VARIABLE])
311
+ end.uniq
312
+ end
313
+
314
+ private
315
+
316
+ # Lexed rather than matched: "npm/@scope/package" and "@alice" hold no variable.
317
+ def first_variable_by_line(code)
318
+ variable_by_line = {}
319
+ return variable_by_line unless code.include?("@")
301
320
 
302
- offense(document, document.line_of(node), "Pass `#{variable}` to the partial as a local")
321
+ Prism.lex(code).value.each do |token,|
322
+ # An `@` that no name follows is lexed as one too: `@<%= name %>` in a generator's template.
323
+ next unless token.type == :INSTANCE_VARIABLE && token.value != "@"
324
+
325
+ variable_by_line[token.location.start_line] ||= token.value
303
326
  end
327
+ variable_by_line
304
328
  end
305
329
  end
306
330
 
@@ -328,7 +352,8 @@ module SuperSlim
328
352
  read = Set.new
329
353
  definition.parameters.keywords.each { read.merge(names_read(_1.value)) if _1.respond_to?(:value) }
330
354
  each_ruby(document) { |code,| read.merge(names_read(code)) }
331
- return [] if read.include?(:local_assigns)
355
+ # `binding.local_variable_get(:class)` reads a local named after a keyword.
356
+ return [] if read.include?(:local_assigns) || read.include?(:binding)
332
357
 
333
358
  (declared - read.to_a).map { offense(document, lineno + 1, "The local `#{_1}` is declared but never read") }
334
359
  end
@@ -583,24 +608,26 @@ module SuperSlim
583
608
  class UnescapedOutput < Rule
584
609
  DEFAULTS = {enabled: false}.freeze
585
610
  SKIPS_ESCAPING = /\.html_safe\b|(?<![\w.:@])raw[ (]/
586
- UNESCAPED_INTERPOLATION = /#\{\{/
587
611
  MESSAGE = "skips HTML escaping: output with `=`, or render HTML from a translation key ending in `_html`"
588
612
 
589
613
  def offenses(document, _source)
590
614
  document.enum_for(:each_node).flat_map do |node, ancestors|
591
- reasons_of(node).map { offense(document, line_near(document, node, ancestors), "#{_1} #{MESSAGE}") }
615
+ reasons_of(node, ancestors).map { offense(document, line_near(document, node, ancestors), "#{_1} #{MESSAGE}") }
592
616
  end
593
617
  end
594
618
 
595
619
  private
596
620
 
597
- def reasons_of(node)
621
+ def reasons_of(node, ancestors)
598
622
  case node
599
623
  when AST::Output then [*("`==`" unless node.escape), *code_reason(node.code)]
600
624
  when AST::Control then code_reason(node.code)
601
625
  when AST::Tag then node.attributes.flat_map { attribute_reasons(_1) }
602
- when AST::Text then node.text.match?(UNESCAPED_INTERPOLATION) ? ["`\#{{}}`"] : []
603
- when AST::Embedded then (node.engine == "ruby") ? code_reason(node.children.grep(AST::Text).map(&:text).join("\n")) : []
626
+ when AST::InlineHtml then text_reasons(node.text)
627
+ # The text of a `ruby:` block is code, read whole with the block.
628
+ when AST::Text then ruby_block?(ancestors.last) ? [] : text_reasons(node.text)
629
+ when AST::Embedded
630
+ [*node.attributes.flat_map { attribute_reasons(_1) }, *(code_reason(ruby_block_code(node)) if ruby_block?(node))]
604
631
  else []
605
632
  end
606
633
  end
@@ -608,11 +635,21 @@ module SuperSlim
608
635
  def attribute_reasons(attribute)
609
636
  case attribute
610
637
  when AST::CodeAttribute then [*("`==`" unless attribute.escape), *code_reason(attribute.code)]
638
+ when AST::QuotedAttribute then text_reasons(attribute.text, escape: attribute.escape)
611
639
  when AST::Splat then code_reason(attribute.code)
612
640
  else []
613
641
  end
614
642
  end
615
643
 
644
+ # `==` before literal text skips escaping nothing but what the author wrote: only interpolations count.
645
+ def text_reasons(text, escape: true)
646
+ Compiler.interpolation_parts(text).flat_map do |kind, code, escape_interpolation|
647
+ next [] unless kind == :dynamic
648
+
649
+ [*("`==`" unless escape), *("`\#{{}}`" unless escape_interpolation), *code_reason(code)]
650
+ end.uniq
651
+ end
652
+
616
653
  def code_reason(code)
617
654
  return [] unless (call = code[SKIPS_ESCAPING])
618
655
 
@@ -635,16 +672,18 @@ module SuperSlim
635
672
 
636
673
  class HardcodedText < Rule
637
674
  DEFAULTS = {enabled: false}.freeze
638
- NOT_WORDS = /#\{\{?[^{}]*\}?\}|&(?:[a-z]+|#\d+|#x\h+);|<!\[CDATA\[|\]\]>|<[^<>]+>/i
675
+ NOT_WORDS = /&(?:[a-z]+|#\d+|#x\h+);|<!\[CDATA\[|\]\]>|<[^<>]+>/i
639
676
  EXCERPT_LENGTH = 40
640
677
 
641
678
  def offenses(document, _source)
642
679
  document.enum_for(:each_node).filter_map do |node, ancestors|
643
680
  next unless node.is_a?(AST::TextBlock) && !ancestors.inside_comment
644
681
 
645
- text = node.children.grep(AST::Text).map(&:text).join(" ").gsub(/\s+/, " ").strip
646
- next unless text.gsub(NOT_WORDS, "").match?(/\p{L}/)
682
+ texts = node.children.grep(AST::Text).map(&:text)
683
+ literal_texts = texts.flat_map { |text| Compiler.interpolation_parts(text).filter_map { |kind, literal| literal if kind == :static } }
684
+ next unless literal_texts.join(" ").gsub(NOT_WORDS, "").match?(/\p{L}/)
647
685
 
686
+ text = texts.join(" ").gsub(/\s+/, " ").strip
648
687
  excerpt = (text.length > EXCERPT_LENGTH) ? "#{text[0, EXCERPT_LENGTH]}…" : text
649
688
  offense(document, line_near(document, node, ancestors), "Translate `#{excerpt}` instead of writing it in the template")
650
689
  end
@@ -661,8 +700,6 @@ module SuperSlim
661
700
  def offenses(document, _source)
662
701
  calls_by_lineno = Hash.new { |hash, lineno| hash[lineno] = [] }
663
702
  each_ruby(document) do |code, lineno|
664
- next unless lineno
665
-
666
703
  each_prism_node(code) do |node|
667
704
  next unless node.is_a?(Prism::CallNode) && (call = query(node))
668
705
 
@@ -717,19 +754,26 @@ module SuperSlim
717
754
  # Ruby that a plainer line of Slim says better, after haml-lint.
718
755
 
719
756
  class UnnecessaryInterpolation < Rule
720
- LONE_INTERPOLATION = /\A#\{([^{}]+)\}\z/
721
-
722
757
  def offenses(document, _source)
723
758
  document.enum_for(:each_node).filter_map do |node, ancestors|
724
759
  next unless node.is_a?(AST::TextBlock)
725
760
  next unless (lineno = document.line_of(node) || document.line_of(ancestors.last))
726
761
 
727
762
  texts = node.children.grep(AST::Text)
728
- next unless texts.size == 1 && texts.first.text =~ LONE_INTERPOLATION
763
+ next unless texts.size == 1 && (code = lone_interpolation(texts.first.text))
729
764
 
730
- offense(document, lineno, "Write `= #{$1.strip}` instead of interpolating it alone")
765
+ offense(document, lineno, "Write `= #{code}` instead of interpolating it alone")
731
766
  end
732
767
  end
768
+
769
+ private
770
+
771
+ # The code of an escaped interpolation that is the whole text: `#{{}}` would need `==`.
772
+ def lone_interpolation(text)
773
+ parts = Compiler.interpolation_parts(text)
774
+ kind, code, escape = parts.first
775
+ code.strip if parts.size == 1 && kind == :dynamic && escape && !code.strip.empty?
776
+ end
733
777
  end
734
778
 
735
779
  class UnnecessaryStringOutput < Rule
@@ -76,6 +76,17 @@ module SuperSlim
76
76
  # The layout rules: what `super-slim format` rewrites.
77
77
  LAYOUT_RULE_NAMES = %w[Indentation Tab TrailingWhitespace EmptyLines ControlStatementSpacing RedundantDiv].freeze
78
78
  GLOB_OPTIONS = %w[include exclude].freeze
79
+ SETTINGS = %w[linters format fmt tailwind_classes].freeze
80
+ FORMAT_SETTINGS = %w[max_line_length attribute_delimiters].freeze
81
+ # What the default of a rule's option asks of the value that replaces it.
82
+ VALUE_KIND_BY_DEFAULT_CLASS = {
83
+ TrueClass => ["true or false", [TrueClass, FalseClass]],
84
+ FalseClass => ["true or false", [TrueClass, FalseClass]],
85
+ Integer => ["a whole number", [Integer]],
86
+ # Left empty under a preset, `classes:` is nil.
87
+ Hash => ["a mapping", [Hash, NilClass]],
88
+ Array => ["a list", [Array]]
89
+ }.freeze
79
90
 
80
91
  def self.load(directory = Dir.pwd)
81
92
  new(configuration(directory).fetch("linters", {}), directory)
@@ -88,22 +99,62 @@ module SuperSlim
88
99
  configuration
89
100
  end
90
101
 
91
- # A value of the wrong shape would fail later, inside a rule, with a NoMethodError naming none of this file.
102
+ # A value of the wrong shape would fail later, inside a rule or the formatter, on every template and with an error
103
+ # naming none of this file: `max: "120"` compares a number with text.
92
104
  def self.check_configuration(configuration)
93
105
  raise Error, "#{CONFIG_FILE}: expected a mapping of settings" unless configuration.is_a?(Hash)
94
106
 
107
+ check_names(configuration.keys, SETTINGS, "a setting")
95
108
  %w[linters format fmt].each do |key|
96
109
  raise Error, "#{CONFIG_FILE}: `#{key}` must be a mapping" unless configuration.fetch(key, {}).is_a?(Hash)
97
110
  end
98
- configuration.fetch("linters", {}).each do |rule_name, options|
99
- raise Error, "#{CONFIG_FILE}: `linters: #{rule_name}` must be a mapping of options" unless options.is_a?(Hash)
111
+ raise Error, "#{CONFIG_FILE}: `tailwind_classes` must be true or false" unless [true, false, nil].include?(configuration["tailwind_classes"])
100
112
 
101
- GLOB_OPTIONS.each do |key|
102
- globs = Array(options[key])
103
- raise Error, "#{CONFIG_FILE}: `#{rule_name}: #{key}` must be a list of globs" unless globs.all?(String)
104
- end
113
+ configuration.fetch("linters", {}).each { |rule_name, options| check_rule_options(rule_name, options) }
114
+ configuration.slice("format", "fmt").each { |key, options| check_format_options(key, options) }
115
+ end
116
+
117
+ def self.check_rule_options(rule_name, options)
118
+ raise Error, "#{CONFIG_FILE}: `linters: #{rule_name}` must be a mapping of options" unless options.is_a?(Hash)
119
+
120
+ GLOB_OPTIONS.each do |key|
121
+ globs = Array(options[key])
122
+ raise Error, "#{CONFIG_FILE}: `#{rule_name}: #{key}` must be a list of globs" unless globs.all?(String)
123
+ end
124
+ rule_class = Rules.all.find { _1.rule_name == rule_name }
125
+ raise Error, "#{CONFIG_FILE}: `#{rule_name}` is not a rule of super-slim lint" unless rule_class
126
+
127
+ preset_option = (PRESETS.any? { |_preset, options_by_rule| options_by_rule.key?(rule_name) }) ? ["preset"] : []
128
+ check_names(options.keys, rule_class::DEFAULTS.keys.map(&:to_s) + GLOB_OPTIONS + preset_option, "an option of #{rule_name}")
129
+ rule_class::DEFAULTS.each do |key, default|
130
+ next unless options.key?(key.to_s)
131
+
132
+ kind, classes = VALUE_KIND_BY_DEFAULT_CLASS.fetch(default.class)
133
+ raise Error, "#{CONFIG_FILE}: `#{rule_name}: #{key}` must be #{kind}" unless classes.any? { options[key.to_s].is_a?(_1) }
105
134
  end
106
135
  end
136
+ private_class_method :check_rule_options
137
+
138
+ def self.check_format_options(key, options)
139
+ check_names(options.keys, FORMAT_SETTINGS, "a setting of `#{key}`")
140
+ max_line_length = options["max_line_length"]
141
+ wraps_nothing_or_at_a_length = max_line_length.nil? || (max_line_length.is_a?(Integer) && max_line_length.positive?)
142
+ raise Error, "#{CONFIG_FILE}: `#{key}: max_line_length` must be a whole number above 0" unless wraps_nothing_or_at_a_length
143
+
144
+ delimiters = Formatter::LineWrapper::OPENING_BY_ATTRIBUTE_DELIMITERS.keys
145
+ return if !options.key?("attribute_delimiters") || delimiters.include?(options["attribute_delimiters"])
146
+
147
+ raise Error, "#{CONFIG_FILE}: `#{key}: attribute_delimiters` must be one of #{delimiters.join(", ")}"
148
+ end
149
+ private_class_method :check_format_options
150
+
151
+ # A misspelt name is a setting that does nothing and says nothing: the rule it meant to turn off stays on.
152
+ def self.check_names(names, known_names, kind)
153
+ unknown_name = (names - known_names).first or return
154
+
155
+ raise Error, "#{CONFIG_FILE}: `#{unknown_name}` is not #{kind}, use one of: #{known_names.join(", ")}"
156
+ end
157
+ private_class_method :check_names
107
158
 
108
159
  # include: and exclude: globs match paths relative to `root`, the directory of .super-slim.yml.
109
160
  def initialize(options_by_rule_name = {}, root = Dir.pwd)
@@ -292,7 +292,8 @@ module SuperSlim
292
292
  def parse_comment
293
293
  if @scanner.skip(HTML_COMMENT)
294
294
  text_indent = @indents.last + @scanner[1].size + 2
295
- @stacks.last << Comment.new(parse_text_block(@scanner.rest, text_indent))
295
+ lineno = @lineno
296
+ @stacks.last << located(Comment.new(parse_text_block(@scanner.rest, text_indent)), lineno)
296
297
  elsif @scanner.match?(CONDITIONAL_COMMENT)
297
298
  syntax_error!("Conditional comments are not supported")
298
299
  else
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module SuperSlim
4
- VERSION = "3.5.0"
4
+ VERSION = "3.6.1"
5
5
  end
data/lib/super_slim.rb CHANGED
@@ -8,8 +8,10 @@ require_relative "super_slim/compiler"
8
8
  require_relative "super_slim/runtime"
9
9
 
10
10
  module SuperSlim
11
- autoload :Formatter, "super_slim/formatter"
12
- autoload :RuboCop, "super_slim/rubocop"
11
+ # By their full path: a bare "super_slim/formatter" is the first one on the load path, which is another copy of the
12
+ # gem when this one was loaded by its path, as `exe/super-slim` does in a checkout.
13
+ autoload :Formatter, File.join(__dir__, "super_slim/formatter")
14
+ autoload :RuboCop, File.join(__dir__, "super_slim/rubocop")
13
15
 
14
16
  class Error < StandardError; end
15
17
  class InvalidAttributeNameError < Error; end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: super-slim
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.5.0
4
+ version: 3.6.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Level UP Solutions