forked from Knetic/govaluate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stagePlanner.go
671 lines (567 loc) · 16.5 KB
/
stagePlanner.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
package govaluate
import (
"errors"
"time"
"fmt"
)
var stageSymbolMap = map[OperatorSymbol]evaluationOperator{
EQ: equalStage,
NEQ: notEqualStage,
GT: gtStage,
LT: ltStage,
GTE: gteStage,
LTE: lteStage,
REQ: regexStage,
NREQ: notRegexStage,
AND: andStage,
OR: orStage,
IN: inStage,
BITWISE_OR: bitwiseOrStage,
BITWISE_AND: bitwiseAndStage,
BITWISE_XOR: bitwiseXORStage,
BITWISE_LSHIFT: leftShiftStage,
BITWISE_RSHIFT: rightShiftStage,
PLUS: addStage,
MINUS: subtractStage,
MULTIPLY: multiplyStage,
DIVIDE: divideStage,
MODULUS: modulusStage,
EXPONENT: exponentStage,
NEGATE: negateStage,
INVERT: invertStage,
BITWISE_NOT: bitwiseNotStage,
TERNARY_TRUE: ternaryIfStage,
TERNARY_FALSE: ternaryElseStage,
COALESCE: ternaryElseStage,
SEPARATE: separatorStage,
}
/*
A "precedent" is a function which will recursively parse new evaluateionStages from a given stream of tokens.
It's called a `precedent` because it is expected to handle exactly what precedence of operator,
and defer to other `precedent`s for other operators.
*/
type precedent func(stream *tokenStream) (*evaluationStage, error)
/*
A convenience function for specifying the behavior of a `precedent`.
Most `precedent` functions can be described by the same function, just with different type checks, symbols, and error formats.
This struct is passed to `makePrecedentFromPlanner` to create a `precedent` function.
*/
type precedencePlanner struct {
validSymbols map[string]OperatorSymbol
validKinds []TokenKind
typeErrorFormat string
next precedent
nextRight precedent
}
var planPrefix precedent
var planExponential precedent
var planMultiplicative precedent
var planAdditive precedent
var planBitwise precedent
var planShift precedent
var planComparator precedent
var planLogicalAnd precedent
var planLogicalOr precedent
var planTernary precedent
var planSeparator precedent
func init() {
// all these stages can use the same code (in `planPrecedenceLevel`) to execute,
// they simply need different type checks, symbols, and recursive precedents.
// While not all precedent phases are listed here, most can be represented this way.
planPrefix = makePrecedentFromPlanner(&precedencePlanner{
validSymbols: PREFIX_SYMBOLS,
validKinds: []TokenKind{PREFIX},
typeErrorFormat: TYPEERROR_PREFIX,
nextRight: planFunction,
})
planExponential = makePrecedentFromPlanner(&precedencePlanner{
validSymbols: EXPONENTIAL_SYMBOLS,
validKinds: []TokenKind{MODIFIER},
typeErrorFormat: TYPEERROR_MODIFIER,
next: planFunction,
})
planMultiplicative = makePrecedentFromPlanner(&precedencePlanner{
validSymbols: MULTIPLICATIVE_SYMBOLS,
validKinds: []TokenKind{MODIFIER},
typeErrorFormat: TYPEERROR_MODIFIER,
next: planExponential,
})
planAdditive = makePrecedentFromPlanner(&precedencePlanner{
validSymbols: ADDITIVE_SYMBOLS,
validKinds: []TokenKind{MODIFIER},
typeErrorFormat: TYPEERROR_MODIFIER,
next: planMultiplicative,
})
planShift = makePrecedentFromPlanner(&precedencePlanner{
validSymbols: BITWISE_SHIFT_SYMBOLS,
validKinds: []TokenKind{MODIFIER},
typeErrorFormat: TYPEERROR_MODIFIER,
next: planAdditive,
})
planBitwise = makePrecedentFromPlanner(&precedencePlanner{
validSymbols: BITWISE_SYMBOLS,
validKinds: []TokenKind{MODIFIER},
typeErrorFormat: TYPEERROR_MODIFIER,
next: planShift,
})
planComparator = makePrecedentFromPlanner(&precedencePlanner{
validSymbols: COMPARATOR_SYMBOLS,
validKinds: []TokenKind{COMPARATOR},
typeErrorFormat: TYPEERROR_COMPARATOR,
next: planBitwise,
})
planLogicalAnd = makePrecedentFromPlanner(&precedencePlanner{
validSymbols: map[string]OperatorSymbol{"&&": AND},
validKinds: []TokenKind{LOGICALOP},
typeErrorFormat: TYPEERROR_LOGICAL,
next: planComparator,
})
planLogicalOr = makePrecedentFromPlanner(&precedencePlanner{
validSymbols: map[string]OperatorSymbol{"||": OR},
validKinds: []TokenKind{LOGICALOP},
typeErrorFormat: TYPEERROR_LOGICAL,
next: planLogicalAnd,
})
planTernary = makePrecedentFromPlanner(&precedencePlanner{
validSymbols: TERNARY_SYMBOLS,
validKinds: []TokenKind{TERNARY},
typeErrorFormat: TYPEERROR_TERNARY,
next: planLogicalOr,
})
planSeparator = makePrecedentFromPlanner(&precedencePlanner{
validSymbols: SEPARATOR_SYMBOLS,
validKinds: []TokenKind{SEPARATOR},
next: planTernary,
})
}
/*
Given a planner, creates a function which will evaluate a specific precedence level of operators,
and link it to other `precedent`s which recurse to parse other precedence levels.
*/
func makePrecedentFromPlanner(planner *precedencePlanner) precedent {
var generated precedent
var nextRight precedent
generated = func(stream *tokenStream) (*evaluationStage, error) {
return planPrecedenceLevel(
stream,
planner.typeErrorFormat,
planner.validSymbols,
planner.validKinds,
nextRight,
planner.next,
)
}
if planner.nextRight != nil {
nextRight = planner.nextRight
} else {
nextRight = generated
}
return generated
}
/*
Creates a `evaluationStageList` object which represents an execution plan (or tree)
which is used to completely evaluate a set of tokens at evaluation-time.
The three stages of evaluation can be thought of as parsing strings to tokens, then tokens to a stage list, then evaluation with parameters.
*/
func planStages(tokens []ExpressionToken) (*evaluationStage, error) {
stream := newTokenStream(tokens)
stage, err := planTokens(stream)
if err != nil {
return nil, err
}
// while we're now fully-planned, we now need to re-order same-precedence operators.
// this could probably be avoided with a different planning method
reorderStages(stage)
stage = elideLiterals(stage)
return stage, nil
}
func planTokens(stream *tokenStream) (*evaluationStage, error) {
if !stream.hasNext() {
return nil, nil
}
return planSeparator(stream)
}
/*
The most usual method of parsing an evaluation stage for a given precedence.
Most stages use the same logic
*/
func planPrecedenceLevel(
stream *tokenStream,
typeErrorFormat string,
validSymbols map[string]OperatorSymbol,
validKinds []TokenKind,
rightPrecedent precedent,
leftPrecedent precedent) (*evaluationStage, error) {
var token ExpressionToken
var symbol OperatorSymbol
var leftStage, rightStage *evaluationStage
var checks typeChecks
var err error
var keyFound bool
if leftPrecedent != nil {
leftStage, err = leftPrecedent(stream)
if err != nil {
return nil, err
}
}
for stream.hasNext() {
token = stream.next()
if len(validKinds) > 0 {
keyFound = false
for _, kind := range validKinds {
if kind == token.Kind {
keyFound = true
break
}
}
if !keyFound {
break
}
}
if validSymbols != nil {
if !isString(token.Value) {
break
}
symbol, keyFound = validSymbols[token.Value.(string)]
if !keyFound {
break
}
}
if rightPrecedent != nil {
rightStage, err = rightPrecedent(stream)
if err != nil {
return nil, err
}
}
checks = findTypeChecks(symbol)
return &evaluationStage{
symbol: symbol,
leftStage: leftStage,
rightStage: rightStage,
operator: stageSymbolMap[symbol],
leftTypeCheck: checks.left,
rightTypeCheck: checks.right,
typeCheck: checks.combined,
typeErrorFormat: typeErrorFormat,
}, nil
}
stream.rewind()
return leftStage, nil
}
/*
A special case where functions need to be of higher precedence than values, and need a special wrapped execution stage operator.
*/
func planFunction(stream *tokenStream) (*evaluationStage, error) {
var token ExpressionToken
var rightStage *evaluationStage
var err error
token = stream.next()
if token.Kind != FUNCTION {
stream.rewind()
return planValue(stream)
}
rightStage, err = planValue(stream)
if err != nil {
return nil, err
}
return &evaluationStage{
symbol: FUNCTIONAL,
rightStage: rightStage,
operator: makeFunctionStage(token.Value.(ExpressionFunction)),
typeErrorFormat: "Unable to run function '%v': %v",
}, nil
}
/*
A truly special precedence function, this handles all the "lowest-case" errata of the process, including literals, parmeters,
clauses, and prefixes.
*/
func planValue(stream *tokenStream) (*evaluationStage, error) {
var token ExpressionToken
var symbol OperatorSymbol
var ret *evaluationStage
var operator evaluationOperator
var err error
token = stream.next()
switch token.Kind {
case CLAUSE:
ret, err = planTokens(stream)
if err != nil {
return nil, err
}
// advance past the CLAUSE_CLOSE token. We know that it's a CLAUSE_CLOSE, because at parse-time we check for unbalanced parens.
stream.next()
// the stage we got represents all of the logic contained within the parens
// but for technical reasons, we need to wrap this stage in a "noop" stage which breaks long chains of precedence.
// see github #33.
ret = &evaluationStage {
rightStage: ret,
operator: noopStageRight,
symbol: NOOP,
}
return ret, nil
case CLAUSE_CLOSE:
// when functions have empty params, this will be hit. In this case, we don't have any evaluation stage to do,
// so we just return nil so that the stage planner continues on its way.
stream.rewind()
return nil, nil
case VARIABLE:
operator = makeParameterStage(token.Value.(string))
case NUMERIC:
fallthrough
case STRING:
fallthrough
case PATTERN:
fallthrough
case BOOLEAN:
symbol = LITERAL
operator = makeLiteralStage(token.Value)
case TIME:
symbol = LITERAL
operator = makeLiteralStage(float64(token.Value.(time.Time).Unix()))
case PREFIX:
stream.rewind()
return planPrefix(stream)
}
if operator == nil {
errorMsg := fmt.Sprintf("Unable to plan token kind: '%s', value: '%v'", GetTokenKindString(token.Kind), token.Value)
return nil, errors.New(errorMsg)
}
return &evaluationStage{
symbol: symbol,
operator: operator,
}, nil
}
/*
Convenience function to pass a triplet of typechecks between `findTypeChecks` and `planPrecedenceLevel`.
Each of these members may be nil, which indicates that type does not matter for that value.
*/
type typeChecks struct {
left stageTypeCheck
right stageTypeCheck
combined stageCombinedTypeCheck
}
/*
Maps a given [symbol] to a set of typechecks to be used during runtime.
*/
func findTypeChecks(symbol OperatorSymbol) typeChecks {
switch symbol {
case GT:
fallthrough
case LT:
fallthrough
case GTE:
fallthrough
case LTE:
return typeChecks{
combined: comparatorTypeCheck,
}
case REQ:
fallthrough
case NREQ:
return typeChecks{
left: isString,
right: isRegexOrString,
}
case AND:
fallthrough
case OR:
return typeChecks{
left: isBool,
right: isBool,
}
case IN:
return typeChecks{
right: isArray,
}
case BITWISE_LSHIFT:
fallthrough
case BITWISE_RSHIFT:
fallthrough
case BITWISE_OR:
fallthrough
case BITWISE_AND:
fallthrough
case BITWISE_XOR:
return typeChecks{
left: isFloat64,
right: isFloat64,
}
case PLUS:
return typeChecks{
combined: additionTypeCheck,
}
case MINUS:
fallthrough
case MULTIPLY:
fallthrough
case DIVIDE:
fallthrough
case MODULUS:
fallthrough
case EXPONENT:
return typeChecks{
left: isFloat64,
right: isFloat64,
}
case NEGATE:
return typeChecks{
right: isFloat64,
}
case INVERT:
return typeChecks{
right: isBool,
}
case BITWISE_NOT:
return typeChecks{
right: isFloat64,
}
case TERNARY_TRUE:
return typeChecks{
left: isBool,
}
// unchecked cases
case EQ:
fallthrough
case NEQ:
return typeChecks{}
case TERNARY_FALSE:
fallthrough
case COALESCE:
fallthrough
default:
return typeChecks{}
}
}
/*
During stage planning, stages of equal precedence are parsed such that they'll be evaluated in reverse order.
For commutative operators like "+" or "-", it's no big deal. But for order-specific operators, it ruins the expected result.
*/
func reorderStages(rootStage *evaluationStage) {
// traverse every rightStage until we find multiples in a row of the same precedence.
var identicalPrecedences []*evaluationStage
var currentStage, nextStage *evaluationStage
var precedence, currentPrecedence OperatorPrecedence
nextStage = rootStage
precedence = findOperatorPrecedenceForSymbol(rootStage.symbol)
for nextStage != nil {
currentStage = nextStage
nextStage = currentStage.rightStage
// left depth first, since this entire method only looks for precedences down the right side of the tree
if currentStage.leftStage != nil {
reorderStages(currentStage.leftStage)
}
currentPrecedence = findOperatorPrecedenceForSymbol(currentStage.symbol)
if currentPrecedence == precedence {
identicalPrecedences = append(identicalPrecedences, currentStage)
continue
}
// precedence break.
// See how many in a row we had, and reorder if there's more than one.
if len(identicalPrecedences) > 1 {
mirrorStageSubtree(identicalPrecedences)
}
identicalPrecedences = []*evaluationStage{currentStage}
precedence = currentPrecedence
}
if len(identicalPrecedences) > 1 {
mirrorStageSubtree(identicalPrecedences)
}
}
/*
Performs a "mirror" on a subtree of stages.
This mirror functionally inverts the order of execution for all members of the [stages] list.
That list is assumed to be a root-to-leaf (ordered) list of evaluation stages, where each is a right-hand stage of the last.
*/
func mirrorStageSubtree(stages []*evaluationStage) {
var rootStage, inverseStage, carryStage, frontStage *evaluationStage
stagesLength := len(stages)
// reverse all right/left
for _, frontStage = range stages {
carryStage = frontStage.rightStage
frontStage.rightStage = frontStage.leftStage
frontStage.leftStage = carryStage
}
// end left swaps with root right
rootStage = stages[0]
frontStage = stages[stagesLength-1]
carryStage = frontStage.leftStage
frontStage.leftStage = rootStage.rightStage
rootStage.rightStage = carryStage
// for all non-root non-end stages, right is swapped with inverse stage right in list
for i := 0; i < (stagesLength-2)/2+1; i++ {
frontStage = stages[i+1]
inverseStage = stages[stagesLength-i-1]
carryStage = frontStage.rightStage
frontStage.rightStage = inverseStage.rightStage
inverseStage.rightStage = carryStage
}
// swap all other information with inverse stages
for i := 0; i < stagesLength/2; i++ {
frontStage = stages[i]
inverseStage = stages[stagesLength-i-1]
frontStage.swapWith(inverseStage)
}
}
/*
Recurses through all operators in the entire tree, eliding operators where both sides are literals.
*/
func elideLiterals(root *evaluationStage) *evaluationStage {
if root.leftStage != nil {
root.leftStage = elideLiterals(root.leftStage)
}
if root.rightStage != nil {
root.rightStage = elideLiterals(root.rightStage)
}
return elideStage(root)
}
/*
Elides a specific stage, if possible.
Returns the unmodified [root] stage if it cannot or should not be elided.
Otherwise, returns a new stage representing the condensed value from the elided stages.
*/
func elideStage(root *evaluationStage) *evaluationStage {
var leftValue, rightValue, result interface{}
var err error
// right side must be a non-nil value. Left side must be nil or a value.
if root.rightStage == nil ||
root.rightStage.symbol != LITERAL ||
root.leftStage == nil ||
root.leftStage.symbol != LITERAL {
return root
}
// don't elide some operators
switch root.symbol {
case SEPARATE:
fallthrough
case IN:
return root
}
// both sides are values, get their actual values.
// errors should be near-impossible here. If we encounter them, just abort this optimization.
leftValue, err = root.leftStage.operator(nil, nil, nil)
if err != nil {
return root
}
rightValue, err = root.rightStage.operator(nil, nil, nil)
if err != nil {
return root
}
// typcheck, since the grammar checker is a bit loose with which operator symbols go together.
err = typeCheck(root.leftTypeCheck, leftValue, root.symbol, root.typeErrorFormat)
if err != nil {
return root
}
err = typeCheck(root.rightTypeCheck, rightValue, root.symbol, root.typeErrorFormat)
if err != nil {
return root
}
// pre-calculate, and return a new stage representing the result.
result, err = root.operator(leftValue, rightValue, nil)
if err != nil {
return root
}
return &evaluationStage {
symbol: LITERAL,
operator: makeLiteralStage(result),
}
}