Skip to content

Commit 774ba83

Browse files
authored
Rollup merge of #81473 - sanxiyn:write-only-field, r=oli-obk
Warn write-only fields cc `@Boscop's` example in #49256.
2 parents fe27dea + 85ad773 commit 774ba83

File tree

4 files changed

+62
-0
lines changed

4 files changed

+62
-0
lines changed

compiler/rustc_passes/src/dead.rs

+15
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,15 @@ fn should_explore(tcx: TyCtxt<'_>, hir_id: hir::HirId) -> bool {
3737
)
3838
}
3939

40+
fn base_expr<'a>(mut expr: &'a hir::Expr<'a>) -> &'a hir::Expr<'a> {
41+
loop {
42+
match expr.kind {
43+
hir::ExprKind::Field(base, ..) => expr = base,
44+
_ => return expr,
45+
}
46+
}
47+
}
48+
4049
struct MarkSymbolVisitor<'tcx> {
4150
worklist: Vec<hir::HirId>,
4251
tcx: TyCtxt<'tcx>,
@@ -263,6 +272,12 @@ impl<'tcx> Visitor<'tcx> for MarkSymbolVisitor<'tcx> {
263272
hir::ExprKind::MethodCall(..) => {
264273
self.lookup_and_handle_method(expr.hir_id);
265274
}
275+
hir::ExprKind::Assign(ref left, ref right, ..) => {
276+
// Ignore write to field
277+
self.visit_expr(base_expr(left));
278+
self.visit_expr(right);
279+
return;
280+
}
266281
hir::ExprKind::Field(ref lhs, ..) => {
267282
self.handle_field_access(&lhs, expr.hir_id);
268283
}

src/test/ui/borrowck/borrowck-assign-to-subfield.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// run-pass
22
// pretty-expanded FIXME #23616
3+
#![allow(dead_code)]
34

45
pub fn main() {
56
struct A {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
#![deny(dead_code)]
2+
3+
struct S {
4+
f: i32, //~ ERROR: field is never read
5+
sub: Sub, //~ ERROR: field is never read
6+
}
7+
8+
struct Sub {
9+
f: i32, //~ ERROR: field is never read
10+
}
11+
12+
fn field_write(s: &mut S) {
13+
s.f = 1;
14+
s.sub.f = 2;
15+
}
16+
17+
fn main() {
18+
let mut s = S { f: 0, sub: Sub { f: 0 } };
19+
field_write(&mut s);
20+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
error: field is never read: `f`
2+
--> $DIR/write-only-field.rs:4:5
3+
|
4+
LL | f: i32,
5+
| ^^^^^^
6+
|
7+
note: the lint level is defined here
8+
--> $DIR/write-only-field.rs:1:9
9+
|
10+
LL | #![deny(dead_code)]
11+
| ^^^^^^^^^
12+
13+
error: field is never read: `sub`
14+
--> $DIR/write-only-field.rs:5:5
15+
|
16+
LL | sub: Sub,
17+
| ^^^^^^^^
18+
19+
error: field is never read: `f`
20+
--> $DIR/write-only-field.rs:9:5
21+
|
22+
LL | f: i32,
23+
| ^^^^^^
24+
25+
error: aborting due to 3 previous errors
26+

0 commit comments

Comments
 (0)