libperl-macrogen 0.1.4

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
//! 意味解析モジュール
//!
//! スコープ管理と型推論を行う。

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

use crate::apidoc::ApidocDict;
use crate::ast::*;
use crate::fields_dict::FieldsDict;
use crate::inline_fn::InlineFnDict;
use crate::intern::{InternedStr, StringInterner};
use crate::parser::parse_type_from_string;
use crate::rust_decl::RustDeclDict;
use crate::source::{FileRegistry, SourceLocation};
use crate::type_env::{TypeEnv, TypeConstraint as TypeEnvConstraint};
use crate::type_repr::{
    CTypeSource, CTypeSpecs, CDerivedType, InferredType,
    RustTypeRepr, RustTypeSource, TypeRepr,
};
use crate::unified_type::{IntSize, UnifiedType};

/// `Member` / `PtrMember` / `Deref` / `Cast` の連鎖を遡って leftmost の Ident
/// を探す。Ident が macro params に含まれていれば `Some((name, expr_id))` を
/// 返す。Call や Binary 等で連鎖が中断する場合は `None` を返す(誤推論を避ける)。
///
/// GCC StmtExpr による MUTABLE_PTR の展開
/// `({ void *p_ = (expr); p_; })` も透過する(perl5 の MUTABLE_PTR は
/// この形に展開されることがある)。
fn leftmost_param_ident(
    expr: &Expr,
    params: &HashSet<InternedStr>,
) -> Option<(InternedStr, ExprId)> {
    let mut cur = expr;
    loop {
        match &cur.kind {
            ExprKind::Member { expr: base, .. }
            | ExprKind::PtrMember { expr: base, .. }
            | ExprKind::Deref(base)
            | ExprKind::Cast { expr: base, .. } => cur = base,
            ExprKind::StmtExpr(compound) => {
                if let Some(inner) = mutable_ptr_inner_expr(compound) {
                    cur = inner;
                } else {
                    return None;
                }
            }
            ExprKind::Ident(name) if params.contains(name) => {
                return Some((*name, cur.id));
            }
            _ => return None,
        }
    }
}

/// `({ void *p_ = (expr); p_; })` という MUTABLE_PTR の GCC StmtExpr 展開を
/// 検出し、内側の expr への参照を返す。`detect_mutable_ptr_pattern`
/// (`src/rust_codegen.rs`) と同等の判定を semantic 側で行う。
fn mutable_ptr_inner_expr(compound: &CompoundStmt) -> Option<&Expr> {
    if compound.items.len() != 2 {
        return None;
    }
    let decl = match &compound.items[0] {
        BlockItem::Decl(d) => d,
        _ => return None,
    };
    if decl.declarators.len() != 1 {
        return None;
    }
    let init_decl = &decl.declarators[0];
    let declared_name = init_decl.declarator.name?;
    let init_expr = match init_decl.init.as_ref()? {
        Initializer::Expr(e) => e.as_ref(),
        _ => return None,
    };
    let last_expr = match &compound.items[1] {
        BlockItem::Stmt(Stmt::Expr(Some(e), _)) => e,
        _ => return None,
    };
    if let ExprKind::Ident(name) = &last_expr.kind {
        if *name == declared_name {
            return Some(init_expr);
        }
    }
    None
}

/// `TypeRepr` が「無名 struct/union 型のフィールドそのもの」かを判定する。
///
/// 例: C で `union { ... } op_pmstashstartu;` のように書かれた anonymous
/// union を fields_dict に格納すると、`CTypeSpecs::Struct { name: None,
/// is_union: true }` で derived = [] となる。この場合
/// `to_display_string` は `"union"` を返してしまい、後続 member access
/// の base 型として使い物にならない。bindings.rs から bindgen 生成の
/// named 型(例: `pmop__bindgen_ty_2`)に置き換える必要がある。
fn is_anonymous_struct_or_union_field(t: &TypeRepr) -> bool {
    if let TypeRepr::CType { specs, derived, .. } = t {
        if !derived.is_empty() {
            return false;
        }
        return matches!(
            specs,
            crate::type_repr::CTypeSpecs::Struct { name: None, .. }
        );
    }
    false
}

/// `TypeRepr` から struct/union/typedef 名を文字列として取得する。
///
/// `TypeRepr::type_name()` は `InternedStr` を返すが、`RustTypeRepr` 側は
/// String ベースで保持しているため常に `None` を返す。bindings.rs 由来の
/// `RustType::Named("pmop__bindgen_ty_2")` のような名前も拾うために、
/// 個別に String として取り出すヘルパーを提供する。
fn extract_struct_name_str(t: &TypeRepr, interner: &crate::intern::StringInterner) -> Option<String> {
    use crate::type_repr::{CTypeSpecs, RustTypeRepr};
    match t {
        TypeRepr::CType { specs, derived, .. } if derived.is_empty() => match specs {
            CTypeSpecs::TypedefName(n) => Some(interner.get(*n).to_string()),
            CTypeSpecs::Struct { name: Some(n), .. } => Some(interner.get(*n).to_string()),
            _ => None,
        },
        TypeRepr::RustType { repr, .. } => match repr {
            RustTypeRepr::Named(s) => Some(s.clone()),
            _ => None,
        },
        TypeRepr::Inferred(inferred) => {
            inferred.resolved_type().and_then(|t| extract_struct_name_str(t, interner))
        }
        _ => None,
    }
}

/// 既存の `TypeRepr` の最も外側に Pointer derived を一段被せた新しい
/// `TypeRepr` を返す。flexible array member (`T[1]`) を `T*` として扱う際に使う。
/// 元が `RustType` や `Inferred` の場合はサポート外として `None` 相当ではなく
/// 安全側で元をそのまま返す(呼び出し側は CType 由来のみ渡す想定)。
fn wrap_with_outer_pointer(ty: TypeRepr, is_const: bool) -> TypeRepr {
    use crate::type_repr::CDerivedType;
    match ty {
        TypeRepr::CType { specs, mut derived, source } => {
            derived.push(CDerivedType::Pointer { is_const, is_volatile: false, is_restrict: false });
            TypeRepr::CType { specs, derived, source }
        }
        other => other,
    }
}

/// 型変数 ID (制約ベース型推論用)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct TypeVar(usize);

/// 型制約 (マクロ引数の型推論用)
#[derive(Debug, Clone)]
pub enum TypeConstraint {
    /// 関数呼び出しの引数として使用
    FunctionArg {
        var: TypeVar,
        func_name: InternedStr,
        arg_index: usize,
    },
    /// フィールドアクセスの基底として使用
    HasField {
        var: TypeVar,
        field: InternedStr,
    },
}

/// 解決済み型
#[derive(Debug, Clone, PartialEq)]
pub enum Type {
    /// void
    Void,
    /// char
    Char,
    /// signed char
    SignedChar,
    /// unsigned char
    UnsignedChar,
    /// short
    Short,
    /// unsigned short
    UnsignedShort,
    /// int
    Int,
    /// unsigned int
    UnsignedInt,
    /// long
    Long,
    /// unsigned long
    UnsignedLong,
    /// long long
    LongLong,
    /// unsigned long long
    UnsignedLongLong,
    /// float
    Float,
    /// double
    Double,
    /// long double
    LongDouble,
    /// _Bool
    Bool,
    /// __int128
    Int128,
    /// unsigned __int128
    UnsignedInt128,
    /// ポインタ型
    Pointer(Box<Type>, TypeQualifiers),
    /// 配列型
    Array(Box<Type>, Option<usize>),
    /// 関数型
    Function {
        return_type: Box<Type>,
        params: Vec<Type>,
        variadic: bool,
    },
    /// 構造体型
    Struct {
        name: Option<InternedStr>,
        /// メンバー (名前, 型)
        members: Option<Vec<(InternedStr, Type)>>,
    },
    /// 共用体型
    Union {
        name: Option<InternedStr>,
        members: Option<Vec<(InternedStr, Type)>>,
    },
    /// 列挙型
    Enum {
        name: Option<InternedStr>,
    },
    /// typedef名(未解決)
    TypedefName(InternedStr),
    /// 不明な型(エラー時)
    Unknown,
}

impl Type {
    /// 型を人間が読める形式で表示
    pub fn display(&self, interner: &StringInterner) -> String {
        match self {
            Type::Void => "void".to_string(),
            Type::Char => "char".to_string(),
            Type::SignedChar => "signed char".to_string(),
            Type::UnsignedChar => "unsigned char".to_string(),
            Type::Short => "short".to_string(),
            Type::UnsignedShort => "unsigned short".to_string(),
            Type::Int => "int".to_string(),
            Type::UnsignedInt => "unsigned int".to_string(),
            Type::Long => "long".to_string(),
            Type::UnsignedLong => "unsigned long".to_string(),
            Type::LongLong => "long long".to_string(),
            Type::UnsignedLongLong => "unsigned long long".to_string(),
            Type::Float => "float".to_string(),
            Type::Double => "double".to_string(),
            Type::LongDouble => "long double".to_string(),
            Type::Bool => "_Bool".to_string(),
            Type::Int128 => "__int128".to_string(),
            Type::UnsignedInt128 => "unsigned __int128".to_string(),
            Type::Pointer(inner, quals) => {
                let mut s = inner.display(interner);
                s.push('*');
                if quals.is_const {
                    s.push_str(" const");
                }
                if quals.is_volatile {
                    s.push_str(" volatile");
                }
                if quals.is_restrict {
                    s.push_str(" restrict");
                }
                s
            }
            Type::Array(inner, size) => {
                let inner_s = inner.display(interner);
                match size {
                    Some(n) => format!("{}[{}]", inner_s, n),
                    None => format!("{}[]", inner_s),
                }
            }
            Type::Function { return_type, params, variadic } => {
                let params_s: Vec<_> = params.iter()
                    .map(|p| p.display(interner))
                    .collect();
                let mut s = format!("(function {} ({}))", return_type.display(interner), params_s.join(", "));
                if *variadic {
                    s = s.replace("))", ", ...))");
                }
                s
            }
            Type::Struct { name, .. } => {
                match name {
                    Some(n) => format!("struct {}", interner.get(*n)),
                    None => "struct <anonymous>".to_string(),
                }
            }
            Type::Union { name, .. } => {
                match name {
                    Some(n) => format!("union {}", interner.get(*n)),
                    None => "union <anonymous>".to_string(),
                }
            }
            Type::Enum { name } => {
                match name {
                    Some(n) => format!("enum {}", interner.get(*n)),
                    None => "enum <anonymous>".to_string(),
                }
            }
            Type::TypedefName(name) => interner.get(*name).to_string(),
            Type::Unknown => "<unknown>".to_string(),
        }
    }

    /// 整数型かどうか
    pub fn is_integer(&self) -> bool {
        matches!(
            self,
            Type::Char
                | Type::SignedChar
                | Type::UnsignedChar
                | Type::Short
                | Type::UnsignedShort
                | Type::Int
                | Type::UnsignedInt
                | Type::Long
                | Type::UnsignedLong
                | Type::LongLong
                | Type::UnsignedLongLong
                | Type::Bool
                | Type::Int128
                | Type::UnsignedInt128
                | Type::Enum { .. }
        )
    }

    /// 浮動小数点型かどうか
    pub fn is_floating(&self) -> bool {
        matches!(self, Type::Float | Type::Double | Type::LongDouble)
    }

    /// 算術型かどうか
    pub fn is_arithmetic(&self) -> bool {
        self.is_integer() || self.is_floating()
    }

    /// ポインタ型かどうか
    pub fn is_pointer(&self) -> bool {
        matches!(self, Type::Pointer(_, _))
    }

    /// UnifiedType に変換
    pub fn to_unified(&self, interner: &StringInterner) -> UnifiedType {
        match self {
            Type::Void => UnifiedType::Void,
            Type::Bool => UnifiedType::Bool,

            Type::Char => UnifiedType::Char { signed: None },
            Type::SignedChar => UnifiedType::Char { signed: Some(true) },
            Type::UnsignedChar => UnifiedType::Char { signed: Some(false) },

            Type::Short => UnifiedType::Int { signed: true, size: IntSize::Short },
            Type::UnsignedShort => UnifiedType::Int { signed: false, size: IntSize::Short },
            Type::Int => UnifiedType::Int { signed: true, size: IntSize::Int },
            Type::UnsignedInt => UnifiedType::Int { signed: false, size: IntSize::Int },
            Type::Long => UnifiedType::Int { signed: true, size: IntSize::Long },
            Type::UnsignedLong => UnifiedType::Int { signed: false, size: IntSize::Long },
            Type::LongLong => UnifiedType::Int { signed: true, size: IntSize::LongLong },
            Type::UnsignedLongLong => UnifiedType::Int { signed: false, size: IntSize::LongLong },
            Type::Int128 => UnifiedType::Int { signed: true, size: IntSize::Int128 },
            Type::UnsignedInt128 => UnifiedType::Int { signed: false, size: IntSize::Int128 },

            Type::Float => UnifiedType::Float,
            Type::Double => UnifiedType::Double,
            Type::LongDouble => UnifiedType::LongDouble,

            Type::Pointer(inner, quals) => UnifiedType::Pointer {
                inner: Box::new(inner.to_unified(interner)),
                is_const: quals.is_const,
            },

            Type::Array(inner, size) => UnifiedType::Array {
                inner: Box::new(inner.to_unified(interner)),
                size: *size,
            },

            Type::Struct { name: Some(n), .. } => {
                UnifiedType::Named(interner.get(*n).to_string())
            }
            Type::Struct { name: None, .. } => UnifiedType::Unknown,

            Type::Union { name: Some(n), .. } => {
                UnifiedType::Named(interner.get(*n).to_string())
            }
            Type::Union { name: None, .. } => UnifiedType::Unknown,

            Type::Enum { name: Some(n) } => {
                UnifiedType::Named(interner.get(*n).to_string())
            }
            Type::Enum { name: None } => UnifiedType::Int { signed: true, size: IntSize::Int },

            Type::TypedefName(name) => {
                UnifiedType::Named(interner.get(*name).to_string())
            }

            Type::Function { .. } => UnifiedType::Unknown, // 関数型は未サポート

            Type::Unknown => UnifiedType::Unknown,
        }
    }
}

/// シンボル情報
#[derive(Debug, Clone)]
pub struct Symbol {
    /// 名前
    pub name: InternedStr,
    ///    pub ty: Type,
    /// 定義位置
    pub loc: SourceLocation,
    /// シンボルの種類
    pub kind: SymbolKind,
}

/// シンボルの種類
#[derive(Debug, Clone, PartialEq)]
pub enum SymbolKind {
    /// 変数
    Variable,
    /// 関数
    Function,
    /// typedef
    Typedef,
    /// 列挙定数
    EnumConstant(i64),
}

/// スコープ
#[derive(Debug)]
pub struct Scope {
    /// シンボルテーブル (名前 -> シンボル)
    symbols: HashMap<InternedStr, Symbol>,
    /// 親スコープID (グローバルスコープはNone)
    parent: Option<ScopeId>,
}

impl Scope {
    fn new(parent: Option<ScopeId>) -> Self {
        Self {
            symbols: HashMap::new(),
            parent,
        }
    }
}

/// スコープID
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ScopeId(usize);

/// 意味解析器
pub struct SemanticAnalyzer<'a> {
    /// 文字列インターナー
    interner: &'a StringInterner,
    /// スコープスタック
    scopes: Vec<Scope>,
    /// 現在のスコープID
    current_scope: ScopeId,
    /// 構造体定義 (名前 -> メンバーリスト)
    struct_defs: HashMap<InternedStr, Vec<(InternedStr, Type)>>,
    /// 共用体定義
    union_defs: HashMap<InternedStr, Vec<(InternedStr, Type)>>,
    /// typedef定義 (名前 -> 型)
    typedef_defs: HashMap<InternedStr, Type>,
    /// Apidoc辞書(関数/マクロのシグネチャ情報)
    apidoc: Option<&'a ApidocDict>,
    /// フィールド辞書(構造体フィールドの型情報)
    fields_dict: Option<&'a FieldsDict>,
    /// RustDeclDict への参照 (bindings.rs の関数型情報)
    rust_decl_dict: Option<&'a RustDeclDict>,
    /// InlineFnDict への参照 (inline関数のAST情報)
    inline_fn_dict: Option<&'a InlineFnDict>,
    /// 型変数マップ (引数名 -> TypeVar)
    type_vars: HashMap<InternedStr, TypeVar>,
    /// 次の型変数ID
    next_type_var: usize,
    /// 収集された制約
    constraints: Vec<TypeConstraint>,
    /// 制約収集モードか
    constraint_mode: bool,
    /// マクロパラメータ名の集合(型制約収集用)
    macro_params: HashSet<InternedStr>,
    /// 確定済みマクロの戻り値型(マクロ名 -> 戻り値型)への参照
    macro_return_types: Option<&'a HashMap<String, String>>,
    /// 確定済みマクロのパラメータ型(マクロ名 -> [(パラメータ名, 型)])への参照
    /// ネストしたマクロ呼び出しからの型伝播に使用
    macro_param_types: Option<&'a HashMap<String, Vec<(String, String)>>>,
    /// ファイルレジストリ(型文字列パース用)
    files: Option<&'a FileRegistry>,
    /// typedef 名の集合(型文字列パース用)
    parser_typedefs: Option<&'a HashSet<InternedStr>>,
}

impl<'a> SemanticAnalyzer<'a> {
    /// 新しい意味解析器を作成
    pub fn new(
        interner: &'a StringInterner,
        apidoc: Option<&'a ApidocDict>,
        fields_dict: Option<&'a FieldsDict>,
    ) -> Self {
        Self::with_rust_decl_dict(interner, apidoc, fields_dict, None, None)
    }

    /// RustDeclDict と InlineFnDict を指定して意味解析器を作成
    pub fn with_rust_decl_dict(
        interner: &'a StringInterner,
        apidoc: Option<&'a ApidocDict>,
        fields_dict: Option<&'a FieldsDict>,
        rust_decl_dict: Option<&'a RustDeclDict>,
        inline_fn_dict: Option<&'a InlineFnDict>,
    ) -> Self {
        let global_scope = Scope::new(None);
        Self {
            interner,
            scopes: vec![global_scope],
            current_scope: ScopeId(0),
            struct_defs: HashMap::new(),
            union_defs: HashMap::new(),
            typedef_defs: HashMap::new(),
            apidoc,
            fields_dict,
            rust_decl_dict,
            inline_fn_dict,
            type_vars: HashMap::new(),
            next_type_var: 0,
            constraints: Vec::new(),
            constraint_mode: false,
            macro_params: HashSet::new(),
            macro_return_types: None,
            macro_param_types: None,
            files: None,
            parser_typedefs: None,
        }
    }

    /// 確定済みマクロの戻り値型キャッシュへの参照を設定
    pub fn set_macro_return_types(&mut self, cache: &'a HashMap<String, String>) {
        self.macro_return_types = Some(cache);
    }

    /// 確定済みマクロのパラメータ型キャッシュへの参照を設定
    pub fn set_macro_param_types(&mut self, cache: &'a HashMap<String, Vec<(String, String)>>) {
        self.macro_param_types = Some(cache);
    }

    /// マクロの戻り値型を取得
    pub fn get_macro_return_type(&self, macro_name: &str) -> Option<&str> {
        self.macro_return_types
            .and_then(|cache| cache.get(macro_name))
            .map(|s| s.as_str())
    }

    /// マクロのパラメータ型を取得
    pub fn get_macro_param_types(&self, macro_name: &str) -> Option<&Vec<(String, String)>> {
        self.macro_param_types
            .and_then(|cache| cache.get(macro_name))
    }

    /// 新しいスコープを開始
    pub fn push_scope(&mut self) {
        let new_scope = Scope::new(Some(self.current_scope));
        let new_id = ScopeId(self.scopes.len());
        self.scopes.push(new_scope);
        self.current_scope = new_id;
    }

    /// 現在のスコープを終了
    pub fn pop_scope(&mut self) {
        if let Some(parent) = self.scopes[self.current_scope.0].parent {
            self.current_scope = parent;
        }
    }

    /// シンボルを現在のスコープに追加
    pub fn define_symbol(&mut self, symbol: Symbol) {
        let scope = &mut self.scopes[self.current_scope.0];
        scope.symbols.insert(symbol.name, symbol);
    }

    /// シンボルを検索(現在のスコープから親スコープへ)
    pub fn lookup_symbol(&self, name: InternedStr) -> Option<&Symbol> {
        let mut scope_id = Some(self.current_scope);
        while let Some(id) = scope_id {
            let scope = &self.scopes[id.0];
            if let Some(sym) = scope.symbols.get(&name) {
                return Some(sym);
            }
            scope_id = scope.parent;
        }
        None
    }

    // ========================================
    // 制約ベース型推論 (マクロ引数用)
    // ========================================

    /// 制約収集モードを開始し、パラメータを型変数として登録
    pub fn begin_param_inference(&mut self, params: &[InternedStr]) {
        self.constraint_mode = true;
        self.type_vars.clear();
        self.constraints.clear();
        self.next_type_var = 0;

        for &param in params {
            let var = TypeVar(self.next_type_var);
            self.next_type_var += 1;
            self.type_vars.insert(param, var);
        }
    }

    /// 制約を解いて引数型を取得し、制約収集モードを終了
    pub fn end_param_inference(&mut self) -> HashMap<InternedStr, Type> {
        self.constraint_mode = false;
        let solutions = self.solve_constraints();

        // 型変数名から Type へのマップを構築
        let mut result = HashMap::new();
        for (&name, &var) in &self.type_vars {
            if let Some(ty) = solutions.get(&var) {
                result.insert(name, ty.clone());
            }
        }

        // クリーンアップ
        self.type_vars.clear();
        self.constraints.clear();
        self.next_type_var = 0;

        result
    }

    /// 制約を解く
    fn solve_constraints(&self) -> HashMap<TypeVar, Type> {
        let mut solutions = HashMap::new();

        for constraint in &self.constraints {
            match constraint {
                TypeConstraint::FunctionArg { var, func_name, arg_index } => {
                    if solutions.contains_key(var) {
                        continue;
                    }

                    // RustDeclDict (bindings.rs) から関数シグネチャを取得
                    if let Some(ty) = self.lookup_rust_decl_param_type(*func_name, *arg_index) {
                        solutions.insert(*var, ty);
                    }
                }
                TypeConstraint::HasField { var, field } => {
                    if solutions.contains_key(var) {
                        continue;
                    }

                    // FieldsDict からフィールドを持つ構造体を特定
                    if let Some(fields_dict) = self.fields_dict {
                        if let Some(struct_name) = fields_dict.lookup_unique(*field) {
                            // struct_name は既に InternedStr なので直接使用
                            solutions.insert(
                                *var,
                                Type::Pointer(
                                    Box::new(Type::TypedefName(struct_name)),
                                    TypeQualifiers::default(),
                                ),
                            );
                        }
                    }
                }
            }
        }

        solutions
    }

    /// RustDeclDict から関数の引数型を取得
    fn lookup_rust_decl_param_type(&self, func_name: InternedStr, arg_index: usize) -> Option<Type> {
        let rust_decl_dict = self.rust_decl_dict?;
        let func_name_str = self.interner.get(func_name);
        let rust_fn = rust_decl_dict.fns.get(func_name_str)?;
        let param = rust_fn.params.get(arg_index)?;
        // Rust型文字列 (e.g., "*mut *mut SV") を Type に変換
        Some(self.parse_rust_type_string(&param.ty))
    }

    /// InlineFnDict から inline 関数の引数型を取得
    /// InlineFnDict から inline 関数のパラメータ型を TypeRepr として直接取得
    ///
    /// AST (DeclSpecs + Declarator) から TypeRepr を直接構築する。
    /// 文字列への変換・再パースを経由しないため、修飾子付きポインタ等も正確に処理できる。
    fn lookup_inline_fn_param_type_repr(
        &self,
        func_name: InternedStr,
        arg_index: usize,
    ) -> Option<TypeRepr> {
        let dict = self.inline_fn_dict?;
        let func_def = dict.get(func_name)?;

        let param_list = func_def.declarator.derived.iter()
            .find_map(|d| match d {
                DerivedDecl::Function(params) => Some(params),
                _ => None,
            })?;

        let param = param_list.params.get(arg_index)?;

        let specs = CTypeSpecs::from_decl_specs(&param.specs, self.interner);
        let derived = param.declarator.as_ref()
            .map(|d| {
                // Function 派生型より前の部分のみ(パラメータ自体の型)
                CDerivedType::from_derived_decls(&d.derived)
                    .into_iter()
                    .take_while(|d| !matches!(d, CDerivedType::Function { .. }))
                    .collect()
            })
            .unwrap_or_default();

        Some(TypeRepr::CType {
            specs,
            derived,
            source: CTypeSource::InlineFn { func_name },
        })
    }

    /// InlineFnDict から inline 関数の戻り値型を TypeRepr として直接取得
    fn lookup_inline_fn_return_type_repr(&self, func_name: InternedStr) -> Option<TypeRepr> {
        let dict = self.inline_fn_dict?;
        let func_def = dict.get(func_name)?;

        let specs = CTypeSpecs::from_decl_specs(&func_def.specs, self.interner);

        // Declarator の Function より前の derived 部分のみ(戻り値のポインタ等)
        let derived: Vec<_> = CDerivedType::from_derived_decls(&func_def.declarator.derived)
            .into_iter()
            .take_while(|d| !matches!(d, CDerivedType::Function { .. }))
            .collect();

        Some(TypeRepr::CType {
            specs,
            derived,
            source: CTypeSource::InlineFn { func_name },
        })
    }

    /// DeclSpecs から Type を構築
    pub fn resolve_decl_specs(&mut self, specs: &DeclSpecs) -> Type {
        // 型指定子を集める
        let mut is_signed = false;
        let mut is_unsigned = false;
        let mut is_short = false;
        let mut is_long = 0u8; // longの個数
        let mut base_type: Option<Type> = None;

        for spec in &specs.type_specs {
            match spec {
                TypeSpec::Void => base_type = Some(Type::Void),
                TypeSpec::Char => base_type = Some(Type::Char),
                TypeSpec::Short => is_short = true,
                TypeSpec::Int => {
                    if base_type.is_none() {
                        base_type = Some(Type::Int);
                    }
                }
                TypeSpec::Long => is_long += 1,
                TypeSpec::Float => base_type = Some(Type::Float),
                TypeSpec::Double => base_type = Some(Type::Double),
                TypeSpec::Signed => is_signed = true,
                TypeSpec::Unsigned => is_unsigned = true,
                TypeSpec::Bool => base_type = Some(Type::Bool),
                TypeSpec::Int128 => base_type = Some(Type::Int128),
                TypeSpec::Struct(s) => {
                    let members = self.resolve_struct_members(s);
                    if let (Some(name), Some(m)) = (s.name, &members) {
                        self.struct_defs.insert(name, m.clone());
                    }
                    base_type = Some(Type::Struct {
                        name: s.name,
                        members,
                    });
                }
                TypeSpec::Union(s) => {
                    let members = self.resolve_struct_members(s);
                    if let (Some(name), Some(m)) = (s.name, &members) {
                        self.union_defs.insert(name, m.clone());
                    }
                    base_type = Some(Type::Union {
                        name: s.name,
                        members,
                    });
                }
                TypeSpec::Enum(e) => {
                    // 列挙定数を登録
                    self.process_enum(e);
                    base_type = Some(Type::Enum { name: e.name });
                }
                TypeSpec::TypedefName(name) => {
                    // typedefを解決
                    if let Some(ty) = self.typedef_defs.get(name) {
                        base_type = Some(ty.clone());
                    } else {
                        base_type = Some(Type::TypedefName(*name));
                    }
                }
                TypeSpec::TypeofExpr(_) => {
                    // TODO: typeof式の型を推論
                    base_type = Some(Type::Unknown);
                }
                _ => {}
            }
        }

        // 型修飾子を組み合わせる
        match (is_unsigned, is_signed, is_short, is_long, &base_type) {
            // unsigned指定
            (true, _, _, 0, None) | (true, _, _, 0, Some(Type::Int)) => Type::UnsignedInt,
            (true, _, _, 1, _) => Type::UnsignedLong,
            (true, _, _, 2, _) => Type::UnsignedLongLong,
            (true, _, true, _, _) => Type::UnsignedShort,
            (true, _, _, _, Some(Type::Char)) => Type::UnsignedChar,
            (true, _, _, _, Some(Type::Int128)) => Type::UnsignedInt128,
            // signed指定
            (_, true, _, _, Some(Type::Char)) => Type::SignedChar,
            // long指定
            (_, _, _, 1, None) | (_, _, _, 1, Some(Type::Int)) => Type::Long,
            (_, _, _, 2, _) => Type::LongLong,
            (_, _, _, 1, Some(Type::Double)) => Type::LongDouble,
            // short指定
            (_, _, true, _, _) => Type::Short,
            // デフォルト
            _ => base_type.unwrap_or(Type::Int),
        }
    }

    /// 構造体メンバーを解決
    fn resolve_struct_members(&mut self, spec: &StructSpec) -> Option<Vec<(InternedStr, Type)>> {
        spec.members.as_ref().map(|members| {
            let mut result = Vec::new();
            for member in members {
                let base_ty = self.resolve_decl_specs(&member.specs);
                for decl in &member.declarators {
                    if let Some(ref d) = decl.declarator {
                        if let Some(name) = d.name {
                            let ty = self.apply_declarator(&base_ty, d);
                            result.push((name, ty));
                        }
                    }
                }
            }
            result
        })
    }

    /// 列挙型を処理
    fn process_enum(&mut self, spec: &EnumSpec) {
        if let Some(ref enumerators) = spec.enumerators {
            let mut value = 0i64;
            for e in enumerators {
                if e.value.is_some() {
                    // TODO: 定数式を評価
                    value = 0; //                }
                self.define_symbol(Symbol {
                    name: e.name,
                    ty: Type::Int,
                    loc: spec.loc.clone(),
                    kind: SymbolKind::EnumConstant(value),
                });
                value += 1;
            }
        }
    }

    /// Declarator を適用して型を構築
    pub fn apply_declarator(&self, base_type: &Type, decl: &Declarator) -> Type {
        let mut ty = base_type.clone();

        for derived in &decl.derived {
            ty = match derived {
                DerivedDecl::Pointer(quals) => Type::Pointer(Box::new(ty), quals.clone()),
                DerivedDecl::Array(arr) => {
                    // TODO: サイズを評価
                    let _size = &arr.size;
                    Type::Array(Box::new(ty), None)
                }
                DerivedDecl::Function(params) => {
                    let param_types: Vec<_> = params.params
                        .iter()
                        .map(|p| {
                            let base = self.resolve_decl_specs_readonly(&p.specs);
                            if let Some(ref d) = p.declarator {
                                self.apply_declarator(&base, d)
                            } else {
                                base
                            }
                        })
                        .collect();
                    Type::Function {
                        return_type: Box::new(ty),
                        params: param_types,
                        variadic: params.is_variadic,
                    }
                }
            };
        }

        ty
    }

    /// DeclSpecs を読み取り専用で解決(再帰呼び出し用)
    fn resolve_decl_specs_readonly(&self, specs: &DeclSpecs) -> Type {
        // 簡略版: 主要な型のみ処理
        let mut is_unsigned = false;
        let mut is_long = 0u8;
        let mut base_type: Option<Type> = None;

        for spec in &specs.type_specs {
            match spec {
                TypeSpec::Void => base_type = Some(Type::Void),
                TypeSpec::Char => base_type = Some(Type::Char),
                TypeSpec::Int => base_type = Some(Type::Int),
                TypeSpec::Long => is_long += 1,
                TypeSpec::Float => base_type = Some(Type::Float),
                TypeSpec::Double => base_type = Some(Type::Double),
                TypeSpec::Unsigned => is_unsigned = true,
                TypeSpec::Bool => base_type = Some(Type::Bool),
                TypeSpec::TypedefName(name) => {
                    if let Some(ty) = self.typedef_defs.get(name) {
                        base_type = Some(ty.clone());
                    } else {
                        base_type = Some(Type::TypedefName(*name));
                    }
                }
                _ => {}
            }
        }

        match (is_unsigned, is_long, &base_type) {
            (true, 0, None) | (true, 0, Some(Type::Int)) => Type::UnsignedInt,
            (true, 1, _) => Type::UnsignedLong,
            (_, 1, None) | (_, 1, Some(Type::Int)) => Type::Long,
            (_, 2, _) => Type::LongLong,
            _ => base_type.unwrap_or(Type::Int),
        }
    }

    /// TypeName から型を解決
    pub fn resolve_type_name(&self, type_name: &TypeName) -> Type {
        let base_ty = self.resolve_decl_specs_readonly(&type_name.specs);
        if let Some(ref abs_decl) = type_name.declarator {
            self.apply_abstract_declarator(&base_ty, abs_decl)
        } else {
            base_ty
        }
    }

    /// AbstractDeclarator を適用して型を構築
    fn apply_abstract_declarator(&self, base_type: &Type, decl: &AbstractDeclarator) -> Type {
        let mut ty = base_type.clone();

        for derived in &decl.derived {
            ty = match derived {
                DerivedDecl::Pointer(quals) => Type::Pointer(Box::new(ty), quals.clone()),
                DerivedDecl::Array(_) => {
                    Type::Array(Box::new(ty), None)
                }
                DerivedDecl::Function(params) => {
                    let param_types: Vec<_> = params.params
                        .iter()
                        .map(|p| {
                            let base = self.resolve_decl_specs_readonly(&p.specs);
                            if let Some(ref d) = p.declarator {
                                self.apply_declarator(&base, d)
                            } else {
                                base
                            }
                        })
                        .collect();
                    Type::Function {
                        return_type: Box::new(ty),
                        params: param_types,
                        variadic: params.is_variadic,
                    }
                }
            };
        }

        ty
    }

    /// 宣言を処理してシンボルを登録
    pub fn process_declaration(&mut self, decl: &Declaration) {
        let base_ty = self.resolve_decl_specs(&decl.specs);

        // typedefの場合
        if decl.specs.storage == Some(StorageClass::Typedef) {
            for init_decl in &decl.declarators {
                if let Some(name) = init_decl.declarator.name {
                    let ty = self.apply_declarator(&base_ty, &init_decl.declarator);
                    self.typedef_defs.insert(name, ty);
                }
            }
            return;
        }

        // 通常の変数宣言
        for init_decl in &decl.declarators {
            if let Some(name) = init_decl.declarator.name {
                let ty = self.apply_declarator(&base_ty, &init_decl.declarator);
                self.define_symbol(Symbol {
                    name,
                    ty,
                    loc: decl.loc().clone(),
                    kind: SymbolKind::Variable,
                });
            }
        }
    }

    /// 関数定義を処理
    pub fn process_function_def(&mut self, func: &FunctionDef) {
        let return_ty = self.resolve_decl_specs(&func.specs);
        let func_ty = self.apply_declarator(&return_ty, &func.declarator);

        // 関数をグローバルスコープに登録
        if let Some(name) = func.declarator.name {
            self.define_symbol(Symbol {
                name,
                ty: func_ty.clone(),
                loc: func.loc().clone(),
                kind: SymbolKind::Function,
            });
        }

        // 関数本体用のスコープを開始
        self.push_scope();

        // パラメータを登録
        if let Type::Function { params, .. } = &func_ty {
            for derived in &func.declarator.derived {
                if let DerivedDecl::Function(param_list) = derived {
                    for (param, param_ty) in param_list.params.iter().zip(params.iter()) {
                        if let Some(ref decl) = param.declarator {
                            if let Some(name) = decl.name {
                                self.define_symbol(Symbol {
                                    name,
                                    ty: param_ty.clone(),
                                    loc: func.loc().clone(),
                                    kind: SymbolKind::Variable,
                                });
                            }
                        }
                    }
                    break;
                }
            }
        }

        // 関数本体を処理
        self.process_compound_stmt(&func.body);

        self.pop_scope();
    }

    /// 複合文を処理
    pub fn process_compound_stmt(&mut self, stmt: &CompoundStmt) {
        self.push_scope();
        for item in &stmt.items {
            match item {
                BlockItem::Decl(decl) => self.process_declaration(decl),
                BlockItem::Stmt(stmt) => self.process_stmt(stmt),
            }
        }
        self.pop_scope();
    }

    /// 文を処理
    fn process_stmt(&mut self, stmt: &Stmt) {
        match stmt {
            Stmt::Compound(compound) => self.process_compound_stmt(compound),
            Stmt::For { init, .. } => {
                self.push_scope();
                if let Some(ForInit::Decl(decl)) = init {
                    self.process_declaration(decl);
                }
                // TODO: 本体を処理
                self.pop_scope();
            }
            _ => {}
        }
    }

    // ========================================
    // TypeEnv への型制約収集
    // ========================================

    /// マクロパラメータを設定
    pub fn set_macro_params(&mut self, params: &[InternedStr]) {
        self.macro_params.clear();
        for &param in params {
            self.macro_params.insert(param);
        }
    }

    /// マクロパラメータをクリア
    pub fn clear_macro_params(&mut self) {
        self.macro_params.clear();
    }

    /// マクロパラメータを apidoc 型情報付きでシンボルテーブルに登録
    ///
    /// # Arguments
    /// * `macro_name` - マクロ名
    /// * `params` - パラメータ名のリスト
    /// * `files` - ファイルレジストリ
    /// * `typedefs` - typedef 名セット
    pub fn register_macro_params_from_apidoc(
        &mut self,
        macro_name: InternedStr,
        params: &[InternedStr],
        files: &'a FileRegistry,
        typedefs: &'a HashSet<InternedStr>,
    ) {
        // files と typedefs を保存(後で型パース時に使用)
        self.files = Some(files);
        self.parser_typedefs = Some(typedefs);

        // macro_params に名前を登録(既存の動作を維持)
        self.macro_params.clear();
        for &param in params {
            self.macro_params.insert(param);
        }

        // apidoc からマクロ情報を取得
        let macro_name_str = self.interner.get(macro_name);
        if let Some(apidoc) = self.apidoc {
            if let Some(entry) = apidoc.get(macro_name_str) {
                // パラメータをシンボルとして登録
                for (i, &param_name) in params.iter().enumerate() {
                    if let Some(apidoc_arg) = entry.args.get(i) {
                        // parser で型文字列をパース
                        match parse_type_from_string(
                            &apidoc_arg.ty,
                            self.interner,
                            files,
                            typedefs,
                        ) {
                            Ok(type_name) => {
                                let ty = self.resolve_type_name(&type_name);
                                self.define_symbol(Symbol {
                                    name: param_name,
                                    ty,
                                    loc: SourceLocation::default(),
                                    kind: SymbolKind::Variable,
                                });
                            }
                            Err(_) => {}
                        }
                    }
                }
            }
        }
    }

    /// C 型文字列から TypeRepr を作成
    ///
    /// `files` と `parser_typedefs` が設定されている場合は完全な C パーサーを使用。
    /// 設定されていない場合は簡易パーサーにフォールバック。
    fn parse_type_string(&self, s: &str) -> TypeRepr {
        if let (Some(files), Some(typedefs)) = (self.files, self.parser_typedefs) {
            TypeRepr::from_c_type_string(s, self.interner, files, typedefs)
        } else {
            TypeRepr::from_apidoc_string(s, self.interner)
        }
    }

    /// 識別子がマクロパラメータかどうか
    fn is_macro_param(&self, name: InternedStr) -> bool {
        self.macro_params.contains(&name)
    }

    /// *mut SV を表す TypeRepr を作成
    fn make_sv_ptr_type(&self) -> TypeRepr {
        let sv_name = self.interner.lookup("SV")
            .expect("SV should be interned");
        TypeRepr::CType {
            specs: CTypeSpecs::TypedefName(sv_name),
            derived: vec![CDerivedType::Pointer { is_const: false, is_volatile: false, is_restrict: false }],
            source: CTypeSource::SvFamilyCast,
        }
    }

    /// `*mut <typedef>` 形式の SV ファミリー型を作成(共通マクロ由来、tier 3)
    fn make_sv_family_ptr_type(&self, typedef_name: InternedStr) -> TypeRepr {
        TypeRepr::CType {
            specs: CTypeSpecs::TypedefName(typedef_name),
            derived: vec![CDerivedType::Pointer { is_const: false, is_volatile: false, is_restrict: false }],
            source: CTypeSource::CommonMacroFieldInference,
        }
    }

    /// 共通フィールドマクロ宣言フィールドへのアクセス経路から SV ファミリー
    /// パラメータ型を逆推論する。
    ///
    /// 例: `(cv)->sv_any->xcv_gv_u` の `xcv_gv_u` は `_XPVCV_COMMON` 由来 →
    /// 経路を辿って `cv` macro param に `*mut CV` 制約を追加。
    fn try_infer_sv_family_from_member(
        &self,
        member: InternedStr,
        base: &Expr,
        type_env: &mut TypeEnv,
    ) {
        let Some(fields_dict) = self.fields_dict else { return };
        let Some(macro_id) = fields_dict.defining_macro_of(member) else { return };
        let Some(sv_typedef) = fields_dict.sv_family_of_common_macro(macro_id) else { return };
        let Some((_param_name, param_node_id)) = leftmost_param_ident(base, &self.macro_params)
        else {
            return;
        };
        let sv_type = self.make_sv_family_ptr_type(sv_typedef);
        let typedef_str = self.interner.get(sv_typedef);
        let member_str = self.interner.get(member);
        type_env.add_constraint(TypeEnvConstraint::new(
            param_node_id,
            sv_type,
            format!("common-macro field {} implies {}*", member_str, typedef_str),
        ));
    }

    /// type_env から式の TypeRepr を直接取得
    fn get_expr_type_repr(&self, expr_id: ExprId, type_env: &TypeEnv) -> Option<TypeRepr> {
        type_env.expr_constraints.get(&expr_id)
            .and_then(|c| c.first())
            .map(|c| c.ty.clone())
    }

    /// type_env から式の TypeRepr を取得、無ければ "<unknown>" 由来の Void を返す。
    /// 旧 `get_expr_type_str` + `from_apidoc_string` round-trip を置き換える。
    /// round-trip だと RustType("*mut T" 等の Rust 表記)が C 専用パーサに
    /// 渡されて Void に潰れていたため、TypeRepr を直接保持することで型情報を
    /// 維持する。
    fn get_expr_type_repr_or_unknown(&self, expr_id: ExprId, type_env: &TypeEnv) -> TypeRepr {
        self.get_expr_type_repr(expr_id, type_env)
            .unwrap_or_else(|| TypeRepr::from_apidoc_string("<unknown>", self.interner))
    }

    /// type_env から式の型文字列を取得
    fn get_expr_type_str(&self, expr_id: ExprId, type_env: &TypeEnv) -> String {
        if let Some(constraints) = type_env.expr_constraints.get(&expr_id) {
            if let Some(c) = constraints.first() {
                return c.ty.to_display_string(self.interner);
            }
        }
        "<unknown>".to_string()
    }

    /// 二項演算の結果型を計算(文字列ベース)
    fn compute_binary_type_str(&self, op: &BinOp, lhs_id: ExprId, rhs_id: ExprId, type_env: &TypeEnv) -> String {
        match op {
            // 比較演算子・論理演算子は int を返す
            BinOp::Lt | BinOp::Gt | BinOp::Le | BinOp::Ge |
            BinOp::Eq | BinOp::Ne | BinOp::LogAnd | BinOp::LogOr => "int".to_string(),
            // 算術演算子は通常の型昇格
            _ => {
                let lhs_ty = self.get_expr_type_str(lhs_id, type_env);
                let rhs_ty = self.get_expr_type_str(rhs_id, type_env);
                self.usual_arithmetic_conversion_str(&lhs_ty, &rhs_ty)
            }
        }
    }

    /// 通常の算術型変換(文字列ベース)
    fn usual_arithmetic_conversion_str(&self, lhs: &str, rhs: &str) -> String {
        // ポインタ型が含まれる場合はポインタ型を優先
        let is_ptr = |ty: &str| ty.contains('*');
        if is_ptr(lhs) && !is_ptr(rhs) {
            return lhs.to_string();
        }
        if is_ptr(rhs) && !is_ptr(lhs) {
            return rhs.to_string();
        }

        // 簡易的な実装:ランク付けで大きい方を返す
        let rank = |ty: &str| -> u8 {
            match ty {
                "long double" => 10,
                "double" => 9,
                "float" => 8,
                "unsigned long long" => 7,
                "long long" => 6,
                "unsigned long" => 5,
                "long" => 4,
                "unsigned int" => 3,
                "int" => 2,
                "unsigned short" => 1,
                "short" => 1,
                _ => 0,
            }
        };

        if rank(lhs) >= rank(rhs) {
            lhs.to_string()
        } else {
            rhs.to_string()
        }
    }

    /// 条件演算の結果型を計算(文字列ベース)
    fn compute_conditional_type_str(&self, then_id: ExprId, else_id: ExprId, type_env: &TypeEnv) -> String {
        let then_ty = self.get_expr_type_str(then_id, type_env);
        let else_ty = self.get_expr_type_str(else_id, type_env);
        // void * vs 具体的ポインタ → 具体的な方を優先
        let is_void_ptr = |s: &str| s.contains("void") && s.contains('*');
        let is_concrete_ptr = |s: &str| !s.contains("void") && s.contains('*');
        if is_void_ptr(&then_ty) && is_concrete_ptr(&else_ty) {
            return else_ty;
        }
        if is_void_ptr(&else_ty) && is_concrete_ptr(&then_ty) {
            return then_ty;
        }
        self.usual_arithmetic_conversion_str(&then_ty, &else_ty)
    }

    /// 文から式の型制約を収集(再帰的に走査)
    ///
    /// 文に含まれる式に対して `collect_expr_constraints` を呼び出す。
    pub fn collect_stmt_constraints(&mut self, stmt: &Stmt, type_env: &mut TypeEnv) {
        match stmt {
            Stmt::Compound(compound) => {
                for item in &compound.items {
                    match item {
                        BlockItem::Stmt(s) => self.collect_stmt_constraints(s, type_env),
                        BlockItem::Decl(_) => {} // 宣言は型制約収集の対象外
                    }
                }
            }
            Stmt::Expr(Some(expr), _) => {
                self.collect_expr_constraints(expr, type_env);
            }
            Stmt::If { cond, then_stmt, else_stmt, .. } => {
                self.collect_expr_constraints(cond, type_env);
                self.collect_stmt_constraints(then_stmt, type_env);
                if let Some(else_s) = else_stmt {
                    self.collect_stmt_constraints(else_s, type_env);
                }
            }
            Stmt::While { cond, body, .. } => {
                self.collect_expr_constraints(cond, type_env);
                self.collect_stmt_constraints(body, type_env);
            }
            Stmt::DoWhile { body, cond, .. } => {
                self.collect_stmt_constraints(body, type_env);
                self.collect_expr_constraints(cond, type_env);
            }
            Stmt::For { init, cond, step, body, .. } => {
                if let Some(ForInit::Expr(e)) = init {
                    self.collect_expr_constraints(e, type_env);
                }
                if let Some(c) = cond {
                    self.collect_expr_constraints(c, type_env);
                }
                if let Some(s) = step {
                    self.collect_expr_constraints(s, type_env);
                }
                self.collect_stmt_constraints(body, type_env);
            }
            Stmt::Return(Some(expr), _) => {
                self.collect_expr_constraints(expr, type_env);
            }
            Stmt::Switch { expr, body, .. } => {
                self.collect_expr_constraints(expr, type_env);
                self.collect_stmt_constraints(body, type_env);
            }
            Stmt::Case { expr, stmt, .. } => {
                self.collect_expr_constraints(expr, type_env);
                self.collect_stmt_constraints(stmt, type_env);
            }
            Stmt::Default { stmt, .. } | Stmt::Label { stmt, .. } => {
                self.collect_stmt_constraints(stmt, type_env);
            }
            _ => {} // Break, Continue, Goto, Asm, Expr(None), Return(None)
        }
    }

    /// `c_field_type` が anonymous struct/union だった場合、bindings.rs
    /// (rust_decl_dict) から同じ親 struct + 同名フィールドを引いて、
    /// bindgen が生成した named 型 (`pmop__bindgen_ty_2` 等) で置き換える。
    ///
    /// これは perl の C ヘッダがインライン anonymous union を多用しており
    /// (例: `union { HV *op_pmstash; PADOFFSET op_pmstashoff; } op_pmstashstartu;`)、
    /// その内部メンバへの member access を解決するために必要。
    /// fields_dict 単体では anonymous union のフィールドを引けないが、
    /// bindings.rs では bindgen が `pmop__bindgen_ty_2` のような名前を
    /// 与えており、そこには `op_pmstash: *mut HV` 等のフィールドが
    /// 登録されている。
    /// `name` が typedef なら base struct 名へ展開する
    /// 例: "PMOP" → "pmop"。base が struct でない、または再帰深度
    /// が深すぎる場合は元の名前を返す。
    fn resolve_typedef_to_struct_name<'b>(&self, name: &'b str) -> std::borrow::Cow<'b, str> {
        let Some(rd) = self.rust_decl_dict else {
            return std::borrow::Cow::Borrowed(name);
        };
        let mut current = std::borrow::Cow::Borrowed(name);
        for _ in 0..8 {
            // 既に struct として登録されていれば終了
            if rd.structs.contains_key(current.as_ref()) {
                return current;
            }
            // typedef を辿る
            let Some(alias) = rd.types.get(current.as_ref()) else {
                return current;
            };
            current = std::borrow::Cow::Owned(alias.ty.clone());
        }
        current
    }

    fn replace_anonymous_with_bindings(
        &self,
        parent_struct_name_str: &str,
        field_name_str: &str,
        c_field_type: TypeRepr,
    ) -> TypeRepr {
        if !is_anonymous_struct_or_union_field(&c_field_type) {
            return c_field_type;
        }
        let Some(rd) = self.rust_decl_dict else {
            return c_field_type;
        };
        let resolved = self.resolve_typedef_to_struct_name(parent_struct_name_str);
        let Some(rust_struct) = rd.structs.get(resolved.as_ref()) else {
            return c_field_type;
        };
        let Some(rust_field) = rust_struct.fields.iter().find(|f| f.name == field_name_str) else {
            return c_field_type;
        };
        // 構造化された RustField.uty (UnifiedType) を直接 TypeRepr に変換。
        // 文字列 round-trip (`from_rust_string` / `from_apidoc_string` 経由) は
        // prefix 剥がしの累積で破綻するため使わない。
        TypeRepr::from_unified_type(&rust_field.uty, self.interner)
    }

    /// fields_dict (C 由来) でフィールドが見つからなかった場合の
    /// bindings.rs フォールバックルックアップ。bindgen 生成の anonymous
    /// union (`pmop__bindgen_ty_2` 等) は fields_dict には登録されない
    /// ため、その内部メンバアクセスはこの経路でのみ解決できる。
    fn lookup_field_in_bindings(
        &self,
        parent_struct_name_str: &str,
        field_name_str: &str,
    ) -> Option<TypeRepr> {
        let rd = self.rust_decl_dict?;
        let resolved = self.resolve_typedef_to_struct_name(parent_struct_name_str);
        let rust_struct = rd.structs.get(resolved.as_ref())?;
        let rust_field = rust_struct.fields.iter().find(|f| f.name == field_name_str)?;
        Some(TypeRepr::from_unified_type(&rust_field.uty, self.interner))
    }

    /// 式全体から型制約を収集し、全式の型を計算(再帰的に走査)
    ///
    /// 子式を先に処理し、親式の型を後で計算する。
    pub fn collect_expr_constraints(&mut self, expr: &Expr, type_env: &mut TypeEnv) {
        match &expr.kind {
            // リテラル
            ExprKind::IntLit(_) => {
                type_env.add_constraint(TypeEnvConstraint::new(
                    expr.id,
                    TypeRepr::Inferred(InferredType::IntLiteral),
                    "integer literal",
                ));
            }
            ExprKind::UIntLit(_) => {
                type_env.add_constraint(TypeEnvConstraint::new(
                    expr.id,
                    TypeRepr::Inferred(InferredType::UIntLiteral),
                    "unsigned integer literal",
                ));
            }
            ExprKind::FloatLit(_) => {
                type_env.add_constraint(TypeEnvConstraint::new(
                    expr.id,
                    TypeRepr::Inferred(InferredType::FloatLiteral),
                    "float literal",
                ));
            }
            ExprKind::CharLit(_) => {
                type_env.add_constraint(TypeEnvConstraint::new(
                    expr.id,
                    TypeRepr::Inferred(InferredType::CharLiteral),
                    "char literal",
                ));
            }
            ExprKind::StringLit(_) => {
                type_env.add_constraint(TypeEnvConstraint::new(
                    expr.id,
                    TypeRepr::Inferred(InferredType::StringLiteral),
                    "string literal",
                ));
            }

            // 識別子
            ExprKind::Ident(name) => {
                let name_str = self.interner.get(*name);

                // シンボルテーブルから型を取得
                if let Some(sym) = self.lookup_symbol(*name) {
                    let ty_str = sym.ty.display(self.interner);
                    // シンボル参照を示す TypeRepr を作成
                    // resolved_type は文字列からパースした C 型
                    let resolved = TypeRepr::from_apidoc_string(&ty_str, self.interner);
                    type_env.add_constraint(TypeEnvConstraint::new(
                        expr.id,
                        TypeRepr::Inferred(InferredType::SymbolLookup {
                            name: *name,
                            resolved_type: Box::new(resolved),
                        }),
                        "symbol lookup",
                    ));
                // RustDeclDict から定数の型を取得
                } else if let Some(rust_decl_dict) = self.rust_decl_dict {
                    if let Some(rust_const) = rust_decl_dict.lookup_const(name_str) {
                        type_env.add_constraint(TypeEnvConstraint::new(
                            expr.id,
                            TypeRepr::RustType {
                                repr: RustTypeRepr::from_type_string(&rust_const.ty),
                                source: RustTypeSource::Const {
                                    const_name: name_str.to_string(),
                                },
                            },
                            "bindings constant",
                        ));
                    } else if name_str == "my_perl" {
                        // THX 由来の my_perl はデフォルトで *mut PerlInterpreter
                        type_env.add_constraint(TypeEnvConstraint::new(
                            expr.id,
                            TypeRepr::Inferred(InferredType::ThxDefault),
                            "THX default type",
                        ));
                    }
                } else if name_str == "my_perl" {
                    // THX 由来の my_perl はデフォルトで *mut PerlInterpreter
                    type_env.add_constraint(TypeEnvConstraint::new(
                        expr.id,
                        TypeRepr::Inferred(InferredType::ThxDefault),
                        "THX default type",
                    ));
                }

                // パラメータ参照の場合、ExprId とパラメータを紐付け
                if self.is_macro_param(*name) {
                    type_env.link_expr_to_param(expr.id, *name, "parameter reference");
                }
            }

            // 関数呼び出し
            ExprKind::Call { func, args } => {
                // 子式を先に処理
                self.collect_expr_constraints(func, type_env);
                for arg in args {
                    self.collect_expr_constraints(arg, type_env);
                }
                // Call の型制約を追加(RustDeclDict / Apidoc から)
                self.collect_call_constraints(expr.id, func, args, type_env);
            }

            // 二項演算子
            ExprKind::Binary { op, lhs, rhs } => {
                // 子式を先に処理
                self.collect_expr_constraints(lhs, type_env);
                self.collect_expr_constraints(rhs, type_env);
                // 親式の型を計算
                let result_ty_str = self.compute_binary_type_str(op, lhs.id, rhs.id, type_env);
                let result_type = TypeRepr::from_apidoc_string(&result_ty_str, self.interner);
                type_env.add_constraint(TypeEnvConstraint::new(
                    expr.id,
                    TypeRepr::Inferred(InferredType::BinaryOp {
                        op: *op,
                        result_type: Box::new(result_type),
                    }),
                    "binary expression",
                ));
            }

            // 条件演算子
            ExprKind::Conditional { cond, then_expr, else_expr } => {
                self.collect_expr_constraints(cond, type_env);
                self.collect_expr_constraints(then_expr, type_env);
                self.collect_expr_constraints(else_expr, type_env);
                let then_type = self.get_expr_type_repr_or_unknown(then_expr.id, type_env);
                let else_type = self.get_expr_type_repr_or_unknown(else_expr.id, type_env);
                // result_type は void* と具体型の選択など文字列ベースのルールが
                // 残っているため当面 from_apidoc_string 経由のままとする
                let result_ty_str = self.compute_conditional_type_str(then_expr.id, else_expr.id, type_env);
                let result_type = TypeRepr::from_apidoc_string(&result_ty_str, self.interner);
                type_env.add_constraint(TypeEnvConstraint::new(
                    expr.id,
                    TypeRepr::Inferred(InferredType::Conditional {
                        then_type: Box::new(then_type),
                        else_type: Box::new(else_type),
                        result_type: Box::new(result_type),
                    }),
                    "conditional expression",
                ));
            }

            // キャスト
            ExprKind::Cast { type_name, expr: inner } => {
                self.collect_expr_constraints(inner, type_env);
                // AST → TypeRepr 直接変換(Type→String→TypeRepr roundtrip を排除)
                let specs = CTypeSpecs::from_decl_specs(&type_name.specs, self.interner);
                let derived: Vec<CDerivedType> = type_name.declarator.as_ref()
                    .map(|d| {
                        CDerivedType::from_derived_decls(&d.derived)
                            .into_iter()
                            .take_while(|d| !matches!(d, CDerivedType::Function { .. }))
                            .collect()
                    })
                    .unwrap_or_default();
                let target_type = TypeRepr::CType {
                    specs: specs.clone(),
                    derived: derived.clone(),
                    source: CTypeSource::Cast,
                };
                type_env.add_constraint(TypeEnvConstraint::new(
                    expr.id,
                    TypeRepr::Inferred(InferredType::Cast {
                        target_type: Box::new(target_type),
                    }),
                    "cast expression",
                ));

                // SV ファミリーキャストからのパラメータ型推論
                // (SV_FAMILY_TYPE *)param → param に *mut SV 制約を追加
                if let Some(fields_dict) = self.fields_dict {
                    let is_single_ptr = derived.len() == 1
                        && matches!(derived[0], CDerivedType::Pointer { .. });
                    if is_single_ptr {
                        if let Some(type_name_id) = specs.type_name() {
                            if fields_dict.is_sv_family_type(type_name_id) {
                                if let ExprKind::Ident(param_name) = &inner.kind {
                                    if self.is_macro_param(*param_name) {
                                        let sv_type = self.make_sv_ptr_type();
                                        type_env.add_constraint(TypeEnvConstraint::new(
                                            inner.id,
                                            sv_type,
                                            "SV family cast",
                                        ));
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // 配列添字
            ExprKind::Index { expr: base, index } => {
                self.collect_expr_constraints(base, type_env);
                self.collect_expr_constraints(index, type_env);
                // 配列/ポインタの要素型を推論
                let base_ty_str = self.get_expr_type_str(base.id, type_env);
                let elem_ty_str = if base_ty_str.ends_with('*') {
                    base_ty_str.trim_end_matches('*').trim().to_string()
                } else if base_ty_str.contains('[') {
                    base_ty_str.split('[').next().unwrap_or(&base_ty_str).trim().to_string()
                } else {
                    "<unknown>".to_string()
                };
                let base_type = TypeRepr::from_apidoc_string(&base_ty_str, self.interner);
                let element_type = TypeRepr::from_apidoc_string(&elem_ty_str, self.interner);
                type_env.add_constraint(TypeEnvConstraint::new(
                    expr.id,
                    TypeRepr::Inferred(InferredType::ArraySubscript {
                        base_type: Box::new(base_type),
                        element_type: Box::new(element_type),
                    }),
                    "array subscript",
                ));
            }

            // メンバーアクセス
            ExprKind::Member { expr: base, member } => {
                self.collect_expr_constraints(base, type_env);

                let base_ty = self.get_expr_type_str(base.id, type_env);
                let member_name = self.interner.get(*member);

                // sv_u フィールドアクセスの特殊処理
                // base が ->sv_u パターンの場合、sv_u 辞書から型を解決
                // それ以外は FieldsDict から TypeRepr を直接取得
                let field_type = if self.is_sv_u_access(base) {
                    // sv_u フィールドは C 形式の型文字列で格納されている
                    self.lookup_sv_u_field_type(*member)
                        .map(|c_type| Box::new(TypeRepr::from_apidoc_string(&c_type, self.interner)))
                } else {
                    // TypeRepr ベースのフィールドルックアップ
                    let base_type_repr = self.get_expr_type_repr(base.id, type_env);
                    let struct_name_id = base_type_repr.as_ref().and_then(|t| t.type_name());
                    // bindings.rs 由来の RustType::Named (`pmop__bindgen_ty_2` 等) も拾う
                    let struct_name_str = base_type_repr.as_ref()
                        .and_then(|t| extract_struct_name_str(t, self.interner));
                    let field_str = self.interner.get(*member);
                    // flexible array member の特別扱い: 配列ではなく要素型へのポインタ
                    let flex_ptr = struct_name_id.and_then(|n| {
                        self.fields_dict?
                            .flexible_array_element(n, *member)
                            .map(|elem| Box::new(wrap_with_outer_pointer(elem.clone(), false)))
                    });
                    // anonymous struct/union の type_repr は bindings.rs の named 型で置換
                    let direct = flex_ptr.or_else(|| {
                        struct_name_id.and_then(|n| {
                            self.fields_dict?.get_field_type(n, *member).map(|ft| {
                                let parent_str = self.interner.get(n);
                                let patched = self.replace_anonymous_with_bindings(
                                    parent_str, field_str, ft.type_repr.clone(),
                                );
                                Box::new(patched)
                            })
                        })
                    });
                    // fields_dict にない場合は bindings.rs から直接引く
                    // (bindgen 生成の anonymous union のメンバアクセス用)
                    let direct = direct.or_else(|| {
                        struct_name_str.as_deref().and_then(|parent_str| {
                            self.lookup_field_in_bindings(parent_str, field_str)
                                .map(Box::new)
                        })
                    });
                    // フォールバック: 共通フィールドマクロ × bindings.rs マッピング
                    // (無名 union メンバ等、上の経路で解決できないケース)
                    direct.or_else(|| {
                        self.fields_dict
                            .and_then(|fd| fd.rust_type_of_common_field(*member))
                            .cloned()
                            .map(Box::new)
                    })
                };

                type_env.add_constraint(TypeEnvConstraint::new(
                    expr.id,
                    TypeRepr::Inferred(InferredType::MemberAccess {
                        base_type: base_ty.clone(),
                        member: *member,
                        field_type,
                    }),
                    format!("{}.{}", base_ty, member_name),
                ));

                // 共通フィールドマクロ宣言フィールド → SV ファミリー型逆推論
                self.try_infer_sv_family_from_member(*member, base, type_env);
            }

            // ポインタメンバーアクセス
            ExprKind::PtrMember { expr: base, member } => {
                self.collect_expr_constraints(base, type_env);

                // ベース型からメンバー型を推論
                let base_ty = self.get_expr_type_str(base.id, type_env);
                let member_name = self.interner.get(*member);

                // === ベース型の逆推論 ===
                // フィールド名から構造体を特定できる場合、ベース型を推論
                if let Some(fields_dict) = self.fields_dict {
                    // ベース型がまだ不明(unknown または Ident)の場合のみ逆推論を試みる
                    if base_ty == "/* unknown */" || self.is_ident_expr(base) {
                        // 1. まず一意なフィールドを試す (Phase 1)
                        // 2. 次に SV ファミリー共通フィールドを試す (Phase 2)
                        let inferred_struct = fields_dict.lookup_unique(*member)
                            .or_else(|| fields_dict.get_consistent_base_type(*member, self.interner));

                        if let Some(struct_name) = inferred_struct {
                            // typedef 名があれば使用(例: sv → SV)
                            let type_name = fields_dict.get_typedef_for_struct(struct_name)
                                .unwrap_or(struct_name);
                            let type_name_str = self.interner.get(type_name);
                            let base_type = TypeRepr::CType {
                                specs: CTypeSpecs::TypedefName(type_name),
                                derived: vec![CDerivedType::Pointer {
                                    is_const: false,
                                    is_volatile: false,
                                    is_restrict: false,
                                }],
                                source: CTypeSource::FieldInference { field_name: *member },
                            };
                            type_env.add_constraint(TypeEnvConstraint::new(
                                base.id,
                                base_type,
                                format!("field {} implies {}*", member_name, type_name_str),
                            ));
                        }
                    }
                }

                // TypeRepr ベースのフィールドルックアップ
                let base_type_repr = self.get_expr_type_repr(base.id, type_env);
                let pointee = base_type_repr.as_ref().and_then(|t| t.pointee_name());
                let (field_type, used_consistent_type) = if let Some(name) = pointee {
                    // flexible array member の特別扱い: 配列ではなく要素型へのポインタ
                    let flex_ptr = self.fields_dict.and_then(|fd| {
                        fd.flexible_array_element(name, *member)
                            .map(|elem| Box::new(wrap_with_outer_pointer(elem.clone(), false)))
                    });
                    let parent_str = self.interner.get(name);
                    let field_str = self.interner.get(*member);
                    // ベース型が既知のポインタ型:構造体名で直接ルックアップ
                    // anonymous struct/union の場合は bindings.rs の named 型で置換
                    let direct = flex_ptr.or_else(|| {
                        self.fields_dict
                            .and_then(|fd| fd.get_field_type(name, *member))
                            .map(|ft| {
                                let patched = self.replace_anonymous_with_bindings(
                                    parent_str, field_str, ft.type_repr.clone(),
                                );
                                Box::new(patched)
                            })
                    });
                    // fields_dict にない場合は bindings.rs から直接引く
                    // (bindgen 生成の anonymous union のメンバアクセス用)
                    let direct = direct.or_else(|| {
                        self.lookup_field_in_bindings(parent_str, field_str)
                            .map(Box::new)
                    });
                    let ty = direct.or_else(|| {
                        // 共通フィールドマクロ × bindings.rs マッピング(無名 union 等)
                        self.fields_dict
                            .and_then(|fd| fd.rust_type_of_common_field(*member))
                            .cloned()
                            .map(Box::new)
                    });
                    (ty, false)
                } else if let Some(fields_dict) = self.fields_dict {
                    // ベース型が不明な場合:一致型があればそれを使用(O(1))
                    let consistent = fields_dict.get_consistent_field_type(*member)
                        .cloned()
                        .map(Box::new);
                    let ty = consistent.or_else(|| {
                        fields_dict.rust_type_of_common_field(*member)
                            .cloned()
                            .map(Box::new)
                    });
                    (ty, true)
                } else {
                    (None, false)
                };

                type_env.add_constraint(TypeEnvConstraint::new(
                    expr.id,
                    TypeRepr::Inferred(InferredType::PtrMemberAccess {
                        base_type: base_ty.clone(),
                        member: *member,
                        field_type,
                        used_consistent_type,
                    }),
                    format!("{}->{}", base_ty, member_name),
                ));

                // 共通フィールドマクロ宣言フィールド → SV ファミリー型逆推論
                self.try_infer_sv_family_from_member(*member, base, type_env);
            }

            // 代入演算子
            ExprKind::Assign { lhs, rhs, .. } => {
                self.collect_expr_constraints(lhs, type_env);
                self.collect_expr_constraints(rhs, type_env);
                // 代入式の型は左辺の型
                let lhs_type = self.get_expr_type_repr_or_unknown(lhs.id, type_env);
                type_env.add_constraint(TypeEnvConstraint::new(
                    expr.id,
                    TypeRepr::Inferred(InferredType::Assignment {
                        lhs_type: Box::new(lhs_type),
                    }),
                    "assignment expression",
                ));
            }

            // コンマ演算子
            ExprKind::Comma { lhs, rhs } => {
                self.collect_expr_constraints(lhs, type_env);
                self.collect_expr_constraints(rhs, type_env);
                // コンマ式の型は右辺の型
                let rhs_type = self.get_expr_type_repr_or_unknown(rhs.id, type_env);
                type_env.add_constraint(TypeEnvConstraint::new(
                    expr.id,
                    TypeRepr::Inferred(InferredType::Comma {
                        rhs_type: Box::new(rhs_type),
                    }),
                    "comma expression",
                ));
            }

            // 前置/後置インクリメント/デクリメント
            ExprKind::PreInc(inner) | ExprKind::PreDec(inner) |
            ExprKind::PostInc(inner) | ExprKind::PostDec(inner) => {
                self.collect_expr_constraints(inner, type_env);
                let inner_type = self.get_expr_type_repr_or_unknown(inner.id, type_env);
                type_env.add_constraint(TypeEnvConstraint::new(
                    expr.id,
                    TypeRepr::Inferred(InferredType::IncDec {
                        inner_type: Box::new(inner_type),
                    }),
                    "increment/decrement",
                ));
            }

            // アドレス取得
            ExprKind::AddrOf(inner) => {
                self.collect_expr_constraints(inner, type_env);
                let inner_type = self.get_expr_type_repr_or_unknown(inner.id, type_env);
                type_env.add_constraint(TypeEnvConstraint::new(
                    expr.id,
                    TypeRepr::Inferred(InferredType::AddressOf {
                        inner_type: Box::new(inner_type),
                    }),
                    "address-of",
                ));
            }

            // 間接参照
            ExprKind::Deref(inner) => {
                self.collect_expr_constraints(inner, type_env);
                let pointer_type = self.get_expr_type_repr_or_unknown(inner.id, type_env);
                type_env.add_constraint(TypeEnvConstraint::new(
                    expr.id,
                    TypeRepr::Inferred(InferredType::Dereference {
                        pointer_type: Box::new(pointer_type),
                    }),
                    "dereference",
                ));
            }

            // 単項プラス/マイナス
            ExprKind::UnaryPlus(inner) | ExprKind::UnaryMinus(inner) => {
                self.collect_expr_constraints(inner, type_env);
                let inner_type = self.get_expr_type_repr_or_unknown(inner.id, type_env);
                type_env.add_constraint(TypeEnvConstraint::new(
                    expr.id,
                    TypeRepr::Inferred(InferredType::UnaryArithmetic {
                        inner_type: Box::new(inner_type),
                    }),
                    "unary plus/minus",
                ));
            }

            // ビット反転
            ExprKind::BitNot(inner) => {
                self.collect_expr_constraints(inner, type_env);
                let inner_type = self.get_expr_type_repr_or_unknown(inner.id, type_env);
                type_env.add_constraint(TypeEnvConstraint::new(
                    expr.id,
                    TypeRepr::Inferred(InferredType::UnaryArithmetic {
                        inner_type: Box::new(inner_type),
                    }),
                    "bitwise not",
                ));
            }

            // 論理否定
            ExprKind::LogNot(inner) => {
                self.collect_expr_constraints(inner, type_env);
                type_env.add_constraint(TypeEnvConstraint::new(
                    expr.id,
                    TypeRepr::Inferred(InferredType::LogicalNot),
                    "logical not",
                ));
            }

            // sizeof(式)
            ExprKind::Sizeof(inner) => {
                self.collect_expr_constraints(inner, type_env);
                type_env.add_constraint(TypeEnvConstraint::new(
                    expr.id,
                    TypeRepr::Inferred(InferredType::Sizeof),
                    "sizeof expression",
                ));
            }

            // sizeof(型)
            ExprKind::SizeofType(_) => {
                type_env.add_constraint(TypeEnvConstraint::new(
                    expr.id,
                    TypeRepr::Inferred(InferredType::Sizeof),
                    "sizeof type",
                ));
            }

            // alignof
            ExprKind::Alignof(_) => {
                type_env.add_constraint(TypeEnvConstraint::new(
                    expr.id,
                    TypeRepr::Inferred(InferredType::Alignof),
                    "alignof",
                ));
            }

            // 複合リテラル
            ExprKind::CompoundLit { type_name, .. } => {
                let ty = self.resolve_type_name(type_name);
                let ty_str = ty.display(self.interner);
                let type_name_repr = TypeRepr::from_apidoc_string(&ty_str, self.interner);
                type_env.add_constraint(TypeEnvConstraint::new(
                    expr.id,
                    TypeRepr::Inferred(InferredType::CompoundLiteral {
                        type_name: Box::new(type_name_repr),
                    }),
                    "compound literal",
                ));
            }

            // Statement Expression (GCC拡張)
            ExprKind::StmtExpr(compound) => {
                self.collect_compound_constraints(compound, type_env);
                // 最後の式の型を取得
                if let Some(last_expr_id) = self.get_last_expr_id(compound) {
                    let last_expr_type = self.get_expr_type_repr_or_unknown(last_expr_id, type_env);
                    type_env.add_constraint(TypeEnvConstraint::new(
                        expr.id,
                        TypeRepr::Inferred(InferredType::StmtExpr {
                            last_expr_type: Some(Box::new(last_expr_type)),
                        }),
                        "statement expression",
                    ));
                } else {
                    type_env.add_constraint(TypeEnvConstraint::new(
                        expr.id,
                        TypeRepr::Inferred(InferredType::StmtExpr {
                            last_expr_type: None,
                        }),
                        "statement expression (empty)",
                    ));
                }
            }

            // アサーション式
            ExprKind::Assert { condition, .. } => {
                self.collect_expr_constraints(condition, type_env);
                type_env.add_constraint(TypeEnvConstraint::new(
                    expr.id,
                    TypeRepr::Inferred(InferredType::Assert),
                    "assertion",
                ));
            }

            // ビルトイン呼び出し(offsetof 等)
            ExprKind::BuiltinCall { name, args } => {
                // 引数内の式の型制約を収集
                for arg in args {
                    if let crate::ast::BuiltinArg::Expr(e) = arg {
                        self.collect_expr_constraints(e, type_env);
                    }
                }
                // offsetof → size_t (same as sizeof)
                let func_name = self.interner.get(*name);
                if func_name == "offsetof" || func_name == "__builtin_offsetof"
                    || func_name == "STRUCT_OFFSET"
                {
                    type_env.add_constraint(TypeEnvConstraint::new(
                        expr.id,
                        TypeRepr::Inferred(InferredType::Sizeof),
                        "offsetof returns size_t",
                    ));
                }
            }

            // マクロ呼び出し(展開結果の型を使用)
            ExprKind::MacroCall { name, args, expanded, .. } => {
                // 引数の型制約を収集
                for arg in args {
                    self.collect_expr_constraints(arg, type_env);
                }

                // 確定済みマクロのパラメータ型を参照(ネストしたマクロ呼び出しからの型伝播)
                let macro_name_str = self.interner.get(*name);
                if let Some(param_types) = self.get_macro_param_types(macro_name_str) {
                    for (i, arg) in args.iter().enumerate() {
                        if let Some((param_name, type_str)) = param_types.get(i) {
                            // キャッシュには Rust 形式の型文字列が保存されている
                            let constraint = TypeEnvConstraint::new(
                                arg.id,
                                TypeRepr::from_rust_string(type_str),
                                format!("arg {} ({}) of macro {}()", i, param_name, macro_name_str),
                            );
                            type_env.add_constraint(constraint);
                        }
                    }
                }

                // 展開結果の型制約を収集
                self.collect_expr_constraints(expanded, type_env);
                // MacroCall 式全体の型は expanded と同じ
                if let Some(constraints) = type_env.get_expr_constraints(expanded.id) {
                    if let Some(constraint) = constraints.first() {
                        type_env.add_constraint(TypeEnvConstraint::new(
                            expr.id,
                            constraint.ty.clone(),
                            "macro call (expanded)",
                        ));
                    }
                }
            }
        }
    }

    /// 複合文の最後の式の ExprId を取得
    fn get_last_expr_id(&self, compound: &CompoundStmt) -> Option<ExprId> {
        if let Some(BlockItem::Stmt(Stmt::Expr(Some(expr), _))) = compound.items.last() {
            Some(expr.id)
        } else {
            None
        }
    }

    /// base が ->sv_u アクセスかどうかを判定
    ///
    /// `sv->sv_u.svu_pv` のような式で、`.svu_pv` の base が `sv->sv_u` かどうかを判定する。
    fn is_sv_u_access(&self, base: &Expr) -> bool {
        if let ExprKind::PtrMember { member, .. } = &base.kind {
            let sv_u_id = self.interner.lookup("sv_u");
            sv_u_id.map_or(false, |id| *member == id)
        } else {
            false
        }
    }

    /// 式が単純な識別子かどうかを判定
    ///
    /// マクロパラメータのように、まだ型が決まっていない識別子の場合に true を返す。
    fn is_ident_expr(&self, expr: &Expr) -> bool {
        matches!(expr.kind, ExprKind::Ident(_))
    }

    /// sv_u ユニオンフィールドの型を取得
    ///
    /// sv_u union のフィールド名から対応する C 型を返す。
    /// 例: svu_pv → "char*", svu_hash → "HE**"
    fn lookup_sv_u_field_type(&self, field: InternedStr) -> Option<String> {
        self.fields_dict?
            .get_sv_u_field_type(field)
            .map(|s| s.to_string())
    }

    /// 関数呼び出しから型制約を収集
    fn collect_call_constraints(
        &mut self,
        call_expr_id: ExprId,
        func: &Expr,
        args: &[Expr],
        type_env: &mut TypeEnv,
    ) {
        // 関数名を取得
        let func_name = match &func.kind {
            ExprKind::Ident(name) => *name,
            _ => return, // 間接呼び出しは未対応
        };

        let func_name_str = self.interner.get(func_name);

        // RustDeclDict から引数の型を取得
        if let Some(rust_decl_dict) = self.rust_decl_dict {
            if let Some(rust_fn) = rust_decl_dict.fns.get(func_name_str) {
                for (i, arg) in args.iter().enumerate() {
                    if let Some(param) = rust_fn.params.get(i) {
                        let constraint = TypeEnvConstraint::new(
                            arg.id,
                            TypeRepr::RustType {
                                repr: RustTypeRepr::from_type_string(&param.ty),
                                source: RustTypeSource::FnParam {
                                    func_name: func_name_str.to_string(),
                                    param_index: i,
                                },
                            },
                            format!("arg {} of {}()", i, func_name_str),
                        );
                        type_env.add_constraint(constraint);
                    }
                }

                // 戻り値型も制約として追加
                if let Some(ref ret_ty) = rust_fn.ret_ty {
                    let return_constraint = TypeEnvConstraint::new(
                        call_expr_id,
                        TypeRepr::RustType {
                            repr: RustTypeRepr::from_type_string(ret_ty),
                            source: RustTypeSource::FnReturn {
                                func_name: func_name_str.to_string(),
                            },
                        },
                        format!("return type of {}()", func_name_str),
                    );
                    type_env.add_constraint(return_constraint);
                }
            }
        }

        // Apidoc から型を取得
        if let Some(apidoc) = self.apidoc {
            if let Some(entry) = apidoc.get(func_name_str) {
                // 引数の型
                for (i, arg) in args.iter().enumerate() {
                    if let Some(apidoc_arg) = entry.args.get(i) {
                        let constraint = TypeEnvConstraint::new(
                            arg.id,
                            self.parse_type_string(&apidoc_arg.ty),
                            format!("arg {} ({}) of {}()", i, apidoc_arg.name, func_name_str),
                        );
                        type_env.add_constraint(constraint);
                    }
                }

                // 戻り値型
                if let Some(ref return_type) = entry.return_type {
                    let return_constraint = TypeEnvConstraint::new(
                        call_expr_id,
                        self.parse_type_string(return_type),
                        format!("return type of {}()", func_name_str),
                    );
                    type_env.add_constraint(return_constraint);
                }
            }
        }

        // InlineFnDict から型を取得(AST から TypeRepr を直接構築)
        if self.inline_fn_dict.is_some() {
            // 引数の型
            for (i, arg) in args.iter().enumerate() {
                if let Some(type_repr) = self.lookup_inline_fn_param_type_repr(func_name, i) {
                    let constraint = TypeEnvConstraint::new(
                        arg.id,
                        type_repr,
                        format!("arg {} of inline {}()", i, func_name_str),
                    );
                    type_env.add_constraint(constraint);
                }
            }

            // 戻り値型
            if let Some(type_repr) = self.lookup_inline_fn_return_type_repr(func_name) {
                let return_constraint = TypeEnvConstraint::new(
                    call_expr_id,
                    type_repr,
                    format!("return type of inline {}()", func_name_str),
                );
                type_env.add_constraint(return_constraint);
            }
        }

        // 確定済みマクロのパラメータ型を参照(ネストしたマクロ呼び出しからの型伝播)
        if let Some(param_types) = self.get_macro_param_types(func_name_str) {
            for (i, arg) in args.iter().enumerate() {
                if let Some((param_name, type_str)) = param_types.get(i) {
                    // キャッシュには Rust 形式の型文字列が保存されている
                    let constraint = TypeEnvConstraint::new(
                        arg.id,
                        TypeRepr::from_rust_string(type_str),
                        format!("arg {} ({}) of macro {}()", i, param_name, func_name_str),
                    );
                    type_env.add_constraint(constraint);
                }
            }
        }

        // 確定済みマクロの戻り値型を参照
        if let Some(return_type_str) = self.get_macro_return_type(func_name_str) {
            // キャッシュには Rust 形式の型文字列が保存されている
            let return_constraint = TypeEnvConstraint::new(
                call_expr_id,
                TypeRepr::from_rust_string(return_type_str),
                format!("return type of macro {}()", func_name_str),
            );
            type_env.add_constraint(return_constraint);
        }
    }

    /// 複合文から型制約を収集
    fn collect_compound_constraints(&mut self, compound: &CompoundStmt, type_env: &mut TypeEnv) {
        for item in &compound.items {
            match item {
                BlockItem::Decl(decl) => {
                    // 宣言の初期化子内の式を処理
                    self.collect_decl_initializer_constraints(decl, type_env);
                }
                BlockItem::Stmt(Stmt::Expr(Some(expr), _)) => {
                    self.collect_expr_constraints(expr, type_env);
                }
                BlockItem::Stmt(Stmt::Return(Some(expr), _)) => {
                    self.collect_expr_constraints(expr, type_env);
                }
                BlockItem::Stmt(Stmt::Compound(inner)) => {
                    self.collect_compound_constraints(inner, type_env);
                }
                _ => {}
            }
        }
    }

    /// 宣言の初期化子から型制約を収集
    fn collect_decl_initializer_constraints(&mut self, decl: &Declaration, type_env: &mut TypeEnv) {
        for init_decl in &decl.declarators {
            if let Some(ref init) = init_decl.init {
                self.collect_initializer_constraints(init, type_env);
            }
        }
    }

    /// 初期化子から型制約を収集(再帰)
    fn collect_initializer_constraints(&mut self, init: &Initializer, type_env: &mut TypeEnv) {
        match init {
            Initializer::Expr(expr) => {
                self.collect_expr_constraints(expr, type_env);
            }
            Initializer::List(items) => {
                for item in items {
                    self.collect_initializer_constraints(&item.init, type_env);
                }
            }
        }
    }

    /// Rust型文字列を Type に変換
    fn parse_rust_type_string(&self, type_str: &str) -> Type {
        // synのto_token_stream().to_string()は "* mut" のようにスペースを入れるため正規化
        let normalized = type_str
            .replace("* mut", "*mut")
            .replace("* const", "*const");
        let trimmed = normalized.trim();

        // ポインタ型
        if let Some(rest) = trimmed.strip_prefix("*mut ") {
            return Type::Pointer(
                Box::new(self.parse_rust_type_string(rest)),
                TypeQualifiers::default(),
            );
        }
        if let Some(rest) = trimmed.strip_prefix("*const ") {
            return Type::Pointer(
                Box::new(self.parse_rust_type_string(rest)),
                TypeQualifiers { is_const: true, ..Default::default() },
            );
        }

        // 基本型
        match trimmed {
            "()" => Type::Void,
            "c_char" => Type::Char,
            "c_int" => Type::Int,
            "c_uint" => Type::UnsignedInt,
            "c_long" => Type::Long,
            "c_ulong" => Type::UnsignedLong,
            "bool" => Type::Bool,
            "usize" => Type::UnsignedLong,
            "isize" => Type::Long,
            _ => {
                // typedef名として扱う
                if let Some(interned) = self.interner.lookup(trimmed) {
                    Type::TypedefName(interned)
                } else {
                    Type::Unknown
                }
            }
        }
    }
}

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

    #[test]
    fn test_type_display() {
        let interner = StringInterner::new();

        assert_eq!(Type::Int.display(&interner), "int");
        assert_eq!(Type::UnsignedLong.display(&interner), "unsigned long");
        assert_eq!(
            Type::Pointer(Box::new(Type::Char), TypeQualifiers::default()).display(&interner),
            "char*"
        );
    }

    #[test]
    fn test_scope_management() {
        let mut interner = StringInterner::new();
        let x = interner.intern("x");
        let mut analyzer = SemanticAnalyzer::new(&interner, None, None);

        // グローバルスコープでxを定義
        analyzer.define_symbol(Symbol {
            name: x,
            ty: Type::Int,
            loc: SourceLocation::default(),
            kind: SymbolKind::Variable,
        });

        assert!(analyzer.lookup_symbol(x).is_some());

        // 新しいスコープを開始
        analyzer.push_scope();

        // まだxが見える
        assert!(analyzer.lookup_symbol(x).is_some());

        // ローカルスコープでxをシャドウイング
        analyzer.define_symbol(Symbol {
            name: x,
            ty: Type::Float, // 異なる型
            loc: SourceLocation::default(),
            kind: SymbolKind::Variable,
        });

        // ローカルのxが見える
        let sym = analyzer.lookup_symbol(x).unwrap();
        assert_eq!(sym.ty, Type::Float);

        // スコープを終了
        analyzer.pop_scope();

        // グローバルのxが見える
        let sym = analyzer.lookup_symbol(x).unwrap();
        assert_eq!(sym.ty, Type::Int);
    }
}