Skip to content

Suggest implementing #[derive(PartialEq)] for types in vectors and arrays #95371

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

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
60 changes: 38 additions & 22 deletions compiler/rustc_typeck/src/check/method/suggest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1270,30 +1270,45 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
None
}

fn get_trait_ref_self_type(&self, trait_pred: ty::TraitPredicate<'tcx>) -> Ty<'tcx> {
fn get_self_type<'a>(tcx: TyCtxt<'_>, ty: Ty<'a>) -> Ty<'a> {
match ty.kind() {
ty::Adt(def, subs) => {
if tcx.is_diagnostic_item(sym::Vec, def.did()) {
return get_self_type(tcx, subs.type_at(0));
}
ty
}
ty::Array(ty, _) => {
return get_self_type(tcx, *ty);
}
_ => ty,
}
}

if Some(trait_pred.trait_ref.def_id) == self.tcx.lang_items().eq_trait() {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you leave a comment for what this function does? Also a comment explaining the special casing just for Eq. Alternatively, we could think of some way to generalize this?

Copy link
Member Author

@TaKO8Ki TaKO8Ki Mar 29, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm. In case of PartialOrd, rustc properly explains why xs can't be compared with [X, X, X].

fn main() {
    struct X;
    let xs = [X, X, X];
    let eq = xs > [X, X, X];
}

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=7115dbcd188f44a242ba8640347bbfe3

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it possible to implement the PartialEq suggestion by re-using the code for PartialOrd?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. I'm going to do it.

get_self_type(self.tcx, trait_pred.self_ty())
} else {
trait_pred.self_ty()
}
}

crate fn note_unmet_impls_on_type(
&self,
err: &mut Diagnostic,
errors: Vec<FulfillmentError<'tcx>>,
) {
let all_local_types_needing_impls =
errors.iter().all(|e| match e.obligation.predicate.kind().skip_binder() {
ty::PredicateKind::Trait(pred) => match pred.self_ty().kind() {
ty::Adt(def, _) => def.did().is_local(),
_ => false,
},
_ => false,
});
let mut preds: Vec<_> = errors
let mut preds_and_self_types: Vec<_> = errors
.iter()
.filter_map(|e| match e.obligation.predicate.kind().skip_binder() {
ty::PredicateKind::Trait(pred) => Some(pred),
ty::PredicateKind::Trait(pred) => Some((pred, self.get_trait_ref_self_type(pred))),
_ => None,
})
.collect();
preds.sort_by_key(|pred| (pred.def_id(), pred.self_ty()));
let def_ids = preds
preds_and_self_types.sort_by_key(|(pred, self_ty)| (pred.def_id(), *self_ty));
let def_ids = preds_and_self_types
.iter()
.filter_map(|pred| match pred.self_ty().kind() {
.filter_map(|(_, ty)| match ty.kind() {
ty::Adt(def, _) => Some(def.did()),
_ => None,
})
Expand All @@ -1308,8 +1323,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
.collect::<Vec<_>>()
.into();

for pred in &preds {
match pred.self_ty().kind() {
for (pred, ty) in &preds_and_self_types {
match ty.kind() {
ty::Adt(def, _) => {
spans.push_span_label(
sm.guess_head_span(self.tcx.def_span(def.did())),
Expand All @@ -1320,20 +1335,20 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}
}

if all_local_types_needing_impls && spans.primary_span().is_some() {
let msg = if preds.len() == 1 {
if def_ids.iter().all(|did| did.is_local()) && spans.primary_span().is_some() {
let msg = if preds_and_self_types.len() == 1 {
format!(
"an implementation of `{}` might be missing for `{}`",
preds[0].trait_ref.print_only_trait_path(),
preds[0].self_ty()
preds_and_self_types[0].0.trait_ref.print_only_trait_path(),
preds_and_self_types[0].1
)
} else {
format!(
"the following type{} would have to `impl` {} required trait{} for this \
operation to be valid",
pluralize!(def_ids.len()),
if def_ids.len() == 1 { "its" } else { "their" },
pluralize!(preds.len()),
pluralize!(preds_and_self_types.len()),
)
};
err.span_note(spans, &msg);
Expand All @@ -1359,7 +1374,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let mut traits = Vec::<Span>::new();
for (pred, _, _) in unsatisfied_predicates {
let ty::PredicateKind::Trait(trait_pred) = pred.kind().skip_binder() else { continue };
let adt = match trait_pred.self_ty().ty_adt_def() {
let self_ty = self.get_trait_ref_self_type(trait_pred);
let adt = match self_ty.ty_adt_def() {
Some(adt) if adt.did().is_local() => adt,
_ => continue,
};
Expand All @@ -1377,7 +1393,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
_ => false,
};
if can_derive {
let self_name = trait_pred.self_ty().to_string();
let self_name = self_ty.to_string();
let self_span = self.tcx.def_span(adt.did());
if let Some(poly_trait_ref) = pred.to_opt_poly_trait_pred() {
for super_trait in supertraits(self.tcx, poly_trait_ref.to_poly_trait_ref())
Expand Down
8 changes: 8 additions & 0 deletions src/test/ui/binop/binop-on-array-and-vector.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
fn main() {
struct X;
let foo = [X, X, X];
foo == [X, X, X]; //~ ERROR binary operation `==` cannot be applied to type `[X; 3]` [E0369]

let bar = vec![X, X, X];
bar == [X, X, X]; //~ ERROR binary operation `==` cannot be applied to type `Vec<X>` [E0369]
}
39 changes: 39 additions & 0 deletions src/test/ui/binop/binop-on-array-and-vector.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
error[E0369]: binary operation `==` cannot be applied to type `[X; 3]`
--> $DIR/binop-on-array-and-vector.rs:4:9
|
LL | foo == [X, X, X];
| --- ^^ --------- [X; 3]
| |
| [X; 3]
|
note: an implementation of `PartialEq<_>` might be missing for `X`
--> $DIR/binop-on-array-and-vector.rs:2:5
|
LL | struct X;
| ^^^^^^^^^ must implement `PartialEq<_>`
help: consider annotating `X` with `#[derive(PartialEq)]`
|
LL | #[derive(PartialEq)]
|

error[E0369]: binary operation `==` cannot be applied to type `Vec<X>`
--> $DIR/binop-on-array-and-vector.rs:7:9
|
LL | bar == [X, X, X];
| --- ^^ --------- [X; 3]
| |
| Vec<X>
|
note: an implementation of `PartialEq<_>` might be missing for `X`
--> $DIR/binop-on-array-and-vector.rs:2:5
|
LL | struct X;
| ^^^^^^^^^ must implement `PartialEq<_>`
help: consider annotating `X` with `#[derive(PartialEq)]`
|
LL | #[derive(PartialEq)]
|

error: aborting due to 2 previous errors

For more information about this error, try `rustc --explain E0369`.