]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/unused_label.rs
Auto merge of #4409 - jeremystucki:export, r=phansch
[rust.git] / clippy_lints / src / unused_label.rs
1 use crate::utils::span_lint;
2 use rustc::hir;
3 use rustc::hir::intravisit::{walk_expr, walk_fn, FnKind, NestedVisitorMap, Visitor};
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
5 use rustc::{declare_lint_pass, declare_tool_lint};
6 use rustc_data_structures::fx::FxHashMap;
7 use syntax::source_map::Span;
8 use syntax::symbol::LocalInternedString;
9
10 declare_clippy_lint! {
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     pub UNUSED_LABEL,
26     complexity,
27     "unused labels"
28 }
29
30 struct UnusedLabelVisitor<'a, 'tcx> {
31     labels: FxHashMap<LocalInternedString, Span>,
32     cx: &'a LateContext<'a, 'tcx>,
33 }
34
35 declare_lint_pass!(UnusedLabel => [UNUSED_LABEL]);
36
37 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedLabel {
38     fn check_fn(
39         &mut self,
40         cx: &LateContext<'a, 'tcx>,
41         kind: FnKind<'tcx>,
42         decl: &'tcx hir::FnDecl,
43         body: &'tcx hir::Body,
44         span: Span,
45         fn_id: hir::HirId,
46     ) {
47         if span.from_expansion() {
48             return;
49         }
50
51         let mut v = UnusedLabelVisitor {
52             cx,
53             labels: FxHashMap::default(),
54         };
55         walk_fn(&mut v, kind, decl, body.id(), span, fn_id);
56
57         for (label, span) in v.labels {
58             span_lint(cx, UNUSED_LABEL, span, &format!("unused label `{}`", label));
59         }
60     }
61 }
62
63 impl<'a, 'tcx> Visitor<'tcx> for UnusedLabelVisitor<'a, 'tcx> {
64     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
65         match expr.node {
66             hir::ExprKind::Break(destination, _) | hir::ExprKind::Continue(destination) => {
67                 if let Some(label) = destination.label {
68                     self.labels.remove(&label.ident.as_str());
69                 }
70             },
71             hir::ExprKind::Loop(_, Some(label), _) => {
72                 self.labels.insert(label.ident.as_str(), expr.span);
73             },
74             _ => (),
75         }
76
77         walk_expr(self, expr);
78     }
79     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
80         NestedVisitorMap::All(&self.cx.tcx.hir())
81     }
82 }