-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.go
More file actions
782 lines (682 loc) · 18.7 KB
/
functions.go
File metadata and controls
782 lines (682 loc) · 18.7 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
package jsonpath
import (
"encoding/json"
"fmt"
"math"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"unicode/utf8"
)
// Function represents a JSONPath function
type Function interface {
Call(args []interface{}) (interface{}, error)
Name() string
}
// builtinFunction is a helper type for implementing Function interface
type builtinFunction struct {
name string
callback func([]interface{}) (interface{}, error)
}
func (f *builtinFunction) Call(args []interface{}) (interface{}, error) {
return f.callback(args)
}
func (f *builtinFunction) Name() string {
return f.name
}
// regexCache 用于缓存编译后的正则表达式
var regexCache = make(map[string]*regexp.Regexp)
var regexCacheMutex sync.RWMutex
// getCompiledRegex 从缓存中获取或编译正则表达式
func getCompiledRegex(pattern string) (*regexp.Regexp, error) {
// 先尝试从缓存中读取
regexCacheMutex.RLock()
if re, ok := regexCache[pattern]; ok {
regexCacheMutex.RUnlock()
return re, nil
}
regexCacheMutex.RUnlock()
// 如果缓存中没有,则编译正则表达式
re, err := regexp.Compile(pattern)
if err != nil {
return nil, err
}
// 将编译后的正则表达式存入缓存
regexCacheMutex.Lock()
regexCache[pattern] = re
regexCacheMutex.Unlock()
return re, nil
}
// removeAnchors 移除模式中的 ^ 和 $ 锚点
func removeAnchors(pattern string) string {
if len(pattern) == 0 {
return pattern
}
// 移除开头的 ^
if pattern[0] == '^' {
pattern = pattern[1:]
}
// 移除结尾的 $
if len(pattern) > 0 && pattern[len(pattern)-1] == '$' {
pattern = pattern[:len(pattern)-1]
}
return pattern
}
// numberType 表示数值类型
type numberType int
const (
numberTypeInteger numberType = iota
numberTypeFloat
numberTypeNaN
numberTypeInfinity
numberTypeNegativeInfinity
)
// numberValue 表示标准化的数值
type numberValue struct {
typ numberType
value float64
}
// convertToNumber 将任意值转换为标准化的数值
func convertToNumber(v interface{}) (numberValue, error) {
switch val := v.(type) {
case int:
return numberValue{typ: numberTypeInteger, value: float64(val)}, nil
case int32:
return numberValue{typ: numberTypeInteger, value: float64(val)}, nil
case int64:
return numberValue{typ: numberTypeInteger, value: float64(val)}, nil
case float32:
if isNaN32(float32(val)) {
return numberValue{typ: numberTypeNaN}, nil
}
if isInf32(float32(val), 1) {
return numberValue{typ: numberTypeInfinity, value: 1}, nil
}
if isInf32(float32(val), -1) {
return numberValue{typ: numberTypeNegativeInfinity, value: -1}, nil
}
return numberValue{typ: numberTypeFloat, value: float64(val)}, nil
case float64:
if math.IsNaN(val) {
return numberValue{typ: numberTypeNaN}, nil
}
if math.IsInf(val, 1) {
return numberValue{typ: numberTypeInfinity, value: 1}, nil
}
if math.IsInf(val, -1) {
return numberValue{typ: numberTypeNegativeInfinity, value: -1}, nil
}
if val == float64(int64(val)) {
return numberValue{typ: numberTypeInteger, value: val}, nil
}
return numberValue{typ: numberTypeFloat, value: val}, nil
case json.Number:
if f, err := val.Float64(); err == nil {
return convertToNumber(f)
}
if i, err := val.Int64(); err == nil {
return numberValue{typ: numberTypeInteger, value: float64(i)}, nil
}
return numberValue{}, fmt.Errorf("invalid number: %v", val)
case string:
if f, err := strconv.ParseFloat(val, 64); err == nil {
return convertToNumber(f)
}
return numberValue{}, fmt.Errorf("invalid number string: %v", val)
default:
return numberValue{}, fmt.Errorf("cannot convert to number: %v", v)
}
}
// compareNumberValues 比较两个数值
func compareNumberValues(a, b numberValue) int {
// 处理特殊值
if a.typ == numberTypeNaN || b.typ == numberTypeNaN {
return 0 // NaN 等于 NaN,不等于其他任何值
}
if a.typ == numberTypeInfinity {
if b.typ == numberTypeInfinity {
return 0
}
return 1
}
if a.typ == numberTypeNegativeInfinity {
if b.typ == numberTypeNegativeInfinity {
return 0
}
return -1
}
if b.typ == numberTypeInfinity {
return -1
}
if b.typ == numberTypeNegativeInfinity {
return 1
}
// 处理普通数值
diff := a.value - b.value
if math.Abs(diff) < 1e-10 { // 使用精度阈值处理浮点数比较
return 0
}
if diff > 0 {
return 1
}
return -1
}
// isNaN32 检查 float32 是否为 NaN
func isNaN32(f float32) bool {
return f != f
}
// isInf32 检查 float32 是否为 Infinity
func isInf32(f float32, sign int) bool {
return math.IsInf(float64(f), sign)
}
// globalFunctions is the registry of built-in functions
var globalFunctions = map[string]Function{
"length": &builtinFunction{
name: "length",
callback: func(args []interface{}) (interface{}, error) {
if len(args) != 1 {
return nil, fmt.Errorf("length() requires exactly 1 argument")
}
// 如果参数是数组,返回数组长度
if arr, ok := args[0].([]interface{}); ok {
return float64(len(arr)), nil
}
// 如果参数是字符串,返回字符串长度
if str, ok := args[0].(string); ok {
return float64(utf8.RuneCountInString(str)), nil
}
// 如果参数是对象,返回对象的键数量
if obj, ok := args[0].(map[string]interface{}); ok {
return float64(len(obj)), nil
}
return nil, fmt.Errorf("length() argument must be string, array, or object")
},
},
"keys": &builtinFunction{
name: "keys",
callback: func(args []interface{}) (interface{}, error) {
if len(args) != 1 {
return nil, fmt.Errorf("keys() requires exactly 1 argument")
}
// 确保参数是对象
obj, ok := args[0].(map[string]interface{})
if !ok {
return nil, fmt.Errorf("keys() argument must be an object")
}
// 获取所有键并排序
keys := make([]string, 0, len(obj))
for k := range obj {
keys = append(keys, k)
}
sort.Strings(keys) // 按字母顺序排序
// 转换为 interface{} 切片
result := make([]interface{}, len(keys))
for i, k := range keys {
result[i] = k
}
return result, nil
},
},
"values": &builtinFunction{
name: "values",
callback: func(args []interface{}) (interface{}, error) {
if len(args) != 1 {
return nil, fmt.Errorf("values() requires exactly 1 argument")
}
// 确保参数是对象
obj, ok := args[0].(map[string]interface{})
if !ok {
return nil, fmt.Errorf("values() argument must be an object")
}
// 获取所有键并排序,以确保值的顺序一致
keys := make([]string, 0, len(obj))
for k := range obj {
keys = append(keys, k)
}
sort.Strings(keys)
// 按键的顺序获取值
values := make([]interface{}, len(keys))
for i, k := range keys {
values[i] = obj[k]
}
return values, nil
},
},
// RFC 9535 count() - counts nodes in a nodelist
"count": &builtinFunction{
name: "count",
callback: func(args []interface{}) (interface{}, error) {
if len(args) != 1 {
return nil, fmt.Errorf("count() requires exactly 1 argument")
}
// 如果参数是数组,返回数组长度
if arr, ok := args[0].([]interface{}); ok {
return float64(len(arr)), nil
}
// 如果参数是 NodeList (通过反射检查)
// NodeList 在运行时是 []interface{} 类型
return nil, fmt.Errorf("count() argument must be a nodelist")
},
},
// Non-standard extension: occurrences() - counts value occurrences in an array
"occurrences": &builtinFunction{
name: "occurrences",
callback: func(args []interface{}) (interface{}, error) {
if len(args) != 2 {
return nil, fmt.Errorf("occurrences() requires exactly 2 arguments: array and value")
}
// 确保第一个参数是数组
arr, ok := args[0].([]interface{})
if !ok {
return nil, fmt.Errorf("occurrences() first argument must be an array")
}
// 计算匹配值的数量
count := 0
for _, item := range arr {
if reflect.DeepEqual(item, args[1]) {
count++
}
}
return float64(count), nil
},
},
"min": &builtinFunction{
name: "min",
callback: func(args []interface{}) (interface{}, error) {
if len(args) != 1 {
return nil, fmt.Errorf("min() requires exactly 1 argument")
}
// 确保参数是数组
arr, ok := args[0].([]interface{})
if !ok {
return nil, fmt.Errorf("min() argument must be an array")
}
if len(arr) == 0 {
return nil, fmt.Errorf("min() cannot be applied to an empty array")
}
var minVal *numberValue
for _, item := range arr {
num, err := convertToNumber(item)
if err != nil {
continue // 跳过无效的数值
}
// 跳过 NaN
if num.typ == numberTypeNaN {
continue
}
if minVal == nil {
minVal = &num
continue
}
if compareNumberValues(num, *minVal) < 0 {
minVal = &num
}
}
if minVal == nil {
return nil, fmt.Errorf("min() no valid numbers in array")
}
// 返回原始类型的值
if minVal.typ == numberTypeInteger {
return int64(minVal.value), nil
}
return minVal.value, nil
},
},
"max": &builtinFunction{
name: "max",
callback: func(args []interface{}) (interface{}, error) {
if len(args) != 1 {
return nil, fmt.Errorf("max() requires exactly 1 argument")
}
// 确保参数是数组
arr, ok := args[0].([]interface{})
if !ok {
return nil, fmt.Errorf("max() argument must be an array")
}
if len(arr) == 0 {
return nil, fmt.Errorf("max() cannot be applied to an empty array")
}
var maxVal *numberValue
for _, item := range arr {
num, err := convertToNumber(item)
if err != nil {
continue // 跳过无效的数值
}
// 跳过 NaN
if num.typ == numberTypeNaN {
continue
}
if maxVal == nil {
maxVal = &num
continue
}
if compareNumberValues(num, *maxVal) > 0 {
maxVal = &num
}
}
if maxVal == nil {
return nil, fmt.Errorf("max() no valid numbers in array")
}
// 返回原始类型的值
if maxVal.typ == numberTypeInteger {
return int64(maxVal.value), nil
}
return maxVal.value, nil
},
},
"avg": &builtinFunction{
name: "avg",
callback: func(args []interface{}) (interface{}, error) {
if len(args) != 1 {
return nil, fmt.Errorf("avg() requires exactly 1 argument")
}
// 确保参数是数组
arr, ok := args[0].([]interface{})
if !ok {
return nil, fmt.Errorf("avg() argument must be an array")
}
if len(arr) == 0 {
return nil, fmt.Errorf("avg() cannot be applied to an empty array")
}
var sum float64
count := 0
for _, item := range arr {
num, err := convertToNumber(item)
if err != nil {
continue // 跳过无效的数值
}
// 跳过特殊值
if num.typ == numberTypeNaN ||
num.typ == numberTypeInfinity ||
num.typ == numberTypeNegativeInfinity {
continue
}
sum += num.value
count++
}
if count == 0 {
return nil, fmt.Errorf("avg() no valid numbers in array")
}
result := sum / float64(count)
if result == float64(int64(result)) {
return int64(result), nil
}
return result, nil
},
},
"sum": &builtinFunction{
name: "sum",
callback: func(args []interface{}) (interface{}, error) {
if len(args) != 1 {
return nil, fmt.Errorf("sum() requires exactly 1 argument")
}
// 确保参数是数组
arr, ok := args[0].([]interface{})
if !ok {
return nil, fmt.Errorf("sum() argument must be an array")
}
if len(arr) == 0 {
return nil, fmt.Errorf("sum() cannot be applied to an empty array")
}
var sum float64
count := 0
allIntegers := true
for _, item := range arr {
num, err := convertToNumber(item)
if err != nil {
continue // 跳过无效的数值
}
// 跳过特殊值
if num.typ == numberTypeNaN ||
num.typ == numberTypeInfinity ||
num.typ == numberTypeNegativeInfinity {
continue
}
if num.typ == numberTypeFloat {
allIntegers = false
}
sum += num.value
count++
}
if count == 0 {
return nil, fmt.Errorf("sum() no valid numbers in array")
}
// 如果所有数都是整数且结果也是整数,返回整数类型
if allIntegers && sum == float64(int64(sum)) {
return int64(sum), nil
}
return sum, nil
},
},
// RFC 9535 match() - function-style: match(string, pattern)
// Uses I-Regexp for full-string matching
"match": &builtinFunction{
name: "match",
callback: func(args []interface{}) (interface{}, error) {
// 1. 验证参数数量
if len(args) != 2 {
return nil, fmt.Errorf("match() requires exactly 2 arguments: string and pattern")
}
// 2. 获取并验证第二个参数(正则表达式模式)
pattern, ok := args[1].(string)
if !ok {
return nil, fmt.Errorf("match() second argument must be a string pattern")
}
// 3. 处理空模式
if pattern == "" {
return false, nil
}
// 4. 获取第一个参数(要匹配的字符串)
var str string
switch v := args[0].(type) {
case string:
str = v
default:
// 对于非字符串值,返回 false
return false, nil
}
// 5. 将 I-Regexp 转换为 Go regexp
goPattern, err := IRegexpToGoRegexp(pattern)
if err != nil {
return false, nil // 无效模式返回 false
}
// 6. 对于 match() 函数,我们需要全字符串匹配
// 移除现有的锚点,然后添加全字符串匹配
goPattern = removeAnchors(goPattern)
goPattern = "\\A(?:" + goPattern + ")\\z"
// 7. 获取或编译正则表达式
re, err := getCompiledRegex(goPattern)
if err != nil {
return false, nil // 正则表达式语法错误时返回 false
}
// 8. 执行匹配
return re.MatchString(str), nil
},
},
// RFC 9535 search() - function-style: search(string, pattern)
// Returns true if string contains a match for the I-Regexp pattern
"search": &builtinFunction{
name: "search",
callback: func(args []interface{}) (interface{}, error) {
// 1. 验证参数数量
if len(args) != 2 {
return nil, fmt.Errorf("search() requires exactly 2 arguments: string and pattern")
}
// 2. 获取并验证第二个参数(正则表达式模式)
pattern, ok := args[1].(string)
if !ok {
return nil, fmt.Errorf("search() second argument must be a string pattern")
}
// 3. 处理空模式
if pattern == "" {
return true, nil // 空模式匹配任何字符串
}
// 4. 获取第一个参数(要搜索的字符串)
var str string
switch v := args[0].(type) {
case string:
str = v
default:
return nil, fmt.Errorf("search() first argument must be a string")
}
// 5. 将 I-Regexp 转换为 Go regexp
goPattern, err := IRegexpToGoRegexp(pattern)
if err != nil {
return nil, fmt.Errorf("invalid I-Regexp pattern: %v", err)
}
// 6. 获取或编译正则表达式
re, err := getCompiledRegex(goPattern)
if err != nil {
return nil, fmt.Errorf("invalid regular expression: %v", err)
}
// 7. 执行搜索
return re.MatchString(str), nil
},
},
// Non-standard extension: filterMatch() - filters array by regex
// Renamed from the old search() function
"filterMatch": &builtinFunction{
name: "filterMatch",
callback: func(args []interface{}) (interface{}, error) {
// 1. 验证参数数量
if len(args) != 2 {
return nil, fmt.Errorf("filterMatch() requires exactly 2 arguments")
}
// 2. 获取数组参数
arr, ok := args[0].([]interface{})
if !ok {
return nil, fmt.Errorf("first argument must be an array")
}
// 3. 获取正则表达式参数
pattern, ok := args[1].(string)
if !ok {
return nil, fmt.Errorf("second argument must be a string pattern")
}
// 4. 处理转义字符
var result strings.Builder
var escaped bool
var inCharClass bool
for i := 0; i < len(pattern); i++ {
ch := pattern[i]
if escaped {
switch ch {
case 'd', 'D', 'w', 'W', 's', 'S', 'b', 'B':
// 保持原样的特殊字符序列
result.WriteByte('\\')
result.WriteByte(ch)
case 'n':
result.WriteString(`\n`)
case 'r':
result.WriteString(`\r`)
case 't':
result.WriteString(`\t`)
case '[', ']', '(', ')', '{', '}', '\\', '.', '*', '+', '?', '|', '^', '$':
// 转义元字符
result.WriteByte(ch)
case 'p', 'P':
// 处理 Unicode 属性
result.WriteByte('\\')
result.WriteByte(ch)
if i+1 < len(pattern) && pattern[i+1] == '{' {
i++ // 跳过 '{'
result.WriteByte('{')
for i+1 < len(pattern) && pattern[i+1] != '}' {
i++
result.WriteByte(pattern[i])
}
if i+1 < len(pattern) && pattern[i+1] == '}' {
i++
result.WriteByte('}')
}
}
default:
if inCharClass {
result.WriteByte(ch)
} else {
result.WriteByte(ch)
}
}
escaped = false
} else if ch == '\\' {
escaped = true
} else if ch == '[' {
inCharClass = true
result.WriteByte(ch)
} else if ch == ']' {
inCharClass = false
result.WriteByte(ch)
} else {
result.WriteByte(ch)
}
}
// 处理末尾的反斜杠
if escaped {
result.WriteByte('\\')
}
pattern = result.String()
// 5. 获取或编译正则表达式
re, err := getCompiledRegex(pattern)
if err != nil {
return nil, fmt.Errorf("invalid regular expression: %v", err)
}
// 6. 搜索匹配的元素
matches := make([]interface{}, 0)
for _, item := range arr {
var str string
switch v := item.(type) {
case string:
str = v
case float64:
str = strconv.FormatFloat(v, 'f', -1, 64)
case int:
str = strconv.Itoa(v)
case bool:
str = strconv.FormatBool(v)
case nil:
str = "null"
default:
// 尝试将其他类型转换为 JSON 字符串
if jsonBytes, err := json.Marshal(v); err == nil {
str = string(jsonBytes)
} else {
continue // 跳过无法转换的值
}
}
if re.MatchString(str) {
matches = append(matches, item) // 保持原始值类型
}
}
return matches, nil
},
},
// RFC 9535 value() - extracts a single value from a nodelist
"value": &builtinFunction{
name: "value",
callback: func(args []interface{}) (interface{}, error) {
if len(args) != 1 {
return nil, fmt.Errorf("value() requires exactly 1 argument")
}
// 参数必须是数组(NodeList)
arr, ok := args[0].([]interface{})
if !ok {
return nil, fmt.Errorf("value() argument must be a nodelist")
}
// 如果恰好有一个节点,返回其值
if len(arr) == 1 {
return arr[0], nil
}
// 否则返回 Nothing
return Nothing{}, nil
},
},
}
// GetFunction returns a registered function by name
func GetFunction(name string) (Function, error) {
if f, exists := globalFunctions[name]; exists {
return f, nil
}
return nil, fmt.Errorf("function %s not found", name)
}