/
lexer.go
3329 lines (3049 loc) · 81.7 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 Lex is a Lexer for QLBridge which is more of a lex-toolkit and
// implements 4 Dialects {SQL, FilterQL, Json, Expressions}.
package lex
import (
"bytes"
"fmt"
"os"
"strings"
"unicode"
"unicode/utf8"
u "github.com/araddon/gou"
)
var (
// Trace is a global var to turn on tracing. can be turned out with env
// variable "lextrace=true"
//
// export lextrace=true
Trace bool
)
func init() {
if t := os.Getenv("lextrace"); t != "" {
Trace = true
}
}
func debugf(f string, args ...interface{}) {
if Trace {
u.DoLog(3, u.DEBUG, fmt.Sprintf(f, args...))
}
}
var (
// SUPPORT_DURATION FEATURE FLAGS
SUPPORT_DURATION = true
// Identity Quoting
// http://stackoverflow.com/questions/1992314/what-is-the-difference-between-single-and-double-quotes-in-sql
// you might want to set this to not include single ticks
// http://dev.mysql.com/doc/refman/5.7/en/string-literals.html
//IdentityQuoting = []byte{'[', '`', '"'} // mysql ansi-ish, no single quote identities, and allowing double-quote
IdentityQuotingWSingleQuote = []byte{'[', '`', '\''} // more ansi-ish, allow single quotes around identities
IdentityQuoting = []byte{'[', '`'} // no single quote around identities bc effing mysql uses single quote for string literals
)
const (
eof = -1
decDigits = "0123456789"
hexDigits = "0123456789ABCDEF"
)
// StateFn represents the state of the lexer as a function that returns the
// next state.
type StateFn func(*Lexer) StateFn
// NamedStateFn is a StateFn which has a name for tracing debugging.
type NamedStateFn struct {
Name string
StateFn StateFn
}
// NewLexer Creates a new lexer for the input string
func NewLexer(input string, dialect *Dialect) *Lexer {
// Three tokens of buffering is sufficient for all state functions.
l := &Lexer{
input: input,
state: LexDialectForStatement,
tokens: make(chan Token, 3),
stack: make([]NamedStateFn, 0, 10),
dialect: dialect,
}
if len(dialect.IdentityQuoting) > 0 {
l.identityRunes = dialect.IdentityQuoting
} else {
l.identityRunes = IdentityQuoting
}
l.init()
return l
}
// Lexer holds the state of the lexical scanning.
//
// Holds a *Dialect* which gives much of the rules specific to this language.
//
// many-generations removed from that Based on the lexer from the "text/template" package.
// See http://www.youtube.com/watch?v=HxaD_trXwRE
type Lexer struct {
input string // the string being scanned
state StateFn // the next lexing function to enter
identityRunes []byte // List of legal identity escape bytes
pos int // current position in the input
start int // start position of this token
width int // width of last rune read from input
line int // Line we are currently on
linepos int // Position of start of current line
lastToken Token // last token we emitted
tokens chan Token // channel of scanned tokens we output on
doubleDelim bool // flag for tags starting with double braces
dialect *Dialect // Dialect is the syntax-rules for all statement-types of this language
statement *Clause // Statement type we are lexing
curClause *Clause // Current clause we are lexing, we descend, ascend, iter()
descent *Clause // Clause we have descended to
peekedWordPos int
peekedWord string
lastQuoteMark byte
// Due to nested Expressions and evaluation this allows us to descend/ascend
// during lex, using push/pop to add and remove states needing evaluation
stack []NamedStateFn
}
func (l *Lexer) init() {
l.ReverseTrim()
}
// ErrMsg an error message helper which provides context of where in input string
// the error is occuring, line, column, current token info.
func (l *Lexer) ErrMsg(t Token, msg string) error {
raw := l.RawInput()
if len(raw) == l.pos {
raw = ""
} else if len(raw) > t.Pos {
if t.Pos > 0 {
raw = raw[t.Pos-1:]
} else {
raw = raw[t.Pos:]
}
if len(raw) > 20 {
raw = raw[:19]
}
} else {
raw = ""
}
if len(msg) > 0 {
return fmt.Errorf("%s Got %s near: %s", msg, t.String(), raw)
}
return fmt.Errorf("Unrecognized input at Line %v Column %v %s", t.Line, t.Column, raw)
}
// NextToken returns the next token from the input.
func (l *Lexer) NextToken() Token {
for {
//u.Debugf("token: start=%v pos=%v peek5=%s", l.start, l.pos, l.PeekX(5))
select {
case token := <-l.tokens:
return token
default:
if l.state == nil && len(l.stack) > 0 {
l.state = l.pop()
} else if l.state == nil {
return Token{T: TokenEOF, V: ""}
}
l.state = l.state(l)
}
}
}
// Push a named StateFn onto stack.
func (l *Lexer) Push(name string, state StateFn) {
debugf("push %d %v", len(l.stack)+1, name)
if len(l.stack) < 500 {
l.stack = append(l.stack, NamedStateFn{name, state})
} else {
out := ""
if len(l.input) > 200 {
out = strings.Replace(l.input[0:199], "\n", " ", -1)
} else {
out = strings.Replace(l.input, "\n", " ", -1)
}
u.LogThrottle(u.WARN, 10, "Gracefully refusing to add more LexExpression: %s", out)
}
}
func (l *Lexer) pop() StateFn {
if len(l.stack) == 0 {
return l.errorf("BUG in lexer: no states to pop.")
}
li := len(l.stack) - 1
last := l.stack[li]
l.stack = l.stack[0:li]
debugf("popped item off stack: %d %v", len(l.stack)+1, last.Name)
return last.StateFn
}
// Next returns the next rune in the input
func (l *Lexer) Next() (r rune) {
if l.pos >= len(l.input) {
l.width = 0
return eof
}
r, l.width = utf8.DecodeRuneInString(l.input[l.pos:])
l.pos += l.width
return r
}
func (l *Lexer) skipX(ct int) {
for i := 0; i < ct; i++ {
l.Next()
}
}
// RawInput return the orgiginal string we are lexing.
func (l *Lexer) RawInput() string {
return l.input
}
// Remainder SQL and other string expressions may contain more than one
// statement such as:
//
// use schema_x; show tables;
//
// set @my_var = "value"; select a,b from `users` where name = @my_var;
//
func (l *Lexer) Remainder() (string, bool) {
l.SkipWhiteSpaces()
if r := l.Peek(); r == ';' {
l.Next()
}
l.SkipWhiteSpaces()
if l.pos >= len(l.input) {
return "", false
}
input := l.input[l.pos:]
if len(input) < 5 {
return "", false
}
return input, true
}
// Peek returns but does not consume the next rune in the input.
func (l *Lexer) Peek() rune {
r := l.Next()
l.backup()
return r
}
// PeekX grab the next x characters without consuming
func (l *Lexer) PeekX(x int) string {
if l.pos+x > len(l.input) {
return l.input[l.pos:]
}
return l.input[l.pos : l.pos+x]
}
// get single character PAST
func (l *Lexer) peekRunePast(skip int) rune {
if l.pos+skip+1 > len(l.input) {
return rune(0)
}
for ; skip < len(l.input)-l.pos; skip++ {
r, ri := utf8.DecodeRuneInString(l.input[l.pos+skip:])
if ri != 1 {
skip += (ri - 1)
}
if !unicode.IsSpace(r) {
return r
}
}
return rune(0)
}
// PeekWord grab the next word (till whitespace, without consuming)
func (l *Lexer) PeekWord() string {
if l.pos == l.peekedWordPos && l.peekedWordPos > 0 {
return l.peekedWord
}
// TODO: optimize this, this is by far the most expensive operation
// in the lexer
// - move to some type of early bail? ie, use Accept() wherever possible?
skipWs := 0
for ; skipWs < len(l.input)-l.pos; skipWs++ {
r, ri := utf8.DecodeRuneInString(l.input[l.pos+skipWs:])
if ri != 1 {
//skipWs += (ri - 1)
}
if !unicode.IsSpace(r) {
break
}
}
i := skipWs
for ; i < len(l.input)-l.pos; i++ {
r, ri := utf8.DecodeRuneInString(l.input[l.pos+i:])
//u.Debugf("r: %v identifier?%v", string(r), IsIdentifierRune(r))
if ri != 1 {
//i += (ri - 1)
}
if unicode.IsSpace(r) || (!IsIdentifierRune(r) && r != '@') || r == '(' {
if i > 0 {
//u.Infof("hm: '%v'", l.input[l.pos+skipWs:l.pos+i])
l.peekedWordPos = l.pos
l.peekedWord = l.input[l.pos+skipWs : l.pos+i]
return l.peekedWord
} else if r == '(' {
// regardless of being short, lets treat like word
return string(r)
}
}
}
//u.Infof("hm: '%v'", l.input[l.pos+skipWs:l.pos+i])
l.peekedWordPos = l.pos
l.peekedWord = l.input[l.pos+skipWs : l.pos+i]
return l.peekedWord
}
/*
// get single character
func (l *Lexer) peekXrune(x int) rune {
if l.pos+x > len(l.input) {
return rune(0)
}
return rune(l.input[l.pos+x])
}
// PeekWord2 grab the next word (till whitespace, without consuming)
func (l *Lexer) PeekWord2() string {
skipWs := 0
for ; skipWs < len(l.input)-l.pos; skipWs++ {
r, _ := utf8.DecodeRuneInString(l.input[l.pos+skipWs:])
if !unicode.IsSpace(r) {
break
}
}
word := ""
for i := skipWs; i < len(l.input)-l.pos; i++ {
r, _ := utf8.DecodeRuneInString(l.input[l.pos+i:])
if unicode.IsSpace(r) || !IsIdentifierRune(r) {
u.Infof("hm: '%v' word='%s' %v", l.input[l.pos:l.pos+i], word, l.input[l.pos:l.pos+i] == word)
return word
} else {
word = word + string(r)
}
}
return word
}
// peek word, but using laxIdentifier characters
func (l *Lexer) peekLaxWord() string {
word := ""
for i := 0; i < len(l.input)-l.pos; i++ {
r, _ := utf8.DecodeRuneInString(l.input[l.pos+i:])
if !isLaxIdentifierRune(r) {
return word
} else {
word = word + string(r)
}
}
return word
}
// Discard skips over the pending input before this point.
func (l *Lexer) Discard() {
l.start = l.pos
}
*/
// backup steps back one rune. Can only be called once per call of next.
func (l *Lexer) backup() {
l.pos -= l.width
}
// IsEnd have we consumed all input?
func (l *Lexer) IsEnd() bool {
//u.Infof("isEnd? %v:%v", l.pos, len(l.input))
if l.pos >= len(l.input) {
return true
}
// if l.Peek() == ';' {
// return true
// }
return false
}
// IsComment Is this a comment?
func (l *Lexer) IsComment() bool {
r := l.Peek()
switch r {
case '#':
return true
case '/', '-':
// continue on, might be, check 2nd character
cv := l.PeekX(2)
switch cv {
case "//":
return true
case "--":
return true
}
default:
return false
}
return false
}
// Emit passes an token back to the client.
func (l *Lexer) Emit(t TokenType) {
debugf("emit: %s '%s' stack=%v start=%d pos=%d", t, l.input[l.start:l.pos], len(l.stack), l.start, l.pos)
// We are going to use 1 based indexing (not 0 based) for lines
// because humans don't think that way
if l.lastQuoteMark != 0 {
l.lastToken = Token{T: t, V: l.input[l.start:l.pos], Quote: l.lastQuoteMark, Line: l.line + 1, Column: l.columnNumber(), Pos: l.pos}
l.lastQuoteMark = 0
} else {
l.lastToken = Token{T: t, V: l.input[l.start:l.pos], Line: l.line + 1, Column: l.columnNumber(), Pos: l.pos}
}
l.tokens <- l.lastToken
l.start = l.pos
}
// ignore skips over the pending input before this point.
func (l *Lexer) ignore() {
l.start = l.pos
}
// ignore skips over the item
func (l *Lexer) ignoreWord(word string) {
l.pos += len(word)
l.start = l.pos
}
// accept consumes the next rune if it's from the valid set.
func (l *Lexer) accept(valid string) bool {
if strings.IndexRune(valid, l.Next()) >= 0 {
return true
}
l.backup()
return false
}
// acceptRun consumes a run of runes from the valid set.
func (l *Lexer) acceptRun(valid string) bool {
pos := l.pos
for strings.IndexRune(valid, l.Next()) >= 0 {
}
l.backup()
return l.pos > pos
}
// Returns current string not yet emitted
func (l *Lexer) current() string {
if l.pos <= l.start {
return ""
}
str := l.input[l.start:l.pos]
l.start = l.pos
return str
}
// ConsumeWord lets move position to consume given word
func (l *Lexer) ConsumeWord(word string) {
// pretty sure the len(word) is valid right?
l.pos += len(word)
}
/*
// lineNumber reports which line we're on. Doing it this way
// means we don't have to worry about peek double counting.
func (l *Lexer) lineNumber() int {
//return 1 + strings.Count(l.input[:l.pos], "\n")
return l.line
}
// Returns remainder of input not yet lexed
func (l *Lexer) remainder() string {
return l.input[l.start : len(l.input)-1]
}
*/
// error returns an error token and terminates the scan by passing
// back a nil pointer that will be the next state, terminating l.nextToken.
func (l *Lexer) errorf(format string, args ...interface{}) StateFn {
l.tokens <- Token{T: TokenError, V: fmt.Sprintf(format, args...)}
return nil
}
// columnNumber reports which column in the current line we're on.
func (l *Lexer) columnNumber() int {
// n := strings.LastIndex(l.input[:l.pos], "\n")
// if n == -1 {
// n = 0
// }
// return l.pos - n
return l.pos - l.linepos
}
// SkipWhiteSpaces Skips white space characters in the input.
func (l *Lexer) SkipWhiteSpaces() {
for rune := l.Next(); unicode.IsSpace(rune); rune = l.Next() {
if rune == '\n' {
// New line, lets keep track of line position
l.line++
l.linepos = l.pos
}
}
l.backup()
l.ignore()
}
// SkipWhiteSpacesNewLine Skips white space characters in the input, returns bool
// for if it contained new line
func (l *Lexer) SkipWhiteSpacesNewLine() bool {
rune := l.Next()
hasNewLine := false
for {
if rune == '\n' {
hasNewLine = true
// New line, lets keep track of line position
l.line++
l.linepos = 0
} else if !unicode.IsSpace(rune) {
break
}
rune = l.Next()
}
l.backup()
l.ignore()
return hasNewLine
}
// Skips white space characters at end by trimming so we can recognize the end
// more easily
func (l *Lexer) ReverseTrim() {
for i := len(l.input) - 1; i >= 0; i-- {
if !unicode.IsSpace(rune(l.input[i])) {
if i < (len(l.input) - 1) {
//u.Warnf("trim: '%v'", l.input[:i+1])
l.input = l.input[:i+1]
}
break
}
}
}
// Scans input and matches against the string.
// Returns true if the expected string was matched.
// expects matchTo to be a lower case string
func (l *Lexer) match(matchTo string, skip int) bool {
//u.Debugf("match(%q) peek:%q ", matchTo, l.PeekWord())
for _, matchRune := range matchTo {
//u.Debugf("match rune? %v", string(matchRune))
if skip > 0 {
skip--
continue
}
nr := l.Next()
//u.Debugf("rune=%s n=%s %v %v", string(matchRune), string(nr), matchRune != nr, unicode.ToLower(nr) != matchRune)
if matchRune != nr && unicode.ToLower(nr) != matchRune {
//u.Debugf("setting done = false?, ie did not match")
return false
}
}
if l.IsEnd() {
return true
}
// If we finished looking for the match word, and the next item is not
// whitespace, it means we failed
if !isWhiteSpace(l.Peek()) {
return false
}
//u.Debugf("Found match(): %v", matchTo)
return true
}
// Scans input and tries to match the expected string.
// Returns true if the expected string was matched.
// Does not advance the input if the string was not matched.
//
// NOTE: this assumes the @val you are trying to match against is LOWER CASE
func (l *Lexer) tryMatch(matchTo string) bool {
i := 0
//u.Debugf("tryMatch: start='%v'", l.PeekWord())
for _, matchRune := range matchTo {
i++
nextRune := l.Next()
if unicode.ToLower(nextRune) != matchRune {
for ; i > 0; i-- {
l.backup()
}
//u.Warnf("not found: %v:%v", string(nextRune), matchTo)
return false
}
}
//u.Debugf("tryMatch: good='%v'", matchTo)
return true
}
// Emits an error token and terminates the scan
// by passing back a nil ponter that will be the next state
// terminating lexer.next function
func (l *Lexer) errorToken(format string, args ...interface{}) StateFn {
//fmt.Sprintf(format, args...)
l.Emit(TokenError)
return nil
}
// non-consuming isExpression, expressions are defined by
// starting with
// - negation (!)
// - non quoted alpha character
// - ( left-paren
//
func (l *Lexer) isExpr() bool {
// Expressions are strings not values, so quoting them means no
r := l.Peek()
switch {
case r == '\'':
return false
case isDigit(r):
// first character of expression cannot be digit
return false
case r == '!':
//u.Debugf("found negation! : %v", string(r))
// Negation is possible?
l.Next()
if l.isExpr() {
l.backup()
return true
}
l.backup()
case r == '(':
// ??? paran's wrapping sub-expressions?
return true
}
// Expressions are terminated by either a parenthesis
// never by spaces
for i := 0; i < len(l.input)-l.pos; i++ {
r, _ := utf8.DecodeRuneInString(l.input[l.pos+i:])
if r == '(' && i > 0 {
return true
} else if unicode.IsSpace(r) {
return false
} else if !isAlNumOrPeriod(r) {
return false
} // else isAlNumOrPeriod so keep looking
}
return false
}
// non-consuming check to see if we are about to find next keyword
func (l *Lexer) isNextKeyword(peekWord string) bool {
if len(peekWord) == 0 {
return false
}
kwMaybe := strings.ToLower(peekWord)
//u.Debugf("isNextKeyword? '%s' len:%v", kwMaybe, len(l.statement.Clauses))
clause := l.curClause.next
if clause == nil {
clause = l.curClause.parent
}
//u.Infof("clause: %s", clause)
for {
if clause == nil {
//u.Warnf("returning, not keyword")
break
}
//clause = l.statement.Clauses[i]
//u.Infof("clause: %+v", clause)
//u.Debugf("clause next keyword? peek=%s cname=%q keyword=%v multi?%v children?%v", kwMaybe, clause.Name, clause.keyword, clause.multiWord, len(clause.Clauses))
if clause.keyword == kwMaybe || (clause.multiWord && strings.ToLower(l.PeekX(len(clause.fullWord))) == clause.fullWord) {
//u.Infof("return true: %v", strings.ToLower(l.PeekX(len(clause.fullWord))))
return true
}
// TODO: allow clauses to reserve keywords, or sub-clause
switch kwMaybe {
case "select", "insert", "delete", "update", "from", "inner", "outer":
//u.Warnf("doing true: %v", kwMaybe)
return true
}
if !clause.Optional {
return false
}
clause = clause.next
}
return false
}
// non-consuming isIdentity
// Identities are non-numeric string values that are not quoted
func (l *Lexer) isIdentity() bool {
// Identity are strings not values
r := l.Peek()
switch {
case r == '[':
// This character [ is a little special
// as it is going to look to see if the 2nd character is
// valid identity character so ie alpha/numeric
peek2 := l.PeekX(2)
if len(peek2) == 2 {
return isIdentifierFirstRune(rune(peek2[1]))
}
return true
case l.isIdentityQuoteMark(r):
// are these always identities? or do we need
// to also check first identifier?
// peek2 := l.PeekX(2)
// if len(peek2) == 2 {
// return isIdentifierFirstRune(rune(peek2[1]))
// }
return true
}
return isIdentifierFirstRune(r)
}
// Uses the identity escaping/quote characters
func (l *Lexer) isIdentityQuoteMark(r rune) bool {
return bytes.IndexByte(l.identityRunes, byte(r)) >= 0
}
/*
// LexMatchSkip matches expected tokentype emitting the token on success
// and returning passed state function.
func (l *Lexer) LexMatchSkip(tok TokenType, skip int, fn StateFn) StateFn {
//u.Debugf("lexMatch t=%s peek=%s", tok, l.PeekWord())
if l.match(tok.String(), skip) {
//u.Debugf("found match: %s %v", tok, fn)
l.Emit(tok)
return fn
}
u.Error("unexpected token", tok)
return l.errorToken("Unexpected token:" + l.current())
}
*/
// lexer to match expected value returns with args of
// @matchState state function if match
// if no match, return nil
func (l *Lexer) lexIfMatch(tok TokenType, matchState StateFn) StateFn {
l.SkipWhiteSpaces()
if l.tryMatch(tok.String()) {
l.Emit(tok)
return matchState
}
return nil
}
// current clause state function, used for repeated clauses
func (l *Lexer) clauseState() StateFn {
if l.curClause != nil {
if len(l.curClause.Clauses) > 0 {
return l.curClause.Clauses[0].Lexer
}
return l.curClause.Lexer
}
return emptyLexFn
}
var emptyLexFn = func(*Lexer) StateFn { u.Debugf("empty statefun"); return nil }
// LexMatchClosure matches expected tokentype emitting the token on success
// and returning passed state function.
func LexMatchClosure(tok TokenType, nextFn StateFn) StateFn {
return func(l *Lexer) StateFn {
//u.Debugf("%p lexMatch t=%s peek=%s", l, tok, l.PeekWord())
if l.match(tok.String(), 0) {
//u.Debugf("found match: %s %v", tok, nextFn)
l.Emit(tok)
return nextFn
}
u.Warnf("unexpected token: %v peek:%s", tok, l.PeekX(20))
return l.errorToken("Unexpected token:" + l.current())
}
}
// State functions ------------------------------------------------------------
// Find first keyword in the current queryText, then find appropriate statement in dialect.
// ie [SELECT, ALTER, CREATE, INSERT] in sql
func LexDialectForStatement(l *Lexer) StateFn {
l.SkipWhiteSpaces()
r := l.Peek()
switch r {
case '/', '-', '#':
// ensure we have consumed all initial pre-statement comments
l.Push("LexDialectForStatement", LexDialectForStatement)
return LexComment(l)
default:
peekWord := strings.ToLower(l.PeekWord())
for _, stmt := range l.dialect.Statements {
if l.IsEnd() {
break
}
//u.Warnf("LexDialectForStatement peek=%s keyword=%v ", peekWord, stmt.Token.String())
if stmt.MatchesKeyword(peekWord, l) {
// We aren't actually going to consume anything here, just find
// the correct statement
l.statement = stmt
l.curClause = stmt
if len(stmt.Clauses) > 0 {
l.curClause = stmt.Clauses[0]
}
//u.Infof("statement: %s curClause %s", l.statement, l.curClause)
return LexStatement
} else if stmt.Token == TokenNil {
if len(stmt.Clauses) == 1 {
l.statement = stmt
l.curClause = stmt
if len(stmt.Clauses) > 0 {
l.curClause = stmt.Clauses[0]
}
return l.clauseState()
}
l.statement = stmt
l.curClause = stmt
if len(stmt.Clauses) > 0 {
l.curClause = stmt.Clauses[0]
}
return LexStatement
}
}
return l.errorToken("un recognized keyword token:" + peekWord)
}
}
// LexStatement is the main entrypoint to lex Grammars primarily associated with QL type
// languages, which is keywords separate clauses, and have order [select .. FROM name WHERE ..]
// the keywords which are reserved serve as identifiers to stop lexing and move to next clause
// lexer
func LexStatement(l *Lexer) StateFn {
l.SkipWhiteSpaces()
r := l.Peek()
switch r {
case '/', '-', '#':
// ensure we have consumed all comments
l.Push("LexStatement", LexStatement)
return LexComment(l)
default:
clause := l.curClause
repeat := false
peekWord := strings.ToLower(l.PeekWord())
//u.Debugf("%p curClause %s peek: %s", l, clause, peekWord)
// Before we move onto next clause, lets check and see if we need to descend
// into sub-clauses of current statement
if len(clause.Clauses) > 0 {
//u.Infof("%p has sub-clauses kw=%-10s peek=%-10s", l, clause.keyword, peekWord)
for _, sc := range clause.Clauses {
//u.Infof("%p has sub-clauses kw=%-10s peek=%-10s", l, sc.keyword, peekWord)
if sc.MatchesKeyword(peekWord, l) {
//u.Infof("matches Sub-Clause: %-10s", sc.keyword)
l.curClause = sc
clause = sc
break
} else if !sc.Optional {
break // First non-optional we don't match we bail
}
}
}
ClauseIterator:
for {
if clause == nil || l.IsEnd() {
break
}
// we only ever consume each clause once?
//u.Debugf("%p:%p stmt.clause parser? peek=%-10q keyword=%-10q multi?%v name=%-10q", clause.parent, clause, peekWord, clause.keyword, clause.multiWord, clause.Name)
if clause.Lexer != nil && clause.MatchesKeyword(peekWord, l) {
// Set the default entry point for this keyword
l.curClause = clause
//u.Debugf("dialect clause: '%v' LexerNil?%v \n\t %s ", clause.keyword, clause.Lexer == nil, l.input)
//u.Infof("matched stmt.clause token=%-10q match %-10q clausekw=%-10q multi?%v name=%-10q", clause.Token, peekWord, clause.keyword, clause.multiWord, clause.Name)
l.Push("LexStatement", LexStatement)
if int(clause.Token) == 0 {
nextState := clause.Lexer(l)
if nextState == nil {
//u.Warnf("nil next state")
} else {
//u.Debugf("found next state")
return nextState
}
} else if clause.Optional {
return l.lexIfMatch(clause.Token, clause.Lexer)
} else {
return LexMatchClosure(clause.Token, clause.Lexer)
}
} else if clause.MatchesKeyword(peekWord, l) {
//u.Debugf("nil lexer but matches? repeat?%v isrepeat?%v name=%q", clause.Repeat, repeat, clause.Name)
if !repeat || clause.Repeat {
// Before we move into child clause, lets check and see if we need to descend
// into sub-clauses of current statement
if len(clause.Clauses) > 0 {
//u.Debugf("has sub-clauses kw=%-10s peek=%-10s", clause.keyword, peekWord)
for _, sc := range clause.Clauses {
//u.Debugf("has sub-clauses kw=%-10s peek=%-10s", sc.keyword, peekWord)
if sc.MatchesKeyword(peekWord, l) {
//u.Debugf("matches Sub-Clause: kw=%-15q %-15q", sc.keyword, sc.Name)
l.curClause = sc
clause = sc
repeat = true
goto ClauseIterator
} else if !sc.Optional {
break // First non-optional we don't match we bail
}
}
}
}
}
// if we didn't match
if clause.next == nil && clause.parent != nil {
if clause.parent.Repeat && repeat == false {
// we haven't tried to repeat yet
repeat = true
clause = clause.parent
//u.Debugf("repeating clause: %v", clause.keyword)
// Before we move onto next clause, lets check and see if we need to descend
// into sub-clauses of current statement
if len(clause.Clauses) > 0 {
//u.Debugf("has sub-clauses kw=%-10s peek=%-10s", clause.keyword, peekWord)
for _, sc := range clause.Clauses {
//u.Infof("has sub-clauses kw=%-10s peek=%-10s", sc.keyword, peekWord)
if sc.MatchesKeyword(peekWord, l) {
//u.Debugf("matches Sub-Clause: %-10s", sc.keyword)
l.curClause = sc
clause = sc
break
} else if !sc.Optional {
break // First non-optional we don't match we bail
}
}
}
} else {
if clause.parent.next == nil {
//u.Warnf("nil? %#v ", clause.parent)
clause = clause.parent.next
break
}
clause = clause.parent.next
//u.Infof("moving to next parent clause: %v", clause.keyword)
}
} else {
clause = clause.next
}
}
// If we have consumed all clauses, we are ready to be done?
//u.Debugf("not found? word? '%s' %v", peekWord, clause)
if clause == nil {
//u.Infof("%p Run End of statement", l)
return LexEndOfStatement
}
}
// Correctly reached EOF.
if l.pos > l.start {
// What is this?
l.Emit(TokenRaw)
}
//u.Infof("end of statement")
l.Emit(TokenEOF)
return nil
}
//Doesn't actually lex anything, used for single token clauses
func LexEmpty(l *Lexer) StateFn { return nil }
// lex a value: string, integer, float
//
// - literal strings must be quoted
// - numerics with no period are integers
// - numerics with period are floats
//
// "stuff" -> [string] = stuff
// 'stuff' -> [string] = stuff
// "items's with quote" -> [string] = items's with quote
// 1.23 -> [float] = 1.23
// 100 -> [integer] = 100
// ["hello","world"] -> [array] {"hello","world"}
//
func LexValue(l *Lexer) StateFn {