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