diff --git a/crates/ty_ide/src/inlay_hints.rs b/crates/ty_ide/src/inlay_hints.rs index 75976fd469272..cf256aa0c5027 100644 --- a/crates/ty_ide/src/inlay_hints.rs +++ b/crates/ty_ide/src/inlay_hints.rs @@ -6191,13 +6191,14 @@ mod tests { | info[inlay-hint-location]: Inlay Hint Target - --> main.py:5:9 + --> main.py:7:9 | - 4 | @overload 5 | def foo(x: int) -> str: ... - | ^ 6 | @overload 7 | def foo(x: str) -> int: ... + | ^ + 8 | def foo(x): + 9 | return x | info: Source --> main2.py:12:6 @@ -6209,6 +6210,146 @@ mod tests { "); } + #[test] + fn test_overloaded_function_calls_different_params() { + let mut test = inlay_hint_test( + " + from typing import overload, Optional, Sequence + + @overload + def S(name: str, is_symmetric: Optional[bool] = None) -> str: ... + @overload + def S(*names: str, is_symmetric: Optional[bool] = None) -> Sequence[str]: ... + def S(): + pass + + b = S('x', 'y')", + ); + + // The call S('x', 'y') should match the second overload (*names: str), + // and since *names is variadic, no parameter name hints should be shown. + // Before the fix, this incorrectly showed `name=` and `is_symmetric=` hints + // from the first overload. + assert_snapshot!(test.inlay_hints(), @" + + from typing import overload, Optional, Sequence + + @overload + def S(name: str, is_symmetric: Optional[bool] = None) -> str: ... + @overload + def S(*names: str, is_symmetric: Optional[bool] = None) -> Sequence[str]: ... + def S(): + pass + + b[: Sequence[str]] = S('x', 'y') + --------------------------------------------- + info[inlay-hint-location]: Inlay Hint Target + --> stdlib/typing.pyi:1565:7 + | + 1563 | def __len__(self) -> int: ... + 1564 | + 1565 | class Sequence(Reversible[_T_co], Collection[_T_co]): + | ^^^^^^^^ + 1566 | \"\"\"All the operations on a read-only sequence. + | + info: Source + --> main2.py:11:5 + | + 9 | pass + 10 | + 11 | b[: Sequence[str]] = S('x', 'y') + | ^^^^^^^^ + | + + info[inlay-hint-location]: Inlay Hint Target + --> stdlib/builtins.pyi:915:7 + | + 914 | @disjoint_base + 915 | class str(Sequence[str]): + | ^^^ + 916 | \"\"\"str(object='') -> str + 917 | str(bytes_or_buffer[, encoding[, errors]]) -> str + | + info: Source + --> main2.py:11:14 + | + 9 | pass + 10 | + 11 | b[: Sequence[str]] = S('x', 'y') + | ^^^ + | + + --------------------------------------------- + info[inlay-hint-edit]: File after edits + info: Source + + from typing import overload, Optional, Sequence + + @overload + def S(name: str, is_symmetric: Optional[bool] = None) -> str: ... + @overload + def S(*names: str, is_symmetric: Optional[bool] = None) -> Sequence[str]: ... + def S(): + pass + + b: Sequence[str] = S('x', 'y') + "); + } + + #[test] + fn test_overloaded_function_calls_no_matching_overload() { + let mut test = inlay_hint_test( + " + from typing import overload + + @overload + def f(x: int) -> str: ... + @overload + def f(x: str, y: str) -> int: ... + def f(x): + return x + + f([]) + ", + ); + + // Neither overload matches via type checking (list[Unknown] is neither int nor str), + // so `matching_overloads()` returns empty. The arity-based fallback picks the first + // overload (1 matched arg out of 1 required), and we should see the `x=` hint. + assert_snapshot!(test.inlay_hints(), @r" + + from typing import overload + + @overload + def f(x: int) -> str: ... + @overload + def f(x: str, y: str) -> int: ... + def f(x): + return x + + f([x=][]) + + --------------------------------------------- + info[inlay-hint-location]: Inlay Hint Target + --> main.py:5:7 + | + 4 | @overload + 5 | def f(x: int) -> str: ... + | ^ + 6 | @overload + 7 | def f(x: str, y: str) -> int: ... + | + info: Source + --> main2.py:11:4 + | + 9 | return x + 10 | + 11 | f([x=][]) + | ^ + | + "); + } + #[test] fn test_disabled_function_argument_names() { let mut test = inlay_hint_test( diff --git a/crates/ty_python_semantic/src/types/call/arguments.rs b/crates/ty_python_semantic/src/types/call/arguments.rs index fa45d408c764a..ac2761bfcd833 100644 --- a/crates/ty_python_semantic/src/types/call/arguments.rs +++ b/crates/ty_python_semantic/src/types/call/arguments.rs @@ -73,23 +73,23 @@ impl<'a, 'db> CallArguments<'a, 'db> { /// typechecking. pub(crate) fn from_arguments_typed( arguments: &'a ast::Arguments, - mut infer_argument_type: impl FnMut(Option<&ast::Expr>, &ast::Expr) -> Type<'db>, + mut infer_argument_type: impl FnMut(&ast::Expr) -> Type<'db>, ) -> Self { arguments .arguments_source_order() .map(|arg_or_keyword| match arg_or_keyword { ast::ArgOrKeyword::Arg(arg) => match arg { ast::Expr::Starred(ast::ExprStarred { value, .. }) => { - let ty = infer_argument_type(Some(arg), value); + let ty = infer_argument_type(value); (Argument::Variadic, Some(ty)) } _ => { - let ty = infer_argument_type(None, arg); + let ty = infer_argument_type(arg); (Argument::Positional, Some(ty)) } }, ast::ArgOrKeyword::Keyword(ast::Keyword { arg, value, .. }) => { - let ty = infer_argument_type(None, value); + let ty = infer_argument_type(value); if let Some(arg) = arg { (Argument::Keyword(&arg.id), Some(ty)) } else { diff --git a/crates/ty_python_semantic/src/types/ide_support.rs b/crates/ty_python_semantic/src/types/ide_support.rs index 7d13a14941bf2..f625774e3f216 100644 --- a/crates/ty_python_semantic/src/types/ide_support.rs +++ b/crates/ty_python_semantic/src/types/ide_support.rs @@ -5,7 +5,7 @@ use crate::place::builtins_module_scope; use crate::semantic_index::definition::Definition; use crate::semantic_index::definition::DefinitionKind; use crate::semantic_index::{attribute_scopes, global_scope, semantic_index, use_def_map}; -use crate::types::call::{CallArguments, MatchedArgument}; +use crate::types::call::{CallArguments, CallError, MatchedArgument}; use crate::types::signatures::{ParameterKind, Signature}; use crate::types::{ CallDunderError, CallableTypes, ClassBase, ClassLiteral, ClassType, KnownUnion, Type, @@ -514,7 +514,29 @@ pub struct CallSignatureDetails<'db> { pub argument_to_parameter_mapping: Vec>, } -impl CallSignatureDetails<'_> { +impl<'db> CallSignatureDetails<'db> { + fn from_binding(db: &'db dyn Db, binding: &crate::types::call::Binding<'db>) -> Self { + let argument_to_parameter_mapping = binding.argument_matches().to_vec(); + let signature = binding.signature.clone(); + let display_details = signature.display(db).to_string_parts(); + let (parameter_kinds, parameter_types): (Vec, Vec) = signature + .parameters() + .iter() + .map(|param| (param.kind().clone(), param.annotated_type())) + .unzip(); + + CallSignatureDetails { + definition: signature.definition(), + signature, + label: display_details.label, + parameter_label_offsets: display_details.parameter_ranges, + parameter_names: display_details.parameter_names, + parameter_kinds, + parameter_types, + argument_to_parameter_mapping, + } + } + fn get_definition_parameter_range(&self, db: &dyn Db, name: &str) -> Option { let definition = self.signature.definition()?; let file = definition.file(db); @@ -542,10 +564,12 @@ pub fn call_signature_details<'db>( return Vec::new(); }; + let db = model.db(); + // Use into_callable to handle all the complex type conversions if let Some(callable_type) = func_type - .try_upcast_to_callable(model.db()) - .map(|callables| callables.into_type(model.db())) + .try_upcast_to_callable(db) + .map(|callables| callables.into_type(db)) { let call_arguments = CallArguments::from_arguments(&call_expr.arguments, |_, splatted_value| { @@ -554,36 +578,14 @@ pub fn call_signature_details<'db>( .unwrap_or(Type::unknown()) }); let bindings = callable_type - .bindings(model.db()) - .match_parameters(model.db(), &call_arguments); + .bindings(db) + .match_parameters(db, &call_arguments); // Extract signature details from all callable bindings bindings .into_iter() .flatten() - .map(|binding| { - let argument_to_parameter_mapping = binding.argument_matches().to_vec(); - let signature = binding.signature; - let display_details = signature.display(model.db()).to_string_parts(); - let parameter_label_offsets = display_details.parameter_ranges; - let parameter_names = display_details.parameter_names; - let (parameter_kinds, parameter_types): (Vec, Vec) = signature - .parameters() - .iter() - .map(|param| (param.kind().clone(), param.annotated_type())) - .unzip(); - - CallSignatureDetails { - definition: signature.definition(), - signature, - label: display_details.label, - parameter_label_offsets, - parameter_names, - parameter_kinds, - parameter_types, - argument_to_parameter_mapping, - } - }) + .map(|binding| CallSignatureDetails::from_binding(db, &binding)) .collect() } else { // Type is not callable, return empty signatures @@ -621,7 +623,7 @@ pub fn call_type_simplified_by_overloads( } // Hand the overload resolution system as much type info as we have - let args = CallArguments::from_arguments_typed(&call_expr.arguments, |_, splatted_value| { + let args = CallArguments::from_arguments_typed(&call_expr.arguments, |splatted_value| { splatted_value .inferred_type(model) .unwrap_or(Type::unknown()) @@ -796,6 +798,60 @@ pub fn find_active_signature_from_details( Some(best_index) } +/// Resolve a call expression to its matching overload's signature details, +/// using full type checking (not just arity matching) for overload resolution. +/// +/// Falls back to arity-based matching if type-based resolution fails. +fn resolve_call_signature<'db>( + model: &SemanticModel<'db>, + call_expr: &ast::ExprCall, +) -> Option> { + let db = model.db(); + let func_type = call_expr.func.inferred_type(model)?; + let callable_type = func_type.try_upcast_to_callable(db)?.into_type(db); + + let args = CallArguments::from_arguments_typed(&call_expr.arguments, |splatted_value| { + splatted_value + .inferred_type(model) + .unwrap_or(Type::unknown()) + }); + + // Extract the `Bindings` regardless of whether type checking succeeded or failed. + let bindings = callable_type + .bindings(db) + .match_parameters(db, &args) + .check_types(db, &args, TypeContext::default(), &[]) + .unwrap_or_else(|CallError(_, bindings)| *bindings); + + // First, try to find the matching overload after full type checking. + let type_checked_details: Vec<_> = bindings + .iter() + .flat_map(|binding| binding.matching_overloads().map(|(_, overload)| overload)) + .map(|binding| CallSignatureDetails::from_binding(db, binding)) + .collect(); + + if !type_checked_details.is_empty() { + let active = find_active_signature_from_details(&type_checked_details)?; + return type_checked_details.into_iter().nth(active); + } + + // If all overloads have type-checking errors (e.g., `InvalidArgumentType`), + // `matching_overloads()` returns empty. Fall back to arity-based matching + // across all overloads to pick the best candidate for showing hints. + let all_details: Vec<_> = bindings + .iter() + .flatten() + .map(|binding| CallSignatureDetails::from_binding(db, binding)) + .collect(); + + if all_details.is_empty() { + return None; + } + + let active = find_active_signature_from_details(&all_details)?; + all_details.into_iter().nth(active) +} + #[derive(Default)] pub struct InlayHintCallArgumentDetails { /// The position of the arguments mapped to their name and the range of the argument definition in the signature. @@ -807,25 +863,14 @@ pub fn inlay_hint_call_argument_details<'db>( model: &SemanticModel<'db>, call_expr: &ast::ExprCall, ) -> Option { - let signature_details = call_signature_details(model, call_expr); + let resolved = resolve_call_signature(model, call_expr)?; - if signature_details.is_empty() { - return None; - } - - let active_signature_index = find_active_signature_from_details(&signature_details)?; - - let call_signature_details = signature_details.get(active_signature_index)?; - - let parameters = call_signature_details.signature.parameters(); + let parameters = resolved.signature.parameters(); let mut argument_names = HashMap::new(); for arg_index in 0..call_expr.arguments.args.len() { - let Some(arg_mapping) = call_signature_details - .argument_to_parameter_mapping - .get(arg_index) - else { + let Some(arg_mapping) = resolved.argument_to_parameter_mapping.get(arg_index) else { continue; }; @@ -847,8 +892,7 @@ pub fn inlay_hint_call_argument_details<'db>( continue; }; - let parameter_label_offset = - call_signature_details.get_definition_parameter_range(db, param.name()?); + let parameter_label_offset = resolved.get_definition_parameter_range(db, param.name()?); // Only add hints for parameters that can be specified by name if !param.is_positional_only() && !param.is_variadic() && !param.is_keyword_variadic() {