]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/matches.rs
Fix formatting
[rust.git] / clippy_lints / src / matches.rs
1 use crate::consts::{constant, miri_to_const, Constant};
2 use crate::utils::paths;
3 use crate::utils::sugg::Sugg;
4 use crate::utils::{
5     expr_block, is_allowed, is_expn_of, match_qpath, match_type, match_var, multispan_sugg, remove_blocks, snippet,
6     snippet_with_applicability, span_help_and_lint, span_lint_and_sugg, span_lint_and_then, span_note_and_lint,
7     walk_ptrs_ty,
8 };
9 use if_chain::if_chain;
10 use rustc::hir::map::Map;
11 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
12 use rustc::ty::{self, Ty};
13 use rustc_errors::Applicability;
14 use rustc_hir::def::CtorKind;
15 use rustc_hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
16 use rustc_hir::*;
17 use rustc_lint::{LateContext, LateLintPass, LintContext};
18 use rustc_session::{declare_lint_pass, declare_tool_lint};
19 use rustc_span::source_map::Span;
20 use rustc_span::symbol::Ident;
21 use std::cmp::Ordering;
22 use std::collections::Bound;
23 use syntax::ast::{self, LitKind};
24
25 declare_clippy_lint! {
26     /// **What it does:** Checks for matches with a single arm where an `if let`
27     /// will usually suffice.
28     ///
29     /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
30     ///
31     /// **Known problems:** None.
32     ///
33     /// **Example:**
34     /// ```rust
35     /// # fn bar(stool: &str) {}
36     /// # let x = Some("abc");
37     /// match x {
38     ///     Some(ref foo) => bar(foo),
39     ///     _ => (),
40     /// }
41     /// ```
42     pub SINGLE_MATCH,
43     style,
44     "a `match` statement with a single nontrivial arm (i.e., where the other arm is `_ => {}`) instead of `if let`"
45 }
46
47 declare_clippy_lint! {
48     /// **What it does:** Checks for matches with two arms where an `if let else` will
49     /// usually suffice.
50     ///
51     /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
52     ///
53     /// **Known problems:** Personal style preferences may differ.
54     ///
55     /// **Example:**
56     ///
57     /// Using `match`:
58     ///
59     /// ```rust
60     /// # fn bar(foo: &usize) {}
61     /// # let other_ref: usize = 1;
62     /// # let x: Option<&usize> = Some(&1);
63     /// match x {
64     ///     Some(ref foo) => bar(foo),
65     ///     _ => bar(&other_ref),
66     /// }
67     /// ```
68     ///
69     /// Using `if let` with `else`:
70     ///
71     /// ```rust
72     /// # fn bar(foo: &usize) {}
73     /// # let other_ref: usize = 1;
74     /// # let x: Option<&usize> = Some(&1);
75     /// if let Some(ref foo) = x {
76     ///     bar(foo);
77     /// } else {
78     ///     bar(&other_ref);
79     /// }
80     /// ```
81     pub SINGLE_MATCH_ELSE,
82     pedantic,
83     "a `match` statement with two arms where the second arm's pattern is a placeholder instead of a specific match pattern"
84 }
85
86 declare_clippy_lint! {
87     /// **What it does:** Checks for matches where all arms match a reference,
88     /// suggesting to remove the reference and deref the matched expression
89     /// instead. It also checks for `if let &foo = bar` blocks.
90     ///
91     /// **Why is this bad?** It just makes the code less readable. That reference
92     /// destructuring adds nothing to the code.
93     ///
94     /// **Known problems:** None.
95     ///
96     /// **Example:**
97     /// ```rust,ignore
98     /// match x {
99     ///     &A(ref y) => foo(y),
100     ///     &B => bar(),
101     ///     _ => frob(&x),
102     /// }
103     /// ```
104     pub MATCH_REF_PATS,
105     style,
106     "a `match` or `if let` with all arms prefixed with `&` instead of deref-ing the match expression"
107 }
108
109 declare_clippy_lint! {
110     /// **What it does:** Checks for matches where match expression is a `bool`. It
111     /// suggests to replace the expression with an `if...else` block.
112     ///
113     /// **Why is this bad?** It makes the code less readable.
114     ///
115     /// **Known problems:** None.
116     ///
117     /// **Example:**
118     /// ```rust
119     /// # fn foo() {}
120     /// # fn bar() {}
121     /// let condition: bool = true;
122     /// match condition {
123     ///     true => foo(),
124     ///     false => bar(),
125     /// }
126     /// ```
127     /// Use if/else instead:
128     /// ```rust
129     /// # fn foo() {}
130     /// # fn bar() {}
131     /// let condition: bool = true;
132     /// if condition {
133     ///     foo();
134     /// } else {
135     ///     bar();
136     /// }
137     /// ```
138     pub MATCH_BOOL,
139     style,
140     "a `match` on a boolean expression instead of an `if..else` block"
141 }
142
143 declare_clippy_lint! {
144     /// **What it does:** Checks for overlapping match arms.
145     ///
146     /// **Why is this bad?** It is likely to be an error and if not, makes the code
147     /// less obvious.
148     ///
149     /// **Known problems:** None.
150     ///
151     /// **Example:**
152     /// ```rust
153     /// let x = 5;
154     /// match x {
155     ///     1...10 => println!("1 ... 10"),
156     ///     5...15 => println!("5 ... 15"),
157     ///     _ => (),
158     /// }
159     /// ```
160     pub MATCH_OVERLAPPING_ARM,
161     style,
162     "a `match` with overlapping arms"
163 }
164
165 declare_clippy_lint! {
166     /// **What it does:** Checks for arm which matches all errors with `Err(_)`
167     /// and take drastic actions like `panic!`.
168     ///
169     /// **Why is this bad?** It is generally a bad practice, just like
170     /// catching all exceptions in java with `catch(Exception)`
171     ///
172     /// **Known problems:** None.
173     ///
174     /// **Example:**
175     /// ```rust
176     /// let x: Result<i32, &str> = Ok(3);
177     /// match x {
178     ///     Ok(_) => println!("ok"),
179     ///     Err(_) => panic!("err"),
180     /// }
181     /// ```
182     pub MATCH_WILD_ERR_ARM,
183     style,
184     "a `match` with `Err(_)` arm and take drastic actions"
185 }
186
187 declare_clippy_lint! {
188     /// **What it does:** Checks for match which is used to add a reference to an
189     /// `Option` value.
190     ///
191     /// **Why is this bad?** Using `as_ref()` or `as_mut()` instead is shorter.
192     ///
193     /// **Known problems:** None.
194     ///
195     /// **Example:**
196     /// ```rust
197     /// let x: Option<()> = None;
198     /// let r: Option<&()> = match x {
199     ///     None => None,
200     ///     Some(ref v) => Some(v),
201     /// };
202     /// ```
203     pub MATCH_AS_REF,
204     complexity,
205     "a `match` on an Option value instead of using `as_ref()` or `as_mut`"
206 }
207
208 declare_clippy_lint! {
209     /// **What it does:** Checks for wildcard enum matches using `_`.
210     ///
211     /// **Why is this bad?** New enum variants added by library updates can be missed.
212     ///
213     /// **Known problems:** Suggested replacements may be incorrect if guards exhaustively cover some
214     /// variants, and also may not use correct path to enum if it's not present in the current scope.
215     ///
216     /// **Example:**
217     /// ```rust
218     /// # enum Foo { A(usize), B(usize) }
219     /// # let x = Foo::B(1);
220     /// match x {
221     ///     A => {},
222     ///     _ => {},
223     /// }
224     /// ```
225     pub WILDCARD_ENUM_MATCH_ARM,
226     restriction,
227     "a wildcard enum match arm using `_`"
228 }
229
230 declare_clippy_lint! {
231     /// **What it does:** Checks for wildcard pattern used with others patterns in same match arm.
232     ///
233     /// **Why is this bad?** Wildcard pattern already covers any other pattern as it will match anyway.
234     /// It makes the code less readable, especially to spot wildcard pattern use in match arm.
235     ///
236     /// **Known problems:** None.
237     ///
238     /// **Example:**
239     /// ```rust
240     /// match "foo" {
241     ///     "a" => {},
242     ///     "bar" | _ => {},
243     /// }
244     /// ```
245     pub WILDCARD_IN_OR_PATTERNS,
246     complexity,
247     "a wildcard pattern used with others patterns in same match arm"
248 }
249
250 declare_lint_pass!(Matches => [
251     SINGLE_MATCH,
252     MATCH_REF_PATS,
253     MATCH_BOOL,
254     SINGLE_MATCH_ELSE,
255     MATCH_OVERLAPPING_ARM,
256     MATCH_WILD_ERR_ARM,
257     MATCH_AS_REF,
258     WILDCARD_ENUM_MATCH_ARM,
259     WILDCARD_IN_OR_PATTERNS
260 ]);
261
262 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Matches {
263     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
264         if in_external_macro(cx.sess(), expr.span) {
265             return;
266         }
267         if let ExprKind::Match(ref ex, ref arms, MatchSource::Normal) = expr.kind {
268             check_single_match(cx, ex, arms, expr);
269             check_match_bool(cx, ex, arms, expr);
270             check_overlapping_arms(cx, ex, arms);
271             check_wild_err_arm(cx, ex, arms);
272             check_wild_enum_match(cx, ex, arms);
273             check_match_as_ref(cx, ex, arms, expr);
274             check_wild_in_or_pats(cx, arms);
275         }
276         if let ExprKind::Match(ref ex, ref arms, _) = expr.kind {
277             check_match_ref_pats(cx, ex, arms, expr);
278         }
279     }
280 }
281
282 #[rustfmt::skip]
283 fn check_single_match(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
284     if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
285         if let PatKind::Or(..) = arms[0].pat.kind {
286             // don't lint for or patterns for now, this makes
287             // the lint noisy in unnecessary situations
288             return;
289         }
290         let els = remove_blocks(&arms[1].body);
291         let els = if is_unit_expr(els) {
292             None
293         } else if let ExprKind::Block(_, _) = els.kind {
294             // matches with blocks that contain statements are prettier as `if let + else`
295             Some(els)
296         } else {
297             // allow match arms with just expressions
298             return;
299         };
300         let ty = cx.tables.expr_ty(ex);
301         if ty.kind != ty::Bool || is_allowed(cx, MATCH_BOOL, ex.hir_id) {
302             check_single_match_single_pattern(cx, ex, arms, expr, els);
303             check_single_match_opt_like(cx, ex, arms, expr, ty, els);
304         }
305     }
306 }
307
308 fn check_single_match_single_pattern(
309     cx: &LateContext<'_, '_>,
310     ex: &Expr<'_>,
311     arms: &[Arm<'_>],
312     expr: &Expr<'_>,
313     els: Option<&Expr<'_>>,
314 ) {
315     if is_wild(&arms[1].pat) {
316         report_single_match_single_pattern(cx, ex, arms, expr, els);
317     }
318 }
319
320 fn report_single_match_single_pattern(
321     cx: &LateContext<'_, '_>,
322     ex: &Expr<'_>,
323     arms: &[Arm<'_>],
324     expr: &Expr<'_>,
325     els: Option<&Expr<'_>>,
326 ) {
327     let lint = if els.is_some() { SINGLE_MATCH_ELSE } else { SINGLE_MATCH };
328     let els_str = els.map_or(String::new(), |els| {
329         format!(" else {}", expr_block(cx, els, None, ".."))
330     });
331     span_lint_and_sugg(
332         cx,
333         lint,
334         expr.span,
335         "you seem to be trying to use match for destructuring a single pattern. Consider using `if \
336          let`",
337         "try this",
338         format!(
339             "if let {} = {} {}{}",
340             snippet(cx, arms[0].pat.span, ".."),
341             snippet(cx, ex.span, ".."),
342             expr_block(cx, &arms[0].body, None, ".."),
343             els_str,
344         ),
345         Applicability::HasPlaceholders,
346     );
347 }
348
349 fn check_single_match_opt_like(
350     cx: &LateContext<'_, '_>,
351     ex: &Expr<'_>,
352     arms: &[Arm<'_>],
353     expr: &Expr<'_>,
354     ty: Ty<'_>,
355     els: Option<&Expr<'_>>,
356 ) {
357     // list of candidate `Enum`s we know will never get any more members
358     let candidates = &[
359         (&paths::COW, "Borrowed"),
360         (&paths::COW, "Cow::Borrowed"),
361         (&paths::COW, "Cow::Owned"),
362         (&paths::COW, "Owned"),
363         (&paths::OPTION, "None"),
364         (&paths::RESULT, "Err"),
365         (&paths::RESULT, "Ok"),
366     ];
367
368     let path = match arms[1].pat.kind {
369         PatKind::TupleStruct(ref path, ref inner, _) => {
370             // Contains any non wildcard patterns (e.g., `Err(err)`)?
371             if !inner.iter().all(is_wild) {
372                 return;
373             }
374             print::to_string(print::NO_ANN, |s| s.print_qpath(path, false))
375         },
376         PatKind::Binding(BindingAnnotation::Unannotated, .., ident, None) => ident.to_string(),
377         PatKind::Path(ref path) => print::to_string(print::NO_ANN, |s| s.print_qpath(path, false)),
378         _ => return,
379     };
380
381     for &(ty_path, pat_path) in candidates {
382         if path == *pat_path && match_type(cx, ty, ty_path) {
383             report_single_match_single_pattern(cx, ex, arms, expr, els);
384         }
385     }
386 }
387
388 fn check_match_bool(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
389     // Type of expression is `bool`.
390     if cx.tables.expr_ty(ex).kind == ty::Bool {
391         span_lint_and_then(
392             cx,
393             MATCH_BOOL,
394             expr.span,
395             "you seem to be trying to match on a boolean expression",
396             move |db| {
397                 if arms.len() == 2 {
398                     // no guards
399                     let exprs = if let PatKind::Lit(ref arm_bool) = arms[0].pat.kind {
400                         if let ExprKind::Lit(ref lit) = arm_bool.kind {
401                             match lit.node {
402                                 LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
403                                 LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
404                                 _ => None,
405                             }
406                         } else {
407                             None
408                         }
409                     } else {
410                         None
411                     };
412
413                     if let Some((true_expr, false_expr)) = exprs {
414                         let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
415                             (false, false) => Some(format!(
416                                 "if {} {} else {}",
417                                 snippet(cx, ex.span, "b"),
418                                 expr_block(cx, true_expr, None, ".."),
419                                 expr_block(cx, false_expr, None, "..")
420                             )),
421                             (false, true) => Some(format!(
422                                 "if {} {}",
423                                 snippet(cx, ex.span, "b"),
424                                 expr_block(cx, true_expr, None, "..")
425                             )),
426                             (true, false) => {
427                                 let test = Sugg::hir(cx, ex, "..");
428                                 Some(format!("if {} {}", !test, expr_block(cx, false_expr, None, "..")))
429                             },
430                             (true, true) => None,
431                         };
432
433                         if let Some(sugg) = sugg {
434                             db.span_suggestion(
435                                 expr.span,
436                                 "consider using an `if`/`else` expression",
437                                 sugg,
438                                 Applicability::HasPlaceholders,
439                             );
440                         }
441                     }
442                 }
443             },
444         );
445     }
446 }
447
448 fn check_overlapping_arms<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ex: &'tcx Expr<'_>, arms: &'tcx [Arm<'_>]) {
449     if arms.len() >= 2 && cx.tables.expr_ty(ex).is_integral() {
450         let ranges = all_ranges(cx, arms, cx.tables.expr_ty(ex));
451         let type_ranges = type_ranges(&ranges);
452         if !type_ranges.is_empty() {
453             if let Some((start, end)) = overlapping(&type_ranges) {
454                 span_note_and_lint(
455                     cx,
456                     MATCH_OVERLAPPING_ARM,
457                     start.span,
458                     "some ranges overlap",
459                     end.span,
460                     "overlaps with this",
461                 );
462             }
463         }
464     }
465 }
466
467 fn is_wild<'tcx>(pat: &impl std::ops::Deref<Target = Pat<'tcx>>) -> bool {
468     match pat.kind {
469         PatKind::Wild => true,
470         _ => false,
471     }
472 }
473
474 fn is_unused<'tcx>(ident: &'tcx Ident, body: &'tcx Expr<'_>) -> bool {
475     let mut visitor = UsedVisitor {
476         var: ident.name,
477         used: false,
478     };
479     walk_expr(&mut visitor, body);
480     !visitor.used
481 }
482
483 struct UsedVisitor {
484     var: ast::Name, // var to look for
485     used: bool,     // has the var been used otherwise?
486 }
487
488 impl<'tcx> Visitor<'tcx> for UsedVisitor {
489     type Map = Map<'tcx>;
490
491     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
492         if match_var(expr, self.var) {
493             self.used = true;
494         } else {
495             walk_expr(self, expr);
496         }
497     }
498
499     fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
500         NestedVisitorMap::None
501     }
502 }
503
504 fn check_wild_err_arm(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>]) {
505     let ex_ty = walk_ptrs_ty(cx.tables.expr_ty(ex));
506     if match_type(cx, ex_ty, &paths::RESULT) {
507         for arm in arms {
508             if let PatKind::TupleStruct(ref path, ref inner, _) = arm.pat.kind {
509                 let path_str = print::to_string(print::NO_ANN, |s| s.print_qpath(path, false));
510                 if path_str == "Err" {
511                     let mut matching_wild = inner.iter().any(is_wild);
512                     let mut ident_bind_name = String::from("_");
513                     if !matching_wild {
514                         // Looking for unused bindings (i.e.: `_e`)
515                         inner.iter().for_each(|pat| {
516                             if let PatKind::Binding(.., ident, None) = &pat.kind {
517                                 if ident.as_str().starts_with('_') && is_unused(ident, arm.body) {
518                                     ident_bind_name = (&ident.name.as_str()).to_string();
519                                     matching_wild = true;
520                                 }
521                             }
522                         });
523                     }
524                     if_chain! {
525                         if matching_wild;
526                         if let ExprKind::Block(ref block, _) = arm.body.kind;
527                         if is_panic_block(block);
528                         then {
529                             // `Err(_)` or `Err(_e)` arm with `panic!` found
530                             span_note_and_lint(cx,
531                                 MATCH_WILD_ERR_ARM,
532                                 arm.pat.span,
533                                 &format!("`Err({})` will match all errors, maybe not a good idea", &ident_bind_name),
534                                 arm.pat.span,
535                                 "to remove this warning, match each error separately \
536                                     or use `unreachable!` macro"
537                             );
538                         }
539                     }
540                 }
541             }
542         }
543     }
544 }
545
546 fn check_wild_enum_match(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>]) {
547     let ty = cx.tables.expr_ty(ex);
548     if !ty.is_enum() {
549         // If there isn't a nice closed set of possible values that can be conveniently enumerated,
550         // don't complain about not enumerating the mall.
551         return;
552     }
553
554     // First pass - check for violation, but don't do much book-keeping because this is hopefully
555     // the uncommon case, and the book-keeping is slightly expensive.
556     let mut wildcard_span = None;
557     let mut wildcard_ident = None;
558     for arm in arms {
559         if let PatKind::Wild = arm.pat.kind {
560             wildcard_span = Some(arm.pat.span);
561         } else if let PatKind::Binding(_, _, ident, None) = arm.pat.kind {
562             wildcard_span = Some(arm.pat.span);
563             wildcard_ident = Some(ident);
564         }
565     }
566
567     if let Some(wildcard_span) = wildcard_span {
568         // Accumulate the variants which should be put in place of the wildcard because they're not
569         // already covered.
570
571         let mut missing_variants = vec![];
572         if let ty::Adt(def, _) = ty.kind {
573             for variant in &def.variants {
574                 missing_variants.push(variant);
575             }
576         }
577
578         for arm in arms {
579             if arm.guard.is_some() {
580                 // Guards mean that this case probably isn't exhaustively covered. Technically
581                 // this is incorrect, as we should really check whether each variant is exhaustively
582                 // covered by the set of guards that cover it, but that's really hard to do.
583                 continue;
584             }
585             if let PatKind::Path(ref path) = arm.pat.kind {
586                 if let QPath::Resolved(_, p) = path {
587                     missing_variants.retain(|e| e.ctor_def_id != Some(p.res.def_id()));
588                 }
589             } else if let PatKind::TupleStruct(ref path, ..) = arm.pat.kind {
590                 if let QPath::Resolved(_, p) = path {
591                     missing_variants.retain(|e| e.ctor_def_id != Some(p.res.def_id()));
592                 }
593             }
594         }
595
596         let mut suggestion: Vec<String> = missing_variants
597             .iter()
598             .map(|v| {
599                 let suffix = match v.ctor_kind {
600                     CtorKind::Fn => "(..)",
601                     CtorKind::Const | CtorKind::Fictive => "",
602                 };
603                 let ident_str = if let Some(ident) = wildcard_ident {
604                     format!("{} @ ", ident.name)
605                 } else {
606                     String::new()
607                 };
608                 // This path assumes that the enum type is imported into scope.
609                 format!("{}{}{}", ident_str, cx.tcx.def_path_str(v.def_id), suffix)
610             })
611             .collect();
612
613         if suggestion.is_empty() {
614             return;
615         }
616
617         let mut message = "wildcard match will miss any future added variants";
618
619         if let ty::Adt(def, _) = ty.kind {
620             if def.is_variant_list_non_exhaustive() {
621                 message = "match on non-exhaustive enum doesn't explicitly match all known variants";
622                 suggestion.push(String::from("_"));
623             }
624         }
625
626         span_lint_and_sugg(
627             cx,
628             WILDCARD_ENUM_MATCH_ARM,
629             wildcard_span,
630             message,
631             "try this",
632             suggestion.join(" | "),
633             Applicability::MachineApplicable,
634         )
635     }
636 }
637
638 // If the block contains only a `panic!` macro (as expression or statement)
639 fn is_panic_block(block: &Block<'_>) -> bool {
640     match (&block.expr, block.stmts.len(), block.stmts.first()) {
641         (&Some(ref exp), 0, _) => {
642             is_expn_of(exp.span, "panic").is_some() && is_expn_of(exp.span, "unreachable").is_none()
643         },
644         (&None, 1, Some(stmt)) => {
645             is_expn_of(stmt.span, "panic").is_some() && is_expn_of(stmt.span, "unreachable").is_none()
646         },
647         _ => false,
648     }
649 }
650
651 fn check_match_ref_pats(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
652     if has_only_ref_pats(arms) {
653         let mut suggs = Vec::new();
654         let (title, msg) = if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, ref inner) = ex.kind {
655             let span = ex.span.source_callsite();
656             suggs.push((span, Sugg::hir_with_macro_callsite(cx, inner, "..").to_string()));
657             (
658                 "you don't need to add `&` to both the expression and the patterns",
659                 "try",
660             )
661         } else {
662             let span = ex.span.source_callsite();
663             suggs.push((span, Sugg::hir_with_macro_callsite(cx, ex, "..").deref().to_string()));
664             (
665                 "you don't need to add `&` to all patterns",
666                 "instead of prefixing all patterns with `&`, you can dereference the expression",
667             )
668         };
669
670         suggs.extend(arms.iter().filter_map(|a| {
671             if let PatKind::Ref(ref refp, _) = a.pat.kind {
672                 Some((a.pat.span, snippet(cx, refp.span, "..").to_string()))
673             } else {
674                 None
675             }
676         }));
677
678         span_lint_and_then(cx, MATCH_REF_PATS, expr.span, title, |db| {
679             if !expr.span.from_expansion() {
680                 multispan_sugg(db, msg.to_owned(), suggs);
681             }
682         });
683     }
684 }
685
686 fn check_match_as_ref(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
687     if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
688         let arm_ref: Option<BindingAnnotation> = if is_none_arm(&arms[0]) {
689             is_ref_some_arm(&arms[1])
690         } else if is_none_arm(&arms[1]) {
691             is_ref_some_arm(&arms[0])
692         } else {
693             None
694         };
695         if let Some(rb) = arm_ref {
696             let suggestion = if rb == BindingAnnotation::Ref {
697                 "as_ref"
698             } else {
699                 "as_mut"
700             };
701
702             let output_ty = cx.tables.expr_ty(expr);
703             let input_ty = cx.tables.expr_ty(ex);
704
705             let cast = if_chain! {
706                 if let ty::Adt(_, substs) = input_ty.kind;
707                 let input_ty = substs.type_at(0);
708                 if let ty::Adt(_, substs) = output_ty.kind;
709                 let output_ty = substs.type_at(0);
710                 if let ty::Ref(_, output_ty, _) = output_ty.kind;
711                 if input_ty != output_ty;
712                 then {
713                     ".map(|x| x as _)"
714                 } else {
715                     ""
716                 }
717             };
718
719             let mut applicability = Applicability::MachineApplicable;
720             span_lint_and_sugg(
721                 cx,
722                 MATCH_AS_REF,
723                 expr.span,
724                 &format!("use `{}()` instead", suggestion),
725                 "try this",
726                 format!(
727                     "{}.{}(){}",
728                     snippet_with_applicability(cx, ex.span, "_", &mut applicability),
729                     suggestion,
730                     cast,
731                 ),
732                 applicability,
733             )
734         }
735     }
736 }
737
738 fn check_wild_in_or_pats(cx: &LateContext<'_, '_>, arms: &[Arm<'_>]) {
739     for arm in arms {
740         if let PatKind::Or(ref fields) = arm.pat.kind {
741             // look for multiple fields in this arm that contains at least one Wild pattern
742             if fields.len() > 1 && fields.iter().any(is_wild) {
743                 span_help_and_lint(
744                     cx,
745                     WILDCARD_IN_OR_PATTERNS,
746                     arm.pat.span,
747                     "wildcard pattern covers any other pattern as it will match anyway.",
748                     "Consider handling `_` separately.",
749                 );
750             }
751         }
752     }
753 }
754
755 /// Gets all arms that are unbounded `PatRange`s.
756 fn all_ranges<'a, 'tcx>(
757     cx: &LateContext<'a, 'tcx>,
758     arms: &'tcx [Arm<'_>],
759     ty: Ty<'tcx>,
760 ) -> Vec<SpannedRange<Constant>> {
761     arms.iter()
762         .flat_map(|arm| {
763             if let Arm {
764                 ref pat, guard: None, ..
765             } = *arm
766             {
767                 if let PatKind::Range(ref lhs, ref rhs, range_end) = pat.kind {
768                     let lhs = match lhs {
769                         Some(lhs) => constant(cx, cx.tables, lhs)?.0,
770                         None => miri_to_const(ty.numeric_min_val(cx.tcx)?)?,
771                     };
772                     let rhs = match rhs {
773                         Some(rhs) => constant(cx, cx.tables, rhs)?.0,
774                         None => miri_to_const(ty.numeric_max_val(cx.tcx)?)?,
775                     };
776                     let rhs = match range_end {
777                         RangeEnd::Included => Bound::Included(rhs),
778                         RangeEnd::Excluded => Bound::Excluded(rhs),
779                     };
780                     return Some(SpannedRange {
781                         span: pat.span,
782                         node: (lhs, rhs),
783                     });
784                 }
785
786                 if let PatKind::Lit(ref value) = pat.kind {
787                     let value = constant(cx, cx.tables, value)?.0;
788                     return Some(SpannedRange {
789                         span: pat.span,
790                         node: (value.clone(), Bound::Included(value)),
791                     });
792                 }
793             }
794             None
795         })
796         .collect()
797 }
798
799 #[derive(Debug, Eq, PartialEq)]
800 pub struct SpannedRange<T> {
801     pub span: Span,
802     pub node: (T, Bound<T>),
803 }
804
805 type TypedRanges = Vec<SpannedRange<u128>>;
806
807 /// Gets all `Int` ranges or all `Uint` ranges. Mixed types are an error anyway
808 /// and other types than
809 /// `Uint` and `Int` probably don't make sense.
810 fn type_ranges(ranges: &[SpannedRange<Constant>]) -> TypedRanges {
811     ranges
812         .iter()
813         .filter_map(|range| match range.node {
814             (Constant::Int(start), Bound::Included(Constant::Int(end))) => Some(SpannedRange {
815                 span: range.span,
816                 node: (start, Bound::Included(end)),
817             }),
818             (Constant::Int(start), Bound::Excluded(Constant::Int(end))) => Some(SpannedRange {
819                 span: range.span,
820                 node: (start, Bound::Excluded(end)),
821             }),
822             (Constant::Int(start), Bound::Unbounded) => Some(SpannedRange {
823                 span: range.span,
824                 node: (start, Bound::Unbounded),
825             }),
826             _ => None,
827         })
828         .collect()
829 }
830
831 fn is_unit_expr(expr: &Expr<'_>) -> bool {
832     match expr.kind {
833         ExprKind::Tup(ref v) if v.is_empty() => true,
834         ExprKind::Block(ref b, _) if b.stmts.is_empty() && b.expr.is_none() => true,
835         _ => false,
836     }
837 }
838
839 // Checks if arm has the form `None => None`
840 fn is_none_arm(arm: &Arm<'_>) -> bool {
841     match arm.pat.kind {
842         PatKind::Path(ref path) if match_qpath(path, &paths::OPTION_NONE) => true,
843         _ => false,
844     }
845 }
846
847 // Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`)
848 fn is_ref_some_arm(arm: &Arm<'_>) -> Option<BindingAnnotation> {
849     if_chain! {
850         if let PatKind::TupleStruct(ref path, ref pats, _) = arm.pat.kind;
851         if pats.len() == 1 && match_qpath(path, &paths::OPTION_SOME);
852         if let PatKind::Binding(rb, .., ident, _) = pats[0].kind;
853         if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
854         if let ExprKind::Call(ref e, ref args) = remove_blocks(&arm.body).kind;
855         if let ExprKind::Path(ref some_path) = e.kind;
856         if match_qpath(some_path, &paths::OPTION_SOME) && args.len() == 1;
857         if let ExprKind::Path(ref qpath) = args[0].kind;
858         if let &QPath::Resolved(_, ref path2) = qpath;
859         if path2.segments.len() == 1 && ident.name == path2.segments[0].ident.name;
860         then {
861             return Some(rb)
862         }
863     }
864     None
865 }
866
867 fn has_only_ref_pats(arms: &[Arm<'_>]) -> bool {
868     let mapped = arms
869         .iter()
870         .map(|a| {
871             match a.pat.kind {
872                 PatKind::Ref(..) => Some(true), // &-patterns
873                 PatKind::Wild => Some(false),   // an "anything" wildcard is also fine
874                 _ => None,                      // any other pattern is not fine
875             }
876         })
877         .collect::<Option<Vec<bool>>>();
878     // look for Some(v) where there's at least one true element
879     mapped.map_or(false, |v| v.iter().any(|el| *el))
880 }
881
882 pub fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
883 where
884     T: Copy + Ord,
885 {
886     #[derive(Copy, Clone, Debug, Eq, PartialEq)]
887     enum Kind<'a, T> {
888         Start(T, &'a SpannedRange<T>),
889         End(Bound<T>, &'a SpannedRange<T>),
890     }
891
892     impl<'a, T: Copy> Kind<'a, T> {
893         fn range(&self) -> &'a SpannedRange<T> {
894             match *self {
895                 Kind::Start(_, r) | Kind::End(_, r) => r,
896             }
897         }
898
899         fn value(self) -> Bound<T> {
900             match self {
901                 Kind::Start(t, _) => Bound::Included(t),
902                 Kind::End(t, _) => t,
903             }
904         }
905     }
906
907     impl<'a, T: Copy + Ord> PartialOrd for Kind<'a, T> {
908         fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
909             Some(self.cmp(other))
910         }
911     }
912
913     impl<'a, T: Copy + Ord> Ord for Kind<'a, T> {
914         fn cmp(&self, other: &Self) -> Ordering {
915             match (self.value(), other.value()) {
916                 (Bound::Included(a), Bound::Included(b)) | (Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
917                 // Range patterns cannot be unbounded (yet)
918                 (Bound::Unbounded, _) | (_, Bound::Unbounded) => unimplemented!(),
919                 (Bound::Included(a), Bound::Excluded(b)) => match a.cmp(&b) {
920                     Ordering::Equal => Ordering::Greater,
921                     other => other,
922                 },
923                 (Bound::Excluded(a), Bound::Included(b)) => match a.cmp(&b) {
924                     Ordering::Equal => Ordering::Less,
925                     other => other,
926                 },
927             }
928         }
929     }
930
931     let mut values = Vec::with_capacity(2 * ranges.len());
932
933     for r in ranges {
934         values.push(Kind::Start(r.node.0, r));
935         values.push(Kind::End(r.node.1, r));
936     }
937
938     values.sort();
939
940     for (a, b) in values.iter().zip(values.iter().skip(1)) {
941         match (a, b) {
942             (&Kind::Start(_, ra), &Kind::End(_, rb)) => {
943                 if ra.node != rb.node {
944                     return Some((ra, rb));
945                 }
946             },
947             (&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (),
948             _ => return Some((a.range(), b.range())),
949         }
950     }
951
952     None
953 }