]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/matches/mod.rs
Split out `single_match`
[rust.git] / clippy_lints / src / matches / mod.rs
1 use clippy_utils::consts::{constant, constant_full_int, miri_to_const, FullInt};
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::macros::{is_panic, root_macro_call};
6 use clippy_utils::peel_blocks_with_stmt;
7 use clippy_utils::source::{expr_block, indent_of, snippet, snippet_block, snippet_opt, snippet_with_applicability};
8 use clippy_utils::sugg::Sugg;
9 use clippy_utils::ty::is_type_diagnostic_item;
10 use clippy_utils::visitors::is_local_used;
11 use clippy_utils::{
12     get_parent_expr, is_lang_ctor, is_refutable, is_unit_expr, is_wild, meets_msrv, msrvs, path_to_local_id,
13     peel_blocks, peel_hir_pat_refs, recurse_or_patterns, strip_pat_refs,
14 };
15 use core::iter::once;
16 use if_chain::if_chain;
17 use rustc_ast::ast::LitKind;
18 use rustc_errors::Applicability;
19 use rustc_hir::def::{CtorKind, DefKind, Res};
20 use rustc_hir::LangItem::{OptionNone, OptionSome};
21 use rustc_hir::{
22     self as hir, Arm, BindingAnnotation, BorrowKind, Expr, ExprKind, Local, MatchSource, Mutability, Node, Pat,
23     PatKind, PathSegment, QPath, RangeEnd, TyKind,
24 };
25 use rustc_lint::{LateContext, LateLintPass};
26 use rustc_middle::ty::{self, Ty, VariantDef};
27 use rustc_semver::RustcVersion;
28 use rustc_session::{declare_tool_lint, impl_lint_pass};
29 use rustc_span::{sym, symbol::kw, Span};
30 use std::cmp::Ordering;
31
32 mod match_like_matches;
33 mod match_same_arms;
34 mod redundant_pattern_match;
35 mod single_match;
36
37 declare_clippy_lint! {
38     /// ### What it does
39     /// Checks for matches with a single arm where an `if let`
40     /// will usually suffice.
41     ///
42     /// ### Why is this bad?
43     /// Just readability – `if let` nests less than a `match`.
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     #[clippy::version = "pre 1.29.0"]
61     pub SINGLE_MATCH,
62     style,
63     "a `match` statement with a single nontrivial arm (i.e., where the other arm is `_ => {}`) instead of `if let`"
64 }
65
66 declare_clippy_lint! {
67     /// ### What it does
68     /// Checks for matches with two arms where an `if let else` will
69     /// usually suffice.
70     ///
71     /// ### Why is this bad?
72     /// Just readability – `if let` nests less than a `match`.
73     ///
74     /// ### Known problems
75     /// Personal style preferences may differ.
76     ///
77     /// ### Example
78     /// Using `match`:
79     ///
80     /// ```rust
81     /// # fn bar(foo: &usize) {}
82     /// # let other_ref: usize = 1;
83     /// # let x: Option<&usize> = Some(&1);
84     /// match x {
85     ///     Some(ref foo) => bar(foo),
86     ///     _ => bar(&other_ref),
87     /// }
88     /// ```
89     ///
90     /// Using `if let` with `else`:
91     ///
92     /// ```rust
93     /// # fn bar(foo: &usize) {}
94     /// # let other_ref: usize = 1;
95     /// # let x: Option<&usize> = Some(&1);
96     /// if let Some(ref foo) = x {
97     ///     bar(foo);
98     /// } else {
99     ///     bar(&other_ref);
100     /// }
101     /// ```
102     #[clippy::version = "pre 1.29.0"]
103     pub SINGLE_MATCH_ELSE,
104     pedantic,
105     "a `match` statement with two arms where the second arm's pattern is a placeholder instead of a specific match pattern"
106 }
107
108 declare_clippy_lint! {
109     /// ### What it does
110     /// Checks for matches where all arms match a reference,
111     /// suggesting to remove the reference and deref the matched expression
112     /// instead. It also checks for `if let &foo = bar` blocks.
113     ///
114     /// ### Why is this bad?
115     /// It just makes the code less readable. That reference
116     /// destructuring adds nothing to the code.
117     ///
118     /// ### Example
119     /// ```rust,ignore
120     /// // Bad
121     /// match x {
122     ///     &A(ref y) => foo(y),
123     ///     &B => bar(),
124     ///     _ => frob(&x),
125     /// }
126     ///
127     /// // Good
128     /// match *x {
129     ///     A(ref y) => foo(y),
130     ///     B => bar(),
131     ///     _ => frob(x),
132     /// }
133     /// ```
134     #[clippy::version = "pre 1.29.0"]
135     pub MATCH_REF_PATS,
136     style,
137     "a `match` or `if let` with all arms prefixed with `&` instead of deref-ing the match expression"
138 }
139
140 declare_clippy_lint! {
141     /// ### What it does
142     /// Checks for matches where match expression is a `bool`. It
143     /// suggests to replace the expression with an `if...else` block.
144     ///
145     /// ### Why is this bad?
146     /// It makes the code less readable.
147     ///
148     /// ### Example
149     /// ```rust
150     /// # fn foo() {}
151     /// # fn bar() {}
152     /// let condition: bool = true;
153     /// match condition {
154     ///     true => foo(),
155     ///     false => bar(),
156     /// }
157     /// ```
158     /// Use if/else instead:
159     /// ```rust
160     /// # fn foo() {}
161     /// # fn bar() {}
162     /// let condition: bool = true;
163     /// if condition {
164     ///     foo();
165     /// } else {
166     ///     bar();
167     /// }
168     /// ```
169     #[clippy::version = "pre 1.29.0"]
170     pub MATCH_BOOL,
171     pedantic,
172     "a `match` on a boolean expression instead of an `if..else` block"
173 }
174
175 declare_clippy_lint! {
176     /// ### What it does
177     /// Checks for overlapping match arms.
178     ///
179     /// ### Why is this bad?
180     /// It is likely to be an error and if not, makes the code
181     /// less obvious.
182     ///
183     /// ### Example
184     /// ```rust
185     /// let x = 5;
186     /// match x {
187     ///     1..=10 => println!("1 ... 10"),
188     ///     5..=15 => println!("5 ... 15"),
189     ///     _ => (),
190     /// }
191     /// ```
192     #[clippy::version = "pre 1.29.0"]
193     pub MATCH_OVERLAPPING_ARM,
194     style,
195     "a `match` with overlapping arms"
196 }
197
198 declare_clippy_lint! {
199     /// ### What it does
200     /// Checks for arm which matches all errors with `Err(_)`
201     /// and take drastic actions like `panic!`.
202     ///
203     /// ### Why is this bad?
204     /// It is generally a bad practice, similar to
205     /// catching all exceptions in java with `catch(Exception)`
206     ///
207     /// ### Example
208     /// ```rust
209     /// let x: Result<i32, &str> = Ok(3);
210     /// match x {
211     ///     Ok(_) => println!("ok"),
212     ///     Err(_) => panic!("err"),
213     /// }
214     /// ```
215     #[clippy::version = "pre 1.29.0"]
216     pub MATCH_WILD_ERR_ARM,
217     pedantic,
218     "a `match` with `Err(_)` arm and take drastic actions"
219 }
220
221 declare_clippy_lint! {
222     /// ### What it does
223     /// Checks for match which is used to add a reference to an
224     /// `Option` value.
225     ///
226     /// ### Why is this bad?
227     /// Using `as_ref()` or `as_mut()` instead is shorter.
228     ///
229     /// ### Example
230     /// ```rust
231     /// let x: Option<()> = None;
232     ///
233     /// // Bad
234     /// let r: Option<&()> = match x {
235     ///     None => None,
236     ///     Some(ref v) => Some(v),
237     /// };
238     ///
239     /// // Good
240     /// let r: Option<&()> = x.as_ref();
241     /// ```
242     #[clippy::version = "pre 1.29.0"]
243     pub MATCH_AS_REF,
244     complexity,
245     "a `match` on an Option value instead of using `as_ref()` or `as_mut`"
246 }
247
248 declare_clippy_lint! {
249     /// ### What it does
250     /// Checks for wildcard enum matches using `_`.
251     ///
252     /// ### Why is this bad?
253     /// New enum variants added by library updates can be missed.
254     ///
255     /// ### Known problems
256     /// Suggested replacements may be incorrect if guards exhaustively cover some
257     /// variants, and also may not use correct path to enum if it's not present in the current scope.
258     ///
259     /// ### Example
260     /// ```rust
261     /// # enum Foo { A(usize), B(usize) }
262     /// # let x = Foo::B(1);
263     /// // Bad
264     /// match x {
265     ///     Foo::A(_) => {},
266     ///     _ => {},
267     /// }
268     ///
269     /// // Good
270     /// match x {
271     ///     Foo::A(_) => {},
272     ///     Foo::B(_) => {},
273     /// }
274     /// ```
275     #[clippy::version = "1.34.0"]
276     pub WILDCARD_ENUM_MATCH_ARM,
277     restriction,
278     "a wildcard enum match arm using `_`"
279 }
280
281 declare_clippy_lint! {
282     /// ### What it does
283     /// Checks for wildcard enum matches for a single variant.
284     ///
285     /// ### Why is this bad?
286     /// New enum variants added by library updates can be missed.
287     ///
288     /// ### Known problems
289     /// Suggested replacements may not use correct path to enum
290     /// if it's not present in the current scope.
291     ///
292     /// ### Example
293     /// ```rust
294     /// # enum Foo { A, B, C }
295     /// # let x = Foo::B;
296     /// // Bad
297     /// match x {
298     ///     Foo::A => {},
299     ///     Foo::B => {},
300     ///     _ => {},
301     /// }
302     ///
303     /// // Good
304     /// match x {
305     ///     Foo::A => {},
306     ///     Foo::B => {},
307     ///     Foo::C => {},
308     /// }
309     /// ```
310     #[clippy::version = "1.45.0"]
311     pub MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
312     pedantic,
313     "a wildcard enum match for a single variant"
314 }
315
316 declare_clippy_lint! {
317     /// ### What it does
318     /// Checks for wildcard pattern used with others patterns in same match arm.
319     ///
320     /// ### Why is this bad?
321     /// Wildcard pattern already covers any other pattern as it will match anyway.
322     /// It makes the code less readable, especially to spot wildcard pattern use in match arm.
323     ///
324     /// ### Example
325     /// ```rust
326     /// // Bad
327     /// match "foo" {
328     ///     "a" => {},
329     ///     "bar" | _ => {},
330     /// }
331     ///
332     /// // Good
333     /// match "foo" {
334     ///     "a" => {},
335     ///     _ => {},
336     /// }
337     /// ```
338     #[clippy::version = "1.42.0"]
339     pub WILDCARD_IN_OR_PATTERNS,
340     complexity,
341     "a wildcard pattern used with others patterns in same match arm"
342 }
343
344 declare_clippy_lint! {
345     /// ### What it does
346     /// Checks for matches being used to destructure a single-variant enum
347     /// or tuple struct where a `let` will suffice.
348     ///
349     /// ### Why is this bad?
350     /// Just readability – `let` doesn't nest, whereas a `match` does.
351     ///
352     /// ### Example
353     /// ```rust
354     /// enum Wrapper {
355     ///     Data(i32),
356     /// }
357     ///
358     /// let wrapper = Wrapper::Data(42);
359     ///
360     /// let data = match wrapper {
361     ///     Wrapper::Data(i) => i,
362     /// };
363     /// ```
364     ///
365     /// The correct use would be:
366     /// ```rust
367     /// enum Wrapper {
368     ///     Data(i32),
369     /// }
370     ///
371     /// let wrapper = Wrapper::Data(42);
372     /// let Wrapper::Data(data) = wrapper;
373     /// ```
374     #[clippy::version = "pre 1.29.0"]
375     pub INFALLIBLE_DESTRUCTURING_MATCH,
376     style,
377     "a `match` statement with a single infallible arm instead of a `let`"
378 }
379
380 declare_clippy_lint! {
381     /// ### What it does
382     /// Checks for useless match that binds to only one value.
383     ///
384     /// ### Why is this bad?
385     /// Readability and needless complexity.
386     ///
387     /// ### Known problems
388     ///  Suggested replacements may be incorrect when `match`
389     /// is actually binding temporary value, bringing a 'dropped while borrowed' error.
390     ///
391     /// ### Example
392     /// ```rust
393     /// # let a = 1;
394     /// # let b = 2;
395     ///
396     /// // Bad
397     /// match (a, b) {
398     ///     (c, d) => {
399     ///         // useless match
400     ///     }
401     /// }
402     ///
403     /// // Good
404     /// let (c, d) = (a, b);
405     /// ```
406     #[clippy::version = "1.43.0"]
407     pub MATCH_SINGLE_BINDING,
408     complexity,
409     "a match with a single binding instead of using `let` statement"
410 }
411
412 declare_clippy_lint! {
413     /// ### What it does
414     /// Checks for unnecessary '..' pattern binding on struct when all fields are explicitly matched.
415     ///
416     /// ### Why is this bad?
417     /// Correctness and readability. It's like having a wildcard pattern after
418     /// matching all enum variants explicitly.
419     ///
420     /// ### Example
421     /// ```rust
422     /// # struct A { a: i32 }
423     /// let a = A { a: 5 };
424     ///
425     /// // Bad
426     /// match a {
427     ///     A { a: 5, .. } => {},
428     ///     _ => {},
429     /// }
430     ///
431     /// // Good
432     /// match a {
433     ///     A { a: 5 } => {},
434     ///     _ => {},
435     /// }
436     /// ```
437     #[clippy::version = "1.43.0"]
438     pub REST_PAT_IN_FULLY_BOUND_STRUCTS,
439     restriction,
440     "a match on a struct that binds all fields but still uses the wildcard pattern"
441 }
442
443 declare_clippy_lint! {
444     /// ### What it does
445     /// Lint for redundant pattern matching over `Result`, `Option`,
446     /// `std::task::Poll` or `std::net::IpAddr`
447     ///
448     /// ### Why is this bad?
449     /// It's more concise and clear to just use the proper
450     /// utility function
451     ///
452     /// ### Known problems
453     /// This will change the drop order for the matched type. Both `if let` and
454     /// `while let` will drop the value at the end of the block, both `if` and `while` will drop the
455     /// value before entering the block. For most types this change will not matter, but for a few
456     /// types this will not be an acceptable change (e.g. locks). See the
457     /// [reference](https://doc.rust-lang.org/reference/destructors.html#drop-scopes) for more about
458     /// drop order.
459     ///
460     /// ### Example
461     /// ```rust
462     /// # use std::task::Poll;
463     /// # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
464     /// if let Ok(_) = Ok::<i32, i32>(42) {}
465     /// if let Err(_) = Err::<i32, i32>(42) {}
466     /// if let None = None::<()> {}
467     /// if let Some(_) = Some(42) {}
468     /// if let Poll::Pending = Poll::Pending::<()> {}
469     /// if let Poll::Ready(_) = Poll::Ready(42) {}
470     /// if let IpAddr::V4(_) = IpAddr::V4(Ipv4Addr::LOCALHOST) {}
471     /// if let IpAddr::V6(_) = IpAddr::V6(Ipv6Addr::LOCALHOST) {}
472     /// match Ok::<i32, i32>(42) {
473     ///     Ok(_) => true,
474     ///     Err(_) => false,
475     /// };
476     /// ```
477     ///
478     /// The more idiomatic use would be:
479     ///
480     /// ```rust
481     /// # use std::task::Poll;
482     /// # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
483     /// if Ok::<i32, i32>(42).is_ok() {}
484     /// if Err::<i32, i32>(42).is_err() {}
485     /// if None::<()>.is_none() {}
486     /// if Some(42).is_some() {}
487     /// if Poll::Pending::<()>.is_pending() {}
488     /// if Poll::Ready(42).is_ready() {}
489     /// if IpAddr::V4(Ipv4Addr::LOCALHOST).is_ipv4() {}
490     /// if IpAddr::V6(Ipv6Addr::LOCALHOST).is_ipv6() {}
491     /// Ok::<i32, i32>(42).is_ok();
492     /// ```
493     #[clippy::version = "1.31.0"]
494     pub REDUNDANT_PATTERN_MATCHING,
495     style,
496     "use the proper utility function avoiding an `if let`"
497 }
498
499 declare_clippy_lint! {
500     /// ### What it does
501     /// Checks for `match`  or `if let` expressions producing a
502     /// `bool` that could be written using `matches!`
503     ///
504     /// ### Why is this bad?
505     /// Readability and needless complexity.
506     ///
507     /// ### Known problems
508     /// This lint falsely triggers, if there are arms with
509     /// `cfg` attributes that remove an arm evaluating to `false`.
510     ///
511     /// ### Example
512     /// ```rust
513     /// let x = Some(5);
514     ///
515     /// // Bad
516     /// let a = match x {
517     ///     Some(0) => true,
518     ///     _ => false,
519     /// };
520     ///
521     /// let a = if let Some(0) = x {
522     ///     true
523     /// } else {
524     ///     false
525     /// };
526     ///
527     /// // Good
528     /// let a = matches!(x, Some(0));
529     /// ```
530     #[clippy::version = "1.47.0"]
531     pub MATCH_LIKE_MATCHES_MACRO,
532     style,
533     "a match that could be written with the matches! macro"
534 }
535
536 declare_clippy_lint! {
537     /// ### What it does
538     /// Checks for `match` with identical arm bodies.
539     ///
540     /// ### Why is this bad?
541     /// This is probably a copy & paste error. If arm bodies
542     /// are the same on purpose, you can factor them
543     /// [using `|`](https://doc.rust-lang.org/book/patterns.html#multiple-patterns).
544     ///
545     /// ### Known problems
546     /// False positive possible with order dependent `match`
547     /// (see issue
548     /// [#860](https://github.com/rust-lang/rust-clippy/issues/860)).
549     ///
550     /// ### Example
551     /// ```rust,ignore
552     /// match foo {
553     ///     Bar => bar(),
554     ///     Quz => quz(),
555     ///     Baz => bar(), // <= oops
556     /// }
557     /// ```
558     ///
559     /// This should probably be
560     /// ```rust,ignore
561     /// match foo {
562     ///     Bar => bar(),
563     ///     Quz => quz(),
564     ///     Baz => baz(), // <= fixed
565     /// }
566     /// ```
567     ///
568     /// or if the original code was not a typo:
569     /// ```rust,ignore
570     /// match foo {
571     ///     Bar | Baz => bar(), // <= shows the intent better
572     ///     Quz => quz(),
573     /// }
574     /// ```
575     #[clippy::version = "pre 1.29.0"]
576     pub MATCH_SAME_ARMS,
577     pedantic,
578     "`match` with identical arm bodies"
579 }
580
581 #[derive(Default)]
582 pub struct Matches {
583     msrv: Option<RustcVersion>,
584     infallible_destructuring_match_linted: bool,
585 }
586
587 impl Matches {
588     #[must_use]
589     pub fn new(msrv: Option<RustcVersion>) -> Self {
590         Self {
591             msrv,
592             ..Matches::default()
593         }
594     }
595 }
596
597 impl_lint_pass!(Matches => [
598     SINGLE_MATCH,
599     MATCH_REF_PATS,
600     MATCH_BOOL,
601     SINGLE_MATCH_ELSE,
602     MATCH_OVERLAPPING_ARM,
603     MATCH_WILD_ERR_ARM,
604     MATCH_AS_REF,
605     WILDCARD_ENUM_MATCH_ARM,
606     MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
607     WILDCARD_IN_OR_PATTERNS,
608     MATCH_SINGLE_BINDING,
609     INFALLIBLE_DESTRUCTURING_MATCH,
610     REST_PAT_IN_FULLY_BOUND_STRUCTS,
611     REDUNDANT_PATTERN_MATCHING,
612     MATCH_LIKE_MATCHES_MACRO,
613     MATCH_SAME_ARMS,
614 ]);
615
616 impl<'tcx> LateLintPass<'tcx> for Matches {
617     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
618         if expr.span.from_expansion() {
619             return;
620         }
621
622         redundant_pattern_match::check(cx, expr);
623
624         if meets_msrv(self.msrv.as_ref(), &msrvs::MATCHES_MACRO) {
625             if !match_like_matches::check(cx, expr) {
626                 match_same_arms::check(cx, expr);
627             }
628         } else {
629             match_same_arms::check(cx, expr);
630         }
631
632         if let ExprKind::Match(ex, arms, MatchSource::Normal) = expr.kind {
633             single_match::check(cx, ex, arms, expr);
634             check_match_bool(cx, ex, arms, expr);
635             check_overlapping_arms(cx, ex, arms);
636             check_wild_err_arm(cx, ex, arms);
637             check_wild_enum_match(cx, ex, arms);
638             check_match_as_ref(cx, ex, arms, expr);
639             check_wild_in_or_pats(cx, arms);
640
641             if self.infallible_destructuring_match_linted {
642                 self.infallible_destructuring_match_linted = false;
643             } else {
644                 check_match_single_binding(cx, ex, arms, expr);
645             }
646         }
647         if let ExprKind::Match(ex, arms, _) = expr.kind {
648             check_match_ref_pats(cx, ex, arms.iter().map(|el| el.pat), expr);
649         }
650     }
651
652     fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'_>) {
653         if_chain! {
654             if !local.span.from_expansion();
655             if let Some(expr) = local.init;
656             if let ExprKind::Match(target, arms, MatchSource::Normal) = expr.kind;
657             if arms.len() == 1 && arms[0].guard.is_none();
658             if let PatKind::TupleStruct(
659                 QPath::Resolved(None, variant_name), args, _) = arms[0].pat.kind;
660             if args.len() == 1;
661             if let PatKind::Binding(_, arg, ..) = strip_pat_refs(&args[0]).kind;
662             let body = peel_blocks(arms[0].body);
663             if path_to_local_id(body, arg);
664
665             then {
666                 let mut applicability = Applicability::MachineApplicable;
667                 self.infallible_destructuring_match_linted = true;
668                 span_lint_and_sugg(
669                     cx,
670                     INFALLIBLE_DESTRUCTURING_MATCH,
671                     local.span,
672                     "you seem to be trying to use `match` to destructure a single infallible pattern. \
673                     Consider using `let`",
674                     "try this",
675                     format!(
676                         "let {}({}) = {};",
677                         snippet_with_applicability(cx, variant_name.span, "..", &mut applicability),
678                         snippet_with_applicability(cx, local.pat.span, "..", &mut applicability),
679                         snippet_with_applicability(cx, target.span, "..", &mut applicability),
680                     ),
681                     applicability,
682                 );
683             }
684         }
685     }
686
687     fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) {
688         if_chain! {
689             if !pat.span.from_expansion();
690             if let PatKind::Struct(QPath::Resolved(_, path), fields, true) = pat.kind;
691             if let Some(def_id) = path.res.opt_def_id();
692             let ty = cx.tcx.type_of(def_id);
693             if let ty::Adt(def, _) = ty.kind();
694             if def.is_struct() || def.is_union();
695             if fields.len() == def.non_enum_variant().fields.len();
696
697             then {
698                 span_lint_and_help(
699                     cx,
700                     REST_PAT_IN_FULLY_BOUND_STRUCTS,
701                     pat.span,
702                     "unnecessary use of `..` pattern in struct binding. All fields were already bound",
703                     None,
704                     "consider removing `..` from this binding",
705                 );
706             }
707         }
708     }
709
710     extract_msrv_attr!(LateContext);
711 }
712
713 fn check_match_bool(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
714     // Type of expression is `bool`.
715     if *cx.typeck_results().expr_ty(ex).kind() == ty::Bool {
716         span_lint_and_then(
717             cx,
718             MATCH_BOOL,
719             expr.span,
720             "you seem to be trying to match on a boolean expression",
721             move |diag| {
722                 if arms.len() == 2 {
723                     // no guards
724                     let exprs = if let PatKind::Lit(arm_bool) = arms[0].pat.kind {
725                         if let ExprKind::Lit(ref lit) = arm_bool.kind {
726                             match lit.node {
727                                 LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
728                                 LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
729                                 _ => None,
730                             }
731                         } else {
732                             None
733                         }
734                     } else {
735                         None
736                     };
737
738                     if let Some((true_expr, false_expr)) = exprs {
739                         let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
740                             (false, false) => Some(format!(
741                                 "if {} {} else {}",
742                                 snippet(cx, ex.span, "b"),
743                                 expr_block(cx, true_expr, None, "..", Some(expr.span)),
744                                 expr_block(cx, false_expr, None, "..", Some(expr.span))
745                             )),
746                             (false, true) => Some(format!(
747                                 "if {} {}",
748                                 snippet(cx, ex.span, "b"),
749                                 expr_block(cx, true_expr, None, "..", Some(expr.span))
750                             )),
751                             (true, false) => {
752                                 let test = Sugg::hir(cx, ex, "..");
753                                 Some(format!(
754                                     "if {} {}",
755                                     !test,
756                                     expr_block(cx, false_expr, None, "..", Some(expr.span))
757                                 ))
758                             },
759                             (true, true) => None,
760                         };
761
762                         if let Some(sugg) = sugg {
763                             diag.span_suggestion(
764                                 expr.span,
765                                 "consider using an `if`/`else` expression",
766                                 sugg,
767                                 Applicability::HasPlaceholders,
768                             );
769                         }
770                     }
771                 }
772             },
773         );
774     }
775 }
776
777 fn check_overlapping_arms<'tcx>(cx: &LateContext<'tcx>, ex: &'tcx Expr<'_>, arms: &'tcx [Arm<'_>]) {
778     if arms.len() >= 2 && cx.typeck_results().expr_ty(ex).is_integral() {
779         let ranges = all_ranges(cx, arms, cx.typeck_results().expr_ty(ex));
780         if !ranges.is_empty() {
781             if let Some((start, end)) = overlapping(&ranges) {
782                 span_lint_and_note(
783                     cx,
784                     MATCH_OVERLAPPING_ARM,
785                     start.span,
786                     "some ranges overlap",
787                     Some(end.span),
788                     "overlaps with this",
789                 );
790             }
791         }
792     }
793 }
794
795 fn check_wild_err_arm<'tcx>(cx: &LateContext<'tcx>, ex: &Expr<'tcx>, arms: &[Arm<'tcx>]) {
796     let ex_ty = cx.typeck_results().expr_ty(ex).peel_refs();
797     if is_type_diagnostic_item(cx, ex_ty, sym::Result) {
798         for arm in arms {
799             if let PatKind::TupleStruct(ref path, inner, _) = arm.pat.kind {
800                 let path_str = rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false));
801                 if path_str == "Err" {
802                     let mut matching_wild = inner.iter().any(is_wild);
803                     let mut ident_bind_name = kw::Underscore;
804                     if !matching_wild {
805                         // Looking for unused bindings (i.e.: `_e`)
806                         for pat in inner.iter() {
807                             if let PatKind::Binding(_, id, ident, None) = pat.kind {
808                                 if ident.as_str().starts_with('_') && !is_local_used(cx, arm.body, id) {
809                                     ident_bind_name = ident.name;
810                                     matching_wild = true;
811                                 }
812                             }
813                         }
814                     }
815                     if_chain! {
816                         if matching_wild;
817                         if let Some(macro_call) = root_macro_call(peel_blocks_with_stmt(arm.body).span);
818                         if is_panic(cx, macro_call.def_id);
819                         then {
820                             // `Err(_)` or `Err(_e)` arm with `panic!` found
821                             span_lint_and_note(cx,
822                                 MATCH_WILD_ERR_ARM,
823                                 arm.pat.span,
824                                 &format!("`Err({})` matches all errors", ident_bind_name),
825                                 None,
826                                 "match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable",
827                             );
828                         }
829                     }
830                 }
831             }
832         }
833     }
834 }
835
836 enum CommonPrefixSearcher<'a> {
837     None,
838     Path(&'a [PathSegment<'a>]),
839     Mixed,
840 }
841 impl<'a> CommonPrefixSearcher<'a> {
842     fn with_path(&mut self, path: &'a [PathSegment<'a>]) {
843         match path {
844             [path @ .., _] => self.with_prefix(path),
845             [] => (),
846         }
847     }
848
849     fn with_prefix(&mut self, path: &'a [PathSegment<'a>]) {
850         match self {
851             Self::None => *self = Self::Path(path),
852             Self::Path(self_path)
853                 if path
854                     .iter()
855                     .map(|p| p.ident.name)
856                     .eq(self_path.iter().map(|p| p.ident.name)) => {},
857             Self::Path(_) => *self = Self::Mixed,
858             Self::Mixed => (),
859         }
860     }
861 }
862
863 fn is_hidden(cx: &LateContext<'_>, variant_def: &VariantDef) -> bool {
864     let attrs = cx.tcx.get_attrs(variant_def.def_id);
865     clippy_utils::attrs::is_doc_hidden(attrs) || clippy_utils::attrs::is_unstable(attrs)
866 }
867
868 #[allow(clippy::too_many_lines)]
869 fn check_wild_enum_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>]) {
870     let ty = cx.typeck_results().expr_ty(ex).peel_refs();
871     let adt_def = match ty.kind() {
872         ty::Adt(adt_def, _)
873             if adt_def.is_enum()
874                 && !(is_type_diagnostic_item(cx, ty, sym::Option) || is_type_diagnostic_item(cx, ty, sym::Result)) =>
875         {
876             adt_def
877         },
878         _ => return,
879     };
880
881     // First pass - check for violation, but don't do much book-keeping because this is hopefully
882     // the uncommon case, and the book-keeping is slightly expensive.
883     let mut wildcard_span = None;
884     let mut wildcard_ident = None;
885     let mut has_non_wild = false;
886     for arm in arms {
887         match peel_hir_pat_refs(arm.pat).0.kind {
888             PatKind::Wild => wildcard_span = Some(arm.pat.span),
889             PatKind::Binding(_, _, ident, None) => {
890                 wildcard_span = Some(arm.pat.span);
891                 wildcard_ident = Some(ident);
892             },
893             _ => has_non_wild = true,
894         }
895     }
896     let wildcard_span = match wildcard_span {
897         Some(x) if has_non_wild => x,
898         _ => return,
899     };
900
901     // Accumulate the variants which should be put in place of the wildcard because they're not
902     // already covered.
903     let has_hidden = adt_def.variants.iter().any(|x| is_hidden(cx, x));
904     let mut missing_variants: Vec<_> = adt_def.variants.iter().filter(|x| !is_hidden(cx, x)).collect();
905
906     let mut path_prefix = CommonPrefixSearcher::None;
907     for arm in arms {
908         // Guards mean that this case probably isn't exhaustively covered. Technically
909         // this is incorrect, as we should really check whether each variant is exhaustively
910         // covered by the set of guards that cover it, but that's really hard to do.
911         recurse_or_patterns(arm.pat, |pat| {
912             let path = match &peel_hir_pat_refs(pat).0.kind {
913                 PatKind::Path(path) => {
914                     #[allow(clippy::match_same_arms)]
915                     let id = match cx.qpath_res(path, pat.hir_id) {
916                         Res::Def(
917                             DefKind::Const | DefKind::ConstParam | DefKind::AnonConst | DefKind::InlineConst,
918                             _,
919                         ) => return,
920                         Res::Def(_, id) => id,
921                         _ => return,
922                     };
923                     if arm.guard.is_none() {
924                         missing_variants.retain(|e| e.ctor_def_id != Some(id));
925                     }
926                     path
927                 },
928                 PatKind::TupleStruct(path, patterns, ..) => {
929                     if let Some(id) = cx.qpath_res(path, pat.hir_id).opt_def_id() {
930                         if arm.guard.is_none() && patterns.iter().all(|p| !is_refutable(cx, p)) {
931                             missing_variants.retain(|e| e.ctor_def_id != Some(id));
932                         }
933                     }
934                     path
935                 },
936                 PatKind::Struct(path, patterns, ..) => {
937                     if let Some(id) = cx.qpath_res(path, pat.hir_id).opt_def_id() {
938                         if arm.guard.is_none() && patterns.iter().all(|p| !is_refutable(cx, p.pat)) {
939                             missing_variants.retain(|e| e.def_id != id);
940                         }
941                     }
942                     path
943                 },
944                 _ => return,
945             };
946             match path {
947                 QPath::Resolved(_, path) => path_prefix.with_path(path.segments),
948                 QPath::TypeRelative(
949                     hir::Ty {
950                         kind: TyKind::Path(QPath::Resolved(_, path)),
951                         ..
952                     },
953                     _,
954                 ) => path_prefix.with_prefix(path.segments),
955                 _ => (),
956             }
957         });
958     }
959
960     let format_suggestion = |variant: &VariantDef| {
961         format!(
962             "{}{}{}{}",
963             if let Some(ident) = wildcard_ident {
964                 format!("{} @ ", ident.name)
965             } else {
966                 String::new()
967             },
968             if let CommonPrefixSearcher::Path(path_prefix) = path_prefix {
969                 let mut s = String::new();
970                 for seg in path_prefix {
971                     s.push_str(seg.ident.as_str());
972                     s.push_str("::");
973                 }
974                 s
975             } else {
976                 let mut s = cx.tcx.def_path_str(adt_def.did);
977                 s.push_str("::");
978                 s
979             },
980             variant.name,
981             match variant.ctor_kind {
982                 CtorKind::Fn if variant.fields.len() == 1 => "(_)",
983                 CtorKind::Fn => "(..)",
984                 CtorKind::Const => "",
985                 CtorKind::Fictive => "{ .. }",
986             }
987         )
988     };
989
990     match missing_variants.as_slice() {
991         [] => (),
992         [x] if !adt_def.is_variant_list_non_exhaustive() && !has_hidden => span_lint_and_sugg(
993             cx,
994             MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
995             wildcard_span,
996             "wildcard matches only a single variant and will also match any future added variants",
997             "try this",
998             format_suggestion(x),
999             Applicability::MaybeIncorrect,
1000         ),
1001         variants => {
1002             let mut suggestions: Vec<_> = variants.iter().copied().map(format_suggestion).collect();
1003             let message = if adt_def.is_variant_list_non_exhaustive() || has_hidden {
1004                 suggestions.push("_".into());
1005                 "wildcard matches known variants and will also match future added variants"
1006             } else {
1007                 "wildcard match will also match any future added variants"
1008             };
1009
1010             span_lint_and_sugg(
1011                 cx,
1012                 WILDCARD_ENUM_MATCH_ARM,
1013                 wildcard_span,
1014                 message,
1015                 "try this",
1016                 suggestions.join(" | "),
1017                 Applicability::MaybeIncorrect,
1018             );
1019         },
1020     };
1021 }
1022
1023 fn check_match_ref_pats<'a, 'b, I>(cx: &LateContext<'_>, ex: &Expr<'_>, pats: I, expr: &Expr<'_>)
1024 where
1025     'b: 'a,
1026     I: Clone + Iterator<Item = &'a Pat<'b>>,
1027 {
1028     if !has_multiple_ref_pats(pats.clone()) {
1029         return;
1030     }
1031
1032     let (first_sugg, msg, title);
1033     let span = ex.span.source_callsite();
1034     if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, inner) = ex.kind {
1035         first_sugg = once((span, Sugg::hir_with_macro_callsite(cx, inner, "..").to_string()));
1036         msg = "try";
1037         title = "you don't need to add `&` to both the expression and the patterns";
1038     } else {
1039         first_sugg = once((span, Sugg::hir_with_macro_callsite(cx, ex, "..").deref().to_string()));
1040         msg = "instead of prefixing all patterns with `&`, you can dereference the expression";
1041         title = "you don't need to add `&` to all patterns";
1042     }
1043
1044     let remaining_suggs = pats.filter_map(|pat| {
1045         if let PatKind::Ref(refp, _) = pat.kind {
1046             Some((pat.span, snippet(cx, refp.span, "..").to_string()))
1047         } else {
1048             None
1049         }
1050     });
1051
1052     span_lint_and_then(cx, MATCH_REF_PATS, expr.span, title, |diag| {
1053         if !expr.span.from_expansion() {
1054             multispan_sugg(diag, msg, first_sugg.chain(remaining_suggs));
1055         }
1056     });
1057 }
1058
1059 fn check_match_as_ref(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1060     if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
1061         let arm_ref: Option<BindingAnnotation> = if is_none_arm(cx, &arms[0]) {
1062             is_ref_some_arm(cx, &arms[1])
1063         } else if is_none_arm(cx, &arms[1]) {
1064             is_ref_some_arm(cx, &arms[0])
1065         } else {
1066             None
1067         };
1068         if let Some(rb) = arm_ref {
1069             let suggestion = if rb == BindingAnnotation::Ref {
1070                 "as_ref"
1071             } else {
1072                 "as_mut"
1073             };
1074
1075             let output_ty = cx.typeck_results().expr_ty(expr);
1076             let input_ty = cx.typeck_results().expr_ty(ex);
1077
1078             let cast = if_chain! {
1079                 if let ty::Adt(_, substs) = input_ty.kind();
1080                 let input_ty = substs.type_at(0);
1081                 if let ty::Adt(_, substs) = output_ty.kind();
1082                 let output_ty = substs.type_at(0);
1083                 if let ty::Ref(_, output_ty, _) = *output_ty.kind();
1084                 if input_ty != output_ty;
1085                 then {
1086                     ".map(|x| x as _)"
1087                 } else {
1088                     ""
1089                 }
1090             };
1091
1092             let mut applicability = Applicability::MachineApplicable;
1093             span_lint_and_sugg(
1094                 cx,
1095                 MATCH_AS_REF,
1096                 expr.span,
1097                 &format!("use `{}()` instead", suggestion),
1098                 "try this",
1099                 format!(
1100                     "{}.{}(){}",
1101                     snippet_with_applicability(cx, ex.span, "_", &mut applicability),
1102                     suggestion,
1103                     cast,
1104                 ),
1105                 applicability,
1106             );
1107         }
1108     }
1109 }
1110
1111 fn check_wild_in_or_pats(cx: &LateContext<'_>, arms: &[Arm<'_>]) {
1112     for arm in arms {
1113         if let PatKind::Or(fields) = arm.pat.kind {
1114             // look for multiple fields in this arm that contains at least one Wild pattern
1115             if fields.len() > 1 && fields.iter().any(is_wild) {
1116                 span_lint_and_help(
1117                     cx,
1118                     WILDCARD_IN_OR_PATTERNS,
1119                     arm.pat.span,
1120                     "wildcard pattern covers any other pattern as it will match anyway",
1121                     None,
1122                     "consider handling `_` separately",
1123                 );
1124             }
1125         }
1126     }
1127 }
1128
1129 #[allow(clippy::too_many_lines)]
1130 fn check_match_single_binding<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1131     if expr.span.from_expansion() || arms.len() != 1 || is_refutable(cx, arms[0].pat) {
1132         return;
1133     }
1134
1135     // HACK:
1136     // This is a hack to deal with arms that are excluded by macros like `#[cfg]`. It is only used here
1137     // to prevent false positives as there is currently no better way to detect if code was excluded by
1138     // a macro. See PR #6435
1139     if_chain! {
1140         if let Some(match_snippet) = snippet_opt(cx, expr.span);
1141         if let Some(arm_snippet) = snippet_opt(cx, arms[0].span);
1142         if let Some(ex_snippet) = snippet_opt(cx, ex.span);
1143         let rest_snippet = match_snippet.replace(&arm_snippet, "").replace(&ex_snippet, "");
1144         if rest_snippet.contains("=>");
1145         then {
1146             // The code it self contains another thick arrow "=>"
1147             // -> Either another arm or a comment
1148             return;
1149         }
1150     }
1151
1152     let matched_vars = ex.span;
1153     let bind_names = arms[0].pat.span;
1154     let match_body = peel_blocks(arms[0].body);
1155     let mut snippet_body = if match_body.span.from_expansion() {
1156         Sugg::hir_with_macro_callsite(cx, match_body, "..").to_string()
1157     } else {
1158         snippet_block(cx, match_body.span, "..", Some(expr.span)).to_string()
1159     };
1160
1161     // Do we need to add ';' to suggestion ?
1162     match match_body.kind {
1163         ExprKind::Block(block, _) => {
1164             // macro + expr_ty(body) == ()
1165             if block.span.from_expansion() && cx.typeck_results().expr_ty(match_body).is_unit() {
1166                 snippet_body.push(';');
1167             }
1168         },
1169         _ => {
1170             // expr_ty(body) == ()
1171             if cx.typeck_results().expr_ty(match_body).is_unit() {
1172                 snippet_body.push(';');
1173             }
1174         },
1175     }
1176
1177     let mut applicability = Applicability::MaybeIncorrect;
1178     match arms[0].pat.kind {
1179         PatKind::Binding(..) | PatKind::Tuple(_, _) | PatKind::Struct(..) => {
1180             // If this match is in a local (`let`) stmt
1181             let (target_span, sugg) = if let Some(parent_let_node) = opt_parent_let(cx, ex) {
1182                 (
1183                     parent_let_node.span,
1184                     format!(
1185                         "let {} = {};\n{}let {} = {};",
1186                         snippet_with_applicability(cx, bind_names, "..", &mut applicability),
1187                         snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
1188                         " ".repeat(indent_of(cx, expr.span).unwrap_or(0)),
1189                         snippet_with_applicability(cx, parent_let_node.pat.span, "..", &mut applicability),
1190                         snippet_body
1191                     ),
1192                 )
1193             } else {
1194                 // If we are in closure, we need curly braces around suggestion
1195                 let mut indent = " ".repeat(indent_of(cx, ex.span).unwrap_or(0));
1196                 let (mut cbrace_start, mut cbrace_end) = ("".to_string(), "".to_string());
1197                 if let Some(parent_expr) = get_parent_expr(cx, expr) {
1198                     if let ExprKind::Closure(..) = parent_expr.kind {
1199                         cbrace_end = format!("\n{}}}", indent);
1200                         // Fix body indent due to the closure
1201                         indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0));
1202                         cbrace_start = format!("{{\n{}", indent);
1203                     }
1204                 }
1205                 // If the parent is already an arm, and the body is another match statement,
1206                 // we need curly braces around suggestion
1207                 let parent_node_id = cx.tcx.hir().get_parent_node(expr.hir_id);
1208                 if let Node::Arm(arm) = &cx.tcx.hir().get(parent_node_id) {
1209                     if let ExprKind::Match(..) = arm.body.kind {
1210                         cbrace_end = format!("\n{}}}", indent);
1211                         // Fix body indent due to the match
1212                         indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0));
1213                         cbrace_start = format!("{{\n{}", indent);
1214                     }
1215                 }
1216                 (
1217                     expr.span,
1218                     format!(
1219                         "{}let {} = {};\n{}{}{}",
1220                         cbrace_start,
1221                         snippet_with_applicability(cx, bind_names, "..", &mut applicability),
1222                         snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
1223                         indent,
1224                         snippet_body,
1225                         cbrace_end
1226                     ),
1227                 )
1228             };
1229             span_lint_and_sugg(
1230                 cx,
1231                 MATCH_SINGLE_BINDING,
1232                 target_span,
1233                 "this match could be written as a `let` statement",
1234                 "consider using `let` statement",
1235                 sugg,
1236                 applicability,
1237             );
1238         },
1239         PatKind::Wild => {
1240             if ex.can_have_side_effects() {
1241                 let indent = " ".repeat(indent_of(cx, expr.span).unwrap_or(0));
1242                 let sugg = format!(
1243                     "{};\n{}{}",
1244                     snippet_with_applicability(cx, ex.span, "..", &mut applicability),
1245                     indent,
1246                     snippet_body
1247                 );
1248                 span_lint_and_sugg(
1249                     cx,
1250                     MATCH_SINGLE_BINDING,
1251                     expr.span,
1252                     "this match could be replaced by its scrutinee and body",
1253                     "consider using the scrutinee and body instead",
1254                     sugg,
1255                     applicability,
1256                 );
1257             } else {
1258                 span_lint_and_sugg(
1259                     cx,
1260                     MATCH_SINGLE_BINDING,
1261                     expr.span,
1262                     "this match could be replaced by its body itself",
1263                     "consider using the match body instead",
1264                     snippet_body,
1265                     Applicability::MachineApplicable,
1266                 );
1267             }
1268         },
1269         _ => (),
1270     }
1271 }
1272
1273 /// Returns true if the `ex` match expression is in a local (`let`) statement
1274 fn opt_parent_let<'a>(cx: &LateContext<'a>, ex: &Expr<'a>) -> Option<&'a Local<'a>> {
1275     let map = &cx.tcx.hir();
1276     if_chain! {
1277         if let Some(Node::Expr(parent_arm_expr)) = map.find(map.get_parent_node(ex.hir_id));
1278         if let Some(Node::Local(parent_let_expr)) = map.find(map.get_parent_node(parent_arm_expr.hir_id));
1279         then {
1280             return Some(parent_let_expr);
1281         }
1282     }
1283     None
1284 }
1285
1286 /// Gets the ranges for each range pattern arm. Applies `ty` bounds for open ranges.
1287 fn all_ranges<'tcx>(cx: &LateContext<'tcx>, arms: &'tcx [Arm<'_>], ty: Ty<'tcx>) -> Vec<SpannedRange<FullInt>> {
1288     arms.iter()
1289         .filter_map(|arm| {
1290             if let Arm { pat, guard: None, .. } = *arm {
1291                 if let PatKind::Range(ref lhs, ref rhs, range_end) = pat.kind {
1292                     let lhs_const = match lhs {
1293                         Some(lhs) => constant(cx, cx.typeck_results(), lhs)?.0,
1294                         None => miri_to_const(ty.numeric_min_val(cx.tcx)?)?,
1295                     };
1296                     let rhs_const = match rhs {
1297                         Some(rhs) => constant(cx, cx.typeck_results(), rhs)?.0,
1298                         None => miri_to_const(ty.numeric_max_val(cx.tcx)?)?,
1299                     };
1300
1301                     let lhs_val = lhs_const.int_value(cx, ty)?;
1302                     let rhs_val = rhs_const.int_value(cx, ty)?;
1303
1304                     let rhs_bound = match range_end {
1305                         RangeEnd::Included => EndBound::Included(rhs_val),
1306                         RangeEnd::Excluded => EndBound::Excluded(rhs_val),
1307                     };
1308                     return Some(SpannedRange {
1309                         span: pat.span,
1310                         node: (lhs_val, rhs_bound),
1311                     });
1312                 }
1313
1314                 if let PatKind::Lit(value) = pat.kind {
1315                     let value = constant_full_int(cx, cx.typeck_results(), value)?;
1316                     return Some(SpannedRange {
1317                         span: pat.span,
1318                         node: (value, EndBound::Included(value)),
1319                     });
1320                 }
1321             }
1322             None
1323         })
1324         .collect()
1325 }
1326
1327 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
1328 pub enum EndBound<T> {
1329     Included(T),
1330     Excluded(T),
1331 }
1332
1333 #[derive(Debug, Eq, PartialEq)]
1334 struct SpannedRange<T> {
1335     pub span: Span,
1336     pub node: (T, EndBound<T>),
1337 }
1338
1339 // Checks if arm has the form `None => None`
1340 fn is_none_arm(cx: &LateContext<'_>, arm: &Arm<'_>) -> bool {
1341     matches!(arm.pat.kind, PatKind::Path(ref qpath) if is_lang_ctor(cx, qpath, OptionNone))
1342 }
1343
1344 // Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`)
1345 fn is_ref_some_arm(cx: &LateContext<'_>, arm: &Arm<'_>) -> Option<BindingAnnotation> {
1346     if_chain! {
1347         if let PatKind::TupleStruct(ref qpath, [first_pat, ..], _) = arm.pat.kind;
1348         if is_lang_ctor(cx, qpath, OptionSome);
1349         if let PatKind::Binding(rb, .., ident, _) = first_pat.kind;
1350         if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
1351         if let ExprKind::Call(e, args) = peel_blocks(arm.body).kind;
1352         if let ExprKind::Path(ref some_path) = e.kind;
1353         if is_lang_ctor(cx, some_path, OptionSome) && args.len() == 1;
1354         if let ExprKind::Path(QPath::Resolved(_, path2)) = args[0].kind;
1355         if path2.segments.len() == 1 && ident.name == path2.segments[0].ident.name;
1356         then {
1357             return Some(rb)
1358         }
1359     }
1360     None
1361 }
1362
1363 fn has_multiple_ref_pats<'a, 'b, I>(pats: I) -> bool
1364 where
1365     'b: 'a,
1366     I: Iterator<Item = &'a Pat<'b>>,
1367 {
1368     let mut ref_count = 0;
1369     for opt in pats.map(|pat| match pat.kind {
1370         PatKind::Ref(..) => Some(true), // &-patterns
1371         PatKind::Wild => Some(false),   // an "anything" wildcard is also fine
1372         _ => None,                      // any other pattern is not fine
1373     }) {
1374         if let Some(inner) = opt {
1375             if inner {
1376                 ref_count += 1;
1377             }
1378         } else {
1379             return false;
1380         }
1381     }
1382     ref_count > 1
1383 }
1384
1385 fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
1386 where
1387     T: Copy + Ord,
1388 {
1389     #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
1390     enum BoundKind {
1391         EndExcluded,
1392         Start,
1393         EndIncluded,
1394     }
1395
1396     #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1397     struct RangeBound<'a, T>(T, BoundKind, &'a SpannedRange<T>);
1398
1399     impl<'a, T: Copy + Ord> PartialOrd for RangeBound<'a, T> {
1400         fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1401             Some(self.cmp(other))
1402         }
1403     }
1404
1405     impl<'a, T: Copy + Ord> Ord for RangeBound<'a, T> {
1406         fn cmp(&self, RangeBound(other_value, other_kind, _): &Self) -> Ordering {
1407             let RangeBound(self_value, self_kind, _) = *self;
1408             (self_value, self_kind).cmp(&(*other_value, *other_kind))
1409         }
1410     }
1411
1412     let mut values = Vec::with_capacity(2 * ranges.len());
1413
1414     for r @ SpannedRange { node: (start, end), .. } in ranges {
1415         values.push(RangeBound(*start, BoundKind::Start, r));
1416         values.push(match end {
1417             EndBound::Excluded(val) => RangeBound(*val, BoundKind::EndExcluded, r),
1418             EndBound::Included(val) => RangeBound(*val, BoundKind::EndIncluded, r),
1419         });
1420     }
1421
1422     values.sort();
1423
1424     let mut started = vec![];
1425
1426     for RangeBound(_, kind, range) in values {
1427         match kind {
1428             BoundKind::Start => started.push(range),
1429             BoundKind::EndExcluded | BoundKind::EndIncluded => {
1430                 let mut overlap = None;
1431
1432                 while let Some(last_started) = started.pop() {
1433                     if last_started == range {
1434                         break;
1435                     }
1436                     overlap = Some(last_started);
1437                 }
1438
1439                 if let Some(first_overlapping) = overlap {
1440                     return Some((range, first_overlapping));
1441                 }
1442             },
1443         }
1444     }
1445
1446     None
1447 }
1448
1449 #[test]
1450 fn test_overlapping() {
1451     use rustc_span::source_map::DUMMY_SP;
1452
1453     let sp = |s, e| SpannedRange {
1454         span: DUMMY_SP,
1455         node: (s, e),
1456     };
1457
1458     assert_eq!(None, overlapping::<u8>(&[]));
1459     assert_eq!(None, overlapping(&[sp(1, EndBound::Included(4))]));
1460     assert_eq!(
1461         None,
1462         overlapping(&[sp(1, EndBound::Included(4)), sp(5, EndBound::Included(6))])
1463     );
1464     assert_eq!(
1465         None,
1466         overlapping(&[
1467             sp(1, EndBound::Included(4)),
1468             sp(5, EndBound::Included(6)),
1469             sp(10, EndBound::Included(11))
1470         ],)
1471     );
1472     assert_eq!(
1473         Some((&sp(1, EndBound::Included(4)), &sp(3, EndBound::Included(6)))),
1474         overlapping(&[sp(1, EndBound::Included(4)), sp(3, EndBound::Included(6))])
1475     );
1476     assert_eq!(
1477         Some((&sp(5, EndBound::Included(6)), &sp(6, EndBound::Included(11)))),
1478         overlapping(&[
1479             sp(1, EndBound::Included(4)),
1480             sp(5, EndBound::Included(6)),
1481             sp(6, EndBound::Included(11))
1482         ],)
1483     );
1484 }