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