diff --git a/verifier/src/main/java/dev/cel/verifier/BUILD.bazel b/verifier/src/main/java/dev/cel/verifier/BUILD.bazel index 4554cca1f..4add4e84f 100644 --- a/verifier/src/main/java/dev/cel/verifier/BUILD.bazel +++ b/verifier/src/main/java/dev/cel/verifier/BUILD.bazel @@ -163,14 +163,20 @@ java_library( "CelVerifierZ3Impl.java", "CelZ3ComprehensionTranslator.java", "CelZ3CounterexampleGenerator.java", + "CelZ3Equality.java", "CelZ3ExtensionalityAxioms.java", "CelZ3FunctionRegistry.java", "CelZ3OperatorTranslator.java", "CelZ3StructTranslator.java", "CelZ3TranslationContext.java", "CelZ3TypeConstraintGenerator.java", + "ListValueModel.java", + "MapValueModel.java", + "NumericValueModel.java", + "OptionalValueModel.java", "RuntimeOracle.java", "TranslatedValue.java", + "ValueModel.java", ], compatible_with = [], tags = [ @@ -193,6 +199,7 @@ java_library( "//common/internal:proto_time_utils", "//common/types", "//common/types:cel_types", + "//common/types:default_type_provider", "//common/types:type_providers", "//common/values", "//common/values:cel_byte_string", diff --git a/verifier/src/main/java/dev/cel/verifier/CelAstToZ3Translator.java b/verifier/src/main/java/dev/cel/verifier/CelAstToZ3Translator.java index 7fec67e94..e9e82f585 100644 --- a/verifier/src/main/java/dev/cel/verifier/CelAstToZ3Translator.java +++ b/verifier/src/main/java/dev/cel/verifier/CelAstToZ3Translator.java @@ -15,6 +15,7 @@ package dev.cel.verifier; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; @@ -39,6 +40,9 @@ import dev.cel.common.types.CelKind; import dev.cel.common.types.CelType; import dev.cel.common.types.CelTypeProvider; +import dev.cel.common.types.CelTypes; +import dev.cel.common.types.DefaultTypeProvider; +import dev.cel.common.types.StructType; import dev.cel.common.types.TypeType; import java.util.ArrayList; import java.util.Arrays; @@ -49,6 +53,7 @@ import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.stream.Stream; /** * Internal translator from CEL AST to Z3 SMT expressions using a 4-valued logic tagged union. @@ -139,11 +144,16 @@ TranslatedValue translate(CelAbstractSyntaxTree ast) { CelZ3ExtensionalityAxioms.generateAxioms(ctx, typeSystem, listRefs, mapRefs, msgRefs) .forEach(context::addConstraint); - // A present optional holds a CEL value, even when the optional is held by a dyn. + // A present optional holds a CEL value, even when the optional is held by a dyn, and is the + // optional of that value. for (Expr ref : optRefs) { - context.constrainValidValue( - ctx.mkAnd(typeSystem.isOptional(ref.getArgs()[0]), typeSystem.optHasValue(ref)), - typeSystem.getOptionalValue(ref)); + BoolExpr isPresent = + ctx.mkAnd(typeSystem.isOptional(ref.getArgs()[0]), typeSystem.optHasValue(ref)); + Expr value = typeSystem.getOptionalValue(ref); + context.constrainValidValue(isPresent, value); + context.addConstraint( + ctx.mkImplies( + isPresent, ctx.mkEq(ctx.mkApp(typeSystem.optionalOfRefFunc(), value), ref))); } return result; @@ -250,12 +260,21 @@ private TranslatedValue translateIdent(CelExpr celExpr, CelAbstractSyntaxTree as // Nothing binds `n`, so if it's typed type(T), it names T (e.g. `int`). if (type instanceof TypeType) { TypeType typeType = (TypeType) type; - if (typeType.type().kind() != CelKind.DYN) { + if (typeType.type().kind() != CelKind.DYN || n.equals("type")) { return TranslatedValue.create( - typeSystem.mkString(typeType.containingTypeName()), + typeSystem.mkType(typeType.containingTypeName()), typeSystem, /* isApproximate= */ ctx.mkFalse()); } + // `dyn` and variables holding a type check as type(dyn). + if (n.equals("dyn")) { + // The spec says `dyn` has no value at runtime. + return TranslatedValue.create( + ctx.mkConst("!dyn", typeSystem.celValueSort()), + typeSystem, + context.recordApproximation( + "the `dyn` type as a value", /* condition= */ ctx.mkTrue())); + } } Expr v = ctx.mkConst(n, typeSystem.celValueSort()); context.addInputVariable(v, type); @@ -524,7 +543,7 @@ private static String uninterpretedFunctionSymbol(long exprId, CelAbstractSyntax */ private static boolean mayEmbedArgs(String functionName, CelType resultType) { return (!CelZ3OperatorTranslator.isStaticallyKnown(resultType) - || !resultType.parameters().isEmpty()) + || (!resultType.parameters().isEmpty() && resultType.kind() != CelKind.TYPE)) && !functionName.equals(Operator.INDEX.getFunction()) && !functionName.equals(Operator.CONDITIONAL.getFunction()); } @@ -537,7 +556,17 @@ private static boolean mayEmbedArgs(String functionName, CelType resultType) { CelTypeProvider typeProvider, boolean parameterizeUnknowns) { this.ctx = ctx; - this.typeSystem = new CelZ3TypeSystem(ctx, parameterizeUnknowns); + this.typeSystem = + new CelZ3TypeSystem( + ctx, + parameterizeUnknowns, + Stream.concat( + DefaultTypeProvider.getInstance().types().stream(), + typeProvider.types().stream() + .filter( + t -> t instanceof StructType && !CelTypes.isWellKnownType(t.name()))) + .map(CelType::name) + .collect(toImmutableSet())); this.context = new CelZ3TranslationContext(ctx, typeSystem, comprehensionUnrollLimit); this.typeConstraintGenerator = context.typeConstraintGenerator(); this.operatorTranslator = new CelZ3OperatorTranslator(context, functionRegistry); diff --git a/verifier/src/main/java/dev/cel/verifier/CelVerifierZ3Impl.java b/verifier/src/main/java/dev/cel/verifier/CelVerifierZ3Impl.java index faf154b2a..e520bbe4b 100644 --- a/verifier/src/main/java/dev/cel/verifier/CelVerifierZ3Impl.java +++ b/verifier/src/main/java/dev/cel/verifier/CelVerifierZ3Impl.java @@ -38,6 +38,7 @@ import dev.cel.verifier.axioms.CelZ3FunctionAxiom; import dev.cel.verifier.axioms.CelZ3StandardAxioms; import java.time.Duration; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; @@ -436,19 +437,31 @@ private static Status checkSat(Solver solver, CelZ3TypeSystem typeSystem, BoolEx solver.push(); solver.add(assertions); Status status = solver.check(); - // Each round defines at least one more double, so this terminates. Each round gets the full - // timeout; the rounds are bounded by the doubles in int/double comparisons. + List preferences = new ArrayList<>(); + // Each round defines at least one more double or prefers one more type value's name, so this + // terminates. Each round gets the full timeout; the rounds are bounded by the doubles in + // int/double comparisons and the values that may be types. while (status == Status.SATISFIABLE) { - ImmutableList definitions = - typeSystem.defineDoublesContradictedBy(solver.getModel()); + Model model = solver.getModel(); + ImmutableList definitions = typeSystem.defineDoublesContradictedBy(model); if (definitions.isEmpty()) { - break; + ImmutableList moreKnownNames = typeSystem.preferKnownTypeNamesOver(model); + if (moreKnownNames.isEmpty()) { + break; + } + preferences.addAll(moreKnownNames); + } else { + solver.pop(); + solver.add(definitions.toArray(new BoolExpr[0])); + solver.push(); + solver.add(assertions); + } + status = solver.check(preferences.toArray(new BoolExpr[0])); + if (status != Status.SATISFIABLE && !preferences.isEmpty()) { + // No model avoids the unknown names, so they may well be real. + preferences.clear(); + status = solver.check(); } - solver.pop(); - solver.add(definitions.toArray(new BoolExpr[0])); - solver.push(); - solver.add(assertions); - status = solver.check(); } if (status == Status.UNSATISFIABLE) { solver.pop(); diff --git a/verifier/src/main/java/dev/cel/verifier/CelZ3CounterexampleGenerator.java b/verifier/src/main/java/dev/cel/verifier/CelZ3CounterexampleGenerator.java index 94bcef460..f9e2e10b7 100644 --- a/verifier/src/main/java/dev/cel/verifier/CelZ3CounterexampleGenerator.java +++ b/verifier/src/main/java/dev/cel/verifier/CelZ3CounterexampleGenerator.java @@ -16,6 +16,7 @@ import static java.nio.charset.StandardCharsets.UTF_8; +import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.primitives.UnsignedLong; @@ -30,6 +31,7 @@ import dev.cel.common.internal.ProtoTimeUtils; import dev.cel.common.values.CelByteString; import dev.cel.common.values.NullValue; +import dev.cel.runtime.CelAttribute; import java.math.BigInteger; import java.time.Duration; import java.time.Instant; @@ -126,6 +128,12 @@ private Value extractValue(Expr expr) { return extractString(args[0], /* isBytes= */ false); } else if (decl.equals(typeSystem.bytesCons().ConstructorDecl())) { return extractString(args[0], /* isBytes= */ true); + } else if (decl.equals(typeSystem.typeCons().ConstructorDecl())) { + String name = args[0].getString(); + return Value.inexact( + Splitter.on('.').splitToStream(name).allMatch(CelAttribute.Qualifier::isLegalIdentifier) + ? name + : ""); } else if (decl.equals(typeSystem.timestampCons().ConstructorDecl())) { BigInteger nanos = ((IntNum) args[0]).getBigInteger(); BigInteger nanoAdjustment = nanos.mod(NANOS_PER_SECOND); diff --git a/verifier/src/main/java/dev/cel/verifier/CelZ3Equality.java b/verifier/src/main/java/dev/cel/verifier/CelZ3Equality.java new file mode 100644 index 000000000..893012ad7 --- /dev/null +++ b/verifier/src/main/java/dev/cel/verifier/CelZ3Equality.java @@ -0,0 +1,298 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package dev.cel.verifier; + +import com.google.common.collect.ImmutableList; +import com.microsoft.z3.BoolExpr; +import com.microsoft.z3.Context; +import com.microsoft.z3.Expr; +import com.microsoft.z3.FuncDecl; +import com.microsoft.z3.IntExpr; +import com.microsoft.z3.SeqExpr; +import com.microsoft.z3.Sort; +import dev.cel.common.CelAbstractSyntaxTree; +import dev.cel.common.Operator; +import dev.cel.common.types.CelType; +import dev.cel.common.types.ListType; +import dev.cel.common.types.SimpleType; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.stream.Stream; + +/** CEL equality, dispatched to the {@link ValueModel} of each kind of value compared. */ +final class CelZ3Equality { + private static final String FUNC_APPROX_EQ = "!approxEq"; + private static final String FUNC_APPROX_IN = "!approxIn"; + + private final Context ctx; + private final CelZ3TypeSystem typeSystem; + private final CelZ3TranslationContext context; + private final int comprehensionUnrollLimit; + private final NumericValueModel numericModel; + private final ListValueModel listModel; + // Kinds compared by more than their terms, in order of precedence. + private final ImmutableList containers; + + /** + * CEL equality. Values read out of lists and maps that aren't literals ({@code shallow}) compare + * numbers numerically, but ints and doubles approximately, and lists, maps, messages and + * optionals approximately (performance only). + */ + TranslatedValue translate( + TranslatedValue arg0, + TranslatedValue arg1, + CelAbstractSyntaxTree ast, + boolean isEquals, + boolean shallow) { + Expr z3Arg0 = arg0.z3Expr(); + Expr z3Arg1 = arg1.z3Expr(); + CelType type0 = arg0.staticType(ast); + CelType type1 = arg1.staticType(ast); + + BoolExpr equality; + List taints = new ArrayList<>(); + if (!shallow) { + taints.add(mayObserveTruncatedTypeConstraint(ast, arg0, arg1)); + } + + if (numericModel.hasKind(type0) && numericModel.hasKind(type1)) { + equality = numericModel.equal(arg0, arg1, ast, taints, this); + } else { + BoolExpr structuralEq; + if (shallow) { + structuralEq = + approximateEqualityWhere( + context.recordApproximation( + "comparisons of lists, maps, messages or optionals read out of lists and maps", + bothContainers( + z3Arg0, + z3Arg1, + ctx.mkAnd(typeSystem.isMessage(z3Arg0), typeSystem.isMessage(z3Arg1)))), + z3Arg0, + z3Arg1, + /* exact= */ ctx.mkEq(z3Arg0, z3Arg1), + taints); + } else { + // Lists, maps and optionals compare by CEL equality, unless their guaranteed types make it + // their terms'. + structuralEq = typeSystem.getStructuralEquality(z3Arg0, z3Arg1); + if (!isExact(context.guaranteedType(arg0, ast), context.guaranteedType(arg1, ast))) { + Optional model = + containers.stream().filter(m -> m.hasKind(type0) || m.hasKind(type1)).findFirst(); + if (model.isPresent()) { + structuralEq = + (BoolExpr) + ctx.mkITE( + both(model.get(), z3Arg0, z3Arg1), + model.get().equal(arg0, arg1, ast, taints, this), + structuralEq); + } else if (!CelZ3OperatorTranslator.isStaticallyKnown(type0) + && !CelZ3OperatorTranslator.isStaticallyKnown(type1)) { + // Performance only: a side with a known type isn't a list, map or optional here. + structuralEq = + approximateEqualityWhere( + context.recordApproximation( + "comparisons of lists, maps or optionals typed dyn", + bothContainers(z3Arg0, z3Arg1)), + z3Arg0, + z3Arg1, + structuralEq, + taints); + } + } + } + equality = + (BoolExpr) + ctx.mkITE( + both(numericModel, z3Arg0, z3Arg1), + numericModel.equal( + arg0, arg1, ast, taints, this, /* approximateIntDouble= */ shallow), + structuralEq); + } + + return TranslatedValue.propagateStrict( + ctx, + typeSystem, + isEquals ? Operator.EQUALS.getFunction() : Operator.NOT_EQUALS.getFunction(), + typeSystem.wrapBool(isEquals ? equality : ctx.mkNot(equality)), + arg0, + arg1) + .withApproximation(CelZ3Exprs.mkOrFlattened(ctx, taints)); + } + + /** + * {@code in} on a list compares each element with lhs by CEL equality, unrolled over a literal's + * elements or else up to the unroll limit, past which a match is approximate. + */ + BoolExpr listMembership( + TranslatedValue lhs, TranslatedValue list, CelAbstractSyntaxTree ast, List taints) { + boolean isLiteral = ListValueModel.isFixedLengthListLiteral(list); + boolean shallow = + !isLiteral && !lhs.celExpr().map(TranslatedValue::isContainerLiteral).orElse(false); + SeqExpr seq = typeSystem.getSeq(typeSystem.getListRef(list.z3Expr())); + IntExpr length = ctx.mkLength(seq); + List matches = new ArrayList<>(); + int size = isLiteral ? list.celExpr().get().list().elements().size() : comprehensionUnrollLimit; + for (int i = 0; i < size; i++) { + BoolExpr inBounds = ctx.mkLt(ctx.mkInt(i), length); + // The runtime compares each element with lhs, in that order. + TranslatedValue equality = + translate( + listModel.element(list, seq, i, isLiteral, ast), + lhs, + ast, + /* isEquals= */ true, + shallow); + matches.add(ctx.mkAnd(inBounds, typeSystem.isTrue(equality.z3Expr()))); + taints.add(ctx.mkAnd(inBounds, equality.isApproximate())); + } + BoolExpr found = CelZ3Exprs.mkOrFlattened(ctx, matches); + if (isLiteral) { + return found; + } + CelType listType = context.guaranteedType(list, ast); + CelType elemType = + listType instanceof ListType ? ((ListType) listType).elemType() : SimpleType.DYN; + return approximateWhere( + context.recordUnrollLimitApproximation( + CelZ3Exprs.mkAndFlattened( + ctx, + ctx.mkGt(length, ctx.mkInt(comprehensionUnrollLimit)), + ctx.mkNot(found), + mayEqualElement(lhs.z3Expr(), elemType))), + uninterpreted(FUNC_APPROX_IN, lhs.z3Expr(), list.z3Expr()), + found, + taints); + } + + // Whether lhs may equal an element of elemType: a number only across numeric types, and a list + // only another list (anything else conservatively). + private BoolExpr mayEqualElement(Expr lhs, CelType elemType) { + if (numericModel.hasKind(elemType)) { + return numericModel.is(lhs); + } + return listModel.hasKind(elemType) ? listModel.is(lhs) : ctx.mkTrue(); + } + + private BoolExpr both(ValueModel model, Expr z3Expr0, Expr z3Expr1) { + return ctx.mkAnd(model.is(z3Expr0), model.is(z3Expr1)); + } + + // A flat disjunction, so that no recorded approximation is a subterm of another. + private BoolExpr bothContainers(Expr z3Expr0, Expr z3Expr1, BoolExpr... others) { + return ctx.mkOr( + Stream.concat( + containers.stream().map(m -> both(m, z3Expr0, z3Expr1)), Arrays.stream(others)) + .toArray(BoolExpr[]::new)); + } + + // Where the recorded approximation holds, the verifier doesn't model the result, so it's the + // given uninterpreted relation there. + private BoolExpr approximateWhere( + BoolExpr approximation, BoolExpr relation, BoolExpr exact, List taints) { + taints.add(approximation); + return (BoolExpr) ctx.mkITE(approximation, relation, exact); + } + + private BoolExpr uninterpreted(String name, Expr z3Expr0, Expr z3Expr1) { + Sort sort = typeSystem.celValueSort(); + FuncDecl relation = + typeSystem.internFuncDecl(name, new Sort[] {sort, sort}, ctx.getBoolSort()); + return (BoolExpr) ctx.mkApp(relation, z3Expr0, z3Expr1); + } + + /** Like approximateWhere, for CEL equality, which is symmetric. */ + BoolExpr approximateEqualityWhere( + BoolExpr approximation, + Expr z3Expr0, + Expr z3Expr1, + BoolExpr exact, + List taints) { + // Ordered by term id (in either direction) so that x == y and y == x share one application. + // Asserting both orders instead doubles the applications, which made nested comparisons slow. + boolean swap = z3Expr0.getId() > z3Expr1.getId(); + BoolExpr relation = + uninterpreted(FUNC_APPROX_EQ, swap ? z3Expr1 : z3Expr0, swap ? z3Expr0 : z3Expr1); + return approximateWhere(approximation, relation, exact, taints); + } + + /** Lists and maps compared up to the unroll limit may differ past it. */ + BoolExpr approximatePastUnrollLimit( + IntExpr length, Expr z3Expr0, Expr z3Expr1, List taints) { + return approximateEqualityWhere( + context.recordUnrollLimitApproximation( + ctx.mkGt(length, ctx.mkInt(comprehensionUnrollLimit))), + z3Expr0, + z3Expr1, + /* exact= */ ctx.mkTrue(), + taints); + } + + /** + * Whether observing {@code a} and {@code b} together may expose a value beyond a truncated type + * constraint in either. Type constraints at the point of observation rule this out only if both + * have a concrete static type (unlike e.g. {@code dyn(int_list)}). + */ + BoolExpr mayObserveTruncatedTypeConstraint( + CelAbstractSyntaxTree ast, TranslatedValue a, TranslatedValue b) { + if (CelZ3OperatorTranslator.isConcrete(a.staticType(ast)) + && CelZ3OperatorTranslator.isConcrete(b.staticType(ast))) { + return ctx.mkFalse(); + } + return context.recordUnrollLimitApproximation( + CelZ3Exprs.mkOrFlattened( + ctx, + typeSystem.hasTruncatedTypeConstraint(a.z3Expr()), + typeSystem.hasTruncatedTypeConstraint(b.z3Expr()))); + } + + /** Whether values of these types are equal exactly when their terms are. */ + static boolean isExact(CelType type0, CelType type1) { + return type0.equals(type1) && hasStructuralEquality(type0); + } + + private static boolean hasStructuralEquality(CelType type) { + switch (type.kind()) { + case BOOL: + case INT: + case UINT: + case STRING: + case BYTES: + case TIMESTAMP: + case DURATION: + case TYPE: + return true; + case LIST: + case MAP: + return type.parameters().stream().allMatch(CelZ3Equality::hasStructuralEquality); + default: + // Doubles (NaN, -0.0), dyn, messages and the rest compare by CEL equality. + return false; + } + } + + CelZ3Equality(CelZ3TranslationContext context) { + this.ctx = context.ctx(); + this.typeSystem = context.typeSystem(); + this.context = context; + this.comprehensionUnrollLimit = context.comprehensionUnrollLimit(); + this.numericModel = new NumericValueModel(context); + this.listModel = new ListValueModel(context); + this.containers = + ImmutableList.of(listModel, new MapValueModel(context), new OptionalValueModel(context)); + } +} diff --git a/verifier/src/main/java/dev/cel/verifier/CelZ3OperatorTranslator.java b/verifier/src/main/java/dev/cel/verifier/CelZ3OperatorTranslator.java index 6f1e17e43..d932b5e10 100644 --- a/verifier/src/main/java/dev/cel/verifier/CelZ3OperatorTranslator.java +++ b/verifier/src/main/java/dev/cel/verifier/CelZ3OperatorTranslator.java @@ -22,46 +22,35 @@ import com.microsoft.z3.BoolExpr; import com.microsoft.z3.Context; import com.microsoft.z3.Expr; -import com.microsoft.z3.FPExpr; -import com.microsoft.z3.FuncDecl; import com.microsoft.z3.IntExpr; import com.microsoft.z3.SeqExpr; -import com.microsoft.z3.Sort; import dev.cel.common.CelAbstractSyntaxTree; import dev.cel.common.CelFunctionDecl; import dev.cel.common.CelOverloadDecl; import dev.cel.common.Operator; -import dev.cel.common.ast.CelConstant; -import dev.cel.common.ast.CelExpr; -import dev.cel.common.ast.CelExpr.ExprKind; import dev.cel.common.ast.CelReference; import dev.cel.common.types.CelKind; import dev.cel.common.types.CelType; import dev.cel.common.types.ListType; import dev.cel.common.types.MapType; -import dev.cel.common.types.NullableType; import dev.cel.common.types.OptionalType; import dev.cel.common.types.SimpleType; import dev.cel.verifier.axioms.CelZ3OverloadResult; import dev.cel.verifier.axioms.CelZ3OverloadTranslator; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.Optional; /** Handles mapping CEL Operators to Z3 SMT logic. */ @SuppressWarnings({"unchecked", "rawtypes"}) // Z3 Java API uses raw types. final class CelZ3OperatorTranslator { - private static final String FUNC_APPROX_EQ = "!approxEq"; - private static final String FUNC_APPROX_IN = "!approxIn"; - private static final MapType DYN_MAP = MapType.create(SimpleType.DYN, SimpleType.DYN); - private final Context ctx; private final CelZ3TypeSystem typeSystem; private final CelZ3TranslationContext context; private final CelZ3TypeConstraintGenerator typeConstraintGenerator; private final CelZ3FunctionRegistry functionRegistry; private final int comprehensionUnrollLimit; + private final CelZ3Equality equality; Optional translateFunctionCall( String functionName, List args, long exprId, CelAbstractSyntaxTree ast) { @@ -161,7 +150,8 @@ Optional translateFunctionCall( currentApprox = CelZ3Exprs.mkOrFlattened(ctx, currentApprox, constrainInWitnessTypes(lhs, list, ast)); BoolExpr isList = typeSystem.isList(list.z3Expr()); - if (isExact(ListType.create(guaranteedType(lhs, ast)), guaranteedType(list, ast))) { + if (CelZ3Equality.isExact( + ListType.create(context.guaranteedType(lhs, ast)), context.guaranteedType(list, ast))) { // IN_LIST matched by terms, but a miss may be past the unroll limit, where elements aren't // constrained to the element type (e.g. `!(false in bool_list)` with a 6th element of 1). ArithExpr length = ctx.mkLength(typeSystem.getSeq(typeSystem.getListRef(list.z3Expr()))); @@ -175,10 +165,10 @@ Optional translateFunctionCall( isList, ctx.mkGt(length, ctx.mkInt(comprehensionUnrollLimit)), ctx.mkNot(typeSystem.isTrue(currentZ3Result))))); - } else if (extractAstTypeOrDefault(list, ast).kind() != CelKind.MAP) { + } else if (list.staticType(ast).kind() != CelKind.MAP) { // Performance only: maps never take the list overload. List taints = new ArrayList<>(); - BoolExpr found = listMembership(lhs, list, ast, taints); + BoolExpr found = equality.listMembership(lhs, list, ast, taints); currentZ3Result = ctx.mkITE(isList, typeSystem.wrapBool(found), currentZ3Result); currentApprox = CelZ3Exprs.mkOrFlattened( @@ -219,7 +209,7 @@ private BoolExpr constrainInWitnessTypes( TranslatedValue lhsTv, TranslatedValue rhsTv, CelAbstractSyntaxTree ast) { Expr lhs = lhsTv.z3Expr(); Expr rhs = rhsTv.z3Expr(); - CelType rhsType = guaranteedType(rhsTv, ast); + CelType rhsType = context.guaranteedType(rhsTv, ast); if (rhsType instanceof MapType) { // IN_MAP probes lhs and its numeric counterparts, which type constraints unrolled up to the // limit don't cover (e.g. a string found in a map with int keys). @@ -243,7 +233,7 @@ private BoolExpr constrainInWitnessTypes( CelZ3Exprs.mkOrFlattened( ctx, context.isTruncatedMap(rhs), - mayObserveTruncatedTypeConstraint(ast, lhsTv, rhsTv))); + equality.mayObserveTruncatedTypeConstraint(ast, lhsTv, rhsTv))); } /** @@ -314,6 +304,8 @@ private BoolExpr mkTypeGuard(Expr arg, CelType expectedType) { return typeSystem.isStruct(arg); case NULL_TYPE: return typeSystem.isNull(arg); + case TYPE: + return typeSystem.isType(arg); case OPAQUE: if (expectedType.name().equals(OptionalType.NAME)) { return typeSystem.isOptional(arg); @@ -374,11 +366,9 @@ private TranslatedValue translateOperatorCall( case NEGATE: return translateNegate(args.get(0), ast); case EQUALS: - return translateEquality( - args.get(0), args.get(1), ast, /* isEquals= */ true, /* shallow= */ false); case NOT_EQUALS: - return translateEquality( - args.get(0), args.get(1), ast, /* isEquals= */ false, /* shallow= */ false); + return equality.translate( + args.get(0), args.get(1), ast, op == Operator.EQUALS, /* shallow= */ false); case LESS: case GREATER: case LESS_EQUALS: @@ -469,7 +459,7 @@ private TranslatedValue translateBinaryLogicalAndOr( private TranslatedValue translateLogicalNot( List args, CelAbstractSyntaxTree ast) { TranslatedValue arg = args.get(0); - CelType type = extractAstTypeOrDefault(arg, ast); + CelType type = arg.staticType(ast); Expr baseResult = typeSystem.wrapBool(ctx.mkNot((BoolExpr) arg.unwrapZ3Bool())); if (!type.equals(SimpleType.BOOL)) { @@ -481,7 +471,7 @@ private TranslatedValue translateLogicalNot( } private TranslatedValue translateNegate(TranslatedValue arg, CelAbstractSyntaxTree ast) { - CelType type = extractAstTypeOrDefault(arg, ast); + CelType type = arg.staticType(ast); Expr z3Expr = arg.z3Expr(); Expr result; @@ -508,560 +498,6 @@ private TranslatedValue translateNegate(TranslatedValue arg, CelAbstractSyntaxTr ctx, typeSystem, Operator.NEGATE.getFunction(), result, arg); } - private BoolExpr isNumeric(Expr arg) { - return ctx.mkOr(typeSystem.isInt(arg), typeSystem.isUint(arg), typeSystem.isDouble(arg)); - } - - private BoolExpr getNumericEqualityWithConstant( - Expr symVal, CelConstant constant, CelType symType) { - Optional intRange = Optional.empty(); - Optional uintRange = Optional.empty(); - double doubleVal; - - switch (constant.getKind()) { - case INT64_VALUE: - long vInt = constant.int64Value(); - intRange = Optional.of(CelNumericBounds.IntRange.of(vInt, vInt)); - if (vInt >= 0) { - uintRange = - Optional.of(CelNumericBounds.UintRange.of(Long.toString(vInt), Long.toString(vInt))); - } - doubleVal = (double) vInt; - break; - case UINT64_VALUE: - long vUint = constant.uint64Value().longValue(); - if (vUint >= 0) { - intRange = Optional.of(CelNumericBounds.IntRange.of(vUint, vUint)); - } - String uStr = constant.uint64Value().toString(); - uintRange = Optional.of(CelNumericBounds.UintRange.of(uStr, uStr)); - doubleVal = constant.uint64Value().doubleValue(); - break; - case DOUBLE_VALUE: - double vDouble = constant.doubleValue(); - doubleVal = vDouble; - intRange = CelNumericBounds.getMatchingIntRange(vDouble); - uintRange = CelNumericBounds.getMatchingUintRange(vDouble); - break; - default: - throw new IllegalArgumentException( - "Unexpected numeric constant kind: " + constant.getKind()); - } - if (isStaticallyKnown(symType)) { - if (symType.kind() == CelKind.INT) { - return buildIntRangeExpr(intRange, typeSystem.getInt(symVal)); - } else if (symType.kind() == CelKind.UINT) { - return buildUintRangeExpr(uintRange, typeSystem.getUint(symVal)); - } else if (symType.kind() == CelKind.DOUBLE) { - return ctx.mkFPEq(typeSystem.getDouble(symVal), typeSystem.mkFpDouble(doubleVal)); - } - } - - BoolExpr intEq = buildIntRangeExpr(intRange, typeSystem.getInt(symVal)); - BoolExpr uintEq = buildUintRangeExpr(uintRange, typeSystem.getUint(symVal)); - BoolExpr doubleEq = ctx.mkFPEq(typeSystem.getDouble(symVal), typeSystem.mkFpDouble(doubleVal)); - - return (BoolExpr) - CelZ3Exprs.SwitchBuilder.newBuilder(ctx) - .addCase(typeSystem.isInt(symVal), intEq) - .addCase(typeSystem.isUint(symVal), uintEq) - .addCase(typeSystem.isDouble(symVal), doubleEq) - .build(ctx.mkFalse()); - } - - private BoolExpr buildIntRangeExpr(Optional rangeOpt, IntExpr symInt) { - return rangeOpt - .map(range -> buildIntRangeExpr(range.min(), range.max(), symInt)) - .orElseGet(ctx::mkFalse); - } - - private BoolExpr buildIntRangeExpr(long min, long max, IntExpr symInt) { - return ctx.mkAnd(ctx.mkGe(symInt, ctx.mkInt(min)), ctx.mkLe(symInt, ctx.mkInt(max))); - } - - private BoolExpr buildUintRangeExpr( - Optional rangeOpt, IntExpr symUint) { - return rangeOpt - .map(range -> buildUintRangeExpr(range.min(), range.max(), symUint)) - .orElseGet(ctx::mkFalse); - } - - private BoolExpr buildUintRangeExpr(String min, String max, IntExpr symUint) { - return ctx.mkAnd(ctx.mkGe(symUint, ctx.mkInt(min)), ctx.mkLe(symUint, ctx.mkInt(max))); - } - - private BoolExpr getNumericEquality( - TranslatedValue arg0, - TranslatedValue arg1, - CelAbstractSyntaxTree ast, - List taints, - boolean approximateIntDouble) { - if (arg0.isNumericConstant()) { - return getNumericEqualityWithConstant( - arg1.z3Expr(), arg0.celExpr().get().constant(), extractAstTypeOrDefault(arg1, ast)); - } else if (arg1.isNumericConstant()) { - return getNumericEqualityWithConstant( - arg0.z3Expr(), arg1.celExpr().get().constant(), extractAstTypeOrDefault(arg0, ast)); - } - - CelType type0 = extractAstTypeOrDefault(arg0, ast); - CelType type1 = extractAstTypeOrDefault(arg1, ast); - if (isStaticallyKnown(type0) && isStaticallyKnown(type1) && type0.kind() == type1.kind()) { - return getStaticallyKnownNumericEquality(arg0.z3Expr(), type0, arg1.z3Expr()); - } - - return getDynamicNumericEquality(arg0.z3Expr(), arg1.z3Expr(), taints, approximateIntDouble); - } - - /** Evaluates numeric equality when types are statically known. */ - private BoolExpr getStaticallyKnownNumericEquality( - Expr z3Expr0, CelType type0, Expr z3Expr1) { - switch (type0.kind()) { - case INT: - return ctx.mkEq(typeSystem.getInt(z3Expr0), typeSystem.getInt(z3Expr1)); - case UINT: - return ctx.mkEq(typeSystem.getUint(z3Expr0), typeSystem.getUint(z3Expr1)); - case DOUBLE: - return ctx.mkFPEq(typeSystem.getDouble(z3Expr0), typeSystem.getDouble(z3Expr1)); - default: - return ctx.mkFalse(); - } - } - - private BoolExpr getDynamicNumericEquality( - Expr z3Expr0, Expr z3Expr1, List taints, boolean approximateIntDouble) { - BoolExpr isIntOrUint0 = ctx.mkOr(typeSystem.isInt(z3Expr0), typeSystem.isUint(z3Expr0)); - BoolExpr isIntOrUint1 = ctx.mkOr(typeSystem.isInt(z3Expr1), typeSystem.isUint(z3Expr1)); - BoolExpr bothIntOrUint = ctx.mkAnd(isIntOrUint0, isIntOrUint1); - - // Fall back to 0 if the expression is neither an INT nor a UINT. - // This prevents Z3 from evaluating getUint() on a DOUBLE, which causes the OSS solver to enter - // an incomplete state. - IntExpr val0 = - (IntExpr) - ctx.mkITE( - typeSystem.isInt(z3Expr0), - typeSystem.getInt(z3Expr0), - ctx.mkITE(typeSystem.isUint(z3Expr0), typeSystem.getUint(z3Expr0), ctx.mkInt(0))); - IntExpr val1 = - (IntExpr) - ctx.mkITE( - typeSystem.isInt(z3Expr1), - typeSystem.getInt(z3Expr1), - ctx.mkITE(typeSystem.isUint(z3Expr1), typeSystem.getUint(z3Expr1), ctx.mkInt(0))); - - BoolExpr bothDouble = ctx.mkAnd(typeSystem.isDouble(z3Expr0), typeSystem.isDouble(z3Expr1)); - - BoolExpr isIntOrUintAndDouble = ctx.mkAnd(isIntOrUint0, typeSystem.isDouble(z3Expr1)); - BoolExpr isDoubleAndIntOrUint = ctx.mkAnd(typeSystem.isDouble(z3Expr0), isIntOrUint1); - - CelZ3Exprs.SwitchBuilder equality = - CelZ3Exprs.SwitchBuilder.newBuilder(ctx) - .addCase(bothIntOrUint, ctx.mkEq(val0, val1)) - .addCase( - bothDouble, - ctx.mkFPEq(typeSystem.getDouble(z3Expr0), typeSystem.getDouble(z3Expr1))); - if (approximateIntDouble) { - return approximateEqualityWhere( - context.recordApproximation( - "comparisons of ints with doubles read out of lists and maps", - ctx.mkOr(isIntOrUintAndDouble, isDoubleAndIntOrUint)), - z3Expr0, - z3Expr1, - /* exact= */ (BoolExpr) equality.build(ctx.mkFalse()), - taints); - } - // Likewise fall back to 0.0, which the int/double comparisons never need to define. - FPExpr fpVal0 = guardedDouble(z3Expr0); - FPExpr fpVal1 = guardedDouble(z3Expr1); - return (BoolExpr) - equality - .addCase(isIntOrUintAndDouble, typeSystem.intEqDouble(val0, fpVal1)) - .addCase(isDoubleAndIntOrUint, typeSystem.intEqDouble(val1, fpVal0)) - .build(ctx.mkFalse()); - } - - private FPExpr guardedDouble(Expr z3Expr) { - return (FPExpr) - ctx.mkITE( - typeSystem.isDouble(z3Expr), typeSystem.getDouble(z3Expr), typeSystem.mkFpDouble(0.0)); - } - - // A literal with optional elements has as many elements as are present, so no fixed length. - private static boolean isFixedLengthListLiteral(TranslatedValue list) { - return list.isLiteral(ExprKind.Kind.LIST) - && list.celExpr().get().list().optionalIndices().isEmpty(); - } - - // Unrolls list equality element-wise (up to the unroll limit unless either is a literal), adding - // each element equality's approximation to taints: numerically equal elements (e.g. 1 == 1u) - // needn't be equal terms. - private BoolExpr unrollListEquality( - TranslatedValue listA, - TranslatedValue listB, - CelAbstractSyntaxTree ast, - List taints) { - boolean isLiteralA = isFixedLengthListLiteral(listA); - boolean isLiteralB = isFixedLengthListLiteral(listB); - boolean isLiteral = isLiteralA || isLiteralB; - SeqExpr seq0 = typeSystem.getSeq(typeSystem.getListRef(listA.z3Expr())); - SeqExpr seq1 = typeSystem.getSeq(typeSystem.getListRef(listB.z3Expr())); - ArithExpr length = ctx.mkLength(seq0); - - List equalities = new ArrayList<>(); - equalities.add(ctx.mkEq(length, ctx.mkLength(seq1))); - int size = - isLiteral - ? (isLiteralA ? listA : listB).celExpr().get().list().elements().size() - : comprehensionUnrollLimit; - if (!isLiteral) { - equalities.add(approximatePastUnrollLimit(length, listA.z3Expr(), listB.z3Expr(), taints)); - } - for (int i = 0; i < size; i++) { - TranslatedValue elemA = listElement(listA, seq0, i, isLiteralA, ast); - TranslatedValue elemB = listElement(listB, seq1, i, isLiteralB, ast); - TranslatedValue elemEquality = - translateEquality(elemA, elemB, ast, /* isEquals= */ true, /* shallow= */ !isLiteral); - BoolExpr inBounds = ctx.mkLt(ctx.mkInt(i), length); - equalities.add(ctx.mkImplies(inBounds, typeSystem.isTrue(elemEquality.z3Expr()))); - taints.add(ctx.mkAnd(inBounds, elemEquality.isApproximate())); - } - return CelZ3Exprs.mkAndFlattened(ctx, equalities); - } - - // Element i of list, typed by the literal's element if list is a literal. - private TranslatedValue listElement( - TranslatedValue list, SeqExpr seq, int i, boolean isLiteral, CelAbstractSyntaxTree ast) { - Expr elem = ctx.mkNth(seq, ctx.mkInt(i)); - // A literal's elements are already CEL values (performance only). - if (!isLiteral) { - BoolExpr inBounds = ctx.mkLt(ctx.mkInt(i), ctx.mkLength(seq)); - context.constrainValidValue(ctx.mkAnd(typeSystem.isList(list.z3Expr()), inBounds), elem); - CelType listType = guaranteedType(list, ast); - // Type constraints are only unrolled up to the limit. - if (i >= comprehensionUnrollLimit && listType instanceof ListType) { - context.addConstraint( - ctx.mkImplies( - inBounds, - typeConstraintGenerator.createTypeConstraintForType( - elem, ((ListType) listType).elemType()))); - } - } - return TranslatedValue.create( - elem, - isLiteral ? list.listElementAt(i) : Optional.empty(), - typeSystem, - list.isApproximate()); - } - - // Unrolled over a map literal's keys, or else mapA's up to the unroll limit: the other map has as - // many keys, and an equal key and value for each. - private BoolExpr unrollMapEquality( - TranslatedValue mapA, - TranslatedValue mapB, - CelAbstractSyntaxTree ast, - List taints) { - boolean isLiteral = mapA.isLiteral(ExprKind.Kind.MAP) || mapB.isLiteral(ExprKind.Kind.MAP); - // Prefer a literal whose values are list or map literals, which compare element-wise. - boolean isMapA = - !mapB.isLiteral(ExprKind.Kind.MAP) - || (mapA.isLiteral(ExprKind.Kind.MAP) && !hasContainerLiteralValue(mapB)); - TranslatedValue map = isMapA ? mapA : mapB; - TranslatedValue otherMap = isMapA ? mapB : mapA; - Expr other = otherMap.z3Expr(); - BoolExpr isOtherMap = typeSystem.isMap(other); - Expr mapRef = typeSystem.getMapRef(map.z3Expr()); - SeqExpr keys = typeSystem.getMapKeys(mapRef); - ArrayExpr values = (ArrayExpr) typeSystem.getMapValues(mapRef); - ArithExpr length = ctx.mkLength(keys); - Expr otherRef = typeSystem.getMapRef(other); - SeqExpr otherKeys = typeSystem.getMapKeys(otherRef); - - List equalities = new ArrayList<>(); - equalities.add(ctx.mkEq(length, ctx.mkLength(otherKeys))); - ImmutableList entries = - isLiteral ? map.celExpr().get().map().entries() : ImmutableList.of(); - // The keys are in entry order unless an optional entry is absent (repeated keys are errors). - boolean inEntryOrder = - isLiteral && entries.stream().noneMatch(CelExpr.CelMap.Entry::optionalEntry); - int size = isLiteral ? entries.size() : comprehensionUnrollLimit; - if (!isLiteral) { - equalities.add(approximatePastUnrollLimit(length, map.z3Expr(), other, taints)); - // A map that isn't a literal or of a declared map type isn't otherwise known to be - // well-formed (distinct keys matching its presence, valid keys and values). - for (TranslatedValue operand : ImmutableList.of(mapA, mapB)) { - if (!(guaranteedType(operand, ast) instanceof MapType)) { - context.addConstraint( - ctx.mkImplies( - typeSystem.isMap(operand.z3Expr()), - typeConstraintGenerator.createTypeConstraintForType(operand.z3Expr(), DYN_MAP))); - } - } - } - for (int i = 0; i < size; i++) { - BoolExpr inBounds = ctx.mkLt(ctx.mkInt(i), length); - Expr key = ctx.mkNth(keys, ctx.mkInt(i)).simplify(); - ImmutableList equalKeys = typeSystem.equalKeys(key); - BoolExpr hasKey = typeSystem.hasEqualKey(other, equalKeys); - Expr otherValue = typeSystem.valueAtEqualKey(other, equalKeys); - context.constrainValidValue(ctx.mkAnd(isOtherMap, inBounds, hasKey), otherValue); - TranslatedValue valueEquality = - translateEquality( - TranslatedValue.create( - ctx.mkSelect(values, key), - inEntryOrder ? Optional.of(entries.get(i).value()) : Optional.empty(), - typeSystem, - map.isApproximate()), - TranslatedValue.create(otherValue, typeSystem, otherMap.isApproximate()), - ast, - /* isEquals= */ true, - /* shallow= */ !isLiteral); - taints.add(ctx.mkAnd(inBounds, valueEquality.isApproximate())); - equalities.add( - ctx.mkImplies(inBounds, ctx.mkAnd(hasKey, typeSystem.isTrue(valueEquality.z3Expr())))); - } - if (isLiteral) { - // The other map's keys are exactly the present ones, so each equals a literal key: as many - // as the literal's, which are all present. - ArrayExpr presence = ctx.mkConstArray(typeSystem.celValueSort(), ctx.mkFalse()); - for (int j = 0; j < entries.size(); j++) { - Expr otherKey = ctx.mkNth(otherKeys, ctx.mkInt(j)); - presence = - (ArrayExpr) - ctx.mkITE( - ctx.mkLt(ctx.mkInt(j), length), - ctx.mkStore(presence, otherKey, ctx.mkTrue()), - presence); - } - equalities.add(ctx.mkEq(typeSystem.getMapPresence(otherRef), presence)); - } - return CelZ3Exprs.mkAndFlattened(ctx, equalities); - } - - // Maps whose keys and values compare by their terms are equal when they have the same keys, and - // the same values at the literal's keys (performance only). - private BoolExpr mapEqualityAtLiteralKeys(TranslatedValue mapA, TranslatedValue mapB) { - boolean isLiteralA = mapA.isLiteral(ExprKind.Kind.MAP); - Expr literalRef = typeSystem.getMapRef((isLiteralA ? mapA : mapB).z3Expr()); - Expr otherRef = typeSystem.getMapRef((isLiteralA ? mapB : mapA).z3Expr()); - SeqExpr keys = typeSystem.getMapKeys(literalRef); - ArrayExpr values = (ArrayExpr) typeSystem.getMapValues(literalRef); - ArrayExpr otherValues = (ArrayExpr) typeSystem.getMapValues(otherRef); - List equalities = new ArrayList<>(); - // Same size and same keys. Past the unroll limit, a map's presence isn't tied to its keys, so - // matching presence alone doesn't rule out extra keys (e.g. a 6-key map equal to {'a': 1}). - equalities.add(ctx.mkEq(ctx.mkLength(keys), ctx.mkLength(typeSystem.getMapKeys(otherRef)))); - equalities.add( - ctx.mkEq(typeSystem.getMapPresence(literalRef), typeSystem.getMapPresence(otherRef))); - int size = (isLiteralA ? mapA : mapB).celExpr().get().map().entries().size(); - for (int i = 0; i < size; i++) { - Expr key = ctx.mkNth(keys, ctx.mkInt(i)); - equalities.add( - ctx.mkImplies( - ctx.mkLt(ctx.mkInt(i), ctx.mkLength(keys)), - typeSystem.getStructuralEquality( - ctx.mkSelect(values, key), ctx.mkSelect(otherValues, key)))); - } - return CelZ3Exprs.mkAndFlattened(ctx, equalities); - } - - // `in` on a list compares each element with lhs by CEL equality, unrolled over a literal's - // elements or else up to the unroll limit, past which a match is approximate. - private BoolExpr listMembership( - TranslatedValue lhs, TranslatedValue list, CelAbstractSyntaxTree ast, List taints) { - boolean isLiteral = isFixedLengthListLiteral(list); - SeqExpr seq = typeSystem.getSeq(typeSystem.getListRef(list.z3Expr())); - ArithExpr length = ctx.mkLength(seq); - List matches = new ArrayList<>(); - int size = isLiteral ? list.celExpr().get().list().elements().size() : comprehensionUnrollLimit; - for (int i = 0; i < size; i++) { - BoolExpr inBounds = ctx.mkLt(ctx.mkInt(i), length); - // The runtime compares each element with lhs, in that order. - TranslatedValue equality = - translateEquality( - listElement(list, seq, i, isLiteral, ast), - lhs, - ast, - /* isEquals= */ true, - /* shallow= */ !isLiteral); - matches.add(ctx.mkAnd(inBounds, typeSystem.isTrue(equality.z3Expr()))); - taints.add(ctx.mkAnd(inBounds, equality.isApproximate())); - } - BoolExpr found = CelZ3Exprs.mkOrFlattened(ctx, matches); - if (isLiteral) { - return found; - } - CelType listType = guaranteedType(list, ast); - CelType elemType = - listType instanceof ListType ? ((ListType) listType).elemType() : SimpleType.DYN; - return approximateWhere( - context.recordUnrollLimitApproximation( - CelZ3Exprs.mkAndFlattened( - ctx, - ctx.mkGt(length, ctx.mkInt(comprehensionUnrollLimit)), - ctx.mkNot(found), - mayEqualElement(lhs.z3Expr(), elemType))), - uninterpreted(FUNC_APPROX_IN, lhs.z3Expr(), list.z3Expr()), - found, - taints); - } - - // Whether lhs may equal an element of elemType: a number only across numeric types, and a list - // only another list (anything else conservatively). - private BoolExpr mayEqualElement(Expr lhs, CelType elemType) { - if (isNumericType(elemType)) { - return isNumeric(lhs); - } - return elemType.kind() == CelKind.LIST ? typeSystem.isList(lhs) : ctx.mkTrue(); - } - - // Where the recorded approximation holds, the verifier doesn't model the result, so it's the - // given uninterpreted relation there. - private BoolExpr approximateWhere( - BoolExpr approximation, BoolExpr relation, BoolExpr exact, List taints) { - taints.add(approximation); - return (BoolExpr) ctx.mkITE(approximation, relation, exact); - } - - private BoolExpr uninterpreted(String name, Expr z3Expr0, Expr z3Expr1) { - Sort sort = typeSystem.celValueSort(); - FuncDecl relation = - typeSystem.internFuncDecl(name, new Sort[] {sort, sort}, ctx.getBoolSort()); - return (BoolExpr) ctx.mkApp(relation, z3Expr0, z3Expr1); - } - - // Like approximateWhere, for CEL equality, which is symmetric. - private BoolExpr approximateEqualityWhere( - BoolExpr approximation, - Expr z3Expr0, - Expr z3Expr1, - BoolExpr exact, - List taints) { - // Ordered by term id (in either direction) so that x == y and y == x share one application. - // Asserting both orders instead doubles the applications, which made nested comparisons slow. - boolean swap = z3Expr0.getId() > z3Expr1.getId(); - BoolExpr relation = - uninterpreted(FUNC_APPROX_EQ, swap ? z3Expr1 : z3Expr0, swap ? z3Expr0 : z3Expr1); - return approximateWhere(approximation, relation, exact, taints); - } - - // Lists and maps compared up to the unroll limit may differ past it. - private BoolExpr approximatePastUnrollLimit( - ArithExpr length, Expr z3Expr0, Expr z3Expr1, List taints) { - return approximateEqualityWhere( - context.recordUnrollLimitApproximation( - ctx.mkGt(length, ctx.mkInt(comprehensionUnrollLimit))), - z3Expr0, - z3Expr1, - /* exact= */ ctx.mkTrue(), - taints); - } - - private static boolean hasContainerLiteralValue(TranslatedValue map) { - return map.celExpr().get().map().entries().stream() - .anyMatch(e -> isContainerLiteral(e.value())); - } - - private static boolean isContainerLiteral(CelExpr expr) { - return expr.getKind() == ExprKind.Kind.LIST || expr.getKind() == ExprKind.Kind.MAP; - } - - private static boolean isContainerLiteral(TranslatedValue val) { - return val.isLiteral(ExprKind.Kind.LIST) || val.isLiteral(ExprKind.Kind.MAP); - } - - // CEL equality. Values read out of lists and maps that aren't literals (shallow, unless either is - // a list or map literal) compare numbers numerically, but ints and doubles approximately, and - // lists, maps, messages and optionals approximately (performance only). - private TranslatedValue translateEquality( - TranslatedValue arg0, - TranslatedValue arg1, - CelAbstractSyntaxTree ast, - boolean isEquals, - boolean shallow) { - boolean isShallow = shallow && !isContainerLiteral(arg0) && !isContainerLiteral(arg1); - Expr z3Arg0 = arg0.z3Expr(); - Expr z3Arg1 = arg1.z3Expr(); - - CelType type0 = extractAstTypeOrDefault(arg0, ast); - CelType type1 = extractAstTypeOrDefault(arg1, ast); - - BoolExpr equality; - List taints = new ArrayList<>(); - if (!isShallow) { - taints.add(mayObserveTruncatedTypeConstraint(ast, arg0, arg1)); - } - - if (isNumericType(type0) && isNumericType(type1)) { - equality = getNumericEquality(arg0, arg1, ast, taints, /* approximateIntDouble= */ false); - } else { - BoolExpr bothLists = ctx.mkAnd(typeSystem.isList(z3Arg0), typeSystem.isList(z3Arg1)); - BoolExpr bothMaps = ctx.mkAnd(typeSystem.isMap(z3Arg0), typeSystem.isMap(z3Arg1)); - BoolExpr structuralEq; - if (isShallow) { - structuralEq = - approximateEqualityWhere( - context.recordApproximation( - "comparisons of lists, maps, messages or optionals read out of lists and maps", - CelZ3Exprs.mkOrFlattened( - ctx, - bothLists, - bothMaps, - ctx.mkAnd(typeSystem.isMessage(z3Arg0), typeSystem.isMessage(z3Arg1)), - ctx.mkAnd(typeSystem.isOptional(z3Arg0), typeSystem.isOptional(z3Arg1)))), - z3Arg0, - z3Arg1, - /* exact= */ ctx.mkEq(z3Arg0, z3Arg1), - taints); - } else { - // Lists and maps compare by CEL equality, unless their guaranteed types make it their - // terms'. - structuralEq = typeSystem.getStructuralEquality(z3Arg0, z3Arg1); - if (!isExact(guaranteedType(arg0, ast), guaranteedType(arg1, ast))) { - if (type0.kind() == CelKind.LIST || type1.kind() == CelKind.LIST) { - structuralEq = - (BoolExpr) - ctx.mkITE(bothLists, unrollListEquality(arg0, arg1, ast, taints), structuralEq); - } else if (type0.kind() == CelKind.MAP || type1.kind() == CelKind.MAP) { - BoolExpr mapEquality = - isExact(type0, type1) - && (arg0.isLiteral(ExprKind.Kind.MAP) || arg1.isLiteral(ExprKind.Kind.MAP)) - ? mapEqualityAtLiteralKeys(arg0, arg1) - : unrollMapEquality(arg0, arg1, ast, taints); - structuralEq = (BoolExpr) ctx.mkITE(bothMaps, mapEquality, structuralEq); - } else if (!isStaticallyKnown(type0) && !isStaticallyKnown(type1)) { - // Performance only: a side with a known type isn't a list or map here. - structuralEq = - approximateEqualityWhere( - context.recordApproximation( - "comparisons of lists or maps typed dyn", ctx.mkOr(bothLists, bothMaps)), - z3Arg0, - z3Arg1, - structuralEq, - taints); - } - } - } - equality = - (BoolExpr) - ctx.mkITE( - ctx.mkAnd(isNumeric(z3Arg0), isNumeric(z3Arg1)), - getNumericEquality( - arg0, arg1, ast, taints, /* approximateIntDouble= */ isShallow), - structuralEq); - } - - if (!isEquals) { - equality = ctx.mkNot(equality); - } - - Expr equalityExpr = typeSystem.wrapBool(equality); - String opName = isEquals ? Operator.EQUALS.getFunction() : Operator.NOT_EQUALS.getFunction(); - - return TranslatedValue.propagateStrict(ctx, typeSystem, opName, equalityExpr, arg0, arg1) - .withApproximation(CelZ3Exprs.mkOrFlattened(ctx, taints)); - } - /** A list element or map value, read without regard to optionals. */ private static final class IndexAccess { private final BoolExpr valid; @@ -1125,7 +561,7 @@ private TranslatedValue translateIndex( List args, CelAbstractSyntaxTree ast, Operator op) { TranslatedValue lhs = args.get(0); TranslatedValue rhs = args.get(1); - CelType lhsType = extractAstTypeOrDefault(lhs, ast); + CelType lhsType = lhs.staticType(ast); CelType containerType = lhsType instanceof OptionalType ? lhsType.parameters().get(0) : lhsType; Expr lhsTrans = lhs.z3Expr(); @@ -1170,7 +606,7 @@ private TranslatedValue translateConditional( TranslatedValue cond = args.get(0); TranslatedValue trueBranch = args.get(1); TranslatedValue falseBranch = args.get(2); - CelType condType = extractAstTypeOrDefault(cond, ast); + CelType condType = cond.staticType(ast); BoolExpr condTrue = ctx.mkAnd(cond.isZ3Bool(), (BoolExpr) cond.unwrapZ3Bool()); @@ -1215,17 +651,6 @@ private TranslatedValue translateNotStrictlyFalse(List args) { typeSystem.wrapBool(ctx.mkNot(isFalse)), typeSystem, arg.isApproximate()); } - private static CelType extractAstTypeOrDefault(TranslatedValue val, CelAbstractSyntaxTree ast) { - return val.celExpr().map(node -> ast.getTypeOrThrow(node.id())).orElse(SimpleType.DYN); - } - - /** Returns a constant's type, or an input variable's declared type, or else dyn. */ - private CelType guaranteedType(TranslatedValue val, CelAbstractSyntaxTree ast) { - return val.isLiteral(ExprKind.Kind.CONSTANT) - ? extractAstTypeOrDefault(val, ast) - : context.guaranteedType(val.z3Expr()); - } - /** * Whether {@code type} itself is neither dyn nor a type parameter. Unlike {@link #isConcrete}, * its type parameters may still be (e.g. {@code list(dyn)}). @@ -1242,60 +667,15 @@ static boolean hasConcreteElements(CelType type) { } /** Whether {@code type} and, recursively, its type parameters are statically known. */ - private static boolean isConcrete(CelType type) { + static boolean isConcrete(CelType type) { + if (type.kind() == CelKind.TYPE) { + // A type value holds no value of its parameter. + return true; + } return isStaticallyKnown(type) && type.parameters().stream().allMatch(CelZ3OperatorTranslator::isConcrete); } - private static boolean isExact(CelType type0, CelType type1) { - return type0.equals(type1) && hasStructuralEquality(type0); - } - - /** Whether values of {@code type} are equal exactly when their terms are. */ - private static boolean hasStructuralEquality(CelType type) { - switch (type.kind()) { - case BOOL: - case INT: - case UINT: - case STRING: - case BYTES: - case TIMESTAMP: - case DURATION: - return true; - case LIST: - case MAP: - return type.parameters().stream().allMatch(CelZ3OperatorTranslator::hasStructuralEquality); - default: - // Doubles (NaN, -0.0), dyn, messages and the rest compare by CEL equality. - return false; - } - } - - /** Excludes wrappers, whose kind is their value's but which may also be null. */ - private static boolean isNumericType(CelType type) { - CelKind kind = type.kind(); - return !(type instanceof NullableType) - && (kind == CelKind.INT || kind == CelKind.UINT || kind == CelKind.DOUBLE); - } - - /** - * Whether observing {@code args} together may expose a value beyond a truncated type constraint - * in any of them. Type constraints at the point of observation rule this out only if every arg - * has a concrete static type (unlike e.g. {@code dyn(int_list)}). - */ - private BoolExpr mayObserveTruncatedTypeConstraint( - CelAbstractSyntaxTree ast, TranslatedValue... args) { - if (Arrays.stream(args).allMatch(arg -> isConcrete(extractAstTypeOrDefault(arg, ast)))) { - return ctx.mkFalse(); - } - return context.recordUnrollLimitApproximation( - CelZ3Exprs.mkOrFlattened( - ctx, - Arrays.stream(args) - .map(arg -> typeSystem.hasTruncatedTypeConstraint(arg.z3Expr())) - .collect(toImmutableList()))); - } - CelZ3OperatorTranslator(CelZ3TranslationContext context, CelZ3FunctionRegistry functionRegistry) { this.ctx = context.ctx(); this.typeSystem = context.typeSystem(); @@ -1303,5 +683,6 @@ private BoolExpr mayObserveTruncatedTypeConstraint( this.typeConstraintGenerator = context.typeConstraintGenerator(); this.functionRegistry = functionRegistry; this.comprehensionUnrollLimit = context.comprehensionUnrollLimit(); + this.equality = new CelZ3Equality(context); } } diff --git a/verifier/src/main/java/dev/cel/verifier/CelZ3StructTranslator.java b/verifier/src/main/java/dev/cel/verifier/CelZ3StructTranslator.java index 645720443..514fc880e 100644 --- a/verifier/src/main/java/dev/cel/verifier/CelZ3StructTranslator.java +++ b/verifier/src/main/java/dev/cel/verifier/CelZ3StructTranslator.java @@ -15,8 +15,6 @@ package dev.cel.verifier; import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; -import com.google.common.collect.Streams; import com.microsoft.z3.ArrayExpr; import com.microsoft.z3.BoolExpr; import com.microsoft.z3.Context; @@ -32,21 +30,25 @@ import dev.cel.common.types.CelType; import dev.cel.common.types.CelTypeProvider; import dev.cel.common.types.CelTypes; +import dev.cel.common.types.EnumType; import dev.cel.common.types.ListType; import dev.cel.common.types.MapType; import dev.cel.common.types.NullableType; import dev.cel.common.types.OptionalType; +import dev.cel.common.types.ProtoMessageType; import dev.cel.common.types.SimpleType; import dev.cel.common.types.StructType; import dev.cel.common.types.StructTypeReference; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.BiFunction; +import org.jspecify.annotations.Nullable; /** Translates CEL message construction and field selection to Z3. */ @SuppressWarnings({"unchecked", "rawtypes"}) // Z3 Java API uses raw types. @@ -55,7 +57,7 @@ final class CelZ3StructTranslator { private static final String EMPTY_MSG_REF_PREFIX = "!empty_msg_ref_"; private static final String EMPTY_LIST_PREFIX = "!empty_list"; private static final String EMPTY_MAP_PREFIX = "!empty_map"; - private static final String NULL_VALUE_FIELD = "null_value"; + private static final String VALUE_FIELD = "value"; private static final String SECONDS_FIELD = "seconds"; private static final String NANOS_FIELD = "nanos"; private static final long MAX_UINT32 = 0xFFFFFFFFL; @@ -67,8 +69,8 @@ final class CelZ3StructTranslator { private final CelTypeProvider typeProvider; private final BiFunction exprTranslator; private final Map> emptyMessageCache; - private Expr emptyListCache; - private Expr emptyMapCache; + private @Nullable Expr emptyListCache; + private @Nullable Expr emptyMapCache; TranslatedValue translateStruct(CelExpr celExpr, CelAbstractSyntaxTree ast) { CelExpr.CelStruct createStruct = celExpr.struct(); @@ -104,35 +106,17 @@ TranslatedValue translateStruct(CelExpr celExpr, CelAbstractSyntaxTree ast) { ArrayExpr msgPresence = ctx.mkConstArray(ctx.getStringSort(), ctx.mkFalse()); List elementsTv = new ArrayList<>(); - List invalidFields = new ArrayList<>(); + Map invalidFields = new LinkedHashMap<>(); Set fields = new HashSet<>(); for (CelExpr.CelStruct.Entry entryAst : createStruct.entries()) { Expr key = ctx.mkString(entryAst.fieldKey()); - TranslatedValue valueTv = translateExpr(entryAst.value(), ast); - Expr value = valueTv.z3Expr(); - - CelType fieldType = - typeProvider - .findType(createStruct.messageName()) - .filter(t -> t instanceof StructType) - .map(t -> (StructType) t) - .flatMap(t -> t.findField(entryAst.fieldKey())) - .map(StructType.Field::type) - .orElseGet(() -> extractAstTypeOrDefault(ast, entryAst.value().id())); - - Expr finalValue = value; - BoolExpr optionalHasValue = ctx.mkTrue(); - if (entryAst.optionalEntry()) { - Expr checkedValue = - typeSystem.withRuntimeError(value, ctx.mkNot(typeSystem.isOptional(value))); - valueTv = - TranslatedValue.create( - checkedValue, entryAst.value(), typeSystem, valueTv.isApproximate()); - Expr optRef = typeSystem.getOptionalRef(checkedValue); - optionalHasValue = typeSystem.optHasValue(optRef); - finalValue = typeSystem.getOptionalValue(optRef); - } + StructEntry entry = translateEntry(entryAst, ast); + TranslatedValue valueTv = entry.valueTv; + + CelType fieldType = findFieldType(createStruct.messageName(), entryAst, ast); + BoolExpr isValid = fieldKindConstraint(fieldType, entry.value); + recordFieldValidity(invalidFields, entryAst.fieldKey(), isValid, entry); // Canonicalization Trick: // @@ -144,18 +128,15 @@ TranslatedValue translateStruct(CelExpr celExpr, CelAbstractSyntaxTree ast) { // `msgPresence`. BoolExpr isUnset = ctx.mkFalse(); if (fieldType.kind().isPrimitive()) { - isUnset = ctx.mkEq(finalValue, getDefaultValueForType(fieldType)); - } else if (fieldType.kind() == CelKind.LIST || fieldType.kind() == CelKind.MAP) { - // Empty repeated and map fields are unset too. Other values can't initialize them. + isUnset = ctx.mkEq(entry.value, getDefaultValueForType(fieldType)); + } else if (isValid != null) { + // Empty repeated and map fields are unset too. boolean isList = fieldType.kind() == CelKind.LIST; - BoolExpr hasFieldKind = - isList ? typeSystem.isList(finalValue) : typeSystem.isMap(finalValue); - invalidFields.add(ctx.mkAnd(optionalHasValue, ctx.mkNot(hasFieldKind))); SeqExpr elements = isList - ? typeSystem.getSeq(typeSystem.getListRef(finalValue)) - : typeSystem.getMapKeys(typeSystem.getMapRef(finalValue)); - BoolExpr isEmpty = ctx.mkAnd(hasFieldKind, ctx.mkEq(ctx.mkLength(elements), ctx.mkInt(0))); + ? typeSystem.getSeq(typeSystem.getListRef(entry.value)) + : typeSystem.getMapKeys(typeSystem.getMapRef(entry.value)); + BoolExpr isEmpty = ctx.mkAnd(isValid, ctx.mkEq(ctx.mkLength(elements), ctx.mkInt(0))); isUnset = isEmpty; // A google.protobuf.ListValue or Struct field has the same type, but is set even if empty, // so either may hold. @@ -165,7 +146,7 @@ TranslatedValue translateStruct(CelExpr celExpr, CelAbstractSyntaxTree ast) { valueTv.withApproximation( context.recordApproximation( "whether empty `list(dyn)` and `map(string, dyn)` fields are set", - CelZ3Exprs.mkAndFlattened(ctx, optionalHasValue, isEmpty))); + CelZ3Exprs.mkAndFlattened(ctx, entry.hasValue, isEmpty))); isUnset = ctx.mkAnd( isEmpty, @@ -175,8 +156,7 @@ TranslatedValue translateStruct(CelExpr celExpr, CelAbstractSyntaxTree ast) { } elementsTv.add(valueTv); - BoolExpr shouldBypass = ctx.mkOr(ctx.mkNot(optionalHasValue), isUnset); - // The last entry for a field wins, so a later unset entry clears an earlier one. + BoolExpr shouldBypass = ctx.mkOr(ctx.mkNot(entry.hasValue), isUnset); boolean isRepeatedEntry = !fields.add(entryAst.fieldKey()); msgValues = @@ -184,7 +164,7 @@ TranslatedValue translateStruct(CelExpr celExpr, CelAbstractSyntaxTree ast) { ctx.mkITE( shouldBypass, isRepeatedEntry ? ctx.mkStore(msgValues, key, typeSystem.mkUnknown()) : msgValues, - ctx.mkStore(msgValues, key, finalValue)); + ctx.mkStore(msgValues, key, entry.value)); msgPresence = (ArrayExpr) @@ -199,10 +179,89 @@ TranslatedValue translateStruct(CelExpr celExpr, CelAbstractSyntaxTree ast) { context.addConstraint(ctx.mkEq(typeSystem.getMsgValues(msgRef), msgValues)); context.addConstraint(ctx.mkEq(typeSystem.getMsgPresence(msgRef), msgPresence)); - Expr result = + elementsTv.addAll(invalidFields.values()); + return TranslatedValue.propagateStrict( + ctx, typeSystem, typeSystem.wrapMessage(msgRef), celExpr, elementsTv); + } + + private static final class StructEntry { + private final TranslatedValue valueTv; + private final BoolExpr hasValue; + private final Expr value; + + private StructEntry(TranslatedValue valueTv, BoolExpr hasValue, Expr value) { + this.valueTv = valueTv; + this.hasValue = hasValue; + this.value = value; + } + } + + private StructEntry translateEntry(CelExpr.CelStruct.Entry entry, CelAbstractSyntaxTree ast) { + TranslatedValue valueTv = translateExpr(entry.value(), ast); + Expr value = valueTv.z3Expr(); + if (!entry.optionalEntry()) { + return new StructEntry(valueTv, /* hasValue= */ ctx.mkTrue(), value); + } + BoolExpr isOptional = typeSystem.isOptional(value); + Expr checkedValue = typeSystem.withRuntimeError( - typeSystem.wrapMessage(msgRef), CelZ3Exprs.mkOrFlattened(ctx, invalidFields)); - return TranslatedValue.propagateStrict(ctx, typeSystem, result, celExpr, elementsTv); + value, ctx.mkAnd(ctx.mkNot(typeSystem.isUnknown(value)), ctx.mkNot(isOptional))); + TranslatedValue checkedTv = + TranslatedValue.create(checkedValue, entry.value(), typeSystem, valueTv.isApproximate()); + Expr optRef = typeSystem.getOptionalRef(checkedValue); + return new StructEntry( + checkedTv, + ctx.mkAnd(isOptional, typeSystem.optHasValue(optRef)), + typeSystem.getOptionalValue(optRef)); + } + + private CelType findFieldType( + String messageName, CelExpr.CelStruct.Entry entry, CelAbstractSyntaxTree ast) { + String fieldKey = entry.fieldKey(); + return typeProvider + .findType(messageName) + .filter(t -> t instanceof StructType) + .map(t -> (StructType) t) + .flatMap(t -> { + Optional field = t.findField(fieldKey).map(StructType.Field::type); + if (field.isPresent() || !(t instanceof ProtoMessageType)) { + return field; + } + return ((ProtoMessageType) t) + .findExtension(fieldKey) + .map(ProtoMessageType.Extension::type); + }) + .orElseGet(() -> extractAstTypeOrDefault(ast, entry.value().id())); + } + + private @Nullable BoolExpr fieldKindConstraint(CelType fieldType, Expr val) { + if (fieldType.kind().isPrimitive()) { + return typeConstraintGenerator.createTypeConstraintForType(val, fieldType); + } + if (fieldType.kind() == CelKind.LIST) { + return typeSystem.isList(val); + } + if (fieldType.kind() == CelKind.MAP) { + return typeSystem.isMap(val); + } + return null; + } + + private void recordFieldValidity( + Map invalidFields, + String fieldKey, + @Nullable BoolExpr isValid, + StructEntry entry) { + if (isValid != null) { + invalidFields.put( + fieldKey, + TranslatedValue.create( + typeSystem.withRuntimeError( + typeSystem.mkNull(), + CelZ3Exprs.mkAndFlattened(ctx, entry.hasValue, ctx.mkNot(isValid))), + typeSystem, + entry.valueTv.isApproximate())); + } } private static boolean isJsonWkt(String messageName) { @@ -224,42 +283,42 @@ private TranslatedValue translateJsonWktStruct( fallback = getDefaultValueForType(MapType.create(SimpleType.STRING, SimpleType.DYN)); } - if (createStruct.entries().isEmpty()) { - return TranslatedValue.create(fallback, celExpr, typeSystem, ctx.mkFalse()); + ImmutableList entries = createStruct.entries(); + List elementsTv = new ArrayList<>(); + Map fields = new HashMap<>(); + Map fieldOrder = new HashMap<>(); + Map invalidFields = new LinkedHashMap<>(); + for (int i = 0; i < entries.size(); i++) { + CelExpr.CelStruct.Entry entryAst = entries.get(i); + StructEntry entry = translateEntry(entryAst, ast); + elementsTv.add(entry.valueTv); + + CelType fieldType = findFieldType(createStruct.messageName(), entryAst, ast); + BoolExpr isValid = fieldKindConstraint(fieldType, entry.value); + recordFieldValidity(invalidFields, entryAst.fieldKey(), isValid, entry); + + Expr unwrappedVal = fieldType instanceof EnumType ? typeSystem.mkNull() : entry.value; + String key = entryAst.fieldKey(); + FieldAccess prev = fields.put(key, new FieldAccess(entry.hasValue, unwrappedVal)); + fieldOrder.put( + key, + prev == null + ? ctx.mkInt(i) + : (IntExpr) ctx.mkITE(prev.presence, fieldOrder.get(key), ctx.mkInt(i))); } + elementsTv.addAll(invalidFields.values()); - // JSON WKT messages (gp.Struct, gp.Value, gp.ListValue) can only have a single top-level - // field entry in non-empty creation literals (e.g., 'fields' for Struct, 'values' for - // ListValue, or a single 'oneof' field for Value). - CelExpr.CelStruct.Entry entry = Iterables.getOnlyElement(createStruct.entries()); - - // Translate the value to properly capture approximations and Optionals - TranslatedValue entryTv = translateExpr(entry.value(), ast); - Expr finalVal = entryTv.z3Expr(); - - boolean isNullValueField = - createStruct.messageName().equals(CelTypes.VALUE_MESSAGE) - && entry.fieldKey().equals(NULL_VALUE_FIELD); - - if (entry.optionalEntry()) { - Expr checkedVal = - typeSystem.withRuntimeError(finalVal, ctx.mkNot(typeSystem.isOptional(finalVal))); - entryTv = - TranslatedValue.create(checkedVal, entry.value(), typeSystem, entryTv.isApproximate()); - Expr optRef = typeSystem.getOptionalRef(checkedVal); - BoolExpr hasValue = typeSystem.optHasValue(optRef); - - Expr unpackedVal = typeSystem.getOptionalValue(optRef); - if (isNullValueField) { - unpackedVal = typeSystem.mkNull(); - } - finalVal = ctx.mkITE(hasValue, unpackedVal, fallback); - } else if (isNullValueField) { - finalVal = typeSystem.mkNull(); + Expr result = fallback; + for (int i = 0; i < entries.size(); i++) { + String key = entries.get(i).fieldKey(); + FieldAccess field = fields.get(key); + result = + ctx.mkITE( + ctx.mkAnd(field.presence, ctx.mkEq(fieldOrder.get(key), ctx.mkInt(i))), + field.value, + result); } - - return TranslatedValue.propagateStrict( - ctx, typeSystem, finalVal, celExpr, ImmutableList.of(entryTv)); + return TranslatedValue.propagateStrict(ctx, typeSystem, result, celExpr, elementsTv); } private TranslatedValue translateWrapperWktStruct( @@ -270,25 +329,10 @@ private TranslatedValue translateWrapperWktStruct( .orElseThrow( () -> new IllegalArgumentException("Unexpected wrapper type: " + typeName)); CelType targetType = ((NullableType) wrapperType).targetType(); - Expr currentVal = getDefaultValueForType(targetType); - List entryTvs = new ArrayList<>(); - for (CelExpr.CelStruct.Entry entry : createStruct.entries()) { - TranslatedValue entryTv = translateExpr(entry.value(), ast); - Expr val = entryTv.z3Expr(); - if (entry.optionalEntry()) { - Expr checkedVal = - typeSystem.withRuntimeError(val, ctx.mkNot(typeSystem.isOptional(val))); - entryTv = - TranslatedValue.create(checkedVal, entry.value(), typeSystem, entryTv.isApproximate()); - Expr optRef = typeSystem.getOptionalRef(checkedVal); - BoolExpr hasValue = typeSystem.optHasValue(optRef); - currentVal = ctx.mkITE(hasValue, typeSystem.getOptionalValue(optRef), currentVal); - } else { - currentVal = val; - } - entryTvs.add(entryTv); - } + Expr currentVal = + resolveStructFieldValue( + createStruct, VALUE_FIELD, getDefaultValueForType(targetType), ast, entryTvs); BoolExpr validValue = typeConstraintGenerator.createTypeConstraintForType(currentVal, targetType); if (typeName.equals(CelTypes.INT32_WRAPPER_MESSAGE)) { @@ -390,29 +434,16 @@ private Expr resolveStructFieldValue( Expr defaultValue, CelAbstractSyntaxTree ast, List entryTvs) { - return Streams.findLast( - createStruct.entries().stream().filter(entry -> entry.fieldKey().equals(fieldName))) - .>map( - entry -> { - TranslatedValue entryTv = translateExpr(entry.value(), ast); - Expr val = entryTv.z3Expr(); - if (entry.optionalEntry()) { - Expr checkedVal = - typeSystem.withRuntimeError(val, ctx.mkNot(typeSystem.isOptional(val))); - entryTv = - TranslatedValue.create( - checkedVal, entry.value(), typeSystem, entryTv.isApproximate()); - Expr optRef = typeSystem.getOptionalRef(checkedVal); - val = - ctx.mkITE( - typeSystem.optHasValue(optRef), - typeSystem.getOptionalValue(optRef), - defaultValue); - } - entryTvs.add(entryTv); - return val; - }) - .orElse(defaultValue); + Expr currentVal = defaultValue; + for (CelExpr.CelStruct.Entry entryAst : createStruct.entries()) { + if (!entryAst.fieldKey().equals(fieldName)) { + continue; + } + StructEntry entry = translateEntry(entryAst, ast); + entryTvs.add(entry.valueTv); + currentVal = ctx.mkITE(entry.hasValue, entry.value, defaultValue); + } + return currentVal; } // TODO: proto2 fields with a custom default read as their type's zero value. diff --git a/verifier/src/main/java/dev/cel/verifier/CelZ3TranslationContext.java b/verifier/src/main/java/dev/cel/verifier/CelZ3TranslationContext.java index ff5d80ab1..ee5594c10 100644 --- a/verifier/src/main/java/dev/cel/verifier/CelZ3TranslationContext.java +++ b/verifier/src/main/java/dev/cel/verifier/CelZ3TranslationContext.java @@ -21,6 +21,8 @@ import com.microsoft.z3.Context; import com.microsoft.z3.Expr; import com.microsoft.z3.Model; +import dev.cel.common.CelAbstractSyntaxTree; +import dev.cel.common.ast.CelExpr.ExprKind; import dev.cel.common.types.CelType; import dev.cel.common.types.SimpleType; import java.util.ArrayList; @@ -102,6 +104,13 @@ CelType guaranteedType(Expr value) { return inputVariableTypes.getOrDefault(value, SimpleType.DYN); } + /** Returns a constant's type, or an input variable's declared type, or else dyn. */ + CelType guaranteedType(TranslatedValue val, CelAbstractSyntaxTree ast) { + return val.isLiteral(ExprKind.Kind.CONSTANT) + ? val.staticType(ast) + : guaranteedType(val.z3Expr()); + } + /** * Whether {@code val} is a map with more keys than the unroll limit, beyond which its presence is * not linked to its keys. diff --git a/verifier/src/main/java/dev/cel/verifier/CelZ3TypeConstraintGenerator.java b/verifier/src/main/java/dev/cel/verifier/CelZ3TypeConstraintGenerator.java index 386e2f6f6..1d1687242 100644 --- a/verifier/src/main/java/dev/cel/verifier/CelZ3TypeConstraintGenerator.java +++ b/verifier/src/main/java/dev/cel/verifier/CelZ3TypeConstraintGenerator.java @@ -24,6 +24,7 @@ import dev.cel.common.CelAbstractSyntaxTree; import dev.cel.common.types.CelKind; import dev.cel.common.types.CelType; +import dev.cel.common.types.EnumType; import dev.cel.common.types.ListType; import dev.cel.common.types.MapType; import dev.cel.common.types.NullableType; @@ -75,6 +76,13 @@ BoolExpr createTypeConstraintForType(Expr val, CelType type) { IntExpr unwrapped = typeSystem.getInt(val); return ctx.mkAnd(typeSystem.isInt(val), ctx.mkNot(typeSystem.checkIntOverflow(unwrapped))); } + if (type instanceof EnumType) { + IntExpr unwrapped = typeSystem.getInt(val); + return ctx.mkAnd( + typeSystem.isInt(val), + ctx.mkGe(unwrapped, ctx.mkInt(Integer.MIN_VALUE)), + ctx.mkLe(unwrapped, ctx.mkInt(Integer.MAX_VALUE))); + } if (type.equals(SimpleType.UINT)) { IntExpr unwrapped = typeSystem.getUint(val); return ctx.mkAnd(typeSystem.isUint(val), ctx.mkNot(typeSystem.checkUintOverflow(unwrapped))); @@ -194,6 +202,9 @@ BoolExpr createTypeConstraintForType(Expr val, CelType type) { return CelZ3Exprs.mkAndFlattened(ctx, boundsAndTypes); } + if (type.kind() == CelKind.TYPE) { + return ctx.mkAnd(typeSystem.isType(val), typeSystem.isValidScalar(val)); + } if (type.kind() == CelKind.STRUCT) { return ctx.mkAnd( typeSystem.isMessage(val), diff --git a/verifier/src/main/java/dev/cel/verifier/CelZ3TypeSystem.java b/verifier/src/main/java/dev/cel/verifier/CelZ3TypeSystem.java index f5fd569cc..10445db38 100644 --- a/verifier/src/main/java/dev/cel/verifier/CelZ3TypeSystem.java +++ b/verifier/src/main/java/dev/cel/verifier/CelZ3TypeSystem.java @@ -18,6 +18,7 @@ import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableSet; import com.google.common.collect.ObjectArrays; import com.google.common.math.DoubleMath; import com.google.common.primitives.UnsignedLongs; @@ -100,6 +101,10 @@ public final class CelZ3TypeSystem { private static final String IS_STRING = "isString"; private static final String GET_STRING = "getString"; + private static final String CONS_TYPE = "CelType"; + private static final String IS_TYPE = "isType"; + private static final String GET_TYPE = "getType"; + private static final String CONS_BYTES = "Bytes"; private static final String IS_BYTES = "isBytes"; private static final String GET_BYTES = "getBytes"; @@ -168,6 +173,7 @@ public final class CelZ3TypeSystem { private final Constructor doubleCons; private final Constructor stringCons; private final Constructor bytesCons; + private final Constructor typeCons; private final Constructor timestampCons; private final Constructor durationCons; private final Constructor errorCons; @@ -200,6 +206,10 @@ public final class CelZ3TypeSystem { private final FuncDecl hasFractionFunc; // Doubles whose truncation and fraction are still uninterpreted, in order of first use. private final Set undefinedDoubles; + // The names of the runtime types the environment declares. + private final ImmutableSet typeNames; + // Valid values that preferKnownTypeNamesOver may still steer away from unknown type names. + private final Set> unrestrictedTypeValues; private final boolean parameterizeUnknowns; @@ -264,6 +274,10 @@ Constructor bytesCons() { return bytesCons; } + Constructor typeCons() { + return typeCons; + } + Constructor timestampCons() { return timestampCons; } @@ -435,6 +449,21 @@ public Expr mkString(String val) { return ctx.mkApp(stringCons.ConstructorDecl(), ctx.mkString(val)); } + /** Creates a CelValue for the type named {@code name}. */ + public Expr mkType(String name) { + return wrapType(ctx.mkString(name)); + } + + /** Wraps a Z3 string type name into a CelValue type. */ + public Expr wrapType(Expr name) { + return ctx.mkApp(typeCons.ConstructorDecl(), name); + } + + /** Checks if the given CelValue is a type. */ + public BoolExpr isType(Expr val) { + return (BoolExpr) ctx.mkApp(typeCons.getTesterDecl(), val); + } + /** Creates a CelValue containing bytes. */ public Expr mkBytes(String val) { return ctx.mkApp(bytesCons.ConstructorDecl(), ctx.mkString(val)); @@ -822,6 +851,7 @@ public BoolExpr checkDurationOverflow(ArithExpr result) { *

Values of other kinds always qualify. */ BoolExpr isValidScalar(Expr val) { + unrestrictedTypeValues.add(val); FPExpr d = getDouble(val); return CelZ3Exprs.mkAndFlattened( ctx, @@ -1006,6 +1036,30 @@ ImmutableList defineDoublesContradictedBy(Model model) { return definitions.build(); } + /** + * Returns assumptions that the valid values {@code model} makes types of unknown names (bogus in + * a witness) have known names instead. They only pick a better model: constraining every value + * eagerly slows the solver down a lot, and an unknown name may still be real. + */ + ImmutableList preferKnownTypeNamesOver(Model model) { + ImmutableList.Builder constraints = ImmutableList.builder(); + for (Iterator> it = unrestrictedTypeValues.iterator(); it.hasNext(); ) { + Expr val = it.next(); + Expr value = model.evaluate(val, /* completion= */ true); + if (value.getFuncDecl().equals(typeCons.ConstructorDecl()) + && !typeNames.contains(value.getArgs()[0].getString())) { + it.remove(); + Expr name = ctx.mkApp(typeCons.getAccessorDecls()[0], val); + constraints.add( + ctx.mkOr( + typeNames.stream() + .map(n -> ctx.mkEq(name, ctx.mkString(n))) + .toArray(BoolExpr[]::new))); + } + } + return constraints.build(); + } + /** Converts a Z3 double to the Java double with the same IEEE 754 bits (or NaN). */ double toJavaDouble(FPNum fpNum) { // Z3 doesn't simplify the bits of NaN to a numeral. @@ -1082,7 +1136,7 @@ private static FuncDeclKey create(String name, Sort[] domain, Sort range) { } } - CelZ3TypeSystem(Context ctx, boolean parameterizeUnknowns) { + CelZ3TypeSystem(Context ctx, boolean parameterizeUnknowns, ImmutableSet typeNames) { this.ctx = ctx; this.funcDeclCache = new HashMap<>(); this.boolCons = @@ -1113,6 +1167,9 @@ private static FuncDeclKey create(String name, Sort[] domain, Sort range) { this.bytesCons = ctx.mkConstructor( CONS_BYTES, IS_BYTES, new String[] {GET_BYTES}, new Sort[] {ctx.getStringSort()}, null); + this.typeCons = + ctx.mkConstructor( + CONS_TYPE, IS_TYPE, new String[] {GET_TYPE}, new Sort[] {ctx.getStringSort()}, null); this.timestampCons = ctx.mkConstructor( CONS_TIMESTAMP, @@ -1173,6 +1230,7 @@ private static FuncDeclKey create(String name, Sort[] domain, Sort range) { this.doubleCons, this.stringCons, this.bytesCons, + this.typeCons, this.timestampCons, this.durationCons, this.errorCons, @@ -1231,6 +1289,8 @@ private static FuncDeclKey create(String name, Sort[] domain, Sort range) { this.hasFractionFunc = ctx.mkFuncDecl(FUNC_HAS_FRACTION, ctx.mkFPSortDouble(), ctx.getBoolSort()); this.undefinedDoubles = new LinkedHashSet<>(); + this.typeNames = typeNames; + this.unrestrictedTypeValues = new LinkedHashSet<>(); this.parameterizeUnknowns = parameterizeUnknowns; } } diff --git a/verifier/src/main/java/dev/cel/verifier/ListValueModel.java b/verifier/src/main/java/dev/cel/verifier/ListValueModel.java new file mode 100644 index 000000000..fa716e5a1 --- /dev/null +++ b/verifier/src/main/java/dev/cel/verifier/ListValueModel.java @@ -0,0 +1,119 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package dev.cel.verifier; + +import com.microsoft.z3.BoolExpr; +import com.microsoft.z3.Context; +import com.microsoft.z3.Expr; +import com.microsoft.z3.IntExpr; +import com.microsoft.z3.SeqExpr; +import dev.cel.common.CelAbstractSyntaxTree; +import dev.cel.common.ast.CelExpr.ExprKind; +import dev.cel.common.types.CelKind; +import dev.cel.common.types.CelType; +import dev.cel.common.types.ListType; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** Lists, which compare element-wise. */ +final class ListValueModel implements ValueModel { + private final Context ctx; + private final CelZ3TypeSystem typeSystem; + private final CelZ3TranslationContext context; + + @Override + public boolean hasKind(CelType type) { + return type.kind() == CelKind.LIST; + } + + @Override + public BoolExpr is(Expr value) { + return typeSystem.isList(value); + } + + @Override + public BoolExpr equal( + TranslatedValue a, + TranslatedValue b, + CelAbstractSyntaxTree ast, + List taints, + CelZ3Equality equality) { + boolean isLiteralA = isFixedLengthListLiteral(a); + boolean isLiteralB = isFixedLengthListLiteral(b); + boolean isLiteral = isLiteralA || isLiteralB; + SeqExpr seq0 = typeSystem.getSeq(typeSystem.getListRef(a.z3Expr())); + SeqExpr seq1 = typeSystem.getSeq(typeSystem.getListRef(b.z3Expr())); + IntExpr length = ctx.mkLength(seq0); + + List equalities = new ArrayList<>(); + equalities.add(ctx.mkEq(length, ctx.mkLength(seq1))); + int size = + isLiteral + ? (isLiteralA ? a : b).celExpr().get().list().elements().size() + : context.comprehensionUnrollLimit(); + if (!isLiteral) { + equalities.add(equality.approximatePastUnrollLimit(length, a.z3Expr(), b.z3Expr(), taints)); + } + for (int i = 0; i < size; i++) { + TranslatedValue elemA = element(a, seq0, i, isLiteralA, ast); + TranslatedValue elemB = element(b, seq1, i, isLiteralB, ast); + TranslatedValue elemEquality = + equality.translate(elemA, elemB, ast, /* isEquals= */ true, /* shallow= */ !isLiteral); + BoolExpr inBounds = ctx.mkLt(ctx.mkInt(i), length); + equalities.add(ctx.mkImplies(inBounds, typeSystem.isTrue(elemEquality.z3Expr()))); + taints.add(ctx.mkAnd(inBounds, elemEquality.isApproximate())); + } + return CelZ3Exprs.mkAndFlattened(ctx, equalities); + } + + /** A literal with optional elements has as many elements as are present, so no fixed length. */ + static boolean isFixedLengthListLiteral(TranslatedValue list) { + return list.isLiteral(ExprKind.Kind.LIST) + && list.celExpr().get().list().optionalIndices().isEmpty(); + } + + /** Element i of list, typed by the literal's element if list is a literal. */ + TranslatedValue element( + TranslatedValue list, SeqExpr seq, int i, boolean isLiteral, CelAbstractSyntaxTree ast) { + Expr elem = ctx.mkNth(seq, ctx.mkInt(i)); + // A literal's elements are already CEL values (performance only). + if (!isLiteral) { + BoolExpr inBounds = ctx.mkLt(ctx.mkInt(i), ctx.mkLength(seq)); + context.constrainValidValue(ctx.mkAnd(typeSystem.isList(list.z3Expr()), inBounds), elem); + CelType listType = context.guaranteedType(list, ast); + // Type constraints are only unrolled up to the limit. + if (i >= context.comprehensionUnrollLimit() && listType instanceof ListType) { + context.addConstraint( + ctx.mkImplies( + inBounds, + context + .typeConstraintGenerator() + .createTypeConstraintForType(elem, ((ListType) listType).elemType()))); + } + } + return TranslatedValue.create( + elem, + isLiteral ? list.listElementAt(i) : Optional.empty(), + typeSystem, + list.isApproximate()); + } + + ListValueModel(CelZ3TranslationContext context) { + this.ctx = context.ctx(); + this.typeSystem = context.typeSystem(); + this.context = context; + } +} diff --git a/verifier/src/main/java/dev/cel/verifier/MapValueModel.java b/verifier/src/main/java/dev/cel/verifier/MapValueModel.java new file mode 100644 index 000000000..383ca85b6 --- /dev/null +++ b/verifier/src/main/java/dev/cel/verifier/MapValueModel.java @@ -0,0 +1,188 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package dev.cel.verifier; + +import com.google.common.collect.ImmutableList; +import com.microsoft.z3.ArrayExpr; +import com.microsoft.z3.BoolExpr; +import com.microsoft.z3.Context; +import com.microsoft.z3.Expr; +import com.microsoft.z3.IntExpr; +import com.microsoft.z3.SeqExpr; +import dev.cel.common.CelAbstractSyntaxTree; +import dev.cel.common.ast.CelExpr; +import dev.cel.common.ast.CelExpr.ExprKind; +import dev.cel.common.types.CelKind; +import dev.cel.common.types.CelType; +import dev.cel.common.types.MapType; +import dev.cel.common.types.SimpleType; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** Maps, which compare by their keys and the values at them. */ +@SuppressWarnings({"unchecked", "rawtypes"}) // Z3 Java API uses raw types. +final class MapValueModel implements ValueModel { + private static final MapType DYN_MAP = MapType.create(SimpleType.DYN, SimpleType.DYN); + + private final Context ctx; + private final CelZ3TypeSystem typeSystem; + private final CelZ3TranslationContext context; + + @Override + public boolean hasKind(CelType type) { + return type.kind() == CelKind.MAP; + } + + @Override + public BoolExpr is(Expr value) { + return typeSystem.isMap(value); + } + + @Override + public BoolExpr equal( + TranslatedValue a, + TranslatedValue b, + CelAbstractSyntaxTree ast, + List taints, + CelZ3Equality equality) { + return CelZ3Equality.isExact(a.staticType(ast), b.staticType(ast)) + && (a.isLiteral(ExprKind.Kind.MAP) || b.isLiteral(ExprKind.Kind.MAP)) + ? equalAtLiteralKeys(a, b) + : unrolledEqual(a, b, ast, taints, equality); + } + + // Unrolled over a map literal's keys, or else a's up to the unroll limit: the other map has as + // many keys, and an equal key and value for each. + private BoolExpr unrolledEqual( + TranslatedValue a, + TranslatedValue b, + CelAbstractSyntaxTree ast, + List taints, + CelZ3Equality equality) { + boolean isLiteral = a.isLiteral(ExprKind.Kind.MAP) || b.isLiteral(ExprKind.Kind.MAP); + // Prefer a literal whose values are list or map literals, which compare element-wise. + boolean isMapA = + !b.isLiteral(ExprKind.Kind.MAP) + || (a.isLiteral(ExprKind.Kind.MAP) + && b.celExpr().get().map().entries().stream() + .noneMatch(e -> TranslatedValue.isContainerLiteral(e.value()))); + TranslatedValue map = isMapA ? a : b; + TranslatedValue otherMap = isMapA ? b : a; + Expr other = otherMap.z3Expr(); + BoolExpr isOtherMap = typeSystem.isMap(other); + Expr mapRef = typeSystem.getMapRef(map.z3Expr()); + SeqExpr keys = typeSystem.getMapKeys(mapRef); + ArrayExpr values = (ArrayExpr) typeSystem.getMapValues(mapRef); + IntExpr length = ctx.mkLength(keys); + Expr otherRef = typeSystem.getMapRef(other); + SeqExpr otherKeys = typeSystem.getMapKeys(otherRef); + + List equalities = new ArrayList<>(); + equalities.add(ctx.mkEq(length, ctx.mkLength(otherKeys))); + ImmutableList entries = + isLiteral ? map.celExpr().get().map().entries() : ImmutableList.of(); + // The keys are in entry order unless an optional entry is absent (repeated keys are errors). + boolean inEntryOrder = + isLiteral && entries.stream().noneMatch(CelExpr.CelMap.Entry::optionalEntry); + int size = isLiteral ? entries.size() : context.comprehensionUnrollLimit(); + if (!isLiteral) { + equalities.add(equality.approximatePastUnrollLimit(length, map.z3Expr(), other, taints)); + // A map that isn't a literal or of a declared map type isn't otherwise known to be + // well-formed (distinct keys matching its presence, valid keys and values). + for (TranslatedValue operand : ImmutableList.of(a, b)) { + if (!(context.guaranteedType(operand, ast) instanceof MapType)) { + context.addConstraint( + ctx.mkImplies( + typeSystem.isMap(operand.z3Expr()), + context + .typeConstraintGenerator() + .createTypeConstraintForType(operand.z3Expr(), DYN_MAP))); + } + } + } + for (int i = 0; i < size; i++) { + BoolExpr inBounds = ctx.mkLt(ctx.mkInt(i), length); + Expr key = ctx.mkNth(keys, ctx.mkInt(i)).simplify(); + ImmutableList equalKeys = typeSystem.equalKeys(key); + BoolExpr hasKey = typeSystem.hasEqualKey(other, equalKeys); + Expr otherValue = typeSystem.valueAtEqualKey(other, equalKeys); + context.constrainValidValue(ctx.mkAnd(isOtherMap, inBounds, hasKey), otherValue); + TranslatedValue valueEquality = + equality.translate( + TranslatedValue.create( + ctx.mkSelect(values, key), + inEntryOrder ? Optional.of(entries.get(i).value()) : Optional.empty(), + typeSystem, + map.isApproximate()), + TranslatedValue.create(otherValue, typeSystem, otherMap.isApproximate()), + ast, + /* isEquals= */ true, + /* shallow= */ !isLiteral); + taints.add(ctx.mkAnd(inBounds, valueEquality.isApproximate())); + equalities.add( + ctx.mkImplies(inBounds, ctx.mkAnd(hasKey, typeSystem.isTrue(valueEquality.z3Expr())))); + } + if (isLiteral) { + // The other map's keys are exactly the present ones, so each equals a literal key: as many + // as the literal's, which are all present. + ArrayExpr presence = ctx.mkConstArray(typeSystem.celValueSort(), ctx.mkFalse()); + for (int j = 0; j < entries.size(); j++) { + Expr otherKey = ctx.mkNth(otherKeys, ctx.mkInt(j)); + presence = + (ArrayExpr) + ctx.mkITE( + ctx.mkLt(ctx.mkInt(j), length), + ctx.mkStore(presence, otherKey, ctx.mkTrue()), + presence); + } + equalities.add(ctx.mkEq(typeSystem.getMapPresence(otherRef), presence)); + } + return CelZ3Exprs.mkAndFlattened(ctx, equalities); + } + + // Maps whose keys and values compare by their terms are equal when they have the same keys, and + // the same values at the literal's keys (performance only). + private BoolExpr equalAtLiteralKeys(TranslatedValue a, TranslatedValue b) { + boolean isLiteralA = a.isLiteral(ExprKind.Kind.MAP); + Expr literalRef = typeSystem.getMapRef((isLiteralA ? a : b).z3Expr()); + Expr otherRef = typeSystem.getMapRef((isLiteralA ? b : a).z3Expr()); + SeqExpr keys = typeSystem.getMapKeys(literalRef); + ArrayExpr values = (ArrayExpr) typeSystem.getMapValues(literalRef); + ArrayExpr otherValues = (ArrayExpr) typeSystem.getMapValues(otherRef); + List equalities = new ArrayList<>(); + // Same size and same keys. Past the unroll limit, a map's presence isn't tied to its keys, so + // matching presence alone doesn't rule out extra keys (e.g. a 6-key map equal to {'a': 1}). + equalities.add(ctx.mkEq(ctx.mkLength(keys), ctx.mkLength(typeSystem.getMapKeys(otherRef)))); + equalities.add( + ctx.mkEq(typeSystem.getMapPresence(literalRef), typeSystem.getMapPresence(otherRef))); + int size = (isLiteralA ? a : b).celExpr().get().map().entries().size(); + for (int i = 0; i < size; i++) { + Expr key = ctx.mkNth(keys, ctx.mkInt(i)); + equalities.add( + ctx.mkImplies( + ctx.mkLt(ctx.mkInt(i), ctx.mkLength(keys)), + typeSystem.getStructuralEquality( + ctx.mkSelect(values, key), ctx.mkSelect(otherValues, key)))); + } + return CelZ3Exprs.mkAndFlattened(ctx, equalities); + } + + MapValueModel(CelZ3TranslationContext context) { + this.ctx = context.ctx(); + this.typeSystem = context.typeSystem(); + this.context = context; + } +} diff --git a/verifier/src/main/java/dev/cel/verifier/NumericValueModel.java b/verifier/src/main/java/dev/cel/verifier/NumericValueModel.java new file mode 100644 index 000000000..0a7f152f7 --- /dev/null +++ b/verifier/src/main/java/dev/cel/verifier/NumericValueModel.java @@ -0,0 +1,209 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package dev.cel.verifier; + +import com.microsoft.z3.BoolExpr; +import com.microsoft.z3.Context; +import com.microsoft.z3.Expr; +import com.microsoft.z3.FPExpr; +import com.microsoft.z3.IntExpr; +import dev.cel.common.CelAbstractSyntaxTree; +import dev.cel.common.ast.CelConstant; +import dev.cel.common.types.CelKind; +import dev.cel.common.types.CelType; +import dev.cel.common.types.NullableType; +import java.util.List; +import java.util.Optional; + +/** Ints, uints and doubles, which compare numerically across kinds. */ +final class NumericValueModel implements ValueModel { + private final Context ctx; + private final CelZ3TypeSystem typeSystem; + private final CelZ3TranslationContext context; + + /** Excludes wrappers, whose kind is their value's but which may also be null. */ + @Override + public boolean hasKind(CelType type) { + CelKind kind = type.kind(); + return !(type instanceof NullableType) + && (kind == CelKind.INT || kind == CelKind.UINT || kind == CelKind.DOUBLE); + } + + @Override + public BoolExpr is(Expr value) { + return ctx.mkOr(typeSystem.isInt(value), typeSystem.isUint(value), typeSystem.isDouble(value)); + } + + @Override + public BoolExpr equal( + TranslatedValue a, + TranslatedValue b, + CelAbstractSyntaxTree ast, + List taints, + CelZ3Equality equality) { + return equal(a, b, ast, taints, equality, /* approximateIntDouble= */ false); + } + + /** Like {@code equal}, but ints and doubles compare approximately if approximateIntDouble. */ + BoolExpr equal( + TranslatedValue a, + TranslatedValue b, + CelAbstractSyntaxTree ast, + List taints, + CelZ3Equality equality, + boolean approximateIntDouble) { + if (a.isNumericConstant()) { + return equalWithConstant(b.z3Expr(), a.celExpr().get().constant(), b.staticType(ast)); + } else if (b.isNumericConstant()) { + return equalWithConstant(a.z3Expr(), b.celExpr().get().constant(), a.staticType(ast)); + } + CelType type0 = a.staticType(ast); + if (CelZ3OperatorTranslator.isStaticallyKnown(type0) + && type0.kind() == b.staticType(ast).kind()) { + return equalSameKind(a.z3Expr(), type0, b.z3Expr()); + } + return equalDynamic(a.z3Expr(), b.z3Expr(), taints, equality, approximateIntDouble); + } + + private BoolExpr equalWithConstant(Expr symVal, CelConstant constant, CelType symType) { + Optional intRange = Optional.empty(); + Optional uintRange = Optional.empty(); + double doubleVal; + if (constant.getKind() == CelConstant.Kind.INT64_VALUE) { + long vInt = constant.int64Value(); + intRange = Optional.of(CelNumericBounds.IntRange.of(vInt, vInt)); + if (vInt >= 0) { + uintRange = + Optional.of(CelNumericBounds.UintRange.of(Long.toString(vInt), Long.toString(vInt))); + } + doubleVal = (double) vInt; + } else if (constant.getKind() == CelConstant.Kind.UINT64_VALUE) { + long vUint = constant.uint64Value().longValue(); + if (vUint >= 0) { + intRange = Optional.of(CelNumericBounds.IntRange.of(vUint, vUint)); + } + String uStr = constant.uint64Value().toString(); + uintRange = Optional.of(CelNumericBounds.UintRange.of(uStr, uStr)); + doubleVal = constant.uint64Value().doubleValue(); + } else { + doubleVal = constant.doubleValue(); + intRange = CelNumericBounds.getMatchingIntRange(doubleVal); + uintRange = CelNumericBounds.getMatchingUintRange(doubleVal); + } + switch (symType.kind()) { + case INT: + return inIntRange(intRange, typeSystem.getInt(symVal)); + case UINT: + return inUintRange(uintRange, typeSystem.getUint(symVal)); + case DOUBLE: + return ctx.mkFPEq(typeSystem.getDouble(symVal), typeSystem.mkFpDouble(doubleVal)); + default: + return (BoolExpr) + CelZ3Exprs.SwitchBuilder.newBuilder(ctx) + .addCase(typeSystem.isInt(symVal), inIntRange(intRange, typeSystem.getInt(symVal))) + .addCase( + typeSystem.isUint(symVal), inUintRange(uintRange, typeSystem.getUint(symVal))) + .addCase( + typeSystem.isDouble(symVal), + ctx.mkFPEq(typeSystem.getDouble(symVal), typeSystem.mkFpDouble(doubleVal))) + .build(ctx.mkFalse()); + } + } + + private BoolExpr inIntRange(Optional range, IntExpr n) { + return range + .map(r -> ctx.mkAnd(ctx.mkGe(n, ctx.mkInt(r.min())), ctx.mkLe(n, ctx.mkInt(r.max())))) + .orElseGet(ctx::mkFalse); + } + + private BoolExpr inUintRange(Optional range, IntExpr n) { + return range + .map(r -> ctx.mkAnd(ctx.mkGe(n, ctx.mkInt(r.min())), ctx.mkLe(n, ctx.mkInt(r.max())))) + .orElseGet(ctx::mkFalse); + } + + private BoolExpr equalSameKind(Expr z3Expr0, CelType type0, Expr z3Expr1) { + switch (type0.kind()) { + case INT: + return ctx.mkEq(typeSystem.getInt(z3Expr0), typeSystem.getInt(z3Expr1)); + case UINT: + return ctx.mkEq(typeSystem.getUint(z3Expr0), typeSystem.getUint(z3Expr1)); + case DOUBLE: + return ctx.mkFPEq(typeSystem.getDouble(z3Expr0), typeSystem.getDouble(z3Expr1)); + default: + return ctx.mkFalse(); + } + } + + private BoolExpr equalDynamic( + Expr z3Expr0, + Expr z3Expr1, + List taints, + CelZ3Equality equality, + boolean approximateIntDouble) { + BoolExpr isIntOrUint0 = ctx.mkOr(typeSystem.isInt(z3Expr0), typeSystem.isUint(z3Expr0)); + BoolExpr isIntOrUint1 = ctx.mkOr(typeSystem.isInt(z3Expr1), typeSystem.isUint(z3Expr1)); + BoolExpr bothIntOrUint = ctx.mkAnd(isIntOrUint0, isIntOrUint1); + IntExpr val0 = guardedInt(z3Expr0); + IntExpr val1 = guardedInt(z3Expr1); + BoolExpr bothDouble = ctx.mkAnd(typeSystem.isDouble(z3Expr0), typeSystem.isDouble(z3Expr1)); + BoolExpr isIntOrUintAndDouble = ctx.mkAnd(isIntOrUint0, typeSystem.isDouble(z3Expr1)); + BoolExpr isDoubleAndIntOrUint = ctx.mkAnd(typeSystem.isDouble(z3Expr0), isIntOrUint1); + + CelZ3Exprs.SwitchBuilder numericEquality = + CelZ3Exprs.SwitchBuilder.newBuilder(ctx) + .addCase(bothIntOrUint, ctx.mkEq(val0, val1)) + .addCase( + bothDouble, + ctx.mkFPEq(typeSystem.getDouble(z3Expr0), typeSystem.getDouble(z3Expr1))); + if (approximateIntDouble) { + return equality.approximateEqualityWhere( + context.recordApproximation( + "comparisons of ints with doubles read out of lists and maps", + ctx.mkOr(isIntOrUintAndDouble, isDoubleAndIntOrUint)), + z3Expr0, + z3Expr1, + /* exact= */ (BoolExpr) numericEquality.build(ctx.mkFalse()), + taints); + } + return (BoolExpr) + numericEquality + .addCase(isIntOrUintAndDouble, typeSystem.intEqDouble(val0, guardedDouble(z3Expr1))) + .addCase(isDoubleAndIntOrUint, typeSystem.intEqDouble(val1, guardedDouble(z3Expr0))) + .build(ctx.mkFalse()); + } + + // An int or uint's value, else 0: reading a uint out of a double makes the OSS solver incomplete. + private IntExpr guardedInt(Expr z3Expr) { + return (IntExpr) + ctx.mkITE( + typeSystem.isInt(z3Expr), + typeSystem.getInt(z3Expr), + ctx.mkITE(typeSystem.isUint(z3Expr), typeSystem.getUint(z3Expr), ctx.mkInt(0))); + } + + // A double's value, else 0.0, which the int/double comparisons never need to define. + private FPExpr guardedDouble(Expr z3Expr) { + return (FPExpr) + ctx.mkITE( + typeSystem.isDouble(z3Expr), typeSystem.getDouble(z3Expr), typeSystem.mkFpDouble(0.0)); + } + + NumericValueModel(CelZ3TranslationContext context) { + this.ctx = context.ctx(); + this.typeSystem = context.typeSystem(); + this.context = context; + } +} diff --git a/verifier/src/main/java/dev/cel/verifier/OptionalValueModel.java b/verifier/src/main/java/dev/cel/verifier/OptionalValueModel.java new file mode 100644 index 000000000..a069f5b65 --- /dev/null +++ b/verifier/src/main/java/dev/cel/verifier/OptionalValueModel.java @@ -0,0 +1,98 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package dev.cel.verifier; + +import com.google.common.collect.ImmutableList; +import com.microsoft.z3.BoolExpr; +import com.microsoft.z3.Context; +import com.microsoft.z3.Expr; +import dev.cel.common.CelAbstractSyntaxTree; +import dev.cel.common.ast.CelExpr; +import dev.cel.common.ast.CelExpr.ExprKind; +import dev.cel.common.ast.CelReference; +import dev.cel.common.types.CelType; +import dev.cel.common.types.OptionalType; +import java.util.List; +import java.util.Optional; + +/** Optionals, which are equal when both are empty or both hold CEL-equal values. */ +final class OptionalValueModel implements ValueModel { + private final Context ctx; + private final CelZ3TypeSystem typeSystem; + private final CelZ3TranslationContext context; + + @Override + public boolean hasKind(CelType type) { + return type instanceof OptionalType; + } + + @Override + public BoolExpr is(Expr value) { + return typeSystem.isOptional(value); + } + + @Override + public BoolExpr equal( + TranslatedValue a, + TranslatedValue b, + CelAbstractSyntaxTree ast, + List taints, + CelZ3Equality equality) { + Expr ref0 = typeSystem.getOptionalRef(a.z3Expr()); + Expr ref1 = typeSystem.getOptionalRef(b.z3Expr()); + BoolExpr hasValue0 = typeSystem.optHasValue(ref0); + BoolExpr hasValue1 = typeSystem.optHasValue(ref1); + TranslatedValue valueEquality = + equality.translate( + value(a, ref0, ast), + value(b, ref1, ast), + ast, + /* isEquals= */ true, + /* shallow= */ false); + taints.add( + ctx.mkAnd( + ctx.mkAnd(is(a.z3Expr()), is(b.z3Expr())), + hasValue0, + hasValue1, + valueEquality.isApproximate())); + return ctx.mkAnd( + ctx.mkEq(hasValue0, hasValue1), + ctx.mkImplies(hasValue0, typeSystem.isTrue(valueEquality.z3Expr()))); + } + + // opt's value, typed by its argument if opt is an `optional.of` call. + private TranslatedValue value(TranslatedValue opt, Expr ref, CelAbstractSyntaxTree ast) { + Optional arg = + opt.celExpr() + .filter(e -> + ast.getReference(e.id()) + .map(CelReference::overloadIds) + .equals(Optional.of(ImmutableList.of("optional_of")))) + .map(e -> e.call().args().get(0)); + // A variable keeps its own term, so its declared type is still trusted. + Expr value = + arg.filter(e -> e.getKind() == ExprKind.Kind.IDENT) + .flatMap(e -> context.lookupSymbol(e.ident().name())) + .>map(TranslatedValue::z3Expr) + .orElseGet(() -> typeSystem.getOptionalValue(ref)); + return TranslatedValue.create(value, arg, typeSystem, /* isApproximate= */ ctx.mkFalse()); + } + + OptionalValueModel(CelZ3TranslationContext context) { + this.ctx = context.ctx(); + this.typeSystem = context.typeSystem(); + this.context = context; + } +} diff --git a/verifier/src/main/java/dev/cel/verifier/TranslatedValue.java b/verifier/src/main/java/dev/cel/verifier/TranslatedValue.java index 201739f66..5d1e36d85 100644 --- a/verifier/src/main/java/dev/cel/verifier/TranslatedValue.java +++ b/verifier/src/main/java/dev/cel/verifier/TranslatedValue.java @@ -18,9 +18,12 @@ import com.microsoft.z3.BoolExpr; import com.microsoft.z3.Context; import com.microsoft.z3.Expr; +import dev.cel.common.CelAbstractSyntaxTree; import dev.cel.common.ast.CelConstant; import dev.cel.common.ast.CelExpr; import dev.cel.common.ast.CelExpr.ExprKind; +import dev.cel.common.types.CelType; +import dev.cel.common.types.SimpleType; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -43,6 +46,15 @@ boolean isLiteral(ExprKind.Kind kind) { return celExpr().map(node -> node.exprKind().getKind() == kind).orElse(false); } + static boolean isContainerLiteral(CelExpr expr) { + return expr.getKind() == ExprKind.Kind.LIST || expr.getKind() == ExprKind.Kind.MAP; + } + + /** The checked type of the AST node, or dyn without one. */ + CelType staticType(CelAbstractSyntaxTree ast) { + return celExpr().map(node -> ast.getTypeOrThrow(node.id())).orElse(SimpleType.DYN); + } + /** Safely extracts a list element AST if it exists */ Optional listElementAt(int index) { return celExpr() diff --git a/verifier/src/main/java/dev/cel/verifier/ValueModel.java b/verifier/src/main/java/dev/cel/verifier/ValueModel.java new file mode 100644 index 000000000..d7ce0b339 --- /dev/null +++ b/verifier/src/main/java/dev/cel/verifier/ValueModel.java @@ -0,0 +1,39 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package dev.cel.verifier; + +import com.microsoft.z3.BoolExpr; +import com.microsoft.z3.Expr; +import dev.cel.common.CelAbstractSyntaxTree; +import dev.cel.common.types.CelType; +import java.util.List; + +/** The CEL semantics of one kind of value, like a {@code CelValue} subclass. */ +interface ValueModel { + boolean hasKind(CelType type); + + BoolExpr is(Expr value); + + /** + * CEL equality of {@code a} and {@code b}, read only where both are of this kind. Approximations + * may be added to {@code taints} unguarded by kind. + */ + BoolExpr equal( + TranslatedValue a, + TranslatedValue b, + CelAbstractSyntaxTree ast, + List taints, + CelZ3Equality equality); +} diff --git a/verifier/src/main/java/dev/cel/verifier/axioms/TypeAxiom.java b/verifier/src/main/java/dev/cel/verifier/axioms/TypeAxiom.java index baebfff60..00b6f914d 100644 --- a/verifier/src/main/java/dev/cel/verifier/axioms/TypeAxiom.java +++ b/verifier/src/main/java/dev/cel/verifier/axioms/TypeAxiom.java @@ -22,6 +22,7 @@ import dev.cel.common.types.MapType; import dev.cel.common.types.OptionalType; import dev.cel.common.types.SimpleType; +import dev.cel.common.types.TypeType; import dev.cel.verifier.CelZ3Exprs; import dev.cel.verifier.CelZ3TypeSystem; import java.util.Optional; @@ -31,6 +32,7 @@ final class TypeAxiom { private static final String TYPE_NAME_LIST = ListType.create().name(); private static final String TYPE_NAME_MAP = MapType.create(SimpleType.DYN, SimpleType.DYN).name(); + private static final String TYPE_NAME_TYPE = TypeType.create(SimpleType.DYN).name(); static final CelZ3FunctionAxiom INSTANCE = CelZ3FunctionAxiom.newBuilder(StandardFunction.TYPE.functionDecl()) @@ -52,19 +54,20 @@ private static Expr getTypeExpression(Context ctx, CelZ3TypeSystem typeSystem return CelZ3Exprs.SwitchBuilder.newBuilder(ctx) .addCase( typeSystem.isStruct(val), - typeSystem.wrapString(typeSystem.getMsgTypeName(typeSystem.getMessageRef(val)))) - .addCase(typeSystem.isOptional(val), typeSystem.mkString(OptionalType.NAME)) - .addCase(typeSystem.isNull(val), typeSystem.mkString(SimpleType.NULL_TYPE.name())) - .addCase(typeSystem.isTimestamp(val), typeSystem.mkString(SimpleType.TIMESTAMP.name())) - .addCase(typeSystem.isDuration(val), typeSystem.mkString(SimpleType.DURATION.name())) - .addCase(typeSystem.isMap(val), typeSystem.mkString(TYPE_NAME_MAP)) - .addCase(typeSystem.isList(val), typeSystem.mkString(TYPE_NAME_LIST)) - .addCase(typeSystem.isBytes(val), typeSystem.mkString(SimpleType.BYTES.name())) - .addCase(typeSystem.isString(val), typeSystem.mkString(SimpleType.STRING.name())) - .addCase(typeSystem.isDouble(val), typeSystem.mkString(SimpleType.DOUBLE.name())) - .addCase(typeSystem.isUint(val), typeSystem.mkString(SimpleType.UINT.name())) - .addCase(typeSystem.isInt(val), typeSystem.mkString(SimpleType.INT.name())) - .addCase(typeSystem.isBool(val), typeSystem.mkString(SimpleType.BOOL.name())) + typeSystem.wrapType(typeSystem.getMsgTypeName(typeSystem.getMessageRef(val)))) + .addCase(typeSystem.isOptional(val), typeSystem.mkType(OptionalType.NAME)) + .addCase(typeSystem.isNull(val), typeSystem.mkType(SimpleType.NULL_TYPE.name())) + .addCase(typeSystem.isTimestamp(val), typeSystem.mkType(SimpleType.TIMESTAMP.name())) + .addCase(typeSystem.isDuration(val), typeSystem.mkType(SimpleType.DURATION.name())) + .addCase(typeSystem.isMap(val), typeSystem.mkType(TYPE_NAME_MAP)) + .addCase(typeSystem.isList(val), typeSystem.mkType(TYPE_NAME_LIST)) + .addCase(typeSystem.isBytes(val), typeSystem.mkType(SimpleType.BYTES.name())) + .addCase(typeSystem.isString(val), typeSystem.mkType(SimpleType.STRING.name())) + .addCase(typeSystem.isDouble(val), typeSystem.mkType(SimpleType.DOUBLE.name())) + .addCase(typeSystem.isUint(val), typeSystem.mkType(SimpleType.UINT.name())) + .addCase(typeSystem.isInt(val), typeSystem.mkType(SimpleType.INT.name())) + .addCase(typeSystem.isBool(val), typeSystem.mkType(SimpleType.BOOL.name())) + .addCase(typeSystem.isType(val), typeSystem.mkType(TYPE_NAME_TYPE)) .build(typeSystem.mkError()); } diff --git a/verifier/src/test/java/dev/cel/verifier/BUILD.bazel b/verifier/src/test/java/dev/cel/verifier/BUILD.bazel index da198b15e..3af34d370 100644 --- a/verifier/src/test/java/dev/cel/verifier/BUILD.bazel +++ b/verifier/src/test/java/dev/cel/verifier/BUILD.bazel @@ -65,6 +65,7 @@ java_library( "//verifier:verifier_factory", "//verifier:z3_impl", "//verifier/axioms", + "@cel_conformance//proto/cel/expr/conformance/proto2:test_all_types_java_proto", "@cel_conformance//proto/cel/expr/conformance/proto3:test_all_types_java_proto", "@maven//:com_google_guava_guava", ], diff --git a/verifier/src/test/java/dev/cel/verifier/CelVerifierZ3ImplTest.java b/verifier/src/test/java/dev/cel/verifier/CelVerifierZ3ImplTest.java index b993fe18b..a04f4d2cc 100644 --- a/verifier/src/test/java/dev/cel/verifier/CelVerifierZ3ImplTest.java +++ b/verifier/src/test/java/dev/cel/verifier/CelVerifierZ3ImplTest.java @@ -25,6 +25,7 @@ import com.google.errorprone.annotations.Immutable; import com.google.testing.junit.testparameterinjector.TestParameter; import com.google.testing.junit.testparameterinjector.TestParameterInjector; +import com.google.testing.junit.testparameterinjector.TestParameters; // import com.google.testing.testsize.MediumTest; import com.microsoft.z3.ArrayExpr; import com.microsoft.z3.BoolExpr; @@ -55,6 +56,7 @@ import dev.cel.common.types.StructTypeReference; import dev.cel.common.types.TypeType; import dev.cel.compiler.CelCompiler; +import dev.cel.expr.conformance.proto2.TestAllTypesExtensions; import dev.cel.expr.conformance.proto3.TestAllTypes; import dev.cel.extensions.CelExtensions; import dev.cel.extensions.CelOptionalLibrary; @@ -66,6 +68,7 @@ import dev.cel.parser.CelStandardMacro; import dev.cel.runtime.CelFunctionBinding; import dev.cel.runtime.CelUnknownSet; +import dev.cel.testing.testdata.proto3.StandaloneGlobalEnum; import dev.cel.verifier.CelVerificationResult.VerificationStatus; import dev.cel.verifier.axioms.CelZ3FunctionAxiom; import dev.cel.verifier.axioms.CelZ3OverloadResult; @@ -74,6 +77,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; +import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.stream.IntStream; import org.junit.Before; @@ -121,6 +125,7 @@ public final class CelVerifierZ3ImplTest { .addVar("dyn_var", SimpleType.DYN) .addVar("dyn_var2", SimpleType.DYN) .addVar("type_var", TypeType.create(SimpleType.DYN)) + .addVar("type_list", ListType.create(TypeType.create(SimpleType.DYN))) .addVar("opt_var", OptionalType.create(SimpleType.INT)) .addVar("opt_dyn_var", OptionalType.create(SimpleType.DYN)) .addVar("nullable_int", NullableType.create(SimpleType.INT)) @@ -185,6 +190,16 @@ public void setUp() { private enum IsSatisfiableTestCase { SATISFIABLE("x > 5", "x = (?:[6-9]|[1-9]\\d+)"), + TYPE_VALUE("type_var == int", "type_var = int$"), + TYPE_VALUE_OF_DECLARED_TYPE( + "type_var != int && type_var != uint && type_var != double && type_var != bool" + + " && type_var != string && type_var != bytes && type_var != null_type" + + " && type_var != list && type_var != map && type_var != type" + + " && type_var != optional_type && type_var != google.protobuf.Timestamp" + + " && type_var != google.protobuf.Duration", + "type_var = (cel\\.expr\\.conformance|google\\.protobuf)\\.[\\w.]+$"), + TYPE_OF_TRUNCATED_LIST("size(int_list) == 6 && dyn(type(int_list)) == list", "int_list = "), + TRUNCATED_TYPE_LIST_EQUALITY("size(type_list) == 6 && type_list == type_list", "type_list = "), OPTIONAL_OR_VALUE_SKIPS_APPROXIMATE_ALTERNATIVE( "optional.of(x).orValue(int('123')) == 7", "x = 7"), DYNAMIC_ARITHMETIC("request == 1 && request + 2 == 3", "request = 1"), @@ -247,6 +262,10 @@ private enum IsSatisfiableTestCase { OR_VALUE_OF_DYN_NAN( "dyn_var.orValue(1) != dyn_var.orValue(1)", "dyn_var = optional\\.of\\(double\\(\"NaN\"\\)\\)"), + OPTIONAL_OF_NAN_NEQ_ITSELF( + "opt_dyn_var != opt_dyn_var", "opt_dyn_var = optional\\.of\\(double\\(\"NaN\"\\)\\)"), + OPTIONAL_PAST_UNROLL_LIMIT_NEQ_NONE( + "size(dyn_list) == 6 && optional.of(dyn_list) != optional.none()", "dyn_list = "), // Indexing and conditionals return existing values, so they do not inherit truncated type // constraints from their operands. DYN_ELEMENT_OF_LONG_NESTED_LIST_EQUALITY( @@ -386,7 +405,8 @@ private enum InexactWitnessTestCase { LIST_WITH_INEXACT_ELEMENT("dyn_list == [b'\\xc3\\xa9']", "dyn_list"), MAP_WITH_INEXACT_KEY("b'\\xc3\\xa9' in dyn_int_map", "dyn_int_map"), MAP_WITH_INEXACT_VALUE("string_dyn_map == {'a': b'\\xc3\\xa9'}", "string_dyn_map"), - OPTIONAL_WITH_INEXACT_VALUE("opt_dyn_var == optional.of(b'\\xc3\\xa9')", "opt_dyn_var"); + OPTIONAL_WITH_INEXACT_VALUE("opt_dyn_var == optional.of(b'\\xc3\\xa9')", "opt_dyn_var"), + TYPE_VALUE("type_var == int", "type_var"); private final String expr; private final String variableName; @@ -431,33 +451,130 @@ private enum InexactMapTestCase { @SuppressWarnings({"unchecked", "rawtypes"}) // Z3 Java API uses raw types. public void generateWitness_mapWithoutExactValue_valueEmpty( @TestParameter InexactMapTestCase testCase) { + CelWitness.Variable variable = + generateWitness( + "map", + (typeSystem, map) -> { + Context ctx = typeSystem.ctx(); + Expr mapRef = typeSystem.getMapRef(map); + SeqExpr keys = ctx.mkEmptySeq(ctx.mkSeqSort(typeSystem.celValueSort())); + for (String key : testCase.keySequence) { + keys = ctx.mkConcat(keys, ctx.mkUnit(typeSystem.mkString(key))); + } + ArrayExpr presence = ctx.mkConstArray(typeSystem.celValueSort(), ctx.mkFalse()); + for (String key : testCase.presentKeys) { + presence = ctx.mkStore(presence, (Expr) typeSystem.mkString(key), ctx.mkTrue()); + } + return ctx.mkAnd( + typeSystem.isMap(map), + ctx.mkEq(typeSystem.getMapKeys(mapRef), keys), + ctx.mkEq(typeSystem.getMapPresence(mapRef), presence)); + }); + + assertThat(variable.value()).isEmpty(); + } + + @Test + @TestParameters({ + "{name: 'int', expectedDisplay: 'int'}", + "{name: 'google.protobuf.Timestamp', expectedDisplay: 'google.protobuf.Timestamp'}", + "{name: '', expectedDisplay: ''}", + "{name: 'a b', expectedDisplay: ''}", + }) + public void generate_typeValue_displaysNameOrQuotesIt(String name, String expectedDisplay) { + CelWitness.Variable variable = + generateWitness("t", (typeSystem, t) -> typeSystem.ctx().mkEq(t, typeSystem.mkType(name))); + + assertThat(variable.displayValue()).isEqualTo(expectedDisplay); + } + + @Test + public void isSatisfiable_typeExcludingAllKnownTypes_remainsSatisfiable() throws Exception { + Cel cel = + CelFactory.plannerCelBuilder() + .addCompilerLibraries(CelOptionalLibrary.INSTANCE) + .addRuntimeLibraries(CelOptionalLibrary.INSTANCE) + .addFileTypes(StandaloneGlobalEnum.getDescriptor().getFile()) + .addMessageTypes( + TestAllTypes.getDescriptor() + .findFieldByName("single_int64_wrapper") + .getMessageType()) + .addVar("type_var", TypeType.create(SimpleType.DYN)) + .build(); + CelAbstractSyntaxTree ast = + cel.compile(IsSatisfiableTestCase.TYPE_VALUE_OF_DECLARED_TYPE.expr).getAst(); + + CelVerificationResult result = checkedVerifier(cel).build().isSatisfiable(ast); + + assertExact(result, VerificationStatus.VERIFIED); + assertThat(result.message()).doesNotContain("StandaloneGlobalEnum"); + assertThat(result.message()).doesNotContain("google.protobuf."); + } + + @Test + public void isSatisfiable_unknownOptionalEmptyDynListField_returnsViolated() throws Exception { + CelVerifier verifier = checkedVerifier(CEL).addUnknownIdentifier("opt_dyn_var").build(); + CelAbstractSyntaxTree ast = + CEL.compile( + "TestAllTypes{?list_value: opt_dyn_var} == TestAllTypes{single_int64: 1}" + + " && (dyn_var.exists(e, e == 1) || true)") + .getAst(); + + CelVerificationResult result = verifier.isSatisfiable(ast); + + assertExact(result, VerificationStatus.VIOLATED); + } + + @Test + public void verifyEquivalence_unknownOptionalStructEntry_notEquivalentToError() throws Exception { + CelVerifier verifier = + CelVerifierFactory.newVerifier(CEL).addUnknownIdentifier("opt_dyn_var").build(); + CelAbstractSyntaxTree astA = + CEL.compile("TestAllTypes{?single_int64: opt_dyn_var, single_int64: dyn(1.5)}").getAst(); + CelAbstractSyntaxTree astB = CEL.compile("TestAllTypes{single_int64: dyn(1.5)}").getAst(); + + CelVerificationResult result = verifier.verifyEquivalence(astA, astB); + + assertExact(result, VerificationStatus.VIOLATED); + } + + @Test + public void isAlwaysTrue_proto2ExtensionFieldOfOtherKind_returnsViolated() throws Exception { + Cel cel = + CelFactory.plannerCelBuilder() + .setContainer(CelContainer.ofName("cel.expr.conformance.proto2")) + .addFileTypes(TestAllTypesExtensions.getDescriptor()) + .addVar("dyn_var", SimpleType.DYN) + .build(); + CelAbstractSyntaxTree ast = + cel.compile( + "dyn_var != 1.5 || !(TestAllTypes{`cel.expr.conformance.proto2.int32_ext`:" + + " dyn_var} == TestAllTypes{})") + .getAst(); + + CelVerificationResult result = checkedVerifier(cel).build().isAlwaysTrue(ast); + + assertExact(result, VerificationStatus.VIOLATED); + assertThat(result.message()).contains("dyn_var = 1.5"); + } + + private static CelWitness.Variable generateWitness( + String name, BiFunction, BoolExpr> constraint) { try (Context ctx = new Context()) { - CelZ3TypeSystem typeSystem = new CelZ3TypeSystem(ctx, /* parameterizeUnknowns= */ false); - Expr map = ctx.mkConst("map", typeSystem.celValueSort()); - Expr mapRef = typeSystem.getMapRef(map); - SeqExpr keys = ctx.mkEmptySeq(ctx.mkSeqSort(typeSystem.celValueSort())); - for (String key : testCase.keySequence) { - keys = ctx.mkConcat(keys, ctx.mkUnit(typeSystem.mkString(key))); - } - ArrayExpr presence = ctx.mkConstArray(typeSystem.celValueSort(), ctx.mkFalse()); - for (String key : testCase.presentKeys) { - presence = ctx.mkStore(presence, (Expr) typeSystem.mkString(key), ctx.mkTrue()); - } + CelZ3TypeSystem typeSystem = + new CelZ3TypeSystem(ctx, /* parameterizeUnknowns= */ false, ImmutableSet.of()); + Expr variable = ctx.mkConst(name, typeSystem.celValueSort()); Solver solver = ctx.mkSolver(); - solver.add(typeSystem.isMap(map)); - solver.add(ctx.mkEq(typeSystem.getMapKeys(mapRef), keys)); - solver.add(ctx.mkEq(typeSystem.getMapPresence(mapRef), presence)); + solver.add(constraint.apply(typeSystem, variable)); assertThat(solver.check()).isEqualTo(Status.SATISFIABLE); - - CelWitness witness = - CelZ3CounterexampleGenerator.generate( + return CelZ3CounterexampleGenerator.generate( ctx, typeSystem, solver.getModel(), /* comprehensionUnrollLimit= */ 5, - ImmutableSet.of(map)); - - assertThat(witness.variables().get("map").value()).isEmpty(); + ImmutableSet.of(variable)) + .variables() + .get(name); } } @@ -591,6 +708,7 @@ public void isSatisfiable_unconditional_returnsUnconditionalMessage() throws Exc private enum ApproximationSourceTestCase { PARTIALLY_MODELED_FUNCTION("int(string_var) == 5", "calls to `int`"), + DYN_TYPE_VALUE("type(x) == dyn", "the `dyn` type as a value"), EMPTY_LIST_DYN_FIELD( "has(TestAllTypes{list_value: []}.list_value)", "whether empty `list(dyn)` and `map(string, dyn)` fields are set"), @@ -646,7 +764,13 @@ private enum ApproximationSourceTestCase { "comparisons of lists, maps, messages or optionals read out of lists and maps"), DYN_LIST_VARIABLES( "size(dyn_var) == 1 && dyn_var[0] == 1 && dyn_var == dyn_var2", - "comparisons of lists or maps typed dyn"); + "comparisons of lists, maps or optionals typed dyn"), + DYN_OPTIONAL_VARIABLES( + "dyn_var.hasValue() && dyn_var == dyn_var2", + "comparisons of lists, maps or optionals typed dyn"), + OPTIONAL_VALUES_TYPED_DYN( + "size(dyn_var) == 1 && dyn_var[0] == 1 && opt_dyn_var == optional.of(dyn_var)", + "comparisons of lists, maps or optionals typed dyn"); private final String expr; private final String expectedSources; @@ -726,6 +850,12 @@ public void isSatisfiable_approximate_returnsPotentialSatisfyingInput() throws E } private enum IsSatisfiableInconclusiveTestCase { + STRUCT_LITERAL_OPTIONAL_TRUNCATED_COMPREHENSION( + "size(int_list) == 6 && TestAllTypes{?single_int64: int_list.map(e, e) == [1, 2, 3, 4, 5," + + " 6] ? optional.of(1) : optional.none()} == TestAllTypes{}"), + JSON_VALUE_OPTIONAL_TRUNCATED_COMPREHENSION( + "size(int_list) == 6 && google.protobuf.Value{?number_value: int_list.map(e, e) == [1, 2," + + " 3, 4, 5, 6] ? optional.of(1.0) : optional.none()} == null"), OPTIONAL_OR_VALUE_EMPTY_RECEIVER_APPROXIMATE_ALTERNATIVE( "optional.none().orValue(int('123')) == 7"), OPTIONAL_OR_VALUE_APPROXIMATE_RECEIVER("optional.of(int('123')).orValue(1) == 7"), @@ -882,6 +1012,8 @@ private enum IsUnsatisfiableTestCase { NULLABLE_NULL_AND_ONE("nullable_int == null && nullable_int == 1"), REPEATED_FIELD_FROM_NON_LIST( "dyn_var == 42 && TestAllTypes{repeated_int64: dyn_var} == TestAllTypes{}"), + ENUM_LITERAL_NON_INT_FIELD( + "dyn_var == 1.5 && has(TestAllTypes{standalone_enum: dyn_var}.standalone_enum)"), UNSATISFIABLE("x > 5 && x < 3"), DYN_RANGE_COMPREHENSION_MASKED_BY_FALSE("dyn_var.exists(e, e == 1) && false"), CONTRADICTORY_TYPES_FOR_DYNAMIC_VARIABLE("unknown_var + 1 == 2 && unknown_var[0] == 1"), @@ -1020,7 +1152,44 @@ public void isSatisfiable_timeout_throwsException() throws Exception { } private enum IsAlwaysTrueTestCase { + STRUCT_LITERAL_DUPLICATE_FIELD_LAST_WINS( + "TestAllTypes{single_int64: dyn_var, single_int64: 1}.single_int64 == 1"), + STRUCT_LITERAL_DUPLICATE_LIST_MAP_LAST_WINS( + "TestAllTypes{repeated_int64: dyn_var, repeated_int64: [1]}.repeated_int64 == [1]" + + " && TestAllTypes{map_string_string: dyn_var, map_string_string: {'a':" + + " 'b'}}.map_string_string == {'a': 'b'}"), + STRUCT_LITERAL_ABSENT_OPTIONAL_CLEARS_INVALID( + "TestAllTypes{single_int64: dyn_var, ?single_int64: optional.none()} == TestAllTypes{}"), + STRUCT_LITERAL_ABSENT_OPTIONAL_CLEARS_MESSAGE( + "TestAllTypes{standalone_message: TestAllTypes.NestedMessage{}, ?standalone_message:" + + " optional.none()} == TestAllTypes{}"), + STRUCT_LITERAL_ENUM_INT32_BOUNDS( + "has(TestAllTypes{standalone_enum: -2147483648}.standalone_enum)" + + " && has(TestAllTypes{standalone_enum: 2147483647}.standalone_enum)"), + JSON_VALUE_DUPLICATE_LAST_WINS( + "google.protobuf.Value{string_value: dyn_var, string_value: 'ok'} == 'ok'"), + JSON_VALUE_MULTI_FIELD_ABSENT_OPTIONAL( + "google.protobuf.Value{string_value: 'a', ?number_value: optional.none()} == 'a'"), + JSON_VALUE_REPEATED_PRESENT_KEEPS_ORDER( + "google.protobuf.Value{string_value: 'a', number_value: 1.0, string_value: 'b'} == 1.0"), + JSON_VALUE_ABSENT_OPTIONAL_MOVES_REPEATED_FIELD_TO_TAIL( + "google.protobuf.Value{string_value: 'a', ?string_value: optional.none(), number_value:" + + " 1.0, string_value: 'b'} == 'b'"), + JSON_VALUE_DYNAMIC_OPTIONAL_REPEATED_FIELD_ORDER( + "(opt_dyn_var == optional.of('a') || opt_dyn_var == optional.none())" + + " ? google.protobuf.Value{?string_value: opt_dyn_var, number_value: 1.0," + + " string_value: 'b'} == (opt_dyn_var.hasValue() ? dyn(1.0) : dyn('b'))" + + " : true"), + WRAPPER_ABSENT_OPTIONAL_CLEARS_DUPLICATE( + "google.protobuf.Int64Value{value: dyn_var, ?value: optional.none()} == 0"), LOGICAL_OR_CONSTANTS("true || false"), + TYPE_NOT_STRING("dyn('int') != int && type(x) != dyn('int')"), + TYPE_OF_TYPE( + "type(type) == type && [int, string].all(t, type(t) == type) && type(type(dyn_var)) ==" + + " type && type(type_var) == type"), + TYPE_IN_LIST("int in [int, string]"), + TYPE_LIST_EQUALITY("type_list == type_list"), + TYPE_OF_MESSAGE("type(TestAllTypes{}) == TestAllTypes"), // Elements of `dyn` inputs are never unknown. DYN_LIST_ELEMENT_NOT_UNKNOWN( "size(dyn_list) == 1 ? (dyn_list.exists(x, x == 1) || !dyn_list.exists(x, x == 1)) : true"), @@ -1261,6 +1430,22 @@ private enum IsAlwaysTrueTestCase { OPTIONAL_NONE_EQ_NONE("optional.none() == optional.none()"), OPTIONAL_OF_EQ_OF("optional.of(1) == optional.of(1)"), OPTIONAL_OF_NEQ_NONE("optional.of(1) != optional.none()"), + OPTIONAL_OF_NUMERICALLY_EQUAL("dyn(optional.of(1)) == optional.of(1.0)"), + OPTIONAL_OF_NAN_NEQ_ITSELF("optional.of(0.0 / 0.0) != optional.of(0.0 / 0.0)"), + OPTIONAL_OF_NEG_ZERO_EQ("optional.of(0.0) == optional.of(-0.0)"), + OPTIONAL_OF_LIST_NUMERICALLY_EQUAL("optional.of([dyn(1)]) == optional.of([dyn(1.0)])"), + OPTIONAL_NEQ_NON_OPTIONAL("dyn_var == 1 ? opt_var != dyn_var : true"), + OPTIONAL_OF_LIST_VAR_EQ_ITSELF("optional.of(int_list) == optional.of(int_list)"), + OPTIONAL_LIST_IN_LIST_LITERAL_NUMERICALLY_EQUAL( + "[optional.of([dyn(1)])] == [optional.of([dyn(1.0)])]"), + OPTIONAL_SELECT_NUMERICALLY_EQUAL("optional.of({'a': dyn(1)}).a == optional.of(1.0)"), + OPTIONAL_MAP_VAR_IN_MAP_LITERAL( + "string_int_map == {'k': 1}" + + " ? {'a': optional.of(string_int_map)} == {'a': optional.of({'k': 1})} : true"), + // `int_list` holds ints past the unroll limit too. + OPTIONAL_OF_LIST_VAR_PAST_UNROLL_LIMIT( + "optional.of(int_list) == optional.of([1, 2, 3, 4, 5, 6]) && int_list_2 == [1, 2, 3, 4, 5," + + " 6] ? int_list == int_list_2 : true"), OPTIONAL_VALUE("optional.of('test').value() == 'test'"), OPTIONAL_HAS_VALUE_TRUE("optional.of(true).hasValue()"), OPTIONAL_HAS_VALUE_FALSE("!optional.none().hasValue()"), @@ -1919,7 +2104,9 @@ private enum UnconditionalErrorTestCase { TIMESTAMP_INT_CONVERSION_OUT_OF_BOUNDS( "timestamp(999999999999999) == timestamp(999999999999999)"), TIMESTAMP_INT_CONVERSION_UNDERFLOW( - "timestamp(-999999999999999) == timestamp(-999999999999999)"); + "timestamp(-999999999999999) == timestamp(-999999999999999)"), + TIMESTAMP_DUPLICATE_ENTRY_ERROR( + "google.protobuf.Timestamp{seconds: 1 / 0, seconds: 1} == timestamp(1)"); final String expr; @@ -2043,6 +2230,58 @@ public void verifyEquivalence_infinityConstants_notEquivalent() throws Exception } private enum IsAlwaysTrueViolationTestCase { + STRUCT_LITERAL_FIELD_OF_OTHER_KIND( + "dyn_var != 1.5 || TestAllTypes{single_int64: dyn_var}.single_int64 == 5", + "dyn_var = 1\\.5"), + STRUCT_LITERAL_NULL_FIELD( + "dyn_var != null || TestAllTypes{single_int64: dyn_var}.single_int64 == 0", + "dyn_var = null"), + STRUCT_LITERAL_OPTIONAL_FIELD_OF_OTHER_KIND( + "dyn_var != 1.5 || TestAllTypes{?single_int64: optional.of(dyn_var)}.single_int64 == 5", + "dyn_var = 1\\.5"), + STRUCT_LITERAL_WRAPPER_FIELD_OF_OTHER_KIND( + "dyn_var != 'a' || TestAllTypes{single_int64_wrapper: dyn_var}.single_int64_wrapper == 5", + "dyn_var = \"a\""), + STRUCT_LITERAL_ENUM_FIELD_OF_OTHER_KIND( + "dyn_var != 1.5 || has(TestAllTypes{standalone_enum: dyn_var}.standalone_enum)", + "dyn_var = 1\\.5"), + STRUCT_LITERAL_REPEATED_FIELD_OF_OTHER_KIND( + "dyn_var != 1 || has(TestAllTypes{repeated_int64: dyn_var}.repeated_int64)", "dyn_var = 1"), + STRUCT_LITERAL_ENUM_FIELD_OUT_OF_RANGE( + "x != 2147483648 || has(TestAllTypes{standalone_enum: x}.standalone_enum)", + "x = 2147483648"), + STRUCT_LITERAL_ENUM_FIELD_UNDERFLOW( + "x != -2147483649 || has(TestAllTypes{standalone_enum: x}.standalone_enum)", + "x = -2147483649"), + STRUCT_LITERAL_INVALID_FIELD_OVERRIDES_APPROXIMATION( + "dyn_var != 1.5 || TestAllTypes{repeated_value: [], single_int64: dyn_var} ==" + + " TestAllTypes{}", + "dyn_var = 1\\.5"), + STRUCT_LITERAL_DUPLICATE_INVALID_OVERRIDES_EMPTY_DYN_LIST( + "dyn_var != 1 || TestAllTypes{list_value: [], list_value: dyn_var} == TestAllTypes{}", + "dyn_var = 1"), + JSON_VALUE_SCALAR_FIELD_OF_OTHER_KIND( + "dyn_var != 1.5 || google.protobuf.Value{string_value: dyn_var} == 1.5", "dyn_var = 1\\.5"), + JSON_VALUE_OPTIONAL_FIELD_OF_OTHER_KIND( + "dyn_var != 'a' || google.protobuf.Value{?number_value: optional.of(dyn_var)} == 'a'", + "dyn_var = \"a\""), + JSON_VALUE_NULL_VALUE_OF_OTHER_KIND( + "dyn_var != 'a' || google.protobuf.Value{null_value: dyn_var} == null", "dyn_var = \"a\""), + JSON_VALUE_NULL_VALUE_OUT_OF_RANGE( + "x != 2147483648 || google.protobuf.Value{null_value: x} == null", "x = 2147483648"), + JSON_VALUE_OVERRIDDEN_ONEOF_VALIDATED( + "dyn_var != 1.5 || google.protobuf.Value{string_value: dyn_var, number_value: 1.0} == 1.0", + "dyn_var = 1\\.5"), + JSON_VALUE_DYNAMIC_OPTIONAL_ABSENT_MOVES_TO_TAIL( + "opt_dyn_var != optional.none()" + + " || google.protobuf.Value{?string_value: opt_dyn_var, number_value: 1.0," + + " string_value: 'b'} == 1.0", + "opt_dyn_var = optional\\.none\\(\\)"), + JSON_LIST_VALUE_OF_OTHER_KIND( + "dyn_var != 1 || google.protobuf.ListValue{values: dyn_var} != []", "dyn_var = 1"), + JSON_STRUCT_OF_OTHER_KIND( + "dyn_var != 1 || google.protobuf.Struct{fields: dyn_var} != {}", "dyn_var = 1"), + STRING_NAMING_TYPE("!(dyn_var == 'int' && dyn_var != int)", "dyn_var = \"int\""), // `[NaN]` differs from itself. DYNAMIC_LIST_VARIABLE_EQUALITY("dyn_list == dyn_list", "dyn_list = \\[double\\(\"NaN\"\\)\\]"), DYNAMIC_MAP_VARIABLE_EQUALITY( @@ -2062,16 +2301,16 @@ private enum IsAlwaysTrueViolationTestCase { NARROWED_TYPE_NUMERIC_EQUALITY( "dyn_var == optional.of(1) ? optional.ofNonZeroValue('').or(dyn_var).value() != dyn(1.0)" + " : true", - "dyn_var = optional\\.of\\(1\\)"), + "dyn_var = optional\\.of\\(1(u|\\.0)?\\)"), NARROWED_OPTIONAL_INDEX_NOT_CONTAINER( "dyn_var == optional.of(42) ? dyn_var.orValue(optional.of([1]))[0] in [42, optional.of(42)]" + " : true", - "dyn_var = optional\\.of\\(42\\)"), + "dyn_var = optional\\.of\\(42(u|\\.0)?\\)"), NARROWED_OPTIONAL_MAP_SELECTED( "dyn_var == optional.of(optional.of(42))" + " ? (dyn_var.orValue(optional.of({'a': 1})).a.hasValue()" + " || !dyn_var.orValue(optional.of({'a': 1})).a.hasValue()) : true", - "dyn_var = optional\\.of\\(optional\\.of\\(42\\)\\)"), + "dyn_var = optional\\.of\\(optional\\.of\\(42(u|\\.0)?\\)\\)"), // Map literal keys must be strings, ints, uints or bools, and can't repeat. MAP_LITERAL_RANGE_REPEATED_KEY("x == 1 ? {x: 'a', 1u: 'b'}.all(k, true) : true", "x = 1"), MAP_LITERAL_DOUBLE_KEY("{1.0: 'a'}[dyn(1)] == 'a'", "Condition is not always true\\."), @@ -2450,6 +2689,12 @@ public void isAlwaysTrue_dynamicMapComprehensionNestedEquality_violated() throws } private enum IsInconclusiveTestCase { + STRUCT_LITERAL_APPROXIMATE_FIELD_INVALID( + "TestAllTypes{single_int64: (TestAllTypes{list_value: []} == TestAllTypes{} ? dyn(1.5) :" + + " dyn(1))}.single_int64 == 1"), + JSON_VALUE_APPROXIMATE_FIELD_INVALID( + "google.protobuf.Value{string_value: (TestAllTypes{list_value: []} == TestAllTypes{} ?" + + " dyn(1.5) : dyn('ok'))} == 'ok'"), // int('5') == 5 is approximate and may really be true, which absorbs the 1 / 0 error. APPROXIMATE_MATCH_BEFORE_ERROR( "int_list == [1, 0] ? int_list.exists(x, x == 1 ? int('5') == 5 : 1 / x == 1) : true"), @@ -2529,6 +2774,10 @@ private enum IsInconclusiveTestCase { "{\"key\": request.matches('a') ? 1 : 2}.all(k, v, v == 1)"), BIND_APPROXIMATE_ACCU("cel.bind(x, request.matches('a') ? 1 : 2, x == 1)"), BIND_APPROXIMATE_BODY("cel.bind(x, 1, x == 1 && request.matches('a'))"), + // The optionals are typed dyn, and optional.of(1.0) equals optional.of(1). + OR_WITH_DYN_ALTERNATIVE( + "dyn_var == optional.of(optional.of(1)) && type(dyn_var.value().value()) == double" + + " ? optional.ofNonZeroValue('').or(dyn_var).value() != dyn(optional.of(1)) : true"), COMPREHENSION_OPTIONAL_MAP_ENTRY( "size(int_list) == 6 ? size(int_list.map(x, {? x: optional.of(1)})) == 6 : true"), COMPREHENSION_OPTIONAL_STRUCT_ENTRY( @@ -2594,12 +2843,6 @@ private enum EquivalenceInconclusiveTestCase { "test_all_types.single_any != test_all_types.single_any" + " ? 0.0 / 0.0 : test_all_types.single_any", "test_all_types.single_any"), - // TODO: number_value set from an optional isn't checked to be a double, so it may - // be a list here. - DYN_OPTIONAL_JSON_NAN_AND_LITERAL( - "google.protobuf.Value{?number_value: dyn_var} != google.protobuf.Value{?number_value:" - + " dyn_var} ? 0.0 / 0.0 : google.protobuf.Value{?number_value: dyn_var}", - "google.protobuf.Value{?number_value: dyn_var}"), // The lists nested in literals are compared element-wise up to the unroll limit. NESTED_LIST_VARIABLE_EQUALITY( "[int_list] == [int_list_2] ? int_list == int_list_2 : true", "true"), @@ -2712,6 +2955,10 @@ public void verifyEquivalence_inconclusive( } private enum EquivalenceTestCase { + DYN_OPTIONAL_JSON_NAN_AND_LITERAL( + "google.protobuf.Value{?number_value: dyn_var} != google.protobuf.Value{?number_value:" + + " dyn_var} ? 0.0 / 0.0 : google.protobuf.Value{?number_value: dyn_var}", + "google.protobuf.Value{?number_value: dyn_var}"), OPTIONAL_OR_VALUE_OF_NON_OPTIONAL("dyn(1).orValue(int('123'))", "1 / 0"), STRUCT_UNSET_TIMESTAMP_DEFAULT("TestAllTypes{}.single_timestamp", "timestamp(0)"), // Both are errors. @@ -2799,6 +3046,8 @@ private enum EquivalenceTestCase { OPTIONAL_NONE_HAS_VALUE_EQUIVALENCE("optional.none().hasValue()", "false"), OPTIONAL_OF_NON_ZERO_VALUE_ARITHMETIC_EQUIVALENCE( "[optional.ofNonZeroValue(1 + 2 + 3)]", "[optional.of(6)]"), + OPTIONAL_EQUAL_TO_LITERAL( + "opt_var == optional.of(1) ? opt_var : optional.of(1)", "optional.of(1)"), OPTIONAL_OF_NON_ZERO_VALUE_INT_ZERO_EQUIVALENCE( "optional.ofNonZeroValue(0)", "optional.none()"), OPTIONAL_OF_NON_ZERO_VALUE_INT_NON_ZERO_EQUIVALENCE( @@ -2977,7 +3226,8 @@ private enum EquivalenceTestCase { "optional.of(TestAllTypes{repeated_string: ['foo']}).?repeated_string[0]", "optional.of('foo')"), OPTIONAL_CHAINING_DYN( - "dyn_var == optional.of({'a': [1]}) ? dyn_var.a[0] : optional.of(1)", "optional.of(1)"), + "dyn_var == optional.of({'a': ['x']}) ? dyn_var.a[0] : optional.of('x')", + "optional.of('x')"), OPTIONAL_CHAINING_DYN_NONE( "request == optional.none() ? request.l : optional.none()", "optional.none()"), JSON_VALUE_BOOL("google.protobuf.Value{bool_value: true}", "true"), @@ -4023,7 +4273,8 @@ public void addFunctionAxioms_allPrimitiveTypes_checksAllTypes() throws Exceptio SimpleType.BOOL, SimpleType.STRING, SimpleType.BYTES, - StructTypeReference.create("test.Message"))); + StructTypeReference.create("test.Message"), + TypeType.create(SimpleType.DYN))); CelZ3FunctionAxiom dummyAxiom = CelZ3FunctionAxiom.newBuilder(dummyDecl) .addOverloadTranslator( @@ -4041,20 +4292,27 @@ public void addFunctionAxioms_allPrimitiveTypes_checksAllTypes() throws Exceptio .addVar("string_var", SimpleType.STRING) .addVar("bytes_var", SimpleType.BYTES) .addVar("msg_var", StructTypeReference.create("test.Message")) + .addVar("type_var", TypeType.create(SimpleType.DYN)) .addFunctionDeclarations(dummyDecl) .build(); CelVerifier verifier = CelVerifierZ3Impl.newBuilder(cel).addFunctionAxioms(ImmutableList.of(dummyAxiom)).build(); CelAbstractSyntaxTree ast = cel.compile( - "dummy_all_types(uint_var, double_var, bool_var, string_var, bytes_var, msg_var) ==" - + " true") + "dummy_all_types(uint_var, double_var, bool_var, string_var, bytes_var, msg_var," + + " type_var) == true") .getAst(); CelVerificationResult result = verifier.isAlwaysTrue(ast); assertWithMessage(result.message()) .that(result.status()) .isEqualTo(VerificationStatus.VERIFIED); + CelAbstractSyntaxTree badTypeAst = + cel.compile( + "dummy_all_types(uint_var, double_var, bool_var, string_var, bytes_var, msg_var," + + " dyn('int')) == true") + .getAst(); + assertThat(verifier.isAlwaysTrue(badTypeAst).status()).isEqualTo(VerificationStatus.VIOLATED); } @Test