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::Unary(..) => Some("unary operation"),
161 if let Some(must_use_op) = must_use_op {
162 cx.struct_span_lint(UNUSED_MUST_USE, expr.span, |lint| {
163 lint.build(&format!("unused {} that must be used", must_use_op)).emit()
168 if !(type_permits_lack_of_use || fn_warned || op_warned) {
169 cx.struct_span_lint(UNUSED_RESULTS, s.span, |lint| lint.build("unused result").emit());
172 // Returns whether an error has been emitted (and thus another does not need to be later).
173 fn check_must_use_ty<'tcx>(
174 cx: &LateContext<'tcx>,
176 expr: &hir::Expr<'_>,
183 || cx.tcx.is_ty_uninhabited_from(
184 cx.tcx.parent_module(expr.hir_id).to_def_id(),
192 let plural_suffix = pluralize!(plural_len);
195 ty::Adt(..) if ty.is_box() => {
196 let boxed_ty = ty.boxed_ty();
197 let descr_pre = &format!("{}boxed ", descr_pre);
198 check_must_use_ty(cx, boxed_ty, expr, span, descr_pre, descr_post, plural_len)
200 ty::Adt(def, _) => check_must_use_def(cx, def.did, span, descr_pre, descr_post),
201 ty::Opaque(def, _) => {
202 let mut has_emitted = false;
203 for &(predicate, _) in cx.tcx.explicit_item_bounds(def) {
204 // We only look at the `DefId`, so it is safe to skip the binder here.
205 if let ty::PredicateKind::Trait(ref poly_trait_predicate, _) =
206 predicate.kind().skip_binder()
208 let def_id = poly_trait_predicate.trait_ref.def_id;
210 &format!("{}implementer{} of ", descr_pre, plural_suffix,);
211 if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
219 ty::Dynamic(binder, _) => {
220 let mut has_emitted = false;
221 for predicate in binder.iter() {
222 if let ty::ExistentialPredicate::Trait(ref trait_ref) =
223 predicate.skip_binder()
225 let def_id = trait_ref.def_id;
227 &format!(" trait object{}{}", plural_suffix, descr_post,);
228 if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
236 ty::Tuple(ref tys) => {
237 let mut has_emitted = false;
238 let spans = if let hir::ExprKind::Tup(comps) = &expr.kind {
239 debug_assert_eq!(comps.len(), tys.len());
240 comps.iter().map(|e| e.span).collect()
244 for (i, ty) in tys.iter().map(|k| k.expect_ty()).enumerate() {
245 let descr_post = &format!(" in tuple element {}", i);
246 let span = *spans.get(i).unwrap_or(&span);
247 if check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, plural_len)
254 ty::Array(ty, len) => match len.try_eval_usize(cx.tcx, cx.param_env) {
255 // If the array is empty we don't lint, to avoid false positives
256 Some(0) | None => false,
257 // If the array is definitely non-empty, we can do `#[must_use]` checking.
259 let descr_pre = &format!("{}array{} of ", descr_pre, plural_suffix,);
260 check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, n as usize + 1)
264 cx.struct_span_lint(UNUSED_MUST_USE, span, |lint| {
265 let mut err = lint.build(&format!(
266 "unused {}closure{}{} that must be used",
267 descr_pre, plural_suffix, descr_post,
269 err.note("closures are lazy and do nothing unless called");
274 ty::Generator(..) => {
275 cx.struct_span_lint(UNUSED_MUST_USE, span, |lint| {
276 let mut err = lint.build(&format!(
277 "unused {}generator{}{} that must be used",
278 descr_pre, plural_suffix, descr_post,
280 err.note("generators are lazy and do nothing unless resumed");
289 // Returns whether an error has been emitted (and thus another does not need to be later).
290 // FIXME: Args desc_{pre,post}_path could be made lazy by taking Fn() -> &str, but this
291 // would make calling it a big awkward. Could also take String (so args are moved), but
292 // this would still require a copy into the format string, which would only be executed
294 fn check_must_use_def(
295 cx: &LateContext<'_>,
298 descr_pre_path: &str,
299 descr_post_path: &str,
301 for attr in cx.tcx.get_attrs(def_id).iter() {
302 if cx.sess().check_name(attr, sym::must_use) {
303 cx.struct_span_lint(UNUSED_MUST_USE, span, |lint| {
305 "unused {}`{}`{} that must be used",
307 cx.tcx.def_path_str(def_id),
310 let mut err = lint.build(&msg);
311 // check for #[must_use = "..."]
312 if let Some(note) = attr.value_str() {
313 err.note(¬e.as_str());
326 /// The `path_statements` lint detects path statements with no effect.
340 /// It is usually a mistake to have a statement that has no effect.
343 "path statements with no effect"
346 declare_lint_pass!(PathStatements => [PATH_STATEMENTS]);
348 impl<'tcx> LateLintPass<'tcx> for PathStatements {
349 fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
350 if let hir::StmtKind::Semi(expr) = s.kind {
351 if let hir::ExprKind::Path(_) = expr.kind {
352 cx.struct_span_lint(PATH_STATEMENTS, s.span, |lint| {
353 let ty = cx.typeck_results().expr_ty(expr);
354 if ty.needs_drop(cx.tcx, cx.param_env) {
355 let mut lint = lint.build("path statement drops value");
356 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(expr.span) {
357 lint.span_suggestion(
359 "use `drop` to clarify the intent",
360 format!("drop({});", snippet),
361 Applicability::MachineApplicable,
364 lint.span_help(s.span, "use `drop` to clarify the intent");
368 lint.build("path statement with no effect").emit()
376 #[derive(Copy, Clone)]
377 pub struct UnusedAttributes {
378 builtin_attributes: &'static FxHashMap<Symbol, &'static BuiltinAttribute>,
381 impl UnusedAttributes {
382 pub fn new() -> Self {
383 UnusedAttributes { builtin_attributes: &*BUILTIN_ATTRIBUTE_MAP }
387 impl_lint_pass!(UnusedAttributes => [UNUSED_ATTRIBUTES]);
389 impl<'tcx> LateLintPass<'tcx> for UnusedAttributes {
390 fn check_attribute(&mut self, cx: &LateContext<'_>, attr: &ast::Attribute) {
391 debug!("checking attribute: {:?}", attr);
393 if attr.is_doc_comment() {
397 let attr_info = attr.ident().and_then(|ident| self.builtin_attributes.get(&ident.name));
399 if let Some(&&(name, ty, ..)) = attr_info {
400 if let AttributeType::AssumedUsed = ty {
401 debug!("{:?} is AssumedUsed", name);
406 if !cx.sess().is_attr_used(attr) {
407 debug!("emitting warning for: {:?}", attr);
408 cx.struct_span_lint(UNUSED_ATTRIBUTES, attr.span, |lint| {
409 lint.build("unused attribute").emit()
411 // Is it a builtin attribute that must be used at the crate level?
412 if attr_info.map_or(false, |(_, ty, ..)| ty == &AttributeType::CrateLevel) {
413 cx.struct_span_lint(UNUSED_ATTRIBUTES, attr.span, |lint| {
414 let msg = match attr.style {
415 ast::AttrStyle::Outer => {
416 "crate-level attribute should be an inner attribute: add an exclamation \
419 ast::AttrStyle::Inner => "crate-level attribute should be in the root module",
421 lint.build(msg).emit()
425 debug!("Attr was used: {:?}", attr);
430 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
431 enum UnusedDelimsCtx {
446 impl From<UnusedDelimsCtx> for &'static str {
447 fn from(ctx: UnusedDelimsCtx) -> &'static str {
449 UnusedDelimsCtx::FunctionArg => "function argument",
450 UnusedDelimsCtx::MethodArg => "method argument",
451 UnusedDelimsCtx::AssignedValue => "assigned value",
452 UnusedDelimsCtx::IfCond => "`if` condition",
453 UnusedDelimsCtx::WhileCond => "`while` condition",
454 UnusedDelimsCtx::ForIterExpr => "`for` iterator expression",
455 UnusedDelimsCtx::MatchScrutineeExpr => "`match` scrutinee expression",
456 UnusedDelimsCtx::ReturnValue => "`return` value",
457 UnusedDelimsCtx::BlockRetValue => "block return value",
458 UnusedDelimsCtx::LetScrutineeExpr => "`let` scrutinee expression",
459 UnusedDelimsCtx::ArrayLenExpr | UnusedDelimsCtx::AnonConst => "const expression",
464 /// Used by both `UnusedParens` and `UnusedBraces` to prevent code duplication.
465 trait UnusedDelimLint {
466 const DELIM_STR: &'static str;
468 /// Due to `ref` pattern, there can be a difference between using
469 /// `{ expr }` and `expr` in pattern-matching contexts. This means
470 /// that we should only lint `unused_parens` and not `unused_braces`
475 /// let ref b = { a }; // We actually borrow a copy of `a` here.
476 /// a += 1; // By mutating `a` we invalidate any borrows of `a`.
477 /// assert_eq!(b + 1, a); // `b` does not borrow `a`, so we can still use it here.
479 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool;
481 // this cannot be a constant is it refers to a static.
482 fn lint(&self) -> &'static Lint;
484 fn check_unused_delims_expr(
486 cx: &EarlyContext<'_>,
488 ctx: UnusedDelimsCtx,
489 followed_by_block: bool,
490 left_pos: Option<BytePos>,
491 right_pos: Option<BytePos>,
494 fn is_expr_delims_necessary(inner: &ast::Expr, followed_by_block: bool) -> bool {
495 // Prevent false-positives in cases like `fn x() -> u8 { ({ 0 } + 1) }`
496 let lhs_needs_parens = {
497 let mut innermost = inner;
499 if let ExprKind::Binary(_, lhs, _rhs) = &innermost.kind {
501 if !rustc_ast::util::classify::expr_requires_semi_to_be_stmt(innermost) {
511 || (followed_by_block
512 && match inner.kind {
513 ExprKind::Ret(_) | ExprKind::Break(..) | ExprKind::Yield(..) => true,
514 _ => parser::contains_exterior_struct_lit(&inner),
518 fn emit_unused_delims_expr(
520 cx: &EarlyContext<'_>,
522 ctx: UnusedDelimsCtx,
523 left_pos: Option<BytePos>,
524 right_pos: Option<BytePos>,
526 let expr_text = if let Ok(snippet) = cx.sess().source_map().span_to_snippet(value.span) {
529 pprust::expr_to_string(value)
532 left_pos.map_or(false, |s| s >= value.span.lo()),
533 right_pos.map_or(false, |s| s <= value.span.hi()),
535 self.emit_unused_delims(cx, value.span, &expr_text, ctx.into(), keep_space);
538 fn emit_unused_delims(
540 cx: &EarlyContext<'_>,
544 keep_space: (bool, bool),
546 // FIXME(flip1995): Quick and dirty fix for #70814. This should be fixed in rustdoc
548 if span == DUMMY_SP {
552 cx.struct_span_lint(self.lint(), span, |lint| {
553 let span_msg = format!("unnecessary {} around {}", Self::DELIM_STR, msg);
554 let mut err = lint.build(&span_msg);
555 let mut ate_left_paren = false;
556 let mut ate_right_paren = false;
557 let parens_removed = pattern
558 .trim_matches(|c| match c {
563 ate_left_paren = true;
571 ate_right_paren = true;
580 let mut replace = if keep_space.0 {
581 let mut s = String::from(" ");
582 s.push_str(parens_removed);
585 String::from(parens_removed)
594 let suggestion = format!("remove these {}", Self::DELIM_STR);
596 err.span_suggestion_short(span, &suggestion, replace, Applicability::MachineApplicable);
601 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
602 use rustc_ast::ExprKind::*;
603 let (value, ctx, followed_by_block, left_pos, right_pos) = match e.kind {
604 // Do not lint `unused_braces` in `if let` expressions.
605 If(ref cond, ref block, ..)
606 if !matches!(cond.kind, Let(_, _)) || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
608 let left = e.span.lo() + rustc_span::BytePos(2);
609 let right = block.span.lo();
610 (cond, UnusedDelimsCtx::IfCond, true, Some(left), Some(right))
613 // Do not lint `unused_braces` in `while let` expressions.
614 While(ref cond, ref block, ..)
615 if !matches!(cond.kind, Let(_, _)) || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
617 let left = e.span.lo() + rustc_span::BytePos(5);
618 let right = block.span.lo();
619 (cond, UnusedDelimsCtx::WhileCond, true, Some(left), Some(right))
622 ForLoop(_, ref cond, ref block, ..) => {
623 (cond, UnusedDelimsCtx::ForIterExpr, true, None, Some(block.span.lo()))
626 Match(ref head, _) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
627 let left = e.span.lo() + rustc_span::BytePos(5);
628 (head, UnusedDelimsCtx::MatchScrutineeExpr, true, Some(left), None)
631 Ret(Some(ref value)) => {
632 let left = e.span.lo() + rustc_span::BytePos(3);
633 (value, UnusedDelimsCtx::ReturnValue, false, Some(left), None)
636 Assign(_, ref value, _) | AssignOp(.., ref value) => {
637 (value, UnusedDelimsCtx::AssignedValue, false, None, None)
639 // either function/method call, or something this lint doesn't care about
640 ref call_or_other => {
641 let (args_to_check, ctx) = match *call_or_other {
642 Call(_, ref args) => (&args[..], UnusedDelimsCtx::FunctionArg),
643 // first "argument" is self (which sometimes needs delims)
644 MethodCall(_, ref args, _) => (&args[1..], UnusedDelimsCtx::MethodArg),
645 // actual catch-all arm
650 // Don't lint if this is a nested macro expansion: otherwise, the lint could
651 // trigger in situations that macro authors shouldn't have to care about, e.g.,
652 // when a parenthesized token tree matched in one macro expansion is matched as
653 // an expression in another and used as a fn/method argument (Issue #47775)
654 if e.span.ctxt().outer_expn_data().call_site.from_expansion() {
657 for arg in args_to_check {
658 self.check_unused_delims_expr(cx, arg, ctx, false, None, None);
663 self.check_unused_delims_expr(cx, &value, ctx, followed_by_block, left_pos, right_pos);
666 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
668 StmtKind::Local(ref local) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
669 if let Some(ref value) = local.init {
670 self.check_unused_delims_expr(
673 UnusedDelimsCtx::AssignedValue,
680 StmtKind::Expr(ref expr) => {
681 self.check_unused_delims_expr(
684 UnusedDelimsCtx::BlockRetValue,
694 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
695 use ast::ItemKind::*;
697 if let Const(.., Some(expr)) | Static(.., Some(expr)) = &item.kind {
698 self.check_unused_delims_expr(
701 UnusedDelimsCtx::AssignedValue,
711 /// The `unused_parens` lint detects `if`, `match`, `while` and `return`
712 /// with parentheses; they do not need them.
724 /// The parenthesis are not needed, and should be removed. This is the
725 /// preferred style for writing these expressions.
726 pub(super) UNUSED_PARENS,
728 "`if`, `match`, `while` and `return` do not need parentheses"
731 declare_lint_pass!(UnusedParens => [UNUSED_PARENS]);
733 impl UnusedDelimLint for UnusedParens {
734 const DELIM_STR: &'static str = "parentheses";
736 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = true;
738 fn lint(&self) -> &'static Lint {
742 fn check_unused_delims_expr(
744 cx: &EarlyContext<'_>,
746 ctx: UnusedDelimsCtx,
747 followed_by_block: bool,
748 left_pos: Option<BytePos>,
749 right_pos: Option<BytePos>,
752 ast::ExprKind::Paren(ref inner) => {
753 if !Self::is_expr_delims_necessary(inner, followed_by_block)
754 && value.attrs.is_empty()
755 && !value.span.from_expansion()
756 && (ctx != UnusedDelimsCtx::LetScrutineeExpr
757 || !matches!(inner.kind, ast::ExprKind::Binary(
758 rustc_span::source_map::Spanned { node, .. },
763 self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
766 ast::ExprKind::Let(_, ref expr) => {
767 self.check_unused_delims_expr(
770 UnusedDelimsCtx::LetScrutineeExpr,
782 fn check_unused_parens_pat(
784 cx: &EarlyContext<'_>,
789 use ast::{BindingMode, Mutability, PatKind};
791 if let PatKind::Paren(inner) = &value.kind {
793 // The lint visitor will visit each subpattern of `p`. We do not want to lint
794 // any range pattern no matter where it occurs in the pattern. For something like
795 // `&(a..=b)`, there is a recursive `check_pat` on `a` and `b`, but we will assume
796 // that if there are unnecessary parens they serve a purpose of readability.
797 PatKind::Range(..) => return,
798 // Avoid `p0 | .. | pn` if we should.
799 PatKind::Or(..) if avoid_or => return,
800 // Avoid `mut x` and `mut x @ p` if we should:
801 PatKind::Ident(BindingMode::ByValue(Mutability::Mut), ..) if avoid_mut => return,
802 // Otherwise proceed with linting.
807 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(value.span) {
810 pprust::pat_to_string(value)
812 self.emit_unused_delims(cx, value.span, &pattern_text, "pattern", (false, false));
817 impl EarlyLintPass for UnusedParens {
818 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
819 if let ExprKind::Let(ref pat, ..) | ExprKind::ForLoop(ref pat, ..) = e.kind {
820 self.check_unused_parens_pat(cx, pat, false, false);
823 <Self as UnusedDelimLint>::check_expr(self, cx, e)
826 fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
827 use ast::{Mutability, PatKind::*};
829 // Do not lint on `(..)` as that will result in the other arms being useless.
831 // The other cases do not contain sub-patterns.
832 | Wild | Rest | Lit(..) | MacCall(..) | Range(..) | Ident(.., None) | Path(..) => {},
833 // These are list-like patterns; parens can always be removed.
834 TupleStruct(_, ps) | Tuple(ps) | Slice(ps) | Or(ps) => for p in ps {
835 self.check_unused_parens_pat(cx, p, false, false);
837 Struct(_, fps, _) => for f in fps {
838 self.check_unused_parens_pat(cx, &f.pat, false, false);
840 // Avoid linting on `i @ (p0 | .. | pn)` and `box (p0 | .. | pn)`, #64106.
841 Ident(.., Some(p)) | Box(p) => self.check_unused_parens_pat(cx, p, true, false),
842 // Avoid linting on `&(mut x)` as `&mut x` has a different meaning, #55342.
843 // Also avoid linting on `& mut? (p0 | .. | pn)`, #64106.
844 Ref(p, m) => self.check_unused_parens_pat(cx, p, true, *m == Mutability::Not),
848 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
849 if let StmtKind::Local(ref local) = s.kind {
850 self.check_unused_parens_pat(cx, &local.pat, false, false);
853 <Self as UnusedDelimLint>::check_stmt(self, cx, s)
856 fn check_param(&mut self, cx: &EarlyContext<'_>, param: &ast::Param) {
857 self.check_unused_parens_pat(cx, ¶m.pat, true, false);
860 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
861 self.check_unused_parens_pat(cx, &arm.pat, false, false);
864 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
865 if let ast::TyKind::Paren(r) = &ty.kind {
867 ast::TyKind::TraitObject(..) => {}
868 ast::TyKind::ImplTrait(_, bounds) if bounds.len() > 1 => {}
869 ast::TyKind::Array(_, len) => {
870 self.check_unused_delims_expr(
873 UnusedDelimsCtx::ArrayLenExpr,
881 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(ty.span) {
884 pprust::ty_to_string(ty)
887 self.emit_unused_delims(cx, ty.span, &pattern_text, "type", (false, false));
893 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
894 <Self as UnusedDelimLint>::check_item(self, cx, item)
899 /// The `unused_braces` lint detects unnecessary braces around an
914 /// The braces are not needed, and should be removed. This is the
915 /// preferred style for writing these expressions.
916 pub(super) UNUSED_BRACES,
918 "unnecessary braces around an expression"
921 declare_lint_pass!(UnusedBraces => [UNUSED_BRACES]);
923 impl UnusedDelimLint for UnusedBraces {
924 const DELIM_STR: &'static str = "braces";
926 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = false;
928 fn lint(&self) -> &'static Lint {
932 fn check_unused_delims_expr(
934 cx: &EarlyContext<'_>,
936 ctx: UnusedDelimsCtx,
937 followed_by_block: bool,
938 left_pos: Option<BytePos>,
939 right_pos: Option<BytePos>,
942 ast::ExprKind::Block(ref inner, None)
943 if inner.rules == ast::BlockCheckMode::Default =>
945 // emit a warning under the following conditions:
947 // - the block does not have a label
948 // - the block is not `unsafe`
949 // - the block contains exactly one expression (do not lint `{ expr; }`)
950 // - `followed_by_block` is true and the internal expr may contain a `{`
951 // - the block is not multiline (do not lint multiline match arms)
955 // somewhat_long_expression
960 // - the block has no attribute and was not created inside a macro
961 // - if the block is an `anon_const`, the inner expr must be a literal
962 // (do not lint `struct A<const N: usize>; let _: A<{ 2 + 3 }>;`)
964 // FIXME(const_generics): handle paths when #67075 is fixed.
965 if let [stmt] = inner.stmts.as_slice() {
966 if let ast::StmtKind::Expr(ref expr) = stmt.kind {
967 if !Self::is_expr_delims_necessary(expr, followed_by_block)
968 && (ctx != UnusedDelimsCtx::AnonConst
969 || matches!(expr.kind, ast::ExprKind::Lit(_)))
970 && !cx.sess().source_map().is_multiline(value.span)
971 && value.attrs.is_empty()
972 && !value.span.from_expansion()
974 self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
979 ast::ExprKind::Let(_, ref expr) => {
980 self.check_unused_delims_expr(
983 UnusedDelimsCtx::LetScrutineeExpr,
994 impl EarlyLintPass for UnusedBraces {
995 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
996 <Self as UnusedDelimLint>::check_stmt(self, cx, s)
999 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
1000 <Self as UnusedDelimLint>::check_expr(self, cx, e);
1002 if let ExprKind::Repeat(_, ref anon_const) = e.kind {
1003 self.check_unused_delims_expr(
1006 UnusedDelimsCtx::AnonConst,
1014 fn check_generic_arg(&mut self, cx: &EarlyContext<'_>, arg: &ast::GenericArg) {
1015 if let ast::GenericArg::Const(ct) = arg {
1016 self.check_unused_delims_expr(
1019 UnusedDelimsCtx::AnonConst,
1027 fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant) {
1028 if let Some(anon_const) = &v.disr_expr {
1029 self.check_unused_delims_expr(
1032 UnusedDelimsCtx::AnonConst,
1040 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
1042 ast::TyKind::Array(_, ref len) => {
1043 self.check_unused_delims_expr(
1046 UnusedDelimsCtx::ArrayLenExpr,
1053 ast::TyKind::Typeof(ref anon_const) => {
1054 self.check_unused_delims_expr(
1057 UnusedDelimsCtx::AnonConst,
1068 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1069 <Self as UnusedDelimLint>::check_item(self, cx, item)
1074 /// The `unused_import_braces` lint catches unnecessary braces around an
1079 /// ```rust,compile_fail
1080 /// #![deny(unused_import_braces)]
1093 /// If there is only a single item, then remove the braces (`use test::A;`
1096 /// This lint is "allow" by default because it is only enforcing a
1097 /// stylistic choice.
1098 UNUSED_IMPORT_BRACES,
1100 "unnecessary braces around an imported item"
1103 declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]);
1105 impl UnusedImportBraces {
1106 fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
1107 if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
1108 // Recursively check nested UseTrees
1109 for &(ref tree, _) in items {
1110 self.check_use_tree(cx, tree, item);
1113 // Trigger the lint only if there is one nested item
1114 if items.len() != 1 {
1118 // Trigger the lint if the nested item is a non-self single item
1119 let node_name = match items[0].0.kind {
1120 ast::UseTreeKind::Simple(rename, ..) => {
1121 let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
1122 if orig_ident.name == kw::SelfLower {
1125 rename.unwrap_or(orig_ident).name
1127 ast::UseTreeKind::Glob => Symbol::intern("*"),
1128 ast::UseTreeKind::Nested(_) => return,
1131 cx.struct_span_lint(UNUSED_IMPORT_BRACES, item.span, |lint| {
1132 lint.build(&format!("braces around {} is unnecessary", node_name)).emit()
1138 impl EarlyLintPass for UnusedImportBraces {
1139 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1140 if let ast::ItemKind::Use(ref use_tree) = item.kind {
1141 self.check_use_tree(cx, use_tree, item);
1147 /// The `unused_allocation` lint detects unnecessary allocations that can
1153 /// #![feature(box_syntax)]
1155 /// let a = (box [1, 2, 3]).len();
1163 /// When a `box` expression is immediately coerced to a reference, then
1164 /// the allocation is unnecessary, and a reference (using `&` or `&mut`)
1165 /// should be used instead to avoid the allocation.
1166 pub(super) UNUSED_ALLOCATION,
1168 "detects unnecessary allocations that can be eliminated"
1171 declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]);
1173 impl<'tcx> LateLintPass<'tcx> for UnusedAllocation {
1174 fn check_expr(&mut self, cx: &LateContext<'_>, e: &hir::Expr<'_>) {
1176 hir::ExprKind::Box(_) => {}
1180 for adj in cx.typeck_results().expr_adjustments(e) {
1181 if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
1182 cx.struct_span_lint(UNUSED_ALLOCATION, e.span, |lint| {
1184 adjustment::AutoBorrowMutability::Not => {
1185 "unnecessary allocation, use `&` instead"
1187 adjustment::AutoBorrowMutability::Mut { .. } => {
1188 "unnecessary allocation, use `&mut` instead"
1191 lint.build(msg).emit()