]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/unused.rs
Rollup merge of #72061 - lcnr:const-inference-test, r=eddyb
[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::PredicateKind::Trait(ref poly_trait_predicate, _) =
150                             predicate.kind()
151                         {
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     /// Due to `ref` pattern, there can be a difference between using
359     /// `{ expr }` and `expr` in pattern-matching contexts. This means
360     /// that we should only lint `unused_parens` and not `unused_braces`
361     /// in this case.
362     ///
363     /// ```rust
364     /// let mut a = 7;
365     /// let ref b = { a }; // We actually borrow a copy of `a` here.
366     /// a += 1; // By mutating `a` we invalidate any borrows of `a`.
367     /// assert_eq!(b + 1, a); // `b` does not borrow `a`, so we can still use it here.
368     /// ```
369     const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool;
370
371     // this cannot be a constant is it refers to a static.
372     fn lint(&self) -> &'static Lint;
373
374     fn check_unused_delims_expr(
375         &self,
376         cx: &EarlyContext<'_>,
377         value: &ast::Expr,
378         ctx: UnusedDelimsCtx,
379         followed_by_block: bool,
380         left_pos: Option<BytePos>,
381         right_pos: Option<BytePos>,
382     );
383
384     fn is_expr_delims_necessary(inner: &ast::Expr, followed_by_block: bool) -> bool {
385         // Prevent false-positives in cases like `fn x() -> u8 { ({ 0 } + 1) }`
386         let lhs_needs_parens = {
387             let mut innermost = inner;
388             loop {
389                 if let ExprKind::Binary(_, lhs, _rhs) = &innermost.kind {
390                     innermost = lhs;
391                     if !rustc_ast::util::classify::expr_requires_semi_to_be_stmt(innermost) {
392                         break true;
393                     }
394                 } else {
395                     break false;
396                 }
397             }
398         };
399
400         lhs_needs_parens
401             || (followed_by_block
402                 && match inner.kind {
403                     ExprKind::Ret(_) | ExprKind::Break(..) => true,
404                     _ => parser::contains_exterior_struct_lit(&inner),
405                 })
406     }
407
408     fn emit_unused_delims_expr(
409         &self,
410         cx: &EarlyContext<'_>,
411         value: &ast::Expr,
412         ctx: UnusedDelimsCtx,
413         left_pos: Option<BytePos>,
414         right_pos: Option<BytePos>,
415     ) {
416         let expr_text = if let Ok(snippet) = cx.sess().source_map().span_to_snippet(value.span) {
417             snippet
418         } else {
419             pprust::expr_to_string(value)
420         };
421         let keep_space = (
422             left_pos.map(|s| s >= value.span.lo()).unwrap_or(false),
423             right_pos.map(|s| s <= value.span.hi()).unwrap_or(false),
424         );
425         self.emit_unused_delims(cx, value.span, &expr_text, ctx.into(), keep_space);
426     }
427
428     fn emit_unused_delims(
429         &self,
430         cx: &EarlyContext<'_>,
431         span: Span,
432         pattern: &str,
433         msg: &str,
434         keep_space: (bool, bool),
435     ) {
436         // FIXME(flip1995): Quick and dirty fix for #70814. This should be fixed in rustdoc
437         // properly.
438         if span == DUMMY_SP {
439             return;
440         }
441
442         cx.struct_span_lint(self.lint(), span, |lint| {
443             let span_msg = format!("unnecessary {} around {}", Self::DELIM_STR, msg);
444             let mut err = lint.build(&span_msg);
445             let mut ate_left_paren = false;
446             let mut ate_right_paren = false;
447             let parens_removed = pattern.trim_matches(|c| match c {
448                 '(' | '{' => {
449                     if ate_left_paren {
450                         false
451                     } else {
452                         ate_left_paren = true;
453                         true
454                     }
455                 }
456                 ')' | '}' => {
457                     if ate_right_paren {
458                         false
459                     } else {
460                         ate_right_paren = true;
461                         true
462                     }
463                 }
464                 _ => false,
465             });
466
467             let replace = {
468                 let mut replace = if keep_space.0 {
469                     let mut s = String::from(" ");
470                     s.push_str(parens_removed);
471                     s
472                 } else {
473                     String::from(parens_removed)
474                 };
475
476                 if keep_space.1 {
477                     replace.push(' ');
478                 }
479                 replace
480             };
481
482             let suggestion = format!("remove these {}", Self::DELIM_STR);
483
484             err.span_suggestion_short(span, &suggestion, replace, Applicability::MachineApplicable);
485             err.emit();
486         });
487     }
488
489     fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
490         use rustc_ast::ast::ExprKind::*;
491         let (value, ctx, followed_by_block, left_pos, right_pos) = match e.kind {
492             // Do not lint `unused_braces` in `if let` expressions.
493             If(ref cond, ref block, ..)
494                 if !matches!(cond.kind, Let(_, _)) || Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX =>
495             {
496                 let left = e.span.lo() + rustc_span::BytePos(2);
497                 let right = block.span.lo();
498                 (cond, UnusedDelimsCtx::IfCond, true, Some(left), Some(right))
499             }
500
501             While(ref cond, ref block, ..) => {
502                 let left = e.span.lo() + rustc_span::BytePos(5);
503                 let right = block.span.lo();
504                 (cond, UnusedDelimsCtx::WhileCond, true, Some(left), Some(right))
505             }
506
507             ForLoop(_, ref cond, ref block, ..) => {
508                 (cond, UnusedDelimsCtx::ForIterExpr, true, None, Some(block.span.lo()))
509             }
510
511             Match(ref head, _) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
512                 let left = e.span.lo() + rustc_span::BytePos(5);
513                 (head, UnusedDelimsCtx::MatchScrutineeExpr, true, Some(left), None)
514             }
515
516             Ret(Some(ref value)) => {
517                 let left = e.span.lo() + rustc_span::BytePos(3);
518                 (value, UnusedDelimsCtx::ReturnValue, false, Some(left), None)
519             }
520
521             Assign(_, ref value, _) | AssignOp(.., ref value) => {
522                 (value, UnusedDelimsCtx::AssignedValue, false, None, None)
523             }
524             // either function/method call, or something this lint doesn't care about
525             ref call_or_other => {
526                 let (args_to_check, ctx) = match *call_or_other {
527                     Call(_, ref args) => (&args[..], UnusedDelimsCtx::FunctionArg),
528                     // first "argument" is self (which sometimes needs delims)
529                     MethodCall(_, ref args) => (&args[1..], UnusedDelimsCtx::MethodArg),
530                     // actual catch-all arm
531                     _ => {
532                         return;
533                     }
534                 };
535                 // Don't lint if this is a nested macro expansion: otherwise, the lint could
536                 // trigger in situations that macro authors shouldn't have to care about, e.g.,
537                 // when a parenthesized token tree matched in one macro expansion is matched as
538                 // an expression in another and used as a fn/method argument (Issue #47775)
539                 if e.span.ctxt().outer_expn_data().call_site.from_expansion() {
540                     return;
541                 }
542                 for arg in args_to_check {
543                     self.check_unused_delims_expr(cx, arg, ctx, false, None, None);
544                 }
545                 return;
546             }
547         };
548         self.check_unused_delims_expr(cx, &value, ctx, followed_by_block, left_pos, right_pos);
549     }
550
551     fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
552         match s.kind {
553             StmtKind::Local(ref local) if Self::LINT_EXPR_IN_PATTERN_MATCHING_CTX => {
554                 if let Some(ref value) = local.init {
555                     self.check_unused_delims_expr(
556                         cx,
557                         &value,
558                         UnusedDelimsCtx::AssignedValue,
559                         false,
560                         None,
561                         None,
562                     );
563                 }
564             }
565             StmtKind::Expr(ref expr) => {
566                 self.check_unused_delims_expr(
567                     cx,
568                     &expr,
569                     UnusedDelimsCtx::BlockRetValue,
570                     false,
571                     None,
572                     None,
573                 );
574             }
575             _ => {}
576         }
577     }
578
579     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
580         use ast::ItemKind::*;
581
582         if let Const(.., Some(expr)) | Static(.., Some(expr)) = &item.kind {
583             self.check_unused_delims_expr(
584                 cx,
585                 expr,
586                 UnusedDelimsCtx::AssignedValue,
587                 false,
588                 None,
589                 None,
590             );
591         }
592     }
593 }
594
595 declare_lint! {
596     pub(super) UNUSED_PARENS,
597     Warn,
598     "`if`, `match`, `while` and `return` do not need parentheses"
599 }
600
601 declare_lint_pass!(UnusedParens => [UNUSED_PARENS]);
602
603 impl UnusedDelimLint for UnusedParens {
604     const DELIM_STR: &'static str = "parentheses";
605
606     const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = true;
607
608     fn lint(&self) -> &'static Lint {
609         UNUSED_PARENS
610     }
611
612     fn check_unused_delims_expr(
613         &self,
614         cx: &EarlyContext<'_>,
615         value: &ast::Expr,
616         ctx: UnusedDelimsCtx,
617         followed_by_block: bool,
618         left_pos: Option<BytePos>,
619         right_pos: Option<BytePos>,
620     ) {
621         match value.kind {
622             ast::ExprKind::Paren(ref inner) => {
623                 if !Self::is_expr_delims_necessary(inner, followed_by_block)
624                     && value.attrs.is_empty()
625                     && !value.span.from_expansion()
626                 {
627                     self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
628                 }
629             }
630             ast::ExprKind::Let(_, ref expr) => {
631                 // FIXME(#60336): Properly handle `let true = (false && true)`
632                 // actually needing the parenthesis.
633                 self.check_unused_delims_expr(
634                     cx,
635                     expr,
636                     UnusedDelimsCtx::LetScrutineeExpr,
637                     followed_by_block,
638                     None,
639                     None,
640                 );
641             }
642             _ => {}
643         }
644     }
645 }
646
647 impl UnusedParens {
648     fn check_unused_parens_pat(
649         &self,
650         cx: &EarlyContext<'_>,
651         value: &ast::Pat,
652         avoid_or: bool,
653         avoid_mut: bool,
654     ) {
655         use ast::{BindingMode, Mutability, PatKind};
656
657         if let PatKind::Paren(inner) = &value.kind {
658             match inner.kind {
659                 // The lint visitor will visit each subpattern of `p`. We do not want to lint
660                 // any range pattern no matter where it occurs in the pattern. For something like
661                 // `&(a..=b)`, there is a recursive `check_pat` on `a` and `b`, but we will assume
662                 // that if there are unnecessary parens they serve a purpose of readability.
663                 PatKind::Range(..) => return,
664                 // Avoid `p0 | .. | pn` if we should.
665                 PatKind::Or(..) if avoid_or => return,
666                 // Avoid `mut x` and `mut x @ p` if we should:
667                 PatKind::Ident(BindingMode::ByValue(Mutability::Mut), ..) if avoid_mut => return,
668                 // Otherwise proceed with linting.
669                 _ => {}
670             }
671
672             let pattern_text =
673                 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(value.span) {
674                     snippet
675                 } else {
676                     pprust::pat_to_string(value)
677                 };
678             self.emit_unused_delims(cx, value.span, &pattern_text, "pattern", (false, false));
679         }
680     }
681 }
682
683 impl EarlyLintPass for UnusedParens {
684     fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
685         if let ExprKind::Let(ref pat, ..) | ExprKind::ForLoop(ref pat, ..) = e.kind {
686             self.check_unused_parens_pat(cx, pat, false, false);
687         }
688
689         <Self as UnusedDelimLint>::check_expr(self, cx, e)
690     }
691
692     fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) {
693         use ast::{Mutability, PatKind::*};
694         match &p.kind {
695             // Do not lint on `(..)` as that will result in the other arms being useless.
696             Paren(_)
697             // The other cases do not contain sub-patterns.
698             | Wild | Rest | Lit(..) | MacCall(..) | Range(..) | Ident(.., None) | Path(..) => {},
699             // These are list-like patterns; parens can always be removed.
700             TupleStruct(_, ps) | Tuple(ps) | Slice(ps) | Or(ps) => for p in ps {
701                 self.check_unused_parens_pat(cx, p, false, false);
702             },
703             Struct(_, fps, _) => for f in fps {
704                 self.check_unused_parens_pat(cx, &f.pat, false, false);
705             },
706             // Avoid linting on `i @ (p0 | .. | pn)` and `box (p0 | .. | pn)`, #64106.
707             Ident(.., Some(p)) | Box(p) => self.check_unused_parens_pat(cx, p, true, false),
708             // Avoid linting on `&(mut x)` as `&mut x` has a different meaning, #55342.
709             // Also avoid linting on `& mut? (p0 | .. | pn)`, #64106.
710             Ref(p, m) => self.check_unused_parens_pat(cx, p, true, *m == Mutability::Not),
711         }
712     }
713
714     fn check_anon_const(&mut self, cx: &EarlyContext<'_>, c: &ast::AnonConst) {
715         self.check_unused_delims_expr(cx, &c.value, UnusedDelimsCtx::AnonConst, false, None, None);
716     }
717
718     fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
719         if let StmtKind::Local(ref local) = s.kind {
720             self.check_unused_parens_pat(cx, &local.pat, false, false);
721         }
722
723         <Self as UnusedDelimLint>::check_stmt(self, cx, s)
724     }
725
726     fn check_param(&mut self, cx: &EarlyContext<'_>, param: &ast::Param) {
727         self.check_unused_parens_pat(cx, &param.pat, true, false);
728     }
729
730     fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
731         self.check_unused_parens_pat(cx, &arm.pat, false, false);
732     }
733
734     fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
735         if let &ast::TyKind::Paren(ref r) = &ty.kind {
736             match &r.kind {
737                 &ast::TyKind::TraitObject(..) => {}
738                 &ast::TyKind::ImplTrait(_, ref bounds) if bounds.len() > 1 => {}
739                 &ast::TyKind::Array(_, ref len) => {
740                     self.check_unused_delims_expr(
741                         cx,
742                         &len.value,
743                         UnusedDelimsCtx::ArrayLenExpr,
744                         false,
745                         None,
746                         None,
747                     );
748                 }
749                 _ => {
750                     let pattern_text =
751                         if let Ok(snippet) = cx.sess().source_map().span_to_snippet(ty.span) {
752                             snippet
753                         } else {
754                             pprust::ty_to_string(ty)
755                         };
756
757                     self.emit_unused_delims(cx, ty.span, &pattern_text, "type", (false, false));
758                 }
759             }
760         }
761     }
762
763     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
764         <Self as UnusedDelimLint>::check_item(self, cx, item)
765     }
766 }
767
768 declare_lint! {
769     pub(super) UNUSED_BRACES,
770     Warn,
771     "unnecessary braces around an expression"
772 }
773
774 declare_lint_pass!(UnusedBraces => [UNUSED_BRACES]);
775
776 impl UnusedDelimLint for UnusedBraces {
777     const DELIM_STR: &'static str = "braces";
778
779     const LINT_EXPR_IN_PATTERN_MATCHING_CTX: bool = false;
780
781     fn lint(&self) -> &'static Lint {
782         UNUSED_BRACES
783     }
784
785     fn check_unused_delims_expr(
786         &self,
787         cx: &EarlyContext<'_>,
788         value: &ast::Expr,
789         ctx: UnusedDelimsCtx,
790         followed_by_block: bool,
791         left_pos: Option<BytePos>,
792         right_pos: Option<BytePos>,
793     ) {
794         match value.kind {
795             ast::ExprKind::Block(ref inner, None)
796                 if inner.rules == ast::BlockCheckMode::Default =>
797             {
798                 // emit a warning under the following conditions:
799                 //
800                 // - the block does not have a label
801                 // - the block is not `unsafe`
802                 // - the block contains exactly one expression (do not lint `{ expr; }`)
803                 // - `followed_by_block` is true and the internal expr may contain a `{`
804                 // - the block is not multiline (do not lint multiline match arms)
805                 //      ```
806                 //      match expr {
807                 //          Pattern => {
808                 //              somewhat_long_expression
809                 //          }
810                 //          // ...
811                 //      }
812                 //      ```
813                 // - the block has no attribute and was not created inside a macro
814                 // - if the block is an `anon_const`, the inner expr must be a literal
815                 //      (do not lint `struct A<const N: usize>; let _: A<{ 2 + 3 }>;`)
816                 //
817                 // FIXME(const_generics): handle paths when #67075 is fixed.
818                 if let [stmt] = inner.stmts.as_slice() {
819                     if let ast::StmtKind::Expr(ref expr) = stmt.kind {
820                         if !Self::is_expr_delims_necessary(expr, followed_by_block)
821                             && (ctx != UnusedDelimsCtx::AnonConst
822                                 || matches!(expr.kind, ast::ExprKind::Lit(_)))
823                             // array length expressions are checked during `check_anon_const` and `check_ty`,
824                             // once as `ArrayLenExpr` and once as `AnonConst`.
825                             //
826                             // As we do not want to lint this twice, we do not emit an error for
827                             // `ArrayLenExpr` if `AnonConst` would do the same.
828                             && (ctx != UnusedDelimsCtx::ArrayLenExpr
829                                 || !matches!(expr.kind, ast::ExprKind::Lit(_)))
830                             && !cx.sess().source_map().is_multiline(value.span)
831                             && value.attrs.is_empty()
832                             && !value.span.from_expansion()
833                         {
834                             self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
835                         }
836                     }
837                 }
838             }
839             ast::ExprKind::Let(_, ref expr) => {
840                 // FIXME(#60336): Properly handle `let true = (false && true)`
841                 // actually needing the parenthesis.
842                 self.check_unused_delims_expr(
843                     cx,
844                     expr,
845                     UnusedDelimsCtx::LetScrutineeExpr,
846                     followed_by_block,
847                     None,
848                     None,
849                 );
850             }
851             _ => {}
852         }
853     }
854 }
855
856 impl EarlyLintPass for UnusedBraces {
857     fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
858         <Self as UnusedDelimLint>::check_expr(self, cx, e)
859     }
860
861     fn check_anon_const(&mut self, cx: &EarlyContext<'_>, c: &ast::AnonConst) {
862         self.check_unused_delims_expr(cx, &c.value, UnusedDelimsCtx::AnonConst, false, None, None);
863     }
864
865     fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
866         <Self as UnusedDelimLint>::check_stmt(self, cx, s)
867     }
868
869     fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
870         if let &ast::TyKind::Paren(ref r) = &ty.kind {
871             if let ast::TyKind::Array(_, ref len) = r.kind {
872                 self.check_unused_delims_expr(
873                     cx,
874                     &len.value,
875                     UnusedDelimsCtx::ArrayLenExpr,
876                     false,
877                     None,
878                     None,
879                 );
880             }
881         }
882     }
883
884     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
885         <Self as UnusedDelimLint>::check_item(self, cx, item)
886     }
887 }
888
889 declare_lint! {
890     UNUSED_IMPORT_BRACES,
891     Allow,
892     "unnecessary braces around an imported item"
893 }
894
895 declare_lint_pass!(UnusedImportBraces => [UNUSED_IMPORT_BRACES]);
896
897 impl UnusedImportBraces {
898     fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
899         if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
900             // Recursively check nested UseTrees
901             for &(ref tree, _) in items {
902                 self.check_use_tree(cx, tree, item);
903             }
904
905             // Trigger the lint only if there is one nested item
906             if items.len() != 1 {
907                 return;
908             }
909
910             // Trigger the lint if the nested item is a non-self single item
911             let node_name = match items[0].0.kind {
912                 ast::UseTreeKind::Simple(rename, ..) => {
913                     let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
914                     if orig_ident.name == kw::SelfLower {
915                         return;
916                     }
917                     rename.unwrap_or(orig_ident).name
918                 }
919                 ast::UseTreeKind::Glob => Symbol::intern("*"),
920                 ast::UseTreeKind::Nested(_) => return,
921             };
922
923             cx.struct_span_lint(UNUSED_IMPORT_BRACES, item.span, |lint| {
924                 lint.build(&format!("braces around {} is unnecessary", node_name)).emit()
925             });
926         }
927     }
928 }
929
930 impl EarlyLintPass for UnusedImportBraces {
931     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
932         if let ast::ItemKind::Use(ref use_tree) = item.kind {
933             self.check_use_tree(cx, use_tree, item);
934         }
935     }
936 }
937
938 declare_lint! {
939     pub(super) UNUSED_ALLOCATION,
940     Warn,
941     "detects unnecessary allocations that can be eliminated"
942 }
943
944 declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]);
945
946 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAllocation {
947     fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr<'_>) {
948         match e.kind {
949             hir::ExprKind::Box(_) => {}
950             _ => return,
951         }
952
953         for adj in cx.tables.expr_adjustments(e) {
954             if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind {
955                 cx.struct_span_lint(UNUSED_ALLOCATION, e.span, |lint| {
956                     let msg = match m {
957                         adjustment::AutoBorrowMutability::Not => {
958                             "unnecessary allocation, use `&` instead"
959                         }
960                         adjustment::AutoBorrowMutability::Mut { .. } => {
961                             "unnecessary allocation, use `&mut` instead"
962                         }
963                     };
964                     lint.build(msg).emit()
965                 });
966             }
967         }
968     }
969 }