reallyme-buffa-codegen 0.1.0

ReallyMe fork: Shared code generation logic for buffa (descriptor → Rust source)
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
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
//! Integration tests that invoke protoc to parse real `.proto` files or
//! inline proto definitions, then run the full codegen pipeline. This
//! exercises the same code paths as `buffa-build`, but inside the test
//! binary where llvm-cov can instrument the codegen.
//!
//! Requires `protoc` on PATH. Tests panic with a clear message if protoc
//! is not available.

use buffa::Message;
use buffa_codegen::generated::descriptor::FileDescriptorSet;
use buffa_codegen::{CodeGenConfig, GeneratedFile};
use std::path::Path;
use std::process::Command;

/// Directory containing the shared test proto files.
const PROTOS_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../buffa-test/protos");

// ── Helpers ─────────────────────────────────────────────────────────────

/// Strip common leading whitespace from a multi-line string.
fn dedent(s: &str) -> String {
    let lines: Vec<&str> = s.lines().collect();
    let min_indent = lines
        .iter()
        .filter(|l| !l.trim().is_empty())
        .map(|l| l.len() - l.trim_start().len())
        .min()
        .unwrap_or(0);
    lines
        .iter()
        .map(|l| {
            if l.len() >= min_indent {
                &l[min_indent..]
            } else {
                l.trim()
            }
        })
        .collect::<Vec<_>>()
        .join("\n")
}

/// Invoke protoc to compile proto files into a `FileDescriptorSet`.
fn compile_protos(files: &[&str], includes: &[&str]) -> FileDescriptorSet {
    let protoc = std::env::var("PROTOC").unwrap_or_else(|_| "protoc".to_string());

    let tmp = tempfile::NamedTempFile::new().expect("failed to create temp file");
    let descriptor_path = tmp.path().to_path_buf();

    let mut cmd = Command::new(&protoc);
    cmd.arg("--include_imports");
    cmd.arg(format!(
        "--descriptor_set_out={}",
        descriptor_path.display()
    ));
    for include in includes {
        cmd.arg(format!("--proto_path={include}"));
    }
    for file in files {
        cmd.arg(file);
    }

    let output = cmd.output().unwrap_or_else(|e| {
        panic!("protoc not found ({e}). Install protoc to run codegen integration tests.")
    });

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        panic!("protoc failed: {stderr}");
    }

    let bytes = std::fs::read(&descriptor_path).expect("failed to read descriptor set");
    FileDescriptorSet::decode_from_slice(&bytes).expect("failed to decode descriptors")
}

/// Compile an inline proto definition and run codegen, returning the
/// generated Rust source. The proto string is dedented automatically.
fn generate_proto(proto: &str, config: &CodeGenConfig) -> String {
    let proto = dedent(proto);
    let dir = tempfile::tempdir().expect("failed to create temp dir");
    let proto_path = dir.path().join("test.proto");
    std::fs::write(&proto_path, &proto).expect("failed to write proto");

    let fds = compile_protos(
        &[proto_path.to_str().unwrap()],
        &[dir.path().to_str().unwrap()],
    );

    let files = buffa_codegen::generate(&fds.file, &["test.proto".into()], config)
        .unwrap_or_else(|e| panic!("codegen failed: {e}\n\nProto:\n{proto}"));

    // 5 content files + 1 stitcher per package; concat for substring asserts.
    files
        .into_iter()
        .map(|f| f.content)
        .collect::<Vec<_>>()
        .join("\n")
}

/// Helper: run codegen on a proto file from buffa-test/protos/.
fn generate_for(proto_file: &str, config: &CodeGenConfig) -> Vec<GeneratedFile> {
    let proto_path = Path::new(PROTOS_DIR).join(proto_file);
    let fds = compile_protos(&[proto_path.to_str().unwrap()], &[PROTOS_DIR]);
    let files_to_generate = vec![proto_file.to_string()];
    buffa_codegen::generate(&fds.file, &files_to_generate, config)
        .unwrap_or_else(|e| panic!("codegen failed for {proto_file}: {e}"))
}

fn no_views() -> CodeGenConfig {
    let mut c = CodeGenConfig::default();
    c.generate_views = false;
    c
}

fn json_no_views() -> CodeGenConfig {
    let mut c = CodeGenConfig::default();
    c.generate_views = false;
    c.generate_json = true;
    c
}

fn json_with_views() -> CodeGenConfig {
    let mut c = CodeGenConfig::default();
    c.generate_json = true;
    c
}

/// Body of the first `pub struct {name}` in generated source.
/// Skips a longer identifier (`Keep` vs `KeepView`) and any generics
/// (`KeepView<'a>`).
fn struct_body<'a>(content: &'a str, name: &str) -> &'a str {
    let needle = format!("pub struct {name}");
    let mut search = 0;
    loop {
        let rel = content[search..]
            .find(&needle)
            .unwrap_or_else(|| panic!("missing `{needle}` in:\n{content}"));
        let abs = search + rel;
        let after_name = abs + needle.len();
        let rest = &content[after_name..];
        if rest
            .chars()
            .next()
            .is_some_and(|c| c.is_ascii_alphanumeric() || c == '_')
        {
            search = after_name;
            continue;
        }
        let brace = rest
            .find('{')
            .unwrap_or_else(|| panic!("no `{{` after `{needle}` in:\n{content}"));
        let body_start = after_name + brace + 1;
        let bytes = content.as_bytes();
        let mut depth = 1usize;
        for (i, &b) in bytes.iter().enumerate().skip(body_start) {
            match b {
                b'{' => depth += 1,
                b'}' => {
                    depth -= 1;
                    if depth == 0 {
                        return &content[body_start..i];
                    }
                }
                _ => {}
            }
        }
        panic!("unclosed `{needle}` in:\n{content}");
    }
}

fn struct_has_unknown_fields(content: &str, name: &str) -> bool {
    struct_body(content, name).contains("__buffa_unknown_fields")
}

// ── Tests using shared proto files from buffa-test/protos/ ──────────────

#[test]
fn codegen_basic() {
    let files = generate_for("basic.proto", &CodeGenConfig::default());
    assert!(!files.is_empty());
    assert!(files[0].content.contains("@generated"));
}

#[test]
fn codegen_basic_views_vs_no_views() {
    let total = |files: &[GeneratedFile]| files.iter().map(|f| f.content.len()).sum::<usize>();
    let with_views = generate_for("basic.proto", &CodeGenConfig::default());
    let without_views = generate_for("basic.proto", &no_views());
    assert!(
        total(&without_views) < total(&with_views),
        "disabling views should produce shorter output"
    );
}

#[test]
fn codegen_keywords() {
    let files = generate_for("keywords.proto", &no_views());
    let content = &files[0].content;
    assert!(content.contains("pub mod r#type"));
    assert!(content.contains("self_:"));
    assert!(content.contains("r#type:"));
}

#[test]
fn codegen_proto2_defaults() {
    let files = generate_for("proto2_defaults.proto", &no_views());
    let content = &files[0].content;
    assert!(content.contains("pub struct WithDefaults"));
    assert!(content.contains("pub struct Proto2Message"));
    assert!(content.contains("pub name:"));
    assert!(content.contains("pub id:"));
}

#[test]
fn codegen_json_produces_serde_derives() {
    let files = generate_for("json_types.proto", &json_no_views());
    let content = &files[0].content;
    assert!(content.contains("::serde::Serialize"));
    assert!(content.contains("::serde::Deserialize"));
}

#[test]
fn codegen_json_disabled_has_no_serde() {
    let files = generate_for("json_types.proto", &no_views());
    assert!(!files[0].content.contains("::serde::Serialize"));
}

#[test]
fn codegen_nested_deep() {
    let files = generate_for("nested_deep.proto", &no_views());
    let content = &files[0].content;
    assert!(content.contains("pub mod outer"));
    assert!(content.contains("pub mod middle"));
    assert!(content.contains("pub struct Inner"));
}

#[test]
fn codegen_wkt_auto_mapping() {
    let files = generate_for("wkt_usage.proto", &no_views());
    let content = &files[0].content;
    assert!(content.contains("::buffa_types::google::protobuf::Timestamp"));
    assert!(content.contains("::buffa_types::google::protobuf::Duration"));
}

#[test]
fn gen_wkt_types_derives_eq_and_hash_only_for_selected_owned_messages() {
    let expected = [
        "Any",
        "Api",
        "BoolValue",
        "BytesValue",
        "Duration",
        "Empty",
        "Enum",
        "EnumValue",
        "Field",
        "FieldMask",
        "Int32Value",
        "Int64Value",
        "Method",
        "Mixin",
        "Option",
        "SourceContext",
        "StringValue",
        "Timestamp",
        "Type",
        "UInt32Value",
        "UInt64Value",
    ];
    let excluded = ["DoubleValue", "FloatValue", "ListValue", "Struct", "Value"];
    let protos_dir = concat!(env!("CARGO_MANIFEST_DIR"), "/../buffa-types/protos");
    let fds = compile_protos(
        &[
            "google/protobuf/any.proto",
            "google/protobuf/api.proto",
            "google/protobuf/duration.proto",
            "google/protobuf/empty.proto",
            "google/protobuf/field_mask.proto",
            "google/protobuf/source_context.proto",
            "google/protobuf/struct.proto",
            "google/protobuf/timestamp.proto",
            "google/protobuf/type.proto",
            "google/protobuf/wrappers.proto",
        ],
        &[protos_dir],
    );
    let dir = tempfile::tempdir().unwrap();
    let descriptor_path = dir.path().join("wkt.pb");
    let output_dir = dir.path().join("generated");
    std::fs::write(&descriptor_path, fds.encode_to_vec()).unwrap();
    let output = Command::new(env!("CARGO_BIN_EXE_gen_wkt_types"))
        .arg(&descriptor_path)
        .arg(&output_dir)
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "gen_wkt_types failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let mut actual = Vec::new();
    let mut actual_excluded = Vec::new();
    for entry in std::fs::read_dir(output_dir).unwrap() {
        let content = std::fs::read_to_string(entry.unwrap().path()).unwrap();
        for item in syn::parse_file(&content).unwrap().items {
            let syn::Item::Struct(message) = item else {
                continue;
            };
            let name = message.ident.to_string();
            let mut derives = Vec::new();
            for attr in &message.attrs {
                if attr.path().is_ident("derive") {
                    derives.extend(
                        attr.parse_args_with(
                            syn::punctuated::Punctuated::<syn::Path, syn::Token![,]>::parse_terminated,
                        )
                        .unwrap(),
                    );
                }
            }
            let has_trait = |trait_name: &str| derives.iter().any(|path| path.is_ident(trait_name));
            let selected = expected.contains(&name.as_str());
            assert_eq!(has_trait("Eq"), selected, "Eq derive for {name}");
            assert_eq!(has_trait("Hash"), selected, "Hash derive for {name}");
            if !name.ends_with("View") {
                assert!(has_trait("PartialEq"), "PartialEq derive for {name}");
            }
            if selected {
                actual.push(name);
            } else if excluded.contains(&name.as_str()) {
                actual_excluded.push(name);
            }
        }
    }
    actual.sort();
    assert_eq!(actual, expected);
    actual_excluded.sort();
    assert_eq!(actual_excluded, excluded);
}

#[test]
fn codegen_wkt_api_auto_mapping() {
    // #382: googleapis WKTs must resolve through buffa-types, including views.
    let files = generate_for("wkt_api.proto", &CodeGenConfig::default());
    let combined = files
        .iter()
        .map(|f| f.content.as_str())
        .collect::<Vec<_>>()
        .join("\n");
    assert!(combined.contains("::buffa_types::google::protobuf::Api"));
    assert!(combined.contains("::buffa_types::google::protobuf::Type"));
    assert!(combined.contains("::buffa_types::google::protobuf::SourceContext"));
    assert!(combined.contains("::buffa_types::google::protobuf::Enum"));
    assert!(combined.contains("::buffa_types::google::protobuf::__buffa::view::ApiView"));
    assert!(combined.contains("::buffa_types::google::protobuf::__buffa::view::TypeView"));
    assert!(combined.contains("::buffa_types::google::protobuf::__buffa::view::EnumView"));
}

#[test]
fn codegen_wkt_explicit_extern_overrides_auto() {
    let mut config = no_views();
    config
        .extern_paths
        .push((".google.protobuf".into(), "::my_custom_wkts".into()));
    let files = generate_for("wkt_usage.proto", &config);
    let content = &files[0].content;
    assert!(content.contains("::my_custom_wkts::Timestamp"));
    assert!(!content.contains("::buffa_types::"));
}

#[test]
fn codegen_name_collisions() {
    let files = generate_for("name_collisions.proto", &no_views());
    let content = &files[0].content;
    assert!(content.contains("pub struct Vec"));
    assert!(content.contains("pub struct String"));
    assert!(content.contains("pub struct Option"));
    assert!(content.contains("::core::option::Option"));
}

#[test]
fn codegen_renames_keyword_members_that_collide_after_escaping() {
    let proto = r#"
        syntax = "proto2";
        package test;

        message FieldCollision {
            optional int32 self = 1;
            optional int32 self_ = 2;
            optional int32 crate = 3;
            optional int32 crate_ = 4;
        }

        message OneofCollision {
            optional int32 self_ = 1;
            oneof self {
                string choice = 2;
            }
        }
    "#;

    for idiomatic_field_names in [false, true] {
        let mut config = CodeGenConfig::default();
        config.idiomatic_field_names = idiomatic_field_names;
        let content = generate_proto(proto, &config);
        let field_body = struct_body(&content, "FieldCollision");
        assert!(field_body.contains("pub self__:"), "{field_body}");
        assert!(field_body.contains("pub self_:"), "{field_body}");
        assert!(field_body.contains("pub crate__:"), "{field_body}");
        assert!(field_body.contains("pub crate_:"), "{field_body}");

        let oneof_body = struct_body(&content, "OneofCollision");
        assert!(oneof_body.contains("pub self_:"), "{oneof_body}");
        assert!(oneof_body.contains("pub self__:"), "{oneof_body}");
    }
}

#[test]
fn codegen_cross_package_uses_super() {
    let basic_path = Path::new(PROTOS_DIR).join("basic.proto");
    let nested_path = Path::new(PROTOS_DIR).join("nested_deep.proto");
    let cross_path = Path::new(PROTOS_DIR).join("cross_package.proto");
    let fds = compile_protos(
        &[
            basic_path.to_str().unwrap(),
            nested_path.to_str().unwrap(),
            cross_path.to_str().unwrap(),
        ],
        &[PROTOS_DIR],
    );
    let files = buffa_codegen::generate(&fds.file, &["cross_package.proto".into()], &no_views())
        .expect("codegen failed");
    assert!(files[0].content.contains("super::"));
}

// ── Module tree generation ──────────────────────────────────────────────

#[test]
fn module_tree_basic() {
    let entries = vec![
        ("foo.rs", "my.pkg"),
        ("bar.rs", "my.pkg"),
        ("baz.rs", "other"),
    ];
    let tree = buffa_codegen::generate_module_tree(
        &entries,
        buffa_codegen::IncludeMode::Relative(""),
        false,
    );
    assert!(tree.contains("pub mod my"));
    assert!(tree.contains("pub mod pkg"));
    assert!(tree.contains("pub mod other"));
    assert!(tree.contains(r#"include!("foo.rs")"#));
}

#[test]
fn module_tree_inner_allow() {
    let entries = vec![("f.rs", "pkg")];
    let with = buffa_codegen::generate_module_tree(
        &entries,
        buffa_codegen::IncludeMode::Relative(""),
        true,
    );
    let without = buffa_codegen::generate_module_tree(
        &entries,
        buffa_codegen::IncludeMode::Relative(""),
        false,
    );
    assert!(with.contains("#![allow("));
    assert!(!without.contains("#![allow("));
}

#[test]
fn module_tree_keyword_escaping() {
    let entries = vec![("t.rs", "google.type")];
    let tree = buffa_codegen::generate_module_tree(
        &entries,
        buffa_codegen::IncludeMode::Relative(""),
        false,
    );
    assert!(tree.contains("pub mod r#type"));
}

// ── Inline proto tests ──────────────────────────────────────────────────
// These replace the hand-constructed DescriptorProto tests in lib.rs,
// using inline proto definitions for clarity.

#[test]
fn inline_scalar_fields() {
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message Scalars {
          int32 id = 1;
          string name = 2;
          bytes data = 3;
          bool active = 4;
          double score = 5;
          float ratio = 6;
          uint32 count = 7;
          uint64 big = 8;
          sint32 delta = 9;
          sint64 offset = 10;
          fixed32 hash = 11;
          fixed64 fingerprint = 12;
          sfixed32 temp = 13;
          sfixed64 precise = 14;
        }
        "#,
        &no_views(),
    );
    assert!(content.contains("pub id: i32"));
    assert!(content.contains("pub name: ::buffa::alloc::string::String"));
    assert!(content.contains("pub data: ::buffa::alloc::vec::Vec<u8>"));
    assert!(content.contains("pub active: bool"));
    assert!(content.contains("pub score: f64"));
    assert!(content.contains("pub ratio: f32"));
}

#[test]
fn inline_nested_message() {
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message Outer {
          message Inner { int32 value = 1; }
          Inner child = 1;
        }
        "#,
        &no_views(),
    );
    assert!(content.contains("pub struct Outer"));
    assert!(content.contains("pub mod outer"));
    assert!(content.contains("pub struct Inner"));
    assert!(content.contains("::buffa::MessageField<outer::Inner, ::buffa::Inline<outer::Inner>>"));
}

#[test]
fn inline_enum_field() {
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        enum Status { UNKNOWN = 0; ACTIVE = 1; INACTIVE = 2; }
        message Item { Status status = 1; }
        "#,
        &no_views(),
    );
    assert!(content.contains("pub enum Status"));
    assert!(content.contains("pub status: ::buffa::EnumValue<Status>"));
}

#[test]
fn inline_map_field() {
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message Address { string street = 1; }
        message Book {
          map<string, int32> stock = 1;
          map<string, Address> locations = 2;
        }
        "#,
        &no_views(),
    );
    assert!(content.contains("pub stock: ::buffa::__private::HashMap<"));
    assert!(content.contains("pub locations: ::buffa::__private::HashMap<"));
}

#[test]
fn inline_oneof() {
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message Contact {
          oneof info {
            string email = 1;
            string phone = 2;
          }
        }
        "#,
        &no_views(),
    );
    assert!(content.contains("pub info: ::core::option::Option<__buffa::oneof::contact::Info>"));
    assert!(content.contains("pub enum Info"));
    assert!(content.contains("Email("));
    assert!(content.contains("Phone("));
}

#[test]
fn inline_proto3_optional() {
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message Item {
          optional int32 count = 1;
          optional string label = 2;
        }
        "#,
        &no_views(),
    );
    assert!(content.contains("pub count: ::core::option::Option<i32>"));
    assert!(content.contains("pub label: ::core::option::Option<::buffa::alloc::string::String>"));
}

#[test]
fn inline_repeated_fields() {
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message Address { string street = 1; }
        message Item {
          repeated string tags = 1;
          repeated int32 numbers = 2;
          repeated Address addresses = 3;
        }
        "#,
        &no_views(),
    );
    assert!(content.contains("pub tags: ::buffa::alloc::vec::Vec<::buffa::alloc::string::String>"));
    assert!(content.contains("pub numbers: ::buffa::alloc::vec::Vec<i32>"));
    assert!(content.contains("pub addresses: ::buffa::alloc::vec::Vec<Address>"));
}

#[test]
fn inline_type_url() {
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package my.pkg;
        message Foo {
          message Bar { int32 x = 1; }
          Bar bar = 1;
        }
        "#,
        &no_views(),
    );
    assert!(
        content.contains(r#"TYPE_URL: &'static str = "type.googleapis.com/my.pkg.Foo""#),
        "top-level TYPE_URL should use package: {content}"
    );
    assert!(
        content.contains(r#"TYPE_URL: &'static str = "type.googleapis.com/my.pkg.Foo.Bar""#),
        "nested TYPE_URL should include parent: {content}"
    );
}

#[test]
fn inline_enum_alias() {
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        enum Priority {
          option allow_alias = true;
          LOW = 0;
          DEFAULT = 0;
          HIGH = 1;
        }
        "#,
        &no_views(),
    );
    // First value is the enum variant, alias becomes a const.
    assert!(content.contains("LOW = 0i32"));
    assert!(content.contains("pub const DEFAULT: Self = Self::LOW"));
}

#[test]
fn inline_json_message() {
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message Item {
          int64 id = 1;
          string name = 2;
          bytes data = 3;
        }
        "#,
        &json_no_views(),
    );
    assert!(content.contains("::serde::Serialize"));
    assert!(content.contains("::serde::Deserialize"));
    // int64 should use json helper for string encoding.
    assert!(content.contains("json_helpers::int64"));
    // bytes should use base64 json helper.
    assert!(content.contains("json_helpers::bytes"));
}

#[test]
fn inline_json_oneof() {
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message Msg {
          oneof value {
            string text = 1;
            int32 number = 2;
          }
        }
        "#,
        &json_no_views(),
    );
    // Oneof field should be flattened in serde.
    assert!(content.contains("serde(flatten)"));
}

#[test]
fn inline_oneof_duplicate_message_type_no_from_collision() {
    // Regression: google.api.expr.v1alpha1.Type.type_kind has TWO Empty
    // variants and TWO PrimitiveType variants. Generating From<T> for both
    // causes E0119 (conflicting impls). Types appearing multiple times must
    // not get From impls.
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message Placeholder {}
        message T {
          oneof kind {
            Placeholder dyn = 1;
            Placeholder error = 2;
            string name = 3;
            T nested = 4;
          }
        }
        "#,
        &no_views(),
    );
    // Box on both message variants. Oneof body now sits at depth 3
    // (`__buffa::oneof::t::`), so 3× super.
    assert_eq!(
        content
            .matches("::buffa::alloc::boxed::Box<super::super::super::Placeholder>")
            .count(),
        2,
        "both Placeholder variants should be boxed: {content}"
    );
    // Only ONE From impl (for T, which appears once), not two for Placeholder.
    assert_eq!(
        content
            .matches("impl ::core::convert::From<super::super::super::Placeholder> for Kind")
            .count(),
        0,
        "duplicate-type From impls must be skipped: {content}"
    );
    assert_eq!(
        content
            .matches("impl ::core::convert::From<super::super::super::T> for Kind")
            .count(),
        1,
        "unique-type From impl must still be generated: {content}"
    );
}

#[test]
fn inline_oneof_unbox_opt_out_drops_box() {
    // unbox_oneof opts a non-recursive message variant out of Box wrapping.
    // The opted-out variant stores its message inline; sibling message
    // variants left alone stay boxed.
    let mut config = no_views();
    config
        .unboxed_oneof_fields
        .push(".test.Envelope.body.small".to_string());
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message Small { int32 value = 1; }
        message Large { string label = 1; }
        message Envelope {
          oneof body {
            Small small = 1;
            Large large = 2;
          }
        }
        "#,
        &config,
    );
    // `small` is stored inline, `large` stays boxed.
    assert!(
        content.contains("Small(super::super::super::Small)"),
        "opted-out variant should be stored inline: {content}"
    );
    assert!(
        content.contains("Large(::buffa::alloc::boxed::Box<super::super::super::Large>)"),
        "unmatched variant should stay boxed: {content}"
    );
    // The From impl for the inline variant moves the value in without a Box.
    assert!(
        content.contains("Self::Small(v)"),
        "From impl for the inline variant must not wrap in Box: {content}"
    );
    // An enum with an inline message variant allows large_enum_variant: the
    // user chose inline storage and cannot edit generated code to silence it.
    assert!(
        content.contains("#[allow(clippy::large_enum_variant)]"),
        "enum with an inline variant should allow large_enum_variant: {content}"
    );
}

#[test]
fn inline_oneof_no_unbox_rules_no_large_enum_allow() {
    // Default codegen (no unbox rules) must not grow the new allow attribute —
    // output stays byte-identical for existing users.
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message Small { int32 value = 1; }
        message Envelope {
          oneof body {
            Small small = 1;
          }
        }
        "#,
        &no_views(),
    );
    assert!(
        !content.contains("large_enum_variant"),
        "default output must not carry the allow: {content}"
    );
}

#[test]
fn inline_oneof_unbox_recursive_variant_is_rejected() {
    // Opting a recursive variant out of boxing would make the enum unsized,
    // so codegen must reject it rather than emit code that fails to compile.
    let proto = dedent(
        r#"
        syntax = "proto3";
        package test;
        message Node {
          oneof kind {
            Node child = 1;
            int32 leaf = 2;
          }
        }
        "#,
    );
    let dir = tempfile::tempdir().expect("temp dir");
    let proto_path = dir.path().join("test.proto");
    std::fs::write(&proto_path, &proto).expect("write proto");
    let fds = compile_protos(
        &[proto_path.to_str().unwrap()],
        &[dir.path().to_str().unwrap()],
    );

    let mut config = no_views();
    config
        .unboxed_oneof_fields
        .push(".test.Node.kind.child".to_string());
    let result = buffa_codegen::generate(&fds.file, &["test.proto".into()], &config);
    let err = result.expect_err("unboxing a recursive variant should error");
    assert!(
        err.to_string().contains("recursive"),
        "error should explain the recursion: {err}"
    );
}

#[test]
fn inline_proto2_required_no_json_skip() {
    // Regression: proto2 required fields got skip_serializing_if, so a
    // required int32 with value 0 was omitted from JSON. The binary encoder
    // correctly always encodes required fields (is_proto2_required check);
    // JSON must do the same.
    let content = generate_proto(
        r#"
        syntax = "proto2";
        package test;
        message Item {
          required int32 id = 1;
          required string name = 2;
          optional int32 count = 3;
        }
        "#,
        &json_no_views(),
    );
    // Required fields must NOT have skip_serializing_if.
    // The id field is required int32 — it must always be emitted even at 0.
    // Check: id's serde attr should have rename but NOT skip_serializing_if.
    // The optional `count` DOES get skip_serializing_if (Option::is_none).
    // Count skip_serializing_if occurrences: should be 1 (just `count`),
    // not 3 (id + name + count).
    let skip_count = content.matches("skip_serializing_if").count();
    assert_eq!(
        skip_count, 1,
        "only the optional field should have skip_serializing_if, got {skip_count}: {content}"
    );
}

#[test]
fn inline_proto2_custom_deserialize_honours_struct_default() {
    // Regression: custom Deserialize (triggered by oneof) used
    // var.unwrap_or_default() which calls i32::default() = 0, ignoring the
    // struct's custom Default impl that sets bar: 42 per [default = 42].
    // The derive path (#[serde(default)]) correctly uses the struct Default.
    let content = generate_proto(
        r#"
        syntax = "proto2";
        package test;
        message Item {
          required int32 bar = 1 [default = 42];
          oneof choice {
            string a = 2;
            int32 b = 3;
          }
        }
        "#,
        &json_no_views(),
    );
    // Must have a custom Default impl (required field with default_value).
    assert!(
        content.contains("bar: 42i32"),
        "custom Default must set bar: 42: {content}"
    );
    // Custom Deserialize must start from Default::default() and overwrite,
    // not build a struct literal with unwrap_or_default().
    assert!(
        content.contains("::core::default::Default>::default()") && content.contains("__r.bar"),
        "custom Deserialize must init from struct Default: {content}"
    );
    // Must NOT use unwrap_or_default() which would give i32 default (0).
    assert!(
        !content.contains(".unwrap_or_default()"),
        "must not use unwrap_or_default (uses type default, not struct): {content}"
    );
}

#[test]
fn inline_proto2_optional() {
    let content = generate_proto(
        r#"
        syntax = "proto2";
        package test;
        message Item {
          optional int32 count = 1;
          required string name = 2;
          optional string label = 3 [default = "untitled"];
        }
        "#,
        &no_views(),
    );
    // Proto2 optional → ::core::option::Option<T>
    assert!(content.contains("pub count: ::core::option::Option<i32>"));
    // Proto2 required → bare type (always encoded)
    assert!(content.contains("pub name: ::buffa::alloc::string::String"));
}

#[test]
fn inline_proto2_closed_enum() {
    let content = generate_proto(
        r#"
        syntax = "proto2";
        package test;
        enum Status { UNKNOWN = 0; ACTIVE = 1; }
        message Item { optional Status status = 1; }
        "#,
        &no_views(),
    );
    // Proto2 closed enum → bare type (not EnumValue<T>)
    assert!(
        content.contains("pub status: ::core::option::Option<Status>"),
        "proto2 closed enum should be ::core::option::Option<Status>, not EnumValue: {content}"
    );
}

#[test]
fn inline_cross_package_super() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(
        dir.path().join("dep.proto"),
        "syntax = \"proto3\";\npackage dep;\nmessage Shared { int32 x = 1; }\n",
    )
    .unwrap();
    std::fs::write(
        dir.path().join("main.proto"),
        "syntax = \"proto3\";\npackage main;\nimport \"dep.proto\";\nmessage Msg { dep.Shared s = 1; }\n",
    )
    .unwrap();

    let dep_path = dir.path().join("dep.proto");
    let main_path = dir.path().join("main.proto");
    let fds = compile_protos(
        &[dep_path.to_str().unwrap(), main_path.to_str().unwrap()],
        &[dir.path().to_str().unwrap()],
    );
    let files = buffa_codegen::generate(&fds.file, &["main.proto".into()], &no_views())
        .expect("codegen failed");
    let content = &files[0].content;
    // Cross-package ref should use super:: to reach sibling package.
    assert!(
        content.contains("super::dep::Shared"),
        "cross-package ref should use super::dep::Shared: {content}"
    );
}

#[test]
fn inline_view_keyword_package_path() {
    // Regression: view.rs to_owned used syn::parse_str which chokes on
    // keyword path segments like `super::r#type::LatLng` (google.type pkg).
    // rust_path_to_tokens handles keywords; view.rs must use it.
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(
        dir.path().join("latlng.proto"),
        "syntax = \"proto3\";\npackage google.type;\nmessage LatLng { double lat = 1; double lng = 2; }\n",
    )
    .unwrap();
    std::fs::write(
        dir.path().join("marker.proto"),
        "syntax = \"proto3\";\npackage google.maps;\nimport \"latlng.proto\";\nmessage Marker { google.type.LatLng location = 1; }\n",
    )
    .unwrap();

    let latlng_path = dir.path().join("latlng.proto");
    let marker_path = dir.path().join("marker.proto");
    let fds = compile_protos(
        &[latlng_path.to_str().unwrap(), marker_path.to_str().unwrap()],
        &[dir.path().to_str().unwrap()],
    );
    // Default config has views enabled — this exercises the to_owned path.
    let files = buffa_codegen::generate(
        &fds.file,
        &["marker.proto".into(), "latlng.proto".into()],
        &CodeGenConfig::default(),
    )
    .expect("codegen failed for keyword package with views");
    let marker = files
        .iter()
        .find(|f| f.package == "google.maps")
        .expect("google.maps.rs not generated");
    // Must emit r#type (raw ident), not plain `type`.
    assert!(
        marker.content.contains("r#type"),
        "keyword package segment must use raw ident: {}",
        marker.content
    );
}

// ── Config option tests ─────────────────────────────────────────────────

#[test]
fn inline_bytes_field_mapping() {
    let mut config = no_views();
    config
        .bytes_fields
        .push((".".into(), buffa_codegen::BytesRepr::Bytes));
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message Msg {
          bytes data = 1;
          bytes payload = 2;
        }
        "#,
        &config,
    );
    assert!(
        content.contains("::buffa::bytes::Bytes"),
        "bytes fields should use Bytes type: {content}"
    );
    assert!(
        !content.contains("Vec<u8>"),
        "bytes fields should not use Vec<u8> when bytes mapping is enabled"
    );
    // Regression: decode path must use the Bytes-producing helper (not call
    // merge_bytes which expects &mut Vec<u8>).
    assert!(
        content.contains("::buffa::types::decode_bytes_to_bytes"),
        "decode must use decode_bytes_to_bytes for Bytes field: {content}"
    );
    assert!(
        !content.contains("Bytes::from("),
        "must not wrap decode in Bytes::from (regression to alloc+copy): {content}"
    );
    assert!(
        !content.contains("merge_bytes(&mut self"),
        "must not call merge_bytes on Bytes field (no &mut): {content}"
    );
}

#[test]
fn inline_bytes_field_selective_mapping() {
    let mut config = no_views();
    config
        .bytes_fields
        .push((".test.Msg.data".into(), buffa_codegen::BytesRepr::Bytes));
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message Msg {
          bytes data = 1;
          bytes other = 2;
        }
        "#,
        &config,
    );
    // Only `data` should use Bytes; `other` should remain Vec<u8>.
    assert!(
        content.contains("::buffa::bytes::Bytes"),
        "selected field should use Bytes: {content}"
    );
    assert!(
        content.contains("Vec<u8>"),
        "non-selected field should still use Vec<u8>: {content}"
    );
}

#[test]
fn module_collision_nested_message_vs_subpackage() {
    // Issue #135: `message Oof` (with nested types) snake-cases to module `oof`,
    // colliding with sibling sub-package `foo.oof`. Both compiled together so
    // codegen sees the sub-package and deconflicts the nested module to `oof_`.
    let dir = tempfile::tempdir().expect("temp dir");
    std::fs::write(
        dir.path().join("foo.proto"),
        "syntax = \"proto3\";\npackage foo;\nmessage Oof { message Inner { int32 x = 1; } Inner inner = 1; }\n",
    )
    .unwrap();
    std::fs::write(
        dir.path().join("foo_oof.proto"),
        "syntax = \"proto3\";\npackage foo.oof;\nmessage Thing { int32 y = 1; }\n",
    )
    .unwrap();
    let fds = compile_protos(
        &[
            dir.path().join("foo.proto").to_str().unwrap(),
            dir.path().join("foo_oof.proto").to_str().unwrap(),
        ],
        &[dir.path().to_str().unwrap()],
    );
    let config = no_views();
    let content = buffa_codegen::generate(&fds.file, &["foo.proto".into()], &config)
        .expect("codegen")
        .into_iter()
        .map(|f| f.content)
        .collect::<Vec<_>>()
        .join("\n");

    // The nested-types module is deconflicted; references use the same name.
    assert!(
        content.contains("pub mod oof_"),
        "nested module should be deconflicted to `oof_`: {content}"
    );
    assert!(
        content.contains("oof_ :: Inner") || content.contains("oof_::Inner"),
        "nested-type references should use the deconflicted module: {content}"
    );
    // The struct itself (PascalCase) is untouched.
    assert!(content.contains("struct Oof"), "{content}");
}

#[test]
fn module_collision_two_messages_race_to_distinct_names() {
    // Pathological: `Oof`(oof) and `Oof_`(oof_) both collide, with sub-packages
    // `foo.oof` AND `foo.oof_`. Each deconflicted name must be distinct from the
    // other's and from both sub-packages — `oof__` and `oof___`, not both `oof__`.
    let dir = tempfile::tempdir().expect("temp dir");
    std::fs::write(
        dir.path().join("foo.proto"),
        "syntax = \"proto3\";\npackage foo;\n\
         message Oof { message Inner { int32 x = 1; } Inner inner = 1; }\n\
         message Oof_ { message Inner { int32 x = 1; } Inner inner = 1; }\n",
    )
    .unwrap();
    std::fs::write(
        dir.path().join("a.proto"),
        "syntax = \"proto3\";\npackage foo.oof;\nmessage Thing { int32 y = 1; }\n",
    )
    .unwrap();
    std::fs::write(
        dir.path().join("b.proto"),
        "syntax = \"proto3\";\npackage foo.oof_;\nmessage Widget { int32 z = 1; }\n",
    )
    .unwrap();
    let fds = compile_protos(
        &[
            dir.path().join("foo.proto").to_str().unwrap(),
            dir.path().join("a.proto").to_str().unwrap(),
            dir.path().join("b.proto").to_str().unwrap(),
        ],
        &[dir.path().to_str().unwrap()],
    );
    let content = buffa_codegen::generate(&fds.file, &["foo.proto".into()], &no_views())
        .expect("codegen")
        .into_iter()
        .map(|f| f.content)
        .collect::<Vec<_>>()
        .join("\n");

    // Each message's `inner` field references its own deconflicted module.
    // `oof__::Inner` is not a substring of `oof___::Inner`, so finding both
    // proves the two modules are distinct (and neither is the bare `oof`/`oof_`).
    assert!(
        content.contains("oof__ :: Inner") || content.contains("oof__::Inner"),
        "Oof should reference oof__::Inner: {content}"
    );
    assert!(
        content.contains("oof___ :: Inner") || content.contains("oof___::Inner"),
        "Oof_ should reference oof___::Inner: {content}"
    );
}

#[test]
fn module_no_collision_keeps_natural_module_name() {
    // Without a colliding sub-package, the nested module stays `oof` (no churn).
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package foo;
        message Oof { message Inner { int32 x = 1; } Inner inner = 1; }
        "#,
        &no_views(),
    );
    // The nested module is present and NOT deconflicted (no `_` suffix). The
    // `!oof_` check is the meaningful guard; `oof::Inner` confirms the module
    // exists, both robust to prettyplease spacing.
    assert!(
        content.contains("oof :: Inner") || content.contains("oof::Inner"),
        "{content}"
    );
    assert!(
        !content.contains("pub mod oof_") && !content.contains("oof_ ::"),
        "no spurious dedup: {content}"
    );
}

#[test]
fn module_of_a_lower_case_message_gets_a_suffix() {
    // `message item` declares `struct item`, so its nested types, and its
    // modules in the `__buffa` trees, are in `item_`.
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package foo;
        message item {
          message Inner { int32 x = 1; }
          Inner inner = 1;
          oneof pick { int32 a = 2; string b = 3; }
        }
        message User { item.Inner inner = 1; }
        "#,
        &CodeGenConfig::default(),
    );
    assert!(content.contains("pub struct item {"), "{content}");
    assert!(!content.contains("pub mod item {"), "{content}");
    // Once in the owned tree, and once each under `__buffa::view`,
    // `__buffa::oneof` and `__buffa::view::oneof`.
    assert_eq!(content.matches("pub mod item_ {").count(), 4, "{content}");
    for path in [
        "item_::Inner",
        "__buffa::view::item_::InnerView",
        "__buffa::oneof::item_::Pick",
    ] {
        assert!(content.contains(path), "missing `{path}`: {content}");
    }
    assert!(
        content.contains("because `item` is not available in this scope"),
        "the renamed module is documented: {content}"
    );
}

#[test]
fn module_named_after_a_path_keyword_gets_a_suffix() {
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package foo;
        message Crate { message Inner { int32 x = 1; } Inner inner = 1; }
        message Self { message Inner { int32 x = 1; } Inner inner = 1; }
        message User { Crate.Inner a = 1; Self.Inner b = 2; }
        "#,
        &CodeGenConfig::default(),
    );
    for expected in [
        "pub mod crate_ {",
        "pub mod self_ {",
        "pub struct Self_ {",
        "crate_::Inner",
        "self_::Inner",
        "__buffa::view::crate_::InnerView",
    ] {
        assert!(
            content.contains(expected),
            "missing `{expected}`: {content}"
        );
    }
    assert!(!content.contains("crate::Inner"), "{content}");
}

#[test]
fn module_named_arbitrary_gets_a_suffix_whatever_the_config() {
    let proto = r#"
        syntax = "proto3";
        package foo;
        message Arbitrary { message Inner { int32 x = 1; } Inner inner = 1; }
        "#;
    let mut config = no_views();
    for generate_arbitrary in [false, true] {
        config.generate_arbitrary = generate_arbitrary;
        let content = generate_proto(proto, &config);
        assert!(content.contains("pub mod arbitrary_ {"), "{content}");
        assert!(content.contains("arbitrary_::Inner"), "{content}");
    }
}

#[test]
fn module_named_oneof_gets_a_suffix_at_package_level() {
    // `__buffa::view::oneof` is the root of the view-oneof tree.
    let proto = r#"
        syntax = "proto3";
        package foo;
        message Oneof {
          message Inner { int32 x = 1; }
          message Oneof { message Deep { int32 x = 1; } Deep deep = 1; }
          Inner inner = 1;
          oneof pick { int32 a = 2; string b = 3; }
        }
        "#;
    for config in [CodeGenConfig::default(), no_views()] {
        let content = generate_proto(proto, &config);
        assert!(content.contains("pub mod oneof_ {"), "{content}");
        assert!(content.contains("oneof_::Inner"), "{content}");
        // The nested `Oneof` keeps `oneof`: only the package level is taken.
        assert!(content.contains("oneof_::oneof::Deep"), "{content}");
    }
    let content = generate_proto(proto, &CodeGenConfig::default());
    assert!(
        content.contains("__buffa::view::oneof_::InnerView"),
        "{content}"
    );
    assert!(
        content.contains("__buffa::view::oneof::oneof_::Pick"),
        "{content}"
    );
}

#[test]
fn nested_module_avoids_a_sibling_type_name() {
    // Inside `Outer`: `leaf` declares `struct leaf`, and the enum `mode`
    // takes the module name of `Mode`.
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package foo;
        message Outer {
          message leaf { message Deep { int32 n = 1; } Deep deep = 1; }
          message Mode { message Detail { int32 n = 1; } Detail detail = 1; }
          enum mode { MODE_UNSPECIFIED = 0; }
          leaf l = 1;
          Mode m = 2;
          mode e = 3;
        }
        "#,
        &no_views(),
    );
    for expected in [
        "pub mod leaf_ {",
        "pub mod mode_ {",
        "leaf_::Deep",
        "mode_::Detail",
    ] {
        assert!(
            content.contains(expected),
            "missing `{expected}`: {content}"
        );
    }
    assert!(!content.contains("pub mod leaf {"), "{content}");
}

#[test]
fn module_deconflicted_from_a_subpackage_is_renamed_in_the_view_tree() {
    // `InnerView` takes the name of the natural re-export of `Inner`'s view.
    let dir = tempfile::tempdir().expect("temp dir");
    std::fs::write(
        dir.path().join("foo.proto"),
        "syntax = \"proto3\";\npackage foo;\n\
         message Oof {\n\
           message Inner { int32 x = 1; }\n\
           message InnerView { int32 y = 1; }\n\
           Inner inner = 1;\n\
         }\n",
    )
    .unwrap();
    std::fs::write(
        dir.path().join("foo_oof.proto"),
        "syntax = \"proto3\";\npackage foo.oof;\nmessage Thing { int32 y = 1; }\n",
    )
    .unwrap();
    let fds = compile_protos(
        &[
            dir.path().join("foo.proto").to_str().unwrap(),
            dir.path().join("foo_oof.proto").to_str().unwrap(),
        ],
        &[dir.path().to_str().unwrap()],
    );
    let content =
        buffa_codegen::generate(&fds.file, &["foo.proto".into()], &CodeGenConfig::default())
            .expect("codegen")
            .into_iter()
            .map(|f| f.content)
            .collect::<Vec<_>>()
            .join("\n");
    assert!(!content.contains("pub mod oof {"), "{content}");
    assert!(
        content.contains("__buffa::view::oof_::InnerView"),
        "{content}"
    );
}

#[test]
fn inline_string_field_mapping() {
    use buffa_codegen::StringRepr;
    let mut config = no_views();
    config
        .string_fields
        .push((".".into(), StringRepr::Custom("::smol_str::SmolStr".into())));
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message Msg {
          string name = 1;
          optional string nick = 2;
        }
        "#,
        &config,
    );
    assert!(
        content.contains("::smol_str::SmolStr"),
        "string fields should use the custom type: {content}"
    );
    // Non-optional singular decode must use the generic helper, not merge_string.
    assert!(
        content.contains("::buffa::types::decode_string_to"),
        "decode must use decode_string_to for non-default string repr: {content}"
    );
    assert!(
        !content.contains("merge_string(&mut self"),
        "must not call merge_string on a non-default string field: {content}"
    );
}

#[test]
fn inline_string_field_selective_and_override() {
    use buffa_codegen::StringRepr;
    let mut config = no_views();
    // Broad default, then a more specific override (last match wins).
    config
        .string_fields
        .push((".".into(), StringRepr::Custom("::smol_str::SmolStr".into())));
    config.string_fields.push((
        ".test.Msg.code".into(),
        StringRepr::Custom("::compact_str::CompactString".into()),
    ));
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message Msg {
          string name = 1;
          string code = 2;
        }
        "#,
        &config,
    );
    assert!(
        content.contains("::smol_str::SmolStr"),
        "broad rule should apply SmolStr to `name`: {content}"
    );
    assert!(
        content.contains("::compact_str::CompactString"),
        "specific override should apply CompactString to `code`: {content}"
    );
}

#[test]
fn inline_string_custom_emits_generic_arbitrary_builder() {
    use buffa_codegen::{BytesRepr, StringRepr};
    let mut config = no_views();
    config.generate_arbitrary = true;
    config
        .string_fields
        .push((".".into(), StringRepr::Custom("::ecow::EcoString".into())));
    config.bytes_fields.push((".".into(), BytesRepr::Bytes));
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message Msg {
            string name = 1;
            optional string nick = 2;
            repeated string tags = 3;
            bytes blob = 4;
        }
        "#,
        &config,
    );
    assert!(
        content.contains("::ecow::EcoString"),
        "string field should use the custom type: {content}"
    );
    // A non-default repr attaches the builder for the field's shape, whether
    // or not the type has a native Arbitrary impl.
    assert_eq!(
        ["name", "nick", "tags", "blob"].map(|field| arbitrary_builder_of(&content, field)),
        [
            Some("arbitrary_proto_string"),
            Some("arbitrary_proto_string_opt"),
            Some("arbitrary_proto_string_vec"),
            Some("arbitrary_proto_bytes"),
        ]
    );
}

/// The `::buffa::__private` function named by the `arbitrary(with = ...)`
/// attribute on `field`, or `None` when the field has no such attribute.
fn arbitrary_builder_of<'a>(content: &'a str, field: &str) -> Option<&'a str> {
    let decl = content
        .find(&format!("pub {field}:"))
        .unwrap_or_else(|| panic!("no field `{field}` in: {content}"));
    // The field's attributes follow the previous `pub` item: the preceding
    // field, or the struct itself.
    let before = &content[..decl];
    let attrs = &before[before.rfind("pub ").unwrap_or(0)..];
    let prefix = "arbitrary(with = ::buffa::__private::";
    let rest = &attrs[attrs.find(prefix)? + prefix.len()..];
    Some(&rest[..rest.find(')').expect("unterminated arbitrary attribute")])
}

const ARBITRARY_MAP_PROTO: &str = r#"
    syntax = "proto3";
    package test;
    message Msg {
        map<string, int32> string_key = 1;
        map<int32, string> string_value = 2;
        map<string, string> both_strings = 3;
        map<string, bytes> string_key_bytes_value = 4;
        map<int32, bytes> bytes_value = 5;
        map<int32, int32> no_string_or_bytes = 6;
    }
"#;

/// Asserts the builder of each field of [`ARBITRARY_MAP_PROTO`], in field
/// order.
#[track_caller]
fn assert_arbitrary_map_builders(config: &CodeGenConfig, expected: [Option<&str>; 6]) {
    let content = generate_proto(ARBITRARY_MAP_PROTO, config);
    let fields = [
        "string_key",
        "string_value",
        "both_strings",
        "string_key_bytes_value",
        "bytes_value",
        "no_string_or_bytes",
    ];
    assert_eq!(
        fields.map(|field| arbitrary_builder_of(&content, field)),
        expected,
        "builders of {fields:?}"
    );
}

#[test]
fn arbitrary_map_builder_matches_the_slots_that_convert() {
    use buffa_codegen::{BytesRepr, StringRepr};

    let custom_string = (
        ".".to_owned(),
        StringRepr::Custom("::ecow::EcoString".into()),
    );
    let bytes = (".".to_owned(), BytesRepr::Bytes);

    // Custom string and `bytes::Bytes`: every slot that is `string` or `bytes`
    // converts.
    let mut config = no_views();
    config.generate_arbitrary = true;
    config.string_fields.push(custom_string.clone());
    config.bytes_fields.push(bytes.clone());
    assert_arbitrary_map_builders(
        &config,
        [
            Some("arbitrary_proto_string_map_key"),
            Some("arbitrary_proto_string_map_value"),
            Some("arbitrary_proto_string_map"),
            Some("arbitrary_proto_string_bytes_map"),
            Some("arbitrary_proto_bytes_map"),
            None,
        ],
    );

    // Custom string, default `Vec<u8>`: a `bytes` value uses its own impl.
    let mut config = no_views();
    config.generate_arbitrary = true;
    config.string_fields.push(custom_string);
    assert_arbitrary_map_builders(
        &config,
        [
            Some("arbitrary_proto_string_map_key"),
            Some("arbitrary_proto_string_map_value"),
            Some("arbitrary_proto_string_map"),
            Some("arbitrary_proto_string_map_key"),
            None,
            None,
        ],
    );

    // Default `String`, `bytes::Bytes`: a `string` key uses its own impl, so a
    // `map<string, bytes>` takes the builder that converts only the value.
    let mut config = no_views();
    config.generate_arbitrary = true;
    config.bytes_fields.push(bytes);
    assert_arbitrary_map_builders(
        &config,
        [
            None,
            None,
            None,
            Some("arbitrary_proto_bytes_map"),
            Some("arbitrary_proto_bytes_map"),
            None,
        ],
    );
}

#[test]
fn arbitrary_builder_for_a_proto2_repeated_field_is_the_vec_builder() {
    use buffa_codegen::{BytesRepr, StringRepr};

    let mut config = no_views();
    config.generate_arbitrary = true;
    config
        .string_fields
        .push((".".into(), StringRepr::Custom("::ecow::EcoString".into())));
    config.bytes_fields.push((".".into(), BytesRepr::Bytes));
    // In a proto2 file a `repeated` field inherits the file's explicit
    // `field_presence`, which sets `FieldInfo::is_optional`; its field type
    // is still `Vec<T>`.
    let content = generate_proto(
        r#"
        syntax = "proto2";
        package test;
        message Msg {
            repeated string names = 1;
            repeated bytes blobs = 2;
            optional string name = 3;
            optional bytes blob = 4;
        }
        "#,
        &config,
    );
    assert_eq!(
        ["names", "blobs", "name", "blob"].map(|field| arbitrary_builder_of(&content, field)),
        [
            Some("arbitrary_proto_string_vec"),
            Some("arbitrary_proto_bytes_vec"),
            Some("arbitrary_proto_string_opt"),
            Some("arbitrary_proto_bytes_opt"),
        ]
    );
}

#[test]
fn inline_string_default_is_unchanged() {
    // With no string_fields rule, output must still use String + merge_string.
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message Msg { string name = 1; }
        "#,
        &no_views(),
    );
    assert!(
        content.contains("::buffa::alloc::string::String"),
        "default string repr should remain String: {content}"
    );
    assert!(
        content.contains("merge_string(&mut self"),
        "default string field should keep the in-place merge_string fast path: {content}"
    );
    assert!(
        !content.contains("decode_string_to"),
        "default string field must not use the generic decode helper: {content}"
    );
}

#[test]
fn inline_preserve_unknown_fields_disabled() {
    let mut config = no_views();
    config.preserve_unknown_fields = false;
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message Msg { int32 x = 1; }
        "#,
        &config,
    );
    assert!(
        !content.contains("__buffa_unknown_fields"),
        "unknown fields should not be present when preservation is disabled: {content}"
    );
}

#[test]
fn inline_empty_message() {
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message Empty {}
        "#,
        &no_views(),
    );
    assert!(content.contains("pub struct Empty"));
    // Empty message should still implement Message.
    assert!(content.contains("impl ::buffa::Message for Empty"));
    // Should have the unknown-fields plumbing but no user fields and no
    // serialization-state field — sizes live in the external SizeCache.
    assert!(content.contains("__buffa_unknown_fields"));
    assert!(!content.contains("__buffa_cached_size"));
}

#[test]
fn inline_empty_message_no_unknown_fields() {
    let mut config = no_views();
    config.preserve_unknown_fields = false;
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message Empty {}
        "#,
        &config,
    );
    assert!(content.contains("pub struct Empty"));
    assert!(!content.contains("__buffa_unknown_fields"));
}

#[test]
fn inline_preserve_unknown_fields_in_keeps_selected_messages() {
    let mut config = no_views();
    config.preserve_unknown_fields = false;
    config.preserve_unknown_fields_in = vec![(".test.Keep".to_string(), true)];
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message Keep {}
        message Drop {}
        "#,
        &config,
    );
    assert!(
        struct_has_unknown_fields(&content, "Keep"),
        "Keep must retain unknown fields: {content}"
    );
    assert!(
        !struct_has_unknown_fields(&content, "Drop"),
        "Drop must omit unknown fields: {content}"
    );
}

#[test]
fn inline_preserve_unknown_fields_in_last_match_and_nested() {
    let mut config = no_views();
    config.preserve_unknown_fields = false;
    config.preserve_unknown_fields_in = vec![
        (".test".to_string(), true),
        (".test.Drop".to_string(), false),
        (".test.Outer.Inner".to_string(), true),
    ];
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message Keep {}
        message Drop {}
        message Outer {
          message Inner {}
        }
        "#,
        &config,
    );
    assert!(struct_has_unknown_fields(&content, "Keep"));
    assert!(!struct_has_unknown_fields(&content, "Drop"));
    // The package rule `.test` enables Outer; Inner is enabled by both the
    // package rule and its own rule.
    assert!(struct_has_unknown_fields(&content, "Outer"));
    assert!(struct_has_unknown_fields(&content, "Inner"));
}

#[test]
fn inline_preserve_unknown_fields_in_outer_on_inner_off() {
    // A rule naming `Outer` is a prefix of `Outer.Inner`, so it covers the
    // nested message too; a later, more specific `false` entry (expressible
    // through `CodeGenConfig`, not the enable-only builder) carves it out.
    let proto = r#"
        syntax = "proto3";
        package test;
        message Outer {
          message Inner {}
        }
        "#;
    let mut config = no_views();
    config.preserve_unknown_fields = false;
    config.preserve_unknown_fields_in = vec![(".test.Outer".to_string(), true)];
    let content = generate_proto(proto, &config);
    assert!(struct_has_unknown_fields(&content, "Outer"));
    assert!(
        struct_has_unknown_fields(&content, "Inner"),
        "a rule naming Outer covers Outer.Inner: {content}"
    );

    config
        .preserve_unknown_fields_in
        .push((".test.Outer.Inner".to_string(), false));
    let content = generate_proto(proto, &config);
    assert!(struct_has_unknown_fields(&content, "Outer"));
    assert!(
        !struct_has_unknown_fields(&content, "Inner"),
        "a later Inner=false rule must win over the enclosing Outer=true rule: {content}"
    );
}

#[test]
fn inline_preserve_unknown_fields_in_nested_independent_of_outer() {
    let mut config = no_views();
    config.preserve_unknown_fields = false;
    config.preserve_unknown_fields_in = vec![(".test.Outer.Inner".to_string(), true)];
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message Outer {
          message Inner {}
        }
        "#,
        &config,
    );
    assert!(
        !struct_has_unknown_fields(&content, "Outer"),
        "enabling Inner must not enable Outer: {content}"
    );
    assert!(
        struct_has_unknown_fields(&content, "Inner"),
        "Inner must retain unknown fields: {content}"
    );
}

#[test]
fn inline_preserve_unknown_fields_in_views() {
    let mut config = CodeGenConfig::default();
    config.preserve_unknown_fields = false;
    config.preserve_unknown_fields_in = vec![(".test.Keep".to_string(), true)];
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message Keep {}
        message Drop {}
        "#,
        &config,
    );
    assert!(struct_has_unknown_fields(&content, "Keep"));
    assert!(!struct_has_unknown_fields(&content, "Drop"));
    assert!(
        struct_has_unknown_fields(&content, "KeepView"),
        "KeepView must retain unknown fields: {content}"
    );
    assert!(
        !struct_has_unknown_fields(&content, "DropView"),
        "DropView must omit unknown fields: {content}"
    );
}

// ── View Serialize codegen tests ────────────────────────────────────────

#[test]
fn test_view_serialize_impl_emitted_when_json_enabled() {
    let files = generate_for("json_types.proto", &json_with_views());
    let combined = files
        .iter()
        .map(|f| f.content.as_str())
        .collect::<Vec<_>>()
        .join("\n");
    assert!(
        combined.contains("impl<'__a> ::serde::Serialize for"),
        "view Serialize impl must be emitted when generate_json=true: {combined}"
    );
    for file in &files {
        syn::parse_file(&file.content).unwrap_or_else(|e| {
            panic!(
                "generated file must parse ({}): {e}\n---\n{}",
                file.package, file.content
            )
        });
    }
}

#[test]
fn test_view_serialize_not_emitted_when_json_disabled() {
    // CodeGenConfig::default() has generate_views=true, generate_json=false.
    let files = generate_for("json_types.proto", &CodeGenConfig::default());
    let combined = files
        .iter()
        .map(|f| f.content.as_str())
        .collect::<Vec<_>>()
        .join("\n");
    assert!(
        !combined.contains("impl<'__a> ::serde::Serialize for"),
        "view Serialize impl must NOT be emitted when generate_json=false"
    );
}

#[test]
fn test_view_serialize_json_helpers_used() {
    // Verify that int64 and bytes fields in a view use json_helpers paths.
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message Item {
          int64 id = 1;
          bytes data = 2;
          double score = 3;
        }
        "#,
        &json_with_views(),
    );
    assert!(
        content.contains("json_helpers"),
        "view Serialize must use json_helpers for int64/bytes/double: {content}"
    );
    syn::parse_file(&content).expect("generated content must parse");
}

#[test]
fn test_view_serialize_map_keys_stringified() {
    // Protobuf JSON requires map keys to be JSON strings. The view Serialize
    // impl must emit an explicit `_WK` newtype with `collect_str` for
    // non-string scalar keys, mirroring the owned-side `DisplayKey` wrapper —
    // not rely on the serializer's `MapKeySerializer` to stringify primitives
    // (which only `serde_json` does).
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message Maps {
          map<int64, string> by_id = 1;
          map<bool, string> by_flag = 2;
          map<string, string> by_name = 3;
        }
        "#,
        &json_with_views(),
    );
    syn::parse_file(&content).expect("generated content must parse");
    assert!(
        content.contains("::buffa::json_helpers::MapKeyJson"),
        "non-string map keys must be stringified via MapKeyJson: {content}"
    );
}

#[test]
fn test_view_serialize_proto2_required_multi_field_parses() {
    // Regression: proto2 required fields with helper-typed scalars previously
    // emitted `struct _W` at fn scope without a wrapping block, causing E0428
    // (duplicate definition) when two or more such fields appeared in one message.
    // This test asserts the generated output parses (syntax-level regression guard).
    let content = generate_proto(
        r#"
        syntax = "proto2";
        package test;
        message TwoRequired {
          required int64 a = 1;
          required bytes b = 2;
          required int64 c = 3;
        }
        "#,
        &json_with_views(),
    );
    syn::parse_file(&content)
        .expect("proto2 required multi-field view Serialize must produce parseable output");
    // Each required field must be serialized unconditionally (no skip_if).
    assert!(
        content.contains("impl<'__a> ::serde::Serialize for TwoRequiredView"),
        "view Serialize impl must be emitted: {content}"
    );
}

// ── with_* setter tests ───────────────────────────────────────────────────────

#[test]
fn with_setters_emitted_for_explicit_presence_fields() {
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        enum Color { COLOR_UNSPECIFIED = 0; RED = 1; }
        message Msg {
          optional int32   count  = 1;
          optional string  name   = 2;
          optional bytes   data   = 3;
          optional Color   color  = 4;
          // implicit-presence fields — no setter
          int32   implicit_int    = 5;
          string  implicit_str    = 6;
          // repeated — no setter
          repeated string tags    = 7;
        }
        "#,
        &no_views(),
    );

    // Explicit-presence fields get setters.
    assert!(
        content.contains("pub fn with_count"),
        "with_count missing: {content}"
    );
    assert!(
        content.contains("pub fn with_name"),
        "with_name missing: {content}"
    );
    assert!(
        content.contains("pub fn with_data"),
        "with_data missing: {content}"
    );
    assert!(
        content.contains("pub fn with_color"),
        "with_color missing: {content}"
    );

    // String setter uses impl Into<...> for &str ergonomics.
    assert!(
        content.contains("impl ::core::convert::Into"),
        "string setter should use impl Into: {content}"
    );

    // Implicit-presence and repeated fields must NOT get setters.
    assert!(
        !content.contains("with_implicit_int"),
        "implicit int should not get setter: {content}"
    );
    assert!(
        !content.contains("with_implicit_str"),
        "implicit string should not get setter: {content}"
    );
    assert!(
        !content.contains("with_tags"),
        "repeated field should not get setter: {content}"
    );
}

#[test]
fn with_setters_disabled_by_config() {
    let mut config = no_views();
    config.generate_with_setters = false;
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message Msg { optional int32 count = 1; }
        "#,
        &config,
    );
    assert!(
        !content.contains("pub fn with_count"),
        "setter should be absent when generate_with_setters=false: {content}"
    );
}

#[test]
fn with_setters_bytes_type_uses_into() {
    let mut config = no_views();
    config
        .bytes_fields
        .push((".test.Msg.data".into(), buffa_codegen::BytesRepr::Bytes));
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message Msg { optional bytes data = 1; }
        "#,
        &config,
    );
    // bytes::Bytes field should use impl Into for ergonomics.
    assert!(
        content.contains("pub fn with_data"),
        "with_data missing: {content}"
    );
    assert!(
        content.contains("impl ::core::convert::Into"),
        "bytes::Bytes setter should use impl Into: {content}"
    );
}

#[test]
fn with_setters_vec_u8_uses_into() {
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message Msg { optional bytes data = 1; }
        "#,
        &no_views(),
    );
    // Vec<u8> bytes field uses impl Into: From<&[T; N]> for Vec<T> is stable
    // since Rust 1.74, so b"hello" works directly without .to_vec().
    assert!(
        content.contains("pub fn with_data"),
        "with_data missing: {content}"
    );
    assert!(
        content.contains("impl ::core::convert::Into"),
        "Vec<u8> setter should use impl Into: {content}"
    );
}

#[test]
fn with_setters_enum_uses_into() {
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        enum Color { COLOR_UNSPECIFIED = 0; RED = 1; }
        message Msg { optional Color color = 1; }
        "#,
        &no_views(),
    );
    // EnumValue<E>: From<E>, so impl Into<EnumValue<E>> lets callers pass the
    // enum variant directly without wrapping in EnumValue::Known(...).
    assert!(
        content.contains("pub fn with_color"),
        "with_color missing: {content}"
    );
    assert!(
        content.contains("impl ::core::convert::Into"),
        "enum setter should use impl Into: {content}"
    );
}

#[test]
fn with_setters_proto2_repeated_no_setter() {
    // Regression: proto2 repeated fields have is_explicit_presence=true due to
    // proto2's EXPLICIT presence default, but their struct field is Vec<T>,
    // not Option<T>. They must not receive a setter.
    let content = generate_proto(
        r#"
        syntax = "proto2";
        package test;
        message Msg { repeated string items = 1; }
        "#,
        &no_views(),
    );
    assert!(
        !content.contains("with_items"),
        "proto2 repeated field should not get setter: {content}"
    );
}

#[test]
fn blanket_unbox_oneof_skips_recursive_variants() {
    // Config::unbox_oneof() ("." blanket rule) stores every NON-recursive
    // variant inline: recursive variants are silently kept boxed rather than
    // rejected. Only an exact-path rule on a recursive variant errors (see
    // inline_oneof_unbox_recursive_variant_is_rejected).
    let proto = dedent(
        r#"
        syntax = "proto3";
        package test;
        message Node {
          oneof kind {
            Node child = 1;
            int32 leaf = 2;
          }
        }
        message Small { int32 value = 1; }
        message Envelope {
          oneof body {
            Small small = 1;
          }
        }
        "#,
    );
    let dir = tempfile::tempdir().expect("temp dir");
    let proto_path = dir.path().join("test.proto");
    std::fs::write(&proto_path, &proto).expect("write proto");
    let fds = compile_protos(
        &[proto_path.to_str().unwrap()],
        &[dir.path().to_str().unwrap()],
    );

    let mut config = no_views();
    config.unboxed_oneof_fields.push(".".to_string()); // == Config::unbox_oneof()
    let result = buffa_codegen::generate(&fds.file, &["test.proto".into()], &config);
    let files = result.unwrap_or_else(|e| {
        panic!("blanket unbox_oneof() should skip the recursive variant, but errored: {e}")
    });
    let content = files
        .into_iter()
        .map(|f| f.content)
        .collect::<Vec<_>>()
        .join("\n");
    assert!(
        content.contains("Child(::buffa::alloc::boxed::Box<"),
        "recursive variant must stay boxed under the blanket rule"
    );
    assert!(
        content.contains("Small(super::super::super::Small)"),
        "non-recursive variant should be inline under the blanket rule"
    );
}

#[test]
fn blanket_unbox_oneof_keeps_mutually_recursive_variants_boxed() {
    // Mutual recursion: A.body.b -> B and B.body.a -> A form a cycle only
    // when BOTH edges are inline. The blanket rule must keep both boxed
    // (the walk is conservative and order-independent), while the
    // non-recursive C variant inlines.
    let mut config = no_views();
    config.unboxed_oneof_fields.push(".".to_string());
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message A {
          oneof body {
            B b = 1;
            C c = 2;
          }
        }
        message B {
          oneof body {
            A a = 1;
          }
        }
        message C { int32 value = 1; }
        "#,
        &config,
    );
    assert!(
        content.contains("B(::buffa::alloc::boxed::Box<super::super::super::B>)"),
        "mutually recursive variant A.body.b must stay boxed: {content}"
    );
    assert!(
        content.contains("A(::buffa::alloc::boxed::Box<super::super::super::A>)"),
        "mutually recursive variant B.body.a must stay boxed: {content}"
    );
    assert!(
        content.contains("C(super::super::super::C)"),
        "non-recursive variant should be inline under the blanket rule: {content}"
    );
}

#[test]
fn prefix_unbox_rule_on_recursive_variant_skips_without_error() {
    // A non-blanket prefix rule (message scope, not exact variant path) that
    // matches a recursive variant takes the silent-skip path, not the
    // exact-rule error: the recursive variant stays boxed, siblings inline.
    let mut config = no_views();
    config.unboxed_oneof_fields.push(".test.Node".to_string());
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message Leaf { int32 value = 1; }
        message Node {
          oneof kind {
            Node child = 1;
            Leaf leaf = 2;
          }
        }
        "#,
        &config,
    );
    assert!(
        content.contains("Child(::buffa::alloc::boxed::Box<super::super::super::Node>)"),
        "recursive variant must stay boxed under a prefix rule: {content}"
    );
    assert!(
        content.contains("Leaf(super::super::super::Leaf)"),
        "non-recursive sibling should be inline under the prefix rule: {content}"
    );
}

#[test]
fn default_inline_pointer_skips_recursive_fields() {
    // PointerRepr::Inline (the default) stores every NON-recursive singular
    // message field inline; recursive fields are silently kept on Box.
    // Mirrors blanket_unbox_oneof_skips_recursive_variants for #248.
    let config = no_views();
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message Small { int32 value = 1; }
        message Node {
          Node child = 1;
          Small leaf = 2;
        }
        "#,
        &config,
    );
    assert!(
        content.contains("pub child: ::buffa::MessageField<Self>,"),
        "recursive singular field must stay on Box (default pointer) under the blanket rule: {content}"
    );
    assert!(
        content.contains("pub leaf: ::buffa::MessageField<Small, ::buffa::Inline<Small>>"),
        "non-recursive singular field should be inline under the blanket rule: {content}"
    );
}

#[test]
fn default_inline_pointer_keeps_mutually_recursive_boxed() {
    // Mutual recursion: A.b -> B and B.a -> A form a cycle only when BOTH
    // fields are inline. The default Inline must keep both on Box; the
    // non-recursive A.c field inlines.
    let config = no_views();
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message A { B b = 1; C c = 2; }
        message B { A a = 1; }
        message C { int32 value = 1; }
        "#,
        &config,
    );
    assert!(
        content.contains("pub b: ::buffa::MessageField<B>,"),
        "mutually recursive field A.b must stay on Box: {content}"
    );
    assert!(
        content.contains("pub a: ::buffa::MessageField<A>,"),
        "mutually recursive field B.a must stay on Box: {content}"
    );
    assert!(
        content.contains("pub c: ::buffa::MessageField<C, ::buffa::Inline<C>>"),
        "non-recursive field A.c should be inline under the blanket rule: {content}"
    );
}

#[test]
fn exact_inline_rule_on_recursive_field_is_rejected() {
    // An exact-path PointerRepr::Inline rule naming a recursive singular
    // field is a hard codegen error — the user asked for an unsized struct.
    let proto = dedent(
        r#"
        syntax = "proto3";
        package test;
        message Node { Node child = 1; }
        "#,
    );
    let dir = tempfile::tempdir().expect("temp dir");
    let proto_path = dir.path().join("test.proto");
    std::fs::write(&proto_path, &proto).expect("write proto");
    let fds = compile_protos(
        &[proto_path.to_str().unwrap()],
        &[dir.path().to_str().unwrap()],
    );

    let mut config = no_views();
    config.pointer_fields.push((
        ".test.Node.child".to_string(),
        buffa_codegen::PointerRepr::Inline,
    ));
    let result = buffa_codegen::generate(&fds.file, &["test.proto".into()], &config);
    let err = result.expect_err("inlining a recursive singular field should error");
    let msg = err.to_string();
    assert!(
        msg.contains("recursive") && msg.contains(".test.Node.child"),
        "error should explain the recursion and name the field: {err}"
    );
}

#[test]
fn box_type_opt_out_restores_boxed_default() {
    // PointerRepr::Box is the opt-out from the Inline default: a path-scoped
    // rule keeps the matched fields on Box; a "." blanket restores the
    // pre-0.9 boxed default everywhere.
    let mut config = no_views();
    config
        .pointer_fields
        .push((".test.Node".to_string(), buffa_codegen::PointerRepr::Box));
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message Leaf { int32 value = 1; }
        message Node { Leaf leaf = 1; }
        message Elsewhere { Leaf leaf = 1; }
        "#,
        &config,
    );
    assert!(
        content.contains("pub leaf: ::buffa::MessageField<Leaf>,"),
        "Node.leaf opted out via Box rule must use the boxed pointer: {content}"
    );
    assert!(
        content.contains("pub leaf: ::buffa::MessageField<Leaf, ::buffa::Inline<Leaf>>"),
        "Elsewhere.leaf (no rule) should be inline by default: {content}"
    );
}

#[test]
fn unbox_oneof_and_inline_field_detect_cross_kind_cycle() {
    // A cycle through ONE inlined oneof variant and ONE inlined singular field
    // (A.body.b -> B, B.a -> A) must be caught by both resolvers: the variant
    // stays boxed and the field stays on Box. Either alone is non-recursive,
    // so the recursion DFS must follow both edge kinds.
    let mut config = no_views();
    config.unboxed_oneof_fields.push(".".to_string());
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message A {
          oneof body { B b = 1; }
        }
        message B { A a = 1; }
        "#,
        &config,
    );
    assert!(
        content.contains("B(::buffa::alloc::boxed::Box<super::super::super::B>)"),
        "oneof variant in a cross-kind cycle must stay boxed: {content}"
    );
    assert!(
        content.contains("pub a: ::buffa::MessageField<A>,"),
        "singular field in a cross-kind cycle must stay on Box: {content}"
    );
}

#[test]
fn boxed_oneof_variant_under_inline_default_uses_box() {
    // The default PointerRepr::Inline also matches boxed oneof variant paths,
    // but the resolved-set check (singular fields only) demotes them: the
    // variant stays Box-wrapped so unbox_oneof remains the sole inlining knob
    // for oneofs and its recursion guard cannot be bypassed.
    let config = no_views();
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package test;
        message Node {
          oneof kind { Node child = 1; }
        }
        "#,
        &config,
    );
    assert!(
        content.contains("Child(::buffa::alloc::boxed::Box<"),
        "boxed oneof variant must use Box even under a blanket Inline rule: {content}"
    );
    assert!(
        !content.contains("Child(::buffa::Inline<"),
        "boxed oneof variant must not use the Inline pointer: {content}"
    );
}

#[test]
fn custom_deserialize_qualifies_core_paths() {
    // A proto package named after a crate in the extern prelude shadows that
    // crate inside the generated module, so every path the codegen emits has
    // to be absolute. The generated Deserialize impl (oneofs and
    // extension-preserving messages take this path) reached core::fmt
    // unqualified, which resolves to the generated `core` module and fails to
    // compile with E0433.
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package core;
        message RegisterRequest {
          string name = 1;
          oneof kind {
            string a = 2;
            int32 b = 3;
          }
        }
        "#,
        &json_with_views(),
    );
    assert!(
        content.contains("&mut ::core::fmt::Formatter"),
        "expecting() must take an absolute ::core::fmt path: {content}"
    );
    assert!(
        !content.contains("&mut core::fmt::Formatter"),
        "expecting() must not emit a bare core::fmt path: {content}"
    );
}

#[test]
fn json_codegen_qualifies_serde_paths() {
    // Same shadowing hazard as above for the `serde` crate: a package or
    // nested message named `serde` puts a `mod serde` in scope, so every
    // `serde::` path the JSON emitters write has to be absolute. The
    // non-oneof field is what makes the custom Deserialize impl emit its
    // `DeserializeSeed` helper; keep it.
    let content = generate_proto(
        r#"
        syntax = "proto3";
        package serde;
        message RegisterRequest {
          string name = 1;
          oneof kind {
            string a = 2;
            int32 b = 3;
          }
        }
        "#,
        &json_with_views(),
    );

    // Every `serde::` occurrence must be the tail of a `::serde::` path.
    // Counting covers every emitter at once, where a list of literal
    // patterns silently misses the ones prettyplease wraps onto their own
    // line (`::serde::de::Error::custom(` is emitted that way).
    assert_eq!(
        content.matches("serde::").count(),
        content.matches("::serde::").count(),
        "generated code must not contain a bare serde:: path: {content}"
    );

    assert!(
        content.contains("impl ::serde::Serialize for Kind"),
        "oneof serialization must use an absolute serde path: {content}"
    );
    assert!(
        content.contains("impl<'de> ::serde::Deserialize<'de> for RegisterRequest"),
        "custom deserialization must use an absolute serde path: {content}"
    );
}

// ── deny_unknown_json_fields ─────────────────────────────────────────────────
//
// The emitted-text assertions below are about *which* mechanism each codegen
// path gets; `buffa-test/src/tests/strict_json.rs` covers what the generated
// code then does at parse time.

/// A proto with one derive-path message (no oneof, no extension ranges) and
/// one hand-written-visitor message (a real oneof).
const STRICT_JSON_PROTO: &str = r#"
    syntax = "proto3";
    package t;
    message Plain {
      int32 value = 1;
      int32 max_items = 2;
    }
    message Choice {
      oneof kind {
        int32 a = 1;
        string b_name = 2;
      }
    }
"#;

fn json_strict() -> CodeGenConfig {
    let mut c = json_no_views();
    c.deny_unknown_json_fields = true;
    c
}

/// Run codegen on an inline proto and return the rendered warnings.
fn generate_warnings(proto: &str, config: &CodeGenConfig) -> Vec<String> {
    let proto = dedent(proto);
    let dir = tempfile::tempdir().expect("failed to create temp dir");
    let proto_path = dir.path().join("test.proto");
    std::fs::write(&proto_path, &proto).expect("failed to write proto");
    let fds = compile_protos(
        &[proto_path.to_str().unwrap()],
        &[dir.path().to_str().unwrap()],
    );
    let (_, warnings) =
        buffa_codegen::generate_with_diagnostics(&fds.file, &["test.proto".into()], config)
            .expect("codegen failed");
    warnings.iter().map(ToString::to_string).collect()
}

#[test]
fn deny_unknown_json_fields_off_by_default() {
    let content = generate_proto(STRICT_JSON_PROTO, &json_no_views());
    assert!(!content.contains("deny_unknown_fields"));
    // The lenient terminal arm in the oneof message's visitor.
    assert!(content.contains("IgnoredAny"));
}

#[test]
fn deny_unknown_json_fields_uses_serdes_attribute_on_the_derive_path() {
    let content = generate_proto(STRICT_JSON_PROTO, &json_strict());
    assert!(content.contains("serde(deny_unknown_fields)"));
}

#[test]
fn deny_unknown_json_fields_uses_a_strict_arm_in_the_custom_visitor() {
    let content = generate_proto(STRICT_JSON_PROTO, &json_strict());
    // serde's own constructor, so the diagnostic matches the derive path's.
    // Qualified, to tell it apart from textproto's `dec.unknown_field()` and
    // the wire decoder's `decode_unknown_field`.
    assert!(content.contains("::unknown_field("));
    // Both spellings of every oneof variant are named as accepted.
    assert!(content.contains("\"bName\""));
    assert!(content.contains("\"b_name\""));
    // The message with a oneof has no lenient skip left.
    assert!(!content.contains("IgnoredAny"));
}

#[test]
fn deny_unknown_json_fields_emits_nothing_without_json() {
    let mut config = no_views();
    config.deny_unknown_json_fields = true;
    let content = generate_proto(STRICT_JSON_PROTO, &config);
    assert!(!content.contains("deny_unknown_fields"));
    assert!(!content.contains("::unknown_field("));
}

#[test]
fn deny_unknown_json_fields_without_json_warns() {
    let mut config = no_views();
    config.deny_unknown_json_fields = true;
    let warnings = generate_warnings(STRICT_JSON_PROTO, &config);
    assert!(
        warnings
            .iter()
            .any(|w| w.contains("deny_unknown_json_fields requires generate_json")),
        "{warnings:?}"
    );

    // A path-scoped rule alone is enough to warn, and a correct path does not
    // make it quiet.
    let mut config = no_views();
    config.deny_unknown_json_fields_in = vec![(".t.Choice".to_string(), true)];
    let warnings = generate_warnings(STRICT_JSON_PROTO, &config);
    assert!(
        warnings
            .iter()
            .any(|w| w.contains("deny_unknown_json_fields requires generate_json")),
        "{warnings:?}"
    );

    // A rule that only disables asks for nothing, so it stays quiet.
    let mut config = no_views();
    config.deny_unknown_json_fields_in = vec![(".t.Choice".to_string(), false)];
    let warnings = generate_warnings(STRICT_JSON_PROTO, &config);
    assert!(
        !warnings
            .iter()
            .any(|w| w.contains("deny_unknown_json_fields requires generate_json")),
        "{warnings:?}"
    );

    // With JSON on, it stays quiet.
    let warnings = generate_warnings(STRICT_JSON_PROTO, &json_strict());
    assert!(
        !warnings
            .iter()
            .any(|w| w.contains("deny_unknown_json_fields requires generate_json")),
        "{warnings:?}"
    );
}

#[test]
fn deny_unknown_json_fields_in_scopes_to_matching_messages() {
    let mut config = json_no_views();
    config.deny_unknown_json_fields_in = vec![(".t.Choice".to_string(), true)];
    let content = generate_proto(STRICT_JSON_PROTO, &config);
    // Choice (custom visitor) is strict; Plain (derive) keeps the default.
    assert!(content.contains("::unknown_field("));
    assert!(!content.contains("deny_unknown_fields"));
}

#[test]
fn deny_unknown_json_fields_in_rule_matching_nothing_warns() {
    let mut config = json_no_views();
    config.deny_unknown_json_fields_in = vec![(".t.Typo".to_string(), true)];
    let warnings = generate_warnings(STRICT_JSON_PROTO, &config);
    assert!(
        warnings.iter().any(|w| w
            .contains("deny_unknown_json_fields_in rule '.t.Typo' matched no generated message")),
        "{warnings:?}"
    );
}

/// `#[serde(deny_unknown_fields)]` must never land on a struct that also
/// carries `#[serde(flatten)]`. serde documents that combination as
/// unsupported but does not reject it: it compiles and unknown keys are still
/// reported, but as a bare ``unknown field `x` `` with no expected-key list,
/// and through the buffering path the wrapper gate in `message.rs` avoids.
/// buffa emits two kinds of flattened field — the extension-JSON wrapper and
/// each oneof field — and both force the hand-written-visitor path, so neither
/// can meet the attribute. serde will not catch a regression, so assert it
/// here.
#[test]
fn deny_unknown_json_fields_never_meets_the_flattened_extension_wrapper() {
    let proto = r#"
        syntax = "proto2";
        package t;
        message Carrier {
          extensions 100 to 200;
          optional int32 x = 1;
        }
        extend Carrier {
          optional string label = 100;
        }
    "#;
    let content = generate_proto(proto, &json_strict());
    // The wrapper is there (preservation is on by default) …
    assert!(
        content.contains("serde(flatten)"),
        "no flattened wrapper emitted"
    );
    // … so strictness came from the visitor, not from serde's attribute.
    assert!(content.contains("::unknown_field("));
    assert!(!content.contains("deny_unknown_fields"));
}