-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.go
150 lines (133 loc) · 2.37 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
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
package validator
import (
"fmt"
"io"
"strings"
)
type ValidateTag struct {
Op string
Args []interface{}
}
type LookaheadReader struct {
cur, next rune
reader *strings.Reader
}
func NewLookaheadReader(s string) *LookaheadReader {
r := &LookaheadReader{
reader: strings.NewReader(s),
}
r.Next()
return r
}
func (r *LookaheadReader) Next() rune {
r.cur = r.next
next, _, err := r.reader.ReadRune()
if err != nil {
if err == io.EOF {
next = 0
} else {
panic(err.Error())
}
}
r.next = next
return r.cur
}
func (r *LookaheadReader) Peek() rune {
return r.next
}
func (r *LookaheadReader) Match(want rune) bool {
if r.next == want {
r.Next()
return true
}
return false
}
func (r *LookaheadReader) Read(want rune) error {
if r.next == want {
r.Next()
return nil
}
return fmt.Errorf("unexpected character: %c", r.next)
}
func (r *LookaheadReader) HasNext() bool {
return r.next != 0
}
func parseValidateTags(tag string) []ValidateTag {
tags := []ValidateTag{}
r := NewLookaheadReader(tag)
for {
eatWhitespace(r)
if !r.HasNext() {
break
}
op := readLiteral(r)
args := []interface{}{}
eatWhitespace(r)
if r.Match('(') {
//We got an argument list
for {
eatWhitespace(r)
if r.Match(')') {
break
}
arg := readLiteral(r)
args = append(args, arg)
eatWhitespace(r)
if r.Match(',') {
continue
}
}
}
tags = append(tags, ValidateTag{
Op: op,
Args: args,
})
eatWhitespace(r)
if !r.Match(',') {
break
}
}
return tags
}
func eatWhitespace(r *LookaheadReader) {
for {
if !r.Match(' ') {
break
}
}
}
func read(r *strings.Reader, exp rune) {
ch, _, err := r.ReadRune()
if err != nil {
panic(fmt.Sprintf("Unexpected string reader error: %s", err))
}
if ch != exp {
panic(fmt.Sprintf("Unexpected rune: got: %c, want: %c", ch, exp))
}
}
func isAlphanum(ch rune) bool {
return (ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z') ||
(ch >= '0' && ch <= '9')
}
func isNumericSep(ch rune) bool {
return ch == '.' ||
ch == '-' ||
ch == 'e' ||
ch == 'E' ||
ch == '+'
}
func isUtilChar(ch rune) bool {
return ch == '_'
}
func readLiteral(r *LookaheadReader) string {
var res strings.Builder
for r.HasNext() {
if ch := r.Peek(); !(isAlphanum(ch) || isNumericSep(ch) || isUtilChar(ch)) {
goto Res
}
res.WriteRune(r.Next())
}
Res:
return res.String()
}