Skip to main content

alef_backend_csharp/gen_bindings/
mod.rs

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