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,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,12 +95,28 @@ 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
- source.each_line { |line| line_starts << line_starts.last + line.size }
110
+ if source.ascii_only?
111
+ line_start = 0
112
+ while (newline_index = source.byteindex("\n", line_start))
113
+ line_start = newline_index + 1
114
+ line_starts << byte_order_mark_size + line_start
115
+ end
116
+ line_starts << byte_order_mark_size + source.bytesize if line_start < source.bytesize
117
+ else
118
+ source.each_line { |line| line_starts << line_starts.last + line.size }
119
+ end
107
120
  line_starts
108
121
  end
109
122
 
@@ -133,12 +146,37 @@ module SuperSlim
133
146
 
134
147
  # Characters of the line read so far, even when the scanner reads a stripped copy or attribute source.
135
148
  def column
136
- @line.size - (@scanner.string.size - @scanner.charpos)
149
+ charpos = scanner_charpos
150
+ line_size - (@scanner_string_size - charpos)
137
151
  end
138
152
 
139
153
  # Where the scanner stands in the source, unlike `column` exact on a stripped line or on attribute source.
140
154
  def source_offset
141
- @line_starts[@lineno] + @scanner_column + @scanner.charpos
155
+ @line_starts[@lineno] + @scanner_column + scanner_charpos
156
+ end
157
+
158
+ # StringScanner#charpos and String#size count from the start of the string at each call, and the outline asks
159
+ # for them at each attribute: counted on from where the last call left off, they stay linear in the line.
160
+ def scanner_charpos
161
+ string = @scanner.string
162
+ position = @scanner.pos
163
+ unless string.equal?(@charpos_string) && position >= @charpos_byte
164
+ @charpos_string = string
165
+ @charpos_byte = @charpos_char = 0
166
+ @scanner_string_size = string.size
167
+ @scanner_string_ascii = string.ascii_only?
168
+ end
169
+ return position if @scanner_string_ascii
170
+
171
+ @charpos_char += string.byteslice(@charpos_byte, position - @charpos_byte).size
172
+ @charpos_byte = position
173
+ @charpos_char
174
+ end
175
+
176
+ def line_size
177
+ @line_size = @line.size unless @line.equal?(@sized_line)
178
+ @sized_line = @line
179
+ @line_size
142
180
  end
143
181
 
144
182
  def line_end_offset
@@ -229,10 +267,13 @@ module SuperSlim
229
267
  end
230
268
 
231
269
  def parse_inline_html
232
- record_ruby(:text, source_offset, line_end_offset) if @outline
270
+ if @outline
271
+ @outline[@lineno].text = true
272
+ record_ruby(:text, source_offset, line_end_offset)
273
+ end
233
274
  children = []
234
275
  @stacks.last << located(InlineHtml.new(@scanner.rest, children))
235
- @stacks << children
276
+ nest(children)
236
277
  end
237
278
 
238
279
  def parse_control
@@ -240,7 +281,7 @@ module SuperSlim
240
281
  @scanner.pos += 1
241
282
  children = []
242
283
  @stacks.last << located(Control.new(parse_broken_line, children), lineno)
243
- @stacks << children
284
+ nest(children)
244
285
  end
245
286
 
246
287
  def parse_output
@@ -259,7 +300,7 @@ module SuperSlim
259
300
  lineno = @lineno
260
301
  @stacks.last << located(Output.new(parse_broken_line, escape, children), lineno)
261
302
  @stacks.last << Static.new(" ") if trailing_whitespace
262
- @stacks << children
303
+ nest(children)
263
304
  end
264
305
 
265
306
  def parse_tag_line
@@ -362,36 +403,25 @@ module SuperSlim
362
403
  end
363
404
 
364
405
  def parse_broken_line
365
- first = source_offset + @scanner.rest[/\A\s*/].size if @outline
406
+ first = source_offset + @scanner.match?(WHITESPACE) if @outline
366
407
  broken_line = @scanner.rest
367
408
  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))
409
+ brackets = RubyBrackets.new(broken_line) if broken_line.match?(OPENING_BRACKET_AT_LINE_END)
410
+ line = broken_line
411
+ while line.match?(LINE_CONTINUATION) || brackets&.open_at_line_end?
369
412
  expect_next_line
370
- broken_line << "\n" << @scanner.string
413
+ line = @scanner.string
414
+ broken_line << "\n" << line
415
+ if brackets
416
+ brackets << line
417
+ elsif line.match?(OPENING_BRACKET_AT_LINE_END)
418
+ brackets = RubyBrackets.new(broken_line)
419
+ end
371
420
  end
372
421
  record_ruby(:code, first, line_end_offset) if @outline
373
422
  broken_line
374
423
  end
375
424
 
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
425
  def parse_tag(tag)
396
426
  tag_lineno = @lineno
397
427
  tag = Shortcuts::DEFAULT_TAG if Shortcuts::ATTRIBUTE_BY_SHORTCUT.key?(tag)
@@ -428,18 +458,19 @@ module SuperSlim
428
458
  siblings.insert(-2, Static.new(" ")) if output_leading_whitespace && !leading_whitespace
429
459
  siblings << Static.new(" ") if output_trailing_whitespace && !trailing_whitespace
430
460
  end
431
- @stacks << block if block
461
+ nest(block) if block
432
462
  end
433
463
 
434
464
  # Returns the tag content, the block expecting indented children, and the whitespace an `=<>` output adds.
435
465
  def parse_tag_content
436
- output_column = column if @outline
466
+ # Not `column`, which counts the spaces stripped from the end of a continuation line.
467
+ output_column = @scanner_column + scanner_charpos if @outline
437
468
  if @scanner.skip(NESTED_TAG)
438
469
  return [[parse_embedded(@scanner[1], @scanner[2], @scanner.rest)]] if @scanner.skip(ENGINE)
439
470
 
440
471
  (tag = scan_tag) || syntax_error!("Expected tag")
441
472
  content = []
442
- @stacks << content
473
+ nest(content)
443
474
  stack_index = @stacks.size - 1
444
475
  parse_tag(tag)
445
476
  @stacks.delete_at(stack_index)
@@ -554,6 +585,8 @@ module SuperSlim
554
585
 
555
586
  until depth == 0 && @scanner.peek_byte == quote_byte
556
587
  if @scanner.eos? || @scanner.match?(BACKSLASH_AT_END)
588
+ # Unlike a stripped continuation line, a line read whole keeps its trailing whitespace in the value.
589
+ @outline[@lineno].text = true if @outline && @scanner.eos? && @scanner.string.equal?(@line)
557
590
  value << (@scanner.eos? ? "\n" : " ")
558
591
  @stacks.last << NEWLINE
559
592
  expect_next_line
@@ -572,6 +605,12 @@ module SuperSlim
572
605
  value
573
606
  end
574
607
 
608
+ # The compiler, the linter and Ruby's own parser of the compiled code walk the tree recursively.
609
+ def nest(children)
610
+ syntax_error!("Tags nested more than #{MAX_NESTING} levels deep") if @stacks.size > MAX_NESTING
611
+ @stacks << children
612
+ end
613
+
575
614
  def syntax_error!(message)
576
615
  error = SyntaxError.new(message, @file, @line, @lineno, (@line && @scanner) ? column : 0)
577
616
  error.set_backtrace(["#{@file}:#{@lineno}", *caller])
@@ -5,7 +5,11 @@ module SuperSlim
5
5
  initializer "super_slim.register_template_handler" do
6
6
  ActiveSupport.on_load(:action_view) do
7
7
  require_relative "rails_handler"
8
+ require "action_view/dependency_tracker" # Rails 8.0 does not autoload it
8
9
  ActionView::Template.register_template_handler(:slim, SuperSlim::RailsHandler.new)
10
+ # After the handler: register_tracker looks it up by extension, an unknown one falls back to the Raw handler.
11
+ # Not ERBTracker: since Rails 8.1 it only reads <% %> tags, and finds no render call in Slim.
12
+ ActionView::DependencyTracker.register_tracker(:slim, ActionView::DependencyTracker::RubyTracker)
9
13
  end
10
14
  end
11
15
  end
@@ -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
@@ -45,7 +45,9 @@ module SuperSlim
45
45
 
46
46
  def initialize(processed_source)
47
47
  @processed_source = processed_source
48
- @source = processed_source.raw_source
48
+ # Offsets count in the source buffer, which reads \r\n as \n: counted with the \r, a correction lands one
49
+ # character further for each line above it.
50
+ @source = processed_source.raw_source.gsub("\r\n", "\n")
49
51
  end
50
52
 
51
53
  def call
@@ -63,8 +65,8 @@ module SuperSlim
63
65
  parser.call(@source)
64
66
  parser.ruby_ranges.flat_map do |kind, first, last|
65
67
  # 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)
68
+ first = character_offset((@source.byterindex("\n", byte_offset(first) - 1) || -1) + 1) if kind == :embedded_ruby
69
+ fragment = Fragment.new(@source.byteslice(byte_offset(first)...byte_offset(last)), first)
68
70
  case kind
69
71
  when :text then interpolations(fragment)
70
72
  when :code then without_block_syntax(fragment)
@@ -75,19 +77,41 @@ module SuperSlim
75
77
  []
76
78
  end
77
79
 
80
+ # The ranges count characters, and slicing by characters counts them again from the start of the template
81
+ # at each slice: on a template that isn't ASCII, each character's byte offset is worked out once.
82
+ def byte_offset(character_offset)
83
+ byte_offsets ? byte_offsets[character_offset] : character_offset
84
+ end
85
+
86
+ def character_offset(byte_offset)
87
+ byte_offsets ? byte_offsets.bsearch_index { _1 >= byte_offset } : byte_offset
88
+ end
89
+
90
+ def byte_offsets
91
+ return if @source.ascii_only?
92
+
93
+ @byte_offsets ||= begin
94
+ offsets = [0]
95
+ @source.each_char { |character| offsets << offsets.last + character.bytesize }
96
+ offsets
97
+ end
98
+ end
99
+
78
100
  def tailwind_classes?
79
101
  configuration = Linter.configuration
80
102
  configuration.key?("tailwind_classes") ? configuration["tailwind_classes"] : SuperSlim.tailwind_classes
81
103
  end
82
104
 
83
105
  def interpolations(text)
106
+ closing_by_opening = Compiler.closing_braces(text.code)
84
107
  scanner = StringScanner.new(text.code)
85
108
  fragments = []
86
109
  until scanner.eos?
87
110
  next if scanner.skip(ESCAPED_INTERPOLATION)
88
111
 
89
- if scanner.scan(INTERPOLATION)
90
- code = scanner[1]
112
+ if scanner.match?(INTERPOLATION_START) && (closing = closing_by_opening[scanner.pos + 1])
113
+ code = text.code.byteslice(scanner.pos + 2...closing)
114
+ scanner.pos = closing + 1
91
115
  offset = text.offset + scanner.charpos - code.size - 1
92
116
  fragments << (code.match?(UNESCAPED_INTERPOLATION_CODE) ? Fragment.new(code[1..-2], offset + 1) : Fragment.new(code, offset))
93
117
  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.2.0"
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.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Level UP Solutions
@@ -23,10 +23,10 @@ dependencies:
23
23
  - - ">="
24
24
  - !ruby/object:Gem::Version
25
25
  version: 3.1.1
26
- description: 'A Slim template engine rewritten from scratch, without Temple: same
27
- HTML as Slim 5, faster compilation and rendering with fewer allocations, a formatter
28
- that cannot change a page, a linter with HTML and accessibility rules, and a RuboCop
29
- plugin for the Ruby inside templates.'
26
+ description: A Slim template engine written from scratch, without Temple. It renders
27
+ the same HTML as Slim 5, compiles and renders faster with fewer allocations, and
28
+ comes with a formatter that cannot change a page, a linter with HTML and accessibility
29
+ rules, and a RuboCop plugin for the Ruby inside templates.
30
30
  executables:
31
31
  - super-slim
32
32
  extensions: []
@@ -44,12 +44,15 @@ files:
44
44
  - lib/super_slim/cli.rb
45
45
  - lib/super_slim/compiler.rb
46
46
  - lib/super_slim/formatter.rb
47
+ - lib/super_slim/formatter/attribute_arranger.rb
48
+ - lib/super_slim/formatter/code_wrapper.rb
47
49
  - lib/super_slim/formatter/line_wrapper.rb
48
50
  - lib/super_slim/linter.rb
49
51
  - lib/super_slim/linter/presets.rb
50
52
  - lib/super_slim/linter/rules.rb
51
53
  - lib/super_slim/parallel.rb
52
54
  - lib/super_slim/parser.rb
55
+ - lib/super_slim/parser/ruby_brackets.rb
53
56
  - lib/super_slim/rails_handler.rb
54
57
  - lib/super_slim/railtie.rb
55
58
  - lib/super_slim/rubocop.rb
@@ -82,6 +85,6 @@ required_rubygems_version: !ruby/object:Gem::Requirement
82
85
  requirements: []
83
86
  rubygems_version: 4.0.20
84
87
  specification_version: 4
85
- summary: 'Slim templates, rewritten: faster to compile and render, with a formatter
86
- and a linter'
88
+ summary: A Slim template engine that compiles and renders faster, with a formatter
89
+ and a linter
87
90
  test_files: []