1 #![deny(rustc::untranslatable_diagnostic)]
2 #![deny(rustc::diagnostic_outside_of_impl)]
4 PathStatementDrop, PathStatementDropSub, PathStatementNoEffect, UnusedAllocationDiag,
5 UnusedAllocationMutDiag, UnusedClosure, UnusedDef, UnusedDelim, UnusedDelimSuggestion,
6 UnusedGenerator, UnusedImportBracesDiag, UnusedOp, UnusedResult,
9 use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
11 use rustc_ast::util::{classify, parser};
12 use rustc_ast::{ExprKind, StmtKind};
13 use rustc_errors::{pluralize, MultiSpan};
15 use rustc_hir::def::{DefKind, Res};
16 use rustc_hir::def_id::DefId;
17 use rustc_infer::traits::util::elaborate_predicates_with_span;
18 use rustc_middle::ty::adjustment;
19 use rustc_middle::ty::{self, DefIdTree, Ty};
20 use rustc_span::symbol::Symbol;
21 use rustc_span::symbol::{kw, sym};
22 use rustc_span::{BytePos, Span};
26 /// The `unused_must_use` lint detects unused result of a type flagged as
32 /// fn returns_result() -> Result<(), ()> {
45 /// The `#[must_use]` attribute is an indicator that it is a mistake to
46 /// ignore the value. See [the reference] for more details.
48 /// [the reference]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
51 "unused result of a type flagged as `#[must_use]`",
52 report_in_external_macro
56 /// The `unused_results` lint checks for the unused result of an
57 /// expression in a statement.
61 /// ```rust,compile_fail
62 /// #![deny(unused_results)]
63 /// fn foo<T>() -> T { panic!() }
74 /// Ignoring the return value of a function may indicate a mistake. In
75 /// cases were it is almost certain that the result should be used, it is
76 /// recommended to annotate the function with the [`must_use` attribute].
77 /// Failure to use such a return value will trigger the [`unused_must_use`
78 /// lint] which is warn-by-default. The `unused_results` lint is
79 /// essentially the same, but triggers for *all* return values.
81 /// This lint is "allow" by default because it can be noisy, and may not be
82 /// an actual problem. For example, calling the `remove` method of a `Vec`
83 /// or `HashMap` returns the previous value, which you may not care about.
84 /// Using this lint would require explicitly ignoring or discarding such
87 /// [`must_use` attribute]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
88 /// [`unused_must_use` lint]: warn-by-default.html#unused-must-use
91 "unused result of an expression in a statement"
94 declare_lint_pass!(UnusedResults => [UNUSED_MUST_USE, UNUSED_RESULTS]);
96 impl<'tcx> LateLintPass<'tcx> for UnusedResults {
97 fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
98 let hir::StmtKind::Semi(expr) = s.kind else { return; };
100 if let hir::ExprKind::Ret(..) = expr.kind {
104 if let hir::ExprKind::Match(await_expr, _arms, hir::MatchSource::AwaitDesugar) = expr.kind
105 && let ty = cx.typeck_results().expr_ty(&await_expr)
106 && let ty::Alias(ty::Opaque, ty::AliasTy { def_id: future_def_id, .. }) = ty.kind()
107 && cx.tcx.ty_is_opaque_future(ty)
108 // FIXME: This also includes non-async fns that return `impl Future`.
109 && let async_fn_def_id = cx.tcx.parent(*future_def_id)
110 && check_must_use_def(
114 "output of future returned by ",
118 // We have a bare `foo().await;` on an opaque type from an async function that was
119 // annotated with `#[must_use]`.
123 let ty = cx.typeck_results().expr_ty(&expr);
125 let must_use_result = is_ty_must_use(cx, ty, &expr, expr.span);
126 let type_lint_emitted_or_suppressed = match must_use_result {
128 emit_must_use_untranslated(cx, &path, "", "", 1);
134 let fn_warned = check_fn_must_use(cx, expr);
136 if !fn_warned && type_lint_emitted_or_suppressed {
137 // We don't warn about unused unit or uninhabited types.
138 // (See https://github.com/rust-lang/rust/issues/43806 for details.)
142 let must_use_op = match expr.kind {
143 // Hardcoding operators here seemed more expedient than the
144 // refactoring that would be needed to look up the `#[must_use]`
145 // attribute which does exist on the comparison trait methods
146 hir::ExprKind::Binary(bin_op, ..) => match bin_op.node {
152 | hir::BinOpKind::Gt => Some("comparison"),
154 | hir::BinOpKind::Sub
155 | hir::BinOpKind::Div
156 | hir::BinOpKind::Mul
157 | hir::BinOpKind::Rem => Some("arithmetic operation"),
158 hir::BinOpKind::And | hir::BinOpKind::Or => Some("logical operation"),
159 hir::BinOpKind::BitXor
160 | hir::BinOpKind::BitAnd
161 | hir::BinOpKind::BitOr
162 | hir::BinOpKind::Shl
163 | hir::BinOpKind::Shr => Some("bitwise operation"),
165 hir::ExprKind::AddrOf(..) => Some("borrow"),
166 hir::ExprKind::Unary(..) => Some("unary operation"),
170 let mut op_warned = false;
172 if let Some(must_use_op) = must_use_op {
173 cx.emit_spanned_lint(
179 suggestion: expr.span.shrink_to_lo(),
185 if !(type_lint_emitted_or_suppressed || fn_warned || op_warned) {
186 cx.emit_spanned_lint(UNUSED_RESULTS, s.span, UnusedResult { ty });
189 fn check_fn_must_use(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool {
190 let maybe_def_id = match expr.kind {
191 hir::ExprKind::Call(ref callee, _) => {
193 hir::ExprKind::Path(ref qpath) => {
194 match cx.qpath_res(qpath, callee.hir_id) {
195 Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) => Some(def_id),
196 // `Res::Local` if it was a closure, for which we
197 // do not currently support must-use linting
204 hir::ExprKind::MethodCall(..) => {
205 cx.typeck_results().type_dependent_def_id(expr.hir_id)
209 if let Some(def_id) = maybe_def_id {
210 check_must_use_def(cx, def_id, expr.span, "return value of ", "")
216 /// A path through a type to a must_use source. Contains useful info for the lint.
219 /// Suppress must_use checking.
221 /// The root of the normal must_use lint with an optional message.
222 Def(Span, DefId, Option<Symbol>),
225 TraitObject(Box<Self>),
226 TupleElement(Vec<(usize, Self)>),
227 Array(Box<Self>, u64),
228 /// The root of the unused_closures lint.
230 /// The root of the unused_generators lint.
234 #[instrument(skip(cx, expr), level = "debug", ret)]
235 fn is_ty_must_use<'tcx>(
236 cx: &LateContext<'tcx>,
238 expr: &hir::Expr<'_>,
240 ) -> Option<MustUsePath> {
242 || !ty.is_inhabited_from(
244 cx.tcx.parent_module(expr.hir_id).to_def_id(),
248 return Some(MustUsePath::Suppressed);
252 ty::Adt(..) if ty.is_box() => {
253 let boxed_ty = ty.boxed_ty();
254 is_ty_must_use(cx, boxed_ty, expr, span)
255 .map(|inner| MustUsePath::Boxed(Box::new(inner)))
257 ty::Adt(def, _) => is_def_must_use(cx, def.did(), span),
258 ty::Alias(ty::Opaque, ty::AliasTy { def_id: def, .. }) => {
259 elaborate_predicates_with_span(
261 cx.tcx.explicit_item_bounds(def).iter().cloned(),
263 .find_map(|obligation| {
264 // We only look at the `DefId`, so it is safe to skip the binder here.
265 if let ty::PredicateKind::Clause(ty::Clause::Trait(
266 ref poly_trait_predicate,
267 )) = obligation.predicate.kind().skip_binder()
269 let def_id = poly_trait_predicate.trait_ref.def_id;
271 is_def_must_use(cx, def_id, span)
276 .map(|inner| MustUsePath::Opaque(Box::new(inner)))
278 ty::Dynamic(binders, _, _) => binders.iter().find_map(|predicate| {
279 if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder()
281 let def_id = trait_ref.def_id;
282 is_def_must_use(cx, def_id, span)
283 .map(|inner| MustUsePath::TraitObject(Box::new(inner)))
289 let elem_exprs = if let hir::ExprKind::Tup(elem_exprs) = expr.kind {
290 debug_assert_eq!(elem_exprs.len(), tys.len());
296 // Default to `expr`.
297 let elem_exprs = elem_exprs.iter().chain(iter::repeat(expr));
299 let nested_must_use = tys
303 .filter_map(|(i, (ty, expr))| {
304 is_ty_must_use(cx, ty, expr, expr.span).map(|path| (i, path))
306 .collect::<Vec<_>>();
308 if !nested_must_use.is_empty() {
309 Some(MustUsePath::TupleElement(nested_must_use))
314 ty::Array(ty, len) => match len.try_eval_usize(cx.tcx, cx.param_env) {
315 // If the array is empty we don't lint, to avoid false positives
316 Some(0) | None => None,
317 // If the array is definitely non-empty, we can do `#[must_use]` checking.
318 Some(len) => is_ty_must_use(cx, ty, expr, span)
319 .map(|inner| MustUsePath::Array(Box::new(inner), len)),
321 ty::Closure(..) => Some(MustUsePath::Closure(span)),
322 ty::Generator(def_id, ..) => {
323 // async fn should be treated as "implementor of `Future`"
324 let must_use = if cx.tcx.generator_is_async(def_id) {
325 let def_id = cx.tcx.lang_items().future_trait().unwrap();
326 is_def_must_use(cx, def_id, span)
327 .map(|inner| MustUsePath::Opaque(Box::new(inner)))
331 must_use.or(Some(MustUsePath::Generator(span)))
337 fn is_def_must_use(cx: &LateContext<'_>, def_id: DefId, span: Span) -> Option<MustUsePath> {
338 if let Some(attr) = cx.tcx.get_attr(def_id, sym::must_use) {
339 // check for #[must_use = "..."]
340 let reason = attr.value_str();
341 Some(MustUsePath::Def(span, def_id, reason))
347 // Returns whether further errors should be suppressed because either a lint has been emitted or the type should be ignored.
348 fn check_must_use_def(
349 cx: &LateContext<'_>,
352 descr_pre_path: &str,
353 descr_post_path: &str,
355 is_def_must_use(cx, def_id, span)
356 .map(|must_use_path| {
357 emit_must_use_untranslated(
368 #[instrument(skip(cx), level = "debug")]
369 fn emit_must_use_untranslated(
370 cx: &LateContext<'_>,
376 let plural_suffix = pluralize!(plural_len);
379 MustUsePath::Suppressed => {}
380 MustUsePath::Boxed(path) => {
381 let descr_pre = &format!("{}boxed ", descr_pre);
382 emit_must_use_untranslated(cx, path, descr_pre, descr_post, plural_len);
384 MustUsePath::Opaque(path) => {
385 let descr_pre = &format!("{}implementer{} of ", descr_pre, plural_suffix);
386 emit_must_use_untranslated(cx, path, descr_pre, descr_post, plural_len);
388 MustUsePath::TraitObject(path) => {
389 let descr_post = &format!(" trait object{}{}", plural_suffix, descr_post);
390 emit_must_use_untranslated(cx, path, descr_pre, descr_post, plural_len);
392 MustUsePath::TupleElement(elems) => {
393 for (index, path) in elems {
394 let descr_post = &format!(" in tuple element {}", index);
395 emit_must_use_untranslated(cx, path, descr_pre, descr_post, plural_len);
398 MustUsePath::Array(path, len) => {
399 let descr_pre = &format!("{}array{} of ", descr_pre, plural_suffix);
400 emit_must_use_untranslated(
405 plural_len.saturating_add(usize::try_from(*len).unwrap_or(usize::MAX)),
408 MustUsePath::Closure(span) => {
409 cx.emit_spanned_lint(
412 UnusedClosure { count: plural_len, pre: descr_pre, post: descr_post },
415 MustUsePath::Generator(span) => {
416 cx.emit_spanned_lint(
419 UnusedGenerator { count: plural_len, pre: descr_pre, post: descr_post },
422 MustUsePath::Def(span, def_id, reason) => {
423 cx.emit_spanned_lint(
441 /// The `path_statements` lint detects path statements with no effect.
455 /// It is usually a mistake to have a statement that has no effect.
458 "path statements with no effect"
461 declare_lint_pass!(PathStatements => [PATH_STATEMENTS]);
463 impl<'tcx> LateLintPass<'tcx> for PathStatements {
464 fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
465 if let hir::StmtKind::Semi(expr) = s.kind {
466 if let hir::ExprKind::Path(_) = expr.kind {
467 let ty = cx.typeck_results().expr_ty(expr);
468 if ty.needs_drop(cx.tcx, cx.param_env) {
469 let sub = if let Ok(snippet) = cx.sess().source_map().span_to_snippet(expr.span)
471 PathStatementDropSub::Suggestion { span: s.span, snippet }
473 PathStatementDropSub::Help { span: s.span }
475 cx.emit_spanned_lint(PATH_STATEMENTS, s.span, PathStatementDrop { sub })
477 cx.emit_spanned_lint(PATH_STATEMENTS, s.span, PathStatementNoEffect);
484 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
485 enum UnusedDelimsCtx {
489 AssignedValueLetElse,
502 impl From<UnusedDelimsCtx> for &'static str {
503 fn from(ctx: UnusedDelimsCtx) -> &'static str {
505 UnusedDelimsCtx::FunctionArg => "function argument",
506 UnusedDelimsCtx::MethodArg => "method argument",
507 UnusedDelimsCtx::AssignedValue | UnusedDelimsCtx::AssignedValueLetElse => {
510 UnusedDelimsCtx::IfCond => "`if` condition",
511 UnusedDelimsCtx::WhileCond => "`while` condition",
512 UnusedDelimsCtx::ForIterExpr => "`for` iterator expression",
513 UnusedDelimsCtx::MatchScrutineeExpr => "`match` scrutinee expression",
514 UnusedDelimsCtx::ReturnValue => "`return` value",
515 UnusedDelimsCtx::BlockRetValue => "block return value",
516 UnusedDelimsCtx::LetScrutineeExpr => "`let` scrutinee expression",
517 UnusedDelimsCtx::ArrayLenExpr | UnusedDelimsCtx::AnonConst => "const expression",
518 UnusedDelimsCtx::MatchArmExpr => "match arm expression",
523 /// Used by both `UnusedParens` and `UnusedBraces` to prevent code duplication.
524 trait UnusedDelimLint {
525 const DELIM_STR: &'static str;
527 /// Due to `ref` pattern, there can be a difference between using
528 /// `{ expr }` and `expr` in pattern-matching contexts. This means
529 /// that we should only lint `unused_parens` and not `unused_braces`
534 /// let ref b = { a }; // We actually borrow a copy of `a` here.
535 /// a += 1; // By mutating `a` we invalidate any borrows of `a`.
536 /// assert_eq!(b + 1, a); // `b` does not borrow `a`, so we can still use it here.
538 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool;
540 // this cannot be a constant is it refers to a static.
541 fn lint(&self) -> &'static Lint;
543 fn check_unused_delims_expr(
545 cx: &EarlyContext<'_>,
547 ctx: UnusedDelimsCtx,
548 followed_by_block: bool,
549 left_pos: Option<BytePos>,
550 right_pos: Option<BytePos>,
553 fn is_expr_delims_necessary(
555 followed_by_block: bool,
556 followed_by_else: bool,
558 if followed_by_else {
560 ast::ExprKind::Binary(op, ..) if op.node.lazy() => return true,
561 _ if classify::expr_trailing_brace(inner).is_some() => return true,
566 // Prevent false-positives in cases like `fn x() -> u8 { ({ 0 } + 1) }`
567 let lhs_needs_parens = {
568 let mut innermost = inner;
570 innermost = match &innermost.kind {
571 ExprKind::Binary(_, lhs, _rhs) => lhs,
572 ExprKind::Call(fn_, _params) => fn_,
573 ExprKind::Cast(expr, _ty) => expr,
574 ExprKind::Type(expr, _ty) => expr,
575 ExprKind::Index(base, _subscript) => base,
578 if !classify::expr_requires_semi_to_be_stmt(innermost) {
585 || (followed_by_block
586 && match &inner.kind {
588 | ExprKind::Break(..)
589 | ExprKind::Yield(..)
590 | ExprKind::Yeet(..) => true,
591 ExprKind::Range(_lhs, Some(rhs), _limits) => {
592 matches!(rhs.kind, ExprKind::Block(..))
594 _ => parser::contains_exterior_struct_lit(&inner),
598 fn emit_unused_delims_expr(
600 cx: &EarlyContext<'_>,
602 ctx: UnusedDelimsCtx,
603 left_pos: Option<BytePos>,
604 right_pos: Option<BytePos>,
606 // If `value` has `ExprKind::Err`, unused delim lint can be broken.
607 // For example, the following code caused ICE.
608 // This is because the `ExprKind::Call` in `value` has `ExprKind::Err` as its argument
609 // and this leads to wrong spans. #104897
614 use rustc_ast::visit::{walk_expr, Visitor};
615 struct ErrExprVisitor {
618 impl<'ast> Visitor<'ast> for ErrExprVisitor {
619 fn visit_expr(&mut self, expr: &'ast ast::Expr) {
620 if let ExprKind::Err = expr.kind {
621 self.has_error = true;
624 walk_expr(self, expr)
627 let mut visitor = ErrExprVisitor { has_error: false };
628 visitor.visit_expr(value);
629 if visitor.has_error {
632 let spans = match value.kind {
633 ast::ExprKind::Block(ref block, None) if block.stmts.len() == 1 => {
634 if let Some(span) = block.stmts[0].span.find_ancestor_inside(value.span) {
635 Some((value.span.with_hi(span.lo()), value.span.with_lo(span.hi())))
640 ast::ExprKind::Paren(ref expr) => {
641 let expr_span = expr.span.find_ancestor_inside(value.span);
642 if let Some(expr_span) = expr_span {
643 Some((value.span.with_hi(expr_span.lo()), value.span.with_lo(expr_span.hi())))
651 left_pos.map_or(false, |s| s >= value.span.lo()),
652 right_pos.map_or(false, |s| s <= value.span.hi()),
654 self.emit_unused_delims(cx, value.span, spans, ctx.into(), keep_space);
657 fn emit_unused_delims(
659 cx: &EarlyContext<'_>,
661 spans: Option<(Span, Span)>,
663 keep_space: (bool, bool),
665 let primary_span = if let Some((lo, hi)) = spans {
666 MultiSpan::from(vec![lo, hi])
668 MultiSpan::from(value_span)
670 let suggestion = spans.map(|(lo, hi)| {
671 let sm = cx.sess().source_map();
674 let Ok(snip) = sm.span_to_prev_source(lo) && !snip.ends_with(' ') {
682 let Ok(snip) = sm.span_to_next_source(hi) && !snip.starts_with(' ') {
687 UnusedDelimSuggestion {
689 start_replace: lo_replace,
691 end_replace: hi_replace,
694 cx.emit_spanned_lint(
697 UnusedDelim { delim: Self::DELIM_STR, item: msg, suggestion },
701 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
702 use rustc_ast::ExprKind::*;
703 let (value, ctx, followed_by_block, left_pos, right_pos) = match e.kind {
704 // Do not lint `unused_braces` in `if let` expressions.
705 If(ref cond, ref block, _)
706 if !matches!(cond.kind, Let(_, _, _))
707 || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
709 let left = e.span.lo() + rustc_span::BytePos(2);
710 let right = block.span.lo();
711 (cond, UnusedDelimsCtx::IfCond, true, Some(left), Some(right))
714 // Do not lint `unused_braces` in `while let` expressions.
715 While(ref cond, ref block, ..)
716 if !matches!(cond.kind, Let(_, _, _))
717 || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
719 let left = e.span.lo() + rustc_span::BytePos(5);
720 let right = block.span.lo();
721 (cond, UnusedDelimsCtx::WhileCond, true, Some(left), Some(right))
724 ForLoop(_, ref cond, ref block, ..) => {
725 (cond, UnusedDelimsCtx::ForIterExpr, true, None, Some(block.span.lo()))
728 Match(ref head, _) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
729 let left = e.span.lo() + rustc_span::BytePos(5);
730 (head, UnusedDelimsCtx::MatchScrutineeExpr, true, Some(left), None)
733 Ret(Some(ref value)) => {
734 let left = e.span.lo() + rustc_span::BytePos(3);
735 (value, UnusedDelimsCtx::ReturnValue, false, Some(left), None)
738 Assign(_, ref value, _) | AssignOp(.., ref value) => {
739 (value, UnusedDelimsCtx::AssignedValue, false, None, None)
741 // either function/method call, or something this lint doesn't care about
742 ref call_or_other => {
743 let (args_to_check, ctx) = match *call_or_other {
744 Call(_, ref args) => (&args[..], UnusedDelimsCtx::FunctionArg),
745 MethodCall(ref call) => (&call.args[..], UnusedDelimsCtx::MethodArg),
746 // actual catch-all arm
751 // Don't lint if this is a nested macro expansion: otherwise, the lint could
752 // trigger in situations that macro authors shouldn't have to care about, e.g.,
753 // when a parenthesized token tree matched in one macro expansion is matched as
754 // an expression in another and used as a fn/method argument (Issue #47775)
755 if e.span.ctxt().outer_expn_data().call_site.from_expansion() {
758 for arg in args_to_check {
759 self.check_unused_delims_expr(cx, arg, ctx, false, None, None);
764 self.check_unused_delims_expr(cx, &value, ctx, followed_by_block, left_pos, right_pos);
767 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
769 StmtKind::Local(ref local) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
770 if let Some((init, els)) = local.kind.init_else_opt() {
771 let ctx = match els {
772 None => UnusedDelimsCtx::AssignedValue,
773 Some(_) => UnusedDelimsCtx::AssignedValueLetElse,
775 self.check_unused_delims_expr(cx, init, ctx, false, None, None);
778 StmtKind::Expr(ref expr) => {
779 self.check_unused_delims_expr(
782 UnusedDelimsCtx::BlockRetValue,
792 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
793 use ast::ItemKind::*;
795 if let Const(.., Some(expr)) | Static(.., Some(expr)) = &item.kind {
796 self.check_unused_delims_expr(
799 UnusedDelimsCtx::AssignedValue,
809 /// The `unused_parens` lint detects `if`, `match`, `while` and `return`
810 /// with parentheses; they do not need them.
822 /// The parentheses are not needed, and should be removed. This is the
823 /// preferred style for writing these expressions.
824 pub(super) UNUSED_PARENS,
826 "`if`, `match`, `while` and `return` do not need parentheses"
829 declare_lint_pass!(UnusedParens => [UNUSED_PARENS]);
831 impl UnusedDelimLint for UnusedParens {
832 const DELIM_STR: &'static str = "parentheses";
834 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = true;
836 fn lint(&self) -> &'static Lint {
840 fn check_unused_delims_expr(
842 cx: &EarlyContext<'_>,
844 ctx: UnusedDelimsCtx,
845 followed_by_block: bool,
846 left_pos: Option<BytePos>,
847 right_pos: Option<BytePos>,
850 ast::ExprKind::Paren(ref inner) => {
851 let followed_by_else = ctx == UnusedDelimsCtx::AssignedValueLetElse;
852 if !Self::is_expr_delims_necessary(inner, followed_by_block, followed_by_else)
853 && value.attrs.is_empty()
854 && !value.span.from_expansion()
855 && (ctx != UnusedDelimsCtx::LetScrutineeExpr
856 || !matches!(inner.kind, ast::ExprKind::Binary(
857 rustc_span::source_map::Spanned { node, .. },
862 self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
865 ast::ExprKind::Let(_, ref expr, _) => {
866 self.check_unused_delims_expr(
869 UnusedDelimsCtx::LetScrutineeExpr,
881 fn check_unused_parens_pat(
883 cx: &EarlyContext<'_>,
887 keep_space: (bool, bool),
889 use ast::{BindingAnnotation, PatKind};
891 if let PatKind::Paren(inner) = &value.kind {
893 // The lint visitor will visit each subpattern of `p`. We do not want to lint
894 // any range pattern no matter where it occurs in the pattern. For something like
895 // `&(a..=b)`, there is a recursive `check_pat` on `a` and `b`, but we will assume
896 // that if there are unnecessary parens they serve a purpose of readability.
897 PatKind::Range(..) => return,
898 // Avoid `p0 | .. | pn` if we should.
899 PatKind::Or(..) if avoid_or => return,
900 // Avoid `mut x` and `mut x @ p` if we should:
901 PatKind::Ident(BindingAnnotation::MUT, ..) if avoid_mut => {
904 // Otherwise proceed with linting.
907 let spans = if let Some(inner) = inner.span.find_ancestor_inside(value.span) {
908 Some((value.span.with_hi(inner.lo()), value.span.with_lo(inner.hi())))
912 self.emit_unused_delims(cx, value.span, spans, "pattern", keep_space);
917 impl EarlyLintPass for UnusedParens {
919 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
921 ExprKind::Let(ref pat, _, _) | ExprKind::ForLoop(ref pat, ..) => {
922 self.check_unused_parens_pat(cx, pat, false, false, (true, true));
924 // We ignore parens in cases like `if (((let Some(0) = Some(1))))` because we already
925 // handle a hard error for them during AST lowering in `lower_expr_mut`, but we still
926 // want to complain about things like `if let 42 = (42)`.
927 ExprKind::If(ref cond, ref block, ref else_)
928 if matches!(cond.peel_parens().kind, ExprKind::Let(..)) =>
930 self.check_unused_delims_expr(
933 UnusedDelimsCtx::LetScrutineeExpr,
938 for stmt in &block.stmts {
939 <Self as UnusedDelimLint>::check_stmt(self, cx, stmt);
941 if let Some(e) = else_ {
942 <Self as UnusedDelimLint>::check_expr(self, cx, e);
946 ExprKind::Match(ref _expr, ref arm) => {
948 self.check_unused_delims_expr(
951 UnusedDelimsCtx::MatchArmExpr,
961 <Self as UnusedDelimLint>::check_expr(self, cx, e)
964 fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
965 use ast::{Mutability, PatKind::*};
966 let keep_space = (false, false);
968 // Do not lint on `(..)` as that will result in the other arms being useless.
970 // The other cases do not contain sub-patterns.
971 | Wild | Rest | Lit(..) | MacCall(..) | Range(..) | Ident(.., None) | Path(..) => {},
972 // These are list-like patterns; parens can always be removed.
973 TupleStruct(_, _, ps) | Tuple(ps) | Slice(ps) | Or(ps) => for p in ps {
974 self.check_unused_parens_pat(cx, p, false, false, keep_space);
976 Struct(_, _, fps, _) => for f in fps {
977 self.check_unused_parens_pat(cx, &f.pat, false, false, keep_space);
979 // Avoid linting on `i @ (p0 | .. | pn)` and `box (p0 | .. | pn)`, #64106.
980 Ident(.., Some(p)) | Box(p) => self.check_unused_parens_pat(cx, p, true, false, keep_space),
981 // Avoid linting on `&(mut x)` as `&mut x` has a different meaning, #55342.
982 // Also avoid linting on `& mut? (p0 | .. | pn)`, #64106.
983 Ref(p, m) => self.check_unused_parens_pat(cx, p, true, *m == Mutability::Not, keep_space),
987 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
988 if let StmtKind::Local(ref local) = s.kind {
989 self.check_unused_parens_pat(cx, &local.pat, true, false, (false, false));
992 <Self as UnusedDelimLint>::check_stmt(self, cx, s)
995 fn check_param(&mut self, cx: &EarlyContext<'_>, param: &ast::Param) {
996 self.check_unused_parens_pat(cx, ¶m.pat, true, false, (false, false));
999 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
1000 self.check_unused_parens_pat(cx, &arm.pat, false, false, (false, false));
1003 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
1004 if let ast::TyKind::Paren(r) = &ty.kind {
1006 ast::TyKind::TraitObject(..) => {}
1007 ast::TyKind::BareFn(b) if b.generic_params.len() > 0 => {}
1008 ast::TyKind::ImplTrait(_, bounds) if bounds.len() > 1 => {}
1009 ast::TyKind::Array(_, len) => {
1010 self.check_unused_delims_expr(
1013 UnusedDelimsCtx::ArrayLenExpr,
1020 let spans = if let Some(r) = r.span.find_ancestor_inside(ty.span) {
1021 Some((ty.span.with_hi(r.lo()), ty.span.with_lo(r.hi())))
1025 self.emit_unused_delims(cx, ty.span, spans, "type", (false, false));
1031 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1032 <Self as UnusedDelimLint>::check_item(self, cx, item)
1037 /// The `unused_braces` lint detects unnecessary braces around an
1052 /// The braces are not needed, and should be removed. This is the
1053 /// preferred style for writing these expressions.
1054 pub(super) UNUSED_BRACES,
1056 "unnecessary braces around an expression"
1059 declare_lint_pass!(UnusedBraces => [UNUSED_BRACES]);
1061 impl UnusedDelimLint for UnusedBraces {
1062 const DELIM_STR: &'static str = "braces";
1064 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = false;
1066 fn lint(&self) -> &'static Lint {
1070 fn check_unused_delims_expr(
1072 cx: &EarlyContext<'_>,
1074 ctx: UnusedDelimsCtx,
1075 followed_by_block: bool,
1076 left_pos: Option<BytePos>,
1077 right_pos: Option<BytePos>,
1080 ast::ExprKind::Block(ref inner, None)
1081 if inner.rules == ast::BlockCheckMode::Default =>
1083 // emit a warning under the following conditions:
1085 // - the block does not have a label
1086 // - the block is not `unsafe`
1087 // - the block contains exactly one expression (do not lint `{ expr; }`)
1088 // - `followed_by_block` is true and the internal expr may contain a `{`
1089 // - the block is not multiline (do not lint multiline match arms)
1093 // somewhat_long_expression
1098 // - the block has no attribute and was not created inside a macro
1099 // - if the block is an `anon_const`, the inner expr must be a literal
1100 // (do not lint `struct A<const N: usize>; let _: A<{ 2 + 3 }>;`)
1102 // FIXME(const_generics): handle paths when #67075 is fixed.
1103 if let [stmt] = inner.stmts.as_slice() {
1104 if let ast::StmtKind::Expr(ref expr) = stmt.kind {
1105 if !Self::is_expr_delims_necessary(expr, followed_by_block, false)
1106 && (ctx != UnusedDelimsCtx::AnonConst
1107 || matches!(expr.kind, ast::ExprKind::Lit(_)))
1108 && !cx.sess().source_map().is_multiline(value.span)
1109 && value.attrs.is_empty()
1110 && !value.span.from_expansion()
1111 && !inner.span.from_expansion()
1113 self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
1118 ast::ExprKind::Let(_, ref expr, _) => {
1119 self.check_unused_delims_expr(
1122 UnusedDelimsCtx::LetScrutineeExpr,
1133 impl EarlyLintPass for UnusedBraces {
1134 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
1135 <Self as UnusedDelimLint>::check_stmt(self, cx, s)
1139 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
1140 <Self as UnusedDelimLint>::check_expr(self, cx, e);
1142 if let ExprKind::Repeat(_, ref anon_const) = e.kind {
1143 self.check_unused_delims_expr(
1146 UnusedDelimsCtx::AnonConst,
1154 fn check_generic_arg(&mut self, cx: &EarlyContext<'_>, arg: &ast::GenericArg) {
1155 if let ast::GenericArg::Const(ct) = arg {
1156 self.check_unused_delims_expr(
1159 UnusedDelimsCtx::AnonConst,
1167 fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant) {
1168 if let Some(anon_const) = &v.disr_expr {
1169 self.check_unused_delims_expr(
1172 UnusedDelimsCtx::AnonConst,
1180 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
1182 ast::TyKind::Array(_, ref len) => {
1183 self.check_unused_delims_expr(
1186 UnusedDelimsCtx::ArrayLenExpr,
1193 ast::TyKind::Typeof(ref anon_const) => {
1194 self.check_unused_delims_expr(
1197 UnusedDelimsCtx::AnonConst,
1208 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1209 <Self as UnusedDelimLint>::check_item(self, cx, item)
1214 /// The `unused_import_braces` lint catches unnecessary braces around an
1219 /// ```rust,compile_fail
1220 /// #![deny(unused_import_braces)]
1233 /// If there is only a single item, then remove the braces (`use test::A;`
1236 /// This lint is "allow" by default because it is only enforcing a
1237 /// stylistic choice.
1238 UNUSED_IMPORT_BRACES,
1240 "unnecessary braces around an imported item"
1243 declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]);
1245 impl UnusedImportBraces {
1246 fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
1247 if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
1248 // Recursively check nested UseTrees
1249 for (tree, _) in items {
1250 self.check_use_tree(cx, tree, item);
1253 // Trigger the lint only if there is one nested item
1254 if items.len() != 1 {
1258 // Trigger the lint if the nested item is a non-self single item
1259 let node_name = match items[0].0.kind {
1260 ast::UseTreeKind::Simple(rename) => {
1261 let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
1262 if orig_ident.name == kw::SelfLower {
1265 rename.unwrap_or(orig_ident).name
1267 ast::UseTreeKind::Glob => Symbol::intern("*"),
1268 ast::UseTreeKind::Nested(_) => return,
1271 cx.emit_spanned_lint(
1272 UNUSED_IMPORT_BRACES,
1274 UnusedImportBracesDiag { node: node_name },
1280 impl EarlyLintPass for UnusedImportBraces {
1281 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1282 if let ast::ItemKind::Use(ref use_tree) = item.kind {
1283 self.check_use_tree(cx, use_tree, item);
1289 /// The `unused_allocation` lint detects unnecessary allocations that can
1295 /// #![feature(box_syntax)]
1297 /// let a = (box [1, 2, 3]).len();
1305 /// When a `box` expression is immediately coerced to a reference, then
1306 /// the allocation is unnecessary, and a reference (using `&` or `&mut`)
1307 /// should be used instead to avoid the allocation.
1308 pub(super) UNUSED_ALLOCATION,
1310 "detects unnecessary allocations that can be eliminated"
1313 declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]);
1315 impl<'tcx> LateLintPass<'tcx> for UnusedAllocation {
1316 fn check_expr(&mut self, cx: &LateContext<'_>, e: &hir::Expr<'_>) {
1318 hir::ExprKind::Box(_) => {}
1322 for adj in cx.typeck_results().expr_adjustments(e) {
1323 if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
1325 adjustment::AutoBorrowMutability::Not => {
1326 cx.emit_spanned_lint(UNUSED_ALLOCATION, e.span, UnusedAllocationDiag);
1328 adjustment::AutoBorrowMutability::Mut { .. } => {
1329 cx.emit_spanned_lint(UNUSED_ALLOCATION, e.span, UnusedAllocationMutDiag);