Skip to content
Merged
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
34 changes: 34 additions & 0 deletions crates/ty_python_semantic/resources/mdtest/protocols.md
Original file line number Diff line number Diff line change
Expand Up @@ -2292,6 +2292,40 @@ static_assert(not is_assignable_to(NStaticMethodBad, PStaticMethod)) # error: [
static_assert(not is_assignable_to(NStaticMethodGood | NStaticMethodBad, PStaticMethod)) # error: [static-assert-error]
```

## Subtyping of protocols with decorated method members

Protocol methods can be decorated with other decorators like `@contextmanager`. When matching
protocol methods to implementations, decorators should be applied consistently:

```py
from typing import Protocol
from collections.abc import Generator
from contextlib import contextmanager
from ty_extensions import static_assert, is_subtype_of, is_assignable_to

class ContextManagerProtocol(Protocol):
@contextmanager
def method(self, y: bool = False) -> Generator[None, None, None]: ...

class CorrectImpl:
@contextmanager
def method(self, y: bool = False) -> Generator[None, None, None]:
yield

class AlsoCorrect:
@contextmanager
def method(self, y: bool = True) -> Generator[None, None, None]:
yield

class MissingDecorator:
def method(self, y: bool = False) -> Generator[None, None, None]:
yield

static_assert(is_assignable_to(CorrectImpl, ContextManagerProtocol))
static_assert(is_assignable_to(AlsoCorrect, ContextManagerProtocol))
static_assert(not is_assignable_to(MissingDecorator, ContextManagerProtocol))
```

## Equivalence of protocols with method or property members

Two protocols `P1` and `P2`, both with a method member `x`, are considered equivalent if the
Expand Down
34 changes: 25 additions & 9 deletions crates/ty_python_semantic/src/types/infer/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9392,15 +9392,31 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
}
}

let propagatable_kind = decorated_ty
.try_upcast_to_callable(self.db())
.and_then(CallableTypes::exactly_one)
.and_then(|callable| match callable.kind(self.db()) {
kind @ (CallableTypeKind::FunctionLike
| CallableTypeKind::StaticMethodLike
| CallableTypeKind::ClassMethodLike) => Some(kind),
_ => None,
});
// For FunctionLiteral, get the kind directly without computing the full signature.
// This avoids a query cycle when the function has default parameter values, since
// computing the signature requires evaluating those defaults which may trigger
// deferred inference.
let propagatable_kind = match decorated_ty {
Type::FunctionLiteral(func) => {
let db = self.db();
if func.is_classmethod(db) {
Some(CallableTypeKind::ClassMethodLike)
} else if func.is_staticmethod(db) {
Some(CallableTypeKind::StaticMethodLike)
} else {
Some(CallableTypeKind::FunctionLike)
}
}
_ => decorated_ty
.try_upcast_to_callable(self.db())
.and_then(CallableTypes::exactly_one)
.and_then(|callable| match callable.kind(self.db()) {
kind @ (CallableTypeKind::FunctionLike
| CallableTypeKind::StaticMethodLike
| CallableTypeKind::ClassMethodLike) => Some(kind),
_ => None,
}),
};

// Check if this is a class-like type that should use constructor call handling.
let class = match decorator_ty {
Expand Down
11 changes: 8 additions & 3 deletions crates/ty_python_semantic/src/types/signatures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use itertools::{EitherOrBoth, Itertools};
use rustc_hash::FxHashMap;
use smallvec::{SmallVec, smallvec_inline};

use super::{DynamicType, Type, TypeVarVariance, definition_expression_type, semantic_index};
use super::{DynamicType, Type, TypeVarVariance, semantic_index};
use crate::semantic_index::definition::Definition;
use crate::types::constraints::{ConstraintSet, IteratorConstraintsExtension};
use crate::types::generics::{GenericContext, InferableTypeVars, walk_generic_context};
Expand All @@ -35,7 +35,7 @@ use ruff_python_ast::{self as ast, name::Name};

/// Infer the type of a parameter or return annotation in a function signature.
///
/// This is very similar to [`definition_expression_type`], but knows that `TypeInferenceBuilder`
/// This is very similar to `definition_expression_type`, but knows that `TypeInferenceBuilder`
/// will always infer the parameters and return of a function in its PEP-695 typevar scope, if
/// there is one; otherwise they will be inferred in the function definition scope, but will always
/// be deferred. (This prevents spurious salsa cycles when we need the signature of the function
Expand Down Expand Up @@ -1998,7 +1998,12 @@ impl<'db> Parameters<'db> {

let default_type = |param: &ast::ParameterWithDefault| {
param.default().map(|default| {
definition_expression_type(db, definition, default).replace_parameter_defaults(db)
// Use the same approach as function_signature_expression_type to avoid cycles.
// Defaults are always deferred (see infer_function_definition), so we can go
// directly to infer_deferred_types without first checking infer_definition_types.
infer_deferred_types(db, definition)
.expression_type(default)
.replace_parameter_defaults(db)
})
};

Expand Down