Class: Antlers::Lexer

Inherits:
Object
  • Object
show all
Defined in:
lib/lexer.rb

Constant Summary collapse

IF_KEYWORDS =
['if:', ':if'].freeze
FOR_KEYWORDS =
['for:', 'in:', ':for'].freeze
FORM_KEYWORDS =
['form:', ':form'].freeze

Instance Method Summary collapse

Constructor Details

#initializeLexer

Returns a new instance of Lexer.



15
16
17
18
19
# File 'lib/lexer.rb', line 15

def initialize
  @delimiters = ['<{', '}>', '{', '}']
  @keywords = [*IF_KEYWORDS, *FORM_KEYWORDS, *FOR_KEYWORDS, 'slot:', ':slot']
  @cursor = 0
end

Instance Method Details

#parse(template) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/lexer.rb', line 21

def parse(template)
  @cursor = 0
  sequence = []

  # Split on delimiters and retain capture groups.
  segments = template.split(/(#{Regexp.union(@delimiters)})/).map(&:strip)

  until segments[@cursor].nil?
    if (antlers_segment = antlers_segment(segments:))
      sequence << antlers_lexeme(antlers_segment:, segments:)
      # Skipping: ['{', 'expression', '}']
      # Skipping: ['<{', 'name + props + keywords', '}>']
      @cursor += 3
    else
      segment = segments[@cursor]
      sequence << segment unless segment.empty?
      @cursor += 1
    end
  end

  sequence
end