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