diff --git a/pyrefly/lib/alt/call.rs b/pyrefly/lib/alt/call.rs index 3cfb913817..a508e700a5 100644 --- a/pyrefly/lib/alt/call.rs +++ b/pyrefly/lib/alt/call.rs @@ -2144,10 +2144,77 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> { } } CallTarget::BoundMethodOverload(obj, overloads, meta) => { + // Bind the receiver before matching the arguments, as for a non-overloaded + // method, so that only the overloads that accept it are matched. A receiver with + // unsolved vars is matched along with the arguments instead, because checking it + // here could pin those vars. + let (accepting, rejecting): (Vec<_>, Vec<_>) = + if obj.collect_maybe_placeholder_vars().is_empty() { + overloads + .into_iter() + .partition(|overload| self.accepts_receiver(&overload.1, &obj)) + } else { + (overloads.into_vec(), Vec::new()) + }; + let (overloads, self_obj) = match Vec1::try_from_vec(accepting) { + // If the receiver rules out every overload but one, that overload is called + // like a non-overloaded method. + Ok(accepting) if accepting.len() == 1 && !rejecting.is_empty() => { + return self.call_infer_with_callee_range( + CallTarget::BoundMethod(obj, accepting.split_off_first().0), + args, + keywords, + arguments_range, + callee_range, + errors, + call_errors, + return_errors, + context, + hint, + ctor_targs, + ); + } + Ok(accepting) => (accepting, Some(obj)), + // No overload accepts the receiver. Report it once, as for a non-overloaded + // method, and match the arguments as if `self` were bound. + Err(_) => { + let rejecting = Vec1::try_from_vec(rejecting) + .expect("an overloaded function has at least one signature"); + let signature = &rejecting.first().1.signature; + let self_name = match &signature.params { + Params::List(params) | Params::Partial(params) => { + params.items().first().and_then(|param| param.name()) + } + _ => None, + }; + let self_ty = signature + .get_first_param() + .expect("a signature that rejects the receiver has a first parameter"); + self.check_type(&obj, self_ty, arguments_range, call_errors, &|| { + TypeCheckContext::of_kind(TypeCheckKind::CallArgument( + self_name.cloned(), + Some(meta.kind.clone()), + )) + .with_context(context.map(|ctx| ctx())) + }); + let unbound = rejecting.mapped(|TargetWithTParams(tparams, func)| { + TargetWithTParams( + tparams, + Function { + signature: func.signature.strip_first_param().expect( + "a signature that rejects the receiver has a first parameter", + ), + metadata: func.metadata, + }, + ) + }); + (unbound, None) + } + }; let (ty, _callable, overload_table, argmap) = self.call_overloads( overloads, &meta, - Some(obj), + self_obj, args, keywords, arguments_range, diff --git a/pyrefly/lib/alt/function.rs b/pyrefly/lib/alt/function.rs index bb0fa72329..24695acc90 100644 --- a/pyrefly/lib/alt/function.rs +++ b/pyrefly/lib/alt/function.rs @@ -2827,26 +2827,32 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> { self.bind_bound_method_type(&m.func, &m.obj, skip_instantiation, is_subset) } - /// Drop overloads whose first parameter cannot accept `receiver`. Type parameters on both - /// sides are replaced with `Any`, so an overload is dropped only if no specialization of it - /// could accept the receiver. If every overload would be dropped, `func` is returned - /// unchanged so that the callable stays usable. - fn filter_overloads_by_receiver(&self, func: Type, receiver: &Type) -> Type { - let Type::Overload(overload) = &func else { - return func; - }; + /// Whether the first parameter of `function` can accept `receiver`. Type parameters on both + /// sides are replaced with `Any`, so this is false only if no specialization of `function` + /// could accept the receiver. + pub fn accepts_receiver(&self, function: &Function, receiver: &Type) -> bool { let any = self.heap.mk_any_implicit(); let erase_tparams = |ty: &Type| { let mut ty = ty.clone(); ty.subst_mut_fn(&mut |_| Some(any.clone())); ty }; - let receiver = erase_tparams(receiver); + function + .signature + .get_first_param() + .is_none_or(|param| self.is_subset_eq(&erase_tparams(receiver), &erase_tparams(param))) + } + + /// Drop overloads whose first parameter cannot accept `receiver`, as decided by + /// `accepts_receiver`. If every overload would be dropped, `func` is returned unchanged so + /// that the callable stays usable. + fn filter_overloads_by_receiver(&self, func: Type, receiver: &Type) -> Type { + let Type::Overload(overload) = &func else { + return func; + }; let signatures = overload.signatures.iter().filter(|sig| { let (OverloadType::Function(f) | OverloadType::Forall(Forall { body: f, .. })) = sig; - f.signature - .get_first_param() - .is_none_or(|param| self.is_subset_eq(&receiver, &erase_tparams(param))) + self.accepts_receiver(f, receiver) }); match Vec1::try_from_vec(signatures.cloned().collect()) { Ok(signatures) => self.heap.mk_overload(Overload { diff --git a/pyrefly/lib/test/decorators.rs b/pyrefly/lib/test/decorators.rs index 914896d385..d7661f8217 100644 --- a/pyrefly/lib/test/decorators.rs +++ b/pyrefly/lib/test/decorators.rs @@ -3043,7 +3043,7 @@ class A: assert_type(A().g(1), int) assert_type(A().g("hello"), str) -A.f(1) # E: No matching overload +A.f(1) # E: Argument `type[A]` is not assignable "#, ); diff --git a/pyrefly/lib/test/generic_basic.rs b/pyrefly/lib/test/generic_basic.rs index a50241d2b6..0cbeeb1a7e 100644 --- a/pyrefly/lib/test/generic_basic.rs +++ b/pyrefly/lib/test/generic_basic.rs @@ -531,7 +531,7 @@ def f(): def g(): x: dict[int, int] = {} - x.update(a=1) # E: `dict[int, int]` is not assignable to parameter `self` with type `SupportsGetItem[str, int]` + x.update(a=1) # E: No matching overload found for function `typing.MutableMapping.update` "#, ); diff --git a/pyrefly/lib/test/intersection_calls.rs b/pyrefly/lib/test/intersection_calls.rs index d9c4342417..f9e837b1c4 100644 --- a/pyrefly/lib/test/intersection_calls.rs +++ b/pyrefly/lib/test/intersection_calls.rs @@ -619,12 +619,12 @@ class D: def method(self, callback: Callable[[int], int]) -> RetA: ... def int_first(a: A): if isinstance(a, B): - reveal_type(a.method(lambda v: v + 1)) # E: revealed type: RetA & RetB + reveal_type(a.method(lambda v: v + 1)) # E: revealed type: RetA typed: Callable[[int], int] = lambda v: v + 1 reveal_type(a.method(typed)) # E: revealed type: RetA def str_first(c: C): if isinstance(c, D): - reveal_type(c.method(lambda v: v + 1)) # E: revealed type: RetA & RetB + reveal_type(c.method(lambda v: v + 1)) # E: revealed type: RetA def ordinary(a: A): assert_type(a.method(lambda v: v + 1), RetA) def intrinsic_errors(a: A): diff --git a/pyrefly/lib/test/overload.rs b/pyrefly/lib/test/overload.rs index e71e7e05ef..80e37301f1 100644 --- a/pyrefly/lib/test/overload.rs +++ b/pyrefly/lib/test/overload.rs @@ -2529,6 +2529,39 @@ f(3.14) # E: `float` is not assignable to parameter `x` with type `int` "#, ); +// Regression test for https://github.com/facebook/pyrefly/issues/5217 +testcase!( + test_overload_error_bad_self_argument, + r#" +from typing import assert_type, overload + +class A: + @overload + def meth(self, a: int) -> int: ... + @overload + def meth(self, a: str) -> str: ... + def meth(self, a: int | str) -> int | str: ... + +class B: + meth = A.meth + +class C[T]: + @overload + def f(self: C[int], x: int) -> int: ... + @overload + def f(self: C[str], x: str) -> str: ... + def f(self, x: int | str) -> int | str: ... + +def test(b: B, c: C[str], d: C[bytes]): + # No overload accepts `b`, so it is reported once, and the arguments are still matched. + assert_type(b.meth(1), int) # E: Argument `B` is not assignable to parameter `self` with type `A` in function `A.meth` + b.meth(1.5) # E: Argument `B` is not assignable to parameter `self` # E: No matching overload found for function `A.meth` called with arguments: (float) + # Only the overload whose `self` accepts `c` is matched. + c.f(1) # E: Argument `Literal[1]` is not assignable to parameter `x` with type `str` + d.f(1) # E: Argument `C[bytes]` is not assignable to parameter `self` with type `C[int]` + "#, +); + testcase!( test_varargs_materialization, r#"