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