rust/clippy_lints/src/enum_glob_use.rs

65 lines
2.0 KiB
Rust
Raw Normal View History

//! lint on `use`ing all variants of an enum
use rustc::hir::*;
2017-09-05 04:33:04 -05:00
use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
use syntax::ast::NodeId;
2016-02-24 10:38:57 -06:00
use syntax::codemap::Span;
use utils::span_lint;
/// **What it does:** Checks for `use Enum::*`.
///
/// **Why is this bad?** It is usually better style to use the prefixed name of
/// an enumeration variant, rather than importing variants.
///
/// **Known problems:** Old-style enumerations that prefix the variants are
/// still around. May cause problems with modules that are not snake_case (see
/// [#2397](https://github.com/rust-lang-nursery/rust-clippy/issues/2397))
///
2016-07-15 17:25:44 -05:00
/// **Example:**
/// ```rust
/// use std::cmp::Ordering::*;
/// ```
declare_lint! {
pub ENUM_GLOB_USE,
Allow,
"use items that import all variants of an enum"
}
pub struct EnumGlobUse;
impl LintPass for EnumGlobUse {
fn get_lints(&self) -> LintArray {
lint_array!(ENUM_GLOB_USE)
}
}
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EnumGlobUse {
fn check_mod(&mut self, cx: &LateContext<'a, 'tcx>, m: &'tcx Mod, _: Span, _: NodeId) {
// only check top level `use` statements
for item in &m.item_ids {
self.lint_item(cx, cx.tcx.hir.expect_item(item.id));
}
}
}
impl EnumGlobUse {
fn lint_item(&self, cx: &LateContext, item: &Item) {
if item.vis == Visibility::Public {
return; // re-exports are fine
}
if let ItemUse(ref path, UseKind::Glob) = item.node {
2016-12-02 10:38:31 -06:00
// FIXME: ask jseyfried why the qpath.def for `use std::cmp::Ordering::*;`
2017-08-09 02:30:56 -05:00
// extracted through `ItemUse(ref qpath, UseKind::Glob)` is a `Mod` and not an
// `Enum`
2016-12-20 11:21:30 -06:00
// if let Def::Enum(_) = path.def {
2017-08-09 02:30:56 -05:00
if path.segments
.last()
.and_then(|seg| seg.name.as_str().chars().next())
.map_or(false, char::is_uppercase)
{
span_lint(cx, ENUM_GLOB_USE, item.span, "don't use glob imports for enum variants");
}
}
}
}