1 use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
2 use rustc::ty::adjustment;
3 use rustc::ty::{self, Ty};
4 use rustc_data_structures::fx::FxHashMap;
5 use rustc_errors::{pluralize, Applicability};
6 use rustc_feature::{AttributeType, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP};
8 use rustc_hir::def::{DefKind, Res};
9 use rustc_hir::def_id::DefId;
10 use rustc_session::lint::builtin::UNUSED_ATTRIBUTES;
11 use rustc_span::symbol::Symbol;
12 use rustc_span::symbol::{kw, sym};
13 use rustc_span::{BytePos, Span};
16 use syntax::print::pprust;
17 use syntax::util::parser;
24 "unused result of a type flagged as `#[must_use]`",
25 report_in_external_macro
31 "unused result of an expression in a statement"
34 declare_lint_pass!(UnusedResults => [UNUSED_MUST_USE, UNUSED_RESULTS]);
36 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedResults {
37 fn check_stmt(&mut self, cx: &LateContext<'_, '_>, s: &hir::Stmt<'_>) {
38 let expr = match s.kind {
39 hir::StmtKind::Semi(ref expr) => &**expr,
43 if let hir::ExprKind::Ret(..) = expr.kind {
47 let ty = cx.tables.expr_ty(&expr);
48 let type_permits_lack_of_use = check_must_use_ty(cx, ty, &expr, s.span, "", "", 1);
50 let mut fn_warned = false;
51 let mut op_warned = false;
52 let maybe_def_id = match expr.kind {
53 hir::ExprKind::Call(ref callee, _) => {
55 hir::ExprKind::Path(ref qpath) => {
56 match cx.tables.qpath_res(qpath, callee.hir_id) {
57 Res::Def(DefKind::Fn, def_id) | Res::Def(DefKind::Method, def_id) => {
60 // `Res::Local` if it was a closure, for which we
61 // do not currently support must-use linting
68 hir::ExprKind::MethodCall(..) => cx.tables.type_dependent_def_id(expr.hir_id),
71 if let Some(def_id) = maybe_def_id {
72 fn_warned = check_must_use_def(cx, def_id, s.span, "return value of ", "");
73 } else if type_permits_lack_of_use {
74 // We don't warn about unused unit or uninhabited types.
75 // (See https://github.com/rust-lang/rust/issues/43806 for details.)
79 let must_use_op = match expr.kind {
80 // Hardcoding operators here seemed more expedient than the
81 // refactoring that would be needed to look up the `#[must_use]`
82 // attribute which does exist on the comparison trait methods
83 hir::ExprKind::Binary(bin_op, ..) => match bin_op.node {
89 | hir::BinOpKind::Gt => Some("comparison"),
94 | hir::BinOpKind::Rem => Some("arithmetic operation"),
95 hir::BinOpKind::And | hir::BinOpKind::Or => Some("logical operation"),
96 hir::BinOpKind::BitXor
97 | hir::BinOpKind::BitAnd
98 | hir::BinOpKind::BitOr
100 | hir::BinOpKind::Shr => Some("bitwise operation"),
102 hir::ExprKind::Unary(..) => Some("unary operation"),
106 if let Some(must_use_op) = must_use_op {
110 &format!("unused {} that must be used", must_use_op),
115 if !(type_permits_lack_of_use || fn_warned || op_warned) {
116 cx.span_lint(UNUSED_RESULTS, s.span, "unused result");
119 // Returns whether an error has been emitted (and thus another does not need to be later).
120 fn check_must_use_ty<'tcx>(
121 cx: &LateContext<'_, 'tcx>,
123 expr: &hir::Expr<'_>,
130 || cx.tcx.is_ty_uninhabited_from(cx.tcx.hir().get_module_parent(expr.hir_id), ty)
135 let plural_suffix = pluralize!(plural_len);
138 ty::Adt(..) if ty.is_box() => {
139 let boxed_ty = ty.boxed_ty();
140 let descr_pre = &format!("{}boxed ", descr_pre);
141 check_must_use_ty(cx, boxed_ty, expr, span, descr_pre, descr_post, plural_len)
143 ty::Adt(def, _) => check_must_use_def(cx, def.did, span, descr_pre, descr_post),
144 ty::Opaque(def, _) => {
145 let mut has_emitted = false;
146 for (predicate, _) in cx.tcx.predicates_of(def).predicates {
147 if let ty::Predicate::Trait(ref poly_trait_predicate, _) = predicate {
148 let trait_ref = poly_trait_predicate.skip_binder().trait_ref;
149 let def_id = trait_ref.def_id;
151 &format!("{}implementer{} of ", descr_pre, plural_suffix,);
152 if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
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;
166 &format!(" trait object{}{}", plural_suffix, descr_post,);
167 if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
175 ty::Tuple(ref tys) => {
176 let mut has_emitted = false;
177 let spans = if let hir::ExprKind::Tup(comps) = &expr.kind {
178 debug_assert_eq!(comps.len(), tys.len());
179 comps.iter().map(|e| e.span).collect()
183 for (i, ty) in tys.iter().map(|k| k.expect_ty()).enumerate() {
184 let descr_post = &format!(" in tuple element {}", i);
185 let span = *spans.get(i).unwrap_or(&span);
186 if check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, plural_len)
193 ty::Array(ty, len) => match len.try_eval_usize(cx.tcx, cx.param_env) {
194 // If the array is definitely non-empty, we can do `#[must_use]` checking.
195 Some(n) if n != 0 => {
196 let descr_pre = &format!("{}array{} of ", descr_pre, plural_suffix,);
197 check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, n as usize + 1)
199 // Otherwise, we don't lint, to avoid false positives.
206 // Returns whether an error has been emitted (and thus another does not need to be later).
207 fn check_must_use_def(
208 cx: &LateContext<'_, '_>,
211 descr_pre_path: &str,
212 descr_post_path: &str,
214 for attr in cx.tcx.get_attrs(def_id).iter() {
215 if attr.check_name(sym::must_use) {
217 "unused {}`{}`{} that must be used",
219 cx.tcx.def_path_str(def_id),
222 let mut err = cx.struct_span_lint(UNUSED_MUST_USE, span, &msg);
223 // check for #[must_use = "..."]
224 if let Some(note) = attr.value_str() {
225 err.note(¬e.as_str());
239 "path statements with no effect"
242 declare_lint_pass!(PathStatements => [PATH_STATEMENTS]);
244 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PathStatements {
245 fn check_stmt(&mut self, cx: &LateContext<'_, '_>, s: &hir::Stmt<'_>) {
246 if let hir::StmtKind::Semi(ref expr) = s.kind {
247 if let hir::ExprKind::Path(_) = expr.kind {
248 cx.span_lint(PATH_STATEMENTS, s.span, "path statement with no effect");
254 #[derive(Copy, Clone)]
255 pub struct UnusedAttributes {
256 builtin_attributes: &'static FxHashMap<Symbol, &'static BuiltinAttribute>,
259 impl UnusedAttributes {
260 pub fn new() -> Self {
261 UnusedAttributes { builtin_attributes: &*BUILTIN_ATTRIBUTE_MAP }
265 impl_lint_pass!(UnusedAttributes => [UNUSED_ATTRIBUTES]);
267 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAttributes {
268 fn check_attribute(&mut self, cx: &LateContext<'_, '_>, attr: &ast::Attribute) {
269 debug!("checking attribute: {:?}", attr);
271 if attr.is_doc_comment() {
275 let attr_info = attr.ident().and_then(|ident| self.builtin_attributes.get(&ident.name));
277 if let Some(&&(name, ty, ..)) = attr_info {
279 AttributeType::Whitelisted => {
280 debug!("{:?} is Whitelisted", name);
287 if !attr::is_used(attr) {
288 debug!("emitting warning for: {:?}", attr);
289 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
290 // Is it a builtin attribute that must be used at the crate level?
291 if attr_info.map_or(false, |(_, ty, ..)| ty == &AttributeType::CrateLevel) {
292 let msg = match attr.style {
293 ast::AttrStyle::Outer => {
294 "crate-level attribute should be an inner attribute: add an exclamation \
297 ast::AttrStyle::Inner => "crate-level attribute should be in the root module",
299 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
302 debug!("Attr was used: {:?}", attr);
308 pub(super) UNUSED_PARENS,
310 "`if`, `match`, `while` and `return` do not need parentheses"
313 declare_lint_pass!(UnusedParens => [UNUSED_PARENS]);
316 fn is_expr_parens_necessary(inner: &ast::Expr, followed_by_block: bool) -> bool {
318 && match inner.kind {
319 ast::ExprKind::Ret(_) | ast::ExprKind::Break(..) => true,
320 _ => parser::contains_exterior_struct_lit(&inner),
324 fn check_unused_parens_expr(
326 cx: &EarlyContext<'_>,
329 followed_by_block: bool,
330 left_pos: Option<BytePos>,
331 right_pos: Option<BytePos>,
334 ast::ExprKind::Paren(ref inner) => {
335 if !Self::is_expr_parens_necessary(inner, followed_by_block)
336 && value.attrs.is_empty()
337 && !value.span.from_expansion()
340 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(value.span) {
343 pprust::expr_to_string(value)
346 left_pos.map(|s| s >= value.span.lo()).unwrap_or(false),
347 right_pos.map(|s| s <= value.span.hi()).unwrap_or(false),
349 Self::remove_outer_parens(cx, value.span, &expr_text, msg, keep_space);
352 ast::ExprKind::Let(_, ref expr) => {
353 // FIXME(#60336): Properly handle `let true = (false && true)`
354 // actually needing the parenthesis.
355 self.check_unused_parens_expr(
358 "`let` head expression",
368 fn check_unused_parens_pat(
370 cx: &EarlyContext<'_>,
375 use ast::{BindingMode, Mutability, PatKind};
377 if let PatKind::Paren(inner) = &value.kind {
379 // The lint visitor will visit each subpattern of `p`. We do not want to lint
380 // any range pattern no matter where it occurs in the pattern. For something like
381 // `&(a..=b)`, there is a recursive `check_pat` on `a` and `b`, but we will assume
382 // that if there are unnecessary parens they serve a purpose of readability.
383 PatKind::Range(..) => return,
384 // Avoid `p0 | .. | pn` if we should.
385 PatKind::Or(..) if avoid_or => return,
386 // Avoid `mut x` and `mut x @ p` if we should:
387 PatKind::Ident(BindingMode::ByValue(Mutability::Mut), ..) if avoid_mut => return,
388 // Otherwise proceed with linting.
393 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(value.span) {
396 pprust::pat_to_string(value)
398 Self::remove_outer_parens(cx, value.span, &pattern_text, "pattern", (false, false));
402 fn remove_outer_parens(
403 cx: &EarlyContext<'_>,
407 keep_space: (bool, bool),
409 let span_msg = format!("unnecessary parentheses around {}", msg);
410 let mut err = cx.struct_span_lint(UNUSED_PARENS, span, &span_msg);
411 let mut ate_left_paren = false;
412 let mut ate_right_paren = false;
413 let parens_removed = pattern.trim_matches(|c| match c {
418 ate_left_paren = true;
426 ate_right_paren = true;
434 let mut replace = if keep_space.0 {
435 let mut s = String::from(" ");
436 s.push_str(parens_removed);
439 String::from(parens_removed)
448 err.span_suggestion_short(
450 "remove these parentheses",
452 Applicability::MachineApplicable,
458 impl EarlyLintPass for UnusedParens {
459 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
460 use syntax::ast::ExprKind::*;
461 let (value, msg, followed_by_block, left_pos, right_pos) = match e.kind {
462 Let(ref pat, ..) => {
463 self.check_unused_parens_pat(cx, pat, false, false);
467 If(ref cond, ref block, ..) => {
468 let left = e.span.lo() + rustc_span::BytePos(2);
469 let right = block.span.lo();
470 (cond, "`if` condition", true, Some(left), Some(right))
473 While(ref cond, ref block, ..) => {
474 let left = e.span.lo() + rustc_span::BytePos(5);
475 let right = block.span.lo();
476 (cond, "`while` condition", true, Some(left), Some(right))
479 ForLoop(ref pat, ref cond, ref block, ..) => {
480 self.check_unused_parens_pat(cx, pat, false, false);
481 (cond, "`for` head expression", true, None, Some(block.span.lo()))
484 Match(ref head, _) => {
485 let left = e.span.lo() + rustc_span::BytePos(5);
486 (head, "`match` head expression", true, Some(left), None)
489 Ret(Some(ref value)) => {
490 let left = e.span.lo() + rustc_span::BytePos(3);
491 (value, "`return` value", false, Some(left), None)
494 Assign(_, ref value, _) => (value, "assigned value", false, None, None),
495 AssignOp(.., ref value) => (value, "assigned value", false, None, None),
496 // either function/method call, or something this lint doesn't care about
497 ref call_or_other => {
498 let (args_to_check, call_kind) = match *call_or_other {
499 Call(_, ref args) => (&args[..], "function"),
500 // first "argument" is self (which sometimes needs parens)
501 MethodCall(_, ref args) => (&args[1..], "method"),
502 // actual catch-all arm
507 // Don't lint if this is a nested macro expansion: otherwise, the lint could
508 // trigger in situations that macro authors shouldn't have to care about, e.g.,
509 // when a parenthesized token tree matched in one macro expansion is matched as
510 // an expression in another and used as a fn/method argument (Issue #47775)
511 if e.span.ctxt().outer_expn_data().call_site.from_expansion() {
514 let msg = format!("{} argument", call_kind);
515 for arg in args_to_check {
516 self.check_unused_parens_expr(cx, arg, &msg, false, None, None);
521 self.check_unused_parens_expr(cx, &value, msg, followed_by_block, left_pos, right_pos);
524 fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
525 use ast::{Mutability, PatKind::*};
527 // Do not lint on `(..)` as that will result in the other arms being useless.
529 // The other cases do not contain sub-patterns.
530 | Wild | Rest | Lit(..) | Mac(..) | Range(..) | Ident(.., None) | Path(..) => return,
531 // These are list-like patterns; parens can always be removed.
532 TupleStruct(_, ps) | Tuple(ps) | Slice(ps) | Or(ps) => for p in ps {
533 self.check_unused_parens_pat(cx, p, false, false);
535 Struct(_, fps, _) => for f in fps {
536 self.check_unused_parens_pat(cx, &f.pat, false, false);
538 // Avoid linting on `i @ (p0 | .. | pn)` and `box (p0 | .. | pn)`, #64106.
539 Ident(.., Some(p)) | Box(p) => self.check_unused_parens_pat(cx, p, true, false),
540 // Avoid linting on `&(mut x)` as `&mut x` has a different meaning, #55342.
541 // Also avoid linting on `& mut? (p0 | .. | pn)`, #64106.
542 Ref(p, m) => self.check_unused_parens_pat(cx, p, true, *m == Mutability::Not),
546 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
547 if let ast::StmtKind::Local(ref local) = s.kind {
548 self.check_unused_parens_pat(cx, &local.pat, false, false);
550 if let Some(ref value) = local.init {
551 self.check_unused_parens_expr(cx, &value, "assigned value", false, None, None);
556 fn check_param(&mut self, cx: &EarlyContext<'_>, param: &ast::Param) {
557 self.check_unused_parens_pat(cx, ¶m.pat, true, false);
560 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
561 self.check_unused_parens_pat(cx, &arm.pat, false, false);
564 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
565 if let &ast::TyKind::Paren(ref r) = &ty.kind {
567 &ast::TyKind::TraitObject(..) => {}
568 &ast::TyKind::ImplTrait(_, ref bounds) if bounds.len() > 1 => {}
571 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(ty.span) {
574 pprust::ty_to_string(ty)
577 Self::remove_outer_parens(cx, ty.span, &pattern_text, "type", (false, false));
585 UNUSED_IMPORT_BRACES,
587 "unnecessary braces around an imported item"
590 declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]);
592 impl UnusedImportBraces {
593 fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
594 if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
595 // Recursively check nested UseTrees
596 for &(ref tree, _) in items {
597 self.check_use_tree(cx, tree, item);
600 // Trigger the lint only if there is one nested item
601 if items.len() != 1 {
605 // Trigger the lint if the nested item is a non-self single item
606 let node_name = match items[0].0.kind {
607 ast::UseTreeKind::Simple(rename, ..) => {
608 let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
609 if orig_ident.name == kw::SelfLower {
612 rename.unwrap_or(orig_ident).name
614 ast::UseTreeKind::Glob => Symbol::intern("*"),
615 ast::UseTreeKind::Nested(_) => return,
618 let msg = format!("braces around {} is unnecessary", node_name);
619 cx.span_lint(UNUSED_IMPORT_BRACES, item.span, &msg);
624 impl EarlyLintPass for UnusedImportBraces {
625 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
626 if let ast::ItemKind::Use(ref use_tree) = item.kind {
627 self.check_use_tree(cx, use_tree, item);
633 pub(super) UNUSED_ALLOCATION,
635 "detects unnecessary allocations that can be eliminated"
638 declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]);
640 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAllocation {
641 fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr<'_>) {
643 hir::ExprKind::Box(_) => {}
647 for adj in cx.tables.expr_adjustments(e) {
648 if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
650 adjustment::AutoBorrowMutability::Not => {
651 "unnecessary allocation, use `&` instead"
653 adjustment::AutoBorrowMutability::Mut { .. } => {
654 "unnecessary allocation, use `&mut` instead"
657 cx.span_lint(UNUSED_ALLOCATION, e.span, msg);