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