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..5098bea9d 100644 --- a/checker/src/main/java/dev/cel/checker/CelStandardDeclarations.java +++ b/checker/src/main/java/dev/cel/checker/CelStandardDeclarations.java @@ -18,7 +18,9 @@ import static com.google.common.collect.ImmutableSet.toImmutableSet; import static java.util.Arrays.stream; +import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Maps; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.Immutable; import dev.cel.common.CelFunctionDecl; @@ -56,6 +58,11 @@ public final class CelStandardDeclarations { private final ImmutableSet celFunctionDecls; private final ImmutableSet celIdentDecls; + // The declarations above 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 functionDeclsByName; + private final ImmutableMap identifierDeclsByName; + /** Enumeration of Standard Functions. */ public enum StandardFunction implements CelFunctionDecl.Declarer { // Deprecated - use {@link #IN} @@ -1787,9 +1794,19 @@ ImmutableSet identifierDecls() { return celIdentDecls; } + ImmutableMap functionDeclsByName() { + return functionDeclsByName; + } + + ImmutableMap identifierDeclsByName() { + return identifierDeclsByName; + } + private CelStandardDeclarations( ImmutableSet celFunctionDecls, ImmutableSet celIdentDecls) { this.celFunctionDecls = celFunctionDecls; this.celIdentDecls = celIdentDecls; + this.functionDeclsByName = Maps.uniqueIndex(celFunctionDecls, CelFunctionDecl::name); + this.identifierDeclsByName = Maps.uniqueIndex(celIdentDecls, CelVarDecl::name); } } diff --git a/checker/src/main/java/dev/cel/checker/Env.java b/checker/src/main/java/dev/cel/checker/Env.java index 19acb0957..35ff572f7 100644 --- a/checker/src/main/java/dev/cel/checker/Env.java +++ b/checker/src/main/java/dev/cel/checker/Env.java @@ -204,15 +204,45 @@ static Env standard( CelTypeProvider celTypeProvider, @Nullable TypeProvider legacyTypeProvider, CelOptions celOptions) { - Env env = Env.unconfigured(errors, celTypeProvider, legacyTypeProvider, celOptions); + Env env = + new Env( + errors, + celTypeProvider, + legacyTypeProvider, + new DeclGroup( + celStandardDeclaration.identifierDeclsByName(), + celStandardDeclaration.functionDeclsByName(), + /* isComprehensionScope= */ false), + celOptions); // Isolate the standard declarations into their own scope for forward compatibility. - celStandardDeclaration.functionDecls().forEach(env::add); - celStandardDeclaration.identifierDecls().forEach(env::add); - env.enterScope(); return env; } + /** + * 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 = + standard( + celStandardDeclarations, errors, celTypeProvider, legacyTypeProvider, celOptions); + env.decls.set(env.scopeDepth(), declGroup); + return env; + } + @Deprecated public static Env standard( CelStandardDeclarations celStandardDeclaration, @@ -222,7 +252,7 @@ public static Env standard( return standard(celStandardDeclaration, errors, EMPTY_TYPE_PROVIDER, typeProvider, celOptions); } - private static CelStandardDeclarations newStandardDeclarations(CelOptions celOptions) { + static CelStandardDeclarations newStandardDeclarations(CelOptions celOptions) { return CelStandardDeclarations.newBuilder() .filterFunctions( (function, overload) -> { @@ -968,8 +998,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 +1022,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 +1035,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(new HashMap<>(), new HashMap<>(), 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..4cd018a9a 100644 --- a/checker/src/test/java/dev/cel/checker/CelCheckerLegacyImplTest.java +++ b/checker/src/test/java/dev/cel/checker/CelCheckerLegacyImplTest.java @@ -35,6 +35,7 @@ import dev.cel.common.CelValidationException; import dev.cel.common.CelVarDecl; import dev.cel.common.ast.CelExpr; +import dev.cel.common.internal.Errors; import dev.cel.common.types.CelType; import dev.cel.common.types.CelTypeProvider; import dev.cel.common.types.EnumType; @@ -172,6 +173,87 @@ 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(); + assertThat(withMessageTypes.check(ast).hasError()).isFalse(); + assertThat(withoutMessageTypes.check(ast).hasError()).isTrue(); + } + + @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..b23c6a31f 100644 --- a/checker/src/test/java/dev/cel/checker/CelStandardDeclarationsTest.java +++ b/checker/src/test/java/dev/cel/checker/CelStandardDeclarationsTest.java @@ -18,6 +18,7 @@ import static dev.cel.common.CelFunctionDecl.newFunctionDeclaration; import static org.junit.Assert.assertThrows; +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; @@ -26,6 +27,10 @@ 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 org.junit.Test; @@ -385,4 +390,73 @@ 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 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"); + } }