Skip to main content

alef_codegen/
naming.rs

1use heck::{ToLowerCamelCase, ToPascalCase, ToShoutySnakeCase, ToSnakeCase};
2
3/// Convert a Rust snake_case name to the target language convention.
4pub fn to_python_name(name: &str) -> String {
5    name.to_snake_case()
6}
7
8/// Convert a Rust snake_case name to Node.js/TypeScript lowerCamelCase convention.
9pub fn to_node_name(name: &str) -> String {
10    name.to_lower_camel_case()
11}
12
13/// Convert a Rust snake_case name to Ruby snake_case convention.
14pub fn to_ruby_name(name: &str) -> String {
15    name.to_snake_case()
16}
17
18/// Convert a Rust snake_case name to PHP lowerCamelCase convention.
19pub fn to_php_name(name: &str) -> String {
20    name.to_lower_camel_case()
21}
22
23/// Convert a Rust snake_case name to Elixir snake_case convention.
24pub fn to_elixir_name(name: &str) -> String {
25    name.to_snake_case()
26}
27
28/// Well-known Go acronyms that must be fully uppercased per Go naming conventions.
29/// See: https://go.dev/wiki/CodeReviewComments#initialisms
30const GO_ACRONYMS: &[&str] = &[
31    "API", "ASCII", "CPU", "CSS", "DNS", "EOF", "FTP", "GID", "GUI", "HTML", "HTTP", "HTTPS", "ID", "IMAP", "IP",
32    "JSON", "LHS", "MFA", "POP", "QPS", "RAM", "RHS", "RPC", "SLA", "SMTP", "SQL", "SSH", "SSL", "TCP", "TLS", "TTL",
33    "UDP", "UI", "UID", "UUID", "URI", "URL", "UTF8", "VM", "XML", "XMPP", "XSRF", "XSS",
34];
35
36/// Apply Go acronym uppercasing to a PascalCase name.
37///
38/// Scans word boundaries in the PascalCase string and replaces any run of
39/// characters that matches a known Go acronym (case-insensitively) with the
40/// all-caps form. For example `ImageUrl` becomes `ImageURL` and `UserId`
41/// becomes `UserID`.
42fn apply_go_acronyms(name: &str) -> String {
43    if name.is_empty() {
44        return name.to_string();
45    }
46
47    // Split the PascalCase string into words at uppercase letter boundaries.
48    // Each "word" is a contiguous sequence starting with an uppercase letter.
49    let mut words: Vec<&str> = Vec::new();
50    let mut word_start = 0;
51    let bytes = name.as_bytes();
52    for i in 1..bytes.len() {
53        if bytes[i].is_ascii_uppercase() {
54            words.push(&name[word_start..i]);
55            word_start = i;
56        }
57    }
58    words.push(&name[word_start..]);
59
60    // For each word, check if it matches a known acronym (case-insensitive).
61    let mut result = String::with_capacity(name.len());
62    let mut i = 0;
63    while i < words.len() {
64        // Try to match as many consecutive words as possible to a single acronym
65        // (handles acronyms like "UTF8" which span one word but look like two parts).
66        let word = words[i];
67        let upper = word.to_ascii_uppercase();
68        if GO_ACRONYMS.contains(&upper.as_str()) {
69            result.push_str(&upper);
70        } else {
71            result.push_str(word);
72        }
73        i += 1;
74    }
75    result
76}
77
78/// Convert a Rust snake_case name to Go PascalCase convention with acronym uppercasing.
79pub fn to_go_name(name: &str) -> String {
80    apply_go_acronyms(&name.to_pascal_case())
81}
82
83/// Apply Go acronym uppercasing to a name that is already in PascalCase (e.g. an IR type name).
84///
85/// IR type names come directly from Rust PascalCase (e.g. `ImageUrl`, `JsonSchemaFormat`).
86/// This function uppercases known acronym segments so they conform to Go naming conventions
87/// (e.g. `ImageUrl` → `ImageURL`, `JsonSchemaFormat` → `JSONSchemaFormat`).
88pub fn go_type_name(name: &str) -> String {
89    apply_go_acronyms(name)
90}
91
92/// Convert a Rust snake_case parameter/variable name to Go lowerCamelCase with acronym uppercasing.
93///
94/// Go naming conventions require that acronyms in identifiers be fully uppercased.
95/// `to_lower_camel_case` alone converts `base_url` → `baseUrl`, but Go wants `baseURL`.
96/// This function converts via PascalCase (which applies acronym uppercasing) then lowercases
97/// the first "word" (the initial run of uppercase letters treated as a unit) while preserving
98/// the case of subsequent words/acronyms:
99/// - `base_url`  → `BaseURL`  → `baseURL`
100/// - `api_key`   → `APIKey`   → `apiKey`
101/// - `user_id`   → `UserID`   → `userID`
102/// - `json`      → `JSON`     → `json`
103pub fn go_param_name(name: &str) -> String {
104    let pascal = apply_go_acronyms(&name.to_pascal_case());
105    if pascal.is_empty() {
106        return pascal;
107    }
108    let bytes = pascal.as_bytes();
109    // Find the boundary of the first "word":
110    // - If the string begins with a multi-char uppercase run followed by a lowercase letter,
111    //   the run minus its last char is an acronym prefix (e.g. "APIKey": run="API", next='K')
112    //   → lowercase "AP" and keep "IKey" → "apIKey" ... but Go actually wants "apiKey".
113    //   The real rule: lowercase the whole leading uppercase run regardless, because the
114    //   acronym-prefix IS the first word.
115    // - If the string begins with a single uppercase char (e.g. "BaseURL"), lowercase just it.
116    //
117    // Concretely: find how many leading bytes are uppercase. If that whole run is followed by
118    // end-of-string, lowercase everything. If followed by more chars, lowercase the entire run.
119    // For "APIKey": upper_len=3, next='K'(uppercase) but that starts the second word.
120    // Actually: scan for the first lowercase char to find where the first word ends.
121    let first_lower = bytes.iter().position(|b| b.is_ascii_lowercase());
122    match first_lower {
123        None => {
124            // Entire string is uppercase (single acronym like "JSON", "URL") — all lowercase.
125            pascal.to_lowercase()
126        }
127        Some(0) => {
128            // Starts with lowercase (already correct)
129            pascal
130        }
131        Some(pos) => {
132            // pos is the index of the first lowercase char.
133            // The first "word" ends just before pos-1 (the char at pos-1 is the first char of
134            // the next PascalCase word that isnds with a lowercase continuation).
135            // For "BaseURL": pos=1 ('a'), so uppercase run = ['B'], lowercase just index 0.
136            // For "APIKey":  pos=4 ('e' in "Key"), uppercase run = "APIK", next lower = 'e',
137            //   so word boundary is at pos-1=3 ('K' is start of "Key").
138            //   → lowercase "API" (indices 0..2), keep "Key" → "apiKey" ✓
139            // For "UserID":  pos=1 ('s'), uppercase run starts at 'U', lowercase just 'U' → "userID"... wait
140            //   "UserID": 'U'(upper),'s'(lower) → pos=1, word="U", lower "U" → "u"+"serID" = "userID" ✓
141            let word_end = if pos > 1 { pos - 1 } else { 1 };
142            let lower_prefix = pascal[..word_end].to_lowercase();
143            format!("{}{}", lower_prefix, &pascal[word_end..])
144        }
145    }
146}
147
148/// Convert a Rust snake_case name to Java lowerCamelCase convention.
149pub fn to_java_name(name: &str) -> String {
150    name.to_lower_camel_case()
151}
152
153/// Convert a Rust snake_case name to C# PascalCase convention.
154pub fn to_csharp_name(name: &str) -> String {
155    name.to_pascal_case()
156}
157
158/// Convert a Rust name to a C-style prefixed snake_case identifier (e.g. `prefix_name`).
159pub fn to_c_name(prefix: &str, name: &str) -> String {
160    format!("{}_{}", prefix, name.to_snake_case())
161}
162
163/// Convert a Rust type name to class name convention for target language.
164pub fn to_class_name(name: &str) -> String {
165    name.to_pascal_case()
166}
167
168/// Convert to SCREAMING_SNAKE for constants.
169pub fn to_constant_name(name: &str) -> String {
170    name.to_shouty_snake_case()
171}