libperl-macrogen 0.1.3

Generate Rust FFI bindings from C macro functions in Perl headers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
//! 型表現モジュール
//!
//! TypeConstraint で使用する構造化された型表現を提供する。
//! C 型、Rust 型、推論結果を統一的に表現し、文字列ベースの型比較を排除する。

use std::fmt;

use crate::ast::BinOp;
use crate::intern::InternedStr;

// ============================================================================
// TypeRepr: トップレベル型表現
// ============================================================================

/// 型表現(出所情報を含む)
#[derive(Debug, Clone)]
pub enum TypeRepr {
    /// C 言語の型(CHeader, Apidoc, InlineFn 共通)
    CType {
        /// 型指定子(int, char, struct X, など)
        specs: CTypeSpecs,
        /// 派生型(ポインタ、配列など)
        derived: Vec<CDerivedType>,
        /// 出所(デバッグ用)
        source: CTypeSource,
    },

    /// Rust バインディングからの型(syn::Type 由来)
    RustType {
        /// 型表現
        repr: RustTypeRepr,
        /// 出所(関数名など)
        source: RustTypeSource,
    },

    /// 推論で導出
    Inferred(InferredType),
}

// ============================================================================
// C 型の出所
// ============================================================================

/// C 型の出所
#[derive(Debug, Clone)]
pub enum CTypeSource {
    /// C ヘッダーのパース結果
    Header,
    /// apidoc(embed.fnc 等)- 元の文字列を保持
    Apidoc { raw: String },
    /// inline 関数の AST
    InlineFn { func_name: InternedStr },
    /// parser.rs の parse_type_from_string を使用して解析
    Parser,
    /// フィールドアクセスからの逆推論
    FieldInference { field_name: InternedStr },
    /// キャスト式の型名(AST から直接変換)
    Cast,
    /// SV ファミリーキャストからの型推論
    SvFamilyCast,
    /// 共通フィールドマクロ宣言フィールドへのアクセス経路から逆推論された
    /// SV ファミリー型(例: `xcv_gv_u` (in `_XPVCV_COMMON`) アクセス →
    /// 引数 `cv` は `*mut CV`)。総称的な `SvFamilyCast` 由来の `*mut SV`
    /// より優先するため、`confidence_tier` で 3 を返す。
    CommonMacroFieldInference,
}

// ============================================================================
// Rust 型の出所
// ============================================================================

/// Rust 型の出所
#[derive(Debug, Clone)]
pub enum RustTypeSource {
    /// bindings.rs の関数引数
    FnParam { func_name: String, param_index: usize },
    /// bindings.rs の関数戻り値
    FnReturn { func_name: String },
    /// bindings.rs の定数
    Const { const_name: String },
    /// 文字列からパースされた型(具体的な出所は不明)
    Parsed { raw: String },
}

// ============================================================================
// C 型の構造化表現
// ============================================================================

/// C 型指定子(DeclSpecs から抽出)
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CTypeSpecs {
    /// void
    Void,
    /// char (signed: None = plain char, Some(true) = signed, Some(false) = unsigned)
    Char { signed: Option<bool> },
    /// 整数型
    Int { signed: bool, size: IntSize },
    /// float
    Float,
    /// double (is_long: long double かどうか)
    Double { is_long: bool },
    /// _Bool
    Bool,
    /// 構造体/共用体
    Struct { name: Option<InternedStr>, is_union: bool },
    /// enum
    Enum { name: Option<InternedStr> },
    /// typedef 名
    TypedefName(InternedStr),
    /// 未解決の typedef 名(interner に登録されていない場合)
    UnknownTypedef(String),
}

/// 整数サイズ
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IntSize {
    /// short
    Short,
    /// int (default)
    Int,
    /// long
    Long,
    /// long long
    LongLong,
    /// __int128
    Int128,
}

/// C 派生型
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CDerivedType {
    /// ポインタ
    Pointer {
        is_const: bool,
        is_volatile: bool,
        is_restrict: bool,
    },
    /// 配列
    Array { size: Option<usize> },
    /// 関数
    Function {
        params: Vec<CTypeSpecs>,
        variadic: bool,
    },
}

// ============================================================================
// Rust 型の構造化表現
// ============================================================================

/// Rust 型表現(syn::Type から変換)
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RustTypeRepr {
    /// C互換基本型 (c_int, c_char, etc.)
    CPrimitive(CPrimitiveKind),
    /// Rust基本型 (i32, u64, bool, etc.)
    RustPrimitive(RustPrimitiveKind),
    /// ポインタ (*mut T, *const T)
    Pointer {
        inner: Box<RustTypeRepr>,
        is_const: bool,
    },
    /// 参照 (&T, &mut T)
    Reference {
        inner: Box<RustTypeRepr>,
        is_mut: bool,
    },
    /// 名前付き型 (SV, AV, PerlInterpreter, etc.)
    Named(String),
    /// Option<T>
    Option(Box<RustTypeRepr>),
    /// 関数ポインタ
    FnPointer {
        params: Vec<RustTypeRepr>,
        ret: Option<Box<RustTypeRepr>>,
    },
    /// ユニット ()
    Unit,
    /// パース不能だった型(文字列で保持)
    Unknown(String),
}

/// C互換基本型
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CPrimitiveKind {
    CChar,
    CSchar,
    CUchar,
    CShort,
    CUshort,
    CInt,
    CUint,
    CLong,
    CUlong,
    CLongLong,
    CUlongLong,
    CFloat,
    CDouble,
}

/// Rust基本型
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RustPrimitiveKind {
    I8,
    I16,
    I32,
    I64,
    I128,
    Isize,
    U8,
    U16,
    U32,
    U64,
    U128,
    Usize,
    F32,
    F64,
    Bool,
}

// ============================================================================
// 推論の根拠 (InferredType)
// ============================================================================

/// 推論で導出された型
#[derive(Debug, Clone)]
pub enum InferredType {
    // ==================== リテラル ====================
    /// 整数リテラル (42, 0x1F, etc.)
    IntLiteral,
    /// 符号なし整数リテラル (42u, etc.)
    UIntLiteral,
    /// 浮動小数点リテラル (3.14, etc.)
    FloatLiteral,
    /// 文字リテラル ('a')
    CharLiteral,
    /// 文字列リテラル ("hello")
    StringLiteral,

    // ==================== 識別子参照 ====================
    /// シンボルテーブルからの参照
    SymbolLookup {
        name: InternedStr,
        /// 解決された型
        resolved_type: Box<TypeRepr>,
    },
    /// THX (my_perl) のデフォルト型
    ThxDefault,

    // ==================== 演算子 ====================
    /// 二項演算の結果
    BinaryOp {
        op: BinOp,
        /// 左右オペランドの型から計算された結果型
        result_type: Box<TypeRepr>,
    },
    /// 単項演算 (+, -, ~)
    UnaryArithmetic {
        /// 内部式の型をそのまま継承
        inner_type: Box<TypeRepr>,
    },
    /// 論理否定 (!) - 常に int
    LogicalNot,
    /// アドレス取得 (&x)
    AddressOf { inner_type: Box<TypeRepr> },
    /// 間接参照 (*p)
    Dereference { pointer_type: Box<TypeRepr> },
    /// インクリメント/デクリメント (++, --)
    IncDec { inner_type: Box<TypeRepr> },

    // ==================== メンバーアクセス ====================
    /// 直接メンバーアクセス (expr.member)
    MemberAccess {
        base_type: String,
        member: InternedStr,
        /// 解決されたフィールド型
        field_type: Option<Box<TypeRepr>>,
    },
    /// ポインタメンバーアクセス (expr->member)
    PtrMemberAccess {
        base_type: String,
        member: InternedStr,
        /// 解決されたフィールド型
        field_type: Option<Box<TypeRepr>>,
        /// 一致型を使用した場合(ベース型が不明時)
        used_consistent_type: bool,
    },

    // ==================== 配列/添字 ====================
    /// 配列添字 (arr[i])
    ArraySubscript {
        base_type: Box<TypeRepr>,
        /// 要素型
        element_type: Box<TypeRepr>,
    },

    // ==================== 条件・制御 ====================
    /// 条件演算子 (cond ? then : else)
    Conditional {
        then_type: Box<TypeRepr>,
        else_type: Box<TypeRepr>,
        /// 計算された共通型
        result_type: Box<TypeRepr>,
    },
    /// コンマ式 (a, b)
    Comma {
        /// 右辺の型
        rhs_type: Box<TypeRepr>,
    },
    /// 代入式 (a = b)
    Assignment {
        /// 左辺の型
        lhs_type: Box<TypeRepr>,
    },

    // ==================== 型操作 ====================
    /// キャスト式 ((type)expr)
    Cast { target_type: Box<TypeRepr> },
    /// sizeof 式/型 - 常に unsigned long
    Sizeof,
    /// alignof - 常に unsigned long
    Alignof,
    /// 複合リテラル ((type){...})
    CompoundLiteral { type_name: Box<TypeRepr> },

    // ==================== その他 ====================
    /// 文式 ({ ... })
    StmtExpr {
        /// 最後の式の型
        last_expr_type: Option<Box<TypeRepr>>,
    },
    /// アサーション - 常に void
    Assert,
    /// 関数呼び出しの戻り値(RustBindings/Apidoc から取得できなかった場合)
    FunctionReturn { func_name: InternedStr },
}

// ============================================================================
// 変換関数
// ============================================================================

impl CTypeSpecs {
    /// DeclSpecs から CTypeSpecs を抽出
    pub fn from_decl_specs(specs: &crate::ast::DeclSpecs, _interner: &crate::intern::StringInterner) -> Self {
        use crate::ast::TypeSpec;

        let mut has_signed = false;
        let mut has_unsigned = false;
        let mut has_short = false;
        let mut has_long: u8 = 0;
        let mut base_type: Option<CTypeSpecs> = None;

        for type_spec in &specs.type_specs {
            match type_spec {
                TypeSpec::Void => base_type = Some(CTypeSpecs::Void),
                TypeSpec::Char => {
                    // char の signed/unsigned は後で決定
                    if base_type.is_none() {
                        base_type = Some(CTypeSpecs::Char { signed: None });
                    }
                }
                TypeSpec::Short => has_short = true,
                TypeSpec::Int => {
                    if base_type.is_none() {
                        base_type = Some(CTypeSpecs::Int {
                            signed: true,
                            size: IntSize::Int,
                        });
                    }
                }
                TypeSpec::Long => has_long += 1,
                TypeSpec::Float => base_type = Some(CTypeSpecs::Float),
                TypeSpec::Double => base_type = Some(CTypeSpecs::Double { is_long: false }),
                TypeSpec::Signed => has_signed = true,
                TypeSpec::Unsigned => has_unsigned = true,
                TypeSpec::Bool => base_type = Some(CTypeSpecs::Bool),
                TypeSpec::Int128 => {
                    base_type = Some(CTypeSpecs::Int {
                        signed: !has_unsigned,
                        size: IntSize::Int128,
                    });
                }
                TypeSpec::Struct(s) => {
                    base_type = Some(CTypeSpecs::Struct {
                        name: s.name,
                        is_union: false,
                    });
                }
                TypeSpec::Union(s) => {
                    base_type = Some(CTypeSpecs::Struct {
                        name: s.name,
                        is_union: true,
                    });
                }
                TypeSpec::Enum(e) => {
                    base_type = Some(CTypeSpecs::Enum { name: e.name });
                }
                TypeSpec::TypedefName(name) => {
                    base_type = Some(CTypeSpecs::TypedefName(*name));
                }
                _ => {}
            }
        }

        // signed/unsigned と short/long の組み合わせを処理
        if has_short {
            return CTypeSpecs::Int {
                signed: !has_unsigned,
                size: IntSize::Short,
            };
        }

        if has_long >= 2 {
            return CTypeSpecs::Int {
                signed: !has_unsigned,
                size: IntSize::LongLong,
            };
        }

        if has_long == 1 {
            if let Some(CTypeSpecs::Double { .. }) = base_type {
                return CTypeSpecs::Double { is_long: true };
            }
            return CTypeSpecs::Int {
                signed: !has_unsigned,
                size: IntSize::Long,
            };
        }

        // char の signed/unsigned を確定
        if let Some(CTypeSpecs::Char { .. }) = base_type {
            if has_signed {
                return CTypeSpecs::Char { signed: Some(true) };
            } else if has_unsigned {
                return CTypeSpecs::Char { signed: Some(false) };
            }
            return CTypeSpecs::Char { signed: None };
        }

        // 単独の signed/unsigned
        if has_unsigned && base_type.is_none() {
            return CTypeSpecs::Int {
                signed: false,
                size: IntSize::Int,
            };
        }
        if has_signed && base_type.is_none() {
            return CTypeSpecs::Int {
                signed: true,
                size: IntSize::Int,
            };
        }

        // int の unsigned
        if has_unsigned {
            if let Some(CTypeSpecs::Int { size, .. }) = base_type {
                return CTypeSpecs::Int {
                    signed: false,
                    size,
                };
            }
        }

        base_type.unwrap_or(CTypeSpecs::Int {
            signed: true,
            size: IntSize::Int,
        })
    }
}

impl CDerivedType {
    /// DerivedDecl のリストから CDerivedType のリストを作成
    pub fn from_derived_decls(derived: &[crate::ast::DerivedDecl]) -> Vec<Self> {
        use crate::ast::ExprKind;

        derived
            .iter()
            .map(|d| match d {
                crate::ast::DerivedDecl::Pointer(quals) => CDerivedType::Pointer {
                    is_const: quals.is_const,
                    is_volatile: quals.is_volatile,
                    is_restrict: quals.is_restrict,
                },
                crate::ast::DerivedDecl::Array(array_decl) => {
                    // 配列サイズが定数リテラルの場合のみ抽出
                    let size = array_decl.size.as_ref().and_then(|expr| {
                        match &expr.kind {
                            ExprKind::IntLit(n) => Some(*n as usize),
                            ExprKind::UIntLit(n) => Some(*n as usize),
                            _ => None,
                        }
                    });
                    CDerivedType::Array { size }
                }
                crate::ast::DerivedDecl::Function(_params) => {
                    // 関数パラメータの詳細は簡略化
                    CDerivedType::Function {
                        params: vec![],
                        variadic: false,
                    }
                }
            })
            .collect()
    }
}

impl RustTypeRepr {
    /// 型文字列から RustTypeRepr をパース
    pub fn from_type_string(s: &str) -> Self {
        let s = s.trim();

        // ユニット型
        if s == "()" {
            return RustTypeRepr::Unit;
        }

        // ポインタ型
        if let Some(rest) = s.strip_prefix("*mut ") {
            return RustTypeRepr::Pointer {
                inner: Box::new(Self::from_type_string(rest)),
                is_const: false,
            };
        }
        if let Some(rest) = s.strip_prefix("* mut ") {
            return RustTypeRepr::Pointer {
                inner: Box::new(Self::from_type_string(rest)),
                is_const: false,
            };
        }
        if let Some(rest) = s.strip_prefix("*const ") {
            return RustTypeRepr::Pointer {
                inner: Box::new(Self::from_type_string(rest)),
                is_const: true,
            };
        }
        if let Some(rest) = s.strip_prefix("* const ") {
            return RustTypeRepr::Pointer {
                inner: Box::new(Self::from_type_string(rest)),
                is_const: true,
            };
        }

        // 参照型
        if let Some(rest) = s.strip_prefix("&mut ") {
            return RustTypeRepr::Reference {
                inner: Box::new(Self::from_type_string(rest)),
                is_mut: true,
            };
        }
        if let Some(rest) = s.strip_prefix("& mut ") {
            return RustTypeRepr::Reference {
                inner: Box::new(Self::from_type_string(rest)),
                is_mut: true,
            };
        }
        if let Some(rest) = s.strip_prefix('&') {
            return RustTypeRepr::Reference {
                inner: Box::new(Self::from_type_string(rest.trim())),
                is_mut: false,
            };
        }

        // C 互換基本型
        if let Some(kind) = Self::parse_c_primitive(s) {
            return RustTypeRepr::CPrimitive(kind);
        }

        // Rust 基本型
        if let Some(kind) = Self::parse_rust_primitive(s) {
            return RustTypeRepr::RustPrimitive(kind);
        }

        // Option<T>
        if s.starts_with("Option<") || s.starts_with(":: std :: option :: Option<") {
            if let Some(inner) = Self::extract_generic_param(s, "Option") {
                return RustTypeRepr::Option(Box::new(Self::from_type_string(&inner)));
            }
        }

        // 名前付き型(識別子)
        if s.chars().next().map(|c| c.is_alphabetic() || c == '_').unwrap_or(false) {
            // パスセパレータを含む場合は最後の部分を使用
            let name = s.split("::").last().unwrap_or(s).trim();
            return RustTypeRepr::Named(name.to_string());
        }

        // パース不能
        RustTypeRepr::Unknown(s.to_string())
    }

    /// C 互換基本型をパース
    fn parse_c_primitive(s: &str) -> Option<CPrimitiveKind> {
        // :: std :: os :: raw :: c_* 形式にも対応
        let s = s.trim();
        let name = if s.contains("::") {
            s.split("::").last()?.trim()
        } else {
            s
        };

        match name {
            "c_char" => Some(CPrimitiveKind::CChar),
            "c_schar" => Some(CPrimitiveKind::CSchar),
            "c_uchar" => Some(CPrimitiveKind::CUchar),
            "c_short" => Some(CPrimitiveKind::CShort),
            "c_ushort" => Some(CPrimitiveKind::CUshort),
            "c_int" => Some(CPrimitiveKind::CInt),
            "c_uint" => Some(CPrimitiveKind::CUint),
            "c_long" => Some(CPrimitiveKind::CLong),
            "c_ulong" => Some(CPrimitiveKind::CUlong),
            "c_longlong" => Some(CPrimitiveKind::CLongLong),
            "c_ulonglong" => Some(CPrimitiveKind::CUlongLong),
            "c_float" => Some(CPrimitiveKind::CFloat),
            "c_double" => Some(CPrimitiveKind::CDouble),
            _ => None,
        }
    }

    /// Rust 基本型をパース
    fn parse_rust_primitive(s: &str) -> Option<RustPrimitiveKind> {
        match s.trim() {
            "i8" => Some(RustPrimitiveKind::I8),
            "i16" => Some(RustPrimitiveKind::I16),
            "i32" => Some(RustPrimitiveKind::I32),
            "i64" => Some(RustPrimitiveKind::I64),
            "i128" => Some(RustPrimitiveKind::I128),
            "isize" => Some(RustPrimitiveKind::Isize),
            "u8" => Some(RustPrimitiveKind::U8),
            "u16" => Some(RustPrimitiveKind::U16),
            "u32" => Some(RustPrimitiveKind::U32),
            "u64" => Some(RustPrimitiveKind::U64),
            "u128" => Some(RustPrimitiveKind::U128),
            "usize" => Some(RustPrimitiveKind::Usize),
            "f32" => Some(RustPrimitiveKind::F32),
            "f64" => Some(RustPrimitiveKind::F64),
            "bool" => Some(RustPrimitiveKind::Bool),
            _ => None,
        }
    }

    /// ジェネリック型のパラメータを抽出
    fn extract_generic_param(s: &str, type_name: &str) -> Option<String> {
        // "Option<T>" または ":: std :: option :: Option<T>" から T を抽出
        let start = s.find(&format!("{}<", type_name))?;
        let after_open = start + type_name.len() + 1;
        let content = &s[after_open..];

        // 対応する > を探す(ネストを考慮)
        let mut depth = 1;
        let mut end = 0;
        for (i, c) in content.char_indices() {
            match c {
                '<' => depth += 1,
                '>' => {
                    depth -= 1;
                    if depth == 0 {
                        end = i;
                        break;
                    }
                }
                _ => {}
            }
        }

        if end > 0 {
            Some(content[..end].trim().to_string())
        } else {
            None
        }
    }
}

impl TypeRepr {
    /// 出所の表示用文字列を取得
    pub fn source_display(&self) -> &'static str {
        match self {
            TypeRepr::CType { source, .. } => match source {
                CTypeSource::Header => "c-header",
                CTypeSource::Apidoc { .. } => "apidoc",
                CTypeSource::InlineFn { .. } => "inline-fn",
                CTypeSource::Parser => "parser",
                CTypeSource::FieldInference { .. } => "field-inference",
                CTypeSource::Cast => "cast",
                CTypeSource::SvFamilyCast => "sv-family-cast",
                CTypeSource::CommonMacroFieldInference => "common-macro-field-inference",
            },
            TypeRepr::RustType { .. } => "rust-bindings",
            TypeRepr::Inferred(_) => "inferred",
        }
    }

    /// void 型かどうかを判定
    ///
    /// ポインタを含まない void 型の場合に true を返す。
    /// `void *` は false を返す(有効なポインタ型のため)。
    /// bindings.rs の FnParam ソースかどうか
    pub fn is_fn_param_source(&self) -> bool {
        matches!(self, TypeRepr::RustType { source: RustTypeSource::FnParam { .. }, .. })
    }

    /// 型情報の確度 Tier を返す
    ///
    /// - Tier 1: bindings.rs (bindgen生成、変更不可)
    /// - Tier 2: C ヘッダー宣言 / inline 関数パラメータ (変更不可)
    /// - Tier 3: apidoc (embed.fnc 等、参考情報)
    /// - Tier 4: 推論結果 (変更可能)
    pub fn confidence_tier(&self) -> u8 {
        match self {
            TypeRepr::RustType { source, .. } => match source {
                RustTypeSource::FnParam { .. }
                | RustTypeSource::FnReturn { .. }
                | RustTypeSource::Const { .. } => 1,
                RustTypeSource::Parsed { .. } => 3,
            },
            TypeRepr::CType { source, .. } => match source {
                CTypeSource::InlineFn { .. } | CTypeSource::Header => 2,
                CTypeSource::Apidoc { .. }
                | CTypeSource::CommonMacroFieldInference => 3,
                CTypeSource::Cast
                | CTypeSource::SvFamilyCast
                | CTypeSource::FieldInference { .. }
                | CTypeSource::Parser => 4,
            },
            TypeRepr::Inferred(_) => 4,
        }
    }

    pub fn is_void(&self) -> bool {
        match self {
            TypeRepr::CType { specs, derived, .. } => {
                // ポインタや配列がない純粋な void のみ true
                derived.is_empty() && matches!(specs, CTypeSpecs::Void)
            }
            TypeRepr::RustType { repr, .. } => {
                matches!(repr, RustTypeRepr::Unit)
            }
            TypeRepr::Inferred(inferred) => {
                match inferred {
                    InferredType::SymbolLookup { resolved_type, .. } => {
                        resolved_type.is_void()
                    }
                    _ => false,
                }
            }
        }
    }

    /// 最外ポインタの is_const を true に変更する
    /// 最外ポインタの is_const を false に変更する(must-mut 用)
    pub fn make_outer_pointer_mut(&mut self) {
        match self {
            TypeRepr::CType { derived, .. } => {
                for d in derived.iter_mut().rev() {
                    if let CDerivedType::Pointer { is_const, .. } = d {
                        *is_const = false;
                        return;
                    }
                }
            }
            TypeRepr::RustType { repr, .. } => {
                if let RustTypeRepr::Pointer { is_const, .. } = repr {
                    *is_const = false;
                }
            }
            _ => {}
        }
    }

    pub fn make_outer_pointer_const(&mut self) {
        match self {
            TypeRepr::CType { derived, .. } => {
                // derived の最後(最外側)のポインタを const に
                for d in derived.iter_mut().rev() {
                    if let CDerivedType::Pointer { is_const, .. } = d {
                        *is_const = true;
                        return;
                    }
                }
            }
            TypeRepr::RustType { repr, .. } => {
                repr.make_outer_pointer_const();
            }
            TypeRepr::Inferred(inferred) => {
                match inferred {
                    InferredType::SymbolLookup { resolved_type, .. } => {
                        resolved_type.make_outer_pointer_const();
                    }
                    InferredType::Cast { target_type } => {
                        target_type.make_outer_pointer_const();
                    }
                    _ => {}
                }
            }
        }
    }

    /// ポインタ型かどうか (`has_outer_pointer` のエイリアス)。
    ///
    /// `Inferred` ラッパは `resolved_type()` を経由して中身を再帰参照する点で
    /// `has_outer_pointer` と挙動が異なる (本メソッドは構造的「実体型」判定に
    /// 使う)。`has_outer_pointer` 自体は既存の使用箇所が `Inferred` を別扱い
    /// しているため挙動を変えない。
    pub fn is_pointer_type(&self) -> bool {
        match self {
            TypeRepr::CType { derived, .. } => {
                derived.iter().any(|d| matches!(d, CDerivedType::Pointer { .. }))
            }
            TypeRepr::RustType { repr, .. } => repr.has_outer_pointer(),
            TypeRepr::Inferred(inferred) => inferred
                .resolved_type()
                .is_some_and(|t| t.is_pointer_type()),
        }
    }

    /// `void *` / `*mut c_void` / `*const c_void` かどうかを **構造的に** 判定する。
    ///
    /// 文字列 `contains("void")` ではなく specs/derived の構造で判定するので、
    /// `*mut struct void_table` のような偽陽性に引っかからない。
    /// `Inferred` ラッパは `resolved_type()` 経由で中身を再帰参照する。
    pub fn is_void_pointer(&self) -> bool {
        match self {
            TypeRepr::CType { specs, derived, .. } => {
                derived.iter().any(|d| matches!(d, CDerivedType::Pointer { .. }))
                    && matches!(specs, CTypeSpecs::Void)
            }
            TypeRepr::RustType { repr, .. } => match repr {
                RustTypeRepr::Pointer { inner, .. } => {
                    matches!(inner.as_ref(), RustTypeRepr::Unit)
                        || matches!(inner.as_ref(), RustTypeRepr::Named(n) if n == "c_void")
                }
                _ => false,
            },
            TypeRepr::Inferred(inferred) => inferred
                .resolved_type()
                .is_some_and(|t| t.is_void_pointer()),
        }
    }

    /// 具体的なポインタ (`void *` ではないポインタ型) かどうか
    pub fn is_concrete_pointer(&self) -> bool {
        self.is_pointer_type() && !self.is_void_pointer()
    }

    /// 最外ポインタを持つかどうか
    ///
    /// 既存呼出側の挙動を変えないため `Inferred` は false を返す
    /// (再帰判定が必要な場合は `is_pointer_type` を使うこと)。
    pub fn has_outer_pointer(&self) -> bool {
        match self {
            TypeRepr::CType { derived, .. } => {
                derived.iter().any(|d| matches!(d, CDerivedType::Pointer { .. }))
            }
            TypeRepr::RustType { repr, .. } => repr.has_outer_pointer(),
            _ => false,
        }
    }

    /// Apidoc の型文字列から TypeRepr を作成
    pub fn from_apidoc_string(s: &str, interner: &crate::intern::StringInterner) -> Self {
        // C 型文字列をパース
        let (specs, derived) = Self::parse_c_type_string(s, interner);
        TypeRepr::CType {
            specs,
            derived,
            source: CTypeSource::Apidoc { raw: s.to_string() },
        }
    }

    /// Rust 形式の型文字列から TypeRepr を作成
    ///
    /// `*mut T`, `*const T`, `c_int` などの Rust 形式の型文字列をパースする。
    /// rust_decl.rs からの型情報の読み込みに使用する。
    pub fn from_rust_string(s: &str) -> Self {
        let repr = RustTypeRepr::from_type_string(s);
        TypeRepr::RustType {
            repr,
            source: RustTypeSource::Parsed {
                raw: s.to_string(),
            },
        }
    }

    /// **構造ベース**: `UnifiedType` から `TypeRepr` を直接構築する。
    ///
    /// bindings.rs (`syn::File`) → `RustField.uty` (`UnifiedType`) で得た
    /// 構造化情報を、文字列を経由せず TypeRepr に変換する。
    /// Pointer / Array / Named / 基本型は `CType` として表現し、
    /// FnPtr / Verbatim / Unknown は表現できないので `RustType` の
    /// `Unknown(canonical_string)` にフォールバックする。
    ///
    /// Source は `CTypeSource::Apidoc { raw }` で記録する (tier 3 相当)。
    /// bindings は本来 tier 1 だが、本メソッドの呼出元 (anonymous union
    /// メンバ解決) は元の C-side フィールド型を補完する用途なので、tier 3
    /// で十分。tier 1 が必要な経路ができたら別 source variant を追加する。
    pub fn from_unified_type(
        ut: &crate::unified_type::UnifiedType,
        interner: &crate::intern::StringInterner,
    ) -> Self {
        let raw = ut.to_rust_string();
        if let Some((specs, derived)) = unified_to_c(ut, interner) {
            return TypeRepr::CType {
                specs,
                derived,
                source: CTypeSource::Apidoc { raw },
            };
        }
        TypeRepr::RustType {
            repr: RustTypeRepr::Unknown(raw.clone()),
            source: RustTypeSource::Parsed { raw },
        }
    }

    /// DeclSpecs と Declarator から TypeRepr を作成
    ///
    /// C ヘッダーのパース結果から直接 TypeRepr を生成する。
    /// fields_dict.rs でのフィールド型収集に使用する。
    pub fn from_decl(
        specs: &crate::ast::DeclSpecs,
        declarator: &crate::ast::Declarator,
        _interner: &crate::intern::StringInterner,
    ) -> Self {
        let c_specs = CTypeSpecs::from_decl_specs(specs, _interner);
        let derived = CDerivedType::from_derived_decls(&declarator.derived);
        TypeRepr::CType {
            specs: c_specs,
            derived,
            source: CTypeSource::Header,
        }
    }

    /// TypeName (パーサー出力) から TypeRepr を作成
    ///
    /// `parser::parse_type_from_string` の結果から TypeRepr を生成する。
    /// `from_apidoc_string` の代替として使用し、完全な C パーサーを活用する。
    pub fn from_type_name(
        type_name: &crate::ast::TypeName,
        interner: &crate::intern::StringInterner,
    ) -> Self {
        let c_specs = CTypeSpecs::from_decl_specs(&type_name.specs, interner);
        let derived = type_name.declarator
            .as_ref()
            .map(|d| CDerivedType::from_derived_decls(&d.derived))
            .unwrap_or_default();
        TypeRepr::CType {
            specs: c_specs,
            derived,
            source: CTypeSource::Parser,
        }
    }

    /// C 型文字列から TypeRepr を作成(パーサー版)
    ///
    /// `parser.rs` の `parse_type_from_string` を使用して完全な C パーサーで解析する。
    /// `files` と `typedefs` が必要なため、`SemanticAnalyzer` など型情報が揃っている
    /// コンテキストでの使用を推奨。
    ///
    /// パースに失敗した場合は `from_apidoc_string` と同じ簡易パーサーにフォールバックする。
    pub fn from_c_type_string(
        s: &str,
        interner: &crate::intern::StringInterner,
        files: &crate::source::FileRegistry,
        typedefs: &std::collections::HashSet<crate::intern::InternedStr>,
    ) -> Self {
        use crate::parser::parse_type_from_string;

        match parse_type_from_string(s, interner, files, typedefs) {
            Ok(type_name) => Self::from_type_name(&type_name, interner),
            Err(_) => {
                // フォールバック: 既存の簡易パーサーを使用
                let (specs, derived) = Self::parse_c_type_string(s, interner);
                TypeRepr::CType {
                    specs,
                    derived,
                    source: CTypeSource::Apidoc { raw: s.to_string() },
                }
            }
        }
    }

    /// C 型文字列をパース(簡易版)
    fn parse_c_type_string(s: &str, interner: &crate::intern::StringInterner) -> (CTypeSpecs, Vec<CDerivedType>) {
        let s = s.trim();

        // Rust 形式 (`*mut T` / `*const T`) は先頭から prefix で剥がす。
        // bindings.rs (`RustField.ty`) 由来の文字列が経由する経路で必要。
        // 通常の C 形式 (`T *`) と混在しないよう、先頭プレフィクスがある間
        // 繰り返し処理する。
        let mut prefix_pointers: Vec<bool> = Vec::new(); // is_const
        let mut current = s;
        loop {
            if let Some(rest) = current.strip_prefix("*mut ") {
                prefix_pointers.push(false);
                current = rest.trim();
            } else if let Some(rest) = current.strip_prefix("*const ") {
                prefix_pointers.push(true);
                current = rest.trim();
            } else {
                break;
            }
        }

        // ポインタ数をカウント
        let mut ptr_count = 0;
        let mut is_const = false;
        let mut base = current;

        // 末尾の * をカウント
        while base.ends_with('*') {
            ptr_count += 1;
            base = base[..base.len() - 1].trim();
        }

        // "const" をチェック
        if base.starts_with("const ") {
            is_const = true;
            base = base[6..].trim();
        }
        if base.ends_with(" const") {
            is_const = true;
            base = base[..base.len() - 6].trim();
        }

        // 基本型をパース
        let specs = Self::parse_c_base_type(base, interner);

        // 派生型を構築
        // 内側の Rust prefix ポインタを最初に積み、続いて C 形式 trailing
        // ポインタを積む。`*mut HV` (Rust) は `HV *` (C) と等価なので
        // 出力 derived は同じ並びになる。
        let mut derived: Vec<CDerivedType> = Vec::with_capacity(prefix_pointers.len() + ptr_count);
        for is_const_p in prefix_pointers.iter().rev() {
            derived.push(CDerivedType::Pointer {
                is_const: *is_const_p,
                is_volatile: false,
                is_restrict: false,
            });
        }
        for i in 0..ptr_count {
            derived.push(CDerivedType::Pointer {
                is_const: i == 0 && is_const,
                is_volatile: false,
                is_restrict: false,
            });
        }

        (specs, derived)
    }

    /// C 基本型文字列をパース
    fn parse_c_base_type(s: &str, interner: &crate::intern::StringInterner) -> CTypeSpecs {
        match s {
            "void" => CTypeSpecs::Void,
            "char" => CTypeSpecs::Char { signed: None },
            "signed char" => CTypeSpecs::Char { signed: Some(true) },
            "unsigned char" => CTypeSpecs::Char { signed: Some(false) },
            "short" | "short int" | "signed short" | "signed short int" => {
                CTypeSpecs::Int { signed: true, size: IntSize::Short }
            }
            "unsigned short" | "unsigned short int" => {
                CTypeSpecs::Int { signed: false, size: IntSize::Short }
            }
            "int" | "signed" | "signed int" => {
                CTypeSpecs::Int { signed: true, size: IntSize::Int }
            }
            "unsigned" | "unsigned int" => {
                CTypeSpecs::Int { signed: false, size: IntSize::Int }
            }
            "long" | "long int" | "signed long" | "signed long int" => {
                CTypeSpecs::Int { signed: true, size: IntSize::Long }
            }
            "unsigned long" | "unsigned long int" => {
                CTypeSpecs::Int { signed: false, size: IntSize::Long }
            }
            "long long" | "long long int" | "signed long long" | "signed long long int" => {
                CTypeSpecs::Int { signed: true, size: IntSize::LongLong }
            }
            "unsigned long long" | "unsigned long long int" => {
                CTypeSpecs::Int { signed: false, size: IntSize::LongLong }
            }
            "float" => CTypeSpecs::Float,
            "double" => CTypeSpecs::Double { is_long: false },
            "long double" => CTypeSpecs::Double { is_long: true },
            "_Bool" | "bool" => CTypeSpecs::Bool,
            _ => {
                // 構造体/共用体/typedef 名として扱う
                if let Some(rest) = s.strip_prefix("struct ") {
                    if let Some(name) = interner.lookup(rest.trim()) {
                        return CTypeSpecs::Struct { name: Some(name), is_union: false };
                    }
                    return CTypeSpecs::Struct { name: None, is_union: false };
                }
                if let Some(rest) = s.strip_prefix("union ") {
                    if let Some(name) = interner.lookup(rest.trim()) {
                        return CTypeSpecs::Struct { name: Some(name), is_union: true };
                    }
                    return CTypeSpecs::Struct { name: None, is_union: true };
                }
                if let Some(rest) = s.strip_prefix("enum ") {
                    if let Some(name) = interner.lookup(rest.trim()) {
                        return CTypeSpecs::Enum { name: Some(name) };
                    }
                    return CTypeSpecs::Enum { name: None };
                }
                // typedef 名
                if let Some(name) = interner.lookup(s) {
                    CTypeSpecs::TypedefName(name)
                } else {
                    // 未知の型は typedef 名として扱う(文字列で保持できないので)
                    // この場合は interner に登録されていないため、後で解決する必要がある
                    CTypeSpecs::Void // フォールバック
                }
            }
        }
    }

    /// 後方互換: 文字列に変換(デバッグ用)
    pub fn to_display_string(&self, interner: &crate::intern::StringInterner) -> String {
        match self {
            TypeRepr::CType { specs, derived, .. } => {
                let base = specs.to_display_string(interner);
                let mut result = base;
                for d in derived {
                    match d {
                        CDerivedType::Pointer { is_const: true, .. } => result.push_str(" *const"),
                        CDerivedType::Pointer { .. } => result.push_str(" *"),
                        CDerivedType::Array { size: Some(n) } => {
                            result.push_str(&format!("[{}]", n));
                        }
                        CDerivedType::Array { size: None } => result.push_str("[]"),
                        CDerivedType::Function { .. } => result.push_str("()"),
                    }
                }
                result
            }
            TypeRepr::RustType { repr, .. } => repr.to_display_string(),
            TypeRepr::Inferred(inferred) => inferred.to_display_string(interner),
        }
    }

    /// Rust コード生成用の型文字列に変換
    pub fn to_rust_string(&self, interner: &crate::intern::StringInterner) -> String {
        match self {
            TypeRepr::CType { specs, derived, .. } => {
                let base = specs.to_rust_string(interner);
                // ポインタは逆順に適用(Rustの表記に合わせる)
                let mut result = base;
                for d in derived.iter().rev() {
                    // void ポインタの場合は c_void を使用
                    if result == "()" && matches!(d, CDerivedType::Pointer { .. } | CDerivedType::Array { .. }) {
                        result = "c_void".to_string();
                    }
                    result = match d {
                        CDerivedType::Pointer { is_const: true, .. } => format!("*const {}", result),
                        CDerivedType::Pointer { .. } => format!("*mut {}", result),
                        CDerivedType::Array { size: Some(n) } => format!("[{}; {}]", result, n),
                        CDerivedType::Array { size: None } => format!("*mut {}", result),
                        CDerivedType::Function { .. } => format!("/* fn */"),
                    };
                }
                result
            }
            TypeRepr::RustType { repr, .. } => repr.to_display_string(),
            TypeRepr::Inferred(inferred) => inferred.to_rust_string(interner),
        }
    }
}

// ============================================================================
// `UnifiedType` → `(CTypeSpecs, Vec<CDerivedType>)` 構造的変換
// ============================================================================

/// `UnifiedType` を C 型表現 (specs + derived) に分解する。
/// FnPtr / Verbatim / Unknown は C 表現に落とせないので `None` を返す。
fn unified_to_c(
    ut: &crate::unified_type::UnifiedType,
    interner: &crate::intern::StringInterner,
) -> Option<(CTypeSpecs, Vec<CDerivedType>)> {
    use crate::unified_type::{UnifiedType as UT, IntSize as UIS};

    match ut {
        UT::Void => Some((CTypeSpecs::Void, vec![])),
        UT::Bool => Some((CTypeSpecs::Bool, vec![])),
        UT::Char { signed } => Some((CTypeSpecs::Char { signed: *signed }, vec![])),
        UT::Int { signed, size } => {
            // UnifiedType::IntSize::Char は C の signed/unsigned char に倒す
            // (TypeRepr::IntSize には Char バリアントが無い)
            if matches!(size, UIS::Char) {
                return Some((CTypeSpecs::Char { signed: Some(*signed) }, vec![]));
            }
            let target = match size {
                UIS::Char => unreachable!(),
                UIS::Short => IntSize::Short,
                UIS::Int => IntSize::Int,
                UIS::Long => IntSize::Long,
                UIS::LongLong => IntSize::LongLong,
                UIS::Int128 => IntSize::Int128,
            };
            Some((CTypeSpecs::Int { signed: *signed, size: target }, vec![]))
        }
        UT::Float => Some((CTypeSpecs::Float, vec![])),
        UT::Double => Some((CTypeSpecs::Double { is_long: false }, vec![])),
        UT::LongDouble => Some((CTypeSpecs::Double { is_long: true }, vec![])),
        UT::Pointer { inner, is_const } => {
            let (specs, mut derived) = unified_to_c(inner, interner)?;
            // 最も外側の derived として Pointer を追加 (derived 配列は外→内順)
            derived.insert(
                0,
                CDerivedType::Pointer {
                    is_const: *is_const,
                    is_volatile: false,
                    is_restrict: false,
                },
            );
            Some((specs, derived))
        }
        UT::Array { inner, size } => {
            let (specs, mut derived) = unified_to_c(inner, interner)?;
            derived.insert(0, CDerivedType::Array { size: *size });
            Some((specs, derived))
        }
        UT::Named(name) => {
            let specs = match interner.lookup(name) {
                Some(id) => CTypeSpecs::TypedefName(id),
                None => CTypeSpecs::UnknownTypedef(name.clone()),
            };
            Some((specs, vec![]))
        }
        UT::FnPtr { .. } | UT::Verbatim(_) | UT::Unknown => None,
    }
}

// ============================================================================
// 型名抽出メソッド(文字列ラウンドトリップ廃止用)
// ============================================================================

impl TypeRepr {
    /// ポインタ型の参照先の構造体/typedef 名を InternedStr で取得
    ///
    /// PtrMember (->) の base 型から構造体名を抽出するために使用。
    /// 例: `*mut SV` → `Some(SV)`, `XPVHV *` → `Some(XPVHV)`
    pub fn pointee_name(&self) -> Option<InternedStr> {
        match self {
            TypeRepr::CType { specs, derived, .. } => {
                if derived.iter().any(|d| matches!(d, CDerivedType::Pointer { .. })) {
                    specs.type_name()
                } else {
                    None
                }
            }
            TypeRepr::RustType { repr, .. } => repr.pointee_name(),
            TypeRepr::Inferred(inferred) => inferred.resolved_type()?.pointee_name(),
        }
    }

    /// 非ポインタ型の構造体/typedef 名を InternedStr で取得
    ///
    /// Member (.) の base 型から構造体名を抽出するために使用。
    /// 例: `union _xhvnameu` → `Some(_xhvnameu)`, `SV` → `Some(SV)`
    pub fn type_name(&self) -> Option<InternedStr> {
        match self {
            TypeRepr::CType { specs, .. } => specs.type_name(),
            TypeRepr::RustType { repr, .. } => repr.type_name(),
            TypeRepr::Inferred(inferred) => inferred.resolved_type()?.type_name(),
        }
    }
}

impl CTypeSpecs {
    /// 構造体/typedef/enum 名を InternedStr で取得
    pub fn type_name(&self) -> Option<InternedStr> {
        match self {
            CTypeSpecs::Struct { name: Some(n), .. } => Some(*n),
            CTypeSpecs::TypedefName(n) => Some(*n),
            CTypeSpecs::Enum { name: Some(n) } => Some(*n),
            _ => None,
        }
    }
}

impl InferredType {
    /// Inferred ラッパーを解決して内側の TypeRepr を返す
    ///
    /// 各 InferredType バリアントが保持する「結果の型」を取得する。
    /// `pointee_name()` / `type_name()` から再帰的に呼ばれる。
    pub fn resolved_type(&self) -> Option<&TypeRepr> {
        match self {
            InferredType::Cast { target_type } => Some(target_type),
            InferredType::PtrMemberAccess { field_type: Some(ft), .. } => Some(ft),
            InferredType::MemberAccess { field_type: Some(ft), .. } => Some(ft),
            InferredType::ArraySubscript { element_type, .. } => Some(element_type),
            InferredType::AddressOf { inner_type } => Some(inner_type),
            InferredType::Dereference { pointer_type } => Some(pointer_type),
            InferredType::SymbolLookup { resolved_type, .. } => Some(resolved_type),
            InferredType::IncDec { inner_type } => Some(inner_type),
            InferredType::Assignment { lhs_type } => Some(lhs_type),
            InferredType::Comma { rhs_type } => Some(rhs_type),
            InferredType::Conditional { result_type, .. } => Some(result_type),
            InferredType::BinaryOp { result_type, .. } => Some(result_type),
            InferredType::UnaryArithmetic { inner_type } => Some(inner_type),
            InferredType::CompoundLiteral { type_name } => Some(type_name),
            InferredType::StmtExpr { last_expr_type } => last_expr_type.as_deref(),
            _ => None,
        }
    }
}

impl RustTypeRepr {
    /// ポインタ型の参照先の型名を InternedStr で取得
    ///
    /// RustTypeRepr は String ベースで型名を格納しているため、
    /// InternedStr の取得には interner が必要。当面は None を返す。
    fn pointee_name(&self) -> Option<InternedStr> {
        // RustTypeRepr は String ベースのため InternedStr を直接取得できない。
        // 将来的に RustTypeRepr 自体を InternedStr ベースに改修する際に対応する。
        None
    }

    /// 型名を InternedStr で取得
    fn type_name(&self) -> Option<InternedStr> {
        None
    }
}

// ============================================================================
// Display 実装
// ============================================================================

impl CTypeSpecs {
    /// 表示用文字列に変換
    pub fn to_display_string(&self, interner: &crate::intern::StringInterner) -> String {
        match self {
            CTypeSpecs::Void => "void".to_string(),
            CTypeSpecs::Char { signed: None } => "char".to_string(),
            CTypeSpecs::Char { signed: Some(true) } => "signed char".to_string(),
            CTypeSpecs::Char { signed: Some(false) } => "unsigned char".to_string(),
            CTypeSpecs::Int { signed: true, size: IntSize::Short } => "short".to_string(),
            CTypeSpecs::Int { signed: false, size: IntSize::Short } => "unsigned short".to_string(),
            CTypeSpecs::Int { signed: true, size: IntSize::Int } => "int".to_string(),
            CTypeSpecs::Int { signed: false, size: IntSize::Int } => "unsigned int".to_string(),
            CTypeSpecs::Int { signed: true, size: IntSize::Long } => "long".to_string(),
            CTypeSpecs::Int { signed: false, size: IntSize::Long } => "unsigned long".to_string(),
            CTypeSpecs::Int { signed: true, size: IntSize::LongLong } => "long long".to_string(),
            CTypeSpecs::Int { signed: false, size: IntSize::LongLong } => "unsigned long long".to_string(),
            CTypeSpecs::Int { signed: true, size: IntSize::Int128 } => "__int128".to_string(),
            CTypeSpecs::Int { signed: false, size: IntSize::Int128 } => "unsigned __int128".to_string(),
            CTypeSpecs::Float => "float".to_string(),
            CTypeSpecs::Double { is_long: false } => "double".to_string(),
            CTypeSpecs::Double { is_long: true } => "long double".to_string(),
            CTypeSpecs::Bool => "_Bool".to_string(),
            CTypeSpecs::Struct { name: Some(n), is_union: false } => {
                format!("struct {}", interner.get(*n))
            }
            CTypeSpecs::Struct { name: None, is_union: false } => "struct".to_string(),
            CTypeSpecs::Struct { name: Some(n), is_union: true } => {
                format!("union {}", interner.get(*n))
            }
            CTypeSpecs::Struct { name: None, is_union: true } => "union".to_string(),
            CTypeSpecs::Enum { name: Some(n) } => format!("enum {}", interner.get(*n)),
            CTypeSpecs::Enum { name: None } => "enum".to_string(),
            CTypeSpecs::TypedefName(n) => interner.get(*n).to_string(),
            CTypeSpecs::UnknownTypedef(s) => s.clone(),
        }
    }

    /// Rust コード生成用の型文字列に変換
    pub fn to_rust_string(&self, interner: &crate::intern::StringInterner) -> String {
        match self {
            CTypeSpecs::Void => "()".to_string(),
            CTypeSpecs::Char { signed: None } => "c_char".to_string(),
            CTypeSpecs::Char { signed: Some(true) } => "c_schar".to_string(),
            CTypeSpecs::Char { signed: Some(false) } => "c_uchar".to_string(),
            CTypeSpecs::Int { signed: true, size: IntSize::Short } => "c_short".to_string(),
            CTypeSpecs::Int { signed: false, size: IntSize::Short } => "c_ushort".to_string(),
            CTypeSpecs::Int { signed: true, size: IntSize::Int } => "c_int".to_string(),
            CTypeSpecs::Int { signed: false, size: IntSize::Int } => "c_uint".to_string(),
            CTypeSpecs::Int { signed: true, size: IntSize::Long } => "c_long".to_string(),
            CTypeSpecs::Int { signed: false, size: IntSize::Long } => "c_ulong".to_string(),
            CTypeSpecs::Int { signed: true, size: IntSize::LongLong } => "c_longlong".to_string(),
            CTypeSpecs::Int { signed: false, size: IntSize::LongLong } => "c_ulonglong".to_string(),
            CTypeSpecs::Int { signed: true, size: IntSize::Int128 } => "i128".to_string(),
            CTypeSpecs::Int { signed: false, size: IntSize::Int128 } => "u128".to_string(),
            CTypeSpecs::Float => "c_float".to_string(),
            CTypeSpecs::Double { is_long: false } => "c_double".to_string(),
            CTypeSpecs::Double { is_long: true } => "c_double".to_string(), // long double → c_double
            CTypeSpecs::Bool => "bool".to_string(),
            CTypeSpecs::Struct { name: Some(n), .. } => interner.get(*n).to_string(),
            CTypeSpecs::Struct { name: None, .. } => "/* anonymous struct */".to_string(),
            CTypeSpecs::Enum { name: Some(n) } => interner.get(*n).to_string(),
            CTypeSpecs::Enum { name: None } => "/* anonymous enum */".to_string(),
            CTypeSpecs::TypedefName(n) => interner.get(*n).to_string(),
            CTypeSpecs::UnknownTypedef(s) => s.clone(),
        }
    }
}

impl RustTypeRepr {
    /// 最外ポインタの is_const を true に変更する
    pub fn make_outer_pointer_const(&mut self) {
        if let RustTypeRepr::Pointer { is_const, .. } = self {
            *is_const = true;
        }
    }

    /// 最外ポインタを持つかどうか
    pub fn has_outer_pointer(&self) -> bool {
        matches!(self, RustTypeRepr::Pointer { .. })
    }
}

impl RustTypeRepr {
    /// 表示用文字列に変換
    pub fn to_display_string(&self) -> String {
        match self {
            RustTypeRepr::CPrimitive(kind) => kind.to_string(),
            RustTypeRepr::RustPrimitive(kind) => kind.to_string(),
            RustTypeRepr::Pointer { inner, is_const: true } => {
                format!("*const {}", inner.to_display_string())
            }
            RustTypeRepr::Pointer { inner, is_const: false } => {
                format!("*mut {}", inner.to_display_string())
            }
            RustTypeRepr::Reference { inner, is_mut: true } => {
                format!("&mut {}", inner.to_display_string())
            }
            RustTypeRepr::Reference { inner, is_mut: false } => {
                format!("&{}", inner.to_display_string())
            }
            RustTypeRepr::Named(name) => name.clone(),
            RustTypeRepr::Option(inner) => format!("Option<{}>", inner.to_display_string()),
            RustTypeRepr::FnPointer { params, ret } => {
                let params_str: Vec<_> = params.iter().map(|p| p.to_display_string()).collect();
                let ret_str = ret
                    .as_ref()
                    .map(|r| format!(" -> {}", r.to_display_string()))
                    .unwrap_or_default();
                format!("fn({}){}", params_str.join(", "), ret_str)
            }
            RustTypeRepr::Unit => "()".to_string(),
            RustTypeRepr::Unknown(s) => s.clone(),
        }
    }
}

impl fmt::Display for CPrimitiveKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            CPrimitiveKind::CChar => "c_char",
            CPrimitiveKind::CSchar => "c_schar",
            CPrimitiveKind::CUchar => "c_uchar",
            CPrimitiveKind::CShort => "c_short",
            CPrimitiveKind::CUshort => "c_ushort",
            CPrimitiveKind::CInt => "c_int",
            CPrimitiveKind::CUint => "c_uint",
            CPrimitiveKind::CLong => "c_long",
            CPrimitiveKind::CUlong => "c_ulong",
            CPrimitiveKind::CLongLong => "c_longlong",
            CPrimitiveKind::CUlongLong => "c_ulonglong",
            CPrimitiveKind::CFloat => "c_float",
            CPrimitiveKind::CDouble => "c_double",
        };
        write!(f, "{}", s)
    }
}

impl fmt::Display for RustPrimitiveKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            RustPrimitiveKind::I8 => "i8",
            RustPrimitiveKind::I16 => "i16",
            RustPrimitiveKind::I32 => "i32",
            RustPrimitiveKind::I64 => "i64",
            RustPrimitiveKind::I128 => "i128",
            RustPrimitiveKind::Isize => "isize",
            RustPrimitiveKind::U8 => "u8",
            RustPrimitiveKind::U16 => "u16",
            RustPrimitiveKind::U32 => "u32",
            RustPrimitiveKind::U64 => "u64",
            RustPrimitiveKind::U128 => "u128",
            RustPrimitiveKind::Usize => "usize",
            RustPrimitiveKind::F32 => "f32",
            RustPrimitiveKind::F64 => "f64",
            RustPrimitiveKind::Bool => "bool",
        };
        write!(f, "{}", s)
    }
}

impl InferredType {
    /// 表示用文字列に変換
    pub fn to_display_string(&self, interner: &crate::intern::StringInterner) -> String {
        match self {
            InferredType::IntLiteral => "int".to_string(),
            InferredType::UIntLiteral => "unsigned int".to_string(),
            InferredType::FloatLiteral => "double".to_string(),
            InferredType::CharLiteral => "int".to_string(),
            InferredType::StringLiteral => "char *".to_string(),
            InferredType::SymbolLookup { resolved_type, .. } => {
                resolved_type.to_display_string(interner)
            }
            InferredType::ThxDefault => "*mut PerlInterpreter".to_string(),
            InferredType::BinaryOp { result_type, .. } => result_type.to_display_string(interner),
            InferredType::UnaryArithmetic { inner_type } => inner_type.to_display_string(interner),
            InferredType::LogicalNot => "int".to_string(),
            InferredType::AddressOf { inner_type } => {
                format!("{} *", inner_type.to_display_string(interner))
            }
            InferredType::Dereference { pointer_type } => {
                let s = pointer_type.to_display_string(interner);
                s.trim_end_matches(" *").to_string()
            }
            InferredType::IncDec { inner_type } => inner_type.to_display_string(interner),
            InferredType::MemberAccess { field_type: Some(ft), .. } => {
                ft.to_display_string(interner)
            }
            InferredType::MemberAccess { base_type, member, .. } => {
                format!("{}.{}", base_type, interner.get(*member))
            }
            InferredType::PtrMemberAccess { field_type: Some(ft), .. } => {
                ft.to_display_string(interner)
            }
            InferredType::PtrMemberAccess { base_type, member, .. } => {
                format!("{}->{}", base_type, interner.get(*member))
            }
            InferredType::ArraySubscript { element_type, .. } => {
                element_type.to_display_string(interner)
            }
            InferredType::Conditional { result_type, .. } => {
                result_type.to_display_string(interner)
            }
            InferredType::Comma { rhs_type } => rhs_type.to_display_string(interner),
            InferredType::Assignment { lhs_type } => lhs_type.to_display_string(interner),
            InferredType::Cast { target_type } => target_type.to_display_string(interner),
            InferredType::Sizeof | InferredType::Alignof => "unsigned long".to_string(),
            InferredType::CompoundLiteral { type_name } => type_name.to_display_string(interner),
            InferredType::StmtExpr { last_expr_type: Some(t) } => t.to_display_string(interner),
            InferredType::StmtExpr { last_expr_type: None } => "void".to_string(),
            InferredType::Assert => "void".to_string(),
            InferredType::FunctionReturn { func_name } => {
                format!("{}()", interner.get(*func_name))
            }
        }
    }

    /// Rust コード生成用の型文字列に変換
    pub fn to_rust_string(&self, interner: &crate::intern::StringInterner) -> String {
        match self {
            InferredType::IntLiteral => "c_int".to_string(),
            InferredType::UIntLiteral => "c_uint".to_string(),
            InferredType::FloatLiteral => "c_double".to_string(),
            InferredType::CharLiteral => "c_int".to_string(),
            InferredType::StringLiteral => "*const c_char".to_string(),
            InferredType::SymbolLookup { resolved_type, .. } => {
                resolved_type.to_rust_string(interner)
            }
            InferredType::ThxDefault => "*mut PerlInterpreter".to_string(),
            InferredType::BinaryOp { result_type, .. } => result_type.to_rust_string(interner),
            InferredType::UnaryArithmetic { inner_type } => inner_type.to_rust_string(interner),
            InferredType::LogicalNot => "c_int".to_string(),
            InferredType::AddressOf { inner_type } => {
                format!("*mut {}", inner_type.to_rust_string(interner))
            }
            InferredType::Dereference { pointer_type } => {
                let s = pointer_type.to_rust_string(interner);
                // *mut T → T
                s.strip_prefix("*mut ").or_else(|| s.strip_prefix("*const "))
                    .unwrap_or(&s).to_string()
            }
            InferredType::IncDec { inner_type } => inner_type.to_rust_string(interner),
            InferredType::MemberAccess { field_type: Some(ft), .. } => {
                ft.to_rust_string(interner)
            }
            InferredType::MemberAccess { base_type, member, .. } => {
                format!("/* {}.{} */", base_type, interner.get(*member))
            }
            InferredType::PtrMemberAccess { field_type: Some(ft), .. } => {
                ft.to_rust_string(interner)
            }
            InferredType::PtrMemberAccess { base_type, member, .. } => {
                format!("/* {}->{} */", base_type, interner.get(*member))
            }
            InferredType::ArraySubscript { element_type, .. } => {
                element_type.to_rust_string(interner)
            }
            InferredType::Conditional { result_type, .. } => {
                result_type.to_rust_string(interner)
            }
            InferredType::Comma { rhs_type } => rhs_type.to_rust_string(interner),
            InferredType::Assignment { lhs_type } => lhs_type.to_rust_string(interner),
            InferredType::Cast { target_type } => target_type.to_rust_string(interner),
            InferredType::Sizeof | InferredType::Alignof => "c_ulong".to_string(),
            InferredType::CompoundLiteral { type_name } => type_name.to_rust_string(interner),
            InferredType::StmtExpr { last_expr_type: Some(t) } => t.to_rust_string(interner),
            InferredType::StmtExpr { last_expr_type: None } => "()".to_string(),
            InferredType::Assert => "()".to_string(),
            InferredType::FunctionReturn { func_name } => {
                format!("/* {}() ret */", interner.get(*func_name))
            }
        }
    }
}

// ============================================================================
// テスト
// ============================================================================

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

    #[test]
    fn test_rust_type_repr_from_string() {
        assert!(matches!(
            RustTypeRepr::from_type_string("c_int"),
            RustTypeRepr::CPrimitive(CPrimitiveKind::CInt)
        ));

        assert!(matches!(
            RustTypeRepr::from_type_string("i32"),
            RustTypeRepr::RustPrimitive(RustPrimitiveKind::I32)
        ));

        assert!(matches!(
            RustTypeRepr::from_type_string("()"),
            RustTypeRepr::Unit
        ));

        if let RustTypeRepr::Pointer { inner, is_const: false } =
            RustTypeRepr::from_type_string("*mut SV")
        {
            assert!(matches!(*inner, RustTypeRepr::Named(ref n) if n == "SV"));
        } else {
            panic!("Expected *mut SV");
        }

        if let RustTypeRepr::Pointer { inner, is_const: true } =
            RustTypeRepr::from_type_string("*const c_char")
        {
            assert!(matches!(*inner, RustTypeRepr::CPrimitive(CPrimitiveKind::CChar)));
        } else {
            panic!("Expected *const c_char");
        }
    }

    #[test]
    fn test_rust_type_repr_from_string_with_spaces() {
        // syn の出力形式(スペースあり)
        if let RustTypeRepr::Pointer { inner, is_const: false } =
            RustTypeRepr::from_type_string("* mut SV")
        {
            assert!(matches!(*inner, RustTypeRepr::Named(ref n) if n == "SV"));
        } else {
            panic!("Expected * mut SV");
        }
    }

    #[test]
    fn test_c_primitive_display() {
        assert_eq!(CPrimitiveKind::CInt.to_string(), "c_int");
        assert_eq!(CPrimitiveKind::CUlong.to_string(), "c_ulong");
    }

    #[test]
    fn test_rust_primitive_display() {
        assert_eq!(RustPrimitiveKind::I32.to_string(), "i32");
        assert_eq!(RustPrimitiveKind::Usize.to_string(), "usize");
    }

    // === Stage 5: 構造的 pointer 判定 (`is_pointer_type` / `is_void_pointer`) ===

    fn make_void_ptr() -> TypeRepr {
        TypeRepr::CType {
            specs: CTypeSpecs::Void,
            derived: vec![CDerivedType::Pointer {
                is_const: false,
                is_volatile: false,
                is_restrict: false,
            }],
            source: CTypeSource::Apidoc { raw: "void *".to_string() },
        }
    }

    fn make_concrete_ptr() -> TypeRepr {
        TypeRepr::CType {
            specs: CTypeSpecs::Char { signed: None },
            derived: vec![CDerivedType::Pointer {
                is_const: false,
                is_volatile: false,
                is_restrict: false,
            }],
            source: CTypeSource::Apidoc { raw: "char *".to_string() },
        }
    }

    #[test]
    fn test_void_pointer_structural() {
        let vp = make_void_ptr();
        assert!(vp.is_pointer_type());
        assert!(vp.is_void_pointer());
        assert!(!vp.is_concrete_pointer());
    }

    #[test]
    fn test_concrete_pointer_structural() {
        let cp = make_concrete_ptr();
        assert!(cp.is_pointer_type());
        assert!(!cp.is_void_pointer());
        assert!(cp.is_concrete_pointer());
    }

    #[test]
    fn test_inferred_member_access_pointer_recursive() {
        // bindings.rs 経由で MemberAccess の field_type が `*mut c_char` のとき、
        // `is_pointer_type` は Inferred を再帰参照して true を返すべき。
        // (Stage 4 までの `has_outer_pointer` は false を返してしまう)
        let inner = make_concrete_ptr();
        let inferred = TypeRepr::Inferred(InferredType::MemberAccess {
            base_type: "xpvcv".to_string(),
            member: crate::intern::StringInterner::new().intern("foo"),
            field_type: Some(Box::new(inner)),
        });
        assert!(inferred.is_pointer_type());
        assert!(!inferred.is_void_pointer());
        assert!(inferred.is_concrete_pointer());
        // 一方、has_outer_pointer は既存挙動 (Inferred → false) を維持
        assert!(!inferred.has_outer_pointer());
    }
}