-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlex.go
543 lines (497 loc) · 10.5 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
541
542
543
package kdl
import (
"bufio"
"errors"
"fmt"
"io"
"strings"
)
const (
newlineChars = "\x0D\x0A\x85\x0C\u2028\u2029"
spaceChars = "\t \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000"
)
func identifierCharacter(r rune) bool {
if r < 0x20 || r > 0x10FFFF {
return false
}
if space(r) || newline(r) {
return false
}
const excluded = `\/<>{};=,"`
for _, e := range excluded {
if r == e {
return false
}
}
return true
}
func digit(r rune) bool {
return r >= '0' && r <= '9'
}
func numberStart(r rune) bool {
return digit(r) || r == '+' || r == '-'
}
func identifierStart(r rune) bool {
return identifierCharacter(r) && !digit(r)
}
func newline(r rune) bool {
return strings.IndexRune(newlineChars, r) >= 0
}
func space(r rune) bool {
return strings.IndexRune(spaceChars, r) >= 0
}
//go:generate stringer -type=tokenType -trimprefix=tok
type tokenType int
const (
tokEOF tokenType = iota
tokErr
tokInt
tokFloat
tokNewline
tokIgnoreNode
tokSpace
tokIdentifier
tokString
tokEqual
tokOpenBracket
tokCloseBracket
tokSemicolon
)
type token struct {
typ tokenType
err error // for tokErr
str string // for tokIdentifier, tokString, tokInt, tokFloat
}
func (t token) String() string {
switch t.typ {
case tokErr:
return fmt.Sprintf("%s (%s)", t.typ, t.err)
case tokIdentifier, tokString, tokInt, tokFloat:
return fmt.Sprintf("%s (%q)", t.typ, t.str)
default:
return t.typ.String()
}
}
type lexer struct {
tokens chan token
close chan struct{} // closed by Close
r *bufio.Reader
rs []rune
// TODO: will we ever need to peek >1 rune? If not, can save some
// array nonsense here.
peekrs []rune // if non-zero, un-next()-ed runes in reverse order (last first)
atEOF bool // flips once to true when lexer finds EOF
lastWasSpace bool // last emitted token was a tokSpace
}
func NewLexer(r io.Reader) *lexer {
var br *bufio.Reader
if sr, ok := r.(*bufio.Reader); ok {
br = sr
} else {
br = bufio.NewReader(r)
}
ret := &lexer{
tokens: make(chan token),
close: make(chan struct{}),
r: br,
rs: make([]rune, 0, 1024),
}
go ret.lex()
return ret
}
func (l *lexer) Next() token {
// Handily, when the channel is closed, the zero value is
// returned, whose typ is tokEOF. So, we EOF for ever once
// closed.
return <-l.tokens
}
var lexClosed = errors.New("lexer closed")
func (l *lexer) emit(t token) {
if t.typ == tokSpace && l.lastWasSpace {
l.ignore()
return
}
l.lastWasSpace = t.typ == tokSpace
select {
case l.tokens <- t:
l.rs = l.rs[:0]
case <-l.close:
// Will get recovered at the top level of lex()
panic(lexClosed)
}
}
func (l *lexer) err(format string, args ...interface{}) lexFn {
l.lastWasSpace = false
select {
case l.tokens <- token{typ: tokErr, err: fmt.Errorf(format, args...)}:
case <-l.close:
panic(lexClosed)
}
return nil // Will break out of the top-level lex loop and clean up.
}
const eof = -1 // outside the valid range for unicode codepoints
func (l *lexer) next() (r rune) {
if len(l.peekrs) > 0 {
l.rs = append(l.rs, l.peekrs[len(l.peekrs)-1])
l.peekrs = l.peekrs[:len(l.peekrs)-1]
return l.last()
}
if l.atEOF {
return eof
}
r, _, err := l.r.ReadRune()
if err == io.EOF {
l.atEOF = true
return eof
} else if err != nil {
// TODO: something else?
l.atEOF = true
return eof
}
l.rs = append(l.rs, r)
return r
}
func (l *lexer) backup() {
if l.atEOF {
// "backing up" from EOF is meaningless, therefore do nothing.
return
}
if len(l.rs) == 0 {
panic("cannot backup with nothing buffered")
}
l.peekrs = append(l.peekrs, l.rs[len(l.rs)-1])
l.rs = l.rs[:len(l.rs)-1]
}
func (l *lexer) peek() rune {
r := l.next()
l.backup()
return r
}
// returns last consumed rune
func (l *lexer) last() rune {
if len(l.rs) == 0 {
return -1
}
return l.rs[len(l.rs)-1]
}
func (l *lexer) ignore() {
l.rs = l.rs[:0]
}
func (l *lexer) accept(valid string) bool {
if strings.IndexRune(valid, l.next()) >= 0 {
return true
}
l.backup()
return false
}
func (l *lexer) acceptNewline() bool {
r := l.next()
switch {
case r == eof:
return false
case r == '\r':
if l.peek() == '\n' {
l.next()
}
return true
case newline(r):
return true
default:
return false
}
}
func (l *lexer) acceptRun(valid string) {
for strings.IndexRune(valid, l.next()) >= 0 {
}
l.backup()
}
// until consumes runes until it encounters a rune in invalid, or
// EOF. Returns whether the read was interrupted by EOF or invalid
// characters.
func (l *lexer) until(invalid string) (notEOF bool) {
for strings.IndexRune(invalid, l.peek()) < 0 && l.peek() != eof {
l.next()
}
if l.peek() == eof {
return false
}
return true
}
type lexFn func() lexFn
func (l *lexer) lex() {
defer func() {
close(l.tokens)
if r := recover(); r != nil {
if r != lexClosed {
panic(r)
}
}
}()
for st := l.lexAny; st != nil; {
st = st()
}
}
func (l *lexer) lexAny() lexFn {
r := l.peek()
switch {
case r == eof:
return nil
case numberStart(r):
return l.lexNumber
case identifierStart(r):
return l.lexIdentifier
case r == '"':
return l.lexString
case r == '=':
l.next()
l.emit(token{typ: tokEqual})
return l.lexAny
case r == '{':
l.next()
l.emit(token{typ: tokOpenBracket})
return l.lexAny
case r == '}':
l.next()
l.emit(token{typ: tokCloseBracket})
return l.lexAny
case r == ';':
l.next()
l.emit(token{typ: tokSemicolon})
return l.lexAny
case r == '/':
return l.lexComment
case space(r):
return l.lexSpace
case newline(r):
return l.lexNewline
default:
return l.err("don't know how to lex %q", r)
}
}
func (l *lexer) lexNumber() lexFn {
l.accept("+-")
if l.last() == '+' && !digit(l.peek()) {
// Woops, this is an identifier, not a number.
return l.lexIdentifier
}
if l.accept("0") {
// Could be a radix prefix, with simpler parsing rules.
switch l.next() {
case eof:
l.emit(token{typ: tokInt, str: string(l.rs)})
return nil
case 'x':
l.acceptRun("0123456789abcdefABCDEF_")
l.emit(token{typ: tokInt, str: string(l.rs)})
return l.lexSpace
case 'b':
l.acceptRun("01_")
l.emit(token{typ: tokInt, str: string(l.rs)})
return l.lexSpace
case 'o':
l.acceptRun("01234567_")
l.emit(token{typ: tokInt, str: string(l.rs)})
return l.lexSpace
default:
l.backup()
}
}
// Full decimal/float.
fl := false
const digits = "0123456789_"
l.acceptRun(digits)
if l.accept(".") {
fl = true
l.acceptRun(digits)
}
if l.accept("eE") {
l.accept("+-")
l.acceptRun(digits)
}
if fl {
l.emit(token{typ: tokFloat, str: string(l.rs)})
} else {
l.emit(token{typ: tokInt, str: string(l.rs)})
}
return l.lexSpace
}
func (l *lexer) lexComment() lexFn {
if l.next() != '/' {
panic("how did we end up in lexComment without a slash?!")
}
r := l.next()
switch r {
case '/':
if !l.until(newlineChars) {
return nil
}
l.ignore()
return l.lexNewline
case '*':
for depth := 1; depth > 0; {
if !l.until("*/") {
return l.err("EOF during multiline comment")
}
switch l.next() {
case '*':
if l.peek() != '/' {
continue
}
l.next()
depth--
case '/':
if l.peek() != '*' {
continue
}
l.next()
depth++
}
}
l.ignore()
return l.lexSpace
case '-':
l.emit(token{typ: tokIgnoreNode})
return l.lexSpace
default:
return l.err("unknown kind of comment \"/%s\"", string(r))
}
}
func (l *lexer) lexIdentifier() lexFn {
if l.accept("r") {
if r := l.peek(); r == '#' || r == '"' {
// Woops, this is a raw string.
return l.lexRawString
}
} else if r := l.next(); !identifierStart(r) {
return l.err("unexpected rune %q at start of identifier", r)
}
for identifierCharacter(l.next()) {
}
l.backup()
l.emit(token{typ: tokIdentifier, str: string(l.rs)})
return l.lexAny
}
func (l *lexer) lexString() lexFn {
l.accept(`"`)
for {
if !l.until(`"\\`) {
return l.err("EOF during string")
}
switch l.next() {
case '"':
l.emit(token{typ: tokString, str: string(l.rs[1 : len(l.rs)-1])})
return l.lexAny
case '\\':
replacePoint := len(l.rs) - 1 // position of the \
replace := rune(eof)
r := l.next()
switch r {
case 'n':
replace = '\n'
case 'r':
replace = '\r'
case 't':
replace = '\t'
case '\\':
replace = '\\'
case '/':
replace = '/'
case '"':
replace = '"'
case 'b':
replace = '\b'
case 'f':
replace = '\f'
case 'u':
if l.next() != '{' {
return l.err("expected open bracket after \\u, got %q", string(r))
}
replace = 0
parseHex:
for i := 0; i < 6; i++ {
r = l.next()
switch {
case r >= '0' && r <= '9':
replace = (replace << 4) + (r - '0')
case r >= 'a' && r <= 'f':
replace = (replace << 4) + (r - 'a' + 10)
case r >= 'A' && r <= 'F':
replace = (replace << 4) + (r - 'A' + 10)
case r == '}':
if i == 0 {
return l.err("no hex in \\u escape sequence")
}
break parseHex
default:
return l.err("unexpected hex in \\u escape sequence, got %q", string(r))
}
}
default:
return l.err("unknown escape sequence \\%s", string(r))
}
l.rs = append(l.rs[:replacePoint], replace)
}
}
}
func (l *lexer) lexRawString() lexFn {
// Leading 'r' was accepted prior to entering this lex state.
hashes := 0
for l.next() == '#' {
hashes++
}
if l.last() != '"' {
return l.err("expected dquote, got %q", l.last())
}
findEnd:
for {
if !l.until(`"`) {
return l.err("EOF in raw string")
}
l.accept(`"`)
for i := 0; i < hashes; i++ {
if !l.accept("#") {
// Turns out this wasn't the end of the string after all.
continue findEnd
}
}
l.emit(token{typ: tokString, str: string(l.rs[hashes+2 : len(l.rs)-hashes-1])})
return l.lexAny
}
}
func (l *lexer) lexSpace() lexFn {
if !l.accept(spaceChars) {
return l.lexAny
}
l.acceptRun(spaceChars)
switch l.peek() {
case eof:
l.emit(token{typ: tokSpace})
return nil
case '\\':
l.next() // TODO: check if there _must_ be at least one space, currently accept zero.
l.acceptRun(spaceChars)
if l.peek() == '/' {
l.next()
if r := l.peek(); r != '/' {
return l.err("unexpected rune %q in newline continuation", r)
}
if !l.until(newlineChars) {
return nil
}
}
if !l.acceptNewline() {
return l.err("unexpected rune %q in newline continuation", l.peek())
}
return l.lexSpace
default:
l.emit(token{typ: tokSpace})
return l.lexAny
}
}
func (l *lexer) lexNewline() lexFn {
if !l.acceptNewline() {
l.err("tried to lex newline when not at newline")
}
l.emit(token{typ: tokNewline})
return l.lexAny
}