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
138 changes: 74 additions & 64 deletions pyrefly/lib/solver/subset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -591,7 +591,8 @@ impl<'solver, 'subset, Ans: LookupAnswer> Subset<'solver, 'subset, Ans> {
_ => return Err(lists.error_at(l_arg, u_arg, SubsetError::Other)),
}
}
// We can use a HashMap for `l_keywords` since the order does not matter
// `l_keywords` is a `HashMap` because entries are removed one at a time as they are
// matched, and a TypedDict may expand into thousands of keyword parameters.
let mut l_keywords = HashMap::new();
let mut l_kwargs_param = None;
for arg in Option::into_iter(l_arg).chain(l_args) {
Expand Down Expand Up @@ -620,82 +621,64 @@ impl<'solver, 'subset, Ans: LookupAnswer> Subset<'solver, 'subset, Ans> {
_ => (),
}
}
let object_type = self
.solver
.heap
.mk_class_type(self.type_order.stdlib().object().clone());
// Expand typed dict kwargs if necessary, check regular kwargs
// `UnpackKind::Kwargs` is produced only for a `**kwargs: Unpack[TD]` annotation, and
// `validate_type_form` has already rejected any inner type that is not a TypedDict, so
// these arms do not need to consult class metadata to recognize one.
// Keyword parameters expanded from a TypedDict are attributed to its `**kwargs`.
let l_kwargs = match (l_kwargs_param, u_kwargs_param) {
// `l_kwargs` and `u_kwargs` are the types of the extra keyword arguments that each side
// accepts, or `None` if it accepts none.
let (l_kwargs, u_kwargs) = match (l_kwargs_param, u_kwargs_param) {
(
Some(Param::Kwargs(_, l @ Type::Var(_))),
Some(Param::Kwargs(_, u @ Type::Unpack(_, UnpackKind::Kwargs))),
) if l_keywords.is_empty() => {
self.is_subset_eq(u, l)
.map_err(|e| lists.error_at(l_kwargs_param, u_kwargs_param, e))?;
Some(object_type)
}
(
Some(l_param @ Param::Kwargs(_, Type::Unpack(l_inner, UnpackKind::Kwargs))),
Some(u_param @ Param::Kwargs(_, Type::Unpack(u_inner, UnpackKind::Kwargs))),
) if let (Type::ClassType(l_typed_dict), Type::ClassType(u_typed_dict)) =
(&**l_inner, &**u_inner) =>
{
for (name, ty, required) in self.type_order.typed_dict_kw_param_info(l_typed_dict) {
l_keywords.insert(name, (ty, required == Required::Required, l_param));
}
for (name, ty, required) in self.type_order.typed_dict_kw_param_info(u_typed_dict) {
u_keywords.insert(name, (ty, required == Required::Required, u_param));
}
Some(object_type)
}
(Some(l_param @ Param::Kwargs(_, Type::Unpack(l_inner, UnpackKind::Kwargs))), _)
if let Type::ClassType(l_typed_dict) = &**l_inner =>
{
for (name, ty, required) in self.type_order.typed_dict_kw_param_info(l_typed_dict) {
l_keywords.insert(name, (ty, required == Required::Required, l_param));
}
Some(object_type)
}
(
l_kwargs_param,
Some(u_param @ Param::Kwargs(_, Type::Unpack(u_inner, UnpackKind::Kwargs))),
) if let Type::ClassType(u_typed_dict) = &**u_inner => {
// Allow expanding Unpack[TypedDict] kwargs against explicit keyword params
// only when the other side also has **kwargs or the TypedDict is closed.
if l_kwargs_param.is_none()
&& !matches!(
self.type_order.typed_dict_extra_items(u_typed_dict),
ExtraItems::Closed
)
{
return Err(lists.error_at(
None,
Some(u_param),
SubsetError::OpenTypedDictKwargs(
u_typed_dict.name(&self.type_order).clone(),
),
));
}
for (name, ty, required) in self.type_order.typed_dict_kw_param_info(u_typed_dict) {
u_keywords.insert(name, (ty, required == Required::Required, u_param));
}
l_kwargs_param.map(|l_param| l_param.as_type().clone())
}
(Some(l_param), Some(u_param)) => {
self.is_subset_eq(u_param.as_type(), l_param.as_type())
.map_err(|e| lists.error_at(l_kwargs_param, u_kwargs_param, e))?;
Some(l_param.as_type().clone())
let object_type = self
.solver
.heap
.mk_class_type(self.type_order.stdlib().object().clone());
(Some(object_type), None)
}
_ => {
// Keyword parameters expanded from a TypedDict are attributed to its `**kwargs`.
let l_kwargs = l_kwargs_param.and_then(|l_param| {
let (keywords, extra) = self.split_kwargs(l_param.as_type());
for (name, ty, required) in keywords {
l_keywords.insert(name, (ty, required == Required::Required, l_param));
}
extra
});
let u_kwargs = u_kwargs_param.and_then(|u_param| {
let (keywords, extra) = self.split_kwargs(u_param.as_type());
for (name, ty, required) in keywords {
u_keywords.insert(name, (ty, required == Required::Required, u_param));
}
extra
});
(l_kwargs, u_kwargs)
}
};
match (&l_kwargs, &u_kwargs) {
(Some(l_ty), Some(u_ty)) => self
.is_subset_eq(u_ty, l_ty)
.map_err(|e| lists.error_at(l_kwargs_param, u_kwargs_param, e))?,
// The gradual `**kwargs` of `u` stands for any remaining keyword parameters of `l`.
(None, Some(_)) if !u_gradual => {
return Err(lists.error_at(None, u_kwargs_param, SubsetError::Other));
let error = match u_kwargs_param {
Some(Param::Kwargs(_, Type::Unpack(u_inner, UnpackKind::Kwargs)))
if l_kwargs_param.is_none()
&& let Type::ClassType(u_typed_dict) = &**u_inner =>
{
SubsetError::OpenTypedDictKwargs(
u_typed_dict.name(&self.type_order).clone(),
)
}
_ => SubsetError::Other,
};
return Err(lists.error_at(l_kwargs_param, u_kwargs_param, error));
}
(l_kwargs_param, _) => l_kwargs_param.map(|l_param| l_param.as_type().clone()),
};
_ => {}
}
// These parameters from `u` may be passed by name or position. We matched the positional
// case with *args from `l` already; now we check that they can be passed by name.
for (name, u_ty, u_param) in u_param_matched_with_l_varargs {
Expand Down Expand Up @@ -739,9 +722,36 @@ impl<'solver, 'subset, Ans: LookupAnswer> Subset<'solver, 'subset, Ans> {
{
return Err(error);
}
// `u` may pass an extra keyword argument to any keyword parameter of `l` that it does not
// declare itself. Sorting by name keeps the reported error independent of `HashMap`
// iteration order.
if let Some(u_ty) = &u_kwargs {
for (_, (l_ty, _, l_param)) in l_keywords.iter().sorted_by_key(|(name, _)| *name) {
self.is_subset_eq(u_ty, l_ty)
.map_err(|e| lists.error_at(Some(l_param), u_kwargs_param, e))?;
}
}
Ok(())
}

/// Splits the type of a `**kwargs` parameter into the keyword parameters expanded from an
/// `Unpack[TypedDict]` annotation and the type of the remaining keyword arguments it accepts,
/// which is `None` for a closed TypedDict.
fn split_kwargs(&self, kwargs: &Type) -> (Vec<(Name, Type, Required)>, Option<Type>) {
match kwargs {
Type::Unpack(inner, UnpackKind::Kwargs)
if let Type::ClassType(typed_dict) = &**inner =>
{
let extra = match self.type_order.typed_dict_extra_items(typed_dict) {
ExtraItems::Closed => None,
extra => Some(extra.extra_item(self.type_order.stdlib()).ty),
};
(self.type_order.typed_dict_kw_param_info(typed_dict), extra)
}
_ => (Vec::new(), Some(kwargs.clone())),
}
}

/// `l_gradual` and `u_gradual` say whether `l_params` and `u_params` have a gradual tail; see
/// `params_have_gradual_tail`.
fn is_subset_params(
Expand Down
64 changes: 55 additions & 9 deletions pyrefly/lib/test/callable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1157,11 +1157,56 @@ class P4(Protocol):
def __call__(self, **kwargs: int): ...
def test(unannotated: P1, unpacked: P2, annotated: P3, annotated_wrong: P4):
a: P2 = unannotated
b: P2 = annotated
# `TD` is not closed, so `P2` may be called with extra keyword arguments of type `object`.
b: P2 = annotated # E: `P3` is not assignable to `P2`
c: P2 = annotated_wrong # E: `P4` is not assignable to `P2`
"#,
);

// https://github.com/python/typing/pull/2338#issuecomment-5395279191
testcase!(
test_override_unpack_kwargs_with_extra_keyword,
r#"
from typing import TypedDict, Unpack

class Person(TypedDict):
name: str
age: int

class Base:
def foo(self, **kwargs: Unpack[Person]) -> None: ...
class SubGood(Base):
# `Person` is not closed, so `Base.foo` accepts `extra` with any type.
def foo(self, *, name: str, age: int, extra: bool = False) -> None: ... # E: `SubGood.foo` overrides parent class `Base` in an inconsistent manner
"#,
);

// https://github.com/python/typing/pull/2338#issuecomment-5395279191
// A non-closed TypedDict in `Unpack` behaves as if it had `extra_items=object`.
testcase!(
test_assignability_unpack_kwargs_open_typed_dict_extra_items,
r#"
from typing import Protocol, TypedDict, Unpack

class TDBase(TypedDict):
x: int

class TD(TDBase, total=False):
y: int

def a1(**kwargs: Unpack[TDBase]) -> None: ...
def a2(**kwargs: Unpack[TD]) -> None: ...

class P1(Protocol):
def __call__(self, **kwargs: Unpack[TDBase]) -> None: ...
class P2(Protocol):
def __call__(self, **kwargs: Unpack[TD]) -> None: ...

x1: P1 = a2 # E: `(**kwargs: Unpack[TD]) -> None` is not assignable to `P1`
x2: P2 = a1
"#,
);

testcase!(
test_assignability_typed_dict_wrong_kwarg,
r#"
Expand Down Expand Up @@ -2327,9 +2372,9 @@ callback: Callback = lambda **kwargs: (
)[3]
split_callback: SplitCallback = lambda consumed, **kwargs: (
assert_type(consumed, int),
assert_type(kwargs, dict[str, str]),
assert_type(kwargs["remaining"], str),
assert_type(kwargs["consumed"], str),
assert_type(kwargs, dict[str, object]),
assert_type(kwargs["remaining"], object),
assert_type(kwargs["consumed"], object),
None,
)[4]
generic_callback: GenericCallback = generic
Expand All @@ -2341,13 +2386,14 @@ apply(source, lambda **kwargs: (
)[3])
apply(split_source, lambda consumed, **kwargs: (
assert_type(consumed, int),
assert_type(kwargs, dict[str, str]),
assert_type(kwargs["remaining"], str),
assert_type(kwargs["consumed"], str),
assert_type(kwargs, dict[str, object]),
assert_type(kwargs["remaining"], object),
assert_type(kwargs["consumed"], object),
None,
)[4])
plain_callback: SplitCallback = split_plain
apply(split_source, split_plain)
# `SplitOptions` is not closed, so its extra items of type `object` are not assignable to `str`.
plain_callback: SplitCallback = split_plain # E: is not assignable to `SplitCallback`
apply(split_source, split_plain) # E: is not assignable to parameter `g`
"#,
);

Expand Down
Loading