ruchy 4.1.2

A systems scripting language that transpiles to idiomatic Rust with extreme quality engineering
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
//! Type transpilation and struct/trait definitions
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::wildcard_imports)]
#![allow(clippy::collapsible_else_if)]
#![allow(clippy::only_used_in_recursion)]
use super::*;
use crate::frontend::ast::{
    ClassMethod, Constructor, EnumVariant, ImplMethod, StructField, TraitMethod, Type, TypeKind,
};
use anyhow::{bail, Result};
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::Lifetime;
impl Transpiler {
    /// Transpiles type annotations
    ///
    /// # Examples
    ///
    /// ```
    /// use ruchy::{Transpiler, Parser};
    ///
    /// // Basic types
    /// let mut transpiler = Transpiler::new();
    /// let mut parser = Parser::new("let x: i32 = 42");
    /// let ast = parser.parse().expect("Failed to parse");
    ///
    /// let result = transpiler.transpile(&ast).expect("operation should succeed in test");
    /// let code = result.to_string();
    /// assert!(code.contains("i32"));
    /// assert!(code.contains("42"));
    /// ```
    ///
    /// ```
    /// use ruchy::{Transpiler, Parser};
    ///
    /// // Generic types
    /// let mut transpiler = Transpiler::new();
    /// let mut parser = Parser::new("let v = [1, 2, 3]");
    /// let ast = parser.parse().expect("operation should succeed in test");
    ///
    /// let result = transpiler.transpile(&ast).expect("operation should succeed in test");
    /// // Basic transpilation test - just check it compiles
    /// assert!(!result.to_string().is_empty());
    /// ```
    ///
    /// ```
    /// use ruchy::{Transpiler, Parser};
    ///
    /// // Optional types
    /// let mut transpiler = Transpiler::new();
    /// let mut parser = Parser::new("let opt = Some(42)");
    /// let ast = parser.parse().expect("operation should succeed in test");
    ///
    /// let result = transpiler.transpile(&ast).expect("operation should succeed in test");
    /// let code = result.to_string();
    /// assert!(code.contains("Some"));
    /// ```
    pub fn transpile_type(&self, ty: &Type) -> Result<TokenStream> {
        use crate::frontend::ast::TypeKind;
        match &ty.kind {
            TypeKind::Named(name) => self.transpile_named_type(name),
            TypeKind::Generic { base, params } => self.transpile_generic_type(base, params),
            TypeKind::Optional(inner) => self.transpile_optional_type(inner),
            TypeKind::List(elem_type) => self.transpile_list_type(elem_type),
            TypeKind::Array { elem_type, size } => self.transpile_array_type(elem_type, *size),
            TypeKind::Tuple(types) => self.transpile_tuple_type(types),
            TypeKind::Function { params, ret } => self.transpile_function_type(params, ret),
            TypeKind::DataFrame { .. } => Ok(quote! { polars::prelude::DataFrame }),
            TypeKind::Series { .. } => Ok(quote! { polars::prelude::Series }),
            TypeKind::Reference {
                is_mut,
                lifetime,
                inner,
            } => self.transpile_reference_type(*is_mut, lifetime.as_deref(), inner),
            // SPEC-001-H: Refined types - transpile base type only, ignore constraint
            // Rust's type system doesn't support runtime refinement checking
            // The constraint is a compile-time annotation in Ruchy
            TypeKind::Refined { base, .. } => self.transpile_type(base),
        }
    }
    /// Transpile named types with built-in type mapping
    pub(crate) fn transpile_named_type(&self, name: &str) -> Result<TokenStream> {
        let rust_type = match name {
            "int" => quote! { i64 },
            "float" => quote! { f64 },
            "bool" => quote! { bool },
            "str" => quote! { &str }, // String slice reference (sized type for function parameters)
            "string" | "String" => quote! { String },
            "char" => quote! { char },
            "()" => quote! { () },       // Unit type
            "_" | "Any" => quote! { _ }, // Use Rust type inference
            "Object" => quote! { std::collections::BTreeMap<String, String> }, // TRANSPILER-013 FIX: Use String for standalone rustc compatibility
            _ => {
                // TRANSPILER-DEFECT-005: Handle namespaced types (e.g., trace::Sampler, std::io::Error)
                if name.contains("::") {
                    // Split into path segments and build path token
                    let segments: Vec<_> = name
                        .split("::")
                        .map(|seg| format_ident!("{}", seg))
                        .collect();
                    quote! { #(#segments)::* }
                } else {
                    // Simple identifier
                    let type_ident = format_ident!("{}", name);
                    quote! { #type_ident }
                }
            }
        };
        Ok(rust_type)
    }
    /// Transpile generic types with type parameters
    /// BOOK-COMPAT-007: Auto-box recursive types in Option (e.g., Option<Node> -> Option<Box<Node>>)
    pub(crate) fn transpile_generic_type(
        &self,
        base: &str,
        params: &[Type],
    ) -> Result<TokenStream> {
        use crate::frontend::ast::TypeKind;

        // BOOK-COMPAT-007: Special handling for Option<RecursiveType> pattern
        if base == "Option" && params.len() == 1 {
            if let TypeKind::Named(inner_name) = &params[0].kind {
                let current_struct = self.current_struct_name.borrow();
                let is_recursive = current_struct.as_ref().is_some_and(|c| c == inner_name);

                if is_recursive {
                    // BOOK-COMPAT-007B: Record this field as auto-boxed for struct literal handling
                    // Note: We need access to the field name, which comes from the caller context
                    // For now, we'll record by struct name and inner type
                    if let Some(struct_name) = current_struct.as_ref() {
                        // Store in auto_boxed_fields - key is (struct_name, inner_type)
                        // This will be used during struct literal transpilation
                        self.auto_boxed_fields.borrow_mut().insert(
                            (struct_name.clone(), inner_name.clone()),
                            inner_name.clone(),
                        );
                    }
                    drop(current_struct); // Release borrow before returning
                    let inner_ident = format_ident!("{}", inner_name);
                    return Ok(quote! { Option<Box<#inner_ident>> });
                }
            }
        }

        let base_ident = format_ident!("{}", base);
        let param_tokens: Result<Vec<_>> = params.iter().map(|p| self.transpile_type(p)).collect();
        let param_tokens = param_tokens?;
        Ok(quote! { #base_ident<#(#param_tokens),*> })
    }
    /// Transpile optional types to Option<T>
    /// BOOK-COMPAT-007: Auto-box recursive types (e.g., Option<Node> -> Option<Box<Node>>)
    pub(crate) fn transpile_optional_type(&self, inner: &Type) -> Result<TokenStream> {
        use crate::frontend::ast::TypeKind;

        // Check if this is a recursive type reference
        let is_recursive = if let TypeKind::Named(name) = &inner.kind {
            self.current_struct_name
                .borrow()
                .as_ref()
                .is_some_and(|current| current == name)
        } else {
            false
        };

        let inner_tokens = self.transpile_type(inner)?;

        if is_recursive {
            // BOOK-COMPAT-007: Wrap recursive type in Box to break infinite size
            Ok(quote! { Option<Box<#inner_tokens>> })
        } else {
            Ok(quote! { Option<#inner_tokens> })
        }
    }
    /// Transpile list types to Vec<T>
    pub(crate) fn transpile_list_type(&self, elem_type: &Type) -> Result<TokenStream> {
        let elem_tokens = self.transpile_type(elem_type)?;
        Ok(quote! { Vec<#elem_tokens> })
    }
    /// Transpile array types with fixed size
    pub(crate) fn transpile_array_type(
        &self,
        elem_type: &Type,
        size: usize,
    ) -> Result<TokenStream> {
        let elem_tokens = self.transpile_type(elem_type)?;
        let size_lit = proc_macro2::Literal::usize_unsuffixed(size);
        Ok(quote! { [#elem_tokens; #size_lit] })
    }
    /// Transpile tuple types
    pub(crate) fn transpile_tuple_type(&self, types: &[Type]) -> Result<TokenStream> {
        let type_tokens: Result<Vec<_>> = types.iter().map(|t| self.transpile_type(t)).collect();
        let type_tokens = type_tokens?;
        Ok(quote! { (#(#type_tokens),*) })
    }
    /// Transpile function types
    pub(crate) fn transpile_function_type(
        &self,
        params: &[Type],
        ret: &Type,
    ) -> Result<TokenStream> {
        let param_tokens: Result<Vec<_>> = params.iter().map(|p| self.transpile_type(p)).collect();
        let param_tokens = param_tokens?;
        let ret_tokens = self.transpile_type(ret)?;
        Ok(quote! { fn(#(#param_tokens),*) -> #ret_tokens })
    }
    /// Transpile reference types with special handling for &str and lifetimes
    pub(crate) fn transpile_reference_type(
        &self,
        is_mut: bool,
        lifetime: Option<&str>,
        inner: &Type,
    ) -> Result<TokenStream> {
        use crate::frontend::ast::TypeKind;

        // Create lifetime token if provided
        let lifetime_token = if let Some(lt) = lifetime {
            let lifetime = Lifetime::new(lt, proc_macro2::Span::call_site());
            quote! { #lifetime }
        } else {
            quote! {}
        };

        // Special case: &str should not become &&str
        if let TypeKind::Named(name) = &inner.kind {
            if name == "str" {
                return if is_mut {
                    Ok(quote! { &#lifetime_token mut str })
                } else {
                    Ok(quote! { &#lifetime_token str })
                };
            }
        }
        let inner_tokens = self.transpile_type(inner)?;
        if is_mut {
            Ok(quote! { &#lifetime_token mut #inner_tokens })
        } else {
            Ok(quote! { &#lifetime_token #inner_tokens })
        }
    }
    /// Transpiles tuple struct definitions
    pub fn transpile_tuple_struct(
        &self,
        name: &str,
        type_params: &[String],
        fields: &[Type],
        derives: &[String],
        is_pub: bool,
    ) -> Result<TokenStream> {
        let struct_name = format_ident!("{}", name);
        let type_param_tokens: Vec<TokenStream> = type_params
            .iter()
            .map(|p| Self::parse_type_param_to_tokens(p))
            .collect();

        // Convert field types to tokens
        let field_tokens: Vec<TokenStream> = fields
            .iter()
            .map(|ty| self.transpile_type(ty).unwrap_or_else(|_| quote! { _ }))
            .collect();

        let visibility = if is_pub {
            quote! { pub }
        } else {
            quote! {}
        };

        // DEFECT-014: Auto-add Clone to derives for Vec indexing support
        let mut extended_derives = derives.to_vec();
        if !extended_derives.contains(&"Clone".to_string()) {
            extended_derives.push("Clone".to_string());
        }

        // Generate derive attributes using helper (PARSER-077 fix)
        let derive_attrs = self.generate_derive_attributes(&extended_derives);

        // Generate tuple struct definition
        let struct_def = if type_params.is_empty() {
            quote! {
                #derive_attrs
                #visibility struct #struct_name(#(pub #field_tokens),*);
            }
        } else {
            quote! {
                #derive_attrs
                #visibility struct #struct_name<#(#type_param_tokens),*>(#(pub #field_tokens),*);
            }
        };

        Ok(struct_def)
    }

    /// Helper: Check if any field has a reference type (for lifetime detection)
    /// Complexity: 2 (simple iteration + match)
    pub(crate) fn has_reference_fields(&self, fields: &[StructField]) -> bool {
        use crate::frontend::ast::TypeKind;
        fields
            .iter()
            .any(|field| matches!(field.ty.kind, TypeKind::Reference { .. }))
    }

    /// Helper: Check if type params already contain a lifetime
    /// Complexity: 1 (simple predicate)
    pub(crate) fn has_lifetime_params(&self, type_params: &[String]) -> bool {
        type_params.iter().any(|p| p.starts_with('\''))
    }

    /// DEFECT-021 FIX: Parse type parameter string to `TokenStream`
    /// Handles both simple params ("T") and params with bounds ("T: Clone + Debug")
    pub(crate) fn parse_type_param_to_tokens(p: &str) -> TokenStream {
        if p.starts_with('\'') {
            // Lifetime parameter
            let lifetime = Lifetime::new(p, proc_macro2::Span::call_site());
            quote! { #lifetime }
        } else if p.contains(':') {
            // Type parameter with trait bounds (e.g., "T: Clone + Debug")
            syn::parse_str::<syn::TypeParam>(p).map_or_else(
                |_| {
                    // Fallback: just use the name part
                    let name = p.split(':').next().unwrap_or(p).trim();
                    let ident = format_ident!("{}", name);
                    quote! { #ident }
                },
                |tp| quote! { #tp },
            )
        } else {
            // Simple type parameter
            let ident = format_ident!("{}", p);
            quote! { #ident }
        }
    }

    /// Helper: Transpile type with explicit lifetime annotation for struct fields
    /// Complexity: 3 (type matching + recursive call)
    pub(crate) fn transpile_struct_field_type_with_lifetime(
        &self,
        ty: &Type,
        lifetime: &str,
    ) -> Result<TokenStream> {
        use crate::frontend::ast::TypeKind;
        match &ty.kind {
            TypeKind::Reference { is_mut, inner, .. } => {
                // Override lifetime for references
                self.transpile_reference_type(*is_mut, Some(lifetime), inner)
            }
            _ => {
                // For non-reference types, use regular transpilation
                self.transpile_type(ty)
            }
        }
    }

    /// Transpiles struct definitions
    pub fn transpile_struct(
        &self,
        name: &str,
        type_params: &[String],
        fields: &[StructField],
        derives: &[String],
        is_pub: bool,
    ) -> Result<TokenStream> {
        self.transpile_struct_with_methods(name, type_params, fields, &[], derives, is_pub)
    }

    pub fn transpile_struct_with_methods(
        &self,
        name: &str,
        type_params: &[String],
        fields: &[StructField],
        methods: &[ClassMethod],
        derives: &[String],
        is_pub: bool,
    ) -> Result<TokenStream> {
        // BOOK-COMPAT-007: Track current struct name for recursive type detection
        *self.current_struct_name.borrow_mut() = Some(name.to_string());

        let struct_name = format_ident!("{}", name);

        // BOOK-COMPAT-001: Auto-add lifetime parameter if struct has reference fields
        let needs_lifetime =
            self.has_reference_fields(fields) && !self.has_lifetime_params(type_params);
        let effective_type_params: Vec<String> = if needs_lifetime {
            let mut params = vec!["'a".to_string()];
            params.extend_from_slice(type_params);
            params
        } else {
            type_params.to_vec()
        };

        let type_param_tokens: Vec<TokenStream> = effective_type_params
            .iter()
            .map(|p| Self::parse_type_param_to_tokens(p))
            .collect();
        let field_tokens: Vec<TokenStream> = fields
            .iter()
            .map(|field| {
                let field_name = format_ident!("{}", field.name);

                // BOOK-COMPAT-001: Add lifetime to reference types if needed
                let field_type = if needs_lifetime {
                    self.transpile_struct_field_type_with_lifetime(&field.ty, "'a")
                        .unwrap_or_else(|_| quote! { _ })
                } else {
                    self.transpile_type(&field.ty)
                        .unwrap_or_else(|_| quote! { _ })
                };

                use crate::frontend::ast::Visibility;
                match &field.visibility {
                    Visibility::Public => quote! { pub #field_name: #field_type },
                    Visibility::PubCrate => quote! { pub(crate) #field_name: #field_type },
                    Visibility::PubSuper => quote! { pub(super) #field_name: #field_type },
                    Visibility::Private | Visibility::Protected => {
                        quote! { #field_name: #field_type }
                    }
                }
            })
            .collect();
        let visibility = if is_pub {
            quote! { pub }
        } else {
            quote! {}
        };

        // DEFECT-014: Auto-add Clone to derives for Vec indexing support
        let mut extended_derives = derives.to_vec();
        if !extended_derives.contains(&"Clone".to_string()) {
            extended_derives.push("Clone".to_string());
        }

        // Generate derive attributes using helper (PARSER-077 fix)
        let derive_attrs = self.generate_derive_attributes(&extended_derives);

        // BOOK-COMPAT-002: Store struct field types for proper string literal conversion
        // When transpiling struct literals, we need to know if a field is String type
        // to add .to_string() for string literal values
        {
            use crate::frontend::ast::TypeKind;
            let mut field_types = self.struct_field_types.borrow_mut();
            for field in fields {
                // Extract type name from TypeKind::Named
                let type_name = match &field.ty.kind {
                    TypeKind::Named(n) => n.clone(),
                    _ => format!("{:?}", field.ty.kind), // Fallback for complex types
                };
                field_types.insert((name.to_string(), field.name.clone()), type_name);
            }
        }

        // Generate struct definition
        let struct_def = if effective_type_params.is_empty() {
            quote! {
                #derive_attrs
                #visibility struct #struct_name {
                    #(#field_tokens,)*
                }
            }
        } else {
            quote! {
                #derive_attrs
                #visibility struct #struct_name<#(#type_param_tokens),*> {
                    #(#field_tokens,)*
                }
            }
        };

        // Check if any fields have default values
        let has_defaults = fields.iter().any(|f| f.default_value.is_some());

        // Generate Default impl if there are default values
        if has_defaults {
            use crate::frontend::ast::{ExprKind, Literal};
            let default_field_tokens: Result<Vec<_>> = fields
                .iter()
                .map(|field| -> Result<TokenStream> {
                    let field_name = format_ident!("{}", field.name);
                    if let Some(ref default_expr) = field.default_value {
                        let default_value = self.transpile_expr(default_expr)?;
                        // BOOK-COMPAT-004: Add .to_string() for String fields with string literal defaults
                        let is_string_field =
                            matches!(&field.ty.kind, TypeKind::Named(n) if n == "String");
                        let is_string_literal =
                            matches!(&default_expr.kind, ExprKind::Literal(Literal::String(_)));
                        if is_string_field && is_string_literal {
                            Ok(quote! { #field_name: #default_value.to_string() })
                        } else {
                            Ok(quote! { #field_name: #default_value })
                        }
                    } else {
                        Ok(quote! { #field_name: Default::default() })
                    }
                })
                .collect();
            let default_field_tokens = default_field_tokens?;

            let default_impl = if type_params.is_empty() {
                quote! {
                    impl Default for #struct_name {
                        fn default() -> Self {
                            Self {
                                #(#default_field_tokens,)*
                            }
                        }
                    }
                }
            } else {
                // For generic structs, we need to add Default bounds
                let where_clause_tokens: Vec<_> = type_params
                    .iter()
                    .map(|p| {
                        let param_ident = format_ident!("{}", p);
                        quote! { #param_ident: Default }
                    })
                    .collect();

                quote! {
                    impl<#(#type_param_tokens),*> Default for #struct_name<#(#type_param_tokens),*>
                    where
                        #(#where_clause_tokens),*
                    {
                        fn default() -> Self {
                            Self {
                                #(#default_field_tokens,)*
                            }
                        }
                    }
                }
            };

            if methods.is_empty() {
                Ok(quote! {
                    #struct_def

                    #default_impl
                })
            } else {
                let method_tokens = self.transpile_class_methods(methods)?;
                let type_param_tokens = self.generate_class_type_param_tokens(type_params);
                let impl_block = if type_param_tokens.is_empty() {
                    quote! {
                        impl #struct_name {
                            #(#method_tokens)*
                        }
                    }
                } else {
                    quote! {
                        impl<#(#type_param_tokens),*> #struct_name<#(#type_param_tokens),*> {
                            #(#method_tokens)*
                        }
                    }
                };
                Ok(quote! {
                    #struct_def

                    #default_impl

                    #impl_block
                })
            }
        } else {
            if methods.is_empty() {
                Ok(struct_def)
            } else {
                let method_tokens = self.transpile_class_methods(methods)?;
                let type_param_tokens = self.generate_class_type_param_tokens(type_params);
                let impl_block = if type_param_tokens.is_empty() {
                    quote! {
                        impl #struct_name {
                            #(#method_tokens)*
                        }
                    }
                } else {
                    quote! {
                        impl<#(#type_param_tokens),*> #struct_name<#(#type_param_tokens),*> {
                            #(#method_tokens)*
                        }
                    }
                };
                Ok(quote! {
                    #struct_def

                    #impl_block
                })
            }
        }
    }

    /// Transpiles class definitions to struct + impl blocks following Ruchy class sugar specification
    /// Transpile class to struct with impl blocks
    /// Complexity: 5 (within Toyota Way limits)
    pub fn transpile_class(
        &self,
        name: &str,
        type_params: &[String],
        _traits: &[String],
        fields: &[StructField],
        constructors: &[Constructor],
        methods: &[ClassMethod],
        constants: &[crate::frontend::ast::ClassConstant],
        derives: &[String],
        is_pub: bool,
    ) -> Result<TokenStream> {
        let struct_tokens = self.transpile_struct(name, type_params, fields, derives, is_pub)?;
        let type_param_tokens = self.generate_class_type_param_tokens(type_params);
        let struct_name = format_ident!("{}", name);

        let constructor_tokens = self.transpile_constructors(constructors)?;
        let method_tokens = self.transpile_class_methods(methods)?;
        let constant_tokens = self.transpile_class_constants(constants)?;

        let impl_tokens = self.generate_impl_block(
            &struct_name,
            &type_param_tokens,
            &constant_tokens,
            &constructor_tokens,
            &method_tokens,
        );

        let default_impl = self.generate_default_impl(fields, &struct_name, &type_param_tokens)?;

        Ok(quote! {
            #struct_tokens
            #impl_tokens
            #default_impl
        })
    }

    /// Generate derive attributes
    /// Complexity: 1 (within Toyota Way limits)
    pub(crate) fn generate_derive_attributes(&self, derives: &[String]) -> TokenStream {
        if derives.is_empty() {
            quote! {}
        } else {
            let derive_idents: Vec<_> = derives.iter().map(|d| format_ident!("{}", d)).collect();
            quote! { #[derive(#(#derive_idents),*)] }
        }
    }

    /// Generate type parameter tokens for classes
    /// Complexity: 2 (within Toyota Way limits)
    pub(crate) fn generate_class_type_param_tokens(
        &self,
        type_params: &[String],
    ) -> Vec<TokenStream> {
        type_params
            .iter()
            .map(|p| {
                if p.starts_with('\'') {
                    let lifetime = Lifetime::new(p, proc_macro2::Span::call_site());
                    quote! { #lifetime }
                } else {
                    let ident = format_ident!("{}", p);
                    quote! { #ident }
                }
            })
            .collect()
    }

    /// BOOK-COMPAT-010: Transform constructor body with self.field = value patterns
    /// into proper struct initialization: Self { field: value, ... }
    fn transpile_constructor_body(&self, body: &Expr) -> Result<TokenStream> {
        use crate::frontend::ast::ExprKind;

        // Extract self-assignments from block body
        if let ExprKind::Block(exprs) = &body.kind {
            let mut field_inits: Vec<(String, TokenStream)> = Vec::new();

            for expr in exprs {
                if let ExprKind::Assign { target, value } = &expr.kind {
                    // Check if target is self.field
                    if let ExprKind::FieldAccess { object, field } = &target.kind {
                        if let ExprKind::Identifier(name) = &object.kind {
                            if name == "self" {
                                let value_tokens = self.transpile_expr(value)?;
                                field_inits.push((field.clone(), value_tokens));
                                continue;
                            }
                        }
                    }
                }
                // Non-self-assignment in constructor - fall back to regular transpilation
                return self.transpile_expr(body);
            }

            // Generate Self { field1: value1, field2: value2, ... }
            if !field_inits.is_empty() {
                let fields: Vec<TokenStream> = field_inits
                    .into_iter()
                    .map(|(name, value)| {
                        let field_ident = format_ident!("{}", name);
                        quote! { #field_ident: #value }
                    })
                    .collect();
                return Ok(quote! { Self { #(#fields),* } });
            }
        }

        // Single self-assignment expression
        if let ExprKind::Assign { target, value } = &body.kind {
            if let ExprKind::FieldAccess { object, field } = &target.kind {
                if let ExprKind::Identifier(name) = &object.kind {
                    if name == "self" {
                        let field_ident = format_ident!("{}", field);
                        let value_tokens = self.transpile_expr(value)?;
                        return Ok(quote! { Self { #field_ident: #value_tokens } });
                    }
                }
            }
        }

        // Default: transpile as regular expression
        self.transpile_expr(body)
    }

    /// Transpile constructors to methods
    /// Complexity: 6 (within Toyota Way limits)
    pub(crate) fn transpile_constructors(
        &self,
        constructors: &[Constructor],
    ) -> Result<Vec<TokenStream>> {
        constructors
            .iter()
            .map(|ctor| {
                let params = self.transpile_params(&ctor.params)?;
                // BOOK-COMPAT-010: Use special constructor body transpilation
                let body = self.transpile_constructor_body(&ctor.body)?;
                let visibility = if ctor.is_pub {
                    quote! { pub }
                } else {
                    quote! {}
                };
                let method_name = ctor
                    .name
                    .as_ref()
                    .map_or_else(|| format_ident!("new"), |n| format_ident!("{}", n));
                let return_type = if let Some(ref ret_ty) = ctor.return_type {
                    let ret_tokens = self.transpile_type(ret_ty)?;
                    quote! { -> #ret_tokens }
                } else {
                    quote! { -> Self }
                };

                Ok(quote! {
                    #visibility fn #method_name(#(#params),*) #return_type {
                        #body
                    }
                })
            })
            .collect()
    }

    /// Transpile class methods
    /// Complexity: 5 (within Toyota Way limits)
    pub(crate) fn transpile_class_methods(
        &self,
        methods: &[ClassMethod],
    ) -> Result<Vec<TokenStream>> {
        methods
            .iter()
            .map(|method| {
                let method_name = format_ident!("{}", method.name);
                let params = self.transpile_params(&method.params)?;
                let return_type = if let Some(ref ret_ty) = method.return_type {
                    let ret_tokens = self.transpile_type(ret_ty)?;
                    quote! { -> #ret_tokens }
                } else {
                    quote! {}
                };
                let body = self.transpile_expr(&method.body)?;
                let visibility = if method.is_pub {
                    quote! { pub }
                } else {
                    quote! {}
                };

                Ok(quote! {
                    #visibility fn #method_name(#(#params),*) #return_type {
                        #body
                    }
                })
            })
            .collect()
    }

    /// Transpile class constants
    /// Complexity: 3 (within Toyota Way limits)
    pub(crate) fn transpile_class_constants(
        &self,
        constants: &[crate::frontend::ast::ClassConstant],
    ) -> Result<Vec<TokenStream>> {
        constants
            .iter()
            .map(|constant| {
                let const_name = format_ident!("{}", constant.name);
                let const_type = self.transpile_type(&constant.ty)?;
                let const_value = self.transpile_expr(&constant.value)?;
                let visibility = if constant.is_pub {
                    quote! { pub }
                } else {
                    quote! {}
                };

                Ok(quote! {
                    #visibility const #const_name: #const_type = #const_value;
                })
            })
            .collect()
    }

    /// Generate impl block
    /// Complexity: 1 (within Toyota Way limits)
    pub(crate) fn generate_impl_block(
        &self,
        struct_name: &proc_macro2::Ident,
        type_param_tokens: &[TokenStream],
        constant_tokens: &[TokenStream],
        constructor_tokens: &[TokenStream],
        method_tokens: &[TokenStream],
    ) -> TokenStream {
        if type_param_tokens.is_empty() {
            quote! {
                impl #struct_name {
                    #(#constant_tokens)*
                    #(#constructor_tokens)*
                    #(#method_tokens)*
                }
            }
        } else {
            quote! {
                impl<#(#type_param_tokens),*> #struct_name<#(#type_param_tokens),*> {
                    #(#constant_tokens)*
                    #(#constructor_tokens)*
                    #(#method_tokens)*
                }
            }
        }
    }

    /// Generate Default impl if needed
    /// Complexity: 4 (within Toyota Way limits)
    pub(crate) fn generate_default_impl(
        &self,
        fields: &[StructField],
        struct_name: &proc_macro2::Ident,
        type_param_tokens: &[TokenStream],
    ) -> Result<TokenStream> {
        let has_defaults = fields.iter().any(|f| f.default_value.is_some());
        if !has_defaults {
            return Ok(quote! {});
        }

        let default_field_tokens: Result<Vec<_>> = fields
            .iter()
            .map(|field| {
                let field_name = format_ident!("{}", field.name);
                if let Some(ref default_expr) = field.default_value {
                    let default_value = self.transpile_expr(default_expr)?;
                    Ok(quote! { #field_name: #default_value })
                } else {
                    Ok(quote! { #field_name: Default::default() })
                }
            })
            .collect();
        let default_field_tokens = default_field_tokens?;

        Ok(if type_param_tokens.is_empty() {
            quote! {
                impl Default for #struct_name {
                    fn default() -> Self {
                        Self {
                            #(#default_field_tokens,)*
                        }
                    }
                }
            }
        } else {
            quote! {
                impl<#(#type_param_tokens),*> Default for #struct_name<#(#type_param_tokens),*> {
                    fn default() -> Self {
                        Self {
                            #(#default_field_tokens,)*
                        }
                    }
                }
            }
        })
    }

    /// Simple parameter transpilation for class methods (no body analysis needed)
    pub(crate) fn transpile_params(
        &self,
        params: &[crate::frontend::ast::Param],
    ) -> Result<Vec<TokenStream>> {
        params
            .iter()
            .map(|param| -> Result<TokenStream> {
                let param_name = param.name();

                // Handle self parameters specially
                if param_name == "self" {
                    use crate::frontend::ast::TypeKind;
                    match &param.ty.kind {
                        TypeKind::Reference { is_mut: true, .. } => Ok(quote! { &mut self }),
                        TypeKind::Reference { is_mut: false, .. } => Ok(quote! { &self }),
                        _ => {
                            // Check if it's a mutable move (mut self)
                            if param.is_mutable {
                                Ok(quote! { mut self })
                            } else {
                                Ok(quote! { self })
                            }
                        }
                    }
                } else {
                    // Regular parameter
                    // TRANSPILER-005 FIX: Preserve mut keyword for mutable parameters
                    let param_ident = format_ident!("{}", param_name);
                    let type_tokens = self.transpile_type(&param.ty)?;
                    if param.is_mutable {
                        Ok(quote! { mut #param_ident: #type_tokens })
                    } else {
                        Ok(quote! { #param_ident: #type_tokens })
                    }
                }
            })
            .collect()
    }

    /// Transpiles trait definitions
    pub fn transpile_enum(
        &self,
        name: &str,
        type_params: &[String],
        variants: &[EnumVariant],
        is_pub: bool,
    ) -> Result<TokenStream> {
        let enum_name = format_ident!("{}", name);
        let type_param_tokens: Vec<_> = type_params
            .iter()
            .map(|p| Self::parse_type_param_to_tokens(p))
            .collect();
        // Check if any variant has discriminant values
        let has_discriminants = variants.iter().any(|v| v.discriminant.is_some());
        let variant_tokens: Vec<TokenStream> = variants
            .iter()
            .map(|variant| {
                use crate::frontend::ast::EnumVariantKind;
                let variant_name = format_ident!("{}", variant.name);

                match &variant.kind {
                    EnumVariantKind::Tuple(fields) => {
                        // Tuple variant: Write(String)
                        let field_types: Vec<TokenStream> = fields
                            .iter()
                            .map(|ty| self.transpile_type(ty).unwrap_or_else(|_| quote! { _ }))
                            .collect();
                        quote! { #variant_name(#(#field_types),*) }
                    }
                    EnumVariantKind::Struct(fields) => {
                        // Struct variant: Move { x: i32, y: i32 }
                        let field_defs: Vec<TokenStream> = fields
                            .iter()
                            .map(|field| {
                                let field_name = format_ident!("{}", field.name);
                                let field_type = self
                                    .transpile_type(&field.ty)
                                    .unwrap_or_else(|_| quote! { _ });
                                quote! { #field_name: #field_type }
                            })
                            .collect();
                        quote! { #variant_name { #(#field_defs),* } }
                    }
                    EnumVariantKind::Unit => {
                        // Unit variant with optional discriminant
                        if let Some(disc_value) = variant.discriminant {
                            let disc_literal =
                                proc_macro2::Literal::i32_unsuffixed(disc_value as i32);
                            quote! { #variant_name = #disc_literal }
                        } else {
                            quote! { #variant_name }
                        }
                    }
                }
            })
            .collect();
        let visibility = if is_pub {
            quote! { pub }
        } else {
            quote! {}
        };
        // Add #[derive(Debug, Clone, PartialEq)] for better usability
        let derive_attr = quote! { #[derive(Debug, Clone, PartialEq)] };

        // Add #[repr(i32)] attribute if enum has discriminant values
        let repr_attr = if has_discriminants {
            quote! { #[repr(i32)] }
        } else {
            quote! {}
        };
        if type_params.is_empty() {
            Ok(quote! {
                #derive_attr
                #repr_attr
                #visibility enum #enum_name {
                    #(#variant_tokens,)*
                }
            })
        } else {
            Ok(quote! {
                #derive_attr
                #repr_attr
                #visibility enum #enum_name<#(#type_param_tokens),*> {
                    #(#variant_tokens,)*
                }
            })
        }
    }
    pub fn transpile_trait(
        &self,
        name: &str,
        type_params: &[String],
        associated_types: &[String],
        methods: &[TraitMethod],
        is_pub: bool,
    ) -> Result<TokenStream> {
        let trait_name = format_ident!("{}", name);

        // Generate associated type declarations: type Item;
        let associated_type_tokens: Vec<TokenStream> = associated_types
            .iter()
            .map(|type_name| {
                let type_ident = format_ident!("{}", type_name);
                quote! { type #type_ident; }
            })
            .collect();

        let method_tokens: Result<Vec<_>> = methods
            .iter()
            .map(|method| {
                let method_name = format_ident!("{}", method.name);
                // TRANSPILER-TRAIT-001 FIX: Determine if self is mutated for &mut self inference
                // For traits with default implementations, check the body for mutations
                let self_is_mutated = method.body.as_ref().is_some_and(|body| {
                    crate::backend::transpiler::mutation_detection::is_variable_mutated(
                        "self", body,
                    )
                });
                // Process parameters
                let param_tokens: Vec<TokenStream> = method
                    .params
                    .iter()
                    .enumerate()
                    .map(|(i, param)| {
                        if i == 0 && (param.name() == "self" || param.name() == "&self") {
                            // TRANSPILER-TRAIT-001 FIX: Handle self parameter consistently
                            // Check the TYPE for reference/mutable reference
                            if let TypeKind::Reference { is_mut, .. } = &param.ty.kind {
                                if *is_mut {
                                    quote! { &mut self }
                                } else {
                                    quote! { &self }
                                }
                            } else if param.name().starts_with('&') {
                                // Legacy: name-based detection (e.g., "&self" as name)
                                quote! { &self }
                            } else {
                                // TRANSPILER-TRAIT-001 FIX: Default to &self or &mut self based on mutation
                                // In Ruchy, `self` without explicit type defaults to reference
                                // This matches Python's implicit self and Rust's common patterns
                                if self_is_mutated {
                                    quote! { &mut self }
                                } else {
                                    quote! { &self }
                                }
                            }
                        } else {
                            let param_name = format_ident!("{}", param.name());
                            let type_tokens = self
                                .transpile_type(&param.ty)
                                .unwrap_or_else(|_| quote! { _ });
                            quote! { #param_name: #type_tokens }
                        }
                    })
                    .collect();
                // Process return type
                let return_type_tokens = if let Some(ref ty) = method.return_type {
                    let ty_tokens = self.transpile_type(ty)?;
                    quote! { -> #ty_tokens }
                } else {
                    quote! {}
                };
                // TRANSPILER-TRAIT-001 FIX: Trait methods cannot have visibility modifiers
                // In Rust, trait method declarations are implicitly public.
                // Adding `pub` causes prettyplease to fail with "not implemented: TraitItem::Verbatim"
                // Process method body (if default implementation)
                if let Some(ref body) = method.body {
                    let body_tokens = self.transpile_expr(body)?;
                    Ok(quote! {
                        fn #method_name(#(#param_tokens),*) #return_type_tokens {
                            #body_tokens
                        }
                    })
                } else {
                    Ok(quote! {
                        fn #method_name(#(#param_tokens),*) #return_type_tokens;
                    })
                }
            })
            .collect();
        let method_tokens = method_tokens?;
        let type_param_tokens: Vec<_> = type_params
            .iter()
            .map(|p| Self::parse_type_param_to_tokens(p))
            .collect();
        let visibility = if is_pub {
            quote! { pub }
        } else {
            quote! {}
        };
        if type_params.is_empty() {
            Ok(quote! {
                #visibility trait #trait_name {
                    #(#associated_type_tokens)*
                    #(#method_tokens)*
                }
            })
        } else {
            Ok(quote! {
                #visibility trait #trait_name<#(#type_param_tokens),*> {
                    #(#associated_type_tokens)*
                    #(#method_tokens)*
                }
            })
        }
    }
    /// Transpiles impl blocks
    pub fn transpile_impl(
        &self,
        for_type: &str,
        type_params: &[String],
        trait_name: Option<&str>,
        methods: &[ImplMethod],
        _is_pub: bool,
    ) -> Result<TokenStream> {
        // DEFECT-027 FIX: Strip generic parameters from for_type if present
        // e.g., "Container<T>" -> "Container"
        let base_type = for_type.split('<').next().unwrap_or(for_type).trim();
        let type_ident = format_ident!("{}", base_type);
        let method_tokens: Result<Vec<_>> = methods
            .iter()
            .map(|method| {
                let method_name = format_ident!("{}", method.name);
                // TRANSPILER-METHOD-SELF-001 FIX: Check if self is mutated in method body
                // to infer &mut self vs &self when not explicitly annotated
                let self_is_mutated =
                    crate::backend::transpiler::mutation_detection::is_variable_mutated(
                        "self",
                        &method.body,
                    );
                // Process parameters
                let param_tokens: Vec<TokenStream> = method
                    .params
                    .iter()
                    .map(|param| {
                        let name = param.name();
                        // QUALITY-001: Handle special Rust receiver syntax (&self, &mut self, self)
                        // Method receivers in Rust have special syntax that differs from normal parameters
                        if name == "self" {
                            // Check if it's a reference type (in the TYPE, not the name)
                            if let TypeKind::Reference { is_mut, .. } = &param.ty.kind {
                                if *is_mut {
                                    quote! { &mut self }
                                } else {
                                    quote! { &self }
                                }
                            } else {
                                // TRANSPILER-METHOD-SELF-001 FIX: Infer &mut self or &self
                                // based on whether self is mutated in the method body
                                // This makes Ruchy more Python-like where self is always a reference
                                if self_is_mutated {
                                    quote! { &mut self }
                                } else {
                                    quote! { &self }
                                }
                            }
                        } else {
                            let param_name = format_ident!("{}", param.name());
                            let type_tokens = self
                                .transpile_type(&param.ty)
                                .unwrap_or_else(|_| quote! { _ });
                            quote! { #param_name: #type_tokens }
                        }
                    })
                    .collect();
                // Process return type
                let return_type_tokens = if let Some(ref ty) = method.return_type {
                    let ty_tokens = self.transpile_type(ty)?;
                    quote! { -> #ty_tokens }
                } else {
                    quote! {}
                };
                // BOOK-COMPAT-016: Check if we need auto-clone for &self method returning owned type
                let needs_auto_clone = !self_is_mutated
                    && method
                        .return_type
                        .as_ref()
                        .is_some_and(Self::is_owned_type)
                    && Self::body_returns_self_field(&method.body);
                // Process method body (always present in ImplMethod)
                let body_tokens = if needs_auto_clone {
                    self.transpile_body_with_auto_clone(&method.body)?
                } else {
                    self.transpile_expr(&method.body)?
                };
                // Process method visibility
                let visibility = if method.is_pub {
                    quote! { pub }
                } else {
                    quote! {}
                };
                Ok(quote! {
                    #visibility fn #method_name(#(#param_tokens),*) #return_type_tokens {
                        #body_tokens
                    }
                })
            })
            .collect();
        let method_tokens = method_tokens?;
        let type_param_tokens: Vec<_> = type_params
            .iter()
            .map(|p| Self::parse_type_param_to_tokens(p))
            .collect();
        if let Some(trait_name) = trait_name {
            let trait_ident = format_ident!("{}", trait_name);
            if type_params.is_empty() {
                Ok(quote! {
                    impl #trait_ident for #type_ident {
                        #(#method_tokens)*
                    }
                })
            } else {
                Ok(quote! {
                    impl<#(#type_param_tokens),*> #trait_ident for #type_ident<#(#type_param_tokens),*> {
                        #(#method_tokens)*
                    }
                })
            }
        } else {
            if type_params.is_empty() {
                Ok(quote! {
                    impl #type_ident {
                        #(#method_tokens)*
                    }
                })
            } else {
                Ok(quote! {
                    impl<#(#type_param_tokens),*> #type_ident<#(#type_param_tokens),*> {
                        #(#method_tokens)*
                    }
                })
            }
        }
    }
    /// Transpiles property test attributes
    pub fn transpile_property_test(&self, expr: &Expr, _attr: &Attribute) -> Result<TokenStream> {
        // Property tests in Rust typically use proptest or quickcheck
        // We'll generate proptest-compatible code
        if let ExprKind::Function {
            name, params, body, ..
        } = &expr.kind
        {
            let fn_name = format_ident!("{}", name);
            // Generate property test parameters
            let param_tokens: Vec<TokenStream> = params
                .iter()
                .map(|p| {
                    let param_name = format_ident!("{}", p.name());
                    let type_tokens = self
                        .transpile_type(&p.ty)
                        .unwrap_or_else(|_| quote! { i32 });
                    quote! { #param_name: #type_tokens }
                })
                .collect();
            let body_tokens = self.transpile_expr(body)?;
            // Generate the proptest macro invocation
            Ok(quote! {
                #[cfg(test)]
                mod #fn_name {
                    use super::*;
                    proptest! {
                        #[test]
                        fn #fn_name(#(#param_tokens),*) {
                            #body_tokens
                        }
                    }
                }
            })
        } else {
            bail!("Property test attribute can only be applied to functions");
        }
    }
    /// Transpiles extension methods into trait + impl
    ///
    /// Generates both a trait definition and an implementation according to the specification:
    /// ```text
    /// Ruchy: extend String { fun is_palindrome(&self) -> bool { ... } }
    /// Rust:  trait StringExt { fn is_palindrome(&self) -> bool; }
    ///        impl StringExt for String { fn is_palindrome(&self) -> bool { ... } }
    /// ```
    pub fn transpile_extend(
        &self,
        target_type: &str,
        methods: &[ImplMethod],
    ) -> Result<TokenStream> {
        let target_ident = format_ident!("{}", target_type);
        let trait_name = format_ident!("{}Ext", target_type); // e.g., StringExt
                                                              // Generate trait definition
        let trait_method_tokens: Result<Vec<_>> = methods
            .iter()
            .map(|method| {
                let method_name = format_ident!("{}", method.name);
                // Process parameters
                let param_tokens: Vec<TokenStream> = method
                    .params
                    .iter()
                    .map(|param| {
                        let name = param.name();
                        // QUALITY-001: Handle special Rust receiver syntax (&self, &mut self, self)
                        // Method receivers in Rust have special syntax that differs from normal parameters
                        if name == "self" {
                            // Check if it's a reference type (in the TYPE, not the name)
                            if let TypeKind::Reference { is_mut, .. } = &param.ty.kind {
                                if *is_mut {
                                    quote! { &mut self }
                                } else {
                                    quote! { &self }
                                }
                            } else {
                                quote! { self }
                            }
                        } else {
                            let param_name = format_ident!("{}", param.name());
                            let type_tokens = self
                                .transpile_type(&param.ty)
                                .unwrap_or_else(|_| quote! { _ });
                            quote! { #param_name: #type_tokens }
                        }
                    })
                    .collect();
                // Process return type
                let return_type_tokens = if let Some(ref ty) = method.return_type {
                    let ty_tokens = self.transpile_type(ty)?;
                    quote! { -> #ty_tokens }
                } else {
                    quote! {}
                };
                // Trait methods are just signatures (no body)
                Ok(quote! {
                    fn #method_name(#(#param_tokens),*) #return_type_tokens;
                })
            })
            .collect();
        let trait_method_tokens = trait_method_tokens?;
        // Generate impl definition
        let impl_method_tokens: Result<Vec<_>> = methods
            .iter()
            .map(|method| {
                let method_name = format_ident!("{}", method.name);
                // Process parameters (same as trait)
                let param_tokens: Vec<TokenStream> = method
                    .params
                    .iter()
                    .enumerate()
                    .map(|(i, param)| {
                        if i == 0 && (param.name() == "self" || param.name() == "&self") {
                            if param.name().starts_with('&') {
                                quote! { &self }
                            } else {
                                quote! { self }
                            }
                        } else {
                            let param_name = format_ident!("{}", param.name());
                            let type_tokens = self
                                .transpile_type(&param.ty)
                                .unwrap_or_else(|_| quote! { _ });
                            quote! { #param_name: #type_tokens }
                        }
                    })
                    .collect();
                // Process return type
                let return_type_tokens = if let Some(ref ty) = method.return_type {
                    let ty_tokens = self.transpile_type(ty)?;
                    quote! { -> #ty_tokens }
                } else {
                    quote! {}
                };
                // Impl methods have bodies
                let body_tokens = self.transpile_expr(&method.body)?;
                Ok(quote! {
                    fn #method_name(#(#param_tokens),*) #return_type_tokens {
                        #body_tokens
                    }
                })
            })
            .collect();
        let impl_method_tokens = impl_method_tokens?;
        // Generate both trait and impl
        Ok(quote! {
            trait #trait_name {
                #(#trait_method_tokens)*
            }
            impl #trait_name for #target_ident {
                #(#impl_method_tokens)*
            }
        })
    }

    /// BOOK-COMPAT-016: Check if a type is an owned type that would need cloning
    fn is_owned_type(ty: &Type) -> bool {
        matches!(&ty.kind, TypeKind::Named(name) if name == "String" || name == "Vec" || name == "HashMap")
    }

    /// BOOK-COMPAT-016: Check if body returns a self.field expression
    fn body_returns_self_field(body: &Expr) -> bool {
        match &body.kind {
            ExprKind::FieldAccess { object, .. } => {
                matches!(&object.kind, ExprKind::Identifier(name) if name == "self")
            }
            ExprKind::Block(exprs) => {
                if let Some(last) = exprs.last() {
                    Self::body_returns_self_field(last)
                } else {
                    false
                }
            }
            _ => false,
        }
    }

    /// BOOK-COMPAT-016: Transpile body with auto-clone for self.field
    fn transpile_body_with_auto_clone(&self, body: &Expr) -> Result<TokenStream> {
        match &body.kind {
            ExprKind::FieldAccess { object, field } => {
                if matches!(&object.kind, ExprKind::Identifier(name) if name == "self") {
                    let field_ident = format_ident!("{}", field);
                    Ok(quote! { self.#field_ident.clone() })
                } else {
                    self.transpile_expr(body)
                }
            }
            ExprKind::Block(exprs) if !exprs.is_empty() => {
                let mut tokens = Vec::new();
                for expr in exprs.iter().take(exprs.len() - 1) {
                    tokens.push(self.transpile_expr(expr)?);
                }
                if let Some(last) = exprs.last() {
                    let last_tokens = self.transpile_body_with_auto_clone(last)?;
                    tokens.push(last_tokens);
                }
                Ok(quote! { { #(#tokens)* } })
            }
            _ => self.transpile_expr(body),
        }
    }
}

// ===== EXTREME TDD Round 155 - Type Transpilation Tests =====

#[cfg(test)]
mod extreme_tdd_tests {
    use super::*;
    use crate::frontend::ast::{
        EnumVariant, EnumVariantKind, ImplMethod, Span, StructField, TraitMethod, Type, TypeKind,
        Visibility,
    };

    fn make_type(kind: TypeKind) -> Type {
        Type {
            kind,
            span: Span::new(0, 0),
        }
    }

    fn make_expr(kind: crate::frontend::ast::ExprKind) -> Expr {
        Expr {
            kind,
            span: Span::new(0, 0),
            attributes: vec![],
            leading_comments: vec![],
            trailing_comment: None,
        }
    }

    fn make_param(name: &str, ty: Type) -> crate::frontend::ast::Param {
        crate::frontend::ast::Param {
            pattern: crate::frontend::ast::Pattern::Identifier(name.to_string()),
            ty,
            span: Span::new(0, 0),
            is_mutable: false,
            default_value: None,
        }
    }

    fn make_struct_field(name: &str, ty: Type, visibility: Visibility) -> StructField {
        StructField {
            name: name.to_string(),
            ty,
            visibility,
            default_value: None,
            decorators: vec![],
            is_mut: false,
        }
    }

    // ===== Named Type Tests =====

    #[test]
    fn test_transpile_named_type_int() {
        let t = Transpiler::new();
        let result = t.transpile_named_type("int").unwrap();
        assert!(result.to_string().contains("i64"));
    }

    #[test]
    fn test_transpile_named_type_float() {
        let t = Transpiler::new();
        let result = t.transpile_named_type("float").unwrap();
        assert!(result.to_string().contains("f64"));
    }

    #[test]
    fn test_transpile_named_type_bool() {
        let t = Transpiler::new();
        let result = t.transpile_named_type("bool").unwrap();
        assert!(result.to_string().contains("bool"));
    }

    #[test]
    fn test_transpile_named_type_str() {
        let t = Transpiler::new();
        let result = t.transpile_named_type("str").unwrap();
        assert!(result.to_string().contains("& str"));
    }

    #[test]
    fn test_transpile_named_type_string() {
        let t = Transpiler::new();
        let result = t.transpile_named_type("string").unwrap();
        assert!(result.to_string().contains("String"));
    }

    #[test]
    fn test_transpile_named_type_char() {
        let t = Transpiler::new();
        let result = t.transpile_named_type("char").unwrap();
        assert!(result.to_string().contains("char"));
    }

    #[test]
    fn test_transpile_named_type_unit() {
        let t = Transpiler::new();
        let result = t.transpile_named_type("()").unwrap();
        assert!(result.to_string().contains("()"));
    }

    #[test]
    fn test_transpile_named_type_any() {
        let t = Transpiler::new();
        let result = t.transpile_named_type("Any").unwrap();
        assert!(result.to_string().contains("_"));
    }

    #[test]
    fn test_transpile_named_type_object() {
        let t = Transpiler::new();
        let result = t.transpile_named_type("Object").unwrap();
        assert!(result.to_string().contains("BTreeMap"));
    }

    #[test]
    fn test_transpile_named_type_namespaced() {
        let t = Transpiler::new();
        let result = t.transpile_named_type("std::io::Error").unwrap();
        let s = result.to_string();
        assert!(s.contains("std"));
        assert!(s.contains("io"));
        assert!(s.contains("Error"));
    }

    #[test]
    fn test_transpile_named_type_custom() {
        let t = Transpiler::new();
        let result = t.transpile_named_type("MyCustomType").unwrap();
        assert!(result.to_string().contains("MyCustomType"));
    }

    // ===== Generic Type Tests =====

    #[test]
    fn test_transpile_generic_type_single_param() {
        let t = Transpiler::new();
        let inner = make_type(TypeKind::Named("i32".to_string()));
        let result = t.transpile_generic_type("Vec", &[inner]).unwrap();
        assert!(result.to_string().contains("Vec"));
        assert!(result.to_string().contains("i32"));
    }

    #[test]
    fn test_transpile_generic_type_multiple_params() {
        let t = Transpiler::new();
        let k = make_type(TypeKind::Named("String".to_string()));
        let v = make_type(TypeKind::Named("i32".to_string()));
        let result = t.transpile_generic_type("HashMap", &[k, v]).unwrap();
        let s = result.to_string();
        assert!(s.contains("HashMap"));
        assert!(s.contains("String"));
        assert!(s.contains("i32"));
    }

    // ===== Optional Type Tests =====

    #[test]
    fn test_transpile_optional_type() {
        let t = Transpiler::new();
        let inner = make_type(TypeKind::Named("i32".to_string()));
        let result = t.transpile_optional_type(&inner).unwrap();
        let s = result.to_string();
        assert!(s.contains("Option"));
        assert!(s.contains("i32"));
    }

    // ===== List Type Tests =====

    #[test]
    fn test_transpile_list_type() {
        let t = Transpiler::new();
        let elem = make_type(TypeKind::Named("String".to_string()));
        let result = t.transpile_list_type(&elem).unwrap();
        let s = result.to_string();
        assert!(s.contains("Vec"));
        assert!(s.contains("String"));
    }

    // ===== Array Type Tests =====

    #[test]
    fn test_transpile_array_type() {
        let t = Transpiler::new();
        let elem = make_type(TypeKind::Named("f64".to_string()));
        let result = t.transpile_array_type(&elem, 10).unwrap();
        let s = result.to_string();
        assert!(s.contains("f64"));
        assert!(s.contains("10"));
    }

    // ===== Tuple Type Tests =====

    #[test]
    fn test_transpile_tuple_type_empty() {
        let t = Transpiler::new();
        let result = t.transpile_tuple_type(&[]).unwrap();
        assert!(result.to_string().contains("()"));
    }

    #[test]
    fn test_transpile_tuple_type_single() {
        let t = Transpiler::new();
        let elem = make_type(TypeKind::Named("i32".to_string()));
        let result = t.transpile_tuple_type(&[elem]).unwrap();
        assert!(result.to_string().contains("i32"));
    }

    #[test]
    fn test_transpile_tuple_type_multiple() {
        let t = Transpiler::new();
        let e1 = make_type(TypeKind::Named("i32".to_string()));
        let e2 = make_type(TypeKind::Named("String".to_string()));
        let e3 = make_type(TypeKind::Named("bool".to_string()));
        let result = t.transpile_tuple_type(&[e1, e2, e3]).unwrap();
        let s = result.to_string();
        assert!(s.contains("i32"));
        assert!(s.contains("String"));
        assert!(s.contains("bool"));
    }

    // ===== Function Type Tests =====

    #[test]
    fn test_transpile_function_type() {
        let t = Transpiler::new();
        let param = make_type(TypeKind::Named("i32".to_string()));
        let ret = make_type(TypeKind::Named("bool".to_string()));
        let result = t.transpile_function_type(&[param], &ret).unwrap();
        let s = result.to_string();
        assert!(s.contains("fn"));
        assert!(s.contains("i32"));
        assert!(s.contains("bool"));
    }

    // ===== Reference Type Tests =====

    #[test]
    fn test_transpile_reference_type_immutable() {
        let t = Transpiler::new();
        let inner = make_type(TypeKind::Named("i32".to_string()));
        let result = t.transpile_reference_type(false, None, &inner).unwrap();
        let s = result.to_string();
        assert!(s.contains("&"));
        assert!(s.contains("i32"));
        assert!(!s.contains("mut"));
    }

    #[test]
    fn test_transpile_reference_type_mutable() {
        let t = Transpiler::new();
        let inner = make_type(TypeKind::Named("i32".to_string()));
        let result = t.transpile_reference_type(true, None, &inner).unwrap();
        let s = result.to_string();
        assert!(s.contains("mut"));
        assert!(s.contains("i32"));
    }

    #[test]
    fn test_transpile_reference_type_with_lifetime() {
        let t = Transpiler::new();
        let inner = make_type(TypeKind::Named("i32".to_string()));
        let result = t
            .transpile_reference_type(false, Some("'a"), &inner)
            .unwrap();
        let s = result.to_string();
        assert!(s.contains("'a"));
        assert!(s.contains("i32"));
    }

    #[test]
    fn test_transpile_reference_type_str_special() {
        let t = Transpiler::new();
        let inner = make_type(TypeKind::Named("str".to_string()));
        let result = t.transpile_reference_type(false, None, &inner).unwrap();
        // Should be &str, not &&str
        assert_eq!(result.to_string().matches("&").count(), 1);
    }

    // ===== Type Parameter Tests =====

    #[test]
    fn test_parse_type_param_simple() {
        let result = Transpiler::parse_type_param_to_tokens("T");
        assert!(result.to_string().contains("T"));
    }

    #[test]
    fn test_parse_type_param_lifetime() {
        let result = Transpiler::parse_type_param_to_tokens("'a");
        assert!(result.to_string().contains("'a"));
    }

    #[test]
    fn test_parse_type_param_with_bound() {
        let result = Transpiler::parse_type_param_to_tokens("T: Clone");
        let s = result.to_string();
        assert!(s.contains("T"));
        assert!(s.contains("Clone"));
    }

    // ===== Struct Tests =====

    #[test]
    fn test_transpile_struct_empty() {
        let t = Transpiler::new();
        let result = t.transpile_struct("Empty", &[], &[], &[], false).unwrap();
        let s = result.to_string();
        assert!(s.contains("struct"));
        assert!(s.contains("Empty"));
    }

    #[test]
    fn test_transpile_struct_with_fields() {
        let t = Transpiler::new();
        let fields = vec![
            make_struct_field(
                "x",
                make_type(TypeKind::Named("i32".to_string())),
                Visibility::Public,
            ),
            make_struct_field(
                "y",
                make_type(TypeKind::Named("i32".to_string())),
                Visibility::Private,
            ),
        ];
        let result = t
            .transpile_struct("Point", &[], &fields, &[], true)
            .unwrap();
        let s = result.to_string();
        assert!(s.contains("pub struct"));
        assert!(s.contains("Point"));
        assert!(s.contains("x"));
        assert!(s.contains("y"));
    }

    #[test]
    fn test_transpile_struct_with_type_params() {
        let t = Transpiler::new();
        let fields = vec![make_struct_field(
            "value",
            make_type(TypeKind::Named("T".to_string())),
            Visibility::Public,
        )];
        let result = t
            .transpile_struct("Container", &["T".to_string()], &fields, &[], true)
            .unwrap();
        let s = result.to_string();
        assert!(s.contains("Container"));
        assert!(s.contains("<"));
        assert!(s.contains("T"));
    }

    #[test]
    fn test_transpile_struct_with_derives() {
        let t = Transpiler::new();
        let result = t
            .transpile_struct(
                "MyStruct",
                &[],
                &[],
                &["Debug".to_string(), "Clone".to_string()],
                false,
            )
            .unwrap();
        let s = result.to_string();
        assert!(s.contains("derive"));
        assert!(s.contains("Debug"));
        assert!(s.contains("Clone"));
    }

    // ===== Tuple Struct Tests =====

    #[test]
    fn test_transpile_tuple_struct() {
        let t = Transpiler::new();
        let fields = vec![
            make_type(TypeKind::Named("i32".to_string())),
            make_type(TypeKind::Named("String".to_string())),
        ];
        let result = t
            .transpile_tuple_struct("Pair", &[], &fields, &[], true)
            .unwrap();
        let s = result.to_string();
        assert!(s.contains("pub struct"));
        assert!(s.contains("Pair"));
        assert!(s.contains("i32"));
        assert!(s.contains("String"));
    }

    // ===== Enum Tests =====

    #[test]
    fn test_transpile_enum_unit_variants() {
        let t = Transpiler::new();
        let variants = vec![
            EnumVariant {
                name: "Red".to_string(),
                kind: EnumVariantKind::Unit,
                discriminant: None,
            },
            EnumVariant {
                name: "Green".to_string(),
                kind: EnumVariantKind::Unit,
                discriminant: None,
            },
            EnumVariant {
                name: "Blue".to_string(),
                kind: EnumVariantKind::Unit,
                discriminant: None,
            },
        ];
        let result = t.transpile_enum("Color", &[], &variants, true).unwrap();
        let s = result.to_string();
        assert!(s.contains("pub enum"));
        assert!(s.contains("Color"));
        assert!(s.contains("Red"));
        assert!(s.contains("Green"));
        assert!(s.contains("Blue"));
    }

    #[test]
    fn test_transpile_enum_with_discriminants() {
        let t = Transpiler::new();
        let variants = vec![
            EnumVariant {
                name: "A".to_string(),
                kind: EnumVariantKind::Unit,
                discriminant: Some(1),
            },
            EnumVariant {
                name: "B".to_string(),
                kind: EnumVariantKind::Unit,
                discriminant: Some(2),
            },
        ];
        let result = t.transpile_enum("MyEnum", &[], &variants, false).unwrap();
        let s = result.to_string();
        assert!(s.contains("repr"));
        assert!(s.contains("= 1"));
        assert!(s.contains("= 2"));
    }

    #[test]
    fn test_transpile_enum_tuple_variant() {
        let t = Transpiler::new();
        let variants = vec![
            EnumVariant {
                name: "Some".to_string(),
                kind: EnumVariantKind::Tuple(vec![make_type(TypeKind::Named("T".to_string()))]),
                discriminant: None,
            },
            EnumVariant {
                name: "None".to_string(),
                kind: EnumVariantKind::Unit,
                discriminant: None,
            },
        ];
        let result = t
            .transpile_enum("MyOption", &["T".to_string()], &variants, true)
            .unwrap();
        let s = result.to_string();
        assert!(s.contains("MyOption"));
        assert!(s.contains("Some"));
        assert!(s.contains("None"));
    }

    #[test]
    fn test_transpile_enum_struct_variant() {
        let t = Transpiler::new();
        let variants = vec![EnumVariant {
            name: "Move".to_string(),
            kind: EnumVariantKind::Struct(vec![
                make_struct_field(
                    "x",
                    make_type(TypeKind::Named("i32".to_string())),
                    Visibility::Public,
                ),
                make_struct_field(
                    "y",
                    make_type(TypeKind::Named("i32".to_string())),
                    Visibility::Public,
                ),
            ]),
            discriminant: None,
        }];
        let result = t.transpile_enum("Message", &[], &variants, true).unwrap();
        let s = result.to_string();
        assert!(s.contains("Move"));
        assert!(s.contains("x"));
        assert!(s.contains("y"));
    }

    // ===== Trait Tests =====

    #[test]
    fn test_transpile_trait_empty() {
        let t = Transpiler::new();
        let result = t.transpile_trait("Empty", &[], &[], &[], true).unwrap();
        let s = result.to_string();
        assert!(s.contains("pub trait"));
        assert!(s.contains("Empty"));
    }

    #[test]
    fn test_transpile_trait_with_method() {
        let t = Transpiler::new();
        let methods = vec![TraitMethod {
            name: "do_something".to_string(),
            params: vec![make_param(
                "self",
                make_type(TypeKind::Reference {
                    is_mut: false,
                    lifetime: None,
                    inner: Box::new(make_type(TypeKind::Named("Self".to_string()))),
                }),
            )],
            return_type: Some(make_type(TypeKind::Named("i32".to_string()))),
            body: None,
            is_pub: false,
        }];
        let result = t
            .transpile_trait("MyTrait", &[], &[], &methods, true)
            .unwrap();
        let s = result.to_string();
        assert!(s.contains("MyTrait"));
        assert!(s.contains("do_something"));
        assert!(s.contains("i32"));
    }

    #[test]
    fn test_transpile_trait_with_associated_type() {
        let t = Transpiler::new();
        let result = t
            .transpile_trait("Iterator", &[], &["Item".to_string()], &[], true)
            .unwrap();
        let s = result.to_string();
        assert!(s.contains("type Item"));
    }

    // ===== Impl Tests =====

    #[test]
    fn test_transpile_impl_inherent() {
        let t = Transpiler::new();
        let body = make_expr(crate::frontend::ast::ExprKind::Literal(
            crate::frontend::ast::Literal::Integer(42, None),
        ));
        let methods = vec![ImplMethod {
            name: "answer".to_string(),
            params: vec![],
            return_type: Some(make_type(TypeKind::Named("i32".to_string()))),
            body: Box::new(body),
            is_pub: true,
        }];
        let result = t
            .transpile_impl("MyStruct", &[], None, &methods, true)
            .unwrap();
        let s = result.to_string();
        assert!(s.contains("impl MyStruct"));
        assert!(s.contains("answer"));
    }

    #[test]
    fn test_transpile_impl_trait() {
        let t = Transpiler::new();
        let body = make_expr(crate::frontend::ast::ExprKind::Literal(
            crate::frontend::ast::Literal::Integer(0, None),
        ));
        let methods = vec![ImplMethod {
            name: "default".to_string(),
            params: vec![],
            return_type: Some(make_type(TypeKind::Named("Self".to_string()))),
            body: Box::new(body),
            is_pub: false,
        }];
        let result = t
            .transpile_impl("MyStruct", &[], Some("Default"), &methods, false)
            .unwrap();
        let s = result.to_string();
        assert!(s.contains("impl Default for MyStruct"));
    }

    // ===== Extend Tests =====

    #[test]
    fn test_transpile_extend() {
        let t = Transpiler::new();
        let body = make_expr(crate::frontend::ast::ExprKind::Literal(
            crate::frontend::ast::Literal::Bool(true),
        ));
        let methods = vec![ImplMethod {
            name: "is_empty".to_string(),
            params: vec![make_param(
                "self",
                make_type(TypeKind::Reference {
                    is_mut: false,
                    lifetime: None,
                    inner: Box::new(make_type(TypeKind::Named("Self".to_string()))),
                }),
            )],
            return_type: Some(make_type(TypeKind::Named("bool".to_string()))),
            body: Box::new(body),
            is_pub: true,
        }];
        let result = t.transpile_extend("String", &methods).unwrap();
        let s = result.to_string();
        assert!(s.contains("trait StringExt"));
        assert!(s.contains("impl StringExt for String"));
    }

    // ===== Helper Method Tests =====

    #[test]
    fn test_has_reference_fields_true() {
        let t = Transpiler::new();
        let fields = vec![StructField {
            name: "data".to_string(),
            ty: make_type(TypeKind::Reference {
                is_mut: false,
                lifetime: None,
                inner: Box::new(make_type(TypeKind::Named("str".to_string()))),
            }),
            visibility: Visibility::Public,
            default_value: None,
            decorators: vec![],
            is_mut: false,
        }];
        assert!(t.has_reference_fields(&fields));
    }

    #[test]
    fn test_has_reference_fields_false() {
        let t = Transpiler::new();
        let fields = vec![StructField {
            name: "data".to_string(),
            ty: make_type(TypeKind::Named("String".to_string())),
            visibility: Visibility::Public,
            default_value: None,
            decorators: vec![],
            is_mut: false,
        }];
        assert!(!t.has_reference_fields(&fields));
    }

    #[test]
    fn test_has_lifetime_params_true() {
        let t = Transpiler::new();
        assert!(t.has_lifetime_params(&["'a".to_string(), "T".to_string()]));
    }

    #[test]
    fn test_has_lifetime_params_false() {
        let t = Transpiler::new();
        assert!(!t.has_lifetime_params(&["T".to_string(), "U".to_string()]));
    }

    #[test]
    fn test_generate_derive_attributes_empty() {
        let t = Transpiler::new();
        let result = t.generate_derive_attributes(&[]);
        assert!(result.is_empty());
    }

    #[test]
    fn test_generate_derive_attributes_multiple() {
        let t = Transpiler::new();
        let result = t.generate_derive_attributes(&["Debug".to_string(), "Clone".to_string()]);
        let s = result.to_string();
        assert!(s.contains("derive"));
        assert!(s.contains("Debug"));
        assert!(s.contains("Clone"));
    }

    #[test]
    fn test_generate_class_type_param_tokens() {
        let t = Transpiler::new();
        let result = t.generate_class_type_param_tokens(&["T".to_string(), "'a".to_string()]);
        assert_eq!(result.len(), 2);
    }

    // ===== transpile_type Integration Tests =====

    #[test]
    fn test_transpile_type_named() {
        let t = Transpiler::new();
        let ty = make_type(TypeKind::Named("i32".to_string()));
        let result = t.transpile_type(&ty).unwrap();
        assert!(result.to_string().contains("i32"));
    }

    #[test]
    fn test_transpile_type_optional() {
        let t = Transpiler::new();
        let ty = make_type(TypeKind::Optional(Box::new(make_type(TypeKind::Named(
            "i32".to_string(),
        )))));
        let result = t.transpile_type(&ty).unwrap();
        assert!(result.to_string().contains("Option"));
    }

    #[test]
    fn test_transpile_type_list() {
        let t = Transpiler::new();
        let ty = make_type(TypeKind::List(Box::new(make_type(TypeKind::Named(
            "String".to_string(),
        )))));
        let result = t.transpile_type(&ty).unwrap();
        assert!(result.to_string().contains("Vec"));
    }

    #[test]
    fn test_transpile_type_dataframe() {
        let t = Transpiler::new();
        let ty = make_type(TypeKind::DataFrame { columns: vec![] });
        let result = t.transpile_type(&ty).unwrap();
        assert!(result.to_string().contains("DataFrame"));
    }

    #[test]
    fn test_transpile_type_series() {
        let t = Transpiler::new();
        let ty = make_type(TypeKind::Series {
            dtype: Box::new(make_type(TypeKind::Named("f64".to_string()))),
        });
        let result = t.transpile_type(&ty).unwrap();
        assert!(result.to_string().contains("Series"));
    }

    #[test]
    fn test_transpile_type_refined() {
        let t = Transpiler::new();
        let ty = make_type(TypeKind::Refined {
            base: Box::new(make_type(TypeKind::Named("i32".to_string()))),
            constraint: Box::new(make_expr(crate::frontend::ast::ExprKind::Literal(
                crate::frontend::ast::Literal::Bool(true),
            ))),
        });
        let result = t.transpile_type(&ty).unwrap();
        // Refined types transpile to just the base type
        assert!(result.to_string().contains("i32"));
    }
}