]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/misc_early/unneeded_wildcard_pattern.rs
Rollup merge of #85760 - ChrisDenton:path-doc-platform-specific, r=m-ou-se
[rust.git] / src / tools / clippy / clippy_lints / src / misc_early / unneeded_wildcard_pattern.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use rustc_ast::ast::{Pat, PatKind};
3 use rustc_errors::Applicability;
4 use rustc_lint::EarlyContext;
5 use rustc_span::source_map::Span;
6
7 use super::UNNEEDED_WILDCARD_PATTERN;
8
9 pub(super) fn check(cx: &EarlyContext<'_>, pat: &Pat) {
10     if let PatKind::TupleStruct(_, ref patterns) | PatKind::Tuple(ref patterns) = pat.kind {
11         if let Some(rest_index) = patterns.iter().position(|pat| pat.is_rest()) {
12             if let Some((left_index, left_pat)) = patterns[..rest_index]
13                 .iter()
14                 .rev()
15                 .take_while(|pat| matches!(pat.kind, PatKind::Wild))
16                 .enumerate()
17                 .last()
18             {
19                 span_lint(cx, left_pat.span.until(patterns[rest_index].span), left_index == 0);
20             }
21
22             if let Some((right_index, right_pat)) = patterns[rest_index + 1..]
23                 .iter()
24                 .take_while(|pat| matches!(pat.kind, PatKind::Wild))
25                 .enumerate()
26                 .last()
27             {
28                 span_lint(
29                     cx,
30                     patterns[rest_index].span.shrink_to_hi().to(right_pat.span),
31                     right_index == 0,
32                 );
33             }
34         }
35     }
36 }
37
38 fn span_lint(cx: &EarlyContext<'_>, span: Span, only_one: bool) {
39     span_lint_and_sugg(
40         cx,
41         UNNEEDED_WILDCARD_PATTERN,
42         span,
43         if only_one {
44             "this pattern is unneeded as the `..` pattern can match that element"
45         } else {
46             "these patterns are unneeded as the `..` pattern can match those elements"
47         },
48         if only_one { "remove it" } else { "remove them" },
49         "".to_string(),
50         Applicability::MachineApplicable,
51     );
52 }