This repository has been archived by the owner on Aug 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
scanner.go
660 lines (619 loc) · 12.4 KB
/
scanner.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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
package goal
import (
"bytes"
"fmt"
"io"
"strings"
)
// Token represents a token information.
type Token struct {
Type TokenType // token type
Pos int // token's offset in the source
Text string // content text (identifier, string, number)
}
func (t Token) String() string {
switch t.Type {
case ADVERB, ERROR, IDENT, DYAD, NUMBER, REGEXP, QQSTART, QQEND, SADVERB:
return fmt.Sprintf("{%s %s}", t.Type.String(), t.Text)
case LEFTBRACE:
return "{"
case LEFTBRACKET, LEFTBRACKETS:
return "["
case LEFTPAREN:
return "("
case RIGHTBRACE:
return "}"
case RIGHTBRACKET:
return "]"
case RIGHTPAREN:
return ")"
case SEMICOLON:
return ";"
case STRING:
return "\"" + t.Text + "\""
default:
return t.Type.String()
}
}
// TokenType represents the different kinds of tokens.
type TokenType int
// These constants describe the possible kinds of tokens.
const (
NONE TokenType = iota
EOF
ERROR
ADVERB
DYAD
DYADASSIGN
IDENT
LEFTBRACE
LEFTBRACKET
LEFTBRACKETS
LEFTPAREN
NEWLINE
NUMBER
MONAD
REGEXP
RIGHTBRACE
RIGHTBRACKET
RIGHTPAREN
SEMICOLON
SADVERB
STRING
QQSTART
QQEND
)
// IdentType represents the different kinds of special roles for alphanumeric
// identifiers that act as keywords.
type IdentType int
// These constants represent the different kinds of special names.
const (
IdentVar IdentType = iota // a normal identifier (default zero value)
IdentMonad // a builtin monad (cannot have left argument)
IdentDyad // a builtin dyad (can have left argument)
)
// Scanner represents the state of the scanner.
type Scanner struct {
names map[string]IdentType // special keywords
reader *strings.Reader // rune reader
buf *bytes.Buffer // buffer for building strings
err error // scanning error (if any)
npos int // position of next rune in the input
epos int // next token end position
tpos int // next token start position
psize int // size of last peeked rune
pr rune // peeked rune
r rune // current rune
exprEnd bool // at expression start
delimOp bool // at list start
peeked bool // peeked next
start bool // at line start
token Token // last token
source string // source string
state stateFn // starting state for Next
qr rune // quote closing rune
}
type stateFn func(*Scanner) stateFn
// NewScanner returns a scanner for the given source string.
func NewScanner(names map[string]IdentType, source string) *Scanner {
s := &Scanner{names: names}
s.source = source
s.reader = strings.NewReader(source)
s.buf = &bytes.Buffer{}
s.start = true
s.state = scanAny
s.next()
return s
}
// Next produces the next token from the input reader.
func (s *Scanner) Next() Token {
state := s.state
for {
state = state(s)
if state == nil {
return s.token
}
}
}
const eof = -1
func (s *Scanner) peek() rune {
if s.peeked {
return s.pr
}
r, size, err := s.reader.ReadRune()
if err != nil {
if err != io.EOF {
s.err = err
}
r = eof
}
s.peeked = true
s.pr = r
s.psize = size
return s.pr
}
func (s *Scanner) next() {
if s.peeked {
s.peeked = false
s.r = s.pr
s.epos = s.npos
s.npos += s.psize
return
}
r, sz, err := s.reader.ReadRune()
s.r = r
s.epos = s.npos
s.npos += sz
if err != nil {
if err != io.EOF {
s.err = err
}
s.r = eof
}
//fmt.Printf("[%c]", r)
}
func (s *Scanner) emit(t TokenType) stateFn {
s.token = Token{Type: t, Pos: s.tpos}
s.start = t == NEWLINE
s.delimOp = t == LEFTPAREN || t == LEFTBRACKET || t == LEFTBRACE || t == LEFTBRACKETS
switch t {
case LEFTBRACE, LEFTBRACKET, LEFTBRACKETS, LEFTPAREN, NEWLINE, SEMICOLON, EOF:
// all of these don't have additional content, so we don't do
// this test in the other emits.
s.exprEnd = false
default:
s.exprEnd = true
}
return nil
}
func (s *Scanner) emitError(err string) stateFn {
s.token = Token{Type: ERROR, Pos: s.tpos, Text: err}
return nil
}
func (s *Scanner) emitString(t TokenType) stateFn {
s.token = Token{Type: t, Pos: s.tpos, Text: s.source[s.tpos:s.epos]}
s.start = false
s.delimOp = false
s.exprEnd = true
return nil
}
func (s *Scanner) emitRegexp(text string) stateFn {
s.token = Token{Type: REGEXP, Pos: s.tpos, Text: text}
s.start = false
s.delimOp = false
s.exprEnd = true
return nil
}
func (s *Scanner) emitNewString(t TokenType, text string) stateFn {
s.token = Token{Type: t, Pos: s.tpos, Text: text}
s.start = false
s.delimOp = false
s.exprEnd = true
return nil
}
func (s *Scanner) emitSpecial(r rune) stateFn {
s.token = Token{Type: SADVERB, Pos: s.tpos, Text: string(r)}
s.start = false
s.delimOp = true
s.exprEnd = false
return nil
}
func (s *Scanner) emitIDENT() stateFn {
if s.tpos == s.epos {
return s.emitError("empty identifier")
}
switch s.names[s.source[s.tpos:s.epos]] {
case IdentDyad:
return s.emitOp(DYAD)
case IdentMonad:
return s.emitOp(MONAD)
default:
return s.emitString(IDENT)
}
}
func (s *Scanner) emitOp(t TokenType) stateFn {
s.token = Token{Type: t, Pos: s.tpos, Text: s.source[s.tpos:s.epos]}
s.start = false
s.delimOp = false
s.exprEnd = false
return nil
}
func (s *Scanner) emitEOF() stateFn {
if s.err != nil {
return s.emitError(s.err.Error())
}
return s.emit(EOF)
}
func scanAny(s *Scanner) stateFn {
s.tpos = s.epos
switch s.r {
case eof:
return s.emitEOF()
case '\n':
s.next()
if !s.start {
if !s.delimOp {
return s.emit(NEWLINE)
}
s.start = true
}
return scanAny
case ' ', '\t', '\r':
return scanSpace
case '/':
if s.start {
return scanCommentLine
}
s.next()
return s.emitOp(ADVERB)
case '\'', '\\':
s.next()
return s.emitOp(ADVERB)
case '{':
s.next()
return s.emit(LEFTBRACE)
case '[':
s.next()
return s.emit(LEFTBRACKET)
case '(':
s.next()
return s.emit(LEFTPAREN)
case '}':
s.next()
return s.emit(RIGHTBRACE)
case ']':
s.next()
return s.emit(RIGHTBRACKET)
case ')':
s.next()
return s.emit(RIGHTPAREN)
case ';':
s.next()
return s.emit(SEMICOLON)
case '-':
if !s.exprEnd {
return scanMinus
}
return scanDyadOp
case ':':
s.next()
if s.r == ':' {
s.next()
}
return s.emitOp(DYAD)
case '+', '*', '%', '!', '&', '|', '<', '>',
'=', '~', ',', '^', '#', '_', '$', '?', '@', '.', '»', '«', '¿':
return scanDyadOp
case '"':
s.qr = s.r
s.state = scanQQ
s.next()
return s.emit(QQSTART)
case '`':
return scanBackQuotedString
}
switch {
case isDigit(s.r):
return scanNumber
case isAlpha(s.r):
return scanIdent
default:
return s.emitError(fmt.Sprintf("unexpected character: %q", s.r))
}
}
func isDigit(r rune) bool {
return r >= '0' && r <= '9'
}
func isAlpha(r rune) bool {
return r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z'
}
func isAlphaNum(r rune) bool {
return isAlpha(r) || isDigit(r)
}
func scanDyadOp(s *Scanner) stateFn {
s.next()
if s.r == ':' {
s.next()
if s.r == ':' {
s.next()
}
return s.emitOp(DYADASSIGN)
}
return s.emitOp(DYAD)
}
func scanSpace(s *Scanner) stateFn {
for {
s.next()
switch s.r {
case '/':
return scanComment
case ' ', '\t', '\r':
case '-':
s.tpos = s.epos
return scanMinus
case '[':
s.tpos = s.epos
s.next()
return s.emit(LEFTBRACKETS)
case '\'', '\\':
s.tpos = s.epos
rs := s.emitSpecial(s.r)
s.next()
return rs
default:
return scanAny
}
}
}
func scanComment(s *Scanner) stateFn {
for {
s.next()
switch s.r {
case eof:
return s.emitEOF()
case '\n':
s.next()
if !s.start {
if !s.delimOp {
return s.emit(NEWLINE)
}
s.start = true
}
return scanAny
}
}
}
func scanCommentLine(s *Scanner) stateFn {
s.next()
if s.r == '\n' {
return scanMultiLineComment
}
return scanComment
}
func scanMultiLineComment(s *Scanner) stateFn {
for {
s.next()
switch {
case s.r == eof:
return s.emitEOF()
case s.r == '\\' && s.start:
s.next()
if s.r == '\n' {
s.next()
return scanAny
}
}
}
}
func scanBackQuotedString(s *Scanner) stateFn {
for {
s.next()
switch s.r {
case eof:
return s.emitError("non terminated string: unexpected EOF")
case '`':
s.next()
return s.emitString(STRING)
}
}
}
func scanRawString(s *Scanner) stateFn {
s.buf.Reset()
s.buf.WriteByte('"')
for {
s.next()
switch s.r {
case eof:
return s.emitError("non terminated string: unexpected EOF")
case '\n':
s.buf.WriteString(`\n`)
case '"':
s.buf.WriteString(`\"`)
case '\\':
s.buf.WriteString(`\\`)
case s.qr:
if s.peek() == s.qr {
s.next()
s.buf.WriteRune(s.r)
break
}
s.buf.WriteString(`"`)
s.next()
return s.emitNewString(STRING, s.buf.String())
default:
s.buf.WriteRune(s.r)
}
}
}
func scanRegexp(s *Scanner) stateFn {
s.buf.Reset()
for {
s.next()
switch s.r {
case eof:
return s.emitError("non terminated rx/PATTERN/: unexpected EOF")
case '\\':
nr := s.peek()
if nr == s.qr {
s.next()
} else if nr == '\\' {
s.next()
s.buf.WriteRune(nr)
}
s.buf.WriteRune(s.r)
case s.qr:
s.next()
return s.emitRegexp(s.buf.String())
default:
s.buf.WriteRune(s.r)
}
}
}
func scanNumber(s *Scanner) stateFn {
for {
s.next()
switch {
case s.r == eof:
return s.emitString(NUMBER)
case s.r == '.':
case s.r == 'e' || s.r == 'E' ||
s.r == 'p' || s.r == 'P':
r := s.peek()
if r == '+' || r == '-' {
s.next()
return scanExponent
}
case !isAlphaNum(s.r):
return s.emitString(NUMBER)
}
}
}
func scanExponent(s *Scanner) stateFn {
for {
s.next()
switch {
case s.r == eof:
return s.emitString(NUMBER)
case !isDigit(s.r):
return s.emitString(NUMBER)
}
}
}
func scanMinus(s *Scanner) stateFn {
s.next()
if isDigit(s.r) {
return scanNumber
}
return s.emitOp(DYAD)
}
func scanIdent(s *Scanner) stateFn {
dots := 0
const delimchars = ":+-*%!&|=~,^#_?@/'"
for {
s.next()
switch {
case s.r == eof:
return s.emitIDENT()
case isAlphaNum(s.r):
case s.r == '.':
r := s.peek()
if !isAlpha(r) {
return s.emitIDENT()
}
if dots > 0 {
return s.emitError("too many dots in identifier")
}
dots++
case s.source[s.tpos:s.epos] == "qq":
if strings.ContainsRune(delimchars, s.r) {
s.qr = s.r
s.state = scanQQ
s.next()
return s.emit(QQSTART)
}
return s.emitIDENT()
case s.source[s.tpos:s.epos] == "rq":
if strings.ContainsRune(delimchars, s.r) {
s.qr = s.r
return scanRawString
}
return s.emitIDENT()
case s.source[s.tpos:s.epos] == "rx":
if strings.ContainsRune(delimchars, s.r) {
s.qr = s.r
return scanRegexp
}
return s.emitIDENT()
default:
return s.emitIDENT()
}
}
}
func scanQQ(s *Scanner) stateFn {
s.tpos = s.epos
switch s.r {
case eof:
return s.emitError("non terminated string: unexpected EOF")
case s.qr:
s.state = scanAny
s.next()
return s.emit(QQEND)
case '$':
s.tpos++
return scanQQIdent(s)
default:
s.buf.Reset()
s.buf.WriteByte('"')
for {
switch s.r {
case eof:
return s.emitError("non terminated string: unexpected EOF")
case '\n':
s.buf.WriteString(`\n`)
case '\\':
nr := s.peek()
switch {
case nr == '\\' || nr == '"' && s.qr == '"':
s.buf.WriteByte('\\')
s.buf.WriteRune(nr)
s.next()
case nr == s.qr || nr == '$':
s.buf.WriteRune(nr)
s.next()
case nr == '\n':
default:
s.buf.WriteRune(s.r)
}
case s.qr:
s.buf.WriteByte('"')
return s.emitNewString(STRING, s.buf.String())
case '"':
s.buf.WriteString(`\"`)
case '$':
s.buf.WriteByte('"')
return s.emitNewString(STRING, s.buf.String())
default:
s.buf.WriteRune(s.r)
}
s.next()
}
}
}
func scanQQIdent(s *Scanner) stateFn {
dots := 0
braced := false
if s.peek() == '{' {
s.next()
s.tpos++
braced = true
}
for {
s.next()
switch {
case s.r == eof:
if braced {
return s.emitError("interpolation ${ without closing }")
}
return s.emitIDENT()
case s.r == '.':
r := s.peek()
if !isAlpha(r) && !braced {
return s.emitIDENT()
}
if dots > 0 {
return s.emitError("too many dots in identifier")
}
dots++
case isAlphaNum(s.r):
case braced && s.r == '}':
f := s.emitIDENT()
s.next()
return f
default:
if braced {
return s.emitError("invalid char in ${IDENT}")
}
return s.emitIDENT()
}
}
}