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