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