2 use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
4 use rustc_ast::util::{classify, parser};
5 use rustc_ast::{ExprKind, StmtKind};
6 use rustc_errors::{fluent, pluralize, Applicability, MultiSpan};
8 use rustc_hir::def::{DefKind, Res};
9 use rustc_hir::def_id::DefId;
10 use rustc_infer::traits::util::elaborate_predicates_with_span;
11 use rustc_middle::ty::adjustment;
12 use rustc_middle::ty::{self, Ty};
13 use rustc_span::symbol::Symbol;
14 use rustc_span::symbol::{kw, sym};
15 use rustc_span::{BytePos, Span};
18 /// The `unused_must_use` lint detects unused result of a type flagged as
24 /// fn returns_result() -> Result<(), ()> {
37 /// The `#[must_use]` attribute is an indicator that it is a mistake to
38 /// ignore the value. See [the reference] for more details.
40 /// [the reference]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
43 "unused result of a type flagged as `#[must_use]`",
44 report_in_external_macro
48 /// The `unused_results` lint checks for the unused result of an
49 /// expression in a statement.
53 /// ```rust,compile_fail
54 /// #![deny(unused_results)]
55 /// fn foo<T>() -> T { panic!() }
66 /// Ignoring the return value of a function may indicate a mistake. In
67 /// cases were it is almost certain that the result should be used, it is
68 /// recommended to annotate the function with the [`must_use` attribute].
69 /// Failure to use such a return value will trigger the [`unused_must_use`
70 /// lint] which is warn-by-default. The `unused_results` lint is
71 /// essentially the same, but triggers for *all* return values.
73 /// This lint is "allow" by default because it can be noisy, and may not be
74 /// an actual problem. For example, calling the `remove` method of a `Vec`
75 /// or `HashMap` returns the previous value, which you may not care about.
76 /// Using this lint would require explicitly ignoring or discarding such
79 /// [`must_use` attribute]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
80 /// [`unused_must_use` lint]: warn-by-default.html#unused-must-use
83 "unused result of an expression in a statement"
86 declare_lint_pass!(UnusedResults => [UNUSED_MUST_USE, UNUSED_RESULTS]);
88 impl<'tcx> LateLintPass<'tcx> for UnusedResults {
89 fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
90 let expr = match s.kind {
91 hir::StmtKind::Semi(ref expr) => &**expr,
95 if let hir::ExprKind::Ret(..) = expr.kind {
99 let ty = cx.typeck_results().expr_ty(&expr);
100 let type_permits_lack_of_use = check_must_use_ty(cx, ty, &expr, s.span, "", "", 1);
102 let mut fn_warned = false;
103 let mut op_warned = false;
104 let maybe_def_id = match expr.kind {
105 hir::ExprKind::Call(ref callee, _) => {
107 hir::ExprKind::Path(ref qpath) => {
108 match cx.qpath_res(qpath, callee.hir_id) {
109 Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) => Some(def_id),
110 // `Res::Local` if it was a closure, for which we
111 // do not currently support must-use linting
118 hir::ExprKind::MethodCall(..) => cx.typeck_results().type_dependent_def_id(expr.hir_id),
121 if let Some(def_id) = maybe_def_id {
122 fn_warned = check_must_use_def(cx, def_id, s.span, "return value of ", "");
123 } else if type_permits_lack_of_use {
124 // We don't warn about unused unit or uninhabited types.
125 // (See https://github.com/rust-lang/rust/issues/43806 for details.)
129 let must_use_op = match expr.kind {
130 // Hardcoding operators here seemed more expedient than the
131 // refactoring that would be needed to look up the `#[must_use]`
132 // attribute which does exist on the comparison trait methods
133 hir::ExprKind::Binary(bin_op, ..) => match bin_op.node {
139 | hir::BinOpKind::Gt => Some("comparison"),
141 | hir::BinOpKind::Sub
142 | hir::BinOpKind::Div
143 | hir::BinOpKind::Mul
144 | hir::BinOpKind::Rem => Some("arithmetic operation"),
145 hir::BinOpKind::And | hir::BinOpKind::Or => Some("logical operation"),
146 hir::BinOpKind::BitXor
147 | hir::BinOpKind::BitAnd
148 | hir::BinOpKind::BitOr
149 | hir::BinOpKind::Shl
150 | hir::BinOpKind::Shr => Some("bitwise operation"),
152 hir::ExprKind::AddrOf(..) => Some("borrow"),
153 hir::ExprKind::Unary(..) => Some("unary operation"),
157 if let Some(must_use_op) = must_use_op {
158 cx.struct_span_lint(UNUSED_MUST_USE, expr.span, fluent::lint_unused_op, |lint| {
159 lint.set_arg("op", must_use_op)
160 .span_label(expr.span, fluent::label)
161 .span_suggestion_verbose(
162 expr.span.shrink_to_lo(),
165 Applicability::MachineApplicable,
171 if !(type_permits_lack_of_use || fn_warned || op_warned) {
172 cx.struct_span_lint(UNUSED_RESULTS, s.span, fluent::lint_unused_result, |lint| {
173 lint.set_arg("ty", ty)
177 // Returns whether an error has been emitted (and thus another does not need to be later).
178 fn check_must_use_ty<'tcx>(
179 cx: &LateContext<'tcx>,
181 expr: &hir::Expr<'_>,
188 || cx.tcx.is_ty_uninhabited_from(
189 cx.tcx.parent_module(expr.hir_id).to_def_id(),
197 let plural_suffix = pluralize!(plural_len);
200 ty::Adt(..) if ty.is_box() => {
201 let boxed_ty = ty.boxed_ty();
202 let descr_pre = &format!("{}boxed ", descr_pre);
203 check_must_use_ty(cx, boxed_ty, expr, span, descr_pre, descr_post, plural_len)
205 ty::Adt(def, _) => check_must_use_def(cx, def.did(), span, descr_pre, descr_post),
206 ty::Opaque(def, _) => {
207 let mut has_emitted = false;
208 for obligation in elaborate_predicates_with_span(
210 cx.tcx.explicit_item_bounds(def).iter().cloned(),
212 // We only look at the `DefId`, so it is safe to skip the binder here.
213 if let ty::PredicateKind::Trait(ref poly_trait_predicate) =
214 obligation.predicate.kind().skip_binder()
216 let def_id = poly_trait_predicate.trait_ref.def_id;
218 &format!("{}implementer{} of ", descr_pre, plural_suffix,);
219 if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
227 ty::Dynamic(binder, _, _) => {
228 let mut has_emitted = false;
229 for predicate in binder.iter() {
230 if let ty::ExistentialPredicate::Trait(ref trait_ref) =
231 predicate.skip_binder()
233 let def_id = trait_ref.def_id;
235 &format!(" trait object{}{}", plural_suffix, descr_post,);
236 if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
244 ty::Tuple(ref tys) => {
245 let mut has_emitted = false;
246 let comps = if let hir::ExprKind::Tup(comps) = expr.kind {
247 debug_assert_eq!(comps.len(), tys.len());
252 for (i, ty) in tys.iter().enumerate() {
253 let descr_post = &format!(" in tuple element {}", i);
254 let e = comps.get(i).unwrap_or(expr);
256 if check_must_use_ty(cx, ty, e, span, descr_pre, descr_post, plural_len) {
262 ty::Array(ty, len) => match len.try_eval_usize(cx.tcx, cx.param_env) {
263 // If the array is empty we don't lint, to avoid false positives
264 Some(0) | None => false,
265 // If the array is definitely non-empty, we can do `#[must_use]` checking.
267 let descr_pre = &format!("{}array{} of ", descr_pre, plural_suffix,);
268 check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, n as usize + 1)
275 fluent::lint_unused_closure,
277 // FIXME(davidtwco): this isn't properly translatable because of the
279 lint.set_arg("count", plural_len)
280 .set_arg("pre", descr_pre)
281 .set_arg("post", descr_post)
287 ty::Generator(..) => {
291 fluent::lint_unused_generator,
293 // FIXME(davidtwco): this isn't properly translatable because of the
295 lint.set_arg("count", plural_len)
296 .set_arg("pre", descr_pre)
297 .set_arg("post", descr_post)
307 // Returns whether an error has been emitted (and thus another does not need to be later).
308 // FIXME: Args desc_{pre,post}_path could be made lazy by taking Fn() -> &str, but this
309 // would make calling it a big awkward. Could also take String (so args are moved), but
310 // this would still require a copy into the format string, which would only be executed
312 fn check_must_use_def(
313 cx: &LateContext<'_>,
316 descr_pre_path: &str,
317 descr_post_path: &str,
319 if let Some(attr) = cx.tcx.get_attr(def_id, sym::must_use) {
320 cx.struct_span_lint(UNUSED_MUST_USE, span, fluent::lint_unused_def, |lint| {
321 // FIXME(davidtwco): this isn't properly translatable because of the pre/post
323 lint.set_arg("pre", descr_pre_path);
324 lint.set_arg("post", descr_post_path);
325 lint.set_arg("def", cx.tcx.def_path_str(def_id));
326 // check for #[must_use = "..."]
327 if let Some(note) = attr.value_str() {
328 lint.note(note.as_str());
341 /// The `path_statements` lint detects path statements with no effect.
355 /// It is usually a mistake to have a statement that has no effect.
358 "path statements with no effect"
361 declare_lint_pass!(PathStatements => [PATH_STATEMENTS]);
363 impl<'tcx> LateLintPass<'tcx> for PathStatements {
364 fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
365 if let hir::StmtKind::Semi(expr) = s.kind {
366 if let hir::ExprKind::Path(_) = expr.kind {
367 let ty = cx.typeck_results().expr_ty(expr);
368 if ty.needs_drop(cx.tcx, cx.param_env) {
372 fluent::lint_path_statement_drop,
374 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(expr.span) {
375 lint.span_suggestion(
378 format!("drop({});", snippet),
379 Applicability::MachineApplicable,
382 lint.span_help(s.span, fluent::suggestion);
391 fluent::lint_path_statement_no_effect,
400 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
401 enum UnusedDelimsCtx {
405 AssignedValueLetElse,
418 impl From<UnusedDelimsCtx> for &'static str {
419 fn from(ctx: UnusedDelimsCtx) -> &'static str {
421 UnusedDelimsCtx::FunctionArg => "function argument",
422 UnusedDelimsCtx::MethodArg => "method argument",
423 UnusedDelimsCtx::AssignedValue | UnusedDelimsCtx::AssignedValueLetElse => {
426 UnusedDelimsCtx::IfCond => "`if` condition",
427 UnusedDelimsCtx::WhileCond => "`while` condition",
428 UnusedDelimsCtx::ForIterExpr => "`for` iterator expression",
429 UnusedDelimsCtx::MatchScrutineeExpr => "`match` scrutinee expression",
430 UnusedDelimsCtx::ReturnValue => "`return` value",
431 UnusedDelimsCtx::BlockRetValue => "block return value",
432 UnusedDelimsCtx::LetScrutineeExpr => "`let` scrutinee expression",
433 UnusedDelimsCtx::ArrayLenExpr | UnusedDelimsCtx::AnonConst => "const expression",
434 UnusedDelimsCtx::MatchArmExpr => "match arm expression",
439 /// Used by both `UnusedParens` and `UnusedBraces` to prevent code duplication.
440 trait UnusedDelimLint {
441 const DELIM_STR: &'static str;
443 /// Due to `ref` pattern, there can be a difference between using
444 /// `{ expr }` and `expr` in pattern-matching contexts. This means
445 /// that we should only lint `unused_parens` and not `unused_braces`
450 /// let ref b = { a }; // We actually borrow a copy of `a` here.
451 /// a += 1; // By mutating `a` we invalidate any borrows of `a`.
452 /// assert_eq!(b + 1, a); // `b` does not borrow `a`, so we can still use it here.
454 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool;
456 // this cannot be a constant is it refers to a static.
457 fn lint(&self) -> &'static Lint;
459 fn check_unused_delims_expr(
461 cx: &EarlyContext<'_>,
463 ctx: UnusedDelimsCtx,
464 followed_by_block: bool,
465 left_pos: Option<BytePos>,
466 right_pos: Option<BytePos>,
469 fn is_expr_delims_necessary(
471 followed_by_block: bool,
472 followed_by_else: bool,
474 if followed_by_else {
476 ast::ExprKind::Binary(op, ..) if op.node.lazy() => return true,
477 _ if classify::expr_trailing_brace(inner).is_some() => return true,
482 // Prevent false-positives in cases like `fn x() -> u8 { ({ 0 } + 1) }`
483 let lhs_needs_parens = {
484 let mut innermost = inner;
486 innermost = match &innermost.kind {
487 ExprKind::Binary(_, lhs, _rhs) => lhs,
488 ExprKind::Call(fn_, _params) => fn_,
489 ExprKind::Cast(expr, _ty) => expr,
490 ExprKind::Type(expr, _ty) => expr,
491 ExprKind::Index(base, _subscript) => base,
494 if !classify::expr_requires_semi_to_be_stmt(innermost) {
501 || (followed_by_block
502 && match &inner.kind {
503 ExprKind::Ret(_) | ExprKind::Break(..) | ExprKind::Yield(..) => true,
504 ExprKind::Range(_lhs, Some(rhs), _limits) => {
505 matches!(rhs.kind, ExprKind::Block(..))
507 _ => parser::contains_exterior_struct_lit(&inner),
511 fn emit_unused_delims_expr(
513 cx: &EarlyContext<'_>,
515 ctx: UnusedDelimsCtx,
516 left_pos: Option<BytePos>,
517 right_pos: Option<BytePos>,
519 let spans = match value.kind {
520 ast::ExprKind::Block(ref block, None) if block.stmts.len() > 0 => {
521 let start = block.stmts[0].span;
522 let end = block.stmts[block.stmts.len() - 1].span;
523 if let Some(start) = start.find_ancestor_inside(value.span)
524 && let Some(end) = end.find_ancestor_inside(value.span)
527 value.span.with_hi(start.lo()),
528 value.span.with_lo(end.hi()),
534 ast::ExprKind::Paren(ref expr) => {
535 let expr_span = expr.span.find_ancestor_inside(value.span);
536 if let Some(expr_span) = expr_span {
537 Some((value.span.with_hi(expr_span.lo()), value.span.with_lo(expr_span.hi())))
545 left_pos.map_or(false, |s| s >= value.span.lo()),
546 right_pos.map_or(false, |s| s <= value.span.hi()),
548 self.emit_unused_delims(cx, value.span, spans, ctx.into(), keep_space);
551 fn emit_unused_delims(
553 cx: &EarlyContext<'_>,
555 spans: Option<(Span, Span)>,
557 keep_space: (bool, bool),
559 let primary_span = if let Some((lo, hi)) = spans {
560 MultiSpan::from(vec![lo, hi])
562 MultiSpan::from(value_span)
564 cx.struct_span_lint(self.lint(), primary_span, fluent::lint_unused_delim, |lint| {
565 lint.set_arg("delim", Self::DELIM_STR);
566 lint.set_arg("item", msg);
567 if let Some((lo, hi)) = spans {
568 let replacement = vec![
569 (lo, if keep_space.0 { " ".into() } else { "".into() }),
570 (hi, if keep_space.1 { " ".into() } else { "".into() }),
572 lint.multipart_suggestion(
575 Applicability::MachineApplicable,
582 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
583 use rustc_ast::ExprKind::*;
584 let (value, ctx, followed_by_block, left_pos, right_pos) = match e.kind {
585 // Do not lint `unused_braces` in `if let` expressions.
586 If(ref cond, ref block, _)
587 if !matches!(cond.kind, Let(_, _, _))
588 || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
590 let left = e.span.lo() + rustc_span::BytePos(2);
591 let right = block.span.lo();
592 (cond, UnusedDelimsCtx::IfCond, true, Some(left), Some(right))
595 // Do not lint `unused_braces` in `while let` expressions.
596 While(ref cond, ref block, ..)
597 if !matches!(cond.kind, Let(_, _, _))
598 || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
600 let left = e.span.lo() + rustc_span::BytePos(5);
601 let right = block.span.lo();
602 (cond, UnusedDelimsCtx::WhileCond, true, Some(left), Some(right))
605 ForLoop(_, ref cond, ref block, ..) => {
606 (cond, UnusedDelimsCtx::ForIterExpr, true, None, Some(block.span.lo()))
609 Match(ref head, _) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
610 let left = e.span.lo() + rustc_span::BytePos(5);
611 (head, UnusedDelimsCtx::MatchScrutineeExpr, true, Some(left), None)
614 Ret(Some(ref value)) => {
615 let left = e.span.lo() + rustc_span::BytePos(3);
616 (value, UnusedDelimsCtx::ReturnValue, false, Some(left), None)
619 Assign(_, ref value, _) | AssignOp(.., ref value) => {
620 (value, UnusedDelimsCtx::AssignedValue, false, None, None)
622 // either function/method call, or something this lint doesn't care about
623 ref call_or_other => {
624 let (args_to_check, ctx) = match *call_or_other {
625 Call(_, ref args) => (&args[..], UnusedDelimsCtx::FunctionArg),
626 MethodCall(_, _, ref args, _) => (&args[..], UnusedDelimsCtx::MethodArg),
627 // actual catch-all arm
632 // Don't lint if this is a nested macro expansion: otherwise, the lint could
633 // trigger in situations that macro authors shouldn't have to care about, e.g.,
634 // when a parenthesized token tree matched in one macro expansion is matched as
635 // an expression in another and used as a fn/method argument (Issue #47775)
636 if e.span.ctxt().outer_expn_data().call_site.from_expansion() {
639 for arg in args_to_check {
640 self.check_unused_delims_expr(cx, arg, ctx, false, None, None);
645 self.check_unused_delims_expr(cx, &value, ctx, followed_by_block, left_pos, right_pos);
648 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
650 StmtKind::Local(ref local) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
651 if let Some((init, els)) = local.kind.init_else_opt() {
652 let ctx = match els {
653 None => UnusedDelimsCtx::AssignedValue,
654 Some(_) => UnusedDelimsCtx::AssignedValueLetElse,
656 self.check_unused_delims_expr(cx, init, ctx, false, None, None);
659 StmtKind::Expr(ref expr) => {
660 self.check_unused_delims_expr(
663 UnusedDelimsCtx::BlockRetValue,
673 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
674 use ast::ItemKind::*;
676 if let Const(.., Some(expr)) | Static(.., Some(expr)) = &item.kind {
677 self.check_unused_delims_expr(
680 UnusedDelimsCtx::AssignedValue,
690 /// The `unused_parens` lint detects `if`, `match`, `while` and `return`
691 /// with parentheses; they do not need them.
703 /// The parentheses are not needed, and should be removed. This is the
704 /// preferred style for writing these expressions.
705 pub(super) UNUSED_PARENS,
707 "`if`, `match`, `while` and `return` do not need parentheses"
710 declare_lint_pass!(UnusedParens => [UNUSED_PARENS]);
712 impl UnusedDelimLint for UnusedParens {
713 const DELIM_STR: &'static str = "parentheses";
715 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = true;
717 fn lint(&self) -> &'static Lint {
721 fn check_unused_delims_expr(
723 cx: &EarlyContext<'_>,
725 ctx: UnusedDelimsCtx,
726 followed_by_block: bool,
727 left_pos: Option<BytePos>,
728 right_pos: Option<BytePos>,
731 ast::ExprKind::Paren(ref inner) => {
732 let followed_by_else = ctx == UnusedDelimsCtx::AssignedValueLetElse;
733 if !Self::is_expr_delims_necessary(inner, followed_by_block, followed_by_else)
734 && value.attrs.is_empty()
735 && !value.span.from_expansion()
736 && (ctx != UnusedDelimsCtx::LetScrutineeExpr
737 || !matches!(inner.kind, ast::ExprKind::Binary(
738 rustc_span::source_map::Spanned { node, .. },
743 self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
746 ast::ExprKind::Let(_, ref expr, _) => {
747 self.check_unused_delims_expr(
750 UnusedDelimsCtx::LetScrutineeExpr,
762 fn check_unused_parens_pat(
764 cx: &EarlyContext<'_>,
769 use ast::{BindingAnnotation, PatKind};
771 if let PatKind::Paren(inner) = &value.kind {
773 // The lint visitor will visit each subpattern of `p`. We do not want to lint
774 // any range pattern no matter where it occurs in the pattern. For something like
775 // `&(a..=b)`, there is a recursive `check_pat` on `a` and `b`, but we will assume
776 // that if there are unnecessary parens they serve a purpose of readability.
777 PatKind::Range(..) => return,
778 // Avoid `p0 | .. | pn` if we should.
779 PatKind::Or(..) if avoid_or => return,
780 // Avoid `mut x` and `mut x @ p` if we should:
781 PatKind::Ident(BindingAnnotation::MUT, ..) if avoid_mut => {
784 // Otherwise proceed with linting.
787 let spans = if let Some(inner) = inner.span.find_ancestor_inside(value.span) {
788 Some((value.span.with_hi(inner.lo()), value.span.with_lo(inner.hi())))
792 self.emit_unused_delims(cx, value.span, spans, "pattern", (false, false));
797 impl EarlyLintPass for UnusedParens {
798 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
800 ExprKind::Let(ref pat, _, _) | ExprKind::ForLoop(ref pat, ..) => {
801 self.check_unused_parens_pat(cx, pat, false, false);
803 // We ignore parens in cases like `if (((let Some(0) = Some(1))))` because we already
804 // handle a hard error for them during AST lowering in `lower_expr_mut`, but we still
805 // want to complain about things like `if let 42 = (42)`.
806 ExprKind::If(ref cond, ref block, ref else_)
807 if matches!(cond.peel_parens().kind, ExprKind::Let(..)) =>
809 self.check_unused_delims_expr(
812 UnusedDelimsCtx::LetScrutineeExpr,
817 for stmt in &block.stmts {
818 <Self as UnusedDelimLint>::check_stmt(self, cx, stmt);
820 if let Some(e) = else_ {
821 <Self as UnusedDelimLint>::check_expr(self, cx, e);
825 ExprKind::Match(ref _expr, ref arm) => {
827 self.check_unused_delims_expr(
830 UnusedDelimsCtx::MatchArmExpr,
840 <Self as UnusedDelimLint>::check_expr(self, cx, e)
843 fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
844 use ast::{Mutability, PatKind::*};
846 // Do not lint on `(..)` as that will result in the other arms being useless.
848 // The other cases do not contain sub-patterns.
849 | Wild | Rest | Lit(..) | MacCall(..) | Range(..) | Ident(.., None) | Path(..) => {},
850 // These are list-like patterns; parens can always be removed.
851 TupleStruct(_, _, ps) | Tuple(ps) | Slice(ps) | Or(ps) => for p in ps {
852 self.check_unused_parens_pat(cx, p, false, false);
854 Struct(_, _, fps, _) => for f in fps {
855 self.check_unused_parens_pat(cx, &f.pat, false, false);
857 // Avoid linting on `i @ (p0 | .. | pn)` and `box (p0 | .. | pn)`, #64106.
858 Ident(.., Some(p)) | Box(p) => self.check_unused_parens_pat(cx, p, true, false),
859 // Avoid linting on `&(mut x)` as `&mut x` has a different meaning, #55342.
860 // Also avoid linting on `& mut? (p0 | .. | pn)`, #64106.
861 Ref(p, m) => self.check_unused_parens_pat(cx, p, true, *m == Mutability::Not),
865 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
866 if let StmtKind::Local(ref local) = s.kind {
867 self.check_unused_parens_pat(cx, &local.pat, true, false);
870 <Self as UnusedDelimLint>::check_stmt(self, cx, s)
873 fn check_param(&mut self, cx: &EarlyContext<'_>, param: &ast::Param) {
874 self.check_unused_parens_pat(cx, ¶m.pat, true, false);
877 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
878 self.check_unused_parens_pat(cx, &arm.pat, false, false);
881 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
882 if let ast::TyKind::Paren(r) = &ty.kind {
884 ast::TyKind::TraitObject(..) => {}
885 ast::TyKind::ImplTrait(_, bounds) if bounds.len() > 1 => {}
886 ast::TyKind::Array(_, len) => {
887 self.check_unused_delims_expr(
890 UnusedDelimsCtx::ArrayLenExpr,
897 let spans = if let Some(r) = r.span.find_ancestor_inside(ty.span) {
898 Some((ty.span.with_hi(r.lo()), ty.span.with_lo(r.hi())))
902 self.emit_unused_delims(cx, ty.span, spans, "type", (false, false));
908 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
909 <Self as UnusedDelimLint>::check_item(self, cx, item)
914 /// The `unused_braces` lint detects unnecessary braces around an
929 /// The braces are not needed, and should be removed. This is the
930 /// preferred style for writing these expressions.
931 pub(super) UNUSED_BRACES,
933 "unnecessary braces around an expression"
936 declare_lint_pass!(UnusedBraces => [UNUSED_BRACES]);
938 impl UnusedDelimLint for UnusedBraces {
939 const DELIM_STR: &'static str = "braces";
941 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = false;
943 fn lint(&self) -> &'static Lint {
947 fn check_unused_delims_expr(
949 cx: &EarlyContext<'_>,
951 ctx: UnusedDelimsCtx,
952 followed_by_block: bool,
953 left_pos: Option<BytePos>,
954 right_pos: Option<BytePos>,
957 ast::ExprKind::Block(ref inner, None)
958 if inner.rules == ast::BlockCheckMode::Default =>
960 // emit a warning under the following conditions:
962 // - the block does not have a label
963 // - the block is not `unsafe`
964 // - the block contains exactly one expression (do not lint `{ expr; }`)
965 // - `followed_by_block` is true and the internal expr may contain a `{`
966 // - the block is not multiline (do not lint multiline match arms)
970 // somewhat_long_expression
975 // - the block has no attribute and was not created inside a macro
976 // - if the block is an `anon_const`, the inner expr must be a literal
977 // (do not lint `struct A<const N: usize>; let _: A<{ 2 + 3 }>;`)
979 // FIXME(const_generics): handle paths when #67075 is fixed.
980 if let [stmt] = inner.stmts.as_slice() {
981 if let ast::StmtKind::Expr(ref expr) = stmt.kind {
982 if !Self::is_expr_delims_necessary(expr, followed_by_block, false)
983 && (ctx != UnusedDelimsCtx::AnonConst
984 || matches!(expr.kind, ast::ExprKind::Lit(_)))
985 && !cx.sess().source_map().is_multiline(value.span)
986 && value.attrs.is_empty()
987 && !value.span.from_expansion()
989 self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
994 ast::ExprKind::Let(_, ref expr, _) => {
995 self.check_unused_delims_expr(
998 UnusedDelimsCtx::LetScrutineeExpr,
1009 impl EarlyLintPass for UnusedBraces {
1010 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
1011 <Self as UnusedDelimLint>::check_stmt(self, cx, s)
1014 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
1015 <Self as UnusedDelimLint>::check_expr(self, cx, e);
1017 if let ExprKind::Repeat(_, ref anon_const) = e.kind {
1018 self.check_unused_delims_expr(
1021 UnusedDelimsCtx::AnonConst,
1029 fn check_generic_arg(&mut self, cx: &EarlyContext<'_>, arg: &ast::GenericArg) {
1030 if let ast::GenericArg::Const(ct) = arg {
1031 self.check_unused_delims_expr(
1034 UnusedDelimsCtx::AnonConst,
1042 fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant) {
1043 if let Some(anon_const) = &v.disr_expr {
1044 self.check_unused_delims_expr(
1047 UnusedDelimsCtx::AnonConst,
1055 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
1057 ast::TyKind::Array(_, ref len) => {
1058 self.check_unused_delims_expr(
1061 UnusedDelimsCtx::ArrayLenExpr,
1068 ast::TyKind::Typeof(ref anon_const) => {
1069 self.check_unused_delims_expr(
1072 UnusedDelimsCtx::AnonConst,
1083 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1084 <Self as UnusedDelimLint>::check_item(self, cx, item)
1089 /// The `unused_import_braces` lint catches unnecessary braces around an
1094 /// ```rust,compile_fail
1095 /// #![deny(unused_import_braces)]
1108 /// If there is only a single item, then remove the braces (`use test::A;`
1111 /// This lint is "allow" by default because it is only enforcing a
1112 /// stylistic choice.
1113 UNUSED_IMPORT_BRACES,
1115 "unnecessary braces around an imported item"
1118 declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]);
1120 impl UnusedImportBraces {
1121 fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
1122 if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
1123 // Recursively check nested UseTrees
1124 for &(ref tree, _) in items {
1125 self.check_use_tree(cx, tree, item);
1128 // Trigger the lint only if there is one nested item
1129 if items.len() != 1 {
1133 // Trigger the lint if the nested item is a non-self single item
1134 let node_name = match items[0].0.kind {
1135 ast::UseTreeKind::Simple(rename, ..) => {
1136 let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
1137 if orig_ident.name == kw::SelfLower {
1140 rename.unwrap_or(orig_ident).name
1142 ast::UseTreeKind::Glob => Symbol::intern("*"),
1143 ast::UseTreeKind::Nested(_) => return,
1146 cx.struct_span_lint(
1147 UNUSED_IMPORT_BRACES,
1149 fluent::lint_unused_import_braces,
1150 |lint| lint.set_arg("node", node_name),
1156 impl EarlyLintPass for UnusedImportBraces {
1157 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1158 if let ast::ItemKind::Use(ref use_tree) = item.kind {
1159 self.check_use_tree(cx, use_tree, item);
1165 /// The `unused_allocation` lint detects unnecessary allocations that can
1171 /// #![feature(box_syntax)]
1173 /// let a = (box [1, 2, 3]).len();
1181 /// When a `box` expression is immediately coerced to a reference, then
1182 /// the allocation is unnecessary, and a reference (using `&` or `&mut`)
1183 /// should be used instead to avoid the allocation.
1184 pub(super) UNUSED_ALLOCATION,
1186 "detects unnecessary allocations that can be eliminated"
1189 declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]);
1191 impl<'tcx> LateLintPass<'tcx> for UnusedAllocation {
1192 fn check_expr(&mut self, cx: &LateContext<'_>, e: &hir::Expr<'_>) {
1194 hir::ExprKind::Box(_) => {}
1198 for adj in cx.typeck_results().expr_adjustments(e) {
1199 if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
1200 cx.struct_span_lint(
1204 adjustment::AutoBorrowMutability::Not => fluent::lint_unused_allocation,
1205 adjustment::AutoBorrowMutability::Mut { .. } => {
1206 fluent::lint_unused_allocation_mut