]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/unused.rs
Rollup merge of #65746 - estebank:newcomer-format, r=Centril
[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::ty::{self, Ty};
5 use rustc::ty::adjustment;
6 use rustc_data_structures::fx::FxHashMap;
7 use lint::{LateContext, EarlyContext, LintContext, LintArray};
8 use lint::{LintPass, EarlyLintPass, LateLintPass};
9
10 use syntax::ast;
11 use syntax::attr;
12 use syntax::errors::{Applicability, pluralise};
13 use syntax::feature_gate::{AttributeType, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP};
14 use syntax::print::pprust;
15 use syntax::symbol::{kw, sym};
16 use syntax::symbol::Symbol;
17 use syntax::util::parser;
18 use syntax_pos::{Span, BytePos};
19
20 use rustc::hir;
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 = pluralise!(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 declare_lint! {
281     pub UNUSED_ATTRIBUTES,
282     Warn,
283     "detects attributes that were not used by the compiler"
284 }
285
286 #[derive(Copy, Clone)]
287 pub struct UnusedAttributes {
288     builtin_attributes: &'static FxHashMap<Symbol, &'static BuiltinAttribute>,
289 }
290
291 impl UnusedAttributes {
292     pub fn new() -> Self {
293         UnusedAttributes {
294             builtin_attributes: &*BUILTIN_ATTRIBUTE_MAP,
295         }
296     }
297 }
298
299 impl_lint_pass!(UnusedAttributes => [UNUSED_ATTRIBUTES]);
300
301 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAttributes {
302     fn check_attribute(&mut self, cx: &LateContext<'_, '_>, attr: &ast::Attribute) {
303         debug!("checking attribute: {:?}", attr);
304
305         let attr_info = attr.ident().and_then(|ident| self.builtin_attributes.get(&ident.name));
306
307         if let Some(&&(name, ty, ..)) = attr_info {
308             match ty {
309                 AttributeType::Whitelisted => {
310                     debug!("{:?} is Whitelisted", name);
311                     return;
312                 }
313                 _ => (),
314             }
315         }
316
317         let plugin_attributes = cx.sess().plugin_attributes.borrow_mut();
318         for &(name, ty) in plugin_attributes.iter() {
319             if ty == AttributeType::Whitelisted && attr.check_name(name) {
320                 debug!("{:?} (plugin attr) is whitelisted with ty {:?}", name, ty);
321                 break;
322             }
323         }
324
325         let name = attr.name_or_empty();
326         if !attr::is_used(attr) {
327             debug!("emitting warning for: {:?}", attr);
328             cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
329             // Is it a builtin attribute that must be used at the crate level?
330             let known_crate = attr_info.map(|&&(_, ty, ..)| {
331                     ty == AttributeType::CrateLevel
332             }).unwrap_or(false);
333
334             // Has a plugin registered this attribute as one that must be used at
335             // the crate level?
336             let plugin_crate = plugin_attributes.iter()
337                 .find(|&&(x, t)| name == x && AttributeType::CrateLevel == t)
338                 .is_some();
339             if known_crate || plugin_crate {
340                 let msg = match attr.style {
341                     ast::AttrStyle::Outer => {
342                         "crate-level attribute should be an inner attribute: add an exclamation \
343                          mark: `#![foo]`"
344                     }
345                     ast::AttrStyle::Inner => "crate-level attribute should be in the root module",
346                 };
347                 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
348             }
349         } else {
350             debug!("Attr was used: {:?}", attr);
351         }
352     }
353 }
354
355 declare_lint! {
356     pub(super) UNUSED_PARENS,
357     Warn,
358     "`if`, `match`, `while` and `return` do not need parentheses"
359 }
360
361 declare_lint_pass!(UnusedParens => [UNUSED_PARENS]);
362
363 impl UnusedParens {
364
365     fn is_expr_parens_necessary(inner: &ast::Expr, followed_by_block: bool) -> bool {
366         followed_by_block && match inner.kind {
367             ast::ExprKind::Ret(_) | ast::ExprKind::Break(..) => true,
368             _ => parser::contains_exterior_struct_lit(&inner),
369         }
370     }
371
372     fn check_unused_parens_expr(&self,
373                                      cx: &EarlyContext<'_>,
374                                      value: &ast::Expr,
375                                      msg: &str,
376                                      followed_by_block: bool,
377                                      left_pos: Option<BytePos>,
378                                      right_pos: Option<BytePos>) {
379         match value.kind {
380             ast::ExprKind::Paren(ref inner) => {
381                 if !Self::is_expr_parens_necessary(inner, followed_by_block) &&
382                     value.attrs.is_empty() {
383                     let expr_text = if let Ok(snippet) = cx.sess().source_map()
384                         .span_to_snippet(value.span) {
385                             snippet
386                         } else {
387                             pprust::expr_to_string(value)
388                         };
389                     let keep_space = (
390                         left_pos.map(|s| s >= value.span.lo()).unwrap_or(false),
391                         right_pos.map(|s| s <= value.span.hi()).unwrap_or(false),
392                     );
393                     Self::remove_outer_parens(cx, value.span, &expr_text, msg, keep_space);
394                 }
395             }
396             ast::ExprKind::Let(_, ref expr) => {
397                 // FIXME(#60336): Properly handle `let true = (false && true)`
398                 // actually needing the parenthesis.
399                 self.check_unused_parens_expr(
400                     cx, expr,
401                     "`let` head expression",
402                     followed_by_block,
403                     None, None
404                 );
405             }
406             _ => {}
407         }
408     }
409
410     fn check_unused_parens_pat(
411         &self,
412         cx: &EarlyContext<'_>,
413         value: &ast::Pat,
414         avoid_or: bool,
415         avoid_mut: bool,
416     ) {
417         use ast::{PatKind, BindingMode::ByValue, Mutability::Mutable};
418
419         if let PatKind::Paren(inner) = &value.kind {
420             match inner.kind {
421                 // The lint visitor will visit each subpattern of `p`. We do not want to lint
422                 // any range pattern no matter where it occurs in the pattern. For something like
423                 // `&(a..=b)`, there is a recursive `check_pat` on `a` and `b`, but we will assume
424                 // that if there are unnecessary parens they serve a purpose of readability.
425                 PatKind::Range(..) => return,
426                 // Avoid `p0 | .. | pn` if we should.
427                 PatKind::Or(..) if avoid_or => return,
428                 // Avoid `mut x` and `mut x @ p` if we should:
429                 PatKind::Ident(ByValue(Mutable), ..) if avoid_mut => return,
430                 // Otherwise proceed with linting.
431                 _ => {}
432             }
433
434             let pattern_text = if let Ok(snippet) = cx.sess().source_map()
435                 .span_to_snippet(value.span) {
436                     snippet
437                 } else {
438                     pprust::pat_to_string(value)
439                 };
440             Self::remove_outer_parens(cx, value.span, &pattern_text, "pattern", (false, false));
441         }
442     }
443
444     fn remove_outer_parens(cx: &EarlyContext<'_>,
445                            span: Span,
446                            pattern: &str,
447                            msg: &str,
448                            keep_space: (bool, bool)) {
449         let span_msg = format!("unnecessary parentheses around {}", msg);
450         let mut err = cx.struct_span_lint(UNUSED_PARENS, span, &span_msg);
451         let mut ate_left_paren = false;
452         let mut ate_right_paren = false;
453         let parens_removed = pattern
454             .trim_matches(|c| {
455                 match c {
456                     '(' => {
457                         if ate_left_paren {
458                             false
459                         } else {
460                             ate_left_paren = true;
461                             true
462                         }
463                     },
464                     ')' => {
465                         if ate_right_paren {
466                             false
467                         } else {
468                             ate_right_paren = true;
469                             true
470                         }
471                     },
472                     _ => false,
473                 }
474             });
475
476         let replace = {
477             let mut replace = if keep_space.0 {
478                 let mut s = String::from(" ");
479                 s.push_str(parens_removed);
480                 s
481             } else {
482                 String::from(parens_removed)
483             };
484
485             if keep_space.1 {
486                 replace.push(' ');
487             }
488             replace
489         };
490
491         err.span_suggestion_short(
492             span,
493             "remove these parentheses",
494             replace,
495             Applicability::MachineApplicable,
496         );
497         err.emit();
498     }
499 }
500
501 impl EarlyLintPass for UnusedParens {
502     fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
503         use syntax::ast::ExprKind::*;
504         let (value, msg, followed_by_block, left_pos, right_pos) = match e.kind {
505             Let(ref pat, ..) => {
506                 self.check_unused_parens_pat(cx, pat, false, false);
507                 return;
508             }
509
510             If(ref cond, ref block, ..) => {
511                 let left = e.span.lo() + syntax_pos::BytePos(2);
512                 let right = block.span.lo();
513                 (cond, "`if` condition", true, Some(left), Some(right))
514             }
515
516             While(ref cond, ref block, ..) => {
517                 let left = e.span.lo() + syntax_pos::BytePos(5);
518                 let right = block.span.lo();
519                 (cond, "`while` condition", true, Some(left), Some(right))
520             },
521
522             ForLoop(ref pat, ref cond, ref block, ..) => {
523                 self.check_unused_parens_pat(cx, pat, false, false);
524                 (cond, "`for` head expression", true, None, Some(block.span.lo()))
525             }
526
527             Match(ref head, _) => {
528                 let left = e.span.lo() + syntax_pos::BytePos(5);
529                 (head, "`match` head expression", true, Some(left), None)
530             }
531
532             Ret(Some(ref value)) => {
533                 let left = e.span.lo() + syntax_pos::BytePos(3);
534                 (value, "`return` value", false, Some(left), None)
535             }
536
537             Assign(_, ref value) => (value, "assigned value", false, None, None),
538             AssignOp(.., ref value) => (value, "assigned value", false, None, None),
539             // either function/method call, or something this lint doesn't care about
540             ref call_or_other => {
541                 let (args_to_check, call_kind) = match *call_or_other {
542                     Call(_, ref args) => (&args[..], "function"),
543                     // first "argument" is self (which sometimes needs parens)
544                     MethodCall(_, ref args) => (&args[1..], "method"),
545                     // actual catch-all arm
546                     _ => {
547                         return;
548                     }
549                 };
550                 // Don't lint if this is a nested macro expansion: otherwise, the lint could
551                 // trigger in situations that macro authors shouldn't have to care about, e.g.,
552                 // when a parenthesized token tree matched in one macro expansion is matched as
553                 // an expression in another and used as a fn/method argument (Issue #47775)
554                 if e.span.ctxt().outer_expn_data().call_site.from_expansion() {
555                     return;
556                 }
557                 let msg = format!("{} argument", call_kind);
558                 for arg in args_to_check {
559                     self.check_unused_parens_expr(cx, arg, &msg, false, None, None);
560                 }
561                 return;
562             }
563         };
564         self.check_unused_parens_expr(cx, &value, msg, followed_by_block, left_pos, right_pos);
565     }
566
567     fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
568         use ast::{PatKind::*, Mutability};
569         match &p.kind {
570             // Do not lint on `(..)` as that will result in the other arms being useless.
571             Paren(_)
572             // The other cases do not contain sub-patterns.
573             | Wild | Rest | Lit(..) | Mac(..) | Range(..) | Ident(.., None) | Path(..) => return,
574             // These are list-like patterns; parens can always be removed.
575             TupleStruct(_, ps) | Tuple(ps) | Slice(ps) | Or(ps) => for p in ps {
576                 self.check_unused_parens_pat(cx, p, false, false);
577             },
578             Struct(_, fps, _) => for f in fps {
579                 self.check_unused_parens_pat(cx, &f.pat, false, false);
580             },
581             // Avoid linting on `i @ (p0 | .. | pn)` and `box (p0 | .. | pn)`, #64106.
582             Ident(.., Some(p)) | Box(p) => self.check_unused_parens_pat(cx, p, true, false),
583             // Avoid linting on `&(mut x)` as `&mut x` has a different meaning, #55342.
584             // Also avoid linting on `& mut? (p0 | .. | pn)`, #64106.
585             Ref(p, m) => self.check_unused_parens_pat(cx, p, true, *m == Mutability::Immutable),
586         }
587     }
588
589     fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
590         if let ast::StmtKind::Local(ref local) = s.kind {
591             self.check_unused_parens_pat(cx, &local.pat, false, false);
592
593             if let Some(ref value) = local.init {
594                 self.check_unused_parens_expr(cx, &value, "assigned value", false, None, None);
595             }
596         }
597     }
598
599     fn check_param(&mut self, cx: &EarlyContext<'_>, param: &ast::Param) {
600         self.check_unused_parens_pat(cx, &param.pat, true, false);
601     }
602
603     fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
604         self.check_unused_parens_pat(cx, &arm.pat, false, false);
605     }
606 }
607
608 declare_lint! {
609     UNUSED_IMPORT_BRACES,
610     Allow,
611     "unnecessary braces around an imported item"
612 }
613
614 declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]);
615
616 impl UnusedImportBraces {
617     fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
618         if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
619             // Recursively check nested UseTrees
620             for &(ref tree, _) in items {
621                 self.check_use_tree(cx, tree, item);
622             }
623
624             // Trigger the lint only if there is one nested item
625             if items.len() != 1 {
626                 return;
627             }
628
629             // Trigger the lint if the nested item is a non-self single item
630             let node_name = match items[0].0.kind {
631                 ast::UseTreeKind::Simple(rename, ..) => {
632                     let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
633                     if orig_ident.name == kw::SelfLower {
634                         return;
635                     }
636                     rename.unwrap_or(orig_ident).name
637                 }
638                 ast::UseTreeKind::Glob => Symbol::intern("*"),
639                 ast::UseTreeKind::Nested(_) => return,
640             };
641
642             let msg = format!("braces around {} is unnecessary", node_name);
643             cx.span_lint(UNUSED_IMPORT_BRACES, item.span, &msg);
644         }
645     }
646 }
647
648 impl EarlyLintPass for UnusedImportBraces {
649     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
650         if let ast::ItemKind::Use(ref use_tree) = item.kind {
651             self.check_use_tree(cx, use_tree, item);
652         }
653     }
654 }
655
656 declare_lint! {
657     pub(super) UNUSED_ALLOCATION,
658     Warn,
659     "detects unnecessary allocations that can be eliminated"
660 }
661
662 declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]);
663
664 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAllocation {
665     fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr) {
666         match e.kind {
667             hir::ExprKind::Box(_) => {}
668             _ => return,
669         }
670
671         for adj in cx.tables.expr_adjustments(e) {
672             if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
673                 let msg = match m {
674                     adjustment::AutoBorrowMutability::Immutable =>
675                         "unnecessary allocation, use `&` instead",
676                     adjustment::AutoBorrowMutability::Mutable { .. }=>
677                         "unnecessary allocation, use `&mut` instead"
678                 };
679                 cx.span_lint(UNUSED_ALLOCATION, e.span, msg);
680             }
681         }
682     }
683 }