Skip to content
Open
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
67 changes: 63 additions & 4 deletions checker/internal/type_checker_impl_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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<AstType>(DynTypeSpec()),
std::make_unique<AstType>(DynTypeSpec())))},
CheckedExprTestCase{.expr = "false ? {dyn(1): 1} : {'b': dyn('c')}",
.expected_result_type = AstType(MapTypeSpec(
std::make_unique<AstType>(DynTypeSpec()),
std::make_unique<AstType>(DynTypeSpec())))},
CheckedExprTestCase{
.expr = "[test_msg.single_any, test_msg.single_any]",
.expected_result_type = AstType(ListTypeSpec(
std::make_unique<AstType>(WellKnownTypeSpec::kAny)))},
CheckedExprTestCase{.expr = "[test_msg.single_any, 1]",
.expected_result_type = AstType(ListTypeSpec(
std::make_unique<AstType>(DynTypeSpec())))},
CheckedExprTestCase{.expr = "[1, test_msg.single_any]",
.expected_result_type = AstType(ListTypeSpec(
std::make_unique<AstType>(DynTypeSpec())))},
CheckedExprTestCase{.expr = "[dyn(1), test_msg.single_any]",
.expected_result_type = AstType(ListTypeSpec(
std::make_unique<AstType>(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<AstType>(DynTypeSpec())))},
CheckedExprTestCase{.expr = "dyn([1]) + ['a']",
.expected_result_type = AstType(ListTypeSpec(
std::make_unique<AstType>(DynTypeSpec())))},
CheckedExprTestCase{.expr = "[test_msg.single_int64_wrapper, 1, null]",
.expected_result_type = AstType(ListTypeSpec(
std::make_unique<AstType>(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<AstType>(PrimitiveType::kString),
std::make_unique<AstType>(DynTypeSpec())))},
ListTypeSpec(std::make_unique<AstType>(DynTypeSpec())))},
CheckedExprTestCase{
.expr = "[{'k': 1}, {dyn('k'): 1}][0]",
.expected_result_type = AstType(
Expand All @@ -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<AstType>(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<AstType>(MessageTypeSpec(
"cel.expr.conformance.proto3.TestAllTypes"))))},
CheckedExprTestCase{
.expr = "false ? [test_msg] : [null]",
.expected_result_type =
AstType(ListTypeSpec(std::make_unique<AstType>(MessageTypeSpec(
"cel.expr.conformance.proto3.TestAllTypes"))))},
CheckedExprTestCase{
.expr = "test_msg.single_int64",
.expected_result_type = AstType(PrimitiveType::kInt64),
Expand Down
89 changes: 76 additions & 13 deletions checker/internal/type_inference_context.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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<absl::string_view, Type>& 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
Expand Down Expand Up @@ -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<Type> joined =
JoinTypeTypes(from_subs, to_subs, join_subs);
if (std::optional<Type> 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);
Expand Down Expand Up @@ -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;
}

Expand Down Expand Up @@ -450,11 +478,35 @@ Type TypeInferenceContext::Substitute(
return subs;
}

std::optional<Type> TypeInferenceContext::JoinTypeTypes(
std::optional<Type> 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(),
Expand All @@ -479,13 +531,18 @@ std::optional<Type> TypeInferenceContext::JoinTypeTypes(
joined.reserve(to_params.size());
for (size_t i = 0; i < to_params.size(); ++i) {
std::optional<Type> 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;
}
Expand Down Expand Up @@ -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();
}
}
Expand Down
28 changes: 19 additions & 9 deletions checker/internal/type_inference_context.h
Original file line number Diff line number Diff line change
Expand Up @@ -231,17 +231,27 @@ class TypeInferenceContext {
const Type& type,
absl::FunctionRef<Type(absl::string_view)> 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<Type> 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<Type> JoinTypes(const Type& from, const Type& to,
SubstitutionMap& prospective_substitutions);

bool OccursWithin(absl::string_view var_name, const Type& type,
const SubstitutionMap& substitutions) const;
Expand Down
Loading
Loading