diff --git a/pyrefly/lib/alt/answers.rs b/pyrefly/lib/alt/answers.rs index 7b1c7710ba..6cee1a1c8d 100644 --- a/pyrefly/lib/alt/answers.rs +++ b/pyrefly/lib/alt/answers.rs @@ -88,6 +88,7 @@ use crate::types::class::ClassFields; use crate::types::env::TypeEnv; use crate::types::equality::TypeEq; use crate::types::equality::TypeEqCtx; +use crate::types::function::FuncDefId; use crate::types::heap::TypeHeap; use crate::types::stdlib::Stdlib; use crate::types::types::Forall; @@ -173,6 +174,7 @@ impl VisitMut for Traces { let OverloadTrace { callable, tparams: _, + .. } = trace; callable.visit_mut(f); } @@ -180,6 +182,7 @@ impl VisitMut for Traces { for OverloadTrace { callable, tparams: _, + .. } in all.iter_mut().chain(std::iter::once(closest)) { callable.visit_mut(f); @@ -194,11 +197,20 @@ impl VisitMut for Traces { pub struct OverloadTrace { callable: Callable, tparams: Option>, + func_def_id: Option>, } impl OverloadTrace { - pub(crate) fn new(callable: Callable, tparams: Option>) -> Self { - Self { callable, tparams } + pub(crate) fn new( + callable: Callable, + tparams: Option>, + func_def_id: Option>, + ) -> Self { + Self { + callable, + tparams, + func_def_id, + } } fn as_type(&self) -> Type { @@ -1888,6 +1900,19 @@ impl Answers { } } + /// The source definition chosen for a successfully resolved overload call. + pub fn get_chosen_overload_func_def_id(&self, range: TextRange) -> Option> { + let lock = self.trace.as_ref()?.lock(); + match lock.overloaded_callees.get(&range)? { + OverloadedCallee::Candidates { + closest, + is_closest_chosen: true, + .. + } => closest.func_def_id.clone(), + _ => None, + } + } + /// Returns all the overload, and the index of a chosen one pub fn get_all_overload_trace( &self, @@ -1937,7 +1962,7 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> { self.trace_state().record_resolved_trace( loc, OverloadedCallee::Resolved { - callable: OverloadTrace::new(callable, None), + callable: OverloadTrace::new(callable, None, None), }, ); } diff --git a/pyrefly/lib/alt/overload.rs b/pyrefly/lib/alt/overload.rs index f827a0a00b..40cba16f9d 100644 --- a/pyrefly/lib/alt/overload.rs +++ b/pyrefly/lib/alt/overload.rs @@ -6,6 +6,7 @@ */ use std::cmp::max; +use std::sync::Arc; use itertools::Either; use itertools::Itertools; @@ -520,7 +521,16 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> { .as_ref() .filter(|tparams| !tparams.is_empty()) .cloned(); - OverloadTrace::new(target.1.signature.clone(), tparams) + OverloadTrace::new( + target.1.signature.clone(), + tparams, + target + .1 + .metadata + .kind + .as_func_def_id() + .map(|func_id| Arc::new(func_id.clone())), + ) }; let all_overload_traces = overloads.iter().map(&mut overload_trace).collect(); let closest_overload_trace = overload_trace(closest_overload.func); diff --git a/pyrefly/lib/lsp/wasm/hover.rs b/pyrefly/lib/lsp/wasm/hover.rs index f5cdb70ac4..5d6bd90bf7 100644 --- a/pyrefly/lib/lsp/wasm/hover.rs +++ b/pyrefly/lib/lsp/wasm/hover.rs @@ -8,6 +8,7 @@ // @lint-ignore-every SPELL use std::cell::LazyCell; +use std::sync::Arc; use std::sync::LazyLock; use dupe::Dupe; @@ -37,6 +38,7 @@ use pyrefly_types::callable::Required; use pyrefly_types::class::Class; use pyrefly_types::class::ClassType; use pyrefly_types::display::LspDisplayMode; +use pyrefly_types::function::FuncDefId; use pyrefly_types::type_var::Variance; use pyrefly_types::types::Type; use pyrefly_util::absolutize::Absolutize as _; @@ -1487,6 +1489,72 @@ fn nonempty_docstring(docstring: Docstring) -> Option { docstring.has_content().then_some(docstring) } +fn docstring_for_func_def( + transaction: &Transaction<'_>, + handle: &Handle, + func_id: &FuncDefId, +) -> Option { + let definition_handle = transaction.imported_handle( + handle, + func_id.qname.module_name(), + func_id.qname.module_path().dupe(), + ); + let ast = transaction.get_ast(&definition_handle)?; + let function = Ast::locate_node(ast.as_ref(), func_id.qname.range().start()) + .into_iter() + .find_map(|node| match node { + AnyNodeRef::StmtFunctionDef(function) + if function.name.range == func_id.qname.range() => + { + Some(function) + } + _ => None, + })?; + let range = function_doc_ranges(function).docstring()?; + Some(Docstring( + range, + transaction.get_module_info(&definition_handle)?, + )) +} + +/// Find the source definition selected by the overload call under the cursor. +fn selected_overload_func_def( + transaction: &Transaction<'_>, + handle: &Handle, + ast: &ModModule, + position: TextSize, +) -> Option> { + let (_, arguments_range, on_name) = callee_at_position(transaction, handle, ast, position)?; + if !on_name { + return None; + } + transaction + .get_answers(handle)? + .get_chosen_overload_func_def_id(arguments_range) +} + +fn overload_implementation_docstring( + transaction: &Transaction<'_>, + handle: &Handle, + ast: &ModModule, + position: TextSize, +) -> Option { + let (callee_range, _, on_name) = callee_at_position(transaction, handle, ast, position)?; + if !on_name { + return None; + } + let func_id = transaction + .get_answers(handle)? + .get_type_trace(callee_range) + .and_then(|type_| { + type_ + .toplevel_func_metadata() + .and_then(|metadata| metadata.kind.as_func_def_id()) + .cloned() + })?; + docstring_for_func_def(transaction, handle, &func_id) +} + /// Class docstring for a constructor call whose `__init__` or `__new__` has none. /// /// Eligibility comes from the callee's class type. `find_definition` with dunder @@ -1797,10 +1865,25 @@ pub fn get_hover_with_verbosity( } else { (None, fallback_name_from_type, None, Vec::new()) }; - let docstring = interface_docstring - .and_then(nonempty_docstring) - .or_else(|| fallback_docstring.and_then(nonempty_docstring)) - .or_else(|| docstring_for_class_object_type(transaction, handle, &type_)); + let selected_overload = ast + .as_deref() + .and_then(|ast| selected_overload_func_def(transaction, handle, ast, position)); + let docstring = if let Some(func_id) = selected_overload { + docstring_for_func_def(transaction, handle, &func_id) + .and_then(nonempty_docstring) + .or_else(|| { + ast.as_deref() + .and_then(|ast| { + overload_implementation_docstring(transaction, handle, ast, position) + }) + .and_then(nonempty_docstring) + }) + } else { + interface_docstring + .and_then(nonempty_docstring) + .or_else(|| fallback_docstring.and_then(nonempty_docstring)) + .or_else(|| docstring_for_class_object_type(transaction, handle, &type_)) + }; let docstring = if hover_constructor_dunder { docstring.or_else(|| class_docstring_for_constructor(transaction, handle, position)) diff --git a/pyrefly/lib/test/lsp/hover.rs b/pyrefly/lib/test/lsp/hover.rs index 093e28b8e9..37db4ef89e 100644 --- a/pyrefly/lib/test/lsp/hover.rs +++ b/pyrefly/lib/test/lsp/hover.rs @@ -450,6 +450,179 @@ Foo().bar(1) ); } +#[test] +fn hover_on_overloaded_methods_shows_matching_overload_docstring() { + let code = r#" +from typing import overload + +class Foo: + @overload + def fn(self, a: int) -> int: + """int overload""" + @overload + def fn(self, a: str) -> str: + """str overload""" + @overload + def fn(self, a: bytes) -> bytes: ... + def fn(self, a: str | int | bytes) -> str | int | bytes: + return a + +f = Foo() +_ = f.fn(1) +# ^ +_ = f.fn("") +# ^ +_ = f.fn(b"") +# ^ +"#; + + let report = get_batched_lsp_operations_report(&[("main", code)], |state, handle, position| { + match get_hover(&state.transaction(), handle, position, false) { + Some(Hover { + contents: Contents::MarkupContent(markup), + .. + }) => markup.value, + _ => "None".to_owned(), + } + }); + assert!( + report.contains( + r#" +17 | _ = f.fn(1) + ^ +```python +(method) fn: def fn( + self: Foo, + a: int +) -> int: ... +``` +--- +int overload"# + ), + "Expected the int overload docstring in hover, got: {report}" + ); + assert!( + report.contains( + r#" +19 | _ = f.fn("") + ^ +```python +(method) fn: def fn( + self: Foo, + a: str +) -> str: ... +``` +--- +str overload"# + ), + "Expected the str overload docstring in hover, got: {report}" + ); + assert!( + report.contains( + r#" +21 | _ = f.fn(b"") + ^ +```python +(method) fn: def fn( + self: Foo, + a: bytes +) -> bytes: ... +```"# + ) && !report.contains( + r#" +21 | _ = f.fn(b"") + ^ +```python +(method) fn: def fn( + self: Foo, + a: bytes +) -> bytes: ... +``` +---"# + ), + "Expected the undocumented overload hover, got: {report}" + ); +} + +#[test] +fn hover_on_overloaded_function_shows_matching_overload_docstring() { + let code = r#" +from typing import overload + +@overload +def fn(a: int) -> int: + """int overload""" +@overload +def fn(a: str) -> str: + """str overload""" +@overload +def fn(a: bytes) -> bytes: ... +def fn(a: str | int | bytes) -> str | int | bytes: + return a + +_ = fn(1) +# ^ +_ = fn("") +# ^ +_ = fn(b"") +# ^ +"#; + let report = get_batched_lsp_operations_report(&[("main", code)], |state, handle, position| { + match get_hover(&state.transaction(), handle, position, false) { + Some(Hover { + contents: Contents::MarkupContent(markup), + .. + }) => markup.value, + _ => "None".to_owned(), + } + }); + assert!( + report.contains( + r#" +15 | _ = fn(1) + ^ +```python +(function) fn: def fn(a: int) -> int: ... +``` +--- +int overload"# + ), + "Expected the int overload docstring in hover, got: {report}" + ); + assert!( + report.contains( + r#" +17 | _ = fn("") + ^ +```python +(function) fn: def fn(a: str) -> str: ... +``` +--- +str overload"# + ), + "Expected the str overload docstring in hover, got: {report}" + ); + assert!( + report.contains( + r#" +19 | _ = fn(b"") + ^ +```python +(function) fn: def fn(a: bytes) -> bytes: ... +```"# + ) && !report.contains( + r#" +19 | _ = fn(b"") + ^ +```python +(function) fn: def fn(a: bytes) -> bytes: ... +``` +---"# + ), + "Expected the undocumented overload hover, got: {report}" + ); +} + #[test] fn hover_on_union_method_call_shows_method_signature() { let code = r#"