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};
18 /// The `unused_must_use` lint detects unused result of a type flagged as
24 /// fn returns_result() -> Result<(), ()> {
37 /// The `#[must_use]` attribute is an indicator that it is a mistake to
38 /// ignore the value. See [the reference] for more details.
40 /// [the reference]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
43 "unused result of a type flagged as `#[must_use]`",
44 report_in_external_macro
48 /// The `unused_results` lint checks for the unused result of an
49 /// expression in a statement.
53 /// ```rust,compile_fail
54 /// #![deny(unused_results)]
55 /// fn foo<T>() -> T { panic!() }
66 /// Ignoring the return value of a function may indicate a mistake. In
67 /// cases were it is almost certain that the result should be used, it is
68 /// recommended to annotate the function with the [`must_use` attribute].
69 /// Failure to use such a return value will trigger the [`unused_must_use`
70 /// lint] which is warn-by-default. The `unused_results` lint is
71 /// essentially the same, but triggers for *all* return values.
73 /// This lint is "allow" by default because it can be noisy, and may not be
74 /// an actual problem. For example, calling the `remove` method of a `Vec`
75 /// or `HashMap` returns the previous value, which you may not care about.
76 /// Using this lint would require explicitly ignoring or discarding such
79 /// [`must_use` attribute]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
80 /// [`unused_must_use` lint]: warn-by-default.html#unused-must-use
83 "unused result of an expression in a statement"
86 declare_lint_pass!(UnusedResults => [UNUSED_MUST_USE, UNUSED_RESULTS]);
88 impl<'tcx> LateLintPass<'tcx> for UnusedResults {
89 fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
90 let hir::StmtKind::Semi(expr) = s.kind else { return; };
92 if let hir::ExprKind::Ret(..) = expr.kind {
96 if let hir::ExprKind::Match(await_expr, _arms, hir::MatchSource::AwaitDesugar) = expr.kind
97 && let ty = cx.typeck_results().expr_ty(&await_expr)
98 && let ty::Opaque(future_def_id, _) = ty.kind()
99 && cx.tcx.ty_is_opaque_future(ty)
100 // FIXME: This also includes non-async fns that return `impl Future`.
101 && let async_fn_def_id = cx.tcx.parent(*future_def_id)
102 && check_must_use_def(
106 "output of future returned by ",
110 // We have a bare `foo().await;` on an opaque type from an async function that was
111 // annotated with `#[must_use]`.
115 let ty = cx.typeck_results().expr_ty(&expr);
116 let type_permits_lack_of_use = check_must_use_ty(cx, ty, &expr, expr.span, "", "", 1);
118 let mut fn_warned = false;
119 let mut op_warned = false;
120 let maybe_def_id = match expr.kind {
121 hir::ExprKind::Call(ref callee, _) => {
123 hir::ExprKind::Path(ref qpath) => {
124 match cx.qpath_res(qpath, callee.hir_id) {
125 Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) => Some(def_id),
126 // `Res::Local` if it was a closure, for which we
127 // do not currently support must-use linting
134 hir::ExprKind::MethodCall(..) => cx.typeck_results().type_dependent_def_id(expr.hir_id),
137 if let Some(def_id) = maybe_def_id {
138 fn_warned = check_must_use_def(cx, def_id, expr.span, "return value of ", "");
139 } else if type_permits_lack_of_use {
140 // We don't warn about unused unit or uninhabited types.
141 // (See https://github.com/rust-lang/rust/issues/43806 for details.)
145 let must_use_op = match expr.kind {
146 // Hardcoding operators here seemed more expedient than the
147 // refactoring that would be needed to look up the `#[must_use]`
148 // attribute which does exist on the comparison trait methods
149 hir::ExprKind::Binary(bin_op, ..) => match bin_op.node {
155 | hir::BinOpKind::Gt => Some("comparison"),
157 | hir::BinOpKind::Sub
158 | hir::BinOpKind::Div
159 | hir::BinOpKind::Mul
160 | hir::BinOpKind::Rem => Some("arithmetic operation"),
161 hir::BinOpKind::And | hir::BinOpKind::Or => Some("logical operation"),
162 hir::BinOpKind::BitXor
163 | hir::BinOpKind::BitAnd
164 | hir::BinOpKind::BitOr
165 | hir::BinOpKind::Shl
166 | hir::BinOpKind::Shr => Some("bitwise operation"),
168 hir::ExprKind::AddrOf(..) => Some("borrow"),
169 hir::ExprKind::Unary(..) => Some("unary operation"),
173 if let Some(must_use_op) = must_use_op {
174 cx.struct_span_lint(UNUSED_MUST_USE, expr.span, fluent::lint_unused_op, |lint| {
175 lint.set_arg("op", must_use_op)
176 .span_label(expr.span, fluent::label)
177 .span_suggestion_verbose(
178 expr.span.shrink_to_lo(),
181 Applicability::MachineApplicable,
187 if !(type_permits_lack_of_use || fn_warned || op_warned) {
188 cx.struct_span_lint(UNUSED_RESULTS, s.span, fluent::lint_unused_result, |lint| {
189 lint.set_arg("ty", ty)
193 // Returns whether an error has been emitted (and thus another does not need to be later).
194 fn check_must_use_ty<'tcx>(
195 cx: &LateContext<'tcx>,
197 expr: &hir::Expr<'_>,
204 || cx.tcx.is_ty_uninhabited_from(
205 cx.tcx.parent_module(expr.hir_id).to_def_id(),
213 let plural_suffix = pluralize!(plural_len);
216 ty::Adt(..) if ty.is_box() => {
217 let boxed_ty = ty.boxed_ty();
218 let descr_pre = &format!("{}boxed ", descr_pre);
219 check_must_use_ty(cx, boxed_ty, expr, span, descr_pre, descr_post, plural_len)
221 ty::Adt(def, _) => check_must_use_def(cx, def.did(), span, descr_pre, descr_post),
222 ty::Opaque(def, _) => {
223 let mut has_emitted = false;
224 for obligation in elaborate_predicates_with_span(
226 cx.tcx.explicit_item_bounds(def).iter().cloned(),
228 // We only look at the `DefId`, so it is safe to skip the binder here.
229 if let ty::PredicateKind::Trait(ref poly_trait_predicate) =
230 obligation.predicate.kind().skip_binder()
232 let def_id = poly_trait_predicate.trait_ref.def_id;
234 &format!("{}implementer{} of ", descr_pre, plural_suffix,);
235 if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
243 ty::Dynamic(binder, _, _) => {
244 let mut has_emitted = false;
245 for predicate in binder.iter() {
246 if let ty::ExistentialPredicate::Trait(ref trait_ref) =
247 predicate.skip_binder()
249 let def_id = trait_ref.def_id;
251 &format!(" trait object{}{}", plural_suffix, descr_post,);
252 if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
260 ty::Tuple(ref tys) => {
261 let mut has_emitted = false;
262 let comps = if let hir::ExprKind::Tup(comps) = expr.kind {
263 debug_assert_eq!(comps.len(), tys.len());
268 for (i, ty) in tys.iter().enumerate() {
269 let descr_post = &format!(" in tuple element {}", i);
270 let e = comps.get(i).unwrap_or(expr);
272 if check_must_use_ty(cx, ty, e, span, descr_pre, descr_post, plural_len) {
278 ty::Array(ty, len) => match len.try_eval_usize(cx.tcx, cx.param_env) {
279 // If the array is empty we don't lint, to avoid false positives
280 Some(0) | None => false,
281 // If the array is definitely non-empty, we can do `#[must_use]` checking.
283 let descr_pre = &format!("{}array{} of ", descr_pre, plural_suffix,);
284 check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, n as usize + 1)
291 fluent::lint_unused_closure,
293 // FIXME(davidtwco): this isn't properly translatable because of the
295 lint.set_arg("count", plural_len)
296 .set_arg("pre", descr_pre)
297 .set_arg("post", descr_post)
303 ty::Generator(..) => {
307 fluent::lint_unused_generator,
309 // FIXME(davidtwco): this isn't properly translatable because of the
311 lint.set_arg("count", plural_len)
312 .set_arg("pre", descr_pre)
313 .set_arg("post", descr_post)
323 // Returns whether an error has been emitted (and thus another does not need to be later).
324 // FIXME: Args desc_{pre,post}_path could be made lazy by taking Fn() -> &str, but this
325 // would make calling it a big awkward. Could also take String (so args are moved), but
326 // this would still require a copy into the format string, which would only be executed
328 fn check_must_use_def(
329 cx: &LateContext<'_>,
332 descr_pre_path: &str,
333 descr_post_path: &str,
335 if let Some(attr) = cx.tcx.get_attr(def_id, sym::must_use) {
336 cx.struct_span_lint(UNUSED_MUST_USE, span, fluent::lint_unused_def, |lint| {
337 // FIXME(davidtwco): this isn't properly translatable because of the pre/post
339 lint.set_arg("pre", descr_pre_path);
340 lint.set_arg("post", descr_post_path);
341 lint.set_arg("def", cx.tcx.def_path_str(def_id));
342 // check for #[must_use = "..."]
343 if let Some(note) = attr.value_str() {
344 lint.note(note.as_str());
357 /// The `path_statements` lint detects path statements with no effect.
371 /// It is usually a mistake to have a statement that has no effect.
374 "path statements with no effect"
377 declare_lint_pass!(PathStatements => [PATH_STATEMENTS]);
379 impl<'tcx> LateLintPass<'tcx> for PathStatements {
380 fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
381 if let hir::StmtKind::Semi(expr) = s.kind {
382 if let hir::ExprKind::Path(_) = expr.kind {
383 let ty = cx.typeck_results().expr_ty(expr);
384 if ty.needs_drop(cx.tcx, cx.param_env) {
388 fluent::lint_path_statement_drop,
390 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(expr.span) {
391 lint.span_suggestion(
394 format!("drop({});", snippet),
395 Applicability::MachineApplicable,
398 lint.span_help(s.span, fluent::suggestion);
407 fluent::lint_path_statement_no_effect,
416 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
417 enum UnusedDelimsCtx {
421 AssignedValueLetElse,
434 impl From<UnusedDelimsCtx> for &'static str {
435 fn from(ctx: UnusedDelimsCtx) -> &'static str {
437 UnusedDelimsCtx::FunctionArg => "function argument",
438 UnusedDelimsCtx::MethodArg => "method argument",
439 UnusedDelimsCtx::AssignedValue | UnusedDelimsCtx::AssignedValueLetElse => {
442 UnusedDelimsCtx::IfCond => "`if` condition",
443 UnusedDelimsCtx::WhileCond => "`while` condition",
444 UnusedDelimsCtx::ForIterExpr => "`for` iterator expression",
445 UnusedDelimsCtx::MatchScrutineeExpr => "`match` scrutinee expression",
446 UnusedDelimsCtx::ReturnValue => "`return` value",
447 UnusedDelimsCtx::BlockRetValue => "block return value",
448 UnusedDelimsCtx::LetScrutineeExpr => "`let` scrutinee expression",
449 UnusedDelimsCtx::ArrayLenExpr | UnusedDelimsCtx::AnonConst => "const expression",
450 UnusedDelimsCtx::MatchArmExpr => "match arm expression",
455 /// Used by both `UnusedParens` and `UnusedBraces` to prevent code duplication.
456 trait UnusedDelimLint {
457 const DELIM_STR: &'static str;
459 /// Due to `ref` pattern, there can be a difference between using
460 /// `{ expr }` and `expr` in pattern-matching contexts. This means
461 /// that we should only lint `unused_parens` and not `unused_braces`
466 /// let ref b = { a }; // We actually borrow a copy of `a` here.
467 /// a += 1; // By mutating `a` we invalidate any borrows of `a`.
468 /// assert_eq!(b + 1, a); // `b` does not borrow `a`, so we can still use it here.
470 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool;
472 // this cannot be a constant is it refers to a static.
473 fn lint(&self) -> &'static Lint;
475 fn check_unused_delims_expr(
477 cx: &EarlyContext<'_>,
479 ctx: UnusedDelimsCtx,
480 followed_by_block: bool,
481 left_pos: Option<BytePos>,
482 right_pos: Option<BytePos>,
485 fn is_expr_delims_necessary(
487 followed_by_block: bool,
488 followed_by_else: bool,
490 if followed_by_else {
492 ast::ExprKind::Binary(op, ..) if op.node.lazy() => return true,
493 _ if classify::expr_trailing_brace(inner).is_some() => return true,
498 // Prevent false-positives in cases like `fn x() -> u8 { ({ 0 } + 1) }`
499 let lhs_needs_parens = {
500 let mut innermost = inner;
502 innermost = match &innermost.kind {
503 ExprKind::Binary(_, lhs, _rhs) => lhs,
504 ExprKind::Call(fn_, _params) => fn_,
505 ExprKind::Cast(expr, _ty) => expr,
506 ExprKind::Type(expr, _ty) => expr,
507 ExprKind::Index(base, _subscript) => base,
510 if !classify::expr_requires_semi_to_be_stmt(innermost) {
517 || (followed_by_block
518 && match &inner.kind {
519 ExprKind::Ret(_) | ExprKind::Break(..) | ExprKind::Yield(..) => true,
520 ExprKind::Range(_lhs, Some(rhs), _limits) => {
521 matches!(rhs.kind, ExprKind::Block(..))
523 _ => parser::contains_exterior_struct_lit(&inner),
527 fn emit_unused_delims_expr(
529 cx: &EarlyContext<'_>,
531 ctx: UnusedDelimsCtx,
532 left_pos: Option<BytePos>,
533 right_pos: Option<BytePos>,
535 let spans = match value.kind {
536 ast::ExprKind::Block(ref block, None) if block.stmts.len() == 1 => {
537 if let StmtKind::Expr(expr) = &block.stmts[0].kind
538 && let ExprKind::Err = expr.kind
542 if let Some(span) = block.stmts[0].span.find_ancestor_inside(value.span) {
543 Some((value.span.with_hi(span.lo()), value.span.with_lo(span.hi())))
548 ast::ExprKind::Paren(ref expr) => {
549 let expr_span = expr.span.find_ancestor_inside(value.span);
550 if let Some(expr_span) = expr_span {
551 Some((value.span.with_hi(expr_span.lo()), value.span.with_lo(expr_span.hi())))
559 left_pos.map_or(false, |s| s >= value.span.lo()),
560 right_pos.map_or(false, |s| s <= value.span.hi()),
562 self.emit_unused_delims(cx, value.span, spans, ctx.into(), keep_space);
565 fn emit_unused_delims(
567 cx: &EarlyContext<'_>,
569 spans: Option<(Span, Span)>,
571 keep_space: (bool, bool),
573 let primary_span = if let Some((lo, hi)) = spans {
574 MultiSpan::from(vec![lo, hi])
576 MultiSpan::from(value_span)
578 cx.struct_span_lint(self.lint(), primary_span, fluent::lint_unused_delim, |lint| {
579 lint.set_arg("delim", Self::DELIM_STR);
580 lint.set_arg("item", msg);
581 if let Some((lo, hi)) = spans {
582 let sm = cx.sess().source_map();
585 let Ok(snip) = sm.span_to_prev_source(lo) && !snip.ends_with(" ") {
593 let Ok(snip) = sm.span_to_next_source(hi) && !snip.starts_with(" ") {
599 let replacement = vec![(lo, lo_replace), (hi, hi_replace)];
600 lint.multipart_suggestion(
603 Applicability::MachineApplicable,
610 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
611 use rustc_ast::ExprKind::*;
612 let (value, ctx, followed_by_block, left_pos, right_pos) = match e.kind {
613 // Do not lint `unused_braces` in `if let` expressions.
614 If(ref cond, ref block, _)
615 if !matches!(cond.kind, Let(_, _, _))
616 || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
618 let left = e.span.lo() + rustc_span::BytePos(2);
619 let right = block.span.lo();
620 (cond, UnusedDelimsCtx::IfCond, true, Some(left), Some(right))
623 // Do not lint `unused_braces` in `while let` expressions.
624 While(ref cond, ref block, ..)
625 if !matches!(cond.kind, Let(_, _, _))
626 || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
628 let left = e.span.lo() + rustc_span::BytePos(5);
629 let right = block.span.lo();
630 (cond, UnusedDelimsCtx::WhileCond, true, Some(left), Some(right))
633 ForLoop(_, ref cond, ref block, ..) => {
634 (cond, UnusedDelimsCtx::ForIterExpr, true, None, Some(block.span.lo()))
637 Match(ref head, _) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
638 let left = e.span.lo() + rustc_span::BytePos(5);
639 (head, UnusedDelimsCtx::MatchScrutineeExpr, true, Some(left), None)
642 Ret(Some(ref value)) => {
643 let left = e.span.lo() + rustc_span::BytePos(3);
644 (value, UnusedDelimsCtx::ReturnValue, false, Some(left), None)
647 Assign(_, ref value, _) | AssignOp(.., ref value) => {
648 (value, UnusedDelimsCtx::AssignedValue, false, None, None)
650 // either function/method call, or something this lint doesn't care about
651 ref call_or_other => {
652 let (args_to_check, ctx) = match *call_or_other {
653 Call(_, ref args) => (&args[..], UnusedDelimsCtx::FunctionArg),
654 MethodCall(ref call) => (&call.args[..], UnusedDelimsCtx::MethodArg),
655 // actual catch-all arm
660 // Don't lint if this is a nested macro expansion: otherwise, the lint could
661 // trigger in situations that macro authors shouldn't have to care about, e.g.,
662 // when a parenthesized token tree matched in one macro expansion is matched as
663 // an expression in another and used as a fn/method argument (Issue #47775)
664 if e.span.ctxt().outer_expn_data().call_site.from_expansion() {
667 for arg in args_to_check {
668 self.check_unused_delims_expr(cx, arg, ctx, false, None, None);
673 self.check_unused_delims_expr(cx, &value, ctx, followed_by_block, left_pos, right_pos);
676 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
678 StmtKind::Local(ref local) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
679 if let Some((init, els)) = local.kind.init_else_opt() {
680 let ctx = match els {
681 None => UnusedDelimsCtx::AssignedValue,
682 Some(_) => UnusedDelimsCtx::AssignedValueLetElse,
684 self.check_unused_delims_expr(cx, init, ctx, false, None, None);
687 StmtKind::Expr(ref expr) => {
688 self.check_unused_delims_expr(
691 UnusedDelimsCtx::BlockRetValue,
701 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
702 use ast::ItemKind::*;
704 if let Const(.., Some(expr)) | Static(.., Some(expr)) = &item.kind {
705 self.check_unused_delims_expr(
708 UnusedDelimsCtx::AssignedValue,
718 /// The `unused_parens` lint detects `if`, `match`, `while` and `return`
719 /// with parentheses; they do not need them.
731 /// The parentheses are not needed, and should be removed. This is the
732 /// preferred style for writing these expressions.
733 pub(super) UNUSED_PARENS,
735 "`if`, `match`, `while` and `return` do not need parentheses"
738 declare_lint_pass!(UnusedParens => [UNUSED_PARENS]);
740 impl UnusedDelimLint for UnusedParens {
741 const DELIM_STR: &'static str = "parentheses";
743 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = true;
745 fn lint(&self) -> &'static Lint {
749 fn check_unused_delims_expr(
751 cx: &EarlyContext<'_>,
753 ctx: UnusedDelimsCtx,
754 followed_by_block: bool,
755 left_pos: Option<BytePos>,
756 right_pos: Option<BytePos>,
759 ast::ExprKind::Paren(ref inner) => {
760 let followed_by_else = ctx == UnusedDelimsCtx::AssignedValueLetElse;
761 if !Self::is_expr_delims_necessary(inner, followed_by_block, followed_by_else)
762 && value.attrs.is_empty()
763 && !value.span.from_expansion()
764 && (ctx != UnusedDelimsCtx::LetScrutineeExpr
765 || !matches!(inner.kind, ast::ExprKind::Binary(
766 rustc_span::source_map::Spanned { node, .. },
771 self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
774 ast::ExprKind::Let(_, ref expr, _) => {
775 self.check_unused_delims_expr(
778 UnusedDelimsCtx::LetScrutineeExpr,
790 fn check_unused_parens_pat(
792 cx: &EarlyContext<'_>,
796 keep_space: (bool, bool),
798 use ast::{BindingAnnotation, PatKind};
800 if let PatKind::Paren(inner) = &value.kind {
802 // The lint visitor will visit each subpattern of `p`. We do not want to lint
803 // any range pattern no matter where it occurs in the pattern. For something like
804 // `&(a..=b)`, there is a recursive `check_pat` on `a` and `b`, but we will assume
805 // that if there are unnecessary parens they serve a purpose of readability.
806 PatKind::Range(..) => return,
807 // Avoid `p0 | .. | pn` if we should.
808 PatKind::Or(..) if avoid_or => return,
809 // Avoid `mut x` and `mut x @ p` if we should:
810 PatKind::Ident(BindingAnnotation::MUT, ..) if avoid_mut => {
813 // Otherwise proceed with linting.
816 let spans = if let Some(inner) = inner.span.find_ancestor_inside(value.span) {
817 Some((value.span.with_hi(inner.lo()), value.span.with_lo(inner.hi())))
821 self.emit_unused_delims(cx, value.span, spans, "pattern", keep_space);
826 impl EarlyLintPass for UnusedParens {
827 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
829 ExprKind::Let(ref pat, _, _) | ExprKind::ForLoop(ref pat, ..) => {
830 self.check_unused_parens_pat(cx, pat, false, false, (true, true));
832 // We ignore parens in cases like `if (((let Some(0) = Some(1))))` because we already
833 // handle a hard error for them during AST lowering in `lower_expr_mut`, but we still
834 // want to complain about things like `if let 42 = (42)`.
835 ExprKind::If(ref cond, ref block, ref else_)
836 if matches!(cond.peel_parens().kind, ExprKind::Let(..)) =>
838 self.check_unused_delims_expr(
841 UnusedDelimsCtx::LetScrutineeExpr,
846 for stmt in &block.stmts {
847 <Self as UnusedDelimLint>::check_stmt(self, cx, stmt);
849 if let Some(e) = else_ {
850 <Self as UnusedDelimLint>::check_expr(self, cx, e);
854 ExprKind::Match(ref _expr, ref arm) => {
856 self.check_unused_delims_expr(
859 UnusedDelimsCtx::MatchArmExpr,
869 <Self as UnusedDelimLint>::check_expr(self, cx, e)
872 fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
873 use ast::{Mutability, PatKind::*};
874 let keep_space = (false, false);
876 // Do not lint on `(..)` as that will result in the other arms being useless.
878 // The other cases do not contain sub-patterns.
879 | Wild | Rest | Lit(..) | MacCall(..) | Range(..) | Ident(.., None) | Path(..) => {},
880 // These are list-like patterns; parens can always be removed.
881 TupleStruct(_, _, ps) | Tuple(ps) | Slice(ps) | Or(ps) => for p in ps {
882 self.check_unused_parens_pat(cx, p, false, false, keep_space);
884 Struct(_, _, fps, _) => for f in fps {
885 self.check_unused_parens_pat(cx, &f.pat, false, false, keep_space);
887 // Avoid linting on `i @ (p0 | .. | pn)` and `box (p0 | .. | pn)`, #64106.
888 Ident(.., Some(p)) | Box(p) => self.check_unused_parens_pat(cx, p, true, false, keep_space),
889 // Avoid linting on `&(mut x)` as `&mut x` has a different meaning, #55342.
890 // Also avoid linting on `& mut? (p0 | .. | pn)`, #64106.
891 Ref(p, m) => self.check_unused_parens_pat(cx, p, true, *m == Mutability::Not, keep_space),
895 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
896 if let StmtKind::Local(ref local) = s.kind {
897 self.check_unused_parens_pat(cx, &local.pat, true, false, (false, false));
900 <Self as UnusedDelimLint>::check_stmt(self, cx, s)
903 fn check_param(&mut self, cx: &EarlyContext<'_>, param: &ast::Param) {
904 self.check_unused_parens_pat(cx, ¶m.pat, true, false, (false, false));
907 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
908 self.check_unused_parens_pat(cx, &arm.pat, false, false, (false, false));
911 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
912 if let ast::TyKind::Paren(r) = &ty.kind {
914 ast::TyKind::TraitObject(..) => {}
915 ast::TyKind::ImplTrait(_, bounds) if bounds.len() > 1 => {}
916 ast::TyKind::Array(_, len) => {
917 self.check_unused_delims_expr(
920 UnusedDelimsCtx::ArrayLenExpr,
927 let spans = if let Some(r) = r.span.find_ancestor_inside(ty.span) {
928 Some((ty.span.with_hi(r.lo()), ty.span.with_lo(r.hi())))
932 self.emit_unused_delims(cx, ty.span, spans, "type", (false, false));
938 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
939 <Self as UnusedDelimLint>::check_item(self, cx, item)
944 /// The `unused_braces` lint detects unnecessary braces around an
959 /// The braces are not needed, and should be removed. This is the
960 /// preferred style for writing these expressions.
961 pub(super) UNUSED_BRACES,
963 "unnecessary braces around an expression"
966 declare_lint_pass!(UnusedBraces => [UNUSED_BRACES]);
968 impl UnusedDelimLint for UnusedBraces {
969 const DELIM_STR: &'static str = "braces";
971 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = false;
973 fn lint(&self) -> &'static Lint {
977 fn check_unused_delims_expr(
979 cx: &EarlyContext<'_>,
981 ctx: UnusedDelimsCtx,
982 followed_by_block: bool,
983 left_pos: Option<BytePos>,
984 right_pos: Option<BytePos>,
987 ast::ExprKind::Block(ref inner, None)
988 if inner.rules == ast::BlockCheckMode::Default =>
990 // emit a warning under the following conditions:
992 // - the block does not have a label
993 // - the block is not `unsafe`
994 // - the block contains exactly one expression (do not lint `{ expr; }`)
995 // - `followed_by_block` is true and the internal expr may contain a `{`
996 // - the block is not multiline (do not lint multiline match arms)
1000 // somewhat_long_expression
1005 // - the block has no attribute and was not created inside a macro
1006 // - if the block is an `anon_const`, the inner expr must be a literal
1007 // (do not lint `struct A<const N: usize>; let _: A<{ 2 + 3 }>;`)
1009 // FIXME(const_generics): handle paths when #67075 is fixed.
1010 if let [stmt] = inner.stmts.as_slice() {
1011 if let ast::StmtKind::Expr(ref expr) = stmt.kind {
1012 if !Self::is_expr_delims_necessary(expr, followed_by_block, false)
1013 && (ctx != UnusedDelimsCtx::AnonConst
1014 || matches!(expr.kind, ast::ExprKind::Lit(_)))
1015 && !cx.sess().source_map().is_multiline(value.span)
1016 && value.attrs.is_empty()
1017 && !value.span.from_expansion()
1019 self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
1024 ast::ExprKind::Let(_, ref expr, _) => {
1025 self.check_unused_delims_expr(
1028 UnusedDelimsCtx::LetScrutineeExpr,
1039 impl EarlyLintPass for UnusedBraces {
1040 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
1041 <Self as UnusedDelimLint>::check_stmt(self, cx, s)
1044 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
1045 <Self as UnusedDelimLint>::check_expr(self, cx, e);
1047 if let ExprKind::Repeat(_, ref anon_const) = e.kind {
1048 self.check_unused_delims_expr(
1051 UnusedDelimsCtx::AnonConst,
1059 fn check_generic_arg(&mut self, cx: &EarlyContext<'_>, arg: &ast::GenericArg) {
1060 if let ast::GenericArg::Const(ct) = arg {
1061 self.check_unused_delims_expr(
1064 UnusedDelimsCtx::AnonConst,
1072 fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant) {
1073 if let Some(anon_const) = &v.disr_expr {
1074 self.check_unused_delims_expr(
1077 UnusedDelimsCtx::AnonConst,
1085 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
1087 ast::TyKind::Array(_, ref len) => {
1088 self.check_unused_delims_expr(
1091 UnusedDelimsCtx::ArrayLenExpr,
1098 ast::TyKind::Typeof(ref anon_const) => {
1099 self.check_unused_delims_expr(
1102 UnusedDelimsCtx::AnonConst,
1113 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1114 <Self as UnusedDelimLint>::check_item(self, cx, item)
1119 /// The `unused_import_braces` lint catches unnecessary braces around an
1124 /// ```rust,compile_fail
1125 /// #![deny(unused_import_braces)]
1138 /// If there is only a single item, then remove the braces (`use test::A;`
1141 /// This lint is "allow" by default because it is only enforcing a
1142 /// stylistic choice.
1143 UNUSED_IMPORT_BRACES,
1145 "unnecessary braces around an imported item"
1148 declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]);
1150 impl UnusedImportBraces {
1151 fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
1152 if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
1153 // Recursively check nested UseTrees
1154 for &(ref tree, _) in items {
1155 self.check_use_tree(cx, tree, item);
1158 // Trigger the lint only if there is one nested item
1159 if items.len() != 1 {
1163 // Trigger the lint if the nested item is a non-self single item
1164 let node_name = match items[0].0.kind {
1165 ast::UseTreeKind::Simple(rename, ..) => {
1166 let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
1167 if orig_ident.name == kw::SelfLower {
1170 rename.unwrap_or(orig_ident).name
1172 ast::UseTreeKind::Glob => Symbol::intern("*"),
1173 ast::UseTreeKind::Nested(_) => return,
1176 cx.struct_span_lint(
1177 UNUSED_IMPORT_BRACES,
1179 fluent::lint_unused_import_braces,
1180 |lint| lint.set_arg("node", node_name),
1186 impl EarlyLintPass for UnusedImportBraces {
1187 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1188 if let ast::ItemKind::Use(ref use_tree) = item.kind {
1189 self.check_use_tree(cx, use_tree, item);
1195 /// The `unused_allocation` lint detects unnecessary allocations that can
1201 /// #![feature(box_syntax)]
1203 /// let a = (box [1, 2, 3]).len();
1211 /// When a `box` expression is immediately coerced to a reference, then
1212 /// the allocation is unnecessary, and a reference (using `&` or `&mut`)
1213 /// should be used instead to avoid the allocation.
1214 pub(super) UNUSED_ALLOCATION,
1216 "detects unnecessary allocations that can be eliminated"
1219 declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]);
1221 impl<'tcx> LateLintPass<'tcx> for UnusedAllocation {
1222 fn check_expr(&mut self, cx: &LateContext<'_>, e: &hir::Expr<'_>) {
1224 hir::ExprKind::Box(_) => {}
1228 for adj in cx.typeck_results().expr_adjustments(e) {
1229 if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
1230 cx.struct_span_lint(
1234 adjustment::AutoBorrowMutability::Not => fluent::lint_unused_allocation,
1235 adjustment::AutoBorrowMutability::Mut { .. } => {
1236 fluent::lint_unused_allocation_mut