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