1use alef_core::backend::{Backend, BuildConfig, BuildDependency, Capabilities, GeneratedFile};
2use alef_core::config::{AdapterPattern, Language, ResolvedCrateConfig, resolve_output_dir};
3use alef_core::hash::{self, CommentStyle};
4use alef_core::ir::{ApiSurface, FieldDef, TypeRef};
5use heck::ToPascalCase;
6use std::collections::{HashMap, HashSet};
7use std::path::PathBuf;
8
9#[derive(Debug, Clone)]
13pub(super) struct StreamingMethodMeta {
14 #[allow(dead_code)]
17 pub owner_type: String,
18 pub item_type: String,
19}
20
21pub(super) mod enums;
22pub(super) mod errors;
23pub(super) mod functions;
24pub(super) mod methods;
25pub(super) mod types;
26
27pub struct CsharpBackend;
28
29impl CsharpBackend {
30 }
32
33impl Backend for CsharpBackend {
34 fn name(&self) -> &str {
35 "csharp"
36 }
37
38 fn language(&self) -> Language {
39 Language::Csharp
40 }
41
42 fn capabilities(&self) -> Capabilities {
43 Capabilities {
44 supports_async: true,
45 supports_classes: true,
46 supports_enums: true,
47 supports_option: true,
48 supports_result: true,
49 ..Capabilities::default()
50 }
51 }
52
53 fn generate_bindings(&self, api: &ApiSurface, config: &ResolvedCrateConfig) -> anyhow::Result<Vec<GeneratedFile>> {
54 let namespace = config.csharp_namespace();
55 let prefix = config.ffi_prefix();
56 let lib_name = config.ffi_lib_name();
57
58 let bridge_param_names: HashSet<String> = config
61 .trait_bridges
62 .iter()
63 .filter_map(|b| b.param_name.clone())
64 .collect();
65 let bridge_type_aliases: HashSet<String> = config
66 .trait_bridges
67 .iter()
68 .filter_map(|b| b.type_alias.clone())
69 .collect();
70 let has_visitor_callbacks = config.ffi.as_ref().map(|f| f.visitor_callbacks).unwrap_or(false);
72
73 let streaming_methods: HashSet<String> = config
78 .adapters
79 .iter()
80 .filter(|a| matches!(a.pattern, AdapterPattern::Streaming))
81 .map(|a| a.name.clone())
82 .collect();
83 let streaming_methods_meta: HashMap<String, StreamingMethodMeta> = config
84 .adapters
85 .iter()
86 .filter(|a| matches!(a.pattern, AdapterPattern::Streaming))
87 .filter_map(|a| {
88 let owner_type = a.owner_type.clone()?;
89 let item_type = a.item_type.clone()?;
90 Some((a.name.clone(), StreamingMethodMeta { owner_type, item_type }))
91 })
92 .collect();
93
94 let exclude_functions: HashSet<String> = config
96 .csharp
97 .as_ref()
98 .map(|c| c.exclude_functions.iter().cloned().collect())
99 .unwrap_or_default();
100
101 let output_dir = resolve_output_dir(config.output_paths.get("csharp"), &config.name, "packages/csharp/");
102
103 let base_path = PathBuf::from(&output_dir).join(namespace.replace('.', "/"));
104
105 let mut files = Vec::new();
106
107 let exception_class_name = format!("{}Exception", api.crate_name.to_pascal_case());
109
110 files.push(GeneratedFile {
112 path: base_path.join("NativeMethods.cs"),
113 content: strip_trailing_whitespace(&functions::gen_native_methods(
114 api,
115 &namespace,
116 &lib_name,
117 &prefix,
118 &bridge_param_names,
119 &bridge_type_aliases,
120 has_visitor_callbacks,
121 &config.trait_bridges,
122 &streaming_methods,
123 &streaming_methods_meta,
124 &exclude_functions,
125 )),
126 generated_header: true,
127 });
128
129 if !api.errors.is_empty() {
131 for error in &api.errors {
132 let error_files =
133 alef_codegen::error_gen::gen_csharp_error_types(error, &namespace, Some(&exception_class_name));
134 for (class_name, content) in error_files {
135 files.push(GeneratedFile {
136 path: base_path.join(format!("{}.cs", class_name)),
137 content: strip_trailing_whitespace(&content),
138 generated_header: false, });
140 }
141 }
142 }
143
144 if api.errors.is_empty()
146 || !api
147 .errors
148 .iter()
149 .any(|e| format!("{}Exception", e.name) == exception_class_name)
150 {
151 files.push(GeneratedFile {
152 path: base_path.join(format!("{}.cs", exception_class_name)),
153 content: strip_trailing_whitespace(&errors::gen_exception_class(&namespace, &exception_class_name)),
154 generated_header: true,
155 });
156 }
157
158 let base_class_name = api.crate_name.to_pascal_case();
160 let wrapper_class_name = if namespace == base_class_name {
161 format!("{}Lib", base_class_name)
162 } else {
163 base_class_name
164 };
165 files.push(GeneratedFile {
166 path: base_path.join(format!("{}.cs", wrapper_class_name)),
167 content: strip_trailing_whitespace(&methods::gen_wrapper_class(
168 api,
169 &namespace,
170 &wrapper_class_name,
171 &exception_class_name,
172 &prefix,
173 &bridge_param_names,
174 &bridge_type_aliases,
175 has_visitor_callbacks,
176 &streaming_methods,
177 &streaming_methods_meta,
178 &exclude_functions,
179 )),
180 generated_header: true,
181 });
182
183 if has_visitor_callbacks {
185 for (filename, content) in crate::gen_visitor::gen_visitor_files(&namespace) {
186 files.push(GeneratedFile {
187 path: base_path.join(filename),
188 content: strip_trailing_whitespace(&content),
189 generated_header: true,
190 });
191 }
192 delete_superseded_visitor_files(&base_path)?;
196 } else {
197 delete_stale_visitor_files(&base_path)?;
200 }
201
202 if !config.trait_bridges.is_empty() {
204 let trait_defs: Vec<_> = api.types.iter().filter(|t| t.is_trait).collect();
205 let bridges: Vec<_> = config
206 .trait_bridges
207 .iter()
208 .filter_map(|cfg| {
209 let trait_name = cfg.trait_name.clone();
210 trait_defs
211 .iter()
212 .find(|t| t.name == trait_name)
213 .map(|trait_def| (trait_name, cfg, *trait_def))
214 })
215 .collect();
216
217 if !bridges.is_empty() {
218 let (filename, content) = crate::trait_bridge::gen_trait_bridges_file(&namespace, &prefix, &bridges);
219 files.push(GeneratedFile {
220 path: base_path.join(filename),
221 content: strip_trailing_whitespace(&content),
222 generated_header: true,
223 });
224 }
225 }
226
227 let enum_names: HashSet<String> = api.enums.iter().map(|e| e.name.to_pascal_case()).collect();
229
230 let all_opaque_type_names: HashSet<String> = api
233 .types
234 .iter()
235 .filter(|t| t.is_opaque)
236 .map(|t| t.name.to_pascal_case())
237 .collect();
238
239 for typ in api.types.iter().filter(|typ| !typ.is_trait) {
241 if typ.is_opaque {
242 let type_filename = typ.name.to_pascal_case();
243 files.push(GeneratedFile {
244 path: base_path.join(format!("{}.cs", type_filename)),
245 content: strip_trailing_whitespace(&types::gen_opaque_handle(
246 typ,
247 &namespace,
248 &exception_class_name,
249 &enum_names,
250 &streaming_methods,
251 &streaming_methods_meta,
252 &all_opaque_type_names,
253 )),
254 generated_header: true,
255 });
256 }
257 }
258
259 let complex_enums: HashSet<String> = HashSet::new();
263
264 let custom_converter_enums: HashSet<String> = api
270 .enums
271 .iter()
272 .filter(|e| {
273 let is_tagged_union = e.serde_tag.is_some() && e.variants.iter().any(|v| !v.fields.is_empty());
275 if is_tagged_union {
276 return false;
277 }
278 e.variants.iter().any(|v| {
280 if let Some(ref rename) = v.serde_rename {
281 let snake = enums::apply_rename_all(&v.name, e.serde_rename_all.as_deref());
282 rename != &snake
283 } else {
284 false
285 }
286 })
287 })
288 .map(|e| e.name.to_pascal_case())
289 .collect();
290
291 let lang_rename_all = config.serde_rename_all_for_language(Language::Csharp);
293
294 for typ in api.types.iter().filter(|typ| !typ.is_trait) {
296 if !typ.is_opaque {
297 let has_named_fields = typ.fields.iter().any(|f| !is_tuple_field(f));
300 if !typ.fields.is_empty() && !has_named_fields {
301 continue;
302 }
303 if has_visitor_callbacks && (typ.name == "NodeContext" || typ.name == "VisitResult") {
305 continue;
306 }
307
308 let type_filename = typ.name.to_pascal_case();
309 files.push(GeneratedFile {
310 path: base_path.join(format!("{}.cs", type_filename)),
311 content: strip_trailing_whitespace(&types::gen_record_type(
312 typ,
313 &namespace,
314 &enum_names,
315 &complex_enums,
316 &custom_converter_enums,
317 &lang_rename_all,
318 &bridge_type_aliases,
319 )),
320 generated_header: true,
321 });
322 }
323 }
324
325 for enum_def in &api.enums {
327 if has_visitor_callbacks && (enum_def.name == "VisitResult" || enum_def.name == "NodeContext") {
329 continue;
330 }
331 let enum_filename = enum_def.name.to_pascal_case();
332 files.push(GeneratedFile {
333 path: base_path.join(format!("{}.cs", enum_filename)),
334 content: strip_trailing_whitespace(&enums::gen_enum(enum_def, &namespace)),
335 generated_header: true,
336 });
337 }
338
339 let needs_byte_array_converter = api
342 .types
343 .iter()
344 .any(|t| !t.is_opaque && t.fields.iter().any(|f| !f.optional && matches!(f.ty, TypeRef::Bytes)));
345 if needs_byte_array_converter {
346 files.push(GeneratedFile {
347 path: base_path.join("ByteArrayToIntArrayConverter.cs"),
348 content: types::gen_byte_array_to_int_array_converter(&namespace),
349 generated_header: true,
350 });
351 }
352
353 let _adapter_bodies = alef_adapters::build_adapter_bodies(config, Language::Csharp)?;
355
356 files.push(GeneratedFile {
360 path: PathBuf::from("packages/csharp/Directory.Build.props"),
361 content: gen_directory_build_props(),
362 generated_header: true,
363 });
364
365 Ok(files)
366 }
367
368 fn generate_public_api(
373 &self,
374 _api: &ApiSurface,
375 _config: &ResolvedCrateConfig,
376 ) -> anyhow::Result<Vec<GeneratedFile>> {
377 Ok(vec![])
379 }
380
381 fn build_config(&self) -> Option<BuildConfig> {
382 Some(BuildConfig {
383 tool: "dotnet",
384 crate_suffix: "",
385 build_dep: BuildDependency::Ffi,
386 post_build: vec![],
387 })
388 }
389}
390
391pub(super) fn is_tuple_field(field: &FieldDef) -> bool {
393 (field.name.starts_with('_') && field.name[1..].chars().all(|c| c.is_ascii_digit()))
394 || field.name.chars().next().is_none_or(|c| c.is_ascii_digit())
395}
396
397pub(super) fn strip_trailing_whitespace(content: &str) -> String {
399 let mut result: String = content
400 .lines()
401 .map(|line| line.trim_end())
402 .collect::<Vec<_>>()
403 .join("\n");
404 if !result.ends_with('\n') {
405 result.push('\n');
406 }
407 result
408}
409
410pub(super) fn csharp_file_header() -> String {
412 let mut out = hash::header(CommentStyle::DoubleSlash);
413 out.push_str("#nullable enable\n\n");
414 out
415}
416
417fn gen_directory_build_props() -> String {
420 "<!-- auto-generated by alef (generate_bindings) -->\n\
421<Project>\n \
422<PropertyGroup>\n \
423<Nullable>enable</Nullable>\n \
424<LangVersion>latest</LangVersion>\n \
425<TreatWarningsAsErrors>true</TreatWarningsAsErrors>\n \
426</PropertyGroup>\n\
427</Project>\n"
428 .to_string()
429}
430
431fn delete_superseded_visitor_files(base_path: &std::path::Path) -> anyhow::Result<()> {
436 let superseded = ["IVisitor.cs", "VisitorCallbacks.cs"];
437 for filename in superseded {
438 let path = base_path.join(filename);
439 if path.exists() {
440 std::fs::remove_file(&path)
441 .map_err(|e| anyhow::anyhow!("Failed to delete superseded visitor file {}: {}", path.display(), e))?;
442 }
443 }
444 Ok(())
445}
446
447fn delete_stale_visitor_files(base_path: &std::path::Path) -> anyhow::Result<()> {
451 let stale_files = vec!["IVisitor.cs", "VisitorCallbacks.cs", "NodeContext.cs", "VisitResult.cs"];
452
453 for filename in stale_files {
454 let path = base_path.join(filename);
455 if path.exists() {
456 std::fs::remove_file(&path)
457 .map_err(|e| anyhow::anyhow!("Failed to delete stale visitor file {}: {}", path.display(), e))?;
458 }
459 }
460
461 Ok(())
462}
463
464use alef_core::ir::PrimitiveType;
469
470pub(super) fn pinvoke_return_type(ty: &TypeRef) -> &'static str {
477 match ty {
478 TypeRef::Unit => "void",
479 TypeRef::Primitive(PrimitiveType::Bool) => "int",
481 TypeRef::Primitive(PrimitiveType::U8) => "byte",
483 TypeRef::Primitive(PrimitiveType::U16) => "ushort",
484 TypeRef::Primitive(PrimitiveType::U32) => "uint",
485 TypeRef::Primitive(PrimitiveType::U64) => "ulong",
486 TypeRef::Primitive(PrimitiveType::I8) => "sbyte",
487 TypeRef::Primitive(PrimitiveType::I16) => "short",
488 TypeRef::Primitive(PrimitiveType::I32) => "int",
489 TypeRef::Primitive(PrimitiveType::I64) => "long",
490 TypeRef::Primitive(PrimitiveType::F32) => "float",
491 TypeRef::Primitive(PrimitiveType::F64) => "double",
492 TypeRef::Primitive(PrimitiveType::Usize) => "ulong",
493 TypeRef::Primitive(PrimitiveType::Isize) => "long",
494 TypeRef::Duration => "ulong",
496 TypeRef::String
498 | TypeRef::Char
499 | TypeRef::Bytes
500 | TypeRef::Optional(_)
501 | TypeRef::Vec(_)
502 | TypeRef::Map(_, _)
503 | TypeRef::Named(_)
504 | TypeRef::Path
505 | TypeRef::Json => "IntPtr",
506 }
507}
508
509pub(super) fn pinvoke_param_type(ty: &TypeRef) -> &'static str {
516 match ty {
517 TypeRef::String | TypeRef::Char | TypeRef::Path | TypeRef::Json => "string",
518 TypeRef::Named(_) | TypeRef::Vec(_) | TypeRef::Map(_, _) | TypeRef::Bytes | TypeRef::Optional(_) => "IntPtr",
520 TypeRef::Unit => "void",
521 TypeRef::Primitive(PrimitiveType::Bool) => "int",
522 TypeRef::Primitive(PrimitiveType::U8) => "byte",
523 TypeRef::Primitive(PrimitiveType::U16) => "ushort",
524 TypeRef::Primitive(PrimitiveType::U32) => "uint",
525 TypeRef::Primitive(PrimitiveType::U64) => "ulong",
526 TypeRef::Primitive(PrimitiveType::I8) => "sbyte",
527 TypeRef::Primitive(PrimitiveType::I16) => "short",
528 TypeRef::Primitive(PrimitiveType::I32) => "int",
529 TypeRef::Primitive(PrimitiveType::I64) => "long",
530 TypeRef::Primitive(PrimitiveType::F32) => "float",
531 TypeRef::Primitive(PrimitiveType::F64) => "double",
532 TypeRef::Primitive(PrimitiveType::Usize) => "ulong",
533 TypeRef::Primitive(PrimitiveType::Isize) => "long",
534 TypeRef::Duration => "ulong",
535 }
536}
537
538pub(super) fn is_bridge_param(
541 param: &alef_core::ir::ParamDef,
542 bridge_param_names: &HashSet<String>,
543 bridge_type_aliases: &HashSet<String>,
544) -> bool {
545 bridge_param_names.contains(¶m.name)
546 || matches!(¶m.ty, alef_core::ir::TypeRef::Named(n) if bridge_type_aliases.contains(n))
547}
548
549pub(super) fn returns_string(ty: &TypeRef) -> bool {
551 matches!(ty, TypeRef::String | TypeRef::Char | TypeRef::Path | TypeRef::Json)
552}
553
554pub(super) fn returns_bool_via_int(ty: &TypeRef) -> bool {
556 matches!(ty, TypeRef::Primitive(PrimitiveType::Bool))
557}
558
559pub(super) fn returns_json_object(ty: &TypeRef) -> bool {
561 matches!(
562 ty,
563 TypeRef::Vec(_) | TypeRef::Map(_, _) | TypeRef::Named(_) | TypeRef::Bytes | TypeRef::Optional(_)
564 )
565}
566
567pub(super) fn returns_ptr(ty: &TypeRef) -> bool {
570 matches!(
571 ty,
572 TypeRef::String
573 | TypeRef::Char
574 | TypeRef::Path
575 | TypeRef::Json
576 | TypeRef::Named(_)
577 | TypeRef::Vec(_)
578 | TypeRef::Map(_, _)
579 | TypeRef::Bytes
580 | TypeRef::Optional(_)
581 )
582}
583
584pub(super) fn native_call_arg(
590 ty: &TypeRef,
591 param_name: &str,
592 optional: bool,
593 true_opaque_types: &HashSet<String>,
594) -> String {
595 match ty {
596 TypeRef::Named(type_name) if true_opaque_types.contains(type_name) => {
597 let bang = if optional { "!" } else { "" };
599 format!("{param_name}{bang}.Handle")
600 }
601 TypeRef::Named(_) | TypeRef::Vec(_) | TypeRef::Map(_, _) => {
602 format!("{param_name}Handle")
603 }
604 TypeRef::Bytes => {
605 format!("{param_name}Handle.AddrOfPinnedObject()")
606 }
607 TypeRef::Primitive(alef_core::ir::PrimitiveType::Bool) => {
608 if optional {
610 format!("({param_name}?.Value ? 1 : 0)")
611 } else {
612 format!("({param_name} ? 1 : 0)")
613 }
614 }
615 ty => {
616 if optional {
617 let needs_value_unwrap = matches!(ty, TypeRef::Primitive(_) | TypeRef::Duration);
621 if needs_value_unwrap {
622 format!("{param_name}.GetValueOrDefault()")
623 } else {
624 format!("{param_name}!")
625 }
626 } else {
627 param_name.to_string()
628 }
629 }
630 }
631}
632
633pub(super) fn emit_named_param_setup(
638 out: &mut String,
639 params: &[alef_core::ir::ParamDef],
640 indent: &str,
641 true_opaque_types: &HashSet<String>,
642 exception_name: &str,
643) {
644 for param in params {
645 let param_name = param.name.to_lower_camel_case();
646 let json_var = format!("{param_name}Json");
647 let handle_var = format!("{param_name}Handle");
648
649 match ¶m.ty {
650 TypeRef::Named(type_name) => {
651 if true_opaque_types.contains(type_name) {
654 continue;
655 }
656 let from_json_method = format!("{}FromJson", type_name.to_pascal_case());
657
658 let is_config_param = param.name == "config";
660 let param_to_serialize = if is_config_param {
661 let type_pascal = type_name.to_pascal_case();
662 format!("({} ?? new {}())", param_name, type_pascal)
663 } else {
664 param_name.to_string()
665 };
666
667 if param.optional && !is_config_param {
668 out.push_str(&crate::template_env::render(
672 "named_param_handle_from_json_optional.jinja",
673 minijinja::context! {
674 indent,
675 handle_var => &handle_var,
676 from_json_method => &from_json_method,
677 json_var => &json_var,
678 param_name => ¶m_name,
679 exception_name => exception_name,
680 },
681 ));
682 } else {
683 out.push_str(&crate::template_env::render(
684 "named_param_json_serialize.jinja",
685 minijinja::context! { indent, json_var => &json_var, param_name => ¶m_to_serialize },
686 ));
687 out.push_str(&crate::template_env::render(
688 "named_param_handle_from_json.jinja",
689 minijinja::context! {
690 indent,
691 handle_var => &handle_var,
692 from_json_method => &from_json_method,
693 json_var => &json_var,
694 exception_name => exception_name,
695 },
696 ));
697 }
698 }
699 TypeRef::Vec(_) | TypeRef::Map(_, _) => {
700 out.push_str(&crate::template_env::render(
702 "named_param_json_serialize.jinja",
703 minijinja::context! { indent, json_var => &json_var, param_name => ¶m_name },
704 ));
705 out.push_str(&crate::template_env::render(
706 "named_param_handle_string.jinja",
707 minijinja::context! { indent, handle_var => &handle_var, json_var => &json_var },
708 ));
709 }
710 TypeRef::Bytes => {
711 out.push_str(&crate::template_env::render(
713 "named_param_handle_pin.jinja",
714 minijinja::context! { indent, handle_var => &handle_var, param_name => ¶m_name },
715 ));
716 }
717 _ => {}
718 }
719 }
720}
721
722pub(super) fn emit_named_param_teardown(
727 out: &mut String,
728 params: &[alef_core::ir::ParamDef],
729 true_opaque_types: &HashSet<String>,
730) {
731 for param in params {
732 let param_name = param.name.to_lower_camel_case();
733 let handle_var = format!("{param_name}Handle");
734 match ¶m.ty {
735 TypeRef::Named(type_name) => {
736 if true_opaque_types.contains(type_name) {
737 continue;
739 }
740 let free_method = format!("{}Free", type_name.to_pascal_case());
741 out.push_str(&crate::template_env::render(
742 "named_param_teardown_free.jinja",
743 minijinja::context! { indent => " ", free_method => &free_method, handle_var => &handle_var },
744 ));
745 }
746 TypeRef::Vec(_) | TypeRef::Map(_, _) => {
747 out.push_str(&crate::template_env::render(
748 "named_param_teardown_hglobal.jinja",
749 minijinja::context! { indent => " ", handle_var => &handle_var },
750 ));
751 }
752 TypeRef::Bytes => {
753 out.push_str(&crate::template_env::render(
754 "named_param_teardown_gchandle.jinja",
755 minijinja::context! { indent => " ", handle_var => &handle_var },
756 ));
757 }
758 _ => {}
759 }
760 }
761}
762
763pub(super) fn emit_named_param_teardown_indented(
765 out: &mut String,
766 params: &[alef_core::ir::ParamDef],
767 indent: &str,
768 true_opaque_types: &HashSet<String>,
769) {
770 for param in params {
771 let param_name = param.name.to_lower_camel_case();
772 let handle_var = format!("{param_name}Handle");
773 match ¶m.ty {
774 TypeRef::Named(type_name) => {
775 if true_opaque_types.contains(type_name) {
776 continue;
778 }
779 let free_method = format!("{}Free", type_name.to_pascal_case());
780 out.push_str(&crate::template_env::render(
781 "named_param_teardown_free.jinja",
782 minijinja::context! { indent, free_method => &free_method, handle_var => &handle_var },
783 ));
784 }
785 TypeRef::Vec(_) | TypeRef::Map(_, _) => {
786 out.push_str(&crate::template_env::render(
787 "named_param_teardown_hglobal.jinja",
788 minijinja::context! { indent, handle_var => &handle_var },
789 ));
790 }
791 TypeRef::Bytes => {
792 out.push_str(&crate::template_env::render(
793 "named_param_teardown_gchandle.jinja",
794 minijinja::context! { indent, handle_var => &handle_var },
795 ));
796 }
797 _ => {}
798 }
799 }
800}
801
802use heck::ToLowerCamelCase;