Skip to content
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

Warn write-only fields #81473

Merged
merged 3 commits into from
Jan 30, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
19 changes: 19 additions & 0 deletions compiler/rustc_passes/src/dead.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,19 @@ fn should_explore(tcx: TyCtxt<'_>, hir_id: hir::HirId) -> bool {
)
}

fn base_expr<'a>(expr: &'a hir::Expr<'a>) -> &'a hir::Expr<'a> {
let mut current = expr;
loop {
match current.kind {
hir::ExprKind::Field(base, ..) => {
current = base;
}
_ => break,
}
}
current
sanxiyn marked this conversation as resolved.
Show resolved Hide resolved
}

struct MarkSymbolVisitor<'tcx> {
worklist: Vec<hir::HirId>,
tcx: TyCtxt<'tcx>,
Expand Down Expand Up @@ -263,6 +276,12 @@ impl<'tcx> Visitor<'tcx> for MarkSymbolVisitor<'tcx> {
hir::ExprKind::MethodCall(..) => {
self.lookup_and_handle_method(expr.hir_id);
}
hir::ExprKind::Assign(ref left, ref right, ..) => {
// Ignore write to field
self.visit_expr(base_expr(left));
self.visit_expr(right);
return;
}
hir::ExprKind::Field(ref lhs, ..) => {
self.handle_field_access(&lhs, expr.hir_id);
}
Expand Down
1 change: 1 addition & 0 deletions src/test/ui/borrowck/borrowck-assign-to-subfield.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// run-pass
// pretty-expanded FIXME #23616
#![allow(dead_code)]

pub fn main() {
struct A {
Expand Down
20 changes: 20 additions & 0 deletions src/test/ui/lint/dead-code/write-only-field.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#![deny(dead_code)]

struct S {
f: i32, //~ ERROR: field is never read
sub: Sub, //~ ERROR: field is never read
}

struct Sub {
f: i32, //~ ERROR: field is never read
}

fn field_write(s: &mut S) {
s.f = 1;
s.sub.f = 2;
}

fn main() {
let mut s = S { f: 0, sub: Sub { f: 0 } };
field_write(&mut s);
}
26 changes: 26 additions & 0 deletions src/test/ui/lint/dead-code/write-only-field.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
error: field is never read: `f`
--> $DIR/write-only-field.rs:4:5
|
LL | f: i32,
| ^^^^^^
|
note: the lint level is defined here
--> $DIR/write-only-field.rs:1:9
|
LL | #![deny(dead_code)]
| ^^^^^^^^^

error: field is never read: `sub`
--> $DIR/write-only-field.rs:5:5
|
LL | sub: Sub,
| ^^^^^^^^

error: field is never read: `f`
--> $DIR/write-only-field.rs:9:5
|
LL | f: i32,
| ^^^^^^

error: aborting due to 3 previous errors