2 use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
4 use rustc_ast::ast::{ExprKind, StmtKind};
6 use rustc_ast::util::parser;
7 use rustc_ast_pretty::pprust;
8 use rustc_data_structures::fx::FxHashMap;
9 use rustc_errors::{pluralize, Applicability};
10 use rustc_feature::{AttributeType, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP};
12 use rustc_hir::def::{DefKind, Res};
13 use rustc_hir::def_id::DefId;
14 use rustc_middle::ty::adjustment;
15 use rustc_middle::ty::{self, Ty};
16 use rustc_session::lint::builtin::UNUSED_ATTRIBUTES;
17 use rustc_span::symbol::Symbol;
18 use rustc_span::symbol::{kw, sym};
19 use rustc_span::{BytePos, Span, DUMMY_SP};
26 "unused result of a type flagged as `#[must_use]`",
27 report_in_external_macro
33 "unused result of an expression in a statement"
36 declare_lint_pass!(UnusedResults => [UNUSED_MUST_USE, UNUSED_RESULTS]);
38 impl<'tcx> LateLintPass<'tcx> for UnusedResults {
39 fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
40 let expr = match s.kind {
41 hir::StmtKind::Semi(ref expr) => &**expr,
45 if let hir::ExprKind::Ret(..) = expr.kind {
49 let ty = cx.typeck_results().expr_ty(&expr);
50 let type_permits_lack_of_use = check_must_use_ty(cx, ty, &expr, s.span, "", "", 1);
52 let mut fn_warned = false;
53 let mut op_warned = false;
54 let maybe_def_id = match expr.kind {
55 hir::ExprKind::Call(ref callee, _) => {
57 hir::ExprKind::Path(ref qpath) => {
58 match cx.qpath_res(qpath, callee.hir_id) {
59 Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) => Some(def_id),
60 // `Res::Local` if it was a closure, for which we
61 // do not currently support must-use linting
68 hir::ExprKind::MethodCall(..) => cx.typeck_results().type_dependent_def_id(expr.hir_id),
71 if let Some(def_id) = maybe_def_id {
72 fn_warned = check_must_use_def(cx, def_id, s.span, "return value of ", "");
73 } else if type_permits_lack_of_use {
74 // We don't warn about unused unit or uninhabited types.
75 // (See https://github.com/rust-lang/rust/issues/43806 for details.)
79 let must_use_op = match expr.kind {
80 // Hardcoding operators here seemed more expedient than the
81 // refactoring that would be needed to look up the `#[must_use]`
82 // attribute which does exist on the comparison trait methods
83 hir::ExprKind::Binary(bin_op, ..) => match bin_op.node {
89 | hir::BinOpKind::Gt => Some("comparison"),
94 | hir::BinOpKind::Rem => Some("arithmetic operation"),
95 hir::BinOpKind::And | hir::BinOpKind::Or => Some("logical operation"),
96 hir::BinOpKind::BitXor
97 | hir::BinOpKind::BitAnd
98 | hir::BinOpKind::BitOr
100 | hir::BinOpKind::Shr => Some("bitwise operation"),
102 hir::ExprKind::Unary(..) => Some("unary operation"),
106 if let Some(must_use_op) = must_use_op {
107 cx.struct_span_lint(UNUSED_MUST_USE, expr.span, |lint| {
108 lint.build(&format!("unused {} that must be used", must_use_op)).emit()
113 if !(type_permits_lack_of_use || fn_warned || op_warned) {
114 cx.struct_span_lint(UNUSED_RESULTS, s.span, |lint| lint.build("unused result").emit());
117 // Returns whether an error has been emitted (and thus another does not need to be later).
118 fn check_must_use_ty<'tcx>(
119 cx: &LateContext<'tcx>,
121 expr: &hir::Expr<'_>,
128 || cx.tcx.is_ty_uninhabited_from(
129 cx.tcx.parent_module(expr.hir_id).to_def_id(),
137 let plural_suffix = pluralize!(plural_len);
140 ty::Adt(..) if ty.is_box() => {
141 let boxed_ty = ty.boxed_ty();
142 let descr_pre = &format!("{}boxed ", descr_pre);
143 check_must_use_ty(cx, boxed_ty, expr, span, descr_pre, descr_post, plural_len)
145 ty::Adt(def, _) => check_must_use_def(cx, def.did, span, descr_pre, descr_post),
146 ty::Opaque(def, _) => {
147 let mut has_emitted = false;
148 for (predicate, _) in cx.tcx.predicates_of(def).predicates {
149 // We only look at the `DefId`, so it is safe to skip the binder here.
150 if let ty::PredicateAtom::Trait(ref poly_trait_predicate, _) =
151 predicate.skip_binders()
153 let def_id = poly_trait_predicate.trait_ref.def_id;
155 &format!("{}implementer{} of ", descr_pre, plural_suffix,);
156 if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
164 ty::Dynamic(binder, _) => {
165 let mut has_emitted = false;
166 for predicate in binder.skip_binder().iter() {
167 if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate {
168 let def_id = trait_ref.def_id;
170 &format!(" trait object{}{}", plural_suffix, descr_post,);
171 if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
179 ty::Tuple(ref tys) => {
180 let mut has_emitted = false;
181 let spans = if let hir::ExprKind::Tup(comps) = &expr.kind {
182 debug_assert_eq!(comps.len(), tys.len());
183 comps.iter().map(|e| e.span).collect()
187 for (i, ty) in tys.iter().map(|k| k.expect_ty()).enumerate() {
188 let descr_post = &format!(" in tuple element {}", i);
189 let span = *spans.get(i).unwrap_or(&span);
190 if check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, plural_len)
197 ty::Array(ty, len) => match len.try_eval_usize(cx.tcx, cx.param_env) {
198 // If the array is definitely non-empty, we can do `#[must_use]` checking.
199 Some(n) if n != 0 => {
200 let descr_pre = &format!("{}array{} of ", descr_pre, plural_suffix,);
201 check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, n as usize + 1)
203 // Otherwise, we don't lint, to avoid false positives.
207 cx.struct_span_lint(UNUSED_MUST_USE, span, |lint| {
208 let mut err = lint.build(&format!(
209 "unused {}closure{}{} that must be used",
210 descr_pre, plural_suffix, descr_post,
212 err.note("closures are lazy and do nothing unless called");
217 ty::Generator(..) => {
218 cx.struct_span_lint(UNUSED_MUST_USE, span, |lint| {
219 let mut err = lint.build(&format!(
220 "unused {}generator{}{} that must be used",
221 descr_pre, plural_suffix, descr_post,
223 err.note("generators are lazy and do nothing unless resumed");
232 // Returns whether an error has been emitted (and thus another does not need to be later).
233 // FIXME: Args desc_{pre,post}_path could be made lazy by taking Fn() -> &str, but this
234 // would make calling it a big awkward. Could also take String (so args are moved), but
235 // this would still require a copy into the format string, which would only be executed
237 fn check_must_use_def(
238 cx: &LateContext<'_>,
241 descr_pre_path: &str,
242 descr_post_path: &str,
244 for attr in cx.tcx.get_attrs(def_id).iter() {
245 if attr.check_name(sym::must_use) {
246 cx.struct_span_lint(UNUSED_MUST_USE, span, |lint| {
248 "unused {}`{}`{} that must be used",
250 cx.tcx.def_path_str(def_id),
253 let mut err = lint.build(&msg);
254 // check for #[must_use = "..."]
255 if let Some(note) = attr.value_str() {
256 err.note(¬e.as_str());
271 "path statements with no effect"
274 declare_lint_pass!(PathStatements => [PATH_STATEMENTS]);
276 impl<'tcx> LateLintPass<'tcx> for PathStatements {
277 fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
278 if let hir::StmtKind::Semi(expr) = s.kind {
279 if let hir::ExprKind::Path(_) = expr.kind {
280 cx.struct_span_lint(PATH_STATEMENTS, s.span, |lint| {
281 let ty = cx.typeck_results().expr_ty(expr);
282 if ty.needs_drop(cx.tcx, cx.param_env) {
283 let mut lint = lint.build("path statement drops value");
284 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(expr.span) {
285 lint.span_suggestion(
287 "use `drop` to clarify the intent",
288 format!("drop({});", snippet),
289 Applicability::MachineApplicable,
292 lint.span_help(s.span, "use `drop` to clarify the intent");
296 lint.build("path statement with no effect").emit()
304 #[derive(Copy, Clone)]
305 pub struct UnusedAttributes {
306 builtin_attributes: &'static FxHashMap<Symbol, &'static BuiltinAttribute>,
309 impl UnusedAttributes {
310 pub fn new() -> Self {
311 UnusedAttributes { builtin_attributes: &*BUILTIN_ATTRIBUTE_MAP }
315 impl_lint_pass!(UnusedAttributes => [UNUSED_ATTRIBUTES]);
317 impl<'tcx> LateLintPass<'tcx> for UnusedAttributes {
318 fn check_attribute(&mut self, cx: &LateContext<'_>, attr: &ast::Attribute) {
319 debug!("checking attribute: {:?}", attr);
321 if attr.is_doc_comment() {
325 let attr_info = attr.ident().and_then(|ident| self.builtin_attributes.get(&ident.name));
327 if let Some(&&(name, ty, ..)) = attr_info {
328 if let AttributeType::AssumedUsed = ty {
329 debug!("{:?} is AssumedUsed", name);
334 if !attr::is_used(attr) {
335 debug!("emitting warning for: {:?}", attr);
336 cx.struct_span_lint(UNUSED_ATTRIBUTES, attr.span, |lint| {
337 lint.build("unused attribute").emit()
339 // Is it a builtin attribute that must be used at the crate level?
340 if attr_info.map_or(false, |(_, ty, ..)| ty == &AttributeType::CrateLevel) {
341 cx.struct_span_lint(UNUSED_ATTRIBUTES, attr.span, |lint| {
342 let msg = match attr.style {
343 ast::AttrStyle::Outer => {
344 "crate-level attribute should be an inner attribute: add an exclamation \
347 ast::AttrStyle::Inner => "crate-level attribute should be in the root module",
349 lint.build(msg).emit()
353 debug!("Attr was used: {:?}", attr);
358 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
359 enum UnusedDelimsCtx {
374 impl From<UnusedDelimsCtx> for &'static str {
375 fn from(ctx: UnusedDelimsCtx) -> &'static str {
377 UnusedDelimsCtx::FunctionArg => "function argument",
378 UnusedDelimsCtx::MethodArg => "method argument",
379 UnusedDelimsCtx::AssignedValue => "assigned value",
380 UnusedDelimsCtx::IfCond => "`if` condition",
381 UnusedDelimsCtx::WhileCond => "`while` condition",
382 UnusedDelimsCtx::ForIterExpr => "`for` iterator expression",
383 UnusedDelimsCtx::MatchScrutineeExpr => "`match` scrutinee expression",
384 UnusedDelimsCtx::ReturnValue => "`return` value",
385 UnusedDelimsCtx::BlockRetValue => "block return value",
386 UnusedDelimsCtx::LetScrutineeExpr => "`let` scrutinee expression",
387 UnusedDelimsCtx::ArrayLenExpr | UnusedDelimsCtx::AnonConst => "const expression",
392 /// Used by both `UnusedParens` and `UnusedBraces` to prevent code duplication.
393 trait UnusedDelimLint {
394 const DELIM_STR: &'static str;
396 /// Due to `ref` pattern, there can be a difference between using
397 /// `{ expr }` and `expr` in pattern-matching contexts. This means
398 /// that we should only lint `unused_parens` and not `unused_braces`
403 /// let ref b = { a }; // We actually borrow a copy of `a` here.
404 /// a += 1; // By mutating `a` we invalidate any borrows of `a`.
405 /// assert_eq!(b + 1, a); // `b` does not borrow `a`, so we can still use it here.
407 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool;
409 // this cannot be a constant is it refers to a static.
410 fn lint(&self) -> &'static Lint;
412 fn check_unused_delims_expr(
414 cx: &EarlyContext<'_>,
416 ctx: UnusedDelimsCtx,
417 followed_by_block: bool,
418 left_pos: Option<BytePos>,
419 right_pos: Option<BytePos>,
422 fn is_expr_delims_necessary(inner: &ast::Expr, followed_by_block: bool) -> bool {
423 // Prevent false-positives in cases like `fn x() -> u8 { ({ 0 } + 1) }`
424 let lhs_needs_parens = {
425 let mut innermost = inner;
427 if let ExprKind::Binary(_, lhs, _rhs) = &innermost.kind {
429 if !rustc_ast::util::classify::expr_requires_semi_to_be_stmt(innermost) {
439 || (followed_by_block
440 && match inner.kind {
441 ExprKind::Ret(_) | ExprKind::Break(..) | ExprKind::Yield(..) => true,
442 _ => parser::contains_exterior_struct_lit(&inner),
446 fn emit_unused_delims_expr(
448 cx: &EarlyContext<'_>,
450 ctx: UnusedDelimsCtx,
451 left_pos: Option<BytePos>,
452 right_pos: Option<BytePos>,
454 let expr_text = if let Ok(snippet) = cx.sess().source_map().span_to_snippet(value.span) {
457 pprust::expr_to_string(value)
460 left_pos.map(|s| s >= value.span.lo()).unwrap_or(false),
461 right_pos.map(|s| s <= value.span.hi()).unwrap_or(false),
463 self.emit_unused_delims(cx, value.span, &expr_text, ctx.into(), keep_space);
466 fn emit_unused_delims(
468 cx: &EarlyContext<'_>,
472 keep_space: (bool, bool),
474 // FIXME(flip1995): Quick and dirty fix for #70814. This should be fixed in rustdoc
476 if span == DUMMY_SP {
480 cx.struct_span_lint(self.lint(), span, |lint| {
481 let span_msg = format!("unnecessary {} around {}", Self::DELIM_STR, msg);
482 let mut err = lint.build(&span_msg);
483 let mut ate_left_paren = false;
484 let mut ate_right_paren = false;
485 let parens_removed = pattern.trim_matches(|c| match c {
490 ate_left_paren = true;
498 ate_right_paren = true;
506 let mut replace = if keep_space.0 {
507 let mut s = String::from(" ");
508 s.push_str(parens_removed);
511 String::from(parens_removed)
520 let suggestion = format!("remove these {}", Self::DELIM_STR);
522 err.span_suggestion_short(span, &suggestion, replace, Applicability::MachineApplicable);
527 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
528 use rustc_ast::ast::ExprKind::*;
529 let (value, ctx, followed_by_block, left_pos, right_pos) = match e.kind {
530 // Do not lint `unused_braces` in `if let` expressions.
531 If(ref cond, ref block, ..)
532 if !matches!(cond.kind, Let(_, _)) || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
534 let left = e.span.lo() + rustc_span::BytePos(2);
535 let right = block.span.lo();
536 (cond, UnusedDelimsCtx::IfCond, true, Some(left), Some(right))
539 // Do not lint `unused_braces` in `while let` expressions.
540 While(ref cond, ref block, ..)
541 if !matches!(cond.kind, Let(_, _)) || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
543 let left = e.span.lo() + rustc_span::BytePos(5);
544 let right = block.span.lo();
545 (cond, UnusedDelimsCtx::WhileCond, true, Some(left), Some(right))
548 ForLoop(_, ref cond, ref block, ..) => {
549 (cond, UnusedDelimsCtx::ForIterExpr, true, None, Some(block.span.lo()))
552 Match(ref head, _) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
553 let left = e.span.lo() + rustc_span::BytePos(5);
554 (head, UnusedDelimsCtx::MatchScrutineeExpr, true, Some(left), None)
557 Ret(Some(ref value)) => {
558 let left = e.span.lo() + rustc_span::BytePos(3);
559 (value, UnusedDelimsCtx::ReturnValue, false, Some(left), None)
562 Assign(_, ref value, _) | AssignOp(.., ref value) => {
563 (value, UnusedDelimsCtx::AssignedValue, false, None, None)
565 // either function/method call, or something this lint doesn't care about
566 ref call_or_other => {
567 let (args_to_check, ctx) = match *call_or_other {
568 Call(_, ref args) => (&args[..], UnusedDelimsCtx::FunctionArg),
569 // first "argument" is self (which sometimes needs delims)
570 MethodCall(_, ref args, _) => (&args[1..], UnusedDelimsCtx::MethodArg),
571 // actual catch-all arm
576 // Don't lint if this is a nested macro expansion: otherwise, the lint could
577 // trigger in situations that macro authors shouldn't have to care about, e.g.,
578 // when a parenthesized token tree matched in one macro expansion is matched as
579 // an expression in another and used as a fn/method argument (Issue #47775)
580 if e.span.ctxt().outer_expn_data().call_site.from_expansion() {
583 for arg in args_to_check {
584 self.check_unused_delims_expr(cx, arg, ctx, false, None, None);
589 self.check_unused_delims_expr(cx, &value, ctx, followed_by_block, left_pos, right_pos);
592 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
594 StmtKind::Local(ref local) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
595 if let Some(ref value) = local.init {
596 self.check_unused_delims_expr(
599 UnusedDelimsCtx::AssignedValue,
606 StmtKind::Expr(ref expr) => {
607 self.check_unused_delims_expr(
610 UnusedDelimsCtx::BlockRetValue,
620 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
621 use ast::ItemKind::*;
623 if let Const(.., Some(expr)) | Static(.., Some(expr)) = &item.kind {
624 self.check_unused_delims_expr(
627 UnusedDelimsCtx::AssignedValue,
637 pub(super) UNUSED_PARENS,
639 "`if`, `match`, `while` and `return` do not need parentheses"
642 declare_lint_pass!(UnusedParens => [UNUSED_PARENS]);
644 impl UnusedDelimLint for UnusedParens {
645 const DELIM_STR: &'static str = "parentheses";
647 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = true;
649 fn lint(&self) -> &'static Lint {
653 fn check_unused_delims_expr(
655 cx: &EarlyContext<'_>,
657 ctx: UnusedDelimsCtx,
658 followed_by_block: bool,
659 left_pos: Option<BytePos>,
660 right_pos: Option<BytePos>,
663 ast::ExprKind::Paren(ref inner) => {
664 if !Self::is_expr_delims_necessary(inner, followed_by_block)
665 && value.attrs.is_empty()
666 && !value.span.from_expansion()
668 self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
671 ast::ExprKind::Let(_, ref expr) => {
672 // FIXME(#60336): Properly handle `let true = (false && true)`
673 // actually needing the parenthesis.
674 self.check_unused_delims_expr(
677 UnusedDelimsCtx::LetScrutineeExpr,
689 fn check_unused_parens_pat(
691 cx: &EarlyContext<'_>,
696 use ast::{BindingMode, Mutability, PatKind};
698 if let PatKind::Paren(inner) = &value.kind {
700 // The lint visitor will visit each subpattern of `p`. We do not want to lint
701 // any range pattern no matter where it occurs in the pattern. For something like
702 // `&(a..=b)`, there is a recursive `check_pat` on `a` and `b`, but we will assume
703 // that if there are unnecessary parens they serve a purpose of readability.
704 PatKind::Range(..) => return,
705 // Avoid `p0 | .. | pn` if we should.
706 PatKind::Or(..) if avoid_or => return,
707 // Avoid `mut x` and `mut x @ p` if we should:
708 PatKind::Ident(BindingMode::ByValue(Mutability::Mut), ..) if avoid_mut => return,
709 // Otherwise proceed with linting.
714 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(value.span) {
717 pprust::pat_to_string(value)
719 self.emit_unused_delims(cx, value.span, &pattern_text, "pattern", (false, false));
724 impl EarlyLintPass for UnusedParens {
725 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
726 if let ExprKind::Let(ref pat, ..) | ExprKind::ForLoop(ref pat, ..) = e.kind {
727 self.check_unused_parens_pat(cx, pat, false, false);
730 <Self as UnusedDelimLint>::check_expr(self, cx, e)
733 fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
734 use ast::{Mutability, PatKind::*};
736 // Do not lint on `(..)` as that will result in the other arms being useless.
738 // The other cases do not contain sub-patterns.
739 | Wild | Rest | Lit(..) | MacCall(..) | Range(..) | Ident(.., None) | Path(..) => {},
740 // These are list-like patterns; parens can always be removed.
741 TupleStruct(_, ps) | Tuple(ps) | Slice(ps) | Or(ps) => for p in ps {
742 self.check_unused_parens_pat(cx, p, false, false);
744 Struct(_, fps, _) => for f in fps {
745 self.check_unused_parens_pat(cx, &f.pat, false, false);
747 // Avoid linting on `i @ (p0 | .. | pn)` and `box (p0 | .. | pn)`, #64106.
748 Ident(.., Some(p)) | Box(p) => self.check_unused_parens_pat(cx, p, true, false),
749 // Avoid linting on `&(mut x)` as `&mut x` has a different meaning, #55342.
750 // Also avoid linting on `& mut? (p0 | .. | pn)`, #64106.
751 Ref(p, m) => self.check_unused_parens_pat(cx, p, true, *m == Mutability::Not),
755 fn check_anon_const(&mut self, cx: &EarlyContext<'_>, c: &ast::AnonConst) {
756 self.check_unused_delims_expr(cx, &c.value, UnusedDelimsCtx::AnonConst, false, None, None);
759 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
760 if let StmtKind::Local(ref local) = s.kind {
761 self.check_unused_parens_pat(cx, &local.pat, false, false);
764 <Self as UnusedDelimLint>::check_stmt(self, cx, s)
767 fn check_param(&mut self, cx: &EarlyContext<'_>, param: &ast::Param) {
768 self.check_unused_parens_pat(cx, ¶m.pat, true, false);
771 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
772 self.check_unused_parens_pat(cx, &arm.pat, false, false);
775 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
776 if let &ast::TyKind::Paren(ref r) = &ty.kind {
778 &ast::TyKind::TraitObject(..) => {}
779 &ast::TyKind::ImplTrait(_, ref bounds) if bounds.len() > 1 => {}
780 &ast::TyKind::Array(_, ref len) => {
781 self.check_unused_delims_expr(
784 UnusedDelimsCtx::ArrayLenExpr,
792 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(ty.span) {
795 pprust::ty_to_string(ty)
798 self.emit_unused_delims(cx, ty.span, &pattern_text, "type", (false, false));
804 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
805 <Self as UnusedDelimLint>::check_item(self, cx, item)
810 pub(super) UNUSED_BRACES,
812 "unnecessary braces around an expression"
815 declare_lint_pass!(UnusedBraces => [UNUSED_BRACES]);
817 impl UnusedDelimLint for UnusedBraces {
818 const DELIM_STR: &'static str = "braces";
820 const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = false;
822 fn lint(&self) -> &'static Lint {
826 fn check_unused_delims_expr(
828 cx: &EarlyContext<'_>,
830 ctx: UnusedDelimsCtx,
831 followed_by_block: bool,
832 left_pos: Option<BytePos>,
833 right_pos: Option<BytePos>,
836 ast::ExprKind::Block(ref inner, None)
837 if inner.rules == ast::BlockCheckMode::Default =>
839 // emit a warning under the following conditions:
841 // - the block does not have a label
842 // - the block is not `unsafe`
843 // - the block contains exactly one expression (do not lint `{ expr; }`)
844 // - `followed_by_block` is true and the internal expr may contain a `{`
845 // - the block is not multiline (do not lint multiline match arms)
849 // somewhat_long_expression
854 // - the block has no attribute and was not created inside a macro
855 // - if the block is an `anon_const`, the inner expr must be a literal
856 // (do not lint `struct A<const N: usize>; let _: A<{ 2 + 3 }>;`)
858 // FIXME(const_generics): handle paths when #67075 is fixed.
859 if let [stmt] = inner.stmts.as_slice() {
860 if let ast::StmtKind::Expr(ref expr) = stmt.kind {
861 if !Self::is_expr_delims_necessary(expr, followed_by_block)
862 && (ctx != UnusedDelimsCtx::AnonConst
863 || matches!(expr.kind, ast::ExprKind::Lit(_)))
864 // array length expressions are checked during `check_anon_const` and `check_ty`,
865 // once as `ArrayLenExpr` and once as `AnonConst`.
867 // As we do not want to lint this twice, we do not emit an error for
868 // `ArrayLenExpr` if `AnonConst` would do the same.
869 && (ctx != UnusedDelimsCtx::ArrayLenExpr
870 || !matches!(expr.kind, ast::ExprKind::Lit(_)))
871 && !cx.sess().source_map().is_multiline(value.span)
872 && value.attrs.is_empty()
873 && !value.span.from_expansion()
875 self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
880 ast::ExprKind::Let(_, ref expr) => {
881 // FIXME(#60336): Properly handle `let true = (false && true)`
882 // actually needing the parenthesis.
883 self.check_unused_delims_expr(
886 UnusedDelimsCtx::LetScrutineeExpr,
897 impl EarlyLintPass for UnusedBraces {
898 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
899 <Self as UnusedDelimLint>::check_expr(self, cx, e)
902 fn check_anon_const(&mut self, cx: &EarlyContext<'_>, c: &ast::AnonConst) {
903 self.check_unused_delims_expr(cx, &c.value, UnusedDelimsCtx::AnonConst, false, None, None);
906 fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
907 <Self as UnusedDelimLint>::check_stmt(self, cx, s)
910 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
911 if let &ast::TyKind::Paren(ref r) = &ty.kind {
912 if let ast::TyKind::Array(_, ref len) = r.kind {
913 self.check_unused_delims_expr(
916 UnusedDelimsCtx::ArrayLenExpr,
925 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
926 <Self as UnusedDelimLint>::check_item(self, cx, item)
931 UNUSED_IMPORT_BRACES,
933 "unnecessary braces around an imported item"
936 declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]);
938 impl UnusedImportBraces {
939 fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
940 if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
941 // Recursively check nested UseTrees
942 for &(ref tree, _) in items {
943 self.check_use_tree(cx, tree, item);
946 // Trigger the lint only if there is one nested item
947 if items.len() != 1 {
951 // Trigger the lint if the nested item is a non-self single item
952 let node_name = match items[0].0.kind {
953 ast::UseTreeKind::Simple(rename, ..) => {
954 let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
955 if orig_ident.name == kw::SelfLower {
958 rename.unwrap_or(orig_ident).name
960 ast::UseTreeKind::Glob => Symbol::intern("*"),
961 ast::UseTreeKind::Nested(_) => return,
964 cx.struct_span_lint(UNUSED_IMPORT_BRACES, item.span, |lint| {
965 lint.build(&format!("braces around {} is unnecessary", node_name)).emit()
971 impl EarlyLintPass for UnusedImportBraces {
972 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
973 if let ast::ItemKind::Use(ref use_tree) = item.kind {
974 self.check_use_tree(cx, use_tree, item);
980 pub(super) UNUSED_ALLOCATION,
982 "detects unnecessary allocations that can be eliminated"
985 declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]);
987 impl<'tcx> LateLintPass<'tcx> for UnusedAllocation {
988 fn check_expr(&mut self, cx: &LateContext<'_>, e: &hir::Expr<'_>) {
990 hir::ExprKind::Box(_) => {}
994 for adj in cx.typeck_results().expr_adjustments(e) {
995 if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
996 cx.struct_span_lint(UNUSED_ALLOCATION, e.span, |lint| {
998 adjustment::AutoBorrowMutability::Not => {
999 "unnecessary allocation, use `&` instead"
1001 adjustment::AutoBorrowMutability::Mut { .. } => {
1002 "unnecessary allocation, use `&mut` instead"
1005 lint.build(msg).emit()