depyler-core 4.1.1

Core transpilation engine for the Depyler Python-to-Rust transpiler
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
//! Generator support and code generation
//!
//! This module handles Python generator functions, converting them to
//! Rust Iterator implementations with state structs.

use crate::generator_state::GeneratorStateInfo;
use crate::generator_yield_analysis::YieldAnalysis;
use crate::hir::{HirExpr, HirFunction, HirStmt, Literal, Type};
use crate::rust_gen::context::{CodeGenContext, ToRustExpr};
use crate::rust_gen::keywords::safe_ident; // DEPYLER-0562: Escape keywords like 'match'
use crate::rust_gen::type_gen::rust_type_to_syn;
use anyhow::Result;
use quote::quote;

/// Generate struct fields for generator state variables
///
/// Creates field declarations for variables that need to persist across yields.
///
/// # Complexity
/// 3 (iter + map + collect)
fn generate_state_fields(
    state_info: &GeneratorStateInfo,
    ctx: &mut CodeGenContext,
) -> Result<Vec<proc_macro2::TokenStream>> {
    state_info
        .state_variables
        .iter()
        .map(|var| {
            // DEPYLER-0562: Use safe_ident to escape keywords like 'match'
            let field_name = safe_ident(&var.name);
            let rust_type = ctx.type_mapper.map_type(&var.ty);
            // DEPYLER-0188: Box impl Trait types for struct fields
            let field_rust_type = box_impl_trait_for_field(&rust_type);
            // DEPYLER-0772: Use concrete fallback for TypeParam in struct fields
            let concrete_type = concretize_type_param_for_struct(&field_rust_type);
            let field_type = rust_type_to_syn(&concrete_type)?;
            Ok(quote! { #field_name: #field_type })
        })
        .collect()
}

/// DEPYLER-0772: Convert TypeParam to concrete type for struct fields
///
/// Generator state structs cannot use bare type parameters like `T` without
/// declaring them. When a state variable has unknown type that maps to `T`,
/// we use `i32` as a safe default since most generator variables are counters
/// or indices.
///
/// # Complexity: 2 (match + clone)
#[inline]
fn concretize_type_param_for_struct(
    rust_type: &crate::type_mapper::RustType,
) -> crate::type_mapper::RustType {
    use crate::type_mapper::{PrimitiveType, RustType};

    match rust_type {
        // DEPYLER-0772: Replace bare `T` with concrete `i32`
        // Most generator state variables are loop counters or accumulator values
        RustType::TypeParam(_) => RustType::Primitive(PrimitiveType::I32),
        other => other.clone(),
    }
}

/// Convert impl Trait types to boxed trait objects for struct fields
///
/// DEPYLER-0188: Rust doesn't allow `impl Trait` in struct field positions,
/// so we convert them to `Box<dyn Trait>` for dynamic dispatch.
///
/// # Complexity
/// 2 (string ops)
fn box_impl_trait_for_field(
    rust_type: &crate::type_mapper::RustType,
) -> crate::type_mapper::RustType {
    use crate::type_mapper::RustType;

    match rust_type {
        RustType::Custom(s) if s.starts_with("impl Iterator") => {
            // impl Iterator<Item=T> -> Box<dyn Iterator<Item=T>>
            let boxed = s.replace("impl Iterator", "Box<dyn Iterator");
            RustType::Custom(format!("{}>", boxed))
        }
        RustType::Custom(s) if s.starts_with("impl IntoIterator") => {
            // impl IntoIterator<Item=T> -> Box<dyn IntoIterator<Item=T>>
            let boxed = s.replace("impl IntoIterator", "Box<dyn IntoIterator");
            RustType::Custom(format!("{}>", boxed))
        }
        other => other.clone(),
    }
}

/// Generate struct fields for captured parameters
///
/// Creates field declarations for function parameters that are captured
/// in the generator state.
///
/// # Complexity
/// 4 (iter + filter + map + collect)
fn generate_param_fields(
    func: &HirFunction,
    state_info: &GeneratorStateInfo,
    ctx: &mut CodeGenContext,
) -> Result<Vec<proc_macro2::TokenStream>> {
    func.params
        .iter()
        .filter(|p| state_info.captured_params.contains(&p.name))
        .map(|param| {
            // DEPYLER-0562: Use safe_ident to escape keywords like 'match'
            let field_name = safe_ident(&param.name);
            let rust_type = ctx.type_mapper.map_type(&param.ty);
            // DEPYLER-0188: Box impl Trait types for struct fields
            let field_rust_type = box_impl_trait_for_field(&rust_type);
            // DEPYLER-0772: Use concrete fallback for TypeParam in struct fields
            let concrete_type = concretize_type_param_for_struct(&field_rust_type);
            let field_type = rust_type_to_syn(&concrete_type)?;
            Ok(quote! { #field_name: #field_type })
        })
        .collect()
}

/// Extract the Item type for the Iterator from generator return type
///
/// DEPYLER-0263 FIX: Infer yield type from yield analysis, not func.ret_type.
/// func.ret_type is often Type::Unknown for generators, which maps to DynamicType.
/// Instead, we analyze the actual yield expressions to infer the concrete type.
///
/// # Complexity
/// 3 (analyze + map + convert)
#[inline]
fn extract_generator_item_type(
    func: &HirFunction,
    yield_analysis: &YieldAnalysis,
    ctx: &CodeGenContext,
) -> Result<syn::Type> {
    // DEPYLER-0495: Extract element type from Iterator[T] return type
    // If return type is Iterator[int], we need item type = int (not Iterator<int>)
    let element_type = match &func.ret_type {
        // Iterator[T] -> extract T
        Type::Generic { base, params } if base == "Iterator" && params.len() == 1 => {
            params[0].clone()
        }
        // Generator[YieldType, SendType, ReturnType] -> extract YieldType
        Type::Generic { base, params } if base == "Generator" && !params.is_empty() => {
            params[0].clone()
        }
        // Unknown -> infer from yield expression (DEPYLER-0263)
        Type::Unknown if !yield_analysis.yield_points.is_empty() => {
            infer_yield_type(&yield_analysis.yield_points[0].yield_expr)
        }
        // Other types -> use as-is (backwards compatibility)
        other => other.clone(),
    };

    let rust_element_type = ctx.type_mapper.map_type(&element_type);
    rust_type_to_syn(&rust_element_type)
}

/// Infer type from a yield expression
///
/// DEPYLER-0769: Handle tuple yields and other composite expressions
/// to prevent undefined type `T` in generated code.
///
/// # Complexity: 4 (nested match + recursion for tuples)
#[inline]
fn infer_yield_type(expr: &HirExpr) -> Type {
    match expr {
        HirExpr::Literal(lit) => match lit {
            Literal::Int(_) => Type::Int,
            Literal::Float(_) => Type::Float,
            Literal::String(_) => Type::String,
            Literal::Bytes(_) => Type::Custom("bytes".to_string()),
            Literal::Bool(_) => Type::Bool,
            Literal::None => Type::None,
        },
        // DEPYLER-0769: Handle tuple yields like `yield a, b`
        // Recursively infer types for each element
        HirExpr::Tuple(elems) => {
            let elem_types: Vec<Type> = elems.iter().map(infer_yield_type).collect();
            Type::Tuple(elem_types)
        }
        // DEPYLER-0769: Default to String for variables without type info
        // String is safer than Int as it can represent most yield patterns
        HirExpr::Var(_) => Type::String,
        // For other expressions (calls, binary ops, etc.), default to String
        // which is a safer fallback than Unknown (which maps to undefined T)
        _ => Type::String,
    }
}

/// Generate field initializers for state variables (with default values)
///
/// Creates initialization expressions like `field_name: 0` or `field_name: false`.
///
/// # Complexity
/// 3 (iter + map + collect)
fn generate_state_initializers(state_info: &GeneratorStateInfo) -> Vec<proc_macro2::TokenStream> {
    state_info
        .state_variables
        .iter()
        .map(|var| {
            // DEPYLER-0562: Use safe_ident to escape keywords like 'match'
            let field_name = safe_ident(&var.name);
            // Initialize with type-appropriate default (0 for int, false for bool, etc.)
            let default_value = get_default_value_for_type(&var.ty);
            quote! { #field_name: #default_value }
        })
        .collect()
}

/// Generate field initializers for captured parameters
///
/// Creates initialization expressions like `field_name: field_name` to capture
/// the parameter value.
///
/// # Complexity
/// 4 (iter + filter + map + collect)
fn generate_param_initializers(
    func: &HirFunction,
    state_info: &GeneratorStateInfo,
) -> Vec<proc_macro2::TokenStream> {
    func.params
        .iter()
        .filter(|p| state_info.captured_params.contains(&p.name))
        .map(|param| {
            // DEPYLER-0562: Use safe_ident to escape keywords like 'match'
            let field_name = safe_ident(&param.name);

            // DEPYLER-0498: Dereference Option parameters (&Option<T> -> Option<T>)
            // DEPYLER-1078: Clone List/Dict/Set parameters (&Vec<T> -> Vec<T>)
            // DEPYLER-1079: Box Iterator/Generator parameters for struct fields
            // Five-Whys Root Cause: Parameters are borrowed but struct fields are owned
            // Solution: Dereference, clone, or box based on type
            let init_value = match &param.ty {
                // Option<T> implements Copy for Copy inner types - dereference
                Type::Optional(_) => quote! { *#field_name },
                // List/Vec - clone the reference to get owned value
                Type::List(_) => quote! { #field_name.clone() },
                // Dict/HashMap - clone the reference
                Type::Dict(_, _) => quote! { #field_name.clone() },
                // Set - clone the reference
                Type::Set(_) => quote! { #field_name.clone() },
                // String - clone the reference
                Type::String => quote! { #field_name.clone() },
                // DEPYLER-1082: Box impl Iterator/Generator parameters for struct fields
                // Struct fields are typed as Box<dyn Iterator> (via box_impl_trait_for_field)
                // so we must wrap the impl Trait parameter with Box::new() for type erasure
                Type::Generic { base, .. }
                    if base == "Iterator" || base == "Generator" || base == "Iterable" =>
                {
                    quote! { Box::new(#field_name) as _ }
                }
                // Other types - direct assignment (primitives implement Copy)
                _ => quote! { #field_name },
            };

            quote! { #field_name: #init_value }
        })
        .collect()
}

/// Get default value expression for Int type
///
/// # Complexity: 1
#[inline]
fn default_int() -> proc_macro2::TokenStream {
    quote! { 0 }
}

/// Get default value expression for Float type
///
/// # Complexity: 1
#[inline]
fn default_float() -> proc_macro2::TokenStream {
    quote! { 0.0 }
}

/// Get default value expression for Bool type
///
/// # Complexity: 1
#[inline]
fn default_bool() -> proc_macro2::TokenStream {
    quote! { false }
}

/// Get default value expression for String type
///
/// # Complexity: 1
#[inline]
fn default_string() -> proc_macro2::TokenStream {
    quote! { String::new() }
}

/// Get default value expression for other types
///
/// # Complexity: 1
#[inline]
fn default_generic() -> proc_macro2::TokenStream {
    quote! { Default::default() }
}

/// Get default value expression for a type
///
/// Returns appropriate default value based on HIR type.
///
/// # Complexity
/// 6 (match with 5 arms)
#[inline]
fn get_default_value_for_type(ty: &Type) -> proc_macro2::TokenStream {
    match ty {
        Type::Int => default_int(),
        Type::Float => default_float(),
        Type::Bool => default_bool(),
        Type::String => default_string(),
        _ => default_generic(),
    }
}

/// Generate state struct name by converting snake_case to PascalCase
///
/// DEPYLER-0259: Converts snake_case to PascalCase properly
/// Examples: count_up → CountUpState, counter → CounterState
///
/// # Complexity: 6 (within ≤10 target)
#[inline]
fn generate_state_struct_name(name: &syn::Ident) -> syn::Ident {
    let name_str = name.to_string();

    // DEPYLER-0259 FIX: Convert snake_case to PascalCase properly
    let pascal_case = name_str
        .split('_')
        .map(|word| {
            let mut chars = word.chars();
            match chars.next() {
                Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
                None => String::new(),
            }
        })
        .collect::<String>();

    let state_struct_name = format!("{}State", pascal_case);
    syn::Ident::new(&state_struct_name, name.span())
}

/// Populate generator state variables in context
///
/// # Complexity: 4 (clear + 2 loops + iterator check)
#[inline]
fn populate_generator_state_vars(
    ctx: &mut CodeGenContext,
    state_info: &GeneratorStateInfo,
    func: &HirFunction,
) {
    ctx.generator_state_vars.clear();
    ctx.generator_iterator_state_vars.clear();
    for var in &state_info.state_variables {
        ctx.generator_state_vars.insert(var.name.clone());
    }
    for param in &state_info.captured_params {
        ctx.generator_state_vars.insert(param.clone());
    }
    // DEPYLER-1082: Track which state vars have Iterator/Generator type
    // These need while-let iteration because Box<dyn Iterator> doesn't impl IntoIterator
    for param in &func.params {
        if matches!(&param.ty, Type::Generic { base, .. }
            if base == "Iterator" || base == "Generator" || base == "Iterable")
        {
            ctx.generator_iterator_state_vars.insert(param.name.clone());
        }
    }
}

/// Generate generator body statements with proper context flags
///
/// # Complexity: 4 (set flag + collect + clear flag + clear vars)
#[inline]
fn generate_generator_body(
    func: &HirFunction,
    ctx: &mut CodeGenContext,
) -> Result<Vec<proc_macro2::TokenStream>> {
    use crate::rust_gen::RustCodeGen;

    ctx.in_generator = true;
    let generator_body_stmts: Vec<_> = func
        .body
        .iter()
        .map(|stmt| stmt.to_rust_tokens(ctx))
        .collect::<Result<Vec<_>>>()?;
    ctx.in_generator = false;
    ctx.generator_state_vars.clear();
    ctx.generator_iterator_state_vars.clear();

    Ok(generator_body_stmts)
}

/// Convert HirExpr to syn::Expr for code generation
///
/// # Complexity: 1 (direct conversion)
#[inline]
fn hir_expr_to_syn(expr: &HirExpr, ctx: &mut CodeGenContext) -> Result<syn::Expr> {
    // Use the ToRustExpr trait to convert HIR expression to syn::Expr
    expr.to_rust_expr(ctx)
}

/// Generate multi-state match arms for sequential yields
///
/// DEPYLER-0262 Phase 3A: Transforms sequential yield points into proper state machine.
/// Each yield becomes a separate state with resumption at the next statement.
///
/// # Complexity: 5 (iterate yields + generate arms)
#[inline]
fn generate_simple_multi_state_match(
    yield_analysis: &YieldAnalysis,
    _func: &HirFunction,
    ctx: &mut CodeGenContext,
) -> Result<proc_macro2::TokenStream> {
    // DEPYLER-0263: Set generator context flag for proper variable scoping
    ctx.in_generator = true;

    let mut match_arms = Vec::new();

    // State 0: Initial state - execute up to first yield
    if let Some(first_yield) = yield_analysis.yield_points.first() {
        let yield_value = hir_expr_to_syn(&first_yield.yield_expr, ctx)?;
        let next_state = first_yield.state_id;

        match_arms.push(quote! {
            0 => {
                self.state = #next_state;
                return Some(#yield_value);
            }
        });
    }

    // Generate state for each yield point (states 1..N)
    for (idx, yield_point) in yield_analysis.yield_points.iter().enumerate() {
        let current_state = yield_point.state_id;

        // If there's a next yield, transition to it; otherwise go to terminal state
        if let Some(next_yield) = yield_analysis.yield_points.get(idx + 1) {
            let yield_value = hir_expr_to_syn(&next_yield.yield_expr, ctx)?;
            let next_state = next_yield.state_id;

            match_arms.push(quote! {
                #current_state => {
                    self.state = #next_state;
                    return Some(#yield_value);
                }
            });
        } else {
            // Last yield - transition to terminal state
            match_arms.push(quote! {
                #current_state => {
                    self.state = #current_state + 1;
                    None
                }
            });
        }
    }

    // Terminal state: generator exhausted
    match_arms.push(quote! {
        _ => None
    });

    // Clear generator context flag
    ctx.in_generator = false;

    Ok(quote! {
        match self.state {
            #(#match_arms)*
        }
    })
}

/// Generate loop with yield transformation
///
/// DEPYLER-0262 Phase 3B: Transforms simple loops with single yield into state machines.
/// Handles pattern: `while condition: yield value; increment`
///
/// Strategy:
/// - Extract loop from function body
/// - Generate initialization code (statements before loop)
/// - Generate loop state that checks condition and yields properly
///
/// # Complexity: 8 (within ≤10 target)
#[inline]
fn generate_simple_loop_with_yield(
    func: &HirFunction,
    yield_analysis: &YieldAnalysis,
    ctx: &mut CodeGenContext,
) -> Result<proc_macro2::TokenStream> {
    // DEPYLER-0263: Set generator context flag for proper variable scoping
    ctx.in_generator = true;

    // Find the loop statement in the function body
    let loop_info = extract_loop_info(func)?;

    // Generate initialization statements (before the loop)
    let init_stmts = generate_loop_init_stmts(&loop_info.pre_loop_stmts, ctx)?;

    // Get the yield expression
    let yield_point = &yield_analysis.yield_points[0];
    let yield_value = hir_expr_to_syn(&yield_point.yield_expr, ctx)?;

    // Extract loop condition
    let loop_condition = hir_expr_to_syn(&loop_info.condition, ctx)?;

    // Generate loop body statements (updates, increments)
    let loop_body_stmts = generate_loop_body_stmts(&loop_info.body_stmts, ctx)?;

    // Clear generator context flag
    ctx.in_generator = false;

    // Generate the state machine
    Ok(quote! {
        match self.state {
            0 => {
                // Initialize loop variables
                #(#init_stmts)*
                // Transition to loop state
                self.state = 1;
                // Check condition immediately
                self.next()
            }
            1 => {
                // Check loop condition
                if #loop_condition {
                    // Yield the value
                    let result = #yield_value;
                    // Execute loop body (increments, updates)
                    #(#loop_body_stmts)*
                    // Stay in state 1 (continue looping)
                    return Some(result);
                } else {
                    // Condition false - exit loop
                    self.state = 2;
                    None
                }
            }
            _ => None
        }
    })
}

/// Extract loop information from function body
///
/// # Complexity: 5
#[inline]
fn extract_loop_info(func: &HirFunction) -> Result<LoopInfo> {
    // Find the While statement in the body
    let mut pre_loop_stmts = Vec::new();
    let mut loop_stmt = None;

    for stmt in &func.body {
        match stmt {
            HirStmt::While { condition, body } => {
                loop_stmt = Some((condition.clone(), body.clone()));
                break;
            }
            _ => {
                // Statements before the loop (initialization)
                pre_loop_stmts.push(stmt.clone());
            }
        }
    }

    let (condition, body) =
        loop_stmt.ok_or_else(|| anyhow::anyhow!("No while loop found in generator function"))?;

    // Separate yield statement from other body statements
    let mut body_stmts = Vec::new();
    for stmt in &body {
        // Skip the yield statement itself - we'll handle it separately
        if !matches!(stmt, HirStmt::Expr(HirExpr::Yield { .. })) {
            body_stmts.push(stmt.clone());
        }
    }

    Ok(LoopInfo {
        pre_loop_stmts,
        condition,
        body_stmts,
    })
}

/// Loop information structure
struct LoopInfo {
    pre_loop_stmts: Vec<HirStmt>,
    condition: HirExpr,
    body_stmts: Vec<HirStmt>,
}

/// Generate initialization statements before loop
///
/// # Complexity: 2
#[inline]
fn generate_loop_init_stmts(
    stmts: &[HirStmt],
    ctx: &mut CodeGenContext,
) -> Result<Vec<proc_macro2::TokenStream>> {
    use crate::rust_gen::RustCodeGen;
    stmts.iter().map(|stmt| stmt.to_rust_tokens(ctx)).collect()
}

/// Generate loop body statements (after yield)
///
/// # Complexity: 2
#[inline]
fn generate_loop_body_stmts(
    stmts: &[HirStmt],
    ctx: &mut CodeGenContext,
) -> Result<Vec<proc_macro2::TokenStream>> {
    use crate::rust_gen::RustCodeGen;
    stmts.iter().map(|stmt| stmt.to_rust_tokens(ctx)).collect()
}

/// Generate complete generator function with state struct and Iterator impl
///
/// This is the main entry point for generator code generation. It:
/// 1. Analyzes generator state requirements
/// 2. Creates a state struct with captured variables
/// 3. Generates a constructor function
/// 4. Implements Iterator with state machine logic
///
/// # Arguments
/// * `func` - The HIR function to generate
/// * `name` - Function name identifier
/// * `generic_params` - Generic parameters token stream
/// * `where_clause` - Where clause token stream
/// * `params` - Parameter declarations
/// * `attrs` - Function attributes
/// * `rust_ret_type` - Return type
/// * `ctx` - Code generation context
///
/// # Returns
/// Complete generator implementation including state struct and Iterator impl
///
/// # Complexity
/// 5 (delegated to helper functions)
#[inline]
#[allow(clippy::too_many_arguments)] // Generator needs all metadata for complex transformation
pub fn codegen_generator_function(
    func: &HirFunction,
    name: &syn::Ident,
    generic_params: &proc_macro2::TokenStream,
    where_clause: &proc_macro2::TokenStream,
    params: &[proc_macro2::TokenStream],
    attrs: &[proc_macro2::TokenStream],
    _rust_ret_type: &crate::type_mapper::RustType,
    ctx: &mut CodeGenContext,
) -> Result<proc_macro2::TokenStream> {
    // DEPYLER-1082: Add 'static bound to impl Iterator params that will be boxed
    // When impl Iterator params are stored in struct fields as Box<dyn Iterator>,
    // they require 'static lifetime for the unsized coercion
    let params: Vec<proc_macro2::TokenStream> = params
        .iter()
        .map(|p| {
            let p_str = p.to_string();
            // Check if this param is impl Iterator without 'static
            if p_str.contains("impl Iterator") && !p_str.contains("'static") {
                // DEPYLER-1082: Add 'static bound for boxed iterator params
                // impl Iterator<Item=T> -> impl Iterator<Item=T> + 'static
                let modified = if p_str.contains(">") {
                    p_str.replace(">", "> + 'static")
                } else {
                    p_str.clone()
                };
                syn::parse_str(&modified).unwrap_or_else(|_| p.clone())
            } else {
                p.clone()
            }
        })
        .collect();

    // Analyze generator state requirements
    let state_info = GeneratorStateInfo::analyze(func);

    // DEPYLER-0262 Phase 2: Analyze yield points for state machine transformation
    let yield_analysis = YieldAnalysis::analyze(func);

    // DEPYLER-0262 Phase 3A: Check if we can use simple multi-state transformation
    let use_simple_multi_state =
        yield_analysis.has_yields() && yield_analysis.yield_points.iter().all(|yp| yp.depth == 0);

    // Generate state struct name
    let state_ident = generate_state_struct_name(name);

    // Build state struct fields from analysis
    let state_fields = generate_state_fields(&state_info, ctx)?;
    let param_fields = generate_param_fields(func, &state_info, ctx)?;
    let all_fields = [state_fields, param_fields].concat();

    // Build field initializers
    let state_inits = generate_state_initializers(&state_info);
    let param_inits = generate_param_initializers(func, &state_info);
    let all_inits = [state_inits, param_inits].concat();

    // Generate state machine field
    let state_machine_field = quote! {
        state: usize
    };

    // DEPYLER-0263: Extract yield value type, inferring from yield expressions if needed
    let item_type = extract_generator_item_type(func, &yield_analysis, ctx)?;

    // DEPYLER-0494 FIX: Populate generator state variables BEFORE generating state machine
    // This ensures ctx.generator_state_vars is available when codegen_assign_tuple() is called
    populate_generator_state_vars(ctx, &state_info, func);

    // DEPYLER-0262 Phase 3B: Check if we have simple loop with yield pattern
    let has_while_loop = func
        .body
        .iter()
        .any(|stmt| matches!(stmt, HirStmt::While { .. }));
    let has_loop_yields =
        yield_analysis.has_yields() && yield_analysis.yield_points.iter().any(|yp| yp.depth > 0);

    // Generate state machine implementation based on yield analysis
    let state_machine_impl = if use_simple_multi_state {
        // DEPYLER-0262 Phase 3A: Multi-state transformation for sequential yields
        generate_simple_multi_state_match(&yield_analysis, func, ctx)?
    } else if has_while_loop && has_loop_yields && yield_analysis.yield_points.len() == 1 {
        // DEPYLER-0262 Phase 3B: Simple loop with single yield pattern
        generate_simple_loop_with_yield(func, &yield_analysis, ctx)?
    } else {
        // Fallback: Single-state implementation (for complex cases or no yields)
        let generator_body_stmts = generate_generator_body(func, ctx)?;
        quote! {
            match self.state {
                0 => {
                    self.state = 1;
                    // Execute generator body with early-exit semantics
                    #(#generator_body_stmts)*
                    None
                }
                _ => None
            }
        }
    };

    // DEPYLER-1082: Check if we need manual Debug impl (Box<dyn Iterator> doesn't impl Debug)
    let has_iterator_fields = func.params.iter().any(|p| {
        matches!(&p.ty, Type::Generic { base, .. }
            if base == "Iterator" || base == "Generator" || base == "Iterable")
    });

    // Generate the complete generator implementation
    let debug_impl = if has_iterator_fields {
        // DEPYLER-1082: Manual Debug impl for structs with Box<dyn Iterator> fields
        // Box<dyn Iterator> doesn't implement Debug, so we print a placeholder
        quote! {
            impl std::fmt::Debug for #state_ident {
                fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                    f.debug_struct(stringify!(#state_ident))
                        .field("state", &self.state)
                        .finish_non_exhaustive()
                }
            }
        }
    } else {
        // No iterator fields - can derive Debug normally
        quote! {}
    };

    let derive_debug = if has_iterator_fields {
        quote! {} // No derive, use manual impl
    } else {
        quote! { #[derive(Debug)] }
    };

    Ok(quote! {
        #(#attrs)*
        #[doc = " Generator state struct"]
        #derive_debug
        struct #state_ident {
            #state_machine_field,
            #(#all_fields),*
        }

        #debug_impl

        #[doc = " Generator function - returns Iterator"]
        pub fn #name #generic_params(#(#params),*) -> impl Iterator<Item = #item_type> #where_clause {
            #state_ident {
                state: 0,
                #(#all_inits),*
            }
        }

        impl Iterator for #state_ident {
            type Item = #item_type;

            fn next(&mut self) -> Option<Self::Item> {
                #state_machine_impl
            }
        }
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::type_mapper::{PrimitiveType, RustType};

    // ============================================================
    // generate_state_struct_name tests
    // ============================================================

    #[test]
    #[allow(non_snake_case)]
    fn test_depyler_0259_snake_case_to_pascal_case_naming() {
        let input_name = syn::Ident::new("count_up", proc_macro2::Span::call_site());
        let result = generate_state_struct_name(&input_name);
        assert_eq!(result.to_string(), "CountUpState");
    }

    #[test]
    #[allow(non_snake_case)]
    fn test_depyler_0259_single_word_naming() {
        let input_name = syn::Ident::new("counter", proc_macro2::Span::call_site());
        let result = generate_state_struct_name(&input_name);
        assert_eq!(result.to_string(), "CounterState");
    }

    #[test]
    #[allow(non_snake_case)]
    fn test_depyler_0259_multiple_words_naming() {
        let input_name = syn::Ident::new(
            "fibonacci_generator_with_memo",
            proc_macro2::Span::call_site(),
        );
        let result = generate_state_struct_name(&input_name);
        assert_eq!(result.to_string(), "FibonacciGeneratorWithMemoState");
    }

    #[test]
    fn test_generate_state_struct_name_empty_parts() {
        // Test with double underscore (edge case)
        let input_name = syn::Ident::new("a__b", proc_macro2::Span::call_site());
        let result = generate_state_struct_name(&input_name);
        // Empty parts become empty strings in PascalCase
        assert_eq!(result.to_string(), "ABState");
    }

    #[test]
    fn test_generate_state_struct_name_leading_underscore() {
        let input_name = syn::Ident::new("_private_gen", proc_macro2::Span::call_site());
        let result = generate_state_struct_name(&input_name);
        assert_eq!(result.to_string(), "PrivateGenState");
    }

    #[test]
    fn test_generate_state_struct_name_all_caps() {
        let input_name = syn::Ident::new("HTTP_GEN", proc_macro2::Span::call_site());
        let result = generate_state_struct_name(&input_name);
        // DEPYLER capitalizes first letter, keeps rest
        assert_eq!(result.to_string(), "HTTPGENState");
    }

    // ============================================================
    // concretize_type_param_for_struct tests
    // ============================================================

    #[test]
    fn test_concretize_type_param_converts_to_i32() {
        let type_param = RustType::TypeParam("T".to_string());
        let result = concretize_type_param_for_struct(&type_param);
        assert!(matches!(result, RustType::Primitive(PrimitiveType::I32)));
    }

    #[test]
    fn test_concretize_type_param_preserves_primitives() {
        let int_type = RustType::Primitive(PrimitiveType::I64);
        let result = concretize_type_param_for_struct(&int_type);
        assert!(matches!(result, RustType::Primitive(PrimitiveType::I64)));
    }

    #[test]
    fn test_concretize_type_param_preserves_string() {
        let string_type = RustType::String;
        let result = concretize_type_param_for_struct(&string_type);
        assert!(matches!(result, RustType::String));
    }

    #[test]
    fn test_concretize_type_param_preserves_vec() {
        let vec_type = RustType::Vec(Box::new(RustType::Primitive(PrimitiveType::I32)));
        let result = concretize_type_param_for_struct(&vec_type);
        assert!(matches!(result, RustType::Vec(_)));
    }

    #[test]
    fn test_concretize_type_param_preserves_option() {
        let opt_type = RustType::Option(Box::new(RustType::String));
        let result = concretize_type_param_for_struct(&opt_type);
        assert!(matches!(result, RustType::Option(_)));
    }

    #[test]
    fn test_concretize_type_param_preserves_custom() {
        let custom_type = RustType::Custom("MyType".to_string());
        let result = concretize_type_param_for_struct(&custom_type);
        assert!(matches!(result, RustType::Custom(s) if s == "MyType"));
    }

    // ============================================================
    // box_impl_trait_for_field tests
    // ============================================================

    #[test]
    fn test_box_impl_iterator_trait() {
        let impl_iter = RustType::Custom("impl Iterator<Item=i32>".to_string());
        let result = box_impl_trait_for_field(&impl_iter);
        match result {
            RustType::Custom(s) => assert_eq!(s, "Box<dyn Iterator<Item=i32>>"),
            _ => panic!("Expected Custom type"),
        }
    }

    #[test]
    fn test_box_impl_into_iterator_trait() {
        let impl_into_iter = RustType::Custom("impl IntoIterator<Item=String>".to_string());
        let result = box_impl_trait_for_field(&impl_into_iter);
        match result {
            RustType::Custom(s) => assert_eq!(s, "Box<dyn IntoIterator<Item=String>>"),
            _ => panic!("Expected Custom type"),
        }
    }

    #[test]
    fn test_box_impl_trait_preserves_non_impl() {
        let regular_type = RustType::Custom("Vec<i32>".to_string());
        let result = box_impl_trait_for_field(&regular_type);
        match result {
            RustType::Custom(s) => assert_eq!(s, "Vec<i32>"),
            _ => panic!("Expected Custom type"),
        }
    }

    #[test]
    fn test_box_impl_trait_preserves_primitives() {
        let int_type = RustType::Primitive(PrimitiveType::I32);
        let result = box_impl_trait_for_field(&int_type);
        assert!(matches!(result, RustType::Primitive(PrimitiveType::I32)));
    }

    #[test]
    fn test_box_impl_trait_preserves_string() {
        let string_type = RustType::String;
        let result = box_impl_trait_for_field(&string_type);
        assert!(matches!(result, RustType::String));
    }

    // ============================================================
    // default value helper tests
    // ============================================================

    #[test]
    fn test_default_int() {
        let result = default_int();
        assert_eq!(result.to_string(), "0");
    }

    #[test]
    fn test_default_float() {
        let result = default_float();
        assert_eq!(result.to_string(), "0.0");
    }

    #[test]
    fn test_default_bool() {
        let result = default_bool();
        assert_eq!(result.to_string(), "false");
    }

    #[test]
    fn test_default_string() {
        let result = default_string();
        assert_eq!(result.to_string(), "String :: new ()");
    }

    #[test]
    fn test_default_generic() {
        let result = default_generic();
        assert_eq!(result.to_string(), "Default :: default ()");
    }

    // ============================================================
    // get_default_value_for_type tests
    // ============================================================

    #[test]
    fn test_get_default_value_int() {
        let result = get_default_value_for_type(&Type::Int);
        assert_eq!(result.to_string(), "0");
    }

    #[test]
    fn test_get_default_value_float() {
        let result = get_default_value_for_type(&Type::Float);
        assert_eq!(result.to_string(), "0.0");
    }

    #[test]
    fn test_get_default_value_bool() {
        let result = get_default_value_for_type(&Type::Bool);
        assert_eq!(result.to_string(), "false");
    }

    #[test]
    fn test_get_default_value_string() {
        let result = get_default_value_for_type(&Type::String);
        assert_eq!(result.to_string(), "String :: new ()");
    }

    #[test]
    fn test_get_default_value_unknown() {
        let result = get_default_value_for_type(&Type::Unknown);
        assert_eq!(result.to_string(), "Default :: default ()");
    }

    #[test]
    fn test_get_default_value_list() {
        let result = get_default_value_for_type(&Type::List(Box::new(Type::Int)));
        assert_eq!(result.to_string(), "Default :: default ()");
    }

    #[test]
    fn test_get_default_value_optional() {
        let result = get_default_value_for_type(&Type::Optional(Box::new(Type::Int)));
        assert_eq!(result.to_string(), "Default :: default ()");
    }

    #[test]
    fn test_get_default_value_tuple() {
        let result = get_default_value_for_type(&Type::Tuple(vec![Type::Int, Type::Bool]));
        assert_eq!(result.to_string(), "Default :: default ()");
    }

    #[test]
    fn test_get_default_value_none() {
        let result = get_default_value_for_type(&Type::None);
        assert_eq!(result.to_string(), "Default :: default ()");
    }

    // ============================================================
    // infer_yield_type tests
    // ============================================================

    #[test]
    fn test_infer_yield_type_int_literal() {
        let expr = HirExpr::Literal(Literal::Int(42));
        let result = infer_yield_type(&expr);
        assert!(matches!(result, Type::Int));
    }

    #[test]
    fn test_infer_yield_type_float_literal() {
        let expr = HirExpr::Literal(Literal::Float(3.15));
        let result = infer_yield_type(&expr);
        assert!(matches!(result, Type::Float));
    }

    #[test]
    fn test_infer_yield_type_string_literal() {
        let expr = HirExpr::Literal(Literal::String("hello".to_string()));
        let result = infer_yield_type(&expr);
        assert!(matches!(result, Type::String));
    }

    #[test]
    fn test_infer_yield_type_bool_literal() {
        let expr = HirExpr::Literal(Literal::Bool(true));
        let result = infer_yield_type(&expr);
        assert!(matches!(result, Type::Bool));
    }

    #[test]
    fn test_infer_yield_type_none_literal() {
        let expr = HirExpr::Literal(Literal::None);
        let result = infer_yield_type(&expr);
        assert!(matches!(result, Type::None));
    }

    #[test]
    fn test_infer_yield_type_bytes_literal() {
        let expr = HirExpr::Literal(Literal::Bytes(vec![0u8, 1, 2]));
        let result = infer_yield_type(&expr);
        assert!(matches!(result, Type::Custom(s) if s == "bytes"));
    }

    #[test]
    fn test_infer_yield_type_tuple() {
        let expr = HirExpr::Tuple(vec![
            HirExpr::Literal(Literal::Int(1)),
            HirExpr::Literal(Literal::String("hello".to_string())),
        ]);
        let result = infer_yield_type(&expr);
        match result {
            Type::Tuple(types) => {
                assert_eq!(types.len(), 2);
                assert!(matches!(types[0], Type::Int));
                assert!(matches!(types[1], Type::String));
            }
            _ => panic!("Expected Tuple type"),
        }
    }

    #[test]
    fn test_infer_yield_type_var() {
        let expr = HirExpr::Var("x".to_string());
        let result = infer_yield_type(&expr);
        // Variables default to String (safer than Unknown)
        assert!(matches!(result, Type::String));
    }

    #[test]
    fn test_infer_yield_type_binary_op() {
        let expr = HirExpr::Binary {
            op: crate::hir::BinOp::Add,
            left: Box::new(HirExpr::Literal(Literal::Int(1))),
            right: Box::new(HirExpr::Literal(Literal::Int(2))),
        };
        let result = infer_yield_type(&expr);
        // Binary ops default to String (catch-all)
        assert!(matches!(result, Type::String));
    }

    #[test]
    fn test_infer_yield_type_call() {
        let expr = HirExpr::Call {
            func: "foo".to_string(),
            args: vec![],
            kwargs: vec![],
        };
        let result = infer_yield_type(&expr);
        // Calls default to String
        assert!(matches!(result, Type::String));
    }

    #[test]
    fn test_infer_yield_type_nested_tuple() {
        let expr = HirExpr::Tuple(vec![
            HirExpr::Tuple(vec![
                HirExpr::Literal(Literal::Int(1)),
                HirExpr::Literal(Literal::Int(2)),
            ]),
            HirExpr::Literal(Literal::Bool(true)),
        ]);
        let result = infer_yield_type(&expr);
        match result {
            Type::Tuple(types) => {
                assert_eq!(types.len(), 2);
                match &types[0] {
                    Type::Tuple(inner) => {
                        assert_eq!(inner.len(), 2);
                        assert!(matches!(inner[0], Type::Int));
                        assert!(matches!(inner[1], Type::Int));
                    }
                    _ => panic!("Expected nested Tuple"),
                }
                assert!(matches!(types[1], Type::Bool));
            }
            _ => panic!("Expected Tuple type"),
        }
    }

    // ============================================================
    // LoopInfo tests (via extract_loop_info)
    // ============================================================

    #[test]
    fn test_loop_info_struct_fields() {
        // LoopInfo struct has pre_loop_stmts, condition, body_stmts
        let loop_info = LoopInfo {
            pre_loop_stmts: vec![],
            condition: HirExpr::Literal(Literal::Bool(true)),
            body_stmts: vec![],
        };
        assert!(loop_info.pre_loop_stmts.is_empty());
        assert!(loop_info.body_stmts.is_empty());
    }

    // ============================================================
    // populate_generator_state_vars tests
    // ============================================================

    // Helper function to create empty HirFunction for tests
    fn empty_hir_function() -> HirFunction {
        use crate::hir::FunctionProperties;
        use depyler_annotations::TranspilationAnnotations;
        use smallvec::smallvec;
        HirFunction {
            name: "test".to_string(),
            params: smallvec![],
            body: vec![],
            ret_type: Type::Unknown,
            properties: FunctionProperties::default(),
            annotations: TranspilationAnnotations::default(),
            docstring: None,
        }
    }

    #[test]
    fn test_populate_generator_state_vars_empty() {
        let mut ctx = CodeGenContext::default();
        let state_info = GeneratorStateInfo {
            state_variables: vec![],
            captured_params: vec![],
            yield_count: 0,
            has_loops: false,
        };
        populate_generator_state_vars(&mut ctx, &state_info, &empty_hir_function());
        assert!(ctx.generator_state_vars.is_empty());
    }

    #[test]
    fn test_populate_generator_state_vars_with_state() {
        use crate::generator_state::StateVariable;
        let mut ctx = CodeGenContext::default();
        let state_info = GeneratorStateInfo {
            state_variables: vec![StateVariable {
                name: "counter".to_string(),
                ty: Type::Int,
            }],
            captured_params: vec![],
            yield_count: 1,
            has_loops: false,
        };
        populate_generator_state_vars(&mut ctx, &state_info, &empty_hir_function());
        assert!(ctx.generator_state_vars.contains("counter"));
        assert_eq!(ctx.generator_state_vars.len(), 1);
    }

    #[test]
    fn test_populate_generator_state_vars_with_params() {
        let mut ctx = CodeGenContext::default();
        let state_info = GeneratorStateInfo {
            state_variables: vec![],
            captured_params: vec!["n".to_string(), "limit".to_string()],
            yield_count: 1,
            has_loops: true,
        };
        populate_generator_state_vars(&mut ctx, &state_info, &empty_hir_function());
        assert!(ctx.generator_state_vars.contains("n"));
        assert!(ctx.generator_state_vars.contains("limit"));
        assert_eq!(ctx.generator_state_vars.len(), 2);
    }

    #[test]
    fn test_populate_generator_state_vars_mixed() {
        use crate::generator_state::StateVariable;
        let mut ctx = CodeGenContext::default();
        let state_info = GeneratorStateInfo {
            state_variables: vec![
                StateVariable {
                    name: "i".to_string(),
                    ty: Type::Int,
                },
                StateVariable {
                    name: "acc".to_string(),
                    ty: Type::Float,
                },
            ],
            captured_params: vec!["start".to_string()],
            yield_count: 2,
            has_loops: true,
        };
        populate_generator_state_vars(&mut ctx, &state_info, &empty_hir_function());
        assert!(ctx.generator_state_vars.contains("i"));
        assert!(ctx.generator_state_vars.contains("acc"));
        assert!(ctx.generator_state_vars.contains("start"));
        assert_eq!(ctx.generator_state_vars.len(), 3);
    }

    #[test]
    fn test_populate_generator_state_vars_clears_previous() {
        use crate::generator_state::StateVariable;
        let mut ctx = CodeGenContext::default();
        ctx.generator_state_vars.insert("old_var".to_string());

        let state_info = GeneratorStateInfo {
            state_variables: vec![StateVariable {
                name: "new_var".to_string(),
                ty: Type::Int,
            }],
            captured_params: vec![],
            yield_count: 1,
            has_loops: false,
        };
        populate_generator_state_vars(&mut ctx, &state_info, &empty_hir_function());
        assert!(!ctx.generator_state_vars.contains("old_var"));
        assert!(ctx.generator_state_vars.contains("new_var"));
        assert_eq!(ctx.generator_state_vars.len(), 1);
    }

    // ============================================================
    // Edge case tests
    // ============================================================

    #[test]
    fn test_box_impl_trait_iterator_without_item() {
        let impl_iter = RustType::Custom("impl Iterator".to_string());
        let result = box_impl_trait_for_field(&impl_iter);
        match result {
            RustType::Custom(s) => assert_eq!(s, "Box<dyn Iterator>"),
            _ => panic!("Expected Custom type"),
        }
    }

    #[test]
    fn test_infer_yield_type_empty_tuple() {
        let expr = HirExpr::Tuple(vec![]);
        let result = infer_yield_type(&expr);
        match result {
            Type::Tuple(types) => assert!(types.is_empty()),
            _ => panic!("Expected empty Tuple type"),
        }
    }

    #[test]
    fn test_infer_yield_type_attribute_access() {
        let expr = HirExpr::Attribute {
            value: Box::new(HirExpr::Var("obj".to_string())),
            attr: "field".to_string(),
        };
        let result = infer_yield_type(&expr);
        // Attribute access defaults to String (catch-all)
        assert!(matches!(result, Type::String));
    }

    #[test]
    fn test_infer_yield_type_subscript() {
        let expr = HirExpr::Index {
            base: Box::new(HirExpr::Var("arr".to_string())),
            index: Box::new(HirExpr::Literal(Literal::Int(0))),
        };
        let result = infer_yield_type(&expr);
        // Index access defaults to String (catch-all)
        assert!(matches!(result, Type::String));
    }

    #[test]
    fn test_generate_state_struct_name_trailing_underscore() {
        let input_name = syn::Ident::new("gen_", proc_macro2::Span::call_site());
        let result = generate_state_struct_name(&input_name);
        assert_eq!(result.to_string(), "GenState");
    }

    #[test]
    fn test_concretize_preserves_result() {
        let result_type = RustType::Result(
            Box::new(RustType::String),
            Box::new(RustType::Custom("Error".to_string())),
        );
        let result = concretize_type_param_for_struct(&result_type);
        assert!(matches!(result, RustType::Result(_, _)));
    }

    #[test]
    fn test_concretize_preserves_hashmap() {
        let map_type = RustType::HashMap(
            Box::new(RustType::String),
            Box::new(RustType::Primitive(PrimitiveType::I32)),
        );
        let result = concretize_type_param_for_struct(&map_type);
        assert!(matches!(result, RustType::HashMap(_, _)));
    }

    #[test]
    fn test_concretize_type_param_u() {
        // TypeParam with different name
        let type_param = RustType::TypeParam("U".to_string());
        let result = concretize_type_param_for_struct(&type_param);
        assert!(matches!(result, RustType::Primitive(PrimitiveType::I32)));
    }

    #[test]
    fn test_get_default_value_dict() {
        let result =
            get_default_value_for_type(&Type::Dict(Box::new(Type::String), Box::new(Type::Int)));
        assert_eq!(result.to_string(), "Default :: default ()");
    }

    #[test]
    fn test_get_default_value_set() {
        let result = get_default_value_for_type(&Type::Set(Box::new(Type::Int)));
        assert_eq!(result.to_string(), "Default :: default ()");
    }

    #[test]
    fn test_get_default_value_custom() {
        let result = get_default_value_for_type(&Type::Custom("MyType".to_string()));
        assert_eq!(result.to_string(), "Default :: default ()");
    }

    #[test]
    fn test_get_default_value_generic() {
        let result = get_default_value_for_type(&Type::Generic {
            base: "Iterator".to_string(),
            params: vec![Type::Int],
        });
        assert_eq!(result.to_string(), "Default :: default ()");
    }

    #[test]
    fn test_infer_yield_type_unary_op() {
        let expr = HirExpr::Unary {
            op: crate::hir::UnaryOp::Neg,
            operand: Box::new(HirExpr::Literal(Literal::Int(5))),
        };
        let result = infer_yield_type(&expr);
        // UnaryOp defaults to String
        assert!(matches!(result, Type::String));
    }

    #[test]
    fn test_infer_yield_type_list() {
        let expr = HirExpr::List(vec![
            HirExpr::Literal(Literal::Int(1)),
            HirExpr::Literal(Literal::Int(2)),
        ]);
        let result = infer_yield_type(&expr);
        // List defaults to String (catch-all for complex expressions)
        assert!(matches!(result, Type::String));
    }

    #[test]
    fn test_infer_yield_type_dict() {
        let expr = HirExpr::Dict(vec![(
            HirExpr::Literal(Literal::String("key".to_string())),
            HirExpr::Literal(Literal::Int(1)),
        )]);
        let result = infer_yield_type(&expr);
        // Dict defaults to String
        assert!(matches!(result, Type::String));
    }

    #[test]
    fn test_box_impl_trait_impl_clone() {
        // Other impl Trait types are not boxed
        let impl_clone = RustType::Custom("impl Clone".to_string());
        let result = box_impl_trait_for_field(&impl_clone);
        match result {
            RustType::Custom(s) => assert_eq!(s, "impl Clone"),
            _ => panic!("Expected Custom type"),
        }
    }

    #[test]
    fn test_generate_state_struct_name_numeric_suffix() {
        let input_name = syn::Ident::new("gen_v2", proc_macro2::Span::call_site());
        let result = generate_state_struct_name(&input_name);
        assert_eq!(result.to_string(), "GenV2State");
    }

    #[test]
    fn test_generate_state_struct_name_single_char() {
        let input_name = syn::Ident::new("g", proc_macro2::Span::call_site());
        let result = generate_state_struct_name(&input_name);
        assert_eq!(result.to_string(), "GState");
    }

    // ============================================================
    // Transpile-based generator tests (DEPYLER-COVERAGE-GEN)
    // ============================================================

    /// Helper function for transpile-based tests
    fn transpile(python_code: &str) -> String {
        use crate::ast_bridge::AstBridge;
        use crate::rust_gen::generate_rust_file;
        use crate::type_mapper::TypeMapper;
        use rustpython_parser::{parse, Mode};
        let ast = parse(python_code, Mode::Module, "<test>").expect("parse");
        let (module, _) = AstBridge::new()
            .with_source(python_code.to_string())
            .python_to_hir(ast)
            .expect("hir");
        let tm = TypeMapper::default();
        let (result, _) = generate_rust_file(&module, &tm).expect("codegen");
        result
    }

    // --- Basic yield ---

    #[test]
    fn test_transpile_simple_yield_generates_iterator() {
        let code = "def gen():\n    yield 1";
        let rust = transpile(code);
        assert!(rust.contains("impl Iterator"), "should implement Iterator");
        assert!(rust.contains("fn next("), "should have next() method");
    }

    #[test]
    fn test_transpile_simple_yield_generates_state_struct() {
        let code = "def gen():\n    yield 1";
        let rust = transpile(code);
        assert!(
            rust.contains("GenState"),
            "should create PascalCase state struct: got {}",
            rust
        );
        assert!(rust.contains("state:"), "state struct should have state field");
    }

    #[test]
    fn test_transpile_yield_int_literal_item_type() {
        let code = "def gen():\n    yield 42";
        let rust = transpile(code);
        assert!(
            rust.contains("Item = i64") || rust.contains("Item = i32"),
            "yield int should produce integer Item type: got {}",
            rust
        );
    }

    #[test]
    fn test_transpile_yield_string_literal_item_type() {
        let code = "def gen():\n    yield 'hello'";
        let rust = transpile(code);
        assert!(
            rust.contains("Item = String"),
            "yield str should produce String Item type: got {}",
            rust
        );
    }

    #[test]
    fn test_transpile_multiple_yields_state_machine() {
        let code = "def gen():\n    yield 1\n    yield 2\n    yield 3";
        let rust = transpile(code);
        assert!(
            rust.contains("self.state"),
            "multiple yields should produce state machine: got {}",
            rust
        );
        assert!(
            rust.contains("match"),
            "state machine should use match: got {}",
            rust
        );
    }

    #[test]
    fn test_transpile_multiple_yields_returns_none_when_exhausted() {
        let code = "def gen():\n    yield 1\n    yield 2";
        let rust = transpile(code);
        assert!(
            rust.contains("None"),
            "exhausted generator should return None: got {}",
            rust
        );
    }

    #[test]
    fn test_transpile_yield_produces_some() {
        let code = "def gen():\n    yield 10";
        let rust = transpile(code);
        assert!(
            rust.contains("Some("),
            "yield should produce Some(...): got {}",
            rust
        );
    }

    // --- Yield from ---

    #[test]
    fn test_transpile_yield_from_list() {
        let code = "def gen():\n    yield from [1, 2, 3]";
        let rust = transpile(code);
        // yield from should either use into_iter/chain or flatten pattern
        assert!(
            rust.contains("iter") || rust.contains("Iterator") || rust.contains("into_iter"),
            "yield from list should use iteration: got {}",
            rust
        );
    }

    #[test]
    fn test_transpile_yield_from_range() {
        let code = "def gen():\n    yield from range(5)";
        let rust = transpile(code);
        assert!(
            rust.contains("Iterator") || rust.contains("iter"),
            "yield from range should produce iterator code: got {}",
            rust
        );
    }

    #[test]
    fn test_transpile_yield_from_generator() {
        let code = "def inner():\n    yield 1\n\ndef outer():\n    yield from inner()";
        let rust = transpile(code);
        assert!(
            rust.contains("InnerState") || rust.contains("inner"),
            "yield from generator should reference inner gen: got {}",
            rust
        );
        assert!(
            rust.contains("OuterState") || rust.contains("outer"),
            "yield from should produce outer state struct: got {}",
            rust
        );
    }

    // --- Generator expressions ---

    #[test]
    fn test_transpile_generator_expression_simple() {
        let code = "result = (x for x in range(10))";
        let rust = transpile(code);
        assert!(
            rust.contains("map") || rust.contains("iter") || rust.contains("filter"),
            "genexpr should use iterator combinators: got {}",
            rust
        );
    }

    #[test]
    fn test_transpile_generator_expression_with_filter() {
        let code = "result = (x for x in range(10) if x > 5)";
        let rust = transpile(code);
        assert!(
            rust.contains("filter") || rust.contains("if") || rust.contains("> 5"),
            "filtered genexpr should have condition: got {}",
            rust
        );
    }

    #[test]
    fn test_transpile_generator_expression_with_transform() {
        let code = "result = (x * 2 for x in range(10))";
        let rust = transpile(code);
        assert!(
            rust.contains("map") || rust.contains("* 2"),
            "transform genexpr should apply mapping: got {}",
            rust
        );
    }

    // --- Generator with return value ---

    #[test]
    fn test_transpile_generator_early_return_empty() {
        let code = "def gen(n):\n    if n < 0:\n        return\n    yield n";
        let rust = transpile(code);
        assert!(
            rust.contains("None") || rust.contains("return"),
            "early return in generator should map to None: got {}",
            rust
        );
    }

    #[test]
    fn test_transpile_generator_with_return_produces_struct() {
        let code = "def gen():\n    yield 1\n    return";
        let rust = transpile(code);
        assert!(
            rust.contains("GenState"),
            "generator with return should still produce state struct: got {}",
            rust
        );
    }

    // --- Generator with state variables ---

    #[test]
    fn test_transpile_generator_with_accumulator() {
        let code =
            "def gen(n: int):\n    total = 0\n    for i in range(n):\n        total += i\n        yield total";
        let rust = transpile(code);
        assert!(
            rust.contains("GenState"),
            "generator should create state struct: got {}",
            rust
        );
        assert!(
            rust.contains("impl Iterator"),
            "should implement Iterator: got {}",
            rust
        );
    }

    #[test]
    fn test_transpile_generator_fibonacci() {
        let code = "def fib(n):\n    a, b = 0, 1\n    for _ in range(n):\n        yield a\n        a, b = b, a + b";
        let rust = transpile(code);
        assert!(
            rust.contains("FibState"),
            "fibonacci gen should produce FibState: got {}",
            rust
        );
    }

    // --- Generator with while loops ---

    #[test]
    fn test_transpile_while_loop_generator() {
        let code = "def gen():\n    i = 0\n    while i < 5:\n        yield i\n        i += 1";
        let rust = transpile(code);
        assert!(
            rust.contains("self.state"),
            "while loop gen should produce state machine: got {}",
            rust
        );
    }

    #[test]
    fn test_transpile_infinite_generator() {
        let code =
            "def count(start: int = 0):\n    n = start\n    while True:\n        yield n\n        n += 1";
        let rust = transpile(code);
        assert!(
            rust.contains("CountState"),
            "infinite gen should produce CountState: got {}",
            rust
        );
        assert!(
            rust.contains("impl Iterator"),
            "should implement Iterator: got {}",
            rust
        );
    }

    // --- Generator with parameters ---

    #[test]
    fn test_transpile_generator_single_typed_param() {
        let code = "def gen(n: int):\n    for i in range(n):\n        yield i";
        let rust = transpile(code);
        assert!(
            rust.contains("n:") || rust.contains("n :"),
            "should capture param n: got {}",
            rust
        );
    }

    #[test]
    fn test_transpile_generator_multiple_params() {
        let code = "def gen(start: int, end: int):\n    i = start\n    while i < end:\n        yield i\n        i += 1";
        let rust = transpile(code);
        assert!(
            rust.contains("GenState"),
            "multi-param generator should produce state struct: got {}",
            rust
        );
    }

    // --- Generator with conditionals ---

    #[test]
    fn test_transpile_generator_with_if_filter() {
        let code =
            "def gen(n: int):\n    for i in range(n):\n        if i % 2 == 0:\n            yield i";
        let rust = transpile(code);
        assert!(
            rust.contains("% 2") || rust.contains("== 0"),
            "conditional generator should have modulo check: got {}",
            rust
        );
    }

    #[test]
    fn test_transpile_generator_if_else_yield() {
        let code = "def gen(n: int):\n    for i in range(n):\n        if i > 5:\n            yield i\n        else:\n            yield 0";
        let rust = transpile(code);
        assert!(
            rust.contains("if") && rust.contains("else"),
            "if/else generator should preserve conditional: got {}",
            rust
        );
    }

    // --- Nested generators ---

    #[test]
    fn test_transpile_nested_loop_generator() {
        let code = "def gen(rows: int, cols: int):\n    for i in range(rows):\n        for j in range(cols):\n            yield (i, j)";
        let rust = transpile(code);
        assert!(
            rust.contains("GenState"),
            "nested loop gen should produce state struct: got {}",
            rust
        );
    }

    #[test]
    fn test_transpile_generator_pipeline() {
        let code =
            "def gen1():\n    yield 1\n    yield 2\n\ndef gen2():\n    for x in gen1():\n        yield x * 2";
        let rust = transpile(code);
        assert!(
            rust.contains("Gen1State") || rust.contains("Gen1"),
            "pipeline should produce Gen1State: got {}",
            rust
        );
        assert!(
            rust.contains("Gen2State") || rust.contains("Gen2"),
            "pipeline should produce Gen2State: got {}",
            rust
        );
    }

    // --- Generator with try/except ---

    #[test]
    fn test_transpile_generator_with_try_except() {
        let code = "def gen(items):\n    for item in items:\n        try:\n            yield int(item)\n        except:\n            pass";
        let rust = transpile(code);
        assert!(
            rust.contains("GenState"),
            "try/except gen should produce state struct: got {}",
            rust
        );
    }

    // --- Type annotations on generators ---

    #[test]
    fn test_transpile_iterator_int_return_type() {
        let code =
            "from typing import Iterator\n\ndef gen() -> Iterator[int]:\n    yield 1\n    yield 2";
        let rust = transpile(code);
        assert!(
            rust.contains("i64") || rust.contains("i32"),
            "Iterator[int] should produce integer type: got {}",
            rust
        );
    }

    #[test]
    fn test_transpile_iterator_str_return_type() {
        let code =
            "from typing import Iterator\n\ndef gen() -> Iterator[str]:\n    yield 'hello'";
        let rust = transpile(code);
        assert!(
            rust.contains("String"),
            "Iterator[str] should produce String type: got {}",
            rust
        );
    }

    // --- State struct naming ---

    #[test]
    fn test_transpile_snake_case_generator_name() {
        let code = "def count_up():\n    yield 1";
        let rust = transpile(code);
        assert!(
            rust.contains("CountUpState"),
            "snake_case name should become PascalCase state struct: got {}",
            rust
        );
    }

    #[test]
    fn test_transpile_single_word_generator_name() {
        let code = "def counter():\n    yield 1";
        let rust = transpile(code);
        assert!(
            rust.contains("CounterState"),
            "single word should be PascalCased: got {}",
            rust
        );
    }

    // --- StopIteration handling ---

    #[test]
    fn test_transpile_generator_terminal_state_returns_none() {
        let code = "def gen():\n    yield 1\n    yield 2";
        let rust = transpile(code);
        // Terminal state must return None (StopIteration equivalent)
        assert!(
            rust.contains("_ => None"),
            "terminal state should return None for StopIteration: got {}",
            rust
        );
    }

    // --- Generator with break ---

    #[test]
    fn test_transpile_generator_with_break() {
        let code = "def gen(n: int):\n    for i in range(100):\n        if i >= n:\n            break\n        yield i";
        let rust = transpile(code);
        assert!(
            rust.contains("break"),
            "generator with break should preserve break: got {}",
            rust
        );
    }

    // --- Generator consuming ---

    #[test]
    fn test_transpile_generator_consumed_in_list() {
        let code = "def gen():\n    yield 1\n    yield 2\n\nresult = list(gen())";
        let rust = transpile(code);
        assert!(
            rust.contains("collect") || rust.contains("vec!") || rust.contains("Vec"),
            "list(gen()) should use collect or Vec: got {}",
            rust
        );
    }

    #[test]
    fn test_transpile_generator_consumed_in_sum() {
        let code = "def gen():\n    yield 1\n    yield 2\n\ntotal = sum(gen())";
        let rust = transpile(code);
        assert!(
            rust.contains("sum") || rust.contains("fold"),
            "sum(gen()) should produce sum/fold: got {}",
            rust
        );
    }

    // --- Public function signature ---

    #[test]
    fn test_transpile_generator_public_fn() {
        let code = "def gen():\n    yield 1";
        let rust = transpile(code);
        assert!(
            rust.contains("pub fn gen"),
            "generator function should be public: got {}",
            rust
        );
    }

    #[test]
    fn test_transpile_generator_returns_impl_iterator() {
        let code = "def gen():\n    yield 1";
        let rust = transpile(code);
        assert!(
            rust.contains("impl Iterator"),
            "generator fn should return impl Iterator: got {}",
            rust
        );
    }

    // --- Sequential loops ---

    #[test]
    fn test_transpile_sequential_loop_generator() {
        let code = "def gen():\n    for i in range(3):\n        yield i\n    for j in range(3, 6):\n        yield j";
        let rust = transpile(code);
        assert!(
            rust.contains("GenState"),
            "sequential loop gen should produce state struct: got {}",
            rust
        );
    }

    // --- Yield None ---

    #[test]
    fn test_transpile_yield_none() {
        let code = "def gen():\n    yield None";
        let rust = transpile(code);
        assert!(
            rust.contains("None"),
            "yield None should produce None in output: got {}",
            rust
        );
    }

    // --- Yield expression ---

    #[test]
    fn test_transpile_yield_binary_expression() {
        let code = "def gen(a: int, b: int):\n    yield a + b";
        let rust = transpile(code);
        assert!(
            rust.contains("+"),
            "yield a+b should preserve addition: got {}",
            rust
        );
    }

    // --- Generator with list state ---

    #[test]
    fn test_transpile_generator_list_state() {
        let code = "def gen():\n    items = []\n    for i in range(5):\n        yield i";
        let rust = transpile(code);
        assert!(
            rust.contains("GenState"),
            "generator with list state should produce struct: got {}",
            rust
        );
    }

    // --- Debug derive ---

    #[test]
    fn test_transpile_generator_derives_debug() {
        let code = "def gen():\n    yield 1";
        let rust = transpile(code);
        assert!(
            rust.contains("Debug"),
            "generator state struct should derive or impl Debug: got {}",
            rust
        );
    }

    // --- Yield in conditional ---

    #[test]
    fn test_transpile_yield_in_if_false_guard() {
        let code = "def gen():\n    if False:\n        yield 1";
        let rust = transpile(code);
        assert!(
            rust.contains("GenState"),
            "guarded yield should still produce state struct: got {}",
            rust
        );
    }

    // --- Generator with default param ---

    #[test]
    fn test_transpile_generator_default_param() {
        let code = "def gen(n: int = 10):\n    for i in range(n):\n        yield i";
        let rust = transpile(code);
        assert!(
            rust.contains("GenState"),
            "generator with default param should produce struct: got {}",
            rust
        );
    }

    // --- Yield function call result ---

    #[test]
    fn test_transpile_yield_function_call() {
        let code = "def gen():\n    yield len([1, 2, 3])";
        let rust = transpile(code);
        assert!(
            rust.contains("len") || rust.contains(".len()"),
            "yield len() should produce len call: got {}",
            rust
        );
    }

    // --- Yield method call result ---

    #[test]
    fn test_transpile_yield_method_call() {
        let code = "def gen():\n    yield 'hello'.upper()";
        let rust = transpile(code);
        assert!(
            rust.contains("to_uppercase") || rust.contains("upper"),
            "yield str.upper() should map to Rust uppercase: got {}",
            rust
        );
    }
}