-
Notifications
You must be signed in to change notification settings - Fork 0
/
lex.go
315 lines (289 loc) · 6.63 KB
/
lex.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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
package query
import (
"errors"
"fmt"
"strings"
"unicode/utf8"
)
// Based on the talk "Lexical Scanning in Go" by Rob Pike.
// http://talks.golang.org/2011/lex.slide
// character sets
const (
charAlpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
charAlphanum = charAlpha + charNumeric
charDelim = "(),"
charGlob = "[]{}*"
charDot = "."
charIdentifier = charAlphanum + "-_"
charNumeric = "0123456789"
charQuote = `"'`
charWhitespace = " \t\r\n\v\f"
)
func is(r int, sets ...string) bool {
for _, v := range sets {
if strings.ContainsRune(v, rune(r)) {
return true
}
}
return false
}
const eof = -1
type item struct {
typ int // see %token decl in expr.y
val string
}
type stateFn func(*lexer) stateFn
type lexer struct {
input string // the input string
start, pos int // start, end+1 of current item
width int // length of previous utf8 codepoint
items chan item // scanned lexemes go here
err []string // errors from yacc
last string // last token emitted
result *Query // yacc puts our result here
}
func lex(input string) *lexer {
l := lexer{
input: input,
items: make(chan item),
}
go l.run()
return &l
}
// implement the yyLex interface
func (l *lexer) Error(e string) {
s := fmt.Sprintf("%v in %q at column %d", e, l.last, l.pos-len(l.last))
l.err = append(l.err, s)
}
func (l *lexer) Lex(lval *yySymType) int {
tok, ok := <-l.items
if !ok {
// eof reached
return 0
}
lval.str = tok.val
if tok.typ == pERROR {
return 1
}
return tok.typ
}
func (l *lexer) Err() error {
if len(l.err) > 0 {
return errors.New(strings.Join(l.err, "\n\t"))
}
return nil
}
func (l *lexer) dot() string { return l.input[l.start:l.pos] }
func (l *lexer) rest() string { return l.input[l.pos:] }
func (l *lexer) ignore() { l.start = l.pos }
func (l *lexer) backup() { l.pos -= l.width }
func (l *lexer) peek() int { defer l.backup(); return l.next() }
func (l *lexer) emit(t int) {
l.last = l.dot()
l.items <- item{t, l.dot()}
l.start = l.pos
}
func (l *lexer) errorf(format string, v ...interface{}) stateFn {
l.items <- item{pERROR, fmt.Sprintf(format, v...)}
return nil
}
func (l *lexer) run() {
for state := lexClear; state != nil; state = state(l) {
}
close(l.items)
}
// Any call to lex() should be paired with a deferred
// call to l.drain(). This ensures that the lexing goroutine
// finishes.
func (l *lexer) drain() {
for range l.items {
}
}
// consumes the next character in the input
func (l *lexer) next() int {
var r rune
if l.pos >= len(l.input) {
l.width = 0
return eof
}
r, l.width = utf8.DecodeRuneInString(l.rest())
l.pos += l.width
return int(r)
}
// consume a rune from the valid set
func (l *lexer) accept(valid ...string) bool {
for _, v := range valid {
if strings.ContainsRune(v, rune(l.next())) {
return true
}
l.backup()
}
return false
}
// consume a run of consecutive runes from the valid set
func (l *lexer) acceptRun(valid ...string) {
Loop:
for {
r := rune(l.next())
for _, v := range valid {
if strings.ContainsRune(v, r) {
continue Loop
}
}
break Loop
}
l.backup()
}
// starting state, scan for any expression
func lexClear(l *lexer) stateFn {
for {
switch r := l.next(); {
case is(r, charNumeric, "+-"):
l.backup()
return lexNumber
case is(r, charWhitespace):
l.ignore()
case is(r, charIdentifier):
l.backup()
return lexName
case is(r, charGlob):
l.backup()
return lexMetric
case is(r, charDelim):
l.emit(r)
return lexClear
case is(r, charQuote):
// note that quote tokens contain their
// surrounding tokens. this allows us to
// preserve the formatting of string literals
// exactly (this is a proxy, after all).
l.backup()
return lexQuote
case r == eof:
return nil
default:
return l.errorf("unexpected character '%c' (%d)", r)
}
}
panic("not reached")
}
// read a (possibly negative, possibly) number.
// graphite only accepts decimal numbers. No
// scientific notation or imaginary numbers are
// allowed. But note that something like
//
// 305.mymetric.count
//
// could be a valid name for a metric.
func lexNumber(l *lexer) stateFn {
l.accept("+-")
l.acceptRun(charNumeric)
if l.accept(".") {
l.acceptRun(charNumeric)
}
if l.accept(charWhitespace, charDelim) {
l.backup()
l.emit(pNUMBER)
return lexClear
}
if l.accept(charAlphanum, charGlob, ".") {
l.backup()
return lexMetric
}
return l.errorf("unexpected character '%c' in number", l.peek())
}
// read a simple word, such as a function name
func lexName(l *lexer) stateFn {
l.acceptRun(charIdentifier)
if l.accept(charWhitespace, charDelim) {
l.backup()
l.emit(pWORD)
return lexClear
}
if l.accept(charGlob, charDot) {
l.backup()
return lexMetric
}
return l.errorf("unexpected character '%c' in word", l.peek())
}
// read a metric name, which is a series of words
// connected by dots. metrics may contain complex
// patterns, for instance
//
// servers.{prod,dev,stage}-sql[1-4].loadavg.*
//
// two additional states ensure the braces and brackets
// are balanced.
func lexMetric(l *lexer) stateFn {
l.acceptRun(charIdentifier, "*.")
if l.accept("{") {
return lexCurlyBrace
} else if l.accept("[") {
return lexSquareBracket
} else if l.accept(charWhitespace, charDelim) {
l.backup()
l.emit(pMETRIC)
return lexClear
} else if l.peek() == eof {
l.emit(pMETRIC)
return lexClear
}
return l.errorf("unexpected character '%c' in metric", l.peek())
}
// consume a glob expression of the form {x,y,z} (do not emit it)
// The opening '{' is already consumed. '}' characters may be
// escaped with a backslash.
func lexCurlyBrace(l *lexer) stateFn {
for {
switch l.next() {
case '\\':
if r := l.next(); r != eof {
break
}
fallthrough
case eof:
return l.errorf("unterminated brace list")
case '}':
return lexMetric
}
}
}
// consume, do not emit, a glob expression of the form [chars]
// The opening '[' is already consumed. characters may be
// escaped with a backslash.
func lexSquareBracket(l *lexer) stateFn {
for {
switch l.next() {
case '\\':
if r := l.next(); r != eof {
break
}
fallthrough
case eof:
return l.errorf("unterminated '[' glob")
case ']':
return lexMetric
}
}
}
// consume a quoted string. quotation marks within the
// string may be escaped with a backslash.
func lexQuote(l *lexer) stateFn {
quoteChar := l.next()
Loop:
for {
switch l.next() {
case '\\':
if r := l.next(); r != eof {
break
}
fallthrough
case eof:
return l.errorf("unterminated string")
case quoteChar:
break Loop
}
}
l.emit(pSTRING)
return lexClear
}