bitsandbytes-macros 0.3.1

Procedural macros for the `bitsandbytes` crate: #[bin], #[bitfield], #[derive(BitEnum)].
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
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
//! Expansion of `#[derive(BitDecode)]` / `#[derive(BitEncode)]` — the bit-stream
//! message codec.
//!
//! Each generates an impl that reads/writes the struct's named fields **in
//! declaration order** from a `bnb::BitReader`/`BitWriter` bit cursor. A field
//! is read with `__bnb_r.read()` / written with `__bnb_w.write(self.field)`, which works for
//! any `bnb::Bits` type (`u1`..`u127`, `#[bitfield]`, `#[derive(BitEnum)]`), so
//! the bit-stream codec composes with the rest of the crate's macros. Nested
//! `#[nested]` messages, `[u8; N]` payloads, `magic`, `#[br(count = …)]` `Vec`s,
//! `ctx` parameterization, `#[br(temp)]`/`#[bw(calc = …)]`, `#[br(if(…))]`
//! conditional `Option`s, `#[br(map/try_map = …)]`/`#[bw(map = …)]` transforms, and
//! `#[reserved]`/`#[reserved_with(…)]` bits, positioning (`pad_*`/`align_*`/
//! `restore_position`), and the `parse_with`/`write_with` escape hatches are all
//! supported (`temp`/`calc`/`reserved` via `#[bin]`, which generates the codec
//! directly).
//!
//! ## Right-tool guard
//!
//! The bare `#[derive(BitDecode/BitEncode)]` is the low-level bit codec; if a
//! struct's fields are **all byte-aligned** (every width a multiple of 8) the cursor
//! never leaves byte boundaries, so `#[bin]` (the unified codec) is the better tool.
//! The derives emit a const-eval guard that rejects such a struct, steering the
//! author to `#[bin]`. The escape hatch is `#[bit_stream(allow_byte_aligned)]`.

use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote};
use syn::parse::{Parse, ParseStream, Parser};
use syn::punctuated::Punctuated;
use syn::{
    Data, DeriveInput, Fields, FieldsNamed, Ident, ItemStruct, Token, Type, parse_macro_input,
};

/// A declared context parameter `name: Ty` from `ctx(name: Ty, …)`.
struct CtxParam {
    name: Ident,
    ty: Type,
}

impl Parse for CtxParam {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let name: Ident = input.parse()?;
        input.parse::<Token![:]>()?;
        let ty: Type = input.parse()?;
        Ok(CtxParam { name, ty })
    }
}

/// The generated context-struct name for a type/ident — `Foo` ⇒ `FooCtx`.
fn ctx_struct_ident(name: &Ident) -> Ident {
    format_ident!("{}Ctx", name)
}

/// The context-struct **type** for a field/element type — appends `Ctx` to the
/// last path segment so `m::Value` ⇒ `m::ValueCtx`.
fn ctx_struct_ty(ty: &Type) -> syn::Result<TokenStream2> {
    if let Type::Path(p) = ty {
        let mut path = p.path.clone();
        if let Some(last) = path.segments.last_mut() {
            last.ident = ctx_struct_ident(&last.ident);
            last.arguments = syn::PathArguments::None;
            return Ok(quote!(#path));
        }
    }
    Err(syn::Error::new_spanned(
        ty,
        "a `ctx`-parameterized field must have a path type (so its `…Ctx` struct can be named)",
    ))
}

/// The const-eval guard's message — steers the bare derive toward `#[bin]`.
const BYTE_ALIGNED_MSG: &str = "this struct's fields are all byte-aligned. The bare \
`#[derive(BitDecode/BitEncode)]` is the low-level bit codec; for a byte-aligned message use \
`#[bin]` — the unified codec (it handles byte-aligned data natively and adds \
magic/count/ctx/map/if/validate). The bare derive is for fields that straddle byte boundaries \
(e.g. a 108-bit payload). To keep the bare derive on an all-byte-aligned struct anyway, add \
`#[bit_stream(allow_byte_aligned)]`.";

/// Returns the named fields of a non-generic struct, or a well-spanned error.
fn named_struct(input: &DeriveInput) -> syn::Result<&FieldsNamed> {
    if !input.generics.params.is_empty() {
        return Err(syn::Error::new_spanned(
            &input.generics,
            "BitDecode/BitEncode do not support generic parameters yet",
        ));
    }
    match &input.data {
        Data::Struct(s) => match &s.fields {
            Fields::Named(f) => Ok(f),
            _ => Err(syn::Error::new_spanned(
                &input.ident,
                "BitDecode/BitEncode require a struct with named fields",
            )),
        },
        _ => Err(syn::Error::new_spanned(
            &input.ident,
            "BitDecode/BitEncode can only derive for structs",
        )),
    }
}

/// Parsed struct-level `#[bit_stream(...)]` options.
#[derive(Default)]
struct BitStreamAttrs {
    /// `allow_byte_aligned` — opt out of the right-tool guard.
    allow_byte_aligned: bool,
    /// `bits = lsb` (else MSB-first, the default).
    lsb: bool,
    /// `little` / `bytes = little` (else big-endian, the default).
    little: bool,
    /// `magic = <expr>` — a leading constant verified on read, emitted on write.
    /// Any `Bits` value, so it can even be sub-byte (`u3::new(0b110)`).
    magic: Option<syn::Expr>,
    /// `ctx(name: Ty, …)` — context this type needs from its parent. When present the
    /// type gets `decode_with`/`encode_with` (it does **not** implement
    /// `BitDecode`/`BitEncode`, which take no context).
    ctx: Vec<(Ident, Type)>,
    /// `auto_len(field.nested = kind(source), …)` — cross-struct `WireLen` derivation,
    /// applied at the targeted field's encode. Empty for the bare derives (`#[bin]` only).
    auto_len: Vec<AutoLenSpec>,
}

fn parse_bit_stream(input: &DeriveInput) -> syn::Result<BitStreamAttrs> {
    let mut attrs = BitStreamAttrs::default();
    for attr in &input.attrs {
        if attr.path().is_ident("bit_stream") {
            attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("allow_byte_aligned") {
                    attrs.allow_byte_aligned = true;
                    Ok(())
                } else if meta.path.is_ident("bits") {
                    let val: Ident = meta.value()?.parse()?;
                    match val.to_string().as_str() {
                        "msb" => attrs.lsb = false,
                        "lsb" => attrs.lsb = true,
                        _ => return Err(meta.error("expected `msb` or `lsb`")),
                    }
                    Ok(())
                } else if meta.path.is_ident("bytes") {
                    let val: Ident = meta.value()?.parse()?;
                    match val.to_string().as_str() {
                        "big" => attrs.little = false,
                        "little" => attrs.little = true,
                        _ => return Err(meta.error("expected `big` or `little`")),
                    }
                    Ok(())
                } else if meta.path.is_ident("magic") {
                    attrs.magic = Some(meta.value()?.parse()?);
                    Ok(())
                } else if meta.path.is_ident("ctx") {
                    let content;
                    syn::parenthesized!(content in meta.input);
                    let params = Punctuated::<CtxParam, Token![,]>::parse_terminated(&content)?;
                    attrs.ctx = params.into_iter().map(|p| (p.name, p.ty)).collect();
                    Ok(())
                } else {
                    Err(meta.error(
                        "unknown `#[bit_stream(...)]` option; expected `allow_byte_aligned`, `bits = msb|lsb`, `bytes = big|little`, `magic = <expr>`, or `ctx(name: Ty, …)`",
                    ))
                }
            })?;
        }
    }
    Ok(attrs)
}

/// The runtime [`Layout`](bnb::Layout) (bit + byte order) for the struct.
fn layout_token(attrs: &BitStreamAttrs) -> TokenStream2 {
    let bnb = crate::bnb_path();
    let bit = if attrs.lsb {
        quote!(#bnb::__private::BitOrder::Lsb)
    } else {
        quote!(#bnb::__private::BitOrder::Msb)
    };
    let byte = if attrs.little {
        quote!(#bnb::__private::ByteOrder::Little)
    } else {
        quote!(#bnb::__private::ByteOrder::Big)
    };
    quote!(#bnb::__private::Layout { bit: #bit, byte: #byte })
}

// `#[nested]` is now obsolete: every field type (a `Bits` leaf or a message) implements
// `BitDecode`/`BitEncode`, so `#[bin]` decodes/encodes and sizes every field uniformly with no
// marker. The attribute is still accepted (and stripped by `is_codec_field_attr`) for backward
// compatibility, but it no longer affects codegen.

/// If the field is a fixed `[u8; N]` byte array, returns its length expression.
fn byte_array_len(f: &syn::Field) -> Option<&syn::Expr> {
    if let syn::Type::Array(arr) = &f.ty {
        if let syn::Type::Path(p) = &*arr.elem {
            if p.path.is_ident("u8") {
                return Some(&arr.len);
            }
        }
    }
    None
}

/// If the field's type is `Vec<T>`, returns the element type `T` — a
/// variable-length, `count`-driven field.
fn vec_elem(f: &syn::Field) -> Option<&syn::Type> {
    single_generic(&f.ty, "Vec")
}

/// If the field's type is `Option<T>`, returns the inner type `T` — a
/// conditional (`#[br(if(...))]`) field.
fn option_elem(f: &syn::Field) -> Option<&syn::Type> {
    single_generic(&f.ty, "Option")
}

/// The single type argument of `Wrapper<T>`, if `ty` is `Wrapper<T>`.
fn single_generic<'a>(ty: &'a syn::Type, wrapper: &str) -> Option<&'a syn::Type> {
    if let syn::Type::Path(p) = ty {
        let seg = p.path.segments.last()?;
        if seg.ident == wrapper {
            if let syn::PathArguments::AngleBracketed(a) = &seg.arguments {
                if let Some(syn::GenericArgument::Type(t)) = a.args.first() {
                    return Some(t);
                }
            }
        }
    }
    None
}

/// Parsed field-level `#[br(...)]` directives.
#[derive(Default)]
struct FieldBr {
    /// `count = <expr>` — element count for a `Vec<T>` (may name an earlier field).
    count: Option<syn::Expr>,
    /// `ctx { a, b }` — pass context to a nested `ctx` message's `decode_with`/
    /// `encode_with`. Each name is a parent field or the parent's own ctx param.
    ctx: Option<Vec<Ident>>,
    /// `#[br(temp)]` — read into a local (usable by a later `count`/`ctx`) but do
    /// **not** store the field; `#[bin]` strips it from the struct. Pairs with
    /// `#[bw(calc = …)]` for the write side.
    temp: bool,
    /// `#[br(if(<expr>))]` — a conditional `Option<T>` field: read `Some` when the
    /// condition (over earlier fields, as locals) holds, else `None`; on encode the
    /// `Option`'s presence drives whether it is written.
    cond: Option<syn::Expr>,
    /// `#[brw(ignore)]` — a field that is **neither read nor written**: in-memory
    /// only, `Default::default()` on read (no input consumed) and skipped on write.
    /// Spelled with `brw` because it applies to both directions.
    ignore: bool,
    /// `#[brw(variable)]` — the field's type has a **variable-length** custom
    /// `BitDecode`/`BitEncode` (e.g. a `#[bin(codec = …)]` newtype): marks the parent's
    /// width indeterminate, so it never claims `FixedBitLen`. Redundant (and harmless)
    /// on a field that is already indeterminate (a `Vec`, a directive-bearing field).
    variable: bool,
    /// `#[br(map = <f>)]` — read the wire value `f`'s argument types, then `f(raw)`
    /// gives the field. `#[br(try_map = <f>)]` is the fallible form (`f` returns a
    /// `Result`); they are mutually exclusive.
    map: Option<syn::Expr>,
    try_map: Option<syn::Expr>,
    /// `#[br(parse_with = <f>)]` — the escape hatch: `f(r) -> Result<T, BitError>`
    /// reads the field with a custom function (`f: fn<S: Source>(&mut S) -> …`).
    parse_with: Option<syn::Expr>,
    /// `#[bw(calc = <expr>)]` — on encode, write `expr` (computed from the other
    /// fields) instead of `self.field`. The matched read/write pair is generated
    /// together so the directions can't drift.
    calc: Option<syn::Expr>,
    /// `#[br(calc = <expr>)]` — the read-side dual of `#[bw(calc)]`: on **decode**,
    /// bind the field to `expr` (computed from earlier fields, as locals) instead of
    /// reading wire bits, and on **encode** write nothing. The field is stored (so it
    /// is a normal builder/struct field), but it consumes zero wire bits in both
    /// directions — its bytes live in the raw fields it derives from (typically
    /// `#[br(temp)]` + `#[bw(calc)]`). This lets a later field give context to a
    /// stored typed field without a look-ahead: read the raw layout into temps in
    /// wire order, then `calc` the typed fields from the full set.
    br_calc: Option<syn::Expr>,
    /// `#[bw(map = <f>)]` — on encode, write `f(&self.field)` (the wire value).
    bw_map: Option<syn::Expr>,
    /// `#[bw(write_with = <f>)]` — the escape hatch: `f(&self.field, w) -> Result<(),
    /// BitError>` writes the field with a custom function.
    write_with: Option<syn::Expr>,
    /// `#[br(pad_before/pad_after = <bits>)]` — skip a bit count around the field
    /// (`4.bits()` / `3.bytes()` via `bnb::prelude`). `align_before/align_after`
    /// skip to the next byte boundary.
    pad_before: Option<syn::Expr>,
    pad_after: Option<syn::Expr>,
    align_before: bool,
    align_after: bool,
    /// `#[br(restore_position)]` — read the field (a peek), then rewind the cursor so
    /// later fields re-read from the same offset; skipped on write. Seeks, so the
    /// generated `decode` is bound on [`SeekSource`](bnb::SeekSource): a
    /// forward-only stream is a compile error (the slice entry points
    /// `decode`/`peek`/`decode_exact` always qualify).
    restore_position: bool,
    /// `#[br(seek = <bits>)]` — before reading, jump the cursor to that **absolute**
    /// bit offset (e.g. following a pointer). A read-side primitive (the writer is
    /// append-only); pair with `restore_position` to read at an offset and return.
    /// Like `restore_position` it seeks, so `decode` is bound on
    /// [`SeekSource`](bnb::SeekSource). On encode the seek is a no-op — see the guide.
    seek: Option<syn::Expr>,
    /// `#[br(dbg)]` — emit a `tracing` event (TRACE level, target `bnb::dbg`) carrying
    /// the field's start offset and decoded value as it is read (the field type must be
    /// `Debug`). A read-only diagnostic: it consumes no extra bits and is inert on encode.
    dbg: bool,
    /// `#[br(assert(<expr>))]` / `#[br(assert(<expr>, "fmt", args…))]` — a **decode-time
    /// guard**: after the field is read (and mapped), the expression (over this and
    /// earlier fields) must hold, else decode fails with `ErrorKind::Convert`. The
    /// *explicit opt-in* strictness escape hatch (same rejection family as `magic`,
    /// closed enums, and `try_map`: values unrepresentable in the domain) — the default
    /// stays permissive. Read-only: no `bw` inverse is needed, and encode is untouched.
    /// Multiple asserts run in order.
    asserts: Vec<(syn::Expr, Option<Punctuated<syn::Expr, Token![,]>>)>,
    /// `#[bw(auto_len = count(<field>))]` / `#[bw(auto_len = bytes(<field>))]` — the field is a
    /// [`WireLen<T>`](bnb::WireLen): on encode, an `Auto` value derives its length from the
    /// named sibling (element count, or encoded byte length), while a `Set(n)` writes `n`
    /// verbatim (dual-use). Decode reads it as `Set` transparently (via `WireLen`'s own
    /// `BitDecode`), so no `br` side is needed here. The same-struct counterpart to the
    /// struct-level `#[bin(auto_len(...))]` (which targets a *nested* field); same keyword.
    auto_len: Option<AutoTarget>,
}

/// The derivation target of a `#[bw(auto_len = …)]` [`WireLen`](bnb::WireLen) field — a sibling
/// field measured by element count or encoded byte length.
#[derive(Clone)]
enum AutoTarget {
    /// `count(<field>)` — the sibling's `.len()` (element count).
    Count(Ident),
    /// `bytes(<field>)` — the sibling's encoded byte length (measured by a probe encode).
    Bytes(Ident),
}

/// Parse the `count(<field>)` / `bytes(<field>)` call-expression of a `#[bw(auto_len = …)]`.
fn parse_auto_target(expr: &syn::Expr) -> syn::Result<AutoTarget> {
    let err = || {
        syn::Error::new_spanned(
            expr,
            "expected `count(<field>)` or `bytes(<field>)` naming a sibling field",
        )
    };
    let syn::Expr::Call(call) = expr else {
        return Err(err());
    };
    let syn::Expr::Path(func) = &*call.func else {
        return Err(err());
    };
    let kind = func.path.get_ident().ok_or_else(err)?;
    if call.args.len() != 1 {
        return Err(err());
    }
    let syn::Expr::Path(arg) = &call.args[0] else {
        return Err(err());
    };
    let field = arg.path.get_ident().ok_or_else(err)?.clone();
    if kind == "count" {
        Ok(AutoTarget::Count(field))
    } else if kind == "bytes" {
        Ok(AutoTarget::Bytes(field))
    } else {
        Err(err())
    }
}

/// One entry of a struct-level `#[bin(auto_len(<field>.<nested> = count|bytes(<source>), …))]`
/// directive — a cross-struct length rule: the `<nested>` [`WireLen`](bnb::WireLen) field of
/// this struct's `<field>` derives (when `Auto`) from the sibling `<source>`.
#[derive(Clone)]
struct AutoLenSpec {
    /// The immediate field holding the nested length (e.g. `header`).
    field: Ident,
    /// The nested `WireLen` field within it (e.g. `qdcount`).
    nested: Ident,
    /// `count` or `bytes`.
    kind: Ident,
    /// The sibling field measured (e.g. `questions`).
    source: Ident,
}

impl syn::parse::Parse for AutoLenSpec {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let field: Ident = input.parse()?;
        input.parse::<Token![.]>()?;
        let nested: Ident = input.parse()?;
        input.parse::<Token![=]>()?;
        let kind: Ident = input.parse()?;
        if kind != "count" && kind != "bytes" {
            return Err(syn::Error::new_spanned(
                &kind,
                "expected `count(<source>)` or `bytes(<source>)`",
            ));
        }
        let content;
        syn::parenthesized!(content in input);
        let source: Ident = content.parse()?;
        Ok(AutoLenSpec {
            field,
            nested,
            kind,
            source,
        })
    }
}

/// One `#[br(...)]` directive. A hand-rolled parser (not `parse_nested_meta`)
/// because `if` is a keyword and can't be read as a meta path ident.
enum BrDirective {
    Count(syn::Expr),
    Ctx(Vec<Ident>),
    Temp,
    If(syn::Expr),
    Map(syn::Expr),
    TryMap(syn::Expr),
    ParseWith(syn::Expr),
    PadBefore(syn::Expr),
    PadAfter(syn::Expr),
    AlignBefore,
    AlignAfter,
    RestorePosition,
    Seek(syn::Expr),
    Dbg,
    Assert(Box<syn::Expr>, Option<Punctuated<syn::Expr, Token![,]>>),
    Calc(syn::Expr),
}

impl Parse for BrDirective {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        if input.peek(Token![if]) {
            input.parse::<Token![if]>()?;
            let content;
            syn::parenthesized!(content in input);
            Ok(BrDirective::If(content.parse()?))
        } else {
            let kw: Ident = input.parse()?;
            match kw.to_string().as_str() {
                "count" => {
                    input.parse::<Token![=]>()?;
                    Ok(BrDirective::Count(input.parse()?))
                }
                "calc" => {
                    input.parse::<Token![=]>()?;
                    Ok(BrDirective::Calc(input.parse()?))
                }
                "temp" => Ok(BrDirective::Temp),
                "assert" => {
                    // `assert(<expr>)` or `assert(<expr>, "fmt", args…)` — binrw parity.
                    let content;
                    syn::parenthesized!(content in input);
                    let cond: syn::Expr = content.parse()?;
                    let msg = if content.peek(Token![,]) {
                        content.parse::<Token![,]>()?;
                        Some(Punctuated::<syn::Expr, Token![,]>::parse_terminated(
                            &content,
                        )?)
                    } else {
                        None
                    };
                    Ok(BrDirective::Assert(Box::new(cond), msg))
                }
                "ignore" => Err(syn::Error::new_spanned(
                    &kw,
                    "`ignore` marks a field as neither read nor written; write it as `#[brw(ignore)]`",
                )),
                "ctx" => {
                    let content;
                    syn::braced!(content in input);
                    let names = Punctuated::<Ident, Token![,]>::parse_terminated(&content)?;
                    Ok(BrDirective::Ctx(names.into_iter().collect()))
                }
                "map" => {
                    input.parse::<Token![=]>()?;
                    Ok(BrDirective::Map(input.parse()?))
                }
                "try_map" => {
                    input.parse::<Token![=]>()?;
                    Ok(BrDirective::TryMap(input.parse()?))
                }
                "parse_with" => {
                    input.parse::<Token![=]>()?;
                    Ok(BrDirective::ParseWith(input.parse()?))
                }
                "pad_before" => {
                    input.parse::<Token![=]>()?;
                    Ok(BrDirective::PadBefore(input.parse()?))
                }
                "pad_after" => {
                    input.parse::<Token![=]>()?;
                    Ok(BrDirective::PadAfter(input.parse()?))
                }
                "align_before" => Ok(BrDirective::AlignBefore),
                "align_after" => Ok(BrDirective::AlignAfter),
                "restore_position" => Ok(BrDirective::RestorePosition),
                "seek" => {
                    input.parse::<Token![=]>()?;
                    Ok(BrDirective::Seek(input.parse()?))
                }
                "dbg" => Ok(BrDirective::Dbg),
                _ => Err(syn::Error::new_spanned(
                    kw,
                    "unknown `#[br(...)]` directive; expected `count`, `calc`, `ctx`, `temp`, `if`, `assert(<expr>)`, `map`, `try_map`, `parse_with`, `pad_before/after`, `align_before/after`, `restore_position`, `seek = <bits>`, or `dbg`",
                )),
            }
        }
    }
}

/// Parses a field's `#[br(count = …, ctx { … }, temp, if(…))]` and `#[bw(calc = …)]`.
fn parse_field_br(f: &syn::Field) -> syn::Result<FieldBr> {
    // The codec reads/writes through a generated source `__bnb_r` and sink `__bnb_w` — names
    // hygienic enough that a user field (even one named `r` or `w`) never shadows them, so
    // no field name is reserved.
    let mut br = FieldBr::default();
    for attr in &f.attrs {
        if attr.path().is_ident("br") {
            let directives =
                attr.parse_args_with(Punctuated::<BrDirective, Token![,]>::parse_terminated)?;
            for d in directives {
                match d {
                    BrDirective::Count(e) => br.count = Some(e),
                    BrDirective::Ctx(names) => br.ctx = Some(names),
                    BrDirective::Temp => br.temp = true,
                    BrDirective::If(e) => br.cond = Some(e),
                    BrDirective::Map(e) => br.map = Some(e),
                    BrDirective::TryMap(e) => br.try_map = Some(e),
                    BrDirective::ParseWith(e) => br.parse_with = Some(e),
                    BrDirective::PadBefore(e) => br.pad_before = Some(e),
                    BrDirective::PadAfter(e) => br.pad_after = Some(e),
                    BrDirective::AlignBefore => br.align_before = true,
                    BrDirective::AlignAfter => br.align_after = true,
                    BrDirective::RestorePosition => br.restore_position = true,
                    BrDirective::Seek(e) => br.seek = Some(e),
                    BrDirective::Dbg => br.dbg = true,
                    BrDirective::Assert(cond, msg) => br.asserts.push((*cond, msg)),
                    BrDirective::Calc(e) => br.br_calc = Some(e),
                }
            }
        } else if attr.path().is_ident("bw") {
            attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("calc") {
                    br.calc = Some(meta.value()?.parse()?);
                    Ok(())
                } else if meta.path.is_ident("map") {
                    br.bw_map = Some(meta.value()?.parse()?);
                    Ok(())
                } else if meta.path.is_ident("write_with") {
                    br.write_with = Some(meta.value()?.parse()?);
                    Ok(())
                } else if meta.path.is_ident("auto_len") {
                    br.auto_len = Some(parse_auto_target(&meta.value()?.parse()?)?);
                    Ok(())
                } else {
                    Err(meta.error(
                        "unknown `#[bw(...)]` directive; expected `calc = <expr>`, `map = <f>`, `write_with = <f>`, or `auto_len = count(<field>)|bytes(<field>)`",
                    ))
                }
            })?;
        } else if attr.path().is_ident("brw") {
            attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("ignore") {
                    br.ignore = true;
                    Ok(())
                } else if meta.path.is_ident("variable") {
                    br.variable = true;
                    Ok(())
                } else if meta.path.is_ident("count_prefix") {
                    // Under `#[bin]` the desugar strips this directive before the field
                    // ever reaches this parser — so reaching it means a bare derive.
                    let _ = meta.value()?.parse::<syn::Type>()?; // consume for a clean span
                    Err(meta.error(
                        "`count_prefix` is only supported under `#[bin]` — the bare \
                         `BitDecode`/`BitEncode` derives cannot inject the length field; write \
                         the `#[br(temp)]`/`#[bw(calc = …)]`/`#[br(count = …)]` triad by hand",
                    ))
                } else {
                    Err(meta.error(
                        "unknown `#[brw(...)]` directive; expected `ignore`, `variable`, or `count_prefix = <Ty>`",
                    ))
                }
            })?;
        }
    }
    if br.map.is_some() && br.try_map.is_some() {
        return Err(syn::Error::new_spanned(
            f,
            "`#[br(map = …)]` and `#[br(try_map = …)]` are mutually exclusive",
        ));
    }
    // `#[br(calc)]` reads no wire bits and is not stored-to-wire, so it cannot combine
    // with any directive that reads, maps, positions, or writes the same field.
    if br.br_calc.is_some()
        && (br.count.is_some()
            || br.ctx.is_some()
            || br.temp
            || br.cond.is_some()
            || br.map.is_some()
            || br.try_map.is_some()
            || br.parse_with.is_some()
            || br.calc.is_some()
            || br.bw_map.is_some()
            || br.write_with.is_some()
            || br.auto_len.is_some()
            || br.ignore
            || br.seek.is_some()
            || br.restore_position)
    {
        return Err(syn::Error::new_spanned(
            f,
            "`#[br(calc = …)]` computes the field on decode and writes nothing on encode, \
             so it cannot combine with a reading, mapping, positioning, or writing directive",
        ));
    }
    Ok(br)
}

/// Whether a field is `#[br(temp)]` (read into a local, not stored). Used by the
/// `#[bin]` front-end ([`bin_inner`]) to filter the emitted struct/builder; the codec
/// generators read `temp` off the pre-parsed [`FieldBr`] instead.
fn field_is_temp(f: &syn::Field) -> bool {
    parse_field_br(f).is_ok_and(|br| br.temp)
}

/// Whether a field is `#[brw(ignore)]` (in-memory only — defaulted on read, not
/// written, zero wire bits). Read by [`field_width`], which has no parsed `br`.
fn field_is_ignore(f: &syn::Field) -> bool {
    parse_field_br(f).is_ok_and(|br| br.ignore)
}

/// Whether a field is `#[br(calc = …)]` (decode-computed, zero wire bits, not written).
/// Read by [`field_width`], which has no parsed `br`.
fn field_is_br_calc(f: &syn::Field) -> bool {
    parse_field_br(f).is_ok_and(|br| br.br_calc.is_some())
}

/// Whether a field's directives make the message variable-length / its width
/// indeterminate, so it is exempt from the alignment guard and the message never
/// implements `FixedBitLen`: a `ctx` child (not `Bits`/`FixedBitLen`), a conditional
/// `if` (present or absent), a custom codec (`map`/`try_map`/`parse_with`/`write_with`,
/// whose wire shape lives in the converter), an explicit `#[brw(variable)]` (a
/// variable-length custom-`BitDecode` field type), or a positioning directive
/// (`pad_*`/`align_*`/`seek`/`restore_position`, which shifts the cursor).
fn br_indeterminate(br: &FieldBr) -> bool {
    br.ctx.is_some()
        || br.cond.is_some()
        || br.map.is_some()
        || br.try_map.is_some()
        || br.bw_map.is_some()
        || br.parse_with.is_some()
        || br.write_with.is_some()
        || br.variable
        || br.pad_before.is_some()
        || br.pad_after.is_some()
        || br.align_before
        || br.align_after
        || br.restore_position
        || br.seek.is_some()
}

/// A reserved field — a normal stored field with a known **spec value** (the type's
/// zero, or the `reserved_with` expression). On the default codec path it reads/writes
/// like any field (so you observe and can override the actual wire bits); the canonical
/// encoder and the builder default use the spec value instead.
enum Reserved {
    /// `#[reserved]` — spec value is the type's zero.
    Zero,
    /// `#[reserved_with(<expr>)]` — spec value is `<expr>` (e.g. a must-be-one pattern).
    With(Box<syn::Expr>),
}

/// Parses a field's `#[reserved]` / `#[reserved_with(<expr>)]`, if present.
fn field_reserved(f: &syn::Field) -> syn::Result<Option<Reserved>> {
    for attr in &f.attrs {
        if attr.path().is_ident("reserved") {
            return Ok(Some(Reserved::Zero));
        }
        if attr.path().is_ident("reserved_with") {
            return Ok(Some(Reserved::With(Box::new(attr.parse_args()?))));
        }
    }
    Ok(None)
}

/// The spec value of a reserved field — what the canonical encoder writes and what the
/// builder defaults to: the type's zero for `#[reserved]`, the given expression for
/// `#[reserved_with(<expr>)]`. `None` if the field is not reserved. (On the verbatim
/// path a reserved field is a normal stored field; only the canonical encoder and the
/// builder default use this.)
fn reserved_spec_value(f: &syn::Field) -> syn::Result<Option<TokenStream2>> {
    let bnb = crate::bnb_path();
    let ty = &f.ty;
    Ok(field_reserved(f)?.map(|reserved| match reserved {
        Reserved::Zero => quote!(<#ty as #bnb::__private::Bits>::from_bits(0)),
        Reserved::With(expr) => {
            let expr = *expr;
            quote!({ let __r: #ty = #expr; __r })
        }
    }))
}

/// Whether a field carries `#[reserved]`/`#[reserved_with]` (a cheap attribute check).
fn field_is_reserved(f: &syn::Field) -> bool {
    f.attrs
        .iter()
        .any(|a| a.path().is_ident("reserved") || a.path().is_ident("reserved_with"))
}

/// Whether a field attribute is one `#[bin]` consumes itself (`#[nested]`/`#[br]`/
/// `#[bw]` for the codec, `#[builder]` for the builder) and must strip from the
/// struct it emits — it generates the codec and builder directly, so nothing
/// registers these as helper attributes.
fn is_codec_field_attr(a: &syn::Attribute) -> bool {
    [
        "nested",
        "br",
        "bw",
        "brw",
        "builder",
        "reserved",
        "reserved_with",
        "try_str",
    ]
    .iter()
    .any(|n| a.path().is_ident(n))
}

/// A field marked `#[try_str]` — a `Debug`-rendering hint: render this byte-buffer field as a
/// string when it is valid UTF-8, else as hex bytes (all-or-nothing; never lossy).
fn field_is_try_str(f: &syn::Field) -> bool {
    f.attrs.iter().any(|a| a.path().is_ident("try_str"))
}

/// Removes `Debug` from the struct's `#[derive(…)]` lists (keeping the other derives), so
/// `#[bin]` can emit a custom `Debug`. Returns whether `Debug` was present.
fn intercept_debug_derive(attrs: &[syn::Attribute]) -> syn::Result<(bool, Vec<syn::Attribute>)> {
    let mut had_debug = false;
    let mut out = Vec::new();
    for attr in attrs {
        if attr.path().is_ident("derive") {
            let paths =
                attr.parse_args_with(Punctuated::<syn::Path, Token![,]>::parse_terminated)?;
            let kept: Vec<_> = paths
                .into_iter()
                .filter(|p| {
                    if p.is_ident("Debug") {
                        had_debug = true;
                        false
                    } else {
                        true
                    }
                })
                .collect();
            if !kept.is_empty() {
                out.extend(syn::Attribute::parse_outer.parse2(quote!(#[derive(#(#kept),*)]))?);
            }
        } else {
            out.push(attr.clone());
        }
    }
    Ok((had_debug, out))
}

/// The per-field `.field(…)` calls for a generated `debug_struct`, wrapping `#[try_str]` fields
/// in the adaptive [`TryStr`] formatter.
fn debug_field_calls(
    idents: &[syn::Ident],
    try_str: &[syn::Ident],
    bnb: &TokenStream2,
) -> TokenStream2 {
    let calls = idents.iter().map(|id| {
        if try_str.iter().any(|t| t == id) {
            quote!(.field(::core::stringify!(#id), &#bnb::__private::TryStr(&self.#id)))
        } else {
            quote!(.field(::core::stringify!(#id), &self.#id))
        }
    });
    quote!(#(#calls)*)
}

/// A custom `Debug` for a `#[bin]` enum when any variant field is `#[try_str]`: renders those
/// fields adaptively (string-or-bytes) and the rest as the std derive would. Returns `None` when
/// no variant field is `#[try_str]` (the std `#[derive(Debug)]` is then left untouched). It
/// matches over the **stored** fields (`temp` fields are dropped from the emitted enum).
fn enum_try_str_debug(
    name: &syn::Ident,
    variants: &Punctuated<syn::Variant, Token![,]>,
    bnb: &TokenStream2,
) -> Option<TokenStream2> {
    let has_try_str = variants.iter().any(|v| {
        v.fields
            .iter()
            .any(|f| !field_is_temp(f) && field_is_try_str(f))
    });
    if !has_try_str {
        return None;
    }
    let arms = variants.iter().map(|v| {
        let vn = &v.ident;
        match &v.fields {
            Fields::Unit => quote!(Self::#vn => __f.write_str(::core::stringify!(#vn))),
            Fields::Named(named) => {
                let stored: Vec<&syn::Field> =
                    named.named.iter().filter(|f| !field_is_temp(f)).collect();
                let binds: Vec<&syn::Ident> =
                    stored.iter().filter_map(|f| f.ident.as_ref()).collect();
                let calls = stored.iter().map(|f| {
                    let id = f.ident.as_ref().unwrap();
                    if field_is_try_str(f) {
                        quote!(.field(::core::stringify!(#id), &#bnb::__private::TryStr(#id)))
                    } else {
                        quote!(.field(::core::stringify!(#id), #id))
                    }
                });
                quote!(Self::#vn { #(#binds),* } =>
                    __f.debug_struct(::core::stringify!(#vn)) #(#calls)* .finish())
            }
            Fields::Unnamed(unnamed) => {
                let stored: Vec<&syn::Field> = unnamed
                    .unnamed
                    .iter()
                    .filter(|f| !field_is_temp(f))
                    .collect();
                let binds: Vec<syn::Ident> = (0..stored.len())
                    .map(|i| quote::format_ident!("__f{i}"))
                    .collect();
                let calls = stored.iter().zip(&binds).map(|(f, b)| {
                    if field_is_try_str(f) {
                        quote!(.field(&#bnb::__private::TryStr(#b)))
                    } else {
                        quote!(.field(#b))
                    }
                });
                quote!(Self::#vn( #(#binds),* ) =>
                    __f.debug_tuple(::core::stringify!(#vn)) #(#calls)* .finish())
            }
        }
    });
    Some(quote! {
        impl ::core::fmt::Debug for #name {
            fn fmt(&self, __f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                match self {
                    #(#arms),*
                }
            }
        }
    })
}

/// The context-struct literal for a `ctx { a, b }` pass, resolving each name:
/// on encode a parent **field** becomes `name: self.name`, anything else (the
/// parent's own ctx param, already a local) stays shorthand `name`. On decode all
/// names are locals, so all stay shorthand.
fn ctx_literal(
    ctx_ty: &TokenStream2,
    names: &[Ident],
    field_set: Option<&[&Ident]>,
) -> TokenStream2 {
    let inits = names.iter().map(|n| match field_set {
        Some(fields) if fields.contains(&n) => quote!(#n: self.#n),
        _ => quote!(#n),
    });
    quote!(#ctx_ty { #(#inits),* })
}

/// The bit-width expression for a field, used by the alignment guard (and, for a
/// fixed message, the `BIT_LEN` sum): a nested message contributes its
/// `FixedBitLen::BIT_LEN`, a fixed `[u8; N]` `N * 8`, a `Bits` leaf its `BITS`, a
/// `Vec<T>` its **element** width (its alignment is the element's). Resolved by
/// the compiler (the macro never computes widths).
fn field_width(f: &syn::Field) -> TokenStream2 {
    let bnb = crate::bnb_path();
    let ty = &f.ty;
    if field_is_ignore(f) || field_is_br_calc(f) {
        return quote!(0u32); // in-memory only / decode-computed: zero wire bits
    }
    if let Some(elem) = vec_elem(f) {
        quote!(<#elem as #bnb::__private::FixedBitLen>::BIT_LEN)
    } else if let Some(len) = byte_array_len(f) {
        quote!(((#len) as u32 * 8))
    } else {
        // A leaf and a fixed message both report their width via `FixedBitLen` (leaves carry
        // the impl now: `BIT_LEN == Bits::BITS`), so no `#[nested]` is needed to size a field.
        quote!(<#ty as #bnb::__private::FixedBitLen>::BIT_LEN)
    }
}

/// Positioning statements emitted before/after a field: `align_*` skips to the next
/// byte boundary, `pad_*` skips a bit count.
fn pad_read_tokens(align: bool, pad: Option<&syn::Expr>) -> TokenStream2 {
    let bnb = crate::bnb_path();
    let align = align.then(|| quote!(#bnb::__private::align_read(__bnb_r)?;));
    let pad = pad.map(|n| quote!(#bnb::__private::skip_read(__bnb_r, #n)?;));
    quote!(#align #pad)
}

fn pad_write_tokens(align: bool, pad: Option<&syn::Expr>) -> TokenStream2 {
    let bnb = crate::bnb_path();
    let align = align.then(|| quote!(#bnb::__private::align_write(__bnb_w)?;));
    let pad = pad.map(|n| quote!(#bnb::__private::skip_write(__bnb_w, #n)?;));
    quote!(#align #pad)
}

/// The decode statement for one field — a `let #id = …;` binding, wrapped with any
/// `pad_*`/`align_*` positioning. A later `count` can name an earlier field.
fn field_read_stmt(f: &syn::Field, br: &FieldBr) -> syn::Result<TokenStream2> {
    let bnb = crate::bnb_path();
    let pre = pad_read_tokens(br.align_before, br.pad_before.as_ref());
    let post = pad_read_tokens(br.align_after, br.pad_after.as_ref());
    // `seek = <bits>`: jump to an absolute bit offset before the read (following a
    // pointer). Read-side only; emitted inside the `restore_position` wrap so the saved
    // offset is the *pre-seek* one (read at the offset, then return).
    let seek = br
        .seek
        .as_ref()
        .map(|e| quote!(#bnb::__private::Source::seek_to_bit(__bnb_r, (#e) as usize)?;));
    let mut core = field_read_core(f, br)?;
    // `dbg`: trace the field's start offset and decoded value (the field must be
    // `Debug`). Captured after any `seek`, so the offset is where the bits actually came
    // from. TRACE level under target `bnb::dbg` — enable with `RUST_LOG=bnb::dbg=trace`.
    if br.dbg {
        let id = f.ident.as_ref().expect("named field");
        core = quote! {
            let __dbg_at = #bnb::__private::Source::bit_pos(__bnb_r);
            #core
            #bnb::__private::tracing::trace!(
                target: "bnb::dbg",
                field = ::core::stringify!(#id),
                at_bit = __dbg_at,
                value = ?#id,
            );
        };
    }
    // `assert(...)`: decode-time guards, run in order after the value is bound (and
    // after any `map`, so they see the *mapped* value). Read-only — encode is untouched.
    if !br.asserts.is_empty() {
        let id = f.ident.as_ref().expect("named field");
        let checks = br.asserts.iter().map(|(cond, msg)| {
            let msg_ts = match msg {
                Some(args) => quote!(#bnb::__private::format!(#args)),
                None => quote!(#bnb::__private::String::from(::core::concat!(
                    "assertion failed: `",
                    ::core::stringify!(#cond),
                    "`"
                ))),
            };
            quote! {
                if !(#cond) {
                    return ::core::result::Result::Err(
                        #bnb::__private::BitError::convert(
                            #msg_ts,
                            #bnb::__private::Source::bit_pos(__bnb_r),
                        )
                        .in_field(::core::stringify!(#id)),
                    );
                }
            }
        });
        core = quote!(#core #(#checks)*);
    }
    let mut body = quote!(#seek #core);
    if br.restore_position {
        // Peek: save the offset (before any seek), read the field, rewind so later
        // fields re-read from where they were.
        body = quote! {
            let __pos = #bnb::__private::Source::bit_pos(__bnb_r);
            #body
            #bnb::__private::Source::seek_to_bit(__bnb_r, __pos)?;
        };
    }
    Ok(quote!(#pre #body #post))
}

/// The core decode statement (without positioning).
fn field_read_core(f: &syn::Field, br: &FieldBr) -> syn::Result<TokenStream2> {
    let bnb = crate::bnb_path();
    let id = f.ident.as_ref().expect("named field");
    let ty = &f.ty;
    // A `#[reserved]` field reads as a normal stored leaf here (so the actual wire bits
    // are observable and retained — decode is always verbatim).
    // `ignore`: in-memory only — `Default::default()` on read, no input consumed.
    if br.ignore {
        return Ok(quote!(let #id = ::core::default::Default::default();));
    }
    // `calc`: the read-side dual of `#[bw(calc)]` — bind `expr` (over earlier fields,
    // as locals) with no wire read. Pinned to the declared type so inference can't drift.
    if let Some(calc) = &br.br_calc {
        return Ok(quote!(let #id: #ty = #calc;));
    }
    // `if(<cond>)`: a conditional `Option<T>`. `cond` is over earlier fields (as
    // locals). `Some(read)` when it holds, else `None` (consuming nothing).
    if let Some(cond) = &br.cond {
        let inner = option_elem(f).ok_or_else(|| {
            syn::Error::new_spanned(f, "`#[br(if(...))]` requires an `Option<_>` field")
        })?;
        // Uniform field codec: a leaf (`uN`/bitfield/enum) and a nested message both decode
        // via `BitDecode` (leaves carry the impl now), so no `#[nested]` marker is needed.
        let read_inner = quote!(<#inner as #bnb::__private::BitDecode>::bit_decode(__bnb_r)
            .map_err(|e| e.in_field(::core::stringify!(#id)))?);
        return Ok(quote! {
            let #id = if (#cond) {
                ::core::option::Option::Some(#read_inner)
            } else {
                ::core::option::Option::None
            };
        });
    }
    // `map`/`try_map`: read the wire value (`f`'s argument type) and transform it to
    // the field type, pinned to the field's declared type.
    if let Some(map) = &br.map {
        return Ok(
            quote!(let #id: #ty = #bnb::__private::read_mapped(__bnb_r, #map)
            .map_err(|e| e.in_field(::core::stringify!(#id)))?;),
        );
    }
    if let Some(try_map) = &br.try_map {
        return Ok(
            quote!(let #id: #ty = #bnb::__private::read_try_mapped(__bnb_r, #try_map)
            .map_err(|e| e.in_field(::core::stringify!(#id)))?;),
        );
    }
    // `parse_with`: the escape hatch — a custom `f(r) -> Result<T, BitError>`.
    if let Some(f) = &br.parse_with {
        return Ok(quote!(let #id: #ty = (#f)(__bnb_r)
            .map_err(|e| e.in_field(::core::stringify!(#id)))?;));
    }
    if let Some(elem) = vec_elem(f) {
        let count = br.count.as_ref().ok_or_else(|| {
            syn::Error::new_spanned(f, "a `Vec<_>` field needs `#[br(count = <expr>)]`")
        })?;
        // Read one element into `__e`, pinning its type so inference can't drift.
        let read_elem = if let Some(names) = &br.ctx {
            let lit = ctx_literal(&ctx_struct_ty(elem)?, names, None);
            quote! {
                let __e = <#elem>::decode_with(__bnb_r, #lit)
                    .map_err(|e| e.in_field(::core::stringify!(#id)))?;
            }
        } else {
            quote! {
                let __e = <#elem as #bnb::__private::BitDecode>::bit_decode(__bnb_r)
                    .map_err(|e| e.in_field(::core::stringify!(#id)))?;
            }
        };
        // No untrusted pre-allocation: `count` is attacker-controlled, so grow the
        // Vec by pushing (bounded by the input — each element consumes ≥1 bit).
        Ok(quote! {
            let #id = {
                let __n = (#count) as usize;
                let mut __v: #bnb::__private::Vec<#elem> = #bnb::__private::Vec::new();
                for _ in 0..__n {
                    #read_elem
                    __v.push(__e);
                }
                __v
            };
        })
    } else {
        if br.count.is_some() {
            return Err(syn::Error::new_spanned(
                f,
                "`#[br(count = …)]` applies only to a `Vec<_>` field",
            ));
        }
        if let Some(names) = &br.ctx {
            let lit = ctx_literal(&ctx_struct_ty(ty)?, names, None);
            Ok(quote!(let #id = <#ty>::decode_with(__bnb_r, #lit)
                .map_err(|e| e.in_field(::core::stringify!(#id)))?;))
        } else if byte_array_len(f).is_some() {
            Ok(quote!(let #id = #bnb::__private::read_byte_array(__bnb_r)
                .map_err(|e| e.in_field(::core::stringify!(#id)))?;))
        } else {
            // Uniform codec: a leaf or a nested message both decode via `BitDecode`.
            // (`bit_decode` returns `#ty`, so a `temp` field's type is pinned without an
            // explicit annotation.)
            Ok(
                quote!(let #id = <#ty as #bnb::__private::BitDecode>::bit_decode(__bnb_r)
                .map_err(|e| e.in_field(::core::stringify!(#id)))?;),
            )
        }
    }
}

/// The encode statement for one field, wrapped with any `pad_*`/`align_*`. `Vec<T>`
/// writes every element; the count is implied by `len()` (a separate length field
/// is the user's, often `calc`'d). `field_set` is the parent's field names, for
/// resolving a `ctx { … }` pass.
fn field_write_stmt(
    f: &syn::Field,
    br: &FieldBr,
    field_set: &[&Ident],
    spec: bool,
) -> syn::Result<TokenStream2> {
    let pre = pad_write_tokens(br.align_before, br.pad_before.as_ref());
    let post = pad_write_tokens(br.align_after, br.pad_after.as_ref());
    // A `restore_position` field is a read-side peek (it overlaps later data), so it
    // is not written — the overlapping field emits those bytes.
    let core = if br.restore_position {
        quote!()
    } else {
        field_write_core(f, br, field_set, spec)?
    };
    Ok(quote!(#pre #core #post))
}

/// The core encode statement (without positioning).
fn field_write_core(
    f: &syn::Field,
    br: &FieldBr,
    field_set: &[&Ident],
    spec: bool,
) -> syn::Result<TokenStream2> {
    let bnb = crate::bnb_path();
    let id = f.ident.as_ref().expect("named field");
    let ty = &f.ty;
    // `#[reserved]` on the **canonical** path: write the spec value (type zero, or the
    // `reserved_with` expression). On the verbatim (default) path a reserved field falls
    // through and writes its stored value like any field.
    if spec {
        if let Some(value) = reserved_spec_value(f)? {
            return Ok(quote!(#bnb::__private::Sink::write(__bnb_w, #value)
                .map_err(|e| e.in_field(::core::stringify!(#id)))?;));
        }
    }
    // `ignore`: in-memory only — emit nothing.
    if br.ignore {
        return Ok(quote!());
    }
    // `#[br(calc)]`: a decode-computed field whose bits live in the raw fields it
    // derives from — it is never on the wire, so it writes nothing (both passes).
    if br.br_calc.is_some() {
        return Ok(quote!());
    }
    // `calc`: a value computed from the other fields. On the **canonical** path
    // (`spec == true`) we recompute it; on the default **verbatim** path a *stored*
    // (non-`temp`) `calc` field is written as-is — `to_bytes` never silently rewrites what
    // the caller put in the field (dual-use). A `temp` field has no stored value, so it
    // always recomputes.
    if let Some(calc) = &br.calc {
        if br.temp {
            // Not stored, so a later `#[br(ctx { … })]` pass can't resolve it via
            // `self.#id`. Bind the computed value to a **named** local (in encode-fn scope,
            // in declaration order) so the ctx pass finds it — e.g. a tag recomputed with
            // `#[bw(calc = self.body.tag())]` and handed to a `tag`-dispatched enum.
            return Ok(quote! {
                let #id: #ty = #calc;
                #bnb::__private::Sink::write(__bnb_w, #id)
                    .map_err(|e| e.in_field(::core::stringify!(#id)))?;
            });
        }
        if spec {
            // Canonical: recompute from the other fields, pinned to the declared type.
            return Ok(quote! {
                {
                    let __calc: #ty = #calc;
                    #bnb::__private::Sink::write(__bnb_w, __calc)
                        .map_err(|e| e.in_field(::core::stringify!(#id)))?;
                }
            });
        }
        // Verbatim (default): write the stored value exactly as it is.
        return Ok(quote!(#bnb::__private::Sink::write(__bnb_w, self.#id)
            .map_err(|e| e.in_field(::core::stringify!(#id)))?;));
    }
    // A `temp` field is never stored, so it cannot be written without a `calc`.
    if br.temp {
        return Err(syn::Error::new_spanned(
            f,
            "a `#[br(temp)]` field is not stored, so it needs `#[bw(calc = <expr>)]` to encode",
        ));
    }
    // `map`: write `f(&self.field)` (the wire value). A read-side `map`/`try_map`
    // needs the inverse `#[bw(map = …)]` to be encodable.
    if let Some(bw_map) = &br.bw_map {
        return Ok(
            quote!(#bnb::__private::write_mapped(__bnb_w, &self.#id, #bw_map)
            .map_err(|e| e.in_field(::core::stringify!(#id)))?;),
        );
    }
    // `write_with`: the escape hatch — a custom `f(&self.field, w) -> Result<()>`.
    if let Some(f) = &br.write_with {
        return Ok(quote!((#f)(&self.#id, __bnb_w)
            .map_err(|e| e.in_field(::core::stringify!(#id)))?;));
    }
    // `auto_len = count(x)|bytes(x)`: a `WireLen<T>` field. `Set(n)` writes `n` verbatim
    // (dual-use); `Auto` derives its length from the named sibling — the element count
    // (`count`) or the encoded byte length (`bytes`, a probe encode) — checked via
    // `CountPrefix::try_from_count` (no silent truncation). `resolve_count` folds both:
    // it fills an `Auto` with the checked length and passes a `Set` through unchanged, so
    // the resolved `WireLen` (now always `Set`) writes through its own `BitEncode`. This
    // fires on both the verbatim and canonical passes — an `Auto` has no stored scalar to
    // preserve (like a `temp` `calc`), so deriving it on the verbatim path is correct.
    if let Some(target) = &br.auto_len {
        let measure = match target {
            AutoTarget::Count(field) => quote!(self.#field.len()),
            AutoTarget::Bytes(field) => quote! {{
                // A probe encode: the byte length is independent of the writer's order.
                let mut __probe = #bnb::__private::BitWriter::new();
                #bnb::__private::BitEncode::bit_encode(&self.#field, &mut __probe)
                    .map_err(|e| e.in_field(::core::stringify!(#id)))?;
                __probe.bit_len().div_ceil(8)
            }},
        };
        // Only an `Auto` value computes the measure (a `bytes(x)` probe encode is not
        // free); a `Set(n)` override is written verbatim, skipping the measure entirely.
        return Ok(quote! {
            {
                let __resolved = match &self.#id {
                    #bnb::__private::WireLen::Set(_) => ::core::clone::Clone::clone(&self.#id),
                    #bnb::__private::WireLen::Auto => self.#id.resolve_count(#measure)
                        .map_err(|e| e.in_field(::core::stringify!(#id)))?,
                };
                <#ty as #bnb::__private::BitEncode>::bit_encode(&__resolved, __bnb_w)
                    .map_err(|e| e.in_field(::core::stringify!(#id)))?;
            }
        });
    }
    if br.map.is_some() || br.try_map.is_some() {
        return Err(syn::Error::new_spanned(
            f,
            "a `#[br(map = …)]`/`#[br(try_map = …)]` field needs the inverse `#[bw(map = <f>)]` to encode",
        ));
    }
    if br.parse_with.is_some() {
        return Err(syn::Error::new_spanned(
            f,
            "a `#[br(parse_with = …)]` field needs the inverse `#[bw(write_with = <f>)]` to encode",
        ));
    }
    // `if(...)`: a conditional `Option<T>` — write the inner value iff present (the
    // `Option` drives the write; the read-side condition is not re-evaluated).
    if br.cond.is_some() {
        let inner = option_elem(f).ok_or_else(|| {
            syn::Error::new_spanned(f, "`#[br(if(...))]` requires an `Option<_>` field")
        })?;
        let write_inner = quote!(<#inner as #bnb::__private::BitEncode>::bit_encode(__v, __bnb_w)
            .map_err(|e| e.in_field(::core::stringify!(#id)))?;);
        return Ok(quote! {
            if let ::core::option::Option::Some(__v) = &self.#id {
                #write_inner
            }
        });
    }
    if let Some(elem) = vec_elem(f) {
        let write_elem = if let Some(names) = &br.ctx {
            let elem_ctx = ctx_struct_ty(elem)?;
            let lit = ctx_literal(&elem_ctx, names, Some(field_set));
            quote!(<#elem as #bnb::EncodeWith<#elem_ctx>>::encode_with(__e, __bnb_w, #lit)
                .map_err(|e| e.in_field(::core::stringify!(#id)))?;)
        } else {
            quote!(<#elem as #bnb::__private::BitEncode>::bit_encode(__e, __bnb_w)
                .map_err(|e| e.in_field(::core::stringify!(#id)))?;)
        };
        Ok(quote! {
            for __e in &self.#id {
                #write_elem
            }
        })
    } else if let Some(names) = &br.ctx {
        let child_ctx = ctx_struct_ty(ty)?;
        let lit = ctx_literal(&child_ctx, names, Some(field_set));
        Ok(
            quote!(<#ty as #bnb::EncodeWith<#child_ctx>>::encode_with(&self.#id, __bnb_w, #lit)
            .map_err(|e| e.in_field(::core::stringify!(#id)))?;),
        )
    } else if byte_array_len(f).is_some() {
        Ok(quote!(#bnb::__private::write_byte_array(&self.#id, __bnb_w)
            .map_err(|e| e.in_field(::core::stringify!(#id)))?;))
    } else {
        // Uniform codec: a leaf or a nested message both encode via `BitEncode`.
        Ok(
            quote!(<#ty as #bnb::__private::BitEncode>::bit_encode(&self.#id, __bnb_w)
            .map_err(|e| e.in_field(::core::stringify!(#id)))?;),
        )
    }
}

/// A const-eval assertion that the struct is *not* entirely byte-aligned (the
/// bit-stream codec would otherwise be the wrong tool). Empty/opted-out → no guard.
/// A sub-byte `magic` counts as a non-byte-aligned element, so it suppresses the
/// guard just like a sub-byte field.
fn alignment_guard(fields: &FieldsNamed, allow: bool, magic: Option<&syn::Expr>) -> TokenStream2 {
    if allow || (fields.named.is_empty() && magic.is_none()) {
        return quote!();
    }
    let bnb = crate::bnb_path();
    let mut terms: Vec<TokenStream2> = fields
        .named
        .iter()
        .map(|f| {
            let w = field_width(f);
            quote!((#w % 8 == 0))
        })
        .collect();
    if let Some(m) = magic {
        terms.push(quote!((#bnb::__private::bits_of(&#m) % 8 == 0)));
    }
    quote! {
        const _: () = {
            assert!(!(true #(&& #terms)*), #BYTE_ALIGNED_MSG);
        };
    }
}

pub(crate) fn expand_decode(item: TokenStream) -> TokenStream {
    let input = parse_macro_input!(item as DeriveInput);
    match decode_inner(&input) {
        Ok(ts) => ts.into(),
        Err(e) => e.to_compile_error().into(),
    }
}

fn decode_inner(input: &DeriveInput) -> syn::Result<TokenStream2> {
    gen_decode(
        &input.ident,
        named_struct(input)?,
        &parse_bit_stream(input)?,
    )
}

/// Generates the decode side (`BitDecode` + entry points, or `decode_with` for a
/// `ctx` type) from a name + field list + parsed options. Shared by the
/// `#[derive(BitDecode)]` path and by `#[bin]` (which can pass `temp` fields not
/// present in the emitted struct).
fn gen_decode(
    name: &Ident,
    fields: &FieldsNamed,
    attrs: &BitStreamAttrs,
) -> syn::Result<TokenStream2> {
    let bnb = crate::bnb_path();
    // Parse each field's `#[br]`/`#[bw]` directives once, up front (propagating any
    // parse error immediately), then drive every decision off the parsed list — no
    // re-parsing per predicate.
    let brs: Vec<FieldBr> = fields
        .named
        .iter()
        .map(parse_field_br)
        .collect::<syn::Result<Vec<_>>>()?;
    // A `ctx`/`if`/map/positioning field anywhere makes widths/alignment
    // indeterminable: exempt from the guard and never `FixedBitLen`.
    let indeterminate = !attrs.ctx.is_empty() || brs.iter().any(br_indeterminate);
    let guard = alignment_guard(
        fields,
        attrs.allow_byte_aligned || indeterminate,
        attrs.magic.as_ref(),
    );
    let layout = layout_token(attrs);
    // `magic`: a leading constant read and verified before the fields. Its width
    // (inferred from the value's type) joins `BIT_LEN`.
    let (magic_read, magic_bits) = match &attrs.magic {
        Some(m) => (
            quote! {
                #bnb::__private::verify_magic(__bnb_r, #m).map_err(|e| e.in_field("magic"))?;
            },
            quote!(#bnb::__private::bits_of(&#m) +),
        ),
        None => (quote!(), quote!()),
    };

    // Read each field into a same-named local (declaration order), so a later
    // `count`/`ctx` directive can reference an earlier field; then build `Self`
    // from the **stored** fields only (`#[br(temp)]` reads into a local but is not
    // a struct field).
    let ids: Vec<&Ident> = fields
        .named
        .iter()
        .zip(&brs)
        .filter(|(_, br)| !br.temp)
        .map(|(f, _)| f.ident.as_ref().expect("named field"))
        .collect();
    let read_stmts = fields
        .named
        .iter()
        .zip(&brs)
        .map(|(f, br)| field_read_stmt(f, br))
        .collect::<syn::Result<Vec<_>>>()?;

    // A `ctx(...)`-declaring message takes context it can't get from the plain
    // `BitDecode` trait, so it gets inherent `decode_with`/`decode_with_exact`
    // (binding the ctx params as locals) instead — no `BitDecode`/`FixedBitLen`.
    if !attrs.ctx.is_empty() {
        let ctx_name = ctx_struct_ident(name);
        let ctx_binds = attrs.ctx.iter().map(|(n, _)| quote!(let #n = __ctx.#n;));
        return Ok(quote! {
            #guard
            impl #name {
                #[doc = "Decode from a bit source, given the context this type declares via `ctx(...)`."]
                #[allow(unused_variables)] // a ctx param may be used on only one side
                pub fn decode_with<S: #bnb::__private::Source>(
                    __bnb_r: &mut S,
                    __ctx: #ctx_name,
                ) -> ::core::result::Result<Self, #bnb::__private::BitError> {
                    #(#ctx_binds)*
                    #magic_read
                    #(#read_stmts)*
                    ::core::result::Result::Ok(Self { #(#ids),* })
                }
                #[doc = "Decode from bytes with context, requiring every whole byte consumed."]
                pub fn decode_with_exact(
                    bytes: &[u8],
                    __ctx: #ctx_name,
                ) -> ::core::result::Result<Self, #bnb::__private::BitError> {
                    #bnb::__private::decode_exact_with(bytes, #layout, |__bnb_r| Self::decode_with(__bnb_r, __ctx))
                }
            }
            // ctx Layer 2: the polymorphic companion, so generic combinators can take
            // this type via `T: DecodeWith<#ctx_name>`.
            impl #bnb::DecodeWith<#ctx_name> for #name {
                fn decode_with<S: #bnb::__private::Source>(
                    __bnb_r: &mut S,
                    args: #ctx_name,
                ) -> ::core::result::Result<Self, #bnb::__private::BitError> {
                    <#name>::decode_with(__bnb_r, args)
                }
            }
        });
    }

    // A message with a `count`-driven `Vec` (or a `ctx`/`if` field) is variable-
    // length; only a fixed one also implements `FixedBitLen` (sizes embedded regions).
    let variable = indeterminate || fields.named.iter().any(|f| vec_elem(f).is_some());
    let fixed_bit_len = if variable {
        quote!()
    } else {
        let widths = fields.named.iter().map(field_width);
        quote! {
            impl #bnb::__private::FixedBitLen for #name {
                const BIT_LEN: u32 = #magic_bits 0 #(+ #widths)*;
            }
        }
    };

    // `restore_position` seeks, so the explicit-source entry point requires a
    // [`SeekSource`]; a forward-only stream is then a compile error. Without a seek,
    // any forward `Source` (including a streaming reader) works. The slice entry
    // points (`decode`/`peek`/`decode_exact`) always go through a seekable
    // `BitReader`, so they are unaffected.
    let seeks = brs
        .iter()
        .any(|br| br.restore_position || br.seek.is_some());
    let from_bound = if seeks {
        quote!(#bnb::__private::SeekSource)
    } else {
        quote!(#bnb::__private::Source)
    };
    let from_doc = if seeks {
        "Decode one message from a **seekable** bit cursor (a `BitReader`, `BufSource`, `BitBuf`, \
         …), advancing it. This message uses a seeking directive (`restore_position`/`seek`), so a \
         forward-only stream is rejected at compile time. The byte/bit order is the cursor's — \
         build it with the message's layout, or use `decode_exact`/`decode_all`, which bake it in."
    } else {
        "Decode one message from a bit cursor (a `BitReader`, `BufSource`, `BitBuf`, a streaming \
         reader, …), advancing it. The byte/bit order is the cursor's, not the message's — for a \
         non-default (`little`/`lsb`) order build the cursor with the message's layout (e.g. \
         `BitReader::with_layout`), or use `decode_exact`/`decode_all`, which bake it in."
    };

    // There is no canonical *decode*: `decode_*` is always verbatim (it retains the wire
    // bits of reserved fields — dual-use). Canonicalization is an encode-side concern
    // (`to_canonical_bytes`) or an explicit in-memory helper.

    Ok(quote! {
        #guard
        #fixed_bit_len
        impl #bnb::BitDecode for #name {
            fn bit_decode<S: #bnb::__private::Source>(
                __bnb_r: &mut S,
            ) -> ::core::result::Result<Self, #bnb::__private::BitError> {
                #magic_read
                #(#read_stmts)*
                ::core::result::Result::Ok(Self { #(#ids),* })
            }
        }

        impl #name {
            #[doc = #from_doc]
            pub fn decode<S: #from_bound>(
                __bnb_r: &mut S,
            ) -> ::core::result::Result<Self, #bnb::__private::BitError> {
                <Self as #bnb::BitDecode>::bit_decode(__bnb_r)
            }
            #[doc = "Decode every message from `bytes` into a `Vec`, bit-aware with the message's own byte/bit order baked in. The buffer must hold whole messages (a partial tail is an error)."]
            pub fn decode_all(
                bytes: &[u8],
            ) -> ::core::result::Result<#bnb::__private::Vec<Self>, #bnb::__private::BitError> {
                #bnb::__private::decode_all(bytes, #layout)
            }
            #[doc = "A lazy iterator decoding successive messages from `bytes` (layout baked in) until it is drained, ending after the first error if one occurs."]
            pub fn decode_iter(
                bytes: &[u8],
            ) -> impl ::core::iter::Iterator<Item = ::core::result::Result<Self, #bnb::__private::BitError>> + '_ {
                #bnb::__private::decode_iter(bytes, #layout)
            }
            #[doc = "Decode one message from `bytes` without consuming the caller's buffer (tail-tolerant)."]
            pub fn peek(bytes: &[u8]) -> ::core::result::Result<Self, #bnb::__private::BitError> {
                #bnb::__private::decode_peek(bytes, #layout)
            }
            #[doc = "Decode and require every whole byte consumed (errors with `ErrorKind::TrailingBytes` otherwise)."]
            pub fn decode_exact(bytes: &[u8]) -> ::core::result::Result<Self, #bnb::__private::BitError> {
                #bnb::__private::decode_exact(bytes, #layout)
            }
        }
    })
}

/// Whether a token stream mentions any of `names` (recursing into groups). Decides whether
/// a type's generated **encode** body reads a `ctx` parameter — and so whether `ctx` is
/// decode-only for it (plain encode) or it needs `encode_with`. Scanning the emitted tokens
/// catches *every* write-side reference (`calc`/`bw(map)`/`write_with`/`reserved_with`/
/// positioning, or a `ctx { … }` forward passing a param down) with no false negatives;
/// over-detection is harmless (it would merely keep `encode_with`).
fn tokens_mention(ts: TokenStream2, names: &[&Ident]) -> bool {
    ts.into_iter().any(|tt| match tt {
        proc_macro2::TokenTree::Ident(id) => names.iter().any(|n| **n == id),
        proc_macro2::TokenTree::Group(g) => tokens_mention(g.stream(), names),
        _ => false,
    })
}

pub(crate) fn expand_encode(item: TokenStream) -> TokenStream {
    let input = parse_macro_input!(item as DeriveInput);
    match encode_inner(&input) {
        Ok(ts) => ts.into(),
        Err(e) => e.to_compile_error().into(),
    }
}

fn encode_inner(input: &DeriveInput) -> syn::Result<TokenStream2> {
    gen_encode(
        &input.ident,
        named_struct(input)?,
        &parse_bit_stream(input)?,
    )
}

/// Generates the encode side (`BitEncode` + entry points, or `encode_with` for a
/// `ctx` type). Shared by `#[derive(BitEncode)]` and `#[bin]`. `calc` fields write
/// a computed value; `temp` fields (no `self` field) are written via their `calc`.
/// [`field_write_stmt`], but for a field targeted by a struct-level `auto_len(...)` rule:
/// emit a clone-and-fill that resolves each nested `Auto` [`WireLen`](bnb::WireLen) from its
/// sibling before encoding the field. Untargeted fields fall through unchanged. The resolve
/// is mode-independent — an `Auto` has no stored scalar to preserve on the verbatim path.
fn field_write_stmt_auto(
    f: &syn::Field,
    br: &FieldBr,
    field_set: &[&Ident],
    spec: bool,
    auto_len: &[AutoLenSpec],
) -> syn::Result<TokenStream2> {
    let id = f.ident.as_ref().expect("named field");
    let targeting: Vec<&AutoLenSpec> = auto_len.iter().filter(|s| &s.field == id).collect();
    if targeting.is_empty() {
        return field_write_stmt(f, br, field_set, spec);
    }
    // An `auto_len` target is written via a clone-and-fill, which can't compose with a
    // codec-overriding directive on the same field (they'd be silently dropped, breaking the
    // encode/decode symmetry). Positioning (`pad_*`/`align_*`) is fine — it wraps the write.
    if br.calc.is_some()
        || br.bw_map.is_some()
        || br.write_with.is_some()
        || br.map.is_some()
        || br.try_map.is_some()
        || br.parse_with.is_some()
        || br.auto_len.is_some()
        || br.cond.is_some()
        || br.count.is_some()
        || br.ctx.is_some()
        || br.temp
        || br.ignore
        || br.restore_position
    {
        return Err(syn::Error::new_spanned(
            f,
            "a field targeted by `#[bin(auto_len(...))]` cannot also carry a codec directive \
             (`calc`/`map`/`write_with`/`parse_with`/`auto_len`/`if`/`count`/`ctx`/`temp`/`ignore`/\
             `restore_position`); only positioning (`pad_*`/`align_*`) may accompany it",
        ));
    }
    let bnb = crate::bnb_path();
    let ty = &f.ty;
    let fills = targeting.iter().map(|s| {
        let nested = &s.nested;
        let source = &s.source;
        let measure = if s.kind == "bytes" {
            quote! {{
                let mut __probe = #bnb::__private::BitWriter::new();
                #bnb::__private::BitEncode::bit_encode(&self.#source, &mut __probe)
                    .map_err(|e| e.in_field(::core::stringify!(#nested)))?;
                __probe.bit_len().div_ceil(8)
            }}
        } else {
            quote!(self.#source.len())
        };
        // Only an `Auto` nested value computes the measure (a `bytes` probe isn't free); a
        // `Set(n)` override is kept verbatim.
        quote! {
            if #bnb::__private::WireLen::is_auto(&__auto.#nested) {
                __auto.#nested = __auto.#nested.resolve_count(#measure)
                    .map_err(|e| e.in_field(::core::stringify!(#nested)))?;
            }
        }
    });
    // Preserve the field's positioning (the decode side applies it too — dropping it here
    // would desync the streams).
    let pre = pad_write_tokens(br.align_before, br.pad_before.as_ref());
    let post = pad_write_tokens(br.align_after, br.pad_after.as_ref());
    Ok(quote! {
        #pre
        {
            let mut __auto = ::core::clone::Clone::clone(&self.#id);
            #(#fills)*
            <#ty as #bnb::__private::BitEncode>::bit_encode(&__auto, __bnb_w)
                .map_err(|e| e.in_field(::core::stringify!(#id)))?;
        }
        #post
    })
}

fn gen_encode(
    name: &Ident,
    fields: &FieldsNamed,
    attrs: &BitStreamAttrs,
) -> syn::Result<TokenStream2> {
    let bnb = crate::bnb_path();
    // Parse each field's directives once (see `gen_decode`), then derive everything
    // from the parsed list.
    let brs: Vec<FieldBr> = fields
        .named
        .iter()
        .map(parse_field_br)
        .collect::<syn::Result<Vec<_>>>()?;
    // Validate each `auto_len(field.nested = …)` names a real, stored field of this struct —
    // a typo would otherwise vanish silently, leaving the nested `WireLen` unresolved (`Auto`)
    // and failing only at encode with an opaque error — and that no two specs target the same
    // `field.nested` path (the second would be a silent no-op, since resolving passes an
    // already-`Set` value through unchanged).
    for (i, spec) in attrs.auto_len.iter().enumerate() {
        let exists = fields
            .named
            .iter()
            .zip(&brs)
            .any(|(f, br)| !br.temp && f.ident.as_ref() == Some(&spec.field));
        if !exists {
            return Err(syn::Error::new_spanned(
                &spec.field,
                format!(
                    "`auto_len` names `{}`, which is not a stored field of this struct",
                    spec.field
                ),
            ));
        }
        if attrs.auto_len[..i]
            .iter()
            .any(|prev| prev.field == spec.field && prev.nested == spec.nested)
        {
            return Err(syn::Error::new_spanned(
                &spec.nested,
                format!(
                    "`auto_len` targets `{}.{}` more than once",
                    spec.field, spec.nested
                ),
            ));
        }
    }
    let indeterminate = !attrs.ctx.is_empty() || brs.iter().any(br_indeterminate);
    let guard = alignment_guard(
        fields,
        attrs.allow_byte_aligned || indeterminate,
        attrs.magic.as_ref(),
    );
    let layout = layout_token(attrs);
    // `magic`: emit the leading constant before the fields (matched read/write).
    let magic_write = match &attrs.magic {
        Some(m) => quote! {
            #bnb::__private::Sink::write(__bnb_w, #m).map_err(|e| e.in_field("magic"))?;
        },
        None => quote!(),
    };
    // Only stored (non-`temp`) fields exist on `self`, for `ctx { … }` resolution.
    let field_set: Vec<&Ident> = fields
        .named
        .iter()
        .zip(&brs)
        .filter(|(_, br)| !br.temp)
        .map(|(f, _)| f.ident.as_ref().expect("named field"))
        .collect();
    let writes = fields
        .named
        .iter()
        .zip(&brs)
        .map(|(f, br)| field_write_stmt_auto(f, br, &field_set, false, &attrs.auto_len))
        .collect::<syn::Result<Vec<_>>>()?;

    // `ctx` is **decode-only** by default: if the generated encode body references a ctx
    // param — a `calc`/`bw(map)`/`write_with`/`reserved_with`/positioning expr, or a
    // `ctx { … }` forward passing one down — the type gets `encode_with`/`to_bytes_with`;
    // otherwise a plain `BitEncode`/`to_bytes` (below), so encode needs no context.
    let ctx_names: Vec<&Ident> = attrs.ctx.iter().map(|(n, _)| n).collect();
    let encode_uses_ctx =
        !ctx_names.is_empty() && writes.iter().any(|w| tokens_mention(w.clone(), &ctx_names));
    if encode_uses_ctx {
        let ctx_name = ctx_struct_ident(name);
        let ctx_binds = attrs.ctx.iter().map(|(n, _)| quote!(let #n = __ctx.#n;));
        return Ok(quote! {
            #guard
            impl #name {
                #[doc = "Encode to a bit sink, given the context this type declares via `ctx(...)`."]
                #[allow(unused_variables)] // a ctx param may be used on only one side
                pub fn encode_with<K: #bnb::__private::Sink>(
                    &self,
                    __bnb_w: &mut K,
                    __ctx: #ctx_name,
                ) -> ::core::result::Result<(), #bnb::__private::BitError> {
                    #(#ctx_binds)*
                    #magic_write
                    #(#writes)*
                    ::core::result::Result::Ok(())
                }
                #[doc = "Encode to a `Vec<u8>` with context."]
                pub fn to_bytes_with(
                    &self,
                    __ctx: #ctx_name,
                ) -> ::core::result::Result<#bnb::__private::Vec<u8>, #bnb::__private::BitError> {
                    #bnb::__private::encode_to_vec_with(#layout, |__bnb_w| self.encode_with(__bnb_w, __ctx))
                }
            }
            // ctx Layer 2: the polymorphic companion (dual of `DecodeWith`).
            impl #bnb::EncodeWith<#ctx_name> for #name {
                fn encode_with<K: #bnb::__private::Sink>(
                    &self,
                    __bnb_w: &mut K,
                    args: #ctx_name,
                ) -> ::core::result::Result<(), #bnb::__private::BitError> {
                    <#name>::encode_with(self, __bnb_w, args)
                }
            }
        });
    }

    // The **canonical** encoder: reserved fields written as their spec value and `calc`
    // fields recomputed (ignoring the stored values). Generated only when it would differ
    // from the verbatim encoder — i.e. the message has a reserved field or a non-`temp`
    // `calc` field (otherwise canonical and verbatim are identical).
    let has_canonical = fields
        .named
        .iter()
        .zip(&brs)
        .any(|(f, br)| field_is_reserved(f) || (br.calc.is_some() && !br.temp));
    let (canonical_method, canonical_inherent) = if !has_canonical {
        (quote!(), quote!())
    } else {
        let writes_canonical = fields
            .named
            .iter()
            .zip(&brs)
            .map(|(f, br)| field_write_stmt_auto(f, br, &field_set, true, &attrs.auto_len))
            .collect::<syn::Result<Vec<_>>>()?;

        // In-memory canonicalization helpers (`to_canonical`/`canonical_diff`/
        // `is_canonical`). For each *stored* (non-`temp`) field the canonical value is: the
        // recomputed `calc` expr, the reserved spec value, or the field itself unchanged.
        let mut calc_precompute = Vec::new();
        let mut field_inits = Vec::new();
        let mut diff_checks = Vec::new();
        for (f, br) in fields.named.iter().zip(&brs) {
            if br.temp {
                continue; // not stored — absent from the struct
            }
            let id = f.ident.as_ref().expect("named field");
            let ty = &f.ty;
            if let Some(calc) = &br.calc {
                // Non-`temp` `calc` (temp filtered above): canonical value = recompute.
                let local = format_ident!("__canon_{}", id);
                calc_precompute.push(quote!(let #local: #ty = #calc;));
                field_inits.push(quote!(#id: #local));
                diff_checks
                    .push(quote!(if self.#id != (#calc) { __d.push(::core::stringify!(#id)); }));
            } else if let Some(spec) = reserved_spec_value(f)? {
                // Reserved: canonical value = spec value.
                field_inits.push(quote!(#id: #spec));
                diff_checks
                    .push(quote!(if self.#id != (#spec) { __d.push(::core::stringify!(#id)); }));
            } else {
                // Ordinary stored field: moved unchanged.
                field_inits.push(quote!(#id: self.#id));
            }
        }

        // Overrides `BitEncode`'s default (verbatim) `canonical_bit_encode`.
        let method = quote! {
            fn canonical_bit_encode<K: #bnb::__private::Sink>(
                &self,
                __bnb_w: &mut K,
            ) -> ::core::result::Result<(), #bnb::__private::BitError> {
                #magic_write
                #(#writes_canonical)*
                ::core::result::Result::Ok(())
            }
        };
        let inherent = quote! {
            impl #name {
                #[doc = "Encode the **canonical** form to a `Vec<u8>`: reserved fields written as their"]
                #[doc = "spec value and `calc` fields recomputed (ignoring the stored values), so the"]
                #[doc = "result is always spec-compliant. (`to_bytes` is verbatim — it writes exactly"]
                #[doc = "what is stored.) To emit this form over a `std::io::Write`, encode the"]
                #[doc = "canonical copy: `value.to_canonical().encode(&mut w)`."]
                pub fn to_canonical_bytes(&self) -> ::core::result::Result<#bnb::__private::Vec<u8>, #bnb::__private::BitError> {
                    #bnb::__private::encode_to_vec_with(
                        #layout,
                        |__bnb_w| <Self as #bnb::BitEncode>::canonical_bit_encode(self, __bnb_w),
                    )
                }

                #[doc = "The **canonical form in memory**: a copy with reserved fields set to their"]
                #[doc = "spec value and `calc` fields recomputed. `value.to_canonical().to_bytes()`"]
                #[doc = "equals `value.to_canonical_bytes()`."]
                pub fn to_canonical(self) -> Self {
                    #(#calc_precompute)*
                    Self { #(#field_inits),* }
                }

                #[doc = "The names of the stored fields whose value differs from canonical — i.e."]
                #[doc = "reserved fields not at their spec value, or `calc` fields not equal to their"]
                #[doc = "recomputed value. Empty iff `self` is already canonical."]
                pub fn canonical_diff(&self) -> #bnb::__private::Vec<&'static str> {
                    let mut __d = #bnb::__private::Vec::new();
                    #(#diff_checks)*
                    __d
                }

                #[doc = "Whether `self` is already in canonical form (no reserved/`calc` field differs)."]
                pub fn is_canonical(&self) -> bool {
                    self.canonical_diff().is_empty()
                }
            }
        };
        (method, inherent)
    };

    // A `ctx` type whose encode does *not* read context still impls `EncodeWith` (ignoring
    // the context), so a parent can forward to it uniformly whether or not it needs one.
    let encode_with_trait = if attrs.ctx.is_empty() {
        quote!()
    } else {
        let ctx_name = ctx_struct_ident(name);
        quote! {
            impl #bnb::EncodeWith<#ctx_name> for #name {
                #[allow(unused_variables)]
                fn encode_with<K: #bnb::__private::Sink>(
                    &self,
                    __bnb_w: &mut K,
                    args: #ctx_name,
                ) -> ::core::result::Result<(), #bnb::__private::BitError> {
                    <Self as #bnb::BitEncode>::bit_encode(self, __bnb_w)
                }
            }
        }
    };

    Ok(quote! {
        #guard
        impl #bnb::BitEncode for #name {
            const LAYOUT: #bnb::Layout = #layout;
            fn bit_encode<K: #bnb::__private::Sink>(
                &self,
                __bnb_w: &mut K,
            ) -> ::core::result::Result<(), #bnb::__private::BitError> {
                #magic_write
                #(#writes)*
                ::core::result::Result::Ok(())
            }
            #canonical_method
        }

        impl #name {
            #[doc = "Encode to a `Vec<u8>`, **verbatim** — exactly what's stored, never silently"]
            #[doc = "rewritten (so `decode` then `to_bytes` round-trips byte-for-byte). For the"]
            #[doc = "spec-normalized form, use `to_canonical_bytes` (generated when the message has"]
            #[doc = "a `reserved` or `calc` field). To write into an explicit bit sink (a `BitWriter`)"]
            #[doc = "or a `std::io::Write`, bring [`BitEncode`](::bnb::BitEncode) /"]
            #[doc = "[`EncodeExt`](::bnb::EncodeExt) into scope and call `.bit_encode(&mut sink)` /"]
            #[doc = "`.encode(&mut w)` (the latter is verbatim, `std` only)."]
            pub fn to_bytes(&self) -> ::core::result::Result<#bnb::__private::Vec<u8>, #bnb::__private::BitError> {
                #bnb::__private::encode_to_vec(self, #layout)
            }
        }
        #encode_with_trait
        #canonical_inherent
    })
}

// ---------------------------------------------------------------------------
// `#[bin]` — the unified codec attribute.
//
// One macro that folds codec + builder. It generates the codec **directly** from
// the full field list (shared generators: `gen_decode`/`gen_encode`, the same
// functions the bare derives call) — it does *not* lower to the derives, because
// it needs the full list (`temp` fields included) while emitting a struct without
// them. That struct ownership is also what enables field *injection*: the
// `count_prefix` desugar into the temp+calc+count triad — not possible from a
// derive, which cannot re-emit the item.
// Field directives (`#[br]`/`#[bw]`/`#[brw]`) are stripped from the emitted struct.
// ---------------------------------------------------------------------------

/// Parsed struct-level `#[bin(...)]` options.
#[derive(Default)]
struct BinArgs {
    read_only: bool,
    write_only: bool,
    no_builder: bool,
    forward_only: bool,
    lsb: bool,
    little: bool,
    magic: Option<syn::Expr>,
    ctx: Vec<(Ident, Type)>,
    /// `auto_len(<field>.<nested> = count|bytes(<source>), …)` — cross-struct
    /// [`WireLen`](bnb::WireLen) derivation: on encode, resolve each nested `Auto` length
    /// from a sibling collection (DNS `header.qdcount = count(questions)`). A `Set` value is
    /// still honored (dual-use).
    auto_len: Vec<AutoLenSpec>,
    /// `validate = <path>` — a `fn(&Self) -> Result<(), impl Display>` run by
    /// `build()` (construction soundness; the parser stays permissive). A free
    /// function, not a method, so it isn't mistaken for protocol-context validity.
    validate: Option<syn::Path>,
    /// `tag = <ctx-param>` (enum only) — the **selector**: dispatch each `#[bin(tag =
    /// <value>)]` variant on this `ctx(...)` parameter (read-only, never on the wire).
    tag: Option<Ident>,
    /// `map = |w: Wire| Self` (struct only) — the logical type's wire form is the message
    /// type `Wire`; decode reads `Wire` then maps it. The wire type is taken from the
    /// closure's annotated parameter.
    map: Option<syn::Expr>,
    /// `try_map = |w: Wire| Result<Self, E>` — the fallible form of [`map`](Self::map).
    try_map: Option<syn::Expr>,
    /// `bw_map = |s: &Self| Wire` (struct only) — the encode dual: map the logical type to
    /// its wire form, then encode that.
    bw_map: Option<syn::Expr>,
    /// `wire = WireType` (struct only) — the conversion-trait form of [`map`](Self::map):
    /// decode reads `WireType` then `Self::from(wire)` (needs `From<WireType> for Self`), encode
    /// writes `WireType::from(&self)` (needs `From<&Self> for WireType`). The transitions live in
    /// the user's `impl From` blocks (a clean home, reusable in-program).
    wire: Option<Type>,
    /// `try_wire = WireType` — the fallible form of [`wire`](Self::wire): decode is
    /// `Self::try_from(wire)` (needs `TryFrom<WireType> for Self`, `Error: Display`).
    try_wire: Option<Type>,
    /// `codec = <module>` (desugared at parse time to `<module>::parse` /
    /// `<module>::write`) or `codec(parse = <f>, write = <f>)` — a **per-type codec**:
    /// this single-field tuple struct's wire form is owned by the fn pair (the reusable
    /// dual of the per-field `parse_with`/`write_with`). Either fn may be absent under
    /// the paren form when `read_only`/`write_only` narrows the direction.
    codec_parse: Option<syn::Expr>,
    codec_write: Option<syn::Expr>,
}

impl BinArgs {
    /// Whether any wire-mapping option is set (the struct serializes via a separate wire type
    /// rather than its own fields) — either the closure form (`map`/`try_map`/`bw_map`) or the
    /// conversion-trait form (`wire`/`try_wire`).
    fn is_mapped(&self) -> bool {
        self.map.is_some()
            || self.try_map.is_some()
            || self.bw_map.is_some()
            || self.wire.is_some()
            || self.try_wire.is_some()
    }

    /// Whether a per-type codec is set (either form, either direction).
    fn has_codec(&self) -> bool {
        self.codec_parse.is_some() || self.codec_write.is_some()
    }
}

/// One `parse = <expr>` / `write = <expr>` entry inside `#[bin(codec(...))]`. The expr
/// swallows a full turbofish path (`prefixed::parse_string::<_, u16>` is one expression),
/// so the comma-separated entries split correctly.
struct CodecFn {
    name: Ident,
    expr: syn::Expr,
}

impl Parse for CodecFn {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let name: Ident = input.parse()?;
        input.parse::<Token![=]>()?;
        Ok(CodecFn {
            name,
            expr: input.parse()?,
        })
    }
}

/// Entry for `#[bin(...)]`.
pub(crate) fn expand_bin(attr: TokenStream, item: TokenStream) -> TokenStream {
    match bin_inner(attr, item) {
        Ok(ts) => ts.into(),
        Err(e) => e.to_compile_error().into(),
    }
}

fn bin_inner(attr: TokenStream, item: TokenStream) -> syn::Result<TokenStream2> {
    let mut args = BinArgs::default();
    let parser = syn::meta::parser(|meta| {
        if meta.path.is_ident("read_only") {
            args.read_only = true;
        } else if meta.path.is_ident("write_only") {
            args.write_only = true;
        } else if meta.path.is_ident("no_builder") {
            args.no_builder = true;
        } else if meta.path.is_ident("forward_only") {
            args.forward_only = true;
        } else if meta.path.is_ident("bits") {
            let v: Ident = meta.value()?.parse()?;
            match v.to_string().as_str() {
                "msb" => args.lsb = false,
                "lsb" => args.lsb = true,
                _ => return Err(meta.error("expected `msb` or `lsb`")),
            }
        } else if meta.path.is_ident("bytes") {
            let v: Ident = meta.value()?.parse()?;
            match v.to_string().as_str() {
                "big" => args.little = false,
                "little" => args.little = true,
                _ => return Err(meta.error("expected `big` or `little`")),
            }
        } else if meta.path.is_ident("big") {
            // Bare `big`/`little` is the terse `#[bin]` sugar for `bytes = big|little`.
            args.little = false;
        } else if meta.path.is_ident("little") {
            args.little = true;
        } else if meta.path.is_ident("magic") {
            args.magic = Some(meta.value()?.parse()?);
        } else if meta.path.is_ident("ctx") {
            let content;
            syn::parenthesized!(content in meta.input);
            let params = Punctuated::<CtxParam, Token![,]>::parse_terminated(&content)?;
            args.ctx = params.into_iter().map(|p| (p.name, p.ty)).collect();
        } else if meta.path.is_ident("auto_len") {
            let content;
            syn::parenthesized!(content in meta.input);
            let specs = Punctuated::<AutoLenSpec, Token![,]>::parse_terminated(&content)?;
            args.auto_len = specs.into_iter().collect();
        } else if meta.path.is_ident("validate") {
            args.validate = Some(meta.value()?.parse()?);
        } else if meta.path.is_ident("tag") {
            args.tag = Some(meta.value()?.parse()?);
        } else if meta.path.is_ident("map") {
            args.map = Some(meta.value()?.parse()?);
        } else if meta.path.is_ident("try_map") {
            args.try_map = Some(meta.value()?.parse()?);
        } else if meta.path.is_ident("bw_map") {
            args.bw_map = Some(meta.value()?.parse()?);
        } else if meta.path.is_ident("wire") {
            args.wire = Some(meta.value()?.parse()?);
        } else if meta.path.is_ident("try_wire") {
            args.try_wire = Some(meta.value()?.parse()?);
        } else if meta.path.is_ident("codec") {
            if args.has_codec() {
                return Err(meta.error("duplicate `codec`"));
            }
            if meta.input.peek(Token![=]) {
                // `codec = <module>` — shorthand for the module's `parse`/`write` pair.
                let m: syn::Path = meta.value()?.parse()?;
                args.codec_parse = Some(syn::parse_quote!(#m::parse));
                args.codec_write = Some(syn::parse_quote!(#m::write));
            } else {
                // `codec(parse = <f>, write = <f>)` — the general form (any fn names,
                // turbofish allowed); either entry may be omitted under a directional
                // struct (checked in `bin_struct_codec`).
                let content;
                syn::parenthesized!(content in meta.input);
                let fns = Punctuated::<CodecFn, Token![,]>::parse_terminated(&content)?;
                for f in fns {
                    match f.name.to_string().as_str() {
                        "parse" => {
                            if args.codec_parse.is_some() {
                                return Err(syn::Error::new_spanned(&f.name, "duplicate `parse`"));
                            }
                            args.codec_parse = Some(f.expr);
                        }
                        "write" => {
                            if args.codec_write.is_some() {
                                return Err(syn::Error::new_spanned(&f.name, "duplicate `write`"));
                            }
                            args.codec_write = Some(f.expr);
                        }
                        _ => {
                            return Err(syn::Error::new_spanned(
                                &f.name,
                                "unknown `codec(...)` entry; expected `parse = <fn>` and/or `write = <fn>`",
                            ));
                        }
                    }
                }
                if !args.has_codec() {
                    return Err(meta.error(
                        "empty `codec(...)`; expected `parse = <fn>` and/or `write = <fn>`",
                    ));
                }
            }
        } else {
            return Err(meta.error(
                "unknown `#[bin(...)]` option; expected one of: read_only, write_only, \
                 no_builder, forward_only, big, little, bytes = big|little, bits = msb|lsb, magic = <expr>, \
                 ctx(name: Ty, …), validate = <path>, tag = <ctx-param>, \
                 map/try_map = |w: Wire| …, bw_map = |s: &Self| Wire, wire/try_wire = WireType, \
                 codec = <module>, or codec(parse = <f>, write = <f>)",
            ));
        }
        Ok(())
    });
    Parser::parse(parser, attr)?;

    if args.read_only && args.write_only {
        return Err(syn::Error::new(
            ::proc_macro2::Span::call_site(),
            "`read_only` and `write_only` are mutually exclusive",
        ));
    }
    if args.has_codec() && args.is_mapped() {
        return Err(syn::Error::new(
            ::proc_macro2::Span::call_site(),
            "`codec` and struct-level wire mapping (`map`/`try_map`/`bw_map`/`wire`/`try_wire`) \
             are mutually exclusive — a codec newtype's fns own its wire form",
        ));
    }
    match syn::parse::<syn::Item>(item)? {
        syn::Item::Struct(s) => bin_struct(&args, &s),
        syn::Item::Enum(e) => {
            if args.is_mapped() {
                return Err(syn::Error::new_spanned(
                    &e.ident,
                    "struct-level wire mapping (`map`/`try_map`/`bw_map`/`wire`/`try_wire`) applies \
                     to a `#[bin]` struct, not an enum — map the enum's variant fields, or wrap \
                     the enum in a mapped struct",
                ));
            }
            if args.has_codec() {
                return Err(syn::Error::new_spanned(
                    &e.ident,
                    "`codec` applies to a single-field tuple struct (a newtype), not an enum",
                ));
            }
            bin_enum(&args, &e)
        }
        other => Err(syn::Error::new_spanned(
            other,
            "#[bin] requires a struct or an enum",
        )),
    }
}

/// The wire **message** type for a mapped `#[bin]` struct: given directly by `wire`/`try_wire`,
/// or (closure form) taken from the `map`/`try_map` closure's annotated parameter, or the
/// `bw_map` closure's annotated return (write-only).
fn mapped_wire_type(args: &BinArgs) -> syn::Result<Type> {
    // Conversion-trait form: the wire type is named directly.
    if let Some(w) = args.wire.as_ref().or(args.try_wire.as_ref()) {
        return Ok(w.clone());
    }
    // Closure form: from the decode closure's annotated parameter…
    if let Some(expr) = args.map.as_ref().or(args.try_map.as_ref()) {
        if let syn::Expr::Closure(c) = expr {
            return match c.inputs.first() {
                Some(syn::Pat::Type(pt)) => Ok((*pt.ty).clone()),
                _ => Err(syn::Error::new_spanned(
                    expr,
                    "the `map`/`try_map` closure must annotate its wire-type parameter, \
                     e.g. `map = |w: WireType| …`",
                )),
            };
        }
        return Err(syn::Error::new_spanned(
            expr,
            "struct-level `map`/`try_map` must be a closure, e.g. `map = |w: WireType| Self::from(w)`",
        ));
    }
    // …or (write-only) the encode closure's annotated return.
    let expr = args
        .bw_map
        .as_ref()
        .expect("a mapped struct sets at least one mapping option");
    if let syn::Expr::Closure(c) = expr {
        if let syn::ReturnType::Type(_, ty) = &c.output {
            return Ok((**ty).clone());
        }
        return Err(syn::Error::new_spanned(
            expr,
            "a write-only mapped struct needs the wire type: annotate the `bw_map` return, \
             e.g. `bw_map = |s: &Self| -> WireType { … }`",
        ));
    }
    Err(syn::Error::new_spanned(
        expr,
        "struct-level `bw_map` must be a closure",
    ))
}

/// The **mapped** `#[bin]` struct path: the logical type's wire form is another message type
/// `Wire`, bridged either by closures (`map`/`try_map` decode, `bw_map` encode) or by the
/// conversion traits (`wire`/`try_wire`: `From`/`TryFrom<Wire>` decode + `From<&Self>` encode).
/// Bypasses the field codec — the struct's own fields are the *logical* data, never the wire.
/// Because the generated `BitDecode`/`BitEncode` carry the mapping, the ordinary slice helpers
/// (`decode_all`/`peek`/…) work at the wire type's layout. It does **not** emit `FixedBitLen`
/// (so the wire type may be variable-length); add `impl FixedBitLen` by hand to nest a
/// fixed-wire mapped type as a plain field.
fn bin_struct_mapped(args: &BinArgs, s: &ItemStruct) -> syn::Result<TokenStream2> {
    let bnb = crate::bnb_path();
    let name = &s.ident;
    let vis = &s.vis;

    let from_form = args.wire.is_some() || args.try_wire.is_some();
    let closure_form = args.map.is_some() || args.try_map.is_some() || args.bw_map.is_some();
    if from_form && closure_form {
        return Err(syn::Error::new_spanned(
            name,
            "`wire`/`try_wire` (conversion-trait mapping) can't be combined with \
             `map`/`try_map`/`bw_map` (closure mapping) — pick one form",
        ));
    }
    if args.wire.is_some() && args.try_wire.is_some() {
        return Err(syn::Error::new_spanned(
            name,
            "`wire` and `try_wire` are mutually exclusive",
        ));
    }
    if args.map.is_some() && args.try_map.is_some() {
        return Err(syn::Error::new_spanned(
            name,
            "`map` and `try_map` are mutually exclusive",
        ));
    }
    if !s.generics.params.is_empty() {
        return Err(syn::Error::new_spanned(
            &s.generics,
            "#[bin] does not support generic parameters yet",
        ));
    }
    for (opt, present) in [
        ("magic", args.magic.is_some()),
        ("ctx", !args.ctx.is_empty()),
        ("validate", args.validate.is_some()),
        ("tag", args.tag.is_some()),
    ] {
        if present {
            return Err(syn::Error::new_spanned(
                name,
                format!(
                    "`{opt}` is not supported on a mapped `#[bin]` struct — put it on the wire \
                     type instead (the wire type owns the framing)"
                ),
            ));
        }
    }
    // Directions: the `wire`/`try_wire` form is bidirectional unless `read_only`/`write_only`
    // narrows it; the closure form is driven by which closures are present.
    let (has_decode, has_encode) = if from_form {
        (!args.write_only, !args.read_only)
    } else {
        (
            args.map.is_some() || args.try_map.is_some(),
            args.bw_map.is_some(),
        )
    };
    if !from_form {
        if args.read_only && has_encode {
            return Err(syn::Error::new_spanned(
                name,
                "`read_only` conflicts with `bw_map` (drop one)",
            ));
        }
        if args.write_only && has_decode {
            return Err(syn::Error::new_spanned(
                name,
                "`write_only` conflicts with `map`/`try_map` (drop one)",
            ));
        }
    }

    let wire = mapped_wire_type(args)?;
    let layout = quote!(<#wire as #bnb::__private::BitEncode>::LAYOUT);

    let decode_ts = if has_decode {
        let decode_call = if from_form {
            if args.wire.is_some() {
                // decode: read the wire message, then `Self::from(wire)`.
                quote!(#bnb::__private::decode_mapped_msg(
                    __bnb_r,
                    |__w: #wire| <#name as ::core::convert::From<#wire>>::from(__w)
                ))
            } else {
                // try_wire: `Self::try_from(wire)` — a conversion error becomes a decode error.
                quote!(#bnb::__private::decode_try_mapped_msg(
                    __bnb_r,
                    |__w: #wire| <#name as ::core::convert::TryFrom<#wire>>::try_from(__w)
                ))
            }
        } else if let Some(map) = &args.map {
            quote!(#bnb::__private::decode_mapped_msg(__bnb_r, #map))
        } else {
            let tm = args.try_map.as_ref().unwrap();
            quote!(#bnb::__private::decode_try_mapped_msg(__bnb_r, #tm))
        };
        quote! {
            impl #bnb::__private::BitDecode for #name {
                fn bit_decode<__S: #bnb::__private::Source>(
                    __bnb_r: &mut __S,
                ) -> ::core::result::Result<Self, #bnb::__private::BitError> {
                    #decode_call
                }
            }

            impl #name {
                #[doc = "Decode one message from a `Source` cursor (mapping the wire type to this logical type)."]
                #vis fn decode<__S: #bnb::__private::Source>(
                    __bnb_r: &mut __S,
                ) -> ::core::result::Result<Self, #bnb::__private::BitError> {
                    <Self as #bnb::BitDecode>::bit_decode(__bnb_r)
                }
                #[doc = "Decode every message from `bytes` into a `Vec` (at the wire type's layout)."]
                #vis fn decode_all(
                    bytes: &[u8],
                ) -> ::core::result::Result<#bnb::__private::Vec<Self>, #bnb::__private::BitError> {
                    #bnb::__private::decode_all(bytes, #layout)
                }
                #[doc = "A lazy iterator decoding successive messages from `bytes`."]
                #vis fn decode_iter(
                    bytes: &[u8],
                ) -> impl ::core::iter::Iterator<Item = ::core::result::Result<Self, #bnb::__private::BitError>> + '_
                {
                    #bnb::__private::decode_iter(bytes, #layout)
                }
                #[doc = "Decode one message without consuming the buffer (tail-tolerant)."]
                #vis fn peek(bytes: &[u8]) -> ::core::result::Result<Self, #bnb::__private::BitError> {
                    #bnb::__private::decode_peek(bytes, #layout)
                }
                #[doc = "Decode and require every whole byte consumed."]
                #vis fn decode_exact(bytes: &[u8]) -> ::core::result::Result<Self, #bnb::__private::BitError> {
                    #bnb::__private::decode_exact(bytes, #layout)
                }
            }
        }
    } else {
        quote!()
    };

    let encode_ts = if has_encode {
        let encode_call = if from_form {
            // encode: map to the wire message via `WireType::from(&self)`, then write it.
            quote!(#bnb::__private::encode_mapped_msg(
                __bnb_w,
                self,
                |__v: &#name| -> #wire { ::core::convert::Into::into(__v) }
            ))
        } else {
            let bw = args.bw_map.as_ref().unwrap();
            quote!(#bnb::__private::encode_mapped_msg(__bnb_w, self, #bw))
        };
        quote! {
            impl #bnb::__private::BitEncode for #name {
                const LAYOUT: #bnb::__private::Layout = #layout;
                fn bit_encode<__K: #bnb::__private::Sink>(
                    &self,
                    __bnb_w: &mut __K,
                ) -> ::core::result::Result<(), #bnb::__private::BitError> {
                    #encode_call
                }
            }

            impl #name {
                #[doc = "Encode to a fresh `Vec` (mapping this logical type to its wire type)."]
                #vis fn to_bytes(
                    &self,
                ) -> ::core::result::Result<#bnb::__private::Vec<u8>, #bnb::__private::BitError> {
                    #bnb::__private::encode_to_vec(self, #layout)
                }
            }
        }
    } else {
        quote!()
    };

    // No `FixedBitLen` is emitted: the wire type may be variable-length (so a variable-length
    // logical format works out of the box). To nest a *fixed*-wire mapped type as a plain field,
    // add a one-line `impl FixedBitLen for Self { const BIT_LEN = <Wire as FixedBitLen>::BIT_LEN; }`.
    Ok(quote! {
        #s
        #decode_ts
        #encode_ts
    })
}

/// The **codec newtype** `#[bin]` path: a single-field tuple struct whose wire form is
/// owned by a `parse`/`write` fn pair — `#[bin(codec = <module>)]` (the module's
/// `parse`/`write`) or `#[bin(codec(parse = <f>, write = <f>))]`. The reusable
/// *per-type* dual of the per-field `parse_with`/`write_with` escape hatch: annotate
/// once, use as a plain field everywhere. Like the mapped path it emits no
/// `FixedBitLen` (a codec's wire form is assumed variable — a fixed-width codec adds
/// the one-liner by hand); embed one in an otherwise-fixed parent with
/// `#[brw(variable)]` on the field. Also emits `From<Inner> for Self` and
/// `From<Self> for Inner` (in-memory conversions, both directions regardless of
/// `read_only`/`write_only`).
fn bin_struct_codec(args: &BinArgs, s: &ItemStruct) -> syn::Result<TokenStream2> {
    let bnb = crate::bnb_path();
    let name = &s.ident;
    let vis = &s.vis;

    if !s.generics.params.is_empty() {
        return Err(syn::Error::new_spanned(
            &s.generics,
            "#[bin] does not support generic parameters yet",
        ));
    }
    // The codec fns own the framing — the whole-message options don't apply here.
    for (opt, set) in [
        ("magic", args.magic.is_some()),
        ("ctx", !args.ctx.is_empty()),
        ("validate", args.validate.is_some()),
        ("tag", args.tag.is_some()),
    ] {
        if set {
            return Err(syn::Error::new_spanned(
                &s.ident,
                format!(
                    "`{opt}` is not supported on a `#[bin(codec = …)]` newtype — the codec \
                     functions own the framing; move it into (or wrap) the codec fns, or use \
                     a full `#[bin]` struct"
                ),
            ));
        }
    }
    let inner_ty = match &s.fields {
        Fields::Unnamed(u) if u.unnamed.len() == 1 => &u.unnamed.first().expect("len checked").ty,
        _ => {
            return Err(syn::Error::new_spanned(
                &s.ident,
                "`codec` applies to a single-field tuple struct (a newtype), e.g. \
                 `#[bin(codec = bnb::codecs::leb128)] pub struct Varint(pub u64);` — for a \
                 one-off field use `#[br(parse_with = …)]`/`#[bw(write_with = …)]` instead",
            ));
        }
    };
    // Directional narrowing: an unneeded fn is silently unused (the module shorthand
    // always synthesizes both), but a *needed* one must be present.
    let (has_decode, has_encode) = (!args.write_only, !args.read_only);
    if has_decode && args.codec_parse.is_none() {
        return Err(syn::Error::new_spanned(
            &s.ident,
            "this codec has no `parse` function — add `parse = <f>` inside `codec(...)`, \
             or mark the struct `write_only`",
        ));
    }
    if has_encode && args.codec_write.is_none() {
        return Err(syn::Error::new_spanned(
            &s.ident,
            "this codec has no `write` function — add `write = <f>` inside `codec(...)`, \
             or mark the struct `read_only`",
        ));
    }

    // The newtype's own declared order backs its slice entry points (`decode_all`/
    // `to_bytes`); a *field* of this type decodes through the parent's cursor, where
    // the parent's layout governs. There is no wire type to borrow `LAYOUT` from.
    let layout = layout_token(&BitStreamAttrs {
        allow_byte_aligned: true, // inert here (no guard runs on this path)
        lsb: args.lsb,
        little: args.little,
        magic: None,
        ctx: Vec::new(),
        auto_len: Vec::new(),
    });

    let decode_ts = if has_decode {
        let parse_fn = args.codec_parse.as_ref().expect("checked above");
        quote! {
            impl #bnb::__private::BitDecode for #name {
                fn bit_decode<__S: #bnb::__private::Source>(
                    __bnb_r: &mut __S,
                ) -> ::core::result::Result<Self, #bnb::__private::BitError> {
                    // The codec fn's `BitError` passes through untouched: the *parent's*
                    // field read wraps it with `in_field` (innermost-wins), so wrapping
                    // here would steal the parent's field name.
                    ::core::result::Result::Ok(Self((#parse_fn)(__bnb_r)?))
                }
            }

            impl #name {
                #[doc = "Decode one value from a `Source` cursor (via this type's codec functions)."]
                #vis fn decode<__S: #bnb::__private::Source>(
                    __bnb_r: &mut __S,
                ) -> ::core::result::Result<Self, #bnb::__private::BitError> {
                    <Self as #bnb::BitDecode>::bit_decode(__bnb_r)
                }
                #[doc = "Decode every value from `bytes` into a `Vec` (at this type's declared layout)."]
                #vis fn decode_all(
                    bytes: &[u8],
                ) -> ::core::result::Result<#bnb::__private::Vec<Self>, #bnb::__private::BitError> {
                    #bnb::__private::decode_all(bytes, #layout)
                }
                #[doc = "A lazy iterator decoding successive values from `bytes`."]
                #vis fn decode_iter(
                    bytes: &[u8],
                ) -> impl ::core::iter::Iterator<Item = ::core::result::Result<Self, #bnb::__private::BitError>> + '_
                {
                    #bnb::__private::decode_iter(bytes, #layout)
                }
                #[doc = "Decode one value without consuming the buffer (tail-tolerant)."]
                #vis fn peek(bytes: &[u8]) -> ::core::result::Result<Self, #bnb::__private::BitError> {
                    #bnb::__private::decode_peek(bytes, #layout)
                }
                #[doc = "Decode and require every whole byte consumed."]
                #vis fn decode_exact(bytes: &[u8]) -> ::core::result::Result<Self, #bnb::__private::BitError> {
                    #bnb::__private::decode_exact(bytes, #layout)
                }
            }
        }
    } else {
        quote!()
    };

    let encode_ts = if has_encode {
        let write_fn = args.codec_write.as_ref().expect("checked above");
        quote! {
            impl #bnb::__private::BitEncode for #name {
                const LAYOUT: #bnb::__private::Layout = #layout;
                fn bit_encode<__K: #bnb::__private::Sink>(
                    &self,
                    __bnb_w: &mut __K,
                ) -> ::core::result::Result<(), #bnb::__private::BitError> {
                    (#write_fn)(&self.0, __bnb_w)
                }
            }

            impl #name {
                #[doc = "Encode to a fresh `Vec` (via this type's codec functions)."]
                #vis fn to_bytes(
                    &self,
                ) -> ::core::result::Result<#bnb::__private::Vec<u8>, #bnb::__private::BitError> {
                    #bnb::__private::encode_to_vec(self, #layout)
                }
            }
        }
    } else {
        quote!()
    };

    // In-memory conversions, both directions regardless of the wire direction. Emitted
    // in the struct's own module scope, so a private `.0` is still reachable.
    let from_ts = quote! {
        impl ::core::convert::From<#inner_ty> for #name {
            fn from(v: #inner_ty) -> Self {
                Self(v)
            }
        }
        impl ::core::convert::From<#name> for #inner_ty {
            fn from(v: #name) -> Self {
                v.0
            }
        }
    };

    // No `FixedBitLen` is emitted: a codec's wire form is assumed variable-length. A
    // fixed-width codec opts in with the one-line manual impl (same doctrine as the
    // mapped path above); a variable one embeds in a fixed parent via `#[brw(variable)]`.
    Ok(quote! {
        #s
        #decode_ts
        #encode_ts
        #from_ts
    })
}

/// One `#[brw(...)]` directive — the bidirectional attr carries only the directives
/// that genuinely act on both sides (`ignore`, `variable`, `count_prefix`).
enum BrwDirective {
    Ignore,
    Variable,
    CountPrefix(Box<syn::Type>),
}

impl Parse for BrwDirective {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let kw: Ident = input.parse()?;
        match kw.to_string().as_str() {
            "ignore" => Ok(BrwDirective::Ignore),
            "variable" => Ok(BrwDirective::Variable),
            "count_prefix" => {
                input.parse::<Token![=]>()?;
                Ok(BrwDirective::CountPrefix(Box::new(input.parse()?)))
            }
            _ => Err(syn::Error::new_spanned(
                kw,
                "unknown `#[brw(...)]` directive; expected `ignore`, `variable`, or `count_prefix = <Ty>`",
            )),
        }
    }
}

/// How the desugared `count_prefix` calc addresses the counted collection: through
/// `self.<id>` (a struct field) or the match-bound local `<id>` (an enum-variant field).
#[derive(Clone, Copy)]
enum CountPrefixSite {
    Struct,
    Variant,
}

/// Scans a field's `#[brw(...)]` attrs for `count_prefix = <Ty>`; removes the directive
/// (keeping a co-listed `ignore`, though the pair is rejected downstream) and returns the
/// prefix type. Duplicates are an error.
fn extract_count_prefix(f: &mut syn::Field) -> syn::Result<Option<syn::Type>> {
    let mut found: Option<syn::Type> = None;
    let mut rebuilt: Vec<syn::Attribute> = Vec::with_capacity(f.attrs.len());
    for attr in f.attrs.drain(..) {
        if !attr.path().is_ident("brw") {
            rebuilt.push(attr);
            continue;
        }
        let directives =
            attr.parse_args_with(Punctuated::<BrwDirective, Token![,]>::parse_terminated)?;
        if !directives
            .iter()
            .any(|d| matches!(d, BrwDirective::CountPrefix(_)))
        {
            rebuilt.push(attr);
            continue;
        }
        for d in directives {
            match d {
                BrwDirective::Ignore => rebuilt.push(syn::parse_quote!(#[brw(ignore)])),
                BrwDirective::Variable => rebuilt.push(syn::parse_quote!(#[brw(variable)])),
                BrwDirective::CountPrefix(ty) => {
                    if found.is_some() {
                        return Err(syn::Error::new_spanned(&attr, "duplicate `count_prefix`"));
                    }
                    found = Some(*ty);
                }
            }
        }
    }
    f.attrs = rebuilt;
    Ok(found)
}

/// The `#[bin]` `count_prefix` desugar: `#[brw(count_prefix = <Ty>)] items: Vec<T>`
/// expands to the temp+calc+count triad —
///
/// ```text
/// #[br(temp)]
/// #[bw(calc = <checked Ty from items.len()>)]
/// __bnb_count_items: Ty,
/// #[br(count = <items count from __bnb_count_items>)]
/// items: Vec<T>,
/// ```
///
/// — so it rides the existing temp-local decode, calc write, count read, struct-emission
/// temp-drop, and builder/`new` exclusion unchanged. Both conversions are checked through
/// the runtime `CountPrefix` trait: encode never truncates (an oversized `len()` is a
/// `BitError`, not a wrapped prefix), and a `uN` prefix reads/writes its declared width.
fn desugar_count_prefix(
    bnb: &TokenStream2,
    fields: &mut Punctuated<syn::Field, Token![,]>,
    site: CountPrefixSite,
) -> syn::Result<()> {
    let existing: Vec<String> = fields
        .iter()
        .filter_map(|f| f.ident.as_ref().map(ToString::to_string))
        .collect();
    let mut out: Punctuated<syn::Field, Token![,]> = Punctuated::new();
    for mut f in core::mem::take(fields) {
        let Some(pty) = extract_count_prefix(&mut f)? else {
            out.push(f);
            continue;
        };
        if vec_elem(&f).is_none() {
            return Err(syn::Error::new_spanned(
                &f,
                "`#[brw(count_prefix = …)]` applies only to a `Vec<_>` field",
            ));
        }
        // The directive *generates* the length field and the count expression; a
        // directive that reads, stores, or replaces the same machinery conflicts.
        let br = parse_field_br(&f)?;
        if br.count.is_some()
            || br.temp
            || br.calc.is_some()
            || br.br_calc.is_some()
            || br.ignore
            || br.cond.is_some()
            || br.map.is_some()
            || br.try_map.is_some()
            || br.bw_map.is_some()
            || br.parse_with.is_some()
            || br.write_with.is_some()
        {
            return Err(syn::Error::new_spanned(
                &f,
                "`count_prefix` generates the length field and the element count itself; it \
                 can't be combined with `count`, `temp`, `calc`, `ignore`, `if`, \
                 `map`/`try_map`, or `parse_with`/`write_with` on this field",
            ));
        }
        let id = f.ident.clone().expect("checked: named fields only");
        let count_id = format_ident!("__bnb_count_{}", id, span = id.span());
        let count_name = count_id.to_string();
        if existing.contains(&count_name) {
            return Err(syn::Error::new_spanned(
                &f,
                format!(
                    "`count_prefix` on `{id}` injects a length field named `{count_id}`; \
                     rename that field"
                ),
            ));
        }
        // Encode: the prefix is derived from `len()` — checked, so an oversized
        // collection is a `BitError` pinned to the *user's* field, never a wrapped count.
        let len_expr = match site {
            CountPrefixSite::Struct => quote!(self.#id.len()),
            CountPrefixSite::Variant => quote!(#id.len()),
        };
        let calc_expr = quote! {
            <#pty as #bnb::__private::CountPrefix>::try_from_count(#len_expr)
                .map_err(|__e| #bnb::__private::BitError::from(__e)
                    .in_field(::core::stringify!(#id)))?
        };
        out.push(syn::Field::parse_named.parse2(quote! {
            #[br(temp)]
            #[bw(calc = #calc_expr)]
            #count_id: #pty
        })?);
        // Decode: a separate `#[br]` attr, so it merges with any user `#[br(ctx {…})]`.
        f.attrs.push(syn::parse_quote!(
            #[br(count = <#pty as #bnb::__private::CountPrefix>::to_count(#count_id))]
        ));
        out.push(f);
    }
    *fields = out;
    Ok(())
}

/// The `#[bin]` struct path: the codec (`BitDecode`/`BitEncode`) and the
/// required-by-default builder, folded over a named-field struct.
fn bin_struct(args: &BinArgs, s: &ItemStruct) -> syn::Result<TokenStream2> {
    let bnb = crate::bnb_path();
    if args.is_mapped() {
        return bin_struct_mapped(args, s);
    }
    if args.has_codec() {
        return bin_struct_codec(args, s);
    }
    if args.tag.is_some() {
        return Err(syn::Error::new_spanned(
            &s.ident,
            "`tag` (variant dispatch) applies to a `#[bin]` enum, not a struct",
        ));
    }
    if !s.generics.params.is_empty() {
        return Err(syn::Error::new_spanned(
            &s.generics,
            "#[bin] does not support generic parameters yet",
        ));
    }
    // Desugar `#[brw(count_prefix = <Ty>)]` into the temp+calc+count triad before any
    // generator sees the fields (a tuple struct no-ops here and errors just below).
    let mut s_desugared = s.clone();
    if let Fields::Named(named) = &mut s_desugared.fields {
        desugar_count_prefix(&bnb, &mut named.named, CountPrefixSite::Struct)?;
    }
    let s = &s_desugared;
    let full_fields = match &s.fields {
        Fields::Named(n) => n,
        _ => {
            return Err(syn::Error::new_spanned(
                &s.ident,
                "#[bin] requires a struct with named fields",
            ));
        }
    };
    // `forward_only` pins a `Source`-only bound: a seek directive is then a compile
    // error (it would need a `SeekSource`).
    if args.forward_only {
        for f in &full_fields.named {
            let Ok(br) = parse_field_br(f) else { continue };
            let seeking = if br.restore_position {
                Some("restore_position")
            } else if br.seek.is_some() {
                Some("seek = …")
            } else {
                None
            };
            if let Some(name) = seeking {
                return Err(syn::Error::new_spanned(
                    f,
                    format!(
                        "`#[br({name})]` needs to seek, but the struct is `#[bin(forward_only)]`"
                    ),
                ));
            }
        }
    }

    // `#[bin]` generates the codec **directly** from the full field list — so a
    // `#[br(temp)]` field (read into a local, not stored) can participate — while
    // the emitted struct drops it. (Unlike P2.0–P2.3, this no longer lowers to the
    // `#[derive(BitDecode/BitEncode)]` codec; those derives remain usable directly.)
    //
    // The right-tool guard is always suppressed for `#[bin]`: it is the *unified*
    // codec, so a byte-aligned message is a first-class use, not a misuse. The
    // guard stays on the bare derives as advisory steering toward `#[bin]`.
    let attrs = BitStreamAttrs {
        allow_byte_aligned: true,
        lsb: args.lsb,
        little: args.little,
        magic: args.magic.clone(),
        ctx: args.ctx.clone(),
        auto_len: args.auto_len.clone(),
    };
    // `#[try_str]` is a Debug-rendering hint: a stored byte-buffer field renders as a string
    // when it is valid UTF-8, else as hex bytes. Collect the stored (non-`temp`) ones.
    let try_str_idents: Vec<syn::Ident> = full_fields
        .named
        .iter()
        .filter(|f| field_is_try_str(f) && !field_is_temp(f))
        .filter_map(|f| f.ident.clone())
        .collect();

    let decode = if args.write_only {
        quote!()
    } else {
        gen_decode(&s.ident, full_fields, &attrs)?
    };
    let encode = if args.read_only {
        quote!()
    } else {
        gen_encode(&s.ident, full_fields, &attrs)?
    };

    // The emitted struct: drop `#[br(temp)]` fields (not stored) and strip codec-only
    // field attributes (they are not registered helper attrs here — the codec is
    // generated directly, not via the derives). A `#[reserved]` field is kept (it is a
    // normal stored field now), with its `#[reserved]`/`#[reserved_with]` attr stripped.
    let mut clean = s.clone();
    if let Fields::Named(named) = &mut clean.fields {
        named.named = named
            .named
            .iter()
            .filter(|f| !field_is_temp(f))
            .cloned()
            .map(|mut f| {
                f.attrs.retain(|a| !is_codec_field_attr(a));
                f
            })
            .collect();
    }

    // `#[try_str]` fields need adaptive Debug rendering: intercept *only* `Debug` (other
    // derives stay) and emit a custom impl over all stored fields. With no `#[derive(Debug)]`
    // there's nothing to intercept.
    let mode_extras = if !try_str_idents.is_empty() {
        let (had_debug, new_attrs) = intercept_debug_derive(&clean.attrs)?;
        if had_debug {
            clean.attrs = new_attrs;
            let name = &s.ident;
            let stored_idents: Vec<syn::Ident> = match &clean.fields {
                Fields::Named(n) => n.named.iter().filter_map(|f| f.ident.clone()).collect(),
                _ => Vec::new(),
            };
            let debug_calls = debug_field_calls(&stored_idents, &try_str_idents, &bnb);
            quote! {
                impl ::core::fmt::Debug for #name {
                    fn fmt(&self, __f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                        __f.debug_struct(::core::stringify!(#name))
                            #debug_calls
                            .finish()
                    }
                }
            }
        } else {
            quote!()
        }
    } else {
        quote!()
    };

    // The builder is generated directly from the stored fields (so it can run the
    // `validate` hook via `builder::generate`'s post_build). `temp` fields are absent;
    // a reserved field is present but optional, defaulting to its spec value.
    let builder = if args.read_only || args.no_builder {
        if args.validate.is_some() {
            return Err(syn::Error::new_spanned(
                &s.ident,
                "`validate` needs the builder; it is incompatible with `read_only`/`no_builder`",
            ));
        }
        quote!()
    } else {
        // `validate`: run the soundness check on the built value; a failure is a
        // `BuilderError::Invalid`. The parser stays permissive (decode never runs it).
        let post_build = args.validate.as_ref().map(|path| {
            quote! {
                (#path)(&__value)
                    .map_err(|__e| #bnb::BuilderError::invalid(__e.to_string()))?;
            }
        });
        let mut bfields = Vec::new();
        for f in &full_fields.named {
            if field_is_temp(f) {
                continue; // a temp field is not stored, so not a builder field
            }
            let ident = f.ident.clone().expect("named field");
            let ty = f.ty.clone();
            // A reserved field is optional, defaulting to its spec value (so the builder
            // doesn't require it, but a caller can override it). A normal field is
            // required unless it carries `#[builder(default[= …])]`.
            let mut default = match reserved_spec_value(f)? {
                Some(spec) => crate::builder::FieldDefault::DefaultExpr(syn::parse2(spec)?),
                None => crate::builder::FieldDefault::Required,
            };
            // A `#[bw(auto_len = …)]` `WireLen` field is optional too, defaulting to
            // `WireLen::auto()` — auto-derivation is the norm, so the builder omits it; a
            // deliberate override passes `WireLen::set(n)` explicitly.
            if parse_field_br(f)?.auto_len.is_some() {
                default = crate::builder::FieldDefault::DefaultExpr(
                    syn::parse_quote!(#bnb::__private::WireLen::auto()),
                );
            }
            for attr in &f.attrs {
                if let Some(d) = crate::builder::parse_builder_attr(attr)? {
                    default = d;
                }
            }
            bfields.push(crate::builder::BField { ident, ty, default });
        }
        crate::builder::generate(
            &s.ident,
            &s.vis,
            &bfields,
            crate::builder::BuildKind::Plain,
            post_build.as_ref(),
        )
    };

    // `ctx(...)`: the single front-end owns the generated `<Name>Ctx` struct.
    let ctx_struct = if args.ctx.is_empty() {
        quote!()
    } else {
        let ctx_name = ctx_struct_ident(&s.ident);
        let vis = &s.vis;
        let decls = args.ctx.iter().map(|(n, t)| {
            let doc = format!("The `{n}` context parameter.");
            quote!(#[doc = #doc] #vis #n: #t)
        });
        let params = args.ctx.iter().map(|(n, t)| quote!(#n: #t));
        let names = args.ctx.iter().map(|(n, _)| n);
        quote! {
            #[derive(Clone)]
            #[doc = "Context for the matching `#[bin(ctx(...))]` type — pass it to `decode_with`."]
            #vis struct #ctx_name { #(#decls),* }
            impl #ctx_name {
                #[doc = "Construct the context positionally, in declaration order."]
                #vis fn new(#(#params),*) -> Self {
                    Self { #(#names),* }
                }
            }
        }
    };

    // `validate = path` is also exposed as re-runnable methods: `build()` checks once at
    // construction, but the value can be mutated before sending — `validate()`/`is_valid()`
    // re-check on demand (always current, never a stale flag).
    let validate_methods = if let Some(path) = &args.validate {
        let vis = &s.vis;
        let name = &s.ident;
        quote! {
            impl #name {
                #[doc = "Re-run the `#[bin(validate = …)]` soundness check against the current value."]
                #[doc = "`build()` runs it once at construction; call this before sending if the value"]
                #[doc = "may have been mutated since. It checks **semantic** soundness — by convention"]
                #[doc = "not `calc`/`reserved` fields, which are representational (normalized by"]
                #[doc = "`to_canonical_bytes`) rather than a matter of validity."]
                #[doc = ""]
                #[doc = "# Errors"]
                #[doc = "The validator's error when the value is unsound."]
                #vis fn validate(&self) -> ::core::result::Result<(), impl ::core::fmt::Display> {
                    (#path)(self)
                }
                #[doc = "Whether the `#[bin(validate = …)]` check passes for the current value —"]
                #[doc = "computed on demand, so it never goes stale after a mutation."]
                #[must_use]
                #vis fn is_valid(&self) -> bool {
                    self.validate().is_ok()
                }
            }
        }
    } else {
        quote!()
    };

    Ok(quote! {
        #ctx_struct
        #clean
        #mode_extras
        #validate_methods
        #builder
        #decode
        #encode
    })
}

// ---------------------------------------------------------------------------
// `#[bin]` on an enum — a dispatched tagged union.
//
// A variant is selected by its on-wire `magic` (a constant read+written), by a read-only
// `tag` selector drawn from a `ctx` param (never on the wire), or a hybrid of the two;
// each variant is a mini-struct whose fields reuse the `#[br]`/`#[bw]` grammar.
// `#[catch_all]` preserves an unknown discriminant and its payload (dual-use). Decode
// reuses `field_read_stmt` (it reads into locals, so it is variant-agnostic); encode needs
// a local-based writer because the struct writer is `self.#id`-coupled.
// ---------------------------------------------------------------------------

/// The bind idents for a variant's fields — the field's own ident (named) or a
/// synthesized `__f{i}` (tuple). Empty for a unit variant.
fn variant_bind_idents(fields: &Fields) -> Vec<Ident> {
    fields
        .iter()
        .enumerate()
        .map(|(i, f)| f.ident.clone().unwrap_or_else(|| format_ident!("__f{}", i)))
        .collect()
}

/// `Name::Variant { a, b }` / `Name::Variant(a, b)` / `Name::Variant` — serves as
/// **both** the destructuring pattern (encode/`tag`) and the construction expr
/// (decode), which are syntactically identical with field-shorthand.
fn variant_path_fields(
    name: &Ident,
    vid: &Ident,
    fields: &Fields,
    idents: &[Ident],
) -> TokenStream2 {
    match fields {
        Fields::Named(_) => quote!(#name::#vid { #(#idents),* }),
        Fields::Unnamed(_) => quote!(#name::#vid( #(#idents),* )),
        Fields::Unit => quote!(#name::#vid),
    }
}

/// `ctx { … }` literal for a **variant** encode arm. A name that is a stored sibling is
/// a match-bound `&FieldTy`, so it is dereferenced (`*n`); a `temp` local or an enum
/// `ctx` parameter is already a value (`n`). (The struct dual, [`ctx_literal`], uses
/// `self.n` for stored fields instead.)
fn ctx_literal_variant(ctx_ty: &TokenStream2, names: &[Ident], stored: &[Ident]) -> TokenStream2 {
    let inits = names.iter().map(|n| {
        if stored.contains(n) {
            quote!(#n: *#n)
        } else {
            quote!(#n)
        }
    });
    quote!(#ctx_ty { #(#inits),* })
}

/// The encode statement for one variant field, addressing the **match-bound local**
/// `id` (a `&FieldTy`) rather than `self.#id`. Mirrors [`field_write_core`] for the
/// variant world: `calc`/`temp`/`ctx` resolve sibling names against `stored` (the
/// arm's bound stored fields), which a variant `ctx` literal dereferences.
fn variant_field_write(
    f: &syn::Field,
    br: &FieldBr,
    id: &Ident,
    stored: &[Ident],
) -> syn::Result<TokenStream2> {
    let bnb = crate::bnb_path();
    let ty = &f.ty;
    let pre = pad_write_tokens(br.align_before, br.pad_before.as_ref());
    let post = pad_write_tokens(br.align_after, br.pad_after.as_ref());
    // `restore_position`: a read-side peek — the overlapping field owns the bytes.
    if br.restore_position {
        return Ok(quote!(#pre #post));
    }
    // `calc`: write a computed value. A `temp` field isn't in the match pattern, so bind
    // its value to a **named** local (so a later `ctx`/field can resolve it); a non-temp
    // `calc` field is in the pattern, so use a throwaway. The expr sees stored siblings as
    // references (use `s.len()` / `*s`), like a struct `calc` sees `self.s`.
    if let Some(calc) = &br.calc {
        let core = if br.temp {
            quote! {
                let #id: #ty = #calc;
                #bnb::__private::Sink::write(__bnb_w, #id)
                    .map_err(|e| e.in_field(::core::stringify!(#id)))?;
            }
        } else {
            quote! {{
                let __v: #ty = #calc;
                #bnb::__private::Sink::write(__bnb_w, __v)
                    .map_err(|e| e.in_field(::core::stringify!(#id)))?;
            }}
        };
        return Ok(quote!(#pre #core #post));
    }
    if br.temp {
        return Err(syn::Error::new_spanned(
            f,
            "a `#[br(temp)]` variant field is not stored, so it needs `#[bw(calc = <expr>)]` to encode",
        ));
    }
    // `ctx { … }` on a single nested ctx-message (the `Vec<_>` case is handled below):
    // resolve the passed names against the arm's stored siblings (deref'd) and enum ctx
    // params / temp locals (by value).
    if let (Some(names), None) = (&br.ctx, vec_elem(f)) {
        let child_ctx = ctx_struct_ty(ty)?;
        let lit = ctx_literal_variant(&child_ctx, names, stored);
        let core = quote!(<#ty as #bnb::EncodeWith<#child_ctx>>::encode_with(#id, __bnb_w, #lit)
            .map_err(|e| e.in_field(::core::stringify!(#id)))?;);
        return Ok(quote!(#pre #core #post));
    }
    let core = if br.ignore {
        quote!()
    } else if let Some(bw_map) = &br.bw_map {
        quote!(#bnb::__private::write_mapped(__bnb_w, #id, #bw_map)
            .map_err(|e| e.in_field(::core::stringify!(#id)))?;)
    } else if let Some(wf) = &br.write_with {
        quote!((#wf)(#id, __bnb_w).map_err(|e| e.in_field(::core::stringify!(#id)))?;)
    } else if br.map.is_some() || br.try_map.is_some() {
        return Err(syn::Error::new_spanned(
            f,
            "a `#[br(map = …)]`/`#[br(try_map = …)]` variant field needs the inverse `#[bw(map = <f>)]`",
        ));
    } else if br.parse_with.is_some() {
        return Err(syn::Error::new_spanned(
            f,
            "a `#[br(parse_with = …)]` variant field needs the inverse `#[bw(write_with = <f>)]`",
        ));
    } else if br.cond.is_some() {
        let inner = option_elem(f).ok_or_else(|| {
            syn::Error::new_spanned(f, "`#[br(if(...))]` requires an `Option<_>`")
        })?;
        let write_inner = quote!(<#inner as #bnb::__private::BitEncode>::bit_encode(__v, __bnb_w)
            .map_err(|e| e.in_field(::core::stringify!(#id)))?;);
        quote!(if let ::core::option::Option::Some(__v) = #id { #write_inner })
    } else if let Some(elem) = vec_elem(f) {
        let write_elem = if let Some(names) = &br.ctx {
            let elem_ctx = ctx_struct_ty(elem)?;
            let lit = ctx_literal_variant(&elem_ctx, names, stored);
            quote!(<#elem as #bnb::EncodeWith<#elem_ctx>>::encode_with(__e, __bnb_w, #lit)
                .map_err(|e| e.in_field(::core::stringify!(#id)))?;)
        } else {
            quote!(<#elem as #bnb::__private::BitEncode>::bit_encode(__e, __bnb_w)
                .map_err(|e| e.in_field(::core::stringify!(#id)))?;)
        };
        quote!(for __e in #id { #write_elem })
    } else if byte_array_len(f).is_some() {
        quote!(#bnb::__private::write_byte_array(#id, __bnb_w)
            .map_err(|e| e.in_field(::core::stringify!(#id)))?;)
    } else {
        // Uniform codec: a leaf or a nested message both encode via `BitEncode`.
        quote!(<#ty as #bnb::__private::BitEncode>::bit_encode(#id, __bnb_w)
            .map_err(|e| e.in_field(::core::stringify!(#id)))?;)
    };
    Ok(quote!(#pre #core #post))
}

// ---------------------------------------------------------------------------
// Dispatch model for `#[bin]` enums. Two orthogonal axes:
//   * `tag`   — a read-only selector from `ctx` (never on the wire) that *picks*
//               the variant; takes priority over magic.
//   * `magic` — a wire constant (byte string or byte-aligned unsigned int literal),
//               verified on read and written on encode; the discriminant when there
//               is no tag, or a post-selection signature when there is.
// This module is the parsed+validated model; `bin_enum` (below) is wired onto it.
// ---------------------------------------------------------------------------

/// A `magic` wire constant. Restricted to **byte-oriented literals** so its on-wire
/// width is unambiguous: a byte string (`b"IHDR"`) or a width-suffixed unsigned
/// integer (`0x01u16`). Sub-byte types (`u4`) and non-literals are rejected.
enum Magic {
    /// A byte-string/byte literal — its raw bytes.
    Bytes(Vec<u8>),
    /// A byte-aligned unsigned integer literal — the expression and its byte width.
    /// `value` is boxed: `syn::Expr` is large (~240 bytes), so an unboxed variant would
    /// dominate the enum's size (`clippy::large_enum_variant`).
    Int { value: Box<syn::Expr>, width: usize },
}

/// The unsigned integer type token for a byte width (1/2/4/8/16).
fn int_type_for_width(width: usize) -> TokenStream2 {
    match width {
        1 => quote!(u8),
        2 => quote!(u16),
        4 => quote!(u32),
        8 => quote!(u64),
        16 => quote!(u128),
        _ => unreachable!("magic int width is validated to 1/2/4/8/16"),
    }
}

impl Magic {
    /// The on-wire byte length of this magic.
    fn byte_len(&self) -> usize {
        match self {
            Magic::Bytes(b) => b.len(),
            Magic::Int { width, .. } => *width,
        }
    }

    /// A coarse shape discriminator (byte-string vs integer) for "all magics in this
    /// enum read the same way" checks — two magics dispatch uniformly iff their
    /// `(kind, byte_len)` agree.
    fn kind(&self) -> u8 {
        match self {
            Magic::Bytes(_) => 0,
            Magic::Int { .. } => 1,
        }
    }

    /// The type this magic is read into: `[u8; N]` for a byte string, the unsigned
    /// integer type for an int.
    fn read_type(&self) -> TokenStream2 {
        match self {
            Magic::Bytes(b) => {
                let n = b.len();
                quote!([u8; #n])
            }
            Magic::Int { width, .. } => int_type_for_width(*width),
        }
    }

    /// A `read_type`-valued constant equal to this magic — for `==` dispatch and for
    /// writing a known variant's magic.
    fn const_expr(&self) -> TokenStream2 {
        match self {
            Magic::Bytes(b) => {
                let bytes = b.iter();
                quote!([#(#bytes),*])
            }
            Magic::Int { value, .. } => quote!(#value),
        }
    }

    /// Read this magic from `r` into the local `binding`.
    fn read_into(&self, binding: &Ident) -> TokenStream2 {
        let bnb = crate::bnb_path();
        let ty = self.read_type();
        match self {
            Magic::Bytes(_) => quote!(
                let #binding: #ty = #bnb::__private::read_byte_array(__bnb_r).map_err(|e| e.in_field("magic"))?;
            ),
            Magic::Int { .. } => quote!(
                let #binding: #ty = #bnb::__private::Source::read(__bnb_r).map_err(|e| e.in_field("magic"))?;
            ),
        }
    }

    /// Read and verify this magic, erroring on mismatch (`what` names the site).
    fn verify(&self, what: &str) -> TokenStream2 {
        let bnb = crate::bnb_path();
        let binding = format_ident!("__vm");
        let read = self.read_into(&binding);
        let expected = self.const_expr();
        let msg = format!("magic mismatch ({what})");
        quote! {
            #read
            if #binding != #expected {
                return ::core::result::Result::Err(
                    #bnb::__private::BitError::convert(
                        #bnb::__private::String::from(#msg),
                        #bnb::__private::Source::bit_pos(__bnb_r),
                    ).in_field("magic"),
                );
            }
        }
    }

    /// Write `value` (a `read_type`-typed expression) as this magic to `w`.
    fn write_value(&self, value: &TokenStream2) -> TokenStream2 {
        let bnb = crate::bnb_path();
        match self {
            Magic::Bytes(_) => quote!(
                #bnb::__private::write_byte_array(&#value, __bnb_w).map_err(|e| e.in_field("magic"))?;
            ),
            Magic::Int { .. } => quote!(
                #bnb::__private::Sink::write(__bnb_w, #value).map_err(|e| e.in_field("magic"))?;
            ),
        }
    }

    /// Write this magic's constant value to `w` (for a known variant).
    fn write_const(&self) -> TokenStream2 {
        let c = self.const_expr();
        self.write_value(&c)
    }
}

/// Parses + validates a `magic = <literal>` value into a [`Magic`].
fn parse_magic(expr: &syn::Expr) -> syn::Result<Magic> {
    if let syn::Expr::Lit(syn::ExprLit { lit, .. }) = expr {
        match lit {
            syn::Lit::ByteStr(s) => return Ok(Magic::Bytes(s.value())),
            syn::Lit::Byte(b) => return Ok(Magic::Bytes(vec![b.value()])),
            syn::Lit::Int(li) => {
                let width = match li.suffix() {
                    "u8" => 1usize,
                    "u16" => 2,
                    "u32" => 4,
                    "u64" => 8,
                    "u128" => 16,
                    "" => {
                        return Err(syn::Error::new_spanned(
                            expr,
                            "a `magic` integer needs a width suffix so its wire size is unambiguous, e.g. `0x01u16`",
                        ));
                    }
                    other => {
                        return Err(syn::Error::new_spanned(
                            expr,
                            format!(
                                "`{other}` is not a valid `magic` type; use a byte-aligned unsigned integer (u8/u16/u32/u64/u128) or a byte string"
                            ),
                        ));
                    }
                };
                return Ok(Magic::Int {
                    value: Box::new(expr.clone()),
                    width,
                });
            }
            _ => {}
        }
    }
    Err(syn::Error::new_spanned(
        expr,
        "a `magic` must be a byte string (`b\"…\"`) or a byte-aligned unsigned integer literal (`0x01u16`)",
    ))
}

/// How a single variant is selected.
#[derive(PartialEq, Eq, Debug)]
enum VariantRole {
    /// `#[bin(tag = V)]` — chosen by the selector; no wire signature.
    TagOnly,
    /// `#[bin(tag = V, magic = M)]` — chosen by the selector, then verify `M`.
    TagAndMagic,
    /// `#[bin(magic = M)]` — chosen by matching `M` on the wire.
    MagicOnly,
    /// neither tag nor magic — the typed fallback (at most one).
    Fallback,
    /// `#[catch_all]` — the raw capture (at most one).
    CatchAll,
}

/// One variant's dispatch directives.
struct VariantDispatch<'a> {
    variant: &'a syn::Variant,
    /// `#[bin(tag = V)]` — the selector value to match against.
    tag: Option<syn::Expr>,
    /// `#[bin(magic = M)]` — the wire signature.
    magic: Option<Magic>,
    catch_all: bool,
}

impl VariantDispatch<'_> {
    fn role(&self) -> VariantRole {
        if self.catch_all {
            VariantRole::CatchAll
        } else {
            match (self.tag.is_some(), self.magic.is_some()) {
                (true, true) => VariantRole::TagAndMagic,
                (true, false) => VariantRole::TagOnly,
                (false, true) => VariantRole::MagicOnly,
                (false, false) => VariantRole::Fallback,
            }
        }
    }
}

/// The uniformity of the variant magic widths — decides single-read vs peek dispatch.
#[derive(PartialEq, Eq, Debug)]
enum MagicWidth {
    /// No variant carries a magic.
    None,
    /// Every magic-bearing variant has this same byte width (single-read dispatch).
    Uniform(usize),
    /// Magics differ in width (peek-and-match dispatch — a later step).
    Mixed,
}

/// The parsed + validated dispatch plan for a `#[bin]` enum.
struct EnumDispatch<'a> {
    /// `#[bin(tag = <ctx-param>)]` — the selector for tag-variants, if any.
    selector: Option<Ident>,
    /// `#[bin(magic = <const>)]` — an optional leading prefix.
    prefix: Option<Magic>,
    variants: Vec<VariantDispatch<'a>>,
}

impl<'a> EnumDispatch<'a> {
    /// Parses every variant's dispatch directives and validates the structural rules
    /// (a tag-variant needs a declared selector; at most one `#[catch_all]`; at most
    /// one typed fallback). `selector`/`prefix` come from the enum-level `#[bin(...)]`.
    fn parse(
        e: &'a syn::ItemEnum,
        selector: Option<Ident>,
        prefix: Option<Magic>,
    ) -> syn::Result<Self> {
        let mut variants = Vec::new();
        let mut catch_alls = 0u32;
        let mut fallbacks = 0u32;
        for v in &e.variants {
            let mut tag = None;
            let mut magic = None;
            let mut catch_all = false;
            for a in &v.attrs {
                if a.path().is_ident("catch_all") {
                    catch_all = true;
                } else if a.path().is_ident("bin") {
                    a.parse_nested_meta(|m| {
                        if m.path.is_ident("tag") {
                            tag = Some(m.value()?.parse()?);
                            Ok(())
                        } else if m.path.is_ident("magic") {
                            let expr: syn::Expr = m.value()?.parse()?;
                            magic = Some(parse_magic(&expr)?);
                            Ok(())
                        } else {
                            Err(m.error(
                                "expected `tag = <value>` or `magic = <literal>` on a variant",
                            ))
                        }
                    })?;
                }
            }
            let vd = VariantDispatch {
                variant: v,
                tag,
                magic,
                catch_all,
            };
            match vd.role() {
                VariantRole::CatchAll => catch_alls += 1,
                VariantRole::Fallback => fallbacks += 1,
                VariantRole::TagOnly | VariantRole::TagAndMagic if selector.is_none() => {
                    return Err(syn::Error::new_spanned(
                        &v.ident,
                        "a variant with `tag = …` needs the enum to declare the selector via `#[bin(tag = <ctx-param>)]`",
                    ));
                }
                _ => {}
            }
            variants.push(vd);
        }
        if catch_alls > 1 {
            return Err(syn::Error::new_spanned(
                &e.ident,
                "a `#[bin]` enum may have at most one `#[catch_all]` variant",
            ));
        }
        if fallbacks > 1 {
            return Err(syn::Error::new_spanned(
                &e.ident,
                "a `#[bin]` enum may have at most one no-tag/no-magic fallback variant",
            ));
        }
        Ok(EnumDispatch {
            selector,
            prefix,
            variants,
        })
    }

    /// The width uniformity of the **dispatching** magics (magic-only variants). A magic
    /// on a tag-variant is a post-selection signature, verified per variant, so it never
    /// participates in the read-once-then-match decision this drives.
    fn magic_width(&self) -> MagicWidth {
        let mut width: Option<usize> = None;
        let mut mixed = false;
        for v in &self.variants {
            if v.role() == VariantRole::MagicOnly {
                let len = v.magic.as_ref().expect("MagicOnly has a magic").byte_len();
                match width {
                    None => width = Some(len),
                    Some(__bnb_w) if __bnb_w != len => mixed = true,
                    _ => {}
                }
            }
        }
        match (width, mixed) {
            (_, true) => MagicWidth::Mixed,
            (Some(__bnb_w), false) => MagicWidth::Uniform(__bnb_w),
            (None, false) => MagicWidth::None,
        }
    }

    /// The read type shared by all dispatching magics, if they agree on `(kind, width)`
    /// (a single-read `__m`); `None` if there are none or they disagree (peek dispatch).
    fn uniform_magic_read_type(&self) -> Option<TokenStream2> {
        let mut shape: Option<(u8, usize)> = None;
        let mut ty = None;
        for v in &self.variants {
            if v.role() == VariantRole::MagicOnly {
                let m = v.magic.as_ref().expect("MagicOnly has a magic");
                let s = (m.kind(), m.byte_len());
                match shape {
                    None => {
                        shape = Some(s);
                        ty = Some(m.read_type());
                    }
                    Some(prev) if prev != s => return None,
                    _ => {}
                }
            }
        }
        ty
    }
}

/// Field-level decode/encode for one variant: the per-field reads + the path-with-fields
/// (used as both the decode constructor and the encode pattern) + the per-field writes.
/// For a `#[catch_all]`, `catch_capture` is the discriminant expression bound into the
/// first field on read; that field is omitted from `writes` (the dispatch emits it).
/// `#[br(temp)]` fields are read but dropped from the variant (mirrors a struct).
fn variant_field_codec(
    name: &Ident,
    v: &syn::Variant,
    catch_capture: Option<&TokenStream2>,
) -> syn::Result<(Vec<TokenStream2>, TokenStream2, Vec<TokenStream2>)> {
    let vid = &v.ident;
    let idents = variant_bind_idents(&v.fields);
    let stored_idents: Vec<Ident> = v
        .fields
        .iter()
        .zip(&idents)
        .filter(|(f, _)| !field_is_temp(f))
        .map(|(_, id)| id.clone())
        .collect();
    let path = variant_path_fields(name, vid, &v.fields, &stored_idents);

    let is_catch = catch_capture.is_some();
    if is_catch && v.fields.is_empty() {
        return Err(syn::Error::new_spanned(
            vid,
            "a `#[catch_all]` variant needs a first field to hold the captured discriminant",
        ));
    }

    let mut reads = Vec::new();
    for (i, f) in v.fields.iter().enumerate() {
        let id = &idents[i];
        let br = parse_field_br(f)?;
        if is_catch && i == 0 {
            if br.temp {
                return Err(syn::Error::new_spanned(
                    f,
                    "the `#[catch_all]` first field holds the captured discriminant, so it can't be `#[br(temp)]`",
                ));
            }
            let cap = catch_capture.expect("catch capture present");
            reads.push(quote!(let #id = #cap;));
        } else {
            let mut nf = f.clone();
            nf.ident = Some(id.clone());
            reads.push(field_read_stmt(&nf, &br)?);
        }
    }

    let mut writes = Vec::new();
    for (i, f) in v.fields.iter().enumerate() {
        if is_catch && i == 0 {
            continue; // the captured discriminant — the dispatch emits it
        }
        let id = &idents[i];
        let br = parse_field_br(f)?;
        writes.push(variant_field_write(f, &br, id, &stored_idents)?);
    }

    Ok((reads, path, writes))
}

/// `CamelCase` → `snake_case`, for the generated `decode_as_<variant>` methods.
fn snake_case(ident: &Ident) -> String {
    let s = ident.to_string();
    let mut out = String::with_capacity(s.len() + 4);
    for (i, ch) in s.char_indices() {
        if ch.is_ascii_uppercase() {
            if i != 0 {
                out.push('_');
            }
            out.push(ch.to_ascii_lowercase());
        } else {
            out.push(ch);
        }
    }
    out
}

/// The `#[bin]` enum path. See the module banner above.
fn bin_enum(args: &BinArgs, e: &syn::ItemEnum) -> syn::Result<TokenStream2> {
    let bnb = crate::bnb_path();
    let name = &e.ident;
    let vis = &e.vis;
    if !e.generics.params.is_empty() {
        return Err(syn::Error::new_spanned(
            &e.generics,
            "#[bin] does not support generic parameters yet",
        ));
    }
    if args.validate.is_some() {
        return Err(syn::Error::new_spanned(
            name,
            "`validate` needs the builder; a `#[bin]` enum has none",
        ));
    }

    // Desugar `#[brw(count_prefix = <Ty>)]` in each struct-style variant before dispatch
    // parsing / codegen see the fields. Tuple variants are rejected: the injected length
    // field must be nameable, and inserting into positional binds would renumber them.
    let mut e_desugared = e.clone();
    for v in &mut e_desugared.variants {
        match &mut v.fields {
            Fields::Named(named) => {
                desugar_count_prefix(&bnb, &mut named.named, CountPrefixSite::Variant)?;
            }
            Fields::Unnamed(unnamed) => {
                for f in &mut unnamed.unnamed {
                    if extract_count_prefix(f)?.is_some() {
                        return Err(syn::Error::new_spanned(
                            &*f,
                            "`count_prefix` needs a named field (the injected length field \
                             must be nameable); use a struct-style variant",
                        ));
                    }
                }
            }
            Fields::Unit => {}
        }
    }
    let e = &e_desugared;

    // Enum-level `magic` is a leading prefix constant, verified on read / written on
    // encode before dispatch. Then parse + validate the per-variant dispatch model.
    let prefix = args.magic.as_ref().map(parse_magic).transpose()?;
    let dispatch = EnumDispatch::parse(e, args.tag.clone(), prefix)?;

    // Dispatch mode + the variants that form the "nothing matched" tail.
    let has_selector = dispatch.selector.is_some();
    let magic_dispatch = dispatch
        .variants
        .iter()
        .any(|v| v.role() == VariantRole::MagicOnly);
    let fallback_variant = dispatch
        .variants
        .iter()
        .find(|v| v.role() == VariantRole::Fallback);
    let catch_variant = dispatch
        .variants
        .iter()
        .find(|v| v.role() == VariantRole::CatchAll);

    // Hybrid (some tag variants, some magic-only): the selector picks a tag variant first,
    // then unmatched selectors fall through to magic dispatch (tag priority).
    let hybrid = has_selector && magic_dispatch;
    if !has_selector && !magic_dispatch {
        return Err(syn::Error::new_spanned(
            name,
            "a `#[bin]` enum dispatches on `tag = <ctx-param>` (variant `tag`s) or per-variant `magic`s; it has neither",
        ));
    }
    if fallback_variant.is_some() && catch_variant.is_some() {
        return Err(syn::Error::new_spanned(
            name,
            "use either a typed fallback variant (no tag/magic) or a `#[catch_all]`, not both",
        ));
    }

    // Magic dispatch reads the discriminant once and matches by `==` when the magics are
    // uniform-width and there is no typed fallback; otherwise it **peeks** the longest
    // magic, matches a prefix, and seeks past the winner — so a fallback / catch-all can
    // read the still-unconsumed bytes. The peek path needs byte-string magics (so
    // `starts_with` is well-defined) and a seekable source.
    let mixed = magic_dispatch && dispatch.magic_width() == MagicWidth::Mixed;
    let use_peek = magic_dispatch && (mixed || fallback_variant.is_some());
    if use_peek
        && dispatch.variants.iter().any(|v| {
            v.role() == VariantRole::MagicOnly
                && matches!(v.magic.as_ref().expect("magic-only"), Magic::Int { .. })
        })
    {
        return Err(syn::Error::new_spanned(
            name,
            "variable-width / fallback magic dispatch needs byte-string magics (so an unmatched discriminant can be re-read)",
        ));
    }

    // For tag dispatch: the selector ident + its `ctx` type. For magic dispatch: a
    // representative dispatching magic (drives the single-read `__m` + the catch writer).
    let selector_ty = dispatch
        .selector
        .as_ref()
        .map(|sel| {
            args.ctx
                .iter()
                .find(|(n, _)| n == sel)
                .map(|(_, t)| t.clone())
                .ok_or_else(|| {
                    syn::Error::new_spanned(
                        sel,
                        "`tag = <ctx-param>` must name a `ctx(...)` parameter",
                    )
                })
        })
        .transpose()?;
    let rep_magic = dispatch
        .variants
        .iter()
        .find_map(|v| (v.role() == VariantRole::MagicOnly).then(|| v.magic.as_ref().unwrap()));

    // The "nothing matched" tail: a typed fallback (parse the unconsumed bytes — no
    // capture), else a `#[catch_all]` capturing the read magic (`__m`, single-read), the
    // unmatched selector (`__other`, tag), or nothing (peek path — the magic stays in the
    // catch-all's own fields).
    let tail_variant = fallback_variant.or(catch_variant);
    let tail_capture: Option<TokenStream2> = if fallback_variant.is_some() {
        None
    } else if catch_variant.is_some() {
        if use_peek {
            None
        } else if magic_dispatch {
            Some(quote!(__m))
        } else {
            Some(quote!(__other))
        }
    } else {
        None
    };

    // An accessor (`tag()`/`magic()`) reports a single discriminant; that is only
    // well-defined for a uniform-width, single-kind dispatch with no typed fallback (so
    // not mixed-width, not a fallback, and not a hybrid's two discriminant kinds).
    let gen_accessor = !mixed && fallback_variant.is_none() && !hybrid;

    // Per-variant encode arms (+ accessor arms). The tail variant (typed fallback or
    // catch-all) writes no discriminant of its own, except a single-read catch-all, which
    // writes back its captured magic.
    let mut encode_arms = Vec::new();
    let mut accessor_arms = Vec::new();
    for v in &dispatch.variants {
        let is_tail = matches!(v.role(), VariantRole::Fallback | VariantRole::CatchAll);
        let cap = if is_tail { tail_capture.clone() } else { None };
        let (_, pat, writes) = variant_field_codec(name, v.variant, cap.as_ref())?;

        let write_disc = if v.role() == VariantRole::CatchAll && cap.is_some() && magic_dispatch {
            let first = &variant_bind_idents(&v.variant.fields)[0];
            match rep_magic.expect("magic dispatch").kind() {
                0 => {
                    quote!(#bnb::__private::write_byte_array(#first, __bnb_w).map_err(|e| e.in_field("magic"))?;)
                }
                _ => {
                    quote!(#bnb::__private::Sink::write(__bnb_w, *#first).map_err(|e| e.in_field("magic"))?;)
                }
            }
        } else if let Some(m) = v.magic.as_ref().filter(|_| !is_tail) {
            m.write_const()
        } else {
            quote!()
        };
        encode_arms.push(quote!(#pat => { #write_disc #(#writes)* }));

        if gen_accessor {
            let acc = if is_tail {
                let first = &variant_bind_idents(&v.variant.fields)[0];
                quote!(*#first)
            } else if magic_dispatch {
                v.magic.as_ref().expect("magic variant").const_expr()
            } else {
                let tagval = v.tag.as_ref().expect("tag variant");
                quote!(#tagval)
            };
            accessor_arms.push(quote!(#pat => #acc,));
        }
    }

    // The "nothing matched" body: the tail variant (a typed fallback parsing the
    // unconsumed bytes, or a catch-all capturing the discriminant), else — a closed set —
    // an `unrecognized discriminant` error.
    let disc_field = if magic_dispatch { "magic" } else { "tag" };
    let tail_body = if let Some(tv) = tail_variant {
        let (reads, ctor, _) = variant_field_codec(name, tv.variant, tail_capture.as_ref())?;
        quote! {{
            #(#reads)*
            ::core::result::Result::Ok(#ctor)
        }}
    } else {
        quote! {{
            ::core::result::Result::Err(#bnb::__private::BitError::convert(
                #bnb::__private::String::from(concat!("unrecognized ", stringify!(#name), " discriminant")),
                #bnb::__private::Source::bit_pos(__bnb_r),
            ).in_field(#disc_field))
        }}
    };

    // The decode dispatch. Magic: a single `__m` read + an `==` chain (uniform width, no
    // fallback), or a `peek_bytes` + `starts_with` + seek chain (variable width / fallback,
    // so the tail can re-read the unconsumed magic). Tag: a `match` on the selector. The
    // tail body is the final else.
    //
    // The magic block: a single `__m` read + `==` chain (uniform width), or a `peek_bytes`
    // + `starts_with` + seek chain (variable width / fallback), ending in the tail body.
    // Used directly for pure-magic dispatch, and as the selector `match`'s fall-through
    // under hybrid (tag takes priority, then magic).
    let magic_block = if !magic_dispatch {
        quote!()
    } else if use_peek {
        let max = dispatch
            .variants
            .iter()
            .filter(|v| v.role() == VariantRole::MagicOnly)
            .map(|v| v.magic.as_ref().unwrap().byte_len())
            .max()
            .expect("at least one magic-only variant");
        let mut chain = tail_body.clone();
        for v in dispatch.variants.iter().rev() {
            if v.role() == VariantRole::MagicOnly {
                let Magic::Bytes(bytes) = v.magic.as_ref().unwrap() else {
                    unreachable!("peek path validated to byte-string magics");
                };
                let len = bytes.len();
                let bytes = bytes.iter();
                let (reads, ctor, _) = variant_field_codec(name, v.variant, None)?;
                chain = quote! {
                    if __peek.starts_with(&[#(#bytes),*]) {
                        #bnb::__private::Source::seek_to_bit(__bnb_r, #bnb::__private::Source::bit_pos(__bnb_r) + #len * 8)?;
                        #(#reads)*
                        ::core::result::Result::Ok(#ctor)
                    } else #chain
                };
            }
        }
        quote! {
            let __peek = #bnb::__private::peek_bytes(__bnb_r, #max)?;
            #chain
        }
    } else {
        let read = rep_magic
            .expect("magic dispatch has a representative magic")
            .read_into(&format_ident!("__m"));
        let mut chain = tail_body.clone();
        for v in dispatch.variants.iter().rev() {
            if v.role() == VariantRole::MagicOnly {
                let c = v.magic.as_ref().unwrap().const_expr();
                let (reads, ctor, _) = variant_field_codec(name, v.variant, None)?;
                chain = quote! {
                    if __m == #c {
                        #(#reads)*
                        ::core::result::Result::Ok(#ctor)
                    } else #chain
                };
            }
        }
        quote!(#read #chain)
    };

    let dispatch_decode = if has_selector {
        // Tag dispatch (incl. hybrid): match the selector; an unmatched selector falls to
        // the magic block (hybrid) or the tail body (pure tag).
        let sel = dispatch
            .selector
            .as_ref()
            .expect("tag dispatch has a selector");
        let mut arms = Vec::new();
        for v in &dispatch.variants {
            if matches!(v.role(), VariantRole::TagOnly | VariantRole::TagAndMagic) {
                let tagval = v.tag.as_ref().unwrap();
                let verify = v
                    .magic
                    .as_ref()
                    .map(|m| m.verify(&v.variant.ident.to_string()));
                let (reads, ctor, _) = variant_field_codec(name, v.variant, None)?;
                arms.push(quote! {
                    #tagval => {
                        #verify
                        #(#reads)*
                        ::core::result::Result::Ok(#ctor)
                    }
                });
            }
        }
        let else_body = if magic_dispatch {
            quote!({ #magic_block })
        } else {
            tail_body.clone()
        };
        // A pure-tag catch-all captures the unmatched selector (`__other`); a hybrid reads
        // `__m` in the magic block, so the unmatched selector is unused there.
        let catch_pat = if !magic_dispatch && tail_variant.is_some() {
            quote!(__other)
        } else {
            quote!(_)
        };
        quote!(match #sel { #(#arms)* #catch_pat => #else_body })
    } else {
        magic_block
    };

    let prefix_verify = dispatch.prefix.as_ref().map(|m| m.verify("prefix"));
    let prefix_write = dispatch.prefix.as_ref().map(|m| m.write_const());

    let decode_body = quote! {
        #prefix_verify
        #dispatch_decode
    };
    let encode_body = quote! {
        #prefix_write
        match self {
            #(#encode_arms)*
        }
        ::core::result::Result::Ok(())
    };

    // The explicit source is bound on `SeekSource` when a variant field seeks
    // (`seek`/`restore_position`) or the variable-width / fallback magic path peeks; a
    // `forward_only` enum then rejects either, mirroring the struct path.
    let seeks = use_peek
        || e.variants
            .iter()
            .flat_map(|v| &v.fields)
            .any(|f| parse_field_br(f).is_ok_and(|br| br.restore_position || br.seek.is_some()));
    if args.forward_only && seeks {
        let reason = if use_peek {
            "variable-width / fallback magic dispatch peeks (it needs to seek)"
        } else {
            "a seeking variant field (`seek`/`restore_position`)"
        };
        return Err(syn::Error::new_spanned(
            name,
            format!("{reason} is incompatible with `#[bin(forward_only)]`"),
        ));
    }
    let from_bound = if seeks {
        quote!(#bnb::__private::SeekSource)
    } else {
        quote!(#bnb::__private::Source)
    };

    let attrs = BitStreamAttrs {
        allow_byte_aligned: true,
        lsb: args.lsb,
        little: args.little,
        magic: None,
        ctx: args.ctx.clone(),
        auto_len: args.auto_len.clone(),
    };
    let layout = layout_token(&attrs);
    let want_decode = !args.write_only;
    let want_encode = !args.read_only;
    let is_ctx_type = !args.ctx.is_empty();
    let ctx_binds: Vec<TokenStream2> = args
        .ctx
        .iter()
        .map(|(n, _)| quote!(let #n = __ctx.#n;))
        .collect();

    // An inherent accessor on a dispatched enum: `tag()` (the off-wire selector this value
    // dispatches as — drives a parent's `#[bw(calc = self.body.tag())]`) for tag dispatch,
    // or `magic()` (the wire signature) for magic dispatch. Omitted when there is no
    // single discriminant to report (variable-width magic, or a typed fallback).
    let accessor_fn = if !gen_accessor {
        quote!()
    } else if magic_dispatch {
        let magic_ty = dispatch
            .uniform_magic_read_type()
            .expect("uniform magic dispatch has a read type");
        quote! {
            impl #name {
                #[doc = "The wire magic this value encodes as."]
                #[allow(unused_variables)]
                pub fn magic(&self) -> #magic_ty {
                    match self {
                        #(#accessor_arms)*
                    }
                }
            }
        }
    } else {
        let sel_ty = selector_ty
            .as_ref()
            .expect("tag dispatch has a selector type");
        quote! {
            impl #name {
                #[doc = "The selector this value dispatches as (the off-wire `tag`)."]
                #[allow(unused_variables)]
                pub fn tag(&self) -> #sel_ty {
                    match self {
                        #(#accessor_arms)*
                    }
                }
            }
        }
    };

    // Decode helpers: `decode_as_<variant>` parses the bytes as one explicit variant
    // (its magic, if any, then its payload), bypassing dispatch — handy when the variant
    // is known out of band, and for tests. `decode_tagged` feeds a tag-dispatched enum
    // its selector directly. A `ctx` enum threads the context through both.
    let ctx_name = ctx_struct_ident(name);
    let mut helper_methods = Vec::new();
    for v in &dispatch.variants {
        if v.role() == VariantRole::CatchAll {
            continue; // the catch-all isn't an explicit target — use `decode`/`decode_with`
        }
        let mname = format_ident!("decode_as_{}", snake_case(&v.variant.ident));
        let (reads, ctor, _) = variant_field_codec(name, v.variant, None)?;
        let magic_verify = v
            .magic
            .as_ref()
            .map(|m| m.verify(&v.variant.ident.to_string()));
        let doc = format!(
            "Decode `bytes` as the `{}` variant — its `magic` (if any) then its payload, requiring every whole byte consumed.",
            v.variant.ident
        );
        let body = quote! {
            #prefix_verify
            #magic_verify
            #(#reads)*
            ::core::result::Result::Ok(#ctor)
        };
        if is_ctx_type {
            helper_methods.push(quote! {
                #[doc = #doc]
                #[allow(unused_variables)]
                pub fn #mname(bytes: &[u8], __ctx: #ctx_name) -> ::core::result::Result<Self, #bnb::__private::BitError> {
                    #bnb::__private::decode_exact_with(bytes, #layout, |__bnb_r| { #(#ctx_binds)* #body })
                }
            });
        } else {
            helper_methods.push(quote! {
                #[doc = #doc]
                pub fn #mname(bytes: &[u8]) -> ::core::result::Result<Self, #bnb::__private::BitError> {
                    #bnb::__private::decode_exact_with(bytes, #layout, |__bnb_r| { #body })
                }
            });
        }
    }
    // `decode_tagged(selector, bytes)` — sugar for a tag-dispatched enum whose only
    // context is the selector.
    if !magic_dispatch && want_decode && args.ctx.len() == 1 {
        let sel = dispatch
            .selector
            .as_ref()
            .expect("tag dispatch has a selector");
        let sel_ty = selector_ty
            .as_ref()
            .expect("tag dispatch has a selector type");
        helper_methods.push(quote! {
            #[doc = "Decode `bytes` with the given selector (tag), then dispatch — sugar for `decode_with_exact`."]
            pub fn decode_tagged(#sel: #sel_ty, bytes: &[u8]) -> ::core::result::Result<Self, #bnb::__private::BitError> {
                Self::decode_with_exact(bytes, #ctx_name { #sel })
            }
        });
    }
    // `peek_variant` + a `<Name>Kind` enum: identify the variant by the wire magic
    // (the dispatch decision only, no payload). Magic dispatch only — under tag dispatch
    // the caller already holds the selector.
    let kind_name = format_ident!("{}Kind", name);
    let kind_enum = if magic_dispatch && !has_selector && want_decode {
        // The "nothing matched" kind: the tail variant's kind, else an error.
        let tail_kind = tail_variant
            .map(|tv| {
                let k = &tv.variant.ident;
                quote!(::core::result::Result::Ok(#kind_name::#k))
            })
            .unwrap_or_else(|| {
                quote!(::core::result::Result::Err(
                    #bnb::__private::BitError::convert(
                        #bnb::__private::String::from(concat!(
                            "unrecognized ",
                            stringify!(#name),
                            " discriminant"
                        )),
                        #bnb::__private::Source::bit_pos(__bnb_r),
                    )
                    .in_field("magic")
                ))
            });
        let decision = if use_peek {
            let max = dispatch
                .variants
                .iter()
                .filter(|v| v.role() == VariantRole::MagicOnly)
                .map(|v| v.magic.as_ref().unwrap().byte_len())
                .max()
                .expect("at least one magic-only variant");
            let mut chain = quote!({ #tail_kind });
            for v in dispatch.variants.iter().rev() {
                if v.role() == VariantRole::MagicOnly {
                    let Magic::Bytes(bytes) = v.magic.as_ref().unwrap() else {
                        unreachable!("peek path validated to byte-string magics");
                    };
                    let bytes = bytes.iter();
                    let k = &v.variant.ident;
                    chain = quote!(if __peek.starts_with(&[#(#bytes),*]) { ::core::result::Result::Ok(#kind_name::#k) } else #chain);
                }
            }
            quote! {
                let __peek = #bnb::__private::peek_bytes(__bnb_r, #max)?;
                #chain
            }
        } else {
            let read = rep_magic
                .expect("magic dispatch has a representative magic")
                .read_into(&format_ident!("__m"));
            let mut chain = quote!({ #tail_kind });
            for v in dispatch.variants.iter().rev() {
                if v.role() == VariantRole::MagicOnly {
                    let c = v.magic.as_ref().unwrap().const_expr();
                    let k = &v.variant.ident;
                    chain = quote!(if __m == #c { ::core::result::Result::Ok(#kind_name::#k) } else #chain);
                }
            }
            quote!(#read #chain)
        };
        helper_methods.push(quote! {
            #[doc = "Identify which variant `bytes` is from the wire magic, without parsing the payload."]
            pub fn peek_variant(bytes: &[u8]) -> ::core::result::Result<#kind_name, #bnb::__private::BitError> {
                #bnb::__private::decode_peek_with(bytes, #layout, |__bnb_r| {
                    #prefix_verify
                    #decision
                })
            }
        });
        let kvars = dispatch.variants.iter().map(|v| &v.variant.ident);
        quote! {
            #[doc = "The variant kind of a value, from `peek_variant` (the dispatch decision only)."]
            #[derive(::core::clone::Clone, ::core::marker::Copy, ::core::fmt::Debug, ::core::cmp::PartialEq, ::core::cmp::Eq)]
            #vis enum #kind_name { #(#kvars),* }
        }
    } else {
        quote!()
    };
    let helpers = if helper_methods.is_empty() {
        quote!()
    } else {
        quote!(impl #name { #(#helper_methods)* })
    };

    // The codec impls. Decode: a `ctx` enum gets `decode_with` (+ `DecodeWith`); a plain
    // one gets `BitDecode` + the slice/stream entry points. Encode: `ctx` is decode-only,
    // so a `ctx` enum still gets a **plain** `BitEncode`/`to_bytes` unless its encode body
    // actually reads a ctx param (a `calc`/`bw(map)`/`ctx`-forward naming one) — then it
    // gets `encode_with`/`to_bytes_with` instead. Either way it impls `EncodeWith` so a
    // parent can forward to it.
    let ctx_param_names: Vec<&Ident> = args.ctx.iter().map(|(n, _)| n).collect();
    let enum_encode_uses_ctx = is_ctx_type && tokens_mention(encode_body.clone(), &ctx_param_names);

    let decode = if !want_decode {
        quote!()
    } else if is_ctx_type {
        quote! {
            impl #name {
                #[doc = "Decode from a bit source, given the context this type declares via `ctx(...)`."]
                #[allow(unused_variables)]
                pub fn decode_with<S: #from_bound>(
                    __bnb_r: &mut S,
                    __ctx: #ctx_name,
                ) -> ::core::result::Result<Self, #bnb::__private::BitError> {
                    #(#ctx_binds)*
                    #decode_body
                }
                #[doc = "Decode from bytes with context, requiring every whole byte consumed."]
                pub fn decode_with_exact(
                    bytes: &[u8],
                    __ctx: #ctx_name,
                ) -> ::core::result::Result<Self, #bnb::__private::BitError> {
                    #bnb::__private::decode_exact_with(bytes, #layout, |__bnb_r| Self::decode_with(__bnb_r, __ctx.clone()))
                }
            }
            impl #bnb::DecodeWith<#ctx_name> for #name {
                fn decode_with<S: #bnb::__private::Source>(
                    __bnb_r: &mut S,
                    args: #ctx_name,
                ) -> ::core::result::Result<Self, #bnb::__private::BitError> {
                    <#name>::decode_with(__bnb_r, args)
                }
            }
        }
    } else {
        quote! {
            impl #bnb::BitDecode for #name {
                fn bit_decode<S: #bnb::__private::Source>(
                    __bnb_r: &mut S,
                ) -> ::core::result::Result<Self, #bnb::__private::BitError> {
                    #decode_body
                }
            }
            impl #name {
                #[doc = "Decode one message from a bit cursor (a `BitReader`, `BufSource`, `BitBuf`, a streaming reader, …), advancing it; a seekable cursor is required if a variant seeks. The byte/bit order is the cursor's — use `decode_exact`/`decode_all` to bake the message's in."]
                pub fn decode<S: #from_bound>(
                    __bnb_r: &mut S,
                ) -> ::core::result::Result<Self, #bnb::__private::BitError> {
                    <Self as #bnb::BitDecode>::bit_decode(__bnb_r)
                }
                #[doc = "Decode every message from `bytes` into a `Vec`, bit-aware with the message's own byte/bit order baked in. The buffer must hold whole messages (a partial tail is an error)."]
                pub fn decode_all(
                    bytes: &[u8],
                ) -> ::core::result::Result<#bnb::__private::Vec<Self>, #bnb::__private::BitError> {
                    #bnb::__private::decode_all(bytes, #layout)
                }
                #[doc = "A lazy iterator decoding successive messages from `bytes` (layout baked in) until it is drained, ending after the first error if one occurs."]
                pub fn decode_iter(
                    bytes: &[u8],
                ) -> impl ::core::iter::Iterator<Item = ::core::result::Result<Self, #bnb::__private::BitError>> + '_ {
                    #bnb::__private::decode_iter(bytes, #layout)
                }
                #[doc = "Decode one message from `bytes` without consuming the caller's buffer (tail-tolerant)."]
                pub fn peek(bytes: &[u8]) -> ::core::result::Result<Self, #bnb::__private::BitError> {
                    #bnb::__private::decode_peek(bytes, #layout)
                }
                #[doc = "Decode and require every whole byte consumed."]
                pub fn decode_exact(bytes: &[u8]) -> ::core::result::Result<Self, #bnb::__private::BitError> {
                    #bnb::__private::decode_exact(bytes, #layout)
                }
            }
        }
    };

    let encode = if !want_encode {
        quote!()
    } else if enum_encode_uses_ctx {
        quote! {
            impl #name {
                #[doc = "Encode to a bit sink, given the context this type declares via `ctx(...)`."]
                #[allow(unused_variables)]
                pub fn encode_with<K: #bnb::__private::Sink>(
                    &self,
                    __bnb_w: &mut K,
                    __ctx: #ctx_name,
                ) -> ::core::result::Result<(), #bnb::__private::BitError> {
                    #(#ctx_binds)*
                    #encode_body
                }
                #[doc = "Encode to a `Vec<u8>` with context."]
                pub fn to_bytes_with(
                    &self,
                    __ctx: #ctx_name,
                ) -> ::core::result::Result<#bnb::__private::Vec<u8>, #bnb::__private::BitError> {
                    #bnb::__private::encode_to_vec_with(#layout, |__bnb_w| self.encode_with(__bnb_w, __ctx.clone()))
                }
            }
            impl #bnb::EncodeWith<#ctx_name> for #name {
                fn encode_with<K: #bnb::__private::Sink>(
                    &self,
                    __bnb_w: &mut K,
                    args: #ctx_name,
                ) -> ::core::result::Result<(), #bnb::__private::BitError> {
                    <#name>::encode_with(self, __bnb_w, args)
                }
            }
        }
    } else {
        // Plain encode (ctx not used on the write side). A `ctx` enum additionally impls a
        // context-ignoring `EncodeWith` so a parent can forward to it uniformly.
        let encode_with_trait = is_ctx_type.then(|| {
            quote! {
                impl #bnb::EncodeWith<#ctx_name> for #name {
                    #[allow(unused_variables)]
                    fn encode_with<K: #bnb::__private::Sink>(
                        &self,
                        __bnb_w: &mut K,
                        args: #ctx_name,
                    ) -> ::core::result::Result<(), #bnb::__private::BitError> {
                        <Self as #bnb::BitEncode>::bit_encode(self, __bnb_w)
                    }
                }
            }
        });
        quote! {
            impl #bnb::BitEncode for #name {
                const LAYOUT: #bnb::Layout = #layout;
                fn bit_encode<K: #bnb::__private::Sink>(
                    &self,
                    __bnb_w: &mut K,
                ) -> ::core::result::Result<(), #bnb::__private::BitError> {
                    #encode_body
                }
            }
            impl #name {
                #[doc = "Encode to a `Vec<u8>`. To write into an explicit bit sink (a `BitWriter`)"]
                #[doc = "or a `std::io::Write`, bring [`BitEncode`](::bnb::BitEncode) /"]
                #[doc = "[`EncodeExt`](::bnb::EncodeExt) into scope and call `.bit_encode(&mut sink)` /"]
                #[doc = "`.encode(&mut w)` (the latter is `std`-only)."]
                pub fn to_bytes(&self) -> ::core::result::Result<#bnb::__private::Vec<u8>, #bnb::__private::BitError> {
                    #bnb::__private::encode_to_vec(self, #layout)
                }
            }
            #encode_with_trait
        }
    };

    let ctx_struct = if is_ctx_type {
        let decls = args.ctx.iter().map(|(n, t)| {
            let doc = format!("The `{n}` context parameter.");
            quote!(#[doc = #doc] #vis #n: #t)
        });
        let params = args.ctx.iter().map(|(n, t)| quote!(#n: #t));
        let names = args.ctx.iter().map(|(n, _)| n);
        quote! {
            #[derive(Clone)]
            #[doc = "Context for the matching `#[bin(ctx(...))]` type — pass it to `decode_with`."]
            #vis struct #ctx_name { #(#decls),* }
            impl #ctx_name {
                #[doc = "Construct the context positionally, in declaration order."]
                #vis fn new(#(#params),*) -> Self {
                    Self { #(#names),* }
                }
            }
        }
    } else {
        quote!()
    };

    // The emitted enum: drop `#[br(temp)]` variant fields (read but not stored), strip
    // the dispatch attrs (`#[bin(tag=…)]`, `#[catch_all]`) and codec field attrs, leaving
    // an ordinary enum beside the generated impls.
    let strip = |f: &syn::Field| -> Option<syn::Field> {
        (!field_is_temp(f)).then(|| {
            let mut f = f.clone();
            f.attrs.retain(|a| !is_codec_field_attr(a));
            f
        })
    };
    let mut clean = e.clone();
    for v in &mut clean.variants {
        v.attrs
            .retain(|a| !(a.path().is_ident("bin") || a.path().is_ident("catch_all")));
        match &mut v.fields {
            Fields::Named(n) => n.named = n.named.iter().filter_map(&strip).collect(),
            Fields::Unnamed(u) => u.unnamed = u.unnamed.iter().filter_map(&strip).collect(),
            Fields::Unit => {}
        }
    }

    // `#[try_str]` variant fields render adaptively: intercept `Debug` (when derived) and emit a
    // custom impl over the variants. No `#[derive(Debug)]` ⇒ nothing to replace.
    let try_str_debug = match enum_try_str_debug(name, &e.variants, &bnb) {
        Some(impl_) => {
            let (had_debug, new_attrs) = intercept_debug_derive(&clean.attrs)?;
            had_debug.then(|| {
                clean.attrs = new_attrs;
                impl_
            })
        }
        None => None,
    };

    Ok(quote! {
        #ctx_struct
        #clean
        #try_str_debug
        #kind_enum
        #accessor_fn
        #helpers
        #decode
        #encode
    })
}

#[cfg(test)]
mod dispatch_tests {
    // Source snippets are kept uniformly as `r#"…"#` (several contain `b"…"` magics).
    #![allow(clippy::needless_raw_string_hashes)]
    use super::{EnumDispatch, Magic, MagicWidth, VariantRole};

    fn enum_of(src: &str) -> syn::ItemEnum {
        syn::parse_str(src).expect("valid enum source")
    }
    fn sel(name: &str) -> syn::Ident {
        syn::parse_str(name).expect("valid ident")
    }

    #[test]
    fn integer_magic_widths_inferred_from_suffix() {
        let src = r#"enum E { #[bin(magic = 0xCAFEu16)] A(u32), #[bin(magic = 0x01u16)] B }"#;
        let e = enum_of(src);
        let d = EnumDispatch::parse(&e, None, None).unwrap();
        assert_eq!(d.variants.len(), 2);
        assert_eq!(d.variants[0].magic.as_ref().unwrap().byte_len(), 2);
        assert_eq!(d.variants[0].role(), VariantRole::MagicOnly);
        assert_eq!(d.magic_width(), MagicWidth::Uniform(2));
    }

    #[test]
    fn byte_string_magic_widths_and_mixed_detection() {
        let e = enum_of(r#"enum E { #[bin(magic = b"IHDR")] A, #[bin(magic = b"END")] B }"#);
        let d = EnumDispatch::parse(&e, None, None).unwrap();
        assert_eq!(d.variants[0].magic.as_ref().unwrap().byte_len(), 4);
        assert_eq!(d.variants[1].magic.as_ref().unwrap().byte_len(), 3);
        assert_eq!(d.magic_width(), MagicWidth::Mixed);
    }

    #[test]
    fn tag_variant_requires_a_selector() {
        let e = enum_of(r#"enum E { #[bin(tag = 1)] A(u8) }"#);
        assert!(EnumDispatch::parse(&e, None, None).is_err());
        let d = EnumDispatch::parse(&e, Some(sel("kind")), None).unwrap();
        assert_eq!(d.variants[0].role(), VariantRole::TagOnly);
    }

    #[test]
    fn tag_and_magic_compose_on_one_variant() {
        let e = enum_of(r#"enum E { #[bin(tag = 1, magic = b"LI")] A(u32) }"#);
        let d = EnumDispatch::parse(&e, Some(sel("kind")), None).unwrap();
        assert_eq!(d.variants[0].role(), VariantRole::TagAndMagic);
    }

    #[test]
    fn fallback_and_catch_all_roles() {
        let e = enum_of(r#"enum E { #[bin(magic = b"X")] A, Plain(u32), #[catch_all] Other(u8) }"#);
        let d = EnumDispatch::parse(&e, None, None).unwrap();
        assert_eq!(d.variants[1].role(), VariantRole::Fallback);
        assert_eq!(d.variants[2].role(), VariantRole::CatchAll);
    }

    #[test]
    fn rejects_invalid_magic_values() {
        let bad = [
            r#"enum E { #[bin(magic = SOME_CONST)] A }"#, // non-literal
            r#"enum E { #[bin(magic = 1)] A }"#,          // unsuffixed int (ambiguous width)
            r#"enum E { #[bin(magic = 1usize)] A }"#,     // non-byte-aligned/platform width
            r#"enum E { #[bin(magic = u4::new(1))] A }"#, // sub-byte, and a non-literal
        ];
        for src in bad {
            assert!(
                EnumDispatch::parse(&enum_of(src), None, None).is_err(),
                "should reject: {src}"
            );
        }
    }

    #[test]
    fn rejects_two_catch_alls_and_two_fallbacks() {
        let two_catch = r#"enum E { #[catch_all] A(u8), #[catch_all] B(u8) }"#;
        assert!(EnumDispatch::parse(&enum_of(two_catch), None, None).is_err());
        let two_fallback = r#"enum E { A(u8), B(u8) }"#;
        assert!(EnumDispatch::parse(&enum_of(two_fallback), None, None).is_err());
    }

    #[test]
    fn prefix_is_recorded() {
        let e = enum_of(r#"enum E { #[bin(magic = b"X")] A }"#);
        let d = EnumDispatch::parse(&e, None, Some(Magic::Bytes(b"PRE".to_vec()))).unwrap();
        assert_eq!(d.prefix.as_ref().unwrap().byte_len(), 3);
    }
}