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