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