]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/unused.rs
Auto merge of #67768 - wesleywiser:dnm_test_perf_65244, r=Mark-Simulacrum
[rust.git] / src / librustc_lint / unused.rs
1 use lint::{EarlyContext, LateContext, LintArray, LintContext};
2 use lint::{EarlyLintPass, LateLintPass, LintPass};
3 use rustc::hir;
4 use rustc::hir::def::{DefKind, Res};
5 use rustc::hir::def_id::DefId;
6 use rustc::lint;
7 use rustc::lint::builtin::UNUSED_ATTRIBUTES;
8 use rustc::ty::adjustment;
9 use rustc::ty::{self, Ty};
10 use rustc_data_structures::fx::FxHashMap;
11 use rustc_feature::{AttributeType, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP};
12
13 use rustc_span::{BytePos, Span};
14 use syntax::ast;
15 use syntax::attr;
16 use syntax::errors::{pluralize, Applicability};
17 use syntax::print::pprust;
18 use syntax::symbol::Symbol;
19 use syntax::symbol::{kw, sym};
20 use syntax::util::parser;
21
22 use log::debug;
23
24 declare_lint! {
25     pub UNUSED_MUST_USE,
26     Warn,
27     "unused result of a type flagged as `#[must_use]`",
28     report_in_external_macro
29 }
30
31 declare_lint! {
32     pub UNUSED_RESULTS,
33     Allow,
34     "unused result of an expression in a statement"
35 }
36
37 declare_lint_pass!(UnusedResults => [UNUSED_MUST_USE, UNUSED_RESULTS]);
38
39 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedResults {
40     fn check_stmt(&mut self, cx: &LateContext<'_, '_>, s: &hir::Stmt<'_>) {
41         let expr = match s.kind {
42             hir::StmtKind::Semi(ref expr) => &**expr,
43             _ => return,
44         };
45
46         if let hir::ExprKind::Ret(..) = expr.kind {
47             return;
48         }
49
50         let ty = cx.tables.expr_ty(&expr);
51         let type_permits_lack_of_use = check_must_use_ty(cx, ty, &expr, s.span, "", "", 1);
52
53         let mut fn_warned = false;
54         let mut op_warned = false;
55         let maybe_def_id = match expr.kind {
56             hir::ExprKind::Call(ref callee, _) => {
57                 match callee.kind {
58                     hir::ExprKind::Path(ref qpath) => {
59                         match cx.tables.qpath_res(qpath, callee.hir_id) {
60                             Res::Def(DefKind::Fn, def_id) | Res::Def(DefKind::Method, def_id) => {
61                                 Some(def_id)
62                             }
63                             // `Res::Local` if it was a closure, for which we
64                             // do not currently support must-use linting
65                             _ => None,
66                         }
67                     }
68                     _ => None,
69                 }
70             }
71             hir::ExprKind::MethodCall(..) => cx.tables.type_dependent_def_id(expr.hir_id),
72             _ => None,
73         };
74         if let Some(def_id) = maybe_def_id {
75             fn_warned = check_must_use_def(cx, def_id, s.span, "return value of ", "");
76         } else if type_permits_lack_of_use {
77             // We don't warn about unused unit or uninhabited types.
78             // (See https://github.com/rust-lang/rust/issues/43806 for details.)
79             return;
80         }
81
82         let must_use_op = match expr.kind {
83             // Hardcoding operators here seemed more expedient than the
84             // refactoring that would be needed to look up the `#[must_use]`
85             // attribute which does exist on the comparison trait methods
86             hir::ExprKind::Binary(bin_op, ..) => match bin_op.node {
87                 hir::BinOpKind::Eq
88                 | hir::BinOpKind::Lt
89                 | hir::BinOpKind::Le
90                 | hir::BinOpKind::Ne
91                 | hir::BinOpKind::Ge
92                 | hir::BinOpKind::Gt => Some("comparison"),
93                 hir::BinOpKind::Add
94                 | hir::BinOpKind::Sub
95                 | hir::BinOpKind::Div
96                 | hir::BinOpKind::Mul
97                 | hir::BinOpKind::Rem => Some("arithmetic operation"),
98                 hir::BinOpKind::And | hir::BinOpKind::Or => Some("logical operation"),
99                 hir::BinOpKind::BitXor
100                 | hir::BinOpKind::BitAnd
101                 | hir::BinOpKind::BitOr
102                 | hir::BinOpKind::Shl
103                 | hir::BinOpKind::Shr => Some("bitwise operation"),
104             },
105             hir::ExprKind::Unary(..) => Some("unary operation"),
106             _ => None,
107         };
108
109         if let Some(must_use_op) = must_use_op {
110             cx.span_lint(
111                 UNUSED_MUST_USE,
112                 expr.span,
113                 &format!("unused {} that must be used", must_use_op),
114             );
115             op_warned = true;
116         }
117
118         if !(type_permits_lack_of_use || fn_warned || op_warned) {
119             cx.span_lint(UNUSED_RESULTS, s.span, "unused result");
120         }
121
122         // Returns whether an error has been emitted (and thus another does not need to be later).
123         fn check_must_use_ty<'tcx>(
124             cx: &LateContext<'_, 'tcx>,
125             ty: Ty<'tcx>,
126             expr: &hir::Expr<'_>,
127             span: Span,
128             descr_pre: &str,
129             descr_post: &str,
130             plural_len: usize,
131         ) -> bool {
132             if ty.is_unit()
133                 || cx.tcx.is_ty_uninhabited_from(cx.tcx.hir().get_module_parent(expr.hir_id), ty)
134             {
135                 return true;
136             }
137
138             let plural_suffix = pluralize!(plural_len);
139
140             match ty.kind {
141                 ty::Adt(..) if ty.is_box() => {
142                     let boxed_ty = ty.boxed_ty();
143                     let descr_pre = &format!("{}boxed ", descr_pre);
144                     check_must_use_ty(cx, boxed_ty, expr, span, descr_pre, descr_post, plural_len)
145                 }
146                 ty::Adt(def, _) => check_must_use_def(cx, def.did, span, descr_pre, descr_post),
147                 ty::Opaque(def, _) => {
148                     let mut has_emitted = false;
149                     for (predicate, _) in cx.tcx.predicates_of(def).predicates {
150                         if let ty::Predicate::Trait(ref poly_trait_predicate) = predicate {
151                             let trait_ref = poly_trait_predicate.skip_binder().trait_ref;
152                             let def_id = trait_ref.def_id;
153                             let descr_pre =
154                                 &format!("{}implementer{} of ", descr_pre, plural_suffix,);
155                             if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
156                                 has_emitted = true;
157                                 break;
158                             }
159                         }
160                     }
161                     has_emitted
162                 }
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;
168                             let descr_post =
169                                 &format!(" trait object{}{}", plural_suffix, descr_post,);
170                             if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
171                                 has_emitted = true;
172                                 break;
173                             }
174                         }
175                     }
176                     has_emitted
177                 }
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()
183                     } else {
184                         vec![]
185                     };
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)
190                         {
191                             has_emitted = true;
192                         }
193                     }
194                     has_emitted
195                 }
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)
201                     }
202                     // Otherwise, we don't lint, to avoid false positives.
203                     _ => false,
204                 },
205                 _ => false,
206             }
207         }
208
209         // Returns whether an error has been emitted (and thus another does not need to be later).
210         fn check_must_use_def(
211             cx: &LateContext<'_, '_>,
212             def_id: DefId,
213             span: Span,
214             descr_pre_path: &str,
215             descr_post_path: &str,
216         ) -> bool {
217             for attr in cx.tcx.get_attrs(def_id).iter() {
218                 if attr.check_name(sym::must_use) {
219                     let msg = format!(
220                         "unused {}`{}`{} that must be used",
221                         descr_pre_path,
222                         cx.tcx.def_path_str(def_id),
223                         descr_post_path
224                     );
225                     let mut err = cx.struct_span_lint(UNUSED_MUST_USE, span, &msg);
226                     // check for #[must_use = "..."]
227                     if let Some(note) = attr.value_str() {
228                         err.note(&note.as_str());
229                     }
230                     err.emit();
231                     return true;
232                 }
233             }
234             false
235         }
236     }
237 }
238
239 declare_lint! {
240     pub PATH_STATEMENTS,
241     Warn,
242     "path statements with no effect"
243 }
244
245 declare_lint_pass!(PathStatements => [PATH_STATEMENTS]);
246
247 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PathStatements {
248     fn check_stmt(&mut self, cx: &LateContext<'_, '_>, s: &hir::Stmt<'_>) {
249         if let hir::StmtKind::Semi(ref expr) = s.kind {
250             if let hir::ExprKind::Path(_) = expr.kind {
251                 cx.span_lint(PATH_STATEMENTS, s.span, "path statement with no effect");
252             }
253         }
254     }
255 }
256
257 #[derive(Copy, Clone)]
258 pub struct UnusedAttributes {
259     builtin_attributes: &'static FxHashMap<Symbol, &'static BuiltinAttribute>,
260 }
261
262 impl UnusedAttributes {
263     pub fn new() -> Self {
264         UnusedAttributes { builtin_attributes: &*BUILTIN_ATTRIBUTE_MAP }
265     }
266 }
267
268 impl_lint_pass!(UnusedAttributes => [UNUSED_ATTRIBUTES]);
269
270 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAttributes {
271     fn check_attribute(&mut self, cx: &LateContext<'_, '_>, attr: &ast::Attribute) {
272         debug!("checking attribute: {:?}", attr);
273
274         if attr.is_doc_comment() {
275             return;
276         }
277
278         let attr_info = attr.ident().and_then(|ident| self.builtin_attributes.get(&ident.name));
279
280         if let Some(&&(name, ty, ..)) = attr_info {
281             match ty {
282                 AttributeType::Whitelisted => {
283                     debug!("{:?} is Whitelisted", name);
284                     return;
285                 }
286                 _ => (),
287             }
288         }
289
290         if !attr::is_used(attr) {
291             debug!("emitting warning for: {:?}", attr);
292             cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
293             // Is it a builtin attribute that must be used at the crate level?
294             if attr_info.map_or(false, |(_, ty, ..)| ty == &AttributeType::CrateLevel) {
295                 let msg = match attr.style {
296                     ast::AttrStyle::Outer => {
297                         "crate-level attribute should be an inner attribute: add an exclamation \
298                          mark: `#![foo]`"
299                     }
300                     ast::AttrStyle::Inner => "crate-level attribute should be in the root module",
301                 };
302                 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
303             }
304         } else {
305             debug!("Attr was used: {:?}", attr);
306         }
307     }
308 }
309
310 declare_lint! {
311     pub(super) UNUSED_PARENS,
312     Warn,
313     "`if`, `match`, `while` and `return` do not need parentheses"
314 }
315
316 declare_lint_pass!(UnusedParens => [UNUSED_PARENS]);
317
318 impl UnusedParens {
319     fn is_expr_parens_necessary(inner: &ast::Expr, followed_by_block: bool) -> bool {
320         followed_by_block
321             && match inner.kind {
322                 ast::ExprKind::Ret(_) | ast::ExprKind::Break(..) => true,
323                 _ => parser::contains_exterior_struct_lit(&inner),
324             }
325     }
326
327     fn check_unused_parens_expr(
328         &self,
329         cx: &EarlyContext<'_>,
330         value: &ast::Expr,
331         msg: &str,
332         followed_by_block: bool,
333         left_pos: Option<BytePos>,
334         right_pos: Option<BytePos>,
335     ) {
336         match value.kind {
337             ast::ExprKind::Paren(ref inner) => {
338                 if !Self::is_expr_parens_necessary(inner, followed_by_block)
339                     && value.attrs.is_empty()
340                     && !value.span.from_expansion()
341                 {
342                     let expr_text =
343                         if let Ok(snippet) = cx.sess().source_map().span_to_snippet(value.span) {
344                             snippet
345                         } else {
346                             pprust::expr_to_string(value)
347                         };
348                     let keep_space = (
349                         left_pos.map(|s| s >= value.span.lo()).unwrap_or(false),
350                         right_pos.map(|s| s <= value.span.hi()).unwrap_or(false),
351                     );
352                     Self::remove_outer_parens(cx, value.span, &expr_text, msg, keep_space);
353                 }
354             }
355             ast::ExprKind::Let(_, ref expr) => {
356                 // FIXME(#60336): Properly handle `let true = (false && true)`
357                 // actually needing the parenthesis.
358                 self.check_unused_parens_expr(
359                     cx,
360                     expr,
361                     "`let` head expression",
362                     followed_by_block,
363                     None,
364                     None,
365                 );
366             }
367             _ => {}
368         }
369     }
370
371     fn check_unused_parens_pat(
372         &self,
373         cx: &EarlyContext<'_>,
374         value: &ast::Pat,
375         avoid_or: bool,
376         avoid_mut: bool,
377     ) {
378         use ast::{BindingMode, Mutability, PatKind};
379
380         if let PatKind::Paren(inner) = &value.kind {
381             match inner.kind {
382                 // The lint visitor will visit each subpattern of `p`. We do not want to lint
383                 // any range pattern no matter where it occurs in the pattern. For something like
384                 // `&(a..=b)`, there is a recursive `check_pat` on `a` and `b`, but we will assume
385                 // that if there are unnecessary parens they serve a purpose of readability.
386                 PatKind::Range(..) => return,
387                 // Avoid `p0 | .. | pn` if we should.
388                 PatKind::Or(..) if avoid_or => return,
389                 // Avoid `mut x` and `mut x @ p` if we should:
390                 PatKind::Ident(BindingMode::ByValue(Mutability::Mut), ..) if avoid_mut => return,
391                 // Otherwise proceed with linting.
392                 _ => {}
393             }
394
395             let pattern_text =
396                 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(value.span) {
397                     snippet
398                 } else {
399                     pprust::pat_to_string(value)
400                 };
401             Self::remove_outer_parens(cx, value.span, &pattern_text, "pattern", (false, false));
402         }
403     }
404
405     fn remove_outer_parens(
406         cx: &EarlyContext<'_>,
407         span: Span,
408         pattern: &str,
409         msg: &str,
410         keep_space: (bool, bool),
411     ) {
412         let span_msg = format!("unnecessary parentheses around {}", msg);
413         let mut err = cx.struct_span_lint(UNUSED_PARENS, span, &span_msg);
414         let mut ate_left_paren = false;
415         let mut ate_right_paren = false;
416         let parens_removed = pattern.trim_matches(|c| match c {
417             '(' => {
418                 if ate_left_paren {
419                     false
420                 } else {
421                     ate_left_paren = true;
422                     true
423                 }
424             }
425             ')' => {
426                 if ate_right_paren {
427                     false
428                 } else {
429                     ate_right_paren = true;
430                     true
431                 }
432             }
433             _ => false,
434         });
435
436         let replace = {
437             let mut replace = if keep_space.0 {
438                 let mut s = String::from(" ");
439                 s.push_str(parens_removed);
440                 s
441             } else {
442                 String::from(parens_removed)
443             };
444
445             if keep_space.1 {
446                 replace.push(' ');
447             }
448             replace
449         };
450
451         err.span_suggestion_short(
452             span,
453             "remove these parentheses",
454             replace,
455             Applicability::MachineApplicable,
456         );
457         err.emit();
458     }
459 }
460
461 impl EarlyLintPass for UnusedParens {
462     fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
463         use syntax::ast::ExprKind::*;
464         let (value, msg, followed_by_block, left_pos, right_pos) = match e.kind {
465             Let(ref pat, ..) => {
466                 self.check_unused_parens_pat(cx, pat, false, false);
467                 return;
468             }
469
470             If(ref cond, ref block, ..) => {
471                 let left = e.span.lo() + rustc_span::BytePos(2);
472                 let right = block.span.lo();
473                 (cond, "`if` condition", true, Some(left), Some(right))
474             }
475
476             While(ref cond, ref block, ..) => {
477                 let left = e.span.lo() + rustc_span::BytePos(5);
478                 let right = block.span.lo();
479                 (cond, "`while` condition", true, Some(left), Some(right))
480             }
481
482             ForLoop(ref pat, ref cond, ref block, ..) => {
483                 self.check_unused_parens_pat(cx, pat, false, false);
484                 (cond, "`for` head expression", true, None, Some(block.span.lo()))
485             }
486
487             Match(ref head, _) => {
488                 let left = e.span.lo() + rustc_span::BytePos(5);
489                 (head, "`match` head expression", true, Some(left), None)
490             }
491
492             Ret(Some(ref value)) => {
493                 let left = e.span.lo() + rustc_span::BytePos(3);
494                 (value, "`return` value", false, Some(left), None)
495             }
496
497             Assign(_, ref value, _) => (value, "assigned value", false, None, None),
498             AssignOp(.., ref value) => (value, "assigned value", false, None, None),
499             // either function/method call, or something this lint doesn't care about
500             ref call_or_other => {
501                 let (args_to_check, call_kind) = match *call_or_other {
502                     Call(_, ref args) => (&args[..], "function"),
503                     // first "argument" is self (which sometimes needs parens)
504                     MethodCall(_, ref args) => (&args[1..], "method"),
505                     // actual catch-all arm
506                     _ => {
507                         return;
508                     }
509                 };
510                 // Don't lint if this is a nested macro expansion: otherwise, the lint could
511                 // trigger in situations that macro authors shouldn't have to care about, e.g.,
512                 // when a parenthesized token tree matched in one macro expansion is matched as
513                 // an expression in another and used as a fn/method argument (Issue #47775)
514                 if e.span.ctxt().outer_expn_data().call_site.from_expansion() {
515                     return;
516                 }
517                 let msg = format!("{} argument", call_kind);
518                 for arg in args_to_check {
519                     self.check_unused_parens_expr(cx, arg, &msg, false, None, None);
520                 }
521                 return;
522             }
523         };
524         self.check_unused_parens_expr(cx, &value, msg, followed_by_block, left_pos, right_pos);
525     }
526
527     fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
528         use ast::{Mutability, PatKind::*};
529         match &p.kind {
530             // Do not lint on `(..)` as that will result in the other arms being useless.
531             Paren(_)
532             // The other cases do not contain sub-patterns.
533             | Wild | Rest | Lit(..) | Mac(..) | Range(..) | Ident(.., None) | Path(..) => return,
534             // These are list-like patterns; parens can always be removed.
535             TupleStruct(_, ps) | Tuple(ps) | Slice(ps) | Or(ps) => for p in ps {
536                 self.check_unused_parens_pat(cx, p, false, false);
537             },
538             Struct(_, fps, _) => for f in fps {
539                 self.check_unused_parens_pat(cx, &f.pat, false, false);
540             },
541             // Avoid linting on `i @ (p0 | .. | pn)` and `box (p0 | .. | pn)`, #64106.
542             Ident(.., Some(p)) | Box(p) => self.check_unused_parens_pat(cx, p, true, false),
543             // Avoid linting on `&(mut x)` as `&mut x` has a different meaning, #55342.
544             // Also avoid linting on `& mut? (p0 | .. | pn)`, #64106.
545             Ref(p, m) => self.check_unused_parens_pat(cx, p, true, *m == Mutability::Not),
546         }
547     }
548
549     fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
550         if let ast::StmtKind::Local(ref local) = s.kind {
551             self.check_unused_parens_pat(cx, &local.pat, false, false);
552
553             if let Some(ref value) = local.init {
554                 self.check_unused_parens_expr(cx, &value, "assigned value", false, None, None);
555             }
556         }
557     }
558
559     fn check_param(&mut self, cx: &EarlyContext<'_>, param: &ast::Param) {
560         self.check_unused_parens_pat(cx, &param.pat, true, false);
561     }
562
563     fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
564         self.check_unused_parens_pat(cx, &arm.pat, false, false);
565     }
566
567     fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
568         if let &ast::TyKind::Paren(ref r) = &ty.kind {
569             match &r.kind {
570                 &ast::TyKind::TraitObject(..) => {}
571                 &ast::TyKind::ImplTrait(_, ref bounds) if bounds.len() > 1 => {}
572                 _ => {
573                     let pattern_text =
574                         if let Ok(snippet) = cx.sess().source_map().span_to_snippet(ty.span) {
575                             snippet
576                         } else {
577                             pprust::ty_to_string(ty)
578                         };
579
580                     Self::remove_outer_parens(cx, ty.span, &pattern_text, "type", (false, false));
581                 }
582             }
583         }
584     }
585 }
586
587 declare_lint! {
588     UNUSED_IMPORT_BRACES,
589     Allow,
590     "unnecessary braces around an imported item"
591 }
592
593 declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]);
594
595 impl UnusedImportBraces {
596     fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
597         if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
598             // Recursively check nested UseTrees
599             for &(ref tree, _) in items {
600                 self.check_use_tree(cx, tree, item);
601             }
602
603             // Trigger the lint only if there is one nested item
604             if items.len() != 1 {
605                 return;
606             }
607
608             // Trigger the lint if the nested item is a non-self single item
609             let node_name = match items[0].0.kind {
610                 ast::UseTreeKind::Simple(rename, ..) => {
611                     let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
612                     if orig_ident.name == kw::SelfLower {
613                         return;
614                     }
615                     rename.unwrap_or(orig_ident).name
616                 }
617                 ast::UseTreeKind::Glob => Symbol::intern("*"),
618                 ast::UseTreeKind::Nested(_) => return,
619             };
620
621             let msg = format!("braces around {} is unnecessary", node_name);
622             cx.span_lint(UNUSED_IMPORT_BRACES, item.span, &msg);
623         }
624     }
625 }
626
627 impl EarlyLintPass for UnusedImportBraces {
628     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
629         if let ast::ItemKind::Use(ref use_tree) = item.kind {
630             self.check_use_tree(cx, use_tree, item);
631         }
632     }
633 }
634
635 declare_lint! {
636     pub(super) UNUSED_ALLOCATION,
637     Warn,
638     "detects unnecessary allocations that can be eliminated"
639 }
640
641 declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]);
642
643 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAllocation {
644     fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr<'_>) {
645         match e.kind {
646             hir::ExprKind::Box(_) => {}
647             _ => return,
648         }
649
650         for adj in cx.tables.expr_adjustments(e) {
651             if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
652                 let msg = match m {
653                     adjustment::AutoBorrowMutability::Not => {
654                         "unnecessary allocation, use `&` instead"
655                     }
656                     adjustment::AutoBorrowMutability::Mut { .. } => {
657                         "unnecessary allocation, use `&mut` instead"
658                     }
659                 };
660                 cx.span_lint(UNUSED_ALLOCATION, e.span, msg);
661             }
662         }
663     }
664 }