hopper-derive 0.2.0

Proc macro layer for Hopper. Generates account layouts, typed context accessors, instruction dispatchers, schema metadata, and CPI builders.
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
//! `#[hopper_context]`. typed context accessor codegen.
//!
//! Parses context structs with `#[account(...)]` annotations and generates:
//! - A typed binder over `hopper_runtime::Context`
//! - Per-field account accessors (`vault_account()`, `vault_load()`, etc.)
//! - Per-field segment accessors (`vault_balance_mut()`, etc.)
//! - Up-front signer, writable, owner, and layout validation
//! - Receipt scopes derived from the same mutable segment metadata
//!
//! All generated accessors are `#[inline(always)]` with const segment offsets.

use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::{
    parse::{Parse, ParseStream},
    parse2,
    punctuated::Punctuated,
    token::Comma,
    Attribute, Expr, Fields, GenericParam, Ident, ItemStruct, Result, Token, Type, TypePath,
};

/// Parsed `#[account(...)]` attribute. the full Anchor-grade surface.
///
/// The first three groups (`is_signer`, `is_mut`, `mut_segments`,
/// `read_segments`) are the pre-Stage-2 Hopper baseline. The remainder
/// mirrors Anchor's `#[derive(Accounts)]` constraint set so programs
/// can lower declarative account validation and lifecycle (init,
/// realloc, close) through the same canonical path.
#[derive(Default)]
struct AccountAttr {
    /// Whether the account is a signer.
    is_signer: bool,
    /// Whether the entire account is mutable.
    is_mut: bool,
    /// Specific mutable segment names (from `mut(field1, field2)`).
    mut_segments: Vec<String>,
    /// Specific read-only segment names (from `read(field1, field2)`).
    read_segments: Vec<String>,

    // ── Anchor-grade declarative constraints (audit ST2) ────────────
    /// `init`. account must be created fresh this instruction.
    /// Requires `payer` and `space`; implies `mut`. PDA-init also
    /// requires `seeds` + `bump`.
    init: bool,
    /// `init_if_needed`. Anchor-parity sibling of `init`. When the
    /// account is already allocated (data_len > 0 with a Hopper
    /// header in place) the lifecycle helper returns `Ok(())` without
    /// invoking the system-program CreateAccount CPI. When the
    /// account is empty, it falls through to the same init path as
    /// `init`. Requires the same fields as `init` (`payer`, `space`,
    /// optional `seeds`/`bump`). Callers must still validate the
    /// existing layout separately - `init_if_needed` guarantees the
    /// account exists and was sized at creation time, not that its
    /// current contents match a specific layout.
    init_if_needed: bool,
    /// `zero`. assert the account was previously zero-initialized.
    /// Cheaper than `init` for already-allocated accounts.
    zero: bool,
    /// `close = target`. at the end of the instruction, transfer the
    /// account's lamports to `target` and mark the data for reclaim.
    /// Implies `mut`.
    close: Option<Ident>,
    /// `realloc = new_size_expr`. resize account data before the
    /// instruction body. Requires `realloc_payer` and `realloc_zero`
    /// policy.
    realloc: Option<Expr>,
    /// Field that pays for realloc top-up lamports.
    realloc_payer: Option<Ident>,
    /// Whether realloc'd bytes must be zero-filled.
    realloc_zero: bool,
    /// `payer = field`. the field in this context struct that funds
    /// an `init` or `realloc` operation. Must itself be a signer.
    payer: Option<Ident>,
    /// `space = expr`. byte count for an `init`. Typically
    /// `Layout::LEN`.
    space: Option<Expr>,
    /// `seeds = [expr1, expr2, ...]`. PDA derivation input.
    seeds: Option<Vec<Expr>>,
    /// `seeds_fn = Type::seeds(&arg1, &arg2)`. Typed-seeds sugar. The
    /// provided expression must evaluate to a value that implements
    /// `AsRef<[Seed]>` or equivalently yields `&[&[u8]]`. Hopper uses
    /// it in place of the inline `seeds = [...]` array. Inspired by
    /// Quasar's `Type::seeds(...)` pattern; the point is that each
    /// type can centralize its PDA seed layout in one place and
    /// every context just calls the helper.
    seeds_fn: Option<Expr>,
    /// `bump` (inferred each call) or `bump = stored_byte`.
    bump: Option<BumpSpec>,
    /// `has_one = other_field`. require `self.field == other.key()`
    /// after layout load. Can appear multiple times.
    has_one: Vec<Ident>,
    /// `owner = expr`. require the account's owner equal `expr`.
    /// Default for layout fields is `ctx.program_id()`.
    owner: Option<Expr>,
    /// `address = expr`. require the account's key equal `expr`.
    address: Option<Expr>,
    /// `constraint = expr`. arbitrary boolean guard, evaluated as the
    /// last step of validation.
    constraint: Vec<Expr>,

    // ── Anchor SPL parity (audit ST2: "make Hopper the best of three") ──
    //
    // These constraints bring Hopper's declarative account layer to
    // strict parity with Anchor's `#[account(token::mint = X, ...)]`
    // family. Each attribute is parsed in the nested-meta pass below
    // and lowered into a call to the matching `require_*` helper in
    // `hopper_runtime::token`. Those helpers read exactly the bytes
    // that matter from an already-borrowed account buffer. no
    // full-struct deserialize, no new crate dependencies, no ABI
    // coupling to an external spl-token version.
    //
    /// `token::mint = expr`. require this SPL TokenAccount's bytes
    /// `[0..32]` equal the pubkey produced by `expr`.
    token_mint: Option<Expr>,
    /// `token::authority = expr`. require this SPL TokenAccount's
    /// bytes `[32..64]` equal the pubkey produced by `expr`.
    token_authority: Option<Expr>,
    /// `token::token_program = expr`. require this account's Solana
    /// owner-program equals `expr`. The usual case is pointing at
    /// Token-2022 instead of the default SPL Token program, so the
    /// program can validate a Token-2022 token account the same way
    /// it validates a legacy SPL one. Defaults to SPL Token when
    /// `token::mint` or `token::authority` are set without an
    /// explicit `token_program`.
    token_token_program: Option<Expr>,
    /// `mint::authority = expr`. require this SPL Mint's
    /// `mint_authority` COption equals `Some(expr)`.
    mint_authority: Option<Expr>,
    /// `mint::decimals = expr`. require this SPL Mint's byte 44 equal
    /// `expr as u8`.
    mint_decimals: Option<Expr>,
    /// `mint::freeze_authority = expr`. require this SPL Mint's
    /// `freeze_authority` COption equals `Some(expr)`.
    mint_freeze_authority: Option<Expr>,
    /// `mint::token_program = expr`. require this account's Solana
    /// owner-program equals `expr`. Defaults to SPL Token when any
    /// `mint::*` constraint is set without an explicit `token_program`.
    /// The Token-2022 parity lever for the mint axis.
    mint_token_program: Option<Expr>,
    /// `associated_token::mint = expr`. ATA derivation input.
    associated_token_mint: Option<Expr>,
    /// `associated_token::authority = expr`. ATA derivation input.
    associated_token_authority: Option<Expr>,
    /// `associated_token::token_program = expr`. optional token-program
    /// override. defaults to the legacy SPL Token program ID when
    /// the user omits it. Accepting this value is what lets Hopper
    /// support ATAs over Token-2022 mints without a second attribute.
    associated_token_token_program: Option<Expr>,
    /// `seeds::program = expr`. when present, PDA derivation for this
    /// field uses the given program ID instead of
    /// `ctx.program_id()`. Anchor emits this as the third positional
    /// argument to `Pubkey::find_program_address(..., program_id)`.
    seeds_program: Option<Expr>,

    // ── Token-2022 extension constraints (zero-copy TLV readers) ──
    //
    // Each lever lowers to a single call into
    // `hopper_runtime::token_2022_ext::require_*`. The readers scan
    // the mint or token-account TLV region in place, no heap, no full
    // decode. This is the surface Anchor routes through
    // `InterfaceAccount<Mint>` with a Borsh deserialize; Hopper keeps
    // it on the zero-copy path end to end.
    ext_non_transferable: bool,
    ext_immutable_owner: bool,
    ext_mint_close_authority: Option<Expr>,
    ext_permanent_delegate: Option<Expr>,
    ext_transfer_hook_authority: Option<Expr>,
    ext_transfer_hook_program: Option<Expr>,
    ext_metadata_pointer_authority: Option<Expr>,
    ext_metadata_pointer_address: Option<Expr>,
    ext_default_account_state: Option<Expr>,
    ext_interest_bearing_authority: Option<Expr>,
    ext_transfer_fee_config_authority: Option<Expr>,
    ext_transfer_fee_withdraw_authority: Option<Expr>,

    // ── Metaplex Token Metadata constraints / CPI helpers ─────────────
    /// `metadata::name = expr`. Name for `CreateMetadataAccountV3`.
    metadata_name: Option<Expr>,
    /// `metadata::symbol = expr`. Symbol for `CreateMetadataAccountV3`.
    metadata_symbol: Option<Expr>,
    /// `metadata::uri = expr`. URI for `CreateMetadataAccountV3`.
    metadata_uri: Option<Expr>,
    /// `metadata::seller_fee_basis_points = expr`. Royalty basis points.
    metadata_seller_fee_basis_points: Option<Expr>,
    /// `metadata::is_mutable = expr`. Defaults to true when omitted.
    metadata_is_mutable: Option<Expr>,
    /// `metadata::mint = field`. Mint account used by the CPI helper.
    metadata_mint: Option<Ident>,
    /// `metadata::mint_authority = field`. Mint-authority signer.
    metadata_mint_authority: Option<Ident>,
    /// `metadata::payer = field`. Payer signer+writable account.
    metadata_payer: Option<Ident>,
    /// `metadata::update_authority = field`. Update-authority signer.
    metadata_update_authority: Option<Ident>,
    /// `metadata::system_program = field`. System Program account.
    metadata_system_program: Option<Ident>,
    /// `metadata::rent = field`. Optional rent sysvar account.
    metadata_rent: Option<Ident>,

    /// `master_edition::max_supply = expr`. Accepts u64 or Option<u64>.
    master_edition_max_supply: Option<Expr>,
    /// `master_edition::mint = field`. Mint account used by the CPI helper.
    master_edition_mint: Option<Ident>,
    /// `master_edition::metadata = field`. Metadata account sibling.
    master_edition_metadata: Option<Ident>,
    /// `master_edition::update_authority = field`. Update-authority signer.
    master_edition_update_authority: Option<Ident>,
    /// `master_edition::mint_authority = field`. Mint-authority signer.
    master_edition_mint_authority: Option<Ident>,
    /// `master_edition::payer = field`. Payer signer+writable account.
    master_edition_payer: Option<Ident>,
    /// `master_edition::token_program = field`. SPL Token program account.
    master_edition_token_program: Option<Ident>,
    /// `master_edition::system_program = field`. System Program account.
    master_edition_system_program: Option<Ident>,
    /// `master_edition::rent = field`. Optional rent sysvar account.
    master_edition_rent: Option<Ident>,

    /// `dup = other_field`. This slot is allowed to
    /// alias `other_field` (the caller intentionally passed the same
    /// account in two roles). Skips the "no duplicate writables" and
    /// "no duplicate signers" pipeline checks for this pair. Does
    /// NOT imply `mut`.
    dup: Option<Ident>,

    /// `sweep = target_field`. After the handler returns Ok, move
    /// any remaining lamports from this account to `target_field`'s
    /// address. Runs as a post-handler epilogue emitted by `bind`.
    /// Used for pool fee sweeps, keeper cleanup, and rent-reclaim
    /// patterns. Implies `mut` on both the source and target.
    sweep: Option<Ident>,

    /// `executable`. Anchor-parity keyword. Requires the account's
    /// `executable` flag to be true - i.e. it must be a deployed BPF
    /// program. Hopper's `Program<P>` wrapper type already implies
    /// this, but the bare keyword exists for ports of Anchor code and
    /// for cases where the field type is `AccountView` instead of a
    /// typed wrapper.
    executable: bool,

    /// `rent_exempt = enforce | skip`. Anchor-parity keyword. When set
    /// to `enforce` the context binder checks that the account's
    /// lamport balance is at or above the rent-exemption minimum for
    /// its data length. When set to `skip` the check is explicitly
    /// omitted (useful when the caller has asserted rent-exemption
    /// through a different pathway and wants the intent recorded).
    /// When unset (the default), no check is emitted and the caller
    /// is responsible for rent safety.
    rent_exempt: Option<RentExemptPolicy>,
}

/// Policy for the `rent_exempt` field keyword.
#[derive(Clone, Copy, PartialEq, Eq)]
#[allow(dead_code)]
enum RentExemptPolicy {
    /// `rent_exempt = enforce`. Runtime check that
    /// `account.lamports() >= Rent::minimum_balance(data_len)`.
    Enforce,
    /// `rent_exempt = skip`. Explicitly opts out; emits no check but
    /// records the intent in the generated code (and in the schema
    /// manifest) so an auditor can see the acknowledgment.
    Skip,
}

/// How the bump for a PDA-derived account is supplied.
#[derive(Clone)]
#[allow(dead_code)]
enum BumpSpec {
    /// `bump`. re-derive via `find_program_address` each call.
    /// More expensive but removes the need to store the bump byte.
    Inferred,
    /// `bump = self.field_name.bump`. read the bump byte from a
    /// struct member, then use `create_program_address` for a cheap
    /// verification. Matches the on-chain-PDA cache pattern from
    /// `hopper_verify_pda!`.
    Stored(Expr),
}

/// Parsed context field.
struct ContextField {
    name: Ident,
    ty: Type,
    attr: AccountAttr,
    index: usize,
}

struct AccountsBindingFragments {
    field_decl: TokenStream,
    init_stmt: TokenStream,
    bound_field: TokenStream,
}

/// A single `name: Type` binding inside a struct-level
/// `#[instruction(...)]` attribute.
///
/// ## Design notes
///
/// Anchor's `#[instruction(...)]` is a **parse-only** hint. its argument
/// names never appear in generated `impl` bodies beyond the accounts
/// constraint expressions themselves, so there's no way to cross-check
/// the declared arg list against the actual instruction decoder. a
/// mismatch is only caught when the seed expression fails to typecheck.
///
/// Hopper threads the declared args through both:
/// - every per-field `validate_<field>` function, so that each constraint
///   gets the same Rust parameters (and the compiler surfaces a
///   helpful error if the type doesn't match), and
/// - the emitted `SCHEMA_METADATA` (`context_args`), so off-chain tooling
///   (hopper-sdk, Codama, IDL) can see the declared args without
///   re-parsing source.
///
/// The args also drive a dedicated `*_with_args` pair of `validate` /
/// `bind` entry points. the args-less `validate` / `bind` are **not**
/// emitted in that case, because a seed/constraint expression referring
/// to an arg cannot compile without the binding in scope. forcing the
/// user to call `bind_with_args` keeps the contract honest.
#[derive(Debug)]
struct InstructionArgDecl {
    name: Ident,
    ty: Type,
}

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

/// Scan a struct's outer attribute list for `#[instruction(...)]`,
/// returning the parsed `(name, type)` bindings and stripping the
/// attribute from the struct so it doesn't leak through the emitted
/// code path.
///
/// Accepts exactly one `#[instruction(...)]` attribute per struct.
/// Multiple attributes or duplicate arg names are rejected with a
/// span-attached compile error so the failure points at the offending
/// token rather than bubbling up as an opaque runtime symbol clash.
fn parse_instruction_attr(attrs: &mut Vec<Attribute>) -> Result<Vec<InstructionArgDecl>> {
    let mut out: Vec<InstructionArgDecl> = Vec::new();
    let mut seen = 0usize;

    for attr in attrs.iter() {
        if !attr.path().is_ident("instruction") {
            continue;
        }
        if seen > 0 {
            return Err(syn::Error::new_spanned(
                attr,
                "#[hopper::context] accepts at most one #[instruction(...)] attribute; \
                 put every arg in a single list, comma-separated",
            ));
        }
        seen += 1;

        let parsed: Punctuated<InstructionArgDecl, Comma> =
            attr.parse_args_with(Punctuated::<InstructionArgDecl, Comma>::parse_terminated)?;
        for arg in parsed {
            if out.iter().any(|a| a.name == arg.name) {
                return Err(syn::Error::new_spanned(
                    &arg.name,
                    format!(
                        "duplicate instruction argument `{}`: each binding must be uniquely named",
                        arg.name
                    ),
                ));
            }
            out.push(arg);
        }
    }

    attrs.retain(|a| !a.path().is_ident("instruction"));
    Ok(out)
}

/// Public entry point for the `#[hopper::context]` attribute.
///
/// Backward-compatible wrapper around [`expand_inner`]; emits the original
/// struct definition, since attribute macros are responsible for the
/// passthrough.
pub fn expand(_attr: TokenStream, item: TokenStream) -> Result<TokenStream> {
    expand_inner(item, /* emit_struct */ true)
}

/// Public entry point for the `#[derive(Accounts)]` proc-macro derive.
///
/// Functionally identical to [`expand`], except the original input struct
/// is **not** re-emitted (the user already declared it themselves). Helper
/// attributes - `#[account(...)]`, `#[signer]`, `#[instruction(...)]`,
/// `#[validate]` - are still parsed off the input but cannot be stripped
/// in place because the struct is not under our attribute. We rely on the
/// `attributes(...)` declaration on the derive macro to silence the
/// compiler's "unknown attribute" check; the helpers are dropped from the
/// final compilation unit by `rustc` once all derives have run.
pub fn expand_for_derive(item: TokenStream) -> Result<TokenStream> {
    expand_inner(item, /* emit_struct */ false)
}

fn expand_inner(item: TokenStream, emit_struct: bool) -> Result<TokenStream> {
    let mut input: ItemStruct = parse2(item)?;

    // ── Instruction-arg typing (audit Stage 2.6) ──────────────────────
    //
    // Parse the struct-level `#[instruction(name: Type, ...)]` attribute
    // before anything else touches `input.attrs`. we strip it in place
    // so the emitted struct doesn't re-export an attribute with no
    // attached proc-macro (Rust would emit `unknown attribute` otherwise).
    //
    // When non-empty, the declared args are threaded as ordinary Rust
    // parameters into every per-field validator and into the top-level
    // entry points. seed / constraint / owner / address expressions
    // that reference these names compile the same way any other local
    // binding compiles. no magic, no hidden thread-local, no runtime
    // lookup. this is the piece that lets declarative seeds say
    // `seeds = [b"vault", nonce.to_le_bytes().as_ref()]` and have
    // `nonce` resolve to the typed instruction argument.
    let instruction_args = parse_instruction_attr(&mut input.attrs)?;
    let has_instruction_args = !instruction_args.is_empty();

    // Anchor-parity `#[validate]` opt-in. When the author adds
    // `#[validate]` at the struct level, `bind()` calls a
    // user-provided inherent method
    // `fn validate(&self) -> Result<(), ProgramError>` on the bound
    // context struct after every built-in constraint has passed.
    //
    // Why a marker instead of auto-detect: Rust trait dispatch cannot
    // tell "user implemented validate" apart from "user didn't touch
    // it" without specialization. An explicit opt-in keeps the call
    // path honest, and an unset `#[validate]` on a struct that
    // happens to have its own `validate(&self)` is a dead method the
    // compiler warns about, which is the correct failure mode.
    let user_validate = input.attrs.iter().any(|a| a.path().is_ident("validate"));
    input.attrs.retain(|a| !a.path().is_ident("validate"));

    // Prebuilt fragments for the declared instruction args. each one
    // is used in several places in the emitted output (per-field
    // validator signatures, top-level validate/bind signatures, call
    // sites that forward args down), so we compute them once.
    let arg_params: Vec<TokenStream> = instruction_args
        .iter()
        .map(|a| {
            let n = &a.name;
            let t = &a.ty;
            quote! { #n: #t }
        })
        .collect();
    let arg_names: Vec<Ident> = instruction_args.iter().map(|a| a.name.clone()).collect();
    // `_with_args` suffix on the top-level entry points when the user
    // has declared any typed args. this gives callers a distinct symbol
    // and lets us *omit* the args-less `validate`/`bind` entirely when
    // they'd be incomplete (a seed expression that references an arg
    // can't compile without the binding in scope, so silently emitting
    // a half-validated `validate` would be a footgun).
    let top_validate_ident = if has_instruction_args {
        format_ident!("validate_with_args")
    } else {
        format_ident!("validate")
    };
    let top_bind_ident = if has_instruction_args {
        format_ident!("bind_with_args")
    } else {
        format_ident!("bind")
    };

    let name = &input.ident;
    let vis = &input.vis;
    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
    let bound_name = format_ident!("{}Ctx", name);
    let receipt_scope_name = format_ident!("{}ReceiptScope", name);

    let fields = match &mut input.fields {
        Fields::Named(f) => &mut f.named,
        _ => {
            return Err(syn::Error::new_spanned(
                &input,
                "hopper_context requires a struct with named fields",
            ))
        }
    };

    let mut ctx_fields = Vec::new();
    for (i, field) in fields.iter_mut().enumerate() {
        let field_name = field.ident.as_ref().unwrap().clone();
        let field_ty = field.ty.clone();
        reject_reference_wrapped_account(&field_name, &field_ty)?;
        let attr = parse_account_attr(&field.attrs)?;
        validate_account_attr(&field_name, &attr)?;
        if (!attr.mut_segments.is_empty() || !attr.read_segments.is_empty())
            && skips_layout_validation(&field_ty)
        {
            return Err(syn::Error::new_spanned(
                &field.ty,
                "segment accessors require a Hopper layout type, not a raw account view",
            ));
        }
        field
            .attrs
            .retain(|attr| !attr.path().is_ident("account") && !attr.path().is_ident("signer"));
        ctx_fields.push(ContextField {
            name: field_name,
            ty: field_ty,
            attr,
            index: i,
        });
    }
    let accounts_binding = accounts_binding_fragments(name, &input.generics, &ctx_fields);
    let accounts_field_decl = accounts_binding.field_decl;
    let accounts_init_stmt = accounts_binding.init_stmt;
    let accounts_bound_field = accounts_binding.bound_field;

    // Generate per-field validation functions and collect check descriptions.
    let mut validation_stmts = Vec::new();
    let mut per_field_validators = Vec::new();
    let mut check_descriptions: Vec<String> = Vec::new();

    // Bumps captured during the PDA-derivation pass. Each entry is
    // `(field_ident, derive_expr)` where `derive_expr` evaluates to a
    // `::core::result::Result<u8, ProgramError>` inside `bind(...)`.
    // Inferred bumps re-run `find_program_address` in a dedicated
    // helper on the bound-context path (accept the extra derivation
    // cost for the ergonomic win; stored bumps are free). Stored bumps
    // read the user-supplied byte directly. Fields without `seeds = ...`
    // never appear here and never show up on the `Bumps` struct,
    // matching Anchor's shape exactly. That asymmetry is deliberate:
    // a `Bumps` struct with a `u8` slot for every account would invite
    // readers to assume every slot had a meaning, and writing `0` for
    // non-PDAs is worse than omitting them.
    let mut bump_entries: Vec<(Ident, TokenStream)> = Vec::new();

    for cf in &ctx_fields {
        let idx = cf.index;
        let field_name = &cf.name;
        let validate_fn = format_ident!("validate_{}", field_name);
        let mut field_checks = Vec::new();

        // ── Audit page 12: deterministic validation ordering ──────────
        //
        // 1. presence (handled by `require_accounts` at top of validate())
        // 2. signer / mut / owner / executable / address
        // 3. duplicate-writable / signer rules
        // 4. PDA derivation
        // 5. init / realloc / close preconditions
        // 6. custom `constraint = expr`
        //
        // We accumulate checks into `field_checks` in that order so the
        // emitted error always points at the most specific reason first.

        // ── Audit Stage 2.3: wrapper-type auto-promotion ───────────────
        //
        // If the field type is a Hopper-owned wrapper
        // (`Signer<'info>`, `Account<'info, T>`,
        // `InitAccount<'info, T>`, `Program<'info, P>`), emit the
        // wrapper-specific checks first. Attribute-based constraints
        // layer on top of the wrapper-derived defaults. both paths
        // compose, neither overrides.
        let wrapper = classify_wrapper(&cf.ty);
        let wrapper_is_signer = matches!(wrapper, Some(WrapperKind::Signer));
        let wrapper_is_init = matches!(wrapper, Some(WrapperKind::InitAccount { .. }));
        // The has_layout / layout_ty computation below resolves
        // `Account<'info, T>` → `T` so `load::<T>()` targets the
        // right layout.
        if let Some(WrapperKind::Program) = &wrapper {
            // Program<'info, P>. require address == P::ID + executable.
            // P is the last type arg of the path.
            if let Type::Path(TypePath { path, .. }) = &cf.ty {
                if let Some(segment) = path.segments.last() {
                    if let syn::PathArguments::AngleBracketed(args) = &segment.arguments {
                        if let Some(program_ty) = args.args.iter().find_map(|arg| {
                            if let syn::GenericArgument::Type(t) = arg {
                                Some(t.clone())
                            } else {
                                None
                            }
                        }) {
                            field_checks.push(quote! {
                                if ctx.account(#idx)?.address()
                                    != &<#program_ty as ::hopper::__runtime::ProgramId>::ID
                                {
                                    return ::core::result::Result::Err(
                                        ::hopper::__runtime::ProgramError::IncorrectProgramId
                                    );
                                }
                                if !ctx.account(#idx)?.executable() {
                                    return ::core::result::Result::Err(
                                        ::hopper::__runtime::ProgramError::InvalidAccountData
                                    );
                                }
                            });
                            check_descriptions.push(format!(
                                "accounts[{}] ({}) must be the declared program (address + executable pin)",
                                idx, field_name
                            ));
                        }
                    }
                }
            }
        }
        if let Some(WrapperKind::Interface { spec }) = &wrapper {
            field_checks.push(quote! {
                if !<#spec as ::hopper::__runtime::InterfaceSpec>::contains(
                    ctx.account(#idx)?.address()
                ) {
                    return ::core::result::Result::Err(
                        ::hopper::__runtime::ProgramError::IncorrectProgramId
                    );
                }
                if !ctx.account(#idx)?.executable() {
                    return ::core::result::Result::Err(
                        ::hopper::__runtime::ProgramError::InvalidAccountData
                    );
                }
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) must be one of the declared interface programs (address set + executable pin)",
                idx, field_name
            ));
        }
        if let Some(WrapperKind::InterfaceAccount { inner }) = &wrapper {
            field_checks.push(quote! {
                let _ = ::hopper::prelude::InterfaceAccount::<#inner>::try_new(
                    ctx.account(#idx)?
                )?;
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) owner must belong to its declared interface and match the Hopper layout header",
                idx, field_name
            ));
        }
        if let Some(WrapperKind::SystemAccount) = &wrapper {
            field_checks.push(quote! {
                ctx.account(#idx)?.check_owned_by(&::hopper::prelude::SystemId::ID)?;
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) must be owned by the System Program",
                idx, field_name
            ));
        }

        // -- Stage 2: signer / mut / address / owner / layout -------------

        if cf.attr.is_signer || wrapper_is_signer {
            field_checks.push(quote! {
                ctx.account(#idx)?.check_signer()?;
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) must be a signer",
                idx, field_name
            ));
        }
        if cf.attr.is_mut || !cf.attr.mut_segments.is_empty() {
            field_checks.push(quote! {
                ctx.account(#idx)?.check_writable()?;
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) must be writable",
                idx, field_name
            ));
        }
        if cf.attr.executable {
            // Anchor-parity `executable` keyword. Routes through
            // AccountView::check_executable which returns an error
            // when the `executable` flag on the loader-provided
            // account header is unset.
            field_checks.push(quote! {
                ctx.account(#idx)?.check_executable()?;
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) must be executable (deployed BPF program)",
                idx, field_name
            ));
        }
        if let Some(policy) = cf.attr.rent_exempt {
            match policy {
                RentExemptPolicy::Enforce => {
                    // Anchor-parity `rent_exempt = enforce`. Requires
                    // `lamports() >= Rent::minimum_balance(data_len)`.
                    // Uses the runtime helper that reads the Rent
                    // sysvar lazily - the check is explicit, not a
                    // heuristic.
                    field_checks.push(quote! {
                        ::hopper::hopper_runtime::rent::check_rent_exempt(
                            ctx.account(#idx)?,
                        )?;
                    });
                    check_descriptions.push(format!(
                        "accounts[{}] ({}) must be rent-exempt (lamports >= Rent::minimum_balance(data_len))",
                        idx, field_name
                    ));
                }
                RentExemptPolicy::Skip => {
                    // `rent_exempt = skip` is an explicit acknowledgment
                    // that the caller is handling rent-exemption through
                    // a different pathway. Emits no check; only records
                    // the intent in the schema so auditors can see it.
                    check_descriptions.push(format!(
                        "accounts[{}] ({}) rent-exemption intentionally skipped (rent_exempt = skip)",
                        idx, field_name
                    ));
                }
            }
        }
        if let Some(addr_expr) = &cf.attr.address {
            field_checks.push(quote! {
                if ctx.account(#idx)?.address() != &(#addr_expr) {
                    return ::core::result::Result::Err(
                        ::hopper::__runtime::ProgramError::InvalidAccountData
                    );
                }
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) address must match `address = ...`",
                idx, field_name
            ));
        }
        let owner_expr = cf.attr.owner.clone();
        // Wrapper-aware layout handling:
        //   Account<'info, T>     → layout = T, has_layout = true
        //   InitAccount<'info, T> → has_layout = false at validate time
        //   Signer/Program/raw    → has_layout = false
        //   Plain T               → has_layout from skips_layout_validation
        let (has_layout, layout_ty): (bool, Option<Type>) = match &wrapper {
            Some(WrapperKind::Account { inner }) => (true, Some(inner.clone())),
            Some(WrapperKind::InitAccount { .. })
            | Some(WrapperKind::Signer)
            | Some(WrapperKind::Program)
            | Some(WrapperKind::Interface { .. })
            | Some(WrapperKind::InterfaceAccount { .. })
            | Some(WrapperKind::UncheckedAccount)
            | Some(WrapperKind::SystemAccount) => (false, None),
            None => {
                let h = !skips_layout_validation(&cf.ty);
                (h, if h { Some(cf.ty.clone()) } else { None })
            }
        };

        // For `init` accounts the account hasn't been created yet, so we
        // skip the owner+load step. the `init_{field}()` lifecycle
        // helper will allocate and write the header later. Other cases
        // (including `zero`) assume the account already exists. The same
        // reasoning applies when the field is typed as `InitAccount<T>`.
        let is_init_field = cf.attr.init || wrapper_is_init;
        if has_layout && !is_init_field {
            let field_ty = layout_ty.as_ref().unwrap_or(&cf.ty);
            let owner_check = if let Some(expr) = &owner_expr {
                quote! {
                    ctx.account(#idx)?.check_owned_by(&(#expr))?;
                }
            } else {
                quote! {
                    ctx.account(#idx)?.check_owned_by(ctx.program_id())?;
                }
            };
            field_checks.push(quote! {
                #owner_check
                let _ = ctx.account(#idx)?.load::<#field_ty>()?;
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) owner matches, valid {} header",
                idx,
                field_name,
                type_ident(field_ty)
                    .map(|i| i.to_string())
                    .unwrap_or_default()
            ));
        } else if !has_layout {
            // For raw AccountView fields, still honor an explicit
            // `owner = expr` even without a layout header to validate.
            if let Some(expr) = &owner_expr {
                field_checks.push(quote! {
                    ctx.account(#idx)?.check_owned_by(&(#expr))?;
                });
                check_descriptions.push(format!(
                    "accounts[{}] ({}) owner must match `owner = ...`",
                    idx, field_name
                ));
            }
        }

        // -- Stage 4a: typed-seeds sugar (`seeds_fn = Type::seeds(...)`) --
        //
        // PDA seed wiring: the user centralizes their PDA seed
        // layout on the account type via a `seeds(...) -> ...` helper,
        // and every context references it by name. We lower to
        // `find_program_address(expr(), program_id)` and verify the
        // resulting pubkey matches the account at `#idx`. Bumps come
        // back on the returned value from `find_program_address` so
        // no separate `bump` attribute is needed with this form.
        if let Some(seeds_fn_expr) = &cf.attr.seeds_fn {
            // Reject a combination that would be ambiguous: the user
            // supplied both a seeds array AND a seeds_fn. Which
            // derivation wins is a coin flip the author should not
            // depend on.
            if cf.attr.seeds.is_some() {
                return Err(syn::Error::new_spanned(
                    seeds_fn_expr,
                    "`seeds_fn = ...` cannot be combined with `seeds = [...]`. Pick one.",
                ));
            }
            let pda_program_expr = if let Some(prog) = &cf.attr.seeds_program {
                quote! { &(#prog) }
            } else {
                quote! { ctx.program_id() }
            };
            field_checks.push(quote! {
                {
                    let __seed_slices: &[&[u8]] = (#seeds_fn_expr).as_ref();
                    let (expected, _bump) = ::hopper::pda::find_program_address(
                        __seed_slices,
                        #pda_program_expr,
                    );
                    if ctx.account(#idx)?.address() != &expected {
                        return ::core::result::Result::Err(
                            ::hopper::__runtime::ProgramError::InvalidSeeds
                        );
                    }
                }
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) matches PDA derived from typed seeds helper",
                idx, field_name
            ));
            bump_entries.push((
                field_name.clone(),
                quote! {
                    {
                        let __seed_slices: &[&[u8]] = (#seeds_fn_expr).as_ref();
                        let (_, __b) = ::hopper::pda::find_program_address(
                            __seed_slices,
                            #pda_program_expr,
                        );
                        __b
                    }
                },
            ));
        }

        // -- Stage 4: PDA derivation (seeds + bump) ----------------------
        if let (Some(seeds), Some(bump)) = (&cf.attr.seeds, &cf.attr.bump) {
            let seed_exprs: Vec<_> = seeds.iter().collect();
            // `seeds::program = X` (Anchor-compat) redirects PDA
            // derivation to a program ID other than the currently
            // executing one. This is how a program verifies that an
            // account is a PDA of *another* program. a common pattern
            // when interoperating with governance or registry programs.
            // When omitted, we keep the existing behavior of using
            // `ctx.program_id()`.
            let pda_program_expr = if let Some(prog) = &cf.attr.seeds_program {
                quote! { &(#prog) }
            } else {
                quote! { ctx.program_id() }
            };
            let verify_call = match bump {
                BumpSpec::Inferred => quote! {
                    {
                        let (expected, _bump) = ::hopper::pda::find_program_address(
                            &[ #( AsRef::<[u8]>::as_ref(&(#seed_exprs)) ),* ],
                            #pda_program_expr,
                        );
                        if ctx.account(#idx)?.address() != &expected {
                            return ::core::result::Result::Err(
                                ::hopper::__runtime::ProgramError::InvalidSeeds
                            );
                        }
                    }
                },
                BumpSpec::Stored(bump_expr) => quote! {
                    {
                        let bump: u8 = #bump_expr;
                        let seeds_with_bump: &[&[u8]] = &[
                            #( AsRef::<[u8]>::as_ref(&(#seed_exprs)) ),*,
                            ::core::slice::from_ref(&bump),
                        ];
                        let expected = ::hopper::pda::create_program_address(
                            seeds_with_bump,
                            #pda_program_expr,
                        )?;
                        if ctx.account(#idx)?.address() != &expected {
                            return ::core::result::Result::Err(
                                ::hopper::__runtime::ProgramError::InvalidSeeds
                            );
                        }
                    }
                },
            };
            field_checks.push(verify_call);
            check_descriptions.push(format!(
                "accounts[{}] ({}) matches PDA derived from declared seeds{}",
                idx,
                field_name,
                if cf.attr.seeds_program.is_some() {
                    " (under custom program ID)"
                } else {
                    ""
                }
            ));

            // Build the derive expression used by the generated Bumps
            // struct gatherer. Stored bumps read the user-supplied byte
            // straight from scope; Inferred bumps re-run
            // `find_program_address` on the bound-context path. The
            // extra derivation for Inferred is the cost of the
            // ergonomic win: the whole point of surfacing
            // `ctx.bumps().field` is to save the caller from redoing
            // the work in a CPI signer-seeds block one line later.
            // Stored bumps cost zero CU.
            let bump_gather_expr: TokenStream = match bump {
                BumpSpec::Stored(bump_expr) => quote! {
                    { let __b: u8 = #bump_expr; __b }
                },
                BumpSpec::Inferred => quote! {
                    {
                        let (_, __b) = ::hopper::pda::find_program_address(
                            &[ #( AsRef::<[u8]>::as_ref(&(#seed_exprs)) ),* ],
                            #pda_program_expr,
                        );
                        __b
                    }
                },
            };
            bump_entries.push((field_name.clone(), bump_gather_expr));
        }

        // -- Stage 5: init / realloc / close preconditions ----------------
        //
        // The preconditions live with validate(); the *execution* of
        // init / realloc / close happens via the per-field lifecycle
        // methods on the bound context. The payer/space/target
        // existence checks are cheap and catch malformed Context
        // wiring up-front.
        if cf.attr.init {
            // Precondition: the account must be writable and, once the
            // lifecycle helper runs, owned by this program. The
            // helper itself handles CPI + header write.
            field_checks.push(quote! {
                ctx.account(#idx)?.check_writable()?;
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) must be writable (init precondition)",
                idx, field_name
            ));
        }
        if cf.attr.realloc.is_some() {
            field_checks.push(quote! {
                ctx.account(#idx)?.check_writable()?;
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) must be writable (realloc precondition)",
                idx, field_name
            ));
        }
        if cf.attr.close.is_some() {
            field_checks.push(quote! {
                ctx.account(#idx)?.check_writable()?;
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) must be writable (close precondition)",
                idx, field_name
            ));
        }

        // -- Stage 5.5: has_one. field value must equal other account's key.
        // Runs after layout load so we can read the struct field.
        for target_ident in &cf.attr.has_one {
            let target_name = target_ident.to_string();
            let target_idx = ctx_fields
                .iter()
                .position(|c| c.name == *target_ident)
                .ok_or_else(|| {
                    syn::Error::new_spanned(
                        target_ident,
                        format!(
                            "has_one = `{}`: no field named `{}` in this context",
                            target_name, target_name
                        ),
                    )
                })?;
            let field_ty = layout_type_for_field(cf).ok_or_else(|| {
                syn::Error::new_spanned(
                    &cf.ty,
                    "has_one requires a Hopper layout field or Account<'info, T> wrapper",
                )
            })?;
            let target_field_ident = target_ident.clone();
            field_checks.push(quote! {
                {
                    let view = ctx.account(#idx)?;
                    let layout = view.load::<#field_ty>()?;
                    let expected_key = ctx.account(#target_idx)?.address();
                    // Convention: the cross-referenced field on the
                    // layout must be named identically to the target
                    // account's field, and must coerce to an `Address`.
                    if ::core::convert::AsRef::<[u8; 32]>::as_ref(&layout.#target_field_ident)
                        != ::core::convert::AsRef::<[u8; 32]>::as_ref(expected_key)
                    {
                        return ::core::result::Result::Err(
                            ::hopper::__runtime::ProgramError::InvalidAccountData
                        );
                    }
                }
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) .{} must equal accounts[{}] ({}) key",
                idx, field_name, target_name, target_idx, target_name
            ));
        }

        // -- Stage 6: arbitrary `constraint = expr` -----------------------
        for (i, expr) in cf.attr.constraint.iter().enumerate() {
            field_checks.push(quote! {
                if !({ #expr }) {
                    return ::core::result::Result::Err(
                        ::hopper::__runtime::ProgramError::Custom(0xc0_00 | (#idx as u32))
                    );
                }
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) custom constraint #{} must hold",
                idx, field_name, i
            ));
        }

        // -- Stage 7: Anchor SPL parity -----------------------------------
        //
        // token::mint / token::authority / mint::authority / mint::decimals /
        // mint::freeze_authority / associated_token::{mint,authority,token_program}.
        //
        // Each of these lowers to a single call to a `hopper_runtime::token`
        // precondition helper, each of which reads only the exact bytes
        // it needs from the already-borrowed account buffer. no
        // full-struct deserialize, no new crate dependencies.
        //
        // The helpers live in `hopper_runtime::token` (for Token + Mint
        // shape checks) and in `hopper_solana::ata` (for ATA
        // derivation. only on-chain via `#[cfg(target_os = "solana")]`).
        // Owner-program override for the `token::*` family. Emitted
        // exactly once when any `token::mint` / `token::authority` /
        // `token::token_program` is present, so the owner check runs
        // before the byte-level shape checks and rejects a wrong-program
        // account without reading its payload.
        //
        // Default: SPL Token. Explicit `token::token_program = X`
        // routes to X instead (the Token-2022 pattern). A standalone
        // `token::token_program` with no shape check is valid and
        // still enforces owner alone, matching Anchor's behavior.
        let has_token_shape = cf.attr.token_mint.is_some() || cf.attr.token_authority.is_some();
        if has_token_shape || cf.attr.token_token_program.is_some() {
            let prog_expr = if let Some(tp) = &cf.attr.token_token_program {
                quote! { &(#tp) }
            } else {
                quote! { &::hopper::__runtime::token::TOKEN_PROGRAM_ID }
            };
            field_checks.push(quote! {
                ctx.account(#idx)?.check_owned_by(#prog_expr)?;
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) is owned by the declared token program{}",
                idx,
                field_name,
                if cf.attr.token_token_program.is_some() {
                    " (explicit token_program override)"
                } else {
                    " (SPL Token default)"
                }
            ));
        }

        if let Some(expected_mint) = &cf.attr.token_mint {
            field_checks.push(quote! {
                ::hopper::__runtime::token::require_token_mint(
                    ctx.account(#idx)?,
                    &(#expected_mint),
                )?;
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) is a token account for the declared mint",
                idx, field_name
            ));
        }
        if let Some(expected_authority) = &cf.attr.token_authority {
            field_checks.push(quote! {
                ::hopper::__runtime::token::require_token_owner_eq(
                    ctx.account(#idx)?,
                    &(#expected_authority),
                )?;
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) token account authority matches declared authority",
                idx, field_name
            ));
        }
        // Owner-program override for the `mint::*` family. Same
        // pattern as the token-axis check: emit once whenever any
        // `mint::authority` / `mint::decimals` / `mint::freeze_authority` /
        // `mint::token_program` appears, so the owner is pinned before
        // any layout-byte check runs.
        let has_mint_shape = cf.attr.mint_authority.is_some()
            || cf.attr.mint_decimals.is_some()
            || cf.attr.mint_freeze_authority.is_some();
        if has_mint_shape || cf.attr.mint_token_program.is_some() {
            let prog_expr = if let Some(tp) = &cf.attr.mint_token_program {
                quote! { &(#tp) }
            } else {
                quote! { &::hopper::__runtime::token::TOKEN_PROGRAM_ID }
            };
            field_checks.push(quote! {
                ctx.account(#idx)?.check_owned_by(#prog_expr)?;
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) is a mint owned by the declared token program{}",
                idx,
                field_name,
                if cf.attr.mint_token_program.is_some() {
                    " (explicit token_program override)"
                } else {
                    " (SPL Token default)"
                }
            ));
        }

        if let Some(expected_mint_authority) = &cf.attr.mint_authority {
            field_checks.push(quote! {
                ::hopper::__runtime::token::require_mint_authority(
                    ctx.account(#idx)?,
                    &(#expected_mint_authority),
                )?;
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) mint_authority matches declared authority",
                idx, field_name
            ));
        }
        if let Some(decimals_expr) = &cf.attr.mint_decimals {
            field_checks.push(quote! {
                ::hopper::__runtime::token::require_mint_decimals(
                    ctx.account(#idx)?,
                    (#decimals_expr) as u8,
                )?;
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) mint decimals equals declared value",
                idx, field_name
            ));
        }
        if let Some(expected_freeze) = &cf.attr.mint_freeze_authority {
            field_checks.push(quote! {
                ::hopper::__runtime::token::require_mint_freeze_authority(
                    ctx.account(#idx)?,
                    &(#expected_freeze),
                )?;
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) mint freeze_authority matches declared authority",
                idx, field_name
            ));
        }

        // Token-2022 extension constraints. Each lowers to a single
        // TLV-scan call on the Token-2022 account bytes. Extensions
        // are only valid on Token-2022 accounts, so the usual
        // `token::token_program = TOKEN_2022_ID` or
        // `mint::token_program = TOKEN_2022_ID` constraint should
        // precede them in source; the emitted owner check has
        // already run before any of this lowers.
        if cf.attr.ext_non_transferable {
            field_checks.push(quote! {
                ::hopper::__runtime::token_2022_ext::require_non_transferable(
                    ctx.account(#idx)?,
                )?;
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) carries NonTransferable extension",
                idx, field_name
            ));
        }
        if cf.attr.ext_immutable_owner {
            field_checks.push(quote! {
                ::hopper::__runtime::token_2022_ext::require_immutable_owner(
                    ctx.account(#idx)?,
                )?;
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) carries ImmutableOwner extension",
                idx, field_name
            ));
        }
        if let Some(expected) = &cf.attr.ext_mint_close_authority {
            field_checks.push(quote! {
                ::hopper::__runtime::token_2022_ext::require_mint_close_authority(
                    ctx.account(#idx)?,
                    &(#expected),
                )?;
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) MintCloseAuthority matches",
                idx, field_name
            ));
        }
        if let Some(expected) = &cf.attr.ext_permanent_delegate {
            field_checks.push(quote! {
                ::hopper::__runtime::token_2022_ext::require_permanent_delegate(
                    ctx.account(#idx)?,
                    &(#expected),
                )?;
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) PermanentDelegate matches",
                idx, field_name
            ));
        }
        if let Some(expected) = &cf.attr.ext_transfer_hook_authority {
            field_checks.push(quote! {
                ::hopper::__runtime::token_2022_ext::require_transfer_hook_authority(
                    ctx.account(#idx)?,
                    &(#expected),
                )?;
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) TransferHook authority matches",
                idx, field_name
            ));
        }
        if let Some(expected) = &cf.attr.ext_transfer_hook_program {
            field_checks.push(quote! {
                ::hopper::__runtime::token_2022_ext::require_transfer_hook_program(
                    ctx.account(#idx)?,
                    &(#expected),
                )?;
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) TransferHook program_id matches",
                idx, field_name
            ));
        }
        if let Some(expected) = &cf.attr.ext_metadata_pointer_authority {
            field_checks.push(quote! {
                ::hopper::__runtime::token_2022_ext::require_metadata_pointer_authority(
                    ctx.account(#idx)?,
                    &(#expected),
                )?;
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) MetadataPointer authority matches",
                idx, field_name
            ));
        }
        if let Some(expected) = &cf.attr.ext_metadata_pointer_address {
            field_checks.push(quote! {
                ::hopper::__runtime::token_2022_ext::require_metadata_pointer_address(
                    ctx.account(#idx)?,
                    &(#expected),
                )?;
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) MetadataPointer metadata_address matches",
                idx, field_name
            ));
        }
        if let Some(expected) = &cf.attr.ext_default_account_state {
            field_checks.push(quote! {
                ::hopper::__runtime::token_2022_ext::require_default_account_state(
                    ctx.account(#idx)?,
                    (#expected) as u8,
                )?;
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) DefaultAccountState matches",
                idx, field_name
            ));
        }
        if let Some(expected) = &cf.attr.ext_interest_bearing_authority {
            field_checks.push(quote! {
                ::hopper::__runtime::token_2022_ext::require_interest_bearing_authority(
                    ctx.account(#idx)?,
                    &(#expected),
                )?;
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) InterestBearing rate_authority matches",
                idx, field_name
            ));
        }
        if let Some(expected) = &cf.attr.ext_transfer_fee_config_authority {
            field_checks.push(quote! {
                ::hopper::__runtime::token_2022_ext::require_transfer_fee_config_authority(
                    ctx.account(#idx)?,
                    &(#expected),
                )?;
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) TransferFeeConfig authority matches",
                idx, field_name
            ));
        }
        if let Some(expected) = &cf.attr.ext_transfer_fee_withdraw_authority {
            field_checks.push(quote! {
                ::hopper::__runtime::token_2022_ext::require_transfer_fee_withdraw_authority(
                    ctx.account(#idx)?,
                    &(#expected),
                )?;
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) TransferFeeConfig withdraw_authority matches",
                idx, field_name
            ));
        }

        // Metaplex Token Metadata constraints. These are primarily
        // CPI-helper inputs, but validation still performs the cheap
        // data-shape checks up front so an oversized name/symbol/uri
        // fails in Hopper before issuing a Metaplex CPI.
        if let (Some(name_expr), Some(symbol_expr), Some(uri_expr), Some(sfbp_expr)) = (
            &cf.attr.metadata_name,
            &cf.attr.metadata_symbol,
            &cf.attr.metadata_uri,
            &cf.attr.metadata_seller_fee_basis_points,
        ) {
            field_checks.push(quote! {
                ::hopper::hopper_metaplex::DataV2::simple(
                    #name_expr,
                    #symbol_expr,
                    #uri_expr,
                    (#sfbp_expr) as u16,
                ).validate_for_context()?;
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) metadata data fits Metaplex name/symbol/uri limits",
                idx, field_name
            ));
        }

        if let Some(max_supply_expr) = &cf.attr.master_edition_max_supply {
            field_checks.push(quote! {
                let _max_supply: ::core::option::Option<u64> =
                    ::hopper::hopper_metaplex::IntoMasterEditionMaxSupply::into_master_edition_max_supply(
                        #max_supply_expr
                    );
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) master-edition max_supply is a valid u64/Option<u64> value",
                idx, field_name
            ));
        }

        // `dup = other_field`. Require this slot to alias the named
        // other slot. The caller explicitly opted into aliasing by
        // declaring it, which is the safe pattern. If the caller
        // actually passes different accounts, we reject rather than
        // silently accept, matching Quasar's dup semantic.
        if let Some(other) = &cf.attr.dup {
            let other_idx = ctx_fields
                .iter()
                .position(|f| &f.name == other)
                .ok_or_else(|| {
                    syn::Error::new_spanned(
                        other,
                        format!(
                            "`dup = {}` must name a sibling field on the same context",
                            other
                        ),
                    )
                })?;
            field_checks.push(quote! {
                if ctx.account(#idx)?.address() != ctx.account(#other_idx)?.address() {
                    return ::core::result::Result::Err(
                        ::hopper::__runtime::ProgramError::InvalidAccountData
                    );
                }
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) aliases accounts[{}] ({})",
                idx, field_name, other_idx, other
            ));
        }
        // ATA derivation: both mint and authority must be declared to
        // be verifiable. Validation enforces that in
        // `validate_account_attr`. Here we can assume the pair is
        // coherent.
        if let (Some(ata_mint), Some(ata_auth)) = (
            &cf.attr.associated_token_mint,
            &cf.attr.associated_token_authority,
        ) {
            // Optional token-program override. when omitted we fall
            // back to the canonical SPL Token program ID re-exported
            // from `hopper_runtime::token`.
            let token_program_expr = if let Some(tp) = &cf.attr.associated_token_token_program {
                quote! { &(#tp) }
            } else {
                quote! { &::hopper::__runtime::token::TOKEN_PROGRAM_ID }
            };
            field_checks.push(quote! {
                {
                    // On-chain PDA derivation is only available when
                    // targeting the Solana runtime. Off-chain tooling
                    // (IDL dumps, hopper-sdk) does not build these
                    // checks into the same binary, so we gate the
                    // call under the Solana target triple.
                    //
                    // `derive_ata_for_program` returns `(Address, u8)`.
                    // We only need the address; the bump byte is
                    // meaningful only if the caller wants to cache it
                    // in account data.
                    #[cfg(target_os = "solana")]
                    {
                        let (expected, _bump) =
                            ::hopper::hopper_associated_token::derive_ata_for_program(
                                &(#ata_auth),
                                &(#ata_mint),
                                #token_program_expr,
                            );
                        if ctx.account(#idx)?.address() != &expected {
                            return ::core::result::Result::Err(
                                ::hopper::__runtime::ProgramError::InvalidSeeds
                            );
                        }
                    }
                }
            });
            check_descriptions.push(format!(
                "accounts[{}] ({}) is the ATA for (authority, mint, token_program)",
                idx, field_name
            ));
        }

        if !field_checks.is_empty() {
            // When the user declared `#[instruction(...)]` at the struct
            // level, every per-field validator threads the declared
            // args through its signature. The fragment
            // `#(#arg_params),*` expands to an empty token span when
            // `has_instruction_args` is false, so the args-less case
            // is still `fn validate_<field>(ctx: &Context<'_>)` exactly
            // as before. The leading comma is guarded the same way,
            // giving us a single unified emission path.
            // Quote's repetition `#(#v)*` consumes `v` via `IntoIterator`,
            // so we clone the arg token streams per call site. this matches
            // the pattern used in `error.rs` (`idents_for_from`,
            // `idents_for_code`, etc.) and keeps the outer loop safe.
            let arg_param_fragment = if has_instruction_args {
                let aps = arg_params.clone();
                quote! { , #(#aps),* }
            } else {
                TokenStream::new()
            };
            let arg_name_fragment = if has_instruction_args {
                let ans = arg_names.clone();
                quote! { , #(#ans),* }
            } else {
                TokenStream::new()
            };
            per_field_validators.push(quote! {
                /// Validate the `#field_name` account (index #idx).
                #[inline(always)]
                #vis fn #validate_fn(
                    ctx: &::hopper::prelude::Context<'_>
                    #arg_param_fragment
                ) -> ::core::result::Result<(), ::hopper::__runtime::ProgramError> {
                    #(#field_checks)*
                    Ok(())
                }
            });

            // Monolithic `validate` / `validate_with_args` composition.
            // Forwards whatever args were declared at the struct level
            // so each per-field validator sees the same typed bindings.
            validation_stmts.push(quote! {
                Self::#validate_fn(ctx #arg_name_fragment)?;
            });
        }
    }

    let check_desc_literals: Vec<_> = check_descriptions.iter().map(|s| quote! { #s }).collect();
    let check_count = check_descriptions.len();

    // Generate segment accessor methods with const segment bindings.
    let mut accessors = Vec::new();

    for cf in &ctx_fields {
        let field_name = &cf.name;
        let idx = cf.index;
        let layout_ty = layout_type_for_field(cf);
        let display_ty = layout_ty.as_ref().unwrap_or(&cf.ty);
        let type_ident = type_ident(display_ty)?;
        let type_upper = to_screaming_snake(&type_ident.to_string());

        // `sweep = target` emits an inherent method `sweep_<field>()`
        // on the bound context. The method moves every remaining
        // lamport from this slot into the target slot. Calling it is
        // up to the user: bind() does not auto-run sweeps because
        // handler semantics (short-circuit on error, skip cleanup on
        // failure) vary per program. Typically called in the happy
        // path right before the handler returns Ok.
        if let Some(target) = &cf.attr.sweep {
            let target_idx = ctx_fields
                .iter()
                .position(|f| &f.name == target)
                .ok_or_else(|| {
                    syn::Error::new_spanned(
                        target,
                        format!(
                            "`sweep = {}` must name a sibling field on the same context",
                            target
                        ),
                    )
                })?;
            let sweep_fn = format_ident!("sweep_{}", field_name);
            accessors.push(quote! {
                /// Drain every lamport from this slot into the declared
                /// sweep target. Call in the happy path just before
                /// returning. Returns the drained amount.
                #[inline]
                #vis fn #sweep_fn(&mut self)
                    -> ::core::result::Result<u64, ::hopper::__runtime::ProgramError>
                {
                    let src = self.ctx.account(#idx)?;
                    let dst = self.ctx.account(#target_idx)?;
                    let amount = src.lamports();
                    if amount == 0 {
                        return Ok(0);
                    }
                    src.try_borrow_mut_lamports()?
                        .checked_sub(amount)
                        .map(|v| *src.try_borrow_mut_lamports().unwrap() = v)
                        .ok_or(::hopper::__runtime::ProgramError::ArithmeticOverflow)?;
                    let dst_lam = dst.try_borrow_mut_lamports()?;
                    *dst_lam = dst_lam
                        .checked_add(amount)
                        .ok_or(::hopper::__runtime::ProgramError::ArithmeticOverflow)?;
                    Ok(amount)
                }
            });
        }

        let account_fn = format_ident!("{}_account", field_name);
        accessors.push(quote! {
            /// Return the underlying Hopper account view for `#field_name`.
            #[inline(always)]
            #vis fn #account_fn(
                &self,
            ) -> ::core::result::Result<
                &::hopper::prelude::AccountView,
                ::hopper::__runtime::ProgramError,
            > {
                self.ctx.account(#idx)
            }
        });

        if let Some(field_ty) = layout_ty.as_ref() {
            let load_fn = format_ident!("{}_load", field_name);
            let raw_ref_fn = format_ident!("{}_raw_ref", field_name);

            accessors.push(quote! {
                /// Validate and load the full typed layout for `#field_name`.
                #[inline(always)]
                #vis fn #load_fn(
                    &self,
                ) -> ::core::result::Result<
                    ::hopper::__runtime::Ref<'_, #field_ty>,
                    ::hopper::__runtime::ProgramError,
                > {
                    self.ctx.account(#idx)?.load::<#field_ty>()
                }
            });

            accessors.push(quote! {
                /// Explicit raw typed read of the full buffer for `#field_name`.
                #[inline(always)]
                #vis fn #raw_ref_fn(
                    &self,
                ) -> ::core::result::Result<
                    ::hopper::__runtime::Ref<'_, #field_ty>,
                    ::hopper::__runtime::ProgramError,
                > {
                    unsafe { self.ctx.account(#idx)?.raw_ref::<#field_ty>() }
                }
            });

            if cf.attr.is_mut {
                let load_mut_fn = format_ident!("{}_load_mut", field_name);
                let raw_mut_fn = format_ident!("{}_raw_mut", field_name);
                let segment_mut_fn = format_ident!("{}_segment_mut", field_name);
                let segment_ref_fn = format_ident!("{}_segment_ref", field_name);

                accessors.push(quote! {
                    /// Validate and mutably load the full typed layout for `#field_name`.
                    #[inline(always)]
                    #vis fn #load_mut_fn(
                        &self,
                    ) -> ::core::result::Result<
                        ::hopper::__runtime::RefMut<'_, #field_ty>,
                        ::hopper::__runtime::ProgramError,
                    > {
                        self.ctx.account(#idx)?.load_mut::<#field_ty>()
                    }
                });

                accessors.push(quote! {
                    /// Explicit raw typed write of the full buffer for `#field_name`.
                    #[inline(always)]
                    #vis fn #raw_mut_fn(
                        &self,
                    ) -> ::core::result::Result<
                        ::hopper::__runtime::RefMut<'_, #field_ty>,
                        ::hopper::__runtime::ProgramError,
                    > {
                        unsafe { self.ctx.account(#idx)?.raw_mut::<#field_ty>() }
                    }
                });

                // General-purpose typed segment escape for full-mut fields.
                // Lets callers project any segment of `#field_name` without
                // pre-declaring it via `mut(field1, field2)`. The `abs_offset`
                // argument is intended to be a const segment offset (e.g.
                // `HEADER_LEN as u32 + VAULT_BALANCE_OFFSET`) so the call
                // collapses to the same const arithmetic as the named accessors.
                accessors.push(quote! {
                    /// Mutable segment escape: project an arbitrary
                    /// typed sub-slice of `#field_name`. Borrow tracking
                    /// is registered against the instruction-scoped
                    /// segment registry as a RAII **lease**. the
                    /// returned [`SegRefMut`] releases both the account
                    /// byte guard and the registry entry on drop.
                    #[inline(always)]
                    #vis fn #segment_mut_fn<__SegT: ::hopper::__runtime::Pod>(
                        &mut self,
                        abs_offset: u32,
                    ) -> ::core::result::Result<
                        ::hopper::__runtime::SegRefMut<'_, __SegT>,
                        ::hopper::__runtime::ProgramError,
                    > {
                        self.ctx.segment_mut::<__SegT>(#idx, abs_offset)
                    }
                });

                accessors.push(quote! {
                    /// Read-only segment escape: project an arbitrary
                    /// typed sub-slice of `#field_name`. The returned
                    /// [`SegRef`] is a RAII-leased guard that releases
                    /// the shared byte borrow on drop, so the same
                    /// account can be accessed in non-overlapping
                    /// segments sequentially within one instruction.
                    /// For pre-declared `read(...)` segments, prefer
                    /// the field-specific `<field>_<seg>_ref()`
                    /// accessor for type safety and clarity.
                    #[inline(always)]
                    #vis fn #segment_ref_fn<__SegT: ::hopper::__runtime::Pod>(
                        &mut self,
                        abs_offset: u32,
                    ) -> ::core::result::Result<
                        ::hopper::__runtime::SegRef<'_, __SegT>,
                        ::hopper::__runtime::ProgramError,
                    > {
                        self.ctx.segment_ref::<__SegT>(#idx, abs_offset)
                    }
                });
            }
        }

        // Generate mutable segment accessors.
        //
        // We reference both the module-level constants (`VAULT_BALANCE_OFFSET`,
        // `VAULT_BALANCE_TYPE`) emitted by `#[hopper::state]` and the inherent
        // associated constants (`Vault::BALANCE_OFFSET`) it also emits. Using
        // the inherent constant for the offset means contexts compile cleanly
        // even when the layout type is imported from another module.
        if let Some(field_ty) = layout_ty.as_ref() {
            for seg_name in &cf.attr.mut_segments {
                let fn_name = format_ident!("{}_{}_mut", field_name, seg_name);
                let seg_upper = to_screaming_snake(seg_name);
                let assoc_offset = format_ident!("{}_OFFSET", seg_upper);
                let type_alias = format_ident!("{}_{}_TYPE", type_upper, seg_upper);

                accessors.push(quote! {
                    /// Mutable access to the `#seg_name` segment of `#field_name`.
                    ///
                    /// Returns a [`SegRefMut`](::hopper::__runtime::SegRefMut)
                    ///. a RAII-leased guard that releases both the account
                    /// byte borrow and the segment registry entry on drop.
                    #[inline(always)]
                    #vis fn #fn_name(
                        &mut self,
                    ) -> ::core::result::Result<
                        ::hopper::__runtime::SegRefMut<'_, #type_alias>,
                        ::hopper::__runtime::ProgramError,
                    > {
                        // const offset folded at the call site; this lowers to a
                        // single immediate add over `data_ptr` on Solana SBF.
                        const ABS_OFFSET: u32 =
                            ::hopper::hopper_core::account::HEADER_LEN as u32 + <#field_ty>::#assoc_offset;
                        self.ctx.segment_mut::<#type_alias>(#idx, ABS_OFFSET)
                    }
                });
            }
        }

        // Generate read-only segment accessors.
        if let Some(field_ty) = layout_ty.as_ref() {
            for seg_name in &cf.attr.read_segments {
                let fn_name = format_ident!("{}_{}_ref", field_name, seg_name);
                let seg_upper = to_screaming_snake(seg_name);
                let assoc_offset = format_ident!("{}_OFFSET", seg_upper);
                let type_alias = format_ident!("{}_{}_TYPE", type_upper, seg_upper);

                accessors.push(quote! {
                    /// Read-only access to the `#seg_name` segment of `#field_name`.
                    ///
                    /// Returns a [`SegRef`](::hopper::__runtime::SegRef) - a
                    /// RAII-leased guard that releases the shared byte borrow
                    /// on drop, allowing sequential non-overlapping reads
                    /// from the same account within one instruction.
                    #[inline(always)]
                    #vis fn #fn_name(
                        &mut self,
                    ) -> ::core::result::Result<
                        ::hopper::__runtime::SegRef<'_, #type_alias>,
                        ::hopper::__runtime::ProgramError,
                    > {
                        const ABS_OFFSET: u32 =
                            ::hopper::hopper_core::account::HEADER_LEN as u32 + <#field_ty>::#assoc_offset;
                        self.ctx.segment_ref::<#type_alias>(#idx, ABS_OFFSET)
                    }
                });
            }
        }
    }

    // ── Stage 2.4 lifecycle helpers (init / realloc / close) ───────────
    //
    // Emit `init_{field}()`, `realloc_{field}()`, and `close_{field}()`
    // methods on the bound context struct so programs can execute the
    // account-lifecycle step declared in `#[account(init/realloc/close)]`
    // with one call instead of hand-plumbing the System Program CPI
    // sequence + header write + receipt.
    //
    // The helpers call into the existing declarative macros
    // (`hopper_init!`, `hopper_close!`) so there's exactly one code
    // path for CPI + zero-init + header write. That also means
    // lifecycle flows honor whatever policy those declarative macros
    // enforce (rent-exempt minimum, sentinel-protected close, etc.).
    for cf in &ctx_fields {
        let field_name = &cf.name;
        let layout_ty = layout_type_for_field(cf);
        let field_ty = layout_ty.as_ref().unwrap_or(&cf.ty);
        let idx = cf.index;

        if cf.attr.init || cf.attr.init_if_needed {
            let is_if_needed = cf.attr.init_if_needed;
            let init_fn = format_ident!("init_{}", field_name);
            let payer_ident = cf
                .attr
                .payer
                .as_ref()
                .expect("validate_account_attr guarantees init/init_if_needed has payer");
            let payer_idx = ctx_fields
                .iter()
                .position(|c| c.name == *payer_ident)
                .ok_or_else(|| {
                    syn::Error::new_spanned(
                        payer_ident,
                        format!(
                            "init payer `{}`: no field named `{}` in this context",
                            payer_ident, payer_ident
                        ),
                    )
                })?;
            // Find the system_program field. by convention named
            // `system_program` and typed as AccountView or Program<'info, System>.
            let system_program_idx = ctx_fields
                .iter()
                .position(|c| c.name == format_ident!("system_program"))
                .ok_or_else(|| {
                    syn::Error::new_spanned(
                        field_name,
                        "#[account(init | init_if_needed)] requires a `system_program` field in the context",
                    )
                })?;

            // Two emission shapes:
            //
            //   init            - call hopper_init! to create or allocate+assign
            //                     a zero-data account, then write the header.
            //
            //   init_if_needed  - skip the lifecycle CPI entirely
            //                     when the account already has data.
            //                     The account is then assumed to be
            //                     set up by a prior invocation; the
            //                     caller is responsible for verifying
            //                     the existing layout separately.
            let body = if is_if_needed {
                quote! {
                    let account = self.ctx.account(#idx)?;
                    if account.data_len() > 0 {
                        // Already allocated; nothing to do. Caller
                        // should still validate the layout via
                        // `<ctx>_load()` or equivalent.
                        return ::core::result::Result::Ok(());
                    }
                    let payer = self.ctx.account(#payer_idx)?;
                    let system_program = self.ctx.account(#system_program_idx)?;
                    ::hopper::hopper_init!(
                        payer,
                        account,
                        system_program,
                        self.ctx.program_id(),
                        #field_ty
                    )
                }
            } else {
                quote! {
                    let payer = self.ctx.account(#payer_idx)?;
                    let account = self.ctx.account(#idx)?;
                    let system_program = self.ctx.account(#system_program_idx)?;
                    ::hopper::hopper_init!(
                        payer,
                        account,
                        system_program,
                        self.ctx.program_id(),
                        #field_ty
                    )
                }
            };

            let doc = if is_if_needed {
                "Create or allocate+assign the account via System Program CPI if it doesn't exist yet (init_if_needed). \
                 If the account is already allocated (data_len > 0) the helper returns Ok(()) without \
                 touching lamports or data - caller is responsible for validating the existing layout."
            } else {
                "Create or allocate+assign the account via System Program CPI, zero-init its data, and write the Hopper header. \
                  Errors if the account already has data."
            };

            accessors.push(quote! {
                #[doc = #doc]
                #[inline]
                #vis fn #init_fn(&self) -> ::core::result::Result<(), ::hopper::__runtime::ProgramError> {
                    #body
                }
            });
        }

        if let (
            Some(name_expr),
            Some(symbol_expr),
            Some(uri_expr),
            Some(sfbp_expr),
            Some(mint_ident),
            Some(mint_authority_ident),
            Some(payer_ident),
            Some(update_authority_ident),
            Some(system_program_ident),
        ) = (
            &cf.attr.metadata_name,
            &cf.attr.metadata_symbol,
            &cf.attr.metadata_uri,
            &cf.attr.metadata_seller_fee_basis_points,
            &cf.attr.metadata_mint,
            &cf.attr.metadata_mint_authority,
            &cf.attr.metadata_payer,
            &cf.attr.metadata_update_authority,
            &cf.attr.metadata_system_program,
        ) {
            let create_fn = format_ident!("create_{}", field_name);
            let mint_idx = sibling_index(&ctx_fields, mint_ident, "metadata::mint")?;
            let mint_authority_idx = sibling_index(
                &ctx_fields,
                mint_authority_ident,
                "metadata::mint_authority",
            )?;
            let payer_idx = sibling_index(&ctx_fields, payer_ident, "metadata::payer")?;
            let update_authority_idx = sibling_index(
                &ctx_fields,
                update_authority_ident,
                "metadata::update_authority",
            )?;
            let system_program_idx = sibling_index(
                &ctx_fields,
                system_program_ident,
                "metadata::system_program",
            )?;
            let rent_expr = if let Some(rent_ident) = &cf.attr.metadata_rent {
                let rent_idx = sibling_index(&ctx_fields, rent_ident, "metadata::rent")?;
                quote! { ::core::option::Option::Some(self.ctx.account(#rent_idx)?) }
            } else {
                quote! { ::core::option::Option::None }
            };
            let is_mutable_expr = if let Some(expr) = &cf.attr.metadata_is_mutable {
                quote! { (#expr) }
            } else {
                quote! { true }
            };
            let method_arg_fragment = if has_instruction_args {
                let aps = arg_params.clone();
                quote! { , #(#aps),* }
            } else {
                TokenStream::new()
            };

            accessors.push(quote! {
                /// Invoke Metaplex `CreateMetadataAccountV3` using the
                /// `metadata::*` accounts and data declared on this field.
                #[inline]
                #vis fn #create_fn(
                    &self
                    #method_arg_fragment
                ) -> ::core::result::Result<(), ::hopper::__runtime::ProgramError> {
                    ::hopper::hopper_metaplex::CreateMetadataAccountV3 {
                        metadata: self.ctx.account(#idx)?,
                        mint: self.ctx.account(#mint_idx)?,
                        mint_authority: self.ctx.account(#mint_authority_idx)?,
                        payer: self.ctx.account(#payer_idx)?,
                        update_authority: self.ctx.account(#update_authority_idx)?,
                        system_program: self.ctx.account(#system_program_idx)?,
                        rent: #rent_expr,
                        data: ::hopper::hopper_metaplex::DataV2::simple(
                            #name_expr,
                            #symbol_expr,
                            #uri_expr,
                            (#sfbp_expr) as u16,
                        ),
                        is_mutable: #is_mutable_expr,
                    }.invoke()
                }
            });
        }

        if let (
            Some(max_supply_expr),
            Some(mint_ident),
            Some(metadata_ident),
            Some(update_authority_ident),
            Some(mint_authority_ident),
            Some(payer_ident),
            Some(token_program_ident),
            Some(system_program_ident),
        ) = (
            &cf.attr.master_edition_max_supply,
            &cf.attr.master_edition_mint,
            &cf.attr.master_edition_metadata,
            &cf.attr.master_edition_update_authority,
            &cf.attr.master_edition_mint_authority,
            &cf.attr.master_edition_payer,
            &cf.attr.master_edition_token_program,
            &cf.attr.master_edition_system_program,
        ) {
            let create_fn = format_ident!("create_{}", field_name);
            let mint_idx = sibling_index(&ctx_fields, mint_ident, "master_edition::mint")?;
            let metadata_idx =
                sibling_index(&ctx_fields, metadata_ident, "master_edition::metadata")?;
            let update_authority_idx = sibling_index(
                &ctx_fields,
                update_authority_ident,
                "master_edition::update_authority",
            )?;
            let mint_authority_idx = sibling_index(
                &ctx_fields,
                mint_authority_ident,
                "master_edition::mint_authority",
            )?;
            let payer_idx = sibling_index(&ctx_fields, payer_ident, "master_edition::payer")?;
            let token_program_idx = sibling_index(
                &ctx_fields,
                token_program_ident,
                "master_edition::token_program",
            )?;
            let system_program_idx = sibling_index(
                &ctx_fields,
                system_program_ident,
                "master_edition::system_program",
            )?;
            let rent_expr = if let Some(rent_ident) = &cf.attr.master_edition_rent {
                let rent_idx = sibling_index(&ctx_fields, rent_ident, "master_edition::rent")?;
                quote! { ::core::option::Option::Some(self.ctx.account(#rent_idx)?) }
            } else {
                quote! { ::core::option::Option::None }
            };
            let method_arg_fragment = if has_instruction_args {
                let aps = arg_params.clone();
                quote! { , #(#aps),* }
            } else {
                TokenStream::new()
            };

            accessors.push(quote! {
                /// Invoke Metaplex `CreateMasterEditionV3` using the
                /// `master_edition::*` accounts and max_supply declared
                /// on this field.
                #[inline]
                #vis fn #create_fn(
                    &self
                    #method_arg_fragment
                ) -> ::core::result::Result<(), ::hopper::__runtime::ProgramError> {
                    let __max_supply: ::core::option::Option<u64> =
                        ::hopper::hopper_metaplex::IntoMasterEditionMaxSupply::into_master_edition_max_supply(
                            #max_supply_expr
                        );
                    ::hopper::hopper_metaplex::CreateMasterEditionV3 {
                        edition: self.ctx.account(#idx)?,
                        mint: self.ctx.account(#mint_idx)?,
                        update_authority: self.ctx.account(#update_authority_idx)?,
                        mint_authority: self.ctx.account(#mint_authority_idx)?,
                        payer: self.ctx.account(#payer_idx)?,
                        metadata: self.ctx.account(#metadata_idx)?,
                        token_program: self.ctx.account(#token_program_idx)?,
                        system_program: self.ctx.account(#system_program_idx)?,
                        rent: #rent_expr,
                        max_supply: __max_supply,
                    }.invoke()
                }
            });
        }

        if let Some(close_target) = &cf.attr.close {
            let close_fn = format_ident!("close_{}", field_name);
            let close_target_idx = ctx_fields
                .iter()
                .position(|c| c.name == *close_target)
                .ok_or_else(|| {
                    syn::Error::new_spanned(
                        close_target,
                        format!(
                            "close target `{}`: no field named `{}` in this context",
                            close_target, close_target
                        ),
                    )
                })?;
            accessors.push(quote! {
                /// Drain lamports from `#field_name` into the declared
                /// close target and mark the data for reclaim. Uses the
                /// sentinel-protected close path so a double-close (via
                /// a re-entered instruction) is detected rather than
                /// silently zeroing a reused account.
                #[inline]
                #vis fn #close_fn(&self) -> ::core::result::Result<(), ::hopper::__runtime::ProgramError> {
                    let account = self.ctx.account(#idx)?;
                    let destination = self.ctx.account(#close_target_idx)?;
                    ::hopper::hopper_close!(account, destination)
                }
            });
        }

        if let Some(realloc_expr) = &cf.attr.realloc {
            let realloc_fn = format_ident!("realloc_{}", field_name);
            let zero = cf.attr.realloc_zero;
            let payer_path = cf
                .attr
                .realloc_payer
                .as_ref()
                .map(|p_ident| {
                    let p_idx = ctx_fields
                        .iter()
                        .position(|c| c.name == *p_ident)
                        .ok_or_else(|| {
                            syn::Error::new_spanned(
                                p_ident,
                                format!(
                                    "realloc_payer `{}`: no field named `{}` in this context",
                                    p_ident, p_ident
                                ),
                            )
                        })?;
                    Ok::<_, syn::Error>(quote! { Some(self.ctx.account(#p_idx)?) })
                })
                .transpose()?
                .unwrap_or_else(|| quote! { None });

            accessors.push(quote! {
                /// Resize `#field_name`'s data to the declared length,
                /// topping up the rent-exempt lamport minimum from the
                /// declared `realloc_payer` if needed, and zero-filling
                /// any newly-appended bytes per `realloc_zero` policy.
                #[inline]
                #vis fn #realloc_fn(&self) -> ::core::result::Result<(), ::hopper::__runtime::ProgramError> {
                    let account = self.ctx.account(#idx)?;
                    let new_len: usize = (#realloc_expr) as usize;
                    let old_len = account.data_len() as usize;
                    ::hopper::__runtime::__hopper_native::batch::realloc_checked(
                        account,
                        new_len,
                        #payer_path,
                    )?;
                    if #zero && new_len > old_len {
                        let mut data = account.try_borrow_mut()?;
                        for byte in data[old_len..new_len].iter_mut() {
                            *byte = 0;
                        }
                    }
                    ::core::result::Result::Ok(())
                }
            });
        }
    }

    let mut receipt_scope_fields = Vec::new();
    let mut receipt_begin_inits = Vec::new();
    let mut receipt_finish_blocks = Vec::new();

    for cf in &ctx_fields {
        let Some(field_ty) = layout_type_for_field(cf) else {
            continue;
        };
        if !(cf.attr.is_mut || !cf.attr.mut_segments.is_empty()) {
            continue;
        }

        let field_name = &cf.name;
        let idx = cf.index;
        let receipt_field_name = format_ident!("{}_receipt", field_name);
        let layout_ident = type_ident(&field_ty)?;

        receipt_scope_fields.push(quote! {
            #receipt_field_name: ::hopper::receipt::StateReceipt<SNAP>,
        });

        receipt_begin_inits.push(quote! {
            #receipt_field_name: {
                let account = ctx.account(#idx)?;
                let data = account.try_borrow()?;
                ::hopper::receipt::StateReceipt::<SNAP>::begin(
                    &<#field_ty as ::hopper::hopper_runtime::LayoutContract>::LAYOUT_ID,
                    &data,
                )
            }
        });

        let segment_pairs: Vec<_> = if cf.attr.mut_segments.is_empty() {
            vec![quote! {
                (
                    ::hopper::hopper_core::account::HEADER_LEN,
                    <#field_ty as ::hopper::hopper_runtime::LayoutContract>::SIZE
                        - ::hopper::hopper_core::account::HEADER_LEN,
                )
            }]
        } else {
            let type_upper = to_screaming_snake(&layout_ident.to_string());
            cf.attr
                .mut_segments
                .iter()
                .map(|seg_name| {
                    let seg_upper = to_screaming_snake(seg_name);
                    let offset_const = format_ident!("{}_{}_OFFSET", type_upper, seg_upper);
                    let size_const = format_ident!("{}_{}_SIZE", type_upper, seg_upper);
                    quote! {
                        (
                            ::hopper::hopper_core::account::HEADER_LEN + #offset_const as usize,
                            #size_const as usize,
                        )
                    }
                })
                .collect()
        };

        receipt_finish_blocks.push(quote! {
            {
                let account = ctx.account(#idx)?;
                let data = account.try_borrow()?;
                self.#receipt_field_name.commit_with_segments(&data, &[#(#segment_pairs),*]);
                self.#receipt_field_name.set_invariants(invariants_passed, invariants_checked);
                // If a failure was recorded for this instruction, stamp the
                // receipt *before* emission so off-chain consumers can map the
                // code → invariant name via the program's ErrorRegistry.
                if let ::core::option::Option::Some((__hp_code, __hp_idx, __hp_stage)) = failure {
                    self.#receipt_field_name.set_failure(__hp_code, __hp_idx, __hp_stage);
                }
                ::hopper::receipt::emit_receipt(&self.#receipt_field_name.to_bytes())?;
            }
        });
    }

    let account_count = ctx_fields.len();
    let receipt_expected = !receipt_scope_fields.is_empty();
    let mutable_account_count = receipt_scope_fields.len();

    // ── Stage 2.5 schema-metadata emission (audit ST2/D4 closure) ──
    //
    // For every `#[hopper::context]` struct, emit a `const
    // SCHEMA_METADATA: ContextDescriptor` that captures every audit-
    // grade constraint field so downstream tooling (IDL generators,
    // Codama, client builders, `hopper compile --emit schema`) can
    // consume the full picture without re-parsing the source. The
    // same data is available at runtime via
    // `Deposit::SCHEMA_METADATA` and at compile time as a `const`.
    let account_schema_entries: Vec<TokenStream> = ctx_fields
        .iter()
        .map(|cf| {
            let name_lit = cf.name.to_string();
            let layout_ty = layout_type_for_field(cf);
            let display_ty = layout_ty.as_ref().unwrap_or(&cf.ty);
            let kind_lit = type_ident(display_ty)
                .map(|i| i.to_string())
                .unwrap_or_else(|_| "AccountView".to_string());
            let layout_lit = if layout_ty.is_some() {
                kind_lit.clone()
            } else {
                String::new()
            };
            let writable = cf.attr.is_mut || !cf.attr.mut_segments.is_empty();
            let signer = cf.attr.is_signer;
            let optional = false;
            let seeds_lits: Vec<String> = cf
                .attr
                .seeds
                .as_deref()
                .unwrap_or(&[])
                .iter()
                .map(|e| quote!(#e).to_string())
                .collect();
            let has_one_lits: Vec<String> = cf.attr.has_one.iter().map(|i| i.to_string()).collect();
            let lifecycle_path = if cf.attr.init {
                quote! { ::hopper::hopper_schema::accounts::AccountLifecycle::Init }
            } else if cf.attr.realloc.is_some() {
                quote! { ::hopper::hopper_schema::accounts::AccountLifecycle::Realloc }
            } else if cf.attr.close.is_some() {
                quote! { ::hopper::hopper_schema::accounts::AccountLifecycle::Close }
            } else {
                quote! { ::hopper::hopper_schema::accounts::AccountLifecycle::Existing }
            };
            let payer_lit = cf
                .attr
                .payer
                .as_ref()
                .map(|i| i.to_string())
                .unwrap_or_default();
            let init_space_expr = if let Some(expr) = &cf.attr.space {
                quote! { (#expr) as u32 }
            } else {
                quote! { 0u32 }
            };
            let expected_address_lit = cf
                .attr
                .address
                .as_ref()
                .map(|e| quote!(#e).to_string())
                .unwrap_or_default();
            let expected_owner_lit = cf
                .attr
                .owner
                .as_ref()
                .map(|e| quote!(#e).to_string())
                .unwrap_or_default();

            quote! {
                ::hopper::hopper_schema::accounts::ContextAccountDescriptor {
                    name: #name_lit,
                    kind: #kind_lit,
                    writable: #writable,
                    signer: #signer,
                    layout_ref: #layout_lit,
                    policy_ref: "",
                    seeds: &[ #( #seeds_lits ),* ],
                    optional: #optional,
                    lifecycle: #lifecycle_path,
                    payer: #payer_lit,
                    init_space: #init_space_expr,
                    has_one: &[ #( #has_one_lits ),* ],
                    expected_address: #expected_address_lit,
                    expected_owner: #expected_owner_lit,
                }
            }
        })
        .collect();

    let ctx_name_lit = name.to_string();

    // Precomputed signature / call-site fragments for the top-level
    // `validate` / `bind` entry points. Kept as one-shot `TokenStream`s
    // so the `quote! { ... }` block below stays readable. The leading
    // comma is only emitted when there are actually args to declare. // which is how we keep the args-less case byte-for-byte identical
    // to pre-instruction-args output.
    let top_arg_param_fragment = if has_instruction_args {
        let aps = arg_params.clone();
        quote! { , #(#aps),* }
    } else {
        TokenStream::new()
    };
    let top_arg_name_fragment = if has_instruction_args {
        let names = arg_names.clone();
        quote! { , #(#names),* }
    } else {
        TokenStream::new()
    };

    // ── Tooling surface for declared instruction args ─────────────────
    //
    // Expose the declared arg list as `(name, canonical_type)` pairs
    // so tooling (hopper-sdk, Codama, IDL generators) can see the
    // context's instruction-arg contract without re-parsing source.
    // The canonical-type rendering is best-effort: we stringify the
    // Rust type via `quote`, matching the same vocabulary the
    // `#[hopper::args]` derive already uses ("u64", "[u8; 32]", etc.).
    //
    // Emitted as a `pub const CONTEXT_ARGS: &[(&str, &str)]` on the
    // impl block (see the `quote!` block below). We keep this off
    // `ContextDescriptor` for now so this change remains purely
    // additive. the schema crate can grow a dedicated field in a
    // future pass without breaking the runtime ABI here.
    let context_arg_entries: Vec<TokenStream> = instruction_args
        .iter()
        .map(|a| {
            let n = a.name.to_string();
            let ty = &a.ty;
            let t = quote!(#ty).to_string();
            quote! { (#n, #t) }
        })
        .collect();

    // ── Bumps struct (Anchor-parity ergonomic) ─────────────────────
    //
    // For every field with a `seeds = ...` constraint, emit a `u8`
    // slot on `<Name>Bumps` and populate it during `bind()`. The
    // resulting struct is reachable as `ctx.bumps()` on the bound
    // context, which is exactly what a CPI signer-seeds block wants:
    //
    //   let bumps = vault_ctx.bumps();
    //   let seeds: &[&[u8]] = &[b"vault", authority.as_ref(), &[bumps.vault]];
    //
    // Contexts with zero PDAs still get a unit-ish `struct <Name>Bumps {}`
    // so downstream code can spell the type unconditionally. `#[derive]`
    // is split: `Default` is always on (so construction is trivial),
    // `Copy / Clone / Debug` only when at least one field exists (an
    // empty-fields struct still derives them cleanly, so emit both
    // paths identically for simplicity).
    let bumps_name = format_ident!("{}Bumps", name);
    let bumps_field_defs: Vec<TokenStream> = bump_entries
        .iter()
        .map(|(ident, _)| quote! { pub #ident: u8, })
        .collect();
    let bumps_gather_stmts: Vec<TokenStream> = bump_entries
        .iter()
        .map(|(ident, expr)| quote! { __hopper_bumps.#ident = #expr; })
        .collect();
    let bumps_registry_entries: Vec<TokenStream> = bump_entries
        .iter()
        .map(|(ident, _)| {
            let s = ident.to_string();
            quote! { #s }
        })
        .collect();

    // Emit the user-validate call only when the author opted in.
    // The call is spelled `<Bound>::validate(&bound)` so a user who
    // forgets to define the method sees a clean "no method named
    // `validate`" error pointing at their own impl block, not at
    // macro-generated code.
    let user_validate_call: TokenStream = if user_validate {
        quote! {
            #bound_name::validate(&__hopper_bound)?;
        }
    } else {
        TokenStream::new()
    };

    // When called from `#[derive(Accounts)]` the struct already exists in
    // the user's source. Skip re-emitting it - emitting twice would be a
    // duplicate-definition error. When called from `#[hopper::context]`
    // we keep the original passthrough since attribute macros own the
    // item they decorate.
    let original_struct: TokenStream = if emit_struct {
        quote! { #input }
    } else {
        TokenStream::new()
    };

    let expanded = quote! {
        // Emit the original struct unchanged (attribute macro path only).
        #original_struct

        /// Captured PDA bumps for every `seeds = ...` field in this
        /// context. One `u8` slot per PDA, named after the field. Read
        /// from the bound context as `ctx.bumps().<field>` and hand
        /// straight to a CPI signer-seeds block.
        ///
        /// Anchor's `ctx.bumps.<field>` pattern, spelled out: the field
        /// set is derived at macro-expansion time from the fields that
        /// carry `seeds`, so there is zero runtime lookup and zero
        /// allocation. A context with no PDA fields still gets a valid
        /// type (empty body) so downstream code can name it uniformly.
        #[derive(::core::default::Default, ::core::clone::Clone, ::core::marker::Copy, ::core::fmt::Debug)]
        #vis struct #bumps_name {
            #( #bumps_field_defs )*
        }

        impl #bumps_name {
            /// Field names that carry a PDA bump, in declaration order.
            /// Lets off-chain tooling iterate the PDA slot set without
            /// needing reflection or a JSON descriptor.
            pub const FIELDS: &'static [&'static str] = &[
                #( #bumps_registry_entries ),*
            ];
        }

        #vis struct #bound_name<'ctx, 'a> {
            ctx: &'ctx mut ::hopper::prelude::Context<'a>,
            #accounts_field_decl
            pub bumps: #bumps_name,
        }

        #vis struct #receipt_scope_name<const SNAP: usize> {
            #(#receipt_scope_fields)*
        }

        impl #impl_generics #name #ty_generics #where_clause {
            /// Number of accounts this context requires.
            pub const ACCOUNT_COUNT: usize = #account_count;
            pub const RECEIPT_EXPECTED: bool = #receipt_expected;
            pub const MUTABLE_ACCOUNT_COUNT: usize = #mutable_account_count;

            /// Number of individual validation checks performed.
            pub const VALIDATION_CHECK_COUNT: usize = #check_count;

            /// Human-readable descriptions of every validation check.
            ///
            /// Inspect this constant (or use `hopper compile --emit rust`) to
            /// see exactly what `validate()` enforces. nothing is hidden.
            pub const VALIDATION_CHECKS: &'static [&'static str] = &[
                #(#check_desc_literals),*
            ];

            /// Full Anchor-grade schema metadata: lifecycle role, PDA
            /// seeds, `has_one` edges, `payer`/`space` for init,
            /// `address`/`owner` pins. everything the audit's
            /// Stage 2.5 closure asks client generators and IDL tools
            /// to consume without re-parsing source. The `const`
            /// guarantees it's available at compile time too.
            pub const SCHEMA_METADATA: ::hopper::hopper_schema::accounts::ContextDescriptor =
                ::hopper::hopper_schema::accounts::ContextDescriptor {
                    name: #ctx_name_lit,
                    accounts: &[ #( #account_schema_entries ),* ],
                    policies: &[],
                    receipts_expected: #receipt_expected,
                    mutation_classes: &[],
                };

            /// Declared instruction-arg bindings for this context, as
            /// `(name, canonical_type)` pairs in the order given to
            /// `#[instruction(...)]`. Empty when no args were declared.
            ///
            /// Tooling (hopper-sdk, IDL / Codama projectors, client
            /// generators) consumes this slice directly rather than
            /// re-parsing the source. the same contract Anchor's
            /// `#[derive(Accounts)] #[instruction(...)]` exposes, but
            /// backed by real typed Rust bindings so a mismatch is a
            /// compile error, not a runtime surprise.
            pub const CONTEXT_ARGS: &'static [(&'static str, &'static str)] = &[
                #( #context_arg_entries ),*
            ];

            // ── Per-field validators ─────────────────────────────────
            //
            // Each field gets its own `validate_{name}()` so the checks
            // are individually callable, testable, and visible in
            // `hopper compile --emit rust` output.
            //
            // When the struct declares `#[instruction(...)]`, each
            // per-field validator takes the declared args as ordinary
            // parameters. the same mechanism Anchor users expect,
            // but threaded through *typed* Rust bindings rather than
            // free identifiers that happen to resolve to the right
            // thing.
            #(#per_field_validators)*

            /// Validate the account slice against this context spec.
            ///
            /// This calls each per-field validator in order. Every check
            /// is also available as a standalone `validate_{field}()` method
            /// for fine-grained control and testing.
            ///
            /// When the struct declares `#[instruction(...)]`, this
            /// entry point is renamed to `validate_with_args(...)` and
            /// carries the declared typed args as additional
            /// parameters. the args-less `validate(...)` is **not**
            /// emitted in that case, because any seed / constraint
            /// expression referencing an instruction arg would not
            /// compile without the binding in scope.
            #[inline]
            pub fn #top_validate_ident(
                ctx: &::hopper::prelude::Context<'_>
                #top_arg_param_fragment
            ) -> ::core::result::Result<(), ::hopper::__runtime::ProgramError> {
                ctx.require_accounts(Self::ACCOUNT_COUNT)?;
                #(#validation_stmts)*
                Ok(())
            }

            /// Bind a raw Hopper context into the typed proc-macro wrapper.
            ///
            /// Mirrors `validate`: when `#[instruction(...)]` is
            /// declared at the struct level, this becomes
            /// `bind_with_args(ctx, arg0, arg1, ...)` and the args-less
            /// variant is omitted.
            #[inline]
            pub fn #top_bind_ident<'ctx, 'a>(
                ctx: &'ctx mut ::hopper::prelude::Context<'a>
                #top_arg_param_fragment
            ) -> ::core::result::Result<#bound_name<'ctx, 'a>, ::hopper::__runtime::ProgramError> {
                Self::#top_validate_ident(ctx #top_arg_name_fragment)?;
                // `validate` already proved every PDA matches its seeds,
                // so each gather expression can assume the derivation
                // will produce the same pubkey. For stored bumps this
                // is a byte read; for inferred bumps it is a second
                // `find_program_address` call, which is the cost of
                // handing the caller a ready-to-use bump without
                // them re-deriving it at the CPI site. Stored bumps
                // are the recommended path in hot handlers.
                let mut __hopper_bumps = <#bumps_name as ::core::default::Default>::default();
                #( #bumps_gather_stmts )*
                #accounts_init_stmt
                let __hopper_bound = #bound_name {
                    ctx,
                    #accounts_bound_field
                    bumps: __hopper_bumps,
                };
                #user_validate_call
                Ok(__hopper_bound)
            }

            #[inline]
            pub fn begin_receipt_scope<const SNAP: usize>(
                ctx: &::hopper::prelude::Context<'_>,
            ) -> ::core::result::Result<#receipt_scope_name<SNAP>, ::hopper::__runtime::ProgramError> {
                Ok(#receipt_scope_name {
                    #(#receipt_begin_inits),*
                })
            }
        }

        impl<const SNAP: usize> #receipt_scope_name<SNAP> {
            /// Seal and emit every receipt tracked by this scope.
            ///
            /// `failure` carries `(error_code, invariant_idx, stage)` when
            /// a guard or invariant failed during the handler; it is
            /// stamped into every mutable account's receipt so the
            /// off-chain SDK can resolve the failure to a named
            /// invariant via the program's `ErrorRegistry`. Pass `None`
            /// on the success path.
            #[inline]
            #vis fn finish(
                mut self,
                ctx: &::hopper::prelude::Context<'_>,
                invariants_passed: bool,
                invariants_checked: u16,
                failure: ::core::option::Option<(
                    u32,
                    u8,
                    ::hopper::receipt::FailureStage,
                )>,
            ) -> ::core::result::Result<(), ::hopper::__runtime::ProgramError> {
                #(#receipt_finish_blocks)*
                Ok(())
            }
        }

        impl<'ctx, 'a> #bound_name<'ctx, 'a> {
            #[inline(always)]
            #vis fn raw(&mut self) -> &mut ::hopper::prelude::Context<'a> {
                self.ctx
            }

            /// Captured PDA bumps for every `seeds = ...` field.
            ///
            /// Returns a reference, not a copy, so the type can grow
            /// fields later without forcing existing call sites to
            /// update. Hand straight to a CPI signer-seeds block:
            ///
            /// ```ignore
            /// let bumps = ctx.bumps();
            /// let signer_seeds: &[&[u8]] = &[
            ///     b"vault",
            ///     authority_key.as_ref(),
            ///     ::core::slice::from_ref(&bumps.vault),
            /// ];
            /// ```
            #[inline(always)]
            #vis fn bumps(&self) -> &#bumps_name {
                &self.bumps
            }

            #[inline(always)]
            #vis fn program_id(&self) -> &::hopper::prelude::Address {
                self.ctx.program_id()
            }

            #[inline(always)]
            #vis fn instruction_data(&self) -> &[u8] {
                self.ctx.instruction_data()
            }

            #[inline(always)]
            #vis fn account(
                &self,
                index: usize,
            ) -> ::core::result::Result<
                &::hopper::prelude::AccountView,
                ::hopper::__runtime::ProgramError,
            > {
                self.ctx.account(index)
            }

            #[inline(always)]
            #vis fn account_mut(
                &self,
                index: usize,
            ) -> ::core::result::Result<
                &::hopper::prelude::AccountView,
                ::hopper::__runtime::ProgramError,
            > {
                self.ctx.account_mut(index)
            }

            #[inline(always)]
            #vis fn remaining_accounts(
                &self,
            ) -> ::hopper::hopper_runtime::remaining::RemainingAccounts<'_> {
                self.ctx.remaining_accounts_strict(#account_count)
            }

            #[inline(always)]
            #vis fn remaining_accounts_passthrough(
                &self,
            ) -> ::hopper::hopper_runtime::remaining::RemainingAccounts<'_> {
                self.ctx.remaining_accounts_passthrough(#account_count)
            }

            #[inline(always)]
            #vis fn remaining_accounts_raw(&self) -> &[::hopper::prelude::AccountView] {
                self.ctx.remaining_accounts(#account_count)
            }

            // --- Generated segment accessors ---
            #(#accessors)*
        }
    };

    Ok(expanded)
}

/// Parse `#[account(...)]` attributes from a field.
///
/// Recognizes the full Anchor-grade surface: `signer`, `mut`, `mut(seg,...)`,
/// `read(seg,...)`, `init`, `zero`, `close = target`, `realloc = expr`,
/// `realloc_payer = field`, `realloc_zero = bool`, `payer = field`,
/// `space = expr`, `seeds = [...]`, `bump` or `bump = stored_byte`,
/// `has_one = field` (repeatable), `owner = expr`, `address = expr`,
/// `constraint = expr` (repeatable).
///
/// After parsing, `validate_account_attr` runs cross-attribute
/// consistency rules (e.g. `init` requires `payer` + `space`).
fn parse_account_attr(attrs: &[Attribute]) -> Result<AccountAttr> {
    let mut result = AccountAttr::default();

    for attr in attrs {
        if attr.path().is_ident("signer") {
            result.is_signer = true;
            continue;
        }

        if !attr.path().is_ident("account") {
            continue;
        }

        attr.parse_nested_meta(|meta| {
            // Handle double-segment paths first (`token::mint`,
            // `mint::authority`, `associated_token::mint`,
            // `seeds::program`). These are Anchor's established
            // vocabulary for SPL-specific constraints; accepting
            // them by the same spelling makes Anchor programs a
            // mechanical port to Hopper rather than a rewrite.
            // Three-segment Token-2022 extension paths:
            // `extensions::transfer_hook::authority = X`, etc.
            if meta.path.segments.len() == 3
                && meta.path.segments[0].ident == "extensions"
            {
                let group = meta.path.segments[1].ident.to_string();
                let field = meta.path.segments[2].ident.to_string();
                return match (group.as_str(), field.as_str()) {
                    ("mint_close_authority", "authority") => {
                        let expr: Expr = meta.value()?.parse()?;
                        result.ext_mint_close_authority = Some(expr);
                        Ok(())
                    }
                    ("permanent_delegate", "delegate") => {
                        let expr: Expr = meta.value()?.parse()?;
                        result.ext_permanent_delegate = Some(expr);
                        Ok(())
                    }
                    ("transfer_hook", "authority") => {
                        let expr: Expr = meta.value()?.parse()?;
                        result.ext_transfer_hook_authority = Some(expr);
                        Ok(())
                    }
                    ("transfer_hook", "program_id") => {
                        let expr: Expr = meta.value()?.parse()?;
                        result.ext_transfer_hook_program = Some(expr);
                        Ok(())
                    }
                    ("metadata_pointer", "authority") => {
                        let expr: Expr = meta.value()?.parse()?;
                        result.ext_metadata_pointer_authority = Some(expr);
                        Ok(())
                    }
                    ("metadata_pointer", "metadata_address") => {
                        let expr: Expr = meta.value()?.parse()?;
                        result.ext_metadata_pointer_address = Some(expr);
                        Ok(())
                    }
                    ("default_account_state", "state") => {
                        let expr: Expr = meta.value()?.parse()?;
                        result.ext_default_account_state = Some(expr);
                        Ok(())
                    }
                    ("interest_bearing", "rate_authority") => {
                        let expr: Expr = meta.value()?.parse()?;
                        result.ext_interest_bearing_authority = Some(expr);
                        Ok(())
                    }
                    ("transfer_fee_config", "authority") => {
                        let expr: Expr = meta.value()?.parse()?;
                        result.ext_transfer_fee_config_authority = Some(expr);
                        Ok(())
                    }
                    ("transfer_fee_config", "withdraw_withheld_authority") => {
                        let expr: Expr = meta.value()?.parse()?;
                        result.ext_transfer_fee_withdraw_authority = Some(expr);
                        Ok(())
                    }
                    _ => Err(meta.error(format!(
                        "unrecognized extension constraint `extensions::{group}::{field}`. \
                         accepted: extensions::{{mint_close_authority,permanent_delegate,transfer_hook,metadata_pointer,default_account_state,interest_bearing,transfer_fee_config}}::*",
                    ))),
                };
            }

            if meta.path.segments.len() == 2 {
                let ns = meta.path.segments[0].ident.to_string();
                let key = meta.path.segments[1].ident.to_string();
                return match (ns.as_str(), key.as_str()) {
                    ("token", "mint") => {
                        let expr: Expr = meta.value()?.parse()?;
                        result.token_mint = Some(expr);
                        Ok(())
                    }
                    ("token", "authority") => {
                        let expr: Expr = meta.value()?.parse()?;
                        result.token_authority = Some(expr);
                        Ok(())
                    }
                    ("token", "token_program") => {
                        // Anchor-parity lever for Token-2022 routing.
                        // Without this, a `token::mint` / `token::authority`
                        // check validates the *content* of the token
                        // account but not which token program owns it.
                        // Setting `token::token_program = TOKEN_2022_ID`
                        // binds the account to Token-2022 so a legacy
                        // Token account pasted into the same slot is
                        // rejected before any byte-level check runs.
                        let expr: Expr = meta.value()?.parse()?;
                        result.token_token_program = Some(expr);
                        Ok(())
                    }
                    ("mint", "authority") => {
                        let expr: Expr = meta.value()?.parse()?;
                        result.mint_authority = Some(expr);
                        Ok(())
                    }
                    ("mint", "decimals") => {
                        let expr: Expr = meta.value()?.parse()?;
                        result.mint_decimals = Some(expr);
                        Ok(())
                    }
                    ("mint", "freeze_authority") => {
                        let expr: Expr = meta.value()?.parse()?;
                        result.mint_freeze_authority = Some(expr);
                        Ok(())
                    }
                    ("mint", "token_program") => {
                        // Mint-axis twin of `token::token_program`. Lets
                        // a program assert that a Mint account is owned
                        // by Token-2022 (or any specific program) before
                        // trusting its layout bytes.
                        let expr: Expr = meta.value()?.parse()?;
                        result.mint_token_program = Some(expr);
                        Ok(())
                    }
                    ("associated_token", "mint") => {
                        let expr: Expr = meta.value()?.parse()?;
                        result.associated_token_mint = Some(expr);
                        Ok(())
                    }
                    ("associated_token", "authority") => {
                        let expr: Expr = meta.value()?.parse()?;
                        result.associated_token_authority = Some(expr);
                        Ok(())
                    }
                    ("associated_token", "token_program") => {
                        let expr: Expr = meta.value()?.parse()?;
                        result.associated_token_token_program = Some(expr);
                        Ok(())
                    }
                    ("metadata", "name") => {
                        let expr: Expr = meta.value()?.parse()?;
                        result.metadata_name = Some(expr);
                        result.is_mut = true;
                        Ok(())
                    }
                    ("metadata", "symbol") => {
                        let expr: Expr = meta.value()?.parse()?;
                        result.metadata_symbol = Some(expr);
                        result.is_mut = true;
                        Ok(())
                    }
                    ("metadata", "uri") => {
                        let expr: Expr = meta.value()?.parse()?;
                        result.metadata_uri = Some(expr);
                        result.is_mut = true;
                        Ok(())
                    }
                    ("metadata", "seller_fee_basis_points") => {
                        let expr: Expr = meta.value()?.parse()?;
                        result.metadata_seller_fee_basis_points = Some(expr);
                        result.is_mut = true;
                        Ok(())
                    }
                    ("metadata", "is_mutable") => {
                        let expr: Expr = meta.value()?.parse()?;
                        result.metadata_is_mutable = Some(expr);
                        result.is_mut = true;
                        Ok(())
                    }
                    ("metadata", "mint") => {
                        let ident: Ident = meta.value()?.parse()?;
                        result.metadata_mint = Some(ident);
                        result.is_mut = true;
                        Ok(())
                    }
                    ("metadata", "mint_authority") => {
                        let ident: Ident = meta.value()?.parse()?;
                        result.metadata_mint_authority = Some(ident);
                        result.is_mut = true;
                        Ok(())
                    }
                    ("metadata", "payer") => {
                        let ident: Ident = meta.value()?.parse()?;
                        result.metadata_payer = Some(ident);
                        result.is_mut = true;
                        Ok(())
                    }
                    ("metadata", "update_authority") => {
                        let ident: Ident = meta.value()?.parse()?;
                        result.metadata_update_authority = Some(ident);
                        result.is_mut = true;
                        Ok(())
                    }
                    ("metadata", "system_program") => {
                        let ident: Ident = meta.value()?.parse()?;
                        result.metadata_system_program = Some(ident);
                        result.is_mut = true;
                        Ok(())
                    }
                    ("metadata", "rent") => {
                        let ident: Ident = meta.value()?.parse()?;
                        result.metadata_rent = Some(ident);
                        result.is_mut = true;
                        Ok(())
                    }
                    ("master_edition", "max_supply") => {
                        let expr: Expr = meta.value()?.parse()?;
                        result.master_edition_max_supply = Some(expr);
                        result.is_mut = true;
                        Ok(())
                    }
                    ("master_edition", "mint") => {
                        let ident: Ident = meta.value()?.parse()?;
                        result.master_edition_mint = Some(ident);
                        result.is_mut = true;
                        Ok(())
                    }
                    ("master_edition", "metadata") => {
                        let ident: Ident = meta.value()?.parse()?;
                        result.master_edition_metadata = Some(ident);
                        result.is_mut = true;
                        Ok(())
                    }
                    ("master_edition", "update_authority") => {
                        let ident: Ident = meta.value()?.parse()?;
                        result.master_edition_update_authority = Some(ident);
                        result.is_mut = true;
                        Ok(())
                    }
                    ("master_edition", "mint_authority") => {
                        let ident: Ident = meta.value()?.parse()?;
                        result.master_edition_mint_authority = Some(ident);
                        result.is_mut = true;
                        Ok(())
                    }
                    ("master_edition", "payer") => {
                        let ident: Ident = meta.value()?.parse()?;
                        result.master_edition_payer = Some(ident);
                        result.is_mut = true;
                        Ok(())
                    }
                    ("master_edition", "token_program") => {
                        let ident: Ident = meta.value()?.parse()?;
                        result.master_edition_token_program = Some(ident);
                        result.is_mut = true;
                        Ok(())
                    }
                    ("master_edition", "system_program") => {
                        let ident: Ident = meta.value()?.parse()?;
                        result.master_edition_system_program = Some(ident);
                        result.is_mut = true;
                        Ok(())
                    }
                    ("master_edition", "rent") => {
                        let ident: Ident = meta.value()?.parse()?;
                        result.master_edition_rent = Some(ident);
                        result.is_mut = true;
                        Ok(())
                    }
                    ("seeds", "program") => {
                        let expr: Expr = meta.value()?.parse()?;
                        result.seeds_program = Some(expr);
                        Ok(())
                    }
                    // Token-2022 extension constraints. Three-segment
                    // paths (extensions::foo::bar) are routed via the
                    // fall-through below; two-segment `extensions::foo`
                    // flags (non_transferable, immutable_owner) hit here.
                    ("extensions", "non_transferable") => {
                        result.ext_non_transferable = true;
                        Ok(())
                    }
                    ("extensions", "immutable_owner") => {
                        result.ext_immutable_owner = true;
                        Ok(())
                    }
                    _ => Err(meta.error(format!(
                        "unrecognized nested account attribute `{ns}::{key}`. \
                         accepted namespaces: token::{{mint,authority,token_program}}, \
                         mint::{{authority,decimals,freeze_authority,token_program}}, \
                         associated_token::{{mint,authority,token_program}}, \
                         metadata::{{name,symbol,uri,seller_fee_basis_points,is_mutable,mint,mint_authority,payer,update_authority,system_program,rent}}, \
                         master_edition::{{max_supply,mint,metadata,update_authority,mint_authority,payer,token_program,system_program,rent}}, \
                         seeds::{{program}}",
                    ))),
                };
            }

            let ident = meta.path.get_ident().cloned();
            let name = ident.as_ref().map(|i| i.to_string()).unwrap_or_default();

            match name.as_str() {
                "signer" => {
                    result.is_signer = true;
                    Ok(())
                }
                "mut" => {
                    // `mut(field1, field2)` or bare `mut`
                    if meta.input.peek(syn::token::Paren) {
                        let content;
                        syn::parenthesized!(content in meta.input);
                        let segments: Punctuated<Ident, Comma> =
                            content.parse_terminated(Ident::parse, Token![,])?;
                        for seg in segments {
                            result.mut_segments.push(seg.to_string());
                        }
                    } else {
                        result.is_mut = true;
                    }
                    Ok(())
                }
                "read" => {
                    if meta.input.peek(syn::token::Paren) {
                        let content;
                        syn::parenthesized!(content in meta.input);
                        let segments: Punctuated<Ident, Comma> =
                            content.parse_terminated(Ident::parse, Token![,])?;
                        for seg in segments {
                            result.read_segments.push(seg.to_string());
                        }
                    }
                    Ok(())
                }
                "init" => {
                    result.init = true;
                    // `init` implies `mut`. the lifecycle helper must
                    // mutate the account. Callers don't need to write
                    // `init, mut` twice.
                    result.is_mut = true;
                    Ok(())
                }
                "init_if_needed" => {
                    // Anchor-parity. Like `init` but the lifecycle
                    // helper skips the CreateAccount CPI when the
                    // account already has non-zero data. Same
                    // implication: `mut` is required. Doesn't imply
                    // `init` because the two flags emit different
                    // lifecycle-helper bodies.
                    result.init_if_needed = true;
                    result.is_mut = true;
                    Ok(())
                }
                "zero" => {
                    result.zero = true;
                    Ok(())
                }
                "close" => {
                    let target: Ident = meta.value()?.parse()?;
                    result.close = Some(target);
                    // `close` implies `mut`. lamports are drained.
                    result.is_mut = true;
                    Ok(())
                }
                "realloc" => {
                    let expr: Expr = meta.value()?.parse()?;
                    result.realloc = Some(expr);
                    result.is_mut = true;
                    Ok(())
                }
                "realloc_payer" => {
                    let ident: Ident = meta.value()?.parse()?;
                    result.realloc_payer = Some(ident);
                    Ok(())
                }
                "realloc_zero" => {
                    // Accept both `realloc_zero = true/false` and bare
                    // `realloc_zero` (meaning true, matching Anchor).
                    if meta.input.peek(Token![=]) {
                        let lit: syn::LitBool = meta.value()?.parse()?;
                        result.realloc_zero = lit.value;
                    } else {
                        result.realloc_zero = true;
                    }
                    Ok(())
                }
                "payer" => {
                    let ident: Ident = meta.value()?.parse()?;
                    result.payer = Some(ident);
                    Ok(())
                }
                "space" => {
                    let expr: Expr = meta.value()?.parse()?;
                    result.space = Some(expr);
                    Ok(())
                }
                "seeds" => {
                    // `seeds = [a, b, c]`
                    let content;
                    // meta.value()? consumes the `=`; then an array literal.
                    let _eq = meta.value()?;
                    syn::bracketed!(content in _eq);
                    let items: Punctuated<Expr, Comma> =
                        content.parse_terminated(Expr::parse, Token![,])?;
                    result.seeds = Some(items.into_iter().collect());
                    Ok(())
                }
                "seeds_fn" => {
                    // `seeds_fn = Type::seeds(&arg1, &arg2)`
                    // One expression evaluating to a slice-of-byte-slices
                    // (or anything that coerces to `&[&[u8]]`). The
                    // type author owns the seed layout; every context
                    // reuses it.
                    let expr: Expr = meta.value()?.parse()?;
                    result.seeds_fn = Some(expr);
                    Ok(())
                }
                "bump" => {
                    // `bump` (inferred) or `bump = stored_expr`.
                    if meta.input.peek(Token![=]) {
                        let expr: Expr = meta.value()?.parse()?;
                        result.bump = Some(BumpSpec::Stored(expr));
                    } else {
                        result.bump = Some(BumpSpec::Inferred);
                    }
                    Ok(())
                }
                "has_one" => {
                    let ident: Ident = meta.value()?.parse()?;
                    result.has_one.push(ident);
                    Ok(())
                }
                "dup" => {
                    let ident: Ident = meta.value()?.parse()?;
                    if result.dup.is_some() {
                        return Err(meta.error("`dup` may only be set once per field"));
                    }
                    result.dup = Some(ident);
                    Ok(())
                }
                "sweep" => {
                    let ident: Ident = meta.value()?.parse()?;
                    if result.sweep.is_some() {
                        return Err(meta.error("`sweep` may only be set once per field"));
                    }
                    result.sweep = Some(ident);
                    Ok(())
                }
                "owner" => {
                    let expr: Expr = meta.value()?.parse()?;
                    result.owner = Some(expr);
                    Ok(())
                }
                "address" => {
                    let expr: Expr = meta.value()?.parse()?;
                    result.address = Some(expr);
                    Ok(())
                }
                "constraint" => {
                    let expr: Expr = meta.value()?.parse()?;
                    result.constraint.push(expr);
                    Ok(())
                }
                "executable" => {
                    result.executable = true;
                    Ok(())
                }
                "rent_exempt" => {
                    // `rent_exempt = enforce` or `rent_exempt = skip`.
                    // Accept both as plain idents (the canonical Anchor
                    // spelling). Anything else is rejected so typos
                    // don't silently degrade to a no-op.
                    let policy: Ident = meta.value()?.parse()?;
                    match policy.to_string().as_str() {
                        "enforce" => result.rent_exempt = Some(RentExemptPolicy::Enforce),
                        "skip" => result.rent_exempt = Some(RentExemptPolicy::Skip),
                        other => {
                            return Err(meta.error(format!(
                                "rent_exempt must be `enforce` or `skip`, got `{}`",
                                other
                            )));
                        }
                    }
                    Ok(())
                }
                _ => Err(meta.error(format!("unrecognized account attribute `{}`", name))),
            }
        })?;
    }

    Ok(result)
}

/// Post-parse consistency checks. Emits spanned errors for declarations
/// that are syntactically valid but semantically incoherent (e.g. `init`
/// without `payer`). The Hopper Safety Audit's compile-fail matrix
/// (D2. page 4) enumerates these; each violation here corresponds to
/// one entry in the trybuild suite.
fn validate_account_attr(field_name: &Ident, attr: &AccountAttr) -> Result<()> {
    if attr.init && attr.init_if_needed {
        return Err(syn::Error::new_spanned(
            field_name,
            "use either `init` or `init_if_needed`, not both",
        ));
    }
    if attr.init || attr.init_if_needed {
        let kw = if attr.init_if_needed {
            "init_if_needed"
        } else {
            "init"
        };
        if attr.payer.is_none() {
            return Err(syn::Error::new_spanned(
                field_name,
                format!("#[account({})] requires `payer = <field>`", kw),
            ));
        }
        if attr.space.is_none() {
            return Err(syn::Error::new_spanned(
                field_name,
                format!("#[account({})] requires `space = <expr>`", kw),
            ));
        }
        if attr.seeds.is_some() && attr.bump.is_none() {
            return Err(syn::Error::new_spanned(
                field_name,
                format!(
                    "#[account({}, seeds = ...)] requires `bump` (inferred) or `bump = <stored_byte>`",
                    kw
                ),
            ));
        }
    }
    if attr.realloc.is_some() {
        if attr.realloc_payer.is_none() {
            return Err(syn::Error::new_spanned(
                field_name,
                "#[account(realloc = ...)] requires `realloc_payer = <field>`",
            ));
        }
        if !attr.realloc_zero {
            return Err(syn::Error::new_spanned(
                field_name,
                "#[account(realloc = ...)] requires an explicit `realloc_zero` policy (use `realloc_zero = true` to zero the newly-allocated bytes)",
            ));
        }
    }
    if attr.close.is_some() && !attr.is_mut {
        return Err(syn::Error::new_spanned(
            field_name,
            "#[account(close = ...)] requires `mut`. lamports must be drainable",
        ));
    }
    if attr.seeds.is_some() && attr.bump.is_none() && !attr.init {
        return Err(syn::Error::new_spanned(
            field_name,
            "#[account(seeds = ...)] requires `bump` (or `bump = <stored_byte>`)",
        ));
    }
    // `seeds::program = X` only makes sense when `seeds = [...]` is
    // declared. otherwise there's no PDA derivation to redirect.
    if attr.seeds_program.is_some() && attr.seeds.is_none() {
        return Err(syn::Error::new_spanned(
            field_name,
            "#[account(seeds::program = ...)] requires `seeds = [...]`",
        ));
    }
    // Associated-token pair coherence. the mint/authority inputs are
    // joint input to the ATA PDA derivation and declaring just one
    // would produce an ATA derivation with a missing dimension.
    // Rather than silently skip the check, we raise a compile error
    // pointing at the field with an actionable message.
    match (
        attr.associated_token_mint.is_some(),
        attr.associated_token_authority.is_some(),
    ) {
        (true, false) => {
            return Err(syn::Error::new_spanned(
                field_name,
                "#[account(associated_token::mint = ...)] also requires `associated_token::authority = ...`",
            ));
        }
        (false, true) => {
            return Err(syn::Error::new_spanned(
                field_name,
                "#[account(associated_token::authority = ...)] also requires `associated_token::mint = ...`",
            ));
        }
        _ => {}
    }
    // `associated_token::token_program` only has meaning alongside
    // the derivation pair. on its own it configures nothing.
    if attr.associated_token_token_program.is_some()
        && attr.associated_token_mint.is_none()
        && attr.associated_token_authority.is_none()
    {
        return Err(syn::Error::new_spanned(
            field_name,
            "#[account(associated_token::token_program = ...)] requires `associated_token::mint = ...` and `associated_token::authority = ...`",
        ));
    }

    let metadata_data_any = attr.metadata_name.is_some()
        || attr.metadata_symbol.is_some()
        || attr.metadata_uri.is_some()
        || attr.metadata_seller_fee_basis_points.is_some()
        || attr.metadata_is_mutable.is_some();
    let metadata_data_complete = attr.metadata_name.is_some()
        && attr.metadata_symbol.is_some()
        && attr.metadata_uri.is_some()
        && attr.metadata_seller_fee_basis_points.is_some();
    if metadata_data_any && !metadata_data_complete {
        return Err(syn::Error::new_spanned(
            field_name,
            "metadata constraints require `metadata::name`, `metadata::symbol`, `metadata::uri`, and `metadata::seller_fee_basis_points` together",
        ));
    }
    let metadata_cpi_any = attr.metadata_mint.is_some()
        || attr.metadata_mint_authority.is_some()
        || attr.metadata_payer.is_some()
        || attr.metadata_update_authority.is_some()
        || attr.metadata_system_program.is_some()
        || attr.metadata_rent.is_some();
    if metadata_cpi_any {
        if !metadata_data_complete
            || attr.metadata_mint.is_none()
            || attr.metadata_mint_authority.is_none()
            || attr.metadata_payer.is_none()
            || attr.metadata_update_authority.is_none()
            || attr.metadata_system_program.is_none()
        {
            return Err(syn::Error::new_spanned(
                field_name,
                "metadata CPI helpers require metadata::{mint,mint_authority,payer,update_authority,system_program,name,symbol,uri,seller_fee_basis_points}; `metadata::rent` is optional",
            ));
        }
    }

    let master_edition_any = attr.master_edition_max_supply.is_some()
        || attr.master_edition_mint.is_some()
        || attr.master_edition_metadata.is_some()
        || attr.master_edition_update_authority.is_some()
        || attr.master_edition_mint_authority.is_some()
        || attr.master_edition_payer.is_some()
        || attr.master_edition_token_program.is_some()
        || attr.master_edition_system_program.is_some()
        || attr.master_edition_rent.is_some();
    if (metadata_data_any || metadata_cpi_any) && master_edition_any {
        return Err(syn::Error::new_spanned(
            field_name,
            "declare `metadata::*` and `master_edition::*` on separate account fields",
        ));
    }
    if master_edition_any
        && (attr.master_edition_max_supply.is_none()
            || attr.master_edition_mint.is_none()
            || attr.master_edition_metadata.is_none()
            || attr.master_edition_update_authority.is_none()
            || attr.master_edition_mint_authority.is_none()
            || attr.master_edition_payer.is_none()
            || attr.master_edition_token_program.is_none()
            || attr.master_edition_system_program.is_none())
    {
        return Err(syn::Error::new_spanned(
            field_name,
            "master_edition helpers require master_edition::{max_supply,mint,metadata,update_authority,mint_authority,payer,token_program,system_program}; `master_edition::rent` is optional",
        ));
    }
    Ok(())
}

fn sibling_index(ctx_fields: &[ContextField], ident: &Ident, role: &str) -> Result<usize> {
    ctx_fields
        .iter()
        .position(|field| field.name == *ident)
        .ok_or_else(|| {
            syn::Error::new_spanned(
                ident,
                format!(
                    "{} references `{}`, but no sibling context field has that name",
                    role, ident
                ),
            )
        })
}

fn type_ident(ty: &Type) -> Result<Ident> {
    match ty {
        Type::Path(TypePath { path, .. }) => path
            .segments
            .last()
            .map(|segment| segment.ident.clone())
            .ok_or_else(|| syn::Error::new_spanned(ty, "expected a path type for account field")),
        _ => Err(syn::Error::new_spanned(
            ty,
            "hopper_context segment accessors require path types such as `Vault`",
        )),
    }
}

fn reject_reference_wrapped_account(field_name: &Ident, ty: &Type) -> Result<()> {
    let Type::Reference(reference) = ty else {
        return Ok(());
    };

    let Some(wrapper) = classify_wrapper(reference.elem.as_ref()) else {
        return Ok(());
    };

    match wrapper {
        WrapperKind::Account { inner } => {
            let inner = type_ident(&inner)
                .map(|ident| ident.to_string())
                .unwrap_or_else(|_| "T".to_string());
            let account_ty = format!("Account<'info, {}>", inner);
            let hint = if reference.mutability.is_some() {
                format!("#[account(mut)] pub {}: {}", field_name, account_ty)
            } else {
                format!("pub {}: {}", field_name, account_ty)
            };
            let reason = if reference.mutability.is_some() {
                "mutable access is enforced by Hopper account-data guards, not by `&mut` on the wrapper"
            } else {
                "the wrapper is already a borrowed role view over the account"
            };
            Err(syn::Error::new_spanned(
                ty,
                format!("Use `{}` in Hopper; {}.", hint, reason),
            ))
        }
        WrapperKind::InitAccount { inner } => {
            let inner = type_ident(&inner)
                .map(|ident| ident.to_string())
                .unwrap_or_else(|_| "T".to_string());
            Err(syn::Error::new_spanned(
                ty,
                format!(
                    "Use `pub {}: InitAccount<'info, {}>` with the appropriate `#[account(init, ...)]` attributes in Hopper; do not wrap Hopper account wrappers in references.",
                    field_name, inner
                ),
            ))
        }
        WrapperKind::Interface { .. } | WrapperKind::InterfaceAccount { .. } => Err(
            syn::Error::new_spanned(
                ty,
                "Hopper interface wrappers are value role wrappers; remove `&` or `&mut` from this field type and put mutability in `#[account(...)]` attributes.",
            ),
        ),
        WrapperKind::Signer
        | WrapperKind::Program
        | WrapperKind::UncheckedAccount
        | WrapperKind::SystemAccount => Err(syn::Error::new_spanned(
            ty,
            "Hopper account wrappers are value role wrappers; remove `&` or `&mut` from this field type and put mutability in `#[account(...)]` attributes.",
        )),
    }
}

fn skips_layout_validation(ty: &Type) -> bool {
    match ty {
        Type::Path(TypePath { path, .. }) => path
            .segments
            .last()
            .map(|segment| {
                matches!(
                    segment.ident.to_string().as_str(),
                    "AccountView"
                        | "Signer"
                        | "HopperSigner"
                        | "UncheckedAccount"
                        | "SystemAccount"
                        | "ProgramRef"
                        | "Program"
                        | "Interface"
                        | "InterfaceAccount"
                )
            })
            .unwrap_or(false),
        _ => false,
    }
}

/// Audit Stage 2.3: classify wrapper types so the context macro can
/// auto-derive the appropriate checks from the type name alone.
#[derive(Clone)]
#[allow(dead_code)]
enum WrapperKind {
    /// `Signer<'info>`. emit `check_signer`.
    Signer,
    /// `Program<'info, P>`. emit `check_address == P::ID` and
    /// `check_executable`. Layout validation skipped.
    Program,
    /// `Interface<'info, I>`. emit address-in-interface-set and executable.
    Interface { spec: Type },
    /// `UncheckedAccount<'info>`. no type-derived validation.
    UncheckedAccount,
    /// `SystemAccount<'info>`. emit owner == System Program.
    SystemAccount,
    /// `Account<'info, T>`. emit `check_owned_by(program_id)` +
    /// `load::<T>()` using `T` as the layout.
    Account { inner: Type },
    /// `InitAccount<'info, T>`. skip pre-instruction layout check
    /// (account doesn't exist yet); the `init_{field}` lifecycle
    /// helper will create + initialise it.
    InitAccount { inner: Type },
    /// `InterfaceAccount<'info, T>`. emit owner-in-interface-set plus
    /// cross-program Hopper layout validation.
    InterfaceAccount { inner: Type },
}

/// Recognize typed wrapper types (`Signer<'info>`, `Account<'info, T>`,
/// `InitAccount<'info, T>`, `Program<'info, P>`) and extract the inner
/// layout type where applicable. Returns `None` for raw `AccountView`
/// or plain layout types.
fn classify_wrapper(ty: &Type) -> Option<WrapperKind> {
    let Type::Path(TypePath { path, .. }) = ty else {
        return None;
    };
    let segment = path.segments.last()?;
    let name = segment.ident.to_string();

    match name.as_str() {
        "Signer" | "HopperSigner" => Some(WrapperKind::Signer),
        "Program" => Some(WrapperKind::Program),
        "Interface" => {
            let syn::PathArguments::AngleBracketed(args) = &segment.arguments else {
                return None;
            };
            let spec = args.args.iter().find_map(|arg| {
                if let syn::GenericArgument::Type(ty) = arg {
                    Some(ty.clone())
                } else {
                    None
                }
            })?;
            Some(WrapperKind::Interface { spec })
        }
        "UncheckedAccount" => Some(WrapperKind::UncheckedAccount),
        "SystemAccount" => Some(WrapperKind::SystemAccount),
        "Account" | "InitAccount" | "InterfaceAccount" => {
            // Pull out the generic `T` arg. `Account<'info, T>` has
            // a lifetime arg first, then a type arg. we want the
            // last type arg.
            let syn::PathArguments::AngleBracketed(args) = &segment.arguments else {
                return None;
            };
            let inner = args.args.iter().find_map(|arg| {
                if let syn::GenericArgument::Type(ty) = arg {
                    Some(ty.clone())
                } else {
                    None
                }
            })?;
            if name == "Account" {
                Some(WrapperKind::Account { inner })
            } else if name == "InitAccount" {
                Some(WrapperKind::InitAccount { inner })
            } else {
                Some(WrapperKind::InterfaceAccount { inner })
            }
        }
        _ => None,
    }
}

fn accounts_binding_fragments(
    name: &Ident,
    generics: &syn::Generics,
    ctx_fields: &[ContextField],
) -> AccountsBindingFragments {
    let has_only_lifetime_generics = generics
        .params
        .iter()
        .all(|param| matches!(param, GenericParam::Lifetime(_)));
    let all_fields_are_wrappers = ctx_fields
        .iter()
        .all(|field| classify_wrapper(&field.ty).is_some());

    if ctx_fields.is_empty() || !has_only_lifetime_generics || !all_fields_are_wrappers {
        return AccountsBindingFragments {
            field_decl: TokenStream::new(),
            init_stmt: TokenStream::new(),
            bound_field: TokenStream::new(),
        };
    }

    let generic_args: Vec<TokenStream> = generics.params.iter().map(|_| quote! { 'a }).collect();
    let accounts_ty = if generic_args.is_empty() {
        quote! { #name }
    } else {
        quote! { #name<#(#generic_args),*> }
    };

    let field_inits = ctx_fields.iter().map(|field| {
        let field_name = &field.name;
        let idx = field.index;
        match classify_wrapper(&field.ty).expect("checked above") {
            WrapperKind::Signer => quote! {
                #field_name: ::hopper::prelude::Signer::try_new(ctx.account(#idx)?)?
            },
            WrapperKind::Program => quote! {
                #field_name: ::hopper::prelude::Program::try_new(ctx.account(#idx)?)?
            },
            WrapperKind::Interface { spec } => quote! {
                #field_name: ::hopper::prelude::Interface::<#spec>::try_new(ctx.account(#idx)?)?
            },
            WrapperKind::UncheckedAccount => quote! {
                #field_name: unsafe {
                    ::hopper::prelude::UncheckedAccount::new_unchecked(ctx.account(#idx)?)
                }
            },
            WrapperKind::SystemAccount => quote! {
                #field_name: ::hopper::prelude::SystemAccount::try_new(ctx.account(#idx)?)?
            },
            WrapperKind::Account { .. } => quote! {
                #field_name: unsafe {
                    ::hopper::prelude::Account::new_unchecked(ctx.account(#idx)?)
                }
            },
            WrapperKind::InitAccount { .. } => quote! {
                #field_name: unsafe {
                    ::hopper::prelude::InitAccount::new_unchecked(ctx.account(#idx)?)
                }
            },
            WrapperKind::InterfaceAccount { .. } => quote! {
                #field_name: unsafe {
                    ::hopper::prelude::InterfaceAccount::new_unchecked(ctx.account(#idx)?)
                }
            },
        }
    });

    AccountsBindingFragments {
        field_decl: quote! { pub accounts: #accounts_ty, },
        init_stmt: quote! {
            let __hopper_accounts: #accounts_ty = #name {
                #(#field_inits),*
            };
        },
        bound_field: quote! { accounts: __hopper_accounts, },
    }
}

fn layout_type_for_field(field: &ContextField) -> Option<Type> {
    match classify_wrapper(&field.ty) {
        Some(WrapperKind::Account { inner }) | Some(WrapperKind::InitAccount { inner }) => {
            Some(inner)
        }
        Some(WrapperKind::Signer)
        | Some(WrapperKind::Program)
        | Some(WrapperKind::Interface { .. })
        | Some(WrapperKind::InterfaceAccount { .. })
        | Some(WrapperKind::UncheckedAccount)
        | Some(WrapperKind::SystemAccount) => None,
        None => {
            if skips_layout_validation(&field.ty) {
                None
            } else {
                Some(field.ty.clone())
            }
        }
    }
}

fn to_screaming_snake(s: &str) -> String {
    let mut result = String::with_capacity(s.len() + 4);
    for (i, c) in s.chars().enumerate() {
        if c.is_uppercase() && i > 0 {
            result.push('_');
        }
        result.push(c.to_ascii_uppercase());
    }
    result
}

// -----------------------------------------------------------------------------
// Regression tests
// -----------------------------------------------------------------------------
//
// The proc-macro expansion path itself is best exercised through a
// downstream trybuild suite (see `tests/context/ui/*.rs`). These unit
// tests target the pure-function helpers that don't require spawning
// a fresh `rustc` invocation. `parse_instruction_attr` is one of the
// more fragile pieces because it combines attribute-walking with a
// hand-rolled `Parse` impl for `name: Type` pairs, so it gets the
// lion's share of coverage here.
#[cfg(test)]
mod instruction_arg_tests {
    use super::*;
    use quote::ToTokens;
    use syn::{parse_quote, ItemStruct};

    fn args_of(mut s: ItemStruct) -> Vec<(String, String)> {
        let decls = parse_instruction_attr(&mut s.attrs).expect("parse ok");
        decls
            .into_iter()
            .map(|a| (a.name.to_string(), a.ty.to_token_stream().to_string()))
            .collect()
    }

    #[test]
    fn parses_single_primitive_arg() {
        let input: ItemStruct = parse_quote! {
            #[instruction(amount: u64)]
            pub struct Swap {}
        };
        let out = args_of(input);
        assert_eq!(out, vec![("amount".into(), "u64".into())]);
    }

    #[test]
    fn parses_multiple_args_including_array() {
        let input: ItemStruct = parse_quote! {
            #[instruction(nonce: u64, memo: [u8; 32], kind: u8)]
            pub struct Swap {}
        };
        let out = args_of(input);
        // We verify count + names + scalar types exactly. the array
        // type's stringified form is quote-spacing-dependent, so for
        // that one we just check that both `u8` and `32` appear in
        // the rendered token stream.
        assert_eq!(out.len(), 3);
        assert_eq!(out[0].0, "nonce");
        assert_eq!(out[1].0, "memo");
        assert_eq!(out[2].0, "kind");
        assert_eq!(out[0].1, "u64");
        assert!(out[1].1.contains("u8"));
        assert!(out[1].1.contains("32"));
        assert_eq!(out[2].1, "u8");
    }

    #[test]
    fn rejects_duplicate_arg_names() {
        let mut input: ItemStruct = parse_quote! {
            #[instruction(amount: u64, amount: u128)]
            pub struct Swap {}
        };
        let err = parse_instruction_attr(&mut input.attrs).expect_err("expected error");
        let msg = err.to_string();
        assert!(msg.contains("duplicate"), "got: {msg}");
        assert!(msg.contains("amount"), "got: {msg}");
    }

    #[test]
    fn rejects_multiple_instruction_attributes() {
        let mut input: ItemStruct = parse_quote! {
            #[instruction(amount: u64)]
            #[instruction(extra: u8)]
            pub struct Swap {}
        };
        let err = parse_instruction_attr(&mut input.attrs).expect_err("expected error");
        let msg = err.to_string();
        assert!(msg.contains("at most one"), "got: {msg}");
    }

    #[test]
    fn empty_on_struct_without_instruction_attr() {
        let input: ItemStruct = parse_quote! {
            pub struct NoArgs {}
        };
        let out = args_of(input);
        assert!(out.is_empty());
    }

    /// `#[derive(Accounts)]` mirrors `#[hopper::context]` exactly except
    /// it does NOT re-emit the user's input struct (the user already
    /// declared it). This pins the flag plumbing: we lower the same
    /// constraint surface to a binder type but skip the struct
    /// passthrough. If this test starts asserting `pub struct Deposit`
    /// in the derive output, the duplicate-definition guard regressed.
    #[test]
    fn derive_does_not_reemit_struct_definition() {
        let item: TokenStream = quote! {
            #[derive(Accounts)]
            pub struct Deposit {
                #[signer]
                pub authority: AccountView,
            }
        };
        let derived = expand_for_derive(item).expect("derive expand ok");
        let s = derived.to_string();
        // Generated items still include the binder.
        assert!(
            s.contains("DepositCtx"),
            "derive output missing the bound context type: {s}"
        );
        // But the input struct itself is NOT in the emitted token stream
        // - that would be a duplicate definition once the user's
        // declaration compiles.
        assert!(
            !s.contains("pub struct Deposit "),
            "derive must not re-emit the user's struct: {s}"
        );
    }

    /// And the attribute form keeps emitting the struct, since it owns
    /// the item it decorates. This is the existing contract the rest
    /// of the codebase depends on.
    #[test]
    fn attr_does_reemit_struct_definition() {
        let item: TokenStream = quote! {
            pub struct Deposit {
                #[signer]
                pub authority: AccountView,
            }
        };
        let attr = expand(TokenStream::new(), item).expect("attr expand ok");
        let s = attr.to_string();
        assert!(
            s.contains("pub struct Deposit"),
            "attribute form must re-emit the input struct: {s}"
        );
        assert!(
            s.contains("DepositCtx"),
            "attribute form missing the bound context type: {s}"
        );
    }

    #[test]
    fn strips_attribute_in_place() {
        let mut input: ItemStruct = parse_quote! {
            #[instruction(nonce: u64)]
            #[derive(Clone)]
            pub struct Keep {}
        };
        let _ = parse_instruction_attr(&mut input.attrs).expect("parse ok");
        // After parsing, the #[instruction(...)] attr is removed but
        // other outer attributes (#[derive(Clone)], etc.) are kept. // the emitted struct therefore retains whatever derives the
        // user declared.
        assert!(
            input
                .attrs
                .iter()
                .all(|a| !a.path().is_ident("instruction")),
            "instruction attr was not stripped"
        );
        assert!(
            input.attrs.iter().any(|a| a.path().is_ident("derive")),
            "non-instruction attrs must be preserved"
        );
    }

    #[test]
    fn rejects_positional_form() {
        // `#[instruction(u64)]` (positional, no name) is rejected because
        // seed / constraint expressions need a named binding to refer
        // to. Anchor accepts the positional form but the generated
        // code is harder to read and impossible to regenerate
        // consistently for client tooling.
        let mut input: ItemStruct = parse_quote! {
            #[instruction(u64)]
            pub struct Bad {}
        };
        let err = parse_instruction_attr(&mut input.attrs).expect_err("expected error");
        // The underlying syn error comes from the `:` parser failing
        // once it consumes the type without finding a colon.
        let _ = err;
    }
}