]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/matches.rs
Improve extract_msrv_attr! situation
[rust.git] / clippy_lints / src / matches.rs
1 use crate::consts::{constant, miri_to_const, Constant};
2 use crate::utils::sugg::Sugg;
3 use crate::utils::usage::is_unused;
4 use crate::utils::{
5     expr_block, get_arg_name, get_parent_expr, in_macro, indent_of, is_allowed, is_expn_of, is_refutable,
6     is_type_diagnostic_item, is_wild, match_qpath, match_type, match_var, meets_msrv, multispan_sugg, remove_blocks,
7     snippet, snippet_block, snippet_with_applicability, span_lint_and_help, span_lint_and_note, span_lint_and_sugg,
8     span_lint_and_then,
9 };
10 use crate::utils::{paths, search_same, SpanlessEq, SpanlessHash};
11 use if_chain::if_chain;
12 use rustc_ast::ast::LitKind;
13 use rustc_data_structures::fx::FxHashMap;
14 use rustc_errors::Applicability;
15 use rustc_hir::def::CtorKind;
16 use rustc_hir::{
17     Arm, BindingAnnotation, Block, BorrowKind, Expr, ExprKind, Guard, Local, MatchSource, Mutability, Node, Pat,
18     PatKind, QPath, RangeEnd,
19 };
20 use rustc_lint::{LateContext, LateLintPass, LintContext};
21 use rustc_middle::lint::in_external_macro;
22 use rustc_middle::ty::{self, Ty, TyS};
23 use rustc_session::{declare_tool_lint, impl_lint_pass};
24 use rustc_span::source_map::{Span, Spanned};
25 use rustc_span::{sym, Symbol};
26 use semver::{Version, VersionReq};
27 use std::cmp::Ordering;
28 use std::collections::hash_map::Entry;
29 use std::collections::Bound;
30
31 declare_clippy_lint! {
32     /// **What it does:** Checks for matches with a single arm where an `if let`
33     /// will usually suffice.
34     ///
35     /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
36     ///
37     /// **Known problems:** None.
38     ///
39     /// **Example:**
40     /// ```rust
41     /// # fn bar(stool: &str) {}
42     /// # let x = Some("abc");
43     /// // Bad
44     /// match x {
45     ///     Some(ref foo) => bar(foo),
46     ///     _ => (),
47     /// }
48     ///
49     /// // Good
50     /// if let Some(ref foo) = x {
51     ///     bar(foo);
52     /// }
53     /// ```
54     pub SINGLE_MATCH,
55     style,
56     "a `match` statement with a single nontrivial arm (i.e., where the other arm is `_ => {}`) instead of `if let`"
57 }
58
59 declare_clippy_lint! {
60     /// **What it does:** Checks for matches with two arms where an `if let else` will
61     /// usually suffice.
62     ///
63     /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
64     ///
65     /// **Known problems:** Personal style preferences may differ.
66     ///
67     /// **Example:**
68     ///
69     /// Using `match`:
70     ///
71     /// ```rust
72     /// # fn bar(foo: &usize) {}
73     /// # let other_ref: usize = 1;
74     /// # let x: Option<&usize> = Some(&1);
75     /// match x {
76     ///     Some(ref foo) => bar(foo),
77     ///     _ => bar(&other_ref),
78     /// }
79     /// ```
80     ///
81     /// Using `if let` with `else`:
82     ///
83     /// ```rust
84     /// # fn bar(foo: &usize) {}
85     /// # let other_ref: usize = 1;
86     /// # let x: Option<&usize> = Some(&1);
87     /// if let Some(ref foo) = x {
88     ///     bar(foo);
89     /// } else {
90     ///     bar(&other_ref);
91     /// }
92     /// ```
93     pub SINGLE_MATCH_ELSE,
94     pedantic,
95     "a `match` statement with two arms where the second arm's pattern is a placeholder instead of a specific match pattern"
96 }
97
98 declare_clippy_lint! {
99     /// **What it does:** Checks for matches where all arms match a reference,
100     /// suggesting to remove the reference and deref the matched expression
101     /// instead. It also checks for `if let &foo = bar` blocks.
102     ///
103     /// **Why is this bad?** It just makes the code less readable. That reference
104     /// destructuring adds nothing to the code.
105     ///
106     /// **Known problems:** None.
107     ///
108     /// **Example:**
109     /// ```rust,ignore
110     /// // Bad
111     /// match x {
112     ///     &A(ref y) => foo(y),
113     ///     &B => bar(),
114     ///     _ => frob(&x),
115     /// }
116     ///
117     /// // Good
118     /// match *x {
119     ///     A(ref y) => foo(y),
120     ///     B => bar(),
121     ///     _ => frob(x),
122     /// }
123     /// ```
124     pub MATCH_REF_PATS,
125     style,
126     "a `match` or `if let` with all arms prefixed with `&` instead of deref-ing the match expression"
127 }
128
129 declare_clippy_lint! {
130     /// **What it does:** Checks for matches where match expression is a `bool`. It
131     /// suggests to replace the expression with an `if...else` block.
132     ///
133     /// **Why is this bad?** It makes the code less readable.
134     ///
135     /// **Known problems:** None.
136     ///
137     /// **Example:**
138     /// ```rust
139     /// # fn foo() {}
140     /// # fn bar() {}
141     /// let condition: bool = true;
142     /// match condition {
143     ///     true => foo(),
144     ///     false => bar(),
145     /// }
146     /// ```
147     /// Use if/else instead:
148     /// ```rust
149     /// # fn foo() {}
150     /// # fn bar() {}
151     /// let condition: bool = true;
152     /// if condition {
153     ///     foo();
154     /// } else {
155     ///     bar();
156     /// }
157     /// ```
158     pub MATCH_BOOL,
159     pedantic,
160     "a `match` on a boolean expression instead of an `if..else` block"
161 }
162
163 declare_clippy_lint! {
164     /// **What it does:** Checks for overlapping match arms.
165     ///
166     /// **Why is this bad?** It is likely to be an error and if not, makes the code
167     /// less obvious.
168     ///
169     /// **Known problems:** None.
170     ///
171     /// **Example:**
172     /// ```rust
173     /// let x = 5;
174     /// match x {
175     ///     1...10 => println!("1 ... 10"),
176     ///     5...15 => println!("5 ... 15"),
177     ///     _ => (),
178     /// }
179     /// ```
180     pub MATCH_OVERLAPPING_ARM,
181     style,
182     "a `match` with overlapping arms"
183 }
184
185 declare_clippy_lint! {
186     /// **What it does:** Checks for arm which matches all errors with `Err(_)`
187     /// and take drastic actions like `panic!`.
188     ///
189     /// **Why is this bad?** It is generally a bad practice, similar to
190     /// catching all exceptions in java with `catch(Exception)`
191     ///
192     /// **Known problems:** None.
193     ///
194     /// **Example:**
195     /// ```rust
196     /// let x: Result<i32, &str> = Ok(3);
197     /// match x {
198     ///     Ok(_) => println!("ok"),
199     ///     Err(_) => panic!("err"),
200     /// }
201     /// ```
202     pub MATCH_WILD_ERR_ARM,
203     pedantic,
204     "a `match` with `Err(_)` arm and take drastic actions"
205 }
206
207 declare_clippy_lint! {
208     /// **What it does:** Checks for match which is used to add a reference to an
209     /// `Option` value.
210     ///
211     /// **Why is this bad?** Using `as_ref()` or `as_mut()` instead is shorter.
212     ///
213     /// **Known problems:** None.
214     ///
215     /// **Example:**
216     /// ```rust
217     /// let x: Option<()> = None;
218     ///
219     /// // Bad
220     /// let r: Option<&()> = match x {
221     ///     None => None,
222     ///     Some(ref v) => Some(v),
223     /// };
224     ///
225     /// // Good
226     /// let r: Option<&()> = x.as_ref();
227     /// ```
228     pub MATCH_AS_REF,
229     complexity,
230     "a `match` on an Option value instead of using `as_ref()` or `as_mut`"
231 }
232
233 declare_clippy_lint! {
234     /// **What it does:** Checks for wildcard enum matches using `_`.
235     ///
236     /// **Why is this bad?** New enum variants added by library updates can be missed.
237     ///
238     /// **Known problems:** Suggested replacements may be incorrect if guards exhaustively cover some
239     /// variants, and also may not use correct path to enum if it's not present in the current scope.
240     ///
241     /// **Example:**
242     /// ```rust
243     /// # enum Foo { A(usize), B(usize) }
244     /// # let x = Foo::B(1);
245     /// // Bad
246     /// match x {
247     ///     Foo::A(_) => {},
248     ///     _ => {},
249     /// }
250     ///
251     /// // Good
252     /// match x {
253     ///     Foo::A(_) => {},
254     ///     Foo::B(_) => {},
255     /// }
256     /// ```
257     pub WILDCARD_ENUM_MATCH_ARM,
258     restriction,
259     "a wildcard enum match arm using `_`"
260 }
261
262 declare_clippy_lint! {
263     /// **What it does:** Checks for wildcard enum matches for a single variant.
264     ///
265     /// **Why is this bad?** New enum variants added by library updates can be missed.
266     ///
267     /// **Known problems:** Suggested replacements may not use correct path to enum
268     /// if it's not present in the current scope.
269     ///
270     /// **Example:**
271     ///
272     /// ```rust
273     /// # enum Foo { A, B, C }
274     /// # let x = Foo::B;
275     /// // Bad
276     /// match x {
277     ///     Foo::A => {},
278     ///     Foo::B => {},
279     ///     _ => {},
280     /// }
281     ///
282     /// // Good
283     /// match x {
284     ///     Foo::A => {},
285     ///     Foo::B => {},
286     ///     Foo::C => {},
287     /// }
288     /// ```
289     pub MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
290     pedantic,
291     "a wildcard enum match for a single variant"
292 }
293
294 declare_clippy_lint! {
295     /// **What it does:** Checks for wildcard pattern used with others patterns in same match arm.
296     ///
297     /// **Why is this bad?** Wildcard pattern already covers any other pattern as it will match anyway.
298     /// It makes the code less readable, especially to spot wildcard pattern use in match arm.
299     ///
300     /// **Known problems:** None.
301     ///
302     /// **Example:**
303     /// ```rust
304     /// // Bad
305     /// match "foo" {
306     ///     "a" => {},
307     ///     "bar" | _ => {},
308     /// }
309     ///
310     /// // Good
311     /// match "foo" {
312     ///     "a" => {},
313     ///     _ => {},
314     /// }
315     /// ```
316     pub WILDCARD_IN_OR_PATTERNS,
317     complexity,
318     "a wildcard pattern used with others patterns in same match arm"
319 }
320
321 declare_clippy_lint! {
322     /// **What it does:** Checks for matches being used to destructure a single-variant enum
323     /// or tuple struct where a `let` will suffice.
324     ///
325     /// **Why is this bad?** Just readability – `let` doesn't nest, whereas a `match` does.
326     ///
327     /// **Known problems:** None.
328     ///
329     /// **Example:**
330     /// ```rust
331     /// enum Wrapper {
332     ///     Data(i32),
333     /// }
334     ///
335     /// let wrapper = Wrapper::Data(42);
336     ///
337     /// let data = match wrapper {
338     ///     Wrapper::Data(i) => i,
339     /// };
340     /// ```
341     ///
342     /// The correct use would be:
343     /// ```rust
344     /// enum Wrapper {
345     ///     Data(i32),
346     /// }
347     ///
348     /// let wrapper = Wrapper::Data(42);
349     /// let Wrapper::Data(data) = wrapper;
350     /// ```
351     pub INFALLIBLE_DESTRUCTURING_MATCH,
352     style,
353     "a `match` statement with a single infallible arm instead of a `let`"
354 }
355
356 declare_clippy_lint! {
357     /// **What it does:** Checks for useless match that binds to only one value.
358     ///
359     /// **Why is this bad?** Readability and needless complexity.
360     ///
361     /// **Known problems:**  Suggested replacements may be incorrect when `match`
362     /// is actually binding temporary value, bringing a 'dropped while borrowed' error.
363     ///
364     /// **Example:**
365     /// ```rust
366     /// # let a = 1;
367     /// # let b = 2;
368     ///
369     /// // Bad
370     /// match (a, b) {
371     ///     (c, d) => {
372     ///         // useless match
373     ///     }
374     /// }
375     ///
376     /// // Good
377     /// let (c, d) = (a, b);
378     /// ```
379     pub MATCH_SINGLE_BINDING,
380     complexity,
381     "a match with a single binding instead of using `let` statement"
382 }
383
384 declare_clippy_lint! {
385     /// **What it does:** Checks for unnecessary '..' pattern binding on struct when all fields are explicitly matched.
386     ///
387     /// **Why is this bad?** Correctness and readability. It's like having a wildcard pattern after
388     /// matching all enum variants explicitly.
389     ///
390     /// **Known problems:** None.
391     ///
392     /// **Example:**
393     /// ```rust
394     /// # struct A { a: i32 }
395     /// let a = A { a: 5 };
396     ///
397     /// // Bad
398     /// match a {
399     ///     A { a: 5, .. } => {},
400     ///     _ => {},
401     /// }
402     ///
403     /// // Good
404     /// match a {
405     ///     A { a: 5 } => {},
406     ///     _ => {},
407     /// }
408     /// ```
409     pub REST_PAT_IN_FULLY_BOUND_STRUCTS,
410     restriction,
411     "a match on a struct that binds all fields but still uses the wildcard pattern"
412 }
413
414 declare_clippy_lint! {
415     /// **What it does:** Lint for redundant pattern matching over `Result`, `Option` or
416     /// `std::task::Poll`
417     ///
418     /// **Why is this bad?** It's more concise and clear to just use the proper
419     /// utility function
420     ///
421     /// **Known problems:** None.
422     ///
423     /// **Example:**
424     ///
425     /// ```rust
426     /// # use std::task::Poll;
427     /// if let Ok(_) = Ok::<i32, i32>(42) {}
428     /// if let Err(_) = Err::<i32, i32>(42) {}
429     /// if let None = None::<()> {}
430     /// if let Some(_) = Some(42) {}
431     /// if let Poll::Pending = Poll::Pending::<()> {}
432     /// if let Poll::Ready(_) = Poll::Ready(42) {}
433     /// match Ok::<i32, i32>(42) {
434     ///     Ok(_) => true,
435     ///     Err(_) => false,
436     /// };
437     /// ```
438     ///
439     /// The more idiomatic use would be:
440     ///
441     /// ```rust
442     /// # use std::task::Poll;
443     /// if Ok::<i32, i32>(42).is_ok() {}
444     /// if Err::<i32, i32>(42).is_err() {}
445     /// if None::<()>.is_none() {}
446     /// if Some(42).is_some() {}
447     /// if Poll::Pending::<()>.is_pending() {}
448     /// if Poll::Ready(42).is_ready() {}
449     /// Ok::<i32, i32>(42).is_ok();
450     /// ```
451     pub REDUNDANT_PATTERN_MATCHING,
452     style,
453     "use the proper utility function avoiding an `if let`"
454 }
455
456 declare_clippy_lint! {
457     /// **What it does:** Checks for `match`  or `if let` expressions producing a
458     /// `bool` that could be written using `matches!`
459     ///
460     /// **Why is this bad?** Readability and needless complexity.
461     ///
462     /// **Known problems:** None
463     ///
464     /// **Example:**
465     /// ```rust
466     /// let x = Some(5);
467     ///
468     /// // Bad
469     /// let a = match x {
470     ///     Some(0) => true,
471     ///     _ => false,
472     /// };
473     ///
474     /// let a = if let Some(0) = x {
475     ///     true
476     /// } else {
477     ///     false
478     /// };
479     ///
480     /// // Good
481     /// let a = matches!(x, Some(0));
482     /// ```
483     pub MATCH_LIKE_MATCHES_MACRO,
484     style,
485     "a match that could be written with the matches! macro"
486 }
487
488 declare_clippy_lint! {
489     /// **What it does:** Checks for `match` with identical arm bodies.
490     ///
491     /// **Why is this bad?** This is probably a copy & paste error. If arm bodies
492     /// are the same on purpose, you can factor them
493     /// [using `|`](https://doc.rust-lang.org/book/patterns.html#multiple-patterns).
494     ///
495     /// **Known problems:** False positive possible with order dependent `match`
496     /// (see issue
497     /// [#860](https://github.com/rust-lang/rust-clippy/issues/860)).
498     ///
499     /// **Example:**
500     /// ```rust,ignore
501     /// match foo {
502     ///     Bar => bar(),
503     ///     Quz => quz(),
504     ///     Baz => bar(), // <= oops
505     /// }
506     /// ```
507     ///
508     /// This should probably be
509     /// ```rust,ignore
510     /// match foo {
511     ///     Bar => bar(),
512     ///     Quz => quz(),
513     ///     Baz => baz(), // <= fixed
514     /// }
515     /// ```
516     ///
517     /// or if the original code was not a typo:
518     /// ```rust,ignore
519     /// match foo {
520     ///     Bar | Baz => bar(), // <= shows the intent better
521     ///     Quz => quz(),
522     /// }
523     /// ```
524     pub MATCH_SAME_ARMS,
525     pedantic,
526     "`match` with identical arm bodies"
527 }
528
529 #[derive(Default)]
530 pub struct Matches {
531     msrv: Option<VersionReq>,
532     infallible_destructuring_match_linted: bool,
533 }
534
535 impl Matches {
536     #[must_use]
537     pub fn new(msrv: Option<VersionReq>) -> Self {
538         Self {
539             msrv,
540             ..Matches::default()
541         }
542     }
543 }
544
545 impl_lint_pass!(Matches => [
546     SINGLE_MATCH,
547     MATCH_REF_PATS,
548     MATCH_BOOL,
549     SINGLE_MATCH_ELSE,
550     MATCH_OVERLAPPING_ARM,
551     MATCH_WILD_ERR_ARM,
552     MATCH_AS_REF,
553     WILDCARD_ENUM_MATCH_ARM,
554     MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
555     WILDCARD_IN_OR_PATTERNS,
556     MATCH_SINGLE_BINDING,
557     INFALLIBLE_DESTRUCTURING_MATCH,
558     REST_PAT_IN_FULLY_BOUND_STRUCTS,
559     REDUNDANT_PATTERN_MATCHING,
560     MATCH_LIKE_MATCHES_MACRO,
561     MATCH_SAME_ARMS,
562 ]);
563
564 const MATCH_LIKE_MATCHES_MACRO_MSRV: Version = Version {
565     major: 1,
566     minor: 42,
567     patch: 0,
568     pre: Vec::new(),
569     build: Vec::new(),
570 };
571
572 impl<'tcx> LateLintPass<'tcx> for Matches {
573     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
574         if in_external_macro(cx.sess(), expr.span) || in_macro(expr.span) {
575             return;
576         }
577
578         redundant_pattern_match::check(cx, expr);
579
580         if meets_msrv(self.msrv.as_ref(), &MATCH_LIKE_MATCHES_MACRO_MSRV) {
581             if !check_match_like_matches(cx, expr) {
582                 lint_match_arms(cx, expr);
583             }
584         } else {
585             lint_match_arms(cx, expr);
586         }
587
588         if let ExprKind::Match(ref ex, ref arms, MatchSource::Normal) = expr.kind {
589             check_single_match(cx, ex, arms, expr);
590             check_match_bool(cx, ex, arms, expr);
591             check_overlapping_arms(cx, ex, arms);
592             check_wild_err_arm(cx, ex, arms);
593             check_wild_enum_match(cx, ex, arms);
594             check_match_as_ref(cx, ex, arms, expr);
595             check_wild_in_or_pats(cx, arms);
596
597             if self.infallible_destructuring_match_linted {
598                 self.infallible_destructuring_match_linted = false;
599             } else {
600                 check_match_single_binding(cx, ex, arms, expr);
601             }
602         }
603         if let ExprKind::Match(ref ex, ref arms, _) = expr.kind {
604             check_match_ref_pats(cx, ex, arms, expr);
605         }
606     }
607
608     fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'_>) {
609         if_chain! {
610             if !in_external_macro(cx.sess(), local.span);
611             if !in_macro(local.span);
612             if let Some(ref expr) = local.init;
613             if let ExprKind::Match(ref target, ref arms, MatchSource::Normal) = expr.kind;
614             if arms.len() == 1 && arms[0].guard.is_none();
615             if let PatKind::TupleStruct(
616                 QPath::Resolved(None, ref variant_name), ref args, _) = arms[0].pat.kind;
617             if args.len() == 1;
618             if let Some(arg) = get_arg_name(&args[0]);
619             let body = remove_blocks(&arms[0].body);
620             if match_var(body, arg);
621
622             then {
623                 let mut applicability = Applicability::MachineApplicable;
624                 self.infallible_destructuring_match_linted = true;
625                 span_lint_and_sugg(
626                     cx,
627                     INFALLIBLE_DESTRUCTURING_MATCH,
628                     local.span,
629                     "you seem to be trying to use `match` to destructure a single infallible pattern. \
630                     Consider using `let`",
631                     "try this",
632                     format!(
633                         "let {}({}) = {};",
634                         snippet_with_applicability(cx, variant_name.span, "..", &mut applicability),
635                         snippet_with_applicability(cx, local.pat.span, "..", &mut applicability),
636                         snippet_with_applicability(cx, target.span, "..", &mut applicability),
637                     ),
638                     applicability,
639                 );
640             }
641         }
642     }
643
644     fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) {
645         if_chain! {
646             if !in_external_macro(cx.sess(), pat.span);
647             if !in_macro(pat.span);
648             if let PatKind::Struct(ref qpath, fields, true) = pat.kind;
649             if let QPath::Resolved(_, ref path) = qpath;
650             if let Some(def_id) = path.res.opt_def_id();
651             let ty = cx.tcx.type_of(def_id);
652             if let ty::Adt(def, _) = ty.kind();
653             if def.is_struct() || def.is_union();
654             if fields.len() == def.non_enum_variant().fields.len();
655
656             then {
657                 span_lint_and_help(
658                     cx,
659                     REST_PAT_IN_FULLY_BOUND_STRUCTS,
660                     pat.span,
661                     "unnecessary use of `..` pattern in struct binding. All fields were already bound",
662                     None,
663                     "consider removing `..` from this binding",
664                 );
665             }
666         }
667     }
668
669     extract_msrv_attr!(LateContext);
670 }
671
672 #[rustfmt::skip]
673 fn check_single_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
674     if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
675         if in_macro(expr.span) {
676             // Don't lint match expressions present in
677             // macro_rules! block
678             return;
679         }
680         if let PatKind::Or(..) = arms[0].pat.kind {
681             // don't lint for or patterns for now, this makes
682             // the lint noisy in unnecessary situations
683             return;
684         }
685         let els = arms[1].body;
686         let els = if is_unit_expr(remove_blocks(els)) {
687             None
688         } else if let ExprKind::Block(Block { stmts, expr: block_expr, .. }, _) = els.kind {
689             if stmts.len() == 1 && block_expr.is_none() || stmts.is_empty() && block_expr.is_some() {
690                 // single statement/expr "else" block, don't lint
691                 return;
692             } else {
693                 // block with 2+ statements or 1 expr and 1+ statement
694                 Some(els)
695             }
696         } else {
697             // not a block, don't lint
698             return;
699         };
700
701         let ty = cx.typeck_results().expr_ty(ex);
702         if *ty.kind() != ty::Bool || is_allowed(cx, MATCH_BOOL, ex.hir_id) {
703             check_single_match_single_pattern(cx, ex, arms, expr, els);
704             check_single_match_opt_like(cx, ex, arms, expr, ty, els);
705         }
706     }
707 }
708
709 fn check_single_match_single_pattern(
710     cx: &LateContext<'_>,
711     ex: &Expr<'_>,
712     arms: &[Arm<'_>],
713     expr: &Expr<'_>,
714     els: Option<&Expr<'_>>,
715 ) {
716     if is_wild(&arms[1].pat) {
717         report_single_match_single_pattern(cx, ex, arms, expr, els);
718     }
719 }
720
721 fn report_single_match_single_pattern(
722     cx: &LateContext<'_>,
723     ex: &Expr<'_>,
724     arms: &[Arm<'_>],
725     expr: &Expr<'_>,
726     els: Option<&Expr<'_>>,
727 ) {
728     let lint = if els.is_some() { SINGLE_MATCH_ELSE } else { SINGLE_MATCH };
729     let els_str = els.map_or(String::new(), |els| {
730         format!(" else {}", expr_block(cx, els, None, "..", Some(expr.span)))
731     });
732     span_lint_and_sugg(
733         cx,
734         lint,
735         expr.span,
736         "you seem to be trying to use match for destructuring a single pattern. Consider using `if \
737          let`",
738         "try this",
739         format!(
740             "if let {} = {} {}{}",
741             snippet(cx, arms[0].pat.span, ".."),
742             snippet(cx, ex.span, ".."),
743             expr_block(cx, &arms[0].body, None, "..", Some(expr.span)),
744             els_str,
745         ),
746         Applicability::HasPlaceholders,
747     );
748 }
749
750 fn check_single_match_opt_like(
751     cx: &LateContext<'_>,
752     ex: &Expr<'_>,
753     arms: &[Arm<'_>],
754     expr: &Expr<'_>,
755     ty: Ty<'_>,
756     els: Option<&Expr<'_>>,
757 ) {
758     // list of candidate `Enum`s we know will never get any more members
759     let candidates = &[
760         (&paths::COW, "Borrowed"),
761         (&paths::COW, "Cow::Borrowed"),
762         (&paths::COW, "Cow::Owned"),
763         (&paths::COW, "Owned"),
764         (&paths::OPTION, "None"),
765         (&paths::RESULT, "Err"),
766         (&paths::RESULT, "Ok"),
767     ];
768
769     let path = match arms[1].pat.kind {
770         PatKind::TupleStruct(ref path, ref inner, _) => {
771             // Contains any non wildcard patterns (e.g., `Err(err)`)?
772             if !inner.iter().all(is_wild) {
773                 return;
774             }
775             rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false))
776         },
777         PatKind::Binding(BindingAnnotation::Unannotated, .., ident, None) => ident.to_string(),
778         PatKind::Path(ref path) => {
779             rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false))
780         },
781         _ => return,
782     };
783
784     for &(ty_path, pat_path) in candidates {
785         if path == *pat_path && match_type(cx, ty, ty_path) {
786             report_single_match_single_pattern(cx, ex, arms, expr, els);
787         }
788     }
789 }
790
791 fn check_match_bool(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
792     // Type of expression is `bool`.
793     if *cx.typeck_results().expr_ty(ex).kind() == ty::Bool {
794         span_lint_and_then(
795             cx,
796             MATCH_BOOL,
797             expr.span,
798             "you seem to be trying to match on a boolean expression",
799             move |diag| {
800                 if arms.len() == 2 {
801                     // no guards
802                     let exprs = if let PatKind::Lit(ref arm_bool) = arms[0].pat.kind {
803                         if let ExprKind::Lit(ref lit) = arm_bool.kind {
804                             match lit.node {
805                                 LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
806                                 LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
807                                 _ => None,
808                             }
809                         } else {
810                             None
811                         }
812                     } else {
813                         None
814                     };
815
816                     if let Some((true_expr, false_expr)) = exprs {
817                         let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
818                             (false, false) => Some(format!(
819                                 "if {} {} else {}",
820                                 snippet(cx, ex.span, "b"),
821                                 expr_block(cx, true_expr, None, "..", Some(expr.span)),
822                                 expr_block(cx, false_expr, None, "..", Some(expr.span))
823                             )),
824                             (false, true) => Some(format!(
825                                 "if {} {}",
826                                 snippet(cx, ex.span, "b"),
827                                 expr_block(cx, true_expr, None, "..", Some(expr.span))
828                             )),
829                             (true, false) => {
830                                 let test = Sugg::hir(cx, ex, "..");
831                                 Some(format!(
832                                     "if {} {}",
833                                     !test,
834                                     expr_block(cx, false_expr, None, "..", Some(expr.span))
835                                 ))
836                             },
837                             (true, true) => None,
838                         };
839
840                         if let Some(sugg) = sugg {
841                             diag.span_suggestion(
842                                 expr.span,
843                                 "consider using an `if`/`else` expression",
844                                 sugg,
845                                 Applicability::HasPlaceholders,
846                             );
847                         }
848                     }
849                 }
850             },
851         );
852     }
853 }
854
855 fn check_overlapping_arms<'tcx>(cx: &LateContext<'tcx>, ex: &'tcx Expr<'_>, arms: &'tcx [Arm<'_>]) {
856     if arms.len() >= 2 && cx.typeck_results().expr_ty(ex).is_integral() {
857         let ranges = all_ranges(cx, arms, cx.typeck_results().expr_ty(ex));
858         let type_ranges = type_ranges(&ranges);
859         if !type_ranges.is_empty() {
860             if let Some((start, end)) = overlapping(&type_ranges) {
861                 span_lint_and_note(
862                     cx,
863                     MATCH_OVERLAPPING_ARM,
864                     start.span,
865                     "some ranges overlap",
866                     Some(end.span),
867                     "overlaps with this",
868                 );
869             }
870         }
871     }
872 }
873
874 fn check_wild_err_arm(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>]) {
875     let ex_ty = cx.typeck_results().expr_ty(ex).peel_refs();
876     if is_type_diagnostic_item(cx, ex_ty, sym::result_type) {
877         for arm in arms {
878             if let PatKind::TupleStruct(ref path, ref inner, _) = arm.pat.kind {
879                 let path_str = rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false));
880                 if path_str == "Err" {
881                     let mut matching_wild = inner.iter().any(is_wild);
882                     let mut ident_bind_name = String::from("_");
883                     if !matching_wild {
884                         // Looking for unused bindings (i.e.: `_e`)
885                         inner.iter().for_each(|pat| {
886                             if let PatKind::Binding(.., ident, None) = &pat.kind {
887                                 if ident.as_str().starts_with('_') && is_unused(ident, arm.body) {
888                                     ident_bind_name = (&ident.name.as_str()).to_string();
889                                     matching_wild = true;
890                                 }
891                             }
892                         });
893                     }
894                     if_chain! {
895                         if matching_wild;
896                         if let ExprKind::Block(ref block, _) = arm.body.kind;
897                         if is_panic_block(block);
898                         then {
899                             // `Err(_)` or `Err(_e)` arm with `panic!` found
900                             span_lint_and_note(cx,
901                                 MATCH_WILD_ERR_ARM,
902                                 arm.pat.span,
903                                 &format!("`Err({})` matches all errors", &ident_bind_name),
904                                 None,
905                                 "match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable",
906                             );
907                         }
908                     }
909                 }
910             }
911         }
912     }
913 }
914
915 fn check_wild_enum_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>]) {
916     let ty = cx.typeck_results().expr_ty(ex);
917     if !ty.is_enum() {
918         // If there isn't a nice closed set of possible values that can be conveniently enumerated,
919         // don't complain about not enumerating the mall.
920         return;
921     }
922
923     // First pass - check for violation, but don't do much book-keeping because this is hopefully
924     // the uncommon case, and the book-keeping is slightly expensive.
925     let mut wildcard_span = None;
926     let mut wildcard_ident = None;
927     for arm in arms {
928         if let PatKind::Wild = arm.pat.kind {
929             wildcard_span = Some(arm.pat.span);
930         } else if let PatKind::Binding(_, _, ident, None) = arm.pat.kind {
931             wildcard_span = Some(arm.pat.span);
932             wildcard_ident = Some(ident);
933         }
934     }
935
936     if let Some(wildcard_span) = wildcard_span {
937         // Accumulate the variants which should be put in place of the wildcard because they're not
938         // already covered.
939
940         let mut missing_variants = vec![];
941         if let ty::Adt(def, _) = ty.kind() {
942             for variant in &def.variants {
943                 missing_variants.push(variant);
944             }
945         }
946
947         for arm in arms {
948             if arm.guard.is_some() {
949                 // Guards mean that this case probably isn't exhaustively covered. Technically
950                 // this is incorrect, as we should really check whether each variant is exhaustively
951                 // covered by the set of guards that cover it, but that's really hard to do.
952                 continue;
953             }
954             if let PatKind::Path(ref path) = arm.pat.kind {
955                 if let QPath::Resolved(_, p) = path {
956                     missing_variants.retain(|e| e.ctor_def_id != Some(p.res.def_id()));
957                 }
958             } else if let PatKind::TupleStruct(ref path, ref patterns, ..) = arm.pat.kind {
959                 if let QPath::Resolved(_, p) = path {
960                     // Some simple checks for exhaustive patterns.
961                     // There is a room for improvements to detect more cases,
962                     // but it can be more expensive to do so.
963                     let is_pattern_exhaustive =
964                         |pat: &&Pat<'_>| matches!(pat.kind, PatKind::Wild | PatKind::Binding(.., None));
965                     if patterns.iter().all(is_pattern_exhaustive) {
966                         missing_variants.retain(|e| e.ctor_def_id != Some(p.res.def_id()));
967                     }
968                 }
969             }
970         }
971
972         let mut suggestion: Vec<String> = missing_variants
973             .iter()
974             .map(|v| {
975                 let suffix = match v.ctor_kind {
976                     CtorKind::Fn => "(..)",
977                     CtorKind::Const | CtorKind::Fictive => "",
978                 };
979                 let ident_str = if let Some(ident) = wildcard_ident {
980                     format!("{} @ ", ident.name)
981                 } else {
982                     String::new()
983                 };
984                 // This path assumes that the enum type is imported into scope.
985                 format!("{}{}{}", ident_str, cx.tcx.def_path_str(v.def_id), suffix)
986             })
987             .collect();
988
989         if suggestion.is_empty() {
990             return;
991         }
992
993         let mut message = "wildcard match will miss any future added variants";
994
995         if let ty::Adt(def, _) = ty.kind() {
996             if def.is_variant_list_non_exhaustive() {
997                 message = "match on non-exhaustive enum doesn't explicitly match all known variants";
998                 suggestion.push(String::from("_"));
999             }
1000         }
1001
1002         if suggestion.len() == 1 {
1003             // No need to check for non-exhaustive enum as in that case len would be greater than 1
1004             span_lint_and_sugg(
1005                 cx,
1006                 MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
1007                 wildcard_span,
1008                 message,
1009                 "try this",
1010                 suggestion[0].clone(),
1011                 Applicability::MaybeIncorrect,
1012             )
1013         };
1014
1015         span_lint_and_sugg(
1016             cx,
1017             WILDCARD_ENUM_MATCH_ARM,
1018             wildcard_span,
1019             message,
1020             "try this",
1021             suggestion.join(" | "),
1022             Applicability::MaybeIncorrect,
1023         )
1024     }
1025 }
1026
1027 // If the block contains only a `panic!` macro (as expression or statement)
1028 fn is_panic_block(block: &Block<'_>) -> bool {
1029     match (&block.expr, block.stmts.len(), block.stmts.first()) {
1030         (&Some(ref exp), 0, _) => {
1031             is_expn_of(exp.span, "panic").is_some() && is_expn_of(exp.span, "unreachable").is_none()
1032         },
1033         (&None, 1, Some(stmt)) => {
1034             is_expn_of(stmt.span, "panic").is_some() && is_expn_of(stmt.span, "unreachable").is_none()
1035         },
1036         _ => false,
1037     }
1038 }
1039
1040 fn check_match_ref_pats(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1041     if has_only_ref_pats(arms) {
1042         let mut suggs = Vec::with_capacity(arms.len() + 1);
1043         let (title, msg) = if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, ref inner) = ex.kind {
1044             let span = ex.span.source_callsite();
1045             suggs.push((span, Sugg::hir_with_macro_callsite(cx, inner, "..").to_string()));
1046             (
1047                 "you don't need to add `&` to both the expression and the patterns",
1048                 "try",
1049             )
1050         } else {
1051             let span = ex.span.source_callsite();
1052             suggs.push((span, Sugg::hir_with_macro_callsite(cx, ex, "..").deref().to_string()));
1053             (
1054                 "you don't need to add `&` to all patterns",
1055                 "instead of prefixing all patterns with `&`, you can dereference the expression",
1056             )
1057         };
1058
1059         suggs.extend(arms.iter().filter_map(|a| {
1060             if let PatKind::Ref(ref refp, _) = a.pat.kind {
1061                 Some((a.pat.span, snippet(cx, refp.span, "..").to_string()))
1062             } else {
1063                 None
1064             }
1065         }));
1066
1067         span_lint_and_then(cx, MATCH_REF_PATS, expr.span, title, |diag| {
1068             if !expr.span.from_expansion() {
1069                 multispan_sugg(diag, msg, suggs);
1070             }
1071         });
1072     }
1073 }
1074
1075 fn check_match_as_ref(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1076     if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
1077         let arm_ref: Option<BindingAnnotation> = if is_none_arm(&arms[0]) {
1078             is_ref_some_arm(&arms[1])
1079         } else if is_none_arm(&arms[1]) {
1080             is_ref_some_arm(&arms[0])
1081         } else {
1082             None
1083         };
1084         if let Some(rb) = arm_ref {
1085             let suggestion = if rb == BindingAnnotation::Ref {
1086                 "as_ref"
1087             } else {
1088                 "as_mut"
1089             };
1090
1091             let output_ty = cx.typeck_results().expr_ty(expr);
1092             let input_ty = cx.typeck_results().expr_ty(ex);
1093
1094             let cast = if_chain! {
1095                 if let ty::Adt(_, substs) = input_ty.kind();
1096                 let input_ty = substs.type_at(0);
1097                 if let ty::Adt(_, substs) = output_ty.kind();
1098                 let output_ty = substs.type_at(0);
1099                 if let ty::Ref(_, output_ty, _) = *output_ty.kind();
1100                 if input_ty != output_ty;
1101                 then {
1102                     ".map(|x| x as _)"
1103                 } else {
1104                     ""
1105                 }
1106             };
1107
1108             let mut applicability = Applicability::MachineApplicable;
1109             span_lint_and_sugg(
1110                 cx,
1111                 MATCH_AS_REF,
1112                 expr.span,
1113                 &format!("use `{}()` instead", suggestion),
1114                 "try this",
1115                 format!(
1116                     "{}.{}(){}",
1117                     snippet_with_applicability(cx, ex.span, "_", &mut applicability),
1118                     suggestion,
1119                     cast,
1120                 ),
1121                 applicability,
1122             )
1123         }
1124     }
1125 }
1126
1127 fn check_wild_in_or_pats(cx: &LateContext<'_>, arms: &[Arm<'_>]) {
1128     for arm in arms {
1129         if let PatKind::Or(ref fields) = arm.pat.kind {
1130             // look for multiple fields in this arm that contains at least one Wild pattern
1131             if fields.len() > 1 && fields.iter().any(is_wild) {
1132                 span_lint_and_help(
1133                     cx,
1134                     WILDCARD_IN_OR_PATTERNS,
1135                     arm.pat.span,
1136                     "wildcard pattern covers any other pattern as it will match anyway.",
1137                     None,
1138                     "Consider handling `_` separately.",
1139                 );
1140             }
1141         }
1142     }
1143 }
1144
1145 /// Lint a `match` or `if let .. { .. } else { .. }` expr that could be replaced by `matches!`
1146 fn check_match_like_matches<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
1147     if let ExprKind::Match(ex, arms, ref match_source) = &expr.kind {
1148         match match_source {
1149             MatchSource::Normal => find_matches_sugg(cx, ex, arms, expr, false),
1150             MatchSource::IfLetDesugar { .. } => find_matches_sugg(cx, ex, arms, expr, true),
1151             _ => false,
1152         }
1153     } else {
1154         false
1155     }
1156 }
1157
1158 /// Lint a `match` or desugared `if let` for replacement by `matches!`
1159 fn find_matches_sugg(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>, desugared: bool) -> bool {
1160     if_chain! {
1161         if arms.len() >= 2;
1162         if cx.typeck_results().expr_ty(expr).is_bool();
1163         if let Some((b1_arm, b0_arms)) = arms.split_last();
1164         if let Some(b0) = find_bool_lit(&b0_arms[0].body.kind, desugared);
1165         if let Some(b1) = find_bool_lit(&b1_arm.body.kind, desugared);
1166         if is_wild(&b1_arm.pat);
1167         if b0 != b1;
1168         let if_guard = &b0_arms[0].guard;
1169         if if_guard.is_none() || b0_arms.len() == 1;
1170         if b0_arms[1..].iter()
1171             .all(|arm| {
1172                 find_bool_lit(&arm.body.kind, desugared).map_or(false, |b| b == b0) &&
1173                 arm.guard.is_none()
1174             });
1175         then {
1176             let mut applicability = Applicability::MachineApplicable;
1177             let pat = {
1178                 use itertools::Itertools as _;
1179                 b0_arms.iter()
1180                     .map(|arm| snippet_with_applicability(cx, arm.pat.span, "..", &mut applicability))
1181                     .join(" | ")
1182             };
1183             let pat_and_guard = if let Some(Guard::If(g)) = if_guard {
1184                 format!("{} if {}", pat, snippet_with_applicability(cx, g.span, "..", &mut applicability))
1185             } else {
1186                 pat
1187             };
1188             span_lint_and_sugg(
1189                 cx,
1190                 MATCH_LIKE_MATCHES_MACRO,
1191                 expr.span,
1192                 &format!("{} expression looks like `matches!` macro", if desugared { "if let .. else" } else { "match" }),
1193                 "try this",
1194                 format!(
1195                     "{}matches!({}, {})",
1196                     if b0 { "" } else { "!" },
1197                     snippet_with_applicability(cx, ex.span, "..", &mut applicability),
1198                     pat_and_guard,
1199                 ),
1200                 applicability,
1201             );
1202             true
1203         } else {
1204             false
1205         }
1206     }
1207 }
1208
1209 /// Extract a `bool` or `{ bool }`
1210 fn find_bool_lit(ex: &ExprKind<'_>, desugared: bool) -> Option<bool> {
1211     match ex {
1212         ExprKind::Lit(Spanned {
1213             node: LitKind::Bool(b), ..
1214         }) => Some(*b),
1215         ExprKind::Block(
1216             rustc_hir::Block {
1217                 stmts: &[],
1218                 expr: Some(exp),
1219                 ..
1220             },
1221             _,
1222         ) if desugared => {
1223             if let ExprKind::Lit(Spanned {
1224                 node: LitKind::Bool(b), ..
1225             }) = exp.kind
1226             {
1227                 Some(b)
1228             } else {
1229                 None
1230             }
1231         },
1232         _ => None,
1233     }
1234 }
1235
1236 fn check_match_single_binding<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1237     if in_macro(expr.span) || arms.len() != 1 || is_refutable(cx, arms[0].pat) {
1238         return;
1239     }
1240     let matched_vars = ex.span;
1241     let bind_names = arms[0].pat.span;
1242     let match_body = remove_blocks(&arms[0].body);
1243     let mut snippet_body = if match_body.span.from_expansion() {
1244         Sugg::hir_with_macro_callsite(cx, match_body, "..").to_string()
1245     } else {
1246         snippet_block(cx, match_body.span, "..", Some(expr.span)).to_string()
1247     };
1248
1249     // Do we need to add ';' to suggestion ?
1250     match match_body.kind {
1251         ExprKind::Block(block, _) => {
1252             // macro + expr_ty(body) == ()
1253             if block.span.from_expansion() && cx.typeck_results().expr_ty(&match_body).is_unit() {
1254                 snippet_body.push(';');
1255             }
1256         },
1257         _ => {
1258             // expr_ty(body) == ()
1259             if cx.typeck_results().expr_ty(&match_body).is_unit() {
1260                 snippet_body.push(';');
1261             }
1262         },
1263     }
1264
1265     let mut applicability = Applicability::MaybeIncorrect;
1266     match arms[0].pat.kind {
1267         PatKind::Binding(..) | PatKind::Tuple(_, _) | PatKind::Struct(..) => {
1268             // If this match is in a local (`let`) stmt
1269             let (target_span, sugg) = if let Some(parent_let_node) = opt_parent_let(cx, ex) {
1270                 (
1271                     parent_let_node.span,
1272                     format!(
1273                         "let {} = {};\n{}let {} = {};",
1274                         snippet_with_applicability(cx, bind_names, "..", &mut applicability),
1275                         snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
1276                         " ".repeat(indent_of(cx, expr.span).unwrap_or(0)),
1277                         snippet_with_applicability(cx, parent_let_node.pat.span, "..", &mut applicability),
1278                         snippet_body
1279                     ),
1280                 )
1281             } else {
1282                 // If we are in closure, we need curly braces around suggestion
1283                 let mut indent = " ".repeat(indent_of(cx, ex.span).unwrap_or(0));
1284                 let (mut cbrace_start, mut cbrace_end) = ("".to_string(), "".to_string());
1285                 if let Some(parent_expr) = get_parent_expr(cx, expr) {
1286                     if let ExprKind::Closure(..) = parent_expr.kind {
1287                         cbrace_end = format!("\n{}}}", indent);
1288                         // Fix body indent due to the closure
1289                         indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0));
1290                         cbrace_start = format!("{{\n{}", indent);
1291                     }
1292                 };
1293                 (
1294                     expr.span,
1295                     format!(
1296                         "{}let {} = {};\n{}{}{}",
1297                         cbrace_start,
1298                         snippet_with_applicability(cx, bind_names, "..", &mut applicability),
1299                         snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
1300                         indent,
1301                         snippet_body,
1302                         cbrace_end
1303                     ),
1304                 )
1305             };
1306             span_lint_and_sugg(
1307                 cx,
1308                 MATCH_SINGLE_BINDING,
1309                 target_span,
1310                 "this match could be written as a `let` statement",
1311                 "consider using `let` statement",
1312                 sugg,
1313                 applicability,
1314             );
1315         },
1316         PatKind::Wild => {
1317             span_lint_and_sugg(
1318                 cx,
1319                 MATCH_SINGLE_BINDING,
1320                 expr.span,
1321                 "this match could be replaced by its body itself",
1322                 "consider using the match body instead",
1323                 snippet_body,
1324                 Applicability::MachineApplicable,
1325             );
1326         },
1327         _ => (),
1328     }
1329 }
1330
1331 /// Returns true if the `ex` match expression is in a local (`let`) statement
1332 fn opt_parent_let<'a>(cx: &LateContext<'a>, ex: &Expr<'a>) -> Option<&'a Local<'a>> {
1333     if_chain! {
1334         let map = &cx.tcx.hir();
1335         if let Some(Node::Expr(parent_arm_expr)) = map.find(map.get_parent_node(ex.hir_id));
1336         if let Some(Node::Local(parent_let_expr)) = map.find(map.get_parent_node(parent_arm_expr.hir_id));
1337         then {
1338             return Some(parent_let_expr);
1339         }
1340     }
1341     None
1342 }
1343
1344 /// Gets all arms that are unbounded `PatRange`s.
1345 fn all_ranges<'tcx>(cx: &LateContext<'tcx>, arms: &'tcx [Arm<'_>], ty: Ty<'tcx>) -> Vec<SpannedRange<Constant>> {
1346     arms.iter()
1347         .flat_map(|arm| {
1348             if let Arm {
1349                 ref pat, guard: None, ..
1350             } = *arm
1351             {
1352                 if let PatKind::Range(ref lhs, ref rhs, range_end) = pat.kind {
1353                     let lhs = match lhs {
1354                         Some(lhs) => constant(cx, cx.typeck_results(), lhs)?.0,
1355                         None => miri_to_const(ty.numeric_min_val(cx.tcx)?)?,
1356                     };
1357                     let rhs = match rhs {
1358                         Some(rhs) => constant(cx, cx.typeck_results(), rhs)?.0,
1359                         None => miri_to_const(ty.numeric_max_val(cx.tcx)?)?,
1360                     };
1361                     let rhs = match range_end {
1362                         RangeEnd::Included => Bound::Included(rhs),
1363                         RangeEnd::Excluded => Bound::Excluded(rhs),
1364                     };
1365                     return Some(SpannedRange {
1366                         span: pat.span,
1367                         node: (lhs, rhs),
1368                     });
1369                 }
1370
1371                 if let PatKind::Lit(ref value) = pat.kind {
1372                     let value = constant(cx, cx.typeck_results(), value)?.0;
1373                     return Some(SpannedRange {
1374                         span: pat.span,
1375                         node: (value.clone(), Bound::Included(value)),
1376                     });
1377                 }
1378             }
1379             None
1380         })
1381         .collect()
1382 }
1383
1384 #[derive(Debug, Eq, PartialEq)]
1385 pub struct SpannedRange<T> {
1386     pub span: Span,
1387     pub node: (T, Bound<T>),
1388 }
1389
1390 type TypedRanges = Vec<SpannedRange<u128>>;
1391
1392 /// Gets all `Int` ranges or all `Uint` ranges. Mixed types are an error anyway
1393 /// and other types than
1394 /// `Uint` and `Int` probably don't make sense.
1395 fn type_ranges(ranges: &[SpannedRange<Constant>]) -> TypedRanges {
1396     ranges
1397         .iter()
1398         .filter_map(|range| match range.node {
1399             (Constant::Int(start), Bound::Included(Constant::Int(end))) => Some(SpannedRange {
1400                 span: range.span,
1401                 node: (start, Bound::Included(end)),
1402             }),
1403             (Constant::Int(start), Bound::Excluded(Constant::Int(end))) => Some(SpannedRange {
1404                 span: range.span,
1405                 node: (start, Bound::Excluded(end)),
1406             }),
1407             (Constant::Int(start), Bound::Unbounded) => Some(SpannedRange {
1408                 span: range.span,
1409                 node: (start, Bound::Unbounded),
1410             }),
1411             _ => None,
1412         })
1413         .collect()
1414 }
1415
1416 fn is_unit_expr(expr: &Expr<'_>) -> bool {
1417     match expr.kind {
1418         ExprKind::Tup(ref v) if v.is_empty() => true,
1419         ExprKind::Block(ref b, _) if b.stmts.is_empty() && b.expr.is_none() => true,
1420         _ => false,
1421     }
1422 }
1423
1424 // Checks if arm has the form `None => None`
1425 fn is_none_arm(arm: &Arm<'_>) -> bool {
1426     matches!(arm.pat.kind, PatKind::Path(ref path) if match_qpath(path, &paths::OPTION_NONE))
1427 }
1428
1429 // Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`)
1430 fn is_ref_some_arm(arm: &Arm<'_>) -> Option<BindingAnnotation> {
1431     if_chain! {
1432         if let PatKind::TupleStruct(ref path, ref pats, _) = arm.pat.kind;
1433         if pats.len() == 1 && match_qpath(path, &paths::OPTION_SOME);
1434         if let PatKind::Binding(rb, .., ident, _) = pats[0].kind;
1435         if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
1436         if let ExprKind::Call(ref e, ref args) = remove_blocks(&arm.body).kind;
1437         if let ExprKind::Path(ref some_path) = e.kind;
1438         if match_qpath(some_path, &paths::OPTION_SOME) && args.len() == 1;
1439         if let ExprKind::Path(ref qpath) = args[0].kind;
1440         if let &QPath::Resolved(_, ref path2) = qpath;
1441         if path2.segments.len() == 1 && ident.name == path2.segments[0].ident.name;
1442         then {
1443             return Some(rb)
1444         }
1445     }
1446     None
1447 }
1448
1449 fn has_only_ref_pats(arms: &[Arm<'_>]) -> bool {
1450     let mapped = arms
1451         .iter()
1452         .map(|a| {
1453             match a.pat.kind {
1454                 PatKind::Ref(..) => Some(true), // &-patterns
1455                 PatKind::Wild => Some(false),   // an "anything" wildcard is also fine
1456                 _ => None,                      // any other pattern is not fine
1457             }
1458         })
1459         .collect::<Option<Vec<bool>>>();
1460     // look for Some(v) where there's at least one true element
1461     mapped.map_or(false, |v| v.iter().any(|el| *el))
1462 }
1463
1464 pub fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
1465 where
1466     T: Copy + Ord,
1467 {
1468     #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1469     enum Kind<'a, T> {
1470         Start(T, &'a SpannedRange<T>),
1471         End(Bound<T>, &'a SpannedRange<T>),
1472     }
1473
1474     impl<'a, T: Copy> Kind<'a, T> {
1475         fn range(&self) -> &'a SpannedRange<T> {
1476             match *self {
1477                 Kind::Start(_, r) | Kind::End(_, r) => r,
1478             }
1479         }
1480
1481         fn value(self) -> Bound<T> {
1482             match self {
1483                 Kind::Start(t, _) => Bound::Included(t),
1484                 Kind::End(t, _) => t,
1485             }
1486         }
1487     }
1488
1489     impl<'a, T: Copy + Ord> PartialOrd for Kind<'a, T> {
1490         fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1491             Some(self.cmp(other))
1492         }
1493     }
1494
1495     impl<'a, T: Copy + Ord> Ord for Kind<'a, T> {
1496         fn cmp(&self, other: &Self) -> Ordering {
1497             match (self.value(), other.value()) {
1498                 (Bound::Included(a), Bound::Included(b)) | (Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
1499                 // Range patterns cannot be unbounded (yet)
1500                 (Bound::Unbounded, _) | (_, Bound::Unbounded) => unimplemented!(),
1501                 (Bound::Included(a), Bound::Excluded(b)) => match a.cmp(&b) {
1502                     Ordering::Equal => Ordering::Greater,
1503                     other => other,
1504                 },
1505                 (Bound::Excluded(a), Bound::Included(b)) => match a.cmp(&b) {
1506                     Ordering::Equal => Ordering::Less,
1507                     other => other,
1508                 },
1509             }
1510         }
1511     }
1512
1513     let mut values = Vec::with_capacity(2 * ranges.len());
1514
1515     for r in ranges {
1516         values.push(Kind::Start(r.node.0, r));
1517         values.push(Kind::End(r.node.1, r));
1518     }
1519
1520     values.sort();
1521
1522     for (a, b) in values.iter().zip(values.iter().skip(1)) {
1523         match (a, b) {
1524             (&Kind::Start(_, ra), &Kind::End(_, rb)) => {
1525                 if ra.node != rb.node {
1526                     return Some((ra, rb));
1527                 }
1528             },
1529             (&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (),
1530             _ => return Some((a.range(), b.range())),
1531         }
1532     }
1533
1534     None
1535 }
1536
1537 mod redundant_pattern_match {
1538     use super::REDUNDANT_PATTERN_MATCHING;
1539     use crate::utils::{match_qpath, match_trait_method, paths, snippet, span_lint_and_then};
1540     use if_chain::if_chain;
1541     use rustc_ast::ast::LitKind;
1542     use rustc_errors::Applicability;
1543     use rustc_hir::{Arm, Expr, ExprKind, MatchSource, PatKind, QPath};
1544     use rustc_lint::LateContext;
1545     use rustc_span::sym;
1546
1547     pub fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
1548         if let ExprKind::Match(op, arms, ref match_source) = &expr.kind {
1549             match match_source {
1550                 MatchSource::Normal => find_sugg_for_match(cx, expr, op, arms),
1551                 MatchSource::IfLetDesugar { .. } => find_sugg_for_if_let(cx, expr, op, arms, "if"),
1552                 MatchSource::WhileLetDesugar => find_sugg_for_if_let(cx, expr, op, arms, "while"),
1553                 _ => {},
1554             }
1555         }
1556     }
1557
1558     fn find_sugg_for_if_let<'tcx>(
1559         cx: &LateContext<'tcx>,
1560         expr: &'tcx Expr<'_>,
1561         op: &Expr<'_>,
1562         arms: &[Arm<'_>],
1563         keyword: &'static str,
1564     ) {
1565         let good_method = match arms[0].pat.kind {
1566             PatKind::TupleStruct(ref path, ref patterns, _) if patterns.len() == 1 => {
1567                 if let PatKind::Wild = patterns[0].kind {
1568                     if match_qpath(path, &paths::RESULT_OK) {
1569                         "is_ok()"
1570                     } else if match_qpath(path, &paths::RESULT_ERR) {
1571                         "is_err()"
1572                     } else if match_qpath(path, &paths::OPTION_SOME) {
1573                         "is_some()"
1574                     } else if match_qpath(path, &paths::POLL_READY) {
1575                         "is_ready()"
1576                     } else {
1577                         return;
1578                     }
1579                 } else {
1580                     return;
1581                 }
1582             },
1583             PatKind::Path(ref path) => {
1584                 if match_qpath(path, &paths::OPTION_NONE) {
1585                     "is_none()"
1586                 } else if match_qpath(path, &paths::POLL_PENDING) {
1587                     "is_pending()"
1588                 } else {
1589                     return;
1590                 }
1591             },
1592             _ => return,
1593         };
1594
1595         // check that `while_let_on_iterator` lint does not trigger
1596         if_chain! {
1597             if keyword == "while";
1598             if let ExprKind::MethodCall(method_path, _, _, _) = op.kind;
1599             if method_path.ident.name == sym::next;
1600             if match_trait_method(cx, op, &paths::ITERATOR);
1601             then {
1602                 return;
1603             }
1604         }
1605
1606         let result_expr = match &op.kind {
1607             ExprKind::AddrOf(_, _, borrowed) => borrowed,
1608             _ => op,
1609         };
1610         span_lint_and_then(
1611             cx,
1612             REDUNDANT_PATTERN_MATCHING,
1613             arms[0].pat.span,
1614             &format!("redundant pattern matching, consider using `{}`", good_method),
1615             |diag| {
1616                 // while let ... = ... { ... }
1617                 // ^^^^^^^^^^^^^^^^^^^^^^^^^^^
1618                 let expr_span = expr.span;
1619
1620                 // while let ... = ... { ... }
1621                 //                 ^^^
1622                 let op_span = result_expr.span.source_callsite();
1623
1624                 // while let ... = ... { ... }
1625                 // ^^^^^^^^^^^^^^^^^^^
1626                 let span = expr_span.until(op_span.shrink_to_hi());
1627                 diag.span_suggestion(
1628                     span,
1629                     "try this",
1630                     format!("{} {}.{}", keyword, snippet(cx, op_span, "_"), good_method),
1631                     Applicability::MachineApplicable, // snippet
1632                 );
1633             },
1634         );
1635     }
1636
1637     fn find_sugg_for_match<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, op: &Expr<'_>, arms: &[Arm<'_>]) {
1638         if arms.len() == 2 {
1639             let node_pair = (&arms[0].pat.kind, &arms[1].pat.kind);
1640
1641             let found_good_method = match node_pair {
1642                 (
1643                     PatKind::TupleStruct(ref path_left, ref patterns_left, _),
1644                     PatKind::TupleStruct(ref path_right, ref patterns_right, _),
1645                 ) if patterns_left.len() == 1 && patterns_right.len() == 1 => {
1646                     if let (PatKind::Wild, PatKind::Wild) = (&patterns_left[0].kind, &patterns_right[0].kind) {
1647                         find_good_method_for_match(
1648                             arms,
1649                             path_left,
1650                             path_right,
1651                             &paths::RESULT_OK,
1652                             &paths::RESULT_ERR,
1653                             "is_ok()",
1654                             "is_err()",
1655                         )
1656                     } else {
1657                         None
1658                     }
1659                 },
1660                 (PatKind::TupleStruct(ref path_left, ref patterns, _), PatKind::Path(ref path_right))
1661                 | (PatKind::Path(ref path_left), PatKind::TupleStruct(ref path_right, ref patterns, _))
1662                     if patterns.len() == 1 =>
1663                 {
1664                     if let PatKind::Wild = patterns[0].kind {
1665                         find_good_method_for_match(
1666                             arms,
1667                             path_left,
1668                             path_right,
1669                             &paths::OPTION_SOME,
1670                             &paths::OPTION_NONE,
1671                             "is_some()",
1672                             "is_none()",
1673                         )
1674                         .or_else(|| {
1675                             find_good_method_for_match(
1676                                 arms,
1677                                 path_left,
1678                                 path_right,
1679                                 &paths::POLL_READY,
1680                                 &paths::POLL_PENDING,
1681                                 "is_ready()",
1682                                 "is_pending()",
1683                             )
1684                         })
1685                     } else {
1686                         None
1687                     }
1688                 },
1689                 _ => None,
1690             };
1691
1692             if let Some(good_method) = found_good_method {
1693                 let span = expr.span.to(op.span);
1694                 let result_expr = match &op.kind {
1695                     ExprKind::AddrOf(_, _, borrowed) => borrowed,
1696                     _ => op,
1697                 };
1698                 span_lint_and_then(
1699                     cx,
1700                     REDUNDANT_PATTERN_MATCHING,
1701                     expr.span,
1702                     &format!("redundant pattern matching, consider using `{}`", good_method),
1703                     |diag| {
1704                         diag.span_suggestion(
1705                             span,
1706                             "try this",
1707                             format!("{}.{}", snippet(cx, result_expr.span, "_"), good_method),
1708                             Applicability::MaybeIncorrect, // snippet
1709                         );
1710                     },
1711                 );
1712             }
1713         }
1714     }
1715
1716     fn find_good_method_for_match<'a>(
1717         arms: &[Arm<'_>],
1718         path_left: &QPath<'_>,
1719         path_right: &QPath<'_>,
1720         expected_left: &[&str],
1721         expected_right: &[&str],
1722         should_be_left: &'a str,
1723         should_be_right: &'a str,
1724     ) -> Option<&'a str> {
1725         let body_node_pair = if match_qpath(path_left, expected_left) && match_qpath(path_right, expected_right) {
1726             (&(*arms[0].body).kind, &(*arms[1].body).kind)
1727         } else if match_qpath(path_right, expected_left) && match_qpath(path_left, expected_right) {
1728             (&(*arms[1].body).kind, &(*arms[0].body).kind)
1729         } else {
1730             return None;
1731         };
1732
1733         match body_node_pair {
1734             (ExprKind::Lit(ref lit_left), ExprKind::Lit(ref lit_right)) => match (&lit_left.node, &lit_right.node) {
1735                 (LitKind::Bool(true), LitKind::Bool(false)) => Some(should_be_left),
1736                 (LitKind::Bool(false), LitKind::Bool(true)) => Some(should_be_right),
1737                 _ => None,
1738             },
1739             _ => None,
1740         }
1741     }
1742 }
1743
1744 #[test]
1745 fn test_overlapping() {
1746     use rustc_span::source_map::DUMMY_SP;
1747
1748     let sp = |s, e| SpannedRange {
1749         span: DUMMY_SP,
1750         node: (s, e),
1751     };
1752
1753     assert_eq!(None, overlapping::<u8>(&[]));
1754     assert_eq!(None, overlapping(&[sp(1, Bound::Included(4))]));
1755     assert_eq!(
1756         None,
1757         overlapping(&[sp(1, Bound::Included(4)), sp(5, Bound::Included(6))])
1758     );
1759     assert_eq!(
1760         None,
1761         overlapping(&[
1762             sp(1, Bound::Included(4)),
1763             sp(5, Bound::Included(6)),
1764             sp(10, Bound::Included(11))
1765         ],)
1766     );
1767     assert_eq!(
1768         Some((&sp(1, Bound::Included(4)), &sp(3, Bound::Included(6)))),
1769         overlapping(&[sp(1, Bound::Included(4)), sp(3, Bound::Included(6))])
1770     );
1771     assert_eq!(
1772         Some((&sp(5, Bound::Included(6)), &sp(6, Bound::Included(11)))),
1773         overlapping(&[
1774             sp(1, Bound::Included(4)),
1775             sp(5, Bound::Included(6)),
1776             sp(6, Bound::Included(11))
1777         ],)
1778     );
1779 }
1780
1781 /// Implementation of `MATCH_SAME_ARMS`.
1782 fn lint_match_arms<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) {
1783     fn same_bindings<'tcx>(lhs: &FxHashMap<Symbol, Ty<'tcx>>, rhs: &FxHashMap<Symbol, Ty<'tcx>>) -> bool {
1784         lhs.len() == rhs.len()
1785             && lhs
1786                 .iter()
1787                 .all(|(name, l_ty)| rhs.get(name).map_or(false, |r_ty| TyS::same_type(l_ty, r_ty)))
1788     }
1789
1790     if let ExprKind::Match(_, ref arms, MatchSource::Normal) = expr.kind {
1791         let hash = |&(_, arm): &(usize, &Arm<'_>)| -> u64 {
1792             let mut h = SpanlessHash::new(cx);
1793             h.hash_expr(&arm.body);
1794             h.finish()
1795         };
1796
1797         let eq = |&(lindex, lhs): &(usize, &Arm<'_>), &(rindex, rhs): &(usize, &Arm<'_>)| -> bool {
1798             let min_index = usize::min(lindex, rindex);
1799             let max_index = usize::max(lindex, rindex);
1800
1801             // Arms with a guard are ignored, those can’t always be merged together
1802             // This is also the case for arms in-between each there is an arm with a guard
1803             (min_index..=max_index).all(|index| arms[index].guard.is_none()) &&
1804                 SpanlessEq::new(cx).eq_expr(&lhs.body, &rhs.body) &&
1805                 // all patterns should have the same bindings
1806                 same_bindings(&bindings(cx, &lhs.pat), &bindings(cx, &rhs.pat))
1807         };
1808
1809         let indexed_arms: Vec<(usize, &Arm<'_>)> = arms.iter().enumerate().collect();
1810         for (&(_, i), &(_, j)) in search_same(&indexed_arms, hash, eq) {
1811             span_lint_and_then(
1812                 cx,
1813                 MATCH_SAME_ARMS,
1814                 j.body.span,
1815                 "this `match` has identical arm bodies",
1816                 |diag| {
1817                     diag.span_note(i.body.span, "same as this");
1818
1819                     // Note: this does not use `span_suggestion` on purpose:
1820                     // there is no clean way
1821                     // to remove the other arm. Building a span and suggest to replace it to ""
1822                     // makes an even more confusing error message. Also in order not to make up a
1823                     // span for the whole pattern, the suggestion is only shown when there is only
1824                     // one pattern. The user should know about `|` if they are already using it…
1825
1826                     let lhs = snippet(cx, i.pat.span, "<pat1>");
1827                     let rhs = snippet(cx, j.pat.span, "<pat2>");
1828
1829                     if let PatKind::Wild = j.pat.kind {
1830                         // if the last arm is _, then i could be integrated into _
1831                         // note that i.pat cannot be _, because that would mean that we're
1832                         // hiding all the subsequent arms, and rust won't compile
1833                         diag.span_note(
1834                             i.body.span,
1835                             &format!(
1836                                 "`{}` has the same arm body as the `_` wildcard, consider removing it",
1837                                 lhs
1838                             ),
1839                         );
1840                     } else {
1841                         diag.span_help(i.pat.span, &format!("consider refactoring into `{} | {}`", lhs, rhs));
1842                     }
1843                 },
1844             );
1845         }
1846     }
1847 }
1848
1849 /// Returns the list of bindings in a pattern.
1850 fn bindings<'tcx>(cx: &LateContext<'tcx>, pat: &Pat<'_>) -> FxHashMap<Symbol, Ty<'tcx>> {
1851     fn bindings_impl<'tcx>(cx: &LateContext<'tcx>, pat: &Pat<'_>, map: &mut FxHashMap<Symbol, Ty<'tcx>>) {
1852         match pat.kind {
1853             PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => bindings_impl(cx, pat, map),
1854             PatKind::TupleStruct(_, pats, _) => {
1855                 for pat in pats {
1856                     bindings_impl(cx, pat, map);
1857                 }
1858             },
1859             PatKind::Binding(.., ident, ref as_pat) => {
1860                 if let Entry::Vacant(v) = map.entry(ident.name) {
1861                     v.insert(cx.typeck_results().pat_ty(pat));
1862                 }
1863                 if let Some(ref as_pat) = *as_pat {
1864                     bindings_impl(cx, as_pat, map);
1865                 }
1866             },
1867             PatKind::Or(fields) | PatKind::Tuple(fields, _) => {
1868                 for pat in fields {
1869                     bindings_impl(cx, pat, map);
1870                 }
1871             },
1872             PatKind::Struct(_, fields, _) => {
1873                 for pat in fields {
1874                     bindings_impl(cx, &pat.pat, map);
1875                 }
1876             },
1877             PatKind::Slice(lhs, ref mid, rhs) => {
1878                 for pat in lhs {
1879                     bindings_impl(cx, pat, map);
1880                 }
1881                 if let Some(ref mid) = *mid {
1882                     bindings_impl(cx, mid, map);
1883                 }
1884                 for pat in rhs {
1885                     bindings_impl(cx, pat, map);
1886                 }
1887             },
1888             PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild | PatKind::Path(..) => (),
1889         }
1890     }
1891
1892     let mut result = FxHashMap::default();
1893     bindings_impl(cx, pat, &mut result);
1894     result
1895 }