2 use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
4 use rustc_ast::util::parser;
5 use rustc_ast::{ExprKind, StmtKind};
6 use rustc_ast_pretty::pprust;
7 use rustc_data_structures::fx::FxHashMap;
8 use rustc_errors::{pluralize, Applicability};
9 use rustc_feature::{AttributeType, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP};
11 use rustc_hir::def::{DefKind, Res};
12 use rustc_hir::def_id::DefId;
13 use rustc_middle::ty::adjustment;
14 use rustc_middle::ty::{self, Ty};
15 use rustc_session::lint::builtin::UNUSED_ATTRIBUTES;
16 use rustc_span::symbol::Symbol;
17 use rustc_span::symbol::{kw, sym};
18 use rustc_span::{BytePos, Span, DUMMY_SP};
23 /// The `unused_must_use` lint detects unused result of a type flagged as
29 /// fn returns_result() -> Result<(), ()> {
42 /// The `#[must_use]` attribute is an indicator that it is a mistake to
43 /// ignore the value. See [the reference] for more details.
45 /// [the reference]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
48 "unused result of a type flagged as `#[must_use]`",
49 report_in_external_macro
53 /// The `unused_results` lint checks for the unused result of an
54 /// expression in a statement.
58 /// ```rust,compile_fail
59 /// #![deny(unused_results)]
60 /// fn foo<T>() -> T { panic!() }
71 /// Ignoring the return value of a function may indicate a mistake. In
72 /// cases were it is almost certain that the result should be used, it is
73 /// recommended to annotate the function with the [`must_use` attribute].
74 /// Failure to use such a return value will trigger the [`unused_must_use`
75 /// lint] which is warn-by-default. The `unused_results` lint is
76 /// essentially the same, but triggers for *all* return values.
78 /// This lint is "allow" by default because it can be noisy, and may not be
79 /// an actual problem. For example, calling the `remove` method of a `Vec`
80 /// or `HashMap` returns the previous value, which you may not care about.
81 /// Using this lint would require explicitly ignoring or discarding such
84 /// [`must_use` attribute]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
85 /// [`unused_must_use` lint]: warn-by-default.html#unused-must-use
88 "unused result of an expression in a statement"
91 declare_lint_pass!(UnusedResults => [UNUSED_MUST_USE, UNUSED_RESULTS]);
93 impl<'tcx> LateLintPass<'tcx> for UnusedResults {
94 fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
95 let expr = match s.kind {
96 hir::StmtKind::Semi(ref expr) => &**expr,
100 if let hir::ExprKind::Ret(..) = expr.kind {
104 let ty = cx.typeck_results().expr_ty(&expr);
105 let type_permits_lack_of_use = check_must_use_ty(cx, ty, &expr, s.span, "", "", 1);
107 let mut fn_warned = false;
108 let mut op_warned = false;
109 let maybe_def_id = match expr.kind {
110 hir::ExprKind::Call(ref callee, _) => {
112 hir::ExprKind::Path(ref qpath) => {
113 match cx.qpath_res(qpath, callee.hir_id) {
114 Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) => Some(def_id),
115 // `Res::Local` if it was a closure, for which we
116 // do not currently support must-use linting
123 hir::ExprKind::MethodCall(..) => cx.typeck_results().type_dependent_def_id(expr.hir_id),
126 if let Some(def_id) = maybe_def_id {
127 fn_warned = check_must_use_def(cx, def_id, s.span, "return value of ", "");
128 } else if type_permits_lack_of_use {
129 // We don't warn about unused unit or uninhabited types.
130 // (See https://github.com/rust-lang/rust/issues/43806 for details.)
134 let must_use_op = match expr.kind {
135 // Hardcoding operators here seemed more expedient than the
136 // refactoring that would be needed to look up the `#[must_use]`
137 // attribute which does exist on the comparison trait methods
138 hir::ExprKind::Binary(bin_op, ..) => match bin_op.node {
144 | hir::BinOpKind::Gt => Some("comparison"),
146 | hir::BinOpKind::Sub
147 | hir::BinOpKind::Div
148 | hir::BinOpKind::Mul
149 | hir::BinOpKind::Rem => Some("arithmetic operation"),
150 hir::BinOpKind::And | hir::BinOpKind::Or => Some("logical operation"),
151 hir::BinOpKind::BitXor
152 | hir::BinOpKind::BitAnd
153 | hir::BinOpKind::BitOr
154 | hir::BinOpKind::Shl
155 | hir::BinOpKind::Shr => Some("bitwise operation"),
157 hir::ExprKind::AddrOf(..) => Some("borrow"),
158 hir::ExprKind::Unary(..) => Some("unary operation"),
162 if let Some(must_use_op) = must_use_op {
163 cx.struct_span_lint(UNUSED_MUST_USE, expr.span, |lint| {
164 let mut lint = lint.build(&format!("unused {} that must be used", must_use_op));
165 lint.span_label(expr.span, &format!("the {} produces a value", must_use_op));
166 lint.span_suggestion_verbose(
167 expr.span.shrink_to_lo(),
168 "use `let _ = ...` to ignore the resulting value",
169 "let _ = ".to_string(),
170 Applicability::MachineApplicable,
177 if !(type_permits_lack_of_use || fn_warned || op_warned) {
178 cx.struct_span_lint(UNUSED_RESULTS, s.span, |lint| lint.build("unused result").emit());
181 // Returns whether an error has been emitted (and thus another does not need to be later).
182 fn check_must_use_ty<'tcx>(
183 cx: &LateContext<'tcx>,
185 expr: &hir::Expr<'_>,
192 || cx.tcx.is_ty_uninhabited_from(
193 cx.tcx.parent_module(expr.hir_id).to_def_id(),
201 let plural_suffix = pluralize!(plural_len);
204 ty::Adt(..) if ty.is_box() => {
205 let boxed_ty = ty.boxed_ty();
206 let descr_pre = &format!("{}boxed ", descr_pre);
207 check_must_use_ty(cx, boxed_ty, expr, span, descr_pre, descr_post, plural_len)
209 ty::Adt(def, _) => check_must_use_def(cx, def.did, span, descr_pre, descr_post),
210 ty::Opaque(def, _) => {
211 let mut has_emitted = false;
212 for &(predicate, _) in cx.tcx.explicit_item_bounds(def) {
213 // We only look at the `DefId`, so it is safe to skip the binder here.
214 if let ty::PredicateKind::Trait(ref poly_trait_predicate) =
215 predicate.kind().skip_binder()
217 let def_id = poly_trait_predicate.trait_ref.def_id;
219 &format!("{}implementer{} of ", descr_pre, plural_suffix,);
220 if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
228 ty::Dynamic(binder, _) => {
229 let mut has_emitted = false;
230 for predicate in binder.iter() {
231 if let ty::ExistentialPredicate::Trait(ref trait_ref) =
232 predicate.skip_binder()
234 let def_id = trait_ref.def_id;
236 &format!(" trait object{}{}", plural_suffix, descr_post,);
237 if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
245 ty::Tuple(ref tys) => {
246 let mut has_emitted = false;
247 let spans = if let hir::ExprKind::Tup(comps) = &expr.kind {
248 debug_assert_eq!(comps.len(), tys.len());
249 comps.iter().map(|e| e.span).collect()
253 for (i, ty) in tys.iter().map(|k| k.expect_ty()).enumerate() {
254 let descr_post = &format!(" in tuple element {}", i);
255 let span = *spans.get(i).unwrap_or(&span);
256 if check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, plural_len)
263 ty::Array(ty, len) => match len.try_eval_usize(cx.tcx, cx.param_env) {
264 // If the array is empty we don't lint, to avoid false positives
265 Some(0) | None => false,
266 // If the array is definitely non-empty, we can do `#[must_use]` checking.
268 let descr_pre = &format!("{}array{} of ", descr_pre, plural_suffix,);
269 check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, n as usize + 1)
273 cx.struct_span_lint(UNUSED_MUST_USE, span, |lint| {
274 let mut err = lint.build(&format!(
275 "unused {}closure{}{} that must be used",
276 descr_pre, plural_suffix, descr_post,
278 err.note("closures are lazy and do nothing unless called");
283 ty::Generator(..) => {
284 cx.struct_span_lint(UNUSED_MUST_USE, span, |lint| {
285 let mut err = lint.build(&format!(
286 "unused {}generator{}{} that must be used",
287 descr_pre, plural_suffix, descr_post,
289 err.note("generators are lazy and do nothing unless resumed");
298 // Returns whether an error has been emitted (and thus another does not need to be later).
299 // FIXME: Args desc_{pre,post}_path could be made lazy by taking Fn() -> &str, but this
300 // would make calling it a big awkward. Could also take String (so args are moved), but
301 // this would still require a copy into the format string, which would only be executed
303 fn check_must_use_def(
304 cx: &LateContext<'_>,
307 descr_pre_path: &str,
308 descr_post_path: &str,
310 for attr in cx.tcx.get_attrs(def_id).iter() {
311 if cx.sess().check_name(attr, sym::must_use) {
312 cx.struct_span_lint(UNUSED_MUST_USE, span, |lint| {
314 "unused {}`{}`{} that must be used",
316 cx.tcx.def_path_str(def_id),
319 let mut err = lint.build(&msg);
320 // check for #[must_use = "..."]
321 if let Some(note) = attr.value_str() {
322 err.note(¬e.as_str());
335 /// The `path_statements` lint detects path statements with no effect.
349 /// It is usually a mistake to have a statement that has no effect.
352 "path statements with no effect"
355 declare_lint_pass!(PathStatements => [PATH_STATEMENTS]);
357 impl<'tcx> LateLintPass<'tcx> for PathStatements {
358 fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
359 if let hir::StmtKind::Semi(expr) = s.kind {
360 if let hir::ExprKind::Path(_) = expr.kind {
361 cx.struct_span_lint(PATH_STATEMENTS, s.span, |lint| {
362 let ty = cx.typeck_results().expr_ty(expr);
363 if ty.needs_drop(cx.tcx, cx.param_env) {
364 let mut lint = lint.build("path statement drops value");
365 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(expr.span) {
366 lint.span_suggestion(
368 "use `drop` to clarify the intent",
369 format!("drop({});", snippet),
370 Applicability::MachineApplicable,
373 lint.span_help(s.span, "use `drop` to clarify the intent");
377 lint.build("path statement with no effect").emit()
385 #[derive(Copy, Clone)]
386 pub struct UnusedAttributes {
387 builtin_attributes: &'static FxHashMap<Symbol, &'static BuiltinAttribute>,
390 impl UnusedAttributes {
391 pub fn new() -> Self {
392 UnusedAttributes { builtin_attributes: &*BUILTIN_ATTRIBUTE_MAP }
396 impl_lint_pass!(UnusedAttributes => [UNUSED_ATTRIBUTES]);
398 impl<'tcx> LateLintPass<'tcx> for UnusedAttributes {
399 fn check_attribute(&mut self, cx: &LateContext<'_>, attr: &ast::Attribute) {
400 debug!("checking attribute: {:?}", attr);
402 if attr.is_doc_comment() {
406 let attr_info = attr.ident().and_then(|ident| self.builtin_attributes.get(&ident.name));
408 if let Some(&&(name, ty, ..)) = attr_info {
409 if let AttributeType::AssumedUsed = ty {
410 debug!("{:?} is AssumedUsed", name);
415 if !cx.sess().is_attr_used(attr) {
416 debug!("emitting warning for: {:?}", attr);
417 cx.struct_span_lint(UNUSED_ATTRIBUTES, attr.span, |lint| {
418 // Mark as used to avoid duplicate warnings.
419 cx.sess().mark_attr_used(attr);
420 lint.build("unused attribute").emit()
422 // Is it a builtin attribute that must be used at the crate level?
423 if attr_info.map_or(false, |(_, ty, ..)| ty == &AttributeType::CrateLevel) {
424 cx.struct_span_lint(UNUSED_ATTRIBUTES, attr.span, |lint| {
425 let msg = match attr.style {
426 ast::AttrStyle::Outer => {
427 "crate-level attribute should be an inner attribute: add an exclamation \
430 ast::AttrStyle::Inner => "crate-level attribute should be in the root module",
432 lint.build(msg).emit()
436 debug!("Attr was used: {:?}", attr);
441 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
442 enum UnusedDelimsCtx {
457 impl From<UnusedDelimsCtx> for &'static str {
458 fn from(ctx: UnusedDelimsCtx) -> &'static str {
460 UnusedDelimsCtx::FunctionArg => "function argument",
461 UnusedDelimsCtx::MethodArg => "method argument",
462 UnusedDelimsCtx::AssignedValue => "assigned value",
463 UnusedDelimsCtx::IfCond => "`if` condition",
464 UnusedDelimsCtx::WhileCond => "`while` condition",
465 UnusedDelimsCtx::ForIterExpr => "`for` iterator expression",
466 UnusedDelimsCtx::MatchScrutineeExpr => "`match` scrutinee expression",
467 UnusedDelimsCtx::ReturnValue => "`return` value",
468 UnusedDelimsCtx::BlockRetValue => "block return value",
469 UnusedDelimsCtx::LetScrutineeExpr => "`let` scrutinee expression",
470 UnusedDelimsCtx::ArrayLenExpr | UnusedDelimsCtx::AnonConst => "const expression",
475 /// Used by both `UnusedParens` and `UnusedBraces` to prevent code duplication.
476 trait UnusedDelimLint {
477 const DELIM_STR: &'static str;
479 /// Due to `ref` pattern, there can be a difference between using
480 /// `{ expr }` and `expr` in pattern-matching contexts. This means
481 /// that we should only lint `unused_parens` and not `unused_braces`
486 /// let ref b = { a }; // We actually borrow a copy of `a` here.
487 /// a += 1; // By mutating `a` we invalidate any borrows of `a`.
488 /// assert_eq!(b + 1, a); // `b` does not borrow `a`, so we can still use it here.
490 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool;
492 // this cannot be a constant is it refers to a static.
493 fn lint(&self) -> &'static Lint;
495 fn check_unused_delims_expr(
497 cx: &EarlyContext<'_>,
499 ctx: UnusedDelimsCtx,
500 followed_by_block: bool,
501 left_pos: Option<BytePos>,
502 right_pos: Option<BytePos>,
505 fn is_expr_delims_necessary(inner: &ast::Expr, followed_by_block: bool) -> bool {
506 // Prevent false-positives in cases like `fn x() -> u8 { ({ 0 } + 1) }`
507 let lhs_needs_parens = {
508 let mut innermost = inner;
510 if let ExprKind::Binary(_, lhs, _rhs) = &innermost.kind {
512 if !rustc_ast::util::classify::expr_requires_semi_to_be_stmt(innermost) {
522 || (followed_by_block
523 && match inner.kind {
524 ExprKind::Ret(_) | ExprKind::Break(..) | ExprKind::Yield(..) => true,
525 _ => parser::contains_exterior_struct_lit(&inner),
529 fn emit_unused_delims_expr(
531 cx: &EarlyContext<'_>,
533 ctx: UnusedDelimsCtx,
534 left_pos: Option<BytePos>,
535 right_pos: Option<BytePos>,
537 let expr_text = if let Ok(snippet) = cx.sess().source_map().span_to_snippet(value.span) {
540 pprust::expr_to_string(value)
543 left_pos.map_or(false, |s| s >= value.span.lo()),
544 right_pos.map_or(false, |s| s <= value.span.hi()),
546 self.emit_unused_delims(cx, value.span, &expr_text, ctx.into(), keep_space);
549 fn emit_unused_delims(
551 cx: &EarlyContext<'_>,
555 keep_space: (bool, bool),
557 // FIXME(flip1995): Quick and dirty fix for #70814. This should be fixed in rustdoc
559 if span == DUMMY_SP {
563 cx.struct_span_lint(self.lint(), span, |lint| {
564 let span_msg = format!("unnecessary {} around {}", Self::DELIM_STR, msg);
565 let mut err = lint.build(&span_msg);
566 let mut ate_left_paren = false;
567 let mut ate_right_paren = false;
568 let parens_removed = pattern
569 .trim_matches(|c| match c {
574 ate_left_paren = true;
582 ate_right_paren = true;
591 let mut replace = if keep_space.0 {
592 let mut s = String::from(" ");
593 s.push_str(parens_removed);
596 String::from(parens_removed)
605 let suggestion = format!("remove these {}", Self::DELIM_STR);
607 err.span_suggestion_short(span, &suggestion, replace, Applicability::MachineApplicable);
612 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
613 use rustc_ast::ExprKind::*;
614 let (value, ctx, followed_by_block, left_pos, right_pos) = match e.kind {
615 // Do not lint `unused_braces` in `if let` expressions.
616 If(ref cond, ref block, _)
617 if !matches!(cond.kind, Let(_, _)) || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
619 let left = e.span.lo() + rustc_span::BytePos(2);
620 let right = block.span.lo();
621 (cond, UnusedDelimsCtx::IfCond, true, Some(left), Some(right))
624 // Do not lint `unused_braces` in `while let` expressions.
625 While(ref cond, ref block, ..)
626 if !matches!(cond.kind, Let(_, _)) || 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 // first "argument" is self (which sometimes needs delims)
655 MethodCall(_, ref args, _) => (&args[1..], UnusedDelimsCtx::MethodArg),
656 // actual catch-all arm
661 // Don't lint if this is a nested macro expansion: otherwise, the lint could
662 // trigger in situations that macro authors shouldn't have to care about, e.g.,
663 // when a parenthesized token tree matched in one macro expansion is matched as
664 // an expression in another and used as a fn/method argument (Issue #47775)
665 if e.span.ctxt().outer_expn_data().call_site.from_expansion() {
668 for arg in args_to_check {
669 self.check_unused_delims_expr(cx, arg, ctx, false, None, None);
674 self.check_unused_delims_expr(cx, &value, ctx, followed_by_block, left_pos, right_pos);
677 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
679 StmtKind::Local(ref local) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
680 if let Some(ref value) = local.init {
681 self.check_unused_delims_expr(
684 UnusedDelimsCtx::AssignedValue,
691 StmtKind::Expr(ref expr) => {
692 self.check_unused_delims_expr(
695 UnusedDelimsCtx::BlockRetValue,
705 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
706 use ast::ItemKind::*;
708 if let Const(.., Some(expr)) | Static(.., Some(expr)) = &item.kind {
709 self.check_unused_delims_expr(
712 UnusedDelimsCtx::AssignedValue,
722 /// The `unused_parens` lint detects `if`, `match`, `while` and `return`
723 /// with parentheses; they do not need them.
735 /// The parenthesis are not needed, and should be removed. This is the
736 /// preferred style for writing these expressions.
737 pub(super) UNUSED_PARENS,
739 "`if`, `match`, `while` and `return` do not need parentheses"
742 declare_lint_pass!(UnusedParens => [UNUSED_PARENS]);
744 impl UnusedDelimLint for UnusedParens {
745 const DELIM_STR: &'static str = "parentheses";
747 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = true;
749 fn lint(&self) -> &'static Lint {
753 fn check_unused_delims_expr(
755 cx: &EarlyContext<'_>,
757 ctx: UnusedDelimsCtx,
758 followed_by_block: bool,
759 left_pos: Option<BytePos>,
760 right_pos: Option<BytePos>,
763 ast::ExprKind::Paren(ref inner) => {
764 if !Self::is_expr_delims_necessary(inner, followed_by_block)
765 && value.attrs.is_empty()
766 && !value.span.from_expansion()
767 && (ctx != UnusedDelimsCtx::LetScrutineeExpr
768 || !matches!(inner.kind, ast::ExprKind::Binary(
769 rustc_span::source_map::Spanned { node, .. },
774 self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
777 ast::ExprKind::Let(_, ref expr) => {
778 self.check_unused_delims_expr(
781 UnusedDelimsCtx::LetScrutineeExpr,
793 fn check_unused_parens_pat(
795 cx: &EarlyContext<'_>,
800 use ast::{BindingMode, Mutability, PatKind};
802 if let PatKind::Paren(inner) = &value.kind {
804 // The lint visitor will visit each subpattern of `p`. We do not want to lint
805 // any range pattern no matter where it occurs in the pattern. For something like
806 // `&(a..=b)`, there is a recursive `check_pat` on `a` and `b`, but we will assume
807 // that if there are unnecessary parens they serve a purpose of readability.
808 PatKind::Range(..) => return,
809 // Avoid `p0 | .. | pn` if we should.
810 PatKind::Or(..) if avoid_or => return,
811 // Avoid `mut x` and `mut x @ p` if we should:
812 PatKind::Ident(BindingMode::ByValue(Mutability::Mut), ..) if avoid_mut => return,
813 // Otherwise proceed with linting.
818 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(value.span) {
821 pprust::pat_to_string(value)
823 self.emit_unused_delims(cx, value.span, &pattern_text, "pattern", (false, false));
828 impl EarlyLintPass for UnusedParens {
829 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
831 ExprKind::Let(ref pat, _) | ExprKind::ForLoop(ref pat, ..) => {
832 self.check_unused_parens_pat(cx, pat, false, false);
834 // We ignore parens in cases like `if (((let Some(0) = Some(1))))` because we already
835 // handle a hard error for them during AST lowering in `lower_expr_mut`, but we still
836 // want to complain about things like `if let 42 = (42)`.
837 ExprKind::If(ref cond, ref block, ref else_)
838 if matches!(cond.peel_parens().kind, ExprKind::Let(..)) =>
840 self.check_unused_delims_expr(
843 UnusedDelimsCtx::LetScrutineeExpr,
848 for stmt in &block.stmts {
849 <Self as UnusedDelimLint>::check_stmt(self, cx, stmt);
851 if let Some(e) = else_ {
852 <Self as UnusedDelimLint>::check_expr(self, cx, e);
859 <Self as UnusedDelimLint>::check_expr(self, cx, e)
862 fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
863 use ast::{Mutability, PatKind::*};
865 // Do not lint on `(..)` as that will result in the other arms being useless.
867 // The other cases do not contain sub-patterns.
868 | Wild | Rest | Lit(..) | MacCall(..) | Range(..) | Ident(.., None) | Path(..) => {},
869 // These are list-like patterns; parens can always be removed.
870 TupleStruct(_, _, ps) | Tuple(ps) | Slice(ps) | Or(ps) => for p in ps {
871 self.check_unused_parens_pat(cx, p, false, false);
873 Struct(_, _, fps, _) => for f in fps {
874 self.check_unused_parens_pat(cx, &f.pat, false, false);
876 // Avoid linting on `i @ (p0 | .. | pn)` and `box (p0 | .. | pn)`, #64106.
877 Ident(.., Some(p)) | Box(p) => self.check_unused_parens_pat(cx, p, true, false),
878 // Avoid linting on `&(mut x)` as `&mut x` has a different meaning, #55342.
879 // Also avoid linting on `& mut? (p0 | .. | pn)`, #64106.
880 Ref(p, m) => self.check_unused_parens_pat(cx, p, true, *m == Mutability::Not),
884 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
885 if let StmtKind::Local(ref local) = s.kind {
886 self.check_unused_parens_pat(cx, &local.pat, true, false);
889 <Self as UnusedDelimLint>::check_stmt(self, cx, s)
892 fn check_param(&mut self, cx: &EarlyContext<'_>, param: &ast::Param) {
893 self.check_unused_parens_pat(cx, ¶m.pat, true, false);
896 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
897 self.check_unused_parens_pat(cx, &arm.pat, false, false);
900 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
901 if let ast::TyKind::Paren(r) = &ty.kind {
903 ast::TyKind::TraitObject(..) => {}
904 ast::TyKind::ImplTrait(_, bounds) if bounds.len() > 1 => {}
905 ast::TyKind::Array(_, len) => {
906 self.check_unused_delims_expr(
909 UnusedDelimsCtx::ArrayLenExpr,
917 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(ty.span) {
920 pprust::ty_to_string(ty)
923 self.emit_unused_delims(cx, ty.span, &pattern_text, "type", (false, false));
929 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
930 <Self as UnusedDelimLint>::check_item(self, cx, item)
935 /// The `unused_braces` lint detects unnecessary braces around an
950 /// The braces are not needed, and should be removed. This is the
951 /// preferred style for writing these expressions.
952 pub(super) UNUSED_BRACES,
954 "unnecessary braces around an expression"
957 declare_lint_pass!(UnusedBraces => [UNUSED_BRACES]);
959 impl UnusedDelimLint for UnusedBraces {
960 const DELIM_STR: &'static str = "braces";
962 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = false;
964 fn lint(&self) -> &'static Lint {
968 fn check_unused_delims_expr(
970 cx: &EarlyContext<'_>,
972 ctx: UnusedDelimsCtx,
973 followed_by_block: bool,
974 left_pos: Option<BytePos>,
975 right_pos: Option<BytePos>,
978 ast::ExprKind::Block(ref inner, None)
979 if inner.rules == ast::BlockCheckMode::Default =>
981 // emit a warning under the following conditions:
983 // - the block does not have a label
984 // - the block is not `unsafe`
985 // - the block contains exactly one expression (do not lint `{ expr; }`)
986 // - `followed_by_block` is true and the internal expr may contain a `{`
987 // - the block is not multiline (do not lint multiline match arms)
991 // somewhat_long_expression
996 // - the block has no attribute and was not created inside a macro
997 // - if the block is an `anon_const`, the inner expr must be a literal
998 // (do not lint `struct A<const N: usize>; let _: A<{ 2 + 3 }>;`)
1000 // FIXME(const_generics): handle paths when #67075 is fixed.
1001 if let [stmt] = inner.stmts.as_slice() {
1002 if let ast::StmtKind::Expr(ref expr) = stmt.kind {
1003 if !Self::is_expr_delims_necessary(expr, followed_by_block)
1004 && (ctx != UnusedDelimsCtx::AnonConst
1005 || matches!(expr.kind, ast::ExprKind::Lit(_)))
1006 && !cx.sess().source_map().is_multiline(value.span)
1007 && value.attrs.is_empty()
1008 && !value.span.from_expansion()
1010 self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
1015 ast::ExprKind::Let(_, ref expr) => {
1016 self.check_unused_delims_expr(
1019 UnusedDelimsCtx::LetScrutineeExpr,
1030 impl EarlyLintPass for UnusedBraces {
1031 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
1032 <Self as UnusedDelimLint>::check_stmt(self, cx, s)
1035 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
1036 <Self as UnusedDelimLint>::check_expr(self, cx, e);
1038 if let ExprKind::Repeat(_, ref anon_const) = e.kind {
1039 self.check_unused_delims_expr(
1042 UnusedDelimsCtx::AnonConst,
1050 fn check_generic_arg(&mut self, cx: &EarlyContext<'_>, arg: &ast::GenericArg) {
1051 if let ast::GenericArg::Const(ct) = arg {
1052 self.check_unused_delims_expr(
1055 UnusedDelimsCtx::AnonConst,
1063 fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant) {
1064 if let Some(anon_const) = &v.disr_expr {
1065 self.check_unused_delims_expr(
1068 UnusedDelimsCtx::AnonConst,
1076 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
1078 ast::TyKind::Array(_, ref len) => {
1079 self.check_unused_delims_expr(
1082 UnusedDelimsCtx::ArrayLenExpr,
1089 ast::TyKind::Typeof(ref anon_const) => {
1090 self.check_unused_delims_expr(
1093 UnusedDelimsCtx::AnonConst,
1104 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1105 <Self as UnusedDelimLint>::check_item(self, cx, item)
1110 /// The `unused_import_braces` lint catches unnecessary braces around an
1115 /// ```rust,compile_fail
1116 /// #![deny(unused_import_braces)]
1129 /// If there is only a single item, then remove the braces (`use test::A;`
1132 /// This lint is "allow" by default because it is only enforcing a
1133 /// stylistic choice.
1134 UNUSED_IMPORT_BRACES,
1136 "unnecessary braces around an imported item"
1139 declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]);
1141 impl UnusedImportBraces {
1142 fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
1143 if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
1144 // Recursively check nested UseTrees
1145 for &(ref tree, _) in items {
1146 self.check_use_tree(cx, tree, item);
1149 // Trigger the lint only if there is one nested item
1150 if items.len() != 1 {
1154 // Trigger the lint if the nested item is a non-self single item
1155 let node_name = match items[0].0.kind {
1156 ast::UseTreeKind::Simple(rename, ..) => {
1157 let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
1158 if orig_ident.name == kw::SelfLower {
1161 rename.unwrap_or(orig_ident).name
1163 ast::UseTreeKind::Glob => Symbol::intern("*"),
1164 ast::UseTreeKind::Nested(_) => return,
1167 cx.struct_span_lint(UNUSED_IMPORT_BRACES, item.span, |lint| {
1168 lint.build(&format!("braces around {} is unnecessary", node_name)).emit()
1174 impl EarlyLintPass for UnusedImportBraces {
1175 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1176 if let ast::ItemKind::Use(ref use_tree) = item.kind {
1177 self.check_use_tree(cx, use_tree, item);
1183 /// The `unused_allocation` lint detects unnecessary allocations that can
1189 /// #![feature(box_syntax)]
1191 /// let a = (box [1, 2, 3]).len();
1199 /// When a `box` expression is immediately coerced to a reference, then
1200 /// the allocation is unnecessary, and a reference (using `&` or `&mut`)
1201 /// should be used instead to avoid the allocation.
1202 pub(super) UNUSED_ALLOCATION,
1204 "detects unnecessary allocations that can be eliminated"
1207 declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]);
1209 impl<'tcx> LateLintPass<'tcx> for UnusedAllocation {
1210 fn check_expr(&mut self, cx: &LateContext<'_>, e: &hir::Expr<'_>) {
1212 hir::ExprKind::Box(_) => {}
1216 for adj in cx.typeck_results().expr_adjustments(e) {
1217 if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
1218 cx.struct_span_lint(UNUSED_ALLOCATION, e.span, |lint| {
1220 adjustment::AutoBorrowMutability::Not => {
1221 "unnecessary allocation, use `&` instead"
1223 adjustment::AutoBorrowMutability::Mut { .. } => {
1224 "unnecessary allocation, use `&mut` instead"
1227 lint.build(msg).emit()