]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/matches.rs
Fix FN in `iter_cloned_collect` with a large array
[rust.git] / clippy_lints / src / matches.rs
1 use crate::consts::{constant, miri_to_const, Constant};
2 use clippy_utils::diagnostics::{
3     multispan_sugg, span_lint_and_help, span_lint_and_note, span_lint_and_sugg, span_lint_and_then,
4 };
5 use clippy_utils::source::{expr_block, indent_of, snippet, snippet_block, snippet_opt, snippet_with_applicability};
6 use clippy_utils::sugg::Sugg;
7 use clippy_utils::ty::{implements_trait, is_type_diagnostic_item, match_type, peel_mid_ty_refs};
8 use clippy_utils::visitors::LocalUsedVisitor;
9 use clippy_utils::{
10     get_parent_expr, in_macro, is_allowed, is_expn_of, is_lang_ctor, is_refutable, is_wild, meets_msrv, path_to_local,
11     path_to_local_id, peel_hir_pat_refs, peel_n_hir_expr_refs, recurse_or_patterns, remove_blocks, strip_pat_refs,
12 };
13 use clippy_utils::{paths, search_same, SpanlessEq, SpanlessHash};
14 use if_chain::if_chain;
15 use rustc_ast::ast::LitKind;
16 use rustc_errors::Applicability;
17 use rustc_hir::def::{CtorKind, DefKind, Res};
18 use rustc_hir::LangItem::{OptionNone, OptionSome};
19 use rustc_hir::{
20     self as hir, Arm, BindingAnnotation, Block, BorrowKind, Expr, ExprKind, Guard, HirId, Local, MatchSource,
21     Mutability, Node, Pat, PatKind, PathSegment, QPath, RangeEnd, TyKind,
22 };
23 use rustc_hir::{HirIdMap, HirIdSet};
24 use rustc_lint::{LateContext, LateLintPass, LintContext};
25 use rustc_middle::lint::in_external_macro;
26 use rustc_middle::ty::{self, Ty, TyS, VariantDef};
27 use rustc_semver::RustcVersion;
28 use rustc_session::{declare_tool_lint, impl_lint_pass};
29 use rustc_span::source_map::{Span, Spanned};
30 use rustc_span::sym;
31 use std::cmp::Ordering;
32 use std::collections::hash_map::Entry;
33 use std::iter;
34 use std::ops::Bound;
35
36 declare_clippy_lint! {
37     /// **What it does:** Checks for matches with a single arm where an `if let`
38     /// will usually suffice.
39     ///
40     /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
41     ///
42     /// **Known problems:** None.
43     ///
44     /// **Example:**
45     /// ```rust
46     /// # fn bar(stool: &str) {}
47     /// # let x = Some("abc");
48     /// // Bad
49     /// match x {
50     ///     Some(ref foo) => bar(foo),
51     ///     _ => (),
52     /// }
53     ///
54     /// // Good
55     /// if let Some(ref foo) = x {
56     ///     bar(foo);
57     /// }
58     /// ```
59     pub SINGLE_MATCH,
60     style,
61     "a `match` statement with a single nontrivial arm (i.e., where the other arm is `_ => {}`) instead of `if let`"
62 }
63
64 declare_clippy_lint! {
65     /// **What it does:** Checks for matches with two arms where an `if let else` will
66     /// usually suffice.
67     ///
68     /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
69     ///
70     /// **Known problems:** Personal style preferences may differ.
71     ///
72     /// **Example:**
73     ///
74     /// Using `match`:
75     ///
76     /// ```rust
77     /// # fn bar(foo: &usize) {}
78     /// # let other_ref: usize = 1;
79     /// # let x: Option<&usize> = Some(&1);
80     /// match x {
81     ///     Some(ref foo) => bar(foo),
82     ///     _ => bar(&other_ref),
83     /// }
84     /// ```
85     ///
86     /// Using `if let` with `else`:
87     ///
88     /// ```rust
89     /// # fn bar(foo: &usize) {}
90     /// # let other_ref: usize = 1;
91     /// # let x: Option<&usize> = Some(&1);
92     /// if let Some(ref foo) = x {
93     ///     bar(foo);
94     /// } else {
95     ///     bar(&other_ref);
96     /// }
97     /// ```
98     pub SINGLE_MATCH_ELSE,
99     pedantic,
100     "a `match` statement with two arms where the second arm's pattern is a placeholder instead of a specific match pattern"
101 }
102
103 declare_clippy_lint! {
104     /// **What it does:** Checks for matches where all arms match a reference,
105     /// suggesting to remove the reference and deref the matched expression
106     /// instead. It also checks for `if let &foo = bar` blocks.
107     ///
108     /// **Why is this bad?** It just makes the code less readable. That reference
109     /// destructuring adds nothing to the code.
110     ///
111     /// **Known problems:** None.
112     ///
113     /// **Example:**
114     /// ```rust,ignore
115     /// // Bad
116     /// match x {
117     ///     &A(ref y) => foo(y),
118     ///     &B => bar(),
119     ///     _ => frob(&x),
120     /// }
121     ///
122     /// // Good
123     /// match *x {
124     ///     A(ref y) => foo(y),
125     ///     B => bar(),
126     ///     _ => frob(x),
127     /// }
128     /// ```
129     pub MATCH_REF_PATS,
130     style,
131     "a `match` or `if let` with all arms prefixed with `&` instead of deref-ing the match expression"
132 }
133
134 declare_clippy_lint! {
135     /// **What it does:** Checks for matches where match expression is a `bool`. It
136     /// suggests to replace the expression with an `if...else` block.
137     ///
138     /// **Why is this bad?** It makes the code less readable.
139     ///
140     /// **Known problems:** None.
141     ///
142     /// **Example:**
143     /// ```rust
144     /// # fn foo() {}
145     /// # fn bar() {}
146     /// let condition: bool = true;
147     /// match condition {
148     ///     true => foo(),
149     ///     false => bar(),
150     /// }
151     /// ```
152     /// Use if/else instead:
153     /// ```rust
154     /// # fn foo() {}
155     /// # fn bar() {}
156     /// let condition: bool = true;
157     /// if condition {
158     ///     foo();
159     /// } else {
160     ///     bar();
161     /// }
162     /// ```
163     pub MATCH_BOOL,
164     pedantic,
165     "a `match` on a boolean expression instead of an `if..else` block"
166 }
167
168 declare_clippy_lint! {
169     /// **What it does:** Checks for overlapping match arms.
170     ///
171     /// **Why is this bad?** It is likely to be an error and if not, makes the code
172     /// less obvious.
173     ///
174     /// **Known problems:** None.
175     ///
176     /// **Example:**
177     /// ```rust
178     /// let x = 5;
179     /// match x {
180     ///     1...10 => println!("1 ... 10"),
181     ///     5...15 => println!("5 ... 15"),
182     ///     _ => (),
183     /// }
184     /// ```
185     pub MATCH_OVERLAPPING_ARM,
186     style,
187     "a `match` with overlapping arms"
188 }
189
190 declare_clippy_lint! {
191     /// **What it does:** Checks for arm which matches all errors with `Err(_)`
192     /// and take drastic actions like `panic!`.
193     ///
194     /// **Why is this bad?** It is generally a bad practice, similar to
195     /// catching all exceptions in java with `catch(Exception)`
196     ///
197     /// **Known problems:** None.
198     ///
199     /// **Example:**
200     /// ```rust
201     /// let x: Result<i32, &str> = Ok(3);
202     /// match x {
203     ///     Ok(_) => println!("ok"),
204     ///     Err(_) => panic!("err"),
205     /// }
206     /// ```
207     pub MATCH_WILD_ERR_ARM,
208     pedantic,
209     "a `match` with `Err(_)` arm and take drastic actions"
210 }
211
212 declare_clippy_lint! {
213     /// **What it does:** Checks for match which is used to add a reference to an
214     /// `Option` value.
215     ///
216     /// **Why is this bad?** Using `as_ref()` or `as_mut()` instead is shorter.
217     ///
218     /// **Known problems:** None.
219     ///
220     /// **Example:**
221     /// ```rust
222     /// let x: Option<()> = None;
223     ///
224     /// // Bad
225     /// let r: Option<&()> = match x {
226     ///     None => None,
227     ///     Some(ref v) => Some(v),
228     /// };
229     ///
230     /// // Good
231     /// let r: Option<&()> = x.as_ref();
232     /// ```
233     pub MATCH_AS_REF,
234     complexity,
235     "a `match` on an Option value instead of using `as_ref()` or `as_mut`"
236 }
237
238 declare_clippy_lint! {
239     /// **What it does:** Checks for wildcard enum matches using `_`.
240     ///
241     /// **Why is this bad?** New enum variants added by library updates can be missed.
242     ///
243     /// **Known problems:** Suggested replacements may be incorrect if guards exhaustively cover some
244     /// variants, and also may not use correct path to enum if it's not present in the current scope.
245     ///
246     /// **Example:**
247     /// ```rust
248     /// # enum Foo { A(usize), B(usize) }
249     /// # let x = Foo::B(1);
250     /// // Bad
251     /// match x {
252     ///     Foo::A(_) => {},
253     ///     _ => {},
254     /// }
255     ///
256     /// // Good
257     /// match x {
258     ///     Foo::A(_) => {},
259     ///     Foo::B(_) => {},
260     /// }
261     /// ```
262     pub WILDCARD_ENUM_MATCH_ARM,
263     restriction,
264     "a wildcard enum match arm using `_`"
265 }
266
267 declare_clippy_lint! {
268     /// **What it does:** Checks for wildcard enum matches for a single variant.
269     ///
270     /// **Why is this bad?** New enum variants added by library updates can be missed.
271     ///
272     /// **Known problems:** Suggested replacements may not use correct path to enum
273     /// if it's not present in the current scope.
274     ///
275     /// **Example:**
276     ///
277     /// ```rust
278     /// # enum Foo { A, B, C }
279     /// # let x = Foo::B;
280     /// // Bad
281     /// match x {
282     ///     Foo::A => {},
283     ///     Foo::B => {},
284     ///     _ => {},
285     /// }
286     ///
287     /// // Good
288     /// match x {
289     ///     Foo::A => {},
290     ///     Foo::B => {},
291     ///     Foo::C => {},
292     /// }
293     /// ```
294     pub MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
295     pedantic,
296     "a wildcard enum match for a single variant"
297 }
298
299 declare_clippy_lint! {
300     /// **What it does:** Checks for wildcard pattern used with others patterns in same match arm.
301     ///
302     /// **Why is this bad?** Wildcard pattern already covers any other pattern as it will match anyway.
303     /// It makes the code less readable, especially to spot wildcard pattern use in match arm.
304     ///
305     /// **Known problems:** None.
306     ///
307     /// **Example:**
308     /// ```rust
309     /// // Bad
310     /// match "foo" {
311     ///     "a" => {},
312     ///     "bar" | _ => {},
313     /// }
314     ///
315     /// // Good
316     /// match "foo" {
317     ///     "a" => {},
318     ///     _ => {},
319     /// }
320     /// ```
321     pub WILDCARD_IN_OR_PATTERNS,
322     complexity,
323     "a wildcard pattern used with others patterns in same match arm"
324 }
325
326 declare_clippy_lint! {
327     /// **What it does:** Checks for matches being used to destructure a single-variant enum
328     /// or tuple struct where a `let` will suffice.
329     ///
330     /// **Why is this bad?** Just readability – `let` doesn't nest, whereas a `match` does.
331     ///
332     /// **Known problems:** None.
333     ///
334     /// **Example:**
335     /// ```rust
336     /// enum Wrapper {
337     ///     Data(i32),
338     /// }
339     ///
340     /// let wrapper = Wrapper::Data(42);
341     ///
342     /// let data = match wrapper {
343     ///     Wrapper::Data(i) => i,
344     /// };
345     /// ```
346     ///
347     /// The correct use would be:
348     /// ```rust
349     /// enum Wrapper {
350     ///     Data(i32),
351     /// }
352     ///
353     /// let wrapper = Wrapper::Data(42);
354     /// let Wrapper::Data(data) = wrapper;
355     /// ```
356     pub INFALLIBLE_DESTRUCTURING_MATCH,
357     style,
358     "a `match` statement with a single infallible arm instead of a `let`"
359 }
360
361 declare_clippy_lint! {
362     /// **What it does:** Checks for useless match that binds to only one value.
363     ///
364     /// **Why is this bad?** Readability and needless complexity.
365     ///
366     /// **Known problems:**  Suggested replacements may be incorrect when `match`
367     /// is actually binding temporary value, bringing a 'dropped while borrowed' error.
368     ///
369     /// **Example:**
370     /// ```rust
371     /// # let a = 1;
372     /// # let b = 2;
373     ///
374     /// // Bad
375     /// match (a, b) {
376     ///     (c, d) => {
377     ///         // useless match
378     ///     }
379     /// }
380     ///
381     /// // Good
382     /// let (c, d) = (a, b);
383     /// ```
384     pub MATCH_SINGLE_BINDING,
385     complexity,
386     "a match with a single binding instead of using `let` statement"
387 }
388
389 declare_clippy_lint! {
390     /// **What it does:** Checks for unnecessary '..' pattern binding on struct when all fields are explicitly matched.
391     ///
392     /// **Why is this bad?** Correctness and readability. It's like having a wildcard pattern after
393     /// matching all enum variants explicitly.
394     ///
395     /// **Known problems:** None.
396     ///
397     /// **Example:**
398     /// ```rust
399     /// # struct A { a: i32 }
400     /// let a = A { a: 5 };
401     ///
402     /// // Bad
403     /// match a {
404     ///     A { a: 5, .. } => {},
405     ///     _ => {},
406     /// }
407     ///
408     /// // Good
409     /// match a {
410     ///     A { a: 5 } => {},
411     ///     _ => {},
412     /// }
413     /// ```
414     pub REST_PAT_IN_FULLY_BOUND_STRUCTS,
415     restriction,
416     "a match on a struct that binds all fields but still uses the wildcard pattern"
417 }
418
419 declare_clippy_lint! {
420     /// **What it does:** Lint for redundant pattern matching over `Result`, `Option`,
421     /// `std::task::Poll` or `std::net::IpAddr`
422     ///
423     /// **Why is this bad?** It's more concise and clear to just use the proper
424     /// utility function
425     ///
426     /// **Known problems:** This will change the drop order for the matched type. Both `if let` and
427     /// `while let` will drop the value at the end of the block, both `if` and `while` will drop the
428     /// value before entering the block. For most types this change will not matter, but for a few
429     /// types this will not be an acceptable change (e.g. locks). See the
430     /// [reference](https://doc.rust-lang.org/reference/destructors.html#drop-scopes) for more about
431     /// drop order.
432     ///
433     /// **Example:**
434     ///
435     /// ```rust
436     /// # use std::task::Poll;
437     /// # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
438     /// if let Ok(_) = Ok::<i32, i32>(42) {}
439     /// if let Err(_) = Err::<i32, i32>(42) {}
440     /// if let None = None::<()> {}
441     /// if let Some(_) = Some(42) {}
442     /// if let Poll::Pending = Poll::Pending::<()> {}
443     /// if let Poll::Ready(_) = Poll::Ready(42) {}
444     /// if let IpAddr::V4(_) = IpAddr::V4(Ipv4Addr::LOCALHOST) {}
445     /// if let IpAddr::V6(_) = IpAddr::V6(Ipv6Addr::LOCALHOST) {}
446     /// match Ok::<i32, i32>(42) {
447     ///     Ok(_) => true,
448     ///     Err(_) => false,
449     /// };
450     /// ```
451     ///
452     /// The more idiomatic use would be:
453     ///
454     /// ```rust
455     /// # use std::task::Poll;
456     /// # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
457     /// if Ok::<i32, i32>(42).is_ok() {}
458     /// if Err::<i32, i32>(42).is_err() {}
459     /// if None::<()>.is_none() {}
460     /// if Some(42).is_some() {}
461     /// if Poll::Pending::<()>.is_pending() {}
462     /// if Poll::Ready(42).is_ready() {}
463     /// if IpAddr::V4(Ipv4Addr::LOCALHOST).is_ipv4() {}
464     /// if IpAddr::V6(Ipv6Addr::LOCALHOST).is_ipv6() {}
465     /// Ok::<i32, i32>(42).is_ok();
466     /// ```
467     pub REDUNDANT_PATTERN_MATCHING,
468     style,
469     "use the proper utility function avoiding an `if let`"
470 }
471
472 declare_clippy_lint! {
473     /// **What it does:** Checks for `match`  or `if let` expressions producing a
474     /// `bool` that could be written using `matches!`
475     ///
476     /// **Why is this bad?** Readability and needless complexity.
477     ///
478     /// **Known problems:** This lint falsely triggers, if there are arms with
479     /// `cfg` attributes that remove an arm evaluating to `false`.
480     ///
481     /// **Example:**
482     /// ```rust
483     /// let x = Some(5);
484     ///
485     /// // Bad
486     /// let a = match x {
487     ///     Some(0) => true,
488     ///     _ => false,
489     /// };
490     ///
491     /// let a = if let Some(0) = x {
492     ///     true
493     /// } else {
494     ///     false
495     /// };
496     ///
497     /// // Good
498     /// let a = matches!(x, Some(0));
499     /// ```
500     pub MATCH_LIKE_MATCHES_MACRO,
501     style,
502     "a match that could be written with the matches! macro"
503 }
504
505 declare_clippy_lint! {
506     /// **What it does:** Checks for `match` with identical arm bodies.
507     ///
508     /// **Why is this bad?** This is probably a copy & paste error. If arm bodies
509     /// are the same on purpose, you can factor them
510     /// [using `|`](https://doc.rust-lang.org/book/patterns.html#multiple-patterns).
511     ///
512     /// **Known problems:** False positive possible with order dependent `match`
513     /// (see issue
514     /// [#860](https://github.com/rust-lang/rust-clippy/issues/860)).
515     ///
516     /// **Example:**
517     /// ```rust,ignore
518     /// match foo {
519     ///     Bar => bar(),
520     ///     Quz => quz(),
521     ///     Baz => bar(), // <= oops
522     /// }
523     /// ```
524     ///
525     /// This should probably be
526     /// ```rust,ignore
527     /// match foo {
528     ///     Bar => bar(),
529     ///     Quz => quz(),
530     ///     Baz => baz(), // <= fixed
531     /// }
532     /// ```
533     ///
534     /// or if the original code was not a typo:
535     /// ```rust,ignore
536     /// match foo {
537     ///     Bar | Baz => bar(), // <= shows the intent better
538     ///     Quz => quz(),
539     /// }
540     /// ```
541     pub MATCH_SAME_ARMS,
542     pedantic,
543     "`match` with identical arm bodies"
544 }
545
546 #[derive(Default)]
547 pub struct Matches {
548     msrv: Option<RustcVersion>,
549     infallible_destructuring_match_linted: bool,
550 }
551
552 impl Matches {
553     #[must_use]
554     pub fn new(msrv: Option<RustcVersion>) -> Self {
555         Self {
556             msrv,
557             ..Matches::default()
558         }
559     }
560 }
561
562 impl_lint_pass!(Matches => [
563     SINGLE_MATCH,
564     MATCH_REF_PATS,
565     MATCH_BOOL,
566     SINGLE_MATCH_ELSE,
567     MATCH_OVERLAPPING_ARM,
568     MATCH_WILD_ERR_ARM,
569     MATCH_AS_REF,
570     WILDCARD_ENUM_MATCH_ARM,
571     MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
572     WILDCARD_IN_OR_PATTERNS,
573     MATCH_SINGLE_BINDING,
574     INFALLIBLE_DESTRUCTURING_MATCH,
575     REST_PAT_IN_FULLY_BOUND_STRUCTS,
576     REDUNDANT_PATTERN_MATCHING,
577     MATCH_LIKE_MATCHES_MACRO,
578     MATCH_SAME_ARMS,
579 ]);
580
581 const MATCH_LIKE_MATCHES_MACRO_MSRV: RustcVersion = RustcVersion::new(1, 42, 0);
582
583 impl<'tcx> LateLintPass<'tcx> for Matches {
584     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
585         if in_external_macro(cx.sess(), expr.span) || in_macro(expr.span) {
586             return;
587         }
588
589         redundant_pattern_match::check(cx, expr);
590
591         if meets_msrv(self.msrv.as_ref(), &MATCH_LIKE_MATCHES_MACRO_MSRV) {
592             if !check_match_like_matches(cx, expr) {
593                 lint_match_arms(cx, expr);
594             }
595         } else {
596             lint_match_arms(cx, expr);
597         }
598
599         if let ExprKind::Match(ex, arms, MatchSource::Normal) = expr.kind {
600             check_single_match(cx, ex, arms, expr);
601             check_match_bool(cx, ex, arms, expr);
602             check_overlapping_arms(cx, ex, arms);
603             check_wild_err_arm(cx, ex, arms);
604             check_wild_enum_match(cx, ex, arms);
605             check_match_as_ref(cx, ex, arms, expr);
606             check_wild_in_or_pats(cx, arms);
607
608             if self.infallible_destructuring_match_linted {
609                 self.infallible_destructuring_match_linted = false;
610             } else {
611                 check_match_single_binding(cx, ex, arms, expr);
612             }
613         }
614         if let ExprKind::Match(ex, arms, _) = expr.kind {
615             check_match_ref_pats(cx, ex, arms, expr);
616         }
617     }
618
619     fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'_>) {
620         if_chain! {
621             if !in_external_macro(cx.sess(), local.span);
622             if !in_macro(local.span);
623             if let Some(expr) = local.init;
624             if let ExprKind::Match(target, arms, MatchSource::Normal) = expr.kind;
625             if arms.len() == 1 && arms[0].guard.is_none();
626             if let PatKind::TupleStruct(
627                 QPath::Resolved(None, variant_name), args, _) = arms[0].pat.kind;
628             if args.len() == 1;
629             if let PatKind::Binding(_, arg, ..) = strip_pat_refs(args[0]).kind;
630             let body = remove_blocks(arms[0].body);
631             if path_to_local_id(body, arg);
632
633             then {
634                 let mut applicability = Applicability::MachineApplicable;
635                 self.infallible_destructuring_match_linted = true;
636                 span_lint_and_sugg(
637                     cx,
638                     INFALLIBLE_DESTRUCTURING_MATCH,
639                     local.span,
640                     "you seem to be trying to use `match` to destructure a single infallible pattern. \
641                     Consider using `let`",
642                     "try this",
643                     format!(
644                         "let {}({}) = {};",
645                         snippet_with_applicability(cx, variant_name.span, "..", &mut applicability),
646                         snippet_with_applicability(cx, local.pat.span, "..", &mut applicability),
647                         snippet_with_applicability(cx, target.span, "..", &mut applicability),
648                     ),
649                     applicability,
650                 );
651             }
652         }
653     }
654
655     fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) {
656         if_chain! {
657             if !in_external_macro(cx.sess(), pat.span);
658             if !in_macro(pat.span);
659             if let PatKind::Struct(QPath::Resolved(_, path), fields, true) = pat.kind;
660             if let Some(def_id) = path.res.opt_def_id();
661             let ty = cx.tcx.type_of(def_id);
662             if let ty::Adt(def, _) = ty.kind();
663             if def.is_struct() || def.is_union();
664             if fields.len() == def.non_enum_variant().fields.len();
665
666             then {
667                 span_lint_and_help(
668                     cx,
669                     REST_PAT_IN_FULLY_BOUND_STRUCTS,
670                     pat.span,
671                     "unnecessary use of `..` pattern in struct binding. All fields were already bound",
672                     None,
673                     "consider removing `..` from this binding",
674                 );
675             }
676         }
677     }
678
679     extract_msrv_attr!(LateContext);
680 }
681
682 #[rustfmt::skip]
683 fn check_single_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
684     if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
685         if in_macro(expr.span) {
686             // Don't lint match expressions present in
687             // macro_rules! block
688             return;
689         }
690         if let PatKind::Or(..) = arms[0].pat.kind {
691             // don't lint for or patterns for now, this makes
692             // the lint noisy in unnecessary situations
693             return;
694         }
695         let els = arms[1].body;
696         let els = if is_unit_expr(remove_blocks(els)) {
697             None
698         } else if let ExprKind::Block(Block { stmts, expr: block_expr, .. }, _) = els.kind {
699             if stmts.len() == 1 && block_expr.is_none() || stmts.is_empty() && block_expr.is_some() {
700                 // single statement/expr "else" block, don't lint
701                 return;
702             }
703             // block with 2+ statements or 1 expr and 1+ statement
704             Some(els)
705         } else {
706             // not a block, don't lint
707             return;
708         };
709
710         let ty = cx.typeck_results().expr_ty(ex);
711         if *ty.kind() != ty::Bool || is_allowed(cx, MATCH_BOOL, ex.hir_id) {
712             check_single_match_single_pattern(cx, ex, arms, expr, els);
713             check_single_match_opt_like(cx, ex, arms, expr, ty, els);
714         }
715     }
716 }
717
718 fn check_single_match_single_pattern(
719     cx: &LateContext<'_>,
720     ex: &Expr<'_>,
721     arms: &[Arm<'_>],
722     expr: &Expr<'_>,
723     els: Option<&Expr<'_>>,
724 ) {
725     if is_wild(&arms[1].pat) {
726         report_single_match_single_pattern(cx, ex, arms, expr, els);
727     }
728 }
729
730 fn report_single_match_single_pattern(
731     cx: &LateContext<'_>,
732     ex: &Expr<'_>,
733     arms: &[Arm<'_>],
734     expr: &Expr<'_>,
735     els: Option<&Expr<'_>>,
736 ) {
737     let lint = if els.is_some() { SINGLE_MATCH_ELSE } else { SINGLE_MATCH };
738     let els_str = els.map_or(String::new(), |els| {
739         format!(" else {}", expr_block(cx, els, None, "..", Some(expr.span)))
740     });
741
742     let (pat, pat_ref_count) = peel_hir_pat_refs(arms[0].pat);
743     let (msg, sugg) = if_chain! {
744         if let PatKind::Path(_) | PatKind::Lit(_) = pat.kind;
745         let (ty, ty_ref_count) = peel_mid_ty_refs(cx.typeck_results().expr_ty(ex));
746         if let Some(spe_trait_id) = cx.tcx.lang_items().structural_peq_trait();
747         if let Some(pe_trait_id) = cx.tcx.lang_items().eq_trait();
748         if ty.is_integral() || ty.is_char() || ty.is_str()
749             || (implements_trait(cx, ty, spe_trait_id, &[])
750                 && implements_trait(cx, ty, pe_trait_id, &[ty.into()]));
751         then {
752             // scrutinee derives PartialEq and the pattern is a constant.
753             let pat_ref_count = match pat.kind {
754                 // string literals are already a reference.
755                 PatKind::Lit(Expr { kind: ExprKind::Lit(lit), .. }) if lit.node.is_str() => pat_ref_count + 1,
756                 _ => pat_ref_count,
757             };
758             // References are only implicitly added to the pattern, so no overflow here.
759             // e.g. will work: match &Some(_) { Some(_) => () }
760             // will not: match Some(_) { &Some(_) => () }
761             let ref_count_diff = ty_ref_count - pat_ref_count;
762
763             // Try to remove address of expressions first.
764             let (ex, removed) = peel_n_hir_expr_refs(ex, ref_count_diff);
765             let ref_count_diff = ref_count_diff - removed;
766
767             let msg = "you seem to be trying to use `match` for an equality check. Consider using `if`";
768             let sugg = format!(
769                 "if {} == {}{} {}{}",
770                 snippet(cx, ex.span, ".."),
771                 // PartialEq for different reference counts may not exist.
772                 "&".repeat(ref_count_diff),
773                 snippet(cx, arms[0].pat.span, ".."),
774                 expr_block(cx, arms[0].body, None, "..", Some(expr.span)),
775                 els_str,
776             );
777             (msg, sugg)
778         } else {
779             let msg = "you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let`";
780             let sugg = format!(
781                 "if let {} = {} {}{}",
782                 snippet(cx, arms[0].pat.span, ".."),
783                 snippet(cx, ex.span, ".."),
784                 expr_block(cx, arms[0].body, None, "..", Some(expr.span)),
785                 els_str,
786             );
787             (msg, sugg)
788         }
789     };
790
791     span_lint_and_sugg(
792         cx,
793         lint,
794         expr.span,
795         msg,
796         "try this",
797         sugg,
798         Applicability::HasPlaceholders,
799     );
800 }
801
802 fn check_single_match_opt_like(
803     cx: &LateContext<'_>,
804     ex: &Expr<'_>,
805     arms: &[Arm<'_>],
806     expr: &Expr<'_>,
807     ty: Ty<'_>,
808     els: Option<&Expr<'_>>,
809 ) {
810     // list of candidate `Enum`s we know will never get any more members
811     let candidates = &[
812         (&paths::COW, "Borrowed"),
813         (&paths::COW, "Cow::Borrowed"),
814         (&paths::COW, "Cow::Owned"),
815         (&paths::COW, "Owned"),
816         (&paths::OPTION, "None"),
817         (&paths::RESULT, "Err"),
818         (&paths::RESULT, "Ok"),
819     ];
820
821     let path = match arms[1].pat.kind {
822         PatKind::TupleStruct(ref path, inner, _) => {
823             // Contains any non wildcard patterns (e.g., `Err(err)`)?
824             if !inner.iter().all(is_wild) {
825                 return;
826             }
827             rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false))
828         },
829         PatKind::Binding(BindingAnnotation::Unannotated, .., ident, None) => ident.to_string(),
830         PatKind::Path(ref path) => {
831             rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false))
832         },
833         _ => return,
834     };
835
836     for &(ty_path, pat_path) in candidates {
837         if path == *pat_path && match_type(cx, ty, ty_path) {
838             report_single_match_single_pattern(cx, ex, arms, expr, els);
839         }
840     }
841 }
842
843 fn check_match_bool(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
844     // Type of expression is `bool`.
845     if *cx.typeck_results().expr_ty(ex).kind() == ty::Bool {
846         span_lint_and_then(
847             cx,
848             MATCH_BOOL,
849             expr.span,
850             "you seem to be trying to match on a boolean expression",
851             move |diag| {
852                 if arms.len() == 2 {
853                     // no guards
854                     let exprs = if let PatKind::Lit(arm_bool) = arms[0].pat.kind {
855                         if let ExprKind::Lit(ref lit) = arm_bool.kind {
856                             match lit.node {
857                                 LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
858                                 LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
859                                 _ => None,
860                             }
861                         } else {
862                             None
863                         }
864                     } else {
865                         None
866                     };
867
868                     if let Some((true_expr, false_expr)) = exprs {
869                         let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
870                             (false, false) => Some(format!(
871                                 "if {} {} else {}",
872                                 snippet(cx, ex.span, "b"),
873                                 expr_block(cx, true_expr, None, "..", Some(expr.span)),
874                                 expr_block(cx, false_expr, None, "..", Some(expr.span))
875                             )),
876                             (false, true) => Some(format!(
877                                 "if {} {}",
878                                 snippet(cx, ex.span, "b"),
879                                 expr_block(cx, true_expr, None, "..", Some(expr.span))
880                             )),
881                             (true, false) => {
882                                 let test = Sugg::hir(cx, ex, "..");
883                                 Some(format!(
884                                     "if {} {}",
885                                     !test,
886                                     expr_block(cx, false_expr, None, "..", Some(expr.span))
887                                 ))
888                             },
889                             (true, true) => None,
890                         };
891
892                         if let Some(sugg) = sugg {
893                             diag.span_suggestion(
894                                 expr.span,
895                                 "consider using an `if`/`else` expression",
896                                 sugg,
897                                 Applicability::HasPlaceholders,
898                             );
899                         }
900                     }
901                 }
902             },
903         );
904     }
905 }
906
907 fn check_overlapping_arms<'tcx>(cx: &LateContext<'tcx>, ex: &'tcx Expr<'_>, arms: &'tcx [Arm<'_>]) {
908     if arms.len() >= 2 && cx.typeck_results().expr_ty(ex).is_integral() {
909         let ranges = all_ranges(cx, arms, cx.typeck_results().expr_ty(ex));
910         let type_ranges = type_ranges(&ranges);
911         if !type_ranges.is_empty() {
912             if let Some((start, end)) = overlapping(&type_ranges) {
913                 span_lint_and_note(
914                     cx,
915                     MATCH_OVERLAPPING_ARM,
916                     start.span,
917                     "some ranges overlap",
918                     Some(end.span),
919                     "overlaps with this",
920                 );
921             }
922         }
923     }
924 }
925
926 fn check_wild_err_arm<'tcx>(cx: &LateContext<'tcx>, ex: &Expr<'tcx>, arms: &[Arm<'tcx>]) {
927     let ex_ty = cx.typeck_results().expr_ty(ex).peel_refs();
928     if is_type_diagnostic_item(cx, ex_ty, sym::result_type) {
929         for arm in arms {
930             if let PatKind::TupleStruct(ref path, inner, _) = arm.pat.kind {
931                 let path_str = rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false));
932                 if path_str == "Err" {
933                     let mut matching_wild = inner.iter().any(is_wild);
934                     let mut ident_bind_name = String::from("_");
935                     if !matching_wild {
936                         // Looking for unused bindings (i.e.: `_e`)
937                         for pat in inner.iter() {
938                             if let PatKind::Binding(_, id, ident, None) = pat.kind {
939                                 if ident.as_str().starts_with('_')
940                                     && !LocalUsedVisitor::new(cx, id).check_expr(arm.body)
941                                 {
942                                     ident_bind_name = (&ident.name.as_str()).to_string();
943                                     matching_wild = true;
944                                 }
945                             }
946                         }
947                     }
948                     if_chain! {
949                         if matching_wild;
950                         if let ExprKind::Block(block, _) = arm.body.kind;
951                         if is_panic_block(block);
952                         then {
953                             // `Err(_)` or `Err(_e)` arm with `panic!` found
954                             span_lint_and_note(cx,
955                                 MATCH_WILD_ERR_ARM,
956                                 arm.pat.span,
957                                 &format!("`Err({})` matches all errors", &ident_bind_name),
958                                 None,
959                                 "match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable",
960                             );
961                         }
962                     }
963                 }
964             }
965         }
966     }
967 }
968
969 enum CommonPrefixSearcher<'a> {
970     None,
971     Path(&'a [PathSegment<'a>]),
972     Mixed,
973 }
974 impl CommonPrefixSearcher<'a> {
975     fn with_path(&mut self, path: &'a [PathSegment<'a>]) {
976         match path {
977             [path @ .., _] => self.with_prefix(path),
978             [] => (),
979         }
980     }
981
982     fn with_prefix(&mut self, path: &'a [PathSegment<'a>]) {
983         match self {
984             Self::None => *self = Self::Path(path),
985             Self::Path(self_path)
986                 if path
987                     .iter()
988                     .map(|p| p.ident.name)
989                     .eq(self_path.iter().map(|p| p.ident.name)) => {},
990             Self::Path(_) => *self = Self::Mixed,
991             Self::Mixed => (),
992         }
993     }
994 }
995
996 fn is_doc_hidden(cx: &LateContext<'_>, variant_def: &VariantDef) -> bool {
997     let attrs = cx.tcx.get_attrs(variant_def.def_id);
998     clippy_utils::attrs::is_doc_hidden(attrs)
999 }
1000
1001 #[allow(clippy::too_many_lines)]
1002 fn check_wild_enum_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>]) {
1003     let ty = cx.typeck_results().expr_ty(ex).peel_refs();
1004     let adt_def = match ty.kind() {
1005         ty::Adt(adt_def, _)
1006             if adt_def.is_enum()
1007                 && !(is_type_diagnostic_item(cx, ty, sym::option_type)
1008                     || is_type_diagnostic_item(cx, ty, sym::result_type)) =>
1009         {
1010             adt_def
1011         },
1012         _ => return,
1013     };
1014
1015     // First pass - check for violation, but don't do much book-keeping because this is hopefully
1016     // the uncommon case, and the book-keeping is slightly expensive.
1017     let mut wildcard_span = None;
1018     let mut wildcard_ident = None;
1019     let mut has_non_wild = false;
1020     for arm in arms {
1021         match peel_hir_pat_refs(arm.pat).0.kind {
1022             PatKind::Wild => wildcard_span = Some(arm.pat.span),
1023             PatKind::Binding(_, _, ident, None) => {
1024                 wildcard_span = Some(arm.pat.span);
1025                 wildcard_ident = Some(ident);
1026             },
1027             _ => has_non_wild = true,
1028         }
1029     }
1030     let wildcard_span = match wildcard_span {
1031         Some(x) if has_non_wild => x,
1032         _ => return,
1033     };
1034
1035     // Accumulate the variants which should be put in place of the wildcard because they're not
1036     // already covered.
1037     let mut missing_variants: Vec<_> = adt_def.variants.iter().collect();
1038
1039     let mut path_prefix = CommonPrefixSearcher::None;
1040     for arm in arms {
1041         // Guards mean that this case probably isn't exhaustively covered. Technically
1042         // this is incorrect, as we should really check whether each variant is exhaustively
1043         // covered by the set of guards that cover it, but that's really hard to do.
1044         recurse_or_patterns(arm.pat, |pat| {
1045             let path = match &peel_hir_pat_refs(pat).0.kind {
1046                 PatKind::Path(path) => {
1047                     #[allow(clippy::match_same_arms)]
1048                     let id = match cx.qpath_res(path, pat.hir_id) {
1049                         Res::Def(DefKind::Const | DefKind::ConstParam | DefKind::AnonConst, _) => return,
1050                         Res::Def(_, id) => id,
1051                         _ => return,
1052                     };
1053                     if arm.guard.is_none() {
1054                         missing_variants.retain(|e| e.ctor_def_id != Some(id));
1055                     }
1056                     path
1057                 },
1058                 PatKind::TupleStruct(path, patterns, ..) => {
1059                     if let Some(id) = cx.qpath_res(path, pat.hir_id).opt_def_id() {
1060                         if arm.guard.is_none() && patterns.iter().all(|p| !is_refutable(cx, p)) {
1061                             missing_variants.retain(|e| e.ctor_def_id != Some(id));
1062                         }
1063                     }
1064                     path
1065                 },
1066                 PatKind::Struct(path, patterns, ..) => {
1067                     if let Some(id) = cx.qpath_res(path, pat.hir_id).opt_def_id() {
1068                         if arm.guard.is_none() && patterns.iter().all(|p| !is_refutable(cx, p.pat)) {
1069                             missing_variants.retain(|e| e.def_id != id);
1070                         }
1071                     }
1072                     path
1073                 },
1074                 _ => return,
1075             };
1076             match path {
1077                 QPath::Resolved(_, path) => path_prefix.with_path(path.segments),
1078                 QPath::TypeRelative(
1079                     hir::Ty {
1080                         kind: TyKind::Path(QPath::Resolved(_, path)),
1081                         ..
1082                     },
1083                     _,
1084                 ) => path_prefix.with_prefix(path.segments),
1085                 _ => (),
1086             }
1087         });
1088     }
1089
1090     let format_suggestion = |variant: &VariantDef| {
1091         format!(
1092             "{}{}{}{}",
1093             if let Some(ident) = wildcard_ident {
1094                 format!("{} @ ", ident.name)
1095             } else {
1096                 String::new()
1097             },
1098             if let CommonPrefixSearcher::Path(path_prefix) = path_prefix {
1099                 let mut s = String::new();
1100                 for seg in path_prefix {
1101                     s.push_str(&seg.ident.as_str());
1102                     s.push_str("::");
1103                 }
1104                 s
1105             } else {
1106                 let mut s = cx.tcx.def_path_str(adt_def.did);
1107                 s.push_str("::");
1108                 s
1109             },
1110             variant.ident.name,
1111             match variant.ctor_kind {
1112                 CtorKind::Fn if variant.fields.len() == 1 => "(_)",
1113                 CtorKind::Fn => "(..)",
1114                 CtorKind::Const => "",
1115                 CtorKind::Fictive => "{ .. }",
1116             }
1117         )
1118     };
1119
1120     match missing_variants.as_slice() {
1121         [] => (),
1122         [x] if !adt_def.is_variant_list_non_exhaustive() && !is_doc_hidden(cx, x) => span_lint_and_sugg(
1123             cx,
1124             MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
1125             wildcard_span,
1126             "wildcard matches only a single variant and will also match any future added variants",
1127             "try this",
1128             format_suggestion(x),
1129             Applicability::MaybeIncorrect,
1130         ),
1131         variants => {
1132             let mut suggestions: Vec<_> = variants.iter().copied().map(format_suggestion).collect();
1133             let message = if adt_def.is_variant_list_non_exhaustive() {
1134                 suggestions.push("_".into());
1135                 "wildcard matches known variants and will also match future added variants"
1136             } else {
1137                 "wildcard match will also match any future added variants"
1138             };
1139
1140             span_lint_and_sugg(
1141                 cx,
1142                 WILDCARD_ENUM_MATCH_ARM,
1143                 wildcard_span,
1144                 message,
1145                 "try this",
1146                 suggestions.join(" | "),
1147                 Applicability::MaybeIncorrect,
1148             )
1149         },
1150     };
1151 }
1152
1153 // If the block contains only a `panic!` macro (as expression or statement)
1154 fn is_panic_block(block: &Block<'_>) -> bool {
1155     match (&block.expr, block.stmts.len(), block.stmts.first()) {
1156         (&Some(exp), 0, _) => is_expn_of(exp.span, "panic").is_some() && is_expn_of(exp.span, "unreachable").is_none(),
1157         (&None, 1, Some(stmt)) => {
1158             is_expn_of(stmt.span, "panic").is_some() && is_expn_of(stmt.span, "unreachable").is_none()
1159         },
1160         _ => false,
1161     }
1162 }
1163
1164 fn check_match_ref_pats(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1165     if has_only_ref_pats(arms) {
1166         let mut suggs = Vec::with_capacity(arms.len() + 1);
1167         let (title, msg) = if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, inner) = ex.kind {
1168             let span = ex.span.source_callsite();
1169             suggs.push((span, Sugg::hir_with_macro_callsite(cx, inner, "..").to_string()));
1170             (
1171                 "you don't need to add `&` to both the expression and the patterns",
1172                 "try",
1173             )
1174         } else {
1175             let span = ex.span.source_callsite();
1176             suggs.push((span, Sugg::hir_with_macro_callsite(cx, ex, "..").deref().to_string()));
1177             (
1178                 "you don't need to add `&` to all patterns",
1179                 "instead of prefixing all patterns with `&`, you can dereference the expression",
1180             )
1181         };
1182
1183         suggs.extend(arms.iter().filter_map(|a| {
1184             if let PatKind::Ref(refp, _) = a.pat.kind {
1185                 Some((a.pat.span, snippet(cx, refp.span, "..").to_string()))
1186             } else {
1187                 None
1188             }
1189         }));
1190
1191         span_lint_and_then(cx, MATCH_REF_PATS, expr.span, title, |diag| {
1192             if !expr.span.from_expansion() {
1193                 multispan_sugg(diag, msg, suggs);
1194             }
1195         });
1196     }
1197 }
1198
1199 fn check_match_as_ref(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1200     if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
1201         let arm_ref: Option<BindingAnnotation> = if is_none_arm(cx, &arms[0]) {
1202             is_ref_some_arm(cx, &arms[1])
1203         } else if is_none_arm(cx, &arms[1]) {
1204             is_ref_some_arm(cx, &arms[0])
1205         } else {
1206             None
1207         };
1208         if let Some(rb) = arm_ref {
1209             let suggestion = if rb == BindingAnnotation::Ref {
1210                 "as_ref"
1211             } else {
1212                 "as_mut"
1213             };
1214
1215             let output_ty = cx.typeck_results().expr_ty(expr);
1216             let input_ty = cx.typeck_results().expr_ty(ex);
1217
1218             let cast = if_chain! {
1219                 if let ty::Adt(_, substs) = input_ty.kind();
1220                 let input_ty = substs.type_at(0);
1221                 if let ty::Adt(_, substs) = output_ty.kind();
1222                 let output_ty = substs.type_at(0);
1223                 if let ty::Ref(_, output_ty, _) = *output_ty.kind();
1224                 if input_ty != output_ty;
1225                 then {
1226                     ".map(|x| x as _)"
1227                 } else {
1228                     ""
1229                 }
1230             };
1231
1232             let mut applicability = Applicability::MachineApplicable;
1233             span_lint_and_sugg(
1234                 cx,
1235                 MATCH_AS_REF,
1236                 expr.span,
1237                 &format!("use `{}()` instead", suggestion),
1238                 "try this",
1239                 format!(
1240                     "{}.{}(){}",
1241                     snippet_with_applicability(cx, ex.span, "_", &mut applicability),
1242                     suggestion,
1243                     cast,
1244                 ),
1245                 applicability,
1246             )
1247         }
1248     }
1249 }
1250
1251 fn check_wild_in_or_pats(cx: &LateContext<'_>, arms: &[Arm<'_>]) {
1252     for arm in arms {
1253         if let PatKind::Or(fields) = arm.pat.kind {
1254             // look for multiple fields in this arm that contains at least one Wild pattern
1255             if fields.len() > 1 && fields.iter().any(is_wild) {
1256                 span_lint_and_help(
1257                     cx,
1258                     WILDCARD_IN_OR_PATTERNS,
1259                     arm.pat.span,
1260                     "wildcard pattern covers any other pattern as it will match anyway",
1261                     None,
1262                     "consider handling `_` separately",
1263                 );
1264             }
1265         }
1266     }
1267 }
1268
1269 /// Lint a `match` or `if let .. { .. } else { .. }` expr that could be replaced by `matches!`
1270 fn check_match_like_matches<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
1271     if let ExprKind::Match(ex, arms, ref match_source) = &expr.kind {
1272         match match_source {
1273             MatchSource::Normal => find_matches_sugg(cx, ex, arms, expr, false),
1274             MatchSource::IfLetDesugar { .. } => find_matches_sugg(cx, ex, arms, expr, true),
1275             _ => false,
1276         }
1277     } else {
1278         false
1279     }
1280 }
1281
1282 /// Lint a `match` or desugared `if let` for replacement by `matches!`
1283 fn find_matches_sugg(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>, desugared: bool) -> bool {
1284     if_chain! {
1285         if arms.len() >= 2;
1286         if cx.typeck_results().expr_ty(expr).is_bool();
1287         if let Some((b1_arm, b0_arms)) = arms.split_last();
1288         if let Some(b0) = find_bool_lit(&b0_arms[0].body.kind, desugared);
1289         if let Some(b1) = find_bool_lit(&b1_arm.body.kind, desugared);
1290         if is_wild(&b1_arm.pat);
1291         if b0 != b1;
1292         let if_guard = &b0_arms[0].guard;
1293         if if_guard.is_none() || b0_arms.len() == 1;
1294         if cx.tcx.hir().attrs(b0_arms[0].hir_id).is_empty();
1295         if b0_arms[1..].iter()
1296             .all(|arm| {
1297                 find_bool_lit(&arm.body.kind, desugared).map_or(false, |b| b == b0) &&
1298                 arm.guard.is_none() && cx.tcx.hir().attrs(arm.hir_id).is_empty()
1299             });
1300         then {
1301             // The suggestion may be incorrect, because some arms can have `cfg` attributes
1302             // evaluated into `false` and so such arms will be stripped before.
1303             let mut applicability = Applicability::MaybeIncorrect;
1304             let pat = {
1305                 use itertools::Itertools as _;
1306                 b0_arms.iter()
1307                     .map(|arm| snippet_with_applicability(cx, arm.pat.span, "..", &mut applicability))
1308                     .join(" | ")
1309             };
1310             let pat_and_guard = if let Some(Guard::If(g)) = if_guard {
1311                 format!("{} if {}", pat, snippet_with_applicability(cx, g.span, "..", &mut applicability))
1312             } else {
1313                 pat
1314             };
1315
1316             // strip potential borrows (#6503), but only if the type is a reference
1317             let mut ex_new = ex;
1318             if let ExprKind::AddrOf(BorrowKind::Ref, .., ex_inner) = ex.kind {
1319                 if let ty::Ref(..) = cx.typeck_results().expr_ty(ex_inner).kind() {
1320                     ex_new = ex_inner;
1321                 }
1322             };
1323             span_lint_and_sugg(
1324                 cx,
1325                 MATCH_LIKE_MATCHES_MACRO,
1326                 expr.span,
1327                 &format!("{} expression looks like `matches!` macro", if desugared { "if let .. else" } else { "match" }),
1328                 "try this",
1329                 format!(
1330                     "{}matches!({}, {})",
1331                     if b0 { "" } else { "!" },
1332                     snippet_with_applicability(cx, ex_new.span, "..", &mut applicability),
1333                     pat_and_guard,
1334                 ),
1335                 applicability,
1336             );
1337             true
1338         } else {
1339             false
1340         }
1341     }
1342 }
1343
1344 /// Extract a `bool` or `{ bool }`
1345 fn find_bool_lit(ex: &ExprKind<'_>, desugared: bool) -> Option<bool> {
1346     match ex {
1347         ExprKind::Lit(Spanned {
1348             node: LitKind::Bool(b), ..
1349         }) => Some(*b),
1350         ExprKind::Block(
1351             rustc_hir::Block {
1352                 stmts: &[],
1353                 expr: Some(exp),
1354                 ..
1355             },
1356             _,
1357         ) if desugared => {
1358             if let ExprKind::Lit(Spanned {
1359                 node: LitKind::Bool(b), ..
1360             }) = exp.kind
1361             {
1362                 Some(b)
1363             } else {
1364                 None
1365             }
1366         },
1367         _ => None,
1368     }
1369 }
1370
1371 #[allow(clippy::too_many_lines)]
1372 fn check_match_single_binding<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1373     if in_macro(expr.span) || arms.len() != 1 || is_refutable(cx, arms[0].pat) {
1374         return;
1375     }
1376
1377     // HACK:
1378     // This is a hack to deal with arms that are excluded by macros like `#[cfg]`. It is only used here
1379     // to prevent false positives as there is currently no better way to detect if code was excluded by
1380     // a macro. See PR #6435
1381     if_chain! {
1382         if let Some(match_snippet) = snippet_opt(cx, expr.span);
1383         if let Some(arm_snippet) = snippet_opt(cx, arms[0].span);
1384         if let Some(ex_snippet) = snippet_opt(cx, ex.span);
1385         let rest_snippet = match_snippet.replace(&arm_snippet, "").replace(&ex_snippet, "");
1386         if rest_snippet.contains("=>");
1387         then {
1388             // The code it self contains another thick arrow "=>"
1389             // -> Either another arm or a comment
1390             return;
1391         }
1392     }
1393
1394     let matched_vars = ex.span;
1395     let bind_names = arms[0].pat.span;
1396     let match_body = remove_blocks(arms[0].body);
1397     let mut snippet_body = if match_body.span.from_expansion() {
1398         Sugg::hir_with_macro_callsite(cx, match_body, "..").to_string()
1399     } else {
1400         snippet_block(cx, match_body.span, "..", Some(expr.span)).to_string()
1401     };
1402
1403     // Do we need to add ';' to suggestion ?
1404     match match_body.kind {
1405         ExprKind::Block(block, _) => {
1406             // macro + expr_ty(body) == ()
1407             if block.span.from_expansion() && cx.typeck_results().expr_ty(match_body).is_unit() {
1408                 snippet_body.push(';');
1409             }
1410         },
1411         _ => {
1412             // expr_ty(body) == ()
1413             if cx.typeck_results().expr_ty(match_body).is_unit() {
1414                 snippet_body.push(';');
1415             }
1416         },
1417     }
1418
1419     let mut applicability = Applicability::MaybeIncorrect;
1420     match arms[0].pat.kind {
1421         PatKind::Binding(..) | PatKind::Tuple(_, _) | PatKind::Struct(..) => {
1422             // If this match is in a local (`let`) stmt
1423             let (target_span, sugg) = if let Some(parent_let_node) = opt_parent_let(cx, ex) {
1424                 (
1425                     parent_let_node.span,
1426                     format!(
1427                         "let {} = {};\n{}let {} = {};",
1428                         snippet_with_applicability(cx, bind_names, "..", &mut applicability),
1429                         snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
1430                         " ".repeat(indent_of(cx, expr.span).unwrap_or(0)),
1431                         snippet_with_applicability(cx, parent_let_node.pat.span, "..", &mut applicability),
1432                         snippet_body
1433                     ),
1434                 )
1435             } else {
1436                 // If we are in closure, we need curly braces around suggestion
1437                 let mut indent = " ".repeat(indent_of(cx, ex.span).unwrap_or(0));
1438                 let (mut cbrace_start, mut cbrace_end) = ("".to_string(), "".to_string());
1439                 if let Some(parent_expr) = get_parent_expr(cx, expr) {
1440                     if let ExprKind::Closure(..) = parent_expr.kind {
1441                         cbrace_end = format!("\n{}}}", indent);
1442                         // Fix body indent due to the closure
1443                         indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0));
1444                         cbrace_start = format!("{{\n{}", indent);
1445                     }
1446                 }
1447                 // If the parent is already an arm, and the body is another match statement,
1448                 // we need curly braces around suggestion
1449                 let parent_node_id = cx.tcx.hir().get_parent_node(expr.hir_id);
1450                 if let Node::Arm(arm) = &cx.tcx.hir().get(parent_node_id) {
1451                     if let ExprKind::Match(..) = arm.body.kind {
1452                         cbrace_end = format!("\n{}}}", indent);
1453                         // Fix body indent due to the match
1454                         indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0));
1455                         cbrace_start = format!("{{\n{}", indent);
1456                     }
1457                 }
1458                 (
1459                     expr.span,
1460                     format!(
1461                         "{}let {} = {};\n{}{}{}",
1462                         cbrace_start,
1463                         snippet_with_applicability(cx, bind_names, "..", &mut applicability),
1464                         snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
1465                         indent,
1466                         snippet_body,
1467                         cbrace_end
1468                     ),
1469                 )
1470             };
1471             span_lint_and_sugg(
1472                 cx,
1473                 MATCH_SINGLE_BINDING,
1474                 target_span,
1475                 "this match could be written as a `let` statement",
1476                 "consider using `let` statement",
1477                 sugg,
1478                 applicability,
1479             );
1480         },
1481         PatKind::Wild => {
1482             span_lint_and_sugg(
1483                 cx,
1484                 MATCH_SINGLE_BINDING,
1485                 expr.span,
1486                 "this match could be replaced by its body itself",
1487                 "consider using the match body instead",
1488                 snippet_body,
1489                 Applicability::MachineApplicable,
1490             );
1491         },
1492         _ => (),
1493     }
1494 }
1495
1496 /// Returns true if the `ex` match expression is in a local (`let`) statement
1497 fn opt_parent_let<'a>(cx: &LateContext<'a>, ex: &Expr<'a>) -> Option<&'a Local<'a>> {
1498     let map = &cx.tcx.hir();
1499     if_chain! {
1500         if let Some(Node::Expr(parent_arm_expr)) = map.find(map.get_parent_node(ex.hir_id));
1501         if let Some(Node::Local(parent_let_expr)) = map.find(map.get_parent_node(parent_arm_expr.hir_id));
1502         then {
1503             return Some(parent_let_expr);
1504         }
1505     }
1506     None
1507 }
1508
1509 /// Gets all arms that are unbounded `PatRange`s.
1510 fn all_ranges<'tcx>(cx: &LateContext<'tcx>, arms: &'tcx [Arm<'_>], ty: Ty<'tcx>) -> Vec<SpannedRange<Constant>> {
1511     arms.iter()
1512         .filter_map(|arm| {
1513             if let Arm { pat, guard: None, .. } = *arm {
1514                 if let PatKind::Range(ref lhs, ref rhs, range_end) = pat.kind {
1515                     let lhs = match lhs {
1516                         Some(lhs) => constant(cx, cx.typeck_results(), lhs)?.0,
1517                         None => miri_to_const(ty.numeric_min_val(cx.tcx)?)?,
1518                     };
1519                     let rhs = match rhs {
1520                         Some(rhs) => constant(cx, cx.typeck_results(), rhs)?.0,
1521                         None => miri_to_const(ty.numeric_max_val(cx.tcx)?)?,
1522                     };
1523                     let rhs = match range_end {
1524                         RangeEnd::Included => Bound::Included(rhs),
1525                         RangeEnd::Excluded => Bound::Excluded(rhs),
1526                     };
1527                     return Some(SpannedRange {
1528                         span: pat.span,
1529                         node: (lhs, rhs),
1530                     });
1531                 }
1532
1533                 if let PatKind::Lit(value) = pat.kind {
1534                     let value = constant(cx, cx.typeck_results(), value)?.0;
1535                     return Some(SpannedRange {
1536                         span: pat.span,
1537                         node: (value.clone(), Bound::Included(value)),
1538                     });
1539                 }
1540             }
1541             None
1542         })
1543         .collect()
1544 }
1545
1546 #[derive(Debug, Eq, PartialEq)]
1547 pub struct SpannedRange<T> {
1548     pub span: Span,
1549     pub node: (T, Bound<T>),
1550 }
1551
1552 type TypedRanges = Vec<SpannedRange<u128>>;
1553
1554 /// Gets all `Int` ranges or all `Uint` ranges. Mixed types are an error anyway
1555 /// and other types than
1556 /// `Uint` and `Int` probably don't make sense.
1557 fn type_ranges(ranges: &[SpannedRange<Constant>]) -> TypedRanges {
1558     ranges
1559         .iter()
1560         .filter_map(|range| match range.node {
1561             (Constant::Int(start), Bound::Included(Constant::Int(end))) => Some(SpannedRange {
1562                 span: range.span,
1563                 node: (start, Bound::Included(end)),
1564             }),
1565             (Constant::Int(start), Bound::Excluded(Constant::Int(end))) => Some(SpannedRange {
1566                 span: range.span,
1567                 node: (start, Bound::Excluded(end)),
1568             }),
1569             (Constant::Int(start), Bound::Unbounded) => Some(SpannedRange {
1570                 span: range.span,
1571                 node: (start, Bound::Unbounded),
1572             }),
1573             _ => None,
1574         })
1575         .collect()
1576 }
1577
1578 fn is_unit_expr(expr: &Expr<'_>) -> bool {
1579     match expr.kind {
1580         ExprKind::Tup(v) if v.is_empty() => true,
1581         ExprKind::Block(b, _) if b.stmts.is_empty() && b.expr.is_none() => true,
1582         _ => false,
1583     }
1584 }
1585
1586 // Checks if arm has the form `None => None`
1587 fn is_none_arm(cx: &LateContext<'_>, arm: &Arm<'_>) -> bool {
1588     matches!(arm.pat.kind, PatKind::Path(ref qpath) if is_lang_ctor(cx, qpath, OptionNone))
1589 }
1590
1591 // Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`)
1592 fn is_ref_some_arm(cx: &LateContext<'_>, arm: &Arm<'_>) -> Option<BindingAnnotation> {
1593     if_chain! {
1594         if let PatKind::TupleStruct(ref qpath, pats, _) = arm.pat.kind;
1595         if is_lang_ctor(cx, qpath, OptionSome);
1596         if let PatKind::Binding(rb, .., ident, _) = pats[0].kind;
1597         if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
1598         if let ExprKind::Call(e, args) = remove_blocks(arm.body).kind;
1599         if let ExprKind::Path(ref some_path) = e.kind;
1600         if is_lang_ctor(cx, some_path, OptionSome) && args.len() == 1;
1601         if let ExprKind::Path(QPath::Resolved(_, path2)) = args[0].kind;
1602         if path2.segments.len() == 1 && ident.name == path2.segments[0].ident.name;
1603         then {
1604             return Some(rb)
1605         }
1606     }
1607     None
1608 }
1609
1610 fn has_only_ref_pats(arms: &[Arm<'_>]) -> bool {
1611     let mapped = arms
1612         .iter()
1613         .map(|a| {
1614             match a.pat.kind {
1615                 PatKind::Ref(..) => Some(true), // &-patterns
1616                 PatKind::Wild => Some(false),   // an "anything" wildcard is also fine
1617                 _ => None,                      // any other pattern is not fine
1618             }
1619         })
1620         .collect::<Option<Vec<bool>>>();
1621     // look for Some(v) where there's at least one true element
1622     mapped.map_or(false, |v| v.iter().any(|el| *el))
1623 }
1624
1625 pub fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
1626 where
1627     T: Copy + Ord,
1628 {
1629     #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1630     enum Kind<'a, T> {
1631         Start(T, &'a SpannedRange<T>),
1632         End(Bound<T>, &'a SpannedRange<T>),
1633     }
1634
1635     impl<'a, T: Copy> Kind<'a, T> {
1636         fn range(&self) -> &'a SpannedRange<T> {
1637             match *self {
1638                 Kind::Start(_, r) | Kind::End(_, r) => r,
1639             }
1640         }
1641
1642         fn value(self) -> Bound<T> {
1643             match self {
1644                 Kind::Start(t, _) => Bound::Included(t),
1645                 Kind::End(t, _) => t,
1646             }
1647         }
1648     }
1649
1650     impl<'a, T: Copy + Ord> PartialOrd for Kind<'a, T> {
1651         fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1652             Some(self.cmp(other))
1653         }
1654     }
1655
1656     impl<'a, T: Copy + Ord> Ord for Kind<'a, T> {
1657         fn cmp(&self, other: &Self) -> Ordering {
1658             match (self.value(), other.value()) {
1659                 (Bound::Included(a), Bound::Included(b)) | (Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
1660                 // Range patterns cannot be unbounded (yet)
1661                 (Bound::Unbounded, _) | (_, Bound::Unbounded) => unimplemented!(),
1662                 (Bound::Included(a), Bound::Excluded(b)) => match a.cmp(&b) {
1663                     Ordering::Equal => Ordering::Greater,
1664                     other => other,
1665                 },
1666                 (Bound::Excluded(a), Bound::Included(b)) => match a.cmp(&b) {
1667                     Ordering::Equal => Ordering::Less,
1668                     other => other,
1669                 },
1670             }
1671         }
1672     }
1673
1674     let mut values = Vec::with_capacity(2 * ranges.len());
1675
1676     for r in ranges {
1677         values.push(Kind::Start(r.node.0, r));
1678         values.push(Kind::End(r.node.1, r));
1679     }
1680
1681     values.sort();
1682
1683     for (a, b) in iter::zip(&values, values.iter().skip(1)) {
1684         match (a, b) {
1685             (&Kind::Start(_, ra), &Kind::End(_, rb)) => {
1686                 if ra.node != rb.node {
1687                     return Some((ra, rb));
1688                 }
1689             },
1690             (&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (),
1691             _ => {
1692                 // skip if the range `a` is completely included into the range `b`
1693                 if let Ordering::Equal | Ordering::Less = a.cmp(b) {
1694                     let kind_a = Kind::End(a.range().node.1, a.range());
1695                     let kind_b = Kind::End(b.range().node.1, b.range());
1696                     if let Ordering::Equal | Ordering::Greater = kind_a.cmp(&kind_b) {
1697                         return None;
1698                     }
1699                 }
1700                 return Some((a.range(), b.range()));
1701             },
1702         }
1703     }
1704
1705     None
1706 }
1707
1708 mod redundant_pattern_match {
1709     use super::REDUNDANT_PATTERN_MATCHING;
1710     use clippy_utils::diagnostics::span_lint_and_then;
1711     use clippy_utils::source::{snippet, snippet_with_applicability};
1712     use clippy_utils::ty::{implements_trait, is_type_diagnostic_item, is_type_lang_item, match_type};
1713     use clippy_utils::{is_lang_ctor, is_qpath_def_path, is_trait_method, paths};
1714     use if_chain::if_chain;
1715     use rustc_ast::ast::LitKind;
1716     use rustc_errors::Applicability;
1717     use rustc_hir::LangItem::{OptionNone, OptionSome, PollPending, PollReady, ResultErr, ResultOk};
1718     use rustc_hir::{
1719         intravisit::{walk_expr, ErasedMap, NestedVisitorMap, Visitor},
1720         Arm, Block, Expr, ExprKind, LangItem, MatchSource, Node, PatKind, QPath,
1721     };
1722     use rustc_lint::LateContext;
1723     use rustc_middle::ty::{self, subst::GenericArgKind, Ty};
1724     use rustc_span::sym;
1725
1726     pub fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
1727         if let ExprKind::Match(op, arms, ref match_source) = &expr.kind {
1728             match match_source {
1729                 MatchSource::Normal => find_sugg_for_match(cx, expr, op, arms),
1730                 MatchSource::IfLetDesugar { contains_else_clause } => {
1731                     find_sugg_for_if_let(cx, expr, op, &arms[0], "if", *contains_else_clause)
1732                 },
1733                 MatchSource::WhileLetDesugar => find_sugg_for_if_let(cx, expr, op, &arms[0], "while", false),
1734                 _ => {},
1735             }
1736         }
1737     }
1738
1739     /// Checks if the drop order for a type matters. Some std types implement drop solely to
1740     /// deallocate memory. For these types, and composites containing them, changing the drop order
1741     /// won't result in any observable side effects.
1742     fn type_needs_ordered_drop(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
1743         if !ty.needs_drop(cx.tcx, cx.param_env) {
1744             false
1745         } else if !cx
1746             .tcx
1747             .lang_items()
1748             .drop_trait()
1749             .map_or(false, |id| implements_trait(cx, ty, id, &[]))
1750         {
1751             // This type doesn't implement drop, so no side effects here.
1752             // Check if any component type has any.
1753             match ty.kind() {
1754                 ty::Tuple(_) => ty.tuple_fields().any(|ty| type_needs_ordered_drop(cx, ty)),
1755                 ty::Array(ty, _) => type_needs_ordered_drop(cx, ty),
1756                 ty::Adt(adt, subs) => adt
1757                     .all_fields()
1758                     .map(|f| f.ty(cx.tcx, subs))
1759                     .any(|ty| type_needs_ordered_drop(cx, ty)),
1760                 _ => true,
1761             }
1762         }
1763         // Check for std types which implement drop, but only for memory allocation.
1764         else if is_type_diagnostic_item(cx, ty, sym::vec_type)
1765             || is_type_lang_item(cx, ty, LangItem::OwnedBox)
1766             || is_type_diagnostic_item(cx, ty, sym::Rc)
1767             || is_type_diagnostic_item(cx, ty, sym::Arc)
1768             || is_type_diagnostic_item(cx, ty, sym::cstring_type)
1769             || match_type(cx, ty, &paths::BTREEMAP)
1770             || match_type(cx, ty, &paths::LINKED_LIST)
1771             || match_type(cx, ty, &paths::WEAK_RC)
1772             || match_type(cx, ty, &paths::WEAK_ARC)
1773         {
1774             // Check all of the generic arguments.
1775             if let ty::Adt(_, subs) = ty.kind() {
1776                 subs.types().any(|ty| type_needs_ordered_drop(cx, ty))
1777             } else {
1778                 true
1779             }
1780         } else {
1781             true
1782         }
1783     }
1784
1785     // Extract the generic arguments out of a type
1786     fn try_get_generic_ty(ty: Ty<'_>, index: usize) -> Option<Ty<'_>> {
1787         if_chain! {
1788             if let ty::Adt(_, subs) = ty.kind();
1789             if let Some(sub) = subs.get(index);
1790             if let GenericArgKind::Type(sub_ty) = sub.unpack();
1791             then {
1792                 Some(sub_ty)
1793             } else {
1794                 None
1795             }
1796         }
1797     }
1798
1799     // Checks if there are any temporaries created in the given expression for which drop order
1800     // matters.
1801     fn temporaries_need_ordered_drop(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
1802         struct V<'a, 'tcx> {
1803             cx: &'a LateContext<'tcx>,
1804             res: bool,
1805         }
1806         impl<'a, 'tcx> Visitor<'tcx> for V<'a, 'tcx> {
1807             type Map = ErasedMap<'tcx>;
1808             fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1809                 NestedVisitorMap::None
1810             }
1811
1812             fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
1813                 match expr.kind {
1814                     // Taking the reference of a value leaves a temporary
1815                     // e.g. In `&String::new()` the string is a temporary value.
1816                     // Remaining fields are temporary values
1817                     // e.g. In `(String::new(), 0).1` the string is a temporary value.
1818                     ExprKind::AddrOf(_, _, expr) | ExprKind::Field(expr, _) => {
1819                         if !matches!(expr.kind, ExprKind::Path(_)) {
1820                             if type_needs_ordered_drop(self.cx, self.cx.typeck_results().expr_ty(expr)) {
1821                                 self.res = true;
1822                             } else {
1823                                 self.visit_expr(expr);
1824                             }
1825                         }
1826                     },
1827                     // the base type is alway taken by reference.
1828                     // e.g. In `(vec![0])[0]` the vector is a temporary value.
1829                     ExprKind::Index(base, index) => {
1830                         if !matches!(base.kind, ExprKind::Path(_)) {
1831                             if type_needs_ordered_drop(self.cx, self.cx.typeck_results().expr_ty(base)) {
1832                                 self.res = true;
1833                             } else {
1834                                 self.visit_expr(base);
1835                             }
1836                         }
1837                         self.visit_expr(index);
1838                     },
1839                     // Method calls can take self by reference.
1840                     // e.g. In `String::new().len()` the string is a temporary value.
1841                     ExprKind::MethodCall(_, _, [self_arg, args @ ..], _) => {
1842                         if !matches!(self_arg.kind, ExprKind::Path(_)) {
1843                             let self_by_ref = self
1844                                 .cx
1845                                 .typeck_results()
1846                                 .type_dependent_def_id(expr.hir_id)
1847                                 .map_or(false, |id| self.cx.tcx.fn_sig(id).skip_binder().inputs()[0].is_ref());
1848                             if self_by_ref
1849                                 && type_needs_ordered_drop(self.cx, self.cx.typeck_results().expr_ty(self_arg))
1850                             {
1851                                 self.res = true;
1852                             } else {
1853                                 self.visit_expr(self_arg)
1854                             }
1855                         }
1856                         args.iter().for_each(|arg| self.visit_expr(arg));
1857                     },
1858                     // Either explicitly drops values, or changes control flow.
1859                     ExprKind::DropTemps(_)
1860                     | ExprKind::Ret(_)
1861                     | ExprKind::Break(..)
1862                     | ExprKind::Yield(..)
1863                     | ExprKind::Block(Block { expr: None, .. }, _)
1864                     | ExprKind::Loop(..) => (),
1865
1866                     // Only consider the final expression.
1867                     ExprKind::Block(Block { expr: Some(expr), .. }, _) => self.visit_expr(expr),
1868
1869                     _ => walk_expr(self, expr),
1870                 }
1871             }
1872         }
1873
1874         let mut v = V { cx, res: false };
1875         v.visit_expr(expr);
1876         v.res
1877     }
1878
1879     fn find_sugg_for_if_let<'tcx>(
1880         cx: &LateContext<'tcx>,
1881         expr: &'tcx Expr<'_>,
1882         op: &'tcx Expr<'tcx>,
1883         arm: &Arm<'_>,
1884         keyword: &'static str,
1885         has_else: bool,
1886     ) {
1887         // also look inside refs
1888         let mut kind = &arm.pat.kind;
1889         // if we have &None for example, peel it so we can detect "if let None = x"
1890         if let PatKind::Ref(inner, _mutability) = kind {
1891             kind = &inner.kind;
1892         }
1893         let op_ty = cx.typeck_results().expr_ty(op);
1894         // Determine which function should be used, and the type contained by the corresponding
1895         // variant.
1896         let (good_method, inner_ty) = match kind {
1897             PatKind::TupleStruct(ref path, [sub_pat], _) => {
1898                 if let PatKind::Wild = sub_pat.kind {
1899                     if is_lang_ctor(cx, path, ResultOk) {
1900                         ("is_ok()", try_get_generic_ty(op_ty, 0).unwrap_or(op_ty))
1901                     } else if is_lang_ctor(cx, path, ResultErr) {
1902                         ("is_err()", try_get_generic_ty(op_ty, 1).unwrap_or(op_ty))
1903                     } else if is_lang_ctor(cx, path, OptionSome) {
1904                         ("is_some()", op_ty)
1905                     } else if is_lang_ctor(cx, path, PollReady) {
1906                         ("is_ready()", op_ty)
1907                     } else if is_qpath_def_path(cx, path, sub_pat.hir_id, &paths::IPADDR_V4) {
1908                         ("is_ipv4()", op_ty)
1909                     } else if is_qpath_def_path(cx, path, sub_pat.hir_id, &paths::IPADDR_V6) {
1910                         ("is_ipv6()", op_ty)
1911                     } else {
1912                         return;
1913                     }
1914                 } else {
1915                     return;
1916                 }
1917             },
1918             PatKind::Path(ref path) => {
1919                 let method = if is_lang_ctor(cx, path, OptionNone) {
1920                     "is_none()"
1921                 } else if is_lang_ctor(cx, path, PollPending) {
1922                     "is_pending()"
1923                 } else {
1924                     return;
1925                 };
1926                 // `None` and `Pending` don't have an inner type.
1927                 (method, cx.tcx.types.unit)
1928             },
1929             _ => return,
1930         };
1931
1932         // If this is the last expression in a block or there is an else clause then the whole
1933         // type needs to be considered, not just the inner type of the branch being matched on.
1934         // Note the last expression in a block is dropped after all local bindings.
1935         let check_ty = if has_else
1936             || (keyword == "if" && matches!(cx.tcx.hir().parent_iter(expr.hir_id).next(), Some((_, Node::Block(..)))))
1937         {
1938             op_ty
1939         } else {
1940             inner_ty
1941         };
1942
1943         // All temporaries created in the scrutinee expression are dropped at the same time as the
1944         // scrutinee would be, so they have to be considered as well.
1945         // e.g. in `if let Some(x) = foo.lock().unwrap().baz.as_ref() { .. }` the lock will be held
1946         // for the duration if body.
1947         let needs_drop = type_needs_ordered_drop(cx, check_ty) || temporaries_need_ordered_drop(cx, op);
1948
1949         // check that `while_let_on_iterator` lint does not trigger
1950         if_chain! {
1951             if keyword == "while";
1952             if let ExprKind::MethodCall(method_path, _, _, _) = op.kind;
1953             if method_path.ident.name == sym::next;
1954             if is_trait_method(cx, op, sym::Iterator);
1955             then {
1956                 return;
1957             }
1958         }
1959
1960         let result_expr = match &op.kind {
1961             ExprKind::AddrOf(_, _, borrowed) => borrowed,
1962             _ => op,
1963         };
1964         span_lint_and_then(
1965             cx,
1966             REDUNDANT_PATTERN_MATCHING,
1967             arm.pat.span,
1968             &format!("redundant pattern matching, consider using `{}`", good_method),
1969             |diag| {
1970                 // while let ... = ... { ... }
1971                 // ^^^^^^^^^^^^^^^^^^^^^^^^^^^
1972                 let expr_span = expr.span;
1973
1974                 // while let ... = ... { ... }
1975                 //                 ^^^
1976                 let op_span = result_expr.span.source_callsite();
1977
1978                 // while let ... = ... { ... }
1979                 // ^^^^^^^^^^^^^^^^^^^
1980                 let span = expr_span.until(op_span.shrink_to_hi());
1981
1982                 let mut app = if needs_drop {
1983                     Applicability::MaybeIncorrect
1984                 } else {
1985                     Applicability::MachineApplicable
1986                 };
1987                 let sugg = snippet_with_applicability(cx, op_span, "_", &mut app);
1988
1989                 diag.span_suggestion(span, "try this", format!("{} {}.{}", keyword, sugg, good_method), app);
1990
1991                 if needs_drop {
1992                     diag.note("this will change drop order of the result, as well as all temporaries");
1993                     diag.note("add `#[allow(clippy::redundant_pattern_matching)]` if this is important");
1994                 }
1995             },
1996         );
1997     }
1998
1999     fn find_sugg_for_match<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, op: &Expr<'_>, arms: &[Arm<'_>]) {
2000         if arms.len() == 2 {
2001             let node_pair = (&arms[0].pat.kind, &arms[1].pat.kind);
2002
2003             let found_good_method = match node_pair {
2004                 (
2005                     PatKind::TupleStruct(ref path_left, patterns_left, _),
2006                     PatKind::TupleStruct(ref path_right, patterns_right, _),
2007                 ) if patterns_left.len() == 1 && patterns_right.len() == 1 => {
2008                     if let (PatKind::Wild, PatKind::Wild) = (&patterns_left[0].kind, &patterns_right[0].kind) {
2009                         find_good_method_for_match(
2010                             cx,
2011                             arms,
2012                             path_left,
2013                             path_right,
2014                             &paths::RESULT_OK,
2015                             &paths::RESULT_ERR,
2016                             "is_ok()",
2017                             "is_err()",
2018                         )
2019                         .or_else(|| {
2020                             find_good_method_for_match(
2021                                 cx,
2022                                 arms,
2023                                 path_left,
2024                                 path_right,
2025                                 &paths::IPADDR_V4,
2026                                 &paths::IPADDR_V6,
2027                                 "is_ipv4()",
2028                                 "is_ipv6()",
2029                             )
2030                         })
2031                     } else {
2032                         None
2033                     }
2034                 },
2035                 (PatKind::TupleStruct(ref path_left, patterns, _), PatKind::Path(ref path_right))
2036                 | (PatKind::Path(ref path_left), PatKind::TupleStruct(ref path_right, patterns, _))
2037                     if patterns.len() == 1 =>
2038                 {
2039                     if let PatKind::Wild = patterns[0].kind {
2040                         find_good_method_for_match(
2041                             cx,
2042                             arms,
2043                             path_left,
2044                             path_right,
2045                             &paths::OPTION_SOME,
2046                             &paths::OPTION_NONE,
2047                             "is_some()",
2048                             "is_none()",
2049                         )
2050                         .or_else(|| {
2051                             find_good_method_for_match(
2052                                 cx,
2053                                 arms,
2054                                 path_left,
2055                                 path_right,
2056                                 &paths::POLL_READY,
2057                                 &paths::POLL_PENDING,
2058                                 "is_ready()",
2059                                 "is_pending()",
2060                             )
2061                         })
2062                     } else {
2063                         None
2064                     }
2065                 },
2066                 _ => None,
2067             };
2068
2069             if let Some(good_method) = found_good_method {
2070                 let span = expr.span.to(op.span);
2071                 let result_expr = match &op.kind {
2072                     ExprKind::AddrOf(_, _, borrowed) => borrowed,
2073                     _ => op,
2074                 };
2075                 span_lint_and_then(
2076                     cx,
2077                     REDUNDANT_PATTERN_MATCHING,
2078                     expr.span,
2079                     &format!("redundant pattern matching, consider using `{}`", good_method),
2080                     |diag| {
2081                         diag.span_suggestion(
2082                             span,
2083                             "try this",
2084                             format!("{}.{}", snippet(cx, result_expr.span, "_"), good_method),
2085                             Applicability::MaybeIncorrect, // snippet
2086                         );
2087                     },
2088                 );
2089             }
2090         }
2091     }
2092
2093     #[allow(clippy::too_many_arguments)]
2094     fn find_good_method_for_match<'a>(
2095         cx: &LateContext<'_>,
2096         arms: &[Arm<'_>],
2097         path_left: &QPath<'_>,
2098         path_right: &QPath<'_>,
2099         expected_left: &[&str],
2100         expected_right: &[&str],
2101         should_be_left: &'a str,
2102         should_be_right: &'a str,
2103     ) -> Option<&'a str> {
2104         let body_node_pair = if is_qpath_def_path(cx, path_left, arms[0].pat.hir_id, expected_left)
2105             && is_qpath_def_path(cx, path_right, arms[1].pat.hir_id, expected_right)
2106         {
2107             (&(*arms[0].body).kind, &(*arms[1].body).kind)
2108         } else if is_qpath_def_path(cx, path_right, arms[1].pat.hir_id, expected_left)
2109             && is_qpath_def_path(cx, path_left, arms[0].pat.hir_id, expected_right)
2110         {
2111             (&(*arms[1].body).kind, &(*arms[0].body).kind)
2112         } else {
2113             return None;
2114         };
2115
2116         match body_node_pair {
2117             (ExprKind::Lit(ref lit_left), ExprKind::Lit(ref lit_right)) => match (&lit_left.node, &lit_right.node) {
2118                 (LitKind::Bool(true), LitKind::Bool(false)) => Some(should_be_left),
2119                 (LitKind::Bool(false), LitKind::Bool(true)) => Some(should_be_right),
2120                 _ => None,
2121             },
2122             _ => None,
2123         }
2124     }
2125 }
2126
2127 #[test]
2128 fn test_overlapping() {
2129     use rustc_span::source_map::DUMMY_SP;
2130
2131     let sp = |s, e| SpannedRange {
2132         span: DUMMY_SP,
2133         node: (s, e),
2134     };
2135
2136     assert_eq!(None, overlapping::<u8>(&[]));
2137     assert_eq!(None, overlapping(&[sp(1, Bound::Included(4))]));
2138     assert_eq!(
2139         None,
2140         overlapping(&[sp(1, Bound::Included(4)), sp(5, Bound::Included(6))])
2141     );
2142     assert_eq!(
2143         None,
2144         overlapping(&[
2145             sp(1, Bound::Included(4)),
2146             sp(5, Bound::Included(6)),
2147             sp(10, Bound::Included(11))
2148         ],)
2149     );
2150     assert_eq!(
2151         Some((&sp(1, Bound::Included(4)), &sp(3, Bound::Included(6)))),
2152         overlapping(&[sp(1, Bound::Included(4)), sp(3, Bound::Included(6))])
2153     );
2154     assert_eq!(
2155         Some((&sp(5, Bound::Included(6)), &sp(6, Bound::Included(11)))),
2156         overlapping(&[
2157             sp(1, Bound::Included(4)),
2158             sp(5, Bound::Included(6)),
2159             sp(6, Bound::Included(11))
2160         ],)
2161     );
2162 }
2163
2164 /// Implementation of `MATCH_SAME_ARMS`.
2165 fn lint_match_arms<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) {
2166     if let ExprKind::Match(_, arms, MatchSource::Normal) = expr.kind {
2167         let hash = |&(_, arm): &(usize, &Arm<'_>)| -> u64 {
2168             let mut h = SpanlessHash::new(cx);
2169             h.hash_expr(arm.body);
2170             h.finish()
2171         };
2172
2173         let eq = |&(lindex, lhs): &(usize, &Arm<'_>), &(rindex, rhs): &(usize, &Arm<'_>)| -> bool {
2174             let min_index = usize::min(lindex, rindex);
2175             let max_index = usize::max(lindex, rindex);
2176
2177             let mut local_map: HirIdMap<HirId> = HirIdMap::default();
2178             let eq_fallback = |a: &Expr<'_>, b: &Expr<'_>| {
2179                 if_chain! {
2180                     if let Some(a_id) = path_to_local(a);
2181                     if let Some(b_id) = path_to_local(b);
2182                     let entry = match local_map.entry(a_id) {
2183                         Entry::Vacant(entry) => entry,
2184                         // check if using the same bindings as before
2185                         Entry::Occupied(entry) => return *entry.get() == b_id,
2186                     };
2187                     // the names technically don't have to match; this makes the lint more conservative
2188                     if cx.tcx.hir().name(a_id) == cx.tcx.hir().name(b_id);
2189                     if TyS::same_type(cx.typeck_results().expr_ty(a), cx.typeck_results().expr_ty(b));
2190                     if pat_contains_local(lhs.pat, a_id);
2191                     if pat_contains_local(rhs.pat, b_id);
2192                     then {
2193                         entry.insert(b_id);
2194                         true
2195                     } else {
2196                         false
2197                     }
2198                 }
2199             };
2200             // Arms with a guard are ignored, those can’t always be merged together
2201             // This is also the case for arms in-between each there is an arm with a guard
2202             (min_index..=max_index).all(|index| arms[index].guard.is_none())
2203                 && SpanlessEq::new(cx)
2204                     .expr_fallback(eq_fallback)
2205                     .eq_expr(lhs.body, rhs.body)
2206                 // these checks could be removed to allow unused bindings
2207                 && bindings_eq(lhs.pat, local_map.keys().copied().collect())
2208                 && bindings_eq(rhs.pat, local_map.values().copied().collect())
2209         };
2210
2211         let indexed_arms: Vec<(usize, &Arm<'_>)> = arms.iter().enumerate().collect();
2212         for (&(_, i), &(_, j)) in search_same(&indexed_arms, hash, eq) {
2213             span_lint_and_then(
2214                 cx,
2215                 MATCH_SAME_ARMS,
2216                 j.body.span,
2217                 "this `match` has identical arm bodies",
2218                 |diag| {
2219                     diag.span_note(i.body.span, "same as this");
2220
2221                     // Note: this does not use `span_suggestion` on purpose:
2222                     // there is no clean way
2223                     // to remove the other arm. Building a span and suggest to replace it to ""
2224                     // makes an even more confusing error message. Also in order not to make up a
2225                     // span for the whole pattern, the suggestion is only shown when there is only
2226                     // one pattern. The user should know about `|` if they are already using it…
2227
2228                     let lhs = snippet(cx, i.pat.span, "<pat1>");
2229                     let rhs = snippet(cx, j.pat.span, "<pat2>");
2230
2231                     if let PatKind::Wild = j.pat.kind {
2232                         // if the last arm is _, then i could be integrated into _
2233                         // note that i.pat cannot be _, because that would mean that we're
2234                         // hiding all the subsequent arms, and rust won't compile
2235                         diag.span_note(
2236                             i.body.span,
2237                             &format!(
2238                                 "`{}` has the same arm body as the `_` wildcard, consider removing it",
2239                                 lhs
2240                             ),
2241                         );
2242                     } else {
2243                         diag.span_help(i.pat.span, &format!("consider refactoring into `{} | {}`", lhs, rhs));
2244                     }
2245                 },
2246             );
2247         }
2248     }
2249 }
2250
2251 fn pat_contains_local(pat: &Pat<'_>, id: HirId) -> bool {
2252     let mut result = false;
2253     pat.walk_short(|p| {
2254         result |= matches!(p.kind, PatKind::Binding(_, binding_id, ..) if binding_id == id);
2255         !result
2256     });
2257     result
2258 }
2259
2260 /// Returns true if all the bindings in the `Pat` are in `ids` and vice versa
2261 fn bindings_eq(pat: &Pat<'_>, mut ids: HirIdSet) -> bool {
2262     let mut result = true;
2263     pat.each_binding_or_first(&mut |_, id, _, _| result &= ids.remove(&id));
2264     result && ids.is_empty()
2265 }