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::pat_util;
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 pat_util::pat_bindings(p, |mode, id, _, path1| {
48 let name = path1.node;
49 if let hir::BindByValue(hir::MutMutable) = mode {
50 if !name.as_str().starts_with("_") {
51 match mutables.entry(name) {
53 entry.insert(vec![id]);
55 Occupied(mut entry) => {
56 entry.get_mut().push(id);
64 let used_mutables = cx.tcx.used_mut_nodes.borrow();
65 for (_, v) in &mutables {
66 if !v.iter().any(|e| used_mutables.contains(e)) {
67 cx.span_lint(UNUSED_MUT,
68 cx.tcx.map.span(v[0]),
69 "variable does not need to be mutable");
75 impl LintPass for UnusedMut {
76 fn get_lints(&self) -> LintArray {
77 lint_array!(UNUSED_MUT)
81 impl LateLintPass for UnusedMut {
82 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
83 if let hir::ExprMatch(_, ref arms, _) = e.node {
85 self.check_unused_mut_pat(cx, &a.pats)
90 fn check_stmt(&mut self, cx: &LateContext, s: &hir::Stmt) {
91 if let hir::StmtDecl(ref d, _) = s.node {
92 if let hir::DeclLocal(ref l) = d.node {
93 self.check_unused_mut_pat(cx, slice::ref_slice(&l.pat));
98 fn check_fn(&mut self,
105 for a in &decl.inputs {
106 self.check_unused_mut_pat(cx, slice::ref_slice(&a.pat));
114 "unused result of a type flagged as #[must_use]"
120 "unused result of an expression in a statement"
123 #[derive(Copy, Clone)]
124 pub struct UnusedResults;
126 impl LintPass for UnusedResults {
127 fn get_lints(&self) -> LintArray {
128 lint_array!(UNUSED_MUST_USE, UNUSED_RESULTS)
132 impl LateLintPass for UnusedResults {
133 fn check_stmt(&mut self, cx: &LateContext, s: &hir::Stmt) {
134 let expr = match s.node {
135 hir::StmtSemi(ref expr, _) => &**expr,
139 if let hir::ExprRet(..) = expr.node {
143 let t = cx.tcx.tables().expr_ty(&expr);
144 let warned = match t.sty {
145 ty::TyTuple(ref tys) if tys.is_empty() => return,
146 ty::TyNever => return,
147 ty::TyBool => return,
148 ty::TyAdt(def, _) => {
149 let attrs = cx.tcx.get_attrs(def.did);
150 check_must_use(cx, &attrs[..], s.span)
155 cx.span_lint(UNUSED_RESULTS, s.span, "unused result");
158 fn check_must_use(cx: &LateContext, attrs: &[ast::Attribute], sp: Span) -> bool {
160 if attr.check_name("must_use") {
161 let mut msg = "unused result which must be used".to_string();
162 // check for #[must_use="..."]
163 if let Some(s) = attr.value_str() {
165 msg.push_str(&s.as_str());
167 cx.span_lint(UNUSED_MUST_USE, sp, &msg);
179 "unnecessary use of an `unsafe` block"
182 #[derive(Copy, Clone)]
183 pub struct UnusedUnsafe;
185 impl LintPass for UnusedUnsafe {
186 fn get_lints(&self) -> LintArray {
187 lint_array!(UNUSED_UNSAFE)
191 impl LateLintPass for UnusedUnsafe {
192 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
193 if let hir::ExprBlock(ref blk) = e.node {
194 // Don't warn about generated blocks, that'll just pollute the output.
195 if blk.rules == hir::UnsafeBlock(hir::UserProvided) &&
196 !cx.tcx.used_unsafe.borrow().contains(&blk.id) {
197 cx.span_lint(UNUSED_UNSAFE, blk.span, "unnecessary `unsafe` block");
206 "path statements with no effect"
209 #[derive(Copy, Clone)]
210 pub struct PathStatements;
212 impl LintPass for PathStatements {
213 fn get_lints(&self) -> LintArray {
214 lint_array!(PATH_STATEMENTS)
218 impl LateLintPass for PathStatements {
219 fn check_stmt(&mut self, cx: &LateContext, s: &hir::Stmt) {
220 if let hir::StmtSemi(ref expr, _) = s.node {
221 if let hir::ExprPath(_) = expr.node {
222 cx.span_lint(PATH_STATEMENTS, s.span, "path statement with no effect");
229 pub UNUSED_ATTRIBUTES,
231 "detects attributes that were not used by the compiler"
234 #[derive(Copy, Clone)]
235 pub struct UnusedAttributes;
237 impl LintPass for UnusedAttributes {
238 fn get_lints(&self) -> LintArray {
239 lint_array!(UNUSED_ATTRIBUTES)
243 impl LateLintPass for UnusedAttributes {
244 fn check_attribute(&mut self, cx: &LateContext, attr: &ast::Attribute) {
245 debug!("checking attribute: {:?}", attr);
247 // Note that check_name() marks the attribute as used if it matches.
248 for &(ref name, ty, _) in BUILTIN_ATTRIBUTES {
250 AttributeType::Whitelisted if attr.check_name(name) => {
251 debug!("{:?} is Whitelisted", name);
258 let plugin_attributes = cx.sess().plugin_attributes.borrow_mut();
259 for &(ref name, ty) in plugin_attributes.iter() {
260 if ty == AttributeType::Whitelisted && attr.check_name(&name) {
261 debug!("{:?} (plugin attr) is whitelisted with ty {:?}", name, ty);
266 if !attr::is_used(attr) {
267 debug!("Emitting warning for: {:?}", attr);
268 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
269 // Is it a builtin attribute that must be used at the crate level?
270 let known_crate = BUILTIN_ATTRIBUTES.iter()
271 .find(|&&(name, ty, _)| attr.name() == name && ty == AttributeType::CrateLevel)
274 // Has a plugin registered this attribute as one which must be used at
276 let plugin_crate = plugin_attributes.iter()
277 .find(|&&(ref x, t)| attr.name() == &**x && AttributeType::CrateLevel == t)
279 if known_crate || plugin_crate {
280 let msg = match attr.style {
281 ast::AttrStyle::Outer => {
282 "crate-level attribute should be an inner attribute: add an exclamation \
285 ast::AttrStyle::Inner => "crate-level attribute should be in the root module",
287 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
290 debug!("Attr was used: {:?}", attr);
298 "`if`, `match`, `while` and `return` do not need parentheses"
301 #[derive(Copy, Clone)]
302 pub struct UnusedParens;
305 fn check_unused_parens_core(&self,
309 struct_lit_needs_parens: bool) {
310 if let ast::ExprKind::Paren(ref inner) = value.node {
311 let necessary = struct_lit_needs_parens && contains_exterior_struct_lit(&inner);
313 cx.span_lint(UNUSED_PARENS,
315 &format!("unnecessary parentheses around {}", msg))
319 /// Expressions that syntactically contain an "exterior" struct
320 /// literal i.e. not surrounded by any parens or other
321 /// delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo
322 /// == X { y: 1 }` and `X { y: 1 } == foo` all do, but `(X {
323 /// y: 1 }) == foo` does not.
324 fn contains_exterior_struct_lit(value: &ast::Expr) -> bool {
326 ast::ExprKind::Struct(..) => true,
328 ast::ExprKind::Assign(ref lhs, ref rhs) |
329 ast::ExprKind::AssignOp(_, ref lhs, ref rhs) |
330 ast::ExprKind::Binary(_, ref lhs, ref rhs) => {
331 // X { y: 1 } + X { y: 2 }
332 contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
334 ast::ExprKind::Unary(_, ref x) |
335 ast::ExprKind::Cast(ref x, _) |
336 ast::ExprKind::Type(ref x, _) |
337 ast::ExprKind::Field(ref x, _) |
338 ast::ExprKind::TupField(ref x, _) |
339 ast::ExprKind::Index(ref x, _) => {
340 // &X { y: 1 }, X { y: 1 }.y
341 contains_exterior_struct_lit(&x)
344 ast::ExprKind::MethodCall(.., ref exprs) => {
345 // X { y: 1 }.bar(...)
346 contains_exterior_struct_lit(&exprs[0])
355 impl LintPass for UnusedParens {
356 fn get_lints(&self) -> LintArray {
357 lint_array!(UNUSED_PARENS)
361 impl EarlyLintPass for UnusedParens {
362 fn check_expr(&mut self, cx: &EarlyContext, e: &ast::Expr) {
363 use syntax::ast::ExprKind::*;
364 let (value, msg, struct_lit_needs_parens) = match e.node {
365 If(ref cond, ..) => (cond, "`if` condition", true),
366 While(ref cond, ..) => (cond, "`while` condition", true),
367 IfLet(_, ref cond, ..) => (cond, "`if let` head expression", true),
368 WhileLet(_, ref cond, ..) => (cond, "`while let` head expression", true),
369 ForLoop(_, ref cond, ..) => (cond, "`for` head expression", true),
370 Match(ref head, _) => (head, "`match` head expression", true),
371 Ret(Some(ref value)) => (value, "`return` value", false),
372 Assign(_, ref value) => (value, "assigned value", false),
373 AssignOp(.., ref value) => (value, "assigned value", false),
374 InPlace(_, ref value) => (value, "emplacement value", false),
377 self.check_unused_parens_core(cx, &value, msg, struct_lit_needs_parens);
380 fn check_stmt(&mut self, cx: &EarlyContext, s: &ast::Stmt) {
381 let (value, msg) = match s.node {
382 ast::StmtKind::Local(ref local) => {
384 Some(ref value) => (value, "assigned value"),
390 self.check_unused_parens_core(cx, &value, msg, false);
395 UNUSED_IMPORT_BRACES,
397 "unnecessary braces around an imported item"
400 #[derive(Copy, Clone)]
401 pub struct UnusedImportBraces;
403 impl LintPass for UnusedImportBraces {
404 fn get_lints(&self) -> LintArray {
405 lint_array!(UNUSED_IMPORT_BRACES)
409 impl LateLintPass for UnusedImportBraces {
410 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
411 if let hir::ItemUse(ref view_path) = item.node {
412 if let hir::ViewPathList(_, ref items) = view_path.node {
413 if items.len() == 1 && items[0].node.name != keywords::SelfValue.name() {
414 let msg = format!("braces around {} is unnecessary", items[0].node.name);
415 cx.span_lint(UNUSED_IMPORT_BRACES, item.span, &msg);
425 "detects unnecessary allocations that can be eliminated"
428 #[derive(Copy, Clone)]
429 pub struct UnusedAllocation;
431 impl LintPass for UnusedAllocation {
432 fn get_lints(&self) -> LintArray {
433 lint_array!(UNUSED_ALLOCATION)
437 impl LateLintPass for UnusedAllocation {
438 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
440 hir::ExprBox(_) => {}
444 if let Some(adjustment) = cx.tcx.tables().adjustments.get(&e.id) {
445 if let adjustment::Adjust::DerefRef { autoref, .. } = adjustment.kind {
447 Some(adjustment::AutoBorrow::Ref(_, hir::MutImmutable)) => {
448 cx.span_lint(UNUSED_ALLOCATION,
450 "unnecessary allocation, use & instead");
452 Some(adjustment::AutoBorrow::Ref(_, hir::MutMutable)) => {
453 cx.span_lint(UNUSED_ALLOCATION,
455 "unnecessary allocation, use &mut instead");