-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.go
More file actions
2438 lines (2243 loc) · 65.5 KB
/
parser.go
File metadata and controls
2438 lines (2243 loc) · 65.5 KB
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 jsonpath
import (
"fmt"
"math"
"regexp"
"strconv"
"strings"
)
// 解析 JSONPath 表达式
func parse(path string) ([]segment, error) {
// 处理空路径
if path == "" {
return nil, nil
}
// 检查是否是函数调用格式: functionName(arg1, arg2, ...)
// 这是 RFC 9535 的 match() 和 search() 函数语法
if idx := strings.Index(path, "("); idx > 0 && strings.HasSuffix(path, ")") {
funcName := path[:idx]
// 验证函数名是有效的标识符
if isValidFunctionName(funcName) {
argsStr := path[idx+1 : len(path)-1]
return parseTopLevelFunctionCall(funcName, argsStr)
}
}
// 检查并移除 $ 前缀
if !strings.HasPrefix(path, "$") {
return nil, NewError(ErrSyntax, "path must start with $", path)
}
path = strings.TrimPrefix(path, "$")
// 如果路径只有 $,返回空段列表
if path == "" {
return nil, nil
}
// Reject path that is only whitespace after $ (e.g. "$ ")
if strings.TrimSpace(path) == "" {
return nil, NewError(ErrSyntax, "invalid path: trailing whitespace after $", "$"+path)
}
// 移除前导点
dotStripped := false
if strings.HasPrefix(path, ".") {
path = path[1:]
dotStripped = true
}
// Reject whitespace between dot and name (e.g. "$. a" after stripping $)
// Only applies when a dot was actually stripped from the path
if dotStripped && len(path) > 0 && (path[0] == ' ' || path[0] == '\t' || path[0] == '\n' || path[0] == '\r') {
return nil, NewError(ErrSyntax, "whitespace is not allowed between dot and member name", "$")
}
// 处理递归下降
if strings.HasPrefix(path, ".") {
return parseRecursive(path[1:])
}
// 处理常规路径
return parseRegular(path)
}
// isValidFunctionName 检查是否是有效的函数名
func isValidFunctionName(name string) bool {
if name == "" {
return false
}
for i, r := range name {
if i == 0 {
if !((r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || r == '_') {
return false
}
} else {
if !((r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '_') {
return false
}
}
}
return true
}
// parseTopLevelFunctionCall 解析顶层函数调用
func parseTopLevelFunctionCall(funcName, argsStr string) ([]segment, error) {
// 解析参数
args, err := parseFunctionArgsList(argsStr)
if err != nil {
return nil, err
}
// 创建函数段
return []segment{&functionSegment{name: funcName, args: args}}, nil
}
// parseFunctionArgsList 解析函数参数列表
func parseFunctionArgsList(argsStr string) ([]interface{}, error) {
if strings.TrimSpace(argsStr) == "" {
return nil, nil
}
var args []interface{}
var currentArg strings.Builder
var inQuote bool
var quoteChar rune
parenDepth := 0
bracketDepth := 0
for i := 0; i < len(argsStr); i++ {
ch := rune(argsStr[i])
switch {
case (ch == '\'' || ch == '"') && !inQuote:
// 开始引号
inQuote = true
quoteChar = ch
// 不将引号写入 currentArg
case ch == quoteChar && inQuote:
// 结束引号
inQuote = false
quoteChar = 0
// 不将引号写入 currentArg
case ch == '\\' && inQuote && i+1 < len(argsStr):
// 处理转义字符
nextCh := rune(argsStr[i+1])
if nextCh == quoteChar || nextCh == '\\' {
// 转义的引号或反斜杠
currentArg.WriteRune(nextCh)
i++ // 跳过下一个字符
} else {
// 其他转义序列,保持原样
currentArg.WriteRune(ch)
}
case ch == '[' && !inQuote:
bracketDepth++
currentArg.WriteRune(ch)
case ch == ']' && !inQuote:
bracketDepth--
currentArg.WriteRune(ch)
case ch == '(' && !inQuote:
parenDepth++
currentArg.WriteRune(ch)
case ch == ')' && !inQuote:
parenDepth--
currentArg.WriteRune(ch)
case ch == ',' && !inQuote && parenDepth == 0 && bracketDepth == 0:
arg := strings.TrimSpace(currentArg.String())
if arg != "" {
parsedArg, err := parseSingleFunctionArg(arg)
if err != nil {
return nil, err
}
args = append(args, parsedArg)
}
currentArg.Reset()
default:
currentArg.WriteRune(ch)
}
}
// 处理最后一个参数
arg := strings.TrimSpace(currentArg.String())
if arg != "" {
parsedArg, err := parseSingleFunctionArg(arg)
if err != nil {
return nil, err
}
args = append(args, parsedArg)
}
return args, nil
}
// parseSingleFunctionArg 解析单个函数参数
func parseSingleFunctionArg(arg string) (interface{}, error) {
arg = strings.TrimSpace(arg)
// 尝试解析为数字
if num, err := strconv.ParseFloat(arg, 64); err == nil {
return num, nil
}
// 处理布尔值
if arg == "true" {
return true, nil
}
if arg == "false" {
return false, nil
}
// 处理 null
if arg == "null" {
return nil, nil
}
// 如果以 $ 开头,它是一个路径引用
if strings.HasPrefix(arg, "$") {
return arg, nil
}
// 处理 @ 引用(在过滤器上下文中)
if strings.HasPrefix(arg, "@") {
return arg, nil
}
// 其他情况都作为字符串处理(包括正则表达式模式)
return arg, nil
}
// 解析递归下降路径
func parseRecursive(path string) ([]segment, error) {
// Reject bare recursive descent: $..
if path == "" {
return nil, NewError(ErrSyntax, "bare recursive descent is not allowed", "..")
}
// Reject whitespace after recursive descent: $.. a
if path[0] == ' ' || path[0] == '\t' || path[0] == '\n' || path[0] == '\r' {
return nil, NewError(ErrSyntax, "whitespace is not allowed between recursive descent and member name", "..")
}
var segments []segment
segments = append(segments, &recursiveSegment{})
// 移除前导点
path = strings.TrimPrefix(path, ".")
// 如果还有路径,继续解析
if path != "" {
remainingSegments, err := parseRegular(path)
if err != nil {
return nil, err
}
segments = append(segments, remainingSegments...)
}
return segments, nil
}
// 解析常规路径
func parseRegular(path string) ([]segment, error) {
var segments []segment
var current string
afterDot := false
parenDepth := 0
// Use rune iteration to properly handle multi-byte UTF-8 characters
runes := []rune(path)
i := 0
for i < len(runes) {
r := runes[i]
switch {
case r == '[':
if current != "" {
seg, err := createDotSegment(current)
if err != nil {
return nil, err
}
segments = append(segments, seg)
current = ""
}
afterDot = false
// Find the matching closing bracket by counting bracket depth
// This correctly handles nested brackets in filter expressions
depth := 0
j := i + 1
inQuotes := false
inSingleQuotes := false
for j < len(runes) {
ch := runes[j]
// Handle escape sequences inside strings
if (inQuotes || inSingleQuotes) && ch == '\\' && j+1 < len(runes) {
j += 2 // skip the backslash and the next character
continue
}
if ch == '"' && !inSingleQuotes {
inQuotes = !inQuotes
} else if ch == '\'' && !inQuotes {
inSingleQuotes = !inSingleQuotes
} else if !inQuotes && !inSingleQuotes {
if ch == '[' {
depth++
} else if ch == ']' {
if depth == 0 {
break
}
depth--
}
}
j++
}
if j >= len(runes) {
return nil, NewError(ErrSyntax, "unclosed bracket", path)
}
bracketContent := string(runes[i+1 : j])
seg, err := parseBracketSegment(bracketContent)
if err != nil {
return nil, err
}
segments = append(segments, seg)
i = j // advance past the closing ']'
case r == '(' && i == 0:
// Handle leading parenthesis in dot notation
parenDepth++
current += string(r)
afterDot = false
case r == '(':
parenDepth++
current += string(r)
afterDot = false
case r == ')':
parenDepth--
current += string(r)
afterDot = false
case r == '.' && parenDepth == 0:
if afterDot {
// Second dot in ".." → recursive descent
segments = append(segments, &recursiveSegment{})
afterDot = false
} else {
if current != "" {
seg, err := createDotSegment(current)
if err != nil {
return nil, err
}
segments = append(segments, seg)
current = ""
}
afterDot = true
}
case (r == ' ' || r == '\t' || r == '\n' || r == '\r') && parenDepth == 0:
// RFC 9535: whitespace is allowed between root and dot (e.g. "$ .a")
// but NOT between dot and name (e.g. "$. a" is invalid).
if afterDot {
// Whitespace immediately after dot: invalid
return nil, NewError(ErrSyntax, "whitespace is not allowed between dot and member name", path)
}
if current == "" {
// Leading whitespace (e.g. "$ .a"), skip it
} else {
// Whitespace after a name: flush the name as a segment
seg, err := createDotSegment(current)
if err != nil {
return nil, err
}
segments = append(segments, seg)
current = ""
}
default:
current += string(r)
afterDot = false
}
i++
}
// 处理最后一个段
if current != "" {
seg, err := createDotSegment(current)
if err != nil {
return nil, err
}
segments = append(segments, seg)
}
return segments, nil
}
// 创建点表示法段
func createDotSegment(name string) (segment, error) {
if name == "*" {
return &wildcardSegment{}, nil
}
// Only validate non-function names (functions are handled by nameSegmentV3.evaluateFunction)
if !strings.Contains(name, "(") && !isValidMemberName(name) {
return nil, NewError(ErrSyntax, fmt.Sprintf("invalid member name: %s", name), name)
}
return &nameSegment{name: name}, nil
}
// isValidMemberName checks if a name is valid for dot notation per RFC 9535.
// member-name-shorthand = name-first *name-char
// name-first = %x41-5A / "_" / %x61-7A / %x80-10FFFF (letter / "_" / non-ASCII)
// name-char = name-first / %x30-39 (name-first / digit)
func isValidMemberName(name string) bool {
if name == "" {
return false
}
for i, r := range name {
if i == 0 {
if !((r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') || r == '_' || r >= 0x80) {
return false
}
} else {
if !((r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '_' || r >= 0x80) {
return false
}
}
}
return true
}
// 解析方括号段
func parseBracketSegment(content string) (segment, error) {
// RFC 9535: whitespace is allowed around selectors in brackets
content = strings.TrimSpace(content)
// Reject empty brackets: $[]
if content == "" {
return nil, NewError(ErrSyntax, "empty bracket segment", "")
}
// Reject @ outside of filter expression (must be preceded by ?)
if strings.HasPrefix(content, "@") {
return nil, NewError(ErrSyntax, "@ is only allowed inside filter expressions", content)
}
// Reject $ outside of filter expression (must be preceded by ?)
if strings.HasPrefix(content, "$") {
return nil, NewError(ErrSyntax, "$ is only allowed inside filter expressions", content)
}
// Reject space-separated indices: $[0 2]
// After trimming, check if content looks like "0 2" (numbers separated by space)
// But allow whitespace in slice expressions (e.g., "1 :5:2", "1: 5:2")
if strings.Contains(content, " ") && !strings.Contains(content, ",") && !strings.HasPrefix(content, "?") && !strings.HasPrefix(content, "'") && !strings.HasPrefix(content, "\"") && !strings.Contains(content, ":") {
// Check if it looks like space-separated tokens (not just whitespace in a string)
parts := strings.Fields(content)
if len(parts) > 1 {
return nil, NewError(ErrSyntax, "space is not a valid separator in bracket selector, use comma", content)
}
}
// 处理通配符
if content == "*" {
return &wildcardSegment{}, nil
}
// 处理过滤器表达式
if strings.HasPrefix(content, "?") {
// Check if there are multiple selectors (commas at top level)
if hasTopLevelComma(content) {
return parseMultiIndexSegment(content)
}
return parseFilterSegment(content[1:])
}
// 处理多索引选择或多字段选择
if strings.Contains(content, ",") ||
((strings.HasPrefix(content, "'") && strings.HasSuffix(content, "'")) && strings.Contains(content[1:len(content)-1], "','")) ||
((strings.HasPrefix(content, "\"") && strings.HasSuffix(content, "\"")) && strings.Contains(content[1:len(content)-1], "\",\"")) {
return parseMultiIndexSegment(content)
}
// 处理切片表达式
if strings.Contains(content, ":") {
return parseSliceSegment(content)
}
// 处理索引或名称
return parseIndexOrName(content)
}
// hasTopLevelComma checks if content has commas at the top level (not inside parentheses, brackets, or quotes)
func hasTopLevelComma(content string) bool {
inQuotes := false
inSingleQuotes := false
parenDepth := 0
bracketDepth := 0
for i := 0; i < len(content); i++ {
ch := content[i]
if (inQuotes || inSingleQuotes) && ch == '\\' && i+1 < len(content) {
i++ // skip escaped character
continue
}
if ch == '"' && !inSingleQuotes {
inQuotes = !inQuotes
} else if ch == '\'' && !inQuotes {
inSingleQuotes = !inSingleQuotes
} else if !inQuotes && !inSingleQuotes {
if ch == '(' {
parenDepth++
} else if ch == ')' {
parenDepth--
} else if ch == '[' {
bracketDepth++
} else if ch == ']' {
bracketDepth--
} else if ch == ',' && parenDepth == 0 && bracketDepth == 0 {
return true
}
}
}
return false
}
// splitTopLevel splits content by the given delimiter at the top level (not inside parentheses, brackets, or quotes)
func splitTopLevel(content string, delimiter byte) []string {
var parts []string
inQuotes := false
inSingleQuotes := false
parenDepth := 0
bracketDepth := 0
start := 0
for i := 0; i < len(content); i++ {
ch := content[i]
if (inQuotes || inSingleQuotes) && ch == '\\' && i+1 < len(content) {
i++ // skip escaped character
continue
}
if ch == '"' && !inSingleQuotes {
inQuotes = !inQuotes
} else if ch == '\'' && !inQuotes {
inSingleQuotes = !inSingleQuotes
} else if !inQuotes && !inSingleQuotes {
if ch == '(' {
parenDepth++
} else if ch == ')' {
parenDepth--
} else if ch == '[' {
bracketDepth++
} else if ch == ']' {
bracketDepth--
} else if ch == delimiter && parenDepth == 0 && bracketDepth == 0 {
parts = append(parts, content[start:i])
start = i + 1
}
}
}
parts = append(parts, content[start:])
return parts
}
// 标准化过滤器表达式
func normalizeFilterExpression(expr string) string {
expr = strings.TrimSpace(expr)
return expr
}
// expressionParser is a recursive descent parser for filter expressions
type expressionParser struct {
input string
pos int
}
// parseFilterExpression parses a filter expression string into an expression tree
func parseFilterExpression(input string) (exprNode, error) {
p := &expressionParser{input: input, pos: 0}
node, err := p.parseOr()
if err != nil {
return nil, err
}
p.skipSpaces()
if p.pos < len(p.input) {
return nil, NewError(ErrInvalidFilter, fmt.Sprintf("unexpected character at position %d: %c", p.pos, p.input[p.pos]), input)
}
return node, nil
}
func (p *expressionParser) skipSpaces() {
for p.pos < len(p.input) && p.input[p.pos] == ' ' {
p.pos++
}
}
func (p *expressionParser) parseOr() (exprNode, error) {
left, err := p.parseAnd()
if err != nil {
return nil, err
}
children := []exprNode{left}
for {
p.skipSpaces()
if p.pos+1 < len(p.input) && p.input[p.pos:p.pos+2] == "||" {
p.pos += 2
right, err := p.parseAnd()
if err != nil {
return nil, err
}
children = append(children, right)
} else {
break
}
}
if len(children) == 1 {
return children[0], nil
}
return &orNode{children: children}, nil
}
func (p *expressionParser) parseAnd() (exprNode, error) {
left, err := p.parseUnary()
if err != nil {
return nil, err
}
children := []exprNode{left}
for {
p.skipSpaces()
if p.pos+1 < len(p.input) && p.input[p.pos:p.pos+2] == "&&" {
p.pos += 2
right, err := p.parseUnary()
if err != nil {
return nil, err
}
children = append(children, right)
} else {
break
}
}
if len(children) == 1 {
return children[0], nil
}
return &andNode{children: children}, nil
}
func (p *expressionParser) parseUnary() (exprNode, error) {
p.skipSpaces()
if p.pos < len(p.input) && p.input[p.pos] == '!' {
p.pos++
inner, err := p.parsePrimary()
if err != nil {
return nil, err
}
return negateNode(inner)
}
return p.parsePrimary()
}
func (p *expressionParser) parsePrimary() (exprNode, error) {
p.skipSpaces()
if p.pos >= len(p.input) {
return nil, NewError(ErrInvalidFilter, "unexpected end of expression", p.input)
}
// Handle parenthesized expression
if p.input[p.pos] == '(' {
p.pos++ // skip '('
node, err := p.parseOr()
if err != nil {
return nil, err
}
p.skipSpaces()
if p.pos >= len(p.input) || p.input[p.pos] != ')' {
return nil, NewError(ErrInvalidFilter, "missing closing parenthesis", p.input)
}
p.pos++ // skip ')'
return node, nil
}
// Parse atomic condition (everything until next &&, ||, or unmatched )) or ])
start := p.pos
depth := 0
bracketDepth := 0
inQuotes := false
inSingleQuotes := false
for p.pos < len(p.input) {
ch := p.input[p.pos]
// Handle escape sequences inside strings
if (inQuotes || inSingleQuotes) && ch == '\\' && p.pos+1 < len(p.input) {
p.pos += 2 // skip backslash and the escaped character
continue
}
if ch == '"' && !inSingleQuotes {
inQuotes = !inQuotes
p.pos++
continue
}
if ch == '\'' && !inQuotes {
inSingleQuotes = !inSingleQuotes
p.pos++
continue
}
if inQuotes || inSingleQuotes {
p.pos++
continue
}
if ch == '(' {
depth++
p.pos++
continue
}
if ch == ')' {
if depth == 0 {
break
}
depth--
p.pos++
continue
}
if ch == '[' {
bracketDepth++
p.pos++
continue
}
if ch == ']' {
if bracketDepth == 0 {
break
}
bracketDepth--
p.pos++
continue
}
// Check for top-level && or ||
if depth == 0 && bracketDepth == 0 && p.pos+1 < len(p.input) {
op := p.input[p.pos : p.pos+2]
if op == "&&" || op == "||" {
break
}
}
p.pos++
}
condStr := strings.TrimSpace(p.input[start:p.pos])
if condStr == "" {
return nil, NewError(ErrInvalidFilter, "empty condition", p.input)
}
cond, err := parseFilterCondition(condStr)
if err != nil {
return nil, err
}
return &conditionNode{cond: cond}, nil
}
// negateNode applies negation to an expression node
func negateNode(node exprNode) (exprNode, error) {
switch n := node.(type) {
case *conditionNode:
newCond := n.cond
switch newCond.operator {
case "==":
newCond.operator = "!="
case "!=":
newCond.operator = "=="
case "<":
newCond.operator = ">="
case "<=":
newCond.operator = ">"
case ">":
newCond.operator = "<="
case ">=":
newCond.operator = "<"
case "exists":
newCond.operator = "not_exists"
case "not_exists":
newCond.operator = "exists"
case "match":
newCond.operator = "not_match"
case "not_match":
newCond.operator = "match"
case "search":
newCond.operator = "not_search"
case "not_search":
newCond.operator = "search"
default:
return nil, NewError(ErrInvalidFilter, fmt.Sprintf("cannot negate operator: %s", newCond.operator), "")
}
return &conditionNode{cond: newCond}, nil
case *andNode:
children := make([]exprNode, len(n.children))
for i, child := range n.children {
negated, err := negateNode(child)
if err != nil {
return nil, err
}
children[i] = negated
}
return &orNode{children: children}, nil
case *orNode:
children := make([]exprNode, len(n.children))
for i, child := range n.children {
negated, err := negateNode(child)
if err != nil {
return nil, err
}
children[i] = negated
}
return &andNode{children: children}, nil
default:
return nil, NewError(ErrInvalidFilter, "cannot negate expression", "")
}
}
// normalizeFilterWhitespace handles whitespace in filter expressions
// Removes whitespace between ! and ( to support expressions like "!\n(@.a=='b')"
func normalizeFilterWhitespace(content string) string {
if len(content) < 2 {
return content
}
// Check if content starts with ! followed by whitespace and then (
if content[0] == '!' {
// Find the first non-whitespace character after !
i := 1
for i < len(content) && (content[i] == ' ' || content[i] == '\t' || content[i] == '\n' || content[i] == '\r') {
i++
}
if i < len(content) && content[i] == '(' {
// Remove whitespace between ! and (
return "!" + content[i:]
}
}
return content
}
// 解析过滤器表达式
func parseFilterSegment(content string) (segment, error) {
// RFC 9535: allow whitespace in filter expressions
content = strings.TrimSpace(content)
// 检查是否是完整的函数调用格式: functionName(arg1, arg2)
// 使用 tryParseFunctionCall 进行正确的括号匹配
if funcName, argsStr, ok := tryParseFunctionCall(content); ok {
cond, err := parseFilterFunctionCall(funcName, argsStr)
if err != nil {
return nil, NewError(ErrInvalidFilter, fmt.Sprintf("invalid filter syntax: %s", content), content)
}
return &filterSegment{expr: &conditionNode{cond: cond}}, nil
}
// 检查语法 - 支持 @, $, 函数调用, 和 ! 作为过滤器表达式的开头
trimmed := strings.TrimSpace(content)
isFunctionCallExpr := false
if !strings.HasPrefix(trimmed, "@") && !strings.HasPrefix(trimmed, "$") &&
!strings.HasPrefix(trimmed, "(@") && !strings.HasPrefix(trimmed, "($") &&
!strings.HasPrefix(trimmed, "!") && !strings.HasPrefix(trimmed, "(!") &&
!strings.HasPrefix(trimmed, "(") {
// Check if it starts with a function name (e.g., count(@..*)>2, length(@.a)>=2)
if idx := strings.Index(trimmed, "("); idx > 0 {
funcName := trimmed[:idx]
if !isValidFunctionName(funcName) {
return nil, NewError(ErrInvalidFilter, fmt.Sprintf("invalid filter syntax: %s", content), content)
}
// Check if there's a top-level comparison operator (not inside function parens)
// If so, it's a comparison expression, not a standalone function call
if hasTopLevelOperator(trimmed) {
// It's a comparison expression with function calls - pass to expression parser
isFunctionCallExpr = true
} else {
// Standalone function call - pass to expression parser
isFunctionCallExpr = true
}
} else {
return nil, NewError(ErrInvalidFilter, fmt.Sprintf("invalid filter syntax: %s", content), content)
}
}
// Normalize whitespace: remove whitespace between ! and (
// e.g., "!\n(@.a=='b')" becomes "(!@.a=='b')"
content = normalizeFilterWhitespace(content)
// 取过滤器内容
var filterContent string
switch {
case isFunctionCallExpr:
// Function call expression (e.g., count(@..*)>2) - pass to expression parser
filterContent = content
case strings.HasPrefix(content, "(!"):
if !strings.HasSuffix(content, ")") {
return nil, NewError(ErrInvalidFilter, "invalid filter syntax: missing closing parenthesis", content)
}
filterContent = content[2 : len(content)-1]
// Apply De Morgan's laws: !(A && B) => !A || !B, !(A || B) => !A && !B
expr, err := parseFilterExpression(filterContent)
if err != nil {
return nil, NewError(ErrInvalidFilter, fmt.Sprintf("error parsing filter expression: %v", err), content)
}
negated, err := negateNode(expr)
if err != nil {
return nil, NewError(ErrInvalidFilter, fmt.Sprintf("error negating expression: %v", err), content)
}
return &filterSegment{expr: negated}, nil
case strings.HasPrefix(content, "!@"):
// Keep the ! in the content for the parser to handle as unary operator
filterContent = content
case strings.HasPrefix(content, "(@"):
// Check if outer parens match properly
depth := 0
matchIdx := -1
for i := 0; i < len(content); i++ {
if content[i] == '(' {
depth++
} else if content[i] == ')' {
depth--
if depth == 0 {
matchIdx = i
break
}
}
}
if matchIdx == len(content)-1 {
// The first '(' matches the last ')' - strip outer (@...)
filterContent = content[2 : len(content)-1]
} else {
// The first '(' doesn't match the last ')' - pass whole content to parser
// e.g., "(@.a || @.b) && @.c"
filterContent = content
}
case strings.HasPrefix(content, "($"):
// Check if outer parens match properly
depth := 0
matchIdx := -1
for i := 0; i < len(content); i++ {
if content[i] == '(' {
depth++
} else if content[i] == ')' {
depth--
if depth == 0 {
matchIdx = i
break
}
}
}
if matchIdx == len(content)-1 {
// The first '(' matches the last ')' - strip outer ($...)
filterContent = content[2 : len(content)-1]
} else {
// The first '(' doesn't match the last ')' - pass whole content to parser
filterContent = content
}
case strings.HasPrefix(content, "@"):
filterContent = content
case strings.HasPrefix(content, "$"):
filterContent = content
case strings.HasPrefix(content, "!"):
// Keep the ! in the content for the parser to handle as unary operator
filterContent = content
// Check for !(expr) pattern
if len(content) > 1 && content[1] == '(' {
if !strings.HasSuffix(content, ")") {
return nil, NewError(ErrInvalidFilter, "invalid filter syntax: missing closing parenthesis", content)
}
// Apply De Morgan's laws for !(expr)
innerContent := content[2 : len(content)-1]
expr, err := parseFilterExpression(innerContent)
if err != nil {
return nil, NewError(ErrInvalidFilter, fmt.Sprintf("error parsing filter expression: %v", err), content)
}
negated, err := negateNode(expr)
if err != nil {
return nil, NewError(ErrInvalidFilter, fmt.Sprintf("error negating expression: %v", err), content)
}
return &filterSegment{expr: negated}, nil
}
case strings.HasPrefix(content, "("):
// Check if the outer parens actually match (not just first and last char)
depth := 0
matchingIdx := -1
for i := 0; i < len(content); i++ {
if content[i] == '(' {
depth++
} else if content[i] == ')' {
depth--
if depth == 0 {
matchingIdx = i
break
}
}
}
if matchingIdx == len(content)-1 {
// The first '(' matches the last ')' - strip outer parens
filterContent = content[1 : len(content)-1]
} else {
// The first '(' doesn't match the last ')' - pass whole content to parser
// e.g., "(@.a || @.b) && @.c"
filterContent = content
}
default:
filterContent = content
}
// 标准化表达式
filterContent = normalizeFilterExpression(filterContent)
// 解析表达式为树结构
expr, err := parseFilterExpression(filterContent)
if err != nil {
return nil, NewError(ErrInvalidFilter, fmt.Sprintf("error parsing filter expression: %v", err), content)
}