rust-clippy/clippy_lints/src/unused_label.rs

93 lines
2.6 KiB
Rust
Raw Normal View History

2018-05-30 08:15:50 +00:00
use crate::utils::{in_macro, span_lint};
use rustc::hir;
use rustc::hir::intravisit::{walk_expr, walk_fn, FnKind, NestedVisitorMap, Visitor};
use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
use rustc::{declare_tool_lint, lint_array};
use rustc_data_structures::fx::FxHashMap;
use syntax::source_map::Span;
use syntax::symbol::LocalInternedString;
2016-03-01 14:15:39 +00:00
2018-03-28 13:24:26 +00:00
declare_clippy_lint! {
/// **What it does:** Checks for unused labels.
///
/// **Why is this bad?** Maybe the label should be used in which case there is
/// an error in the code or it should be removed.
///
/// **Known problems:** Hopefully none.
///
/// **Example:**
/// ```rust,ignore
/// fn unused_label() {
/// 'label: for i in 1..2 {
/// if i > 4 { continue }
/// }
/// ```
2016-03-01 14:15:39 +00:00
pub UNUSED_LABEL,
2018-03-28 13:24:26 +00:00
complexity,
"unused labels"
2016-03-01 14:15:39 +00:00
}
pub struct UnusedLabel;
struct UnusedLabelVisitor<'a, 'tcx: 'a> {
labels: FxHashMap<LocalInternedString, Span>,
cx: &'a LateContext<'a, 'tcx>,
2016-03-01 14:15:39 +00:00
}
impl LintPass for UnusedLabel {
fn get_lints(&self) -> LintArray {
lint_array!(UNUSED_LABEL)
}
fn name(&self) -> &'static str {
"UnusedLable"
}
2016-03-01 14:15:39 +00:00
}
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedLabel {
fn check_fn(
&mut self,
cx: &LateContext<'a, 'tcx>,
kind: FnKind<'tcx>,
decl: &'tcx hir::FnDecl,
body: &'tcx hir::Body,
span: Span,
2019-02-20 10:11:11 +00:00
fn_id: hir::HirId,
) {
if in_macro(span) {
2016-03-01 14:15:39 +00:00
return;
}
let mut v = UnusedLabelVisitor {
cx,
labels: FxHashMap::default(),
};
walk_fn(&mut v, kind, decl, body.id(), span, fn_id);
2016-03-01 14:15:39 +00:00
for (label, span) in v.labels {
span_lint(cx, UNUSED_LABEL, span, &format!("unused label `{}`", label));
}
}
}
impl<'a, 'tcx: 'a> Visitor<'tcx> for UnusedLabelVisitor<'a, 'tcx> {
fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
2016-03-01 14:15:39 +00:00
match expr.node {
2018-11-27 20:14:15 +00:00
hir::ExprKind::Break(destination, _) | hir::ExprKind::Continue(destination) => {
if let Some(label) = destination.label {
self.labels.remove(&label.ident.as_str());
}
2016-12-20 17:21:30 +00:00
},
2018-07-12 07:30:57 +00:00
hir::ExprKind::Loop(_, Some(label), _) | hir::ExprKind::While(_, _, Some(label)) => {
2018-06-28 13:46:58 +00:00
self.labels.insert(label.ident.as_str(), expr.span);
2016-12-20 17:21:30 +00:00
},
2016-03-01 14:15:39 +00:00
_ => (),
}
walk_expr(self, expr);
}
fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
NestedVisitorMap::All(&self.cx.tcx.hir())
}
2016-03-01 14:15:39 +00:00
}