day-build 0.3.0

Declarative app development API using native UI toolkits
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
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
// Copyright © The Daybrite Project
// SPDX-License-Identifier: MPL-2.0

//! daybridge codegen (docs/bridge.md, DESIGN.md §15.6) — the Rust half.
//!
//! Called from a bridged crate's `build.rs`:
//!
//! ```ignore
//! fn main() { day_build::bridge::generate().expect("day-build: bridge codegen"); }
//! ```
//!
//! It reads the crate's own `src/**/*.rs`, finds every `day_bridge::bridge! { … }` block, and
//! writes two things into `$OUT_DIR/day-bridge/`:
//!
//! - `mod.rs` — the Rust side: each declared function, cfg-gated per target, plus a
//!   `<fn>_support()` reporting what this target's arm promises. The `bridge!` macro `include!`s it.
//! - `manifest.json` — every foreign arm, for `day build` to emit adapters from (docs/bridge.md
//!   "What the build does"). Written even when empty so a stale one never lingers.
//!
//! Parsing is a text scan, not a syntax tree, for the same reason `swiftui.rs` scans Swift: the
//! input is *not all Rust*. An arm's body is a raw string holding another language, and the
//! attribute markers are inert tokens rustc never resolves.

use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::path::{Path, PathBuf};

/// A language an arm can be written in.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub enum Lang {
    Rust,
    Swift,
    Kotlin,
    Java,
    ArkTs,
    Js,
    C,
    Cpp,
}

impl Lang {
    fn parse(s: &str) -> Option<Lang> {
        Some(match s {
            "rust" => Lang::Rust,
            "swift" => Lang::Swift,
            "kotlin" => Lang::Kotlin,
            "java" => Lang::Java,
            "arkts" => Lang::ArkTs,
            "js" => Lang::Js,
            "c" => Lang::C,
            "cpp" => Lang::Cpp,
            _ => return None,
        })
    }

    /// The key used in the manifest and in `day build`'s emitters.
    pub fn key(self) -> &'static str {
        match self {
            Lang::Rust => "rust",
            Lang::Swift => "swift",
            Lang::Kotlin => "kotlin",
            Lang::Java => "java",
            Lang::ArkTs => "arkts",
            Lang::Js => "js",
            Lang::C => "c",
            Lang::Cpp => "cpp",
        }
    }
}

/// Every platform an arm may claim. `Other` is "whatever no other arm took".
const PLATFORMS: &[&str] = &[
    "ios", "macos", "android", "ohos", "web", "linux", "windows", "other",
];

/// Every option an arm may carry beside `platforms` (docs/bridge.md). Closed, so a typo fails the
/// build instead of being ignored.
const ARM_OPTIONS: &[&str] = &["src", "link", "pkg_config", "encoding", "support"];

/// The `cfg` predicate for one platform. `linux` and `ohos` both report `target_os = "linux"`,
/// so they are told apart by `target_env` exactly as day-part-battery's hand-written arms do.
fn cfg_for(platform: &str) -> &'static str {
    match platform {
        "ios" => "target_os = \"ios\"",
        "macos" => "target_os = \"macos\"",
        "android" => "target_os = \"android\"",
        "windows" => "target_os = \"windows\"",
        "web" => "target_arch = \"wasm32\"",
        "linux" => "all(target_os = \"linux\", not(target_env = \"ohos\"))",
        "ohos" => "all(target_os = \"linux\", target_env = \"ohos\")",
        _ => "",
    }
}

/// The v1 type table (docs/bridge.md "Types"). Anything else is a build error, which is how a
/// declaration that four languages cannot agree on is caught before an arm is written against it.
const SCALARS: &[&str] = &["bool", "i32", "i64", "f32", "f64"];

/// One function in a `#[day_bridge::declare] extern "day" { … }` block.
#[derive(Clone, Debug)]
pub struct Decl {
    pub name: String,
    /// `(name, type)` in declaration order.
    pub args: Vec<(String, String)>,
    /// The return type as written, minus `-> `; empty for unit.
    pub ret: String,
    /// Byte offset of the declaration in its source file, for diagnostics.
    pub line: usize,
}

/// One implementation of the declared API for a set of platforms.
#[derive(Clone, Debug)]
pub struct Arm {
    pub lang: Lang,
    pub platforms: Vec<String>,
    /// Inline body (the raw string's contents), or `None` when the arm names a file.
    pub body: Option<String>,
    /// The arm's file-level preamble — imports only, and only where the language needs them
    /// outside the body (a JVM arm's body sits inside the generated class). Per ARM, not per
    /// language: imports are usually platform-specific, and two arms of one language claiming
    /// different platforms must not receive each other's.
    pub prelude: Option<String>,
    /// `src = "…"`, relative to the crate root.
    pub src: Option<String>,
    /// Extra keys: `encoding`, `link`, `pkg_config`, `support`.
    pub options: BTreeMap<String, String>,
    /// The crate-relative `.rs` this arm was written in, for `#line` and diagnostics.
    pub source: Option<String>,
    /// The line the attribute sits on — what an error message names.
    pub line: usize,
    /// The line the arm's first line of foreign code sits on — what `#line` maps to, so a
    /// compiler diagnostic lands on the code rather than on the marker above it.
    pub body_line: usize,
}

/// Everything one crate declares.
#[derive(Default, Debug)]
pub struct Bridge {
    pub decls: Vec<Decl>,
    pub arms: Vec<Arm>,
}

/// Read `src/**/*.rs`, generate `$OUT_DIR/day-bridge/{mod.rs,manifest.json}`.
///
/// A crate with no `bridge!` block still gets an (empty) `mod.rs`, so a crate that removes its last
/// bridge does not fail on a stale `include!`.
pub fn generate() -> Result<(), String> {
    let root = std::env::var("CARGO_MANIFEST_DIR").map_err(|_| "CARGO_MANIFEST_DIR unset")?;
    let out = std::env::var("OUT_DIR").map_err(|_| "OUT_DIR unset")?;
    let crate_name = std::env::var("CARGO_PKG_NAME").map_err(|_| "CARGO_PKG_NAME unset")?;
    generate_in(Path::new(&root), Path::new(&out), &crate_name)
}

/// Parse one crate's `bridge!` blocks — the entry point `day build` uses to generate the foreign
/// half. The CLI reads crate SOURCES rather than build-script output, so staging never depends on
/// cargo having run first (docs/bridge.md "What the build does").
pub fn parse_crate(root: &Path) -> Result<Bridge, String> {
    let bridge = scan(root)?;
    validate(&bridge)?;
    Ok(bridge)
}

/// Whether a crate declares any bridge at all — cheap enough to run over a whole dependency graph.
pub fn is_bridged(root: &Path) -> bool {
    let mut sources: Vec<PathBuf> = Vec::new();
    collect_rs(&root.join("src"), &mut sources);
    sources.iter().any(|p| {
        std::fs::read_to_string(p)
            .map(|t| {
                t.lines()
                    .any(|l| !l.trim_start().starts_with("//") && l.contains("bridge!"))
            })
            .unwrap_or(false)
    })
}

/// The generated Swift adapter for `arm`, ready to stage into the DayPieces package.
pub fn swift_adapter(bridge: &Bridge, arm: &Arm, crate_name: &str) -> String {
    render_swift(bridge, arm, crate_name)
}

/// The generated JVM adapter for `arm` — Kotlin or Java — ready to stage into a Gradle source
/// directory. The language decides only the file extension and whether the project needs the
/// Kotlin plugin (see the check in `day lint` and the error in `day build`).
pub fn jvm_adapter(bridge: &Bridge, arm: &Arm, crate_name: &str) -> String {
    match arm.lang {
        Lang::Java => render_java(arm, crate_name),
        _ => render_kotlin(bridge, arm, crate_name),
    }
}

/// The generated ES module for `arm`, ready to stage beside the day-dom shim.
pub fn js_adapter(bridge: &Bridge, arm: &Arm, crate_name: &str) -> String {
    render_js(bridge, arm, crate_name)
}

/// The generated ArkTS module for `arm`, ready to stage into the HarmonyOS host project.
pub fn arkts_adapter(bridge: &Bridge, arm: &Arm, crate_name: &str) -> String {
    render_arkts(bridge, arm, crate_name)
}

/// The Java package a crate's Kotlin adapter declares — the directory Gradle expects it under.
pub fn kotlin_package_of(crate_name: &str) -> String {
    kotlin_package(crate_name)
}

/// The file name an arm's adapter is staged under.
pub fn adapter_name(arm: &Arm, crate_name: &str) -> String {
    generated_name(arm, crate_name)
}

fn scan(root: &Path) -> Result<Bridge, String> {
    let mut sources: Vec<PathBuf> = Vec::new();
    collect_rs(&root.join("src"), &mut sources);
    sources.sort(); // deterministic output (docs/bridge.md "Determinism and mtimes")

    let mut bridge = Bridge::default();
    for path in &sources {
        let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
        if !text.contains("bridge!") {
            continue;
        }
        let rel = path
            .strip_prefix(root)
            .unwrap_or(path)
            .display()
            .to_string();
        // Forward slashes always. This string is baked into every generated artifact — the C
        // `#line`, Swift's `#sourceLocation`, the Kotlin header, the `@generated` banner — so a
        // host separator would make the generated files differ byte-for-byte between Windows and
        // everywhere else, against the determinism this module already sorts its inputs for.
        // Windows-only: a backslash is a legal character in a POSIX filename.
        #[cfg(windows)]
        let rel = rel.replace('\\', "/");
        parse_into(&text, &rel, &mut bridge).map_err(|e| format!("{rel}: {e}"))?;
    }
    Ok(bridge)
}

/// The testable core of [`generate`]: the Rust side, plus the C/C++ arms cargo itself compiles.
pub fn generate_in(root: &Path, out_dir: &Path, crate_name: &str) -> Result<(), String> {
    // Only a build script may print cargo directives — `parse_crate` is also called by `day build`,
    // where a stray `cargo:` line would land in the CLI's own output (and, once, inside a
    // generated ES module).
    let mut sources: Vec<PathBuf> = Vec::new();
    collect_rs(&root.join("src"), &mut sources);
    sources.sort();
    for path in &sources {
        println!("cargo:rerun-if-changed={}", path.display());
    }

    let bridge = parse_crate(root)?;

    let dir = out_dir.join("day-bridge");
    std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
    write_if_changed(&dir.join("mod.rs"), &render_rust(&bridge, crate_name))?;
    emit_c(&bridge, &dir, crate_name)?;
    Ok(())
}

/// The platform this build is for, from cargo's own cfg environment — the same distinction the
/// generated `cfg`s make, so exactly one arm is ever active.
fn active_platform() -> Option<String> {
    let os = std::env::var("CARGO_CFG_TARGET_OS").ok()?;
    let env = std::env::var("CARGO_CFG_TARGET_ENV").unwrap_or_default();
    let arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default();
    Some(
        match (os.as_str(), env.as_str(), arch.as_str()) {
            (_, _, "wasm32") => "web",
            ("linux", "ohos", _) => "ohos",
            ("linux", _, _) => "linux",
            ("ios", _, _) => "ios",
            ("macos", _, _) => "macos",
            ("android", _, _) => "android",
            ("windows", _, _) => "windows",
            _ => return None,
        }
        .to_string(),
    )
}

/// Write every C/C++ arm's translation unit, and compile the one this target selects. Swift,
/// Kotlin, ArkTS and JavaScript adapters are NOT written here — `day build` renders those from the
/// crate's source when it stages them, so each artifact has exactly one producer.
///
/// Sources for inactive arms are written too: they cost nothing, they keep the generated tree
/// diffable, and a cross-compile that switches targets finds them already correct.
fn emit_c(bridge: &Bridge, dir: &Path, crate_name: &str) -> Result<(), String> {
    let active = active_platform();

    // Declare the cfg unconditionally (cargo lints unknown ones), and set it only when `day build`
    // says it is staging and linking this crate's foreign half for the active target.
    println!("cargo:rustc-check-cfg=cfg({STAGED_CFG})");
    println!("cargo:rerun-if-env-changed=DAY_BRIDGE_STAGED");
    let staged_here = std::env::var("DAY_BRIDGE_STAGED").is_ok()
        && bridge.arms.iter().any(|a| {
            staged_by_cli(a.lang)
                && active
                    .as_deref()
                    .is_some_and(|p| a.platforms.iter().any(|x| x == p))
        });
    if staged_here {
        println!("cargo:rustc-cfg={STAGED_CFG}");
    }

    // Swift arms are compiled by `day build`'s prepass into the generated DayPieces package, not
    // by cargo: this writes the adapter and the manifest points at it (docs/bridge.md).
    for arm in bridge.arms.iter().filter(|a| a.lang == Lang::Swift) {
        let file = dir.join(format!("{}-{}.swift", crate_name, arm.platforms.join("-")));
        write_if_changed(&file, &render_swift(bridge, arm, crate_name))?;
    }

    for arm in bridge
        .arms
        .iter()
        .filter(|a| matches!(a.lang, Lang::C | Lang::Cpp))
    {
        let cpp = arm.lang == Lang::Cpp;
        let file = dir.join(format!(
            "{}-{}.{}",
            crate_name,
            arm.platforms.join("-"),
            if cpp { "cpp" } else { "c" }
        ));
        write_if_changed(&file, &render_c(bridge, arm, crate_name))?;

        let selected = active
            .as_deref()
            .is_some_and(|p| arm.platforms.iter().any(|a| a == p));
        if !selected {
            continue;
        }
        let mut build = cc::Build::new();
        build.file(&file).cpp(cpp).warnings(false);
        if cpp {
            build.std("c++17");
        }
        build.compile(&format!("day_bridge_{}", crate_name.replace('-', "_")));
        for lib in arm
            .options
            .get("link")
            .map(|v| v.trim_matches(['[', ']']).to_string())
            .unwrap_or_default()
            .split(',')
            .map(|l| l.trim().trim_matches('"'))
            .filter(|l| !l.is_empty())
        {
            println!("cargo:rustc-link-lib={lib}");
        }
        if let Some(pkg) = arm.options.get("pkg_config") {
            println!("cargo:rustc-link-lib={pkg}");
        }
    }
    Ok(())
}

fn collect_rs(dir: &Path, out: &mut Vec<PathBuf>) {
    let Ok(rd) = std::fs::read_dir(dir) else {
        return;
    };
    for entry in rd.flatten() {
        let path = entry.path();
        if path.is_dir() {
            collect_rs(&path, out);
        } else if path.extension().and_then(|e| e.to_str()) == Some("rs") {
            out.push(path);
        }
    }
}

// ---------------------------------------------------------------------------
// Parsing
// ---------------------------------------------------------------------------

/// Find every `bridge! { … }` body in `text` and parse its items into `bridge`.
fn parse_into(text: &str, source: &str, bridge: &mut Bridge) -> Result<(), String> {
    let mut at = 0;
    while let Some(found) = text[at..].find("bridge!") {
        let start = at + found;
        // A doc comment showing the macro is not an invocation of it (this crate's own docs do
        // exactly that), so a match whose line is a comment is skipped.
        let line_start = text[..start].rfind('\n').map(|i| i + 1).unwrap_or(0);
        if text[line_start..start].trim_start().starts_with("//") {
            at = start + "bridge!".len();
            continue;
        }
        // Only a macro invocation: require the next non-space character to open a brace.
        let after = start + "bridge!".len();
        let Some(brace) = text[after..]
            .find(|c: char| !c.is_whitespace())
            .map(|i| after + i)
        else {
            break;
        };
        if text.as_bytes().get(brace) != Some(&b'{') {
            at = after;
            continue;
        }
        let end = match_delim(text, brace, b'{', b'}')
            .ok_or_else(|| "unterminated `bridge! {` block".to_string())?;
        let first = bridge.arms.len();
        parse_body(&text[brace + 1..end], line_of(text, brace), bridge)?;
        for arm in &mut bridge.arms[first..] {
            arm.source = Some(source.to_string());
        }
        at = end + 1;
    }
    Ok(())
}

/// Walk items inside one `bridge!` body. Every item starts with a `#[day_bridge::…]` marker.
fn parse_body(body: &str, base_line: usize, bridge: &mut Bridge) -> Result<(), String> {
    let mut at = 0;
    while let Some(found) = body[at..].find("#[day_bridge::") {
        let start = at + found;
        let open = start + "#[".len() - 1; // the '[' of the attribute
        let close = match_delim(body, open, b'[', b']')
            .ok_or_else(|| "unterminated bridge attribute".to_string())?;
        let attr = &body[start + 2..close];
        // `line_of` is 1-based within the body, and the body starts on the same line as the
        // opening brace — so the two overlap by one line.
        let line = base_line + line_of(body, start) - 1;
        let rest = &body[close + 1..];

        let kind = attr
            .trim_start_matches("day_bridge::")
            .split(['(', ' '])
            .next()
            .unwrap_or("")
            .trim();
        let consumed = match kind {
            "declare" => parse_declare(rest, line, bridge)?,
            "prelude" => {
                return Err(format!(
                    "line {line}: a standalone `prelude` attribute no longer exists — write it as \
                     `lang!(prelude = r#\"\"#, body = r#\"\"#)` on the arm it belongs to \
                     (docs/bridge.md \"The file\")"
                ));
            }
            "impl" => parse_impl(attr, rest, line, bridge)?,
            "data" => 0, // the struct is ordinary Rust; day-cli reads it from the manifest's decls
            other => return Err(format!("line {line}: unknown bridge attribute `{other}`")),
        };
        at = close + 1 + consumed;
    }
    Ok(())
}

/// `extern "day" { fn a(…) -> …; fn b(); }` → one [`Decl`] each.
fn parse_declare(rest: &str, line: usize, bridge: &mut Bridge) -> Result<usize, String> {
    let open = rest
        .find('{')
        .ok_or_else(|| format!("line {line}: `declare` needs an `extern \"day\" {{}}` block"))?;
    let close = match_delim(rest, open, b'{', b'}')
        .ok_or_else(|| format!("line {line}: unterminated `extern \"day\"` block"))?;
    // Comments come out BEFORE the split: a `;` inside a doc comment would otherwise end the
    // declaration early and leave prose where the next `fn` should be.
    let block = strip_comments(&rest[open + 1..close]);
    for raw in block.split(';') {
        let sig = raw.trim();
        if sig.is_empty() {
            continue;
        }
        let sig = sig
            .strip_prefix("fn ")
            .ok_or_else(|| format!("line {line}: `{sig}` is not a `fn` declaration"))?;
        let name_end = sig
            .find('(')
            .ok_or_else(|| format!("line {line}: `{sig}` has no argument list"))?;
        let name = sig[..name_end].trim().to_string();
        let args_end = match_delim(sig, name_end, b'(', b')')
            .ok_or_else(|| format!("line {line}: `{name}` has an unterminated argument list"))?;
        let mut args = Vec::new();
        for arg in split_top(&sig[name_end + 1..args_end], ',') {
            let arg = arg.trim();
            if arg.is_empty() {
                continue;
            }
            let (n, t) = arg
                .split_once(':')
                .ok_or_else(|| format!("line {line}: argument `{arg}` needs a type"))?;
            args.push((n.trim().to_string(), t.trim().to_string()));
        }
        let ret = sig[args_end + 1..]
            .trim()
            .strip_prefix("->")
            .map(|r| r.trim().to_string())
            .unwrap_or_default();
        bridge.decls.push(Decl {
            name,
            args,
            ret,
            line,
        });
    }
    Ok(close + 1)
}

fn parse_impl(attr: &str, rest: &str, line: usize, bridge: &mut Bridge) -> Result<usize, String> {
    let lang = attr_lang(attr, line)?;
    let inner = attr
        .split_once('(')
        .map(|(_, v)| v.trim_end().trim_end_matches(')'))
        .unwrap_or("");
    let mut platforms = Vec::new();
    let mut options = BTreeMap::new();
    for part in split_top(inner, ',') {
        let part = part.trim();
        if part.is_empty() || Lang::parse(part).is_some() {
            continue;
        }
        let Some((key, value)) = part.split_once('=') else {
            return Err(format!("line {line}: `{part}` is not `key = value`"));
        };
        let key = key.trim();
        let value = value.trim().trim_matches('"');
        if key == "platforms" {
            for p in value.trim_matches(['[', ']']).split(',') {
                let p = p.trim();
                if p.is_empty() {
                    continue;
                }
                if !PLATFORMS.contains(&p) {
                    return Err(format!(
                        "line {line}: unknown platform `{p}` (expected one of {})",
                        PLATFORMS.join(", ")
                    ));
                }
                platforms.push(p.to_string());
            }
        } else {
            // A misspelled key used to be accepted and then ignored, which is the worst outcome:
            // `linkk = ["sapi"]` links nothing and surfaces as an undefined symbol somewhere else
            // entirely. The known set is small and closed, so an unknown key is an error.
            if !ARM_OPTIONS.contains(&key) {
                return Err(format!(
                    "line {line}: unknown arm option `{key}` (expected one of {})",
                    ARM_OPTIONS.join(", ")
                ));
            }
            if key == "encoding" && value != "utf8" && value != "utf16" {
                return Err(format!(
                    "line {line}: `encoding = \"{value}\"` — expected \"utf8\" or \"utf16\""
                ));
            }
            if key == "support" && value != "native" && value != "emulated" {
                return Err(format!(
                    "line {line}: `support = \"{value}\"` — expected \"native\" or \"emulated\""
                ));
            }
            options.insert(key.to_string(), value.to_string());
        }
    }
    if platforms.is_empty() {
        return Err(format!("line {line}: an arm must name `platforms = [ … ]`"));
    }

    // A rust arm is ordinary Rust captured verbatim; every other language rides one or two named
    // raw strings, or names a file with `src = "…"`.
    let (prelude, body, consumed, body_line) = if lang == Lang::Rust {
        let (body, consumed) = rust_item_after(rest, line)?;
        (None, Some(body), consumed, line)
    } else if options.contains_key("src") {
        (None, None, 0, line)
    } else {
        let call = macro_call_after(rest, line)?;
        (
            call.prelude,
            Some(call.body),
            call.consumed,
            line + call.body_skipped + 1,
        )
    };
    if let Some(text) = &prelude {
        for bad in ["package ", "namespace ", "module "] {
            if text.lines().any(|l| l.trim_start().starts_with(bad)) {
                return Err(format!(
                    "line {line}: a `{}` line belongs to the generator, not a prelude — daybridge \
                     derives it from the crate name (docs/bridge.md \"Names\")",
                    bad.trim()
                ));
            }
        }
    }

    bridge.arms.push(Arm {
        lang,
        platforms,
        body,
        prelude,
        src: options.get("src").cloned(),
        options,
        source: None,
        line,
        body_line,
    });
    Ok(consumed)
}

fn attr_lang(attr: &str, line: usize) -> Result<Lang, String> {
    let inner = attr.split_once('(').map(|(_, v)| v).unwrap_or("");
    let first = inner.split([',', ')']).next().unwrap_or("").trim();
    Lang::parse(first).ok_or_else(|| format!("line {line}: unknown bridge language `{first}`"))
}

/// One `lang!( … )` invocation's raw-string arguments.
struct MacroCall {
    /// `prelude = r#"…"#`, when the arm has one.
    prelude: Option<String>,
    /// The arm itself: the sole argument, or `body = r#"…"#`.
    body: String,
    /// Bytes of `rest` the whole invocation consumed.
    consumed: usize,
    /// Newlines before the body's first character, so `#line` can be exact.
    body_skipped: usize,
}

/// Parse the `lang!( … )` that follows an `impl` attribute.
///
/// Two spellings, because most arms need no preamble and should not pay for one:
///
/// ```text
/// swift!(r#" … "#)                                  // body only
/// swift!(prelude = r#" … "#, body = r#" … "#)       // both, in either order
/// ```
///
/// Any hash count is accepted for each raw string, because one is not always enough: an arm
/// containing the two characters `"#` — `document.querySelector("#speech")` is the everyday
/// example — ends an `r#"…"#` string early and takes the rest of the file with it. Writing that
/// arm as `r##"…"##` is the fix, and it only works if the parser counts hashes as rustc does.
fn macro_call_after(rest: &str, line: usize) -> Result<MacroCall, String> {
    let open = rest.find('(').ok_or_else(|| {
        format!("line {line}: expected a language macro, e.g. `java!(r#\"\"#)`")
    })?;
    let close = match_delim(rest, open, b'(', b')')
        .ok_or_else(|| format!("line {line}: unterminated language macro"))?;

    let mut prelude: Option<String> = None;
    let mut body: Option<(String, usize)> = None;
    let mut at = open + 1;
    while let Some(rel) = find_raw_open(&rest[at..close]) {
        let r = at + rel;
        let hashes = rest[r + 1..].bytes().take_while(|b| *b == b'#').count();
        let start = r + 1 + hashes + 1; // `r` + hashes + `"`
        let terminator = format!("\"{}", "#".repeat(hashes));
        let end = rest[start..close]
            .find(&terminator)
            .map(|i| start + i)
            .ok_or_else(|| format!("line {line}: unterminated raw string"))?;
        // Whatever sits between the previous argument and this raw string names it.
        let key = rest[at..r]
            .trim()
            .trim_start_matches(',')
            .trim()
            .trim_end_matches('=')
            .trim()
            .to_string();
        let text = dedent(&rest[start..end]);
        match key.as_str() {
            "prelude" => prelude = Some(text),
            "body" | "" => body = Some((text, rest[..start].matches('\n').count())),
            other => {
                return Err(format!(
                    "line {line}: unknown argument `{other}` — a language macro takes `prelude` \
                     and `body` (docs/bridge.md \"The file\")"
                ));
            }
        }
        at = end + terminator.len();
    }

    let (body, body_skipped) = body.ok_or_else(|| {
        format!("line {line}: expected a raw-string body, e.g. `java!(r#\"\"#)`")
    })?;
    Ok(MacroCall {
        prelude,
        body,
        consumed: close + 1,
        body_skipped,
    })
}

/// Offset of the `r` opening the next raw string (`r"`, `r#"`, `r##"`, …), or `None`.
fn find_raw_open(text: &str) -> Option<usize> {
    let b = text.as_bytes();
    let mut i = 0;
    while i < b.len() {
        if b[i] == b'r' {
            let mut j = i + 1;
            while j < b.len() && b[j] == b'#' {
                j += 1;
            }
            if b.get(j) == Some(&b'"') {
                return Some(i);
            }
        }
        i += 1;
    }
    None
}

/// Take one complete Rust item (`fn … { … }`) following an attribute, verbatim.
fn rust_item_after(rest: &str, line: usize) -> Result<(String, usize), String> {
    let open = rest
        .find('{')
        .ok_or_else(|| format!("line {line}: expected a Rust `fn` body"))?;
    let close = match_delim(rest, open, b'{', b'}')
        .ok_or_else(|| format!("line {line}: unterminated Rust body"))?;
    Ok((dedent_item(rest[..=close].trim()), close + 1))
}

// ---------------------------------------------------------------------------
// Scanning helpers
// ---------------------------------------------------------------------------

/// Index of the delimiter closing the one at `from`, skipping strings, raw strings, chars and
/// comments — the whole reason this is hand-written rather than a `find`.
fn match_delim(text: &str, from: usize, open: u8, close: u8) -> Option<usize> {
    let b = text.as_bytes();
    let mut depth = 0usize;
    let mut i = from;
    while i < b.len() {
        match b[i] {
            // A raw string of any hash count, skipped whole: its contents are another language and
            // may hold unbalanced braces, quotes, and `//` (docs/bridge.md).
            b'r' if raw_open_hashes(b, i).is_some() => {
                let hashes = raw_open_hashes(b, i).unwrap_or(0);
                let terminator: Vec<u8> = std::iter::once(b'"')
                    .chain(std::iter::repeat_n(b'#', hashes))
                    .collect();
                i += 1 + hashes + 1;
                while i < b.len() && !b[i..].starts_with(&terminator) {
                    i += 1;
                }
                i += terminator.len();
                continue;
            }
            b'"' => {
                i += 1;
                while i < b.len() && b[i] != b'"' {
                    i += if b[i] == b'\\' { 2 } else { 1 };
                }
            }
            b'/' if b.get(i + 1) == Some(&b'/') => {
                while i < b.len() && b[i] != b'\n' {
                    i += 1;
                }
            }
            c if c == open => depth += 1,
            c if c == close => {
                depth = depth.checked_sub(1)?;
                if depth == 0 {
                    return Some(i);
                }
            }
            _ => {}
        }
        i += 1;
    }
    None
}

/// The hash count of the raw string opening at `i` (`r"` is 0, `r#"` is 1, …), or `None` when this
/// `r` does not open one.
fn raw_open_hashes(b: &[u8], i: usize) -> Option<usize> {
    if b.get(i) != Some(&b'r') {
        return None;
    }
    let mut j = i + 1;
    while b.get(j) == Some(&b'#') {
        j += 1;
    }
    (b.get(j) == Some(&b'"')).then_some(j - i - 1)
}

/// Split on `sep` at nesting depth zero.
fn split_top(text: &str, sep: char) -> Vec<String> {
    let mut out = Vec::new();
    let mut depth = 0i32;
    let mut cur = String::new();
    for c in text.chars() {
        match c {
            '(' | '[' | '<' | '{' => depth += 1,
            ')' | ']' | '>' | '}' => depth -= 1,
            _ => {}
        }
        if c == sep && depth == 0 {
            out.push(std::mem::take(&mut cur));
        } else {
            cur.push(c);
        }
    }
    out.push(cur);
    out
}

fn strip_comments(text: &str) -> String {
    text.lines()
        .map(|l| l.split_once("//").map(|(a, _)| a).unwrap_or(l))
        .collect::<Vec<_>>()
        .join("\n")
}

fn line_of(text: &str, at: usize) -> usize {
    text[..at].matches('\n').count() + 1
}

/// Remove the common leading indentation an inline arm picked up from the `.rs` file it lives in,
/// so the generated foreign source starts at column zero.
fn dedent(body: &str) -> String {
    let indent = body
        .lines()
        .filter(|l| !l.trim().is_empty())
        .map(|l| l.len() - l.trim_start().len())
        .min()
        .unwrap_or(0);
    body.lines()
        // `indent` is a byte count of ASCII-space/tab indentation in the common case; the boundary
        // check keeps a line indented with a multi-byte Unicode space from panicking the build.
        .map(|l| {
            if l.len() >= indent && l.is_char_boundary(indent) {
                &l[indent..]
            } else {
                l.trim_start()
            }
        })
        .collect::<Vec<_>>()
        .join("\n")
        .trim_matches('\n')
        .to_string()
}

/// Strip the indentation a captured Rust item inherited from the `bridge!` block around it: the
/// first line is already flush, so the rest is re-based on its own minimum.
fn dedent_item(item: &str) -> String {
    let mut lines = item.lines();
    let Some(first) = lines.next() else {
        return String::new();
    };
    let rest: Vec<&str> = lines.collect();
    let indent = rest
        .iter()
        .filter(|l| !l.trim().is_empty())
        .map(|l| l.len() - l.trim_start().len())
        .min()
        .unwrap_or(0);
    let mut out = String::from(first);
    for line in rest {
        out.push('\n');
        out.push_str(if line.len() >= indent && line.is_char_boundary(indent) {
            &line[indent..]
        } else {
            line.trim_start()
        });
    }
    out
}

// ---------------------------------------------------------------------------
// Validation (docs/bridge.md "What fails the build")
// ---------------------------------------------------------------------------

fn validate(bridge: &Bridge) -> Result<(), String> {
    if bridge.decls.is_empty() && bridge.arms.is_empty() {
        return Ok(());
    }

    // Types must be inside the v1 table.
    for decl in &bridge.decls {
        for (arg, ty) in &decl.args {
            check_type(ty, true)
                .map_err(|e| format!("line {}: `{}`'s `{arg}`: {e}", decl.line, decl.name))?;
        }
        if !decl.ret.is_empty() {
            let inner = decl
                .ret
                .strip_prefix("Result<")
                .and_then(|r| r.strip_suffix('>'))
                .map(|r| split_top(r, ',').first().cloned().unwrap_or_default())
                .unwrap_or_else(|| decl.ret.clone());
            let inner = inner.trim();
            if !inner.is_empty() && inner != "()" {
                check_type(inner, false)
                    .map_err(|e| format!("line {}: `{}`'s return: {e}", decl.line, decl.name))?;
            }
        }
    }

    // The v1 type table is the DESIGN surface; `implemented` is the built one. A gap between them
    // must fail here rather than emit an adapter that cannot compile — or, worse, one that
    // compiles and marshals the wrong bytes.
    for arm in &bridge.arms {
        for decl in &bridge.decls {
            for (arg, ty) in &decl.args {
                if !implemented(arm.lang, ty, true) {
                    return Err(format!(
                        "line {}: `{}`'s `{arg}: {ty}` is in the type table but the {} generator \
                         does not marshal it yet (docs/bridge.md \"Types\")",
                        arm.line,
                        decl.name,
                        arm.lang.key()
                    ));
                }
            }
            let Some(ty) = result_value(&decl.ret) else {
                continue;
            };
            if !implemented(arm.lang, &ty, false) {
                return Err(match arm.lang {
                    // The status code owns the return slot on these, and v1 has no spelling for
                    // an out-parameter.
                    Lang::C | Lang::Cpp | Lang::Swift => format!(
                        "line {}: `{}` returns a value, which the {} arm cannot express yet — \
                         return `Result<(), day_bridge::Error>` there, or split the value into \
                         its own function",
                        arm.line,
                        decl.name,
                        arm.lang.key()
                    ),
                    _ => format!(
                        "line {}: `{}` returns `{ty}`, which the {} generator does not marshal \
                         yet (docs/bridge.md \"Types\")",
                        arm.line,
                        decl.name,
                        arm.lang.key()
                    ),
                });
            }
        }
    }

    // One LANGUAGE per target, and a fallback for everything else. Several arms may share a
    // language and a platform — that is how the rust arm implements one `fn` per item, and how a
    // Kotlin arm can be split — but two languages claiming one target would leave the generator
    // with no answer for which adapter to emit.
    let mut claimed: BTreeMap<&str, (Lang, usize)> = BTreeMap::new();
    for arm in &bridge.arms {
        for p in &arm.platforms {
            match claimed.get(p.as_str()) {
                Some(&(lang, first)) if lang != arm.lang => {
                    return Err(format!(
                        "line {}: platform `{p}` is already claimed by the {} arm on line {first}",
                        arm.line,
                        lang.key()
                    ));
                }
                _ => {
                    claimed.insert(p, (arm.lang, arm.line));
                }
            }
        }
    }
    if !bridge.decls.is_empty() && !claimed.contains_key("other") {
        return Err(
            "no `other` arm: a bridged crate must compile under day-mock on any host \
             (docs/bridge.md \"Platform selection\")"
                .into(),
        );
    }

    // The rust arm's coverage is checkable right here: a missing definition would otherwise be an
    // error inside generated code, pointing at a file nobody wrote.
    let rust: Vec<&str> = bridge
        .arms
        .iter()
        .filter(|a| a.lang == Lang::Rust)
        .filter_map(|a| a.body.as_deref())
        .collect();
    if !rust.is_empty() {
        for decl in &bridge.decls {
            let wanted = format!("fn {}", decl.name);
            if !rust.iter().any(|body| body.contains(&wanted)) {
                return Err(format!(
                    "line {}: no rust arm implements `{}`",
                    decl.line, decl.name
                ));
            }
        }
    }
    Ok(())
}

/// Whether `lang`'s generator marshals `ty` today, as an argument or as the value of a
/// `Result<T, Error>` return. Narrower than [`check_type`] on purpose: that one polices the v1
/// design surface, this one polices what is actually built (docs/bridge.md "Types").
fn implemented(lang: Lang, ty: &str, argument: bool) -> bool {
    let ty = ty.trim();
    if lang == Lang::Rust {
        return true;
    }
    if argument {
        return SCALARS.contains(&ty) || ty == "&str";
    }
    match lang {
        // The JVM's error channel is the exception, so the return slot is free for a value.
        Lang::Kotlin | Lang::Java => SCALARS.contains(&ty) || ty == "String",
        Lang::Js | Lang::ArkTs => SCALARS.contains(&ty),
        // C, C++ and Swift spend the return slot on the status code.
        _ => false,
    }
}

fn check_type(ty: &str, argument: bool) -> Result<(), String> {
    let ty = ty.trim();
    if SCALARS.contains(&ty) {
        return Ok(());
    }
    if argument && (ty == "&str" || ty == "&[u8]") {
        return Ok(());
    }
    if !argument && (ty == "String" || ty == "Vec<u8>") {
        return Ok(());
    }
    if ty.starts_with("Option<") {
        return Err(format!(
            "`{ty}` does not cross a bridge — model absence in the value, or return `Result` \
             (docs/bridge.md \"Types\")"
        ));
    }
    // A `#[day_bridge::data]` struct is named by the crate; day-cli validates its fields.
    if ty.chars().next().is_some_and(|c| c.is_ascii_uppercase()) {
        return Ok(());
    }
    Err(format!(
        "`{ty}` is outside the v1 type table (docs/bridge.md \"Types\")"
    ))
}

// ---------------------------------------------------------------------------
// Emitting
// ---------------------------------------------------------------------------

/// The exported symbol for one declared function (docs/bridge.md "Names").
fn symbol(crate_name: &str, decl: &Decl) -> String {
    format!("day_bridge_{}_{}", crate_name.replace('-', "_"), decl.name)
}

/// The C spelling of a v1 type. `&str` is UTF-8 unless the arm opts into UTF-16
/// (docs/bridge.md "Types").
fn c_type(ty: &str, utf16: bool) -> &'static str {
    match ty.trim() {
        "bool" | "i32" => "int32_t",
        "i64" => "int64_t",
        "f32" => "float",
        "f64" => "double",
        "&str" if utf16 => "const char16_t*",
        "&str" => "const char*",
        _ => "const void*",
    }
}

fn rust_c_type(ty: &str, utf16: bool) -> &'static str {
    match ty.trim() {
        "bool" | "i32" => "i32",
        "i64" => "i64",
        "f32" => "f32",
        "f64" => "f64",
        "&str" if utf16 => "*const u16",
        "&str" => "*const std::ffi::c_char",
        _ => "*const std::ffi::c_void",
    }
}

/// The translation unit for one C/C++ arm: the crate's prelude for that language, a `#line`
/// pointing back at the `.rs` the arm was written in, the arm itself, and one exported adapter per
/// declared function. The arm writes plain `speak_native(…)`; the adapter is what carries the
/// prefixed symbol Rust links against, so nothing in the arm has to know the naming scheme.
fn render_c(bridge: &Bridge, arm: &Arm, crate_name: &str) -> String {
    let utf16 = arm.options.get("encoding").map(String::as_str) == Some("utf16");
    let source = arm.source.as_deref().unwrap_or("src/lib.rs");
    let mut out = String::new();
    let _ = writeln!(
        out,
        "/* @generated by day-build from {source}:{} — edit the arm, never this file. */",
        arm.line
    );
    let _ = writeln!(out, "#include <stdint.h>");
    if let Some(prelude) = &arm.prelude {
        let _ = writeln!(out, "{}", prelude);
    }
    let _ = writeln!(out, "\n#line {} {}", arm.body_line, quote(source));
    let _ = writeln!(out, "{}\n", arm.body.as_deref().unwrap_or(""));
    let _ = writeln!(out, "#line 1 {}", quote("<day-bridge adapters>"));
    // A C++ translation unit mangles these names unless they are told not to, and Rust links
    // against the unmangled spelling. C needs no such thing.
    if arm.lang == Lang::Cpp {
        let _ = writeln!(out, "extern \"C\" {{");
    }
    for decl in &bridge.decls {
        let params: Vec<String> = decl
            .args
            .iter()
            .map(|(n, t)| format!("{} {n}", c_type(t, utf16)))
            .collect();
        let names: Vec<&str> = decl.args.iter().map(|(n, _)| n.as_str()).collect();
        let params = if params.is_empty() {
            "void".to_string()
        } else {
            params.join(", ")
        };
        if decl.ret.is_empty() {
            let _ = writeln!(
                out,
                "void {}({params}) {{ {}({}); }}",
                symbol(crate_name, decl),
                decl.name,
                names.join(", ")
            );
        } else {
            let _ = writeln!(
                out,
                "int32_t {}({params}) {{ return {}({}); }}",
                symbol(crate_name, decl),
                decl.name,
                names.join(", ")
            );
        }
    }
    if arm.lang == Lang::Cpp {
        let _ = writeln!(out, "}}");
    }
    out
}

/// The Swift adapter for one arm: the crate's Swift prelude, a `#sourceLocation` back to the
/// `.rs`, the arm itself, and one `@_cdecl` export per declared function. The arm writes ordinary
/// Swift — `func speakNative(text: String) throws` — and never sees the C ABI.
fn render_swift(bridge: &Bridge, arm: &Arm, crate_name: &str) -> String {
    let source = arm.source.as_deref().unwrap_or("src/lib.rs");
    let mut out = String::new();
    let _ = writeln!(
        out,
        "// @generated by day-build from {source}:{} — edit the arm, never this file.",
        arm.line
    );
    let _ = writeln!(out, "import Foundation");
    if let Some(prelude) = &arm.prelude {
        let _ = writeln!(out, "{}", prelude);
    }
    // swiftc maps every following line back to the crate's own source, so a type error in an arm
    // names the file its author opened (docs/bridge.md "Diagnostics").
    let _ = writeln!(
        out,
        "\n#sourceLocation(file: {}, line: {})",
        quote(source),
        arm.body_line
    );
    let _ = writeln!(out, "{}", arm.body.as_deref().unwrap_or(""));
    let _ = writeln!(out, "#sourceLocation()\n");

    for decl in &bridge.decls {
        let params: Vec<String> = decl
            .args
            .iter()
            .map(|(n, t)| format!("{n}: {}", swift_abi_type(t)))
            .collect();
        let ret = if decl.ret.is_empty() { "" } else { " -> Int32" };
        let _ = writeln!(out, "@_cdecl({})", quote(&symbol(crate_name, decl)));
        let _ = writeln!(
            out,
            "public func {}({}){ret} {{",
            symbol(crate_name, decl),
            params.join(", ")
        );
        // Marshal each argument into the Swift type the arm declared.
        let mut passed: Vec<String> = Vec::new();
        for (n, t) in &decl.args {
            match t.trim() {
                "&str" => {
                    let _ = writeln!(out, "    let {n}_s = String(cString: {n})");
                    passed.push(format!("{n}: {n}_s"));
                }
                "bool" => {
                    let _ = writeln!(out, "    let {n}_b = {n} != 0");
                    passed.push(format!("{n}: {n}_b"));
                }
                _ => passed.push(format!("{n}: {n}")),
            }
        }
        let call = format!("{}({})", decl.name, passed.join(", "));
        if decl.ret.is_empty() {
            let _ = writeln!(out, "    {call}");
        } else {
            // A `throws` arm becomes a status code: 0 on success, 1 with the message logged.
            let _ = writeln!(out, "    do {{");
            let _ = writeln!(out, "        try {call}");
            let _ = writeln!(out, "        return 0");
            let _ = writeln!(out, "    }} catch {{");
            let _ = writeln!(
                out,
                "        FileHandle.standardError.write(\"day-bridge: \\(error)\\n\".data(using: .utf8)!)"
            );
            let _ = writeln!(out, "        return 1");
            let _ = writeln!(out, "    }}");
        }
        let _ = writeln!(out, "}}\n");
    }
    out
}

/// The generated ES module for a JavaScript arm: the crate's prelude, the arm itself, and a
/// `register(rt)` returning the wasm imports the day-dom shim merges into its `env` object.
///
/// wasm has no C ABI for strings, so a `&str` argument crosses as `(ptr, len)` into the module's
/// linear memory and the runtime helper `rt.str` decodes it (docs/web.md's shim owns `wasm.memory`,
/// not this module). The arm never sees any of that.
fn render_js(bridge: &Bridge, arm: &Arm, crate_name: &str) -> String {
    let source = arm.source.as_deref().unwrap_or("src/lib.rs");
    let mut out = String::new();
    let _ = writeln!(
        out,
        "// @generated by day-build from {source}:{} — edit the arm, never this file.\n\
         //# sourceURL={source}",
        arm.line
    );
    if let Some(prelude) = &arm.prelude {
        let _ = writeln!(out, "{}", prelude);
    }
    let _ = writeln!(out, "\n{}\n", arm.body.as_deref().unwrap_or(""));

    let _ = writeln!(
        out,
        "// The shim calls this once at boot and spreads the result into the wasm import object."
    );
    let _ = writeln!(out, "export function register(rt) {{");
    let _ = writeln!(out, "  return {{");
    for decl in &bridge.decls {
        let mut params: Vec<String> = Vec::new();
        let mut passed: Vec<String> = Vec::new();
        for (n, t) in &decl.args {
            if t.trim() == "&str" {
                params.push(format!("{n}_ptr"));
                params.push(format!("{n}_len"));
                passed.push(format!("rt.str({n}_ptr, {n}_len)"));
            } else {
                params.push(n.clone());
                passed.push(n.clone());
            }
        }
        let call = format!("{}({})", decl.name, passed.join(", "));
        let _ = writeln!(
            out,
            "    {}({}) {{",
            symbol(crate_name, decl),
            params.join(", ")
        );
        match (decl.ret.is_empty(), result_value(&decl.ret)) {
            (true, _) => {
                let _ = writeln!(out, "      {call};");
            }
            (false, None) => {
                // A thrown error is the failure channel, mapped to the same status code C uses.
                let _ = writeln!(out, "      try {{");
                let _ = writeln!(out, "        {call};");
                let _ = writeln!(out, "        return 0;");
                let _ = writeln!(out, "      }} catch (e) {{");
                let _ = writeln!(
                    out,
                    "        console.error('day-bridge: {}', e);",
                    decl.name
                );
                let _ = writeln!(out, "        return 1;");
                let _ = writeln!(out, "      }}");
            }
            (false, Some(_)) => {
                let _ = writeln!(out, "      return {call};");
            }
        }
        let _ = writeln!(out, "    }},");
    }
    let _ = writeln!(out, "  }};");
    let _ = writeln!(out, "}}");
    out
}

/// The generated ArkTS module for one arm. HarmonyOS compiles ArkTS only from inside the host
/// module, so this lands in the project's `daypieces` tree beside the piece modules (§15.2) and is
/// reached through the `Index.ets` the CLI writes next to it.
fn render_arkts(bridge: &Bridge, arm: &Arm, crate_name: &str) -> String {
    let source = arm.source.as_deref().unwrap_or("src/lib.rs");
    let mut out = String::new();
    let _ = writeln!(
        out,
        "// @generated by day-build from {source}:{} — edit the arm, never this file.",
        arm.line
    );
    if let Some(prelude) = &arm.prelude {
        let _ = writeln!(out, "{}", prelude);
    }
    let _ = writeln!(out, "\n{}\n", arm.body.as_deref().unwrap_or(""));
    let _ = writeln!(
        out,
        "// The host calls this once at startup; the returned record is registered with the napi\n\
         // module so the Rust side can reach each arm by name."
    );
    let _ = writeln!(
        out,
        "export function register(): Record<string, Function> {{"
    );
    let _ = writeln!(out, "  return {{");
    for decl in &bridge.decls {
        let _ = writeln!(out, "    '{}': {},", symbol(crate_name, decl), decl.name);
    }
    let _ = writeln!(out, "  }};");
    let _ = writeln!(out, "}}");
    out
}

/// The Rust half of a JavaScript arm: wasm imports, with `&str` crossing as `(ptr, len)` into the
/// module's own linear memory — no CString, no allocation, nothing to free.
fn render_js_rust(bridge: &Bridge, crate_name: &str) -> String {
    let mut out = String::new();
    // Without this the linker treats the imports as symbols it must resolve and fails with
    // "undefined symbol"; with it they are wasm imports the host supplies at instantiation, which
    // is exactly how day-dom declares the shim's own entry points (toolkits/day-dom/src/lib.rs).
    let _ = writeln!(out, "#[link(wasm_import_module = \"env\")]");
    let _ = writeln!(out, "unsafe extern \"C\" {{");
    for decl in &bridge.decls {
        let mut params: Vec<String> = Vec::new();
        for (n, t) in &decl.args {
            if t.trim() == "&str" {
                params.push(format!("{n}_ptr: *const u8"));
                params.push(format!("{n}_len: usize"));
            } else {
                params.push(format!("{n}: {}", rust_c_type(t, false)));
            }
        }
        let ret = match (decl.ret.is_empty(), result_value(&decl.ret)) {
            (true, _) => String::new(),
            (false, None) => " -> i32".to_string(),
            (false, Some(ty)) => format!(" -> {ty}"),
        };
        let _ = writeln!(
            out,
            "    fn {}({}){ret};",
            symbol(crate_name, decl),
            params.join(", ")
        );
    }
    let _ = writeln!(out, "}}\n");

    for decl in &bridge.decls {
        let args: Vec<String> = decl.args.iter().map(|(n, t)| format!("{n}: {t}")).collect();
        let ret = if decl.ret.is_empty() {
            String::new()
        } else {
            format!(" -> {}", decl.ret)
        };
        let _ = writeln!(out, "fn {}({}){ret} {{", decl.name, args.join(", "));
        let mut passed: Vec<String> = Vec::new();
        for (n, t) in &decl.args {
            if t.trim() == "&str" {
                passed.push(format!("{n}.as_ptr()"));
                passed.push(format!("{n}.len()"));
            } else if t.trim() == "bool" {
                passed.push(format!("{n} as i32"));
            } else {
                passed.push(n.clone());
            }
        }
        let call = format!(
            "unsafe {{ {}({}) }}",
            symbol(crate_name, decl),
            passed.join(", ")
        );
        match (decl.ret.is_empty(), result_value(&decl.ret)) {
            (true, _) => {
                let _ = writeln!(out, "    {call};");
            }
            (false, None) => {
                let _ = writeln!(out, "    if {call} == 0 {{");
                let _ = writeln!(out, "        Ok(())");
                let _ = writeln!(out, "    }} else {{");
                let _ = writeln!(
                    out,
                    "        Err(day_bridge::Error::Foreign(\"{}\".into()))",
                    decl.name
                );
                let _ = writeln!(out, "    }}");
            }
            (false, Some(_)) => {
                let _ = writeln!(out, "    Ok({call})");
            }
        }
        let _ = writeln!(out, "}}\n");
    }
    out
}

/// The generated Kotlin object for one arm: the crate's Kotlin prelude, the arm itself, and a
/// `@JvmStatic` entry per declared function for JNI to call. The arm writes ordinary Kotlin —
/// `fun speak_native(text: String)` — and never sees JNI.
///
/// The name is the DECLARED one, unchanged: a bridged function is called `speak_native` in Rust,
/// Kotlin, Swift, ArkTS, JavaScript and C alike, so one grep finds the declaration and every arm.
/// It costs the JVM and Swift naming conventions; it buys never having to map a name in your head
/// or in a stack trace (docs/bridge.md "Names").
///
/// Kotlin has no `#line` equivalent, so the header names the source and the arm's line, and long
/// arms belong in their own `.kt` (docs/bridge.md "Diagnostics").
fn render_kotlin(bridge: &Bridge, arm: &Arm, crate_name: &str) -> String {
    let pkg = kotlin_package(crate_name);
    let object = kotlin_object(crate_name);
    let source = arm.source.as_deref().unwrap_or("src/lib.rs");
    let mut out = String::new();
    let _ = writeln!(
        out,
        "// @generated by day-build from {source}:{} — edit the arm, never this file.\n\
         // Kotlin carries no line directive: an error below is at {source}:{} plus the offset.",
        arm.line, arm.body_line
    );
    let _ = writeln!(out, "package {pkg}\n");
    if let Some(prelude) = &arm.prelude {
        let _ = writeln!(out, "{}", prelude);
    }
    let _ = writeln!(out, "\n{}\n", arm.body.as_deref().unwrap_or(""));

    let _ = writeln!(out, "object {object} {{");
    for decl in &bridge.decls {
        let params: Vec<String> = decl
            .args
            .iter()
            .map(|(n, t)| format!("{n}: {}", kotlin_type(t)))
            .collect();
        let call = format!(
            // Fully qualified so it resolves to the arm's top-level function, never to this
            // object's member of the same name.
            "{pkg}.{}({})",
            decl.name,
            decl.args
                .iter()
                .map(|(n, _)| format!("{n} = {n}"))
                .collect::<Vec<_>>()
                .join(", ")
        );
        // No try/catch: on the JVM an exception IS the error channel, and JNI reports it to
        // the caller — so a Kotlin arm's failure becomes `Error::Foreign` on the Rust side with
        // no status code. C and Swift, having no such channel, use one.
        let value = result_value(&decl.ret);
        let ret = match value.as_deref() {
            None => String::new(),
            Some(ty) => format!(": {}", kotlin_type(ty)),
        };
        let _ = writeln!(out, "    @JvmStatic");
        let _ = writeln!(out, "    fun {}({}){ret} {{", decl.name, params.join(", "));
        if value.is_some() {
            let _ = writeln!(out, "        return {call}");
        } else {
            let _ = writeln!(out, "        {call}");
        }
        let _ = writeln!(out, "    }}");
    }
    let _ = writeln!(out, "}}");
    out
}

/// The generated Java class for one arm — the same shape the Kotlin emitter produces, for a
/// project whose Gradle build has no Kotlin plugin. Java needs none: `com.android.application`
/// compiles `.java` out of any `srcDir`, which is what makes this the arm that always works.
fn render_java(arm: &Arm, crate_name: &str) -> String {
    let pkg = kotlin_package(crate_name);
    let class = kotlin_object(crate_name);
    let source = arm.source.as_deref().unwrap_or("src/lib.rs");
    let mut out = String::new();
    let _ = writeln!(
        out,
        "// @generated by day-build from {source}:{} — edit the arm, never this file.\n\
         // Java carries no line directive: an error below is at {source}:{} plus the offset.",
        arm.line, arm.body_line
    );
    let _ = writeln!(out, "package {pkg};\n");
    if let Some(prelude) = &arm.prelude {
        let _ = writeln!(out, "{}", prelude);
    }
    let _ = writeln!(out, "\npublic final class {class} {{");
    let _ = writeln!(out, "    private {class}() {{}}\n");
    // The arm becomes the body of the class, so it writes ordinary `public static` methods and
    // never sees JNI — the same contract the Kotlin arm has.
    for line in arm.body.as_deref().unwrap_or("").lines() {
        if line.trim().is_empty() {
            let _ = writeln!(out);
        } else {
            let _ = writeln!(out, "    {line}");
        }
    }
    let _ = writeln!(out, "}}");
    out
}

/// The Rust half of a Kotlin arm: a JNI static call per function, through day-android's cached JVM
/// and its `dcall_static` helper — the same path day-part-battery's hand-written arm takes today.
fn render_jvm_rust(bridge: &Bridge, crate_name: &str) -> String {
    let class = kotlin_package(crate_name).replace('.', "/") + "/" + &kotlin_object(crate_name);
    let mut out = String::new();
    for decl in &bridge.decls {
        let args: Vec<String> = decl.args.iter().map(|(n, t)| format!("{n}: {t}")).collect();
        let ret = if decl.ret.is_empty() {
            String::new()
        } else {
            format!(" -> {}", decl.ret)
        };
        let _ = writeln!(out, "fn {}({}){ret} {{", decl.name, args.join(", "));
        let _ = writeln!(out, "    use day_android::{{DayEnv, with_env}};");
        // A headless part is ordinary Rust anyone may call, including before (or without) a Day
        // app's init — where `with_env` would panic on the missing JVM. Asking first makes that
        // an ordinary `Runtime` error.
        let _ = writeln!(out, "    if !day_android::vm_ready() {{");
        let _ = writeln!(
            out,
            "        return{};",
            if decl.ret.is_empty() {
                String::new()
            } else {
                " Err(day_bridge::Error::Runtime)".to_string()
            }
        );
        let _ = writeln!(out, "    }}");
        let _ = writeln!(out, "    let called = with_env(|env| {{");
        // Marshal arguments into JNI values; a String has to become a local ref first.
        let mut jvalues: Vec<String> = Vec::new();
        for (n, t) in &decl.args {
            match t.trim() {
                "&str" => {
                    let _ = writeln!(out, "        let {n}_j = env.new_string({n}).ok()?;");
                    jvalues.push(format!("(&{n}_j).into()"));
                }
                "bool" => jvalues.push(format!(
                    "day_android::jni::objects::JValue::Bool({n} as u8)"
                )),
                "i32" => jvalues.push(format!("day_android::jni::objects::JValue::Int({n})")),
                "i64" => jvalues.push(format!("day_android::jni::objects::JValue::Long({n})")),
                "f32" => jvalues.push(format!("day_android::jni::objects::JValue::Float({n})")),
                "f64" => jvalues.push(format!("day_android::jni::objects::JValue::Double({n})")),
                _ => jvalues.push(n.clone()),
            }
        }
        let _ = writeln!(
            out,
            "        let outcome = env.dcall_static({}, {}, {}, &[{}]);",
            quote(&class),
            quote(&decl.name),
            quote(&jni_signature(decl)),
            jvalues.join(", ")
        );
        // A throwing arm leaves the exception PENDING on this thread. `with_env`'s attach guard
        // treats a pending exception as fatal and panics, which would turn the contract's
        // "an exception becomes Error::Foreign" into a contained panic that leaves the UI's
        // reactive state suspect. Logging and clearing it here is what keeps it an ordinary error.
        let _ = writeln!(out, "        if env.exception_check() {{");
        let _ = writeln!(out, "            env.exception_describe(); // → logcat");
        let _ = writeln!(out, "            env.exception_clear();");
        let _ = writeln!(out, "        }}");
        // Three shapes, not two: a bare unit call drops failures, `Result<(), _>` reports them,
        // and `Result<T, _>` also carries a value back.
        match (decl.ret.is_empty(), result_value(&decl.ret)) {
            (true, _) => {
                let _ = writeln!(out, "        outcome.ok()?;");
                let _ = writeln!(out, "        Some(())");
                let _ = writeln!(out, "    }});");
                let _ = writeln!(out, "    let _ = called;");
            }
            (false, None) => {
                let _ = writeln!(out, "        outcome.ok()?;");
                let _ = writeln!(out, "        Some(())");
                let _ = writeln!(out, "    }});");
                let _ = writeln!(
                    out,
                    "    // A Java exception fails `dcall_static`, so a throwing"
                );
                let _ = writeln!(out, "    // arm arrives here as `None`.");
                let _ = writeln!(out, "    match called {{");
                let _ = writeln!(out, "        Some(()) => Ok(()),");
                let _ = writeln!(
                    out,
                    "        None => Err(day_bridge::Error::Foreign(\"{}\".into())),",
                    decl.name
                );
                let _ = writeln!(out, "    }}");
            }
            (false, Some(ty)) => {
                if ty == "String" {
                    // Copied out of the JVM immediately (docs/bridge.md "Ownership"); a null
                    // return is the arm saying "nothing", which the caller sees as an empty
                    // string rather than a foreign failure.
                    let _ = writeln!(out, "        let obj = outcome.ok()?.l().ok()?;");
                    let _ = writeln!(out, "        if obj.is_null() {{");
                    let _ = writeln!(out, "            return Some(String::new());");
                    let _ = writeln!(out, "        }}");
                    let _ = writeln!(out, "        env.dstr(&day_android::as_jstring(obj)).ok()");
                } else {
                    let _ = writeln!(out, "        outcome.ok()?.{}().ok()", jvalue_accessor(&ty));
                }
                let _ = writeln!(out, "    }});");
                let _ = writeln!(
                    out,
                    "    // A Java exception fails `dcall_static`, so a throwing"
                );
                let _ = writeln!(out, "    // arm arrives here as `None`.");
                let _ = writeln!(out, "    match called {{");
                let _ = writeln!(out, "        Some(v) => Ok(v),");
                let _ = writeln!(
                    out,
                    "        None => Err(day_bridge::Error::Foreign(\"{}\".into())),",
                    decl.name
                );
                let _ = writeln!(out, "    }}");
            }
        }
        let _ = writeln!(out, "}}\n");
    }
    out
}

/// The `T` in `Result<T, Error>`, or `None` for `Result<(), Error>` and a unit return.
fn result_value(ret: &str) -> Option<String> {
    let inner = ret
        .trim()
        .strip_prefix("Result<")
        .and_then(|r| r.strip_suffix('>'))?;
    let value = split_top(inner, ',').first()?.trim().to_string();
    (!value.is_empty() && value != "()").then_some(value)
}

/// The `JValueOwned` accessor for a v1 scalar.
fn jvalue_accessor(ty: &str) -> &'static str {
    match ty.trim() {
        "bool" => "z",
        "i32" => "i",
        "i64" => "j",
        "f32" => "f",
        "f64" => "d",
        _ => "i",
    }
}

/// `(Ljava/lang/String;)I` — the descriptor `dcall_static` needs for one declaration.
fn jni_signature(decl: &Decl) -> String {
    let args: String = decl
        .args
        .iter()
        .map(|(_, t)| match t.trim() {
            "bool" => "Z",
            "i32" => "I",
            "i64" => "J",
            "f32" => "F",
            "f64" => "D",
            "&str" => "Ljava/lang/String;",
            _ => "Ljava/lang/Object;",
        })
        .collect();
    let ret = match result_value(&decl.ret).as_deref() {
        None => "V",
        Some("bool") => "Z",
        Some("i32") => "I",
        Some("i64") => "J",
        Some("f32") => "F",
        Some("f64") => "D",
        Some("String") => "Ljava/lang/String;",
        Some(_) => "Ljava/lang/Object;",
    };
    format!("({args}){ret}")
}

fn kotlin_type(ty: &str) -> &'static str {
    match ty.trim() {
        "bool" => "Boolean",
        "i32" => "Int",
        "i64" => "Long",
        "f32" => "Float",
        "f64" => "Double",
        "&str" | "String" => "String",
        _ => "Any",
    }
}

/// `day-part-speech` → `dev.daybrite.day.bridge.day_part_speech` (docs/bridge.md "Names").
fn kotlin_package(crate_name: &str) -> String {
    format!("dev.daybrite.day.bridge.{}", crate_name.replace('-', "_"))
}

/// `day-part-speech` → `DayPartSpeechBridge`.
fn kotlin_object(crate_name: &str) -> String {
    let mut out = String::new();
    for part in crate_name.split('-') {
        let mut chars = part.chars();
        if let Some(first) = chars.next() {
            out.extend(first.to_uppercase());
            out.push_str(chars.as_str());
        }
    }
    format!("{out}Bridge")
}

/// The C-ABI spelling an `@_cdecl` function takes for a v1 type.
fn swift_abi_type(ty: &str) -> &'static str {
    match ty.trim() {
        "bool" | "i32" => "Int32",
        "i64" => "Int64",
        "f32" => "Float",
        "f64" => "Double",
        "&str" => "UnsafePointer<CChar>",
        _ => "UnsafeRawPointer",
    }
}

/// The Rust half of a C/C++ arm: the `extern "C"` declarations plus a safe wrapper per function,
/// converting arguments and turning a nonzero status into [`day_bridge::Error::Foreign`].
fn render_c_rust(bridge: &Bridge, arm: &Arm, crate_name: &str) -> String {
    let utf16 = arm.options.get("encoding").map(String::as_str) == Some("utf16");
    let mut out = String::new();
    let _ = writeln!(out, "unsafe extern \"C\" {{");
    for decl in &bridge.decls {
        let args: Vec<String> = decl
            .args
            .iter()
            .map(|(n, t)| format!("{n}: {}", rust_c_type(t, utf16)))
            .collect();
        let ret = if decl.ret.is_empty() { "" } else { " -> i32" };
        let _ = writeln!(
            out,
            "    fn {}({}){ret};",
            symbol(crate_name, decl),
            args.join(", ")
        );
    }
    let _ = writeln!(out, "}}\n");

    for decl in &bridge.decls {
        let args: Vec<String> = decl.args.iter().map(|(n, t)| format!("{n}: {t}")).collect();
        let ret = if decl.ret.is_empty() {
            String::new()
        } else {
            format!(" -> {}", decl.ret)
        };
        let _ = writeln!(out, "fn {}({}){ret} {{", decl.name, args.join(", "));
        let mut passed: Vec<String> = Vec::new();
        for (n, t) in &decl.args {
            match t.trim() {
                "&str" if utf16 => {
                    let _ = writeln!(
                        out,
                        "    let mut {n}_w: Vec<u16> = {n}.encode_utf16().collect();"
                    );
                    let _ = writeln!(out, "    {n}_w.push(0);");
                    passed.push(format!("{n}_w.as_ptr()"));
                }
                "&str" => {
                    let _ = writeln!(
                        out,
                        "    let Ok({n}_c) = std::ffi::CString::new({n}) else {{"
                    );
                    let _ = writeln!(
                        out,
                        "        return {};",
                        if decl.ret.is_empty() {
                            "".to_string()
                        } else {
                            "Err(day_bridge::Error::Encoding)".to_string()
                        }
                    );
                    let _ = writeln!(out, "    }};");
                    passed.push(format!("{n}_c.as_ptr()"));
                }
                "bool" => passed.push(format!("{n} as i32")),
                _ => passed.push(n.clone()),
            }
        }
        let call = format!(
            "unsafe {{ {}({}) }}",
            symbol(crate_name, decl),
            passed.join(", ")
        );
        if decl.ret.is_empty() {
            let _ = writeln!(out, "    {call};");
        } else {
            let _ = writeln!(out, "    if {call} == 0 {{");
            let _ = writeln!(out, "        Ok(())");
            let _ = writeln!(out, "    }} else {{");
            let _ = writeln!(
                out,
                "        Err(day_bridge::Error::Foreign(\"{} failed\".into()))",
                decl.name
            );
            let _ = writeln!(out, "    }}");
        }
        let _ = writeln!(out, "}}\n");
    }
    out
}

/// Whether an arm's foreign half is built by `day build` rather than by cargo. C and C++ are
/// compiled here through `cc`; Swift, Kotlin, ArkTS and JavaScript are staged into a host project
/// the CLI drives, so a bare `cargo build` has no way to link them.
fn staged_by_cli(lang: Lang) -> bool {
    matches!(
        lang,
        Lang::Swift | Lang::Kotlin | Lang::Java | Lang::ArkTs | Lang::Js
    )
}

/// The cfg naming "this crate's staged foreign half is present in the link".
const STAGED_CFG: &str = "day_bridge_staged";

/// The `cfg` an arm compiles under. `other` is the negation of every claimed platform, which is
/// how one crate's arms partition the target space without any of them naming the others.
fn arm_cfg(arm: &Arm, bridge: &Bridge) -> String {
    if arm.platforms.iter().any(|p| p == "other") {
        let mut claimed: Vec<&str> = bridge
            .arms
            .iter()
            .flat_map(|a| a.platforms.iter())
            .filter(|p| p.as_str() != "other")
            .map(|p| cfg_for(p))
            .collect();
        claimed.sort_unstable();
        claimed.dedup();
        return format!("not(any({}))", claimed.join(", "));
    }
    let mut list: Vec<&str> = arm.platforms.iter().map(|p| cfg_for(p)).collect();
    list.sort_unstable();
    list.dedup();
    let platform = if list.len() == 1 {
        list[0].to_string()
    } else {
        format!("any({})", list.join(", "))
    };
    if staged_by_cli(arm.lang) {
        format!("all({platform}, {STAGED_CFG})")
    } else {
        platform
    }
}

/// The cfg for a staged arm's platforms when the staged half is NOT in the link — a plain
/// `cargo build`, or a `day build` for a target this arm does not claim. The crate keeps
/// compiling and reports `Unsupported`, rather than failing to link a symbol nobody produced.
fn unstaged_cfg(arm: &Arm) -> String {
    let mut list: Vec<&str> = arm.platforms.iter().map(|p| cfg_for(p)).collect();
    list.sort_unstable();
    list.dedup();
    let platform = if list.len() == 1 {
        list[0].to_string()
    } else {
        format!("any({})", list.join(", "))
    };
    format!("all({platform}, not({STAGED_CFG}))")
}

/// `#[cfg(…)]` for a predicate, or `None` when it is always true — which is what the `other` arm's
/// predicate collapses to in a crate whose only arm is the fallback.
fn cfg_attr(pred: &str) -> Option<String> {
    (pred != "not(any())").then(|| format!("#[cfg({pred})]"))
}

fn render_rust(bridge: &Bridge, crate_name: &str) -> String {
    let mut out = String::from(
        "// @generated by day-build from this crate's `day_bridge::bridge!` block.\n\
         // Edit the arms in the crate source, never this file (docs/bridge.md).\n\n",
    );
    if bridge.decls.is_empty() {
        return out;
    }

    for arm in bridge.arms.iter().filter(|a| a.lang == Lang::Rust) {
        if let Some(cfg) = cfg_attr(&arm_cfg(arm, bridge)) {
            let _ = writeln!(out, "{cfg}");
        }
        let _ = writeln!(out, "#[allow(dead_code)]");
        let _ = writeln!(out, "{}\n", arm.body.as_deref().unwrap_or(""));
    }

    // Where a staged arm's foreign half is absent, the fallback stands in — same bodies as the
    // `other` arm, under the staged arm's platforms.
    let fallback: Vec<&Arm> = bridge
        .arms
        .iter()
        .filter(|a| a.lang == Lang::Rust && a.platforms.iter().any(|p| p == "other"))
        .collect();
    for arm in bridge.arms.iter().filter(|a| staged_by_cli(a.lang)) {
        for fb in &fallback {
            let _ = writeln!(out, "#[cfg({})]", unstaged_cfg(arm));
            let _ = writeln!(out, "#[allow(dead_code)]");
            let _ = writeln!(out, "{}\n", fb.body.as_deref().unwrap_or(""));
        }
    }

    // A JavaScript arm rides wasm imports rather than the C ABI: strings cross as (ptr, len).
    for arm in bridge.arms.iter().filter(|a| a.lang == Lang::Js) {
        let block = render_js_rust(bridge, crate_name);
        let cfg = arm_cfg(arm, bridge);
        for item in block.split("\n\n").filter(|i| !i.trim().is_empty()) {
            let _ = writeln!(
                out,
                "#[cfg({cfg})]\n#[allow(dead_code)]\n{}\n",
                item.trim_end()
            );
        }
    }

    // A Kotlin arm is called the other way round — Rust into the JVM — so it gets its own
    // wrappers rather than an extern block.
    for arm in bridge
        .arms
        .iter()
        .filter(|a| matches!(a.lang, Lang::Kotlin | Lang::Java))
    {
        let block = render_jvm_rust(bridge, crate_name);
        let cfg = arm_cfg(arm, bridge);
        for item in block.split("\n\n").filter(|i| !i.trim().is_empty()) {
            let _ = writeln!(
                out,
                "#[cfg({cfg})]\n#[allow(dead_code)]\n{}\n",
                item.trim_end()
            );
        }
    }

    // A C, C++ or Swift arm reaches Rust through the C ABI — Swift's `@_cdecl` exports exactly the
    // symbol C would — so one emitter covers all three. The extern block and the safe wrappers are
    // cfg-gated exactly like the rust arm, so the call site never changes.
    for arm in bridge
        .arms
        .iter()
        .filter(|a| matches!(a.lang, Lang::C | Lang::Cpp | Lang::Swift))
    {
        let block = render_c_rust(bridge, arm, crate_name);
        match cfg_attr(&arm_cfg(arm, bridge)) {
            Some(cfg) => {
                // One cfg per item, so the block stays a set of plain items.
                for item in block.split("\n\n").filter(|i| !i.trim().is_empty()) {
                    let _ = writeln!(out, "{cfg}\n#[allow(dead_code)]\n{}\n", item.trim_end());
                }
            }
            None => {
                let _ = writeln!(out, "{block}");
            }
        }
    }

    // `<fn>_support()`: what this target promises. One definition per distinct cfg, NOT per arm —
    // several arms share a cfg whenever a language needs one item per function (the rust arm
    // always does), and two definitions under one cfg would collide.
    let mut levels: Vec<(String, &'static str)> = Vec::new();
    for arm in &bridge.arms {
        let support = if arm.lang == Lang::Rust && arm.platforms.iter().any(|p| p == "other") {
            "Unsupported"
        } else if arm.options.get("support").map(String::as_str) == Some("emulated") {
            "Emulated"
        } else {
            "Native"
        };
        let cfg = arm_cfg(arm, bridge);
        if !levels.iter().any(|(seen, _)| seen == &cfg) {
            levels.push((cfg, support));
        }
        if staged_by_cli(arm.lang) {
            let cfg = unstaged_cfg(arm);
            if !levels.iter().any(|(seen, _)| seen == &cfg) {
                levels.push((cfg, "Unsupported"));
            }
        }
    }
    for decl in &bridge.decls {
        for (cfg, support) in &levels {
            if let Some(attr) = cfg_attr(cfg) {
                let _ = writeln!(out, "{attr}");
            }
            let _ = writeln!(
                out,
                "#[allow(dead_code)]\npub(crate) fn {}_support() -> day_bridge::Support {{\n    \
                 day_bridge::Support::{support}\n}}\n",
                decl.name
            );
        }
    }
    out
}

/// The file name an arm's adapter is staged under, derived from the crate and the platforms it
/// claims so two crates' adapters can share one directory.
fn generated_name(arm: &Arm, crate_name: &str) -> String {
    // javac requires a public class to sit in a file named after it, so a Java arm takes the class
    // name and nothing else. Every other language's file name is free, and encodes the platforms so
    // two crates' adapters can share one staging directory.
    if arm.lang == Lang::Java {
        return format!("{}.java", kotlin_object(crate_name));
    }
    let ext = match arm.lang {
        Lang::Swift => "swift",
        Lang::Kotlin => "kt",
        Lang::Java => "java",
        Lang::ArkTs => "ets",
        Lang::Js => "js",
        Lang::Cpp => "cpp",
        Lang::C => "c",
        Lang::Rust => "rs",
    };
    format!("{crate_name}-{}.{ext}", arm.platforms.join("-"))
}

fn quote(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    out.push('"');
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if (c as u32) < 0x20 => {
                let _ = write!(out, "\\u{:04x}", c as u32);
            }
            c => out.push(c),
        }
    }
    out.push('"');
    out
}

/// Touch only when the bytes change (DESIGN §17.5): the native builds behind generated sources key
/// on mtime, so an unconditional write recompiles them on every `day build`.
fn write_if_changed(path: &Path, content: &str) -> Result<(), String> {
    if std::fs::read(path).is_ok_and(|cur| cur == content.as_bytes()) {
        return Ok(());
    }
    std::fs::write(path, content).map_err(|e| format!("{}: {e}", path.display()))
}

#[cfg(test)]
mod tests {
    use super::*;

    const SPEECH: &str = r###"
day_bridge::bridge! {
    #[day_bridge::declare]
    extern "day" {
        fn speak_native(text: &str) -> Result<(), day_bridge::Error>;
        fn stop_native();
    }

    #[day_bridge::impl(kotlin, platforms = [android])]
    kotlin!(
        prelude = r#"
            import android.speech.tts.TextToSpeech
        "#,
        body = r#"
            fun speak_native(text: String) { engine?.speak(text) }
        "#,
    );

    #[day_bridge::impl(rust, platforms = [other])]
    fn speak_native(_text: &str) -> Result<(), day_bridge::Error> {
        Err(day_bridge::Error::Unsupported)
    }

    #[day_bridge::impl(rust, platforms = [other])]
    fn stop_native() {}
}
"###;

    fn parse(src: &str) -> Bridge {
        let mut b = Bridge::default();
        parse_into(src, "src/lib.rs", &mut b).expect("parse");
        b
    }

    fn parse_err(src: &str) -> String {
        let mut b = Bridge::default();
        parse_into(src, "src/lib.rs", &mut b).expect_err("should not parse")
    }

    #[test]
    fn parses_declarations_and_arms() {
        let b = parse(SPEECH);
        assert_eq!(b.decls.len(), 2);
        assert_eq!(b.decls[0].name, "speak_native");
        assert_eq!(b.decls[0].args, vec![("text".into(), "&str".into())]);
        assert_eq!(b.decls[0].ret, "Result<(), day_bridge::Error>");
        assert_eq!(b.decls[1].name, "stop_native");
        assert!(b.decls[1].args.is_empty());
        assert_eq!(b.arms.len(), 3);
        assert_eq!(
            b.arms[0].prelude.as_deref(),
            Some("import android.speech.tts.TextToSpeech"),
            "the prelude belongs to the arm that declared it"
        );
        assert_eq!(b.arms[0].lang, Lang::Kotlin);
        assert_eq!(b.arms[0].platforms, vec!["android".to_string()]);
        assert!(
            b.arms[0]
                .body
                .as_deref()
                .unwrap()
                .starts_with("fun speak_native")
        );
    }

    #[test]
    fn validates_and_renders_the_rust_arm() {
        let b = parse(SPEECH);
        validate(&b).expect("valid");
        let rust = render_rust(&b, "day-part-speech");
        // The android arm is claimed, so `other` excludes it.
        assert!(
            rust.contains("#[cfg(not(any(target_os = \"android\")))]"),
            "{rust}"
        );
        assert!(rust.contains("fn speak_native(_text: &str)"));
        assert!(rust.contains("pub(crate) fn speak_native_support()"));
        assert!(
            rust.contains("Support::Native"),
            "the android arm reports Native"
        );
        assert!(
            rust.contains("Support::Unsupported"),
            "the fallback reports Unsupported"
        );
    }

    #[test]
    fn rejects_a_type_outside_the_table() {
        let b = parse(
            r###"
            day_bridge::bridge! {
                #[day_bridge::declare]
                extern "day" { fn f(x: Option<i32>); }
                #[day_bridge::impl(rust, platforms = [other])]
                fn f(_x: Option<i32>) {}
            }
            "###,
        );
        let err = validate(&b).unwrap_err();
        assert!(err.contains("does not cross a bridge"), "{err}");
    }

    #[test]
    fn rejects_a_missing_fallback() {
        let b = parse(
            r###"
            day_bridge::bridge! {
                #[day_bridge::declare]
                extern "day" { fn f(); }
                #[day_bridge::impl(kotlin, platforms = [android])]
                kotlin!(r#" fun f() {} "#);
            }
            "###,
        );
        assert!(validate(&b).unwrap_err().contains("no `other` arm"));
    }

    #[test]
    fn rejects_two_arms_claiming_one_platform() {
        let b = parse(
            r###"
            day_bridge::bridge! {
                #[day_bridge::declare]
                extern "day" { fn f(); }
                #[day_bridge::impl(kotlin, platforms = [android])]
                kotlin!(r#" fun f() {} "#);
                #[day_bridge::impl(js, platforms = [android])]
                js!(r#" export function f() {} "#);
                #[day_bridge::impl(rust, platforms = [other])]
                fn f() {}
            }
            "###,
        );
        assert!(validate(&b).unwrap_err().contains("already claimed"));
    }

    /// `"#` is ordinary in JavaScript, CSS selectors and C format strings, and it ends an `r#"…"#`
    /// body early — silently, taking the rest of the arm with it. More hashes is the author's fix,
    /// so the parser counts them the way rustc does.
    #[test]
    fn a_body_containing_a_quote_hash_needs_more_hashes() {
        let b = parse(
            r####"
            day_bridge::bridge! {
                #[day_bridge::declare]
                extern "day" { fn focus_native(); }
                #[day_bridge::impl(js, platforms = [web])]
                js!(r##"
                    export function focus_native() { document.querySelector("#speech").focus(); }
                "##);
                #[day_bridge::impl(rust, platforms = [other])]
                fn focus_native() {}
            }
            "####,
        );
        let arm = b.arms.iter().find(|a| a.lang == Lang::Js).unwrap();
        let body = arm.body.as_deref().unwrap();
        assert!(
            body.contains("querySelector(\"#speech\")") && body.ends_with("}"),
            "the whole body survives:\n{body}"
        );
        // The arm after it still parses, which is what an early terminator would have eaten.
        assert!(b.arms.iter().any(|a| a.lang == Lang::Rust), "{:?}", b.arms);
    }

    /// A misspelled option used to be ignored, which surfaced far from the mistake.
    #[test]
    fn rejects_unknown_arm_options_and_values() {
        let bad_key = parse_err(
            r###"
            day_bridge::bridge! {
                #[day_bridge::impl(c, platforms = [linux], linkk = ["speechd"])]
                c!(r#" void f(void) {} "#);
            }
            "###,
        );
        assert!(bad_key.contains("unknown arm option `linkk`"), "{bad_key}");

        let bad_encoding = parse_err(
            r###"
            day_bridge::bridge! {
                #[day_bridge::impl(cpp, platforms = [windows], encoding = "utf-16")]
                cpp!(r#" void f(void) {} "#);
            }
            "###,
        );
        assert!(
            bad_encoding.contains("expected \"utf8\" or \"utf16\""),
            "{bad_encoding}"
        );

        let bad_support = parse_err(
            r###"
            day_bridge::bridge! {
                #[day_bridge::impl(arkts, platforms = [ohos], support = "partial")]
                arkts!(r#" export function f() {} "#);
            }
            "###,
        );
        assert!(
            bad_support.contains("expected \"native\" or \"emulated\""),
            "{bad_support}"
        );
    }

    #[test]
    fn rejects_a_package_line_in_a_prelude() {
        let err = parse_err(
            r###"
            day_bridge::bridge! {
                #[day_bridge::impl(kotlin, platforms = [android])]
                kotlin!(
                    prelude = r#"
                        package dev.example.mine
                    "#,
                    body = r#"
                        fun f() {}
                    "#,
                );
            }
            "###,
        );
        assert!(err.contains("belongs to the generator"), "{err}");
    }

    /// The prelude is per ARM, so two arms of one language claiming different platforms cannot
    /// receive each other's imports — the bug the old per-language prelude had by construction.
    #[test]
    fn a_prelude_reaches_only_its_own_arm() {
        let b = parse(
            r###"
            day_bridge::bridge! {
                #[day_bridge::declare]
                extern "day" { fn f(); }

                #[day_bridge::impl(c, platforms = [linux])]
                c!(
                    prelude = r#"
                        #include <linux_only.h>
                    "#,
                    body = r#" void f(void) {} "#,
                );

                #[day_bridge::impl(c, platforms = [windows])]
                c!(
                    prelude = r#"
                        #include <windows.h>
                    "#,
                    body = r#" void f(void) {} "#,
                );

                #[day_bridge::impl(rust, platforms = [other])]
                fn f() {}
            }
            "###,
        );
        let windows = b
            .arms
            .iter()
            .find(|a| a.platforms.iter().any(|p| p == "windows"))
            .unwrap();
        let c = render_c(&b, windows, "day-part-demo");
        assert!(c.contains("#include <windows.h>"), "{c}");
        assert!(
            !c.contains("linux_only.h"),
            "no leak from the other arm:\n{c}"
        );
    }

    /// The old spelling was a separate item; the error says where it went.
    #[test]
    fn a_standalone_prelude_attribute_says_what_replaced_it() {
        let err = parse_err(
            r###"
            day_bridge::bridge! {
                #[day_bridge::prelude(swift)]
                swift!(r#" import AVFoundation "#);
            }
            "###,
        );
        assert!(err.contains("no longer exists"), "{err}");
        assert!(err.contains("prelude = r#"), "{err}");
    }

    #[test]
    fn renders_the_kotlin_adapter_and_its_jni_side() {
        let b = parse(SPEECH);
        let arm = b.arms.iter().find(|a| a.lang == Lang::Kotlin).unwrap();
        let kt = render_kotlin(&b, arm, "day-part-speech");
        assert!(
            kt.contains("package dev.daybrite.day.bridge.day_part_speech"),
            "{kt}"
        );
        assert!(
            kt.contains("import android.speech.tts.TextToSpeech"),
            "prelude hoisted:\n{kt}"
        );
        assert!(kt.contains("object DayPartSpeechBridge {"), "{kt}");
        // The entry calls the arm's top-level function by its package-qualified name, so it can
        // never recurse into the object member of the same name.
        assert!(
            kt.contains("dev.daybrite.day.bridge.day_part_speech.speak_native(text = text)"),
            "the declared name is used verbatim, not camel-cased:\n{kt}"
        );
        // No status code and no catch: an exception is the JVM's error channel, and JNI hands it
        // to the caller, which the Rust side turns into `Error::Foreign`.
        assert!(
            !kt.contains("catch ("),
            "the arm's exceptions cross as-is:\n{kt}"
        );

        let rust = render_jvm_rust(&b, "day-part-speech");
        assert!(
            rust.contains(
                "env.dcall_static(\"dev/daybrite/day/bridge/day_part_speech/DayPartSpeechBridge\", \"speak_native\", \"(Ljava/lang/String;)V\""
            ),
            "{rust}"
        );
        assert!(
            rust.contains("let text_j = env.new_string(text).ok()?;"),
            "{rust}"
        );
        assert!(
            rust.contains("Err(day_bridge::Error::Foreign(\"speak_native\".into()))"),
            "a failed call becomes Foreign:\n{rust}"
        );
    }

    #[test]
    fn renders_the_java_adapter_the_jvm_side_shares() {
        // Java and Kotlin arms produce the same class, the same method names, and the same JNI
        // descriptors — only the syntax and the file name differ (docs/bridge.md "Android").
        let b = parse(&SPEECH.replace("kotlin", "java"));
        let arm = b.arms.iter().find(|a| a.lang == Lang::Java).unwrap();
        let java = render_java(arm, "day-part-speech");
        assert!(
            java.contains("package dev.daybrite.day.bridge.day_part_speech;"),
            "{java}"
        );
        assert!(
            java.contains("import android.speech.tts.TextToSpeech"),
            "prelude hoisted:\n{java}"
        );
        assert!(
            java.contains("public final class DayPartSpeechBridge {"),
            "{java}"
        );
        assert!(
            java.contains("speak_native"),
            "the declared name is used verbatim:\n{java}"
        );
        // javac requires the file to be named after its public class; every other language's
        // adapter encodes the platforms instead.
        assert_eq!(
            adapter_name(arm, "day-part-speech"),
            "DayPartSpeechBridge.java"
        );

        // The Rust half is language-blind: one JNI call, whichever language wrote the class.
        let rust = render_jvm_rust(&b, "day-part-speech");
        assert!(
            rust.contains(
                "env.dcall_static(\"dev/daybrite/day/bridge/day_part_speech/DayPartSpeechBridge\", \"speak_native\", \"(Ljava/lang/String;)V\""
            ),
            "{rust}"
        );
    }

    /// A C++ arm's exported adapters must not be mangled — Rust links the plain symbol — and a
    /// UTF-16 arm must be handed `char16_t*` with the conversion happening on the Rust side.
    #[test]
    fn a_cpp_arm_exports_unmangled_utf16_adapters() {
        let b = parse(
            r###"
            day_bridge::bridge! {
                #[day_bridge::declare]
                extern "day" {
                    fn speak_native(text: &str) -> Result<(), day_bridge::Error>;
                    fn stop_native();
                }
                #[day_bridge::impl(cpp, platforms = [windows], encoding = "utf16", link = ["ole32", "sapi"])]
                cpp!(r#" int32_t speak_native(const char16_t* t) { return 0; } "#);
                #[day_bridge::impl(rust, platforms = [other])]
                fn speak_native(_text: &str) -> Result<(), day_bridge::Error> {
                    Err(day_bridge::Error::Unsupported)
                }
                #[day_bridge::impl(rust, platforms = [other])]
                fn stop_native() {}
            }
            "###,
        );
        validate(&b).expect("valid");
        let arm = b.arms.iter().find(|a| a.lang == Lang::Cpp).unwrap();
        let cpp = render_c(&b, arm, "day-part-speech");
        assert!(cpp.contains("extern \"C\" {"), "{cpp}");
        assert!(
            cpp.contains(
                "int32_t day_bridge_day_part_speech_speak_native(const char16_t* text) { return speak_native(text); }"
            ),
            "{cpp}"
        );

        let rust = render_c_rust(&b, arm, "day-part-speech");
        assert!(
            rust.contains("fn day_bridge_day_part_speech_speak_native(text: *const u16) -> i32;"),
            "{rust}"
        );
        assert!(
            rust.contains("let mut text_w: Vec<u16> = text.encode_utf16().collect();")
                && rust.contains("text_w.push(0);"),
            "the wide string is built and NUL-terminated in Rust:\n{rust}"
        );
    }

    /// The same generator, without the C++ rules: a C arm is already unmangled, and its `&str`
    /// stays `const char*`.
    #[test]
    fn a_c_arm_takes_no_extern_c_wrapper() {
        let b = parse(
            r###"
            day_bridge::bridge! {
                #[day_bridge::declare]
                extern "day" { fn f(text: &str); }
                #[day_bridge::impl(c, platforms = [linux])]
                c!(r#" void f(const char* t) {} "#);
                #[day_bridge::impl(rust, platforms = [other])]
                fn f(_text: &str) {}
            }
            "###,
        );
        let arm = b.arms.iter().find(|a| a.lang == Lang::C).unwrap();
        let c = render_c(&b, arm, "day-part-demo");
        assert!(!c.contains("extern \"C\""), "{c}");
        assert!(c.contains("(const char* text)"), "{c}");
    }

    #[test]
    fn jni_descriptors_match_the_declaration() {
        let unit = Decl {
            name: "stop".into(),
            args: vec![],
            ret: String::new(),
            line: 1,
        };
        assert_eq!(jni_signature(&unit), "()V");
        let mixed = Decl {
            name: "f".into(),
            args: vec![
                ("a".into(), "&str".into()),
                ("b".into(), "i64".into()),
                ("c".into(), "bool".into()),
            ],
            ret: "Result<(), day_bridge::Error>".into(),
            line: 1,
        };
        // `Result<(), Error>` returns nothing: the error rides the exception channel.
        assert_eq!(jni_signature(&mixed), "(Ljava/lang/String;JZ)V");

        // A value return carries its own descriptor.
        let valued = Decl {
            name: "level".into(),
            args: vec![],
            ret: "Result<i32, day_bridge::Error>".into(),
            line: 1,
        };
        assert_eq!(jni_signature(&valued), "()I");
        assert_eq!(result_value(&valued.ret).as_deref(), Some("i32"));
    }

    #[test]
    fn the_cli_can_parse_a_crate_without_cargo() {
        // The staging half reads sources, so a foreign adapter is renderable with no OUT_DIR and
        // no build script having run (docs/bridge.md "What the build does").
        let b = parse(SPEECH);
        let kotlin = b.arms.iter().find(|a| a.lang == Lang::Kotlin).unwrap();
        assert_eq!(
            adapter_name(kotlin, "day-part-speech"),
            "day-part-speech-android.kt"
        );
    }
}