Skip to content
Open
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
67 changes: 67 additions & 0 deletions pyrefly/lib/alt/class/class_field.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3165,6 +3165,7 @@ impl<'a, Ans: LookupAnswer> AnswersSolver<'a, Ans> {
}
attr
};
let want_attribute = self.filter_overloads_for_override(want_attribute, cls);
if got_attribute.is_none() {
// Optimisation: Only compute the `got_attr` once, and only if we actually need it.
got_attribute = Some(self.as_instance_attribute(
Expand Down Expand Up @@ -4239,6 +4240,72 @@ impl<'a, Ans: LookupAnswer> AnswersSolver<'a, Ans> {
}
}

/// Filter out overloads from a parent's attribute whose `self` parameter type is
/// incompatible with the child class. This prevents false positive `bad-override` errors
/// when the parent has overloads specialized on `self` types (e.g., `LiteralString`) that
/// don't apply to the child class.
fn filter_overloads_for_override(
&self,
attr: ClassAttribute,
child_cls: &Class,
) -> ClassAttribute {
let child_type = self
.heap
.mk_class_type(self.as_class_type_unchecked(child_cls));
let filter_type = |ty: Type| -> Type {
match ty {
Type::BoundMethod(box BoundMethod {
obj,
func: BoundMethodType::Overload(overload),
}) => {
let dominated: Vec<usize> = overload
.signatures
.iter()
.enumerate()
.filter(|(_, sig)| {
matches!(sig, OverloadType::Function(f)
if f.signature.get_first_param()
.is_some_and(|param| !self.is_subset_eq(&child_type, &param)))
})
.map(|(i, _)| i)
.collect();
if dominated.is_empty() || dominated.len() == overload.signatures.len() {
BoundMethod {
obj,
func: BoundMethodType::Overload(overload),
}
.as_type()
} else {
let signatures = overload
.signatures
.into_iter()
.enumerate()
.filter(|(i, _)| !dominated.contains(i))
.map(|(_, sig)| sig)
.collect::<Vec<_>>();
BoundMethod {
obj,
func: BoundMethodType::Overload(Overload {
signatures: vec1::Vec1::try_from_vec(signatures)
.expect("at least one overload remains after filtering"),
metadata: overload.metadata,
}),
}
.as_type()
}
}
other => other,
}
};
match attr {
ClassAttribute::ReadWrite(ty) => ClassAttribute::ReadWrite(filter_type(ty)),
ClassAttribute::ReadOnly(ty, reason) => {
ClassAttribute::ReadOnly(filter_type(ty), reason)
}
other => other,
}
}

pub fn is_class_attribute_subset(
&self,
got: &ClassAttribute,
Expand Down
9 changes: 9 additions & 0 deletions pyrefly/lib/test/class_overrides.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1296,3 +1296,12 @@ class B(A):
return 100
"#,
);

testcase!(
test_override_str_subclass_with_optional_param,
r#"
class MyString(str):
def upper(self, locale: str = "en") -> str:
return super().upper()
"#,
);
Loading