Skip to content

Emit a lint for unused assign to temporary variables #71681

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
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
51 changes: 51 additions & 0 deletions src/librustc_typeck/check/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ use rustc_middle::ty::adjustment::{
use rustc_middle::ty::Ty;
use rustc_middle::ty::TypeFoldable;
use rustc_middle::ty::{AdtKind, Visibility};
use rustc_session::lint::builtin::UNUSED_ASSIGNMENTS;
use rustc_span::hygiene::DesugaringKind;
use rustc_span::source_map::Span;
use rustc_span::symbol::{kw, sym, Symbol};
Expand Down Expand Up @@ -800,13 +801,63 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {

self.require_type_is_sized(lhs_ty, lhs.span, traits::AssignmentLhsSized);

self.check_unused_assign_to_field(lhs, span);

if lhs_ty.references_error() || rhs_ty.references_error() {
self.tcx.types.err
} else {
self.tcx.mk_unit()
}
}

/// Check the LHS for unused assignments to fields, when they aren't bound to a local variable
pub(crate) fn check_unused_assign_to_field(
&self,
lhs: &'tcx hir::Expr<'tcx>,
expr_span: &Span,
) {
debug!("check_unused_assign(lhs = {:?})", &lhs);
match lhs.kind {
ExprKind::Struct(..) | ExprKind::Tup(..) => {
self.tcx.struct_span_lint_hir(UNUSED_ASSIGNMENTS, lhs.hir_id, *expr_span, |lint| {
lint.build("unused assignement to temporary")
.span_label(lhs.span, "this is not bound to any variable")
.emit();
})
}
// Assigning to a field of a const is useless, since the constant will
// get evaluated and injected into the expression
ExprKind::Path(QPath::Resolved(
_,
hir::Path { res: Res::Def(DefKind::Const, _), ref segments, .. },
)) => {
let const_name = segments.last().unwrap().ident.as_str();
let mut path_str = String::new();
for (i, seg) in segments.iter().enumerate() {
if i > 0 {
path_str.push_str("::");
}
if seg.ident.name != kw::PathRoot {
path_str.push_str(&seg.ident.as_str());
}
}
Comment on lines +835 to +843
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Is there any existing function that does this? I tried to search but didn't find anything but in rustdoc (which I... err... copy-pasted 😄)

Copy link
Contributor

Choose a reason for hiding this comment

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

Isn't the hir::Path itself already printable? You can use @ to bind the entire path while also keeping the filtering and reference to segments.


self.tcx.struct_span_lint_hir(UNUSED_ASSIGNMENTS, lhs.hir_id, *expr_span, |lint| {
lint.build("unused assignement to temporary")
.span_label(lhs.span, "this is not bound to any variable")
.note("in Rust, constants are not associated with a specific memory location, and are inlined wherever they are used")
.span_suggestion(
Copy link
Contributor

Choose a reason for hiding this comment

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

Can we change this to be span_suggestion_verbose? This will make the suggestion not be a label, but show you the final code instead.

lhs.span.shrink_to_lo(),
"consider introducing a local variable",
format!("let mut {} = {};", (&*const_name).to_lowercase(), path_str), Applicability::MaybeIncorrect)
.emit();
})
}
ExprKind::Field(ref base, _) => self.check_unused_assign_to_field(base, expr_span),
_ => {}
}
}

fn check_expr_loop(
&self,
body: &'tcx hir::Block<'tcx>,
Expand Down
1 change: 1 addition & 0 deletions src/librustc_typeck/check/op.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
};

self.check_lhs_assignable(lhs, "E0067", &op.span);
self.check_unused_assign_to_field(lhs, &op.span);

ty
}
Expand Down
34 changes: 34 additions & 0 deletions src/test/ui/unused/unused-field-assign.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#![deny(unused_assignments)]

struct Foo {
x: i16
}

const FOO: Foo = Foo { x: 1 };
const BAR: (i16, bool) = (2, false);

fn main() {
Foo { x: 2 }.x = 3;
//~^ ERROR unused assignement to temporary
Foo { x: 2 }.x += 1;
//~^ ERROR unused assignement to temporary

(2, 12).0 += 10;
//~^ ERROR unused assignement to temporary
(10, false).1 = true;
//~^ ERROR unused assignement to temporary

FOO.x = 2;
//~^ ERROR unused assignement to temporary
//~| HELP consider introducing a local variable
FOO.x -= 6;
//~^ ERROR unused assignement to temporary
//~| HELP consider introducing a local variable

BAR.1 = true;
//~^ ERROR unused assignement to temporary
//~| HELP consider introducing a local variable
BAR.0 *= 2;
//~^ ERROR unused assignement to temporary
//~| HELP consider introducing a local variable
}
84 changes: 84 additions & 0 deletions src/test/ui/unused/unused-field-assign.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
error: unused assignement to temporary
--> $DIR/unused-field-assign.rs:11:20
|
LL | Foo { x: 2 }.x = 3;
| ------------ ^
| |
| this is not bound to any variable
|
note: the lint level is defined here
--> $DIR/unused-field-assign.rs:1:9
|
LL | #![deny(unused_assignments)]
| ^^^^^^^^^^^^^^^^^^

error: unused assignement to temporary
--> $DIR/unused-field-assign.rs:13:20
|
LL | Foo { x: 2 }.x += 1;
| ------------ ^^
| |
| this is not bound to any variable

error: unused assignement to temporary
--> $DIR/unused-field-assign.rs:16:15
|
LL | (2, 12).0 += 10;
| ------- ^^
| |
| this is not bound to any variable

error: unused assignement to temporary
--> $DIR/unused-field-assign.rs:18:19
|
LL | (10, false).1 = true;
| ----------- ^
| |
| this is not bound to any variable

error: unused assignement to temporary
--> $DIR/unused-field-assign.rs:21:11
|
LL | FOO.x = 2;
| --- ^
| |
| this is not bound to any variable
| help: consider introducing a local variable: `let mut foo = FOO;`
Copy link
Contributor

Choose a reason for hiding this comment

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

This will cause the final code applied by rustfix to be let mut foo = FOO;.x = 2;, which is incorrect.

|
= note: in Rust, constants are not associated with a specific memory location, and are inlined wherever they are used

error: unused assignement to temporary
--> $DIR/unused-field-assign.rs:24:11
|
LL | FOO.x -= 6;
| --- ^^
| |
| this is not bound to any variable
| help: consider introducing a local variable: `let mut foo = FOO;`
|
= note: in Rust, constants are not associated with a specific memory location, and are inlined wherever they are used

error: unused assignement to temporary
--> $DIR/unused-field-assign.rs:28:11
|
LL | BAR.1 = true;
| --- ^
| |
| this is not bound to any variable
| help: consider introducing a local variable: `let mut bar = BAR;`
|
= note: in Rust, constants are not associated with a specific memory location, and are inlined wherever they are used

error: unused assignement to temporary
--> $DIR/unused-field-assign.rs:31:11
|
LL | BAR.0 *= 2;
| --- ^^
| |
| this is not bound to any variable
| help: consider introducing a local variable: `let mut bar = BAR;`
|
= note: in Rust, constants are not associated with a specific memory location, and are inlined wherever they are used

error: aborting due to 8 previous errors