Skip to content

Commit df852c0

Browse files
committed
Suggest appropriate code for unused field when desrtucturing patttern
Fix rust-lang#56472.
1 parent c1d2d83 commit df852c0

File tree

3 files changed

+54
-1
lines changed

3 files changed

+54
-1
lines changed

src/librustc/middle/liveness.rs

+14-1
Original file line numberDiff line numberDiff line change
@@ -379,9 +379,22 @@ fn visit_fn<'a, 'tcx: 'a>(ir: &mut IrMaps<'a, 'tcx>,
379379
let body = ir.tcx.hir().body(body_id);
380380

381381
for arg in &body.arguments {
382+
let is_shorthand = match arg.pat.node {
383+
crate::hir::PatKind::Struct(..) => true,
384+
_ => false,
385+
};
382386
arg.pat.each_binding(|_bm, hir_id, _x, ident| {
383387
debug!("adding argument {:?}", hir_id);
384-
fn_maps.add_variable(Arg(hir_id, ident.name));
388+
let var = if is_shorthand {
389+
Local(LocalInfo {
390+
id: hir_id,
391+
name: ident.name,
392+
is_shorthand: true,
393+
})
394+
} else {
395+
Arg(hir_id, ident.name)
396+
};
397+
fn_maps.add_variable(var);
385398
})
386399
};
387400

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
#![deny(unused_variables)]
2+
3+
struct Point {
4+
x: i32,
5+
y: i32,
6+
}
7+
8+
fn main() {
9+
let points = vec!(Point { x: 1, y: 2 }, Point { x: 3, y: 4 });
10+
11+
let _: i32 = points.iter()
12+
.map(|Point { x, y }| y)
13+
//~^ ERROR unused variable
14+
.sum();
15+
16+
let _: i32 = points.iter()
17+
.map(|x| 4)
18+
//~^ ERROR unused variable
19+
.sum();
20+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
error: unused variable: `x`
2+
--> $DIR/unused-closure-argument.rs:12:23
3+
|
4+
LL | .map(|Point { x, y }| y)
5+
| ^ help: try ignoring the field: `x: _`
6+
|
7+
note: lint level defined here
8+
--> $DIR/unused-closure-argument.rs:1:9
9+
|
10+
LL | #![deny(unused_variables)]
11+
| ^^^^^^^^^^^^^^^^
12+
13+
error: unused variable: `x`
14+
--> $DIR/unused-closure-argument.rs:17:15
15+
|
16+
LL | .map(|x| 4)
17+
| ^ help: consider prefixing with an underscore: `_x`
18+
19+
error: aborting due to 2 previous errors
20+

0 commit comments

Comments
 (0)