Skip to main content

alef_backend_csharp/gen_bindings/
mod.rs

1use alef_core::backend::{Backend, BuildConfig, BuildDependency, Capabilities, GeneratedFile};
2use alef_core::config::{AdapterPattern, Language, ResolvedCrateConfig, resolve_output_dir};
3use alef_core::hash::{self, CommentStyle};
4use alef_core::ir::{ApiSurface, FieldDef, TypeRef};
5use heck::ToPascalCase;
6use std::collections::{HashMap, HashSet};
7use std::path::PathBuf;
8
9/// Metadata for a streaming adapter, used to drive emission of an
10/// `IAsyncEnumerable<Item>` method over the FFI iterator-handle protocol
11/// (`_start` / `_next` / `_free`).
12#[derive(Debug, Clone)]
13pub(super) struct StreamingMethodMeta {
14    /// Owner type (e.g. `DefaultClient`). Retained for future routing decisions even when the
15    /// current emitter derives the receiver type from the enclosing class.
16    #[allow(dead_code)]
17    pub owner_type: String,
18    pub item_type: String,
19}
20
21pub(super) mod enums;
22pub(super) mod errors;
23pub(super) mod functions;
24pub(super) mod methods;
25pub(super) mod types;
26
27pub struct CsharpBackend;
28
29impl CsharpBackend {
30    // lib_name comes from config.ffi_lib_name()
31}
32
33impl Backend for CsharpBackend {
34    fn name(&self) -> &str {
35        "csharp"
36    }
37
38    fn language(&self) -> Language {
39        Language::Csharp
40    }
41
42    fn capabilities(&self) -> Capabilities {
43        Capabilities {
44            supports_async: true,
45            supports_classes: true,
46            supports_enums: true,
47            supports_option: true,
48            supports_result: true,
49            ..Capabilities::default()
50        }
51    }
52
53    fn generate_bindings(&self, api: &ApiSurface, config: &ResolvedCrateConfig) -> anyhow::Result<Vec<GeneratedFile>> {
54        let namespace = config.csharp_namespace();
55        let prefix = config.ffi_prefix();
56        let lib_name = config.ffi_lib_name();
57
58        // Collect bridge param names and type aliases from trait_bridges config so we can strip
59        // them from generated function signatures and emit ConvertWithVisitor instead.
60        let bridge_param_names: HashSet<String> = config
61            .trait_bridges
62            .iter()
63            .filter_map(|b| b.param_name.clone())
64            .collect();
65        let bridge_type_aliases: HashSet<String> = config
66            .trait_bridges
67            .iter()
68            .filter_map(|b| b.type_alias.clone())
69            .collect();
70        // Only emit ConvertWithVisitor method if visitor_callbacks is explicitly enabled in FFI config
71        let has_visitor_callbacks = config.ffi.as_ref().map(|f| f.visitor_callbacks).unwrap_or(false);
72        let bridge_associated_types = config.bridge_associated_types();
73
74        // Streaming adapter methods are emitted via the iterator-handle FFI protocol
75        // (`{prefix}_{owner}_{name}_start` / `_next` / `_free`) — not as direct P/Invoke calls
76        // of the callback-based variant. The set is still used to skip the default
77        // method-emission path; the parallel meta map drives the `IAsyncEnumerable` emitters.
78        let streaming_methods: HashSet<String> = config
79            .adapters
80            .iter()
81            .filter(|a| matches!(a.pattern, AdapterPattern::Streaming))
82            .map(|a| a.name.clone())
83            .collect();
84        let streaming_methods_meta: HashMap<String, StreamingMethodMeta> = config
85            .adapters
86            .iter()
87            .filter(|a| matches!(a.pattern, AdapterPattern::Streaming))
88            .filter_map(|a| {
89                let owner_type = a.owner_type.clone()?;
90                let item_type = a.item_type.clone()?;
91                Some((a.name.clone(), StreamingMethodMeta { owner_type, item_type }))
92            })
93            .collect();
94
95        // Functions explicitly excluded from C# bindings (e.g., not present in the C FFI layer).
96        let exclude_functions: HashSet<String> = config
97            .csharp
98            .as_ref()
99            .map(|c| c.exclude_functions.iter().cloned().collect())
100            .unwrap_or_default();
101
102        let output_dir = resolve_output_dir(config.output_paths.get("csharp"), &config.name, "packages/csharp/");
103
104        let base_path = PathBuf::from(&output_dir).join(namespace.replace('.', "/"));
105
106        let mut files = Vec::new();
107
108        // Fallback generic exception class name (used by GetLastError and as base for typed errors)
109        let exception_class_name = format!("{}Exception", api.crate_name.to_pascal_case());
110
111        // 1. Generate NativeMethods.cs
112        files.push(GeneratedFile {
113            path: base_path.join("NativeMethods.cs"),
114            content: strip_trailing_whitespace(&functions::gen_native_methods(
115                api,
116                &namespace,
117                &lib_name,
118                &prefix,
119                &bridge_param_names,
120                &bridge_type_aliases,
121                has_visitor_callbacks,
122                &config.trait_bridges,
123                &streaming_methods,
124                &streaming_methods_meta,
125                &exclude_functions,
126            )),
127            generated_header: true,
128        });
129
130        // 2. Generate error types from thiserror enums (if any), otherwise generic exception
131        if !api.errors.is_empty() {
132            for error in &api.errors {
133                let error_files =
134                    alef_codegen::error_gen::gen_csharp_error_types(error, &namespace, Some(&exception_class_name));
135                for (class_name, content) in error_files {
136                    files.push(GeneratedFile {
137                        path: base_path.join(format!("{}.cs", class_name)),
138                        content: strip_trailing_whitespace(&content),
139                        generated_header: false, // already has header
140                    });
141                }
142            }
143        }
144
145        // Fallback generic exception class (always generated for GetLastError)
146        if api.errors.is_empty()
147            || !api
148                .errors
149                .iter()
150                .any(|e| format!("{}Exception", e.name) == exception_class_name)
151        {
152            files.push(GeneratedFile {
153                path: base_path.join(format!("{}.cs", exception_class_name)),
154                content: strip_trailing_whitespace(&errors::gen_exception_class(&namespace, &exception_class_name)),
155                generated_header: true,
156            });
157        }
158
159        // 3. Generate main wrapper class
160        let base_class_name = api.crate_name.to_pascal_case();
161        let wrapper_class_name = if namespace == base_class_name {
162            format!("{}Lib", base_class_name)
163        } else {
164            base_class_name
165        };
166        files.push(GeneratedFile {
167            path: base_path.join(format!("{}.cs", wrapper_class_name)),
168            content: strip_trailing_whitespace(&methods::gen_wrapper_class(
169                api,
170                &namespace,
171                &wrapper_class_name,
172                &exception_class_name,
173                &prefix,
174                &bridge_param_names,
175                &bridge_type_aliases,
176                has_visitor_callbacks,
177                &streaming_methods,
178                &streaming_methods_meta,
179                &exclude_functions,
180                &config.trait_bridges,
181            )),
182            generated_header: true,
183        });
184
185        // 3b. Generate visitor support files when a bridge is configured.
186        if has_visitor_callbacks {
187            // Look up the visitor trait def from the IR via TraitBridgeConfig.trait_name,
188            // mirroring the Go backend's pattern so that gen_visitor_files is IR-driven.
189            let visitor_bridge_cfg = config
190                .trait_bridges
191                .iter()
192                .find(|b| b.bind_via == alef_core::config::BridgeBinding::OptionsField);
193            let trait_map: std::collections::HashMap<&str, &alef_core::ir::TypeDef> = api
194                .types
195                .iter()
196                .filter(|t| t.is_trait)
197                .map(|t| (t.name.as_str(), t))
198                .collect();
199            let visitor_trait = visitor_bridge_cfg.and_then(|b| trait_map.get(b.trait_name.as_str()).copied());
200
201            if let Some(trait_def) = visitor_trait {
202                for (filename, content) in crate::gen_visitor::gen_visitor_files(&namespace, trait_def) {
203                    files.push(GeneratedFile {
204                        path: base_path.join(filename),
205                        content: strip_trailing_whitespace(&content),
206                        generated_header: true,
207                    });
208                }
209            } else {
210                // Trait not in IR (e.g. parsed separately); fall back to a minimal placeholder.
211                let placeholder = alef_core::ir::TypeDef {
212                    name: String::new(),
213                    rust_path: String::new(),
214                    original_rust_path: String::new(),
215                    fields: vec![],
216                    methods: vec![],
217                    is_opaque: false,
218                    is_clone: false,
219                    is_copy: false,
220                    is_trait: true,
221                    has_default: false,
222                    has_stripped_cfg_fields: false,
223                    is_return_type: false,
224                    serde_rename_all: None,
225                    has_serde: false,
226                    super_traits: vec![],
227                    doc: String::new(),
228                    cfg: None,
229                };
230                for (filename, content) in crate::gen_visitor::gen_visitor_files(&namespace, &placeholder) {
231                    files.push(GeneratedFile {
232                        path: base_path.join(filename),
233                        content: strip_trailing_whitespace(&content),
234                        generated_header: true,
235                    });
236                }
237            }
238            // IVisitor.cs and VisitorCallbacks.cs were removed from gen_visitor_files() in favour
239            // of the HtmlVisitorBridge path in TraitBridges.cs.  Delete any stale copies left
240            // over from earlier generator runs.
241            delete_superseded_visitor_files(&base_path)?;
242        } else {
243            // When visitor_callbacks is disabled, delete stale files from prior runs
244            // to prevent CS8632 warnings (nullable context not enabled).
245            delete_stale_visitor_files(&base_path)?;
246        }
247
248        // 3c. Generate trait bridge classes when configured.
249        if !config.trait_bridges.is_empty() {
250            let trait_defs: Vec<_> = api.types.iter().filter(|t| t.is_trait).collect();
251            let bridges: Vec<_> = config
252                .trait_bridges
253                .iter()
254                .filter_map(|cfg| {
255                    let trait_name = cfg.trait_name.clone();
256                    trait_defs
257                        .iter()
258                        .find(|t| t.name == trait_name)
259                        .map(|trait_def| (trait_name, cfg, *trait_def))
260                })
261                .collect();
262
263            if !bridges.is_empty() {
264                // Collect visible type names (non-trait types that have C# bindings)
265                let visible_type_names: HashSet<&str> = api
266                    .types
267                    .iter()
268                    .filter(|t| !t.is_trait)
269                    .map(|t| t.name.as_str())
270                    .collect();
271                let (filename, content) =
272                    crate::trait_bridge::gen_trait_bridges_file(&namespace, &prefix, &bridges, &visible_type_names);
273                files.push(GeneratedFile {
274                    path: base_path.join(filename),
275                    content: strip_trailing_whitespace(&content),
276                    generated_header: true,
277                });
278            }
279        }
280
281        // Collect enum names so record generation can distinguish enum fields from class fields.
282        let enum_names: HashSet<String> = api.enums.iter().map(|e| e.name.to_pascal_case()).collect();
283
284        // Collect all opaque type names (pascal-cased) so methods on one opaque type that
285        // return another opaque type are wrapped correctly rather than JSON-serialized.
286        let all_opaque_type_names: HashSet<String> = api
287            .types
288            .iter()
289            .filter(|t| t.is_opaque)
290            .map(|t| t.name.to_pascal_case())
291            .collect();
292
293        // 4. Generate opaque handle classes
294        for typ in api.types.iter().filter(|typ| !typ.is_trait) {
295            if typ.is_opaque {
296                let type_filename = typ.name.to_pascal_case();
297                files.push(GeneratedFile {
298                    path: base_path.join(format!("{}.cs", type_filename)),
299                    content: strip_trailing_whitespace(&types::gen_opaque_handle(
300                        typ,
301                        &namespace,
302                        &exception_class_name,
303                        &enum_names,
304                        &streaming_methods,
305                        &streaming_methods_meta,
306                        &all_opaque_type_names,
307                    )),
308                    generated_header: true,
309                });
310            }
311        }
312
313        // Untagged unions with data variants now emit as JsonElement-wrapper classes
314        // (see gen_untagged_wrapper). The set is intentionally empty so record fields
315        // keep their wrapper-class type instead of being downcast to JsonElement.
316        let complex_enums: HashSet<String> = HashSet::new();
317
318        // Collect enums that require a custom JsonConverter (non-standard serialized names only).
319        // Tagged unions are generated as abstract records with [JsonPolymorphic] and do NOT need
320        // a custom converter — the attribute on the type itself handles polymorphic deserialization.
321        // When a property has a custom-converter enum as its type, emit a property-level
322        // [JsonConverter] attribute so the custom converter wins over the global JsonStringEnumConverter.
323        let custom_converter_enums: HashSet<String> = api
324            .enums
325            .iter()
326            .filter(|e| {
327                // Skip tagged unions — they use [JsonPolymorphic] instead
328                let is_tagged_union = e.serde_tag.is_some() && e.variants.iter().any(|v| !v.fields.is_empty());
329                if is_tagged_union {
330                    return false;
331                }
332                // Enums whose `serde_rename_all` is something other than snake_case
333                // (e.g. "kebab-case" for `FilePurpose::FineTune` → `"fine-tune"`)
334                // need a custom converter — `JsonStringEnumConverter(SnakeCaseLower)`
335                // would write `"fine_tune"` instead.
336                let rename_all_differs = matches!(
337                    e.serde_rename_all.as_deref(),
338                    Some("kebab-case") | Some("SCREAMING-KEBAB-CASE") | Some("camelCase") | Some("PascalCase")
339                );
340                if rename_all_differs {
341                    return true;
342                }
343                // Enums with non-standard variant names need a custom converter
344                e.variants.iter().any(|v| {
345                    if let Some(ref rename) = v.serde_rename {
346                        let snake = enums::apply_rename_all(&v.name, e.serde_rename_all.as_deref());
347                        rename != &snake
348                    } else {
349                        false
350                    }
351                })
352            })
353            .map(|e| e.name.to_pascal_case())
354            .collect();
355
356        // Resolve the language-level serde rename_all strategy (always wins over IR type-level).
357        let lang_rename_all = config.serde_rename_all_for_language(Language::Csharp);
358
359        // 5. Generate record types (structs)
360        for typ in api.types.iter().filter(|typ| !typ.is_trait) {
361            if !typ.is_opaque {
362                // Skip types where all fields are unnamed tuple positions — they have no
363                // meaningful properties to expose in C#.
364                let has_named_fields = typ.fields.iter().any(|f| !is_tuple_field(f));
365                if !typ.fields.is_empty() && !has_named_fields {
366                    continue;
367                }
368                // Skip types that gen_visitor handles with richer visitor-specific versions
369                if has_visitor_callbacks && bridge_associated_types.contains(typ.name.as_str()) {
370                    continue;
371                }
372
373                let type_filename = typ.name.to_pascal_case();
374                files.push(GeneratedFile {
375                    path: base_path.join(format!("{}.cs", type_filename)),
376                    content: strip_trailing_whitespace(&types::gen_record_type(
377                        typ,
378                        &namespace,
379                        &enum_names,
380                        &complex_enums,
381                        &custom_converter_enums,
382                        &lang_rename_all,
383                        &bridge_type_aliases,
384                        &exception_class_name,
385                    )),
386                    generated_header: true,
387                });
388            }
389        }
390
391        // 6. Generate enums
392        for enum_def in &api.enums {
393            // Skip enums that gen_visitor handles with richer visitor-specific versions
394            if has_visitor_callbacks && bridge_associated_types.contains(enum_def.name.as_str()) {
395                continue;
396            }
397            let enum_filename = enum_def.name.to_pascal_case();
398            files.push(GeneratedFile {
399                path: base_path.join(format!("{}.cs", enum_filename)),
400                content: strip_trailing_whitespace(&enums::gen_enum(enum_def, &namespace)),
401                generated_header: true,
402            });
403        }
404
405        // 7. Generate ByteArrayToIntArrayConverter if any non-opaque type has non-optional Bytes fields.
406        // Non-optional byte[] fields must be serialized as JSON int arrays, not base64 strings.
407        let needs_byte_array_converter = api
408            .types
409            .iter()
410            .any(|t| !t.is_opaque && t.fields.iter().any(|f| !f.optional && matches!(f.ty, TypeRef::Bytes)));
411        if needs_byte_array_converter {
412            files.push(GeneratedFile {
413                path: base_path.join("ByteArrayToIntArrayConverter.cs"),
414                content: types::gen_byte_array_to_int_array_converter(&namespace),
415                generated_header: true,
416            });
417        }
418
419        // Build adapter body map (consumed by generators via body substitution)
420        let _adapter_bodies = alef_adapters::build_adapter_bodies(config, Language::Csharp)?;
421
422        // 8. Generate Directory.Build.props at the package root (always overwritten).
423        // This file enables Nullable=enable and latest LangVersion for all C# projects
424        // in the packages/csharp hierarchy without requiring per-csproj configuration.
425        files.push(GeneratedFile {
426            path: PathBuf::from("packages/csharp/Directory.Build.props"),
427            content: gen_directory_build_props(),
428            generated_header: true,
429        });
430
431        Ok(files)
432    }
433
434    /// C# wrapper class is already the public API.
435    /// The `gen_wrapper_class` (generated in `generate_bindings`) provides high-level public methods
436    /// that wrap NativeMethods (P/Invoke), marshal types, and handle errors.
437    /// No additional facade is needed.
438    fn generate_public_api(
439        &self,
440        _api: &ApiSurface,
441        _config: &ResolvedCrateConfig,
442    ) -> anyhow::Result<Vec<GeneratedFile>> {
443        // C#'s wrapper class IS the public API — no additional wrapper needed.
444        Ok(vec![])
445    }
446
447    fn build_config(&self) -> Option<BuildConfig> {
448        Some(BuildConfig {
449            tool: "dotnet",
450            crate_suffix: "",
451            build_dep: BuildDependency::Ffi,
452            post_build: vec![],
453        })
454    }
455}
456
457/// Returns true if a field is a tuple struct positional field (e.g., `_0`, `_1`, `0`, `1`).
458pub(super) fn is_tuple_field(field: &FieldDef) -> bool {
459    (field.name.starts_with('_') && field.name[1..].chars().all(|c| c.is_ascii_digit()))
460        || field.name.chars().next().is_none_or(|c| c.is_ascii_digit())
461}
462
463/// Strip trailing whitespace from every line and ensure the file ends with a single newline.
464pub(super) fn strip_trailing_whitespace(content: &str) -> String {
465    let mut result: String = content
466        .lines()
467        .map(|line| line.trim_end())
468        .collect::<Vec<_>>()
469        .join("\n");
470    if !result.ends_with('\n') {
471        result.push('\n');
472    }
473    result
474}
475
476/// Generate C# file header with hash and nullable-enable pragma.
477pub(super) fn csharp_file_header() -> String {
478    let mut out = hash::header(CommentStyle::DoubleSlash);
479    out.push_str("#nullable enable\n\n");
480    out
481}
482
483/// Generate Directory.Build.props with Nullable=enable and LangVersion=latest.
484/// This is auto-generated (overwritten on each build) so it doesn't require user maintenance.
485fn gen_directory_build_props() -> String {
486    "<!-- auto-generated by alef (generate_bindings) -->\n\
487<Project>\n  \
488<PropertyGroup>\n    \
489<Nullable>enable</Nullable>\n    \
490<LangVersion>latest</LangVersion>\n    \
491<TreatWarningsAsErrors>true</TreatWarningsAsErrors>\n  \
492</PropertyGroup>\n\
493</Project>\n"
494        .to_string()
495}
496
497/// Delete `IVisitor.cs` and `VisitorCallbacks.cs` when visitor_callbacks is enabled but the
498/// modern `HtmlVisitorBridge` / `TraitBridges.cs` path supersedes them.
499/// These files are no longer emitted by `gen_visitor_files()` but may exist on disk from older
500/// generator runs.
501fn delete_superseded_visitor_files(base_path: &std::path::Path) -> anyhow::Result<()> {
502    let superseded = ["IVisitor.cs", "VisitorCallbacks.cs"];
503    for filename in superseded {
504        let path = base_path.join(filename);
505        if path.exists() {
506            std::fs::remove_file(&path)
507                .map_err(|e| anyhow::anyhow!("Failed to delete superseded visitor file {}: {}", path.display(), e))?;
508        }
509    }
510    Ok(())
511}
512
513/// Delete stale visitor-related files when visitor_callbacks is disabled.
514/// When visitor_callbacks transitions from true → false, these files remain on disk
515/// and cause CS8632 warnings (nullable context not enabled in these files).
516fn delete_stale_visitor_files(base_path: &std::path::Path) -> anyhow::Result<()> {
517    let stale_files = vec!["IVisitor.cs", "VisitorCallbacks.cs", "NodeContext.cs", "VisitResult.cs"];
518
519    for filename in stale_files {
520        let path = base_path.join(filename);
521        if path.exists() {
522            std::fs::remove_file(&path)
523                .map_err(|e| anyhow::anyhow!("Failed to delete stale visitor file {}: {}", path.display(), e))?;
524        }
525    }
526
527    Ok(())
528}
529
530// ---------------------------------------------------------------------------
531// Helpers: P/Invoke return type mapping
532// ---------------------------------------------------------------------------
533
534use alef_core::ir::PrimitiveType;
535
536/// Returns the C# type to use in a `[DllImport]` declaration for the given return type.
537///
538/// Key differences from the high-level `csharp_type`:
539/// - Bool is marshalled as `int` (C FFI convention) — the wrapper compares != 0.
540/// - String / Named / Vec / Map / Path / Json / Bytes all come back as `IntPtr`.
541/// - Numeric primitives use their natural C# types (`nuint`, `int`, etc.).
542pub(super) fn pinvoke_return_type(ty: &TypeRef) -> &'static str {
543    match ty {
544        TypeRef::Unit => "void",
545        // Bool over FFI is a C int (0/1).
546        TypeRef::Primitive(PrimitiveType::Bool) => "int",
547        // Numeric primitives — use their real C# types.
548        TypeRef::Primitive(PrimitiveType::U8) => "byte",
549        TypeRef::Primitive(PrimitiveType::U16) => "ushort",
550        TypeRef::Primitive(PrimitiveType::U32) => "uint",
551        TypeRef::Primitive(PrimitiveType::U64) => "ulong",
552        TypeRef::Primitive(PrimitiveType::I8) => "sbyte",
553        TypeRef::Primitive(PrimitiveType::I16) => "short",
554        TypeRef::Primitive(PrimitiveType::I32) => "int",
555        TypeRef::Primitive(PrimitiveType::I64) => "long",
556        TypeRef::Primitive(PrimitiveType::F32) => "float",
557        TypeRef::Primitive(PrimitiveType::F64) => "double",
558        TypeRef::Primitive(PrimitiveType::Usize) => "ulong",
559        TypeRef::Primitive(PrimitiveType::Isize) => "long",
560        // Duration as u64
561        TypeRef::Duration => "ulong",
562        // Everything else is a pointer that needs manual marshalling.
563        TypeRef::String
564        | TypeRef::Char
565        | TypeRef::Bytes
566        | TypeRef::Optional(_)
567        | TypeRef::Vec(_)
568        | TypeRef::Map(_, _)
569        | TypeRef::Named(_)
570        | TypeRef::Path
571        | TypeRef::Json => "IntPtr",
572    }
573}
574
575/// Returns the C# type to use for a parameter in a `[DllImport]` declaration.
576///
577/// Managed reference types (Named structs, Vec, Map, Bytes, Optional of Named, etc.)
578/// cannot be directly marshalled by P/Invoke.  They must be passed as `IntPtr` (opaque
579/// handle or JSON-string pointer).  Primitive types and plain strings use their natural
580/// types.
581pub(super) fn pinvoke_param_type(ty: &TypeRef) -> &'static str {
582    match ty {
583        TypeRef::String | TypeRef::Char | TypeRef::Path | TypeRef::Json => "string",
584        // Managed objects — pass as opaque IntPtr (serialised to handle before call)
585        TypeRef::Named(_) | TypeRef::Vec(_) | TypeRef::Map(_, _) | TypeRef::Bytes | TypeRef::Optional(_) => "IntPtr",
586        TypeRef::Unit => "void",
587        TypeRef::Primitive(PrimitiveType::Bool) => "int",
588        TypeRef::Primitive(PrimitiveType::U8) => "byte",
589        TypeRef::Primitive(PrimitiveType::U16) => "ushort",
590        TypeRef::Primitive(PrimitiveType::U32) => "uint",
591        TypeRef::Primitive(PrimitiveType::U64) => "ulong",
592        TypeRef::Primitive(PrimitiveType::I8) => "sbyte",
593        TypeRef::Primitive(PrimitiveType::I16) => "short",
594        TypeRef::Primitive(PrimitiveType::I32) => "int",
595        TypeRef::Primitive(PrimitiveType::I64) => "long",
596        TypeRef::Primitive(PrimitiveType::F32) => "float",
597        TypeRef::Primitive(PrimitiveType::F64) => "double",
598        TypeRef::Primitive(PrimitiveType::Usize) => "ulong",
599        TypeRef::Primitive(PrimitiveType::Isize) => "long",
600        TypeRef::Duration => "ulong",
601    }
602}
603
604/// Returns true if a parameter should be hidden from the public API because it is a
605/// trait-bridge param (e.g. the FFI visitor handle).
606pub(super) fn is_bridge_param(
607    param: &alef_core::ir::ParamDef,
608    bridge_param_names: &HashSet<String>,
609    bridge_type_aliases: &HashSet<String>,
610) -> bool {
611    bridge_param_names.contains(&param.name)
612        || matches!(&param.ty, alef_core::ir::TypeRef::Named(n) if bridge_type_aliases.contains(n))
613}
614
615/// Does the return type need IntPtr→string marshalling in the wrapper?
616pub(super) fn returns_string(ty: &TypeRef) -> bool {
617    matches!(ty, TypeRef::String | TypeRef::Char | TypeRef::Path | TypeRef::Json)
618}
619
620/// Does the return type come back as a C int that should be converted to bool?
621pub(super) fn returns_bool_via_int(ty: &TypeRef) -> bool {
622    matches!(ty, TypeRef::Primitive(PrimitiveType::Bool))
623}
624
625/// Does the return type need JSON deserialization from an IntPtr string?
626pub(super) fn returns_json_object(ty: &TypeRef) -> bool {
627    matches!(
628        ty,
629        TypeRef::Vec(_) | TypeRef::Map(_, _) | TypeRef::Named(_) | TypeRef::Bytes | TypeRef::Optional(_)
630    )
631}
632
633/// Returns true if the FFI return type is a pointer (IntPtr), as opposed to a numeric value.
634/// Only pointer-returning functions use `IntPtr.Zero` as an error sentinel.
635pub(super) fn returns_ptr(ty: &TypeRef) -> bool {
636    matches!(
637        ty,
638        TypeRef::String
639            | TypeRef::Char
640            | TypeRef::Path
641            | TypeRef::Json
642            | TypeRef::Named(_)
643            | TypeRef::Vec(_)
644            | TypeRef::Map(_, _)
645            | TypeRef::Bytes
646            | TypeRef::Optional(_)
647    )
648}
649
650/// Returns the argument expression to pass to the native method for a given parameter.
651///
652/// For truly opaque types (is_opaque = true), the C# class wraps an IntPtr; pass `.Handle`.
653/// For data-struct `Named` types this is the handle variable (e.g. `optionsHandle`).
654/// For everything else it is the parameter name (with `!` for optional).
655pub(super) fn native_call_arg(
656    ty: &TypeRef,
657    param_name: &str,
658    optional: bool,
659    true_opaque_types: &HashSet<String>,
660) -> String {
661    match ty {
662        TypeRef::Named(type_name) if true_opaque_types.contains(type_name) => {
663            // Truly opaque: unwrap the IntPtr from the C# handle class.
664            let bang = if optional { "!" } else { "" };
665            format!("{param_name}{bang}.Handle")
666        }
667        TypeRef::Named(_) | TypeRef::Vec(_) | TypeRef::Map(_, _) => {
668            format!("{param_name}Handle")
669        }
670        TypeRef::Bytes => {
671            format!("{param_name}Handle.AddrOfPinnedObject()")
672        }
673        TypeRef::Primitive(alef_core::ir::PrimitiveType::Bool) => {
674            // FFI convention: bool marshalled as int (0 = false, non-zero = true)
675            if optional {
676                format!("({param_name}?.Value ? 1 : 0)")
677            } else {
678                format!("({param_name} ? 1 : 0)")
679            }
680        }
681        ty => {
682            if optional {
683                // For optional primitive types (e.g. ulong?, uint?), pass the FFI's
684                // None sentinel when the value is null. The FFI shim decodes
685                // `{prim}::MAX` (and NAN for floats) as None — passing 0 collides with
686                // a legitimate zero from the caller, e.g. timeout_secs=0 = "no timeout"
687                // would be silently treated as "unset" without this. Mirrors the
688                // `alef-backend-ffi` `param_optional_numeric_conversion` decoder.
689                // String/Char/Path/Json are reference types so `!` is correct for those.
690                if let TypeRef::Primitive(prim) = ty {
691                    use alef_core::ir::PrimitiveType;
692                    let sentinel = match prim {
693                        PrimitiveType::U8 => "byte.MaxValue",
694                        PrimitiveType::U16 => "ushort.MaxValue",
695                        PrimitiveType::U32 => "uint.MaxValue",
696                        PrimitiveType::U64 | PrimitiveType::Usize => "ulong.MaxValue",
697                        PrimitiveType::I8 => "sbyte.MaxValue",
698                        PrimitiveType::I16 => "short.MaxValue",
699                        PrimitiveType::I32 => "int.MaxValue",
700                        PrimitiveType::I64 | PrimitiveType::Isize => "long.MaxValue",
701                        PrimitiveType::F32 => "float.NaN",
702                        PrimitiveType::F64 => "double.NaN",
703                        PrimitiveType::Bool => unreachable!("handled above"),
704                    };
705                    format!("{param_name} ?? {sentinel}")
706                } else if matches!(ty, TypeRef::Duration) {
707                    format!("{param_name}.GetValueOrDefault()")
708                } else {
709                    format!("{param_name}!")
710                }
711            } else {
712                param_name.to_string()
713            }
714        }
715    }
716}
717
718/// For each `Named` parameter, emit code to serialise it to JSON and obtain a native handle.
719///
720/// For truly opaque types (is_opaque = true), the C# class already wraps the native handle, so
721/// we pass `param.Handle` directly without any JSON serialisation.
722pub(super) fn emit_named_param_setup(
723    out: &mut String,
724    params: &[alef_core::ir::ParamDef],
725    indent: &str,
726    true_opaque_types: &HashSet<String>,
727    exception_name: &str,
728) {
729    for param in params {
730        let param_name = param.name.to_lower_camel_case();
731        let json_var = format!("{param_name}Json");
732        let handle_var = format!("{param_name}Handle");
733
734        match &param.ty {
735            TypeRef::Named(type_name) => {
736                // Truly opaque handles: the C# wrapper class holds the IntPtr directly.
737                // No from_json round-trip needed — pass .Handle directly in native_call_arg.
738                if true_opaque_types.contains(type_name) {
739                    continue;
740                }
741                let from_json_method = format!("{}FromJson", type_name.to_pascal_case());
742
743                // Config parameters: always treat as optional and default null to new instance
744                let is_config_param = param.name == "config";
745                let param_to_serialize = if is_config_param {
746                    let type_pascal = type_name.to_pascal_case();
747                    format!("({} ?? new {}())", param_name, type_pascal)
748                } else {
749                    param_name.to_string()
750                };
751
752                if param.optional && !is_config_param {
753                    // Optional Named param: pass IntPtr.Zero through to native when the
754                    // C# arg is null instead of round-tripping `"null"` through FromJson
755                    // which would error with "invalid type: null, expected struct T".
756                    out.push_str(&crate::template_env::render(
757                        "named_param_handle_from_json_optional.jinja",
758                        minijinja::context! {
759                            indent,
760                            handle_var => &handle_var,
761                            from_json_method => &from_json_method,
762                            json_var => &json_var,
763                            param_name => &param_name,
764                            exception_name => exception_name,
765                        },
766                    ));
767                } else {
768                    out.push_str(&crate::template_env::render(
769                        "named_param_json_serialize.jinja",
770                        minijinja::context! { indent, json_var => &json_var, param_name => &param_to_serialize },
771                    ));
772                    out.push_str(&crate::template_env::render(
773                        "named_param_handle_from_json.jinja",
774                        minijinja::context! {
775                            indent,
776                            handle_var => &handle_var,
777                            from_json_method => &from_json_method,
778                            json_var => &json_var,
779                            exception_name => exception_name,
780                        },
781                    ));
782                }
783            }
784            TypeRef::Vec(_) | TypeRef::Map(_, _) => {
785                // Vec/Map: serialize to JSON string, marshal to native pointer
786                out.push_str(&crate::template_env::render(
787                    "named_param_json_serialize.jinja",
788                    minijinja::context! { indent, json_var => &json_var, param_name => &param_name },
789                ));
790                out.push_str(&crate::template_env::render(
791                    "named_param_handle_string.jinja",
792                    minijinja::context! { indent, handle_var => &handle_var, json_var => &json_var },
793                ));
794            }
795            TypeRef::Bytes => {
796                // byte[]: pin the managed array and pass pointer to native
797                out.push_str(&crate::template_env::render(
798                    "named_param_handle_pin.jinja",
799                    minijinja::context! { indent, handle_var => &handle_var, param_name => &param_name },
800                ));
801            }
802            _ => {}
803        }
804    }
805}
806
807/// Emit cleanup code to free native handles allocated for `Named` parameters.
808///
809/// Truly opaque handles (is_opaque = true) are NOT freed here — their lifetime is managed by
810/// the C# wrapper class (IDisposable). Only data-struct handles (from_json-allocated) are freed.
811pub(super) fn emit_named_param_teardown(
812    out: &mut String,
813    params: &[alef_core::ir::ParamDef],
814    true_opaque_types: &HashSet<String>,
815) {
816    for param in params {
817        let param_name = param.name.to_lower_camel_case();
818        let handle_var = format!("{param_name}Handle");
819        match &param.ty {
820            TypeRef::Named(type_name) => {
821                if true_opaque_types.contains(type_name) {
822                    // Caller owns the opaque handle — do not free it here.
823                    continue;
824                }
825                let free_method = format!("{}Free", type_name.to_pascal_case());
826                out.push_str(&crate::template_env::render(
827                    "named_param_teardown_free.jinja",
828                    minijinja::context! { indent => "        ", free_method => &free_method, handle_var => &handle_var },
829                ));
830            }
831            TypeRef::Vec(_) | TypeRef::Map(_, _) => {
832                out.push_str(&crate::template_env::render(
833                    "named_param_teardown_hglobal.jinja",
834                    minijinja::context! { indent => "        ", handle_var => &handle_var },
835                ));
836            }
837            TypeRef::Bytes => {
838                out.push_str(&crate::template_env::render(
839                    "named_param_teardown_gchandle.jinja",
840                    minijinja::context! { indent => "        ", handle_var => &handle_var },
841                ));
842            }
843            _ => {}
844        }
845    }
846}
847
848/// Emit cleanup code with configurable indentation (used inside `Task.Run` lambdas).
849pub(super) fn emit_named_param_teardown_indented(
850    out: &mut String,
851    params: &[alef_core::ir::ParamDef],
852    indent: &str,
853    true_opaque_types: &HashSet<String>,
854) {
855    for param in params {
856        let param_name = param.name.to_lower_camel_case();
857        let handle_var = format!("{param_name}Handle");
858        match &param.ty {
859            TypeRef::Named(type_name) => {
860                if true_opaque_types.contains(type_name) {
861                    // Caller owns the opaque handle — do not free it here.
862                    continue;
863                }
864                let free_method = format!("{}Free", type_name.to_pascal_case());
865                out.push_str(&crate::template_env::render(
866                    "named_param_teardown_free.jinja",
867                    minijinja::context! { indent, free_method => &free_method, handle_var => &handle_var },
868                ));
869            }
870            TypeRef::Vec(_) | TypeRef::Map(_, _) => {
871                out.push_str(&crate::template_env::render(
872                    "named_param_teardown_hglobal.jinja",
873                    minijinja::context! { indent, handle_var => &handle_var },
874                ));
875            }
876            TypeRef::Bytes => {
877                out.push_str(&crate::template_env::render(
878                    "named_param_teardown_gchandle.jinja",
879                    minijinja::context! { indent, handle_var => &handle_var },
880                ));
881            }
882            _ => {}
883        }
884    }
885}
886
887use heck::ToLowerCamelCase;