2 PathStatementDrop, PathStatementDropSub, PathStatementNoEffect, UnusedAllocationDiag,
3 UnusedAllocationMutDiag, UnusedClosure, UnusedDef, UnusedDefSuggestion, UnusedDelim,
4 UnusedDelimSuggestion, UnusedGenerator, UnusedImportBracesDiag, UnusedOp, UnusedResult,
7 use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
9 use rustc_ast::util::{classify, parser};
10 use rustc_ast::{ExprKind, StmtKind};
11 use rustc_errors::{pluralize, MultiSpan};
13 use rustc_hir::def::{DefKind, Res};
14 use rustc_hir::def_id::DefId;
15 use rustc_infer::traits::util::elaborate_predicates_with_span;
16 use rustc_middle::ty::adjustment;
17 use rustc_middle::ty::{self, DefIdTree, Ty};
18 use rustc_span::symbol::Symbol;
19 use rustc_span::symbol::{kw, sym};
20 use rustc_span::{BytePos, Span};
24 /// The `unused_must_use` lint detects unused result of a type flagged as
30 /// fn returns_result() -> Result<(), ()> {
43 /// The `#[must_use]` attribute is an indicator that it is a mistake to
44 /// ignore the value. See [the reference] for more details.
46 /// [the reference]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
49 "unused result of a type flagged as `#[must_use]`",
50 report_in_external_macro
54 /// The `unused_results` lint checks for the unused result of an
55 /// expression in a statement.
59 /// ```rust,compile_fail
60 /// #![deny(unused_results)]
61 /// fn foo<T>() -> T { panic!() }
72 /// Ignoring the return value of a function may indicate a mistake. In
73 /// cases were it is almost certain that the result should be used, it is
74 /// recommended to annotate the function with the [`must_use` attribute].
75 /// Failure to use such a return value will trigger the [`unused_must_use`
76 /// lint] which is warn-by-default. The `unused_results` lint is
77 /// essentially the same, but triggers for *all* return values.
79 /// This lint is "allow" by default because it can be noisy, and may not be
80 /// an actual problem. For example, calling the `remove` method of a `Vec`
81 /// or `HashMap` returns the previous value, which you may not care about.
82 /// Using this lint would require explicitly ignoring or discarding such
85 /// [`must_use` attribute]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
86 /// [`unused_must_use` lint]: warn-by-default.html#unused-must-use
89 "unused result of an expression in a statement"
92 declare_lint_pass!(UnusedResults => [UNUSED_MUST_USE, UNUSED_RESULTS]);
94 impl<'tcx> LateLintPass<'tcx> for UnusedResults {
95 fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
96 let hir::StmtKind::Semi(expr) = s.kind else { return; };
98 if let hir::ExprKind::Ret(..) = expr.kind {
102 if let hir::ExprKind::Match(await_expr, _arms, hir::MatchSource::AwaitDesugar) = expr.kind
103 && let ty = cx.typeck_results().expr_ty(&await_expr)
104 && let ty::Alias(ty::Opaque, ty::AliasTy { def_id: future_def_id, .. }) = ty.kind()
105 && cx.tcx.ty_is_opaque_future(ty)
106 // FIXME: This also includes non-async fns that return `impl Future`.
107 && let async_fn_def_id = cx.tcx.parent(*future_def_id)
108 && check_must_use_def(
112 "output of future returned by ",
116 // We have a bare `foo().await;` on an opaque type from an async function that was
117 // annotated with `#[must_use]`.
121 let ty = cx.typeck_results().expr_ty(&expr);
123 let must_use_result = is_ty_must_use(cx, ty, &expr, expr.span);
124 let type_lint_emitted_or_suppressed = match must_use_result {
126 emit_must_use_untranslated(cx, &path, "", "", 1);
132 let fn_warned = check_fn_must_use(cx, expr);
134 if !fn_warned && type_lint_emitted_or_suppressed {
135 // We don't warn about unused unit or uninhabited types.
136 // (See https://github.com/rust-lang/rust/issues/43806 for details.)
140 let must_use_op = match expr.kind {
141 // Hardcoding operators here seemed more expedient than the
142 // refactoring that would be needed to look up the `#[must_use]`
143 // attribute which does exist on the comparison trait methods
144 hir::ExprKind::Binary(bin_op, ..) => match bin_op.node {
150 | hir::BinOpKind::Gt => Some("comparison"),
152 | hir::BinOpKind::Sub
153 | hir::BinOpKind::Div
154 | hir::BinOpKind::Mul
155 | hir::BinOpKind::Rem => Some("arithmetic operation"),
156 hir::BinOpKind::And | hir::BinOpKind::Or => Some("logical operation"),
157 hir::BinOpKind::BitXor
158 | hir::BinOpKind::BitAnd
159 | hir::BinOpKind::BitOr
160 | hir::BinOpKind::Shl
161 | hir::BinOpKind::Shr => Some("bitwise operation"),
163 hir::ExprKind::AddrOf(..) => Some("borrow"),
164 hir::ExprKind::Unary(..) => Some("unary operation"),
168 let mut op_warned = false;
170 if let Some(must_use_op) = must_use_op {
171 cx.emit_spanned_lint(
177 suggestion: expr.span.shrink_to_lo(),
183 if !(type_lint_emitted_or_suppressed || fn_warned || op_warned) {
184 cx.emit_spanned_lint(UNUSED_RESULTS, s.span, UnusedResult { ty });
187 fn check_fn_must_use(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool {
188 let maybe_def_id = match expr.kind {
189 hir::ExprKind::Call(ref callee, _) => {
191 hir::ExprKind::Path(ref qpath) => {
192 match cx.qpath_res(qpath, callee.hir_id) {
193 Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) => Some(def_id),
194 // `Res::Local` if it was a closure, for which we
195 // do not currently support must-use linting
202 hir::ExprKind::MethodCall(..) => {
203 cx.typeck_results().type_dependent_def_id(expr.hir_id)
207 if let Some(def_id) = maybe_def_id {
208 check_must_use_def(cx, def_id, expr.span, "return value of ", "")
214 /// A path through a type to a must_use source. Contains useful info for the lint.
217 /// Suppress must_use checking.
219 /// The root of the normal must_use lint with an optional message.
220 Def(Span, DefId, Option<Symbol>),
223 TraitObject(Box<Self>),
224 TupleElement(Vec<(usize, Self)>),
225 Array(Box<Self>, u64),
226 /// The root of the unused_closures lint.
228 /// The root of the unused_generators lint.
232 #[instrument(skip(cx, expr), level = "debug", ret)]
233 fn is_ty_must_use<'tcx>(
234 cx: &LateContext<'tcx>,
236 expr: &hir::Expr<'_>,
238 ) -> Option<MustUsePath> {
240 || !ty.is_inhabited_from(
242 cx.tcx.parent_module(expr.hir_id).to_def_id(),
246 return Some(MustUsePath::Suppressed);
250 ty::Adt(..) if ty.is_box() => {
251 let boxed_ty = ty.boxed_ty();
252 is_ty_must_use(cx, boxed_ty, expr, span)
253 .map(|inner| MustUsePath::Boxed(Box::new(inner)))
255 ty::Adt(def, _) => is_def_must_use(cx, def.did(), span),
256 ty::Alias(ty::Opaque, ty::AliasTy { def_id: def, .. }) => {
257 elaborate_predicates_with_span(
259 cx.tcx.explicit_item_bounds(def).iter().cloned(),
261 .find_map(|obligation| {
262 // We only look at the `DefId`, so it is safe to skip the binder here.
263 if let ty::PredicateKind::Clause(ty::Clause::Trait(
264 ref poly_trait_predicate,
265 )) = obligation.predicate.kind().skip_binder()
267 let def_id = poly_trait_predicate.trait_ref.def_id;
269 is_def_must_use(cx, def_id, span)
274 .map(|inner| MustUsePath::Opaque(Box::new(inner)))
276 ty::Dynamic(binders, _, _) => binders.iter().find_map(|predicate| {
277 if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder()
279 let def_id = trait_ref.def_id;
280 is_def_must_use(cx, def_id, span)
281 .map(|inner| MustUsePath::TraitObject(Box::new(inner)))
287 let elem_exprs = if let hir::ExprKind::Tup(elem_exprs) = expr.kind {
288 debug_assert_eq!(elem_exprs.len(), tys.len());
294 // Default to `expr`.
295 let elem_exprs = elem_exprs.iter().chain(iter::repeat(expr));
297 let nested_must_use = tys
301 .filter_map(|(i, (ty, expr))| {
302 is_ty_must_use(cx, ty, expr, expr.span).map(|path| (i, path))
304 .collect::<Vec<_>>();
306 if !nested_must_use.is_empty() {
307 Some(MustUsePath::TupleElement(nested_must_use))
312 ty::Array(ty, len) => match len.try_eval_usize(cx.tcx, cx.param_env) {
313 // If the array is empty we don't lint, to avoid false positives
314 Some(0) | None => None,
315 // If the array is definitely non-empty, we can do `#[must_use]` checking.
316 Some(len) => is_ty_must_use(cx, ty, expr, span)
317 .map(|inner| MustUsePath::Array(Box::new(inner), len)),
319 ty::Closure(..) => Some(MustUsePath::Closure(span)),
320 ty::Generator(def_id, ..) => {
321 // async fn should be treated as "implementor of `Future`"
322 let must_use = if cx.tcx.generator_is_async(def_id) {
323 let def_id = cx.tcx.lang_items().future_trait().unwrap();
324 is_def_must_use(cx, def_id, span)
325 .map(|inner| MustUsePath::Opaque(Box::new(inner)))
329 must_use.or(Some(MustUsePath::Generator(span)))
335 fn is_def_must_use(cx: &LateContext<'_>, def_id: DefId, span: Span) -> Option<MustUsePath> {
336 if let Some(attr) = cx.tcx.get_attr(def_id, sym::must_use) {
337 // check for #[must_use = "..."]
338 let reason = attr.value_str();
339 Some(MustUsePath::Def(span, def_id, reason))
345 // Returns whether further errors should be suppressed because either a lint has been emitted or the type should be ignored.
346 fn check_must_use_def(
347 cx: &LateContext<'_>,
350 descr_pre_path: &str,
351 descr_post_path: &str,
353 is_def_must_use(cx, def_id, span)
354 .map(|must_use_path| {
355 emit_must_use_untranslated(
366 #[instrument(skip(cx), level = "debug")]
367 fn emit_must_use_untranslated(
368 cx: &LateContext<'_>,
374 let plural_suffix = pluralize!(plural_len);
377 MustUsePath::Suppressed => {}
378 MustUsePath::Boxed(path) => {
379 let descr_pre = &format!("{}boxed ", descr_pre);
380 emit_must_use_untranslated(cx, path, descr_pre, descr_post, plural_len);
382 MustUsePath::Opaque(path) => {
383 let descr_pre = &format!("{}implementer{} of ", descr_pre, plural_suffix);
384 emit_must_use_untranslated(cx, path, descr_pre, descr_post, plural_len);
386 MustUsePath::TraitObject(path) => {
387 let descr_post = &format!(" trait object{}{}", plural_suffix, descr_post);
388 emit_must_use_untranslated(cx, path, descr_pre, descr_post, plural_len);
390 MustUsePath::TupleElement(elems) => {
391 for (index, path) in elems {
392 let descr_post = &format!(" in tuple element {}", index);
393 emit_must_use_untranslated(cx, path, descr_pre, descr_post, plural_len);
396 MustUsePath::Array(path, len) => {
397 let descr_pre = &format!("{}array{} of ", descr_pre, plural_suffix);
398 emit_must_use_untranslated(
403 plural_len.saturating_add(usize::try_from(*len).unwrap_or(usize::MAX)),
406 MustUsePath::Closure(span) => {
407 cx.emit_spanned_lint(
410 UnusedClosure { count: plural_len, pre: descr_pre, post: descr_post },
413 MustUsePath::Generator(span) => {
414 cx.emit_spanned_lint(
417 UnusedGenerator { count: plural_len, pre: descr_pre, post: descr_post },
420 MustUsePath::Def(span, def_id, reason) => {
421 let suggestion = if matches!(
422 cx.tcx.get_diagnostic_name(*def_id),
430 Some(UnusedDefSuggestion::Default { span: span.shrink_to_lo() })
434 cx.emit_spanned_lint(
453 /// The `path_statements` lint detects path statements with no effect.
467 /// It is usually a mistake to have a statement that has no effect.
470 "path statements with no effect"
473 declare_lint_pass!(PathStatements => [PATH_STATEMENTS]);
475 impl<'tcx> LateLintPass<'tcx> for PathStatements {
476 fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
477 if let hir::StmtKind::Semi(expr) = s.kind {
478 if let hir::ExprKind::Path(_) = expr.kind {
479 let ty = cx.typeck_results().expr_ty(expr);
480 if ty.needs_drop(cx.tcx, cx.param_env) {
481 let sub = if let Ok(snippet) = cx.sess().source_map().span_to_snippet(expr.span)
483 PathStatementDropSub::Suggestion { span: s.span, snippet }
485 PathStatementDropSub::Help { span: s.span }
487 cx.emit_spanned_lint(PATH_STATEMENTS, s.span, PathStatementDrop { sub })
489 cx.emit_spanned_lint(PATH_STATEMENTS, s.span, PathStatementNoEffect);
496 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
497 enum UnusedDelimsCtx {
501 AssignedValueLetElse,
514 impl From<UnusedDelimsCtx> for &'static str {
515 fn from(ctx: UnusedDelimsCtx) -> &'static str {
517 UnusedDelimsCtx::FunctionArg => "function argument",
518 UnusedDelimsCtx::MethodArg => "method argument",
519 UnusedDelimsCtx::AssignedValue | UnusedDelimsCtx::AssignedValueLetElse => {
522 UnusedDelimsCtx::IfCond => "`if` condition",
523 UnusedDelimsCtx::WhileCond => "`while` condition",
524 UnusedDelimsCtx::ForIterExpr => "`for` iterator expression",
525 UnusedDelimsCtx::MatchScrutineeExpr => "`match` scrutinee expression",
526 UnusedDelimsCtx::ReturnValue => "`return` value",
527 UnusedDelimsCtx::BlockRetValue => "block return value",
528 UnusedDelimsCtx::LetScrutineeExpr => "`let` scrutinee expression",
529 UnusedDelimsCtx::ArrayLenExpr | UnusedDelimsCtx::AnonConst => "const expression",
530 UnusedDelimsCtx::MatchArmExpr => "match arm expression",
535 /// Used by both `UnusedParens` and `UnusedBraces` to prevent code duplication.
536 trait UnusedDelimLint {
537 const DELIM_STR: &'static str;
539 /// Due to `ref` pattern, there can be a difference between using
540 /// `{ expr }` and `expr` in pattern-matching contexts. This means
541 /// that we should only lint `unused_parens` and not `unused_braces`
546 /// let ref b = { a }; // We actually borrow a copy of `a` here.
547 /// a += 1; // By mutating `a` we invalidate any borrows of `a`.
548 /// assert_eq!(b + 1, a); // `b` does not borrow `a`, so we can still use it here.
550 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool;
552 // this cannot be a constant is it refers to a static.
553 fn lint(&self) -> &'static Lint;
555 fn check_unused_delims_expr(
557 cx: &EarlyContext<'_>,
559 ctx: UnusedDelimsCtx,
560 followed_by_block: bool,
561 left_pos: Option<BytePos>,
562 right_pos: Option<BytePos>,
565 fn is_expr_delims_necessary(
567 followed_by_block: bool,
568 followed_by_else: bool,
570 if followed_by_else {
572 ast::ExprKind::Binary(op, ..) if op.node.lazy() => return true,
573 _ if classify::expr_trailing_brace(inner).is_some() => return true,
578 // Prevent false-positives in cases like `fn x() -> u8 { ({ 0 } + 1) }`
579 let lhs_needs_parens = {
580 let mut innermost = inner;
582 innermost = match &innermost.kind {
583 ExprKind::Binary(_, lhs, _rhs) => lhs,
584 ExprKind::Call(fn_, _params) => fn_,
585 ExprKind::Cast(expr, _ty) => expr,
586 ExprKind::Type(expr, _ty) => expr,
587 ExprKind::Index(base, _subscript) => base,
590 if !classify::expr_requires_semi_to_be_stmt(innermost) {
597 || (followed_by_block
598 && match &inner.kind {
600 | ExprKind::Break(..)
601 | ExprKind::Yield(..)
602 | ExprKind::Yeet(..) => true,
603 ExprKind::Range(_lhs, Some(rhs), _limits) => {
604 matches!(rhs.kind, ExprKind::Block(..))
606 _ => parser::contains_exterior_struct_lit(&inner),
610 fn emit_unused_delims_expr(
612 cx: &EarlyContext<'_>,
614 ctx: UnusedDelimsCtx,
615 left_pos: Option<BytePos>,
616 right_pos: Option<BytePos>,
618 // If `value` has `ExprKind::Err`, unused delim lint can be broken.
619 // For example, the following code caused ICE.
620 // This is because the `ExprKind::Call` in `value` has `ExprKind::Err` as its argument
621 // and this leads to wrong spans. #104897
626 use rustc_ast::visit::{walk_expr, Visitor};
627 struct ErrExprVisitor {
630 impl<'ast> Visitor<'ast> for ErrExprVisitor {
631 fn visit_expr(&mut self, expr: &'ast ast::Expr) {
632 if let ExprKind::Err = expr.kind {
633 self.has_error = true;
636 walk_expr(self, expr)
639 let mut visitor = ErrExprVisitor { has_error: false };
640 visitor.visit_expr(value);
641 if visitor.has_error {
644 let spans = match value.kind {
645 ast::ExprKind::Block(ref block, None) if block.stmts.len() == 1 => {
646 if let Some(span) = block.stmts[0].span.find_ancestor_inside(value.span) {
647 Some((value.span.with_hi(span.lo()), value.span.with_lo(span.hi())))
652 ast::ExprKind::Paren(ref expr) => {
653 let expr_span = expr.span.find_ancestor_inside(value.span);
654 if let Some(expr_span) = expr_span {
655 Some((value.span.with_hi(expr_span.lo()), value.span.with_lo(expr_span.hi())))
663 left_pos.map_or(false, |s| s >= value.span.lo()),
664 right_pos.map_or(false, |s| s <= value.span.hi()),
666 self.emit_unused_delims(cx, value.span, spans, ctx.into(), keep_space);
669 fn emit_unused_delims(
671 cx: &EarlyContext<'_>,
673 spans: Option<(Span, Span)>,
675 keep_space: (bool, bool),
677 let primary_span = if let Some((lo, hi)) = spans {
678 MultiSpan::from(vec![lo, hi])
680 MultiSpan::from(value_span)
682 let suggestion = spans.map(|(lo, hi)| {
683 let sm = cx.sess().source_map();
686 let Ok(snip) = sm.span_to_prev_source(lo) && !snip.ends_with(' ') {
694 let Ok(snip) = sm.span_to_next_source(hi) && !snip.starts_with(' ') {
699 UnusedDelimSuggestion {
701 start_replace: lo_replace,
703 end_replace: hi_replace,
706 cx.emit_spanned_lint(
709 UnusedDelim { delim: Self::DELIM_STR, item: msg, suggestion },
713 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
714 use rustc_ast::ExprKind::*;
715 let (value, ctx, followed_by_block, left_pos, right_pos) = match e.kind {
716 // Do not lint `unused_braces` in `if let` expressions.
717 If(ref cond, ref block, _)
718 if !matches!(cond.kind, Let(_, _, _))
719 || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
721 let left = e.span.lo() + rustc_span::BytePos(2);
722 let right = block.span.lo();
723 (cond, UnusedDelimsCtx::IfCond, true, Some(left), Some(right))
726 // Do not lint `unused_braces` in `while let` expressions.
727 While(ref cond, ref block, ..)
728 if !matches!(cond.kind, Let(_, _, _))
729 || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
731 let left = e.span.lo() + rustc_span::BytePos(5);
732 let right = block.span.lo();
733 (cond, UnusedDelimsCtx::WhileCond, true, Some(left), Some(right))
736 ForLoop(_, ref cond, ref block, ..) => {
737 (cond, UnusedDelimsCtx::ForIterExpr, true, None, Some(block.span.lo()))
740 Match(ref head, _) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
741 let left = e.span.lo() + rustc_span::BytePos(5);
742 (head, UnusedDelimsCtx::MatchScrutineeExpr, true, Some(left), None)
745 Ret(Some(ref value)) => {
746 let left = e.span.lo() + rustc_span::BytePos(3);
747 (value, UnusedDelimsCtx::ReturnValue, false, Some(left), None)
750 Assign(_, ref value, _) | AssignOp(.., ref value) => {
751 (value, UnusedDelimsCtx::AssignedValue, false, None, None)
753 // either function/method call, or something this lint doesn't care about
754 ref call_or_other => {
755 let (args_to_check, ctx) = match *call_or_other {
756 Call(_, ref args) => (&args[..], UnusedDelimsCtx::FunctionArg),
757 MethodCall(ref call) => (&call.args[..], UnusedDelimsCtx::MethodArg),
758 // actual catch-all arm
763 // Don't lint if this is a nested macro expansion: otherwise, the lint could
764 // trigger in situations that macro authors shouldn't have to care about, e.g.,
765 // when a parenthesized token tree matched in one macro expansion is matched as
766 // an expression in another and used as a fn/method argument (Issue #47775)
767 if e.span.ctxt().outer_expn_data().call_site.from_expansion() {
770 for arg in args_to_check {
771 self.check_unused_delims_expr(cx, arg, ctx, false, None, None);
776 self.check_unused_delims_expr(cx, &value, ctx, followed_by_block, left_pos, right_pos);
779 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
781 StmtKind::Local(ref local) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
782 if let Some((init, els)) = local.kind.init_else_opt() {
783 let ctx = match els {
784 None => UnusedDelimsCtx::AssignedValue,
785 Some(_) => UnusedDelimsCtx::AssignedValueLetElse,
787 self.check_unused_delims_expr(cx, init, ctx, false, None, None);
790 StmtKind::Expr(ref expr) => {
791 self.check_unused_delims_expr(
794 UnusedDelimsCtx::BlockRetValue,
804 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
805 use ast::ItemKind::*;
807 if let Const(.., Some(expr)) | Static(.., Some(expr)) = &item.kind {
808 self.check_unused_delims_expr(
811 UnusedDelimsCtx::AssignedValue,
821 /// The `unused_parens` lint detects `if`, `match`, `while` and `return`
822 /// with parentheses; they do not need them.
834 /// The parentheses are not needed, and should be removed. This is the
835 /// preferred style for writing these expressions.
836 pub(super) UNUSED_PARENS,
838 "`if`, `match`, `while` and `return` do not need parentheses"
841 pub struct UnusedParens {
842 with_self_ty_parens: bool,
846 pub fn new() -> Self {
847 Self { with_self_ty_parens: false }
851 impl_lint_pass!(UnusedParens => [UNUSED_PARENS]);
853 impl UnusedDelimLint for UnusedParens {
854 const DELIM_STR: &'static str = "parentheses";
856 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = true;
858 fn lint(&self) -> &'static Lint {
862 fn check_unused_delims_expr(
864 cx: &EarlyContext<'_>,
866 ctx: UnusedDelimsCtx,
867 followed_by_block: bool,
868 left_pos: Option<BytePos>,
869 right_pos: Option<BytePos>,
872 ast::ExprKind::Paren(ref inner) => {
873 let followed_by_else = ctx == UnusedDelimsCtx::AssignedValueLetElse;
874 if !Self::is_expr_delims_necessary(inner, followed_by_block, followed_by_else)
875 && value.attrs.is_empty()
876 && !value.span.from_expansion()
877 && (ctx != UnusedDelimsCtx::LetScrutineeExpr
878 || !matches!(inner.kind, ast::ExprKind::Binary(
879 rustc_span::source_map::Spanned { node, .. },
884 self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
887 ast::ExprKind::Let(_, ref expr, _) => {
888 self.check_unused_delims_expr(
891 UnusedDelimsCtx::LetScrutineeExpr,
903 fn check_unused_parens_pat(
905 cx: &EarlyContext<'_>,
909 keep_space: (bool, bool),
911 use ast::{BindingAnnotation, PatKind};
913 if let PatKind::Paren(inner) = &value.kind {
915 // The lint visitor will visit each subpattern of `p`. We do not want to lint
916 // any range pattern no matter where it occurs in the pattern. For something like
917 // `&(a..=b)`, there is a recursive `check_pat` on `a` and `b`, but we will assume
918 // that if there are unnecessary parens they serve a purpose of readability.
919 PatKind::Range(..) => return,
920 // Avoid `p0 | .. | pn` if we should.
921 PatKind::Or(..) if avoid_or => return,
922 // Avoid `mut x` and `mut x @ p` if we should:
923 PatKind::Ident(BindingAnnotation::MUT, ..) if avoid_mut => {
926 // Otherwise proceed with linting.
929 let spans = if let Some(inner) = inner.span.find_ancestor_inside(value.span) {
930 Some((value.span.with_hi(inner.lo()), value.span.with_lo(inner.hi())))
934 self.emit_unused_delims(cx, value.span, spans, "pattern", keep_space);
939 impl EarlyLintPass for UnusedParens {
941 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
943 ExprKind::Let(ref pat, _, _) | ExprKind::ForLoop(ref pat, ..) => {
944 self.check_unused_parens_pat(cx, pat, false, false, (true, true));
946 // We ignore parens in cases like `if (((let Some(0) = Some(1))))` because we already
947 // handle a hard error for them during AST lowering in `lower_expr_mut`, but we still
948 // want to complain about things like `if let 42 = (42)`.
949 ExprKind::If(ref cond, ref block, ref else_)
950 if matches!(cond.peel_parens().kind, ExprKind::Let(..)) =>
952 self.check_unused_delims_expr(
955 UnusedDelimsCtx::LetScrutineeExpr,
960 for stmt in &block.stmts {
961 <Self as UnusedDelimLint>::check_stmt(self, cx, stmt);
963 if let Some(e) = else_ {
964 <Self as UnusedDelimLint>::check_expr(self, cx, e);
968 ExprKind::Match(ref _expr, ref arm) => {
970 self.check_unused_delims_expr(
973 UnusedDelimsCtx::MatchArmExpr,
983 <Self as UnusedDelimLint>::check_expr(self, cx, e)
986 fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
987 use ast::{Mutability, PatKind::*};
988 let keep_space = (false, false);
990 // Do not lint on `(..)` as that will result in the other arms being useless.
992 // The other cases do not contain sub-patterns.
993 | Wild | Rest | Lit(..) | MacCall(..) | Range(..) | Ident(.., None) | Path(..) => {},
994 // These are list-like patterns; parens can always be removed.
995 TupleStruct(_, _, ps) | Tuple(ps) | Slice(ps) | Or(ps) => for p in ps {
996 self.check_unused_parens_pat(cx, p, false, false, keep_space);
998 Struct(_, _, fps, _) => for f in fps {
999 self.check_unused_parens_pat(cx, &f.pat, false, false, keep_space);
1001 // Avoid linting on `i @ (p0 | .. | pn)` and `box (p0 | .. | pn)`, #64106.
1002 Ident(.., Some(p)) | Box(p) => self.check_unused_parens_pat(cx, p, true, false, keep_space),
1003 // Avoid linting on `&(mut x)` as `&mut x` has a different meaning, #55342.
1004 // Also avoid linting on `& mut? (p0 | .. | pn)`, #64106.
1005 Ref(p, m) => self.check_unused_parens_pat(cx, p, true, *m == Mutability::Not, keep_space),
1009 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
1010 if let StmtKind::Local(ref local) = s.kind {
1011 self.check_unused_parens_pat(cx, &local.pat, true, false, (false, false));
1014 <Self as UnusedDelimLint>::check_stmt(self, cx, s)
1017 fn check_param(&mut self, cx: &EarlyContext<'_>, param: &ast::Param) {
1018 self.check_unused_parens_pat(cx, ¶m.pat, true, false, (false, false));
1021 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
1022 self.check_unused_parens_pat(cx, &arm.pat, false, false, (false, false));
1025 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
1027 ast::TyKind::Array(_, len) => {
1028 self.check_unused_delims_expr(
1031 UnusedDelimsCtx::ArrayLenExpr,
1037 ast::TyKind::Paren(r) => {
1039 ast::TyKind::TraitObject(..) => {}
1040 ast::TyKind::BareFn(b)
1041 if self.with_self_ty_parens && b.generic_params.len() > 0 => {}
1042 ast::TyKind::ImplTrait(_, bounds) if bounds.len() > 1 => {}
1044 let spans = if let Some(r) = r.span.find_ancestor_inside(ty.span) {
1045 Some((ty.span.with_hi(r.lo()), ty.span.with_lo(r.hi())))
1049 self.emit_unused_delims(cx, ty.span, spans, "type", (false, false));
1052 self.with_self_ty_parens = false;
1058 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1059 <Self as UnusedDelimLint>::check_item(self, cx, item)
1062 fn enter_where_predicate(&mut self, _: &EarlyContext<'_>, pred: &ast::WherePredicate) {
1063 use rustc_ast::{WhereBoundPredicate, WherePredicate};
1064 if let WherePredicate::BoundPredicate(WhereBoundPredicate {
1066 bound_generic_params,
1069 let ast::TyKind::Paren(_) = &bounded_ty.kind &&
1070 bound_generic_params.is_empty() {
1071 self.with_self_ty_parens = true;
1075 fn exit_where_predicate(&mut self, _: &EarlyContext<'_>, _: &ast::WherePredicate) {
1076 assert!(!self.with_self_ty_parens);
1081 /// The `unused_braces` lint detects unnecessary braces around an
1096 /// The braces are not needed, and should be removed. This is the
1097 /// preferred style for writing these expressions.
1098 pub(super) UNUSED_BRACES,
1100 "unnecessary braces around an expression"
1103 declare_lint_pass!(UnusedBraces => [UNUSED_BRACES]);
1105 impl UnusedDelimLint for UnusedBraces {
1106 const DELIM_STR: &'static str = "braces";
1108 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = false;
1110 fn lint(&self) -> &'static Lint {
1114 fn check_unused_delims_expr(
1116 cx: &EarlyContext<'_>,
1118 ctx: UnusedDelimsCtx,
1119 followed_by_block: bool,
1120 left_pos: Option<BytePos>,
1121 right_pos: Option<BytePos>,
1124 ast::ExprKind::Block(ref inner, None)
1125 if inner.rules == ast::BlockCheckMode::Default =>
1127 // emit a warning under the following conditions:
1129 // - the block does not have a label
1130 // - the block is not `unsafe`
1131 // - the block contains exactly one expression (do not lint `{ expr; }`)
1132 // - `followed_by_block` is true and the internal expr may contain a `{`
1133 // - the block is not multiline (do not lint multiline match arms)
1137 // somewhat_long_expression
1142 // - the block has no attribute and was not created inside a macro
1143 // - if the block is an `anon_const`, the inner expr must be a literal
1144 // not created by a macro, i.e. do not lint on:
1146 // struct A<const N: usize>;
1147 // let _: A<{ 2 + 3 }>;
1148 // let _: A<{produces_literal!()}>;
1150 // FIXME(const_generics): handle paths when #67075 is fixed.
1151 if let [stmt] = inner.stmts.as_slice() {
1152 if let ast::StmtKind::Expr(ref expr) = stmt.kind {
1153 if !Self::is_expr_delims_necessary(expr, followed_by_block, false)
1154 && (ctx != UnusedDelimsCtx::AnonConst
1155 || (matches!(expr.kind, ast::ExprKind::Lit(_))
1156 && !expr.span.from_expansion()))
1157 && !cx.sess().source_map().is_multiline(value.span)
1158 && value.attrs.is_empty()
1159 && !value.span.from_expansion()
1160 && !inner.span.from_expansion()
1162 self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
1167 ast::ExprKind::Let(_, ref expr, _) => {
1168 self.check_unused_delims_expr(
1171 UnusedDelimsCtx::LetScrutineeExpr,
1182 impl EarlyLintPass for UnusedBraces {
1183 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
1184 <Self as UnusedDelimLint>::check_stmt(self, cx, s)
1188 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
1189 <Self as UnusedDelimLint>::check_expr(self, cx, e);
1191 if let ExprKind::Repeat(_, ref anon_const) = e.kind {
1192 self.check_unused_delims_expr(
1195 UnusedDelimsCtx::AnonConst,
1203 fn check_generic_arg(&mut self, cx: &EarlyContext<'_>, arg: &ast::GenericArg) {
1204 if let ast::GenericArg::Const(ct) = arg {
1205 self.check_unused_delims_expr(
1208 UnusedDelimsCtx::AnonConst,
1216 fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant) {
1217 if let Some(anon_const) = &v.disr_expr {
1218 self.check_unused_delims_expr(
1221 UnusedDelimsCtx::AnonConst,
1229 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
1231 ast::TyKind::Array(_, ref len) => {
1232 self.check_unused_delims_expr(
1235 UnusedDelimsCtx::ArrayLenExpr,
1242 ast::TyKind::Typeof(ref anon_const) => {
1243 self.check_unused_delims_expr(
1246 UnusedDelimsCtx::AnonConst,
1257 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1258 <Self as UnusedDelimLint>::check_item(self, cx, item)
1263 /// The `unused_import_braces` lint catches unnecessary braces around an
1268 /// ```rust,compile_fail
1269 /// #![deny(unused_import_braces)]
1282 /// If there is only a single item, then remove the braces (`use test::A;`
1285 /// This lint is "allow" by default because it is only enforcing a
1286 /// stylistic choice.
1287 UNUSED_IMPORT_BRACES,
1289 "unnecessary braces around an imported item"
1292 declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]);
1294 impl UnusedImportBraces {
1295 fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
1296 if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
1297 // Recursively check nested UseTrees
1298 for (tree, _) in items {
1299 self.check_use_tree(cx, tree, item);
1302 // Trigger the lint only if there is one nested item
1303 if items.len() != 1 {
1307 // Trigger the lint if the nested item is a non-self single item
1308 let node_name = match items[0].0.kind {
1309 ast::UseTreeKind::Simple(rename) => {
1310 let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
1311 if orig_ident.name == kw::SelfLower {
1314 rename.unwrap_or(orig_ident).name
1316 ast::UseTreeKind::Glob => Symbol::intern("*"),
1317 ast::UseTreeKind::Nested(_) => return,
1320 cx.emit_spanned_lint(
1321 UNUSED_IMPORT_BRACES,
1323 UnusedImportBracesDiag { node: node_name },
1329 impl EarlyLintPass for UnusedImportBraces {
1330 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1331 if let ast::ItemKind::Use(ref use_tree) = item.kind {
1332 self.check_use_tree(cx, use_tree, item);
1338 /// The `unused_allocation` lint detects unnecessary allocations that can
1344 /// #![feature(box_syntax)]
1346 /// let a = (box [1, 2, 3]).len();
1354 /// When a `box` expression is immediately coerced to a reference, then
1355 /// the allocation is unnecessary, and a reference (using `&` or `&mut`)
1356 /// should be used instead to avoid the allocation.
1357 pub(super) UNUSED_ALLOCATION,
1359 "detects unnecessary allocations that can be eliminated"
1362 declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]);
1364 impl<'tcx> LateLintPass<'tcx> for UnusedAllocation {
1365 fn check_expr(&mut self, cx: &LateContext<'_>, e: &hir::Expr<'_>) {
1367 hir::ExprKind::Box(_) => {}
1371 for adj in cx.typeck_results().expr_adjustments(e) {
1372 if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
1374 adjustment::AutoBorrowMutability::Not => {
1375 cx.emit_spanned_lint(UNUSED_ALLOCATION, e.span, UnusedAllocationDiag);
1377 adjustment::AutoBorrowMutability::Mut { .. } => {
1378 cx.emit_spanned_lint(UNUSED_ALLOCATION, e.span, UnusedAllocationMutDiag);