Skip to content

Commit a8cc55b

Browse files
committed
[ty] Use C[T] instead of C[Unknown] for the upper bound of Self
1 parent 48ada2d commit a8cc55b

File tree

6 files changed

+186
-12
lines changed

6 files changed

+186
-12
lines changed

crates/ty_python_semantic/resources/mdtest/generics/legacy/functions.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -366,6 +366,31 @@ reveal_type(f(g("a"))) # revealed: tuple[Literal["a"] | None, int]
366366
reveal_type(g(f("a"))) # revealed: tuple[Literal["a"], int] | None
367367
```
368368

369+
## Passing generic functions to generics functions
370+
371+
```py
372+
from typing import Callable, TypeVar
373+
374+
A = TypeVar("A")
375+
B = TypeVar("B")
376+
T = TypeVar("T")
377+
378+
def invoke(fn: Callable[[A], B], value: A) -> B:
379+
return fn(value)
380+
381+
def identity(x: T) -> T:
382+
return x
383+
384+
def head(xs: list[T]) -> T:
385+
return xs[0]
386+
387+
# TODO: this should be `Literal[1]`
388+
reveal_type(invoke(identity, 1)) # revealed: Unknown
389+
390+
# TODO: this should be `Unknown | int`
391+
reveal_type(invoke(head, [1, 2, 3])) # revealed: Unknown
392+
```
393+
369394
## Opaque decorators don't affect typevar binding
370395

371396
Inside the body of a generic function, we should be able to see that the typevars bound by that

crates/ty_python_semantic/resources/mdtest/generics/pep695/functions.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,27 @@ reveal_type(f(g("a"))) # revealed: tuple[Literal["a"] | None, int]
323323
reveal_type(g(f("a"))) # revealed: tuple[Literal["a"], int] | None
324324
```
325325

326+
## Passing generic functions to generics functions
327+
328+
```py
329+
from typing import Callable
330+
331+
def invoke[A, B](fn: Callable[[A], B], value: A) -> B:
332+
return fn(value)
333+
334+
def identity[T](x: T) -> T:
335+
return x
336+
337+
def head[T](xs: list[T]) -> T:
338+
return xs[0]
339+
340+
# TODO: this should be `Literal[1]`
341+
reveal_type(invoke(identity, 1)) # revealed: Unknown
342+
343+
# TODO: this should be `Unknown | int`
344+
reveal_type(invoke(head, [1, 2, 3])) # revealed: Unknown
345+
```
346+
326347
## Protocols as TypeVar bounds
327348

328349
Protocol types can be used as TypeVar bounds, just like nominal types.

crates/ty_python_semantic/resources/mdtest/narrow/isinstance.md

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -321,8 +321,10 @@ a covariant generic, this is equivalent to using the upper bound of the type par
321321
`object`):
322322

323323
```py
324+
from typing import Self
325+
324326
class Covariant[T]:
325-
def get(self) -> T:
327+
def get(self: Self) -> T:
326328
raise NotImplementedError
327329

328330
def _(x: object):
@@ -335,11 +337,12 @@ Similarly, contravariant type parameters use their lower bound of `Never`:
335337

336338
```py
337339
class Contravariant[T]:
338-
def push(self, x: T) -> None: ...
340+
def push(self: Self, x: T) -> None: ...
339341

340342
def _(x: object):
341343
if isinstance(x, Contravariant):
342344
reveal_type(x) # revealed: Contravariant[Never]
345+
# error: [invalid-argument-type] "Argument to bound method `push` is incorrect: Argument type `Contravariant[Never]` does not satisfy upper bound `Contravariant[T@Contravariant]` of type variable `Self`"
343346
# error: [invalid-argument-type] "Argument to bound method `push` is incorrect: Expected `Never`, found `Literal[42]`"
344347
x.push(42)
345348
```
@@ -350,8 +353,8 @@ the type system, so we represent it with the internal `Top[]` special form.
350353

351354
```py
352355
class Invariant[T]:
353-
def push(self, x: T) -> None: ...
354-
def get(self) -> T:
356+
def push(self: Self, x: T) -> None: ...
357+
def get(self: Self) -> T:
355358
raise NotImplementedError
356359

357360
def _(x: object):

crates/ty_python_semantic/src/types.rs

Lines changed: 115 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1631,6 +1631,31 @@ impl<'db> Type<'db> {
16311631
// be specialized to `Never`.)
16321632
(_, Type::NonInferableTypeVar(_)) => ConstraintSet::from(false),
16331633

1634+
(Type::TypeVar(_), _) if relation.is_assignability() => {
1635+
// The implicit lower bound of a typevar is `Never`, which means
1636+
// that it is always assignable to any other type.
1637+
1638+
// TODO: record the unification constraints
1639+
1640+
ConstraintSet::from(true)
1641+
}
1642+
1643+
(_, Type::TypeVar(typevar))
1644+
if relation.is_assignability()
1645+
&& typevar.typevar(db).upper_bound(db).is_none_or(|bound| {
1646+
!self
1647+
.has_relation_to_impl(db, bound, relation, visitor)
1648+
.is_never_satisfied()
1649+
}) =>
1650+
{
1651+
// TODO: record the unification constraints
1652+
1653+
typevar
1654+
.typevar(db)
1655+
.upper_bound(db)
1656+
.when_none_or(|bound| self.has_relation_to_impl(db, bound, relation, visitor))
1657+
}
1658+
16341659
// TODO: Infer specializations here
16351660
(Type::TypeVar(_), _) | (_, Type::TypeVar(_)) => ConstraintSet::from(false),
16361661

@@ -5661,13 +5686,25 @@ impl<'db> Type<'db> {
56615686
],
56625687
});
56635688
};
5664-
let instance = Type::instance(db, class.unknown_specialization(db));
5689+
5690+
let upper_bound = Type::instance(
5691+
db,
5692+
class.apply_specialization(db, |generic_context| {
5693+
let types = generic_context
5694+
.variables(db)
5695+
.iter()
5696+
.map(|typevar| Type::NonInferableTypeVar(*typevar));
5697+
5698+
generic_context.specialize(db, types.collect())
5699+
}),
5700+
);
5701+
56655702
let class_definition = class.definition(db);
56665703
let typevar = TypeVarInstance::new(
56675704
db,
56685705
ast::name::Name::new_static("Self"),
56695706
Some(class_definition),
5670-
Some(TypeVarBoundOrConstraints::UpperBound(instance).into()),
5707+
Some(TypeVarBoundOrConstraints::UpperBound(upper_bound).into()),
56715708
// According to the [spec], we can consider `Self`
56725709
// equivalent to an invariant type variable
56735710
// [spec]: https://typing.python.org/en/latest/spec/generics.html#self
@@ -6009,8 +6046,8 @@ impl<'db> Type<'db> {
60096046
partial.get(db, bound_typevar).unwrap_or(self)
60106047
}
60116048
TypeMapping::MarkTypeVarsInferable(binding_context) => {
6012-
if bound_typevar.binding_context(db) == *binding_context {
6013-
Type::TypeVar(bound_typevar)
6049+
if binding_context.is_none_or(|context| context == bound_typevar.binding_context(db)) {
6050+
Type::TypeVar(bound_typevar.mark_typevars_inferable(db, visitor))
60146051
} else {
60156052
self
60166053
}
@@ -6694,8 +6731,9 @@ pub enum TypeMapping<'a, 'db> {
66946731
BindSelf(Type<'db>),
66956732
/// Replaces occurrences of `typing.Self` with a new `Self` type variable with the given upper bound.
66966733
ReplaceSelf { new_upper_bound: Type<'db> },
6697-
/// Marks the typevars that are bound by a generic class or function as inferable.
6698-
MarkTypeVarsInferable(BindingContext<'db>),
6734+
/// Marks the typevars that are bound by a generic class or function as inferable. If the parameter
6735+
/// is `None`, *all* typevars are marked as inferable.
6736+
MarkTypeVarsInferable(Option<BindingContext<'db>>),
66996737
/// Create the top or bottom materialization of a type.
67006738
Materialize(MaterializationKind),
67016739
}
@@ -7636,6 +7674,40 @@ impl<'db> TypeVarInstance<'db> {
76367674
)
76377675
}
76387676

7677+
fn mark_typevars_inferable(
7678+
self,
7679+
db: &'db dyn Db,
7680+
visitor: &ApplyTypeMappingVisitor<'db>,
7681+
) -> Self {
7682+
let type_mapping = &TypeMapping::MarkTypeVarsInferable(None);
7683+
7684+
Self::new(
7685+
db,
7686+
self.name(db),
7687+
self.definition(db),
7688+
self._bound_or_constraints(db)
7689+
.map(|bound_or_constraints| match bound_or_constraints {
7690+
TypeVarBoundOrConstraintsEvaluation::Eager(bound_or_constraints) => {
7691+
bound_or_constraints
7692+
.mark_typevars_inferable(db, visitor)
7693+
.into()
7694+
}
7695+
TypeVarBoundOrConstraintsEvaluation::LazyUpperBound
7696+
| TypeVarBoundOrConstraintsEvaluation::LazyConstraints => bound_or_constraints,
7697+
}),
7698+
self.explicit_variance(db),
7699+
self._default(db).and_then(|default| match default {
7700+
TypeVarDefaultEvaluation::Eager(ty) => {
7701+
Some(ty.apply_type_mapping_impl(db, type_mapping, visitor).into())
7702+
}
7703+
TypeVarDefaultEvaluation::Lazy => self
7704+
.lazy_default(db)
7705+
.map(|ty| ty.apply_type_mapping_impl(db, type_mapping, visitor).into()),
7706+
}),
7707+
self.kind(db),
7708+
)
7709+
}
7710+
76397711
fn to_instance(self, db: &'db dyn Db) -> Option<Self> {
76407712
let bound_or_constraints = match self.bound_or_constraints(db)? {
76417713
TypeVarBoundOrConstraints::UpperBound(upper_bound) => {
@@ -7866,6 +7938,18 @@ impl<'db> BoundTypeVarInstance<'db> {
78667938
)
78677939
}
78687940

7941+
fn mark_typevars_inferable(
7942+
self,
7943+
db: &'db dyn Db,
7944+
visitor: &ApplyTypeMappingVisitor<'db>,
7945+
) -> Self {
7946+
Self::new(
7947+
db,
7948+
self.typevar(db).mark_typevars_inferable(db, visitor),
7949+
self.binding_context(db),
7950+
)
7951+
}
7952+
78697953
fn to_instance(self, db: &'db dyn Db) -> Option<Self> {
78707954
Some(Self::new(
78717955
db,
@@ -7971,6 +8055,31 @@ impl<'db> TypeVarBoundOrConstraints<'db> {
79718055
}
79728056
}
79738057
}
8058+
8059+
fn mark_typevars_inferable<'a>(
8060+
self,
8061+
db: &'db dyn Db,
8062+
visitor: &ApplyTypeMappingVisitor<'db>,
8063+
) -> Self {
8064+
let type_mapping = &TypeMapping::MarkTypeVarsInferable(None);
8065+
8066+
match self {
8067+
TypeVarBoundOrConstraints::UpperBound(bound) => TypeVarBoundOrConstraints::UpperBound(
8068+
bound.apply_type_mapping_impl(db, type_mapping, visitor),
8069+
),
8070+
TypeVarBoundOrConstraints::Constraints(constraints) => {
8071+
TypeVarBoundOrConstraints::Constraints(UnionType::new(
8072+
db,
8073+
constraints
8074+
.elements(db)
8075+
.iter()
8076+
.map(|ty| ty.apply_type_mapping_impl(db, type_mapping, visitor))
8077+
.collect::<Vec<_>>()
8078+
.into_boxed_slice(),
8079+
))
8080+
}
8081+
}
8082+
}
79748083
}
79758084

79768085
/// Error returned if a type is not awaitable.

crates/ty_python_semantic/src/types/generics.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -491,6 +491,18 @@ fn is_subtype_in_invariant_position<'db>(
491491
let base_bottom = base_type.bottom_materialization(db);
492492

493493
let is_subtype_of = |derived: Type<'db>, base: Type<'db>| {
494+
// TODO:
495+
// This should be removed and properly handled in the respective
496+
// `(Type::TypeVar(_), _) | (_, Type::TypeVar(_))` branch of
497+
// `Type::has_relation_to_impl`. Right now, we can not generally
498+
// return `ConstraintSet::from(true)` from that branch, as that
499+
// leads to union simplification, which means that we lose track
500+
// of type variables without recording the constraints under which
501+
// the relation holds.
502+
if matches!(base, Type::TypeVar(_)) || matches!(derived, Type::TypeVar(_)) {
503+
return ConstraintSet::from(true);
504+
}
505+
494506
derived.has_relation_to_impl(db, base, TypeRelation::Subtyping, visitor)
495507
};
496508
match (derived_materialization, base_materialization) {

crates/ty_python_semantic/src/types/signatures.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -367,7 +367,9 @@ impl<'db> Signature<'db> {
367367
let plain_return_ty = definition_expression_type(db, definition, returns.as_ref())
368368
.apply_type_mapping(
369369
db,
370-
&TypeMapping::MarkTypeVarsInferable(BindingContext::Definition(definition)),
370+
&TypeMapping::MarkTypeVarsInferable(Some(BindingContext::Definition(
371+
definition,
372+
))),
371373
);
372374
if function_node.is_async && !is_generator {
373375
KnownClass::CoroutineType
@@ -1549,7 +1551,9 @@ impl<'db> Parameter<'db> {
15491551
annotated_type: parameter.annotation().map(|annotation| {
15501552
definition_expression_type(db, definition, annotation).apply_type_mapping(
15511553
db,
1552-
&TypeMapping::MarkTypeVarsInferable(BindingContext::Definition(definition)),
1554+
&TypeMapping::MarkTypeVarsInferable(Some(BindingContext::Definition(
1555+
definition,
1556+
))),
15531557
)
15541558
}),
15551559
kind,

0 commit comments

Comments
 (0)