-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse.go
83 lines (68 loc) · 1.45 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
package vdf
import (
"log"
)
type parser struct {
lex *lexer
token [3]token
peekCount int
}
// -------------------------------------------------------
// Parse returns a map of parsed data
func Parse(data string) map[string]interface{} {
p := &parser{
lex: &lexer{
src: data,
},
}
m := make(map[string]interface{})
if t := p.next(); t.Typ == IDENTIFIER && p.peek().Typ == LBRACE {
m[t.Val] = p.parseInside()
}
return m
}
// -------------------------------------------------------
// parseInside parses inside braces
func (p *parser) parseInside() map[string]interface{} {
m := make(map[string]interface{})
p.next() // skip left brace
loop:
for {
switch t := p.next(); t.Typ {
case EOF:
break loop
case ILLEGAL:
log.Fatalf("%+v", t)
case RBRACE:
return m
case IDENTIFIER:
if p.peek().Typ == LBRACE {
m[t.Val] = p.parseInside()
} else if p.peek().Typ == IDENTIFIER {
m[t.Val] = p.next().Val
}
default:
log.Fatalf("unexpected token: %+v", t)
}
}
return m
}
// -------------------------------------------------------
// next returns the next token.
func (p *parser) next() token {
if p.peekCount > 0 {
p.peekCount--
} else {
p.token[0] = p.lex.token()
}
return p.token[p.peekCount]
}
// peek returns but does not consume the next token.
func (p *parser) peek() token {
if p.peekCount > 0 {
return p.token[p.peekCount-1]
}
p.peekCount = 1
p.token[0] = p.lex.token()
return p.token[0]
}