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, DefIdTree, Ty};
13 use rustc_span::symbol::Symbol;
14 use rustc_span::symbol::{kw, sym};
15 use rustc_span::{BytePos, Span};
19 /// The `unused_must_use` lint detects unused result of a type flagged as
25 /// fn returns_result() -> Result<(), ()> {
38 /// The `#[must_use]` attribute is an indicator that it is a mistake to
39 /// ignore the value. See [the reference] for more details.
41 /// [the reference]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
44 "unused result of a type flagged as `#[must_use]`",
45 report_in_external_macro
49 /// The `unused_results` lint checks for the unused result of an
50 /// expression in a statement.
54 /// ```rust,compile_fail
55 /// #![deny(unused_results)]
56 /// fn foo<T>() -> T { panic!() }
67 /// Ignoring the return value of a function may indicate a mistake. In
68 /// cases were it is almost certain that the result should be used, it is
69 /// recommended to annotate the function with the [`must_use` attribute].
70 /// Failure to use such a return value will trigger the [`unused_must_use`
71 /// lint] which is warn-by-default. The `unused_results` lint is
72 /// essentially the same, but triggers for *all* return values.
74 /// This lint is "allow" by default because it can be noisy, and may not be
75 /// an actual problem. For example, calling the `remove` method of a `Vec`
76 /// or `HashMap` returns the previous value, which you may not care about.
77 /// Using this lint would require explicitly ignoring or discarding such
80 /// [`must_use` attribute]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
81 /// [`unused_must_use` lint]: warn-by-default.html#unused-must-use
84 "unused result of an expression in a statement"
87 declare_lint_pass!(UnusedResults => [UNUSED_MUST_USE, UNUSED_RESULTS]);
89 impl<'tcx> LateLintPass<'tcx> for UnusedResults {
90 fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
91 let hir::StmtKind::Semi(expr) = s.kind else { return; };
93 if let hir::ExprKind::Ret(..) = expr.kind {
97 if let hir::ExprKind::Match(await_expr, _arms, hir::MatchSource::AwaitDesugar) = expr.kind
98 && let ty = cx.typeck_results().expr_ty(&await_expr)
99 && let ty::Opaque(future_def_id, _) = ty.kind()
100 && cx.tcx.ty_is_opaque_future(ty)
101 // FIXME: This also includes non-async fns that return `impl Future`.
102 && let async_fn_def_id = cx.tcx.parent(*future_def_id)
103 && check_must_use_def(
107 "output of future returned by ",
111 // We have a bare `foo().await;` on an opaque type from an async function that was
112 // annotated with `#[must_use]`.
116 let ty = cx.typeck_results().expr_ty(&expr);
118 let must_use_result = is_ty_must_use(cx, ty, &expr, expr.span);
119 let type_lint_emitted_or_suppressed = match must_use_result {
121 emit_must_use_untranslated(cx, &path, "", "", 1);
127 let fn_warned = check_fn_must_use(cx, expr);
129 if !fn_warned && type_lint_emitted_or_suppressed {
130 // We don't warn about unused unit or uninhabited types.
131 // (See https://github.com/rust-lang/rust/issues/43806 for details.)
135 let must_use_op = match expr.kind {
136 // Hardcoding operators here seemed more expedient than the
137 // refactoring that would be needed to look up the `#[must_use]`
138 // attribute which does exist on the comparison trait methods
139 hir::ExprKind::Binary(bin_op, ..) => match bin_op.node {
145 | hir::BinOpKind::Gt => Some("comparison"),
147 | hir::BinOpKind::Sub
148 | hir::BinOpKind::Div
149 | hir::BinOpKind::Mul
150 | hir::BinOpKind::Rem => Some("arithmetic operation"),
151 hir::BinOpKind::And | hir::BinOpKind::Or => Some("logical operation"),
152 hir::BinOpKind::BitXor
153 | hir::BinOpKind::BitAnd
154 | hir::BinOpKind::BitOr
155 | hir::BinOpKind::Shl
156 | hir::BinOpKind::Shr => Some("bitwise operation"),
158 hir::ExprKind::AddrOf(..) => Some("borrow"),
159 hir::ExprKind::Unary(..) => Some("unary operation"),
163 let mut op_warned = false;
165 if let Some(must_use_op) = must_use_op {
166 cx.struct_span_lint(UNUSED_MUST_USE, expr.span, fluent::lint_unused_op, |lint| {
167 lint.set_arg("op", must_use_op)
168 .span_label(expr.span, fluent::label)
169 .span_suggestion_verbose(
170 expr.span.shrink_to_lo(),
173 Applicability::MachineApplicable,
179 if !(type_lint_emitted_or_suppressed || fn_warned || op_warned) {
180 cx.struct_span_lint(UNUSED_RESULTS, s.span, fluent::lint_unused_result, |lint| {
181 lint.set_arg("ty", ty)
185 fn check_fn_must_use(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool {
186 let maybe_def_id = match expr.kind {
187 hir::ExprKind::Call(ref callee, _) => {
189 hir::ExprKind::Path(ref qpath) => {
190 match cx.qpath_res(qpath, callee.hir_id) {
191 Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) => Some(def_id),
192 // `Res::Local` if it was a closure, for which we
193 // do not currently support must-use linting
200 hir::ExprKind::MethodCall(..) => {
201 cx.typeck_results().type_dependent_def_id(expr.hir_id)
205 if let Some(def_id) = maybe_def_id {
206 check_must_use_def(cx, def_id, expr.span, "return value of ", "")
212 /// A path through a type to a must_use source. Contains useful info for the lint.
215 /// Suppress must_use checking.
217 /// The root of the normal must_use lint with an optional message.
218 Def(Span, DefId, Option<Symbol>),
221 TraitObject(Box<Self>),
222 TupleElement(Vec<(usize, Self)>),
223 Array(Box<Self>, u64),
224 /// The root of the unused_closures lint.
226 /// The root of the unused_generators lint.
230 #[instrument(skip(cx, expr), level = "debug", ret)]
231 fn is_ty_must_use<'tcx>(
232 cx: &LateContext<'tcx>,
234 expr: &hir::Expr<'_>,
236 ) -> Option<MustUsePath> {
238 || !ty.is_inhabited_from(
240 cx.tcx.parent_module(expr.hir_id).to_def_id(),
244 return Some(MustUsePath::Suppressed);
248 ty::Adt(..) if ty.is_box() => {
249 let boxed_ty = ty.boxed_ty();
250 is_ty_must_use(cx, boxed_ty, expr, span)
251 .map(|inner| MustUsePath::Boxed(Box::new(inner)))
253 ty::Adt(def, _) => is_def_must_use(cx, def.did(), span),
254 ty::Opaque(def, _) => {
255 elaborate_predicates_with_span(
257 cx.tcx.explicit_item_bounds(def).iter().cloned(),
259 .filter_map(|obligation| {
260 // We only look at the `DefId`, so it is safe to skip the binder here.
261 if let ty::PredicateKind::Trait(ref poly_trait_predicate) =
262 obligation.predicate.kind().skip_binder()
264 let def_id = poly_trait_predicate.trait_ref.def_id;
266 is_def_must_use(cx, def_id, span)
271 .map(|inner| MustUsePath::Opaque(Box::new(inner)))
274 ty::Dynamic(binders, _, _) => binders
276 .filter_map(|predicate| {
277 if let ty::ExistentialPredicate::Trait(ref trait_ref) =
278 predicate.skip_binder()
280 let def_id = trait_ref.def_id;
281 is_def_must_use(cx, def_id, span)
285 .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(..) => Some(MustUsePath::Generator(span)),
327 fn is_def_must_use(cx: &LateContext<'_>, def_id: DefId, span: Span) -> Option<MustUsePath> {
328 if let Some(attr) = cx.tcx.get_attr(def_id, sym::must_use) {
329 // check for #[must_use = "..."]
330 let reason = attr.value_str();
331 Some(MustUsePath::Def(span, def_id, reason))
337 // Returns whether further errors should be suppressed because either a lint has been emitted or the type should be ignored.
338 fn check_must_use_def(
339 cx: &LateContext<'_>,
342 descr_pre_path: &str,
343 descr_post_path: &str,
345 is_def_must_use(cx, def_id, span)
346 .map(|must_use_path| {
347 emit_must_use_untranslated(
358 #[instrument(skip(cx), level = "debug")]
359 fn emit_must_use_untranslated(
360 cx: &LateContext<'_>,
366 let plural_suffix = pluralize!(plural_len);
369 MustUsePath::Suppressed => {}
370 MustUsePath::Boxed(path) => {
371 let descr_pre = &format!("{}boxed ", descr_pre);
372 emit_must_use_untranslated(cx, path, descr_pre, descr_post, plural_len);
374 MustUsePath::Opaque(path) => {
375 let descr_pre = &format!("{}implementer{} of ", descr_pre, plural_suffix);
376 emit_must_use_untranslated(cx, path, descr_pre, descr_post, plural_len);
378 MustUsePath::TraitObject(path) => {
379 let descr_post = &format!(" trait object{}{}", plural_suffix, descr_post);
380 emit_must_use_untranslated(cx, path, descr_pre, descr_post, plural_len);
382 MustUsePath::TupleElement(elems) => {
383 for (index, path) in elems {
384 let descr_post = &format!(" in tuple element {}", index);
385 emit_must_use_untranslated(cx, path, descr_pre, descr_post, plural_len);
388 MustUsePath::Array(path, len) => {
389 let descr_pre = &format!("{}array{} of ", descr_pre, plural_suffix);
390 emit_must_use_untranslated(
395 plural_len.saturating_add(usize::try_from(*len).unwrap_or(usize::MAX)),
398 MustUsePath::Closure(span) => {
402 fluent::lint_unused_closure,
404 // FIXME(davidtwco): this isn't properly translatable because of the
406 lint.set_arg("count", plural_len)
407 .set_arg("pre", descr_pre)
408 .set_arg("post", descr_post)
413 MustUsePath::Generator(span) => {
417 fluent::lint_unused_generator,
419 // FIXME(davidtwco): this isn't properly translatable because of the
421 lint.set_arg("count", plural_len)
422 .set_arg("pre", descr_pre)
423 .set_arg("post", descr_post)
428 MustUsePath::Def(span, def_id, reason) => {
429 cx.struct_span_lint(UNUSED_MUST_USE, *span, fluent::lint_unused_def, |lint| {
430 // FIXME(davidtwco): this isn't properly translatable because of the pre/post
432 lint.set_arg("pre", descr_pre);
433 lint.set_arg("post", descr_post);
434 lint.set_arg("def", cx.tcx.def_path_str(*def_id));
435 if let Some(note) = reason {
436 lint.note(note.as_str());
447 /// The `path_statements` lint detects path statements with no effect.
461 /// It is usually a mistake to have a statement that has no effect.
464 "path statements with no effect"
467 declare_lint_pass!(PathStatements => [PATH_STATEMENTS]);
469 impl<'tcx> LateLintPass<'tcx> for PathStatements {
470 fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
471 if let hir::StmtKind::Semi(expr) = s.kind {
472 if let hir::ExprKind::Path(_) = expr.kind {
473 let ty = cx.typeck_results().expr_ty(expr);
474 if ty.needs_drop(cx.tcx, cx.param_env) {
478 fluent::lint_path_statement_drop,
480 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(expr.span) {
481 lint.span_suggestion(
484 format!("drop({});", snippet),
485 Applicability::MachineApplicable,
488 lint.span_help(s.span, fluent::suggestion);
497 fluent::lint_path_statement_no_effect,
506 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
507 enum UnusedDelimsCtx {
511 AssignedValueLetElse,
524 impl From<UnusedDelimsCtx> for &'static str {
525 fn from(ctx: UnusedDelimsCtx) -> &'static str {
527 UnusedDelimsCtx::FunctionArg => "function argument",
528 UnusedDelimsCtx::MethodArg => "method argument",
529 UnusedDelimsCtx::AssignedValue | UnusedDelimsCtx::AssignedValueLetElse => {
532 UnusedDelimsCtx::IfCond => "`if` condition",
533 UnusedDelimsCtx::WhileCond => "`while` condition",
534 UnusedDelimsCtx::ForIterExpr => "`for` iterator expression",
535 UnusedDelimsCtx::MatchScrutineeExpr => "`match` scrutinee expression",
536 UnusedDelimsCtx::ReturnValue => "`return` value",
537 UnusedDelimsCtx::BlockRetValue => "block return value",
538 UnusedDelimsCtx::LetScrutineeExpr => "`let` scrutinee expression",
539 UnusedDelimsCtx::ArrayLenExpr | UnusedDelimsCtx::AnonConst => "const expression",
540 UnusedDelimsCtx::MatchArmExpr => "match arm expression",
545 /// Used by both `UnusedParens` and `UnusedBraces` to prevent code duplication.
546 trait UnusedDelimLint {
547 const DELIM_STR: &'static str;
549 /// Due to `ref` pattern, there can be a difference between using
550 /// `{ expr }` and `expr` in pattern-matching contexts. This means
551 /// that we should only lint `unused_parens` and not `unused_braces`
556 /// let ref b = { a }; // We actually borrow a copy of `a` here.
557 /// a += 1; // By mutating `a` we invalidate any borrows of `a`.
558 /// assert_eq!(b + 1, a); // `b` does not borrow `a`, so we can still use it here.
560 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool;
562 // this cannot be a constant is it refers to a static.
563 fn lint(&self) -> &'static Lint;
565 fn check_unused_delims_expr(
567 cx: &EarlyContext<'_>,
569 ctx: UnusedDelimsCtx,
570 followed_by_block: bool,
571 left_pos: Option<BytePos>,
572 right_pos: Option<BytePos>,
575 fn is_expr_delims_necessary(
577 followed_by_block: bool,
578 followed_by_else: bool,
580 if followed_by_else {
582 ast::ExprKind::Binary(op, ..) if op.node.lazy() => return true,
583 _ if classify::expr_trailing_brace(inner).is_some() => return true,
588 // Prevent false-positives in cases like `fn x() -> u8 { ({ 0 } + 1) }`
589 let lhs_needs_parens = {
590 let mut innermost = inner;
592 innermost = match &innermost.kind {
593 ExprKind::Binary(_, lhs, _rhs) => lhs,
594 ExprKind::Call(fn_, _params) => fn_,
595 ExprKind::Cast(expr, _ty) => expr,
596 ExprKind::Type(expr, _ty) => expr,
597 ExprKind::Index(base, _subscript) => base,
600 if !classify::expr_requires_semi_to_be_stmt(innermost) {
607 || (followed_by_block
608 && match &inner.kind {
609 ExprKind::Ret(_) | ExprKind::Break(..) | ExprKind::Yield(..) => true,
610 ExprKind::Range(_lhs, Some(rhs), _limits) => {
611 matches!(rhs.kind, ExprKind::Block(..))
613 _ => parser::contains_exterior_struct_lit(&inner),
617 fn emit_unused_delims_expr(
619 cx: &EarlyContext<'_>,
621 ctx: UnusedDelimsCtx,
622 left_pos: Option<BytePos>,
623 right_pos: Option<BytePos>,
625 let spans = match value.kind {
626 ast::ExprKind::Block(ref block, None) if block.stmts.len() == 1 => {
627 if let StmtKind::Expr(expr) = &block.stmts[0].kind
628 && let ExprKind::Err = expr.kind
632 if let Some(span) = block.stmts[0].span.find_ancestor_inside(value.span) {
633 Some((value.span.with_hi(span.lo()), value.span.with_lo(span.hi())))
638 ast::ExprKind::Paren(ref expr) => {
639 let expr_span = expr.span.find_ancestor_inside(value.span);
640 if let Some(expr_span) = expr_span {
641 Some((value.span.with_hi(expr_span.lo()), value.span.with_lo(expr_span.hi())))
649 left_pos.map_or(false, |s| s >= value.span.lo()),
650 right_pos.map_or(false, |s| s <= value.span.hi()),
652 self.emit_unused_delims(cx, value.span, spans, ctx.into(), keep_space);
655 fn emit_unused_delims(
657 cx: &EarlyContext<'_>,
659 spans: Option<(Span, Span)>,
661 keep_space: (bool, bool),
663 let primary_span = if let Some((lo, hi)) = spans {
664 MultiSpan::from(vec![lo, hi])
666 MultiSpan::from(value_span)
668 cx.struct_span_lint(self.lint(), primary_span, fluent::lint_unused_delim, |lint| {
669 lint.set_arg("delim", Self::DELIM_STR);
670 lint.set_arg("item", msg);
671 if let Some((lo, hi)) = spans {
672 let sm = cx.sess().source_map();
675 let Ok(snip) = sm.span_to_prev_source(lo) && !snip.ends_with(' ') {
683 let Ok(snip) = sm.span_to_next_source(hi) && !snip.starts_with(' ') {
689 let replacement = vec![(lo, lo_replace), (hi, hi_replace)];
690 lint.multipart_suggestion(
693 Applicability::MachineApplicable,
700 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
701 use rustc_ast::ExprKind::*;
702 let (value, ctx, followed_by_block, left_pos, right_pos) = match e.kind {
703 // Do not lint `unused_braces` in `if let` expressions.
704 If(ref cond, ref block, _)
705 if !matches!(cond.kind, Let(_, _, _))
706 || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
708 let left = e.span.lo() + rustc_span::BytePos(2);
709 let right = block.span.lo();
710 (cond, UnusedDelimsCtx::IfCond, true, Some(left), Some(right))
713 // Do not lint `unused_braces` in `while let` expressions.
714 While(ref cond, ref block, ..)
715 if !matches!(cond.kind, Let(_, _, _))
716 || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
718 let left = e.span.lo() + rustc_span::BytePos(5);
719 let right = block.span.lo();
720 (cond, UnusedDelimsCtx::WhileCond, true, Some(left), Some(right))
723 ForLoop(_, ref cond, ref block, ..) => {
724 (cond, UnusedDelimsCtx::ForIterExpr, true, None, Some(block.span.lo()))
727 Match(ref head, _) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
728 let left = e.span.lo() + rustc_span::BytePos(5);
729 (head, UnusedDelimsCtx::MatchScrutineeExpr, true, Some(left), None)
732 Ret(Some(ref value)) => {
733 let left = e.span.lo() + rustc_span::BytePos(3);
734 (value, UnusedDelimsCtx::ReturnValue, false, Some(left), None)
737 Assign(_, ref value, _) | AssignOp(.., ref value) => {
738 (value, UnusedDelimsCtx::AssignedValue, false, None, None)
740 // either function/method call, or something this lint doesn't care about
741 ref call_or_other => {
742 let (args_to_check, ctx) = match *call_or_other {
743 Call(_, ref args) => (&args[..], UnusedDelimsCtx::FunctionArg),
744 MethodCall(ref call) => (&call.args[..], UnusedDelimsCtx::MethodArg),
745 // actual catch-all arm
750 // Don't lint if this is a nested macro expansion: otherwise, the lint could
751 // trigger in situations that macro authors shouldn't have to care about, e.g.,
752 // when a parenthesized token tree matched in one macro expansion is matched as
753 // an expression in another and used as a fn/method argument (Issue #47775)
754 if e.span.ctxt().outer_expn_data().call_site.from_expansion() {
757 for arg in args_to_check {
758 self.check_unused_delims_expr(cx, arg, ctx, false, None, None);
763 self.check_unused_delims_expr(cx, &value, ctx, followed_by_block, left_pos, right_pos);
766 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
768 StmtKind::Local(ref local) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
769 if let Some((init, els)) = local.kind.init_else_opt() {
770 let ctx = match els {
771 None => UnusedDelimsCtx::AssignedValue,
772 Some(_) => UnusedDelimsCtx::AssignedValueLetElse,
774 self.check_unused_delims_expr(cx, init, ctx, false, None, None);
777 StmtKind::Expr(ref expr) => {
778 self.check_unused_delims_expr(
781 UnusedDelimsCtx::BlockRetValue,
791 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
792 use ast::ItemKind::*;
794 if let Const(.., Some(expr)) | Static(.., Some(expr)) = &item.kind {
795 self.check_unused_delims_expr(
798 UnusedDelimsCtx::AssignedValue,
808 /// The `unused_parens` lint detects `if`, `match`, `while` and `return`
809 /// with parentheses; they do not need them.
821 /// The parentheses are not needed, and should be removed. This is the
822 /// preferred style for writing these expressions.
823 pub(super) UNUSED_PARENS,
825 "`if`, `match`, `while` and `return` do not need parentheses"
828 declare_lint_pass!(UnusedParens => [UNUSED_PARENS]);
830 impl UnusedDelimLint for UnusedParens {
831 const DELIM_STR: &'static str = "parentheses";
833 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = true;
835 fn lint(&self) -> &'static Lint {
839 fn check_unused_delims_expr(
841 cx: &EarlyContext<'_>,
843 ctx: UnusedDelimsCtx,
844 followed_by_block: bool,
845 left_pos: Option<BytePos>,
846 right_pos: Option<BytePos>,
849 ast::ExprKind::Paren(ref inner) => {
850 let followed_by_else = ctx == UnusedDelimsCtx::AssignedValueLetElse;
851 if !Self::is_expr_delims_necessary(inner, followed_by_block, followed_by_else)
852 && value.attrs.is_empty()
853 && !value.span.from_expansion()
854 && (ctx != UnusedDelimsCtx::LetScrutineeExpr
855 || !matches!(inner.kind, ast::ExprKind::Binary(
856 rustc_span::source_map::Spanned { node, .. },
861 self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
864 ast::ExprKind::Let(_, ref expr, _) => {
865 self.check_unused_delims_expr(
868 UnusedDelimsCtx::LetScrutineeExpr,
880 fn check_unused_parens_pat(
882 cx: &EarlyContext<'_>,
886 keep_space: (bool, bool),
888 use ast::{BindingAnnotation, PatKind};
890 if let PatKind::Paren(inner) = &value.kind {
892 // The lint visitor will visit each subpattern of `p`. We do not want to lint
893 // any range pattern no matter where it occurs in the pattern. For something like
894 // `&(a..=b)`, there is a recursive `check_pat` on `a` and `b`, but we will assume
895 // that if there are unnecessary parens they serve a purpose of readability.
896 PatKind::Range(..) => return,
897 // Avoid `p0 | .. | pn` if we should.
898 PatKind::Or(..) if avoid_or => return,
899 // Avoid `mut x` and `mut x @ p` if we should:
900 PatKind::Ident(BindingAnnotation::MUT, ..) if avoid_mut => {
903 // Otherwise proceed with linting.
906 let spans = if let Some(inner) = inner.span.find_ancestor_inside(value.span) {
907 Some((value.span.with_hi(inner.lo()), value.span.with_lo(inner.hi())))
911 self.emit_unused_delims(cx, value.span, spans, "pattern", keep_space);
916 impl EarlyLintPass for UnusedParens {
917 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
919 ExprKind::Let(ref pat, _, _) | ExprKind::ForLoop(ref pat, ..) => {
920 self.check_unused_parens_pat(cx, pat, false, false, (true, true));
922 // We ignore parens in cases like `if (((let Some(0) = Some(1))))` because we already
923 // handle a hard error for them during AST lowering in `lower_expr_mut`, but we still
924 // want to complain about things like `if let 42 = (42)`.
925 ExprKind::If(ref cond, ref block, ref else_)
926 if matches!(cond.peel_parens().kind, ExprKind::Let(..)) =>
928 self.check_unused_delims_expr(
931 UnusedDelimsCtx::LetScrutineeExpr,
936 for stmt in &block.stmts {
937 <Self as UnusedDelimLint>::check_stmt(self, cx, stmt);
939 if let Some(e) = else_ {
940 <Self as UnusedDelimLint>::check_expr(self, cx, e);
944 ExprKind::Match(ref _expr, ref arm) => {
946 self.check_unused_delims_expr(
949 UnusedDelimsCtx::MatchArmExpr,
959 <Self as UnusedDelimLint>::check_expr(self, cx, e)
962 fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
963 use ast::{Mutability, PatKind::*};
964 let keep_space = (false, false);
966 // Do not lint on `(..)` as that will result in the other arms being useless.
968 // The other cases do not contain sub-patterns.
969 | Wild | Rest | Lit(..) | MacCall(..) | Range(..) | Ident(.., None) | Path(..) => {},
970 // These are list-like patterns; parens can always be removed.
971 TupleStruct(_, _, ps) | Tuple(ps) | Slice(ps) | Or(ps) => for p in ps {
972 self.check_unused_parens_pat(cx, p, false, false, keep_space);
974 Struct(_, _, fps, _) => for f in fps {
975 self.check_unused_parens_pat(cx, &f.pat, false, false, keep_space);
977 // Avoid linting on `i @ (p0 | .. | pn)` and `box (p0 | .. | pn)`, #64106.
978 Ident(.., Some(p)) | Box(p) => self.check_unused_parens_pat(cx, p, true, false, keep_space),
979 // Avoid linting on `&(mut x)` as `&mut x` has a different meaning, #55342.
980 // Also avoid linting on `& mut? (p0 | .. | pn)`, #64106.
981 Ref(p, m) => self.check_unused_parens_pat(cx, p, true, *m == Mutability::Not, keep_space),
985 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
986 if let StmtKind::Local(ref local) = s.kind {
987 self.check_unused_parens_pat(cx, &local.pat, true, false, (false, false));
990 <Self as UnusedDelimLint>::check_stmt(self, cx, s)
993 fn check_param(&mut self, cx: &EarlyContext<'_>, param: &ast::Param) {
994 self.check_unused_parens_pat(cx, ¶m.pat, true, false, (false, false));
997 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
998 self.check_unused_parens_pat(cx, &arm.pat, false, false, (false, false));
1001 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
1002 if let ast::TyKind::Paren(r) = &ty.kind {
1004 ast::TyKind::TraitObject(..) => {}
1005 ast::TyKind::ImplTrait(_, bounds) if bounds.len() > 1 => {}
1006 ast::TyKind::Array(_, len) => {
1007 self.check_unused_delims_expr(
1010 UnusedDelimsCtx::ArrayLenExpr,
1017 let spans = if let Some(r) = r.span.find_ancestor_inside(ty.span) {
1018 Some((ty.span.with_hi(r.lo()), ty.span.with_lo(r.hi())))
1022 self.emit_unused_delims(cx, ty.span, spans, "type", (false, false));
1028 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1029 <Self as UnusedDelimLint>::check_item(self, cx, item)
1034 /// The `unused_braces` lint detects unnecessary braces around an
1049 /// The braces are not needed, and should be removed. This is the
1050 /// preferred style for writing these expressions.
1051 pub(super) UNUSED_BRACES,
1053 "unnecessary braces around an expression"
1056 declare_lint_pass!(UnusedBraces => [UNUSED_BRACES]);
1058 impl UnusedDelimLint for UnusedBraces {
1059 const DELIM_STR: &'static str = "braces";
1061 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = false;
1063 fn lint(&self) -> &'static Lint {
1067 fn check_unused_delims_expr(
1069 cx: &EarlyContext<'_>,
1071 ctx: UnusedDelimsCtx,
1072 followed_by_block: bool,
1073 left_pos: Option<BytePos>,
1074 right_pos: Option<BytePos>,
1077 ast::ExprKind::Block(ref inner, None)
1078 if inner.rules == ast::BlockCheckMode::Default =>
1080 // emit a warning under the following conditions:
1082 // - the block does not have a label
1083 // - the block is not `unsafe`
1084 // - the block contains exactly one expression (do not lint `{ expr; }`)
1085 // - `followed_by_block` is true and the internal expr may contain a `{`
1086 // - the block is not multiline (do not lint multiline match arms)
1090 // somewhat_long_expression
1095 // - the block has no attribute and was not created inside a macro
1096 // - if the block is an `anon_const`, the inner expr must be a literal
1097 // (do not lint `struct A<const N: usize>; let _: A<{ 2 + 3 }>;`)
1099 // FIXME(const_generics): handle paths when #67075 is fixed.
1100 if let [stmt] = inner.stmts.as_slice() {
1101 if let ast::StmtKind::Expr(ref expr) = stmt.kind {
1102 if !Self::is_expr_delims_necessary(expr, followed_by_block, false)
1103 && (ctx != UnusedDelimsCtx::AnonConst
1104 || matches!(expr.kind, ast::ExprKind::Lit(_)))
1105 && !cx.sess().source_map().is_multiline(value.span)
1106 && value.attrs.is_empty()
1107 && !value.span.from_expansion()
1109 self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
1114 ast::ExprKind::Let(_, ref expr, _) => {
1115 self.check_unused_delims_expr(
1118 UnusedDelimsCtx::LetScrutineeExpr,
1129 impl EarlyLintPass for UnusedBraces {
1130 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
1131 <Self as UnusedDelimLint>::check_stmt(self, cx, s)
1134 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
1135 <Self as UnusedDelimLint>::check_expr(self, cx, e);
1137 if let ExprKind::Repeat(_, ref anon_const) = e.kind {
1138 self.check_unused_delims_expr(
1141 UnusedDelimsCtx::AnonConst,
1149 fn check_generic_arg(&mut self, cx: &EarlyContext<'_>, arg: &ast::GenericArg) {
1150 if let ast::GenericArg::Const(ct) = arg {
1151 self.check_unused_delims_expr(
1154 UnusedDelimsCtx::AnonConst,
1162 fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant) {
1163 if let Some(anon_const) = &v.disr_expr {
1164 self.check_unused_delims_expr(
1167 UnusedDelimsCtx::AnonConst,
1175 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
1177 ast::TyKind::Array(_, ref len) => {
1178 self.check_unused_delims_expr(
1181 UnusedDelimsCtx::ArrayLenExpr,
1188 ast::TyKind::Typeof(ref anon_const) => {
1189 self.check_unused_delims_expr(
1192 UnusedDelimsCtx::AnonConst,
1203 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1204 <Self as UnusedDelimLint>::check_item(self, cx, item)
1209 /// The `unused_import_braces` lint catches unnecessary braces around an
1214 /// ```rust,compile_fail
1215 /// #![deny(unused_import_braces)]
1228 /// If there is only a single item, then remove the braces (`use test::A;`
1231 /// This lint is "allow" by default because it is only enforcing a
1232 /// stylistic choice.
1233 UNUSED_IMPORT_BRACES,
1235 "unnecessary braces around an imported item"
1238 declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]);
1240 impl UnusedImportBraces {
1241 fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
1242 if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
1243 // Recursively check nested UseTrees
1244 for &(ref tree, _) in items {
1245 self.check_use_tree(cx, tree, item);
1248 // Trigger the lint only if there is one nested item
1249 if items.len() != 1 {
1253 // Trigger the lint if the nested item is a non-self single item
1254 let node_name = match items[0].0.kind {
1255 ast::UseTreeKind::Simple(rename, ..) => {
1256 let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
1257 if orig_ident.name == kw::SelfLower {
1260 rename.unwrap_or(orig_ident).name
1262 ast::UseTreeKind::Glob => Symbol::intern("*"),
1263 ast::UseTreeKind::Nested(_) => return,
1266 cx.struct_span_lint(
1267 UNUSED_IMPORT_BRACES,
1269 fluent::lint_unused_import_braces,
1270 |lint| lint.set_arg("node", node_name),
1276 impl EarlyLintPass for UnusedImportBraces {
1277 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1278 if let ast::ItemKind::Use(ref use_tree) = item.kind {
1279 self.check_use_tree(cx, use_tree, item);
1285 /// The `unused_allocation` lint detects unnecessary allocations that can
1291 /// #![feature(box_syntax)]
1293 /// let a = (box [1, 2, 3]).len();
1301 /// When a `box` expression is immediately coerced to a reference, then
1302 /// the allocation is unnecessary, and a reference (using `&` or `&mut`)
1303 /// should be used instead to avoid the allocation.
1304 pub(super) UNUSED_ALLOCATION,
1306 "detects unnecessary allocations that can be eliminated"
1309 declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]);
1311 impl<'tcx> LateLintPass<'tcx> for UnusedAllocation {
1312 fn check_expr(&mut self, cx: &LateContext<'_>, e: &hir::Expr<'_>) {
1314 hir::ExprKind::Box(_) => {}
1318 for adj in cx.typeck_results().expr_adjustments(e) {
1319 if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
1320 cx.struct_span_lint(
1324 adjustment::AutoBorrowMutability::Not => fluent::lint_unused_allocation,
1325 adjustment::AutoBorrowMutability::Mut { .. } => {
1326 fluent::lint_unused_allocation_mut