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 pattern = pprust::expr_to_string(value);
288 Self::remove_outer_parens(cx, value.span, &pattern, msg);
293 fn check_unused_parens_pat(&self,
297 if let ast::PatKind::Paren(_) = value.node {
298 let pattern = pprust::pat_to_string(value);
299 Self::remove_outer_parens(cx, value.span, &pattern, msg);
303 fn remove_outer_parens(cx: &EarlyContext, span: Span, pattern: &str, msg: &str) {
304 let span_msg = format!("unnecessary parentheses around {}", msg);
305 let mut err = cx.struct_span_lint(UNUSED_PARENS, span, &span_msg);
306 let mut ate_left_paren = false;
307 let mut ate_right_paren = false;
308 let parens_removed = pattern
315 ate_left_paren = true;
323 ate_right_paren = true;
330 err.span_suggestion_short_with_applicability(
332 "remove these parentheses",
334 Applicability::MachineApplicable
340 impl LintPass for UnusedParens {
341 fn get_lints(&self) -> LintArray {
342 lint_array!(UNUSED_PARENS)
346 impl EarlyLintPass for UnusedParens {
347 fn check_expr(&mut self, cx: &EarlyContext, e: &ast::Expr) {
348 use syntax::ast::ExprKind::*;
349 let (value, msg, followed_by_block) = match e.node {
350 If(ref cond, ..) => (cond, "`if` condition", true),
351 While(ref cond, ..) => (cond, "`while` condition", true),
352 IfLet(_, ref cond, ..) => (cond, "`if let` head expression", true),
353 WhileLet(_, ref cond, ..) => (cond, "`while let` head expression", true),
354 ForLoop(_, ref cond, ..) => (cond, "`for` head expression", true),
355 Match(ref head, _) => (head, "`match` head expression", true),
356 Ret(Some(ref value)) => (value, "`return` value", false),
357 Assign(_, ref value) => (value, "assigned value", false),
358 AssignOp(.., ref value) => (value, "assigned value", false),
359 // either function/method call, or something this lint doesn't care about
360 ref call_or_other => {
361 let (args_to_check, call_kind) = match *call_or_other {
362 Call(_, ref args) => (&args[..], "function"),
363 // first "argument" is self (which sometimes needs parens)
364 MethodCall(_, ref args) => (&args[1..], "method"),
365 // actual catch-all arm
370 // Don't lint if this is a nested macro expansion: otherwise, the lint could
371 // trigger in situations that macro authors shouldn't have to care about, e.g.,
372 // when a parenthesized token tree matched in one macro expansion is matched as
373 // an expression in another and used as a fn/method argument (Issue #47775)
374 if e.span.ctxt().outer().expn_info()
375 .map_or(false, |info| info.call_site.ctxt().outer()
376 .expn_info().is_some()) {
379 let msg = format!("{} argument", call_kind);
380 for arg in args_to_check {
381 self.check_unused_parens_expr(cx, arg, &msg, false);
386 self.check_unused_parens_expr(cx, &value, msg, followed_by_block);
389 fn check_pat(&mut self, cx: &EarlyContext, p: &ast::Pat) {
390 use ast::PatKind::{Paren, Range};
391 // The lint visitor will visit each subpattern of `p`. We do not want to lint any range
392 // pattern no matter where it occurs in the pattern. For something like `&(a..=b)`, there
393 // is a recursive `check_pat` on `a` and `b`, but we will assume that if there are
394 // unnecessry parens they serve a purpose of readability.
395 if let Paren(ref pat) = p.node {
398 _ => self.check_unused_parens_pat(cx, &p, "pattern")
403 fn check_stmt(&mut self, cx: &EarlyContext, s: &ast::Stmt) {
404 if let ast::StmtKind::Local(ref local) = s.node {
405 if let Some(ref value) = local.init {
406 self.check_unused_parens_expr(cx, &value, "assigned value", false);
413 UNUSED_IMPORT_BRACES,
415 "unnecessary braces around an imported item"
418 #[derive(Copy, Clone)]
419 pub struct UnusedImportBraces;
421 impl UnusedImportBraces {
422 fn check_use_tree(&self, cx: &EarlyContext, use_tree: &ast::UseTree, item: &ast::Item) {
423 if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
424 // Recursively check nested UseTrees
425 for &(ref tree, _) in items {
426 self.check_use_tree(cx, tree, item);
429 // Trigger the lint only if there is one nested item
430 if items.len() != 1 {
434 // Trigger the lint if the nested item is a non-self single item
436 match items[0].0.kind {
437 ast::UseTreeKind::Simple(rename, ..) => {
438 let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
439 if orig_ident.name == keywords::SelfValue.name() {
442 node_ident = rename.unwrap_or(orig_ident);
444 ast::UseTreeKind::Glob => {
445 node_ident = ast::Ident::from_str("*");
447 ast::UseTreeKind::Nested(_) => {
452 let msg = format!("braces around {} is unnecessary", node_ident.name);
453 cx.span_lint(UNUSED_IMPORT_BRACES, item.span, &msg);
458 impl LintPass for UnusedImportBraces {
459 fn get_lints(&self) -> LintArray {
460 lint_array!(UNUSED_IMPORT_BRACES)
464 impl EarlyLintPass for UnusedImportBraces {
465 fn check_item(&mut self, cx: &EarlyContext, item: &ast::Item) {
466 if let ast::ItemKind::Use(ref use_tree) = item.node {
467 self.check_use_tree(cx, use_tree, item);
473 pub(super) UNUSED_ALLOCATION,
475 "detects unnecessary allocations that can be eliminated"
478 #[derive(Copy, Clone)]
479 pub struct UnusedAllocation;
481 impl LintPass for UnusedAllocation {
482 fn get_lints(&self) -> LintArray {
483 lint_array!(UNUSED_ALLOCATION)
487 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAllocation {
488 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
490 hir::ExprKind::Box(_) => {}
494 for adj in cx.tables.expr_adjustments(e) {
495 if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
497 adjustment::AutoBorrowMutability::Immutable =>
498 "unnecessary allocation, use & instead",
499 adjustment::AutoBorrowMutability::Mutable { .. }=>
500 "unnecessary allocation, use &mut instead"
502 cx.span_lint(UNUSED_ALLOCATION, e.span, msg);