super-slim 3.2.2 → 3.3.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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +31 -1
- data/README.md +39 -12
- data/lib/super_slim/compiler.rb +9 -13
- data/lib/super_slim/formatter/code_wrapper.rb +41 -25
- data/lib/super_slim/formatter/line_wrapper.rb +52 -20
- data/lib/super_slim/formatter.rb +156 -49
- data/lib/super_slim/linter/rules.rb +47 -8
- data/lib/super_slim/linter.rb +41 -8
- data/lib/super_slim/parser/ruby_brackets.rb +16 -6
- data/lib/super_slim/parser.rb +55 -12
- data/lib/super_slim/version.rb +1 -1
- metadata +1 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 5149a2f9c05783ba0fdab16defa340f6bb78603ad9ea8e74c4f6e625c4bd1392
|
|
4
|
+
data.tar.gz: 6d18ebb68b10c7b1bdb622165cc37b6bd8b419570da4b44701f6c46c77027db7
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: a4cd215f77343dcb06e119108786e85e9444b9301e6466aa7750bdd7dd3072afe6d4c986132c4f868833e2f53437fa3e263c167df372b3210a7548bb86200ffd
|
|
7
|
+
data.tar.gz: ed08caa1d54ab6a225949485473fac9c637c0319b72772032181b1e5877ab5995c8df00ccce8c3375d96d2f64e6ce623dcbf8354b1ce13c53667ef37914c812d
|
data/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,35 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## [3.3.0] — 2026-11-07
|
|
6
|
+
|
|
7
|
+
Formatted templates that Slim and Brakeman read, lines and rules you can opt out of, and a formatter about 30% faster.
|
|
8
|
+
|
|
9
|
+
**New**
|
|
10
|
+
- `/ super-slim:format off` keeps the lines after it as written, up to `/ super-slim:format on` or the end of their
|
|
11
|
+
block, and `/ super-slim:disable Rule, OtherRule` silences rules for the next tag or line of code. An unknown rule
|
|
12
|
+
name, or a directive with no line after it, is reported.
|
|
13
|
+
- The `SlimSyntax` lint rule, on by default, flags what Slim, and so Brakeman, can't read: code continued after an
|
|
14
|
+
opening bracket, and a comment after code.
|
|
15
|
+
- The `AriaBooleanValue` lint rule, on by default, flags `aria-*=true`, which renders without a value, and
|
|
16
|
+
`aria-*=false`, which Slim leaves out.
|
|
17
|
+
- `super-slim format` removes a blank line at the start of a block, sets a partial's first-line `/# locals:`
|
|
18
|
+
signature apart with a blank line, and writes the `do` that Slim adds to a line of code whose children render
|
|
19
|
+
something.
|
|
20
|
+
|
|
21
|
+
**Faster**
|
|
22
|
+
- `super-slim format` is about 30% faster: it compares the compiled Ruby as text before parsing it, and reads each
|
|
23
|
+
template once.
|
|
24
|
+
|
|
25
|
+
**Fixed**
|
|
26
|
+
- With `max_line_length`, `super-slim format` spreads a long call one argument per line, each line but the last
|
|
27
|
+
ending with a comma, instead of between brackets that close on a line of their own. Slim only continues code after
|
|
28
|
+
a comma or a backslash, so since 3.2.0 Brakeman could check nothing in a wrapped template. Formatting again
|
|
29
|
+
repairs the templates already written, a tag's output after its attributes included. A first argument too long to
|
|
30
|
+
follow its call, or the brackets or the `do` that close the last one, go to the next line after a backslash.
|
|
31
|
+
- Code spread by hand with a comment inside stays as written, instead of keeping the formatter from wrapping
|
|
32
|
+
anything else in its file.
|
|
33
|
+
|
|
5
34
|
## [3.2.2] — 2026-11-06
|
|
6
35
|
|
|
7
36
|
`super-slim format` no longer joins code spread by hand into lines past `max_line_length`.
|
|
@@ -193,7 +222,8 @@ renders what Slim 5 renders with `format: :html, sort_attrs: false`, byte for by
|
|
|
193
222
|
- 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,
|
|
194
223
|
newer than the one Ruby 3.3 ships.
|
|
195
224
|
|
|
196
|
-
[Unreleased]: https://github.com/levups/super-slim/compare/v3.
|
|
225
|
+
[Unreleased]: https://github.com/levups/super-slim/compare/v3.3.0...HEAD
|
|
226
|
+
[3.3.0]: https://github.com/levups/super-slim/compare/v3.2.2...v3.3.0
|
|
197
227
|
[3.2.2]: https://github.com/levups/super-slim/compare/v3.2.1...v3.2.2
|
|
198
228
|
[3.2.1]: https://github.com/levups/super-slim/compare/v3.2.0...v3.2.1
|
|
199
229
|
[3.2.0]: https://github.com/levups/super-slim/compare/v3.1.1...v3.2.0
|
data/README.md
CHANGED
|
@@ -94,7 +94,8 @@ Templates for XML formats (`.xml`, `.rss`, `.atom`) render as XML automatically,
|
|
|
94
94
|
|
|
95
95
|
`super-slim format` rewrites templates in one layout: two spaces per level, a space after `-` and `=`, no `div`
|
|
96
96
|
where a `.class` or `#id` is enough, no trailing whitespace unless it renders, single blank lines and a final
|
|
97
|
-
newline.
|
|
97
|
+
newline. A block starts right after the line that opens it, a partial's `/# locals:` signature stands apart from its
|
|
98
|
+
body, and Ruby code with children ends with the `do` that Slim would add. This template:
|
|
98
99
|
|
|
99
100
|
```slim
|
|
100
101
|
div.card
|
|
@@ -140,18 +141,20 @@ format:
|
|
|
140
141
|
|
|
141
142
|
The formatter then gives each line one layout, whatever its author chose. Ruby code spread over several lines is
|
|
142
143
|
joined back when it fits. A longer line spreads the arguments of its call, or the elements of its array or hash, one
|
|
143
|
-
per line
|
|
144
|
+
per line, each line but the last ending with a comma:
|
|
144
145
|
|
|
145
146
|
```slim
|
|
146
|
-
=
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
)
|
|
147
|
+
= link_to "Read the whole post",
|
|
148
|
+
post_path(post),
|
|
149
|
+
class: "btn btn-primary"
|
|
150
150
|
```
|
|
151
151
|
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
would
|
|
152
|
+
Slim, and so Brakeman, reads a line that ends with a comma or a backslash as going on, but not one that ends with an
|
|
153
|
+
opening bracket. A call whose only argument is a call spreads that one: `= render Card.new(title: post.title,`. A
|
|
154
|
+
first argument that would pass the limit goes to the next line after a backslash, and so do the brackets or the `do`
|
|
155
|
+
that close the last one when they would. The lines after the first go two spaces deep, two more when the line opens a
|
|
156
|
+
block. Code spread by hand stays as it is when it holds a comment, or when this layout would leave a line longer than
|
|
157
|
+
the limit and Slim can read it. Arguments to `new` go in parentheses.
|
|
155
158
|
|
|
156
159
|
A tag's attributes stand without delimiters when they fit on its line, and one per line inside the delimiters when
|
|
157
160
|
they don't, unless its shortcuts alone pass the limit. A literal `id` or `class` becomes a shortcut, a class shortcut
|
|
@@ -161,6 +164,17 @@ named twice goes, and the other attributes follow one order: `id`, `class`, what
|
|
|
161
164
|
an attribute, and a tag with a `*splat` keeps its order. The formatter takes attribute values to have no side
|
|
162
165
|
effects: reordering two Ruby values changes the order they run in.
|
|
163
166
|
|
|
167
|
+
Lines the formatter should leave alone go between two comments. Without `on`, the rest of the block that holds the
|
|
168
|
+
comment stays as written, the rest of the template at the top level. The lines keep their text and only move with
|
|
169
|
+
their block, and the lint rules that `super-slim format` would fix stay quiet there:
|
|
170
|
+
|
|
171
|
+
```slim
|
|
172
|
+
table
|
|
173
|
+
/ super-slim:format off
|
|
174
|
+
tr: td colspan=8 = t(".empty")
|
|
175
|
+
/ super-slim:format on
|
|
176
|
+
```
|
|
177
|
+
|
|
164
178
|
## Linter
|
|
165
179
|
|
|
166
180
|
```sh
|
|
@@ -183,10 +197,11 @@ linters, so most will look familiar:
|
|
|
183
197
|
| LineLength (`max: 120`), CommentControlStatement, EmptyControlStatement, ConsecutiveControlStatements (`max: 2`), TagCase | slim-lint | on |
|
|
184
198
|
| InstanceVariables (in partials) | haml-lint, Rails conventions | on |
|
|
185
199
|
| StrictLocals (partials declare `/# locals:`) | Rails 7.1 strict locals | off |
|
|
186
|
-
| DuplicateId, ImageAlt, IframeTitle, AnchorHref, NestedLinks, PositiveTabindex, BooleanAttributeValue, AriaRole, AriaAttribute | Herb, eslint-plugin-jsx-a11y | on |
|
|
200
|
+
| DuplicateId, ImageAlt, IframeTitle, AnchorHref, NestedLinks, PositiveTabindex, BooleanAttributeValue, AriaBooleanValue (`aria-*=true` renders no value, `aria-*=false` no attribute), AriaRole, AriaAttribute | Herb, eslint-plugin-jsx-a11y | on |
|
|
187
201
|
| ButtonType, InlineStyles | eslint-plugin-react, haml-lint | off |
|
|
188
202
|
| DeprecatedClasses (`classes: {old: new}`, `old-*: new-*` for a prefix), DeprecatedAttributes (`attributes: {old: new}`), both with `preset: bootstrap5` | erb_lint | on, but empty |
|
|
189
203
|
| UnescapedOutput (`==`, `html_safe`, `raw`, `#{{}}`) | Brakeman, erb_lint | off |
|
|
204
|
+
| SlimSyntax (code continued after an opening bracket, a comment after code: Slim and Brakeman can't read them) | Brakeman | on |
|
|
190
205
|
| EmbeddedEngines (`forbidden_engines: [javascript, css]`) | slim-lint | off |
|
|
191
206
|
| HardcodedText (text that should be translated) | erb_lint | off |
|
|
192
207
|
| UnnecessaryInterpolation, UnnecessaryStringOutput | haml-lint | on |
|
|
@@ -220,6 +235,14 @@ linters:
|
|
|
220
235
|
Every rule accepts `include:` and `exclude:`, lists of glob patterns matched against paths relative to
|
|
221
236
|
`.super-slim.yml` (`**/` matches any number of directories).
|
|
222
237
|
|
|
238
|
+
A comment silences rules on the next tag or code line, blank lines and comments skipped, and on the lines it goes on
|
|
239
|
+
over. The linter reports a rule name it doesn't know:
|
|
240
|
+
|
|
241
|
+
```slim
|
|
242
|
+
/ super-slim:disable ButtonType, InlineStyles
|
|
243
|
+
button style="all: unset" Close
|
|
244
|
+
```
|
|
245
|
+
|
|
223
246
|
The `bootstrap5` preset lists the classes and data attributes that Bootstrap 5.3 renamed, including the ones with
|
|
224
247
|
breakpoints such as `text-md-right`. Its data attributes are only those of Bootstrap's own components
|
|
225
248
|
(`data-toggle`, `data-target` and the like). If your app also uses generic ones such as `data-content`, add them
|
|
@@ -277,6 +300,9 @@ Slim compiles `= render CardComponent.new(post:) # rubocop:disable Some/Cop -- r
|
|
|
277
300
|
comment swallows the parenthesis that closes the output, or the `do` of a block. SuperSlim leaves a comment that
|
|
278
301
|
follows code on its line out of the compiled Ruby, after `=`, `==` and `-` alike, so a RuboCop directive can sit on
|
|
279
302
|
the line it is about.
|
|
303
|
+
Slim still can't read such a template, and neither can Brakeman, which parses views with Slim: it reports the
|
|
304
|
+
template as an error and checks nothing in it. The `SlimSyntax` linter rule flags these lines; turn it off if you
|
|
305
|
+
don't run Brakeman.
|
|
280
306
|
|
|
281
307
|
### Tailwind class names
|
|
282
308
|
|
|
@@ -365,8 +391,9 @@ On top of that:
|
|
|
365
391
|
Real templates come from 30 open-source apps, pinned to a commit in `corpus/manifest.yml`. `rake corpus:fetch`
|
|
366
392
|
downloads only their `.slim` files, into `corpus/cache` (ignored by Git). `rake corpus:check` compiles, formats
|
|
367
393
|
and lints each of them and compares the result with Slim. `rake corpus:diff BASE=rev` shows what a change does to
|
|
368
|
-
them: compiled Ruby, formatting and lint offenses.
|
|
369
|
-
|
|
394
|
+
them: compiled Ruby, formatting and lint offenses. It fails when formatting changes, unless `FORMATTING_CHANGES=1`
|
|
395
|
+
says the change means to; in CI, a pull request says so with the `formatting change` label. These templates are
|
|
396
|
+
never rendered, because rendering would run their Ruby code. Your own templates can be rendered too: pass their directories in `SUPER_SLIM_CORPUS`.
|
|
370
397
|
|
|
371
398
|
## Development
|
|
372
399
|
|
data/lib/super_slim/compiler.rb
CHANGED
|
@@ -137,15 +137,15 @@ module SuperSlim
|
|
|
137
137
|
return compile_children(output.children)
|
|
138
138
|
end
|
|
139
139
|
|
|
140
|
-
|
|
141
|
-
emit_code("#{
|
|
140
|
+
returned_value = new_variable
|
|
141
|
+
emit_code("#{returned_value} = #{code}")
|
|
142
142
|
if @rails
|
|
143
143
|
compile_children(output.children)
|
|
144
144
|
else
|
|
145
145
|
capture_into(new_variable) { compile_children(output.children) }
|
|
146
146
|
end
|
|
147
147
|
emit_code("end")
|
|
148
|
-
emit_output(
|
|
148
|
+
emit_output(returned_value, output.escape)
|
|
149
149
|
end
|
|
150
150
|
|
|
151
151
|
def with_do(code, children)
|
|
@@ -157,12 +157,9 @@ module SuperSlim
|
|
|
157
157
|
# parenthesis of an output or the `do` of a block. It never runs, so it is left out. One alone on a line
|
|
158
158
|
# stays: a backslash before it carries the code on to that line.
|
|
159
159
|
def without_trailing_comment(code)
|
|
160
|
-
|
|
160
|
+
comment_offset = Parser::RubyBrackets.code_comment_offset(code) or return code
|
|
161
161
|
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
code_before = code.byteslice(0, comment_offset).sub(/[ \t]+\z/, "")
|
|
165
|
-
(code_before.empty? || code_before.end_with?("\n")) ? code : code_before
|
|
162
|
+
code.byteslice(0, comment_offset).sub(/[ \t]+\z/, "")
|
|
166
163
|
end
|
|
167
164
|
|
|
168
165
|
def compile_tag(tag)
|
|
@@ -251,9 +248,9 @@ module SuperSlim
|
|
|
251
248
|
# separator, so nothing is joined at render time.
|
|
252
249
|
def compile_class_attribute(values)
|
|
253
250
|
values = values.reject { |parts| parts.all? { |kind, value| kind == :static && value.empty? } }
|
|
254
|
-
if values.empty?
|
|
255
|
-
|
|
256
|
-
|
|
251
|
+
return if values.empty?
|
|
252
|
+
|
|
253
|
+
if literal_text?(values.first)
|
|
257
254
|
emit_static(' class="')
|
|
258
255
|
values.each_with_index { |parts, index| emit_class_value(parts, separator: index > 0) }
|
|
259
256
|
emit_static('"')
|
|
@@ -380,8 +377,7 @@ module SuperSlim
|
|
|
380
377
|
|
|
381
378
|
def compile_embedded(embedded)
|
|
382
379
|
case embedded.engine
|
|
383
|
-
when "ruby"
|
|
384
|
-
compile_ruby(embedded.children)
|
|
380
|
+
when "ruby" then compile_ruby(embedded.children)
|
|
385
381
|
when "javascript" then compile_tag(Tag.new("script", embedded.attributes, [TextBlock.new(embedded.children)]))
|
|
386
382
|
when "css" then compile_tag(Tag.new("style", embedded.attributes, embedded.children))
|
|
387
383
|
when "markdown" then compile_markdown(embedded.children)
|
|
@@ -3,18 +3,19 @@
|
|
|
3
3
|
module SuperSlim
|
|
4
4
|
class Formatter
|
|
5
5
|
# Spreads a line of Ruby code over several: the arguments of its call, or the elements of its array or hash,
|
|
6
|
-
# one per line, each
|
|
7
|
-
#
|
|
6
|
+
# one per line, each line but the last ending with a comma. Slim, and Brakeman with it, reads a line ending with
|
|
7
|
+
# a comma or a backslash as going on, but not one ending with an opening bracket. A call whose only argument is
|
|
8
|
+
# itself a call, an array or a hash spreads that argument instead: `render Card.new(…)`.
|
|
8
9
|
class CodeWrapper
|
|
9
10
|
METHOD_NAME = /\A[a-z_][a-zA-Z0-9_]*[?!]?\z/
|
|
10
11
|
# Rails runs a template inside a method, where `yield` is valid.
|
|
11
12
|
TEMPLATE_METHOD = "def template\n"
|
|
12
13
|
CODE_OFFSET = TEMPLATE_METHOD.bytesize
|
|
13
14
|
|
|
14
|
-
# Returns the lines
|
|
15
|
+
# Returns the lines, the first one starting with head, or nil when the code has nothing to spread. An item
|
|
15
16
|
# still longer than max_line_length spreads its own arguments or elements.
|
|
16
|
-
def self.call(code, indent, opens_block:, max_line_length:)
|
|
17
|
-
new(code, indent, opens_block:, max_line_length:).call
|
|
17
|
+
def self.call(code, indent, head:, opens_block:, max_line_length:)
|
|
18
|
+
new(code, indent, head:, opens_block:, max_line_length:).call
|
|
18
19
|
end
|
|
19
20
|
|
|
20
21
|
# `render Card.new title:` reads as if title went to render: arguments to `new` go in parentheses.
|
|
@@ -69,9 +70,10 @@ module SuperSlim
|
|
|
69
70
|
end
|
|
70
71
|
|
|
71
72
|
# opens_block: whether the line has children, which Slim passes to its call as a block even without `do`.
|
|
72
|
-
def initialize(code, indent, opens_block:, max_line_length:)
|
|
73
|
+
def initialize(code, indent, head:, opens_block:, max_line_length:)
|
|
73
74
|
@code = code
|
|
74
75
|
@indent = indent
|
|
76
|
+
@head = head
|
|
75
77
|
@opens_block = opens_block
|
|
76
78
|
@max_line_length = max_line_length
|
|
77
79
|
end
|
|
@@ -80,8 +82,9 @@ module SuperSlim
|
|
|
80
82
|
statements, opens_block = self.class.parse(@code)
|
|
81
83
|
return unless statements&.size == 1 && (node = spreadable(statements.first))
|
|
82
84
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
+
# Set apart from the children of a line that opens a block.
|
|
86
|
+
indent = @indent + (" " * ((@opens_block || opens_block) ? INDENT_WIDTH : 0))
|
|
87
|
+
spread(node, CODE_OFFSET, CODE_OFFSET + @code.bytesize, @head, indent)
|
|
85
88
|
end
|
|
86
89
|
|
|
87
90
|
private
|
|
@@ -103,35 +106,48 @@ module SuperSlim
|
|
|
103
106
|
end
|
|
104
107
|
end
|
|
105
108
|
|
|
106
|
-
# The lines of the code from first to last, node's
|
|
107
|
-
|
|
109
|
+
# The lines of the code from first to last after prefix, node's first item on the first line, and each other
|
|
110
|
+
# one on a line of its own, indented one level deeper than indent.
|
|
111
|
+
def spread(node, first, last, prefix, indent)
|
|
108
112
|
items = node.is_a?(Prism::CallNode) ? self.class.arguments_of(node) : node.elements
|
|
109
113
|
# `hint: -> do` ends past the line, with the children of the line.
|
|
110
114
|
return if self.class.end_offset(items.last) > CODE_OFFSET + @code.bytesize
|
|
111
115
|
|
|
112
|
-
item_indent =
|
|
113
|
-
head,
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
116
|
+
item_indent = indent + (" " * INDENT_WIDTH)
|
|
117
|
+
head = prefix + slice(first, node.opening_loc&.end_offset || items.first.location.start_offset)
|
|
118
|
+
tail = slice(node.closing_loc&.start_offset || self.class.end_offset(items.last), last)
|
|
119
|
+
# The last item carries what closes the node: brackets, a block, a method called on the spread array.
|
|
120
|
+
suffixes = items.map { _1.equal?(items.last) ? tail : "," }
|
|
121
|
+
first_lines = item_lines(items.first, head, item_indent, suffixes.first)
|
|
122
|
+
# A first item that passes the limit after the head goes to a line of its own, after a backslash.
|
|
123
|
+
if first_lines.first.size > @max_line_length && !head.strip.empty?
|
|
124
|
+
backslash = head.match?(Parser::OPENING_BRACKET_AT_LINE_END) ? "\\" : " \\"
|
|
125
|
+
first_lines = ["#{head.rstrip}#{backslash}", *item_lines(items.first, item_indent, item_indent, suffixes.first)]
|
|
126
|
+
end
|
|
127
|
+
*lines, last_line = first_lines + items.zip(suffixes).drop(1).flat_map { |item, suffix| item_lines(item, item_indent, item_indent, suffix) }
|
|
128
|
+
lines + closing_lines(last_line, tail, item_indent)
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
# What closes the last item goes to the next line after a backslash when the last line would pass the limit.
|
|
132
|
+
def closing_lines(last_line, tail, indent)
|
|
133
|
+
return [last_line] if tail.empty? || last_line.size <= @max_line_length
|
|
134
|
+
|
|
135
|
+
after_backslash = ["#{last_line.delete_suffix(tail)} \\", indent + tail.lstrip]
|
|
136
|
+
(after_backslash.map(&:size).max < last_line.size) ? after_backslash : [last_line]
|
|
121
137
|
end
|
|
122
138
|
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
comma = "," unless item.is_a?(Prism::BlockArgumentNode)
|
|
139
|
+
# The lines of item after prefix, then suffix.
|
|
140
|
+
def item_lines(item, prefix, indent, suffix)
|
|
126
141
|
item_end = self.class.end_offset(item)
|
|
127
|
-
line = "#{
|
|
142
|
+
line = "#{prefix}#{slice(item.location.start_offset, item_end)}#{suffix}"
|
|
128
143
|
return [line] if line.size <= @max_line_length
|
|
129
144
|
|
|
130
145
|
nested = spreadable(item.is_a?(Prism::AssocNode) ? item.value : item)
|
|
131
|
-
lines = nested && spread(nested, item.location.start_offset, item_end, indent)
|
|
146
|
+
lines = nested && spread(nested, item.location.start_offset, item_end, prefix, indent)
|
|
132
147
|
return [line] unless lines
|
|
133
148
|
|
|
134
|
-
|
|
149
|
+
lines[-1] += suffix
|
|
150
|
+
lines
|
|
135
151
|
end
|
|
136
152
|
|
|
137
153
|
# From offsets in the parsed source, up to the end of the line by default.
|
|
@@ -26,18 +26,23 @@ module SuperSlim
|
|
|
26
26
|
@attribute_arranger = AttributeArranger.new(tailwind_classes:)
|
|
27
27
|
end
|
|
28
28
|
|
|
29
|
-
def call(source)
|
|
29
|
+
def call(source, parser: nil)
|
|
30
30
|
lines = source.split("\n")
|
|
31
|
-
parser
|
|
32
|
-
|
|
31
|
+
unless parser
|
|
32
|
+
parser = Parser.new(outline: true, tailwind_classes: @tailwind_classes)
|
|
33
|
+
parser.call(source)
|
|
34
|
+
end
|
|
33
35
|
outline = parser.outline
|
|
36
|
+
unformatted_linenos = Parser.unformatted_linenos(lines, outline)
|
|
37
|
+
block_opening_linenos = Formatter.block_opening_linenos(parser)
|
|
34
38
|
wrapped = []
|
|
35
39
|
lineno = 1
|
|
36
40
|
while lineno <= lines.size
|
|
37
41
|
info = outline[lineno]
|
|
38
42
|
last_lineno = lineno
|
|
39
43
|
last_lineno += 1 while outline[last_lineno + 1]&.owner == lineno && CONTINUATION_KINDS.include?(outline[last_lineno + 1].kind)
|
|
40
|
-
|
|
44
|
+
structure_lines = lines[(lineno - 1)...last_lineno]
|
|
45
|
+
wrapped.concat(unformatted_linenos.include?(lineno) ? structure_lines : layout(structure_lines, info, outline, lineno, block_opening_linenos))
|
|
41
46
|
lineno = last_lineno + 1
|
|
42
47
|
end
|
|
43
48
|
"#{wrapped.join("\n")}\n"
|
|
@@ -45,26 +50,36 @@ module SuperSlim
|
|
|
45
50
|
|
|
46
51
|
private
|
|
47
52
|
|
|
48
|
-
def layout(lines, info, outline, lineno)
|
|
53
|
+
def layout(lines, info, outline, lineno, block_opening_linenos)
|
|
49
54
|
return lines unless info.kind == :structure
|
|
50
55
|
|
|
51
|
-
|
|
52
|
-
|
|
56
|
+
spread = lines.size > 1
|
|
57
|
+
line = lines.first
|
|
58
|
+
if spread
|
|
59
|
+
attributes_end = attributes_end(lines, info)
|
|
60
|
+
code_lines = attributes_end ? lines.drop(attributes_end) : lines
|
|
61
|
+
line = attributes_end ? joined_attributes(lines, attributes_end) : joined_code(lines, info)
|
|
62
|
+
return lines unless line
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
line = line[/\A */] + Formatter.with_do(line.lstrip) if spread && block_opening_linenos.include?(lineno)
|
|
53
66
|
|
|
54
67
|
line, arranged_info = @attribute_arranger.call(line, (info if line == lines.first))
|
|
55
68
|
info = arranged_info || info
|
|
56
69
|
line = with_new_parenthesized(line, info)
|
|
70
|
+
return lines if spread && !ruby_reads_joined?(line, info)
|
|
57
71
|
return [line] if line.size <= @max_line_length
|
|
58
72
|
|
|
59
73
|
broken = wrap(line, info, children?(outline, lineno))
|
|
60
|
-
|
|
74
|
+
kept = lines if spread && Parser.slim_continuation?(code_lines)
|
|
75
|
+
return kept || broken if broken == [line]
|
|
61
76
|
|
|
62
77
|
# Joined back, brackets lose the spaces inside them (`{ a: 1 }` becomes `{a: 1}`), which may now fit.
|
|
63
78
|
rejoined = joined_code(broken, info)
|
|
64
79
|
return [rejoined] if rejoined && rejoined.size <= @max_line_length
|
|
65
80
|
|
|
66
81
|
# A string continued with `\` comes back on one line, longer than the author's.
|
|
67
|
-
return
|
|
82
|
+
return kept if kept && broken.max_by(&:size).size > lines.max_by(&:size).size
|
|
68
83
|
|
|
69
84
|
broken
|
|
70
85
|
end
|
|
@@ -78,9 +93,29 @@ module SuperSlim
|
|
|
78
93
|
# The code of a line continued after a comma, a backslash or an opening bracket, on one line; nil when the
|
|
79
94
|
# continuation lines hold anything else, such as attributes or text.
|
|
80
95
|
def joined_code(lines, info)
|
|
81
|
-
|
|
96
|
+
joined(lines.first, lines.drop(1)) if info.text.nil? && code_start(lines.first, info.output_column)
|
|
97
|
+
end
|
|
82
98
|
|
|
83
|
-
|
|
99
|
+
# A tag whose attributes stand one per line inside delimiters, on one line, with the code that continues its
|
|
100
|
+
# closing line: `p {`, `title="A"`, `} = format_date post.created_at,`, `:long`.
|
|
101
|
+
def joined_attributes(lines, attributes_end)
|
|
102
|
+
tag = lines.first.rstrip + lines[1...attributes_end].map(&:strip).join(" ") + lines[attributes_end].strip
|
|
103
|
+
joined(tag, lines.drop(attributes_end + 1))
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
# The index of the line that closes the attributes of a tag spread one per line inside delimiters.
|
|
107
|
+
def attributes_end(lines, info)
|
|
108
|
+
return unless info.text.nil? && lines.first.lstrip.match?(Shortcuts::TAG_PATTERN) && !code_start(lines.first, info.output_column)
|
|
109
|
+
return unless lines.first.rstrip.match?(Parser::OPENING_BRACKET_AT_LINE_END)
|
|
110
|
+
|
|
111
|
+
closing = lines.index { _1.strip.match?(CLOSING_BRACKET_AT_START) }
|
|
112
|
+
closing if closing && lines[1...closing].none? { _1.strip.empty? }
|
|
113
|
+
end
|
|
114
|
+
|
|
115
|
+
def joined(first_line, continuation_lines)
|
|
116
|
+
return if continuation_lines.any? { _1.strip.empty? }
|
|
117
|
+
|
|
118
|
+
continuation_lines.reduce(first_line.rstrip) do |joined, line|
|
|
84
119
|
piece = line.strip
|
|
85
120
|
joined = joined.delete_suffix("\\").rstrip
|
|
86
121
|
if piece.match?(CLOSING_BRACKET_AT_START)
|
|
@@ -93,13 +128,10 @@ module SuperSlim
|
|
|
93
128
|
end
|
|
94
129
|
end
|
|
95
130
|
|
|
96
|
-
# A
|
|
97
|
-
def
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
return unless lines.last.strip.match?(CLOSING_BRACKET_AT_START) && lines[1...-1].none? { _1.strip.empty? }
|
|
101
|
-
|
|
102
|
-
lines.first.rstrip + lines[1...-1].map(&:strip).join(" ") + lines.last.strip
|
|
131
|
+
# A comment inside code spread by hand comments out the rest of the code once joined.
|
|
132
|
+
def ruby_reads_joined?(line, info)
|
|
133
|
+
start = code_start(line, info.output_column)
|
|
134
|
+
start.nil? || CodeWrapper.parse(line[start..])
|
|
103
135
|
end
|
|
104
136
|
|
|
105
137
|
def children?(outline, lineno)
|
|
@@ -121,10 +153,10 @@ module SuperSlim
|
|
|
121
153
|
return lines unless code_start && lines.last.size > @max_line_length
|
|
122
154
|
|
|
123
155
|
last_indent = lines.last[/\A */]
|
|
124
|
-
code_lines = CodeWrapper.call(lines.last[code_start..], last_indent, opens_block:, max_line_length: @max_line_length)
|
|
156
|
+
code_lines = CodeWrapper.call(lines.last[code_start..], last_indent, head: lines.last[0...code_start], opens_block:, max_line_length: @max_line_length)
|
|
125
157
|
return lines unless code_lines
|
|
126
158
|
|
|
127
|
-
lines[0...-1] +
|
|
159
|
+
lines[0...-1] + code_lines
|
|
128
160
|
end
|
|
129
161
|
|
|
130
162
|
# A dynamic tag, `*{tag: name}` or `li: *{tag: name}`, has no name for its attribute list to follow.
|
data/lib/super_slim/formatter.rb
CHANGED
|
@@ -15,35 +15,66 @@ module SuperSlim
|
|
|
15
15
|
OUTPUT = /\A(==?)([<>]*)\s*/
|
|
16
16
|
TAG_OUTPUT = /\A\s*(==?)(['<>]*)\s*/
|
|
17
17
|
REDUNDANT_DIV = /\Adiv(?=[.#][\p{Word}-])/
|
|
18
|
+
LOCALS_HEADER = %r{\A?/#\s*locals:}
|
|
19
|
+
CODE_LINE = /\A(?:-|==?[<>]*) (.+)\z/
|
|
20
|
+
# `while x do` is valid Ruby that nobody writes.
|
|
21
|
+
LOOP = /\A(?:while|until|for)\b/
|
|
18
22
|
# Prism 1.x counts in a node's flags whether it starts a line.
|
|
19
23
|
NEWLINE_FLAG = defined?(Prism::NodeFlags::NEWLINE) ? Prism::NodeFlags::NEWLINE : 0
|
|
20
24
|
FIELDS_BY_NODE_CLASS = {}
|
|
25
|
+
COMPARATOR_BY_NODE_CLASS = {}
|
|
21
26
|
|
|
22
27
|
def self.call(source, **)
|
|
23
28
|
new(**).call(source)
|
|
24
29
|
end
|
|
25
30
|
|
|
31
|
+
# Slim's own test for a block: children that render something, a comment alone opens none.
|
|
32
|
+
def self.block_opening_linenos(parser)
|
|
33
|
+
parser.line_by_node.filter_map do |node, lineno|
|
|
34
|
+
lineno if (node.is_a?(AST::Output) || node.is_a?(AST::Control)) && !AST.empty?(node.children)
|
|
35
|
+
end.to_set
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
# Slim opens a block when Ruby code has children, but only `do` shows that the call takes one. A `#` may start a
|
|
39
|
+
# comment, which `do` would land in.
|
|
40
|
+
def self.with_do(content)
|
|
41
|
+
code = content[CODE_LINE, 1]
|
|
42
|
+
return content if code.nil? || code.include?("#") || code.end_with?("{", "|", ",", "\\", ";", "&&", "||")
|
|
43
|
+
return content if code.match?(Compiler::BLOCK_SELF_OPENING) || code.match?(LOOP)
|
|
44
|
+
|
|
45
|
+
"#{content} do"
|
|
46
|
+
end
|
|
47
|
+
|
|
26
48
|
def initialize(tailwind_classes: SuperSlim.tailwind_classes, max_line_length: nil, attribute_delimiters: "()")
|
|
27
49
|
@tailwind_classes = tailwind_classes
|
|
28
50
|
@line_wrapper = LineWrapper.new(max_line_length, tailwind_classes:, attribute_delimiters:) if max_line_length
|
|
29
51
|
end
|
|
30
52
|
|
|
31
53
|
def call(source)
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
54
|
+
parser = Parser.new(outline: true, tailwind_classes: @tailwind_classes)
|
|
55
|
+
nodes = parser.call(source)
|
|
56
|
+
formatted = layout(source, parser)
|
|
57
|
+
unless formatted == source
|
|
58
|
+
source_code = compiled_code(nodes)
|
|
59
|
+
nodes, parser = parsed_template(formatted)
|
|
60
|
+
formatted_code = compiled_code(nodes)
|
|
61
|
+
# Most templates the layout changes compile to the very same Ruby: only the others are parsed.
|
|
62
|
+
unless source_code.is_a?(String) && source_code == formatted_code
|
|
63
|
+
formatted_ruby = parsed_ruby(formatted_code)
|
|
64
|
+
raise UnsafeFormattingError, "Formatting would change how this template renders" unless same_ruby?(parsed_ruby(source_code), formatted_ruby)
|
|
65
|
+
end
|
|
36
66
|
end
|
|
37
67
|
return formatted unless @line_wrapper
|
|
38
68
|
|
|
39
|
-
wrapped = @line_wrapper.call(formatted)
|
|
69
|
+
wrapped = @line_wrapper.call(formatted, parser:)
|
|
40
70
|
return formatted if wrapped == formatted
|
|
41
71
|
|
|
42
|
-
wrapped_ruby =
|
|
72
|
+
wrapped_ruby = parsed_ruby(compiled_code(parsed_template(wrapped, outline: false).first))
|
|
43
73
|
# Only Prism's tree vouches for a wrap: a compile error can read the same before and after it.
|
|
44
74
|
return formatted unless wrapped_ruby.is_a?(Prism::ParseResult)
|
|
45
75
|
|
|
46
|
-
|
|
76
|
+
formatted_ruby ||= parsed_ruby(formatted_code || compiled_code(nodes))
|
|
77
|
+
same_ruby?(formatted_ruby, wrapped_ruby) ? wrapped : formatted
|
|
47
78
|
# Prism walks code recursively too: code nested thousands deep can't be checked, so it isn't formatted.
|
|
48
79
|
rescue SystemStackError
|
|
49
80
|
raise UnsafeFormattingError, "Code nested too deep to check that formatting changes nothing"
|
|
@@ -51,25 +82,51 @@ module SuperSlim
|
|
|
51
82
|
|
|
52
83
|
private
|
|
53
84
|
|
|
54
|
-
def layout(source)
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
lines = source.delete_prefix("").split(/\r?\n/)
|
|
85
|
+
def layout(source, parser)
|
|
86
|
+
source = source.delete_prefix("")
|
|
87
|
+
lines = Parser.split_lines(source)
|
|
58
88
|
|
|
89
|
+
outline = parser.outline
|
|
90
|
+
unformatted_linenos = Parser.unformatted_linenos(lines, outline)
|
|
91
|
+
first_structure_lineno = (1...outline.size).find { outline[_1].kind == :structure }
|
|
92
|
+
# A partial's signature reads like a method's: alone at the top, set apart from the body.
|
|
93
|
+
locals_header_lineno = first_structure_lineno if first_structure_lineno && lines[first_structure_lineno - 1].match?(LOCALS_HEADER)
|
|
94
|
+
block_opening_linenos = Formatter.block_opening_linenos(parser)
|
|
59
95
|
formatted = []
|
|
60
96
|
indent_shift_by_lineno = {}
|
|
97
|
+
indent_shift = 0
|
|
98
|
+
previous_structure_lineno = nil
|
|
99
|
+
blank_line_pending = false
|
|
61
100
|
lines.each.with_index(1) do |line, lineno|
|
|
62
|
-
info =
|
|
101
|
+
info = outline[lineno]
|
|
102
|
+
# Unformatted lines move with the directive above them, so that they stay inside its block.
|
|
103
|
+
if unformatted_linenos.include?(lineno)
|
|
104
|
+
blank_line_pending = false
|
|
105
|
+
next formatted << shifted(line, indent_shift)
|
|
106
|
+
end
|
|
107
|
+
|
|
63
108
|
case info.kind
|
|
64
109
|
when :blank
|
|
65
110
|
formatted << "" unless formatted.empty? || formatted.last.empty?
|
|
111
|
+
blank_line_pending = formatted.last == ""
|
|
66
112
|
when :text_blank
|
|
67
113
|
formatted << ""
|
|
114
|
+
blank_line_pending = false
|
|
68
115
|
when :structure
|
|
116
|
+
previous_info = outline[previous_structure_lineno] if previous_structure_lineno
|
|
117
|
+
# A block's first line comes right after the line that opens it.
|
|
118
|
+
formatted.pop if blank_line_pending && previous_info && info.depth > previous_info.depth
|
|
119
|
+
formatted << "" if previous_structure_lineno && previous_structure_lineno == locals_header_lineno && formatted.last != ""
|
|
69
120
|
indent = info.depth * INDENT_WIDTH
|
|
70
|
-
indent_shift_by_lineno[lineno] = indent - indent_of(line)
|
|
71
|
-
|
|
121
|
+
indent_shift = indent_shift_by_lineno[lineno] = indent - indent_of(line)
|
|
122
|
+
content = structure(line, info)
|
|
123
|
+
# Code that goes on over more lines takes its `do` once the line wrapper joins it.
|
|
124
|
+
content = Formatter.with_do(content) if block_opening_linenos.include?(lineno) && !info.text && outline[lineno + 1]&.kind != :continuation
|
|
125
|
+
formatted << (" " * indent) + content
|
|
126
|
+
previous_structure_lineno = lineno
|
|
127
|
+
blank_line_pending = false
|
|
72
128
|
else
|
|
129
|
+
blank_line_pending = false
|
|
73
130
|
formatted << continuation(line, info, indent_shift_by_lineno.fetch(info.owner, 0))
|
|
74
131
|
end
|
|
75
132
|
end
|
|
@@ -96,6 +153,13 @@ module SuperSlim
|
|
|
96
153
|
(" " * indent) + content
|
|
97
154
|
end
|
|
98
155
|
|
|
156
|
+
def shifted(line, indent_shift)
|
|
157
|
+
line = expand_tabs(line)
|
|
158
|
+
return "" if line.strip.empty?
|
|
159
|
+
|
|
160
|
+
(" " * [line[/\A */].size + indent_shift, 0].max) + line.lstrip
|
|
161
|
+
end
|
|
162
|
+
|
|
99
163
|
def with_output_spacing(line, info)
|
|
100
164
|
return line unless info.output_column && line[info.output_column..] =~ TAG_OUTPUT
|
|
101
165
|
|
|
@@ -108,18 +172,35 @@ module SuperSlim
|
|
|
108
172
|
end
|
|
109
173
|
|
|
110
174
|
def expand_tabs(line)
|
|
175
|
+
return line unless line.include?("\t")
|
|
176
|
+
|
|
111
177
|
line.sub(/\A[ \t]*/) { _1.gsub(Parser::TAB, "\\1#{" " * Parser::TAB_SIZE}") }
|
|
112
178
|
end
|
|
113
179
|
|
|
180
|
+
# The template's nodes and its parser, which holds the outline; the error when it doesn't parse.
|
|
181
|
+
def parsed_template(template, outline: true)
|
|
182
|
+
parser = Parser.new(outline:, tailwind_classes: @tailwind_classes)
|
|
183
|
+
[parser.call(template), parser]
|
|
184
|
+
rescue Error => exception
|
|
185
|
+
[exception, nil]
|
|
186
|
+
end
|
|
187
|
+
|
|
188
|
+
# The Ruby the nodes compile to, their attributes sorted by name; the error when they don't parse or compile.
|
|
189
|
+
def compiled_code(nodes)
|
|
190
|
+
return nodes if nodes.is_a?(Error)
|
|
191
|
+
|
|
192
|
+
Compiler.new(format: :xml).call(with_attributes_sorted_by_name(nodes))
|
|
193
|
+
rescue Error => exception
|
|
194
|
+
exception
|
|
195
|
+
end
|
|
196
|
+
|
|
114
197
|
# 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
|
|
117
|
-
|
|
118
|
-
|
|
198
|
+
# message when the template doesn't compile.
|
|
199
|
+
def parsed_ruby(code)
|
|
200
|
+
return code.message if code.is_a?(Error)
|
|
201
|
+
|
|
119
202
|
parsed = Prism.parse("#{CodeWrapper::TEMPLATE_METHOD}#{code}\nend")
|
|
120
203
|
parsed.success? ? parsed : code.gsub(/(?:\s*[;\n]\s*)+/, ";")
|
|
121
|
-
rescue Error => exception
|
|
122
|
-
exception.message
|
|
123
204
|
end
|
|
124
205
|
|
|
125
206
|
# A tag renders the same whatever the order of its attributes, and with a class shortcut named twice once: both
|
|
@@ -149,52 +230,78 @@ module SuperSlim
|
|
|
149
230
|
same_node?(ruby.value, other_ruby.value) && comment_texts(ruby) == comment_texts(other_ruby)
|
|
150
231
|
end
|
|
151
232
|
|
|
152
|
-
# Walks both trees with a stack of its own
|
|
233
|
+
# Walks both trees with a stack of its own, the two values of each pair pushed one after the other: deep code or
|
|
234
|
+
# a deep template would exhaust Ruby's.
|
|
153
235
|
def same_node?(node, other_node)
|
|
154
|
-
|
|
155
|
-
until
|
|
156
|
-
|
|
236
|
+
pending_values = [node, other_node]
|
|
237
|
+
until pending_values.empty?
|
|
238
|
+
other_value = pending_values.pop
|
|
239
|
+
value = pending_values.pop
|
|
157
240
|
case value
|
|
158
241
|
when Prism::Node
|
|
159
|
-
return false unless value.instance_of?(other_value.class)
|
|
160
|
-
return false unless same_node_value?(value, other_value)
|
|
242
|
+
return false unless value.instance_of?(other_value.class) && node_comparator(value).call(value, other_value, pending_values)
|
|
161
243
|
when Array
|
|
162
244
|
return false unless other_value.is_a?(Array) && value.size == other_value.size
|
|
245
|
+
|
|
246
|
+
index = 0
|
|
247
|
+
while index < value.size
|
|
248
|
+
pending_values << value[index] << other_value[index]
|
|
249
|
+
index += 1
|
|
250
|
+
end
|
|
163
251
|
else
|
|
164
252
|
return false unless value == other_value
|
|
165
|
-
|
|
166
|
-
next
|
|
167
253
|
end
|
|
168
|
-
pairs.concat(children_pairs(value, other_value).reverse)
|
|
169
254
|
end
|
|
170
255
|
true
|
|
171
256
|
end
|
|
172
257
|
|
|
173
|
-
def
|
|
174
|
-
|
|
175
|
-
return node.location.start_line == other_node.location.start_line if node.is_a?(Prism::SourceLineNode)
|
|
176
|
-
|
|
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))
|
|
181
|
-
|
|
182
|
-
located_names.all? { |name| same_name?(node.public_send(name), other_node.public_send(name)) }
|
|
258
|
+
def node_comparator(node)
|
|
259
|
+
COMPARATOR_BY_NODE_CLASS[node.class] ||= Formatter.send(:comparator_for, node.class, *node_fields(node))
|
|
183
260
|
end
|
|
184
261
|
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
262
|
+
class << self
|
|
263
|
+
private
|
|
264
|
+
|
|
265
|
+
# Compares what two nodes of one class hold besides their children, and pushes their children on `pending_values`.
|
|
266
|
+
def comparator_for(node_class, field_names, located_names, flagged)
|
|
267
|
+
if node_class <= Prism::SourceLineNode
|
|
268
|
+
# `__LINE__` holds no value in the tree: removing a blank line above it changes what it renders.
|
|
269
|
+
->(source_line, other_source_line, _pending_values) { source_line.location.start_line == other_source_line.location.start_line }
|
|
270
|
+
elsif field_names.empty? && (node_class <= Prism::IntegerNode || node_class <= Prism::FloatNode)
|
|
271
|
+
# 2026-11: Prism 0.19 (Ruby 3.3) keeps the value of an integer or a float out of its fields.
|
|
272
|
+
->(number, other_number, _pending_values) { (!flagged || same_flags?(number, other_number)) && number.value == other_number.value }
|
|
273
|
+
else
|
|
274
|
+
clauses = []
|
|
275
|
+
clauses << "same_flags?(value, other_value)" if flagged
|
|
276
|
+
located_names.each { |name| clauses << "same_name?(value.#{name}, other_value.#{name})" }
|
|
277
|
+
pushes = field_names.map { |name| "pending_values << value.#{name} << other_value.#{name}" }
|
|
278
|
+
# Fields unrolled, without public_send: 2.5x faster with YJIT. The names come from Prism's own classes.
|
|
279
|
+
lambda_from(<<~LAMBDA)
|
|
280
|
+
->(value, other_value, pending_values) do
|
|
281
|
+
#{"return false unless #{clauses.join(" && ")}" unless clauses.empty?}
|
|
282
|
+
#{pushes.join("\n")}
|
|
283
|
+
true
|
|
284
|
+
end
|
|
285
|
+
LAMBDA
|
|
286
|
+
end
|
|
287
|
+
end
|
|
188
288
|
|
|
189
|
-
|
|
190
|
-
|
|
289
|
+
# Evaluated here, the lambda holds no local but its own source.
|
|
290
|
+
def lambda_from(code)
|
|
291
|
+
eval(code, binding, __FILE__, __LINE__) # rubocop:disable Security/Eval
|
|
292
|
+
end
|
|
293
|
+
|
|
294
|
+
def same_flags?(node, other_node)
|
|
295
|
+
(node.send(:flags) & ~NEWLINE_FLAG) == (other_node.send(:flags) & ~NEWLINE_FLAG)
|
|
296
|
+
end
|
|
191
297
|
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
298
|
+
# Beside a location, a field holds either a name or, from Prism 2 on, the source the location covers
|
|
299
|
+
# (`opening` beside `opening_loc`): only the name counts.
|
|
300
|
+
def same_name?(name, other_name)
|
|
301
|
+
return true unless name.is_a?(Symbol) || other_name.is_a?(Symbol)
|
|
196
302
|
|
|
197
|
-
|
|
303
|
+
name == other_name
|
|
304
|
+
end
|
|
198
305
|
end
|
|
199
306
|
|
|
200
307
|
# 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 { |
|
|
222
|
-
.filter_map do
|
|
223
|
-
next unless
|
|
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(
|
|
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).
|
|
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
|
|
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
|
data/lib/super_slim/linter.rb
CHANGED
|
@@ -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 =
|
|
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)
|
|
@@ -3,9 +3,9 @@
|
|
|
3
3
|
module SuperSlim
|
|
4
4
|
class Parser
|
|
5
5
|
# Read by hand, a line at a time: Prism would cost every process that renders templates its load time and memory.
|
|
6
|
-
# Misread, all rare after a bracket that ends its line or before a comment that ends the code: heredocs, `?(`,
|
|
7
|
-
# keyword (`when /'/`), `%` glued to a value (`"%d"%[a]`), interpolation
|
|
8
|
-
# other delimiters (`%|a(|`).
|
|
6
|
+
# Misread, all rare after a bracket that ends its line or before a comment that ends the code: heredocs, `?(`,
|
|
7
|
+
# `$'`, a regexp after a method name or a keyword (`when /'/`), `%` glued to a value (`"%d"%[a]`), interpolation
|
|
8
|
+
# in a %-literal and %-literals between other delimiters (`%|a(|`).
|
|
9
9
|
class RubyBrackets
|
|
10
10
|
PLAIN_RUBY = /[^()\[\]{}"'`#%\/]+/
|
|
11
11
|
QUOTED_TEXT_BY_DELIMITER = %w[" ` /].to_h { |delimiter| [delimiter, /(?:[^\\#{delimiter}#]|\\.|#(?!\{))*/m] }
|
|
@@ -18,6 +18,19 @@ module SuperSlim
|
|
|
18
18
|
# `%w[a) b(]` nests only its own kind of bracket.
|
|
19
19
|
PercentLiteral = Struct.new(:opening, :closing, :depth)
|
|
20
20
|
|
|
21
|
+
# Where a comment that follows code on its line starts in code, nil when there is none. One alone on a line is
|
|
22
|
+
# left out: a backslash before it carries the code on to that line.
|
|
23
|
+
def self.code_comment_offset(code)
|
|
24
|
+
return unless code.include?("#")
|
|
25
|
+
|
|
26
|
+
offset = new(code).trailing_comment_offset or return
|
|
27
|
+
code_before = code.byteslice(0, offset).sub(/[ \t]+\z/, "")
|
|
28
|
+
offset unless code_before.empty? || code_before.end_with?("\n")
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
# The byte offset of the comment that ends the code, if one does.
|
|
32
|
+
attr_reader :trailing_comment_offset
|
|
33
|
+
|
|
21
34
|
def initialize(code)
|
|
22
35
|
@scanner = StringScanner.new(code.dup)
|
|
23
36
|
# Whether each bracket still open ends its line.
|
|
@@ -28,9 +41,6 @@ module SuperSlim
|
|
|
28
41
|
read
|
|
29
42
|
end
|
|
30
43
|
|
|
31
|
-
# The byte offset of the comment that ends the code, if one does.
|
|
32
|
-
attr_reader :trailing_comment_offset
|
|
33
|
-
|
|
34
44
|
def <<(line)
|
|
35
45
|
@trailing_comment_offset = nil
|
|
36
46
|
@scanner << "\n" << line
|
data/lib/super_slim/parser.rb
CHANGED
|
@@ -55,9 +55,55 @@ module SuperSlim
|
|
|
55
55
|
# What the formatter and the linter need to know about each source line, indexed by line number. A tag's
|
|
56
56
|
# attribute list on one line is [first, last, [[first, last], …]], in columns of that line.
|
|
57
57
|
LineInfo = Struct.new(:kind, :depth, :owner, :text, :output_column, :attribute_lists)
|
|
58
|
+
FORMAT_DIRECTIVE = %r{\A?\s*/\s*super-slim:format\s+(off|on)\s*\z}
|
|
59
|
+
# A comment that renders nothing: not `/!` or `/[if IE]`.
|
|
60
|
+
CODE_COMMENT = %r{\A?\s*/(?![!\[])}
|
|
61
|
+
|
|
62
|
+
# A string separator splits 6x faster than the regexp, which only templates with \r need.
|
|
63
|
+
def self.split_lines(source)
|
|
64
|
+
source.include?("\r") ? source.split(/\r?\n/) : source.split("\n")
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
# Whether Slim, and so Brakeman, reads these lines of code as one: it goes on after a comma or a backslash, not
|
|
68
|
+
# after an opening bracket.
|
|
69
|
+
def self.slim_continuation?(lines)
|
|
70
|
+
lines[0...-1].all? { _1.rstrip.match?(LINE_CONTINUATION) }
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
# The lines after `/ super-slim:format off`, up to `/ super-slim:format on` at its depth or the end of the block
|
|
74
|
+
# that holds it. A directive deeper than the `off` is a line like the others; blank lines that close the block
|
|
75
|
+
# are not in it.
|
|
76
|
+
def self.unformatted_linenos(lines, outline)
|
|
77
|
+
unformatted_linenos = Set.new
|
|
78
|
+
return unformatted_linenos if lines.none? { _1.include?("super-slim:format") }
|
|
79
|
+
|
|
80
|
+
off_depth = nil
|
|
81
|
+
blank_linenos = []
|
|
82
|
+
lines.each.with_index(1) do |line, lineno|
|
|
83
|
+
info = outline[lineno]
|
|
84
|
+
if info.kind == :blank
|
|
85
|
+
blank_linenos << lineno if off_depth
|
|
86
|
+
next
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
if info.kind == :structure
|
|
90
|
+
off_depth = nil if off_depth && info.depth < off_depth
|
|
91
|
+
if (off_depth.nil? || info.depth == off_depth) && (directive = line[FORMAT_DIRECTIVE, 1])
|
|
92
|
+
off_depth = (directive == "off") ? info.depth : nil
|
|
93
|
+
blank_linenos.clear
|
|
94
|
+
next
|
|
95
|
+
end
|
|
96
|
+
end
|
|
97
|
+
unformatted_linenos.merge(blank_linenos) if off_depth
|
|
98
|
+
blank_linenos.clear
|
|
99
|
+
unformatted_linenos << lineno if off_depth
|
|
100
|
+
end
|
|
101
|
+
unformatted_linenos
|
|
102
|
+
end
|
|
58
103
|
|
|
104
|
+
attr_reader :outline, :line_by_node
|
|
59
105
|
# Ruby code and interpolated text, as [kind, first, last] character offsets in the source: what the RuboCop plugin lints.
|
|
60
|
-
attr_reader :
|
|
106
|
+
attr_reader :ruby_ranges
|
|
61
107
|
|
|
62
108
|
def initialize(file: nil, outline: false, tailwind_classes: SuperSlim.tailwind_classes)
|
|
63
109
|
@file = file
|
|
@@ -74,8 +120,7 @@ module SuperSlim
|
|
|
74
120
|
end
|
|
75
121
|
normalized = normalize(source)
|
|
76
122
|
@line_starts = line_starts(normalized, source.size - normalized.size) if @record_outline
|
|
77
|
-
|
|
78
|
-
@lines = normalized.include?("\r") ? normalized.split(/\r?\n/) : normalized.split("\n")
|
|
123
|
+
@lines = Parser.split_lines(normalized)
|
|
79
124
|
@scanner = StringScanner.new("")
|
|
80
125
|
@stacks = [root]
|
|
81
126
|
@indents = []
|
|
@@ -530,15 +575,13 @@ module SuperSlim
|
|
|
530
575
|
end
|
|
531
576
|
break unless closing
|
|
532
577
|
|
|
533
|
-
if @scanner.skip(ATTRIBUTE_LIST_END_BY_CLOSING[closing])
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
next_line
|
|
541
|
-
end
|
|
578
|
+
break if @scanner.skip(ATTRIBUTE_LIST_END_BY_CLOSING[closing])
|
|
579
|
+
|
|
580
|
+
@scanner.skip(WHITESPACE)
|
|
581
|
+
syntax_error!("Expected attribute") unless @scanner.eos?
|
|
582
|
+
@stacks.last << NEWLINE
|
|
583
|
+
syntax_error!("Expected closing delimiter #{closing}") if @lines.empty?
|
|
584
|
+
next_line
|
|
542
585
|
end
|
|
543
586
|
if outline && lineno == @lineno && !spans.empty?
|
|
544
587
|
list_first = spans.first.first unless closing
|
data/lib/super_slim/version.rb
CHANGED