2 use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
3 use rustc::ty::adjustment;
4 use rustc::ty::{self, Ty};
6 use rustc_ast::ast::{ExprKind, StmtKind};
8 use rustc_ast::util::parser;
9 use rustc_ast_pretty::pprust;
10 use rustc_data_structures::fx::FxHashMap;
11 use rustc_errors::{pluralize, Applicability};
12 use rustc_feature::{AttributeType, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP};
14 use rustc_hir::def::{DefKind, Res};
15 use rustc_hir::def_id::DefId;
16 use rustc_session::lint::builtin::UNUSED_ATTRIBUTES;
17 use rustc_span::symbol::Symbol;
18 use rustc_span::symbol::{kw, sym};
19 use rustc_span::{BytePos, Span};
26 "unused result of a type flagged as `#[must_use]`",
27 report_in_external_macro
33 "unused result of an expression in a statement"
36 declare_lint_pass!(UnusedResults => [UNUSED_MUST_USE, UNUSED_RESULTS]);
38 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedResults {
39 fn check_stmt(&mut self, cx: &LateContext<'_, '_>, s: &hir::Stmt<'_>) {
40 let expr = match s.kind {
41 hir::StmtKind::Semi(ref expr) => &**expr,
45 if let hir::ExprKind::Ret(..) = expr.kind {
49 let ty = cx.tables.expr_ty(&expr);
50 let type_permits_lack_of_use = check_must_use_ty(cx, ty, &expr, s.span, "", "", 1);
52 let mut fn_warned = false;
53 let mut op_warned = false;
54 let maybe_def_id = match expr.kind {
55 hir::ExprKind::Call(ref callee, _) => {
57 hir::ExprKind::Path(ref qpath) => {
58 match cx.tables.qpath_res(qpath, callee.hir_id) {
59 Res::Def(DefKind::Fn, def_id) | Res::Def(DefKind::AssocFn, def_id) => {
62 // `Res::Local` if it was a closure, for which we
63 // do not currently support must-use linting
70 hir::ExprKind::MethodCall(..) => cx.tables.type_dependent_def_id(expr.hir_id),
73 if let Some(def_id) = maybe_def_id {
74 fn_warned = check_must_use_def(cx, def_id, s.span, "return value of ", "");
75 } else if type_permits_lack_of_use {
76 // We don't warn about unused unit or uninhabited types.
77 // (See https://github.com/rust-lang/rust/issues/43806 for details.)
81 let must_use_op = match expr.kind {
82 // Hardcoding operators here seemed more expedient than the
83 // refactoring that would be needed to look up the `#[must_use]`
84 // attribute which does exist on the comparison trait methods
85 hir::ExprKind::Binary(bin_op, ..) => match bin_op.node {
91 | hir::BinOpKind::Gt => Some("comparison"),
96 | hir::BinOpKind::Rem => Some("arithmetic operation"),
97 hir::BinOpKind::And | hir::BinOpKind::Or => Some("logical operation"),
98 hir::BinOpKind::BitXor
99 | hir::BinOpKind::BitAnd
100 | hir::BinOpKind::BitOr
101 | hir::BinOpKind::Shl
102 | hir::BinOpKind::Shr => Some("bitwise operation"),
104 hir::ExprKind::Unary(..) => Some("unary operation"),
108 if let Some(must_use_op) = must_use_op {
109 cx.struct_span_lint(UNUSED_MUST_USE, expr.span, |lint| {
110 lint.build(&format!("unused {} that must be used", must_use_op)).emit()
115 if !(type_permits_lack_of_use || fn_warned || op_warned) {
116 cx.struct_span_lint(UNUSED_RESULTS, s.span, |lint| lint.build("unused result").emit());
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(
131 cx.tcx.parent_module(expr.hir_id).to_def_id(),
139 let plural_suffix = pluralize!(plural_len);
142 ty::Adt(..) if ty.is_box() => {
143 let boxed_ty = ty.boxed_ty();
144 let descr_pre = &format!("{}boxed ", descr_pre);
145 check_must_use_ty(cx, boxed_ty, expr, span, descr_pre, descr_post, plural_len)
147 ty::Adt(def, _) => check_must_use_def(cx, def.did, span, descr_pre, descr_post),
148 ty::Opaque(def, _) => {
149 let mut has_emitted = false;
150 for (predicate, _) in cx.tcx.predicates_of(def).predicates {
151 if let ty::Predicate::Trait(ref poly_trait_predicate, _) = predicate {
152 let trait_ref = poly_trait_predicate.skip_binder().trait_ref;
153 let def_id = trait_ref.def_id;
155 &format!("{}implementer{} of ", descr_pre, plural_suffix,);
156 if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
164 ty::Dynamic(binder, _) => {
165 let mut has_emitted = false;
166 for predicate in binder.skip_binder().iter() {
167 if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate {
168 let def_id = trait_ref.def_id;
170 &format!(" trait object{}{}", plural_suffix, descr_post,);
171 if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
179 ty::Tuple(ref tys) => {
180 let mut has_emitted = false;
181 let spans = if let hir::ExprKind::Tup(comps) = &expr.kind {
182 debug_assert_eq!(comps.len(), tys.len());
183 comps.iter().map(|e| e.span).collect()
187 for (i, ty) in tys.iter().map(|k| k.expect_ty()).enumerate() {
188 let descr_post = &format!(" in tuple element {}", i);
189 let span = *spans.get(i).unwrap_or(&span);
190 if check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, plural_len)
197 ty::Array(ty, len) => match len.try_eval_usize(cx.tcx, cx.param_env) {
198 // If the array is definitely non-empty, we can do `#[must_use]` checking.
199 Some(n) if n != 0 => {
200 let descr_pre = &format!("{}array{} of ", descr_pre, plural_suffix,);
201 check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, n as usize + 1)
203 // Otherwise, we don't lint, to avoid false positives.
210 // Returns whether an error has been emitted (and thus another does not need to be later).
211 // FIXME: Args desc_{pre,post}_path could be made lazy by taking Fn() -> &str, but this
212 // would make calling it a big awkward. Could also take String (so args are moved), but
213 // this would still require a copy into the format string, which would only be executed
215 fn check_must_use_def(
216 cx: &LateContext<'_, '_>,
219 descr_pre_path: &str,
220 descr_post_path: &str,
222 for attr in cx.tcx.get_attrs(def_id).iter() {
223 if attr.check_name(sym::must_use) {
224 cx.struct_span_lint(UNUSED_MUST_USE, span, |lint| {
226 "unused {}`{}`{} that must be used",
228 cx.tcx.def_path_str(def_id),
231 let mut err = lint.build(&msg);
232 // check for #[must_use = "..."]
233 if let Some(note) = attr.value_str() {
234 err.note(¬e.as_str());
249 "path statements with no effect"
252 declare_lint_pass!(PathStatements => [PATH_STATEMENTS]);
254 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PathStatements {
255 fn check_stmt(&mut self, cx: &LateContext<'_, '_>, s: &hir::Stmt<'_>) {
256 if let hir::StmtKind::Semi(ref expr) = s.kind {
257 if let hir::ExprKind::Path(_) = expr.kind {
258 cx.struct_span_lint(PATH_STATEMENTS, s.span, |lint| {
259 lint.build("path statement with no effect").emit()
266 #[derive(Copy, Clone)]
267 pub struct UnusedAttributes {
268 builtin_attributes: &'static FxHashMap<Symbol, &'static BuiltinAttribute>,
271 impl UnusedAttributes {
272 pub fn new() -> Self {
273 UnusedAttributes { builtin_attributes: &*BUILTIN_ATTRIBUTE_MAP }
277 impl_lint_pass!(UnusedAttributes => [UNUSED_ATTRIBUTES]);
279 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAttributes {
280 fn check_attribute(&mut self, cx: &LateContext<'_, '_>, attr: &ast::Attribute) {
281 debug!("checking attribute: {:?}", attr);
283 if attr.is_doc_comment() {
287 let attr_info = attr.ident().and_then(|ident| self.builtin_attributes.get(&ident.name));
289 if let Some(&&(name, ty, ..)) = attr_info {
291 AttributeType::Whitelisted => {
292 debug!("{:?} is Whitelisted", name);
299 if !attr::is_used(attr) {
300 debug!("emitting warning for: {:?}", attr);
301 cx.struct_span_lint(UNUSED_ATTRIBUTES, attr.span, |lint| {
302 lint.build("unused attribute").emit()
304 // Is it a builtin attribute that must be used at the crate level?
305 if attr_info.map_or(false, |(_, ty, ..)| ty == &AttributeType::CrateLevel) {
306 cx.struct_span_lint(UNUSED_ATTRIBUTES, attr.span, |lint| {
307 let msg = match attr.style {
308 ast::AttrStyle::Outer => {
309 "crate-level attribute should be an inner attribute: add an exclamation \
312 ast::AttrStyle::Inner => "crate-level attribute should be in the root module",
314 lint.build(msg).emit()
318 debug!("Attr was used: {:?}", attr);
323 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
324 enum UnusedDelimsCtx {
339 impl From<UnusedDelimsCtx> for &'static str {
340 fn from(ctx: UnusedDelimsCtx) -> &'static str {
342 UnusedDelimsCtx::FunctionArg => "function argument",
343 UnusedDelimsCtx::MethodArg => "method argument",
344 UnusedDelimsCtx::AssignedValue => "assigned value",
345 UnusedDelimsCtx::IfCond => "`if` condition",
346 UnusedDelimsCtx::WhileCond => "`while` condition",
347 UnusedDelimsCtx::ForIterExpr => "`for` iterator expression",
348 UnusedDelimsCtx::MatchScrutineeExpr => "`match` scrutinee expression",
349 UnusedDelimsCtx::ReturnValue => "`return` value",
350 UnusedDelimsCtx::BlockRetValue => "block return value",
351 UnusedDelimsCtx::LetScrutineeExpr => "`let` scrutinee expression",
352 UnusedDelimsCtx::ArrayLenExpr | UnusedDelimsCtx::AnonConst => "const expression",
357 /// Used by both `UnusedParens` and `UnusedBraces` to prevent code duplication.
358 trait UnusedDelimLint {
359 const DELIM_STR: &'static str;
361 // this cannot be a constant is it refers to a static.
362 fn lint(&self) -> &'static Lint;
364 fn check_unused_delims_expr(
366 cx: &EarlyContext<'_>,
368 ctx: UnusedDelimsCtx,
369 followed_by_block: bool,
370 left_pos: Option<BytePos>,
371 right_pos: Option<BytePos>,
374 fn is_expr_delims_necessary(inner: &ast::Expr, followed_by_block: bool) -> bool {
376 && match inner.kind {
377 ast::ExprKind::Ret(_) | ast::ExprKind::Break(..) => true,
378 _ => parser::contains_exterior_struct_lit(&inner),
382 fn emit_unused_delims_expr(
384 cx: &EarlyContext<'_>,
386 ctx: UnusedDelimsCtx,
387 left_pos: Option<BytePos>,
388 right_pos: Option<BytePos>,
390 let expr_text = if let Ok(snippet) = cx.sess().source_map().span_to_snippet(value.span) {
393 pprust::expr_to_string(value)
396 left_pos.map(|s| s >= value.span.lo()).unwrap_or(false),
397 right_pos.map(|s| s <= value.span.hi()).unwrap_or(false),
399 self.emit_unused_delims(cx, value.span, &expr_text, ctx.into(), keep_space);
402 fn emit_unused_delims(
404 cx: &EarlyContext<'_>,
408 keep_space: (bool, bool),
410 cx.struct_span_lint(self.lint(), span, |lint| {
411 let span_msg = format!("unnecessary {} around {}", Self::DELIM_STR, msg);
412 let mut err = lint.build(&span_msg);
413 let mut ate_left_paren = false;
414 let mut ate_right_paren = false;
415 let parens_removed = pattern.trim_matches(|c| match c {
420 ate_left_paren = true;
428 ate_right_paren = true;
436 let mut replace = if keep_space.0 {
437 let mut s = String::from(" ");
438 s.push_str(parens_removed);
441 String::from(parens_removed)
450 let suggestion = format!("remove these {}", Self::DELIM_STR);
452 err.span_suggestion_short(span, &suggestion, replace, Applicability::MachineApplicable);
457 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
458 use rustc_ast::ast::ExprKind::*;
459 let (value, ctx, followed_by_block, left_pos, right_pos) = match e.kind {
460 If(ref cond, ref block, ..) => {
461 let left = e.span.lo() + rustc_span::BytePos(2);
462 let right = block.span.lo();
463 (cond, UnusedDelimsCtx::IfCond, true, Some(left), Some(right))
466 While(ref cond, ref block, ..) => {
467 let left = e.span.lo() + rustc_span::BytePos(5);
468 let right = block.span.lo();
469 (cond, UnusedDelimsCtx::WhileCond, true, Some(left), Some(right))
472 ForLoop(_, ref cond, ref block, ..) => {
473 (cond, UnusedDelimsCtx::ForIterExpr, true, None, Some(block.span.lo()))
476 Match(ref head, _) => {
477 let left = e.span.lo() + rustc_span::BytePos(5);
478 (head, UnusedDelimsCtx::MatchScrutineeExpr, true, Some(left), None)
481 Ret(Some(ref value)) => {
482 let left = e.span.lo() + rustc_span::BytePos(3);
483 (value, UnusedDelimsCtx::ReturnValue, false, Some(left), None)
486 Assign(_, ref value, _) | AssignOp(.., ref value) => {
487 (value, UnusedDelimsCtx::AssignedValue, false, None, None)
489 // either function/method call, or something this lint doesn't care about
490 ref call_or_other => {
491 let (args_to_check, ctx) = match *call_or_other {
492 Call(_, ref args) => (&args[..], UnusedDelimsCtx::FunctionArg),
493 // first "argument" is self (which sometimes needs delims)
494 MethodCall(_, ref args) => (&args[1..], UnusedDelimsCtx::MethodArg),
495 // actual catch-all arm
500 // Don't lint if this is a nested macro expansion: otherwise, the lint could
501 // trigger in situations that macro authors shouldn't have to care about, e.g.,
502 // when a parenthesized token tree matched in one macro expansion is matched as
503 // an expression in another and used as a fn/method argument (Issue #47775)
504 if e.span.ctxt().outer_expn_data().call_site.from_expansion() {
507 for arg in args_to_check {
508 self.check_unused_delims_expr(cx, arg, ctx, false, None, None);
513 self.check_unused_delims_expr(cx, &value, ctx, followed_by_block, left_pos, right_pos);
516 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
518 StmtKind::Local(ref local) => {
519 if let Some(ref value) = local.init {
520 self.check_unused_delims_expr(
523 UnusedDelimsCtx::AssignedValue,
530 StmtKind::Expr(ref expr) => {
531 self.check_unused_delims_expr(
534 UnusedDelimsCtx::BlockRetValue,
544 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
545 use ast::ItemKind::*;
547 if let Const(.., Some(expr)) | Static(.., Some(expr)) = &item.kind {
548 self.check_unused_delims_expr(
551 UnusedDelimsCtx::AssignedValue,
561 pub(super) UNUSED_PARENS,
563 "`if`, `match`, `while` and `return` do not need parentheses"
566 declare_lint_pass!(UnusedParens => [UNUSED_PARENS]);
568 impl UnusedDelimLint for UnusedParens {
569 const DELIM_STR: &'static str = "parentheses";
571 fn lint(&self) -> &'static Lint {
575 fn check_unused_delims_expr(
577 cx: &EarlyContext<'_>,
579 ctx: UnusedDelimsCtx,
580 followed_by_block: bool,
581 left_pos: Option<BytePos>,
582 right_pos: Option<BytePos>,
585 ast::ExprKind::Paren(ref inner) => {
586 if !Self::is_expr_delims_necessary(inner, followed_by_block)
587 && value.attrs.is_empty()
588 && !value.span.from_expansion()
590 self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
593 ast::ExprKind::Let(_, ref expr) => {
594 // FIXME(#60336): Properly handle `let true = (false && true)`
595 // actually needing the parenthesis.
596 self.check_unused_delims_expr(
599 UnusedDelimsCtx::LetScrutineeExpr,
611 fn check_unused_parens_pat(
613 cx: &EarlyContext<'_>,
618 use ast::{BindingMode, Mutability, PatKind};
620 if let PatKind::Paren(inner) = &value.kind {
622 // The lint visitor will visit each subpattern of `p`. We do not want to lint
623 // any range pattern no matter where it occurs in the pattern. For something like
624 // `&(a..=b)`, there is a recursive `check_pat` on `a` and `b`, but we will assume
625 // that if there are unnecessary parens they serve a purpose of readability.
626 PatKind::Range(..) => return,
627 // Avoid `p0 | .. | pn` if we should.
628 PatKind::Or(..) if avoid_or => return,
629 // Avoid `mut x` and `mut x @ p` if we should:
630 PatKind::Ident(BindingMode::ByValue(Mutability::Mut), ..) if avoid_mut => return,
631 // Otherwise proceed with linting.
636 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(value.span) {
639 pprust::pat_to_string(value)
641 self.emit_unused_delims(cx, value.span, &pattern_text, "pattern", (false, false));
646 impl EarlyLintPass for UnusedParens {
647 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
648 if let ExprKind::Let(ref pat, ..) | ExprKind::ForLoop(ref pat, ..) = e.kind {
649 self.check_unused_parens_pat(cx, pat, false, false);
652 <Self as UnusedDelimLint>::check_expr(self, cx, e)
655 fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
656 use ast::{Mutability, PatKind::*};
658 // Do not lint on `(..)` as that will result in the other arms being useless.
660 // The other cases do not contain sub-patterns.
661 | Wild | Rest | Lit(..) | MacCall(..) | Range(..) | Ident(.., None) | Path(..) => {},
662 // These are list-like patterns; parens can always be removed.
663 TupleStruct(_, ps) | Tuple(ps) | Slice(ps) | Or(ps) => for p in ps {
664 self.check_unused_parens_pat(cx, p, false, false);
666 Struct(_, fps, _) => for f in fps {
667 self.check_unused_parens_pat(cx, &f.pat, false, false);
669 // Avoid linting on `i @ (p0 | .. | pn)` and `box (p0 | .. | pn)`, #64106.
670 Ident(.., Some(p)) | Box(p) => self.check_unused_parens_pat(cx, p, true, false),
671 // Avoid linting on `&(mut x)` as `&mut x` has a different meaning, #55342.
672 // Also avoid linting on `& mut? (p0 | .. | pn)`, #64106.
673 Ref(p, m) => self.check_unused_parens_pat(cx, p, true, *m == Mutability::Not),
677 fn check_anon_const(&mut self, cx: &EarlyContext<'_>, c: &ast::AnonConst) {
678 self.check_unused_delims_expr(cx, &c.value, UnusedDelimsCtx::AnonConst, false, None, None);
681 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
682 if let StmtKind::Local(ref local) = s.kind {
683 self.check_unused_parens_pat(cx, &local.pat, false, false);
686 <Self as UnusedDelimLint>::check_stmt(self, cx, s)
689 fn check_param(&mut self, cx: &EarlyContext<'_>, param: &ast::Param) {
690 self.check_unused_parens_pat(cx, ¶m.pat, true, false);
693 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
694 self.check_unused_parens_pat(cx, &arm.pat, false, false);
697 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
698 if let &ast::TyKind::Paren(ref r) = &ty.kind {
700 &ast::TyKind::TraitObject(..) => {}
701 &ast::TyKind::ImplTrait(_, ref bounds) if bounds.len() > 1 => {}
702 &ast::TyKind::Array(_, ref len) => {
703 self.check_unused_delims_expr(
706 UnusedDelimsCtx::ArrayLenExpr,
714 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(ty.span) {
717 pprust::ty_to_string(ty)
720 self.emit_unused_delims(cx, ty.span, &pattern_text, "type", (false, false));
726 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
727 <Self as UnusedDelimLint>::check_item(self, cx, item)
732 pub(super) UNUSED_BRACES,
734 "unnecessary braces around an expression"
737 declare_lint_pass!(UnusedBraces => [UNUSED_BRACES]);
739 impl UnusedDelimLint for UnusedBraces {
740 const DELIM_STR: &'static str = "braces";
742 fn lint(&self) -> &'static Lint {
746 fn check_unused_delims_expr(
748 cx: &EarlyContext<'_>,
750 ctx: UnusedDelimsCtx,
751 followed_by_block: bool,
752 left_pos: Option<BytePos>,
753 right_pos: Option<BytePos>,
756 ast::ExprKind::Block(ref inner, None)
757 if inner.rules == ast::BlockCheckMode::Default =>
759 // emit a warning under the following conditions:
761 // - the block does not have a label
762 // - the block is not `unsafe`
763 // - the block contains exactly one expression (do not lint `{ expr; }`)
764 // - `followed_by_block` is true and the internal expr may contain a `{`
765 // - the block is not multiline (do not lint multiline match arms)
769 // somewhat_long_expression
774 // - the block has no attribute and was not created inside a macro
775 // - if the block is an `anon_const`, the inner expr must be a literal
776 // (do not lint `struct A<const N: usize>; let _: A<{ 2 + 3 }>;`)
778 // FIXME(const_generics): handle paths when #67075 is fixed.
779 if let [stmt] = inner.stmts.as_slice() {
780 if let ast::StmtKind::Expr(ref expr) = stmt.kind {
781 if !Self::is_expr_delims_necessary(expr, followed_by_block)
782 && (ctx != UnusedDelimsCtx::AnonConst
783 || matches!(expr.kind, ast::ExprKind::Lit(_)))
784 // array length expressions are checked during `check_anon_const` and `check_ty`,
785 // once as `ArrayLenExpr` and once as `AnonConst`.
787 // As we do not want to lint this twice, we do not emit an error for
788 // `ArrayLenExpr` if `AnonConst` would do the same.
789 && (ctx != UnusedDelimsCtx::ArrayLenExpr
790 || !matches!(expr.kind, ast::ExprKind::Lit(_)))
791 && !cx.sess().source_map().is_multiline(value.span)
792 && value.attrs.is_empty()
793 && !value.span.from_expansion()
795 self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
800 ast::ExprKind::Let(_, ref expr) => {
801 // FIXME(#60336): Properly handle `let true = (false && true)`
802 // actually needing the parenthesis.
803 self.check_unused_delims_expr(
806 UnusedDelimsCtx::LetScrutineeExpr,
817 impl EarlyLintPass for UnusedBraces {
818 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
819 <Self as UnusedDelimLint>::check_expr(self, cx, e)
822 fn check_anon_const(&mut self, cx: &EarlyContext<'_>, c: &ast::AnonConst) {
823 self.check_unused_delims_expr(cx, &c.value, UnusedDelimsCtx::AnonConst, false, None, None);
826 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
827 <Self as UnusedDelimLint>::check_stmt(self, cx, s)
830 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
831 if let &ast::TyKind::Paren(ref r) = &ty.kind {
832 if let ast::TyKind::Array(_, ref len) = r.kind {
833 self.check_unused_delims_expr(
836 UnusedDelimsCtx::ArrayLenExpr,
845 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
846 <Self as UnusedDelimLint>::check_item(self, cx, item)
851 UNUSED_IMPORT_BRACES,
853 "unnecessary braces around an imported item"
856 declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]);
858 impl UnusedImportBraces {
859 fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
860 if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
861 // Recursively check nested UseTrees
862 for &(ref tree, _) in items {
863 self.check_use_tree(cx, tree, item);
866 // Trigger the lint only if there is one nested item
867 if items.len() != 1 {
871 // Trigger the lint if the nested item is a non-self single item
872 let node_name = match items[0].0.kind {
873 ast::UseTreeKind::Simple(rename, ..) => {
874 let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
875 if orig_ident.name == kw::SelfLower {
878 rename.unwrap_or(orig_ident).name
880 ast::UseTreeKind::Glob => Symbol::intern("*"),
881 ast::UseTreeKind::Nested(_) => return,
884 cx.struct_span_lint(UNUSED_IMPORT_BRACES, item.span, |lint| {
885 lint.build(&format!("braces around {} is unnecessary", node_name)).emit()
891 impl EarlyLintPass for UnusedImportBraces {
892 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
893 if let ast::ItemKind::Use(ref use_tree) = item.kind {
894 self.check_use_tree(cx, use_tree, item);
900 pub(super) UNUSED_ALLOCATION,
902 "detects unnecessary allocations that can be eliminated"
905 declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]);
907 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAllocation {
908 fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr<'_>) {
910 hir::ExprKind::Box(_) => {}
914 for adj in cx.tables.expr_adjustments(e) {
915 if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
916 cx.struct_span_lint(UNUSED_ALLOCATION, e.span, |lint| {
918 adjustment::AutoBorrowMutability::Not => {
919 "unnecessary allocation, use `&` instead"
921 adjustment::AutoBorrowMutability::Mut { .. } => {
922 "unnecessary allocation, use `&mut` instead"
925 lint.build(msg).emit()