1 use rustc::hir::def::{Res, DefKind};
2 use rustc::hir::def_id::DefId;
4 use rustc::ty::{self, Ty};
5 use rustc::ty::adjustment;
6 use rustc_data_structures::fx::FxHashMap;
7 use lint::{LateContext, EarlyContext, LintContext, LintArray};
8 use lint::{LintPass, EarlyLintPass, LateLintPass};
12 use syntax::errors::Applicability;
13 use syntax::feature_gate::{AttributeType, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP};
14 use syntax::print::pprust;
15 use syntax::symbol::{kw, sym};
16 use syntax::symbol::Symbol;
17 use syntax::util::parser;
27 "unused result of a type flagged as #[must_use]",
28 report_in_external_macro: true
34 "unused result of an expression in a statement"
37 declare_lint_pass!(UnusedResults => [UNUSED_MUST_USE, UNUSED_RESULTS]);
39 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedResults {
40 fn check_stmt(&mut self, cx: &LateContext<'_, '_>, s: &hir::Stmt) {
41 let expr = match s.node {
42 hir::StmtKind::Semi(ref expr) => &**expr,
46 if let hir::ExprKind::Ret(..) = expr.node {
50 let ty = cx.tables.expr_ty(&expr);
51 let type_permits_lack_of_use = check_must_use_ty(cx, ty, &expr, s.span, "");
53 let mut fn_warned = false;
54 let mut op_warned = false;
55 let maybe_def_id = match expr.node {
56 hir::ExprKind::Call(ref callee, _) => {
58 hir::ExprKind::Path(ref qpath) => {
59 match cx.tables.qpath_res(qpath, callee.hir_id) {
60 Res::Def(DefKind::Fn, def_id)
61 | Res::Def(DefKind::Method, def_id) => Some(def_id),
62 // `Res::Local` if it was a closure, for which we
63 // do not currently support must-use linting
70 hir::ExprKind::MethodCall(..) => {
71 cx.tables.type_dependent_def_id(expr.hir_id)
75 if let Some(def_id) = maybe_def_id {
76 fn_warned = check_must_use_def(cx, def_id, s.span, "return value of ", "");
77 } else if type_permits_lack_of_use {
78 // We don't warn about unused unit or uninhabited types.
79 // (See https://github.com/rust-lang/rust/issues/43806 for details.)
83 let must_use_op = match expr.node {
84 // Hardcoding operators here seemed more expedient than the
85 // refactoring that would be needed to look up the `#[must_use]`
86 // attribute which does exist on the comparison trait methods
87 hir::ExprKind::Binary(bin_op, ..) => {
94 hir::BinOpKind::Gt => {
100 hir::BinOpKind::Mul |
101 hir::BinOpKind::Rem => {
102 Some("arithmetic operation")
104 hir::BinOpKind::And | hir::BinOpKind::Or => {
105 Some("logical operation")
107 hir::BinOpKind::BitXor |
108 hir::BinOpKind::BitAnd |
109 hir::BinOpKind::BitOr |
110 hir::BinOpKind::Shl |
111 hir::BinOpKind::Shr => {
112 Some("bitwise operation")
116 hir::ExprKind::Unary(..) => Some("unary operation"),
120 if let Some(must_use_op) = must_use_op {
121 cx.span_lint(UNUSED_MUST_USE, expr.span,
122 &format!("unused {} that must be used", must_use_op));
126 if !(type_permits_lack_of_use || fn_warned || op_warned) {
127 cx.span_lint(UNUSED_RESULTS, s.span, "unused result");
130 // Returns whether an error has been emitted (and thus another does not need to be later).
131 fn check_must_use_ty<'tcx>(
132 cx: &LateContext<'_, 'tcx>,
136 descr_post_path: &str,
138 if ty.is_unit() || cx.tcx.is_ty_uninhabited_from(
139 cx.tcx.hir().get_module_parent_by_hir_id(expr.hir_id), ty)
145 ty::Adt(def, _) => check_must_use_def(cx, def.did, span, "", descr_post_path),
146 ty::Opaque(def, _) => {
147 let mut has_emitted = false;
148 for (predicate, _) in &cx.tcx.predicates_of(def).predicates {
149 if let ty::Predicate::Trait(ref poly_trait_predicate) = predicate {
150 let trait_ref = poly_trait_predicate.skip_binder().trait_ref;
151 let def_id = trait_ref.def_id;
152 if check_must_use_def(cx, def_id, span, "implementer of ", "") {
160 ty::Dynamic(binder, _) => {
161 let mut has_emitted = false;
162 for predicate in binder.skip_binder().iter() {
163 if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate {
164 let def_id = trait_ref.def_id;
165 if check_must_use_def(cx, def_id, span, "", " trait object") {
173 ty::Tuple(ref tys) => {
174 let mut has_emitted = false;
175 let spans = if let hir::ExprKind::Tup(comps) = &expr.node {
176 debug_assert_eq!(comps.len(), tys.len());
177 comps.iter().map(|e| e.span).collect()
181 for (i, ty) in tys.iter().map(|k| k.expect_ty()).enumerate() {
182 let descr_post_path = &format!(" in tuple element {}", i);
183 let span = *spans.get(i).unwrap_or(&span);
184 if check_must_use_ty(cx, ty, expr, span, descr_post_path) {
194 // Returns whether an error has been emitted (and thus another does not need to be later).
195 fn check_must_use_def(
196 cx: &LateContext<'_, '_>,
199 descr_pre_path: &str,
200 descr_post_path: &str,
202 for attr in cx.tcx.get_attrs(def_id).iter() {
203 if attr.check_name(sym::must_use) {
204 let msg = format!("unused {}`{}`{} that must be used",
205 descr_pre_path, cx.tcx.def_path_str(def_id), descr_post_path);
206 let mut err = cx.struct_span_lint(UNUSED_MUST_USE, span, &msg);
207 // check for #[must_use = "..."]
208 if let Some(note) = attr.value_str() {
209 err.note(¬e.as_str());
223 "path statements with no effect"
226 declare_lint_pass!(PathStatements => [PATH_STATEMENTS]);
228 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PathStatements {
229 fn check_stmt(&mut self, cx: &LateContext<'_, '_>, s: &hir::Stmt) {
230 if let hir::StmtKind::Semi(ref expr) = s.node {
231 if let hir::ExprKind::Path(_) = expr.node {
232 cx.span_lint(PATH_STATEMENTS, s.span, "path statement with no effect");
239 pub UNUSED_ATTRIBUTES,
241 "detects attributes that were not used by the compiler"
244 #[derive(Copy, Clone)]
245 pub struct UnusedAttributes {
246 builtin_attributes: &'static FxHashMap<Symbol, &'static BuiltinAttribute>,
249 impl UnusedAttributes {
250 pub fn new() -> Self {
252 builtin_attributes: &*BUILTIN_ATTRIBUTE_MAP,
257 impl_lint_pass!(UnusedAttributes => [UNUSED_ATTRIBUTES]);
259 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAttributes {
260 fn check_attribute(&mut self, cx: &LateContext<'_, '_>, attr: &ast::Attribute) {
261 debug!("checking attribute: {:?}", attr);
263 let attr_info = attr.ident().and_then(|ident| self.builtin_attributes.get(&ident.name));
265 if let Some(&&(name, ty, ..)) = attr_info {
267 AttributeType::Whitelisted => {
268 debug!("{:?} is Whitelisted", name);
275 let plugin_attributes = cx.sess().plugin_attributes.borrow_mut();
276 for &(name, ty) in plugin_attributes.iter() {
277 if ty == AttributeType::Whitelisted && attr.check_name(name) {
278 debug!("{:?} (plugin attr) is whitelisted with ty {:?}", name, ty);
283 let name = attr.name_or_empty();
284 if !attr::is_used(attr) {
285 debug!("Emitting warning for: {:?}", attr);
286 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
287 // Is it a builtin attribute that must be used at the crate level?
288 let known_crate = attr_info.map(|&&(_, ty, ..)| {
289 ty == AttributeType::CrateLevel
292 // Has a plugin registered this attribute as one that must be used at
294 let plugin_crate = plugin_attributes.iter()
295 .find(|&&(x, t)| name == x && AttributeType::CrateLevel == t)
297 if known_crate || plugin_crate {
298 let msg = match attr.style {
299 ast::AttrStyle::Outer => {
300 "crate-level attribute should be an inner attribute: add an exclamation \
303 ast::AttrStyle::Inner => "crate-level attribute should be in the root module",
305 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
308 debug!("Attr was used: {:?}", attr);
314 pub(super) UNUSED_PARENS,
316 "`if`, `match`, `while` and `return` do not need parentheses"
319 declare_lint_pass!(UnusedParens => [UNUSED_PARENS]);
322 fn check_unused_parens_expr(&self,
323 cx: &EarlyContext<'_>,
326 followed_by_block: bool) {
327 if let ast::ExprKind::Paren(ref inner) = value.node {
328 let necessary = followed_by_block && match inner.node {
329 ast::ExprKind::Ret(_) | ast::ExprKind::Break(..) => true,
330 _ => parser::contains_exterior_struct_lit(&inner),
333 let expr_text = if let Ok(snippet) = cx.sess().source_map()
334 .span_to_snippet(value.span) {
337 pprust::expr_to_string(value)
339 Self::remove_outer_parens(cx, value.span, &expr_text, msg);
344 fn check_unused_parens_pat(&self,
345 cx: &EarlyContext<'_>,
348 if let ast::PatKind::Paren(_) = value.node {
349 let pattern_text = if let Ok(snippet) = cx.sess().source_map()
350 .span_to_snippet(value.span) {
353 pprust::pat_to_string(value)
355 Self::remove_outer_parens(cx, value.span, &pattern_text, msg);
359 fn remove_outer_parens(cx: &EarlyContext<'_>, span: Span, pattern: &str, msg: &str) {
360 let span_msg = format!("unnecessary parentheses around {}", msg);
361 let mut err = cx.struct_span_lint(UNUSED_PARENS, span, &span_msg);
362 let mut ate_left_paren = false;
363 let mut ate_right_paren = false;
364 let parens_removed = pattern
371 ate_left_paren = true;
379 ate_right_paren = true;
386 err.span_suggestion_short(
388 "remove these parentheses",
390 Applicability::MachineApplicable,
396 impl EarlyLintPass for UnusedParens {
397 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
398 use syntax::ast::ExprKind::*;
399 let (value, msg, followed_by_block) = match e.node {
400 If(ref cond, ..) => (cond, "`if` condition", true),
401 While(ref cond, ..) => (cond, "`while` condition", true),
402 IfLet(_, ref cond, ..) => (cond, "`if let` head expression", true),
403 WhileLet(_, ref cond, ..) => (cond, "`while let` head expression", true),
404 ForLoop(_, ref cond, ..) => (cond, "`for` head expression", true),
405 Match(ref head, _) => (head, "`match` head expression", true),
406 Ret(Some(ref value)) => (value, "`return` value", false),
407 Assign(_, ref value) => (value, "assigned value", false),
408 AssignOp(.., ref value) => (value, "assigned value", false),
409 // either function/method call, or something this lint doesn't care about
410 ref call_or_other => {
411 let (args_to_check, call_kind) = match *call_or_other {
412 Call(_, ref args) => (&args[..], "function"),
413 // first "argument" is self (which sometimes needs parens)
414 MethodCall(_, ref args) => (&args[1..], "method"),
415 // actual catch-all arm
420 // Don't lint if this is a nested macro expansion: otherwise, the lint could
421 // trigger in situations that macro authors shouldn't have to care about, e.g.,
422 // when a parenthesized token tree matched in one macro expansion is matched as
423 // an expression in another and used as a fn/method argument (Issue #47775)
424 if e.span.ctxt().outer_expn_info()
425 .map_or(false, |info| info.call_site.ctxt().outer_expn_info().is_some()) {
428 let msg = format!("{} argument", call_kind);
429 for arg in args_to_check {
430 self.check_unused_parens_expr(cx, arg, &msg, false);
435 self.check_unused_parens_expr(cx, &value, msg, followed_by_block);
438 fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
439 use ast::PatKind::{Paren, Range};
440 // The lint visitor will visit each subpattern of `p`. We do not want to lint any range
441 // pattern no matter where it occurs in the pattern. For something like `&(a..=b)`, there
442 // is a recursive `check_pat` on `a` and `b`, but we will assume that if there are
443 // unnecessary parens they serve a purpose of readability.
444 if let Paren(ref pat) = p.node {
447 _ => self.check_unused_parens_pat(cx, &p, "pattern")
452 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
453 if let ast::StmtKind::Local(ref local) = s.node {
454 if let Some(ref value) = local.init {
455 self.check_unused_parens_expr(cx, &value, "assigned value", false);
462 UNUSED_IMPORT_BRACES,
464 "unnecessary braces around an imported item"
467 declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]);
469 impl UnusedImportBraces {
470 fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
471 if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
472 // Recursively check nested UseTrees
473 for &(ref tree, _) in items {
474 self.check_use_tree(cx, tree, item);
477 // Trigger the lint only if there is one nested item
478 if items.len() != 1 {
482 // Trigger the lint if the nested item is a non-self single item
484 match items[0].0.kind {
485 ast::UseTreeKind::Simple(rename, ..) => {
486 let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
487 if orig_ident.name == kw::SelfLower {
490 node_ident = rename.unwrap_or(orig_ident);
492 ast::UseTreeKind::Glob => {
493 node_ident = ast::Ident::from_str("*");
495 ast::UseTreeKind::Nested(_) => {
500 let msg = format!("braces around {} is unnecessary", node_ident.name);
501 cx.span_lint(UNUSED_IMPORT_BRACES, item.span, &msg);
506 impl EarlyLintPass for UnusedImportBraces {
507 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
508 if let ast::ItemKind::Use(ref use_tree) = item.node {
509 self.check_use_tree(cx, use_tree, item);
515 pub(super) UNUSED_ALLOCATION,
517 "detects unnecessary allocations that can be eliminated"
520 declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]);
522 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAllocation {
523 fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr) {
525 hir::ExprKind::Box(_) => {}
529 for adj in cx.tables.expr_adjustments(e) {
530 if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
532 adjustment::AutoBorrowMutability::Immutable =>
533 "unnecessary allocation, use & instead",
534 adjustment::AutoBorrowMutability::Mutable { .. }=>
535 "unnecessary allocation, use &mut instead"
537 cx.span_lint(UNUSED_ALLOCATION, e.span, msg);