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