-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
lexer.go
553 lines (462 loc) · 11.8 KB
/
lexer.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
541
542
543
544
545
546
547
548
549
550
551
552
553
// Package lexer contains our lexer.
//
// The lexer returns tokens from a (string) input. These tokens are then
// parsed as a program to generate an AST, which is used to emit bytecode
// instructions ready for evaluation.
package lexer
import (
"errors"
"fmt"
"strings"
"unicode"
"github.com/skx/evalfilter/v2/token"
)
// Lexer holds our object-state.
type Lexer struct {
// The current character position
position int
// The next character position
readPosition int
// The current character
ch rune
// A rune slice of our input string
characters []rune
// Previous token.
prevToken token.Token
// Line contains our current line-number
line int
// column contains the place within the line where we are.
column int
}
// New creates a Lexer instance from the given string
func New(input string) *Lexer {
// Line counting starts at one.
l := &Lexer{characters: []rune(input), line: 1}
l.readChar()
return l
}
// read forward one character.
func (l *Lexer) readChar() {
if l.readPosition >= len(l.characters) {
l.ch = rune(0)
} else {
l.ch = l.characters[l.readPosition]
}
l.position = l.readPosition
l.readPosition++
// Line counting
if l.ch == rune('\n') {
l.column = 0
l.line++
} else {
l.column++
}
}
// NextToken reads and returns the next token, skipping any intervening
// white space, and swallowing any comments, in the process.
func (l *Lexer) NextToken() token.Token {
var tok token.Token
l.skipWhitespace()
// skip single-line comments
if l.ch == rune('/') && l.peekChar() == rune('/') {
l.skipComment()
return (l.NextToken())
}
switch l.ch {
case rune('&'):
if l.peekChar() == rune('&') {
ch := l.ch
l.readChar()
tok = token.Token{Type: token.AND, Literal: string(ch) + string(l.ch), Line: l.line, Column: l.column}
}
case rune('|'):
if l.peekChar() == rune('|') {
ch := l.ch
l.readChar()
tok = token.Token{Type: token.OR, Literal: string(ch) + string(l.ch), Line: l.line, Column: l.column}
}
case rune('='):
if l.peekChar() == rune('=') {
ch := l.ch
l.readChar()
tok = token.Token{Type: token.EQ, Literal: string(ch) + string(l.ch), Line: l.line, Column: l.column}
} else {
tok = l.newToken(token.ASSIGN, l.ch)
}
case rune(';'):
tok = l.newToken(token.SEMICOLON, l.ch)
case rune('('):
tok = l.newToken(token.LPAREN, l.ch)
case rune(')'):
tok = l.newToken(token.RPAREN, l.ch)
case rune(','):
tok = l.newToken(token.COMMA, l.ch)
case rune('.'):
if l.peekChar() == rune('.') {
ch := l.ch
l.readChar()
tok = token.Token{Type: token.DOTDOT, Literal: string(ch) + string(l.ch), Line: l.line, Column: l.column}
} else {
tok = l.newToken(token.PERIOD, l.ch)
}
case rune('+'):
if l.peekChar() == rune('+') {
ch := l.ch
l.readChar()
tok = token.Token{Type: token.PLUSPLUS, Literal: string(ch) + string(l.ch), Line: l.line, Column: l.column}
} else if l.peekChar() == rune('=') {
ch := l.ch
l.readChar()
tok = token.Token{Type: token.PLUSEQUALS, Literal: string(ch) + string(l.ch), Line: l.line, Column: l.column}
} else {
tok = l.newToken(token.PLUS, l.ch)
}
case rune('%'):
tok = l.newToken(token.MOD, l.ch)
case rune('√'):
tok = l.newToken(token.SQRT, l.ch)
case rune('{'):
tok = l.newToken(token.LBRACE, l.ch)
case rune('}'):
tok = l.newToken(token.RBRACE, l.ch)
case rune('['):
tok = l.newToken(token.LSQUARE, l.ch)
case rune(']'):
tok = l.newToken(token.RSQUARE, l.ch)
case rune('-'):
if l.peekChar() == rune('-') {
ch := l.ch
l.readChar()
tok = token.Token{Type: token.MINUSMINUS, Literal: string(ch) + string(l.ch), Line: l.line, Column: l.column}
} else if l.peekChar() == rune('=') {
ch := l.ch
l.readChar()
tok = token.Token{Type: token.MINUSEQUALS, Literal: string(ch) + string(l.ch), Line: l.line, Column: l.column}
} else {
tok = l.newToken(token.MINUS, l.ch)
}
case rune('/'):
// slash is mostly division, but could
// be the start of a regular expression
// We exclude:
// ( a + b ) / c -> RPAREN
// a / c -> IDENT
// foo[3] / 3 -> INDEX
// 3.2 / c -> FLOAT
// 1 / c -> INT
//
if l.prevToken.Type == token.RPAREN ||
l.prevToken.Type == token.IDENT ||
l.prevToken.Type == token.RSQUARE ||
l.prevToken.Type == token.FLOAT ||
l.prevToken.Type == token.INT {
if l.peekChar() == rune('=') {
ch := l.ch
l.readChar()
tok = token.Token{Type: token.SLASHEQUALS, Literal: string(ch) + string(l.ch), Line: l.line, Column: l.column}
} else {
tok = l.newToken(token.SLASH, l.ch)
}
} else {
str, err := l.readRegexp()
if err == nil {
tok.Column = l.column
tok.Line = l.line
tok.Literal = str
tok.Type = token.REGEXP
} else {
tok.Column = l.column
tok.Line = l.line
tok.Literal = err.Error()
tok.Type = token.ILLEGAL
}
return tok
}
case rune('*'):
if l.peekChar() == rune('*') {
ch := l.ch
l.readChar()
tok = token.Token{Type: token.POW, Literal: string(ch) + string(l.ch), Line: l.line, Column: l.column}
} else if l.peekChar() == rune('=') {
ch := l.ch
l.readChar()
tok = token.Token{Type: token.ASTERISKEQUALS, Literal: string(ch) + string(l.ch), Line: l.line, Column: l.column}
} else {
tok = l.newToken(token.ASTERISK, l.ch)
}
case rune('?'):
tok = l.newToken(token.QUESTION, l.ch)
case rune(':'):
tok = l.newToken(token.COLON, l.ch)
case rune('<'):
if l.peekChar() == rune('=') {
ch := l.ch
l.readChar()
tok = token.Token{Type: token.LTEQUALS, Literal: string(ch) + string(l.ch), Line: l.line, Column: l.column}
} else {
tok = l.newToken(token.LT, l.ch)
}
case rune('>'):
if l.peekChar() == rune('=') {
ch := l.ch
l.readChar()
tok = token.Token{Type: token.GTEQUALS, Literal: string(ch) + string(l.ch), Line: l.line, Column: l.column}
} else {
tok = l.newToken(token.GT, l.ch)
}
case rune('~'):
if l.peekChar() == rune('=') {
ch := l.ch
l.readChar()
tok = token.Token{Type: token.CONTAINS, Literal: string(ch) + string(l.ch), Line: l.line, Column: l.column}
}
case rune('!'):
if l.peekChar() == rune('=') {
ch := l.ch
l.readChar()
tok = token.Token{Type: token.NOTEQ, Literal: string(ch) + string(l.ch), Line: l.line, Column: l.column}
} else {
if l.peekChar() == rune('~') {
ch := l.ch
l.readChar()
tok = token.Token{Type: token.MISSING, Literal: string(ch) + string(l.ch), Line: l.line, Column: l.column}
} else {
tok = l.newToken(token.BANG, l.ch)
}
}
case rune('"'):
str, err := l.readString('"')
if err == nil {
tok.Column = l.column
tok.Line = l.line
tok.Literal = str
tok.Type = token.STRING
} else {
tok.Column = l.column
tok.Line = l.line
tok.Literal = err.Error()
tok.Type = token.ILLEGAL
}
case rune('\''):
str, err := l.readString('\'')
if err == nil {
tok.Column = l.column
tok.Line = l.line
tok.Literal = str
tok.Type = token.STRING
} else {
tok.Column = l.column
tok.Line = l.line
tok.Literal = err.Error()
tok.Type = token.ILLEGAL
}
case rune(0):
tok.Literal = ""
tok.Type = token.EOF
default:
if isDigit(l.ch) {
tok = l.readDecimal()
l.prevToken = tok
tok.Column = l.column
tok.Line = l.line
return tok
}
tok.Literal = l.readIdentifier()
if len(tok.Literal) > 0 {
tok.Type = token.LookupIdentifier(tok.Literal)
l.prevToken = tok
tok.Column = l.column
tok.Line = l.line
return tok
}
tok.Type = token.ILLEGAL
tok.Literal = fmt.Sprintf("invalid character for identifier '%c'", l.ch)
tok.Column = l.column
tok.Line = l.line
l.readChar()
return tok
}
l.readChar()
l.prevToken = tok
return tok
}
// return new token
func (l *Lexer) newToken(tokenType token.Type, ch rune) token.Token {
return token.Token{Type: tokenType, Literal: string(ch), Line: l.line, Column: l.column}
}
// readIdentifier is designed to read an identifier (name of variable,
// function, etc).
func (l *Lexer) readIdentifier() string {
id := ""
for isIdentifier(l.ch) {
id += string(l.ch)
l.readChar()
}
return id
}
// skip over any white space.
func (l *Lexer) skipWhitespace() {
for isWhitespace(l.ch) {
l.readChar()
}
}
// skip a comment (until the end of the line).
func (l *Lexer) skipComment() {
for l.ch != '\n' && l.ch != rune(0) {
l.readChar()
}
l.skipWhitespace()
}
// read a number. We only care about numerical digits here, floats will
// be handled elsewhere.
func (l *Lexer) readNumber() string {
id := ""
for isDigit(l.ch) {
id += string(l.ch)
l.readChar()
}
return id
}
// read a decimal number, either int or floating-point.
func (l *Lexer) readDecimal() token.Token {
//
// Read an integer-number.
//
integer := l.readNumber()
//
// If the next token is a `.` we've got a floating-point number.
//
if l.ch == rune('.') && isDigit(l.peekChar()) {
// Skip the period
l.readChar()
// Get the float-component.
fraction := l.readNumber()
return token.Token{Type: token.FLOAT, Literal: integer + "." + fraction}
}
//
// Just an integer.
//
return token.Token{Type: token.INT, Literal: integer}
}
// read a string, deliminated by the given character.
func (l *Lexer) readString(delim rune) (string, error) {
out := ""
for {
l.readChar()
if l.ch == rune(0) {
return "", fmt.Errorf("unterminated string")
}
if l.ch == delim {
break
}
//
// Handle \n, \r, \t, \", etc.
//
if l.ch == '\\' {
// Line ending with "\" + newline
if l.peekChar() == '\n' {
// consume the newline.
l.readChar()
continue
}
l.readChar()
if l.ch == rune(0) {
return "", errors.New("unterminated string")
}
if l.ch == rune('n') {
l.ch = '\n'
}
if l.ch == rune('r') {
l.ch = '\r'
}
if l.ch == rune('t') {
l.ch = '\t'
}
if l.ch == rune('"') {
l.ch = '"'
}
if l.ch == rune('\\') {
l.ch = '\\'
}
}
out = out + string(l.ch)
}
return out, nil
}
// read a regexp, including flags.
func (l *Lexer) readRegexp() (string, error) {
out := ""
for {
l.readChar()
if l.ch == rune(0) {
return "", fmt.Errorf("unterminated regular expression")
}
if l.ch == '/' {
// consume the terminating "/".
l.readChar()
// prepare to look for flags
flags := ""
// two flags are supported:
// i -> Ignore-case
// m -> Multiline
//
// We need to consume all letters, so we can
// alert on illegal ones.
for unicode.IsLetter(l.ch) {
// save the char - unless it is a repeat
if !strings.Contains(flags, string(l.ch)) {
// we're going to sort the flags
tmp := strings.Split(flags, "")
tmp = append(tmp, string(l.ch))
flags = strings.Join(tmp, "")
}
// read the next
l.readChar()
}
for _, c := range flags {
switch c {
case 'i', 'm':
// nop
default:
return "", fmt.Errorf("illegal regexp flag '%c' in string '%s'", c, flags)
}
}
// convert the regexp to go-lang
if len(flags) > 0 {
out = "(?" + flags + ")" + out
}
break
}
if l.ch == '\\' {
// Skip the escape-marker, and read the
// escaped character literally.
l.readChar()
}
out = out + string(l.ch)
}
return out, nil
}
// peek character
func (l *Lexer) peekChar() rune {
if l.readPosition >= len(l.characters) {
return rune(0)
}
return l.characters[l.readPosition]
}
// determinate ch is identifier or not. Identifiers may be alphanumeric,
// but they must start with a letter. Here that works because we are only
// called if the first character is alphabetical.
func isIdentifier(ch rune) bool {
if unicode.IsLetter(ch) || unicode.IsDigit(ch) || ch == '$' || ch == '_' {
return true
}
return false
}
// is white space
func isWhitespace(ch rune) bool {
return ch == rune(' ') || ch == rune('\t') || ch == rune('\n') || ch == rune('\r')
}
// is Digit
func isDigit(ch rune) bool {
return rune('0') <= ch && ch <= rune('9')
}