summaryrefslogtreecommitdiffstats
path: root/src/tools/clippy/clippy_lints/src/matches/match_str_case_mismatch.rs
blob: 6647322caa37a846520edfc81251261d9e312c6c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::ty::is_type_diagnostic_item;
use rustc_ast::ast::LitKind;
use rustc_errors::Applicability;
use rustc_hir::intravisit::{walk_expr, Visitor};
use rustc_hir::{Arm, Expr, ExprKind, PatKind};
use rustc_lint::LateContext;
use rustc_middle::ty;
use rustc_span::symbol::Symbol;
use rustc_span::{sym, Span};

use super::MATCH_STR_CASE_MISMATCH;

#[derive(Debug)]
enum CaseMethod {
    LowerCase,
    AsciiLowerCase,
    UpperCase,
    AsciiUppercase,
}

pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, scrutinee: &'tcx Expr<'_>, arms: &'tcx [Arm<'_>]) {
    if_chain! {
        if let ty::Ref(_, ty, _) = cx.typeck_results().expr_ty(scrutinee).kind();
        if let ty::Str = ty.kind();
        then {
            let mut visitor = MatchExprVisitor {
                cx,
                case_method: None,
            };

            visitor.visit_expr(scrutinee);

            if let Some(case_method) = visitor.case_method {
                if let Some((bad_case_span, bad_case_sym)) = verify_case(&case_method, arms) {
                    lint(cx, &case_method, bad_case_span, bad_case_sym.as_str());
                }
            }
        }
    }
}

struct MatchExprVisitor<'a, 'tcx> {
    cx: &'a LateContext<'tcx>,
    case_method: Option<CaseMethod>,
}

impl<'a, 'tcx> Visitor<'tcx> for MatchExprVisitor<'a, 'tcx> {
    fn visit_expr(&mut self, ex: &'tcx Expr<'_>) {
        match ex.kind {
            ExprKind::MethodCall(segment, receiver, [], _) if self.case_altered(segment.ident.as_str(), receiver) => {},
            _ => walk_expr(self, ex),
        }
    }
}

impl<'a, 'tcx> MatchExprVisitor<'a, 'tcx> {
    fn case_altered(&mut self, segment_ident: &str, receiver: &Expr<'_>) -> bool {
        if let Some(case_method) = get_case_method(segment_ident) {
            let ty = self.cx.typeck_results().expr_ty(receiver).peel_refs();

            if is_type_diagnostic_item(self.cx, ty, sym::String) || ty.kind() == &ty::Str {
                self.case_method = Some(case_method);
                return true;
            }
        }

        false
    }
}

fn get_case_method(segment_ident_str: &str) -> Option<CaseMethod> {
    match segment_ident_str {
        "to_lowercase" => Some(CaseMethod::LowerCase),
        "to_ascii_lowercase" => Some(CaseMethod::AsciiLowerCase),
        "to_uppercase" => Some(CaseMethod::UpperCase),
        "to_ascii_uppercase" => Some(CaseMethod::AsciiUppercase),
        _ => None,
    }
}

fn verify_case<'a>(case_method: &'a CaseMethod, arms: &'a [Arm<'_>]) -> Option<(Span, Symbol)> {
    let case_check = match case_method {
        CaseMethod::LowerCase => |input: &str| -> bool { input.chars().all(|c| c.to_lowercase().next() == Some(c)) },
        CaseMethod::AsciiLowerCase => |input: &str| -> bool { !input.chars().any(|c| c.is_ascii_uppercase()) },
        CaseMethod::UpperCase => |input: &str| -> bool { input.chars().all(|c| c.to_uppercase().next() == Some(c)) },
        CaseMethod::AsciiUppercase => |input: &str| -> bool { !input.chars().any(|c| c.is_ascii_lowercase()) },
    };

    for arm in arms {
        if_chain! {
            if let PatKind::Lit(Expr {
                                kind: ExprKind::Lit(lit),
                                ..
                            }) = arm.pat.kind;
            if let LitKind::Str(symbol, _) = lit.node;
            let input = symbol.as_str();
            if !case_check(input);
            then {
                return Some((lit.span, symbol));
            }
        }
    }

    None
}

fn lint(cx: &LateContext<'_>, case_method: &CaseMethod, bad_case_span: Span, bad_case_str: &str) {
    let (method_str, suggestion) = match case_method {
        CaseMethod::LowerCase => ("to_lowercase", bad_case_str.to_lowercase()),
        CaseMethod::AsciiLowerCase => ("to_ascii_lowercase", bad_case_str.to_ascii_lowercase()),
        CaseMethod::UpperCase => ("to_uppercase", bad_case_str.to_uppercase()),
        CaseMethod::AsciiUppercase => ("to_ascii_uppercase", bad_case_str.to_ascii_uppercase()),
    };

    span_lint_and_sugg(
        cx,
        MATCH_STR_CASE_MISMATCH,
        bad_case_span,
        "this `match` arm has a differing case than its expression",
        &format!("consider changing the case of this arm to respect `{method_str}`"),
        format!("\"{suggestion}\""),
        Applicability::MachineApplicable,
    );
}