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