-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlexer.go
1527 lines (1373 loc) · 39.6 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
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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package codf // import "go.spiff.io/codf"
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"math/big"
"regexp"
"strconv"
"strings"
"time"
"unicode"
)
// DefaultPrecision is the default precision of TFloat tokens produced by Lexer.
// This can be overridden in the Lexer by setting its Precision field to a non-zero value.
const DefaultPrecision = 80
// ErrUnexpectedEOF is returned by the Lexer when EOF is encountered mid-token where a valid token
// cannot be cut off.
var ErrUnexpectedEOF = errors.New("unexpected EOF")
const eof rune = -1
// TokenKind is an enumeration of the kinds of tokens produced by a Lexer and consumed by a Parser.
type TokenKind uint
func (t TokenKind) String() string {
i := int(t)
if i < 0 || len(tokenNames) <= i {
return "invalid"
}
return tokenNames[t]
}
// Lex-able Token kinds encountered in codf.
const (
tEmpty = TokenKind(iota)
TEOF // !.
// BarewordRune := ![;{}\[\]"'`] Unicode(L,M,N,P,S)
TWhitespace // [ \n\r\t]+
TComment // '//' { !EOL . } ( EOL | EOF )
TWord // BarewordRune {BarewordRune}
TSemicolon // ';'
TCurlOpen // '{'
TCurlClose // '}'
TBracketOpen // '['
TBracketClose // ']'
TMapOpen // '#{'
TRegexp // '#/' { '\\/' | [^/] } '/'
// Strings also include TWord, above, which is an unquoted string.
// Escape := '\\' ( [abfnrtv\\"] | 'x' Hex2 | 'u' Hex4 | 'U' Hex8 | Oct3 )
TString // '"' ( Escape | [^"] )* '"'
TRawString // '`' ( '``' | [^`] )* '`'
// TBoolean is produced by the parser transforming a boolean TWord into a TBoolean with
// a corresponding bool value.
TBoolean // Title/lower/UPPER of: 'true' | 'false' | 'yes' | 'no
// All numbers may begin with '-' (negative) or '+' (positive).
// Numbers without signs are positive.
// Leading zeroes are only permitted on octal numbers or following the 'b', 'x', or '#' of
// a base number. For example, 10#00001 is the integer 1.
TInteger // '0' | [1-9] [0-9]*
TFloat // Integer '.' Integer Exponent? | Integer Exponent
THex // '0' [Xx] [a-fA-F0-9]+
TOctal // '0' [0-7]+
TBinary // '0' [bB] [01]+
TBaseInt // 2-36 '#' [a-zA-Z0-9]+ (corresponding to base)
TDuration // 1m1.033s1h...
TRational // Integer '/' Integer
)
var tokenNames = []string{
tEmpty: "empty",
TEOF: "EOF",
TWhitespace: "whitespace",
TComment: "comment",
TWord: "word",
TSemicolon: "semicolon",
TCurlOpen: "open brace",
TCurlClose: "close brace",
TBracketOpen: "open bracket",
TBracketClose: "close bracket",
TMapOpen: "map",
TRegexp: "regexp",
TString: "string",
TRawString: "raw string",
TBoolean: "bool",
TInteger: "integer",
TFloat: "float",
THex: "hex integer",
TOctal: "octal integer",
TBinary: "binary integer",
TBaseInt: "base integer",
TDuration: "duration",
TRational: "rational",
}
// Token is a token with a kind and a start and end location.
// Start, end, and raw fields are considered metadata and should not be used by a parser except to
// provide information to the user.
//
// Kind is a TokenKind, such as TWord, and Value is the corresponding value of that TokenKind.
// Depending on the Kind, the Token must have a Value of the types described below. For all other
// TokenKinds not in the table below, a Value is not expected.
//
// | Kind | Value Type |
// |-----------+----------------|
// | TWord | string |
// | TString | string |
// | TRegexp | *regexp.Regexp |
// | TBoolean | bool |
// | TFloat | *big.Float |
// | TRational | *big.Rat |
// | TInteger | *big.Int |
// | THex | *big.Int |
// | TOctal | *big.Int |
// | TBinary | *big.Int |
// | TBaseInt | *big.Int |
// | TDuration | time.Duration |
//
type Token struct {
Start, End Location
Kind TokenKind
Raw []byte
Value interface{}
}
// Location describes a location in an input byte sequence.
type Location struct {
Name string // Name is an identifier, usually a file path, for the location.
Offset int // A byte offset into an input sequence. Starts at 0.
Line int // A line number, delimited by '\n'. Starts at 1.
Column int // A column number. Starts at 1.
}
func (l Location) String() string {
pos := strconv.Itoa(l.Line) + ":" + strconv.Itoa(l.Column) + ":" + strconv.Itoa(l.Offset)
if l.Name != "" {
return l.Name + ":" + pos
}
return pos
}
func (l Location) add(r rune, size int) Location {
l.Offset += size
l.Column++
if r == '\n' {
l.Line++
l.Column = 1
}
return l
}
type scanResult struct {
r rune
size int
err error
}
// NamedReader is an optional interface that an io.Reader can implement to provide a name for its
// data source.
type NamedReader interface {
io.Reader
// Name returns a non-empty string identifying the reader's data source. This may be a file,
// URL, resource ID, or some other thing. If the returned string is empty, it will be
// treated as unnamed.
Name() string
}
var noToken Token
// Special lexer runes
const (
rSentinel = ';'
rCurlOpen = '{'
rCurlClose = '}'
rBracketOpen = '['
rBracketClose = ']'
rDoubleQuote = '"'
rBackQuote = '`'
rSpecial = '#'
rComment = '/'
rDot = '.'
rFracSep = '/'
rBaseSep = '#'
rRegexpOpen = '/'
rRegexpClose = '/'
)
// LexerFlag is a bitset representing a combination of zero or more Lex flags, such as LexNoRegexps,
// LexWordLiterals, and others. These Lex flags affect the Lexer's output, allowing one to disable
// specific tokenization behavior.
type LexerFlag uint64
const (
// LexDefaultFlags is the empty flag set (the default).
LexDefaultFlags LexerFlag = 0
// LexWordLiterals treats all literals, other than strings and compounds (maps, arrays) as
// words. This is the union of LexNo* flags.
LexWordLiterals = LexNoRegexps |
LexNoBools |
LexNoDurations |
LexNoRationals |
LexNoFloats |
LexNoBaseInts |
LexNoNumbers
)
const (
// LexNoRegexps disables regular expressions.
LexNoRegexps LexerFlag = 1 << iota
// LexNoBools disables true/false/yes/no parsing.
LexNoBools
// LexNoDurations disables durations.
LexNoDurations
// LexNoRationals disables rationals.
LexNoRationals
// LexNoFloats disables floating point numbers.
LexNoFloats
// LexNoBaseInts disables non-base-10 number forms.
LexNoBaseInts
// LexNoNumbers disables all numbers.
// Implies NoBaseInts, NoFloats, NoRationals, and NoDurations
LexNoNumbers
)
func (f LexerFlag) none(bits LexerFlag) bool {
return f&bits == 0
}
func (f LexerFlag) any(bits LexerFlag) bool {
return f&bits != 0
}
func (f LexerFlag) all(bits LexerFlag) bool {
return f&bits == bits
}
// Lexer takes an input sequence of runes and constructs Tokens from it.
type Lexer struct {
// Precision is the precision used in *big.Float when taking the actual value of a TFloat
// token.
Precision uint
// Name is the name of the token source currently being lexed. It is used to identify the
// source of a location by name. It is not necessarily a filename, but usually is.
//
// If the scanner provided to the Lexer implements NamedScanner, the scanner's name takes
// priority.
Name string
// Flags is a set of Lex flags that can be used to change lexer behavior.
Flags LexerFlag
scanner io.RuneReader
pending bool
lastScan scanResult
lastPos Location
startPos Location
pos Location
next consumerFunc
buf bytes.Buffer
strbuf bytes.Buffer
}
// NewLexer allocates a new Lexer that reads runes from r.
func NewLexer(r io.Reader) *Lexer {
rr := runeReader(r)
le := &Lexer{
Precision: DefaultPrecision,
Flags: LexDefaultFlags,
scanner: rr,
pos: Location{Line: 1, Column: 1},
}
return le
}
type nameRuneReader struct {
*bufio.Reader
namefn func() string
}
func (n nameRuneReader) Name() string {
return n.namefn()
}
func runeReader(r io.Reader) io.RuneReader {
switch r := r.(type) {
case io.RuneReader:
return r
case NamedReader:
return nameRuneReader{bufio.NewReader(r), r.Name}
default:
return bufio.NewReader(r)
}
}
// ReadToken returns a token or an error. If EOF occurs, a TEOF token is returned without an error,
// and will be returned by all subsequent calls to ReadToken.
func (l *Lexer) ReadToken() (tok Token, err error) {
l.reset()
if l.next == nil {
l.next = l.lexSegment
}
if l.pos == (Location{Line: 1, Column: 1}) {
l.pos.Name = l.posName()
}
l.startPos = l.scanPos()
var r rune
for {
r, err = l.readRune()
if err != nil {
return tok, err
}
tok, l.next, err = l.next(r)
if err != nil || tok.Kind != tEmpty {
return tok, err
}
}
}
type convertFunc func(Token) (Token, error)
func (l *Lexer) valueToken(kind TokenKind, convert convertFunc) (tok Token, err error) {
tok = l.token(kind, true)
if convert != nil {
tok, err = convert(tok)
}
return tok, err
}
func (l *Lexer) token(kind TokenKind, takeBuffer bool) Token {
var txt []byte
if buflen := l.buf.Len(); buflen > 0 && takeBuffer {
txt = make([]byte, buflen)
copy(txt, l.buf.Bytes())
} else if takeBuffer {
txt = []byte{}
}
l.buf.Reset()
tok := Token{
Start: l.startPos,
End: l.scanPos(),
Kind: kind,
Raw: txt,
}
if takeBuffer {
tok.Value = l.strbuf.String()
l.strbuf.Reset()
}
return tok
}
func (l *Lexer) readRune() (r rune, err error) {
const invalid rune = '\uFFFD'
if l.pending {
l.pending = false
return l.lastScan.r, l.lastScan.err
}
var size int
l.pos.Name = l.posName()
r, size, err = l.scanner.ReadRune()
if err == io.EOF {
r, size, err = eof, 0, nil
}
res := scanResult{r: r, size: size, err: err}
l.lastScan, l.lastPos = res, l.pos
if size > 0 {
l.pos = l.pos.add(r, size)
}
if r == invalid && err == nil {
err = fmt.Errorf("invalid UTF-8 at %v", l.pos)
}
return
}
func (l *Lexer) posName() string {
if named, ok := l.scanner.(NamedReader); ok {
if name := named.Name(); name != "" {
return name
}
}
return l.Name
}
// unread takes the last-scanned rune and tells the lexer to return it on the next call to readRune.
// This can be used to walk back a single readRune call.
func (l *Lexer) unread() {
if l.pending {
panic("unread() called with pending rune")
}
l.pending = true
}
func (l *Lexer) reset() {
l.buf.Reset()
l.strbuf.Reset()
}
func (l *Lexer) buffer(raw, str rune) {
if raw >= 0 {
l.buf.WriteRune(raw)
}
if str >= 0 {
l.strbuf.WriteRune(str)
}
}
func (l *Lexer) scanPos() Location {
if l.pending {
return l.lastPos
}
return l.pos
}
// Rune cases
var barewordTables = []*unicode.RangeTable{
unicode.L, // Letters
unicode.M, // Marks
unicode.N, // Numbers
unicode.P, // Punctuation
unicode.S, // Symbols
}
// isBarewordRune returns true if r is valid inside of a bareword (but not necessarily if the lexer
// can start a bareword from r initially).
func isBarewordRune(r rune) bool {
return unicode.In(r, barewordTables...) &&
!isBarewordForbidden(r)
}
// isBarewordTransition returns true if r is valid inside of a token that is not a bareword but
// would become one by consuming r.
func isBarewordTransition(r rune) bool {
return unicode.In(r, barewordTables...) &&
!isStatementSep(r)
}
// isBarewordForbidden returns true if r is one of the characters that may not appear in a bareword.
func isBarewordForbidden(r rune) bool {
return isWordSep(r) || unicode.IsControl(r)
}
func isWordSep(r rune) bool {
return unicode.IsSpace(r) ||
r == rSentinel || // End statement
r == rDoubleQuote || // Quoted string
r == rBackQuote // Raw string
}
func isStatementSep(r rune) bool {
return unicode.IsSpace(r) ||
r == rSentinel || // End statement
r == rCurlOpen || // Begin section (in statement)
r == rCurlClose || // Close map (in statement)
r == rBracketOpen || // Open array
r == rBracketClose || // Close array
r == rDoubleQuote || // Quoted string
r == rBackQuote // Raw string
}
func isLongIntervalInitial(r rune) bool {
return r == 'n' || // 'ns'
r == 'u' || // 'us'
r == 'μ' // 'μs'
}
func isIntervalInitial(r rune) bool {
return r == 's' || // 's'
r == 'n' || // 'ns'
r == 'h' || // 'h'
r == 'm' || // 'ms' | 'm'
r == 'u' || // 'us'
r == 'μ' // 'μs'
}
func isMaybeLongIntervalInitial(r rune) bool {
return r == 'm' // 'ms' | 'm'
}
func isSign(r rune) bool {
return r == '-' || r == '+'
}
func isNonZero(r rune) bool {
return r >= '1' && r <= '9'
}
func isDecimal(r rune) bool {
return '0' <= r && r <= '9'
}
func isBinary(r rune) bool {
return r == '0' || r == '1'
}
func isOctal(r rune) bool {
return '0' <= r && r <= '7'
}
func isHex(r rune) bool {
return isDecimal(r) ||
('a' <= r && r <= 'f') ||
('A' <= r && r <= 'F')
}
// Branches
type consumerFunc func(rune) (Token, consumerFunc, error)
func (l *Lexer) lexSpace(r rune, next consumerFunc) consumerFunc {
var spaceConsumer consumerFunc
l.buffer(r, -1)
spaceConsumer = func(r rune) (Token, consumerFunc, error) {
if !unicode.IsSpace(r) {
l.unread()
return l.token(TWhitespace, true), next, nil
}
l.buffer(r, -1)
return noToken, spaceConsumer, nil
}
return spaceConsumer
}
func (l *Lexer) lexCommentStart(next consumerFunc) consumerFunc {
l.buffer(rComment, -1)
return func(r rune) (Token, consumerFunc, error) {
if r != rComment {
l.unread()
return l.lexBecomeWord(-1)
}
return noToken, l.lexComment(next), nil
}
}
func (l *Lexer) lexComment(next consumerFunc) consumerFunc {
var commentConsumer consumerFunc
l.buffer(rComment, -1)
commentConsumer = func(r rune) (Token, consumerFunc, error) {
if r == '\n' || r == eof {
l.unread()
return l.token(TComment, true), next, nil
}
l.buffer(r, r)
return noToken, commentConsumer, nil
}
return commentConsumer
}
func (l *Lexer) lexSegment(r rune) (Token, consumerFunc, error) {
switch {
// EOF
case r == eof:
return l.token(TEOF, false), l.lexSegment, nil
// Whitespace
case unicode.IsSpace(r):
return noToken, l.lexSpace(r, l.lexSegment), nil
// Semicolon
case r == rSentinel:
return l.token(TSemicolon, false), l.lexSegment, nil
// Braces
case r == rCurlOpen:
return l.token(TCurlOpen, false), l.lexSegment, nil
case r == rCurlClose:
return l.token(TCurlClose, false), l.lexSegment, nil
// Brackets
case r == rBracketOpen:
return l.token(TBracketOpen, false), l.lexSegment, nil
case r == rBracketClose:
return l.token(TBracketClose, false), l.lexSegment, nil
// Comment
case r == rComment:
return noToken, l.lexCommentStart(l.lexSegment), nil
// Map / regexp (#// | #{})
case r == rSpecial:
return noToken, l.lexSpecial, nil
}
// Numerics (integer, decimal, rational, duration)
switch {
case l.Flags.any(LexNoNumbers):
case isSign(r):
l.buffer(r, r)
return noToken, l.lexSignedNumber, nil
case r == '0':
l.buffer(r, r)
return noToken, l.lexZero, nil
case isDecimal(r):
l.buffer(r, r)
return noToken, l.lexNonZero, nil
}
// String
switch r {
case rDoubleQuote:
l.buffer(r, -1)
return noToken, l.lexString, nil
case rBackQuote:
l.buffer(r, -1)
return noToken, l.lexRawString, nil
}
// Word
if isBarewordRune(r) {
return l.lexBecomeWord(r)
}
return noToken, nil, fmt.Errorf("unexpected character %q at %v", r, l.pos)
}
func (l *Lexer) lexWordTail(next consumerFunc) consumerFunc {
var wordConsumer consumerFunc
var braces int
wordConsumer = func(r rune) (Token, consumerFunc, error) {
switch {
case r == rCurlOpen || r == rBracketOpen:
braces++
l.buffer(r, r)
return noToken, wordConsumer, nil
case (r == rCurlClose || r == rBracketClose):
if braces <= 0 {
break
}
braces--
fallthrough
case isBarewordRune(r):
l.buffer(r, r)
return noToken, wordConsumer, nil
}
l.unread()
tok := l.token(TWord, true)
tok.Value = string(tok.Raw)
if l.Flags.none(LexNoBools) {
tok = wordToBool(tok)
}
return tok, next, nil
}
return wordConsumer
}
func (l *Lexer) lexBecomeWord(r rune) (Token, consumerFunc, error) {
if r >= 0 {
l.buffer(r, r)
}
return noToken, l.lexWordTail(l.lexSegmentTail), nil
}
func (l *Lexer) lexSegmentTail(r rune) (Token, consumerFunc, error) {
l.unread()
switch {
case r == eof:
return l.token(TEOF, false), nil, nil
case isStatementSep(r):
return noToken, l.lexSegment, nil
}
return noToken, nil, fmt.Errorf("unexpected character %q: expected a name character", r)
}
func (l *Lexer) lexSignedNumber(r rune) (Token, consumerFunc, error) {
switch {
case l.Flags.none(LexNoNumbers) && isDecimal(r):
l.buffer(r, r)
if r == '0' {
return noToken, l.lexZero, nil
}
return noToken, l.lexNonZero, nil
case isStatementSep(r) || r == eof:
l.unread()
return l.lexBecomeWord(-1)
case isBarewordTransition(r):
return l.lexBecomeWord(r)
}
return noToken, nil, fmt.Errorf("unexpected character %q: expected number after sign", r)
}
func parseBaseInt(base int) convertFunc {
return func(t Token) (Token, error) {
var x big.Int
if _, ok := x.SetString(t.Value.(string), base); !ok {
return t, fmt.Errorf("malformed base-%d integer: %q", base, t.Value)
}
t.Value = &x
return t, nil
}
}
func (l *Lexer) lexOctalNumber(r rune) (Token, consumerFunc, error) {
switch {
case isOctal(r):
l.buffer(r, r)
return noToken, l.lexOctalNumber, nil
case isStatementSep(r) || r == eof:
l.unread()
tok, err := l.valueToken(TOctal, parseBaseInt(8))
return tok, l.lexSegment, err
case isBarewordTransition(r):
return l.lexBecomeWord(r)
}
return noToken, nil, fmt.Errorf("unexpected character %q: expected octal digit or separator", r)
}
func (l *Lexer) lexNoTerminate(next consumerFunc, expect string) consumerFunc {
return func(r rune) (Token, consumerFunc, error) {
switch {
case r == eof:
return noToken, l.lexNoTerminate(next, expect), fmt.Errorf("expected %s: %v", expect, ErrUnexpectedEOF)
case isStatementSep(r):
return noToken, nil, fmt.Errorf("unexpected character %q: expect %s", r, expect)
}
return next(r)
}
}
func (l *Lexer) lexHexNum(r rune) (Token, consumerFunc, error) {
switch {
case isHex(r):
l.buffer(r, r)
return noToken, l.lexHexNum, nil
case isStatementSep(r) || r == eof:
l.unread()
tok, err := l.valueToken(THex, parseBaseInt(16))
return tok, l.lexSegment, err
case isBarewordTransition(r):
return l.lexBecomeWord(r)
}
return noToken, nil, fmt.Errorf("unexpected character %q: expected hex digit or separator", r)
}
func (l *Lexer) lexBinNum(r rune) (Token, consumerFunc, error) {
switch {
case isBinary(r):
l.buffer(r, r)
return noToken, l.lexBinNum, nil
case isStatementSep(r) || r == eof:
l.unread()
tok, err := l.valueToken(TBinary, parseBaseInt(2))
return tok, l.lexSegment, err
case isBarewordTransition(r):
return l.lexBecomeWord(r)
}
return noToken, nil, fmt.Errorf("unexpected character %q: expected binary digit or separator", r)
}
func parseRational(t Token) (Token, error) {
var x big.Rat
text := t.Value.(string)
if _, ok := x.SetString(text); !ok {
return t, fmt.Errorf("malformed rational %q", text)
}
t.Value = &x
return t, nil
}
func (l *Lexer) lexRationalDenomInitial(r rune) (Token, consumerFunc, error) {
switch {
case isNonZero(r):
l.buffer(r, r)
return noToken, l.lexRationalDenomTail, nil
case isStatementSep(r) || r == eof:
l.unread()
return l.lexBecomeWord(-1)
case isBarewordTransition(r):
return l.lexBecomeWord(r)
}
return noToken, nil, fmt.Errorf("unexpected character %q: expected positive number", r)
}
func (l *Lexer) lexRationalDenomTail(r rune) (Token, consumerFunc, error) {
switch {
case isDecimal(r):
l.buffer(r, r)
return noToken, l.lexRationalDenomTail, nil
case isBarewordTransition(r):
return l.lexBecomeWord(r)
case isStatementSep(r) || r == eof:
l.unread()
tok, err := l.valueToken(TRational, parseRational)
return tok, l.lexSegment, err
}
return noToken, nil, fmt.Errorf("unexpected character %q: expected rational number", r)
}
func parseBigFloat(prec uint) convertFunc {
if prec == 0 {
prec = DefaultPrecision
}
return func(tok Token) (Token, error) {
var f big.Float
f.SetPrec(prec)
text := tok.Value.(string)
if _, ok := f.SetString(text); !ok {
return tok, fmt.Errorf("malformed decimal %q", text)
}
tok.Value = &f
return tok, nil
}
}
func (l *Lexer) lexFloatExponentUnsigned(r rune) (Token, consumerFunc, error) {
//
// Occurs after an 'e' or 'E', indicating that a float has an exponent. This is before any
// digit of the exponent has been consumed.
//
// '0' -> lex decimal end
// [1-9] -> lex signed tail (implicit positive sign)
// '-' | '+' -> lex signed initial (explicit sign, no digit)
// Sep -> Bareword
// BarewordRune -> lex bareword
//
switch {
case r == '0': // End of float
l.buffer(r, r)
return noToken, l.lexFloatEnd, nil
case isDecimal(r):
l.buffer(r, r)
return noToken, l.lexFloatExponentSignedTail, nil
case isSign(r):
l.buffer(r, r)
return noToken, l.lexFloatExponentSignedInitial, nil
case r == eof || isStatementSep(r):
l.unread()
return l.lexBecomeWord(-1)
case isBarewordTransition(r):
return l.lexBecomeWord(r)
}
return noToken, nil, fmt.Errorf("unexpected character %q: expected sign or digit", r)
}
func (l *Lexer) lexFloatExponentSignedTail(r rune) (Token, consumerFunc, error) {
//
// Occurs in the middle of a signed float exponent (meaning either implicitly or explicitly
// signed).
//
switch {
case isDecimal(r):
l.buffer(r, r)
return noToken, l.lexFloatExponentSignedTail, nil
case isStatementSep(r) || r == eof:
l.unread()
tok, err := l.valueToken(TFloat, parseBigFloat(l.Precision))
return tok, l.lexSegment, err
case isBarewordTransition(r):
return l.lexBecomeWord(r)
}
return noToken, nil, fmt.Errorf("unexpected character %q: expected digit or separator", r)
}
func (l *Lexer) lexFloatExponentSignedInitial(r rune) (Token, consumerFunc, error) {
//
// Occurs after an '-' or '+' in a float's exponent.
//
// '0' -> lex decimal end
// Sep -> Bareword
// _ -> lex decimal exponent signed tail
//
if r == '0' {
l.buffer(r, r)
return noToken, l.lexFloatEnd, nil
} else if isStatementSep(r) || r == eof {
l.unread()
return l.lexBecomeWord(-1)
}
return l.lexFloatExponentSignedTail(r)
}
func (l *Lexer) lexFloatEnd(r rune) (Token, consumerFunc, error) {
//
// Occurs after a '0' in an exponent, indicating that the number must necessarily end. If
// r is not a separator and is a valid bareword rune, it becomes a bareword.
//
// Sep -> Float
// BarewordRune -> lex bareword
//
// Any other character following 1e0 is invalid (e.g., the string "1e0\x00" cannot be
// lexed).
//
switch {
case r == eof || isStatementSep(r):
l.unread()
tok, err := l.valueToken(TFloat, parseBigFloat(l.Precision))
return tok, l.lexSegment, err
case isBarewordTransition(r):
return l.lexBecomeWord(r)
}
return noToken, nil, fmt.Errorf("unexpected character %q: expected separator", r)
}
func (l *Lexer) lexFloatPointInitial(r rune) (Token, consumerFunc, error) {
//
// Occurs after a '.' while lexing an integer -- the token is lexed as a float from then on.
//
// [0-9] -> lex decimal point
// Sep -> Bareword
// BarewordRune -> lex bareword
//
switch {
case isDecimal(r):
case r == eof || isStatementSep(r):
l.unread()
return l.lexBecomeWord(-1)
case isBarewordTransition(r):
return l.lexBecomeWord(r)
}
return l.lexFloatPoint(r)
}
func (l *Lexer) lexFloatPoint(r rune) (Token, consumerFunc, error) {
//
// Occurs after a '.' and at least one digit while lexing an integer -- the token is lexed
// as a float from then on.
//
// [Ee] -> lex float from exponent
// IntervalUnit -> lex interval unit (lexed as interval from then on)
// [0-9] -> continue
// Sep -> Float
// BarewordRune -> lex bareword
//
var (
allowFloat = l.Flags.none(LexNoFloats)
allowDurations = l.Flags.none(LexNoDurations)
)
switch {
case allowFloat && (r == 'E' || r == 'e'): // exponent
l.buffer(r, r)
return noToken, l.lexFloatExponentUnsigned, nil
case allowDurations && isIntervalInitial(r):
return l.lexIntervalConsumer(r)
case isDecimal(r):
l.buffer(r, r)
return noToken, l.lexFloatPoint, nil
case isStatementSep(r) || r == eof:
l.unread()
if !allowFloat {
return l.lexBecomeWord(-1)
}
tok, err := l.valueToken(TFloat, parseBigFloat(l.Precision))
return tok, l.lexSegment, err
case isBarewordTransition(r):
return l.lexBecomeWord(r)
}
return noToken, nil, fmt.Errorf("unexpected character %q: expected digit, exponent, or separator", r)
}
func parseDuration(tok Token) (Token, error) {
text := tok.Value.(string)
d, err := time.ParseDuration(text)
if err != nil {
return tok, fmt.Errorf("malformed duration %q: %v", text, err)
}
tok.Value = d
return tok, nil
}
// lexIntervalConsumer returns the next consumerFunc for a given interval unit, depending on whether
// the unit is necessarily long (two runes), maybe long (one to two runes), or short (one rune).
func (l *Lexer) lexIntervalConsumer(r rune) (Token, consumerFunc, error) {
l.buffer(r, r)
if isLongIntervalInitial(r) {
return noToken, l.lexIntervalUnitLong, nil
} else if isMaybeLongIntervalInitial(r) {