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