Class: VDF4R::Parser

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input) ⇒ Parser

Returns a new instance of Parser.



21
22
23
24
25
26
27
28
29
30
# File 'lib/vdf4r/parser.rb', line 21

def initialize(input)
  case
  when input.respond_to?(:each_line)
    @input = input.each_line.to_a
  when input.respond_to?(:lines)
    @input = input.lines
  else
    raise ArgumentError.new('input must respond to #each_line or #lines')
  end
end

Class Method Details

.clean(input) ⇒ Object



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

def clean(input)
  input.gsub(/\\"/, '"')
end

.dirty(input) ⇒ Object



16
17
18
# File 'lib/vdf4r/parser.rb', line 16

def dirty(input)
  input.gsub('"', '\"')
end

Instance Method Details

#parseObject



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/vdf4r/parser.rb', line 32

def parse
  parser        = VDF4R::KeyValuesParser.new
  store         = Store.new
  key           = nil
  partial_value = nil
  path          = []

  @input.each_with_index do |line, index|
    node = parser.parse(Parser.clean(line))

    if node.nil?
      raise "ungrammatical content at line #{index+1}: '#{line}'" if node.nil?
    end

    begin
      _, (encounter, context) = node.value
    rescue NoMethodError => e
      
    end

    case encounter
    when :blank, :comment
      # do nothing
    when :enter_object
      raise 'no preceding key for object' unless key
      raise 'too recursive' if path.length > MAX_RECURSION
      raise 'enter during multi-line value' if partial_value
      path.push key
      key = nil
    when :exit_object
      raise 'nesting unbalanced (excessive exit)' if path.empty?
      raise 'exit during multi-line value' if partial_value
      path.pop
    when :key_value
      k, v = context
      store.traverse(path)[k] = Parser.dirty(v)
    when :key
      key = context[0]
    when :key_enter_value
      key, partial_value = context
    when :key_continue_value
      # raise unless value is non-nil
      partial_value += "\n#{context[0]}"
    when :key_exit_value
      v = partial_value + "\n#{context[0]}"
      partial_value = nil
      store.traverse(path)[k] = Parser.dirty(v)
    else
      raise 'unknown node value'
    end
  end

  raise 'nesting unbalanced (insufficient exit)' unless path.empty?

  store
end