super-slim 3.1.0 → 3.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +21 -1
- data/README.md +280 -138
- data/lib/super_slim/cli.rb +40 -8
- data/lib/super_slim/compiler.rb +29 -10
- data/lib/super_slim/formatter/line_wrapper.rb +10 -4
- data/lib/super_slim/formatter.rb +63 -20
- data/lib/super_slim/linter/rules.rb +8 -11
- data/lib/super_slim/linter.rb +53 -6
- data/lib/super_slim/parallel.rb +31 -11
- data/lib/super_slim/parser/ruby_brackets.rb +115 -0
- data/lib/super_slim/parser.rb +60 -35
- data/lib/super_slim/rubocop.rb +27 -5
- data/lib/super_slim/runtime.rb +12 -4
- data/lib/super_slim/version.rb +1 -1
- data/lib/super_slim.rb +2 -1
- metadata +2 -1
data/lib/super_slim/cli.rb
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
+
require "tempfile"
|
|
3
4
|
require_relative "../super_slim"
|
|
4
5
|
require_relative "linter"
|
|
5
6
|
require_relative "parallel"
|
|
@@ -15,6 +16,8 @@ module SuperSlim
|
|
|
15
16
|
EX_USAGE = 64
|
|
16
17
|
HELP_OPTIONS = %w[--help -h].freeze
|
|
17
18
|
OPTIONS_BY_COMMAND = {"format" => ["--check"], "fmt" => ["--check"]}.freeze
|
|
19
|
+
# File names and template text reach the terminal and CI logs, where escapes and a `::` line are commands.
|
|
20
|
+
CONTROL_CHARACTER = /[\x00-\x08\x0a-\x1f\x7f]/
|
|
18
21
|
|
|
19
22
|
def call(arguments)
|
|
20
23
|
return puts(USAGE) || 0 if arguments.first == "help" || arguments.intersect?(HELP_OPTIONS)
|
|
@@ -23,7 +26,11 @@ module SuperSlim
|
|
|
23
26
|
unknown_option = (arguments.grep(/\A-/) - OPTIONS_BY_COMMAND.fetch(command, [])).first
|
|
24
27
|
return warn("Unknown option #{unknown_option}", USAGE) || EX_USAGE if unknown_option
|
|
25
28
|
|
|
26
|
-
|
|
29
|
+
begin
|
|
30
|
+
configuration = Linter.configuration
|
|
31
|
+
rescue Error, Psych::Exception => exception
|
|
32
|
+
return warn(exception.message) || EX_USAGE
|
|
33
|
+
end
|
|
27
34
|
SuperSlim.tailwind_classes = configuration["tailwind_classes"] if configuration.key?("tailwind_classes")
|
|
28
35
|
case command
|
|
29
36
|
when "lint" then lint(arguments, configuration)
|
|
@@ -41,8 +48,13 @@ module SuperSlim
|
|
|
41
48
|
rescue Error => exception
|
|
42
49
|
return warn(exception.message) || EX_USAGE
|
|
43
50
|
end
|
|
44
|
-
offenses = Parallel.map(templates(paths))
|
|
45
|
-
|
|
51
|
+
offenses = Parallel.map(templates(paths)) do |path|
|
|
52
|
+
linter.call(path, File.read(path))
|
|
53
|
+
# One template that breaks SuperSlim, a bug or a stack too deep, must not hide the offenses of the others.
|
|
54
|
+
rescue StandardError, SystemStackError => exception
|
|
55
|
+
[Linter::Offense.new(path, 0, "Error", "#{exception.class}: #{exception.message.lines.first&.strip}")]
|
|
56
|
+
end.flatten
|
|
57
|
+
offenses.each { |offense| puts printable("#{offense.path}:#{offense.lineno}: [#{offense.rule}] #{offense.message}") }
|
|
46
58
|
offenses.empty? ? 0 : 1
|
|
47
59
|
end
|
|
48
60
|
|
|
@@ -54,22 +66,42 @@ module SuperSlim
|
|
|
54
66
|
formatted = formatter.call(source)
|
|
55
67
|
next if formatted == source
|
|
56
68
|
|
|
57
|
-
|
|
69
|
+
replace(path, formatted) unless check
|
|
58
70
|
[:reformatted, path]
|
|
59
|
-
rescue
|
|
60
|
-
|
|
71
|
+
rescue StandardError, SystemStackError => exception
|
|
72
|
+
message = exception.message.lines.first&.strip
|
|
73
|
+
[:refused, "#{path}: #{exception.is_a?(Error) ? message : "#{exception.class}: #{message}"}"]
|
|
61
74
|
end
|
|
62
|
-
outcomes.compact.each { |outcome, text| (outcome == :reformatted) ? puts(text) : warn(text) }
|
|
75
|
+
outcomes.compact.each { |outcome, text| (outcome == :reformatted) ? puts(printable(text)) : warn(printable(text)) }
|
|
63
76
|
(outcomes.any? { |outcome,| outcome == :refused || (outcome == :reformatted && check) }) ? 1 : 0
|
|
64
77
|
end
|
|
65
78
|
|
|
79
|
+
# A template found in a directory is a regular file of its own: a symlink in a checkout could point the
|
|
80
|
+
# formatter at any file the user can write, and a device or a FIFO would never end.
|
|
66
81
|
def templates(paths)
|
|
67
82
|
paths = ["."] if paths.empty?
|
|
68
83
|
paths.flat_map do |path|
|
|
69
84
|
next [path] unless File.directory?(path)
|
|
70
85
|
|
|
71
|
-
Dir.glob("**/*.slim", base: path).filter_map
|
|
86
|
+
Dir.glob("**/*.slim", base: path).filter_map do |template|
|
|
87
|
+
template_path = File.join(path, template)
|
|
88
|
+
template_path if !template.match?(SKIPPED_DIRECTORIES) && File.lstat(template_path).file?
|
|
89
|
+
end
|
|
72
90
|
end.sort
|
|
73
91
|
end
|
|
92
|
+
|
|
93
|
+
# Written beside the template then renamed over it, so that a full disk or a kill cannot leave it cut short.
|
|
94
|
+
def replace(path, content)
|
|
95
|
+
Tempfile.create([".super-slim-", ".tmp"], File.dirname(path)) do |file|
|
|
96
|
+
file.write(content)
|
|
97
|
+
file.close
|
|
98
|
+
File.chmod(File.stat(path).mode & 0o7777, file.path)
|
|
99
|
+
File.rename(file.path, path)
|
|
100
|
+
end
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
def printable(text)
|
|
104
|
+
text.gsub(CONTROL_CHARACTER) { |character| character.inspect[1...-1] }
|
|
105
|
+
end
|
|
74
106
|
end
|
|
75
107
|
end
|
data/lib/super_slim/compiler.rb
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
+
require "strscan"
|
|
4
|
+
|
|
3
5
|
module SuperSlim
|
|
4
6
|
class Compiler
|
|
5
7
|
include AST
|
|
@@ -34,7 +36,9 @@ module SuperSlim
|
|
|
34
36
|
CAPTURED_OUTPUT = /\A(if|unless)\b|\bdo\s*(\|[^|]*\|)?\s*$/
|
|
35
37
|
|
|
36
38
|
ESCAPED_INTERPOLATION = /\A\\#\{/
|
|
37
|
-
|
|
39
|
+
INTERPOLATION_START = /#\{/
|
|
40
|
+
OPENING_BRACE = "{".ord
|
|
41
|
+
CLOSING_BRACE = "}".ord
|
|
38
42
|
UNESCAPED_INTERPOLATION_CODE = /\A\{.*\}\Z/
|
|
39
43
|
INTERPOLATION_FREE_TEXT = /\A([#\\]?[^#\\]*([#\\][^\\#\{][^#\\]*)*)/ # rubocop:disable Style/RedundantRegexpEscape -- `#{` would open an interpolation
|
|
40
44
|
|
|
@@ -64,6 +68,21 @@ module SuperSlim
|
|
|
64
68
|
@code
|
|
65
69
|
end
|
|
66
70
|
|
|
71
|
+
# Byte offset of each `{` to that of the `}` closing it, in one pass: a regexp of balanced braces backtracks
|
|
72
|
+
# exponentially, and rescans the rest of the text from each `#{` left open.
|
|
73
|
+
def self.closing_braces(text)
|
|
74
|
+
closing_by_opening = {}
|
|
75
|
+
openings = []
|
|
76
|
+
text.each_byte.with_index do |byte, index|
|
|
77
|
+
if byte == OPENING_BRACE
|
|
78
|
+
openings << index
|
|
79
|
+
elsif byte == CLOSING_BRACE && (opening = openings.pop)
|
|
80
|
+
closing_by_opening[opening] = index
|
|
81
|
+
end
|
|
82
|
+
end
|
|
83
|
+
closing_by_opening
|
|
84
|
+
end
|
|
85
|
+
|
|
67
86
|
private
|
|
68
87
|
|
|
69
88
|
def compile_children(nodes)
|
|
@@ -328,20 +347,20 @@ module SuperSlim
|
|
|
328
347
|
def interpolation_parts(text)
|
|
329
348
|
return [[:static, text]] unless text.include?('#{')
|
|
330
349
|
|
|
350
|
+
closing_by_opening = Compiler.closing_braces(text)
|
|
351
|
+
scanner = StringScanner.new(text)
|
|
331
352
|
parts = []
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
when ESCAPED_INTERPOLATION
|
|
353
|
+
until scanner.eos?
|
|
354
|
+
if scanner.skip(ESCAPED_INTERPOLATION)
|
|
335
355
|
parts << [:static, '#{']
|
|
336
|
-
|
|
337
|
-
code =
|
|
356
|
+
elsif scanner.match?(INTERPOLATION_START) && (closing = closing_by_opening[scanner.pos + 1])
|
|
357
|
+
code = text.byteslice(scanner.pos + 2...closing)
|
|
358
|
+
scanner.pos = closing + 1
|
|
338
359
|
escape = !code.match?(UNESCAPED_INTERPOLATION_CODE)
|
|
339
360
|
parts << [:dynamic, escape ? code : code[1..-2], escape]
|
|
340
|
-
|
|
341
|
-
parts << [:static,
|
|
361
|
+
else
|
|
362
|
+
parts << [:static, scanner.scan(INTERPOLATION_FREE_TEXT)]
|
|
342
363
|
end
|
|
343
|
-
text = $'
|
|
344
|
-
break if text.empty?
|
|
345
364
|
end
|
|
346
365
|
parts
|
|
347
366
|
end
|
|
@@ -9,8 +9,14 @@ module SuperSlim
|
|
|
9
9
|
CODE_LINE = /\A *(?:-|==?[<>]*) /
|
|
10
10
|
TAG_OUTPUT = /\G\s*==?['<>]*\s*/
|
|
11
11
|
CONTINUATION_KINDS = %i[continuation text text_blank].freeze
|
|
12
|
-
|
|
12
|
+
DO_KEYWORDS = %i[KEYWORD_DO KEYWORD_DO_BLOCK KEYWORD_DO_LAMBDA KEYWORD_DO_LOOP].freeze
|
|
13
13
|
MODIFIERS = %i[KEYWORD_IF_MODIFIER KEYWORD_UNLESS_MODIFIER KEYWORD_WHILE_MODIFIER KEYWORD_UNTIL_MODIFIER KEYWORD_RESCUE_MODIFIER].freeze
|
|
14
|
+
# Prism 2 splits some tokens by role (BRACE_LEFT_HASH, PARENTHESIS_LEFT_GROUPING): older ones never emit them.
|
|
15
|
+
OPENING_BRACKETS = %i[
|
|
16
|
+
PARENTHESIS_LEFT PARENTHESIS_LEFT_PARENTHESES PARENTHESIS_LEFT_GROUPING BRACKET_LEFT BRACKET_LEFT_ARRAY
|
|
17
|
+
BRACE_LEFT BRACE_LEFT_HASH BRACE_LEFT_ARGUMENT LAMBDA_BEGIN EMBEXPR_BEGIN
|
|
18
|
+
].freeze
|
|
19
|
+
CLOSING_BRACKETS = %i[PARENTHESIS_RIGHT BRACKET_RIGHT BRACE_RIGHT EMBEXPR_END].freeze
|
|
14
20
|
|
|
15
21
|
# Templates attach ( and [ to their tag but set { apart, as a Ruby block: 6,097 public templates agree.
|
|
16
22
|
OPENING_BY_ATTRIBUTE_DELIMITERS = {"()" => "(", "[]" => "[", "{}" => " {"}.freeze
|
|
@@ -112,11 +118,11 @@ module SuperSlim
|
|
|
112
118
|
when :HEREDOC_START then return []
|
|
113
119
|
# `a, b = …` assigns several variables: its commas separate no arguments.
|
|
114
120
|
when :EQUAL then return [] if depth.zero? && !offsets.empty?
|
|
115
|
-
when *
|
|
121
|
+
when *DO_KEYWORDS then break
|
|
116
122
|
# RuboCop refuses a modifier that ends a statement spread over several lines (Style/MultilineIfModifier).
|
|
117
123
|
when *MODIFIERS then return [] if depth.zero?
|
|
118
|
-
when *
|
|
119
|
-
when *
|
|
124
|
+
when *OPENING_BRACKETS then depth += 1
|
|
125
|
+
when *CLOSING_BRACKETS then depth -= 1
|
|
120
126
|
end
|
|
121
127
|
end
|
|
122
128
|
offsets
|
data/lib/super_slim/formatter.rb
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
+
require "prism"
|
|
3
4
|
require_relative "formatter/line_wrapper"
|
|
4
5
|
|
|
5
6
|
module SuperSlim
|
|
@@ -12,6 +13,7 @@ module SuperSlim
|
|
|
12
13
|
OUTPUT = /\A(==?)([<>]*)\s*/
|
|
13
14
|
TAG_OUTPUT = /\A\s*(==?)(['<>]*)\s*/
|
|
14
15
|
REDUNDANT_DIV = /\Adiv(?=[.#][\p{Word}-])/
|
|
16
|
+
# Prism 1.x counts in a node's flags whether it starts a line.
|
|
15
17
|
NEWLINE_FLAG = defined?(Prism::NodeFlags::NEWLINE) ? Prism::NodeFlags::NEWLINE : 0
|
|
16
18
|
FIELDS_BY_NODE_CLASS = {}
|
|
17
19
|
|
|
@@ -35,7 +37,14 @@ module SuperSlim
|
|
|
35
37
|
wrapped = @line_wrapper.call(formatted)
|
|
36
38
|
return formatted if wrapped == formatted
|
|
37
39
|
|
|
38
|
-
|
|
40
|
+
wrapped_ruby = compiled_ruby(wrapped)
|
|
41
|
+
# Only Prism's tree vouches for a wrap: a compile error can read the same before and after it.
|
|
42
|
+
return formatted unless wrapped_ruby.is_a?(Prism::ParseResult)
|
|
43
|
+
|
|
44
|
+
same_ruby?(formatted_ruby || compiled_ruby(formatted), wrapped_ruby) ? wrapped : formatted
|
|
45
|
+
# Prism walks code recursively too: code nested thousands deep can't be checked, so it isn't formatted.
|
|
46
|
+
rescue SystemStackError
|
|
47
|
+
raise UnsafeFormattingError, "Code nested too deep to check that formatting changes nothing"
|
|
39
48
|
end
|
|
40
49
|
|
|
41
50
|
private
|
|
@@ -86,10 +95,9 @@ module SuperSlim
|
|
|
86
95
|
end
|
|
87
96
|
|
|
88
97
|
def with_output_spacing(line, info)
|
|
89
|
-
return line unless info.output_column
|
|
98
|
+
return line unless info.output_column && line[info.output_column..] =~ TAG_OUTPUT
|
|
90
99
|
|
|
91
100
|
before = line[0...info.output_column].rstrip
|
|
92
|
-
line[info.output_column..] =~ TAG_OUTPUT
|
|
93
101
|
$'.empty? ? "#{before} #{$1}#{$2}" : "#{before} #{$1}#{$2} #{$'}"
|
|
94
102
|
end
|
|
95
103
|
|
|
@@ -101,7 +109,8 @@ module SuperSlim
|
|
|
101
109
|
line.sub(/\A[ \t]*/) { _1.gsub(Parser::TAB, "\\1#{" " * Parser::TAB_SIZE}") }
|
|
102
110
|
end
|
|
103
111
|
|
|
104
|
-
# Prism's tree of the compiled Ruby
|
|
112
|
+
# Prism's tree of the compiled Ruby; that Ruby with its separators folded when Prism can't read it; the error
|
|
113
|
+
# when the template doesn't compile.
|
|
105
114
|
def compiled_ruby(source)
|
|
106
115
|
code = SuperSlim.compile(source, tailwind_classes: @tailwind_classes, format: :xml)
|
|
107
116
|
# Rails runs a template inside a method, where `yield` is valid.
|
|
@@ -119,30 +128,64 @@ module SuperSlim
|
|
|
119
128
|
same_node?(ruby.value, other_ruby.value) && comment_texts(ruby) == comment_texts(other_ruby)
|
|
120
129
|
end
|
|
121
130
|
|
|
131
|
+
# Walks both trees with a stack of its own: deep code or a deep template would exhaust Ruby's.
|
|
122
132
|
def same_node?(node, other_node)
|
|
123
|
-
|
|
133
|
+
pairs = [[node, other_node]]
|
|
134
|
+
until pairs.empty?
|
|
135
|
+
value, other_value = pairs.pop
|
|
136
|
+
case value
|
|
137
|
+
when Prism::Node
|
|
138
|
+
return false unless value.instance_of?(other_value.class)
|
|
139
|
+
return false unless same_node_value?(value, other_value)
|
|
140
|
+
when Array
|
|
141
|
+
return false unless other_value.is_a?(Array) && value.size == other_value.size
|
|
142
|
+
else
|
|
143
|
+
return false unless value == other_value
|
|
144
|
+
|
|
145
|
+
next
|
|
146
|
+
end
|
|
147
|
+
pairs.concat(children_pairs(value, other_value).reverse)
|
|
148
|
+
end
|
|
149
|
+
true
|
|
150
|
+
end
|
|
151
|
+
|
|
152
|
+
def same_node_value?(node, other_node)
|
|
153
|
+
# `__LINE__` holds no value in the tree: removing a blank line above it changes what it renders.
|
|
154
|
+
return node.location.start_line == other_node.location.start_line if node.is_a?(Prism::SourceLineNode)
|
|
124
155
|
|
|
125
|
-
field_names,
|
|
126
|
-
return false if
|
|
156
|
+
field_names, located_names, flagged = node_fields(node)
|
|
157
|
+
return false if flagged && (node.send(:flags) & ~NEWLINE_FLAG) != (other_node.send(:flags) & ~NEWLINE_FLAG)
|
|
158
|
+
# 2026-11: Prism 0.19 (Ruby 3.3) keeps the value of an integer or a float out of its fields.
|
|
159
|
+
return node.value == other_node.value if field_names.empty? && (node.is_a?(Prism::IntegerNode) || node.is_a?(Prism::FloatNode))
|
|
127
160
|
|
|
128
|
-
|
|
161
|
+
located_names.all? { |name| same_name?(node.public_send(name), other_node.public_send(name)) }
|
|
129
162
|
end
|
|
130
163
|
|
|
131
|
-
def
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
164
|
+
def children_pairs(value, other_value)
|
|
165
|
+
return value.zip(other_value) if value.is_a?(Array)
|
|
166
|
+
return [] if value.is_a?(Prism::SourceLineNode)
|
|
167
|
+
|
|
168
|
+
node_fields(value).first.map { |name| [value.public_send(name), other_value.public_send(name)] }
|
|
169
|
+
end
|
|
170
|
+
|
|
171
|
+
# Beside a location, a field holds either a name or, from Prism 2 on, the source the location covers
|
|
172
|
+
# (`opening` beside `opening_loc`): only the name counts.
|
|
173
|
+
def same_name?(name, other_name)
|
|
174
|
+
return true unless name.is_a?(Symbol) || other_name.is_a?(Symbol)
|
|
175
|
+
|
|
176
|
+
name == other_name
|
|
137
177
|
end
|
|
138
178
|
|
|
139
|
-
# Prism 0.19 (Ruby 3.3) has no reflection API: the field names come from the first node of each
|
|
140
|
-
# 1.x keeps flags out of deconstruct_keys
|
|
179
|
+
# 2026-11: Prism 0.19 (Ruby 3.3) has no reflection API: the field names come from the first node of each
|
|
180
|
+
# class. Prism 1.x keeps flags out of deconstruct_keys.
|
|
141
181
|
def node_fields(node)
|
|
142
|
-
FIELDS_BY_NODE_CLASS[node.class] ||=
|
|
143
|
-
node.deconstruct_keys(nil).keys
|
|
144
|
-
|
|
145
|
-
|
|
182
|
+
FIELDS_BY_NODE_CLASS[node.class] ||= begin
|
|
183
|
+
keys = node.deconstruct_keys(nil).keys
|
|
184
|
+
located_names, field_names = (keys - %i[node_id flags location])
|
|
185
|
+
.reject { _1.end_with?("_loc") }
|
|
186
|
+
.partition { keys.include?(:"#{_1}_loc") }
|
|
187
|
+
[field_names, located_names, node.respond_to?(:flags, true)]
|
|
188
|
+
end
|
|
146
189
|
end
|
|
147
190
|
|
|
148
191
|
def comment_texts(ruby)
|
|
@@ -49,11 +49,7 @@ module SuperSlim
|
|
|
49
49
|
|
|
50
50
|
# Text nodes carry no line of their own: they take the line of the closest node that does.
|
|
51
51
|
def line_near(document, node, ancestors)
|
|
52
|
-
|
|
53
|
-
lineno = document.line_of(candidate)
|
|
54
|
-
return lineno if lineno
|
|
55
|
-
end
|
|
56
|
-
nil
|
|
52
|
+
document.line_of(node) || document.line_of(ancestors.located)
|
|
57
53
|
end
|
|
58
54
|
|
|
59
55
|
def each_line(document)
|
|
@@ -153,7 +149,8 @@ module SuperSlim
|
|
|
153
149
|
|
|
154
150
|
line = document.lines[lineno - 1]
|
|
155
151
|
if info.output_column
|
|
156
|
-
line[info.output_column..] =~ TAG_OUTPUT
|
|
152
|
+
next unless line[info.output_column..] =~ TAG_OUTPUT
|
|
153
|
+
|
|
157
154
|
offense(document, lineno, "Put a space before and after `#{$2}`") if $1.empty? || $4.empty?
|
|
158
155
|
elsif info.kind == :structure
|
|
159
156
|
case line.lstrip
|
|
@@ -235,7 +232,7 @@ module SuperSlim
|
|
|
235
232
|
|
|
236
233
|
document.enum_for(:each_node).filter_map do |node, ancestors|
|
|
237
234
|
next unless node.is_a?(AST::Tag) && node.name.match?(/[A-Z]/)
|
|
238
|
-
next if ancestors.
|
|
235
|
+
next if ancestors.inside_svg
|
|
239
236
|
|
|
240
237
|
offense(document, document.line_of(node), "Write `#{node.name.downcase}` in lowercase")
|
|
241
238
|
end
|
|
@@ -276,7 +273,7 @@ module SuperSlim
|
|
|
276
273
|
def offenses(document, _source)
|
|
277
274
|
branch_by_id = {}
|
|
278
275
|
enum_for(:each_tag, document).filter_map do |tag, ancestors|
|
|
279
|
-
branch = ancestors.
|
|
276
|
+
branch = ancestors.control
|
|
280
277
|
literal_attributes(tag, "id").filter_map do |attribute|
|
|
281
278
|
id = literal_value(attribute)
|
|
282
279
|
if branch_by_id.key?(id) && branch_by_id[id].equal?(branch)
|
|
@@ -319,7 +316,7 @@ module SuperSlim
|
|
|
319
316
|
class NestedLinks < Rule
|
|
320
317
|
def offenses(document, _source)
|
|
321
318
|
enum_for(:each_tag, document, "a").filter_map do |tag, ancestors|
|
|
322
|
-
next unless ancestors.
|
|
319
|
+
next unless ancestors.inside_link
|
|
323
320
|
|
|
324
321
|
offense(document, document.line_of(tag), "Links cannot contain links")
|
|
325
322
|
end
|
|
@@ -521,7 +518,7 @@ module SuperSlim
|
|
|
521
518
|
|
|
522
519
|
def offenses(document, _source)
|
|
523
520
|
document.enum_for(:each_node).filter_map do |node, ancestors|
|
|
524
|
-
next unless node.is_a?(AST::TextBlock) && ancestors.
|
|
521
|
+
next unless node.is_a?(AST::TextBlock) && !ancestors.inside_comment
|
|
525
522
|
|
|
526
523
|
text = node.children.grep(AST::Text).map(&:text).join(" ").gsub(/\s+/, " ").strip
|
|
527
524
|
next unless text.gsub(NOT_WORDS, "").match?(/\p{L}/)
|
|
@@ -561,7 +558,7 @@ module SuperSlim
|
|
|
561
558
|
|
|
562
559
|
text = $2
|
|
563
560
|
lineno = document.line_of(node)
|
|
564
|
-
message = if text.match?(READ_AS_SYNTAX_AFTER_TAG) && ancestors.
|
|
561
|
+
message = if text.match?(READ_AS_SYNTAX_AFTER_TAG) && ancestors.last && document.line_of(ancestors.last) == lineno
|
|
565
562
|
"Write the text `| #{text}` on its own line, under the tag: inline, it would read as attributes"
|
|
566
563
|
else
|
|
567
564
|
"Write the text `| #{text}` instead of outputting a string"
|
data/lib/super_slim/linter.rb
CHANGED
|
@@ -6,15 +6,42 @@ module SuperSlim
|
|
|
6
6
|
class Linter
|
|
7
7
|
Offense = Data.define(:path, :lineno, :rule, :message)
|
|
8
8
|
|
|
9
|
+
# What the rules ask of a node's ancestors, worked out as the tree is walked: a list of them, copied at each
|
|
10
|
+
# level, made linting quadratic in the depth of the tree.
|
|
11
|
+
Ancestors = Data.define(:last, :control, :located, :inside_svg, :inside_link, :inside_comment) do
|
|
12
|
+
def self.root = new(nil, nil, nil, false, false, false)
|
|
13
|
+
|
|
14
|
+
def under(node, line_by_node)
|
|
15
|
+
tag_name = node.name if node.is_a?(AST::Tag)
|
|
16
|
+
Ancestors.new(
|
|
17
|
+
last: node,
|
|
18
|
+
control: node.is_a?(AST::Control) ? node : control,
|
|
19
|
+
located: line_by_node.key?(node) ? node : located,
|
|
20
|
+
inside_svg: inside_svg || tag_name == "svg",
|
|
21
|
+
inside_link: inside_link || tag_name == "a",
|
|
22
|
+
inside_comment: inside_comment || node.is_a?(AST::Comment)
|
|
23
|
+
)
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
|
|
9
27
|
# The tree is walked once per template: every rule iterates `visits`, each node with its ancestors.
|
|
10
28
|
Document = Data.define(:path, :lines, :nodes, :outline, :line_by_node, :visits, :tag_visits) do
|
|
11
|
-
|
|
12
|
-
|
|
29
|
+
# Depth first, children before the next sibling, with a stack of its own: a deep template would exhaust Ruby's.
|
|
30
|
+
def self.visits_of(nodes, line_by_node)
|
|
31
|
+
visits = []
|
|
32
|
+
frames = [[nodes || [], 0, Ancestors.root]]
|
|
33
|
+
until frames.empty?
|
|
34
|
+
frame = frames.last
|
|
35
|
+
siblings, index, ancestors = frame
|
|
36
|
+
next frames.pop if index == siblings.size
|
|
37
|
+
|
|
38
|
+
frame[1] += 1
|
|
39
|
+
node = siblings[index]
|
|
13
40
|
next if node == AST::NEWLINE
|
|
14
41
|
|
|
15
42
|
visits << [node, ancestors]
|
|
16
43
|
children = children_of(node)
|
|
17
|
-
|
|
44
|
+
frames << [children, 0, ancestors.under(node, line_by_node)] if children
|
|
18
45
|
end
|
|
19
46
|
visits
|
|
20
47
|
end
|
|
@@ -43,6 +70,7 @@ module SuperSlim
|
|
|
43
70
|
end
|
|
44
71
|
|
|
45
72
|
CONFIG_FILE = ".super-slim.yml"
|
|
73
|
+
GLOB_OPTIONS = %w[include exclude].freeze
|
|
46
74
|
|
|
47
75
|
def self.load(directory = Dir.pwd)
|
|
48
76
|
new(configuration(directory).fetch("linters", {}), directory)
|
|
@@ -50,7 +78,26 @@ module SuperSlim
|
|
|
50
78
|
|
|
51
79
|
def self.configuration(directory = Dir.pwd)
|
|
52
80
|
path = File.join(directory, CONFIG_FILE)
|
|
53
|
-
File.exist?(path) ? YAML.safe_load_file(path) || {} : {}
|
|
81
|
+
configuration = File.exist?(path) ? YAML.safe_load_file(path) || {} : {}
|
|
82
|
+
check_configuration(configuration)
|
|
83
|
+
configuration
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
# A value of the wrong shape would fail later, inside a rule, with a NoMethodError naming none of this file.
|
|
87
|
+
def self.check_configuration(configuration)
|
|
88
|
+
raise Error, "#{CONFIG_FILE}: expected a mapping of settings" unless configuration.is_a?(Hash)
|
|
89
|
+
|
|
90
|
+
%w[linters format fmt].each do |key|
|
|
91
|
+
raise Error, "#{CONFIG_FILE}: `#{key}` must be a mapping" unless configuration.fetch(key, {}).is_a?(Hash)
|
|
92
|
+
end
|
|
93
|
+
configuration.fetch("linters", {}).each do |rule_name, options|
|
|
94
|
+
raise Error, "#{CONFIG_FILE}: `linters: #{rule_name}` must be a mapping of options" unless options.is_a?(Hash)
|
|
95
|
+
|
|
96
|
+
GLOB_OPTIONS.each do |key|
|
|
97
|
+
globs = Array(options[key])
|
|
98
|
+
raise Error, "#{CONFIG_FILE}: `#{rule_name}: #{key}` must be a list of globs" unless globs.all?(String)
|
|
99
|
+
end
|
|
100
|
+
end
|
|
54
101
|
end
|
|
55
102
|
|
|
56
103
|
# include: and exclude: globs match paths relative to `root`, the directory of .super-slim.yml.
|
|
@@ -66,13 +113,13 @@ module SuperSlim
|
|
|
66
113
|
def call(path, source)
|
|
67
114
|
parser = Parser.new(file: path, outline: true)
|
|
68
115
|
nodes = parser.call(source)
|
|
69
|
-
visits = Document.visits_of(nodes)
|
|
116
|
+
visits = Document.visits_of(nodes, parser.line_by_node)
|
|
70
117
|
document = Document.new(path:, lines: source.split(/\r?\n/), nodes:, outline: parser.outline, line_by_node: parser.line_by_node,
|
|
71
118
|
visits:, tag_visits: visits.select { |node,| node.is_a?(AST::Tag) })
|
|
72
119
|
relative_path = File.expand_path(path).delete_prefix(@root)
|
|
73
120
|
offenses = @rules.select { _1.applies_to?(relative_path) }.flat_map { _1.offenses(document, source) }
|
|
74
121
|
# sort_by is not stable: the index keeps offenses of one line in rule order.
|
|
75
|
-
offenses.each_with_index.sort_by { |offense, index| [offense.lineno, index] }.map(&:first)
|
|
122
|
+
offenses.each_with_index.sort_by { |offense, index| [offense.lineno.to_i, index] }.map(&:first)
|
|
76
123
|
rescue SyntaxError => exception
|
|
77
124
|
[Offense.new(path, exception.lineno, "Syntax", exception.error)]
|
|
78
125
|
end
|
data/lib/super_slim/parallel.rb
CHANGED
|
@@ -12,25 +12,45 @@ module SuperSlim
|
|
|
12
12
|
process_count = [Etc.nprocessors, items.size / minimum_per_process].min
|
|
13
13
|
return items.map(&block) if process_count < 2 || !Process.respond_to?(:fork)
|
|
14
14
|
|
|
15
|
-
|
|
15
|
+
workers = items.each_slice((items.size.to_f / process_count).ceil).map do |slice|
|
|
16
16
|
reader, writer = IO.pipe
|
|
17
|
-
fork do
|
|
17
|
+
pid = fork do
|
|
18
18
|
reader.close
|
|
19
|
-
|
|
20
|
-
slice.map(&block)
|
|
21
|
-
rescue Exception => exception # rubocop:disable Lint/RescueException -- re-raised by the parent
|
|
22
|
-
exception
|
|
23
|
-
end
|
|
24
|
-
writer.binmode.write(Marshal.dump(results))
|
|
19
|
+
writer.binmode.write(dump { slice.map(&block) })
|
|
25
20
|
exit!(0)
|
|
26
21
|
end
|
|
27
22
|
writer.close
|
|
28
|
-
reader
|
|
23
|
+
[pid, reader]
|
|
29
24
|
end
|
|
30
|
-
results_by_process =
|
|
31
|
-
Process.waitall
|
|
25
|
+
results_by_process = workers.map { |pid, reader| receive(pid, reader) }
|
|
32
26
|
results_by_process.each { |results| raise results if results.is_a?(Exception) }
|
|
33
27
|
results_by_process.flatten(1)
|
|
28
|
+
ensure
|
|
29
|
+
workers&.each do |pid, reader|
|
|
30
|
+
reader.close unless reader.closed?
|
|
31
|
+
Process.wait(pid)
|
|
32
|
+
rescue Errno::ECHILD # already reaped by receive
|
|
33
|
+
end
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
# A result or an exception Marshal cannot dump (a Proc, an IO) is sent as a RuntimeError naming it.
|
|
37
|
+
def dump
|
|
38
|
+
Marshal.dump(yield)
|
|
39
|
+
rescue Exception => exception # rubocop:disable Lint/RescueException -- re-raised by the parent
|
|
40
|
+
begin
|
|
41
|
+
Marshal.dump(exception)
|
|
42
|
+
rescue TypeError
|
|
43
|
+
Marshal.dump(RuntimeError.new("#{exception.class}: #{exception.message}"))
|
|
44
|
+
end
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
def receive(pid, reader)
|
|
48
|
+
payload = reader.binmode.read
|
|
49
|
+
reader.close
|
|
50
|
+
Process.wait(pid)
|
|
51
|
+
raise Error, "Worker #{pid} died: #{$?}" unless $?.success? && !payload.empty?
|
|
52
|
+
|
|
53
|
+
Marshal.load(payload) # rubocop:disable Security/MarshalLoad -- written by our own child
|
|
34
54
|
end
|
|
35
55
|
end
|
|
36
56
|
end
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module SuperSlim
|
|
4
|
+
class Parser
|
|
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: heredocs, `?(`, `$'`, a regexp after a method name or a
|
|
7
|
+
# keyword (`when /'/`), `%` glued to a value (`"%d"%[a]`), interpolation in a %-literal and %-literals between
|
|
8
|
+
# other delimiters (`%|a(|`).
|
|
9
|
+
class RubyBrackets
|
|
10
|
+
PLAIN_RUBY = /[^()\[\]{}"'`#%\/]+/
|
|
11
|
+
QUOTED_TEXT_BY_DELIMITER = %w[" ` /].to_h { |delimiter| [delimiter, /(?:[^\\#{delimiter}#]|\\.|#(?!\{))*/m] }
|
|
12
|
+
.merge("'" => /(?:[^\\']|\\.)*/m).freeze
|
|
13
|
+
PERCENT_LITERAL_OPENING = /[qQwWiIrsx]?([(\[{<])/
|
|
14
|
+
BYTES_BEFORE_REGEXP = "\n(,[{|&=!~;:?<>+-*%^".bytes.freeze
|
|
15
|
+
LINE_END = /[ \t]*(?:\n|\z)/
|
|
16
|
+
LINE_END_OR_COMMENT = /[ \t]*(?:[#\n]|\z)/
|
|
17
|
+
|
|
18
|
+
# `%w[a) b(]` nests only its own kind of bracket.
|
|
19
|
+
PercentLiteral = Struct.new(:opening, :closing, :depth)
|
|
20
|
+
|
|
21
|
+
def initialize(code)
|
|
22
|
+
@scanner = StringScanner.new(code.dup)
|
|
23
|
+
# Whether each bracket still open ends its line.
|
|
24
|
+
@open_brackets = []
|
|
25
|
+
# The strings, regexps and %-literals the scanner is in, innermost last; an integer is an interpolation, the
|
|
26
|
+
# number of open brackets once its `#{` is counted.
|
|
27
|
+
@literals = []
|
|
28
|
+
read
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
def <<(line)
|
|
32
|
+
@scanner << "\n" << line
|
|
33
|
+
read
|
|
34
|
+
self
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
def open_at_line_end?
|
|
38
|
+
@open_brackets.any?
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
private
|
|
42
|
+
|
|
43
|
+
def read
|
|
44
|
+
until @scanner.eos?
|
|
45
|
+
case (literal = @literals.last)
|
|
46
|
+
when String then read_quoted(literal)
|
|
47
|
+
when PercentLiteral then read_percent_literal(literal)
|
|
48
|
+
else read_code(literal)
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
def read_code(interpolation_depth)
|
|
54
|
+
until @scanner.eos?
|
|
55
|
+
next if @scanner.skip(PLAIN_RUBY)
|
|
56
|
+
|
|
57
|
+
character = @scanner.getch
|
|
58
|
+
case character
|
|
59
|
+
when "(", "[", "{" then @open_brackets << @scanner.match?(LINE_END_OR_COMMENT)
|
|
60
|
+
when ")", "]", "}"
|
|
61
|
+
@open_brackets.pop
|
|
62
|
+
return @literals.pop if interpolation_depth && @open_brackets.size < interpolation_depth
|
|
63
|
+
when '"', "'", "`" then return @literals << character
|
|
64
|
+
when "/" then return @literals << character if regexp_start?
|
|
65
|
+
when "%" then return open_percent_literal if @scanner.scan(PERCENT_LITERAL_OPENING)
|
|
66
|
+
when "#" then @scanner.skip_until(LINE_END)
|
|
67
|
+
end
|
|
68
|
+
end
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
def read_quoted(delimiter)
|
|
72
|
+
until @scanner.eos?
|
|
73
|
+
@scanner.skip(QUOTED_TEXT_BY_DELIMITER[delimiter])
|
|
74
|
+
return @literals.pop if @scanner.skip(delimiter)
|
|
75
|
+
|
|
76
|
+
@scanner.getch
|
|
77
|
+
next unless @scanner.skip("{")
|
|
78
|
+
|
|
79
|
+
@open_brackets << @scanner.match?(LINE_END_OR_COMMENT)
|
|
80
|
+
return @literals << @open_brackets.size
|
|
81
|
+
end
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
def regexp_start?
|
|
85
|
+
code = @scanner.string
|
|
86
|
+
offset = @scanner.pos - 2
|
|
87
|
+
offset -= 1 while offset >= 0 && (code.getbyte(offset) == SPACE_BYTE || code.getbyte(offset) == TAB_BYTE)
|
|
88
|
+
offset.negative? || BYTES_BEFORE_REGEXP.include?(code.getbyte(offset))
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
def open_percent_literal
|
|
92
|
+
opening = @scanner[1]
|
|
93
|
+
@open_brackets << @scanner.match?(LINE_END)
|
|
94
|
+
@literals << PercentLiteral.new(opening, DELIMITERS.fetch(opening, ">"), 1)
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
def read_percent_literal(literal)
|
|
98
|
+
until @scanner.eos?
|
|
99
|
+
character = @scanner.getch
|
|
100
|
+
if character == "\\"
|
|
101
|
+
@scanner.getch
|
|
102
|
+
elsif character == literal.opening
|
|
103
|
+
literal.depth += 1
|
|
104
|
+
elsif character == literal.closing
|
|
105
|
+
literal.depth -= 1
|
|
106
|
+
next unless literal.depth.zero?
|
|
107
|
+
|
|
108
|
+
@open_brackets.pop
|
|
109
|
+
return @literals.pop
|
|
110
|
+
end
|
|
111
|
+
end
|
|
112
|
+
end
|
|
113
|
+
end
|
|
114
|
+
end
|
|
115
|
+
end
|