-
Notifications
You must be signed in to change notification settings - Fork 24.3k
/
OptimizerRules.java
1957 lines (1719 loc) · 87.4 KB
/
OptimizerRules.java
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
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.ql.optimizer;
import org.elasticsearch.common.util.set.Sets;
import org.elasticsearch.xpack.ql.expression.Alias;
import org.elasticsearch.xpack.ql.expression.Attribute;
import org.elasticsearch.xpack.ql.expression.AttributeMap;
import org.elasticsearch.xpack.ql.expression.Expression;
import org.elasticsearch.xpack.ql.expression.Expressions;
import org.elasticsearch.xpack.ql.expression.Literal;
import org.elasticsearch.xpack.ql.expression.Nullability;
import org.elasticsearch.xpack.ql.expression.Order;
import org.elasticsearch.xpack.ql.expression.function.Function;
import org.elasticsearch.xpack.ql.expression.function.Functions;
import org.elasticsearch.xpack.ql.expression.function.scalar.ScalarFunction;
import org.elasticsearch.xpack.ql.expression.function.scalar.SurrogateFunction;
import org.elasticsearch.xpack.ql.expression.predicate.BinaryOperator;
import org.elasticsearch.xpack.ql.expression.predicate.BinaryPredicate;
import org.elasticsearch.xpack.ql.expression.predicate.Negatable;
import org.elasticsearch.xpack.ql.expression.predicate.Predicates;
import org.elasticsearch.xpack.ql.expression.predicate.Range;
import org.elasticsearch.xpack.ql.expression.predicate.logical.And;
import org.elasticsearch.xpack.ql.expression.predicate.logical.BinaryLogic;
import org.elasticsearch.xpack.ql.expression.predicate.logical.Not;
import org.elasticsearch.xpack.ql.expression.predicate.logical.Or;
import org.elasticsearch.xpack.ql.expression.predicate.nulls.IsNotNull;
import org.elasticsearch.xpack.ql.expression.predicate.nulls.IsNull;
import org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.ArithmeticOperation;
import org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.BinaryComparisonInversible;
import org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.Neg;
import org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.Sub;
import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.BinaryComparison;
import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.Equals;
import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.GreaterThan;
import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.GreaterThanOrEqual;
import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.In;
import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.LessThan;
import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.LessThanOrEqual;
import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.NotEquals;
import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.NullEquals;
import org.elasticsearch.xpack.ql.expression.predicate.regex.RegexMatch;
import org.elasticsearch.xpack.ql.expression.predicate.regex.StringPattern;
import org.elasticsearch.xpack.ql.plan.logical.Aggregate;
import org.elasticsearch.xpack.ql.plan.logical.Filter;
import org.elasticsearch.xpack.ql.plan.logical.Limit;
import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan;
import org.elasticsearch.xpack.ql.plan.logical.OrderBy;
import org.elasticsearch.xpack.ql.plan.logical.UnaryPlan;
import org.elasticsearch.xpack.ql.rule.Rule;
import org.elasticsearch.xpack.ql.type.DataType;
import org.elasticsearch.xpack.ql.type.DataTypes;
import org.elasticsearch.xpack.ql.util.CollectionUtils;
import org.elasticsearch.xpack.ql.util.ReflectionUtils;
import java.time.DateTimeException;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiFunction;
import static java.lang.Math.signum;
import static java.util.Arrays.asList;
import static java.util.Collections.emptySet;
import static org.elasticsearch.xpack.ql.expression.Literal.FALSE;
import static org.elasticsearch.xpack.ql.expression.Literal.TRUE;
import static org.elasticsearch.xpack.ql.expression.predicate.Predicates.combineAnd;
import static org.elasticsearch.xpack.ql.expression.predicate.Predicates.combineOr;
import static org.elasticsearch.xpack.ql.expression.predicate.Predicates.inCommon;
import static org.elasticsearch.xpack.ql.expression.predicate.Predicates.splitAnd;
import static org.elasticsearch.xpack.ql.expression.predicate.Predicates.splitOr;
import static org.elasticsearch.xpack.ql.expression.predicate.Predicates.subtract;
import static org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.DefaultBinaryArithmeticOperation.ADD;
import static org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.DefaultBinaryArithmeticOperation.DIV;
import static org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.DefaultBinaryArithmeticOperation.MOD;
import static org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.DefaultBinaryArithmeticOperation.MUL;
import static org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.DefaultBinaryArithmeticOperation.SUB;
import static org.elasticsearch.xpack.ql.tree.Source.EMPTY;
import static org.elasticsearch.xpack.ql.util.CollectionUtils.combine;
public final class OptimizerRules {
public static final class ConstantFolding extends OptimizerExpressionRule<Expression> {
public ConstantFolding() {
super(TransformDirection.DOWN);
}
@Override
public Expression rule(Expression e) {
return e.foldable() ? Literal.of(e) : e;
}
}
/**
* This rule must always be placed after {@link LiteralsOnTheRight}, since it looks at TRUE/FALSE literals' existence
* on the right hand-side of the {@link Equals}/{@link NotEquals} expressions.
*/
public static final class BooleanFunctionEqualsElimination extends OptimizerExpressionRule<BinaryComparison> {
public BooleanFunctionEqualsElimination() {
super(TransformDirection.UP);
}
@Override
protected Expression rule(BinaryComparison bc) {
if ((bc instanceof Equals || bc instanceof NotEquals) && bc.left() instanceof Function) {
// for expression "==" or "!=" TRUE/FALSE, return the expression itself or its negated variant
if (TRUE.equals(bc.right())) {
return bc instanceof Equals ? bc.left() : new Not(bc.left().source(), bc.left());
}
if (FALSE.equals(bc.right())) {
return bc instanceof Equals ? new Not(bc.left().source(), bc.left()) : bc.left();
}
}
return bc;
}
}
public static class BooleanSimplification extends OptimizerExpressionRule<ScalarFunction> {
public BooleanSimplification() {
super(TransformDirection.UP);
}
@Override
public Expression rule(ScalarFunction e) {
if (e instanceof And || e instanceof Or) {
return simplifyAndOr((BinaryPredicate<?, ?, ?, ?>) e);
}
if (e instanceof Not) {
return simplifyNot((Not) e);
}
return e;
}
private static Expression simplifyAndOr(BinaryPredicate<?, ?, ?, ?> bc) {
Expression l = bc.left();
Expression r = bc.right();
if (bc instanceof And) {
if (TRUE.equals(l)) {
return r;
}
if (TRUE.equals(r)) {
return l;
}
if (FALSE.equals(l) || FALSE.equals(r)) {
return new Literal(bc.source(), Boolean.FALSE, DataTypes.BOOLEAN);
}
if (l.semanticEquals(r)) {
return l;
}
//
// common factor extraction -> (a || b) && (a || c) => a || (b && c)
//
List<Expression> leftSplit = splitOr(l);
List<Expression> rightSplit = splitOr(r);
List<Expression> common = inCommon(leftSplit, rightSplit);
if (common.isEmpty()) {
return bc;
}
List<Expression> lDiff = subtract(leftSplit, common);
List<Expression> rDiff = subtract(rightSplit, common);
// (a || b || c || ... ) && (a || b) => (a || b)
if (lDiff.isEmpty() || rDiff.isEmpty()) {
return combineOr(common);
}
// (a || b || c || ... ) && (a || b || d || ... ) => ((c || ...) && (d || ...)) || a || b
Expression combineLeft = combineOr(lDiff);
Expression combineRight = combineOr(rDiff);
return combineOr(combine(common, new And(combineLeft.source(), combineLeft, combineRight)));
}
if (bc instanceof Or) {
if (TRUE.equals(l) || TRUE.equals(r)) {
return new Literal(bc.source(), Boolean.TRUE, DataTypes.BOOLEAN);
}
if (FALSE.equals(l)) {
return r;
}
if (FALSE.equals(r)) {
return l;
}
if (l.semanticEquals(r)) {
return l;
}
//
// common factor extraction -> (a && b) || (a && c) => a && (b || c)
//
List<Expression> leftSplit = splitAnd(l);
List<Expression> rightSplit = splitAnd(r);
List<Expression> common = inCommon(leftSplit, rightSplit);
if (common.isEmpty()) {
return bc;
}
List<Expression> lDiff = subtract(leftSplit, common);
List<Expression> rDiff = subtract(rightSplit, common);
// (a || b || c || ... ) && (a || b) => (a || b)
if (lDiff.isEmpty() || rDiff.isEmpty()) {
return combineAnd(common);
}
// (a || b || c || ... ) && (a || b || d || ... ) => ((c || ...) && (d || ...)) || a || b
Expression combineLeft = combineAnd(lDiff);
Expression combineRight = combineAnd(rDiff);
return combineAnd(combine(common, new Or(combineLeft.source(), combineLeft, combineRight)));
}
// TODO: eliminate conjunction/disjunction
return bc;
}
@SuppressWarnings("rawtypes")
private Expression simplifyNot(Not n) {
Expression c = n.field();
if (TRUE.semanticEquals(c)) {
return new Literal(n.source(), Boolean.FALSE, DataTypes.BOOLEAN);
}
if (FALSE.semanticEquals(c)) {
return new Literal(n.source(), Boolean.TRUE, DataTypes.BOOLEAN);
}
Expression negated = maybeSimplifyNegatable(c);
if (negated != null) {
return negated;
}
if (c instanceof Not) {
return ((Not) c).field();
}
return n;
}
/**
* @param e
* @return the negated expression or {@code null} if the parameter is not an instance of {@code Negatable}
*/
protected Expression maybeSimplifyNegatable(Expression e) {
if (e instanceof Negatable) {
return ((Negatable<?>) e).negate();
}
return null;
}
}
public static class BinaryComparisonSimplification extends OptimizerExpressionRule<BinaryComparison> {
public BinaryComparisonSimplification() {
super(TransformDirection.DOWN);
}
@Override
protected Expression rule(BinaryComparison bc) {
Expression l = bc.left();
Expression r = bc.right();
// true for equality
if (bc instanceof Equals || bc instanceof GreaterThanOrEqual || bc instanceof LessThanOrEqual) {
if (l.nullable() == Nullability.FALSE && r.nullable() == Nullability.FALSE && l.semanticEquals(r)) {
return new Literal(bc.source(), Boolean.TRUE, DataTypes.BOOLEAN);
}
}
if (bc instanceof NullEquals) {
if (l.semanticEquals(r)) {
return new Literal(bc.source(), Boolean.TRUE, DataTypes.BOOLEAN);
}
if (Expressions.isNull(r)) {
return new IsNull(bc.source(), l);
}
}
// false for equality
if (bc instanceof NotEquals || bc instanceof GreaterThan || bc instanceof LessThan) {
if (l.nullable() == Nullability.FALSE && r.nullable() == Nullability.FALSE && l.semanticEquals(r)) {
return new Literal(bc.source(), Boolean.FALSE, DataTypes.BOOLEAN);
}
}
return bc;
}
}
public static final class LiteralsOnTheRight extends OptimizerExpressionRule<BinaryOperator<?, ?, ?, ?>> {
public LiteralsOnTheRight() {
super(TransformDirection.UP);
}
@Override
public BinaryOperator<?, ?, ?, ?> rule(BinaryOperator<?, ?, ?, ?> be) {
return be.left() instanceof Literal && (be.right() instanceof Literal) == false ? be.swapLeftAndRight() : be;
}
}
/**
* Propagate Equals to eliminate conjuncted Ranges or BinaryComparisons.
* When encountering a different Equals, non-containing {@link Range} or {@link BinaryComparison}, the conjunction becomes false.
* When encountering a containing {@link Range}, {@link BinaryComparison} or {@link NotEquals}, these get eliminated by the equality.
*
* Since this rule can eliminate Ranges and BinaryComparisons, it should be applied before {@link CombineBinaryComparisons}.
*
* This rule doesn't perform any promotion of {@link BinaryComparison}s, that is handled by
* {@link CombineBinaryComparisons} on purpose as the resulting Range might be foldable
* (which is picked by the folding rule on the next run).
*/
public static final class PropagateEquals extends OptimizerExpressionRule<BinaryLogic> {
public PropagateEquals() {
super(TransformDirection.DOWN);
}
@Override
public Expression rule(BinaryLogic e) {
if (e instanceof And) {
return propagate((And) e);
} else if (e instanceof Or) {
return propagate((Or) e);
}
return e;
}
// combine conjunction
private static Expression propagate(And and) {
List<Range> ranges = new ArrayList<>();
// Only equalities, not-equalities and inequalities with a foldable .right are extracted separately;
// the others go into the general 'exps'.
List<BinaryComparison> equals = new ArrayList<>();
List<NotEquals> notEquals = new ArrayList<>();
List<BinaryComparison> inequalities = new ArrayList<>();
List<Expression> exps = new ArrayList<>();
boolean changed = false;
for (Expression ex : Predicates.splitAnd(and)) {
if (ex instanceof Range) {
ranges.add((Range) ex);
} else if (ex instanceof Equals || ex instanceof NullEquals) {
BinaryComparison otherEq = (BinaryComparison) ex;
// equals on different values evaluate to FALSE
// ignore date/time fields as equality comparison might actually be a range check
if (otherEq.right().foldable() && DataTypes.isDateTime(otherEq.left().dataType()) == false) {
for (BinaryComparison eq : equals) {
if (otherEq.left().semanticEquals(eq.left())) {
Integer comp = BinaryComparison.compare(eq.right().fold(), otherEq.right().fold());
if (comp != null) {
// var cannot be equal to two different values at the same time
if (comp != 0) {
return new Literal(and.source(), Boolean.FALSE, DataTypes.BOOLEAN);
}
}
}
}
equals.add(otherEq);
} else {
exps.add(otherEq);
}
} else if (ex instanceof GreaterThan
|| ex instanceof GreaterThanOrEqual
|| ex instanceof LessThan
|| ex instanceof LessThanOrEqual) {
BinaryComparison bc = (BinaryComparison) ex;
if (bc.right().foldable()) {
inequalities.add(bc);
} else {
exps.add(ex);
}
} else if (ex instanceof NotEquals otherNotEq) {
if (otherNotEq.right().foldable()) {
notEquals.add(otherNotEq);
} else {
exps.add(ex);
}
} else {
exps.add(ex);
}
}
// check
for (BinaryComparison eq : equals) {
Object eqValue = eq.right().fold();
for (Iterator<Range> iterator = ranges.iterator(); iterator.hasNext();) {
Range range = iterator.next();
if (range.value().semanticEquals(eq.left())) {
// if equals is outside the interval, evaluate the whole expression to FALSE
if (range.lower().foldable()) {
Integer compare = BinaryComparison.compare(range.lower().fold(), eqValue);
if (compare != null && (
// eq outside the lower boundary
compare > 0 ||
// eq matches the boundary but should not be included
(compare == 0 && range.includeLower() == false))) {
return new Literal(and.source(), Boolean.FALSE, DataTypes.BOOLEAN);
}
}
if (range.upper().foldable()) {
Integer compare = BinaryComparison.compare(range.upper().fold(), eqValue);
if (compare != null && (
// eq outside the upper boundary
compare < 0 ||
// eq matches the boundary but should not be included
(compare == 0 && range.includeUpper() == false))) {
return new Literal(and.source(), Boolean.FALSE, DataTypes.BOOLEAN);
}
}
// it's in the range and thus, remove it
iterator.remove();
changed = true;
}
}
// evaluate all NotEquals against the Equal
for (Iterator<NotEquals> iter = notEquals.iterator(); iter.hasNext();) {
NotEquals neq = iter.next();
if (eq.left().semanticEquals(neq.left())) {
Integer comp = BinaryComparison.compare(eqValue, neq.right().fold());
if (comp != null) {
if (comp == 0) { // clashing and conflicting: a = 1 AND a != 1
return new Literal(and.source(), Boolean.FALSE, DataTypes.BOOLEAN);
} else { // clashing and redundant: a = 1 AND a != 2
iter.remove();
changed = true;
}
}
}
}
// evaluate all inequalities against the Equal
for (Iterator<BinaryComparison> iter = inequalities.iterator(); iter.hasNext();) {
BinaryComparison bc = iter.next();
if (eq.left().semanticEquals(bc.left())) {
Integer compare = BinaryComparison.compare(eqValue, bc.right().fold());
if (compare != null) {
if (bc instanceof LessThan || bc instanceof LessThanOrEqual) { // a = 2 AND a </<= ?
if ((compare == 0 && bc instanceof LessThan) || // a = 2 AND a < 2
0 < compare) { // a = 2 AND a </<= 1
return new Literal(and.source(), Boolean.FALSE, DataTypes.BOOLEAN);
}
} else if (bc instanceof GreaterThan || bc instanceof GreaterThanOrEqual) { // a = 2 AND a >/>= ?
if ((compare == 0 && bc instanceof GreaterThan) || // a = 2 AND a > 2
compare < 0) { // a = 2 AND a >/>= 3
return new Literal(and.source(), Boolean.FALSE, DataTypes.BOOLEAN);
}
}
iter.remove();
changed = true;
}
}
}
}
return changed ? Predicates.combineAnd(CollectionUtils.combine(exps, equals, notEquals, inequalities, ranges)) : and;
}
// combine disjunction:
// a = 2 OR a > 3 -> nop; a = 2 OR a > 1 -> a > 1
// a = 2 OR a < 3 -> a < 3; a = 2 OR a < 1 -> nop
// a = 2 OR 3 < a < 5 -> nop; a = 2 OR 1 < a < 3 -> 1 < a < 3; a = 2 OR 0 < a < 1 -> nop
// a = 2 OR a != 2 -> TRUE; a = 2 OR a = 5 -> nop; a = 2 OR a != 5 -> a != 5
private static Expression propagate(Or or) {
List<Expression> exps = new ArrayList<>();
List<Equals> equals = new ArrayList<>(); // foldable right term Equals
List<NotEquals> notEquals = new ArrayList<>(); // foldable right term NotEquals
List<Range> ranges = new ArrayList<>();
List<BinaryComparison> inequalities = new ArrayList<>(); // foldable right term (=limit) BinaryComparision
// split expressions by type
for (Expression ex : Predicates.splitOr(or)) {
if (ex instanceof Equals eq) {
if (eq.right().foldable()) {
equals.add(eq);
} else {
exps.add(ex);
}
} else if (ex instanceof NotEquals neq) {
if (neq.right().foldable()) {
notEquals.add(neq);
} else {
exps.add(ex);
}
} else if (ex instanceof Range) {
ranges.add((Range) ex);
} else if (ex instanceof BinaryComparison bc) {
if (bc.right().foldable()) {
inequalities.add(bc);
} else {
exps.add(ex);
}
} else {
exps.add(ex);
}
}
boolean updated = false; // has the expression been modified?
// evaluate the impact of each Equal over the different types of Expressions
for (Iterator<Equals> iterEq = equals.iterator(); iterEq.hasNext();) {
Equals eq = iterEq.next();
Object eqValue = eq.right().fold();
boolean removeEquals = false;
// Equals OR NotEquals
for (NotEquals neq : notEquals) {
if (eq.left().semanticEquals(neq.left())) { // a = 2 OR a != ? -> ...
Integer comp = BinaryComparison.compare(eqValue, neq.right().fold());
if (comp != null) {
if (comp == 0) { // a = 2 OR a != 2 -> TRUE
return TRUE;
} else { // a = 2 OR a != 5 -> a != 5
removeEquals = true;
break;
}
}
}
}
if (removeEquals) {
iterEq.remove();
updated = true;
continue;
}
// Equals OR Range
for (int i = 0; i < ranges.size(); i++) { // might modify list, so use index loop
Range range = ranges.get(i);
if (eq.left().semanticEquals(range.value())) {
Integer lowerComp = range.lower().foldable() ? BinaryComparison.compare(eqValue, range.lower().fold()) : null;
Integer upperComp = range.upper().foldable() ? BinaryComparison.compare(eqValue, range.upper().fold()) : null;
if (lowerComp != null && lowerComp == 0) {
if (range.includeLower() == false) { // a = 2 OR 2 < a < ? -> 2 <= a < ?
ranges.set(
i,
new Range(
range.source(),
range.value(),
range.lower(),
true,
range.upper(),
range.includeUpper(),
range.zoneId()
)
);
} // else : a = 2 OR 2 <= a < ? -> 2 <= a < ?
removeEquals = true; // update range with lower equality instead or simply superfluous
break;
} else if (upperComp != null && upperComp == 0) {
if (range.includeUpper() == false) { // a = 2 OR ? < a < 2 -> ? < a <= 2
ranges.set(
i,
new Range(
range.source(),
range.value(),
range.lower(),
range.includeLower(),
range.upper(),
true,
range.zoneId()
)
);
} // else : a = 2 OR ? < a <= 2 -> ? < a <= 2
removeEquals = true; // update range with upper equality instead
break;
} else if (lowerComp != null && upperComp != null) {
if (0 < lowerComp && upperComp < 0) { // a = 2 OR 1 < a < 3
removeEquals = true; // equality is superfluous
break;
}
}
}
}
if (removeEquals) {
iterEq.remove();
updated = true;
continue;
}
// Equals OR Inequality
for (int i = 0; i < inequalities.size(); i++) {
BinaryComparison bc = inequalities.get(i);
if (eq.left().semanticEquals(bc.left())) {
Integer comp = BinaryComparison.compare(eqValue, bc.right().fold());
if (comp != null) {
if (bc instanceof GreaterThan || bc instanceof GreaterThanOrEqual) {
if (comp < 0) { // a = 1 OR a > 2 -> nop
continue;
} else if (comp == 0 && bc instanceof GreaterThan) { // a = 2 OR a > 2 -> a >= 2
inequalities.set(i, new GreaterThanOrEqual(bc.source(), bc.left(), bc.right(), bc.zoneId()));
} // else (0 < comp || bc instanceof GreaterThanOrEqual) :
// a = 3 OR a > 2 -> a > 2; a = 2 OR a => 2 -> a => 2
removeEquals = true; // update range with equality instead or simply superfluous
break;
} else if (bc instanceof LessThan || bc instanceof LessThanOrEqual) {
if (comp > 0) { // a = 2 OR a < 1 -> nop
continue;
}
if (comp == 0 && bc instanceof LessThan) { // a = 2 OR a < 2 -> a <= 2
inequalities.set(i, new LessThanOrEqual(bc.source(), bc.left(), bc.right(), bc.zoneId()));
} // else (comp < 0 || bc instanceof LessThanOrEqual) : a = 2 OR a < 3 -> a < 3; a = 2 OR a <= 2 -> a <= 2
removeEquals = true; // update range with equality instead or simply superfluous
break;
}
}
}
}
if (removeEquals) {
iterEq.remove();
updated = true;
}
}
return updated ? Predicates.combineOr(CollectionUtils.combine(exps, equals, notEquals, inequalities, ranges)) : or;
}
}
public static final class CombineBinaryComparisons extends OptimizerExpressionRule<BinaryLogic> {
public CombineBinaryComparisons() {
super(TransformDirection.DOWN);
}
@Override
public Expression rule(BinaryLogic e) {
if (e instanceof And) {
return combine((And) e);
} else if (e instanceof Or) {
return combine((Or) e);
}
return e;
}
// combine conjunction
private static Expression combine(And and) {
List<Range> ranges = new ArrayList<>();
List<BinaryComparison> bcs = new ArrayList<>();
List<Expression> exps = new ArrayList<>();
boolean changed = false;
List<Expression> andExps = Predicates.splitAnd(and);
// Ranges need to show up before BinaryComparisons in list, to allow the latter be optimized away into a Range, if possible.
// NotEquals need to be last in list, to have a complete set of Ranges (ranges) and BinaryComparisons (bcs) and allow these to
// optimize the NotEquals away.
andExps.sort((o1, o2) -> {
if (o1 instanceof Range && o2 instanceof Range) {
return 0; // keep ranges' order
} else if (o1 instanceof Range || o2 instanceof Range) {
return o2 instanceof Range ? 1 : -1; // push Ranges down
} else if (o1 instanceof NotEquals && o2 instanceof NotEquals) {
return 0; // keep NotEquals' order
} else if (o1 instanceof NotEquals || o2 instanceof NotEquals) {
return o1 instanceof NotEquals ? 1 : -1; // push NotEquals up
} else {
return 0; // keep non-Ranges' and non-NotEquals' order
}
});
for (Expression ex : andExps) {
if (ex instanceof Range r) {
if (findExistingRange(r, ranges, true)) {
changed = true;
} else {
ranges.add(r);
}
} else if (ex instanceof BinaryComparison bc && (ex instanceof Equals || ex instanceof NotEquals) == false) {
if (bc.right().foldable() && (findConjunctiveComparisonInRange(bc, ranges) || findExistingComparison(bc, bcs, true))) {
changed = true;
} else {
bcs.add(bc);
}
} else if (ex instanceof NotEquals neq) {
if (neq.right().foldable() && notEqualsIsRemovableFromConjunction(neq, ranges, bcs)) {
// the non-equality can simply be dropped: either superfluous or has been merged with an updated range/inequality
changed = true;
} else { // not foldable OR not overlapping
exps.add(ex);
}
} else {
exps.add(ex);
}
}
// finally try combining any left BinaryComparisons into possible Ranges
// this could be a different rule but it's clearer here wrt the order of comparisons
for (int i = 0, step = 1; i < bcs.size() - 1; i += step, step = 1) {
BinaryComparison main = bcs.get(i);
for (int j = i + 1; j < bcs.size(); j++) {
BinaryComparison other = bcs.get(j);
if (main.left().semanticEquals(other.left())) {
// >/>= AND </<=
if ((main instanceof GreaterThan || main instanceof GreaterThanOrEqual)
&& (other instanceof LessThan || other instanceof LessThanOrEqual)) {
bcs.remove(j);
bcs.remove(i);
ranges.add(
new Range(
and.source(),
main.left(),
main.right(),
main instanceof GreaterThanOrEqual,
other.right(),
other instanceof LessThanOrEqual,
main.zoneId()
)
);
changed = true;
step = 0;
break;
}
// </<= AND >/>=
else if ((other instanceof GreaterThan || other instanceof GreaterThanOrEqual)
&& (main instanceof LessThan || main instanceof LessThanOrEqual)) {
bcs.remove(j);
bcs.remove(i);
ranges.add(
new Range(
and.source(),
main.left(),
other.right(),
other instanceof GreaterThanOrEqual,
main.right(),
main instanceof LessThanOrEqual,
main.zoneId()
)
);
changed = true;
step = 0;
break;
}
}
}
}
return changed ? Predicates.combineAnd(CollectionUtils.combine(exps, bcs, ranges)) : and;
}
// combine disjunction
private static Expression combine(Or or) {
List<BinaryComparison> bcs = new ArrayList<>();
List<Range> ranges = new ArrayList<>();
List<Expression> exps = new ArrayList<>();
boolean changed = false;
for (Expression ex : Predicates.splitOr(or)) {
if (ex instanceof Range r) {
if (findExistingRange(r, ranges, false)) {
changed = true;
} else {
ranges.add(r);
}
} else if (ex instanceof BinaryComparison bc) {
if (bc.right().foldable() && findExistingComparison(bc, bcs, false)) {
changed = true;
} else {
bcs.add(bc);
}
} else {
exps.add(ex);
}
}
return changed ? Predicates.combineOr(CollectionUtils.combine(exps, bcs, ranges)) : or;
}
private static boolean findExistingRange(Range main, List<Range> ranges, boolean conjunctive) {
if (main.lower().foldable() == false && main.upper().foldable() == false) {
return false;
}
// NB: the loop modifies the list (hence why the int is used)
for (int i = 0; i < ranges.size(); i++) {
Range other = ranges.get(i);
if (main.value().semanticEquals(other.value())) {
// make sure the comparison was done
boolean compared = false;
boolean lower = false;
boolean upper = false;
// boundary equality (useful to differentiate whether a range is included or not)
// and thus whether it should be preserved or ignored
boolean lowerEq = false;
boolean upperEq = false;
// evaluate lower
if (main.lower().foldable() && other.lower().foldable()) {
compared = true;
Integer comp = BinaryComparison.compare(main.lower().fold(), other.lower().fold());
// values are comparable
if (comp != null) {
// boundary equality
lowerEq = comp == 0 && main.includeLower() == other.includeLower();
// AND
if (conjunctive) {
// (2 < a < 3) AND (1 < a < 3) -> (2 < a < 3)
lower = comp > 0 ||
// (2 < a < 3) AND (2 <= a < 3) -> (2 < a < 3)
(comp == 0 && main.includeLower() == false && other.includeLower());
}
// OR
else {
// (1 < a < 3) OR (2 < a < 3) -> (1 < a < 3)
lower = comp < 0 ||
// (2 <= a < 3) OR (2 < a < 3) -> (2 <= a < 3)
(comp == 0 && main.includeLower() && other.includeLower() == false) || lowerEq;
}
}
}
// evaluate upper
if (main.upper().foldable() && other.upper().foldable()) {
compared = true;
Integer comp = BinaryComparison.compare(main.upper().fold(), other.upper().fold());
// values are comparable
if (comp != null) {
// boundary equality
upperEq = comp == 0 && main.includeUpper() == other.includeUpper();
// AND
if (conjunctive) {
// (1 < a < 2) AND (1 < a < 3) -> (1 < a < 2)
upper = comp < 0 ||
// (1 < a < 2) AND (1 < a <= 2) -> (1 < a < 2)
(comp == 0 && main.includeUpper() == false && other.includeUpper());
}
// OR
else {
// (1 < a < 3) OR (1 < a < 2) -> (1 < a < 3)
upper = comp > 0 ||
// (1 < a <= 3) OR (1 < a < 3) -> (2 < a < 3)
(comp == 0 && main.includeUpper() && other.includeUpper() == false) || upperEq;
}
}
}
// AND - at least one of lower or upper
if (conjunctive) {
// can tighten range
if (lower || upper) {
ranges.set(
i,
new Range(
main.source(),
main.value(),
lower ? main.lower() : other.lower(),
lower ? main.includeLower() : other.includeLower(),
upper ? main.upper() : other.upper(),
upper ? main.includeUpper() : other.includeUpper(),
main.zoneId()
)
);
}
// range was comparable
return compared;
}
// OR - needs both upper and lower to loosen range
else {
// can loosen range
if (lower && upper) {
ranges.set(
i,
new Range(
main.source(),
main.value(),
main.lower(),
main.includeLower(),
main.upper(),
main.includeUpper(),
main.zoneId()
)
);
return true;
}
// if the range in included, no need to add it
return compared && (((lower && lowerEq == false) || (upper && upperEq == false)) == false);
}
}
}
return false;
}
private static boolean findConjunctiveComparisonInRange(BinaryComparison main, List<Range> ranges) {
Object value = main.right().fold();
// NB: the loop modifies the list (hence why the int is used)
for (int i = 0; i < ranges.size(); i++) {
Range other = ranges.get(i);
if (main.left().semanticEquals(other.value())) {
if (main instanceof GreaterThan || main instanceof GreaterThanOrEqual) {
if (other.lower().foldable()) {
Integer comp = BinaryComparison.compare(value, other.lower().fold());
if (comp != null) {
// 2 < a AND (2 <= a < 3) -> 2 < a < 3
boolean lowerEq = comp == 0 && other.includeLower() && main instanceof GreaterThan;
// 2 < a AND (1 < a < 3) -> 2 < a < 3
boolean lower = comp > 0 || lowerEq;
if (lower) {
ranges.set(
i,
new Range(
other.source(),
other.value(),
main.right(),
lowerEq ? false : main instanceof GreaterThanOrEqual,
other.upper(),
other.includeUpper(),
other.zoneId()
)
);
}
// found a match
return true;
}
}
} else if (main instanceof LessThan || main instanceof LessThanOrEqual) {
if (other.upper().foldable()) {
Integer comp = BinaryComparison.compare(value, other.upper().fold());
if (comp != null) {
// a < 2 AND (1 < a <= 2) -> 1 < a < 2
boolean upperEq = comp == 0 && other.includeUpper() && main instanceof LessThan;
// a < 2 AND (1 < a < 3) -> 1 < a < 2
boolean upper = comp < 0 || upperEq;
if (upper) {
ranges.set(
i,
new Range(
other.source(),
other.value(),
other.lower(),
other.includeLower(),
main.right(),
upperEq ? false : main instanceof LessThanOrEqual,
other.zoneId()
)
);
}
// found a match
return true;
}
}
}
return false;
}
}
return false;
}
/**
* Find commonalities between the given comparison in the given list.
* The method can be applied both for conjunctive (AND) or disjunctive purposes (OR).
*/
private static boolean findExistingComparison(BinaryComparison main, List<BinaryComparison> bcs, boolean conjunctive) {
Object value = main.right().fold();
// NB: the loop modifies the list (hence why the int is used)
for (int i = 0; i < bcs.size(); i++) {
BinaryComparison other = bcs.get(i);