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