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