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