From d3fe99a7c0a146785ed8bf160d316e4bef93b964 Mon Sep 17 00:00:00 2001 From: Sean Huh Date: Mon, 23 Nov 2026 15:02:36 -0800 Subject: [PATCH] Treat only comprehension variables as local scopes in the type checker PiperOrigin-RevId: 1028494364 --- .../src/main/java/dev/cel/checker/Env.java | 56 ++++-------- .../java/dev/cel/checker/ExprChecker.java | 23 +++-- .../src/test/java/dev/cel/checker/BUILD.bazel | 1 + .../java/dev/cel/checker/ExprCheckerTest.java | 63 ++++++------- .../referenceAbsolute_bindVariable.baseline | 20 +++++ ...olute_declInNonComprehensionScope.baseline | 34 ------- .../resources/referenceTypeAbsolute.baseline | 90 ++++++++++++++++++- 7 files changed, 165 insertions(+), 122 deletions(-) create mode 100644 checker/src/test/resources/referenceAbsolute_bindVariable.baseline delete mode 100644 checker/src/test/resources/referenceAbsolute_declInNonComprehensionScope.baseline diff --git a/checker/src/main/java/dev/cel/checker/Env.java b/checker/src/main/java/dev/cel/checker/Env.java index ddc98fab5..19acb0957 100644 --- a/checker/src/main/java/dev/cel/checker/Env.java +++ b/checker/src/main/java/dev/cel/checker/Env.java @@ -97,8 +97,6 @@ public class Env { */ private final ArrayList decls = new ArrayList<>(); - private int comprehensionScopeCount = 0; - /** A map from expression ids into references resolved for the overall tree so far. */ private final Map referenceMap = new LinkedHashMap<>(); @@ -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); } /** @@ -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. */ @@ -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. */ @@ -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; } @@ -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; } @@ -603,19 +594,7 @@ private static CelType wrapAsTypeIfNeeded(CelType type) { *

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); } /** @@ -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; } @@ -992,6 +970,7 @@ public static class DeclGroup { private final Map idents; private final Map functions; + private final boolean isComprehensionScope; /** * Get an immutable map of the identifiers in the {@code DeclGroup} keyed by declaration name. @@ -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; } } diff --git a/checker/src/main/java/dev/cel/checker/ExprChecker.java b/checker/src/main/java/dev/cel/checker/ExprChecker.java index c028724a3..c4f0a573d 100644 --- a/checker/src/main/java/dev/cel/checker/ExprChecker.java +++ b/checker/src/main/java/dev/cel/checker/ExprChecker.java @@ -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()))); } @@ -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( diff --git a/checker/src/test/java/dev/cel/checker/BUILD.bazel b/checker/src/test/java/dev/cel/checker/BUILD.bazel index cfb8e5329..5f505d96f 100644 --- a/checker/src/test/java/dev/cel/checker/BUILD.bazel +++ b/checker/src/test/java/dev/cel/checker/BUILD.bazel @@ -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", diff --git a/checker/src/test/java/dev/cel/checker/ExprCheckerTest.java b/checker/src/test/java/dev/cel/checker/ExprCheckerTest.java index 2d3b8eeb7..169c60162 100644 --- a/checker/src/test/java/dev/cel/checker/ExprCheckerTest.java +++ b/checker/src/test/java/dev/cel/checker/ExprCheckerTest.java @@ -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; @@ -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; @@ -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()); @@ -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("", 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 @@ -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); } } diff --git a/checker/src/test/resources/referenceAbsolute_bindVariable.baseline b/checker/src/test/resources/referenceAbsolute_bindVariable.baseline new file mode 100644 index 000000000..da6b55682 --- /dev/null +++ b/checker/src/test/resources/referenceAbsolute_bindVariable.baseline @@ -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 diff --git a/checker/src/test/resources/referenceAbsolute_declInNonComprehensionScope.baseline b/checker/src/test/resources/referenceAbsolute_declInNonComprehensionScope.baseline deleted file mode 100644 index e63a1f129..000000000 --- a/checker/src/test/resources/referenceAbsolute_declInNonComprehensionScope.baseline +++ /dev/null @@ -1,34 +0,0 @@ -Source: [1].all(x, .x == 'a') && .x == 'a' -=====> - -_&&_( - __comprehension__( - // Variable - x, - // Target - [ - 1~int - ]~list(int), - // Accumulator - @result, - // Init - true~bool, - // LoopCondition - @not_strictly_false( - @result~bool^@result - )~bool^not_strictly_false, - // LoopStep - _&&_( - @result~bool^@result, - _==_( - .x~string^.x, - "a"~string - )~bool^equals - )~bool^logical_and, - // Result - @result~bool^@result)~bool, - _==_( - .x~string^.x, - "a"~string - )~bool^equals -)~bool^logical_and diff --git a/checker/src/test/resources/referenceTypeAbsolute.baseline b/checker/src/test/resources/referenceTypeAbsolute.baseline index 3d4a0c94d..fd273c177 100644 --- a/checker/src/test/resources/referenceTypeAbsolute.baseline +++ b/checker/src/test/resources/referenceTypeAbsolute.baseline @@ -36,9 +36,6 @@ __comprehension__( @result~bool^@result)~bool Source: [1].all(int, type(int) == .int) -declare app.config { - value int -} =====> __comprehension__( // Variable @@ -67,3 +64,90 @@ __comprehension__( )~bool^logical_and, // Result @result~bool^@result)~bool + +Source: [1].exists(x, [2].exists(y, .x == 'a')) +declare x { + value string +} +=====> +__comprehension__( + // Variable + x, + // Target + [ + 1~int + ]~list(int), + // Accumulator + @result, + // Init + false~bool, + // LoopCondition + @not_strictly_false( + !_( + @result~bool^@result + )~bool^logical_not + )~bool^not_strictly_false, + // LoopStep + _||_( + @result~bool^@result, + __comprehension__( + // Variable + y, + // Target + [ + 2~int + ]~list(int), + // Accumulator + @result, + // Init + false~bool, + // LoopCondition + @not_strictly_false( + !_( + @result~bool^@result + )~bool^logical_not + )~bool^not_strictly_false, + // LoopStep + _||_( + @result~bool^@result, + _==_( + .x~string^.x, + "a"~string + )~bool^equals + )~bool^logical_or, + // Result + @result~bool^@result)~bool + )~bool^logical_or, + // Result + @result~bool^@result)~bool + +Source: [1].all(b, a == 'a') +declare b { + value string +} +=====> +__comprehension__( + // Variable + b, + // Target + [ + 1~int + ]~list(int), + // Accumulator + @result, + // Init + true~bool, + // LoopCondition + @not_strictly_false( + @result~bool^@result + )~bool^not_strictly_false, + // LoopStep + _&&_( + @result~bool^@result, + _==_( + .b~string^.b, + "a"~string + )~bool^equals + )~bool^logical_and, + // Result + @result~bool^@result)~bool