Skip to main content

nativeview_hybrid_spec/
naming.rs

1//! Identifier and case-conversion utilities for Rust, TypeScript, C++20, ObjC++, and Kotlin.
2
3/// Converts `PascalCase`, `camelCase`, `kebab-case`, or acronym-prefixed names
4/// (e.g. `RCTModalHostView`, `testID`, `portrait-upside-down`) into `snake_case`.
5pub fn to_snake_case(input: &str) -> String {
6    let mut out = String::with_capacity(input.len() + 8);
7    let mut prev_was_underscore = true;
8    let mut prev: Option<char> = None;
9    let mut chars = input.chars().peekable();
10
11    while let Some(ch) = chars.next() {
12        if !ch.is_ascii_alphanumeric() {
13            if !prev_was_underscore && !out.is_empty() {
14                out.push('_');
15                prev_was_underscore = true;
16            }
17            prev = Some(ch);
18            continue;
19        }
20        if ch.is_ascii_uppercase() {
21            let prev_is_lower_or_digit =
22                prev.is_some_and(|p| p.is_ascii_lowercase() || p.is_ascii_digit());
23            let next_is_lower = chars.peek().is_some_and(char::is_ascii_lowercase);
24            let prev_is_upper = prev.is_some_and(|p| p.is_ascii_uppercase());
25            if !out.is_empty()
26                && !prev_was_underscore
27                && (prev_is_lower_or_digit || (prev_is_upper && next_is_lower))
28            {
29                out.push('_');
30            }
31            out.push(ch.to_ascii_lowercase());
32            prev_was_underscore = false;
33        } else {
34            out.push(ch.to_ascii_lowercase());
35            prev_was_underscore = false;
36        }
37        prev = Some(ch);
38    }
39
40    while out.ends_with('_') {
41        out.pop();
42    }
43    if out.is_empty() {
44        "unnamed".to_owned()
45    } else {
46        out
47    }
48}
49
50/// Converts any identifier or hyphenated string literal (e.g. `'portrait-upside-down'`,
51/// `on_count_change`, `small`) into `PascalCase`.
52pub fn to_pascal_case(input: &str) -> String {
53    let mut out = String::with_capacity(input.len());
54    let mut capitalize_next = true;
55
56    for ch in input.chars() {
57        if !ch.is_ascii_alphanumeric() {
58            capitalize_next = true;
59            continue;
60        }
61        if capitalize_next {
62            out.push(ch.to_ascii_uppercase());
63            capitalize_next = false;
64        } else {
65            out.push(ch);
66        }
67    }
68
69    if out.is_empty() {
70        "Unnamed".to_owned()
71    } else if out.chars().next().is_some_and(|c| c.is_ascii_digit()) {
72        format!("V{out}")
73    } else {
74        out
75    }
76}
77
78/// Converts an identifier into `camelCase`.
79pub fn to_camel_case(input: &str) -> String {
80    let mut out = String::with_capacity(input.len());
81    let mut capitalize_next = false;
82
83    for ch in input.chars() {
84        if !ch.is_ascii_alphanumeric() {
85            if !out.is_empty() {
86                capitalize_next = true;
87            }
88            continue;
89        }
90        if out.is_empty() {
91            out.push(ch.to_ascii_lowercase());
92            capitalize_next = false;
93        } else if capitalize_next {
94            out.push(ch.to_ascii_uppercase());
95            capitalize_next = false;
96        } else {
97            out.push(ch);
98        }
99    }
100
101    if out.is_empty() {
102        "unnamed".to_owned()
103    } else if out.as_bytes()[0].is_ascii_digit() {
104        format!("v{out}")
105    } else {
106        out
107    }
108}
109
110/// Converts a `SCREAMING_SNAKE_CASE` constant name into `camelCase` without allocating an
111/// intermediate lowercased `String`.
112pub fn screaming_snake_to_camel_case(input: &str) -> String {
113    let mut out = String::with_capacity(input.len());
114    let mut capitalize_next = false;
115    for ch in input.chars() {
116        if !ch.is_ascii_alphanumeric() {
117            if !out.is_empty() {
118                capitalize_next = true;
119            }
120            continue;
121        }
122        if capitalize_next {
123            out.push(ch.to_ascii_uppercase());
124            capitalize_next = false;
125        } else {
126            out.push(ch.to_ascii_lowercase());
127        }
128    }
129    if out.is_empty() {
130        "unnamed".to_owned()
131    } else if out.chars().next().is_some_and(|c| c.is_ascii_digit()) {
132        format!("v{out}")
133    } else {
134        out
135    }
136}
137
138/// Strips a leading `on` prefix from an event name if followed by an uppercase letter
139/// (e.g. `onCountChange` -> `countChange`, `onChange` -> `change`).
140pub fn strip_on_prefix(event_name: &str) -> String {
141    if let Some(rest) = event_name.strip_prefix("on_")
142        && !rest.is_empty()
143    {
144        return to_camel_case(rest);
145    }
146    if let Some(rest) = event_name.strip_prefix("on") {
147        let mut chars = rest.chars();
148        if let Some(first) = chars.next()
149            && first.is_ascii_uppercase()
150        {
151            let mut out = String::with_capacity(rest.len());
152            out.push(first.to_ascii_lowercase());
153            out.push_str(chars.as_str());
154            return out;
155        }
156    }
157    to_camel_case(event_name)
158}
159
160/// Escapes reserved Rust keywords or leading-digit identifiers.
161pub fn rust_ident(raw: &str) -> String {
162    let mut ident = to_snake_case(raw);
163    if ident.chars().next().is_some_and(|c| c.is_ascii_digit()) {
164        ident.insert(0, '_');
165    }
166    match ident.as_str() {
167        "as" | "async" | "await" | "break" | "const" | "continue" | "crate" | "dyn" | "else"
168        | "enum" | "extern" | "false" | "fn" | "for" | "if" | "impl" | "in" | "let" | "loop"
169        | "match" | "mod" | "move" | "mut" | "pub" | "ref" | "return" | "static" | "struct"
170        | "trait" | "true" | "type" | "unsafe" | "use" | "where" | "while" | "abstract"
171        | "become" | "box" | "do" | "final" | "macro" | "override" | "priv" | "try" | "typeof"
172        | "unsized" | "virtual" | "yield" => format!("r#{ident}"),
173        "self" | "Self" | "super" => format!("{ident}_"),
174        _ => ident,
175    }
176}
177
178/// Escapes reserved C++20 keywords.
179pub fn cpp_ident(raw: &str) -> String {
180    let mut ident = to_camel_case(raw);
181    if ident.chars().next().is_some_and(|c| c.is_ascii_digit()) {
182        ident.insert(0, '_');
183    }
184    match ident.as_str() {
185        "alignas" | "alignof" | "and" | "asm" | "auto" | "bool" | "break" | "case" | "catch"
186        | "char" | "class" | "concept" | "const" | "consteval" | "constexpr" | "constinit"
187        | "continue" | "default" | "delete" | "do" | "double" | "else" | "enum" | "explicit"
188        | "export" | "extern" | "false" | "float" | "for" | "friend" | "goto" | "if" | "inline"
189        | "int" | "long" | "mutable" | "namespace" | "new" | "noexcept" | "not" | "nullptr"
190        | "operator" | "or" | "private" | "protected" | "public" | "register" | "requires"
191        | "return" | "short" | "signed" | "sizeof" | "static" | "struct" | "switch"
192        | "template" | "this" | "throw" | "true" | "try" | "typedef" | "typeid" | "typename"
193        | "union" | "unsigned" | "using" | "virtual" | "void" | "volatile" | "while" => {
194            format!("{ident}_")
195        }
196        _ => ident,
197    }
198}
199
200fn escape_kotlin_keyword(mut ident: String) -> String {
201    if ident.chars().next().is_some_and(|c| c.is_ascii_digit()) {
202        ident.insert(0, '_');
203    }
204    match ident.as_str() {
205        "as" | "break" | "class" | "continue" | "do" | "else" | "false" | "for" | "fun" | "if"
206        | "in" | "interface" | "is" | "null" | "object" | "package" | "return" | "super"
207        | "this" | "throw" | "true" | "try" | "typealias" | "typeof" | "val" | "var" | "when"
208        | "while" => format!("`{ident}`"),
209        _ => ident,
210    }
211}
212
213/// Converts to camelCase and escapes reserved Kotlin keywords.
214pub fn kotlin_ident(raw: &str) -> String {
215    escape_kotlin_keyword(to_camel_case(raw))
216}
217
218/// Escapes a dotted Kotlin package segment without altering underscores or casing, keeping Kotlin
219/// `package` headers aligned 1-to-1 with Gradle `namespace` and RN `codegenConfig.android.javaPackageName`.
220pub fn kotlin_package_segment(raw: &str) -> String {
221    escape_kotlin_keyword(raw.trim().to_owned())
222}
223
224/// Escapes reserved Dart keywords.
225pub fn dart_ident(raw: &str) -> String {
226    let mut ident = to_camel_case(raw);
227    if ident.chars().next().is_some_and(|c| c.is_ascii_digit()) {
228        ident.insert(0, '_');
229    }
230    match ident.as_str() {
231        "abstract" | "as" | "assert" | "async" | "await" | "base" | "break" | "case" | "catch"
232        | "class" | "const" | "continue" | "covariant" | "default" | "deferred" | "do"
233        | "dynamic" | "else" | "enum" | "export" | "extends" | "extension" | "external"
234        | "factory" | "false" | "final" | "finally" | "for" | "Function" | "get" | "hide" | "if"
235        | "implements" | "import" | "in" | "interface" | "is" | "late" | "library" | "mixin"
236        | "new" | "null" | "on" | "operator" | "part" | "required" | "rethrow" | "return"
237        | "sealed" | "set" | "show" | "static" | "super" | "switch" | "sync" | "this" | "throw"
238        | "true" | "try" | "typedef" | "var" | "void" | "when" | "while" | "with" | "yield" => {
239            format!("{ident}Value")
240        }
241        _ => ident,
242    }
243}
244
245/// Escapes reserved Swift keywords.
246pub fn swift_ident(raw: &str) -> String {
247    let mut ident = to_camel_case(raw);
248    if ident.chars().next().is_some_and(|c| c.is_ascii_digit()) {
249        ident.insert(0, '_');
250    }
251    match ident.as_str() {
252        "associatedtype" | "class" | "deinit" | "enum" | "extension" | "fileprivate" | "func"
253        | "import" | "init" | "inout" | "internal" | "let" | "open" | "operator" | "private"
254        | "precedencegroup" | "protocol" | "public" | "rethrows" | "static" | "struct"
255        | "subscript" | "typealias" | "var" | "break" | "case" | "catch" | "continue"
256        | "default" | "defer" | "do" | "else" | "fallthrough" | "for" | "guard" | "if" | "in"
257        | "repeat" | "return" | "throw" | "switch" | "where" | "while" | "as" | "false" | "is"
258        | "nil" | "self" | "Self" | "super" | "throws" | "true" | "try" => format!("`{ident}`"),
259        _ => ident,
260    }
261}
262
263/// Converts any identifier into `kebab-case` (e.g. `NvCounterCard` -> `nv-counter-card`).
264pub fn to_kebab_case(input: &str) -> String {
265    to_snake_case(input).replace('_', "-")
266}
267
268/// Returns a valid Custom Element tag name prefixed with `nv-`
269/// (e.g. `NvCounterCard` -> `nv-counter-card`, `CounterCard` -> `nv-counter-card`).
270pub fn web_component_tag(component_name: &str) -> String {
271    let kebab = to_kebab_case(component_name);
272    if kebab.starts_with("nv-") {
273        kebab
274    } else {
275        format!("nv-{kebab}")
276    }
277}
278
279/// Escapes reserved C11/C++20 keywords for snake_case C struct/vtable field names.
280pub fn c_field_ident(raw: &str) -> String {
281    let mut s = to_snake_case(raw);
282    if s.chars().next().is_some_and(|c| c.is_ascii_digit()) {
283        s.insert(0, '_');
284    }
285    match s.as_str() {
286        "auto" | "break" | "case" | "char" | "const" | "continue" | "default" | "do" | "double"
287        | "else" | "enum" | "extern" | "float" | "for" | "goto" | "if" | "inline" | "int"
288        | "long" | "register" | "restrict" | "return" | "short" | "signed" | "sizeof"
289        | "static" | "struct" | "switch" | "typedef" | "union" | "unsigned" | "void"
290        | "volatile" | "while" | "class" | "delete" | "new" | "namespace" | "template" => {
291            format!("{s}_")
292        }
293        _ => s,
294    }
295}
296
297/// Formats an integer enum discriminant as a `PascalCase` variant identifier (`Neg1` / `V0`).
298pub fn int_enum_variant_pascal(v: i32) -> String {
299    if v < 0 {
300        format!("Neg{}", v.unsigned_abs())
301    } else {
302        format!("V{v}")
303    }
304}
305
306/// Formats an integer enum discriminant as a `camelCase` variant identifier (`neg1` / `v0`).
307pub fn int_enum_variant_camel(v: i32) -> String {
308    if v < 0 {
309        format!("neg{}", v.unsigned_abs())
310    } else {
311        format!("v{v}")
312    }
313}
314
315/// Escapes a string literal for C11, C++20, ObjC++, Rust, and Swift double-quoted literals.
316///
317/// Escaping `\` -> `\\` also prevents Swift `\(...)` string interpolation.
318pub fn escape_c_like_string(s: &str) -> String {
319    let mut out = String::with_capacity(s.len() + 2);
320    for ch in s.chars() {
321        match ch {
322            '\\' => out.push_str("\\\\"),
323            '"' => out.push_str("\\\""),
324            '\n' => out.push_str("\\n"),
325            '\r' => out.push_str("\\r"),
326            '\t' => out.push_str("\\t"),
327            '\0' => out.push_str("\\0"),
328            c => out.push(c),
329        }
330    }
331    out
332}
333
334/// Escapes a string literal for Kotlin double-quoted literals.
335///
336/// Escapes `$` -> `\$` so `"$HOME"` and `"${expr}"` never trigger Kotlin string interpolation,
337/// and escapes `\0` as `\u0000` (Kotlin does not accept `\0`).
338pub fn escape_kotlin_string(s: &str) -> String {
339    let mut out = String::with_capacity(s.len() + 2);
340    for ch in s.chars() {
341        match ch {
342            '\\' => out.push_str("\\\\"),
343            '"' => out.push_str("\\\""),
344            '$' => out.push_str("\\$"),
345            '\n' => out.push_str("\\n"),
346            '\r' => out.push_str("\\r"),
347            '\t' => out.push_str("\\t"),
348            '\0' => out.push_str("\\u0000"),
349            c => out.push(c),
350        }
351    }
352    out
353}
354
355/// Escapes a string literal for Dart single-quoted literals.
356///
357/// Escapes `$` -> `\$` so `'$HOME'` and `'${expr}'` never trigger Dart string interpolation,
358/// and escapes `\0` as `\u0000`.
359pub fn escape_dart_single_quoted_string(s: &str) -> String {
360    let mut out = String::with_capacity(s.len() + 2);
361    for ch in s.chars() {
362        match ch {
363            '\\' => out.push_str("\\\\"),
364            '\'' => out.push_str("\\'"),
365            '$' => out.push_str("\\$"),
366            '\n' => out.push_str("\\n"),
367            '\r' => out.push_str("\\r"),
368            '\t' => out.push_str("\\t"),
369            '\0' => out.push_str("\\u0000"),
370            c => out.push(c),
371        }
372    }
373    out
374}
375
376/// Sanitizes untrusted text for inclusion in a single-line (`//` or `///`) comment.
377///
378/// Strips CR/LF and Unicode line separators so comment breakout onto a new line is impossible.
379pub fn sanitize_single_line_comment(s: &str) -> String {
380    let mut out = String::with_capacity(s.len());
381    let mut prev_sep = false;
382    for ch in s.chars() {
383        if matches!(ch, '\r' | '\n' | '\u{2028}' | '\u{2029}') {
384            if !prev_sep && !out.is_empty() {
385                out.push(' ');
386            }
387            prev_sep = true;
388        } else {
389            out.push(ch);
390            prev_sep = false;
391        }
392    }
393    out.trim_end().to_owned()
394}
395
396/// Sanitizes untrusted text for inclusion in a block comment (`/* ... */` or `/** ... */`).
397///
398/// Breaks any `*/` sequence and strips `\r` so block-comment breakout is impossible.
399pub fn sanitize_block_comment(s: &str) -> String {
400    s.replace('\r', "").replace("*/", "* /")
401}
402
403/// Formats an `f64` so integral values always include `.0` (valid in C++, Kotlin, Swift, Dart, TS).
404pub fn format_float_literal(f: f64) -> String {
405    if !f.is_finite() {
406        return "0.0".to_owned();
407    }
408    let s = f.to_string();
409    if s.contains('.') || s.contains('e') || s.contains('E') {
410        s
411    } else {
412        format!("{s}.0")
413    }
414}
415
416/// Escapes a string literal for TypeScript/JavaScript single-quoted literals.
417pub fn escape_ts_single_quoted(s: &str) -> String {
418    let mut out = String::with_capacity(s.len() + 2);
419    for ch in s.chars() {
420        match ch {
421            '\\' => out.push_str("\\\\"),
422            '\'' => out.push_str("\\'"),
423            '\n' => out.push_str("\\n"),
424            '\r' => out.push_str("\\r"),
425            '\t' => out.push_str("\\t"),
426            '\0' => out.push_str("\\u0000"),
427            '\u{2028}' => out.push_str("\\u2028"),
428            '\u{2029}' => out.push_str("\\u2029"),
429            c => out.push(c),
430        }
431    }
432    out
433}
434
435#[cfg(test)]
436mod tests {
437    use super::{to_camel_case, to_pascal_case, to_snake_case};
438
439    #[test]
440    fn snake_case_handles_acronyms_separators_and_unicode() {
441        for (input, expected) in [
442            ("", "unnamed"),
443            ("___", "unnamed"),
444            ("RCTModalHostView", "rct_modal_host_view"),
445            ("testID", "test_id"),
446            ("portrait-upside-down", "portrait_upside_down"),
447            ("foo1Bar", "foo1_bar"),
448            ("a__b___", "a_b"),
449            ("aéB", "a_b"),
450            ("ABé", "ab"),
451        ] {
452            assert_eq!(to_snake_case(input), expected, "input={input:?}");
453        }
454    }
455
456    #[test]
457    fn camel_case_matches_lowercased_pascal_case() {
458        for input in [
459            "",
460            "___",
461            "a",
462            "A",
463            "ABc",
464            "foo_bar",
465            "foo__bar_",
466            "_foo",
467            "1foo",
468            "1Foo",
469            "1foo_bar",
470            "_1_a",
471            "aéB",
472            "éa",
473            "testID",
474        ] {
475            let pascal = to_pascal_case(input);
476            let mut chars = pascal.chars();
477            let expected = match chars.next() {
478                None => "unnamed".to_owned(),
479                Some(first) => format!("{}{}", first.to_ascii_lowercase(), chars.as_str()),
480            };
481            assert_eq!(to_camel_case(input), expected, "input={input:?}");
482        }
483    }
484}