Skip to content

Commit 317e0a3

Browse files
[ty] Bound nested callable signature display (#29049)
## Summary We limit nested callable signature display to four levels, matching the existing limit for function signatures. Further signatures display as `(...) -> ...`, while a reference back to the same callable displays as `Divergent`. We check for recursion before retrieving a callable's signatures, including callables reached through bound methods. This prevents display from expanding a recursive signature before its recursion guard runs. Nested `Callable` annotations cover both sides of the depth limit.
1 parent 8546752 commit 317e0a3

2 files changed

Lines changed: 52 additions & 17 deletions

File tree

‎crates/ty_python_semantic/resources/mdtest/type_display/callable.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,3 +151,19 @@ class Baz:
151151

152152
reveal_type(Baz().h) # revealed: bound method Baz.h(x: Scalar | GenericArray1d[Scalar]) -> None
153153
```
154+
155+
## Deeply nested callables
156+
157+
We display up to four nested callable signatures, then abbreviate further signatures as
158+
`(...) -> ...`.
159+
160+
```py
161+
from typing import Callable
162+
163+
def f(
164+
at_limit: Callable[[], Callable[[], Callable[[], Callable[[], int]]]],
165+
beyond_limit: Callable[[], Callable[[], Callable[[], Callable[[], Callable[[], int]]]]],
166+
):
167+
reveal_type(at_limit) # revealed: () -> (() -> (() -> (() -> int)))
168+
reveal_type(beyond_limit) # revealed: () -> (() -> (() -> (() -> ((...) -> ...))))
169+
```

‎crates/ty_python_semantic/src/types/display.rs‎

Lines changed: 36 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,7 @@ use crate::types::constraints::ConstraintSetBuilder;
2626
use crate::types::function::{FunctionType, OverloadLiteral};
2727
use crate::types::generics::{GenericContext, Specialization, walk_specialization_types};
2828
use crate::types::recursive::RecursiveType;
29-
use crate::types::signatures::{
30-
CallableSignature, Parameter, Parameters, ParametersKind, Signature,
31-
};
29+
use crate::types::signatures::{Parameter, Parameters, ParametersKind, Signature};
3230
use crate::types::tuple::{TupleSpec, VariableSegment};
3331
use crate::types::type_alias::QualifiedTypeAliasName;
3432
use crate::types::typevar::BoundTypeVarIdentity;
@@ -45,6 +43,9 @@ use ty_python_core::definition::Definition;
4543
use ty_python_core::scope::{FileScopeId, ScopeKind};
4644
use ty_python_core::semantic_index;
4745

46+
/// Bound display expansion even when recursive specialization keeps changing the signature.
47+
const MAX_SIGNATURE_DISPLAY_DEPTH: usize = 4;
48+
4849
/// A named item that can be either a class or a type alias.
4950
///
5051
/// This wrapper allows tracking both classes and type aliases together for
@@ -150,6 +151,8 @@ pub struct DisplaySettings<'db> {
150151
/// Function types that are currently being displayed.
151152
/// Used to prevent infinite recursion when displaying self-referential function types.
152153
visited_function_types: Rc<FxHashSet<FunctionType<'db>>>,
154+
/// Callable signatures can refer back to the same lambda through its lazy return type.
155+
visited_callable_types: Rc<FxHashSet<CallableType<'db>>>,
153156
/// Whether to hide the return type of the outermost signature.
154157
/// Return types of nested callable types inside parameters are still shown.
155158
hide_return_type: bool,
@@ -2019,10 +2022,9 @@ impl<'db> FmtDetailed<'db> for DisplayFunctionType<'_, 'db> {
20192022
// Detect self-referential function types to prevent infinite recursion,
20202023
// and limit display depth for chains of different function types
20212024
// (e.g. multiple redefinitions with `TypeOf[foo]` return types).
2022-
const MAX_FUNCTION_TYPE_DISPLAY_DEPTH: usize = 4;
20232025
let db = self.db;
20242026
if self.settings.visited_function_types.contains(&self.ty)
2025-
|| self.settings.visited_function_types.len() >= MAX_FUNCTION_TYPE_DISPLAY_DEPTH
2027+
|| self.settings.visited_function_types.len() >= MAX_SIGNATURE_DISPLAY_DEPTH
20262028
{
20272029
f.set_invalid_type_annotation();
20282030
f.write_str("def ")?;
@@ -2465,8 +2467,7 @@ impl<'db> CallableType<'db> {
24652467
settings: DisplaySettings<'db>,
24662468
) -> DisplayCallableType<'a, 'db> {
24672469
DisplayCallableType {
2468-
signatures: self.signatures(db),
2469-
kind: self.kind(db),
2470+
ty: *self,
24702471
db,
24712472
env,
24722473
settings,
@@ -2475,8 +2476,7 @@ impl<'db> CallableType<'db> {
24752476
}
24762477

24772478
pub(crate) struct DisplayCallableType<'a, 'db> {
2478-
signatures: &'a CallableSignature<'db>,
2479-
kind: CallableTypeKind,
2479+
ty: CallableType<'db>,
24802480
db: &'db dyn Db,
24812481
env: &'a ProgramEnvironment<'db>,
24822482
settings: DisplaySettings<'db>,
@@ -2485,22 +2485,31 @@ pub(crate) struct DisplayCallableType<'a, 'db> {
24852485
impl<'db> FmtDetailed<'db> for DisplayCallableType<'_, 'db> {
24862486
fn fmt_detailed(&self, f: &mut TypeWriter<'_, '_, 'db>) -> fmt::Result {
24872487
let db = self.db;
2488-
match self.signatures.overloads.as_slice() {
2488+
if self.settings.visited_callable_types.contains(&self.ty) {
2489+
return f.write_str("Divergent");
2490+
}
2491+
if self.settings.visited_callable_types.len() >= MAX_SIGNATURE_DISPLAY_DEPTH {
2492+
f.set_invalid_type_annotation();
2493+
return f.write_str("(...) -> ...");
2494+
}
2495+
let mut settings = self.settings.clone();
2496+
Rc::make_mut(&mut settings.visited_callable_types).insert(self.ty);
2497+
match self.ty.signatures(db).overloads.as_slice() {
24892498
[signature] => {
2490-
if matches!(self.kind, CallableTypeKind::ParamSpecValue) {
2499+
if matches!(self.ty.kind(db), CallableTypeKind::ParamSpecValue) {
24912500
if signature.parameters().is_top() {
24922501
f.write_str("Top[")?;
24932502
}
24942503
signature
24952504
.parameters()
2496-
.display_with(db, self.env, self.settings.clone())
2505+
.display_with(db, self.env, settings.clone())
24972506
.fmt_detailed(f)?;
24982507
if signature.parameters().is_top() {
24992508
f.write_str("]")?;
25002509
}
25012510
} else {
25022511
signature
2503-
.display_with(db, self.env, self.settings.clone())
2512+
.display_with(db, self.env, settings.clone())
25042513
.fmt_detailed(f)?;
25052514
}
25062515
}
@@ -2515,7 +2524,7 @@ impl<'db> FmtDetailed<'db> for DisplayCallableType<'_, 'db> {
25152524
let separator = if self.settings.multiline { "\n" } else { ", " };
25162525
let mut join = f.join(separator);
25172526
for signature in signatures {
2518-
join.entry(&signature.display_with(db, self.env, self.settings.clone()));
2527+
join.entry(&signature.display_with(db, self.env, settings.clone()));
25192528
}
25202529
join.finish()?;
25212530
if !self.settings.multiline {
@@ -2700,7 +2709,7 @@ impl<'db> FmtDetailed<'db> for DisplaySignature<'_, 'db> {
27002709
f.write_str(" -> ")?;
27012710

27022711
let should_parenthesize_return_type =
2703-
should_parenthesize_callable_type(self.return_ty, db);
2712+
should_parenthesize_callable_type(db, self.return_ty, &self.settings);
27042713
if should_parenthesize_return_type {
27052714
f.write_char('(')?;
27062715
}
@@ -3657,8 +3666,18 @@ impl Display for DisplayMaybeNegatedType<'_, '_> {
36573666
/// avoid ambiguity in nested callable displays. The exceptions are:
36583667
/// - Overloaded callables, which display as `Overload[...]` (already unambiguous)
36593668
/// - Callables with top-materialization parameters, which display as `Top[...]` (already unambiguous)
3660-
fn should_parenthesize_callable_type(ty: Type<'_>, db: &dyn Db) -> bool {
3669+
fn should_parenthesize_callable_type<'db>(
3670+
db: &'db dyn Db,
3671+
ty: Type<'db>,
3672+
settings: &DisplaySettings<'db>,
3673+
) -> bool {
36613674
if let Type::Callable(callable) = ty {
3675+
if settings.visited_callable_types.contains(&callable) {
3676+
return false;
3677+
}
3678+
if settings.visited_callable_types.len() >= MAX_SIGNATURE_DISPLAY_DEPTH {
3679+
return true;
3680+
}
36623681
let overloads = &callable.signatures(db).overloads;
36633682
overloads.len() == 1 && !overloads[0].parameters().is_top()
36643683
} else {
@@ -3685,7 +3704,7 @@ impl<'db> FmtDetailed<'db> for DisplayMaybeParenthesizedType<'_, 'db> {
36853704
f.write_char(')')
36863705
};
36873706
match self.ty {
3688-
ty if should_parenthesize_callable_type(ty, db) => write_parentheses(f),
3707+
ty if should_parenthesize_callable_type(db, ty, &self.settings) => write_parentheses(f),
36893708
Type::KnownBoundMethod(_) | Type::FunctionLiteral(_) | Type::BoundMethod(_) => {
36903709
write_parentheses(f)
36913710
}

0 commit comments

Comments
 (0)