libperl-macrogen 0.1.3

Generate Rust FFI bindings from C macro functions in Perl headers
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
//! C言語パーサー
//!
//! tinyccのparser部分に相当。再帰下降パーサーで実装。

use std::collections::{HashMap, HashSet};

use crate::ast::*;
use crate::error::{CompileError, ParseError, Result};
use crate::intern::{InternedStr, StringInterner};
use crate::macro_infer::detect_assert_kind;
use crate::preprocessor::Preprocessor;
use crate::lexer::{Lexer, LookupOnly};
use crate::source::{FileId, SourceLocation};
use crate::token::{MacroBeginInfo, MacroInvocationKind, Token, TokenId, TokenKind};
use crate::token_source::{TokenSliceRef, TokenSource};

/// マクロ展開コンテキスト
///
/// パース中のマクロ展開状態を追跡する。
/// MacroBegin マーカーを見つけたらプッシュし、MacroEnd を見つけたらポップする。
#[derive(Debug, Default)]
pub struct MacroContext {
    /// 現在のマクロ展開スタック(外側から内側へ)
    stack: Vec<MacroBeginInfo>,
}

impl MacroContext {
    /// 新しいコンテキストを作成
    pub fn new() -> Self {
        Self { stack: Vec::new() }
    }

    /// マクロ展開を開始
    pub fn push(&mut self, info: MacroBeginInfo) {
        self.stack.push(info);
    }

    /// マクロ展開を終了
    pub fn pop(&mut self) -> Option<MacroBeginInfo> {
        self.stack.pop()
    }

    /// 現在マクロ展開中かどうか
    pub fn is_in_macro(&self) -> bool {
        !self.stack.is_empty()
    }

    /// 現在のマクロ展開情報から MacroExpansionInfo を構築
    pub fn build_macro_info(&self, interner: &StringInterner) -> Option<MacroExpansionInfo> {
        if self.stack.is_empty() {
            return None;
        }

        let mut info = MacroExpansionInfo::new();
        for begin_info in &self.stack {
            let args = match &begin_info.kind {
                crate::token::MacroInvocationKind::Object => None,
                crate::token::MacroInvocationKind::Function { args } => {
                    // トークン列を文字列に変換
                    Some(args.iter().map(|arg_tokens| {
                        arg_tokens.iter()
                            .map(|t| t.kind.format(interner))
                            .collect::<Vec<_>>()
                            .join(" ")
                    }).collect())
                }
            };
            info.push(MacroInvocation {
                name: begin_info.macro_name,
                call_loc: begin_info.call_loc.clone(),
                args,
            });
        }
        Some(info)
    }

    /// 展開スタックの深さ
    pub fn depth(&self) -> usize {
        self.stack.len()
    }
}

/// パーサー
///
/// 汎用のトークンソースからC言語をパースする。
/// `S` は `TokenSource` トレイトを実装する任意の型。
pub struct Parser<'a, S: TokenSource> {
    source: &'a mut S,
    current: Token,
    /// typedef名のセット
    typedefs: HashSet<InternedStr>,
    /// マクロ展開コンテキスト
    macro_ctx: MacroContext,
    /// マクロマーカーを処理するか(emit_markers=true の場合に true にする)
    handle_macro_markers: bool,
    /// do-while 文の末尾セミコロンを省略可能にするフラグ
    allow_missing_semi: bool,
    /// パース中に検出した関数呼び出しの数
    pub function_call_count: usize,
    /// パース中に検出したポインタデリファレンスの数
    pub deref_count: usize,
    /// マクロ仮引数の辞書(マクロ本体パース時のみ使用)
    /// key: 仮引数名, value: パラメータインデックス
    generic_params: HashMap<InternedStr, usize>,
    /// パース中に型として使用が検出された generic param
    detected_type_params: HashSet<InternedStr>,
}

/// Preprocessor 専用の後方互換コンストラクタ
impl<'a> Parser<'a, Preprocessor> {
    /// 新しいパーサーを作成(Preprocessor専用)
    pub fn new(pp: &'a mut Preprocessor) -> Result<Self> {
        Self::from_source(pp)
    }

    /// ストリーミング形式でパース
    ///
    /// 各宣言をパースするたびにコールバックを呼び出す。
    /// パースエラーが発生した場合はコールバックを呼ばずにエラーを返す。
    /// コールバックが `ControlFlow::Break(())` を返した場合はループを終了。
    pub fn parse_each<F>(&mut self, mut callback: F) -> Result<()>
    where
        F: FnMut(&ExternalDecl, &crate::source::SourceLocation, &std::path::Path, &StringInterner) -> std::ops::ControlFlow<()>,
    {
        while !self.is_eof() {
            let loc = self.current.loc.clone();
            let decl = self.parse_external_decl()?;
            let path = self.source.files().get_path(loc.file_id);
            let interner = self.source.interner();
            if callback(&decl, &loc, path, interner).is_break() {
                break;
            }
        }
        Ok(())
    }

    /// ストリーミング形式でパース(Preprocessor アクセス付き)
    ///
    /// `parse_each` と同様だが、コールバックに Preprocessor への可変参照も渡す。
    /// マクロ呼び出しコールバック(MacroCallWatcher など)にアクセスする場合に使用。
    /// パースエラーが発生した場合はコールバックを呼ばずにエラーを返す。
    pub fn parse_each_with_pp<F>(&mut self, mut callback: F) -> Result<()>
    where
        F: FnMut(&ExternalDecl, &crate::source::SourceLocation, &std::path::Path, &mut Preprocessor) -> std::ops::ControlFlow<()>,
    {
        while !self.is_eof() {
            let loc = self.current.loc.clone();
            let decl = self.parse_external_decl()?;
            let path = self.source.files().get_path(loc.file_id).to_path_buf();
            if callback(&decl, &loc, &path, self.source).is_break() {
                break;
            }
        }
        Ok(())
    }
}

/// 汎用のトークンソースに対するパーサー実装
impl<'a, S: TokenSource> Parser<'a, S> {
    /// トークンソースからパーサーを作成
    pub fn from_source(source: &'a mut S) -> Result<Self> {
        // GCC builtin types を事前登録
        let mut typedefs = HashSet::new();
        typedefs.insert(source.interner_mut().intern("__builtin_va_list"));

        let mut parser = Self {
            source,
            current: Token::default(),
            typedefs,
            macro_ctx: MacroContext::new(),
            handle_macro_markers: false,
            allow_missing_semi: false,
            function_call_count: 0,
            deref_count: 0,
            generic_params: HashMap::new(),
            detected_type_params: HashSet::new(),
        };
        // マーカーをスキップして最初のトークンを取得
        parser.current = parser.inner_next_token()?;

        Ok(parser)
    }

    /// トークンソースからパーサーを作成(既存のtypedef情報を引き継ぐ)
    pub fn from_source_with_typedefs(source: &'a mut S, typedefs: HashSet<InternedStr>) -> Result<Self> {
        let mut parser = Self {
            source,
            current: Token::default(),
            typedefs,
            macro_ctx: MacroContext::new(),
            handle_macro_markers: false,
            allow_missing_semi: false,
            function_call_count: 0,
            deref_count: 0,
            generic_params: HashMap::new(),
            detected_type_params: HashSet::new(),
        };
        // マーカーをスキップして最初のトークンを取得
        parser.current = parser.inner_next_token()?;

        Ok(parser)
    }

    /// マクロマーカー処理を有効にする
    ///
    /// Note: 既に current にマーカートークンがある場合はスキップする
    pub fn set_handle_macro_markers(&mut self, enabled: bool) -> Result<()> {
        self.handle_macro_markers = enabled;

        // 既に current にマーカートークンがある場合はスキップ
        if enabled {
            while matches!(
                self.current.kind,
                TokenKind::MacroBegin(_) | TokenKind::MacroEnd(_)
            ) {
                match &self.current.kind {
                    TokenKind::MacroBegin(info) => {
                        self.macro_ctx.push((**info).clone());
                    }
                    TokenKind::MacroEnd(_) => {
                        self.macro_ctx.pop();
                    }
                    _ => {}
                }
                self.current = self.source.next_token()?;
            }
        }
        Ok(())
    }

    /// StringInterner への参照を取得
    pub fn interner(&self) -> &crate::intern::StringInterner {
        self.source.interner()
    }

    /// typedef名のセットを取得
    pub fn typedefs(&self) -> &HashSet<InternedStr> {
        &self.typedefs
    }

    /// 翻訳単位をパース
    pub fn parse(&mut self) -> Result<TranslationUnit> {
        let mut decls = Vec::new();

        while !self.is_eof() {
            let decl = self.parse_external_decl()?;
            decls.push(decl);
        }

        Ok(TranslationUnit { decls })
    }

    /// 式のみをパース
    ///
    /// マクロ本体など、式だけをパースしたい場合に使用
    pub fn parse_expr_only(&mut self) -> Result<Expr> {
        self.parse_expr()
    }

    /// 文をパース(末尾セミコロン省略可能)
    ///
    /// マクロ body のパースなど、do-while の末尾セミコロンが
    /// 省略されている場合に使用する。
    pub fn parse_stmt_allow_missing_semi(&mut self) -> Result<Stmt> {
        self.allow_missing_semi = true;
        let result = self.parse_stmt();
        self.allow_missing_semi = false;
        result
    }

    /// 外部宣言をパース
    fn parse_external_decl(&mut self) -> Result<ExternalDecl> {
        let comments = self.current.leading_comments.clone();
        let loc = self.current.loc.clone();
        let is_target = self.source.is_file_in_target(loc.file_id);

        // 宣言指定子をパース
        let specs = self.parse_decl_specs()?;

        // ; のみの場合(構造体宣言など)
        if self.check(&TokenKind::Semi) {
            self.advance()?;
            return Ok(ExternalDecl::Declaration(Declaration {
                specs,
                declarators: Vec::new(),
                info: NodeInfo::new(loc),
                comments,
                is_target,
            }));
        }

        // 宣言子をパース
        let declarator = self.parse_declarator()?;

        // __attribute__ をスキップ
        self.try_skip_attribute()?;

        // 関数定義かどうかを判定
        // 関数定義: 宣言子の後に { が来る
        if self.check(&TokenKind::LBrace) {
            // 本体パース前のカウントを記録
            let call_count_before = self.function_call_count;
            let deref_count_before = self.deref_count;

            let body = self.parse_compound_stmt()?;

            // 差分が関数本体のカウント
            let function_call_count = self.function_call_count - call_count_before;
            let deref_count = self.deref_count - deref_count_before;

            return Ok(ExternalDecl::FunctionDef(FunctionDef {
                specs,
                declarator,
                body,
                info: NodeInfo::new(loc),
                comments,
                is_target,
                function_call_count,
                deref_count,
            }));
        }

        // 宣言の続きをパース
        let mut declarators = Vec::new();

        // 最初の宣言子(初期化子あり)
        let init = if self.check(&TokenKind::Eq) {
            self.advance()?;
            Some(self.parse_initializer()?)
        } else {
            None
        };
        declarators.push(InitDeclarator { declarator, init });

        // 追加の宣言子
        while self.check(&TokenKind::Comma) {
            self.advance()?;
            let declarator = self.parse_declarator()?;
            let init = if self.check(&TokenKind::Eq) {
                self.advance()?;
                Some(self.parse_initializer()?)
            } else {
                None
            };
            declarators.push(InitDeclarator { declarator, init });
        }

        // GCC拡張: 宣言の最後の __attribute__((...)) をスキップ
        self.try_skip_attribute()?;

        self.expect(&TokenKind::Semi)?;

        // typedef の場合、名前を登録
        if specs.storage == Some(StorageClass::Typedef) {
            for d in &declarators {
                if let Some(name) = d.declarator.name {
                    self.typedefs.insert(name);
                }
            }
        }

        Ok(ExternalDecl::Declaration(Declaration {
            specs,
            declarators,
            info: NodeInfo::new(loc),
            comments,
            is_target,
        }))
    }

    /// 宣言指定子をパース
    fn parse_decl_specs(&mut self) -> Result<DeclSpecs> {
        let mut specs = DeclSpecs::default();

        loop {
            match &self.current.kind {
                // GCC拡張: __extension__ は無視(TinyCC方式)
                TokenKind::KwExtension => {
                    self.advance()?;
                    continue;
                }
                // C11/GCC: _Thread_local, __thread は無視(TinyCC方式)
                TokenKind::KwThreadLocal | TokenKind::KwThread => {
                    self.advance()?;
                    continue;
                }
                // ストレージクラス
                TokenKind::KwTypedef => {
                    specs.storage = Some(StorageClass::Typedef);
                    self.advance()?;
                }
                TokenKind::KwExtern => {
                    specs.storage = Some(StorageClass::Extern);
                    self.advance()?;
                }
                TokenKind::KwStatic => {
                    specs.storage = Some(StorageClass::Static);
                    self.advance()?;
                }
                TokenKind::KwAuto => {
                    specs.storage = Some(StorageClass::Auto);
                    self.advance()?;
                }
                TokenKind::KwRegister => {
                    specs.storage = Some(StorageClass::Register);
                    self.advance()?;
                }
                // inline
                TokenKind::KwInline | TokenKind::KwInline2 | TokenKind::KwInline3 => {
                    specs.is_inline = true;
                    self.advance()?;
                }
                // 型修飾子
                TokenKind::KwConst | TokenKind::KwConst2 | TokenKind::KwConst3 => {
                    specs.qualifiers.is_const = true;
                    self.advance()?;
                }
                TokenKind::KwVolatile | TokenKind::KwVolatile2 | TokenKind::KwVolatile3 => {
                    specs.qualifiers.is_volatile = true;
                    self.advance()?;
                }
                TokenKind::KwRestrict | TokenKind::KwRestrict2 | TokenKind::KwRestrict3 => {
                    specs.qualifiers.is_restrict = true;
                    self.advance()?;
                }
                TokenKind::KwAtomic => {
                    specs.qualifiers.is_atomic = true;
                    self.advance()?;
                }
                // 型指定子
                TokenKind::KwVoid => {
                    specs.type_specs.push(TypeSpec::Void);
                    self.advance()?;
                }
                TokenKind::KwChar => {
                    specs.type_specs.push(TypeSpec::Char);
                    self.advance()?;
                }
                TokenKind::KwShort => {
                    specs.type_specs.push(TypeSpec::Short);
                    self.advance()?;
                }
                TokenKind::KwInt => {
                    specs.type_specs.push(TypeSpec::Int);
                    self.advance()?;
                }
                TokenKind::KwLong => {
                    specs.type_specs.push(TypeSpec::Long);
                    self.advance()?;
                }
                TokenKind::KwFloat => {
                    specs.type_specs.push(TypeSpec::Float);
                    self.advance()?;
                }
                TokenKind::KwDouble => {
                    specs.type_specs.push(TypeSpec::Double);
                    self.advance()?;
                }
                TokenKind::KwSigned | TokenKind::KwSigned2 => {
                    specs.type_specs.push(TypeSpec::Signed);
                    self.advance()?;
                }
                TokenKind::KwUnsigned => {
                    specs.type_specs.push(TypeSpec::Unsigned);
                    self.advance()?;
                }
                TokenKind::KwBool | TokenKind::KwBool2 => {
                    specs.type_specs.push(TypeSpec::Bool);
                    self.advance()?;
                }
                TokenKind::KwComplex => {
                    specs.type_specs.push(TypeSpec::Complex);
                    self.advance()?;
                }
                // GCC拡張浮動小数点型
                TokenKind::KwFloat16 => {
                    specs.type_specs.push(TypeSpec::Float16);
                    self.advance()?;
                }
                TokenKind::KwFloat32 => {
                    specs.type_specs.push(TypeSpec::Float32);
                    self.advance()?;
                }
                TokenKind::KwFloat64 => {
                    specs.type_specs.push(TypeSpec::Float64);
                    self.advance()?;
                }
                TokenKind::KwFloat128 => {
                    specs.type_specs.push(TypeSpec::Float128);
                    self.advance()?;
                }
                TokenKind::KwFloat32x => {
                    specs.type_specs.push(TypeSpec::Float32x);
                    self.advance()?;
                }
                TokenKind::KwFloat64x => {
                    specs.type_specs.push(TypeSpec::Float64x);
                    self.advance()?;
                }
                // GCC拡張: 128ビット整数
                TokenKind::KwInt128 => {
                    specs.type_specs.push(TypeSpec::Int128);
                    self.advance()?;
                }
                // typeof
                TokenKind::KwTypeof | TokenKind::KwTypeof2 | TokenKind::KwTypeof3 => {
                    self.advance()?;
                    self.expect(&TokenKind::LParen)?;
                    let expr = self.parse_expr()?;
                    self.expect(&TokenKind::RParen)?;
                    specs.type_specs.push(TypeSpec::TypeofExpr(Box::new(expr)));
                }
                // 構造体・共用体・列挙
                TokenKind::KwStruct => {
                    specs.type_specs.push(self.parse_struct_or_union(true)?);
                }
                TokenKind::KwUnion => {
                    specs.type_specs.push(self.parse_struct_or_union(false)?);
                }
                TokenKind::KwEnum => {
                    specs.type_specs.push(self.parse_enum()?);
                }
                // GCC拡張: __attribute__((...)) をスキップ
                TokenKind::KwAttribute | TokenKind::KwAttribute2 => {
                    self.skip_attribute()?;
                }
                // typedef名 or 検出済みの generic 型パラメータ
                TokenKind::Ident(id) if self.typedefs.contains(id) || self.detected_type_params.contains(id) => {
                    let id = *id;
                    specs.type_specs.push(TypeSpec::TypedefName(id));
                    self.advance()?;
                }
                // それ以外はループ終了
                _ => break,
            }
        }

        Ok(specs)
    }

    /// 構造体/共用体をパース
    fn parse_struct_or_union(&mut self, is_struct: bool) -> Result<TypeSpec> {
        let loc = self.current.loc.clone();
        self.advance()?; // struct/union

        // GCC拡張: struct __attribute__((...)) name { ... }
        self.try_skip_attribute()?;

        // 名前(オプション)
        let name = self.current_ident();
        if name.is_some() {
            self.advance()?;
        }

        // メンバーリスト(オプション)
        let members = if self.check(&TokenKind::LBrace) {
            self.advance()?;
            let mut members = Vec::new();
            while !self.check(&TokenKind::RBrace) {
                members.push(self.parse_struct_member()?);
            }
            self.expect(&TokenKind::RBrace)?;
            Some(members)
        } else {
            None
        };

        let spec = StructSpec { name, members, loc };
        if is_struct {
            Ok(TypeSpec::Struct(spec))
        } else {
            Ok(TypeSpec::Union(spec))
        }
    }

    /// 構造体メンバーをパース
    fn parse_struct_member(&mut self) -> Result<StructMember> {
        let specs = self.parse_decl_specs()?;
        let mut declarators = Vec::new();

        loop {
            let declarator = if self.check(&TokenKind::Colon) {
                None
            } else if self.check(&TokenKind::Semi) {
                None
            } else {
                Some(self.parse_declarator()?)
            };

            // GCC拡張: 宣言子の後の __attribute__ をスキップ
            self.try_skip_attribute()?;

            let bitfield = if self.check(&TokenKind::Colon) {
                self.advance()?;
                Some(Box::new(self.parse_conditional_expr()?))
            } else {
                None
            };

            declarators.push(StructDeclarator { declarator, bitfield });

            if !self.check(&TokenKind::Comma) {
                break;
            }
            self.advance()?;
        }

        self.expect(&TokenKind::Semi)?;

        Ok(StructMember { specs, declarators })
    }

    /// 列挙型をパース
    fn parse_enum(&mut self) -> Result<TypeSpec> {
        let loc = self.current.loc.clone();
        self.advance()?; // enum

        // 名前(オプション)
        let name = self.current_ident();
        if name.is_some() {
            self.advance()?;
        }

        // 列挙子リスト(オプション)
        let enumerators = if self.check(&TokenKind::LBrace) {
            self.advance()?;
            let mut enums = Vec::new();
            while !self.check(&TokenKind::RBrace) {
                let eloc = self.current.loc.clone();
                let ename = self.expect_ident()?;
                let value = if self.check(&TokenKind::Eq) {
                    self.advance()?;
                    Some(Box::new(self.parse_conditional_expr()?))
                } else {
                    None
                };
                enums.push(Enumerator {
                    name: ename,
                    value,
                    loc: eloc,
                });
                if !self.check(&TokenKind::Comma) {
                    break;
                }
                self.advance()?;
            }
            self.expect(&TokenKind::RBrace)?;
            Some(enums)
        } else {
            None
        };

        Ok(TypeSpec::Enum(EnumSpec {
            name,
            enumerators,
            loc,
        }))
    }

    /// 宣言子をパース
    fn parse_declarator(&mut self) -> Result<Declarator> {
        let loc = self.current.loc.clone();
        let mut derived = Vec::new();

        // ポインタ
        while self.check(&TokenKind::Star) {
            self.advance()?;
            let qualifiers = self.parse_type_qualifiers()?;
            derived.push(DerivedDecl::Pointer(qualifiers));
        }

        // 直接宣言子
        let (name, inner_derived) = self.parse_direct_declarator()?;
        derived.extend(inner_derived);

        Ok(Declarator {
            name,
            derived,
            loc,
        })
    }

    /// 直接宣言子をパース
    fn parse_direct_declarator(&mut self) -> Result<(Option<InternedStr>, Vec<DerivedDecl>)> {
        let mut derived = Vec::new();

        // 識別子または ( declarator )
        let name = if self.check(&TokenKind::LParen) {
            self.advance()?;
            let inner = self.parse_declarator()?;
            self.expect(&TokenKind::RParen)?;
            // 内側の派生型を先頭に追加
            derived = inner.derived;
            inner.name
        } else if let Some(id) = self.current_ident() {
            // 識別子(キーワードはTokenKind::Kw*なのでここには来ない)
            self.advance()?;
            Some(id)
        } else {
            None
        };

        // 配列・関数の後置修飾
        loop {
            if self.check(&TokenKind::LBracket) {
                derived.push(self.parse_array_declarator()?);
            } else if self.check(&TokenKind::LParen) {
                derived.push(self.parse_function_declarator()?);
            } else {
                break;
            }
        }

        Ok((name, derived))
    }

    /// 配列宣言子をパース
    fn parse_array_declarator(&mut self) -> Result<DerivedDecl> {
        self.advance()?; // [

        let mut qualifiers = TypeQualifiers::default();
        let mut is_static = false;
        let mut is_vla = false;

        // static と型修飾子
        loop {
            match &self.current.kind {
                TokenKind::KwStatic => {
                    is_static = true;
                    self.advance()?;
                }
                TokenKind::KwConst | TokenKind::KwConst2 | TokenKind::KwConst3 => {
                    qualifiers.is_const = true;
                    self.advance()?;
                }
                TokenKind::KwVolatile | TokenKind::KwVolatile2 | TokenKind::KwVolatile3 => {
                    qualifiers.is_volatile = true;
                    self.advance()?;
                }
                TokenKind::KwRestrict | TokenKind::KwRestrict2 | TokenKind::KwRestrict3 => {
                    qualifiers.is_restrict = true;
                    self.advance()?;
                }
                _ => break,
            }
        }

        // サイズ式
        let size = if self.check(&TokenKind::RBracket) {
            None
        } else if self.check(&TokenKind::Star) {
            is_vla = true;
            self.advance()?;
            None
        } else {
            Some(Box::new(self.parse_assignment_expr()?))
        };

        self.expect(&TokenKind::RBracket)?;

        Ok(DerivedDecl::Array(ArrayDecl {
            size,
            qualifiers,
            is_static,
            is_vla,
        }))
    }

    /// 関数宣言子をパース
    fn parse_function_declarator(&mut self) -> Result<DerivedDecl> {
        self.advance()?; // (

        if self.check(&TokenKind::RParen) {
            self.advance()?;
            return Ok(DerivedDecl::Function(ParamList {
                params: Vec::new(),
                is_variadic: false,
            }));
        }

        let mut params = Vec::new();
        let mut is_variadic = false;

        loop {
            if self.check(&TokenKind::Ellipsis) {
                is_variadic = true;
                self.advance()?;
                break;
            }

            let loc = self.current.loc.clone();
            let specs = self.parse_decl_specs()?;
            let declarator = if self.check(&TokenKind::Comma) || self.check(&TokenKind::RParen) {
                None
            } else {
                Some(self.parse_declarator()?)
            };

            // GCC拡張: パラメータ後の __attribute__((...)) をスキップ
            self.try_skip_attribute()?;

            params.push(ParamDecl {
                specs,
                declarator,
                loc,
            });

            if !self.check(&TokenKind::Comma) {
                break;
            }
            self.advance()?;
        }

        self.expect(&TokenKind::RParen)?;

        Ok(DerivedDecl::Function(ParamList { params, is_variadic }))
    }

    /// 型修飾子をパース
    fn parse_type_qualifiers(&mut self) -> Result<TypeQualifiers> {
        let mut qualifiers = TypeQualifiers::default();

        loop {
            match &self.current.kind {
                TokenKind::KwConst | TokenKind::KwConst2 | TokenKind::KwConst3 => {
                    qualifiers.is_const = true;
                    self.advance()?;
                }
                TokenKind::KwVolatile | TokenKind::KwVolatile2 | TokenKind::KwVolatile3 => {
                    qualifiers.is_volatile = true;
                    self.advance()?;
                }
                TokenKind::KwRestrict | TokenKind::KwRestrict2 | TokenKind::KwRestrict3 => {
                    qualifiers.is_restrict = true;
                    self.advance()?;
                }
                TokenKind::KwAtomic => {
                    qualifiers.is_atomic = true;
                    self.advance()?;
                }
                _ => break,
            }
        }

        Ok(qualifiers)
    }

    /// 初期化子をパース
    fn parse_initializer(&mut self) -> Result<Initializer> {
        if self.check(&TokenKind::LBrace) {
            self.advance()?;
            let mut items = Vec::new();

            while !self.check(&TokenKind::RBrace) {
                let designation = self.parse_designation()?;
                let init = self.parse_initializer()?;
                items.push(InitializerItem { designation, init });

                if !self.check(&TokenKind::Comma) {
                    break;
                }
                self.advance()?;
            }
            self.expect(&TokenKind::RBrace)?;

            Ok(Initializer::List(items))
        } else {
            Ok(Initializer::Expr(Box::new(self.parse_assignment_expr()?)))
        }
    }

    /// 指示子列をパース
    fn parse_designation(&mut self) -> Result<Vec<Designator>> {
        let mut designators = Vec::new();

        loop {
            if self.check(&TokenKind::LBracket) {
                self.advance()?;
                let index = self.parse_conditional_expr()?;
                self.expect(&TokenKind::RBracket)?;
                designators.push(Designator::Index(Box::new(index)));
            } else if self.check(&TokenKind::Dot) {
                self.advance()?;
                let name = self.expect_ident()?;
                designators.push(Designator::Member(name));
            } else {
                break;
            }
        }

        if !designators.is_empty() {
            self.expect(&TokenKind::Eq)?;
        }

        Ok(designators)
    }

    /// 型名をパース
    pub fn parse_type_name(&mut self) -> Result<TypeName> {
        let specs = self.parse_decl_specs()?;
        let declarator = if self.check(&TokenKind::RParen) {
            None
        } else {
            Some(self.parse_abstract_declarator()?)
        };
        Ok(TypeName { specs, declarator })
    }

    /// 抽象宣言子をパース
    fn parse_abstract_declarator(&mut self) -> Result<AbstractDeclarator> {
        let mut derived = Vec::new();

        // ポインタ
        while self.check(&TokenKind::Star) {
            self.advance()?;
            let qualifiers = self.parse_type_qualifiers()?;
            derived.push(DerivedDecl::Pointer(qualifiers));
        }

        // 直接抽象宣言子
        if self.check(&TokenKind::LParen) {
            // ( abstract-declarator ) または ( parameter-list )
            // 先読みで判定が必要だが、簡略化のためここでは単純に処理
            self.advance()?;
            if !self.check(&TokenKind::RParen) && !self.is_type_start() {
                let inner = self.parse_abstract_declarator()?;
                self.expect(&TokenKind::RParen)?;
                derived.extend(inner.derived);
            } else {
                // パラメータリストとして処理
                let params = self.parse_param_list_inner()?;
                derived.push(DerivedDecl::Function(params));
            }
        }

        // 配列・関数の後置修飾
        loop {
            if self.check(&TokenKind::LBracket) {
                derived.push(self.parse_array_declarator()?);
            } else if self.check(&TokenKind::LParen) {
                derived.push(self.parse_function_declarator()?);
            } else {
                break;
            }
        }

        Ok(AbstractDeclarator { derived })
    }

    /// パラメータリストの内部をパース(RParen消費済み前提ではない)
    fn parse_param_list_inner(&mut self) -> Result<ParamList> {
        if self.check(&TokenKind::RParen) {
            self.advance()?;
            return Ok(ParamList {
                params: Vec::new(),
                is_variadic: false,
            });
        }

        let mut params = Vec::new();
        let mut is_variadic = false;

        loop {
            if self.check(&TokenKind::Ellipsis) {
                is_variadic = true;
                self.advance()?;
                break;
            }

            let loc = self.current.loc.clone();
            let specs = self.parse_decl_specs()?;
            let declarator = if self.check(&TokenKind::Comma) || self.check(&TokenKind::RParen) {
                None
            } else if self.check(&TokenKind::Star) || self.check(&TokenKind::LParen) || self.check(&TokenKind::LBracket) {
                Some(self.parse_declarator()?)
            } else if let Some(id) = self.current_ident() {
                // 識別子(キーワードはTokenKind::Kw*なのでここには来ない)
                // typedef名でなければ宣言子
                if !self.typedefs.contains(&id) {
                    Some(self.parse_declarator()?)
                } else {
                    None
                }
            } else {
                None
            };

            // GCC拡張: パラメータ後の __attribute__((...)) をスキップ
            self.try_skip_attribute()?;

            params.push(ParamDecl {
                specs,
                declarator,
                loc,
            });

            if !self.check(&TokenKind::Comma) {
                break;
            }
            self.advance()?;
        }

        self.expect(&TokenKind::RParen)?;

        Ok(ParamList { params, is_variadic })
    }

    // ==================== 文のパース ====================

    /// 複合文をパース
    fn parse_compound_stmt(&mut self) -> Result<CompoundStmt> {
        let loc = self.current.loc.clone();
        self.expect(&TokenKind::LBrace)?;

        let mut items = Vec::new();
        while !self.check(&TokenKind::RBrace) {
            items.push(self.parse_block_item()?);
        }

        self.expect(&TokenKind::RBrace)?;

        Ok(CompoundStmt { items, info: NodeInfo::new(loc) })
    }

    /// ブロック項目をパース
    pub(crate) fn parse_block_item(&mut self) -> Result<BlockItem> {
        if self.is_declaration_start() {
            Ok(BlockItem::Decl(self.parse_declaration()?))
        } else {
            Ok(BlockItem::Stmt(self.parse_stmt()?))
        }
    }

    /// 宣言をパース
    fn parse_declaration(&mut self) -> Result<Declaration> {
        let comments = self.current.leading_comments.clone();
        let loc = self.current.loc.clone();
        let is_target = self.source.is_file_in_target(loc.file_id);
        let specs = self.parse_decl_specs()?;

        if self.check(&TokenKind::Semi) {
            self.advance()?;
            return Ok(Declaration {
                specs,
                declarators: Vec::new(),
                info: NodeInfo::new(loc),
                comments,
                is_target,
            });
        }

        let mut declarators = Vec::new();

        loop {
            let declarator = self.parse_declarator()?;

            // GCC拡張: 宣言子の後の __attribute__((...)) をスキップ
            self.try_skip_attribute()?;

            let init = if self.check(&TokenKind::Eq) {
                self.advance()?;
                Some(self.parse_initializer()?)
            } else {
                None
            };
            declarators.push(InitDeclarator { declarator, init });

            if !self.check(&TokenKind::Comma) {
                break;
            }
            self.advance()?;
        }

        // GCC拡張: 宣言の最後の __attribute__((...)) をスキップ
        self.try_skip_attribute()?;

        self.expect(&TokenKind::Semi)?;

        // typedef の場合、名前を登録
        if specs.storage == Some(StorageClass::Typedef) {
            for d in &declarators {
                if let Some(name) = d.declarator.name {
                    self.typedefs.insert(name);
                }
            }
        }

        Ok(Declaration {
            specs,
            declarators,
            info: NodeInfo::new(loc),
            comments,
            is_target,
        })
    }

    /// 文をパース
    fn parse_stmt(&mut self) -> Result<Stmt> {
        let loc = self.current.loc.clone();

        // キーワードに基づく文のパース
        match &self.current.kind {
            // ラベル文
            TokenKind::KwCase => return self.parse_case_stmt(),
            TokenKind::KwDefault => return self.parse_default_stmt(),
            // 複合文
            TokenKind::LBrace => return Ok(Stmt::Compound(self.parse_compound_stmt()?)),
            // 制御フロー文
            TokenKind::KwIf => return self.parse_if_stmt(),
            TokenKind::KwSwitch => return self.parse_switch_stmt(),
            TokenKind::KwWhile => return self.parse_while_stmt(),
            TokenKind::KwDo => return self.parse_do_while_stmt(),
            TokenKind::KwFor => return self.parse_for_stmt(),
            TokenKind::KwGoto => {
                self.advance()?;
                let name = self.expect_ident()?;
                self.expect(&TokenKind::Semi)?;
                return Ok(Stmt::Goto(name, loc));
            }
            TokenKind::KwContinue => {
                self.advance()?;
                self.expect(&TokenKind::Semi)?;
                return Ok(Stmt::Continue(loc));
            }
            TokenKind::KwBreak => {
                self.advance()?;
                self.expect(&TokenKind::Semi)?;
                return Ok(Stmt::Break(loc));
            }
            TokenKind::KwReturn => {
                self.advance()?;
                let expr = if self.check(&TokenKind::Semi) {
                    None
                } else {
                    Some(Box::new(self.parse_expr()?))
                };
                self.expect(&TokenKind::Semi)?;
                return Ok(Stmt::Return(expr, loc));
            }
            // __asm__ 文
            TokenKind::KwAsm | TokenKind::KwAsm2 | TokenKind::KwAsm3 => {
                return self.parse_asm_stmt();
            }
            _ => {}
        }

        // 式文
        if self.check(&TokenKind::Semi) {
            self.advance()?;
            return Ok(Stmt::Expr(None, loc));
        }

        let expr = self.parse_expr()?;

        // ラベルのチェック(識別子 : の場合)
        if self.check(&TokenKind::Colon) {
            if let ExprKind::Ident(name) = expr.kind {
                self.advance()?;
                let stmt = self.parse_stmt()?;
                return Ok(Stmt::Label {
                    name,
                    stmt: Box::new(stmt),
                    loc,
                });
            }
        }

        self.expect(&TokenKind::Semi)?;
        Ok(Stmt::Expr(Some(Box::new(expr)), loc))
    }

    fn parse_if_stmt(&mut self) -> Result<Stmt> {
        let loc = self.current.loc.clone();
        self.advance()?; // if
        self.expect(&TokenKind::LParen)?;
        let cond = Box::new(self.parse_expr()?);
        self.expect(&TokenKind::RParen)?;
        let then_stmt = Box::new(self.parse_stmt()?);

        let else_stmt = if matches!(self.current.kind, TokenKind::KwElse) {
            self.advance()?;
            Some(Box::new(self.parse_stmt()?))
        } else {
            None
        };

        Ok(Stmt::If {
            cond,
            then_stmt,
            else_stmt,
            loc,
        })
    }

    fn parse_switch_stmt(&mut self) -> Result<Stmt> {
        let loc = self.current.loc.clone();
        self.advance()?; // switch
        self.expect(&TokenKind::LParen)?;
        let expr = Box::new(self.parse_expr()?);
        self.expect(&TokenKind::RParen)?;
        let body = Box::new(self.parse_stmt()?);

        Ok(Stmt::Switch { expr, body, loc })
    }

    fn parse_while_stmt(&mut self) -> Result<Stmt> {
        let loc = self.current.loc.clone();
        self.advance()?; // while
        self.expect(&TokenKind::LParen)?;
        let cond = Box::new(self.parse_expr()?);
        self.expect(&TokenKind::RParen)?;
        let body = Box::new(self.parse_stmt()?);

        Ok(Stmt::While { cond, body, loc })
    }

    fn parse_do_while_stmt(&mut self) -> Result<Stmt> {
        let loc = self.current.loc.clone();
        self.advance()?; // do
        let body = Box::new(self.parse_stmt()?);
        // expect 'while' keyword
        if !matches!(self.current.kind, TokenKind::KwWhile) {
            return Err(CompileError::Parse {
                loc: self.current.loc.clone(),
                kind: ParseError::UnexpectedToken {
                    expected: "while".to_string(),
                    found: self.current.kind.clone(),
                },
            });
        }
        self.advance()?;
        self.expect(&TokenKind::LParen)?;
        let cond = Box::new(self.parse_expr()?);
        self.expect(&TokenKind::RParen)?;

        // allow_missing_semi が true の場合、; は任意
        if self.allow_missing_semi {
            if self.check(&TokenKind::Semi) {
                self.advance()?;
            }
        } else {
            self.expect(&TokenKind::Semi)?;
        }

        Ok(Stmt::DoWhile { body, cond, loc })
    }

    fn parse_for_stmt(&mut self) -> Result<Stmt> {
        let loc = self.current.loc.clone();
        self.advance()?; // for
        self.expect(&TokenKind::LParen)?;

        // 初期化部
        let init = if self.check(&TokenKind::Semi) {
            self.advance()?;
            None
        } else if self.is_declaration_start() {
            let decl = self.parse_declaration()?;
            Some(ForInit::Decl(decl))
        } else {
            let expr = self.parse_expr()?;
            self.expect(&TokenKind::Semi)?;
            Some(ForInit::Expr(Box::new(expr)))
        };

        // 条件部
        let cond = if self.check(&TokenKind::Semi) {
            None
        } else {
            Some(Box::new(self.parse_expr()?))
        };
        self.expect(&TokenKind::Semi)?;

        // 更新部
        let step = if self.check(&TokenKind::RParen) {
            None
        } else {
            Some(Box::new(self.parse_expr()?))
        };
        self.expect(&TokenKind::RParen)?;

        let body = Box::new(self.parse_stmt()?);

        Ok(Stmt::For {
            init,
            cond,
            step,
            body,
            loc,
        })
    }

    fn parse_case_stmt(&mut self) -> Result<Stmt> {
        let loc = self.current.loc.clone();
        self.advance()?; // case
        let expr = Box::new(self.parse_conditional_expr()?);
        self.expect(&TokenKind::Colon)?;
        let stmt = Box::new(self.parse_stmt()?);

        Ok(Stmt::Case { expr, stmt, loc })
    }

    fn parse_default_stmt(&mut self) -> Result<Stmt> {
        let loc = self.current.loc.clone();
        self.advance()?; // default
        self.expect(&TokenKind::Colon)?;
        let stmt = Box::new(self.parse_stmt()?);

        Ok(Stmt::Default { stmt, loc })
    }

    fn parse_asm_stmt(&mut self) -> Result<Stmt> {
        let loc = self.current.loc.clone();
        self.advance()?; // asm / __asm / __asm__

        // volatile / __volatile__ はスキップ
        while matches!(
            self.current.kind,
            TokenKind::KwVolatile | TokenKind::KwVolatile2 | TokenKind::KwVolatile3
        ) {
            self.advance()?;
        }

        // 括弧内をスキップ
        self.expect(&TokenKind::LParen)?;
        self.skip_balanced_parens()?;

        self.expect(&TokenKind::Semi)?;
        Ok(Stmt::Asm { loc })
    }

    // ==================== 式のパース ====================

    /// 式をパース(コンマ式を含む)
    fn parse_expr(&mut self) -> Result<Expr> {
        let lhs = self.parse_assignment_expr()?;

        if self.check(&TokenKind::Comma) {
            let loc = self.current.loc.clone();
            self.advance()?;
            let rhs = self.parse_expr()?;
            return Ok(Expr::new(
                ExprKind::Comma {
                    lhs: Box::new(lhs),
                    rhs: Box::new(rhs),
                },
                loc,
            ));
        }

        Ok(lhs)
    }

    /// 代入式をパース
    fn parse_assignment_expr(&mut self) -> Result<Expr> {
        let lhs = self.parse_conditional_expr()?;

        let op = match &self.current.kind {
            TokenKind::Eq => Some(AssignOp::Assign),
            TokenKind::StarEq => Some(AssignOp::MulAssign),
            TokenKind::SlashEq => Some(AssignOp::DivAssign),
            TokenKind::PercentEq => Some(AssignOp::ModAssign),
            TokenKind::PlusEq => Some(AssignOp::AddAssign),
            TokenKind::MinusEq => Some(AssignOp::SubAssign),
            TokenKind::LtLtEq => Some(AssignOp::ShlAssign),
            TokenKind::GtGtEq => Some(AssignOp::ShrAssign),
            TokenKind::AmpEq => Some(AssignOp::AndAssign),
            TokenKind::CaretEq => Some(AssignOp::XorAssign),
            TokenKind::PipeEq => Some(AssignOp::OrAssign),
            _ => None,
        };

        if let Some(op) = op {
            let loc = self.current.loc.clone();
            self.advance()?;
            let rhs = self.parse_assignment_expr()?;
            return Ok(Expr::new(
                ExprKind::Assign {
                    op,
                    lhs: Box::new(lhs),
                    rhs: Box::new(rhs),
                },
                loc,
            ));
        }

        Ok(lhs)
    }

    /// 条件式をパース
    fn parse_conditional_expr(&mut self) -> Result<Expr> {
        let cond = self.parse_logical_or_expr()?;

        if self.check(&TokenKind::Question) {
            let loc = self.current.loc.clone();
            self.advance()?;
            let then_expr = self.parse_expr()?;
            self.expect(&TokenKind::Colon)?;
            let else_expr = self.parse_conditional_expr()?;
            return Ok(Expr::new(
                ExprKind::Conditional {
                    cond: Box::new(cond),
                    then_expr: Box::new(then_expr),
                    else_expr: Box::new(else_expr),
                },
                loc,
            ));
        }

        Ok(cond)
    }

    /// 論理OR式をパース
    fn parse_logical_or_expr(&mut self) -> Result<Expr> {
        let mut lhs = self.parse_logical_and_expr()?;

        while self.check(&TokenKind::PipePipe) {
            let loc = self.current.loc.clone();
            self.advance()?;
            let rhs = self.parse_logical_and_expr()?;
            lhs = Expr::new(
                ExprKind::Binary {
                    op: BinOp::LogOr,
                    lhs: Box::new(lhs),
                    rhs: Box::new(rhs),
                },
                loc,
            );
        }

        Ok(lhs)
    }

    /// 論理AND式をパース
    fn parse_logical_and_expr(&mut self) -> Result<Expr> {
        let mut lhs = self.parse_bitwise_or_expr()?;

        while self.check(&TokenKind::AmpAmp) {
            let loc = self.current.loc.clone();
            self.advance()?;
            let rhs = self.parse_bitwise_or_expr()?;
            lhs = Expr::new(
                ExprKind::Binary {
                    op: BinOp::LogAnd,
                    lhs: Box::new(lhs),
                    rhs: Box::new(rhs),
                },
                loc,
            );
        }

        Ok(lhs)
    }

    /// ビットOR式をパース
    fn parse_bitwise_or_expr(&mut self) -> Result<Expr> {
        let mut lhs = self.parse_bitwise_xor_expr()?;

        while self.check(&TokenKind::Pipe) {
            let loc = self.current.loc.clone();
            self.advance()?;
            let rhs = self.parse_bitwise_xor_expr()?;
            lhs = Expr::new(
                ExprKind::Binary {
                    op: BinOp::BitOr,
                    lhs: Box::new(lhs),
                    rhs: Box::new(rhs),
                },
                loc,
            );
        }

        Ok(lhs)
    }

    /// ビットXOR式をパース
    fn parse_bitwise_xor_expr(&mut self) -> Result<Expr> {
        let mut lhs = self.parse_bitwise_and_expr()?;

        while self.check(&TokenKind::Caret) {
            let loc = self.current.loc.clone();
            self.advance()?;
            let rhs = self.parse_bitwise_and_expr()?;
            lhs = Expr::new(
                ExprKind::Binary {
                    op: BinOp::BitXor,
                    lhs: Box::new(lhs),
                    rhs: Box::new(rhs),
                },
                loc,
            );
        }

        Ok(lhs)
    }

    /// ビットAND式をパース
    fn parse_bitwise_and_expr(&mut self) -> Result<Expr> {
        let mut lhs = self.parse_equality_expr()?;

        while self.check(&TokenKind::Amp) {
            let loc = self.current.loc.clone();
            self.advance()?;
            let rhs = self.parse_equality_expr()?;
            lhs = Expr::new(
                ExprKind::Binary {
                    op: BinOp::BitAnd,
                    lhs: Box::new(lhs),
                    rhs: Box::new(rhs),
                },
                loc,
            );
        }

        Ok(lhs)
    }

    /// 等価式をパース
    fn parse_equality_expr(&mut self) -> Result<Expr> {
        let mut lhs = self.parse_relational_expr()?;

        loop {
            let op = match &self.current.kind {
                TokenKind::EqEq => BinOp::Eq,
                TokenKind::BangEq => BinOp::Ne,
                _ => break,
            };
            let loc = self.current.loc.clone();
            self.advance()?;
            let rhs = self.parse_relational_expr()?;
            lhs = Expr::new(
                ExprKind::Binary {
                    op,
                    lhs: Box::new(lhs),
                    rhs: Box::new(rhs),
                },
                loc,
            );
        }

        Ok(lhs)
    }

    /// 関係式をパース
    fn parse_relational_expr(&mut self) -> Result<Expr> {
        let mut lhs = self.parse_shift_expr()?;

        loop {
            let op = match &self.current.kind {
                TokenKind::Lt => BinOp::Lt,
                TokenKind::Gt => BinOp::Gt,
                TokenKind::LtEq => BinOp::Le,
                TokenKind::GtEq => BinOp::Ge,
                _ => break,
            };
            let loc = self.current.loc.clone();
            self.advance()?;
            let rhs = self.parse_shift_expr()?;
            lhs = Expr::new(
                ExprKind::Binary {
                    op,
                    lhs: Box::new(lhs),
                    rhs: Box::new(rhs),
                },
                loc,
            );
        }

        Ok(lhs)
    }

    /// シフト式をパース
    fn parse_shift_expr(&mut self) -> Result<Expr> {
        let mut lhs = self.parse_additive_expr()?;

        loop {
            let op = match &self.current.kind {
                TokenKind::LtLt => BinOp::Shl,
                TokenKind::GtGt => BinOp::Shr,
                _ => break,
            };
            let loc = self.current.loc.clone();
            self.advance()?;
            let rhs = self.parse_additive_expr()?;
            lhs = Expr::new(
                ExprKind::Binary {
                    op,
                    lhs: Box::new(lhs),
                    rhs: Box::new(rhs),
                },
                loc,
            );
        }

        Ok(lhs)
    }

    /// 加減式をパース
    fn parse_additive_expr(&mut self) -> Result<Expr> {
        let mut lhs = self.parse_multiplicative_expr()?;

        loop {
            let op = match &self.current.kind {
                TokenKind::Plus => BinOp::Add,
                TokenKind::Minus => BinOp::Sub,
                _ => break,
            };
            let loc = self.current.loc.clone();
            self.advance()?;
            let rhs = self.parse_multiplicative_expr()?;
            lhs = Expr::new(
                ExprKind::Binary {
                    op,
                    lhs: Box::new(lhs),
                    rhs: Box::new(rhs),
                },
                loc,
            );
        }

        Ok(lhs)
    }

    /// 乗除式をパース
    fn parse_multiplicative_expr(&mut self) -> Result<Expr> {
        let mut lhs = self.parse_cast_expr()?;

        loop {
            let op = match &self.current.kind {
                TokenKind::Star => BinOp::Mul,
                TokenKind::Slash => BinOp::Div,
                TokenKind::Percent => BinOp::Mod,
                _ => break,
            };
            let loc = self.current.loc.clone();
            self.advance()?;
            let rhs = self.parse_cast_expr()?;
            lhs = Expr::new(
                ExprKind::Binary {
                    op,
                    lhs: Box::new(lhs),
                    rhs: Box::new(rhs),
                },
                loc,
            );
        }

        Ok(lhs)
    }

    /// キャスト式をパース
    fn parse_cast_expr(&mut self) -> Result<Expr> {
        // ( type-name ) cast-expression のみをここで処理
        // ( expr ) は parse_primary_expr で処理し、postfix操作を許可する
        if self.check(&TokenKind::LParen) {
            let loc = self.current.loc.clone();
            self.advance()?; // (

            // 1. 確定的な型名(キーワード/typedef/既検出の generic param)
            if self.is_type_start() {
                return self.finish_parse_cast_or_compound_lit(loc);
            }

            // 2. 未検出の generic param → 先読みで判定
            if let Some(id) = self.current_ident() {
                if self.generic_params.contains_key(&id)
                    && self.looks_like_generic_cast()
                {
                    // 型パラメータとして記録
                    self.detected_type_params.insert(id);
                    return self.finish_parse_cast_or_compound_lit(loc);
                }
            }

            if self.check(&TokenKind::LBrace) {
                // GCC拡張: ステートメント式 ({ ... })
                let stmt = self.parse_compound_stmt()?;
                self.expect(&TokenKind::RParen)?;
                // ステートメント式の後もpostfixを許可する
                let stmt_expr = Expr::new(ExprKind::StmtExpr(stmt), loc);
                return self.parse_postfix_on(stmt_expr);
            } else {
                // 括弧で囲まれた式 - parse_primary_exprに任せる
                // いったん戻してparse_unary_exprに任せる
                // 注: ここではadvanceを巻き戻す代わりに、式をパースしてからpostfixを処理
                let expr = self.parse_expr()?;
                self.expect(&TokenKind::RParen)?;
                // postfix操作を許可する(->や.など)
                return self.parse_postfix_on(expr);
            }
        }

        self.parse_unary_expr()
    }

    /// キャスト式または複合リテラルのパースを完了する
    ///
    /// `parse_cast_expr` で `(` を消費し、current が型名の先頭にある状態で呼ぶ。
    fn finish_parse_cast_or_compound_lit(&mut self, loc: SourceLocation) -> Result<Expr> {
        let type_name = self.parse_type_name()?;
        self.expect(&TokenKind::RParen)?;

        // 複合リテラルのチェック
        if self.check(&TokenKind::LBrace) {
            self.advance()?;
            let mut items = Vec::new();
            while !self.check(&TokenKind::RBrace) {
                let designation = self.parse_designation()?;
                let init = self.parse_initializer()?;
                items.push(InitializerItem { designation, init });
                if !self.check(&TokenKind::Comma) {
                    break;
                }
                self.advance()?;
            }
            self.expect(&TokenKind::RBrace)?;
            return Ok(Expr::new(
                ExprKind::CompoundLit {
                    type_name: Box::new(type_name),
                    init: items,
                },
                loc,
            ));
        }

        let expr = self.parse_cast_expr()?;
        Ok(Expr::new(
            ExprKind::Cast {
                type_name: Box::new(type_name),
                expr: Box::new(expr),
            },
            loc,
        ))
    }

    /// generic param がキャスト式の型として使われているかを先読みで判定
    ///
    /// 呼び出し時点: current = generic param の Ident
    /// TokenSource::next_token + unget_token で先読み
    fn looks_like_generic_cast(&mut self) -> bool {
        // 先読み1: param の次のトークン
        let next1 = match self.source.next_token() {
            Ok(t) => t,
            Err(_) => return false,
        };

        let result = match &next1.kind {
            // (PARAM *...) — ポインタキャスト
            TokenKind::Star => true,

            // (PARAM) — 値キャスト候補、後続の文脈で判定
            TokenKind::RParen => {
                let next2 = match self.source.next_token() {
                    Ok(t) => t,
                    Err(_) => {
                        self.source.unget_token(next1);
                        return false;
                    }
                };
                // ) の後に式の開始トークンが続くならキャスト
                let is_cast = match &next2.kind {
                    TokenKind::LParen       // (PARAM)(expr)
                    | TokenKind::Ident(_)   // (PARAM)ident
                    | TokenKind::IntLit(_) | TokenKind::UIntLit(_)
                    | TokenKind::FloatLit(_)
                    | TokenKind::StringLit(_) | TokenKind::CharLit(_)
                    | TokenKind::Star       // (PARAM)*ptr (deref)
                    | TokenKind::Amp        // (PARAM)&x
                    | TokenKind::Bang       // (PARAM)!x
                    | TokenKind::Tilde      // (PARAM)~x
                    | TokenKind::KwSizeof   // (PARAM)sizeof(x)
                    => true,

                    // (PARAM)-x: 3トークン先読みで判定
                    // `-` の次が数値リテラルなら cast (e.g. (T)-1)
                    // それ以外なら二項減算 (e.g. (val) - func(...))
                    TokenKind::Minus => {
                        let next3 = match self.source.next_token() {
                            Ok(t) => t,
                            Err(_) => {
                                self.source.unget_token(next2);
                                self.source.unget_token(next1);
                                return false;
                            }
                        };
                        let is_numeric = matches!(&next3.kind,
                            TokenKind::IntLit(_)
                            | TokenKind::UIntLit(_)
                            | TokenKind::FloatLit(_)
                        );
                        self.source.unget_token(next3);
                        is_numeric
                    }

                    _ => false,
                };
                self.source.unget_token(next2);
                is_cast
            }

            // (PARAM + ...) など — 括弧付き式
            _ => false,
        };

        self.source.unget_token(next1);
        result
    }

    /// 既存の式に対してpostfix操作をパース
    fn parse_postfix_on(&mut self, mut expr: Expr) -> Result<Expr> {
        loop {
            let loc = self.current.loc.clone();
            match &self.current.kind {
                TokenKind::LBracket => {
                    self.advance()?;
                    let index = self.parse_expr()?;
                    self.expect(&TokenKind::RBracket)?;
                    expr = Expr::new(
                        ExprKind::Index {
                            expr: Box::new(expr),
                            index: Box::new(index),
                        },
                        loc,
                    );
                }
                TokenKind::LParen => {
                    self.advance()?;
                    let mut args = Vec::new();
                    while !self.check(&TokenKind::RParen) {
                        args.push(self.parse_assignment_expr()?);
                        if !self.check(&TokenKind::Comma) {
                            break;
                        }
                        self.advance()?;
                    }
                    self.expect(&TokenKind::RParen)?;
                    self.function_call_count += 1;
                    expr = Expr::new(
                        ExprKind::Call {
                            func: Box::new(expr),
                            args,
                        },
                        loc,
                    );
                }
                TokenKind::Dot => {
                    self.advance()?;
                    let member = self.expect_ident()?;
                    expr = Expr::new(
                        ExprKind::Member {
                            expr: Box::new(expr),
                            member,
                        },
                        loc,
                    );
                }
                TokenKind::Arrow => {
                    self.advance()?;
                    let member = self.expect_ident()?;
                    self.deref_count += 1;
                    expr = Expr::new(
                        ExprKind::PtrMember {
                            expr: Box::new(expr),
                            member,
                        },
                        loc,
                    );
                }
                TokenKind::PlusPlus => {
                    self.advance()?;
                    expr = Expr::new(ExprKind::PostInc(Box::new(expr)), loc);
                }
                TokenKind::MinusMinus => {
                    self.advance()?;
                    expr = Expr::new(ExprKind::PostDec(Box::new(expr)), loc);
                }
                _ => break,
            }
        }
        Ok(expr)
    }

    /// 単項式をパース
    fn parse_unary_expr(&mut self) -> Result<Expr> {
        let loc = self.current.loc.clone();

        match &self.current.kind {
            TokenKind::PlusPlus => {
                self.advance()?;
                let expr = self.parse_unary_expr()?;
                Ok(Expr::new(ExprKind::PreInc(Box::new(expr)), loc))
            }
            TokenKind::MinusMinus => {
                self.advance()?;
                let expr = self.parse_unary_expr()?;
                Ok(Expr::new(ExprKind::PreDec(Box::new(expr)), loc))
            }
            TokenKind::Amp => {
                self.advance()?;
                let expr = self.parse_cast_expr()?;
                Ok(Expr::new(ExprKind::AddrOf(Box::new(expr)), loc))
            }
            TokenKind::Star => {
                self.advance()?;
                let expr = self.parse_cast_expr()?;
                self.deref_count += 1;
                Ok(Expr::new(ExprKind::Deref(Box::new(expr)), loc))
            }
            TokenKind::Plus => {
                self.advance()?;
                let expr = self.parse_cast_expr()?;
                Ok(Expr::new(ExprKind::UnaryPlus(Box::new(expr)), loc))
            }
            TokenKind::Minus => {
                self.advance()?;
                let expr = self.parse_cast_expr()?;
                Ok(Expr::new(ExprKind::UnaryMinus(Box::new(expr)), loc))
            }
            TokenKind::Tilde => {
                self.advance()?;
                let expr = self.parse_cast_expr()?;
                Ok(Expr::new(ExprKind::BitNot(Box::new(expr)), loc))
            }
            TokenKind::Bang => {
                self.advance()?;
                let expr = self.parse_cast_expr()?;
                Ok(Expr::new(ExprKind::LogNot(Box::new(expr)), loc))
            }
            TokenKind::KwSizeof => {
                self.advance()?;
                if self.check(&TokenKind::LParen) {
                    self.advance()?; // (
                    if self.is_type_start() {
                        // sizeof(type)
                        let type_name = self.parse_type_name()?;
                        self.expect(&TokenKind::RParen)?;
                        Ok(Expr::new(ExprKind::SizeofType(Box::new(type_name)), loc))
                    } else {
                        // sizeof(expr) - 括弧付きの式
                        let expr = self.parse_expr()?;
                        self.expect(&TokenKind::RParen)?;
                        Ok(Expr::new(ExprKind::Sizeof(Box::new(expr)), loc))
                    }
                } else {
                    let expr = self.parse_unary_expr()?;
                    Ok(Expr::new(ExprKind::Sizeof(Box::new(expr)), loc))
                }
            }
            TokenKind::KwAlignof | TokenKind::KwAlignof2 | TokenKind::KwAlignof3 => {
                self.advance()?;
                self.expect(&TokenKind::LParen)?;
                let type_name = self.parse_type_name()?;
                self.expect(&TokenKind::RParen)?;
                Ok(Expr::new(ExprKind::Alignof(Box::new(type_name)), loc))
            }
            // GCC拡張: __extension__ は無視して続行(TinyCC方式)
            TokenKind::KwExtension => {
                self.advance()?;
                self.parse_unary_expr()
            }
            _ => self.parse_postfix_expr(),
        }
    }

    /// 後置式をパース
    fn parse_postfix_expr(&mut self) -> Result<Expr> {
        let mut expr = self.parse_primary_expr()?;

        loop {
            let loc = self.current.loc.clone();
            match &self.current.kind {
                TokenKind::LBracket => {
                    self.advance()?;
                    let index = self.parse_expr()?;
                    self.expect(&TokenKind::RBracket)?;
                    expr = Expr::new(
                        ExprKind::Index {
                            expr: Box::new(expr),
                            index: Box::new(index),
                        },
                        loc,
                    );
                }
                TokenKind::LParen => {
                    // ビルトイン呼び出し判定
                    if let ExprKind::Ident(name) = &expr.kind {
                        if self.is_type_arg_builtin(*name) {
                            let builtin_name = *name;
                            self.advance()?; // (
                            let args = self.parse_builtin_args()?;
                            self.expect(&TokenKind::RParen)?;
                            self.function_call_count += 1;
                            expr = Expr::new(
                                ExprKind::BuiltinCall { name: builtin_name, args },
                                loc,
                            );
                            continue;
                        }
                    }
                    // 通常の関数呼び出し
                    self.advance()?;
                    let mut args = Vec::new();
                    if !self.check(&TokenKind::RParen) {
                        loop {
                            args.push(self.parse_assignment_expr()?);
                            if !self.check(&TokenKind::Comma) {
                                break;
                            }
                            self.advance()?;
                        }
                    }
                    self.expect(&TokenKind::RParen)?;
                    self.function_call_count += 1;
                    expr = Expr::new(
                        ExprKind::Call {
                            func: Box::new(expr),
                            args,
                        },
                        loc,
                    );
                }
                TokenKind::Dot => {
                    self.advance()?;
                    let member = self.expect_ident()?;
                    expr = Expr::new(
                        ExprKind::Member {
                            expr: Box::new(expr),
                            member,
                        },
                        loc,
                    );
                }
                TokenKind::Arrow => {
                    self.advance()?;
                    let member = self.expect_ident()?;
                    self.deref_count += 1;
                    expr = Expr::new(
                        ExprKind::PtrMember {
                            expr: Box::new(expr),
                            member,
                        },
                        loc,
                    );
                }
                TokenKind::PlusPlus => {
                    self.advance()?;
                    expr = Expr::new(ExprKind::PostInc(Box::new(expr)), loc);
                }
                TokenKind::MinusMinus => {
                    self.advance()?;
                    expr = Expr::new(ExprKind::PostDec(Box::new(expr)), loc);
                }
                _ => break,
            }
        }

        Ok(expr)
    }

    /// 一次式をパース
    fn parse_primary_expr(&mut self) -> Result<Expr> {
        let loc = self.current.loc.clone();

        match &self.current.kind {
            TokenKind::Ident(id) => {
                let id = *id;
                self.advance()?;
                Ok(Expr::new(ExprKind::Ident(id), loc))
            }
            TokenKind::IntLit(n) => {
                let n = *n;
                self.advance()?;
                Ok(Expr::new(ExprKind::IntLit(n), loc))
            }
            TokenKind::UIntLit(n) => {
                let n = *n;
                self.advance()?;
                Ok(Expr::new(ExprKind::UIntLit(n), loc))
            }
            TokenKind::FloatLit(f) => {
                let f = *f;
                self.advance()?;
                Ok(Expr::new(ExprKind::FloatLit(f), loc))
            }
            TokenKind::CharLit(c) => {
                let c = *c;
                self.advance()?;
                Ok(Expr::new(ExprKind::CharLit(c), loc))
            }
            TokenKind::StringLit(s) => {
                let mut bytes = s.clone();
                self.advance()?;
                // 連続した文字列リテラルを結合
                while let TokenKind::StringLit(s2) = &self.current.kind {
                    bytes.extend_from_slice(s2);
                    self.advance()?;
                }
                Ok(Expr::new(ExprKind::StringLit(bytes), loc))
            }
            TokenKind::LParen => {
                self.advance()?;
                // GCC拡張: ステートメント式 ({ ... })
                if self.check(&TokenKind::LBrace) {
                    let stmt = self.parse_compound_stmt()?;
                    self.expect(&TokenKind::RParen)?;
                    Ok(Expr::new(ExprKind::StmtExpr(stmt), loc))
                } else {
                    let expr = self.parse_expr()?;
                    self.expect(&TokenKind::RParen)?;
                    Ok(expr)
                }
            }
            TokenKind::MacroBegin(info) if info.is_wrapped => {
                // wrapped マクロ(assert 等)を処理
                self.parse_wrapped_macro_expr()
            }
            TokenKind::MacroBegin(info) if info.preserve_call => {
                // preserve_call マクロを MacroCall ノードとして処理
                self.parse_macro_call_expr()
            }
            _ => Err(CompileError::Parse {
                loc,
                kind: ParseError::UnexpectedToken {
                    expected: "primary expression".to_string(),
                    found: self.current.kind.clone(),
                },
            }),
        }
    }

    /// wrapped マクロ(assert 等)を Assert 式としてパース
    ///
    /// MacroBegin(is_wrapped=true) から args を取得し、condition をパースして
    /// Assert 式を生成する。その後 MacroEnd までスキップ。
    ///
    /// `assert_` や `__ASSERT_` は末尾カンマ形式で、式の前に付ける修飾子として使用される。
    /// 空展開時はカンマがないため、後続の式があれば暗黙的にカンマ式を形成する。
    fn parse_wrapped_macro_expr(&mut self) -> Result<Expr> {
        let loc = self.current.loc.clone();

        // MacroBegin から情報を取得
        let (marker_id, macro_name, args) = match &self.current.kind {
            TokenKind::MacroBegin(info) if info.is_wrapped => {
                let args = match &info.kind {
                    MacroInvocationKind::Function { args } => args.clone(),
                    MacroInvocationKind::Object => {
                        let name = self.source.interner().get(info.macro_name).to_string();
                        return Err(CompileError::Parse {
                            loc,
                            kind: ParseError::AssertNotFunctionMacro { macro_name: name },
                        });
                    }
                };
                (info.marker_id, info.macro_name, args)
            }
            _ => unreachable!("parse_wrapped_macro_expr called without wrapped MacroBegin"),
        };

        // 引数数チェック(assert は 1 引数)
        if args.len() != 1 {
            let name = self.source.interner().get(macro_name).to_string();
            return Err(CompileError::Parse {
                loc,
                kind: ParseError::InvalidAssertArgs {
                    macro_name: name,
                    arg_count: args.len(),
                },
            });
        }

        // args[0] から condition をパース
        let condition = self.parse_expr_from_tokens(&args[0], &loc)?;

        // AssertKind を判定
        let macro_name_str = self.source.interner().get(macro_name);
        let kind = detect_assert_kind(macro_name_str).unwrap_or(AssertKind::Assert);

        // MacroBegin を消費して MacroEnd までスキップ
        // 注意: advance() は inner_next_token() を使うため MacroEnd をスキップしてしまう
        // そのため、ここでは skip_to_macro_end() を使って直接ソースから読み取る
        self.skip_to_macro_end(marker_id)?;

        let assert_expr = Expr::new(ExprKind::Assert {
            kind,
            condition: Box::new(condition),
        }, loc.clone());

        // 末尾カンマ形式(assert_, __ASSERT_)の場合、後続の式と暗黙的にカンマ式を形成
        // 次のトークンが式の開始(別の Assert 含む)であれば結合
        if self.is_expression_start() {
            // 後続の式をパース(再帰的に Assert もパースされる)
            let next_expr = self.parse_assignment_expr()?;
            Ok(Expr::new(
                ExprKind::Comma {
                    lhs: Box::new(assert_expr),
                    rhs: Box::new(next_expr),
                },
                loc,
            ))
        } else {
            Ok(assert_expr)
        }
    }

    /// preserve_call マクロを MacroCall 式としてパース
    ///
    /// MacroBegin(preserve_call=true) から元の引数を取得し、
    /// 展開結果をパースして MacroCall ノードを生成する。
    ///
    /// MacroCall は元のマクロ呼び出し情報と展開結果を両方保持することで:
    /// - 展開結果で型推論を実行
    /// - コード生成時にマクロ呼び出し形式で出力可能
    fn parse_macro_call_expr(&mut self) -> Result<Expr> {
        let loc = self.current.loc.clone();

        // MacroBegin から情報を取得
        let (marker_id, macro_name, raw_args, call_loc) = match &self.current.kind {
            TokenKind::MacroBegin(info) if info.preserve_call => {
                let args = match &info.kind {
                    MacroInvocationKind::Function { args } => args.clone(),
                    MacroInvocationKind::Object => Vec::new(),
                };
                (info.marker_id, info.macro_name, args, info.call_loc.clone())
            }
            _ => unreachable!("parse_macro_call_expr called without preserve_call MacroBegin"),
        };

        // MacroBegin を消費(advance は inner_next_token を使うため MacroEnd もスキップされる可能性がある)
        // そのため、ここでは source から直接読み取って展開トークンを収集
        let expanded_tokens = self.collect_tokens_until_macro_end(marker_id)?;

        // 展開トークンから式をパース
        let expanded = if expanded_tokens.is_empty() {
            // 空展開の場合は 0 を返す(void 式として扱う)
            Expr::new(ExprKind::IntLit(0), loc.clone())
        } else {
            crate::parser::parse_expression_from_tokens_ref(
                expanded_tokens,
                self.source.interner(),
                self.source.files(),
                &self.typedefs,
            )?
        };

        // 元の引数トークン列を式としてパース
        let parsed_args: Result<Vec<Expr>> = raw_args.iter()
            .map(|arg_tokens| {
                if arg_tokens.is_empty() {
                    // 空引数の場合
                    Ok(Expr::new(ExprKind::IntLit(0), loc.clone()))
                } else {
                    crate::parser::parse_expression_from_tokens_ref(
                        arg_tokens.clone(),
                        self.source.interner(),
                        self.source.files(),
                        &self.typedefs,
                    )
                }
            })
            .collect();
        let args = parsed_args?;

        // current を次のトークンで更新
        self.current = self.inner_next_token()?;

        Ok(Expr::new(ExprKind::MacroCall {
            name: macro_name,
            args,
            expanded: Box::new(expanded),
            call_loc,
        }, loc))
    }

    /// 指定した marker_id に対応する MacroEnd までのトークンを収集
    ///
    /// source から直接読み取り、MacroBegin/MacroEnd のネストを追跡する。
    fn collect_tokens_until_macro_end(&mut self, target_marker_id: TokenId) -> Result<Vec<Token>> {
        let mut tokens = Vec::new();
        let mut nested_depth = 0;

        loop {
            let token = self.source.next_token()?;

            match &token.kind {
                TokenKind::MacroBegin(_) => {
                    // ネストされたマクロ展開開始
                    nested_depth += 1;
                    tokens.push(token);
                }
                TokenKind::MacroEnd(info) => {
                    if nested_depth > 0 {
                        // ネストされたマクロ展開終了
                        nested_depth -= 1;
                        tokens.push(token);
                    } else if info.begin_marker_id == target_marker_id {
                        // 目標の MacroEnd を見つけた
                        return Ok(tokens);
                    } else {
                        // 異なる MacroEnd(これは起こらないはず)
                        tokens.push(token);
                    }
                }
                TokenKind::Eof => {
                    return Err(CompileError::Parse {
                        loc: token.loc,
                        kind: ParseError::UnexpectedToken {
                            expected: "MacroEnd".to_string(),
                            found: token.kind,
                        },
                    });
                }
                _ => {
                    tokens.push(token);
                }
            }
        }
    }

    /// 現在のトークンが式の開始かどうかを判定
    fn is_expression_start(&self) -> bool {
        match &self.current.kind {
            // 式の開始になり得るトークン
            TokenKind::Ident(_)
            | TokenKind::IntLit(_)
            | TokenKind::UIntLit(_)
            | TokenKind::FloatLit(_)
            | TokenKind::CharLit(_)
            | TokenKind::WideCharLit(_)
            | TokenKind::StringLit(_)
            | TokenKind::WideStringLit(_)
            | TokenKind::LParen
            | TokenKind::Star      // 間接参照
            | TokenKind::Amp       // アドレス取得
            | TokenKind::Plus      // 単項プラス
            | TokenKind::Minus     // 単項マイナス
            | TokenKind::Bang      // 論理否定
            | TokenKind::Tilde     // ビット反転
            | TokenKind::PlusPlus  // 前置インクリメント
            | TokenKind::MinusMinus // 前置デクリメント
            | TokenKind::KwSizeof
            | TokenKind::KwAlignof
            | TokenKind::KwAlignof2
            | TokenKind::KwAlignof3
            | TokenKind::MacroBegin(_) => true, // 別の Assert も含む
            _ => false,
        }
    }

    /// トークン列から式をパース
    ///
    /// args から取り出したトークン列を一時的なソースとして式をパースする。
    /// 入れ子の wrapped マクロがあればエラー。
    fn parse_expr_from_tokens(&self, tokens: &[Token], loc: &SourceLocation) -> Result<Expr> {
        // 入れ子チェック:tokens 内に wrapped MacroBegin があればエラー
        for token in tokens {
            if let TokenKind::MacroBegin(info) = &token.kind {
                if info.is_wrapped {
                    return Err(CompileError::Parse {
                        loc: loc.clone(),
                        kind: ParseError::NestedAssertNotSupported,
                    });
                }
            }
        }

        // トークン列から式をパース
        crate::parser::parse_expression_from_tokens_ref(
            tokens.to_vec(),
            self.source.interner(),
            self.source.files(),
            &self.typedefs,
        )
    }

    /// 指定した marker_id に対応する MacroEnd までスキップ
    ///
    /// inner_next_token は MacroEnd をスキップするため、
    /// ここでは source から直接読み取る。
    fn skip_to_macro_end(&mut self, target_marker_id: TokenId) -> Result<()> {
        // まず current をチェック(MacroBegin の直後なので通常は MacroEnd ではない)
        loop {
            // source から直接読み取る(inner_next_token は MacroEnd をスキップするため)
            let token = self.source.next_token()?;

            match &token.kind {
                TokenKind::MacroEnd(info) if info.begin_marker_id == target_marker_id => {
                    // 目標の MacroEnd を見つけた
                    // current を次のトークンで更新(inner_next_token を使って正常なフローに戻す)
                    self.current = self.inner_next_token()?;
                    return Ok(());
                }
                TokenKind::Eof => {
                    return Err(CompileError::Parse {
                        loc: token.loc.clone(),
                        kind: ParseError::MacroEndNotFound,
                    });
                }
                _ => {
                    // 他のトークンはスキップ(MacroBegin/MacroEnd 含む)
                    continue;
                }
            }
        }
    }

    // ==================== ユーティリティ ====================

    /// 内部トークン取得メソッド(マーカーを透過的に処理)
    ///
    /// `handle_macro_markers` が true の場合、MacroBegin/MacroEnd マーカーを
    /// 処理してスキップし、通常のトークンのみを返す。
    /// ただし、以下の MacroBegin はスキップせず返す:
    /// - `is_wrapped=true`: assert 等の特殊処理用
    /// - `preserve_call=true`: MacroCall ノード生成用
    /// 空展開でもこれらの MacroBegin を返し、適切な AST ノードを生成する。
    fn inner_next_token(&mut self) -> Result<Token> {
        loop {
            let token = self.source.next_token()?;

            if !self.handle_macro_markers {
                return Ok(token);
            }

            match &token.kind {
                TokenKind::MacroBegin(info) => {
                    if info.is_wrapped {
                        // wrapped マクロ(assert 等)は常に返す
                        // 空展開でも Assert ノードとして AST に残す
                        return Ok(token);
                    }
                    if info.preserve_call {
                        // preserve_call マクロは常に返す
                        // MacroCall ノードとして AST に残す
                        return Ok(token);
                    }
                    // 通常のマクロ展開開始:コンテキストにプッシュ
                    self.macro_ctx.push((**info).clone());
                    continue; // マーカーはスキップ
                }
                TokenKind::MacroEnd(_info) => {
                    // マクロ展開終了:コンテキストからポップ
                    self.macro_ctx.pop();
                    continue; // マーカーはスキップ
                }
                _ => return Ok(token),
            }
        }
    }

    fn advance(&mut self) -> Result<Token> {
        let next = self.inner_next_token()?;
        let old = std::mem::replace(&mut self.current, next);
        Ok(old)
    }

    /// 現在のマクロコンテキストから NodeInfo を作成
    pub fn make_node_info(&self, loc: SourceLocation) -> NodeInfo {
        match self.macro_ctx.build_macro_info(self.source.interner()) {
            Some(macro_info) => NodeInfo::with_macro_info(loc, macro_info),
            None => NodeInfo::new(loc),
        }
    }

    /// 現在マクロ展開中かどうか
    pub fn is_in_macro(&self) -> bool {
        self.macro_ctx.is_in_macro()
    }

    /// マクロ展開の深さ
    pub fn macro_depth(&self) -> usize {
        self.macro_ctx.depth()
    }

    fn expect(&mut self, kind: &TokenKind) -> Result<Token> {
        if self.check(kind) {
            self.advance()
        } else {
            Err(CompileError::Parse {
                loc: self.current.loc.clone(),
                kind: ParseError::UnexpectedToken {
                    expected: format!("{:?}", kind),
                    found: self.current.kind.clone(),
                },
            })
        }
    }

    fn expect_ident(&mut self) -> Result<InternedStr> {
        if let TokenKind::Ident(id) = self.current.kind {
            self.advance()?;
            Ok(id)
        } else {
            Err(CompileError::Parse {
                loc: self.current.loc.clone(),
                kind: ParseError::UnexpectedToken {
                    expected: "identifier".to_string(),
                    found: self.current.kind.clone(),
                },
            })
        }
    }

    fn check(&self, kind: &TokenKind) -> bool {
        std::mem::discriminant(&self.current.kind) == std::mem::discriminant(kind)
    }

    fn is_eof(&self) -> bool {
        matches!(self.current.kind, TokenKind::Eof)
    }

    fn current_ident(&self) -> Option<InternedStr> {
        if let TokenKind::Ident(id) = self.current.kind {
            Some(id)
        } else {
            None
        }
    }

    /// 引数に型名を取りうるビルトイン関数名かどうか
    fn is_type_arg_builtin(&self, name: InternedStr) -> bool {
        let s = self.source.interner().get(name);
        matches!(s, "offsetof" | "__builtin_offsetof"
                  | "__builtin_types_compatible_p"
                  | "__builtin_va_arg"
                  | "STRUCT_OFFSET")
    }

    /// ビルトイン関数の引数をパース(型名と式を自動判定)
    fn parse_builtin_args(&mut self) -> Result<Vec<BuiltinArg>> {
        let mut args = Vec::new();
        if !self.check(&TokenKind::RParen) {
            loop {
                if self.is_type_start() {
                    let type_name = self.parse_type_name()?;
                    args.push(BuiltinArg::TypeName(Box::new(type_name)));
                } else {
                    let expr = self.parse_assignment_expr()?;
                    args.push(BuiltinArg::Expr(Box::new(expr)));
                }
                if !self.check(&TokenKind::Comma) {
                    break;
                }
                self.advance()?;
            }
        }
        Ok(args)
    }

    fn is_type_start(&self) -> bool {
        match &self.current.kind {
            // 型指定子キーワード
            TokenKind::KwVoid
            | TokenKind::KwChar
            | TokenKind::KwShort
            | TokenKind::KwInt
            | TokenKind::KwLong
            | TokenKind::KwFloat
            | TokenKind::KwDouble
            | TokenKind::KwSigned
            | TokenKind::KwSigned2
            | TokenKind::KwUnsigned
            | TokenKind::KwBool
            | TokenKind::KwBool2
            | TokenKind::KwComplex
            | TokenKind::KwFloat16
            | TokenKind::KwFloat32
            | TokenKind::KwFloat64
            | TokenKind::KwFloat128
            | TokenKind::KwFloat32x
            | TokenKind::KwFloat64x
            | TokenKind::KwInt128 => true,
            // 型修飾子キーワード
            TokenKind::KwConst
            | TokenKind::KwConst2
            | TokenKind::KwConst3
            | TokenKind::KwVolatile
            | TokenKind::KwVolatile2
            | TokenKind::KwVolatile3
            | TokenKind::KwRestrict
            | TokenKind::KwRestrict2
            | TokenKind::KwRestrict3
            | TokenKind::KwAtomic => true,
            // 構造体・共用体・列挙
            TokenKind::KwStruct | TokenKind::KwUnion | TokenKind::KwEnum => true,
            // typeof
            TokenKind::KwTypeof | TokenKind::KwTypeof2 | TokenKind::KwTypeof3 => true,
            // typedef名 or 検出済みの generic 型パラメータ
            TokenKind::Ident(id) => {
                self.typedefs.contains(id) || self.detected_type_params.contains(id)
            }
            _ => false,
        }
    }

    fn is_declaration_start(&self) -> bool {
        match &self.current.kind {
            // ストレージクラス
            TokenKind::KwTypedef
            | TokenKind::KwExtern
            | TokenKind::KwStatic
            | TokenKind::KwAuto
            | TokenKind::KwRegister => true,
            // inline
            TokenKind::KwInline | TokenKind::KwInline2 | TokenKind::KwInline3 => true,
            // GCC拡張
            TokenKind::KwExtension => true,
            // thread-local
            TokenKind::KwThreadLocal | TokenKind::KwThread => true,
            _ => self.is_type_start(),
        }
    }

    /// __attribute__ / __asm__ があればスキップ(複数連続も対応)
    fn try_skip_attribute(&mut self) -> Result<()> {
        loop {
            match &self.current.kind {
                TokenKind::KwAttribute | TokenKind::KwAttribute2 => {
                    self.skip_attribute()?;
                }
                TokenKind::KwAsm | TokenKind::KwAsm2 | TokenKind::KwAsm3 => {
                    self.try_skip_asm_label()?;
                }
                _ => break,
            }
        }
        Ok(())
    }

    /// GCC拡張: __attribute__((...)) をスキップ
    fn skip_attribute(&mut self) -> Result<()> {
        self.advance()?; // __attribute__ / __attribute

        // 外側の ( を期待
        if !self.check(&TokenKind::LParen) {
            return Ok(()); // 引数なしの場合
        }
        self.advance()?;

        // 内側の ( を期待
        if !self.check(&TokenKind::LParen) {
            // 単一括弧の場合もある
            self.skip_balanced_parens()?;
            return Ok(());
        }
        self.advance()?;

        // 内側の括弧の中身をスキップ
        self.skip_balanced_parens()?;

        // 外側の ) を期待
        self.expect(&TokenKind::RParen)?;

        Ok(())
    }

    /// __asm__(label) があればスキップ
    fn try_skip_asm_label(&mut self) -> Result<()> {
        if matches!(
            self.current.kind,
            TokenKind::KwAsm | TokenKind::KwAsm2 | TokenKind::KwAsm3
        ) {
            self.advance()?; // asm / __asm / __asm__
            if self.check(&TokenKind::LParen) {
                self.advance()?; // (
                self.skip_balanced_parens()?; // 内容をスキップして ) を消費
            }
        }
        Ok(())
    }

    /// 括弧のバランスを取りながらスキップ
    fn skip_balanced_parens(&mut self) -> Result<()> {
        let mut depth = 1;
        while depth > 0 {
            match &self.current.kind {
                TokenKind::LParen => depth += 1,
                TokenKind::RParen => depth -= 1,
                TokenKind::Eof => {
                    return Err(CompileError::Parse {
                        loc: self.current.loc.clone(),
                        kind: ParseError::UnexpectedToken {
                            expected: ")".to_string(),
                            found: TokenKind::Eof,
                        },
                    });
                }
                _ => {}
            }
            if depth > 0 {
                self.advance()?;
            }
        }
        self.advance()?; // 最後の )
        Ok(())
    }
}

// ==================== ヘルパー関数 ====================

use crate::source::FileRegistry;
use crate::token_source::TokenSlice;

/// トークン列から式をパース
///
/// マクロ本体などのトークン列を式としてパースする際に使用。
///
/// # Arguments
/// * `tokens` - パースするトークン列
/// * `interner` - 文字列インターナー
/// * `files` - ファイルレジストリ
/// * `typedefs` - typedef名のセット(キャスト式の型名判定に使用)
pub fn parse_expression_from_tokens(
    tokens: Vec<Token>,
    interner: StringInterner,
    files: FileRegistry,
    typedefs: HashSet<InternedStr>,
) -> Result<Expr> {
    let mut source = TokenSlice::new(tokens, interner, files);
    let mut parser = Parser::from_source_with_typedefs(&mut source, typedefs)?;
    parser.parse_expr_only()
}

/// トークン列から式をパース(参照ベース版)
///
/// `parse_expression_from_tokens` の参照ベース版。
/// interner, files, typedefs をクローンせずに借用することで、
/// 高頻度の呼び出し時のオーバーヘッドを削減する。
///
/// # Arguments
/// * `tokens` - パースするトークン列
/// * `interner` - 文字列インターナーへの参照
/// * `files` - ファイルレジストリへの参照
/// * `typedefs` - typedef名のセットへの参照
pub fn parse_expression_from_tokens_ref(
    tokens: Vec<Token>,
    interner: &StringInterner,
    files: &FileRegistry,
    typedefs: &HashSet<InternedStr>,
) -> Result<Expr> {
    let mut source = TokenSliceRef::new(tokens, interner, files);
    let mut parser = Parser::from_source_with_typedefs(&mut source, typedefs.clone())?;
    parser.parse_expr_only()
}

/// トークン列を文としてパース(参照ベース版)
///
/// マクロ body のパースに使用。do-while の末尾セミコロンは省略可能。
///
/// # Arguments
/// * `tokens` - パースするトークン列
/// * `interner` - 文字列インターナーへの参照
/// * `files` - ファイルレジストリへの参照
/// * `typedefs` - typedef名のセットへの参照
pub fn parse_statement_from_tokens_ref(
    tokens: Vec<Token>,
    interner: &StringInterner,
    files: &FileRegistry,
    typedefs: &HashSet<InternedStr>,
) -> Result<Stmt> {
    let mut source = TokenSliceRef::new(tokens, interner, files);
    let mut parser = Parser::from_source_with_typedefs(&mut source, typedefs.clone())?;
    parser.parse_stmt_allow_missing_semi()
}

/// パース結果に付随する統計情報
#[derive(Debug, Clone, Default)]
pub struct ParseStats {
    /// 関数呼び出しの数
    pub function_call_count: usize,
    /// ポインタデリファレンスの数
    pub deref_count: usize,
}

impl ParseStats {
    /// unsafe 操作を含むか
    pub fn has_unsafe_ops(&self) -> bool {
        self.function_call_count > 0 || self.deref_count > 0
    }
}

/// トークン列から式をパース(統計情報付き・参照ベース版)
///
/// `parse_expression_from_tokens_ref` と同様だが、
/// パース統計(関数呼び出し数など)も返す。
///
/// # Arguments
/// * `tokens` - パースするトークン列
/// * `interner` - 文字列インターナーへの参照
/// * `files` - ファイルレジストリへの参照
/// * `typedefs` - typedef名のセットへの参照
///
/// # Returns
/// (パースされた式, 統計情報)
pub fn parse_expression_from_tokens_ref_with_stats(
    tokens: Vec<Token>,
    interner: &StringInterner,
    files: &FileRegistry,
    typedefs: &HashSet<InternedStr>,
) -> Result<(Expr, ParseStats)> {
    let mut source = TokenSliceRef::new(tokens, interner, files);
    let mut parser = Parser::from_source_with_typedefs(&mut source, typedefs.clone())?;
    let expr = parser.parse_expr_only()?;
    let stats = ParseStats {
        function_call_count: parser.function_call_count,
        deref_count: parser.deref_count,
    };
    Ok((expr, stats))
}

/// トークン列から式をパース(generic_params 付き)
///
/// マクロ本体のパースに使用。マクロの仮引数名を generic_params として渡し、
/// キャスト式での型パラメータ使用を自動検出する。
///
/// # Returns
/// (パースされた式, 統計情報, 検出された型パラメータ)
pub fn parse_expression_from_tokens_ref_with_generic_params(
    tokens: Vec<Token>,
    interner: &StringInterner,
    files: &FileRegistry,
    typedefs: &HashSet<InternedStr>,
    generic_params: HashMap<InternedStr, usize>,
) -> Result<(Expr, ParseStats, HashSet<InternedStr>)> {
    let mut source = TokenSliceRef::new(tokens, interner, files);
    let mut parser = Parser::from_source_with_typedefs(&mut source, typedefs.clone())?;
    parser.generic_params = generic_params;
    let expr = parser.parse_expr_only()?;
    let stats = ParseStats {
        function_call_count: parser.function_call_count,
        deref_count: parser.deref_count,
    };
    let detected = parser.detected_type_params;
    Ok((expr, stats, detected))
}

/// トークン列を文としてパース(統計情報付き・参照ベース版)
///
/// `parse_statement_from_tokens_ref` と同様だが、
/// パース統計(関数呼び出し数など)も返す。
/// do-while の末尾セミコロンは省略可能。
///
/// # Arguments
/// * `tokens` - パースするトークン列
/// * `interner` - 文字列インターナーへの参照
/// * `files` - ファイルレジストリへの参照
/// * `typedefs` - typedef名のセットへの参照
///
/// # Returns
/// (パースされた文, 統計情報)
pub fn parse_statement_from_tokens_ref_with_stats(
    tokens: Vec<Token>,
    interner: &StringInterner,
    files: &FileRegistry,
    typedefs: &HashSet<InternedStr>,
) -> Result<(Stmt, ParseStats)> {
    let mut source = TokenSliceRef::new(tokens, interner, files);
    let mut parser = Parser::from_source_with_typedefs(&mut source, typedefs.clone())?;
    let stmt = parser.parse_stmt_allow_missing_semi()?;
    let stats = ParseStats {
        function_call_count: parser.function_call_count,
        deref_count: parser.deref_count,
    };
    Ok((stmt, stats))
}

/// トークン列を文としてパース(generic_params 付き)
///
/// マクロ本体のパースに使用。マクロの仮引数名を generic_params として渡し、
/// キャスト式での型パラメータ使用を自動検出する。
///
/// # Returns
/// (パースされた文, 統計情報, 検出された型パラメータ)
pub fn parse_statement_from_tokens_ref_with_generic_params(
    tokens: Vec<Token>,
    interner: &StringInterner,
    files: &FileRegistry,
    typedefs: &HashSet<InternedStr>,
    generic_params: HashMap<InternedStr, usize>,
) -> Result<(Stmt, ParseStats, HashSet<InternedStr>)> {
    let mut source = TokenSliceRef::new(tokens, interner, files);
    let mut parser = Parser::from_source_with_typedefs(&mut source, typedefs.clone())?;
    parser.generic_params = generic_params;
    let stmt = parser.parse_stmt_allow_missing_semi()?;
    let stats = ParseStats {
        function_call_count: parser.function_call_count,
        deref_count: parser.deref_count,
    };
    let detected = parser.detected_type_params;
    Ok((stmt, stats, detected))
}

/// トークン列を複数のブロック項目としてパース
///
/// セミコロン区切りの複数文を含むマクロ本体のパースに使用。
/// `{ }` なしの BlockItem リストをパースし、EOF まで読む。
///
/// # Returns
/// (パースされたブロック項目リスト, 統計情報)
pub fn parse_block_items_from_tokens_ref_with_stats(
    tokens: Vec<Token>,
    interner: &StringInterner,
    files: &FileRegistry,
    typedefs: &HashSet<InternedStr>,
) -> Result<(Vec<BlockItem>, ParseStats)> {
    let mut source = TokenSliceRef::new(tokens, interner, files);
    let mut parser = Parser::from_source_with_typedefs(&mut source, typedefs.clone())?;
    parser.allow_missing_semi = true;
    let mut items = Vec::new();
    while !parser.check(&TokenKind::Eof) {
        items.push(parser.parse_block_item()?);
    }
    let stats = ParseStats {
        function_call_count: parser.function_call_count,
        deref_count: parser.deref_count,
    };
    Ok((items, stats))
}

/// トークン列を複数のブロック項目としてパース(generic_params 付き)
///
/// # Returns
/// (パースされたブロック項目リスト, 統計情報, 検出された型パラメータ)
pub fn parse_block_items_from_tokens_ref_with_generic_params(
    tokens: Vec<Token>,
    interner: &StringInterner,
    files: &FileRegistry,
    typedefs: &HashSet<InternedStr>,
    generic_params: HashMap<InternedStr, usize>,
) -> Result<(Vec<BlockItem>, ParseStats, HashSet<InternedStr>)> {
    let mut source = TokenSliceRef::new(tokens, interner, files);
    let mut parser = Parser::from_source_with_typedefs(&mut source, typedefs.clone())?;
    parser.allow_missing_semi = true;
    parser.generic_params = generic_params;
    let mut items = Vec::new();
    while !parser.check(&TokenKind::Eof) {
        items.push(parser.parse_block_item()?);
    }
    let stats = ParseStats {
        function_call_count: parser.function_call_count,
        deref_count: parser.deref_count,
    };
    let detected = parser.detected_type_params;
    Ok((items, stats, detected))
}

/// 型文字列から TypeName をパース
///
/// apidoc 等の型文字列(例: "SV *", "const char *")をパースして
/// TypeName AST を返す。ReadOnlyLexer を使用するため、
/// 型文字列内の識別子は既に intern 済みである必要がある。
///
/// # Arguments
/// * `type_str` - パースする型文字列
/// * `interner` - 文字列インターナーへの参照(読み取り専用)
/// * `files` - ファイルレジストリへの参照
/// * `typedefs` - typedef名のセットへの参照
///
/// # Returns
/// パースされた TypeName AST、または識別子が未知の場合はエラー
pub fn parse_type_from_string(
    type_str: &str,
    interner: &StringInterner,
    files: &FileRegistry,
    typedefs: &HashSet<InternedStr>,
) -> Result<TypeName> {
    // 型文字列用のダミー FileId(エラー時の位置情報は限定的)
    let file_id = FileId::default();

    // ReadOnlyLexer でトークン化(新規 intern なし)
    let mut lexer = Lexer::<LookupOnly>::new_readonly(type_str.as_bytes(), file_id, interner);

    let mut tokens = Vec::new();
    loop {
        let token = lexer.next_token()?;
        if matches!(token.kind, TokenKind::Eof) {
            break;
        }
        tokens.push(token);
    }

    // パース
    let mut source = TokenSliceRef::new(tokens, interner, files);
    let mut parser = Parser::from_source_with_typedefs(&mut source, typedefs.clone())?;
    parser.parse_type_name()
}

/// トークン列を struct メンバー宣言の連続としてパースする。
///
/// `_XPVCV_COMMON` のような共通フィールド宣言マクロの本体を解析する用途。
/// 入力末尾に `;` が無い場合は自動補完する(マクロ本体は典型的に最終
/// 宣言の後に `;` を持たない — 展開先で `;` が補われる)。
pub fn parse_struct_members_from_tokens_ref(
    mut tokens: Vec<Token>,
    interner: &StringInterner,
    files: &FileRegistry,
    typedefs: &HashSet<InternedStr>,
) -> Result<Vec<StructMember>> {
    // 末尾に `;` が無ければ補う(最後の意味のあるトークンを見て判定)
    let needs_trailing_semi = tokens
        .iter()
        .rev()
        .find(|t| !matches!(t.kind, TokenKind::Eof))
        .is_some_and(|t| !matches!(t.kind, TokenKind::Semi));
    if needs_trailing_semi {
        // EOF を取り除いて `;` を足し直す
        let eof = tokens.iter().position(|t| matches!(t.kind, TokenKind::Eof))
            .map(|i| tokens.remove(i));
        let semi_loc = tokens.last().map(|t| t.loc.clone()).unwrap_or_default();
        tokens.push(Token::new(TokenKind::Semi, semi_loc));
        if let Some(eof) = eof {
            tokens.push(eof);
        }
    }
    let mut source = TokenSliceRef::new(tokens, interner, files);
    let mut parser = Parser::from_source_with_typedefs(&mut source, typedefs.clone())?;
    let mut members = Vec::new();
    while !parser.check(&TokenKind::Eof) {
        members.push(parser.parse_struct_member()?);
    }
    Ok(members)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::preprocessor::PPConfig;
    use std::io::Write;
    use tempfile::NamedTempFile;

    fn parse_str(code: &str) -> Result<TranslationUnit> {
        let mut file = NamedTempFile::new().unwrap();
        file.write_all(code.as_bytes()).unwrap();

        let mut pp = Preprocessor::new(PPConfig::default());
        pp.add_source_file(file.path())?;

        let mut parser = Parser::new(&mut pp)?;
        parser.parse()
    }

    #[test]
    fn test_simple_function() {
        let tu = parse_str("int main(void) { return 0; }").unwrap();
        assert_eq!(tu.decls.len(), 1);
        assert!(matches!(tu.decls[0], ExternalDecl::FunctionDef(_)));
    }

    #[test]
    fn test_variable_declaration() {
        let tu = parse_str("int x;").unwrap();
        assert_eq!(tu.decls.len(), 1);
        assert!(matches!(tu.decls[0], ExternalDecl::Declaration(_)));
    }

    #[test]
    fn test_struct_declaration() {
        let tu = parse_str("struct Point { int x; int y; };").unwrap();
        assert_eq!(tu.decls.len(), 1);
    }

    #[test]
    fn test_typedef() {
        let tu = parse_str("typedef int INT; INT x;").unwrap();
        assert_eq!(tu.decls.len(), 2);
    }

    #[test]
    fn test_expression() {
        let tu = parse_str("int x = 1 + 2 * 3;").unwrap();
        assert_eq!(tu.decls.len(), 1);
    }
}