-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoperators.go
More file actions
818 lines (732 loc) · 18.8 KB
/
Copy pathoperators.go
File metadata and controls
818 lines (732 loc) · 18.8 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
package jinja
import (
"fmt"
"math"
"reflect"
"strconv"
"strings"
)
// IsTruthy determines if a value is considered "truthy" in the Python/Jinja2 sense
func IsTruthy(value interface{}) bool {
if value == nil {
return false
}
switch v := value.(type) {
case UndefinedType:
return false
case bool:
return v
case int:
return v != 0
case float64:
return v != 0
case string:
return v != ""
case []interface{}:
return len(v) > 0
case map[string]interface{}:
return len(v) > 0
default:
// Try reflection for slices and maps
rv := reflect.ValueOf(value)
kind := rv.Kind()
if kind == reflect.Slice || kind == reflect.Array || kind == reflect.Map {
return rv.Len() > 0
}
// For other types, treat as truthy by default
return true
}
}
// negateValue negates a numeric value
func negateValue(value interface{}) (interface{}, error) {
switch v := value.(type) {
case int:
return -v, nil
case float64:
return -v, nil
default:
return nil, fmt.Errorf("cannot apply unary minus to non-numeric type: %T", value)
}
}
// equals checks if two values are equal, with type coercion rules similar to Python
func equals(left, right interface{}) (bool, error) {
// Handle nil/None values
if left == nil && right == nil {
return true, nil
}
if left == nil || right == nil {
return false, nil
}
// Type-specific equality
switch l := left.(type) {
case string:
if r, ok := right.(string); ok {
return l == r, nil
}
case int:
switch r := right.(type) {
case int:
return l == r, nil
case float64:
return float64(l) == r, nil
}
case float64:
switch r := right.(type) {
case int:
return l == float64(r), nil
case float64:
return l == r, nil
}
case bool:
if r, ok := right.(bool); ok {
return l == r, nil
}
case []interface{}:
if r, ok := right.([]interface{}); ok {
// Special case for empty slices - both empty slices should be equal
if len(l) == 0 && len(r) == 0 {
return true, nil
}
if len(l) != len(r) {
return false, nil
}
for i := range l {
eq, err := equals(l[i], r[i])
if err != nil {
return false, err
}
if !eq {
return false, nil
}
}
return true, nil
}
case map[string]interface{}:
if r, ok := right.(map[string]interface{}); ok {
if len(l) != len(r) {
return false, nil
}
for k, v := range l {
rv, ok := r[k]
if !ok {
return false, nil
}
eq, err := equals(v, rv)
if err != nil {
return false, err
}
if !eq {
return false, nil
}
}
return true, nil
}
}
// Default to structural equality using reflect.DeepEqual
return reflect.DeepEqual(left, right), nil
}
// CompareOp represents a comparison operation
type CompareOp int
const (
OpLT CompareOp = iota // <
OpLE // <=
OpGT // >
OpGE // >=
OpEQ // ==
OpNE // !=
)
// compare performs a comparison operation between two values
func compare(left, right interface{}, op CompareOp) (interface{}, error) {
// Handle nil values
if left == nil && right == nil {
return op == OpEQ, nil
}
if left == nil || right == nil {
return op == OpNE, nil
}
// Skip comparing for equality operations
switch op {
case OpEQ:
return equals(left, right)
case OpNE:
eq, err := equals(left, right)
return !eq, err
}
// Try direct type matching first for better performance and precision
switch l := left.(type) {
case int:
if r, ok := right.(int); ok {
return compareInts(l, r, op), nil
}
if r, ok := right.(float64); ok {
return compareFloat64s(float64(l), r, op), nil
}
case float64:
if r, ok := right.(float64); ok {
return compareFloat64s(l, r, op), nil
}
if r, ok := right.(int); ok {
return compareFloat64s(l, float64(r), op), nil
}
case string:
if r, ok := right.(string); ok {
return compareStrings(l, r, op), nil
}
// Try to parse both as numbers if one is a string
if lFloat, err := strconv.ParseFloat(l, 64); err == nil {
if rFloat, err2 := toFloat(right); err2 == nil {
return compareFloat64s(lFloat, rFloat, op), nil
}
}
case bool:
if r, ok := right.(bool); ok {
return compareBools(l, r, op), nil
}
}
// Fallback to float conversion for mixed numeric types
leftFloat, err := toFloat(left)
if err != nil {
return nil, fmt.Errorf("cannot compare %T with %T", left, right)
}
rightFloat, err := toFloat(right)
if err != nil {
return nil, fmt.Errorf("cannot compare %T with %T", left, right)
}
return compareFloat64s(leftFloat, rightFloat, op), nil
}
// compareInts compares two integers directly
func compareInts(left, right int, op CompareOp) bool {
switch op {
case OpLT:
return left < right
case OpLE:
return left <= right
case OpGT:
return left > right
case OpGE:
return left >= right
case OpEQ:
return left == right
case OpNE:
return left != right
default:
return false
}
}
// compareFloat64s compares two float64 values
func compareFloat64s(left, right float64, op CompareOp) bool {
switch op {
case OpLT:
return left < right
case OpLE:
return left <= right
case OpGT:
return left > right
case OpGE:
return left >= right
case OpEQ:
return left == right
case OpNE:
return left != right
default:
return false
}
}
// compareStrings compares two strings lexicographically
func compareStrings(left, right string, op CompareOp) bool {
cmp := strings.Compare(left, right)
switch op {
case OpLT:
return cmp < 0
case OpLE:
return cmp <= 0
case OpGT:
return cmp > 0
case OpGE:
return cmp >= 0
case OpEQ:
return cmp == 0
case OpNE:
return cmp != 0
default:
return false
}
}
// compareBools compares two boolean values
func compareBools(left, right bool, op CompareOp) bool {
switch op {
case OpLT:
return !left && right // false < true
case OpLE:
return !left || left == right
case OpGT:
return left && !right // true > false
case OpGE:
return left || left == right
case OpEQ:
return left == right
case OpNE:
return left != right
default:
return false
}
}
// toFloat converts a value to a float64 for comparison operations
func toFloat(value interface{}) (float64, error) {
switch v := value.(type) {
case int:
return float64(v), nil
case int8:
return float64(v), nil
case int16:
return float64(v), nil
case int32:
return float64(v), nil
case int64:
return float64(v), nil
case uint:
return float64(v), nil
case uint8:
return float64(v), nil
case uint16:
return float64(v), nil
case uint32:
return float64(v), nil
case uint64:
return float64(v), nil
case float32:
return float64(v), nil
case float64:
return v, nil
case string:
// Try to parse string as number
f, err := strconv.ParseFloat(v, 64)
if err != nil {
return 0, fmt.Errorf("cannot convert string '%s' to number", v)
}
return f, nil
default:
return 0, fmt.Errorf("cannot convert %T to number", value)
}
}
// toInteger converts a value to an integer for indexing
func toInteger(value interface{}) (int, error) {
switch v := value.(type) {
case int:
return v, nil
case int8:
return int(v), nil
case int16:
return int(v), nil
case int32:
return int(v), nil
case int64:
return int(v), nil
case uint:
return int(v), nil
case uint8:
return int(v), nil
case uint16:
return int(v), nil
case uint32:
return int(v), nil
case uint64:
return int(v), nil
case float32:
return int(v), nil
case float64:
return int(v), nil
case string:
i, err := strconv.Atoi(v)
if err != nil {
return 0, fmt.Errorf("cannot convert string '%s' to integer", v)
}
return i, nil
default:
return 0, fmt.Errorf("cannot convert %T to integer", value)
}
}
// checkMembership checks if an item is in a collection
func checkMembership(collection, item interface{}) (bool, error) {
switch c := collection.(type) {
case string:
// Check if a character/substring is in a string
if s, ok := item.(string); ok {
return strings.Contains(c, s), nil
}
return false, nil
case []interface{}:
// Check if an item is in a list
for _, v := range c {
eq, err := equals(v, item)
if err != nil {
continue
}
return eq, nil
}
return false, nil
case map[string]interface{}:
// Check if a key is in a dictionary
key := fmt.Sprintf("%v", item)
_, ok := c[key]
return ok, nil
default:
// Try reflection for other collection types
rv := reflect.ValueOf(collection)
kind := rv.Kind()
if kind == reflect.Slice || kind == reflect.Array {
for i := 0; i < rv.Len(); i++ {
eq, err := equals(rv.Index(i).Interface(), item)
if err != nil {
continue
}
return eq, nil
}
return false, nil
} else if kind == reflect.Map {
for _, key := range rv.MapKeys() {
eq, err := equals(key.Interface(), item)
if err != nil {
continue
}
return eq, nil
}
return false, nil
}
return false, fmt.Errorf("'in' operator not supported for type: %T", collection)
}
}
// Mathematical operation functions
// add adds two values, with type coercion similar to Python
func add(left, right interface{}) (interface{}, error) {
// String concatenation
if lstr, ok := left.(string); ok {
if rstr, ok := right.(string); ok {
return lstr + rstr, nil
}
return nil, fmt.Errorf("cannot concatenate string with %T", right)
}
// List concatenation
if llist, ok := left.([]interface{}); ok {
if rlist, ok := right.([]interface{}); ok {
result := make([]interface{}, len(llist)+len(rlist))
copy(result, llist)
copy(result[len(llist):], rlist)
return result, nil
}
return nil, fmt.Errorf("cannot concatenate list with %T", right)
}
// Numeric addition
lnum, lerr := toFloat(left)
rnum, rerr := toFloat(right)
if lerr != nil || rerr != nil {
return nil, fmt.Errorf("cannot add %T and %T", left, right)
}
// If both inputs were integers, return integer
if _, lok := left.(int); lok {
if _, rok := right.(int); rok {
return int(lnum) + int(rnum), nil
}
}
// Otherwise return float
return lnum + rnum, nil
}
// subtract subtracts two values
func subtract(left, right interface{}) (interface{}, error) {
lnum, lerr := toFloat(left)
rnum, rerr := toFloat(right)
if lerr != nil || rerr != nil {
return nil, fmt.Errorf("cannot subtract %T from %T", right, left)
}
// If both inputs were integers, return integer
if _, lok := left.(int); lok {
if _, rok := right.(int); rok {
return int(lnum) - int(rnum), nil
}
}
// Otherwise return float
return lnum - rnum, nil
}
// multiply multiplies two values
func multiply(left, right interface{}) (interface{}, error) {
// String repetition: "a" * 3 = "aaa"
if lstr, ok := left.(string); ok {
if rnum, ok := right.(int); ok {
return strings.Repeat(lstr, rnum), nil
}
return nil, fmt.Errorf("cannot multiply string by %T", right)
}
// List repetition: [1, 2] * 3 = [1, 2, 1, 2, 1, 2]
if llist, ok := left.([]interface{}); ok {
if rnum, ok := right.(int); ok {
if rnum <= 0 {
return []interface{}{}, nil
}
result := make([]interface{}, 0, len(llist)*rnum)
for i := 0; i < rnum; i++ {
result = append(result, llist...)
}
return result, nil
}
return nil, fmt.Errorf("cannot multiply list by %T", right)
}
// Numeric multiplication
lnum, lerr := toFloat(left)
rnum, rerr := toFloat(right)
if lerr != nil || rerr != nil {
return nil, fmt.Errorf("cannot multiply %T and %T", left, right)
}
// If both inputs were integers, return integer
if _, lok := left.(int); lok {
if _, rok := right.(int); rok {
return int(lnum) * int(rnum), nil
}
}
// Otherwise return float
return lnum * rnum, nil
}
// divide divides two values (true division like Python's /)
func divide(left, right interface{}) (interface{}, error) {
lnum, lerr := toFloat(left)
rnum, rerr := toFloat(right)
if lerr != nil || rerr != nil {
return nil, fmt.Errorf("cannot divide %T by %T", left, right)
}
if rnum == 0 {
return nil, fmt.Errorf("division by zero")
}
// Always return float for true division
return lnum / rnum, nil
}
// floorDivide performs floor division like Python's //
func floorDivide(left, right interface{}) (interface{}, error) {
lnum, lerr := toFloat(left)
rnum, rerr := toFloat(right)
if lerr != nil || rerr != nil {
return nil, fmt.Errorf("cannot floor divide %T by %T", left, right)
}
if rnum == 0 {
return nil, fmt.Errorf("division by zero")
}
// If both inputs were integers, return integer
if _, lok := left.(int); lok {
if _, rok := right.(int); rok {
return int(math.Floor(lnum / rnum)), nil
}
}
// Otherwise return float
return math.Floor(lnum / rnum), nil
}
// modulo performs the modulo operation
func modulo(left, right interface{}) (interface{}, error) {
lnum, lerr := toFloat(left)
rnum, rerr := toFloat(right)
if lerr != nil || rerr != nil {
return nil, fmt.Errorf("cannot compute modulo of %T and %T", left, right)
}
if rnum == 0 {
return nil, fmt.Errorf("modulo by zero")
}
// If both inputs were integers, return integer
if _, lok := left.(int); lok {
if _, rok := right.(int); rok {
return int(lnum) % int(rnum), nil
}
}
// Otherwise use fmod for floating point modulo
return math.Mod(lnum, rnum), nil
}
// power calculates the power of a value (exponentiation)
func power(left, right interface{}) (interface{}, error) {
lnum, lerr := toFloat(left)
rnum, rerr := toFloat(right)
if lerr != nil || rerr != nil {
return nil, fmt.Errorf("cannot compute power of %T and %T", left, right)
}
// If both inputs were integers and the exponent is positive,
// we can return an integer
if _, lok := left.(int); lok {
if rInt, rok := right.(int); rok && rInt >= 0 {
return int(math.Pow(lnum, rnum)), nil
}
}
// Otherwise return float
return math.Pow(lnum, rnum), nil
}
// getAttributeValue accesses an attribute of an object.
// This is similar to obj.attribute in Python.
func getAttributeValue(obj interface{}, attr string) (interface{}, error) {
if obj == nil {
return nil, fmt.Errorf("cannot access attribute of nil")
}
// Handle different types of objects for attribute access
switch v := obj.(type) {
case map[string]interface{}:
// If it's a map with string keys, direct access
if val, ok := v[attr]; ok {
return val, nil
}
return nil, fmt.Errorf("attribute '%s' not found in map", attr)
case map[interface{}]interface{}:
// If it's a map with interface{} keys, try string or direct
if val, ok := v[attr]; ok {
return val, nil
}
// Try with string conversion
if val, ok := v[string(attr)]; ok {
return val, nil
}
return nil, fmt.Errorf("attribute '%s' not found in map", attr)
default:
// Use reflection for other types
val := reflect.ValueOf(obj)
// Dereference pointers
if val.Kind() == reflect.Ptr {
if val.IsNil() {
return nil, fmt.Errorf("cannot access attribute of nil pointer")
}
val = val.Elem()
}
// Handle different container types
switch val.Kind() {
case reflect.Struct:
// Access struct field
field := val.FieldByName(attr)
if !field.IsValid() {
// Try case-insensitive match as fallback
for i := 0; i < val.NumField(); i++ {
fieldName := val.Type().Field(i).Name
if strings.EqualFold(fieldName, attr) {
field = val.Field(i)
break
}
}
if !field.IsValid() {
return nil, fmt.Errorf("attribute '%s' not found in struct", attr)
}
}
return field.Interface(), nil
case reflect.Map:
// Try to access map with string key
keyVal := reflect.ValueOf(attr)
mapVal := val.MapIndex(keyVal)
if !mapVal.IsValid() {
// If key is not found, try using a literal string for the key
strKey := reflect.ValueOf(string(attr))
mapVal = val.MapIndex(strKey)
if !mapVal.IsValid() {
return nil, fmt.Errorf("key '%s' not found in map", attr)
}
}
return mapVal.Interface(), nil
default:
return nil, fmt.Errorf("cannot access attribute of %s", val.Kind())
}
}
}
// getSubscriptValue gets a value by subscript access (obj[key])
func getSubscriptValue(obj, key interface{}) (interface{}, error) {
if obj == nil {
return nil, fmt.Errorf("cannot subscript nil value")
}
switch o := obj.(type) {
case map[string]interface{}:
// For maps, convert key to string and look it up
k := fmt.Sprintf("%v", key)
if val, exists := o[k]; exists {
return val, nil
}
return nil, fmt.Errorf("key '%v' not found in map", key)
case []interface{}:
// For lists, key must be an integer index
idx, err := toInteger(key)
if err != nil {
return nil, fmt.Errorf("list index must be an integer, got %T", key)
}
// Handle negative index (Python-style)
if idx < 0 {
idx += len(o)
}
if idx < 0 || idx >= len(o) {
return nil, fmt.Errorf("list index out of range: %d", idx)
}
return o[idx], nil
case string:
// For strings, key must be an integer index
idx, err := toInteger(key)
if err != nil {
return nil, fmt.Errorf("string index must be an integer, got %T", key)
}
// Handle negative index (Python-style)
if idx < 0 {
idx += len(o)
}
if idx < 0 || idx >= len(o) {
return nil, fmt.Errorf("string index out of range: %d", idx)
}
return string(o[idx]), nil
default:
// Try reflection for other types
v := reflect.ValueOf(obj)
kind := v.Kind()
if kind == reflect.Map {
mapKey := reflect.ValueOf(key)
if !mapKey.Type().AssignableTo(v.Type().Key()) {
return nil, fmt.Errorf("key type mismatch: expected %v, got %T", v.Type().Key(), key)
}
val := v.MapIndex(mapKey)
if !val.IsValid() {
return nil, fmt.Errorf("key '%v' not found in map", key)
}
return val.Interface(), nil
}
if kind == reflect.Slice || kind == reflect.Array {
idx, err := toInteger(key)
if err != nil {
return nil, fmt.Errorf("index must be an integer, got %T", key)
}
// Handle negative index (Python-style)
if idx < 0 {
idx += v.Len()
}
if idx < 0 || idx >= v.Len() {
return nil, fmt.Errorf("index out of range: %d", idx)
}
return v.Index(idx).Interface(), nil
}
return nil, fmt.Errorf("cannot subscript type: %T", obj)
}
}
// callFunction calls a function with the provided arguments
func callFunction(callable interface{}, args []interface{}) (interface{}, error) {
// Handle function objects
fn, ok := callable.(func(...interface{}) (interface{}, error))
if ok {
return fn(args...)
}
// Use reflection for method calls and other callable types
v := reflect.ValueOf(callable)
if v.Kind() != reflect.Func {
return nil, fmt.Errorf("object is not callable: %T", callable)
}
// Convert arguments to reflect values
reflectArgs := make([]reflect.Value, len(args))
for i, arg := range args {
reflectArgs[i] = reflect.ValueOf(arg)
}
// Call the function
result := v.Call(reflectArgs)
// Handle the return value(s)
if len(result) == 0 {
return nil, nil
} else if len(result) == 1 {
return result[0].Interface(), nil
} else {
// Multiple return values - convert to a slice
values := make([]interface{}, len(result))
for i, r := range result {
values[i] = r.Interface()
}
return values, nil
}
}