1717import static com .google .common .collect .ImmutableList .toImmutableList ;
1818
1919import com .google .common .collect .ImmutableList ;
20+ import com .google .common .collect .ImmutableSet ;
21+ import com .google .common .collect .Lists ;
2022import com .microsoft .z3 .ArithExpr ;
2123import com .microsoft .z3 .ArrayExpr ;
2224import com .microsoft .z3 .BoolExpr ;
@@ -55,6 +57,9 @@ final class CelZ3OperatorTranslator {
5557 private static final String FUNC_APPROX_EQ = "!approxEq" ;
5658 private static final String FUNC_APPROX_IN = "!approxIn" ;
5759 private static final MapType DYN_MAP = MapType .create (SimpleType .DYN , SimpleType .DYN );
60+ // Runtimes evaluate the alternative of `or` and `orValue` only when the receiver is empty.
61+ private static final ImmutableSet <String > RECEIVER_STRICT_OVERLOADS =
62+ ImmutableSet .of ("optional_or_optional" , "optional_orValue_value" );
5863
5964 private final Context ctx ;
6065 private final CelZ3TypeSystem typeSystem ;
@@ -70,15 +75,21 @@ Optional<TranslatedValue> translateFunctionCall(
7075 args .stream ().map (TranslatedValue ::z3Expr ).collect (toImmutableList ());
7176 ImmutableList <BoolExpr > argApproximations =
7277 args .stream ().map (TranslatedValue ::isApproximate ).collect (toImmutableList ());
78+ CelReference reference = ast .getReferenceMap ().get (exprId );
79+ List <TranslatedValue > strictArgs =
80+ reference != null
81+ && !reference .overloadIds ().isEmpty ()
82+ && RECEIVER_STRICT_OVERLOADS .containsAll (reference .overloadIds ())
83+ ? args .subList (0 , 1 )
84+ : args ;
7385
7486 TranslatedValue resultChain =
7587 opOpt
7688 .map (op -> translateOperatorCall (op , args , ast ))
7789 .orElseGet (() ->
7890 TranslatedValue .propagateStrict (
79- ctx , typeSystem , functionName , typeSystem .mkError (), args ));
91+ ctx , typeSystem , functionName , typeSystem .mkError (), strictArgs ));
8092
81- CelReference reference = ast .getReferenceMap ().get (exprId );
8293 CelFunctionDecl decl = functionRegistry .getDeclaration (functionName ).orElse (null );
8394
8495 if (decl == null ) {
@@ -127,7 +138,7 @@ Optional<TranslatedValue> translateFunctionCall(
127138
128139 matchedAny = true ;
129140 List <BoolExpr > typeGuards = new ArrayList <>();
130- for (int i = 0 ; i < z3Args .size (); i ++) {
141+ for (int i = 0 ; i < strictArgs .size (); i ++) {
131142 typeGuards .add (mkTypeGuard (z3Args .get (i ), overload .parameterTypes ().get (i )));
132143 }
133144
@@ -180,7 +191,11 @@ Optional<TranslatedValue> translateFunctionCall(
180191
181192 return Optional .of (
182193 TranslatedValue .create (
183- typeSystem .propagateErrorAndUnknown (functionName , currentZ3Result , z3Args , z3Args ),
194+ typeSystem .propagateErrorAndUnknown (
195+ functionName ,
196+ currentZ3Result ,
197+ Lists .transform (strictArgs , TranslatedValue ::z3Expr ),
198+ z3Args ),
184199 typeSystem ,
185200 currentApprox ));
186201 }
@@ -864,9 +879,6 @@ private BoolExpr listMembership(
864879 // Whether lhs may equal an element of elemType: a number only across numeric types, and a list
865880 // only another list (anything else conservatively).
866881 private BoolExpr mayEqualElement (Expr <?> lhs , CelType elemType ) {
867- if (elemType instanceof NullableType ) {
868- return ctx .mkTrue ();
869- }
870882 if (isNumericType (elemType )) {
871883 return isNumeric (lhs );
872884 }
@@ -989,8 +1001,6 @@ private TranslatedValue translateEquality(
9891001 structuralEq = (BoolExpr ) ctx .mkITE (bothMaps , mapEquality , structuralEq );
9901002 } else if (!isStaticallyKnown (type0 ) && !isStaticallyKnown (type1 )) {
9911003 // Performance only: a side with a known type isn't a list or map here.
992- // TODO: Unless the type checker narrowed it, e.g. `(int_list +
993- // dyn_var)[0]`.
9941004 structuralEq =
9951005 approximateEqualityWhere (
9961006 context .recordApproximation (
@@ -1027,13 +1037,11 @@ private static final class IndexAccess {
10271037 private final BoolExpr valid ;
10281038 private final BoolExpr found ;
10291039 private final Expr <?> value ;
1030- private final BoolExpr isApproximate ;
10311040
1032- private IndexAccess (BoolExpr valid , BoolExpr found , Expr <?> value , BoolExpr isApproximate ) {
1041+ private IndexAccess (BoolExpr valid , BoolExpr found , Expr <?> value ) {
10331042 this .valid = valid ;
10341043 this .found = found ;
10351044 this .value = value ;
1036- this .isApproximate = isApproximate ;
10371045 }
10381046 }
10391047
@@ -1043,54 +1051,40 @@ private IndexAccess listAccess(Expr<?> lhsTrans, Expr<?> rhsTrans) {
10431051 return new IndexAccess (
10441052 ctx .mkAnd (typeSystem .isList (lhsTrans ), typeSystem .isInt (rhsTrans )),
10451053 ctx .mkAnd (ctx .mkGe (index , ctx .mkInt (0 )), ctx .mkLt (index , ctx .mkLength (seq ))),
1046- ctx .mkNth (seq , index ),
1047- /* isApproximate= */ ctx .mkFalse ());
1054+ ctx .mkNth (seq , index ));
10481055 }
10491056
10501057 private IndexAccess mapAccess (Expr <?> lhsTrans , Expr <?> rhsTrans ) {
10511058 ImmutableList <CelZ3TypeSystem .EqualKey > equalKeys = typeSystem .equalKeys (rhsTrans );
10521059 return new IndexAccess (
10531060 typeSystem .isMap (lhsTrans ),
10541061 typeSystem .hasEqualKey (lhsTrans , equalKeys ),
1055- typeSystem .valueAtEqualKey (lhsTrans , equalKeys ),
1056- /* isApproximate= */ ctx .mkFalse ());
1062+ typeSystem .valueAtEqualKey (lhsTrans , equalKeys ));
10571063 }
10581064
10591065 /**
1060- * Looks up {@code rhsTrans} in the list or map {@code lhsTrans}. The value is approximate if the
1061- * static element type isn't guaranteed and it may not conform.
1066+ * Looks up {@code rhsTrans} in the list or map {@code lhsTrans} of type {@code containerType}.
10621067 */
1063- private IndexAccess indexAccess (
1064- Expr <?> lhsTrans , Expr <?> rhsTrans , CelType containerType , boolean isLhsTypeGuaranteed ) {
1068+ private IndexAccess indexAccess (Expr <?> lhsTrans , Expr <?> rhsTrans , CelType containerType ) {
10651069 IndexAccess list = listAccess (lhsTrans , rhsTrans );
10661070 IndexAccess map = mapAccess (lhsTrans , rhsTrans );
10671071 IndexAccess access =
10681072 new IndexAccess (
10691073 ctx .mkOr (list .valid , map .valid ),
10701074 (BoolExpr ) ctx .mkITE (list .valid , list .found , map .found ),
1071- ctx .mkITE (list .valid , list .value , map .value ),
1072- /* isApproximate= */ ctx .mkFalse ());
1075+ ctx .mkITE (list .valid , list .value , map .value ));
10731076 BoolExpr isRead = ctx .mkAnd (access .valid , access .found );
10741077 context .constrainValidValue (isRead , access .value );
1075- if (containerType .kind () != CelKind .MAP && containerType .kind () != CelKind .LIST ) {
1076- return access ;
1077- }
1078- CelType elemType =
1079- containerType .kind () == CelKind .MAP
1080- ? ((MapType ) containerType ).valueType ()
1081- : ((ListType ) containerType ).elemType ();
1082- BoolExpr conforms = typeConstraintGenerator .createTypeConstraintForType (access .value , elemType );
1083- if (isLhsTypeGuaranteed ) {
1084- context .addConstraint (ctx .mkImplies (isRead , conforms ));
1085- return access ;
1078+ if (containerType instanceof MapType || containerType instanceof ListType ) {
1079+ CelType elemType =
1080+ containerType instanceof MapType
1081+ ? ((MapType ) containerType ).valueType ()
1082+ : ((ListType ) containerType ).elemType ();
1083+ context .addConstraint (
1084+ ctx .mkImplies (
1085+ isRead , typeConstraintGenerator .createTypeConstraintForType (access .value , elemType )));
10861086 }
1087- // The type checker may narrow other static types (e.g. `(['a'] + dyn_var)[1]` is typed
1088- // string), so the element may not conform.
1089- return new IndexAccess (
1090- access .valid ,
1091- access .found ,
1092- access .value ,
1093- CelZ3Exprs .mkAndFlattened (ctx , isRead , CelZ3Exprs .mkNotFlattened (ctx , conforms )));
1087+ return access ;
10941088 }
10951089
10961090 /**
@@ -1102,7 +1096,6 @@ private TranslatedValue translateIndex(
11021096 TranslatedValue lhs = args .get (0 );
11031097 TranslatedValue rhs = args .get (1 );
11041098 CelType lhsType = extractAstTypeOrDefault (lhs , ast );
1105- boolean isLhsTypeGuaranteed = lhsType .equals (guaranteedType (lhs , ast ));
11061099 CelType containerType = lhsType instanceof OptionalType ? lhsType .parameters ().get (0 ) : lhsType ;
11071100
11081101 Expr <?> lhsTrans = lhs .z3Expr ();
@@ -1112,7 +1105,7 @@ private TranslatedValue translateIndex(
11121105 BoolExpr lhsHasValue = typeSystem .optHasValue (optRef );
11131106 lhsTrans = ctx .mkITE (isOptionalLhs , typeSystem .getOptionalValue (optRef ), lhsTrans );
11141107 // An empty optional's value can't be read, so constraining it is harmless.
1115- IndexAccess access = indexAccess (lhsTrans , rhsTrans , containerType , isLhsTypeGuaranteed );
1108+ IndexAccess access = indexAccess (lhsTrans , rhsTrans , containerType );
11161109 Expr <?> element =
11171110 ctx .mkITE (ctx .mkAnd (access .valid , access .found ), access .value , typeSystem .mkError ());
11181111 Expr <?> optionalElement =
@@ -1139,8 +1132,7 @@ private TranslatedValue translateIndex(
11391132 BoolExpr isMapIndexTruncated = context .isTruncatedMap (lhsTrans );
11401133 return TranslatedValue .propagateStrict (ctx , typeSystem , op .getFunction (), actualValue , args )
11411134 .withApproximation (
1142- CelZ3Exprs .mkOrFlattened (
1143- ctx , isListIndexTruncated , isMapIndexTruncated , access .isApproximate ));
1135+ CelZ3Exprs .mkOrFlattened (ctx , isListIndexTruncated , isMapIndexTruncated ));
11441136 }
11451137
11461138 private TranslatedValue translateConditional (
@@ -1197,12 +1189,7 @@ private static CelType extractAstTypeOrDefault(TranslatedValue val, CelAbstractS
11971189 return val .celExpr ().map (node -> ast .getTypeOrThrow (node .id ())).orElse (SimpleType .DYN );
11981190 }
11991191
1200- /**
1201- * Returns the type that {@code val} is guaranteed to conform to at runtime: a constant's, the
1202- * declared type of an input variable, or else dyn. Global constraints may only be derived from
1203- * guaranteed types: the type checker may narrow static types (e.g. {@code ['a'] + dyn_var} is
1204- * typed list(string)), so constraints derived from those could exclude valid inputs.
1205- */
1192+ /** Returns a constant's type, or an input variable's declared type, or else dyn. */
12061193 private CelType guaranteedType (TranslatedValue val , CelAbstractSyntaxTree ast ) {
12071194 return val .isLiteral (ExprKind .Kind .CONSTANT )
12081195 ? extractAstTypeOrDefault (val , ast )
@@ -1254,9 +1241,11 @@ private static boolean hasStructuralEquality(CelType type) {
12541241 }
12551242 }
12561243
1244+ /** Excludes wrappers, whose kind is their value's but which may also be null. */
12571245 private static boolean isNumericType (CelType type ) {
12581246 CelKind kind = type .kind ();
1259- return kind == CelKind .INT || kind == CelKind .UINT || kind == CelKind .DOUBLE ;
1247+ return !(type instanceof NullableType )
1248+ && (kind == CelKind .INT || kind == CelKind .UINT || kind == CelKind .DOUBLE );
12601249 }
12611250
12621251 /**
0 commit comments