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