From 5d79bb64a46e8e16c0f60b6c6ebcdc2042188778 Mon Sep 17 00:00:00 2001 From: Jonathan Tatum Date: Wed, 25 Nov 2026 14:24:38 -0800 Subject: [PATCH] Widen type joins to union types and bind type params to dyn for dyn arguments in the checker. PiperOrigin-RevId: 1030191294 --- checker/internal/type_checker_impl_test.cc | 67 +++- checker/internal/type_inference_context.cc | 89 ++++- checker/internal/type_inference_context.h | 28 +- .../internal/type_inference_context_test.cc | 324 ++++++++++++++++++ conformance/BUILD | 21 +- 5 files changed, 491 insertions(+), 38 deletions(-) diff --git a/checker/internal/type_checker_impl_test.cc b/checker/internal/type_checker_impl_test.cc index 2caf25eae..e8a840a7e 100644 --- a/checker/internal/type_checker_impl_test.cc +++ b/checker/internal/type_checker_impl_test.cc @@ -3129,12 +3129,46 @@ INSTANTIATE_TEST_SUITE_P( CheckedExprTestCase{.expr = "[null, test_msg][0]", .expected_result_type = AstType(MessageTypeSpec( "cel.expr.conformance.proto3.TestAllTypes"))}, + CheckedExprTestCase{.expr = "[{'k': dyn(1)}, {dyn('k'): 1}][0]", + // Each parameter is joined independently. + .expected_result_type = AstType(MapTypeSpec( + std::make_unique(DynTypeSpec()), + std::make_unique(DynTypeSpec())))}, + CheckedExprTestCase{.expr = "false ? {dyn(1): 1} : {'b': dyn('c')}", + .expected_result_type = AstType(MapTypeSpec( + std::make_unique(DynTypeSpec()), + std::make_unique(DynTypeSpec())))}, + CheckedExprTestCase{ + .expr = "[test_msg.single_any, test_msg.single_any]", + .expected_result_type = AstType(ListTypeSpec( + std::make_unique(WellKnownTypeSpec::kAny)))}, + CheckedExprTestCase{.expr = "[test_msg.single_any, 1]", + .expected_result_type = AstType(ListTypeSpec( + std::make_unique(DynTypeSpec())))}, + CheckedExprTestCase{.expr = "[1, test_msg.single_any]", + .expected_result_type = AstType(ListTypeSpec( + std::make_unique(DynTypeSpec())))}, + CheckedExprTestCase{.expr = "[dyn(1), test_msg.single_any]", + .expected_result_type = AstType(ListTypeSpec( + std::make_unique(DynTypeSpec())))}, + CheckedExprTestCase{.expr = "true ? test_msg.single_any : 1", + .expected_result_type = AstType(DynTypeSpec())}, + CheckedExprTestCase{.expr = "['a'] + dyn([1])", + .expected_result_type = AstType(ListTypeSpec( + std::make_unique(DynTypeSpec())))}, + CheckedExprTestCase{.expr = "dyn([1]) + ['a']", + .expected_result_type = AstType(ListTypeSpec( + std::make_unique(DynTypeSpec())))}, + CheckedExprTestCase{.expr = "[test_msg.single_int64_wrapper, 1, null]", + .expected_result_type = AstType(ListTypeSpec( + std::make_unique(PrimitiveTypeWrapper( + PrimitiveType::kInt64))))}, CheckedExprTestCase{ - .expr = "[{'k': dyn(1)}, {dyn('k'): 1}][0]", - // Ambiguous type resolution, but we prefer the first option. + // Elements are joined left to right: int and null join to dyn + // before the wrapper is seen. + .expr = "[1, null, test_msg.single_int64_wrapper]", .expected_result_type = AstType( - MapTypeSpec(std::make_unique(PrimitiveType::kString), - std::make_unique(DynTypeSpec())))}, + ListTypeSpec(std::make_unique(DynTypeSpec())))}, CheckedExprTestCase{ .expr = "[{'k': 1}, {dyn('k'): 1}][0]", .expected_result_type = AstType( @@ -3158,6 +3192,31 @@ INSTANTIATE_TEST_SUITE_P( .expr = "[{'k': 1.0}, {dyn('k'): test_msg.single_int64_wrapper}][0]", .expected_result_type = AstType(DynTypeSpec())}, + // Element types that don't unify are not widened parameter-wise: the + // whole element type falls back to dyn. + CheckedExprTestCase{.expr = "[[1], [1u]]", + .expected_result_type = AstType(ListTypeSpec( + std::make_unique(DynTypeSpec())))}, + // Outside of aggregate literals there is no dyn fallback. + CheckedExprTestCase{ + .expr = "false ? [1u] : [2]", + .expected_result_type = AstType(), + .error_substring = "no matching overload for '_?_:_'"}, + CheckedExprTestCase{ + .expr = "false ? {dyn(1): 1} : {'b': 1u}", + .expected_result_type = AstType(), + .error_substring = "no matching overload for '_?_:_'"}, + // Legacy nullable types are kept when joined with null. + CheckedExprTestCase{ + .expr = "false ? [null] : [test_msg]", + .expected_result_type = + AstType(ListTypeSpec(std::make_unique(MessageTypeSpec( + "cel.expr.conformance.proto3.TestAllTypes"))))}, + CheckedExprTestCase{ + .expr = "false ? [test_msg] : [null]", + .expected_result_type = + AstType(ListTypeSpec(std::make_unique(MessageTypeSpec( + "cel.expr.conformance.proto3.TestAllTypes"))))}, CheckedExprTestCase{ .expr = "test_msg.single_int64", .expected_result_type = AstType(PrimitiveType::kInt64), diff --git a/checker/internal/type_inference_context.cc b/checker/internal/type_inference_context.cc index 0140119ef..2899e638f 100644 --- a/checker/internal/type_inference_context.cc +++ b/checker/internal/type_inference_context.cc @@ -104,7 +104,9 @@ bool IsUnionType(Type t) { bool IsSubsetOf(Type a, Type b) { switch (b.kind()) { case TypeKind::kAny: - return true; + // Any only unifies with itself; joining it with any other type widens to + // dyn. + return false; case TypeKind::kBoolWrapper: return a.IsBool() || a.IsNull(); case TypeKind::kBytesWrapper: @@ -179,6 +181,24 @@ bool HasTypeParam(const Type& type) { return false; } +// Binds every type param that occurs in `type` (directly or transitively) to +// dyn in `substitutions`, replacing any existing binding. +// +// Bindings are not followed: a type param that another one is bound to keeps +// its own binding. +void BindTypeParamsToDyn( + const Type& type, + absl::flat_hash_map& substitutions) { + if (type.kind() == TypeKind::kTypeParam) { + TypeParamType type_param = type.GetTypeParam(); + substitutions[type_param.name()] = DynType(); + return; + } + for (const Type& param : type.GetParameters()) { + BindTypeParamsToDyn(param, substitutions); + } +} + // Returns a copy of `type` with `transform` applied to every type in it, in // pre-order: first to `type` itself (updating it in place), then recursively // to each type parameter of the result (the element type of a list, the key @@ -329,13 +349,11 @@ bool TypeInferenceContext::IsAssignableInternal( prospective_substitutions.contains(to.GetTypeParam().name())) { TypeParamType to_param = to.GetTypeParam(); absl::string_view to_name = to_param.name(); - // Types have special unification: type(A) and type(B) unify to type(dyn) - // if A and B are not co-assignable (at any depth, e.g. list(type(int)) and - // list(type(uint)) unify to list(type(dyn))). This is the only widening - // other than for union types. + // Widen the binding to the join of the two types if either one needs to be + // widened to a union type (dyn, a wrapper, or type(dyn)) at any depth, e.g. + // map(dyn, int) and map(string, dyn) unify to map(dyn, dyn). SubstitutionMap join_subs = prospective_substitutions; - if (std::optional joined = - JoinTypeTypes(from_subs, to_subs, join_subs); + if (std::optional joined = JoinTypes(from_subs, to_subs, join_subs); joined.has_value() && !OccursWithin(to_name, *joined, join_subs)) { join_subs[to_name] = *std::move(joined); prospective_substitutions = std::move(join_subs); @@ -399,6 +417,16 @@ bool TypeInferenceContext::IsAssignableInternal( } if (IsWildCardType(from_subs) || IsWildCardType(to_subs)) { + // A dyn (or any) value may hold any instance of a parameterized type, so + // its type params can't be inferred from other arguments, e.g. + // `dyn(optional.of('foo')).orValue(1)` is dyn, not int. Only the type + // params that `to` names are rebound: if `to` is itself a bound type param, + // the type params in its binding belong to another expression. + if ((from_subs.kind() == TypeKind::kDyn || + from_subs.kind() == TypeKind::kAny) && + to.kind() != TypeKind::kTypeParam) { + BindTypeParamsToDyn(to_subs, prospective_substitutions); + } return true; } @@ -450,11 +478,35 @@ Type TypeInferenceContext::Substitute( return subs; } -std::optional TypeInferenceContext::JoinTypeTypes( +std::optional TypeInferenceContext::JoinTypes( const Type& from, const Type& to, SubstitutionMap& prospective_substitutions) { Type from_subs = Substitute(from, prospective_substitutions); Type to_subs = Substitute(to, prospective_substitutions); + if (from_subs == to_subs) { + return std::nullopt; + } + // Free type params are bound by ordinary unification, and errors don't + // constrain the other type. + if (from_subs.kind() == TypeKind::kTypeParam || + to_subs.kind() == TypeKind::kTypeParam || + from_subs.kind() == TypeKind::kError || + to_subs.kind() == TypeKind::kError) { + return std::nullopt; + } + if (to_subs.kind() == TypeKind::kDyn) { + // Already the most general type. + return std::nullopt; + } + // Any is only preserved when joined with itself. + if (from_subs.kind() == TypeKind::kDyn || + from_subs.kind() == TypeKind::kAny || to_subs.kind() == TypeKind::kAny) { + return DynType(); + } + // A wrapper admits its primitive type and null. + if (IsUnionType(from_subs) && IsSubsetOf(to_subs, from_subs)) { + return from_subs; + } if (from_subs.IsType() && to_subs.IsType()) { SubstitutionMap scratch = prospective_substitutions; if (IsAssignableInternal(from_subs.GetType().GetType(), @@ -479,13 +531,18 @@ std::optional TypeInferenceContext::JoinTypeTypes( joined.reserve(to_params.size()); for (size_t i = 0; i < to_params.size(); ++i) { std::optional param = - JoinTypeTypes(from_params[i], to_params[i], scratch); + JoinTypes(from_params[i], to_params[i], scratch); if (param.has_value()) { changed = true; joined.push_back(*std::move(param)); } else if (IsAssignableInternal(from_params[i], to_params[i], scratch)) { - // Positions that don't need widening must still be assignable. - joined.push_back(to_params[i]); + // Positions that don't need widening must still be assignable. Keep the + // more general of the two (e.g. a legacy nullable type over null). + joined.push_back( + CompareGenerality(from_params[i], to_params[i], scratch) == + RelativeGenerality::kMoreGeneral + ? from_params[i] + : to_params[i]); } else { return std::nullopt; } @@ -710,10 +767,16 @@ TypeInferenceContext::ResolveOverload(const FunctionDecl& decl, if (is_match) { matching_overloads.push_back(ovl); assignability_context.UpdateInferredTypeAssignments(); + // Compare the result types with the inferred bindings applied: each + // overload is instantiated with its own type params, so overloads that + // agree on the result (e.g. optional(dyn) for a dyn operand) would + // otherwise never compare equal. + Type overload_result_type = FullySubstitute( + call_type_instance.result_type, /*free_to_dyn=*/false); if (!result_type.has_value()) { - result_type = call_type_instance.result_type; + result_type = overload_result_type; } else { - if (!TypeEquivalent(*result_type, call_type_instance.result_type)) { + if (!TypeEquivalent(*result_type, overload_result_type)) { result_type = DynType(); } } diff --git a/checker/internal/type_inference_context.h b/checker/internal/type_inference_context.h index 9be7a8063..807d05092 100644 --- a/checker/internal/type_inference_context.h +++ b/checker/internal/type_inference_context.h @@ -231,17 +231,27 @@ class TypeInferenceContext { const Type& type, absl::FunctionRef replace_free_var) const; - // Types have special unification: type(A) and type(B) unify to type(dyn) if - // A and B are not co-assignable. This applies at any depth of matching - // parameterized types (e.g. list(type(int)) and list(type(uint)) unify to + // Computes the join (least upper bound) of `from` and `to` when one of them + // has to be widened to a union type: + // + // - dyn joined with any other type is dyn. + // - any joined with any type other than itself is dyn. + // - a wrapper joined with its primitive type or null is the wrapper. + // - type(A) joined with type(B) is type(dyn) if A and B are not + // co-assignable. + // + // This applies at any depth of matching parameterized types, independently + // for each parameter (e.g. map(dyn, int) and map(string, dyn) join to + // map(dyn, dyn), and list(type(int)) and list(type(uint)) join to // list(type(dyn))). // - // Returns the joined type, or nullopt if no type(...) position needs - // widening or the types do not otherwise unify (every position that is not - // widened must be assignable). On success, any type parameter bindings - // needed for the join are added to `prospective_substitutions`. - std::optional JoinTypeTypes(const Type& from, const Type& to, - SubstitutionMap& prospective_substitutions); + // Returns the joined type, or nullopt if `to` already admits `from` without + // widening (including when a free type param can be bound instead) or the + // types do not otherwise unify (every position that is not widened must be + // assignable). On success, any type parameter bindings needed for the join + // are added to `prospective_substitutions`. + std::optional JoinTypes(const Type& from, const Type& to, + SubstitutionMap& prospective_substitutions); bool OccursWithin(absl::string_view var_name, const Type& type, const SubstitutionMap& substitutions) const; diff --git a/checker/internal/type_inference_context_test.cc b/checker/internal/type_inference_context_test.cc index 10fdd84f9..4dfefb170 100644 --- a/checker/internal/type_inference_context_test.cc +++ b/checker/internal/type_inference_context_test.cc @@ -14,6 +14,8 @@ #include "checker/internal/type_inference_context.h" +#include +#include #include #include @@ -1359,5 +1361,327 @@ TEST(TypeInferenceContextTest, ConcreteTypeTypeParamsAreInterchangeable) { TypeType(&arena, StringType()))); } +// Returns the finalized result type of `same(lhs, rhs)`, where `same` is +// declared as `same(A, A) -> A`: the join of `lhs` and `rhs`, in that order. +std::string JoinedTypeName(const Type& lhs, const Type& rhs) { + google::protobuf::Arena arena; + TypeInferenceContext context(&arena); + absl::StatusOr decl = MakeSameTypeDecl(); + ABSL_CHECK_OK(decl.status()); + std::optional resolution = + context.ResolveOverload(*decl, {lhs, rhs}, false); + if (!resolution.has_value()) { + return ""; + } + return FormatTypeName(context.FinalizeType(resolution->result_type)); +} + +TEST(TypeInferenceContextTest, JoinAnyWithNullWidensToDyn) { + EXPECT_EQ(JoinedTypeName(AnyType(), NullType()), "dyn"); + EXPECT_EQ(JoinedTypeName(NullType(), AnyType()), "dyn"); +} + +TEST(TypeInferenceContextTest, JoinNestedAnyWidensToDyn) { + google::protobuf::Arena arena; + + EXPECT_EQ( + JoinedTypeName(ListType(&arena, AnyType()), ListType(&arena, IntType())), + "list(dyn)"); + EXPECT_EQ( + JoinedTypeName(ListType(&arena, IntType()), ListType(&arena, AnyType())), + "list(dyn)"); +} + +TEST(TypeInferenceContextTest, JoinAsymmetricDynNestedMaps) { + google::protobuf::Arena arena; + Type list_map_dyn_int = + ListType(&arena, MapType(&arena, DynType(), IntType())); + Type list_map_string_dyn = + ListType(&arena, MapType(&arena, StringType(), DynType())); + + EXPECT_EQ(JoinedTypeName(list_map_dyn_int, list_map_string_dyn), + "list(map(dyn, dyn))"); + EXPECT_EQ(JoinedTypeName(list_map_string_dyn, list_map_dyn_int), + "list(map(dyn, dyn))"); +} + +TEST(TypeInferenceContextTest, JoinAsymmetricDynOpaqueTypes) { + google::protobuf::Arena arena; + std::vector dyn_int = {DynType(), IntType()}; + std::vector string_dyn = {StringType(), DynType()}; + Type pair_dyn_int = OpaqueType(&arena, "pair", dyn_int); + Type pair_string_dyn = OpaqueType(&arena, "pair", string_dyn); + + EXPECT_EQ(JoinedTypeName(pair_dyn_int, pair_string_dyn), "pair(dyn, dyn)"); + EXPECT_EQ(JoinedTypeName(pair_string_dyn, pair_dyn_int), "pair(dyn, dyn)"); +} + +TEST(TypeInferenceContextTest, JoinAsymmetricWrapperMaps) { + google::protobuf::Arena arena; + Type map_wrapper_int = MapType(&arena, IntWrapperType(), IntType()); + Type map_int_wrapper = MapType(&arena, IntType(), IntWrapperType()); + + for (const auto& [lhs, rhs] : + {std::pair{map_wrapper_int, map_int_wrapper}, + std::pair{map_int_wrapper, map_wrapper_int}}) { + TypeInferenceContext context(&arena); + ASSERT_OK_AND_ASSIGN(FunctionDecl decl, MakeSameTypeDecl()); + std::optional resolution = + context.ResolveOverload(decl, {lhs, rhs}, false); + ASSERT_TRUE(resolution.has_value()); + EXPECT_THAT(context.FinalizeType(resolution->result_type), + IsMapType(IsTypeKind(TypeKind::kIntWrapper), + IsTypeKind(TypeKind::kIntWrapper))); + } +} + +TEST(TypeInferenceContextTest, JoinKeepsLegacyNullableOverNullWhenWidening) { + google::protobuf::Arena arena; + Type map_wrapper_duration = MapType(&arena, IntWrapperType(), DurationType()); + Type map_int_null = MapType(&arena, IntType(), NullType()); + + TypeInferenceContext context(&arena); + ASSERT_OK_AND_ASSIGN(FunctionDecl decl, MakeSameTypeDecl()); + std::optional resolution = + context.ResolveOverload(decl, {map_int_null, map_wrapper_duration}, + false); + ASSERT_TRUE(resolution.has_value()); + EXPECT_THAT(context.FinalizeType(resolution->result_type), + IsMapType(IsTypeKind(TypeKind::kIntWrapper), + IsTypeKind(TypeKind::kDuration))); +} + +constexpr char kNoMatchingOverload[] = ""; + +TEST(TypeInferenceContextTest, JoinFailsForUnrelatedTypes) { + google::protobuf::Arena arena; + + EXPECT_EQ(JoinedTypeName(IntType(), UintType()), kNoMatchingOverload); + EXPECT_EQ(JoinedTypeName(IntWrapperType(), StringType()), + kNoMatchingOverload); + EXPECT_EQ(JoinedTypeName(StringType(), IntWrapperType()), + kNoMatchingOverload); + EXPECT_EQ(JoinedTypeName(IntWrapperType(), StringWrapperType()), + kNoMatchingOverload); + EXPECT_EQ(JoinedTypeName(OptionalType(&arena, IntType()), + ListType(&arena, IntType())), + kNoMatchingOverload); + EXPECT_EQ(JoinedTypeName(ListType(&arena, IntWrapperType()), + ListType(&arena, StringType())), + kNoMatchingOverload); +} + +TEST(TypeInferenceContextTest, JoinFailsIfAnyParameterDoesNotUnify) { + google::protobuf::Arena arena; + // The keys could be widened, but the values don't unify. + Type map_dyn_int = MapType(&arena, DynType(), IntType()); + Type map_string_uint = MapType(&arena, StringType(), UintType()); + Type map_wrapper_int = MapType(&arena, IntWrapperType(), IntType()); + Type map_int_uint = MapType(&arena, IntType(), UintType()); + Type map_type_int = MapType(&arena, TypeType(&arena, IntType()), IntType()); + Type map_type_uint = + MapType(&arena, TypeType(&arena, UintType()), UintType()); + + EXPECT_EQ(JoinedTypeName(map_string_uint, map_dyn_int), kNoMatchingOverload); + EXPECT_EQ(JoinedTypeName(map_wrapper_int, map_int_uint), kNoMatchingOverload); + EXPECT_EQ(JoinedTypeName(map_int_uint, map_wrapper_int), kNoMatchingOverload); + EXPECT_EQ(JoinedTypeName(map_type_int, map_type_uint), kNoMatchingOverload); +} + +TEST(TypeInferenceContextTest, JoinFailsForMismatchedOpaqueTypes) { + google::protobuf::Arena arena; + std::vector dyn_param = {DynType()}; + std::vector int_param = {IntType()}; + std::vector int_int_params = {IntType(), IntType()}; + + EXPECT_EQ(JoinedTypeName(OpaqueType(&arena, "foo", dyn_param), + OpaqueType(&arena, "bar", int_param)), + kNoMatchingOverload); + EXPECT_EQ(JoinedTypeName(OpaqueType(&arena, "tuple", dyn_param), + OpaqueType(&arena, "tuple", int_int_params)), + kNoMatchingOverload); +} + +TEST(TypeInferenceContextTest, FailedJoinLeavesBindingUnchanged) { + google::protobuf::Arena arena; + TypeInferenceContext context(&arena); + Type type_var = context.InstantiateTypeParams(TypeParamType("T")); + ASSERT_TRUE(context.IsAssignable(MapType(&arena, StringType(), UintType()), + type_var)); + + EXPECT_FALSE( + context.IsAssignable(MapType(&arena, DynType(), IntType()), type_var)); + + EXPECT_EQ(FormatTypeName(context.FinalizeType(type_var)), + "map(string, uint)"); +} + +TEST(TypeInferenceContextTest, JoinNullWithMessageFailsWithStrictNulls) { + google::protobuf::Arena arena; + TypeInferenceContext context(&arena, + /*enable_legacy_null_assignment=*/false); + ASSERT_OK_AND_ASSIGN(FunctionDecl decl, MakeSameTypeDecl()); + + EXPECT_FALSE(context + .ResolveOverload(decl, + {ListType(&arena, NullType()), + ListType(&arena, DurationType())}, + false) + .has_value()); +} + +absl::StatusOr MakeOrValueDecl(google::protobuf::Arena* arena) { + return MakeFunctionDecl( + "orValue", MakeOverloadDecl("optional_orValue", TypeParamType("V"), + OptionalType(arena, TypeParamType("V")), + TypeParamType("V"))); +} + +TEST(TypeInferenceContextTest, DynArgBindsTypeParamsOfParameterizedParam) { + google::protobuf::Arena arena; + TypeInferenceContext context(&arena); + ASSERT_OK_AND_ASSIGN(FunctionDecl decl, MakeOrValueDecl(&arena)); + + // The dyn value may hold an optional of any type, so the result can't be + // inferred from the other argument. + std::optional resolution = + context.ResolveOverload(decl, {DynType(), IntType()}, false); + ASSERT_TRUE(resolution.has_value()); + EXPECT_THAT(context.FinalizeType(resolution->result_type), + IsTypeKind(TypeKind::kDyn)); +} + +TEST(TypeInferenceContextTest, AnyArgBindsTypeParamsOfParameterizedParam) { + google::protobuf::Arena arena; + TypeInferenceContext context(&arena); + ASSERT_OK_AND_ASSIGN(FunctionDecl decl, MakeOrValueDecl(&arena)); + + std::optional resolution = + context.ResolveOverload(decl, {AnyType(), IntType()}, false); + ASSERT_TRUE(resolution.has_value()); + EXPECT_THAT(context.FinalizeType(resolution->result_type), + IsTypeKind(TypeKind::kDyn)); +} + +TEST(TypeInferenceContextTest, DynArgBindsNestedTypeParams) { + google::protobuf::Arena arena; + TypeInferenceContext context(&arena); + ASSERT_OK_AND_ASSIGN( + FunctionDecl decl, + MakeFunctionDecl( + "first_elem_type", + MakeOverloadDecl( + "first_elem_type_list", TypeParamType("T"), DynType(), + TypeType(&arena, ListType(&arena, TypeParamType("T")))))); + + std::optional resolution = + context.ResolveOverload(decl, {StringType(), DynType()}, false); + ASSERT_TRUE(resolution.has_value()); + // Bound to dyn rather than left free. + EXPECT_THAT(resolution->result_type, IsTypeKind(TypeKind::kDyn)); +} + +TEST(TypeInferenceContextTest, DynArgWithMultipleOverloadsKeepsCommonResult) { + google::protobuf::Arena arena; + TypeInferenceContext context(&arena); + Type optional_of_v = OptionalType(&arena, TypeParamType("V")); + ASSERT_OK_AND_ASSIGN( + FunctionDecl decl, + MakeFunctionDecl( + "_[?_]", + MakeOverloadDecl("list_optindex_optional_int", optional_of_v, + ListType(&arena, TypeParamType("V")), IntType()), + MakeOverloadDecl( + "map_optindex_optional_value", optional_of_v, + MapType(&arena, TypeParamType("K"), TypeParamType("V")), + TypeParamType("K")))); + + // Both overloads match and resolve to optional(dyn), so the result isn't + // widened to dyn. + std::optional resolution = + context.ResolveOverload(decl, {DynType(), IntType()}, false); + ASSERT_TRUE(resolution.has_value()); + EXPECT_THAT(resolution->overloads, SizeIs(2)); + EXPECT_EQ(FormatTypeName(context.FinalizeType(resolution->result_type)), + "optional_type(dyn)"); +} + +TEST(TypeInferenceContextTest, DynAssignmentOnlyRebindsTargetTypeParam) { + google::protobuf::Arena arena; + TypeInferenceContext context(&arena); + Type t0 = context.InstantiateTypeParams(TypeParamType("T0")); + Type t1 = context.InstantiateTypeParams(TypeParamType("T1")); + // T1 -> T0 -> int. + ASSERT_TRUE(context.IsAssignable(t1, t0)); + ASSERT_TRUE(context.IsAssignable(IntType(), t0)); + + EXPECT_TRUE(context.IsAssignable(DynType(), OptionalType(&arena, t1))); + + EXPECT_THAT(context.FinalizeType(t1), IsTypeKind(TypeKind::kDyn)); + EXPECT_THAT(context.FinalizeType(t0), IsTypeKind(TypeKind::kInt)); +} + +TEST(TypeInferenceContextTest, UpcastToDynPreservesBoundTypeParam) { + google::protobuf::Arena arena; + TypeInferenceContext context(&arena); + Type t0 = context.InstantiateTypeParams(TypeParamType("T0")); + ASSERT_TRUE(context.IsAssignable(IntType(), t0)); + + EXPECT_TRUE(context.IsAssignable(OptionalType(&arena, t0), DynType())); + + EXPECT_THAT(context.FinalizeType(t0), IsTypeKind(TypeKind::kInt)); +} + +TEST(TypeInferenceContextTest, DynArgPreservesTypeParamsBoundByOtherArgument) { + google::protobuf::Arena arena; + TypeInferenceContext context(&arena); + ASSERT_OK_AND_ASSIGN(FunctionDecl decl, MakeSameTypeDecl()); + Type list_of_t0 = + context.InstantiateTypeParams(ListType(&arena, TypeParamType("T0"))); + ASSERT_TRUE( + context.IsAssignable(IntType(), list_of_t0.AsList()->GetElement())); + + // same(list(T0), dyn) widens the function's type param, not T0. + std::optional resolution = + context.ResolveOverload(decl, {list_of_t0, DynType()}, false); + ASSERT_TRUE(resolution.has_value()); + EXPECT_THAT(context.FinalizeType(resolution->result_type), + IsTypeKind(TypeKind::kDyn)); + EXPECT_EQ(FormatTypeName(context.FinalizeType(list_of_t0)), "list(int)"); +} + +TEST(TypeInferenceContextTest, ErrorArgLeavesTypeParamsFree) { + google::protobuf::Arena arena; + TypeInferenceContext context(&arena); + Type t0 = context.InstantiateTypeParams(TypeParamType("T0")); + + EXPECT_TRUE(context.IsAssignable(ErrorType(), OptionalType(&arena, t0))); + + EXPECT_THAT(context.FullySubstitute(t0), IsTypeKind(TypeKind::kTypeParam)); +} + +// Unlike cel-java, a free type param of an argument is bound to the overload's +// type param, so it is widened to dyn along with it. +TEST(TypeInferenceContextTest, DynArgBindsFreeTypeParamUnifiedWithParam) { + google::protobuf::Arena arena; + TypeInferenceContext context(&arena); + Type list_of_a = ListType(&arena, TypeParamType("A")); + ASSERT_OK_AND_ASSIGN( + FunctionDecl decl, + MakeFunctionDecl("_+_", MakeOverloadDecl("add_list", list_of_a, list_of_a, + list_of_a))); + Type list_of_t0 = + context.InstantiateTypeParams(ListType(&arena, TypeParamType("T0"))); + + std::optional resolution = + context.ResolveOverload(decl, {list_of_t0, DynType()}, false); + ASSERT_TRUE(resolution.has_value()); + EXPECT_EQ(FormatTypeName(context.FinalizeType(resolution->result_type)), + "list(dyn)"); + + EXPECT_THAT(context.FullySubstitute(list_of_t0), + IsListType(IsTypeKind(TypeKind::kDyn))); +} + } // namespace } // namespace cel::checker_internal diff --git a/conformance/BUILD b/conformance/BUILD index 7db97361f..7c67c1a2a 100644 --- a/conformance/BUILD +++ b/conformance/BUILD @@ -183,18 +183,6 @@ _TESTS_TO_SKIP = [ # Skip until fixed. "fields/qualified_identifier_resolution/map_value_repeat_key_heterogeneous", - # TODO(b/519683720): Fix dyn type-parameter unification and asymmetric dyn joins in cel-cpp checker. - "optionals/optionals/dyn_optional_nested_or_value_index", - "optionals/optionals/dyn_optional_or_value_optindex", - "optionals/optionals/dyn_optional_or_value_size", - "type_deductions/any/any_list_mixed_dyn_reverse", - "type_deductions/any/any_list_mixed_int", - "type_deductions/any/any_list_mixed_int_reverse", - "type_deductions/any/any_optional_or_value", - "type_deductions/any/any_ternary_mixed_int", - "type_deductions/any/any_ternary_mixed_int_reverse", - "type_deductions/dyn_type_parameter_unification", - # Skip until duration/timestamp range and proto wrapper validation is updated for spec parity. "timestamps/timestamp_arithmetic/add_duration_to_duration_max", "timestamps/timestamp_arithmetic/subtract_duration_from_duration_min", @@ -252,6 +240,15 @@ _TESTS_TO_SKIP_MODERN_DASHBOARD = [ _TESTS_TO_SKIP_LEGACY = _TESTS_TO_SKIP + [ # Legacy value does not support optional_type. "optionals/optionals", + # These use the optional index syntax or the optMap / optFlatMap macros, which aren't enabled + # for the legacy conformance service. + "type_deductions/dyn_type_parameter_unification/dyn_optional_nested_optflatmap_or_value", + "type_deductions/dyn_type_parameter_unification/dyn_optional_none_optmap_or_value", + "type_deductions/dyn_type_parameter_unification/dyn_optional_of_optflatmap_or_value", + "type_deductions/dyn_type_parameter_unification/dyn_optional_of_optmap_or_value", + "type_deductions/dyn_type_parameter_unification/dyn_optional_or_value_optindex", + "type_deductions/dyn_type_parameter_unification/optional_none_optflatmap_or_value", + "type_deductions/dyn_type_parameter_unification/optional_none_optmap_or_value", # TODO(uncreated-issue/81): Fix null assignment to a field "proto2/set_null/list_value",