1 use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
2 use rustc::ty::adjustment;
3 use rustc::ty::{self, Ty};
4 use rustc_ast_pretty::pprust;
5 use rustc_data_structures::fx::FxHashMap;
6 use rustc_errors::{pluralize, Applicability};
7 use rustc_feature::{AttributeType, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP};
9 use rustc_hir::def::{DefKind, Res};
10 use rustc_hir::def_id::DefId;
11 use rustc_session::lint::builtin::UNUSED_ATTRIBUTES;
12 use rustc_span::symbol::Symbol;
13 use rustc_span::symbol::{kw, sym};
14 use rustc_span::{BytePos, Span};
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 {
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(cx.tcx.hir().get_module_parent(expr.hir_id), ty)
133 let plural_suffix = pluralize!(plural_len);
136 ty::Adt(..) if ty.is_box() => {
137 let boxed_ty = ty.boxed_ty();
138 let descr_pre = &format!("{}boxed ", descr_pre);
139 check_must_use_ty(cx, boxed_ty, expr, span, descr_pre, descr_post, plural_len)
141 ty::Adt(def, _) => check_must_use_def(cx, def.did, span, descr_pre, descr_post),
142 ty::Opaque(def, _) => {
143 let mut has_emitted = false;
144 for (predicate, _) in cx.tcx.predicates_of(def).predicates {
145 if let ty::Predicate::Trait(ref poly_trait_predicate, _) = predicate {
146 let trait_ref = poly_trait_predicate.skip_binder().trait_ref;
147 let def_id = trait_ref.def_id;
149 &format!("{}implementer{} of ", descr_pre, plural_suffix,);
150 if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
158 ty::Dynamic(binder, _) => {
159 let mut has_emitted = false;
160 for predicate in binder.skip_binder().iter() {
161 if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate {
162 let def_id = trait_ref.def_id;
164 &format!(" trait object{}{}", plural_suffix, descr_post,);
165 if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
173 ty::Tuple(ref tys) => {
174 let mut has_emitted = false;
175 let spans = if let hir::ExprKind::Tup(comps) = &expr.kind {
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 = &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_pre, descr_post, plural_len)
191 ty::Array(ty, len) => match len.try_eval_usize(cx.tcx, cx.param_env) {
192 // If the array is definitely non-empty, we can do `#[must_use]` checking.
193 Some(n) if n != 0 => {
194 let descr_pre = &format!("{}array{} of ", descr_pre, plural_suffix,);
195 check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, n as usize + 1)
197 // Otherwise, we don't lint, to avoid false positives.
204 // Returns whether an error has been emitted (and thus another does not need to be later).
205 // FIXME: Args desc_{pre,post}_path could be made lazy by taking Fn() -> &str, but this
206 // would make calling it a big awkward. Could also take String (so args are moved), but
207 // this would still require a copy into the format string, which would only be executed
209 fn check_must_use_def(
210 cx: &LateContext<'_, '_>,
213 descr_pre_path: &str,
214 descr_post_path: &str,
216 for attr in cx.tcx.get_attrs(def_id).iter() {
217 if attr.check_name(sym::must_use) {
218 cx.struct_span_lint(UNUSED_MUST_USE, span, |lint| {
220 "unused {}`{}`{} that must be used",
222 cx.tcx.def_path_str(def_id),
225 let mut err = lint.build(&msg);
226 // check for #[must_use = "..."]
227 if let Some(note) = attr.value_str() {
228 err.note(¬e.as_str());
243 "path statements with no effect"
246 declare_lint_pass!(PathStatements => [PATH_STATEMENTS]);
248 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PathStatements {
249 fn check_stmt(&mut self, cx: &LateContext<'_, '_>, s: &hir::Stmt<'_>) {
250 if let hir::StmtKind::Semi(ref expr) = s.kind {
251 if let hir::ExprKind::Path(_) = expr.kind {
252 cx.struct_span_lint(PATH_STATEMENTS, s.span, |lint| {
253 lint.build("path statement with no effect").emit()
260 #[derive(Copy, Clone)]
261 pub struct UnusedAttributes {
262 builtin_attributes: &'static FxHashMap<Symbol, &'static BuiltinAttribute>,
265 impl UnusedAttributes {
266 pub fn new() -> Self {
267 UnusedAttributes { builtin_attributes: &*BUILTIN_ATTRIBUTE_MAP }
271 impl_lint_pass!(UnusedAttributes => [UNUSED_ATTRIBUTES]);
273 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAttributes {
274 fn check_attribute(&mut self, cx: &LateContext<'_, '_>, attr: &ast::Attribute) {
275 debug!("checking attribute: {:?}", attr);
277 if attr.is_doc_comment() {
281 let attr_info = attr.ident().and_then(|ident| self.builtin_attributes.get(&ident.name));
283 if let Some(&&(name, ty, ..)) = attr_info {
285 AttributeType::Whitelisted => {
286 debug!("{:?} is Whitelisted", name);
293 if !attr::is_used(attr) {
294 debug!("emitting warning for: {:?}", attr);
295 cx.struct_span_lint(UNUSED_ATTRIBUTES, attr.span, |lint| {
296 lint.build("unused attribute").emit()
298 // Is it a builtin attribute that must be used at the crate level?
299 if attr_info.map_or(false, |(_, ty, ..)| ty == &AttributeType::CrateLevel) {
300 cx.struct_span_lint(UNUSED_ATTRIBUTES, attr.span, |lint| {
301 let msg = match attr.style {
302 ast::AttrStyle::Outer => {
303 "crate-level attribute should be an inner attribute: add an exclamation \
306 ast::AttrStyle::Inner => "crate-level attribute should be in the root module",
308 lint.build(msg).emit()
312 debug!("Attr was used: {:?}", attr);
318 pub(super) UNUSED_PARENS,
320 "`if`, `match`, `while` and `return` do not need parentheses"
323 declare_lint_pass!(UnusedParens => [UNUSED_PARENS]);
326 fn is_expr_parens_necessary(inner: &ast::Expr, followed_by_block: bool) -> bool {
328 && match inner.kind {
329 ast::ExprKind::Ret(_) | ast::ExprKind::Break(..) => true,
330 _ => parser::contains_exterior_struct_lit(&inner),
334 fn check_unused_parens_expr(
336 cx: &EarlyContext<'_>,
339 followed_by_block: bool,
340 left_pos: Option<BytePos>,
341 right_pos: Option<BytePos>,
344 ast::ExprKind::Paren(ref inner) => {
345 if !Self::is_expr_parens_necessary(inner, followed_by_block)
346 && value.attrs.is_empty()
347 && !value.span.from_expansion()
350 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(value.span) {
353 pprust::expr_to_string(value)
356 left_pos.map(|s| s >= value.span.lo()).unwrap_or(false),
357 right_pos.map(|s| s <= value.span.hi()).unwrap_or(false),
359 Self::remove_outer_parens(cx, value.span, &expr_text, msg, keep_space);
362 ast::ExprKind::Let(_, ref expr) => {
363 // FIXME(#60336): Properly handle `let true = (false && true)`
364 // actually needing the parenthesis.
365 self.check_unused_parens_expr(
368 "`let` head expression",
378 fn check_unused_parens_pat(
380 cx: &EarlyContext<'_>,
385 use ast::{BindingMode, Mutability, PatKind};
387 if let PatKind::Paren(inner) = &value.kind {
389 // The lint visitor will visit each subpattern of `p`. We do not want to lint
390 // any range pattern no matter where it occurs in the pattern. For something like
391 // `&(a..=b)`, there is a recursive `check_pat` on `a` and `b`, but we will assume
392 // that if there are unnecessary parens they serve a purpose of readability.
393 PatKind::Range(..) => return,
394 // Avoid `p0 | .. | pn` if we should.
395 PatKind::Or(..) if avoid_or => return,
396 // Avoid `mut x` and `mut x @ p` if we should:
397 PatKind::Ident(BindingMode::ByValue(Mutability::Mut), ..) if avoid_mut => return,
398 // Otherwise proceed with linting.
403 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(value.span) {
406 pprust::pat_to_string(value)
408 Self::remove_outer_parens(cx, value.span, &pattern_text, "pattern", (false, false));
412 fn remove_outer_parens(
413 cx: &EarlyContext<'_>,
417 keep_space: (bool, bool),
419 cx.struct_span_lint(UNUSED_PARENS, span, |lint| {
420 let span_msg = format!("unnecessary parentheses around {}", msg);
421 let mut err = lint.build(&span_msg);
422 let mut ate_left_paren = false;
423 let mut ate_right_paren = false;
424 let parens_removed = pattern.trim_matches(|c| match c {
429 ate_left_paren = true;
437 ate_right_paren = true;
445 let mut replace = if keep_space.0 {
446 let mut s = String::from(" ");
447 s.push_str(parens_removed);
450 String::from(parens_removed)
459 err.span_suggestion_short(
461 "remove these parentheses",
463 Applicability::MachineApplicable,
470 impl EarlyLintPass for UnusedParens {
471 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
472 use syntax::ast::ExprKind::*;
473 let (value, msg, followed_by_block, left_pos, right_pos) = match e.kind {
474 Let(ref pat, ..) => {
475 self.check_unused_parens_pat(cx, pat, false, false);
479 If(ref cond, ref block, ..) => {
480 let left = e.span.lo() + rustc_span::BytePos(2);
481 let right = block.span.lo();
482 (cond, "`if` condition", true, Some(left), Some(right))
485 While(ref cond, ref block, ..) => {
486 let left = e.span.lo() + rustc_span::BytePos(5);
487 let right = block.span.lo();
488 (cond, "`while` condition", true, Some(left), Some(right))
491 ForLoop(ref pat, ref cond, ref block, ..) => {
492 self.check_unused_parens_pat(cx, pat, false, false);
493 (cond, "`for` head expression", true, None, Some(block.span.lo()))
496 Match(ref head, _) => {
497 let left = e.span.lo() + rustc_span::BytePos(5);
498 (head, "`match` head expression", true, Some(left), None)
501 Ret(Some(ref value)) => {
502 let left = e.span.lo() + rustc_span::BytePos(3);
503 (value, "`return` value", false, Some(left), None)
506 Assign(_, ref value, _) => (value, "assigned value", false, None, None),
507 AssignOp(.., ref value) => (value, "assigned value", false, None, None),
508 // either function/method call, or something this lint doesn't care about
509 ref call_or_other => {
510 let (args_to_check, call_kind) = match *call_or_other {
511 Call(_, ref args) => (&args[..], "function"),
512 // first "argument" is self (which sometimes needs parens)
513 MethodCall(_, ref args) => (&args[1..], "method"),
514 // actual catch-all arm
519 // Don't lint if this is a nested macro expansion: otherwise, the lint could
520 // trigger in situations that macro authors shouldn't have to care about, e.g.,
521 // when a parenthesized token tree matched in one macro expansion is matched as
522 // an expression in another and used as a fn/method argument (Issue #47775)
523 if e.span.ctxt().outer_expn_data().call_site.from_expansion() {
526 let msg = format!("{} argument", call_kind);
527 for arg in args_to_check {
528 self.check_unused_parens_expr(cx, arg, &msg, false, None, None);
533 self.check_unused_parens_expr(cx, &value, msg, followed_by_block, left_pos, right_pos);
536 fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
537 use ast::{Mutability, PatKind::*};
539 // Do not lint on `(..)` as that will result in the other arms being useless.
541 // The other cases do not contain sub-patterns.
542 | Wild | Rest | Lit(..) | Mac(..) | Range(..) | Ident(.., None) | Path(..) => return,
543 // These are list-like patterns; parens can always be removed.
544 TupleStruct(_, ps) | Tuple(ps) | Slice(ps) | Or(ps) => for p in ps {
545 self.check_unused_parens_pat(cx, p, false, false);
547 Struct(_, fps, _) => for f in fps {
548 self.check_unused_parens_pat(cx, &f.pat, false, false);
550 // Avoid linting on `i @ (p0 | .. | pn)` and `box (p0 | .. | pn)`, #64106.
551 Ident(.., Some(p)) | Box(p) => self.check_unused_parens_pat(cx, p, true, false),
552 // Avoid linting on `&(mut x)` as `&mut x` has a different meaning, #55342.
553 // Also avoid linting on `& mut? (p0 | .. | pn)`, #64106.
554 Ref(p, m) => self.check_unused_parens_pat(cx, p, true, *m == Mutability::Not),
558 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
559 use ast::StmtKind::*;
562 Local(ref local) => {
563 self.check_unused_parens_pat(cx, &local.pat, false, false);
565 if let Some(ref value) = local.init {
566 self.check_unused_parens_expr(cx, &value, "assigned value", false, None, None);
570 self.check_unused_parens_expr(cx, &expr, "block return value", false, None, None);
576 fn check_param(&mut self, cx: &EarlyContext<'_>, param: &ast::Param) {
577 self.check_unused_parens_pat(cx, ¶m.pat, true, false);
580 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
581 self.check_unused_parens_pat(cx, &arm.pat, false, false);
584 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
585 if let &ast::TyKind::Paren(ref r) = &ty.kind {
587 &ast::TyKind::TraitObject(..) => {}
588 &ast::TyKind::ImplTrait(_, ref bounds) if bounds.len() > 1 => {}
591 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(ty.span) {
594 pprust::ty_to_string(ty)
597 Self::remove_outer_parens(cx, ty.span, &pattern_text, "type", (false, false));
603 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
604 use ast::ItemKind::*;
606 if let Const(.., ref expr) | Static(.., ref expr) = item.kind {
607 self.check_unused_parens_expr(cx, expr, "assigned value", false, None, None);
613 UNUSED_IMPORT_BRACES,
615 "unnecessary braces around an imported item"
618 declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]);
620 impl UnusedImportBraces {
621 fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
622 if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
623 // Recursively check nested UseTrees
624 for &(ref tree, _) in items {
625 self.check_use_tree(cx, tree, item);
628 // Trigger the lint only if there is one nested item
629 if items.len() != 1 {
633 // Trigger the lint if the nested item is a non-self single item
634 let node_name = match items[0].0.kind {
635 ast::UseTreeKind::Simple(rename, ..) => {
636 let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
637 if orig_ident.name == kw::SelfLower {
640 rename.unwrap_or(orig_ident).name
642 ast::UseTreeKind::Glob => Symbol::intern("*"),
643 ast::UseTreeKind::Nested(_) => return,
646 cx.struct_span_lint(UNUSED_IMPORT_BRACES, item.span, |lint| {
647 lint.build(&format!("braces around {} is unnecessary", node_name)).emit()
653 impl EarlyLintPass for UnusedImportBraces {
654 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
655 if let ast::ItemKind::Use(ref use_tree) = item.kind {
656 self.check_use_tree(cx, use_tree, item);
662 pub(super) UNUSED_ALLOCATION,
664 "detects unnecessary allocations that can be eliminated"
667 declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]);
669 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAllocation {
670 fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr<'_>) {
672 hir::ExprKind::Box(_) => {}
676 for adj in cx.tables.expr_adjustments(e) {
677 if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
678 cx.struct_span_lint(UNUSED_ALLOCATION, e.span, |lint| {
680 adjustment::AutoBorrowMutability::Not => {
681 "unnecessary allocation, use `&` instead"
683 adjustment::AutoBorrowMutability::Mut { .. } => {
684 "unnecessary allocation, use `&mut` instead"
687 lint.build(msg).emit()