Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions verifier/src/main/java/dev/cel/verifier/BUILD.bazel
Original file line numberDiff line numberDiff line change
Expand Up@@ -129,6 +129,7 @@ java_library(
"//common/ast",
"//common/ast:cel_block",
"//common/types",
"//common/types:cel_types",
"//common/types:type_providers",
"//verifier/axioms",
"@maven//:com_google_errorprone_error_prone_annotations",
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,6 +16,7 @@

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.microsoft.z3.ArithExpr;
import com.microsoft.z3.ArrayExpr;
import com.microsoft.z3.BoolExpr;
Expand All@@ -37,6 +38,7 @@
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.ListType;
import dev.cel.common.types.MapType;
import dev.cel.common.types.NullableType;
Expand DownExpand Up@@ -79,6 +81,7 @@ final class CelAstToZ3Translator {
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 final Context ctx;
private final CelZ3TypeSystem typeSystem;
private final CelZ3OperatorTranslator operatorTranslator;
Expand DownExpand Up@@ -370,6 +373,10 @@ private TranslatedValue translateMap(CelExpr celExpr, CelAbstractSyntaxTree ast)

private TranslatedValue translateStruct(CelExpr celExpr, CelAbstractSyntaxTree ast) {
CelExpr.CelStruct createStruct = celExpr.struct();
if (isJsonWkt(createStruct.messageName())) {
return translateJsonWktStruct(celExpr, createStruct, ast);
}

// Bypass SMT when the struct is empty (return the cached SMT default pointer)
if (createStruct.entries().isEmpty()) {
return TranslatedValue.create(
Expand DownExpand Up@@ -448,6 +455,59 @@ private TranslatedValue translateStruct(CelExpr celExpr, CelAbstractSyntaxTree a
return TranslatedValue.propagateStrict(ctx, typeSystem, result, celExpr, elementsTv);
}

private static boolean isJsonWkt(String messageName) {
return messageName.equals(CelTypes.VALUE_MESSAGE)
|| messageName.equals(CelTypes.LIST_VALUE_MESSAGE)
|| messageName.equals(CelTypes.STRUCT_MESSAGE);
}

// Concretize JSON WKT unwrapping directly into native Z3 primitives to avoid
// sort incompatibilities (Message == String) and solver performance penalties (quantifiers).
private TranslatedValue translateJsonWktStruct(
CelExpr celExpr, CelExpr.CelStruct createStruct, CelAbstractSyntaxTree ast) {
Expr<?> fallback;
if (createStruct.messageName().equals(CelTypes.VALUE_MESSAGE)) {
fallback = typeSystem.mkNull();
} else if (createStruct.messageName().equals(CelTypes.LIST_VALUE_MESSAGE)) {
fallback = getDefaultValueForType(ListType.create(SimpleType.DYN));
} else {
fallback = getDefaultValueForType(MapType.create(SimpleType.STRING, SimpleType.DYN));
}

if (createStruct.entries().isEmpty()) {
return TranslatedValue.create(fallback, celExpr, typeSystem, ctx.mkFalse());
}

// 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<?> optRef = typeSystem.getOptionalRef(finalVal);
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();
}

return TranslatedValue.propagateStrict(
ctx, typeSystem, finalVal, celExpr, ImmutableList.of(entryTv));
}

private Expr<?> getDefaultValueForType(CelType type) {
if (type instanceof NullableType) {
return typeSystem.mkNull();
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -805,38 +805,83 @@ private Expr<?> buildMapIndex(

private TranslatedValue translateIndex(
List<TranslatedValue> args, CelAbstractSyntaxTree ast, boolean isOptional) {
Expr<?> lhsTrans = args.get(0).z3Expr();
Expr<?> rhsTrans = args.get(1).z3Expr();

TranslatedValue lhs = args.get(0);
TranslatedValue rhs = args.get(1);
CelType lhsType = extractAstTypeOrDefault(lhs, ast);
CelType rhsType = extractAstTypeOrDefault(rhs, ast);

Expr<?> actualValue;
Expr<?> lhsTrans = lhs.z3Expr();
Expr<?> rhsTrans = rhs.z3Expr();

BoolExpr isLhsOpt = ctx.mkFalse();
BoolExpr lhsHasValue = ctx.mkFalse();
BoolExpr shouldEvaluate = ctx.mkTrue();

if (isOptional) {
isLhsOpt = typeSystem.isOptional(lhsTrans);
Expr<?> optRef = typeSystem.getOptionalRef(lhsTrans);
lhsHasValue = typeSystem.optHasValue(optRef);

lhsTrans = ctx.mkITE(isLhsOpt, typeSystem.getOptionalValue(optRef), lhsTrans);
shouldEvaluate = (BoolExpr) ctx.mkITE(isLhsOpt, lhsHasValue, ctx.mkTrue());

if (lhsType instanceof OptionalType) {
lhsType = lhsType.parameters().get(0);
}
}

Expr<?> actualValue =
buildAndConstrainIndex(lhsTrans, rhsTrans, lhsType, rhsType, shouldEvaluate, isOptional);

if (isOptional) {
actualValue =
ctx.mkITE(
ctx.mkAnd(isLhsOpt, ctx.mkNot(lhsHasValue)),
typeSystem.mkOptionalNone(),
actualValue);
}

return TranslatedValue.propagateStrict(ctx, typeSystem, actualValue, args);
}

private Expr<?> buildAndConstrainIndex(
Expr<?> lhsTrans,
Expr<?> rhsTrans,
CelType lhsType,
CelType rhsType,
BoolExpr shouldEvaluate,
boolean isOptional) {
CelType expectedElemType = null;
if (lhsType.kind() == CelKind.LIST && rhsType.kind() == CelKind.INT) {
actualValue = buildListIndex(lhsTrans, rhsTrans, ctx.mkTrue(), isOptional);
constraintSink.accept(
ctx.mkImplies(
ctx.mkNot(typeSystem.isError(actualValue)),
typeConstraintGenerator.apply(actualValue, ((ListType) lhsType).elemType())));
expectedElemType = ((ListType) lhsType).elemType();
} else if (lhsType.kind() == CelKind.MAP) {
actualValue = buildMapIndex(lhsTrans, rhsTrans, ctx.mkTrue(), isOptional);
expectedElemType = ((MapType) lhsType).valueType();
}

if (expectedElemType != null) {
Expr<?> actualValue =
lhsType.kind() == CelKind.LIST
? buildListIndex(lhsTrans, rhsTrans, shouldEvaluate, isOptional)
: buildMapIndex(lhsTrans, rhsTrans, shouldEvaluate, isOptional);

CelType finalType = isOptional ? OptionalType.create(expectedElemType) : expectedElemType;

constraintSink.accept(
ctx.mkImplies(
ctx.mkNot(typeSystem.isError(actualValue)),
typeConstraintGenerator.apply(actualValue, ((MapType) lhsType).valueType())));
} else {
BoolExpr isListGuard = ctx.mkAnd(typeSystem.isList(lhsTrans), typeSystem.isInt(rhsTrans));
BoolExpr isMapGuard = typeSystem.isMap(lhsTrans);
actualValue =
CelZ3TypeSystem.SwitchBuilder.newBuilder(ctx)
.addCase(isListGuard, buildListIndex(lhsTrans, rhsTrans, isListGuard, isOptional))
.addCase(isMapGuard, buildMapIndex(lhsTrans, rhsTrans, isMapGuard, isOptional))
.build(typeSystem.mkError());
ctx.mkAnd(shouldEvaluate, ctx.mkNot(typeSystem.isError(actualValue))),
typeConstraintGenerator.apply(actualValue, finalType)));

return actualValue;
}

return TranslatedValue.propagateStrict(ctx, typeSystem, actualValue, args);
BoolExpr isListGuard =
ctx.mkAnd(shouldEvaluate, typeSystem.isList(lhsTrans), typeSystem.isInt(rhsTrans));
BoolExpr isMapGuard = ctx.mkAnd(shouldEvaluate, typeSystem.isMap(lhsTrans));

return CelZ3TypeSystem.SwitchBuilder.newBuilder(ctx)
.addCase(isListGuard, buildListIndex(lhsTrans, rhsTrans, isListGuard, isOptional))
.addCase(isMapGuard, buildMapIndex(lhsTrans, rhsTrans, isMapGuard, isOptional))
.build(typeSystem.mkError());
}

private TranslatedValue translateConditional(
Expand Down
88 changes: 75 additions & 13 deletions verifier/src/test/java/dev/cel/verifier/CelVerifierZ3ImplTest.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -115,18 +115,21 @@ public final class CelVerifierZ3ImplTest {
.addVar(
"test_all_types",
StructTypeReference.create("cel.expr.conformance.proto3.TestAllTypes"))
.addVar("json_val", StructTypeReference.create("google.protobuf.Value"))
.addVar("json_list", StructTypeReference.create("google.protobuf.ListValue"))
.addVar("json_struct", StructTypeReference.create("google.protobuf.Struct"))
.build();

private static final CelVerifier VERIFIER =
CelVerifierFactory.newVerifier()
.setTypeProvider(
ProtoMessageTypeProvider.newBuilder()
.addDescriptors(
ImmutableList.of(
TestAllTypes.getDescriptor(), TestAllTypes.NestedMessage.getDescriptor()))
.build())
private static final ProtoMessageTypeProvider TYPE_PROVIDER =
ProtoMessageTypeProvider.newBuilder()
.addDescriptors(
ImmutableList.of(
TestAllTypes.getDescriptor(), TestAllTypes.NestedMessage.getDescriptor()))
.build();

private static final CelVerifier VERIFIER =
CelVerifierFactory.newVerifier().setTypeProvider(TYPE_PROVIDER).build();

@Before
public void setUp() {
System.setProperty("z3.skipLibraryLoad", "true");
Expand DownExpand Up@@ -226,9 +229,6 @@ private enum IsSatisfiableInconclusiveTestCase {
MASKED_BY_BMC_MAP(
"string_int_map == {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6} ? string_int_map.exists(k,"
+ " k == 'g') : false"),
MASKED_BY_BMC_NESTED(
"nested_list == [[1, 2, 3, 4, 5, 6]] ? nested_list.exists(row, row.exists(x, x == 42)) :"
+ " false"),
APPROXIMATED_STRING_TO_INT("int('123') == 123"),
APPROXIMATED_DOUBLE_TO_INT("int(1.5) == 1"),
APPROXIMATED_INT_TO_STRING("string(123) == '123'"),
Expand All@@ -252,6 +252,24 @@ public void isSatisfiable_inconclusive(@TestParameter IsSatisfiableInconclusiveT
assertThat(result.status()).isEqualTo(VerificationStatus.INCONCLUSIVE);
}

@Test
public void isSatisfiable_maskedByBmcNested_inconclusive() throws Exception {
String expr =
"nested_list == [[1, 2, 3, 4, 5, 6]] ? nested_list.exists(row, row.exists(x, x == 42)) :"
+ " false";
CelAbstractSyntaxTree ast = CEL.compile(expr).getAst();

CelVerifier customVerifier =
CelVerifierFactory.newVerifier()
.setComprehensionUnrollLimit(3)
.setTypeProvider(TYPE_PROVIDER)
.build();

CelVerificationResult result = customVerifier.isSatisfiable(ast);

assertThat(result.status()).isEqualTo(VerificationStatus.INCONCLUSIVE);
}

@Test
public void isSatisfiable_comprehensionZeroUnrollLimit_inconclusive() throws Exception {
String expr = "int_list == [1] ? int_list.exists(x, x == 1) : false";
Expand DownExpand Up@@ -1581,6 +1599,9 @@ private enum EquivalenceTestCase {
"TestAllTypes{}.?single_int64_wrapper", "optional.none()"),
OPTIONAL_FIELD_SELECTION_PROTO3_WRAPPER_EXPLICIT_NULL(
"TestAllTypes{single_int64_wrapper: null}.?single_int64_wrapper", "optional.none()"),
OPTIONAL_FIELD_SELECTION_PROTO3_WRAPPER_OPTIONAL_NONE(
"TestAllTypes{?single_int64_wrapper: optional.none()}.?single_int64_wrapper",
"optional.none()"),
OPTIONAL_FIELD_SELECTION_PROTO3_WRAPPER_PRESENT(
"TestAllTypes{single_int64_wrapper: 42}.?single_int64_wrapper", "optional.of(42)"),
OPTIONAL_FIELD_SELECTION_DYNAMIC_MISS(
Expand All@@ -1590,7 +1611,43 @@ private enum EquivalenceTestCase {
"true"),
OPTIONAL_FIELD_SELECTION_MAP_COMPREHENSION(
"{'a': 1, 'b': 2}.transformMap(k, v, v > 1, v).?b", "optional.of(2)"),
OPTIONAL_FIELD_SELECTION_BINDER("cel.bind(m, {'a': 1}, m.?a)", "optional.of(1)");
OPTIONAL_FIELD_SELECTION_BINDER("cel.bind(m, {'a': 1}, m.?a)", "optional.of(1)"),
JSON_VALUE_BOOL("google.protobuf.Value{bool_value: true}", "true"),
JSON_VALUE_NUMBER("google.protobuf.Value{number_value: 1.0}", "1.0"),
JSON_VALUE_NULL("google.protobuf.Value{null_value: 0}", "null"),
JSON_VALUE_EMPTY("google.protobuf.Value{}", "null"),
JSON_LIST_VALUE_EMPTY("google.protobuf.ListValue{}", "[]"),
JSON_STRUCT_EMPTY("google.protobuf.Struct{}", "{}"),
JSON_LIST_VALUE("google.protobuf.ListValue{values: [1, 2]}", "[1, 2]"),
JSON_STRUCT("google.protobuf.Struct{fields: {'a': 1}}", "{'a': 1}"),
JSON_STRUCT_MULTIPLE_FIELDS(
"google.protobuf.Struct{fields: {'a': 1, 'b': 'hello'}}", "{'a': 1, 'b': 'hello'}"),
JSON_STRUCT_EXPLICIT_VALUES(
"google.protobuf.Struct{fields: {'a': google.protobuf.Value{number_value: 1.0}, 'b':"
+ " google.protobuf.Value{string_value: 'hello'}}}",
"{'a': 1.0, 'b': 'hello'}"),
JSON_STRUCT_OPTIONAL_ENTRIES(
"google.protobuf.Struct{fields: {'a': 1, ?'b': optional.of(2), ?'c': optional.none()}}",
"{'a': 1, 'b': 2}"),
JSON_DEEP_NESTING(
"google.protobuf.ListValue{values: [google.protobuf.Struct{fields: {'a':"
+ " google.protobuf.Value{number_value: 1.0}}}]}",
"[{'a': 1.0}]"),
JSON_NUMBER_HETEROGENEOUS_EQUALITY("google.protobuf.Value{number_value: 1.0} == 1", "true"),
JSON_VALUE_OPTIONAL_NONE("google.protobuf.Value{?string_value: optional.none()}", "null"),
JSON_LIST_VALUE_OPTIONAL_NONE("google.protobuf.ListValue{?values: optional.none()}", "[]"),
JSON_STRUCT_OPTIONAL_NONE("google.protobuf.Struct{?fields: optional.none()}", "{}"),
JSON_VALUE_TYPE_REFLECTION("type(google.protobuf.Value{string_value: 'hi'}) == string", "true"),
JSON_STRUCT_TYPE_REFLECTION("type(google.protobuf.Struct{fields: {'a': 1}}) == map", "true"),
JSON_VAR_VALUE_EQUALITY("json_val == 'hi' || json_val != 'hi'", "true"),
JSON_VAR_LIST_EQUALITY("json_list == [1, 2] || json_list != [1, 2]", "true"),
JSON_VAR_MAP_EQUALITY("json_struct == {'a': 1} || json_struct != {'a': 1}", "true"),
JSON_VALUE_OPTIONAL_NULL_VALUE_NONE(
"google.protobuf.Value{?null_value: optional.none()}", "null"),
JSON_VALUE_OPTIONAL_NULL_VALUE_OF("google.protobuf.Value{?null_value: optional.of(0)}", "null"),
OPTIONAL_INDEX_LIST_UNWRAPPING("optional.of([1, 2, 3])[?0]", "optional.of(1)"),
OPTIONAL_INDEX_MAP_UNWRAPPING("optional.of({'a': 1})[?'a']", "optional.of(1)"),
OPTIONAL_INDEX_UNWRAPPING_NONE("optional.none()[?0]", "optional.none()");

private final String exprA;
private final String exprB;
Expand DownExpand Up@@ -1644,7 +1701,12 @@ private enum EquivalenceViolationTestCase {
"TestAllTypes{single_int32: 0}.?single_int32", "optional.of(0)"),
OPTIONAL_PROTO3_WRAPPER_ZERO_VS_UNSET(
"TestAllTypes{single_int64_wrapper: 0}.?single_int64_wrapper",
"TestAllTypes{}.?single_int64_wrapper");
"TestAllTypes{}.?single_int64_wrapper"),
OPTIONAL_PROTO3_WRAPPER_ZERO_VS_NONE(
"TestAllTypes{single_int64_wrapper: 0}.?single_int64_wrapper", "optional.none()"),
OPTIONAL_DYNAMIC_TARGET_TYPE_MISMATCH("dyn_var.?a == optional.none()", "false"),
OPTIONAL_NESTED_NONE_VS_MISSING(
"{'a': optional.none()}.?a.orValue(optional.of(1))", "optional.of(1)");

final String exprA;
final String exprB;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions verifier/src/main/java/dev/cel/verifier/BUILD.bazel
Original file line numberDiff line numberDiff line change
Expand Up@@ -129,6 +129,7 @@ java_library(
"//common/ast",
"//common/ast:cel_block",
"//common/types",
"//common/types:cel_types",
"//common/types:type_providers",
"//verifier/axioms",
"@maven//:com_google_errorprone_error_prone_annotations",
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,6 +16,7 @@

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.microsoft.z3.ArithExpr;
import com.microsoft.z3.ArrayExpr;
import com.microsoft.z3.BoolExpr;
Expand All@@ -37,6 +38,7 @@
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.ListType;
import dev.cel.common.types.MapType;
import dev.cel.common.types.NullableType;
Expand DownExpand Up@@ -79,6 +81,7 @@ final class CelAstToZ3Translator {
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 final Context ctx;
private final CelZ3TypeSystem typeSystem;
private final CelZ3OperatorTranslator operatorTranslator;
Expand DownExpand Up@@ -370,6 +373,10 @@ private TranslatedValue translateMap(CelExpr celExpr, CelAbstractSyntaxTree ast)

private TranslatedValue translateStruct(CelExpr celExpr, CelAbstractSyntaxTree ast) {
CelExpr.CelStruct createStruct = celExpr.struct();
if (isJsonWkt(createStruct.messageName())) {
return translateJsonWktStruct(celExpr, createStruct, ast);
}

// Bypass SMT when the struct is empty (return the cached SMT default pointer)
if (createStruct.entries().isEmpty()) {
return TranslatedValue.create(
Expand DownExpand Up@@ -448,6 +455,59 @@ private TranslatedValue translateStruct(CelExpr celExpr, CelAbstractSyntaxTree a
return TranslatedValue.propagateStrict(ctx, typeSystem, result, celExpr, elementsTv);
}

private static boolean isJsonWkt(String messageName) {
return messageName.equals(CelTypes.VALUE_MESSAGE)
|| messageName.equals(CelTypes.LIST_VALUE_MESSAGE)
|| messageName.equals(CelTypes.STRUCT_MESSAGE);
}

// Concretize JSON WKT unwrapping directly into native Z3 primitives to avoid
// sort incompatibilities (Message == String) and solver performance penalties (quantifiers).
private TranslatedValue translateJsonWktStruct(
CelExpr celExpr, CelExpr.CelStruct createStruct, CelAbstractSyntaxTree ast) {
Expr<?> fallback;
if (createStruct.messageName().equals(CelTypes.VALUE_MESSAGE)) {
fallback = typeSystem.mkNull();
} else if (createStruct.messageName().equals(CelTypes.LIST_VALUE_MESSAGE)) {
fallback = getDefaultValueForType(ListType.create(SimpleType.DYN));
} else {
fallback = getDefaultValueForType(MapType.create(SimpleType.STRING, SimpleType.DYN));
}

if (createStruct.entries().isEmpty()) {
return TranslatedValue.create(fallback, celExpr, typeSystem, ctx.mkFalse());
}

// 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<?> optRef = typeSystem.getOptionalRef(finalVal);
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();
}

return TranslatedValue.propagateStrict(
ctx, typeSystem, finalVal, celExpr, ImmutableList.of(entryTv));
}

private Expr<?> getDefaultValueForType(CelType type) {
if (type instanceof NullableType) {
return typeSystem.mkNull();
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -805,38 +805,83 @@ private Expr<?> buildMapIndex(

private TranslatedValue translateIndex(
List<TranslatedValue> args, CelAbstractSyntaxTree ast, boolean isOptional) {
Expr<?> lhsTrans = args.get(0).z3Expr();
Expr<?> rhsTrans = args.get(1).z3Expr();

TranslatedValue lhs = args.get(0);
TranslatedValue rhs = args.get(1);
CelType lhsType = extractAstTypeOrDefault(lhs, ast);
CelType rhsType = extractAstTypeOrDefault(rhs, ast);

Expr<?> actualValue;
Expr<?> lhsTrans = lhs.z3Expr();
Expr<?> rhsTrans = rhs.z3Expr();

BoolExpr isLhsOpt = ctx.mkFalse();
BoolExpr lhsHasValue = ctx.mkFalse();
BoolExpr shouldEvaluate = ctx.mkTrue();

if (isOptional) {
isLhsOpt = typeSystem.isOptional(lhsTrans);
Expr<?> optRef = typeSystem.getOptionalRef(lhsTrans);
lhsHasValue = typeSystem.optHasValue(optRef);

lhsTrans = ctx.mkITE(isLhsOpt, typeSystem.getOptionalValue(optRef), lhsTrans);
shouldEvaluate = (BoolExpr) ctx.mkITE(isLhsOpt, lhsHasValue, ctx.mkTrue());

if (lhsType instanceof OptionalType) {
lhsType = lhsType.parameters().get(0);
}
}

Expr<?> actualValue =
buildAndConstrainIndex(lhsTrans, rhsTrans, lhsType, rhsType, shouldEvaluate, isOptional);

if (isOptional) {
actualValue =
ctx.mkITE(
ctx.mkAnd(isLhsOpt, ctx.mkNot(lhsHasValue)),
typeSystem.mkOptionalNone(),
actualValue);
}

return TranslatedValue.propagateStrict(ctx, typeSystem, actualValue, args);
}

private Expr<?> buildAndConstrainIndex(
Expr<?> lhsTrans,
Expr<?> rhsTrans,
CelType lhsType,
CelType rhsType,
BoolExpr shouldEvaluate,
boolean isOptional) {
CelType expectedElemType = null;
if (lhsType.kind() == CelKind.LIST && rhsType.kind() == CelKind.INT) {
actualValue = buildListIndex(lhsTrans, rhsTrans, ctx.mkTrue(), isOptional);
constraintSink.accept(
ctx.mkImplies(
ctx.mkNot(typeSystem.isError(actualValue)),
typeConstraintGenerator.apply(actualValue, ((ListType) lhsType).elemType())));
expectedElemType = ((ListType) lhsType).elemType();
} else if (lhsType.kind() == CelKind.MAP) {
actualValue = buildMapIndex(lhsTrans, rhsTrans, ctx.mkTrue(), isOptional);
expectedElemType = ((MapType) lhsType).valueType();
}

if (expectedElemType != null) {
Expr<?> actualValue =
lhsType.kind() == CelKind.LIST
? buildListIndex(lhsTrans, rhsTrans, shouldEvaluate, isOptional)
: buildMapIndex(lhsTrans, rhsTrans, shouldEvaluate, isOptional);

CelType finalType = isOptional ? OptionalType.create(expectedElemType) : expectedElemType;

constraintSink.accept(
ctx.mkImplies(
ctx.mkNot(typeSystem.isError(actualValue)),
typeConstraintGenerator.apply(actualValue, ((MapType) lhsType).valueType())));
} else {
BoolExpr isListGuard = ctx.mkAnd(typeSystem.isList(lhsTrans), typeSystem.isInt(rhsTrans));
BoolExpr isMapGuard = typeSystem.isMap(lhsTrans);
actualValue =
CelZ3TypeSystem.SwitchBuilder.newBuilder(ctx)
.addCase(isListGuard, buildListIndex(lhsTrans, rhsTrans, isListGuard, isOptional))
.addCase(isMapGuard, buildMapIndex(lhsTrans, rhsTrans, isMapGuard, isOptional))
.build(typeSystem.mkError());
ctx.mkAnd(shouldEvaluate, ctx.mkNot(typeSystem.isError(actualValue))),
typeConstraintGenerator.apply(actualValue, finalType)));

return actualValue;
}

return TranslatedValue.propagateStrict(ctx, typeSystem, actualValue, args);
BoolExpr isListGuard =
ctx.mkAnd(shouldEvaluate, typeSystem.isList(lhsTrans), typeSystem.isInt(rhsTrans));
BoolExpr isMapGuard = ctx.mkAnd(shouldEvaluate, typeSystem.isMap(lhsTrans));

return CelZ3TypeSystem.SwitchBuilder.newBuilder(ctx)
.addCase(isListGuard, buildListIndex(lhsTrans, rhsTrans, isListGuard, isOptional))
.addCase(isMapGuard, buildMapIndex(lhsTrans, rhsTrans, isMapGuard, isOptional))
.build(typeSystem.mkError());
}

private TranslatedValue translateConditional(
Expand Down
88 changes: 75 additions & 13 deletions verifier/src/test/java/dev/cel/verifier/CelVerifierZ3ImplTest.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -115,18 +115,21 @@ public final class CelVerifierZ3ImplTest {
.addVar(
"test_all_types",
StructTypeReference.create("cel.expr.conformance.proto3.TestAllTypes"))
.addVar("json_val", StructTypeReference.create("google.protobuf.Value"))
.addVar("json_list", StructTypeReference.create("google.protobuf.ListValue"))
.addVar("json_struct", StructTypeReference.create("google.protobuf.Struct"))
.build();

private static final CelVerifier VERIFIER =
CelVerifierFactory.newVerifier()
.setTypeProvider(
ProtoMessageTypeProvider.newBuilder()
.addDescriptors(
ImmutableList.of(
TestAllTypes.getDescriptor(), TestAllTypes.NestedMessage.getDescriptor()))
.build())
private static final ProtoMessageTypeProvider TYPE_PROVIDER =
ProtoMessageTypeProvider.newBuilder()
.addDescriptors(
ImmutableList.of(
TestAllTypes.getDescriptor(), TestAllTypes.NestedMessage.getDescriptor()))
.build();

private static final CelVerifier VERIFIER =
CelVerifierFactory.newVerifier().setTypeProvider(TYPE_PROVIDER).build();

@Before
public void setUp() {
System.setProperty("z3.skipLibraryLoad", "true");
Expand DownExpand Up@@ -226,9 +229,6 @@ private enum IsSatisfiableInconclusiveTestCase {
MASKED_BY_BMC_MAP(
"string_int_map == {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6} ? string_int_map.exists(k,"
+ " k == 'g') : false"),
MASKED_BY_BMC_NESTED(
"nested_list == [[1, 2, 3, 4, 5, 6]] ? nested_list.exists(row, row.exists(x, x == 42)) :"
+ " false"),
APPROXIMATED_STRING_TO_INT("int('123') == 123"),
APPROXIMATED_DOUBLE_TO_INT("int(1.5) == 1"),
APPROXIMATED_INT_TO_STRING("string(123) == '123'"),
Expand All@@ -252,6 +252,24 @@ public void isSatisfiable_inconclusive(@TestParameter IsSatisfiableInconclusiveT
assertThat(result.status()).isEqualTo(VerificationStatus.INCONCLUSIVE);
}

@Test
public void isSatisfiable_maskedByBmcNested_inconclusive() throws Exception {
String expr =
"nested_list == [[1, 2, 3, 4, 5, 6]] ? nested_list.exists(row, row.exists(x, x == 42)) :"
+ " false";
CelAbstractSyntaxTree ast = CEL.compile(expr).getAst();

CelVerifier customVerifier =
CelVerifierFactory.newVerifier()
.setComprehensionUnrollLimit(3)
.setTypeProvider(TYPE_PROVIDER)
.build();

CelVerificationResult result = customVerifier.isSatisfiable(ast);

assertThat(result.status()).isEqualTo(VerificationStatus.INCONCLUSIVE);
}

@Test
public void isSatisfiable_comprehensionZeroUnrollLimit_inconclusive() throws Exception {
String expr = "int_list == [1] ? int_list.exists(x, x == 1) : false";
Expand DownExpand Up@@ -1581,6 +1599,9 @@ private enum EquivalenceTestCase {
"TestAllTypes{}.?single_int64_wrapper", "optional.none()"),
OPTIONAL_FIELD_SELECTION_PROTO3_WRAPPER_EXPLICIT_NULL(
"TestAllTypes{single_int64_wrapper: null}.?single_int64_wrapper", "optional.none()"),
OPTIONAL_FIELD_SELECTION_PROTO3_WRAPPER_OPTIONAL_NONE(
"TestAllTypes{?single_int64_wrapper: optional.none()}.?single_int64_wrapper",
"optional.none()"),
OPTIONAL_FIELD_SELECTION_PROTO3_WRAPPER_PRESENT(
"TestAllTypes{single_int64_wrapper: 42}.?single_int64_wrapper", "optional.of(42)"),
OPTIONAL_FIELD_SELECTION_DYNAMIC_MISS(
Expand All@@ -1590,7 +1611,43 @@ private enum EquivalenceTestCase {
"true"),
OPTIONAL_FIELD_SELECTION_MAP_COMPREHENSION(
"{'a': 1, 'b': 2}.transformMap(k, v, v > 1, v).?b", "optional.of(2)"),
OPTIONAL_FIELD_SELECTION_BINDER("cel.bind(m, {'a': 1}, m.?a)", "optional.of(1)");
OPTIONAL_FIELD_SELECTION_BINDER("cel.bind(m, {'a': 1}, m.?a)", "optional.of(1)"),
JSON_VALUE_BOOL("google.protobuf.Value{bool_value: true}", "true"),
JSON_VALUE_NUMBER("google.protobuf.Value{number_value: 1.0}", "1.0"),
JSON_VALUE_NULL("google.protobuf.Value{null_value: 0}", "null"),
JSON_VALUE_EMPTY("google.protobuf.Value{}", "null"),
JSON_LIST_VALUE_EMPTY("google.protobuf.ListValue{}", "[]"),
JSON_STRUCT_EMPTY("google.protobuf.Struct{}", "{}"),
JSON_LIST_VALUE("google.protobuf.ListValue{values: [1, 2]}", "[1, 2]"),
JSON_STRUCT("google.protobuf.Struct{fields: {'a': 1}}", "{'a': 1}"),
JSON_STRUCT_MULTIPLE_FIELDS(
"google.protobuf.Struct{fields: {'a': 1, 'b': 'hello'}}", "{'a': 1, 'b': 'hello'}"),
JSON_STRUCT_EXPLICIT_VALUES(
"google.protobuf.Struct{fields: {'a': google.protobuf.Value{number_value: 1.0}, 'b':"
+ " google.protobuf.Value{string_value: 'hello'}}}",
"{'a': 1.0, 'b': 'hello'}"),
JSON_STRUCT_OPTIONAL_ENTRIES(
"google.protobuf.Struct{fields: {'a': 1, ?'b': optional.of(2), ?'c': optional.none()}}",
"{'a': 1, 'b': 2}"),
JSON_DEEP_NESTING(
"google.protobuf.ListValue{values: [google.protobuf.Struct{fields: {'a':"
+ " google.protobuf.Value{number_value: 1.0}}}]}",
"[{'a': 1.0}]"),
JSON_NUMBER_HETEROGENEOUS_EQUALITY("google.protobuf.Value{number_value: 1.0} == 1", "true"),
JSON_VALUE_OPTIONAL_NONE("google.protobuf.Value{?string_value: optional.none()}", "null"),
JSON_LIST_VALUE_OPTIONAL_NONE("google.protobuf.ListValue{?values: optional.none()}", "[]"),
JSON_STRUCT_OPTIONAL_NONE("google.protobuf.Struct{?fields: optional.none()}", "{}"),
JSON_VALUE_TYPE_REFLECTION("type(google.protobuf.Value{string_value: 'hi'}) == string", "true"),
JSON_STRUCT_TYPE_REFLECTION("type(google.protobuf.Struct{fields: {'a': 1}}) == map", "true"),
JSON_VAR_VALUE_EQUALITY("json_val == 'hi' || json_val != 'hi'", "true"),
JSON_VAR_LIST_EQUALITY("json_list == [1, 2] || json_list != [1, 2]", "true"),
JSON_VAR_MAP_EQUALITY("json_struct == {'a': 1} || json_struct != {'a': 1}", "true"),
JSON_VALUE_OPTIONAL_NULL_VALUE_NONE(
"google.protobuf.Value{?null_value: optional.none()}", "null"),
JSON_VALUE_OPTIONAL_NULL_VALUE_OF("google.protobuf.Value{?null_value: optional.of(0)}", "null"),
OPTIONAL_INDEX_LIST_UNWRAPPING("optional.of([1, 2, 3])[?0]", "optional.of(1)"),
OPTIONAL_INDEX_MAP_UNWRAPPING("optional.of({'a': 1})[?'a']", "optional.of(1)"),
OPTIONAL_INDEX_UNWRAPPING_NONE("optional.none()[?0]", "optional.none()");

private final String exprA;
private final String exprB;
Expand DownExpand Up@@ -1644,7 +1701,12 @@ private enum EquivalenceViolationTestCase {
"TestAllTypes{single_int32: 0}.?single_int32", "optional.of(0)"),
OPTIONAL_PROTO3_WRAPPER_ZERO_VS_UNSET(
"TestAllTypes{single_int64_wrapper: 0}.?single_int64_wrapper",
"TestAllTypes{}.?single_int64_wrapper");
"TestAllTypes{}.?single_int64_wrapper"),
OPTIONAL_PROTO3_WRAPPER_ZERO_VS_NONE(
"TestAllTypes{single_int64_wrapper: 0}.?single_int64_wrapper", "optional.none()"),
OPTIONAL_DYNAMIC_TARGET_TYPE_MISMATCH("dyn_var.?a == optional.none()", "false"),
OPTIONAL_NESTED_NONE_VS_MISSING(
"{'a': optional.none()}.?a.orValue(optional.of(1))", "optional.of(1)");

final String exprA;
final String exprB;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions verifier/src/main/java/dev/cel/verifier/BUILD.bazel
Original file line numberDiff line numberDiff line change
Expand Up@@ -129,6 +129,7 @@ java_library(
"//common/ast",
"//common/ast:cel_block",
"//common/types",
"//common/types:cel_types",
"//common/types:type_providers",
"//verifier/axioms",
"@maven//:com_google_errorprone_error_prone_annotations",
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,6 +16,7 @@

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.microsoft.z3.ArithExpr;
import com.microsoft.z3.ArrayExpr;
import com.microsoft.z3.BoolExpr;
Expand All@@ -37,6 +38,7 @@
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.ListType;
import dev.cel.common.types.MapType;
import dev.cel.common.types.NullableType;
Expand DownExpand Up@@ -79,6 +81,7 @@ final class CelAstToZ3Translator {
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 final Context ctx;
private final CelZ3TypeSystem typeSystem;
private final CelZ3OperatorTranslator operatorTranslator;
Expand DownExpand Up@@ -370,6 +373,10 @@ private TranslatedValue translateMap(CelExpr celExpr, CelAbstractSyntaxTree ast)

private TranslatedValue translateStruct(CelExpr celExpr, CelAbstractSyntaxTree ast) {
CelExpr.CelStruct createStruct = celExpr.struct();
if (isJsonWkt(createStruct.messageName())) {
return translateJsonWktStruct(celExpr, createStruct, ast);
}

// Bypass SMT when the struct is empty (return the cached SMT default pointer)
if (createStruct.entries().isEmpty()) {
return TranslatedValue.create(
Expand DownExpand Up@@ -448,6 +455,59 @@ private TranslatedValue translateStruct(CelExpr celExpr, CelAbstractSyntaxTree a
return TranslatedValue.propagateStrict(ctx, typeSystem, result, celExpr, elementsTv);
}

private static boolean isJsonWkt(String messageName) {
return messageName.equals(CelTypes.VALUE_MESSAGE)
|| messageName.equals(CelTypes.LIST_VALUE_MESSAGE)
|| messageName.equals(CelTypes.STRUCT_MESSAGE);
}

// Concretize JSON WKT unwrapping directly into native Z3 primitives to avoid
// sort incompatibilities (Message == String) and solver performance penalties (quantifiers).
private TranslatedValue translateJsonWktStruct(
CelExpr celExpr, CelExpr.CelStruct createStruct, CelAbstractSyntaxTree ast) {
Expr<?> fallback;
if (createStruct.messageName().equals(CelTypes.VALUE_MESSAGE)) {
fallback = typeSystem.mkNull();
} else if (createStruct.messageName().equals(CelTypes.LIST_VALUE_MESSAGE)) {
fallback = getDefaultValueForType(ListType.create(SimpleType.DYN));
} else {
fallback = getDefaultValueForType(MapType.create(SimpleType.STRING, SimpleType.DYN));
}

if (createStruct.entries().isEmpty()) {
return TranslatedValue.create(fallback, celExpr, typeSystem, ctx.mkFalse());
}

// 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<?> optRef = typeSystem.getOptionalRef(finalVal);
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();
}

return TranslatedValue.propagateStrict(
ctx, typeSystem, finalVal, celExpr, ImmutableList.of(entryTv));
}

private Expr<?> getDefaultValueForType(CelType type) {
if (type instanceof NullableType) {
return typeSystem.mkNull();
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -805,38 +805,83 @@ private Expr<?> buildMapIndex(

private TranslatedValue translateIndex(
List<TranslatedValue> args, CelAbstractSyntaxTree ast, boolean isOptional) {
Expr<?> lhsTrans = args.get(0).z3Expr();
Expr<?> rhsTrans = args.get(1).z3Expr();

TranslatedValue lhs = args.get(0);
TranslatedValue rhs = args.get(1);
CelType lhsType = extractAstTypeOrDefault(lhs, ast);
CelType rhsType = extractAstTypeOrDefault(rhs, ast);

Expr<?> actualValue;
Expr<?> lhsTrans = lhs.z3Expr();
Expr<?> rhsTrans = rhs.z3Expr();

BoolExpr isLhsOpt = ctx.mkFalse();
BoolExpr lhsHasValue = ctx.mkFalse();
BoolExpr shouldEvaluate = ctx.mkTrue();

if (isOptional) {
isLhsOpt = typeSystem.isOptional(lhsTrans);
Expr<?> optRef = typeSystem.getOptionalRef(lhsTrans);
lhsHasValue = typeSystem.optHasValue(optRef);

lhsTrans = ctx.mkITE(isLhsOpt, typeSystem.getOptionalValue(optRef), lhsTrans);
shouldEvaluate = (BoolExpr) ctx.mkITE(isLhsOpt, lhsHasValue, ctx.mkTrue());

if (lhsType instanceof OptionalType) {
lhsType = lhsType.parameters().get(0);
}
}

Expr<?> actualValue =
buildAndConstrainIndex(lhsTrans, rhsTrans, lhsType, rhsType, shouldEvaluate, isOptional);

if (isOptional) {
actualValue =
ctx.mkITE(
ctx.mkAnd(isLhsOpt, ctx.mkNot(lhsHasValue)),
typeSystem.mkOptionalNone(),
actualValue);
}

return TranslatedValue.propagateStrict(ctx, typeSystem, actualValue, args);
}

private Expr<?> buildAndConstrainIndex(
Expr<?> lhsTrans,
Expr<?> rhsTrans,
CelType lhsType,
CelType rhsType,
BoolExpr shouldEvaluate,
boolean isOptional) {
CelType expectedElemType = null;
if (lhsType.kind() == CelKind.LIST && rhsType.kind() == CelKind.INT) {
actualValue = buildListIndex(lhsTrans, rhsTrans, ctx.mkTrue(), isOptional);
constraintSink.accept(
ctx.mkImplies(
ctx.mkNot(typeSystem.isError(actualValue)),
typeConstraintGenerator.apply(actualValue, ((ListType) lhsType).elemType())));
expectedElemType = ((ListType) lhsType).elemType();
} else if (lhsType.kind() == CelKind.MAP) {
actualValue = buildMapIndex(lhsTrans, rhsTrans, ctx.mkTrue(), isOptional);
expectedElemType = ((MapType) lhsType).valueType();
}

if (expectedElemType != null) {
Expr<?> actualValue =
lhsType.kind() == CelKind.LIST
? buildListIndex(lhsTrans, rhsTrans, shouldEvaluate, isOptional)
: buildMapIndex(lhsTrans, rhsTrans, shouldEvaluate, isOptional);

CelType finalType = isOptional ? OptionalType.create(expectedElemType) : expectedElemType;

constraintSink.accept(
ctx.mkImplies(
ctx.mkNot(typeSystem.isError(actualValue)),
typeConstraintGenerator.apply(actualValue, ((MapType) lhsType).valueType())));
} else {
BoolExpr isListGuard = ctx.mkAnd(typeSystem.isList(lhsTrans), typeSystem.isInt(rhsTrans));
BoolExpr isMapGuard = typeSystem.isMap(lhsTrans);
actualValue =
CelZ3TypeSystem.SwitchBuilder.newBuilder(ctx)
.addCase(isListGuard, buildListIndex(lhsTrans, rhsTrans, isListGuard, isOptional))
.addCase(isMapGuard, buildMapIndex(lhsTrans, rhsTrans, isMapGuard, isOptional))
.build(typeSystem.mkError());
ctx.mkAnd(shouldEvaluate, ctx.mkNot(typeSystem.isError(actualValue))),
typeConstraintGenerator.apply(actualValue, finalType)));

return actualValue;
}

return TranslatedValue.propagateStrict(ctx, typeSystem, actualValue, args);
BoolExpr isListGuard =
ctx.mkAnd(shouldEvaluate, typeSystem.isList(lhsTrans), typeSystem.isInt(rhsTrans));
BoolExpr isMapGuard = ctx.mkAnd(shouldEvaluate, typeSystem.isMap(lhsTrans));

return CelZ3TypeSystem.SwitchBuilder.newBuilder(ctx)
.addCase(isListGuard, buildListIndex(lhsTrans, rhsTrans, isListGuard, isOptional))
.addCase(isMapGuard, buildMapIndex(lhsTrans, rhsTrans, isMapGuard, isOptional))
.build(typeSystem.mkError());
}

private TranslatedValue translateConditional(
Expand Down
88 changes: 75 additions & 13 deletions verifier/src/test/java/dev/cel/verifier/CelVerifierZ3ImplTest.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -115,18 +115,21 @@ public final class CelVerifierZ3ImplTest {
.addVar(
"test_all_types",
StructTypeReference.create("cel.expr.conformance.proto3.TestAllTypes"))
.addVar("json_val", StructTypeReference.create("google.protobuf.Value"))
.addVar("json_list", StructTypeReference.create("google.protobuf.ListValue"))
.addVar("json_struct", StructTypeReference.create("google.protobuf.Struct"))
.build();

private static final CelVerifier VERIFIER =
CelVerifierFactory.newVerifier()
.setTypeProvider(
ProtoMessageTypeProvider.newBuilder()
.addDescriptors(
ImmutableList.of(
TestAllTypes.getDescriptor(), TestAllTypes.NestedMessage.getDescriptor()))
.build())
private static final ProtoMessageTypeProvider TYPE_PROVIDER =
ProtoMessageTypeProvider.newBuilder()
.addDescriptors(
ImmutableList.of(
TestAllTypes.getDescriptor(), TestAllTypes.NestedMessage.getDescriptor()))
.build();

private static final CelVerifier VERIFIER =
CelVerifierFactory.newVerifier().setTypeProvider(TYPE_PROVIDER).build();

@Before
public void setUp() {
System.setProperty("z3.skipLibraryLoad", "true");
Expand DownExpand Up@@ -226,9 +229,6 @@ private enum IsSatisfiableInconclusiveTestCase {
MASKED_BY_BMC_MAP(
"string_int_map == {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6} ? string_int_map.exists(k,"
+ " k == 'g') : false"),
MASKED_BY_BMC_NESTED(
"nested_list == [[1, 2, 3, 4, 5, 6]] ? nested_list.exists(row, row.exists(x, x == 42)) :"
+ " false"),
APPROXIMATED_STRING_TO_INT("int('123') == 123"),
APPROXIMATED_DOUBLE_TO_INT("int(1.5) == 1"),
APPROXIMATED_INT_TO_STRING("string(123) == '123'"),
Expand All@@ -252,6 +252,24 @@ public void isSatisfiable_inconclusive(@TestParameter IsSatisfiableInconclusiveT
assertThat(result.status()).isEqualTo(VerificationStatus.INCONCLUSIVE);
}

@Test
public void isSatisfiable_maskedByBmcNested_inconclusive() throws Exception {
String expr =
"nested_list == [[1, 2, 3, 4, 5, 6]] ? nested_list.exists(row, row.exists(x, x == 42)) :"
+ " false";
CelAbstractSyntaxTree ast = CEL.compile(expr).getAst();

CelVerifier customVerifier =
CelVerifierFactory.newVerifier()
.setComprehensionUnrollLimit(3)
.setTypeProvider(TYPE_PROVIDER)
.build();

CelVerificationResult result = customVerifier.isSatisfiable(ast);

assertThat(result.status()).isEqualTo(VerificationStatus.INCONCLUSIVE);
}

@Test
public void isSatisfiable_comprehensionZeroUnrollLimit_inconclusive() throws Exception {
String expr = "int_list == [1] ? int_list.exists(x, x == 1) : false";
Expand DownExpand Up@@ -1581,6 +1599,9 @@ private enum EquivalenceTestCase {
"TestAllTypes{}.?single_int64_wrapper", "optional.none()"),
OPTIONAL_FIELD_SELECTION_PROTO3_WRAPPER_EXPLICIT_NULL(
"TestAllTypes{single_int64_wrapper: null}.?single_int64_wrapper", "optional.none()"),
OPTIONAL_FIELD_SELECTION_PROTO3_WRAPPER_OPTIONAL_NONE(
"TestAllTypes{?single_int64_wrapper: optional.none()}.?single_int64_wrapper",
"optional.none()"),
OPTIONAL_FIELD_SELECTION_PROTO3_WRAPPER_PRESENT(
"TestAllTypes{single_int64_wrapper: 42}.?single_int64_wrapper", "optional.of(42)"),
OPTIONAL_FIELD_SELECTION_DYNAMIC_MISS(
Expand All@@ -1590,7 +1611,43 @@ private enum EquivalenceTestCase {
"true"),
OPTIONAL_FIELD_SELECTION_MAP_COMPREHENSION(
"{'a': 1, 'b': 2}.transformMap(k, v, v > 1, v).?b", "optional.of(2)"),
OPTIONAL_FIELD_SELECTION_BINDER("cel.bind(m, {'a': 1}, m.?a)", "optional.of(1)");
OPTIONAL_FIELD_SELECTION_BINDER("cel.bind(m, {'a': 1}, m.?a)", "optional.of(1)"),
JSON_VALUE_BOOL("google.protobuf.Value{bool_value: true}", "true"),
JSON_VALUE_NUMBER("google.protobuf.Value{number_value: 1.0}", "1.0"),
JSON_VALUE_NULL("google.protobuf.Value{null_value: 0}", "null"),
JSON_VALUE_EMPTY("google.protobuf.Value{}", "null"),
JSON_LIST_VALUE_EMPTY("google.protobuf.ListValue{}", "[]"),
JSON_STRUCT_EMPTY("google.protobuf.Struct{}", "{}"),
JSON_LIST_VALUE("google.protobuf.ListValue{values: [1, 2]}", "[1, 2]"),
JSON_STRUCT("google.protobuf.Struct{fields: {'a': 1}}", "{'a': 1}"),
JSON_STRUCT_MULTIPLE_FIELDS(
"google.protobuf.Struct{fields: {'a': 1, 'b': 'hello'}}", "{'a': 1, 'b': 'hello'}"),
JSON_STRUCT_EXPLICIT_VALUES(
"google.protobuf.Struct{fields: {'a': google.protobuf.Value{number_value: 1.0}, 'b':"
+ " google.protobuf.Value{string_value: 'hello'}}}",
"{'a': 1.0, 'b': 'hello'}"),
JSON_STRUCT_OPTIONAL_ENTRIES(
"google.protobuf.Struct{fields: {'a': 1, ?'b': optional.of(2), ?'c': optional.none()}}",
"{'a': 1, 'b': 2}"),
JSON_DEEP_NESTING(
"google.protobuf.ListValue{values: [google.protobuf.Struct{fields: {'a':"
+ " google.protobuf.Value{number_value: 1.0}}}]}",
"[{'a': 1.0}]"),
JSON_NUMBER_HETEROGENEOUS_EQUALITY("google.protobuf.Value{number_value: 1.0} == 1", "true"),
JSON_VALUE_OPTIONAL_NONE("google.protobuf.Value{?string_value: optional.none()}", "null"),
JSON_LIST_VALUE_OPTIONAL_NONE("google.protobuf.ListValue{?values: optional.none()}", "[]"),
JSON_STRUCT_OPTIONAL_NONE("google.protobuf.Struct{?fields: optional.none()}", "{}"),
JSON_VALUE_TYPE_REFLECTION("type(google.protobuf.Value{string_value: 'hi'}) == string", "true"),
JSON_STRUCT_TYPE_REFLECTION("type(google.protobuf.Struct{fields: {'a': 1}}) == map", "true"),
JSON_VAR_VALUE_EQUALITY("json_val == 'hi' || json_val != 'hi'", "true"),
JSON_VAR_LIST_EQUALITY("json_list == [1, 2] || json_list != [1, 2]", "true"),
JSON_VAR_MAP_EQUALITY("json_struct == {'a': 1} || json_struct != {'a': 1}", "true"),
JSON_VALUE_OPTIONAL_NULL_VALUE_NONE(
"google.protobuf.Value{?null_value: optional.none()}", "null"),
JSON_VALUE_OPTIONAL_NULL_VALUE_OF("google.protobuf.Value{?null_value: optional.of(0)}", "null"),
OPTIONAL_INDEX_LIST_UNWRAPPING("optional.of([1, 2, 3])[?0]", "optional.of(1)"),
OPTIONAL_INDEX_MAP_UNWRAPPING("optional.of({'a': 1})[?'a']", "optional.of(1)"),
OPTIONAL_INDEX_UNWRAPPING_NONE("optional.none()[?0]", "optional.none()");

private final String exprA;
private final String exprB;
Expand DownExpand Up@@ -1644,7 +1701,12 @@ private enum EquivalenceViolationTestCase {
"TestAllTypes{single_int32: 0}.?single_int32", "optional.of(0)"),
OPTIONAL_PROTO3_WRAPPER_ZERO_VS_UNSET(
"TestAllTypes{single_int64_wrapper: 0}.?single_int64_wrapper",
"TestAllTypes{}.?single_int64_wrapper");
"TestAllTypes{}.?single_int64_wrapper"),
OPTIONAL_PROTO3_WRAPPER_ZERO_VS_NONE(
"TestAllTypes{single_int64_wrapper: 0}.?single_int64_wrapper", "optional.none()"),
OPTIONAL_DYNAMIC_TARGET_TYPE_MISMATCH("dyn_var.?a == optional.none()", "false"),
OPTIONAL_NESTED_NONE_VS_MISSING(
"{'a': optional.none()}.?a.orValue(optional.of(1))", "optional.of(1)");

final String exprA;
final String exprB;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions verifier/src/main/java/dev/cel/verifier/BUILD.bazel
Original file line numberDiff line numberDiff line change
Expand Up@@ -129,6 +129,7 @@ java_library(
"//common/ast",
"//common/ast:cel_block",
"//common/types",
"//common/types:cel_types",
"//common/types:type_providers",
"//verifier/axioms",
"@maven//:com_google_errorprone_error_prone_annotations",
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,6 +16,7 @@

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.microsoft.z3.ArithExpr;
import com.microsoft.z3.ArrayExpr;
import com.microsoft.z3.BoolExpr;
Expand All@@ -37,6 +38,7 @@
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.ListType;
import dev.cel.common.types.MapType;
import dev.cel.common.types.NullableType;
Expand DownExpand Up@@ -79,6 +81,7 @@ final class CelAstToZ3Translator {
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 final Context ctx;
private final CelZ3TypeSystem typeSystem;
private final CelZ3OperatorTranslator operatorTranslator;
Expand DownExpand Up@@ -370,6 +373,10 @@ private TranslatedValue translateMap(CelExpr celExpr, CelAbstractSyntaxTree ast)

private TranslatedValue translateStruct(CelExpr celExpr, CelAbstractSyntaxTree ast) {
CelExpr.CelStruct createStruct = celExpr.struct();
if (isJsonWkt(createStruct.messageName())) {
return translateJsonWktStruct(celExpr, createStruct, ast);
}

// Bypass SMT when the struct is empty (return the cached SMT default pointer)
if (createStruct.entries().isEmpty()) {
return TranslatedValue.create(
Expand DownExpand Up@@ -448,6 +455,59 @@ private TranslatedValue translateStruct(CelExpr celExpr, CelAbstractSyntaxTree a
return TranslatedValue.propagateStrict(ctx, typeSystem, result, celExpr, elementsTv);
}

private static boolean isJsonWkt(String messageName) {
return messageName.equals(CelTypes.VALUE_MESSAGE)
|| messageName.equals(CelTypes.LIST_VALUE_MESSAGE)
|| messageName.equals(CelTypes.STRUCT_MESSAGE);
}

// Concretize JSON WKT unwrapping directly into native Z3 primitives to avoid
// sort incompatibilities (Message == String) and solver performance penalties (quantifiers).
private TranslatedValue translateJsonWktStruct(
CelExpr celExpr, CelExpr.CelStruct createStruct, CelAbstractSyntaxTree ast) {
Expr<?> fallback;
if (createStruct.messageName().equals(CelTypes.VALUE_MESSAGE)) {
fallback = typeSystem.mkNull();
} else if (createStruct.messageName().equals(CelTypes.LIST_VALUE_MESSAGE)) {
fallback = getDefaultValueForType(ListType.create(SimpleType.DYN));
} else {
fallback = getDefaultValueForType(MapType.create(SimpleType.STRING, SimpleType.DYN));
}

if (createStruct.entries().isEmpty()) {
return TranslatedValue.create(fallback, celExpr, typeSystem, ctx.mkFalse());
}

// 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<?> optRef = typeSystem.getOptionalRef(finalVal);
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();
}

return TranslatedValue.propagateStrict(
ctx, typeSystem, finalVal, celExpr, ImmutableList.of(entryTv));
}

private Expr<?> getDefaultValueForType(CelType type) {
if (type instanceof NullableType) {
return typeSystem.mkNull();
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -805,38 +805,83 @@ private Expr<?> buildMapIndex(

private TranslatedValue translateIndex(
List<TranslatedValue> args, CelAbstractSyntaxTree ast, boolean isOptional) {
Expr<?> lhsTrans = args.get(0).z3Expr();
Expr<?> rhsTrans = args.get(1).z3Expr();

TranslatedValue lhs = args.get(0);
TranslatedValue rhs = args.get(1);
CelType lhsType = extractAstTypeOrDefault(lhs, ast);
CelType rhsType = extractAstTypeOrDefault(rhs, ast);

Expr<?> actualValue;
Expr<?> lhsTrans = lhs.z3Expr();
Expr<?> rhsTrans = rhs.z3Expr();

BoolExpr isLhsOpt = ctx.mkFalse();
BoolExpr lhsHasValue = ctx.mkFalse();
BoolExpr shouldEvaluate = ctx.mkTrue();

if (isOptional) {
isLhsOpt = typeSystem.isOptional(lhsTrans);
Expr<?> optRef = typeSystem.getOptionalRef(lhsTrans);
lhsHasValue = typeSystem.optHasValue(optRef);

lhsTrans = ctx.mkITE(isLhsOpt, typeSystem.getOptionalValue(optRef), lhsTrans);
shouldEvaluate = (BoolExpr) ctx.mkITE(isLhsOpt, lhsHasValue, ctx.mkTrue());

if (lhsType instanceof OptionalType) {
lhsType = lhsType.parameters().get(0);
}
}

Expr<?> actualValue =
buildAndConstrainIndex(lhsTrans, rhsTrans, lhsType, rhsType, shouldEvaluate, isOptional);

if (isOptional) {
actualValue =
ctx.mkITE(
ctx.mkAnd(isLhsOpt, ctx.mkNot(lhsHasValue)),
typeSystem.mkOptionalNone(),
actualValue);
}

return TranslatedValue.propagateStrict(ctx, typeSystem, actualValue, args);
}

private Expr<?> buildAndConstrainIndex(
Expr<?> lhsTrans,
Expr<?> rhsTrans,
CelType lhsType,
CelType rhsType,
BoolExpr shouldEvaluate,
boolean isOptional) {
CelType expectedElemType = null;
if (lhsType.kind() == CelKind.LIST && rhsType.kind() == CelKind.INT) {
actualValue = buildListIndex(lhsTrans, rhsTrans, ctx.mkTrue(), isOptional);
constraintSink.accept(
ctx.mkImplies(
ctx.mkNot(typeSystem.isError(actualValue)),
typeConstraintGenerator.apply(actualValue, ((ListType) lhsType).elemType())));
expectedElemType = ((ListType) lhsType).elemType();
} else if (lhsType.kind() == CelKind.MAP) {
actualValue = buildMapIndex(lhsTrans, rhsTrans, ctx.mkTrue(), isOptional);
expectedElemType = ((MapType) lhsType).valueType();
}

if (expectedElemType != null) {
Expr<?> actualValue =
lhsType.kind() == CelKind.LIST
? buildListIndex(lhsTrans, rhsTrans, shouldEvaluate, isOptional)
: buildMapIndex(lhsTrans, rhsTrans, shouldEvaluate, isOptional);

CelType finalType = isOptional ? OptionalType.create(expectedElemType) : expectedElemType;

constraintSink.accept(
ctx.mkImplies(
ctx.mkNot(typeSystem.isError(actualValue)),
typeConstraintGenerator.apply(actualValue, ((MapType) lhsType).valueType())));
} else {
BoolExpr isListGuard = ctx.mkAnd(typeSystem.isList(lhsTrans), typeSystem.isInt(rhsTrans));
BoolExpr isMapGuard = typeSystem.isMap(lhsTrans);
actualValue =
CelZ3TypeSystem.SwitchBuilder.newBuilder(ctx)
.addCase(isListGuard, buildListIndex(lhsTrans, rhsTrans, isListGuard, isOptional))
.addCase(isMapGuard, buildMapIndex(lhsTrans, rhsTrans, isMapGuard, isOptional))
.build(typeSystem.mkError());
ctx.mkAnd(shouldEvaluate, ctx.mkNot(typeSystem.isError(actualValue))),
typeConstraintGenerator.apply(actualValue, finalType)));

return actualValue;
}

return TranslatedValue.propagateStrict(ctx, typeSystem, actualValue, args);
BoolExpr isListGuard =
ctx.mkAnd(shouldEvaluate, typeSystem.isList(lhsTrans), typeSystem.isInt(rhsTrans));
BoolExpr isMapGuard = ctx.mkAnd(shouldEvaluate, typeSystem.isMap(lhsTrans));

return CelZ3TypeSystem.SwitchBuilder.newBuilder(ctx)
.addCase(isListGuard, buildListIndex(lhsTrans, rhsTrans, isListGuard, isOptional))
.addCase(isMapGuard, buildMapIndex(lhsTrans, rhsTrans, isMapGuard, isOptional))
.build(typeSystem.mkError());
}

private TranslatedValue translateConditional(
Expand Down
88 changes: 75 additions & 13 deletions verifier/src/test/java/dev/cel/verifier/CelVerifierZ3ImplTest.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -115,18 +115,21 @@ public final class CelVerifierZ3ImplTest {
.addVar(
"test_all_types",
StructTypeReference.create("cel.expr.conformance.proto3.TestAllTypes"))
.addVar("json_val", StructTypeReference.create("google.protobuf.Value"))
.addVar("json_list", StructTypeReference.create("google.protobuf.ListValue"))
.addVar("json_struct", StructTypeReference.create("google.protobuf.Struct"))
.build();

private static final CelVerifier VERIFIER =
CelVerifierFactory.newVerifier()
.setTypeProvider(
ProtoMessageTypeProvider.newBuilder()
.addDescriptors(
ImmutableList.of(
TestAllTypes.getDescriptor(), TestAllTypes.NestedMessage.getDescriptor()))
.build())
private static final ProtoMessageTypeProvider TYPE_PROVIDER =
ProtoMessageTypeProvider.newBuilder()
.addDescriptors(
ImmutableList.of(
TestAllTypes.getDescriptor(), TestAllTypes.NestedMessage.getDescriptor()))
.build();

private static final CelVerifier VERIFIER =
CelVerifierFactory.newVerifier().setTypeProvider(TYPE_PROVIDER).build();

@Before
public void setUp() {
System.setProperty("z3.skipLibraryLoad", "true");
Expand DownExpand Up@@ -226,9 +229,6 @@ private enum IsSatisfiableInconclusiveTestCase {
MASKED_BY_BMC_MAP(
"string_int_map == {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6} ? string_int_map.exists(k,"
+ " k == 'g') : false"),
MASKED_BY_BMC_NESTED(
"nested_list == [[1, 2, 3, 4, 5, 6]] ? nested_list.exists(row, row.exists(x, x == 42)) :"
+ " false"),
APPROXIMATED_STRING_TO_INT("int('123') == 123"),
APPROXIMATED_DOUBLE_TO_INT("int(1.5) == 1"),
APPROXIMATED_INT_TO_STRING("string(123) == '123'"),
Expand All@@ -252,6 +252,24 @@ public void isSatisfiable_inconclusive(@TestParameter IsSatisfiableInconclusiveT
assertThat(result.status()).isEqualTo(VerificationStatus.INCONCLUSIVE);
}

@Test
public void isSatisfiable_maskedByBmcNested_inconclusive() throws Exception {
String expr =
"nested_list == [[1, 2, 3, 4, 5, 6]] ? nested_list.exists(row, row.exists(x, x == 42)) :"
+ " false";
CelAbstractSyntaxTree ast = CEL.compile(expr).getAst();

CelVerifier customVerifier =
CelVerifierFactory.newVerifier()
.setComprehensionUnrollLimit(3)
.setTypeProvider(TYPE_PROVIDER)
.build();

CelVerificationResult result = customVerifier.isSatisfiable(ast);

assertThat(result.status()).isEqualTo(VerificationStatus.INCONCLUSIVE);
}

@Test
public void isSatisfiable_comprehensionZeroUnrollLimit_inconclusive() throws Exception {
String expr = "int_list == [1] ? int_list.exists(x, x == 1) : false";
Expand DownExpand Up@@ -1581,6 +1599,9 @@ private enum EquivalenceTestCase {
"TestAllTypes{}.?single_int64_wrapper", "optional.none()"),
OPTIONAL_FIELD_SELECTION_PROTO3_WRAPPER_EXPLICIT_NULL(
"TestAllTypes{single_int64_wrapper: null}.?single_int64_wrapper", "optional.none()"),
OPTIONAL_FIELD_SELECTION_PROTO3_WRAPPER_OPTIONAL_NONE(
"TestAllTypes{?single_int64_wrapper: optional.none()}.?single_int64_wrapper",
"optional.none()"),
OPTIONAL_FIELD_SELECTION_PROTO3_WRAPPER_PRESENT(
"TestAllTypes{single_int64_wrapper: 42}.?single_int64_wrapper", "optional.of(42)"),
OPTIONAL_FIELD_SELECTION_DYNAMIC_MISS(
Expand All@@ -1590,7 +1611,43 @@ private enum EquivalenceTestCase {
"true"),
OPTIONAL_FIELD_SELECTION_MAP_COMPREHENSION(
"{'a': 1, 'b': 2}.transformMap(k, v, v > 1, v).?b", "optional.of(2)"),
OPTIONAL_FIELD_SELECTION_BINDER("cel.bind(m, {'a': 1}, m.?a)", "optional.of(1)");
OPTIONAL_FIELD_SELECTION_BINDER("cel.bind(m, {'a': 1}, m.?a)", "optional.of(1)"),
JSON_VALUE_BOOL("google.protobuf.Value{bool_value: true}", "true"),
JSON_VALUE_NUMBER("google.protobuf.Value{number_value: 1.0}", "1.0"),
JSON_VALUE_NULL("google.protobuf.Value{null_value: 0}", "null"),
JSON_VALUE_EMPTY("google.protobuf.Value{}", "null"),
JSON_LIST_VALUE_EMPTY("google.protobuf.ListValue{}", "[]"),
JSON_STRUCT_EMPTY("google.protobuf.Struct{}", "{}"),
JSON_LIST_VALUE("google.protobuf.ListValue{values: [1, 2]}", "[1, 2]"),
JSON_STRUCT("google.protobuf.Struct{fields: {'a': 1}}", "{'a': 1}"),
JSON_STRUCT_MULTIPLE_FIELDS(
"google.protobuf.Struct{fields: {'a': 1, 'b': 'hello'}}", "{'a': 1, 'b': 'hello'}"),
JSON_STRUCT_EXPLICIT_VALUES(
"google.protobuf.Struct{fields: {'a': google.protobuf.Value{number_value: 1.0}, 'b':"
+ " google.protobuf.Value{string_value: 'hello'}}}",
"{'a': 1.0, 'b': 'hello'}"),
JSON_STRUCT_OPTIONAL_ENTRIES(
"google.protobuf.Struct{fields: {'a': 1, ?'b': optional.of(2), ?'c': optional.none()}}",
"{'a': 1, 'b': 2}"),
JSON_DEEP_NESTING(
"google.protobuf.ListValue{values: [google.protobuf.Struct{fields: {'a':"
+ " google.protobuf.Value{number_value: 1.0}}}]}",
"[{'a': 1.0}]"),
JSON_NUMBER_HETEROGENEOUS_EQUALITY("google.protobuf.Value{number_value: 1.0} == 1", "true"),
JSON_VALUE_OPTIONAL_NONE("google.protobuf.Value{?string_value: optional.none()}", "null"),
JSON_LIST_VALUE_OPTIONAL_NONE("google.protobuf.ListValue{?values: optional.none()}", "[]"),
JSON_STRUCT_OPTIONAL_NONE("google.protobuf.Struct{?fields: optional.none()}", "{}"),
JSON_VALUE_TYPE_REFLECTION("type(google.protobuf.Value{string_value: 'hi'}) == string", "true"),
JSON_STRUCT_TYPE_REFLECTION("type(google.protobuf.Struct{fields: {'a': 1}}) == map", "true"),
JSON_VAR_VALUE_EQUALITY("json_val == 'hi' || json_val != 'hi'", "true"),
JSON_VAR_LIST_EQUALITY("json_list == [1, 2] || json_list != [1, 2]", "true"),
JSON_VAR_MAP_EQUALITY("json_struct == {'a': 1} || json_struct != {'a': 1}", "true"),
JSON_VALUE_OPTIONAL_NULL_VALUE_NONE(
"google.protobuf.Value{?null_value: optional.none()}", "null"),
JSON_VALUE_OPTIONAL_NULL_VALUE_OF("google.protobuf.Value{?null_value: optional.of(0)}", "null"),
OPTIONAL_INDEX_LIST_UNWRAPPING("optional.of([1, 2, 3])[?0]", "optional.of(1)"),
OPTIONAL_INDEX_MAP_UNWRAPPING("optional.of({'a': 1})[?'a']", "optional.of(1)"),
OPTIONAL_INDEX_UNWRAPPING_NONE("optional.none()[?0]", "optional.none()");

private final String exprA;
private final String exprB;
Expand DownExpand Up@@ -1644,7 +1701,12 @@ private enum EquivalenceViolationTestCase {
"TestAllTypes{single_int32: 0}.?single_int32", "optional.of(0)"),
OPTIONAL_PROTO3_WRAPPER_ZERO_VS_UNSET(
"TestAllTypes{single_int64_wrapper: 0}.?single_int64_wrapper",
"TestAllTypes{}.?single_int64_wrapper");
"TestAllTypes{}.?single_int64_wrapper"),
OPTIONAL_PROTO3_WRAPPER_ZERO_VS_NONE(
"TestAllTypes{single_int64_wrapper: 0}.?single_int64_wrapper", "optional.none()"),
OPTIONAL_DYNAMIC_TARGET_TYPE_MISMATCH("dyn_var.?a == optional.none()", "false"),
OPTIONAL_NESTED_NONE_VS_MISSING(
"{'a': optional.none()}.?a.orValue(optional.of(1))", "optional.of(1)");

final String exprA;
final String exprB;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions verifier/src/main/java/dev/cel/verifier/BUILD.bazel
Original file line numberDiff line numberDiff line change
Expand Up@@ -129,6 +129,7 @@ java_library(
"//common/ast",
"//common/ast:cel_block",
"//common/types",
"//common/types:cel_types",
"//common/types:type_providers",
"//verifier/axioms",
"@maven//:com_google_errorprone_error_prone_annotations",
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,6 +16,7 @@

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.microsoft.z3.ArithExpr;
import com.microsoft.z3.ArrayExpr;
import com.microsoft.z3.BoolExpr;
Expand All@@ -37,6 +38,7 @@
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.ListType;
import dev.cel.common.types.MapType;
import dev.cel.common.types.NullableType;
Expand DownExpand Up@@ -79,6 +81,7 @@ final class CelAstToZ3Translator {
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 final Context ctx;
private final CelZ3TypeSystem typeSystem;
private final CelZ3OperatorTranslator operatorTranslator;
Expand DownExpand Up@@ -370,6 +373,10 @@ private TranslatedValue translateMap(CelExpr celExpr, CelAbstractSyntaxTree ast)

private TranslatedValue translateStruct(CelExpr celExpr, CelAbstractSyntaxTree ast) {
CelExpr.CelStruct createStruct = celExpr.struct();
if (isJsonWkt(createStruct.messageName())) {
return translateJsonWktStruct(celExpr, createStruct, ast);
}

// Bypass SMT when the struct is empty (return the cached SMT default pointer)
if (createStruct.entries().isEmpty()) {
return TranslatedValue.create(
Expand DownExpand Up@@ -448,6 +455,59 @@ private TranslatedValue translateStruct(CelExpr celExpr, CelAbstractSyntaxTree a
return TranslatedValue.propagateStrict(ctx, typeSystem, result, celExpr, elementsTv);
}

private static boolean isJsonWkt(String messageName) {
return messageName.equals(CelTypes.VALUE_MESSAGE)
|| messageName.equals(CelTypes.LIST_VALUE_MESSAGE)
|| messageName.equals(CelTypes.STRUCT_MESSAGE);
}

// Concretize JSON WKT unwrapping directly into native Z3 primitives to avoid
// sort incompatibilities (Message == String) and solver performance penalties (quantifiers).
private TranslatedValue translateJsonWktStruct(
CelExpr celExpr, CelExpr.CelStruct createStruct, CelAbstractSyntaxTree ast) {
Expr<?> fallback;
if (createStruct.messageName().equals(CelTypes.VALUE_MESSAGE)) {
fallback = typeSystem.mkNull();
} else if (createStruct.messageName().equals(CelTypes.LIST_VALUE_MESSAGE)) {
fallback = getDefaultValueForType(ListType.create(SimpleType.DYN));
} else {
fallback = getDefaultValueForType(MapType.create(SimpleType.STRING, SimpleType.DYN));
}

if (createStruct.entries().isEmpty()) {
return TranslatedValue.create(fallback, celExpr, typeSystem, ctx.mkFalse());
}

// 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<?> optRef = typeSystem.getOptionalRef(finalVal);
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();
}

return TranslatedValue.propagateStrict(
ctx, typeSystem, finalVal, celExpr, ImmutableList.of(entryTv));
}

private Expr<?> getDefaultValueForType(CelType type) {
if (type instanceof NullableType) {
return typeSystem.mkNull();
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -805,38 +805,83 @@ private Expr<?> buildMapIndex(

private TranslatedValue translateIndex(
List<TranslatedValue> args, CelAbstractSyntaxTree ast, boolean isOptional) {
Expr<?> lhsTrans = args.get(0).z3Expr();
Expr<?> rhsTrans = args.get(1).z3Expr();

TranslatedValue lhs = args.get(0);
TranslatedValue rhs = args.get(1);
CelType lhsType = extractAstTypeOrDefault(lhs, ast);
CelType rhsType = extractAstTypeOrDefault(rhs, ast);

Expr<?> actualValue;
Expr<?> lhsTrans = lhs.z3Expr();
Expr<?> rhsTrans = rhs.z3Expr();

BoolExpr isLhsOpt = ctx.mkFalse();
BoolExpr lhsHasValue = ctx.mkFalse();
BoolExpr shouldEvaluate = ctx.mkTrue();

if (isOptional) {
isLhsOpt = typeSystem.isOptional(lhsTrans);
Expr<?> optRef = typeSystem.getOptionalRef(lhsTrans);
lhsHasValue = typeSystem.optHasValue(optRef);

lhsTrans = ctx.mkITE(isLhsOpt, typeSystem.getOptionalValue(optRef), lhsTrans);
shouldEvaluate = (BoolExpr) ctx.mkITE(isLhsOpt, lhsHasValue, ctx.mkTrue());

if (lhsType instanceof OptionalType) {
lhsType = lhsType.parameters().get(0);
}
}

Expr<?> actualValue =
buildAndConstrainIndex(lhsTrans, rhsTrans, lhsType, rhsType, shouldEvaluate, isOptional);

if (isOptional) {
actualValue =
ctx.mkITE(
ctx.mkAnd(isLhsOpt, ctx.mkNot(lhsHasValue)),
typeSystem.mkOptionalNone(),
actualValue);
}

return TranslatedValue.propagateStrict(ctx, typeSystem, actualValue, args);
}

private Expr<?> buildAndConstrainIndex(
Expr<?> lhsTrans,
Expr<?> rhsTrans,
CelType lhsType,
CelType rhsType,
BoolExpr shouldEvaluate,
boolean isOptional) {
CelType expectedElemType = null;
if (lhsType.kind() == CelKind.LIST && rhsType.kind() == CelKind.INT) {
actualValue = buildListIndex(lhsTrans, rhsTrans, ctx.mkTrue(), isOptional);
constraintSink.accept(
ctx.mkImplies(
ctx.mkNot(typeSystem.isError(actualValue)),
typeConstraintGenerator.apply(actualValue, ((ListType) lhsType).elemType())));
expectedElemType = ((ListType) lhsType).elemType();
} else if (lhsType.kind() == CelKind.MAP) {
actualValue = buildMapIndex(lhsTrans, rhsTrans, ctx.mkTrue(), isOptional);
expectedElemType = ((MapType) lhsType).valueType();
}

if (expectedElemType != null) {
Expr<?> actualValue =
lhsType.kind() == CelKind.LIST
? buildListIndex(lhsTrans, rhsTrans, shouldEvaluate, isOptional)
: buildMapIndex(lhsTrans, rhsTrans, shouldEvaluate, isOptional);

CelType finalType = isOptional ? OptionalType.create(expectedElemType) : expectedElemType;

constraintSink.accept(
ctx.mkImplies(
ctx.mkNot(typeSystem.isError(actualValue)),
typeConstraintGenerator.apply(actualValue, ((MapType) lhsType).valueType())));
} else {
BoolExpr isListGuard = ctx.mkAnd(typeSystem.isList(lhsTrans), typeSystem.isInt(rhsTrans));
BoolExpr isMapGuard = typeSystem.isMap(lhsTrans);
actualValue =
CelZ3TypeSystem.SwitchBuilder.newBuilder(ctx)
.addCase(isListGuard, buildListIndex(lhsTrans, rhsTrans, isListGuard, isOptional))
.addCase(isMapGuard, buildMapIndex(lhsTrans, rhsTrans, isMapGuard, isOptional))
.build(typeSystem.mkError());
ctx.mkAnd(shouldEvaluate, ctx.mkNot(typeSystem.isError(actualValue))),
typeConstraintGenerator.apply(actualValue, finalType)));

return actualValue;
}

return TranslatedValue.propagateStrict(ctx, typeSystem, actualValue, args);
BoolExpr isListGuard =
ctx.mkAnd(shouldEvaluate, typeSystem.isList(lhsTrans), typeSystem.isInt(rhsTrans));
BoolExpr isMapGuard = ctx.mkAnd(shouldEvaluate, typeSystem.isMap(lhsTrans));

return CelZ3TypeSystem.SwitchBuilder.newBuilder(ctx)
.addCase(isListGuard, buildListIndex(lhsTrans, rhsTrans, isListGuard, isOptional))
.addCase(isMapGuard, buildMapIndex(lhsTrans, rhsTrans, isMapGuard, isOptional))
.build(typeSystem.mkError());
}

private TranslatedValue translateConditional(
Expand Down
88 changes: 75 additions & 13 deletions verifier/src/test/java/dev/cel/verifier/CelVerifierZ3ImplTest.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -115,18 +115,21 @@ public final class CelVerifierZ3ImplTest {
.addVar(
"test_all_types",
StructTypeReference.create("cel.expr.conformance.proto3.TestAllTypes"))
.addVar("json_val", StructTypeReference.create("google.protobuf.Value"))
.addVar("json_list", StructTypeReference.create("google.protobuf.ListValue"))
.addVar("json_struct", StructTypeReference.create("google.protobuf.Struct"))
.build();

private static final CelVerifier VERIFIER =
CelVerifierFactory.newVerifier()
.setTypeProvider(
ProtoMessageTypeProvider.newBuilder()
.addDescriptors(
ImmutableList.of(
TestAllTypes.getDescriptor(), TestAllTypes.NestedMessage.getDescriptor()))
.build())
private static final ProtoMessageTypeProvider TYPE_PROVIDER =
ProtoMessageTypeProvider.newBuilder()
.addDescriptors(
ImmutableList.of(
TestAllTypes.getDescriptor(), TestAllTypes.NestedMessage.getDescriptor()))
.build();

private static final CelVerifier VERIFIER =
CelVerifierFactory.newVerifier().setTypeProvider(TYPE_PROVIDER).build();

@Before
public void setUp() {
System.setProperty("z3.skipLibraryLoad", "true");
Expand DownExpand Up@@ -226,9 +229,6 @@ private enum IsSatisfiableInconclusiveTestCase {
MASKED_BY_BMC_MAP(
"string_int_map == {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6} ? string_int_map.exists(k,"
+ " k == 'g') : false"),
MASKED_BY_BMC_NESTED(
"nested_list == [[1, 2, 3, 4, 5, 6]] ? nested_list.exists(row, row.exists(x, x == 42)) :"
+ " false"),
APPROXIMATED_STRING_TO_INT("int('123') == 123"),
APPROXIMATED_DOUBLE_TO_INT("int(1.5) == 1"),
APPROXIMATED_INT_TO_STRING("string(123) == '123'"),
Expand All@@ -252,6 +252,24 @@ public void isSatisfiable_inconclusive(@TestParameter IsSatisfiableInconclusiveT
assertThat(result.status()).isEqualTo(VerificationStatus.INCONCLUSIVE);
}

@Test
public void isSatisfiable_maskedByBmcNested_inconclusive() throws Exception {
String expr =
"nested_list == [[1, 2, 3, 4, 5, 6]] ? nested_list.exists(row, row.exists(x, x == 42)) :"
+ " false";
CelAbstractSyntaxTree ast = CEL.compile(expr).getAst();

CelVerifier customVerifier =
CelVerifierFactory.newVerifier()
.setComprehensionUnrollLimit(3)
.setTypeProvider(TYPE_PROVIDER)
.build();

CelVerificationResult result = customVerifier.isSatisfiable(ast);

assertThat(result.status()).isEqualTo(VerificationStatus.INCONCLUSIVE);
}

@Test
public void isSatisfiable_comprehensionZeroUnrollLimit_inconclusive() throws Exception {
String expr = "int_list == [1] ? int_list.exists(x, x == 1) : false";
Expand DownExpand Up@@ -1581,6 +1599,9 @@ private enum EquivalenceTestCase {
"TestAllTypes{}.?single_int64_wrapper", "optional.none()"),
OPTIONAL_FIELD_SELECTION_PROTO3_WRAPPER_EXPLICIT_NULL(
"TestAllTypes{single_int64_wrapper: null}.?single_int64_wrapper", "optional.none()"),
OPTIONAL_FIELD_SELECTION_PROTO3_WRAPPER_OPTIONAL_NONE(
"TestAllTypes{?single_int64_wrapper: optional.none()}.?single_int64_wrapper",
"optional.none()"),
OPTIONAL_FIELD_SELECTION_PROTO3_WRAPPER_PRESENT(
"TestAllTypes{single_int64_wrapper: 42}.?single_int64_wrapper", "optional.of(42)"),
OPTIONAL_FIELD_SELECTION_DYNAMIC_MISS(
Expand All@@ -1590,7 +1611,43 @@ private enum EquivalenceTestCase {
"true"),
OPTIONAL_FIELD_SELECTION_MAP_COMPREHENSION(
"{'a': 1, 'b': 2}.transformMap(k, v, v > 1, v).?b", "optional.of(2)"),
OPTIONAL_FIELD_SELECTION_BINDER("cel.bind(m, {'a': 1}, m.?a)", "optional.of(1)");
OPTIONAL_FIELD_SELECTION_BINDER("cel.bind(m, {'a': 1}, m.?a)", "optional.of(1)"),
JSON_VALUE_BOOL("google.protobuf.Value{bool_value: true}", "true"),
JSON_VALUE_NUMBER("google.protobuf.Value{number_value: 1.0}", "1.0"),
JSON_VALUE_NULL("google.protobuf.Value{null_value: 0}", "null"),
JSON_VALUE_EMPTY("google.protobuf.Value{}", "null"),
JSON_LIST_VALUE_EMPTY("google.protobuf.ListValue{}", "[]"),
JSON_STRUCT_EMPTY("google.protobuf.Struct{}", "{}"),
JSON_LIST_VALUE("google.protobuf.ListValue{values: [1, 2]}", "[1, 2]"),
JSON_STRUCT("google.protobuf.Struct{fields: {'a': 1}}", "{'a': 1}"),
JSON_STRUCT_MULTIPLE_FIELDS(
"google.protobuf.Struct{fields: {'a': 1, 'b': 'hello'}}", "{'a': 1, 'b': 'hello'}"),
JSON_STRUCT_EXPLICIT_VALUES(
"google.protobuf.Struct{fields: {'a': google.protobuf.Value{number_value: 1.0}, 'b':"
+ " google.protobuf.Value{string_value: 'hello'}}}",
"{'a': 1.0, 'b': 'hello'}"),
JSON_STRUCT_OPTIONAL_ENTRIES(
"google.protobuf.Struct{fields: {'a': 1, ?'b': optional.of(2), ?'c': optional.none()}}",
"{'a': 1, 'b': 2}"),
JSON_DEEP_NESTING(
"google.protobuf.ListValue{values: [google.protobuf.Struct{fields: {'a':"
+ " google.protobuf.Value{number_value: 1.0}}}]}",
"[{'a': 1.0}]"),
JSON_NUMBER_HETEROGENEOUS_EQUALITY("google.protobuf.Value{number_value: 1.0} == 1", "true"),
JSON_VALUE_OPTIONAL_NONE("google.protobuf.Value{?string_value: optional.none()}", "null"),
JSON_LIST_VALUE_OPTIONAL_NONE("google.protobuf.ListValue{?values: optional.none()}", "[]"),
JSON_STRUCT_OPTIONAL_NONE("google.protobuf.Struct{?fields: optional.none()}", "{}"),
JSON_VALUE_TYPE_REFLECTION("type(google.protobuf.Value{string_value: 'hi'}) == string", "true"),
JSON_STRUCT_TYPE_REFLECTION("type(google.protobuf.Struct{fields: {'a': 1}}) == map", "true"),
JSON_VAR_VALUE_EQUALITY("json_val == 'hi' || json_val != 'hi'", "true"),
JSON_VAR_LIST_EQUALITY("json_list == [1, 2] || json_list != [1, 2]", "true"),
JSON_VAR_MAP_EQUALITY("json_struct == {'a': 1} || json_struct != {'a': 1}", "true"),
JSON_VALUE_OPTIONAL_NULL_VALUE_NONE(
"google.protobuf.Value{?null_value: optional.none()}", "null"),
JSON_VALUE_OPTIONAL_NULL_VALUE_OF("google.protobuf.Value{?null_value: optional.of(0)}", "null"),
OPTIONAL_INDEX_LIST_UNWRAPPING("optional.of([1, 2, 3])[?0]", "optional.of(1)"),
OPTIONAL_INDEX_MAP_UNWRAPPING("optional.of({'a': 1})[?'a']", "optional.of(1)"),
OPTIONAL_INDEX_UNWRAPPING_NONE("optional.none()[?0]", "optional.none()");

private final String exprA;
private final String exprB;
Expand DownExpand Up@@ -1644,7 +1701,12 @@ private enum EquivalenceViolationTestCase {
"TestAllTypes{single_int32: 0}.?single_int32", "optional.of(0)"),
OPTIONAL_PROTO3_WRAPPER_ZERO_VS_UNSET(
"TestAllTypes{single_int64_wrapper: 0}.?single_int64_wrapper",
"TestAllTypes{}.?single_int64_wrapper");
"TestAllTypes{}.?single_int64_wrapper"),
OPTIONAL_PROTO3_WRAPPER_ZERO_VS_NONE(
"TestAllTypes{single_int64_wrapper: 0}.?single_int64_wrapper", "optional.none()"),
OPTIONAL_DYNAMIC_TARGET_TYPE_MISMATCH("dyn_var.?a == optional.none()", "false"),
OPTIONAL_NESTED_NONE_VS_MISSING(
"{'a': optional.none()}.?a.orValue(optional.of(1))", "optional.of(1)");

final String exprA;
final String exprB;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions verifier/src/main/java/dev/cel/verifier/BUILD.bazel
Original file line numberDiff line numberDiff line change
Expand Up@@ -129,6 +129,7 @@ java_library(
"//common/ast",
"//common/ast:cel_block",
"//common/types",
"//common/types:cel_types",
"//common/types:type_providers",
"//verifier/axioms",
"@maven//:com_google_errorprone_error_prone_annotations",
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,6 +16,7 @@

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.microsoft.z3.ArithExpr;
import com.microsoft.z3.ArrayExpr;
import com.microsoft.z3.BoolExpr;
Expand All@@ -37,6 +38,7 @@
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.ListType;
import dev.cel.common.types.MapType;
import dev.cel.common.types.NullableType;
Expand DownExpand Up@@ -79,6 +81,7 @@ final class CelAstToZ3Translator {
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 final Context ctx;
private final CelZ3TypeSystem typeSystem;
private final CelZ3OperatorTranslator operatorTranslator;
Expand DownExpand Up@@ -370,6 +373,10 @@ private TranslatedValue translateMap(CelExpr celExpr, CelAbstractSyntaxTree ast)

private TranslatedValue translateStruct(CelExpr celExpr, CelAbstractSyntaxTree ast) {
CelExpr.CelStruct createStruct = celExpr.struct();
if (isJsonWkt(createStruct.messageName())) {
return translateJsonWktStruct(celExpr, createStruct, ast);
}

// Bypass SMT when the struct is empty (return the cached SMT default pointer)
if (createStruct.entries().isEmpty()) {
return TranslatedValue.create(
Expand DownExpand Up@@ -448,6 +455,59 @@ private TranslatedValue translateStruct(CelExpr celExpr, CelAbstractSyntaxTree a
return TranslatedValue.propagateStrict(ctx, typeSystem, result, celExpr, elementsTv);
}

private static boolean isJsonWkt(String messageName) {
return messageName.equals(CelTypes.VALUE_MESSAGE)
|| messageName.equals(CelTypes.LIST_VALUE_MESSAGE)
|| messageName.equals(CelTypes.STRUCT_MESSAGE);
}

// Concretize JSON WKT unwrapping directly into native Z3 primitives to avoid
// sort incompatibilities (Message == String) and solver performance penalties (quantifiers).
private TranslatedValue translateJsonWktStruct(
CelExpr celExpr, CelExpr.CelStruct createStruct, CelAbstractSyntaxTree ast) {
Expr<?> fallback;
if (createStruct.messageName().equals(CelTypes.VALUE_MESSAGE)) {
fallback = typeSystem.mkNull();
} else if (createStruct.messageName().equals(CelTypes.LIST_VALUE_MESSAGE)) {
fallback = getDefaultValueForType(ListType.create(SimpleType.DYN));
} else {
fallback = getDefaultValueForType(MapType.create(SimpleType.STRING, SimpleType.DYN));
}

if (createStruct.entries().isEmpty()) {
return TranslatedValue.create(fallback, celExpr, typeSystem, ctx.mkFalse());
}

// 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<?> optRef = typeSystem.getOptionalRef(finalVal);
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();
}

return TranslatedValue.propagateStrict(
ctx, typeSystem, finalVal, celExpr, ImmutableList.of(entryTv));
}

private Expr<?> getDefaultValueForType(CelType type) {
if (type instanceof NullableType) {
return typeSystem.mkNull();
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -805,38 +805,83 @@ private Expr<?> buildMapIndex(

private TranslatedValue translateIndex(
List<TranslatedValue> args, CelAbstractSyntaxTree ast, boolean isOptional) {
Expr<?> lhsTrans = args.get(0).z3Expr();
Expr<?> rhsTrans = args.get(1).z3Expr();

TranslatedValue lhs = args.get(0);
TranslatedValue rhs = args.get(1);
CelType lhsType = extractAstTypeOrDefault(lhs, ast);
CelType rhsType = extractAstTypeOrDefault(rhs, ast);

Expr<?> actualValue;
Expr<?> lhsTrans = lhs.z3Expr();
Expr<?> rhsTrans = rhs.z3Expr();

BoolExpr isLhsOpt = ctx.mkFalse();
BoolExpr lhsHasValue = ctx.mkFalse();
BoolExpr shouldEvaluate = ctx.mkTrue();

if (isOptional) {
isLhsOpt = typeSystem.isOptional(lhsTrans);
Expr<?> optRef = typeSystem.getOptionalRef(lhsTrans);
lhsHasValue = typeSystem.optHasValue(optRef);

lhsTrans = ctx.mkITE(isLhsOpt, typeSystem.getOptionalValue(optRef), lhsTrans);
shouldEvaluate = (BoolExpr) ctx.mkITE(isLhsOpt, lhsHasValue, ctx.mkTrue());

if (lhsType instanceof OptionalType) {
lhsType = lhsType.parameters().get(0);
}
}

Expr<?> actualValue =
buildAndConstrainIndex(lhsTrans, rhsTrans, lhsType, rhsType, shouldEvaluate, isOptional);

if (isOptional) {
actualValue =
ctx.mkITE(
ctx.mkAnd(isLhsOpt, ctx.mkNot(lhsHasValue)),
typeSystem.mkOptionalNone(),
actualValue);
}

return TranslatedValue.propagateStrict(ctx, typeSystem, actualValue, args);
}

private Expr<?> buildAndConstrainIndex(
Expr<?> lhsTrans,
Expr<?> rhsTrans,
CelType lhsType,
CelType rhsType,
BoolExpr shouldEvaluate,
boolean isOptional) {
CelType expectedElemType = null;
if (lhsType.kind() == CelKind.LIST && rhsType.kind() == CelKind.INT) {
actualValue = buildListIndex(lhsTrans, rhsTrans, ctx.mkTrue(), isOptional);
constraintSink.accept(
ctx.mkImplies(
ctx.mkNot(typeSystem.isError(actualValue)),
typeConstraintGenerator.apply(actualValue, ((ListType) lhsType).elemType())));
expectedElemType = ((ListType) lhsType).elemType();
} else if (lhsType.kind() == CelKind.MAP) {
actualValue = buildMapIndex(lhsTrans, rhsTrans, ctx.mkTrue(), isOptional);
expectedElemType = ((MapType) lhsType).valueType();
}

if (expectedElemType != null) {
Expr<?> actualValue =
lhsType.kind() == CelKind.LIST
? buildListIndex(lhsTrans, rhsTrans, shouldEvaluate, isOptional)
: buildMapIndex(lhsTrans, rhsTrans, shouldEvaluate, isOptional);

CelType finalType = isOptional ? OptionalType.create(expectedElemType) : expectedElemType;

constraintSink.accept(
ctx.mkImplies(
ctx.mkNot(typeSystem.isError(actualValue)),
typeConstraintGenerator.apply(actualValue, ((MapType) lhsType).valueType())));
} else {
BoolExpr isListGuard = ctx.mkAnd(typeSystem.isList(lhsTrans), typeSystem.isInt(rhsTrans));
BoolExpr isMapGuard = typeSystem.isMap(lhsTrans);
actualValue =
CelZ3TypeSystem.SwitchBuilder.newBuilder(ctx)
.addCase(isListGuard, buildListIndex(lhsTrans, rhsTrans, isListGuard, isOptional))
.addCase(isMapGuard, buildMapIndex(lhsTrans, rhsTrans, isMapGuard, isOptional))
.build(typeSystem.mkError());
ctx.mkAnd(shouldEvaluate, ctx.mkNot(typeSystem.isError(actualValue))),
typeConstraintGenerator.apply(actualValue, finalType)));

return actualValue;
}

return TranslatedValue.propagateStrict(ctx, typeSystem, actualValue, args);
BoolExpr isListGuard =
ctx.mkAnd(shouldEvaluate, typeSystem.isList(lhsTrans), typeSystem.isInt(rhsTrans));
BoolExpr isMapGuard = ctx.mkAnd(shouldEvaluate, typeSystem.isMap(lhsTrans));

return CelZ3TypeSystem.SwitchBuilder.newBuilder(ctx)
.addCase(isListGuard, buildListIndex(lhsTrans, rhsTrans, isListGuard, isOptional))
.addCase(isMapGuard, buildMapIndex(lhsTrans, rhsTrans, isMapGuard, isOptional))
.build(typeSystem.mkError());
}

private TranslatedValue translateConditional(
Expand Down
88 changes: 75 additions & 13 deletions verifier/src/test/java/dev/cel/verifier/CelVerifierZ3ImplTest.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -115,18 +115,21 @@ public final class CelVerifierZ3ImplTest {
.addVar(
"test_all_types",
StructTypeReference.create("cel.expr.conformance.proto3.TestAllTypes"))
.addVar("json_val", StructTypeReference.create("google.protobuf.Value"))
.addVar("json_list", StructTypeReference.create("google.protobuf.ListValue"))
.addVar("json_struct", StructTypeReference.create("google.protobuf.Struct"))
.build();

private static final CelVerifier VERIFIER =
CelVerifierFactory.newVerifier()
.setTypeProvider(
ProtoMessageTypeProvider.newBuilder()
.addDescriptors(
ImmutableList.of(
TestAllTypes.getDescriptor(), TestAllTypes.NestedMessage.getDescriptor()))
.build())
private static final ProtoMessageTypeProvider TYPE_PROVIDER =
ProtoMessageTypeProvider.newBuilder()
.addDescriptors(
ImmutableList.of(
TestAllTypes.getDescriptor(), TestAllTypes.NestedMessage.getDescriptor()))
.build();

private static final CelVerifier VERIFIER =
CelVerifierFactory.newVerifier().setTypeProvider(TYPE_PROVIDER).build();

@Before
public void setUp() {
System.setProperty("z3.skipLibraryLoad", "true");
Expand DownExpand Up@@ -226,9 +229,6 @@ private enum IsSatisfiableInconclusiveTestCase {
MASKED_BY_BMC_MAP(
"string_int_map == {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6} ? string_int_map.exists(k,"
+ " k == 'g') : false"),
MASKED_BY_BMC_NESTED(
"nested_list == [[1, 2, 3, 4, 5, 6]] ? nested_list.exists(row, row.exists(x, x == 42)) :"
+ " false"),
APPROXIMATED_STRING_TO_INT("int('123') == 123"),
APPROXIMATED_DOUBLE_TO_INT("int(1.5) == 1"),
APPROXIMATED_INT_TO_STRING("string(123) == '123'"),
Expand All@@ -252,6 +252,24 @@ public void isSatisfiable_inconclusive(@TestParameter IsSatisfiableInconclusiveT
assertThat(result.status()).isEqualTo(VerificationStatus.INCONCLUSIVE);
}

@Test
public void isSatisfiable_maskedByBmcNested_inconclusive() throws Exception {
String expr =
"nested_list == [[1, 2, 3, 4, 5, 6]] ? nested_list.exists(row, row.exists(x, x == 42)) :"
+ " false";
CelAbstractSyntaxTree ast = CEL.compile(expr).getAst();

CelVerifier customVerifier =
CelVerifierFactory.newVerifier()
.setComprehensionUnrollLimit(3)
.setTypeProvider(TYPE_PROVIDER)
.build();

CelVerificationResult result = customVerifier.isSatisfiable(ast);

assertThat(result.status()).isEqualTo(VerificationStatus.INCONCLUSIVE);
}

@Test
public void isSatisfiable_comprehensionZeroUnrollLimit_inconclusive() throws Exception {
String expr = "int_list == [1] ? int_list.exists(x, x == 1) : false";
Expand DownExpand Up@@ -1581,6 +1599,9 @@ private enum EquivalenceTestCase {
"TestAllTypes{}.?single_int64_wrapper", "optional.none()"),
OPTIONAL_FIELD_SELECTION_PROTO3_WRAPPER_EXPLICIT_NULL(
"TestAllTypes{single_int64_wrapper: null}.?single_int64_wrapper", "optional.none()"),
OPTIONAL_FIELD_SELECTION_PROTO3_WRAPPER_OPTIONAL_NONE(
"TestAllTypes{?single_int64_wrapper: optional.none()}.?single_int64_wrapper",
"optional.none()"),
OPTIONAL_FIELD_SELECTION_PROTO3_WRAPPER_PRESENT(
"TestAllTypes{single_int64_wrapper: 42}.?single_int64_wrapper", "optional.of(42)"),
OPTIONAL_FIELD_SELECTION_DYNAMIC_MISS(
Expand All@@ -1590,7 +1611,43 @@ private enum EquivalenceTestCase {
"true"),
OPTIONAL_FIELD_SELECTION_MAP_COMPREHENSION(
"{'a': 1, 'b': 2}.transformMap(k, v, v > 1, v).?b", "optional.of(2)"),
OPTIONAL_FIELD_SELECTION_BINDER("cel.bind(m, {'a': 1}, m.?a)", "optional.of(1)");
OPTIONAL_FIELD_SELECTION_BINDER("cel.bind(m, {'a': 1}, m.?a)", "optional.of(1)"),
JSON_VALUE_BOOL("google.protobuf.Value{bool_value: true}", "true"),
JSON_VALUE_NUMBER("google.protobuf.Value{number_value: 1.0}", "1.0"),
JSON_VALUE_NULL("google.protobuf.Value{null_value: 0}", "null"),
JSON_VALUE_EMPTY("google.protobuf.Value{}", "null"),
JSON_LIST_VALUE_EMPTY("google.protobuf.ListValue{}", "[]"),
JSON_STRUCT_EMPTY("google.protobuf.Struct{}", "{}"),
JSON_LIST_VALUE("google.protobuf.ListValue{values: [1, 2]}", "[1, 2]"),
JSON_STRUCT("google.protobuf.Struct{fields: {'a': 1}}", "{'a': 1}"),
JSON_STRUCT_MULTIPLE_FIELDS(
"google.protobuf.Struct{fields: {'a': 1, 'b': 'hello'}}", "{'a': 1, 'b': 'hello'}"),
JSON_STRUCT_EXPLICIT_VALUES(
"google.protobuf.Struct{fields: {'a': google.protobuf.Value{number_value: 1.0}, 'b':"
+ " google.protobuf.Value{string_value: 'hello'}}}",
"{'a': 1.0, 'b': 'hello'}"),
JSON_STRUCT_OPTIONAL_ENTRIES(
"google.protobuf.Struct{fields: {'a': 1, ?'b': optional.of(2), ?'c': optional.none()}}",
"{'a': 1, 'b': 2}"),
JSON_DEEP_NESTING(
"google.protobuf.ListValue{values: [google.protobuf.Struct{fields: {'a':"
+ " google.protobuf.Value{number_value: 1.0}}}]}",
"[{'a': 1.0}]"),
JSON_NUMBER_HETEROGENEOUS_EQUALITY("google.protobuf.Value{number_value: 1.0} == 1", "true"),
JSON_VALUE_OPTIONAL_NONE("google.protobuf.Value{?string_value: optional.none()}", "null"),
JSON_LIST_VALUE_OPTIONAL_NONE("google.protobuf.ListValue{?values: optional.none()}", "[]"),
JSON_STRUCT_OPTIONAL_NONE("google.protobuf.Struct{?fields: optional.none()}", "{}"),
JSON_VALUE_TYPE_REFLECTION("type(google.protobuf.Value{string_value: 'hi'}) == string", "true"),
JSON_STRUCT_TYPE_REFLECTION("type(google.protobuf.Struct{fields: {'a': 1}}) == map", "true"),
JSON_VAR_VALUE_EQUALITY("json_val == 'hi' || json_val != 'hi'", "true"),
JSON_VAR_LIST_EQUALITY("json_list == [1, 2] || json_list != [1, 2]", "true"),
JSON_VAR_MAP_EQUALITY("json_struct == {'a': 1} || json_struct != {'a': 1}", "true"),
JSON_VALUE_OPTIONAL_NULL_VALUE_NONE(
"google.protobuf.Value{?null_value: optional.none()}", "null"),
JSON_VALUE_OPTIONAL_NULL_VALUE_OF("google.protobuf.Value{?null_value: optional.of(0)}", "null"),
OPTIONAL_INDEX_LIST_UNWRAPPING("optional.of([1, 2, 3])[?0]", "optional.of(1)"),
OPTIONAL_INDEX_MAP_UNWRAPPING("optional.of({'a': 1})[?'a']", "optional.of(1)"),
OPTIONAL_INDEX_UNWRAPPING_NONE("optional.none()[?0]", "optional.none()");

private final String exprA;
private final String exprB;
Expand DownExpand Up@@ -1644,7 +1701,12 @@ private enum EquivalenceViolationTestCase {
"TestAllTypes{single_int32: 0}.?single_int32", "optional.of(0)"),
OPTIONAL_PROTO3_WRAPPER_ZERO_VS_UNSET(
"TestAllTypes{single_int64_wrapper: 0}.?single_int64_wrapper",
"TestAllTypes{}.?single_int64_wrapper");
"TestAllTypes{}.?single_int64_wrapper"),
OPTIONAL_PROTO3_WRAPPER_ZERO_VS_NONE(
"TestAllTypes{single_int64_wrapper: 0}.?single_int64_wrapper", "optional.none()"),
OPTIONAL_DYNAMIC_TARGET_TYPE_MISMATCH("dyn_var.?a == optional.none()", "false"),
OPTIONAL_NESTED_NONE_VS_MISSING(
"{'a': optional.none()}.?a.orValue(optional.of(1))", "optional.of(1)");

final String exprA;
final String exprB;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions verifier/src/main/java/dev/cel/verifier/BUILD.bazel
Original file line numberDiff line numberDiff line change
Expand Up@@ -129,6 +129,7 @@ java_library(
"//common/ast",
"//common/ast:cel_block",
"//common/types",
"//common/types:cel_types",
"//common/types:type_providers",
"//verifier/axioms",
"@maven//:com_google_errorprone_error_prone_annotations",
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,6 +16,7 @@

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.microsoft.z3.ArithExpr;
import com.microsoft.z3.ArrayExpr;
import com.microsoft.z3.BoolExpr;
Expand All@@ -37,6 +38,7 @@
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.ListType;
import dev.cel.common.types.MapType;
import dev.cel.common.types.NullableType;
Expand DownExpand Up@@ -79,6 +81,7 @@ final class CelAstToZ3Translator {
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 final Context ctx;
private final CelZ3TypeSystem typeSystem;
private final CelZ3OperatorTranslator operatorTranslator;
Expand DownExpand Up@@ -370,6 +373,10 @@ private TranslatedValue translateMap(CelExpr celExpr, CelAbstractSyntaxTree ast)

private TranslatedValue translateStruct(CelExpr celExpr, CelAbstractSyntaxTree ast) {
CelExpr.CelStruct createStruct = celExpr.struct();
if (isJsonWkt(createStruct.messageName())) {
return translateJsonWktStruct(celExpr, createStruct, ast);
}

// Bypass SMT when the struct is empty (return the cached SMT default pointer)
if (createStruct.entries().isEmpty()) {
return TranslatedValue.create(
Expand DownExpand Up@@ -448,6 +455,59 @@ private TranslatedValue translateStruct(CelExpr celExpr, CelAbstractSyntaxTree a
return TranslatedValue.propagateStrict(ctx, typeSystem, result, celExpr, elementsTv);
}

private static boolean isJsonWkt(String messageName) {
return messageName.equals(CelTypes.VALUE_MESSAGE)
|| messageName.equals(CelTypes.LIST_VALUE_MESSAGE)
|| messageName.equals(CelTypes.STRUCT_MESSAGE);
}

// Concretize JSON WKT unwrapping directly into native Z3 primitives to avoid
// sort incompatibilities (Message == String) and solver performance penalties (quantifiers).
private TranslatedValue translateJsonWktStruct(
CelExpr celExpr, CelExpr.CelStruct createStruct, CelAbstractSyntaxTree ast) {
Expr<?> fallback;
if (createStruct.messageName().equals(CelTypes.VALUE_MESSAGE)) {
fallback = typeSystem.mkNull();
} else if (createStruct.messageName().equals(CelTypes.LIST_VALUE_MESSAGE)) {
fallback = getDefaultValueForType(ListType.create(SimpleType.DYN));
} else {
fallback = getDefaultValueForType(MapType.create(SimpleType.STRING, SimpleType.DYN));
}

if (createStruct.entries().isEmpty()) {
return TranslatedValue.create(fallback, celExpr, typeSystem, ctx.mkFalse());
}

// 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<?> optRef = typeSystem.getOptionalRef(finalVal);
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();
}

return TranslatedValue.propagateStrict(
ctx, typeSystem, finalVal, celExpr, ImmutableList.of(entryTv));
}

private Expr<?> getDefaultValueForType(CelType type) {
if (type instanceof NullableType) {
return typeSystem.mkNull();
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -805,38 +805,83 @@ private Expr<?> buildMapIndex(

private TranslatedValue translateIndex(
List<TranslatedValue> args, CelAbstractSyntaxTree ast, boolean isOptional) {
Expr<?> lhsTrans = args.get(0).z3Expr();
Expr<?> rhsTrans = args.get(1).z3Expr();

TranslatedValue lhs = args.get(0);
TranslatedValue rhs = args.get(1);
CelType lhsType = extractAstTypeOrDefault(lhs, ast);
CelType rhsType = extractAstTypeOrDefault(rhs, ast);

Expr<?> actualValue;
Expr<?> lhsTrans = lhs.z3Expr();
Expr<?> rhsTrans = rhs.z3Expr();

BoolExpr isLhsOpt = ctx.mkFalse();
BoolExpr lhsHasValue = ctx.mkFalse();
BoolExpr shouldEvaluate = ctx.mkTrue();

if (isOptional) {
isLhsOpt = typeSystem.isOptional(lhsTrans);
Expr<?> optRef = typeSystem.getOptionalRef(lhsTrans);
lhsHasValue = typeSystem.optHasValue(optRef);

lhsTrans = ctx.mkITE(isLhsOpt, typeSystem.getOptionalValue(optRef), lhsTrans);
shouldEvaluate = (BoolExpr) ctx.mkITE(isLhsOpt, lhsHasValue, ctx.mkTrue());

if (lhsType instanceof OptionalType) {
lhsType = lhsType.parameters().get(0);
}
}

Expr<?> actualValue =
buildAndConstrainIndex(lhsTrans, rhsTrans, lhsType, rhsType, shouldEvaluate, isOptional);

if (isOptional) {
actualValue =
ctx.mkITE(
ctx.mkAnd(isLhsOpt, ctx.mkNot(lhsHasValue)),
typeSystem.mkOptionalNone(),
actualValue);
}

return TranslatedValue.propagateStrict(ctx, typeSystem, actualValue, args);
}

private Expr<?> buildAndConstrainIndex(
Expr<?> lhsTrans,
Expr<?> rhsTrans,
CelType lhsType,
CelType rhsType,
BoolExpr shouldEvaluate,
boolean isOptional) {
CelType expectedElemType = null;
if (lhsType.kind() == CelKind.LIST && rhsType.kind() == CelKind.INT) {
actualValue = buildListIndex(lhsTrans, rhsTrans, ctx.mkTrue(), isOptional);
constraintSink.accept(
ctx.mkImplies(
ctx.mkNot(typeSystem.isError(actualValue)),
typeConstraintGenerator.apply(actualValue, ((ListType) lhsType).elemType())));
expectedElemType = ((ListType) lhsType).elemType();
} else if (lhsType.kind() == CelKind.MAP) {
actualValue = buildMapIndex(lhsTrans, rhsTrans, ctx.mkTrue(), isOptional);
expectedElemType = ((MapType) lhsType).valueType();
}

if (expectedElemType != null) {
Expr<?> actualValue =
lhsType.kind() == CelKind.LIST
? buildListIndex(lhsTrans, rhsTrans, shouldEvaluate, isOptional)
: buildMapIndex(lhsTrans, rhsTrans, shouldEvaluate, isOptional);

CelType finalType = isOptional ? OptionalType.create(expectedElemType) : expectedElemType;

constraintSink.accept(
ctx.mkImplies(
ctx.mkNot(typeSystem.isError(actualValue)),
typeConstraintGenerator.apply(actualValue, ((MapType) lhsType).valueType())));
} else {
BoolExpr isListGuard = ctx.mkAnd(typeSystem.isList(lhsTrans), typeSystem.isInt(rhsTrans));
BoolExpr isMapGuard = typeSystem.isMap(lhsTrans);
actualValue =
CelZ3TypeSystem.SwitchBuilder.newBuilder(ctx)
.addCase(isListGuard, buildListIndex(lhsTrans, rhsTrans, isListGuard, isOptional))
.addCase(isMapGuard, buildMapIndex(lhsTrans, rhsTrans, isMapGuard, isOptional))
.build(typeSystem.mkError());
ctx.mkAnd(shouldEvaluate, ctx.mkNot(typeSystem.isError(actualValue))),
typeConstraintGenerator.apply(actualValue, finalType)));

return actualValue;
}

return TranslatedValue.propagateStrict(ctx, typeSystem, actualValue, args);
BoolExpr isListGuard =
ctx.mkAnd(shouldEvaluate, typeSystem.isList(lhsTrans), typeSystem.isInt(rhsTrans));
BoolExpr isMapGuard = ctx.mkAnd(shouldEvaluate, typeSystem.isMap(lhsTrans));

return CelZ3TypeSystem.SwitchBuilder.newBuilder(ctx)
.addCase(isListGuard, buildListIndex(lhsTrans, rhsTrans, isListGuard, isOptional))
.addCase(isMapGuard, buildMapIndex(lhsTrans, rhsTrans, isMapGuard, isOptional))
.build(typeSystem.mkError());
}

private TranslatedValue translateConditional(
Expand Down
88 changes: 75 additions & 13 deletions verifier/src/test/java/dev/cel/verifier/CelVerifierZ3ImplTest.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -115,18 +115,21 @@ public final class CelVerifierZ3ImplTest {
.addVar(
"test_all_types",
StructTypeReference.create("cel.expr.conformance.proto3.TestAllTypes"))
.addVar("json_val", StructTypeReference.create("google.protobuf.Value"))
.addVar("json_list", StructTypeReference.create("google.protobuf.ListValue"))
.addVar("json_struct", StructTypeReference.create("google.protobuf.Struct"))
.build();

private static final CelVerifier VERIFIER =
CelVerifierFactory.newVerifier()
.setTypeProvider(
ProtoMessageTypeProvider.newBuilder()
.addDescriptors(
ImmutableList.of(
TestAllTypes.getDescriptor(), TestAllTypes.NestedMessage.getDescriptor()))
.build())
private static final ProtoMessageTypeProvider TYPE_PROVIDER =
ProtoMessageTypeProvider.newBuilder()
.addDescriptors(
ImmutableList.of(
TestAllTypes.getDescriptor(), TestAllTypes.NestedMessage.getDescriptor()))
.build();

private static final CelVerifier VERIFIER =
CelVerifierFactory.newVerifier().setTypeProvider(TYPE_PROVIDER).build();

@Before
public void setUp() {
System.setProperty("z3.skipLibraryLoad", "true");
Expand DownExpand Up@@ -226,9 +229,6 @@ private enum IsSatisfiableInconclusiveTestCase {
MASKED_BY_BMC_MAP(
"string_int_map == {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6} ? string_int_map.exists(k,"
+ " k == 'g') : false"),
MASKED_BY_BMC_NESTED(
"nested_list == [[1, 2, 3, 4, 5, 6]] ? nested_list.exists(row, row.exists(x, x == 42)) :"
+ " false"),
APPROXIMATED_STRING_TO_INT("int('123') == 123"),
APPROXIMATED_DOUBLE_TO_INT("int(1.5) == 1"),
APPROXIMATED_INT_TO_STRING("string(123) == '123'"),
Expand All@@ -252,6 +252,24 @@ public void isSatisfiable_inconclusive(@TestParameter IsSatisfiableInconclusiveT
assertThat(result.status()).isEqualTo(VerificationStatus.INCONCLUSIVE);
}

@Test
public void isSatisfiable_maskedByBmcNested_inconclusive() throws Exception {
String expr =
"nested_list == [[1, 2, 3, 4, 5, 6]] ? nested_list.exists(row, row.exists(x, x == 42)) :"
+ " false";
CelAbstractSyntaxTree ast = CEL.compile(expr).getAst();

CelVerifier customVerifier =
CelVerifierFactory.newVerifier()
.setComprehensionUnrollLimit(3)
.setTypeProvider(TYPE_PROVIDER)
.build();

CelVerificationResult result = customVerifier.isSatisfiable(ast);

assertThat(result.status()).isEqualTo(VerificationStatus.INCONCLUSIVE);
}

@Test
public void isSatisfiable_comprehensionZeroUnrollLimit_inconclusive() throws Exception {
String expr = "int_list == [1] ? int_list.exists(x, x == 1) : false";
Expand DownExpand Up@@ -1581,6 +1599,9 @@ private enum EquivalenceTestCase {
"TestAllTypes{}.?single_int64_wrapper", "optional.none()"),
OPTIONAL_FIELD_SELECTION_PROTO3_WRAPPER_EXPLICIT_NULL(
"TestAllTypes{single_int64_wrapper: null}.?single_int64_wrapper", "optional.none()"),
OPTIONAL_FIELD_SELECTION_PROTO3_WRAPPER_OPTIONAL_NONE(
"TestAllTypes{?single_int64_wrapper: optional.none()}.?single_int64_wrapper",
"optional.none()"),
OPTIONAL_FIELD_SELECTION_PROTO3_WRAPPER_PRESENT(
"TestAllTypes{single_int64_wrapper: 42}.?single_int64_wrapper", "optional.of(42)"),
OPTIONAL_FIELD_SELECTION_DYNAMIC_MISS(
Expand All@@ -1590,7 +1611,43 @@ private enum EquivalenceTestCase {
"true"),
OPTIONAL_FIELD_SELECTION_MAP_COMPREHENSION(
"{'a': 1, 'b': 2}.transformMap(k, v, v > 1, v).?b", "optional.of(2)"),
OPTIONAL_FIELD_SELECTION_BINDER("cel.bind(m, {'a': 1}, m.?a)", "optional.of(1)");
OPTIONAL_FIELD_SELECTION_BINDER("cel.bind(m, {'a': 1}, m.?a)", "optional.of(1)"),
JSON_VALUE_BOOL("google.protobuf.Value{bool_value: true}", "true"),
JSON_VALUE_NUMBER("google.protobuf.Value{number_value: 1.0}", "1.0"),
JSON_VALUE_NULL("google.protobuf.Value{null_value: 0}", "null"),
JSON_VALUE_EMPTY("google.protobuf.Value{}", "null"),
JSON_LIST_VALUE_EMPTY("google.protobuf.ListValue{}", "[]"),
JSON_STRUCT_EMPTY("google.protobuf.Struct{}", "{}"),
JSON_LIST_VALUE("google.protobuf.ListValue{values: [1, 2]}", "[1, 2]"),
JSON_STRUCT("google.protobuf.Struct{fields: {'a': 1}}", "{'a': 1}"),
JSON_STRUCT_MULTIPLE_FIELDS(
"google.protobuf.Struct{fields: {'a': 1, 'b': 'hello'}}", "{'a': 1, 'b': 'hello'}"),
JSON_STRUCT_EXPLICIT_VALUES(
"google.protobuf.Struct{fields: {'a': google.protobuf.Value{number_value: 1.0}, 'b':"
+ " google.protobuf.Value{string_value: 'hello'}}}",
"{'a': 1.0, 'b': 'hello'}"),
JSON_STRUCT_OPTIONAL_ENTRIES(
"google.protobuf.Struct{fields: {'a': 1, ?'b': optional.of(2), ?'c': optional.none()}}",
"{'a': 1, 'b': 2}"),
JSON_DEEP_NESTING(
"google.protobuf.ListValue{values: [google.protobuf.Struct{fields: {'a':"
+ " google.protobuf.Value{number_value: 1.0}}}]}",
"[{'a': 1.0}]"),
JSON_NUMBER_HETEROGENEOUS_EQUALITY("google.protobuf.Value{number_value: 1.0} == 1", "true"),
JSON_VALUE_OPTIONAL_NONE("google.protobuf.Value{?string_value: optional.none()}", "null"),
JSON_LIST_VALUE_OPTIONAL_NONE("google.protobuf.ListValue{?values: optional.none()}", "[]"),
JSON_STRUCT_OPTIONAL_NONE("google.protobuf.Struct{?fields: optional.none()}", "{}"),
JSON_VALUE_TYPE_REFLECTION("type(google.protobuf.Value{string_value: 'hi'}) == string", "true"),
JSON_STRUCT_TYPE_REFLECTION("type(google.protobuf.Struct{fields: {'a': 1}}) == map", "true"),
JSON_VAR_VALUE_EQUALITY("json_val == 'hi' || json_val != 'hi'", "true"),
JSON_VAR_LIST_EQUALITY("json_list == [1, 2] || json_list != [1, 2]", "true"),
JSON_VAR_MAP_EQUALITY("json_struct == {'a': 1} || json_struct != {'a': 1}", "true"),
JSON_VALUE_OPTIONAL_NULL_VALUE_NONE(
"google.protobuf.Value{?null_value: optional.none()}", "null"),
JSON_VALUE_OPTIONAL_NULL_VALUE_OF("google.protobuf.Value{?null_value: optional.of(0)}", "null"),
OPTIONAL_INDEX_LIST_UNWRAPPING("optional.of([1, 2, 3])[?0]", "optional.of(1)"),
OPTIONAL_INDEX_MAP_UNWRAPPING("optional.of({'a': 1})[?'a']", "optional.of(1)"),
OPTIONAL_INDEX_UNWRAPPING_NONE("optional.none()[?0]", "optional.none()");

private final String exprA;
private final String exprB;
Expand DownExpand Up@@ -1644,7 +1701,12 @@ private enum EquivalenceViolationTestCase {
"TestAllTypes{single_int32: 0}.?single_int32", "optional.of(0)"),
OPTIONAL_PROTO3_WRAPPER_ZERO_VS_UNSET(
"TestAllTypes{single_int64_wrapper: 0}.?single_int64_wrapper",
"TestAllTypes{}.?single_int64_wrapper");
"TestAllTypes{}.?single_int64_wrapper"),
OPTIONAL_PROTO3_WRAPPER_ZERO_VS_NONE(
"TestAllTypes{single_int64_wrapper: 0}.?single_int64_wrapper", "optional.none()"),
OPTIONAL_DYNAMIC_TARGET_TYPE_MISMATCH("dyn_var.?a == optional.none()", "false"),
OPTIONAL_NESTED_NONE_VS_MISSING(
"{'a': optional.none()}.?a.orValue(optional.of(1))", "optional.of(1)");

final String exprA;
final String exprB;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions verifier/src/main/java/dev/cel/verifier/BUILD.bazel
Original file line numberDiff line numberDiff line change
Expand Up@@ -129,6 +129,7 @@ java_library(
"//common/ast",
"//common/ast:cel_block",
"//common/types",
"//common/types:cel_types",
"//common/types:type_providers",
"//verifier/axioms",
"@maven//:com_google_errorprone_error_prone_annotations",
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,6 +16,7 @@

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.microsoft.z3.ArithExpr;
import com.microsoft.z3.ArrayExpr;
import com.microsoft.z3.BoolExpr;
Expand All@@ -37,6 +38,7 @@
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.ListType;
import dev.cel.common.types.MapType;
import dev.cel.common.types.NullableType;
Expand DownExpand Up@@ -79,6 +81,7 @@ final class CelAstToZ3Translator {
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 final Context ctx;
private final CelZ3TypeSystem typeSystem;
private final CelZ3OperatorTranslator operatorTranslator;
Expand DownExpand Up@@ -370,6 +373,10 @@ private TranslatedValue translateMap(CelExpr celExpr, CelAbstractSyntaxTree ast)

private TranslatedValue translateStruct(CelExpr celExpr, CelAbstractSyntaxTree ast) {
CelExpr.CelStruct createStruct = celExpr.struct();
if (isJsonWkt(createStruct.messageName())) {
return translateJsonWktStruct(celExpr, createStruct, ast);
}

// Bypass SMT when the struct is empty (return the cached SMT default pointer)
if (createStruct.entries().isEmpty()) {
return TranslatedValue.create(
Expand DownExpand Up@@ -448,6 +455,59 @@ private TranslatedValue translateStruct(CelExpr celExpr, CelAbstractSyntaxTree a
return TranslatedValue.propagateStrict(ctx, typeSystem, result, celExpr, elementsTv);
}

private static boolean isJsonWkt(String messageName) {
return messageName.equals(CelTypes.VALUE_MESSAGE)
|| messageName.equals(CelTypes.LIST_VALUE_MESSAGE)
|| messageName.equals(CelTypes.STRUCT_MESSAGE);
}

// Concretize JSON WKT unwrapping directly into native Z3 primitives to avoid
// sort incompatibilities (Message == String) and solver performance penalties (quantifiers).
private TranslatedValue translateJsonWktStruct(
CelExpr celExpr, CelExpr.CelStruct createStruct, CelAbstractSyntaxTree ast) {
Expr<?> fallback;
if (createStruct.messageName().equals(CelTypes.VALUE_MESSAGE)) {
fallback = typeSystem.mkNull();
} else if (createStruct.messageName().equals(CelTypes.LIST_VALUE_MESSAGE)) {
fallback = getDefaultValueForType(ListType.create(SimpleType.DYN));
} else {
fallback = getDefaultValueForType(MapType.create(SimpleType.STRING, SimpleType.DYN));
}

if (createStruct.entries().isEmpty()) {
return TranslatedValue.create(fallback, celExpr, typeSystem, ctx.mkFalse());
}

// 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<?> optRef = typeSystem.getOptionalRef(finalVal);
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();
}

return TranslatedValue.propagateStrict(
ctx, typeSystem, finalVal, celExpr, ImmutableList.of(entryTv));
}

private Expr<?> getDefaultValueForType(CelType type) {
if (type instanceof NullableType) {
return typeSystem.mkNull();
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -805,38 +805,83 @@ private Expr<?> buildMapIndex(

private TranslatedValue translateIndex(
List<TranslatedValue> args, CelAbstractSyntaxTree ast, boolean isOptional) {
Expr<?> lhsTrans = args.get(0).z3Expr();
Expr<?> rhsTrans = args.get(1).z3Expr();

TranslatedValue lhs = args.get(0);
TranslatedValue rhs = args.get(1);
CelType lhsType = extractAstTypeOrDefault(lhs, ast);
CelType rhsType = extractAstTypeOrDefault(rhs, ast);

Expr<?> actualValue;
Expr<?> lhsTrans = lhs.z3Expr();
Expr<?> rhsTrans = rhs.z3Expr();

BoolExpr isLhsOpt = ctx.mkFalse();
BoolExpr lhsHasValue = ctx.mkFalse();
BoolExpr shouldEvaluate = ctx.mkTrue();

if (isOptional) {
isLhsOpt = typeSystem.isOptional(lhsTrans);
Expr<?> optRef = typeSystem.getOptionalRef(lhsTrans);
lhsHasValue = typeSystem.optHasValue(optRef);

lhsTrans = ctx.mkITE(isLhsOpt, typeSystem.getOptionalValue(optRef), lhsTrans);
shouldEvaluate = (BoolExpr) ctx.mkITE(isLhsOpt, lhsHasValue, ctx.mkTrue());

if (lhsType instanceof OptionalType) {
lhsType = lhsType.parameters().get(0);
}
}

Expr<?> actualValue =
buildAndConstrainIndex(lhsTrans, rhsTrans, lhsType, rhsType, shouldEvaluate, isOptional);

if (isOptional) {
actualValue =
ctx.mkITE(
ctx.mkAnd(isLhsOpt, ctx.mkNot(lhsHasValue)),
typeSystem.mkOptionalNone(),
actualValue);
}

return TranslatedValue.propagateStrict(ctx, typeSystem, actualValue, args);
}

private Expr<?> buildAndConstrainIndex(
Expr<?> lhsTrans,
Expr<?> rhsTrans,
CelType lhsType,
CelType rhsType,
BoolExpr shouldEvaluate,
boolean isOptional) {
CelType expectedElemType = null;
if (lhsType.kind() == CelKind.LIST && rhsType.kind() == CelKind.INT) {
actualValue = buildListIndex(lhsTrans, rhsTrans, ctx.mkTrue(), isOptional);
constraintSink.accept(
ctx.mkImplies(
ctx.mkNot(typeSystem.isError(actualValue)),
typeConstraintGenerator.apply(actualValue, ((ListType) lhsType).elemType())));
expectedElemType = ((ListType) lhsType).elemType();
} else if (lhsType.kind() == CelKind.MAP) {
actualValue = buildMapIndex(lhsTrans, rhsTrans, ctx.mkTrue(), isOptional);
expectedElemType = ((MapType) lhsType).valueType();
}

if (expectedElemType != null) {
Expr<?> actualValue =
lhsType.kind() == CelKind.LIST
? buildListIndex(lhsTrans, rhsTrans, shouldEvaluate, isOptional)
: buildMapIndex(lhsTrans, rhsTrans, shouldEvaluate, isOptional);

CelType finalType = isOptional ? OptionalType.create(expectedElemType) : expectedElemType;

constraintSink.accept(
ctx.mkImplies(
ctx.mkNot(typeSystem.isError(actualValue)),
typeConstraintGenerator.apply(actualValue, ((MapType) lhsType).valueType())));
} else {
BoolExpr isListGuard = ctx.mkAnd(typeSystem.isList(lhsTrans), typeSystem.isInt(rhsTrans));
BoolExpr isMapGuard = typeSystem.isMap(lhsTrans);
actualValue =
CelZ3TypeSystem.SwitchBuilder.newBuilder(ctx)
.addCase(isListGuard, buildListIndex(lhsTrans, rhsTrans, isListGuard, isOptional))
.addCase(isMapGuard, buildMapIndex(lhsTrans, rhsTrans, isMapGuard, isOptional))
.build(typeSystem.mkError());
ctx.mkAnd(shouldEvaluate, ctx.mkNot(typeSystem.isError(actualValue))),
typeConstraintGenerator.apply(actualValue, finalType)));

return actualValue;
}

return TranslatedValue.propagateStrict(ctx, typeSystem, actualValue, args);
BoolExpr isListGuard =
ctx.mkAnd(shouldEvaluate, typeSystem.isList(lhsTrans), typeSystem.isInt(rhsTrans));
BoolExpr isMapGuard = ctx.mkAnd(shouldEvaluate, typeSystem.isMap(lhsTrans));

return CelZ3TypeSystem.SwitchBuilder.newBuilder(ctx)
.addCase(isListGuard, buildListIndex(lhsTrans, rhsTrans, isListGuard, isOptional))
.addCase(isMapGuard, buildMapIndex(lhsTrans, rhsTrans, isMapGuard, isOptional))
.build(typeSystem.mkError());
}

private TranslatedValue translateConditional(
Expand Down
88 changes: 75 additions & 13 deletions verifier/src/test/java/dev/cel/verifier/CelVerifierZ3ImplTest.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -115,18 +115,21 @@ public final class CelVerifierZ3ImplTest {
.addVar(
"test_all_types",
StructTypeReference.create("cel.expr.conformance.proto3.TestAllTypes"))
.addVar("json_val", StructTypeReference.create("google.protobuf.Value"))
.addVar("json_list", StructTypeReference.create("google.protobuf.ListValue"))
.addVar("json_struct", StructTypeReference.create("google.protobuf.Struct"))
.build();

private static final CelVerifier VERIFIER =
CelVerifierFactory.newVerifier()
.setTypeProvider(
ProtoMessageTypeProvider.newBuilder()
.addDescriptors(
ImmutableList.of(
TestAllTypes.getDescriptor(), TestAllTypes.NestedMessage.getDescriptor()))
.build())
private static final ProtoMessageTypeProvider TYPE_PROVIDER =
ProtoMessageTypeProvider.newBuilder()
.addDescriptors(
ImmutableList.of(
TestAllTypes.getDescriptor(), TestAllTypes.NestedMessage.getDescriptor()))
.build();

private static final CelVerifier VERIFIER =
CelVerifierFactory.newVerifier().setTypeProvider(TYPE_PROVIDER).build();

@Before
public void setUp() {
System.setProperty("z3.skipLibraryLoad", "true");
Expand DownExpand Up@@ -226,9 +229,6 @@ private enum IsSatisfiableInconclusiveTestCase {
MASKED_BY_BMC_MAP(
"string_int_map == {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6} ? string_int_map.exists(k,"
+ " k == 'g') : false"),
MASKED_BY_BMC_NESTED(
"nested_list == [[1, 2, 3, 4, 5, 6]] ? nested_list.exists(row, row.exists(x, x == 42)) :"
+ " false"),
APPROXIMATED_STRING_TO_INT("int('123') == 123"),
APPROXIMATED_DOUBLE_TO_INT("int(1.5) == 1"),
APPROXIMATED_INT_TO_STRING("string(123) == '123'"),
Expand All@@ -252,6 +252,24 @@ public void isSatisfiable_inconclusive(@TestParameter IsSatisfiableInconclusiveT
assertThat(result.status()).isEqualTo(VerificationStatus.INCONCLUSIVE);
}

@Test
public void isSatisfiable_maskedByBmcNested_inconclusive() throws Exception {
String expr =
"nested_list == [[1, 2, 3, 4, 5, 6]] ? nested_list.exists(row, row.exists(x, x == 42)) :"
+ " false";
CelAbstractSyntaxTree ast = CEL.compile(expr).getAst();

CelVerifier customVerifier =
CelVerifierFactory.newVerifier()
.setComprehensionUnrollLimit(3)
.setTypeProvider(TYPE_PROVIDER)
.build();

CelVerificationResult result = customVerifier.isSatisfiable(ast);

assertThat(result.status()).isEqualTo(VerificationStatus.INCONCLUSIVE);
}

@Test
public void isSatisfiable_comprehensionZeroUnrollLimit_inconclusive() throws Exception {
String expr = "int_list == [1] ? int_list.exists(x, x == 1) : false";
Expand DownExpand Up@@ -1581,6 +1599,9 @@ private enum EquivalenceTestCase {
"TestAllTypes{}.?single_int64_wrapper", "optional.none()"),
OPTIONAL_FIELD_SELECTION_PROTO3_WRAPPER_EXPLICIT_NULL(
"TestAllTypes{single_int64_wrapper: null}.?single_int64_wrapper", "optional.none()"),
OPTIONAL_FIELD_SELECTION_PROTO3_WRAPPER_OPTIONAL_NONE(
"TestAllTypes{?single_int64_wrapper: optional.none()}.?single_int64_wrapper",
"optional.none()"),
OPTIONAL_FIELD_SELECTION_PROTO3_WRAPPER_PRESENT(
"TestAllTypes{single_int64_wrapper: 42}.?single_int64_wrapper", "optional.of(42)"),
OPTIONAL_FIELD_SELECTION_DYNAMIC_MISS(
Expand All@@ -1590,7 +1611,43 @@ private enum EquivalenceTestCase {
"true"),
OPTIONAL_FIELD_SELECTION_MAP_COMPREHENSION(
"{'a': 1, 'b': 2}.transformMap(k, v, v > 1, v).?b", "optional.of(2)"),
OPTIONAL_FIELD_SELECTION_BINDER("cel.bind(m, {'a': 1}, m.?a)", "optional.of(1)");
OPTIONAL_FIELD_SELECTION_BINDER("cel.bind(m, {'a': 1}, m.?a)", "optional.of(1)"),
JSON_VALUE_BOOL("google.protobuf.Value{bool_value: true}", "true"),
JSON_VALUE_NUMBER("google.protobuf.Value{number_value: 1.0}", "1.0"),
JSON_VALUE_NULL("google.protobuf.Value{null_value: 0}", "null"),
JSON_VALUE_EMPTY("google.protobuf.Value{}", "null"),
JSON_LIST_VALUE_EMPTY("google.protobuf.ListValue{}", "[]"),
JSON_STRUCT_EMPTY("google.protobuf.Struct{}", "{}"),
JSON_LIST_VALUE("google.protobuf.ListValue{values: [1, 2]}", "[1, 2]"),
JSON_STRUCT("google.protobuf.Struct{fields: {'a': 1}}", "{'a': 1}"),
JSON_STRUCT_MULTIPLE_FIELDS(
"google.protobuf.Struct{fields: {'a': 1, 'b': 'hello'}}", "{'a': 1, 'b': 'hello'}"),
JSON_STRUCT_EXPLICIT_VALUES(
"google.protobuf.Struct{fields: {'a': google.protobuf.Value{number_value: 1.0}, 'b':"
+ " google.protobuf.Value{string_value: 'hello'}}}",
"{'a': 1.0, 'b': 'hello'}"),
JSON_STRUCT_OPTIONAL_ENTRIES(
"google.protobuf.Struct{fields: {'a': 1, ?'b': optional.of(2), ?'c': optional.none()}}",
"{'a': 1, 'b': 2}"),
JSON_DEEP_NESTING(
"google.protobuf.ListValue{values: [google.protobuf.Struct{fields: {'a':"
+ " google.protobuf.Value{number_value: 1.0}}}]}",
"[{'a': 1.0}]"),
JSON_NUMBER_HETEROGENEOUS_EQUALITY("google.protobuf.Value{number_value: 1.0} == 1", "true"),
JSON_VALUE_OPTIONAL_NONE("google.protobuf.Value{?string_value: optional.none()}", "null"),
JSON_LIST_VALUE_OPTIONAL_NONE("google.protobuf.ListValue{?values: optional.none()}", "[]"),
JSON_STRUCT_OPTIONAL_NONE("google.protobuf.Struct{?fields: optional.none()}", "{}"),
JSON_VALUE_TYPE_REFLECTION("type(google.protobuf.Value{string_value: 'hi'}) == string", "true"),
JSON_STRUCT_TYPE_REFLECTION("type(google.protobuf.Struct{fields: {'a': 1}}) == map", "true"),
JSON_VAR_VALUE_EQUALITY("json_val == 'hi' || json_val != 'hi'", "true"),
JSON_VAR_LIST_EQUALITY("json_list == [1, 2] || json_list != [1, 2]", "true"),
JSON_VAR_MAP_EQUALITY("json_struct == {'a': 1} || json_struct != {'a': 1}", "true"),
JSON_VALUE_OPTIONAL_NULL_VALUE_NONE(
"google.protobuf.Value{?null_value: optional.none()}", "null"),
JSON_VALUE_OPTIONAL_NULL_VALUE_OF("google.protobuf.Value{?null_value: optional.of(0)}", "null"),
OPTIONAL_INDEX_LIST_UNWRAPPING("optional.of([1, 2, 3])[?0]", "optional.of(1)"),
OPTIONAL_INDEX_MAP_UNWRAPPING("optional.of({'a': 1})[?'a']", "optional.of(1)"),
OPTIONAL_INDEX_UNWRAPPING_NONE("optional.none()[?0]", "optional.none()");

private final String exprA;
private final String exprB;
Expand DownExpand Up@@ -1644,7 +1701,12 @@ private enum EquivalenceViolationTestCase {
"TestAllTypes{single_int32: 0}.?single_int32", "optional.of(0)"),
OPTIONAL_PROTO3_WRAPPER_ZERO_VS_UNSET(
"TestAllTypes{single_int64_wrapper: 0}.?single_int64_wrapper",
"TestAllTypes{}.?single_int64_wrapper");
"TestAllTypes{}.?single_int64_wrapper"),
OPTIONAL_PROTO3_WRAPPER_ZERO_VS_NONE(
"TestAllTypes{single_int64_wrapper: 0}.?single_int64_wrapper", "optional.none()"),
OPTIONAL_DYNAMIC_TARGET_TYPE_MISMATCH("dyn_var.?a == optional.none()", "false"),
OPTIONAL_NESTED_NONE_VS_MISSING(
"{'a': optional.none()}.?a.orValue(optional.of(1))", "optional.of(1)");

final String exprA;
final String exprB;
Expand Down
Loading