-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlexer.go
495 lines (406 loc) · 8.81 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
package cask
// The Lexer has been stolen from:
// https://github.com/goruby/goruby/blob/master/lexer
import (
"bytes"
"fmt"
"strings"
"unicode"
"unicode/utf8"
)
const eof = -1
// Lexer is the engine to process input and emit Tokens.
type Lexer struct {
// input specifies the string being scanned.
input string
// state specifies the next lexing function to enter.
state StateFn
// position specifies current position in the input.
position int
// lines specifies the number of lines that have been lexed in input.
lines int
// start specifies the position of this item.
start int
// width specifies the width of the last rune read from input.
width int
// tokens specifies the channel of scanned tokens.
tokens chan Token
}
// LexStartFn represents the entrypoint the Lexer uses to start processing the
// input.
var LexStartFn = startLexer
// StateFn represents a function which is capable of lexing parts of the
// input. It returns another StateFn to proceed with.
//
// Typically a state function would get called from LexStartFn and should
// return LexStartFn to go back to the decision loop. It also could return
// another non start state function if the partial input to parse is abiguous.
type StateFn func(*Lexer) StateFn
// NewLexer creates a new Lexer instance and returns its pointer. Requires an
// input to be passed as an argument that is ready to be processed.
func NewLexer(input string) *Lexer {
return &Lexer{
input: input,
state: startLexer,
tokens: make(chan Token, 3), // three tokens are sufficient.
}
}
// NextToken will return the next token processed from the lexer.
func (l *Lexer) NextToken() Token {
for {
select {
case item, ok := <-l.tokens:
if ok {
return item
}
panic(fmt.Errorf("No tokens left"))
default:
l.state = l.state(l)
if l.state == nil {
close(l.tokens)
}
}
}
}
// HasNext returns true if there are tokens left, false if EOF has reached.
func (l *Lexer) HasNext() bool {
return l.state != nil
}
// emit passes a token back to the client.
func (l *Lexer) emit(t TokenType) {
l.tokens <- *NewToken(t, l.input[l.start:l.position], l.start)
l.start = l.position
}
// next returns the next rune in the input.
func (l *Lexer) next() rune {
if l.position >= len(l.input) {
l.width = 0
return eof
}
var r rune
r, l.width = utf8.DecodeRuneInString(l.input[l.position:])
l.position += l.width
return r
}
// ignore skips over the pending input before this point.
func (l *Lexer) ignore() {
l.start = l.position
}
// backup steps back one rune.
func (l *Lexer) backup() {
l.position -= 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
}
// isEndingWithString checks whether the current string input part has the
// provided suffix.
func (l *Lexer) isEndingWithString(s string) bool {
return strings.HasSuffix(l.input[l.start:l.position], s)
}
// errorf returns an error token and terminates the scan by passing
// back a nil pointer that will be the next state, terminating l.run.
func (l *Lexer) errorf(format string, args ...interface{}) StateFn {
l.tokens <- *NewToken(ILLEGAL, fmt.Sprintf(format, args...), l.start)
return nil
}
// startLexer starts the Lexer processing.
func startLexer(l *Lexer) StateFn {
r := l.next()
if isWhitespace(r) {
l.ignore()
return startLexer
}
switch r {
case '$':
return lexGlobal
case '\n':
l.lines++
l.emit(NEWLINE)
return startLexer
case '\'':
return lexSingleQuoteString
case '"':
return lexString
case ':':
if p := l.peek(); p == ':' {
l.next()
l.emit(SCOPE)
return startLexer
}
return lexSymbol
case '.':
l.emit(DOT)
return startLexer
case '=':
if l.peek() == '=' {
l.next()
l.emit(EQ)
} else {
l.emit(ASSIGN)
}
return startLexer
case '+':
l.emit(PLUS)
return startLexer
case '-':
l.emit(MINUS)
return startLexer
case '!':
if l.peek() == '=' {
l.next()
l.emit(NOTEQ)
} else {
l.emit(BANG)
}
return startLexer
case '/':
l.emit(SLASH)
return startLexer
case '%':
if l.peek() == 'r' {
l.next()
l.emit(PNREGEXP)
return lexRegexp
}
l.emit(MODULUS)
return startLexer
case '*':
l.emit(ASTERISK)
return startLexer
case '<':
if l.peek() == '<' {
l.next()
if l.peek() == '-' || l.peek() == '~' {
l.next()
l.emit(HEREDOC)
return lexHeredoc
}
}
l.emit(LT)
return startLexer
case '>':
l.emit(GT)
return startLexer
case '(':
l.emit(LPAREN)
return startLexer
case ')':
l.emit(RPAREN)
return startLexer
case '{':
l.emit(LBRACE)
return startLexer
case '}':
l.emit(RBRACE)
return startLexer
case '[':
l.emit(LBRACKET)
return startLexer
case ']':
l.emit(RBRACKET)
return startLexer
case ',':
l.emit(COMMA)
return startLexer
case ';':
l.emit(SEMICOLON)
return startLexer
case eof:
l.emit(EOF)
return startLexer
case '#':
return commentLexer
case '|':
l.emit(PIPE)
return startLexer
default:
if isLetter(r) {
return lexIdentifier
}
if isDigit(r) {
return lexDigit
}
return l.errorf("Illegal character at %d: '%c'", l.start, r)
}
}
// lexIdentifier lexes the identifier.
func lexIdentifier(l *Lexer) StateFn {
legalIdentifierCharacters := []byte{'?', '!'}
r := l.next()
for isLetter(r) || isDigit(r) || bytes.ContainsRune(legalIdentifierCharacters, r) {
r = l.next()
}
l.backup()
literal := l.input[l.start:l.position]
l.emit(LookupIdent(literal))
return startLexer
}
// lexIdentifier lexes the digit.
func lexDigit(l *Lexer) StateFn {
r := l.next()
for isDigitOrUnderscore(r) {
r = l.next()
}
l.backup()
l.emit(INT)
return startLexer
}
// lexSingleQuoteString lexes the single quote string.
func lexSingleQuoteString(l *Lexer) StateFn {
l.ignore()
r := l.next()
for r != '\'' {
// we skip the escape character
if l.peek() == '\'' && r == '\\' {
l.next()
}
r = l.next()
}
l.backup()
l.emit(STRING)
l.next()
l.ignore()
return startLexer
}
// lexString lexes the string.
func lexString(l *Lexer) StateFn {
l.ignore()
r := l.next()
for r != '"' {
// we skip the escape character
if l.peek() == '"' && r == '\\' {
l.next()
}
r = l.next()
}
l.backup()
l.emit(STRING)
l.next()
l.ignore()
return startLexer
}
// lexRegexp lexes the regular expression.
func lexRegexp(l *Lexer) StateFn {
l.ignore()
r := l.next()
l.emit(PNSTART)
pnStart := r
pnEnd := pnStart
switch pnStart {
case '(':
pnEnd = ')'
break
case '[':
pnEnd = ']'
break
case '{':
pnEnd = '}'
break
case '<':
pnEnd = '>'
break
}
for r != pnEnd {
r = l.next()
}
l.backup()
l.emit(REGEXP)
l.next()
l.emit(PNEND)
return startLexer
}
// lexHeredoc lexes the heredoc expression.
func lexHeredoc(l *Lexer) StateFn {
l.ignore()
// HEREDOCSTART
r := l.next()
hdStart := string(r)
for r != '\n' {
r = l.next()
hdStart += string(r)
}
l.backup() // don't add a newline character
l.emit(HEREDOCSTART)
l.start++ // skip newline character
l.next()
for !l.isEndingWithString(hdStart) {
l.next()
}
l.position -= len(hdStart)
s := strings.TrimRightFunc(l.input[l.start:l.position], func(r rune) bool {
if isWhitespace(r) {
return true
}
return false
})
l.tokens <- *NewToken(STRING, s, l.start)
l.start = l.position
for !l.isEndingWithString(hdStart) {
l.next()
}
l.backup()
l.emit(HEREDOCEND)
return startLexer
}
// lexSymbol lexes the symbol.
func lexSymbol(l *Lexer) StateFn {
l.ignore()
r := l.next()
for isLetter(r) || isDigit(r) {
r = l.next()
}
l.backup()
l.emit(SYMBOL)
return startLexer
}
// lexGlobal lexes the global.
func lexGlobal(l *Lexer) StateFn {
r := l.next()
if isExpressionDelimiter(r) {
return l.errorf("Illegal character at %d: '%c'", l.position, r)
}
if isWhitespace(r) {
return l.errorf("Illegal character at %d: '%c'", l.position, r)
}
for !isWhitespace(r) && !isExpressionDelimiter(r) {
r = l.next()
}
l.backup()
l.emit(GLOBAL)
return startLexer
}
// commentLexer lexes the comment.
func commentLexer(l *Lexer) StateFn {
r := l.next()
for r != '\n' {
r = l.next()
}
l.ignore()
return startLexer
}
// isDigit checks whether the specified rune is a whitespace character.
func isWhitespace(r rune) bool {
return unicode.IsSpace(r) && r != '\n'
}
// isDigit checks whether the specified rune is a letter.
func isLetter(r rune) bool {
return 'a' <= r && r <= 'z' || 'A' <= r && r <= 'Z' || r == '_'
}
// isDigit checks whether the specified rune is a digit.
func isDigit(r rune) bool {
return '0' <= r && r <= '9'
}
// isDigitOrUnderscore checks whether the specified rune is a digit or an
// underscore.
func isDigitOrUnderscore(r rune) bool {
return isDigit(r) || r == '_'
}
// isExpressionDelimiter checks whether the specified rune is an expression
// delimiter.
func isExpressionDelimiter(r rune) bool {
return r == '\n' || r == ';' || r == eof
}