kotlin-codegen 0.2.0

A declaration model and renderer for generating Kotlin source code
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
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
//! Golden-string tests: one per Kotlin construct the jnigen back-end emits.

use std::fs;

use super::{types::ImportSet, *};

/// A process-unique temp directory for a test that writes files. Keyed by
/// pid + a monotonic counter so tests that share a helper and run on
/// separate threads never clobber each other's output dir.
fn unique_test_dir(prefix: &str) -> std::path::PathBuf {
    use std::sync::atomic::{AtomicUsize, Ordering};
    static SEQ: AtomicUsize = AtomicUsize::new(0);
    let seq = SEQ.fetch_add(1, Ordering::Relaxed);
    std::env::temp_dir().join(format!("{prefix}_{}_{}", std::process::id(), seq))
}

fn body_of(src: &str) -> &str {
    // Strip banner + package + imports + the separating blank line.
    let mut rest = src;
    while let Some((line, tail)) = rest.split_once('\n') {
        if line.starts_with("//")
            || line.starts_with("package ")
            || line.starts_with("import ")
            || line.is_empty()
        {
            rest = tail;
            // Stop skipping blank lines once the body starts; the single
            // separator blank is consumed by falling through one more loop.
            if line.is_empty() && !tail.starts_with("import ") && !tail.is_empty() {
                break;
            }
        } else {
            break;
        }
    }
    rest
}

#[test]
fn enum_class_with_from_int_companion() {
    let class = KtClass::enum_("Color")
        .entry(KtEnumEntry::with_args("RED", "0"))
        .entry(KtEnumEntry::with_args("GREEN", "5"))
        .entry(KtEnumEntry::with_args("BLUE", "6"))
        .vis(KtVis::Public)
        .kdoc("JVM-side surface for the native Rust `Color` enum.")
        .ctor_param(
            KtCtorParam::new("value", KtType::int())
                .val()
                .vis(KtVis::Public),
        )
        .companion(
            KtCompanion::new().vis(KtVis::Public).member(
                KtFun::new("fromInt")
                    .vis(KtVis::Public)
                    .annotation("JvmStatic")
                    .param(KtParam::new("value", KtType::int()))
                    .returns(KtType::cls("Color"))
                    .expr_body(KtCode::new().line("entries.first { it.value == value }")),
            ),
        );
    let src = render::render_one(&class.into(), "io.test.jni");
    assert_eq!(
        body_of(&src),
        "\
/** JVM-side surface for the native Rust `Color` enum. */
public enum class Color(public val value: Int) {
    RED(0),
    GREEN(5),
    BLUE(6);

    public companion object {
        @JvmStatic
        public fun fromInt(value: Int): Color = entries.first { it.value == value }
    }
}
"
    );
}

#[test]
fn jvm_inline_value_class() {
    let class = KtClass::value(
        "ZenohId",
        KtCtorParam::new("bytes", KtType::byte_array())
            .val()
            .vis(KtVis::Public),
    )
    .vis(KtVis::Public);
    let src = render::render_one(&class.into(), "io.test.jni");
    assert_eq!(
        body_of(&src),
        "\
@JvmInline
public value class ZenohId(public val bytes: ByteArray)
"
    );
}

#[test]
fn abstract_class_with_volatile_property_and_supertype() {
    let class = KtClass::class_with(KtClassModifier::Abstract, "NativeHandle")
        .vis(KtVis::Public)
        .ctor_param(KtCtorParam::new("initialPtr", KtType::long()))
        .implements(KtType::cls("AutoCloseable"))
        .member(
            KtProperty::var("ptr")
                .ty(KtType::long())
                .initializer("initialPtr")
                .vis(KtVis::Internal)
                .annotation("Volatile"),
        )
        .member(
            KtFun::new("peek")
                .vis(KtVis::Public)
                .returns(KtType::long())
                .expr_body(KtCode::new().line("ptr")),
        );
    let src = render::render_one(&class.into(), "io.test.jni");
    assert_eq!(
        body_of(&src),
        "\
public abstract class NativeHandle(initialPtr: Long) : AutoCloseable {
    @Volatile internal var ptr: Long = initialPtr

    public fun peek(): Long = ptr
}
"
    );
}

#[test]
fn typed_handle_subclass_with_ctor_args_supertype() {
    let class = KtClass::class_("ZThing")
        .vis(KtVis::Public)
        .ctor_param(KtCtorParam::new("initialPtr", KtType::long()))
        .extends(KtType::cls("io.test.jni.NativeHandle"), Some("initialPtr"))
        .member(
            KtFun::new("close")
                .annotation("Synchronized")
                .modifier("override")
                .body(KtCode::new().blk("if (ptr != 0L) {", |c| {
                    c.line("freePtr(ptr)").line("ptr = ptr or 1L")
                })),
        )
        .companion(
            KtCompanion::new().member(
                KtFun::new("freePtr")
                    .annotation("JvmStatic")
                    .external()
                    .param(KtParam::new("ptr", KtType::long())),
            ),
        );
    let src = render::render_one(&class.into(), "io.test.jni.thing");
    assert_eq!(
        body_of(&src),
        "\
public class ZThing(initialPtr: Long) : NativeHandle(initialPtr) {
    @Synchronized
    override fun close() {
        if (ptr != 0L) {
            freePtr(ptr)
            ptr = ptr or 1L
        }
    }

    companion object {
        @JvmStatic
        external fun freePtr(ptr: Long)
    }
}
"
    );
    // Cross-package supertype produced an import.
    assert!(src.contains("import io.test.jni.NativeHandle"), "{src}");
}

#[test]
fn object_with_external_funs() {
    let obj = KtClass::object_("JNINative")
        .vis(KtVis::Internal)
        .member(
            KtFun::new("zThingNew")
                .external()
                .param(KtParam::new("errorSink", KtType::any()))
                .returns(KtType::long()),
        )
        .member(
            KtFun::new("zThingFree")
                .external()
                .param(KtParam::new("ptr", KtType::long())),
        );
    let src = render::render_one(&obj.into(), "io.test.jni");
    assert_eq!(
        body_of(&src),
        "\
internal object JNINative {
    external fun zThingNew(errorSink: Any): Long

    external fun zThingFree(ptr: Long)
}
"
    );
}

#[test]
fn top_level_fun_with_generics_named_lambda_and_default() {
    let f = KtFun::new("zThingSub")
        .vis(KtVis::Public)
        .annotation("Suppress(\"UNCHECKED_CAST\")")
        .generic("R")
        .param(KtParam::new(
            "thing",
            KtType::cls("io.test.jni.thing.ZThing"),
        ))
        .param(
            KtParam::new(
                "onError",
                KtType::lambda(
                    [
                        ("je".to_string(), KtType::string().nullable()),
                        ("message".to_string(), KtType::string()),
                    ],
                    KtType::var_r(),
                ),
            )
            .default("{ __de_je, __de_z0 -> error(__de_je ?: __de_z0) }"),
        )
        .param(KtParam::new(
            "build",
            KtType::lambda(
                [
                    (
                        "handle".to_string(),
                        KtType::cls("io.test.jni.thing.ZThing"),
                    ),
                    ("name".to_string(), KtType::string()),
                ],
                KtType::var_r(),
            ),
        ))
        .returns(KtType::var_r())
        .body(
            KtCode::new()
                .line("var __cap_failed = false")
                .blk("val __ret = run {", |c| {
                    c.line("(JNINative.zThingSub(thing.ptr, build, __cap) as R)")
                })
                .line("if (__cap_failed) return onError(__cap_je, \"\")")
                .line("return __ret"),
        );
    let src = render::render_one(&f.into(), "io.test.jni.thing");
    assert_eq!(
        body_of(&src),
        "\
@Suppress(\"UNCHECKED_CAST\")
public fun <R> zThingSub(
    thing: ZThing,
    onError: (je: String?, message: String) -> R = { __de_je, __de_z0 -> error(__de_je ?: __de_z0) },
    build: (handle: ZThing, name: String) -> R,
): R {
    var __cap_failed = false
    val __ret = run {
        (JNINative.zThingSub(thing.ptr, build, __cap) as R)
    }
    if (__cap_failed) return onError(__cap_je, \"\")
    return __ret
}
"
    );
}

#[test]
fn unit_return_is_omitted() {
    let f = KtFun::new("doIt")
        .vis(KtVis::Public)
        .returns(KtType::unit())
        .body(KtCode::new().line("work()"));
    let src = render::render_one(&f.into(), "p");
    assert!(src.contains("public fun doIt() {"), "{src}");
    assert!(!src.contains(": Unit"), "{src}");
}

#[test]
fn long_signature_wraps_params_one_per_line() {
    // Short signatures stay on a single line.
    let short = KtFun::new("short")
        .vis(KtVis::Public)
        .param(KtParam::new("a", KtType::int()))
        .param(KtParam::new("b", KtType::int()))
        .returns(KtType::int())
        .body(KtCode::new().line("a + b"));
    let src = render::render_one(&short.into(), "p");
    assert!(
        src.contains("public fun short(a: Int, b: Int): Int {"),
        "{src}"
    );

    // A signature wider than the threshold breaks one parameter per line,
    // with a trailing comma and the closing paren at the function indent.
    let long = KtFun::new("zSessionDeclareSubscriber")
        .vis(KtVis::Public)
        .param(KtParam::new("session", KtType::cls("ZSession")))
        .param(KtParam::new("keyExprSel", KtType::int()))
        .param(KtParam::new("keyExpr0", KtType::string().nullable()))
        .param(KtParam::new("keyExpr1", KtType::cls("ZKeyExpr").nullable()))
        .param(KtParam::new("onClose", KtType::lambda([], KtType::unit())))
        .returns(KtType::cls("ZSubscriber"))
        .body(KtCode::new().line("TODO()"));
    let src = render::render_one(&long.into(), "p");
    assert!(
        src.contains(
            "public fun zSessionDeclareSubscriber(\n    \
             session: ZSession,\n    \
             keyExprSel: Int,\n    \
             keyExpr0: String?,\n    \
             keyExpr1: ZKeyExpr?,\n    \
             onClose: () -> Unit,\n\
             ): ZSubscriber {"
        ),
        "{src}"
    );
}

#[test]
fn long_function_type_param_wraps_its_own_params() {
    // A `callback` whose function type is itself too wide breaks the lambda's
    // parameters one-per-line, with the `) -> Ret` closer realigned under the
    // parameter. A short `onError` lambda on the same function stays inline.
    let cb = KtType::lambda(
        [
            ("keyExpr".to_string(), KtType::cls("ZKeyExpr")),
            ("payloadToBytes".to_string(), KtType::byte_array()),
            ("encodingToString".to_string(), KtType::string()),
            ("kind".to_string(), KtType::int()),
            ("timestampNtp64".to_string(), KtType::long().nullable()),
            ("congestionControl".to_string(), KtType::int()),
            (
                "attachmentToBytes".to_string(),
                KtType::byte_array().nullable(),
            ),
        ],
        KtType::unit(),
    );
    let f = KtFun::new("declareSubscriber")
        .vis(KtVis::Public)
        .param(KtParam::new("session", KtType::cls("ZSession")))
        .param(KtParam::new("callback", cb))
        .param(
            KtParam::new(
                "onError",
                KtType::lambda(
                    [("je".to_string(), KtType::string().nullable())],
                    KtType::cls("ZSubscriber"),
                ),
            )
            .default("{ __de_je -> error(__de_je ?: \"\") }"),
        )
        .returns(KtType::cls("ZSubscriber"))
        .body(KtCode::new().line("TODO()"));
    let src = render::render_one(&f.into(), "p");
    assert!(
        src.contains(
            "public fun declareSubscriber(\n    \
             session: ZSession,\n    \
             callback: (\n        \
                 keyExpr: ZKeyExpr,\n        \
                 payloadToBytes: ByteArray,\n        \
                 encodingToString: String,\n        \
                 kind: Int,\n        \
                 timestampNtp64: Long?,\n        \
                 congestionControl: Int,\n        \
                 attachmentToBytes: ByteArray?,\n    \
             ) -> Unit,\n    \
             onError: (je: String?) -> ZSubscriber = { __de_je -> error(__de_je ?: \"\") },\n\
             ): ZSubscriber {"
        ),
        "{src}"
    );
}

#[test]
fn nested_function_type_params_wrap_recursively() {
    // A parameter whose function type contains an *inner* function type that
    // is itself too wide: both levels break, each at its own indent.
    let inner_cb = KtType::lambda(
        [
            ("keyExpression".to_string(), KtType::cls("ZKeyExpr")),
            ("payloadToBytes".to_string(), KtType::byte_array()),
            ("encodingToString".to_string(), KtType::string()),
            (
                "attachmentToBytes".to_string(),
                KtType::byte_array().nullable(),
            ),
        ],
        KtType::unit(),
    );
    let register = KtType::lambda(
        [
            ("callback".to_string(), inner_cb),
            ("onClose".to_string(), KtType::lambda([], KtType::unit())),
        ],
        KtType::cls("ZSubscriber"),
    );
    let f = KtFun::new("declareWithNestedCallback")
        .vis(KtVis::Public)
        .param(KtParam::new("session", KtType::cls("ZSession")))
        .param(KtParam::new("register", register))
        .returns(KtType::cls("ZSubscriber"))
        .body(KtCode::new().line("TODO()"));
    let src = render::render_one(&f.into(), "p");
    assert!(
        src.contains(
            "public fun declareWithNestedCallback(\n    \
             session: ZSession,\n    \
             register: (\n        \
                 callback: (\n            \
                     keyExpression: ZKeyExpr,\n            \
                     payloadToBytes: ByteArray,\n            \
                     encodingToString: String,\n            \
                     attachmentToBytes: ByteArray?,\n        \
                 ) -> Unit,\n        \
                 onClose: () -> Unit,\n    \
                 ) -> ZSubscriber,\n\
                 ): ZSubscriber {"
        ),
        "{src}"
    );
}

#[test]
fn typealias_renders() {
    let d = KtDecl::TypeAlias {
        vis: KtVis::Public,
        name: "OldName".into(),
        target: KtType::cls("io.test.jni.NewName"),
    };
    let src = render::render_one(&d, "io.test.compat");
    assert!(src.contains("public typealias OldName = NewName"), "{src}");
    assert!(src.contains("import io.test.jni.NewName"), "{src}");
}

#[test]
fn import_collision_falls_back_to_fqn() {
    let f = KtFun::new("f")
        .param(KtParam::new("a", KtType::cls("io.a.Same")))
        .param(KtParam::new("b", KtType::cls("io.b.Same")))
        .body(KtCode::new());
    let src = render::render_one(&f.into(), "p");
    assert!(src.contains("import io.a.Same"), "{src}");
    assert!(!src.contains("import io.b.Same"), "{src}");
    assert!(src.contains("a: Same, b: io.b.Same"), "{src}");
}

#[test]
fn same_package_types_need_no_import() {
    let f = KtFun::new("f")
        .param(KtParam::new("a", KtType::cls("io.p.Local")))
        .body(KtCode::new());
    let src = render::render_one(&f.into(), "io.p");
    assert!(!src.contains("import io.p.Local"), "{src}");
    assert!(src.contains("a: Local"), "{src}");
}

#[test]
fn an_extension_receiver_renders_before_the_name() {
    // Generics first, then the receiver, then the bare name — and the receiver
    // goes through the import set like any other type.
    let f = KtFun::new("asRaw")
        .generic("R")
        .receiver(KtType::generic("io.other.Cb", [KtType::var_("R")]))
        .returns(KtType::cls("io.p.CbRaw"))
        .expr_body(KtCode::new().line("CbRaw { }"));
    let src = render::render_one(&f.into(), "io.p");
    assert!(src.contains("fun <R> Cb<R>.asRaw(): CbRaw"), "{src}");
    assert!(src.contains("import io.other.Cb"), "{src}");
}

#[test]
fn an_extension_functions_name_is_still_a_plain_identifier() {
    // The point of the field: the receiver is not smuggled into `name`, so the
    // identifier check sees `asRaw` and passes.
    let file = KtFile::new("io.p").decl(
        KtFun::new("asRaw")
            .receiver(KtType::cls("io.p.Cb"))
            .expr_body(KtCode::new().line("CbRaw { }")),
    );
    assert_eq!(file.validate(), vec![]);
}

#[test]
fn signature_keeps_the_extension_receiver() {
    // `signature()` drops the body and modifiers; losing the receiver too would
    // silently turn an extension into a member.
    let f = KtFun::new("asRaw")
        .receiver(KtType::cls("io.p.Cb"))
        .body(KtCode::new());
    assert!(f.signature().receiver.is_some());
}

#[test]
fn type_construction_covers_metadata_shapes() {
    let mut imp = ImportSet::new("p");
    // The structured shapes jnigen metadata carries, rendered with imports.
    for (ty, want) in [
        (KtType::int(), "Int"),
        (KtType::string().nullable(), "String?"),
        (KtType::cls("io.zenoh.jni.keyexpr.ZKeyExpr"), "ZKeyExpr"),
        (
            KtType::cls("io.zenoh.jni.keyexpr.ZKeyExpr").nullable(),
            "ZKeyExpr?",
        ),
        (
            KtType::generic("List", [KtType::cls("io.zenoh.jni.ZZenohId")]),
            "List<ZZenohId>",
        ),
        (
            KtType::generic("List", [KtType::byte_array()]),
            "List<ByteArray>",
        ),
        (KtType::any().nullable(), "Any?"),
        (KtType::var_r(), "R"),
    ] {
        assert_eq!(ty.render(&mut imp), want);
    }
}

#[test]
fn display_renders_types_verbatim() {
    // `Display` keeps FQNs fully qualified (no import shortening) and
    // renders function types with named params and the nullable wrapper.
    let fun = KtType::lambda(
        [
            ("je".to_string(), KtType::string().nullable()),
            ("message".to_string(), KtType::string()),
        ],
        KtType::cls("ZSubscriber"),
    );
    assert_eq!(
        fun.to_string(),
        "(je: String?, message: String) -> ZSubscriber"
    );
    let nullable_fun =
        KtType::lambda([("a".to_string(), KtType::cls("X"))], KtType::cls("Y")).nullable();
    assert_eq!(nullable_fun.to_string(), "((a: X) -> Y)?");
    assert_eq!(
        KtType::generic("List", [KtType::cls("io.zenoh.jni.ZZenohId")]).to_string(),
        "List<io.zenoh.jni.ZZenohId>"
    );
    // Unnamed lambda params render bare.
    assert_eq!(
        KtType::lambda(
            [
                (String::new(), KtType::int()),
                (String::new(), KtType::string().nullable())
            ],
            KtType::boolean()
        )
        .to_string(),
        "(Int, String?) -> Boolean"
    );
}

#[test]
fn merge_files_groups_by_package_and_rejects_duplicates() {
    let a = KtFile::new("io.p").decl(KtClass::class_("A").vis(KtVis::Public));
    let b = KtFile::new("io.p").decl(KtFun::new("f").body(KtCode::new()));
    let c = KtFile::new("io.q").decl(KtClass::class_("C"));
    let merged = merge_files(vec![a, b, c]).expect("merge");
    assert_eq!(merged.len(), 2);
    assert_eq!(merged[0].package, "io.p");
    assert_eq!(merged[0].decls.len(), 2);

    let d1 = KtFile::new("io.p").decl(KtClass::class_("A"));
    let d2 = KtFile::new("io.p").decl(KtClass::class_("A"));
    assert!(merge_files(vec![d1, d2]).is_err());
}

#[test]
fn merged_file_path_is_flattened() {
    let f = KtFile::new("io.zenoh.jni.bytes");
    let p = merged_file_path(std::path::Path::new("/root"), &f, "X");
    assert_eq!(p, std::path::PathBuf::from("/root/io/zenoh/jni/bytes.kt"));
    let empty = KtFile::new("");
    let p2 = merged_file_path(std::path::Path::new("/root"), &empty, "NativeHandle");
    assert_eq!(p2, std::path::PathBuf::from("/root/NativeHandle.kt"));
}

#[test]
fn write_files_refuses_nonempty_unowned_root() {
    let dir = unique_test_dir("kotlin_unowned_root");
    let root = dir.join("generated");
    fs::create_dir_all(&root).unwrap();
    let handwritten = root.join("Main.kt");
    fs::write(&handwritten, "fun main() = Unit\n").unwrap();

    let err = write_files(&[KtFile::new("io.test")], &root).unwrap_err();
    assert!(err.to_string().contains("ownership marker"), "{err}");
    assert_eq!(
        fs::read_to_string(&handwritten).unwrap(),
        "fun main() = Unit\n"
    );

    let _ = fs::remove_dir_all(dir);
}

#[test]
fn write_files_accepts_crlf_marker() {
    // A committed LF marker is rewritten to CRLF by git's `autocrlf` on a
    // Windows checkout; the (present, valid) marker must still be recognized so
    // regeneration succeeds. Simulate that by writing the marker with CRLF.
    let dir = unique_test_dir("kotlin_crlf_marker");
    let root = dir.join("generated");
    fs::create_dir_all(&root).unwrap();
    fs::write(
        root.join(".kotlin-codegen-output"),
        "kotlin-codegen output v1\r\n",
    )
    .unwrap();
    // A stale generated file from a previous run — must be wiped on rewrite.
    fs::write(root.join("Stale.kt"), "package stale\n").unwrap();

    let paths = write_files(&[KtFile::new("io.test")], &root)
        .expect("CRLF marker must be accepted as an owned root");
    assert!(paths.iter().all(|p| p.exists()));
    assert!(
        !root.join("Stale.kt").exists(),
        "stale file wiped on rewrite"
    );

    let _ = fs::remove_dir_all(dir);
}

#[test]
fn write_files_replaces_marked_root_and_preserves_it_on_staging_failure() {
    let dir = unique_test_dir("kotlin_owned_root");
    let root = dir.join("generated");
    let initial = KtFile::new("io.test").decl(KtFun::new("first").body(KtCode::new()));
    write_files(&[initial], &root).unwrap();
    let stale = root.join("stale.kt");
    fs::write(&stale, "stale\n").unwrap();

    let replacement = KtFile::new("io.test").decl(KtFun::new("second").body(KtCode::new()));
    write_files(&[replacement], &root).unwrap();
    assert!(!stale.exists());
    assert!(root.join(".kotlin-codegen-output").exists());
    assert!(root.join("io/test.kt").exists());

    let escaping_output = KtFile::new("../outside").decl(KtFun::new("one").body(KtCode::new()));
    assert!(write_files(&[escaping_output], &root).is_err());
    assert!(root.join("io/test.kt").exists());

    let _ = fs::remove_dir_all(dir);
}

#[test]
fn multiline_kdoc() {
    let c = KtClass::class_("X").kdoc("First line.\n\nSecond paragraph.");
    let src = render::render_one(&c.into(), "p");
    assert!(
        src.contains("/**\n * First line.\n *\n * Second paragraph.\n */\nclass X"),
        "{src}"
    );
}

#[test]
fn delegated_property_renders_by_clause() {
    let p = KtProperty::val("MAGIC")
        .ty(KtType::long())
        .vis(KtVis::Public)
        .delegate("lazy { constGetMagic(handler) }");
    let src = render::render_one(&p.into(), "p");
    assert!(
        src.contains("public val MAGIC: Long by lazy { constGetMagic(handler) }"),
        "{src}"
    );
}

/// Every position that holds a `KtCode` value must have its `KtCode::import`
/// collected by the file's raw-import prepass.
///
/// A `KtCode` body can carry `.import(fqn)` — the **only** place such FQNs are
/// recorded — so a position the prepass skips renders `Factory.make()` and
/// never emits `import io.example.Factory`, i.e. uncompilable Kotlin.
#[test]
fn every_kt_code_position_contributes_its_raw_imports() {
    fn code(text: &str, fqn: &str) -> KtCode {
        KtCode::new().line(text).import(fqn)
    }

    // fn param default
    let mut f = KtFun::new("withDefault")
        .vis(KtVis::Public)
        .body(KtCode::new());
    let mut p = KtParam::new("factory", KtType::cls("Any"));
    p.default = Some(code("Factory.make()", "io.example.Factory"));
    f = f.param(p);

    // fun interface whose METHOD has a defaulted param
    let mut im = KtFunSig::new("run");
    let mut ip = KtParam::new("codec", KtType::cls("Any"));
    ip.default = Some(code("Codec.utf8()", "io.example.Codec"));
    im = im.param(ip);
    let iface = KtFunInterface::new("Handler", im).vis(KtVis::Public);

    // ctor param default + supertype ctor args
    let mut cp = KtCtorParam::new("seed", KtType::long());
    cp.default = Some(code("Seed.zero()", "io.example.Seed"));
    let mut cls = KtClass::class_("Holder").vis(KtVis::Public).ctor_param(cp);
    cls.supertypes.superclass = Some(KtSuperclass {
        ty: KtType::cls("Base"),
        args: Some(code("Anchor.of(1)", "io.example.Anchor")),
    });

    // enum entry args
    let enum_cls = KtClass::enum_("Kind")
        .entry(KtEnumEntry {
            name: "FIRST".into(),
            args: Some(code("Weight.one()", "io.example.Weight")),
        })
        .vis(KtVis::Public);

    let src = KtFile::new("io.test")
        .decl(f)
        .decl(iface)
        .decl(cls)
        .decl(enum_cls)
        .render();

    for fqn in [
        "io.example.Factory",
        "io.example.Codec",
        "io.example.Seed",
        "io.example.Anchor",
        "io.example.Weight",
    ] {
        assert!(
            src.contains(&format!("import {fqn}")),
            "missing `import {fqn}` — that slot's raw imports were dropped\n{src}"
        );
    }
}

#[test]
fn class_modifiers_render() {
    for (modifier, keyword) in [
        (KtClassModifier::Abstract, "abstract class"),
        (KtClassModifier::Open, "open class"),
        (KtClassModifier::Sealed, "sealed class"),
    ] {
        let c = KtClass::class_with(modifier, "X");
        let src = render::render_one(&c.into(), "io.test");
        assert_eq!(body_of(&src), format!("{keyword} X\n"));
    }
}

#[test]
fn value_class_holds_exactly_one_property() {
    // The single field is a constructor argument, so neither zero nor two are
    // expressible; `ctor_params()` always yields exactly it.
    let c = KtClass::value("Id", KtCtorParam::new("bytes", KtType::byte_array()).val());
    assert_eq!(c.ctor_params().len(), 1);
    assert_eq!(c.ctor_params()[0].name, "bytes");
}

#[test]
fn data_class_always_has_at_least_one_property() {
    let c = KtClass::data("P", KtCtorParam::new("x", KtType::int()).val())
        .ctor_param(KtCtorParam::new("y", KtType::int()).val());
    assert_eq!(c.ctor_params().len(), 2);
}

#[test]
#[should_panic(expected = "has no primary constructor")]
fn object_cannot_take_ctor_params() {
    let _ = KtClass::object_("Obj").ctor_param(KtCtorParam::new("x", KtType::int()));
}

#[test]
#[should_panic(expected = "has no primary constructor")]
fn interface_cannot_take_ctor_params() {
    let _ = KtClass::interface_("I").ctor_param(KtCtorParam::new("x", KtType::int()));
}

#[test]
#[should_panic(expected = "is not an enum class")]
fn non_enum_cannot_take_entries() {
    let _ = KtClass::class_("C").entry(KtEnumEntry::new("A"));
}

#[test]
fn enum_with_primary_constructor_renders_entry_args() {
    let c = KtClass::enum_("Kind")
        .ctor_param(KtCtorParam::new("code", KtType::int()).val())
        .entry(KtEnumEntry::with_args("A", "1"))
        .entry(KtEnumEntry::with_args("B", "2"));
    let src = render::render_one(&c.into(), "io.test");
    assert_eq!(
        body_of(&src),
        "\
enum class Kind(val code: Int) {
    A(1),
    B(2);
}
"
    );
}

#[test]
fn named_companion_object_renders_its_name() {
    let c = KtClass::class_("Holder").companion(
        KtCompanion::named("Factory")
            .vis(KtVis::Public)
            .member(KtFun::new("of").expr_body(KtCode::new().line("Holder()"))),
    );
    let src = render::render_one(&c.into(), "io.test");
    assert_eq!(
        body_of(&src),
        "\
class Holder {
    public companion object Factory {
        fun of() = Holder()
    }
}
"
    );
}

#[test]
fn anonymous_companion_object_omits_the_name() {
    let c = KtClass::class_("Holder")
        .companion(KtCompanion::new().member(KtProperty::val("N").initializer("1")));
    let src = render::render_one(&c.into(), "io.test");
    assert_eq!(
        body_of(&src),
        "\
class Holder {
    companion object {
        val N = 1
    }
}
"
    );
}

#[test]
fn superclass_renders_before_interfaces() {
    let c = KtClass::class_("ZThing")
        .implements(KtType::cls("AutoCloseable"))
        .extends(KtType::cls("Base"), Some("ptr"))
        .implements(KtType::cls("Comparable"));
    let src = render::render_one(&c.into(), "io.test");
    // Declared interface-first, but Kotlin wants the constructed superclass
    // leading — the split makes that ordering structural, not the caller's job.
    assert_eq!(
        body_of(&src),
        "class ZThing : Base(ptr), AutoCloseable, Comparable\n"
    );
}

#[test]
fn superclass_without_args_renders_bare() {
    let c = KtClass::class_("Sub").extends(KtType::cls("Base"), None);
    let src = render::render_one(&c.into(), "io.test");
    assert_eq!(body_of(&src), "class Sub : Base\n");
}

#[test]
#[should_panic(expected = "Kotlin allows only one superclass")]
fn a_class_cannot_extend_twice() {
    let _ = KtClass::class_("X")
        .extends(KtType::cls("A"), Some("1"))
        .extends(KtType::cls("B"), Some("2"));
}

#[test]
fn fun_interface_renders_its_single_abstract_method() {
    let i = KtFunInterface::new(
        "Handler",
        KtFunSig::new("run")
            .param(KtParam::new("value", KtType::long()))
            .returns(KtType::boolean()),
    )
    .vis(KtVis::Public)
    .type_param("out R");
    let src = render::render_one(&i.into(), "io.test");
    assert_eq!(
        body_of(&src),
        "\
public fun interface Handler<out R> {
    fun run(value: Long): Boolean
}
"
    );
}

#[test]
fn a_signature_becomes_a_bodyless_member() {
    // `KtFunSig` converts into `KtDecl`, which is how an interface declares an
    // abstract member without reaching for a body-less `KtFun`.
    let c = KtClass::interface_("Codec").member(
        KtFunSig::new("encode")
            .param(KtParam::new("v", KtType::string()))
            .returns(KtType::byte_array()),
    );
    let src = render::render_one(&c.into(), "io.test");
    assert_eq!(
        body_of(&src),
        "\
interface Codec {
    fun encode(v: String): ByteArray
}
"
    );
}

#[test]
fn signature_of_a_concrete_function_drops_body_and_modifiers() {
    let f = KtFun::new("close")
        .modifier("override")
        .param(KtParam::new("force", KtType::boolean()))
        .returns(KtType::unit())
        .body(KtCode::new().line("free()"));
    let sig = f.signature();
    assert_eq!(sig.name, "close");
    assert_eq!(sig.params.len(), 1);
    // Round-tripping back through `KtFun` yields an abstract member.
    let back: KtFun = sig.into();
    assert!(back.modifiers.is_empty());
    assert!(matches!(back.body, KtBody::None));
}

#[test]
fn external_is_a_body_kind_not_a_modifier() {
    let f = KtFun::new("nativeCall")
        .vis(KtVis::Internal)
        .modifier("inline")
        .param(KtParam::new("ptr", KtType::long()))
        .returns(KtType::boolean())
        .external();
    let src = render::render_one(&f.into(), "io.test");
    // `external` leads the modifier list and the function has no body.
    assert_eq!(
        body_of(&src),
        "internal external inline fun nativeCall(ptr: Long): Boolean\n"
    );
}

#[test]
fn external_and_a_body_are_mutually_exclusive() {
    // Both live in the one `body` field, so setting either clears the other —
    // `external fun f() { … }` has nowhere to exist.
    let f = KtFun::new("f")
        .external()
        .body(KtCode::new().line("work()"));
    assert!(matches!(f.body, KtBody::Block(_)));
    let g = KtFun::new("g")
        .body(KtCode::new().line("work()"))
        .external();
    assert!(matches!(g.body, KtBody::External));
}

#[test]
#[should_panic(expected = "`external` is not a modifier here")]
fn external_cannot_be_passed_as_a_modifier_string() {
    let _ = KtFun::new("f").modifier("external");
}

/// Both of these were `pub` in private modules — reachable from inside the
/// crate but not from a consumer. This test is written against the public
/// paths, so it fails to compile if either is un-exported again.
#[test]
fn banner_and_path_helper_are_reachable_from_the_crate_root() {
    use crate as kotlin_codegen;
    assert!(kotlin_codegen::KOTLIN_BANNER.starts_with("//"));
    let f = KtFile::new("io.p");
    assert_eq!(
        kotlin_codegen::merged_file_path(std::path::Path::new("/root"), &f, "X"),
        std::path::PathBuf::from("/root/io/p.kt")
    );
    // The default banner is what an un-overridden file actually renders.
    assert!(f.render().starts_with(kotlin_codegen::KOTLIN_BANNER));
}

#[test]
fn validation_reports_every_problem_not_just_the_first() {
    // Three distinct duplicates. Stopping at the first would mean three
    // build-fix-rebuild cycles to clear them.
    let f = KtFile::new("io.p")
        .decl(KtClass::class_("A"))
        .decl(KtClass::class_("A"))
        .decl(KtClass::class_("B"))
        .decl(KtClass::class_("B"))
        .decl(KtProperty::val("c").initializer("1"))
        .decl(KtProperty::val("c").initializer("2"));
    let diags = f.validate();
    assert_eq!(diags.len(), 3, "{diags:#?}");
    assert!(diags.iter().all(|d| d.severity == Severity::Error));
    assert!(diags.iter().all(|d| d.scope == "io.p"));
    // Two classes collide in the type namespace, the properties in the value
    // namespace — separate checks, reported together.
    assert_eq!(
        diags
            .iter()
            .filter(|d| d.check == Check::DuplicateType)
            .count(),
        2
    );
    assert_eq!(
        diags
            .iter()
            .filter(|d| d.check == Check::DuplicateValue)
            .count(),
        1
    );
}

#[test]
fn a_check_can_be_downgraded_or_switched_off() {
    let f = KtFile::new("io.p")
        .decl(KtClass::class_("A"))
        .decl(KtClass::class_("A"));

    let warned = f.validate_with(&ValidationPolicy::new().warn(Check::DuplicateType));
    assert_eq!(warned.len(), 1);
    assert_eq!(warned[0].severity, Severity::Warning);

    let off = f.validate_with(&ValidationPolicy::new().allow(Check::DuplicateType));
    assert!(off.is_empty());
}

#[test]
fn a_warning_does_not_stop_merging_but_is_returned() {
    let policy = ValidationPolicy::new().warn(Check::DuplicateType);
    let frags = vec![
        KtFile::new("io.p").decl(KtClass::class_("A")),
        KtFile::new("io.p").decl(KtClass::class_("A")),
    ];
    let (merged, warnings) = merge_files_with(frags, &policy).expect("warnings do not stop merge");
    assert_eq!(merged.len(), 1);
    assert_eq!(warnings.len(), 1);
    assert_eq!(warnings[0].severity, Severity::Warning);

    // The same input at default severity is an error.
    let frags = vec![
        KtFile::new("io.p").decl(KtClass::class_("A")),
        KtFile::new("io.p").decl(KtClass::class_("A")),
    ];
    assert!(merge_files(frags).is_err());
}

#[test]
fn validation_error_message_lists_each_diagnostic() {
    let frags = vec![
        KtFile::new("io.p").decl(KtClass::class_("A")),
        KtFile::new("io.p").decl(KtClass::class_("A")),
        KtFile::new("io.p").decl(KtClass::class_("B")),
        KtFile::new("io.p").decl(KtClass::class_("B")),
    ];
    let err = merge_files(frags).expect_err("duplicates");
    let text = err.to_string();
    assert!(text.contains("2 Kotlin validation error(s)"), "{text}");
    assert!(text.contains("duplicate type `A`"), "{text}");
    assert!(text.contains("duplicate type `B`"), "{text}");
    assert!(text.contains("duplicate-type"), "{text}");
}

#[test]
fn write_files_refuses_to_write_an_invalid_file() {
    let dir = unique_test_dir("kotlin_validate_write");
    let root = dir.join("generated");
    let bad = KtFile::new("io.p")
        .decl(KtClass::class_("A"))
        .decl(KtClass::class_("A"));
    let err = write_files(&[bad], &root).expect_err("invalid file");
    assert!(matches!(err, WriteKotlinError::Validation(_)));
    // Nothing was written — validation runs before the output root is touched.
    assert!(!root.exists());
    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn invalid_identifiers_are_reported_with_their_location() {
    let f = KtFile::new("io.p").decl(
        KtClass::class_("My-Class")
            .ctor_param(KtCtorParam::new("2fast", KtType::int()))
            .member(
                KtFun::new("object")
                    .param(KtParam::new("in", KtType::int()))
                    .body(KtCode::new()),
            )
            .companion(KtCompanion::named("val").member(KtProperty::val("ok").initializer("1"))),
    );
    let diags = f.validate();
    let by_scope: Vec<(String, String)> = diags
        .iter()
        .map(|d| (d.scope.clone(), d.message.clone()))
        .collect();
    assert_eq!(diags.len(), 5, "{by_scope:#?}");
    assert!(diags.iter().all(|d| d.check == Check::InvalidIdentifier));
    // The scope path locates each one without needing source positions.
    assert!(by_scope.contains(&(
        "io.p".to_string(),
        "class name `My-Class` is not a valid Kotlin identifier".to_string()
    )));
    assert!(by_scope.contains(&(
        "io.p/My-Class".to_string(),
        "constructor parameter name `2fast` is not a valid Kotlin identifier".to_string()
    )));
    assert!(by_scope.contains(&(
        "io.p/My-Class/object".to_string(),
        "parameter name `in` is not a valid Kotlin identifier".to_string()
    )));
}

#[test]
fn an_invalid_package_is_reported() {
    assert!(KtFile::new("io..jni")
        .validate()
        .iter()
        .any(|d| d.check == Check::InvalidPackage));
    assert!(KtFile::new("io.object")
        .validate()
        .iter()
        .any(|d| d.check == Check::InvalidPackage));
    // The default (root) package is legal.
    assert!(KtFile::new("").validate().is_empty());
}

#[test]
fn backticked_names_are_accepted() {
    // `escape_kotlin_ident` produces these, so rejecting them would fire on
    // output this crate itself recommends.
    let f = KtFile::new("io.p")
        .decl(KtClass::class_(escape_kotlin_ident("object")))
        .decl(KtFun::new(escape_kotlin_ident("my name")).body(KtCode::new()));
    assert!(f.validate().is_empty(), "{:#?}", f.validate());
}

#[test]
fn free_form_generic_parameters_are_not_checked() {
    // `out R` and `T : Comparable<T>` are parameter *declarations*, not plain
    // identifiers — checking them would be a false positive.
    let f = KtFile::new("io.p")
        .decl(
            KtFunInterface::new("Handler", KtFunSig::new("run"))
                .type_param("out R")
                .type_param("in T"),
        )
        .decl(
            KtFun::new("pick")
                .generic("T : Comparable<T>")
                .body(KtCode::new()),
        );
    assert!(f.validate().is_empty(), "{:#?}", f.validate());
}

#[test]
fn a_raw_blocks_name_is_an_identity_not_an_identifier() {
    // It is never rendered, so it need not be a legal Kotlin name.
    let f = KtFile::new("io.p").decl(KtDecl::Raw {
        name: "__hoisted::singleton#1".to_string(),
        code: KtCode::new().line("internal val x = 1"),
    });
    assert!(f.validate().is_empty(), "{:#?}", f.validate());
}

#[test]
fn a_class_and_a_property_may_share_a_name() {
    // Kotlin keeps types and values in separate namespaces, so this is legal —
    // and was rejected before the namespaces were split.
    let f = KtFile::new("io.p")
        .decl(KtClass::class_("Foo"))
        .decl(KtProperty::val("Foo").initializer("1"))
        .decl(KtFun::new("Foo").body(KtCode::new()));
    assert!(f.validate().is_empty(), "{:#?}", f.validate());
}

#[test]
fn functions_overload_on_parameter_types() {
    let f = KtFile::new("io.p")
        .decl(
            KtFun::new("send")
                .param(KtParam::new("v", KtType::int()))
                .body(KtCode::new()),
        )
        .decl(
            KtFun::new("send")
                .param(KtParam::new("v", KtType::string()))
                .body(KtCode::new()),
        )
        .decl(KtFun::new("send").body(KtCode::new()));
    assert!(f.validate().is_empty(), "{:#?}", f.validate());
}

#[test]
fn functions_with_identical_parameter_types_collide() {
    // Return type is not part of the signature: Kotlin rejects these as a
    // redeclaration whatever they return.
    let f = KtFile::new("io.p")
        .decl(
            KtFun::new("send")
                .param(KtParam::new("v", KtType::int()))
                .returns(KtType::boolean())
                .body(KtCode::new()),
        )
        .decl(
            KtFun::new("send")
                .param(KtParam::new("other", KtType::int()))
                .returns(KtType::long())
                .body(KtCode::new()),
        );
    let diags = f.validate();
    assert_eq!(diags.len(), 1, "{diags:#?}");
    assert_eq!(diags[0].check, Check::DuplicateFunction);
    assert!(diags[0].message.contains("`send(Int)`"), "{diags:#?}");
}

#[test]
fn extensions_on_different_receivers_are_not_duplicates() {
    // Kotlin dispatches an extension on its receiver, so these are two
    // declarations. Keying the overload on the name alone reported them as a
    // redeclaration.
    let f = KtFile::new("io.p")
        .decl(
            KtFun::new("asRaw")
                .receiver(KtType::cls("io.p.Cb"))
                .body(KtCode::new()),
        )
        .decl(
            KtFun::new("asRaw")
                .receiver(KtType::cls("io.p.Other"))
                .body(KtCode::new()),
        );
    assert_eq!(f.validate(), vec![]);
}

#[test]
fn two_extensions_on_the_same_receiver_are_duplicates() {
    let f = KtFile::new("io.p")
        .decl(
            KtFun::new("asRaw")
                .receiver(KtType::cls("io.p.Cb"))
                .body(KtCode::new()),
        )
        .decl(
            KtFun::new("asRaw")
                .receiver(KtType::cls("io.p.Cb"))
                .body(KtCode::new()),
        );
    let diags = f.validate();
    assert_eq!(diags.len(), 1, "{diags:#?}");
    assert_eq!(diags[0].check, Check::DuplicateFunction);
    assert!(diags[0].message.contains("`io.p.Cb.asRaw()`"), "{diags:#?}");
}

#[test]
fn an_extension_does_not_collide_with_a_member_of_the_same_name() {
    // `fun Cb.asRaw()` and `fun asRaw()` are different declarations.
    let f = KtFile::new("io.p")
        .decl(
            KtFun::new("asRaw")
                .receiver(KtType::cls("io.p.Cb"))
                .body(KtCode::new()),
        )
        .decl(KtFun::new("asRaw").body(KtCode::new()));
    assert_eq!(f.validate(), vec![]);
}

#[test]
fn duplicates_inside_a_class_body_are_found() {
    // Where nearly all generated functions actually live — and where the old
    // top-level-only check never looked.
    let f = KtFile::new("io.p").decl(
        KtClass::class_("Session")
            .member(KtFun::new("close").body(KtCode::new()))
            .member(KtFun::new("close").body(KtCode::new()))
            .companion(
                KtCompanion::new()
                    .member(KtFun::new("of").body(KtCode::new()))
                    .member(KtFun::new("of").body(KtCode::new())),
            ),
    );
    let diags = f.validate();
    assert_eq!(diags.len(), 2, "{diags:#?}");
    assert!(diags.iter().all(|d| d.check == Check::DuplicateFunction));
    assert_eq!(diags[0].scope, "io.p/Session");
    assert_eq!(diags[1].scope, "io.p/Session/Companion");
}

#[test]
fn a_ctor_property_collides_with_a_member_property() {
    let f = KtFile::new("io.p").decl(
        KtClass::class_("P")
            .ctor_param(KtCtorParam::new("id", KtType::long()).val())
            .member(KtProperty::val("id").initializer("0")),
    );
    let diags = f.validate();
    assert_eq!(diags.len(), 1, "{diags:#?}");
    assert_eq!(diags[0].check, Check::DuplicateValue);
    assert_eq!(diags[0].scope, "io.p/P");
}

#[test]
fn a_plain_ctor_parameter_declares_nothing() {
    // Not a `val`/`var`, so it is constructor-local and cannot collide with a
    // member of the same name.
    let f = KtFile::new("io.p").decl(
        KtClass::class_("P")
            .ctor_param(KtCtorParam::new("id", KtType::long()))
            .member(KtProperty::val("id").initializer("0")),
    );
    assert!(f.validate().is_empty(), "{:#?}", f.validate());
}

#[test]
fn duplicate_fun_interfaces_are_found() {
    // Never checked at all before: two of these merged into a broken file.
    let f = KtFile::new("io.p")
        .decl(KtFunInterface::new("Handler", KtFunSig::new("run")))
        .decl(KtFunInterface::new("Handler", KtFunSig::new("run")));
    let diags = f.validate();
    assert_eq!(diags.len(), 1, "{diags:#?}");
    assert_eq!(diags[0].check, Check::DuplicateType);
}

#[test]
fn a_class_and_a_typealias_collide() {
    let f = KtFile::new("io.p")
        .decl(KtClass::class_("Foo"))
        .decl(KtDecl::TypeAlias {
            vis: KtVis::Public,
            name: "Foo".to_string(),
            target: KtType::int(),
        });
    let diags = f.validate();
    assert_eq!(diags.len(), 1, "{diags:#?}");
    assert_eq!(diags[0].check, Check::DuplicateType);
}

#[test]
fn identical_raw_blocks_merge_but_differing_ones_are_an_error() {
    let raw = |code: &str| KtDecl::Raw {
        name: "__Builder".to_string(),
        code: KtCode::new().line(code),
    };

    // Two fragments hoisting the same singleton: deduplication, not a mistake.
    let merged = merge_files(vec![
        KtFile::new("io.p").decl(raw("internal val __Builder = 1")),
        KtFile::new("io.p").decl(raw("internal val __Builder = 1")),
    ])
    .expect("identical raw blocks merge");
    assert_eq!(merged[0].decls.len(), 1);

    // Two different blocks claiming one identity is a genuine collision.
    let err = merge_files(vec![
        KtFile::new("io.p").decl(raw("internal val __Builder = 1")),
        KtFile::new("io.p").decl(raw("internal val __Builder = 2")),
    ])
    .expect_err("differing raw blocks collide");
    assert!(err.to_string().contains("duplicate raw block"), "{err}");
}

#[test]
fn a_nested_class_is_its_own_scope() {
    // `Inner.value` and `Outer.value` do not collide.
    let f = KtFile::new("io.p").decl(
        KtClass::class_("Outer")
            .member(KtProperty::val("value").initializer("1"))
            .member(KtClass::class_("Inner").member(KtProperty::val("value").initializer("2"))),
    );
    assert!(f.validate().is_empty(), "{:#?}", f.validate());
}

#[test]
fn a_bare_property_is_reported() {
    let f = KtFile::new("io.p").decl(KtProperty::val("x"));
    let diags = f.validate();
    assert_eq!(diags.len(), 1, "{diags:#?}");
    assert_eq!(diags[0].check, Check::PropertyWithoutTypeOrValue);
}

#[test]
fn a_property_with_any_one_of_the_three_is_accepted() {
    // Type alone is an abstract property; a value alone infers its type;
    // accessors alone is the third legal shape. Only all-absent is wrong.
    let f = KtFile::new("io.p")
        .decl(KtProperty::val("a").ty(KtType::int()))
        .decl(KtProperty::val("b").initializer("1"))
        .decl(KtProperty::val("c").delegate("lazy { 1 }"))
        .decl(KtProperty::val("d").accessors(KtCode::new().line("get() = 1")));
    assert!(f.validate().is_empty(), "{:#?}", f.validate());
}

#[test]
fn enum_entries_must_call_a_declared_primary_constructor() {
    let f = KtFile::new("io.p").decl(
        KtClass::enum_("Kind")
            .ctor_param(KtCtorParam::new("code", KtType::int()).val())
            .entry(KtEnumEntry::with_args("A", "1"))
            .entry(KtEnumEntry::new("B")),
    );
    let diags = f.validate();
    assert_eq!(diags.len(), 1, "{diags:#?}");
    assert_eq!(diags[0].check, Check::EnumEntryMissingArguments);
    assert_eq!(diags[0].scope, "io.p/Kind");
    assert!(diags[0].message.contains("`B`"), "{diags:#?}");
}

#[test]
fn an_enum_without_a_constructor_needs_no_entry_arguments() {
    let f = KtFile::new("io.p").decl(
        KtClass::enum_("Kind")
            .entry(KtEnumEntry::new("A"))
            .entry(KtEnumEntry::new("B")),
    );
    assert!(f.validate().is_empty(), "{:#?}", f.validate());
}

#[test]
fn a_bodyless_function_is_allowed_only_where_it_means_abstract() {
    // Interface member: abstract by position, no keyword needed.
    let ok_iface = KtFile::new("io.p")
        .decl(KtClass::interface_("I").member(KtFunSig::new("run")))
        .decl(KtClass::sealed_interface("S").member(KtFunSig::new("run")));
    assert!(ok_iface.validate().is_empty(), "{:#?}", ok_iface.validate());

    // Abstract class member: allowed, but it has to say `abstract`.
    let ok_abstract = KtFile::new("io.p").decl(
        KtClass::class_with(KtClassModifier::Abstract, "A")
            .member(KtFun::new("run").modifier("abstract")),
    );
    assert!(
        ok_abstract.validate().is_empty(),
        "{:#?}",
        ok_abstract.validate()
    );

    let missing_keyword = KtFile::new("io.p")
        .decl(KtClass::class_with(KtClassModifier::Abstract, "A").member(KtFun::new("run")));
    assert_eq!(
        missing_keyword.validate()[0].check,
        Check::FunctionWithoutBody
    );

    // Top level and inside a concrete class, a body is always required.
    let top_level = KtFile::new("io.p").decl(KtFun::new("run"));
    assert_eq!(top_level.validate()[0].check, Check::FunctionWithoutBody);

    let concrete = KtFile::new("io.p").decl(KtClass::class_("C").member(KtFun::new("run")));
    assert_eq!(concrete.validate()[0].check, Check::FunctionWithoutBody);

    // `external` counts as having a body kind, so it is never flagged.
    let ext = KtFile::new("io.p").decl(KtFun::new("run").external());
    assert!(ext.validate().is_empty(), "{:#?}", ext.validate());
}

#[test]
fn a_companion_is_concrete_so_its_members_need_bodies() {
    let f = KtFile::new("io.p")
        .decl(KtClass::interface_("I").companion(KtCompanion::new().member(KtFun::new("of"))));
    let diags = f.validate();
    assert_eq!(diags.len(), 1, "{diags:#?}");
    assert_eq!(diags[0].check, Check::FunctionWithoutBody);
    assert_eq!(diags[0].scope, "io.p/I/Companion");
}

#[test]
fn check_all_lists_every_variant() {
    // `Check::ALL` drives `warn_all`, so a check missing from it would silently
    // stay fatal during a warn-mode rollout. Names are unique and non-empty.
    let names: std::collections::BTreeSet<&str> = Check::ALL.iter().map(|c| c.name()).collect();
    assert_eq!(names.len(), Check::ALL.len());
    assert!(names.iter().all(|n| !n.is_empty()));
}

#[test]
fn warn_all_lets_a_generator_adopt_validation_gradually() {
    let f = KtFile::new("io.p")
        .decl(KtClass::class_("A"))
        .decl(KtClass::class_("A"))
        .decl(KtProperty::val("bare"))
        .decl(KtFun::new("nobody"));
    // Fatal by default...
    assert!(f.validate().iter().all(|d| d.severity == Severity::Error));
    // ...and purely informational under the rollout policy.
    let warned = f.validate_with(&ValidationPolicy::warn_all());
    assert!(!warned.is_empty());
    assert!(warned.iter().all(|d| d.severity == Severity::Warning));
    // Which means merging succeeds and hands the warnings back.
    let (merged, warnings) =
        merge_files_with(vec![f], &ValidationPolicy::warn_all()).expect("warnings do not stop");
    assert_eq!(merged.len(), 1);
    assert_eq!(warnings.len(), warned.len());
}

// ── Review follow-ups ────────────────────────────────────────────────────

#[test]
#[should_panic(expected = "must be a property")]
fn a_data_class_rejects_a_plain_constructor_parameter() {
    // Kotlin requires every primary-constructor parameter of a data class to
    // be a `val`/`var`; a plain one is a compile error, not a style choice.
    let _ = KtClass::data("P", KtCtorParam::new("x", KtType::int()));
}

#[test]
#[should_panic(expected = "must be a property")]
fn a_data_class_rejects_a_plain_parameter_added_later() {
    let _ = KtClass::data("P", KtCtorParam::new("x", KtType::int()).val())
        .ctor_param(KtCtorParam::new("y", KtType::int()));
}

#[test]
fn a_data_class_accepts_val_and_var_properties() {
    let c = KtClass::data("P", KtCtorParam::new("x", KtType::int()).val())
        .ctor_param(KtCtorParam::new("y", KtType::int()).var());
    assert_eq!(c.ctor_params().len(), 2);
}

#[test]
#[should_panic(expected = "single read-only property")]
fn a_value_class_rejects_a_var() {
    // A value class wraps one *read-only* property.
    let _ = KtClass::value("Id", KtCtorParam::new("v", KtType::long()).var());
}

#[test]
#[should_panic(expected = "single read-only property")]
fn a_value_class_rejects_a_plain_parameter() {
    let _ = KtClass::value("Id", KtCtorParam::new("v", KtType::long()));
}

#[test]
#[should_panic(expected = "name cannot be empty")]
fn a_named_companion_rejects_an_empty_name() {
    // Would have rendered `companion object ` with a dangling space.
    let _ = KtCompanion::named("");
}

#[test]
fn a_companion_object_can_extend_a_class() {
    // Kotlin allows this, the renderer already supported it, but no builder
    // reached it — the field had to be assigned directly.
    let c = KtClass::class_("Holder").companion(
        KtCompanion::new()
            .extends(KtType::cls("Base"), Some("1"))
            .implements(KtType::cls("Marker"))
            .member(KtProperty::val("N").initializer("1")),
    );
    let src = render::render_one(&c.into(), "io.test");
    assert_eq!(
        body_of(&src),
        "\
class Holder {
    companion object : Base(1), Marker {
        val N = 1
    }
}
"
    );
}

#[test]
#[should_panic(expected = "only one superclass")]
fn a_companion_cannot_extend_twice() {
    let _ = KtCompanion::new()
        .extends(KtType::cls("A"), None)
        .extends(KtType::cls("B"), None);
}

#[test]
#[should_panic(expected = "`external` is not a modifier here")]
fn external_with_trailing_space_is_still_rejected() {
    // An exact-string check would have let this through, and it renders the
    // keyword just the same.
    let _ = KtFun::new("f").modifier("external ");
}

#[test]
#[should_panic(expected = "`external` is not a modifier here")]
fn external_inside_a_multi_keyword_modifier_is_rejected() {
    // Modifier strings may hold several keywords ("final override").
    let _ = KtFun::new("f").modifier("external inline");
}

#[test]
fn a_modifier_merely_containing_external_as_a_substring_is_fine() {
    let f = KtFun::new("f").modifier("externalish").body(KtCode::new());
    assert_eq!(f.modifiers, vec!["externalish".to_string()]);
}

#[test]
fn scope_paths_have_no_leading_slash_in_the_root_package() {
    let f = KtFile::new("").decl(
        KtClass::class_("Outer")
            .member(KtProperty::val("dup").initializer("1"))
            .member(KtProperty::val("dup").initializer("2")),
    );
    let diags = f.validate();
    assert_eq!(diags.len(), 1, "{diags:#?}");
    assert_eq!(diags[0].scope, "Outer");
}

#[test]
fn three_colliding_imports_all_report_against_the_one_owner() {
    // `ImportSet` gives the first registration ownership; the diagnostic must
    // agree, or the report names whichever FQN happened to come last.
    let f = KtFile::new("io.p")
        .import("io.a.Same")
        .import("io.b.Same")
        .import("io.c.Same");
    let diags = f.validate();
    assert_eq!(diags.len(), 2, "{diags:#?}");
    assert!(diags.iter().all(|d| d.check == Check::ImportCollision));
    assert!(diags.iter().all(|d| d.message.contains("`io.a.Same`")));
}

#[test]
fn kt_decl_variants_stay_close_in_size() {
    // `KtDecl::Class` is the largest variant; clippy's `large_enum_variant`
    // fires when it exceeds the next-largest by more than 200 bytes, which it
    // did when `KtClass` held its companion inline.
    let class = std::mem::size_of::<KtClass>();
    let next = std::mem::size_of::<KtFun>()
        .max(std::mem::size_of::<KtProperty>())
        .max(std::mem::size_of::<KtFunInterface>());
    assert!(
        class <= next + 200,
        "KtClass is {class} bytes against a next-largest of {next}; \
         box a field before clippy does it for you"
    );
}

#[test]
fn a_named_companion_collides_with_a_nested_type_of_that_name() {
    // Kotlin: "Conflicting declarations: class Factory, companion object
    // Factory" — both are classifiers nested in `Outer`.
    let f = KtFile::new("io.p").decl(
        KtClass::class_("Outer")
            .member(KtClass::class_("Factory"))
            .companion(KtCompanion::named("Factory")),
    );
    let diags = f.validate();
    assert_eq!(diags.len(), 1, "{diags:#?}");
    assert_eq!(diags[0].check, Check::DuplicateType);
    assert_eq!(diags[0].scope, "io.p/Outer");
    assert!(diags[0].message.contains("companion object `Factory`"));
}

#[test]
fn a_named_companion_may_reuse_a_name_from_another_namespace() {
    // A property and a function named `Factory` are values, not types.
    let f = KtFile::new("io.p").decl(
        KtClass::class_("Outer")
            .member(KtProperty::val("Factory").initializer("1"))
            .member(KtFun::new("Factory").body(KtCode::new()))
            .companion(KtCompanion::named("Factory")),
    );
    assert!(f.validate().is_empty(), "{:#?}", f.validate());
}

#[test]
fn an_anonymous_companion_declares_no_name() {
    // `Companion` is a name this crate supplies, not one the model declares,
    // so a generator that manages the collision itself is not second-guessed.
    let f = KtFile::new("io.p").decl(
        KtClass::class_("Outer")
            .member(KtClass::class_("Companion"))
            .companion(KtCompanion::new()),
    );
    assert!(f.validate().is_empty(), "{:#?}", f.validate());
}

#[test]
fn a_named_companion_does_not_collide_across_class_scopes() {
    // Each class is its own scope, so two classes may both have a companion
    // named `Factory`, and a sibling class may share the name too.
    let f = KtFile::new("io.p")
        .decl(KtClass::class_("A").companion(KtCompanion::named("Factory")))
        .decl(KtClass::class_("B").companion(KtCompanion::named("Factory")))
        .decl(KtClass::class_("Factory"));
    assert!(f.validate().is_empty(), "{:#?}", f.validate());
}

#[test]
fn merging_carries_a_banner_override_into_the_merged_file() {
    // The override belongs to the package, not to whichever fragment carried
    // it, so it must survive a merge that rebuilds the file.
    let merged = merge_files(vec![
        KtFile::new("io.p").decl(KtFun::new("a").body(KtCode::new())),
        KtFile::new("io.p")
            .banner("// custom")
            .decl(KtFun::new("b").body(KtCode::new())),
    ])
    .expect("merge");
    assert_eq!(merged[0].banner.as_deref(), Some("// custom"));
    assert!(merged[0].render().starts_with("// custom\n"));

    // First fragment to set one wins; a later fragment does not clear it.
    let merged = merge_files(vec![
        KtFile::new("io.p").banner("// first"),
        KtFile::new("io.p").banner("// second"),
    ])
    .expect("merge");
    assert_eq!(merged[0].banner.as_deref(), Some("// first"));
}

#[test]
fn a_function_type_receiver_is_parenthesized() {
    // `fun (Int) -> String.ext()` parses the `.` against the return type and
    // does not compile; the receiver needs its own parentheses.
    let f = KtFun::new("asRaw")
        .receiver(KtType::lambda(
            [("value".to_string(), KtType::int())],
            KtType::string(),
        ))
        .body(KtCode::new());
    let src = render::render_one(&f.into(), "io.p");
    assert!(
        src.contains("fun ((value: Int) -> String).asRaw()"),
        "{src}"
    );
}

#[test]
fn a_nullable_function_type_receiver_is_not_double_parenthesized() {
    // `KtType::render` already wraps a nullable function type.
    let f = KtFun::new("asRaw")
        .receiver(
            KtType::lambda([("value".to_string(), KtType::int())], KtType::string()).nullable(),
        )
        .body(KtCode::new());
    let src = render::render_one(&f.into(), "io.p");
    assert!(
        src.contains("fun ((value: Int) -> String)?.asRaw()"),
        "{src}"
    );
}

#[test]
fn a_named_receiver_is_rendered_unchanged() {
    let mut imports = ImportSet::new("io.p");
    assert_eq!(
        KtType::cls("io.other.Cb").render_receiver(&mut imports),
        "Cb"
    );
    assert_eq!(
        KtType::generic("List", [KtType::int()]).render_receiver(&mut imports),
        "List<Int>"
    );
    assert_eq!(
        KtType::cls("io.other.Cb")
            .nullable()
            .render_receiver(&mut imports),
        "Cb?"
    );
}

#[test]
fn a_duplicate_on_a_function_type_receiver_reads_as_kotlin_syntax() {
    // The diagnostic parenthesizes the receiver on the same rule the renderer
    // uses, so what it prints matches what would be emitted.
    let ext = || {
        KtFun::new("asRaw")
            .receiver(KtType::lambda(
                [("value".to_string(), KtType::int())],
                KtType::unit(),
            ))
            .body(KtCode::new())
    };
    let f = KtFile::new("io.p").decl(ext()).decl(ext());
    let diags = f.validate();
    assert_eq!(diags.len(), 1, "{diags:#?}");
    assert!(
        diags[0]
            .message
            .contains("`((value: Int) -> Unit).asRaw()`"),
        "{diags:#?}"
    );
}