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 only when the struct derives serde
136        if has_serde && opaque_fields.contains(&field.name.as_str()) {
137            attrs.push("serde(skip)".to_string());
138        }
139        sb.add_field_with_doc(&field.name, &ty, attrs, &field.doc);
140    }
141    sb.build()
142}
143
144/// Generate a struct definition using the builder.
145pub fn gen_struct(typ: &TypeDef, mapper: &dyn TypeMapper, cfg: &RustBindingConfig) -> String {
146    let mut sb = StructBuilder::new(&typ.name);
147    for attr in cfg.struct_attrs {
148        sb.add_attr(attr);
149    }
150
151    // Check if struct has similar field names (e.g., sub_symbol and sup_symbol)
152    let field_names: Vec<_> = typ.fields.iter().filter(|f| f.cfg.is_none()).map(|f| &f.name).collect();
153    if has_similar_names(&field_names) {
154        sb.add_attr("allow(clippy::similar_names)");
155    }
156
157    for d in cfg.struct_derives {
158        sb.add_derive(d);
159    }
160    let _opaque_fields: Vec<&str> = typ
161        .fields
162        .iter()
163        .filter(|f| f.cfg.is_none() && field_references_opaque_type(&f.ty, cfg.opaque_type_names))
164        .map(|f| f.name.as_str())
165        .collect();
166    sb.add_derive("Default");
167    sb.add_derive("serde::Serialize");
168    sb.add_derive("serde::Deserialize");
169    let _has_serde = true;
170    for field in &typ.fields {
171        // Skip cfg-gated fields — they depend on features that may not be enabled
172        // for this binding crate. Including them would require the binding struct to
173        // handle conditional compilation which struct literal initializers can't express.
174        if field.cfg.is_some() {
175            continue;
176        }
177        // When option_duration_on_defaults is set, wrap non-optional Duration fields in
178        // Option<u64> for has_default types so the binding constructor can accept None
179        // and the From conversion falls back to the core type's Default.
180        let force_optional = cfg.option_duration_on_defaults
181            && typ.has_default
182            && !field.optional
183            && matches!(field.ty, TypeRef::Duration);
184        let ty = if (field.optional || force_optional) && !matches!(field.ty, TypeRef::Optional(_)) {
185            mapper.optional(&mapper.map_type(&field.ty))
186        } else {
187            // field.ty is already Optional(T) — mapped type is already Option<T>, don't double-wrap
188            mapper.map_type(&field.ty)
189        };
190        let attrs: Vec<String> = cfg.field_attrs.iter().map(|a| a.to_string()).collect();
191        // Only add #[serde(default)] when serde derives are present on the struct
192        // (opaque_fields empty = serde derives added, opaque field needs serde(default))
193        // This can't happen: if opaque_fields is empty, no field matches this check.
194        // If opaque_fields is non-empty, serde derives were suppressed → skip serde attr.
195        // So this block is effectively dead — remove it to prevent stale serde attrs.
196        sb.add_field_with_doc(&field.name, &ty, attrs, &field.doc);
197    }
198    sb.build()
199}
200
201/// Generate a `Default` impl for a non-opaque binding struct with `has_default`.
202/// All fields use their type's Default::default().
203/// Optional fields use None instead of Default::default().
204/// This enables the struct to be used with `unwrap_or_default()` in config constructors.
205///
206/// WARNING: This assumes all field types implement Default. If a Named field type
207/// doesn't implement Default, this impl will fail to compile. Callers should verify
208/// that the struct's fields can be safely defaulted before calling this function.
209pub fn gen_struct_default_impl(typ: &TypeDef, name_prefix: &str) -> String {
210    let full_name = format!("{}{}", name_prefix, typ.name);
211    let mut out = String::with_capacity(256);
212    writeln!(out, "impl Default for {} {{", full_name).ok();
213    writeln!(out, "    fn default() -> Self {{").ok();
214    writeln!(out, "        Self {{").ok();
215    for field in &typ.fields {
216        if field.cfg.is_some() {
217            continue;
218        }
219        let default_val = match &field.ty {
220            TypeRef::Optional(_) => "None".to_string(),
221            _ => "Default::default()".to_string(),
222        };
223        writeln!(out, "            {}: {},", field.name, default_val).ok();
224    }
225    writeln!(out, "        }}").ok();
226    writeln!(out, "    }}").ok();
227    write!(out, "}}").ok();
228    out
229}
230
231/// Check if any method on a type takes `&mut self`, meaning the opaque wrapper
232/// must use `Arc<Mutex<T>>` instead of `Arc<T>` to allow interior mutability.
233pub fn type_needs_mutex(typ: &TypeDef) -> bool {
234    typ.methods
235        .iter()
236        .any(|m| m.receiver == Some(alef_core::ir::ReceiverKind::RefMut))
237}
238
239/// Generate an opaque wrapper struct with `inner: Arc<core::Type>`.
240/// For trait types, uses `Arc<dyn Type + Send + Sync>`.
241/// For types with `&mut self` methods, uses `Arc<Mutex<core::Type>>`.
242///
243/// Special case: if ALL methods on this type are sanitized, the type was created by the
244/// impl-block fallback for a generic core type (e.g. `GraphQLExecutor<Q,M,S>`). Sanitized
245/// methods never access `self.inner` (they emit `gen_unimplemented_body`), so we omit the
246/// `inner` field entirely. This avoids generating `Arc<CoreType>` with missing generic
247/// parameters, which would fail to compile.
248pub fn gen_opaque_struct(typ: &TypeDef, cfg: &RustBindingConfig) -> String {
249    let needs_mutex = type_needs_mutex(typ);
250    // Omit the inner field only when the rust_path contains generic type parameters
251    // (angle brackets), which means the concrete types are unknown at codegen time and
252    // `Arc<CoreType<_, _, _>>` would fail to compile. This typically occurs for types
253    // created from a generic impl block where all methods are sanitized.
254    // We do NOT omit inner solely because all_methods_sanitized is true: even when no
255    // methods delegate to self.inner, the inner field may be required by From impls
256    // generated for non-opaque structs that have this type as a field.
257    let core_path = typ.rust_path.replace('-', "_");
258    let has_unresolvable_generics = core_path.contains('<');
259    let all_methods_sanitized = !typ.methods.is_empty() && typ.methods.iter().all(|m| m.sanitized);
260    let omit_inner = all_methods_sanitized && has_unresolvable_generics;
261    let mut out = String::with_capacity(512);
262    if !cfg.struct_derives.is_empty() {
263        writeln!(out, "#[derive(Clone)]").ok();
264    }
265    for attr in cfg.struct_attrs {
266        writeln!(out, "#[{attr}]").ok();
267    }
268    writeln!(out, "pub struct {} {{", typ.name).ok();
269    if !omit_inner {
270        if typ.is_trait {
271            writeln!(out, "    inner: Arc<dyn {core_path} + Send + Sync>,").ok();
272        } else if needs_mutex {
273            writeln!(out, "    inner: Arc<std::sync::Mutex<{core_path}>>,").ok();
274        } else {
275            writeln!(out, "    inner: Arc<{core_path}>,").ok();
276        }
277    }
278    write!(out, "}}").ok();
279    out
280}
281
282/// Generate an opaque wrapper struct with `inner: Arc<core::Type>` and a name prefix.
283/// For types with `&mut self` methods, uses `Arc<Mutex<core::Type>>`.
284///
285/// Special case: if ALL methods on this type are sanitized, omit the `inner` field.
286/// See `gen_opaque_struct` for the rationale.
287pub fn gen_opaque_struct_prefixed(typ: &TypeDef, cfg: &RustBindingConfig, prefix: &str) -> String {
288    let needs_mutex = type_needs_mutex(typ);
289    let core_path = typ.rust_path.replace('-', "_");
290    let has_unresolvable_generics = core_path.contains('<');
291    let all_methods_sanitized = !typ.methods.is_empty() && typ.methods.iter().all(|m| m.sanitized);
292    let omit_inner = all_methods_sanitized && has_unresolvable_generics;
293    let mut out = String::with_capacity(512);
294    if !cfg.struct_derives.is_empty() {
295        writeln!(out, "#[derive(Clone)]").ok();
296    }
297    for attr in cfg.struct_attrs {
298        writeln!(out, "#[{attr}]").ok();
299    }
300    writeln!(out, "pub struct {}{} {{", prefix, typ.name).ok();
301    if !omit_inner {
302        if typ.is_trait {
303            writeln!(out, "    inner: Arc<dyn {core_path} + Send + Sync>,").ok();
304        } else if needs_mutex {
305            writeln!(out, "    inner: Arc<std::sync::Mutex<{core_path}>>,").ok();
306        } else {
307            writeln!(out, "    inner: Arc<{core_path}>,").ok();
308        }
309    }
310    write!(out, "}}").ok();
311    out
312}