diff --git a/checker/src/main/java/dev/cel/checker/CelCheckerLegacyImpl.java b/checker/src/main/java/dev/cel/checker/CelCheckerLegacyImpl.java index 52aea8b23..329947ae0 100644 --- a/checker/src/main/java/dev/cel/checker/CelCheckerLegacyImpl.java +++ b/checker/src/main/java/dev/cel/checker/CelCheckerLegacyImpl.java @@ -23,6 +23,7 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Optional; 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; @@ -88,6 +89,15 @@ public final class CelCheckerLegacyImpl implements CelChecker, EnvVisitable { private final ImmutableSet fileDescriptors; private final ImmutableSet protoTypeMasks; + // Standard declarations in effect, null when the standard environment is disabled. + private final @Nullable CelStandardDeclarations standardDeclarations; + + // Identifier and function declarations added on top of the standard declarations, as found in + // the top-most scope of the environment. Null when adding them reported errors, in which case + // they are added on every check so that the errors are reported. + private final @Nullable ImmutableMap identDeclarationsByName; + private final @Nullable ImmutableMap functionDeclarationsByName; + @Override public CelValidationResult check(CelAbstractSyntaxTree ast) { CelSource source = ast.getSource(); @@ -164,16 +174,25 @@ public void accept(EnvVisitor envVisitor) { } private Env getEnv(Errors errors) { - Env env; - if (overriddenStandardDeclarations != null) { - env = - Env.standard( - overriddenStandardDeclarations, errors, celTypeProvider, typeProvider, celOptions); - } else if (standardEnvironmentEnabled) { - env = Env.standard(errors, celTypeProvider, typeProvider, celOptions); - } else { - env = Env.unconfigured(errors, celTypeProvider, typeProvider, celOptions); - } + if (identDeclarationsByName != null && functionDeclarationsByName != null) { + return Env.withDeclarations( + standardDeclarations, + identDeclarationsByName, + functionDeclarationsByName, + errors, + celTypeProvider, + typeProvider, + celOptions); + } + return newEnv(errors); + } + + /** Creates an {@code Env} adding the identifier and function declarations to it. */ + private Env newEnv(Errors errors) { + Env env = + standardDeclarations != null + ? Env.standard(standardDeclarations, errors, celTypeProvider, typeProvider, celOptions) + : Env.unconfigured(errors, celTypeProvider, typeProvider, celOptions); identDeclarations.forEach(env::add); functionDeclarations.forEach(env::add); return env; @@ -522,6 +541,19 @@ private CelCheckerLegacyImpl( this.checkerLibraries = checkerLibraries; this.fileDescriptors = fileDescriptors; this.protoTypeMasks = protoTypeMasks; + if (overriddenStandardDeclarations != null) { + this.standardDeclarations = overriddenStandardDeclarations; + } else if (standardEnvironmentEnabled) { + this.standardDeclarations = Env.newStandardDeclarations(celOptions); + } else { + this.standardDeclarations = null; + } + + Errors errors = new Errors("", ""); + Env.DeclGroup declGroup = newEnv(errors).getDeclGroup(); + boolean valid = errors.getErrorCount() == 0; + this.identDeclarationsByName = valid ? declGroup.getIdents() : null; + this.functionDeclarationsByName = valid ? declGroup.getFunctions() : null; } private static ImmutableList errorsToIssues(Errors errors) { diff --git a/checker/src/main/java/dev/cel/checker/CelStandardDeclarations.java b/checker/src/main/java/dev/cel/checker/CelStandardDeclarations.java index 9417bf1d4..0d9304dcf 100644 --- a/checker/src/main/java/dev/cel/checker/CelStandardDeclarations.java +++ b/checker/src/main/java/dev/cel/checker/CelStandardDeclarations.java @@ -18,6 +18,8 @@ import static com.google.common.collect.ImmutableSet.toImmutableSet; import static java.util.Arrays.stream; +import com.google.common.collect.ImmutableCollection; +import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.Immutable; @@ -51,10 +53,12 @@ public final class CelStandardDeclarations { /** An empty instance of {@link CelStandardDeclarations} with no functions or identifiers. */ public static final CelStandardDeclarations EMPTY = - new CelStandardDeclarations(ImmutableSet.of(), ImmutableSet.of()); + new CelStandardDeclarations(ImmutableMap.of(), ImmutableMap.of()); - private final ImmutableSet celFunctionDecls; - private final ImmutableSet celIdentDecls; + // Declarations keyed by name, as added to the type-checker environment. Declarations are built + // from the standard functions and identifiers, so their names are unique. + private final ImmutableMap celFunctionDecls; + private final ImmutableMap celIdentDecls; /** Enumeration of Standard Functions. */ public enum StandardFunction implements CelFunctionDecl.Declarer { @@ -1686,17 +1690,19 @@ public CelStandardDeclarations build() { "You may only populate one of the following builder methods: includeIdentifiers," + " excludeIdentifiers or filterIdentifiers"); - ImmutableSet.Builder functionDeclBuilder = ImmutableSet.builder(); + ImmutableMap.Builder functionDeclBuilder = ImmutableMap.builder(); for (StandardFunction standardFunction : StandardFunction.values()) { if (hasIncludeFunctions) { if (this.includeFunctions.contains(standardFunction)) { - functionDeclBuilder.add(standardFunction.celFunctionDecl); + functionDeclBuilder.put( + standardFunction.functionName, standardFunction.celFunctionDecl); } continue; } if (hasExcludeFunctions) { if (!this.excludeFunctions.contains(standardFunction)) { - functionDeclBuilder.add(standardFunction.celFunctionDecl); + functionDeclBuilder.put( + standardFunction.functionName, standardFunction.celFunctionDecl); } continue; } @@ -1711,26 +1717,27 @@ public CelStandardDeclarations build() { ImmutableSet overloads = overloadBuilder.build(); if (!overloads.isEmpty()) { - functionDeclBuilder.add(standardFunction.withOverloads(overloadBuilder.build())); + functionDeclBuilder.put( + standardFunction.functionName, standardFunction.withOverloads(overloads)); } continue; } - functionDeclBuilder.add(standardFunction.celFunctionDecl); + functionDeclBuilder.put(standardFunction.functionName, standardFunction.celFunctionDecl); } - ImmutableSet.Builder identBuilder = ImmutableSet.builder(); + ImmutableMap.Builder identBuilder = ImmutableMap.builder(); for (StandardIdentifier standardIdentifier : StandardIdentifier.values()) { if (hasIncludeIdentifiers) { if (this.includeIdentifiers.contains(standardIdentifier)) { - identBuilder.add(standardIdentifier.identDecl); + identBuilder.put(standardIdentifier.identDecl.name(), standardIdentifier.identDecl); } continue; } if (hasExcludeIdentifiers) { if (!this.excludeIdentifiers.contains(standardIdentifier)) { - identBuilder.add(standardIdentifier.identDecl); + identBuilder.put(standardIdentifier.identDecl.name(), standardIdentifier.identDecl); } continue; } @@ -1738,12 +1745,12 @@ public CelStandardDeclarations build() { if (hasIdentifierFilter) { boolean includeIdent = identifierFilter.include(standardIdentifier); if (includeIdent) { - identBuilder.add(standardIdentifier.identDecl); + identBuilder.put(standardIdentifier.identDecl.name(), standardIdentifier.identDecl); } continue; } - identBuilder.add(standardIdentifier.identDecl); + identBuilder.put(standardIdentifier.identDecl.name(), standardIdentifier.identDecl); } return new CelStandardDeclarations(functionDeclBuilder.build(), identBuilder.build()); @@ -1779,16 +1786,38 @@ public static Builder newBuilder() { return new Builder(); } - ImmutableSet functionDecls() { + /** Returns the declarations of all the standard functions and identifiers. */ + static CelStandardDeclarations all() { + return AllHolder.ALL; + } + + /** + * Holds {@link #all()}, built on first use rather than when this class is initialized, since the + * standard functions and identifiers it is built from depend on this class being initialized. + */ + private static final class AllHolder { + private static final CelStandardDeclarations ALL = newBuilder().build(); + } + + ImmutableCollection functionDecls() { + return celFunctionDecls.values(); + } + + ImmutableCollection identifierDecls() { + return celIdentDecls.values(); + } + + ImmutableMap functionDeclsByName() { return celFunctionDecls; } - ImmutableSet identifierDecls() { + ImmutableMap identifierDeclsByName() { return celIdentDecls; } private CelStandardDeclarations( - ImmutableSet celFunctionDecls, ImmutableSet celIdentDecls) { + ImmutableMap celFunctionDecls, + ImmutableMap celIdentDecls) { this.celFunctionDecls = celFunctionDecls; this.celIdentDecls = celIdentDecls; } diff --git a/checker/src/main/java/dev/cel/checker/Env.java b/checker/src/main/java/dev/cel/checker/Env.java index 19acb0957..f3650f205 100644 --- a/checker/src/main/java/dev/cel/checker/Env.java +++ b/checker/src/main/java/dev/cel/checker/Env.java @@ -204,12 +204,45 @@ static Env standard( CelTypeProvider celTypeProvider, @Nullable TypeProvider legacyTypeProvider, CelOptions celOptions) { - Env env = Env.unconfigured(errors, celTypeProvider, legacyTypeProvider, celOptions); - // Isolate the standard declarations into their own scope for forward compatibility. - celStandardDeclaration.functionDecls().forEach(env::add); - celStandardDeclaration.identifierDecls().forEach(env::add); + return withDeclarations( + celStandardDeclaration, + ImmutableMap.of(), + ImmutableMap.of(), + errors, + celTypeProvider, + legacyTypeProvider, + celOptions); + } - env.enterScope(); + /** + * Creates an {@code Env} value with the standard declarations, when provided, and the given + * declarations, as previously added to an {@code Env} created the same way and read back from its + * top-most scope. + */ + static Env withDeclarations( + @Nullable CelStandardDeclarations celStandardDeclarations, + ImmutableMap idents, + ImmutableMap functions, + Errors errors, + CelTypeProvider celTypeProvider, + @Nullable TypeProvider legacyTypeProvider, + CelOptions celOptions) { + DeclGroup declGroup = new DeclGroup(idents, functions, /* isComprehensionScope= */ false); + if (celStandardDeclarations == null) { + return new Env(errors, celTypeProvider, legacyTypeProvider, declGroup, celOptions); + } + Env env = + new Env( + errors, + celTypeProvider, + legacyTypeProvider, + new DeclGroup( + celStandardDeclarations.identifierDeclsByName(), + celStandardDeclarations.functionDeclsByName(), + /* isComprehensionScope= */ false), + celOptions); + // Isolate the standard declarations into their own scope for forward compatibility. + env.decls.add(declGroup); return env; } @@ -222,7 +255,11 @@ public static Env standard( return standard(celStandardDeclaration, errors, EMPTY_TYPE_PROVIDER, typeProvider, celOptions); } - private static CelStandardDeclarations newStandardDeclarations(CelOptions celOptions) { + static CelStandardDeclarations newStandardDeclarations(CelOptions celOptions) { + // Nothing is filtered out with these options. + if (celOptions.enableUnsignedLongs() && celOptions.enableTimestampEpoch()) { + return CelStandardDeclarations.all(); + } return CelStandardDeclarations.newBuilder() .filterFunctions( (function, overload) -> { @@ -968,8 +1005,9 @@ public Decl build() { */ public static class DeclGroup { - private final Map idents; - private final Map functions; + // Copied into mutable maps on first write, so immutable maps can be shared between groups. + private Map idents; + private Map functions; private final boolean isComprehensionScope; /** @@ -991,6 +1029,9 @@ public ImmutableMap getFunctions() { /** Put an identifier declaration into the {@code DeclGroup}. */ public void putIdent(CelVarDecl ident) { + if (idents instanceof ImmutableMap) { + idents = new HashMap<>(idents); + } idents.put(ident.name(), ident); } @@ -1001,12 +1042,22 @@ public void putIdent(CelVarDecl ident) { /** Put a function declaration into the {@code DeclGroup}. */ public void putFunction(CelFunctionDecl function) { + if (functions instanceof ImmutableMap) { + functions = new HashMap<>(functions); + } functions.put(function.name(), function); } private DeclGroup(boolean isComprehensionScope) { - this.idents = new HashMap<>(); - this.functions = new HashMap<>(); + this(ImmutableMap.of(), ImmutableMap.of(), isComprehensionScope); + } + + private DeclGroup( + Map idents, + Map functions, + boolean isComprehensionScope) { + this.idents = idents; + this.functions = functions; this.isComprehensionScope = isComprehensionScope; } } diff --git a/checker/src/test/java/dev/cel/checker/CelCheckerLegacyImplTest.java b/checker/src/test/java/dev/cel/checker/CelCheckerLegacyImplTest.java index 88a78e9ca..adf70f859 100644 --- a/checker/src/test/java/dev/cel/checker/CelCheckerLegacyImplTest.java +++ b/checker/src/test/java/dev/cel/checker/CelCheckerLegacyImplTest.java @@ -17,6 +17,7 @@ import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; +import dev.cel.expr.Decl; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; @@ -35,6 +36,7 @@ import dev.cel.common.CelValidationException; import dev.cel.common.CelVarDecl; import dev.cel.common.ast.CelExpr; +import dev.cel.common.internal.EnvVisitor; import dev.cel.common.types.CelType; import dev.cel.common.types.CelTypeProvider; import dev.cel.common.types.EnumType; @@ -49,6 +51,8 @@ import dev.cel.expr.conformance.proto2.TestAllTypesExtensions; import dev.cel.expr.conformance.proto2.TestAllTypesProto; import dev.cel.expr.conformance.proto3.TestAllTypes; +import dev.cel.parser.CelMacro; +import java.util.List; import java.util.Optional; import org.junit.Test; import org.junit.runner.RunWith; @@ -172,6 +176,122 @@ public void toCheckerBuilder_collectionProperties_areImmutable() { assertThat(newCheckerBuilder.checkerLibraries().build()).isEmpty(); } + @Test + public void check_timestampEpochOption_appliesToStandardScope(@TestParameter boolean enabled) + throws Exception { + CelChecker celChecker = + CelCompilerFactory.standardCelCheckerBuilder() + .setOptions(CelOptions.current().enableTimestampEpoch(enabled).build()) + .build(); + CelCompiler parser = CelCompilerFactory.standardCelCompilerBuilder().build(); + + assertThat(celChecker.check(parser.parse("timestamp(1)").getAst()).hasError()) + .isEqualTo(!enabled); + } + + @Test + public void check_standardDeclarations_onlyDeclaresIncludedFunctions() throws Exception { + CelChecker celChecker = + CelCompilerFactory.standardCelCheckerBuilder() + .setStandardEnvironmentEnabled(false) + .setStandardDeclarations( + CelStandardDeclarations.newBuilder().includeFunctions(StandardFunction.ADD).build()) + .build(); + CelCompiler parser = CelCompilerFactory.standardCelCompilerBuilder().build(); + + assertThat(celChecker.check(parser.parse("1 + 2").getAst()).hasError()).isFalse(); + assertThat(celChecker.check(parser.parse("1 - 2").getAst()).hasError()).isTrue(); + } + + @Test + public void check_resolvedTypes_notVisibleToOtherCheckers() throws Exception { + CelChecker withMessageTypes = + CelCompilerFactory.standardCelCheckerBuilder() + .addMessageTypes(TestAllTypes.getDescriptor()) + .build(); + CelChecker withoutMessageTypes = CelCompilerFactory.standardCelCheckerBuilder().build(); + CelCompiler parser = CelCompilerFactory.standardCelCompilerBuilder().build(); + CelAbstractSyntaxTree ast = parser.parse("cel.expr.conformance.proto3.TestAllTypes{}").getAst(); + + assertThat(withMessageTypes.check(ast).hasError()).isFalse(); + // Checks again, the first check added the resolved type to its own copy of the root scope. + assertThat(withMessageTypes.check(ast).hasError()).isFalse(); + assertThat(withoutMessageTypes.check(ast).hasError()).isTrue(); + } + + @Test + public void check_standardEnvironmentDisabled_resolvedTypesNotAddedToDeclarations() + throws Exception { + CelCheckerLegacyImpl celChecker = + (CelCheckerLegacyImpl) + CelCompilerFactory.standardCelCheckerBuilder() + .setStandardEnvironmentEnabled(false) + .addMessageTypes(TestAllTypes.getDescriptor()) + .addVarDeclarations(CelVarDecl.newVarDeclaration("x", SimpleType.INT)) + .build(); + CelCompiler parser = CelCompilerFactory.standardCelCompilerBuilder().build(); + CelAbstractSyntaxTree ast = parser.parse("cel.expr.conformance.proto3.TestAllTypes{}").getAst(); + ImmutableList declarationNames = declarationNames(celChecker); + + assertThat(celChecker.check(ast).hasError()).isFalse(); + assertThat(celChecker.check(ast).hasError()).isFalse(); + assertThat(declarationNames(celChecker)).isEqualTo(declarationNames); + } + + private static ImmutableList declarationNames(CelCheckerLegacyImpl celChecker) { + ImmutableList.Builder names = ImmutableList.builder(); + celChecker.accept( + new EnvVisitor() { + @Override + public void visitDecl(String name, List decls) { + names.add(name); + } + + @Override + public void visitMacro(CelMacro macro) {} + }); + return names.build(); + } + + @Test + public void check_overlappingUserDeclarations_reportedOnEveryCheck() throws Exception { + CelChecker celChecker = + CelCompilerFactory.standardCelCheckerBuilder() + .addFunctionDeclarations( + CelFunctionDecl.newFunctionDeclaration( + "f", + CelOverloadDecl.newGlobalOverload("f_int", SimpleType.INT, SimpleType.INT)), + CelFunctionDecl.newFunctionDeclaration( + "f", + CelOverloadDecl.newGlobalOverload("f_dyn", SimpleType.INT, SimpleType.DYN))) + .build(); + CelCompiler parser = CelCompilerFactory.standardCelCompilerBuilder().build(); + CelAbstractSyntaxTree ast = parser.parse("1").getAst(); + + assertThat(celChecker.check(ast).getErrorString()) + .contains("overlapping overload for name 'f'"); + assertThat(celChecker.check(ast).getErrorString()) + .contains("overlapping overload for name 'f'"); + } + + @Test + public void check_userDeclarationWithStandardSignature_shadowsStandardFunction() + throws Exception { + CelChecker celChecker = + CelCompilerFactory.standardCelCheckerBuilder() + .addFunctionDeclarations( + CelFunctionDecl.newFunctionDeclaration( + "size", + CelOverloadDecl.newMemberOverload( + "custom_string_size", SimpleType.DOUBLE, SimpleType.STRING))) + .build(); + CelCompiler parser = CelCompilerFactory.standardCelCompilerBuilder().build(); + + CelAbstractSyntaxTree ast = celChecker.check(parser.parse("'abc'.size()").getAst()).getAst(); + + assertThat(ast.getResultType()).isEqualTo(SimpleType.DOUBLE); + } + @Test public void check_wellKnownTypeStructCreation_withLegacyTypeProvider_success() throws Exception { TypeProvider legacyTypeProvider = diff --git a/checker/src/test/java/dev/cel/checker/CelStandardDeclarationsTest.java b/checker/src/test/java/dev/cel/checker/CelStandardDeclarationsTest.java index 8c612b8e3..c10452fd0 100644 --- a/checker/src/test/java/dev/cel/checker/CelStandardDeclarationsTest.java +++ b/checker/src/test/java/dev/cel/checker/CelStandardDeclarationsTest.java @@ -18,16 +18,26 @@ import static dev.cel.common.CelFunctionDecl.newFunctionDeclaration; import static org.junit.Assert.assertThrows; +import com.google.common.io.ByteStreams; +import com.google.testing.junit.testparameterinjector.TestParameter; import com.google.testing.junit.testparameterinjector.TestParameterInjector; import com.google.testing.junit.testparameterinjector.TestParameters; import dev.cel.checker.CelStandardDeclarations.StandardFunction; import dev.cel.checker.CelStandardDeclarations.StandardFunction.Overload.Arithmetic; import dev.cel.checker.CelStandardDeclarations.StandardFunction.Overload.Comparison; +import dev.cel.checker.CelStandardDeclarations.StandardFunction.Overload.Conversions; import dev.cel.checker.CelStandardDeclarations.StandardIdentifier; import dev.cel.common.CelOptions; import dev.cel.common.CelValidationException; +import dev.cel.common.CelVarDecl; +import dev.cel.common.internal.Errors; +import dev.cel.common.types.CelTypeProvider; +import dev.cel.common.types.SimpleType; import dev.cel.compiler.CelCompiler; import dev.cel.compiler.CelCompilerFactory; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Method; import org.junit.Test; import org.junit.runner.RunWith; @@ -385,4 +395,161 @@ public void timestampEpochDisabled_int64Identity_throws() { CelValidationException.class, () -> celCompiler.compile("timestamp(10000)").getAst()); assertThat(e).hasMessageThat().contains("found no matching overload for"); } + + private enum DeclarationsTestCase { + ALL(CelStandardDeclarations.newBuilder().build()), + INCLUDED_FUNCTIONS( + CelStandardDeclarations.newBuilder() + .includeFunctions(StandardFunction.ADD, StandardFunction.SIZE) + .build()), + FILTERED_OVERLOADS( + CelStandardDeclarations.newBuilder() + .filterFunctions( + (function, overload) -> + !(overload instanceof Comparison) + || !((Comparison) overload).isHeterogeneousComparison()) + .build()), + EXCLUDED_IDENTIFIERS( + CelStandardDeclarations.newBuilder() + .excludeIdentifiers(StandardIdentifier.INT, StandardIdentifier.DURATION) + .build()); + + private final CelStandardDeclarations declarations; + + DeclarationsTestCase(CelStandardDeclarations declarations) { + this.declarations = declarations; + } + } + + @Test + public void standardDeclarations_indexedDeclarations_matchDeclarationsAddedToEnv( + @TestParameter DeclarationsTestCase testCase) { + CelStandardDeclarations declarations = testCase.declarations; + Errors errors = new Errors("", ""); + Env env = Env.unconfigured(errors, CelOptions.DEFAULT); + declarations.functionDecls().forEach(env::add); + declarations.identifierDecls().forEach(env::add); + + assertThat(errors.getErrorCount()).isEqualTo(0); + assertThat(declarations.functionDeclsByName()) + .isEqualTo(env.getDeclGroup(Env.ROOT_SCOPE).getFunctions()); + assertThat(declarations.identifierDeclsByName()) + .isEqualTo(env.getDeclGroup(Env.ROOT_SCOPE).getIdents()); + } + + @Test + public void standardFunctionInitializedFirst_initializesClasses() throws Exception { + ClassLoader classLoader = new StandardDeclarationsClassLoader(getClass().getClassLoader()); + + Class standardFunction = + Class.forName(StandardFunction.class.getName(), /* initialize= */ true, classLoader); + Class standardDeclarations = + Class.forName( + CelStandardDeclarations.class.getName(), /* initialize= */ true, classLoader); + Method all = standardDeclarations.getDeclaredMethod("all"); + all.setAccessible(true); + + assertThat(standardFunction.getEnumConstants()).isNotEmpty(); + assertThat(all.invoke(null)).isNotNull(); + } + + /** Loads {@link CelStandardDeclarations} and its nested classes again, uninitialized. */ + private static final class StandardDeclarationsClassLoader extends ClassLoader { + + private StandardDeclarationsClassLoader(ClassLoader parent) { + super(parent); + } + + @Override + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + if (!name.startsWith(CelStandardDeclarations.class.getName())) { + return super.loadClass(name, resolve); + } + synchronized (getClassLoadingLock(name)) { + Class loadedClass = findLoadedClass(name); + if (loadedClass != null) { + return loadedClass; + } + try (InputStream classFile = + getParent().getResourceAsStream(name.replace('.', '/') + ".class")) { + byte[] bytes = ByteStreams.toByteArray(classFile); + return defineClass(name, bytes, 0, bytes.length); + } catch (IOException e) { + throw new ClassNotFoundException(name, e); + } + } + } + } + + @Test + public void newStandardDeclarations_allOptionsEnabled_returnsAll() { + CelOptions celOptions = + CelOptions.current().enableUnsignedLongs(true).enableTimestampEpoch(true).build(); + + assertThat(Env.newStandardDeclarations(celOptions)) + .isSameInstanceAs(CelStandardDeclarations.all()); + assertThat( + CelStandardDeclarations.newBuilder() + .filterFunctions((function, overload) -> true) + .build() + .functionDeclsByName()) + .isEqualTo(CelStandardDeclarations.all().functionDeclsByName()); + } + + @Test + @TestParameters("{enableUnsignedLongs: false, enableTimestampEpoch: false}") + @TestParameters("{enableUnsignedLongs: false, enableTimestampEpoch: true}") + @TestParameters("{enableUnsignedLongs: true, enableTimestampEpoch: false}") + public void newStandardDeclarations_optionDisabled_filtersOverloads( + boolean enableUnsignedLongs, boolean enableTimestampEpoch) { + CelStandardDeclarations declarations = + Env.newStandardDeclarations( + CelOptions.current() + .enableUnsignedLongs(enableUnsignedLongs) + .enableTimestampEpoch(enableTimestampEpoch) + .build()); + + assertThat( + declarations + .functionDeclsByName() + .get("int") + .overloads() + .contains(Conversions.INT64_TO_INT64.celOverloadDecl())) + .isEqualTo(enableUnsignedLongs); + assertThat( + declarations + .functionDeclsByName() + .get("timestamp") + .overloads() + .contains(Conversions.INT64_TO_TIMESTAMP.celOverloadDecl())) + .isEqualTo(enableTimestampEpoch); + } + + @Test + public void standardEnv_rootScopeWrites_notVisibleToOtherEnvs() { + CelStandardDeclarations declarations = CelStandardDeclarations.newBuilder().build(); + CelTypeProvider typeProvider = + CelCompilerFactory.standardCelCheckerBuilder().build().getTypeProvider(); + CelVarDecl ident = CelVarDecl.newVarDeclaration("x", SimpleType.INT); + + Env env = + Env.standard( + declarations, + new Errors("", ""), + typeProvider, + /* legacyTypeProvider= */ null, + CelOptions.DEFAULT); + env.getDeclGroup(Env.ROOT_SCOPE).putIdent(ident); + Env otherEnv = + Env.standard( + declarations, + new Errors("", ""), + typeProvider, + /* legacyTypeProvider= */ null, + CelOptions.DEFAULT); + + assertThat(env.getDeclGroup(Env.ROOT_SCOPE).getIdent("x")).isEqualTo(ident); + assertThat(otherEnv.getDeclGroup(Env.ROOT_SCOPE).getIdent("x")).isNull(); + assertThat(declarations.identifierDeclsByName()).doesNotContainKey("x"); + } }