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,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
- configuration = Linter.configuration
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)) { |path| linter.call(path, File.read(path)) }.flatten
45
- offenses.each { |offense| puts "#{offense.path}:#{offense.lineno}: [#{offense.rule}] #{offense.message}" }
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,51 @@ module SuperSlim
54
66
  formatted = formatter.call(source)
55
67
  next if formatted == source
56
68
 
57
- File.write(path, formatted) unless check
69
+ replace(path, formatted) unless check
58
70
  [:reformatted, path]
59
- rescue Error => exception
60
- [:refused, "#{path}: #{exception.message.lines.first.strip}"]
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 { |template| File.join(path, template) unless template.match?(SKIPPED_DIRECTORIES) }
86
+ templates_in(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
+ # A glob of the whole directory would walk the skipped directories too, node_modules first of all.
94
+ def templates_in(directory)
95
+ subdirectories = Dir.children(directory).select do |name|
96
+ !name.start_with?(".") && !"#{name}/".match?(SKIPPED_DIRECTORIES) && File.lstat(File.join(directory, name)).directory?
97
+ end
98
+ Dir.glob("*.slim", base: directory) +
99
+ subdirectories.flat_map { |name| Dir.glob("**/*.slim", base: File.join(directory, name)).map { |template| File.join(name, template) } }
100
+ end
101
+
102
+ # Written beside the template then renamed over it, so that a full disk or a kill cannot leave it cut short.
103
+ def replace(path, content)
104
+ Tempfile.create([".super-slim-", ".tmp"], File.dirname(path)) do |file|
105
+ file.write(content)
106
+ file.close
107
+ File.chmod(File.stat(path).mode & 0o7777, file.path)
108
+ File.rename(file.path, path)
109
+ end
110
+ end
111
+
112
+ def printable(text)
113
+ text.gsub(CONTROL_CHARACTER) { |character| character.inspect[1...-1] }
114
+ end
74
115
  end
75
116
  end
@@ -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
- INTERPOLATION = /\A#\{((?>[^{}]|(\{(?>[^{}]|\g<1>)*\}))*)\}/
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
- loop do
333
- case text
334
- when ESCAPED_INTERPOLATION
353
+ until scanner.eos?
354
+ if scanner.skip(ESCAPED_INTERPOLATION)
335
355
  parts << [:static, '#{']
336
- when INTERPOLATION
337
- code = $1
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
- when INTERPOLATION_FREE_TEXT
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
@@ -0,0 +1,130 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SuperSlim
4
+ class Formatter
5
+ # Rewrites the attributes of a tag written on one line: a literal id or class becomes a shortcut, a class named
6
+ # twice goes, and the others follow one order: what the element is, then what it does, then how it reads aloud.
7
+ class AttributeArranger
8
+ # Only plain names: a dot between digits (`py-1.5`), `:` or `/` would read as another class under Tailwind.
9
+ SHORTCUT = /[.#][A-Za-z_-][\w-]*/
10
+ WHOLE_SHORTCUT = /\A#{SHORTCUT}\z/
11
+ LITERAL_ID = /\Aid=(["'])([A-Za-z_][\w-]*)\1\z/
12
+ LITERAL_CLASS = /\Aclass=(["']) *([\w-][\w\- ]*)\1\z/
13
+ TAG_HEAD = /\A([\w:-]*)((?:#{SHORTCUT})*)([<>']*)\z/
14
+ LEADING_SHORTCUTS = /\A( *[\w:-]*)((?:#{SHORTCUT})+)(?=[ =<>'\/]|: |\z)/
15
+ ATTRIBUTE_AT_START = /\A#{Parser::CODE_ATTRIBUTE}/
16
+ RANK_BY_NAME = {
17
+ "id" => 0, "class" => 1, **%w[type name href src value for action method].to_h { [_1, 2] },
18
+ "data-controller" => 4, "data-action" => 5, "role" => 7
19
+ }.freeze
20
+
21
+ def initialize(tailwind_classes:)
22
+ @tailwind_classes = tailwind_classes
23
+ end
24
+
25
+ # Returns the line rearranged and its outline, or the line and its outline as they were when its tag has
26
+ # nothing to rearrange. Without an outline, the line is read alone.
27
+ def call(line, info = nil)
28
+ info ||= line_info(line)
29
+ return [line, info] unless info
30
+
31
+ lists = info.attribute_lists
32
+ return without_duplicate_shortcuts(line, info) if lists.nil?
33
+ return [line, info] unless lists.size == 1
34
+
35
+ indent = line[/\A */]
36
+ first, last, spans = lists.first
37
+ head = line[indent.size...first].rstrip
38
+ # A dynamic tag, `*{tag: name}`, has no head to put shortcuts on.
39
+ return [line, info] if head.empty? || !(head_parts = TAG_HEAD.match(head)) || head_parts[1].end_with?(":")
40
+
41
+ attributes = spans.map { |span_first, span_last| line[span_first...span_last] }
42
+ rest = line[last..]
43
+ # Without delimiters, text that reads as an attribute would become one.
44
+ if Parser::DELIMITERS.key?(line[first])
45
+ return [line, info] if attributes.any? { !_1.include?("=") } || rest.match?(ATTRIBUTE_AT_START)
46
+ end
47
+
48
+ name, shortcuts, markers = head_parts.captures
49
+ shortcuts = shortcuts.scan(SHORTCUT)
50
+ # A splat merges attributes in the order they come.
51
+ unless attributes.any? { _1.start_with?("*") }
52
+ attributes = moved_to_shortcuts(attributes, shortcuts)
53
+ attributes = attributes.sort_by.with_index { |attribute, index| [rank(attribute[/\A"?[^=\s"]+/].delete('"')), index] }
54
+ end
55
+ shortcuts.uniq!
56
+
57
+ name = "" if name == "div" && !shortcuts.empty?
58
+ rest = " #{rest.lstrip}" unless rest.empty? || rest.start_with?(" ")
59
+ arranged = "#{indent}#{name}#{shortcuts.join}#{markers}#{" " unless attributes.empty?}#{attributes.join(" ")}#{rest}"
60
+ outlined(arranged, line, info)
61
+ end
62
+
63
+ private
64
+
65
+ # Appends a literal id or class to the shortcuts and returns the attributes left.
66
+ def moved_to_shortcuts(attributes, shortcuts)
67
+ class_kept = false
68
+ attributes.reject do |attribute|
69
+ if (id = LITERAL_ID.match(attribute)) && shortcuts.none? { _1.start_with?("#") }
70
+ shortcuts << "##{id[2]}"
71
+ elsif !class_kept && (class_shortcuts = literal_class_shortcuts(attribute, shortcuts))
72
+ shortcuts.concat(class_shortcuts)
73
+ else
74
+ # Shortcuts come first among class values: a literal class after this one would move ahead of it.
75
+ class_kept ||= attribute.start_with?("class=")
76
+ false
77
+ end
78
+ end
79
+ end
80
+
81
+ # Nil when a class would be named twice: the check reads a shortcut and a class attribute as two values.
82
+ def literal_class_shortcuts(attribute, shortcuts)
83
+ return unless (classes = LITERAL_CLASS.match(attribute))
84
+
85
+ class_shortcuts = classes[2].split.map { ".#{_1}" }
86
+ class_shortcuts if class_shortcuts.all?(WHOLE_SHORTCUT) && class_shortcuts.uniq == class_shortcuts && !shortcuts.intersect?(class_shortcuts)
87
+ end
88
+
89
+ def without_duplicate_shortcuts(line, info)
90
+ shortcuts = line[LEADING_SHORTCUTS, 2]&.scan(SHORTCUT)
91
+ return [line, info] unless shortcuts && shortcuts.uniq.size < shortcuts.size
92
+
93
+ outlined(line.sub(LEADING_SHORTCUTS) { "#{$1}#{shortcuts.uniq.join}" }, line, info)
94
+ end
95
+
96
+ # The outline of a line read alone, in columns of the indented line; nil when it doesn't parse alone.
97
+ def line_info(line)
98
+ indent = line[/\A */].size
99
+ parser = Parser.new(outline: true, tailwind_classes: @tailwind_classes)
100
+ parser.call(line.lstrip)
101
+ info = parser.outline[1].dup
102
+ info.output_column += indent if info.output_column
103
+ info.attribute_lists = info.attribute_lists&.map do |first, last, spans|
104
+ [first + indent, last + indent, spans.map { |span_first, span_last| [span_first + indent, span_last + indent] }]
105
+ end
106
+ info
107
+ rescue Error
108
+ nil
109
+ end
110
+
111
+ def outlined(arranged, line, info)
112
+ return [line, info] if arranged == line
113
+
114
+ arranged_info = line_info(arranged)
115
+ arranged_info ? [arranged, arranged_info] : [line, info]
116
+ end
117
+
118
+ def rank(name)
119
+ RANK_BY_NAME.fetch(name) do
120
+ case name
121
+ when /\Adata-.+-target\z/ then 5
122
+ when /\Adata-/ then 6
123
+ when /\Aaria-/ then 7
124
+ else 3
125
+ end
126
+ end
127
+ end
128
+ end
129
+ end
130
+ end
@@ -0,0 +1,129 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SuperSlim
4
+ class Formatter
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 followed by a comma, between brackets that close on a line of their own. A call whose only
7
+ # argument is itself a call, an array or a hash spreads that argument instead: `render Card.new(…)`.
8
+ class CodeWrapper
9
+ METHOD_NAME = /\A[a-z_][a-zA-Z0-9_]*[?!]?\z/
10
+ # Rails runs a template inside a method, where `yield` is valid.
11
+ TEMPLATE_METHOD = "def template\n"
12
+ CODE_OFFSET = TEMPLATE_METHOD.bytesize
13
+
14
+ # Returns the lines after the first one's indentation, or nil when the code has nothing to spread.
15
+ def self.call(code, indent, opens_block:)
16
+ new(code, indent, opens_block:).call
17
+ end
18
+
19
+ # `render Card.new title:` reads as if title went to render: arguments to `new` go in parentheses.
20
+ def self.parenthesize_new(code)
21
+ loop do
22
+ statements, _opens_block = parse(code)
23
+ call = statements && new_without_parentheses(statements)
24
+ return code unless call
25
+
26
+ arguments = arguments_of(call)
27
+ name_end = call.message_loc.end_offset - CODE_OFFSET
28
+ arguments_start = arguments.first.location.start_offset - CODE_OFFSET
29
+ arguments_end = end_offset(arguments.last) - CODE_OFFSET
30
+ return code if arguments_end > code.bytesize
31
+
32
+ code = "#{code.byteslice(0, name_end)}(#{code.byteslice(arguments_start...arguments_end)})#{code.byteslice(arguments_end..)}"
33
+ end
34
+ end
35
+
36
+ def self.new_without_parentheses(statements)
37
+ nodes = statements.dup
38
+ while (node = nodes.pop)
39
+ return node if node.is_a?(Prism::CallNode) && node.name == :new && node.opening_loc.nil? && arguments_of(node)
40
+
41
+ nodes.concat(node.child_nodes.compact)
42
+ end
43
+ end
44
+ private_class_method :new_without_parentheses
45
+
46
+ # Returns the statements of the line and whether it opens a block: it then holds its `do` but not its `end`.
47
+ # Their offsets count from CODE_OFFSET.
48
+ def self.parse(code)
49
+ parsed = Prism.parse("#{TEMPLATE_METHOD}#{code}\nend")
50
+ opens_block = !parsed.success?
51
+ parsed = Prism.parse("#{TEMPLATE_METHOD}#{code}\nend\nend") if opens_block
52
+ [parsed.value.statements.body.first.body&.body || [], opens_block] if parsed.success? && parsed.comments.empty?
53
+ end
54
+
55
+ # Positional and keyword arguments, then the block argument; nil when the call takes none.
56
+ def self.arguments_of(call)
57
+ arguments = (call.arguments&.arguments || []).flat_map { |argument| argument.is_a?(Prism::KeywordHashNode) ? argument.elements : [argument] }
58
+ arguments += [call.block] if call.block.is_a?(Prism::BlockArgumentNode)
59
+ arguments unless call.message_loc.nil? || arguments.empty?
60
+ end
61
+
62
+ # 2026-11: Prism 0.19 (Ruby 3.3) ends a call that takes a block argument, and any node around it, before the
63
+ # call's closing parenthesis: `f(&x`.
64
+ def self.end_offset(node)
65
+ closing = node.closing_loc if node.respond_to?(:closing_loc)
66
+ child_ends = node.child_nodes.filter_map { |child| end_offset(child) if child }
67
+ [node.location.end_offset, closing&.end_offset || 0, *child_ends].max
68
+ end
69
+
70
+ # opens_block: whether the line has children, which Slim passes to its call as a block even without `do`.
71
+ def initialize(code, indent, opens_block:)
72
+ @code = code
73
+ @indent = indent
74
+ @opens_block = opens_block
75
+ end
76
+
77
+ def call
78
+ statements, opens_block = self.class.parse(@code)
79
+ return unless statements&.size == 1 && (node = spreadable(statements.first))
80
+
81
+ spread(node, @opens_block || opens_block)
82
+ end
83
+
84
+ private
85
+
86
+ def spreadable(node)
87
+ node = node.value if node.type.end_with?("_write_node") && node.respond_to?(:value)
88
+ case node
89
+ when Prism::CallNode
90
+ items = self.class.arguments_of(node)
91
+ # An operator such as `+` has no parentheses to add, and `list[index] = value` holds value in its arguments.
92
+ return if items.nil? || node.name.end_with?("=") || (node.opening_loc.nil? && !METHOD_NAME.match?(node.name.to_s))
93
+ return spreadable(items.first) if items.size == 1
94
+
95
+ node
96
+ when Prism::ArrayNode, Prism::HashNode
97
+ # `%w[a b]` takes no commas.
98
+ node if ["[", "{"].include?(node.opening) && node.elements.size > 1
99
+ end
100
+ end
101
+
102
+ def spread(node, opens_block)
103
+ items = node.is_a?(Prism::CallNode) ? self.class.arguments_of(node) : node.elements
104
+ # `hint: -> do` ends past the line, with the children of the line.
105
+ return if self.class.end_offset(items.last) > CODE_OFFSET + @code.bytesize
106
+
107
+ closing_indent = @indent + (" " * (opens_block ? 2 * INDENT_WIDTH : INDENT_WIDTH))
108
+ item_indent = closing_indent + (" " * INDENT_WIDTH)
109
+ head, tail =
110
+ if node.opening_loc
111
+ [slice(CODE_OFFSET, node.opening_loc.end_offset), slice(node.closing_loc.start_offset)]
112
+ else
113
+ ["#{slice(CODE_OFFSET, node.message_loc.end_offset)}(", ")#{slice(self.class.end_offset(items.last))}"]
114
+ end
115
+ item_lines = items.map do |item|
116
+ # A comma after `&block` is a syntax error.
117
+ comma = "," unless item.is_a?(Prism::BlockArgumentNode)
118
+ "#{item_indent}#{slice(item.location.start_offset, self.class.end_offset(item))}#{comma}"
119
+ end
120
+ [head, *item_lines, closing_indent + tail]
121
+ end
122
+
123
+ # From offsets in the parsed source, up to the end of the line by default.
124
+ def slice(first, last = CODE_OFFSET + @code.bytesize)
125
+ @code.byteslice((first - CODE_OFFSET)...(last - CODE_OFFSET))
126
+ end
127
+ end
128
+ end
129
+ end
@@ -2,15 +2,15 @@
2
2
 
3
3
  module SuperSlim
4
4
  class Formatter
5
- # Breaks the lines of a formatted template longer than max_line_length: a tag's attributes one per line
6
- # inside attribute_delimiters, then the arguments of its Ruby code after each comma, as Slim reads a line ending
7
- # with a comma as continued on the next one. Lines already spread over several lines are left as they are.
5
+ # Gives each line one layout, whatever its author chose: Ruby code spread over several lines is joined back
6
+ # when it fits in max_line_length, and a longer line is broken: a tag's attributes one per line inside
7
+ # attribute_delimiters, then its Ruby code by CodeWrapper.
8
8
  class LineWrapper
9
9
  CODE_LINE = /\A *(?:-|==?[<>]*) /
10
10
  TAG_OUTPUT = /\G\s*==?['<>]*\s*/
11
11
  CONTINUATION_KINDS = %i[continuation text text_blank].freeze
12
- BLOCK_OPENINGS = %i[KEYWORD_DO KEYWORD_DO_LOOP].freeze
13
- MODIFIERS = %i[KEYWORD_IF_MODIFIER KEYWORD_UNLESS_MODIFIER KEYWORD_WHILE_MODIFIER KEYWORD_UNTIL_MODIFIER KEYWORD_RESCUE_MODIFIER].freeze
12
+ CLOSING_BRACKET_AT_START = /\A[)\]}]/
13
+ NEW_WITHOUT_PARENTHESES = /\.new [^\s=]/
14
14
 
15
15
  # Templates attach ( and [ to their tag but set { apart, as a Ruby block: 6,097 public templates agree.
16
16
  OPENING_BY_ATTRIBUTE_DELIMITERS = {"()" => "(", "[]" => "[", "{}" => " {"}.freeze
@@ -23,27 +23,83 @@ module SuperSlim
23
23
  @max_line_length = max_line_length
24
24
  @tailwind_classes = tailwind_classes
25
25
  @closing = attribute_delimiters[1]
26
+ @attribute_arranger = AttributeArranger.new(tailwind_classes:)
26
27
  end
27
28
 
28
29
  def call(source)
29
30
  lines = source.split("\n")
30
- return source if lines.none? { _1.size > @max_line_length }
31
-
32
31
  parser = Parser.new(outline: true, tailwind_classes: @tailwind_classes)
33
32
  parser.call(source)
34
- wrapped = lines.each.with_index(1).flat_map do |line, lineno|
35
- info = parser.outline[lineno]
36
- next [line] unless line.size > @max_line_length && info.kind == :structure && one_line?(parser.outline[lineno + 1], lineno)
37
-
38
- wrap(line, info, children?(parser.outline, lineno))
33
+ outline = parser.outline
34
+ wrapped = []
35
+ lineno = 1
36
+ while lineno <= lines.size
37
+ info = outline[lineno]
38
+ last_lineno = lineno
39
+ last_lineno += 1 while outline[last_lineno + 1]&.owner == lineno && CONTINUATION_KINDS.include?(outline[last_lineno + 1].kind)
40
+ wrapped.concat(layout(lines[(lineno - 1)...last_lineno], info, outline, lineno))
41
+ lineno = last_lineno + 1
39
42
  end
40
43
  "#{wrapped.join("\n")}\n"
41
44
  end
42
45
 
43
46
  private
44
47
 
45
- def one_line?(next_info, lineno)
46
- next_info.nil? || next_info.owner != lineno || !CONTINUATION_KINDS.include?(next_info.kind)
48
+ def layout(lines, info, outline, lineno)
49
+ return lines unless info.kind == :structure
50
+
51
+ line = (lines.size > 1) ? joined_code(lines, info) || joined_attributes(lines, info) : lines.first
52
+ return lines unless line
53
+
54
+ line, arranged_info = @attribute_arranger.call(line, (info if line == lines.first))
55
+ info = arranged_info || info
56
+ line = with_new_parenthesized(line, info)
57
+ return [line] if line.size <= @max_line_length
58
+
59
+ broken = wrap(line, info, children?(outline, lineno))
60
+ return ((lines.size > 1) ? lines : broken) if broken == [line]
61
+
62
+ # Joined back, brackets lose the spaces inside them (`{ a: 1 }` becomes `{a: 1}`), which may now fit.
63
+ rejoined = joined_code(broken, info)
64
+ return [rejoined] if rejoined && rejoined.size <= @max_line_length
65
+
66
+ # Only the outer call is spread: a hash spread inside it by hand would come back longer than the limit.
67
+ return lines if lines.size > 1 && lines.none? { _1.size > @max_line_length } && broken.any? { _1.size > @max_line_length }
68
+
69
+ broken
70
+ end
71
+
72
+ def with_new_parenthesized(line, info)
73
+ return line unless line.match?(NEW_WITHOUT_PARENTHESES) && (start = code_start(line, info.output_column))
74
+
75
+ line[0...start] + CodeWrapper.parenthesize_new(line[start..])
76
+ end
77
+
78
+ # The code of a line continued after a comma, a backslash or an opening bracket, on one line; nil when the
79
+ # continuation lines hold anything else, such as attributes or text.
80
+ def joined_code(lines, info)
81
+ return unless info.text.nil? && code_start(lines.first, info.output_column) && lines.drop(1).none? { _1.strip.empty? }
82
+
83
+ lines.drop(1).reduce(lines.first.rstrip) do |joined, line|
84
+ piece = line.strip
85
+ joined = joined.delete_suffix("\\").rstrip
86
+ if piece.match?(CLOSING_BRACKET_AT_START)
87
+ joined.delete_suffix(",") + piece
88
+ elsif joined.match?(Parser::OPENING_BRACKET_AT_LINE_END)
89
+ joined + piece
90
+ else
91
+ "#{joined} #{piece}"
92
+ end
93
+ end
94
+ end
95
+
96
+ # A tag whose attributes stand one per line inside delimiters, on one line: `p {` `title="A"` `} = text`.
97
+ def joined_attributes(lines, info)
98
+ return unless info.text.nil? && lines.first.lstrip.match?(Shortcuts::TAG_PATTERN) && !code_start(lines.first, info.output_column)
99
+ return unless lines.first.rstrip.match?(Parser::OPENING_BRACKET_AT_LINE_END)
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
47
103
  end
48
104
 
49
105
  def children?(outline, lineno)
@@ -51,20 +107,24 @@ module SuperSlim
51
107
  next_structure && next_structure.depth > outline[lineno].depth
52
108
  end
53
109
 
54
- def wrap(line, info, children)
110
+ def wrap(line, info, opens_block)
55
111
  indent = line[/\A */]
56
112
  lists = info.attribute_lists
113
+ head = line[0...lists.first.first].rstrip if lists&.size == 1
57
114
  lines, code_start =
58
- if lists&.size == 1 && named_tag?(line[0...lists.first.first].strip)
115
+ # Attributes spread over lines would not bring back under the limit a tag whose shortcuts alone pass it.
116
+ if head && named_tag?(head.strip) && head.size + @opening.size <= @max_line_length
59
117
  wrap_attributes(line, lists.first, indent, info.output_column)
60
118
  else
61
119
  [[line], code_start(line, info.output_column)]
62
120
  end
63
121
  return lines unless code_start && lines.last.size > @max_line_length
64
122
 
65
- # Arguments go two levels deeper than the line when it opens a block, so they stand apart from its children.
66
- argument_indent = indent + (" " * (children ? 2 * INDENT_WIDTH : INDENT_WIDTH))
67
- lines[0...-1] + wrap_arguments(lines.last, code_start, argument_indent)
123
+ last_indent = lines.last[/\A */]
124
+ code_lines = CodeWrapper.call(lines.last[code_start..], last_indent, opens_block:)
125
+ return lines unless code_lines
126
+
127
+ lines[0...-1] + [lines.last[0...code_start] + code_lines.first, *code_lines.drop(1)]
68
128
  end
69
129
 
70
130
  # A dynamic tag, `*{tag: name}` or `li: *{tag: name}`, has no name for its attribute list to follow.
@@ -87,40 +147,6 @@ module SuperSlim
87
147
  match.end(0)
88
148
  end
89
149
  end
90
-
91
- def wrap_arguments(line, code_start, argument_indent)
92
- code = line[code_start..]
93
- offsets = argument_breaks(code)
94
- return [line] if offsets.empty?
95
-
96
- first = 0
97
- first_piece, *pieces = [*offsets, code.bytesize].map do |last|
98
- piece = code.byteslice(first...last).strip
99
- first = last
100
- piece
101
- end
102
- [line[0...code_start] + first_piece, *pieces.map { argument_indent + _1 }]
103
- end
104
-
105
- # Byte offsets right after each comma that separates the arguments of the outermost call, up to its block.
106
- def argument_breaks(code)
107
- depth = 0
108
- offsets = []
109
- Prism.lex(code).value.each do |(token, _state)|
110
- case token.type
111
- when :COMMA then offsets << token.location.end_offset if depth.zero?
112
- when :HEREDOC_START then return []
113
- # `a, b = …` assigns several variables: its commas separate no arguments.
114
- when :EQUAL then return [] if depth.zero? && !offsets.empty?
115
- when *BLOCK_OPENINGS then break
116
- # RuboCop refuses a modifier that ends a statement spread over several lines (Style/MultilineIfModifier).
117
- when *MODIFIERS then return [] if depth.zero?
118
- when *Parser::OPENING_BRACKETS then depth += 1
119
- when *Parser::CLOSING_BRACKETS then depth -= 1
120
- end
121
- end
122
- offsets
123
- end
124
150
  end
125
151
  end
126
152
  end