forked from couchbaselabs/gojsonsm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
simpleParser.go
1750 lines (1511 loc) · 52.4 KB
/
simpleParser.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
// Copyright 2018 Couchbase, Inc. All rights reserved.
package gojsonsm
import (
"fmt"
"math"
"regexp"
"strconv"
"strings"
"sync"
)
/**
* SimpleParser provides user to be able to specify a N1QL-Styled expression for gojsonsm.
*
* Values can be string or floats. Strings should be enclosed by double quotes, as to not be confused
* with field variables
*
* Embedded objects are accessed via (.) accessor.
* Example:
* name.first == 'Neil'
*
* Field variables can be escaped by backticks ` to become literals.
* Example:
* `version0.1_serialNumber` LIKE "SN[0-9]+"
*
* Arrays are accessed with brackets, and integer indexes do not have to be enclosed by backticks.
* Example:
* user[10]
* US.`users.ids`[10]
*
* Parenthesis are allowed, but must be surrounded by at least 1 white space
* Currently, only the following operations are supported:
* ==/=, !=, ||/OR, &&/AND, >=, >, <=, <, LIKE/=~, NOT LIKE, EXISTS, IS MISSING, IS NULL, IS NOT NULL
*
* Usage example:
* exprStr := "name.`first.name` == "Neil" && (age < 50 || isActive == true)"
* expr, err := ParseSimpleExpression(exprStr)
*
* Notes:
* - Parenthesis parsing is there but could be a bit wonky should users choose to have invalid and weird syntax with it
*/
// Values by def should be enclosed within double quotes or single quotes
var valueRegex *regexp.Regexp = regexp.MustCompile(`^\".*\"$`)
var valueRegex2 *regexp.Regexp = regexp.MustCompile(`^\'.*\'$`)
// Or Values can be int or floats by themselves (w/o alpha char)
var valueNumRegex *regexp.Regexp = regexp.MustCompile(`^(-?)(0|([1-9][0-9]*))(\.[0-9]+)?$`)
var intNumRegex *regexp.Regexp = regexp.MustCompile(`^(-?)[0-9]+$`)
// Field path can be integers
var fieldTokenInt *regexp.Regexp = regexp.MustCompile(`[0-9]`)
// But they cannot have leading zeros
var fieldIndexNoLeadingZero *regexp.Regexp = regexp.MustCompile(`[^0][0-9]+`)
// Functions patterns
var funcTranslateTable map[string]string = map[string]string{
FuncAbs: MathFuncAbs,
FuncAcos: MathFuncAcos,
FuncAsin: MathFuncAsin,
FuncAtan: MathFuncAtan,
FuncCeil: MathFuncCeil,
FuncCos: MathFuncCos,
FuncDate: DateFunc,
FuncDeg: MathFuncDegrees,
FuncExp: MathFuncExp,
FuncFloor: MathFuncFloor,
FuncLog: MathFuncLog,
FuncLn: MathFuncLn,
FuncSin: MathFuncSin,
FuncTan: MathFuncTan,
FuncRad: MathFuncRadians,
FuncRound: MathFuncRound,
FuncSqrt: MathFuncSqrt,
}
var func0VarTranslateTable map[string]string = map[string]string{
"PI": MathFuncPi,
"E": MathFuncE,
}
// Two variables function patterns
var func2VarsTranslateTable map[string]string = map[string]string{
FuncAtan2: MathFuncAtan2,
FuncPower: MathFuncPow,
}
func funcIsConstantType(fxName string) (bool, interface{}) {
switch fxName {
case MathFuncPi:
return true, float64(math.Pi)
case MathFuncE:
return true, float64(math.E)
}
return false, nil
}
func getOutputFuncName(userInput string) string {
if val, ok := funcTranslateTable[userInput]; ok {
return val
} else if val, ok := func0VarTranslateTable[userInput]; ok {
return val
} else if val, ok := func2VarsTranslateTable[userInput]; ok {
return val
} else {
return ""
}
}
func getCheckFuncPattern(name string) string {
return fmt.Sprintf(`^%s\((?P<args>.+)\)$`, name)
}
func getCheckFunc0Pattern(name string) string {
return fmt.Sprintf(`^%s\(\)$`, name)
}
func getCheckFunc2Pattern(name string) string {
return fmt.Sprintf(`^%s\((?P<args>.+), *(?P<args>.+)\)$`, name)
}
type ParserTreeNode struct {
tokenType ParseTokenType
data interface{}
}
func needToSpawnNewContext(err error) bool {
return err == ErrorNeedToStartOneNewCtx || err == ErrorNeedToStartNewCtx
}
var emptyParserTreeNode ParserTreeNode
func NewParserTreeNode(tokenType ParseTokenType, data interface{}) ParserTreeNode {
newNode := &ParserTreeNode{
tokenType: tokenType,
data: data,
}
return *newNode
}
type parserSubContext struct {
// Actual parser context
currentMode parseMode
lastSubFieldNode int // The last finished left side of the op
skipAdvanceCurrentMode bool
opTokenContext opTokenContext
fieldIsTrueOrFalse bool
// For tree organization
lastParserDataNode int // Last inserted parser data node location
lastBinTreeDataNode int // Last inserted parserTree data node location
lastFieldIndex int
lastOpIndex int
lastValueIndex int
// For inserting node
funcHelperCtx *funcOutputHelper
// Means that we should return as soon as the one layer of field -> op -> value is done
oneLayerMode bool
// Last seeker found
lastSeeker *opSeeker
}
func (subctx *parserSubContext) isUnused() bool {
return subctx.lastFieldIndex == -1 && subctx.lastOpIndex == -1 && subctx.lastValueIndex == -1 &&
subctx.lastSubFieldNode == -1 && subctx.currentMode == fieldMode
}
func NewParserSubContext() *parserSubContext {
subCtx := &parserSubContext{
lastFieldIndex: -1,
lastOpIndex: -1,
lastValueIndex: -1,
lastSubFieldNode: -1,
currentMode: fieldMode,
}
return subCtx
}
func NewParserSubContextOneLayer() *parserSubContext {
subCtx := NewParserSubContext()
subCtx.oneLayerMode = true
return subCtx
}
type multiwordHelperPair struct {
actualMultiWords []string
valid bool
}
type funcOutputHelper struct {
// args represent levels of potential fx recursion. The first slice is always the top level fx call
// The first element of []interface{} is always the func name
args [][]interface{}
lvlMarker int
recursiveKeyFunc checkAndGetKeyFunc
// Functional regex to grab function names and also its arguments
builtInFuncRegex map[string]*regexp.Regexp
}
type opSeeker struct {
completeToken string
idx int
opFound bool
// opFoundLastIdx int
opMatched string
}
func NewOpSeeker(token string) *opSeeker {
seeker := &opSeeker{completeToken: token}
return seeker
}
func (os *opSeeker) Seek() bool {
for i := 0; i < len(os.completeToken); i++ {
os.idx = i
os.seekInternal(i)
if os.opFound {
return true
}
}
return false
}
func (os *opSeeker) GetToken() string {
return os.opMatched
}
func (os *opSeeker) seekInternal(curIdx int) {
compiledStr := os.completeToken[os.idx:curIdx]
if tokenIsOpType(compiledStr) {
if !os.opFound {
os.opFound = true
}
if curIdx == len(os.completeToken) {
// The last character just happens to be the op
os.opMatched = compiledStr
return
}
} else {
if os.opFound {
os.opMatched = os.completeToken[os.idx : curIdx-1]
return
}
}
if curIdx < len(os.completeToken) {
os.seekInternal(curIdx + 1)
}
}
type expressionParserContext struct {
// For token reading
tokens []string
currentTokenIndex int
advTokenPositionOnly bool // This flag is set once, and the corresponding method will toggle it off automatically
multiwordHelperMap map[string]*multiwordHelperPair
multiwordMapOnce sync.Once
// Split the last successful field token into subtokens for transformer's Path
lastFieldTokens []string
// The levels of parenthesis currently discovered in the expression
parenDepth int
// Current sub context
subCtx *parserSubContext
// non-short ciruit eval -> left most expression does not necessarily translate into the first to be examined
shortCircuitEnabled bool
// Final parser tree - binTree is the one that is used to keep track of tree structure
// Each element of []ParserTreeNode corresponds to the # of element in parserTree.data
parserTree binParserTree
parserDataNodes []ParserTreeNode
treeHeadIndex int
// For field tokens, as the parser checks the syntax of the field, it separates them into subtokens for outputting
// to Path for field expressions. This map stores the information. Key is the index of ParserTreeNode
fieldTokenPaths map[int][]string
// Functions are essentially like augmented fields/values.
// Each element in this map that is a field must have a counter part in the fieldTOkensPaths map above
// If it's a value, then it's indicated in the pair, and the value interface is used
funcOutputContext map[int]*funcOutputHelper
builtInFuncRegex map[string]*regexp.Regexp
// Outputting context
currentOuputNode int
// Compile-time determined PCRE module
pcreWrapper PcreWrapperInterface
}
type checkFieldMode int
const (
cfmNone checkFieldMode = iota
cfmBacktick checkFieldMode = iota
cfmNestedNumeric checkFieldMode = iota
)
func NewExpressionParserCtx(strExpression string) (*expressionParserContext, error) {
subCtx := NewParserSubContext()
ctx := &expressionParserContext{
tokens: strings.Fields(strExpression),
subCtx: subCtx,
treeHeadIndex: -1,
fieldTokenPaths: make(map[int][]string),
builtInFuncRegex: make(map[string]*regexp.Regexp),
funcOutputContext: make(map[int]*funcOutputHelper),
}
for k, _ := range funcTranslateTable {
regex := regexp.MustCompile(getCheckFuncPattern(k))
ctx.builtInFuncRegex[k] = regex
}
for k, _ := range func0VarTranslateTable {
regex := regexp.MustCompile(getCheckFunc0Pattern(k))
ctx.builtInFuncRegex[k] = regex
}
for k, _ := range func2VarsTranslateTable {
regex := regexp.MustCompile(getCheckFunc2Pattern(k))
ctx.builtInFuncRegex[k] = regex
}
return ctx, nil
}
type ParseTokenType int
const (
TokenTypeField ParseTokenType = iota
TokenTypeFunc ParseTokenType = iota
TokenTypeOperator ParseTokenType = iota
TokenTypeValue ParseTokenType = iota
TokenTypeRegex ParseTokenType = iota
TokenTypePcre ParseTokenType = iota
TokenTypeParen ParseTokenType = iota
TokenTypeEndParen ParseTokenType = iota
TokenTypeTrue ParseTokenType = iota
TokenTypeFalse ParseTokenType = iota
TokenTypeInvalid ParseTokenType = iota
)
func (ptt ParseTokenType) String() string {
switch ptt {
case TokenTypeField:
return "TokenTypeField"
case TokenTypeOperator:
return "TokenTypeOperator"
case TokenTypeValue:
return "TokenTypeValue"
case TokenTypeRegex:
return "TokenTypeRegex"
case TokenTypePcre:
return "TokenTypePcre"
case TokenTypeParen:
return "TokenTypeParen"
case TokenTypeEndParen:
return "TokenTypeEndParen"
case TokenTypeTrue:
return "TokenTypeTrue"
case TokenTypeFalse:
return "TokenTypeFalse"
case TokenTypeInvalid:
return "TokenTypeInvalid"
}
return "Unknown"
}
func (ptt ParseTokenType) isBoolType() bool {
return ptt == TokenTypeTrue || ptt == TokenTypeFalse
}
func (ptt ParseTokenType) isFieldType() bool {
return ptt == TokenTypeField || ptt == TokenTypeFunc
}
func (ptt ParseTokenType) isOpType() bool {
return ptt == TokenTypeOperator
}
// Regex is a type of special "value", and functions can act as values too
func (ptt ParseTokenType) isValueType() bool {
return ptt == TokenTypeValue || ptt == TokenTypeRegex || ptt == TokenTypeFunc || ptt == TokenTypePcre
}
// Operator types
const (
TokenOperatorEqual = "=="
TokenOperatorNotEqual = "!="
TokenOperatorOr = "||"
TokenOperatorAnd = "&&"
TokenOperatorLessThan = "<"
TokenOperatorLessThanEq = "<="
TokenOperatorGreaterThan = ">"
TokenOperatorGreaterThanEq = ">="
TokenOperatorLike = "=~"
TokenOperatorExists = "EXISTS"
)
// Other allowable operator tokens
const (
TokenOperatorEqual2 = "="
TokenOperatorOr2 = "OR"
TokenOperatorAnd2 = "AND"
TokenOperatorLike2 = "LIKE"
)
// Multi-word operator tokens
var TokenOperatorNotLike []string = []string{"NOT", "LIKE"}
var TokenOperatorIsNull []string = []string{"IS", "NULL"}
var TokenOperatorIsNotNull []string = []string{"IS", "NOT", "NULL"}
var TokenOperatorIsMissing []string = []string{"IS", "MISSING"}
// In keeping with internals, flatten it and use it as comparison for actual op when outputting
func flattenToken(token []string) string {
return strings.Join(token, "_")
}
func replaceOpTokenIfNecessary(token string) string {
switch token {
case TokenOperatorEqual2:
return TokenOperatorEqual
case TokenOperatorOr2:
return TokenOperatorOr
case TokenOperatorAnd2:
return TokenOperatorAnd
case TokenOperatorLike2:
return TokenOperatorLike
}
return token
}
func tokenIsOpType(token string) bool {
// Equal is both numeric and logical
return tokenIsChainOpType(token) || tokenIsEquivalentType(token) || tokenIsCompareOpType(token) || tokenIsLikeType(token) ||
tokenIsOpOnlyType(token)
}
// This ops do not have value follow-ups
func tokenIsOpOnlyType(token string) bool {
return tokenIsExistenceType(token) || tokenIsNullType(token)
}
func tokenIsExistenceType(token string) bool {
return token == TokenOperatorExists || token == flattenToken(TokenOperatorIsMissing)
}
func tokenIsNullType(token string) bool {
return token == flattenToken(TokenOperatorIsNull) || token == flattenToken(TokenOperatorIsNotNull)
}
func tokenIsLikeType(token string) bool {
return token == TokenOperatorLike || token == TokenOperatorLike2 || token == flattenToken(TokenOperatorNotLike)
}
func tokenIsEquivalentType(token string) bool {
return token == TokenOperatorEqual || token == TokenOperatorEqual2 || token == TokenOperatorNotEqual
}
// Comparison Operator can be used for both string comparison and numeric
func tokenIsCompareOpType(token string) bool {
return token == TokenOperatorGreaterThanEq || token == TokenOperatorLessThan || token == TokenOperatorLessThanEq || token == TokenOperatorGreaterThan
}
// Chain-op are operators that can chain multiple expressions together
func tokenIsChainOpType(token string) bool {
return token == TokenOperatorAnd || token == TokenOperatorAnd2 || token == TokenOperatorOr || token == TokenOperatorOr2
}
func (ctx *expressionParserContext) tokenIsBuiltInFuncType(token string) (bool, string) {
for key, checker := range ctx.builtInFuncRegex {
if checker.MatchString(token) {
return true, key
}
}
return false, ""
}
func (opCtx opTokenContext) isChainOp() bool {
return opCtx == chainOp
}
func (opCtx opTokenContext) isCompareOp() bool {
return opCtx == compareOp
}
func (opCtx opTokenContext) isLikeOp() bool {
return opCtx == matchOp
}
func (opCtx *opTokenContext) clear() {
if *opCtx != noOp {
*opCtx = noOp
}
}
// returns a delim string, or true for valueNumRegex match, nor nil if no match
func valueCheck(token string) interface{} {
if valueRegex.MatchString(token) {
return `"`
} else if valueRegex2.MatchString(token) {
return "'"
} else if valueNumRegex.MatchString(token) {
return true
}
return nil
}
func (ctx *expressionParserContext) advanceToken() error {
ctx.currentTokenIndex++
if ctx.advTokenPositionOnly {
ctx.advTokenPositionOnly = false
return nil
}
ctx.subCtx.funcHelperCtx = nil
// context mode transition
switch ctx.subCtx.currentMode {
case fieldMode:
// After the field mode, the next token *must* be an op
ctx.subCtx.currentMode = opMode
case opMode:
switch ctx.subCtx.opTokenContext {
case noFieldOp:
// These ops do not have fields
ctx.subCtx.currentMode = chainMode
case chainOp:
ctx.subCtx.currentMode = fieldMode
ctx.subCtx.fieldIsTrueOrFalse = false
default:
// After the op mode, the next mode should be value mode
ctx.subCtx.currentMode = valueMode
}
case valueMode:
if ctx.subCtx.oneLayerMode {
// One layer mode means that we should return as soon as this value is done so we can merge
ctx.currentTokenIndex = ctx.currentTokenIndex - 1
return NonErrorOneLayerDone
} else {
// After the value is finished, this subcompletion becomes a "field", so the next mode should be
// a op
ctx.subCtx.currentMode = chainMode
}
ctx.subCtx.opTokenContext.clear()
case chainMode:
ctx.subCtx.currentMode = fieldMode
ctx.subCtx.fieldIsTrueOrFalse = false
default:
return fmt.Errorf("Not implemented yet for mode transition %v", ctx.subCtx.currentMode)
}
return nil
}
func (ctx *expressionParserContext) handleParenPrefix(paren string) error {
// Strip the "(" or ")" from this token and into its own element
ctx.tokens = append(ctx.tokens, "")
ctx.tokens[ctx.currentTokenIndex] = strings.TrimPrefix(ctx.tokens[ctx.currentTokenIndex], paren)
copy(ctx.tokens[ctx.currentTokenIndex+1:], ctx.tokens[ctx.currentTokenIndex:])
ctx.tokens[ctx.currentTokenIndex] = paren
return nil
}
func (ctx *expressionParserContext) handleParenSuffix(paren string) error {
// Strip the paren from the end of this token and insert into its own element
for strings.HasSuffix(ctx.tokens[ctx.currentTokenIndex], paren) {
ctx.tokens = append(ctx.tokens, "")
copy(ctx.tokens[ctx.currentTokenIndex+1:], ctx.tokens[ctx.currentTokenIndex:])
ctx.tokens[ctx.currentTokenIndex] = strings.TrimSuffix(ctx.tokens[ctx.currentTokenIndex], paren)
ctx.tokens[ctx.currentTokenIndex+1] = paren
}
return nil
}
func (ctx *expressionParserContext) handleCloseParenBookKeeping() error {
if ctx.parenDepth == 0 {
return ErrorParenMismatch
}
ctx.parenDepth--
// If a close parenthesis is found and there was no op in this latest () and it's not (true) or (false)
if ctx.subCtx.lastOpIndex == -1 && !ctx.subCtx.fieldIsTrueOrFalse && ctx.subCtx.currentMode != fieldMode {
return ErrorMalformedParenthesis
}
return nil
}
func (ctx *expressionParserContext) handleOpenParenBookKeeping() error {
ctx.parenDepth++
// for paren prefix, internally advance so the next getToken will not get a paren
ctx.advTokenPositionOnly = true
return ctx.advanceToken()
}
// Given a specific op token, set the opTokenContext to the type of op it is
func (ctx *expressionParserContext) checkAndMarkDetailedOpToken(token string) {
if tokenIsChainOpType(token) && ctx.subCtx.lastSubFieldNode != -1 {
// Only set chain op if there is something previously to chain
ctx.subCtx.opTokenContext = chainOp
} else if tokenIsCompareOpType(token) {
ctx.subCtx.opTokenContext = compareOp
} else if tokenIsLikeType(token) {
ctx.subCtx.opTokenContext = matchOp
} else if tokenIsOpOnlyType(token) {
ctx.subCtx.opTokenContext = noFieldOp
}
}
func (ctx *expressionParserContext) checkIfTokenIsPotentiallyOpType(token string) bool {
if token == TokenOperatorNotLike[0] || token == TokenOperatorIsNull[0] || token == TokenOperatorIsNotNull[0] {
ctx.multiwordMapOnce.Do(func() {
ctx.multiwordHelperMap = make(map[string]*multiwordHelperPair)
ctx.multiwordHelperMap[flattenToken(TokenOperatorNotLike)] = &multiwordHelperPair{
actualMultiWords: TokenOperatorNotLike,
}
ctx.multiwordHelperMap[flattenToken(TokenOperatorIsNull)] = &multiwordHelperPair{
actualMultiWords: TokenOperatorIsNull,
}
ctx.multiwordHelperMap[flattenToken(TokenOperatorIsNotNull)] = &multiwordHelperPair{
actualMultiWords: TokenOperatorIsNotNull,
}
ctx.multiwordHelperMap[flattenToken(TokenOperatorIsMissing)] = &multiwordHelperPair{
actualMultiWords: TokenOperatorIsMissing,
}
})
for _, v := range ctx.multiwordHelperMap {
v.valid = true
}
return true
}
return false
}
func (ctx *expressionParserContext) handleMultiTokens() (string, ParseTokenType, error) {
var tokenOrig string = ctx.tokens[ctx.currentTokenIndex]
numValids := len(ctx.multiwordHelperMap)
outerLoop:
for i := 0; ctx.currentTokenIndex+i < len(ctx.tokens); i++ {
token := ctx.tokens[ctx.currentTokenIndex+i]
retry := true
for retry {
retry = false
for fstr, pair := range ctx.multiwordHelperMap {
if !pair.valid {
continue
}
if i >= len(pair.actualMultiWords) || pair.actualMultiWords[i] != token {
pair.valid = false
numValids--
retry = true
break
}
if numValids == 0 {
break outerLoop
} else if numValids == 1 && i == len(pair.actualMultiWords)-1 && pair.actualMultiWords[i] == token {
ctx.currentTokenIndex += i
ctx.checkAndMarkDetailedOpToken(fstr)
return fstr, TokenTypeOperator, nil
}
}
}
}
return tokenOrig, TokenTypeInvalid, fmt.Errorf("Error: Invalid use of keyword for token: %s", tokenOrig)
}
func (ctx *expressionParserContext) getCurrentTokenParenHelper(token string) (string, ParseTokenType, error) {
if token != "(" && strings.HasPrefix(token, "(") {
ctx.handleParenPrefix("(")
return ctx.getCurrentToken()
} else if token != "(" && strings.HasSuffix(token, "(") {
ctx.handleParenSuffix("(")
return ctx.getCurrentToken()
} else if token != ")" && strings.HasSuffix(token, ")") {
ctx.handleParenSuffix(")")
return ctx.getCurrentToken()
} else if token != ")" && strings.HasPrefix(token, ")") {
ctx.handleParenPrefix(")")
token = ctx.tokens[ctx.currentTokenIndex]
return token, TokenTypeEndParen, ctx.handleCloseParenBookKeeping()
} else if token == ")" {
return token, TokenTypeEndParen, ctx.handleCloseParenBookKeeping()
} else if token == "(" {
return token, TokenTypeParen, ctx.handleOpenParenBookKeeping()
} else if found := ctx.checkPotentialSeparation(token); found {
return ctx.getAndSeparateToken()
}
return token, TokenTypeInvalid, ErrorMalformedParenthesis
}
func (ctx *expressionParserContext) getTokenValueSubtype() ParseTokenType {
if ctx.subCtx.opTokenContext.isLikeOp() {
return TokenTypeRegex
} else {
return TokenTypeValue
}
}
func (ctx *expressionParserContext) getValueTokenHelper(delim string) (string, ParseTokenType, error) {
token := ctx.tokens[ctx.currentTokenIndex]
// For value, strip the double quotes
token = strings.TrimPrefix(token, delim)
token = strings.TrimSuffix(token, delim)
if ctx.getTokenValueSubtype() != TokenTypeValue {
_, err := regexp.Compile(token)
if err != nil {
if tokenIsPcreValueType(token) {
return token, TokenTypePcre, nil
}
return token, TokenTypeRegex, err
}
}
return token, ctx.getTokenValueSubtype(), nil
}
// Also does some internal ctx set
func (ctx *expressionParserContext) getTrueFalseValue(token string) (string, ParseTokenType, error) {
if token == "true" {
ctx.subCtx.fieldIsTrueOrFalse = true
return token, TokenTypeTrue, nil
} else if token == "false" {
ctx.subCtx.fieldIsTrueOrFalse = true
return token, TokenTypeFalse, nil
} else {
return token, TokenTypeInvalid, ErrorInvalidFuncArgs
}
}
func (ctx *expressionParserContext) getCurrentToken() (string, ParseTokenType, error) {
if ctx.currentTokenIndex >= len(ctx.tokens) {
return "", TokenTypeInvalid, ErrorNoMoreTokens
}
token := ctx.tokens[ctx.currentTokenIndex]
if ctx.checkIfTokenIsPotentiallyOpType(token) {
return ctx.handleMultiTokens()
} else if tokenIsOpType(token) {
token = replaceOpTokenIfNecessary(token)
ctx.checkAndMarkDetailedOpToken(token)
return token, TokenTypeOperator, nil
} else if delim, ok := valueCheck(token).(string); ok && ctx.subCtx.currentMode == valueMode {
return ctx.getValueTokenHelper(delim)
} else if isNum, ok := valueCheck(token).(bool); ok && isNum {
return token, ctx.getTokenValueSubtype(), nil
} else if token == "true" || token == "false" {
return ctx.getTrueFalseValue(token)
} else if isFunc, key := ctx.tokenIsBuiltInFuncType(token); isFunc {
return ctx.getFuncFieldTokenHelper(token, key)
} else if strings.Contains(token, "(") || strings.Contains(token, ")") {
return ctx.getCurrentTokenParenHelper(token)
} else if delim, unfinished := tokenIsUnfinishedValueType(token); ctx.subCtx.currentMode == valueMode && unfinished {
return ctx.getUnfinishedValueHelper(delim)
} else if found := ctx.checkPotentialSeparation(token); found {
return ctx.getAndSeparateToken()
} else {
return ctx.getTokenFieldTokenHelper()
}
}
func tokenIsUnfinishedValueType(token string) (string, bool) {
if strings.HasPrefix(token, `"`) && !strings.HasSuffix(token, `"`) {
return `"`, true
} else if strings.HasPrefix(token, "'") && !strings.HasSuffix(token, "'") {
return `'`, true
}
return "", false
}
func (ctx *expressionParserContext) getUnfinishedValueHelper(delim string) (string, ParseTokenType, error) {
outputToken := strings.TrimPrefix(ctx.tokens[ctx.currentTokenIndex], delim)
tokensLen := len(ctx.tokens)
for ctx.currentTokenIndex++; ctx.currentTokenIndex < tokensLen; ctx.currentTokenIndex++ {
var breakout bool
token := ctx.tokens[ctx.currentTokenIndex]
if ctx.parenDepth > 0 && strings.HasSuffix(token, ")") {
ctx.handleParenSuffix(")")
tokensLen = len(ctx.tokens)
token = ctx.tokens[ctx.currentTokenIndex]
}
if strings.HasSuffix(token, delim) {
breakout = true
token = strings.TrimSuffix(token, delim)
}
outputToken = fmt.Sprintf("%s %s", outputToken, token)
if breakout {
break
}
}
if ctx.currentTokenIndex == tokensLen {
return "", TokenTypeInvalid, ErrorMissingQuote
}
return outputToken, ctx.getTokenValueSubtype(), nil
}
func (ctx *expressionParserContext) NewFuncHelper() *funcOutputHelper {
helper := &funcOutputHelper{
args: make([][]interface{}, 1),
recursiveKeyFunc: func(token string) (bool, string) {
return ctx.tokenIsBuiltInFuncType(token)
},
builtInFuncRegex: ctx.builtInFuncRegex,
}
return helper
}
func (ctx *expressionParserContext) getFuncFieldTokenHelper(token, funcKey string) (string, ParseTokenType, error) {
if ctx.subCtx.currentMode == fieldMode || ctx.subCtx.currentMode == valueMode {
helper := ctx.NewFuncHelper()
ctx.subCtx.funcHelperCtx = helper
defer helper.resetLevel()
return token, TokenTypeFunc, helper.resolveRecursiveFuncs(token, funcKey)
} else {
return token, TokenTypeFunc, fmt.Errorf("Error: %v mode is invalid for functions", ctx.subCtx.currentMode.String())
}
}
// Checks the syntax of field - i.e. paths, array syntax, etc
func (ctx *expressionParserContext) getTokenFieldTokenHelper() (string, ParseTokenType, error) {
var err error
token := ctx.tokens[ctx.currentTokenIndex]
// Field name cannot start or end with a period
invalidPeriodPosRegex := regexp.MustCompile(`(^\.)|(\.$)`)
if invalidPeriodPosRegex.MatchString(token) {
err = fmt.Errorf("Invalid field: %v - cannot start or end with a period", token)
}
if err != nil {
return token, TokenTypeField, err
}
ctx.lastFieldTokens = make([]string, 0)
token, err = checkAndParseField(ctx.tokens, &ctx.currentTokenIndex, &ctx.lastFieldTokens)
return token, TokenTypeField, err
}
func checkAndParseField(tokens []string, i *int, subTokens *[]string) (string, error) {
var mode checkFieldMode
var nextMode checkFieldMode
var skipAppend bool
var unfinishedField []string
var done bool = false
var outputToken string
token := tokens[*i]
if len(token) == 0 {
return outputToken, ErrorEmptyToken
}
for !done {
var pos int
var beginPos int
for ; pos < len(token); pos++ {
switch mode {
case cfmNone:
switch string(token[pos]) {
case fieldSeparator:
if !skipAppend {
*subTokens = append(*subTokens, string(token[beginPos:pos]))
outputToken = fmt.Sprintf("%s %s", outputToken, string(token[beginPos:pos]))
} else {
skipAppend = false
}
beginPos = pos + 1
case fieldLiteral:
mode = cfmBacktick
beginPos = pos + 1
nextMode = cfmNone
case fieldNestedStart:
if !skipAppend {
*subTokens = append(*subTokens, string(token[beginPos:pos]))
outputToken = fmt.Sprintf("%s %s", outputToken, string(token[beginPos:pos]))
} else {
skipAppend = false
}
beginPos = pos
mode = cfmNestedNumeric
}
case cfmBacktick:
// Keep going until we find another literal seperator
switch string(token[pos]) {
case fieldLiteral:
if beginPos == pos {
return outputToken, ErrorEmptyLiteral
}
if len(unfinishedField) > 0 {
unfinishedField = append(unfinishedField, string(token[beginPos:pos]))
*subTokens = append(*subTokens, strings.Join(unfinishedField, " "))
outputToken = fmt.Sprintf("%s %s", outputToken, strings.Join(unfinishedField, " "))
unfinishedField = make([]string, 0)
} else {
*subTokens = append(*subTokens, string(token[beginPos:pos]))
outputToken = fmt.Sprintf("%s %s", outputToken, string(token[beginPos:pos]))
}
mode = nextMode
if pos != len(token)-1 && (string(token[pos+1]) == fieldSeparator || string(token[pos+1]) == fieldNestedStart) || pos == len(token)-1 {
skipAppend = true
}
}
case cfmNestedNumeric:
if pos == beginPos {
continue
}
if pos == beginPos+1 && string(token[pos]) == "0" {
return outputToken, ErrorLeadingZeroes
} else if !fieldTokenInt.MatchString(string(token[pos])) && string(token[pos]) != fieldNestedEnd {
return outputToken, ErrorAllInts
}
switch string(token[pos]) {
case fieldNestedEnd:
// If nothing was entered between the brackets
if pos == beginPos+1 {
return outputToken, ErrorEmptyNest
}
// Advance mode to the next, and skip appending if this is the last or is followed by another nest
mode = cfmNone
if !skipAppend {
*subTokens = append(*subTokens, token[beginPos:pos+1])
outputToken = fmt.Sprintf("%s %s", outputToken, string(token[beginPos:pos+1]))
} else {
skipAppend = false
}
if pos == len(token)-1 || (pos < len(token)-1 && string(token[pos+1]) == fieldNestedStart) {
skipAppend = true
}
case fieldSeparator:
fallthrough
case fieldLiteral:
// For now, bracket can be used only for array indexing
return outputToken, ErrorAllInts
}
}
}
// Catch any outstanding mismatched backticks or anything else
switch mode {
case cfmNone:
if !skipAppend {
// Capture the last string, whatever it is
*subTokens = append(*subTokens, string(token[beginPos:pos]))
outputToken = fmt.Sprintf("%s %s", outputToken, string(token[beginPos:pos]))
}
done = true
case cfmNestedNumeric:
return outputToken, ErrorMissingBacktickBracket
case cfmBacktick:
// We haven't found the end backtick in this token, go through the next token
unfinishedField = append(unfinishedField, string(token[beginPos:pos]))
*i = *i + 1
if *i >= len(tokens) {
return outputToken, ErrorMissingBacktickBracket
}
token = tokens[*i]
}
} // !done
return outputToken, nil
}
func (ctx *expressionParserContext) getErrorNeedToStartNewCtx() error {
return ErrorNeedToStartNewCtx
}
func (ctx *expressionParserContext) getErrorNeedToStartOneNewCtx() error {
if ctx.shortCircuitEnabled {
// If short circuit is enabled, no need to return after one context.
// Having recursively starting new context will make it such that the left-most
// expression stays at the higher levels to be evaluated first
return ErrorNeedToStartNewCtx
} else {
return ErrorNeedToStartOneNewCtx
}
}
func (ctx *expressionParserContext) checkTokenTypeWithinContext(tokenType ParseTokenType, token string) error {
switch ctx.subCtx.currentMode {
case opMode: