-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathCelEnvironment.java
More file actions
1127 lines (905 loc) · 39.8 KB
/
Copy pathCelEnvironment.java
File metadata and controls
1127 lines (905 loc) · 39.8 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 2025 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.bundle;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import com.google.auto.value.AutoValue;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.CheckReturnValue;
import dev.cel.bundle.CelEnvironment.LibrarySubset.FunctionSelector;
import dev.cel.checker.CelStandardDeclarations;
import dev.cel.checker.CelStandardDeclarations.StandardFunction;
import dev.cel.checker.CelStandardDeclarations.StandardOverload;
import dev.cel.checker.ProtoTypeMask;
import dev.cel.common.CelContainer;
import dev.cel.common.CelFunctionDecl;
import dev.cel.common.CelOptions;
import dev.cel.common.CelOverloadDecl;
import dev.cel.common.CelVarDecl;
import dev.cel.common.Source;
import dev.cel.common.types.CelType;
import dev.cel.common.types.CelTypeProvider;
import dev.cel.common.types.ListType;
import dev.cel.common.types.MapType;
import dev.cel.common.types.OptionalType;
import dev.cel.common.types.SimpleType;
import dev.cel.common.types.TypeParamType;
import dev.cel.common.types.TypeType;
import dev.cel.compiler.CelCompiler;
import dev.cel.compiler.CelCompilerBuilder;
import dev.cel.compiler.CelCompilerLibrary;
import dev.cel.extensions.CelExtensions;
import dev.cel.parser.CelStandardMacro;
import dev.cel.runtime.CelRuntime;
import dev.cel.runtime.CelRuntimeBuilder;
import dev.cel.runtime.CelRuntimeLibrary;
import java.util.Arrays;
import java.util.Optional;
import java.util.function.ObjIntConsumer;
/**
* CelEnvironment is a native representation of a CEL environment for compiler and runtime. This
* object is amenable to being serialized into YAML, textproto or other formats as needed.
*/
@AutoValue
public abstract class CelEnvironment {
@VisibleForTesting
static final ImmutableMap<String, CanonicalCelExtension> CEL_EXTENSION_CONFIG_MAP =
ImmutableMap.of(
"bindings", CanonicalCelExtension.BINDINGS,
"encoders", CanonicalCelExtension.ENCODERS,
"lists", CanonicalCelExtension.LISTS,
"math", CanonicalCelExtension.MATH,
"optional", CanonicalCelExtension.OPTIONAL,
"protos", CanonicalCelExtension.PROTOS,
"regex", CanonicalCelExtension.REGEX,
"sets", CanonicalCelExtension.SETS,
"strings", CanonicalCelExtension.STRINGS,
"two-var-comprehensions", CanonicalCelExtension.COMPREHENSIONS);
private static final ImmutableMap<String, ObjIntConsumer<CelOptions.Builder>> LIMIT_HANDLERS =
ImmutableMap.of(
"cel.limit.expression_code_points",
CelOptions.Builder::maxExpressionCodePointSize,
"cel.limit.parse_error_recovery",
CelOptions.Builder::maxParseErrorRecoveryLimit,
"cel.limit.parse_recursion_depth",
CelOptions.Builder::maxParseRecursionDepth,
"cel.limit.expression_node_count",
CelOptions.Builder::maxParseExpressionNodeCount);
private static final ImmutableMap<String, BooleanOptionConsumer> FEATURE_HANDLERS =
ImmutableMap.of(
"cel.feature.macro_call_tracking",
CelOptions.Builder::populateMacroCalls,
"cel.feature.backtick_escape_syntax",
CelOptions.Builder::enableQuotedIdentifierSyntax,
"cel.feature.cross_type_numeric_comparisons",
CelOptions.Builder::enableHeterogeneousNumericComparisons);
/** Environment source in textual format (ex: textproto, YAML). */
public abstract Optional<Source> source();
/** Name of the environment. */
public abstract String name();
/** Container, which captures default namespace and aliases for value resolution. */
public abstract Optional<CelContainer> container();
/**
* An optional description of the environment (example: location of the file containing the config
* content).
*/
public abstract String description();
/** Converts this {@code CelEnvironment} object into a builder. */
public abstract Builder toBuilder();
/**
* Canonical extensions to enable in the environment, such as Optional, String and Math
* extensions.
*/
public abstract ImmutableSet<ExtensionConfig> extensions();
/** New variable declarations to add in the compilation environment. */
public abstract ImmutableSet<VariableDecl> variables();
/** New function declarations to add in the compilation environment. */
public abstract ImmutableSet<FunctionDecl> functions();
/** Standard library subset (which macros, functions to include/exclude) */
public abstract Optional<LibrarySubset> standardLibrarySubset();
/** Feature flags to enable in the environment. */
public abstract ImmutableSet<FeatureFlag> features();
/** Limits to set in the environment. */
public abstract ImmutableSet<Limit> limits();
/** Context variable to enable in the environment. */
public abstract Optional<ContextVariable> contextVariable();
/** Builder for {@link CelEnvironment}. */
@AutoValue.Builder
public abstract static class Builder {
public abstract ImmutableSet.Builder<ExtensionConfig> extensionsBuilder();
// For testing only, to empty out the source.
abstract Builder setSource(Optional<Source> source);
public abstract Builder setSource(Source source);
public abstract Builder setName(String name);
public abstract Builder setDescription(String description);
public abstract Builder setContainer(CelContainer container);
@CanIgnoreReturnValue
public Builder setContainer(String container) {
return setContainer(CelContainer.ofName(container));
}
@CanIgnoreReturnValue
public Builder addExtensions(ExtensionConfig... extensions) {
checkNotNull(extensions);
return addExtensions(Arrays.asList(extensions));
}
@CanIgnoreReturnValue
public Builder addExtensions(Iterable<ExtensionConfig> extensions) {
checkNotNull(extensions);
this.extensionsBuilder().addAll(extensions);
return this;
}
@CanIgnoreReturnValue
public Builder setVariables(VariableDecl... variables) {
return setVariables(ImmutableSet.copyOf(variables));
}
public abstract Builder setVariables(ImmutableSet<VariableDecl> variables);
@CanIgnoreReturnValue
public Builder setFunctions(FunctionDecl... functions) {
return setFunctions(ImmutableSet.copyOf(functions));
}
public abstract Builder setFunctions(ImmutableSet<FunctionDecl> functions);
public abstract Builder setStandardLibrarySubset(LibrarySubset stdLibrarySubset);
@CanIgnoreReturnValue
public Builder setFeatures(FeatureFlag... featureFlags) {
return setFeatures(ImmutableSet.copyOf(featureFlags));
}
public abstract Builder setFeatures(ImmutableSet<FeatureFlag> featureFlags);
@CanIgnoreReturnValue
public Builder setLimits(Limit... limits) {
return setLimits(ImmutableSet.copyOf(limits));
}
public abstract Builder setLimits(ImmutableSet<Limit> limits);
public abstract Builder setContextVariable(ContextVariable contextVariable);
abstract CelEnvironment autoBuild();
@CheckReturnValue
public final CelEnvironment build() {
CelEnvironment env = autoBuild();
LibrarySubset librarySubset = env.standardLibrarySubset().orElse(null);
if (librarySubset != null) {
if (!librarySubset.includedMacros().isEmpty()
&& !librarySubset.excludedMacros().isEmpty()) {
throw new IllegalArgumentException(
"Invalid subset: cannot both include and exclude macros");
}
if (!librarySubset.includedFunctions().isEmpty()
&& !librarySubset.excludedFunctions().isEmpty()) {
throw new IllegalArgumentException(
"Invalid subset: cannot both include and exclude functions");
}
}
return env;
}
}
/** Creates a new builder to construct a {@link CelEnvironment} instance. */
public static Builder newBuilder() {
return new AutoValue_CelEnvironment.Builder()
.setName("")
.setDescription("")
.setVariables(ImmutableSet.of())
.setFunctions(ImmutableSet.of())
.setFeatures(ImmutableSet.of())
.setLimits(ImmutableSet.of());
}
/** Extends the provided {@link CelCompiler} environment with this configuration. */
public CelCompiler extend(CelCompiler celCompiler, CelOptions celOptions)
throws CelEnvironmentException {
celOptions = applyEnvironmentOptions(celOptions);
try {
CelTypeProvider celTypeProvider = celCompiler.getTypeProvider();
CelCompilerBuilder compilerBuilder =
celCompiler
.toCompilerBuilder()
.setOptions(celOptions)
.setTypeProvider(celTypeProvider)
.addVarDeclarations(
variables().stream()
.map(v -> v.toCelVarDecl(celTypeProvider))
.collect(toImmutableList()))
.addFunctionDeclarations(
functions().stream()
.map(f -> f.toCelFunctionDecl(celTypeProvider))
.collect(toImmutableList()));
container().ifPresent(compilerBuilder::setContainer);
addAllCompilerExtensions(compilerBuilder, celOptions);
applyStandardLibrarySubset(compilerBuilder);
contextVariable()
.ifPresent(
cv ->
compilerBuilder.addProtoTypeMasks(
ProtoTypeMask.ofAllFields(cv.typeName()).withFieldsAsVariableDeclarations()));
return compilerBuilder.build();
} catch (RuntimeException e) {
throw new CelEnvironmentException(e.getMessage(), e);
}
}
/** Extends the provided {@link Cel} environment with this configuration. */
public Cel extend(Cel cel, CelOptions celOptions) throws CelEnvironmentException {
celOptions = applyEnvironmentOptions(celOptions);
try {
// Casting is necessary to only extend the compiler here
CelCompiler celCompiler = extend((CelCompiler) cel, celOptions);
CelRuntime celRuntime = extendRuntime(cel, celOptions);
return CelFactory.combine(celCompiler, celRuntime);
} catch (RuntimeException e) {
throw new CelEnvironmentException(e.getMessage(), e);
}
}
private CelOptions applyEnvironmentOptions(CelOptions celOptions) {
CelOptions.Builder optionsBuilder = celOptions.toBuilder();
for (FeatureFlag featureFlag : features()) {
BooleanOptionConsumer consumer = FEATURE_HANDLERS.get(featureFlag.name());
if (consumer == null) {
throw new IllegalArgumentException("Unknown feature flag: " + featureFlag.name());
}
consumer.accept(optionsBuilder, featureFlag.enabled());
}
for (Limit limit : limits()) {
int value = limit.value() < 0 ? -1 : limit.value();
ObjIntConsumer<CelOptions.Builder> consumer = LIMIT_HANDLERS.get(limit.name());
if (consumer == null) {
throw new IllegalArgumentException("Unknown limit: " + limit.name());
}
consumer.accept(optionsBuilder, value);
}
return optionsBuilder.build();
}
private void addAllCompilerExtensions(
CelCompilerBuilder celCompilerBuilder, CelOptions celOptions) {
// TODO: Add capability to accept user defined exceptions
for (ExtensionConfig extensionConfig : extensions()) {
CanonicalCelExtension extension = getExtensionOrThrow(extensionConfig.name());
if (extension.compilerExtensionProvider() != null) {
CelCompilerLibrary celCompilerLibrary =
extension
.compilerExtensionProvider()
.getCelCompilerLibrary(celOptions, extensionConfig.version());
celCompilerBuilder.addLibraries(celCompilerLibrary);
}
}
}
private CelRuntime extendRuntime(CelRuntime celRuntime, CelOptions celOptions) {
CelRuntimeBuilder celRuntimeBuilder = celRuntime.toRuntimeBuilder();
celRuntimeBuilder.setOptions(celOptions);
// TODO: Add capability to accept user defined exceptions
for (ExtensionConfig extensionConfig : extensions()) {
CanonicalCelExtension extension = getExtensionOrThrow(extensionConfig.name());
if (extension.runtimeExtensionProvider() != null) {
CelRuntimeLibrary celRuntimeLibrary =
extension
.runtimeExtensionProvider()
.getCelRuntimeLibrary(celOptions, extensionConfig.version());
celRuntimeBuilder.addLibraries(celRuntimeLibrary);
}
}
return celRuntimeBuilder.build();
}
private void applyStandardLibrarySubset(CelCompilerBuilder compilerBuilder) {
if (!standardLibrarySubset().isPresent()) {
return;
}
LibrarySubset librarySubset = standardLibrarySubset().get();
if (librarySubset.disabled()) {
compilerBuilder.setStandardEnvironmentEnabled(false);
return;
}
if (librarySubset.macrosDisabled()) {
compilerBuilder.setStandardMacros(ImmutableList.of());
} else if (!librarySubset.includedMacros().isEmpty()) {
compilerBuilder.setStandardMacros(
librarySubset.includedMacros().stream()
.flatMap(name -> getStandardMacrosOrThrow(name).stream())
.collect(toImmutableSet()));
} else if (!librarySubset.excludedMacros().isEmpty()) {
ImmutableSet<CelStandardMacro> set =
librarySubset.excludedMacros().stream()
.flatMap(name -> getStandardMacrosOrThrow(name).stream())
.collect(toImmutableSet());
compilerBuilder.setStandardMacros(
CelStandardMacro.STANDARD_MACROS.stream()
.filter(macro -> !set.contains(macro))
.collect(toImmutableSet()));
}
if (!librarySubset.includedFunctions().isEmpty()) {
ImmutableSet<FunctionSelector> includedFunctions = librarySubset.includedFunctions();
compilerBuilder
.setStandardEnvironmentEnabled(false)
.setStandardDeclarations(
CelStandardDeclarations.newBuilder()
.filterFunctions(
(function, overload) ->
FunctionSelector.matchesAny(function, overload, includedFunctions))
.build());
} else if (!librarySubset.excludedFunctions().isEmpty()) {
ImmutableSet<FunctionSelector> excludedFunctions = librarySubset.excludedFunctions();
compilerBuilder
.setStandardEnvironmentEnabled(false)
.setStandardDeclarations(
CelStandardDeclarations.newBuilder()
.filterFunctions(
(function, overload) ->
!FunctionSelector.matchesAny(function, overload, excludedFunctions))
.build());
}
}
private static ImmutableSet<CelStandardMacro> getStandardMacrosOrThrow(String macroName) {
ImmutableSet.Builder<CelStandardMacro> builder = ImmutableSet.builder();
for (CelStandardMacro macro : CelStandardMacro.STANDARD_MACROS) {
if (macro.getFunction().equals(macroName)) {
builder.add(macro);
}
}
ImmutableSet<CelStandardMacro> macros = builder.build();
if (macros.isEmpty()) {
throw new IllegalArgumentException("unrecognized standard macro `" + macroName + "'");
}
return macros;
}
private static CanonicalCelExtension getExtensionOrThrow(String extensionName) {
CanonicalCelExtension extension = CEL_EXTENSION_CONFIG_MAP.get(extensionName);
if (extension == null) {
throw new IllegalArgumentException("Unrecognized extension: " + extensionName);
}
return extension;
}
/** Represents a context variable declaration. */
@AutoValue
public abstract static class ContextVariable {
/** Fully qualified type name of the context variable. */
public abstract String typeName();
public static ContextVariable create(String typeName) {
return new AutoValue_CelEnvironment_ContextVariable(typeName);
}
}
/** Represents a policy variable declaration. */
@AutoValue
public abstract static class VariableDecl {
/** Fully qualified variable name. */
public abstract String name();
/** The type of the variable. */
public abstract TypeDecl type();
public abstract Optional<String> description();
/** Builder for {@link VariableDecl}. */
@AutoValue.Builder
public abstract static class Builder implements RequiredFieldsChecker {
public abstract Optional<String> name();
public abstract Optional<TypeDecl> type();
public abstract VariableDecl.Builder setName(String name);
public abstract VariableDecl.Builder setType(TypeDecl typeDecl);
public abstract VariableDecl.Builder setDescription(String name);
@Override
public ImmutableList<RequiredField> requiredFields() {
return ImmutableList.of(
RequiredField.of("name", this::name), RequiredField.of("type", this::type));
}
/** Builds a new instance of {@link VariableDecl}. */
public abstract VariableDecl build();
}
public static VariableDecl.Builder newBuilder() {
return new AutoValue_CelEnvironment_VariableDecl.Builder();
}
/** Creates a new builder to construct a {@link VariableDecl} instance. */
public static VariableDecl create(String name, TypeDecl type) {
return newBuilder().setName(name).setType(type).build();
}
/** Converts this policy variable declaration into a {@link CelVarDecl}. */
public CelVarDecl toCelVarDecl(CelTypeProvider celTypeProvider) {
return CelVarDecl.newVarDeclaration(name(), type().toCelType(celTypeProvider));
}
}
/** Represents a policy function declaration. */
@AutoValue
public abstract static class FunctionDecl {
public abstract String name();
public abstract Optional<String> description();
public abstract ImmutableSet<OverloadDecl> overloads();
/** Builder for {@link FunctionDecl}. */
@AutoValue.Builder
public abstract static class Builder implements RequiredFieldsChecker {
public abstract Optional<String> name();
public abstract Optional<ImmutableSet<OverloadDecl>> overloads();
public abstract FunctionDecl.Builder setName(String name);
public abstract FunctionDecl.Builder setDescription(String description);
public abstract FunctionDecl.Builder setOverloads(ImmutableSet<OverloadDecl> overloads);
@Override
public ImmutableList<RequiredField> requiredFields() {
return ImmutableList.of(
RequiredField.of("name", this::name), RequiredField.of("overloads", this::overloads));
}
/** Builds a new instance of {@link FunctionDecl}. */
public abstract FunctionDecl build();
}
/** Creates a new builder to construct a {@link FunctionDecl} instance. */
public static FunctionDecl.Builder newBuilder() {
return new AutoValue_CelEnvironment_FunctionDecl.Builder();
}
/** Creates a new {@link FunctionDecl} with the provided function name and its overloads. */
public static FunctionDecl create(String name, ImmutableSet<OverloadDecl> overloads) {
return newBuilder().setName(name).setOverloads(overloads).build();
}
/** Converts this policy function declaration into a {@link CelFunctionDecl}. */
public CelFunctionDecl toCelFunctionDecl(CelTypeProvider celTypeProvider) {
return CelFunctionDecl.newFunctionDeclaration(
name(),
overloads().stream()
.map(o -> o.toCelOverloadDecl(celTypeProvider))
.collect(toImmutableList()));
}
}
/** Represents an overload declaration on a policy function. */
@AutoValue
public abstract static class OverloadDecl {
/**
* A unique overload ID. Required. This should follow the typical naming convention used in CEL
* (e.g: targetType_func_argType1_argType...)
*/
public abstract String id();
/** Target of the function overload if it's a receiver style (example: foo in `foo.f(...)`) */
public abstract Optional<TypeDecl> target();
/** List of function overload type values. */
public abstract ImmutableList<TypeDecl> arguments();
/** Examples for the overload. */
public abstract ImmutableList<String> examples();
/** Return type of the overload. Required. */
public abstract TypeDecl returnType();
/** Builder for {@link OverloadDecl}. */
@AutoValue.Builder
public abstract static class Builder implements RequiredFieldsChecker {
public abstract Optional<String> id();
public abstract Optional<TypeDecl> returnType();
public abstract OverloadDecl.Builder setId(String overloadId);
public abstract OverloadDecl.Builder setTarget(TypeDecl target);
// This should stay package-private to encourage add/set methods to be used instead.
abstract ImmutableList.Builder<TypeDecl> argumentsBuilder();
abstract ImmutableList.Builder<String> examplesBuilder();
public abstract OverloadDecl.Builder setArguments(ImmutableList<TypeDecl> args);
@CanIgnoreReturnValue
public OverloadDecl.Builder addExamples(Iterable<String> examples) {
this.examplesBuilder().addAll(checkNotNull(examples));
return this;
}
@CanIgnoreReturnValue
public OverloadDecl.Builder addExamples(String... examples) {
return addExamples(Arrays.asList(examples));
}
@CanIgnoreReturnValue
public OverloadDecl.Builder addArguments(Iterable<TypeDecl> args) {
this.argumentsBuilder().addAll(checkNotNull(args));
return this;
}
@CanIgnoreReturnValue
public OverloadDecl.Builder addArguments(TypeDecl... args) {
return addArguments(Arrays.asList(args));
}
public abstract OverloadDecl.Builder setReturnType(TypeDecl returnType);
@Override
public ImmutableList<RequiredField> requiredFields() {
return ImmutableList.of(
RequiredField.of("id", this::id), RequiredField.of("return", this::returnType));
}
/** Builds a new instance of {@link OverloadDecl}. */
@CheckReturnValue
public abstract OverloadDecl build();
}
/** Creates a new builder to construct a {@link OverloadDecl} instance. */
public static OverloadDecl.Builder newBuilder() {
return new AutoValue_CelEnvironment_OverloadDecl.Builder().setArguments(ImmutableList.of());
}
/** Converts this policy function overload into a {@link CelOverloadDecl}. */
public CelOverloadDecl toCelOverloadDecl(CelTypeProvider celTypeProvider) {
CelOverloadDecl.Builder builder =
CelOverloadDecl.newBuilder()
.setIsInstanceFunction(false)
.setOverloadId(id())
.setResultType(returnType().toCelType(celTypeProvider));
target()
.ifPresent(
t ->
builder
.setIsInstanceFunction(true)
.addParameterTypes(t.toCelType(celTypeProvider)));
for (TypeDecl type : arguments()) {
builder.addParameterTypes(type.toCelType(celTypeProvider));
}
return builder.build();
}
}
/**
* Represents an abstract type declaration used to declare functions and variables in a policy.
*/
@AutoValue
public abstract static class TypeDecl {
public abstract String name();
public abstract ImmutableList<TypeDecl> params();
public abstract boolean isTypeParam();
/** Builder for {@link TypeDecl}. */
@AutoValue.Builder
public abstract static class Builder implements RequiredFieldsChecker {
public abstract Optional<String> name();
public abstract TypeDecl.Builder setName(String name);
// This should stay package-private to encourage add/set methods to be used instead.
abstract ImmutableList.Builder<TypeDecl> paramsBuilder();
public abstract TypeDecl.Builder setParams(ImmutableList<TypeDecl> typeDecls);
@CanIgnoreReturnValue
public TypeDecl.Builder addParams(TypeDecl... params) {
return addParams(Arrays.asList(params));
}
@CanIgnoreReturnValue
public TypeDecl.Builder addParams(Iterable<TypeDecl> params) {
this.paramsBuilder().addAll(checkNotNull(params));
return this;
}
public abstract TypeDecl.Builder setIsTypeParam(boolean isTypeParam);
@Override
public ImmutableList<RequiredField> requiredFields() {
return ImmutableList.of(RequiredField.of("type_name", this::name));
}
@CheckReturnValue
public abstract TypeDecl build();
}
/** Creates a new {@link TypeDecl} with the provided name. */
public static TypeDecl create(String name) {
return newBuilder().setName(name).build();
}
/**
* Parses a type specifier shorthand string (e.g. {@code "list<int>"}, {@code "map<string,
* dyn>"}, {@code "list<~T>"}) into a {@link TypeDecl}.
*/
static TypeDecl parse(String typeSpecifier) {
return TypeSpecifierParser.parse(typeSpecifier);
}
/** Creates a new {@link TypeDecl} representing a type parameter with the provided name. */
static TypeDecl ofTypeParam(String typeParamName) {
return newBuilder().setName(typeParamName).setIsTypeParam(true).build();
}
public static TypeDecl.Builder newBuilder() {
return new AutoValue_CelEnvironment_TypeDecl.Builder().setIsTypeParam(false);
}
/** Converts this type declaration into a {@link CelType}. */
public CelType toCelType(CelTypeProvider celTypeProvider) {
switch (name()) {
case "list":
if (params().size() != 1) {
throw new IllegalArgumentException(
"List type has unexpected param count: " + params().size());
}
CelType elementType = params().get(0).toCelType(celTypeProvider);
return ListType.create(elementType);
case "map":
if (params().size() != 2) {
throw new IllegalArgumentException(
"Map type has unexpected param count: " + params().size());
}
CelType keyType = params().get(0).toCelType(celTypeProvider);
CelType valueType = params().get(1).toCelType(celTypeProvider);
return MapType.create(keyType, valueType);
case "type":
checkState(
params().size() == 1, "Expected 1 parameter for type, got %s", params().size());
return TypeType.create(params().get(0).toCelType(celTypeProvider));
default:
if (isTypeParam()) {
return TypeParamType.create(name());
}
if (name().equals("dyn")) {
return SimpleType.DYN;
}
CelType simpleType = SimpleType.findByName(name()).orElse(null);
if (simpleType != null) {
return simpleType;
}
if (name().equals(OptionalType.NAME)) {
checkState(
params().size() == 1,
"Optional type must have exactly 1 parameter. Found %s",
params().size());
return OptionalType.create(params().get(0).toCelType(celTypeProvider));
}
return celTypeProvider
.findType(name())
.orElseThrow(() -> new IllegalArgumentException("Undefined type name: " + name()));
}
}
}
/** Represents a feature flag that can be enabled in the environment. */
@AutoValue
public abstract static class FeatureFlag {
/** Normalized name of the feature flag. */
public abstract String name();
/** Whether the feature is enabled or disabled. */
public abstract boolean enabled();
public static FeatureFlag create(String name, boolean enabled) {
return new AutoValue_CelEnvironment_FeatureFlag(name, enabled);
}
}
/**
* Represents a configurable limit in the environment.
*
* <p>A negative value indicates no limit. If not specified, the limit should be set to the
* library default.
*/
@AutoValue
public abstract static class Limit {
/** Normalized name of the limit (e.g. cel.limit.expression_code_points */
public abstract String name();
/** The value of the limit, -1 means no limit. */
public abstract int value();
public static Limit create(String name, int value) {
return new AutoValue_CelEnvironment_Limit(name, value);
}
}
/**
* Represents a configuration for a canonical CEL extension that can be enabled in the
* environment.
*/
@AutoValue
public abstract static class ExtensionConfig {
/** Name of the extension (ex: bindings, optional, math, etc).". */
public abstract String name();
/**
* Version of the extension. Presently, this field is ignored as CEL-Java extensions are not
* versioned.
*/
public abstract int version();
/** Builder for {@link ExtensionConfig}. */
@AutoValue.Builder
public abstract static class Builder implements RequiredFieldsChecker {
public abstract Optional<String> name();
public abstract Optional<Integer> version();
public abstract ExtensionConfig.Builder setName(String name);
public abstract ExtensionConfig.Builder setVersion(int version);
@Override
public ImmutableList<RequiredField> requiredFields() {
return ImmutableList.of(RequiredField.of("name", this::name));
}
/** Builds a new instance of {@link ExtensionConfig}. */
public abstract ExtensionConfig build();
}
/** Creates a new builder to construct a {@link ExtensionConfig} instance. */
public static ExtensionConfig.Builder newBuilder() {
return new AutoValue_CelEnvironment_ExtensionConfig.Builder().setVersion(0);
}
/** Create a new extension config with the specified name and version set to 0. */
public static ExtensionConfig of(String name) {
return of(name, 0);
}
/** Create a new extension config with the specified name and version. */
public static ExtensionConfig of(String name, int version) {
return newBuilder().setName(name).setVersion(version).build();
}
/** Create a new extension config with the specified name and the latest version. */
public static ExtensionConfig latest(String name) {
return of(name, Integer.MAX_VALUE);
}
}
@AutoValue
abstract static class Alias {
abstract String alias();
abstract String qualifiedName();
static Builder newBuilder() {
return new AutoValue_CelEnvironment_Alias.Builder();
}
@AutoValue.Builder
abstract static class Builder implements RequiredFieldsChecker {
abstract Optional<String> alias();
abstract Optional<String> qualifiedName();
abstract Builder setAlias(String alias);
abstract Builder setQualifiedName(String qualifiedName);
abstract Alias build();
@Override
public ImmutableList<RequiredField> requiredFields() {
return ImmutableList.of(
RequiredField.of("alias", this::alias),
RequiredField.of("qualified_name", this::qualifiedName));
}
}
}
@VisibleForTesting
enum CanonicalCelExtension {
BINDINGS((options, version) -> CelExtensions.bindings()),
PROTOS((options, version) -> CelExtensions.protos()),
ENCODERS(
(options, version) -> CelExtensions.encoders(options),
(options, version) -> CelExtensions.encoders(options)),
MATH(
(options, version) -> CelExtensions.math(options, version),
(options, version) -> CelExtensions.math(options, version)),
OPTIONAL(
(options, version) -> CelExtensions.optional(version),
(options, version) -> CelExtensions.optional(version)),
STRINGS(
(options, version) -> CelExtensions.strings(),
(options, version) -> CelExtensions.strings()),
SETS(
(options, version) -> CelExtensions.sets(options),
(options, version) -> CelExtensions.sets(options)),
REGEX((options, version) -> CelExtensions.regex(), (options, version) -> CelExtensions.regex()),
LISTS((options, version) -> CelExtensions.lists(), (options, version) -> CelExtensions.lists()),
COMPREHENSIONS(
(options, version) -> CelExtensions.comprehensions(),
(options, version) -> CelExtensions.comprehensions());
@SuppressWarnings("ImmutableEnumChecker")
private final CompilerExtensionProvider compilerExtensionProvider;
@SuppressWarnings("ImmutableEnumChecker")
private final RuntimeExtensionProvider runtimeExtensionProvider;
interface CompilerExtensionProvider {
CelCompilerLibrary getCelCompilerLibrary(CelOptions options, int version);
}
interface RuntimeExtensionProvider {
CelRuntimeLibrary getCelRuntimeLibrary(CelOptions options, int version);
}
CompilerExtensionProvider compilerExtensionProvider() {
return compilerExtensionProvider;
}
RuntimeExtensionProvider runtimeExtensionProvider() {
return runtimeExtensionProvider;
}
CanonicalCelExtension(CompilerExtensionProvider compilerExtensionProvider) {
this.compilerExtensionProvider = compilerExtensionProvider;
this.runtimeExtensionProvider = null; // Not all extensions augment the runtime.
}
CanonicalCelExtension(
CompilerExtensionProvider compilerExtensionProvider,
RuntimeExtensionProvider runtimeExtensionProvider) {
this.compilerExtensionProvider = compilerExtensionProvider;
this.runtimeExtensionProvider = runtimeExtensionProvider;
}
}
/**
* LibrarySubset indicates a subset of the macros and function supported by a subsettable library.
*/
@AutoValue
public abstract static class LibrarySubset {
/**
* Disabled indicates whether the library has been disabled, typically only used for
* default-enabled libraries like stdlib.
*/
public abstract boolean disabled();
/** DisableMacros disables macros for the given library. */
public abstract boolean macrosDisabled();
/** IncludeMacros specifies a set of macro function names to include in the subset. */
public abstract ImmutableSet<String> includedMacros();
/**
* ExcludeMacros specifies a set of macro function names to exclude from the subset.
*
* <p>Note: if IncludedMacros is non-empty, then ExcludedMacros is ignored.
*/
public abstract ImmutableSet<String> excludedMacros();
/**
* IncludeFunctions specifies a set of functions to include in the subset.
*
* <p>Note: the overloads specified in the subset need only specify their ID.
*
* <p>Note: if IncludedFunctions is non-empty, then ExcludedFunctions is ignored.
*/
public abstract ImmutableSet<FunctionSelector> includedFunctions();
/**
* ExcludeFunctions specifies the set of functions to exclude from the subset.
*
* <p>Note: the overloads specified in the subset need only specify their ID.
*/
public abstract ImmutableSet<FunctionSelector> excludedFunctions();
public static Builder newBuilder() {
return new AutoValue_CelEnvironment_LibrarySubset.Builder()
.setMacrosDisabled(false)
.setIncludedMacros(ImmutableSet.of())
.setExcludedMacros(ImmutableSet.of())
.setIncludedFunctions(ImmutableSet.of())
.setExcludedFunctions(ImmutableSet.of());
}
/** Builder for {@link LibrarySubset}. */
@AutoValue.Builder
public abstract static class Builder {