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::Def;
12 use rustc::hir::def_id::DefId;
14 use rustc::ty::adjustment;
15 use lint::{LateContext, EarlyContext, LintContext, LintArray};
16 use lint::{LintPass, EarlyLintPass, LateLintPass};
20 use syntax::errors::Applicability;
21 use syntax::feature_gate::{BUILTIN_ATTRIBUTES, AttributeType};
22 use syntax::print::pprust;
23 use syntax::symbol::keywords;
24 use syntax::util::parser;
32 "unused result of a type flagged as #[must_use]"
38 "unused result of an expression in a statement"
41 #[derive(Copy, Clone)]
42 pub struct UnusedResults;
44 impl LintPass for UnusedResults {
45 fn get_lints(&self) -> LintArray {
46 lint_array!(UNUSED_MUST_USE, UNUSED_RESULTS)
50 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedResults {
51 fn check_stmt(&mut self, cx: &LateContext, s: &hir::Stmt) {
52 let expr = match s.node {
53 hir::StmtKind::Semi(ref expr, _) => &**expr,
57 if let hir::ExprKind::Ret(..) = expr.node {
61 let t = cx.tables.expr_ty(&expr);
62 // FIXME(varkor): replace with `t.is_unit() || t.conservative_is_uninhabited()`.
63 let type_permits_no_use = match t.sty {
64 ty::Tuple(ref tys) if tys.is_empty() => true,
67 if def.variants.is_empty() {
70 check_must_use(cx, def.did, s.span, "")
76 let mut fn_warned = false;
77 let mut op_warned = false;
78 let maybe_def = match expr.node {
79 hir::ExprKind::Call(ref callee, _) => {
81 hir::ExprKind::Path(ref qpath) => {
82 let def = cx.tables.qpath_def(qpath, callee.hir_id);
84 Def::Fn(_) | Def::Method(_) => Some(def),
85 // `Def::Local` if it was a closure, for which we
86 // do not currently support must-use linting
93 hir::ExprKind::MethodCall(..) => {
94 cx.tables.type_dependent_defs().get(expr.hir_id).cloned()
98 if let Some(def) = maybe_def {
99 let def_id = def.def_id();
100 fn_warned = check_must_use(cx, def_id, s.span, "return value of ");
101 } else if type_permits_no_use {
102 // We don't warn about unused unit or uninhabited types.
103 // (See https://github.com/rust-lang/rust/issues/43806 for details.)
107 let must_use_op = match expr.node {
108 // Hardcoding operators here seemed more expedient than the
109 // refactoring that would be needed to look up the `#[must_use]`
110 // attribute which does exist on the comparison trait methods
111 hir::ExprKind::Binary(bin_op, ..) => {
118 hir::BinOpKind::Gt => {
121 hir::BinOpKind::Add |
122 hir::BinOpKind::Sub |
123 hir::BinOpKind::Div |
124 hir::BinOpKind::Mul |
125 hir::BinOpKind::Rem => {
126 Some("arithmetic operation")
128 hir::BinOpKind::And | hir::BinOpKind::Or => {
129 Some("logical operation")
131 hir::BinOpKind::BitXor |
132 hir::BinOpKind::BitAnd |
133 hir::BinOpKind::BitOr |
134 hir::BinOpKind::Shl |
135 hir::BinOpKind::Shr => {
136 Some("bitwise operation")
140 hir::ExprKind::Unary(..) => Some("unary operation"),
144 if let Some(must_use_op) = must_use_op {
145 cx.span_lint(UNUSED_MUST_USE, expr.span,
146 &format!("unused {} that must be used", must_use_op));
150 if !(type_permits_no_use || fn_warned || op_warned) {
151 cx.span_lint(UNUSED_RESULTS, s.span, "unused result");
154 fn check_must_use(cx: &LateContext, def_id: DefId, sp: Span, describe_path: &str) -> bool {
155 for attr in cx.tcx.get_attrs(def_id).iter() {
156 if attr.check_name("must_use") {
157 let msg = format!("unused {}`{}` that must be used",
158 describe_path, cx.tcx.item_path_str(def_id));
159 let mut err = cx.struct_span_lint(UNUSED_MUST_USE, sp, &msg);
160 // check for #[must_use = "..."]
161 if let Some(note) = attr.value_str() {
162 err.note(¬e.as_str());
176 "path statements with no effect"
179 #[derive(Copy, Clone)]
180 pub struct PathStatements;
182 impl LintPass for PathStatements {
183 fn get_lints(&self) -> LintArray {
184 lint_array!(PATH_STATEMENTS)
188 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PathStatements {
189 fn check_stmt(&mut self, cx: &LateContext, s: &hir::Stmt) {
190 if let hir::StmtKind::Semi(ref expr, _) = s.node {
191 if let hir::ExprKind::Path(_) = expr.node {
192 cx.span_lint(PATH_STATEMENTS, s.span, "path statement with no effect");
199 pub UNUSED_ATTRIBUTES,
201 "detects attributes that were not used by the compiler"
204 #[derive(Copy, Clone)]
205 pub struct UnusedAttributes;
207 impl LintPass for UnusedAttributes {
208 fn get_lints(&self) -> LintArray {
209 lint_array!(UNUSED_ATTRIBUTES)
213 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAttributes {
214 fn check_attribute(&mut self, cx: &LateContext, attr: &ast::Attribute) {
215 debug!("checking attribute: {:?}", attr);
216 // Note that check_name() marks the attribute as used if it matches.
217 for &(ref name, ty, _) in BUILTIN_ATTRIBUTES {
219 AttributeType::Whitelisted if attr.check_name(name) => {
220 debug!("{:?} is Whitelisted", name);
227 let plugin_attributes = cx.sess().plugin_attributes.borrow_mut();
228 for &(ref name, ty) in plugin_attributes.iter() {
229 if ty == AttributeType::Whitelisted && attr.check_name(&name) {
230 debug!("{:?} (plugin attr) is whitelisted with ty {:?}", name, ty);
235 let name = attr.name();
236 if !attr::is_used(attr) {
237 debug!("Emitting warning for: {:?}", attr);
238 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
239 // Is it a builtin attribute that must be used at the crate level?
240 let known_crate = BUILTIN_ATTRIBUTES.iter()
241 .find(|&&(builtin, ty, _)| name == builtin && ty == AttributeType::CrateLevel)
244 // Has a plugin registered this attribute as one that must be used at
246 let plugin_crate = plugin_attributes.iter()
247 .find(|&&(ref x, t)| name == &**x && AttributeType::CrateLevel == t)
249 if known_crate || plugin_crate {
250 let msg = match attr.style {
251 ast::AttrStyle::Outer => {
252 "crate-level attribute should be an inner attribute: add an exclamation \
255 ast::AttrStyle::Inner => "crate-level attribute should be in the root module",
257 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
260 debug!("Attr was used: {:?}", attr);
266 pub(super) UNUSED_PARENS,
268 "`if`, `match`, `while` and `return` do not need parentheses"
271 #[derive(Copy, Clone)]
272 pub struct UnusedParens;
275 fn check_unused_parens_expr(&self,
279 followed_by_block: bool) {
280 if let ast::ExprKind::Paren(ref inner) = value.node {
281 let necessary = followed_by_block && if let ast::ExprKind::Ret(_) = inner.node {
284 parser::contains_exterior_struct_lit(&inner)
287 let expr_text = if let Ok(snippet) = cx.sess().source_map()
288 .span_to_snippet(value.span) {
291 pprust::expr_to_string(value)
293 Self::remove_outer_parens(cx, value.span, &expr_text, msg);
298 fn check_unused_parens_pat(&self,
302 if let ast::PatKind::Paren(_) = value.node {
303 let pattern_text = if let Ok(snippet) = cx.sess().source_map()
304 .span_to_snippet(value.span) {
307 pprust::pat_to_string(value)
309 Self::remove_outer_parens(cx, value.span, &pattern_text, msg);
313 fn remove_outer_parens(cx: &EarlyContext, span: Span, pattern: &str, msg: &str) {
314 let span_msg = format!("unnecessary parentheses around {}", msg);
315 let mut err = cx.struct_span_lint(UNUSED_PARENS, span, &span_msg);
316 let mut ate_left_paren = false;
317 let mut ate_right_paren = false;
318 let parens_removed = pattern
325 ate_left_paren = true;
333 ate_right_paren = true;
340 err.span_suggestion_short_with_applicability(
342 "remove these parentheses",
344 Applicability::MachineApplicable
350 impl LintPass for UnusedParens {
351 fn get_lints(&self) -> LintArray {
352 lint_array!(UNUSED_PARENS)
356 impl EarlyLintPass for UnusedParens {
357 fn check_expr(&mut self, cx: &EarlyContext, e: &ast::Expr) {
358 use syntax::ast::ExprKind::*;
359 let (value, msg, followed_by_block) = match e.node {
360 If(ref cond, ..) => (cond, "`if` condition", true),
361 While(ref cond, ..) => (cond, "`while` condition", true),
362 IfLet(_, ref cond, ..) => (cond, "`if let` head expression", true),
363 WhileLet(_, ref cond, ..) => (cond, "`while let` head expression", true),
364 ForLoop(_, ref cond, ..) => (cond, "`for` head expression", true),
365 Match(ref head, _) => (head, "`match` head expression", true),
366 Ret(Some(ref value)) => (value, "`return` value", false),
367 Assign(_, ref value) => (value, "assigned value", false),
368 AssignOp(.., ref value) => (value, "assigned value", false),
369 // either function/method call, or something this lint doesn't care about
370 ref call_or_other => {
371 let (args_to_check, call_kind) = match *call_or_other {
372 Call(_, ref args) => (&args[..], "function"),
373 // first "argument" is self (which sometimes needs parens)
374 MethodCall(_, ref args) => (&args[1..], "method"),
375 // actual catch-all arm
380 // Don't lint if this is a nested macro expansion: otherwise, the lint could
381 // trigger in situations that macro authors shouldn't have to care about, e.g.,
382 // when a parenthesized token tree matched in one macro expansion is matched as
383 // an expression in another and used as a fn/method argument (Issue #47775)
384 if e.span.ctxt().outer().expn_info()
385 .map_or(false, |info| info.call_site.ctxt().outer()
386 .expn_info().is_some()) {
389 let msg = format!("{} argument", call_kind);
390 for arg in args_to_check {
391 self.check_unused_parens_expr(cx, arg, &msg, false);
396 self.check_unused_parens_expr(cx, &value, msg, followed_by_block);
399 fn check_pat(&mut self, cx: &EarlyContext, p: &ast::Pat) {
400 use ast::PatKind::{Paren, Range};
401 // The lint visitor will visit each subpattern of `p`. We do not want to lint any range
402 // pattern no matter where it occurs in the pattern. For something like `&(a..=b)`, there
403 // is a recursive `check_pat` on `a` and `b`, but we will assume that if there are
404 // unnecessry parens they serve a purpose of readability.
405 if let Paren(ref pat) = p.node {
408 _ => self.check_unused_parens_pat(cx, &p, "pattern")
413 fn check_stmt(&mut self, cx: &EarlyContext, s: &ast::Stmt) {
414 if let ast::StmtKind::Local(ref local) = s.node {
415 if let Some(ref value) = local.init {
416 self.check_unused_parens_expr(cx, &value, "assigned value", false);
423 UNUSED_IMPORT_BRACES,
425 "unnecessary braces around an imported item"
428 #[derive(Copy, Clone)]
429 pub struct UnusedImportBraces;
431 impl UnusedImportBraces {
432 fn check_use_tree(&self, cx: &EarlyContext, use_tree: &ast::UseTree, item: &ast::Item) {
433 if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
434 // Recursively check nested UseTrees
435 for &(ref tree, _) in items {
436 self.check_use_tree(cx, tree, item);
439 // Trigger the lint only if there is one nested item
440 if items.len() != 1 {
444 // Trigger the lint if the nested item is a non-self single item
446 match items[0].0.kind {
447 ast::UseTreeKind::Simple(rename, ..) => {
448 let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
449 if orig_ident.name == keywords::SelfValue.name() {
452 node_ident = rename.unwrap_or(orig_ident);
454 ast::UseTreeKind::Glob => {
455 node_ident = ast::Ident::from_str("*");
457 ast::UseTreeKind::Nested(_) => {
462 let msg = format!("braces around {} is unnecessary", node_ident.name);
463 cx.span_lint(UNUSED_IMPORT_BRACES, item.span, &msg);
468 impl LintPass for UnusedImportBraces {
469 fn get_lints(&self) -> LintArray {
470 lint_array!(UNUSED_IMPORT_BRACES)
474 impl EarlyLintPass for UnusedImportBraces {
475 fn check_item(&mut self, cx: &EarlyContext, item: &ast::Item) {
476 if let ast::ItemKind::Use(ref use_tree) = item.node {
477 self.check_use_tree(cx, use_tree, item);
483 pub(super) UNUSED_ALLOCATION,
485 "detects unnecessary allocations that can be eliminated"
488 #[derive(Copy, Clone)]
489 pub struct UnusedAllocation;
491 impl LintPass for UnusedAllocation {
492 fn get_lints(&self) -> LintArray {
493 lint_array!(UNUSED_ALLOCATION)
497 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAllocation {
498 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
500 hir::ExprKind::Box(_) => {}
504 for adj in cx.tables.expr_adjustments(e) {
505 if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
507 adjustment::AutoBorrowMutability::Immutable =>
508 "unnecessary allocation, use & instead",
509 adjustment::AutoBorrowMutability::Mutable { .. }=>
510 "unnecessary allocation, use &mut instead"
512 cx.span_lint(UNUSED_ALLOCATION, e.span, msg);