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.trim_matches(|c| match c {
489 ate_left_paren = true;
497 ate_right_paren = true;
505 let mut replace = if keep_space.0 {
506 let mut s = String::from(" ");
507 s.push_str(parens_removed);
510 String::from(parens_removed)
519 let suggestion = format!("remove these {}", Self::DELIM_STR);
521 err.span_suggestion_short(span, &suggestion, replace, Applicability::MachineApplicable);
526 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
527 use rustc_ast::ast::ExprKind::*;
528 let (value, ctx, followed_by_block, left_pos, right_pos) = match e.kind {
529 // Do not lint `unused_braces` in `if let` expressions.
530 If(ref cond, ref block, ..)
531 if !matches!(cond.kind, Let(_, _)) || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
533 let left = e.span.lo() + rustc_span::BytePos(2);
534 let right = block.span.lo();
535 (cond, UnusedDelimsCtx::IfCond, true, Some(left), Some(right))
538 // Do not lint `unused_braces` in `while let` expressions.
539 While(ref cond, ref block, ..)
540 if !matches!(cond.kind, Let(_, _)) || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
542 let left = e.span.lo() + rustc_span::BytePos(5);
543 let right = block.span.lo();
544 (cond, UnusedDelimsCtx::WhileCond, true, Some(left), Some(right))
547 ForLoop(_, ref cond, ref block, ..) => {
548 (cond, UnusedDelimsCtx::ForIterExpr, true, None, Some(block.span.lo()))
551 Match(ref head, _) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
552 let left = e.span.lo() + rustc_span::BytePos(5);
553 (head, UnusedDelimsCtx::MatchScrutineeExpr, true, Some(left), None)
556 Ret(Some(ref value)) => {
557 let left = e.span.lo() + rustc_span::BytePos(3);
558 (value, UnusedDelimsCtx::ReturnValue, false, Some(left), None)
561 Assign(_, ref value, _) | AssignOp(.., ref value) => {
562 (value, UnusedDelimsCtx::AssignedValue, false, None, None)
564 // either function/method call, or something this lint doesn't care about
565 ref call_or_other => {
566 let (args_to_check, ctx) = match *call_or_other {
567 Call(_, ref args) => (&args[..], UnusedDelimsCtx::FunctionArg),
568 // first "argument" is self (which sometimes needs delims)
569 MethodCall(_, ref args, _) => (&args[1..], UnusedDelimsCtx::MethodArg),
570 // actual catch-all arm
575 // Don't lint if this is a nested macro expansion: otherwise, the lint could
576 // trigger in situations that macro authors shouldn't have to care about, e.g.,
577 // when a parenthesized token tree matched in one macro expansion is matched as
578 // an expression in another and used as a fn/method argument (Issue #47775)
579 if e.span.ctxt().outer_expn_data().call_site.from_expansion() {
582 for arg in args_to_check {
583 self.check_unused_delims_expr(cx, arg, ctx, false, None, None);
588 self.check_unused_delims_expr(cx, &value, ctx, followed_by_block, left_pos, right_pos);
591 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
593 StmtKind::Local(ref local) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
594 if let Some(ref value) = local.init {
595 self.check_unused_delims_expr(
598 UnusedDelimsCtx::AssignedValue,
605 StmtKind::Expr(ref expr) => {
606 self.check_unused_delims_expr(
609 UnusedDelimsCtx::BlockRetValue,
619 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
620 use ast::ItemKind::*;
622 if let Const(.., Some(expr)) | Static(.., Some(expr)) = &item.kind {
623 self.check_unused_delims_expr(
626 UnusedDelimsCtx::AssignedValue,
636 pub(super) UNUSED_PARENS,
638 "`if`, `match`, `while` and `return` do not need parentheses"
641 declare_lint_pass!(UnusedParens => [UNUSED_PARENS]);
643 impl UnusedDelimLint for UnusedParens {
644 const DELIM_STR: &'static str = "parentheses";
646 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = true;
648 fn lint(&self) -> &'static Lint {
652 fn check_unused_delims_expr(
654 cx: &EarlyContext<'_>,
656 ctx: UnusedDelimsCtx,
657 followed_by_block: bool,
658 left_pos: Option<BytePos>,
659 right_pos: Option<BytePos>,
662 ast::ExprKind::Paren(ref inner) => {
663 if !Self::is_expr_delims_necessary(inner, followed_by_block)
664 && value.attrs.is_empty()
665 && !value.span.from_expansion()
667 self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
670 ast::ExprKind::Let(_, ref expr) => {
671 // FIXME(#60336): Properly handle `let true = (false && true)`
672 // actually needing the parenthesis.
673 self.check_unused_delims_expr(
676 UnusedDelimsCtx::LetScrutineeExpr,
688 fn check_unused_parens_pat(
690 cx: &EarlyContext<'_>,
695 use ast::{BindingMode, Mutability, PatKind};
697 if let PatKind::Paren(inner) = &value.kind {
699 // The lint visitor will visit each subpattern of `p`. We do not want to lint
700 // any range pattern no matter where it occurs in the pattern. For something like
701 // `&(a..=b)`, there is a recursive `check_pat` on `a` and `b`, but we will assume
702 // that if there are unnecessary parens they serve a purpose of readability.
703 PatKind::Range(..) => return,
704 // Avoid `p0 | .. | pn` if we should.
705 PatKind::Or(..) if avoid_or => return,
706 // Avoid `mut x` and `mut x @ p` if we should:
707 PatKind::Ident(BindingMode::ByValue(Mutability::Mut), ..) if avoid_mut => return,
708 // Otherwise proceed with linting.
713 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(value.span) {
716 pprust::pat_to_string(value)
718 self.emit_unused_delims(cx, value.span, &pattern_text, "pattern", (false, false));
723 impl EarlyLintPass for UnusedParens {
724 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
725 if let ExprKind::Let(ref pat, ..) | ExprKind::ForLoop(ref pat, ..) = e.kind {
726 self.check_unused_parens_pat(cx, pat, false, false);
729 <Self as UnusedDelimLint>::check_expr(self, cx, e)
732 fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
733 use ast::{Mutability, PatKind::*};
735 // Do not lint on `(..)` as that will result in the other arms being useless.
737 // The other cases do not contain sub-patterns.
738 | Wild | Rest | Lit(..) | MacCall(..) | Range(..) | Ident(.., None) | Path(..) => {},
739 // These are list-like patterns; parens can always be removed.
740 TupleStruct(_, ps) | Tuple(ps) | Slice(ps) | Or(ps) => for p in ps {
741 self.check_unused_parens_pat(cx, p, false, false);
743 Struct(_, fps, _) => for f in fps {
744 self.check_unused_parens_pat(cx, &f.pat, false, false);
746 // Avoid linting on `i @ (p0 | .. | pn)` and `box (p0 | .. | pn)`, #64106.
747 Ident(.., Some(p)) | Box(p) => self.check_unused_parens_pat(cx, p, true, false),
748 // Avoid linting on `&(mut x)` as `&mut x` has a different meaning, #55342.
749 // Also avoid linting on `& mut? (p0 | .. | pn)`, #64106.
750 Ref(p, m) => self.check_unused_parens_pat(cx, p, true, *m == Mutability::Not),
754 fn check_anon_const(&mut self, cx: &EarlyContext<'_>, c: &ast::AnonConst) {
755 self.check_unused_delims_expr(cx, &c.value, UnusedDelimsCtx::AnonConst, false, None, None);
758 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
759 if let StmtKind::Local(ref local) = s.kind {
760 self.check_unused_parens_pat(cx, &local.pat, false, false);
763 <Self as UnusedDelimLint>::check_stmt(self, cx, s)
766 fn check_param(&mut self, cx: &EarlyContext<'_>, param: &ast::Param) {
767 self.check_unused_parens_pat(cx, ¶m.pat, true, false);
770 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
771 self.check_unused_parens_pat(cx, &arm.pat, false, false);
774 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
775 if let &ast::TyKind::Paren(ref r) = &ty.kind {
777 &ast::TyKind::TraitObject(..) => {}
778 &ast::TyKind::ImplTrait(_, ref bounds) if bounds.len() > 1 => {}
779 &ast::TyKind::Array(_, ref len) => {
780 self.check_unused_delims_expr(
783 UnusedDelimsCtx::ArrayLenExpr,
791 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(ty.span) {
794 pprust::ty_to_string(ty)
797 self.emit_unused_delims(cx, ty.span, &pattern_text, "type", (false, false));
803 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
804 <Self as UnusedDelimLint>::check_item(self, cx, item)
809 pub(super) UNUSED_BRACES,
811 "unnecessary braces around an expression"
814 declare_lint_pass!(UnusedBraces => [UNUSED_BRACES]);
816 impl UnusedDelimLint for UnusedBraces {
817 const DELIM_STR: &'static str = "braces";
819 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = false;
821 fn lint(&self) -> &'static Lint {
825 fn check_unused_delims_expr(
827 cx: &EarlyContext<'_>,
829 ctx: UnusedDelimsCtx,
830 followed_by_block: bool,
831 left_pos: Option<BytePos>,
832 right_pos: Option<BytePos>,
835 ast::ExprKind::Block(ref inner, None)
836 if inner.rules == ast::BlockCheckMode::Default =>
838 // emit a warning under the following conditions:
840 // - the block does not have a label
841 // - the block is not `unsafe`
842 // - the block contains exactly one expression (do not lint `{ expr; }`)
843 // - `followed_by_block` is true and the internal expr may contain a `{`
844 // - the block is not multiline (do not lint multiline match arms)
848 // somewhat_long_expression
853 // - the block has no attribute and was not created inside a macro
854 // - if the block is an `anon_const`, the inner expr must be a literal
855 // (do not lint `struct A<const N: usize>; let _: A<{ 2 + 3 }>;`)
857 // FIXME(const_generics): handle paths when #67075 is fixed.
858 if let [stmt] = inner.stmts.as_slice() {
859 if let ast::StmtKind::Expr(ref expr) = stmt.kind {
860 if !Self::is_expr_delims_necessary(expr, followed_by_block)
861 && (ctx != UnusedDelimsCtx::AnonConst
862 || matches!(expr.kind, ast::ExprKind::Lit(_)))
863 // array length expressions are checked during `check_anon_const` and `check_ty`,
864 // once as `ArrayLenExpr` and once as `AnonConst`.
866 // As we do not want to lint this twice, we do not emit an error for
867 // `ArrayLenExpr` if `AnonConst` would do the same.
868 && (ctx != UnusedDelimsCtx::ArrayLenExpr
869 || !matches!(expr.kind, ast::ExprKind::Lit(_)))
870 && !cx.sess().source_map().is_multiline(value.span)
871 && value.attrs.is_empty()
872 && !value.span.from_expansion()
874 self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
879 ast::ExprKind::Let(_, ref expr) => {
880 // FIXME(#60336): Properly handle `let true = (false && true)`
881 // actually needing the parenthesis.
882 self.check_unused_delims_expr(
885 UnusedDelimsCtx::LetScrutineeExpr,
896 impl EarlyLintPass for UnusedBraces {
897 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
898 <Self as UnusedDelimLint>::check_expr(self, cx, e)
901 fn check_anon_const(&mut self, cx: &EarlyContext<'_>, c: &ast::AnonConst) {
902 self.check_unused_delims_expr(cx, &c.value, UnusedDelimsCtx::AnonConst, false, None, None);
905 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
906 <Self as UnusedDelimLint>::check_stmt(self, cx, s)
909 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
910 if let &ast::TyKind::Paren(ref r) = &ty.kind {
911 if let ast::TyKind::Array(_, ref len) = r.kind {
912 self.check_unused_delims_expr(
915 UnusedDelimsCtx::ArrayLenExpr,
924 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
925 <Self as UnusedDelimLint>::check_item(self, cx, item)
930 UNUSED_IMPORT_BRACES,
932 "unnecessary braces around an imported item"
935 declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]);
937 impl UnusedImportBraces {
938 fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
939 if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
940 // Recursively check nested UseTrees
941 for &(ref tree, _) in items {
942 self.check_use_tree(cx, tree, item);
945 // Trigger the lint only if there is one nested item
946 if items.len() != 1 {
950 // Trigger the lint if the nested item is a non-self single item
951 let node_name = match items[0].0.kind {
952 ast::UseTreeKind::Simple(rename, ..) => {
953 let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
954 if orig_ident.name == kw::SelfLower {
957 rename.unwrap_or(orig_ident).name
959 ast::UseTreeKind::Glob => Symbol::intern("*"),
960 ast::UseTreeKind::Nested(_) => return,
963 cx.struct_span_lint(UNUSED_IMPORT_BRACES, item.span, |lint| {
964 lint.build(&format!("braces around {} is unnecessary", node_name)).emit()
970 impl EarlyLintPass for UnusedImportBraces {
971 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
972 if let ast::ItemKind::Use(ref use_tree) = item.kind {
973 self.check_use_tree(cx, use_tree, item);
979 pub(super) UNUSED_ALLOCATION,
981 "detects unnecessary allocations that can be eliminated"
984 declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]);
986 impl<'tcx> LateLintPass<'tcx> for UnusedAllocation {
987 fn check_expr(&mut self, cx: &LateContext<'_>, e: &hir::Expr<'_>) {
989 hir::ExprKind::Box(_) => {}
993 for adj in cx.typeck_results().expr_adjustments(e) {
994 if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
995 cx.struct_span_lint(UNUSED_ALLOCATION, e.span, |lint| {
997 adjustment::AutoBorrowMutability::Not => {
998 "unnecessary allocation, use `&` instead"
1000 adjustment::AutoBorrowMutability::Mut { .. } => {
1001 "unnecessary allocation, use `&mut` instead"
1004 lint.build(msg).emit()