]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/enum_glob_use.rs
Merge pull request #2399 from rust-lang-nursery/rustup
[rust.git] / clippy_lints / src / enum_glob_use.rs
1 //! lint on `use`ing all variants of an enum
2
3 use rustc::hir::*;
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
5 use syntax::ast::NodeId;
6 use syntax::codemap::Span;
7 use utils::span_lint;
8
9 /// **What it does:** Checks for `use Enum::*`.
10 ///
11 /// **Why is this bad?** It is usually better style to use the prefixed name of
12 /// an enumeration variant, rather than importing variants.
13 ///
14 /// **Known problems:** Old-style enumerations that prefix the variants are
15 /// still around. May cause problems with modules that are not snake_case (see
16 /// [#2397](https://github.com/rust-lang-nursery/rust-clippy/issues/2397))
17 ///
18 /// **Example:**
19 /// ```rust
20 /// use std::cmp::Ordering::*;
21 /// ```
22 declare_lint! {
23     pub ENUM_GLOB_USE,
24     Allow,
25     "use items that import all variants of an enum"
26 }
27
28 pub struct EnumGlobUse;
29
30 impl LintPass for EnumGlobUse {
31     fn get_lints(&self) -> LintArray {
32         lint_array!(ENUM_GLOB_USE)
33     }
34 }
35
36 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EnumGlobUse {
37     fn check_mod(&mut self, cx: &LateContext<'a, 'tcx>, m: &'tcx Mod, _: Span, _: NodeId) {
38         // only check top level `use` statements
39         for item in &m.item_ids {
40             self.lint_item(cx, cx.tcx.hir.expect_item(item.id));
41         }
42     }
43 }
44
45 impl EnumGlobUse {
46     fn lint_item(&self, cx: &LateContext, item: &Item) {
47         if item.vis == Visibility::Public {
48             return; // re-exports are fine
49         }
50         if let ItemUse(ref path, UseKind::Glob) = item.node {
51             // FIXME: ask jseyfried why the qpath.def for `use std::cmp::Ordering::*;`
52             // extracted through `ItemUse(ref qpath, UseKind::Glob)` is a `Mod` and not an
53             // `Enum`
54             // if let Def::Enum(_) = path.def {
55             if path.segments
56                 .last()
57                 .and_then(|seg| seg.name.as_str().chars().next())
58                 .map_or(false, char::is_uppercase)
59             {
60                 span_lint(cx, ENUM_GLOB_USE, item.span, "don't use glob imports for enum variants");
61             }
62         }
63     }
64 }