alef 0.63.0

Opinionated polyglot binding generator for Rust libraries
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
use crate::core::config::Language;
use crate::core::ir::{FunctionDef, MethodDef, TypeRef};
use crate::docs::formatting::{IdentifierPosition, report_identifier_violation};
use crate::docs::naming::{field_name, func_name, method_name, to_camel_case, type_name};
use crate::docs::type_mapping::{FFI_HANDLE_TYPE_NAME, doc_type};
use heck::ToSnakeCase;

/// `crate_name` is the `ApiSurface::crate_name` the backends are generated from; the Java arm
/// needs it to name the exception class the Java backend declares. ~keep
pub(crate) fn render_function_signature(
    func: &FunctionDef,
    lang: Language,
    ffi_prefix: &str,
    crate_name: &str,
) -> String {
    match lang {
        Language::Python => render_python_fn_sig(func, ffi_prefix),
        Language::Node | Language::Wasm => render_typescript_fn_sig(func, ffi_prefix),
        Language::Go => render_go_fn_sig(func, ffi_prefix),
        Language::Java => render_java_fn_sig(func, ffi_prefix, crate_name),
        Language::Ruby => render_ruby_fn_sig(func),
        Language::Ffi | Language::C | Language::Jni => render_c_fn_sig(func, ffi_prefix),
        Language::Php => render_php_fn_sig(func, ffi_prefix),
        Language::Elixir => render_elixir_fn_sig(func),
        Language::R => render_r_fn_sig(func),
        Language::Csharp => render_csharp_fn_sig(func, ffi_prefix),
        Language::Rust => render_rust_fn_sig(func, ffi_prefix),
        Language::Kotlin | Language::KotlinAndroid => render_kotlin_fn_sig(func, ffi_prefix),
        Language::Swift => render_swift_fn_sig(func, ffi_prefix),
        Language::Dart => render_dart_fn_sig(func, ffi_prefix),
        Language::Zig => render_zig_fn_sig(func, ffi_prefix),
        Language::Gleam => {
            format!("// Phase 1: {lang} backend signature generation")
        }
    }
}

pub(crate) fn render_python_fn_sig(func: &FunctionDef, ffi_prefix: &str) -> String {
    // ~keep Routed through `func_name`, not a bare `.to_snake_case()`, so a free function
    // whose name collides with a Python keyword (`global`, `class`, ...) is escaped before the
    // gate ever judges it -- the same discipline `method_name` already applies to opaque-type
    // methods. A real consumer's `pub fn global() -> &'static Registry` is what this closes: a
    // free function, not a constructor, so no per-shape renderer branch could have caught it.
    let name = func_name(&func.name, Language::Python, ffi_prefix);
    report_identifier_violation(
        &name,
        Language::Python,
        IdentifierPosition::Declaration,
        "a function signature",
    );
    let params: Vec<String> = func
        .params
        .iter()
        .map(|p| {
            let pname = p.name.to_snake_case();
            let pty = doc_type(&p.ty, Language::Python, ffi_prefix);
            if p.optional {
                format!("{pname}: {pty} = None")
            } else {
                format!("{pname}: {pty}")
            }
        })
        .collect();
    let ret = doc_type(&func.return_type, Language::Python, ffi_prefix);
    format!("def {}({}) -> {}", name, params.join(", "), ret)
}

pub(crate) fn render_typescript_fn_sig(func: &FunctionDef, ffi_prefix: &str) -> String {
    // ~keep Routed through `func_name` (Declaration position, checked below) rather than a
    // bare `to_camel_case` -- `func_name` never renames anything for Node/Wasm (the member-
    // position relaxation those two languages get depends on the raw word surviving), so this
    // is a no-op today, but a free function *is* judged in Declaration position, where the
    // reserved word is still illegal in every language including these two. Keeping this call
    // site on the same helper as every other renderer, rather than a hand-rolled exception, is
    // what stops that from silently drifting later.
    let name = func_name(&func.name, Language::Node, ffi_prefix);
    report_identifier_violation(
        &name,
        Language::Node,
        IdentifierPosition::Declaration,
        "a function signature",
    );
    let params: Vec<String> = func
        .params
        .iter()
        .map(|p| {
            let pname = to_camel_case(&p.name);
            let pty = doc_type(&p.ty, Language::Node, ffi_prefix);
            if p.optional {
                format!("{pname}?: {pty}")
            } else {
                format!("{pname}: {pty}")
            }
        })
        .collect();
    let ret = doc_type(&func.return_type, Language::Node, ffi_prefix);
    if func.is_async {
        format!("function {}({}): Promise<{}>", name, params.join(", "), ret)
    } else {
        format!("function {}({}): {}", name, params.join(", "), ret)
    }
}

/// ~keep Real Go bindings always pointer-wrap a `TypeRef::Named` return, fallible or not --
/// `gen_method_wrapper` (backends/go/gen_bindings/methods.rs) and `gen_function_wrapper`
/// (.../functions.rs) both route any non-Primitive/Duration/String/Char/Path return through
/// `go_optional_type` (backends/go/type_map.rs), which pointer-wraps `Named`. `doc_type`'s Go
/// arm renders the bare type name -- correct for a *type page* heading (Go structs are still
/// named after the Rust type) -- so the pointer belongs at the call site rendering a
/// *signature*, not in `doc_type` itself. Verified from source, not the constructor-shape
/// discrepancy: this applies to every Go method/function returning a Named type, not just
/// constructors -- opaque-handle params get the same treatment conditionally on opacity,
/// which `doc_type` cannot determine and is therefore NOT modeled here; see the docs-writer
/// report for that gap.
fn go_return_type(return_type: &TypeRef, ret: String) -> String {
    if matches!(return_type, TypeRef::Named(_)) {
        format!("*{ret}")
    } else {
        ret
    }
}

pub(crate) fn render_go_fn_sig(func: &FunctionDef, ffi_prefix: &str) -> String {
    let name = func_name(&func.name, Language::Go, ffi_prefix);
    report_identifier_violation(
        &name,
        Language::Go,
        IdentifierPosition::Declaration,
        "a function signature",
    );
    let params: Vec<String> = func
        .params
        .iter()
        .map(|p| {
            let pname = to_camel_case(&p.name);
            let pty = doc_type(&p.ty, Language::Go, ffi_prefix);
            format!("{pname} {pty}")
        })
        .collect();
    let ret = go_return_type(&func.return_type, doc_type(&func.return_type, Language::Go, ffi_prefix));
    if func.error_type.is_some() {
        if ret.is_empty() {
            format!("func {}({}) error", name, params.join(", "))
        } else {
            format!("func {}({}) ({}, error)", name, params.join(", "), ret)
        }
    } else if ret.is_empty() {
        format!("func {}({})", name, params.join(", "))
    } else {
        format!("func {}({}) {}", name, params.join(", "), ret)
    }
}

pub(crate) fn render_java_fn_sig(func: &FunctionDef, ffi_prefix: &str, crate_name: &str) -> String {
    // ~keep Routed through `func_name` rather than a bare `to_camel_case`: a free function
    // named `new` or `default` used to reach the gate unrenamed (only `method_name`'s opaque
    // methods went through `func_name`'s Java table), so this closes the same gap on the
    // free-function path.
    let name = func_name(&func.name, Language::Java, ffi_prefix);
    report_identifier_violation(
        &name,
        Language::Java,
        IdentifierPosition::Member,
        "a function signature",
    );
    let ret = doc_type(&func.return_type, Language::Java, ffi_prefix);
    let params: Vec<String> = func
        .params
        .iter()
        .map(|p| {
            let pname = to_camel_case(&p.name);
            let pty = doc_type(&p.ty, Language::Java, ffi_prefix);
            format!("{pty} {pname}")
        })
        .collect();
    // ~keep Every generated Java free function crosses the FFI boundary through
    // `emit_method_header` (backends/java/gen_bindings/ffi_class/sync_functions.rs), which
    // renders `ffi_method_signature.jinja` -- `throws {{ exception_class }}` -- unconditionally,
    // with no `error_type`-gated branch. The FFI crossing itself (marshaling, allocation) can
    // fail even when the wrapped Rust function is infallible, so `func.error_type` (a fact
    // about the *core* Rust signature) is the wrong oracle for this clause.
    //
    // ~keep The class is named by `backends::java::naming::exception_class_name`, the same
    // derivation `JavaBackend::resolve_main_class` feeds into `<MainClass>Exception.java`.
    // Building it from `ffi_prefix` here documented a class no generated package declares
    // whenever `[ffi] prefix` differed from the crate name.
    let throws = format!(
        " throws {}",
        crate::backends::java::naming::exception_class_name(crate_name)
    );
    format!("public static {} {}({}){}", ret, name, params.join(", "), throws)
}

pub(crate) fn render_ruby_fn_sig(func: &FunctionDef) -> String {
    let name = func_name(&func.name, Language::Ruby, "");
    report_identifier_violation(
        &name,
        Language::Ruby,
        IdentifierPosition::Member,
        "a function signature",
    );
    let params: Vec<String> = func
        .params
        .iter()
        .map(|p| {
            let pname = p.name.to_snake_case();
            if p.optional { format!("{pname}: nil") } else { pname }
        })
        .collect();
    format!("def self.{}({})", name, params.join(", "))
}

pub(crate) fn render_c_fn_sig(func: &FunctionDef, ffi_prefix: &str) -> String {
    let name = crate::codegen::c_consumer::free_function_symbol(&ffi_prefix.to_snake_case(), &func.name);
    let ret = doc_type(&func.return_type, Language::Ffi, ffi_prefix);
    let params: Vec<String> = func
        .params
        .iter()
        .map(|p| {
            let pname = p.name.to_snake_case();
            let pty = doc_type(&p.ty, Language::Ffi, ffi_prefix);
            format!("{pty} {pname}")
        })
        .collect();
    // ~keep `doc_type` already renders `TypeRef::Named` as the scalar `AlefHandle` token
    // for Ffi/C (see type_mapping.rs), so no pointer suffix belongs here -- adding one
    // was the bug that put a `TYPE*` signature above an `AlefHandle result = ...` example.
    //
    // A fallible function whose logical return type is `()` has no value slot left to
    // signal failure through, so the FFI backend repurposes the return itself as a status
    // code: `gen_function_wrapper_footer`/`gen_free_function` (backends/ffi/gen_bindings/
    // functions/orchestration.rs) emit `i32` -- not `void` -- whenever
    // `has_error && is_void_return(&func.return_type)`, which cbindgen renders as
    // `int32_t`. Documenting `void` there tells a caller they can skip the check.
    let ret_str = match &func.return_type {
        TypeRef::Unit if func.error_type.is_some() => "int32_t".to_string(),
        TypeRef::Unit => "void".to_string(),
        _ => ret,
    };
    format!("{} {}({});", ret_str, name, params.join(", "))
}

pub(crate) fn render_php_fn_sig(func: &FunctionDef, ffi_prefix: &str) -> String {
    let name = func_name(&func.name, Language::Php, ffi_prefix);
    report_identifier_violation(&name, Language::Php, IdentifierPosition::Member, "a function signature");
    let params: Vec<String> = func
        .params
        .iter()
        .map(|p| {
            let pname = format!("${}", to_camel_case(&p.name));
            let pty = doc_type(&p.ty, Language::Php, ffi_prefix);
            if p.optional {
                format!("?{pty} {pname} = null")
            } else {
                format!("{pty} {pname}")
            }
        })
        .collect();
    let ret = doc_type(&func.return_type, Language::Php, ffi_prefix);
    format!("public static function {}({}): {}", name, params.join(", "), ret)
}

pub(crate) fn render_elixir_fn_sig(func: &FunctionDef) -> String {
    let name = func_name(&func.name, Language::Elixir, "");
    report_identifier_violation(
        &name,
        Language::Elixir,
        IdentifierPosition::Declaration,
        "a function signature",
    );
    let params: Vec<String> = func.params.iter().map(|p| p.name.to_snake_case()).collect();
    format!(
        "@spec {}({}) :: {{:ok, term()}} | {{:error, term()}}\ndef {}({})",
        name,
        params.join(", "),
        name,
        params.join(", ")
    )
}

pub(crate) fn render_r_fn_sig(func: &FunctionDef) -> String {
    let name = func_name(&func.name, Language::R, "");
    let params: Vec<String> = func
        .params
        .iter()
        .map(|p| {
            let pname = p.name.to_snake_case();
            if p.optional { format!("{pname} = NULL") } else { pname }
        })
        .collect();
    format!("{}({})", name, params.join(", "))
}

pub(crate) fn render_csharp_fn_sig(func: &FunctionDef, ffi_prefix: &str) -> String {
    let name = func_name(&func.name, Language::Csharp, ffi_prefix);
    report_identifier_violation(
        &name,
        Language::Csharp,
        IdentifierPosition::Member,
        "a function signature",
    );
    let ret = doc_type(&func.return_type, Language::Csharp, ffi_prefix);
    let params: Vec<String> = func
        .params
        .iter()
        .map(|p| {
            let pname = to_camel_case(&p.name);
            let pty = doc_type(&p.ty, Language::Csharp, ffi_prefix);
            if p.optional {
                format!("{pty}? {pname} = null")
            } else {
                format!("{pty} {pname}")
            }
        })
        .collect();
    if func.is_async {
        let async_name = if name.ends_with("Async") {
            name.clone()
        } else {
            format!("{name}Async")
        };
        let task_ret = if ret == "void" {
            "Task".to_string()
        } else {
            format!("Task<{ret}>")
        };
        format!("public static async {} {}({})", task_ret, async_name, params.join(", "))
    } else {
        format!("public static {} {}({})", ret, name, params.join(", "))
    }
}

pub(crate) fn render_rust_fn_sig(func: &FunctionDef, ffi_prefix: &str) -> String {
    let name = func.name.to_snake_case();
    let params: Vec<String> = func
        .params
        .iter()
        .map(|p| {
            let pname = p.name.to_snake_case();
            let pty = doc_type(&p.ty, Language::Rust, ffi_prefix);
            if p.optional {
                format!("{pname}: Option<{pty}>")
            } else {
                match &p.ty {
                    TypeRef::String | TypeRef::Char => format!("{pname}: &str"),
                    TypeRef::Bytes => format!("{pname}: &[u8]"),
                    _ => format!("{pname}: {pty}"),
                }
            }
        })
        .collect();
    let ret = doc_type(&func.return_type, Language::Rust, ffi_prefix);
    let error_part = if let Some(err) = &func.error_type {
        let err_ty = type_name(err, Language::Rust, ffi_prefix);
        if ret == "()" {
            format!(" -> Result<(), {err_ty}>")
        } else {
            format!(" -> Result<{ret}, {err_ty}>")
        }
    } else if ret == "()" {
        String::new()
    } else {
        format!(" -> {ret}")
    };
    if func.is_async {
        format!("pub async fn {}({}){}", name, params.join(", "), error_part)
    } else {
        format!("pub fn {}({}){}", name, params.join(", "), error_part)
    }
}

pub(crate) fn render_kotlin_fn_sig(func: &FunctionDef, ffi_prefix: &str) -> String {
    let name = func_name(&func.name, Language::Kotlin, ffi_prefix);
    report_identifier_violation(
        &name,
        Language::Kotlin,
        IdentifierPosition::Declaration,
        "a function signature",
    );
    let ret = doc_type(&func.return_type, Language::Kotlin, ffi_prefix);
    let params: Vec<String> = func
        .params
        .iter()
        .map(|p| {
            let pname = to_camel_case(&p.name);
            let pty = doc_type(&p.ty, Language::Kotlin, ffi_prefix);
            if p.optional {
                format!("{pname}: {pty}? = null")
            } else {
                format!("{pname}: {pty}")
            }
        })
        .collect();
    let throws = func
        .error_type
        .as_ref()
        .map(|e| format!("@Throws({}::class)\n", type_name(e, Language::Kotlin, ffi_prefix)))
        .unwrap_or_default();
    let ret_part = if ret == "Unit" {
        String::new()
    } else {
        format!(": {ret}")
    };
    format!("{throws}fun {name}({}){ret_part}", params.join(", "))
}

pub(crate) fn render_swift_fn_sig(func: &FunctionDef, ffi_prefix: &str) -> String {
    // ~keep A free function has no owning type, so there is no `is_swift_static_constructor`
    // shape to divert here -- only the generic keyword escape in `func_name` applies. A free
    // Swift function literally named `init` (declaration-keyword collision) or any other
    // reserved word now renders escaped instead of reaching the gate raw.
    let name = func_name(&func.name, Language::Swift, ffi_prefix);
    report_identifier_violation(
        &name,
        Language::Swift,
        IdentifierPosition::Member,
        "a function signature",
    );
    let ret = doc_type(&func.return_type, Language::Swift, ffi_prefix);
    let params: Vec<String> = func
        .params
        .iter()
        .map(|p| {
            let pname = to_camel_case(&p.name);
            let pty = doc_type(&p.ty, Language::Swift, ffi_prefix);
            if p.optional {
                format!("{pname}: {pty}? = nil")
            } else {
                format!("{pname}: {pty}")
            }
        })
        .collect();
    let throws = if func.error_type.is_some() { " throws" } else { "" };
    let ret_part = if ret == "Void" {
        String::new()
    } else {
        format!(" -> {ret}")
    };
    format!("public static func {name}({}){throws}{ret_part}", params.join(", "))
}

pub(crate) fn render_dart_fn_sig(func: &FunctionDef, ffi_prefix: &str) -> String {
    let name = func_name(&func.name, Language::Dart, ffi_prefix);
    report_identifier_violation(
        &name,
        Language::Dart,
        IdentifierPosition::Declaration,
        "a function signature",
    );
    let ret = doc_type(&func.return_type, Language::Dart, ffi_prefix);
    let required: Vec<String> = func
        .params
        .iter()
        .filter(|p| !p.optional)
        .map(|p| {
            let pname = to_camel_case(&p.name);
            let pty = doc_type(&p.ty, Language::Dart, ffi_prefix);
            format!("{pty} {pname}")
        })
        .collect();
    let optional: Vec<String> = func
        .params
        .iter()
        .filter(|p| p.optional)
        .map(|p| {
            let pname = to_camel_case(&p.name);
            let pty = doc_type(&p.ty, Language::Dart, ffi_prefix);
            format!("{pty}? {pname}")
        })
        .collect();
    // ~keep Real Dart params are grouped exactly as `emit_function`'s `params_str` match
    // (backends/dart/gen_bindings/functions.rs) does: required positional params joined with
    // any optional ones wrapped in `{}` (Dart named-optional syntax), never `[]`
    // (positional-optional) -- a caller following a `[]`-bracketed doc could not call the
    // named form the real binding actually exposes.
    let params_str = match (required.is_empty(), optional.is_empty()) {
        (_, true) => required.join(", "),
        (true, false) => format!("{{{}}}", optional.join(", ")),
        (false, false) => format!("{}, {{{}}}", required.join(", "), optional.join(", ")),
    };
    // ~keep Every generated Dart free function is `Future<T>` (`Future<void>` for a `Unit`
    // return), never a bare `T` -- `emit_function`'s return-type branch
    // (backends/dart/gen_bindings/functions.rs) is unconditional, with no `is_async` check:
    // flutter_rust_bridge dispatches every non-`#[frb(sync)]` call across the FFI boundary
    // asynchronously, regardless of whether the wrapped Rust function is itself `async fn`.
    let future_ret = if ret == "void" {
        "Future<void>".to_string()
    } else {
        format!("Future<{ret}>")
    };
    format!("{future_ret} {name}({params_str})")
}

pub(crate) fn render_zig_fn_sig(func: &FunctionDef, ffi_prefix: &str) -> String {
    let name = func_name(&func.name, Language::Zig, ffi_prefix);
    report_identifier_violation(
        &name,
        Language::Zig,
        IdentifierPosition::Declaration,
        "a function signature",
    );
    let ret = doc_type(&func.return_type, Language::Zig, ffi_prefix);
    let params: Vec<String> = func
        .params
        .iter()
        .map(|p| {
            let pname = p.name.to_snake_case();
            let pty = doc_type(&p.ty, Language::Zig, ffi_prefix);
            if p.optional {
                format!("{pname}: ?{pty}")
            } else {
                format!("{pname}: {pty}")
            }
        })
        .collect();
    let ret_str = if let Some(err) = &func.error_type {
        let err_ty = type_name(err, Language::Zig, ffi_prefix);
        if ret == "void" {
            format!("{err_ty}!void")
        } else {
            format!("{err_ty}!{ret}")
        }
    } else {
        ret
    };
    format!("pub fn {name}({}) {ret_str}", params.join(", "))
}

/// Arm-for-arm mirror of the C# backend's `is_static_constructor`
/// (`backends/csharp/gen_bindings/types/constructors.rs`), which decides whether an opaque
/// type's method is emitted as a real C# constructor instead of a named member.
///
/// ~keep Mirrored rather than called: the backend's copy takes the already-resolved `TypeDef`,
/// while the docs layer only ever carries the owning type's Rust name.
/// `test_csharp_docs_constructor_predicate_matches_the_backend_predicate` pins the two together
/// over the whole clause matrix so they cannot drift. Every clause is reproduced, including the
/// non-obvious `params.is_empty()` guard -- a zero-arg `new` is *not* promoted, because the
/// backend emits that shape from the configured `client_constructor`
/// (`gen_opaque_factory_method`, which renders `public static {T} Create(...)`) and a second
/// definition here would be a duplicate. Opacity is not re-checked because the docs pipeline
/// never reaches a C# method signature for a non-opaque type: `methods_bound_in_lang`
/// (`docs/language_pages/type_render.rs`) gates the whole method loop on
/// `lang == Rust || ty.is_opaque || (lang == Go && ty.has_serde)`.
pub(crate) fn is_csharp_static_constructor(method: &MethodDef, owner_type: &str) -> bool {
    if method.name != "new" {
        return false;
    }
    if !method.is_static || method.params.is_empty() {
        return false;
    }
    // ~keep Compared verbatim, not on the `rsplit("::")` short names `type_name` would use:
    // the backend's copy tests `n == typ.name` against the same two IR values this receives
    // (`type_render.rs` passes `&ty.name` straight through), so normalising here would make
    // docs promote a fully qualified return the backend leaves as an ordinary method.
    match &method.return_type {
        TypeRef::Named(n) => n == owner_type,
        _ => false,
    }
}

/// Whether a Rust static `new` returning `Self` must be promoted to a real Swift initializer
/// instead of an ordinary member.
///
/// ~keep Swift's `init` is a declaration keyword, not a reserved identifier: `public static
/// func init(...)` is a syntax error regardless of what the name is escaped or renamed to,
/// because the defect is the *declaration shape* (`static func`), not the identifier. The only
/// legal Swift spelling of a constructor is `init(...)` -- no `static`, no `func`, no name for
/// the identifier gate to judge -- so this, like `is_csharp_static_constructor`, diverts the
/// shape at render time rather than trying to make some string legal in member position.
/// Same clause matrix as the C# mirror (name, staticness, return type), but deliberately
/// without the C# guard's `params.is_empty()` exclusion: C# excludes a zero-arg `new` because
/// the backend's configured `client_constructor` already emits one, and promoting it here
/// would document a duplicate. Swift has no equivalent zero-arg diversion in this docs layer,
/// and two of the four real consumer constructors this was measured against --
/// `LanguageRegistry::new()` and `Parser::new()` -- are zero-arg; excluding them would leave
/// the fatal case half-fixed.
pub(crate) fn is_swift_static_constructor(method: &MethodDef, owner_type: &str) -> bool {
    if method.name != "new" {
        return false;
    }
    if !method.is_static {
        return false;
    }
    match &method.return_type {
        TypeRef::Named(n) => n == owner_type,
        _ => false,
    }
}

#[derive(Debug, Clone, Default)]
pub(crate) struct MethodSignatureOverride {
    pub(crate) name: Option<String>,
    pub(crate) return_type: Option<String>,
    pub(crate) signature: Option<String>,
}

/// Test-only convenience wrapper: no production caller renders a method signature without an
/// override slot, so the crate name is pinned to the docs test fixture's rather than added to
/// ~90 call sites. Java assertions that turn on the exception class must use
/// `render_method_signature_with_override` and pass a crate name explicitly. ~keep
#[cfg(test)]
pub(crate) fn render_method_signature(
    method: &MethodDef,
    type_name_str: &str,
    lang: Language,
    ffi_prefix: &str,
) -> String {
    render_method_signature_with_override(
        method,
        type_name_str,
        lang,
        ffi_prefix,
        crate::docs::test_helpers::TEST_CRATE_NAME,
        None,
    )
}

/// `crate_name` is the `ApiSurface::crate_name` the backends are generated from; the Java arm
/// needs it to name the exception class the Java backend declares. ~keep
pub(crate) fn render_method_signature_with_override(
    method: &MethodDef,
    type_name_str: &str,
    lang: Language,
    ffi_prefix: &str,
    crate_name: &str,
    signature_override: Option<&MethodSignatureOverride>,
) -> String {
    if let Some(signature) = signature_override.and_then(|override_| override_.signature.as_deref()) {
        return signature.to_string();
    }

    let name = signature_override
        .and_then(|override_| override_.name.as_deref())
        .map(str::to_string)
        .unwrap_or_else(|| method_name(type_name_str, &method.name, lang, ffi_prefix));
    // Every documented method name must be a legal identifier in `lang` -- report a
    // reserved-word collision (Java/Dart's `new`, etc.) rather than silently document code
    // that would not compile. `name` is the *renamed* form: `method_name` has already run
    // `func_name`'s per-language keyword table (Java `new` -> `create`), so what the gate
    // judges is what the page will print. Member position, not declaration: this renders a
    // class member in every language, which is exactly why the napi `static new(...)` that
    // used to abort the whole docs run now passes. See formatting.rs's
    // `IdentifierPosition`. ~keep
    report_identifier_violation(&name, lang, IdentifierPosition::Member, "a method signature");
    let overridden_ret = signature_override.and_then(|override_| override_.return_type.as_deref());
    // ~keep An explicitly overridden return type is already the backend-accurate spelling (the
    // streaming adapters supply Dart `Stream<T>`, Swift `AsyncThrowingStream<T, Error>`, ...), so
    // the per-language async wrappers below must not re-wrap it into `Future<Stream<T>>`. Only an
    // IR-derived return type needs that wrapping.
    let ret_is_overridden = overridden_ret.is_some();
    let ret = overridden_ret
        .map(str::to_string)
        .unwrap_or_else(|| doc_type(&method.return_type, lang, ffi_prefix));

    match lang {
        Language::Python => {
            let params: Vec<String> = method
                .params
                .iter()
                .map(|p| {
                    let pname = field_name(&p.name, lang);
                    let pty = doc_type(&p.ty, lang, ffi_prefix);
                    format!("{pname}: {pty}")
                })
                .collect();
            if method.is_static {
                format!("@staticmethod\ndef {}({}) -> {}", name, params.join(", "), ret)
            } else {
                let mut all_params = vec!["self".to_string()];
                all_params.extend(params);
                format!("def {}({}) -> {}", name, all_params.join(", "), ret)
            }
        }
        Language::Node | Language::Wasm => {
            let params: Vec<String> = method
                .params
                .iter()
                .map(|p| {
                    let pname = field_name(&p.name, lang);
                    let pty = doc_type(&p.ty, lang, ffi_prefix);
                    format!("{pname}: {pty}")
                })
                .collect();
            let ret = if method.is_async {
                format!("Promise<{ret}>")
            } else {
                ret
            };
            if method.is_static {
                format!("static {}({}): {}", name, params.join(", "), ret)
            } else {
                format!("{}({}): {}", name, params.join(", "), ret)
            }
        }
        Language::Ruby => {
            let params: Vec<String> = method.params.iter().map(|p| p.name.to_snake_case()).collect();
            if method.is_static {
                format!("def self.{}({})", name, params.join(", "))
            } else {
                format!("def {}({})", name, params.join(", "))
            }
        }
        Language::Go => {
            let go_receiver_type = type_name(type_name_str, Language::Go, ffi_prefix);
            let params: Vec<String> = method
                .params
                .iter()
                .map(|p| {
                    let pname = to_camel_case(&p.name);
                    let pty = doc_type(&p.ty, lang, ffi_prefix);
                    format!("{pname} {pty}")
                })
                .collect();
            // ~keep A Named return is always pointer-wrapped in real Go, fallible or not --
            // see `go_return_type`'s doc comment for the source citation. Skipped when a
            // curated override already supplied the return text (streaming.rs) -- that
            // string is trusted as-is, not reinterpreted from `method.return_type`'s shape.
            let has_return_override = signature_override.and_then(|o| o.return_type.as_deref()).is_some();
            let ret = if has_return_override {
                ret
            } else {
                go_return_type(&method.return_type, ret)
            };
            // ~keep A static Go method is a free function `func {Type}{Method}(...)`, never
            // a method with a receiver -- see method_signature_static.jinja vs
            // method_signature_instance.jinja (backends/go/templates/). Rendering every Go
            // method with `func (o *Type) Method(...)` regardless of `is_static` documented
            // a receiver parameter that does not exist on the real generated function --
            // the same "IR through a per-language template that never checked a flag" defect
            // that broke the C signatures, here fabricating a receiver instead of a pointer.
            let head = if method.is_static {
                format!("func {go_receiver_type}{name}")
            } else {
                format!("func (o *{go_receiver_type}) {name}")
            };
            if method.error_type.is_some() {
                if ret.is_empty() {
                    format!("{head}({}) error", params.join(", "))
                } else {
                    format!("{head}({}) ({}, error)", params.join(", "), ret)
                }
            } else if ret.is_empty() {
                format!("{head}({})", params.join(", "))
            } else {
                format!("{head}({}) {}", params.join(", "), ret)
            }
        }
        Language::Java => {
            // ~keep Java's keyword renames are applied once, by `func_name`, which mirrors the
            // backend's `safe_java_method_name` (`default` -> `defaultInstance`, `new` ->
            // `create`). A second rename here used to map `default` -> `defaultOptions` and
            // silently won, emitting a name the Java backend never generates.
            let params: Vec<String> = method
                .params
                .iter()
                .map(|p| {
                    let pname = to_camel_case(&p.name);
                    let pty = doc_type(&p.ty, lang, ffi_prefix);
                    format!("{pty} {pname}")
                })
                .collect();
            // ~keep Every generated Java method -- instance or static factory, fallible or
            // not -- crosses the FFI boundary through `emit_instance_method_header` /
            // `emit_static_factory_header` (gen_bindings/types/opaque/{instance,extended}.rs),
            // which append `throws {main_class}Exception` unconditionally except for `clone`.
            // The FFI crossing itself (marshaling, allocation) can fail even when the wrapped
            // Rust method returns a bare `T`, so `method.error_type` (a fact about the *core*
            // Rust signature) is the wrong oracle here -- it must always be present and must
            // always name the FFI exception, never the domain error type.
            //
            // ~keep The class is named by `backends::java::naming::exception_class_name`, the
            // same derivation the Java backend declares the class with -- not a second
            // spelling built from `ffi_prefix`, which is a C symbol prefix and is free to
            // differ from the crate name.
            let throws = if method.name == "clone" {
                String::new()
            } else {
                format!(
                    " throws {}",
                    crate::backends::java::naming::exception_class_name(crate_name)
                )
            };
            if method.is_static {
                format!("public static {} {}({}){}", ret, name, params.join(", "), throws)
            } else {
                format!("public {} {}({}){}", ret, name, params.join(", "), throws)
            }
        }
        Language::Csharp => {
            let params: Vec<String> = method
                .params
                .iter()
                .map(|p| {
                    let pname = to_camel_case(&p.name);
                    let pty = doc_type(&p.ty, lang, ffi_prefix);
                    format!("{pty} {pname}")
                })
                .collect();
            // ~keep A static `new` with at least one parameter is not a factory method in the
            // emitted C#: `gen_opaque_type` routes it through `is_static_constructor` ->
            // `gen_opaque_static_constructor`, which renders
            // `opaque_static_constructor_signature.jinja` -- `public {class_name}({params})`, a
            // real instance constructor with no return type and no method name. Documenting it
            // as `public DownloadManager New(string version)` names a member the backend never
            // emits, and a reader following it cannot construct the type at all. The check runs
            // before the async branch because the backend's does too (`is_static_constructor`
            // never inspects `is_async`, and a C# constructor cannot be `async`).
            if is_csharp_static_constructor(method, type_name_str) {
                let class_name = type_name(type_name_str, lang, ffi_prefix);
                format!("public {}({})", class_name, params.join(", "))
            } else {
                // ~keep `static ` is emitted by the backend template itself
                // (`opaque_method_header.jinja`: `public {{ static_kw }}{{ return_type_str }}
                // {{ method_cs_name }}(`), fed by `let static_kw = if is_static { "static " }`
                // in `gen_opaque_method` (backends/csharp/gen_bindings/types/opaque.rs). Omitting
                // it here documented every static factory as an instance method, so a reader
                // would call it on a value they have no way to obtain yet. `static ` precedes
                // `async` in that template, not the other way round.
                let static_kw = if method.is_static { "static " } else { "" };
                if method.is_async {
                    let async_name = if name.ends_with("Async") {
                        name.clone()
                    } else {
                        format!("{name}Async")
                    };
                    let task_ret = if ret == "void" {
                        "Task".to_string()
                    } else {
                        format!("Task<{ret}>")
                    };
                    format!(
                        "public {static_kw}async {} {}({})",
                        task_ret,
                        async_name,
                        params.join(", ")
                    )
                } else {
                    format!("public {static_kw}{} {}({})", ret, name, params.join(", "))
                }
            }
        }
        Language::Php => {
            let params: Vec<String> = method
                .params
                .iter()
                .map(|p| {
                    let pname = format!("${}", to_camel_case(&p.name));
                    let pty = doc_type(&p.ty, lang, ffi_prefix);
                    format!("{pty} {pname}")
                })
                .collect();
            if method.is_static {
                format!("public static function {}({}): {}", name, params.join(", "), ret)
            } else {
                format!("public function {}({}): {}", name, params.join(", "), ret)
            }
        }
        Language::Elixir => {
            // ~keep An instance Elixir method takes the struct as an explicit leading `obj`
            // parameter -- rustler's codegen (`gen_bindings/helpers/conversions.rs`) pushes
            // `"obj"` onto `def_args` whenever `method.receiver.is_some()`, and the jinja
            // template emits `def {{ method_name }}({{ def_args }})` from that list verbatim --
            // there is no implicit `self` the way Ruby/Python have one. `method.is_static` is a
            // safe proxy for `receiver.is_some()`: both derive from the same `detect_receiver()`
            // call (extract/extractor/functions/methods.rs), so a static method (no receiver)
            // must not get the `obj` param, exactly mirroring the real generator.
            let mut params: Vec<String> = if method.is_static {
                Vec::new()
            } else {
                vec!["obj".to_string()]
            };
            params.extend(method.params.iter().map(|p| p.name.to_snake_case()));
            format!("def {}({})", name, params.join(", "))
        }
        Language::R => {
            let params: Vec<String> = method.params.iter().map(|p| p.name.to_snake_case()).collect();
            format!("{}({})", name, params.join(", "))
        }
        Language::Ffi | Language::C | Language::Jni => {
            let mut params: Vec<String> = method
                .params
                .iter()
                .map(|p| {
                    let pname = p.name.to_snake_case();
                    let pty = doc_type(&p.ty, lang, ffi_prefix);
                    format!("{pty} {pname}")
                })
                .collect();
            // ~keep The backend always emits a leading scalar-handle receiver for a non-static
            // method (`gen_method_wrapper`, backends/ffi/gen_bindings/functions/orchestration.rs:
            // `params.push(format!("    {param_name}: {receiver_ty}"))` with `param_name = "this"`
            // and `receiver_ty = "AlefHandle"`). Omitting it here published a signature the
            // caller cannot actually call -- the real symbol takes one more argument than the
            // documented one.
            if !method.is_static {
                let receiver_ty = type_name(FFI_HANDLE_TYPE_NAME, lang, ffi_prefix);
                params.insert(0, format!("{receiver_ty} this"));
            }
            // ~keep Same status-code convention as render_c_fn_sig: a fallible method
            // whose logical return is `()` reports failure through the return itself, so
            // the ABI is `int32_t`, not `void`. Skipped when a curated override already
            // supplied a return type (that string is trusted as-is).
            let has_return_override = signature_override.and_then(|o| o.return_type.as_deref()).is_some();
            let ret = if matches!(lang, Language::Ffi | Language::C)
                && !has_return_override
                && matches!(method.return_type, TypeRef::Unit)
                && method.error_type.is_some()
            {
                "int32_t".to_string()
            } else {
                ret
            };
            format!("{} {}({});", ret, name, params.join(", "))
        }
        Language::Rust => {
            let params: Vec<String> = method
                .params
                .iter()
                .map(|p| {
                    let pname = p.name.to_snake_case();
                    let pty = doc_type(&p.ty, lang, ffi_prefix);
                    if p.optional {
                        format!("{pname}: Option<{pty}>")
                    } else {
                        match &p.ty {
                            TypeRef::String | TypeRef::Char => format!("{pname}: &str"),
                            TypeRef::Bytes => format!("{pname}: &[u8]"),
                            _ => format!("{pname}: {pty}"),
                        }
                    }
                })
                .collect();
            let ret = if let Some(err) = &method.error_type {
                let err_ty = type_name(err, Language::Rust, ffi_prefix);
                if ret == "()" {
                    format!("Result<(), {err_ty}>")
                } else {
                    format!("Result<{ret}, {err_ty}>")
                }
            } else {
                ret
            };
            let fn_keyword = if method.is_async { "pub async fn" } else { "pub fn" };
            if method.is_static {
                if ret == "()" {
                    format!("{fn_keyword} {}({})", name, params.join(", "))
                } else {
                    format!("{fn_keyword} {}({}) -> {}", name, params.join(", "), ret)
                }
            } else {
                let mut all_params = vec!["&self".to_string()];
                all_params.extend(params);
                if ret == "()" {
                    format!("{fn_keyword} {}({})", name, all_params.join(", "))
                } else {
                    format!("{fn_keyword} {}({}) -> {}", name, all_params.join(", "), ret)
                }
            }
        }
        Language::Kotlin | Language::KotlinAndroid => {
            let params: Vec<String> = method
                .params
                .iter()
                .map(|p| {
                    let pname = to_camel_case(&p.name);
                    let pty = doc_type(&p.ty, lang, ffi_prefix);
                    if p.optional {
                        format!("{pname}: {pty}? = null")
                    } else {
                        format!("{pname}: {pty}")
                    }
                })
                .collect();
            let throws = method
                .error_type
                .as_ref()
                .map(|e| format!("@Throws({}::class)\n", type_name(e, lang, ffi_prefix)))
                .unwrap_or_default();
            let ret_part = if ret == "Unit" {
                String::new()
            } else {
                format!(": {ret}")
            };
            if method.is_static {
                format!("{throws}@JvmStatic\nfun {name}({}){ret_part}", params.join(", "))
            } else {
                format!("{throws}fun {name}({}){ret_part}", params.join(", "))
            }
        }
        Language::Swift => {
            let params: Vec<String> = method
                .params
                .iter()
                .map(|p| {
                    let pname = to_camel_case(&p.name);
                    let pty = doc_type(&p.ty, lang, ffi_prefix);
                    if p.optional {
                        format!("{pname}: {pty}? = nil")
                    } else {
                        format!("{pname}: {pty}")
                    }
                })
                .collect();
            let throws = if method.error_type.is_some() { " throws" } else { "" };
            // ~keep A static `new` returning `Self` is a Swift initializer, not a member named
            // `init` -- `public static func init(...)` is a syntax error no identifier fix can
            // repair, since Swift constructors have no `static`, no `func`, and no name at all.
            // This must be checked before the identifier gate would otherwise see `init` as a
            // member-position name; see `is_swift_static_constructor`'s doc comment.
            if is_swift_static_constructor(method, type_name_str) {
                format!("public init({}){throws}", params.join(", "))
            } else {
                let ret_part = if ret == "Void" {
                    String::new()
                } else {
                    format!(" -> {ret}")
                };
                if method.is_static {
                    format!("public static func {name}({}){throws}{ret_part}", params.join(", "))
                } else {
                    format!("public func {name}({}){throws}{ret_part}", params.join(", "))
                }
            }
        }
        Language::Dart => {
            let required: Vec<String> = method
                .params
                .iter()
                .filter(|p| !p.optional)
                .map(|p| {
                    let pname = to_camel_case(&p.name);
                    let pty = doc_type(&p.ty, lang, ffi_prefix);
                    format!("{pty} {pname}")
                })
                .collect();
            let optional: Vec<String> = method
                .params
                .iter()
                .filter(|p| p.optional)
                .map(|p| {
                    let pname = to_camel_case(&p.name);
                    let pty = doc_type(&p.ty, lang, ffi_prefix);
                    format!("{pty}? {pname}")
                })
                .collect();
            // ~keep Same real-backend grouping as `render_dart_fn_sig` -- required positional
            // params, then any optional ones grouped in `{}` (Dart named-optional syntax), not
            // `[]`. See that function's doc comment for the source citation.
            let params_str = match (required.is_empty(), optional.is_empty()) {
                (_, true) => required.join(", "),
                (true, false) => format!("{{{}}}", optional.join(", ")),
                (false, false) => format!("{}, {{{}}}", required.join(", "), optional.join(", ")),
            };
            let static_kw = if method.is_static { "static " } else { "" };
            // ~keep Same unconditional `Future<T>` wrap as `render_dart_fn_sig` -- flutter_rust_bridge
            // dispatches instance and static methods across the FFI boundary the same way it
            // dispatches free functions, so this is not gated on `method.is_async` or
            // `method.is_static` either. See that function's doc comment for the source citation.
            let future_ret = if ret_is_overridden {
                ret.clone()
            } else if ret == "void" {
                "Future<void>".to_string()
            } else {
                format!("Future<{ret}>")
            };
            format!("{static_kw}{future_ret} {name}({params_str})")
        }
        Language::Zig => {
            let params: Vec<String> = method
                .params
                .iter()
                .map(|p| {
                    let pname = p.name.to_snake_case();
                    let pty = doc_type(&p.ty, lang, ffi_prefix);
                    if p.optional {
                        format!("{pname}: ?{pty}")
                    } else {
                        format!("{pname}: {pty}")
                    }
                })
                .collect();
            let ret_str = if let Some(err) = &method.error_type {
                let err_ty = type_name(err, lang, ffi_prefix);
                if ret == "void" {
                    format!("{err_ty}!void")
                } else {
                    format!("{err_ty}!{ret}")
                }
            } else {
                ret
            };
            let receiver_ty = type_name(type_name_str, lang, ffi_prefix);
            // ~keep Zig binds methods only through `emit_opaque_handle`
            // (backends/zig/gen_bindings/mod.rs) -- `emit_type` writes fields and nothing else --
            // and a static one is emitted by `emit_opaque_static_method` through
            // `opaque_static_signature.jinja`: `pub fn {{ method_snake }}_{{ type_snake }}(...)`.
            // That is a *top-level* function whose name carries the owning type as a suffix, not
            // a member of the struct, so `DownloadManager.new(...)` -- the name this arm used to
            // document -- resolves to nothing in the emitted module. `type_snake` is
            // `AsSnakeCase(&ty.name)` on the backend side; snake-casing the resolved short type
            // name reproduces it.
            if method.is_static {
                let type_snake = receiver_ty.to_snake_case();
                format!("pub fn {name}_{type_snake}({}) {ret_str}", params.join(", "))
            } else {
                let mut all_params = vec![format!("self: *const {receiver_ty}")];
                all_params.extend(params);
                format!("pub fn {name}({}) {ret_str}", all_params.join(", "))
            }
        }
        Language::Gleam => {
            format!("// Phase 1: {lang} backend method signature generation")
        }
    }
}

#[cfg(test)]
#[path = "signatures/tests.rs"]
mod tests;