alef 0.106.1

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
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
//! Emits the swift-bridge wrapper newtype structs for IR struct types.
//!
//! `emit_type_wrapper` produces:
//!   - `pub struct T(pub SourceT)` newtype
//!   - `impl T { pub fn new(…) → T }` constructor
//!   - `impl T { pub fn field(&self) → BridgeType }` getters
//!
//! Enum wrappers live in `enums.rs`.

use crate::backends::swift::gen_rust_crate::type_bridge::{
    bridge_result_ok_type_with_handles, bridge_type_enum_aware_ref, enum_from_string_fn_name,
    forces_fallible_enum_bridge, needs_json_bridge, needs_json_bridge_with_handles, swift_bridge_rust_type,
};
use crate::codegen::conversions::helpers::{apply_param_newtype_to_core, is_explicit_newtype};
use crate::codegen::generators::binding_helpers::apply_return_newtype_unwrap;
use crate::core::ir::{PrimitiveType, ReceiverKind, TypeDef, TypeRef};
use crate::core::keywords::swift_ident;
use heck::ToSnakeCase;
use std::collections::{HashMap, HashSet};

/// Emit free function shims for each method on `ty`.
///
/// Each method `fn method_name(&self, param: T) -> Result<R, E>` becomes
/// `pub fn type_name_method_name(client: &TypeName, param: BridgeT) -> Result<BridgeR, String>`.
/// Async methods are emitted as `async fn`s that spawn the work onto the process-wide Tokio
/// runtime (same pattern as function shims).
///
/// The two enum sets are NOT interchangeable and both are required, because the paired
/// `extern "Rust"` declaration (`extern_block::emit_extern_block_for_type_methods`) consults each
/// for a different decision and the two signatures must agree exactly or swift-bridge reports
/// `E0308`: `enum_names` (ALL enums) decides the bridge type — every enum crosses as `String` —
/// while `unit_enum_names` (fieldless variants only) decides both the fallible reverse conversion
/// (`enum_from_string_fn_name`, a helper `enums.rs` emits for unit enums only) and, through
/// `forces_fallible_enum_bridge`, whether the wrapper's return type is forced to `Result`. ~keep
pub(crate) fn emit_type_method_shims(
    ty: &TypeDef,
    _source_crate: &str,
    type_paths: &HashMap<String, String>,
    handle_returned_types: &std::collections::HashSet<String>,
    enum_names: &HashSet<&str>,
    unit_enum_names: &HashSet<&str>,
) -> String {
    let type_snake = ty.name.to_snake_case();
    let type_name = &ty.name;

    let mut out = String::new();

    let mut trait_uses: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
    for method in &ty.methods {
        if method.sanitized {
            continue;
        }
        if let Some(path) = method.trait_source.as_deref() {
            trait_uses.insert(path.to_string());
        }
    }
    for path in &trait_uses {
        out.push_str(&crate::backends::swift::template_env::render(
            "rust_trait_use.rs.jinja",
            minijinja::context! {
                path => path,
            },
        ));
    }
    if !trait_uses.is_empty() {
        out.push('\n');
    }

    for method in &ty.methods {
        if method.sanitized {
            continue;
        }
        if method.is_static {
            continue;
        }
        let method_snake = method.name.to_snake_case();
        let fn_name = format!("{type_snake}_{method_snake}");

        let client_receiver = if matches!(method.receiver, Some(ReceiverKind::RefMut)) {
            format!("client: &mut {type_name}")
        } else {
            format!("client: &{type_name}")
        };
        let mut params_vec: Vec<String> = vec![client_receiver];
        for p in &method.params {
            let bridge_ty = bridge_type_enum_aware_ref(&p.ty, enum_names);
            let bridge_ty = if p.optional && !needs_json_bridge(&p.ty) {
                format!("Option<{bridge_ty}>")
            } else {
                bridge_ty
            };
            let name = swift_ident(&p.name.to_snake_case());
            params_vec.push(format!("{name}: {bridge_ty}"));
        }
        let params_str = params_vec.join(", ");

        // An unrecognised wire string used to `panic!` inside the enum's `_from_swift_string`
        // helper, unwinding across the FFI boundary. That helper now returns `Result<_, String>`,
        // so this wrapper is forced fallible to give the `?` somewhere to go. The paired extern
        // declaration calls the same helper -- see `forces_fallible_enum_bridge`. ~keep
        let forced_fallible =
            method.is_async || forces_fallible_enum_bridge(&method.params, method.error_type.as_ref(), unit_enum_names);

        let return_ty = if method.error_type.is_some() || forced_fallible {
            let ok_ty = bridge_result_ok_type_with_handles(&method.return_type, handle_returned_types);
            if matches!(method.return_type, TypeRef::Unit) {
                "Result<(), String>".to_string()
            } else {
                format!("Result<{ok_ty}, String>")
            }
        } else {
            crate::backends::swift::gen_rust_crate::type_bridge::bridge_type_with_handles(
                &method.return_type,
                handle_returned_types,
            )
        };

        let mut pre_call_bindings: Vec<String> = Vec::new();
        let source_type = |type_name: &str| {
            type_paths
                .get(type_name)
                .cloned()
                .unwrap_or_else(|| type_name.to_string())
                .replace('-', "_")
        };
        let call_args: Vec<String> = method
            .params
            .iter()
            .map(|p| {
                let name = p.name.to_snake_case();
                if p
                    .newtype_wrapper
                    .as_deref()
                    .is_some_and(is_explicit_newtype)
                {
                    let binding_expr = if needs_json_bridge(&p.ty) {
                        let binding_ty = swift_bridge_rust_type(&p.ty);
                        let binding_ty = if p.optional {
                            format!("Option<{binding_ty}>")
                        } else {
                            binding_ty
                        };
                        format!(
                            "::serde_json::from_str::<{binding_ty}>(&{name}).expect(\"valid JSON for {name}\")"
                        )
                    } else {
                        name.clone()
                    };
                    let converted = apply_param_newtype_to_core(&binding_expr, p)
                        .expect("explicit newtype metadata checked above");
                    if p.is_ref {
                        let bound = format!("__{name}_newtype");
                        let mutability = if p.is_mut { "mut " } else { "" };
                        pre_call_bindings.push(format!("    let {mutability}{bound} = {converted};"));
                        if p.optional {
                            return if p.is_mut {
                                format!("{bound}.as_mut()")
                            } else {
                                format!("{bound}.as_ref()")
                            };
                        }
                        return if p.is_mut {
                            format!("&mut {bound}")
                        } else {
                            format!("&{bound}")
                        };
                    }
                    return converted;
                }
                if matches!(&p.ty, TypeRef::Json) {
                    return format!(
                        "serde_json::from_str::<serde_json::Value>(&{name}).unwrap_or(serde_json::Value::Null)"
                    );
                }
                if let TypeRef::Vec(vec_inner) = &p.ty
                    && let TypeRef::Named(n) = vec_inner.as_ref()
                    && unit_enum_names.contains(n.as_str())
                {
                    let fn_name = enum_from_string_fn_name(n);
                    let bound = format!("__{name}_vec_enum");
                    let collect_expr = format!("{name}.into_iter().map(|s| {fn_name}(&s)).collect::<Result<Vec<_>, String>>()");
                    if p.optional {
                        pre_call_bindings.push(format!(
                            "    let {bound} = {name}.map(|values| values.into_iter().map(|s| {fn_name}(&s)).collect::<Result<Vec<_>, String>>()).transpose()?;"
                        ));
                    } else {
                        pre_call_bindings.push(format!("    let {bound} = {collect_expr}?;"));
                    }
                    if p.is_ref {
                        return format!("&{bound}");
                    }
                    return bound;
                }
                // A data-carrying enum has no `__alef_{enum}_from_swift_string` helper to call --
                // `enums.rs` emits that reconstruction only for fieldless enums, since a
                // discriminant-only wire string carries no field data. Such a parameter crosses as
                // JSON instead, exactly as `shims::swift_call_arg` already routes a free
                // function's tagged-enum parameter. ~keep
                if let TypeRef::Vec(vec_inner) = &p.ty
                    && let TypeRef::Named(n) = vec_inner.as_ref()
                    && enum_names.contains(n.as_str())
                {
                    let native_ty = source_type(n);
                    let map_expr = format!(
                        "values.into_iter().map(|s| ::serde_json::from_str::<{native_ty}>(&s).expect(\"valid JSON for {name} element\")).collect::<Vec<_>>()"
                    );
                    if p.optional {
                        return format!("{name}.map(|values| {map_expr})");
                    }
                    if p.is_ref {
                        return format!("&{{ let values = {name}; {map_expr} }}");
                    }
                    return format!("{{ let values = {name}; {map_expr} }}");
                }
                if let TypeRef::Named(n) = &p.ty
                    && enum_names.contains(n.as_str())
                    && !unit_enum_names.contains(n.as_str())
                {
                    let native_ty = source_type(n);
                    let deserialize = |value: &str| {
                        format!("::serde_json::from_str::<{native_ty}>({value}).expect(\"valid JSON for {name}\")")
                    };
                    if p.optional {
                        let converted = format!("{name}.as_ref().map(|value| {})", deserialize("value"));
                        if p.is_ref {
                            return if p.is_mut {
                                format!("{converted}.as_mut()")
                            } else {
                                format!("{converted}.as_ref()")
                            };
                        }
                        return converted;
                    }
                    let converted = deserialize(&format!("&{name}"));
                    if p.is_ref {
                        if p.is_mut {
                            return format!("&mut {converted}");
                        }
                        return format!("&{converted}");
                    }
                    return converted;
                }
                if let TypeRef::Named(n) = &p.ty
                    && unit_enum_names.contains(n.as_str())
                {
                    let fn_name = enum_from_string_fn_name(n);
                    let bound = format!("__{name}_enum");
                    if p.optional {
                        pre_call_bindings.push(format!("    let {bound} = {name}.map(|s| {fn_name}(&s)).transpose()?;"));
                    } else {
                        pre_call_bindings.push(format!("    let {bound} = {fn_name}(&{name})?;"));
                    }
                    if p.is_ref {
                        return format!("&{bound}");
                    }
                    return bound;
                }
                if needs_json_bridge(&p.ty) {
                    let native_ty = swift_bridge_rust_type(&p.ty);
                    return format!("serde_json::from_str::<{native_ty}>(&{name}).expect(\"valid JSON for {name}\")");
                }
                if p.optional
                    && let TypeRef::Named(n) = &p.ty
                    && !unit_enum_names.contains(n.as_str())
                {
                    return format!("{name}.map(|v| v.0)");
                }
                match &p.ty {
                    TypeRef::Named(n) if p.is_ref && !unit_enum_names.contains(n.as_str()) => format!("&{name}.0"),
                    TypeRef::Named(n) if p.is_ref && unit_enum_names.contains(n.as_str()) => format!("&{name}"),
                    TypeRef::Named(n) if !unit_enum_names.contains(n.as_str()) => format!("{name}.0"),
                    TypeRef::Named(n) if unit_enum_names.contains(n.as_str()) => name,
                    TypeRef::String if p.is_ref => format!("&{name}"),
                    TypeRef::Path if p.optional && p.is_ref => {
                        format!("{name}.as_ref().map(::std::path::Path::new)")
                    }
                    TypeRef::Path if p.optional => format!("{name}.map(::std::path::PathBuf::from)"),
                    TypeRef::Path if p.is_ref => format!("::std::path::Path::new(&{name})"),
                    TypeRef::Path => format!("::std::path::PathBuf::from({name})"),
                    TypeRef::Bytes if p.is_ref => format!("&{name}"),
                    TypeRef::Vec(_)
                        if p.is_ref
                            && p.vec_inner_is_ref
                            && matches!(&p.ty, TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::String)) =>
                    {
                        format!("&{name}.iter().map(|s| s.as_str()).collect::<Vec<_>>()")
                    }
                    TypeRef::Vec(_) if p.is_ref => {
                        format!("&{name}")
                    }
                    _ => name,
                }
            })
            .collect();
        let call_args_str = call_args.join(", ");

        let is_owned_receiver = matches!(method.receiver.as_ref(), Some(ReceiverKind::Owned));
        let inner_access = if is_owned_receiver {
            "client.0.clone()"
        } else {
            "client.0"
        };
        let method_call = format!("{inner_access}.{method_snake}({call_args_str})");

        // See `result_ok_needs_json_bridge_with_handles`'s doc comment: only widen the plain
        // json-bridge check with the u64/i64 Result gap when this method's return really is a
        // `Result<_, String>` (matching the `ok_ty` computation above) -- a bare, non-`Result`
        // `u64`/`i64` getter never reaches swift-bridge-ir's panicking path. ~keep
        let is_result_return = method.error_type.is_some() || forced_fallible;
        let json_wrap_ok = needs_json_bridge_with_handles(&method.return_type, handle_returned_types)
            || (is_result_return
                && matches!(
                    &method.return_type,
                    TypeRef::Primitive(PrimitiveType::U64) | TypeRef::Primitive(PrimitiveType::I64)
                ));
        let wrap_return = |source: String| -> String {
            if method.return_newtype_wrapper.is_some() {
                let converted = apply_return_newtype_unwrap(&source, &method.return_newtype_wrapper);
                return if json_wrap_ok {
                    format!("serde_json::to_string(&({converted})).expect(\"serializable return\")")
                } else {
                    converted
                };
            }
            if json_wrap_ok {
                return format!("serde_json::to_string(&({source})).expect(\"serializable return\")");
            }
            match &method.return_type {
                TypeRef::Named(t) => format!("{t}({source})"),
                TypeRef::Optional(inner) => {
                    if let TypeRef::Named(t) = inner.as_ref() {
                        if method.returns_ref {
                            format!("({source}).map(|v| {t}(v.clone()))")
                        } else {
                            format!("({source}).map({t})")
                        }
                    } else {
                        source
                    }
                }
                TypeRef::Vec(inner) if method.returns_ref && matches!(inner.as_ref(), TypeRef::String) => {
                    format!("{source}.iter().map(|s| s.to_string()).collect()")
                }
                TypeRef::Vec(inner) => {
                    if let TypeRef::Named(t) = inner.as_ref() {
                        if method.returns_ref {
                            format!("({source}).iter().map(|v| {t}(v.clone())).collect()")
                        } else {
                            format!("({source}).into_iter().map({t}).collect()")
                        }
                    } else {
                        source
                    }
                }
                TypeRef::String => format!("{source}.to_string()"),
                TypeRef::Path => format!("{source}.to_string_lossy().into_owned()"),
                _ => source,
            }
        };

        let body = if method.is_async {
            let chain = if method.error_type.is_some() {
                let ok_wrap = if method.return_newtype_wrapper.is_some() {
                    let converted = apply_return_newtype_unwrap("v", &method.return_newtype_wrapper);
                    if json_wrap_ok {
                        format!(".map(|v| serde_json::to_string(&({converted})).expect(\"serializable return\"))")
                    } else {
                        format!(".map(|v| {converted})")
                    }
                } else if json_wrap_ok {
                    ".map(|v| serde_json::to_string(&v).expect(\"serializable return\"))".to_string()
                } else {
                    match &method.return_type {
                        TypeRef::Named(t) => format!(".map({t})"),
                        TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Named(_)) => {
                            if let TypeRef::Named(t) = inner.as_ref() {
                                format!(".map(|vec| vec.into_iter().map({t}).collect())")
                            } else {
                                String::new()
                            }
                        }
                        TypeRef::String | TypeRef::Path => ".map(|s| s.to_string())".to_string(),
                        TypeRef::Bytes => ".map(|b| b.to_vec())".to_string(),
                        _ => String::new(),
                    }
                };
                format!("{method_call}.await.map_err(|e| e.to_string()){ok_wrap}")
            } else if forced_fallible {
                format!("Ok({})", wrap_return(format!("{method_call}.await")))
            } else {
                wrap_return(format!("{method_call}.await"))
            };
            // The receiver is borrowed from the Swift object for the duration of the bridged call,
            // but `spawn` needs a `'static` future. Swift keeps its argument alive until the
            // continuation resumes, and the continuation resumes only after this future -- which
            // awaits the spawned task to completion -- returns, so the task never outlives the
            // borrow. swift-bridge never drops the future early. ~keep
            let extend_receiver = match method.receiver {
                Some(ReceiverKind::RefMut) => format!(
                    "    // SAFETY: Swift keeps the receiver alive until this future's task completes.\n    let client: &'static mut {type_name} = unsafe {{ &mut *(client as *mut {type_name}) }};\n"
                ),
                _ => format!(
                    "    // SAFETY: Swift keeps the receiver alive until this future's task completes.\n    let client: &'static {type_name} = unsafe {{ &*(client as *const {type_name}) }};\n"
                ),
            };
            format!(
                "{extend_receiver}    let __alef_task = crate::__alef_tokio_runtime().spawn(async move {{ {chain} }});\n    __alef_task.await.unwrap_or_else(|__alef_join_error| {{\n        Err(format!(\"alef: spawned async task failed: {{__alef_join_error}}\"))\n    }})"
            )
        } else if method.error_type.is_some() {
            let ok_wrap = if method.return_newtype_wrapper.is_some() {
                let converted = apply_return_newtype_unwrap("v", &method.return_newtype_wrapper);
                if json_wrap_ok {
                    format!(".map(|v| serde_json::to_string(&({converted})).expect(\"serializable return\"))")
                } else {
                    format!(".map(|v| {converted})")
                }
            } else if json_wrap_ok {
                ".map(|v| serde_json::to_string(&v).expect(\"serializable return\"))".to_string()
            } else {
                match &method.return_type {
                    TypeRef::Named(t) => format!(".map({t})"),
                    TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Named(_)) => {
                        if let TypeRef::Named(t) = inner.as_ref() {
                            format!(".map(|vec| vec.into_iter().map({t}).collect())")
                        } else {
                            String::new()
                        }
                    }
                    TypeRef::String | TypeRef::Path => ".map(|s| s.to_string())".to_string(),
                    TypeRef::Bytes => ".map(|b| b.to_vec())".to_string(),
                    _ => String::new(),
                }
            };
            format!("    {method_call}.map_err(|e| e.to_string()){ok_wrap}")
        } else if forced_fallible {
            format!("    Ok({})", wrap_return(method_call))
        } else {
            format!("    {}", wrap_return(method_call))
        };
        let bindings_str = if pre_call_bindings.is_empty() {
            String::new()
        } else {
            pre_call_bindings.join("\n") + "\n"
        };
        let body = format!("{bindings_str}{body}");

        let return_clause = if return_ty == "()" {
            String::new()
        } else {
            format!(" -> {return_ty}")
        };
        if let Some(cfg) = ty.cfg.as_deref() {
            out.push_str(&format!("#[cfg({cfg})]\n"));
        }
        out.push_str(&crate::backends::swift::template_env::render(
            "rust_wrapper_free_fn.rs.jinja",
            minijinja::context! {
                fn_name => fn_name,
                params => params_str,
                return_clause => return_clause,
                body => body,
                is_async => method.is_async,
            },
        ));
    }

    out
}

/// Emit wrapper functions for instance methods on first-class (non-opaque) DTOs.
///
/// These wrappers handle JSON marshaling since swift-bridge cannot directly bridge
/// instance methods on value types. Each wrapper:
/// 1. Deserializes the JSON string of `self`
/// 2. Calls the actual method on the deserialized value
/// 3. Serializes the result back to JSON
/// 4. Returns Result<String, String> (JSON result or error)
pub(crate) fn emit_first_class_dto_method_wrappers(
    ty: &TypeDef,
    source_crate: &str,
    type_paths: &HashMap<String, String>,
    _unit_enum_names: &HashSet<&str>,
) -> String {
    if ty.is_opaque {
        return String::new();
    }

    let instance_methods: Vec<_> = ty.methods.iter().filter(|m| !m.sanitized && !m.is_static).collect();
    if instance_methods.is_empty() {
        return String::new();
    }

    let type_name = &ty.name;
    let type_snake = type_name.to_snake_case();
    let core_ty = type_paths
        .get(type_name.as_str())
        .map(|p| p.replace('-', "_"))
        .unwrap_or_else(|| format!("{source_crate}::{type_name}"));
    let mut out = String::new();

    for method in instance_methods {
        let method_snake = method.name.to_snake_case();
        let fn_name = format!("{type_snake}_{method_snake}_from_json");

        let mut params = vec!["json: String".to_string()];
        for p in &method.params {
            let base_ty = match &p.ty {
                TypeRef::Primitive(prim) => format!("{:?}", prim).to_lowercase(),
                TypeRef::String => "String".to_string(),
                TypeRef::Named(n) => n.clone(),
                _ => "String".to_string(),
            };
            // `#[swift_bridge::bridge]` declaration and this impl stay in agreement.
            let ty_str = if p.optional && !needs_json_bridge(&p.ty) {
                format!("Option<{base_ty}>")
            } else {
                base_ty
            };
            let name = p.name.to_snake_case();
            params.push(format!("{name}: {ty_str}"));
        }

        out.push_str(&format!("pub fn {fn_name}("));
        out.push_str(&params.join(", "));
        out.push_str(") -> Result<String, String> {\n");

        let async_uses_transparent_wrapper = method.return_newtype_wrapper.is_some()
            || method.params.iter().any(|param| param.newtype_wrapper.is_some());
        if method.is_async && async_uses_transparent_wrapper {
            out.push_str(&format!(
                "    compile_error!(\"alef cannot safely bridge async first-class DTO method `{}` through Swift; exclude the method from Swift generation\");\n",
                method.name
            ));
            out.push_str("}\n\n");
            continue;
        }

        let self_binding = if matches!(method.receiver, Some(ReceiverKind::RefMut)) {
            "let mut __self"
        } else {
            "let __self"
        };
        out.push_str(&format!(
            "    {self_binding}: {core_ty} = serde_json::from_str(&json)\n"
        ));
        out.push_str(&format!(
            "        .map_err(|e| format!(\"Failed to deserialize {type_name}: {{}}\", e))?;\n"
        ));

        let mut pre_call_bindings = Vec::new();
        let method_call_args: Vec<String> = method
            .params
            .iter()
            .map(|p| {
                let name = p.name.to_snake_case();
                if p.newtype_wrapper.as_deref().is_some_and(is_explicit_newtype) {
                    let binding_expr = if needs_json_bridge(&p.ty) {
                        let binding_ty = swift_bridge_rust_type(&p.ty);
                        let binding_ty = if p.optional {
                            format!("Option<{binding_ty}>")
                        } else {
                            binding_ty
                        };
                        format!("::serde_json::from_str::<{binding_ty}>(&{name}).expect(\"valid JSON for {name}\")")
                    } else {
                        name.clone()
                    };
                    let converted =
                        apply_param_newtype_to_core(&binding_expr, p).expect("explicit newtype metadata checked above");
                    if p.is_ref {
                        let bound = format!("__{name}_newtype");
                        let mutability = if p.is_mut { "mut " } else { "" };
                        pre_call_bindings.push(format!("    let {mutability}{bound} = {converted};\n"));
                        if p.optional {
                            return if p.is_mut {
                                format!("{bound}.as_mut()")
                            } else {
                                format!("{bound}.as_ref()")
                            };
                        }
                        return if p.is_mut {
                            format!("&mut {bound}")
                        } else {
                            format!("&{bound}")
                        };
                    }
                    return converted;
                }
                match &p.ty {
                    TypeRef::Path if p.optional && p.is_ref => {
                        format!("{name}.as_ref().map(::std::path::Path::new)")
                    }
                    TypeRef::Path if p.optional => format!("{name}.map(::std::path::PathBuf::from)"),
                    TypeRef::Path if p.is_ref => format!("::std::path::Path::new(&{name})"),
                    TypeRef::Path => format!("::std::path::PathBuf::from({name})"),
                    TypeRef::String if p.optional && p.is_ref => format!("{name}.as_deref()"),
                    TypeRef::String if p.is_ref => format!("&{name}"),
                    TypeRef::Named(_) if p.optional && p.is_ref => format!("{name}.as_ref()"),
                    TypeRef::Named(_) if p.is_ref => format!("&{name}"),
                    _ => name,
                }
            })
            .collect();
        for binding in pre_call_bindings {
            out.push_str(&binding);
        }
        let __call = format!("__self.{}({})", method.name, method_call_args.join(", "));
        let __call = if method.is_async {
            format!("crate::__alef_tokio_runtime().block_on(async {{ {__call}.await }})")
        } else {
            __call
        };

        if method.error_type.is_some() {
            out.push_str(&format!("    let __result = {__call};\n"));
            if matches!(method.return_type, TypeRef::Unit) {
                // (`let __value = ...` would trip clippy::let_unit_value).
                out.push_str("    __result.map_err(|e| e.to_string())?;\n");
                out.push_str("    Ok(\"{}\".to_string())\n");
            } else {
                out.push_str("    let __value = __result.map_err(|e| e.to_string())?;\n");
                let value = apply_return_newtype_unwrap("__value", &method.return_newtype_wrapper);
                out.push_str(&format!("    serde_json::to_string(&({value}))\n"));
                out.push_str("        .map_err(|e| format!(\"Failed to serialize result: {}\", e))\n");
            }
        } else if matches!(method.return_type, TypeRef::Unit) {
            // value to `let __result` would trip clippy::let_unit_value).
            out.push_str(&format!("    {__call};\n"));
            out.push_str("    Ok(\"{}\".to_string())\n");
        } else {
            out.push_str(&format!("    let __result = {__call};\n"));
            let result = apply_return_newtype_unwrap("__result", &method.return_newtype_wrapper);
            out.push_str(&format!("    serde_json::to_string(&({result}))\n"));
            out.push_str("        .map_err(|e| format!(\"Failed to serialize result: {}\", e))\n");
        }

        out.push_str("}\n\n");
    }

    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::ir::{NewtypeWrapper, NewtypeWrapperMetadata, ParamDef};

    fn transparent_string_wrapper() -> String {
        NewtypeWrapper::encode_explicit(&[NewtypeWrapperMetadata::transparent_string(
            "sample_crate::SecretString",
            "from",
            "into_inner",
            vec![],
        )])
    }

    fn param(name: &str, ty: TypeRef) -> ParamDef {
        ParamDef {
            name: name.to_string(),
            ty,
            ..Default::default()
        }
    }

    fn opaque_type(name: &str, methods: Vec<crate::core::ir::MethodDef>) -> TypeDef {
        TypeDef {
            name: name.to_string(),
            rust_path: format!("sample_crate::{name}"),
            is_opaque: true,
            methods,
            ..Default::default()
        }
    }

    fn async_method(name: &str, receiver: ReceiverKind, error_type: Option<&str>) -> crate::core::ir::MethodDef {
        crate::core::ir::MethodDef {
            name: name.to_string(),
            params: vec![param("req", TypeRef::Named("Request".to_string()))],
            return_type: TypeRef::Named("Response".to_string()),
            error_type: error_type.map(str::to_string),
            is_async: true,
            receiver: Some(receiver),
            ..Default::default()
        }
    }

    /// An async method must be a real `async fn` (the matching extern declaration is `async fn`,
    /// which is what makes the Swift side suspend instead of parking a thread). Its work is spawned
    /// onto the process-wide runtime with a `'static` receiver, only the `JoinHandle` is awaited,
    /// and a failed join becomes `Err(String)` rather than unwinding.
    #[test]
    fn async_method_shim_is_an_async_fn_that_spawns_and_awaits_the_join_handle() {
        let ty = opaque_type(
            "Client",
            vec![
                async_method("chat", ReceiverKind::Ref, Some("ClientError")),
                async_method("infallible", ReceiverKind::Ref, None),
            ],
        );

        let out = emit_type_method_shims(
            &ty,
            "sample_crate",
            &HashMap::new(),
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
        );

        for name in ["client_chat", "client_infallible"] {
            assert!(
                out.contains(&format!(
                    "pub async fn {name}(client: &Client, req: Request) -> Result<Response, String>"
                )),
                "`{name}` must be an `async fn` with a Result return (even when infallible, so a \
                 JoinError has somewhere to land), got:\n{out}"
            );
        }
        assert!(
            !out.contains("block_on"),
            "an async shim must never block a thread on the runtime, got:\n{out}"
        );
        assert!(
            out.contains("crate::__alef_tokio_runtime().spawn(async move {"),
            "the work must be spawned onto the large-stack runtime, got:\n{out}"
        );
        assert!(
            out.contains("let client: &'static Client = unsafe { &*(client as *const Client) };"),
            "spawn needs a 'static receiver, got:\n{out}"
        );
        assert!(
            out.contains("__alef_task.await.unwrap_or_else(|__alef_join_error|"),
            "a join failure must surface as Err(String), got:\n{out}"
        );
    }

    #[test]
    fn async_method_shim_extends_a_mut_receiver_as_static_mut() {
        let ty = opaque_type(
            "Client",
            vec![async_method("chat", ReceiverKind::RefMut, Some("ClientError"))],
        );

        let out = emit_type_method_shims(
            &ty,
            "sample_crate",
            &HashMap::new(),
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
        );

        assert!(
            out.contains("pub async fn client_chat(client: &mut Client,"),
            "got:\n{out}"
        );
        assert!(
            out.contains("let client: &'static mut Client = unsafe { &mut *(client as *mut Client) };"),
            "got:\n{out}"
        );
    }

    #[test]
    fn sync_method_shim_stays_a_plain_fn() {
        let mut method = async_method("chat", ReceiverKind::Ref, Some("ClientError"));
        method.is_async = false;
        let ty = opaque_type("Client", vec![method]);

        let out = emit_type_method_shims(
            &ty,
            "sample_crate",
            &HashMap::new(),
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
        );

        assert!(out.contains("pub fn client_chat("), "got:\n{out}");
        assert!(!out.contains("async") && !out.contains("spawn"), "got:\n{out}");
    }

    #[test]
    fn transparent_string_method_param_and_return_use_explicit_operations() {
        let mut value = param("value", TypeRef::String);
        value.newtype_wrapper = Some(transparent_string_wrapper());
        let method = crate::core::ir::MethodDef {
            name: "replace_secret".to_string(),
            params: vec![value],
            return_type: TypeRef::String,
            return_newtype_wrapper: Some(transparent_string_wrapper()),
            receiver: Some(ReceiverKind::RefMut),
            ..Default::default()
        };
        let ty = opaque_type("Client", vec![method]);

        let out = emit_type_method_shims(
            &ty,
            "sample_crate",
            &HashMap::new(),
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
        );

        assert!(
            out.contains("replace_secret(sample_crate::SecretString::from(value))"),
            "{out}"
        );
        assert!(out.contains(".into_inner()"), "{out}");
        assert!(!out.contains(".to_string()"), "{out}");
    }

    #[test]
    fn first_class_async_transparent_methods_are_explicitly_rejected() {
        let infallible = crate::core::ir::MethodDef {
            name: "async_secret".to_string(),
            return_type: TypeRef::String,
            return_newtype_wrapper: Some(transparent_string_wrapper()),
            receiver: Some(ReceiverKind::Ref),
            is_async: true,
            ..Default::default()
        };
        let fallible = crate::core::ir::MethodDef {
            name: "async_fallible_secret".to_string(),
            return_type: TypeRef::String,
            return_newtype_wrapper: Some(transparent_string_wrapper()),
            receiver: Some(ReceiverKind::Ref),
            is_async: true,
            error_type: Some("SecretError".to_string()),
            ..Default::default()
        };
        let ty = TypeDef {
            name: "Secrets".to_string(),
            rust_path: "sample_crate::Secrets".to_string(),
            methods: vec![infallible, fallible],
            ..Default::default()
        };

        let output = emit_first_class_dto_method_wrappers(&ty, "sample_crate", &HashMap::new(), &HashSet::new());

        assert!(
            output.contains("cannot safely bridge async first-class DTO method `async_secret`"),
            "{output}"
        );
        assert!(
            output.contains("cannot safely bridge async first-class DTO method `async_fallible_secret`"),
            "{output}"
        );
        assert!(!output.contains("block_on(") && !output.contains(".await"), "{output}");
    }

    #[test]
    fn first_class_async_without_transparent_wrappers_keeps_existing_path() {
        let method = crate::core::ir::MethodDef {
            name: "plain_async".to_string(),
            return_type: TypeRef::String,
            receiver: Some(ReceiverKind::Ref),
            is_async: true,
            ..Default::default()
        };
        let ty = TypeDef {
            name: "Plain".to_string(),
            rust_path: "sample_crate::Plain".to_string(),
            methods: vec![method],
            ..Default::default()
        };

        let output = emit_first_class_dto_method_wrappers(&ty, "sample_crate", &HashMap::new(), &HashSet::new());

        assert!(
            output.contains("block_on(async { __self.plain_async().await })"),
            "{output}"
        );
        assert!(!output.contains("compile_error!"), "{output}");
    }

    /// Same defect shape and fix as `shims::tests::infallible_function_with_direct_enum_param_*`,
    /// but for the instance-method wrapper path: an unrecognised wire string used to `panic!`
    /// inside the reverse-conversion helper, which is UB once it unwinds across the swift-bridge
    /// FFI boundary. An infallible method (no `error_type`) with a unit-enum param must have its
    /// wrapper's return type forced to `Result<_, String>` so the `?` in the conversion has
    /// somewhere to go, and the success path wrapped in `Ok(..)`.
    #[test]
    fn infallible_method_with_enum_param_gets_forced_result_return_and_no_panic() {
        let method = crate::core::ir::MethodDef {
            name: "set_mode".to_string(),
            params: vec![param("mode", TypeRef::Named("Mode".to_string()))],
            return_type: TypeRef::Unit,
            receiver: Some(ReceiverKind::RefMut),
            error_type: None,
            ..Default::default()
        };
        let ty = opaque_type("Client", vec![method]);
        let enum_names = HashSet::from(["Mode"]);
        let unit_enum_names = enum_names.clone();
        let handle_returned_types = HashSet::new();
        let type_paths = HashMap::new();

        let out = emit_type_method_shims(
            &ty,
            "sample_crate",
            &type_paths,
            &handle_returned_types,
            &enum_names,
            &unit_enum_names,
        );

        assert!(
            out.contains("-> Result<(), String>"),
            "an infallible method with a fallible enum param conversion must have its wrapper \
             return type forced to Result so the conversion error can propagate, got:\n{out}"
        );
        assert!(
            out.contains(&format!("{}(&mode)?", enum_from_string_fn_name("Mode"))),
            "expected the reverse-conversion call to be `?`-propagated, got:\n{out}"
        );
        assert!(
            out.contains("Ok("),
            "the originally-infallible success path must be wrapped in Ok(..) once the \
             wrapper's return type is forced to Result, got:\n{out}"
        );
        assert!(
            !out.contains("panic!"),
            "must not panic across the FFI boundary, got:\n{out}"
        );
        assert!(
            !out.contains(".expect(\"valid"),
            "must not paper over the fallible conversion with .expect(..) either, got:\n{out}"
        );
    }

    /// A method that is already fallible (`error_type` set) must still `?`-propagate the enum
    /// conversion, without double-wrapping the return type.
    #[test]
    fn fallible_method_with_enum_param_still_propagates_conversion_error() {
        let method = crate::core::ir::MethodDef {
            name: "set_mode".to_string(),
            params: vec![param("mode", TypeRef::Named("Mode".to_string()))],
            return_type: TypeRef::Unit,
            receiver: Some(ReceiverKind::RefMut),
            error_type: Some("ClientError".to_string()),
            ..Default::default()
        };
        let ty = opaque_type("Client", vec![method]);
        let enum_names = HashSet::from(["Mode"]);
        let unit_enum_names = enum_names.clone();
        let handle_returned_types = HashSet::new();
        let type_paths = HashMap::new();

        let out = emit_type_method_shims(
            &ty,
            "sample_crate",
            &type_paths,
            &handle_returned_types,
            &enum_names,
            &unit_enum_names,
        );

        assert!(out.contains("-> Result<(), String>"), "got:\n{out}");
        assert!(
            out.contains(&format!("{}(&mode)?", enum_from_string_fn_name("Mode"))),
            "got:\n{out}"
        );
        assert!(!out.contains("panic!"), "got:\n{out}");
    }

    /// Regression test for the alef CI `generated-output-gate` panic: swift-bridge-ir 0.1.59's
    /// `BridgedType::to_alpha_numeric_underscore_name` (`bridged_type.rs:1986`) has a match arm
    /// for every Rust integer primitive width except `u64`/`i64`; those two fall through to an
    /// unconditional `todo!()`. Every `Result<Ok, String>` alef emits reaches that function
    /// (see `result_ok_needs_json_bridge_with_handles`'s doc comment for why), so declaring
    /// `Result<u64, String>` on a fallible method panicked `alef generate`'s own swift build,
    /// not just a downstream consumer's. Bridging the ok type through JSON avoids the
    /// panicking match arm entirely.
    #[test]
    fn fallible_method_returning_u64_bridges_through_json_not_a_bare_u64() {
        let method = crate::core::ir::MethodDef {
            name: "count".to_string(),
            return_type: TypeRef::Primitive(crate::core::ir::PrimitiveType::U64),
            receiver: Some(ReceiverKind::Ref),
            error_type: Some("ClientError".to_string()),
            ..Default::default()
        };
        let ty = opaque_type("Client", vec![method]);
        let enum_names = HashSet::new();
        let unit_enum_names = enum_names.clone();
        let handle_returned_types = HashSet::new();
        let type_paths = HashMap::new();

        let out = emit_type_method_shims(
            &ty,
            "sample_crate",
            &type_paths,
            &handle_returned_types,
            &enum_names,
            &unit_enum_names,
        );

        assert!(
            out.contains("-> Result<String, String>"),
            "u64 Ok type must be bridged through JSON to dodge swift-bridge-ir's todo!() on \
             u64/i64, got:\n{out}"
        );
        assert!(
            !out.contains("Result<u64, String>"),
            "must never declare the panic-triggering Result<u64, String>, got:\n{out}"
        );
        assert!(
            out.contains("serde_json::to_string(&v)"),
            "the u64 value must be JSON-serialized to match the declared String Ok type, got:\n{out}"
        );
    }

    /// The u64/i64 JSON-bridge in `fallible_method_returning_u64_bridges_through_json_not_a_bare_u64`
    /// is scoped to the `Result` position only: a bare, infallible `u64` return never reaches
    /// swift-bridge-ir's panicking path and must keep its native type.
    #[test]
    fn infallible_method_returning_u64_keeps_native_type() {
        let method = crate::core::ir::MethodDef {
            name: "count".to_string(),
            return_type: TypeRef::Primitive(crate::core::ir::PrimitiveType::U64),
            receiver: Some(ReceiverKind::Ref),
            error_type: None,
            ..Default::default()
        };
        let ty = opaque_type("Client", vec![method]);
        let enum_names = HashSet::new();
        let unit_enum_names = enum_names.clone();
        let handle_returned_types = HashSet::new();
        let type_paths = HashMap::new();

        let out = emit_type_method_shims(
            &ty,
            "sample_crate",
            &type_paths,
            &handle_returned_types,
            &enum_names,
            &unit_enum_names,
        );

        assert!(
            out.contains("-> u64"),
            "an infallible u64 getter must keep its native type, got:\n{out}"
        );
        assert!(
            !out.contains("serde_json::to_string"),
            "an infallible u64 getter must not be JSON-bridged, got:\n{out}"
        );
    }

    /// `emit_type_method_shims` used to take a single enum set, and `gen_rust_crate::mod` handed it
    /// `enum_names` (ALL enums) for a parameter named `unit_enum_names`. A data-carrying enum
    /// parameter therefore reached the unit-enum branch and emitted a call to
    /// `__alef_{enum}_from_swift_string` -- a helper `enums.rs` deliberately emits only for
    /// fieldless enums (`E0425`) -- and, through `forces_fallible_enum_bridge`, forced the wrapper's
    /// return type to `Result` while `extern_block::emit_extern_block_for_type_methods` (fed the
    /// real `unit_enum_names`) declared the infallible one, an `E0308` signature mismatch. A tagged
    /// enum parameter must instead cross as JSON, the route free-function parameters already take.
    #[test]
    fn data_carrying_enum_method_param_bridges_through_json_not_the_unit_enum_helper() {
        let method = crate::core::ir::MethodDef {
            name: "set_routing".to_string(),
            params: vec![param("routing", TypeRef::Named("Routing".to_string()))],
            return_type: TypeRef::Unit,
            receiver: Some(ReceiverKind::RefMut),
            error_type: None,
            ..Default::default()
        };
        let ty = opaque_type("Client", vec![method]);
        let enum_names = HashSet::from(["Routing"]);
        let unit_enum_names: HashSet<&str> = HashSet::new();
        let handle_returned_types = HashSet::new();
        let type_paths = HashMap::from([("Routing".to_string(), "sample_crate::Routing".to_string())]);

        let out = emit_type_method_shims(
            &ty,
            "sample_crate",
            &type_paths,
            &handle_returned_types,
            &enum_names,
            &unit_enum_names,
        );

        assert!(
            out.contains("routing: String"),
            "every enum crosses the bridge as a String, matching the extern declaration, got:\n{out}"
        );
        assert!(
            out.contains("::serde_json::from_str::<sample_crate::Routing>(&routing)"),
            "a data-carrying enum parameter must be deserialized from JSON, got:\n{out}"
        );
        assert!(
            !out.contains(&enum_from_string_fn_name("Routing")),
            "must not call the unit-enum-only from-string helper, which is never emitted for a \
             data-carrying enum, got:\n{out}"
        );
        assert!(
            !out.contains("-> Result<"),
            "a data-carrying enum parameter has no fallible from-string conversion to propagate, \
             so the wrapper must keep the infallible signature the extern block declares, got:\n{out}"
        );
    }

    /// Same defect, same fix, for the `Vec<Enum>` parameter shape: the vector branch also tested
    /// the wrongly-supplied set and mapped every element through the unit-enum-only helper.
    #[test]
    fn data_carrying_enum_vec_method_param_bridges_each_element_through_json() {
        let method = crate::core::ir::MethodDef {
            name: "set_routes".to_string(),
            params: vec![param(
                "routes",
                TypeRef::Vec(Box::new(TypeRef::Named("Routing".to_string()))),
            )],
            return_type: TypeRef::Unit,
            receiver: Some(ReceiverKind::RefMut),
            error_type: None,
            ..Default::default()
        };
        let ty = opaque_type("Client", vec![method]);
        let enum_names = HashSet::from(["Routing"]);
        let unit_enum_names: HashSet<&str> = HashSet::new();
        let handle_returned_types = HashSet::new();
        let type_paths = HashMap::from([("Routing".to_string(), "sample_crate::Routing".to_string())]);

        let out = emit_type_method_shims(
            &ty,
            "sample_crate",
            &type_paths,
            &handle_returned_types,
            &enum_names,
            &unit_enum_names,
        );

        assert!(
            out.contains("routes: Vec<String>"),
            "a Vec of enums crosses as Vec<String>, matching the extern declaration, got:\n{out}"
        );
        assert!(
            out.contains("::serde_json::from_str::<sample_crate::Routing>(&s)"),
            "each element must be deserialized from JSON, got:\n{out}"
        );
        assert!(
            !out.contains(&enum_from_string_fn_name("Routing")),
            "must not call the unit-enum-only from-string helper, got:\n{out}"
        );
        assert!(
            !out.contains("-> Result<"),
            "no fallible conversion is involved, so the infallible signature must be kept, got:\n{out}"
        );
    }
}