aboutsummaryrefslogtreecommitdiff
path: root/crates/hir_ty/src/diagnostics/decl_check/case_conv.rs
blob: 3800f2a6b355a40f18bb71c7f5d429c59695136f (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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
//! Functions for string case manipulation, such as detecting the identifier case,
//! and converting it into appropriate form.

#[derive(Debug)]
enum DetectedCase {
    LowerCamelCase,
    UpperCamelCase,
    LowerSnakeCase,
    UpperSnakeCase,
    Unknown,
}

fn detect_case(ident: &str) -> DetectedCase {
    let trimmed_ident = ident.trim_matches('_');
    let first_lowercase = trimmed_ident.starts_with(|chr: char| chr.is_ascii_lowercase());
    let mut has_lowercase = first_lowercase;
    let mut has_uppercase = false;
    let mut has_underscore = false;

    for chr in trimmed_ident.chars() {
        if chr == '_' {
            has_underscore = true;
        } else if chr.is_ascii_uppercase() {
            has_uppercase = true;
        } else if chr.is_ascii_lowercase() {
            has_lowercase = true;
        }
    }

    if has_uppercase {
        if !has_lowercase {
            DetectedCase::UpperSnakeCase
        } else if !has_underscore {
            if first_lowercase {
                DetectedCase::LowerCamelCase
            } else {
                DetectedCase::UpperCamelCase
            }
        } else {
            // It has uppercase, it has lowercase, it has underscore.
            // No assumptions here
            DetectedCase::Unknown
        }
    } else {
        DetectedCase::LowerSnakeCase
    }
}

/// Converts an identifier to an UpperCamelCase form.
/// Returns `None` if the string is already is UpperCamelCase.
pub fn to_camel_case(ident: &str) -> Option<String> {
    let detected_case = detect_case(ident);

    match detected_case {
        DetectedCase::UpperCamelCase => return None,
        DetectedCase::LowerCamelCase => {
            let mut first_capitalized = false;
            let output = ident
                .chars()
                .map(|chr| {
                    if !first_capitalized && chr.is_ascii_lowercase() {
                        first_capitalized = true;
                        chr.to_ascii_uppercase()
                    } else {
                        chr
                    }
                })
                .collect();
            return Some(output);
        }
        _ => {}
    }

    let mut output = String::with_capacity(ident.len());

    let mut capital_added = false;
    for chr in ident.chars() {
        if chr.is_alphabetic() {
            if !capital_added {
                output.push(chr.to_ascii_uppercase());
                capital_added = true;
            } else {
                output.push(chr.to_ascii_lowercase());
            }
        } else if chr == '_' {
            // Skip this character and make the next one capital.
            capital_added = false;
        } else {
            // Put the characted as-is.
            output.push(chr);
        }
    }

    if output == ident {
        // While we didn't detect the correct case at the beginning, there
        // may be special cases: e.g. `A` is both valid CamelCase and UPPER_SNAKE_CASE.
        None
    } else {
        Some(output)
    }
}

/// Converts an identifier to a lower_snake_case form.
/// Returns `None` if the string is already in lower_snake_case.
pub fn to_lower_snake_case(ident: &str) -> Option<String> {
    // First, assume that it's UPPER_SNAKE_CASE.
    match detect_case(ident) {
        DetectedCase::LowerSnakeCase => return None,
        DetectedCase::UpperSnakeCase => {
            return Some(ident.chars().map(|chr| chr.to_ascii_lowercase()).collect())
        }
        _ => {}
    }

    // Otherwise, assume that it's CamelCase.
    let lower_snake_case = stdx::to_lower_snake_case(ident);

    if lower_snake_case == ident {
        // While we didn't detect the correct case at the beginning, there
        // may be special cases: e.g. `a` is both valid camelCase and snake_case.
        None
    } else {
        Some(lower_snake_case)
    }
}

/// Converts an identifier to an UPPER_SNAKE_CASE form.
/// Returns `None` if the string is already is UPPER_SNAKE_CASE.
pub fn to_upper_snake_case(ident: &str) -> Option<String> {
    match detect_case(ident) {
        DetectedCase::UpperSnakeCase => return None,
        DetectedCase::LowerSnakeCase => {
            return Some(ident.chars().map(|chr| chr.to_ascii_uppercase()).collect())
        }
        _ => {}
    }

    // Normalize the string from whatever form it's in currently, and then just make it uppercase.
    let upper_snake_case = stdx::to_upper_snake_case(ident);

    if upper_snake_case == ident {
        // While we didn't detect the correct case at the beginning, there
        // may be special cases: e.g. `A` is both valid CamelCase and UPPER_SNAKE_CASE.
        None
    } else {
        Some(upper_snake_case)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use expect_test::{expect, Expect};

    fn check<F: Fn(&str) -> Option<String>>(fun: F, input: &str, expect: Expect) {
        // `None` is translated to empty string, meaning that there is nothing to fix.
        let output = fun(input).unwrap_or_default();

        expect.assert_eq(&output);
    }

    #[test]
    fn test_to_lower_snake_case() {
        check(to_lower_snake_case, "lower_snake_case", expect![[""]]);
        check(to_lower_snake_case, "UPPER_SNAKE_CASE", expect![["upper_snake_case"]]);
        check(to_lower_snake_case, "Weird_Case", expect![["weird_case"]]);
        check(to_lower_snake_case, "CamelCase", expect![["camel_case"]]);
        check(to_lower_snake_case, "lowerCamelCase", expect![["lower_camel_case"]]);
        check(to_lower_snake_case, "a", expect![[""]]);
    }

    #[test]
    fn test_to_camel_case() {
        check(to_camel_case, "CamelCase", expect![[""]]);
        check(to_camel_case, "CamelCase_", expect![[""]]);
        check(to_camel_case, "_CamelCase", expect![[""]]);
        check(to_camel_case, "lowerCamelCase", expect![["LowerCamelCase"]]);
        check(to_camel_case, "lower_snake_case", expect![["LowerSnakeCase"]]);
        check(to_camel_case, "UPPER_SNAKE_CASE", expect![["UpperSnakeCase"]]);
        check(to_camel_case, "Weird_Case", expect![["WeirdCase"]]);
        check(to_camel_case, "name", expect![["Name"]]);
        check(to_camel_case, "A", expect![[""]]);
    }

    #[test]
    fn test_to_upper_snake_case() {
        check(to_upper_snake_case, "UPPER_SNAKE_CASE", expect![[""]]);
        check(to_upper_snake_case, "lower_snake_case", expect![["LOWER_SNAKE_CASE"]]);
        check(to_upper_snake_case, "Weird_Case", expect![["WEIRD_CASE"]]);
        check(to_upper_snake_case, "CamelCase", expect![["CAMEL_CASE"]]);
        check(to_upper_snake_case, "lowerCamelCase", expect![["LOWER_CAMEL_CASE"]]);
        check(to_upper_snake_case, "A", expect![[""]]);
    }
}