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