-
Notifications
You must be signed in to change notification settings - Fork 6
/
parse.go
134 lines (119 loc) · 2.53 KB
/
parse.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package ini
// unexpectedTokenErr describes a token that was not expected by the parser in
// the lexer's current state.
type unexpectedTokenErr struct {
got token
}
func (e unexpectedTokenErr) Error() string {
return "unexpected token: " + e.got.val
}
type parser struct {
tree parseTree
l *lexer
tok token
prev *token
}
func newParser(data []byte) *parser {
p := parser{
tree: newParseTree(),
l: lex(string(data)),
}
return &p
}
func (p *parser) nextToken() {
if p.prev != nil {
p.tok = *p.prev
p.prev = nil
} else {
p.tok = p.l.nextToken()
}
}
func (p *parser) backup() {
p.prev = &p.tok
}
// parse advances the token scanner repeatedly, constructing a parseTree on
// each step through the token stream until an EOF token is encountered.
func (p *parser) parse() error {
for {
if p.tok.typ == tokenEOF {
return nil
}
p.nextToken()
switch p.tok.typ {
case tokenEOF:
return nil
case tokenError:
return &unexpectedTokenErr{p.tok}
case tokenSection:
sec := newSection(p.tok.val)
if err := p.parseSection(&sec); err != nil {
return err
}
p.tree.add(sec)
case tokenPropKey:
prop, err := p.tree.global.get(p.tok.val)
if err != nil {
return err
}
if err := p.parseProperty(prop); err != nil {
return err
}
p.tree.global.add(*prop)
case tokenComment:
continue
default:
return &unexpectedTokenErr{got: p.tok}
}
}
}
// parseSection repeatedly advances the token scanner, constructing a section
// parseTree element from the scanned values.
func (p *parser) parseSection(out *section) error {
name := p.tok.val
out.name = name
for {
p.nextToken()
switch p.tok.typ {
case tokenError:
return &unexpectedTokenErr{got: p.tok}
case tokenPropKey:
prop, err := out.get(p.tok.val)
if err != nil {
return err
}
if err := p.parseProperty(prop); err != nil {
return err
}
out.add(*prop)
case tokenSection:
// we've parsed too far; backup so we can parse the next section
p.backup()
return nil
case tokenComment:
continue
default:
return nil
}
}
}
// parseProperty repeatedly advances the token scanner, constructing a property
// parseTree element from the scanned values.
func (p *parser) parseProperty(out *property) error {
key := p.tok.val
subkey := ""
p.nextToken()
if p.tok.typ == tokenMapKey {
subkey = p.tok.val
p.nextToken()
}
p.nextToken()
if p.tok.typ != tokenPropValue {
return &unexpectedTokenErr{
got: p.tok,
}
}
val := p.tok.val
out.key = key
out.add(subkey, val)
return nil
}