Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 27 additions & 10 deletions checker/src/main/java/dev/cel/checker/CelCheckerLegacyImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -88,6 +90,10 @@ public final class CelCheckerLegacyImpl implements CelChecker, EnvVisitable {
private final ImmutableSet<FileDescriptor> fileDescriptors;
private final ImmutableSet<ProtoTypeMask> protoTypeMasks;

// Built on first use and only read afterwards, see Env.newStandardScope.
@SuppressWarnings("Immutable")
private final Supplier<Env.@Nullable DeclGroup> standardScope;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CelImpl already wraps the compiler in Suppliers.memoize. I don't think we want to introduce a double memoization here.


@Override
public CelValidationResult check(CelAbstractSyntaxTree ast) {
CelSource source = ast.getSource();
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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<CelIssue> errorsToIssues(Errors errors) {
Expand Down
111 changes: 105 additions & 6 deletions checker/src/main/java/dev/cel/checker/Env.java
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -972,21 +1021,28 @@ public static class DeclGroup {
private final Map<String, CelFunctionDecl> 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<String, CelVarDecl> 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<String, CelFunctionDecl> 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}. */
Expand All @@ -996,17 +1052,60 @@ 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}. */
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 <V> ImmutableMap<String, V> merge(
Map<String, V> base, Map<String, V> overrides) {
return ImmutableMap.<String, V>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<String, CelVarDecl> idents,
Map<String, CelFunctionDecl> functions,
@Nullable DeclGroup base,
boolean isComprehensionScope) {
this.idents = idents;
this.functions = functions;
this.base = base;
this.isComprehensionScope = isComprehensionScope;
}
}
Expand Down
105 changes: 105 additions & 0 deletions checker/src/test/java/dev/cel/checker/CelCheckerLegacyImplTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 =
Expand Down