-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathSubexpressionOptimizerTest.java
More file actions
803 lines (696 loc) · 31.6 KB
/
Copy pathSubexpressionOptimizerTest.java
File metadata and controls
803 lines (696 loc) · 31.6 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
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package dev.cel.optimizer.optimizers;
import static com.google.common.truth.Truth.assertThat;
import static dev.cel.common.CelOverloadDecl.newGlobalOverload;
import static org.junit.Assert.assertThrows;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.testing.junit.testparameterinjector.TestParameter;
import com.google.testing.junit.testparameterinjector.TestParameterInjector;
import com.google.testing.junit.testparameterinjector.TestParameters;
import dev.cel.bundle.Cel;
import dev.cel.bundle.CelBuilder;
import dev.cel.bundle.CelFactory;
import dev.cel.common.CelAbstractSyntaxTree;
import dev.cel.common.CelFunctionDecl;
import dev.cel.common.CelMutableAst;
import dev.cel.common.CelOptions;
import dev.cel.common.CelOverloadDecl;
import dev.cel.common.CelSource.Extension;
import dev.cel.common.CelSource.Extension.Component;
import dev.cel.common.CelSource.Extension.Version;
import dev.cel.common.CelValidationException;
import dev.cel.common.CelVarDecl;
import dev.cel.common.ast.CelExpr.ExprKind.Kind;
import dev.cel.common.navigation.CelNavigableMutableAst;
import dev.cel.common.navigation.CelNavigableMutableExpr;
import dev.cel.common.types.ListType;
import dev.cel.common.types.SimpleType;
import dev.cel.common.types.StructTypeReference;
import dev.cel.expr.conformance.proto3.TestAllTypes;
import dev.cel.extensions.CelExtensions;
import dev.cel.optimizer.CelOptimizationException;
import dev.cel.optimizer.CelOptimizer;
import dev.cel.optimizer.CelOptimizerFactory;
import dev.cel.optimizer.optimizers.SubexpressionOptimizer.SubexpressionOptimizerOptions;
import dev.cel.parser.CelStandardMacro;
import dev.cel.parser.CelUnparser;
import dev.cel.parser.CelUnparserFactory;
import dev.cel.runtime.CelAttributePattern;
import dev.cel.runtime.CelEvaluationException;
import dev.cel.runtime.CelFunctionBinding;
import dev.cel.runtime.CelRuntime;
import dev.cel.runtime.CelRuntimeFactory;
import dev.cel.runtime.CelUnknownSet;
import dev.cel.runtime.PartialVars;
import dev.cel.runtime.Program;
import dev.cel.testing.CelRuntimeFlavor;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Before;
import org.junit.Test;
import org.junit.function.ThrowingRunnable;
import org.junit.runner.RunWith;
@RunWith(TestParameterInjector.class)
public class SubexpressionOptimizerTest {
private static Cel setupCelEnv(CelBuilder celBuilder) {
return celBuilder
.addMessageTypes(TestAllTypes.getDescriptor())
.setStandardMacros(CelStandardMacro.STANDARD_MACROS)
.setOptions(
CelOptions.current()
.populateMacroCalls(true)
.enableHeterogeneousNumericComparisons(true)
.build())
.addCompilerLibraries(CelExtensions.bindings(), CelExtensions.strings())
.addRuntimeLibraries(CelExtensions.strings())
.addFunctionDeclarations(
CelFunctionDecl.newFunctionDeclaration(
"non_pure_custom_func",
newGlobalOverload("non_pure_custom_func_overload", SimpleType.INT, SimpleType.INT)))
.addVar("x", SimpleType.DYN)
.addVar("msg", StructTypeReference.create(TestAllTypes.getDescriptor().getFullName()))
.build();
}
private static Cel setupCelForEvaluatingBlock(CelBuilder celBuilder) {
return celBuilder
.setStandardMacros(CelStandardMacro.STANDARD_MACROS)
.addFunctionDeclarations(
// These are test only declarations, as the actual function is made internal using @
// symbol.
// If the main function declaration needs updating, be sure to update the test
// declaration as well.
CelFunctionDecl.newFunctionDeclaration(
"cel.block",
CelOverloadDecl.newGlobalOverload(
"block_test_only_overload",
SimpleType.DYN,
ListType.create(SimpleType.DYN),
SimpleType.DYN)),
SubexpressionOptimizer.newCelBlockFunctionDecl(SimpleType.DYN),
CelFunctionDecl.newFunctionDeclaration(
"get_true",
CelOverloadDecl.newGlobalOverload("get_true_overload", SimpleType.BOOL)))
// Similarly, this is a test only decl (index0 -> @index0)
.addVarDeclarations(
CelVarDecl.newVarDeclaration("c0", SimpleType.DYN),
CelVarDecl.newVarDeclaration("c1", SimpleType.DYN),
CelVarDecl.newVarDeclaration("index0", SimpleType.DYN),
CelVarDecl.newVarDeclaration("index1", SimpleType.DYN),
CelVarDecl.newVarDeclaration("index2", SimpleType.DYN),
CelVarDecl.newVarDeclaration("@index0", SimpleType.DYN),
CelVarDecl.newVarDeclaration("@index1", SimpleType.DYN),
CelVarDecl.newVarDeclaration("@index2", SimpleType.DYN))
.addMessageTypes(TestAllTypes.getDescriptor())
.addVar("msg", StructTypeReference.create(TestAllTypes.getDescriptor().getFullName()))
.build();
}
@TestParameter CelRuntimeFlavor runtimeFlavor;
private Cel cel;
private Cel celForEvaluatingBlock;
@Before
public void setUp() {
this.cel = setupCelEnv(runtimeFlavor.builder());
this.celForEvaluatingBlock = setupCelForEvaluatingBlock(runtimeFlavor.builder());
}
private static final CelUnparser CEL_UNPARSER = CelUnparserFactory.newUnparser();
private static CelBuilder newCelBuilder() {
return CelFactory.standardCelBuilder()
.addMessageTypes(TestAllTypes.getDescriptor())
.setStandardMacros(CelStandardMacro.STANDARD_MACROS)
.setOptions(CelOptions.current().populateMacroCalls(true).build())
.addCompilerLibraries(CelExtensions.bindings())
.addFunctionDeclarations(
CelFunctionDecl.newFunctionDeclaration(
"non_pure_custom_func",
newGlobalOverload("non_pure_custom_func_overload", SimpleType.INT, SimpleType.INT)))
.addVar("x", SimpleType.DYN)
.addVar("msg", StructTypeReference.create(TestAllTypes.getDescriptor().getFullName()));
}
private CelOptimizer newCseOptimizer(SubexpressionOptimizerOptions options) {
return CelOptimizerFactory.standardCelOptimizerBuilder(cel)
.addAstOptimizers(SubexpressionOptimizer.newInstance(options))
.build();
}
@Test
public void cse_resultTypeSet_celBlockOptimizationSuccess() throws Exception {
Cel cel = newCelBuilder().setResultType(SimpleType.BOOL).build();
CelOptimizer celOptimizer =
CelOptimizerFactory.standardCelOptimizerBuilder(cel)
.addAstOptimizers(
SubexpressionOptimizer.newInstance(
SubexpressionOptimizerOptions.newBuilder().build()))
.build();
CelAbstractSyntaxTree ast = cel.compile("size('a') + size('a') == 2").getAst();
CelAbstractSyntaxTree optimizedAst = celOptimizer.optimize(ast);
assertThat(cel.createProgram(optimizedAst).eval()).isEqualTo(true);
assertThat(CEL_UNPARSER.unparse(optimizedAst))
.isEqualTo("cel.@block([size(\"a\")], @index0 + @index0 == 2)");
}
@Test
public void cse_indexEvaluationErrors_throws() throws Exception {
CelAbstractSyntaxTree ast = cel.compile("\"abc\".charAt(10) + \"abc\".charAt(10)").getAst();
CelOptimizer optimizedOptimizer =
CelOptimizerFactory.standardCelOptimizerBuilder(cel)
.addAstOptimizers(SubexpressionOptimizer.getInstance())
.build();
CelAbstractSyntaxTree optimizedAst = optimizedOptimizer.optimize(ast);
String unparsed = CEL_UNPARSER.unparse(optimizedAst);
assertThat(unparsed).isEqualTo("cel.@block([\"abc\".charAt(10)], @index0 + @index0)");
Program program = cel.createProgram(optimizedAst);
CelEvaluationException e =
assertThrows(CelEvaluationException.class, () -> program.eval(ImmutableMap.of()));
assertThat(e).hasMessageThat().contains("charAt failure: Index out of range: 10");
}
@Test
public void cse_withUnknownAttributes() throws Exception {
CelAbstractSyntaxTree ast = cel.compile("size(\"a\") == 1 ? x.y : x.y").getAst();
CelOptimizer optimizer =
CelOptimizerFactory.standardCelOptimizerBuilder(cel)
.addAstOptimizers(SubexpressionOptimizer.getInstance())
.build();
CelAbstractSyntaxTree optimizedAst = optimizer.optimize(ast);
assertThat(CEL_UNPARSER.unparse(optimizedAst))
.isEqualTo("cel.@block([x.y], (size(\"a\") == 1) ? @index0 : @index0)");
Object result =
cel.createProgram(optimizedAst)
.eval(PartialVars.of(CelAttributePattern.fromQualifiedIdentifier("x")));
assertThat(result).isInstanceOf(CelUnknownSet.class);
}
private enum CseNoOpTestCase {
// Nothing to optimize
NO_COMMON_SUBEXPR("size(\"hello\")"),
// Constants and identifiers
INT_CONST_ONLY("2 + 2 + 2 + 2"),
IDENT_ONLY("x + x + x + x"),
BOOL_CONST_ONLY("true == true && false == false"),
// Constants and identifiers within a function
CONST_WITHIN_FUNCTION("size(\"hello\" + \"hello\" + \"hello\")"),
IDENT_WITHIN_FUNCTION("string(x + x + x)"),
// Non-standard functions that have not been explicitly added as a candidate are not
// optimized.
NON_STANDARD_FUNCTION_1("non_pure_custom_func(1) + non_pure_custom_func(1)"),
NON_STANDARD_FUNCTION_2("1 + non_pure_custom_func(1) + 1 + non_pure_custom_func(1)"),
// Duplicated but nested calls.
NESTED_FUNCTION("int(timestamp(int(timestamp(1000000000))))"),
// This cannot be optimized. Extracting the common subexpression would presence test
// the bound identifier (e.g: has(@r0)), which is not valid.
UNOPTIMIZABLE_TERNARY("has(msg.single_any) ? msg.single_any : 10"),
MACRO("[1, 2, 3].exists(x, x > 0)");
private final String source;
CseNoOpTestCase(String source) {
this.source = source;
}
}
@Test
public void cse_withCelBind_noop(@TestParameter CseNoOpTestCase testCase) throws Exception {
CelAbstractSyntaxTree ast = cel.compile(testCase.source).getAst();
CelAbstractSyntaxTree optimizedAst =
newCseOptimizer(SubexpressionOptimizerOptions.newBuilder().populateMacroCalls(true).build())
.optimize(ast);
assertThat(ast.getExpr()).isEqualTo(optimizedAst.getExpr());
assertThat(CEL_UNPARSER.unparse(optimizedAst)).isEqualTo(testCase.source);
}
@Test
public void cse_withCelBlock_noop(@TestParameter CseNoOpTestCase testCase) throws Exception {
CelAbstractSyntaxTree ast = cel.compile(testCase.source).getAst();
CelAbstractSyntaxTree optimizedAst =
newCseOptimizer(SubexpressionOptimizerOptions.newBuilder().populateMacroCalls(true).build())
.optimize(ast);
assertThat(ast.getExpr()).isEqualTo(optimizedAst.getExpr());
assertThat(CEL_UNPARSER.unparse(optimizedAst)).isEqualTo(testCase.source);
}
@Test
public void cse_withComprehensionStructureRetained() throws Exception {
CelAbstractSyntaxTree ast =
cel.compile("['foo'].map(x, [x+x]) + ['foo'].map(x, [x+x, x+x])").getAst();
CelOptimizer celOptimizer =
newCseOptimizer(
SubexpressionOptimizerOptions.newBuilder().populateMacroCalls(true).build());
CelAbstractSyntaxTree optimizedAst = celOptimizer.optimize(ast);
assertThat(CEL_UNPARSER.unparse(optimizedAst))
.isEqualTo(
"cel.@block([[\"foo\"]], @index0.map(@it:0:0, [@it:0:0 + @it:0:0]) +"
+ " @index0.map(@it:0:0, [@it:0:0 + @it:0:0, @it:0:0 + @it:0:0]))");
}
@Test
public void cse_applyConstFoldingBefore() throws Exception {
CelAbstractSyntaxTree ast =
cel.compile("size([1+1+1]) + size([1+1+1]) + size([1,1+1+1]) + size([1,1+1+1]) + x")
.getAst();
CelOptimizer optimizer =
CelOptimizerFactory.standardCelOptimizerBuilder(cel)
.addAstOptimizers(
ConstantFoldingOptimizer.getInstance(),
SubexpressionOptimizer.newInstance(
SubexpressionOptimizerOptions.newBuilder().build()))
.build();
CelAbstractSyntaxTree optimizedAst = optimizer.optimize(ast);
assertThat(CEL_UNPARSER.unparse(optimizedAst)).isEqualTo("6 + x");
}
@Test
public void cse_applyConstFoldingAfter() throws Exception {
CelAbstractSyntaxTree ast =
cel.compile("size([1+1+1]) + size([1+1+1]) + size([1,1+1+1]) + size([1,1+1+1]) + x")
.getAst();
CelOptimizer optimizer =
CelOptimizerFactory.standardCelOptimizerBuilder(cel)
.addAstOptimizers(
SubexpressionOptimizer.newInstance(
SubexpressionOptimizerOptions.newBuilder().build()),
ConstantFoldingOptimizer.getInstance())
.build();
CelAbstractSyntaxTree optimizedAst = optimizer.optimize(ast);
assertThat(CEL_UNPARSER.unparse(optimizedAst))
.isEqualTo("cel.@block([1, 2], @index0 + @index0 + @index1 + @index1 + x)");
}
@Test
public void cse_applyConstFoldingAfter_nothingToFold() throws Exception {
CelAbstractSyntaxTree ast = cel.compile("size(x) + size(x)").getAst();
CelOptimizer optimizer =
CelOptimizerFactory.standardCelOptimizerBuilder(cel)
.addAstOptimizers(
SubexpressionOptimizer.newInstance(
SubexpressionOptimizerOptions.newBuilder().populateMacroCalls(true).build()),
ConstantFoldingOptimizer.getInstance())
.build();
CelAbstractSyntaxTree optimizedAst = optimizer.optimize(ast);
assertThat(CEL_UNPARSER.unparse(optimizedAst))
.isEqualTo("cel.@block([size(x)], @index0 + @index0)");
}
@Test
public void iterationLimitReached_throws() throws Exception {
StringBuilder largeExprBuilder = new StringBuilder();
int iterationLimit = 100;
for (int i = 0; i < iterationLimit; i++) {
largeExprBuilder.append("[1,2]");
if (i < iterationLimit - 1) {
largeExprBuilder.append("+");
}
}
CelAbstractSyntaxTree ast = cel.compile(largeExprBuilder.toString()).getAst();
CelOptimizationException e =
assertThrows(
CelOptimizationException.class,
() ->
newCseOptimizer(
SubexpressionOptimizerOptions.newBuilder()
.iterationLimit(iterationLimit)
.build())
.optimize(ast));
assertThat(e).hasMessageThat().isEqualTo("Optimization failure: Max iteration count reached.");
}
@Test
public void celBlock_astExtensionTagged() throws Exception {
CelAbstractSyntaxTree ast = cel.compile("size(x) + size(x)").getAst();
CelOptimizer optimizer =
CelOptimizerFactory.standardCelOptimizerBuilder(cel)
.addAstOptimizers(
SubexpressionOptimizer.newInstance(
SubexpressionOptimizerOptions.newBuilder().populateMacroCalls(true).build()),
ConstantFoldingOptimizer.getInstance())
.build();
CelAbstractSyntaxTree optimizedAst = optimizer.optimize(ast);
assertThat(optimizedAst.getSource().getExtensions())
.containsExactly(
Extension.create("cel_block", Version.of(1L, 1L), Component.COMPONENT_RUNTIME));
}
@SuppressWarnings("Immutable") // Test only
private enum BlockTestCase {
BOOL_LITERAL("cel.block([true, false], index0 || index1)", true),
STRING_CONCAT("cel.block(['a' + 'b', index0 + 'c'], index1 + 'd')", "abcd"),
BLOCK_WITH_EXISTS_TRUE(
"cel.block([[1, 2, 3], [3, 4, 5].exists(e, e in index0)], index1)", true),
BLOCK_WITH_EXISTS_FALSE("cel.block([[1, 2, 3], ![4, 5].exists(e, e in index0)], index1)", true),
;
private final String source;
private final Object expectedResult;
BlockTestCase(String source, Object expectedResult) {
this.source = source;
this.expectedResult = expectedResult;
}
}
@Test
public void block_success(@TestParameter BlockTestCase testCase) throws Exception {
CelAbstractSyntaxTree ast = compileUsingInternalFunctions(testCase.source);
Object evaluatedResult = celForEvaluatingBlock.createProgram(ast).eval();
assertThat(evaluatedResult).isEqualTo(testCase.expectedResult);
}
@Test
public void block_success_parsedOnly(@TestParameter BlockTestCase testCase) throws Exception {
if (runtimeFlavor.equals(CelRuntimeFlavor.LEGACY)) {
return;
}
CelAbstractSyntaxTree ast =
compileUsingInternalFunctions(testCase.source, /* parsedOnly= */ true);
Object evaluatedResult = celForEvaluatingBlock.createProgram(ast).eval();
assertThat(evaluatedResult).isEqualTo(testCase.expectedResult);
}
@Test
@SuppressWarnings("Immutable") // Test only
public void lazyEval_blockIndexNeverReferenced() throws Exception {
AtomicInteger invocation = new AtomicInteger();
CelRuntime celRuntime =
CelRuntimeFactory.standardCelRuntimeBuilder()
.addMessageTypes(TestAllTypes.getDescriptor())
.addFunctionBindings(
CelFunctionBinding.from(
"get_true_overload",
ImmutableList.of(),
arg -> {
invocation.getAndIncrement();
return true;
}))
.build();
CelAbstractSyntaxTree ast =
compileUsingInternalFunctions(
"cel.block([get_true()], has(msg.single_int64) ? index0 : false)");
boolean result =
(boolean)
celRuntime
.createProgram(ast)
.eval(ImmutableMap.of("msg", TestAllTypes.getDefaultInstance()));
assertThat(result).isFalse();
assertThat(invocation.get()).isEqualTo(0);
}
@Test
@SuppressWarnings("Immutable") // Test only
public void lazyEval_blockIndexEvaluatedOnlyOnce() throws Exception {
AtomicInteger invocation = new AtomicInteger();
CelRuntime celRuntime =
CelRuntimeFactory.standardCelRuntimeBuilder()
.addMessageTypes(TestAllTypes.getDescriptor())
.addFunctionBindings(
CelFunctionBinding.from(
"get_true_overload",
ImmutableList.of(),
arg -> {
invocation.getAndIncrement();
return true;
}))
.build();
CelAbstractSyntaxTree ast =
compileUsingInternalFunctions("cel.block([get_true()], index0 && index0 && index0)");
boolean result = (boolean) celRuntime.createProgram(ast).eval();
assertThat(result).isTrue();
assertThat(invocation.get()).isEqualTo(1);
}
@Test
@SuppressWarnings({"Immutable", "unchecked"}) // Test only
public void lazyEval_withinComprehension_blockIndexEvaluatedOnlyOnce() throws Exception {
AtomicInteger invocation = new AtomicInteger();
CelRuntime celRuntime =
CelRuntimeFactory.standardCelRuntimeBuilder()
.addMessageTypes(TestAllTypes.getDescriptor())
.addFunctionBindings(
CelFunctionBinding.from(
"get_true_overload",
ImmutableList.of(),
arg -> {
invocation.getAndIncrement();
return true;
}))
.build();
CelAbstractSyntaxTree ast =
compileUsingInternalFunctions("cel.block([get_true()], [1,2,3].map(x, x < 0 || index0))");
List<Boolean> result = (List<Boolean>) celRuntime.createProgram(ast).eval();
assertThat(result).containsExactly(true, true, true);
assertThat(invocation.get()).isEqualTo(1);
}
@Test
@SuppressWarnings("Immutable") // Test only
public void lazyEval_multipleBlockIndices_inResultExpr() throws Exception {
AtomicInteger invocation = new AtomicInteger();
CelRuntime celRuntime =
CelRuntimeFactory.standardCelRuntimeBuilder()
.addMessageTypes(TestAllTypes.getDescriptor())
.addFunctionBindings(
CelFunctionBinding.from(
"get_true_overload",
ImmutableList.of(),
arg -> {
invocation.getAndIncrement();
return true;
}))
.build();
CelAbstractSyntaxTree ast =
compileUsingInternalFunctions(
"cel.block([get_true(), get_true(), get_true()], index0 && index0 && index1 && index1"
+ " && index2 && index2)");
boolean result = (boolean) celRuntime.createProgram(ast).eval();
assertThat(result).isTrue();
assertThat(invocation.get()).isEqualTo(3);
}
@Test
@SuppressWarnings("Immutable") // Test only
public void lazyEval_multipleBlockIndices_cascaded() throws Exception {
AtomicInteger invocation = new AtomicInteger();
CelRuntime celRuntime =
CelRuntimeFactory.standardCelRuntimeBuilder()
.addMessageTypes(TestAllTypes.getDescriptor())
.addFunctionBindings(
CelFunctionBinding.from(
"get_true_overload",
ImmutableList.of(),
arg -> {
invocation.getAndIncrement();
return true;
}))
.build();
CelAbstractSyntaxTree ast =
compileUsingInternalFunctions("cel.block([get_true(), index0, index1], index2)");
boolean result = (boolean) celRuntime.createProgram(ast).eval();
assertThat(result).isTrue();
assertThat(invocation.get()).isEqualTo(1);
}
@Test
@SuppressWarnings("Immutable") // Test only
public void lazyEval_nestedComprehension_indexReferencedInNestedScopes() throws Exception {
AtomicInteger invocation = new AtomicInteger();
CelRuntime celRuntime =
CelRuntimeFactory.standardCelRuntimeBuilder()
.addMessageTypes(TestAllTypes.getDescriptor())
.addFunctionBindings(
CelFunctionBinding.from(
"get_true_overload",
ImmutableList.of(),
arg -> {
invocation.getAndIncrement();
return true;
}))
.build();
// Equivalent of [true, false, true].map(c0, [c0].map(c1, [c0, c1, true]))
CelAbstractSyntaxTree ast =
compileUsingInternalFunctions(
"cel.block([true, false, get_true()], [index2, false, index2].map(c0, [c0].map(c1, [c0,"
+ " c1, index2]))) == [[[true, true, true]], [[false, false, true]], [[true, true,"
+ " true]]]");
boolean result = (boolean) celRuntime.createProgram(ast).eval();
assertThat(result).isTrue();
// Even though the function get_true() is referenced across different comprehension scopes,
// it still gets memoized only once.
assertThat(invocation.get()).isEqualTo(1);
}
@Test
@TestParameters("{source: 'cel.block([])'}")
@TestParameters("{source: 'cel.block([1])'}")
@TestParameters("{source: 'cel.block(1, 2)'}")
@TestParameters("{source: 'cel.block(1, [1])'}")
public void block_invalidArguments_throws(String source) {
CelValidationException e =
assertThrows(CelValidationException.class, () -> compileUsingInternalFunctions(source));
assertThat(e).hasMessageThat().contains("found no matching overload for 'cel.block'");
}
@Test
public void blockIndex_invalidArgument_throws() {
CelValidationException e =
assertThrows(
CelValidationException.class,
() -> compileUsingInternalFunctions("cel.block([1], index)"));
assertThat(e).hasMessageThat().contains("undeclared reference");
}
@Test
public void verifyOptimizedAstCorrectness_twoCelBlocks_throws() throws Exception {
CelAbstractSyntaxTree ast =
compileUsingInternalFunctions("cel.block([1, 2], cel.block([2], 3))");
IllegalArgumentException e =
assertThrows(
IllegalArgumentException.class,
() -> SubexpressionOptimizer.verifyOptimizedAstCorrectness(ast));
assertThat(e)
.hasMessageThat()
.isEqualTo("Expected 1 cel.block function to be present but found 2");
}
@Test
public void verifyOptimizedAstCorrectness_celBlockNotAtRoot_throws() throws Exception {
CelAbstractSyntaxTree ast = compileUsingInternalFunctions("1 + cel.block([1, 2], index0)");
IllegalArgumentException e =
assertThrows(
IllegalArgumentException.class,
() -> SubexpressionOptimizer.verifyOptimizedAstCorrectness(ast));
assertThat(e).hasMessageThat().isEqualTo("Expected cel.block to be present at root");
}
@Test
public void verifyOptimizedAstCorrectness_blockContainsNoIndexResult_throws() throws Exception {
CelAbstractSyntaxTree ast = compileUsingInternalFunctions("cel.block([1, index0], 2)");
IllegalArgumentException e =
assertThrows(
IllegalArgumentException.class,
() -> SubexpressionOptimizer.verifyOptimizedAstCorrectness(ast));
assertThat(e)
.hasMessageThat()
.isEqualTo("Expected at least one reference of index in cel.block result");
}
@Test
@TestParameters("{source: 'cel.block([], index0)'}")
@TestParameters("{source: 'cel.block([1, 2], index2)'}")
public void verifyOptimizedAstCorrectness_indexOutOfBounds_throws(String source)
throws Exception {
CelAbstractSyntaxTree ast = compileUsingInternalFunctions(source);
IllegalArgumentException e =
assertThrows(
IllegalArgumentException.class,
() -> SubexpressionOptimizer.verifyOptimizedAstCorrectness(ast));
assertThat(e)
.hasMessageThat()
.contains("Illegal block index found. The index value must be less than");
}
@Test
@TestParameters("{source: 'cel.block([index0], index0)'}")
@TestParameters("{source: 'cel.block([1, index1, 2], index2)'}")
@TestParameters("{source: 'cel.block([1, 2, index2], index2)'}")
@TestParameters("{source: 'cel.block([index2, 1, 2], index2)'}")
public void verifyOptimizedAstCorrectness_indexIsNotForwardReferencing_throws(String source)
throws Exception {
CelAbstractSyntaxTree ast = compileUsingInternalFunctions(source);
IllegalArgumentException e =
assertThrows(
IllegalArgumentException.class,
() -> SubexpressionOptimizer.verifyOptimizedAstCorrectness(ast));
assertThat(e)
.hasMessageThat()
.contains("Illegal block index found. The index value must be less than");
}
@Test
public void block_containsCycle_throws() throws Exception {
CelAbstractSyntaxTree ast = compileUsingInternalFunctions("cel.block([index1,index0],index0)");
ThrowingRunnable evaluateProgram = () -> cel.createProgram(ast).eval();
CelEvaluationException e = assertThrows(CelEvaluationException.class, evaluateProgram);
assertThat(e)
.hasMessageThat()
.containsMatch(
"Cycle detected: @index0|Illegal block index found. The index value must be less than"
+ " 0.");
}
@Test
public void block_lazyEvaluationContainsError_cleansUpCycleState() throws Exception {
CelAbstractSyntaxTree ast =
compileUsingInternalFunctions(
"cel.block([1/0 > 0], (index0 && false) || (index0 && true))");
CelEvaluationException e =
assertThrows(CelEvaluationException.class, () -> cel.createProgram(ast).eval());
assertThat(e).hasMessageThat().contains("/ by zero");
assertThat(e).hasMessageThat().doesNotContain("Cycle detected");
}
@Test
public void cse_nestedMacro_noOp_assertAstIdCorrectness() throws Exception {
Cel cel =
runtimeFlavor
.builder()
.addVar("x", SimpleType.DYN)
.setStandardMacros(CelStandardMacro.STANDARD_MACROS)
.setOptions(CelOptions.current().populateMacroCalls(true).build())
.addCompilerLibraries(CelExtensions.comprehensions())
.addRuntimeLibraries(CelExtensions.comprehensions())
.build();
CelOptimizer celOptimizer =
CelOptimizerFactory.standardCelOptimizerBuilder(cel)
.addAstOptimizers(SubexpressionOptimizer.getInstance())
.build();
CelAbstractSyntaxTree ast =
cel.compile("[{}, {\"a\": 1}, {\"b\": 2}].filter(m, has(x.a))").getAst();
CelAbstractSyntaxTree optimizedAst = celOptimizer.optimize(ast);
assertThat(CEL_UNPARSER.unparse(optimizedAst))
.isEqualTo("[{}, {\"a\": 1}, {\"b\": 2}].filter(m, has(x.a))");
assertThat(optimizedAst).isSameInstanceAs(ast);
}
@Test
public void cse_nestedMacro_withOptimization_assertAstIdCorrectness() throws Exception {
Cel cel =
runtimeFlavor
.builder()
.addVar("x", SimpleType.DYN)
.setStandardMacros(CelStandardMacro.STANDARD_MACROS)
.setOptions(
CelOptions.current()
.populateMacroCalls(true)
.enableHeterogeneousNumericComparisons(true)
.build())
.addCompilerLibraries(CelExtensions.comprehensions())
.addRuntimeLibraries(CelExtensions.comprehensions())
.build();
CelOptimizer celOptimizer =
CelOptimizerFactory.standardCelOptimizerBuilder(cel)
.addAstOptimizers(
SubexpressionOptimizer.newInstance(
SubexpressionOptimizerOptions.newBuilder().populateMacroCalls(true).build()))
.build();
CelAbstractSyntaxTree ast =
cel.compile(
"[{}, {\"a\": 1}, {\"b\": 2}].filter(m, has(x.a)) == [{}, {\"a\": 1}, {\"b\":"
+ " 2}].filter(m, has(x.a))")
.getAst();
CelAbstractSyntaxTree optimizedAst = celOptimizer.optimize(ast);
assertThat(CEL_UNPARSER.unparse(optimizedAst))
.isEqualTo(
"cel.@block([[{}, {\"a\": 1}, {\"b\": 2}].filter(@it:0:0, has(x.a))], @index0 =="
+ " @index0)");
}
/**
* Converts AST containing cel.block related test functions to internal functions (e.g: cel.block
* -> cel.@block)
*/
private CelAbstractSyntaxTree compileUsingInternalFunctions(String expression, boolean parsedOnly)
throws CelValidationException {
CelAbstractSyntaxTree astToModify = celForEvaluatingBlock.compile(expression).getAst();
CelMutableAst mutableAst = CelMutableAst.fromCelAst(astToModify);
CelNavigableMutableAst.fromAst(mutableAst)
.getRoot()
.allNodes()
.filter(node -> node.getKind().equals(Kind.CALL))
.map(CelNavigableMutableExpr::expr)
.filter(expr -> expr.call().function().equals("cel.block"))
.forEach(expr -> expr.call().setFunction("cel.@block"));
CelNavigableMutableAst.fromAst(mutableAst)
.getRoot()
.allNodes()
.filter(node -> node.getKind().equals(Kind.IDENT))
.map(CelNavigableMutableExpr::expr)
.filter(expr -> expr.ident().name().startsWith("index"))
.forEach(
indexExpr -> {
String internalIdentName = "@" + indexExpr.ident().name();
indexExpr.ident().setName(internalIdentName);
});
if (parsedOnly) {
return mutableAst.toParsedAst();
}
return celForEvaluatingBlock.check(mutableAst.toParsedAst()).getAst();
}
private CelAbstractSyntaxTree compileUsingInternalFunctions(String expression)
throws CelValidationException {
return compileUsingInternalFunctions(expression, false);
}
}