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