Skip to content

Commit 0aad04e

Browse files
l46kokcopybara-github
authored andcommitted
Fix policy variable scoping issues, enable conformance tests around it
Port of cel-expr/cel-go#1321 PiperOrigin-RevId: 924956895
1 parent 659bfb9 commit 0aad04e

2 files changed

Lines changed: 14 additions & 10 deletions

File tree

policy/src/main/java/dev/cel/policy/CelCompiledRule.java

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -48,21 +48,21 @@ public abstract class CelCompiledRule {
4848
* return an optional value if all match expressions under the rule are conditional.
4949
*/
5050
public boolean hasOptionalOutput() {
51-
boolean isOptionalOutput = false;
51+
if (matches().isEmpty()) {
52+
return false;
53+
}
5254
for (CelCompiledMatch match : matches()) {
53-
if (match.result().kind().equals(CelCompiledMatch.Result.Kind.RULE)
54-
&& match.result().rule().hasOptionalOutput()) {
55-
return true;
55+
boolean matchHasOptional = false;
56+
if (match.result().kind().equals(CelCompiledMatch.Result.Kind.RULE)) {
57+
matchHasOptional = match.result().rule().hasOptionalOutput();
5658
}
5759

58-
if (match.isConditionTriviallyTrue()) {
60+
if (match.isConditionTriviallyTrue() && !matchHasOptional) {
5961
return false;
6062
}
61-
62-
isOptionalOutput = true;
6363
}
6464

65-
return isOptionalOutput;
65+
return true;
6666
}
6767

6868
/**

policy/src/main/java/dev/cel/policy/CelPolicyCompilerImpl.java

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -249,14 +249,18 @@ private CelCompiledRule compileRuleImpl(
249249
}
250250

251251
private void checkUnreachableCode(CelCompiledRule compiledRule, CompilerContext compilerContext) {
252-
boolean ruleHasOptional = compiledRule.hasOptionalOutput();
253252
ImmutableList<CelCompiledMatch> compiledMatches = compiledRule.matches();
254253
int matchCount = compiledMatches.size();
255254
for (int i = matchCount - 1; i >= 0; i--) {
256255
CelCompiledMatch compiledMatch = compiledMatches.get(i);
257256
boolean isTriviallyTrue = compiledMatch.isConditionTriviallyTrue();
258257

259-
if (isTriviallyTrue && !ruleHasOptional && i != matchCount - 1) {
258+
boolean matchHasOptional = false;
259+
if (compiledMatch.result().kind().equals(Kind.RULE)) {
260+
matchHasOptional = compiledMatch.result().rule().hasOptionalOutput();
261+
}
262+
263+
if (isTriviallyTrue && !matchHasOptional && i != matchCount - 1) {
260264
if (compiledMatch.result().kind().equals(Kind.OUTPUT)) {
261265
compilerContext.addIssue(
262266
compiledMatch.sourceId(),

0 commit comments

Comments
 (0)