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