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