alef 0.23.15

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
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
//! Service-API codegen for the Swift backend (bridge-based via swift-bridge 0.1.59).
//!
//! Generates two outputs per [`ServiceDef`] with non-empty registrations:
//!
//! 1. **Rust extern "Rust" declarations** — added to the `#[swift_bridge::bridge] mod ffi`
//!    block in `packages/swift/rust/src/lib.rs`:
//!    - `extern "Rust" { type <ServiceName>; }` — opaque type declaration
//!    - `extern "Rust" { #[swift_bridge(init)] fn new(...) -> <ServiceName>; }`
//!    - `extern "Rust" { fn <configurator>(...); }` per configurator
//!    - `extern "Rust" { fn <register>_via_callback(..., ctx: *mut c_void, callback: extern "C" fn(...) -> *mut u8) -> i32; }`
//!      per registration (C-callback shim)
//!    - `extern "Rust" { fn <run>(...) -> Result<(), String>; }` per entrypoint (blocking, not async)
//!
//! 2. **Swift wrapper class** at `Sources/<ModuleName>/<ServiceName>.swift`:
//!    - Public class wrapping the swift-bridge opaque type
//!    - Idiomatic Swift methods for constructor, configurators, registration (with closure boxing), and entrypoints
//!    - Handler boxes (reference type) to cross closures via C context pointers
//!    - @convention(c) trampolines for C callback interop

use crate::core::backend::GeneratedFile;
use crate::core::config::ResolvedCrateConfig;
use crate::core::ir::{ApiSurface, HandlerContractDef, RegistrationDef, ServiceDef, TypeRef};
use heck::{ToLowerCamelCase, ToSnakeCase};
use std::path::PathBuf;

// ───────────────────────────────────────────────────────────────── helpers ──

fn find_contract<'a>(api: &'a ApiSurface, trait_name: &str) -> Option<&'a HandlerContractDef> {
    api.handler_contracts
        .iter()
        .find(|contract| contract.trait_name == trait_name)
}

/// Format a multi-line Rust doc as a Swift `///` block at the given column
/// indent. Every non-blank line is prefixed with `/// `; blank lines stay as
/// bare `///` so paragraph breaks survive. Includes the trailing newline.
fn format_swift_comment(text: &str, indent: usize) -> String {
    let trimmed = text.trim();
    if trimmed.is_empty() {
        return String::new();
    }
    let pad = " ".repeat(indent);
    let mut out = String::new();
    for line in trimmed.lines() {
        if line.trim().is_empty() {
            out.push_str(&pad);
            out.push_str("///\n");
        } else {
            out.push_str(&pad);
            out.push_str("/// ");
            out.push_str(line);
            out.push('\n');
        }
    }
    out
}

/// Whether an entrypoint's return type can be represented over the C ABI as a function return.
///
/// Unit/primitive/string/bytes map to a status code or scalar; a `Named` type is representable only
/// when this surface wraps it (so it can cross as an opaque handle). Anything else is not representable.
///
/// Also rejects entrypoints whose source method was sanitized — the IR sanitizer maps unknown
/// foreign return types (e.g. `axum::Router`) to `TypeRef::String`, which would otherwise pass
/// the surface check but produce a bridge signature that doesn't match the real Rust method.
fn entrypoint_return_representable(
    ep: &crate::core::ir::EntrypointDef,
    service: &ServiceDef,
    api: &ApiSurface,
) -> bool {
    if let Some(svc_type) = api.types.iter().find(|t| t.name == service.name)
        && let Some(method) = svc_type.methods.iter().find(|m| m.name == ep.method)
        && method.sanitized
    {
        return false;
    }
    match &ep.return_type {
        TypeRef::Unit | TypeRef::String | TypeRef::Char | TypeRef::Primitive(_) | TypeRef::Bytes => true,
        TypeRef::Named(n) => api.types.iter().any(|t| t.name == *n),
        _ => false,
    }
}

/// Map a `TypeRef` to a Swift type string for function parameters.
fn typeref_to_swift_type(ty: &TypeRef) -> String {
    match ty {
        TypeRef::String => "String".to_owned(),
        TypeRef::Char => "Character".to_owned(),
        TypeRef::Primitive(p) => {
            use crate::core::ir::PrimitiveType;
            match p {
                PrimitiveType::Bool => "Bool".to_owned(),
                PrimitiveType::U8 => "UInt8".to_owned(),
                PrimitiveType::U16 => "UInt16".to_owned(),
                PrimitiveType::U32 => "UInt32".to_owned(),
                PrimitiveType::U64 => "UInt64".to_owned(),
                PrimitiveType::I8 => "Int8".to_owned(),
                PrimitiveType::I16 => "Int16".to_owned(),
                PrimitiveType::I32 => "Int32".to_owned(),
                PrimitiveType::I64 => "Int64".to_owned(),
                PrimitiveType::F32 => "Float".to_owned(),
                PrimitiveType::F64 => "Double".to_owned(),
                PrimitiveType::Usize => "Int".to_owned(),
                PrimitiveType::Isize => "Int".to_owned(),
            }
        }
        TypeRef::Bytes => "Data".to_owned(),
        TypeRef::Unit => "Void".to_owned(),
        TypeRef::Named(n) => n.clone(),
        _ => "String".to_owned(), // Json, Vec, Map, etc. go through JSON serialization
    }
}

// ────────────────────────────────────────────────── Rust extern "Rust" output ──

/// Map TypeRef to a Rust FFI type string.
fn typeref_to_rust_ffi_type(ty: &TypeRef) -> String {
    match ty {
        TypeRef::String => "String".to_owned(),
        TypeRef::Primitive(p) => {
            use crate::core::ir::PrimitiveType;
            match p {
                PrimitiveType::Bool => "bool".to_owned(),
                PrimitiveType::U8 => "u8".to_owned(),
                PrimitiveType::U16 => "u16".to_owned(),
                PrimitiveType::U32 => "u32".to_owned(),
                PrimitiveType::U64 => "u64".to_owned(),
                PrimitiveType::I8 => "i8".to_owned(),
                PrimitiveType::I16 => "i16".to_owned(),
                PrimitiveType::I32 => "i32".to_owned(),
                PrimitiveType::I64 => "i64".to_owned(),
                PrimitiveType::F32 => "f32".to_owned(),
                PrimitiveType::F64 => "f64".to_owned(),
                PrimitiveType::Usize => "usize".to_owned(),
                PrimitiveType::Isize => "isize".to_owned(),
            }
        }
        TypeRef::Named(n) => n.clone(),
        _ => "String".to_owned(),
    }
}

/// Collect unique wrapper-constructor extern declarations from all registration variants.
///
/// For each `WrapperConstructorCall` on a `RegistrationVariant` (e.g. `RouteBuilder::new(method, path)`),
/// this emits an extern "Rust" free function declaration like:
///   `fn route_builder_new(method: &Method, path: String) -> RouteBuilder`
///
/// This is needed because swift-bridge represents enums as opaque classes (not mirrored Swift enums),
/// so `Method.Get` is invalid Swift syntax. Instead, the variant shorthand methods call
/// `routeBuilderNew(try methodFromJson("\"Get\""), path)` and delegate to the base registration.
///
/// Returns a deduplicated list of minijinja context values for the template.
fn collect_wrapper_constructor_externs(service: &ServiceDef) -> Vec<minijinja::Value> {
    use crate::core::ir::WrapperConstructorArg;
    use std::collections::HashSet;

    let mut seen: HashSet<String> = HashSet::new();
    let mut result: Vec<minijinja::Value> = Vec::new();

    for reg in &service.registrations {
        for variant in &reg.variants {
            let Some(wc) = &variant.wrapper_call else { continue };
            // Deduplicate by function name (wrapper_type_snake_new).
            let fn_snake = format!("{}_new", wc.wrapper_type_name.to_snake_case());
            if !seen.insert(fn_snake.clone()) {
                continue;
            }
            let fn_camel = fn_snake.to_lower_camel_case();

            // Build argument list for the extern declaration.
            // Fixed args with enum-typed value_expr become `&EnumType` params (opaque ref).
            // Free args become their declared type.
            let args: Vec<minijinja::Value> = wc
                .args
                .iter()
                .map(|arg| match arg {
                    WrapperConstructorArg::Fixed { param_name, value_expr } => {
                        // value_expr is e.g. "source_crate::Method::Get". Extract the type name.
                        // Format is `crate::TypeName::Variant` — split at last `::` twice.
                        let rust_type = if let Some(last_colon) = value_expr.rfind("::") {
                            if let Some(second_colon) = value_expr[..last_colon].rfind("::") {
                                // "source_crate::Method::Get" → "Method"
                                value_expr[second_colon + 2..last_colon].to_string()
                            } else {
                                // "Method::Get" → take before the "::"
                                value_expr[..last_colon].to_string()
                            }
                        } else {
                            value_expr.clone()
                        };
                        // Use `&TypeName` so swift-bridge maps it to `TypeNameRef` (opaque ref param).
                        minijinja::context! {
                            name => param_name,
                            rust_type => format!("&{rust_type}"),
                        }
                    }
                    WrapperConstructorArg::Free { param } => {
                        let rust_type = typeref_to_rust_ffi_type(&param.ty);
                        minijinja::context! {
                            name => &param.name,
                            rust_type => rust_type,
                        }
                    }
                })
                .collect();

            result.push(minijinja::context! {
                fn_snake => &fn_snake,
                fn_camel => fn_camel,
                wrapper_type_name => &wc.wrapper_type_name,
                wrapper_type_path => &wc.wrapper_type_path,
                constructor_method => &wc.constructor_method,
                args => args,
            });
        }
    }

    result
}

/// Generate Rust extern "Rust" declarations for a service (INSIDE the bridge module).
/// These are appended to the `#[swift_bridge::bridge] mod ffi { ... }` block in lib.rs.
/// Registration callbacks are excluded — they go outside the bridge via `generate_rust_callback_c_functions`.
///
/// Split into TWO blocks to work around swift-bridge 0.1.59 parse error ("expected path"):
/// Block 1: Type declaration + constructor
/// Block 2: Instance methods (configurators, entrypoints) using `associated_to` attribute
fn gen_service_rust_extern_blocks(service: &ServiceDef, api: &ApiSurface) -> String {
    // Build configurator list for the template
    let configurators: Vec<minijinja::Value> = service
        .configurators
        .iter()
        .map(|config| {
            let config_snake = config.name.to_snake_case();
            let config_camel = config_snake.to_lower_camel_case();
            minijinja::context! {
                name => &config_snake,
                camel => &config_camel,
            }
        })
        .collect();

    // Build entrypoint list for the template (skip non-representable finalize)
    let entrypoints: Vec<minijinja::Value> = service
        .entrypoints
        .iter()
        .filter(|ep| {
            // Skip finalize entrypoints whose return type can't be represented over the C ABI.
            !matches!(ep.kind, crate::core::ir::EntrypointKind::Finalize)
                || entrypoint_return_representable(ep, service, api)
        })
        .map(|ep| {
            let ep_snake = ep.method.to_snake_case();
            let ep_camel = ep_snake.to_lower_camel_case();
            let params: Vec<minijinja::Value> = ep
                .params
                .iter()
                .map(|p| {
                    minijinja::context! {
                        name => &p.name,
                        rust_type => typeref_to_rust_ffi_type(&p.ty),
                    }
                })
                .collect();

            // Return type. swift-bridge 0.1.59 cannot parse `Result<T, E>` in extern blocks,
            // so error-returning functions return a JSON envelope string instead:
            // `{"ok": <value>}` on success or `{"err": "<message>"}` on failure.
            let return_type = match &ep.return_type {
                TypeRef::Unit => {
                    if ep.error_type.is_some() {
                        "String".to_owned()
                    } else {
                        "()".to_owned()
                    }
                }
                TypeRef::String => "String".to_owned(),
                _ => "String".to_owned(),
            };

            minijinja::context! {
                snake => &ep_snake,
                camel => &ep_camel,
                params => params,
                return_type => return_type,
            }
        })
        .collect();

    // Emit Block 1: Type declaration + constructor
    let mut out = crate::backends::swift::template_env::render(
        "rust_extern_service_type_and_constructor.rs.jinja",
        minijinja::context! {
            service_name => &service.name,
        },
    );

    // Emit Block 2: Methods with associated_to (always — block 2 also carries the
    // `<service>_raw_ptr` helper needed by the @_silgen_name registration shims).
    let service_snake = service.name.to_snake_case();
    let service_camel = service_snake.to_lower_camel_case();

    // Collect unique WrapperConstructorCall signatures from all registration variants.
    // These become `route_builder_new`-style free functions in the extern "Rust" block
    // so Swift can construct wrapper metadata params (e.g. RouteBuilder) without
    // relying on non-existent static enum member syntax (swift-bridge enums are opaque
    // classes, not mirrored Swift enums with static members).
    let wrapper_constructors = collect_wrapper_constructor_externs(service);

    out.push_str(&crate::backends::swift::template_env::render(
        "rust_extern_service_methods.rs.jinja",
        minijinja::context! {
            service_name => &service.name,
            service_snake => &service_snake,
            service_camel => &service_camel,
            configurators => configurators,
            entrypoints => entrypoints,
            wrapper_constructors => wrapper_constructors,
        },
    ));

    out
}

/// Generate plain C functions for callback registration (OUTSIDE the bridge module).
/// These are emitted after the `#[swift_bridge::bridge] mod ffi { ... }` block closes.
fn gen_rust_callback_c_functions_for_service(api: &ApiSurface, service: &ServiceDef) -> String {
    let mut out = String::new();
    let source_crate = api.crate_name.replace('-', "_");
    let service_snake = service.name.to_snake_case();

    for reg in &service.registrations {
        let reg_snake = reg.method.to_snake_case();
        let contract = find_contract(api, &reg.callback_contract);
        let trait_path = contract
            .map(|c| {
                if c.rust_path.is_empty() {
                    format!("{source_crate}::{}", c.trait_name)
                } else {
                    c.rust_path.clone()
                }
            })
            .unwrap_or_else(|| format!("{source_crate}::{}", reg.callback_contract));
        let request_path = contract
            .and_then(|c| c.wire_request_type.as_deref())
            .map(|name| qualify_rust_type(name, &source_crate))
            .unwrap_or_else(|| "serde_json::Value".to_string());
        let response_path = contract
            .and_then(|c| c.wire_response_type.as_deref())
            .map(|name| qualify_rust_type(name, &source_crate))
            .unwrap_or_else(|| "serde_json::Value".to_string());
        let output_type = contract
            .and_then(|c| c.dispatch_return_type.as_deref())
            .map(str::to_owned)
            .unwrap_or_else(|| format!("Result<{response_path}, Box<dyn std::error::Error + Send + Sync>>"));
        let response_adapter = contract
            .and_then(|c| c.response_adapter.as_deref())
            .map(|adapter| format!("{adapter}(outcome)"))
            .unwrap_or_else(|| "outcome".to_string());
        let metadata_params: Vec<minijinja::Value> = reg
            .metadata_params
            .iter()
            .map(|mp| {
                // Named metadata-param types are emitted as swift-bridge wrapper newtypes
                // (`pub struct Foo(pub crate_path::Foo)`), so calling through to the inner
                // service requires `.0` to unwrap. Primitives + String pass through directly.
                let is_opaque_wrapper = matches!(&mp.ty, TypeRef::Named(_));
                minijinja::context! {
                    name => &mp.name,
                    rust_type => typeref_to_rust_ffi_type(&mp.ty),
                    is_opaque_wrapper => is_opaque_wrapper,
                }
            })
            .collect();

        out.push_str(&crate::backends::swift::template_env::render(
            "rust_extern_c_register_via_callback.rs.jinja",
            minijinja::context! {
                service_snake => &service_snake,
                reg_snake => &reg_snake,
                method_name => &reg.method,
                service_name => &service.name,
                source_crate => &source_crate,
                trait_path => &trait_path,
                request_path => &request_path,
                response_path => &response_path,
                output_type => &output_type,
                response_adapter => &response_adapter,
                metadata_params => metadata_params,
            },
        ));
    }

    out
}

// ──────────────────────────────────────────────────────────── Swift output ──

/// Generate the idiomatic Swift service class (`Service.swift`).
///
/// Produces a Swift class that wraps the swift-bridge opaque type and exposes:
/// - A constructor that calls the swift-bridge `_new` function
/// - Configurator methods that chain (return self)
/// - Registration methods that accept Swift closures and wrap them via @convention(c) trampolines
/// - A `run(...)` method that calls the swift-bridge entrypoint
pub(super) fn gen_service_swift(api: &ApiSurface, service: &ServiceDef) -> String {
    let mut out = String::new();

    let class_name = &service.name;
    let service_snake = class_name.to_snake_case();
    let service_camel = service_snake.to_lower_camel_case();

    // File header with Foundation import.
    out.push_str(&crate::backends::swift::template_env::render(
        "swift_file_header.swift.jinja",
        minijinja::Value::from(()),
    ));
    // The wrapper references swift-bridge generated opaque types (`RustBridge.App`,
    // `RouteBuilder`, etc.). Those types live in a sibling Swift target named
    // `RustBridge`; an explicit `import RustBridge` is required for resolution.
    out.push_str("import RustBridge\n\n");

    // Error type used by every generated entrypoint / registration method. Defined
    // once per service file so the wrapper class methods can `throw` it without
    // forcing a separate shared module on consumers.
    out.push_str(
        "/// Errors thrown by service wrapper methods.\n\
         public enum ServiceError: Error {\n\
         \x20\x20\x20\x20/// The service handle was already consumed or never initialised.\n\
         \x20\x20\x20\x20case invalidHandle\n\
         \x20\x20\x20\x20/// The C-side registration call returned a non-zero status code.\n\
         \x20\x20\x20\x20case registrationFailed\n\
         \x20\x20\x20\x20/// The service runtime returned the given error envelope.\n\
         \x20\x20\x20\x20case runtime(String)\n\
         }\n\n",
    );

    // Emit @_silgen_name declarations for callback registration functions (defined outside the bridge module).
    for reg in &service.registrations {
        let reg_snake = reg.method.to_snake_case();
        let metadata_params: Vec<minijinja::Value> = reg
            .metadata_params
            .iter()
            .map(|mp| {
                // The silgen-imported C symbol takes the swift-bridge generated type, which
                // lives in the `RustBridge` sibling target. Named opaque metadata params
                // must therefore be referenced as `RustBridge.<Type>` here, even though the
                // user-facing wrapper class accepts the bridge type directly.
                let swift_ty = typeref_to_swift_type(&mp.ty);
                let bridge_ty = match &mp.ty {
                    TypeRef::Named(n) => format!("RustBridge.{n}"),
                    _ => swift_ty.clone(),
                };
                minijinja::context! {
                    name => &mp.name,
                    swift_type => bridge_ty,
                }
            })
            .collect();

        out.push_str(&crate::backends::swift::template_env::render(
            "swift_silgen_callback.swift.jinja",
            minijinja::context! {
                service_snake => &service_snake,
                reg_snake => &reg_snake,
                metadata_params => metadata_params,
            },
        ));
    }

    // Class header with doc comment
    let doc = if !service.doc.is_empty() {
        format_swift_comment(&service.doc, 0)
    } else {
        String::new()
    };
    out.push_str(&crate::backends::swift::template_env::render(
        "swift_class_header.swift.jinja",
        minijinja::context! {
            class_name => class_name,
            doc => &doc,
        },
    ));

    // Constructor
    out.push_str(&crate::backends::swift::template_env::render(
        "swift_init.swift.jinja",
        minijinja::context! {
            service_snake => &service_snake,
            service_camel => &service_camel,
            service_name => class_name,
        },
    ));

    // Destructor
    out.push_str(&crate::backends::swift::template_env::render(
        "swift_deinit.swift.jinja",
        minijinja::Value::from(()),
    ));

    // Configurator methods (chaining)
    for config in &service.configurators {
        let config_name = &config.name;
        let config_camel = config_name.to_lower_camel_case();
        let doc = if !config.doc.is_empty() {
            format_swift_comment(&config.doc, 4)
        } else {
            String::new()
        };

        out.push_str(&crate::backends::swift::template_env::render(
            "swift_configurator.swift.jinja",
            minijinja::context! {
                service_snake => &service_snake,
                config_name => config_name,
                config_camel => &config_camel,
                doc => &doc,
            },
        ));
    }

    // Registration methods
    for reg in &service.registrations {
        gen_registration_method(&mut out, service, reg, api, &service_snake);
    }

    // Entrypoint methods
    for ep in &service.entrypoints {
        // Skip finalize entrypoints whose return type can't be represented over the C ABI.
        if matches!(ep.kind, crate::core::ir::EntrypointKind::Finalize)
            && !entrypoint_return_representable(ep, service, api)
        {
            continue;
        }
        gen_entrypoint_method(&mut out, service, ep, &service_snake);
    }

    // Class footer
    out.push_str(&crate::backends::swift::template_env::render(
        "swift_class_footer.swift.jinja",
        minijinja::Value::from(()),
    ));

    out
}

fn gen_registration_method(
    out: &mut String,
    _service: &ServiceDef,
    reg: &RegistrationDef,
    _api: &ApiSurface,
    service_snake: &str,
) {
    let method_name = &reg.method;
    let method_camel = method_name.to_lower_camel_case();

    // Build metadata param signature (excluding the callback param). Named opaque
    // metadata params are exposed as their `RustBridge.<Type>` swift-bridge wrapper:
    // the user obtains the value via the bridge module and passes it straight through.
    let meta_params: Vec<String> = reg
        .metadata_params
        .iter()
        .map(|p| {
            let swift_type = match &p.ty {
                TypeRef::Named(n) => format!("RustBridge.{n}"),
                _ => typeref_to_swift_type(&p.ty),
            };
            format!("{}: {}", p.name, swift_type)
        })
        .collect();

    let meta_sig = meta_params.join(", ");

    let doc = if !reg.doc.is_empty() {
        format_swift_comment(&reg.doc, 4)
    } else {
        String::new()
    };

    let metadata_params: Vec<minijinja::Value> = reg
        .metadata_params
        .iter()
        .map(|mp| {
            minijinja::context! {
                name => &mp.name,
            }
        })
        .collect();

    let service_camel = service_snake.to_lower_camel_case();
    out.push_str(&crate::backends::swift::template_env::render(
        "swift_registration.swift.jinja",
        minijinja::context! {
            doc => &doc,
            method_camel => &method_camel,
            meta_params => &meta_sig,
            service_snake => service_snake,
            service_camel => &service_camel,
            method_name => method_name,
            metadata_params => metadata_params,
        },
    ));

    // Emit variant methods
    for variant in &reg.variants {
        gen_registration_variant(out, service_snake, reg, variant);
    }
}

fn gen_registration_variant(
    out: &mut String,
    service_snake: &str,
    reg: &RegistrationDef,
    variant: &crate::core::ir::RegistrationVariant,
) {
    use crate::core::ir::WrapperConstructorArg;

    let variant_name = &variant.name;
    let service_camel = service_snake.to_lower_camel_case();

    // Build signature params with Swift types
    let signature_params: Vec<minijinja::Value> = variant
        .signature_params
        .iter()
        .map(|p| {
            let swift_type = match &p.ty {
                TypeRef::Named(n) => format!("RustBridge.{n}"),
                _ => typeref_to_swift_type(&p.ty),
            };
            minijinja::context! {
                name => &p.name,
                swift_type => swift_type,
            }
        })
        .collect();

    let doc = if let Some(doc_str) = &variant.doc {
        format_swift_comment(doc_str, 4)
    } else {
        // Default doc referencing the base registration
        let default_doc = format!("Shortcut for `{}`.", reg.method);
        format_swift_comment(&default_doc, 4)
    };

    // When the variant has a WrapperConstructorCall, emit a method that:
    //   1. Constructs the wrapper type using the bridge factory (e.g. routeBuilderNew)
    //   2. Delegates to the base Swift registration method (e.g. self.route(handler, builder:))
    //
    // This avoids the invalid `RustBridge.Method.Get` syntax — swift-bridge generates enums as
    // opaque classes, not mirrored Swift enums with static member constants. The
    // `<type>FromJson("\"Variant\"")` factory constructs an opaque instance from its serde
    // wire name, then the wrapper constructor factory combines it with free args.
    if let Some(wrapper_call) = &variant.wrapper_call {
        // Build the argument expression for the wrapper constructor factory call.
        // Fixed args: use `try <TypeFromJson>("\"Variant\"")` factory syntax.
        // Free args: use the param name directly.
        let factory_fn_camel = format!("{}_new", wrapper_call.wrapper_type_name.to_snake_case()).to_lower_camel_case();
        let factory_args: Vec<String> = wrapper_call
            .args
            .iter()
            .map(|arg| match arg {
                WrapperConstructorArg::Fixed {
                    param_name: _,
                    value_expr,
                } => {
                    // value_expr is e.g. "source_crate::Method::Get"
                    // Extract type name and variant name for the from_json factory call.
                    if let Some(last_colon) = value_expr.rfind("::") {
                        let variant_str = &value_expr[last_colon + 2..];
                        if let Some(second_colon) = value_expr[..last_colon].rfind("::") {
                            let type_name = &value_expr[second_colon + 2..last_colon];
                            // type_name "Method" → factory "methodFromJson"
                            let factory_name = format!(
                                "{}FromJson",
                                type_name
                                    .chars()
                                    .next()
                                    .map(|c| c.to_lowercase().to_string())
                                    .unwrap_or_default()
                                    + &type_name[1..]
                            );
                            format!("try {factory_name}(\"\\\"{variant_str}\\\"\")")
                        } else {
                            // Fallback: just the variant name as a string
                            format!("\"{variant_str}\"")
                        }
                    } else {
                        value_expr.clone()
                    }
                }
                WrapperConstructorArg::Free { param } => param.name.clone(),
            })
            .collect();
        let factory_args_str = factory_args.join(", ");
        // The wrapper param name in the base method signature (e.g. "builder" for RouteBuilder).
        let base_param_name = &wrapper_call.metadata_param;
        let base_method_camel = reg.method.to_lower_camel_case();

        out.push_str(&crate::backends::swift::template_env::render(
            "swift_registration_variant_delegate.swift.jinja",
            minijinja::context! {
                doc => &doc,
                variant_name => variant_name,
                signature_params => signature_params,
                factory_fn_camel => factory_fn_camel,
                factory_args_str => factory_args_str,
                wrapper_type_name => &wrapper_call.wrapper_type_name,
                base_param_name => base_param_name,
                base_method_camel => base_method_camel,
            },
        ));
    } else {
        // No wrapper call — fall through to the direct C-callback invocation pattern.
        let wrapper_call_args: Vec<String> = variant.signature_params.iter().map(|p| p.name.clone()).collect();

        out.push_str(&crate::backends::swift::template_env::render(
            "swift_registration_variant.swift.jinja",
            minijinja::context! {
                doc => &doc,
                variant_name => variant_name,
                signature_params => signature_params,
                service_snake => service_snake,
                service_camel => &service_camel,
                base_method_name => &reg.method,
                wrapper_call_args => wrapper_call_args,
            },
        ));
    }
}

fn gen_entrypoint_method(
    out: &mut String,
    _service: &ServiceDef,
    ep: &crate::core::ir::EntrypointDef,
    service_snake: &str,
) {
    let ep_method = &ep.method;
    let ep_camel = ep_method.to_lower_camel_case();

    let doc = if !ep.doc.is_empty() {
        format_swift_comment(&ep.doc, 4)
    } else {
        String::new()
    };

    // Build parameter signature
    let params: Vec<String> = ep
        .params
        .iter()
        .map(|p| {
            let swift_type = typeref_to_swift_type(&p.ty);
            format!("{}: {}", p.name, swift_type)
        })
        .collect();

    let param_sig = if params.is_empty() {
        String::new()
    } else {
        params.join(", ")
    };

    // Return type
    let return_type = if ep.return_type == TypeRef::Unit {
        "Void".to_owned()
    } else {
        typeref_to_swift_type(&ep.return_type)
    };

    let throws_kw = if ep.error_type.is_some() { " throws" } else { "" };

    let ep_params: Vec<minijinja::Value> = ep
        .params
        .iter()
        .map(|p| {
            minijinja::context! {
                name => &p.name,
            }
        })
        .collect();

    out.push_str(&crate::backends::swift::template_env::render(
        "swift_entrypoint.swift.jinja",
        minijinja::context! {
            doc => &doc,
            ep_camel => &ep_camel,
            param_sig => &param_sig,
            throws_kw => throws_kw,
            return_type => &return_type,
            service_snake => service_snake,
            ep_method => ep_method,
            params => ep_params,
            has_error => ep.error_type.is_some(),
            has_return_value => ep.return_type != TypeRef::Unit,
        },
    ));
}

// ─────────────────────────────────────────────────── public entry points ──

/// Generate all service-API files for the Swift backend.
///
/// Returns one `GeneratedFile` per service when services are present:
/// - `{output_dir}/Service.swift` — Swift service class
pub fn generate(api: &ApiSurface, config: &ResolvedCrateConfig) -> anyhow::Result<Vec<GeneratedFile>> {
    if api.services.is_empty() {
        return Ok(vec![]);
    }

    let mut files = Vec::new();

    for service in &api.services {
        if service.registrations.is_empty() {
            continue;
        }

        let module_name = config.swift_module();
        let base_dir =
            crate::core::config::resolve_output_dir(config.output_paths.get("swift"), &config.name, "packages/swift");
        let base_path = PathBuf::from(&base_dir);

        let path = if config.explicit_output.swift.is_some() {
            base_path.join(format!("{}.swift", service.name))
        } else {
            base_path
                .join("Sources")
                .join(&module_name)
                .join(format!("{}.swift", service.name))
        };

        let content = gen_service_swift(api, service);

        files.push(GeneratedFile {
            path,
            content,
            generated_header: true,
        });
    }

    Ok(files)
}

/// Generate Rust extern "Rust" blocks for service-API declarations.
/// These are inserted into the swift-bridge bridge module in the rust crate.
pub fn generate_rust_extern_blocks(api: &ApiSurface) -> anyhow::Result<Vec<String>> {
    let mut blocks = Vec::new();

    for service in &api.services {
        if service.registrations.is_empty() {
            continue;
        }
        blocks.push(gen_service_rust_extern_blocks(service, api));
    }

    Ok(blocks)
}

/// Generate plain C functions for callback registration (OUTSIDE the bridge module).
/// These are emitted after the `#[swift_bridge::bridge] mod ffi { ... }` block closes in lib.rs.
pub fn generate_rust_callback_c_functions(api: &ApiSurface) -> anyhow::Result<Vec<String>> {
    let mut funcs = Vec::new();

    for service in &api.services {
        if service.registrations.is_empty() {
            continue;
        }
        funcs.push(gen_rust_callback_c_functions_for_service(api, service));
    }

    Ok(funcs)
}

fn qualify_rust_type(type_name: &str, source_crate: &str) -> String {
    if type_name.contains("::") {
        type_name.to_string()
    } else {
        format!("{source_crate}::{type_name}")
    }
}

// ───────────────────────────────────────────────────────────────────── tests ──

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::ir::{
        EntrypointDef, EntrypointKind, HandlerContractDef, MethodDef, ParamDef, RegistrationDef, ServiceDef, TypeRef,
    };

    fn make_fixture_surface() -> ApiSurface {
        let constructor = MethodDef {
            name: "new".to_owned(),
            params: vec![],
            return_type: TypeRef::Unit,
            is_async: false,
            is_static: true,
            error_type: None,
            doc: "Create a new service owner.".to_owned(),
            receiver: None,
            sanitized: false,
            trait_source: None,
            returns_ref: false,
            returns_cow: false,
            return_newtype_wrapper: None,
            has_default_impl: false,
            binding_excluded: false,
            binding_exclusion_reason: None,
        };

        let registration = RegistrationDef {
            method: "add_handler".to_owned(),
            callback_param: "handler".to_owned(),
            callback_contract: "RequestHandler".to_owned(),
            metadata_params: vec![ParamDef {
                name: "path".to_owned(),
                ty: TypeRef::String,
                optional: false,
                default: None,
                ..ParamDef::default()
            }],
            receiver: Some(crate::core::ir::ReceiverKind::RefMut),
            return_type: TypeRef::Unit,
            error_type: None,
            doc: "Register a request handler.".to_owned(),
            variants: vec![],
        };

        let run_entrypoint = EntrypointDef {
            method: "run".to_owned(),
            kind: EntrypointKind::Run,
            is_async: false,
            params: vec![ParamDef {
                name: "addr".to_owned(),
                ty: TypeRef::String,
                optional: false,
                default: None,
                ..ParamDef::default()
            }],
            return_type: TypeRef::Unit,
            error_type: Some("IoError".to_owned()),
            doc: "Start the service.".to_owned(),
        };

        let handler_contract = HandlerContractDef {
            trait_name: "RequestHandler".to_owned(),
            rust_path: "my_crate::RequestHandler".to_owned(),
            dispatch: MethodDef {
                name: "handle".to_owned(),
                params: vec![ParamDef {
                    name: "req".to_owned(),
                    ty: TypeRef::Named("RequestData".to_owned()),
                    optional: false,
                    default: None,
                    ..ParamDef::default()
                }],
                return_type: TypeRef::Named("Response".to_owned()),
                is_async: true,
                is_static: false,
                error_type: None,
                doc: "Handle a request.".to_owned(),
                receiver: Some(crate::core::ir::ReceiverKind::Ref),
                sanitized: false,
                trait_source: None,
                returns_ref: false,
                returns_cow: false,
                return_newtype_wrapper: None,
                has_default_impl: false,
                binding_excluded: false,
                binding_exclusion_reason: None,
            },
            optional_methods: vec![],
            wire_request_type: Some("RequestData".to_owned()),
            wire_response_type: Some("Response".to_owned()),
            dispatch_extra_params: vec![],
            wire_param_name: None,
            dispatch_return_type: None,
            response_adapter: None,
            doc: "Handler contract.".to_owned(),
        };

        ApiSurface {
            crate_name: "test_crate".to_owned(),
            version: "1.0.0".to_owned(),
            services: vec![ServiceDef {
                name: "TestService".to_owned(),
                rust_path: "my_crate::TestService".to_owned(),
                constructor,
                configurators: vec![],
                registrations: vec![registration],
                entrypoints: vec![run_entrypoint],
                doc: "Test service.".to_owned(),
                cfg: None,
            }],
            handler_contracts: vec![handler_contract],
            ..ApiSurface::default()
        }
    }

    #[test]
    fn test_gen_service_swift_contains_class() {
        let api = make_fixture_surface();
        let service = &api.services[0];
        let output = gen_service_swift(&api, service);

        assert!(
            output.contains("public final class TestService"),
            "expected `public final class TestService` in output:\n{output}"
        );
    }

    #[test]
    fn test_gen_service_swift_contains_init_and_deinit() {
        let api = make_fixture_surface();
        let service = &api.services[0];
        let output = gen_service_swift(&api, service);

        assert!(
            output.contains("public init()"),
            "expected `public init()` in output:\n{output}"
        );
        assert!(output.contains("deinit"), "expected `deinit` in output:\n{output}");
        assert!(
            output.contains("handlerBoxes.removeAll()"),
            "expected handler box cleanup in deinit:\n{output}"
        );
    }

    #[test]
    fn test_gen_service_swift_boxes_handler() {
        let api = make_fixture_surface();
        let service = &api.services[0];
        let output = gen_service_swift(&api, service);

        assert!(
            output.contains("private final class HandlerBox"),
            "expected HandlerBox reference type:\n{output}"
        );
        assert!(
            output.contains("private var handlerBoxes: [UnsafeMutableRawPointer]"),
            "expected retained-box tracking array:\n{output}"
        );
        assert!(
            output.contains("Unmanaged.passRetained(handlerBox).toOpaque()"),
            "expected the handler box to be retained as the context pointer:\n{output}"
        );
        assert!(
            output.contains("Unmanaged<HandlerBox>.fromOpaque(contextPtr).release()"),
            "expected boxes to be released in deinit:\n{output}"
        );
    }

    #[test]
    fn test_gen_service_swift_contains_registration_method() {
        let api = make_fixture_surface();
        let service = &api.services[0];
        let output = gen_service_swift(&api, service);

        assert!(
            output.contains("public func addHandler"),
            "expected registration method `addHandler`:\n{output}"
        );
        assert!(
            output.contains("@convention(c)"),
            "expected C-compatible closure:\n{output}"
        );
        assert!(
            output.contains("trampolineFunc"),
            "expected C trampoline function:\n{output}"
        );
    }

    #[test]
    fn test_gen_service_swift_contains_context_recovery() {
        let api = make_fixture_surface();
        let service = &api.services[0];
        let output = gen_service_swift(&api, service);

        assert!(
            output.contains("Unmanaged<HandlerBox>.fromOpaque(contextPtr).takeUnretainedValue()"),
            "expected the boxed handler to be recovered from the context pointer:\n{output}"
        );
        assert!(
            output.contains("handlerBox.handler(requestJSON)"),
            "expected the recovered handler to be invoked with the request:\n{output}"
        );
    }

    #[test]
    fn test_gen_service_swift_contains_run_method() {
        let api = make_fixture_surface();
        let service = &api.services[0];
        let output = gen_service_swift(&api, service);

        assert!(
            output.contains("public func run"),
            "expected `run` entrypoint method:\n{output}"
        );
        assert!(
            output.contains("inner.run("),
            "expected instance method call to inner.run():\n{output}"
        );
    }

    #[test]
    fn test_gen_rust_extern_blocks_contains_type_decl() {
        let api = make_fixture_surface();
        let service = &api.services[0];
        let output = gen_service_rust_extern_blocks(service, &api);

        assert!(
            output.contains("type TestService;"),
            "expected opaque type declaration:\n{output}"
        );
        assert!(
            output.contains("extern \"Rust\""),
            "expected extern \"Rust\" block:\n{output}"
        );
    }

    #[test]
    fn test_gen_rust_extern_blocks_excludes_callback_registration() {
        let api = make_fixture_surface();
        let service = &api.services[0];
        let output = gen_service_rust_extern_blocks(service, &api);

        // Callback registration should NOT be in the bridge module
        assert!(
            !output.contains("extern \"C\" fn(*mut std::ffi::c_void, *const u8, usize) -> *mut u8"),
            "expected raw pointer callback signature to be EXCLUDED from bridge module:\n{output}"
        );
        assert!(
            !output.contains("_via_callback"),
            "expected callback-shim registration method to be EXCLUDED from bridge module:\n{output}"
        );
    }

    #[test]
    fn test_generate_rust_callback_c_functions_contains_callback_signature() {
        let api = make_fixture_surface();
        let service = &api.services[0];
        let output = gen_rust_callback_c_functions_for_service(&api, service);

        // Callback registration SHOULD be in the C function output
        assert!(
            output.contains("extern \"C\" fn"),
            "expected extern \"C\" fn in callback C function:\n{output}"
        );
        assert!(
            output.contains("_via_callback"),
            "expected callback-shim function name:\n{output}"
        );
        assert!(
            output.contains("*mut std::ffi::c_void"),
            "expected raw c_void pointer in callback:\n{output}"
        );
        assert!(
            output.contains("#[unsafe(no_mangle)]") || output.contains("#[no_mangle]"),
            "expected #[unsafe(no_mangle)] or #[no_mangle] on extern \"C\" function:\n{output}"
        );
    }

    #[test]
    fn test_gen_rust_extern_blocks_contains_result_return() {
        let api = make_fixture_surface();
        let service = &api.services[0];
        let output = gen_service_rust_extern_blocks(service, &api);

        // Fallible entrypoints return a JSON envelope string (swift-bridge 0.1.59
        // cannot parse Result<T, E> in extern blocks).
        assert!(
            output.contains("-> String") || output.contains("-> Result<(), String>"),
            "expected entrypoint return type (JSON envelope or unit):\n{output}"
        );
    }

    #[test]
    fn test_generate_returns_file_for_non_empty_services() {
        let api = make_fixture_surface();
        let config = ResolvedCrateConfig {
            name: "test_crate".to_owned(),
            ..ResolvedCrateConfig::default()
        };

        let files = generate(&api, &config).expect("generate should not fail");
        assert!(!files.is_empty(), "expected at least one generated file");

        let has_service_file = files.iter().any(|f| {
            f.path
                .file_name()
                .and_then(|n| n.to_str())
                .map(|s| s.ends_with("TestService.swift"))
                .unwrap_or(false)
        });
        assert!(has_service_file, "expected TestService.swift in output");
    }

    #[test]
    fn test_generate_returns_empty_for_no_services() {
        let api = ApiSurface::default();
        let config = ResolvedCrateConfig {
            name: "test_crate".to_owned(),
            ..ResolvedCrateConfig::default()
        };

        let files = generate(&api, &config).expect("generate should not fail");
        assert!(files.is_empty(), "expected no files for surface without services");
    }

    #[test]
    fn test_generate_skips_services_without_registrations() {
        let mut api = make_fixture_surface();
        api.services[0].registrations.clear();

        let config = ResolvedCrateConfig {
            name: "test_crate".to_owned(),
            ..ResolvedCrateConfig::default()
        };

        let files = generate(&api, &config).expect("generate should not fail");
        assert!(files.is_empty(), "expected no files for service without registrations");
    }

    #[test]
    fn test_swift_wrapper_no_dlsym_or_dlopen() {
        let api = make_fixture_surface();
        let service = &api.services[0];
        let output = gen_service_swift(&api, service);

        assert!(
            !output.contains("dlsym"),
            "expected no dlsym (swift-bridge-based, not raw C lookup):\n{output}"
        );
        assert!(
            !output.contains("dlopen"),
            "expected no dlopen (swift-bridge-based, not raw C lookup):\n{output}"
        );
    }

    #[test]
    fn test_rust_extern_blocks_no_raw_symbol_hardcode() {
        let api = make_fixture_surface();
        let service = &api.services[0];
        let output = gen_service_rust_extern_blocks(service, &api);

        // No hardcoded HTTP/framework names — everything from IR
        assert!(
            !output.contains("\"http\""),
            "expected no hardcoded HTTP references:\n{output}"
        );
        assert!(
            !output.contains("\"handler\""),
            "expected no hardcoded handler-trait names:\n{output}"
        );
    }

    #[test]
    fn test_registration_no_empty_leading_comma() {
        let api = make_fixture_surface();
        let service = &api.services[0];
        let output = gen_service_swift(&api, service);

        // Should not have double comma like "(_ handler: ..., , builder: ...)"
        assert!(
            !output.contains(", , "),
            "expected no double comma in registration signature:\n{output}"
        );
    }

    #[test]
    fn test_switch_case_on_own_lines() {
        let api = make_fixture_surface();
        let service = &api.services[0];
        let output = gen_service_swift(&api, service);

        // switch/case should not collapse onto the same line as preceding code
        assert!(
            !output.contains(")        switch"),
            "expected switch on its own line, not collapsed:\n{output}"
        );
        assert!(
            !output.contains("case .success:            break        case .failure"),
            "expected each case on its own line:\n{output}"
        );
    }

    #[test]
    fn test_swift_uses_silgen_not_bridge_method() {
        let api = make_fixture_surface();
        let service = &api.services[0];
        let output = gen_service_swift(&api, service);

        // Should use @_silgen_name'd C function, NOT inner.addHandlerViaCallback()
        assert!(
            !output.contains("inner.addHandlerViaCallback("),
            "expected callback to use @_silgen_name C function, NOT swift-bridge method:\n{output}"
        );
        assert!(
            output.contains("_test_service_add_handler_via_callback("),
            "expected call to @_silgen_name'd C function:\n{output}"
        );
    }

    #[test]
    fn test_swift_contains_silgen_declaration() {
        let api = make_fixture_surface();
        let service = &api.services[0];
        let output = gen_service_swift(&api, service);

        // Should have @_silgen_name declaration at module scope
        assert!(
            output.contains("@_silgen_name(\"test_service_add_handler_via_callback\")"),
            "expected @_silgen_name declaration for callback C function:\n{output}"
        );
        assert!(
            output.contains("private func _test_service_add_handler_via_callback("),
            "expected private func declaration for silgen'd C function:\n{output}"
        );
    }

    #[test]
    fn test_named_metadata_types_preserved() {
        let mut api = make_fixture_surface();
        // Change the metadata param type from String to a Named type
        api.services[0].registrations[0].metadata_params[0].ty = TypeRef::Named("RouteBuilder".to_owned());

        let service = &api.services[0];
        let output = gen_service_swift(&api, service);

        // Should use the swift-bridge wrapper `RustBridge.RouteBuilder` as the type
        // (Named metadata params are owned by the bridge module and must be qualified).
        assert!(
            output.contains("path: RustBridge.RouteBuilder"),
            "expected Named metadata param typed as RustBridge.RouteBuilder, not String:\n{output}"
        );
    }

    #[test]
    fn test_skip_non_representable_finalize() {
        let mut api = make_fixture_surface();
        // Add a finalize entrypoint with a non-representable return type (Vec<String>)
        api.services[0].entrypoints.push(crate::core::ir::EntrypointDef {
            method: "into_router".to_owned(),
            kind: crate::core::ir::EntrypointKind::Finalize,
            is_async: false,
            params: vec![],
            return_type: TypeRef::Vec(Box::new(TypeRef::String)),
            error_type: None,
            doc: "Build the router.".to_owned(),
        });

        let service = &api.services[0];
        let output = gen_service_swift(&api, service);

        // Should not contain intoRouter method
        assert!(
            !output.contains("func intoRouter"),
            "expected finalize with non-representable return to be skipped:\n{output}"
        );
    }

    #[test]
    fn test_rust_extern_has_swift_bridge_names() {
        let api = make_fixture_surface();
        let service = &api.services[0];
        let output = gen_service_rust_extern_blocks(service, &api);

        // Should have #[swift_bridge(swift_name = ...)] attributes in method block
        assert!(
            output.contains("#[swift_bridge(swift_name ="),
            "expected swift_bridge swift_name attribute:\n{output}"
        );
    }
}