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