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 {
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) {
216 cx.struct_span_lint(UNUSED_MUST_USE, span, |lint| {
218 "unused {}`{}`{} that must be used",
220 cx.tcx.def_path_str(def_id),
223 let mut err = lint.build(&msg);
224 // check for #[must_use = "..."]
225 if let Some(note) = attr.value_str() {
226 err.note(¬e.as_str());
241 "path statements with no effect"
244 declare_lint_pass!(PathStatements => [PATH_STATEMENTS]);
246 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PathStatements {
247 fn check_stmt(&mut self, cx: &LateContext<'_, '_>, s: &hir::Stmt<'_>) {
248 if let hir::StmtKind::Semi(ref expr) = s.kind {
249 if let hir::ExprKind::Path(_) = expr.kind {
250 cx.span_lint(PATH_STATEMENTS, s.span, "path statement with no effect");
256 #[derive(Copy, Clone)]
257 pub struct UnusedAttributes {
258 builtin_attributes: &'static FxHashMap<Symbol, &'static BuiltinAttribute>,
261 impl UnusedAttributes {
262 pub fn new() -> Self {
263 UnusedAttributes { builtin_attributes: &*BUILTIN_ATTRIBUTE_MAP }
267 impl_lint_pass!(UnusedAttributes => [UNUSED_ATTRIBUTES]);
269 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAttributes {
270 fn check_attribute(&mut self, cx: &LateContext<'_, '_>, attr: &ast::Attribute) {
271 debug!("checking attribute: {:?}", attr);
273 if attr.is_doc_comment() {
277 let attr_info = attr.ident().and_then(|ident| self.builtin_attributes.get(&ident.name));
279 if let Some(&&(name, ty, ..)) = attr_info {
281 AttributeType::Whitelisted => {
282 debug!("{:?} is Whitelisted", name);
289 if !attr::is_used(attr) {
290 debug!("emitting warning for: {:?}", attr);
291 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
292 // Is it a builtin attribute that must be used at the crate level?
293 if attr_info.map_or(false, |(_, ty, ..)| ty == &AttributeType::CrateLevel) {
294 let msg = match attr.style {
295 ast::AttrStyle::Outer => {
296 "crate-level attribute should be an inner attribute: add an exclamation \
299 ast::AttrStyle::Inner => "crate-level attribute should be in the root module",
301 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
304 debug!("Attr was used: {:?}", attr);
310 pub(super) UNUSED_PARENS,
312 "`if`, `match`, `while` and `return` do not need parentheses"
315 declare_lint_pass!(UnusedParens => [UNUSED_PARENS]);
318 fn is_expr_parens_necessary(inner: &ast::Expr, followed_by_block: bool) -> bool {
320 && match inner.kind {
321 ast::ExprKind::Ret(_) | ast::ExprKind::Break(..) => true,
322 _ => parser::contains_exterior_struct_lit(&inner),
326 fn check_unused_parens_expr(
328 cx: &EarlyContext<'_>,
331 followed_by_block: bool,
332 left_pos: Option<BytePos>,
333 right_pos: Option<BytePos>,
336 ast::ExprKind::Paren(ref inner) => {
337 if !Self::is_expr_parens_necessary(inner, followed_by_block)
338 && value.attrs.is_empty()
339 && !value.span.from_expansion()
342 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(value.span) {
345 pprust::expr_to_string(value)
348 left_pos.map(|s| s >= value.span.lo()).unwrap_or(false),
349 right_pos.map(|s| s <= value.span.hi()).unwrap_or(false),
351 Self::remove_outer_parens(cx, value.span, &expr_text, msg, keep_space);
354 ast::ExprKind::Let(_, ref expr) => {
355 // FIXME(#60336): Properly handle `let true = (false && true)`
356 // actually needing the parenthesis.
357 self.check_unused_parens_expr(
360 "`let` head expression",
370 fn check_unused_parens_pat(
372 cx: &EarlyContext<'_>,
377 use ast::{BindingMode, Mutability, PatKind};
379 if let PatKind::Paren(inner) = &value.kind {
381 // The lint visitor will visit each subpattern of `p`. We do not want to lint
382 // any range pattern no matter where it occurs in the pattern. For something like
383 // `&(a..=b)`, there is a recursive `check_pat` on `a` and `b`, but we will assume
384 // that if there are unnecessary parens they serve a purpose of readability.
385 PatKind::Range(..) => return,
386 // Avoid `p0 | .. | pn` if we should.
387 PatKind::Or(..) if avoid_or => return,
388 // Avoid `mut x` and `mut x @ p` if we should:
389 PatKind::Ident(BindingMode::ByValue(Mutability::Mut), ..) if avoid_mut => return,
390 // Otherwise proceed with linting.
395 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(value.span) {
398 pprust::pat_to_string(value)
400 Self::remove_outer_parens(cx, value.span, &pattern_text, "pattern", (false, false));
404 fn remove_outer_parens(
405 cx: &EarlyContext<'_>,
409 keep_space: (bool, bool),
411 cx.struct_span_lint(UNUSED_PARENS, span, |lint| {
412 let span_msg = format!("unnecessary parentheses around {}", msg);
413 let mut err = lint.build(&span_msg);
414 let mut ate_left_paren = false;
415 let mut ate_right_paren = false;
416 let parens_removed = pattern.trim_matches(|c| match c {
421 ate_left_paren = true;
429 ate_right_paren = true;
437 let mut replace = if keep_space.0 {
438 let mut s = String::from(" ");
439 s.push_str(parens_removed);
442 String::from(parens_removed)
451 err.span_suggestion_short(
453 "remove these parentheses",
455 Applicability::MachineApplicable,
462 impl EarlyLintPass for UnusedParens {
463 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
464 use syntax::ast::ExprKind::*;
465 let (value, msg, followed_by_block, left_pos, right_pos) = match e.kind {
466 Let(ref pat, ..) => {
467 self.check_unused_parens_pat(cx, pat, false, false);
471 If(ref cond, ref block, ..) => {
472 let left = e.span.lo() + rustc_span::BytePos(2);
473 let right = block.span.lo();
474 (cond, "`if` condition", true, Some(left), Some(right))
477 While(ref cond, ref block, ..) => {
478 let left = e.span.lo() + rustc_span::BytePos(5);
479 let right = block.span.lo();
480 (cond, "`while` condition", true, Some(left), Some(right))
483 ForLoop(ref pat, ref cond, ref block, ..) => {
484 self.check_unused_parens_pat(cx, pat, false, false);
485 (cond, "`for` head expression", true, None, Some(block.span.lo()))
488 Match(ref head, _) => {
489 let left = e.span.lo() + rustc_span::BytePos(5);
490 (head, "`match` head expression", true, Some(left), None)
493 Ret(Some(ref value)) => {
494 let left = e.span.lo() + rustc_span::BytePos(3);
495 (value, "`return` value", false, Some(left), None)
498 Assign(_, ref value, _) => (value, "assigned value", false, None, None),
499 AssignOp(.., ref value) => (value, "assigned value", false, None, None),
500 // either function/method call, or something this lint doesn't care about
501 ref call_or_other => {
502 let (args_to_check, call_kind) = match *call_or_other {
503 Call(_, ref args) => (&args[..], "function"),
504 // first "argument" is self (which sometimes needs parens)
505 MethodCall(_, ref args) => (&args[1..], "method"),
506 // actual catch-all arm
511 // Don't lint if this is a nested macro expansion: otherwise, the lint could
512 // trigger in situations that macro authors shouldn't have to care about, e.g.,
513 // when a parenthesized token tree matched in one macro expansion is matched as
514 // an expression in another and used as a fn/method argument (Issue #47775)
515 if e.span.ctxt().outer_expn_data().call_site.from_expansion() {
518 let msg = format!("{} argument", call_kind);
519 for arg in args_to_check {
520 self.check_unused_parens_expr(cx, arg, &msg, false, None, None);
525 self.check_unused_parens_expr(cx, &value, msg, followed_by_block, left_pos, right_pos);
528 fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
529 use ast::{Mutability, PatKind::*};
531 // Do not lint on `(..)` as that will result in the other arms being useless.
533 // The other cases do not contain sub-patterns.
534 | Wild | Rest | Lit(..) | Mac(..) | Range(..) | Ident(.., None) | Path(..) => return,
535 // These are list-like patterns; parens can always be removed.
536 TupleStruct(_, ps) | Tuple(ps) | Slice(ps) | Or(ps) => for p in ps {
537 self.check_unused_parens_pat(cx, p, false, false);
539 Struct(_, fps, _) => for f in fps {
540 self.check_unused_parens_pat(cx, &f.pat, false, false);
542 // Avoid linting on `i @ (p0 | .. | pn)` and `box (p0 | .. | pn)`, #64106.
543 Ident(.., Some(p)) | Box(p) => self.check_unused_parens_pat(cx, p, true, false),
544 // Avoid linting on `&(mut x)` as `&mut x` has a different meaning, #55342.
545 // Also avoid linting on `& mut? (p0 | .. | pn)`, #64106.
546 Ref(p, m) => self.check_unused_parens_pat(cx, p, true, *m == Mutability::Not),
550 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
551 use ast::StmtKind::*;
554 Local(ref local) => {
555 self.check_unused_parens_pat(cx, &local.pat, false, false);
557 if let Some(ref value) = local.init {
558 self.check_unused_parens_expr(cx, &value, "assigned value", false, None, None);
562 self.check_unused_parens_expr(cx, &expr, "block return value", false, None, None);
568 fn check_param(&mut self, cx: &EarlyContext<'_>, param: &ast::Param) {
569 self.check_unused_parens_pat(cx, ¶m.pat, true, false);
572 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
573 self.check_unused_parens_pat(cx, &arm.pat, false, false);
576 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
577 if let &ast::TyKind::Paren(ref r) = &ty.kind {
579 &ast::TyKind::TraitObject(..) => {}
580 &ast::TyKind::ImplTrait(_, ref bounds) if bounds.len() > 1 => {}
583 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(ty.span) {
586 pprust::ty_to_string(ty)
589 Self::remove_outer_parens(cx, ty.span, &pattern_text, "type", (false, false));
595 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
596 use ast::ItemKind::*;
598 if let Const(.., ref expr) | Static(.., ref expr) = item.kind {
599 self.check_unused_parens_expr(cx, expr, "assigned value", false, None, None);
605 UNUSED_IMPORT_BRACES,
607 "unnecessary braces around an imported item"
610 declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]);
612 impl UnusedImportBraces {
613 fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
614 if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
615 // Recursively check nested UseTrees
616 for &(ref tree, _) in items {
617 self.check_use_tree(cx, tree, item);
620 // Trigger the lint only if there is one nested item
621 if items.len() != 1 {
625 // Trigger the lint if the nested item is a non-self single item
626 let node_name = match items[0].0.kind {
627 ast::UseTreeKind::Simple(rename, ..) => {
628 let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
629 if orig_ident.name == kw::SelfLower {
632 rename.unwrap_or(orig_ident).name
634 ast::UseTreeKind::Glob => Symbol::intern("*"),
635 ast::UseTreeKind::Nested(_) => return,
638 let msg = format!("braces around {} is unnecessary", node_name);
639 cx.span_lint(UNUSED_IMPORT_BRACES, item.span, &msg);
644 impl EarlyLintPass for UnusedImportBraces {
645 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
646 if let ast::ItemKind::Use(ref use_tree) = item.kind {
647 self.check_use_tree(cx, use_tree, item);
653 pub(super) UNUSED_ALLOCATION,
655 "detects unnecessary allocations that can be eliminated"
658 declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]);
660 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAllocation {
661 fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr<'_>) {
663 hir::ExprKind::Box(_) => {}
667 for adj in cx.tables.expr_adjustments(e) {
668 if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
670 adjustment::AutoBorrowMutability::Not => {
671 "unnecessary allocation, use `&` instead"
673 adjustment::AutoBorrowMutability::Mut { .. } => {
674 "unnecessary allocation, use `&mut` instead"
677 cx.span_lint(UNUSED_ALLOCATION, e.span, msg);