alef 0.35.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
use crate::core::ir::{FunctionDef, ParamDef, TypeRef};

use super::conversions::{dart_call_arg, frb_rust_type_inner, primitive_name};
use super::helpers::emit_cleaned_dartdoc;

pub(crate) fn emit_bridge_fn(
    out: &mut String,
    f: &FunctionDef,
    source_crate_name: &str,
    type_paths: &std::collections::HashMap<String, String>,
    types_needing_from_conversion: &std::collections::HashSet<String>,
    opaque_type_names: &std::collections::HashSet<String>,
    stub_methods: &[String],
) {
    emit_cleaned_dartdoc(out, &f.doc, "");

    let fn_name = &f.name;
    let async_kw = if f.is_async { "async " } else { "" };

    // though they are layout-identical via `#[frb(mirror(T))]`.
    let params: Vec<String> = f
        .params
        .iter()
        .map(|p| {
            let rust_ty = frb_rust_type_mirror(&p.ty, p.optional);
            let is_opaque_handle = if let TypeRef::Named(type_name) = &p.ty {
                opaque_type_names.contains(type_name.as_str())
            } else {
                false
            };
            let mut_prefix = if p.is_mut && is_opaque_handle { "mut " } else { "" };
            format!("{mut_prefix}{}: {rust_ty}", p.name)
        })
        .collect();

    let has_error = f.error_type.is_some();
    let (return_ty, has_explicit_return) = if has_error {
        (
            format!("Result<{}, String>", frb_rust_type_mirror(&f.return_type, false)),
            true,
        )
    } else if matches!(f.return_type, TypeRef::Unit) {
        (String::new(), false)
    } else {
        (frb_rust_type_mirror(&f.return_type, false), true)
    };

    out.push_str(&crate::backends::dart::template_env::render(
        "rust_bridge_fn_open.jinja",
        minijinja::context! {
            async_kw => async_kw,
            fn_name => fn_name.as_str(),
            params => params.join(", "),
            return_ty => return_ty.as_str(),
            has_explicit_return => has_explicit_return,
            source_cfg => f.cfg.as_deref().unwrap_or(""),
        },
    ));

    if stub_methods.contains(fn_name) {
        out.push_str(&crate::backends::dart::template_env::render(
            "rust_bridge_stub_body.rs.jinja",
            minijinja::context! {
                fn_name => fn_name.as_str(),
            },
        ));
        return;
    }

    let resolved_path = if f.rust_path.is_empty() {
        format!("{source_crate_name}::{fn_name}")
    } else {
        f.rust_path.replace('-', "_")
    };

    if f.return_sanitized {
        let suppress = if f.params.is_empty() {
            String::new()
        } else {
            let names: Vec<&str> = f.params.iter().map(|p| p.name.as_str()).collect();
            if names.len() == 1 {
                format!("    let _ = {};\n", names[0])
            } else {
                format!("    let _ = ({});\n", names.join(", "))
            }
        };
        let default_value = sanitized_return_default(&f.return_type);
        let body = if has_error {
            format!("{suppress}    Ok({default_value})\n")
        } else {
            format!("{suppress}    {default_value}\n")
        };
        out.push_str(&body);
        out.push_str("}\n");
        return;
    }

    let mut pre_call_bindings: Vec<String> = Vec::new();

    // `#[frb(mirror(T))]`) are received as the local mirror type but the core fn
    let call_args: Vec<String> = f
        .params
        .iter()
        .map(|p| {
            if let TypeRef::Map(_, _) = &p.ty {
                if p.map_is_ahash && p.map_key_is_cow {
                    let bound_name = format!("__{}_ahash", p.name);
                    pre_call_bindings.push(format!(
                        "    let {bound_name} = {}.map(|m| m.into_iter().map(|(k, v)| (std::borrow::Cow::Owned(k), serde_json::Value::String(v))).collect::<ahash::AHashMap<std::borrow::Cow<'static, str>, serde_json::Value>>());",
                        p.name
                    ));
                    return if p.optional && p.is_ref {
                        format!("{bound_name}.as_ref()")
                    } else if p.is_ref {
                        format!("{bound_name}.as_ref().unwrap()")
                    } else {
                        bound_name
                    };
                }
                if p.map_is_btree {
                    let bound_name = format!("__{}_btree", p.name);
                    if p.optional {
                        pre_call_bindings.push(format!(
                            "    let {bound_name} = {}.map(|m| m.into_iter().collect::<std::collections::BTreeMap<String, String>>());",
                            p.name
                        ));
                        return if p.is_ref {
                            format!("{bound_name}.as_ref()")
                        } else {
                            bound_name
                        };
                    }
                    pre_call_bindings.push(format!(
                        "    let {bound_name} = {}.into_iter().collect::<std::collections::BTreeMap<String, String>>();",
                        p.name
                    ));
                    return if p.is_ref {
                        format!("&{bound_name}")
                    } else {
                        bound_name
                    };
                }
            }
            dart_call_arg_with_mirror_transmute(
                p,
                source_crate_name,
                type_paths,
                types_needing_from_conversion,
                opaque_type_names,
            )
        })
        .collect();

    let call = format!("{resolved_path}({})", call_args.join(", "));

    let ret_transform = return_transform(
        &f.return_type,
        source_crate_name,
        type_paths,
        opaque_type_names,
        f.returns_ref,
    );

    let result_cast = if matches!(ret_transform, RetTransform::None) {
        build_primitive_result_cast(&f.return_type, f.returns_ref)
    } else {
        String::new()
    };

    let body = build_body(
        &call,
        &result_cast,
        &ret_transform,
        has_error,
        f.is_async,
        matches!(f.return_type, TypeRef::Unit),
    );

    if !pre_call_bindings.is_empty() {
        for binding in &pre_call_bindings {
            out.push_str(binding);
            out.push('\n');
        }
    }
    out.push_str(&body);
    out.push_str("}\n");
}

/// Build the FRB-friendly parameter type using **local mirror names** (no source-crate prefix).
/// FRB decodes wire bytes into local `crate::T` mirror types and passes them to bridge fns.
pub(crate) fn frb_rust_type_mirror(ty: &TypeRef, optional: bool) -> String {
    let inner = frb_rust_type_mirror_inner(ty);
    if optional { format!("Option<{inner}>") } else { inner }
}

fn frb_rust_type_mirror_inner(ty: &TypeRef) -> String {
    match ty {
        TypeRef::Primitive(p) => frb_rust_type_inner(&TypeRef::Primitive(p.clone())),
        TypeRef::String | TypeRef::Char => "String".to_string(),
        TypeRef::Bytes => "Vec<u8>".to_string(),
        TypeRef::Optional(inner) => format!("Option<{}>", frb_rust_type_mirror_inner(inner)),
        TypeRef::Vec(inner) => format!("Vec<{}>", frb_rust_type_mirror_inner(inner)),
        TypeRef::Map(k, v) => format!(
            "std::collections::HashMap<{}, {}>",
            frb_rust_type_mirror_inner(k),
            frb_rust_type_mirror_inner(v)
        ),
        TypeRef::Named(name) => name.clone(),
        TypeRef::Path => "String".to_string(),
        TypeRef::Unit => "()".to_string(),
        TypeRef::Json => "String".to_string(),
        TypeRef::Duration => "i64".to_string(),
    }
}

/// Build call-site expression for one parameter, transmuting Named mirror types to core types.
///
/// For Named types without sanitized fields, the bridge fn receives the local mirror type
/// (`crate::T`) but the core function expects source-crate `T`. Since `#[frb(mirror(T))]`
/// guarantees identical layout for non-sanitized structs, `unsafe { std::mem::transmute }`
/// is sound and zero-cost for those.
///
/// For Named types with sanitized fields (e.g. a config DTO with `Option<String>`
/// in the mirror but different-sized types in core),
/// we use `SourceT::from(name)` instead to avoid UB from layout mismatches.
fn dart_call_arg_with_mirror_transmute(
    p: &ParamDef,
    source_crate_name: &str,
    type_paths: &std::collections::HashMap<String, String>,
    types_needing_from_conversion: &std::collections::HashSet<String>,
    opaque_type_names: &std::collections::HashSet<String>,
) -> String {
    let name = &p.name;
    let original = p.original_type.as_deref().unwrap_or("");
    let stripped_orig = original
        .trim()
        .trim_start_matches('&')
        .trim_start_matches("mut ")
        .trim();

    if !stripped_orig.is_empty() && stripped_orig.starts_with("Vec(") && stripped_orig.contains("Named(\"(") {
        let tuple_inner = stripped_orig
            .find("Named(\"(")
            .and_then(|start| {
                let rest = &stripped_orig[start + 8..];
                rest.find(")\")")
                    .map(|end| rest[..end].trim_end_matches(')').to_string())
            })
            .unwrap_or_default();
        if tuple_inner.starts_with("PathBuf,") || tuple_inner.starts_with("PathBuf ,") {
            return format!("{name}.into_iter().map(|p| (std::path::PathBuf::from(p), None)).collect::<Vec<_>>()");
        }
        if tuple_inner.starts_with("Vec<u8>,") || tuple_inner.starts_with("Vec<u8> ,") {
            return format!(
                "{{ let _ = {name}; compile_error!(\"alef cannot bridge Vec<(Vec<u8>, ...)> through Dart FRB; configure dart.exclude_functions for this item\") }}"
            );
        }
    }

    if matches!(p.ty, TypeRef::Path) {
        if p.optional {
            if p.is_ref {
                return format!("{name}.as_ref().map(std::path::Path::new)");
            }
            return format!("{name}.map(std::path::PathBuf::from)");
        }
        if p.is_ref {
            return format!("&std::path::PathBuf::from({name})");
        }
        return format!("std::path::PathBuf::from({name})");
    }

    if let TypeRef::Primitive(prim) = &p.ty {
        let target = primitive_name(prim);
        if target != "i64" && target != "f64" && target != "bool" {
            if p.optional {
                return format!("{name}.map(|v| v as {target})");
            }
            return if p.is_ref {
                format!("&({name} as {target})")
            } else {
                format!("{name} as {target}")
            };
        }
    }

    if let TypeRef::Vec(inner) = &p.ty {
        if let TypeRef::Primitive(prim) = inner.as_ref() {
            let target = primitive_name(prim);
            if target != "i64" && target != "f64" && target != "bool" {
                if p.optional {
                    if p.is_ref {
                        return format!(
                            "{name}.as_ref().map(|v| v.iter().map(|x| *x as {target}).collect::<Vec<_>>()).as_deref()"
                        );
                    }
                    return format!("{name}.map(|v| v.into_iter().map(|x| x as {target}).collect::<Vec<_>>())");
                }
                if p.is_ref {
                    return format!("{name}.iter().map(|x| *x as {target}).collect::<Vec<_>>().as_slice()");
                }
                return format!("{name}.into_iter().map(|x| x as {target}).collect::<Vec<_>>()");
            }
        }
    }

    // These use #[frb(opaque)] struct { inner: source::T } pattern, so the bridge fn
    if let TypeRef::Named(type_name) = &p.ty {
        if opaque_type_names.contains(type_name.as_str()) {
            if p.optional {
                if p.is_ref {
                    return format!("{name}.as_ref().map(|h| &h.inner)");
                }
                return format!("{name}.map(|h| h.inner)");
            }
            if p.is_mut {
                return format!("&mut {name}.inner");
            }
            if p.is_ref {
                return format!("&{name}.inner");
            }
            return format!("{name}.inner");
        }
    }

    if let TypeRef::Named(type_name) = &p.ty {
        let core_ty = resolve_core_type(type_name, source_crate_name, type_paths);
        if types_needing_from_conversion.contains(type_name.as_str()) {
            return build_named_in_from(name, type_name, &core_ty, p.is_ref, p.is_mut, p.optional);
        }
        return build_named_in_transmute(name, type_name, &core_ty, p.is_ref, p.is_mut, p.optional);
    }

    if let TypeRef::Vec(inner) = &p.ty {
        if p.is_ref && !p.optional && !matches!(inner.as_ref(), TypeRef::Named(_)) {
            if matches!(inner.as_ref(), TypeRef::String) && p.vec_inner_is_ref {
                return format!("&{name}.iter().map(|s| s.as_str()).collect::<Vec<_>>()");
            }
            return format!("&{name}");
        }
    }

    if let TypeRef::Vec(inner) = &p.ty {
        if let TypeRef::Named(type_name) = inner.as_ref() {
            let core_ty = resolve_core_type(type_name, source_crate_name, type_paths);
            if types_needing_from_conversion.contains(type_name.as_str()) {
                if p.optional {
                    return format!("{name}.map(|v| v.into_iter().map({core_ty}::from).collect::<Vec<_>>())");
                }
                let collected = format!("{name}.into_iter().map({core_ty}::from).collect::<Vec<_>>()");
                return if p.is_ref { format!("&{collected}") } else { collected };
            }
            if p.optional {
                return format!(
                    "{name}.map(|v| v.into_iter().map(|x| unsafe {{ std::mem::transmute::<{type_name}, {core_ty}>(x) }}).collect::<Vec<_>>())"
                );
            }
            if p.is_ref {
                return format!(
                    "unsafe {{ std::slice::from_raw_parts(\
                        std::mem::transmute::<*const {type_name}, *const {core_ty}>({name}.as_ptr()), \
                        {name}.len()) }}"
                );
            }
            if p.is_mut {
                return format!(
                    "unsafe {{ std::slice::from_raw_parts_mut(\
                        std::mem::transmute::<*mut {type_name}, *mut {core_ty}>({name}.as_mut_ptr()), \
                        {name}.len()) }}"
                );
            }
            return format!(
                "{name}.into_iter().map(|x| unsafe {{ std::mem::transmute::<{type_name}, {core_ty}>(x) }}).collect::<Vec<_>>()"
            );
        }
    }

    if let TypeRef::Optional(inner) = &p.ty {
        if matches!(inner.as_ref(), TypeRef::Bytes) && p.is_ref {
            return format!("{name}.as_deref()");
        }
    }

    if let TypeRef::Optional(inner) = &p.ty {
        if let TypeRef::Named(type_name) = inner.as_ref() {
            let core_ty = resolve_core_type(type_name, source_crate_name, type_paths);
            if types_needing_from_conversion.contains(type_name.as_str()) {
                return format!("{name}.map({core_ty}::from)");
            }
            return format!("{name}.map(|v| unsafe {{ std::mem::transmute::<{type_name}, {core_ty}>(v) }})");
        }
    }

    if matches!(p.ty, TypeRef::Json) {
        if p.optional {
            return format!("{name}.as_deref().and_then(|s| serde_json::from_str(s).ok())");
        } else {
            return format!("serde_json::from_str(&{name}).unwrap_or(serde_json::Value::Null)");
        }
    }

    dart_call_arg(p)
}

fn resolve_core_type(
    type_name: &str,
    source_crate_name: &str,
    type_paths: &std::collections::HashMap<String, String>,
) -> String {
    match type_paths.get(type_name) {
        Some(path) => path.clone(),
        None => format!("{source_crate_name}::{type_name}"),
    }
}

/// Emit a From-based conversion for a single Named parameter going INTO the core fn.
///
/// Used when the mirror type has sanitized fields that make transmute unsound.
/// Relies on the generated `From<MirrorT> for CoreT` impl from `emit_from_mirror_to_core_struct`.
fn build_named_in_from(
    name: &str,
    _mirror_name: &str,
    core_ty: &str,
    is_ref: bool,
    is_mut: bool,
    optional: bool,
) -> String {
    if optional {
        return format!("{name}.map({core_ty}::from)");
    }
    if is_mut {
        return format!("&mut {core_ty}::from({name})");
    }
    if is_ref {
        return format!("&{core_ty}::from({name})");
    }
    format!("{core_ty}::from({name})")
}

/// Emit the transmute call for a single Named parameter going INTO the core fn.
fn build_named_in_transmute(
    name: &str,
    mirror_name: &str,
    core_ty: &str,
    is_ref: bool,
    is_mut: bool,
    optional: bool,
) -> String {
    if optional {
        return format!("{name}.map(|v| unsafe {{ std::mem::transmute::<{mirror_name}, {core_ty}>(v) }})");
    }
    if is_mut {
        // SAFETY: MirrorT and CoreT are guaranteed layout-compatible (same fields, repr(C) or
        return format!("unsafe {{ std::mem::transmute::<&mut {mirror_name}, &mut {core_ty}>(&mut {name}) }}");
    }
    if is_ref {
        return format!("unsafe {{ std::mem::transmute::<&{mirror_name}, &{core_ty}>(&{name}) }}");
    }
    format!("unsafe {{ std::mem::transmute::<{mirror_name}, {core_ty}>({name}) }}")
}

/// Describes how to transform the raw core-fn return value into the bridge return value.
///
/// Variants are chosen to keep generated Rust clean under clippy 1.95:
/// no `(|v| ...)(expr)` shapes (`clippy::redundant_closure_call`) and no
/// `.into_iter()` on `&[T]` (`clippy::into_iter_on_ref`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum RetTransform {
    /// No mirror transform needed; the raw call value is used as-is (with optional
    /// `result_cast` suffix appended for primitive/string casts).
    None,
    /// Apply `.map(callable)` to the raw call value. Used for scalar `Named` returns
    /// and for `Result<Named, _>` (the `Ok` arm is mapped). The callable is a bare
    /// path like `MirrorName::from` so clippy::redundant_closure is also satisfied.
    Map(String),
    /// Append a suffix expression directly to the raw call value (e.g.
    /// `.into_iter().map(X::from).collect::<Vec<_>>()`). Used for `Vec<Named>` and
    /// `Option<Named>` returns so the emitted Rust never wraps a closure literal
    /// around the call site.
    Suffix(String),
}

/// Decide how to convert the core-fn return into the bridge return.
///
/// Mirror types may differ in layout from core types (e.g. `Cow<'static, str>` in
/// core vs `String` in mirror), so we rely on the generated `From<CoreT> for MirrorT`
/// impl rather than `mem::transmute`.
fn return_transform(
    ty: &TypeRef,
    _source_crate_name: &str,
    _type_paths: &std::collections::HashMap<String, String>,
    opaque_type_names: &std::collections::HashSet<String>,
    returns_ref: bool,
) -> RetTransform {
    match ty {
        TypeRef::Named(mirror_name) => {
            if opaque_type_names.contains(mirror_name.as_str()) {
                // (never `(closure)(expr)`), so clippy::redundant_closure_call is
                RetTransform::Map(format!("|inner| {mirror_name} {{ inner }}"))
            } else {
                // generated From impl. Emit the bare path so clippy::redundant_closure
                RetTransform::Map(format!("{mirror_name}::from"))
            }
        }
        TypeRef::Vec(inner) => {
            if let TypeRef::Named(mirror_name) = inner.as_ref() {
                if returns_ref {
                    if opaque_type_names.contains(mirror_name.as_str()) {
                        RetTransform::Suffix(
                            ".iter().map(|inner| ".to_string()
                                + mirror_name
                                + " { inner: inner.clone() }).collect::<Vec<_>>()",
                        )
                    } else {
                        RetTransform::Suffix(format!(
                            ".iter().map(|x| {mirror_name}::from(x.clone())).collect::<Vec<_>>()"
                        ))
                    }
                } else if opaque_type_names.contains(mirror_name.as_str()) {
                    RetTransform::Suffix(format!(
                        ".into_iter().map(|inner| {mirror_name} {{ inner }}).collect::<Vec<_>>()"
                    ))
                } else {
                    RetTransform::Suffix(format!(".into_iter().map({mirror_name}::from).collect::<Vec<_>>()"))
                }
            } else {
                RetTransform::None
            }
        }
        TypeRef::Optional(inner) => {
            if let TypeRef::Named(mirror_name) = inner.as_ref() {
                if opaque_type_names.contains(mirror_name.as_str()) {
                    RetTransform::Suffix(format!(".map(|inner| {mirror_name} {{ inner }})"))
                } else {
                    RetTransform::Suffix(format!(".map({mirror_name}::from)"))
                }
            } else {
                RetTransform::None
            }
        }
        _ => RetTransform::None,
    }
}

/// Build a Rust default-value expression for a type sanitized from a core Named type.
///
/// Mirrors `gen_unimplemented_body` in `alef-codegen` for primitive/string returns: a
/// sanitized return collapses the core Named type to `String`/`Option<String>`/etc., and
/// the dart bridge stubs the body because the core value cannot be expressed in the
/// sanitized type without `serde_json::to_string` (which requires Serialize bounds the
/// extract pass cannot verify here).
fn sanitized_return_default(ty: &TypeRef) -> String {
    match ty {
        TypeRef::Unit => "()".to_string(),
        TypeRef::String | TypeRef::Char | TypeRef::Path => "String::new()".to_string(),
        TypeRef::Bytes => "Vec::new()".to_string(),
        TypeRef::Primitive(p) => match p {
            crate::core::ir::PrimitiveType::Bool => "false".to_string(),
            crate::core::ir::PrimitiveType::F32 => "0.0f32".to_string(),
            crate::core::ir::PrimitiveType::F64 => "0.0f64".to_string(),
            _ => "0".to_string(),
        },
        TypeRef::Optional(_) => "None".to_string(),
        TypeRef::Vec(_) => "Vec::new()".to_string(),
        TypeRef::Map(_, _) => "Default::default()".to_string(),
        TypeRef::Duration => "0".to_string(),
        TypeRef::Named(_) | TypeRef::Json => "Default::default()".to_string(),
    }
}

/// Build primitive/string result cast (suffix after the raw value).
/// Skips the cast if source and target types are identical (e.g., bool -> bool).
fn build_primitive_result_cast(ty: &TypeRef, returns_ref: bool) -> String {
    match ty {
        TypeRef::Primitive(prim) => {
            let source = primitive_name(prim);
            let target = frb_rust_type_inner(ty);
            if source == target {
                String::new()
            } else {
                format!(" as {target}")
            }
        }
        TypeRef::Path => ".display().to_string()".to_string(),
        TypeRef::String | TypeRef::Char => ".to_string()".to_string(),
        TypeRef::Optional(inner)
            if matches!(inner.as_ref(), TypeRef::String | TypeRef::Path | TypeRef::Char) && returns_ref =>
        {
            ".map(|v| v.to_string())".to_string()
        }
        TypeRef::Vec(inner) => {
            let iter_method = if returns_ref { "iter" } else { "into_iter" };
            match inner.as_ref() {
                TypeRef::Primitive(prim) => {
                    let target = primitive_name(prim);
                    if target == "f64" || target == "i64" || target == "bool" {
                        String::new()
                    } else {
                        format!(
                            ".{iter_method}().map(|x| x as {}).collect::<Vec<_>>()",
                            frb_rust_type_inner(inner)
                        )
                    }
                }
                TypeRef::Path => {
                    format!(".{iter_method}().map(|p| p.to_string_lossy().into_owned()).collect::<Vec<_>>()")
                }
                TypeRef::String | TypeRef::Char => {
                    format!(".{iter_method}().map(|s| s.to_string()).collect::<Vec<_>>()")
                }
                TypeRef::Vec(inner2) => {
                    if let TypeRef::Primitive(prim) = inner2.as_ref() {
                        let target = primitive_name(prim);
                        let frb_target = frb_rust_type_inner(inner2);
                        if target != frb_target.as_str() {
                            format!(
                                ".{iter_method}().map(|row| row.into_iter().map(|x| x as {frb_target}).collect::<Vec<_>>()).collect::<Vec<_>>()"
                            )
                        } else {
                            String::new()
                        }
                    } else {
                        String::new()
                    }
                }
                _ => String::new(),
            }
        }
        TypeRef::Optional(inner) => match inner.as_ref() {
            TypeRef::String | TypeRef::Path | TypeRef::Char => ".map(|s| s.to_string())".to_string(),
            _ => String::new(),
        },
        _ => String::new(),
    }
}

/// Build the function body string.
///
/// `ret_transform` describes how to convert the raw call value into the bridge
/// return value. When `ret_transform == RetTransform::None`, `result_cast` is used
/// as a plain suffix (for primitives / String).
///
/// The `RetTransform::Suffix(_)` and `RetTransform::Map(_)` branches both produce
/// expressions of the form `<call><suffix>` or `<call>.map(<callable>)` — never
/// `(<closure>)(<call>)` — so the emitted Rust stays clean under clippy 1.95's
/// `redundant_closure_call` lint.
fn build_body(
    call: &str,
    result_cast: &str,
    ret_transform: &RetTransform,
    has_error: bool,
    is_async: bool,
    is_unit_return: bool,
) -> String {
    match ret_transform {
        RetTransform::Map(callable) => {
            let map_fn = callable.as_str();
            if has_error {
                if is_async {
                    return format!("    {call}.await.map({map_fn}).map_err(|e| e.to_string())\n");
                }
                return format!("    {call}.map({map_fn}).map_err(|e| e.to_string())\n");
            }
            // shape (`MirrorName { inner: call }`) avoid clippy::redundant_closure_call.
            let raw = if is_async {
                format!("{call}.await")
            } else {
                call.to_string()
            };
            format!("    {expr}\n", expr = call_callable(map_fn, &raw))
        }
        RetTransform::Suffix(suffix) => {
            let s = suffix.as_str();
            if has_error {
                if is_async {
                    return format!("    {call}.await.map(|v| v{s}).map_err(|e| e.to_string())\n");
                }
                return format!("    {call}.map(|v| v{s}).map_err(|e| e.to_string())\n");
            }
            if is_async {
                return format!("    {call}.await{s}\n");
            }
            format!("    {call}{s}\n")
        }
        RetTransform::None => {
            if has_error {
                if is_async {
                    return format!("    {call}.await.map(|v| v{result_cast}).map_err(|e| e.to_string())\n");
                }
                return format!("    {call}.map(|v| v{result_cast}).map_err(|e| e.to_string())\n");
            }
            if is_unit_return {
                if is_async {
                    return format!("    {call}.await;\n");
                }
                return format!("    {call};\n");
            }
            if is_async {
                if result_cast.is_empty() {
                    return format!("    {call}.await\n");
                }
                return format!("    {call}.await{result_cast}\n");
            }
            if result_cast.is_empty() {
                format!("    {call}\n")
            } else {
                format!("    {call}{result_cast}\n")
            }
        }
    }
}

/// Apply a callable string to a bound identifier without producing a
/// `(closure)(ident)` shape that would trigger `clippy::redundant_closure_call`.
///
/// Recognizes the two shapes `return_transform` emits for `RetTransform::Map`:
/// a bare path (`MirrorName::from`) → `MirrorName::from(v)`, and an opaque-wrap
/// closure (`|inner| MirrorName { inner }`) → `MirrorName { inner: v }`.
fn call_callable(callable: &str, ident: &str) -> String {
    if let Some(rest) = callable.strip_prefix("|inner| ") {
        // direct struct literal so clippy::redundant_closure_call does not fire.
        if let Some(name) = rest.strip_suffix(" { inner }") {
            return format!("{name} {{ inner: {ident} }}");
        }
    }
    format!("{callable}({ident})")
}

#[cfg(test)]
mod tests;