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