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