Skip to content

Commit eb1d251

Browse files
committed
red_knot_python_semantic: add "return type span" helper method
This is very similar to querying for the span of a parameter in a function definition, but instead we look for the span of a return type.
1 parent a45a0a9 commit eb1d251

File tree

1 file changed

+39
-0
lines changed
  • crates/red_knot_python_semantic/src

1 file changed

+39
-0
lines changed

crates/red_knot_python_semantic/src/types.rs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4904,6 +4904,45 @@ impl<'db> Type<'db> {
49044904
}
49054905
}
49064906

4907+
/// Returns a tuple of two spans. The first is
4908+
/// the span for the identifier of the function
4909+
/// definition for `self`. The second is
4910+
/// the span for the return type in the function
4911+
/// definition for `self`.
4912+
///
4913+
/// If there are no meaningful spans, then this
4914+
/// returns `None`. For example, when this type
4915+
/// isn't callable or if the function has no
4916+
/// declared return type.
4917+
///
4918+
/// # Performance
4919+
///
4920+
/// Note that this may introduce cross-module
4921+
/// dependencies. This can have an impact on
4922+
/// the effectiveness of incremental caching
4923+
/// and should therefore be used judiciously.
4924+
///
4925+
/// An example of a good use case is to improve
4926+
/// a diagnostic.
4927+
fn return_type_span(&self, db: &'db dyn Db) -> Option<(Span, Span)> {
4928+
match *self {
4929+
Type::FunctionLiteral(function) => {
4930+
let function_scope = function.body_scope(db);
4931+
let span = Span::from(function_scope.file(db));
4932+
let node = function_scope.node(db);
4933+
let func_def = node.as_function()?;
4934+
let return_type_range = func_def.returns.as_ref()?.range();
4935+
let name_span = span.clone().with_range(func_def.name.range);
4936+
let return_type_span = span.with_range(return_type_range);
4937+
Some((name_span, return_type_span))
4938+
}
4939+
Type::BoundMethod(bound_method) => {
4940+
Type::FunctionLiteral(bound_method.function(db)).return_type_span(db)
4941+
}
4942+
_ => None,
4943+
}
4944+
}
4945+
49074946
/// Returns a tuple of two spans. The first is
49084947
/// the span for the identifier of the function
49094948
/// definition for `self`. The second is

0 commit comments

Comments
 (0)