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(namespace: nil, node_types:) ⇒ Parser

Returns a new instance of Parser.



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

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

Instance Method Details

#branch(node:, sequence:) ⇒ Object



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

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)
    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:, id: :root_node) ⇒ Object



12
13
14
# File 'lib/antlers/parser.rb', line 12

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

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



34
35
36
37
38
39
40
41
# File 'lib/antlers/parser.rb', line 34

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