Skip to main content

alef_backend_csharp/gen_bindings/
mod.rs

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