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