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