Skip to main content

hyprstream_rpc_derive/
util.rs

1//! Utility functions for name conversion and type mapping.
2
3use proc_macro2::TokenStream;
4use quote::quote;
5
6use crate::schema::types::{EnumDef, StructDef};
7#[cfg(test)]
8use crate::schema::types::{FieldDef, FieldSection};
9
10// ─────────────────────────────────────────────────────────────────────────────
11// CapnpType — Centralized type classification
12// ─────────────────────────────────────────────────────────────────────────────
13
14/// Classified Cap'n Proto type for codegen dispatch.
15///
16/// Centralizes the type classification that was previously done via string
17/// matching in 19+ match expressions across the codegen modules. Use
18/// `CapnpType::classify()` to create from a raw type name string.
19#[derive(Debug, Clone, PartialEq)]
20pub enum CapnpType {
21    Void,
22    Bool,
23    Text,
24    Data,
25    UInt8,
26    UInt16,
27    UInt32,
28    UInt64,
29    Int8,
30    Int16,
31    Int32,
32    Int64,
33    Float32,
34    Float64,
35    ListText,
36    ListData,
37    /// List of a primitive numeric type (e.g., `List(Int64)` → `ListPrimitive(Int64)`).
38    ListPrimitive(Box<CapnpType>),
39    /// List of a named struct type (e.g., `List(ModelInfo)` → `ListStruct("ModelInfo")`).
40    ListStruct(String),
41    /// A known struct type from the schema.
42    Struct(String),
43    /// A known enum type from the schema.
44    Enum(String),
45    /// Unknown/fallback type (not a primitive, struct, or enum in the schema).
46    Unknown(String),
47}
48
49impl CapnpType {
50    /// Classify a Cap'n Proto type name, resolving structs and enums from schema context.
51    pub fn classify(type_name: &str, structs: &[StructDef], enums: &[EnumDef]) -> Self {
52        match type_name {
53            "Void" => Self::Void,
54            "Bool" => Self::Bool,
55            "Text" => Self::Text,
56            "Data" => Self::Data,
57            "UInt8" => Self::UInt8,
58            "UInt16" => Self::UInt16,
59            "UInt32" => Self::UInt32,
60            "UInt64" => Self::UInt64,
61            "Int8" => Self::Int8,
62            "Int16" => Self::Int16,
63            "Int32" => Self::Int32,
64            "Int64" => Self::Int64,
65            "Float32" => Self::Float32,
66            "Float64" => Self::Float64,
67            t if t.starts_with("List(") && t.ends_with(')') => {
68                let inner = &t[5..t.len() - 1];
69                match inner {
70                    "Text" => Self::ListText,
71                    "Data" => Self::ListData,
72                    _ => {
73                        let inner_type = Self::classify(inner, structs, enums);
74                        if inner_type.is_numeric() || inner_type.is_list() {
75                            Self::ListPrimitive(Box::new(inner_type))
76                        } else {
77                            Self::ListStruct(inner.to_owned())
78                        }
79                    }
80                }
81            }
82            t => {
83                if enums.iter().any(|e| e.name == t) {
84                    Self::Enum(t.to_owned())
85                } else if structs.iter().any(|s| s.name == t) {
86                    Self::Struct(t.to_owned())
87                } else {
88                    Self::Unknown(t.to_owned())
89                }
90            }
91        }
92    }
93
94    /// Classify without schema context (primitives and lists only; structs/enums become Unknown).
95    pub fn classify_primitive(type_name: &str) -> Self {
96        Self::classify(type_name, &[], &[])
97    }
98
99    /// The owned Rust type string (e.g., `"String"`, `"u32"`, `"Vec<String>"`).
100    pub fn rust_owned_type(&self) -> String {
101        match self {
102            Self::Void => "()".into(),
103            Self::Bool => "bool".into(),
104            Self::Text => "String".into(),
105            Self::Data | Self::Unknown(_) => "Vec<u8>".into(),
106            Self::UInt8 => "u8".into(),
107            Self::UInt16 => "u16".into(),
108            Self::UInt32 => "u32".into(),
109            Self::UInt64 => "u64".into(),
110            Self::Int8 => "i8".into(),
111            Self::Int16 => "i16".into(),
112            Self::Int32 => "i32".into(),
113            Self::Int64 => "i64".into(),
114            Self::Float32 => "f32".into(),
115            Self::Float64 => "f64".into(),
116            Self::ListText => "Vec<String>".into(),
117            Self::ListData => "Vec<Vec<u8>>".into(),
118            Self::ListPrimitive(inner) => format!("Vec<{}>", inner.rust_owned_type()),
119            Self::ListStruct(inner) => format!("Vec<{inner}>"),
120            Self::Struct(name) | Self::Enum(name) => name.clone(),
121        }
122    }
123
124    /// The Rust parameter type string (borrowed where appropriate).
125    pub fn rust_param_type(&self) -> String {
126        match self {
127            Self::Text | Self::Enum(_) => "&str".into(),
128            Self::Data => "&[u8]".into(),
129            Self::ListText => "&[String]".into(),
130            Self::ListData => "&[Vec<u8>]".into(),
131            Self::ListPrimitive(inner) => format!("&[{}]", inner.rust_owned_type()),
132            Self::ListStruct(inner) => format!("&[{inner}]"),
133            _ => self.rust_owned_type(),
134        }
135    }
136
137    /// Whether function arguments of this type should be passed by reference in dispatch.
138    pub fn is_by_ref(&self) -> bool {
139        matches!(
140            self,
141            Self::Text
142                | Self::Data
143                | Self::ListText
144                | Self::ListData
145                | Self::ListPrimitive(_)
146                | Self::ListStruct(_)
147                | Self::Enum(_)
148        )
149    }
150
151    /// Whether this is a list type (for nested List(List(...)) support).
152    pub fn is_list(&self) -> bool {
153        matches!(
154            self,
155            Self::ListText | Self::ListData | Self::ListPrimitive(_) | Self::ListStruct(_)
156        )
157    }
158
159    /// Whether this is a numeric/value type (Bool included — Copy semantics).
160    pub fn is_numeric(&self) -> bool {
161        matches!(
162            self,
163            Self::Bool
164                | Self::UInt8
165                | Self::UInt16
166                | Self::UInt32
167                | Self::UInt64
168                | Self::Int8
169                | Self::Int16
170                | Self::Int32
171                | Self::Int64
172                | Self::Float32
173                | Self::Float64
174        )
175    }
176}
177
178// ─────────────────────────────────────────────────────────────────────────────
179// Name conversion — delegated to hyprstream_rpc_build::util for sharing
180// ─────────────────────────────────────────────────────────────────────────────
181
182pub use hyprstream_rpc_build::util::{to_pascal_case, to_snake_case};
183
184/// Convert PascalCase to snake_case matching Cap'n Proto's Rust codegen naming.
185///
186/// Unlike `to_snake_case` (which groups consecutive uppercase letters like `DNS` → `dns`),
187/// capnp inserts `_` before every uppercase letter: `DNSConfig` → `d_n_s_config`.
188pub fn to_capnp_module_name(s: &str) -> String {
189    let mut result = String::with_capacity(s.len() + 8);
190    for (i, c) in s.chars().enumerate() {
191        if c.is_ascii_uppercase() && i > 0 {
192            result.push('_');
193        }
194        result.push(c.to_ascii_lowercase());
195    }
196    result
197}
198
199/// Convert a Rust type string into a TokenStream for use in quote!.
200pub fn rust_type_tokens(type_str: &str) -> TokenStream {
201    let ts: TokenStream = type_str.parse().unwrap_or_else(|_| quote! { Vec<u8> });
202    ts
203}
204
205// ─────────────────────────────────────────────────────────────────────────────
206// Tests
207// ─────────────────────────────────────────────────────────────────────────────
208
209#[cfg(test)]
210#[allow(clippy::expect_used)]
211mod tests {
212    use super::*;
213
214    fn test_structs() -> Vec<StructDef> {
215        vec![StructDef {
216            name: "ModelInfo".into(),
217            fields: vec![
218                FieldDef {
219                    name: "name".into(),
220                    type_name: "Text".into(),
221                    description: String::new(),
222                    fixed_size: None,
223                    max_len: None,
224                    optional: false,
225                    slot_offset: 0,
226                    section: FieldSection::Pointer,
227                    discriminant_value: 0xFFFF,
228                    serde_rename: None,
229                    domain_type: None,
230                },
231                FieldDef {
232                    name: "size".into(),
233                    type_name: "UInt64".into(),
234                    description: String::new(),
235                    fixed_size: None,
236                    max_len: None,
237                    optional: false,
238                    slot_offset: 0,
239                    section: FieldSection::Data,
240                    discriminant_value: 0xFFFF,
241                    serde_rename: None,
242                    domain_type: None,
243                },
244            ],
245            has_union: false,
246            domain_type: None,
247            origin_file: None,
248            data_words: 0,
249            pointer_words: 0,
250            discriminant_count: 0,
251            discriminant_offset: 0,
252            union_arms: vec![],
253        }]
254    }
255
256    fn test_enums() -> Vec<EnumDef> {
257        vec![EnumDef {
258            name: "Status".into(),
259            variants: vec![("active".into(), 0), ("inactive".into(), 1)],
260            origin_file: None,
261        }]
262    }
263
264    #[test]
265    fn classify_primitives() {
266        assert_eq!(CapnpType::classify_primitive("Void"), CapnpType::Void);
267        assert_eq!(CapnpType::classify_primitive("Bool"), CapnpType::Bool);
268        assert_eq!(CapnpType::classify_primitive("Text"), CapnpType::Text);
269        assert_eq!(CapnpType::classify_primitive("Data"), CapnpType::Data);
270        assert_eq!(CapnpType::classify_primitive("UInt32"), CapnpType::UInt32);
271        assert_eq!(CapnpType::classify_primitive("Float64"), CapnpType::Float64);
272    }
273
274    #[test]
275    fn classify_lists() {
276        assert_eq!(
277            CapnpType::classify_primitive("List(Text)"),
278            CapnpType::ListText
279        );
280        assert_eq!(
281            CapnpType::classify_primitive("List(Data)"),
282            CapnpType::ListData
283        );
284        assert_eq!(
285            CapnpType::classify_primitive("List(ModelInfo)"),
286            CapnpType::ListStruct("ModelInfo".into())
287        );
288    }
289
290    #[test]
291    fn classify_list_primitives() {
292        assert_eq!(
293            CapnpType::classify_primitive("List(Int64)"),
294            CapnpType::ListPrimitive(Box::new(CapnpType::Int64))
295        );
296        assert_eq!(
297            CapnpType::classify_primitive("List(UInt8)"),
298            CapnpType::ListPrimitive(Box::new(CapnpType::UInt8))
299        );
300        assert_eq!(
301            CapnpType::classify_primitive("List(Bool)"),
302            CapnpType::ListPrimitive(Box::new(CapnpType::Bool))
303        );
304        assert_eq!(
305            CapnpType::classify_primitive("List(Float64)"),
306            CapnpType::ListPrimitive(Box::new(CapnpType::Float64))
307        );
308        // Verify owned types
309        assert_eq!(
310            CapnpType::ListPrimitive(Box::new(CapnpType::Int64)).rust_owned_type(),
311            "Vec<i64>"
312        );
313        assert_eq!(
314            CapnpType::ListPrimitive(Box::new(CapnpType::UInt8)).rust_owned_type(),
315            "Vec<u8>"
316        );
317        // Verify param types
318        assert_eq!(
319            CapnpType::ListPrimitive(Box::new(CapnpType::Int64)).rust_param_type(),
320            "&[i64]"
321        );
322        // Verify is_by_ref
323        assert!(CapnpType::ListPrimitive(Box::new(CapnpType::Int64)).is_by_ref());
324    }
325
326    #[test]
327    fn classify_with_schema_context() {
328        let structs = test_structs();
329        let enums = test_enums();
330        assert_eq!(
331            CapnpType::classify("ModelInfo", &structs, &enums),
332            CapnpType::Struct("ModelInfo".into())
333        );
334        assert_eq!(
335            CapnpType::classify("Status", &structs, &enums),
336            CapnpType::Enum("Status".into())
337        );
338        assert_eq!(
339            CapnpType::classify("Unknown", &structs, &enums),
340            CapnpType::Unknown("Unknown".into())
341        );
342    }
343
344    #[test]
345    fn rust_owned_types() {
346        assert_eq!(CapnpType::Text.rust_owned_type(), "String");
347        assert_eq!(CapnpType::UInt32.rust_owned_type(), "u32");
348        assert_eq!(CapnpType::ListText.rust_owned_type(), "Vec<String>");
349        assert_eq!(
350            CapnpType::ListStruct("ModelInfo".into()).rust_owned_type(),
351            "Vec<ModelInfo>"
352        );
353        assert_eq!(
354            CapnpType::Struct("ModelInfo".into()).rust_owned_type(),
355            "ModelInfo"
356        );
357        assert_eq!(CapnpType::Enum("Status".into()).rust_owned_type(), "Status");
358    }
359
360    #[test]
361    fn rust_param_types() {
362        assert_eq!(CapnpType::Text.rust_param_type(), "&str");
363        assert_eq!(CapnpType::Data.rust_param_type(), "&[u8]");
364        assert_eq!(CapnpType::UInt32.rust_param_type(), "u32");
365        assert_eq!(CapnpType::ListText.rust_param_type(), "&[String]");
366        assert_eq!(CapnpType::Enum("Status".into()).rust_param_type(), "&str");
367    }
368
369    #[test]
370    fn is_by_ref() {
371        assert!(CapnpType::Text.is_by_ref());
372        assert!(CapnpType::Data.is_by_ref());
373        assert!(CapnpType::ListText.is_by_ref());
374        assert!(!CapnpType::Bool.is_by_ref());
375        assert!(!CapnpType::UInt32.is_by_ref());
376        assert!(!CapnpType::Void.is_by_ref());
377    }
378
379    #[test]
380    fn to_pascal_case_works() {
381        assert_eq!(to_pascal_case("hello_world"), "HelloWorld");
382        assert_eq!(to_pascal_case("helloWorld"), "HelloWorld");
383        assert_eq!(to_pascal_case("policy"), "Policy");
384    }
385
386    #[test]
387    fn to_snake_case_works() {
388        assert_eq!(to_snake_case("HelloWorld"), "hello_world");
389        assert_eq!(to_snake_case("helloWorld"), "hello_world");
390        assert_eq!(to_snake_case("HTTPRequest"), "http_request");
391    }
392}