Skip to main content

hyprstream_rpc_derive/
resolve.rs

1//! Resolution layer between parsing and codegen.
2//!
3//! `ResolvedSchema` is built once from a `ParsedSchema` and provides O(1) lookups
4//! for structs, enums, and response variants, plus cached name conversions and
5//! precomputed type classifications.
6
7use std::collections::{HashMap, HashSet};
8
9use proc_macro2::Ident;
10use quote::format_ident;
11
12use crate::schema::types::*;
13use crate::util::{to_pascal_case, to_snake_case, CapnpType};
14
15/// Cached name conversions for a single identifier string.
16#[derive(Debug, Clone)]
17#[allow(dead_code)]
18pub struct ResolvedName {
19    pub raw: String,
20    pub snake: String,
21    pub pascal: String,
22    pub snake_ident: Ident,
23    pub pascal_ident: Ident,
24}
25
26/// Cached type classification for a single type_name string.
27#[derive(Debug, Clone)]
28pub struct ResolvedType {
29    pub capnp_type: CapnpType,
30    pub rust_owned: String,
31    pub rust_param: String,
32    pub is_by_ref: bool,
33    pub is_numeric: bool,
34}
35
36/// Indexed, precomputed view of a `ParsedSchema`.
37///
38/// Built once in `generate_service()`, consumed by all codegen modules.
39pub struct ResolvedSchema<'a> {
40    pub raw: &'a ParsedSchema,
41    pub struct_index: HashMap<String, usize>,
42    pub enum_index: HashMap<String, usize>,
43    #[allow(dead_code)]
44    pub response_index: HashMap<String, usize>,
45    names: HashMap<String, ResolvedName>,
46    types: HashMap<String, ResolvedType>,
47}
48
49impl<'a> ResolvedSchema<'a> {
50    /// Build a resolved schema from a parsed schema.
51    pub fn from(schema: &'a ParsedSchema) -> Self {
52        // Build indexes
53        let struct_index: HashMap<String, usize> = schema
54            .structs
55            .iter()
56            .enumerate()
57            .map(|(i, s)| (s.name.clone(), i))
58            .collect();
59
60        let enum_index: HashMap<String, usize> = schema
61            .enums
62            .iter()
63            .enumerate()
64            .map(|(i, e)| (e.name.clone(), i))
65            .collect();
66
67        let response_index: HashMap<String, usize> = schema
68            .response_variants
69            .iter()
70            .enumerate()
71            .map(|(i, v)| (v.name.clone(), i))
72            .collect();
73
74        // Collect all unique name strings that need conversion
75        let mut name_strings = HashSet::new();
76        // Collect all unique type_name strings that need classification
77        let mut type_strings = HashSet::new();
78
79        // Walk request/response variants
80        for v in &schema.request_variants {
81            name_strings.insert(v.name.clone());
82            type_strings.insert(v.type_name.clone());
83        }
84        for v in &schema.response_variants {
85            name_strings.insert(v.name.clone());
86            type_strings.insert(v.type_name.clone());
87        }
88
89        // Walk structs and their fields
90        for s in &schema.structs {
91            name_strings.insert(s.name.clone());
92            // Struct names are also valid type references (e.g., when used in
93            // List(StructName) or as field types in other structs)
94            type_strings.insert(s.name.clone());
95            for f in &s.fields {
96                name_strings.insert(f.name.clone());
97                type_strings.insert(f.type_name.clone());
98            }
99            // Walk union arms: arm names become Rust enum variant idents, and arm /
100            // group-leaf type names need classification so codegen can resolve them.
101            for arm in &s.union_arms {
102                name_strings.insert(arm.name.clone());
103                match &arm.payload {
104                    ArmPayload::Void => {}
105                    ArmPayload::Type(name) => {
106                        type_strings.insert(name.clone());
107                    }
108                    ArmPayload::Group(leaves) => {
109                        for leaf in leaves {
110                            name_strings.insert(leaf.name.clone());
111                            type_strings.insert(leaf.type_name.clone());
112                        }
113                    }
114                }
115            }
116        }
117
118        // Walk enums
119        for e in &schema.enums {
120            name_strings.insert(e.name.clone());
121            // Enum names are also valid type references
122            type_strings.insert(e.name.clone());
123            for (vname, _) in &e.variants {
124                name_strings.insert(vname.clone());
125            }
126        }
127
128        // Walk scoped clients recursively
129        fn collect_from_scoped(
130            sc: &ScopedClient,
131            names: &mut HashSet<String>,
132            types: &mut HashSet<String>,
133        ) {
134            names.insert(sc.factory_name.clone());
135            names.insert(sc.client_name.clone());
136            for f in &sc.scope_fields {
137                names.insert(f.name.clone());
138                types.insert(f.type_name.clone());
139            }
140            for v in &sc.inner_request_variants {
141                names.insert(v.name.clone());
142                types.insert(v.type_name.clone());
143            }
144            for v in &sc.inner_response_variants {
145                names.insert(v.name.clone());
146                types.insert(v.type_name.clone());
147            }
148            for nested in &sc.nested_clients {
149                collect_from_scoped(nested, names, types);
150            }
151        }
152        for sc in &schema.scoped_clients {
153            collect_from_scoped(sc, &mut name_strings, &mut type_strings);
154        }
155
156        // Pre-resolve all names
157        let names: HashMap<String, ResolvedName> = name_strings
158            .into_iter()
159            .map(|raw| {
160                let snake = to_snake_case(&raw);
161                let pascal = to_pascal_case(&raw);
162                let snake_ident = format_ident!("{}", snake);
163                let pascal_ident = format_ident!("{}", pascal);
164                (
165                    raw.clone(),
166                    ResolvedName {
167                        raw,
168                        snake,
169                        pascal,
170                        snake_ident,
171                        pascal_ident,
172                    },
173                )
174            })
175            .collect();
176
177        // Pre-resolve all types using indexed lookups
178        let types: HashMap<String, ResolvedType> = type_strings
179            .into_iter()
180            .map(|type_name| {
181                let ct = classify_with_indexes(&type_name, &struct_index, &enum_index);
182                let rust_owned = ct.rust_owned_type();
183                let rust_param = ct.rust_param_type();
184                let is_by_ref = ct.is_by_ref();
185                let is_numeric = ct.is_numeric();
186                (
187                    type_name,
188                    ResolvedType {
189                        capnp_type: ct,
190                        rust_owned,
191                        rust_param,
192                        is_by_ref,
193                        is_numeric,
194                    },
195                )
196            })
197            .collect();
198
199        Self {
200            raw: schema,
201            struct_index,
202            enum_index,
203            response_index,
204            names,
205            types,
206        }
207    }
208
209    /// O(1) struct lookup by name.
210    pub fn find_struct(&self, name: &str) -> Option<&'a StructDef> {
211        self.struct_index.get(name).map(|&i| &self.raw.structs[i])
212    }
213
214    /// O(1) enum lookup by name.
215    pub fn find_enum(&self, name: &str) -> Option<&'a EnumDef> {
216        self.enum_index.get(name).map(|&i| &self.raw.enums[i])
217    }
218
219    /// O(1) response variant lookup by name.
220    #[allow(dead_code)]
221    pub fn find_response(&self, name: &str) -> Option<&'a UnionVariant> {
222        self.response_index
223            .get(name)
224            .map(|&i| &self.raw.response_variants[i])
225    }
226
227    /// O(1) cached name lookup. Panics if name was not seen during schema walk.
228    pub fn name(&self, raw: &str) -> &ResolvedName {
229        self.names.get(raw).unwrap_or_else(|| {
230            panic!(
231                "ResolvedSchema: name '{}' not collected during resolution",
232                raw
233            )
234        })
235    }
236
237    /// O(1) cached type lookup. Panics if type was not seen during schema walk.
238    pub fn resolve_type(&self, type_name: &str) -> &ResolvedType {
239        self.types.get(type_name).unwrap_or_else(|| {
240            panic!(
241                "ResolvedSchema: type '{}' not collected during resolution",
242                type_name
243            )
244        })
245    }
246
247    /// O(1) check if a name refers to a known struct.
248    pub fn is_struct(&self, name: &str) -> bool {
249        self.struct_index.contains_key(name)
250    }
251
252    /// O(1) check if a name refers to a known enum.
253    #[allow(dead_code)]
254    pub fn is_enum(&self, name: &str) -> bool {
255        self.enum_index.contains_key(name)
256    }
257}
258
259/// Classify a Cap'n Proto type name using HashMap indexes instead of linear scans.
260///
261/// This duplicates the classification logic from `CapnpType::classify()` but uses
262/// O(1) HashMap lookups instead of O(n) `iter().any()`. The public `CapnpType::classify()`
263/// API in `util.rs` is unchanged (used by parser and tests).
264fn classify_with_indexes(
265    type_name: &str,
266    struct_index: &HashMap<String, usize>,
267    enum_index: &HashMap<String, usize>,
268) -> CapnpType {
269    match type_name {
270        "Void" => CapnpType::Void,
271        "Bool" => CapnpType::Bool,
272        "Text" => CapnpType::Text,
273        "Data" => CapnpType::Data,
274        "UInt8" => CapnpType::UInt8,
275        "UInt16" => CapnpType::UInt16,
276        "UInt32" => CapnpType::UInt32,
277        "UInt64" => CapnpType::UInt64,
278        "Int8" => CapnpType::Int8,
279        "Int16" => CapnpType::Int16,
280        "Int32" => CapnpType::Int32,
281        "Int64" => CapnpType::Int64,
282        "Float32" => CapnpType::Float32,
283        "Float64" => CapnpType::Float64,
284        t if t.starts_with("List(") && t.ends_with(')') => {
285            let inner = &t[5..t.len() - 1];
286            match inner {
287                "Text" => CapnpType::ListText,
288                "Data" => CapnpType::ListData,
289                _ => {
290                    let inner_type = classify_with_indexes(inner, struct_index, enum_index);
291                    if inner_type.is_numeric() || inner_type.is_list() {
292                        CapnpType::ListPrimitive(Box::new(inner_type))
293                    } else {
294                        CapnpType::ListStruct(inner.to_owned())
295                    }
296                }
297            }
298        }
299        t => {
300            if enum_index.contains_key(t) {
301                CapnpType::Enum(t.to_owned())
302            } else if struct_index.contains_key(t) {
303                CapnpType::Struct(t.to_owned())
304            } else {
305                CapnpType::Unknown(t.to_owned())
306            }
307        }
308    }
309}