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