]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/unused.rs
Rollup merge of #105517 - pcc:process-panic-after-fork, r=davidtwco
[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::Alias(ty::Opaque, ty::AliasTy { def_id: 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::Alias(ty::Opaque, ty::AliasTy { def_id: def, .. }) => {
255                     elaborate_predicates_with_span(
256                         cx.tcx,
257                         cx.tcx.explicit_item_bounds(def).iter().cloned(),
258                     )
259                     .find_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                 }
274                 ty::Dynamic(binders, _, _) => binders.iter().find_map(|predicate| {
275                     if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder()
276                     {
277                         let def_id = trait_ref.def_id;
278                         is_def_must_use(cx, def_id, span)
279                             .map(|inner| MustUsePath::TraitObject(Box::new(inner)))
280                     } else {
281                         None
282                     }
283                 }),
284                 ty::Tuple(tys) => {
285                     let elem_exprs = if let hir::ExprKind::Tup(elem_exprs) = expr.kind {
286                         debug_assert_eq!(elem_exprs.len(), tys.len());
287                         elem_exprs
288                     } else {
289                         &[]
290                     };
291
292                     // Default to `expr`.
293                     let elem_exprs = elem_exprs.iter().chain(iter::repeat(expr));
294
295                     let nested_must_use = tys
296                         .iter()
297                         .zip(elem_exprs)
298                         .enumerate()
299                         .filter_map(|(i, (ty, expr))| {
300                             is_ty_must_use(cx, ty, expr, expr.span).map(|path| (i, path))
301                         })
302                         .collect::<Vec<_>>();
303
304                     if !nested_must_use.is_empty() {
305                         Some(MustUsePath::TupleElement(nested_must_use))
306                     } else {
307                         None
308                     }
309                 }
310                 ty::Array(ty, len) => match len.try_eval_usize(cx.tcx, cx.param_env) {
311                     // If the array is empty we don't lint, to avoid false positives
312                     Some(0) | None => None,
313                     // If the array is definitely non-empty, we can do `#[must_use]` checking.
314                     Some(len) => is_ty_must_use(cx, ty, expr, span)
315                         .map(|inner| MustUsePath::Array(Box::new(inner), len)),
316                 },
317                 ty::Closure(..) => Some(MustUsePath::Closure(span)),
318                 ty::Generator(def_id, ..) => {
319                     // async fn should be treated as "implementor of `Future`"
320                     let must_use = if cx.tcx.generator_is_async(def_id) {
321                         let def_id = cx.tcx.lang_items().future_trait().unwrap();
322                         is_def_must_use(cx, def_id, span)
323                             .map(|inner| MustUsePath::Opaque(Box::new(inner)))
324                     } else {
325                         None
326                     };
327                     must_use.or(Some(MustUsePath::Generator(span)))
328                 }
329                 _ => None,
330             }
331         }
332
333         fn is_def_must_use(cx: &LateContext<'_>, def_id: DefId, span: Span) -> Option<MustUsePath> {
334             if let Some(attr) = cx.tcx.get_attr(def_id, sym::must_use) {
335                 // check for #[must_use = "..."]
336                 let reason = attr.value_str();
337                 Some(MustUsePath::Def(span, def_id, reason))
338             } else {
339                 None
340             }
341         }
342
343         // Returns whether further errors should be suppressed because either a lint has been emitted or the type should be ignored.
344         fn check_must_use_def(
345             cx: &LateContext<'_>,
346             def_id: DefId,
347             span: Span,
348             descr_pre_path: &str,
349             descr_post_path: &str,
350         ) -> bool {
351             is_def_must_use(cx, def_id, span)
352                 .map(|must_use_path| {
353                     emit_must_use_untranslated(
354                         cx,
355                         &must_use_path,
356                         descr_pre_path,
357                         descr_post_path,
358                         1,
359                     )
360                 })
361                 .is_some()
362         }
363
364         #[instrument(skip(cx), level = "debug")]
365         fn emit_must_use_untranslated(
366             cx: &LateContext<'_>,
367             path: &MustUsePath,
368             descr_pre: &str,
369             descr_post: &str,
370             plural_len: usize,
371         ) {
372             let plural_suffix = pluralize!(plural_len);
373
374             match path {
375                 MustUsePath::Suppressed => {}
376                 MustUsePath::Boxed(path) => {
377                     let descr_pre = &format!("{}boxed ", descr_pre);
378                     emit_must_use_untranslated(cx, path, descr_pre, descr_post, plural_len);
379                 }
380                 MustUsePath::Opaque(path) => {
381                     let descr_pre = &format!("{}implementer{} of ", descr_pre, plural_suffix);
382                     emit_must_use_untranslated(cx, path, descr_pre, descr_post, plural_len);
383                 }
384                 MustUsePath::TraitObject(path) => {
385                     let descr_post = &format!(" trait object{}{}", plural_suffix, descr_post);
386                     emit_must_use_untranslated(cx, path, descr_pre, descr_post, plural_len);
387                 }
388                 MustUsePath::TupleElement(elems) => {
389                     for (index, path) in elems {
390                         let descr_post = &format!(" in tuple element {}", index);
391                         emit_must_use_untranslated(cx, path, descr_pre, descr_post, plural_len);
392                     }
393                 }
394                 MustUsePath::Array(path, len) => {
395                     let descr_pre = &format!("{}array{} of ", descr_pre, plural_suffix);
396                     emit_must_use_untranslated(
397                         cx,
398                         path,
399                         descr_pre,
400                         descr_post,
401                         plural_len.saturating_add(usize::try_from(*len).unwrap_or(usize::MAX)),
402                     );
403                 }
404                 MustUsePath::Closure(span) => {
405                     cx.struct_span_lint(
406                         UNUSED_MUST_USE,
407                         *span,
408                         fluent::lint_unused_closure,
409                         |lint| {
410                             // FIXME(davidtwco): this isn't properly translatable because of the
411                             // pre/post strings
412                             lint.set_arg("count", plural_len)
413                                 .set_arg("pre", descr_pre)
414                                 .set_arg("post", descr_post)
415                                 .note(fluent::note)
416                         },
417                     );
418                 }
419                 MustUsePath::Generator(span) => {
420                     cx.struct_span_lint(
421                         UNUSED_MUST_USE,
422                         *span,
423                         fluent::lint_unused_generator,
424                         |lint| {
425                             // FIXME(davidtwco): this isn't properly translatable because of the
426                             // pre/post strings
427                             lint.set_arg("count", plural_len)
428                                 .set_arg("pre", descr_pre)
429                                 .set_arg("post", descr_post)
430                                 .note(fluent::note)
431                         },
432                     );
433                 }
434                 MustUsePath::Def(span, def_id, reason) => {
435                     cx.struct_span_lint(UNUSED_MUST_USE, *span, fluent::lint_unused_def, |lint| {
436                         // FIXME(davidtwco): this isn't properly translatable because of the pre/post
437                         // strings
438                         lint.set_arg("pre", descr_pre);
439                         lint.set_arg("post", descr_post);
440                         lint.set_arg("def", cx.tcx.def_path_str(*def_id));
441                         if let Some(note) = reason {
442                             lint.note(note.as_str());
443                         }
444                         lint
445                     });
446                 }
447             }
448         }
449     }
450 }
451
452 declare_lint! {
453     /// The `path_statements` lint detects path statements with no effect.
454     ///
455     /// ### Example
456     ///
457     /// ```rust
458     /// let x = 42;
459     ///
460     /// x;
461     /// ```
462     ///
463     /// {{produces}}
464     ///
465     /// ### Explanation
466     ///
467     /// It is usually a mistake to have a statement that has no effect.
468     pub PATH_STATEMENTS,
469     Warn,
470     "path statements with no effect"
471 }
472
473 declare_lint_pass!(PathStatements => [PATH_STATEMENTS]);
474
475 impl<'tcx> LateLintPass<'tcx> for PathStatements {
476     fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
477         if let hir::StmtKind::Semi(expr) = s.kind {
478             if let hir::ExprKind::Path(_) = expr.kind {
479                 let ty = cx.typeck_results().expr_ty(expr);
480                 if ty.needs_drop(cx.tcx, cx.param_env) {
481                     cx.struct_span_lint(
482                         PATH_STATEMENTS,
483                         s.span,
484                         fluent::lint_path_statement_drop,
485                         |lint| {
486                             if let Ok(snippet) = cx.sess().source_map().span_to_snippet(expr.span) {
487                                 lint.span_suggestion(
488                                     s.span,
489                                     fluent::suggestion,
490                                     format!("drop({});", snippet),
491                                     Applicability::MachineApplicable,
492                                 );
493                             } else {
494                                 lint.span_help(s.span, fluent::suggestion);
495                             }
496                             lint
497                         },
498                     );
499                 } else {
500                     cx.struct_span_lint(
501                         PATH_STATEMENTS,
502                         s.span,
503                         fluent::lint_path_statement_no_effect,
504                         |lint| lint,
505                     );
506                 }
507             }
508         }
509     }
510 }
511
512 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
513 enum UnusedDelimsCtx {
514     FunctionArg,
515     MethodArg,
516     AssignedValue,
517     AssignedValueLetElse,
518     IfCond,
519     WhileCond,
520     ForIterExpr,
521     MatchScrutineeExpr,
522     ReturnValue,
523     BlockRetValue,
524     LetScrutineeExpr,
525     ArrayLenExpr,
526     AnonConst,
527     MatchArmExpr,
528 }
529
530 impl From<UnusedDelimsCtx> for &'static str {
531     fn from(ctx: UnusedDelimsCtx) -> &'static str {
532         match ctx {
533             UnusedDelimsCtx::FunctionArg => "function argument",
534             UnusedDelimsCtx::MethodArg => "method argument",
535             UnusedDelimsCtx::AssignedValue | UnusedDelimsCtx::AssignedValueLetElse => {
536                 "assigned value"
537             }
538             UnusedDelimsCtx::IfCond => "`if` condition",
539             UnusedDelimsCtx::WhileCond => "`while` condition",
540             UnusedDelimsCtx::ForIterExpr => "`for` iterator expression",
541             UnusedDelimsCtx::MatchScrutineeExpr => "`match` scrutinee expression",
542             UnusedDelimsCtx::ReturnValue => "`return` value",
543             UnusedDelimsCtx::BlockRetValue => "block return value",
544             UnusedDelimsCtx::LetScrutineeExpr => "`let` scrutinee expression",
545             UnusedDelimsCtx::ArrayLenExpr | UnusedDelimsCtx::AnonConst => "const expression",
546             UnusedDelimsCtx::MatchArmExpr => "match arm expression",
547         }
548     }
549 }
550
551 /// Used by both `UnusedParens` and `UnusedBraces` to prevent code duplication.
552 trait UnusedDelimLint {
553     const DELIM_STR: &'static str;
554
555     /// Due to `ref` pattern, there can be a difference between using
556     /// `{ expr }` and `expr` in pattern-matching contexts. This means
557     /// that we should only lint `unused_parens` and not `unused_braces`
558     /// in this case.
559     ///
560     /// ```rust
561     /// let mut a = 7;
562     /// let ref b = { a }; // We actually borrow a copy of `a` here.
563     /// a += 1; // By mutating `a` we invalidate any borrows of `a`.
564     /// assert_eq!(b + 1, a); // `b` does not borrow `a`, so we can still use it here.
565     /// ```
566     const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool;
567
568     // this cannot be a constant is it refers to a static.
569     fn lint(&self) -> &'static Lint;
570
571     fn check_unused_delims_expr(
572         &self,
573         cx: &EarlyContext<'_>,
574         value: &ast::Expr,
575         ctx: UnusedDelimsCtx,
576         followed_by_block: bool,
577         left_pos: Option<BytePos>,
578         right_pos: Option<BytePos>,
579     );
580
581     fn is_expr_delims_necessary(
582         inner: &ast::Expr,
583         followed_by_block: bool,
584         followed_by_else: bool,
585     ) -> bool {
586         if followed_by_else {
587             match inner.kind {
588                 ast::ExprKind::Binary(op, ..) if op.node.lazy() => return true,
589                 _ if classify::expr_trailing_brace(inner).is_some() => return true,
590                 _ => {}
591             }
592         }
593
594         // Prevent false-positives in cases like `fn x() -> u8 { ({ 0 } + 1) }`
595         let lhs_needs_parens = {
596             let mut innermost = inner;
597             loop {
598                 innermost = match &innermost.kind {
599                     ExprKind::Binary(_, lhs, _rhs) => lhs,
600                     ExprKind::Call(fn_, _params) => fn_,
601                     ExprKind::Cast(expr, _ty) => expr,
602                     ExprKind::Type(expr, _ty) => expr,
603                     ExprKind::Index(base, _subscript) => base,
604                     _ => break false,
605                 };
606                 if !classify::expr_requires_semi_to_be_stmt(innermost) {
607                     break true;
608                 }
609             }
610         };
611
612         lhs_needs_parens
613             || (followed_by_block
614                 && match &inner.kind {
615                     ExprKind::Ret(_)
616                     | ExprKind::Break(..)
617                     | ExprKind::Yield(..)
618                     | ExprKind::Yeet(..) => true,
619                     ExprKind::Range(_lhs, Some(rhs), _limits) => {
620                         matches!(rhs.kind, ExprKind::Block(..))
621                     }
622                     _ => parser::contains_exterior_struct_lit(&inner),
623                 })
624     }
625
626     fn emit_unused_delims_expr(
627         &self,
628         cx: &EarlyContext<'_>,
629         value: &ast::Expr,
630         ctx: UnusedDelimsCtx,
631         left_pos: Option<BytePos>,
632         right_pos: Option<BytePos>,
633     ) {
634         // If `value` has `ExprKind::Err`, unused delim lint can be broken.
635         // For example, the following code caused ICE.
636         // This is because the `ExprKind::Call` in `value` has `ExprKind::Err` as its argument
637         // and this leads to wrong spans. #104897
638         //
639         // ```
640         // fn f(){(print!(á
641         // ```
642         use rustc_ast::visit::{walk_expr, Visitor};
643         struct ErrExprVisitor {
644             has_error: bool,
645         }
646         impl<'ast> Visitor<'ast> for ErrExprVisitor {
647             fn visit_expr(&mut self, expr: &'ast ast::Expr) {
648                 if let ExprKind::Err = expr.kind {
649                     self.has_error = true;
650                     return;
651                 }
652                 walk_expr(self, expr)
653             }
654         }
655         let mut visitor = ErrExprVisitor { has_error: false };
656         visitor.visit_expr(value);
657         if visitor.has_error {
658             return;
659         }
660         let spans = match value.kind {
661             ast::ExprKind::Block(ref block, None) if block.stmts.len() == 1 => {
662                 if let Some(span) = block.stmts[0].span.find_ancestor_inside(value.span) {
663                     Some((value.span.with_hi(span.lo()), value.span.with_lo(span.hi())))
664                 } else {
665                     None
666                 }
667             }
668             ast::ExprKind::Paren(ref expr) => {
669                 let expr_span = expr.span.find_ancestor_inside(value.span);
670                 if let Some(expr_span) = expr_span {
671                     Some((value.span.with_hi(expr_span.lo()), value.span.with_lo(expr_span.hi())))
672                 } else {
673                     None
674                 }
675             }
676             _ => return,
677         };
678         let keep_space = (
679             left_pos.map_or(false, |s| s >= value.span.lo()),
680             right_pos.map_or(false, |s| s <= value.span.hi()),
681         );
682         self.emit_unused_delims(cx, value.span, spans, ctx.into(), keep_space);
683     }
684
685     fn emit_unused_delims(
686         &self,
687         cx: &EarlyContext<'_>,
688         value_span: Span,
689         spans: Option<(Span, Span)>,
690         msg: &str,
691         keep_space: (bool, bool),
692     ) {
693         let primary_span = if let Some((lo, hi)) = spans {
694             MultiSpan::from(vec![lo, hi])
695         } else {
696             MultiSpan::from(value_span)
697         };
698         cx.struct_span_lint(self.lint(), primary_span, fluent::lint_unused_delim, |lint| {
699             lint.set_arg("delim", Self::DELIM_STR);
700             lint.set_arg("item", msg);
701             if let Some((lo, hi)) = spans {
702                 let sm = cx.sess().source_map();
703                 let lo_replace =
704                     if keep_space.0 &&
705                         let Ok(snip) = sm.span_to_prev_source(lo) && !snip.ends_with(' ') {
706                         " ".to_string()
707                         } else {
708                             "".to_string()
709                         };
710
711                 let hi_replace =
712                     if keep_space.1 &&
713                         let Ok(snip) = sm.span_to_next_source(hi) && !snip.starts_with(' ') {
714                         " ".to_string()
715                         } else {
716                             "".to_string()
717                         };
718
719                 let replacement = vec![(lo, lo_replace), (hi, hi_replace)];
720                 lint.multipart_suggestion(
721                     fluent::suggestion,
722                     replacement,
723                     Applicability::MachineApplicable,
724                 );
725             }
726             lint
727         });
728     }
729
730     fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
731         use rustc_ast::ExprKind::*;
732         let (value, ctx, followed_by_block, left_pos, right_pos) = match e.kind {
733             // Do not lint `unused_braces` in `if let` expressions.
734             If(ref cond, ref block, _)
735                 if !matches!(cond.kind, Let(_, _, _))
736                     || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
737             {
738                 let left = e.span.lo() + rustc_span::BytePos(2);
739                 let right = block.span.lo();
740                 (cond, UnusedDelimsCtx::IfCond, true, Some(left), Some(right))
741             }
742
743             // Do not lint `unused_braces` in `while let` expressions.
744             While(ref cond, ref block, ..)
745                 if !matches!(cond.kind, Let(_, _, _))
746                     || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
747             {
748                 let left = e.span.lo() + rustc_span::BytePos(5);
749                 let right = block.span.lo();
750                 (cond, UnusedDelimsCtx::WhileCond, true, Some(left), Some(right))
751             }
752
753             ForLoop(_, ref cond, ref block, ..) => {
754                 (cond, UnusedDelimsCtx::ForIterExpr, true, None, Some(block.span.lo()))
755             }
756
757             Match(ref head, _) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
758                 let left = e.span.lo() + rustc_span::BytePos(5);
759                 (head, UnusedDelimsCtx::MatchScrutineeExpr, true, Some(left), None)
760             }
761
762             Ret(Some(ref value)) => {
763                 let left = e.span.lo() + rustc_span::BytePos(3);
764                 (value, UnusedDelimsCtx::ReturnValue, false, Some(left), None)
765             }
766
767             Assign(_, ref value, _) | AssignOp(.., ref value) => {
768                 (value, UnusedDelimsCtx::AssignedValue, false, None, None)
769             }
770             // either function/method call, or something this lint doesn't care about
771             ref call_or_other => {
772                 let (args_to_check, ctx) = match *call_or_other {
773                     Call(_, ref args) => (&args[..], UnusedDelimsCtx::FunctionArg),
774                     MethodCall(ref call) => (&call.args[..], UnusedDelimsCtx::MethodArg),
775                     // actual catch-all arm
776                     _ => {
777                         return;
778                     }
779                 };
780                 // Don't lint if this is a nested macro expansion: otherwise, the lint could
781                 // trigger in situations that macro authors shouldn't have to care about, e.g.,
782                 // when a parenthesized token tree matched in one macro expansion is matched as
783                 // an expression in another and used as a fn/method argument (Issue #47775)
784                 if e.span.ctxt().outer_expn_data().call_site.from_expansion() {
785                     return;
786                 }
787                 for arg in args_to_check {
788                     self.check_unused_delims_expr(cx, arg, ctx, false, None, None);
789                 }
790                 return;
791             }
792         };
793         self.check_unused_delims_expr(cx, &value, ctx, followed_by_block, left_pos, right_pos);
794     }
795
796     fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
797         match s.kind {
798             StmtKind::Local(ref local) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
799                 if let Some((init, els)) = local.kind.init_else_opt() {
800                     let ctx = match els {
801                         None => UnusedDelimsCtx::AssignedValue,
802                         Some(_) => UnusedDelimsCtx::AssignedValueLetElse,
803                     };
804                     self.check_unused_delims_expr(cx, init, ctx, false, None, None);
805                 }
806             }
807             StmtKind::Expr(ref expr) => {
808                 self.check_unused_delims_expr(
809                     cx,
810                     &expr,
811                     UnusedDelimsCtx::BlockRetValue,
812                     false,
813                     None,
814                     None,
815                 );
816             }
817             _ => {}
818         }
819     }
820
821     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
822         use ast::ItemKind::*;
823
824         if let Const(.., Some(expr)) | Static(.., Some(expr)) = &item.kind {
825             self.check_unused_delims_expr(
826                 cx,
827                 expr,
828                 UnusedDelimsCtx::AssignedValue,
829                 false,
830                 None,
831                 None,
832             );
833         }
834     }
835 }
836
837 declare_lint! {
838     /// The `unused_parens` lint detects `if`, `match`, `while` and `return`
839     /// with parentheses; they do not need them.
840     ///
841     /// ### Examples
842     ///
843     /// ```rust
844     /// if(true) {}
845     /// ```
846     ///
847     /// {{produces}}
848     ///
849     /// ### Explanation
850     ///
851     /// The parentheses are not needed, and should be removed. This is the
852     /// preferred style for writing these expressions.
853     pub(super) UNUSED_PARENS,
854     Warn,
855     "`if`, `match`, `while` and `return` do not need parentheses"
856 }
857
858 declare_lint_pass!(UnusedParens => [UNUSED_PARENS]);
859
860 impl UnusedDelimLint for UnusedParens {
861     const DELIM_STR: &'static str = "parentheses";
862
863     const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = true;
864
865     fn lint(&self) -> &'static Lint {
866         UNUSED_PARENS
867     }
868
869     fn check_unused_delims_expr(
870         &self,
871         cx: &EarlyContext<'_>,
872         value: &ast::Expr,
873         ctx: UnusedDelimsCtx,
874         followed_by_block: bool,
875         left_pos: Option<BytePos>,
876         right_pos: Option<BytePos>,
877     ) {
878         match value.kind {
879             ast::ExprKind::Paren(ref inner) => {
880                 let followed_by_else = ctx == UnusedDelimsCtx::AssignedValueLetElse;
881                 if !Self::is_expr_delims_necessary(inner, followed_by_block, followed_by_else)
882                     && value.attrs.is_empty()
883                     && !value.span.from_expansion()
884                     && (ctx != UnusedDelimsCtx::LetScrutineeExpr
885                         || !matches!(inner.kind, ast::ExprKind::Binary(
886                                 rustc_span::source_map::Spanned { node, .. },
887                                 _,
888                                 _,
889                             ) if node.lazy()))
890                 {
891                     self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
892                 }
893             }
894             ast::ExprKind::Let(_, ref expr, _) => {
895                 self.check_unused_delims_expr(
896                     cx,
897                     expr,
898                     UnusedDelimsCtx::LetScrutineeExpr,
899                     followed_by_block,
900                     None,
901                     None,
902                 );
903             }
904             _ => {}
905         }
906     }
907 }
908
909 impl UnusedParens {
910     fn check_unused_parens_pat(
911         &self,
912         cx: &EarlyContext<'_>,
913         value: &ast::Pat,
914         avoid_or: bool,
915         avoid_mut: bool,
916         keep_space: (bool, bool),
917     ) {
918         use ast::{BindingAnnotation, PatKind};
919
920         if let PatKind::Paren(inner) = &value.kind {
921             match inner.kind {
922                 // The lint visitor will visit each subpattern of `p`. We do not want to lint
923                 // any range pattern no matter where it occurs in the pattern. For something like
924                 // `&(a..=b)`, there is a recursive `check_pat` on `a` and `b`, but we will assume
925                 // that if there are unnecessary parens they serve a purpose of readability.
926                 PatKind::Range(..) => return,
927                 // Avoid `p0 | .. | pn` if we should.
928                 PatKind::Or(..) if avoid_or => return,
929                 // Avoid `mut x` and `mut x @ p` if we should:
930                 PatKind::Ident(BindingAnnotation::MUT, ..) if avoid_mut => {
931                     return;
932                 }
933                 // Otherwise proceed with linting.
934                 _ => {}
935             }
936             let spans = if let Some(inner) = inner.span.find_ancestor_inside(value.span) {
937                 Some((value.span.with_hi(inner.lo()), value.span.with_lo(inner.hi())))
938             } else {
939                 None
940             };
941             self.emit_unused_delims(cx, value.span, spans, "pattern", keep_space);
942         }
943     }
944 }
945
946 impl EarlyLintPass for UnusedParens {
947     #[inline]
948     fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
949         match e.kind {
950             ExprKind::Let(ref pat, _, _) | ExprKind::ForLoop(ref pat, ..) => {
951                 self.check_unused_parens_pat(cx, pat, false, false, (true, true));
952             }
953             // We ignore parens in cases like `if (((let Some(0) = Some(1))))` because we already
954             // handle a hard error for them during AST lowering in `lower_expr_mut`, but we still
955             // want to complain about things like `if let 42 = (42)`.
956             ExprKind::If(ref cond, ref block, ref else_)
957                 if matches!(cond.peel_parens().kind, ExprKind::Let(..)) =>
958             {
959                 self.check_unused_delims_expr(
960                     cx,
961                     cond.peel_parens(),
962                     UnusedDelimsCtx::LetScrutineeExpr,
963                     true,
964                     None,
965                     None,
966                 );
967                 for stmt in &block.stmts {
968                     <Self as UnusedDelimLint>::check_stmt(self, cx, stmt);
969                 }
970                 if let Some(e) = else_ {
971                     <Self as UnusedDelimLint>::check_expr(self, cx, e);
972                 }
973                 return;
974             }
975             ExprKind::Match(ref _expr, ref arm) => {
976                 for a in arm {
977                     self.check_unused_delims_expr(
978                         cx,
979                         &a.body,
980                         UnusedDelimsCtx::MatchArmExpr,
981                         false,
982                         None,
983                         None,
984                     );
985                 }
986             }
987             _ => {}
988         }
989
990         <Self as UnusedDelimLint>::check_expr(self, cx, e)
991     }
992
993     fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
994         use ast::{Mutability, PatKind::*};
995         let keep_space = (false, false);
996         match &p.kind {
997             // Do not lint on `(..)` as that will result in the other arms being useless.
998             Paren(_)
999             // The other cases do not contain sub-patterns.
1000             | Wild | Rest | Lit(..) | MacCall(..) | Range(..) | Ident(.., None) | Path(..) => {},
1001             // These are list-like patterns; parens can always be removed.
1002             TupleStruct(_, _, ps) | Tuple(ps) | Slice(ps) | Or(ps) => for p in ps {
1003                 self.check_unused_parens_pat(cx, p, false, false, keep_space);
1004             },
1005             Struct(_, _, fps, _) => for f in fps {
1006                 self.check_unused_parens_pat(cx, &f.pat, false, false, keep_space);
1007             },
1008             // Avoid linting on `i @ (p0 | .. | pn)` and `box (p0 | .. | pn)`, #64106.
1009             Ident(.., Some(p)) | Box(p) => self.check_unused_parens_pat(cx, p, true, false, keep_space),
1010             // Avoid linting on `&(mut x)` as `&mut x` has a different meaning, #55342.
1011             // Also avoid linting on `& mut? (p0 | .. | pn)`, #64106.
1012             Ref(p, m) => self.check_unused_parens_pat(cx, p, true, *m == Mutability::Not, keep_space),
1013         }
1014     }
1015
1016     fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
1017         if let StmtKind::Local(ref local) = s.kind {
1018             self.check_unused_parens_pat(cx, &local.pat, true, false, (false, false));
1019         }
1020
1021         <Self as UnusedDelimLint>::check_stmt(self, cx, s)
1022     }
1023
1024     fn check_param(&mut self, cx: &EarlyContext<'_>, param: &ast::Param) {
1025         self.check_unused_parens_pat(cx, &param.pat, true, false, (false, false));
1026     }
1027
1028     fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
1029         self.check_unused_parens_pat(cx, &arm.pat, false, false, (false, false));
1030     }
1031
1032     fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
1033         if let ast::TyKind::Paren(r) = &ty.kind {
1034             match &r.kind {
1035                 ast::TyKind::TraitObject(..) => {}
1036                 ast::TyKind::BareFn(b) if b.generic_params.len() > 0 => {}
1037                 ast::TyKind::ImplTrait(_, bounds) if bounds.len() > 1 => {}
1038                 ast::TyKind::Array(_, len) => {
1039                     self.check_unused_delims_expr(
1040                         cx,
1041                         &len.value,
1042                         UnusedDelimsCtx::ArrayLenExpr,
1043                         false,
1044                         None,
1045                         None,
1046                     );
1047                 }
1048                 _ => {
1049                     let spans = if let Some(r) = r.span.find_ancestor_inside(ty.span) {
1050                         Some((ty.span.with_hi(r.lo()), ty.span.with_lo(r.hi())))
1051                     } else {
1052                         None
1053                     };
1054                     self.emit_unused_delims(cx, ty.span, spans, "type", (false, false));
1055                 }
1056             }
1057         }
1058     }
1059
1060     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1061         <Self as UnusedDelimLint>::check_item(self, cx, item)
1062     }
1063 }
1064
1065 declare_lint! {
1066     /// The `unused_braces` lint detects unnecessary braces around an
1067     /// expression.
1068     ///
1069     /// ### Example
1070     ///
1071     /// ```rust
1072     /// if { true } {
1073     ///     // ...
1074     /// }
1075     /// ```
1076     ///
1077     /// {{produces}}
1078     ///
1079     /// ### Explanation
1080     ///
1081     /// The braces are not needed, and should be removed. This is the
1082     /// preferred style for writing these expressions.
1083     pub(super) UNUSED_BRACES,
1084     Warn,
1085     "unnecessary braces around an expression"
1086 }
1087
1088 declare_lint_pass!(UnusedBraces => [UNUSED_BRACES]);
1089
1090 impl UnusedDelimLint for UnusedBraces {
1091     const DELIM_STR: &'static str = "braces";
1092
1093     const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = false;
1094
1095     fn lint(&self) -> &'static Lint {
1096         UNUSED_BRACES
1097     }
1098
1099     fn check_unused_delims_expr(
1100         &self,
1101         cx: &EarlyContext<'_>,
1102         value: &ast::Expr,
1103         ctx: UnusedDelimsCtx,
1104         followed_by_block: bool,
1105         left_pos: Option<BytePos>,
1106         right_pos: Option<BytePos>,
1107     ) {
1108         match value.kind {
1109             ast::ExprKind::Block(ref inner, None)
1110                 if inner.rules == ast::BlockCheckMode::Default =>
1111             {
1112                 // emit a warning under the following conditions:
1113                 //
1114                 // - the block does not have a label
1115                 // - the block is not `unsafe`
1116                 // - the block contains exactly one expression (do not lint `{ expr; }`)
1117                 // - `followed_by_block` is true and the internal expr may contain a `{`
1118                 // - the block is not multiline (do not lint multiline match arms)
1119                 //      ```
1120                 //      match expr {
1121                 //          Pattern => {
1122                 //              somewhat_long_expression
1123                 //          }
1124                 //          // ...
1125                 //      }
1126                 //      ```
1127                 // - the block has no attribute and was not created inside a macro
1128                 // - if the block is an `anon_const`, the inner expr must be a literal
1129                 //      (do not lint `struct A<const N: usize>; let _: A<{ 2 + 3 }>;`)
1130                 //
1131                 // FIXME(const_generics): handle paths when #67075 is fixed.
1132                 if let [stmt] = inner.stmts.as_slice() {
1133                     if let ast::StmtKind::Expr(ref expr) = stmt.kind {
1134                         if !Self::is_expr_delims_necessary(expr, followed_by_block, false)
1135                             && (ctx != UnusedDelimsCtx::AnonConst
1136                                 || matches!(expr.kind, ast::ExprKind::Lit(_)))
1137                             && !cx.sess().source_map().is_multiline(value.span)
1138                             && value.attrs.is_empty()
1139                             && !value.span.from_expansion()
1140                             && !inner.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     #[inline]
1168     fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
1169         <Self as UnusedDelimLint>::check_expr(self, cx, e);
1170
1171         if let ExprKind::Repeat(_, ref anon_const) = e.kind {
1172             self.check_unused_delims_expr(
1173                 cx,
1174                 &anon_const.value,
1175                 UnusedDelimsCtx::AnonConst,
1176                 false,
1177                 None,
1178                 None,
1179             );
1180         }
1181     }
1182
1183     fn check_generic_arg(&mut self, cx: &EarlyContext<'_>, arg: &ast::GenericArg) {
1184         if let ast::GenericArg::Const(ct) = arg {
1185             self.check_unused_delims_expr(
1186                 cx,
1187                 &ct.value,
1188                 UnusedDelimsCtx::AnonConst,
1189                 false,
1190                 None,
1191                 None,
1192             );
1193         }
1194     }
1195
1196     fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant) {
1197         if let Some(anon_const) = &v.disr_expr {
1198             self.check_unused_delims_expr(
1199                 cx,
1200                 &anon_const.value,
1201                 UnusedDelimsCtx::AnonConst,
1202                 false,
1203                 None,
1204                 None,
1205             );
1206         }
1207     }
1208
1209     fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
1210         match ty.kind {
1211             ast::TyKind::Array(_, ref len) => {
1212                 self.check_unused_delims_expr(
1213                     cx,
1214                     &len.value,
1215                     UnusedDelimsCtx::ArrayLenExpr,
1216                     false,
1217                     None,
1218                     None,
1219                 );
1220             }
1221
1222             ast::TyKind::Typeof(ref anon_const) => {
1223                 self.check_unused_delims_expr(
1224                     cx,
1225                     &anon_const.value,
1226                     UnusedDelimsCtx::AnonConst,
1227                     false,
1228                     None,
1229                     None,
1230                 );
1231             }
1232
1233             _ => {}
1234         }
1235     }
1236
1237     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1238         <Self as UnusedDelimLint>::check_item(self, cx, item)
1239     }
1240 }
1241
1242 declare_lint! {
1243     /// The `unused_import_braces` lint catches unnecessary braces around an
1244     /// imported item.
1245     ///
1246     /// ### Example
1247     ///
1248     /// ```rust,compile_fail
1249     /// #![deny(unused_import_braces)]
1250     /// use test::{A};
1251     ///
1252     /// pub mod test {
1253     ///     pub struct A;
1254     /// }
1255     /// # fn main() {}
1256     /// ```
1257     ///
1258     /// {{produces}}
1259     ///
1260     /// ### Explanation
1261     ///
1262     /// If there is only a single item, then remove the braces (`use test::A;`
1263     /// for example).
1264     ///
1265     /// This lint is "allow" by default because it is only enforcing a
1266     /// stylistic choice.
1267     UNUSED_IMPORT_BRACES,
1268     Allow,
1269     "unnecessary braces around an imported item"
1270 }
1271
1272 declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]);
1273
1274 impl UnusedImportBraces {
1275     fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
1276         if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
1277             // Recursively check nested UseTrees
1278             for (tree, _) in items {
1279                 self.check_use_tree(cx, tree, item);
1280             }
1281
1282             // Trigger the lint only if there is one nested item
1283             if items.len() != 1 {
1284                 return;
1285             }
1286
1287             // Trigger the lint if the nested item is a non-self single item
1288             let node_name = match items[0].0.kind {
1289                 ast::UseTreeKind::Simple(rename) => {
1290                     let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
1291                     if orig_ident.name == kw::SelfLower {
1292                         return;
1293                     }
1294                     rename.unwrap_or(orig_ident).name
1295                 }
1296                 ast::UseTreeKind::Glob => Symbol::intern("*"),
1297                 ast::UseTreeKind::Nested(_) => return,
1298             };
1299
1300             cx.struct_span_lint(
1301                 UNUSED_IMPORT_BRACES,
1302                 item.span,
1303                 fluent::lint_unused_import_braces,
1304                 |lint| lint.set_arg("node", node_name),
1305             );
1306         }
1307     }
1308 }
1309
1310 impl EarlyLintPass for UnusedImportBraces {
1311     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
1312         if let ast::ItemKind::Use(ref use_tree) = item.kind {
1313             self.check_use_tree(cx, use_tree, item);
1314         }
1315     }
1316 }
1317
1318 declare_lint! {
1319     /// The `unused_allocation` lint detects unnecessary allocations that can
1320     /// be eliminated.
1321     ///
1322     /// ### Example
1323     ///
1324     /// ```rust
1325     /// #![feature(box_syntax)]
1326     /// fn main() {
1327     ///     let a = (box [1, 2, 3]).len();
1328     /// }
1329     /// ```
1330     ///
1331     /// {{produces}}
1332     ///
1333     /// ### Explanation
1334     ///
1335     /// When a `box` expression is immediately coerced to a reference, then
1336     /// the allocation is unnecessary, and a reference (using `&` or `&mut`)
1337     /// should be used instead to avoid the allocation.
1338     pub(super) UNUSED_ALLOCATION,
1339     Warn,
1340     "detects unnecessary allocations that can be eliminated"
1341 }
1342
1343 declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]);
1344
1345 impl<'tcx> LateLintPass<'tcx> for UnusedAllocation {
1346     fn check_expr(&mut self, cx: &LateContext<'_>, e: &hir::Expr<'_>) {
1347         match e.kind {
1348             hir::ExprKind::Box(_) => {}
1349             _ => return,
1350         }
1351
1352         for adj in cx.typeck_results().expr_adjustments(e) {
1353             if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
1354                 cx.struct_span_lint(
1355                     UNUSED_ALLOCATION,
1356                     e.span,
1357                     match m {
1358                         adjustment::AutoBorrowMutability::Not => fluent::lint_unused_allocation,
1359                         adjustment::AutoBorrowMutability::Mut { .. } => {
1360                             fluent::lint_unused_allocation_mut
1361                         }
1362                     },
1363                     |lint| lint,
1364                 );
1365             }
1366         }
1367     }
1368 }