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