rust-clippy/clippy_lints/src/unused_label.rs

89 lines
2.3 KiB
Rust
Raw Normal View History

2016-03-01 14:15:39 +00:00
use rustc::lint::*;
use rustc::hir;
use rustc::hir::intravisit::{FnKind, Visitor, walk_expr, walk_fn, NestedVisitorMap};
2016-03-01 14:15:39 +00:00
use std::collections::HashMap;
use syntax::ast;
use syntax::codemap::Span;
use syntax::symbol::InternedString;
2016-03-01 14:15:39 +00:00
use utils::{in_macro, span_lint};
/// **What it does:** Checks for unused labels.
2016-03-01 14:15:39 +00:00
///
/// **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.
2016-03-01 14:15:39 +00:00
///
/// **Known problems:** Hopefully none.
///
/// **Example:**
/// ```rust,ignore
/// fn unused_label() {
/// 'label: for i in 1..2 {
/// if i > 4 { continue }
/// }
/// ```
declare_lint! {
pub UNUSED_LABEL,
Warn,
"unused labels"
2016-03-01 14:15:39 +00:00
}
pub struct UnusedLabel;
struct UnusedLabelVisitor<'a, 'tcx: 'a> {
2016-03-01 14:15:39 +00:00
labels: HashMap<InternedString, 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)
}
}
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,
fn_id: ast::NodeId
) {
2016-03-01 14:15:39 +00:00
if in_macro(cx, span) {
return;
}
let mut v = UnusedLabelVisitor {
cx: cx,
labels: HashMap::new(),
};
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 {
hir::ExprBreak(Some(label), _) |
hir::ExprAgain(Some(label)) => {
self.labels.remove(&label.name.as_str());
2016-12-20 17:21:30 +00:00
},
hir::ExprLoop(_, Some(label), _) |
hir::ExprWhile(_, _, Some(label)) => {
self.labels.insert(label.node.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.map)
}
2016-03-01 14:15:39 +00:00
}