Skip to content

Commit dafbdeb

Browse files
committed
Add idiom lint for bare extern crate
1 parent 0bfe307 commit dafbdeb

File tree

2 files changed

+66
-1
lines changed

2 files changed

+66
-1
lines changed

src/librustc_lint/builtin.rs

+63
Original file line numberDiff line numberDiff line change
@@ -1508,3 +1508,66 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedBrokenConst {
15081508
}
15091509
}
15101510
}
1511+
1512+
declare_lint! {
1513+
pub UNNECESSARY_EXTERN_CRATE,
1514+
Allow,
1515+
"suggest removing `extern crate` for the 2018 edition"
1516+
}
1517+
1518+
pub struct ExternCrate(/* depth */ u32);
1519+
1520+
impl ExternCrate {
1521+
pub fn new() -> Self {
1522+
ExternCrate(0)
1523+
}
1524+
}
1525+
1526+
impl LintPass for ExternCrate {
1527+
fn get_lints(&self) -> LintArray {
1528+
lint_array!(UNNECESSARY_EXTERN_CRATE)
1529+
}
1530+
}
1531+
1532+
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ExternCrate {
1533+
fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1534+
if let hir::ItemExternCrate(ref orig) = it.node {
1535+
if it.attrs.iter().any(|a| a.check_name("macro_use")) {
1536+
return
1537+
}
1538+
let mut err = cx.struct_span_lint(UNNECESSARY_EXTERN_CRATE,
1539+
it.span, "`extern crate` is unnecessary in the new edition");
1540+
if it.vis == hir::Visibility::Public || self.0 > 1 || orig.is_some() {
1541+
let pub_ = if it.vis == hir::Visibility::Public {
1542+
"pub "
1543+
} else {
1544+
""
1545+
};
1546+
1547+
let help = format!("use `{}use`", pub_);
1548+
1549+
if let Some(orig) = orig {
1550+
err.span_suggestion(it.span, &help,
1551+
format!("{}use {} as {}", pub_, orig, it.name));
1552+
} else {
1553+
err.span_suggestion(it.span, &help,
1554+
format!("{}use {}", pub_, it.name));
1555+
}
1556+
} else {
1557+
err.span_suggestion(it.span, "remove it", "".into());
1558+
}
1559+
1560+
err.emit();
1561+
}
1562+
}
1563+
1564+
fn check_mod(&mut self, _: &LateContext, _: &hir::Mod,
1565+
_: Span, _: ast::NodeId) {
1566+
self.0 += 1;
1567+
}
1568+
1569+
fn check_mod_post(&mut self, _: &LateContext, _: &hir::Mod,
1570+
_: Span, _: ast::NodeId) {
1571+
self.0 += 1;
1572+
}
1573+
}

src/librustc_lint/lib.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,7 @@ pub fn register_builtins(store: &mut lint::LintStore, sess: Option<&Session>) {
143143
TypeLimits,
144144
MissingDoc,
145145
MissingDebugImplementations,
146+
ExternCrate,
146147
);
147148

148149
add_lint_group!(sess,
@@ -180,7 +181,8 @@ pub fn register_builtins(store: &mut lint::LintStore, sess: Option<&Session>) {
180181
add_lint_group!(sess,
181182
"rust_2018_idioms",
182183
BARE_TRAIT_OBJECT,
183-
UNREACHABLE_PUB);
184+
UNREACHABLE_PUB,
185+
UNNECESSARY_EXTERN_CRATE);
184186

185187
// Guidelines for creating a future incompatibility lint:
186188
//

0 commit comments

Comments
 (0)