Skip to main content

wowlab_tidy/languages/rust/rules/style/
naming.rs

1//! Shared identifier-analysis helpers for the style naming rules.
2
3use ra_ap_syntax::ast::{self, HasName};
4
5/// Split a CamelCase identifier into words; an acronym run like `HTML` counts as one word.
6pub(super) fn segments(name: &str) -> Vec<String> {
7    let chars: Vec<char> = name.chars().collect();
8    let mut words = Vec::new();
9    let mut current = String::new();
10
11    for (index, &c) in chars.iter().enumerate() {
12        if c == '_' {
13            if !current.is_empty() {
14                words.push(std::mem::take(&mut current));
15            }
16
17            continue;
18        }
19
20        let after_word_end = index
21            .checked_sub(1)
22            .and_then(|prev| chars.get(prev))
23            .is_some_and(|prev| prev.is_lowercase() || prev.is_ascii_digit());
24        let starts_new_word = chars.get(index + 1).is_some_and(char::is_ascii_lowercase);
25
26        if c.is_uppercase() && !current.is_empty() && (after_word_end || starts_new_word) {
27            words.push(std::mem::take(&mut current));
28        }
29
30        current.push(c);
31    }
32
33    if !current.is_empty() {
34        words.push(current);
35    }
36
37    words
38}
39
40pub(super) fn type_def_name(item: &ast::Item) -> Option<ast::Name> {
41    match item {
42        ast::Item::Struct(item) => item.name(),
43        ast::Item::Enum(item) => item.name(),
44        ast::Item::Trait(item) => item.name(),
45        ast::Item::TypeAlias(item) => item.name(),
46        _ => None,
47    }
48}