super-slim 3.1.0 → 3.2.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.
@@ -1,5 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "prism"
4
+ require_relative "formatter/attribute_arranger"
5
+ require_relative "formatter/code_wrapper"
3
6
  require_relative "formatter/line_wrapper"
4
7
 
5
8
  module SuperSlim
@@ -12,6 +15,7 @@ module SuperSlim
12
15
  OUTPUT = /\A(==?)([<>]*)\s*/
13
16
  TAG_OUTPUT = /\A\s*(==?)(['<>]*)\s*/
14
17
  REDUNDANT_DIV = /\Adiv(?=[.#][\p{Word}-])/
18
+ # Prism 1.x counts in a node's flags whether it starts a line.
15
19
  NEWLINE_FLAG = defined?(Prism::NodeFlags::NEWLINE) ? Prism::NodeFlags::NEWLINE : 0
16
20
  FIELDS_BY_NODE_CLASS = {}
17
21
 
@@ -35,7 +39,14 @@ module SuperSlim
35
39
  wrapped = @line_wrapper.call(formatted)
36
40
  return formatted if wrapped == formatted
37
41
 
38
- same_ruby?(formatted_ruby || compiled_ruby(formatted), compiled_ruby(wrapped)) ? wrapped : formatted
42
+ wrapped_ruby = compiled_ruby(wrapped)
43
+ # Only Prism's tree vouches for a wrap: a compile error can read the same before and after it.
44
+ return formatted unless wrapped_ruby.is_a?(Prism::ParseResult)
45
+
46
+ same_ruby?(formatted_ruby || compiled_ruby(formatted), wrapped_ruby) ? wrapped : formatted
47
+ # Prism walks code recursively too: code nested thousands deep can't be checked, so it isn't formatted.
48
+ rescue SystemStackError
49
+ raise UnsafeFormattingError, "Code nested too deep to check that formatting changes nothing"
39
50
  end
40
51
 
41
52
  private
@@ -86,10 +97,9 @@ module SuperSlim
86
97
  end
87
98
 
88
99
  def with_output_spacing(line, info)
89
- return line unless info.output_column
100
+ return line unless info.output_column && line[info.output_column..] =~ TAG_OUTPUT
90
101
 
91
102
  before = line[0...info.output_column].rstrip
92
- line[info.output_column..] =~ TAG_OUTPUT
93
103
  $'.empty? ? "#{before} #{$1}#{$2}" : "#{before} #{$1}#{$2} #{$'}"
94
104
  end
95
105
 
@@ -101,16 +111,36 @@ module SuperSlim
101
111
  line.sub(/\A[ \t]*/) { _1.gsub(Parser::TAB, "\\1#{" " * Parser::TAB_SIZE}") }
102
112
  end
103
113
 
104
- # Prism's tree of the compiled Ruby, or the error that stops it.
114
+ # 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.
105
116
  def compiled_ruby(source)
106
- code = SuperSlim.compile(source, tailwind_classes: @tailwind_classes, format: :xml)
107
- # Rails runs a template inside a method, where `yield` is valid.
108
- parsed = Prism.parse("def template\n#{code}\nend")
117
+ nodes = Parser.new(tailwind_classes: @tailwind_classes).call(source)
118
+ code = Compiler.new(format: :xml).call(with_attributes_sorted_by_name(nodes))
119
+ parsed = Prism.parse("#{CodeWrapper::TEMPLATE_METHOD}#{code}\nend")
109
120
  parsed.success? ? parsed : code.gsub(/(?:\s*[;\n]\s*)+/, ";")
110
121
  rescue Error => exception
111
122
  exception.message
112
123
  end
113
124
 
125
+ # A tag renders the same whatever the order of its attributes, and with a class shortcut named twice once: both
126
+ # templates get their attributes sorted by name, class values kept in order, before they are compiled. A
127
+ # splat merges attributes in order, so a tag holding one keeps its own.
128
+ def with_attributes_sorted_by_name(nodes)
129
+ nodes.each do |node|
130
+ next unless node.is_a?(Struct)
131
+
132
+ if node.is_a?(AST::Tag) && node.attributes.none?(AST::Splat)
133
+ attributes = node.attributes.uniq { class_shortcut?(_1) ? _1 : _1.__id__ }
134
+ node.attributes = attributes.sort_by.with_index { |attribute, index| [attribute.name, index] }
135
+ end
136
+ node.each { with_attributes_sorted_by_name(_1) if _1.is_a?(Array) }
137
+ end
138
+ end
139
+
140
+ def class_shortcut?(attribute)
141
+ attribute.is_a?(AST::StaticAttribute) && attribute.name == "class"
142
+ end
143
+
114
144
  # Positions aside: line breaks, spaces, a trailing comma and the parentheses of a call change nothing, a
115
145
  # different value or operator does.
116
146
  def same_ruby?(ruby, other_ruby)
@@ -119,30 +149,64 @@ module SuperSlim
119
149
  same_node?(ruby.value, other_ruby.value) && comment_texts(ruby) == comment_texts(other_ruby)
120
150
  end
121
151
 
152
+ # Walks both trees with a stack of its own: deep code or a deep template would exhaust Ruby's.
122
153
  def same_node?(node, other_node)
123
- return false unless node.instance_of?(other_node.class)
154
+ pairs = [[node, other_node]]
155
+ until pairs.empty?
156
+ value, other_value = pairs.pop
157
+ case value
158
+ when Prism::Node
159
+ return false unless value.instance_of?(other_value.class)
160
+ return false unless same_node_value?(value, other_value)
161
+ when Array
162
+ return false unless other_value.is_a?(Array) && value.size == other_value.size
163
+ else
164
+ return false unless value == other_value
165
+
166
+ next
167
+ end
168
+ pairs.concat(children_pairs(value, other_value).reverse)
169
+ end
170
+ true
171
+ end
124
172
 
125
- field_names, flags = node_fields(node)
126
- return false if flags && (node.send(:flags) & ~NEWLINE_FLAG) != (other_node.send(:flags) & ~NEWLINE_FLAG)
173
+ def same_node_value?(node, other_node)
174
+ # `__LINE__` holds no value in the tree: removing a blank line above it changes what it renders.
175
+ return node.location.start_line == other_node.location.start_line if node.is_a?(Prism::SourceLineNode)
127
176
 
128
- field_names.all? { |name| same_field?(node.public_send(name), other_node.public_send(name)) }
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)) }
129
183
  end
130
184
 
131
- def same_field?(value, other_value)
132
- case value
133
- when Prism::Node then other_value.is_a?(Prism::Node) && same_node?(value, other_value)
134
- when Array then other_value.is_a?(Array) && value.size == other_value.size && value.each_index.all? { same_field?(value[_1], other_value[_1]) }
135
- else value == other_value
136
- end
185
+ def children_pairs(value, other_value)
186
+ return value.zip(other_value) if value.is_a?(Array)
187
+ return [] if value.is_a?(Prism::SourceLineNode)
188
+
189
+ node_fields(value).first.map { |name| [value.public_send(name), other_value.public_send(name)] }
137
190
  end
138
191
 
139
- # Prism 0.19 (Ruby 3.3) has no reflection API: the field names come from the first node of each class. Prism
140
- # 1.x keeps flags out of deconstruct_keys, and counts in them whether a node starts a line.
192
+ # Beside a location, a field holds either a name or, from Prism 2 on, the source the location covers
193
+ # (`opening` beside `opening_loc`): only the name counts.
194
+ def same_name?(name, other_name)
195
+ return true unless name.is_a?(Symbol) || other_name.is_a?(Symbol)
196
+
197
+ name == other_name
198
+ end
199
+
200
+ # 2026-11: Prism 0.19 (Ruby 3.3) has no reflection API: the field names come from the first node of each
201
+ # class. Prism 1.x keeps flags out of deconstruct_keys.
141
202
  def node_fields(node)
142
- FIELDS_BY_NODE_CLASS[node.class] ||= [
143
- node.deconstruct_keys(nil).keys.reject { |key| key == :node_id || key == :flags || key == :location || key.end_with?("_loc") },
144
- node.respond_to?(:flags, true)
145
- ]
203
+ FIELDS_BY_NODE_CLASS[node.class] ||= begin
204
+ keys = node.deconstruct_keys(nil).keys
205
+ located_names, field_names = (keys - %i[node_id flags location])
206
+ .reject { _1.end_with?("_loc") }
207
+ .partition { keys.include?(:"#{_1}_loc") }
208
+ [field_names, located_names, node.respond_to?(:flags, true)]
209
+ end
146
210
  end
147
211
 
148
212
  def comment_texts(ruby)
@@ -15,7 +15,7 @@ module SuperSlim
15
15
  DEFAULTS = {enabled: true}.freeze
16
16
 
17
17
  def self.rule_name
18
- name.split("::").last
18
+ @rule_name ||= name.split("::").last
19
19
  end
20
20
 
21
21
  GLOB_FLAGS = File::FNM_PATHNAME | File::FNM_EXTGLOB | File::FNM_DOTMATCH
@@ -49,11 +49,7 @@ module SuperSlim
49
49
 
50
50
  # Text nodes carry no line of their own: they take the line of the closest node that does.
51
51
  def line_near(document, node, ancestors)
52
- [node, *ancestors.reverse].each do |candidate|
53
- lineno = document.line_of(candidate)
54
- return lineno if lineno
55
- end
56
- nil
52
+ document.line_of(node) || document.line_of(ancestors.located)
57
53
  end
58
54
 
59
55
  def each_line(document)
@@ -90,7 +86,9 @@ module SuperSlim
90
86
  document.outline.each_with_index.filter_map do |info, lineno|
91
87
  next unless info&.kind == :structure
92
88
 
93
- indent = document.lines[lineno - 1][/\A */].size
89
+ line = document.lines[lineno - 1]
90
+ indent = 0
91
+ indent += 1 while line.getbyte(indent) == Parser::SPACE_BYTE
94
92
  expected = info.depth * Formatter::INDENT_WIDTH
95
93
  offense(document, lineno, "Indent with #{expected} spaces, not #{indent}") if indent != expected
96
94
  end
@@ -106,11 +104,11 @@ module SuperSlim
106
104
  end
107
105
 
108
106
  class TrailingWhitespace < Rule
109
- # Matches wherever a line may end in whitespace, and a little more (a \r before \n): it only skips files.
110
- ANY_TRAILING_WHITESPACE = /[ \t\r\f\v](?=\r?\n|\z)/
111
-
112
107
  def offenses(document, source)
113
- return [] unless source.match?(ANY_TRAILING_WHITESPACE)
108
+ # Whitespace ending a line is in one of these, as are a few more files (a \r anywhere): they only skip files.
109
+ # A string search is faster than any regexp here.
110
+ return [] unless source.include?(" \n") || source.include?("\t\n") || source.include?("\r") || source.include?("\f") ||
111
+ source.include?("\v") || source.end_with?(" ", "\t")
114
112
 
115
113
  each_line(document).filter_map do |line, lineno|
116
114
  next unless line.match?(/\s\z/)
@@ -146,6 +144,9 @@ module SuperSlim
146
144
 
147
145
  class ControlStatementSpacing < Rule
148
146
  TAG_OUTPUT = /\A(\s*)(==?)(['<>]*)(\s*)(?=\S)/
147
+ # [\s\0]* is what String#lstrip strips.
148
+ UNSPACED_CONTROL = /\A[\s\0]*-(?=\S)/
149
+ UNSPACED_OUTPUT = /\A[\s\0]*((?>==?[<>]*))(?=\S)/
149
150
 
150
151
  def offenses(document, _source)
151
152
  document.outline.each_with_index.filter_map do |info, lineno|
@@ -153,12 +154,13 @@ module SuperSlim
153
154
 
154
155
  line = document.lines[lineno - 1]
155
156
  if info.output_column
156
- line[info.output_column..] =~ TAG_OUTPUT
157
+ next unless line[info.output_column..] =~ TAG_OUTPUT
158
+
157
159
  offense(document, lineno, "Put a space before and after `#{$2}`") if $1.empty? || $4.empty?
158
160
  elsif info.kind == :structure
159
- case line.lstrip
160
- when /\A-(?=\S)/ then offense(document, lineno, "Put a space after `-`")
161
- when /\A((?>==?[<>]*))(?=\S)/ then offense(document, lineno, "Put a space after `#{$1}`")
161
+ case line
162
+ when UNSPACED_CONTROL then offense(document, lineno, "Put a space after `-`")
163
+ when UNSPACED_OUTPUT then offense(document, lineno, "Put a space after `#{$1}`")
162
164
  end
163
165
  end
164
166
  end
@@ -166,9 +168,12 @@ module SuperSlim
166
168
  end
167
169
 
168
170
  class RedundantDiv < Rule
171
+ # [\s\0]* is what String#lstrip strips.
172
+ REDUNDANT_DIV = /\A[\s\0]*div(?=[.#][\p{Word}-])/
173
+
169
174
  def offenses(document, _source)
170
175
  document.outline.each_with_index.filter_map do |info, lineno|
171
- next unless info&.kind == :structure && document.lines[lineno - 1].lstrip.match?(Formatter::REDUNDANT_DIV)
176
+ next unless info&.kind == :structure && document.lines[lineno - 1].match?(REDUNDANT_DIV)
172
177
 
173
178
  offense(document, lineno, "`div` is implied by the `.class` or `#id` shortcut")
174
179
  end
@@ -235,7 +240,7 @@ module SuperSlim
235
240
 
236
241
  document.enum_for(:each_node).filter_map do |node, ancestors|
237
242
  next unless node.is_a?(AST::Tag) && node.name.match?(/[A-Z]/)
238
- next if ancestors.any? { _1.is_a?(AST::Tag) && _1.name == "svg" }
243
+ next if ancestors.inside_svg
239
244
 
240
245
  offense(document, document.line_of(node), "Write `#{node.name.downcase}` in lowercase")
241
246
  end
@@ -276,7 +281,7 @@ module SuperSlim
276
281
  def offenses(document, _source)
277
282
  branch_by_id = {}
278
283
  enum_for(:each_tag, document).filter_map do |tag, ancestors|
279
- branch = ancestors.reverse.find { _1.is_a?(AST::Control) }
284
+ branch = ancestors.control
280
285
  literal_attributes(tag, "id").filter_map do |attribute|
281
286
  id = literal_value(attribute)
282
287
  if branch_by_id.key?(id) && branch_by_id[id].equal?(branch)
@@ -319,7 +324,7 @@ module SuperSlim
319
324
  class NestedLinks < Rule
320
325
  def offenses(document, _source)
321
326
  enum_for(:each_tag, document, "a").filter_map do |tag, ancestors|
322
- next unless ancestors.any? { _1.is_a?(AST::Tag) && _1.name == "a" }
327
+ next unless ancestors.inside_link
323
328
 
324
329
  offense(document, document.line_of(tag), "Links cannot contain links")
325
330
  end
@@ -521,7 +526,7 @@ module SuperSlim
521
526
 
522
527
  def offenses(document, _source)
523
528
  document.enum_for(:each_node).filter_map do |node, ancestors|
524
- next unless node.is_a?(AST::TextBlock) && ancestors.none?(AST::Comment)
529
+ next unless node.is_a?(AST::TextBlock) && !ancestors.inside_comment
525
530
 
526
531
  text = node.children.grep(AST::Text).map(&:text).join(" ").gsub(/\s+/, " ").strip
527
532
  next unless text.gsub(NOT_WORDS, "").match?(/\p{L}/)
@@ -561,7 +566,7 @@ module SuperSlim
561
566
 
562
567
  text = $2
563
568
  lineno = document.line_of(node)
564
- message = if text.match?(READ_AS_SYNTAX_AFTER_TAG) && ancestors.any? && document.line_of(ancestors.last) == lineno
569
+ message = if text.match?(READ_AS_SYNTAX_AFTER_TAG) && ancestors.last && document.line_of(ancestors.last) == lineno
565
570
  "Write the text `| #{text}` on its own line, under the tag: inline, it would read as attributes"
566
571
  else
567
572
  "Write the text `| #{text}` instead of outputting a string"
@@ -577,7 +582,7 @@ module SuperSlim
577
582
  EMOJI_JOINER = /(?<=\p{Extended_Pictographic}|[\u{1F3FB}-\u{1F3FF}]|\uFE0F)\u200D(?=\p{Extended_Pictographic})/
578
583
 
579
584
  def offenses(document, source)
580
- return [] unless source.match?(INVISIBLE)
585
+ return [] if source.ascii_only? || !source.match?(INVISIBLE)
581
586
 
582
587
  each_line(document).filter_map do |line, lineno|
583
588
  line = line.delete_prefix("\uFEFF") if lineno == 1
@@ -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
- def self.visits_of(nodes, ancestors = [], visits = [])
12
- nodes&.each do |node|
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
- visits_of(children, [*ancestors, node].freeze, visits) if children
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,14 @@ 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)
70
- document = Document.new(path:, lines: source.split(/\r?\n/), nodes:, outline: parser.outline, line_by_node: parser.line_by_node,
116
+ visits = Document.visits_of(nodes, parser.line_by_node)
117
+ lines = source.include?("\r") ? source.split(/\r?\n/) : source.split("\n")
118
+ document = Document.new(path:, lines:, nodes:, outline: parser.outline, line_by_node: parser.line_by_node,
71
119
  visits:, tag_visits: visits.select { |node,| node.is_a?(AST::Tag) })
72
120
  relative_path = File.expand_path(path).delete_prefix(@root)
73
121
  offenses = @rules.select { _1.applies_to?(relative_path) }.flat_map { _1.offenses(document, source) }
74
122
  # 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)
123
+ offenses.each_with_index.sort_by { |offense, index| [offense.lineno.to_i, index] }.map(&:first)
76
124
  rescue SyntaxError => exception
77
125
  [Offense.new(path, exception.lineno, "Syntax", exception.error)]
78
126
  end
@@ -12,25 +12,50 @@ 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
- readers = items.each_slice((items.size.to_f / process_count).ceil).map do |slice|
15
+ # Dealt like cards: neighbouring templates, as heavy as each other, would load one process with all of them.
16
+ slices = Array.new(process_count) { |process_index| items.values_at(*process_index.step(items.size - 1, process_count)) }
17
+ workers = slices.map do |slice|
16
18
  reader, writer = IO.pipe
17
- fork do
19
+ pid = fork do
18
20
  reader.close
19
- results = begin
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))
21
+ writer.binmode.write(dump { slice.map(&block) })
25
22
  exit!(0)
26
23
  end
27
24
  writer.close
28
- reader
25
+ [pid, reader]
29
26
  end
30
- results_by_process = readers.map { |reader| Marshal.load(reader.binmode.read) }
31
- Process.waitall
32
- results_by_process.each { |results| raise results if results.is_a?(Exception) }
33
- results_by_process.flatten(1)
27
+ results_per_process = workers.map { |pid, reader| receive(pid, reader) }
28
+ results_per_process.each { |results| raise results if results.is_a?(Exception) }
29
+ # The first slice is the longest: zip pads the others with nils past the last item.
30
+ results_in_item_order = results_per_process.first.zip(*results_per_process.drop(1))
31
+ results_in_item_order.flatten!(1)
32
+ results_in_item_order.first(items.size)
33
+ ensure
34
+ workers&.each do |pid, reader|
35
+ reader.close unless reader.closed?
36
+ Process.wait(pid)
37
+ rescue Errno::ECHILD # already reaped by receive
38
+ end
39
+ end
40
+
41
+ # A result or an exception Marshal cannot dump (a Proc, an IO) is sent as a RuntimeError naming it.
42
+ def dump
43
+ Marshal.dump(yield)
44
+ rescue Exception => exception # rubocop:disable Lint/RescueException -- re-raised by the parent
45
+ begin
46
+ Marshal.dump(exception)
47
+ rescue TypeError
48
+ Marshal.dump(RuntimeError.new("#{exception.class}: #{exception.message}"))
49
+ end
50
+ end
51
+
52
+ def receive(pid, reader)
53
+ payload = reader.binmode.read
54
+ reader.close
55
+ Process.wait(pid)
56
+ raise Error, "Worker #{pid} died: #{$?}" unless $?.success? && !payload.empty?
57
+
58
+ Marshal.load(payload) # rubocop:disable Security/MarshalLoad -- written by our own child
34
59
  end
35
60
  end
36
61
  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