-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode_binary.go
More file actions
568 lines (541 loc) · 14.3 KB
/
Copy pathnode_binary.go
File metadata and controls
568 lines (541 loc) · 14.3 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
package expressionlanguage
import (
"fmt"
"math"
"regexp"
"strconv"
"strings"
)
type binaryNode struct {
operator string
left Node
right Node
}
func NewBinary(operator string, left, right Node) Node {
return &binaryNode{operator: operator, left: left, right: right}
}
func (n *binaryNode) Compile(functions Functions) (Program, error) {
return compilePublic(n, functions)
}
func (n *binaryNode) Evaluate(functions Functions, variables Variables) (any, error) {
return evaluatePublic(n, functions, variables)
}
func (n *binaryNode) compileInternal(functions Functions) (internalProgram, error) {
if !supportedBinaryOperator(n.operator) {
return nil, unsupportedBinaryOperator(n.operator)
}
if n.operator == "+" {
return n.compileAddition(functions)
}
if n.operator == "matches" && isStaticNode(n.right) {
result, err := evaluateNodeInternal(n.right, functions, evaluationContext{})
if err != nil {
return nil, err
}
pattern, ok := result.value.(string)
if !ok {
return nil, newSyntaxError(`The regex passed to "matches" must be a string`, 0, "")
}
if _, err := compileExpressionRegexp(pattern); err != nil {
return nil, err
}
}
left, err := compileNode(n.left, functions)
if err != nil {
return nil, err
}
right, err := compileNode(n.right, functions)
if err != nil {
return nil, err
}
return func(context evaluationContext) (evaluationResult, error) {
leftResult, err := left(context)
if err != nil || leftResult.shortCircuit {
return leftResult, err
}
if (n.operator == "and" || n.operator == "&&") && !truthy(leftResult.value) {
return evaluationResult{value: false}, nil
}
if (n.operator == "or" || n.operator == "||") && truthy(leftResult.value) {
return evaluationResult{value: true}, nil
}
rightResult, err := right(context)
if err != nil || rightResult.shortCircuit {
return rightResult, err
}
value, err := evaluateBinary(n.operator, leftResult.value, rightResult.value)
return evaluationResult{value: value}, err
}, nil
}
func (n *binaryNode) evaluateInternal(functions Functions, context evaluationContext) (evaluationResult, error) {
if !supportedBinaryOperator(n.operator) {
return evaluationResult{}, unsupportedBinaryOperator(n.operator)
}
if n.operator == "+" {
accumulator := numericSum{}
if result, err := evaluateAdditionNode(n, functions, context, &accumulator); err != nil || result.shortCircuit {
return result, err
}
return evaluationResult{value: accumulator.result()}, nil
}
left, err := evaluateNodeInternal(n.left, functions, context)
if err != nil || left.shortCircuit {
return left, err
}
if (n.operator == "and" || n.operator == "&&") && !truthy(left.value) {
return evaluationResult{value: false}, nil
}
if (n.operator == "or" || n.operator == "||") && truthy(left.value) {
return evaluationResult{value: true}, nil
}
right, err := evaluateNodeInternal(n.right, functions, context)
if err != nil || right.shortCircuit {
return right, err
}
value, err := evaluateBinary(n.operator, left.value, right.value)
return evaluationResult{value: value}, err
}
func (n *binaryNode) compileAddition(functions Functions) (internalProgram, error) {
nodes := make([]Node, 0, countAdditionNodes(n))
collectAdditionNodes(n, &nodes)
programs := make([]internalProgram, len(nodes))
for i, node := range nodes {
program, err := compileNode(node, functions)
if err != nil {
return nil, err
}
programs[i] = program
}
return func(context evaluationContext) (evaluationResult, error) {
accumulator := numericSum{}
for _, program := range programs {
result, err := program(context)
if err != nil || result.shortCircuit {
return result, err
}
if err := accumulator.add(result.value); err != nil {
return evaluationResult{}, err
}
}
return evaluationResult{value: accumulator.result()}, nil
}, nil
}
func countAdditionNodes(node Node) int {
if binary, ok := node.(*binaryNode); ok && binary.operator == "+" {
return countAdditionNodes(binary.left) + countAdditionNodes(binary.right)
}
return 1
}
func collectAdditionNodes(node Node, nodes *[]Node) {
if binary, ok := node.(*binaryNode); ok && binary.operator == "+" {
collectAdditionNodes(binary.left, nodes)
collectAdditionNodes(binary.right, nodes)
return
}
*nodes = append(*nodes, node)
}
func evaluateAdditionNode(node Node, functions Functions, context evaluationContext, accumulator *numericSum) (evaluationResult, error) {
if binary, ok := node.(*binaryNode); ok && binary.operator == "+" {
result, err := evaluateAdditionNode(binary.left, functions, context, accumulator)
if err != nil || result.shortCircuit {
return result, err
}
return evaluateAdditionNode(binary.right, functions, context, accumulator)
}
result, err := evaluateNodeInternal(node, functions, context)
if err != nil || result.shortCircuit {
return result, err
}
if err := accumulator.add(result.value); err != nil {
return evaluationResult{}, err
}
return evaluationResult{}, nil
}
type numericSum struct {
integer int
floating float64
isFloat bool
}
func (s *numericSum) add(value any) error {
switch value := value.(type) {
case int:
if s.isFloat {
s.floating += float64(value)
} else {
s.integer += value
}
case float64:
if !s.isFloat {
s.floating = float64(s.integer)
s.isFloat = true
}
s.floating += value
default:
return fmt.Errorf("operator %q requires numbers", "+")
}
return nil
}
func (s *numericSum) result() any {
if s.isFloat {
return s.floating
}
return s.integer
}
func (n *binaryNode) Dump() string {
return "(" + n.left.Dump() + " " + n.operator + " " + n.right.Dump() + ")"
}
func supportedBinaryOperator(operator string) bool {
switch operator {
case "or", "||", "xor", "and", "&&", "&", "|", "^", "<<", ">>",
"<", "<=", ">", ">=", "===", "!==", "==", "!=", "-", "+", "*", "/", "%", "**", "~",
"in", "not in", "..", "starts with", "ends with", "contains", "matches":
return true
default:
return false
}
}
func unsupportedBinaryOperator(operator string) error {
return fmt.Errorf(`BinaryNode does not support the %q operator`, operator)
}
func evaluateBinary(operator string, left, right any) (any, error) {
switch operator {
case "and", "&&":
return truthy(left) && truthy(right), nil
case "or", "||":
return truthy(left) || truthy(right), nil
case "xor":
return truthy(left) != truthy(right), nil
case "&", "|", "^", "<<", ">>":
leftInt, leftOK := asInt(left)
rightInt, rightOK := asInt(right)
if !leftOK || !rightOK {
return nil, fmt.Errorf("operator %q requires integers", operator)
}
switch operator {
case "&":
return leftInt & rightInt, nil
case "|":
return leftInt | rightInt, nil
case "^":
return leftInt ^ rightInt, nil
case "<<":
return leftInt << uint(rightInt), nil
default:
return leftInt >> uint(rightInt), nil
}
case "===":
return strictEqual(left, right), nil
case "!==":
return !strictEqual(left, right), nil
case "==":
return looseEqual(left, right), nil
case "!=":
return !looseEqual(left, right), nil
case "<", "<=", ">", ">=":
comparison, err := compareValues(left, right)
if err != nil {
return nil, err
}
switch operator {
case "<":
return comparison < 0, nil
case "<=":
return comparison <= 0, nil
case ">":
return comparison > 0, nil
default:
return comparison >= 0, nil
}
case "+", "-", "*", "/", "%", "**":
return arithmetic(operator, left, right)
case "~":
return stringify(left) + stringify(right), nil
case "in", "not in":
found, err := containsStrict(right, left)
if err != nil {
return nil, err
}
if operator == "not in" {
return !found, nil
}
return found, nil
case "..":
start, startOK := asInt(left)
end, endOK := asInt(right)
if !startOK || !endOK {
return nil, fmt.Errorf("range boundaries must be integers")
}
step := 1
if start > end {
step = -1
}
result := make([]any, 0, absInt(end-start)+1)
for value := start; ; value += step {
result = append(result, value)
if value == end {
break
}
}
return result, nil
case "starts with":
return strings.HasPrefix(stringify(left), stringify(right)), nil
case "ends with":
return strings.HasSuffix(stringify(left), stringify(right)), nil
case "contains":
return strings.Contains(stringify(left), stringify(right)), nil
case "matches":
pattern, ok := right.(string)
if !ok {
return nil, newSyntaxError(`The regex passed to "matches" must be a string`, 0, "")
}
expression, err := compileExpressionRegexp(pattern)
if err != nil {
return nil, err
}
if expression.MatchString(stringify(left)) {
return 1, nil
}
return 0, nil
default:
return nil, unsupportedBinaryOperator(operator)
}
}
func arithmetic(operator string, left, right any) (any, error) {
const (
divisionByZero = "Division by zero."
moduloByZero = "Modulo by zero."
)
leftInt, leftIsInt := left.(int)
rightInt, rightIsInt := right.(int)
if leftIsInt && rightIsInt {
switch operator {
case "+":
return leftInt + rightInt, nil
case "-":
return leftInt - rightInt, nil
case "*":
return leftInt * rightInt, nil
case "/":
if rightInt == 0 {
return nil, fmt.Errorf("%s", divisionByZero)
}
return leftInt / rightInt, nil
case "%":
if rightInt == 0 {
return nil, fmt.Errorf("%s", moduloByZero)
}
return leftInt % rightInt, nil
case "**":
return int(math.Pow(float64(leftInt), float64(rightInt))), nil
}
}
leftFloat, leftOK := asFloat(left)
rightFloat, rightOK := asFloat(right)
if !leftOK || !rightOK {
return nil, fmt.Errorf("operator %q requires numbers", operator)
}
switch operator {
case "+":
return leftFloat + rightFloat, nil
case "-":
return leftFloat - rightFloat, nil
case "*":
return leftFloat * rightFloat, nil
case "/":
if rightFloat == 0 {
return nil, fmt.Errorf("%s", divisionByZero)
}
return leftFloat / rightFloat, nil
case "%":
if rightFloat == 0 {
return nil, fmt.Errorf("%s", moduloByZero)
}
return math.Mod(leftFloat, rightFloat), nil
default:
return math.Pow(leftFloat, rightFloat), nil
}
}
func asInt(value any) (int, bool) {
integer, ok := value.(int)
return integer, ok
}
func asFloat(value any) (float64, bool) {
switch value := value.(type) {
case int:
return float64(value), true
case float64:
return value, true
default:
return 0, false
}
}
func looseEqual(left, right any) bool {
if strictEqual(left, right) {
return true
}
if leftNumber, ok := numericValue(left); ok {
if rightNumber, ok := numericValue(right); ok {
return leftNumber == rightNumber
}
}
return stringify(left) == stringify(right)
}
func numericValue(value any) (float64, bool) {
if number, ok := asFloat(value); ok {
return number, true
}
text, ok := value.(string)
if !ok {
return 0, false
}
number, err := strconv.ParseFloat(text, 64)
return number, err == nil
}
func compareValues(left, right any) (int, error) {
if leftNumber, ok := asFloat(left); ok {
rightNumber, ok := asFloat(right)
if !ok {
return 0, fmt.Errorf("cannot compare %T and %T", left, right)
}
switch {
case leftNumber < rightNumber:
return -1, nil
case leftNumber > rightNumber:
return 1, nil
default:
return 0, nil
}
}
leftString, leftOK := left.(string)
rightString, rightOK := right.(string)
if leftOK && rightOK {
return strings.Compare(leftString, rightString), nil
}
return 0, fmt.Errorf("cannot compare %T and %T", left, right)
}
func containsStrict(collection, needle any) (bool, error) {
switch collection := collection.(type) {
case []any:
for _, value := range collection {
if strictEqual(value, needle) {
return true, nil
}
}
return false, nil
case OrderedMap:
for _, entry := range collection {
if strictEqual(entry.Value, needle) {
return true, nil
}
}
return false, nil
case map[any]any:
for _, value := range collection {
if strictEqual(value, needle) {
return true, nil
}
}
return false, nil
default:
return false, fmt.Errorf("right operand of in must be a collection")
}
}
func compileExpressionRegexp(pattern string) (*regexp.Regexp, error) {
if pattern == "" || isAlphaNumeric(pattern[0]) || pattern[0] == '\\' || isSpace(pattern[0]) {
return nil, invalidRegexp(pattern, "Delimiter must not be alphanumeric")
}
delimiter := pattern[0]
closing := -1
escaped := false
for i := 1; i < len(pattern); i++ {
if escaped {
escaped = false
continue
}
if pattern[i] == '\\' {
escaped = true
continue
}
if pattern[i] == delimiter {
closing = i
}
}
if closing < 1 {
return nil, invalidRegexp(pattern, "No ending delimiter found")
}
body := pattern[1:closing]
modifiers := pattern[closing+1:]
var prefix strings.Builder
for _, modifier := range modifiers {
switch modifier {
case 'i', 'm', 's':
prefix.WriteString(string(modifier))
default:
return nil, invalidRegexp(pattern, fmt.Sprintf("Unknown modifier %q", modifier))
}
}
if prefix.String() != "" {
body = "(?" + prefix.String() + ")" + body
}
expression, err := regexp.Compile(body)
if err != nil {
return nil, invalidRegexp(pattern, err.Error())
}
return expression, nil
}
func invalidRegexp(pattern, detail string) error {
return newSyntaxError(fmt.Sprintf(`Regexp %q passed to "matches" is not valid: %s`, pattern, detail), 0, "")
}
func isStaticNode(node Node) bool {
switch node := node.(type) {
case *constantNode:
return true
case *unaryNode:
return isStaticNode(node.operand)
case *binaryNode:
return isStaticNode(node.left) && isStaticNode(node.right)
case *arrayNode:
for _, element := range node.elements {
if element.Key != nil && !isStaticNode(element.Key) {
return false
}
if !isStaticNode(element.Value) {
return false
}
}
return true
case *conditionalNode:
return isStaticNode(node.condition) && isStaticNode(node.whenTrue) && isStaticNode(node.whenFalse)
default:
return false
}
}
func stringify(value any) string {
if value == nil {
return ""
}
if value == true {
return "1"
}
if value == false {
return ""
}
return fmt.Sprint(value)
}
func absInt(value int) int {
if value < 0 {
return -value
}
return value
}
func isAlphaNumeric(value byte) bool {
return value >= 'a' && value <= 'z' || value >= 'A' && value <= 'Z' || value >= '0' && value <= '9'
}
func isSpace(value byte) bool {
switch value {
case ' ', '\t', '\r', '\n', '\v', '\f':
return true
default:
return false
}
}