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.
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "prism"
4
3
  require "strscan"
4
+ require_relative "parser/ruby_brackets"
5
5
 
6
6
  module SuperSlim
7
7
  # Reads each line with one StringScanner that moves forward: no MatchData, and no copy of the rest of the
@@ -31,11 +31,8 @@ module SuperSlim
31
31
  # At the scanner, the rest of the line is only this character; on a whole line, the line ends with it.
32
32
  LINE_CONTINUATION = /[,\\]\z/
33
33
  BACKSLASH_AT_END = /\\\z/
34
- OPENING_BRACKET_AT_LINE_END = /[(\[{]$/
35
- OPENING_BRACKETS = %i[PARENTHESIS_LEFT PARENTHESIS_LEFT_PARENTHESES BRACKET_LEFT BRACKET_LEFT_ARRAY BRACE_LEFT LAMBDA_BEGIN EMBEXPR_BEGIN].freeze
36
- CLOSING_BRACKETS = %i[PARENTHESIS_RIGHT BRACKET_RIGHT BRACE_RIGHT EMBEXPR_END].freeze
37
- PERCENT_LISTS = %i[PERCENT_LOWER_W PERCENT_UPPER_W PERCENT_LOWER_I PERCENT_UPPER_I].freeze
38
- LINE_ENDS = %i[NEWLINE IGNORED_NEWLINE EOF COMMENT].freeze
34
+ OPENING_BRACKET_AT_LINE_END = /[(\[{]\z/
35
+ MAX_NESTING = 500
39
36
  WHITESPACE_MARKERS = /[<>']*/
40
37
  TEXT_LINE_INDICATOR = /([|'])([<>]{1,2}(?: |\z)| ?)/
41
38
  HTML_COMMENT = /\/!( ?)/
@@ -98,9 +95,16 @@ module SuperSlim
98
95
  source.force_encoding(Encoding::UTF_8)
99
96
  source.force_encoding(original_encoding) unless source.valid_encoding?
100
97
  end
98
+ invalid_encoding!(source) unless source.encoding == Encoding::UTF_8 && source.valid_encoding?
101
99
  source.delete_prefix("")
102
100
  end
103
101
 
102
+ def invalid_encoding!(source)
103
+ lines = source.b.split("\n")
104
+ lineno = lines.index { |line| !line.dup.force_encoding(Encoding::UTF_8).valid_encoding? } || 0
105
+ raise SyntaxError.new("Invalid UTF-8", @file, lines[lineno].to_s.force_encoding(Encoding::UTF_8).scrub, lineno + 1, 0)
106
+ end
107
+
104
108
  def line_starts(source, byte_order_mark_size)
105
109
  line_starts = [nil, byte_order_mark_size]
106
110
  source.each_line { |line| line_starts << line_starts.last + line.size }
@@ -133,12 +137,37 @@ module SuperSlim
133
137
 
134
138
  # Characters of the line read so far, even when the scanner reads a stripped copy or attribute source.
135
139
  def column
136
- @line.size - (@scanner.string.size - @scanner.charpos)
140
+ charpos = scanner_charpos
141
+ line_size - (@scanner_string_size - charpos)
137
142
  end
138
143
 
139
144
  # Where the scanner stands in the source, unlike `column` exact on a stripped line or on attribute source.
140
145
  def source_offset
141
- @line_starts[@lineno] + @scanner_column + @scanner.charpos
146
+ @line_starts[@lineno] + @scanner_column + scanner_charpos
147
+ end
148
+
149
+ # StringScanner#charpos and String#size count from the start of the string at each call, and the outline asks
150
+ # for them at each attribute: counted on from where the last call left off, they stay linear in the line.
151
+ def scanner_charpos
152
+ string = @scanner.string
153
+ position = @scanner.pos
154
+ unless string.equal?(@charpos_string) && position >= @charpos_byte
155
+ @charpos_string = string
156
+ @charpos_byte = @charpos_char = 0
157
+ @scanner_string_size = string.size
158
+ @scanner_string_ascii = string.ascii_only?
159
+ end
160
+ return position if @scanner_string_ascii
161
+
162
+ @charpos_char += string.byteslice(@charpos_byte, position - @charpos_byte).size
163
+ @charpos_byte = position
164
+ @charpos_char
165
+ end
166
+
167
+ def line_size
168
+ @line_size = @line.size unless @line.equal?(@sized_line)
169
+ @sized_line = @line
170
+ @line_size
142
171
  end
143
172
 
144
173
  def line_end_offset
@@ -232,7 +261,7 @@ module SuperSlim
232
261
  record_ruby(:text, source_offset, line_end_offset) if @outline
233
262
  children = []
234
263
  @stacks.last << located(InlineHtml.new(@scanner.rest, children))
235
- @stacks << children
264
+ nest(children)
236
265
  end
237
266
 
238
267
  def parse_control
@@ -240,7 +269,7 @@ module SuperSlim
240
269
  @scanner.pos += 1
241
270
  children = []
242
271
  @stacks.last << located(Control.new(parse_broken_line, children), lineno)
243
- @stacks << children
272
+ nest(children)
244
273
  end
245
274
 
246
275
  def parse_output
@@ -259,7 +288,7 @@ module SuperSlim
259
288
  lineno = @lineno
260
289
  @stacks.last << located(Output.new(parse_broken_line, escape, children), lineno)
261
290
  @stacks.last << Static.new(" ") if trailing_whitespace
262
- @stacks << children
291
+ nest(children)
263
292
  end
264
293
 
265
294
  def parse_tag_line
@@ -365,33 +394,22 @@ module SuperSlim
365
394
  first = source_offset + @scanner.rest[/\A\s*/].size if @outline
366
395
  broken_line = @scanner.rest
367
396
  broken_line.strip!
368
- while broken_line.match?(LINE_CONTINUATION) || (broken_line.match?(OPENING_BRACKET_AT_LINE_END) && bracket_open_at_line_end?(broken_line))
397
+ brackets = RubyBrackets.new(broken_line) if broken_line.match?(OPENING_BRACKET_AT_LINE_END)
398
+ line = broken_line
399
+ while line.match?(LINE_CONTINUATION) || brackets&.open_at_line_end?
369
400
  expect_next_line
370
- broken_line << "\n" << @scanner.string
401
+ line = @scanner.string
402
+ broken_line << "\n" << line
403
+ if brackets
404
+ brackets << line
405
+ elsif line.match?(OPENING_BRACKET_AT_LINE_END)
406
+ brackets = RubyBrackets.new(broken_line)
407
+ end
371
408
  end
372
409
  record_ruby(:code, first, line_end_offset) if @outline
373
410
  broken_line
374
411
  end
375
412
 
376
- # A bracket that ends its line and is still open continues the code on the next lines, until it closes. A
377
- # bracket opened mid-line, as in `items.each { |item|`, doesn't: Slim reads the lines below it as children.
378
- def bracket_open_at_line_end?(code)
379
- tokens = Prism.lex(code).value
380
- open_brackets = []
381
- tokens.each_with_index do |(token, _state), index|
382
- type = token.type
383
- if OPENING_BRACKETS.include?(type) || PERCENT_LISTS.include?(type)
384
- following = tokens[index + 1]&.first
385
- # In %w[ and %i[, the line break after the bracket is a word separator.
386
- at_line_end = LINE_ENDS.include?(following&.type) || (following&.type == :WORDS_SEP && following.value.start_with?("\n"))
387
- open_brackets << [type, at_line_end]
388
- elsif CLOSING_BRACKETS.include?(type) || (type == :STRING_END && PERCENT_LISTS.include?(open_brackets.last&.first))
389
- open_brackets.pop
390
- end
391
- end
392
- open_brackets.any? { |(_type, at_line_end)| at_line_end }
393
- end
394
-
395
413
  def parse_tag(tag)
396
414
  tag_lineno = @lineno
397
415
  tag = Shortcuts::DEFAULT_TAG if Shortcuts::ATTRIBUTE_BY_SHORTCUT.key?(tag)
@@ -428,18 +446,19 @@ module SuperSlim
428
446
  siblings.insert(-2, Static.new(" ")) if output_leading_whitespace && !leading_whitespace
429
447
  siblings << Static.new(" ") if output_trailing_whitespace && !trailing_whitespace
430
448
  end
431
- @stacks << block if block
449
+ nest(block) if block
432
450
  end
433
451
 
434
452
  # Returns the tag content, the block expecting indented children, and the whitespace an `=<>` output adds.
435
453
  def parse_tag_content
436
- output_column = column if @outline
454
+ # Not `column`, which counts the spaces stripped from the end of a continuation line.
455
+ output_column = @scanner_column + scanner_charpos if @outline
437
456
  if @scanner.skip(NESTED_TAG)
438
457
  return [[parse_embedded(@scanner[1], @scanner[2], @scanner.rest)]] if @scanner.skip(ENGINE)
439
458
 
440
459
  (tag = scan_tag) || syntax_error!("Expected tag")
441
460
  content = []
442
- @stacks << content
461
+ nest(content)
443
462
  stack_index = @stacks.size - 1
444
463
  parse_tag(tag)
445
464
  @stacks.delete_at(stack_index)
@@ -572,6 +591,12 @@ module SuperSlim
572
591
  value
573
592
  end
574
593
 
594
+ # The compiler, the linter and Ruby's own parser of the compiled code walk the tree recursively.
595
+ def nest(children)
596
+ syntax_error!("Tags nested more than #{MAX_NESTING} levels deep") if @stacks.size > MAX_NESTING
597
+ @stacks << children
598
+ end
599
+
575
600
  def syntax_error!(message)
576
601
  error = SyntaxError.new(message, @file, @line, @lineno, (@line && @scanner) ? column : 0)
577
602
  error.set_backtrace(["#{@file}:#{@lineno}", *caller])
@@ -34,7 +34,7 @@ module SuperSlim
34
34
  TRAILING_DO = /(?:\b[ \t]*|[ \t])do[ \t]*(\|[^|]*\|)?[ \t]*(#.*)?\z/
35
35
  WHEN = /\A\s*when[ \t]/
36
36
  THEN = /[ \t]then(?:[ \t].*)?\z/m
37
- INTERPOLATION = /#\{((?>[^{}]|(\{(?>[^{}]|\g<1>)*\}))*)\}/
37
+ INTERPOLATION_START = /#\{/
38
38
  ESCAPED_INTERPOLATION = /\\#\{/
39
39
  UNESCAPED_INTERPOLATION_CODE = /\A\{.*\}\z/m
40
40
  TEXT_WITHOUT_INTERPOLATION = /[^#\\]+|./m
@@ -63,8 +63,8 @@ module SuperSlim
63
63
  parser.call(@source)
64
64
  parser.ruby_ranges.flat_map do |kind, first, last|
65
65
  # From the start of its first line, so that the indentation of a `ruby:` block is the same on every line.
66
- first = (@source.rindex("\n", first - 1) || -1) + 1 if kind == :embedded_ruby
67
- fragment = Fragment.new(@source[first...last], first)
66
+ first = character_offset((@source.byterindex("\n", byte_offset(first) - 1) || -1) + 1) if kind == :embedded_ruby
67
+ fragment = Fragment.new(@source.byteslice(byte_offset(first)...byte_offset(last)), first)
68
68
  case kind
69
69
  when :text then interpolations(fragment)
70
70
  when :code then without_block_syntax(fragment)
@@ -75,19 +75,41 @@ module SuperSlim
75
75
  []
76
76
  end
77
77
 
78
+ # The ranges count characters, and slicing by characters counts them again from the start of the template
79
+ # at each slice: on a template that isn't ASCII, each character's byte offset is worked out once.
80
+ def byte_offset(character_offset)
81
+ byte_offsets ? byte_offsets[character_offset] : character_offset
82
+ end
83
+
84
+ def character_offset(byte_offset)
85
+ byte_offsets ? byte_offsets.bsearch_index { _1 >= byte_offset } : byte_offset
86
+ end
87
+
88
+ def byte_offsets
89
+ return if @source.ascii_only?
90
+
91
+ @byte_offsets ||= begin
92
+ offsets = [0]
93
+ @source.each_char { |character| offsets << offsets.last + character.bytesize }
94
+ offsets
95
+ end
96
+ end
97
+
78
98
  def tailwind_classes?
79
99
  configuration = Linter.configuration
80
100
  configuration.key?("tailwind_classes") ? configuration["tailwind_classes"] : SuperSlim.tailwind_classes
81
101
  end
82
102
 
83
103
  def interpolations(text)
104
+ closing_by_opening = Compiler.closing_braces(text.code)
84
105
  scanner = StringScanner.new(text.code)
85
106
  fragments = []
86
107
  until scanner.eos?
87
108
  next if scanner.skip(ESCAPED_INTERPOLATION)
88
109
 
89
- if scanner.scan(INTERPOLATION)
90
- code = scanner[1]
110
+ if scanner.match?(INTERPOLATION_START) && (closing = closing_by_opening[scanner.pos + 1])
111
+ code = text.code.byteslice(scanner.pos + 2...closing)
112
+ scanner.pos = closing + 1
91
113
  offset = text.offset + scanner.charpos - code.size - 1
92
114
  fragments << (code.match?(UNESCAPED_INTERPOLATION_CODE) ? Fragment.new(code[1..-2], offset + 1) : Fragment.new(code, offset))
93
115
  else
@@ -33,8 +33,13 @@ module SuperSlim
33
33
 
34
34
  # Attributes only known at render time: splats (`*hash`), `data=`/`aria=` hashes and dynamic tags (`*{tag: "a"}`).
35
35
  class Attributes
36
- INVALID_NAME = /[ \0"'>\/=]/
36
+ # Slim lets tabs and line breaks through: they end a name, so `data: {"x\tonclick" => code}` set onclick.
37
+ INVALID_NAME = /[[:cntrl:] "'>\/=]/
38
+ # Read after escaping, which turns markup into entities: `&` is refused with the rest.
39
+ VALID_TAG = /\A[a-zA-Z][^[:cntrl:] "'&<>\/=]*\z/
37
40
  HYPHENATED = %w[data aria].freeze
41
+ # Far deeper than any page needs, and short of the stack a hash referring to itself would exhaust.
42
+ MAX_HYPHENATED_DEPTH = 100
38
43
 
39
44
  def initialize(html_safe)
40
45
  @html_safe = html_safe
@@ -57,7 +62,7 @@ module SuperSlim
57
62
  end
58
63
 
59
64
  def attr(name, value)
60
- raise InvalidAttributeNameError, "Invalid attribute name '#{name}' was rendered" if name.match?(INVALID_NAME)
65
+ raise InvalidAttributeNameError, "Invalid attribute name '#{name}' was rendered" if name.empty? || name.match?(INVALID_NAME)
61
66
 
62
67
  if !@value_by_name.key?(name)
63
68
  @value_by_name[name] = value
@@ -71,6 +76,7 @@ module SuperSlim
71
76
  def build_tag(content = nil)
72
77
  tag = @value_by_name.delete("tag").to_s
73
78
  tag = "div" if tag.empty?
79
+ raise InvalidTagNameError, "Invalid tag name '#{tag}' was rendered" unless tag.match?(VALID_TAG)
74
80
  content ? "<#{tag}#{self}>#{content}</#{tag}>" : "<#{tag}#{self} />"
75
81
  end
76
82
 
@@ -85,9 +91,11 @@ module SuperSlim
85
91
 
86
92
  private
87
93
 
88
- def hyphenated_attr(name, escape, value)
94
+ def hyphenated_attr(name, escape, value, depth = 0)
89
95
  if value.is_a?(Hash)
90
- value.each { |key, nested_value| hyphenated_attr("#{name}-#{key}", escape, nested_value) }
96
+ raise Error, "A data or aria hash is nested more than #{MAX_HYPHENATED_DEPTH} levels deep" if depth > MAX_HYPHENATED_DEPTH
97
+
98
+ value.each { |key, nested_value| hyphenated_attr("#{name}-#{key}", escape, nested_value, depth + 1) }
91
99
  else
92
100
  attr(name, escape(escape, value))
93
101
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module SuperSlim
4
- VERSION = "3.1.0"
4
+ VERSION = "3.1.1"
5
5
  end
data/lib/super_slim.rb CHANGED
@@ -13,6 +13,7 @@ module SuperSlim
13
13
 
14
14
  class Error < StandardError; end
15
15
  class InvalidAttributeNameError < Error; end
16
+ class InvalidTagNameError < Error; end
16
17
  class UnsafeFormattingError < Error; end
17
18
 
18
19
  class SyntaxError < Error
@@ -34,7 +35,7 @@ module SuperSlim
34
35
  #{error}
35
36
  #{file}, Line #{lineno}, Column #{@column}
36
37
  #{line}
37
- #{" " * column}^
38
+ #{" " * [column, 0].max}^
38
39
  MESSAGE
39
40
  end
40
41
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: super-slim
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.1.0
4
+ version: 3.1.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Level UP Solutions
@@ -50,6 +50,7 @@ files:
50
50
  - lib/super_slim/linter/rules.rb
51
51
  - lib/super_slim/parallel.rb
52
52
  - lib/super_slim/parser.rb
53
+ - lib/super_slim/parser/ruby_brackets.rb
53
54
  - lib/super_slim/rails_handler.rb
54
55
  - lib/super_slim/railtie.rb
55
56
  - lib/super_slim/rubocop.rb