forked from magiconair/properties
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.go
86 lines (74 loc) · 1.71 KB
/
parser.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
// Copyright 2013-2022 Frank Schroeder. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package properties
import (
"fmt"
"runtime"
)
type parser struct {
lex *lexer
}
func parse(input string) (properties *Properties, err error) {
p := &parser{lex: lex(input)}
defer p.recover(&err)
properties = NewProperties()
key := ""
comments := []string{}
for {
token := p.expectOneOf(itemComment, itemKey, itemEOF)
switch token.typ {
case itemEOF:
goto done
case itemComment:
comments = append(comments, token.val)
continue
case itemKey:
key = token.val
if _, ok := properties.m[key]; !ok {
properties.k = append(properties.k, key)
}
}
token = p.expectOneOf(itemValue, itemEOF)
if len(comments) > 0 {
properties.c[key] = comments
comments = []string{}
}
switch token.typ {
case itemEOF:
properties.m[key] = ""
goto done
case itemValue:
properties.m[key] = token.val
}
}
done:
return properties, nil
}
func (p *parser) errorf(format string, args ...interface{}) {
format = fmt.Sprintf("properties: Line %d: %s", p.lex.lineNumber(), format)
panic(fmt.Errorf(format, args...))
}
func (p *parser) expectOneOf(expected ...itemType) (token item) {
token = p.lex.nextItem()
for _, v := range expected {
if token.typ == v {
return token
}
}
p.unexpected(token)
panic("unexpected token")
}
func (p *parser) unexpected(token item) {
p.errorf(token.String())
}
// recover is the handler that turns panics into returns from the top level of Parse.
func (p *parser) recover(errp *error) {
e := recover()
if e != nil {
if _, ok := e.(runtime.Error); ok {
panic(e)
}
*errp = e.(error)
}
}