Skip to content

Commit 46fe8e9

Browse files
Don't warn on unused field on union
1 parent 5a5a32a commit 46fe8e9

File tree

3 files changed

+58
-3
lines changed

3 files changed

+58
-3
lines changed

src/librustc/middle/dead.rs

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
// from live codes are live, and everything else is dead.
1414

1515
use hir::map as hir_map;
16-
use hir::{self, PatKind};
16+
use hir::{self, Item_, PatKind};
1717
use hir::intravisit::{self, Visitor, NestedVisitorMap};
1818
use hir::itemlikevisit::ItemLikeVisitor;
1919

@@ -558,8 +558,20 @@ impl<'a, 'tcx> Visitor<'tcx> for DeadVisitor<'a, 'tcx> {
558558

559559
fn visit_struct_field(&mut self, field: &'tcx hir::StructField) {
560560
if self.should_warn_about_field(&field) {
561-
self.warn_dead_code(field.id, field.span,
562-
field.name, "field");
561+
let did = self.tcx.hir.get_parent_did(field.id);
562+
if if let Some(node_id) = self.tcx.hir.as_local_node_id(did) {
563+
match self.tcx.hir.find(node_id) {
564+
Some(hir_map::NodeItem(item)) => match item.node {
565+
Item_::ItemUnion(_, _) => false,
566+
_ => true,
567+
},
568+
_ => true,
569+
}
570+
} else {
571+
true
572+
} {
573+
self.warn_dead_code(field.id, field.span, field.name, "field");
574+
}
563575
}
564576

565577
intravisit::walk_struct_field(self, field);

src/test/ui/union-fields.rs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
#![deny(dead_code)]
12+
13+
union U {
14+
x: u32,
15+
y: f32,
16+
}
17+
18+
struct V {
19+
x: u32,
20+
y: u32,
21+
}
22+
23+
fn main() {
24+
let u = U { x: 0x3f800000 };
25+
let _f = unsafe { u.y };
26+
let v = V { x: 0, y: 0 };
27+
println!("{}", v.x);
28+
}
29+

src/test/ui/union-fields.stderr

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
error: field is never used: `y`
2+
--> $DIR/union-fields.rs:20:5
3+
|
4+
20 | y: u32,
5+
| ^^^^^^
6+
|
7+
note: lint level defined here
8+
--> $DIR/union-fields.rs:11:9
9+
|
10+
11 | #![deny(dead_code)]
11+
| ^^^^^^^^^
12+
13+
error: aborting due to previous error
14+

0 commit comments

Comments
 (0)