alef 0.110.2

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
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
use crate::backends::swift::gen_bindings::zero_arg_default::zero_arg_named_default;
use crate::backends::swift::gen_rust_crate::default_construction::EnumKinds;
use crate::backends::swift::naming::{swift_rust_shim_ident as swift_ident, swift_source_ident as swift_case_ident};
use crate::backends::swift::type_map::SwiftMapper;
use crate::codegen::shared::binding_fields;
use crate::codegen::type_mapper::TypeMapper;
use crate::core::ir::{ApiSurface, DefaultValue, FieldDef, MethodDef, PrimitiveType, TypeDef, TypeRef};
use heck::{AsSnakeCase, ToLowerCamelCase, ToSnakeCase};
use std::collections::HashSet;

pub(super) fn can_emit_first_class_struct(
    ty: &TypeDef,
    _mapper: &SwiftMapper,
    _exclude_fields: &HashSet<String>,
    known_dto_names: &HashSet<String>,
) -> bool {
    !ty.is_opaque
        && ty.has_serde
        && !ty.fields.is_empty()
        && binding_fields(&ty.fields).all(|field| first_class_field_supported(&field.ty, known_dto_names))
        && !ty.fields.iter().all(|f| f.binding_excluded)
}

/// Returns `true` when a field type can be represented as a stored property in a first-class
/// Swift struct and marshaled through the RustBridge FFI layer.
///
/// Accepted:
/// - Primitives and Bool
/// - String
/// - Named(S) where S is a known DTO or enum in the same API
/// - Vec<T> where T is itself accepted (Vec<Primitive>, Vec<String>, Vec<Named(S)>)
/// - Optional<T> (via TypeRef::Optional) where T is accepted — covers Optional<String>,
///   Optional<Primitive>, Optional<Named>, Optional<Vec<T>>
/// - Map<String, V> where V is accepted — a Swift `Dictionary` is `Codable`, `Sendable` and
///   `Hashable`, so it is a valid stored property and a valid Codable enum payload. Accepting it
///   does not change the bridge: `field_needs_json_bridge` already collapses every Map field to
///   one serde_json `String` getter, and `needs_json_bridge_for_swift` already makes the
///   first-class `init(_ rb:)` JSON-decode it, so the wire form is identical either way. The
///   old rejection reasoned about the getter layer, which was never the constraint. ~keep
/// - field.optional = true is handled at the call site; this function only sees the TypeRef
///
/// Rejected (fall through to typealias):
/// - Map whose key is not `String` — Swift's `Dictionary: Codable` emits a JSON *object* only
///   when `Key` is `String` or `Int`; any other key type encodes as a flat array of alternating
///   keys and values, which does not match the serde_json object the bridge getter produces, and
///   the mismatch is silent until decode. `Int` is excluded with the rest because it is
///   reachable only from `isize`, which is not a portable serde map key. A `Named` key is
///   excluded for the same reason, `Hashable` or not: a generated enum is not
///   `CodingKeyRepresentable`, so it also lands in the array encoding. ~keep
/// - Map<String, Json> specifically — `Json` (`serde_json::Value`) is otherwise rejected below,
///   but as a Map *value* it renders as the Codable `JSONValue` stand-in (`swift_field_type`),
///   not the `String` leaf-JSON convention `SwiftMapper::json()` uses everywhere else. A bare
///   `Json` field stays rejected: only the Map-value position has a Codable substitute. ~keep
/// - Path, Bytes, Duration, Char, Json (outside a Map value) — not representable as idiomatic
///   Swift stored props without additional infra
pub(crate) fn first_class_field_supported(ty: &TypeRef, known_dto_names: &HashSet<String>) -> bool {
    match ty {
        TypeRef::Primitive(_) | TypeRef::String => true,
        TypeRef::Named(name) => known_dto_names.contains(name),
        TypeRef::Vec(inner) => first_class_field_supported(inner, known_dto_names),
        TypeRef::Optional(inner) => first_class_field_supported(inner, known_dto_names),
        TypeRef::Map(key, value) => {
            matches!(key.as_ref(), TypeRef::String)
                && (matches!(value.as_ref(), TypeRef::Json) || first_class_field_supported(value, known_dto_names))
        }
        _ => false,
    }
}

/// Swift-side type string for a field, substituting the Codable `JSONValue` stand-in wherever a
/// `Map<String, Json>` value position appears.
///
/// `mapper.map_type` alone renders that value position as `String` (`SwiftMapper::json()`) —
/// correct for a *leaf* `Json` field, which is bridged as a raw, undecoded serde_json string, but
/// wrong here: a `Map<String, Json>` field is JSON-bridged as a whole
/// (`needs_json_bridge_for_swift`), so its value is decoded structurally by the SAME
/// `JSONDecoder().decode(...)` call as the rest of the struct, and `String` throws
/// `DecodingError` on the first non-string JSON value (a number, bool, array, object or null).
/// Everything other than that one shape delegates straight to `mapper.map_type`, so this is a
/// drop-in replacement at every call site that used to read the field's declared Swift type. ~keep
pub(super) fn swift_field_type(mapper: &SwiftMapper, ty: &TypeRef) -> String {
    match ty {
        TypeRef::Map(key, value) if matches!(value.as_ref(), TypeRef::Json) => {
            format!("[{}: JSONValue]", mapper.map_type(key))
        }
        TypeRef::Optional(inner) => format!("{}?", swift_field_type(mapper, inner)),
        TypeRef::Vec(inner) => format!("[{}]", swift_field_type(mapper, inner)),
        other => mapper.map_type(other),
    }
}

/// Whether any first-class-eligible DTO field needs the Codable `JSONValue` support type emitted
/// into the module (see `swift_field_type`). Gated on this rather than emitting `JSONValue`
/// unconditionally: a crate with no `Map<String, Json>` field must stay byte-identical to its
/// pre-existing output, or every crate's snapshot moves for support code nothing calls. ~keep
pub(crate) fn api_needs_json_value_type(api: &ApiSurface, known_dto_names: &HashSet<String>) -> bool {
    fn contains_json_map_value(ty: &TypeRef) -> bool {
        match ty {
            TypeRef::Map(_, value) => matches!(value.as_ref(), TypeRef::Json) || contains_json_map_value(value),
            TypeRef::Optional(inner) | TypeRef::Vec(inner) => contains_json_map_value(inner),
            _ => false,
        }
    }
    api.types
        .iter()
        .filter(|t| known_dto_names.contains(&t.name))
        .flat_map(|t| binding_fields(&t.fields))
        .any(|field| contains_json_map_value(&field.ty))
}

/// A self-reference to `self_name` reached only through Swift-legal indirection (`Vec<Self>` /
/// `Array`, or a Map value) — the same reasoning `struct Node: Codable { var children: [Node] }`
/// relies on: `Array`/`Dictionary` box their elements, so the enclosing type still has a finite
/// size. A *bare* `Named(self_name)` field (or an `Optional<Named(self_name)>`, which Swift's
/// value-type `Optional` does not indirect) is deliberately NOT accepted here — Swift rejects
/// `struct Foo { var next: Foo? }` outright, and this function must not paper over that. Only the
/// fixed-point loop in `compute_first_class_dto_names` calls this, to bootstrap a type's own
/// eligibility past the "referenced name must already be known" rule that would otherwise make
/// self-reference permanently unresolvable.
///
/// `pub(crate)`, not private: the e2e Swift generator's own fixed point
/// (`e2e::codegen::swift::values::build_swift_first_class_map`) must apply the identical
/// bootstrap, or a self-referential DTO (`struct Node { children: Vec<Node> }`) is classified
/// first-class by the binding emitter and opaque by the e2e generator for the exact same IR —
/// the binding emits `public let children: [Node]` while generated e2e assertions still walk it
/// with `.children()` method-call syntax. See
/// `e2e::codegen::swift::self_referential_first_class_tests` for the regression this closes. ~keep
pub(crate) fn is_self_reference_through_indirection(ty: &TypeRef, self_name: &str) -> bool {
    match ty {
        TypeRef::Vec(inner) => {
            matches!(inner.as_ref(), TypeRef::Named(n) if n == self_name)
                || is_self_reference_through_indirection(inner, self_name)
        }
        TypeRef::Map(_, value) => {
            matches!(value.as_ref(), TypeRef::Named(n) if n == self_name)
                || is_self_reference_through_indirection(value, self_name)
        }
        TypeRef::Optional(inner) => is_self_reference_through_indirection(inner, self_name),
        _ => false,
    }
}

/// Compute the set of struct/enum type names that are emitted as first-class Swift Codable
/// values (structs or serde enums), via the same fixed-point iteration used when emitting
/// them in `emit`.
///
/// A type is first-class iff it is non-opaque, has serde, non-trait, non-excluded, has visible
/// fields, and every visible field's type is first-class-supported given the growing set — OR is
/// a self-reference reached only through `Vec<Self>`/Map-value indirection
/// (`is_self_reference_through_indirection`), which the growing-set check alone can never satisfy
/// since a type's own name cannot enter `known` before it does. Unit serde enums and data-variant
/// (tagged/untagged) serde enums seed the set — they are Codable and may appear as fields.
///
/// This is the authoritative classifier shared by the Swift binding emitter (`gen_bindings`) and
/// the swift-bridge Rust-crate getter emitter (`gen_rust_crate`): a `Vec<Named>` getter is
/// JSON-degraded to `Vec<String>` only when the *containing* type is first-class (its Codable
/// wrapper decodes the JSON); an opaque-rendered parent must return a real `Vec<Opaque>` so the
/// opaque element accessors resolve.
pub(crate) fn compute_first_class_dto_names(api: &ApiSurface, exclude_types: &HashSet<String>) -> HashSet<String> {
    let unit_serde_enum_names = api
        .enums
        .iter()
        .filter(|e| !exclude_types.contains(&e.name))
        .filter(|e| e.has_serde && e.variants.iter().all(|v| v.fields.is_empty()))
        .map(|e| e.name.clone());
    let data_variant_serde_enum_names = api
        .enums
        .iter()
        .filter(|e| !exclude_types.contains(&e.name))
        .filter(|e| e.has_serde && e.variants.iter().any(|v| !v.fields.is_empty()))
        .map(|e| e.name.clone());

    let candidate_types: Vec<&TypeDef> = api
        .types
        .iter()
        .filter(|t| !t.is_trait && !t.is_opaque && t.has_serde && !exclude_types.contains(&t.name))
        .filter(|t| !t.fields.is_empty())
        .collect();

    let mut known: HashSet<String> = unit_serde_enum_names.chain(data_variant_serde_enum_names).collect();
    loop {
        let prev_len = known.len();
        for ty in &candidate_types {
            if known.contains(&ty.name) {
                continue;
            }
            if binding_fields(&ty.fields).all(|field| {
                first_class_field_supported(&field.ty, &known)
                    || is_self_reference_through_indirection(&field.ty, &ty.name)
            }) {
                known.insert(ty.name.clone());
            }
        }
        if known.len() == prev_len {
            break;
        }
    }
    known
}

/// Emits a first-class Swift struct (`public struct Foo: Codable, Sendable, Hashable`)
/// for a non-opaque DTO that has serde derives and at least one field.
///
/// Layer 1: public struct declaration with `public let` stored properties,
///          memberwise `public init` with default-nil optionals, and `CodingKeys`
///          when field names differ from their wire (serde snake_case) keys.
/// Layer 2: `internal extension Foo` with `init(_ rb: RustBridge.Foo) throws` and
///          `func intoRust() throws -> RustBridge.Foo` for FFI marshaling.
#[allow(clippy::too_many_arguments)]
pub(super) fn emit_first_class_struct(
    ty: &TypeDef,
    mapper: &SwiftMapper,
    exclude_fields: &HashSet<String>,
    known_dto_names: &HashSet<String>,
    zero_arg_constructible_names: &HashSet<String>,
    unit_enum_names: &HashSet<String>,
    untagged_enum_names: &HashSet<String>,
    serde_struct_names: &HashSet<String>,
    error_type_name: &str,
    configured_features: &std::collections::HashSet<&str>,
    out: &mut String,
) {
    let type_name = &ty.name;
    let type_snake = AsSnakeCase(type_name.as_str()).to_string();

    let visible_fields: Vec<_> = binding_fields(&ty.fields).collect();
    let mut properties = String::new();
    for field in &visible_fields {
        super::client::emit_doc_comment(&field.doc, "    ", &mut properties);
        let camel = swift_case_ident(&field.name.to_lower_camel_case());
        let already_optional = matches!(&field.ty, TypeRef::Optional(_));
        let swift_ty = swift_field_type(mapper, &field.ty);
        let property_type = if field.optional && !already_optional {
            format!("{swift_ty}?")
        } else {
            swift_ty
        };
        properties.push_str(&crate::backends::swift::template_env::render(
            "swift_struct_property.swift.jinja",
            crate::alef_context! {
                name => camel,
                ty => property_type,
            },
        ));
    }

    let params: Vec<String> = visible_fields
        .iter()
        .map(|field| {
            let camel = swift_case_ident(&field.name.to_lower_camel_case());
            let already_optional = matches!(&field.ty, TypeRef::Optional(_));
            let swift_ty = swift_field_type(mapper, &field.ty);
            // The Rust default, when it has a Swift literal, beats the `nil`/required rendering
            // below. `Option<T>` carrying `Some(x)` reaches the IR as the bare literal (the
            // extractor unwraps `Some`), so without this an `Option<u32>` defaulting to
            // `Some(30)` initialised to `nil` — a value the source crate never produces.
            // Collection type-zeros are also exact for `Empty` and bare `serde(default)`, keeping
            // newly added collection fields backward-compatible for Swift callers. ~keep
            let literal = super::zero_arg_default::swift_memberwise_default_literal(field);
            let optional_suffix = if field.optional && !already_optional { "?" } else { "" };
            match literal {
                Some(value) => format!("{camel}: {swift_ty}{optional_suffix} = {value}"),
                None if field.optional || already_optional => format!("{camel}: {swift_ty}{optional_suffix} = nil"),
                None => format!("{camel}: {swift_ty}"),
            }
        })
        .collect();
    let init_params = params.join(", ");
    let mut init_assignments = String::new();
    for field in &visible_fields {
        let camel = swift_case_ident(&field.name.to_lower_camel_case());
        init_assignments.push_str(&crate::backends::swift::template_env::render(
            "swift_self_assignment.swift.jinja",
            crate::alef_context! {
                field => camel,
                expr => camel,
            },
        ));
    }

    let needs_coding_keys = ty.has_default
        || visible_fields.iter().any(|field| {
            let camel = field.name.to_lower_camel_case();
            // `#[serde(rename)]` / `#[serde(rename_all)]`, even if the camelCased identifier matches.
            camel != field.name || field.serde_rename.is_some() || ty.serde_rename_all.is_some()
        });
    let mut coding_keys = String::new();
    if needs_coding_keys {
        for field in &visible_fields {
            let camel = swift_case_ident(&field.name.to_lower_camel_case());
            // `call_type` with `#[serde(rename = "type")]` must decode from `"type"`, not `"call_type"`).
            let wire_key = crate::codegen::naming::wire_field_name(
                &field.name,
                field.serde_rename.as_deref(),
                ty.serde_rename_all.as_deref(),
            );
            coding_keys.push_str(&crate::backends::swift::template_env::render(
                "swift_coding_key.swift.jinja",
                crate::alef_context! {
                    name => camel,
                    wire_key => wire_key,
                },
            ));
        }
    }

    // Custom `init(from decoder:)` when the Rust source has `#[derive(Default)]` or
    // `#[serde(default)]` / `#[serde(skip_serializing_if = ...)]` decode successfully.
    let mut decoder_init = String::new();
    if super::decoder_gate::needs_decoder_init(ty) {
        emit_decoder_init(
            mapper,
            &visible_fields,
            zero_arg_constructible_names,
            ty.has_default,
            &mut decoder_init,
        );
    }

    let mut ffi_init_assignments = String::new();
    for field in &visible_fields {
        let swift_field = swift_case_ident(&field.name.to_lower_camel_case());
        let rust_accessor = swift_ident(&field.name.to_lower_camel_case());
        let is_optional = field.optional || matches!(&field.ty, TypeRef::Optional(_));

        let expr = if is_field_unbridgeable_for_init(ty, field, exclude_fields, known_dto_names) {
            if is_optional {
                "nil".to_string()
            } else {
                let swift_ty = mapper.map_type(&field.ty);
                format!("try JSONDecoder().decode({swift_ty}.self, from: Data(\"null\".utf8))")
            }
        } else if field.optional && matches!(field.ty, TypeRef::Vec(_)) {
            let swift_ty = mapper.map_type(&field.ty);
            let accessor_with_chain = format!("rb.{rust_accessor}().toString()");
            format!(
                "try JSONDecoder().decode({swift_ty}?.self, from: \
                 (({accessor_with_chain}).data(using: .utf8) ?? Data(\"null\".utf8)))"
            )
        } else if is_vec_of_serde_struct(&field.ty, serde_struct_names) {
            let swift_ty = mapper.map_type(&field.ty);
            let swift_ty_with_opt = if is_optional && !matches!(&field.ty, TypeRef::Optional(_)) {
                format!("{swift_ty}?")
            } else {
                swift_ty
            };

            let field_is_optional = is_optional || matches!(&field.ty, TypeRef::Optional(_));
            let inner_vec_named: Option<&str> = match &field.ty {
                TypeRef::Vec(inner) => match inner.as_ref() {
                    TypeRef::Named(name) => Some(name.as_str()),
                    _ => None,
                },
                TypeRef::Optional(opt_inner) => match opt_inner.as_ref() {
                    TypeRef::Vec(inner) => match inner.as_ref() {
                        TypeRef::Named(name) => Some(name.as_str()),
                        _ => None,
                    },
                    _ => None,
                },
                _ => None,
            };

            if field_is_optional {
                let accessor_with_chain = format!("rb.{rust_accessor}().toString()");
                format!(
                    "try JSONDecoder().decode({swift_ty_with_opt}.self, from: \
                     (({accessor_with_chain}).data(using: .utf8) ?? Data(\"null\".utf8)))"
                )
            } else if let Some(inner_struct_name) = inner_vec_named {
                format!(
                    "try rb.{rust_accessor}().map {{ (s: RustStringRef) -> {inner_struct_name} in \
                     let d = s.as_str().toString().data(using: .utf8) ?? Data(); \
                     return try JSONDecoder().decode({inner_struct_name}.self, from: d) }}"
                )
            } else {
                format!("rb.{rust_accessor}()")
            }
        } else if is_untagged_enum_type(&field.ty, untagged_enum_names) {
            // Untagged-enum field (`#[serde(untagged)]`): the swift-bridge accessor returns a
            let swift_ty = mapper.map_type(&field.ty);
            let swift_ty_with_opt = if is_optional && !matches!(&field.ty, TypeRef::Optional(_)) {
                format!("{swift_ty}?")
            } else {
                swift_ty
            };
            let accessor_with_chain = if is_optional {
                format!("rb.{rust_accessor}()?.toString() ?? \"null\"")
            } else {
                format!("rb.{rust_accessor}().toString()")
            };
            format!(
                "try JSONDecoder().decode({swift_ty_with_opt}.self, from: \
                 (({accessor_with_chain}).data(using: .utf8) ?? Data(\"null\".utf8)))"
            )
        } else if needs_json_bridge_for_swift(&field.ty) {
            let swift_ty = swift_field_type(mapper, &field.ty);
            let swift_ty_with_opt = if is_optional && !matches!(&field.ty, TypeRef::Optional(_)) {
                format!("{swift_ty}?")
            } else {
                swift_ty
            };
            let accessor_with_chain = format!("rb.{rust_accessor}().toString()");
            format!(
                "try JSONDecoder().decode({swift_ty_with_opt}.self, from: \
                 (({accessor_with_chain}).data(using: .utf8) ?? Data(\"null\".utf8)))"
            )
        } else {
            swift_ffi_read_expr(
                &field.ty,
                is_optional,
                &rust_accessor,
                known_dto_names,
                unit_enum_names,
                untagged_enum_names,
                error_type_name,
            )
        };
        ffi_init_assignments.push_str(&crate::backends::swift::template_env::render(
            "swift_self_assignment.swift.jinja",
            crate::alef_context! {
                field => swift_field,
                expr => expr,
            },
        ));
    }

    // when the swift-bridge `#[swift_bridge(init)] fn new(...)` extern is emitted for
    let mut into_rust_body = String::new();
    let all_enum_names: HashSet<&str> = unit_enum_names
        .iter()
        .chain(untagged_enum_names.iter())
        .map(String::as_str)
        .collect();
    let unit_enum_names: HashSet<&str> = unit_enum_names.iter().map(String::as_str).collect();
    let direct_call = emit_into_rust_direct_call(
        ty,
        mapper,
        exclude_fields,
        type_name,
        configured_features,
        EnumKinds::new(&all_enum_names, &unit_enum_names),
    );
    match direct_call {
        Some(call) => into_rust_body.push_str(&call),
        None => {
            let from_json_fn = format!("{type_snake}_from_json").to_lower_camel_case();
            into_rust_body.push_str("        let data = try JSONEncoder().encode(self)\n");
            into_rust_body.push_str("        let json = String(data: data, encoding: .utf8) ?? \"{}\"\n");
            into_rust_body.push_str(&crate::backends::swift::template_env::render(
                "swift_into_rust_json_return.swift.jinja",
                crate::alef_context! {
                    from_json_fn => from_json_fn,
                },
            ));
        }
    }

    let property_names: std::collections::HashSet<String> = visible_fields
        .iter()
        .map(|field| swift_case_ident(&field.name.to_lower_camel_case()))
        .collect();

    let (instance_methods, _static_methods) = crate::codegen::shared::partition_methods(&ty.methods);
    let mut methods_source = String::new();
    for method in instance_methods {
        if method.sanitized || method.is_static {
            continue;
        }
        // A stored property and a nullary method with the same name land in the same struct
        // body, and Swift rejects that with `invalid redeclaration of 'name()'`. The property
        // is emitted first and wins. A method taking at least one argument has a distinct
        // selector (`name(arg:)`) and compiles fine, so only nullary methods are dropped. ~keep
        if method.params.is_empty() && property_names.contains(&swift_case_ident(&method.name.to_lower_camel_case())) {
            continue;
        }
        emit_instance_method_for_first_class_struct(method, type_name, mapper, &mut methods_source);
    }

    out.push_str(&crate::backends::swift::template_env::render(
        "first_class_struct.swift.jinja",
        crate::alef_context! {
            type_name => type_name,
            properties => properties,
            init_params => init_params,
            init_assignments => init_assignments,
            coding_keys => coding_keys,
            decoder_init => decoder_init,
            ffi_init_assignments => ffi_init_assignments,
            into_rust_body => into_rust_body,
            methods => methods_source,
        },
    ));
}

/// Renders a typed `DefaultValue` into a Swift literal expression suitable for use as
/// a `??` fallback. Returns `None` for variants that have no direct Swift literal
/// (`Empty`, `None`, `EnumVariant`, `FunctionCall`, `PublicFunctionCall`).
///
/// A `None` is *not* an invitation to substitute a type-based zero: only `Empty`/`None` mean
/// "the type's own default". The other three mean "there is a default whose value is not in the
/// IR", and the callers in this module keep the field required rather than answering them with a
/// zero — see [`emit_decoder_init`]. ~keep
///
/// `FloatLiteral` values that are NaN or infinite are also rejected so generated code
/// stays parseable — callers handle those by falling back to a type-based default.
///
/// `pub(crate)` rather than `pub(super)` so other backends' tests can use it as the reference
/// rendering of a `DefaultValue` in a cross-language agreement check: it is suffix-free and
/// covers bool, int, float, string and list, which makes it the cheapest oracle in the tree for
/// "did this backend keep the Rust default at all".
pub(crate) fn swift_typed_default_literal(dv: &DefaultValue) -> Option<String> {
    match dv {
        // Every element must render or the whole collection falls back to a type-based default,
        // the same all-or-nothing rule the extractor applies when lowering the literal. ~keep
        DefaultValue::ListLiteral(items) => items
            .iter()
            .map(swift_typed_default_literal)
            .collect::<Option<Vec<String>>>()
            .map(|values| format!("[{}]", values.join(", "))),
        DefaultValue::BoolLiteral(true) => Some("true".to_string()),
        DefaultValue::BoolLiteral(false) => Some("false".to_string()),
        DefaultValue::IntLiteral(n) => Some(n.to_string()),
        // `{f}` on a whole-valued f64 prints `1`, which is an *integer* literal in Swift, and the
        // non-finite values print as `NaN`/`inf`, which name nothing. Both rules live in
        // `float_literal_digits` so the oracle and the Java/Kotlin/C# emitters cannot drift. ~keep
        DefaultValue::FloatLiteral(f) => crate::codegen::shared::float_literal_digits(*f),
        DefaultValue::StringLiteral(s) => {
            let mut escaped = String::with_capacity(s.len() + 2);
            escaped.push('"');
            for ch in s.chars() {
                match ch {
                    '\\' => escaped.push_str("\\\\"),
                    '"' => escaped.push_str("\\\""),
                    '\n' => escaped.push_str("\\n"),
                    '\r' => escaped.push_str("\\r"),
                    '\t' => escaped.push_str("\\t"),
                    c => escaped.push(c),
                }
            }
            escaped.push('"');
            Some(escaped)
        }
        DefaultValue::EnumVariant(_) => None,
        DefaultValue::Empty
        | DefaultValue::Unresolved(_)
        | DefaultValue::TupleVariant(..)
        | DefaultValue::StructVariant(..)
        | DefaultValue::None
        | DefaultValue::FunctionCall(_)
        | DefaultValue::PublicFunctionCall(_) => None,
    }
}

/// Returns a Swift literal expression for the "natural" default of a `TypeRef`, used
/// as a fallback when the field has `typed_default = Empty/None` or no typed default
/// at all.
///
/// Returns `None` for `Named(_)`, `Bytes`, `Path`, `Duration`, `Json`, `Char`, `Unit` —
/// the caller then emits a plain `decode(T.self, ...)` which relies on the nested
/// type's own decoder.
pub(crate) fn swift_type_based_default(ty: &TypeRef) -> Option<String> {
    match ty {
        TypeRef::Primitive(prim) => match prim {
            PrimitiveType::Bool => Some("false".to_string()),
            PrimitiveType::U8
            | PrimitiveType::I8
            | PrimitiveType::U16
            | PrimitiveType::I16
            | PrimitiveType::U32
            | PrimitiveType::I32
            | PrimitiveType::U64
            | PrimitiveType::I64
            | PrimitiveType::Usize
            | PrimitiveType::Isize => Some("0".to_string()),
            PrimitiveType::F32 | PrimitiveType::F64 => Some("0".to_string()),
        },
        TypeRef::String => Some("\"\"".to_string()),
        TypeRef::Vec(_) => Some("[]".to_string()),
        TypeRef::Map(_, _) => Some("[:]".to_string()),
        TypeRef::Optional(_) => Some("nil".to_string()),
        _ => None,
    }
}

/// Emits a custom `public init(from decoder: any Decoder) throws` body that uses
/// `decodeIfPresent + ?? <fallback>` for every field whose Rust default has a Swift literal or
/// (via `zero_arg_named_default`) a zero-arg `Named` initializer (Optional fields included —
/// `Some(x)` reaches the IR as the literal for `x`), `decodeIfPresent ?? nil` for Optional fields
/// with no such fallback, and plain `decode(T.self, ...)` for non-Optional fields with none
/// (e.g. an enum, or the defaults whose value alef cannot see at all).
pub(crate) fn emit_decoder_init(
    mapper: &SwiftMapper,
    visible_fields: &[&FieldDef],
    zero_arg_constructible_names: &HashSet<String>,
    every_field_may_be_absent: bool,
    out: &mut String,
) {
    out.push_str("    public init(from decoder: any Decoder) throws {\n");
    out.push_str("        let container = try decoder.container(keyedBy: CodingKeys.self)\n");
    for field in visible_fields {
        let camel = swift_case_ident(&field.name.to_lower_camel_case());
        let already_optional = matches!(&field.ty, TypeRef::Optional(_));
        let is_optional = field.optional || already_optional;
        let swift_ty = swift_field_type(mapper, &field.ty);

        let literal = field.typed_default.as_ref().and_then(swift_typed_default_literal);

        if is_optional {
            let inner_ty = swift_ty.strip_suffix('?').unwrap_or(&swift_ty);
            // `Option<T>` defaulting to `Some(x)` reaches the IR as the bare literal for `x`, so
            // decoding an absent key as `nil` would substitute a value the source crate never
            // produces. Only a genuinely absent literal keeps the `?? nil` rendering. ~keep
            match &literal {
                Some(fb) => out.push_str(&crate::backends::swift::template_env::render(
                    "swift_decode_default_assignment.swift.jinja",
                    crate::alef_context! {
                        field => camel,
                        ty => inner_ty,
                        fallback => fb,
                    },
                )),
                None => out.push_str(&crate::backends::swift::template_env::render(
                    "swift_decode_optional_assignment.swift.jinja",
                    crate::alef_context! {
                        field => camel,
                        ty => inner_ty,
                    },
                )),
            }
            continue;
        }

        // ~keep A fallback answers the question "what if this key is absent?", so it is only
        // reachable for a field that can actually be absent. `every_field_may_be_absent` carries
        // the `has_default` convention (backends treat a `Default`-implementing type as
        // all-fields-optional); beyond it, serde omits a key only for
        // `skip_serializing_if` or a field-level `default`. Without this guard, routing a type
        // here for one skippable field silently made its *required* siblings lenient too --
        // `DocumentNode.id`, which the source crate always writes, decoded an absent key as `""`.
        let may_be_absent =
            every_field_may_be_absent || field.serde_skip_serializing_if || field.typed_default.is_some();
        let fallback = may_be_absent
            .then(|| {
                literal.or_else(|| {
                    // The type-based zero is only a legitimate stand-in when the Rust default *is* the
                    // type's own default. `FunctionCall`/`PublicFunctionCall` (a `#[serde(default =
                    // "path")]` whose body alef never sees), `EnumVariant` (whose enum path the
                    // extractor discards), `Unresolved` (an `impl Default` body alef could not
                    // constant-fold), and `TupleVariant`/`StructVariant` (a resolved enum-variant
                    // default this renderer has no per-argument Swift expression for) all mean "there is
                    // a default and it is not this zero"; answering them with `0`/`""`/`false` is a
                    // silent disagreement with the source crate. Emitting the plain required `decode`
                    // instead makes an absent key throw a `DecodingError` the caller can see. ~keep
                    if matches!(
                        field.typed_default,
                        Some(
                            DefaultValue::FunctionCall(_)
                                | DefaultValue::PublicFunctionCall(_)
                                | DefaultValue::EnumVariant(_)
                                | DefaultValue::Unresolved(_)
                                | DefaultValue::TupleVariant(..)
                                | DefaultValue::StructVariant(..)
                        )
                    ) {
                        return None;
                    }
                    zero_arg_named_default(&field.typed_default, &field.ty, &swift_ty, zero_arg_constructible_names)
                        .or_else(|| swift_type_based_default(&field.ty))
                })
            })
            .flatten();

        match fallback {
            Some(fb) => {
                out.push_str(&crate::backends::swift::template_env::render(
                    "swift_decode_default_assignment.swift.jinja",
                    crate::alef_context! {
                        field => camel,
                        ty => swift_ty,
                        fallback => fb,
                    },
                ));
            }
            None => {
                out.push_str(&crate::backends::swift::template_env::render(
                    "swift_decode_required_assignment.swift.jinja",
                    crate::alef_context! {
                        field => camel,
                        ty => swift_ty,
                    },
                ));
            }
        }
    }
    out.push_str("    }\n");
}

/// Returns the Swift body of `intoRust()` as a direct `RustBridge.{Type}(...)` call when
/// every constructor field can be converted without JSON, or `None` when at least one
/// field requires the JSON fallback (e.g. JSON-bridged Map/Json fields, types without a
/// Default impl that prevent the bulk constructor extern from being emitted).
///
/// Conversions supported in this PoC:
/// - Primitive (Int/UInt/Bool/Float/Double): pass `self.{camel}` directly.
/// - String: pass `self.{camel}` (Swift `String` conforms to swift-bridge's `IntoRustString`).
/// - Named(struct): recurse via `try self.{camel}.intoRust()`.
/// - Vec<Primitive | String | Named>: build a `RustVec<T>` and push each converted element.
/// - Optional<Primitive | String>: pass `self.{camel}` (swift-bridge handles native nullable).
///
/// Returns `None` for anything else (Map, Json, Path, Bytes, Duration, Char, Optional<Vec>,
/// Optional<Named>, Vec<Vec<...>>) so the caller can use the JSON fallback.
pub(super) fn emit_into_rust_direct_call(
    ty: &TypeDef,
    _mapper: &SwiftMapper,
    exclude_fields: &HashSet<String>,
    type_name: &str,
    configured_features: &std::collections::HashSet<&str>,
    enum_kinds: EnumKinds<'_, '_>,
) -> Option<String> {
    use crate::backends::swift::gen_rust_crate::extern_block::{constructor_fields, has_lossless_constructor_extern};

    if !has_lossless_constructor_extern(ty, exclude_fields, configured_features, enum_kinds) {
        return None;
    }

    let ctor_fields = constructor_fields(ty, exclude_fields, configured_features);
    let visible_count = ty.fields.iter().filter(|f| !f.binding_excluded).count();
    if ctor_fields.len() != visible_count {
        return None;
    }

    let mut prelude = String::new();
    let mut args: Vec<String> = Vec::with_capacity(ctor_fields.len());
    for field in &ctor_fields {
        let camel = swift_case_ident(&field.name.to_lower_camel_case());
        let local = format!("__{}", field.name.to_lower_camel_case());
        match field_intorust_arg(&field.ty, field.optional, &camel, &local) {
            Some(FieldArg::Direct(expr)) => args.push(expr),
            Some(FieldArg::WithPrelude { prelude: p, arg }) => {
                prelude.push_str(&p);
                args.push(arg);
            }
            None => return None,
        }
    }

    let mut body = String::new();
    body.push_str(&prelude);
    body.push_str(&crate::backends::swift::template_env::render(
        "swift_bridge_constructor_return.swift.jinja",
        crate::alef_context! {
            type_name => type_name,
            constructor_suffix => if ty.legacy_constructor_fields().is_empty() { "" } else { ".new_with_fields" },
            args => args.join(", "),
        },
    ));
    Some(body)
}

/// One field's contribution to the `RustBridge.{Type}(...)` argument list.
pub(super) enum FieldArg {
    /// Inline expression — no temporaries needed (`self.foo`, etc.).
    Direct(String),
    /// Multi-statement prelude that materialises a temporary, plus the argument
    /// referencing that temporary (`__foo`).
    WithPrelude { prelude: String, arg: String },
}

/// Translate a single field into a `RustBridge.{Type}(...)` argument.
///
/// Returns `None` when the field's Swift type cannot yet be passed directly to the
/// swift-bridge convenience init (Map, Json, Path, Bytes, Duration, Char, etc.) — the
/// caller falls back to the JSON roundtrip.
pub(super) fn field_intorust_arg(
    ty: &TypeRef,
    field_optional: bool,
    self_property: &str,
    local: &str,
) -> Option<FieldArg> {
    let (inner_ty, is_optional) = match ty {
        TypeRef::Optional(inner) => (inner.as_ref(), true),
        _ => (ty, field_optional),
    };

    match inner_ty {
        TypeRef::Primitive(_) => Some(FieldArg::Direct(format!("self.{self_property}"))),

        TypeRef::String if !is_optional => Some(FieldArg::Direct(format!("RustString(self.{self_property})"))),
        TypeRef::String => Some(FieldArg::Direct(format!("self.{self_property}.map(RustString.init)"))),

        TypeRef::Named(_) if !is_optional => Some(FieldArg::Direct(format!("try self.{self_property}.intoRust()"))),

        TypeRef::Vec(elem) if !is_optional => emit_vec_arg(elem, self_property, local),

        _ => None,
    }
}

/// Emit a `RustVec<U>` materialisation prelude and the argument referencing it.
///
/// Supports inner types: Primitive (`RustVec<Int>` etc.), String (`RustVec<RustString>`,
/// because swift-bridge's `Vectorizable` is implemented for `RustString` not `String`),
/// and Named (`RustVec<RustBridge.Foo>` via per-element `intoRust()`).
pub(super) fn emit_vec_arg(elem: &TypeRef, self_property: &str, local: &str) -> Option<FieldArg> {
    let (rust_vec_param, elem_expr): (String, String) = match elem {
        TypeRef::Primitive(prim) => {
            let swift_prim = SwiftMapper.primitive(prim).into_owned();
            (swift_prim, "__elem".to_string())
        }
        TypeRef::String => ("RustString".to_string(), "RustString(__elem)".to_string()),
        TypeRef::Named(name) => (format!("RustBridge.{name}"), "try __elem.intoRust()".to_string()),
        _ => return None,
    };

    let prelude = format!(
        "        let {local} = RustVec<{rust_vec_param}>()\n        \
         for __elem in self.{self_property} {{ {local}.push(value: {elem_expr}) }}\n",
    );
    Some(FieldArg::WithPrelude {
        prelude,
        arg: local.to_string(),
    })
}

/// Returns the Swift expression to read a field value from a `RustBridge` accessor call.
///
/// swift-bridge exposes Rust struct fields as method calls: `.field_name()`.
///
/// Type-specific conversions:
/// - `String` → `.toString()` (RustString → Swift String)
/// - `Named(S)` → `try S(rb.field())` (RustBridge.S → first-class Swift struct via init)
/// - `Vec<String>` → `rb.field().map { $0.toString() }` (RustVec<RustString> → [String])
/// - `Vec<Primitive>` → `Array(rb.field())` (RustVec<T> → [T], RustVec is a Collection)
/// - `Vec<Named(S)>` → `try rb.field().map { try S($0) }` (RustVec<RustBridge.S> → [S])
/// - Optional variants use `?` chains accordingly.
///
/// `field_optional` is true when `field.optional == true` (extractor-unwrapped IR form).
/// `TypeRef::Optional(inner)` is the TypeRef-wrapped form — both are handled.
pub(super) fn swift_ffi_read_expr(
    ty: &TypeRef,
    field_optional: bool,
    accessor: &str,
    known_dto_names: &HashSet<String>,
    unit_enum_names: &HashSet<String>,
    untagged_enum_names: &HashSet<String>,
    error_type_name: &str,
) -> String {
    let opt = field_optional && !matches!(ty, TypeRef::Optional(_));

    match ty {
        TypeRef::String if opt => format!("rb.{accessor}()?.toString()"),
        TypeRef::String => format!("rb.{accessor}().toString()"),

        TypeRef::Named(name) if unit_enum_names.contains(name) && opt => {
            format!("rb.{accessor}().flatMap {{ {name}(rawValue: $0.toString()) }}")
        }
        TypeRef::Named(name) if unit_enum_names.contains(name) => {
            format!(
                "try {{ let rawValue = rb.{accessor}().toString(); \
                 guard let value = {name}(rawValue: rawValue) else {{ \
                 throw {error_type_name}.validation(message: \"Unknown {name} variant\", source: rawValue) \
                 }}; return value }}()"
            )
        }

        TypeRef::Named(name) if known_dto_names.contains(name) && !untagged_enum_names.contains(name) && opt => {
            format!("try rb.{accessor}().map {{ try {name}($0) }}")
        }
        TypeRef::Named(name) if known_dto_names.contains(name) && !untagged_enum_names.contains(name) => {
            format!("try {name}(rb.{accessor}())")
        }

        TypeRef::Vec(inner) if opt => match inner.as_ref() {
            TypeRef::Primitive(_) => format!("rb.{accessor}().map {{ Array($0) }}"),
            TypeRef::String => format!("rb.{accessor}()?.map {{ $0.as_str().toString() }}"),
            TypeRef::Named(name) if untagged_enum_names.contains(name) => {
                format!(
                    "try rb.{accessor}()?.map {{ (s: RustStringRef) -> {name} in \
                         let d = s.as_str().toString().data(using: .utf8) ?? Data(); \
                         return try JSONDecoder().decode({name}.self, from: d) }}"
                )
            }
            TypeRef::Named(name) if known_dto_names.contains(name) => {
                format!("try rb.{accessor}()?.map {{ try {name}($0) }}")
            }
            _ => {
                let map_expr = vec_elem_convert_expr(inner, known_dto_names);
                format!("rb.{accessor}()?.map {{ {map_expr} }}")
            }
        },
        TypeRef::Vec(inner) => match inner.as_ref() {
            TypeRef::Primitive(_) => format!("Array(rb.{accessor}())"),
            TypeRef::String => format!("rb.{accessor}().map {{ $0.as_str().toString() }}"),
            TypeRef::Named(name) if untagged_enum_names.contains(name) => {
                format!(
                    "try rb.{accessor}().map {{ (s: RustStringRef) -> {name} in \
                     let d = s.as_str().toString().data(using: .utf8) ?? Data(); \
                     return try JSONDecoder().decode({name}.self, from: d) }}"
                )
            }
            TypeRef::Named(name) if known_dto_names.contains(name) => {
                format!("try rb.{accessor}().map {{ try {name}($0) }}")
            }
            _ => format!("rb.{accessor}()"),
        },

        TypeRef::Optional(inner) => match inner.as_ref() {
            TypeRef::String => format!("rb.{accessor}()?.toString()"),
            TypeRef::Named(name) if unit_enum_names.contains(name) => {
                format!("rb.{accessor}().flatMap {{ {name}(rawValue: $0.toString()) }}")
            }
            TypeRef::Named(name) if known_dto_names.contains(name) && !untagged_enum_names.contains(name) => {
                format!("try rb.{accessor}().map {{ try {name}($0) }}")
            }
            TypeRef::Vec(elem) => match elem.as_ref() {
                TypeRef::String => format!("rb.{accessor}()?.map {{ $0.as_str().toString() }}"),
                TypeRef::Named(name) if known_dto_names.contains(name) && !untagged_enum_names.contains(name) => {
                    format!("try rb.{accessor}()?.map {{ try {name}($0) }}")
                }
                TypeRef::Primitive(_) => format!("rb.{accessor}().map {{ Array($0) }}"),
                _ => format!("rb.{accessor}()"),
            },
            _ => format!("rb.{accessor}()"),
        },

        _ => format!("rb.{accessor}()"),
    }
}

/// Returns the element-level Swift expression used in a `.map { ... }` closure when
/// converting a `RustVec<T>` element to its first-class Swift equivalent.
pub(super) fn vec_elem_convert_expr(inner: &TypeRef, known_dto_names: &HashSet<String>) -> String {
    match inner {
        TypeRef::String => "$0.as_str().toString()".to_string(),
        TypeRef::Named(name) if known_dto_names.contains(name) => format!("try {name}($0)"),
        TypeRef::Primitive(_) => "$0".to_string(),
        _ => "$0".to_string(),
    }
}

fn is_untagged_enum_type(ty: &TypeRef, untagged_enum_names: &HashSet<String>) -> bool {
    match ty {
        TypeRef::Named(n) => untagged_enum_names.contains(n),
        TypeRef::Optional(inner) => is_untagged_enum_type(inner, untagged_enum_names),
        _ => false,
    }
}

/// Returns true when `ty` is a `Vec<Named(struct)>` or `Option<Vec<Named(struct)>>` where
/// the struct has serde derives. These are JSON-bridged at the Rust boundary and need
/// JSON decoding on the Swift side instead of the `.map { try Struct($0) }` pattern.
fn is_vec_of_serde_struct(ty: &TypeRef, serde_struct_names: &HashSet<String>) -> bool {
    match ty {
        TypeRef::Vec(inner) => {
            if let TypeRef::Named(name) = inner.as_ref() {
                serde_struct_names.contains(name)
            } else {
                false
            }
        }
        TypeRef::Optional(inner) => is_vec_of_serde_struct(inner, serde_struct_names),
        _ => false,
    }
}

pub(crate) fn needs_json_bridge_for_swift(ty: &TypeRef) -> bool {
    fn is_leaf(ty: &TypeRef) -> bool {
        matches!(
            ty,
            TypeRef::Primitive(_)
                | TypeRef::String
                | TypeRef::Char
                | TypeRef::Path
                | TypeRef::Json
                | TypeRef::Unit
                | TypeRef::Duration
                | TypeRef::Bytes
                | TypeRef::Named(_),
        )
    }
    match ty {
        TypeRef::Map(_, _) => true,
        TypeRef::Vec(inner) => !is_leaf(inner),
        TypeRef::Optional(inner) => needs_json_bridge_for_swift(inner),
        _ => false,
    }
}

fn is_field_unbridgeable_for_init(
    ty: &TypeDef,
    field: &FieldDef,
    exclude_fields: &HashSet<String>,
    known_dto_names: &HashSet<String>,
) -> bool {
    let name = field.name.to_snake_case();
    let field_key = format!("{}.{}", ty.name, name);
    if field.binding_excluded || exclude_fields.contains(&field_key) {
        return true;
    }
    if let TypeRef::Vec(inner) = &field.ty
        && field.sanitized
        && !matches!(inner.as_ref(), TypeRef::Primitive(_) | TypeRef::Bytes)
    {
        return true;
    }
    if !ty.has_serde
        && let TypeRef::Vec(inner) = &field.ty
        && !matches!(inner.as_ref(), TypeRef::Primitive(_) | TypeRef::Bytes)
    {
        return true;
    }
    if needs_json_bridge_for_swift(&field.ty) {
        let inner_named = match &field.ty {
            TypeRef::Optional(inner) | TypeRef::Vec(inner) => match inner.as_ref() {
                TypeRef::Named(n) => Some(n.as_str()),
                _ => None,
            },
            TypeRef::Named(n) => Some(n.as_str()),
            _ => None,
        };
        if let Some(n) = inner_named
            && !known_dto_names.contains(n)
        {
            return true;
        }
    }
    false
}

/// Emit a public instance method for a non-opaque first-class struct.
///
/// Calls the Rust bridge extern to invoke the method, converting parameters and return values.
/// The method serializes self to JSON, calls a Rust wrapper extern, and deserializes the result.
fn emit_instance_method_for_first_class_struct(
    method: &MethodDef,
    type_name: &str,
    mapper: &SwiftMapper,
    out: &mut String,
) {
    if method.is_static {
        return;
    }

    let method_swift_name = swift_case_ident(&method.name.to_lower_camel_case());
    let method_snake = method.name.to_snake_case();
    let type_snake = type_name.to_snake_case();
    let extern_fn_name = format!("{type_snake}_{method_snake}_from_json");
    let extern_swift_name = swift_ident(&extern_fn_name.to_lower_camel_case());

    let mut param_decls = Vec::new();
    let mut param_names = Vec::new();
    for param in &method.params {
        let param_swift_type = mapper.map_type(&param.ty);
        let param_swift_name = swift_case_ident(&param.name.to_lower_camel_case());

        let param_type = if param.optional && !matches!(&param.ty, TypeRef::Optional(_)) {
            format!("{param_swift_type}?")
        } else {
            param_swift_type
        };

        param_decls.push(format!("{param_swift_name}: {param_type}"));
        param_names.push(param_swift_name);
    }
    let params_signature = param_decls.join(", ");

    let return_swift_type = if matches!(method.return_type, TypeRef::Unit) {
        "Void".to_string()
    } else {
        mapper.map_type(&method.return_type)
    };

    let return_clause = if return_swift_type == "Void" {
        String::new()
    } else {
        format!(" -> {return_swift_type}")
    };

    let throws_clause = "throws ";

    out.push_str(&format!(
        "    public func {method_swift_name}({params_signature}) {throws_clause}{return_clause} {{\n",
    ));

    out.push_str("        let jsonSelf = try JSONEncoder().encode(self)\n");
    out.push_str("        let selfString = String(data: jsonSelf, encoding: .utf8) ?? \"{}\"\n");

    let call_args = if param_names.is_empty() {
        "selfString".to_string()
    } else {
        format!("selfString, {}", param_names.join(", "))
    };

    if matches!(method.return_type, TypeRef::Unit) {
        out.push_str(&format!(
            "        _ = try RustBridge.{extern_swift_name}({call_args})\n"
        ));
    } else {
        out.push_str(&format!(
            "        let resultJson = try RustBridge.{extern_swift_name}({call_args}).toString()\n"
        ));
        out.push_str("        let data = resultJson.data(using: .utf8) ?? Data()\n");
        out.push_str(&format!(
            "        return try JSONDecoder().decode({}.self, from: data)\n",
            return_swift_type
        ));
    }

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

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

    /// A stored property and a nullary method with the same name both land in the first-class
    /// struct body, and Swift rejects that with `invalid redeclaration of 'providers()'`. The
    /// property is emitted first and wins.
    #[test]
    fn first_class_struct_skips_nullary_method_colliding_with_a_property() {
        let ty = TypeDef {
            name: "LlmConfig".to_string(),
            rust_path: "demo::LlmConfig".to_string(),
            has_serde: true,
            fields: vec![FieldDef {
                name: "providers".to_string(),
                ty: TypeRef::String,
                optional: true,
                ..Default::default()
            }],
            methods: vec![MethodDef {
                name: "providers".to_string(),
                return_type: TypeRef::String,
                receiver: Some(ReceiverKind::Ref),
                cfg: None,
                ..Default::default()
            }],
            ..Default::default()
        };

        let mut out = String::new();
        emit_first_class_struct(
            &ty,
            &SwiftMapper,
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
            "DemoError",
            &std::collections::HashSet::new(),
            &mut out,
        );

        assert!(
            out.contains("public let providers: String?"),
            "the stored property must still be emitted:\n{out}"
        );
        let methods = out.matches("public func providers(").count();
        assert_eq!(
            methods, 0,
            "the same-named nullary method must be skipped, found {methods}:\n{out}"
        );
    }

    /// Only nullary methods redeclare a property in Swift — `providers(limit:)` has a distinct
    /// selector and must survive.
    #[test]
    fn first_class_struct_keeps_method_with_params_despite_same_base_name() {
        let ty = TypeDef {
            name: "LlmConfig".to_string(),
            rust_path: "demo::LlmConfig".to_string(),
            has_serde: true,
            fields: vec![FieldDef {
                name: "providers".to_string(),
                ty: TypeRef::String,
                optional: true,
                ..Default::default()
            }],
            methods: vec![MethodDef {
                name: "providers".to_string(),
                return_type: TypeRef::String,
                receiver: Some(ReceiverKind::Ref),
                cfg: None,
                params: vec![crate::core::ir::ParamDef {
                    name: "limit".to_string(),
                    ty: TypeRef::Primitive(crate::core::ir::PrimitiveType::U32),
                    ..Default::default()
                }],
                ..Default::default()
            }],
            ..Default::default()
        };

        let mut out = String::new();
        emit_first_class_struct(
            &ty,
            &SwiftMapper,
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
            "DemoError",
            &std::collections::HashSet::new(),
            &mut out,
        );

        assert!(
            out.contains("public func providers(limit: UInt32)"),
            "a method with parameters must not be dropped:\n{out}"
        );
    }

    /// A field whose Rust default is a `#[serde(default = "path")]` function. Its value is not in
    /// the IR, so the decoder must not invent one: `?? 0` on a `UInt32` is a silent disagreement
    /// with the source crate (`default_archive_depth()` returns 1 in the crate this was found in),
    /// while a plain `decode` makes an absent key a visible `DecodingError`.
    #[test]
    fn a_function_call_default_never_becomes_a_swift_zero() {
        let field = FieldDef {
            name: "max_archive_depth".to_string(),
            ty: TypeRef::Primitive(PrimitiveType::U32),
            typed_default: Some(DefaultValue::FunctionCall("default_archive_depth".to_string())),
            ..Default::default()
        };

        let mut out = String::new();
        emit_decoder_init(&SwiftMapper, &[&field], &HashSet::new(), true, &mut out);

        assert!(
            out.contains("try container.decode(UInt32.self, forKey: .maxArchiveDepth)"),
            "an unreadable default must leave the key required:\n{out}"
        );
        assert!(
            !out.contains("?? 0"),
            "the UInt32 zero is not the Rust default and must never stand in for it:\n{out}"
        );
    }

    /// The apparatus check for the test above. `Empty` *is* `Default::default()`, so the type zero
    /// is exact there and must still be emitted — without this, the assertion above would pass
    /// just as well against an emitter that had stopped producing `??` fallbacks at all.
    #[test]
    fn an_empty_default_still_becomes_the_swift_zero() {
        let field = FieldDef {
            name: "max_archive_depth".to_string(),
            ty: TypeRef::Primitive(PrimitiveType::U32),
            typed_default: Some(DefaultValue::Empty),
            ..Default::default()
        };

        let mut out = String::new();
        emit_decoder_init(&SwiftMapper, &[&field], &HashSet::new(), true, &mut out);

        assert!(
            out.contains("?? 0"),
            "`Empty` is the type's own default and keeps the zero fallback:\n{out}"
        );
    }

    /// `Option<T>` carrying `Some(x)` reaches the IR as the bare literal for `x` — the extractor
    /// unwraps `Some` (`extract::extractor::defaults`). Decoding an absent key as `nil` therefore
    /// substitutes a value the source crate never produces. 30000 is deliberately not the Swift
    /// zero for the type and not `nil`, so a drop cannot look like a render.
    #[test]
    fn an_optional_field_defaulting_to_some_keeps_the_value() {
        let field = FieldDef {
            name: "timeout_ms".to_string(),
            ty: TypeRef::Primitive(PrimitiveType::U32),
            optional: true,
            typed_default: Some(DefaultValue::IntLiteral(30_000)),
            ..Default::default()
        };

        let mut out = String::new();
        emit_decoder_init(&SwiftMapper, &[&field], &HashSet::new(), true, &mut out);

        assert!(
            out.contains("?? 30000"),
            "`Some(30_000)` must survive into the decoder:\n{out}"
        );
        assert!(
            !out.contains("?? nil"),
            "`nil` is not what `Some(30_000)` means:\n{out}"
        );
    }

    /// The memberwise `init` used to spell no default at all: every defaulted field was a required
    /// argument, and every optional one was `= nil` regardless of what Rust said. Both fixture
    /// values differ from the Swift zero for their type, so a dropped default cannot pass as a
    /// rendered one.
    #[test]
    fn the_memberwise_init_carries_the_rust_default() {
        let ty = TypeDef {
            name: "RetryPolicy".to_string(),
            rust_path: "demo::RetryPolicy".to_string(),
            has_serde: true,
            has_default: true,
            fields: vec![
                FieldDef {
                    name: "attempts".to_string(),
                    ty: TypeRef::Primitive(PrimitiveType::U32),
                    typed_default: Some(DefaultValue::IntLiteral(7)),
                    ..Default::default()
                },
                FieldDef {
                    name: "timeout_ms".to_string(),
                    ty: TypeRef::Primitive(PrimitiveType::U32),
                    optional: true,
                    typed_default: Some(DefaultValue::IntLiteral(30_000)),
                    ..Default::default()
                },
            ],
            ..Default::default()
        };

        let mut out = String::new();
        emit_first_class_struct(
            &ty,
            &SwiftMapper,
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
            "DemoError",
            &std::collections::HashSet::new(),
            &mut out,
        );

        assert!(
            out.contains("attempts: UInt32 = 7"),
            "a defaulted field must not stay a required init argument:\n{out}"
        );
        assert!(
            out.contains("timeoutMs: UInt32? = 30000"),
            "an optional field defaulting to `Some(30_000)` must not initialise to nil:\n{out}"
        );
        assert!(
            !out.contains("timeoutMs: UInt32? = nil"),
            "`nil` is not what `Some(30_000)` means:\n{out}"
        );
    }

    fn string_map() -> TypeRef {
        TypeRef::Map(Box::new(TypeRef::String), Box::new(TypeRef::String))
    }

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

    fn serde_struct(name: &str, fields: Vec<FieldDef>) -> TypeDef {
        TypeDef {
            name: name.to_string(),
            rust_path: format!("demo::{name}"),
            has_serde: true,
            fields,
            ..Default::default()
        }
    }

    #[test]
    fn should_accept_a_string_keyed_map_field_when_classifying_first_class() {
        let known = HashSet::new();
        assert!(
            first_class_field_supported(&string_map(), &known),
            "`Map<String, String>` is a Swift `[String: String]`, which is Codable"
        );
        assert!(
            first_class_field_supported(&TypeRef::Optional(Box::new(string_map())), &known),
            "`Option<Map<String, String>>` must be accepted too"
        );
        let map_of_vec = TypeRef::Map(
            Box::new(TypeRef::String),
            Box::new(TypeRef::Vec(Box::new(TypeRef::String))),
        );
        assert!(
            first_class_field_supported(&map_of_vec, &known),
            "a Map value recurses like any other accepted type"
        );
    }

    #[test]
    fn should_reject_a_map_field_when_the_key_is_not_a_string() {
        let known: HashSet<String> = ["Tag".to_string()].into_iter().collect();
        let u32_keyed = TypeRef::Map(
            Box::new(TypeRef::Primitive(PrimitiveType::U32)),
            Box::new(TypeRef::String),
        );
        assert!(
            !first_class_field_supported(&u32_keyed, &known),
            "Swift encodes a non-String/Int-keyed Dictionary as an array, not the serde_json object"
        );
        assert!(
            !first_class_field_supported(
                &TypeRef::Map(Box::new(TypeRef::Named("Tag".to_string())), Box::new(TypeRef::String)),
                &known
            ),
            "a generated enum is Hashable but not CodingKeyRepresentable, so it hits the array encoding"
        );
    }

    #[test]
    fn should_reject_a_string_keyed_map_when_the_value_type_is_unknown() {
        let known = HashSet::new();
        assert!(
            !first_class_field_supported(
                &TypeRef::Map(
                    Box::new(TypeRef::String),
                    Box::new(TypeRef::Named("Mystery".to_string()))
                ),
                &known
            ),
            "an unknown Named value is still a typealias to an opaque class and cannot be Codable"
        );
        assert!(
            !first_class_field_supported(
                &TypeRef::Map(Box::new(TypeRef::String), Box::new(TypeRef::Bytes)),
                &known
            ),
            "the value side must keep the same rejections as any other field position"
        );
    }

    /// Apparatus check for the two tests above: widening `Map` must not have widened anything
    /// else. Without this, an emitter that had started accepting every type would pass them.
    #[test]
    fn should_still_reject_path_bytes_duration_char_and_json_fields() {
        let known = HashSet::new();
        for ty in [
            TypeRef::Path,
            TypeRef::Bytes,
            TypeRef::Duration,
            TypeRef::Char,
            TypeRef::Json,
            TypeRef::Unit,
        ] {
            assert!(
                !first_class_field_supported(&ty, &known),
                "{ty:?} has no idiomatic Swift stored-property form and must still fall back"
            );
        }
    }

    /// The shipped defect: `HtmlMetadata` carries three `BTreeMap<String, String>` fields, so it
    /// was not first-class, so `FormatMetadata::Html(HtmlMetadata)` failed
    /// `all_variants_codable_safe` and *all* of the enum's variants collapsed into a single
    /// payload-erased `typealias`. Both halves are asserted: the struct must enter the
    /// first-class set, and the enum that carries it must survive as a real Swift enum.
    #[test]
    fn should_keep_a_data_enum_first_class_when_a_variant_payload_carries_map_fields() {
        let html_metadata = serde_struct(
            "HtmlMetadata",
            vec![
                named_field("title", TypeRef::String),
                named_field("meta_tags", string_map()),
                named_field("open_graph", string_map()),
                named_field("twitter_card", string_map()),
            ],
        );
        let api = ApiSurface {
            types: vec![html_metadata],
            enums: vec![crate::core::ir::EnumDef {
                name: "FormatMetadata".to_string(),
                rust_path: "demo::FormatMetadata".to_string(),
                has_serde: true,
                variants: vec![crate::core::ir::EnumVariant {
                    name: "Html".to_string(),
                    is_tuple: true,
                    fields: vec![named_field("0", TypeRef::Named("HtmlMetadata".to_string()))],
                    ..Default::default()
                }],
                ..Default::default()
            }],
            ..Default::default()
        };

        let known = compute_first_class_dto_names(&api, &HashSet::new());

        assert!(
            known.contains("HtmlMetadata"),
            "a struct whose only exotic fields are String-keyed maps must be first-class, got {known:?}"
        );
        assert!(
            super::super::enums::all_variants_codable_safe(&api.enums[0], &known),
            "the payload struct being first-class is what keeps the enum's variants from collapsing"
        );
    }

    /// A `Map` field must render as a Swift `Dictionary` property and be read back through the
    /// getter's serde_json `String`, which is what `needs_json_bridge_for_swift` already routes
    /// it to. A property typed `RustBridge.…` or an `rb.metaTags()` read with no JSON decode
    /// would both compile-fail in the consuming package, so both are pinned.
    #[test]
    fn should_render_a_map_field_as_a_swift_dictionary_property() {
        let ty = serde_struct(
            "HtmlMetadata",
            vec![
                named_field("meta_tags", string_map()),
                named_field("title", TypeRef::String),
            ],
        );

        let mut out = String::new();
        emit_first_class_struct(
            &ty,
            &SwiftMapper,
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
            "DemoError",
            &std::collections::HashSet::new(),
            &mut out,
        );

        assert!(
            out.contains("public let metaTags: [String: String]"),
            "the Map field must be a Swift Dictionary stored property:\n{out}"
        );
        assert!(
            out.contains("self.metaTags = try JSONDecoder().decode([String: String].self"),
            "the FFI init must JSON-decode the getter's serde_json String:\n{out}"
        );
    }

    /// GH#1594: `CodeDataNode { children: Vec<CodeDataNode>, .. }` is legitimately recursive --
    /// `struct Node: Codable { var children: [Node] }` compiles in Swift because `Array` boxes
    /// its elements. The fixed-point loop in `compute_first_class_dto_names` seeds only serde
    /// enums, so without `is_self_reference_through_indirection` a type can never enter `known`
    /// before checking its own fields, and a self-referencing struct is permanently excluded no
    /// matter how many iterations run.
    #[test]
    fn a_struct_recursing_only_through_vec_of_self_stays_first_class() {
        let node = serde_struct(
            "CodeDataNode",
            vec![
                named_field("key", TypeRef::String),
                named_field(
                    "children",
                    TypeRef::Vec(Box::new(TypeRef::Named("CodeDataNode".to_string()))),
                ),
            ],
        );
        let api = ApiSurface {
            types: vec![node],
            ..Default::default()
        };

        let known = compute_first_class_dto_names(&api, &HashSet::new());

        assert!(
            known.contains("CodeDataNode"),
            "Vec<Self> is Swift-legal recursion and must not block first-class status: {known:?}"
        );
    }

    /// A *bare* self-reference (`Option<Self>` etc.) is not Swift-legal for a struct — Swift's
    /// value-type `Optional` does not indirect, so `struct Foo { var next: Foo? }` fails to
    /// compile. `is_self_reference_through_indirection` must not treat this the same as the
    /// `Vec<Self>` case above; the type stays excluded.
    #[test]
    fn a_struct_recursing_through_a_bare_optional_self_is_not_first_class() {
        let node = serde_struct(
            "LinkedNode",
            vec![named_field(
                "next",
                TypeRef::Optional(Box::new(TypeRef::Named("LinkedNode".to_string()))),
            )],
        );
        let api = ApiSurface {
            types: vec![node],
            ..Default::default()
        };

        let known = compute_first_class_dto_names(&api, &HashSet::new());

        assert!(
            !known.contains("LinkedNode"),
            "a bare Optional<Self> is not Swift-legal recursion and must stay excluded: {known:?}"
        );
    }

    /// GH#1594's second blocker: `DocxMetadata.custom_properties: Option<HashMap<String,
    /// serde_json::Value>>`. `serde_json::Value` alone stays rejected (`TypeRef::Json` has no
    /// Codable Swift form), but as a Map *value* it substitutes the Codable `JSONValue` stand-in,
    /// so the field — and the struct carrying it — must stay first-class.
    #[test]
    fn a_map_with_arbitrary_json_values_stays_first_class() {
        let map_of_json = TypeRef::Map(Box::new(TypeRef::String), Box::new(TypeRef::Json));
        let known = HashSet::new();
        assert!(
            first_class_field_supported(&map_of_json, &known),
            "Map<String, Json> has a Codable JSONValue stand-in and must be accepted"
        );
        assert!(
            first_class_field_supported(&TypeRef::Optional(Box::new(map_of_json)), &known),
            "Option<Map<String, Json>> must be accepted too"
        );

        let docx_metadata = serde_struct(
            "DocxMetadata",
            vec![named_field(
                "custom_properties",
                TypeRef::Map(Box::new(TypeRef::String), Box::new(TypeRef::Json)),
            )],
        );
        let api = ApiSurface {
            types: vec![docx_metadata],
            ..Default::default()
        };
        let known = compute_first_class_dto_names(&api, &HashSet::new());
        assert!(
            known.contains("DocxMetadata"),
            "a struct whose only exotic field is Map<String, Json> must be first-class: {known:?}"
        );
    }

    /// The Map<String, Json> value position must render as `JSONValue`, not the `String` a bare
    /// Json leaf renders as (`SwiftMapper::json()`) — `[String: String]` would throw decoding the
    /// first non-string JSON value the real wire format actually carries.
    #[test]
    fn should_render_a_json_valued_map_field_using_the_json_value_stand_in() {
        let ty = serde_struct(
            "DocxMetadata",
            vec![named_field(
                "customProperties",
                TypeRef::Map(Box::new(TypeRef::String), Box::new(TypeRef::Json)),
            )],
        );

        let mut out = String::new();
        emit_first_class_struct(
            &ty,
            &SwiftMapper,
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
            "DemoError",
            &std::collections::HashSet::new(),
            &mut out,
        );

        assert!(
            out.contains("public let customProperties: [String: JSONValue]"),
            "the Map<String, Json> field must be a [String: JSONValue] stored property:\n{out}"
        );
        assert!(
            !out.contains("[String: String]"),
            "the Json value must not fall back to the leaf-JSON String convention:\n{out}"
        );
    }
}