Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 68 additions & 1 deletion pyrefly/lib/alt/call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
30 changes: 18 additions & 12 deletions pyrefly/lib/alt/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion pyrefly/lib/test/decorators.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
"#,
);

Expand Down
2 changes: 1 addition & 1 deletion pyrefly/lib/test/generic_basic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`
"#,
);

Expand Down
4 changes: 2 additions & 2 deletions pyrefly/lib/test/intersection_calls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
33 changes: 33 additions & 0 deletions pyrefly/lib/test/overload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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#"
Expand Down
Loading