1 use lint::{EarlyContext, LateContext, LintArray, LintContext};
2 use lint::{EarlyLintPass, LateLintPass, LintPass};
4 use rustc::hir::def::{DefKind, Res};
5 use rustc::hir::def_id::DefId;
7 use rustc::lint::builtin::UNUSED_ATTRIBUTES;
8 use rustc::ty::adjustment;
9 use rustc::ty::{self, Ty};
10 use rustc_data_structures::fx::FxHashMap;
11 use rustc_feature::{AttributeType, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP};
15 use syntax::errors::{pluralize, Applicability};
16 use syntax::print::pprust;
17 use syntax::symbol::Symbol;
18 use syntax::symbol::{kw, sym};
19 use syntax::util::parser;
20 use syntax_pos::{BytePos, Span};
27 "unused result of a type flagged as `#[must_use]`",
28 report_in_external_macro
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.kind {
42 hir::StmtKind::Semi(ref expr) => &**expr,
46 if let hir::ExprKind::Ret(..) = expr.kind {
50 let ty = cx.tables.expr_ty(&expr);
51 let type_permits_lack_of_use = check_must_use_ty(cx, ty, &expr, s.span, "", "", 1);
53 let mut fn_warned = false;
54 let mut op_warned = false;
55 let maybe_def_id = match expr.kind {
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) | Res::Def(DefKind::Method, def_id) => {
63 // `Res::Local` if it was a closure, for which we
64 // do not currently support must-use linting
71 hir::ExprKind::MethodCall(..) => cx.tables.type_dependent_def_id(expr.hir_id),
74 if let Some(def_id) = maybe_def_id {
75 fn_warned = check_must_use_def(cx, def_id, s.span, "return value of ", "");
76 } else if type_permits_lack_of_use {
77 // We don't warn about unused unit or uninhabited types.
78 // (See https://github.com/rust-lang/rust/issues/43806 for details.)
82 let must_use_op = match expr.kind {
83 // Hardcoding operators here seemed more expedient than the
84 // refactoring that would be needed to look up the `#[must_use]`
85 // attribute which does exist on the comparison trait methods
86 hir::ExprKind::Binary(bin_op, ..) => match bin_op.node {
92 | hir::BinOpKind::Gt => Some("comparison"),
97 | hir::BinOpKind::Rem => Some("arithmetic operation"),
98 hir::BinOpKind::And | hir::BinOpKind::Or => Some("logical operation"),
99 hir::BinOpKind::BitXor
100 | hir::BinOpKind::BitAnd
101 | hir::BinOpKind::BitOr
102 | hir::BinOpKind::Shl
103 | hir::BinOpKind::Shr => Some("bitwise operation"),
105 hir::ExprKind::Unary(..) => Some("unary operation"),
109 if let Some(must_use_op) = must_use_op {
113 &format!("unused {} that must be used", must_use_op),
118 if !(type_permits_lack_of_use || fn_warned || op_warned) {
119 cx.span_lint(UNUSED_RESULTS, s.span, "unused result");
122 // Returns whether an error has been emitted (and thus another does not need to be later).
123 fn check_must_use_ty<'tcx>(
124 cx: &LateContext<'_, 'tcx>,
126 expr: &hir::Expr<'_>,
133 || cx.tcx.is_ty_uninhabited_from(cx.tcx.hir().get_module_parent(expr.hir_id), ty)
138 let plural_suffix = pluralize!(plural_len);
141 ty::Adt(..) if ty.is_box() => {
142 let boxed_ty = ty.boxed_ty();
143 let descr_pre = &format!("{}boxed ", descr_pre);
144 check_must_use_ty(cx, boxed_ty, expr, span, descr_pre, descr_post, plural_len)
146 ty::Adt(def, _) => check_must_use_def(cx, def.did, span, descr_pre, descr_post),
147 ty::Opaque(def, _) => {
148 let mut has_emitted = false;
149 for (predicate, _) in cx.tcx.predicates_of(def).predicates {
150 if let ty::Predicate::Trait(ref poly_trait_predicate) = predicate {
151 let trait_ref = poly_trait_predicate.skip_binder().trait_ref;
152 let def_id = trait_ref.def_id;
154 &format!("{}implementer{} of ", descr_pre, plural_suffix,);
155 if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
163 ty::Dynamic(binder, _) => {
164 let mut has_emitted = false;
165 for predicate in binder.skip_binder().iter() {
166 if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate {
167 let def_id = trait_ref.def_id;
169 &format!(" trait object{}{}", plural_suffix, descr_post,);
170 if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
178 ty::Tuple(ref tys) => {
179 let mut has_emitted = false;
180 let spans = if let hir::ExprKind::Tup(comps) = &expr.kind {
181 debug_assert_eq!(comps.len(), tys.len());
182 comps.iter().map(|e| e.span).collect()
186 for (i, ty) in tys.iter().map(|k| k.expect_ty()).enumerate() {
187 let descr_post = &format!(" in tuple element {}", i);
188 let span = *spans.get(i).unwrap_or(&span);
189 if check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, plural_len)
196 ty::Array(ty, len) => match len.try_eval_usize(cx.tcx, cx.param_env) {
197 // If the array is definitely non-empty, we can do `#[must_use]` checking.
198 Some(n) if n != 0 => {
199 let descr_pre = &format!("{}array{} of ", descr_pre, plural_suffix,);
200 check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, n as usize + 1)
202 // Otherwise, we don't lint, to avoid false positives.
209 // Returns whether an error has been emitted (and thus another does not need to be later).
210 fn check_must_use_def(
211 cx: &LateContext<'_, '_>,
214 descr_pre_path: &str,
215 descr_post_path: &str,
217 for attr in cx.tcx.get_attrs(def_id).iter() {
218 if attr.check_name(sym::must_use) {
220 "unused {}`{}`{} that must be used",
222 cx.tcx.def_path_str(def_id),
225 let mut err = cx.struct_span_lint(UNUSED_MUST_USE, span, &msg);
226 // check for #[must_use = "..."]
227 if let Some(note) = attr.value_str() {
228 err.note(¬e.as_str());
242 "path statements with no effect"
245 declare_lint_pass!(PathStatements => [PATH_STATEMENTS]);
247 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PathStatements {
248 fn check_stmt(&mut self, cx: &LateContext<'_, '_>, s: &hir::Stmt<'_>) {
249 if let hir::StmtKind::Semi(ref expr) = s.kind {
250 if let hir::ExprKind::Path(_) = expr.kind {
251 cx.span_lint(PATH_STATEMENTS, s.span, "path statement with no effect");
257 #[derive(Copy, Clone)]
258 pub struct UnusedAttributes {
259 builtin_attributes: &'static FxHashMap<Symbol, &'static BuiltinAttribute>,
262 impl UnusedAttributes {
263 pub fn new() -> Self {
264 UnusedAttributes { builtin_attributes: &*BUILTIN_ATTRIBUTE_MAP }
268 impl_lint_pass!(UnusedAttributes => [UNUSED_ATTRIBUTES]);
270 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAttributes {
271 fn check_attribute(&mut self, cx: &LateContext<'_, '_>, attr: &ast::Attribute) {
272 debug!("checking attribute: {:?}", attr);
274 let attr_info = attr.ident().and_then(|ident| self.builtin_attributes.get(&ident.name));
276 if let Some(&&(name, ty, ..)) = attr_info {
278 AttributeType::Whitelisted => {
279 debug!("{:?} is Whitelisted", name);
286 if !attr::is_used(attr) {
287 debug!("emitting warning for: {:?}", attr);
288 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
289 // Is it a builtin attribute that must be used at the crate level?
290 if attr_info.map_or(false, |(_, ty, ..)| ty == &AttributeType::CrateLevel) {
291 let msg = match attr.style {
292 ast::AttrStyle::Outer => {
293 "crate-level attribute should be an inner attribute: add an exclamation \
296 ast::AttrStyle::Inner => "crate-level attribute should be in the root module",
298 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
301 debug!("Attr was used: {:?}", attr);
307 pub(super) UNUSED_PARENS,
309 "`if`, `match`, `while` and `return` do not need parentheses"
312 declare_lint_pass!(UnusedParens => [UNUSED_PARENS]);
315 fn is_expr_parens_necessary(inner: &ast::Expr, followed_by_block: bool) -> bool {
317 && match inner.kind {
318 ast::ExprKind::Ret(_) | ast::ExprKind::Break(..) => true,
319 _ => parser::contains_exterior_struct_lit(&inner),
323 fn check_unused_parens_expr(
325 cx: &EarlyContext<'_>,
328 followed_by_block: bool,
329 left_pos: Option<BytePos>,
330 right_pos: Option<BytePos>,
333 ast::ExprKind::Paren(ref inner) => {
334 if !Self::is_expr_parens_necessary(inner, followed_by_block)
335 && value.attrs.is_empty()
336 && !value.span.from_expansion()
339 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(value.span) {
342 pprust::expr_to_string(value)
345 left_pos.map(|s| s >= value.span.lo()).unwrap_or(false),
346 right_pos.map(|s| s <= value.span.hi()).unwrap_or(false),
348 Self::remove_outer_parens(cx, value.span, &expr_text, msg, keep_space);
351 ast::ExprKind::Let(_, ref expr) => {
352 // FIXME(#60336): Properly handle `let true = (false && true)`
353 // actually needing the parenthesis.
354 self.check_unused_parens_expr(
357 "`let` head expression",
367 fn check_unused_parens_pat(
369 cx: &EarlyContext<'_>,
374 use ast::{BindingMode, Mutability, PatKind};
376 if let PatKind::Paren(inner) = &value.kind {
378 // The lint visitor will visit each subpattern of `p`. We do not want to lint
379 // any range pattern no matter where it occurs in the pattern. For something like
380 // `&(a..=b)`, there is a recursive `check_pat` on `a` and `b`, but we will assume
381 // that if there are unnecessary parens they serve a purpose of readability.
382 PatKind::Range(..) => return,
383 // Avoid `p0 | .. | pn` if we should.
384 PatKind::Or(..) if avoid_or => return,
385 // Avoid `mut x` and `mut x @ p` if we should:
386 PatKind::Ident(BindingMode::ByValue(Mutability::Mut), ..) if avoid_mut => return,
387 // Otherwise proceed with linting.
392 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(value.span) {
395 pprust::pat_to_string(value)
397 Self::remove_outer_parens(cx, value.span, &pattern_text, "pattern", (false, false));
401 fn remove_outer_parens(
402 cx: &EarlyContext<'_>,
406 keep_space: (bool, bool),
408 let span_msg = format!("unnecessary parentheses around {}", msg);
409 let mut err = cx.struct_span_lint(UNUSED_PARENS, span, &span_msg);
410 let mut ate_left_paren = false;
411 let mut ate_right_paren = false;
412 let parens_removed = pattern.trim_matches(|c| match c {
417 ate_left_paren = true;
425 ate_right_paren = true;
433 let mut replace = if keep_space.0 {
434 let mut s = String::from(" ");
435 s.push_str(parens_removed);
438 String::from(parens_removed)
447 err.span_suggestion_short(
449 "remove these parentheses",
451 Applicability::MachineApplicable,
457 impl EarlyLintPass for UnusedParens {
458 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
459 use syntax::ast::ExprKind::*;
460 let (value, msg, followed_by_block, left_pos, right_pos) = match e.kind {
461 Let(ref pat, ..) => {
462 self.check_unused_parens_pat(cx, pat, false, false);
466 If(ref cond, ref block, ..) => {
467 let left = e.span.lo() + syntax_pos::BytePos(2);
468 let right = block.span.lo();
469 (cond, "`if` condition", true, Some(left), Some(right))
472 While(ref cond, ref block, ..) => {
473 let left = e.span.lo() + syntax_pos::BytePos(5);
474 let right = block.span.lo();
475 (cond, "`while` condition", true, Some(left), Some(right))
478 ForLoop(ref pat, ref cond, ref block, ..) => {
479 self.check_unused_parens_pat(cx, pat, false, false);
480 (cond, "`for` head expression", true, None, Some(block.span.lo()))
483 Match(ref head, _) => {
484 let left = e.span.lo() + syntax_pos::BytePos(5);
485 (head, "`match` head expression", true, Some(left), None)
488 Ret(Some(ref value)) => {
489 let left = e.span.lo() + syntax_pos::BytePos(3);
490 (value, "`return` value", false, Some(left), None)
493 Assign(_, ref value, _) => (value, "assigned value", false, None, None),
494 AssignOp(.., ref value) => (value, "assigned value", false, None, None),
495 // either function/method call, or something this lint doesn't care about
496 ref call_or_other => {
497 let (args_to_check, call_kind) = match *call_or_other {
498 Call(_, ref args) => (&args[..], "function"),
499 // first "argument" is self (which sometimes needs parens)
500 MethodCall(_, ref args) => (&args[1..], "method"),
501 // actual catch-all arm
506 // Don't lint if this is a nested macro expansion: otherwise, the lint could
507 // trigger in situations that macro authors shouldn't have to care about, e.g.,
508 // when a parenthesized token tree matched in one macro expansion is matched as
509 // an expression in another and used as a fn/method argument (Issue #47775)
510 if e.span.ctxt().outer_expn_data().call_site.from_expansion() {
513 let msg = format!("{} argument", call_kind);
514 for arg in args_to_check {
515 self.check_unused_parens_expr(cx, arg, &msg, false, None, None);
520 self.check_unused_parens_expr(cx, &value, msg, followed_by_block, left_pos, right_pos);
523 fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
524 use ast::{Mutability, PatKind::*};
526 // Do not lint on `(..)` as that will result in the other arms being useless.
528 // The other cases do not contain sub-patterns.
529 | Wild | Rest | Lit(..) | Mac(..) | Range(..) | Ident(.., None) | Path(..) => return,
530 // These are list-like patterns; parens can always be removed.
531 TupleStruct(_, ps) | Tuple(ps) | Slice(ps) | Or(ps) => for p in ps {
532 self.check_unused_parens_pat(cx, p, false, false);
534 Struct(_, fps, _) => for f in fps {
535 self.check_unused_parens_pat(cx, &f.pat, false, false);
537 // Avoid linting on `i @ (p0 | .. | pn)` and `box (p0 | .. | pn)`, #64106.
538 Ident(.., Some(p)) | Box(p) => self.check_unused_parens_pat(cx, p, true, false),
539 // Avoid linting on `&(mut x)` as `&mut x` has a different meaning, #55342.
540 // Also avoid linting on `& mut? (p0 | .. | pn)`, #64106.
541 Ref(p, m) => self.check_unused_parens_pat(cx, p, true, *m == Mutability::Not),
545 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
546 if let ast::StmtKind::Local(ref local) = s.kind {
547 self.check_unused_parens_pat(cx, &local.pat, false, false);
549 if let Some(ref value) = local.init {
550 self.check_unused_parens_expr(cx, &value, "assigned value", false, None, None);
555 fn check_param(&mut self, cx: &EarlyContext<'_>, param: &ast::Param) {
556 self.check_unused_parens_pat(cx, ¶m.pat, true, false);
559 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
560 self.check_unused_parens_pat(cx, &arm.pat, false, false);
563 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
564 if let &ast::TyKind::Paren(ref r) = &ty.kind {
566 &ast::TyKind::TraitObject(..) => {}
567 &ast::TyKind::ImplTrait(_, ref bounds) if bounds.len() > 1 => {}
570 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(ty.span) {
573 pprust::ty_to_string(ty)
576 Self::remove_outer_parens(cx, ty.span, &pattern_text, "type", (false, false));
584 UNUSED_IMPORT_BRACES,
586 "unnecessary braces around an imported item"
589 declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]);
591 impl UnusedImportBraces {
592 fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
593 if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
594 // Recursively check nested UseTrees
595 for &(ref tree, _) in items {
596 self.check_use_tree(cx, tree, item);
599 // Trigger the lint only if there is one nested item
600 if items.len() != 1 {
604 // Trigger the lint if the nested item is a non-self single item
605 let node_name = match items[0].0.kind {
606 ast::UseTreeKind::Simple(rename, ..) => {
607 let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
608 if orig_ident.name == kw::SelfLower {
611 rename.unwrap_or(orig_ident).name
613 ast::UseTreeKind::Glob => Symbol::intern("*"),
614 ast::UseTreeKind::Nested(_) => return,
617 let msg = format!("braces around {} is unnecessary", node_name);
618 cx.span_lint(UNUSED_IMPORT_BRACES, item.span, &msg);
623 impl EarlyLintPass for UnusedImportBraces {
624 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
625 if let ast::ItemKind::Use(ref use_tree) = item.kind {
626 self.check_use_tree(cx, use_tree, item);
632 pub(super) UNUSED_ALLOCATION,
634 "detects unnecessary allocations that can be eliminated"
637 declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]);
639 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAllocation {
640 fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr<'_>) {
642 hir::ExprKind::Box(_) => {}
646 for adj in cx.tables.expr_adjustments(e) {
647 if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
649 adjustment::AutoBorrowMutability::Not => {
650 "unnecessary allocation, use `&` instead"
652 adjustment::AutoBorrowMutability::Mut { .. } => {
653 "unnecessary allocation, use `&mut` instead"
656 cx.span_lint(UNUSED_ALLOCATION, e.span, msg);