]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/match_str_case_mismatch.rs
Auto merge of #92740 - cuviper:update-rayons, r=Mark-Simulacrum
[rust.git] / src / tools / clippy / clippy_lints / src / match_str_case_mismatch.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::ty::is_type_diagnostic_item;
3 use rustc_ast::ast::LitKind;
4 use rustc_errors::Applicability;
5 use rustc_hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
6 use rustc_hir::{Arm, Expr, ExprKind, MatchSource, PatKind};
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_middle::hir::map::Map;
9 use rustc_middle::lint::in_external_macro;
10 use rustc_middle::ty;
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
12 use rustc_span::symbol::Symbol;
13 use rustc_span::{sym, Span};
14
15 declare_clippy_lint! {
16     /// ### What it does
17     /// Checks for `match` expressions modifying the case of a string with non-compliant arms
18     ///
19     /// ### Why is this bad?
20     /// The arm is unreachable, which is likely a mistake
21     ///
22     /// ### Example
23     /// ```rust
24     /// # let text = "Foo";
25     ///
26     /// match &*text.to_ascii_lowercase() {
27     ///     "foo" => {},
28     ///     "Bar" => {},
29     ///     _ => {},
30     /// }
31     /// ```
32     /// Use instead:
33     /// ```rust
34     /// # let text = "Foo";
35     ///
36     /// match &*text.to_ascii_lowercase() {
37     ///     "foo" => {},
38     ///     "bar" => {},
39     ///     _ => {},
40     /// }
41     /// ```
42     #[clippy::version = "1.58.0"]
43     pub MATCH_STR_CASE_MISMATCH,
44     correctness,
45     "creation of a case altering match expression with non-compliant arms"
46 }
47
48 declare_lint_pass!(MatchStrCaseMismatch => [MATCH_STR_CASE_MISMATCH]);
49
50 #[derive(Debug)]
51 enum CaseMethod {
52     LowerCase,
53     AsciiLowerCase,
54     UpperCase,
55     AsciiUppercase,
56 }
57
58 impl<'tcx> LateLintPass<'tcx> for MatchStrCaseMismatch {
59     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
60         if_chain! {
61             if !in_external_macro(cx.tcx.sess, expr.span);
62             if let ExprKind::Match(match_expr, arms, MatchSource::Normal) = expr.kind;
63             if let ty::Ref(_, ty, _) = cx.typeck_results().expr_ty(match_expr).kind();
64             if let ty::Str = ty.kind();
65             then {
66                 let mut visitor = MatchExprVisitor {
67                     cx,
68                     case_method: None,
69                 };
70
71                 visitor.visit_expr(match_expr);
72
73                 if let Some(case_method) = visitor.case_method {
74                     if let Some((bad_case_span, bad_case_sym)) = verify_case(&case_method, arms) {
75                         lint(cx, &case_method, bad_case_span, bad_case_sym.as_str());
76                     }
77                 }
78             }
79         }
80     }
81 }
82
83 struct MatchExprVisitor<'a, 'tcx> {
84     cx: &'a LateContext<'tcx>,
85     case_method: Option<CaseMethod>,
86 }
87
88 impl<'a, 'tcx> Visitor<'tcx> for MatchExprVisitor<'a, 'tcx> {
89     type Map = Map<'tcx>;
90
91     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
92         NestedVisitorMap::None
93     }
94
95     fn visit_expr(&mut self, ex: &'tcx Expr<'_>) {
96         match ex.kind {
97             ExprKind::MethodCall(segment, _, [receiver], _) if self.case_altered(segment.ident.as_str(), receiver) => {
98             },
99             _ => walk_expr(self, ex),
100         }
101     }
102 }
103
104 impl<'a, 'tcx> MatchExprVisitor<'a, 'tcx> {
105     fn case_altered(&mut self, segment_ident: &str, receiver: &Expr<'_>) -> bool {
106         if let Some(case_method) = get_case_method(segment_ident) {
107             let ty = self.cx.typeck_results().expr_ty(receiver).peel_refs();
108
109             if is_type_diagnostic_item(self.cx, ty, sym::String) || ty.kind() == &ty::Str {
110                 self.case_method = Some(case_method);
111                 return true;
112             }
113         }
114
115         false
116     }
117 }
118
119 fn get_case_method(segment_ident_str: &str) -> Option<CaseMethod> {
120     match segment_ident_str {
121         "to_lowercase" => Some(CaseMethod::LowerCase),
122         "to_ascii_lowercase" => Some(CaseMethod::AsciiLowerCase),
123         "to_uppercase" => Some(CaseMethod::UpperCase),
124         "to_ascii_uppercase" => Some(CaseMethod::AsciiUppercase),
125         _ => None,
126     }
127 }
128
129 fn verify_case<'a>(case_method: &'a CaseMethod, arms: &'a [Arm<'_>]) -> Option<(Span, Symbol)> {
130     let case_check = match case_method {
131         CaseMethod::LowerCase => |input: &str| -> bool { input.chars().all(|c| c.to_lowercase().next() == Some(c)) },
132         CaseMethod::AsciiLowerCase => |input: &str| -> bool { !input.chars().any(|c| c.is_ascii_uppercase()) },
133         CaseMethod::UpperCase => |input: &str| -> bool { input.chars().all(|c| c.to_uppercase().next() == Some(c)) },
134         CaseMethod::AsciiUppercase => |input: &str| -> bool { !input.chars().any(|c| c.is_ascii_lowercase()) },
135     };
136
137     for arm in arms {
138         if_chain! {
139             if let PatKind::Lit(Expr {
140                                 kind: ExprKind::Lit(lit),
141                                 ..
142                             }) = arm.pat.kind;
143             if let LitKind::Str(symbol, _) = lit.node;
144             let input = symbol.as_str();
145             if !case_check(input);
146             then {
147                 return Some((lit.span, symbol));
148             }
149         }
150     }
151
152     None
153 }
154
155 fn lint(cx: &LateContext<'_>, case_method: &CaseMethod, bad_case_span: Span, bad_case_str: &str) {
156     let (method_str, suggestion) = match case_method {
157         CaseMethod::LowerCase => ("to_lowercase", bad_case_str.to_lowercase()),
158         CaseMethod::AsciiLowerCase => ("to_ascii_lowercase", bad_case_str.to_ascii_lowercase()),
159         CaseMethod::UpperCase => ("to_uppercase", bad_case_str.to_uppercase()),
160         CaseMethod::AsciiUppercase => ("to_ascii_uppercase", bad_case_str.to_ascii_uppercase()),
161     };
162
163     span_lint_and_sugg(
164         cx,
165         MATCH_STR_CASE_MISMATCH,
166         bad_case_span,
167         "this `match` arm has a differing case than its expression",
168         &*format!("consider changing the case of this arm to respect `{}`", method_str),
169         format!("\"{}\"", suggestion),
170         Applicability::MachineApplicable,
171     );
172 }