Skip to content

Commit 6ff697d

Browse files
committed
rustc: Add lint for misplaced crate attributes
1 parent ffaee0f commit 6ff697d

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

src/etc/extract-tests.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@
6363
#[ allow(unused_variable) ];\n
6464
#[ allow(dead_assignment) ];\n
6565
#[ allow(unused_mut) ];\n
66+
#[ allow(attribute_usage) ];\n
6667
#[ feature(macro_rules, globs, struct_variant, managed_boxes) ];\n
6768
""" + block
6869
if xfail:

src/librustc/middle/lint.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ pub enum lint {
7676
type_overflow,
7777
unused_unsafe,
7878
unsafe_block,
79+
attribute_usage,
7980

8081
managed_heap_memory,
8182
owned_heap_memory,
@@ -244,6 +245,13 @@ static lint_table: &'static [(&'static str, LintSpec)] = &[
244245
default: allow
245246
}),
246247

248+
("attribute_usage",
249+
LintSpec {
250+
lint: attribute_usage,
251+
desc: "detects bad use of attributes",
252+
default: warn
253+
}),
254+
247255
("unused_variable",
248256
LintSpec {
249257
lint: unused_variable,
@@ -790,6 +798,27 @@ fn check_heap_item(cx: &Context, it: &ast::item) {
790798
}
791799
}
792800

801+
// check if crate-level attribute is used on item,
802+
// since it is usually caused by mistake of semicolon omission.
803+
// also make error on obsolete attributes for less confusion.
804+
fn check_item_attribute_usage(cx: &Context, it: &ast::item) {
805+
let crate_attrs = ["crate_type", "link", "feature", "no_uv", "no_main", "no_std"];
806+
807+
for attr in it.attrs.iter() {
808+
let name = attr.node.value.name();
809+
for crate_attr in crate_attrs.iter() {
810+
if name.equiv(crate_attr) {
811+
let msg = match attr.node.style {
812+
ast::AttrOuter => "crate-level attribute should be an inner attribute: \
813+
add semicolon at end",
814+
ast::AttrInner => "crate-level attribute should be in the root module",
815+
};
816+
cx.span_lint(attribute_usage, attr.span, msg);
817+
}
818+
}
819+
}
820+
}
821+
793822
fn check_heap_expr(cx: &Context, e: &ast::Expr) {
794823
let ty = ty::expr_ty(cx.tcx, e);
795824
check_heap_type(cx, e.span, ty);
@@ -1110,6 +1139,7 @@ impl<'self> Visitor<()> for Context<'self> {
11101139
check_item_non_uppercase_statics(cx, it);
11111140
check_heap_item(cx, it);
11121141
check_missing_doc_item(cx, it);
1142+
check_item_attribute_usage(cx, it);
11131143

11141144
do cx.visit_ids |v| {
11151145
v.visit_item(it, ());

0 commit comments

Comments
 (0)