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