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
10 changes: 10 additions & 0 deletions crates/pyrefly_types/src/stdlib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ pub struct Stdlib {
dict_keys: StdlibResult<(Class, Arc<TParams>)>,
dict_values: StdlibResult<(Class, Arc<TParams>)>,
mapping: StdlibResult<(Class, Arc<TParams>)>,
supports_keys_and_get_item: StdlibResult<(Class, Arc<TParams>)>,
set: StdlibResult<(Class, Arc<TParams>)>,
tuple: StdlibResult<(Class, Arc<TParams>)>,
enumerate: StdlibResult<(Class, Arc<TParams>)>,
Expand Down Expand Up @@ -281,6 +282,11 @@ impl Stdlib {
method_type: lookup_concrete(types, "MethodType"),
module_type: lookup_concrete(types, "ModuleType"),
mapping: lookup_generic(typing, "Mapping", 2),
supports_keys_and_get_item: lookup_generic(
ModuleName::from_str("_typeshed"),
"SupportsKeysAndGetItem",
2,
),
enum_meta: lookup_concrete(enum_, "EnumMeta"),
protocol_meta: lookup_concrete(typing, "_ProtocolMeta"),
enum_flag: lookup_concrete(enum_, "Flag"),
Expand Down Expand Up @@ -526,6 +532,10 @@ impl Stdlib {
&Self::unwrap(&self.mapping).0
}

pub fn supports_keys_and_get_item(&self, key: Type, value: Type) -> ClassType {
Self::apply(&self.supports_keys_and_get_item, vec![key, value])
}

pub fn set(&self, x: Type) -> ClassType {
Self::apply(&self.set, vec![x])
}
Expand Down
2 changes: 1 addition & 1 deletion pyrefly/lib/alt/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1982,7 +1982,7 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> {
value_tys.push(field.ty.clone());
}
}
} else if let Some((key_t, value_t)) = self.unwrap_mapping(&ty) {
} else if let Some((key_t, value_t)) = self.unwrap_mapping_for_unpacking(&ty) {
// Non-anonymous-typed-dict unpacking disables anonymous typed dict creation
can_create_anonymous_typed_dict = false;
if !key_t.is_error() {
Expand Down
17 changes: 17 additions & 0 deletions pyrefly/lib/alt/unwrap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,23 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> {
}
}

/// Extract key and value types for dictionary unpacking, including structural mappings.
pub fn unwrap_mapping_for_unpacking(&self, ty: &Type) -> Option<(Type, Type)> {
self.unwrap_mapping(ty).or_else(|| {
let key = self.fresh_var();
let value = self.fresh_var();
let mapping_type = self.heap.mk_class_type(
self.stdlib
.supports_keys_and_get_item(key.to_type(self.heap), value.to_type(self.heap)),
);
if self.is_subset_eq(ty, &mapping_type) {
Some((self.resolve_var(ty, key), self.resolve_var(ty, value)))
} else {
None
}
})
}

/// Warning: this returns `Some` if the type is `Any` or a class that extends `Any`
pub fn unwrap_awaitable(&self, ty: &Type) -> Option<Type> {
let var = self.fresh_var();
Expand Down
59 changes: 59 additions & 0 deletions pyrefly/lib/test/simple.rs
Original file line number Diff line number Diff line change
Expand Up @@ -967,6 +967,65 @@ def test(m: Mapping[str, int]) -> None:
"#,
);

testcase!(
test_dict_unpack_duck_mapping,
r#"
from collections.abc import Iterable
from typing import Any, assert_type

class DuckMapping:
def keys(self) -> Iterable[str]:
return ["a", "b"]

def __getitem__(self, key: str) -> Any:
return {"a": 1, "b": 2}[key]

assert_type({**DuckMapping()}, dict[str, Any])
assert_type({"x": 1, **DuckMapping()}, dict[str, int | Any])

class GenericMapping[K, V]:
def keys(self) -> Iterable[K]: ...
def __getitem__(self, key: K) -> V: ...

def test(mapping: GenericMapping[str, int], union: GenericMapping[str, int] | dict[str, str]):
assert_type({**mapping}, dict[str, int])
assert_type({"x": 1, **mapping}, dict[str, int])
assert_type({**union}, dict[str, int | str])
widened: dict[str, int | str] = {**mapping}
wrong_key: dict[int, int] = {**mapping} # E: `dict[str, int]` is not assignable to `dict[int, int]`
wrong_value: dict[str, str] = {**mapping} # E: `dict[str, int]` is not assignable to `dict[str, str]`

def test_non_string_keys(mapping: GenericMapping[int, str]):
assert_type({**mapping}, dict[int, str])
"#,
);

testcase!(
test_dict_unpack_invalid_duck_mapping,
r#"
from collections.abc import Iterable

class MissingKeys:
def __getitem__(self, key: str) -> int: ...

class MissingGetItem:
def keys(self) -> Iterable[str]: ...

class NonIterableKeys:
def keys(self) -> int: ...
def __getitem__(self, key: str) -> int: ...

class IncompatibleKey:
def keys(self) -> Iterable[str]: ...
def __getitem__(self, key: int) -> int: ...

{**MissingKeys()} # E: Expected a mapping, got MissingKeys
{**MissingGetItem()} # E: Expected a mapping, got MissingGetItem
{**NonIterableKeys()} # E: Expected a mapping, got NonIterableKeys
{**IncompatibleKey()} # E: Expected a mapping, got IncompatibleKey
"#,
);

testcase!(
test_dict_unpack_subclass,
r#"
Expand Down
Loading