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