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::{pluralize, Applicability};
8 use rustc_hir::def::{DefKind, Res};
9 use rustc_hir::def_id::DefId;
10 use rustc_middle::ty::adjustment;
11 use rustc_middle::ty::{self, Ty};
12 use rustc_span::symbol::Symbol;
13 use rustc_span::symbol::{kw, sym};
14 use rustc_span::{BytePos, MultiSpan, Span, DUMMY_SP};
17 /// The `unused_must_use` lint detects unused result of a type flagged as
23 /// fn returns_result() -> Result<(), ()> {
36 /// The `#[must_use]` attribute is an indicator that it is a mistake to
37 /// ignore the value. See [the reference] for more details.
39 /// [the reference]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
42 "unused result of a type flagged as `#[must_use]`",
43 report_in_external_macro
47 /// The `unused_results` lint checks for the unused result of an
48 /// expression in a statement.
52 /// ```rust,compile_fail
53 /// #![deny(unused_results)]
54 /// fn foo<T>() -> T { panic!() }
65 /// Ignoring the return value of a function may indicate a mistake. In
66 /// cases were it is almost certain that the result should be used, it is
67 /// recommended to annotate the function with the [`must_use` attribute].
68 /// Failure to use such a return value will trigger the [`unused_must_use`
69 /// lint] which is warn-by-default. The `unused_results` lint is
70 /// essentially the same, but triggers for *all* return values.
72 /// This lint is "allow" by default because it can be noisy, and may not be
73 /// an actual problem. For example, calling the `remove` method of a `Vec`
74 /// or `HashMap` returns the previous value, which you may not care about.
75 /// Using this lint would require explicitly ignoring or discarding such
78 /// [`must_use` attribute]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
79 /// [`unused_must_use` lint]: warn-by-default.html#unused-must-use
82 "unused result of an expression in a statement"
85 declare_lint_pass!(UnusedResults => [UNUSED_MUST_USE, UNUSED_RESULTS]);
87 impl<'tcx> LateLintPass<'tcx> for UnusedResults {
88 fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
89 let expr = match s.kind {
90 hir::StmtKind::Semi(ref expr) => &**expr,
94 if let hir::ExprKind::Ret(..) = expr.kind {
98 let ty = cx.typeck_results().expr_ty(&expr);
99 let type_permits_lack_of_use = check_must_use_ty(cx, ty, &expr, s.span, "", "", 1);
101 let mut fn_warned = false;
102 let mut op_warned = false;
103 let maybe_def_id = match expr.kind {
104 hir::ExprKind::Call(ref callee, _) => {
106 hir::ExprKind::Path(ref qpath) => {
107 match cx.qpath_res(qpath, callee.hir_id) {
108 Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) => Some(def_id),
109 // `Res::Local` if it was a closure, for which we
110 // do not currently support must-use linting
117 hir::ExprKind::MethodCall(..) => cx.typeck_results().type_dependent_def_id(expr.hir_id),
120 if let Some(def_id) = maybe_def_id {
121 fn_warned = check_must_use_def(cx, def_id, s.span, "return value of ", "");
122 } else if type_permits_lack_of_use {
123 // We don't warn about unused unit or uninhabited types.
124 // (See https://github.com/rust-lang/rust/issues/43806 for details.)
128 let must_use_op = match expr.kind {
129 // Hardcoding operators here seemed more expedient than the
130 // refactoring that would be needed to look up the `#[must_use]`
131 // attribute which does exist on the comparison trait methods
132 hir::ExprKind::Binary(bin_op, ..) => match bin_op.node {
138 | hir::BinOpKind::Gt => Some("comparison"),
140 | hir::BinOpKind::Sub
141 | hir::BinOpKind::Div
142 | hir::BinOpKind::Mul
143 | hir::BinOpKind::Rem => Some("arithmetic operation"),
144 hir::BinOpKind::And | hir::BinOpKind::Or => Some("logical operation"),
145 hir::BinOpKind::BitXor
146 | hir::BinOpKind::BitAnd
147 | hir::BinOpKind::BitOr
148 | hir::BinOpKind::Shl
149 | hir::BinOpKind::Shr => Some("bitwise operation"),
151 hir::ExprKind::AddrOf(..) => Some("borrow"),
152 hir::ExprKind::Unary(..) => Some("unary operation"),
156 if let Some(must_use_op) = must_use_op {
157 cx.struct_span_lint(UNUSED_MUST_USE, expr.span, |lint| {
158 let mut lint = lint.build(&format!("unused {} that must be used", must_use_op));
159 lint.span_label(expr.span, &format!("the {} produces a value", must_use_op));
160 lint.span_suggestion_verbose(
161 expr.span.shrink_to_lo(),
162 "use `let _ = ...` to ignore the resulting value",
163 "let _ = ".to_string(),
164 Applicability::MachineApplicable,
171 if !(type_permits_lack_of_use || fn_warned || op_warned) {
172 cx.struct_span_lint(UNUSED_RESULTS, s.span, |lint| {
173 lint.build(&format!("unused result of type `{}`", ty)).emit()
177 // Returns whether an error has been emitted (and thus another does not need to be later).
178 fn check_must_use_ty<'tcx>(
179 cx: &LateContext<'tcx>,
181 expr: &hir::Expr<'_>,
188 || cx.tcx.is_ty_uninhabited_from(
189 cx.tcx.parent_module(expr.hir_id).to_def_id(),
197 let plural_suffix = pluralize!(plural_len);
200 ty::Adt(..) if ty.is_box() => {
201 let boxed_ty = ty.boxed_ty();
202 let descr_pre = &format!("{}boxed ", descr_pre);
203 check_must_use_ty(cx, boxed_ty, expr, span, descr_pre, descr_post, plural_len)
205 ty::Adt(def, _) => check_must_use_def(cx, def.did, span, descr_pre, descr_post),
206 ty::Opaque(def, _) => {
207 let mut has_emitted = false;
208 for &(predicate, _) in cx.tcx.explicit_item_bounds(def) {
209 // We only look at the `DefId`, so it is safe to skip the binder here.
210 if let ty::PredicateKind::Trait(ref poly_trait_predicate) =
211 predicate.kind().skip_binder()
213 let def_id = poly_trait_predicate.trait_ref.def_id;
215 &format!("{}implementer{} of ", descr_pre, plural_suffix,);
216 if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
224 ty::Dynamic(binder, _) => {
225 let mut has_emitted = false;
226 for predicate in binder.iter() {
227 if let ty::ExistentialPredicate::Trait(ref trait_ref) =
228 predicate.skip_binder()
230 let def_id = trait_ref.def_id;
232 &format!(" trait object{}{}", plural_suffix, descr_post,);
233 if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
241 ty::Tuple(ref tys) => {
242 let mut has_emitted = false;
243 let spans = if let hir::ExprKind::Tup(comps) = &expr.kind {
244 debug_assert_eq!(comps.len(), tys.len());
245 comps.iter().map(|e| e.span).collect()
249 for (i, ty) in tys.iter().map(|k| k.expect_ty()).enumerate() {
250 let descr_post = &format!(" in tuple element {}", i);
251 let span = *spans.get(i).unwrap_or(&span);
252 if check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, plural_len)
259 ty::Array(ty, len) => match len.try_eval_usize(cx.tcx, cx.param_env) {
260 // If the array is empty we don't lint, to avoid false positives
261 Some(0) | None => false,
262 // If the array is definitely non-empty, we can do `#[must_use]` checking.
264 let descr_pre = &format!("{}array{} of ", descr_pre, plural_suffix,);
265 check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, n as usize + 1)
269 cx.struct_span_lint(UNUSED_MUST_USE, span, |lint| {
270 let mut err = lint.build(&format!(
271 "unused {}closure{}{} that must be used",
272 descr_pre, plural_suffix, descr_post,
274 err.note("closures are lazy and do nothing unless called");
279 ty::Generator(..) => {
280 cx.struct_span_lint(UNUSED_MUST_USE, span, |lint| {
281 let mut err = lint.build(&format!(
282 "unused {}generator{}{} that must be used",
283 descr_pre, plural_suffix, descr_post,
285 err.note("generators are lazy and do nothing unless resumed");
294 // Returns whether an error has been emitted (and thus another does not need to be later).
295 // FIXME: Args desc_{pre,post}_path could be made lazy by taking Fn() -> &str, but this
296 // would make calling it a big awkward. Could also take String (so args are moved), but
297 // this would still require a copy into the format string, which would only be executed
299 fn check_must_use_def(
300 cx: &LateContext<'_>,
303 descr_pre_path: &str,
304 descr_post_path: &str,
306 for attr in cx.tcx.get_attrs(def_id).iter() {
307 if attr.has_name(sym::must_use) {
308 cx.struct_span_lint(UNUSED_MUST_USE, span, |lint| {
310 "unused {}`{}`{} that must be used",
312 cx.tcx.def_path_str(def_id),
315 let mut err = lint.build(&msg);
316 // check for #[must_use = "..."]
317 if let Some(note) = attr.value_str() {
318 err.note(note.as_str());
331 /// The `path_statements` lint detects path statements with no effect.
345 /// It is usually a mistake to have a statement that has no effect.
348 "path statements with no effect"
351 declare_lint_pass!(PathStatements => [PATH_STATEMENTS]);
353 impl<'tcx> LateLintPass<'tcx> for PathStatements {
354 fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
355 if let hir::StmtKind::Semi(expr) = s.kind {
356 if let hir::ExprKind::Path(_) = expr.kind {
357 cx.struct_span_lint(PATH_STATEMENTS, s.span, |lint| {
358 let ty = cx.typeck_results().expr_ty(expr);
359 if ty.needs_drop(cx.tcx, cx.param_env) {
360 let mut lint = lint.build("path statement drops value");
361 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(expr.span) {
362 lint.span_suggestion(
364 "use `drop` to clarify the intent",
365 format!("drop({});", snippet),
366 Applicability::MachineApplicable,
369 lint.span_help(s.span, "use `drop` to clarify the intent");
373 lint.build("path statement with no effect").emit()
381 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
382 enum UnusedDelimsCtx {
386 AssignedValueLetElse,
398 impl From<UnusedDelimsCtx> for &'static str {
399 fn from(ctx: UnusedDelimsCtx) -> &'static str {
401 UnusedDelimsCtx::FunctionArg => "function argument",
402 UnusedDelimsCtx::MethodArg => "method argument",
403 UnusedDelimsCtx::AssignedValue | UnusedDelimsCtx::AssignedValueLetElse => {
406 UnusedDelimsCtx::IfCond => "`if` condition",
407 UnusedDelimsCtx::WhileCond => "`while` condition",
408 UnusedDelimsCtx::ForIterExpr => "`for` iterator expression",
409 UnusedDelimsCtx::MatchScrutineeExpr => "`match` scrutinee expression",
410 UnusedDelimsCtx::ReturnValue => "`return` value",
411 UnusedDelimsCtx::BlockRetValue => "block return value",
412 UnusedDelimsCtx::LetScrutineeExpr => "`let` scrutinee expression",
413 UnusedDelimsCtx::ArrayLenExpr | UnusedDelimsCtx::AnonConst => "const expression",
418 /// Used by both `UnusedParens` and `UnusedBraces` to prevent code duplication.
419 trait UnusedDelimLint {
420 const DELIM_STR: &'static str;
422 /// Due to `ref` pattern, there can be a difference between using
423 /// `{ expr }` and `expr` in pattern-matching contexts. This means
424 /// that we should only lint `unused_parens` and not `unused_braces`
429 /// let ref b = { a }; // We actually borrow a copy of `a` here.
430 /// a += 1; // By mutating `a` we invalidate any borrows of `a`.
431 /// assert_eq!(b + 1, a); // `b` does not borrow `a`, so we can still use it here.
433 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool;
435 // this cannot be a constant is it refers to a static.
436 fn lint(&self) -> &'static Lint;
438 fn check_unused_delims_expr(
440 cx: &EarlyContext<'_>,
442 ctx: UnusedDelimsCtx,
443 followed_by_block: bool,
444 left_pos: Option<BytePos>,
445 right_pos: Option<BytePos>,
448 fn is_expr_delims_necessary(
450 followed_by_block: bool,
451 followed_by_else: bool,
453 if followed_by_else {
455 ast::ExprKind::Binary(op, ..) if op.node.lazy() => return true,
456 _ if classify::expr_trailing_brace(inner).is_some() => return true,
461 // Prevent false-positives in cases like `fn x() -> u8 { ({ 0 } + 1) }`
462 let lhs_needs_parens = {
463 let mut innermost = inner;
465 innermost = match &innermost.kind {
466 ExprKind::Binary(_, lhs, _rhs) => lhs,
467 ExprKind::Call(fn_, _params) => fn_,
468 ExprKind::Cast(expr, _ty) => expr,
469 ExprKind::Type(expr, _ty) => expr,
470 ExprKind::Index(base, _subscript) => base,
473 if !classify::expr_requires_semi_to_be_stmt(innermost) {
480 || (followed_by_block
481 && match &inner.kind {
482 ExprKind::Ret(_) | ExprKind::Break(..) | ExprKind::Yield(..) => true,
483 ExprKind::Range(_lhs, Some(rhs), _limits) => {
484 matches!(rhs.kind, ExprKind::Block(..))
486 _ => parser::contains_exterior_struct_lit(&inner),
490 fn emit_unused_delims_expr(
492 cx: &EarlyContext<'_>,
494 ctx: UnusedDelimsCtx,
495 left_pos: Option<BytePos>,
496 right_pos: Option<BytePos>,
498 let spans = match value.kind {
499 ast::ExprKind::Block(ref block, None) if block.stmts.len() > 0 => {
500 let start = block.stmts[0].span;
501 let end = block.stmts[block.stmts.len() - 1].span;
502 if value.span.from_expansion() || start.from_expansion() || end.from_expansion() {
504 value.span.with_hi(value.span.lo() + BytePos(1)),
505 value.span.with_lo(value.span.hi() - BytePos(1)),
508 (value.span.with_hi(start.lo()), value.span.with_lo(end.hi()))
511 ast::ExprKind::Paren(ref expr) => {
512 if value.span.from_expansion() || expr.span.from_expansion() {
514 value.span.with_hi(value.span.lo() + BytePos(1)),
515 value.span.with_lo(value.span.hi() - BytePos(1)),
518 (value.span.with_hi(expr.span.lo()), value.span.with_lo(expr.span.hi()))
524 left_pos.map_or(false, |s| s >= value.span.lo()),
525 right_pos.map_or(false, |s| s <= value.span.hi()),
527 self.emit_unused_delims(cx, spans, ctx.into(), keep_space);
530 fn emit_unused_delims(
532 cx: &EarlyContext<'_>,
535 keep_space: (bool, bool),
537 // FIXME(flip1995): Quick and dirty fix for #70814. This should be fixed in rustdoc
539 if spans.0 == DUMMY_SP || spans.1 == DUMMY_SP {
543 cx.struct_span_lint(self.lint(), MultiSpan::from(vec![spans.0, spans.1]), |lint| {
544 let span_msg = format!("unnecessary {} around {}", Self::DELIM_STR, msg);
545 let mut err = lint.build(&span_msg);
546 let replacement = vec![
547 (spans.0, if keep_space.0 { " ".into() } else { "".into() }),
548 (spans.1, if keep_space.1 { " ".into() } else { "".into() }),
550 let suggestion = format!("remove these {}", Self::DELIM_STR);
551 err.multipart_suggestion(&suggestion, replacement, Applicability::MachineApplicable);
556 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
557 use rustc_ast::ExprKind::*;
558 let (value, ctx, followed_by_block, left_pos, right_pos) = match e.kind {
559 // Do not lint `unused_braces` in `if let` expressions.
560 If(ref cond, ref block, _)
561 if !matches!(cond.kind, Let(_, _, _))
562 || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
564 let left = e.span.lo() + rustc_span::BytePos(2);
565 let right = block.span.lo();
566 (cond, UnusedDelimsCtx::IfCond, true, Some(left), Some(right))
569 // Do not lint `unused_braces` in `while let` expressions.
570 While(ref cond, ref block, ..)
571 if !matches!(cond.kind, Let(_, _, _))
572 || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
574 let left = e.span.lo() + rustc_span::BytePos(5);
575 let right = block.span.lo();
576 (cond, UnusedDelimsCtx::WhileCond, true, Some(left), Some(right))
579 ForLoop(_, ref cond, ref block, ..) => {
580 (cond, UnusedDelimsCtx::ForIterExpr, true, None, Some(block.span.lo()))
583 Match(ref head, _) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
584 let left = e.span.lo() + rustc_span::BytePos(5);
585 (head, UnusedDelimsCtx::MatchScrutineeExpr, true, Some(left), None)
588 Ret(Some(ref value)) => {
589 let left = e.span.lo() + rustc_span::BytePos(3);
590 (value, UnusedDelimsCtx::ReturnValue, false, Some(left), None)
593 Assign(_, ref value, _) | AssignOp(.., ref value) => {
594 (value, UnusedDelimsCtx::AssignedValue, false, None, None)
596 // either function/method call, or something this lint doesn't care about
597 ref call_or_other => {
598 let (args_to_check, ctx) = match *call_or_other {
599 Call(_, ref args) => (&args[..], UnusedDelimsCtx::FunctionArg),
600 // first "argument" is self (which sometimes needs delims)
601 MethodCall(_, ref args, _) => (&args[1..], UnusedDelimsCtx::MethodArg),
602 // actual catch-all arm
607 // Don't lint if this is a nested macro expansion: otherwise, the lint could
608 // trigger in situations that macro authors shouldn't have to care about, e.g.,
609 // when a parenthesized token tree matched in one macro expansion is matched as
610 // an expression in another and used as a fn/method argument (Issue #47775)
611 if e.span.ctxt().outer_expn_data().call_site.from_expansion() {
614 for arg in args_to_check {
615 self.check_unused_delims_expr(cx, arg, ctx, false, None, None);
620 self.check_unused_delims_expr(cx, &value, ctx, followed_by_block, left_pos, right_pos);
623 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
625 StmtKind::Local(ref local) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
626 if let Some((init, els)) = local.kind.init_else_opt() {
627 let ctx = match els {
628 None => UnusedDelimsCtx::AssignedValue,
629 Some(_) => UnusedDelimsCtx::AssignedValueLetElse,
631 self.check_unused_delims_expr(cx, init, ctx, false, None, None);
634 StmtKind::Expr(ref expr) => {
635 self.check_unused_delims_expr(
638 UnusedDelimsCtx::BlockRetValue,
648 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
649 use ast::ItemKind::*;
651 if let Const(.., Some(expr)) | Static(.., Some(expr)) = &item.kind {
652 self.check_unused_delims_expr(
655 UnusedDelimsCtx::AssignedValue,
665 /// The `unused_parens` lint detects `if`, `match`, `while` and `return`
666 /// with parentheses; they do not need them.
678 /// The parentheses are not needed, and should be removed. This is the
679 /// preferred style for writing these expressions.
680 pub(super) UNUSED_PARENS,
682 "`if`, `match`, `while` and `return` do not need parentheses"
685 declare_lint_pass!(UnusedParens => [UNUSED_PARENS]);
687 impl UnusedDelimLint for UnusedParens {
688 const DELIM_STR: &'static str = "parentheses";
690 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = true;
692 fn lint(&self) -> &'static Lint {
696 fn check_unused_delims_expr(
698 cx: &EarlyContext<'_>,
700 ctx: UnusedDelimsCtx,
701 followed_by_block: bool,
702 left_pos: Option<BytePos>,
703 right_pos: Option<BytePos>,
706 ast::ExprKind::Paren(ref inner) => {
707 let followed_by_else = ctx == UnusedDelimsCtx::AssignedValueLetElse;
708 if !Self::is_expr_delims_necessary(inner, followed_by_block, followed_by_else)
709 && value.attrs.is_empty()
710 && !value.span.from_expansion()
711 && (ctx != UnusedDelimsCtx::LetScrutineeExpr
712 || !matches!(inner.kind, ast::ExprKind::Binary(
713 rustc_span::source_map::Spanned { node, .. },
718 self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
721 ast::ExprKind::Let(_, ref expr, _) => {
722 self.check_unused_delims_expr(
725 UnusedDelimsCtx::LetScrutineeExpr,
737 fn check_unused_parens_pat(
739 cx: &EarlyContext<'_>,
744 use ast::{BindingMode, Mutability, PatKind};
746 if let PatKind::Paren(inner) = &value.kind {
748 // The lint visitor will visit each subpattern of `p`. We do not want to lint
749 // any range pattern no matter where it occurs in the pattern. For something like
750 // `&(a..=b)`, there is a recursive `check_pat` on `a` and `b`, but we will assume
751 // that if there are unnecessary parens they serve a purpose of readability.
752 PatKind::Range(..) => return,
753 // Avoid `p0 | .. | pn` if we should.
754 PatKind::Or(..) if avoid_or => return,
755 // Avoid `mut x` and `mut x @ p` if we should:
756 PatKind::Ident(BindingMode::ByValue(Mutability::Mut), ..) if avoid_mut => return,
757 // Otherwise proceed with linting.
760 let spans = if value.span.from_expansion() || inner.span.from_expansion() {
762 value.span.with_hi(value.span.lo() + BytePos(1)),
763 value.span.with_lo(value.span.hi() - BytePos(1)),
766 (value.span.with_hi(inner.span.lo()), value.span.with_lo(inner.span.hi()))
768 self.emit_unused_delims(cx, spans, "pattern", (false, false));
773 impl EarlyLintPass for UnusedParens {
774 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
776 ExprKind::Let(ref pat, _, _) | ExprKind::ForLoop(ref pat, ..) => {
777 self.check_unused_parens_pat(cx, pat, false, false);
779 // We ignore parens in cases like `if (((let Some(0) = Some(1))))` because we already
780 // handle a hard error for them during AST lowering in `lower_expr_mut`, but we still
781 // want to complain about things like `if let 42 = (42)`.
782 ExprKind::If(ref cond, ref block, ref else_)
783 if matches!(cond.peel_parens().kind, ExprKind::Let(..)) =>
785 self.check_unused_delims_expr(
788 UnusedDelimsCtx::LetScrutineeExpr,
793 for stmt in &block.stmts {
794 <Self as UnusedDelimLint>::check_stmt(self, cx, stmt);
796 if let Some(e) = else_ {
797 <Self as UnusedDelimLint>::check_expr(self, cx, e);
804 <Self as UnusedDelimLint>::check_expr(self, cx, e)
807 fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
808 use ast::{Mutability, PatKind::*};
810 // Do not lint on `(..)` as that will result in the other arms being useless.
812 // The other cases do not contain sub-patterns.
813 | Wild | Rest | Lit(..) | MacCall(..) | Range(..) | Ident(.., None) | Path(..) => {},
814 // These are list-like patterns; parens can always be removed.
815 TupleStruct(_, _, ps) | Tuple(ps) | Slice(ps) | Or(ps) => for p in ps {
816 self.check_unused_parens_pat(cx, p, false, false);
818 Struct(_, _, fps, _) => for f in fps {
819 self.check_unused_parens_pat(cx, &f.pat, false, false);
821 // Avoid linting on `i @ (p0 | .. | pn)` and `box (p0 | .. | pn)`, #64106.
822 Ident(.., Some(p)) | Box(p) => self.check_unused_parens_pat(cx, p, true, false),
823 // Avoid linting on `&(mut x)` as `&mut x` has a different meaning, #55342.
824 // Also avoid linting on `& mut? (p0 | .. | pn)`, #64106.
825 Ref(p, m) => self.check_unused_parens_pat(cx, p, true, *m == Mutability::Not),
829 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
830 if let StmtKind::Local(ref local) = s.kind {
831 self.check_unused_parens_pat(cx, &local.pat, true, false);
834 <Self as UnusedDelimLint>::check_stmt(self, cx, s)
837 fn check_param(&mut self, cx: &EarlyContext<'_>, param: &ast::Param) {
838 self.check_unused_parens_pat(cx, ¶m.pat, true, false);
841 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
842 self.check_unused_parens_pat(cx, &arm.pat, false, false);
845 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
846 if let ast::TyKind::Paren(r) = &ty.kind {
848 ast::TyKind::TraitObject(..) => {}
849 ast::TyKind::ImplTrait(_, bounds) if bounds.len() > 1 => {}
850 ast::TyKind::Array(_, len) => {
851 self.check_unused_delims_expr(
854 UnusedDelimsCtx::ArrayLenExpr,
861 let spans = if ty.span.from_expansion() || r.span.from_expansion() {
863 ty.span.with_hi(ty.span.lo() + BytePos(1)),
864 ty.span.with_lo(ty.span.hi() - BytePos(1)),
867 (ty.span.with_hi(r.span.lo()), ty.span.with_lo(r.span.hi()))
869 self.emit_unused_delims(cx, spans, "type", (false, false));
875 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
876 <Self as UnusedDelimLint>::check_item(self, cx, item)
881 /// The `unused_braces` lint detects unnecessary braces around an
896 /// The braces are not needed, and should be removed. This is the
897 /// preferred style for writing these expressions.
898 pub(super) UNUSED_BRACES,
900 "unnecessary braces around an expression"
903 declare_lint_pass!(UnusedBraces => [UNUSED_BRACES]);
905 impl UnusedDelimLint for UnusedBraces {
906 const DELIM_STR: &'static str = "braces";
908 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = false;
910 fn lint(&self) -> &'static Lint {
914 fn check_unused_delims_expr(
916 cx: &EarlyContext<'_>,
918 ctx: UnusedDelimsCtx,
919 followed_by_block: bool,
920 left_pos: Option<BytePos>,
921 right_pos: Option<BytePos>,
924 ast::ExprKind::Block(ref inner, None)
925 if inner.rules == ast::BlockCheckMode::Default =>
927 // emit a warning under the following conditions:
929 // - the block does not have a label
930 // - the block is not `unsafe`
931 // - the block contains exactly one expression (do not lint `{ expr; }`)
932 // - `followed_by_block` is true and the internal expr may contain a `{`
933 // - the block is not multiline (do not lint multiline match arms)
937 // somewhat_long_expression
942 // - the block has no attribute and was not created inside a macro
943 // - if the block is an `anon_const`, the inner expr must be a literal
944 // (do not lint `struct A<const N: usize>; let _: A<{ 2 + 3 }>;`)
946 // FIXME(const_generics): handle paths when #67075 is fixed.
947 if let [stmt] = inner.stmts.as_slice() {
948 if let ast::StmtKind::Expr(ref expr) = stmt.kind {
949 if !Self::is_expr_delims_necessary(expr, followed_by_block, false)
950 && (ctx != UnusedDelimsCtx::AnonConst
951 || matches!(expr.kind, ast::ExprKind::Lit(_)))
952 && !cx.sess().source_map().is_multiline(value.span)
953 && value.attrs.is_empty()
954 && !value.span.from_expansion()
956 self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
961 ast::ExprKind::Let(_, ref expr, _) => {
962 self.check_unused_delims_expr(
965 UnusedDelimsCtx::LetScrutineeExpr,
976 impl EarlyLintPass for UnusedBraces {
977 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
978 <Self as UnusedDelimLint>::check_stmt(self, cx, s)
981 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
982 <Self as UnusedDelimLint>::check_expr(self, cx, e);
984 if let ExprKind::Repeat(_, ref anon_const) = e.kind {
985 self.check_unused_delims_expr(
988 UnusedDelimsCtx::AnonConst,
996 fn check_generic_arg(&mut self, cx: &EarlyContext<'_>, arg: &ast::GenericArg) {
997 if let ast::GenericArg::Const(ct) = arg {
998 self.check_unused_delims_expr(
1001 UnusedDelimsCtx::AnonConst,
1009 fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant) {
1010 if let Some(anon_const) = &v.disr_expr {
1011 self.check_unused_delims_expr(
1014 UnusedDelimsCtx::AnonConst,
1022 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
1024 ast::TyKind::Array(_, ref len) => {
1025 self.check_unused_delims_expr(
1028 UnusedDelimsCtx::ArrayLenExpr,
1035 ast::TyKind::Typeof(ref anon_const) => {
1036 self.check_unused_delims_expr(
1039 UnusedDelimsCtx::AnonConst,
1050 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1051 <Self as UnusedDelimLint>::check_item(self, cx, item)
1056 /// The `unused_import_braces` lint catches unnecessary braces around an
1061 /// ```rust,compile_fail
1062 /// #![deny(unused_import_braces)]
1075 /// If there is only a single item, then remove the braces (`use test::A;`
1078 /// This lint is "allow" by default because it is only enforcing a
1079 /// stylistic choice.
1080 UNUSED_IMPORT_BRACES,
1082 "unnecessary braces around an imported item"
1085 declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]);
1087 impl UnusedImportBraces {
1088 fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
1089 if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
1090 // Recursively check nested UseTrees
1091 for &(ref tree, _) in items {
1092 self.check_use_tree(cx, tree, item);
1095 // Trigger the lint only if there is one nested item
1096 if items.len() != 1 {
1100 // Trigger the lint if the nested item is a non-self single item
1101 let node_name = match items[0].0.kind {
1102 ast::UseTreeKind::Simple(rename, ..) => {
1103 let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
1104 if orig_ident.name == kw::SelfLower {
1107 rename.unwrap_or(orig_ident).name
1109 ast::UseTreeKind::Glob => Symbol::intern("*"),
1110 ast::UseTreeKind::Nested(_) => return,
1113 cx.struct_span_lint(UNUSED_IMPORT_BRACES, item.span, |lint| {
1114 lint.build(&format!("braces around {} is unnecessary", node_name)).emit()
1120 impl EarlyLintPass for UnusedImportBraces {
1121 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1122 if let ast::ItemKind::Use(ref use_tree) = item.kind {
1123 self.check_use_tree(cx, use_tree, item);
1129 /// The `unused_allocation` lint detects unnecessary allocations that can
1135 /// #![feature(box_syntax)]
1137 /// let a = (box [1, 2, 3]).len();
1145 /// When a `box` expression is immediately coerced to a reference, then
1146 /// the allocation is unnecessary, and a reference (using `&` or `&mut`)
1147 /// should be used instead to avoid the allocation.
1148 pub(super) UNUSED_ALLOCATION,
1150 "detects unnecessary allocations that can be eliminated"
1153 declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]);
1155 impl<'tcx> LateLintPass<'tcx> for UnusedAllocation {
1156 fn check_expr(&mut self, cx: &LateContext<'_>, e: &hir::Expr<'_>) {
1158 hir::ExprKind::Box(_) => {}
1162 for adj in cx.typeck_results().expr_adjustments(e) {
1163 if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
1164 cx.struct_span_lint(UNUSED_ALLOCATION, e.span, |lint| {
1166 adjustment::AutoBorrowMutability::Not => {
1167 "unnecessary allocation, use `&` instead"
1169 adjustment::AutoBorrowMutability::Mut { .. } => {
1170 "unnecessary allocation, use `&mut` instead"
1173 lint.build(msg).emit()