-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathAstMutator.java
More file actions
1183 lines (1069 loc) · 50.6 KB
/
Copy pathAstMutator.java
File metadata and controls
1183 lines (1069 loc) · 50.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
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 2023 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;
import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static java.lang.Math.max;
import static java.util.stream.Collectors.toCollection;
import com.google.auto.value.AutoOneOf;
import com.google.auto.value.AutoValue;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Streams;
import com.google.common.collect.Table;
import com.google.errorprone.annotations.Immutable;
import dev.cel.common.CelAbstractSyntaxTree;
import dev.cel.common.CelMutableAst;
import dev.cel.common.CelMutableSource;
import dev.cel.common.ast.CelExpr.ExprKind;
import dev.cel.common.ast.CelExprIdGeneratorFactory;
import dev.cel.common.ast.CelExprIdGeneratorFactory.ExprIdGenerator;
import dev.cel.common.ast.CelExprIdGeneratorFactory.StableIdGenerator;
import dev.cel.common.ast.CelMutableExpr;
import dev.cel.common.ast.CelMutableExpr.CelMutableCall;
import dev.cel.common.ast.CelMutableExpr.CelMutableComprehension;
import dev.cel.common.ast.CelMutableExpr.CelMutableList;
import dev.cel.common.navigation.CelNavigableMutableAst;
import dev.cel.common.navigation.CelNavigableMutableExpr;
import dev.cel.common.navigation.TraversalOrder;
import dev.cel.common.types.CelType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/** AstMutator contains logic for mutating a {@link CelAbstractSyntaxTree}. */
@Immutable
public final class AstMutator {
private static final ExprIdGenerator NO_OP_ID_GENERATOR = id -> id;
private static final ExprIdGenerator UNSET_ID_GENERATOR = id -> 0;
private final long iterationLimit;
/**
* Returns a new instance of an AST mutator with the iteration limit set.
*
* <p>Mutation is performed by walking the existing AST until the expression node to replace is
* found, then the new subtree is walked to complete the mutation. Visiting of each node
* increments the iteration counter. Replace subtree operations will throw an exception if this
* counter reaches the limit.
*
* @param iterationLimit Must be greater than 0.
*/
public static AstMutator newInstance(long iterationLimit) {
return new AstMutator(iterationLimit);
}
private AstMutator(long iterationLimit) {
Preconditions.checkState(iterationLimit > 0L);
this.iterationLimit = iterationLimit;
}
/** Replaces all the expression IDs in the expression tree with 0. */
public CelMutableExpr clearExprIds(CelMutableExpr expr) {
return renumberExprIds(UNSET_ID_GENERATOR, expr);
}
/** Wraps the given AST and its subexpressions with a new cel.@block call. */
public CelMutableAst wrapAstWithNewCelBlock(
String celBlockFunction, CelMutableAst ast, List<CelMutableExpr> subexpressions) {
long maxId = getMaxId(ast);
CelMutableExpr blockExpr =
CelMutableExpr.ofCall(
++maxId,
CelMutableCall.create(
celBlockFunction,
CelMutableExpr.ofList(++maxId, CelMutableList.create(subexpressions)),
ast.expr()));
return CelMutableAst.of(blockExpr, ast.source());
}
/**
* Constructs a new global call wrapped in an AST with the provided ASTs as its argument. This
* will preserve all macro source information contained within the arguments.
*/
public CelMutableAst newGlobalCall(String function, Collection<CelMutableAst> args) {
return newCallAst(Optional.empty(), function, args);
}
/**
* Constructs a new global call wrapped in an AST with the provided ASTs as its argument. This
* will preserve all macro source information contained within the arguments.
*/
public CelMutableAst newGlobalCall(String function, CelMutableAst... args) {
return newGlobalCall(function, Arrays.asList(args));
}
/**
* Constructs a new member call wrapped in an AST the provided ASTs as its arguments. This will
* preserve all macro source information contained within the arguments.
*/
public CelMutableAst newMemberCall(CelMutableAst target, String function, CelMutableAst... args) {
return newMemberCall(target, function, Arrays.asList(args));
}
/**
* Constructs a new member call wrapped in an AST the provided ASTs as its arguments. This will
* preserve all macro source information contained within the arguments.
*/
public CelMutableAst newMemberCall(
CelMutableAst target, String function, Collection<CelMutableAst> args) {
return newCallAst(Optional.of(target), function, args);
}
private CelMutableAst newCallAst(
Optional<CelMutableAst> target, String function, Collection<CelMutableAst> args) {
long maxId = 0;
CelMutableSource combinedSource = CelMutableSource.newInstance();
for (CelMutableAst arg : args) {
CelMutableAst stableArg = stabilizeAst(arg, maxId);
maxId = getMaxId(stableArg);
combinedSource = combine(combinedSource, stableArg.source());
}
Optional<CelMutableAst> maybeTarget = Optional.empty();
if (target.isPresent()) {
CelMutableAst stableTarget = stabilizeAst(target.get(), maxId);
combinedSource = combine(combinedSource, stableTarget.source());
maxId = getMaxId(stableTarget);
maybeTarget = Optional.of(stableTarget);
}
List<CelMutableExpr> exprArgs =
args.stream().map(CelMutableAst::expr).collect(toCollection(ArrayList::new));
CelMutableCall newCall =
maybeTarget
.map(celMutableAst -> CelMutableCall.create(celMutableAst.expr(), function, exprArgs))
.orElseGet(() -> CelMutableCall.create(function, exprArgs));
CelMutableExpr newCallExpr = CelMutableExpr.ofCall(++maxId, newCall);
return CelMutableAst.of(newCallExpr, combinedSource);
}
/** Renumbers all the expr IDs in the given AST in a consecutive manner starting from 1. */
public CelMutableAst renumberIdsConsecutively(CelMutableAst mutableAst) {
StableIdGenerator stableIdGenerator = CelExprIdGeneratorFactory.newStableIdGenerator(0);
CelMutableExpr mutableExpr = renumberExprIds(stableIdGenerator::renumberId, mutableAst.expr());
CelMutableSource newSource =
normalizeMacroSource(
mutableAst.source(), Integer.MIN_VALUE, mutableExpr, stableIdGenerator::renumberId);
return CelMutableAst.of(mutableExpr, newSource);
}
/**
* Replaces all comprehension identifier names with a unique name based on the given prefix.
*
* <p>The purpose of this is to avoid errors that can be caused by shadowed variables while
* augmenting an AST. As an example: {@code [2, 3].exists(x, x - 1 > 3) || x - 1 > 3}. Note that
* the scoping of `x - 1` is different between th two LOGICAL_OR branches. Iteration variable `x`
* in `exists` will be mangled to {@code [2, 3].exists(@c0, @c0 - 1 > 3) || x - 1 > 3} to avoid
* erroneously extracting x - 1 as common subexpression.
*
* <p>The expression IDs are not modified when the identifier names are changed.
*
* <p>Mangling occurs only if the iteration variable is referenced within the loop step.
*
* <p>Iteration variables in comprehensions are numbered based on their comprehension nesting
* levels and the iteration variable's type. Examples:
*
* <ul>
* <li>{@code [true].exists(i, i) && [true].exists(j, j)} -> {@code [true].exists(@c0:0, @c0:0)
* && [true].exists(@c0:0, @c0:0)} // Note that i,j gets replaced to the same @c0:0 in this
* example as they share the same nesting level and type.
* <li>{@code [1].exists(i, i > 0) && [1u].exists(j, j > 0u)} -> {@code [1].exists(@c0:0, @c0:0
* > 0) && [1u].exists(@c0:1, @c0:1 > 0u)}
* <li>{@code [true].exists(i, i && [true].exists(j, j))} -> {@code [true].exists(@c0:0, @c0:0
* && [true].exists(@c1:0, @c1:0))}
* </ul>
*
* @param ast AST containing type-checked references
* @param newIterVarPrefix Prefix to use for new iteration variable identifier name. For example,
* providing @c will produce @c0:0, @c0:1, @c1:0, @c2:0... as new names.
* @param newAccuVarPrefix Prefix to use for new accumulation variable identifier name.
*/
public MangledComprehensionAst mangleComprehensionIdentifierNames(
CelMutableAst ast,
String newIterVarPrefix,
String newIterVar2Prefix,
String newAccuVarPrefix) {
CelNavigableMutableAst navigableMutableAst = CelNavigableMutableAst.fromAst(ast);
Predicate<CelNavigableMutableExpr> comprehensionIdentifierPredicate = x -> true;
comprehensionIdentifierPredicate =
comprehensionIdentifierPredicate
.and(node -> node.getKind().equals(ExprKind.Kind.COMPREHENSION))
.and(node -> !node.expr().comprehension().iterVar().startsWith(newIterVarPrefix + ":"))
.and(node -> !node.expr().comprehension().accuVar().startsWith(newAccuVarPrefix + ":"))
.and(
node ->
!node.expr().comprehension().iterVar2().startsWith(newIterVar2Prefix + ":"));
LinkedHashMap<CelNavigableMutableExpr, MangledComprehensionType> comprehensionsToMangle =
navigableMutableAst
.getRoot()
// This is important - mangling needs to happen bottom-up to avoid stepping over
// shadowed variables that are not part of the comprehension being mangled.
.allNodes(TraversalOrder.POST_ORDER)
.filter(comprehensionIdentifierPredicate)
.filter(
node -> {
// Ensure the iter_var or the comprehension result is actually referenced in the
// loop_step. If it's not, we can skip mangling.
String iterVar = node.expr().comprehension().iterVar();
String iterVar2 = node.expr().comprehension().iterVar2();
String result = node.expr().comprehension().result().ident().name();
return CelNavigableMutableExpr.fromExpr(node.expr().comprehension().loopStep())
.allNodes()
.filter(subNode -> subNode.getKind().equals(ExprKind.Kind.IDENT))
.map(subNode -> subNode.expr().ident())
.anyMatch(
ident ->
ident.name().contains(iterVar)
|| ident.name().contains(iterVar2)
|| ident.name().contains(result));
})
.collect(
Collectors.toMap(
k -> k,
v -> {
CelMutableComprehension comprehension = v.expr().comprehension();
String iterVar = comprehension.iterVar();
String iterVar2 = comprehension.iterVar2();
// Identifiers to mangle could be the iteration variable, comprehension
// result or both, but at least one has to exist.
// As an example, [1,2].map(i, 3) would result in optional.empty for iteration
// variable because `i` is not actually used.
Optional<Long> iterVarId =
CelNavigableMutableExpr.fromExpr(comprehension.loopStep())
.allNodes()
.filter(
loopStepNode ->
loopStepNode.getKind().equals(ExprKind.Kind.IDENT)
&& loopStepNode.expr().ident().name().equals(iterVar))
.map(CelNavigableMutableExpr::id)
.findAny();
Optional<Long> iterVar2Id =
CelNavigableMutableExpr.fromExpr(comprehension.loopStep())
.allNodes()
.filter(
loopStepNode ->
!iterVar2.isEmpty()
&& loopStepNode.getKind().equals(ExprKind.Kind.IDENT)
&& loopStepNode.expr().ident().name().equals(iterVar2))
.map(CelNavigableMutableExpr::id)
.findAny();
Optional<CelType> iterVarType =
iterVarId.map(
id ->
navigableMutableAst
.getType(id)
.orElseThrow(
() ->
new NoSuchElementException(
"Checked type not present for iteration"
+ " variable: "
+ iterVarId)));
Optional<CelType> iterVar2Type =
iterVar2Id.map(
id ->
navigableMutableAst
.getType(id)
.orElseThrow(
() ->
new NoSuchElementException(
"Checked type not present for iteration"
+ " variable: "
+ iterVar2Id)));
CelType resultType =
navigableMutableAst
.getType(comprehension.result().id())
.orElseThrow(
() ->
new IllegalStateException(
"Result type was not present for the comprehension ID: "
+ comprehension.result().id()));
return MangledComprehensionType.of(iterVarType, iterVar2Type, resultType);
},
(x, y) -> {
throw new IllegalStateException(
"Unexpected CelNavigableMutableExpr collision");
},
LinkedHashMap::new));
// The map that we'll eventually return to the caller.
HashMap<MangledComprehensionName, MangledComprehensionType> mangledIdentNamesToType =
new HashMap<>();
// Intermediary table used for the purposes of generating a unique mangled variable name.
Table<Integer, MangledComprehensionType, MangledComprehensionName> comprehensionLevelToType =
HashBasedTable.create();
CelMutableExpr mutatedComprehensionExpr = navigableMutableAst.getAst().expr();
CelMutableSource newSource = navigableMutableAst.getAst().source();
int iterCount = 0;
for (Entry<CelNavigableMutableExpr, MangledComprehensionType> comprehensionEntry :
comprehensionsToMangle.entrySet()) {
CelNavigableMutableExpr comprehensionNode = comprehensionEntry.getKey();
MangledComprehensionType comprehensionEntryType = comprehensionEntry.getValue();
CelMutableExpr comprehensionExpr = comprehensionNode.expr();
MangledComprehensionName mangledComprehensionName =
getMangledComprehensionName(
newIterVarPrefix,
newIterVar2Prefix,
newAccuVarPrefix,
comprehensionNode,
comprehensionLevelToType,
comprehensionEntryType);
mangledIdentNamesToType.put(mangledComprehensionName, comprehensionEntryType);
String iterVar = comprehensionExpr.comprehension().iterVar();
String iterVar2 = comprehensionExpr.comprehension().iterVar2();
String accuVar = comprehensionExpr.comprehension().accuVar();
mutatedComprehensionExpr =
mangleIdentsInComprehensionExpr(
mutatedComprehensionExpr,
comprehensionExpr,
iterVar,
iterVar2,
accuVar,
mangledComprehensionName);
// Repeat the mangling process for the macro source.
newSource =
mangleIdentsInMacroSource(
newSource,
mutatedComprehensionExpr,
iterVar,
iterVar2,
mangledComprehensionName,
comprehensionExpr.id());
iterCount++;
}
if (iterCount >= iterationLimit) {
// Note that it's generally impossible to reach this for a well-formed AST. The nesting level
// of AST being mutated is always deeper than the number of identifiers being mangled, thus
// the mutation operation should throw before we ever reach here.
throw new IllegalStateException("Max iteration count reached.");
}
return MangledComprehensionAst.of(
CelMutableAst.of(mutatedComprehensionExpr, newSource),
ImmutableMap.copyOf(mangledIdentNamesToType));
}
private static MangledComprehensionName getMangledComprehensionName(
String newIterVarPrefix,
String newIterVar2Prefix,
String newResultPrefix,
CelNavigableMutableExpr comprehensionNode,
Table<Integer, MangledComprehensionType, MangledComprehensionName> comprehensionLevelToType,
MangledComprehensionType comprehensionEntryType) {
MangledComprehensionName mangledComprehensionName;
int comprehensionNestingLevel = countComprehensionNestingLevel(comprehensionNode);
if (comprehensionLevelToType.contains(comprehensionNestingLevel, comprehensionEntryType)) {
mangledComprehensionName =
comprehensionLevelToType.get(comprehensionNestingLevel, comprehensionEntryType);
} else {
// First time encountering the pair of <ComprehensionLevel, CelType>. Generate a unique
// mangled variable name for this.
int uniqueTypeIdx = comprehensionLevelToType.row(comprehensionNestingLevel).size();
String mangledIterVarName =
newIterVarPrefix + ":" + comprehensionNestingLevel + ":" + uniqueTypeIdx;
String mangledResultName =
newResultPrefix + ":" + comprehensionNestingLevel + ":" + uniqueTypeIdx;
String mangledIterVar2Name =
newIterVar2Prefix + ":" + comprehensionNestingLevel + ":" + uniqueTypeIdx;
mangledComprehensionName =
MangledComprehensionName.of(mangledIterVarName, mangledIterVar2Name, mangledResultName);
comprehensionLevelToType.put(
comprehensionNestingLevel, comprehensionEntryType, mangledComprehensionName);
}
return mangledComprehensionName;
}
private static int countComprehensionNestingLevel(CelNavigableMutableExpr comprehensionExpr) {
return comprehensionExpr
.descendants()
.filter(node -> node.getKind().equals(ExprKind.Kind.COMPREHENSION))
.mapToInt(
node -> {
int nestedLevel = 1;
CelNavigableMutableExpr maybeParent = node.parent().orElse(null);
while (maybeParent != null && maybeParent.id() != comprehensionExpr.id()) {
if (maybeParent.getKind().equals(ExprKind.Kind.COMPREHENSION)) {
nestedLevel++;
}
maybeParent = maybeParent.parent().orElse(null);
}
return nestedLevel;
})
.max()
.orElse(0);
}
/**
* Replaces a subtree in the given expression node. This operation is intended for AST
* optimization purposes.
*
* <p>This is a very dangerous operation. Callers must re-typecheck the mutated AST and
* additionally verify that the resulting AST is semantically valid.
*
* <p>All expression IDs will be renumbered in a stable manner to ensure there's no ID collision
* between the nodes. The renumbering occurs even if the subtree was not replaced.
*
* <p>If the ability to unparse an expression containing a macro call must be retained, use {@link
* #replaceSubtree(CelMutableAst, CelMutableAst, long) instead.}
*
* @param root Original expression node to rewrite.
* @param newExpr New CelExpr to replace the subtree with.
* @param exprIdToReplace Expression id of the subtree that is getting replaced.
*/
public CelMutableAst replaceSubtree(
CelMutableExpr root, CelMutableExpr newExpr, long exprIdToReplace) {
return replaceSubtree(
CelMutableAst.of(root, CelMutableSource.newInstance()), newExpr, exprIdToReplace);
}
/**
* Replaces a subtree in the given AST. This operation is intended for AST optimization purposes.
*
* <p>This is a very dangerous operation. Callers must re-typecheck the mutated AST and
* additionally verify that the resulting AST is semantically valid.
*
* <p>All expression IDs will be renumbered in a stable manner to ensure there's no ID collision
* between the nodes. The renumbering occurs even if the subtree was not replaced.
*
* <p>This will scrub out the description, positions and line offsets from {@code CelSource}. If
* the source contains macro calls, its call IDs will be to be consistent with the renumbered IDs
* in the AST.
*
* @param ast Original ast to mutate.
* @param newExpr New CelExpr to replace the subtree with.
* @param exprIdToReplace Expression id of the subtree that is getting replaced.
*/
public CelMutableAst replaceSubtree(
CelMutableAst ast, CelMutableExpr newExpr, long exprIdToReplace) {
return replaceSubtree(
ast,
CelMutableAst.of(
newExpr,
// Copy the macro call information to the new AST such that macro call map can be
// normalized post-replacement.
ast.source()),
exprIdToReplace);
}
/**
* Replaces a subtree in the given AST. This operation is intended for AST optimization purposes.
*
* <p>This is a very dangerous operation. Callers must re-typecheck the mutated AST and
* additionally verify that the resulting AST is semantically valid.
*
* <p>All expression IDs will be renumbered in a stable manner to ensure there's no ID collision
* between the nodes. The renumbering occurs even if the subtree was not replaced.
*
* <p>This will scrub out the description, positions and line offsets from {@code CelSource}. If
* the source contains macro calls, its call IDs will be to be consistent with the renumbered IDs
* in the AST.
*
* @param ast Original ast to mutate.
* @param newAst New AST to replace the subtree with.
* @param exprIdToReplace Expression id of the subtree that is getting replaced.
*/
public CelMutableAst replaceSubtree(
CelMutableAst ast, CelMutableAst newAst, long exprIdToReplace) {
return replaceSubtree(
CelNavigableMutableAst.fromAst(ast),
CelNavigableMutableAst.fromAst(newAst),
exprIdToReplace);
}
/**
* Replaces a subtree in the given AST. This operation is intended for AST optimization purposes.
*
* <p>This is a very dangerous operation. Callers must re-typecheck the mutated AST and
* additionally verify that the resulting AST is semantically valid.
*
* <p>All expression IDs will be renumbered in a stable manner to ensure there's no ID collision
* between the nodes. The renumbering occurs even if the subtree was not replaced.
*
* <p>This will scrub out the description, positions and line offsets from {@code CelSource}. If
* the source contains macro calls, its call IDs will be to be consistent with the renumbered IDs
* in the AST.
*
* @param navAst Original navigable ast to mutate.
* @param navNewAst New navigable AST to replace the subtree with.
* @param exprIdToReplace Expression id of the subtree that is getting replaced.
*/
public CelMutableAst replaceSubtree(
CelNavigableMutableAst navAst, CelNavigableMutableAst navNewAst, long exprIdToReplace) {
// Stabilize the incoming AST by renumbering all of its expression IDs.
long maxId = max(getMaxId(navAst), getMaxId(navNewAst));
CelMutableAst ast = navAst.getAst();
CelMutableAst newAst = navNewAst.getAst();
newAst = stabilizeAst(newAst, maxId);
long stablizedNewExprRootId = newAst.expr().id();
// Mutate the AST root with the new subtree. All the existing expr IDs are renumbered in the
// process, but its original IDs are memoized so that we can normalize the expr IDs
// in the macro source map.
StableIdGenerator stableIdGenerator =
CelExprIdGeneratorFactory.newStableIdGenerator(getMaxId(newAst));
CelMutableExpr mutatedRoot =
mutateExpr(stableIdGenerator::renumberId, ast.expr(), newAst.expr(), exprIdToReplace);
CelMutableSource newAstSource =
CelMutableSource.newInstance().setDescription(ast.source().getDescription());
if (!ast.source().getMacroCalls().isEmpty()) {
newAstSource = combine(newAstSource, ast.source());
}
if (!newAst.source().getMacroCalls().isEmpty()) {
stableIdGenerator.memoize(
stablizedNewExprRootId, stableIdGenerator.renumberId(exprIdToReplace));
newAstSource = combine(newAstSource, newAst.source());
}
newAstSource =
normalizeMacroSource(
newAstSource, exprIdToReplace, mutatedRoot, stableIdGenerator::renumberId);
return CelMutableAst.of(mutatedRoot, newAstSource);
}
/**
* Replaces a subtree in the given AST with the specified {@link SubtreeReplacement}.
*
* <p>This operation is intended for AST optimization purposes.
*
* <p>This is a very dangerous operation. Callers must re-typecheck the mutated AST and
* additionally verify that the resulting AST is semantically valid.
*
* <p>All expression IDs will be renumbered in a stable manner to ensure there's no ID collision
* between the nodes. The renumbering occurs even if the subtree was not replaced.
*
* @param ast Original AST to mutate.
* @param replacement Subtree replacement containing the target node ID and the new expression or
* AST.
*/
public CelMutableAst replaceSubtree(CelMutableAst ast, SubtreeReplacement replacement) {
Preconditions.checkNotNull(ast);
Preconditions.checkNotNull(replacement);
switch (replacement.replacement().kind()) {
case EXPR:
return replaceSubtree(ast, replacement.replacement().expr(), replacement.exprIdToReplace());
case AST:
return replaceSubtree(ast, replacement.replacement().ast(), replacement.exprIdToReplace());
}
throw new IllegalArgumentException(
"Unsupported replacement kind: " + replacement.replacement().kind());
}
/**
* Repeatedly applies AST mutations using the provided AST-level rewriter until no further
* replacements match (fixed point reached) or the mutator's iteration limit is exhausted.
*
* <p>Per iteration pass, the AST is traversed to find and perform at most one matching subtree
* substitution before restarting traversal on the newly mutated AST.
*
* <p>This operation is intended for AST optimization purposes.
*
* <p>This is a very dangerous operation. Callers must re-typecheck the mutated AST and
* additionally verify that the resulting AST is semantically valid.
*
* <p>All expression IDs will be renumbered in a stable manner to ensure there's no ID collision
* between the nodes.
*
* @param ast Initial mutable AST to mutate.
* @param astRewriter Function returning a {@link SubtreeReplacement} or {@code Optional.empty()}
* when no further rewrites are possible.
* @return Mutated {@link CelMutableAst} at fixed point.
* @throws IllegalStateException If the iteration count exceeds {@code iterationLimit}.
*/
public CelMutableAst mutateUntilFixedPoint(
CelMutableAst ast,
Function<CelNavigableMutableAst, Optional<SubtreeReplacement>> astRewriter) {
Preconditions.checkNotNull(ast);
Preconditions.checkNotNull(astRewriter);
CelMutableAst mutableAst = ast;
for (long i = 0; i < iterationLimit; i++) {
CelNavigableMutableAst navAst = CelNavigableMutableAst.fromAst(mutableAst);
Optional<SubtreeReplacement> replacement = astRewriter.apply(navAst);
if (!replacement.isPresent()) {
return mutableAst;
}
mutableAst = replaceSubtree(mutableAst, replacement.get());
}
throw new IllegalStateException("Max iteration count reached.");
}
/**
* Traverses nodes using the specified {@link TraversalOrder} and repeatedly rewrites matching
* subtrees until a fixed point is reached.
*
* <p>Per iteration pass, the AST is walked in the given order to find and perform the first
* matching substitution. The traversal then restarts on the freshly mutated AST until no nodes
* match or the mutator's iteration limit is exhausted.
*
* <p>This operation is intended for AST optimization purposes.
*
* <p>This is a very dangerous operation. Callers must re-typecheck the mutated AST and
* additionally verify that the resulting AST is semantically valid.
*
* <p>All expression IDs will be renumbered in a stable manner to ensure there's no ID collision
* between the nodes.
*
* @param ast Initial mutable AST to mutate.
* @param traversalOrder Order in which nodes are visited per iteration pass.
* @param nodeRewriter Function returning a {@link SubtreeReplacement} or {@code
* Optional.empty()}.
* @return Mutated {@link CelMutableAst} at fixed point.
* @throws IllegalStateException If the iteration count exceeds {@code iterationLimit}.
*/
public CelMutableAst mutateUntilFixedPoint(
CelMutableAst ast,
TraversalOrder traversalOrder,
Function<CelNavigableMutableExpr, Optional<SubtreeReplacement>> nodeRewriter) {
Preconditions.checkNotNull(traversalOrder);
Preconditions.checkNotNull(nodeRewriter);
return mutateUntilFixedPoint(
ast,
navAst ->
navAst
.getRoot()
.allNodes(traversalOrder)
.flatMap(node -> Streams.stream(nodeRewriter.apply(node)))
.findFirst());
}
/**
* Traverses nodes using the specified {@link TraversalOrder}, applies the node matcher, and
* substitutes matching nodes with the returned replacement expression (targeting {@code
* node.id()}).
*
* <p>Per iteration pass, the AST is walked in the given order to find and perform the first
* matching substitution. The traversal then restarts on the freshly mutated AST until no nodes
* match or the mutator's iteration limit is exhausted.
*
* <p>This operation is intended for AST optimization purposes.
*
* <p>This is a very dangerous operation. Callers must re-typecheck the mutated AST and
* additionally verify that the resulting AST is semantically valid.
*
* <p>All expression IDs will be renumbered in a stable manner to ensure there's no ID collision
* between the nodes.
*
* @param ast Initial mutable AST to mutate.
* @param traversalOrder Order in which nodes are visited per iteration pass.
* @param nodeMatcher Predicate to filter candidate nodes.
* @param nodeRewriter Function producing the new {@link CelMutableExpr} for matched nodes.
* @return Mutated {@link CelMutableAst} at fixed point.
* @throws IllegalStateException If the iteration count exceeds {@code iterationLimit}.
*/
public CelMutableAst mutateUntilFixedPoint(
CelMutableAst ast,
TraversalOrder traversalOrder,
Predicate<CelNavigableMutableExpr> nodeMatcher,
Function<CelNavigableMutableExpr, Optional<CelMutableExpr>> nodeRewriter) {
Preconditions.checkNotNull(nodeMatcher);
Preconditions.checkNotNull(nodeRewriter);
return mutateUntilFixedPoint(
ast,
traversalOrder,
node ->
nodeMatcher.test(node)
? nodeRewriter.apply(node).map(newExpr -> SubtreeReplacement.of(node.id(), newExpr))
: Optional.empty());
}
private CelMutableExpr mangleIdentsInComprehensionExpr(
CelMutableExpr root,
CelMutableExpr comprehensionExpr,
String originalIterVar,
String originalIterVar2,
String originalAccuVar,
MangledComprehensionName mangledComprehensionName) {
CelMutableComprehension comprehension = comprehensionExpr.comprehension();
replaceIdentName(
comprehension.loopStep(), originalIterVar, mangledComprehensionName.iterVarName());
replaceIdentName(comprehensionExpr, originalAccuVar, mangledComprehensionName.resultName());
comprehension.setIterVar(mangledComprehensionName.iterVarName());
// Most standard macros set accu_var as __result__, but not all (ex: cel.bind).
if (comprehension.accuVar().equals(originalAccuVar)) {
comprehension.setAccuVar(mangledComprehensionName.resultName());
}
if (!originalIterVar2.isEmpty()) {
comprehension.setIterVar2(mangledComprehensionName.iterVar2Name());
replaceIdentName(
comprehension.loopStep(), originalIterVar2, mangledComprehensionName.iterVar2Name());
}
return mutateExpr(NO_OP_ID_GENERATOR, root, comprehensionExpr, comprehensionExpr.id());
}
private void replaceIdentName(
CelMutableExpr comprehensionExpr, String originalIdentName, String newIdentName) {
int iterCount;
for (iterCount = 0; iterCount < iterationLimit; iterCount++) {
CelMutableExpr identToMangle =
CelNavigableMutableExpr.fromExpr(comprehensionExpr)
.descendants()
.map(CelNavigableMutableExpr::expr)
.filter(
node ->
node.getKind().equals(ExprKind.Kind.IDENT)
&& node.ident().name().equals(originalIdentName))
.findAny()
.orElse(null);
if (identToMangle == null) {
break;
}
comprehensionExpr =
mutateExpr(
NO_OP_ID_GENERATOR,
comprehensionExpr,
CelMutableExpr.ofIdent(newIdentName),
identToMangle.id());
}
if (iterCount >= iterationLimit) {
throw new IllegalStateException("Max iteration count reached.");
}
}
private CelMutableSource mangleIdentsInMacroSource(
CelMutableSource sourceBuilder,
CelMutableExpr mutatedComprehensionExpr,
String originalIterVar,
String originalIterVar2,
MangledComprehensionName mangledComprehensionName,
long originalComprehensionId) {
if (!sourceBuilder.getMacroCalls().containsKey(originalComprehensionId)) {
return sourceBuilder;
}
// First, normalize the macro source.
// ex: [x].exists(x, [x].exists(x, x == 1)) -> [x].exists(x, [@c1].exists(x, @c0 == 1)).
CelMutableSource newSource =
normalizeMacroSource(sourceBuilder, -1, mutatedComprehensionExpr, (id) -> id);
// Note that in the above example, the iteration variable is not replaced after normalization.
// This is because populating a macro call map upon parse generates a new unique identifier
// that does not exist in the main AST. Thus, we need to manually replace the identifier.
// Also note that this only applies when the macro is at leaf. For nested macros, the iteration
// variable actually exists in the main AST thus, this step isn't needed.
// ex: [1].map(x, [2].filter(y, x == y). Here, the variable declaration `x` exists in the AST
// but not `y`.
CelMutableExpr macroExpr = newSource.getMacroCalls().get(originalComprehensionId);
// By convention, the iteration variable is always the first argument of the
// macro call expression.
CelMutableExpr identToMangle = macroExpr.call().args().get(0);
if (identToMangle.ident().name().equals(originalIterVar)) {
macroExpr =
mutateExpr(
NO_OP_ID_GENERATOR,
macroExpr,
CelMutableExpr.ofIdent(mangledComprehensionName.iterVarName()),
identToMangle.id());
}
if (!originalIterVar2.isEmpty()) {
// Similarly by convention, iter_var2 is always the second argument of the macro call.
identToMangle = macroExpr.call().args().get(1);
if (identToMangle.ident().name().equals(originalIterVar2)) {
macroExpr =
mutateExpr(
NO_OP_ID_GENERATOR,
macroExpr,
CelMutableExpr.ofIdent(mangledComprehensionName.iterVar2Name()),
identToMangle.id());
}
}
newSource.addMacroCalls(originalComprehensionId, macroExpr);
return newSource;
}
/** Combines two {@link CelMutableSource} instances into a single new instance. */
public static CelMutableSource combine(CelMutableSource celSource1, CelMutableSource celSource2) {
return CelMutableSource.newInstance()
.setDescription(
Strings.isNullOrEmpty(celSource1.getDescription())
? celSource2.getDescription()
: celSource1.getDescription())
.addAllExtensions(celSource1.getExtensions())
.addAllExtensions(celSource2.getExtensions())
.addAllMacroCalls(celSource1.getMacroCalls())
.addAllMacroCalls(celSource2.getMacroCalls());
}
/**
* Stabilizes the incoming AST by ensuring that all of expr IDs are consistently renumbered
* (monotonically increased) from the starting seed ID. If the AST contains any macro calls, its
* IDs are also normalized.
*/
private CelMutableAst stabilizeAst(CelMutableAst mutableAst, long seedExprId) {
CelMutableExpr mutableExpr = mutableAst.expr();
CelMutableSource source = mutableAst.source();
StableIdGenerator stableIdGenerator =
CelExprIdGeneratorFactory.newStableIdGenerator(seedExprId);
CelMutableExpr mutatedExpr = renumberExprIds(stableIdGenerator::nextExprId, mutableExpr);
CelMutableSource sourceBuilder =
CelMutableSource.newInstance().addAllExtensions(source.getExtensions());
// Update the macro call IDs and their call IDs
for (Entry<Long, CelMutableExpr> macroCall : source.getMacroCalls().entrySet()) {
long macroId = macroCall.getKey();
long newCallId = stableIdGenerator.renumberId(macroId);
CelMutableExpr existingMacroCallExpr = CelMutableExpr.newInstance(macroCall.getValue());
CelMutableExpr newCall =
renumberExprIds(stableIdGenerator::renumberId, existingMacroCallExpr);
sourceBuilder.addMacroCalls(newCallId, newCall);
}
return CelMutableAst.of(mutatedExpr, sourceBuilder);
}
private CelMutableSource normalizeMacroSource(
CelMutableSource source,
long exprIdToReplace,
CelMutableExpr mutatedRoot,
ExprIdGenerator idGenerator) {
// Remove the macro metadata that no longer exists in the AST due to being replaced.
source.clearMacroCall(exprIdToReplace);
if (source.getMacroCalls().isEmpty()) {
return source;
}
ImmutableMap<Long, CelMutableExpr> allExprs =
CelNavigableMutableExpr.fromExpr(mutatedRoot)
.allNodes()
.map(CelNavigableMutableExpr::expr)
.collect(
toImmutableMap(
CelMutableExpr::id,
expr -> expr,
(expr1, expr2) -> {
// Comprehensions can reuse same expression (result). We just need to ensure
// that they are identical.
if (expr1.equals(expr2)) {
return expr1;
}
throw new IllegalStateException(
"Expected expressions to be the same for id: " + expr1.id());
}));
CelMutableSource newMacroSource =
CelMutableSource.newInstance()
.setDescription(source.getDescription())
.addAllExtensions(source.getExtensions());
// Update the macro call IDs and their call references
for (Entry<Long, CelMutableExpr> existingMacroCall : source.getMacroCalls().entrySet()) {
long macroId = existingMacroCall.getKey();
long callId = idGenerator.generate(macroId);
if (!allExprs.containsKey(callId)) {
continue;
}
CelMutableExpr existingMacroCallExpr =
CelMutableExpr.newInstance(existingMacroCall.getValue());
CelMutableExpr newMacroCallExpr = renumberExprIds(idGenerator, existingMacroCallExpr);
CelNavigableMutableExpr callNav = CelNavigableMutableExpr.fromExpr(newMacroCallExpr);
ArrayList<CelMutableExpr> callDescendants =
callNav
.descendants()
.map(CelNavigableMutableExpr::expr)
.collect(toCollection(ArrayList::new));
for (CelMutableExpr callChild : callDescendants) {
if (!allExprs.containsKey(callChild.id())) {
continue;
}
CelMutableExpr mutatedExpr = allExprs.get(callChild.id());
if (!callChild.equals(mutatedExpr)) {
newMacroCallExpr =
mutateExpr(NO_OP_ID_GENERATOR, newMacroCallExpr, mutatedExpr, callChild.id());
}
}
if (exprIdToReplace > 0) {
long replacedId = idGenerator.generate(exprIdToReplace);
boolean isListExprBeingReplaced =
allExprs.containsKey(replacedId)
&& allExprs.get(replacedId).getKind().equals(ExprKind.Kind.LIST);
if (isListExprBeingReplaced) {
unwrapListArgumentsInMacroCallExpr(
allExprs.get(callId).comprehension(), newMacroCallExpr);
}
}
newMacroSource.addMacroCalls(callId, newMacroCallExpr);
}
// Replace comprehension nodes with a NOT_SET reference to reduce AST size.
for (Entry<Long, CelMutableExpr> macroCall : newMacroSource.getMacroCalls().entrySet()) {
CelMutableExpr macroCallExpr = macroCall.getValue();
CelNavigableMutableExpr.fromExpr(macroCallExpr)
.allNodes()
.filter(node -> node.getKind().equals(ExprKind.Kind.COMPREHENSION))
.map(CelNavigableMutableExpr::expr)
.forEach(
node -> {
CelMutableExpr mutatedNode =
mutateExpr(
NO_OP_ID_GENERATOR,
macroCallExpr,
CelMutableExpr.ofNotSet(node.id()),
node.id());
macroCall.setValue(mutatedNode);
});
// Prune any NOT_SET (comprehension) nodes that no longer exist in the main AST
// This can occur from pulling out a nested comprehension into a separate cel.block index
CelNavigableMutableExpr.fromExpr(macroCallExpr)
.allNodes()
.filter(node -> node.getKind().equals(ExprKind.Kind.NOT_SET))
.map(CelNavigableMutableExpr::id)
.filter(id -> !allExprs.containsKey(id))
.forEach(
id -> {
ArrayList<CelMutableExpr> newCallArgs =
macroCallExpr.call().args().stream()
.filter(node -> node.id() != id)
.collect(toCollection(ArrayList::new));
CelMutableCall call = macroCallExpr.call();
call.setArgs(newCallArgs);
});
}
return newMacroSource;
}
/**
* Unwraps the arguments in the extraneous list_expr which is present in the AST but does not
* exist in the macro call map. `map`, `filter` are examples of such.
*
* <p>This method inspects the comprehension's accumulator initializer to infer that the list_expr
* solely exists to match the expected result type of the macro call signature.
*
* @param comprehension Comprehension in the main AST to extract the macro call arguments from
* (loop step).
* @param newMacroCallExpr (Output parameter) Modified macro call expression with the call
* arguments unwrapped.
*/
private static void unwrapListArgumentsInMacroCallExpr(
CelMutableComprehension comprehension, CelMutableExpr newMacroCallExpr) {
CelMutableExpr accuInit = comprehension.accuInit();
if (!accuInit.getKind().equals(ExprKind.Kind.LIST) || !accuInit.list().elements().isEmpty()) {
// Does not contain an extraneous list.
return;
}
CelMutableExpr loopStepExpr = comprehension.loopStep();
List<CelMutableExpr> loopStepArgs = loopStepExpr.call().args();
if (loopStepArgs.size() != 2 && loopStepArgs.size() != 3) {
throw new IllegalArgumentException(
String.format(