From c797ec48779b7d0ebcfc0a8a6d07d8268a9a5339 Mon Sep 17 00:00:00 2001 From: OverloadedTech Date: Mon, 16 Nov 2026 10:40:04 +0100 Subject: [PATCH 1/2] Report bad self in overloaded method calls as bad-argument-type When every overload of a method expects the same `self` type and the receiver is the only argument that doesn't match, report the error the same way as for a non-overloaded method instead of listing the overloads. --- pyrefly/lib/alt/class/class_field.rs | 90 ++++++++++++++++------------ pyrefly/lib/alt/overload.rs | 38 ++++++++++-- pyrefly/lib/test/decorators.rs | 2 +- pyrefly/lib/test/overload.rs | 34 +++++++++++ 4 files changed, 119 insertions(+), 45 deletions(-) diff --git a/pyrefly/lib/alt/class/class_field.rs b/pyrefly/lib/alt/class/class_field.rs index 411c865dd0..a98016a948 100644 --- a/pyrefly/lib/alt/class/class_field.rs +++ b/pyrefly/lib/alt/class/class_field.rs @@ -3793,46 +3793,9 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> { .filter(|sig| { let (func, tparams) = match sig { OverloadType::Function(f) => (f, None), - OverloadType::Forall(forall) => (&forall.body, Some(&forall.tparams)), + OverloadType::Forall(forall) => (&forall.body, Some(&*forall.tparams)), }; - // Only instance methods have a `self` first parameter; static and - // class methods' first parameter is a regular argument. - if func.metadata.flags.is_staticmethod || func.metadata.flags.is_classmethod { - return true; - } - func.signature.get_first_param().is_none_or(|p| { - // Replace the overload's own type params in `self:` with `Any` - // (e.g. `self: Array[S, T]` -> `Array[Any, Any]`), matching against a gradual - // `self:` rather than a rigid, unsolvable variable. - let p = match tparams { - Some(tparams) => { - let any = self.heap.mk_any_implicit(); - p.clone() - .subst(&tparams.iter().map(|q| (q, &any)).collect()) - } - None => p.clone(), - }; - // A non-protocol `self:` can't re-enter protocol conformance, so check - // it directly. A protocol-typed `self:`, however, makes - // `is_subset_eq(self_type, p)` re-enter this same filtering on the same - // `(self_type, p)` pair — unbounded recursion for a self-referential - // protocol. Guard only that case coinductively: on re-entry - // of the same pair, assume the overload applies (keep it). - let p_is_protocol = matches!( - &p, - Type::ClassType(cls) if self.type_order().is_protocol(cls.class_object()) - ); - if !p_is_protocol { - return self.is_subset_eq(self_type, &p); - } - let key = (self_type.clone(), p.clone()); - if self.enter_overload_self_filter(key.clone()) { - return true; - } - let applies = self.is_subset_eq(self_type, &p); - self.exit_overload_self_filter(&key); - applies - }) + self.overload_accepts_self_type(func, tparams, self_type) }) .cloned() .collect(); @@ -3847,6 +3810,55 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> { None } + /// Whether the receiver `self_type` is compatible with an overload signature's `self` + /// parameter. Static methods, class methods, and signatures without parameters accept any + /// receiver. + pub(crate) fn overload_accepts_self_type( + &self, + func: &Function, + tparams: Option<&TParams>, + self_type: &Type, + ) -> bool { + // Only instance methods have a `self` first parameter; static and + // class methods' first parameter is a regular argument. + if func.metadata.flags.is_staticmethod || func.metadata.flags.is_classmethod { + return true; + } + func.signature.get_first_param().is_none_or(|p| { + // Replace the overload's own type params in `self:` with `Any` + // (e.g. `self: Array[S, T]` -> `Array[Any, Any]`), matching against a gradual + // `self:` rather than a rigid, unsolvable variable. + let p = match tparams { + Some(tparams) => { + let any = self.heap.mk_any_implicit(); + p.clone() + .subst(&tparams.iter().map(|q| (q, &any)).collect()) + } + None => p.clone(), + }; + // A non-protocol `self:` can't re-enter protocol conformance, so check + // it directly. A protocol-typed `self:`, however, makes + // `is_subset_eq(self_type, p)` re-enter this same filtering on the same + // `(self_type, p)` pair — unbounded recursion for a self-referential + // protocol. Guard only that case coinductively: on re-entry + // of the same pair, assume the overload applies (keep it). + let p_is_protocol = matches!( + &p, + Type::ClassType(cls) if self.type_order().is_protocol(cls.class_object()) + ); + if !p_is_protocol { + return self.is_subset_eq(self_type, &p); + } + let key = (self_type.clone(), p.clone()); + if self.enter_overload_self_filter(key.clone()) { + return true; + } + let applies = self.is_subset_eq(self_type, &p); + self.exit_overload_self_filter(&key); + applies + }) + } + pub(crate) fn as_instance_attribute( &self, field_name: &Name, diff --git a/pyrefly/lib/alt/overload.rs b/pyrefly/lib/alt/overload.rs index 4fc549a628..6247f8e227 100644 --- a/pyrefly/lib/alt/overload.rs +++ b/pyrefly/lib/alt/overload.rs @@ -474,11 +474,17 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> { break; } } - // A unique arity match still supplies recovery when checking fails. - ( - closest_overload, - matched || arity_compatible_overloads.len() == 1, - ) + // A unique arity match still supplies recovery when checking fails. So does a + // call that fails only on `self`, since the overloads don't explain that failure. + // The overload's errors don't carry the call's context, though, so a call with a + // context (e.g. an operator) keeps the overload error, which does. + let matched = matched + || arity_compatible_overloads.len() == 1 + || (context.is_none() + && self_obj.as_ref().is_some_and(|self_obj| { + self.fails_only_on_self(&overloads, &closest_overload, self_obj) + })); + (closest_overload, matched) } }; @@ -630,6 +636,28 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> { } } + /// Whether the closest overload failed only because the receiver doesn't match a `self` + /// parameter that every overload shares. Such a failure is the same as for a non-overloaded + /// method, so it shouldn't be reported in terms of overloads. + fn fails_only_on_self( + &self, + overloads: &[TargetWithTParams], + closest_overload: &CalledOverload<'_>, + self_obj: &Type, + ) -> bool { + let self_param = closest_overload.func.1.signature.get_first_param(); + closest_overload.num_match_errors() == 1 + && self_param.is_some() + && overloads + .iter() + .all(|overload| overload.1.signature.get_first_param() == self_param) + && !self.overload_accepts_self_type( + &closest_overload.func.1, + closest_overload.func.0.as_deref(), + self_obj, + ) + } + fn arity_mismatch_size( &self, expected_arg_counts: &ArgCounts, 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/overload.rs b/pyrefly/lib/test/overload.rs index d73364f954..f7b8317c91 100644 --- a/pyrefly/lib/test/overload.rs +++ b/pyrefly/lib/test/overload.rs @@ -2343,6 +2343,40 @@ 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]): + # Only `self` is wrong, and every overload expects the same `self`, so there's no need to + # mention overloads. + assert_type(b.meth(1), int) # E: Argument `B` is not assignable to parameter `self` with type `A` in function `A.meth` + # The argument doesn't match any overload either. + b.meth(1.5) # E: No matching overload found for function `A.meth` + # The overloads expect different types of `self`, and another overload accepts `c`. + c.f(1) # E: No matching overload found for function `C.f` + "#, +); + testcase!( test_varargs_materialization, r#" From 0e2943e74bcaf401654e64c8e9294110d3b3be74 Mon Sep 17 00:00:00 2001 From: OverloadedTech Date: Tue, 17 Nov 2026 09:38:54 +0100 Subject: [PATCH 2/2] Bind the receiver before matching overloaded methods --- pyrefly/lib/alt/call.rs | 69 +++++++++++++++++++- pyrefly/lib/alt/class/class_field.rs | 90 +++++++++++--------------- pyrefly/lib/alt/function.rs | 30 +++++---- pyrefly/lib/alt/overload.rs | 38 ++--------- pyrefly/lib/test/generic_basic.rs | 2 +- pyrefly/lib/test/intersection_calls.rs | 4 +- pyrefly/lib/test/overload.rs | 13 ++-- 7 files changed, 139 insertions(+), 107 deletions(-) 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/class/class_field.rs b/pyrefly/lib/alt/class/class_field.rs index 9bf400bf25..c0edca13c6 100644 --- a/pyrefly/lib/alt/class/class_field.rs +++ b/pyrefly/lib/alt/class/class_field.rs @@ -3815,9 +3815,46 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> { .filter(|sig| { let (func, tparams) = match sig { OverloadType::Function(f) => (f, None), - OverloadType::Forall(forall) => (&forall.body, Some(&*forall.tparams)), + OverloadType::Forall(forall) => (&forall.body, Some(&forall.tparams)), }; - self.overload_accepts_self_type(func, tparams, self_type) + // Only instance methods have a `self` first parameter; static and + // class methods' first parameter is a regular argument. + if func.metadata.flags.is_staticmethod || func.metadata.flags.is_classmethod { + return true; + } + func.signature.get_first_param().is_none_or(|p| { + // Replace the overload's own type params in `self:` with `Any` + // (e.g. `self: Array[S, T]` -> `Array[Any, Any]`), matching against a gradual + // `self:` rather than a rigid, unsolvable variable. + let p = match tparams { + Some(tparams) => { + let any = self.heap.mk_any_implicit(); + p.clone() + .subst(&tparams.iter().map(|q| (q, &any)).collect()) + } + None => p.clone(), + }; + // A non-protocol `self:` can't re-enter protocol conformance, so check + // it directly. A protocol-typed `self:`, however, makes + // `is_subset_eq(self_type, p)` re-enter this same filtering on the same + // `(self_type, p)` pair — unbounded recursion for a self-referential + // protocol. Guard only that case coinductively: on re-entry + // of the same pair, assume the overload applies (keep it). + let p_is_protocol = matches!( + &p, + Type::ClassType(cls) if self.type_order().is_protocol(cls.class_object()) + ); + if !p_is_protocol { + return self.is_subset_eq(self_type, &p); + } + let key = (self_type.clone(), p.clone()); + if self.enter_overload_self_filter(key.clone()) { + return true; + } + let applies = self.is_subset_eq(self_type, &p); + self.exit_overload_self_filter(&key); + applies + }) }) .cloned() .collect(); @@ -3832,55 +3869,6 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> { None } - /// Whether the receiver `self_type` is compatible with an overload signature's `self` - /// parameter. Static methods, class methods, and signatures without parameters accept any - /// receiver. - pub(crate) fn overload_accepts_self_type( - &self, - func: &Function, - tparams: Option<&TParams>, - self_type: &Type, - ) -> bool { - // Only instance methods have a `self` first parameter; static and - // class methods' first parameter is a regular argument. - if func.metadata.flags.is_staticmethod || func.metadata.flags.is_classmethod { - return true; - } - func.signature.get_first_param().is_none_or(|p| { - // Replace the overload's own type params in `self:` with `Any` - // (e.g. `self: Array[S, T]` -> `Array[Any, Any]`), matching against a gradual - // `self:` rather than a rigid, unsolvable variable. - let p = match tparams { - Some(tparams) => { - let any = self.heap.mk_any_implicit(); - p.clone() - .subst(&tparams.iter().map(|q| (q, &any)).collect()) - } - None => p.clone(), - }; - // A non-protocol `self:` can't re-enter protocol conformance, so check - // it directly. A protocol-typed `self:`, however, makes - // `is_subset_eq(self_type, p)` re-enter this same filtering on the same - // `(self_type, p)` pair — unbounded recursion for a self-referential - // protocol. Guard only that case coinductively: on re-entry - // of the same pair, assume the overload applies (keep it). - let p_is_protocol = matches!( - &p, - Type::ClassType(cls) if self.type_order().is_protocol(cls.class_object()) - ); - if !p_is_protocol { - return self.is_subset_eq(self_type, &p); - } - let key = (self_type.clone(), p.clone()); - if self.enter_overload_self_filter(key.clone()) { - return true; - } - let applies = self.is_subset_eq(self_type, &p); - self.exit_overload_self_filter(&key); - applies - }) - } - pub(crate) fn as_instance_attribute( &self, field_name: &Name, 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/alt/overload.rs b/pyrefly/lib/alt/overload.rs index a0a216f59c..f827a0a00b 100644 --- a/pyrefly/lib/alt/overload.rs +++ b/pyrefly/lib/alt/overload.rs @@ -496,17 +496,11 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> { break; } } - // A unique arity match still supplies recovery when checking fails. So does a - // call that fails only on `self`, since the overloads don't explain that failure. - // The overload's errors don't carry the call's context, though, so a call with a - // context (e.g. an operator) keeps the overload error, which does. - let matched = matched - || arity_compatible_overloads.len() == 1 - || (context.is_none() - && self_obj.as_ref().is_some_and(|self_obj| { - self.fails_only_on_self(&overloads, &closest_overload, self_obj) - })); - (closest_overload, matched) + // A unique arity match still supplies recovery when checking fails. + ( + closest_overload, + matched || arity_compatible_overloads.len() == 1, + ) } }; @@ -660,28 +654,6 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> { } } - /// Whether the closest overload failed only because the receiver doesn't match a `self` - /// parameter that every overload shares. Such a failure is the same as for a non-overloaded - /// method, so it shouldn't be reported in terms of overloads. - fn fails_only_on_self( - &self, - overloads: &[TargetWithTParams], - closest_overload: &CalledOverload<'_>, - self_obj: &Type, - ) -> bool { - let self_param = closest_overload.func.1.signature.get_first_param(); - closest_overload.num_match_errors() == 1 - && self_param.is_some() - && overloads - .iter() - .all(|overload| overload.1.signature.get_first_param() == self_param) - && !self.overload_accepts_self_type( - &closest_overload.func.1, - closest_overload.func.0.as_deref(), - self_obj, - ) - } - fn arity_mismatch_size( &self, expected_arg_counts: &ArgCounts, 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 313268f520..80e37301f1 100644 --- a/pyrefly/lib/test/overload.rs +++ b/pyrefly/lib/test/overload.rs @@ -2552,14 +2552,13 @@ class C[T]: def f(self: C[str], x: str) -> str: ... def f(self, x: int | str) -> int | str: ... -def test(b: B, c: C[str]): - # Only `self` is wrong, and every overload expects the same `self`, so there's no need to - # mention overloads. +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` - # The argument doesn't match any overload either. - b.meth(1.5) # E: No matching overload found for function `A.meth` - # The overloads expect different types of `self`, and another overload accepts `c`. - c.f(1) # E: No matching overload found for function `C.f` + 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]` "#, );