1 use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
2 use rustc::ty::adjustment;
3 use rustc::ty::{self, Ty};
6 use rustc_ast::util::parser;
7 use rustc_ast_pretty::pprust;
8 use rustc_data_structures::fx::FxHashMap;
9 use rustc_errors::{pluralize, Applicability};
10 use rustc_feature::{AttributeType, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP};
12 use rustc_hir::def::{DefKind, Res};
13 use rustc_hir::def_id::DefId;
14 use rustc_session::lint::builtin::UNUSED_ATTRIBUTES;
15 use rustc_span::symbol::Symbol;
16 use rustc_span::symbol::{kw, sym};
17 use rustc_span::{BytePos, Span};
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::AssocFn, 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 {
107 cx.struct_span_lint(UNUSED_MUST_USE, expr.span, |lint| {
108 lint.build(&format!("unused {} that must be used", must_use_op)).emit()
113 if !(type_permits_lack_of_use || fn_warned || op_warned) {
114 cx.struct_span_lint(UNUSED_RESULTS, s.span, |lint| lint.build("unused result").emit());
117 // Returns whether an error has been emitted (and thus another does not need to be later).
118 fn check_must_use_ty<'tcx>(
119 cx: &LateContext<'_, 'tcx>,
121 expr: &hir::Expr<'_>,
128 || cx.tcx.is_ty_uninhabited_from(
129 cx.tcx.parent_module(expr.hir_id).to_def_id(),
137 let plural_suffix = pluralize!(plural_len);
140 ty::Adt(..) if ty.is_box() => {
141 let boxed_ty = ty.boxed_ty();
142 let descr_pre = &format!("{}boxed ", descr_pre);
143 check_must_use_ty(cx, boxed_ty, expr, span, descr_pre, descr_post, plural_len)
145 ty::Adt(def, _) => check_must_use_def(cx, def.did, span, descr_pre, descr_post),
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;
153 &format!("{}implementer{} of ", descr_pre, plural_suffix,);
154 if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
162 ty::Dynamic(binder, _) => {
163 let mut has_emitted = false;
164 for predicate in binder.skip_binder().iter() {
165 if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate {
166 let def_id = trait_ref.def_id;
168 &format!(" trait object{}{}", plural_suffix, descr_post,);
169 if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
177 ty::Tuple(ref tys) => {
178 let mut has_emitted = false;
179 let spans = if let hir::ExprKind::Tup(comps) = &expr.kind {
180 debug_assert_eq!(comps.len(), tys.len());
181 comps.iter().map(|e| e.span).collect()
185 for (i, ty) in tys.iter().map(|k| k.expect_ty()).enumerate() {
186 let descr_post = &format!(" in tuple element {}", i);
187 let span = *spans.get(i).unwrap_or(&span);
188 if check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, plural_len)
195 ty::Array(ty, len) => match len.try_eval_usize(cx.tcx, cx.param_env) {
196 // If the array is definitely non-empty, we can do `#[must_use]` checking.
197 Some(n) if n != 0 => {
198 let descr_pre = &format!("{}array{} of ", descr_pre, plural_suffix,);
199 check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, n as usize + 1)
201 // Otherwise, we don't lint, to avoid false positives.
208 // Returns whether an error has been emitted (and thus another does not need to be later).
209 // FIXME: Args desc_{pre,post}_path could be made lazy by taking Fn() -> &str, but this
210 // would make calling it a big awkward. Could also take String (so args are moved), but
211 // this would still require a copy into the format string, which would only be executed
213 fn check_must_use_def(
214 cx: &LateContext<'_, '_>,
217 descr_pre_path: &str,
218 descr_post_path: &str,
220 for attr in cx.tcx.get_attrs(def_id).iter() {
221 if attr.check_name(sym::must_use) {
222 cx.struct_span_lint(UNUSED_MUST_USE, span, |lint| {
224 "unused {}`{}`{} that must be used",
226 cx.tcx.def_path_str(def_id),
229 let mut err = lint.build(&msg);
230 // check for #[must_use = "..."]
231 if let Some(note) = attr.value_str() {
232 err.note(¬e.as_str());
247 "path statements with no effect"
250 declare_lint_pass!(PathStatements => [PATH_STATEMENTS]);
252 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PathStatements {
253 fn check_stmt(&mut self, cx: &LateContext<'_, '_>, s: &hir::Stmt<'_>) {
254 if let hir::StmtKind::Semi(ref expr) = s.kind {
255 if let hir::ExprKind::Path(_) = expr.kind {
256 cx.struct_span_lint(PATH_STATEMENTS, s.span, |lint| {
257 lint.build("path statement with no effect").emit()
264 #[derive(Copy, Clone)]
265 pub struct UnusedAttributes {
266 builtin_attributes: &'static FxHashMap<Symbol, &'static BuiltinAttribute>,
269 impl UnusedAttributes {
270 pub fn new() -> Self {
271 UnusedAttributes { builtin_attributes: &*BUILTIN_ATTRIBUTE_MAP }
275 impl_lint_pass!(UnusedAttributes => [UNUSED_ATTRIBUTES]);
277 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAttributes {
278 fn check_attribute(&mut self, cx: &LateContext<'_, '_>, attr: &ast::Attribute) {
279 debug!("checking attribute: {:?}", attr);
281 if attr.is_doc_comment() {
285 let attr_info = attr.ident().and_then(|ident| self.builtin_attributes.get(&ident.name));
287 if let Some(&&(name, ty, ..)) = attr_info {
289 AttributeType::Whitelisted => {
290 debug!("{:?} is Whitelisted", name);
297 if !attr::is_used(attr) {
298 debug!("emitting warning for: {:?}", attr);
299 cx.struct_span_lint(UNUSED_ATTRIBUTES, attr.span, |lint| {
300 lint.build("unused attribute").emit()
302 // Is it a builtin attribute that must be used at the crate level?
303 if attr_info.map_or(false, |(_, ty, ..)| ty == &AttributeType::CrateLevel) {
304 cx.struct_span_lint(UNUSED_ATTRIBUTES, attr.span, |lint| {
305 let msg = match attr.style {
306 ast::AttrStyle::Outer => {
307 "crate-level attribute should be an inner attribute: add an exclamation \
310 ast::AttrStyle::Inner => "crate-level attribute should be in the root module",
312 lint.build(msg).emit()
316 debug!("Attr was used: {:?}", attr);
322 pub(super) UNUSED_PARENS,
324 "`if`, `match`, `while` and `return` do not need parentheses"
327 declare_lint_pass!(UnusedParens => [UNUSED_PARENS]);
330 fn is_expr_parens_necessary(inner: &ast::Expr, followed_by_block: bool) -> bool {
332 && match inner.kind {
333 ast::ExprKind::Ret(_) | ast::ExprKind::Break(..) => true,
334 _ => parser::contains_exterior_struct_lit(&inner),
338 fn check_unused_parens_expr(
340 cx: &EarlyContext<'_>,
343 followed_by_block: bool,
344 left_pos: Option<BytePos>,
345 right_pos: Option<BytePos>,
348 ast::ExprKind::Paren(ref inner) => {
349 if !Self::is_expr_parens_necessary(inner, followed_by_block)
350 && value.attrs.is_empty()
351 && !value.span.from_expansion()
354 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(value.span) {
357 pprust::expr_to_string(value)
360 left_pos.map(|s| s >= value.span.lo()).unwrap_or(false),
361 right_pos.map(|s| s <= value.span.hi()).unwrap_or(false),
363 Self::remove_outer_parens(cx, value.span, &expr_text, msg, keep_space);
366 ast::ExprKind::Let(_, ref expr) => {
367 // FIXME(#60336): Properly handle `let true = (false && true)`
368 // actually needing the parenthesis.
369 self.check_unused_parens_expr(
372 "`let` head expression",
382 fn check_unused_parens_pat(
384 cx: &EarlyContext<'_>,
389 use ast::{BindingMode, Mutability, PatKind};
391 if let PatKind::Paren(inner) = &value.kind {
393 // The lint visitor will visit each subpattern of `p`. We do not want to lint
394 // any range pattern no matter where it occurs in the pattern. For something like
395 // `&(a..=b)`, there is a recursive `check_pat` on `a` and `b`, but we will assume
396 // that if there are unnecessary parens they serve a purpose of readability.
397 PatKind::Range(..) => return,
398 // Avoid `p0 | .. | pn` if we should.
399 PatKind::Or(..) if avoid_or => return,
400 // Avoid `mut x` and `mut x @ p` if we should:
401 PatKind::Ident(BindingMode::ByValue(Mutability::Mut), ..) if avoid_mut => return,
402 // Otherwise proceed with linting.
407 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(value.span) {
410 pprust::pat_to_string(value)
412 Self::remove_outer_parens(cx, value.span, &pattern_text, "pattern", (false, false));
416 fn remove_outer_parens(
417 cx: &EarlyContext<'_>,
421 keep_space: (bool, bool),
423 cx.struct_span_lint(UNUSED_PARENS, span, |lint| {
424 let span_msg = format!("unnecessary parentheses around {}", msg);
425 let mut err = lint.build(&span_msg);
426 let mut ate_left_paren = false;
427 let mut ate_right_paren = false;
428 let parens_removed = pattern.trim_matches(|c| match c {
433 ate_left_paren = true;
441 ate_right_paren = true;
449 let mut replace = if keep_space.0 {
450 let mut s = String::from(" ");
451 s.push_str(parens_removed);
454 String::from(parens_removed)
463 err.span_suggestion_short(
465 "remove these parentheses",
467 Applicability::MachineApplicable,
474 impl EarlyLintPass for UnusedParens {
475 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
476 use rustc_ast::ast::ExprKind::*;
477 let (value, msg, followed_by_block, left_pos, right_pos) = match e.kind {
478 Let(ref pat, ..) => {
479 self.check_unused_parens_pat(cx, pat, false, false);
483 If(ref cond, ref block, ..) => {
484 let left = e.span.lo() + rustc_span::BytePos(2);
485 let right = block.span.lo();
486 (cond, "`if` condition", true, Some(left), Some(right))
489 While(ref cond, ref block, ..) => {
490 let left = e.span.lo() + rustc_span::BytePos(5);
491 let right = block.span.lo();
492 (cond, "`while` condition", true, Some(left), Some(right))
495 ForLoop(ref pat, ref cond, ref block, ..) => {
496 self.check_unused_parens_pat(cx, pat, false, false);
497 (cond, "`for` head expression", true, None, Some(block.span.lo()))
500 Match(ref head, _) => {
501 let left = e.span.lo() + rustc_span::BytePos(5);
502 (head, "`match` head expression", true, Some(left), None)
505 Ret(Some(ref value)) => {
506 let left = e.span.lo() + rustc_span::BytePos(3);
507 (value, "`return` value", false, Some(left), None)
510 Assign(_, ref value, _) => (value, "assigned value", false, None, None),
511 AssignOp(.., ref value) => (value, "assigned value", false, None, None),
512 // either function/method call, or something this lint doesn't care about
513 ref call_or_other => {
514 let (args_to_check, call_kind) = match *call_or_other {
515 Call(_, ref args) => (&args[..], "function"),
516 // first "argument" is self (which sometimes needs parens)
517 MethodCall(_, ref args) => (&args[1..], "method"),
518 // actual catch-all arm
523 // Don't lint if this is a nested macro expansion: otherwise, the lint could
524 // trigger in situations that macro authors shouldn't have to care about, e.g.,
525 // when a parenthesized token tree matched in one macro expansion is matched as
526 // an expression in another and used as a fn/method argument (Issue #47775)
527 if e.span.ctxt().outer_expn_data().call_site.from_expansion() {
530 let msg = format!("{} argument", call_kind);
531 for arg in args_to_check {
532 self.check_unused_parens_expr(cx, arg, &msg, false, None, None);
537 self.check_unused_parens_expr(cx, &value, msg, followed_by_block, left_pos, right_pos);
540 fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
541 use ast::{Mutability, PatKind::*};
543 // Do not lint on `(..)` as that will result in the other arms being useless.
545 // The other cases do not contain sub-patterns.
546 | Wild | Rest | Lit(..) | MacCall(..) | Range(..) | Ident(.., None) | Path(..) => {},
547 // These are list-like patterns; parens can always be removed.
548 TupleStruct(_, ps) | Tuple(ps) | Slice(ps) | Or(ps) => for p in ps {
549 self.check_unused_parens_pat(cx, p, false, false);
551 Struct(_, fps, _) => for f in fps {
552 self.check_unused_parens_pat(cx, &f.pat, false, false);
554 // Avoid linting on `i @ (p0 | .. | pn)` and `box (p0 | .. | pn)`, #64106.
555 Ident(.., Some(p)) | Box(p) => self.check_unused_parens_pat(cx, p, true, false),
556 // Avoid linting on `&(mut x)` as `&mut x` has a different meaning, #55342.
557 // Also avoid linting on `& mut? (p0 | .. | pn)`, #64106.
558 Ref(p, m) => self.check_unused_parens_pat(cx, p, true, *m == Mutability::Not),
562 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
563 use ast::StmtKind::*;
566 Local(ref local) => {
567 self.check_unused_parens_pat(cx, &local.pat, false, false);
569 if let Some(ref value) = local.init {
570 self.check_unused_parens_expr(cx, &value, "assigned value", false, None, None);
574 self.check_unused_parens_expr(cx, &expr, "block return value", false, None, None);
580 fn check_param(&mut self, cx: &EarlyContext<'_>, param: &ast::Param) {
581 self.check_unused_parens_pat(cx, ¶m.pat, true, false);
584 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
585 self.check_unused_parens_pat(cx, &arm.pat, false, false);
588 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
589 if let &ast::TyKind::Paren(ref r) = &ty.kind {
591 &ast::TyKind::TraitObject(..) => {}
592 &ast::TyKind::ImplTrait(_, ref bounds) if bounds.len() > 1 => {}
595 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(ty.span) {
598 pprust::ty_to_string(ty)
601 Self::remove_outer_parens(cx, ty.span, &pattern_text, "type", (false, false));
607 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
608 use ast::ItemKind::*;
610 if let Const(.., Some(expr)) | Static(.., Some(expr)) = &item.kind {
611 self.check_unused_parens_expr(cx, expr, "assigned value", false, None, None);
617 UNUSED_IMPORT_BRACES,
619 "unnecessary braces around an imported item"
622 declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]);
624 impl UnusedImportBraces {
625 fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
626 if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
627 // Recursively check nested UseTrees
628 for &(ref tree, _) in items {
629 self.check_use_tree(cx, tree, item);
632 // Trigger the lint only if there is one nested item
633 if items.len() != 1 {
637 // Trigger the lint if the nested item is a non-self single item
638 let node_name = match items[0].0.kind {
639 ast::UseTreeKind::Simple(rename, ..) => {
640 let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
641 if orig_ident.name == kw::SelfLower {
644 rename.unwrap_or(orig_ident).name
646 ast::UseTreeKind::Glob => Symbol::intern("*"),
647 ast::UseTreeKind::Nested(_) => return,
650 cx.struct_span_lint(UNUSED_IMPORT_BRACES, item.span, |lint| {
651 lint.build(&format!("braces around {} is unnecessary", node_name)).emit()
657 impl EarlyLintPass for UnusedImportBraces {
658 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
659 if let ast::ItemKind::Use(ref use_tree) = item.kind {
660 self.check_use_tree(cx, use_tree, item);
666 pub(super) UNUSED_ALLOCATION,
668 "detects unnecessary allocations that can be eliminated"
671 declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]);
673 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAllocation {
674 fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr<'_>) {
676 hir::ExprKind::Box(_) => {}
680 for adj in cx.tables.expr_adjustments(e) {
681 if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
682 cx.struct_span_lint(UNUSED_ALLOCATION, e.span, |lint| {
684 adjustment::AutoBorrowMutability::Not => {
685 "unnecessary allocation, use `&` instead"
687 adjustment::AutoBorrowMutability::Mut { .. } => {
688 "unnecessary allocation, use `&mut` instead"
691 lint.build(msg).emit()