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        // Mirror per-field `#[serde(rename = "...")]` from the core type so the binding
225        // struct's JSON wire format matches the core's. Only when no caller-supplied
226        // serde rename is already present (caller may emit one for keyword-escapes).
227        if has_serde
228            && !attrs.iter().any(|a| a.starts_with("serde(rename"))
229            && !attrs.iter().any(|a| a == "serde(skip)")
230        {
231            if let Some(rename) = &field.serde_rename {
232                attrs.push(format!("serde(rename = \"{rename}\")"));
233            }
234        }
235        let emit_name = name_override.unwrap_or_else(|| field.name.clone());
236        sb.add_field_with_doc(&emit_name, &ty, attrs, &field.doc);
237    }
238    sb.build()
239}
240
241/// Generate a struct definition using the builder.
242pub fn gen_struct(typ: &TypeDef, mapper: &dyn TypeMapper, cfg: &RustBindingConfig) -> String {
243    let mut sb = StructBuilder::new(&typ.name);
244    for attr in cfg.struct_attrs {
245        sb.add_attr(attr);
246    }
247
248    // Check if struct has similar field names (e.g., sub_symbol and sup_symbol)
249    let field_names: Vec<_> = typ.fields.iter().filter(|f| f.cfg.is_none()).map(|f| &f.name).collect();
250    if has_similar_names(&field_names) {
251        sb.add_attr("allow(clippy::similar_names)");
252    }
253
254    for d in cfg.struct_derives {
255        sb.add_derive(d);
256    }
257    let _opaque_fields: Vec<&str> = typ
258        .fields
259        .iter()
260        .filter(|f| f.cfg.is_none() && field_references_opaque_type(&f.ty, cfg.opaque_type_names))
261        .map(|f| f.name.as_str())
262        .collect();
263    sb.add_derive("Default");
264    sb.add_derive("serde::Serialize");
265    sb.add_derive("serde::Deserialize");
266    let _has_serde = true;
267    for field in &typ.fields {
268        // Skip cfg-gated fields — they depend on features that may not be enabled
269        // for this binding crate. Including them would require the binding struct to
270        // handle conditional compilation which struct literal initializers can't express.
271        if field.cfg.is_some() {
272            continue;
273        }
274        // When option_duration_on_defaults is set, wrap non-optional Duration fields in
275        // Option<u64> for has_default types so the binding constructor can accept None
276        // and the From conversion falls back to the core type's Default.
277        let force_optional = cfg.option_duration_on_defaults
278            && typ.has_default
279            && !field.optional
280            && matches!(field.ty, TypeRef::Duration);
281        let ty = if (field.optional || force_optional) && !matches!(field.ty, TypeRef::Optional(_)) {
282            mapper.optional(&mapper.map_type(&field.ty))
283        } else {
284            // field.ty is already Optional(T) — mapped type is already Option<T>, don't double-wrap
285            mapper.map_type(&field.ty)
286        };
287        let mut attrs: Vec<String> = cfg.field_attrs.iter().map(|a| a.to_string()).collect();
288        // Mirror per-field `#[serde(rename = "...")]` from the core type so the binding
289        // struct's JSON wire format matches the core's.
290        if let Some(rename) = &field.serde_rename {
291            if !attrs.iter().any(|a| a.starts_with("serde(rename")) {
292                attrs.push(format!("serde(rename = \"{rename}\")"));
293            }
294        }
295        sb.add_field_with_doc(&field.name, &ty, attrs, &field.doc);
296    }
297    sb.build()
298}
299
300/// Generate a `Default` impl for a non-opaque binding struct with `has_default`.
301/// All fields use their type's Default::default().
302/// Optional fields use None instead of Default::default().
303/// This enables the struct to be used with `unwrap_or_default()` in config constructors.
304///
305/// WARNING: This assumes all field types implement Default. If a Named field type
306/// doesn't implement Default, this impl will fail to compile. Callers should verify
307/// that the struct's fields can be safely defaulted before calling this function.
308pub fn gen_struct_default_impl(typ: &TypeDef, name_prefix: &str) -> String {
309    let full_name = format!("{}{}", name_prefix, typ.name);
310    let fields: Vec<_> = typ
311        .fields
312        .iter()
313        .filter_map(|field| {
314            if field.cfg.is_some() {
315                return None;
316            }
317            let default_val = match &field.ty {
318                TypeRef::Optional(_) => "None".to_string(),
319                _ => "Default::default()".to_string(),
320            };
321            Some(minijinja::context! {
322                name => field.name.clone(),
323                default_val => default_val
324            })
325        })
326        .collect();
327
328    crate::template_env::render(
329        "structs/default_impl.jinja",
330        minijinja::context! {
331            full_name => full_name,
332            fields => fields
333        },
334    )
335}
336
337/// Check if any method on a type takes `&mut self`, meaning the opaque wrapper
338/// must use `Arc<Mutex<T>>` instead of `Arc<T>` to allow interior mutability.
339pub fn type_needs_mutex(typ: &TypeDef) -> bool {
340    typ.methods
341        .iter()
342        .any(|m| m.receiver == Some(alef_core::ir::ReceiverKind::RefMut))
343}
344
345/// Check if a type wrapping `Arc<Mutex<T>>` should use `tokio::sync::Mutex` instead
346/// of `std::sync::Mutex` because every `&mut self` method is `async`.
347///
348/// `std::sync::MutexGuard` is `!Send`, so holding a guard across `.await` makes the
349/// surrounding future `!Send`, which fails to compile in PyO3 / NAPI-RS bindings that
350/// require `Send` futures. `tokio::sync::MutexGuard` IS `Send`, so swapping the lock
351/// type fixes the entire async-locking story for these structs.
352///
353/// The condition is tight: every method that takes `&mut self` MUST be async. If even
354/// one sync method takes `&mut self`, switching to `tokio::sync::Mutex` would break
355/// it (since `tokio::sync::Mutex::lock()` returns a `Future` and cannot be awaited
356/// from sync context). In that mixed case we keep `std::sync::Mutex`.
357pub fn type_needs_tokio_mutex(typ: &TypeDef) -> bool {
358    use alef_core::ir::ReceiverKind;
359    if !type_needs_mutex(typ) {
360        return false;
361    }
362    let refmut_methods = typ.methods.iter().filter(|m| m.receiver == Some(ReceiverKind::RefMut));
363    let mut any = false;
364    for m in refmut_methods {
365        any = true;
366        if !m.is_async {
367            return false;
368        }
369    }
370    any
371}
372
373/// Generate an opaque wrapper struct with `inner: Arc<core::Type>`.
374/// For trait types, uses `Arc<dyn Type + Send + Sync>`.
375/// For types with `&mut self` methods, uses `Arc<Mutex<core::Type>>`.
376///
377/// Special case: if ALL methods on this type are sanitized, the type was created by the
378/// impl-block fallback for a generic core type (e.g. `GraphQLExecutor<Q,M,S>`). Sanitized
379/// methods never access `self.inner` (they emit `gen_unimplemented_body`), so we omit the
380/// `inner` field entirely. This avoids generating `Arc<CoreType>` with missing generic
381/// parameters, which would fail to compile.
382pub fn gen_opaque_struct(typ: &TypeDef, cfg: &RustBindingConfig) -> String {
383    let needs_mutex = type_needs_mutex(typ);
384    // Omit the inner field only when the rust_path contains generic type parameters
385    // (angle brackets), which means the concrete types are unknown at codegen time and
386    // `Arc<CoreType<_, _, _>>` would fail to compile. This typically occurs for types
387    // created from a generic impl block where all methods are sanitized.
388    // We do NOT omit inner solely because all_methods_sanitized is true: even when no
389    // methods delegate to self.inner, the inner field may be required by From impls
390    // generated for non-opaque structs that have this type as a field.
391    let core_path = typ.rust_path.replace('-', "_");
392    let has_unresolvable_generics = core_path.contains('<');
393    let all_methods_sanitized = !typ.methods.is_empty() && typ.methods.iter().all(|m| m.sanitized);
394    let omit_inner = all_methods_sanitized && has_unresolvable_generics;
395
396    let struct_attrs: Vec<_> = cfg.struct_attrs.iter().map(|s| s.to_string()).collect();
397    let has_derives = !cfg.struct_derives.is_empty();
398    let inner_type = if typ.is_trait {
399        format!("Arc<dyn {core_path} + Send + Sync>")
400    } else if needs_mutex {
401        format!("Arc<std::sync::Mutex<{core_path}>>")
402    } else {
403        format!("Arc<{core_path}>")
404    };
405
406    crate::template_env::render(
407        "structs/opaque_struct.jinja",
408        minijinja::context! {
409            struct_name => typ.name.clone(),
410            has_derives => has_derives,
411            struct_attrs => struct_attrs,
412            omit_inner => omit_inner,
413            inner_type => inner_type,
414        },
415    )
416}
417
418/// Generate an opaque wrapper struct with `inner: Arc<core::Type>` and a name prefix.
419/// For types with `&mut self` methods, uses `Arc<Mutex<core::Type>>`.
420///
421/// Special case: if ALL methods on this type are sanitized, omit the `inner` field.
422/// See `gen_opaque_struct` for the rationale.
423pub fn gen_opaque_struct_prefixed(typ: &TypeDef, cfg: &RustBindingConfig, prefix: &str) -> String {
424    let needs_mutex = type_needs_mutex(typ);
425    let core_path = typ.rust_path.replace('-', "_");
426    let has_unresolvable_generics = core_path.contains('<');
427    let all_methods_sanitized = !typ.methods.is_empty() && typ.methods.iter().all(|m| m.sanitized);
428    let omit_inner = all_methods_sanitized && has_unresolvable_generics;
429
430    let struct_attrs: Vec<_> = cfg.struct_attrs.iter().map(|s| s.to_string()).collect();
431    let has_derives = !cfg.struct_derives.is_empty();
432    let struct_name = format!("{prefix}{}", typ.name);
433    let inner_type = if typ.is_trait {
434        format!("Arc<dyn {core_path} + Send + Sync>")
435    } else if needs_mutex {
436        format!("Arc<std::sync::Mutex<{core_path}>>")
437    } else {
438        format!("Arc<{core_path}>")
439    };
440
441    crate::template_env::render(
442        "structs/opaque_struct.jinja",
443        minijinja::context! {
444            struct_name => struct_name,
445            has_derives => has_derives,
446            struct_attrs => struct_attrs,
447            omit_inner => omit_inner,
448            inner_type => inner_type,
449        },
450    )
451}
452
453#[cfg(test)]
454mod tests {
455    use super::{type_needs_mutex, type_needs_tokio_mutex};
456    use alef_core::ir::{MethodDef, ReceiverKind, TypeDef, TypeRef};
457
458    fn method(name: &str, receiver: Option<ReceiverKind>, is_async: bool) -> MethodDef {
459        MethodDef {
460            name: name.into(),
461            params: vec![],
462            return_type: TypeRef::Unit,
463            is_async,
464            is_static: false,
465            error_type: None,
466            doc: String::new(),
467            receiver,
468            sanitized: false,
469            trait_source: None,
470            returns_ref: false,
471            returns_cow: false,
472            return_newtype_wrapper: None,
473            has_default_impl: false,
474        }
475    }
476
477    fn type_with_methods(name: &str, methods: Vec<MethodDef>) -> TypeDef {
478        TypeDef {
479            name: name.into(),
480            rust_path: format!("my_crate::{name}"),
481            original_rust_path: String::new(),
482            fields: vec![],
483            methods,
484            is_opaque: true,
485            is_clone: false,
486            is_copy: false,
487            is_trait: false,
488            has_default: false,
489            has_stripped_cfg_fields: false,
490            is_return_type: false,
491            serde_rename_all: None,
492            has_serde: false,
493            super_traits: vec![],
494            doc: String::new(),
495            cfg: None,
496        }
497    }
498
499    #[test]
500    fn tokio_mutex_when_all_refmut_methods_async() {
501        let typ = type_with_methods(
502            "WebSocketConnection",
503            vec![
504                method("send_text", Some(ReceiverKind::RefMut), true),
505                method("receive_text", Some(ReceiverKind::RefMut), true),
506                method("close", None, true),
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_any_refmut_is_sync() {
515        let typ = type_with_methods(
516            "Mixed",
517            vec![
518                method("async_op", Some(ReceiverKind::RefMut), true),
519                method("sync_op", Some(ReceiverKind::RefMut), false),
520            ],
521        );
522        assert!(type_needs_mutex(&typ));
523        assert!(!type_needs_tokio_mutex(&typ));
524    }
525
526    #[test]
527    fn no_tokio_mutex_when_no_refmut() {
528        let typ = type_with_methods("ReadOnly", vec![method("get", Some(ReceiverKind::Ref), true)]);
529        assert!(!type_needs_mutex(&typ));
530        assert!(!type_needs_tokio_mutex(&typ));
531    }
532
533    #[test]
534    fn no_tokio_mutex_when_empty_methods() {
535        let typ = type_with_methods("Empty", vec![]);
536        assert!(!type_needs_mutex(&typ));
537        assert!(!type_needs_tokio_mutex(&typ));
538    }
539}