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
52 changes: 42 additions & 10 deletions checker/src/main/java/dev/cel/checker/CelCheckerLegacyImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.CheckReturnValue;
Expand Down Expand Up @@ -88,6 +89,15 @@ public final class CelCheckerLegacyImpl implements CelChecker, EnvVisitable {
private final ImmutableSet<FileDescriptor> fileDescriptors;
private final ImmutableSet<ProtoTypeMask> protoTypeMasks;

// Standard declarations in effect, null when the standard environment is disabled.
private final @Nullable CelStandardDeclarations standardDeclarations;

// Identifier and function declarations added on top of the standard declarations, as found in
// the top-most scope of the environment. Null when adding them reported errors, in which case
// they are added on every check so that the errors are reported.
private final @Nullable ImmutableMap<String, CelVarDecl> identDeclarationsByName;
private final @Nullable ImmutableMap<String, CelFunctionDecl> functionDeclarationsByName;

@Override
public CelValidationResult check(CelAbstractSyntaxTree ast) {
CelSource source = ast.getSource();
Expand Down Expand Up @@ -164,16 +174,25 @@ public void accept(EnvVisitor envVisitor) {
}

private Env getEnv(Errors errors) {
Env env;
if (overriddenStandardDeclarations != null) {
env =
Env.standard(
overriddenStandardDeclarations, errors, celTypeProvider, typeProvider, celOptions);
} else if (standardEnvironmentEnabled) {
env = Env.standard(errors, celTypeProvider, typeProvider, celOptions);
} else {
env = Env.unconfigured(errors, celTypeProvider, typeProvider, celOptions);
}
if (identDeclarationsByName != null && functionDeclarationsByName != null) {
return Env.withDeclarations(
standardDeclarations,
identDeclarationsByName,
functionDeclarationsByName,
errors,
celTypeProvider,
typeProvider,
celOptions);
}
return newEnv(errors);
}

/** Creates an {@code Env} adding the identifier and function declarations to it. */
private Env newEnv(Errors errors) {
Env env =
standardDeclarations != null
? Env.standard(standardDeclarations, errors, celTypeProvider, typeProvider, celOptions)
: Env.unconfigured(errors, celTypeProvider, typeProvider, celOptions);
identDeclarations.forEach(env::add);
functionDeclarations.forEach(env::add);
return env;
Expand Down Expand Up @@ -522,6 +541,19 @@ private CelCheckerLegacyImpl(
this.checkerLibraries = checkerLibraries;
this.fileDescriptors = fileDescriptors;
this.protoTypeMasks = protoTypeMasks;
if (overriddenStandardDeclarations != null) {
this.standardDeclarations = overriddenStandardDeclarations;
} else if (standardEnvironmentEnabled) {
this.standardDeclarations = Env.newStandardDeclarations(celOptions);
} else {
this.standardDeclarations = null;
}

Errors errors = new Errors("", "");
Env.DeclGroup declGroup = newEnv(errors).getDeclGroup();
boolean valid = errors.getErrorCount() == 0;
this.identDeclarationsByName = valid ? declGroup.getIdents() : null;
this.functionDeclarationsByName = valid ? declGroup.getFunctions() : null;
}

private static ImmutableList<CelIssue> errorsToIssues(Errors errors) {
Expand Down
17 changes: 17 additions & 0 deletions checker/src/main/java/dev/cel/checker/CelStandardDeclarations.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -56,6 +58,11 @@ public final class CelStandardDeclarations {
private final ImmutableSet<CelFunctionDecl> celFunctionDecls;
private final ImmutableSet<CelVarDecl> 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<String, CelFunctionDecl> functionDeclsByName;
private final ImmutableMap<String, CelVarDecl> identifierDeclsByName;

/** Enumeration of Standard Functions. */
public enum StandardFunction implements CelFunctionDecl.Declarer {
// Deprecated - use {@link #IN}
Expand Down Expand Up @@ -1787,9 +1794,19 @@ ImmutableSet<CelVarDecl> identifierDecls() {
return celIdentDecls;
}

ImmutableMap<String, CelFunctionDecl> functionDeclsByName() {
return functionDeclsByName;
}

ImmutableMap<String, CelVarDecl> identifierDeclsByName() {
return identifierDeclsByName;
}

private CelStandardDeclarations(
ImmutableSet<CelFunctionDecl> celFunctionDecls, ImmutableSet<CelVarDecl> celIdentDecls) {
this.celFunctionDecls = celFunctionDecls;
this.celIdentDecls = celIdentDecls;
this.functionDeclsByName = Maps.uniqueIndex(celFunctionDecls, CelFunctionDecl::name);
this.identifierDeclsByName = Maps.uniqueIndex(celIdentDecls, CelVarDecl::name);
}
}
62 changes: 53 additions & 9 deletions checker/src/main/java/dev/cel/checker/Env.java
Original file line number Diff line number Diff line change
Expand Up @@ -204,15 +204,45 @@ static Env standard(
CelTypeProvider celTypeProvider,
@Nullable TypeProvider legacyTypeProvider,
CelOptions celOptions) {
Env env = Env.unconfigured(errors, celTypeProvider, legacyTypeProvider, celOptions);
Env env =
new Env(
errors,
celTypeProvider,
legacyTypeProvider,
new DeclGroup(
celStandardDeclaration.identifierDeclsByName(),
celStandardDeclaration.functionDeclsByName(),
/* isComprehensionScope= */ false),
celOptions);
// Isolate the standard declarations into their own scope for forward compatibility.
celStandardDeclaration.functionDecls().forEach(env::add);
celStandardDeclaration.identifierDecls().forEach(env::add);

env.enterScope();
return env;
}

/**
* Creates an {@code Env} value with the standard declarations, when provided, and the given
* declarations, as previously added to an {@code Env} created the same way and read back from its
* top-most scope.
*/
static Env withDeclarations(
@Nullable CelStandardDeclarations celStandardDeclarations,
ImmutableMap<String, CelVarDecl> idents,
ImmutableMap<String, CelFunctionDecl> functions,
Errors errors,
CelTypeProvider celTypeProvider,
@Nullable TypeProvider legacyTypeProvider,
CelOptions celOptions) {
DeclGroup declGroup = new DeclGroup(idents, functions, /* isComprehensionScope= */ false);
if (celStandardDeclarations == null) {
return new Env(errors, celTypeProvider, legacyTypeProvider, declGroup, celOptions);
}
Env env =
standard(
celStandardDeclarations, errors, celTypeProvider, legacyTypeProvider, celOptions);
env.decls.set(env.scopeDepth(), declGroup);
return env;
}

@Deprecated
public static Env standard(
CelStandardDeclarations celStandardDeclaration,
Expand All @@ -222,7 +252,7 @@ public static Env standard(
return standard(celStandardDeclaration, errors, EMPTY_TYPE_PROVIDER, typeProvider, celOptions);
}

private static CelStandardDeclarations newStandardDeclarations(CelOptions celOptions) {
static CelStandardDeclarations newStandardDeclarations(CelOptions celOptions) {
return CelStandardDeclarations.newBuilder()
.filterFunctions(
(function, overload) -> {
Expand Down Expand Up @@ -968,8 +998,9 @@ public Decl build() {
*/
public static class DeclGroup {

private final Map<String, CelVarDecl> idents;
private final Map<String, CelFunctionDecl> functions;
// Copied into mutable maps on first write, so immutable maps can be shared between groups.
private Map<String, CelVarDecl> idents;
private Map<String, CelFunctionDecl> functions;
private final boolean isComprehensionScope;

/**
Expand All @@ -991,6 +1022,9 @@ public ImmutableMap<String, CelFunctionDecl> getFunctions() {

/** Put an identifier declaration into the {@code DeclGroup}. */
public void putIdent(CelVarDecl ident) {
if (idents instanceof ImmutableMap) {
idents = new HashMap<>(idents);
}
idents.put(ident.name(), ident);
}

Expand All @@ -1001,12 +1035,22 @@ public void putIdent(CelVarDecl ident) {

/** Put a function declaration into the {@code DeclGroup}. */
public void putFunction(CelFunctionDecl function) {
if (functions instanceof ImmutableMap) {
functions = new HashMap<>(functions);
}
functions.put(function.name(), function);
}

private DeclGroup(boolean isComprehensionScope) {
this.idents = new HashMap<>();
this.functions = new HashMap<>();
this(new HashMap<>(), new HashMap<>(), isComprehensionScope);
}

private DeclGroup(
Map<String, CelVarDecl> idents,
Map<String, CelFunctionDecl> functions,
boolean isComprehensionScope) {
this.idents = idents;
this.functions = functions;
this.isComprehensionScope = isComprehensionScope;
}
}
Expand Down
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,87 @@ public void toCheckerBuilder_collectionProperties_areImmutable() {
assertThat(newCheckerBuilder.checkerLibraries().build()).isEmpty();
}

@Test
public void check_timestampEpochOption_appliesToStandardScope(@TestParameter boolean enabled)
throws Exception {
CelChecker celChecker =
CelCompilerFactory.standardCelCheckerBuilder()
.setOptions(CelOptions.current().enableTimestampEpoch(enabled).build())
.build();
CelCompiler parser = CelCompilerFactory.standardCelCompilerBuilder().build();

assertThat(celChecker.check(parser.parse("timestamp(1)").getAst()).hasError())
.isEqualTo(!enabled);
}

@Test
public void check_standardDeclarations_onlyDeclaresIncludedFunctions() throws Exception {
CelChecker celChecker =
CelCompilerFactory.standardCelCheckerBuilder()
.setStandardEnvironmentEnabled(false)
.setStandardDeclarations(
CelStandardDeclarations.newBuilder().includeFunctions(StandardFunction.ADD).build())
.build();
CelCompiler parser = CelCompilerFactory.standardCelCompilerBuilder().build();

assertThat(celChecker.check(parser.parse("1 + 2").getAst()).hasError()).isFalse();
assertThat(celChecker.check(parser.parse("1 - 2").getAst()).hasError()).isTrue();
}

@Test
public void check_resolvedTypes_notVisibleToOtherCheckers() throws Exception {
CelChecker withMessageTypes =
CelCompilerFactory.standardCelCheckerBuilder()
.addMessageTypes(TestAllTypes.getDescriptor())
.build();
CelChecker withoutMessageTypes = CelCompilerFactory.standardCelCheckerBuilder().build();
CelCompiler parser = CelCompilerFactory.standardCelCompilerBuilder().build();
CelAbstractSyntaxTree ast = parser.parse("cel.expr.conformance.proto3.TestAllTypes{}").getAst();

assertThat(withMessageTypes.check(ast).hasError()).isFalse();
assertThat(withMessageTypes.check(ast).hasError()).isFalse();
assertThat(withoutMessageTypes.check(ast).hasError()).isTrue();
}

@Test
public void check_overlappingUserDeclarations_reportedOnEveryCheck() throws Exception {
CelChecker celChecker =
CelCompilerFactory.standardCelCheckerBuilder()
.addFunctionDeclarations(
CelFunctionDecl.newFunctionDeclaration(
"f",
CelOverloadDecl.newGlobalOverload("f_int", SimpleType.INT, SimpleType.INT)),
CelFunctionDecl.newFunctionDeclaration(
"f",
CelOverloadDecl.newGlobalOverload("f_dyn", SimpleType.INT, SimpleType.DYN)))
.build();
CelCompiler parser = CelCompilerFactory.standardCelCompilerBuilder().build();
CelAbstractSyntaxTree ast = parser.parse("1").getAst();

assertThat(celChecker.check(ast).getErrorString())
.contains("overlapping overload for name 'f'");
assertThat(celChecker.check(ast).getErrorString())
.contains("overlapping overload for name 'f'");
}

@Test
public void check_userDeclarationWithStandardSignature_shadowsStandardFunction()
throws Exception {
CelChecker celChecker =
CelCompilerFactory.standardCelCheckerBuilder()
.addFunctionDeclarations(
CelFunctionDecl.newFunctionDeclaration(
"size",
CelOverloadDecl.newMemberOverload(
"custom_string_size", SimpleType.DOUBLE, SimpleType.STRING)))
.build();
CelCompiler parser = CelCompilerFactory.standardCelCompilerBuilder().build();

CelAbstractSyntaxTree ast = celChecker.check(parser.parse("'abc'.size()").getAst()).getAst();

assertThat(ast.getResultType()).isEqualTo(SimpleType.DOUBLE);
}

@Test
public void check_wellKnownTypeStructCreation_withLegacyTypeProvider_success() throws Exception {
TypeProvider legacyTypeProvider =
Expand Down
Loading