1 use rustc::hir::def::{Res, DefKind};
2 use rustc::hir::def_id::DefId;
4 use rustc::lint::builtin::UNUSED_ATTRIBUTES;
5 use rustc::ty::{self, Ty};
6 use rustc::ty::adjustment;
7 use rustc_data_structures::fx::FxHashMap;
8 use lint::{LateContext, EarlyContext, LintContext, LintArray};
9 use lint::{LintPass, EarlyLintPass, LateLintPass};
13 use syntax::errors::{Applicability, pluralize};
14 use syntax::feature_gate::{AttributeType, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP};
15 use syntax::print::pprust;
16 use syntax::symbol::{kw, sym};
17 use syntax::symbol::Symbol;
18 use syntax::util::parser;
19 use syntax_pos::{Span, BytePos};
28 "unused result of a type flagged as `#[must_use]`",
29 report_in_external_macro
35 "unused result of an expression in a statement"
38 declare_lint_pass!(UnusedResults => [UNUSED_MUST_USE, UNUSED_RESULTS]);
40 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedResults {
41 fn check_stmt(&mut self, cx: &LateContext<'_, '_>, s: &hir::Stmt) {
42 let expr = match s.kind {
43 hir::StmtKind::Semi(ref expr) => &**expr,
47 if let hir::ExprKind::Ret(..) = expr.kind {
51 let ty = cx.tables.expr_ty(&expr);
52 let type_permits_lack_of_use = check_must_use_ty(cx, ty, &expr, s.span, "", "", 1);
54 let mut fn_warned = false;
55 let mut op_warned = false;
56 let maybe_def_id = match expr.kind {
57 hir::ExprKind::Call(ref callee, _) => {
59 hir::ExprKind::Path(ref qpath) => {
60 match cx.tables.qpath_res(qpath, callee.hir_id) {
61 Res::Def(DefKind::Fn, def_id)
62 | Res::Def(DefKind::Method, def_id) => Some(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(..) => {
72 cx.tables.type_dependent_def_id(expr.hir_id)
76 if let Some(def_id) = maybe_def_id {
77 fn_warned = check_must_use_def(cx, def_id, s.span, "return value of ", "");
78 } else if type_permits_lack_of_use {
79 // We don't warn about unused unit or uninhabited types.
80 // (See https://github.com/rust-lang/rust/issues/43806 for details.)
84 let must_use_op = match expr.kind {
85 // Hardcoding operators here seemed more expedient than the
86 // refactoring that would be needed to look up the `#[must_use]`
87 // attribute which does exist on the comparison trait methods
88 hir::ExprKind::Binary(bin_op, ..) => {
95 hir::BinOpKind::Gt => {
100 hir::BinOpKind::Div |
101 hir::BinOpKind::Mul |
102 hir::BinOpKind::Rem => {
103 Some("arithmetic operation")
105 hir::BinOpKind::And | hir::BinOpKind::Or => {
106 Some("logical operation")
108 hir::BinOpKind::BitXor |
109 hir::BinOpKind::BitAnd |
110 hir::BinOpKind::BitOr |
111 hir::BinOpKind::Shl |
112 hir::BinOpKind::Shr => {
113 Some("bitwise operation")
117 hir::ExprKind::Unary(..) => Some("unary operation"),
121 if let Some(must_use_op) = must_use_op {
122 cx.span_lint(UNUSED_MUST_USE, expr.span,
123 &format!("unused {} that must be used", must_use_op));
127 if !(type_permits_lack_of_use || fn_warned || op_warned) {
128 cx.span_lint(UNUSED_RESULTS, s.span, "unused result");
131 // Returns whether an error has been emitted (and thus another does not need to be later).
132 fn check_must_use_ty<'tcx>(
133 cx: &LateContext<'_, 'tcx>,
141 if ty.is_unit() || cx.tcx.is_ty_uninhabited_from(
142 cx.tcx.hir().get_module_parent(expr.hir_id), ty)
147 let plural_suffix = pluralize!(plural_len);
150 ty::Adt(..) if ty.is_box() => {
151 let boxed_ty = ty.boxed_ty();
152 let descr_pre = &format!("{}boxed ", descr_pre);
153 check_must_use_ty(cx, boxed_ty, expr, span, descr_pre, descr_post, plural_len)
156 check_must_use_def(cx, def.did, span, descr_pre, descr_post)
158 ty::Opaque(def, _) => {
159 let mut has_emitted = false;
160 for (predicate, _) in cx.tcx.predicates_of(def).predicates {
161 if let ty::Predicate::Trait(ref poly_trait_predicate) = predicate {
162 let trait_ref = poly_trait_predicate.skip_binder().trait_ref;
163 let def_id = trait_ref.def_id;
164 let descr_pre = &format!(
165 "{}implementer{} of ",
169 if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
177 ty::Dynamic(binder, _) => {
178 let mut has_emitted = false;
179 for predicate in binder.skip_binder().iter() {
180 if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate {
181 let def_id = trait_ref.def_id;
182 let descr_post = &format!(
187 if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
195 ty::Tuple(ref tys) => {
196 let mut has_emitted = false;
197 let spans = if let hir::ExprKind::Tup(comps) = &expr.kind {
198 debug_assert_eq!(comps.len(), tys.len());
199 comps.iter().map(|e| e.span).collect()
203 for (i, ty) in tys.iter().map(|k| k.expect_ty()).enumerate() {
204 let descr_post = &format!(" in tuple element {}", i);
205 let span = *spans.get(i).unwrap_or(&span);
206 if check_must_use_ty(
220 ty::Array(ty, len) => match len.try_eval_usize(cx.tcx, cx.param_env) {
221 // If the array is definitely non-empty, we can do `#[must_use]` checking.
222 Some(n) if n != 0 => {
223 let descr_pre = &format!(
228 check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, n as usize + 1)
230 // Otherwise, we don't lint, to avoid false positives.
237 // Returns whether an error has been emitted (and thus another does not need to be later).
238 fn check_must_use_def(
239 cx: &LateContext<'_, '_>,
242 descr_pre_path: &str,
243 descr_post_path: &str,
245 for attr in cx.tcx.get_attrs(def_id).iter() {
246 if attr.check_name(sym::must_use) {
247 let msg = format!("unused {}`{}`{} that must be used",
248 descr_pre_path, cx.tcx.def_path_str(def_id), descr_post_path);
249 let mut err = cx.struct_span_lint(UNUSED_MUST_USE, span, &msg);
250 // check for #[must_use = "..."]
251 if let Some(note) = attr.value_str() {
252 err.note(¬e.as_str());
266 "path statements with no effect"
269 declare_lint_pass!(PathStatements => [PATH_STATEMENTS]);
271 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PathStatements {
272 fn check_stmt(&mut self, cx: &LateContext<'_, '_>, s: &hir::Stmt) {
273 if let hir::StmtKind::Semi(ref expr) = s.kind {
274 if let hir::ExprKind::Path(_) = expr.kind {
275 cx.span_lint(PATH_STATEMENTS, s.span, "path statement with no effect");
281 #[derive(Copy, Clone)]
282 pub struct UnusedAttributes {
283 builtin_attributes: &'static FxHashMap<Symbol, &'static BuiltinAttribute>,
286 impl UnusedAttributes {
287 pub fn new() -> Self {
289 builtin_attributes: &*BUILTIN_ATTRIBUTE_MAP,
294 impl_lint_pass!(UnusedAttributes => [UNUSED_ATTRIBUTES]);
296 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAttributes {
297 fn check_attribute(&mut self, cx: &LateContext<'_, '_>, attr: &ast::Attribute) {
298 debug!("checking attribute: {:?}", attr);
300 let attr_info = attr.ident().and_then(|ident| self.builtin_attributes.get(&ident.name));
302 if let Some(&&(name, ty, ..)) = attr_info {
304 AttributeType::Whitelisted => {
305 debug!("{:?} is Whitelisted", name);
312 if !attr::is_used(attr) {
313 debug!("emitting warning for: {:?}", attr);
314 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
315 // Is it a builtin attribute that must be used at the crate level?
316 if attr_info.map_or(false, |(_, ty, ..)| ty == &AttributeType::CrateLevel) {
317 let msg = match attr.style {
318 ast::AttrStyle::Outer => {
319 "crate-level attribute should be an inner attribute: add an exclamation \
322 ast::AttrStyle::Inner => "crate-level attribute should be in the root module",
324 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
327 debug!("Attr was used: {:?}", attr);
333 pub(super) UNUSED_PARENS,
335 "`if`, `match`, `while` and `return` do not need parentheses"
338 declare_lint_pass!(UnusedParens => [UNUSED_PARENS]);
342 fn is_expr_parens_necessary(inner: &ast::Expr, followed_by_block: bool) -> bool {
343 followed_by_block && match inner.kind {
344 ast::ExprKind::Ret(_) | ast::ExprKind::Break(..) => true,
345 _ => parser::contains_exterior_struct_lit(&inner),
349 fn check_unused_parens_expr(&self,
350 cx: &EarlyContext<'_>,
353 followed_by_block: bool,
354 left_pos: Option<BytePos>,
355 right_pos: Option<BytePos>) {
357 ast::ExprKind::Paren(ref inner) => {
358 if !Self::is_expr_parens_necessary(inner, followed_by_block) &&
359 value.attrs.is_empty() {
360 let expr_text = if let Ok(snippet) = cx.sess().source_map()
361 .span_to_snippet(value.span) {
364 pprust::expr_to_string(value)
367 left_pos.map(|s| s >= value.span.lo()).unwrap_or(false),
368 right_pos.map(|s| s <= value.span.hi()).unwrap_or(false),
370 Self::remove_outer_parens(cx, value.span, &expr_text, msg, keep_space);
373 ast::ExprKind::Let(_, ref expr) => {
374 // FIXME(#60336): Properly handle `let true = (false && true)`
375 // actually needing the parenthesis.
376 self.check_unused_parens_expr(
378 "`let` head expression",
387 fn check_unused_parens_pat(
389 cx: &EarlyContext<'_>,
394 use ast::{PatKind, BindingMode::ByValue, Mutability::Mutable};
396 if let PatKind::Paren(inner) = &value.kind {
398 // The lint visitor will visit each subpattern of `p`. We do not want to lint
399 // any range pattern no matter where it occurs in the pattern. For something like
400 // `&(a..=b)`, there is a recursive `check_pat` on `a` and `b`, but we will assume
401 // that if there are unnecessary parens they serve a purpose of readability.
402 PatKind::Range(..) => return,
403 // Avoid `p0 | .. | pn` if we should.
404 PatKind::Or(..) if avoid_or => return,
405 // Avoid `mut x` and `mut x @ p` if we should:
406 PatKind::Ident(ByValue(Mutable), ..) if avoid_mut => return,
407 // Otherwise proceed with linting.
411 let pattern_text = if let Ok(snippet) = cx.sess().source_map()
412 .span_to_snippet(value.span) {
415 pprust::pat_to_string(value)
417 Self::remove_outer_parens(cx, value.span, &pattern_text, "pattern", (false, false));
421 fn remove_outer_parens(cx: &EarlyContext<'_>,
425 keep_space: (bool, bool)) {
426 let span_msg = format!("unnecessary parentheses around {}", msg);
427 let mut err = cx.struct_span_lint(UNUSED_PARENS, span, &span_msg);
428 let mut ate_left_paren = false;
429 let mut ate_right_paren = false;
430 let parens_removed = pattern
437 ate_left_paren = true;
445 ate_right_paren = true;
454 let mut replace = if keep_space.0 {
455 let mut s = String::from(" ");
456 s.push_str(parens_removed);
459 String::from(parens_removed)
468 err.span_suggestion_short(
470 "remove these parentheses",
472 Applicability::MachineApplicable,
478 impl EarlyLintPass for UnusedParens {
479 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
480 use syntax::ast::ExprKind::*;
481 let (value, msg, followed_by_block, left_pos, right_pos) = match e.kind {
482 Let(ref pat, ..) => {
483 self.check_unused_parens_pat(cx, pat, false, false);
487 If(ref cond, ref block, ..) => {
488 let left = e.span.lo() + syntax_pos::BytePos(2);
489 let right = block.span.lo();
490 (cond, "`if` condition", true, Some(left), Some(right))
493 While(ref cond, ref block, ..) => {
494 let left = e.span.lo() + syntax_pos::BytePos(5);
495 let right = block.span.lo();
496 (cond, "`while` condition", true, Some(left), Some(right))
499 ForLoop(ref pat, ref cond, ref block, ..) => {
500 self.check_unused_parens_pat(cx, pat, false, false);
501 (cond, "`for` head expression", true, None, Some(block.span.lo()))
504 Match(ref head, _) => {
505 let left = e.span.lo() + syntax_pos::BytePos(5);
506 (head, "`match` head expression", true, Some(left), None)
509 Ret(Some(ref value)) => {
510 let left = e.span.lo() + syntax_pos::BytePos(3);
511 (value, "`return` value", false, Some(left), None)
514 Assign(_, ref value) => (value, "assigned value", false, None, None),
515 AssignOp(.., ref value) => (value, "assigned value", false, None, None),
516 // either function/method call, or something this lint doesn't care about
517 ref call_or_other => {
518 let (args_to_check, call_kind) = match *call_or_other {
519 Call(_, ref args) => (&args[..], "function"),
520 // first "argument" is self (which sometimes needs parens)
521 MethodCall(_, ref args) => (&args[1..], "method"),
522 // actual catch-all arm
527 // Don't lint if this is a nested macro expansion: otherwise, the lint could
528 // trigger in situations that macro authors shouldn't have to care about, e.g.,
529 // when a parenthesized token tree matched in one macro expansion is matched as
530 // an expression in another and used as a fn/method argument (Issue #47775)
531 if e.span.ctxt().outer_expn_data().call_site.from_expansion() {
534 let msg = format!("{} argument", call_kind);
535 for arg in args_to_check {
536 self.check_unused_parens_expr(cx, arg, &msg, false, None, None);
541 self.check_unused_parens_expr(cx, &value, msg, followed_by_block, left_pos, right_pos);
544 fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
545 use ast::{PatKind::*, Mutability};
547 // Do not lint on `(..)` as that will result in the other arms being useless.
549 // The other cases do not contain sub-patterns.
550 | Wild | Rest | Lit(..) | Mac(..) | Range(..) | Ident(.., None) | Path(..) => return,
551 // These are list-like patterns; parens can always be removed.
552 TupleStruct(_, ps) | Tuple(ps) | Slice(ps) | Or(ps) => for p in ps {
553 self.check_unused_parens_pat(cx, p, false, false);
555 Struct(_, fps, _) => for f in fps {
556 self.check_unused_parens_pat(cx, &f.pat, false, false);
558 // Avoid linting on `i @ (p0 | .. | pn)` and `box (p0 | .. | pn)`, #64106.
559 Ident(.., Some(p)) | Box(p) => self.check_unused_parens_pat(cx, p, true, false),
560 // Avoid linting on `&(mut x)` as `&mut x` has a different meaning, #55342.
561 // Also avoid linting on `& mut? (p0 | .. | pn)`, #64106.
562 Ref(p, m) => self.check_unused_parens_pat(cx, p, true, *m == Mutability::Immutable),
566 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
567 if let ast::StmtKind::Local(ref local) = s.kind {
568 self.check_unused_parens_pat(cx, &local.pat, false, false);
570 if let Some(ref value) = local.init {
571 self.check_unused_parens_expr(cx, &value, "assigned 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 => {}
590 let pattern_text = if let Ok(snippet) = cx.sess().source_map()
591 .span_to_snippet(ty.span) {
594 pprust::ty_to_string(ty)
597 Self::remove_outer_parens(cx, ty.span, &pattern_text, "type", (false, false));
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::Immutable =>
671 "unnecessary allocation, use `&` instead",
672 adjustment::AutoBorrowMutability::Mutable { .. }=>
673 "unnecessary allocation, use `&mut` instead"
675 cx.span_lint(UNUSED_ALLOCATION, e.span, msg);