]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/unused.rs
Merge commit '61667dedf55e3e5aa584f7ae2bd0471336b92ce9' into sync_cg_clif-2021-09-19
[rust.git] / compiler / rustc_lint / src / unused.rs
1 use crate::Lint;
2 use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
3 use rustc_ast as ast;
4 use rustc_ast::util::{classify, parser};
5 use rustc_ast::{ExprKind, StmtKind};
6 use rustc_errors::{pluralize, Applicability};
7 use rustc_hir as hir;
8 use rustc_hir::def::{DefKind, Res};
9 use rustc_hir::def_id::DefId;
10 use rustc_middle::ty::adjustment;
11 use rustc_middle::ty::{self, Ty};
12 use rustc_span::symbol::Symbol;
13 use rustc_span::symbol::{kw, sym};
14 use rustc_span::{BytePos, MultiSpan, Span, DUMMY_SP};
15
16 declare_lint! {
17     /// The `unused_must_use` lint detects unused result of a type flagged as
18     /// `#[must_use]`.
19     ///
20     /// ### Example
21     ///
22     /// ```rust
23     /// fn returns_result() -> Result<(), ()> {
24     ///     Ok(())
25     /// }
26     ///
27     /// fn main() {
28     ///     returns_result();
29     /// }
30     /// ```
31     ///
32     /// {{produces}}
33     ///
34     /// ### Explanation
35     ///
36     /// The `#[must_use]` attribute is an indicator that it is a mistake to
37     /// ignore the value. See [the reference] for more details.
38     ///
39     /// [the reference]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
40     pub UNUSED_MUST_USE,
41     Warn,
42     "unused result of a type flagged as `#[must_use]`",
43     report_in_external_macro
44 }
45
46 declare_lint! {
47     /// The `unused_results` lint checks for the unused result of an
48     /// expression in a statement.
49     ///
50     /// ### Example
51     ///
52     /// ```rust,compile_fail
53     /// #![deny(unused_results)]
54     /// fn foo<T>() -> T { panic!() }
55     ///
56     /// fn main() {
57     ///     foo::<usize>();
58     /// }
59     /// ```
60     ///
61     /// {{produces}}
62     ///
63     /// ### Explanation
64     ///
65     /// Ignoring the return value of a function may indicate a mistake. In
66     /// cases were it is almost certain that the result should be used, it is
67     /// recommended to annotate the function with the [`must_use` attribute].
68     /// Failure to use such a return value will trigger the [`unused_must_use`
69     /// lint] which is warn-by-default. The `unused_results` lint is
70     /// essentially the same, but triggers for *all* return values.
71     ///
72     /// This lint is "allow" by default because it can be noisy, and may not be
73     /// an actual problem. For example, calling the `remove` method of a `Vec`
74     /// or `HashMap` returns the previous value, which you may not care about.
75     /// Using this lint would require explicitly ignoring or discarding such
76     /// values.
77     ///
78     /// [`must_use` attribute]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
79     /// [`unused_must_use` lint]: warn-by-default.html#unused-must-use
80     pub UNUSED_RESULTS,
81     Allow,
82     "unused result of an expression in a statement"
83 }
84
85 declare_lint_pass!(UnusedResults => [UNUSED_MUST_USE, UNUSED_RESULTS]);
86
87 impl<'tcx> LateLintPass<'tcx> for UnusedResults {
88     fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
89         let expr = match s.kind {
90             hir::StmtKind::Semi(ref expr) => &**expr,
91             _ => return,
92         };
93
94         if let hir::ExprKind::Ret(..) = expr.kind {
95             return;
96         }
97
98         let ty = cx.typeck_results().expr_ty(&expr);
99         let type_permits_lack_of_use = check_must_use_ty(cx, ty, &expr, s.span, "", "", 1);
100
101         let mut fn_warned = false;
102         let mut op_warned = false;
103         let maybe_def_id = match expr.kind {
104             hir::ExprKind::Call(ref callee, _) => {
105                 match callee.kind {
106                     hir::ExprKind::Path(ref qpath) => {
107                         match cx.qpath_res(qpath, callee.hir_id) {
108                             Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) => Some(def_id),
109                             // `Res::Local` if it was a closure, for which we
110                             // do not currently support must-use linting
111                             _ => None,
112                         }
113                     }
114                     _ => None,
115                 }
116             }
117             hir::ExprKind::MethodCall(..) => cx.typeck_results().type_dependent_def_id(expr.hir_id),
118             _ => None,
119         };
120         if let Some(def_id) = maybe_def_id {
121             fn_warned = check_must_use_def(cx, def_id, s.span, "return value of ", "");
122         } else if type_permits_lack_of_use {
123             // We don't warn about unused unit or uninhabited types.
124             // (See https://github.com/rust-lang/rust/issues/43806 for details.)
125             return;
126         }
127
128         let must_use_op = match expr.kind {
129             // Hardcoding operators here seemed more expedient than the
130             // refactoring that would be needed to look up the `#[must_use]`
131             // attribute which does exist on the comparison trait methods
132             hir::ExprKind::Binary(bin_op, ..) => match bin_op.node {
133                 hir::BinOpKind::Eq
134                 | hir::BinOpKind::Lt
135                 | hir::BinOpKind::Le
136                 | hir::BinOpKind::Ne
137                 | hir::BinOpKind::Ge
138                 | hir::BinOpKind::Gt => Some("comparison"),
139                 hir::BinOpKind::Add
140                 | hir::BinOpKind::Sub
141                 | hir::BinOpKind::Div
142                 | hir::BinOpKind::Mul
143                 | hir::BinOpKind::Rem => Some("arithmetic operation"),
144                 hir::BinOpKind::And | hir::BinOpKind::Or => Some("logical operation"),
145                 hir::BinOpKind::BitXor
146                 | hir::BinOpKind::BitAnd
147                 | hir::BinOpKind::BitOr
148                 | hir::BinOpKind::Shl
149                 | hir::BinOpKind::Shr => Some("bitwise operation"),
150             },
151             hir::ExprKind::AddrOf(..) => Some("borrow"),
152             hir::ExprKind::Unary(..) => Some("unary operation"),
153             _ => None,
154         };
155
156         if let Some(must_use_op) = must_use_op {
157             cx.struct_span_lint(UNUSED_MUST_USE, expr.span, |lint| {
158                 let mut lint = lint.build(&format!("unused {} that must be used", must_use_op));
159                 lint.span_label(expr.span, &format!("the {} produces a value", must_use_op));
160                 lint.span_suggestion_verbose(
161                     expr.span.shrink_to_lo(),
162                     "use `let _ = ...` to ignore the resulting value",
163                     "let _ = ".to_string(),
164                     Applicability::MachineApplicable,
165                 );
166                 lint.emit();
167             });
168             op_warned = true;
169         }
170
171         if !(type_permits_lack_of_use || fn_warned || op_warned) {
172             cx.struct_span_lint(UNUSED_RESULTS, s.span, |lint| lint.build("unused result").emit());
173         }
174
175         // Returns whether an error has been emitted (and thus another does not need to be later).
176         fn check_must_use_ty<'tcx>(
177             cx: &LateContext<'tcx>,
178             ty: Ty<'tcx>,
179             expr: &hir::Expr<'_>,
180             span: Span,
181             descr_pre: &str,
182             descr_post: &str,
183             plural_len: usize,
184         ) -> bool {
185             if ty.is_unit()
186                 || cx.tcx.is_ty_uninhabited_from(
187                     cx.tcx.parent_module(expr.hir_id).to_def_id(),
188                     ty,
189                     cx.param_env,
190                 )
191             {
192                 return true;
193             }
194
195             let plural_suffix = pluralize!(plural_len);
196
197             match *ty.kind() {
198                 ty::Adt(..) if ty.is_box() => {
199                     let boxed_ty = ty.boxed_ty();
200                     let descr_pre = &format!("{}boxed ", descr_pre);
201                     check_must_use_ty(cx, boxed_ty, expr, span, descr_pre, descr_post, plural_len)
202                 }
203                 ty::Adt(def, _) => check_must_use_def(cx, def.did, span, descr_pre, descr_post),
204                 ty::Opaque(def, _) => {
205                     let mut has_emitted = false;
206                     for &(predicate, _) in cx.tcx.explicit_item_bounds(def) {
207                         // We only look at the `DefId`, so it is safe to skip the binder here.
208                         if let ty::PredicateKind::Trait(ref poly_trait_predicate) =
209                             predicate.kind().skip_binder()
210                         {
211                             let def_id = poly_trait_predicate.trait_ref.def_id;
212                             let descr_pre =
213                                 &format!("{}implementer{} of ", descr_pre, plural_suffix,);
214                             if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
215                                 has_emitted = true;
216                                 break;
217                             }
218                         }
219                     }
220                     has_emitted
221                 }
222                 ty::Dynamic(binder, _) => {
223                     let mut has_emitted = false;
224                     for predicate in binder.iter() {
225                         if let ty::ExistentialPredicate::Trait(ref trait_ref) =
226                             predicate.skip_binder()
227                         {
228                             let def_id = trait_ref.def_id;
229                             let descr_post =
230                                 &format!(" trait object{}{}", plural_suffix, descr_post,);
231                             if check_must_use_def(cx, def_id, span, descr_pre, descr_post) {
232                                 has_emitted = true;
233                                 break;
234                             }
235                         }
236                     }
237                     has_emitted
238                 }
239                 ty::Tuple(ref tys) => {
240                     let mut has_emitted = false;
241                     let spans = if let hir::ExprKind::Tup(comps) = &expr.kind {
242                         debug_assert_eq!(comps.len(), tys.len());
243                         comps.iter().map(|e| e.span).collect()
244                     } else {
245                         vec![]
246                     };
247                     for (i, ty) in tys.iter().map(|k| k.expect_ty()).enumerate() {
248                         let descr_post = &format!(" in tuple element {}", i);
249                         let span = *spans.get(i).unwrap_or(&span);
250                         if check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, plural_len)
251                         {
252                             has_emitted = true;
253                         }
254                     }
255                     has_emitted
256                 }
257                 ty::Array(ty, len) => match len.try_eval_usize(cx.tcx, cx.param_env) {
258                     // If the array is empty we don't lint, to avoid false positives
259                     Some(0) | None => false,
260                     // If the array is definitely non-empty, we can do `#[must_use]` checking.
261                     Some(n) => {
262                         let descr_pre = &format!("{}array{} of ", descr_pre, plural_suffix,);
263                         check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, n as usize + 1)
264                     }
265                 },
266                 ty::Closure(..) => {
267                     cx.struct_span_lint(UNUSED_MUST_USE, span, |lint| {
268                         let mut err = lint.build(&format!(
269                             "unused {}closure{}{} that must be used",
270                             descr_pre, plural_suffix, descr_post,
271                         ));
272                         err.note("closures are lazy and do nothing unless called");
273                         err.emit();
274                     });
275                     true
276                 }
277                 ty::Generator(..) => {
278                     cx.struct_span_lint(UNUSED_MUST_USE, span, |lint| {
279                         let mut err = lint.build(&format!(
280                             "unused {}generator{}{} that must be used",
281                             descr_pre, plural_suffix, descr_post,
282                         ));
283                         err.note("generators are lazy and do nothing unless resumed");
284                         err.emit();
285                     });
286                     true
287                 }
288                 _ => false,
289             }
290         }
291
292         // Returns whether an error has been emitted (and thus another does not need to be later).
293         // FIXME: Args desc_{pre,post}_path could be made lazy by taking Fn() -> &str, but this
294         // would make calling it a big awkward. Could also take String (so args are moved), but
295         // this would still require a copy into the format string, which would only be executed
296         // when needed.
297         fn check_must_use_def(
298             cx: &LateContext<'_>,
299             def_id: DefId,
300             span: Span,
301             descr_pre_path: &str,
302             descr_post_path: &str,
303         ) -> bool {
304             for attr in cx.tcx.get_attrs(def_id).iter() {
305                 if attr.has_name(sym::must_use) {
306                     cx.struct_span_lint(UNUSED_MUST_USE, span, |lint| {
307                         let msg = format!(
308                             "unused {}`{}`{} that must be used",
309                             descr_pre_path,
310                             cx.tcx.def_path_str(def_id),
311                             descr_post_path
312                         );
313                         let mut err = lint.build(&msg);
314                         // check for #[must_use = "..."]
315                         if let Some(note) = attr.value_str() {
316                             err.note(&note.as_str());
317                         }
318                         err.emit();
319                     });
320                     return true;
321                 }
322             }
323             false
324         }
325     }
326 }
327
328 declare_lint! {
329     /// The `path_statements` lint detects path statements with no effect.
330     ///
331     /// ### Example
332     ///
333     /// ```rust
334     /// let x = 42;
335     ///
336     /// x;
337     /// ```
338     ///
339     /// {{produces}}
340     ///
341     /// ### Explanation
342     ///
343     /// It is usually a mistake to have a statement that has no effect.
344     pub PATH_STATEMENTS,
345     Warn,
346     "path statements with no effect"
347 }
348
349 declare_lint_pass!(PathStatements => [PATH_STATEMENTS]);
350
351 impl<'tcx> LateLintPass<'tcx> for PathStatements {
352     fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) {
353         if let hir::StmtKind::Semi(expr) = s.kind {
354             if let hir::ExprKind::Path(_) = expr.kind {
355                 cx.struct_span_lint(PATH_STATEMENTS, s.span, |lint| {
356                     let ty = cx.typeck_results().expr_ty(expr);
357                     if ty.needs_drop(cx.tcx, cx.param_env) {
358                         let mut lint = lint.build("path statement drops value");
359                         if let Ok(snippet) = cx.sess().source_map().span_to_snippet(expr.span) {
360                             lint.span_suggestion(
361                                 s.span,
362                                 "use `drop` to clarify the intent",
363                                 format!("drop({});", snippet),
364                                 Applicability::MachineApplicable,
365                             );
366                         } else {
367                             lint.span_help(s.span, "use `drop` to clarify the intent");
368                         }
369                         lint.emit()
370                     } else {
371                         lint.build("path statement with no effect").emit()
372                     }
373                 });
374             }
375         }
376     }
377 }
378
379 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
380 enum UnusedDelimsCtx {
381     FunctionArg,
382     MethodArg,
383     AssignedValue,
384     AssignedValueLetElse,
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 | UnusedDelimsCtx::AssignedValueLetElse => {
402                 "assigned value"
403             }
404             UnusedDelimsCtx::IfCond => "`if` condition",
405             UnusedDelimsCtx::WhileCond => "`while` condition",
406             UnusedDelimsCtx::ForIterExpr => "`for` iterator expression",
407             UnusedDelimsCtx::MatchScrutineeExpr => "`match` scrutinee expression",
408             UnusedDelimsCtx::ReturnValue => "`return` value",
409             UnusedDelimsCtx::BlockRetValue => "block return value",
410             UnusedDelimsCtx::LetScrutineeExpr => "`let` scrutinee expression",
411             UnusedDelimsCtx::ArrayLenExpr | UnusedDelimsCtx::AnonConst => "const expression",
412         }
413     }
414 }
415
416 /// Used by both `UnusedParens` and `UnusedBraces` to prevent code duplication.
417 trait UnusedDelimLint {
418     const DELIM_STR: &'static str;
419
420     /// Due to `ref` pattern, there can be a difference between using
421     /// `{ expr }` and `expr` in pattern-matching contexts. This means
422     /// that we should only lint `unused_parens` and not `unused_braces`
423     /// in this case.
424     ///
425     /// ```rust
426     /// let mut a = 7;
427     /// let ref b = { a }; // We actually borrow a copy of `a` here.
428     /// a += 1; // By mutating `a` we invalidate any borrows of `a`.
429     /// assert_eq!(b + 1, a); // `b` does not borrow `a`, so we can still use it here.
430     /// ```
431     const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool;
432
433     // this cannot be a constant is it refers to a static.
434     fn lint(&self) -> &'static Lint;
435
436     fn check_unused_delims_expr(
437         &self,
438         cx: &EarlyContext<'_>,
439         value: &ast::Expr,
440         ctx: UnusedDelimsCtx,
441         followed_by_block: bool,
442         left_pos: Option<BytePos>,
443         right_pos: Option<BytePos>,
444     );
445
446     fn is_expr_delims_necessary(
447         inner: &ast::Expr,
448         followed_by_block: bool,
449         followed_by_else: bool,
450     ) -> bool {
451         if followed_by_else {
452             match inner.kind {
453                 ast::ExprKind::Binary(op, ..) if op.node.lazy() => return true,
454                 _ if classify::expr_trailing_brace(inner).is_some() => return true,
455                 _ => {}
456             }
457         }
458
459         // Prevent false-positives in cases like `fn x() -> u8 { ({ 0 } + 1) }`
460         let lhs_needs_parens = {
461             let mut innermost = inner;
462             loop {
463                 innermost = match &innermost.kind {
464                     ExprKind::Binary(_, lhs, _rhs) => lhs,
465                     ExprKind::Call(fn_, _params) => fn_,
466                     ExprKind::Cast(expr, _ty) => expr,
467                     ExprKind::Type(expr, _ty) => expr,
468                     ExprKind::Index(base, _subscript) => base,
469                     _ => break false,
470                 };
471                 if !classify::expr_requires_semi_to_be_stmt(innermost) {
472                     break true;
473                 }
474             }
475         };
476
477         lhs_needs_parens
478             || (followed_by_block
479                 && match inner.kind {
480                     ExprKind::Ret(_) | ExprKind::Break(..) | ExprKind::Yield(..) => true,
481                     _ => parser::contains_exterior_struct_lit(&inner),
482                 })
483     }
484
485     fn emit_unused_delims_expr(
486         &self,
487         cx: &EarlyContext<'_>,
488         value: &ast::Expr,
489         ctx: UnusedDelimsCtx,
490         left_pos: Option<BytePos>,
491         right_pos: Option<BytePos>,
492     ) {
493         let spans = match value.kind {
494             ast::ExprKind::Block(ref block, None) if block.stmts.len() > 0 => {
495                 let start = block.stmts[0].span;
496                 let end = block.stmts[block.stmts.len() - 1].span;
497                 if value.span.from_expansion() || start.from_expansion() || end.from_expansion() {
498                     (
499                         value.span.with_hi(value.span.lo() + BytePos(1)),
500                         value.span.with_lo(value.span.hi() - BytePos(1)),
501                     )
502                 } else {
503                     (value.span.with_hi(start.lo()), value.span.with_lo(end.hi()))
504                 }
505             }
506             ast::ExprKind::Paren(ref expr) => {
507                 if value.span.from_expansion() || expr.span.from_expansion() {
508                     (
509                         value.span.with_hi(value.span.lo() + BytePos(1)),
510                         value.span.with_lo(value.span.hi() - BytePos(1)),
511                     )
512                 } else {
513                     (value.span.with_hi(expr.span.lo()), value.span.with_lo(expr.span.hi()))
514                 }
515             }
516             _ => return,
517         };
518         let keep_space = (
519             left_pos.map_or(false, |s| s >= value.span.lo()),
520             right_pos.map_or(false, |s| s <= value.span.hi()),
521         );
522         self.emit_unused_delims(cx, spans, ctx.into(), keep_space);
523     }
524
525     fn emit_unused_delims(
526         &self,
527         cx: &EarlyContext<'_>,
528         spans: (Span, Span),
529         msg: &str,
530         keep_space: (bool, bool),
531     ) {
532         // FIXME(flip1995): Quick and dirty fix for #70814. This should be fixed in rustdoc
533         // properly.
534         if spans.0 == DUMMY_SP || spans.1 == DUMMY_SP {
535             return;
536         }
537
538         cx.struct_span_lint(self.lint(), MultiSpan::from(vec![spans.0, spans.1]), |lint| {
539             let span_msg = format!("unnecessary {} around {}", Self::DELIM_STR, msg);
540             let mut err = lint.build(&span_msg);
541             let replacement = vec![
542                 (spans.0, if keep_space.0 { " ".into() } else { "".into() }),
543                 (spans.1, if keep_space.1 { " ".into() } else { "".into() }),
544             ];
545             let suggestion = format!("remove these {}", Self::DELIM_STR);
546             err.multipart_suggestion(&suggestion, replacement, 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((init, els)) = local.kind.init_else_opt() {
622                     let ctx = match els {
623                         None => UnusedDelimsCtx::AssignedValue,
624                         Some(_) => UnusedDelimsCtx::AssignedValueLetElse,
625                     };
626                     self.check_unused_delims_expr(cx, init, ctx, false, None, None);
627                 }
628             }
629             StmtKind::Expr(ref expr) => {
630                 self.check_unused_delims_expr(
631                     cx,
632                     &expr,
633                     UnusedDelimsCtx::BlockRetValue,
634                     false,
635                     None,
636                     None,
637                 );
638             }
639             _ => {}
640         }
641     }
642
643     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
644         use ast::ItemKind::*;
645
646         if let Const(.., Some(expr)) | Static(.., Some(expr)) = &item.kind {
647             self.check_unused_delims_expr(
648                 cx,
649                 expr,
650                 UnusedDelimsCtx::AssignedValue,
651                 false,
652                 None,
653                 None,
654             );
655         }
656     }
657 }
658
659 declare_lint! {
660     /// The `unused_parens` lint detects `if`, `match`, `while` and `return`
661     /// with parentheses; they do not need them.
662     ///
663     /// ### Examples
664     ///
665     /// ```rust
666     /// if(true) {}
667     /// ```
668     ///
669     /// {{produces}}
670     ///
671     /// ### Explanation
672     ///
673     /// The parenthesis are not needed, and should be removed. This is the
674     /// preferred style for writing these expressions.
675     pub(super) UNUSED_PARENS,
676     Warn,
677     "`if`, `match`, `while` and `return` do not need parentheses"
678 }
679
680 declare_lint_pass!(UnusedParens => [UNUSED_PARENS]);
681
682 impl UnusedDelimLint for UnusedParens {
683     const DELIM_STR: &'static str = "parentheses";
684
685     const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = true;
686
687     fn lint(&self) -> &'static Lint {
688         UNUSED_PARENS
689     }
690
691     fn check_unused_delims_expr(
692         &self,
693         cx: &EarlyContext<'_>,
694         value: &ast::Expr,
695         ctx: UnusedDelimsCtx,
696         followed_by_block: bool,
697         left_pos: Option<BytePos>,
698         right_pos: Option<BytePos>,
699     ) {
700         match value.kind {
701             ast::ExprKind::Paren(ref inner) => {
702                 let followed_by_else = ctx == UnusedDelimsCtx::AssignedValueLetElse;
703                 if !Self::is_expr_delims_necessary(inner, followed_by_block, followed_by_else)
704                     && value.attrs.is_empty()
705                     && !value.span.from_expansion()
706                     && (ctx != UnusedDelimsCtx::LetScrutineeExpr
707                         || !matches!(inner.kind, ast::ExprKind::Binary(
708                                 rustc_span::source_map::Spanned { node, .. },
709                                 _,
710                                 _,
711                             ) if node.lazy()))
712                 {
713                     self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
714                 }
715             }
716             ast::ExprKind::Let(_, ref expr, _) => {
717                 self.check_unused_delims_expr(
718                     cx,
719                     expr,
720                     UnusedDelimsCtx::LetScrutineeExpr,
721                     followed_by_block,
722                     None,
723                     None,
724                 );
725             }
726             _ => {}
727         }
728     }
729 }
730
731 impl UnusedParens {
732     fn check_unused_parens_pat(
733         &self,
734         cx: &EarlyContext<'_>,
735         value: &ast::Pat,
736         avoid_or: bool,
737         avoid_mut: bool,
738     ) {
739         use ast::{BindingMode, Mutability, PatKind};
740
741         if let PatKind::Paren(inner) = &value.kind {
742             match inner.kind {
743                 // The lint visitor will visit each subpattern of `p`. We do not want to lint
744                 // any range pattern no matter where it occurs in the pattern. For something like
745                 // `&(a..=b)`, there is a recursive `check_pat` on `a` and `b`, but we will assume
746                 // that if there are unnecessary parens they serve a purpose of readability.
747                 PatKind::Range(..) => return,
748                 // Avoid `p0 | .. | pn` if we should.
749                 PatKind::Or(..) if avoid_or => return,
750                 // Avoid `mut x` and `mut x @ p` if we should:
751                 PatKind::Ident(BindingMode::ByValue(Mutability::Mut), ..) if avoid_mut => return,
752                 // Otherwise proceed with linting.
753                 _ => {}
754             }
755             let spans = if value.span.from_expansion() || inner.span.from_expansion() {
756                 (
757                     value.span.with_hi(value.span.lo() + BytePos(1)),
758                     value.span.with_lo(value.span.hi() - BytePos(1)),
759                 )
760             } else {
761                 (value.span.with_hi(inner.span.lo()), value.span.with_lo(inner.span.hi()))
762             };
763             self.emit_unused_delims(cx, spans, "pattern", (false, false));
764         }
765     }
766 }
767
768 impl EarlyLintPass for UnusedParens {
769     fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
770         match e.kind {
771             ExprKind::Let(ref pat, _, _) | ExprKind::ForLoop(ref pat, ..) => {
772                 self.check_unused_parens_pat(cx, pat, false, false);
773             }
774             // We ignore parens in cases like `if (((let Some(0) = Some(1))))` because we already
775             // handle a hard error for them during AST lowering in `lower_expr_mut`, but we still
776             // want to complain about things like `if let 42 = (42)`.
777             ExprKind::If(ref cond, ref block, ref else_)
778                 if matches!(cond.peel_parens().kind, ExprKind::Let(..)) =>
779             {
780                 self.check_unused_delims_expr(
781                     cx,
782                     cond.peel_parens(),
783                     UnusedDelimsCtx::LetScrutineeExpr,
784                     true,
785                     None,
786                     None,
787                 );
788                 for stmt in &block.stmts {
789                     <Self as UnusedDelimLint>::check_stmt(self, cx, stmt);
790                 }
791                 if let Some(e) = else_ {
792                     <Self as UnusedDelimLint>::check_expr(self, cx, e);
793                 }
794                 return;
795             }
796             _ => {}
797         }
798
799         <Self as UnusedDelimLint>::check_expr(self, cx, e)
800     }
801
802     fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
803         use ast::{Mutability, PatKind::*};
804         match &p.kind {
805             // Do not lint on `(..)` as that will result in the other arms being useless.
806             Paren(_)
807             // The other cases do not contain sub-patterns.
808             | Wild | Rest | Lit(..) | MacCall(..) | Range(..) | Ident(.., None) | Path(..) => {},
809             // These are list-like patterns; parens can always be removed.
810             TupleStruct(_, _, ps) | Tuple(ps) | Slice(ps) | Or(ps) => for p in ps {
811                 self.check_unused_parens_pat(cx, p, false, false);
812             },
813             Struct(_, _, fps, _) => for f in fps {
814                 self.check_unused_parens_pat(cx, &f.pat, false, false);
815             },
816             // Avoid linting on `i @ (p0 | .. | pn)` and `box (p0 | .. | pn)`, #64106.
817             Ident(.., Some(p)) | Box(p) => self.check_unused_parens_pat(cx, p, true, false),
818             // Avoid linting on `&(mut x)` as `&mut x` has a different meaning, #55342.
819             // Also avoid linting on `& mut? (p0 | .. | pn)`, #64106.
820             Ref(p, m) => self.check_unused_parens_pat(cx, p, true, *m == Mutability::Not),
821         }
822     }
823
824     fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
825         if let StmtKind::Local(ref local) = s.kind {
826             self.check_unused_parens_pat(cx, &local.pat, true, false);
827         }
828
829         <Self as UnusedDelimLint>::check_stmt(self, cx, s)
830     }
831
832     fn check_param(&mut self, cx: &EarlyContext<'_>, param: &ast::Param) {
833         self.check_unused_parens_pat(cx, &param.pat, true, false);
834     }
835
836     fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
837         self.check_unused_parens_pat(cx, &arm.pat, false, false);
838     }
839
840     fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
841         if let ast::TyKind::Paren(r) = &ty.kind {
842             match &r.kind {
843                 ast::TyKind::TraitObject(..) => {}
844                 ast::TyKind::ImplTrait(_, bounds) if bounds.len() > 1 => {}
845                 ast::TyKind::Array(_, len) => {
846                     self.check_unused_delims_expr(
847                         cx,
848                         &len.value,
849                         UnusedDelimsCtx::ArrayLenExpr,
850                         false,
851                         None,
852                         None,
853                     );
854                 }
855                 _ => {
856                     let spans = if ty.span.from_expansion() || r.span.from_expansion() {
857                         (
858                             ty.span.with_hi(ty.span.lo() + BytePos(1)),
859                             ty.span.with_lo(ty.span.hi() - BytePos(1)),
860                         )
861                     } else {
862                         (ty.span.with_hi(r.span.lo()), ty.span.with_lo(r.span.hi()))
863                     };
864                     self.emit_unused_delims(cx, spans, "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, false)
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 }