1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use rustc::hir::def_id::DefId;
13 use rustc::ty::adjustment;
14 use util::nodemap::FxHashMap;
15 use lint::{LateContext, EarlyContext, LintContext, LintArray};
16 use lint::{LintPass, EarlyLintPass, LateLintPass};
18 use std::collections::hash_map::Entry::{Occupied, Vacant};
22 use syntax::feature_gate::{BUILTIN_ATTRIBUTES, AttributeType};
23 use syntax::symbol::keywords;
27 use rustc_back::slice;
29 use rustc::hir::intravisit::FnKind;
34 "detect mut variables which don't need to be mutable"
37 #[derive(Copy, Clone)]
41 fn check_unused_mut_pat(&self, cx: &LateContext, pats: &[P<hir::Pat>]) {
42 // collect all mutable pattern and group their NodeIDs by their Identifier to
43 // avoid false warnings in match arms with multiple patterns
45 let mut mutables = FxHashMap();
47 p.each_binding(|_, id, span, path1| {
48 let hir_id = cx.tcx.hir.node_to_hir_id(id);
49 let bm = match cx.tables.pat_binding_modes().get(hir_id) {
51 None => span_bug!(span, "missing binding mode"),
53 let name = path1.node;
54 if let ty::BindByValue(hir::MutMutable) = bm {
55 if !name.as_str().starts_with("_") {
56 match mutables.entry(name) {
58 entry.insert(vec![id]);
60 Occupied(mut entry) => {
61 entry.get_mut().push(id);
69 let used_mutables = cx.tcx.used_mut_nodes.borrow();
70 for (_, v) in &mutables {
71 if !v.iter().any(|e| used_mutables.contains(e)) {
72 cx.span_lint(UNUSED_MUT,
73 cx.tcx.hir.span(v[0]),
74 "variable does not need to be mutable");
80 impl LintPass for UnusedMut {
81 fn get_lints(&self) -> LintArray {
82 lint_array!(UNUSED_MUT)
86 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedMut {
87 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
88 if let hir::ExprMatch(_, ref arms, _) = e.node {
90 self.check_unused_mut_pat(cx, &a.pats)
95 fn check_stmt(&mut self, cx: &LateContext, s: &hir::Stmt) {
96 if let hir::StmtDecl(ref d, _) = s.node {
97 if let hir::DeclLocal(ref l) = d.node {
98 self.check_unused_mut_pat(cx, slice::ref_slice(&l.pat));
103 fn check_fn(&mut self,
110 for a in &body.arguments {
111 self.check_unused_mut_pat(cx, slice::ref_slice(&a.pat));
119 "unused result of a type flagged as #[must_use]"
125 "unused result of an expression in a statement"
128 #[derive(Copy, Clone)]
129 pub struct UnusedResults;
131 impl LintPass for UnusedResults {
132 fn get_lints(&self) -> LintArray {
133 lint_array!(UNUSED_MUST_USE, UNUSED_RESULTS)
137 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedResults {
138 fn check_stmt(&mut self, cx: &LateContext, s: &hir::Stmt) {
139 let expr = match s.node {
140 hir::StmtSemi(ref expr, _) => &**expr,
144 if let hir::ExprRet(..) = expr.node {
148 let t = cx.tables.expr_ty(&expr);
149 let ty_warned = match t.sty {
150 ty::TyTuple(ref tys, _) if tys.is_empty() => return,
151 ty::TyNever => return,
152 ty::TyAdt(def, _) => {
153 if def.variants.is_empty() {
156 check_must_use(cx, def.did, s.span, "")
162 let mut fn_warned = false;
163 if cx.tcx.sess.features.borrow().fn_must_use {
164 let maybe_def = match expr.node {
165 hir::ExprCall(ref callee, _) => {
167 hir::ExprPath(ref qpath) => {
168 Some(cx.tables.qpath_def(qpath, callee.hir_id))
173 hir::ExprMethodCall(..) => {
174 cx.tables.type_dependent_defs().get(expr.hir_id).cloned()
178 if let Some(def) = maybe_def {
179 let def_id = def.def_id();
180 fn_warned = check_must_use(cx, def_id, s.span, "return value of ");
184 if !(ty_warned || fn_warned) {
185 cx.span_lint(UNUSED_RESULTS, s.span, "unused result");
188 fn check_must_use(cx: &LateContext, def_id: DefId, sp: Span, describe_path: &str) -> bool {
189 for attr in cx.tcx.get_attrs(def_id).iter() {
190 if attr.check_name("must_use") {
191 let mut msg = format!("unused {}`{}` which must be used",
192 describe_path, cx.tcx.item_path_str(def_id));
193 // check for #[must_use="..."]
194 if let Some(s) = attr.value_str() {
196 msg.push_str(&s.as_str());
198 cx.span_lint(UNUSED_MUST_USE, sp, &msg);
210 "unnecessary use of an `unsafe` block"
213 #[derive(Copy, Clone)]
214 pub struct UnusedUnsafe;
216 impl LintPass for UnusedUnsafe {
217 fn get_lints(&self) -> LintArray {
218 lint_array!(UNUSED_UNSAFE)
222 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedUnsafe {
223 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
224 /// Return the NodeId for an enclosing scope that is also `unsafe`
225 fn is_enclosed(cx: &LateContext, id: ast::NodeId) -> Option<(String, ast::NodeId)> {
226 let parent_id = cx.tcx.hir.get_parent_node(id);
228 if cx.tcx.used_unsafe.borrow().contains(&parent_id) {
229 Some(("block".to_string(), parent_id))
230 } else if let Some(hir::map::NodeItem(&hir::Item {
231 node: hir::ItemFn(_, hir::Unsafety::Unsafe, _, _, _, _),
233 })) = cx.tcx.hir.find(parent_id) {
234 Some(("fn".to_string(), parent_id))
236 is_enclosed(cx, parent_id)
242 if let hir::ExprBlock(ref blk) = e.node {
243 // Don't warn about generated blocks, that'll just pollute the output.
244 if blk.rules == hir::UnsafeBlock(hir::UserProvided) &&
245 !cx.tcx.used_unsafe.borrow().contains(&blk.id) {
247 let mut db = cx.struct_span_lint(UNUSED_UNSAFE, blk.span,
248 "unnecessary `unsafe` block");
250 db.span_label(blk.span, "unnecessary `unsafe` block");
251 if let Some((kind, id)) = is_enclosed(cx, blk.id) {
252 db.span_note(cx.tcx.hir.span(id),
253 &format!("because it's nested under this `unsafe` {}", kind));
264 "path statements with no effect"
267 #[derive(Copy, Clone)]
268 pub struct PathStatements;
270 impl LintPass for PathStatements {
271 fn get_lints(&self) -> LintArray {
272 lint_array!(PATH_STATEMENTS)
276 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PathStatements {
277 fn check_stmt(&mut self, cx: &LateContext, s: &hir::Stmt) {
278 if let hir::StmtSemi(ref expr, _) = s.node {
279 if let hir::ExprPath(_) = expr.node {
280 cx.span_lint(PATH_STATEMENTS, s.span, "path statement with no effect");
287 pub UNUSED_ATTRIBUTES,
289 "detects attributes that were not used by the compiler"
292 #[derive(Copy, Clone)]
293 pub struct UnusedAttributes;
295 impl LintPass for UnusedAttributes {
296 fn get_lints(&self) -> LintArray {
297 lint_array!(UNUSED_ATTRIBUTES)
301 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAttributes {
302 fn check_attribute(&mut self, cx: &LateContext, attr: &ast::Attribute) {
303 debug!("checking attribute: {:?}", attr);
304 let name = unwrap_or!(attr.name(), return);
306 // Note that check_name() marks the attribute as used if it matches.
307 for &(ref name, ty, _) in BUILTIN_ATTRIBUTES {
309 AttributeType::Whitelisted if attr.check_name(name) => {
310 debug!("{:?} is Whitelisted", name);
317 let plugin_attributes = cx.sess().plugin_attributes.borrow_mut();
318 for &(ref name, ty) in plugin_attributes.iter() {
319 if ty == AttributeType::Whitelisted && attr.check_name(&name) {
320 debug!("{:?} (plugin attr) is whitelisted with ty {:?}", name, ty);
325 if !attr::is_used(attr) {
326 debug!("Emitting warning for: {:?}", attr);
327 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
328 // Is it a builtin attribute that must be used at the crate level?
329 let known_crate = BUILTIN_ATTRIBUTES.iter()
330 .find(|&&(builtin, ty, _)| name == builtin && ty == AttributeType::CrateLevel)
333 // Has a plugin registered this attribute as one which must be used at
335 let plugin_crate = plugin_attributes.iter()
336 .find(|&&(ref x, t)| name == &**x && AttributeType::CrateLevel == t)
338 if known_crate || plugin_crate {
339 let msg = match attr.style {
340 ast::AttrStyle::Outer => {
341 "crate-level attribute should be an inner attribute: add an exclamation \
344 ast::AttrStyle::Inner => "crate-level attribute should be in the root module",
346 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
349 debug!("Attr was used: {:?}", attr);
357 "`if`, `match`, `while` and `return` do not need parentheses"
360 #[derive(Copy, Clone)]
361 pub struct UnusedParens;
364 fn check_unused_parens_core(&self,
368 struct_lit_needs_parens: bool) {
369 if let ast::ExprKind::Paren(ref inner) = value.node {
370 let necessary = struct_lit_needs_parens && contains_exterior_struct_lit(&inner);
372 cx.span_lint(UNUSED_PARENS,
374 &format!("unnecessary parentheses around {}", msg))
378 /// Expressions that syntactically contain an "exterior" struct
379 /// literal i.e. not surrounded by any parens or other
380 /// delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo
381 /// == X { y: 1 }` and `X { y: 1 } == foo` all do, but `(X {
382 /// y: 1 }) == foo` does not.
383 fn contains_exterior_struct_lit(value: &ast::Expr) -> bool {
385 ast::ExprKind::Struct(..) => true,
387 ast::ExprKind::Assign(ref lhs, ref rhs) |
388 ast::ExprKind::AssignOp(_, ref lhs, ref rhs) |
389 ast::ExprKind::Binary(_, ref lhs, ref rhs) => {
390 // X { y: 1 } + X { y: 2 }
391 contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
393 ast::ExprKind::Unary(_, ref x) |
394 ast::ExprKind::Cast(ref x, _) |
395 ast::ExprKind::Type(ref x, _) |
396 ast::ExprKind::Field(ref x, _) |
397 ast::ExprKind::TupField(ref x, _) |
398 ast::ExprKind::Index(ref x, _) => {
399 // &X { y: 1 }, X { y: 1 }.y
400 contains_exterior_struct_lit(&x)
403 ast::ExprKind::MethodCall(.., ref exprs) => {
404 // X { y: 1 }.bar(...)
405 contains_exterior_struct_lit(&exprs[0])
414 impl LintPass for UnusedParens {
415 fn get_lints(&self) -> LintArray {
416 lint_array!(UNUSED_PARENS)
420 impl EarlyLintPass for UnusedParens {
421 fn check_expr(&mut self, cx: &EarlyContext, e: &ast::Expr) {
422 use syntax::ast::ExprKind::*;
423 let (value, msg, struct_lit_needs_parens) = match e.node {
424 If(ref cond, ..) => (cond, "`if` condition", true),
425 While(ref cond, ..) => (cond, "`while` condition", true),
426 IfLet(_, ref cond, ..) => (cond, "`if let` head expression", true),
427 WhileLet(_, ref cond, ..) => (cond, "`while let` head expression", true),
428 ForLoop(_, ref cond, ..) => (cond, "`for` head expression", true),
429 Match(ref head, _) => (head, "`match` head expression", true),
430 Ret(Some(ref value)) => (value, "`return` value", false),
431 Assign(_, ref value) => (value, "assigned value", false),
432 AssignOp(.., ref value) => (value, "assigned value", false),
433 InPlace(_, ref value) => (value, "emplacement value", false),
436 self.check_unused_parens_core(cx, &value, msg, struct_lit_needs_parens);
439 fn check_stmt(&mut self, cx: &EarlyContext, s: &ast::Stmt) {
440 let (value, msg) = match s.node {
441 ast::StmtKind::Local(ref local) => {
443 Some(ref value) => (value, "assigned value"),
449 self.check_unused_parens_core(cx, &value, msg, false);
454 UNUSED_IMPORT_BRACES,
456 "unnecessary braces around an imported item"
459 #[derive(Copy, Clone)]
460 pub struct UnusedImportBraces;
462 impl LintPass for UnusedImportBraces {
463 fn get_lints(&self) -> LintArray {
464 lint_array!(UNUSED_IMPORT_BRACES)
468 impl EarlyLintPass for UnusedImportBraces {
469 fn check_item(&mut self, cx: &EarlyContext, item: &ast::Item) {
470 if let ast::ItemKind::Use(ref view_path) = item.node {
471 if let ast::ViewPathList(_, ref items) = view_path.node {
472 if items.len() == 1 && items[0].node.name.name != keywords::SelfValue.name() {
473 let msg = format!("braces around {} is unnecessary", items[0].node.name);
474 cx.span_lint(UNUSED_IMPORT_BRACES, item.span, &msg);
484 "detects unnecessary allocations that can be eliminated"
487 #[derive(Copy, Clone)]
488 pub struct UnusedAllocation;
490 impl LintPass for UnusedAllocation {
491 fn get_lints(&self) -> LintArray {
492 lint_array!(UNUSED_ALLOCATION)
496 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAllocation {
497 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
499 hir::ExprBox(_) => {}
503 for adj in cx.tables.expr_adjustments(e) {
504 if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
506 hir::MutImmutable => "unnecessary allocation, use & instead",
507 hir::MutMutable => "unnecessary allocation, use &mut instead"
509 cx.span_lint(UNUSED_ALLOCATION, e.span, msg);