From 98f4b20abc9ad5ff77874119bbec305f4c7c6226 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sat, 3 Sep 2022 19:13:17 +0000 Subject: [PATCH] Also suggest dereferencing LHS when both &mut T and T are valid binop LHS --- compiler/rustc_typeck/src/check/op.rs | 8 ++++++++ .../ui/typeck/assign-non-lval-needs-deref.rs | 19 +++++++++++++++++++ .../typeck/assign-non-lval-needs-deref.stderr | 16 ++++++++++++++++ 3 files changed, 43 insertions(+) create mode 100644 src/test/ui/typeck/assign-non-lval-needs-deref.rs create mode 100644 src/test/ui/typeck/assign-non-lval-needs-deref.stderr diff --git a/compiler/rustc_typeck/src/check/op.rs b/compiler/rustc_typeck/src/check/op.rs index d51dccd1af5..0d9dbb5bc11 100644 --- a/compiler/rustc_typeck/src/check/op.rs +++ b/compiler/rustc_typeck/src/check/op.rs @@ -70,6 +70,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .is_err() { err.downgrade_to_delayed_bug(); + } else { + // Otherwise, it's valid to suggest dereferencing the LHS here. + err.span_suggestion_verbose( + lhs.span.shrink_to_lo(), + "consider dereferencing the left-hand side of this operation", + "*", + Applicability::MaybeIncorrect, + ); } } } diff --git a/src/test/ui/typeck/assign-non-lval-needs-deref.rs b/src/test/ui/typeck/assign-non-lval-needs-deref.rs new file mode 100644 index 00000000000..c979d76b4f4 --- /dev/null +++ b/src/test/ui/typeck/assign-non-lval-needs-deref.rs @@ -0,0 +1,19 @@ +// issue #101376 + +use std::ops::AddAssign; +struct Foo; + +impl AddAssign<()> for Foo { + fn add_assign(&mut self, _: ()) {} +} + +impl AddAssign<()> for &mut Foo { + fn add_assign(&mut self, _: ()) {} +} + +fn main() { + (&mut Foo) += (); + //~^ ERROR invalid left-hand side of assignment + //~| NOTE cannot assign to this expression + //~| HELP consider dereferencing the left-hand side of this operation +} diff --git a/src/test/ui/typeck/assign-non-lval-needs-deref.stderr b/src/test/ui/typeck/assign-non-lval-needs-deref.stderr new file mode 100644 index 00000000000..ee83b145321 --- /dev/null +++ b/src/test/ui/typeck/assign-non-lval-needs-deref.stderr @@ -0,0 +1,16 @@ +error[E0067]: invalid left-hand side of assignment + --> $DIR/assign-non-lval-needs-deref.rs:15:16 + | +LL | (&mut Foo) += (); + | ---------- ^^ + | | + | cannot assign to this expression + | +help: consider dereferencing the left-hand side of this operation + | +LL | *(&mut Foo) += (); + | + + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0067`.