Class: Antlers::Parser

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

Defined Under Namespace

Classes: ParserError

Instance Method Summary collapse

Constructor Details

#initialize(node_types:, namespace: nil) ⇒ Parser

Returns a new instance of Parser.



7
8
9
10
11
# File 'lib/antlers/parser.rb', line 7

def initialize(node_types:, namespace: nil)
  @node_types = node_types.to_a
  @namespace = namespace
  @template = nil
end

Instance Method Details

#branch(node:, sequence:) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/antlers/parser.rb', line 19

def branch(node:, sequence:)
  until sequence.empty?
    segment = sequence.shift

    child_class = @node_types.find { |n| n.match?(segment:) }
    raise(ParserError, "No node matches #{segment}") unless child_class

    child = child_class.build(segment:, namespace: @namespace, template: @template)
    node.children << child

    if (end_key = child_class::END_KEY)
      sub_branch(node: child, sequence:, end_key:, end_name: child.end_name)
    end
  end

  node
end

#parse(sequence:, template: nil, id: :root_node) ⇒ Object



13
14
15
16
17
# File 'lib/antlers/parser.rb', line 13

def parse(sequence:, template: nil, id: :root_node)
  @template = template

  branch(node: RootNode.new(name: id), sequence:)
end

#sub_branch(node:, sequence:, end_key:, end_name: nil) ⇒ Object



37
38
39
40
41
42
43
44
# File 'lib/antlers/parser.rb', line 37

def sub_branch(node:, sequence:, end_key:, end_name: nil)
  sub_sequence = []
  sub_sequence << sequence.shift until sequence.first.is_a?(Hash) && sequence.first[end_key] == end_name
  # Remove the end tag we just stopped before.
  sequence.shift

  branch(node:, sequence: sub_sequence)
end