diff --git a/checker/src/main/java/dev/cel/checker/CelCheckerLegacyImpl.java b/checker/src/main/java/dev/cel/checker/CelCheckerLegacyImpl.java index 52aea8b23..a430e6e56 100644 --- a/checker/src/main/java/dev/cel/checker/CelCheckerLegacyImpl.java +++ b/checker/src/main/java/dev/cel/checker/CelCheckerLegacyImpl.java @@ -163,9 +163,27 @@ public void accept(EnvVisitor envVisitor) { } } + /** + * Returns the shared scope holding the standard declarations, or {@code null} when standard + * declarations are disabled or could not be added without errors. + */ + @VisibleForTesting + Env.@Nullable DeclGroup standardScope() { + if (overriddenStandardDeclarations != null) { + return Env.standardScope(overriddenStandardDeclarations); + } + if (standardEnvironmentEnabled) { + return Env.standardScope(Env.standardDeclarations(celOptions)); + } + return null; + } + private Env getEnv(Errors errors) { Env env; - if (overriddenStandardDeclarations != null) { + Env.DeclGroup standardScope = standardScope(); + if (standardScope != null) { + env = Env.fromStandardScope(standardScope, errors, celTypeProvider, typeProvider, celOptions); + } else if (overriddenStandardDeclarations != null) { env = Env.standard( overriddenStandardDeclarations, errors, celTypeProvider, typeProvider, celOptions); diff --git a/checker/src/main/java/dev/cel/checker/Env.java b/checker/src/main/java/dev/cel/checker/Env.java index ddc98fab5..6aa476242 100644 --- a/checker/src/main/java/dev/cel/checker/Env.java +++ b/checker/src/main/java/dev/cel/checker/Env.java @@ -21,6 +21,9 @@ import dev.cel.expr.Type; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; +import com.google.common.cache.CacheBuilder; +import com.google.common.cache.CacheLoader; +import com.google.common.cache.LoadingCache; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; @@ -58,6 +61,8 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; import org.jspecify.annotations.Nullable; /** @@ -117,6 +122,20 @@ public class Env { .enableNamespacedDeclarations(false) .build(); + /** + * Standard declarations derived from {@link CelOptions}, keyed by {@link + * #standardDeclarationsKey}. + */ + private static final ConcurrentMap STANDARD_DECLARATIONS = + new ConcurrentHashMap<>(); + + /** + * Immutable scopes holding standard declarations, keyed by the identity of the declarations they + * hold. Empty when adding the declarations reported errors. + */ + private static final LoadingCache> STANDARD_SCOPES = + CacheBuilder.newBuilder().weakKeys().build(CacheLoader.from(Env::buildStandardScope)); + /** * @deprecated Do not use. This exists for compatibility reasons. Migrate to CEL-Java fluent APIs. * See {@code CelCompilerFactory}. @@ -208,13 +227,74 @@ static Env standard( 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); + env.addStandardDeclarations(celStandardDeclaration); + + env.enterScope(); + return env; + } + + /** + * Returns the standard declarations derived from {@code celOptions}, shared by all options + * deriving the same declarations. + */ + static CelStandardDeclarations standardDeclarations(CelOptions celOptions) { + return STANDARD_DECLARATIONS.computeIfAbsent( + standardDeclarationsKey(celOptions), unused -> newStandardDeclarations(celOptions)); + } + + /** Must account for every option read by {@link #newStandardDeclarations}. */ + private static int standardDeclarationsKey(CelOptions celOptions) { + return (celOptions.enableUnsignedLongs() ? 1 : 0) | (celOptions.enableTimestampEpoch() ? 2 : 0); + } + + /** + * Returns an immutable scope holding {@code celStandardDeclarations}, built once and shared by + * environments created with {@link #fromStandardScope}. Returns {@code null} if adding the + * declarations reported errors. + */ + static @Nullable DeclGroup standardScope(CelStandardDeclarations celStandardDeclarations) { + return STANDARD_SCOPES.getUnchecked(celStandardDeclarations).orElse(null); + } + + private static Optional buildStandardScope( + CelStandardDeclarations celStandardDeclarations) { + Errors errors = new Errors("", ""); + // Adding declarations does not depend on the type providers or options. + Env env = Env.unconfigured(errors, EMPTY_TYPE_PROVIDER, null, CelOptions.DEFAULT); + env.addStandardDeclarations(celStandardDeclarations); + if (errors.getErrorCount() > 0) { + return Optional.empty(); + } + return Optional.of(env.getDeclGroup().immutableCopy()); + } + /** + * Creates an {@code Env} value configured with a standard scope returned by {@link + * #standardScope}. 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; } + private void addStandardDeclarations(CelStandardDeclarations celStandardDeclarations) { + celStandardDeclarations.functionDecls().forEach(this::add); + celStandardDeclarations.identifierDecls().forEach(this::add); + } + @Deprecated public static Env standard( CelStandardDeclarations celStandardDeclaration, @@ -993,21 +1073,28 @@ public static class DeclGroup { private final Map idents; private final Map functions; + /** + * 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}. */ @@ -1017,7 +1104,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}. */ @@ -1025,9 +1113,43 @@ 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); + } + + /** + * 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 group must not be layered"); + return new DeclGroup(new HashMap<>(), new HashMap<>(), base); + } + + private static ImmutableMap merge( + Map base, Map overrides) { + return ImmutableMap.builderWithExpectedSize(base.size() + overrides.size()) + .putAll(base) + .putAll(overrides) + .buildKeepingLast(); + } + private DeclGroup() { - this.idents = new HashMap<>(); - this.functions = new HashMap<>(); + this(new HashMap<>(), new HashMap<>(), /* base= */ null); + } + + private DeclGroup( + Map idents, + Map functions, + @Nullable DeclGroup base) { + this.idents = idents; + this.functions = functions; + this.base = base; } } diff --git a/checker/src/test/java/dev/cel/checker/CelCheckerLegacyImplTest.java b/checker/src/test/java/dev/cel/checker/CelCheckerLegacyImplTest.java index 88a78e9ca..b1ef3f93b 100644 --- a/checker/src/test/java/dev/cel/checker/CelCheckerLegacyImplTest.java +++ b/checker/src/test/java/dev/cel/checker/CelCheckerLegacyImplTest.java @@ -172,6 +172,165 @@ public void toCheckerBuilder_collectionProperties_areImmutable() { assertThat(newCheckerBuilder.checkerLibraries().build()).isEmpty(); } + @Test + public void standardScope_sameConfiguration_sharedAcrossCheckers() { + CelCheckerLegacyImpl celChecker = + (CelCheckerLegacyImpl) CelCompilerFactory.standardCelCheckerBuilder().build(); + CelCheckerLegacyImpl otherChecker = + (CelCheckerLegacyImpl) + CelCompilerFactory.standardCelCheckerBuilder() + .addVarDeclarations(CelVarDecl.newVarDeclaration("x", SimpleType.INT)) + .build(); + CelCheckerLegacyImpl derivedChecker = + (CelCheckerLegacyImpl) + celChecker + .toCheckerBuilder() + .addVarDeclarations(CelVarDecl.newVarDeclaration("y", SimpleType.INT)) + .build(); + + assertThat(celChecker.standardScope()).isNotNull(); + assertThat(otherChecker.standardScope()).isSameInstanceAs(celChecker.standardScope()); + assertThat(derivedChecker.standardScope()).isSameInstanceAs(celChecker.standardScope()); + } + + @Test + public void standardScope_unrelatedOptionChanged_shared() { + CelOptions options = CelOptions.current().build(); + CelCheckerLegacyImpl celChecker = + (CelCheckerLegacyImpl) + CelCompilerFactory.standardCelCheckerBuilder().setOptions(options).build(); + CelCheckerLegacyImpl otherChecker = + (CelCheckerLegacyImpl) + CelCompilerFactory.standardCelCheckerBuilder() + .setOptions( + options.toBuilder().populateMacroCalls(!options.populateMacroCalls()).build()) + .build(); + + assertThat(otherChecker.standardScope()).isSameInstanceAs(celChecker.standardScope()); + } + + @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 standardScope_sameStandardDeclarations_shared() { + CelStandardDeclarations standardDeclarations = + CelStandardDeclarations.newBuilder().includeFunctions(StandardFunction.ADD).build(); + CelCheckerLegacyImpl celChecker = + (CelCheckerLegacyImpl) + CelCompilerFactory.standardCelCheckerBuilder() + .setStandardEnvironmentEnabled(false) + .setStandardDeclarations(standardDeclarations) + .build(); + CelCheckerLegacyImpl otherChecker = + (CelCheckerLegacyImpl) + CelCompilerFactory.standardCelCheckerBuilder() + .setStandardEnvironmentEnabled(false) + .setStandardDeclarations(standardDeclarations) + .build(); + + assertThat(otherChecker.standardScope()).isSameInstanceAs(celChecker.standardScope()); + } + + @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_checkersSharingStandardScope_doNotShareDeclarations() throws Exception { + CelChecker withX = + CelCompilerFactory.standardCelCheckerBuilder() + .addVarDeclarations(CelVarDecl.newVarDeclaration("x", SimpleType.INT)) + .build(); + CelChecker withY = + CelCompilerFactory.standardCelCheckerBuilder() + .addVarDeclarations(CelVarDecl.newVarDeclaration("y", SimpleType.STRING)) + .build(); + CelCompiler parser = CelCompilerFactory.standardCelCompilerBuilder().build(); + + assertThat(withX.check(parser.parse("x + 1").getAst()).hasError()).isFalse(); + assertThat(withY.check(parser.parse("y + 'a'").getAst()).hasError()).isFalse(); + assertThat(withY.check(parser.parse("x + 1").getAst()).hasError()).isTrue(); + assertThat(withX.check(parser.parse("y + 'a'").getAst()).hasError()).isTrue(); + } + + @Test + public void check_checkersSharingStandardScope_doNotShareResolvedTypes() throws Exception { + CelCheckerLegacyImpl celChecker = + (CelCheckerLegacyImpl) CelCompilerFactory.standardCelCheckerBuilder().build(); + CelCheckerLegacyImpl withMessageTypes = + (CelCheckerLegacyImpl) + CelCompilerFactory.standardCelCheckerBuilder() + .addMessageTypes(TestAllTypes.getDescriptor()) + .build(); + CelCompiler parser = CelCompilerFactory.standardCelCompilerBuilder().build(); + CelAbstractSyntaxTree ast = parser.parse("cel.expr.conformance.proto3.TestAllTypes{}").getAst(); + + assertThat(withMessageTypes.standardScope()).isSameInstanceAs(celChecker.standardScope()); + assertThat(withMessageTypes.check(ast).hasError()).isFalse(); + assertThat(celChecker.check(ast).hasError()).isTrue(); + } + + @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 =