forked from influxdata/kapacitor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lex.go
540 lines (487 loc) · 10.1 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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
package tick
import (
"fmt"
"strings"
"unicode"
"unicode/utf8"
)
type tokenType int
type stateFn func(*lexer) stateFn
const eof = -1
const (
TokenError tokenType = iota
TokenEOF
TokenVar
TokenAsgn
TokenDot
TokenIdent
TokenReference
TokenLambda
TokenNumber
TokenString
TokenDuration
TokenLParen
TokenRParen
TokenComma
TokenNot
TokenTrue
TokenFalse
TokenRegex
// begin operator tokens
begin_tok_operator
//begin mathematical operators
begin_tok_operator_math
TokenPlus
TokenMinus
TokenMult
TokenDiv
TokenMod
//end mathematical operators
end_tok_operator_math
// begin comparison operators
begin_tok_operator_comp
TokenAnd
TokenOr
TokenEqual
TokenNotEqual
TokenLess
TokenGreater
TokenLessEqual
TokenGreaterEqual
TokenRegexEqual
TokenRegexNotEqual
//end comparison operators
end_tok_operator_comp
//end operator tokens
end_tok_operator
)
var operatorStr = [...]string{
TokenNot: "!",
TokenPlus: "+",
TokenMinus: "-",
TokenMult: "*",
TokenDiv: "/",
TokenMod: "%",
TokenEqual: "==",
TokenNotEqual: "!=",
TokenLess: "<",
TokenGreater: ">",
TokenLessEqual: "<=",
TokenGreaterEqual: ">=",
TokenRegexEqual: "=~",
TokenRegexNotEqual: "!~",
TokenAnd: "AND",
TokenOr: "OR",
}
var strToOperator map[string]tokenType
var keywords = map[string]tokenType{
"AND": TokenAnd,
"OR": TokenOr,
"TRUE": TokenTrue,
"FALSE": TokenFalse,
"var": TokenVar,
"lambda": TokenLambda,
}
func init() {
strToOperator = make(map[string]tokenType, len(operatorStr))
for t, s := range operatorStr {
strToOperator[s] = tokenType(t)
}
}
//String representation of an tokenType
func (t tokenType) String() string {
switch {
case t == TokenError:
return "ERR"
case t == TokenEOF:
return "EOF"
case t == TokenVar:
return "var"
case t == TokenIdent:
return "identifier"
case t == TokenReference:
return "reference"
case t == TokenDuration:
return "duration"
case t == TokenNumber:
return "number"
case t == TokenString:
return "string"
case t == TokenRegex:
return "regex"
case t == TokenDot:
return "."
case t == TokenAsgn:
return "="
case t == TokenLParen:
return "("
case t == TokenRParen:
return ")"
case t == TokenComma:
return ","
case t == TokenNot:
return "!"
case t == TokenTrue:
return "TRUE"
case t == TokenFalse:
return "FALSE"
case isOperator(t):
return operatorStr[t]
}
return fmt.Sprintf("%d", t)
}
func isOperator(typ tokenType) bool {
return typ > begin_tok_operator && typ < end_tok_operator
}
func isMathOperator(typ tokenType) bool {
return typ > begin_tok_operator_math && typ < end_tok_operator_math
}
func isCompOperator(typ tokenType) bool {
return typ > begin_tok_operator_comp && typ < end_tok_operator_comp
}
// token represents a token or text string returned from the scanner.
type token struct {
typ tokenType
pos int
val string
}
func (t token) String() string {
return fmt.Sprintf("{%v pos: %d val: %s}", t.typ, t.pos, t.val)
}
// lexer holds the state of the scanner.
type lexer struct {
input string // the string being scanned.
start int // start position of this token.
pos int // current position in the input.
width int // width of last rune read from input.
tokens chan token // channel of scanned tokens.
}
func lex(input string) *lexer {
l := &lexer{
input: input,
tokens: make(chan token),
}
go l.run()
return l
}
// run lexes the input by executing state functions until
// the state is nil.
func (l *lexer) run() {
for state := lexToken; state != nil; {
state = state(l)
}
close(l.tokens)
}
// emit passes an token back to the client.
func (l *lexer) emit(t tokenType) {
l.tokens <- token{t, l.start, l.current()}
l.start = l.pos
}
// nextToken returns the next token from the input.
// The second value is false when there are no more tokens
func (l *lexer) nextToken() (token, bool) {
tok, closed := <-l.tokens
return tok, closed
}
// lineNumber reports which line number and start of line position of a given position is on in the input
func (l *lexer) lineNumber(pos int) (int, int) {
line := 1 + strings.Count(l.input[:pos], "\n")
i := strings.LastIndex(l.input[:pos], "\n")
return line, pos - i
}
// next returns the next rune in the input.
func (l *lexer) next() (r rune) {
if l.pos >= len(l.input) {
l.width = 0
return eof
}
r, l.width =
utf8.DecodeRuneInString(l.input[l.pos:])
l.pos += l.width
return
}
// errorf returns an error token and terminates the scan by passing
// back a nil pointer that will be the next state, terminating l.nextToken.
func (l *lexer) errorf(format string, args ...interface{}) stateFn {
l.tokens <- token{TokenError, l.start, fmt.Sprintf(format, args...)}
return nil
}
//Backup the lexer to the previous rune
func (l *lexer) backup() {
l.pos -= l.width
}
// peek returns but does not consume the next rune in the input.
func (l *lexer) peek() rune {
r := l.next()
l.backup()
return r
}
//Backup the lexer to the previous rune
func (l *lexer) current() string {
return l.input[l.start:l.pos]
}
// ignore skips over the pending input before this point.
func (l *lexer) ignore() {
l.start = l.pos
}
// ignore a contiguous block of spaces.
func (l *lexer) ignoreSpace() {
for isSpace(l.next()) {
l.ignore()
}
l.backup()
}
// expect the next rune to be r
func (l *lexer) expect(r rune) bool {
if l.peek() == r {
l.next()
return true
}
return false
}
func lexToken(l *lexer) stateFn {
for {
switch r := l.next(); {
case isOperatorChar(r):
l.backup()
return lexOperator
case unicode.IsDigit(r), r == '-':
l.backup()
return lexNumberOrDuration
case unicode.IsLetter(r):
return lexIdentOrKeyword
case r == '"':
return lexReference
case r == '\'':
l.backup()
return lexSingleOrTripleString
case isSpace(r):
l.ignore()
case r == '(':
l.emit(TokenLParen)
return lexToken
case r == ')':
l.emit(TokenRParen)
return lexToken
case r == '.':
l.emit(TokenDot)
return lexToken
case r == ',':
l.emit(TokenComma)
return lexToken
case r == eof:
l.emit(TokenEOF)
return nil
default:
l.errorf("unknown state")
return nil
}
}
}
const operatorChars = "+-*/><!=%"
func isOperatorChar(r rune) bool {
return strings.IndexRune(operatorChars, r) != -1
}
func lexOperator(l *lexer) stateFn {
for {
switch l.next() {
case '+', '-', '*', '%':
op := strToOperator[l.current()]
l.emit(op)
return lexToken
case '/':
if l.peek() == '/' {
l.backup()
return lexComment
}
op := strToOperator[l.current()]
l.emit(op)
return lexToken
case '!':
if l.peek() == '=' || l.peek() == '~' {
l.next()
}
op := strToOperator[l.current()]
l.emit(op)
if op == TokenRegexNotEqual {
l.ignoreSpace()
if l.peek() == '/' {
return lexRegex
}
}
return lexToken
case '>', '<':
if l.peek() == '=' {
l.next()
}
op := strToOperator[l.current()]
l.emit(op)
return lexToken
case '=':
if l.peek() == '~' || l.peek() == '=' {
l.next()
op := strToOperator[l.current()]
l.emit(op)
if op == TokenRegexEqual {
l.ignoreSpace()
if l.peek() == '/' {
return lexRegex
}
}
} else {
l.emit(TokenAsgn)
l.ignoreSpace()
if l.peek() == '/' {
return lexRegex
}
}
return lexToken
}
}
}
func lexIdentOrKeyword(l *lexer) stateFn {
for {
switch r := l.next(); {
case isValidIdent(r):
//absorb
default:
l.backup()
if t := keywords[l.current()]; t > 0 {
if t == TokenLambda && l.next() != ':' {
return l.errorf("missing ':' on lambda keyword")
}
l.emit(t)
} else {
l.emit(TokenIdent)
}
return lexToken
}
}
}
// isValidIdent reports whether r is either a letter or a digit
func isValidIdent(r rune) bool {
return unicode.IsDigit(r) || unicode.IsLetter(r) || r == '_'
}
// isSpace reports whether r is a space character.
func isSpace(r rune) bool {
return unicode.IsSpace(r)
}
const durationUnits = "uµsmhdw"
func isDurUnit(r rune) bool {
return strings.IndexRune(durationUnits, r) != -1
}
func lexNumberOrDuration(l *lexer) stateFn {
foundDecimal := false
for {
switch r := l.next(); {
case r == '.':
if foundDecimal {
return l.errorf("multiple decimals in number")
}
foundDecimal = true
case unicode.IsDigit(r):
//absorb
case isDurUnit(r):
if r == 'm' && l.peek() == 's' {
l.next()
}
l.emit(TokenDuration)
return lexToken
default:
l.backup()
l.emit(TokenNumber)
return lexToken
}
}
}
func lexReference(l *lexer) stateFn {
for {
switch r := l.next(); r {
case '\\':
if l.peek() == '"' {
l.next()
}
case '"':
l.emit(TokenReference)
return lexToken
case eof:
return l.errorf("unterminated field reference")
}
}
}
func lexSingleOrTripleString(l *lexer) stateFn {
count := 0
total := 0
for {
switch r := l.next(); r {
case '\'':
count++
if count == 1 && l.peek() == '\'' {
// check for empty '' string
count++
l.next()
if l.peek() == '\'' {
count++
l.next()
} else {
l.emit(TokenString)
return lexToken
}
}
if (count == 1 && l.peek() != '\'') || count == 3 {
total = count
for {
switch r := l.next(); {
//escape single quotes if single quoted
case r == '\\' && count == 1:
if l.peek() == '\'' {
l.next()
}
case r == '\'':
count--
if count == 0 {
l.emit(TokenString)
return lexToken
}
case r == eof:
return l.errorf("unterminated string")
default:
count = total
}
}
}
default:
return l.errorf("unterminated string")
}
}
}
func lexRegex(l *lexer) stateFn {
if n := l.next(); n != '/' {
return l.errorf(`unexpected "%c" expected "/"`, n)
}
for {
switch r := l.next(); {
case r == '\\':
if l.peek() == '/' {
l.next()
}
case r == '/':
l.emit(TokenRegex)
return lexToken
default:
//absorb
}
}
}
func lexComment(l *lexer) stateFn {
if !l.expect('/') {
return l.errorf("invalid character '/'")
}
for {
switch r := l.next(); {
case r == '\n' || r == eof:
l.ignore()
return lexToken
}
}
}