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> = api
266 .enums
267 .iter()
268 .filter(|e| e.serde_untagged && e.variants.iter().any(|v| !v.fields.is_empty()))
269 .map(|e| e.name.to_pascal_case())
270 .collect();
271
272 let custom_converter_enums: HashSet<String> = api
278 .enums
279 .iter()
280 .filter(|e| {
281 let is_tagged_union = e.serde_tag.is_some() && e.variants.iter().any(|v| !v.fields.is_empty());
283 if is_tagged_union {
284 return false;
285 }
286 e.variants.iter().any(|v| {
288 if let Some(ref rename) = v.serde_rename {
289 let snake = enums::apply_rename_all(&v.name, e.serde_rename_all.as_deref());
290 rename != &snake
291 } else {
292 false
293 }
294 })
295 })
296 .map(|e| e.name.to_pascal_case())
297 .collect();
298
299 let lang_rename_all = config.serde_rename_all_for_language(Language::Csharp);
301
302 for typ in api.types.iter().filter(|typ| !typ.is_trait) {
304 if !typ.is_opaque {
305 let has_named_fields = typ.fields.iter().any(|f| !is_tuple_field(f));
308 if !typ.fields.is_empty() && !has_named_fields {
309 continue;
310 }
311 if has_visitor_callbacks && (typ.name == "NodeContext" || typ.name == "VisitResult") {
313 continue;
314 }
315
316 let type_filename = typ.name.to_pascal_case();
317 files.push(GeneratedFile {
318 path: base_path.join(format!("{}.cs", type_filename)),
319 content: strip_trailing_whitespace(&types::gen_record_type(
320 typ,
321 &namespace,
322 &enum_names,
323 &complex_enums,
324 &custom_converter_enums,
325 &lang_rename_all,
326 &bridge_type_aliases,
327 )),
328 generated_header: true,
329 });
330 }
331 }
332
333 for enum_def in &api.enums {
335 if has_visitor_callbacks && (enum_def.name == "VisitResult" || enum_def.name == "NodeContext") {
337 continue;
338 }
339 let enum_filename = enum_def.name.to_pascal_case();
340 files.push(GeneratedFile {
341 path: base_path.join(format!("{}.cs", enum_filename)),
342 content: strip_trailing_whitespace(&enums::gen_enum(enum_def, &namespace)),
343 generated_header: true,
344 });
345 }
346
347 let needs_byte_array_converter = api
350 .types
351 .iter()
352 .any(|t| !t.is_opaque && t.fields.iter().any(|f| !f.optional && matches!(f.ty, TypeRef::Bytes)));
353 if needs_byte_array_converter {
354 files.push(GeneratedFile {
355 path: base_path.join("ByteArrayToIntArrayConverter.cs"),
356 content: types::gen_byte_array_to_int_array_converter(&namespace),
357 generated_header: true,
358 });
359 }
360
361 let _adapter_bodies = alef_adapters::build_adapter_bodies(config, Language::Csharp)?;
363
364 files.push(GeneratedFile {
368 path: PathBuf::from("packages/csharp/Directory.Build.props"),
369 content: gen_directory_build_props(),
370 generated_header: true,
371 });
372
373 Ok(files)
374 }
375
376 fn generate_public_api(
381 &self,
382 _api: &ApiSurface,
383 _config: &ResolvedCrateConfig,
384 ) -> anyhow::Result<Vec<GeneratedFile>> {
385 Ok(vec![])
387 }
388
389 fn build_config(&self) -> Option<BuildConfig> {
390 Some(BuildConfig {
391 tool: "dotnet",
392 crate_suffix: "",
393 build_dep: BuildDependency::Ffi,
394 post_build: vec![],
395 })
396 }
397}
398
399pub(super) fn is_tuple_field(field: &FieldDef) -> bool {
401 (field.name.starts_with('_') && field.name[1..].chars().all(|c| c.is_ascii_digit()))
402 || field.name.chars().next().is_none_or(|c| c.is_ascii_digit())
403}
404
405pub(super) fn strip_trailing_whitespace(content: &str) -> String {
407 let mut result: String = content
408 .lines()
409 .map(|line| line.trim_end())
410 .collect::<Vec<_>>()
411 .join("\n");
412 if !result.ends_with('\n') {
413 result.push('\n');
414 }
415 result
416}
417
418pub(super) fn csharp_file_header() -> String {
420 let mut out = hash::header(CommentStyle::DoubleSlash);
421 out.push_str("#nullable enable\n\n");
422 out
423}
424
425fn gen_directory_build_props() -> String {
428 "<!-- auto-generated by alef (generate_bindings) -->\n\
429<Project>\n \
430<PropertyGroup>\n \
431<Nullable>enable</Nullable>\n \
432<LangVersion>latest</LangVersion>\n \
433<TreatWarningsAsErrors>true</TreatWarningsAsErrors>\n \
434</PropertyGroup>\n\
435</Project>\n"
436 .to_string()
437}
438
439fn delete_superseded_visitor_files(base_path: &std::path::Path) -> anyhow::Result<()> {
444 let superseded = ["IVisitor.cs", "VisitorCallbacks.cs"];
445 for filename in superseded {
446 let path = base_path.join(filename);
447 if path.exists() {
448 std::fs::remove_file(&path)
449 .map_err(|e| anyhow::anyhow!("Failed to delete superseded visitor file {}: {}", path.display(), e))?;
450 }
451 }
452 Ok(())
453}
454
455fn delete_stale_visitor_files(base_path: &std::path::Path) -> anyhow::Result<()> {
459 let stale_files = vec!["IVisitor.cs", "VisitorCallbacks.cs", "NodeContext.cs", "VisitResult.cs"];
460
461 for filename in stale_files {
462 let path = base_path.join(filename);
463 if path.exists() {
464 std::fs::remove_file(&path)
465 .map_err(|e| anyhow::anyhow!("Failed to delete stale visitor file {}: {}", path.display(), e))?;
466 }
467 }
468
469 Ok(())
470}
471
472use alef_core::ir::PrimitiveType;
477
478pub(super) fn pinvoke_return_type(ty: &TypeRef) -> &'static str {
485 match ty {
486 TypeRef::Unit => "void",
487 TypeRef::Primitive(PrimitiveType::Bool) => "int",
489 TypeRef::Primitive(PrimitiveType::U8) => "byte",
491 TypeRef::Primitive(PrimitiveType::U16) => "ushort",
492 TypeRef::Primitive(PrimitiveType::U32) => "uint",
493 TypeRef::Primitive(PrimitiveType::U64) => "ulong",
494 TypeRef::Primitive(PrimitiveType::I8) => "sbyte",
495 TypeRef::Primitive(PrimitiveType::I16) => "short",
496 TypeRef::Primitive(PrimitiveType::I32) => "int",
497 TypeRef::Primitive(PrimitiveType::I64) => "long",
498 TypeRef::Primitive(PrimitiveType::F32) => "float",
499 TypeRef::Primitive(PrimitiveType::F64) => "double",
500 TypeRef::Primitive(PrimitiveType::Usize) => "ulong",
501 TypeRef::Primitive(PrimitiveType::Isize) => "long",
502 TypeRef::Duration => "ulong",
504 TypeRef::String
506 | TypeRef::Char
507 | TypeRef::Bytes
508 | TypeRef::Optional(_)
509 | TypeRef::Vec(_)
510 | TypeRef::Map(_, _)
511 | TypeRef::Named(_)
512 | TypeRef::Path
513 | TypeRef::Json => "IntPtr",
514 }
515}
516
517pub(super) fn pinvoke_param_type(ty: &TypeRef) -> &'static str {
524 match ty {
525 TypeRef::String | TypeRef::Char | TypeRef::Path | TypeRef::Json => "string",
526 TypeRef::Named(_) | TypeRef::Vec(_) | TypeRef::Map(_, _) | TypeRef::Bytes | TypeRef::Optional(_) => "IntPtr",
528 TypeRef::Unit => "void",
529 TypeRef::Primitive(PrimitiveType::Bool) => "int",
530 TypeRef::Primitive(PrimitiveType::U8) => "byte",
531 TypeRef::Primitive(PrimitiveType::U16) => "ushort",
532 TypeRef::Primitive(PrimitiveType::U32) => "uint",
533 TypeRef::Primitive(PrimitiveType::U64) => "ulong",
534 TypeRef::Primitive(PrimitiveType::I8) => "sbyte",
535 TypeRef::Primitive(PrimitiveType::I16) => "short",
536 TypeRef::Primitive(PrimitiveType::I32) => "int",
537 TypeRef::Primitive(PrimitiveType::I64) => "long",
538 TypeRef::Primitive(PrimitiveType::F32) => "float",
539 TypeRef::Primitive(PrimitiveType::F64) => "double",
540 TypeRef::Primitive(PrimitiveType::Usize) => "ulong",
541 TypeRef::Primitive(PrimitiveType::Isize) => "long",
542 TypeRef::Duration => "ulong",
543 }
544}
545
546pub(super) fn is_bridge_param(
549 param: &alef_core::ir::ParamDef,
550 bridge_param_names: &HashSet<String>,
551 bridge_type_aliases: &HashSet<String>,
552) -> bool {
553 bridge_param_names.contains(¶m.name)
554 || matches!(¶m.ty, alef_core::ir::TypeRef::Named(n) if bridge_type_aliases.contains(n))
555}
556
557pub(super) fn returns_string(ty: &TypeRef) -> bool {
559 matches!(ty, TypeRef::String | TypeRef::Char | TypeRef::Path | TypeRef::Json)
560}
561
562pub(super) fn returns_bool_via_int(ty: &TypeRef) -> bool {
564 matches!(ty, TypeRef::Primitive(PrimitiveType::Bool))
565}
566
567pub(super) fn returns_json_object(ty: &TypeRef) -> bool {
569 matches!(
570 ty,
571 TypeRef::Vec(_) | TypeRef::Map(_, _) | TypeRef::Named(_) | TypeRef::Bytes | TypeRef::Optional(_)
572 )
573}
574
575pub(super) fn returns_ptr(ty: &TypeRef) -> bool {
578 matches!(
579 ty,
580 TypeRef::String
581 | TypeRef::Char
582 | TypeRef::Path
583 | TypeRef::Json
584 | TypeRef::Named(_)
585 | TypeRef::Vec(_)
586 | TypeRef::Map(_, _)
587 | TypeRef::Bytes
588 | TypeRef::Optional(_)
589 )
590}
591
592pub(super) fn native_call_arg(
598 ty: &TypeRef,
599 param_name: &str,
600 optional: bool,
601 true_opaque_types: &HashSet<String>,
602) -> String {
603 match ty {
604 TypeRef::Named(type_name) if true_opaque_types.contains(type_name) => {
605 let bang = if optional { "!" } else { "" };
607 format!("{param_name}{bang}.Handle")
608 }
609 TypeRef::Named(_) | TypeRef::Vec(_) | TypeRef::Map(_, _) => {
610 format!("{param_name}Handle")
611 }
612 TypeRef::Bytes => {
613 format!("{param_name}Handle.AddrOfPinnedObject()")
614 }
615 TypeRef::Primitive(alef_core::ir::PrimitiveType::Bool) => {
616 if optional {
618 format!("({param_name}?.Value ? 1 : 0)")
619 } else {
620 format!("({param_name} ? 1 : 0)")
621 }
622 }
623 ty => {
624 if optional {
625 let needs_value_unwrap = matches!(ty, TypeRef::Primitive(_) | TypeRef::Duration);
629 if needs_value_unwrap {
630 format!("{param_name}.GetValueOrDefault()")
631 } else {
632 format!("{param_name}!")
633 }
634 } else {
635 param_name.to_string()
636 }
637 }
638 }
639}
640
641pub(super) fn emit_named_param_setup(
646 out: &mut String,
647 params: &[alef_core::ir::ParamDef],
648 indent: &str,
649 true_opaque_types: &HashSet<String>,
650) {
651 for param in params {
652 let param_name = param.name.to_lower_camel_case();
653 let json_var = format!("{param_name}Json");
654 let handle_var = format!("{param_name}Handle");
655
656 match ¶m.ty {
657 TypeRef::Named(type_name) => {
658 if true_opaque_types.contains(type_name) {
661 continue;
662 }
663 let from_json_method = format!("{}FromJson", type_name.to_pascal_case());
664
665 let is_config_param = param.name == "config";
667 let param_to_serialize = if is_config_param {
668 let type_pascal = type_name.to_pascal_case();
669 format!("({} ?? new {}())", param_name, type_pascal)
670 } else {
671 param_name.to_string()
672 };
673
674 if param.optional && !is_config_param {
675 out.push_str(&crate::template_env::render(
676 "named_param_json_optional.jinja",
677 minijinja::context! { indent, json_var => &json_var, param_name => ¶m_name },
678 ));
679 } else {
680 out.push_str(&crate::template_env::render(
681 "named_param_json_serialize.jinja",
682 minijinja::context! { indent, json_var => &json_var, param_name => ¶m_to_serialize },
683 ));
684 }
685 out.push_str(&crate::template_env::render(
686 "named_param_handle_from_json.jinja",
687 minijinja::context! { indent, handle_var => &handle_var, from_json_method => &from_json_method, json_var => &json_var },
688 ));
689 }
690 TypeRef::Vec(_) | TypeRef::Map(_, _) => {
691 out.push_str(&crate::template_env::render(
693 "named_param_json_serialize.jinja",
694 minijinja::context! { indent, json_var => &json_var, param_name => ¶m_name },
695 ));
696 out.push_str(&crate::template_env::render(
697 "named_param_handle_string.jinja",
698 minijinja::context! { indent, handle_var => &handle_var, json_var => &json_var },
699 ));
700 }
701 TypeRef::Bytes => {
702 out.push_str(&crate::template_env::render(
704 "named_param_handle_pin.jinja",
705 minijinja::context! { indent, handle_var => &handle_var, param_name => ¶m_name },
706 ));
707 }
708 _ => {}
709 }
710 }
711}
712
713pub(super) fn emit_named_param_teardown(
718 out: &mut String,
719 params: &[alef_core::ir::ParamDef],
720 true_opaque_types: &HashSet<String>,
721) {
722 for param in params {
723 let param_name = param.name.to_lower_camel_case();
724 let handle_var = format!("{param_name}Handle");
725 match ¶m.ty {
726 TypeRef::Named(type_name) => {
727 if true_opaque_types.contains(type_name) {
728 continue;
730 }
731 let free_method = format!("{}Free", type_name.to_pascal_case());
732 out.push_str(&crate::template_env::render(
733 "named_param_teardown_free.jinja",
734 minijinja::context! { indent => " ", free_method => &free_method, handle_var => &handle_var },
735 ));
736 }
737 TypeRef::Vec(_) | TypeRef::Map(_, _) => {
738 out.push_str(&crate::template_env::render(
739 "named_param_teardown_hglobal.jinja",
740 minijinja::context! { indent => " ", handle_var => &handle_var },
741 ));
742 }
743 TypeRef::Bytes => {
744 out.push_str(&crate::template_env::render(
745 "named_param_teardown_gchandle.jinja",
746 minijinja::context! { indent => " ", handle_var => &handle_var },
747 ));
748 }
749 _ => {}
750 }
751 }
752}
753
754pub(super) fn emit_named_param_teardown_indented(
756 out: &mut String,
757 params: &[alef_core::ir::ParamDef],
758 indent: &str,
759 true_opaque_types: &HashSet<String>,
760) {
761 for param in params {
762 let param_name = param.name.to_lower_camel_case();
763 let handle_var = format!("{param_name}Handle");
764 match ¶m.ty {
765 TypeRef::Named(type_name) => {
766 if true_opaque_types.contains(type_name) {
767 continue;
769 }
770 let free_method = format!("{}Free", type_name.to_pascal_case());
771 out.push_str(&crate::template_env::render(
772 "named_param_teardown_free.jinja",
773 minijinja::context! { indent, free_method => &free_method, handle_var => &handle_var },
774 ));
775 }
776 TypeRef::Vec(_) | TypeRef::Map(_, _) => {
777 out.push_str(&crate::template_env::render(
778 "named_param_teardown_hglobal.jinja",
779 minijinja::context! { indent, handle_var => &handle_var },
780 ));
781 }
782 TypeRef::Bytes => {
783 out.push_str(&crate::template_env::render(
784 "named_param_teardown_gchandle.jinja",
785 minijinja::context! { indent, handle_var => &handle_var },
786 ));
787 }
788 _ => {}
789 }
790 }
791}
792
793use heck::ToLowerCamelCase;