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