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