alef 0.80.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
use crate::core::config::Language;
use crate::core::ir::{ApiSurface, FunctionDef, MethodDef, TypeRef};
use crate::docs::formatting::{IdentifierPosition, report_identifier_violation};
use crate::docs::naming::{field_name, method_name, to_camel_case, type_name};
use crate::docs::rust_types::{rust_param_type, rust_receiver};
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,
    api: &ApiSurface,
) -> 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, api),
        Language::Gleam => {
            format!("// Phase 1: {lang} backend signature generation")
        }
    }
}

mod function_sigs;
pub(crate) use function_sigs::*;

/// 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,
        &ApiSurface::default(),
    )
}

/// `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. `api` is only consulted by
/// the Zig arm, to ask the backend whether a `Named` param/return is an opaque handle or a
/// struct DTO that serialises to bytes at the wrapper boundary. ~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>,
    api: &ApiSurface,
) -> 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(|| {
        if lang == Language::Zig {
            crate::backends::zig::zig_boundary_return_type(&method.return_type, api)
        } 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 = crate::docs::naming::csharp_async_member_name(&name, true);
                    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 mut params: Vec<String> = rust_receiver(method).map(str::to_string).into_iter().collect();
            params.extend(
                method
                    .params
                    .iter()
                    .map(|p| format!("{}: {}", p.name.to_snake_case(), rust_param_type(p, ffi_prefix))),
            );
            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 ret == "()" {
                format!("{fn_keyword} {}({})", name, params.join(", "))
            } else {
                format!("{fn_keyword} {}({}) -> {}", name, 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 => {
            // ~keep See `render_zig_fn_sig`'s note: a `Named` param asks the backend's own
            // `zig_param_type` (via `zig_boundary_param_type`) whether it is an opaque handle
            // or a struct DTO that serialises to `[]const u8` at the wrapper boundary, instead
            // of re-deriving that shape here.
            let params: Vec<String> = method
                .params
                .iter()
                .map(|p| {
                    let pname = p.name.to_snake_case();
                    let pty = crate::backends::zig::zig_boundary_param_type(&p.ty, p.optional, api);
                    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;