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