Skip to content

fix: add fallback case in generated PartialEq impl #13732

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Dec 12, 2022
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -907,7 +907,34 @@ impl PartialEq for Foo {
}

#[test]
fn add_custom_impl_partial_eq_tuple_enum() {
fn add_custom_impl_partial_eq_single_variant_tuple_enum() {
check_assist(
replace_derive_with_manual_impl,
r#"
//- minicore: eq, derive
#[derive(Partial$0Eq)]
enum Foo {
Bar(String),
}
"#,
r#"
enum Foo {
Bar(String),
}

impl PartialEq for Foo {
$0fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Bar(l0), Self::Bar(r0)) => l0 == r0,
}
}
}
"#,
)
}

#[test]
fn add_custom_impl_partial_eq_partial_tuple_enum() {
check_assist(
replace_derive_with_manual_impl,
r#"
Expand Down Expand Up @@ -936,6 +963,37 @@ impl PartialEq for Foo {
)
}

#[test]
fn add_custom_impl_partial_eq_tuple_enum() {
check_assist(
replace_derive_with_manual_impl,
r#"
//- minicore: eq, derive
#[derive(Partial$0Eq)]
enum Foo {
Bar(String),
Baz(i32),
}
"#,
r#"
enum Foo {
Bar(String),
Baz(i32),
}

impl PartialEq for Foo {
$0fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Bar(l0), Self::Bar(r0)) => l0 == r0,
(Self::Baz(l0), Self::Baz(r0)) => l0 == r0,
_ => false,
}
}
}
"#,
)
}

#[test]
fn add_custom_impl_partial_eq_record_enum() {
check_assist(
Expand Down
14 changes: 11 additions & 3 deletions crates/ide-assists/src/utils/gen_trait_fn_body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -516,10 +516,18 @@ fn gen_partial_eq(adt: &ast::Adt, func: &ast::Fn) -> Option<()> {

let expr = match arms.len() {
0 => eq_check,
_ => {
if n_cases > arms.len() {
arms_len => {
// Generate the fallback arm when this enum has >1 variants.
// The fallback arm will be `_ => false,` if we've already gone through every case where the variants of self and other match,
// and `_ => std::mem::discriminant(self) == std::mem::discriminant(other),` otherwise.
if n_cases > 1 {
let lhs = make::wildcard_pat().into();
arms.push(make::match_arm(Some(lhs), None, eq_check));
let rhs = if arms_len == n_cases {
make::expr_literal("false").into()
} else {
eq_check
};
arms.push(make::match_arm(Some(lhs), None, rhs));
}

let match_target = make::expr_tuple(vec![lhs_name, rhs_name]);
Expand Down