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        // Tagged-union enums (serde-tagged data enums) are emitted as
389        // `public abstract record Base { public sealed record Variant() : Base; }`
390        // where `Base.Variant` is a TYPE — property defaults must be `new Base.Variant()`
391        // rather than the bare `Base.Variant`, otherwise C# raises CS0119
392        // ("X is a type, which is not valid in the given context").
393        let tagged_union_enums: HashSet<String> = api
394            .enums
395            .iter()
396            .filter(|e| e.serde_tag.is_some() && e.variants.iter().any(|v| !v.fields.is_empty()))
397            .map(|e| e.name.to_pascal_case())
398            .collect();
399
400        // Collect enums that require a custom JsonConverter (non-standard serialized names only).
401        // Tagged unions are generated as abstract records with [JsonPolymorphic] and do NOT need
402        // a custom converter — the attribute on the type itself handles polymorphic deserialization.
403        // When a property has a custom-converter enum as its type, emit a property-level
404        // [JsonConverter] attribute so the custom converter wins over the global JsonStringEnumConverter.
405        let custom_converter_enums: HashSet<String> = api
406            .enums
407            .iter()
408            .filter(|e| {
409                // Skip tagged unions — they use [JsonPolymorphic] instead
410                let is_tagged_union = e.serde_tag.is_some() && e.variants.iter().any(|v| !v.fields.is_empty());
411                if is_tagged_union {
412                    return false;
413                }
414                // Enums whose `serde_rename_all` is something other than snake_case
415                // (e.g. "kebab-case" for `FilePurpose::FineTune` → `"fine-tune"`)
416                // need a custom converter — `JsonStringEnumConverter(SnakeCaseLower)`
417                // would write `"fine_tune"` instead.
418                let rename_all_differs = matches!(
419                    e.serde_rename_all.as_deref(),
420                    Some("kebab-case") | Some("SCREAMING-KEBAB-CASE") | Some("camelCase") | Some("PascalCase")
421                );
422                if rename_all_differs {
423                    return true;
424                }
425                // Enums with non-standard variant names need a custom converter
426                e.variants.iter().any(|v| {
427                    if let Some(ref rename) = v.serde_rename {
428                        let snake = enums::apply_rename_all(&v.name, e.serde_rename_all.as_deref());
429                        rename != &snake
430                    } else {
431                        false
432                    }
433                })
434            })
435            .map(|e| e.name.to_pascal_case())
436            .collect();
437
438        // Resolve the language-level serde rename_all strategy (always wins over IR type-level).
439        let lang_rename_all = config.serde_rename_all_for_language(Language::Csharp);
440
441        // 5. Generate record types (structs)
442        for typ in api.types.iter().filter(|typ| !typ.is_trait) {
443            if !typ.is_opaque {
444                // Skip types where all fields are unnamed tuple positions — they have no
445                // meaningful properties to expose in C#.
446                let has_visible_fields = binding_fields(&typ.fields).next().is_some();
447                let has_named_fields = binding_fields(&typ.fields).any(|f| !is_tuple_field(f));
448                if has_visible_fields && !has_named_fields {
449                    continue;
450                }
451                // Skip types that gen_visitor handles with richer visitor-specific versions
452                if has_visitor_callbacks && bridge_associated_types.contains(typ.name.as_str()) {
453                    continue;
454                }
455
456                let type_filename = typ.name.to_pascal_case();
457                let excluded_types: HashSet<String> =
458                    api.excluded_type_paths.keys().map(|n| n.to_pascal_case()).collect();
459                files.push(GeneratedFile {
460                    path: base_path.join(format!("{}.cs", type_filename)),
461                    content: strip_trailing_whitespace(&types::gen_record_type(
462                        typ,
463                        &namespace,
464                        &enum_names,
465                        &complex_enums,
466                        &custom_converter_enums,
467                        &lang_rename_all,
468                        &bridge_type_aliases,
469                        &exception_class_name,
470                        &excluded_types,
471                        &tagged_union_enums,
472                    )),
473                    generated_header: true,
474                });
475            }
476        }
477
478        // 6. Generate enums
479        for enum_def in &api.enums {
480            // Skip enums that gen_visitor handles with richer visitor-specific versions
481            if has_visitor_callbacks && bridge_associated_types.contains(enum_def.name.as_str()) {
482                continue;
483            }
484            let enum_filename = enum_def.name.to_pascal_case();
485            files.push(GeneratedFile {
486                path: base_path.join(format!("{}.cs", enum_filename)),
487                content: strip_trailing_whitespace(&enums::gen_enum(enum_def, &namespace)),
488                generated_header: true,
489            });
490        }
491
492        // 7. Generate ByteArrayToIntArrayConverter if any non-opaque type has non-optional Bytes fields.
493        // Non-optional byte[] fields must be serialized as JSON int arrays, not base64 strings.
494        let needs_byte_array_converter = api
495            .types
496            .iter()
497            .any(|t| !t.is_opaque && t.fields.iter().any(|f| !f.optional && matches!(f.ty, TypeRef::Bytes)));
498        if needs_byte_array_converter {
499            files.push(GeneratedFile {
500                path: base_path.join("ByteArrayToIntArrayConverter.cs"),
501                content: types::gen_byte_array_to_int_array_converter(&namespace),
502                generated_header: true,
503            });
504        }
505
506        // Build adapter body map (consumed by generators via body substitution)
507        let _adapter_bodies = alef_adapters::build_adapter_bodies(config, Language::Csharp)?;
508
509        // 8. Generate Directory.Build.props at the package root (always overwritten).
510        // This file enables Nullable=enable and latest LangVersion for all C# projects
511        // in the packages/csharp hierarchy without requiring per-csproj configuration.
512        files.push(GeneratedFile {
513            path: PathBuf::from("packages/csharp/Directory.Build.props"),
514            content: gen_directory_build_props(),
515            generated_header: true,
516        });
517
518        Ok(files)
519    }
520
521    /// C# wrapper class is already the public API.
522    /// The `gen_wrapper_class` (generated in `generate_bindings`) provides high-level public methods
523    /// that wrap NativeMethods (P/Invoke), marshal types, and handle errors.
524    /// No additional facade is needed.
525    fn generate_public_api(
526        &self,
527        _api: &ApiSurface,
528        _config: &ResolvedCrateConfig,
529    ) -> anyhow::Result<Vec<GeneratedFile>> {
530        // C#'s wrapper class IS the public API — no additional wrapper needed.
531        Ok(vec![])
532    }
533
534    fn build_config(&self) -> Option<BuildConfig> {
535        Some(BuildConfig {
536            tool: "dotnet",
537            crate_suffix: "",
538            build_dep: BuildDependency::Ffi,
539            post_build: vec![],
540        })
541    }
542}
543
544/// Returns true if a field is a tuple struct positional field (e.g., `_0`, `_1`, `0`, `1`).
545pub(super) fn is_tuple_field(field: &FieldDef) -> bool {
546    (field.name.starts_with('_') && field.name[1..].chars().all(|c| c.is_ascii_digit()))
547        || field.name.chars().next().is_none_or(|c| c.is_ascii_digit())
548}
549
550/// Strip trailing whitespace from every line and ensure the file ends with a single newline.
551pub(super) fn strip_trailing_whitespace(content: &str) -> String {
552    let mut result: String = content
553        .lines()
554        .map(|line| line.trim_end())
555        .collect::<Vec<_>>()
556        .join("\n");
557    if !result.ends_with('\n') {
558        result.push('\n');
559    }
560    result
561}
562
563/// Generate C# file header with hash and nullable-enable pragma.
564pub(super) fn csharp_file_header() -> String {
565    let mut out = hash::header(CommentStyle::DoubleSlash);
566    out.push_str("#nullable enable\n\n");
567    out
568}
569
570/// Generate Directory.Build.props with Nullable=enable and LangVersion=latest.
571/// This is auto-generated (overwritten on each build) so it doesn't require user maintenance.
572fn gen_directory_build_props() -> String {
573    "<!-- auto-generated by alef (generate_bindings) -->\n\
574<Project>\n  \
575<PropertyGroup>\n    \
576<Nullable>enable</Nullable>\n    \
577<LangVersion>latest</LangVersion>\n    \
578<TreatWarningsAsErrors>true</TreatWarningsAsErrors>\n  \
579</PropertyGroup>\n\
580</Project>\n"
581        .to_string()
582}
583
584/// Delete `IVisitor.cs` and `VisitorCallbacks.cs` when visitor_callbacks is enabled but the
585/// modern `HtmlVisitorBridge` / `TraitBridges.cs` path supersedes them.
586/// These files are no longer emitted by `gen_visitor_files()` but may exist on disk from older
587/// generator runs.
588fn delete_superseded_visitor_files(base_path: &std::path::Path) -> anyhow::Result<()> {
589    let superseded = ["IVisitor.cs", "VisitorCallbacks.cs"];
590    for filename in superseded {
591        let path = base_path.join(filename);
592        if path.exists() {
593            std::fs::remove_file(&path)
594                .map_err(|e| anyhow::anyhow!("Failed to delete superseded visitor file {}: {}", path.display(), e))?;
595        }
596    }
597    Ok(())
598}
599
600/// Delete stale visitor-related files when visitor_callbacks is disabled.
601/// When visitor_callbacks transitions from true → false, these files remain on disk
602/// and cause CS8632 warnings (nullable context not enabled in these files).
603fn delete_stale_visitor_files(base_path: &std::path::Path) -> anyhow::Result<()> {
604    let stale_files = vec!["IVisitor.cs", "VisitorCallbacks.cs", "NodeContext.cs", "VisitResult.cs"];
605
606    for filename in stale_files {
607        let path = base_path.join(filename);
608        if path.exists() {
609            std::fs::remove_file(&path)
610                .map_err(|e| anyhow::anyhow!("Failed to delete stale visitor file {}: {}", path.display(), e))?;
611        }
612    }
613
614    Ok(())
615}
616
617// ---------------------------------------------------------------------------
618// Helpers: P/Invoke return type mapping
619// ---------------------------------------------------------------------------
620
621use alef_core::ir::PrimitiveType;
622
623/// Returns the C# type to use in a `[DllImport]` declaration for the given return type.
624///
625/// Key differences from the high-level `csharp_type`:
626/// - Bool is marshalled as `int` (C FFI convention) — the wrapper compares != 0.
627/// - String / Named / Vec / Map / Path / Json / Bytes all come back as `IntPtr`.
628/// - Numeric primitives use their natural C# types (`nuint`, `int`, etc.).
629pub(super) fn pinvoke_return_type(ty: &TypeRef) -> &'static str {
630    match ty {
631        TypeRef::Unit => "void",
632        // Bool over FFI is a C int (0/1).
633        TypeRef::Primitive(PrimitiveType::Bool) => "int",
634        // Numeric primitives — use their real C# types.
635        TypeRef::Primitive(PrimitiveType::U8) => "byte",
636        TypeRef::Primitive(PrimitiveType::U16) => "ushort",
637        TypeRef::Primitive(PrimitiveType::U32) => "uint",
638        TypeRef::Primitive(PrimitiveType::U64) => "ulong",
639        TypeRef::Primitive(PrimitiveType::I8) => "sbyte",
640        TypeRef::Primitive(PrimitiveType::I16) => "short",
641        TypeRef::Primitive(PrimitiveType::I32) => "int",
642        TypeRef::Primitive(PrimitiveType::I64) => "long",
643        TypeRef::Primitive(PrimitiveType::F32) => "float",
644        TypeRef::Primitive(PrimitiveType::F64) => "double",
645        TypeRef::Primitive(PrimitiveType::Usize) => "ulong",
646        TypeRef::Primitive(PrimitiveType::Isize) => "long",
647        // Duration as u64
648        TypeRef::Duration => "ulong",
649        // Everything else is a pointer that needs manual marshalling.
650        TypeRef::String
651        | TypeRef::Char
652        | TypeRef::Bytes
653        | TypeRef::Optional(_)
654        | TypeRef::Vec(_)
655        | TypeRef::Map(_, _)
656        | TypeRef::Named(_)
657        | TypeRef::Path
658        | TypeRef::Json => "IntPtr",
659    }
660}
661
662/// Returns the C# type to use for a parameter in a `[DllImport]` declaration.
663///
664/// Managed reference types (Named structs, Vec, Map, Bytes, Optional of Named, etc.)
665/// cannot be directly marshalled by P/Invoke.  They must be passed as `IntPtr` (opaque
666/// handle or JSON-string pointer).  Primitive types and plain strings use their natural
667/// types.
668pub(super) fn pinvoke_param_type(ty: &TypeRef) -> &'static str {
669    match ty {
670        TypeRef::String | TypeRef::Char | TypeRef::Path | TypeRef::Json => "string",
671        // Managed objects — pass as opaque IntPtr (serialised to handle before call)
672        TypeRef::Named(_) | TypeRef::Vec(_) | TypeRef::Map(_, _) | TypeRef::Bytes | TypeRef::Optional(_) => "IntPtr",
673        TypeRef::Unit => "void",
674        TypeRef::Primitive(PrimitiveType::Bool) => "int",
675        TypeRef::Primitive(PrimitiveType::U8) => "byte",
676        TypeRef::Primitive(PrimitiveType::U16) => "ushort",
677        TypeRef::Primitive(PrimitiveType::U32) => "uint",
678        TypeRef::Primitive(PrimitiveType::U64) => "ulong",
679        TypeRef::Primitive(PrimitiveType::I8) => "sbyte",
680        TypeRef::Primitive(PrimitiveType::I16) => "short",
681        TypeRef::Primitive(PrimitiveType::I32) => "int",
682        TypeRef::Primitive(PrimitiveType::I64) => "long",
683        TypeRef::Primitive(PrimitiveType::F32) => "float",
684        TypeRef::Primitive(PrimitiveType::F64) => "double",
685        TypeRef::Primitive(PrimitiveType::Usize) => "ulong",
686        TypeRef::Primitive(PrimitiveType::Isize) => "long",
687        TypeRef::Duration => "ulong",
688    }
689}
690
691/// Returns true if a parameter should be hidden from the public API because it is a
692/// trait-bridge param (e.g. the FFI visitor handle).
693pub(super) fn is_bridge_param(
694    param: &alef_core::ir::ParamDef,
695    bridge_param_names: &HashSet<String>,
696    bridge_type_aliases: &HashSet<String>,
697) -> bool {
698    bridge_param_names.contains(&param.name)
699        || matches!(&param.ty, alef_core::ir::TypeRef::Named(n) if bridge_type_aliases.contains(n))
700}
701
702/// Does the return type need IntPtr→string marshalling in the wrapper?
703pub(super) fn returns_string(ty: &TypeRef) -> bool {
704    matches!(ty, TypeRef::String | TypeRef::Char | TypeRef::Path | TypeRef::Json)
705}
706
707/// Does the return type come back as a C int that should be converted to bool?
708pub(super) fn returns_bool_via_int(ty: &TypeRef) -> bool {
709    matches!(ty, TypeRef::Primitive(PrimitiveType::Bool))
710}
711
712/// Does the return type need JSON deserialization from an IntPtr string?
713pub(super) fn returns_json_object(ty: &TypeRef) -> bool {
714    matches!(
715        ty,
716        TypeRef::Vec(_) | TypeRef::Map(_, _) | TypeRef::Named(_) | TypeRef::Bytes | TypeRef::Optional(_)
717    )
718}
719
720/// Returns true if the FFI return type is a pointer (IntPtr), as opposed to a numeric value.
721/// Only pointer-returning functions use `IntPtr.Zero` as an error sentinel.
722pub(super) fn returns_ptr(ty: &TypeRef) -> bool {
723    matches!(
724        ty,
725        TypeRef::String
726            | TypeRef::Char
727            | TypeRef::Path
728            | TypeRef::Json
729            | TypeRef::Named(_)
730            | TypeRef::Vec(_)
731            | TypeRef::Map(_, _)
732            | TypeRef::Bytes
733            | TypeRef::Optional(_)
734    )
735}
736
737/// Returns the argument expression to pass to the native method for a given parameter.
738///
739/// For truly opaque types (is_opaque = true), the C# class wraps an IntPtr; pass `.Handle`.
740/// For data-struct `Named` types this is the handle variable (e.g. `optionsHandle`).
741/// For everything else it is the parameter name (with `!` for optional).
742pub(super) fn native_call_arg(
743    ty: &TypeRef,
744    param_name: &str,
745    optional: bool,
746    true_opaque_types: &HashSet<String>,
747) -> String {
748    match ty {
749        TypeRef::Named(type_name) if true_opaque_types.contains(type_name) => {
750            // Truly opaque: unwrap the IntPtr from the C# handle class.
751            let bang = if optional { "!" } else { "" };
752            format!("{param_name}{bang}.Handle")
753        }
754        TypeRef::Named(_) | TypeRef::Vec(_) | TypeRef::Map(_, _) => {
755            format!("{param_name}Handle")
756        }
757        TypeRef::Bytes => {
758            format!("{param_name}Handle.AddrOfPinnedObject()")
759        }
760        TypeRef::Primitive(alef_core::ir::PrimitiveType::Bool) => {
761            // FFI convention: bool marshalled as int (0 = false, non-zero = true)
762            if optional {
763                format!("({param_name}?.Value ? 1 : 0)")
764            } else {
765                format!("({param_name} ? 1 : 0)")
766            }
767        }
768        ty => {
769            if optional {
770                // For optional primitive types (e.g. ulong?, uint?), pass the FFI's
771                // None sentinel when the value is null. The FFI shim decodes
772                // `{prim}::MAX` (and NAN for floats) as None — passing 0 collides with
773                // a legitimate zero from the caller, e.g. timeout_secs=0 = "no timeout"
774                // would be silently treated as "unset" without this. Mirrors the
775                // `alef-backend-ffi` `param_optional_numeric_conversion` decoder.
776                // String/Char/Path/Json are reference types so `!` is correct for those.
777                if let TypeRef::Primitive(prim) = ty {
778                    use alef_core::ir::PrimitiveType;
779                    let sentinel = match prim {
780                        PrimitiveType::U8 => "byte.MaxValue",
781                        PrimitiveType::U16 => "ushort.MaxValue",
782                        PrimitiveType::U32 => "uint.MaxValue",
783                        PrimitiveType::U64 | PrimitiveType::Usize => "ulong.MaxValue",
784                        PrimitiveType::I8 => "sbyte.MaxValue",
785                        PrimitiveType::I16 => "short.MaxValue",
786                        PrimitiveType::I32 => "int.MaxValue",
787                        PrimitiveType::I64 | PrimitiveType::Isize => "long.MaxValue",
788                        PrimitiveType::F32 => "float.NaN",
789                        PrimitiveType::F64 => "double.NaN",
790                        PrimitiveType::Bool => unreachable!("handled above"),
791                    };
792                    format!("{param_name} ?? {sentinel}")
793                } else if matches!(ty, TypeRef::Duration) {
794                    format!("{param_name}.GetValueOrDefault()")
795                } else {
796                    format!("{param_name}!")
797                }
798            } else {
799                param_name.to_string()
800            }
801        }
802    }
803}
804
805/// For each `Named` parameter, emit code to serialise it to JSON and obtain a native handle.
806///
807/// For truly opaque types (is_opaque = true), the C# class already wraps the native handle, so
808/// we pass `param.Handle` directly without any JSON serialisation.
809pub(super) fn emit_named_param_setup(
810    out: &mut String,
811    params: &[alef_core::ir::ParamDef],
812    indent: &str,
813    true_opaque_types: &HashSet<String>,
814    exception_name: &str,
815) {
816    for param in params {
817        let param_name = param.name.to_lower_camel_case();
818        let json_var = format!("{param_name}Json");
819        let handle_var = format!("{param_name}Handle");
820
821        match &param.ty {
822            TypeRef::Named(type_name) => {
823                // Truly opaque handles: the C# wrapper class holds the IntPtr directly.
824                // No from_json round-trip needed — pass .Handle directly in native_call_arg.
825                if true_opaque_types.contains(type_name) {
826                    continue;
827                }
828                let from_json_method = format!("{}FromJson", type_name.to_pascal_case());
829
830                // Config parameters: always treat as optional and default null to new instance
831                let is_config_param = param.name == "config";
832                let param_to_serialize = if is_config_param {
833                    let type_pascal = type_name.to_pascal_case();
834                    format!("({} ?? new {}())", param_name, type_pascal)
835                } else {
836                    param_name.to_string()
837                };
838
839                if param.optional && !is_config_param {
840                    // Optional Named param: pass IntPtr.Zero through to native when the
841                    // C# arg is null instead of round-tripping `"null"` through FromJson
842                    // which would error with "invalid type: null, expected struct T".
843                    out.push_str(&crate::template_env::render(
844                        "named_param_handle_from_json_optional.jinja",
845                        minijinja::context! {
846                            indent,
847                            handle_var => &handle_var,
848                            from_json_method => &from_json_method,
849                            json_var => &json_var,
850                            param_name => &param_name,
851                            exception_name => exception_name,
852                        },
853                    ));
854                } else {
855                    out.push_str(&crate::template_env::render(
856                        "named_param_json_serialize.jinja",
857                        minijinja::context! { indent, json_var => &json_var, param_name => &param_to_serialize },
858                    ));
859                    out.push_str(&crate::template_env::render(
860                        "named_param_handle_from_json.jinja",
861                        minijinja::context! {
862                            indent,
863                            handle_var => &handle_var,
864                            from_json_method => &from_json_method,
865                            json_var => &json_var,
866                            exception_name => exception_name,
867                        },
868                    ));
869                }
870            }
871            TypeRef::Vec(_) | TypeRef::Map(_, _) => {
872                // Vec/Map: serialize to JSON string, marshal to native pointer
873                out.push_str(&crate::template_env::render(
874                    "named_param_json_serialize.jinja",
875                    minijinja::context! { indent, json_var => &json_var, param_name => &param_name },
876                ));
877                out.push_str(&crate::template_env::render(
878                    "named_param_handle_string.jinja",
879                    minijinja::context! { indent, handle_var => &handle_var, json_var => &json_var },
880                ));
881            }
882            TypeRef::Bytes => {
883                // byte[]: pin the managed array and pass pointer to native
884                out.push_str(&crate::template_env::render(
885                    "named_param_handle_pin.jinja",
886                    minijinja::context! { indent, handle_var => &handle_var, param_name => &param_name },
887                ));
888            }
889            _ => {}
890        }
891    }
892}
893
894/// Emit cleanup code to free native handles allocated for `Named` parameters.
895///
896/// Truly opaque handles (is_opaque = true) are NOT freed here — their lifetime is managed by
897/// the C# wrapper class (IDisposable). Only data-struct handles (from_json-allocated) are freed.
898pub(super) fn emit_named_param_teardown(
899    out: &mut String,
900    params: &[alef_core::ir::ParamDef],
901    true_opaque_types: &HashSet<String>,
902) {
903    for param in params {
904        let param_name = param.name.to_lower_camel_case();
905        let handle_var = format!("{param_name}Handle");
906        match &param.ty {
907            TypeRef::Named(type_name) => {
908                if true_opaque_types.contains(type_name) {
909                    // Caller owns the opaque handle — do not free it here.
910                    continue;
911                }
912                let free_method = format!("{}Free", type_name.to_pascal_case());
913                out.push_str(&crate::template_env::render(
914                    "named_param_teardown_free.jinja",
915                    minijinja::context! { indent => "        ", free_method => &free_method, handle_var => &handle_var },
916                ));
917            }
918            TypeRef::Vec(_) | TypeRef::Map(_, _) => {
919                out.push_str(&crate::template_env::render(
920                    "named_param_teardown_hglobal.jinja",
921                    minijinja::context! { indent => "        ", handle_var => &handle_var },
922                ));
923            }
924            TypeRef::Bytes => {
925                out.push_str(&crate::template_env::render(
926                    "named_param_teardown_gchandle.jinja",
927                    minijinja::context! { indent => "        ", handle_var => &handle_var },
928                ));
929            }
930            _ => {}
931        }
932    }
933}
934
935/// Emit cleanup code with configurable indentation (used inside `Task.Run` lambdas).
936pub(super) fn emit_named_param_teardown_indented(
937    out: &mut String,
938    params: &[alef_core::ir::ParamDef],
939    indent: &str,
940    true_opaque_types: &HashSet<String>,
941) {
942    for param in params {
943        let param_name = param.name.to_lower_camel_case();
944        let handle_var = format!("{param_name}Handle");
945        match &param.ty {
946            TypeRef::Named(type_name) => {
947                if true_opaque_types.contains(type_name) {
948                    // Caller owns the opaque handle — do not free it here.
949                    continue;
950                }
951                let free_method = format!("{}Free", type_name.to_pascal_case());
952                out.push_str(&crate::template_env::render(
953                    "named_param_teardown_free.jinja",
954                    minijinja::context! { indent, free_method => &free_method, handle_var => &handle_var },
955                ));
956            }
957            TypeRef::Vec(_) | TypeRef::Map(_, _) => {
958                out.push_str(&crate::template_env::render(
959                    "named_param_teardown_hglobal.jinja",
960                    minijinja::context! { indent, handle_var => &handle_var },
961                ));
962            }
963            TypeRef::Bytes => {
964                out.push_str(&crate::template_env::render(
965                    "named_param_teardown_gchandle.jinja",
966                    minijinja::context! { indent, handle_var => &handle_var },
967                ));
968            }
969            _ => {}
970        }
971    }
972}
973
974use heck::ToLowerCamelCase;