diff --git a/checker/src/main/java/dev/cel/checker/CelCheckerLegacyImpl.java b/checker/src/main/java/dev/cel/checker/CelCheckerLegacyImpl.java index 52aea8b23..af6f297f8 100644 --- a/checker/src/main/java/dev/cel/checker/CelCheckerLegacyImpl.java +++ b/checker/src/main/java/dev/cel/checker/CelCheckerLegacyImpl.java @@ -22,6 +22,8 @@ import dev.cel.expr.Type; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Optional; +import com.google.common.base.Supplier; +import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.errorprone.annotations.CanIgnoreReturnValue; @@ -88,6 +90,10 @@ public final class CelCheckerLegacyImpl implements CelChecker, EnvVisitable { private final ImmutableSet fileDescriptors; private final ImmutableSet protoTypeMasks; + // Built on first use and only read afterwards, see Env.newStandardScope. + @SuppressWarnings("Immutable") + private final Supplier standardScope; + @Override public CelValidationResult check(CelAbstractSyntaxTree ast) { CelSource source = ast.getSource(); @@ -163,17 +169,21 @@ public void accept(EnvVisitor envVisitor) { } } + /** + * Returns the scope holding the standard declarations, built on first use and shared by the + * checks of this checker, or {@code null} when standard declarations are disabled. + */ + @VisibleForTesting + Env.@Nullable DeclGroup standardScope() { + return standardScope.get(); + } + 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); - } + Env.DeclGroup scope = standardScope.get(); + Env env = + scope != null + ? Env.fromStandardScope(scope, errors, celTypeProvider, typeProvider, celOptions) + : Env.unconfigured(errors, celTypeProvider, typeProvider, celOptions); identDeclarations.forEach(env::add); functionDeclarations.forEach(env::add); return env; @@ -522,6 +532,13 @@ private CelCheckerLegacyImpl( this.checkerLibraries = checkerLibraries; this.fileDescriptors = fileDescriptors; this.protoTypeMasks = protoTypeMasks; + this.standardScope = + Suppliers.memoize( + () -> + overriddenStandardDeclarations != null || standardEnvironmentEnabled + ? Env.newStandardScope( + overriddenStandardDeclarations, celTypeProvider, typeProvider, celOptions) + : null); } private static ImmutableList errorsToIssues(Errors errors) { diff --git a/checker/src/main/java/dev/cel/checker/Env.java b/checker/src/main/java/dev/cel/checker/Env.java index 19acb0957..d7b46d925 100644 --- a/checker/src/main/java/dev/cel/checker/Env.java +++ b/checker/src/main/java/dev/cel/checker/Env.java @@ -213,6 +213,55 @@ static Env standard( return env; } + /** + * Builds an immutable scope holding the standard declarations, which can be shared by + * environments created with {@link #fromStandardScope}. The declarations are {@code + * celStandardDeclarations} when provided, or the ones derived from {@code celOptions} otherwise. + */ + static DeclGroup newStandardScope( + @Nullable CelStandardDeclarations celStandardDeclarations, + CelTypeProvider celTypeProvider, + @Nullable TypeProvider legacyTypeProvider, + CelOptions celOptions) { + Errors errors = new Errors("", ""); + Env env = + standard( + celStandardDeclarations != null + ? celStandardDeclarations + : newStandardDeclarations(celOptions), + errors, + celTypeProvider, + legacyTypeProvider, + celOptions); + Preconditions.checkState( + errors.getErrorCount() == 0, + "Standard declarations reported errors: %s", + errors.getAllErrorsAsString()); + return env.getDeclGroup(ROOT_SCOPE).immutableCopy(); + } + + /** + * Creates an {@code Env} value configured with a standard scope built by {@link + * #newStandardScope}. Equivalent to {@link #standard} without having to add the standard + * declarations again. + */ + static Env fromStandardScope( + DeclGroup standardScope, + Errors errors, + CelTypeProvider celTypeProvider, + @Nullable TypeProvider legacyTypeProvider, + CelOptions celOptions) { + Env env = + new Env( + errors, + celTypeProvider, + legacyTypeProvider, + DeclGroup.layeredOn(standardScope), + celOptions); + env.enterScope(); + return env; + } + @Deprecated public static Env standard( CelStandardDeclarations celStandardDeclaration, @@ -972,21 +1021,28 @@ public static class DeclGroup { private final Map functions; private final boolean isComprehensionScope; + /** + * Immutable group whose declarations are visible through this one, unless this group holds a + * declaration with the same name. + */ + private final @Nullable DeclGroup base; + /** * Get an immutable map of the identifiers in the {@code DeclGroup} keyed by declaration name. */ public ImmutableMap getIdents() { - return ImmutableMap.copyOf(idents); + return base == null ? ImmutableMap.copyOf(idents) : merge(base.idents, idents); } /** Get an immutable map of the functions in the {@code DeclGroup} keyed by declaration name. */ public ImmutableMap getFunctions() { - return ImmutableMap.copyOf(functions); + return base == null ? ImmutableMap.copyOf(functions) : merge(base.functions, functions); } /** Get an identifier declaration by {@code name}. Returns {@code null} if absent. */ public @Nullable CelVarDecl getIdent(String name) { - return idents.get(name); + CelVarDecl ident = idents.get(name); + return ident == null && base != null ? base.getIdent(name) : ident; } /** Put an identifier declaration into the {@code DeclGroup}. */ @@ -996,7 +1052,8 @@ public void putIdent(CelVarDecl ident) { /** Get a function declaration by {@code name}. Returns {@code null} if absent. */ public @Nullable CelFunctionDecl getFunction(String name) { - return functions.get(name); + CelFunctionDecl function = functions.get(name); + return function == null && base != null ? base.getFunction(name) : function; } /** Put a function declaration into the {@code DeclGroup}. */ @@ -1004,9 +1061,51 @@ public void putFunction(CelFunctionDecl function) { functions.put(function.name(), function); } + /** + * Returns an immutable copy of this {@code DeclGroup}, which can be safely shared across + * environments and threads. + */ + private DeclGroup immutableCopy() { + return new DeclGroup( + ImmutableMap.copyOf(idents), + ImmutableMap.copyOf(functions), + /* base= */ null, + isComprehensionScope); + } + + /** + * Returns a new mutable {@code DeclGroup} exposing the declarations of the immutable {@code + * base} group, where new declarations are only added to the new group. + */ + private static DeclGroup layeredOn(DeclGroup base) { + Preconditions.checkArgument( + base.base == null + && base.idents instanceof ImmutableMap + && base.functions instanceof ImmutableMap, + "base group must be immutable and not layered"); + return new DeclGroup(new HashMap<>(), new HashMap<>(), base, base.isComprehensionScope); + } + + private static ImmutableMap merge( + Map base, Map overrides) { + return ImmutableMap.builderWithExpectedSize(base.size() + overrides.size()) + .putAll(base) + .putAll(overrides) + .buildKeepingLast(); + } + private DeclGroup(boolean isComprehensionScope) { - this.idents = new HashMap<>(); - this.functions = new HashMap<>(); + this(new HashMap<>(), new HashMap<>(), /* base= */ null, isComprehensionScope); + } + + private DeclGroup( + Map idents, + Map functions, + @Nullable DeclGroup base, + boolean isComprehensionScope) { + this.idents = idents; + this.functions = functions; + this.base = base; 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..41846f9c4 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,110 @@ 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 standardScope_standardEnvironmentDisabled_isNull() { + CelCheckerLegacyImpl celChecker = + (CelCheckerLegacyImpl) + CelCompilerFactory.standardCelCheckerBuilder() + .setStandardEnvironmentEnabled(false) + .build(); + + assertThat(celChecker.standardScope()).isNull(); + } + + @Test + public void standardScope_isImmutable() { + CelCheckerLegacyImpl celChecker = + (CelCheckerLegacyImpl) CelCompilerFactory.standardCelCheckerBuilder().build(); + + assertThrows( + UnsupportedOperationException.class, + () -> + celChecker.standardScope().putIdent(CelVarDecl.newVarDeclaration("x", SimpleType.INT))); + } + + @Test + public void check_resolvedTypes_notAddedToStandardScope() throws Exception { + CelCheckerLegacyImpl celChecker = + (CelCheckerLegacyImpl) + CelCompilerFactory.standardCelCheckerBuilder() + .addMessageTypes(TestAllTypes.getDescriptor()) + .build(); + CelCompiler parser = CelCompilerFactory.standardCelCompilerBuilder().build(); + CelAbstractSyntaxTree ast = parser.parse("cel.expr.conformance.proto3.TestAllTypes{}").getAst(); + + assertThat(celChecker.check(ast).hasError()).isFalse(); + assertThat(celChecker.check(ast).hasError()).isFalse(); + assertThat(celChecker.standardScope().getIdents()) + .doesNotContainKey("cel.expr.conformance.proto3.TestAllTypes"); + } + + @Test + public void fromStandardScope_rootScope_matchesStandard() { + CelOptions celOptions = CelOptions.current().build(); + CelTypeProvider celTypeProvider = + CelCompilerFactory.standardCelCheckerBuilder().build().getTypeProvider(); + CelCheckerLegacyImpl celChecker = + (CelCheckerLegacyImpl) + CelCompilerFactory.standardCelCheckerBuilder().setOptions(celOptions).build(); + + Env.DeclGroup expected = + Env.standard(new Errors("", ""), celTypeProvider, null, celOptions) + .getDeclGroup(Env.ROOT_SCOPE); + Env.DeclGroup actual = + Env.fromStandardScope( + celChecker.standardScope(), new Errors("", ""), celTypeProvider, null, celOptions) + .getDeclGroup(Env.ROOT_SCOPE); + + assertThat(actual.getIdents()).isEqualTo(expected.getIdents()); + assertThat(actual.getFunctions()).isEqualTo(expected.getFunctions()); + } + + @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 =