]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/unused_label.rs
Rustup to latest nightly
[rust.git] / clippy_lints / src / unused_label.rs
1 use rustc::lint::*;
2 use rustc::hir;
3 use rustc::hir::intravisit::{walk_expr, walk_fn, FnKind, NestedVisitorMap, Visitor};
4 use std::collections::HashMap;
5 use syntax::ast;
6 use syntax::codemap::Span;
7 use syntax::symbol::LocalInternedString;
8 use utils::{in_macro, span_lint};
9
10 /// **What it does:** Checks for unused labels.
11 ///
12 /// **Why is this bad?** Maybe the label should be used in which case there is
13 /// an error in the code or it should be removed.
14 ///
15 /// **Known problems:** Hopefully none.
16 ///
17 /// **Example:**
18 /// ```rust,ignore
19 /// fn unused_label() {
20 ///     'label: for i in 1..2 {
21 ///         if i > 4 { continue }
22 ///     }
23 /// ```
24 declare_clippy_lint! {
25     pub UNUSED_LABEL,
26     complexity,
27     "unused labels"
28 }
29
30 pub struct UnusedLabel;
31
32 struct UnusedLabelVisitor<'a, 'tcx: 'a> {
33     labels: HashMap<LocalInternedString, Span>,
34     cx: &'a LateContext<'a, 'tcx>,
35 }
36
37 impl LintPass for UnusedLabel {
38     fn get_lints(&self) -> LintArray {
39         lint_array!(UNUSED_LABEL)
40     }
41 }
42
43 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedLabel {
44     fn check_fn(
45         &mut self,
46         cx: &LateContext<'a, 'tcx>,
47         kind: FnKind<'tcx>,
48         decl: &'tcx hir::FnDecl,
49         body: &'tcx hir::Body,
50         span: Span,
51         fn_id: ast::NodeId,
52     ) {
53         if in_macro(span) {
54             return;
55         }
56
57         let mut v = UnusedLabelVisitor {
58             cx,
59             labels: HashMap::new(),
60         };
61         walk_fn(&mut v, kind, decl, body.id(), span, fn_id);
62
63         for (label, span) in v.labels {
64             span_lint(cx, UNUSED_LABEL, span, &format!("unused label `{}`", label));
65         }
66     }
67 }
68
69 impl<'a, 'tcx: 'a> Visitor<'tcx> for UnusedLabelVisitor<'a, 'tcx> {
70     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
71         match expr.node {
72             hir::ExprBreak(destination, _) | hir::ExprAgain(destination) => if let Some(label) = destination.label {
73                 self.labels.remove(&label.name.as_str());
74             },
75             hir::ExprLoop(_, Some(label), _) | hir::ExprWhile(_, _, Some(label)) => {
76                 self.labels.insert(label.name.as_str(), expr.span);
77             },
78             _ => (),
79         }
80
81         walk_expr(self, expr);
82     }
83     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
84         NestedVisitorMap::All(&self.cx.tcx.hir)
85     }
86 }