From 35be08c0bf4477ab3b8397c455b5d1e422648de8 Mon Sep 17 00:00:00 2001 From: Max Penet Date: Wed, 25 Nov 2026 13:56:02 +0100 Subject: [PATCH 1/3] Share the standard declarations scope across type checks CelCheckerLegacyImpl rebuilt the checker Env on every check, adding every standard function and identifier declaration again, along with the overlap checks this involves. This dominated the cost of checking small expressions. Standard declarations are now added once into an immutable DeclGroup, cached by the identity of the CelStandardDeclarations they hold. The declarations derived from CelOptions are cached by the options they depend on, so every checker with the same configuration shares the same scope. Each Env layers a mutable root group on top of it, keeping identifiers resolved through the type provider local to the Env as before. --- .../dev/cel/checker/CelCheckerLegacyImpl.java | 20 ++- .../src/main/java/dev/cel/checker/Env.java | 142 +++++++++++++++- .../cel/checker/CelCheckerLegacyImplTest.java | 159 ++++++++++++++++++ 3 files changed, 312 insertions(+), 9 deletions(-) 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 19acb0957..6f58f4aeb 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; /** @@ -115,6 +120,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}. @@ -206,13 +225,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, @@ -972,21 +1052,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 +1083,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 +1092,47 @@ 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 group must not be 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..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 = From 74bae63f80e06a2ac1cd2aa49f6dee390820d34b Mon Sep 17 00:00:00 2001 From: Max Penet Date: Mon, 30 Nov 2026 21:59:53 +0100 Subject: [PATCH 2/3] Build the standard declarations scope once per checker Replace the static caches with a scope owned by each CelCheckerLegacyImpl, built on first use and passed to the Env on every check. The scope is built through Env.standard with the checker's type providers and options, then copied into an immutable DeclGroup. --- .../dev/cel/checker/CelCheckerLegacyImpl.java | 43 ++++--- .../src/main/java/dev/cel/checker/Env.java | 89 +++++---------- .../cel/checker/CelCheckerLegacyImplTest.java | 108 +++++------------- 3 files changed, 79 insertions(+), 161 deletions(-) diff --git a/checker/src/main/java/dev/cel/checker/CelCheckerLegacyImpl.java b/checker/src/main/java/dev/cel/checker/CelCheckerLegacyImpl.java index a430e6e56..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(); @@ -164,34 +170,20 @@ 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. + * 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() { - if (overriddenStandardDeclarations != null) { - return Env.standardScope(overriddenStandardDeclarations); - } - if (standardEnvironmentEnabled) { - return Env.standardScope(Env.standardDeclarations(celOptions)); - } - return null; + return standardScope.get(); } private Env getEnv(Errors errors) { - Env env; - 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); - } 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; @@ -540,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 6f58f4aeb..d7b46d925 100644 --- a/checker/src/main/java/dev/cel/checker/Env.java +++ b/checker/src/main/java/dev/cel/checker/Env.java @@ -21,9 +21,6 @@ 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; @@ -61,8 +58,6 @@ 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; /** @@ -120,20 +115,6 @@ 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}. @@ -225,50 +206,43 @@ static Env standard( CelOptions celOptions) { Env env = Env.unconfigured(errors, celTypeProvider, legacyTypeProvider, celOptions); // Isolate the standard declarations into their own scope for forward compatibility. - env.addStandardDeclarations(celStandardDeclaration); + celStandardDeclaration.functionDecls().forEach(env::add); + celStandardDeclaration.identifierDecls().forEach(env::add); env.enterScope(); return env; } /** - * Returns the standard declarations derived from {@code celOptions}, shared by all options - * deriving the same declarations. + * 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 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) { + static DeclGroup newStandardScope( + @Nullable CelStandardDeclarations celStandardDeclarations, + CelTypeProvider celTypeProvider, + @Nullable TypeProvider legacyTypeProvider, + CelOptions celOptions) { 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()); + 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 returned by {@link - * #standardScope}. Equivalent to {@link #standard} without having to add the standard + * 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( @@ -288,11 +262,6 @@ static Env fromStandardScope( return env; } - private void addStandardDeclarations(CelStandardDeclarations celStandardDeclarations) { - celStandardDeclarations.functionDecls().forEach(this::add); - celStandardDeclarations.identifierDecls().forEach(this::add); - } - @Deprecated public static Env standard( CelStandardDeclarations celStandardDeclaration, @@ -1109,7 +1078,11 @@ private DeclGroup immutableCopy() { * 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"); + 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); } diff --git a/checker/src/test/java/dev/cel/checker/CelCheckerLegacyImplTest.java b/checker/src/test/java/dev/cel/checker/CelCheckerLegacyImplTest.java index b1ef3f93b..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,43 +173,6 @@ 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 { @@ -222,26 +186,6 @@ public void check_timestampEpochOption_appliesToStandardScope(@TestParameter boo .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 = @@ -279,28 +223,8 @@ public void standardScope_isImmutable() { } @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 { + public void check_resolvedTypes_notAddedToStandardScope() throws Exception { CelCheckerLegacyImpl celChecker = - (CelCheckerLegacyImpl) CelCompilerFactory.standardCelCheckerBuilder().build(); - CelCheckerLegacyImpl withMessageTypes = (CelCheckerLegacyImpl) CelCompilerFactory.standardCelCheckerBuilder() .addMessageTypes(TestAllTypes.getDescriptor()) @@ -308,9 +232,31 @@ public void check_checkersSharingStandardScope_doNotShareResolvedTypes() throws 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(); + 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 From 566dbe80dc2776d05baeb4e0de54be8dbc3ec9a8 Mon Sep 17 00:00:00 2001 From: Max Penet Date: Tue, 1 Dec 2026 08:20:32 +0100 Subject: [PATCH 3/3] Index standard declarations and prebuild user declarations CelStandardDeclarations indexes its declarations by name when built, so Env.standard sets up the standard scope from them without adding each declaration again. DeclGroup is copy-on-write, letting environments share these immutable maps. CelCheckerLegacyImpl adds its identifier and function declarations once, when built, and every check starts from the resulting declarations. If adding them reports errors, they are added on every check as before so the errors are reported. This replaces the per-checker standard scope and the layered DeclGroup. --- .../dev/cel/checker/CelCheckerLegacyImpl.java | 61 +++++---- .../cel/checker/CelStandardDeclarations.java | 17 +++ .../src/main/java/dev/cel/checker/Env.java | 129 +++++------------- .../cel/checker/CelCheckerLegacyImplTest.java | 77 ++++------- .../checker/CelStandardDeclarationsTest.java | 74 ++++++++++ 5 files changed, 193 insertions(+), 165 deletions(-) diff --git a/checker/src/main/java/dev/cel/checker/CelCheckerLegacyImpl.java b/checker/src/main/java/dev/cel/checker/CelCheckerLegacyImpl.java index af6f297f8..329947ae0 100644 --- a/checker/src/main/java/dev/cel/checker/CelCheckerLegacyImpl.java +++ b/checker/src/main/java/dev/cel/checker/CelCheckerLegacyImpl.java @@ -22,9 +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.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.CheckReturnValue; @@ -90,9 +89,14 @@ 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; + // 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) { @@ -169,20 +173,25 @@ 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) { + if (identDeclarationsByName != null && functionDeclarationsByName != null) { + return Env.withDeclarations( + standardDeclarations, + identDeclarationsByName, + functionDeclarationsByName, + errors, + celTypeProvider, + typeProvider, + celOptions); + } + return newEnv(errors); } - private Env getEnv(Errors errors) { - Env.DeclGroup scope = standardScope.get(); + /** Creates an {@code Env} adding the identifier and function declarations to it. */ + private Env newEnv(Errors errors) { Env env = - scope != null - ? Env.fromStandardScope(scope, errors, celTypeProvider, typeProvider, celOptions) + standardDeclarations != null + ? Env.standard(standardDeclarations, errors, celTypeProvider, typeProvider, celOptions) : Env.unconfigured(errors, celTypeProvider, typeProvider, celOptions); identDeclarations.forEach(env::add); functionDeclarations.forEach(env::add); @@ -532,13 +541,19 @@ 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); + 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 d7b46d925..35ff572f7 100644 --- a/checker/src/main/java/dev/cel/checker/Env.java +++ b/checker/src/main/java/dev/cel/checker/Env.java @@ -204,61 +204,42 @@ 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); - - env.enterScope(); - 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), + new Env( errors, celTypeProvider, legacyTypeProvider, + new DeclGroup( + celStandardDeclaration.identifierDeclsByName(), + celStandardDeclaration.functionDeclsByName(), + /* isComprehensionScope= */ false), celOptions); - Preconditions.checkState( - errors.getErrorCount() == 0, - "Standard declarations reported errors: %s", - errors.getAllErrorsAsString()); - return env.getDeclGroup(ROOT_SCOPE).immutableCopy(); + // Isolate the standard declarations into their own scope for forward compatibility. + env.enterScope(); + return env; } /** - * 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. + * 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 fromStandardScope( - DeclGroup standardScope, + 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, - DeclGroup.layeredOn(standardScope), - celOptions); - env.enterScope(); + standard( + celStandardDeclarations, errors, celTypeProvider, legacyTypeProvider, celOptions); + env.decls.set(env.scopeDepth(), declGroup); return env; } @@ -271,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) -> { @@ -1017,95 +998,59 @@ 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; - /** - * 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 base == null ? ImmutableMap.copyOf(idents) : merge(base.idents, idents); + return ImmutableMap.copyOf(idents); } /** Get an immutable map of the functions in the {@code DeclGroup} keyed by declaration name. */ public ImmutableMap getFunctions() { - return base == null ? ImmutableMap.copyOf(functions) : merge(base.functions, functions); + return ImmutableMap.copyOf(functions); } /** Get an identifier declaration by {@code name}. Returns {@code null} if absent. */ public @Nullable CelVarDecl getIdent(String name) { - CelVarDecl ident = idents.get(name); - return ident == null && base != null ? base.getIdent(name) : ident; + return idents.get(name); } /** 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); } /** Get a function declaration by {@code name}. Returns {@code null} if absent. */ public @Nullable CelFunctionDecl getFunction(String name) { - CelFunctionDecl function = functions.get(name); - return function == null && base != null ? base.getFunction(name) : function; + return functions.get(name); } /** 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); } - /** - * 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(new HashMap<>(), new HashMap<>(), /* base= */ null, isComprehensionScope); + this(new HashMap<>(), new HashMap<>(), 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 41846f9c4..4cd018a9a 100644 --- a/checker/src/test/java/dev/cel/checker/CelCheckerLegacyImplTest.java +++ b/checker/src/test/java/dev/cel/checker/CelCheckerLegacyImplTest.java @@ -201,62 +201,39 @@ public void check_standardDeclarations_onlyDeclaresIncludedFunctions() throws Ex } @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(); + 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(celChecker.check(ast).hasError()).isFalse(); - assertThat(celChecker.check(ast).hasError()).isFalse(); - assertThat(celChecker.standardScope().getIdents()) - .doesNotContainKey("cel.expr.conformance.proto3.TestAllTypes"); + assertThat(withMessageTypes.check(ast).hasError()).isFalse(); + assertThat(withMessageTypes.check(ast).hasError()).isFalse(); + assertThat(withoutMessageTypes.check(ast).hasError()).isTrue(); } @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()); + 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 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"); + } }