Skip to main content

alef_codegen/generators/
structs.rs

1use crate::builder::StructBuilder;
2use crate::generators::RustBindingConfig;
3use crate::type_mapper::TypeMapper;
4use alef_core::ir::{CoreWrapper, TypeDef, TypeRef};
5
6/// Check if a type's fields can all be safely defaulted.
7/// Primitives, strings, collections, Options, and Duration all have Default impls.
8/// Named types (custom structs) only have Default if explicitly marked with `has_default=true`.
9/// If any field is a Named type without `has_default`, returning true would generate
10/// code that calls `Default::default()` on a type that doesn't implement it.
11pub fn can_generate_default_impl(typ: &TypeDef, known_default_types: &std::collections::HashSet<&str>) -> bool {
12    for field in &typ.fields {
13        if field.cfg.is_some() {
14            continue; // Skip cfg-gated fields
15        }
16        if !field_type_has_default(&field.ty, known_default_types) {
17            return false;
18        }
19    }
20    true
21}
22
23/// Check if a specific TypeRef can be safely defaulted.
24fn field_type_has_default(ty: &TypeRef, known_default_types: &std::collections::HashSet<&str>) -> bool {
25    match ty {
26        TypeRef::Primitive(_)
27        | TypeRef::String
28        | TypeRef::Char
29        | TypeRef::Bytes
30        | TypeRef::Path
31        | TypeRef::Unit
32        | TypeRef::Duration
33        | TypeRef::Json => true,
34        // Optional<T> defaults to None regardless of T
35        TypeRef::Optional(inner) => field_type_has_default(inner, known_default_types),
36        // Vec<T> defaults to empty vec regardless of T
37        TypeRef::Vec(inner) => field_type_has_default(inner, known_default_types),
38        // Map<K, V> defaults to empty map regardless of K/V
39        TypeRef::Map(k, v) => {
40            field_type_has_default(k, known_default_types) && field_type_has_default(v, known_default_types)
41        }
42        // Named types only have Default if marked with has_default=true
43        TypeRef::Named(name) => known_default_types.contains(name.as_str()),
44    }
45}
46
47/// Check if any two field names are similar enough to trigger clippy::similar_names.
48/// This detects patterns like "sub_symbol" and "sup_symbol" (differ by 1-2 chars).
49fn has_similar_names(names: &[&String]) -> bool {
50    for (i, &name1) in names.iter().enumerate() {
51        for &name2 in &names[i + 1..] {
52            // Simple heuristic: if names differ by <= 2 characters and have same length, flag it
53            if name1.len() == name2.len() && diff_count(name1, name2) <= 2 {
54                return true;
55            }
56        }
57    }
58    false
59}
60
61/// Count how many characters differ between two strings of equal length.
62fn diff_count(s1: &str, s2: &str) -> usize {
63    s1.chars().zip(s2.chars()).filter(|(c1, c2)| c1 != c2).count()
64}
65
66/// Check if a TypeRef references an opaque type, including through Optional and Vec wrappers.
67/// Opaque types use Arc<T> which doesn't implement Serialize/Deserialize, so any struct with
68/// such a field cannot derive those traits.
69pub fn field_references_opaque_type(ty: &TypeRef, opaque_names: &[String]) -> bool {
70    match ty {
71        TypeRef::Named(name) => opaque_names.contains(name),
72        TypeRef::Optional(inner) | TypeRef::Vec(inner) => field_references_opaque_type(inner, opaque_names),
73        TypeRef::Map(k, v) => {
74            field_references_opaque_type(k, opaque_names) || field_references_opaque_type(v, opaque_names)
75        }
76        _ => false,
77    }
78}
79
80/// Generate a struct definition using the builder, with a per-field attribute callback.
81///
82/// `extra_field_attrs` is called for each field and returns additional `#[...]` attributes to
83/// prepend (beyond `cfg.field_attrs`). Pass `|_| vec![]` to use the default behaviour.
84pub fn gen_struct_with_per_field_attrs(
85    typ: &TypeDef,
86    mapper: &dyn TypeMapper,
87    cfg: &RustBindingConfig,
88    extra_field_attrs: impl Fn(&alef_core::ir::FieldDef) -> Vec<String>,
89) -> String {
90    let mut sb = StructBuilder::new(&typ.name);
91    for attr in cfg.struct_attrs {
92        sb.add_attr(attr);
93    }
94
95    // Check if struct has similar field names (e.g., sub_symbol and sup_symbol)
96    let field_names: Vec<_> = typ.fields.iter().filter(|f| f.cfg.is_none()).map(|f| &f.name).collect();
97    if has_similar_names(&field_names) {
98        sb.add_attr("allow(clippy::similar_names)");
99    }
100
101    for d in cfg.struct_derives {
102        sb.add_derive(d);
103    }
104    // Track which fields are opaque so we can conditionally skip derives and add #[serde(skip)].
105    let opaque_fields: Vec<&str> = typ
106        .fields
107        .iter()
108        .filter(|f| f.cfg.is_none() && field_references_opaque_type(&f.ty, cfg.opaque_type_names))
109        .map(|f| f.name.as_str())
110        .collect();
111    // Always derive Default/Serialize/Deserialize. Opaque fields get #[serde(skip)]
112    // so they use Default::default() during deserialization. This is needed for the
113    // serde recovery path where binding types round-trip through JSON.
114    sb.add_derive("Default");
115    sb.add_derive("serde::Serialize");
116    sb.add_derive("serde::Deserialize");
117    let has_serde = true;
118    for field in &typ.fields {
119        if field.cfg.is_some() {
120            continue;
121        }
122        let force_optional = cfg.option_duration_on_defaults
123            && typ.has_default
124            && !field.optional
125            && matches!(field.ty, TypeRef::Duration);
126        let ty = if (field.optional || force_optional) && !matches!(field.ty, TypeRef::Optional(_)) {
127            mapper.optional(&mapper.map_type(&field.ty))
128        } else {
129            // field.ty is already Optional(T) — mapped type is already Option<T>, don't double-wrap
130            mapper.map_type(&field.ty)
131        };
132        let mut attrs: Vec<String> = cfg.field_attrs.iter().map(|a| a.to_string()).collect();
133        attrs.extend(extra_field_attrs(field));
134        // Add #[serde(skip)] for opaque fields or sanitized fields when the struct derives serde.
135        // Cow-backed strings are lossless String bindings, so they must remain serializable.
136        let skip_sanitized_field = field.sanitized && field.core_wrapper != CoreWrapper::Cow;
137        if has_serde && (opaque_fields.contains(&field.name.as_str()) || skip_sanitized_field) {
138            attrs.push("serde(skip)".to_string());
139        }
140        sb.add_field_with_doc(&field.name, &ty, attrs, &field.doc);
141    }
142    sb.build()
143}
144
145/// Generate a struct definition using the builder, with per-field attribute and name override callbacks.
146///
147/// This is the most flexible variant.  Use it when the target language may need to escape
148/// reserved keywords in field names (e.g. Python's `class` → `class_`).
149///
150/// * `extra_field_attrs` — called per field, returns additional `#[…]` attribute strings to
151///   append **after** `cfg.field_attrs`.  Return an empty vec for the default behaviour.
152/// * `field_name_override` — called per field, returns `Some(escaped_name)` when the Rust
153///   binding struct field name should differ from `field.name` (e.g. for keyword escaping),
154///   or `None` to keep the original name.
155///
156/// When a field name is overridden the caller is responsible for adding the appropriate
157/// language attribute (e.g. `pyo3(get, name = "original")`) via `extra_field_attrs`.
158/// `cfg.field_attrs` is **still** applied for non-renamed fields; for renamed fields the
159/// caller should replace the default field attrs entirely by returning them from
160/// `extra_field_attrs` and passing a modified `cfg` with empty `field_attrs`.
161pub fn gen_struct_with_rename(
162    typ: &TypeDef,
163    mapper: &dyn TypeMapper,
164    cfg: &RustBindingConfig,
165    extra_field_attrs: impl Fn(&alef_core::ir::FieldDef) -> Vec<String>,
166    field_name_override: impl Fn(&alef_core::ir::FieldDef) -> Option<String>,
167) -> String {
168    let mut sb = StructBuilder::new(&typ.name);
169    for attr in cfg.struct_attrs {
170        sb.add_attr(attr);
171    }
172
173    let field_names: Vec<_> = typ.fields.iter().filter(|f| f.cfg.is_none()).map(|f| &f.name).collect();
174    if has_similar_names(&field_names) {
175        sb.add_attr("allow(clippy::similar_names)");
176    }
177
178    for d in cfg.struct_derives {
179        sb.add_derive(d);
180    }
181    let opaque_fields: Vec<&str> = typ
182        .fields
183        .iter()
184        .filter(|f| f.cfg.is_none() && field_references_opaque_type(&f.ty, cfg.opaque_type_names))
185        .map(|f| f.name.as_str())
186        .collect();
187    sb.add_derive("Default");
188    sb.add_derive("serde::Serialize");
189    sb.add_derive("serde::Deserialize");
190    let has_serde = true;
191    for field in &typ.fields {
192        if field.cfg.is_some() {
193            continue;
194        }
195        let force_optional = cfg.option_duration_on_defaults
196            && typ.has_default
197            && !field.optional
198            && matches!(field.ty, TypeRef::Duration);
199        let ty = if (field.optional || force_optional) && !matches!(field.ty, TypeRef::Optional(_)) {
200            mapper.optional(&mapper.map_type(&field.ty))
201        } else {
202            mapper.map_type(&field.ty)
203        };
204        let name_override = field_name_override(field);
205        let extra_attrs = extra_field_attrs(field);
206        // When the field name is overridden (keyword-escaped), skip cfg.field_attrs so the
207        // caller's extra_field_attrs callback can supply the full replacement attr set
208        // (e.g. `pyo3(get, name = "class")` instead of the default `pyo3(get)`).
209        let mut attrs: Vec<String> = if name_override.is_some() && !extra_attrs.is_empty() {
210            extra_attrs
211        } else {
212            let mut a: Vec<String> = cfg.field_attrs.iter().map(|a| a.to_string()).collect();
213            a.extend(extra_attrs);
214            a
215        };
216        // Add #[serde(skip)] for opaque fields or sanitized fields — same rationale as in
217        // gen_struct_with_per_field_attrs: sanitized fields have placeholder String types that
218        // cause JSON round-trip failures with "unknown variant ''" errors. Cow-backed strings
219        // are lossless String bindings, so they must remain serializable/deserializable.
220        let skip_sanitized_field = field.sanitized && field.core_wrapper != CoreWrapper::Cow;
221        if has_serde && (opaque_fields.contains(&field.name.as_str()) || skip_sanitized_field) {
222            attrs.push("serde(skip)".to_string());
223        }
224        let emit_name = name_override.unwrap_or_else(|| field.name.clone());
225        sb.add_field_with_doc(&emit_name, &ty, attrs, &field.doc);
226    }
227    sb.build()
228}
229
230/// Generate a struct definition using the builder.
231pub fn gen_struct(typ: &TypeDef, mapper: &dyn TypeMapper, cfg: &RustBindingConfig) -> String {
232    let mut sb = StructBuilder::new(&typ.name);
233    for attr in cfg.struct_attrs {
234        sb.add_attr(attr);
235    }
236
237    // Check if struct has similar field names (e.g., sub_symbol and sup_symbol)
238    let field_names: Vec<_> = typ.fields.iter().filter(|f| f.cfg.is_none()).map(|f| &f.name).collect();
239    if has_similar_names(&field_names) {
240        sb.add_attr("allow(clippy::similar_names)");
241    }
242
243    for d in cfg.struct_derives {
244        sb.add_derive(d);
245    }
246    let _opaque_fields: Vec<&str> = typ
247        .fields
248        .iter()
249        .filter(|f| f.cfg.is_none() && field_references_opaque_type(&f.ty, cfg.opaque_type_names))
250        .map(|f| f.name.as_str())
251        .collect();
252    sb.add_derive("Default");
253    sb.add_derive("serde::Serialize");
254    sb.add_derive("serde::Deserialize");
255    let _has_serde = true;
256    for field in &typ.fields {
257        // Skip cfg-gated fields — they depend on features that may not be enabled
258        // for this binding crate. Including them would require the binding struct to
259        // handle conditional compilation which struct literal initializers can't express.
260        if field.cfg.is_some() {
261            continue;
262        }
263        // When option_duration_on_defaults is set, wrap non-optional Duration fields in
264        // Option<u64> for has_default types so the binding constructor can accept None
265        // and the From conversion falls back to the core type's Default.
266        let force_optional = cfg.option_duration_on_defaults
267            && typ.has_default
268            && !field.optional
269            && matches!(field.ty, TypeRef::Duration);
270        let ty = if (field.optional || force_optional) && !matches!(field.ty, TypeRef::Optional(_)) {
271            mapper.optional(&mapper.map_type(&field.ty))
272        } else {
273            // field.ty is already Optional(T) — mapped type is already Option<T>, don't double-wrap
274            mapper.map_type(&field.ty)
275        };
276        let attrs: Vec<String> = cfg.field_attrs.iter().map(|a| a.to_string()).collect();
277        // Only add #[serde(default)] when serde derives are present on the struct
278        // (opaque_fields empty = serde derives added, opaque field needs serde(default))
279        // This can't happen: if opaque_fields is empty, no field matches this check.
280        // If opaque_fields is non-empty, serde derives were suppressed → skip serde attr.
281        // So this block is effectively dead — remove it to prevent stale serde attrs.
282        sb.add_field_with_doc(&field.name, &ty, attrs, &field.doc);
283    }
284    sb.build()
285}
286
287/// Generate a `Default` impl for a non-opaque binding struct with `has_default`.
288/// All fields use their type's Default::default().
289/// Optional fields use None instead of Default::default().
290/// This enables the struct to be used with `unwrap_or_default()` in config constructors.
291///
292/// WARNING: This assumes all field types implement Default. If a Named field type
293/// doesn't implement Default, this impl will fail to compile. Callers should verify
294/// that the struct's fields can be safely defaulted before calling this function.
295pub fn gen_struct_default_impl(typ: &TypeDef, name_prefix: &str) -> String {
296    let full_name = format!("{}{}", name_prefix, typ.name);
297    let fields: Vec<_> = typ
298        .fields
299        .iter()
300        .filter_map(|field| {
301            if field.cfg.is_some() {
302                return None;
303            }
304            let default_val = match &field.ty {
305                TypeRef::Optional(_) => "None".to_string(),
306                _ => "Default::default()".to_string(),
307            };
308            Some(minijinja::context! {
309                name => field.name.clone(),
310                default_val => default_val
311            })
312        })
313        .collect();
314
315    crate::template_env::render(
316        "structs/default_impl.jinja",
317        minijinja::context! {
318            full_name => full_name,
319            fields => fields
320        },
321    )
322}
323
324/// Check if any method on a type takes `&mut self`, meaning the opaque wrapper
325/// must use `Arc<Mutex<T>>` instead of `Arc<T>` to allow interior mutability.
326pub fn type_needs_mutex(typ: &TypeDef) -> bool {
327    typ.methods
328        .iter()
329        .any(|m| m.receiver == Some(alef_core::ir::ReceiverKind::RefMut))
330}
331
332/// Check if a type wrapping `Arc<Mutex<T>>` should use `tokio::sync::Mutex` instead
333/// of `std::sync::Mutex` because every `&mut self` method is `async`.
334///
335/// `std::sync::MutexGuard` is `!Send`, so holding a guard across `.await` makes the
336/// surrounding future `!Send`, which fails to compile in PyO3 / NAPI-RS bindings that
337/// require `Send` futures. `tokio::sync::MutexGuard` IS `Send`, so swapping the lock
338/// type fixes the entire async-locking story for these structs.
339///
340/// The condition is tight: every method that takes `&mut self` MUST be async. If even
341/// one sync method takes `&mut self`, switching to `tokio::sync::Mutex` would break
342/// it (since `tokio::sync::Mutex::lock()` returns a `Future` and cannot be awaited
343/// from sync context). In that mixed case we keep `std::sync::Mutex`.
344pub fn type_needs_tokio_mutex(typ: &TypeDef) -> bool {
345    use alef_core::ir::ReceiverKind;
346    if !type_needs_mutex(typ) {
347        return false;
348    }
349    let refmut_methods = typ.methods.iter().filter(|m| m.receiver == Some(ReceiverKind::RefMut));
350    let mut any = false;
351    for m in refmut_methods {
352        any = true;
353        if !m.is_async {
354            return false;
355        }
356    }
357    any
358}
359
360/// Generate an opaque wrapper struct with `inner: Arc<core::Type>`.
361/// For trait types, uses `Arc<dyn Type + Send + Sync>`.
362/// For types with `&mut self` methods, uses `Arc<Mutex<core::Type>>`.
363///
364/// Special case: if ALL methods on this type are sanitized, the type was created by the
365/// impl-block fallback for a generic core type (e.g. `GraphQLExecutor<Q,M,S>`). Sanitized
366/// methods never access `self.inner` (they emit `gen_unimplemented_body`), so we omit the
367/// `inner` field entirely. This avoids generating `Arc<CoreType>` with missing generic
368/// parameters, which would fail to compile.
369pub fn gen_opaque_struct(typ: &TypeDef, cfg: &RustBindingConfig) -> String {
370    let needs_mutex = type_needs_mutex(typ);
371    // Omit the inner field only when the rust_path contains generic type parameters
372    // (angle brackets), which means the concrete types are unknown at codegen time and
373    // `Arc<CoreType<_, _, _>>` would fail to compile. This typically occurs for types
374    // created from a generic impl block where all methods are sanitized.
375    // We do NOT omit inner solely because all_methods_sanitized is true: even when no
376    // methods delegate to self.inner, the inner field may be required by From impls
377    // generated for non-opaque structs that have this type as a field.
378    let core_path = typ.rust_path.replace('-', "_");
379    let has_unresolvable_generics = core_path.contains('<');
380    let all_methods_sanitized = !typ.methods.is_empty() && typ.methods.iter().all(|m| m.sanitized);
381    let omit_inner = all_methods_sanitized && has_unresolvable_generics;
382
383    let struct_attrs: Vec<_> = cfg.struct_attrs.iter().map(|s| s.to_string()).collect();
384    let has_derives = !cfg.struct_derives.is_empty();
385    let inner_type = if typ.is_trait {
386        format!("Arc<dyn {core_path} + Send + Sync>")
387    } else if needs_mutex {
388        format!("Arc<std::sync::Mutex<{core_path}>>")
389    } else {
390        format!("Arc<{core_path}>")
391    };
392
393    crate::template_env::render(
394        "structs/opaque_struct.jinja",
395        minijinja::context! {
396            struct_name => typ.name.clone(),
397            has_derives => has_derives,
398            struct_attrs => struct_attrs,
399            omit_inner => omit_inner,
400            inner_type => inner_type,
401        },
402    )
403}
404
405/// Generate an opaque wrapper struct with `inner: Arc<core::Type>` and a name prefix.
406/// For types with `&mut self` methods, uses `Arc<Mutex<core::Type>>`.
407///
408/// Special case: if ALL methods on this type are sanitized, omit the `inner` field.
409/// See `gen_opaque_struct` for the rationale.
410pub fn gen_opaque_struct_prefixed(typ: &TypeDef, cfg: &RustBindingConfig, prefix: &str) -> String {
411    let needs_mutex = type_needs_mutex(typ);
412    let core_path = typ.rust_path.replace('-', "_");
413    let has_unresolvable_generics = core_path.contains('<');
414    let all_methods_sanitized = !typ.methods.is_empty() && typ.methods.iter().all(|m| m.sanitized);
415    let omit_inner = all_methods_sanitized && has_unresolvable_generics;
416
417    let struct_attrs: Vec<_> = cfg.struct_attrs.iter().map(|s| s.to_string()).collect();
418    let has_derives = !cfg.struct_derives.is_empty();
419    let struct_name = format!("{prefix}{}", typ.name);
420    let inner_type = if typ.is_trait {
421        format!("Arc<dyn {core_path} + Send + Sync>")
422    } else if needs_mutex {
423        format!("Arc<std::sync::Mutex<{core_path}>>")
424    } else {
425        format!("Arc<{core_path}>")
426    };
427
428    crate::template_env::render(
429        "structs/opaque_struct.jinja",
430        minijinja::context! {
431            struct_name => struct_name,
432            has_derives => has_derives,
433            struct_attrs => struct_attrs,
434            omit_inner => omit_inner,
435            inner_type => inner_type,
436        },
437    )
438}
439
440#[cfg(test)]
441mod tests {
442    use super::{type_needs_mutex, type_needs_tokio_mutex};
443    use alef_core::ir::{MethodDef, ReceiverKind, TypeDef, TypeRef};
444
445    fn method(name: &str, receiver: Option<ReceiverKind>, is_async: bool) -> MethodDef {
446        MethodDef {
447            name: name.into(),
448            params: vec![],
449            return_type: TypeRef::Unit,
450            is_async,
451            is_static: false,
452            error_type: None,
453            doc: String::new(),
454            receiver,
455            sanitized: false,
456            trait_source: None,
457            returns_ref: false,
458            returns_cow: false,
459            return_newtype_wrapper: None,
460            has_default_impl: false,
461        }
462    }
463
464    fn type_with_methods(name: &str, methods: Vec<MethodDef>) -> TypeDef {
465        TypeDef {
466            name: name.into(),
467            rust_path: format!("my_crate::{name}"),
468            original_rust_path: String::new(),
469            fields: vec![],
470            methods,
471            is_opaque: true,
472            is_clone: false,
473            is_copy: false,
474            is_trait: false,
475            has_default: false,
476            has_stripped_cfg_fields: false,
477            is_return_type: false,
478            serde_rename_all: None,
479            has_serde: false,
480            super_traits: vec![],
481            doc: String::new(),
482            cfg: None,
483        }
484    }
485
486    #[test]
487    fn tokio_mutex_when_all_refmut_methods_async() {
488        let typ = type_with_methods(
489            "WebSocketConnection",
490            vec![
491                method("send_text", Some(ReceiverKind::RefMut), true),
492                method("receive_text", Some(ReceiverKind::RefMut), true),
493                method("close", None, true),
494            ],
495        );
496        assert!(type_needs_mutex(&typ));
497        assert!(type_needs_tokio_mutex(&typ));
498    }
499
500    #[test]
501    fn no_tokio_mutex_when_any_refmut_is_sync() {
502        let typ = type_with_methods(
503            "Mixed",
504            vec![
505                method("async_op", Some(ReceiverKind::RefMut), true),
506                method("sync_op", Some(ReceiverKind::RefMut), false),
507            ],
508        );
509        assert!(type_needs_mutex(&typ));
510        assert!(!type_needs_tokio_mutex(&typ));
511    }
512
513    #[test]
514    fn no_tokio_mutex_when_no_refmut() {
515        let typ = type_with_methods("ReadOnly", vec![method("get", Some(ReceiverKind::Ref), true)]);
516        assert!(!type_needs_mutex(&typ));
517        assert!(!type_needs_tokio_mutex(&typ));
518    }
519
520    #[test]
521    fn no_tokio_mutex_when_empty_methods() {
522        let typ = type_with_methods("Empty", vec![]);
523        assert!(!type_needs_mutex(&typ));
524        assert!(!type_needs_tokio_mutex(&typ));
525    }
526}