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