Skip to content

Commit dcb1fce

Browse files
l46kokcopybara-github
authored andcommitted
Scope policy variables globally and trust checked element types in the verifier
PiperOrigin-RevId: 1021348550
1 parent bbbe626 commit dcb1fce

7 files changed

Lines changed: 242 additions & 124 deletions

File tree

‎verifier/src/main/java/dev/cel/verifier/CelAstToZ3Translator.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,7 @@ private TranslatedValue translateIdent(CelExpr celExpr, CelAbstractSyntaxTree as
243243
}
244244
String name = ident.name();
245245
CelType type = ast.getTypeOrThrow(exprId);
246-
if (type instanceof TypeType) {
246+
if (type instanceof TypeType && !context.lookupSymbol(name).isPresent()) {
247247
TypeType typeType = (TypeType) type;
248248
if (typeType.type().kind() != CelKind.DYN) {
249249
return TranslatedValue.create(

‎verifier/src/main/java/dev/cel/verifier/CelZ3ComprehensionTranslator.java‎

Lines changed: 28 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -51,13 +51,6 @@ final class CelZ3ComprehensionTranslator {
5151
TranslatedValue translateComprehension(CelExpr celExpr, CelAbstractSyntaxTree ast) {
5252
CelComprehension comp = celExpr.comprehension();
5353
CelExpr iterRangeExpr = comp.iterRange();
54-
if (iterRangeExpr.exprKind().getKind() == ExprKind.Kind.IDENT) {
55-
iterRangeExpr =
56-
context
57-
.lookupSymbol(iterRangeExpr.ident().name())
58-
.flatMap(TranslatedValue::celExpr)
59-
.orElse(iterRangeExpr);
60-
}
6154
List<IterationElement> iterationElements = new ArrayList<>();
6255
List<BoolExpr> taints = new ArrayList<>();
6356
List<Expr<?>> allRangeElems = new ArrayList<>();
@@ -86,6 +79,7 @@ TranslatedValue translateComprehension(CelExpr celExpr, CelAbstractSyntaxTree as
8679
allRangeElems.add(key);
8780
allRangeElems.add(value);
8881
}
82+
allRangeElems.add(translateExpr(iterRangeExpr, ast).z3Expr());
8983
} else {
9084
return translateDynamicComprehension(celExpr, ast);
9185
}
@@ -182,18 +176,36 @@ private TranslatedValue translateDynamicComprehension(
182176
isMap ? (ArrayExpr) typeSystem.getMapPresence(typeSystem.getMapRef(iterRange)) : null;
183177

184178
BoolExpr isValidRange = isMap ? typeSystem.isMap(iterRange) : typeSystem.isList(iterRange);
179+
int unrollLimit = unrollLimit(comp.iterRange());
185180
BoolExpr isTruncated =
186181
context.recordUnrollLimitApproximation(
187-
ctx.mkAnd(isValidRange, ctx.mkGt(lengthExpr, ctx.mkInt(comprehensionUnrollLimit))));
182+
ctx.mkAnd(isValidRange, ctx.mkGt(lengthExpr, ctx.mkInt(unrollLimit))));
188183
context.addUnmodeledResult(isTruncated);
189184

190185
if (isAllMacro(comp) || isExistsMacro(comp)) {
191186
return unrollAllAndExists(
192-
celExpr, ast, seq, lengthExpr, mapPresence, isTruncated, iterRangeTv);
187+
celExpr, ast, seq, lengthExpr, mapPresence, isTruncated, iterRangeTv, unrollLimit);
193188
} else {
194189
return unrollMapAndFilter(
195-
celExpr, ast, seq, lengthExpr, mapPresence, isTruncated, iterRangeTv);
190+
celExpr, ast, seq, lengthExpr, mapPresence, isTruncated, iterRangeTv, unrollLimit);
191+
}
192+
}
193+
194+
/** The size of the literal bound to {@code iterRange}, else the unroll limit. */
195+
private int unrollLimit(CelExpr iterRange) {
196+
if (iterRange.exprKind().getKind() != ExprKind.Kind.IDENT) {
197+
return comprehensionUnrollLimit;
196198
}
199+
return context
200+
.lookupSymbol(iterRange.ident().name())
201+
.flatMap(TranslatedValue::celExpr)
202+
.map(e ->
203+
e.exprKind().getKind() == ExprKind.Kind.LIST
204+
? e.list().elements().size()
205+
: e.exprKind().getKind() == ExprKind.Kind.MAP
206+
? e.map().entries().size()
207+
: comprehensionUnrollLimit)
208+
.orElse(comprehensionUnrollLimit);
197209
}
198210

199211
private <T> T withIterationScope(
@@ -260,7 +272,8 @@ private TranslatedValue unrollAllAndExists(
260272
ArithExpr lengthExpr,
261273
ArrayExpr mapPresence,
262274
BoolExpr isTruncated,
263-
TranslatedValue iterRangeTv) {
275+
TranslatedValue iterRangeTv,
276+
int unrollLimit) {
264277
CelComprehension comp = celExpr.comprehension();
265278
List<BoundedIteration> iterations = new ArrayList<>();
266279
TranslatedValue accuInitTv = translateExpr(comp.accuInit(), ast);
@@ -269,7 +282,7 @@ private TranslatedValue unrollAllAndExists(
269282
boolean isMap = mapPresence != null;
270283
boolean isTwoVar = !comp.iterVar2().isEmpty();
271284

272-
for (int i = 0; i < comprehensionUnrollLimit; i++) {
285+
for (int i = 0; i < unrollLimit; i++) {
273286
IntExpr idx = ctx.mkInt(i);
274287
BoolExpr inBounds = ctx.mkLt(idx, lengthExpr);
275288
Expr<?> xVal = ctx.mkNth(seq, idx);
@@ -301,7 +314,8 @@ private TranslatedValue unrollMapAndFilter(
301314
ArithExpr lengthExpr,
302315
ArrayExpr mapPresence,
303316
BoolExpr isTruncated,
304-
TranslatedValue iterRangeTv) {
317+
TranslatedValue iterRangeTv,
318+
int unrollLimit) {
305319
CelComprehension comp = celExpr.comprehension();
306320
// For macros like map and filter, we must sequentially thread the accumulator through the loop
307321
TranslatedValue chainedAccuTv = translateExpr(comp.accuInit(), ast);
@@ -314,7 +328,7 @@ private TranslatedValue unrollMapAndFilter(
314328
taints.add(chainedAccuTv.isApproximate());
315329
taints.add(iterRangeTv.isApproximate());
316330

317-
for (int i = 0; i < comprehensionUnrollLimit; i++) {
331+
for (int i = 0; i < unrollLimit; i++) {
318332
IntExpr idx = ctx.mkInt(i);
319333
BoolExpr inBounds = ctx.mkLt(idx, lengthExpr);
320334
Expr<?> xVal = ctx.mkNth(seq, idx);

‎verifier/src/main/java/dev/cel/verifier/CelZ3OperatorTranslator.java‎

Lines changed: 40 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
import static com.google.common.collect.ImmutableList.toImmutableList;
1818

1919
import com.google.common.collect.ImmutableList;
20+
import com.google.common.collect.ImmutableSet;
21+
import com.google.common.collect.Lists;
2022
import com.microsoft.z3.ArithExpr;
2123
import com.microsoft.z3.ArrayExpr;
2224
import com.microsoft.z3.BoolExpr;
@@ -55,6 +57,9 @@ final class CelZ3OperatorTranslator {
5557
private static final String FUNC_APPROX_EQ = "!approxEq";
5658
private static final String FUNC_APPROX_IN = "!approxIn";
5759
private static final MapType DYN_MAP = MapType.create(SimpleType.DYN, SimpleType.DYN);
60+
// Runtimes evaluate the alternative of `or` and `orValue` only when the receiver is empty.
61+
private static final ImmutableSet<String> RECEIVER_STRICT_OVERLOADS =
62+
ImmutableSet.of("optional_or_optional", "optional_orValue_value");
5863

5964
private final Context ctx;
6065
private final CelZ3TypeSystem typeSystem;
@@ -70,15 +75,21 @@ Optional<TranslatedValue> translateFunctionCall(
7075
args.stream().map(TranslatedValue::z3Expr).collect(toImmutableList());
7176
ImmutableList<BoolExpr> argApproximations =
7277
args.stream().map(TranslatedValue::isApproximate).collect(toImmutableList());
78+
CelReference reference = ast.getReferenceMap().get(exprId);
79+
List<TranslatedValue> strictArgs =
80+
reference != null
81+
&& !reference.overloadIds().isEmpty()
82+
&& RECEIVER_STRICT_OVERLOADS.containsAll(reference.overloadIds())
83+
? args.subList(0, 1)
84+
: args;
7385

7486
TranslatedValue resultChain =
7587
opOpt
7688
.map(op -> translateOperatorCall(op, args, ast))
7789
.orElseGet(() ->
7890
TranslatedValue.propagateStrict(
79-
ctx, typeSystem, functionName, typeSystem.mkError(), args));
91+
ctx, typeSystem, functionName, typeSystem.mkError(), strictArgs));
8092

81-
CelReference reference = ast.getReferenceMap().get(exprId);
8293
CelFunctionDecl decl = functionRegistry.getDeclaration(functionName).orElse(null);
8394

8495
if (decl == null) {
@@ -127,7 +138,7 @@ Optional<TranslatedValue> translateFunctionCall(
127138

128139
matchedAny = true;
129140
List<BoolExpr> typeGuards = new ArrayList<>();
130-
for (int i = 0; i < z3Args.size(); i++) {
141+
for (int i = 0; i < strictArgs.size(); i++) {
131142
typeGuards.add(mkTypeGuard(z3Args.get(i), overload.parameterTypes().get(i)));
132143
}
133144

@@ -180,7 +191,11 @@ Optional<TranslatedValue> translateFunctionCall(
180191

181192
return Optional.of(
182193
TranslatedValue.create(
183-
typeSystem.propagateErrorAndUnknown(functionName, currentZ3Result, z3Args, z3Args),
194+
typeSystem.propagateErrorAndUnknown(
195+
functionName,
196+
currentZ3Result,
197+
Lists.transform(strictArgs, TranslatedValue::z3Expr),
198+
z3Args),
184199
typeSystem,
185200
currentApprox));
186201
}
@@ -864,9 +879,6 @@ private BoolExpr listMembership(
864879
// Whether lhs may equal an element of elemType: a number only across numeric types, and a list
865880
// only another list (anything else conservatively).
866881
private BoolExpr mayEqualElement(Expr<?> lhs, CelType elemType) {
867-
if (elemType instanceof NullableType) {
868-
return ctx.mkTrue();
869-
}
870882
if (isNumericType(elemType)) {
871883
return isNumeric(lhs);
872884
}
@@ -989,8 +1001,6 @@ private TranslatedValue translateEquality(
9891001
structuralEq = (BoolExpr) ctx.mkITE(bothMaps, mapEquality, structuralEq);
9901002
} else if (!isStaticallyKnown(type0) && !isStaticallyKnown(type1)) {
9911003
// Performance only: a side with a known type isn't a list or map here.
992-
// TODO: Unless the type checker narrowed it, e.g. `(int_list +
993-
// dyn_var)[0]`.
9941004
structuralEq =
9951005
approximateEqualityWhere(
9961006
context.recordApproximation(
@@ -1027,13 +1037,11 @@ private static final class IndexAccess {
10271037
private final BoolExpr valid;
10281038
private final BoolExpr found;
10291039
private final Expr<?> value;
1030-
private final BoolExpr isApproximate;
10311040

1032-
private IndexAccess(BoolExpr valid, BoolExpr found, Expr<?> value, BoolExpr isApproximate) {
1041+
private IndexAccess(BoolExpr valid, BoolExpr found, Expr<?> value) {
10331042
this.valid = valid;
10341043
this.found = found;
10351044
this.value = value;
1036-
this.isApproximate = isApproximate;
10371045
}
10381046
}
10391047

@@ -1043,54 +1051,40 @@ private IndexAccess listAccess(Expr<?> lhsTrans, Expr<?> rhsTrans) {
10431051
return new IndexAccess(
10441052
ctx.mkAnd(typeSystem.isList(lhsTrans), typeSystem.isInt(rhsTrans)),
10451053
ctx.mkAnd(ctx.mkGe(index, ctx.mkInt(0)), ctx.mkLt(index, ctx.mkLength(seq))),
1046-
ctx.mkNth(seq, index),
1047-
/* isApproximate= */ ctx.mkFalse());
1054+
ctx.mkNth(seq, index));
10481055
}
10491056

10501057
private IndexAccess mapAccess(Expr<?> lhsTrans, Expr<?> rhsTrans) {
10511058
ImmutableList<CelZ3TypeSystem.EqualKey> equalKeys = typeSystem.equalKeys(rhsTrans);
10521059
return new IndexAccess(
10531060
typeSystem.isMap(lhsTrans),
10541061
typeSystem.hasEqualKey(lhsTrans, equalKeys),
1055-
typeSystem.valueAtEqualKey(lhsTrans, equalKeys),
1056-
/* isApproximate= */ ctx.mkFalse());
1062+
typeSystem.valueAtEqualKey(lhsTrans, equalKeys));
10571063
}
10581064

10591065
/**
1060-
* Looks up {@code rhsTrans} in the list or map {@code lhsTrans}. The value is approximate if the
1061-
* static element type isn't guaranteed and it may not conform.
1066+
* Looks up {@code rhsTrans} in the list or map {@code lhsTrans} of type {@code containerType}.
10621067
*/
1063-
private IndexAccess indexAccess(
1064-
Expr<?> lhsTrans, Expr<?> rhsTrans, CelType containerType, boolean isLhsTypeGuaranteed) {
1068+
private IndexAccess indexAccess(Expr<?> lhsTrans, Expr<?> rhsTrans, CelType containerType) {
10651069
IndexAccess list = listAccess(lhsTrans, rhsTrans);
10661070
IndexAccess map = mapAccess(lhsTrans, rhsTrans);
10671071
IndexAccess access =
10681072
new IndexAccess(
10691073
ctx.mkOr(list.valid, map.valid),
10701074
(BoolExpr) ctx.mkITE(list.valid, list.found, map.found),
1071-
ctx.mkITE(list.valid, list.value, map.value),
1072-
/* isApproximate= */ ctx.mkFalse());
1075+
ctx.mkITE(list.valid, list.value, map.value));
10731076
BoolExpr isRead = ctx.mkAnd(access.valid, access.found);
10741077
context.constrainValidValue(isRead, access.value);
1075-
if (containerType.kind() != CelKind.MAP && containerType.kind() != CelKind.LIST) {
1076-
return access;
1077-
}
1078-
CelType elemType =
1079-
containerType.kind() == CelKind.MAP
1080-
? ((MapType) containerType).valueType()
1081-
: ((ListType) containerType).elemType();
1082-
BoolExpr conforms = typeConstraintGenerator.createTypeConstraintForType(access.value, elemType);
1083-
if (isLhsTypeGuaranteed) {
1084-
context.addConstraint(ctx.mkImplies(isRead, conforms));
1085-
return access;
1078+
if (containerType instanceof MapType || containerType instanceof ListType) {
1079+
CelType elemType =
1080+
containerType instanceof MapType
1081+
? ((MapType) containerType).valueType()
1082+
: ((ListType) containerType).elemType();
1083+
context.addConstraint(
1084+
ctx.mkImplies(
1085+
isRead, typeConstraintGenerator.createTypeConstraintForType(access.value, elemType)));
10861086
}
1087-
// The type checker may narrow other static types (e.g. `(['a'] + dyn_var)[1]` is typed
1088-
// string), so the element may not conform.
1089-
return new IndexAccess(
1090-
access.valid,
1091-
access.found,
1092-
access.value,
1093-
CelZ3Exprs.mkAndFlattened(ctx, isRead, CelZ3Exprs.mkNotFlattened(ctx, conforms)));
1087+
return access;
10941088
}
10951089

10961090
/**
@@ -1102,7 +1096,6 @@ private TranslatedValue translateIndex(
11021096
TranslatedValue lhs = args.get(0);
11031097
TranslatedValue rhs = args.get(1);
11041098
CelType lhsType = extractAstTypeOrDefault(lhs, ast);
1105-
boolean isLhsTypeGuaranteed = lhsType.equals(guaranteedType(lhs, ast));
11061099
CelType containerType = lhsType instanceof OptionalType ? lhsType.parameters().get(0) : lhsType;
11071100

11081101
Expr<?> lhsTrans = lhs.z3Expr();
@@ -1112,7 +1105,7 @@ private TranslatedValue translateIndex(
11121105
BoolExpr lhsHasValue = typeSystem.optHasValue(optRef);
11131106
lhsTrans = ctx.mkITE(isOptionalLhs, typeSystem.getOptionalValue(optRef), lhsTrans);
11141107
// An empty optional's value can't be read, so constraining it is harmless.
1115-
IndexAccess access = indexAccess(lhsTrans, rhsTrans, containerType, isLhsTypeGuaranteed);
1108+
IndexAccess access = indexAccess(lhsTrans, rhsTrans, containerType);
11161109
Expr<?> element =
11171110
ctx.mkITE(ctx.mkAnd(access.valid, access.found), access.value, typeSystem.mkError());
11181111
Expr<?> optionalElement =
@@ -1139,8 +1132,7 @@ private TranslatedValue translateIndex(
11391132
BoolExpr isMapIndexTruncated = context.isTruncatedMap(lhsTrans);
11401133
return TranslatedValue.propagateStrict(ctx, typeSystem, op.getFunction(), actualValue, args)
11411134
.withApproximation(
1142-
CelZ3Exprs.mkOrFlattened(
1143-
ctx, isListIndexTruncated, isMapIndexTruncated, access.isApproximate));
1135+
CelZ3Exprs.mkOrFlattened(ctx, isListIndexTruncated, isMapIndexTruncated));
11441136
}
11451137

11461138
private TranslatedValue translateConditional(
@@ -1197,12 +1189,7 @@ private static CelType extractAstTypeOrDefault(TranslatedValue val, CelAbstractS
11971189
return val.celExpr().map(node -> ast.getTypeOrThrow(node.id())).orElse(SimpleType.DYN);
11981190
}
11991191

1200-
/**
1201-
* Returns the type that {@code val} is guaranteed to conform to at runtime: a constant's, the
1202-
* declared type of an input variable, or else dyn. Global constraints may only be derived from
1203-
* guaranteed types: the type checker may narrow static types (e.g. {@code ['a'] + dyn_var} is
1204-
* typed list(string)), so constraints derived from those could exclude valid inputs.
1205-
*/
1192+
/** Returns a constant's type, or an input variable's declared type, or else dyn. */
12061193
private CelType guaranteedType(TranslatedValue val, CelAbstractSyntaxTree ast) {
12071194
return val.isLiteral(ExprKind.Kind.CONSTANT)
12081195
? extractAstTypeOrDefault(val, ast)
@@ -1254,9 +1241,11 @@ private static boolean hasStructuralEquality(CelType type) {
12541241
}
12551242
}
12561243

1244+
/** Excludes wrappers, whose kind is their value's but which may also be null. */
12571245
private static boolean isNumericType(CelType type) {
12581246
CelKind kind = type.kind();
1259-
return kind == CelKind.INT || kind == CelKind.UINT || kind == CelKind.DOUBLE;
1247+
return !(type instanceof NullableType)
1248+
&& (kind == CelKind.INT || kind == CelKind.UINT || kind == CelKind.DOUBLE);
12601249
}
12611250

12621251
/**

‎verifier/src/main/java/dev/cel/verifier/CelZ3TranslationContext.java‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -178,20 +178,24 @@ BoolExpr hasUnmodeledResult() {
178178
}
179179

180180
void bindSymbol(String name, TranslatedValue value) {
181-
localScope.put(name, value);
181+
symbolTable.put(name, value);
182182
}
183183

184184
Optional<TranslatedValue> lookupSymbol(String name) {
185-
return Optional.ofNullable(localScope.get(name));
185+
TranslatedValue local = localScope.get(name);
186+
return Optional.ofNullable(local != null ? local : symbolTable.get(globalName(name)));
186187
}
187188

188189
TranslatedValue computeSymbolIfAbsent(
189190
String rawName, Function<String, TranslatedValue> mappingFunction) {
190-
if (!rawName.startsWith(".") && localScope.containsKey(rawName)) {
191+
if (localScope.containsKey(rawName)) {
191192
return localScope.get(rawName);
192193
}
193-
return symbolTable.computeIfAbsent(
194-
rawName.startsWith(".") ? rawName.substring(1) : rawName, mappingFunction);
194+
return symbolTable.computeIfAbsent(globalName(rawName), mappingFunction);
195+
}
196+
197+
private static String globalName(String name) {
198+
return name.startsWith(".") ? name.substring(1) : name;
195199
}
196200

197201
/** Binds {@code varName} to {@code value} while running {@code action}, then restores it. */

0 commit comments

Comments
 (0)