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