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
56 changes: 18 additions & 38 deletions checker/src/main/java/dev/cel/checker/Env.java
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,6 @@ public class Env {
*/
private final ArrayList<DeclGroup> decls = new ArrayList<>();

private int comprehensionScopeCount = 0;

/** A map from expression ids into references resolved for the overall tree so far. */
private final Map<Long, CelReference> referenceMap = new LinkedHashMap<>();

Expand Down Expand Up @@ -140,7 +138,7 @@ static Env unconfigured(
CelTypeProvider celTypeProvider,
@Nullable TypeProvider legacyTypeProvider,
CelOptions celOptions) {
return new Env(errors, celTypeProvider, legacyTypeProvider, new DeclGroup(), celOptions);
return new Env(errors, celTypeProvider, legacyTypeProvider, new DeclGroup(false), celOptions);
}

/**
Expand Down Expand Up @@ -285,7 +283,7 @@ CelTypeProvider getCelTypeProvider() {
* scope (overloads from different scopes are not merged).
*/
public void enterScope() {
decls.add(new DeclGroup());
decls.add(new DeclGroup(false));
}

/** Exits a previously opened scope, forgetting all declarations created in this scope. */
Expand All @@ -294,16 +292,9 @@ public void exitScope() {
decls.remove(decls.size() - 1);
}

/** Enters a scope for comprehension variables, which leading-dot identifiers skip. */
/** Enters a scope for comprehension variables, which shadow all other declarations. */
void enterComprehensionScope() {
enterScope();
comprehensionScopeCount++;
}

/** Exits a scope entered with {@link #enterComprehensionScope}. */
void exitComprehensionScope() {
exitScope();
comprehensionScopeCount--;
decls.add(new DeclGroup(true));
}

/** Return the current scope depth for the environment. */
Expand Down Expand Up @@ -515,7 +506,7 @@ public Env add(String name, Type type) {
}

for (String cand : container.resolveCandidateNames(name)) {
CelVarDecl decl = tryLookupCelIdent(cand, name.startsWith("."));
CelVarDecl decl = tryLookupCelIdent(cand);
if (decl != null) {
return decl;
}
Expand All @@ -524,9 +515,9 @@ public Env add(String name, Type type) {
return null;
}

private @Nullable CelVarDecl tryLookupCelIdent(String cand, boolean skipComprehensionScopes) {
private @Nullable CelVarDecl tryLookupCelIdent(String cand) {
// First determine whether we know this name already.
CelVarDecl decl = findIdentDecl(cand, skipComprehensionScopes);
CelVarDecl decl = findIdentDecl(cand, /* comprehensionScopes= */ false);
if (decl != null) {
return decl;
}
Expand Down Expand Up @@ -603,19 +594,7 @@ private static CelType wrapAsTypeIfNeeded(CelType type) {
* <p>Returns {@code null} if not found in local scopes.
*/
@Nullable CelVarDecl tryLookupCelIdentFromLocalScopes(String name) {
int firstUserSpaceScope = 2;
// Iterate from the top of the stack down to the first local scope.
// Note that:
// Scope 0: Standard environment
// Scope 1: User defined environment
// Scope 2 and onwards: comprehension scopes
for (int i = decls.size() - 1; i >= firstUserSpaceScope; i--) {
CelVarDecl ident = decls.get(i).getIdent(name);
if (ident != null) {
return ident;
}
}
return null;
return findIdentDecl(name, /* comprehensionScopes= */ true);
}

/**
Expand Down Expand Up @@ -764,14 +743,13 @@ private void addOverload(CelFunctionDecl.Builder builder, CelOverloadDecl overlo
builder.addOverloads(overload);
}

/**
* Search for the named identifier declaration, optionally skipping the comprehension scopes on
* top of the stack.
*/
private @Nullable CelVarDecl findIdentDecl(String name, boolean skipComprehensionScopes) {
int topScope = decls.size() - 1 - (skipComprehensionScopes ? comprehensionScopeCount : 0);
for (int i = topScope; i >= 0; i--) {
CelVarDecl ident = decls.get(i).getIdent(name);
/** Search for the named identifier declaration in either comprehension or other scopes. */
private @Nullable CelVarDecl findIdentDecl(String name, boolean comprehensionScopes) {
for (DeclGroup declGroup : Lists.reverse(decls)) {
if (declGroup.isComprehensionScope != comprehensionScopes) {
continue;
}
CelVarDecl ident = declGroup.getIdent(name);
if (ident != null) {
return ident;
}
Expand Down Expand Up @@ -992,6 +970,7 @@ public static class DeclGroup {

private final Map<String, CelVarDecl> idents;
private final Map<String, CelFunctionDecl> functions;
private final boolean isComprehensionScope;

/**
* Get an immutable map of the identifiers in the {@code DeclGroup} keyed by declaration name.
Expand Down Expand Up @@ -1025,9 +1004,10 @@ public void putFunction(CelFunctionDecl function) {
functions.put(function.name(), function);
}

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

Expand Down
23 changes: 10 additions & 13 deletions checker/src/main/java/dev/cel/checker/ExprChecker.java
Original file line number Diff line number Diff line change
Expand Up @@ -548,9 +548,9 @@ private void visit(CelMutableExpr expr, CelMutableComprehension compre) {
visit(compre.loopStep());
assertType(compre.loopStep(), accuType);
// Forget iteration variable, as result expression must only depend on accu.
env.exitComprehensionScope();
env.exitScope();
visit(compre.result());
env.exitComprehensionScope();
env.exitScope();

env.setType(expr, inferenceContext.specialize(env.getType(compre.result())));
}
Expand All @@ -562,21 +562,18 @@ private CelReference makeReference(String name, CelVarDecl decl) {
}

/**
* Returns the reference name, prefixed with a leading dot only if disambiguation is needed.
* Disambiguation is needed when: the original name had a leading dot, and there's a local
* variable that would shadow the resolved name.
* Returns the reference name, prefixed with a leading dot when a comprehension variable would
* otherwise shadow the resolved name.
*/
private String maybeDisambiguate(String originalName, String resolvedName) {
if (!originalName.startsWith(".")) {
if (originalName.equals(resolvedName)) {
return resolvedName;
}
String simpleName = originalName.substring(1);
int dotIndex = simpleName.indexOf('.');
String localName = dotIndex > 0 ? simpleName.substring(0, dotIndex) : simpleName;
if (env.tryLookupCelIdentFromLocalScopes(localName) != null) {
return "." + resolvedName;
}
return resolvedName;
int dotIndex = resolvedName.indexOf('.');
String localName = dotIndex > 0 ? resolvedName.substring(0, dotIndex) : resolvedName;
return env.tryLookupCelIdentFromLocalScopes(localName) != null
? "." + resolvedName
: resolvedName;
}

private OverloadResolution resolveOverload(
Expand Down
1 change: 1 addition & 0 deletions checker/src/test/java/dev/cel/checker/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ java_library(
"//common/types:type_providers",
"//compiler",
"//compiler:compiler_builder",
"//extensions",
"//extensions:optional_library",
# "//java/com/google/testing/testsize:annotations",
"//parser:macro",
Expand Down
63 changes: 29 additions & 34 deletions checker/src/test/java/dev/cel/checker/ExprCheckerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,11 @@
import dev.cel.common.CelMutableAst;
import dev.cel.common.CelProtoAbstractSyntaxTree;
import dev.cel.common.CelProtoDeclConverter;
import dev.cel.common.CelVarDecl;
import dev.cel.common.ast.CelConstant;
import dev.cel.common.internal.EnvVisitable;
import dev.cel.common.internal.EnvVisitor;
import dev.cel.common.internal.Errors;
import dev.cel.common.types.CelType;
import dev.cel.common.types.CelTypeProvider;
import dev.cel.common.types.ListType;
import dev.cel.common.types.MapType;
import dev.cel.common.types.NullableType;
Expand All @@ -51,6 +49,7 @@
import dev.cel.common.types.TypeParamType;
import dev.cel.common.types.TypeType;
import dev.cel.expr.conformance.proto3.TestAllTypes;
import dev.cel.extensions.CelExtensions;
import dev.cel.parser.CelMacro;
import dev.cel.testing.CelAdorner;
import dev.cel.testing.CelBaselineTestCase;
Expand All @@ -75,16 +74,20 @@ private void runTest() throws Exception {
TestAllTypes.getDescriptor().getFile(),
dev.cel.expr.conformance.proto2.TestAllTypes.getDescriptor().getFile()));
if (ast != null) {
testOutput()
.println(
CelDebug.toAdornedDebugString(
CelProtoAbstractSyntaxTree.fromCelAst(ast).getExpr(),
new CheckedExprAdorner(
CelProtoAbstractSyntaxTree.fromCelAst(ast).toCheckedExpr())));
printCheckedAst(ast);
}
testOutput().println();
}

private void printCheckedAst(CelAbstractSyntaxTree ast) {
testOutput()
.println(
CelDebug.toAdornedDebugString(
CelProtoAbstractSyntaxTree.fromCelAst(ast).getExpr(),
new CheckedExprAdorner(
CelProtoAbstractSyntaxTree.fromCelAst(ast).toCheckedExpr())));
}

@SuppressWarnings("CheckReturnValue")
private void runErroneousTest(CelAbstractSyntaxTree parsedAst) {
checkArgument(!parsedAst.isChecked());
Expand Down Expand Up @@ -230,32 +233,29 @@ public void referenceTypeAbsolute() throws Exception {
source = "[0].exists(app, .app.config == 1)";
runTest();

clearAllDeclarations();
source = "[1].all(int, type(int) == .int)";
runTest();

declareVariable("x", SimpleType.STRING);
source = "[1].exists(x, [2].exists(y, .x == 'a'))";
runTest();

clearAllDeclarations();
declareVariable("b", SimpleType.STRING);
container = CelContainer.newBuilder().addAlias("a", "b").build();
source = "[1].all(b, a == 'a')";
runTest();
}

@Test
@SuppressWarnings("deprecation") // ExprChecker is used directly to add a non-comprehension scope.
public void referenceAbsolute_declInNonComprehensionScope() throws Exception {
source = "[1].all(x, .x == 'a') && .x == 'a'";
CelTypeProvider typeProvider = ProtoMessageTypeProvider.newBuilder().build();
prepareCompiler(typeProvider);
Errors errors = new Errors("<input>", source);
Env env = Env.standard(errors, typeProvider, null, TEST_OPTIONS);
env.enterScope();
env.add(CelVarDecl.newVarDeclaration("x", SimpleType.STRING));

CelAbstractSyntaxTree ast =
ExprChecker.typecheck(
env, container, celCompiler.parse(source).getAst(), Optional.absent());
public void referenceAbsolute_bindVariable() throws Exception {
declareVariable("x", SimpleType.STRING);
source = "cel.bind(x, 1, .x)";
prepareCompiler(ProtoMessageTypeProvider.newBuilder().build());
celCompiler = celCompiler.toCompilerBuilder().addLibraries(CelExtensions.bindings()).build();

testOutput().println(errors.getAllErrorsAsString());
testOutput()
.println(
CelDebug.toAdornedDebugString(
CelProtoAbstractSyntaxTree.fromCelAst(ast).getExpr(),
new CheckedExprAdorner(
CelProtoAbstractSyntaxTree.fromCelAst(ast).toCheckedExpr())));
printCheckedAst(celCompiler.compile(source).getAst());
}

@Test
Expand Down Expand Up @@ -926,12 +926,7 @@ public void globalStandaloneEnumValues() throws Exception {
descriptorBuilder.addFile(StandaloneGlobalEnum.getDescriptor().getFile().toProto());
CelAbstractSyntaxTree ast = prepareTest(descriptorBuilder.build());
if (ast != null) {
testOutput()
.println(
CelDebug.toAdornedDebugString(
CelProtoAbstractSyntaxTree.fromCelAst(ast).getExpr(),
new CheckedExprAdorner(
CelProtoAbstractSyntaxTree.fromCelAst(ast).toCheckedExpr())));
printCheckedAst(ast);
}
}

Expand Down
20 changes: 20 additions & 0 deletions checker/src/test/resources/referenceAbsolute_bindVariable.baseline
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
Source: cel.bind(x, 1, .x)
declare x {
value string
}
=====>
__comprehension__(
// Variable
#unused,
// Target
[]~list(dyn),
// Accumulator
x,
// Init
1~int,
// LoopCondition
false~bool,
// LoopStep
x~int^x,
// Result
.x~string^.x)~string

This file was deleted.

Loading
Loading