Skip to content

Commit bd4ebf2

Browse files
committed
check that #[used] is used only on statics
1 parent f76f6fb commit bd4ebf2

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

src/librustc/hir/check_attr.rs

+12
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ enum Target {
3131
Expression,
3232
Statement,
3333
Closure,
34+
Static,
3435
Other,
3536
}
3637

@@ -43,6 +44,7 @@ impl Target {
4344
hir::ItemEnum(..) => Target::Enum,
4445
hir::ItemConst(..) => Target::Const,
4546
hir::ItemForeignMod(..) => Target::ForeignMod,
47+
hir::ItemStatic(..) => Target::Static,
4648
_ => Target::Other,
4749
}
4850
}
@@ -102,6 +104,7 @@ impl<'a, 'tcx> CheckAttrVisitor<'a, 'tcx> {
102104
}
103105

104106
self.check_repr(item, target);
107+
self.check_used(item, target);
105108
}
106109

107110
/// Check if an `#[inline]` is applied to a function or a closure.
@@ -305,6 +308,15 @@ impl<'a, 'tcx> CheckAttrVisitor<'a, 'tcx> {
305308
}
306309
}
307310
}
311+
312+
fn check_used(&self, item: &hir::Item, target: Target) {
313+
for attr in &item.attrs {
314+
if attr.name().map(|name| name == "used").unwrap_or(false) && target != Target::Static {
315+
self.tcx.sess
316+
.span_err(attr.span, "attribute must be applied to a `static` variable");
317+
}
318+
}
319+
}
308320
}
309321

310322
impl<'a, 'tcx> Visitor<'tcx> for CheckAttrVisitor<'a, 'tcx> {

src/test/compile-fail/used.rs

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Copyright 2018 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+
#![feature(used)]
12+
13+
#[used]
14+
static FOO: u32 = 0; // OK
15+
16+
#[used] //~ ERROR attribute must be applied to a `static` variable
17+
fn foo() {}
18+
19+
#[used] //~ ERROR attribute must be applied to a `static` variable
20+
struct Foo {}
21+
22+
#[used] //~ ERROR attribute must be applied to a `static` variable
23+
trait Bar {}
24+
25+
#[used] //~ ERROR attribute must be applied to a `static` variable
26+
impl Bar for Foo {}
27+
28+
fn main() {}

0 commit comments

Comments
 (0)