]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/unused.rs
migrate: `unused.rs`
[rust.git] / compiler / rustc_lint / src / unused.rs
1 #![deny(rustc::untranslatable_diagnostic)]
2 #![deny(rustc::diagnostic_outside_of_impl)]
3 use crate::lints::{
4     PathStatementDrop, PathStatementDropSub, PathStatementNoEffect, UnusedAllocationDiag,
5     UnusedAllocationMutDiag, UnusedClosure, UnusedDef, UnusedDelim, UnusedDelimSuggestion,
6     UnusedGenerator, UnusedImportBracesDiag, UnusedOp, UnusedResult,
7 };
8 use crate::Lint;
9 use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
10 use rustc_ast as ast;
11 use rustc_ast::util::{classify, parser};
12 use rustc_ast::{ExprKind, StmtKind};
13 use rustc_errors::{pluralize, MultiSpan};
14 use rustc_hir as hir;
15 use rustc_hir::def::{DefKind, Res};
16 use rustc_hir::def_id::DefId;
17 use rustc_infer::traits::util::elaborate_predicates_with_span;
18 use rustc_middle::ty::adjustment;
19 use rustc_middle::ty::{self, DefIdTree, Ty};
20 use rustc_span::symbol::Symbol;
21 use rustc_span::symbol::{kw, sym};
22 use rustc_span::{BytePos, Span};
23 use std::iter;
24
25 declare_lint! {
26     /// The `unused_must_use` lint detects unused result of a type flagged as
27     /// `#[must_use]`.
28     ///
29     /// ### Example
30     ///
31     /// ```rust
32     /// fn returns_result() -> Result<(), ()> {
33     ///     Ok(())
34     /// }
35     ///
36     /// fn main() {
37     ///     returns_result();
38     /// }
39     /// ```
40     ///
41     /// {{produces}}
42     ///
43     /// ### Explanation
44     ///
45     /// The `#[must_use]` attribute is an indicator that it is a mistake to
46     /// ignore the value. See [the reference] for more details.
47     ///
48     /// [the reference]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
49     pub UNUSED_MUST_USE,
50     Warn,
51     "unused result of a type flagged as `#[must_use]`",
52     report_in_external_macro
53 }
54
55 declare_lint! {
56     /// The `unused_results` lint checks for the unused result of an
57     /// expression in a statement.
58     ///
59     /// ### Example
60     ///
61     /// ```rust,compile_fail
62     /// #![deny(unused_results)]
63     /// fn foo<T>() -> T { panic!() }
64     ///
65     /// fn main() {
66     ///     foo::<usize>();
67     /// }
68     /// ```
69     ///
70     /// {{produces}}
71     ///
72     /// ### Explanation
73     ///
74     /// Ignoring the return value of a function may indicate a mistake. In
75     /// cases were it is almost certain that the result should be used, it is
76     /// recommended to annotate the function with the [`must_use` attribute].
77     /// Failure to use such a return value will trigger the [`unused_must_use`
78     /// lint] which is warn-by-default. The `unused_results` lint is
79     /// essentially the same, but triggers for *all* return values.
80     ///
81     /// This lint is "allow" by default because it can be noisy, and may not be
82     /// an actual problem. For example, calling the `remove` method of a `Vec`
83     /// or `HashMap` returns the previous value, which you may not care about.
84     /// Using this lint would require explicitly ignoring or discarding such
85     /// values.
86     ///
87     /// [`must_use` attribute]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
88     /// [`unused_must_use` lint]: warn-by-default.html#unused-must-use
89     pub UNUSED_RESULTS,
90     Allow,
91     "unused result of an expression in a statement"
92 }
93
94 declare_lint_pass!(UnusedResults => [UNUSED_MUST_USE, UNUSED_RESULTS]);
95
96 impl<'tcx> LateLintPass<'tcx> for UnusedResults {
97     fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
98         let hir::StmtKind::Semi(expr) = s.kind else { return; };
99
100         if let hir::ExprKind::Ret(..) = expr.kind {
101             return;
102         }
103
104         if let hir::ExprKind::Match(await_expr, _arms, hir::MatchSource::AwaitDesugar) = expr.kind
105             && let ty = cx.typeck_results().expr_ty(&await_expr)
106             && let ty::Alias(ty::Opaque, ty::AliasTy { def_id: future_def_id, .. }) = ty.kind()
107             && cx.tcx.ty_is_opaque_future(ty)
108             // FIXME: This also includes non-async fns that return `impl Future`.
109             && let async_fn_def_id = cx.tcx.parent(*future_def_id)
110             && check_must_use_def(
111                 cx,
112                 async_fn_def_id,
113                 expr.span,
114                 "output of future returned by ",
115                 "",
116             )
117         {
118             // We have a bare `foo().await;` on an opaque type from an async function that was
119             // annotated with `#[must_use]`.
120             return;
121         }
122
123         let ty = cx.typeck_results().expr_ty(&expr);
124
125         let must_use_result = is_ty_must_use(cx, ty, &expr, expr.span);
126         let type_lint_emitted_or_suppressed = match must_use_result {
127             Some(path) => {
128                 emit_must_use_untranslated(cx, &path, "", "", 1);
129                 true
130             }
131             None => false,
132         };
133
134         let fn_warned = check_fn_must_use(cx, expr);
135
136         if !fn_warned && type_lint_emitted_or_suppressed {
137             // We don't warn about unused unit or uninhabited types.
138             // (See https://github.com/rust-lang/rust/issues/43806 for details.)
139             return;
140         }
141
142         let must_use_op = match expr.kind {
143             // Hardcoding operators here seemed more expedient than the
144             // refactoring that would be needed to look up the `#[must_use]`
145             // attribute which does exist on the comparison trait methods
146             hir::ExprKind::Binary(bin_op, ..) => match bin_op.node {
147                 hir::BinOpKind::Eq
148                 | hir::BinOpKind::Lt
149                 | hir::BinOpKind::Le
150                 | hir::BinOpKind::Ne
151                 | hir::BinOpKind::Ge
152                 | hir::BinOpKind::Gt => Some("comparison"),
153                 hir::BinOpKind::Add
154                 | hir::BinOpKind::Sub
155                 | hir::BinOpKind::Div
156                 | hir::BinOpKind::Mul
157                 | hir::BinOpKind::Rem => Some("arithmetic operation"),
158                 hir::BinOpKind::And | hir::BinOpKind::Or => Some("logical operation"),
159                 hir::BinOpKind::BitXor
160                 | hir::BinOpKind::BitAnd
161                 | hir::BinOpKind::BitOr
162                 | hir::BinOpKind::Shl
163                 | hir::BinOpKind::Shr => Some("bitwise operation"),
164             },
165             hir::ExprKind::AddrOf(..) => Some("borrow"),
166             hir::ExprKind::Unary(..) => Some("unary operation"),
167             _ => None,
168         };
169
170         let mut op_warned = false;
171
172         if let Some(must_use_op) = must_use_op {
173             cx.emit_spanned_lint(
174                 UNUSED_MUST_USE,
175                 expr.span,
176                 UnusedOp {
177                     op: must_use_op,
178                     label: expr.span,
179                     suggestion: expr.span.shrink_to_lo(),
180                 },
181             );
182             op_warned = true;
183         }
184
185         if !(type_lint_emitted_or_suppressed || fn_warned || op_warned) {
186             cx.emit_spanned_lint(UNUSED_RESULTS, s.span, UnusedResult { ty });
187         }
188
189         fn check_fn_must_use(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool {
190             let maybe_def_id = match expr.kind {
191                 hir::ExprKind::Call(ref callee, _) => {
192                     match callee.kind {
193                         hir::ExprKind::Path(ref qpath) => {
194                             match cx.qpath_res(qpath, callee.hir_id) {
195                                 Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) => Some(def_id),
196                                 // `Res::Local` if it was a closure, for which we
197                                 // do not currently support must-use linting
198                                 _ => None,
199                             }
200                         }
201                         _ => None,
202                     }
203                 }
204                 hir::ExprKind::MethodCall(..) => {
205                     cx.typeck_results().type_dependent_def_id(expr.hir_id)
206                 }
207                 _ => None,
208             };
209             if let Some(def_id) = maybe_def_id {
210                 check_must_use_def(cx, def_id, expr.span, "return value of ", "")
211             } else {
212                 false
213             }
214         }
215
216         /// A path through a type to a must_use source. Contains useful info for the lint.
217         #[derive(Debug)]
218         enum MustUsePath {
219             /// Suppress must_use checking.
220             Suppressed,
221             /// The root of the normal must_use lint with an optional message.
222             Def(Span, DefId, Option<Symbol>),
223             Boxed(Box<Self>),
224             Opaque(Box<Self>),
225             TraitObject(Box<Self>),
226             TupleElement(Vec<(usize, Self)>),
227             Array(Box<Self>, u64),
228             /// The root of the unused_closures lint.
229             Closure(Span),
230             /// The root of the unused_generators lint.
231             Generator(Span),
232         }
233
234         #[instrument(skip(cx, expr), level = "debug", ret)]
235         fn is_ty_must_use<'tcx>(
236             cx: &LateContext<'tcx>,
237             ty: Ty<'tcx>,
238             expr: &hir::Expr<'_>,
239             span: Span,
240         ) -> Option<MustUsePath> {
241             if ty.is_unit()
242                 || !ty.is_inhabited_from(
243                     cx.tcx,
244                     cx.tcx.parent_module(expr.hir_id).to_def_id(),
245                     cx.param_env,
246                 )
247             {
248                 return Some(MustUsePath::Suppressed);
249             }
250
251             match *ty.kind() {
252                 ty::Adt(..) if ty.is_box() => {
253                     let boxed_ty = ty.boxed_ty();
254                     is_ty_must_use(cx, boxed_ty, expr, span)
255                         .map(|inner| MustUsePath::Boxed(Box::new(inner)))
256                 }
257                 ty::Adt(def, _) => is_def_must_use(cx, def.did(), span),
258                 ty::Alias(ty::Opaque, ty::AliasTy { def_id: def, .. }) => {
259                     elaborate_predicates_with_span(
260                         cx.tcx,
261                         cx.tcx.explicit_item_bounds(def).iter().cloned(),
262                     )
263                     .find_map(|obligation| {
264                         // We only look at the `DefId`, so it is safe to skip the binder here.
265                         if let ty::PredicateKind::Clause(ty::Clause::Trait(
266                             ref poly_trait_predicate,
267                         )) = obligation.predicate.kind().skip_binder()
268                         {
269                             let def_id = poly_trait_predicate.trait_ref.def_id;
270
271                             is_def_must_use(cx, def_id, span)
272                         } else {
273                             None
274                         }
275                     })
276                     .map(|inner| MustUsePath::Opaque(Box::new(inner)))
277                 }
278                 ty::Dynamic(binders, _, _) => binders.iter().find_map(|predicate| {
279                     if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder()
280                     {
281                         let def_id = trait_ref.def_id;
282                         is_def_must_use(cx, def_id, span)
283                             .map(|inner| MustUsePath::TraitObject(Box::new(inner)))
284                     } else {
285                         None
286                     }
287                 }),
288                 ty::Tuple(tys) => {
289                     let elem_exprs = if let hir::ExprKind::Tup(elem_exprs) = expr.kind {
290                         debug_assert_eq!(elem_exprs.len(), tys.len());
291                         elem_exprs
292                     } else {
293                         &[]
294                     };
295
296                     // Default to `expr`.
297                     let elem_exprs = elem_exprs.iter().chain(iter::repeat(expr));
298
299                     let nested_must_use = tys
300                         .iter()
301                         .zip(elem_exprs)
302                         .enumerate()
303                         .filter_map(|(i, (ty, expr))| {
304                             is_ty_must_use(cx, ty, expr, expr.span).map(|path| (i, path))
305                         })
306                         .collect::<Vec<_>>();
307
308                     if !nested_must_use.is_empty() {
309                         Some(MustUsePath::TupleElement(nested_must_use))
310                     } else {
311                         None
312                     }
313                 }
314                 ty::Array(ty, len) => match len.try_eval_usize(cx.tcx, cx.param_env) {
315                     // If the array is empty we don't lint, to avoid false positives
316                     Some(0) | None => None,
317                     // If the array is definitely non-empty, we can do `#[must_use]` checking.
318                     Some(len) => is_ty_must_use(cx, ty, expr, span)
319                         .map(|inner| MustUsePath::Array(Box::new(inner), len)),
320                 },
321                 ty::Closure(..) => Some(MustUsePath::Closure(span)),
322                 ty::Generator(def_id, ..) => {
323                     // async fn should be treated as "implementor of `Future`"
324                     let must_use = if cx.tcx.generator_is_async(def_id) {
325                         let def_id = cx.tcx.lang_items().future_trait().unwrap();
326                         is_def_must_use(cx, def_id, span)
327                             .map(|inner| MustUsePath::Opaque(Box::new(inner)))
328                     } else {
329                         None
330                     };
331                     must_use.or(Some(MustUsePath::Generator(span)))
332                 }
333                 _ => None,
334             }
335         }
336
337         fn is_def_must_use(cx: &LateContext<'_>, def_id: DefId, span: Span) -> Option<MustUsePath> {
338             if let Some(attr) = cx.tcx.get_attr(def_id, sym::must_use) {
339                 // check for #[must_use = "..."]
340                 let reason = attr.value_str();
341                 Some(MustUsePath::Def(span, def_id, reason))
342             } else {
343                 None
344             }
345         }
346
347         // Returns whether further errors should be suppressed because either a lint has been emitted or the type should be ignored.
348         fn check_must_use_def(
349             cx: &LateContext<'_>,
350             def_id: DefId,
351             span: Span,
352             descr_pre_path: &str,
353             descr_post_path: &str,
354         ) -> bool {
355             is_def_must_use(cx, def_id, span)
356                 .map(|must_use_path| {
357                     emit_must_use_untranslated(
358                         cx,
359                         &must_use_path,
360                         descr_pre_path,
361                         descr_post_path,
362                         1,
363                     )
364                 })
365                 .is_some()
366         }
367
368         #[instrument(skip(cx), level = "debug")]
369         fn emit_must_use_untranslated(
370             cx: &LateContext<'_>,
371             path: &MustUsePath,
372             descr_pre: &str,
373             descr_post: &str,
374             plural_len: usize,
375         ) {
376             let plural_suffix = pluralize!(plural_len);
377
378             match path {
379                 MustUsePath::Suppressed => {}
380                 MustUsePath::Boxed(path) => {
381                     let descr_pre = &format!("{}boxed ", descr_pre);
382                     emit_must_use_untranslated(cx, path, descr_pre, descr_post, plural_len);
383                 }
384                 MustUsePath::Opaque(path) => {
385                     let descr_pre = &format!("{}implementer{} of ", descr_pre, plural_suffix);
386                     emit_must_use_untranslated(cx, path, descr_pre, descr_post, plural_len);
387                 }
388                 MustUsePath::TraitObject(path) => {
389                     let descr_post = &format!(" trait object{}{}", plural_suffix, descr_post);
390                     emit_must_use_untranslated(cx, path, descr_pre, descr_post, plural_len);
391                 }
392                 MustUsePath::TupleElement(elems) => {
393                     for (index, path) in elems {
394                         let descr_post = &format!(" in tuple element {}", index);
395                         emit_must_use_untranslated(cx, path, descr_pre, descr_post, plural_len);
396                     }
397                 }
398                 MustUsePath::Array(path, len) => {
399                     let descr_pre = &format!("{}array{} of ", descr_pre, plural_suffix);
400                     emit_must_use_untranslated(
401                         cx,
402                         path,
403                         descr_pre,
404                         descr_post,
405                         plural_len.saturating_add(usize::try_from(*len).unwrap_or(usize::MAX)),
406                     );
407                 }
408                 MustUsePath::Closure(span) => {
409                     cx.emit_spanned_lint(
410                         UNUSED_MUST_USE,
411                         *span,
412                         UnusedClosure { count: plural_len, pre: descr_pre, post: descr_post },
413                     );
414                 }
415                 MustUsePath::Generator(span) => {
416                     cx.emit_spanned_lint(
417                         UNUSED_MUST_USE,
418                         *span,
419                         UnusedGenerator { count: plural_len, pre: descr_pre, post: descr_post },
420                     );
421                 }
422                 MustUsePath::Def(span, def_id, reason) => {
423                     cx.emit_spanned_lint(
424                         UNUSED_MUST_USE,
425                         *span,
426                         UnusedDef {
427                             pre: descr_pre,
428                             post: descr_post,
429                             cx,
430                             def_id: *def_id,
431                             note: *reason,
432                         },
433                     );
434                 }
435             }
436         }
437     }
438 }
439
440 declare_lint! {
441     /// The `path_statements` lint detects path statements with no effect.
442     ///
443     /// ### Example
444     ///
445     /// ```rust
446     /// let x = 42;
447     ///
448     /// x;
449     /// ```
450     ///
451     /// {{produces}}
452     ///
453     /// ### Explanation
454     ///
455     /// It is usually a mistake to have a statement that has no effect.
456     pub PATH_STATEMENTS,
457     Warn,
458     "path statements with no effect"
459 }
460
461 declare_lint_pass!(PathStatements => [PATH_STATEMENTS]);
462
463 impl<'tcx> LateLintPass<'tcx> for PathStatements {
464     fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
465         if let hir::StmtKind::Semi(expr) = s.kind {
466             if let hir::ExprKind::Path(_) = expr.kind {
467                 let ty = cx.typeck_results().expr_ty(expr);
468                 if ty.needs_drop(cx.tcx, cx.param_env) {
469                     let sub = if let Ok(snippet) = cx.sess().source_map().span_to_snippet(expr.span)
470                     {
471                         PathStatementDropSub::Suggestion { span: s.span, snippet }
472                     } else {
473                         PathStatementDropSub::Help { span: s.span }
474                     };
475                     cx.emit_spanned_lint(PATH_STATEMENTS, s.span, PathStatementDrop { sub })
476                 } else {
477                     cx.emit_spanned_lint(PATH_STATEMENTS, s.span, PathStatementNoEffect);
478                 }
479             }
480         }
481     }
482 }
483
484 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
485 enum UnusedDelimsCtx {
486     FunctionArg,
487     MethodArg,
488     AssignedValue,
489     AssignedValueLetElse,
490     IfCond,
491     WhileCond,
492     ForIterExpr,
493     MatchScrutineeExpr,
494     ReturnValue,
495     BlockRetValue,
496     LetScrutineeExpr,
497     ArrayLenExpr,
498     AnonConst,
499     MatchArmExpr,
500 }
501
502 impl From<UnusedDelimsCtx> for &'static str {
503     fn from(ctx: UnusedDelimsCtx) -> &'static str {
504         match ctx {
505             UnusedDelimsCtx::FunctionArg => "function argument",
506             UnusedDelimsCtx::MethodArg => "method argument",
507             UnusedDelimsCtx::AssignedValue | UnusedDelimsCtx::AssignedValueLetElse => {
508                 "assigned value"
509             }
510             UnusedDelimsCtx::IfCond => "`if` condition",
511             UnusedDelimsCtx::WhileCond => "`while` condition",
512             UnusedDelimsCtx::ForIterExpr => "`for` iterator expression",
513             UnusedDelimsCtx::MatchScrutineeExpr => "`match` scrutinee expression",
514             UnusedDelimsCtx::ReturnValue => "`return` value",
515             UnusedDelimsCtx::BlockRetValue => "block return value",
516             UnusedDelimsCtx::LetScrutineeExpr => "`let` scrutinee expression",
517             UnusedDelimsCtx::ArrayLenExpr | UnusedDelimsCtx::AnonConst => "const expression",
518             UnusedDelimsCtx::MatchArmExpr => "match arm expression",
519         }
520     }
521 }
522
523 /// Used by both `UnusedParens` and `UnusedBraces` to prevent code duplication.
524 trait UnusedDelimLint {
525     const DELIM_STR: &'static str;
526
527     /// Due to `ref` pattern, there can be a difference between using
528     /// `{ expr }` and `expr` in pattern-matching contexts. This means
529     /// that we should only lint `unused_parens` and not `unused_braces`
530     /// in this case.
531     ///
532     /// ```rust
533     /// let mut a = 7;
534     /// let ref b = { a }; // We actually borrow a copy of `a` here.
535     /// a += 1; // By mutating `a` we invalidate any borrows of `a`.
536     /// assert_eq!(b + 1, a); // `b` does not borrow `a`, so we can still use it here.
537     /// ```
538     const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool;
539
540     // this cannot be a constant is it refers to a static.
541     fn lint(&self) -> &'static Lint;
542
543     fn check_unused_delims_expr(
544         &self,
545         cx: &EarlyContext<'_>,
546         value: &ast::Expr,
547         ctx: UnusedDelimsCtx,
548         followed_by_block: bool,
549         left_pos: Option<BytePos>,
550         right_pos: Option<BytePos>,
551     );
552
553     fn is_expr_delims_necessary(
554         inner: &ast::Expr,
555         followed_by_block: bool,
556         followed_by_else: bool,
557     ) -> bool {
558         if followed_by_else {
559             match inner.kind {
560                 ast::ExprKind::Binary(op, ..) if op.node.lazy() => return true,
561                 _ if classify::expr_trailing_brace(inner).is_some() => return true,
562                 _ => {}
563             }
564         }
565
566         // Prevent false-positives in cases like `fn x() -> u8 { ({ 0 } + 1) }`
567         let lhs_needs_parens = {
568             let mut innermost = inner;
569             loop {
570                 innermost = match &innermost.kind {
571                     ExprKind::Binary(_, lhs, _rhs) => lhs,
572                     ExprKind::Call(fn_, _params) => fn_,
573                     ExprKind::Cast(expr, _ty) => expr,
574                     ExprKind::Type(expr, _ty) => expr,
575                     ExprKind::Index(base, _subscript) => base,
576                     _ => break false,
577                 };
578                 if !classify::expr_requires_semi_to_be_stmt(innermost) {
579                     break true;
580                 }
581             }
582         };
583
584         lhs_needs_parens
585             || (followed_by_block
586                 && match &inner.kind {
587                     ExprKind::Ret(_)
588                     | ExprKind::Break(..)
589                     | ExprKind::Yield(..)
590                     | ExprKind::Yeet(..) => true,
591                     ExprKind::Range(_lhs, Some(rhs), _limits) => {
592                         matches!(rhs.kind, ExprKind::Block(..))
593                     }
594                     _ => parser::contains_exterior_struct_lit(&inner),
595                 })
596     }
597
598     fn emit_unused_delims_expr(
599         &self,
600         cx: &EarlyContext<'_>,
601         value: &ast::Expr,
602         ctx: UnusedDelimsCtx,
603         left_pos: Option<BytePos>,
604         right_pos: Option<BytePos>,
605     ) {
606         // If `value` has `ExprKind::Err`, unused delim lint can be broken.
607         // For example, the following code caused ICE.
608         // This is because the `ExprKind::Call` in `value` has `ExprKind::Err` as its argument
609         // and this leads to wrong spans. #104897
610         //
611         // ```
612         // fn f(){(print!(á
613         // ```
614         use rustc_ast::visit::{walk_expr, Visitor};
615         struct ErrExprVisitor {
616             has_error: bool,
617         }
618         impl<'ast> Visitor<'ast> for ErrExprVisitor {
619             fn visit_expr(&mut self, expr: &'ast ast::Expr) {
620                 if let ExprKind::Err = expr.kind {
621                     self.has_error = true;
622                     return;
623                 }
624                 walk_expr(self, expr)
625             }
626         }
627         let mut visitor = ErrExprVisitor { has_error: false };
628         visitor.visit_expr(value);
629         if visitor.has_error {
630             return;
631         }
632         let spans = match value.kind {
633             ast::ExprKind::Block(ref block, None) if block.stmts.len() == 1 => {
634                 if let Some(span) = block.stmts[0].span.find_ancestor_inside(value.span) {
635                     Some((value.span.with_hi(span.lo()), value.span.with_lo(span.hi())))
636                 } else {
637                     None
638                 }
639             }
640             ast::ExprKind::Paren(ref expr) => {
641                 let expr_span = expr.span.find_ancestor_inside(value.span);
642                 if let Some(expr_span) = expr_span {
643                     Some((value.span.with_hi(expr_span.lo()), value.span.with_lo(expr_span.hi())))
644                 } else {
645                     None
646                 }
647             }
648             _ => return,
649         };
650         let keep_space = (
651             left_pos.map_or(false, |s| s >= value.span.lo()),
652             right_pos.map_or(false, |s| s <= value.span.hi()),
653         );
654         self.emit_unused_delims(cx, value.span, spans, ctx.into(), keep_space);
655     }
656
657     fn emit_unused_delims(
658         &self,
659         cx: &EarlyContext<'_>,
660         value_span: Span,
661         spans: Option<(Span, Span)>,
662         msg: &str,
663         keep_space: (bool, bool),
664     ) {
665         let primary_span = if let Some((lo, hi)) = spans {
666             MultiSpan::from(vec![lo, hi])
667         } else {
668             MultiSpan::from(value_span)
669         };
670         let suggestion = spans.map(|(lo, hi)| {
671             let sm = cx.sess().source_map();
672             let lo_replace =
673                     if keep_space.0 &&
674                         let Ok(snip) = sm.span_to_prev_source(lo) && !snip.ends_with(' ') {
675                         " "
676                         } else {
677                             ""
678                         };
679
680             let hi_replace =
681                     if keep_space.1 &&
682                         let Ok(snip) = sm.span_to_next_source(hi) && !snip.starts_with(' ') {
683                         " "
684                         } else {
685                             ""
686                         };
687             UnusedDelimSuggestion {
688                 start_span: lo,
689                 start_replace: lo_replace,
690                 end_span: hi,
691                 end_replace: hi_replace,
692             }
693         });
694         cx.emit_spanned_lint(
695             self.lint(),
696             primary_span,
697             UnusedDelim { delim: Self::DELIM_STR, item: msg, suggestion },
698         );
699     }
700
701     fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
702         use rustc_ast::ExprKind::*;
703         let (value, ctx, followed_by_block, left_pos, right_pos) = match e.kind {
704             // Do not lint `unused_braces` in `if let` expressions.
705             If(ref cond, ref block, _)
706                 if !matches!(cond.kind, Let(_, _, _))
707                     || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
708             {
709                 let left = e.span.lo() + rustc_span::BytePos(2);
710                 let right = block.span.lo();
711                 (cond, UnusedDelimsCtx::IfCond, true, Some(left), Some(right))
712             }
713
714             // Do not lint `unused_braces` in `while let` expressions.
715             While(ref cond, ref block, ..)
716                 if !matches!(cond.kind, Let(_, _, _))
717                     || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
718             {
719                 let left = e.span.lo() + rustc_span::BytePos(5);
720                 let right = block.span.lo();
721                 (cond, UnusedDelimsCtx::WhileCond, true, Some(left), Some(right))
722             }
723
724             ForLoop(_, ref cond, ref block, ..) => {
725                 (cond, UnusedDelimsCtx::ForIterExpr, true, None, Some(block.span.lo()))
726             }
727
728             Match(ref head, _) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
729                 let left = e.span.lo() + rustc_span::BytePos(5);
730                 (head, UnusedDelimsCtx::MatchScrutineeExpr, true, Some(left), None)
731             }
732
733             Ret(Some(ref value)) => {
734                 let left = e.span.lo() + rustc_span::BytePos(3);
735                 (value, UnusedDelimsCtx::ReturnValue, false, Some(left), None)
736             }
737
738             Assign(_, ref value, _) | AssignOp(.., ref value) => {
739                 (value, UnusedDelimsCtx::AssignedValue, false, None, None)
740             }
741             // either function/method call, or something this lint doesn't care about
742             ref call_or_other => {
743                 let (args_to_check, ctx) = match *call_or_other {
744                     Call(_, ref args) => (&args[..], UnusedDelimsCtx::FunctionArg),
745                     MethodCall(ref call) => (&call.args[..], UnusedDelimsCtx::MethodArg),
746                     // actual catch-all arm
747                     _ => {
748                         return;
749                     }
750                 };
751                 // Don't lint if this is a nested macro expansion: otherwise, the lint could
752                 // trigger in situations that macro authors shouldn't have to care about, e.g.,
753                 // when a parenthesized token tree matched in one macro expansion is matched as
754                 // an expression in another and used as a fn/method argument (Issue #47775)
755                 if e.span.ctxt().outer_expn_data().call_site.from_expansion() {
756                     return;
757                 }
758                 for arg in args_to_check {
759                     self.check_unused_delims_expr(cx, arg, ctx, false, None, None);
760                 }
761                 return;
762             }
763         };
764         self.check_unused_delims_expr(cx, &value, ctx, followed_by_block, left_pos, right_pos);
765     }
766
767     fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
768         match s.kind {
769             StmtKind::Local(ref local) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
770                 if let Some((init, els)) = local.kind.init_else_opt() {
771                     let ctx = match els {
772                         None => UnusedDelimsCtx::AssignedValue,
773                         Some(_) => UnusedDelimsCtx::AssignedValueLetElse,
774                     };
775                     self.check_unused_delims_expr(cx, init, ctx, false, None, None);
776                 }
777             }
778             StmtKind::Expr(ref expr) => {
779                 self.check_unused_delims_expr(
780                     cx,
781                     &expr,
782                     UnusedDelimsCtx::BlockRetValue,
783                     false,
784                     None,
785                     None,
786                 );
787             }
788             _ => {}
789         }
790     }
791
792     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
793         use ast::ItemKind::*;
794
795         if let Const(.., Some(expr)) | Static(.., Some(expr)) = &item.kind {
796             self.check_unused_delims_expr(
797                 cx,
798                 expr,
799                 UnusedDelimsCtx::AssignedValue,
800                 false,
801                 None,
802                 None,
803             );
804         }
805     }
806 }
807
808 declare_lint! {
809     /// The `unused_parens` lint detects `if`, `match`, `while` and `return`
810     /// with parentheses; they do not need them.
811     ///
812     /// ### Examples
813     ///
814     /// ```rust
815     /// if(true) {}
816     /// ```
817     ///
818     /// {{produces}}
819     ///
820     /// ### Explanation
821     ///
822     /// The parentheses are not needed, and should be removed. This is the
823     /// preferred style for writing these expressions.
824     pub(super) UNUSED_PARENS,
825     Warn,
826     "`if`, `match`, `while` and `return` do not need parentheses"
827 }
828
829 declare_lint_pass!(UnusedParens => [UNUSED_PARENS]);
830
831 impl UnusedDelimLint for UnusedParens {
832     const DELIM_STR: &'static str = "parentheses";
833
834     const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = true;
835
836     fn lint(&self) -> &'static Lint {
837         UNUSED_PARENS
838     }
839
840     fn check_unused_delims_expr(
841         &self,
842         cx: &EarlyContext<'_>,
843         value: &ast::Expr,
844         ctx: UnusedDelimsCtx,
845         followed_by_block: bool,
846         left_pos: Option<BytePos>,
847         right_pos: Option<BytePos>,
848     ) {
849         match value.kind {
850             ast::ExprKind::Paren(ref inner) => {
851                 let followed_by_else = ctx == UnusedDelimsCtx::AssignedValueLetElse;
852                 if !Self::is_expr_delims_necessary(inner, followed_by_block, followed_by_else)
853                     && value.attrs.is_empty()
854                     && !value.span.from_expansion()
855                     && (ctx != UnusedDelimsCtx::LetScrutineeExpr
856                         || !matches!(inner.kind, ast::ExprKind::Binary(
857                                 rustc_span::source_map::Spanned { node, .. },
858                                 _,
859                                 _,
860                             ) if node.lazy()))
861                 {
862                     self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
863                 }
864             }
865             ast::ExprKind::Let(_, ref expr, _) => {
866                 self.check_unused_delims_expr(
867                     cx,
868                     expr,
869                     UnusedDelimsCtx::LetScrutineeExpr,
870                     followed_by_block,
871                     None,
872                     None,
873                 );
874             }
875             _ => {}
876         }
877     }
878 }
879
880 impl UnusedParens {
881     fn check_unused_parens_pat(
882         &self,
883         cx: &EarlyContext<'_>,
884         value: &ast::Pat,
885         avoid_or: bool,
886         avoid_mut: bool,
887         keep_space: (bool, bool),
888     ) {
889         use ast::{BindingAnnotation, PatKind};
890
891         if let PatKind::Paren(inner) = &value.kind {
892             match inner.kind {
893                 // The lint visitor will visit each subpattern of `p`. We do not want to lint
894                 // any range pattern no matter where it occurs in the pattern. For something like
895                 // `&(a..=b)`, there is a recursive `check_pat` on `a` and `b`, but we will assume
896                 // that if there are unnecessary parens they serve a purpose of readability.
897                 PatKind::Range(..) => return,
898                 // Avoid `p0 | .. | pn` if we should.
899                 PatKind::Or(..) if avoid_or => return,
900                 // Avoid `mut x` and `mut x @ p` if we should:
901                 PatKind::Ident(BindingAnnotation::MUT, ..) if avoid_mut => {
902                     return;
903                 }
904                 // Otherwise proceed with linting.
905                 _ => {}
906             }
907             let spans = if let Some(inner) = inner.span.find_ancestor_inside(value.span) {
908                 Some((value.span.with_hi(inner.lo()), value.span.with_lo(inner.hi())))
909             } else {
910                 None
911             };
912             self.emit_unused_delims(cx, value.span, spans, "pattern", keep_space);
913         }
914     }
915 }
916
917 impl EarlyLintPass for UnusedParens {
918     #[inline]
919     fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
920         match e.kind {
921             ExprKind::Let(ref pat, _, _) | ExprKind::ForLoop(ref pat, ..) => {
922                 self.check_unused_parens_pat(cx, pat, false, false, (true, true));
923             }
924             // We ignore parens in cases like `if (((let Some(0) = Some(1))))` because we already
925             // handle a hard error for them during AST lowering in `lower_expr_mut`, but we still
926             // want to complain about things like `if let 42 = (42)`.
927             ExprKind::If(ref cond, ref block, ref else_)
928                 if matches!(cond.peel_parens().kind, ExprKind::Let(..)) =>
929             {
930                 self.check_unused_delims_expr(
931                     cx,
932                     cond.peel_parens(),
933                     UnusedDelimsCtx::LetScrutineeExpr,
934                     true,
935                     None,
936                     None,
937                 );
938                 for stmt in &block.stmts {
939                     <Self as UnusedDelimLint>::check_stmt(self, cx, stmt);
940                 }
941                 if let Some(e) = else_ {
942                     <Self as UnusedDelimLint>::check_expr(self, cx, e);
943                 }
944                 return;
945             }
946             ExprKind::Match(ref _expr, ref arm) => {
947                 for a in arm {
948                     self.check_unused_delims_expr(
949                         cx,
950                         &a.body,
951                         UnusedDelimsCtx::MatchArmExpr,
952                         false,
953                         None,
954                         None,
955                     );
956                 }
957             }
958             _ => {}
959         }
960
961         <Self as UnusedDelimLint>::check_expr(self, cx, e)
962     }
963
964     fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
965         use ast::{Mutability, PatKind::*};
966         let keep_space = (false, false);
967         match &p.kind {
968             // Do not lint on `(..)` as that will result in the other arms being useless.
969             Paren(_)
970             // The other cases do not contain sub-patterns.
971             | Wild | Rest | Lit(..) | MacCall(..) | Range(..) | Ident(.., None) | Path(..) => {},
972             // These are list-like patterns; parens can always be removed.
973             TupleStruct(_, _, ps) | Tuple(ps) | Slice(ps) | Or(ps) => for p in ps {
974                 self.check_unused_parens_pat(cx, p, false, false, keep_space);
975             },
976             Struct(_, _, fps, _) => for f in fps {
977                 self.check_unused_parens_pat(cx, &f.pat, false, false, keep_space);
978             },
979             // Avoid linting on `i @ (p0 | .. | pn)` and `box (p0 | .. | pn)`, #64106.
980             Ident(.., Some(p)) | Box(p) => self.check_unused_parens_pat(cx, p, true, false, keep_space),
981             // Avoid linting on `&(mut x)` as `&mut x` has a different meaning, #55342.
982             // Also avoid linting on `& mut? (p0 | .. | pn)`, #64106.
983             Ref(p, m) => self.check_unused_parens_pat(cx, p, true, *m == Mutability::Not, keep_space),
984         }
985     }
986
987     fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
988         if let StmtKind::Local(ref local) = s.kind {
989             self.check_unused_parens_pat(cx, &local.pat, true, false, (false, false));
990         }
991
992         <Self as UnusedDelimLint>::check_stmt(self, cx, s)
993     }
994
995     fn check_param(&mut self, cx: &EarlyContext<'_>, param: &ast::Param) {
996         self.check_unused_parens_pat(cx, &param.pat, true, false, (false, false));
997     }
998
999     fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
1000         self.check_unused_parens_pat(cx, &arm.pat, false, false, (false, false));
1001     }
1002
1003     fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
1004         if let ast::TyKind::Paren(r) = &ty.kind {
1005             match &r.kind {
1006                 ast::TyKind::TraitObject(..) => {}
1007                 ast::TyKind::BareFn(b) if b.generic_params.len() > 0 => {}
1008                 ast::TyKind::ImplTrait(_, bounds) if bounds.len() > 1 => {}
1009                 ast::TyKind::Array(_, len) => {
1010                     self.check_unused_delims_expr(
1011                         cx,
1012                         &len.value,
1013                         UnusedDelimsCtx::ArrayLenExpr,
1014                         false,
1015                         None,
1016                         None,
1017                     );
1018                 }
1019                 _ => {
1020                     let spans = if let Some(r) = r.span.find_ancestor_inside(ty.span) {
1021                         Some((ty.span.with_hi(r.lo()), ty.span.with_lo(r.hi())))
1022                     } else {
1023                         None
1024                     };
1025                     self.emit_unused_delims(cx, ty.span, spans, "type", (false, false));
1026                 }
1027             }
1028         }
1029     }
1030
1031     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1032         <Self as UnusedDelimLint>::check_item(self, cx, item)
1033     }
1034 }
1035
1036 declare_lint! {
1037     /// The `unused_braces` lint detects unnecessary braces around an
1038     /// expression.
1039     ///
1040     /// ### Example
1041     ///
1042     /// ```rust
1043     /// if { true } {
1044     ///     // ...
1045     /// }
1046     /// ```
1047     ///
1048     /// {{produces}}
1049     ///
1050     /// ### Explanation
1051     ///
1052     /// The braces are not needed, and should be removed. This is the
1053     /// preferred style for writing these expressions.
1054     pub(super) UNUSED_BRACES,
1055     Warn,
1056     "unnecessary braces around an expression"
1057 }
1058
1059 declare_lint_pass!(UnusedBraces => [UNUSED_BRACES]);
1060
1061 impl UnusedDelimLint for UnusedBraces {
1062     const DELIM_STR: &'static str = "braces";
1063
1064     const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = false;
1065
1066     fn lint(&self) -> &'static Lint {
1067         UNUSED_BRACES
1068     }
1069
1070     fn check_unused_delims_expr(
1071         &self,
1072         cx: &EarlyContext<'_>,
1073         value: &ast::Expr,
1074         ctx: UnusedDelimsCtx,
1075         followed_by_block: bool,
1076         left_pos: Option<BytePos>,
1077         right_pos: Option<BytePos>,
1078     ) {
1079         match value.kind {
1080             ast::ExprKind::Block(ref inner, None)
1081                 if inner.rules == ast::BlockCheckMode::Default =>
1082             {
1083                 // emit a warning under the following conditions:
1084                 //
1085                 // - the block does not have a label
1086                 // - the block is not `unsafe`
1087                 // - the block contains exactly one expression (do not lint `{ expr; }`)
1088                 // - `followed_by_block` is true and the internal expr may contain a `{`
1089                 // - the block is not multiline (do not lint multiline match arms)
1090                 //      ```
1091                 //      match expr {
1092                 //          Pattern => {
1093                 //              somewhat_long_expression
1094                 //          }
1095                 //          // ...
1096                 //      }
1097                 //      ```
1098                 // - the block has no attribute and was not created inside a macro
1099                 // - if the block is an `anon_const`, the inner expr must be a literal
1100                 //      (do not lint `struct A<const N: usize>; let _: A<{ 2 + 3 }>;`)
1101                 //
1102                 // FIXME(const_generics): handle paths when #67075 is fixed.
1103                 if let [stmt] = inner.stmts.as_slice() {
1104                     if let ast::StmtKind::Expr(ref expr) = stmt.kind {
1105                         if !Self::is_expr_delims_necessary(expr, followed_by_block, false)
1106                             && (ctx != UnusedDelimsCtx::AnonConst
1107                                 || matches!(expr.kind, ast::ExprKind::Lit(_)))
1108                             && !cx.sess().source_map().is_multiline(value.span)
1109                             && value.attrs.is_empty()
1110                             && !value.span.from_expansion()
1111                             && !inner.span.from_expansion()
1112                         {
1113                             self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
1114                         }
1115                     }
1116                 }
1117             }
1118             ast::ExprKind::Let(_, ref expr, _) => {
1119                 self.check_unused_delims_expr(
1120                     cx,
1121                     expr,
1122                     UnusedDelimsCtx::LetScrutineeExpr,
1123                     followed_by_block,
1124                     None,
1125                     None,
1126                 );
1127             }
1128             _ => {}
1129         }
1130     }
1131 }
1132
1133 impl EarlyLintPass for UnusedBraces {
1134     fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
1135         <Self as UnusedDelimLint>::check_stmt(self, cx, s)
1136     }
1137
1138     #[inline]
1139     fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
1140         <Self as UnusedDelimLint>::check_expr(self, cx, e);
1141
1142         if let ExprKind::Repeat(_, ref anon_const) = e.kind {
1143             self.check_unused_delims_expr(
1144                 cx,
1145                 &anon_const.value,
1146                 UnusedDelimsCtx::AnonConst,
1147                 false,
1148                 None,
1149                 None,
1150             );
1151         }
1152     }
1153
1154     fn check_generic_arg(&mut self, cx: &EarlyContext<'_>, arg: &ast::GenericArg) {
1155         if let ast::GenericArg::Const(ct) = arg {
1156             self.check_unused_delims_expr(
1157                 cx,
1158                 &ct.value,
1159                 UnusedDelimsCtx::AnonConst,
1160                 false,
1161                 None,
1162                 None,
1163             );
1164         }
1165     }
1166
1167     fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant) {
1168         if let Some(anon_const) = &v.disr_expr {
1169             self.check_unused_delims_expr(
1170                 cx,
1171                 &anon_const.value,
1172                 UnusedDelimsCtx::AnonConst,
1173                 false,
1174                 None,
1175                 None,
1176             );
1177         }
1178     }
1179
1180     fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
1181         match ty.kind {
1182             ast::TyKind::Array(_, ref len) => {
1183                 self.check_unused_delims_expr(
1184                     cx,
1185                     &len.value,
1186                     UnusedDelimsCtx::ArrayLenExpr,
1187                     false,
1188                     None,
1189                     None,
1190                 );
1191             }
1192
1193             ast::TyKind::Typeof(ref anon_const) => {
1194                 self.check_unused_delims_expr(
1195                     cx,
1196                     &anon_const.value,
1197                     UnusedDelimsCtx::AnonConst,
1198                     false,
1199                     None,
1200                     None,
1201                 );
1202             }
1203
1204             _ => {}
1205         }
1206     }
1207
1208     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1209         <Self as UnusedDelimLint>::check_item(self, cx, item)
1210     }
1211 }
1212
1213 declare_lint! {
1214     /// The `unused_import_braces` lint catches unnecessary braces around an
1215     /// imported item.
1216     ///
1217     /// ### Example
1218     ///
1219     /// ```rust,compile_fail
1220     /// #![deny(unused_import_braces)]
1221     /// use test::{A};
1222     ///
1223     /// pub mod test {
1224     ///     pub struct A;
1225     /// }
1226     /// # fn main() {}
1227     /// ```
1228     ///
1229     /// {{produces}}
1230     ///
1231     /// ### Explanation
1232     ///
1233     /// If there is only a single item, then remove the braces (`use test::A;`
1234     /// for example).
1235     ///
1236     /// This lint is "allow" by default because it is only enforcing a
1237     /// stylistic choice.
1238     UNUSED_IMPORT_BRACES,
1239     Allow,
1240     "unnecessary braces around an imported item"
1241 }
1242
1243 declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]);
1244
1245 impl UnusedImportBraces {
1246     fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
1247         if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
1248             // Recursively check nested UseTrees
1249             for (tree, _) in items {
1250                 self.check_use_tree(cx, tree, item);
1251             }
1252
1253             // Trigger the lint only if there is one nested item
1254             if items.len() != 1 {
1255                 return;
1256             }
1257
1258             // Trigger the lint if the nested item is a non-self single item
1259             let node_name = match items[0].0.kind {
1260                 ast::UseTreeKind::Simple(rename) => {
1261                     let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
1262                     if orig_ident.name == kw::SelfLower {
1263                         return;
1264                     }
1265                     rename.unwrap_or(orig_ident).name
1266                 }
1267                 ast::UseTreeKind::Glob => Symbol::intern("*"),
1268                 ast::UseTreeKind::Nested(_) => return,
1269             };
1270
1271             cx.emit_spanned_lint(
1272                 UNUSED_IMPORT_BRACES,
1273                 item.span,
1274                 UnusedImportBracesDiag { node: node_name },
1275             );
1276         }
1277     }
1278 }
1279
1280 impl EarlyLintPass for UnusedImportBraces {
1281     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1282         if let ast::ItemKind::Use(ref use_tree) = item.kind {
1283             self.check_use_tree(cx, use_tree, item);
1284         }
1285     }
1286 }
1287
1288 declare_lint! {
1289     /// The `unused_allocation` lint detects unnecessary allocations that can
1290     /// be eliminated.
1291     ///
1292     /// ### Example
1293     ///
1294     /// ```rust
1295     /// #![feature(box_syntax)]
1296     /// fn main() {
1297     ///     let a = (box [1, 2, 3]).len();
1298     /// }
1299     /// ```
1300     ///
1301     /// {{produces}}
1302     ///
1303     /// ### Explanation
1304     ///
1305     /// When a `box` expression is immediately coerced to a reference, then
1306     /// the allocation is unnecessary, and a reference (using `&` or `&mut`)
1307     /// should be used instead to avoid the allocation.
1308     pub(super) UNUSED_ALLOCATION,
1309     Warn,
1310     "detects unnecessary allocations that can be eliminated"
1311 }
1312
1313 declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]);
1314
1315 impl<'tcx> LateLintPass<'tcx> for UnusedAllocation {
1316     fn check_expr(&mut self, cx: &LateContext<'_>, e: &hir::Expr<'_>) {
1317         match e.kind {
1318             hir::ExprKind::Box(_) => {}
1319             _ => return,
1320         }
1321
1322         for adj in cx.typeck_results().expr_adjustments(e) {
1323             if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
1324                 match m {
1325                     adjustment::AutoBorrowMutability::Not => {
1326                         cx.emit_spanned_lint(UNUSED_ALLOCATION, e.span, UnusedAllocationDiag);
1327                     }
1328                     adjustment::AutoBorrowMutability::Mut { .. } => {
1329                         cx.emit_spanned_lint(UNUSED_ALLOCATION, e.span, UnusedAllocationMutDiag);
1330                     }
1331                 };
1332             }
1333         }
1334     }
1335 }