2 use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
4 use rustc_ast::ast::{ExprKind, StmtKind};
5 use rustc_ast::util::parser;
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};
25 "unused result of a type flagged as `#[must_use]`",
26 report_in_external_macro
32 "unused result of an expression in a statement"
35 declare_lint_pass!(UnusedResults => [UNUSED_MUST_USE, UNUSED_RESULTS]);
37 impl<'tcx> LateLintPass<'tcx> for UnusedResults {
38 fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
39 let expr = match s.kind {
40 hir::StmtKind::Semi(ref expr) => &**expr,
44 if let hir::ExprKind::Ret(..) = expr.kind {
48 let ty = cx.typeck_results().expr_ty(&expr);
49 let type_permits_lack_of_use = check_must_use_ty(cx, ty, &expr, s.span, "", "", 1);
51 let mut fn_warned = false;
52 let mut op_warned = false;
53 let maybe_def_id = match expr.kind {
54 hir::ExprKind::Call(ref callee, _) => {
56 hir::ExprKind::Path(ref qpath) => {
57 match cx.qpath_res(qpath, callee.hir_id) {
58 Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) => Some(def_id),
59 // `Res::Local` if it was a closure, for which we
60 // do not currently support must-use linting
67 hir::ExprKind::MethodCall(..) => cx.typeck_results().type_dependent_def_id(expr.hir_id),
70 if let Some(def_id) = maybe_def_id {
71 fn_warned = check_must_use_def(cx, def_id, s.span, "return value of ", "");
72 } else if type_permits_lack_of_use {
73 // We don't warn about unused unit or uninhabited types.
74 // (See https://github.com/rust-lang/rust/issues/43806 for details.)
78 let must_use_op = match expr.kind {
79 // Hardcoding operators here seemed more expedient than the
80 // refactoring that would be needed to look up the `#[must_use]`
81 // attribute which does exist on the comparison trait methods
82 hir::ExprKind::Binary(bin_op, ..) => match bin_op.node {
88 | hir::BinOpKind::Gt => Some("comparison"),
93 | hir::BinOpKind::Rem => Some("arithmetic operation"),
94 hir::BinOpKind::And | hir::BinOpKind::Or => Some("logical operation"),
95 hir::BinOpKind::BitXor
96 | hir::BinOpKind::BitAnd
97 | hir::BinOpKind::BitOr
99 | hir::BinOpKind::Shr => Some("bitwise operation"),
101 hir::ExprKind::Unary(..) => Some("unary operation"),
105 if let Some(must_use_op) = must_use_op {
106 cx.struct_span_lint(UNUSED_MUST_USE, expr.span, |lint| {
107 lint.build(&format!("unused {} that must be used", must_use_op)).emit()
112 if !(type_permits_lack_of_use || fn_warned || op_warned) {
113 cx.struct_span_lint(UNUSED_RESULTS, s.span, |lint| lint.build("unused result").emit());
116 // Returns whether an error has been emitted (and thus another does not need to be later).
117 fn check_must_use_ty<'tcx>(
118 cx: &LateContext<'tcx>,
120 expr: &hir::Expr<'_>,
127 || cx.tcx.is_ty_uninhabited_from(
128 cx.tcx.parent_module(expr.hir_id).to_def_id(),
136 let plural_suffix = pluralize!(plural_len);
139 ty::Adt(..) if ty.is_box() => {
140 let boxed_ty = ty.boxed_ty();
141 let descr_pre = &format!("{}boxed ", descr_pre);
142 check_must_use_ty(cx, boxed_ty, expr, span, descr_pre, descr_post, plural_len)
144 ty::Adt(def, _) => check_must_use_def(cx, def.did, span, descr_pre, descr_post),
145 ty::Opaque(def, _) => {
146 let mut has_emitted = false;
147 for (predicate, _) in cx.tcx.predicates_of(def).predicates {
148 // We only look at the `DefId`, so it is safe to skip the binder here.
149 if let ty::PredicateAtom::Trait(ref poly_trait_predicate, _) =
150 predicate.skip_binders()
152 let def_id = poly_trait_predicate.trait_ref.def_id;
154 &format!("{}implementer{} of ", descr_pre, plural_suffix,);
155 if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
163 ty::Dynamic(binder, _) => {
164 let mut has_emitted = false;
165 for predicate in binder.skip_binder().iter() {
166 if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate {
167 let def_id = trait_ref.def_id;
169 &format!(" trait object{}{}", plural_suffix, descr_post,);
170 if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
178 ty::Tuple(ref tys) => {
179 let mut has_emitted = false;
180 let spans = if let hir::ExprKind::Tup(comps) = &expr.kind {
181 debug_assert_eq!(comps.len(), tys.len());
182 comps.iter().map(|e| e.span).collect()
186 for (i, ty) in tys.iter().map(|k| k.expect_ty()).enumerate() {
187 let descr_post = &format!(" in tuple element {}", i);
188 let span = *spans.get(i).unwrap_or(&span);
189 if check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, plural_len)
196 ty::Array(ty, len) => match len.try_eval_usize(cx.tcx, cx.param_env) {
197 // If the array is definitely non-empty, we can do `#[must_use]` checking.
198 Some(n) if n != 0 => {
199 let descr_pre = &format!("{}array{} of ", descr_pre, plural_suffix,);
200 check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, n as usize + 1)
202 // Otherwise, we don't lint, to avoid false positives.
206 cx.struct_span_lint(UNUSED_MUST_USE, span, |lint| {
207 let mut err = lint.build(&format!(
208 "unused {}closure{}{} that must be used",
209 descr_pre, plural_suffix, descr_post,
211 err.note("closures are lazy and do nothing unless called");
216 ty::Generator(..) => {
217 cx.struct_span_lint(UNUSED_MUST_USE, span, |lint| {
218 let mut err = lint.build(&format!(
219 "unused {}generator{}{} that must be used",
220 descr_pre, plural_suffix, descr_post,
222 err.note("generators are lazy and do nothing unless resumed");
231 // Returns whether an error has been emitted (and thus another does not need to be later).
232 // FIXME: Args desc_{pre,post}_path could be made lazy by taking Fn() -> &str, but this
233 // would make calling it a big awkward. Could also take String (so args are moved), but
234 // this would still require a copy into the format string, which would only be executed
236 fn check_must_use_def(
237 cx: &LateContext<'_>,
240 descr_pre_path: &str,
241 descr_post_path: &str,
243 for attr in cx.tcx.get_attrs(def_id).iter() {
244 if cx.sess().check_name(attr, sym::must_use) {
245 cx.struct_span_lint(UNUSED_MUST_USE, span, |lint| {
247 "unused {}`{}`{} that must be used",
249 cx.tcx.def_path_str(def_id),
252 let mut err = lint.build(&msg);
253 // check for #[must_use = "..."]
254 if let Some(note) = attr.value_str() {
255 err.note(¬e.as_str());
270 "path statements with no effect"
273 declare_lint_pass!(PathStatements => [PATH_STATEMENTS]);
275 impl<'tcx> LateLintPass<'tcx> for PathStatements {
276 fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
277 if let hir::StmtKind::Semi(expr) = s.kind {
278 if let hir::ExprKind::Path(_) = expr.kind {
279 cx.struct_span_lint(PATH_STATEMENTS, s.span, |lint| {
280 let ty = cx.typeck_results().expr_ty(expr);
281 if ty.needs_drop(cx.tcx, cx.param_env) {
282 let mut lint = lint.build("path statement drops value");
283 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(expr.span) {
284 lint.span_suggestion(
286 "use `drop` to clarify the intent",
287 format!("drop({});", snippet),
288 Applicability::MachineApplicable,
291 lint.span_help(s.span, "use `drop` to clarify the intent");
295 lint.build("path statement with no effect").emit()
303 #[derive(Copy, Clone)]
304 pub struct UnusedAttributes {
305 builtin_attributes: &'static FxHashMap<Symbol, &'static BuiltinAttribute>,
308 impl UnusedAttributes {
309 pub fn new() -> Self {
310 UnusedAttributes { builtin_attributes: &*BUILTIN_ATTRIBUTE_MAP }
314 impl_lint_pass!(UnusedAttributes => [UNUSED_ATTRIBUTES]);
316 impl<'tcx> LateLintPass<'tcx> for UnusedAttributes {
317 fn check_attribute(&mut self, cx: &LateContext<'_>, attr: &ast::Attribute) {
318 debug!("checking attribute: {:?}", attr);
320 if attr.is_doc_comment() {
324 let attr_info = attr.ident().and_then(|ident| self.builtin_attributes.get(&ident.name));
326 if let Some(&&(name, ty, ..)) = attr_info {
327 if let AttributeType::AssumedUsed = ty {
328 debug!("{:?} is AssumedUsed", name);
333 if !cx.sess().is_attr_used(attr) {
334 debug!("emitting warning for: {:?}", attr);
335 cx.struct_span_lint(UNUSED_ATTRIBUTES, attr.span, |lint| {
336 lint.build("unused attribute").emit()
338 // Is it a builtin attribute that must be used at the crate level?
339 if attr_info.map_or(false, |(_, ty, ..)| ty == &AttributeType::CrateLevel) {
340 cx.struct_span_lint(UNUSED_ATTRIBUTES, attr.span, |lint| {
341 let msg = match attr.style {
342 ast::AttrStyle::Outer => {
343 "crate-level attribute should be an inner attribute: add an exclamation \
346 ast::AttrStyle::Inner => "crate-level attribute should be in the root module",
348 lint.build(msg).emit()
352 debug!("Attr was used: {:?}", attr);
357 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
358 enum UnusedDelimsCtx {
373 impl From<UnusedDelimsCtx> for &'static str {
374 fn from(ctx: UnusedDelimsCtx) -> &'static str {
376 UnusedDelimsCtx::FunctionArg => "function argument",
377 UnusedDelimsCtx::MethodArg => "method argument",
378 UnusedDelimsCtx::AssignedValue => "assigned value",
379 UnusedDelimsCtx::IfCond => "`if` condition",
380 UnusedDelimsCtx::WhileCond => "`while` condition",
381 UnusedDelimsCtx::ForIterExpr => "`for` iterator expression",
382 UnusedDelimsCtx::MatchScrutineeExpr => "`match` scrutinee expression",
383 UnusedDelimsCtx::ReturnValue => "`return` value",
384 UnusedDelimsCtx::BlockRetValue => "block return value",
385 UnusedDelimsCtx::LetScrutineeExpr => "`let` scrutinee expression",
386 UnusedDelimsCtx::ArrayLenExpr | UnusedDelimsCtx::AnonConst => "const expression",
391 /// Used by both `UnusedParens` and `UnusedBraces` to prevent code duplication.
392 trait UnusedDelimLint {
393 const DELIM_STR: &'static str;
395 /// Due to `ref` pattern, there can be a difference between using
396 /// `{ expr }` and `expr` in pattern-matching contexts. This means
397 /// that we should only lint `unused_parens` and not `unused_braces`
402 /// let ref b = { a }; // We actually borrow a copy of `a` here.
403 /// a += 1; // By mutating `a` we invalidate any borrows of `a`.
404 /// assert_eq!(b + 1, a); // `b` does not borrow `a`, so we can still use it here.
406 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool;
408 // this cannot be a constant is it refers to a static.
409 fn lint(&self) -> &'static Lint;
411 fn check_unused_delims_expr(
413 cx: &EarlyContext<'_>,
415 ctx: UnusedDelimsCtx,
416 followed_by_block: bool,
417 left_pos: Option<BytePos>,
418 right_pos: Option<BytePos>,
421 fn is_expr_delims_necessary(inner: &ast::Expr, followed_by_block: bool) -> bool {
422 // Prevent false-positives in cases like `fn x() -> u8 { ({ 0 } + 1) }`
423 let lhs_needs_parens = {
424 let mut innermost = inner;
426 if let ExprKind::Binary(_, lhs, _rhs) = &innermost.kind {
428 if !rustc_ast::util::classify::expr_requires_semi_to_be_stmt(innermost) {
438 || (followed_by_block
439 && match inner.kind {
440 ExprKind::Ret(_) | ExprKind::Break(..) | ExprKind::Yield(..) => true,
441 _ => parser::contains_exterior_struct_lit(&inner),
445 fn emit_unused_delims_expr(
447 cx: &EarlyContext<'_>,
449 ctx: UnusedDelimsCtx,
450 left_pos: Option<BytePos>,
451 right_pos: Option<BytePos>,
453 let expr_text = if let Ok(snippet) = cx.sess().source_map().span_to_snippet(value.span) {
456 pprust::expr_to_string(value)
459 left_pos.map(|s| s >= value.span.lo()).unwrap_or(false),
460 right_pos.map(|s| s <= value.span.hi()).unwrap_or(false),
462 self.emit_unused_delims(cx, value.span, &expr_text, ctx.into(), keep_space);
465 fn emit_unused_delims(
467 cx: &EarlyContext<'_>,
471 keep_space: (bool, bool),
473 // FIXME(flip1995): Quick and dirty fix for #70814. This should be fixed in rustdoc
475 if span == DUMMY_SP {
479 cx.struct_span_lint(self.lint(), span, |lint| {
480 let span_msg = format!("unnecessary {} around {}", Self::DELIM_STR, msg);
481 let mut err = lint.build(&span_msg);
482 let mut ate_left_paren = false;
483 let mut ate_right_paren = false;
484 let parens_removed = pattern
485 .trim_matches(|c| match c {
490 ate_left_paren = true;
498 ate_right_paren = true;
507 let mut replace = if keep_space.0 {
508 let mut s = String::from(" ");
509 s.push_str(parens_removed);
512 String::from(parens_removed)
521 let suggestion = format!("remove these {}", Self::DELIM_STR);
523 err.span_suggestion_short(span, &suggestion, replace, Applicability::MachineApplicable);
528 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
529 use rustc_ast::ast::ExprKind::*;
530 let (value, ctx, followed_by_block, left_pos, right_pos) = match e.kind {
531 // Do not lint `unused_braces` in `if let` expressions.
532 If(ref cond, ref block, ..)
533 if !matches!(cond.kind, Let(_, _)) || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
535 let left = e.span.lo() + rustc_span::BytePos(2);
536 let right = block.span.lo();
537 (cond, UnusedDelimsCtx::IfCond, true, Some(left), Some(right))
540 // Do not lint `unused_braces` in `while let` expressions.
541 While(ref cond, ref block, ..)
542 if !matches!(cond.kind, Let(_, _)) || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
544 let left = e.span.lo() + rustc_span::BytePos(5);
545 let right = block.span.lo();
546 (cond, UnusedDelimsCtx::WhileCond, true, Some(left), Some(right))
549 ForLoop(_, ref cond, ref block, ..) => {
550 (cond, UnusedDelimsCtx::ForIterExpr, true, None, Some(block.span.lo()))
553 Match(ref head, _) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
554 let left = e.span.lo() + rustc_span::BytePos(5);
555 (head, UnusedDelimsCtx::MatchScrutineeExpr, true, Some(left), None)
558 Ret(Some(ref value)) => {
559 let left = e.span.lo() + rustc_span::BytePos(3);
560 (value, UnusedDelimsCtx::ReturnValue, false, Some(left), None)
563 Assign(_, ref value, _) | AssignOp(.., ref value) => {
564 (value, UnusedDelimsCtx::AssignedValue, false, None, None)
566 // either function/method call, or something this lint doesn't care about
567 ref call_or_other => {
568 let (args_to_check, ctx) = match *call_or_other {
569 Call(_, ref args) => (&args[..], UnusedDelimsCtx::FunctionArg),
570 // first "argument" is self (which sometimes needs delims)
571 MethodCall(_, ref args, _) => (&args[1..], UnusedDelimsCtx::MethodArg),
572 // actual catch-all arm
577 // Don't lint if this is a nested macro expansion: otherwise, the lint could
578 // trigger in situations that macro authors shouldn't have to care about, e.g.,
579 // when a parenthesized token tree matched in one macro expansion is matched as
580 // an expression in another and used as a fn/method argument (Issue #47775)
581 if e.span.ctxt().outer_expn_data().call_site.from_expansion() {
584 for arg in args_to_check {
585 self.check_unused_delims_expr(cx, arg, ctx, false, None, None);
590 self.check_unused_delims_expr(cx, &value, ctx, followed_by_block, left_pos, right_pos);
593 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
595 StmtKind::Local(ref local) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
596 if let Some(ref value) = local.init {
597 self.check_unused_delims_expr(
600 UnusedDelimsCtx::AssignedValue,
607 StmtKind::Expr(ref expr) => {
608 self.check_unused_delims_expr(
611 UnusedDelimsCtx::BlockRetValue,
621 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
622 use ast::ItemKind::*;
624 if let Const(.., Some(expr)) | Static(.., Some(expr)) = &item.kind {
625 self.check_unused_delims_expr(
628 UnusedDelimsCtx::AssignedValue,
638 pub(super) UNUSED_PARENS,
640 "`if`, `match`, `while` and `return` do not need parentheses"
643 declare_lint_pass!(UnusedParens => [UNUSED_PARENS]);
645 impl UnusedDelimLint for UnusedParens {
646 const DELIM_STR: &'static str = "parentheses";
648 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = true;
650 fn lint(&self) -> &'static Lint {
654 fn check_unused_delims_expr(
656 cx: &EarlyContext<'_>,
658 ctx: UnusedDelimsCtx,
659 followed_by_block: bool,
660 left_pos: Option<BytePos>,
661 right_pos: Option<BytePos>,
664 ast::ExprKind::Paren(ref inner) => {
665 if !Self::is_expr_delims_necessary(inner, followed_by_block)
666 && value.attrs.is_empty()
667 && !value.span.from_expansion()
669 self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
672 ast::ExprKind::Let(_, ref expr) => {
673 // FIXME(#60336): Properly handle `let true = (false && true)`
674 // actually needing the parenthesis.
675 self.check_unused_delims_expr(
678 UnusedDelimsCtx::LetScrutineeExpr,
690 fn check_unused_parens_pat(
692 cx: &EarlyContext<'_>,
697 use ast::{BindingMode, Mutability, PatKind};
699 if let PatKind::Paren(inner) = &value.kind {
701 // The lint visitor will visit each subpattern of `p`. We do not want to lint
702 // any range pattern no matter where it occurs in the pattern. For something like
703 // `&(a..=b)`, there is a recursive `check_pat` on `a` and `b`, but we will assume
704 // that if there are unnecessary parens they serve a purpose of readability.
705 PatKind::Range(..) => return,
706 // Avoid `p0 | .. | pn` if we should.
707 PatKind::Or(..) if avoid_or => return,
708 // Avoid `mut x` and `mut x @ p` if we should:
709 PatKind::Ident(BindingMode::ByValue(Mutability::Mut), ..) if avoid_mut => return,
710 // Otherwise proceed with linting.
715 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(value.span) {
718 pprust::pat_to_string(value)
720 self.emit_unused_delims(cx, value.span, &pattern_text, "pattern", (false, false));
725 impl EarlyLintPass for UnusedParens {
726 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
727 if let ExprKind::Let(ref pat, ..) | ExprKind::ForLoop(ref pat, ..) = e.kind {
728 self.check_unused_parens_pat(cx, pat, false, false);
731 <Self as UnusedDelimLint>::check_expr(self, cx, e)
734 fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
735 use ast::{Mutability, PatKind::*};
737 // Do not lint on `(..)` as that will result in the other arms being useless.
739 // The other cases do not contain sub-patterns.
740 | Wild | Rest | Lit(..) | MacCall(..) | Range(..) | Ident(.., None) | Path(..) => {},
741 // These are list-like patterns; parens can always be removed.
742 TupleStruct(_, ps) | Tuple(ps) | Slice(ps) | Or(ps) => for p in ps {
743 self.check_unused_parens_pat(cx, p, false, false);
745 Struct(_, fps, _) => for f in fps {
746 self.check_unused_parens_pat(cx, &f.pat, false, false);
748 // Avoid linting on `i @ (p0 | .. | pn)` and `box (p0 | .. | pn)`, #64106.
749 Ident(.., Some(p)) | Box(p) => self.check_unused_parens_pat(cx, p, true, false),
750 // Avoid linting on `&(mut x)` as `&mut x` has a different meaning, #55342.
751 // Also avoid linting on `& mut? (p0 | .. | pn)`, #64106.
752 Ref(p, m) => self.check_unused_parens_pat(cx, p, true, *m == Mutability::Not),
756 fn check_anon_const(&mut self, cx: &EarlyContext<'_>, c: &ast::AnonConst) {
757 self.check_unused_delims_expr(cx, &c.value, UnusedDelimsCtx::AnonConst, false, None, None);
760 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
761 if let StmtKind::Local(ref local) = s.kind {
762 self.check_unused_parens_pat(cx, &local.pat, false, false);
765 <Self as UnusedDelimLint>::check_stmt(self, cx, s)
768 fn check_param(&mut self, cx: &EarlyContext<'_>, param: &ast::Param) {
769 self.check_unused_parens_pat(cx, ¶m.pat, true, false);
772 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
773 self.check_unused_parens_pat(cx, &arm.pat, false, false);
776 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
777 if let &ast::TyKind::Paren(ref r) = &ty.kind {
779 &ast::TyKind::TraitObject(..) => {}
780 &ast::TyKind::ImplTrait(_, ref bounds) if bounds.len() > 1 => {}
781 &ast::TyKind::Array(_, ref len) => {
782 self.check_unused_delims_expr(
785 UnusedDelimsCtx::ArrayLenExpr,
793 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(ty.span) {
796 pprust::ty_to_string(ty)
799 self.emit_unused_delims(cx, ty.span, &pattern_text, "type", (false, false));
805 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
806 <Self as UnusedDelimLint>::check_item(self, cx, item)
811 pub(super) UNUSED_BRACES,
813 "unnecessary braces around an expression"
816 declare_lint_pass!(UnusedBraces => [UNUSED_BRACES]);
818 impl UnusedDelimLint for UnusedBraces {
819 const DELIM_STR: &'static str = "braces";
821 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = false;
823 fn lint(&self) -> &'static Lint {
827 fn check_unused_delims_expr(
829 cx: &EarlyContext<'_>,
831 ctx: UnusedDelimsCtx,
832 followed_by_block: bool,
833 left_pos: Option<BytePos>,
834 right_pos: Option<BytePos>,
837 ast::ExprKind::Block(ref inner, None)
838 if inner.rules == ast::BlockCheckMode::Default =>
840 // emit a warning under the following conditions:
842 // - the block does not have a label
843 // - the block is not `unsafe`
844 // - the block contains exactly one expression (do not lint `{ expr; }`)
845 // - `followed_by_block` is true and the internal expr may contain a `{`
846 // - the block is not multiline (do not lint multiline match arms)
850 // somewhat_long_expression
855 // - the block has no attribute and was not created inside a macro
856 // - if the block is an `anon_const`, the inner expr must be a literal
857 // (do not lint `struct A<const N: usize>; let _: A<{ 2 + 3 }>;`)
859 // FIXME(const_generics): handle paths when #67075 is fixed.
860 if let [stmt] = inner.stmts.as_slice() {
861 if let ast::StmtKind::Expr(ref expr) = stmt.kind {
862 if !Self::is_expr_delims_necessary(expr, followed_by_block)
863 && (ctx != UnusedDelimsCtx::AnonConst
864 || matches!(expr.kind, ast::ExprKind::Lit(_)))
865 // array length expressions are checked during `check_anon_const` and `check_ty`,
866 // once as `ArrayLenExpr` and once as `AnonConst`.
868 // As we do not want to lint this twice, we do not emit an error for
869 // `ArrayLenExpr` if `AnonConst` would do the same.
870 && (ctx != UnusedDelimsCtx::ArrayLenExpr
871 || !matches!(expr.kind, ast::ExprKind::Lit(_)))
872 && !cx.sess().source_map().is_multiline(value.span)
873 && value.attrs.is_empty()
874 && !value.span.from_expansion()
876 self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
881 ast::ExprKind::Let(_, ref expr) => {
882 // FIXME(#60336): Properly handle `let true = (false && true)`
883 // actually needing the parenthesis.
884 self.check_unused_delims_expr(
887 UnusedDelimsCtx::LetScrutineeExpr,
898 impl EarlyLintPass for UnusedBraces {
899 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
900 <Self as UnusedDelimLint>::check_expr(self, cx, e)
903 fn check_anon_const(&mut self, cx: &EarlyContext<'_>, c: &ast::AnonConst) {
904 self.check_unused_delims_expr(cx, &c.value, UnusedDelimsCtx::AnonConst, false, None, None);
907 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
908 <Self as UnusedDelimLint>::check_stmt(self, cx, s)
911 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
912 if let &ast::TyKind::Paren(ref r) = &ty.kind {
913 if let ast::TyKind::Array(_, ref len) = r.kind {
914 self.check_unused_delims_expr(
917 UnusedDelimsCtx::ArrayLenExpr,
926 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
927 <Self as UnusedDelimLint>::check_item(self, cx, item)
932 UNUSED_IMPORT_BRACES,
934 "unnecessary braces around an imported item"
937 declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]);
939 impl UnusedImportBraces {
940 fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
941 if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
942 // Recursively check nested UseTrees
943 for &(ref tree, _) in items {
944 self.check_use_tree(cx, tree, item);
947 // Trigger the lint only if there is one nested item
948 if items.len() != 1 {
952 // Trigger the lint if the nested item is a non-self single item
953 let node_name = match items[0].0.kind {
954 ast::UseTreeKind::Simple(rename, ..) => {
955 let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
956 if orig_ident.name == kw::SelfLower {
959 rename.unwrap_or(orig_ident).name
961 ast::UseTreeKind::Glob => Symbol::intern("*"),
962 ast::UseTreeKind::Nested(_) => return,
965 cx.struct_span_lint(UNUSED_IMPORT_BRACES, item.span, |lint| {
966 lint.build(&format!("braces around {} is unnecessary", node_name)).emit()
972 impl EarlyLintPass for UnusedImportBraces {
973 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
974 if let ast::ItemKind::Use(ref use_tree) = item.kind {
975 self.check_use_tree(cx, use_tree, item);
981 pub(super) UNUSED_ALLOCATION,
983 "detects unnecessary allocations that can be eliminated"
986 declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]);
988 impl<'tcx> LateLintPass<'tcx> for UnusedAllocation {
989 fn check_expr(&mut self, cx: &LateContext<'_>, e: &hir::Expr<'_>) {
991 hir::ExprKind::Box(_) => {}
995 for adj in cx.typeck_results().expr_adjustments(e) {
996 if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
997 cx.struct_span_lint(UNUSED_ALLOCATION, e.span, |lint| {
999 adjustment::AutoBorrowMutability::Not => {
1000 "unnecessary allocation, use `&` instead"
1002 adjustment::AutoBorrowMutability::Mut { .. } => {
1003 "unnecessary allocation, use `&mut` instead"
1006 lint.build(msg).emit()