]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/enum_glob_use.rs
Merge pull request #1146 from birkenfeld/housekeeping
[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::hir::def::Def;
5 use rustc::hir::map::Node::NodeItem;
6 use rustc::lint::{LateLintPass, LintPass, LateContext, LintArray, LintContext};
7 use rustc::middle::cstore::DefLike;
8 use syntax::ast::NodeId;
9 use syntax::codemap::Span;
10 use utils::span_lint;
11
12 /// **What it does:** Checks for `use Enum::*`.
13 ///
14 /// **Why is this bad?** It is usually better style to use the prefixed name of
15 /// an enumeration variant, rather than importing variants.
16 ///
17 /// **Known problems:** Old-style enumerations that prefix the variants are
18 /// still around.
19 ///
20 /// **Example:**
21 /// ```rust
22 /// use std::cmp::Ordering::*;
23 /// ```
24 declare_lint! {
25     pub ENUM_GLOB_USE,
26     Allow,
27     "use items that import all variants of an enum"
28 }
29
30 pub struct EnumGlobUse;
31
32 impl LintPass for EnumGlobUse {
33     fn get_lints(&self) -> LintArray {
34         lint_array!(ENUM_GLOB_USE)
35     }
36 }
37
38 impl LateLintPass for EnumGlobUse {
39     fn check_mod(&mut self, cx: &LateContext, m: &Mod, _: Span, _: NodeId) {
40         // only check top level `use` statements
41         for item in &m.item_ids {
42             self.lint_item(cx, cx.krate.item(item.id));
43         }
44     }
45 }
46
47 impl EnumGlobUse {
48     fn lint_item(&self, cx: &LateContext, item: &Item) {
49         if item.vis == Visibility::Public {
50             return; // re-exports are fine
51         }
52         if let ItemUse(ref item_use) = item.node {
53             if let ViewPath_::ViewPathGlob(_) = item_use.node {
54                 if let Some(def) = cx.tcx.def_map.borrow().get(&item.id) {
55                     if let Some(node_id) = cx.tcx.map.as_local_node_id(def.full_def().def_id()) {
56                         if let Some(NodeItem(it)) = cx.tcx.map.find(node_id) {
57                             if let ItemEnum(..) = it.node {
58                                 span_lint(cx, ENUM_GLOB_USE, item.span, "don't use glob imports for enum variants");
59                             }
60                         }
61                     } else {
62                         let child = cx.sess().cstore.item_children(def.full_def().def_id());
63                         if let Some(child) = child.first() {
64                             if let DefLike::DlDef(Def::Variant(..)) = child.def {
65                                 span_lint(cx, ENUM_GLOB_USE, item.span, "don't use glob imports for enum variants");
66                             }
67                         }
68                     }
69                 }
70             }
71         }
72     }
73 }