]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/unused.rs
Rollup merge of #105245 - RalfJung:align_to, r=Amanieu
[rust.git] / compiler / rustc_lint / src / unused.rs
1 use crate::Lint;
2 use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
3 use rustc_ast as ast;
4 use rustc_ast::util::{classify, parser};
5 use rustc_ast::{ExprKind, StmtKind};
6 use rustc_errors::{fluent, pluralize, Applicability, MultiSpan};
7 use rustc_hir as hir;
8 use rustc_hir::def::{DefKind, Res};
9 use rustc_hir::def_id::DefId;
10 use rustc_infer::traits::util::elaborate_predicates_with_span;
11 use rustc_middle::ty::adjustment;
12 use rustc_middle::ty::{self, DefIdTree, Ty};
13 use rustc_span::symbol::Symbol;
14 use rustc_span::symbol::{kw, sym};
15 use rustc_span::{BytePos, Span};
16 use std::iter;
17
18 declare_lint! {
19     /// The `unused_must_use` lint detects unused result of a type flagged as
20     /// `#[must_use]`.
21     ///
22     /// ### Example
23     ///
24     /// ```rust
25     /// fn returns_result() -> Result<(), ()> {
26     ///     Ok(())
27     /// }
28     ///
29     /// fn main() {
30     ///     returns_result();
31     /// }
32     /// ```
33     ///
34     /// {{produces}}
35     ///
36     /// ### Explanation
37     ///
38     /// The `#[must_use]` attribute is an indicator that it is a mistake to
39     /// ignore the value. See [the reference] for more details.
40     ///
41     /// [the reference]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
42     pub UNUSED_MUST_USE,
43     Warn,
44     "unused result of a type flagged as `#[must_use]`",
45     report_in_external_macro
46 }
47
48 declare_lint! {
49     /// The `unused_results` lint checks for the unused result of an
50     /// expression in a statement.
51     ///
52     /// ### Example
53     ///
54     /// ```rust,compile_fail
55     /// #![deny(unused_results)]
56     /// fn foo<T>() -> T { panic!() }
57     ///
58     /// fn main() {
59     ///     foo::<usize>();
60     /// }
61     /// ```
62     ///
63     /// {{produces}}
64     ///
65     /// ### Explanation
66     ///
67     /// Ignoring the return value of a function may indicate a mistake. In
68     /// cases were it is almost certain that the result should be used, it is
69     /// recommended to annotate the function with the [`must_use` attribute].
70     /// Failure to use such a return value will trigger the [`unused_must_use`
71     /// lint] which is warn-by-default. The `unused_results` lint is
72     /// essentially the same, but triggers for *all* return values.
73     ///
74     /// This lint is "allow" by default because it can be noisy, and may not be
75     /// an actual problem. For example, calling the `remove` method of a `Vec`
76     /// or `HashMap` returns the previous value, which you may not care about.
77     /// Using this lint would require explicitly ignoring or discarding such
78     /// values.
79     ///
80     /// [`must_use` attribute]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
81     /// [`unused_must_use` lint]: warn-by-default.html#unused-must-use
82     pub UNUSED_RESULTS,
83     Allow,
84     "unused result of an expression in a statement"
85 }
86
87 declare_lint_pass!(UnusedResults => [UNUSED_MUST_USE, UNUSED_RESULTS]);
88
89 impl<'tcx> LateLintPass<'tcx> for UnusedResults {
90     fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
91         let hir::StmtKind::Semi(expr) = s.kind else { return; };
92
93         if let hir::ExprKind::Ret(..) = expr.kind {
94             return;
95         }
96
97         if let hir::ExprKind::Match(await_expr, _arms, hir::MatchSource::AwaitDesugar) = expr.kind
98             && let ty = cx.typeck_results().expr_ty(&await_expr)
99             && let ty::Opaque(future_def_id, _) = ty.kind()
100             && cx.tcx.ty_is_opaque_future(ty)
101             // FIXME: This also includes non-async fns that return `impl Future`.
102             && let async_fn_def_id = cx.tcx.parent(*future_def_id)
103             && check_must_use_def(
104                 cx,
105                 async_fn_def_id,
106                 expr.span,
107                 "output of future returned by ",
108                 "",
109             )
110         {
111             // We have a bare `foo().await;` on an opaque type from an async function that was
112             // annotated with `#[must_use]`.
113             return;
114         }
115
116         let ty = cx.typeck_results().expr_ty(&expr);
117
118         let must_use_result = is_ty_must_use(cx, ty, &expr, expr.span);
119         let type_lint_emitted_or_suppressed = match must_use_result {
120             Some(path) => {
121                 emit_must_use_untranslated(cx, &path, "", "", 1);
122                 true
123             }
124             None => false,
125         };
126
127         let fn_warned = check_fn_must_use(cx, expr);
128
129         if !fn_warned && type_lint_emitted_or_suppressed {
130             // We don't warn about unused unit or uninhabited types.
131             // (See https://github.com/rust-lang/rust/issues/43806 for details.)
132             return;
133         }
134
135         let must_use_op = match expr.kind {
136             // Hardcoding operators here seemed more expedient than the
137             // refactoring that would be needed to look up the `#[must_use]`
138             // attribute which does exist on the comparison trait methods
139             hir::ExprKind::Binary(bin_op, ..) => match bin_op.node {
140                 hir::BinOpKind::Eq
141                 | hir::BinOpKind::Lt
142                 | hir::BinOpKind::Le
143                 | hir::BinOpKind::Ne
144                 | hir::BinOpKind::Ge
145                 | hir::BinOpKind::Gt => Some("comparison"),
146                 hir::BinOpKind::Add
147                 | hir::BinOpKind::Sub
148                 | hir::BinOpKind::Div
149                 | hir::BinOpKind::Mul
150                 | hir::BinOpKind::Rem => Some("arithmetic operation"),
151                 hir::BinOpKind::And | hir::BinOpKind::Or => Some("logical operation"),
152                 hir::BinOpKind::BitXor
153                 | hir::BinOpKind::BitAnd
154                 | hir::BinOpKind::BitOr
155                 | hir::BinOpKind::Shl
156                 | hir::BinOpKind::Shr => Some("bitwise operation"),
157             },
158             hir::ExprKind::AddrOf(..) => Some("borrow"),
159             hir::ExprKind::Unary(..) => Some("unary operation"),
160             _ => None,
161         };
162
163         let mut op_warned = false;
164
165         if let Some(must_use_op) = must_use_op {
166             cx.struct_span_lint(UNUSED_MUST_USE, expr.span, fluent::lint_unused_op, |lint| {
167                 lint.set_arg("op", must_use_op)
168                     .span_label(expr.span, fluent::label)
169                     .span_suggestion_verbose(
170                         expr.span.shrink_to_lo(),
171                         fluent::suggestion,
172                         "let _ = ",
173                         Applicability::MachineApplicable,
174                     )
175             });
176             op_warned = true;
177         }
178
179         if !(type_lint_emitted_or_suppressed || fn_warned || op_warned) {
180             cx.struct_span_lint(UNUSED_RESULTS, s.span, fluent::lint_unused_result, |lint| {
181                 lint.set_arg("ty", ty)
182             });
183         }
184
185         fn check_fn_must_use(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool {
186             let maybe_def_id = match expr.kind {
187                 hir::ExprKind::Call(ref callee, _) => {
188                     match callee.kind {
189                         hir::ExprKind::Path(ref qpath) => {
190                             match cx.qpath_res(qpath, callee.hir_id) {
191                                 Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) => Some(def_id),
192                                 // `Res::Local` if it was a closure, for which we
193                                 // do not currently support must-use linting
194                                 _ => None,
195                             }
196                         }
197                         _ => None,
198                     }
199                 }
200                 hir::ExprKind::MethodCall(..) => {
201                     cx.typeck_results().type_dependent_def_id(expr.hir_id)
202                 }
203                 _ => None,
204             };
205             if let Some(def_id) = maybe_def_id {
206                 check_must_use_def(cx, def_id, expr.span, "return value of ", "")
207             } else {
208                 false
209             }
210         }
211
212         /// A path through a type to a must_use source. Contains useful info for the lint.
213         #[derive(Debug)]
214         enum MustUsePath {
215             /// Suppress must_use checking.
216             Suppressed,
217             /// The root of the normal must_use lint with an optional message.
218             Def(Span, DefId, Option<Symbol>),
219             Boxed(Box<Self>),
220             Opaque(Box<Self>),
221             TraitObject(Box<Self>),
222             TupleElement(Vec<(usize, Self)>),
223             Array(Box<Self>, u64),
224             /// The root of the unused_closures lint.
225             Closure(Span),
226             /// The root of the unused_generators lint.
227             Generator(Span),
228         }
229
230         #[instrument(skip(cx, expr), level = "debug", ret)]
231         fn is_ty_must_use<'tcx>(
232             cx: &LateContext<'tcx>,
233             ty: Ty<'tcx>,
234             expr: &hir::Expr<'_>,
235             span: Span,
236         ) -> Option<MustUsePath> {
237             if ty.is_unit()
238                 || !ty.is_inhabited_from(
239                     cx.tcx,
240                     cx.tcx.parent_module(expr.hir_id).to_def_id(),
241                     cx.param_env,
242                 )
243             {
244                 return Some(MustUsePath::Suppressed);
245             }
246
247             match *ty.kind() {
248                 ty::Adt(..) if ty.is_box() => {
249                     let boxed_ty = ty.boxed_ty();
250                     is_ty_must_use(cx, boxed_ty, expr, span)
251                         .map(|inner| MustUsePath::Boxed(Box::new(inner)))
252                 }
253                 ty::Adt(def, _) => is_def_must_use(cx, def.did(), span),
254                 ty::Opaque(def, _) => {
255                     elaborate_predicates_with_span(
256                         cx.tcx,
257                         cx.tcx.explicit_item_bounds(def).iter().cloned(),
258                     )
259                     .filter_map(|obligation| {
260                         // We only look at the `DefId`, so it is safe to skip the binder here.
261                         if let ty::PredicateKind::Clause(ty::Clause::Trait(
262                             ref poly_trait_predicate,
263                         )) = obligation.predicate.kind().skip_binder()
264                         {
265                             let def_id = poly_trait_predicate.trait_ref.def_id;
266
267                             is_def_must_use(cx, def_id, span)
268                         } else {
269                             None
270                         }
271                     })
272                     .map(|inner| MustUsePath::Opaque(Box::new(inner)))
273                     .next()
274                 }
275                 ty::Dynamic(binders, _, _) => binders
276                     .iter()
277                     .filter_map(|predicate| {
278                         if let ty::ExistentialPredicate::Trait(ref trait_ref) =
279                             predicate.skip_binder()
280                         {
281                             let def_id = trait_ref.def_id;
282                             is_def_must_use(cx, def_id, span)
283                         } else {
284                             None
285                         }
286                         .map(|inner| MustUsePath::TraitObject(Box::new(inner)))
287                     })
288                     .next(),
289                 ty::Tuple(tys) => {
290                     let elem_exprs = if let hir::ExprKind::Tup(elem_exprs) = expr.kind {
291                         debug_assert_eq!(elem_exprs.len(), tys.len());
292                         elem_exprs
293                     } else {
294                         &[]
295                     };
296
297                     // Default to `expr`.
298                     let elem_exprs = elem_exprs.iter().chain(iter::repeat(expr));
299
300                     let nested_must_use = tys
301                         .iter()
302                         .zip(elem_exprs)
303                         .enumerate()
304                         .filter_map(|(i, (ty, expr))| {
305                             is_ty_must_use(cx, ty, expr, expr.span).map(|path| (i, path))
306                         })
307                         .collect::<Vec<_>>();
308
309                     if !nested_must_use.is_empty() {
310                         Some(MustUsePath::TupleElement(nested_must_use))
311                     } else {
312                         None
313                     }
314                 }
315                 ty::Array(ty, len) => match len.try_eval_usize(cx.tcx, cx.param_env) {
316                     // If the array is empty we don't lint, to avoid false positives
317                     Some(0) | None => None,
318                     // If the array is definitely non-empty, we can do `#[must_use]` checking.
319                     Some(len) => is_ty_must_use(cx, ty, expr, span)
320                         .map(|inner| MustUsePath::Array(Box::new(inner), len)),
321                 },
322                 ty::Closure(..) => Some(MustUsePath::Closure(span)),
323                 ty::Generator(def_id, ..) => {
324                     // async fn should be treated as "implementor of `Future`"
325                     let must_use = if cx.tcx.generator_is_async(def_id) {
326                         let def_id = cx.tcx.lang_items().future_trait().unwrap();
327                         is_def_must_use(cx, def_id, span)
328                             .map(|inner| MustUsePath::Opaque(Box::new(inner)))
329                     } else {
330                         None
331                     };
332                     must_use.or(Some(MustUsePath::Generator(span)))
333                 }
334                 _ => None,
335             }
336         }
337
338         fn is_def_must_use(cx: &LateContext<'_>, def_id: DefId, span: Span) -> Option<MustUsePath> {
339             if let Some(attr) = cx.tcx.get_attr(def_id, sym::must_use) {
340                 // check for #[must_use = "..."]
341                 let reason = attr.value_str();
342                 Some(MustUsePath::Def(span, def_id, reason))
343             } else {
344                 None
345             }
346         }
347
348         // Returns whether further errors should be suppressed because either a lint has been emitted or the type should be ignored.
349         fn check_must_use_def(
350             cx: &LateContext<'_>,
351             def_id: DefId,
352             span: Span,
353             descr_pre_path: &str,
354             descr_post_path: &str,
355         ) -> bool {
356             is_def_must_use(cx, def_id, span)
357                 .map(|must_use_path| {
358                     emit_must_use_untranslated(
359                         cx,
360                         &must_use_path,
361                         descr_pre_path,
362                         descr_post_path,
363                         1,
364                     )
365                 })
366                 .is_some()
367         }
368
369         #[instrument(skip(cx), level = "debug")]
370         fn emit_must_use_untranslated(
371             cx: &LateContext<'_>,
372             path: &MustUsePath,
373             descr_pre: &str,
374             descr_post: &str,
375             plural_len: usize,
376         ) {
377             let plural_suffix = pluralize!(plural_len);
378
379             match path {
380                 MustUsePath::Suppressed => {}
381                 MustUsePath::Boxed(path) => {
382                     let descr_pre = &format!("{}boxed ", descr_pre);
383                     emit_must_use_untranslated(cx, path, descr_pre, descr_post, plural_len);
384                 }
385                 MustUsePath::Opaque(path) => {
386                     let descr_pre = &format!("{}implementer{} of ", descr_pre, plural_suffix);
387                     emit_must_use_untranslated(cx, path, descr_pre, descr_post, plural_len);
388                 }
389                 MustUsePath::TraitObject(path) => {
390                     let descr_post = &format!(" trait object{}{}", plural_suffix, descr_post);
391                     emit_must_use_untranslated(cx, path, descr_pre, descr_post, plural_len);
392                 }
393                 MustUsePath::TupleElement(elems) => {
394                     for (index, path) in elems {
395                         let descr_post = &format!(" in tuple element {}", index);
396                         emit_must_use_untranslated(cx, path, descr_pre, descr_post, plural_len);
397                     }
398                 }
399                 MustUsePath::Array(path, len) => {
400                     let descr_pre = &format!("{}array{} of ", descr_pre, plural_suffix);
401                     emit_must_use_untranslated(
402                         cx,
403                         path,
404                         descr_pre,
405                         descr_post,
406                         plural_len.saturating_add(usize::try_from(*len).unwrap_or(usize::MAX)),
407                     );
408                 }
409                 MustUsePath::Closure(span) => {
410                     cx.struct_span_lint(
411                         UNUSED_MUST_USE,
412                         *span,
413                         fluent::lint_unused_closure,
414                         |lint| {
415                             // FIXME(davidtwco): this isn't properly translatable because of the
416                             // pre/post strings
417                             lint.set_arg("count", plural_len)
418                                 .set_arg("pre", descr_pre)
419                                 .set_arg("post", descr_post)
420                                 .note(fluent::note)
421                         },
422                     );
423                 }
424                 MustUsePath::Generator(span) => {
425                     cx.struct_span_lint(
426                         UNUSED_MUST_USE,
427                         *span,
428                         fluent::lint_unused_generator,
429                         |lint| {
430                             // FIXME(davidtwco): this isn't properly translatable because of the
431                             // pre/post strings
432                             lint.set_arg("count", plural_len)
433                                 .set_arg("pre", descr_pre)
434                                 .set_arg("post", descr_post)
435                                 .note(fluent::note)
436                         },
437                     );
438                 }
439                 MustUsePath::Def(span, def_id, reason) => {
440                     cx.struct_span_lint(UNUSED_MUST_USE, *span, fluent::lint_unused_def, |lint| {
441                         // FIXME(davidtwco): this isn't properly translatable because of the pre/post
442                         // strings
443                         lint.set_arg("pre", descr_pre);
444                         lint.set_arg("post", descr_post);
445                         lint.set_arg("def", cx.tcx.def_path_str(*def_id));
446                         if let Some(note) = reason {
447                             lint.note(note.as_str());
448                         }
449                         lint
450                     });
451                 }
452             }
453         }
454     }
455 }
456
457 declare_lint! {
458     /// The `path_statements` lint detects path statements with no effect.
459     ///
460     /// ### Example
461     ///
462     /// ```rust
463     /// let x = 42;
464     ///
465     /// x;
466     /// ```
467     ///
468     /// {{produces}}
469     ///
470     /// ### Explanation
471     ///
472     /// It is usually a mistake to have a statement that has no effect.
473     pub PATH_STATEMENTS,
474     Warn,
475     "path statements with no effect"
476 }
477
478 declare_lint_pass!(PathStatements => [PATH_STATEMENTS]);
479
480 impl<'tcx> LateLintPass<'tcx> for PathStatements {
481     fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
482         if let hir::StmtKind::Semi(expr) = s.kind {
483             if let hir::ExprKind::Path(_) = expr.kind {
484                 let ty = cx.typeck_results().expr_ty(expr);
485                 if ty.needs_drop(cx.tcx, cx.param_env) {
486                     cx.struct_span_lint(
487                         PATH_STATEMENTS,
488                         s.span,
489                         fluent::lint_path_statement_drop,
490                         |lint| {
491                             if let Ok(snippet) = cx.sess().source_map().span_to_snippet(expr.span) {
492                                 lint.span_suggestion(
493                                     s.span,
494                                     fluent::suggestion,
495                                     format!("drop({});", snippet),
496                                     Applicability::MachineApplicable,
497                                 );
498                             } else {
499                                 lint.span_help(s.span, fluent::suggestion);
500                             }
501                             lint
502                         },
503                     );
504                 } else {
505                     cx.struct_span_lint(
506                         PATH_STATEMENTS,
507                         s.span,
508                         fluent::lint_path_statement_no_effect,
509                         |lint| lint,
510                     );
511                 }
512             }
513         }
514     }
515 }
516
517 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
518 enum UnusedDelimsCtx {
519     FunctionArg,
520     MethodArg,
521     AssignedValue,
522     AssignedValueLetElse,
523     IfCond,
524     WhileCond,
525     ForIterExpr,
526     MatchScrutineeExpr,
527     ReturnValue,
528     BlockRetValue,
529     LetScrutineeExpr,
530     ArrayLenExpr,
531     AnonConst,
532     MatchArmExpr,
533 }
534
535 impl From<UnusedDelimsCtx> for &'static str {
536     fn from(ctx: UnusedDelimsCtx) -> &'static str {
537         match ctx {
538             UnusedDelimsCtx::FunctionArg => "function argument",
539             UnusedDelimsCtx::MethodArg => "method argument",
540             UnusedDelimsCtx::AssignedValue | UnusedDelimsCtx::AssignedValueLetElse => {
541                 "assigned value"
542             }
543             UnusedDelimsCtx::IfCond => "`if` condition",
544             UnusedDelimsCtx::WhileCond => "`while` condition",
545             UnusedDelimsCtx::ForIterExpr => "`for` iterator expression",
546             UnusedDelimsCtx::MatchScrutineeExpr => "`match` scrutinee expression",
547             UnusedDelimsCtx::ReturnValue => "`return` value",
548             UnusedDelimsCtx::BlockRetValue => "block return value",
549             UnusedDelimsCtx::LetScrutineeExpr => "`let` scrutinee expression",
550             UnusedDelimsCtx::ArrayLenExpr | UnusedDelimsCtx::AnonConst => "const expression",
551             UnusedDelimsCtx::MatchArmExpr => "match arm expression",
552         }
553     }
554 }
555
556 /// Used by both `UnusedParens` and `UnusedBraces` to prevent code duplication.
557 trait UnusedDelimLint {
558     const DELIM_STR: &'static str;
559
560     /// Due to `ref` pattern, there can be a difference between using
561     /// `{ expr }` and `expr` in pattern-matching contexts. This means
562     /// that we should only lint `unused_parens` and not `unused_braces`
563     /// in this case.
564     ///
565     /// ```rust
566     /// let mut a = 7;
567     /// let ref b = { a }; // We actually borrow a copy of `a` here.
568     /// a += 1; // By mutating `a` we invalidate any borrows of `a`.
569     /// assert_eq!(b + 1, a); // `b` does not borrow `a`, so we can still use it here.
570     /// ```
571     const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool;
572
573     // this cannot be a constant is it refers to a static.
574     fn lint(&self) -> &'static Lint;
575
576     fn check_unused_delims_expr(
577         &self,
578         cx: &EarlyContext<'_>,
579         value: &ast::Expr,
580         ctx: UnusedDelimsCtx,
581         followed_by_block: bool,
582         left_pos: Option<BytePos>,
583         right_pos: Option<BytePos>,
584     );
585
586     fn is_expr_delims_necessary(
587         inner: &ast::Expr,
588         followed_by_block: bool,
589         followed_by_else: bool,
590     ) -> bool {
591         if followed_by_else {
592             match inner.kind {
593                 ast::ExprKind::Binary(op, ..) if op.node.lazy() => return true,
594                 _ if classify::expr_trailing_brace(inner).is_some() => return true,
595                 _ => {}
596             }
597         }
598
599         // Prevent false-positives in cases like `fn x() -> u8 { ({ 0 } + 1) }`
600         let lhs_needs_parens = {
601             let mut innermost = inner;
602             loop {
603                 innermost = match &innermost.kind {
604                     ExprKind::Binary(_, lhs, _rhs) => lhs,
605                     ExprKind::Call(fn_, _params) => fn_,
606                     ExprKind::Cast(expr, _ty) => expr,
607                     ExprKind::Type(expr, _ty) => expr,
608                     ExprKind::Index(base, _subscript) => base,
609                     _ => break false,
610                 };
611                 if !classify::expr_requires_semi_to_be_stmt(innermost) {
612                     break true;
613                 }
614             }
615         };
616
617         lhs_needs_parens
618             || (followed_by_block
619                 && match &inner.kind {
620                     ExprKind::Ret(_) | ExprKind::Break(..) | ExprKind::Yield(..) => true,
621                     ExprKind::Range(_lhs, Some(rhs), _limits) => {
622                         matches!(rhs.kind, ExprKind::Block(..))
623                     }
624                     _ => parser::contains_exterior_struct_lit(&inner),
625                 })
626     }
627
628     fn emit_unused_delims_expr(
629         &self,
630         cx: &EarlyContext<'_>,
631         value: &ast::Expr,
632         ctx: UnusedDelimsCtx,
633         left_pos: Option<BytePos>,
634         right_pos: Option<BytePos>,
635     ) {
636         // If `value` has `ExprKind::Err`, unused delim lint can be broken.
637         // For example, the following code caused ICE.
638         // This is because the `ExprKind::Call` in `value` has `ExprKind::Err` as its argument
639         // and this leads to wrong spans. #104897
640         //
641         // ```
642         // fn f(){(print!(á
643         // ```
644         use rustc_ast::visit::{walk_expr, Visitor};
645         struct ErrExprVisitor {
646             has_error: bool,
647         }
648         impl<'ast> Visitor<'ast> for ErrExprVisitor {
649             fn visit_expr(&mut self, expr: &'ast ast::Expr) {
650                 if let ExprKind::Err = expr.kind {
651                     self.has_error = true;
652                     return;
653                 }
654                 walk_expr(self, expr)
655             }
656         }
657         let mut visitor = ErrExprVisitor { has_error: false };
658         visitor.visit_expr(value);
659         if visitor.has_error {
660             return;
661         }
662         let spans = match value.kind {
663             ast::ExprKind::Block(ref block, None) if block.stmts.len() == 1 => {
664                 if let Some(span) = block.stmts[0].span.find_ancestor_inside(value.span) {
665                     Some((value.span.with_hi(span.lo()), value.span.with_lo(span.hi())))
666                 } else {
667                     None
668                 }
669             }
670             ast::ExprKind::Paren(ref expr) => {
671                 let expr_span = expr.span.find_ancestor_inside(value.span);
672                 if let Some(expr_span) = expr_span {
673                     Some((value.span.with_hi(expr_span.lo()), value.span.with_lo(expr_span.hi())))
674                 } else {
675                     None
676                 }
677             }
678             _ => return,
679         };
680         let keep_space = (
681             left_pos.map_or(false, |s| s >= value.span.lo()),
682             right_pos.map_or(false, |s| s <= value.span.hi()),
683         );
684         self.emit_unused_delims(cx, value.span, spans, ctx.into(), keep_space);
685     }
686
687     fn emit_unused_delims(
688         &self,
689         cx: &EarlyContext<'_>,
690         value_span: Span,
691         spans: Option<(Span, Span)>,
692         msg: &str,
693         keep_space: (bool, bool),
694     ) {
695         let primary_span = if let Some((lo, hi)) = spans {
696             MultiSpan::from(vec![lo, hi])
697         } else {
698             MultiSpan::from(value_span)
699         };
700         cx.struct_span_lint(self.lint(), primary_span, fluent::lint_unused_delim, |lint| {
701             lint.set_arg("delim", Self::DELIM_STR);
702             lint.set_arg("item", msg);
703             if let Some((lo, hi)) = spans {
704                 let sm = cx.sess().source_map();
705                 let lo_replace =
706                     if keep_space.0 &&
707                         let Ok(snip) = sm.span_to_prev_source(lo) && !snip.ends_with(' ') {
708                         " ".to_string()
709                         } else {
710                             "".to_string()
711                         };
712
713                 let hi_replace =
714                     if keep_space.1 &&
715                         let Ok(snip) = sm.span_to_next_source(hi) && !snip.starts_with(' ') {
716                         " ".to_string()
717                         } else {
718                             "".to_string()
719                         };
720
721                 let replacement = vec![(lo, lo_replace), (hi, hi_replace)];
722                 lint.multipart_suggestion(
723                     fluent::suggestion,
724                     replacement,
725                     Applicability::MachineApplicable,
726                 );
727             }
728             lint
729         });
730     }
731
732     fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
733         use rustc_ast::ExprKind::*;
734         let (value, ctx, followed_by_block, left_pos, right_pos) = match e.kind {
735             // Do not lint `unused_braces` in `if let` expressions.
736             If(ref cond, ref block, _)
737                 if !matches!(cond.kind, Let(_, _, _))
738                     || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
739             {
740                 let left = e.span.lo() + rustc_span::BytePos(2);
741                 let right = block.span.lo();
742                 (cond, UnusedDelimsCtx::IfCond, true, Some(left), Some(right))
743             }
744
745             // Do not lint `unused_braces` in `while let` expressions.
746             While(ref cond, ref block, ..)
747                 if !matches!(cond.kind, Let(_, _, _))
748                     || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
749             {
750                 let left = e.span.lo() + rustc_span::BytePos(5);
751                 let right = block.span.lo();
752                 (cond, UnusedDelimsCtx::WhileCond, true, Some(left), Some(right))
753             }
754
755             ForLoop(_, ref cond, ref block, ..) => {
756                 (cond, UnusedDelimsCtx::ForIterExpr, true, None, Some(block.span.lo()))
757             }
758
759             Match(ref head, _) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
760                 let left = e.span.lo() + rustc_span::BytePos(5);
761                 (head, UnusedDelimsCtx::MatchScrutineeExpr, true, Some(left), None)
762             }
763
764             Ret(Some(ref value)) => {
765                 let left = e.span.lo() + rustc_span::BytePos(3);
766                 (value, UnusedDelimsCtx::ReturnValue, false, Some(left), None)
767             }
768
769             Assign(_, ref value, _) | AssignOp(.., ref value) => {
770                 (value, UnusedDelimsCtx::AssignedValue, false, None, None)
771             }
772             // either function/method call, or something this lint doesn't care about
773             ref call_or_other => {
774                 let (args_to_check, ctx) = match *call_or_other {
775                     Call(_, ref args) => (&args[..], UnusedDelimsCtx::FunctionArg),
776                     MethodCall(ref call) => (&call.args[..], UnusedDelimsCtx::MethodArg),
777                     // actual catch-all arm
778                     _ => {
779                         return;
780                     }
781                 };
782                 // Don't lint if this is a nested macro expansion: otherwise, the lint could
783                 // trigger in situations that macro authors shouldn't have to care about, e.g.,
784                 // when a parenthesized token tree matched in one macro expansion is matched as
785                 // an expression in another and used as a fn/method argument (Issue #47775)
786                 if e.span.ctxt().outer_expn_data().call_site.from_expansion() {
787                     return;
788                 }
789                 for arg in args_to_check {
790                     self.check_unused_delims_expr(cx, arg, ctx, false, None, None);
791                 }
792                 return;
793             }
794         };
795         self.check_unused_delims_expr(cx, &value, ctx, followed_by_block, left_pos, right_pos);
796     }
797
798     fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
799         match s.kind {
800             StmtKind::Local(ref local) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
801                 if let Some((init, els)) = local.kind.init_else_opt() {
802                     let ctx = match els {
803                         None => UnusedDelimsCtx::AssignedValue,
804                         Some(_) => UnusedDelimsCtx::AssignedValueLetElse,
805                     };
806                     self.check_unused_delims_expr(cx, init, ctx, false, None, None);
807                 }
808             }
809             StmtKind::Expr(ref expr) => {
810                 self.check_unused_delims_expr(
811                     cx,
812                     &expr,
813                     UnusedDelimsCtx::BlockRetValue,
814                     false,
815                     None,
816                     None,
817                 );
818             }
819             _ => {}
820         }
821     }
822
823     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
824         use ast::ItemKind::*;
825
826         if let Const(.., Some(expr)) | Static(.., Some(expr)) = &item.kind {
827             self.check_unused_delims_expr(
828                 cx,
829                 expr,
830                 UnusedDelimsCtx::AssignedValue,
831                 false,
832                 None,
833                 None,
834             );
835         }
836     }
837 }
838
839 declare_lint! {
840     /// The `unused_parens` lint detects `if`, `match`, `while` and `return`
841     /// with parentheses; they do not need them.
842     ///
843     /// ### Examples
844     ///
845     /// ```rust
846     /// if(true) {}
847     /// ```
848     ///
849     /// {{produces}}
850     ///
851     /// ### Explanation
852     ///
853     /// The parentheses are not needed, and should be removed. This is the
854     /// preferred style for writing these expressions.
855     pub(super) UNUSED_PARENS,
856     Warn,
857     "`if`, `match`, `while` and `return` do not need parentheses"
858 }
859
860 declare_lint_pass!(UnusedParens => [UNUSED_PARENS]);
861
862 impl UnusedDelimLint for UnusedParens {
863     const DELIM_STR: &'static str = "parentheses";
864
865     const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = true;
866
867     fn lint(&self) -> &'static Lint {
868         UNUSED_PARENS
869     }
870
871     fn check_unused_delims_expr(
872         &self,
873         cx: &EarlyContext<'_>,
874         value: &ast::Expr,
875         ctx: UnusedDelimsCtx,
876         followed_by_block: bool,
877         left_pos: Option<BytePos>,
878         right_pos: Option<BytePos>,
879     ) {
880         match value.kind {
881             ast::ExprKind::Paren(ref inner) => {
882                 let followed_by_else = ctx == UnusedDelimsCtx::AssignedValueLetElse;
883                 if !Self::is_expr_delims_necessary(inner, followed_by_block, followed_by_else)
884                     && value.attrs.is_empty()
885                     && !value.span.from_expansion()
886                     && (ctx != UnusedDelimsCtx::LetScrutineeExpr
887                         || !matches!(inner.kind, ast::ExprKind::Binary(
888                                 rustc_span::source_map::Spanned { node, .. },
889                                 _,
890                                 _,
891                             ) if node.lazy()))
892                 {
893                     self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
894                 }
895             }
896             ast::ExprKind::Let(_, ref expr, _) => {
897                 self.check_unused_delims_expr(
898                     cx,
899                     expr,
900                     UnusedDelimsCtx::LetScrutineeExpr,
901                     followed_by_block,
902                     None,
903                     None,
904                 );
905             }
906             _ => {}
907         }
908     }
909 }
910
911 impl UnusedParens {
912     fn check_unused_parens_pat(
913         &self,
914         cx: &EarlyContext<'_>,
915         value: &ast::Pat,
916         avoid_or: bool,
917         avoid_mut: bool,
918         keep_space: (bool, bool),
919     ) {
920         use ast::{BindingAnnotation, PatKind};
921
922         if let PatKind::Paren(inner) = &value.kind {
923             match inner.kind {
924                 // The lint visitor will visit each subpattern of `p`. We do not want to lint
925                 // any range pattern no matter where it occurs in the pattern. For something like
926                 // `&(a..=b)`, there is a recursive `check_pat` on `a` and `b`, but we will assume
927                 // that if there are unnecessary parens they serve a purpose of readability.
928                 PatKind::Range(..) => return,
929                 // Avoid `p0 | .. | pn` if we should.
930                 PatKind::Or(..) if avoid_or => return,
931                 // Avoid `mut x` and `mut x @ p` if we should:
932                 PatKind::Ident(BindingAnnotation::MUT, ..) if avoid_mut => {
933                     return;
934                 }
935                 // Otherwise proceed with linting.
936                 _ => {}
937             }
938             let spans = if let Some(inner) = inner.span.find_ancestor_inside(value.span) {
939                 Some((value.span.with_hi(inner.lo()), value.span.with_lo(inner.hi())))
940             } else {
941                 None
942             };
943             self.emit_unused_delims(cx, value.span, spans, "pattern", keep_space);
944         }
945     }
946 }
947
948 impl EarlyLintPass for UnusedParens {
949     fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
950         match e.kind {
951             ExprKind::Let(ref pat, _, _) | ExprKind::ForLoop(ref pat, ..) => {
952                 self.check_unused_parens_pat(cx, pat, false, false, (true, true));
953             }
954             // We ignore parens in cases like `if (((let Some(0) = Some(1))))` because we already
955             // handle a hard error for them during AST lowering in `lower_expr_mut`, but we still
956             // want to complain about things like `if let 42 = (42)`.
957             ExprKind::If(ref cond, ref block, ref else_)
958                 if matches!(cond.peel_parens().kind, ExprKind::Let(..)) =>
959             {
960                 self.check_unused_delims_expr(
961                     cx,
962                     cond.peel_parens(),
963                     UnusedDelimsCtx::LetScrutineeExpr,
964                     true,
965                     None,
966                     None,
967                 );
968                 for stmt in &block.stmts {
969                     <Self as UnusedDelimLint>::check_stmt(self, cx, stmt);
970                 }
971                 if let Some(e) = else_ {
972                     <Self as UnusedDelimLint>::check_expr(self, cx, e);
973                 }
974                 return;
975             }
976             ExprKind::Match(ref _expr, ref arm) => {
977                 for a in arm {
978                     self.check_unused_delims_expr(
979                         cx,
980                         &a.body,
981                         UnusedDelimsCtx::MatchArmExpr,
982                         false,
983                         None,
984                         None,
985                     );
986                 }
987             }
988             _ => {}
989         }
990
991         <Self as UnusedDelimLint>::check_expr(self, cx, e)
992     }
993
994     fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
995         use ast::{Mutability, PatKind::*};
996         let keep_space = (false, false);
997         match &p.kind {
998             // Do not lint on `(..)` as that will result in the other arms being useless.
999             Paren(_)
1000             // The other cases do not contain sub-patterns.
1001             | Wild | Rest | Lit(..) | MacCall(..) | Range(..) | Ident(.., None) | Path(..) => {},
1002             // These are list-like patterns; parens can always be removed.
1003             TupleStruct(_, _, ps) | Tuple(ps) | Slice(ps) | Or(ps) => for p in ps {
1004                 self.check_unused_parens_pat(cx, p, false, false, keep_space);
1005             },
1006             Struct(_, _, fps, _) => for f in fps {
1007                 self.check_unused_parens_pat(cx, &f.pat, false, false, keep_space);
1008             },
1009             // Avoid linting on `i @ (p0 | .. | pn)` and `box (p0 | .. | pn)`, #64106.
1010             Ident(.., Some(p)) | Box(p) => self.check_unused_parens_pat(cx, p, true, false, keep_space),
1011             // Avoid linting on `&(mut x)` as `&mut x` has a different meaning, #55342.
1012             // Also avoid linting on `& mut? (p0 | .. | pn)`, #64106.
1013             Ref(p, m) => self.check_unused_parens_pat(cx, p, true, *m == Mutability::Not, keep_space),
1014         }
1015     }
1016
1017     fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
1018         if let StmtKind::Local(ref local) = s.kind {
1019             self.check_unused_parens_pat(cx, &local.pat, true, false, (false, false));
1020         }
1021
1022         <Self as UnusedDelimLint>::check_stmt(self, cx, s)
1023     }
1024
1025     fn check_param(&mut self, cx: &EarlyContext<'_>, param: &ast::Param) {
1026         self.check_unused_parens_pat(cx, &param.pat, true, false, (false, false));
1027     }
1028
1029     fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
1030         self.check_unused_parens_pat(cx, &arm.pat, false, false, (false, false));
1031     }
1032
1033     fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
1034         if let ast::TyKind::Paren(r) = &ty.kind {
1035             match &r.kind {
1036                 ast::TyKind::TraitObject(..) => {}
1037                 ast::TyKind::BareFn(b) if b.generic_params.len() > 0 => {}
1038                 ast::TyKind::ImplTrait(_, bounds) if bounds.len() > 1 => {}
1039                 ast::TyKind::Array(_, len) => {
1040                     self.check_unused_delims_expr(
1041                         cx,
1042                         &len.value,
1043                         UnusedDelimsCtx::ArrayLenExpr,
1044                         false,
1045                         None,
1046                         None,
1047                     );
1048                 }
1049                 _ => {
1050                     let spans = if let Some(r) = r.span.find_ancestor_inside(ty.span) {
1051                         Some((ty.span.with_hi(r.lo()), ty.span.with_lo(r.hi())))
1052                     } else {
1053                         None
1054                     };
1055                     self.emit_unused_delims(cx, ty.span, spans, "type", (false, false));
1056                 }
1057             }
1058         }
1059     }
1060
1061     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1062         <Self as UnusedDelimLint>::check_item(self, cx, item)
1063     }
1064 }
1065
1066 declare_lint! {
1067     /// The `unused_braces` lint detects unnecessary braces around an
1068     /// expression.
1069     ///
1070     /// ### Example
1071     ///
1072     /// ```rust
1073     /// if { true } {
1074     ///     // ...
1075     /// }
1076     /// ```
1077     ///
1078     /// {{produces}}
1079     ///
1080     /// ### Explanation
1081     ///
1082     /// The braces are not needed, and should be removed. This is the
1083     /// preferred style for writing these expressions.
1084     pub(super) UNUSED_BRACES,
1085     Warn,
1086     "unnecessary braces around an expression"
1087 }
1088
1089 declare_lint_pass!(UnusedBraces => [UNUSED_BRACES]);
1090
1091 impl UnusedDelimLint for UnusedBraces {
1092     const DELIM_STR: &'static str = "braces";
1093
1094     const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = false;
1095
1096     fn lint(&self) -> &'static Lint {
1097         UNUSED_BRACES
1098     }
1099
1100     fn check_unused_delims_expr(
1101         &self,
1102         cx: &EarlyContext<'_>,
1103         value: &ast::Expr,
1104         ctx: UnusedDelimsCtx,
1105         followed_by_block: bool,
1106         left_pos: Option<BytePos>,
1107         right_pos: Option<BytePos>,
1108     ) {
1109         match value.kind {
1110             ast::ExprKind::Block(ref inner, None)
1111                 if inner.rules == ast::BlockCheckMode::Default =>
1112             {
1113                 // emit a warning under the following conditions:
1114                 //
1115                 // - the block does not have a label
1116                 // - the block is not `unsafe`
1117                 // - the block contains exactly one expression (do not lint `{ expr; }`)
1118                 // - `followed_by_block` is true and the internal expr may contain a `{`
1119                 // - the block is not multiline (do not lint multiline match arms)
1120                 //      ```
1121                 //      match expr {
1122                 //          Pattern => {
1123                 //              somewhat_long_expression
1124                 //          }
1125                 //          // ...
1126                 //      }
1127                 //      ```
1128                 // - the block has no attribute and was not created inside a macro
1129                 // - if the block is an `anon_const`, the inner expr must be a literal
1130                 //      (do not lint `struct A<const N: usize>; let _: A<{ 2 + 3 }>;`)
1131                 //
1132                 // FIXME(const_generics): handle paths when #67075 is fixed.
1133                 if let [stmt] = inner.stmts.as_slice() {
1134                     if let ast::StmtKind::Expr(ref expr) = stmt.kind {
1135                         if !Self::is_expr_delims_necessary(expr, followed_by_block, false)
1136                             && (ctx != UnusedDelimsCtx::AnonConst
1137                                 || matches!(expr.kind, ast::ExprKind::Lit(_)))
1138                             && !cx.sess().source_map().is_multiline(value.span)
1139                             && value.attrs.is_empty()
1140                             && !value.span.from_expansion()
1141                         {
1142                             self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
1143                         }
1144                     }
1145                 }
1146             }
1147             ast::ExprKind::Let(_, ref expr, _) => {
1148                 self.check_unused_delims_expr(
1149                     cx,
1150                     expr,
1151                     UnusedDelimsCtx::LetScrutineeExpr,
1152                     followed_by_block,
1153                     None,
1154                     None,
1155                 );
1156             }
1157             _ => {}
1158         }
1159     }
1160 }
1161
1162 impl EarlyLintPass for UnusedBraces {
1163     fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
1164         <Self as UnusedDelimLint>::check_stmt(self, cx, s)
1165     }
1166
1167     fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
1168         <Self as UnusedDelimLint>::check_expr(self, cx, e);
1169
1170         if let ExprKind::Repeat(_, ref anon_const) = e.kind {
1171             self.check_unused_delims_expr(
1172                 cx,
1173                 &anon_const.value,
1174                 UnusedDelimsCtx::AnonConst,
1175                 false,
1176                 None,
1177                 None,
1178             );
1179         }
1180     }
1181
1182     fn check_generic_arg(&mut self, cx: &EarlyContext<'_>, arg: &ast::GenericArg) {
1183         if let ast::GenericArg::Const(ct) = arg {
1184             self.check_unused_delims_expr(
1185                 cx,
1186                 &ct.value,
1187                 UnusedDelimsCtx::AnonConst,
1188                 false,
1189                 None,
1190                 None,
1191             );
1192         }
1193     }
1194
1195     fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant) {
1196         if let Some(anon_const) = &v.disr_expr {
1197             self.check_unused_delims_expr(
1198                 cx,
1199                 &anon_const.value,
1200                 UnusedDelimsCtx::AnonConst,
1201                 false,
1202                 None,
1203                 None,
1204             );
1205         }
1206     }
1207
1208     fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
1209         match ty.kind {
1210             ast::TyKind::Array(_, ref len) => {
1211                 self.check_unused_delims_expr(
1212                     cx,
1213                     &len.value,
1214                     UnusedDelimsCtx::ArrayLenExpr,
1215                     false,
1216                     None,
1217                     None,
1218                 );
1219             }
1220
1221             ast::TyKind::Typeof(ref anon_const) => {
1222                 self.check_unused_delims_expr(
1223                     cx,
1224                     &anon_const.value,
1225                     UnusedDelimsCtx::AnonConst,
1226                     false,
1227                     None,
1228                     None,
1229                 );
1230             }
1231
1232             _ => {}
1233         }
1234     }
1235
1236     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1237         <Self as UnusedDelimLint>::check_item(self, cx, item)
1238     }
1239 }
1240
1241 declare_lint! {
1242     /// The `unused_import_braces` lint catches unnecessary braces around an
1243     /// imported item.
1244     ///
1245     /// ### Example
1246     ///
1247     /// ```rust,compile_fail
1248     /// #![deny(unused_import_braces)]
1249     /// use test::{A};
1250     ///
1251     /// pub mod test {
1252     ///     pub struct A;
1253     /// }
1254     /// # fn main() {}
1255     /// ```
1256     ///
1257     /// {{produces}}
1258     ///
1259     /// ### Explanation
1260     ///
1261     /// If there is only a single item, then remove the braces (`use test::A;`
1262     /// for example).
1263     ///
1264     /// This lint is "allow" by default because it is only enforcing a
1265     /// stylistic choice.
1266     UNUSED_IMPORT_BRACES,
1267     Allow,
1268     "unnecessary braces around an imported item"
1269 }
1270
1271 declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]);
1272
1273 impl UnusedImportBraces {
1274     fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
1275         if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
1276             // Recursively check nested UseTrees
1277             for &(ref tree, _) in items {
1278                 self.check_use_tree(cx, tree, item);
1279             }
1280
1281             // Trigger the lint only if there is one nested item
1282             if items.len() != 1 {
1283                 return;
1284             }
1285
1286             // Trigger the lint if the nested item is a non-self single item
1287             let node_name = match items[0].0.kind {
1288                 ast::UseTreeKind::Simple(rename) => {
1289                     let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
1290                     if orig_ident.name == kw::SelfLower {
1291                         return;
1292                     }
1293                     rename.unwrap_or(orig_ident).name
1294                 }
1295                 ast::UseTreeKind::Glob => Symbol::intern("*"),
1296                 ast::UseTreeKind::Nested(_) => return,
1297             };
1298
1299             cx.struct_span_lint(
1300                 UNUSED_IMPORT_BRACES,
1301                 item.span,
1302                 fluent::lint_unused_import_braces,
1303                 |lint| lint.set_arg("node", node_name),
1304             );
1305         }
1306     }
1307 }
1308
1309 impl EarlyLintPass for UnusedImportBraces {
1310     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1311         if let ast::ItemKind::Use(ref use_tree) = item.kind {
1312             self.check_use_tree(cx, use_tree, item);
1313         }
1314     }
1315 }
1316
1317 declare_lint! {
1318     /// The `unused_allocation` lint detects unnecessary allocations that can
1319     /// be eliminated.
1320     ///
1321     /// ### Example
1322     ///
1323     /// ```rust
1324     /// #![feature(box_syntax)]
1325     /// fn main() {
1326     ///     let a = (box [1, 2, 3]).len();
1327     /// }
1328     /// ```
1329     ///
1330     /// {{produces}}
1331     ///
1332     /// ### Explanation
1333     ///
1334     /// When a `box` expression is immediately coerced to a reference, then
1335     /// the allocation is unnecessary, and a reference (using `&` or `&mut`)
1336     /// should be used instead to avoid the allocation.
1337     pub(super) UNUSED_ALLOCATION,
1338     Warn,
1339     "detects unnecessary allocations that can be eliminated"
1340 }
1341
1342 declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]);
1343
1344 impl<'tcx> LateLintPass<'tcx> for UnusedAllocation {
1345     fn check_expr(&mut self, cx: &LateContext<'_>, e: &hir::Expr<'_>) {
1346         match e.kind {
1347             hir::ExprKind::Box(_) => {}
1348             _ => return,
1349         }
1350
1351         for adj in cx.typeck_results().expr_adjustments(e) {
1352             if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
1353                 cx.struct_span_lint(
1354                     UNUSED_ALLOCATION,
1355                     e.span,
1356                     match m {
1357                         adjustment::AutoBorrowMutability::Not => fluent::lint_unused_allocation,
1358                         adjustment::AutoBorrowMutability::Mut { .. } => {
1359                             fluent::lint_unused_allocation_mut
1360                         }
1361                     },
1362                     |lint| lint,
1363                 );
1364             }
1365         }
1366     }
1367 }