handle-this 0.2.4

Ergonomic error handling with try/catch/throw/inspect/finally syntax and automatic stack traces
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
#!/usr/bin/env python3
"""
Full test matrix generator for handle-this macro.

Generates ALL valid permutations of:
- Try patterns (7)
- Handler types (catch, throw, inspect, else)
- Bindings (8 types)
- Guards (3 types)
- Context modifiers (with, scope, finally combinations)
- Preconditions
- Multi-handler combinations (1-3 handlers)

Splits output into multiple files for manageable compilation.

Usage:
    # Generate all tests (WARNING: 88k+ tests)
    python3 generate_full_matrix.py --all

    # Generate specific combinations
    python3 generate_full_matrix.py -t basic -k catch -b named
    python3 generate_full_matrix.py --try-pattern basic,for --handler catch,throw
    python3 generate_full_matrix.py --category single --try-pattern basic

    # List available options
    python3 generate_full_matrix.py --list

Options:
    -t, --try-pattern   Try patterns: basic, direct, for, any_iter, all_iter, while, async
    -k, --handler       Handler keywords: catch, throw, inspect, else
    -b, --binding       Bindings: none, named, underscore, typed, typed_short, any, any_short, all
    -g, --guard         Guards: none, when_true, when_false, when_kind, when_perm, when_other, match_kind, match_perm
    -c, --context       Contexts: none, with_msg, with_data, with_both, scope, scope_data, finally, scope_finally, with_finally
    -p, --precondition  Preconditions: none, require_pass, require_fail
    -n, --num-handlers  Number of handlers: 0, 1, 2, 3
    --category          Test categories: single, two, three, no_handler, else_suffix, nested, control_flow, deeply_nested, comp_nested
    --all               Generate all tests (use with caution)
    --list              List all available filter values
"""

import os
import sys
import argparse
from dataclasses import dataclass, field
from typing import List, Dict, Optional, Tuple, Iterator, Set
from itertools import product, combinations_with_replacement
import hashlib

# =============================================================================
# Configuration
# =============================================================================

PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TESTS_DIR = os.path.join(PROJECT_ROOT, "tests")
TESTS_PER_FILE = 500  # Keep files manageable for compilation

# =============================================================================
# Dimensions
# =============================================================================

# Try patterns: (name, pattern, default_body, setup, result_type, is_async, is_direct)
# Note: For `for` and `any_iter`, we use iter_all_fail() so handlers actually run.
# With iter_second_ok(), the second item succeeds and handlers never execute.
TRY_PATTERNS = [
    ("basic", "try", "TRY_BODY", "", "i32", False, False),
    ("direct", "try -> i32", "TRY_BODY", "", "i32", False, True),
    ("for", "try for item in items", "item?", "let items = iter_all_fail();", "i32", False, False),
    ("any_iter", "try any item in items", "item?", "let items = iter_all_fail();", "i32", False, False),
    ("all_iter", "try all item in items", "item?", "let items = iter_all_ok();", "Vec<i32>", False, False),
    ("while", "try while attempts < 3", "attempts += 1; Err(io::Error::other(\"retry\"))?", "let mut attempts = 0;", "i32", False, False),
    ("async", "async try", "ASYNC_BODY", "", "i32", True, False),
]

# Handler keywords
HANDLER_KEYWORDS = ["catch", "throw", "inspect", "else"]

# Bindings: (name, code, needs_chain, has_typed_e, has_errors)
BINDINGS = [
    ("none", "", False, False, False),
    ("named", "e", False, False, False),
    ("underscore", "_", False, False, False),
    ("typed", "io::Error(e)", False, True, False),
    ("typed_short", "io::Error", False, False, False),
    ("any", "any io::Error(e)", True, True, False),
    ("any_short", "any io::Error", True, False, False),
    ("all", "all io::Error |errors|", True, False, True),
]

# Guards: (name, code, needs_typed_e, is_match)
# Note: Guards must match our test errors (NotFound) or tests will fail
GUARDS = [
    ("none", "", False, False),
    ("when_true", "when true", False, False),
    ("when_kind", "when e.kind() == ErrorKind::NotFound", True, False),
    # Match clause - only for typed bindings with `e` binding
    ("match_kind", "match e.kind() { ErrorKind::NotFound => MATCH_BODY, _ => MATCH_ELSE }", True, True),
]

# Else suffix: (name, has_else) - for typed handlers only
ELSE_SUFFIXES = [
    ("no_else", False),
    ("with_else", True),
]

# Then chain steps: (name, steps_code, num_steps)
# steps_code is inserted between try body and handlers
# Each step transforms the value: |x| { expression }
THEN_STEPS = [
    ("no_then", "", 0),
    ("then_1", ", then |x| { ok_val(x + 1)? }", 1),
    ("then_2", ", then |x| { ok_val(x * 2)? }, then |y| { ok_val(y + 1)? }", 2),
    ("then_ctx", ", then |x| { ok_val(x + 1)? } with \"step\"", 1),
]

# Nested body types for catch/throw handlers: (name, body_template, returns_value)
# These test nested try blocks within handler bodies
# Note: body_template uses {{ }} for literal braces in f-strings
# The macro correctly identifies that `?` inside nested try blocks is handled by that try,
# so it doesn't trigger "catch must be infallible" errors.
# returns_value: True if the body returns a value (for catch), False if returns string (for throw)
NESTED_BODIES = [
    ("flat", None, True),  # Use default body
    # Nested try blocks (level 1)
    # Note: No outer braces - handler generation adds { body }
    # Note: Use single braces { } - these are NOT f-strings
    ("nested_try_else", "try -> i32 { io_ok()? } else { 0 }", True),
    ("nested_try_catch", "try { io_ok()? } catch { 0 }", True),
    ("nested_try_throw_catch", "try { io_not_found()? } throw { \"inner\" } catch { 0 }", True),
    # Nested try for (level 1)
    ("nested_try_for", "let items = iter_all_ok(); try for item in items { item? } catch { 0 }", True),
    # Deeply nested (level 2) - try inside try
    ("nested_2_try_in_try", "try { try { io_ok()? } catch { 1 } } catch { 0 }", True),
    # Try with inspects
    ("nested_try_inspect", "let mut saw = false; try { io_ok()? } inspect _ { saw = true; } catch { 0 }", True),
]

# Nested bodies specifically for throw handlers (must return string for error message)
# Note: No outer braces - handler generation adds { body }
# Note: Use single braces { } - these are NOT f-strings
NESTED_THROW_BODIES = [
    ("flat", None),  # Use default body
    ("nested_try_else_str", "let s: String = try -> String { \"inner\".to_string() } else { \"fallback\".to_string() }; s"),
    ("nested_try_catch_str", "let s: String = try { Ok::<_, std::io::Error>(\"inner\".to_string())? } catch { \"caught\".to_string() }; s"),
]

# =============================================================================
# Comprehensive Nested Permutation System
# =============================================================================
# Abstracted system for generating nested try permutations across ALL block types.
#
# Block positions that can contain nested try:
# - try_body: try { NESTED }
# - catch_body: catch { NESTED } - must be infallible (no ?)
# - throw_body: throw { NESTED } - must return String
# - inspect_body: inspect e { NESTED; } - statement, doesn't return
# - else_body: else { NESTED } - returns value
# - finally_body: finally { NESTED; } - statement, cleanup
# - try_catch_body: try catch { NESTED } - returns Result
# - match_arm: match expr { arm => NESTED } - returns value
# - require_else: require cond else { NESTED } - returns error

@dataclass
class BlockPosition:
    """Defines a position where nesting can occur."""
    name: str
    returns_value: bool  # True if block returns a value
    return_type: str     # "i32", "String", "Result", "unit", "error"
    is_statement: bool   # True if block is a statement (no return value used)
    can_use_question_mark: bool  # True if ? operator is allowed

# All block positions where nesting can occur
BLOCK_POSITIONS = {
    # Basic try
    "try_body": BlockPosition("try_body", True, "i32", False, True),
    # Handlers
    "catch_body": BlockPosition("catch_body", True, "i32", False, False),  # catch must be infallible
    "throw_body": BlockPosition("throw_body", True, "String", False, False),
    "inspect_body": BlockPosition("inspect_body", False, "unit", True, False),
    "else_body": BlockPosition("else_body", True, "i32", False, False),
    "try_catch_body": BlockPosition("try_catch_body", True, "Result", False, True),
    # Loop bodies
    "for_body": BlockPosition("for_body", True, "i32", False, True),   # try for x in iter { BODY }
    "while_body": BlockPosition("while_body", True, "i32", False, True),  # try while cond { BODY }
    "all_body": BlockPosition("all_body", True, "i32", False, True),   # try all x in iter { BODY }
    # Context/control
    "finally_body": BlockPosition("finally_body", False, "unit", True, False),
    "match_arm": BlockPosition("match_arm", True, "i32", False, False),
    "require_else": BlockPosition("require_else", True, "error", False, False),
}

# Nested patterns parameterized by return type
# Format: (name, template) where template uses {err}, {val}, {str} placeholders
NESTED_PATTERNS_BY_TYPE = {
    "i32": [
        ("try_catch", "try {{ {err} }} catch {{ {val} }}"),
        ("try_throw_catch", "try {{ {err} }} throw {{ \"transformed\" }} catch {{ {val} }}"),
        ("try_inspect_catch", "try {{ {err} }} inspect _ {{ }} catch {{ {val} }}"),
        ("try_direct", "try -> i32 {{ {err} }} else {{ {val} }}"),
        ("try_typed_catch", "try {{ {err} }} catch io::Error(_) {{ {val} }} else {{ {val} + 1 }}"),
        ("try_any_catch", "try {{ Err(chained_io_error())? }} catch any io::Error(_) {{ {val} }}"),
        ("try_for", "{{ let items = iter_all_fail(); try for item in items {{ item? }} catch {{ {val} }} }}"),
        ("try_while", "{{ let mut att = 0; try while att < 2 {{ att += 1; Err(io::Error::other(\"r\"))? }} catch {{ {val} }} }}"),
        ("scoped_try", "scope \"nested\", try {{ {err} }} catch {{ {val} }}"),
        ("scoped_try_kv", "scope \"nested\", {{ key: 42 }}, try {{ {err} }} catch {{ {val} }}"),
        ("scoped_try_kv_multi", "scope \"nested\", {{ id: 1, active: true }}, try {{ {err} }} catch {{ {val} }}"),
        ("scoped_nested", "scope \"outer\", try {{ scope \"inner\", try {{ {err} }} catch {{ {val} }} }} catch {{ {val} + 1 }}"),
        ("scoped_nested_kv", "scope \"outer\", {{ layer: 1 }}, try {{ scope \"inner\", {{ layer: 2 }}, try {{ {err} }} catch {{ {val} }} }} catch {{ {val} + 1 }}"),
        ("try_with_finally", "{{ let mut f = false; let r = try {{ {err} }} finally {{ f = true; }} catch {{ {val} }}; r }}"),
    ],
    "String": [
        ("try_catch_str", "try {{ Ok::<_, Handled>(\"inner\".to_string())? }} catch {{ \"caught\".to_string() }}"),
        ("try_direct_str", "try -> String {{ \"direct\".to_string() }} else {{ \"fallback\".to_string() }}"),
    ],
    "Result": [
        ("try_catch_result", "try {{ {err} }} try catch e {{ if true {{ Ok({val}) }} else {{ Err(e) }} }}"),
        ("nested_ok", "{{ let v: Result<i32> = try {{ {err} }} catch {{ {val} }}; v }}"),
    ],
    "unit": [
        ("try_catch_unit", "{{ let _ = try {{ {err} }} catch {{ {val} }}; }}"),
        ("try_discard", "{{ let _: Result<i32> = try {{ {err} }} catch {{ {val} }}; }}"),
    ],
    "error": [
        ("try_catch_err", "try {{ {err} }} catch {{ Handled::msg(\"nested error\") }}"),
    ],
}

# Error sources for nested patterns
NESTED_ERR_SOURCES = [
    ("io_err", "io_not_found()?"),
    ("chain_err", "Err(chained_io_error())?"),
]

# Values for nested catch bodies
NESTED_VALUES = [1, 42, 99]

# Level 2 templates (nesting inside nesting)
NESTED_L2_TEMPLATES = {
    "i32": [
        ("l2_try_try", "try {{ try {{ {err} }} catch {{ {val} }} }} catch {{ {val} + 10 }}"),
        ("l2_catch_try", "try {{ {err} }} catch {{ try {{ io_ok()? }} catch {{ {val} }} }}"),
        ("l2_throw_try", "try {{ {err} }} throw {{ try -> String {{ \"t\".to_string() }} else {{ \"f\".to_string() }} }} catch {{ {val} }}"),
        ("l2_for_try", "{{ let items = iter_all_fail(); try for item in items {{ try {{ item? }} catch {{ {val} }} }} catch {{ {val} + 10 }} }}"),
    ],
}

# Level 3 templates
NESTED_L3_TEMPLATES = {
    "i32": [
        ("l3_deep", "try {{ try {{ try {{ {err} }} catch {{ {val} }} }} catch {{ {val} + 10 }} }} catch {{ {val} + 20 }}"),
    ],
}

# =============================================================================
# Expanded nested patterns for use in comprehensive tests
# =============================================================================
# These expand the templates above with concrete values for direct use.

def expand_nested_patterns(templates: list, err: str = "io_not_found()?", val: str = "1") -> list:
    """Expand template patterns with concrete error/value placeholders."""
    result = []
    for name, template in templates:
        code = template.format(err=err, val=val, str='"s".to_string()')
        result.append((name, code))
    return result

# Expanded patterns for direct use
NESTED_TRY_I32 = expand_nested_patterns(NESTED_PATTERNS_BY_TYPE["i32"])
NESTED_TRY_STR = [
    (name, template.format(err="io_not_found()?", val="1", str='"s".to_string()'))
    for name, template in NESTED_PATTERNS_BY_TYPE["String"]
]
NESTED_L2_I32 = expand_nested_patterns(NESTED_L2_TEMPLATES["i32"])
NESTED_L3_I32 = expand_nested_patterns(NESTED_L3_TEMPLATES["i32"])

# Control flow in CATCH HANDLERS for loop patterns (try for, try while, try all)
# break/continue work in the catch handler, NOT inside nested try blocks
# Pattern: try for x in iter { ... } catch { break }
CONTROL_FLOW_CATCH_BODIES = [
    ("catch_break", "break"),
    ("catch_continue", "continue"),
]

# Context modifiers: (name, code, needs_setup, setup_code, extra_assert)
CONTEXTS = [
    ("none", [], "", ""),
    ("with_msg", ['with "test context"'], "", ""),
    ("with_data", ['with { key: 42 }'], "", ""),
    ("with_both", ['with "ctx", { key: 42 }'], "", ""),
    ("scope", ['scope "test"'], "", ""),
    ("scope_data", ['scope "test", { key: 42 }'], "", ""),
    ("scope_data_bool", ['scope "test", { enabled: true }'], "", ""),
    ("scope_data_str", ['scope "test", { name: "value" }'], "", ""),
    ("scope_data_multi", ['scope "test", { id: 1, active: true }'], "", ""),
    ("finally", ["finally { finalized = true; }"], "let mut finalized = false;", "assert!(finalized);"),
    ("scope_finally", ['scope "test"', "finally { finalized = true; }"], "let mut finalized = false;", "assert!(finalized);"),
    ("scope_data_finally", ['scope "test", { key: 42 }', "finally { finalized = true; }"], "let mut finalized = false;", "assert!(finalized);"),
    ("with_finally", ['with "ctx"', "finally { finalized = true; }"], "let mut finalized = false;", "assert!(finalized);"),
]

# Preconditions: (name, code)
PRECONDITIONS = [
    ("none", []),
    ("require_pass", ['require true else "failed"']),
    ("require_fail", ['require false else "failed"']),
]

# =============================================================================
# Validation
# =============================================================================

def is_valid_handler(keyword: str, binding: str, guard: str, try_pattern: str) -> bool:
    """Check if a handler combination is valid."""
    bind_name, bind_code, needs_chain, has_typed_e, has_errors = None, None, None, None, None
    for b in BINDINGS:
        if b[0] == binding:
            bind_name, bind_code, needs_chain, has_typed_e, has_errors = b
            break

    guard_name, guard_code, needs_typed_e, is_match = None, None, None, False
    for g in GUARDS:
        if g[0] == guard:
            guard_name, guard_code, needs_typed_e, is_match = g
            break

    is_direct = try_pattern == "direct"
    is_iter = try_pattern in ["for", "any_iter", "all_iter", "while"]

    # else only works in direct mode with no binding/guard
    if keyword == "else":
        return is_direct and binding == "none" and guard == "none"

    # inspect requires some binding
    if keyword == "inspect" and binding == "none":
        return False

    # throw doesn't use underscore
    if keyword == "throw" and binding == "underscore":
        return False

    # guard requires some binding
    if guard != "none" and binding == "none":
        return False

    # when_kind and match_kind require typed binding (e.kind() method)
    if needs_typed_e and not has_typed_e:
        return False

    # match clause requires a typed binding (not untyped catch/throw)
    if is_match and binding not in ["typed", "any"]:
        return False

    return True


def is_untyped_catch(kw: str, bind: str) -> bool:
    """Check if handler is an untyped catch (catches all errors)."""
    return kw in ["catch", "else"] and bind in ["none", "named", "underscore"]


def is_valid_combination(try_pattern: str, handlers: List[Tuple[str, str, str]],
                         context: str, precondition: str, then_steps: str = "no_then") -> bool:
    """Check if a full combination is valid."""
    is_direct = try_pattern == "direct"
    has_then = then_steps != "no_then"

    # Then chains not yet supported with async
    if has_then and try_pattern == "async":
        return False

    # Then chains need special handling for try all (returns Vec) and try while (test body returns ())
    # Skip these combinations in the test generator - they work but need custom then step code
    if has_then and try_pattern in ["all_iter", "while"]:
        return False

    # Then chains don't work with with_* or scope_* contexts - these wrap the try body
    # in ways incompatible with then chain syntax
    if has_then and (context.startswith("with") or context.startswith("scope")):
        return False

    # Then chains don't work with any/all bindings - those require error bodies that return ()
    # but then steps expect a value to transform
    if has_then:
        needs_error_body = any(h[1] in ["any", "any_short", "all"] for h in handlers)
        if needs_error_body:
            return False

    # Then chains require an untyped catch to guarantee success
    # Typed catches might not match (especially after throw transforms error type),
    # causing error to propagate and then chain to never run
    if has_then:
        has_untyped_catch = any(
            h[0] == "catch" and h[1] in ["none", "underscore", "named"]
            for h in handlers
        )
        # If there's any throw, require untyped catch (throw transforms might break typed catch)
        has_any_throw = any(h[0] == "throw" for h in handlers)
        if has_any_throw and not has_untyped_catch:
            return False

    # Validate each handler
    for kw, bind, guard in handlers:
        if not is_valid_handler(kw, bind, guard, try_pattern):
            return False

    # CRITICAL: No handlers may follow an untyped catch.
    # Untyped catch handles ALL errors, making subsequent handlers unreachable.
    # The macro now emits a compile error for this case.
    saw_untyped_catch = False
    for kw, bind, guard in handlers:
        if saw_untyped_catch:
            # Any handler after untyped catch is invalid
            return False
        if is_untyped_catch(kw, bind):
            saw_untyped_catch = True

    # Direct mode requires catch-all fallback
    if is_direct:
        has_catchall = any(
            kw in ["catch", "else"] and bind in ["none", "underscore"] and guard == "none"
            for kw, bind, guard in handlers
        )
        if not has_catchall:
            return False

    # Direct mode cannot be used with require or scope.
    # Direct mode guarantees success (returns T), but require/scope can fail (return Result).
    # The macro emits a compile error for these combinations.
    if is_direct:
        if precondition != "none":
            return False
        if context.startswith("scope"):
            return False

    # KNOWN BUG: require_fail + finally doesn't run finally block
    # Skip these combinations until the bug is fixed
    if precondition == "require_fail" and "finally" in context:
        return False

    # require_fail with catch would still fail (precondition runs first)
    # That's actually valid - test should expect error

    # Async can't use all_iter result type easily
    if try_pattern == "async" and context in ["scope", "scope_data", "scope_finally"]:
        # Scope with async needs careful handling - skip for now
        pass

    return True


# =============================================================================
# Code Generation
# =============================================================================

def get_try_body(binding: str, is_async: bool) -> str:
    """Get appropriate try body."""
    needs_chain = binding in ["any", "any_short", "all"]
    if is_async:
        return "async_io_not_found().await?"
    if needs_chain:
        if binding == "all":
            return "Err(multi_io_chain())?"
        return "Err(chained_io_error())?"
    return "io_not_found()?"


def get_handler_body(keyword: str, binding: str, nested_body: str = None, try_pattern: str = None) -> str:
    """Get handler body.

    Args:
        keyword: Handler keyword (catch, throw, inspect, else)
        binding: Binding type name
        nested_body: Optional nested body template to use instead of default
        try_pattern: Try pattern name (e.g., "all_iter" needs Vec return type)
    """
    has_typed_e = binding in ["typed", "any"]
    has_errors = binding == "all"
    has_e = binding in ["named", "typed", "any"]

    # try all returns Vec<T>, so catch must return Vec<T> too
    needs_vec = try_pattern == "all_iter"

    if keyword == "catch" or keyword == "else":
        if nested_body:
            return nested_body
        if has_errors:
            return "vec![errors.len() as i32]" if needs_vec else "errors.len() as i32"
        elif has_typed_e:
            return "let _ = e.kind(); vec![42]" if needs_vec else "let _ = e.kind(); 42"
        elif has_e:
            return "let _ = &e; vec![42]" if needs_vec else "let _ = &e; 42"
        else:
            return "vec![42]" if needs_vec else "42"
    elif keyword == "throw":
        if nested_body:
            return nested_body
        if has_errors:
            return 'format!("{} errors", errors.len())'
        elif has_typed_e:
            return 'format!("io: {:?}", e.kind())'
        elif has_e:
            return 'format!("err: {}", e)'
        else:
            return '"transformed"'
    else:  # inspect
        if has_errors:
            return "let _ = errors.len(); inspected = true;"
        elif has_typed_e:
            return "let _ = e.kind(); inspected = true;"
        elif has_e:
            return "let _ = &e; inspected = true;"
        else:
            return "inspected = true;"


def build_handler_str(keyword: str, binding: str, guard: str,
                      nested_body: str = None, has_else: bool = False,
                      try_pattern: str = None) -> str:
    """Build handler string.

    Args:
        keyword: Handler keyword (catch, throw, inspect, else)
        binding: Binding type name
        guard: Guard type name
        nested_body: Optional nested body template
        has_else: If True, add else {} fallback after typed handler
        try_pattern: Try pattern name (e.g., "all_iter" needs Vec return type)
    """
    parts = [keyword]

    # try all returns Vec<T>, so catch must return Vec<T> too
    needs_vec = try_pattern == "all_iter"

    for b in BINDINGS:
        if b[0] == binding:
            if b[1]:
                parts.append(b[1])
            break

    # Check if this is a match clause
    is_match = False
    guard_code = ""
    for g in GUARDS:
        if g[0] == guard:
            guard_code = g[1]
            is_match = g[3] if len(g) > 3 else False
            break

    if is_match:
        # Match clause - body is inside the match arms, no separate braces
        # Match arms must be expressions, not statements (no trailing semicolons)
        if keyword == "catch":
            match_body = "vec![42]" if needs_vec else "42"
            match_else = "vec![0]" if needs_vec else "0"
        elif keyword == "throw":
            match_body = '"matched"'
            match_else = '"unmatched"'
        else:  # inspect
            # For inspect, use a block expression that sets the flag
            match_body = "{ inspected = true; }"
            match_else = "{ }"

        # Replace MATCH_BODY and MATCH_ELSE placeholders
        match_code = guard_code.replace("MATCH_BODY", match_body).replace("MATCH_ELSE", match_else)
        parts.append(match_code)
    else:
        # Regular guard
        if guard_code:
            parts.append(guard_code)

        body = get_handler_body(keyword, binding, nested_body, try_pattern)
        parts.append("{ " + body + " }")

        # Add else fallback for typed handlers
        # Note: throw Type {} else {} creates a catch-all CATCH (not throw),
        # so else body should return a value, not an error string
        if has_else:
            if keyword == "catch":
                parts.append("else { vec![0] }" if needs_vec else "else { 0 }")
            elif keyword == "throw":
                # else after throw is a catch-all catch, returns value not error
                parts.append("else { vec![0] }" if needs_vec else "else { 0 }")

    return " ".join(parts)


def get_required_try_body(handlers: List[Tuple[str, str, str]], is_async: bool) -> str:
    """Determine the try body based on what handlers need.

    If any handler uses 'all' binding, we need multi_io_chain().
    If any handler uses 'any' binding, we need chained_io_error().
    Otherwise, use the simple error.
    """
    needs_all = any(h[1] == "all" for h in handlers)
    needs_any = any(h[1] in ["any", "any_short"] for h in handlers)

    if is_async:
        return "async_io_not_found().await?"
    if needs_all:
        return "Err(multi_io_chain())?"
    if needs_any:
        return "Err(chained_io_error())?"
    return "io_not_found()?"


def generate_test(test_id: str, try_pattern_data: tuple, handlers: List[Tuple[str, str, str]],
                  context_data: tuple, precond_data: tuple, then_data: tuple = None) -> Tuple[str, bool, str]:
    """Generate a single test. Returns (code, expects_ok, expected_value)."""
    tp_name, tp_pattern, tp_body, tp_setup, tp_result, tp_async, tp_direct = try_pattern_data
    ctx_name, ctx_codes, ctx_setup, ctx_assert = context_data
    pre_name, pre_codes = precond_data
    # Extract then chain data (name, code, num_steps)
    then_name, then_code, then_num = then_data if then_data else ("no_then", "", 0)

    # Determine actual try body based on what handlers need
    if handlers:
        actual_body = get_required_try_body(handlers, tp_async)
    else:
        actual_body = "io_ok()?" if not tp_async else "async_io_ok().await?"

    # For iteration patterns, use their specific body
    if tp_name in ["for", "any_iter", "all_iter", "while"]:
        actual_body = tp_body

    # Track what kind of io::Error is at root and in chain (for guard matching)
    # The `when e.kind() == NotFound` guard checks the error being matched:
    # - Root-only bindings check root error's kind
    # - Chain-searching bindings (any) check the matched error in chain
    #
    # Error bodies:
    # - io_not_found(): root is NotFound
    # - multi_io_chain(): root is PermissionDenied, NotFound in chain
    # - chained_io_error(): root is StringError (not io::Error), NotFound in chain
    # - iter_all_fail(): produces Other kind
    # - async_io_not_found(): root is NotFound
    #
    # Determine based on actual_body which error structure we have:
    needs_all = any(h[1] == "all" for h in handlers)
    needs_any = any(h[1] in ["any", "any_short"] for h in handlers)
    # Note: all_iter with handlers uses iter_all_fail(), not multi_io_chain/chained_io_error
    iter_patterns = ["for", "any_iter", "while", "async"] + (["all_iter"] if handlers else [])
    uses_multi_io_chain = needs_all and tp_name not in iter_patterns
    uses_chained_io_error = needs_any and not needs_all and tp_name not in iter_patterns

    # Root kind: what kind is the root io::Error?
    # Note: all_iter with handlers uses iter_all_fail() which produces Other kind
    if tp_name in ["for", "any_iter", "while"] or (tp_name == "all_iter" and handlers):
        root_kind_is_notfound = False  # iter_all_fail produces Other kind
    elif uses_multi_io_chain:
        root_kind_is_notfound = False  # root is PermissionDenied
    elif uses_chained_io_error:
        root_kind_is_notfound = False  # root is StringError, not even io::Error
    else:
        root_kind_is_notfound = True  # io_not_found or async_io_not_found

    # Chain has NotFound: is there a NotFound anywhere in the chain?
    # For chain-searching (any) bindings, this determines if guard can match
    # Note: all_iter with handlers uses iter_all_fail() which produces only Other kind
    if tp_name in ["for", "any_iter", "while"] or (tp_name == "all_iter" and handlers):
        chain_has_notfound = False  # iter_all_fail produces only Other kind
    else:
        chain_has_notfound = True  # All other bodies have NotFound somewhere

    # Build test
    lines = []

    # Test attribute
    if tp_async:
        lines.append("#[tokio::test]")
        lines.append(f"async fn {test_id}() {{")
    else:
        lines.append("#[test]")
        lines.append(f"fn {test_id}() {{")

    # Setup
    all_setup = []
    if tp_setup:
        # For all_iter with handlers, use failing iterator to test error handling
        if tp_name == "all_iter" and handlers:
            all_setup.append("let items = iter_all_fail();")
        else:
            all_setup.append(tp_setup)
    if ctx_setup:
        all_setup.append(ctx_setup)

    # Check if we need inspected var
    has_inspect = any(h[0] == "inspect" for h in handlers)
    if has_inspect:
        all_setup.append("let mut inspected = false;")

    for s in all_setup:
        lines.append(f"    {s}")

    # Result type
    if tp_direct:
        lines.append(f"    let result: {tp_result} = handle! {{")
    else:
        lines.append(f"    let result: Result<{tp_result}> = handle! {{")

    # Preconditions
    for pre in pre_codes:
        lines.append(f"        {pre},")

    # Scope context (before try)
    for ctx in ctx_codes:
        if ctx.startswith("scope"):
            lines.append(f"        {ctx},")

    # Try block (with optional then chain)
    lines.append(f"        {tp_pattern} {{ {actual_body} }}{then_code}")

    # Handlers
    for kw, bind, guard in handlers:
        h_str = build_handler_str(kw, bind, guard, try_pattern=tp_name)
        lines.append(f"        {h_str}")

    # Non-scope context (with, finally)
    for ctx in ctx_codes:
        if not ctx.startswith("scope"):
            lines.append(f"        {ctx}")

    lines.append("    };")

    # Determine expected outcome
    expects_ok = True
    expected_value = "42"

    if pre_name == "require_fail":
        expects_ok = False
        expected_value = ""
    elif not handlers:
        # No handlers - depends on whether try body produces error
        # For iteration patterns, check the iterator setup:
        # - for, any_iter: use iter_all_fail() -> all fail -> Err
        # - all_iter: uses iter_all_ok() -> all succeed -> Ok
        # - while: always produces error (body has Err()?)
        # For basic/async: check if body has error-producing keywords
        if tp_name in ["for", "any_iter", "while"]:
            # These use failing iterators/conditions -> Err
            expects_ok = False
            expected_value = ""
        elif tp_name == "all_iter":
            # Uses iter_all_ok() -> all succeed -> Ok with Vec
            expects_ok = True
            expected_value = "vec![1, 2, 3]"
        elif "not_found" in actual_body or "fail" in actual_body or "chained" in actual_body or "multi" in actual_body:
            expects_ok = False
            expected_value = ""
    else:
        # Handler semantics:
        # - throw: transforms error, continues chain (non-terminal)
        # - catch/else: catches (possibly transformed) error, returns Ok (terminal)
        # - inspect: runs side effect, continues chain (non-terminal)
        #
        # IMPORTANT: When throw transforms the error, the TYPE changes.
        # Typed catches after throw won't match if throw transformed to a different type.
        #
        # Binding types:
        # - Untyped: "none", "named", "underscore" - catch any error
        # - Typed: "typed", "typed_short", "any", "any_short", "all" - catch specific type

        def is_untyped_binding(binding_name):
            return binding_name in ["none", "named", "underscore"]

        def is_io_typed(binding_name):
            """Check if binding is typed as io::Error"""
            return binding_name in ["typed", "typed_short", "any", "any_short", "all"]

        def is_chain_searching(binding_name):
            """Check if binding searches the error chain (vs just checking root).

            For BASIC try patterns:
            - typed, typed_short: use downcast_ref (root only)
            - any, any_short, all: use chain_any/chain_all (full chain search)

            For LOOP patterns (for, any_iter, while):
            - ALL typed bindings use chain_any because loop errors are chained
            - So even typed, typed_short are chain-searching in loops

            When throw transforms an error, the original error stays IN the chain.
            Chain-searching bindings will still find the original type.
            """
            is_loop_pattern = tp_name in ["for", "any_iter", "while"]
            is_typed = binding_name in ["typed", "typed_short", "any", "any_short", "all"]
            if is_loop_pattern and is_typed:
                # All typed bindings in loops use chain_any
                return True
            return binding_name in ["any", "any_short", "all"]

        def is_root_only(binding_name):
            """Check if binding only checks the root error (not the chain)."""
            is_loop_pattern = tp_name in ["for", "any_iter", "while"]
            if is_loop_pattern:
                # Loop patterns always use chain_any for typed, never root-only
                return False
            return binding_name in ["typed", "typed_short"]

        # Check for untyped catch (will catch anything including transformed errors)
        has_untyped_catch = any(
            h[0] in ["catch", "else"] and is_untyped_binding(h[1])
            for h in handlers
        )

        # Check for any catch at all
        has_any_catch = any(h[0] in ["catch", "else"] for h in handlers)

        # Handler order matters! Find first catch and first throw positions
        first_catch_idx = None
        first_throw_idx = None
        for i, h in enumerate(handlers):
            if h[0] in ["catch", "else"] and first_catch_idx is None:
                first_catch_idx = i
            if h[0] == "throw" and first_throw_idx is None:
                first_throw_idx = i

        # Check if there's a throw BEFORE any catch
        throw_before_catch = (first_throw_idx is not None and
                              (first_catch_idx is None or first_throw_idx < first_catch_idx))

        # Check if the throw before catch will transform the error
        # (either untyped throw which always transforms, or typed throw that matches io::Error)
        # IMPORTANT: Must also check throw's guard - when_kind requires NotFound but our errors are Other
        throw_transforms_before_catch = False
        if throw_before_catch:
            throw_h = handlers[first_throw_idx]
            throw_binding = throw_h[1]
            throw_guard = throw_h[2]
            # Untyped throw or typed io throw might transform...
            if throw_binding in ["none", "named", "underscore"] or is_io_typed(throw_binding):
                # But check if guard allows it
                # For throw, check the kind based on binding type
                if throw_guard == "when_kind":
                    if throw_binding in ["any", "any_short"]:
                        throw_guard_ok = chain_has_notfound
                    elif throw_binding == "all":
                        throw_guard_ok = chain_has_notfound
                    else:
                        # Root-only or untyped
                        throw_guard_ok = root_kind_is_notfound
                    if not throw_guard_ok:
                        throw_transforms_before_catch = False
                    else:
                        throw_transforms_before_catch = True
                else:
                    # "none" or "when_true" guards - throw matches
                    throw_transforms_before_catch = True

        # Find the first catch handler that will successfully match the error.
        # Handlers are checked in order; the first matching one wins.
        #
        # For a catch to match:
        # - Untyped: always matches (no type check)
        # - Typed: must find io::Error in chain (always present in our tests)
        # - Guard: when_kind only matches NotFound; when_true always matches; no guard always matches
        #
        # If throw transforms before a catch, chain-searching catches can still find the original.

        def handler_will_catch(h, error_transformed):
            """Check if a catch handler will successfully catch the error."""
            # Use outer scope variables (avoid re-definition which causes scope issues)
            nonlocal uses_multi_io_chain, uses_chained_io_error

            kw, bind, guard = h
            if kw not in ["catch", "else"]:
                return False, None

            # Check guard - when_kind requires NotFound error
            # For root-only bindings, check root's kind
            # For chain-searching bindings, check if chain has NotFound
            # match_kind always "matches" (has catch-all arm) but returns different values
            def guard_matches_for_binding(b, g):
                if g == "match_kind":
                    # Match clause always succeeds (has _ arm), but value differs
                    return True
                if g != "when_kind":
                    return True
                # when_kind guard - depends on binding type
                if b in ["any", "any_short"]:
                    # Chain-searching: finds first io::Error in chain
                    return chain_has_notfound
                elif b == "all":
                    # Collects all - at least one must match guard
                    return chain_has_notfound
                else:
                    # Root-only (typed, typed_short) or untyped
                    return root_kind_is_notfound

            guard_matches = guard_matches_for_binding(bind, guard)

            # For match clause, determine which arm's value we get
            def get_match_value(b, g):
                if g != "match_kind":
                    return None  # Not a match clause
                # Check if the matched error has NotFound kind
                # chain_any finds FIRST io::Error in chain, not just any NotFound
                if b in ["any", "any_short"]:
                    # For multi_io_chain: root IS io::Error (PermissionDenied) -> finds that first
                    # For chained_io_error: root is StringError, so first io::Error is in chain (NotFound)
                    # For others: root is io::Error -> check root kind
                    if uses_multi_io_chain:
                        is_notfound = False  # First io::Error is PermissionDenied
                    elif uses_chained_io_error:
                        is_notfound = True  # First io::Error is chained NotFound
                    else:
                        is_notfound = root_kind_is_notfound
                else:
                    is_notfound = root_kind_is_notfound
                return is_notfound  # True = first arm (42), False = else arm (0)

            # For `all` binding, the number of errors depends on the actual try body used:
            # - try for/any_iter/all_iter: chains 3 errors (iter_all_fail produces 3 items)
            # - try while: only keeps last error (1 error)
            # - async: always uses async_io_not_found() which has 1 error
            # - basic/direct with multi_io_chain: 2 errors (NotFound + PermissionDenied)
            # - basic/direct with chained_io_error or io_not_found: 1 error
            def all_binding_value():
                if tp_name in ["for", "any_iter", "all_iter"]:
                    return "3"  # iter patterns chain errors from iterator
                if tp_async:
                    return "1"  # async always uses async_io_not_found (1 error)
                # For non-async, check if we're using multi_io_chain()
                # multi_io_chain is used when needs_all=True (any handler has 'all' binding)
                needs_all_body = any(h[1] == "all" for h in handlers)
                if needs_all_body and tp_name not in ["while"]:
                    return "2"  # multi_io_chain has 2 io::Errors
                return "1"  # single error

            # Determine value for match clause
            def catch_value_for_guard(b, g):
                # For all_iter, catch bodies return Vec
                needs_vec = tp_name == "all_iter"

                if g == "match_kind":
                    # Match clause returns different values based on error kind
                    match_is_notfound = get_match_value(b, g)
                    val = "42" if match_is_notfound else "0"
                    return f"vec![{val}]" if needs_vec else val
                elif b == "all":
                    val = all_binding_value()
                    return f"vec![{val}]" if needs_vec else val
                else:
                    return "vec![42]" if needs_vec else "42"

            # Untyped catch (catches any error)
            if bind in ["none", "named", "underscore"]:
                if guard_matches:
                    return True, catch_value_for_guard(bind, guard)
                else:
                    return False, None

            # Typed catch - check if it can find io::Error
            # After throw transforms, chain-searching bindings can only find original
            # if the original is still in the chain (original_in_chain=True)
            if error_transformed:
                if original_in_chain and is_chain_searching(bind):
                    if guard_matches:
                        return True, catch_value_for_guard(bind, guard)
                    else:
                        return False, None
                else:
                    # Original not in chain, or root-only binding
                    return False, None
            else:
                # No transformation - check if root is directly io::Error
                # chain_after() now preserves the original error at root:
                # - multi_io_chain(): root IS io::Error (PermissionDenied)
                # - chained_io_error(): root is StringError (from Handled::msg)
                # - io_not_found(): root IS io::Error (NotFound)
                #
                # For root-only bindings:
                # - multi_io_chain() and io_not_found(): root-only catch WILL match
                # - chained_io_error(): root-only catch will NOT match (root is StringError)
                # (uses_chained_io_error from outer scope)
                if uses_chained_io_error and is_root_only(bind):
                    # Root is StringError, not io::Error - root-only binding won't match
                    return False, None
                if guard_matches:
                    return True, catch_value_for_guard(bind, guard)
                else:
                    return False, None

        # Check handlers in order to find the first match
        # Track whether error has been transformed and whether chain is preserved
        error_transformed = False
        original_in_chain = True  # Is the original io::Error still in the chain?
        found_match = False
        for h in handlers:
            kw, bind, guard = h

            # Check if this is a throw that transforms the error
            if kw == "throw":
                # Check if throw's guard matches based on binding type
                if guard == "when_kind":
                    if bind in ["any", "any_short"]:
                        throw_guard_matches = chain_has_notfound
                    elif bind == "all":
                        throw_guard_matches = chain_has_notfound
                    else:
                        throw_guard_matches = root_kind_is_notfound
                else:
                    throw_guard_matches = True
                if throw_guard_matches:
                    # ALL throws now use chain_after, so the original is ALWAYS preserved
                    if bind in ["none", "named", "underscore"]:
                        error_transformed = True
                        original_in_chain = True  # chain_after preserves original
                    elif is_io_typed(bind):
                        error_transformed = True
                        original_in_chain = True  # chain_after preserves original

            # Check if this catch will match
            if kw in ["catch", "else"]:
                matches, value = handler_will_catch(h, error_transformed)
                if matches:
                    expects_ok = True
                    expected_value = value
                    found_match = True
                    break

        if not found_match:
            # No catch matched - error propagates
            expects_ok = False
            expected_value = ""

    # Special cases for iteration patterns
    if tp_name == "all_iter" and expects_ok:
        if not handlers:
            # No handlers, iter_all_ok() succeeds
            expected_value = "vec![1, 2, 3]"
        # else: expected_value is already set by handler logic (e.g., "vec![42]")

    # Apply then chain transformations to expected value
    # then_1/then_ctx: x + 1
    # then_2: (x * 2) + 1
    # ONLY applies when try body succeeds - if handlers catch errors, then doesn't run
    # When handlers exist, the try body is set to fail, so then never runs
    if expects_ok and expected_value and then_num > 0 and not handlers:
        try:
            val = int(expected_value)
            if then_name == "then_2":
                val = (val * 2) + 1
            else:
                val = val + 1
            expected_value = str(val)
        except ValueError:
            pass  # Non-integer value (e.g., vec![...]), don't transform

    # Assertions
    if tp_direct:
        if expected_value and expects_ok:
            lines.append(f"    assert_eq!(result, {expected_value});")
    elif expects_ok:
        if expected_value:
            lines.append(f"    assert_eq!(result.unwrap(), {expected_value});")
        else:
            lines.append("    assert!(result.is_ok());")
    else:
        lines.append("    assert!(result.is_err());")

    # Extra asserts
    if ctx_assert:
        lines.append(f"    {ctx_assert}")

    # Only assert inspected if inspect actually runs
    # Conditions:
    # 1. Must be before any catch in source order (otherwise catch handles error first)
    # 2. Must match the error type (but chain-searching bindings can still find original after throw)
    if has_inspect:
        # Find positions and check if inspect will run
        first_catch_idx = None
        first_throw_idx = None
        first_inspect_idx = None
        inspect_binding = None

        inspect_guard = None
        for i, h in enumerate(handlers):
            if h[0] in ["catch", "else"] and first_catch_idx is None:
                first_catch_idx = i
            if h[0] == "throw" and first_throw_idx is None:
                first_throw_idx = i
            if h[0] == "inspect" and first_inspect_idx is None:
                first_inspect_idx = i
                inspect_binding = h[1]
                inspect_guard = h[2]

        # Helper functions (redefined for inspect context)
        def inspect_is_chain_searching(binding_name):
            """Chain-searching bindings find original error even after throw."""
            # For loops, all typed bindings use chain_any
            is_loop_pattern = tp_name in ["for", "any_iter", "while"]
            is_typed = binding_name in ["typed", "typed_short", "any", "any_short", "all"]
            if is_loop_pattern and is_typed:
                return True
            return binding_name in ["any", "any_short", "all"]

        def inspect_is_root_only(binding_name):
            """Root-only bindings won't find original after throw."""
            is_loop_pattern = tp_name in ["for", "any_iter", "while"]
            if is_loop_pattern:
                return False  # Loop patterns always use chain_any
            return binding_name in ["typed", "typed_short"]

        # Check if inspect is typed (looking for io::Error)
        inspect_is_io_typed = inspect_binding in ["typed", "typed_short", "any", "any_short", "all"]

        # Check if inspect guard will match our test errors
        # when_kind guard checks e.kind() == NotFound
        # match_kind: the match runs but `inspected = true` is only in NotFound arm
        # Guard matching depends on binding type
        if inspect_guard == "when_kind":
            if inspect_binding in ["any", "any_short"]:
                inspect_guard_matches = chain_has_notfound
            elif inspect_binding == "all":
                inspect_guard_matches = chain_has_notfound
            else:
                inspect_guard_matches = root_kind_is_notfound
        elif inspect_guard == "match_kind":
            # Match always runs, but inspected is only set in NotFound arm
            # So we need NotFound for the assertion to pass
            if inspect_binding in ["any", "any_short"]:
                inspect_guard_matches = chain_has_notfound
            elif inspect_binding == "all":
                inspect_guard_matches = chain_has_notfound
            else:
                inspect_guard_matches = root_kind_is_notfound
        else:
            inspect_guard_matches = True

        # Check if there's a throw before the inspect that transforms io::Error
        transforming_throw_before_inspect = False
        if first_throw_idx is not None and first_inspect_idx is not None:
            if first_throw_idx < first_inspect_idx:
                for h in handlers[:first_inspect_idx]:
                    if h[0] == "throw":
                        throw_binding = h[1]
                        throw_guard = h[2]

                        # Check if throw guard would match based on binding type
                        if throw_guard == "when_kind":
                            if throw_binding in ["any", "any_short"]:
                                throw_guard_matches = chain_has_notfound
                            elif throw_binding == "all":
                                throw_guard_matches = chain_has_notfound
                            else:
                                throw_guard_matches = root_kind_is_notfound
                        else:
                            throw_guard_matches = True
                        if not throw_guard_matches:
                            continue  # Throw doesn't execute, check next handler

                        # Untyped throw or typed io throw transforms (when guard matches)
                        if throw_binding in ["none", "named", "underscore"]:
                            transforming_throw_before_inspect = True
                            break
                        if throw_binding in ["typed", "typed_short", "any", "any_short", "all"]:
                            transforming_throw_before_inspect = True
                            break

        # Inspect runs if:
        # 1. Inspect comes before first catch (or no catch)
        # 2. AND one of:
        #    a. Inspect is untyped (matches any error)
        #    b. No transforming throw before inspect
        #    c. Inspect uses chain-searching binding (can find original in chain)
        inspect_before_catch = first_catch_idx is None or (first_inspect_idx is not None and first_inspect_idx < first_catch_idx)

        # Type matching logic:
        # - Untyped inspect: always matches
        # - Typed inspect: depends on whether io::Error is findable
        #   - chain_after() preserves original error at root
        #   - multi_io_chain(): root IS io::Error
        #   - chained_io_error(): root is StringError
        # - If throw transforms before inspect:
        #   - Chain-searching: still finds original in chain
        #   - Root-only: won't find (root is transformed)
        needs_all = any(h[1] == "all" for h in handlers)
        needs_any = any(h[1] in ["any", "any_short"] for h in handlers)
        uses_chained_io_error = (
            needs_any and not needs_all
            and tp_name not in ["for", "any_iter", "while", "async"]
        )

        if not inspect_is_io_typed:
            type_matches = True  # Untyped inspect matches any error
        elif uses_chained_io_error and inspect_is_root_only(inspect_binding):
            type_matches = False  # Root is StringError, not io::Error
        elif not transforming_throw_before_inspect:
            type_matches = True  # No transformation, original findable
        elif inspect_is_chain_searching(inspect_binding):
            type_matches = True  # Searches chain, finds original
        else:
            type_matches = False  # Root-only, root is transformed type

        # When require_fail, handlers never run (require fails before try block)
        require_passes = pre_name != "require_fail"
        if require_passes and inspect_before_catch and type_matches and inspect_guard_matches:
            lines.append("    assert!(inspected);")

    lines.append("}")

    return "\n".join(lines), expects_ok, expected_value


# =============================================================================
# Permutation Generator
# =============================================================================

def generate_single_handler_permutations() -> Iterator[Tuple[tuple, List[Tuple[str, str, str]], tuple, tuple]]:
    """Generate all single-handler permutations."""
    for tp in TRY_PATTERNS:
        for kw in HANDLER_KEYWORDS:
            for b in BINDINGS:
                for g in GUARDS:
                    handler = (kw, b[0], g[0])
                    if not is_valid_handler(kw, b[0], g[0], tp[0]):
                        continue
                    for ctx in CONTEXTS:
                        for pre in PRECONDITIONS:
                            if is_valid_combination(tp[0], [handler], ctx[0], pre[0]):
                                yield (tp, [handler], ctx, pre)


def generate_two_handler_permutations() -> Iterator[Tuple[tuple, List[Tuple[str, str, str]], tuple, tuple]]:
    """Generate all two-handler permutations."""
    # Build list of valid handlers per try pattern
    for tp in TRY_PATTERNS:
        if tp[0] == "all_iter":
            continue  # Skip complex result types

        valid_handlers = []
        for kw in HANDLER_KEYWORDS:
            for b in BINDINGS:
                for g in GUARDS:
                    if is_valid_handler(kw, b[0], g[0], tp[0]):
                        valid_handlers.append((kw, b[0], g[0]))

        # Generate pairs - use subset of contexts and preconditions to keep count manageable
        for h1 in valid_handlers:
            for h2 in valid_handlers:
                handlers = [h1, h2]
                for ctx in CONTEXTS[:5]:  # none, with_msg, with_data, with_both, scope
                    for pre in PRECONDITIONS[:2]:  # none, require_pass
                        if is_valid_combination(tp[0], handlers, ctx[0], pre[0]):
                            yield (tp, handlers, ctx, pre)


def generate_three_handler_permutations() -> Iterator[Tuple[tuple, List[Tuple[str, str, str]], tuple, tuple]]:
    """Generate all three-handler permutations.

    This tests complex handler chains like:
    - catch + throw + catch
    - inspect + throw + catch
    - throw + inspect + catch
    etc.
    """
    for tp in TRY_PATTERNS:
        if tp[0] == "all_iter":
            continue  # Skip complex result types
        if tp[0] == "async":
            continue  # Skip async for 3-handler (too many combinations)

        valid_handlers = []
        for kw in HANDLER_KEYWORDS:
            for b in BINDINGS:
                for g in GUARDS:
                    if is_valid_handler(kw, b[0], g[0], tp[0]):
                        valid_handlers.append((kw, b[0], g[0]))

        # Limit handlers to reduce explosion - use simpler bindings/guards for 2nd and 3rd handler
        simple_bindings = ["none", "named", "typed"]
        simple_guards = ["none", "when_true"]

        simple_handlers = [(kw, b, g) for kw, b, g in valid_handlers
                          if b in simple_bindings and g in simple_guards]

        # Generate triples: full × simple × simple to keep count manageable
        for h1 in valid_handlers:
            for h2 in simple_handlers:
                for h3 in simple_handlers:
                    handlers = [h1, h2, h3]
                    # Use minimal contexts for 3-handler
                    for ctx in CONTEXTS[:2]:  # none, with_msg
                        pre = PRECONDITIONS[0]  # none only
                        if is_valid_combination(tp[0], handlers, ctx[0], pre[0]):
                            yield (tp, handlers, ctx, pre)


def generate_no_handler_permutations() -> Iterator[Tuple[tuple, List[Tuple[str, str, str]], tuple, tuple]]:
    """Generate permutations with no handlers (just try block)."""
    for tp in TRY_PATTERNS:
        if tp[0] == "direct":
            continue  # Direct mode needs handler
        for ctx in CONTEXTS:
            for pre in PRECONDITIONS:
                if is_valid_combination(tp[0], [], ctx[0], pre[0]):
                    yield (tp, [], ctx, pre)


def generate_else_suffix_permutations() -> Iterator[Tuple[str, str]]:
    """Generate tests with else suffix on typed handlers.

    Tests patterns like:
    - catch io::Error(e) { 42 } else { 0 }
    - throw io::Error(e) { "msg" } else { "other" }
    """
    tests = []
    counter = 0

    # Test catch Type {} else {}
    for tp in TRY_PATTERNS:
        if tp[0] == "all_iter":
            continue  # Skip complex result types
        if tp[0] == "direct":
            continue  # Direct mode handled separately

        tp_name, tp_pattern, _, tp_setup, tp_result, tp_async, _ = tp

        for bind_name, bind_code, _, _, _ in BINDINGS:
            # Only typed bindings can have else suffix
            if bind_name not in ["typed", "typed_short", "any", "any_short", "all"]:
                continue

            for guard_name, guard_code, needs_typed_e, is_match in GUARDS:
                if needs_typed_e and bind_name not in ["typed", "any"]:
                    continue
                # Skip match clause for else suffix tests (match has its own body structure)
                if is_match:
                    continue

                # Test catch with else
                test_id = f"test_else_suffix_catch_{tp_name}_{bind_name}_{guard_name}_{counter}"
                counter += 1

                lines = []
                if tp_async:
                    lines.append("#[tokio::test]")
                    lines.append(f"async fn {test_id}() {{")
                else:
                    lines.append("#[test]")
                    lines.append(f"fn {test_id}() {{")

                if tp_setup:
                    lines.append(f"    {tp_setup}")

                lines.append(f"    let result: Result<{tp_result}> = handle! {{")

                # Choose appropriate body based on binding
                if bind_name == "all":
                    body = "Err(multi_io_chain())?"
                elif bind_name in ["any", "any_short"]:
                    body = "Err(chained_io_error())?"
                else:
                    body = "io_not_found()?"

                if tp_name in ["for", "any_iter", "while"]:
                    body = "item?" if tp_name != "while" else "attempts += 1; Err(io::Error::other(\"retry\"))?"

                lines.append(f"        {tp_pattern} {{ {body} }}")

                # Build handler with else suffix
                handler_parts = ["catch", bind_code]
                if guard_code:
                    handler_parts.append(guard_code)
                handler_parts.append("{ 42 } else { 0 }")
                lines.append(f"        {' '.join(handler_parts)}")

                lines.append("    };")
                lines.append("    assert!(result.is_ok());")
                lines.append("}")

                tests.append((test_id, "\n".join(lines)))

                # Test throw with else
                test_id = f"test_else_suffix_throw_{tp_name}_{bind_name}_{guard_name}_{counter}"
                counter += 1

                lines = []
                if tp_async:
                    lines.append("#[tokio::test]")
                    lines.append(f"async fn {test_id}() {{")
                else:
                    lines.append("#[test]")
                    lines.append(f"fn {test_id}() {{")

                if tp_setup:
                    lines.append(f"    {tp_setup}")

                lines.append(f"    let result: Result<{tp_result}> = handle! {{")
                lines.append(f"        {tp_pattern} {{ {body} }}")

                # Build throw handler with else suffix
                # throw Type {} else {} means:
                # - If Type matches: transform error, then else catches transformed
                # - If Type doesn't match: else catches original
                # Either way, else handles it (it's a catch-all catch)
                # No additional catch needed - else IS the catch-all
                handler_parts = ["throw", bind_code]
                if guard_code:
                    handler_parts.append(guard_code)
                handler_parts.append('{ "transformed" } else { 0 }')  # else returns value
                lines.append(f"        {' '.join(handler_parts)}")
                # No catch needed - else is the catch-all

                lines.append("    };")
                lines.append("    assert_eq!(result.unwrap(), 0);")  # else returns 0
                lines.append("}")

                tests.append((test_id, "\n".join(lines)))

    return iter(tests)


def generate_nested_body_permutations() -> Iterator[Tuple[str, str]]:
    """Generate tests with nested try blocks in handler bodies.

    Tests patterns like:
    - catch { try { ... } catch { ... } }
    - catch { try -> T { ... } else { ... } }
    - catch { try for x in iter { ... } catch { ... } }
    """
    tests = []
    counter = 0

    for tp in TRY_PATTERNS:
        if tp[0] in ["all_iter", "direct"]:
            continue

        tp_name, tp_pattern, _, tp_setup, tp_result, tp_async, _ = tp

        if tp_async:
            continue  # Skip async for nested tests (complexity)

        # Test nested bodies in catch handlers
        for nested_name, nested_body, returns_value in NESTED_BODIES:
            if nested_body is None:
                continue  # Skip flat - covered by main tests

            # Skip control flow bodies for non-loop patterns
            if "break" in nested_name or "continue" in nested_name:
                continue

            test_id = f"test_nested_{tp_name}_catch_{nested_name}_{counter}"
            counter += 1

            lines = []
            lines.append("#[test]")
            lines.append(f"fn {test_id}() {{")

            if tp_setup:
                lines.append(f"    {tp_setup}")

            lines.append(f"    let result: Result<{tp_result}> = handle! {{")

            # Choose appropriate body
            body = "io_not_found()?"
            if tp_name in ["for", "any_iter"]:
                body = "item?"
            elif tp_name == "while":
                body = "attempts += 1; Err(io::Error::other(\"retry\"))?"

            lines.append(f"        {tp_pattern} {{ {body} }}")
            lines.append(f"        catch {{ {nested_body} }}")

            lines.append("    };")
            lines.append("    assert!(result.is_ok());")
            lines.append("}")

            tests.append((test_id, "\n".join(lines)))

        # Test nested bodies in throw handlers
        for nested_name, nested_body in NESTED_THROW_BODIES:
            if nested_body is None:
                continue

            test_id = f"test_nested_{tp_name}_throw_{nested_name}_{counter}"
            counter += 1

            lines = []
            lines.append("#[test]")
            lines.append(f"fn {test_id}() {{")

            if tp_setup:
                lines.append(f"    {tp_setup}")

            lines.append(f"    let result: Result<{tp_result}> = handle! {{")

            body = "io_not_found()?"
            if tp_name in ["for", "any_iter"]:
                body = "item?"
            elif tp_name == "while":
                body = "attempts += 1; Err(io::Error::other(\"retry\"))?"

            lines.append(f"        {tp_pattern} {{ {body} }}")
            lines.append(f"        throw {{ {nested_body} }}")
            lines.append("        catch { 42 }")

            lines.append("    };")
            lines.append("    assert!(result.is_ok());")
            lines.append("}")

            tests.append((test_id, "\n".join(lines)))

    return iter(tests)


# =============================================================================
# Control Flow Dimensions
# =============================================================================
# Compositional building blocks for control flow tests

# Control flow statements: (name, code)
CF_STATEMENTS = [
    ("break", "break"),
    ("continue", "continue"),
]

# Outer loop types: (name, setup, loop_start, loop_end, counter_var, trigger_cond)
# trigger_cond uses {counter} placeholder for when to trigger error
CF_OUTER_LOOPS = [
    ("for_range", "", "for _ in 0..5 {", "}", "iterations", "{counter} == 2"),
    ("for_enum", "", "for i in 0..5 {", "}", "iterations", "i == 2"),
]

# Try patterns for control flow: (name, pattern, body_template, setup, needs_inner_error)
# body_template uses {error_cond} placeholder
CF_TRY_PATTERNS = [
    ("basic", "try", "if {error_cond} {{ Err(io::Error::other(\"stop\"))? }} 42", "", True),
    ("try_for", "try for i in [1, 2, 3]", "if {error_cond} {{ Err(io::Error::other(\"stop\"))? }} i", "", True),
    ("try_while", "try while retries < 3", "retries += 1; if {error_cond} {{ Err(io::Error::other(\"stop\"))? }} 42", "let mut retries = 0;", True),
    ("try_any", "try any i in [1, 2, 3]", "if {error_cond} {{ Err(io::Error::other(\"stop\"))? }} i", "", True),
    ("try_all", "try all item in [1, 2, 3]", "if {error_cond} {{ Err(io::Error::other(\"stop\"))? }} item", "", True),
]

# Handler types for control flow: (name, keyword, can_have_cf)
CF_HANDLER_TYPES = [
    ("catch", "catch", True),
    ("throw", "throw", True),
    ("inspect", "inspect", True),
]

# Binding variants for control flow handlers: (name, code)
CF_BINDINGS = [
    ("none", ""),
    ("underscore", "_"),
    ("typed", "io::Error(_)"),
]

# Nesting levels: (name, depth)
CF_NESTING = [
    ("flat", 1),
    ("nested", 2),
    ("triple", 3),
]


def build_cf_handler(handler_type: str, binding: str, cf_stmt: str, fallback_value: str = None) -> str:
    """Build a control flow handler string.

    Args:
        handler_type: catch, throw, or inspect
        binding: Binding code (empty, "_", "io::Error(_)", etc.)
        cf_stmt: Control flow statement (break or continue)
        fallback_value: Optional value for non-control-flow path
    """
    parts = [handler_type]
    if binding:
        parts.append(binding)

    if fallback_value is not None:
        # Handler has both control flow and value
        body = f"{{ {cf_stmt}; {fallback_value} }}"
    else:
        # Pure control flow
        body = f"{{ {cf_stmt} }}"

    parts.append(body)
    return " ".join(parts)


def build_cf_nested_try(depth: int, error_cond: str, inner_handler: str, outer_handlers: List[str] = None) -> str:
    """Build nested try blocks with control flow handlers.

    Args:
        depth: Nesting depth (1-3)
        error_cond: Condition that triggers the error
        inner_handler: Handler for the innermost try
        outer_handlers: Handlers for outer try levels (optional)
    """
    if outer_handlers is None:
        outer_handlers = []

    body = f"if {error_cond} {{ Err(io::Error::other(\"err\"))? }} 42"

    # Build from inside out
    for i in range(depth):
        handler = inner_handler if i == 0 else (outer_handlers[i-1] if i-1 < len(outer_handlers) else "")
        body = f"try {{ {body} }} {handler}"

    return body


def generate_cf_test(test_id: str, outer_loop: tuple, try_pattern: tuple,
                     handler: str, setup_extra: str = "", expected_iterations: int = 2,
                     extra_counters: List[str] = None, extra_asserts: List[str] = None,
                     result_type: str = "Result<i32>", use_result: bool = True) -> str:
    """Generate a control flow test.

    Args:
        test_id: Test function name
        outer_loop: Tuple from CF_OUTER_LOOPS
        try_pattern: Tuple from CF_TRY_PATTERNS or custom (name, pattern, body, setup, _)
        handler: Handler string
        setup_extra: Additional setup code
        expected_iterations: Expected iteration count for assertion
        extra_counters: Additional counter variables to declare
        extra_asserts: Additional assertions
        result_type: Type for result binding
        use_result: Whether to bind result to a variable
    """
    loop_name, loop_setup, loop_start, loop_end, counter_var, trigger_cond = outer_loop
    tp_name, tp_pattern, tp_body, tp_setup, _ = try_pattern

    lines = ["#[test]", f"fn {test_id}() {{"]

    # Setup
    if loop_setup:
        lines.append(f"    {loop_setup}")
    lines.append(f"    let mut {counter_var} = 0;")
    if extra_counters:
        for c in extra_counters:
            lines.append(f"    let mut {c} = 0;")
    if setup_extra:
        lines.append(f"    {setup_extra}")

    # Loop
    lines.append(f"    {loop_start}")
    lines.append(f"        {counter_var} += 1;")

    # Try pattern setup
    if tp_setup:
        lines.append(f"        {tp_setup}")

    # Handle! block
    error_cond = trigger_cond.format(counter=counter_var)
    body = tp_body.format(error_cond=error_cond)

    if use_result:
        lines.append(f"        let _: {result_type} = handle! {{")
    else:
        lines.append("        handle! {")
    lines.append(f"            {tp_pattern} {{ {body} }}")
    lines.append(f"            {handler}")
    lines.append("        };")

    lines.append(f"    {loop_end}")

    # Assertions
    lines.append(f"    assert_eq!({counter_var}, {expected_iterations});")
    if extra_asserts:
        for a in extra_asserts:
            lines.append(f"    {a}")

    lines.append("}")
    return "\n".join(lines)


def generate_control_flow_permutations() -> Iterator[Tuple[str, str]]:
    """Generate tests with control flow (break/continue) in handlers.

    Builds tests compositionally from:
    - Outer loop types
    - Try patterns (basic, for, while, any, all)
    - Handler types (catch, throw, inspect)
    - Control flow statements (break, continue)
    - Bindings (none, underscore, typed)
    - Nesting levels (1-3)
    """
    tests = []
    counter = [0]  # Use list for closure mutation

    def make_id(prefix: str) -> str:
        test_id = f"{prefix}_{counter[0]}"
        counter[0] += 1
        return test_id

    # =========================================================================
    # BASIC: Try pattern × Handler type × CF statement × Binding
    # =========================================================================
    for tp_name, tp_pattern, tp_body, tp_setup, _ in CF_TRY_PATTERNS:
        for ht_name, ht_keyword, _ in CF_HANDLER_TYPES:
            for cf_name, cf_code in CF_STATEMENTS:
                for bind_name, bind_code in CF_BINDINGS:
                    # Skip invalid combinations
                    if ht_keyword == "inspect" and bind_name == "none":
                        continue  # inspect requires binding

                    # For loop patterns (try for, try while, etc.):
                    # - Skip typed bindings (produce Result type that needs binding)
                    # - Skip throw (transforms error, needs result handling)
                    # - Skip inspect (propagates error, needs result handling)
                    is_loop_pattern = tp_name != "basic"
                    is_typed = bind_name == "typed"

                    if is_loop_pattern and (is_typed or ht_keyword in ["throw", "inspect"]):
                        continue

                    test_id = make_id(f"test_cf_{tp_name}_{ht_name}_{cf_name}_{bind_name}")
                    handler = build_cf_handler(ht_keyword, bind_code, cf_code)

                    # For try_all, need Vec result type
                    result_type = "Vec<i32>" if tp_name == "try_all" else "i32"
                    # Use result binding for basic pattern
                    use_result = tp_name == "basic"

                    # break stops at iteration 2, continue runs all 5
                    expected_iters = 2 if cf_name == "break" else 5

                    test = generate_cf_test(
                        test_id,
                        CF_OUTER_LOOPS[0],  # for_range
                        (tp_name, tp_pattern, tp_body, tp_setup, True),
                        handler,
                        result_type=f"Result<{result_type}>",
                        use_result=use_result,
                        expected_iterations=expected_iters,
                    )
                    tests.append((test_id, test))

    # =========================================================================
    # NESTED: 2-level nesting with CF in inner vs outer handlers
    # =========================================================================
    for cf_name, cf_code in CF_STATEMENTS:
        for position in ["inner", "outer"]:
            test_id = make_id(f"test_cf_nested_{position}_{cf_name}")
            expected_iters = 2 if cf_name == "break" else 5

            if position == "inner":
                # CF in inner handler, outer has no handler
                inner = f"try {{ if iterations == 2 {{ Err(io::Error::other(\"err\"))? }} 42 }} catch _ {{ {cf_code} }}"
                body = f"try {{ {inner} }}"
            else:
                # Inner has value handler, CF in outer
                inner = "try { if iterations == 2 { Err(io::Error::other(\"err\"))? } 42 }"
                body = f"try {{ {inner} }} catch _ {{ {cf_code} }}"

            test = f'''#[test]
fn {test_id}() {{
    let mut iterations = 0;
    for _ in 0..5 {{
        iterations += 1;
        let _: Result<i32> = handle! {{
            {body}
        }};
    }}
    assert_eq!(iterations, {expected_iters});
}}'''
            tests.append((test_id, test))

    # =========================================================================
    # NESTED: Inner and outer both have control flow (tests hybrid mode)
    # =========================================================================
    for inner_cf, inner_code in CF_STATEMENTS:
        for outer_cf, outer_code in CF_STATEMENTS:
            test_id = make_id(f"test_cf_nested_inner_{inner_cf}_outer_{outer_cf}")

            # Errors on odd iterations (1,3,5,7,9) - inner throw handles all
            # Inner break: stops at iter 1, inner_count=1
            # Inner continue: runs all 10, inner_count=5
            # Outer never runs because inner always handles
            if inner_cf == "break":
                expected_iters = 1
                expected_inner = 1
            else:  # continue
                expected_iters = 10
                expected_inner = 5
            expected_outer = 0

            test = f'''#[test]
fn {test_id}() {{
    let mut inner_count = 0;
    let mut outer_count = 0;
    let mut iterations = 0;
    for _ in 0..10 {{
        iterations += 1;
        let _: Result<i32> = handle! {{
            try {{
                try {{
                    if iterations % 2 == 1 {{
                        Err(io::Error::other("odd"))?
                    }}
                    42
                }}
                throw _ {{
                    inner_count += 1;
                    {inner_code}
                }}
            }}
            catch _ {{
                outer_count += 1;
                {outer_code}
            }}
        }};
    }}
    assert_eq!(iterations, {expected_iters});
    assert_eq!(inner_count, {expected_inner});
    assert_eq!(outer_count, {expected_outer});
}}'''
            tests.append((test_id, test))

    # =========================================================================
    # TRIPLE NESTED: CF at different levels
    # =========================================================================
    for level, level_name in [(0, "innermost"), (1, "middle"), (2, "outermost")]:
        for cf_name, cf_code in CF_STATEMENTS:
            test_id = make_id(f"test_cf_triple_{level_name}_{cf_name}")
            expected_iters = 2 if cf_name == "break" else 5

            # Build triple nested with CF at specified level
            handlers = ["", "", ""]
            handlers[level] = f"catch _ {{ {cf_code} }}"

            inner = "if iterations == 2 { Err(io::Error::other(\"deep\"))? } 42"
            for i in range(3):
                h = handlers[2-i]  # Reverse order (innermost first)
                inner = f"try {{ {inner} }} {h}"

            test = f'''#[test]
fn {test_id}() {{
    let mut iterations = 0;
    for _ in 0..5 {{
        iterations += 1;
        let _: Result<i32> = handle! {{
            {inner}
        }};
    }}
    assert_eq!(iterations, {expected_iters});
}}'''
            tests.append((test_id, test))

    # =========================================================================
    # TYPED HANDLERS: Typed catch/throw with CF and fallbacks
    # =========================================================================
    for cf_name, cf_code in CF_STATEMENTS:
        test_id = make_id(f"test_cf_typed_catch_{cf_name}_with_fallback")
        # i=0,1,3: success
        # i=2: io::Error -> typed catch with CF
        # i=4: ParseIntError -> fallback catch
        # break at i=2: iterations=3, typed=1, fallback=0
        # continue at i=2: iterations=5, typed=1, fallback=1
        if cf_name == "break":
            expected_iters = 3
            expected_typed = 1
            expected_fallback = 0
        else:
            expected_iters = 5
            expected_typed = 1
            expected_fallback = 1

        test = f'''#[test]
fn test_cf_typed_catch_{cf_name}_with_fallback() {{
    let mut typed_count = 0;
    let mut fallback_count = 0;
    let mut iterations = 0;
    for i in 0..5 {{
        iterations += 1;
        let _: Result<i32> = handle! {{
            try {{
                if i == 2 {{
                    Err(io::Error::other("io error"))?
                }} else if i == 4 {{
                    Err("x".parse::<i32>().unwrap_err())?
                }}
                42
            }}
            catch io::Error(_) {{
                typed_count += 1;
                {cf_code}
            }}
            catch _ {{
                fallback_count += 1;
                0
            }}
        }};
    }}
    assert_eq!(iterations, {expected_iters});
    assert_eq!(typed_count, {expected_typed});
    assert_eq!(fallback_count, {expected_fallback});
}}'''
        tests.append((test_id, test))

    # =========================================================================
    # GUARDS: Guard conditions with CF
    # =========================================================================
    for cf_name, cf_code in CF_STATEMENTS:
        test_id = make_id(f"test_cf_guard_when_{cf_name}")
        # Error at iterations >= 2 (so 2,3,4,5) = 4 errors, all NotFound
        # Guard always matches, fallback never runs
        # break: iterations=2, guarded=1, fallback=0
        # continue: iterations=5, guarded=4, fallback=0
        if cf_name == "break":
            expected_iters = 2
            expected_guarded = 1
        else:
            expected_iters = 5
            expected_guarded = 4
        expected_fallback = 0

        test = f'''#[test]
fn {test_id}() {{
    let mut guarded = 0;
    let mut fallback = 0;
    let mut iterations = 0;
    for _ in 0..5 {{
        iterations += 1;
        let _: Result<i32> = handle! {{
            try {{
                if iterations >= 2 {{
                    Err(io::Error::new(ErrorKind::NotFound, "not found"))?
                }}
                42
            }}
            catch io::Error(e) when e.kind() == ErrorKind::NotFound {{
                guarded += 1;
                {cf_code}
            }}
            catch _ {{
                fallback += 1;
                0
            }}
        }};
    }}
    assert_eq!(iterations, {expected_iters});
    assert_eq!(guarded, {expected_guarded});
    assert_eq!(fallback, {expected_fallback});
}}'''
        tests.append((test_id, test))

    # =========================================================================
    # ELSE SUFFIX: Typed catch with else, both having CF
    # =========================================================================
    for main_cf, main_code in CF_STATEMENTS:
        for else_cf, else_code in CF_STATEMENTS:
            if main_cf == else_cf:
                continue  # Skip same CF in both
            test_id = make_id(f"test_cf_else_{main_cf}_{else_cf}")
            # i=0,1: ParseIntError -> else branch
            # i=2: io::Error -> main branch
            # i=3,4: success
            #
            # main=break, else=continue:
            #   i=0: else+continue, i=1: else+continue, i=2: main+break
            #   iterations=3, main=1, else=2
            #
            # main=continue, else=break:
            #   i=0: else+break
            #   iterations=1, main=0, else=1
            if main_cf == "break" and else_cf == "continue":
                expected_iters = 3
                expected_main = 1
                expected_else = 2
            else:  # main=continue, else=break
                expected_iters = 1
                expected_main = 0
                expected_else = 1

            test = f'''#[test]
fn {test_id}() {{
    let mut main_count = 0;
    let mut else_count = 0;
    let mut iterations = 0;
    for i in 0..5 {{
        iterations += 1;
        let _: Result<i32> = handle! {{
            try {{
                if i == 2 {{
                    Err(io::Error::other("io"))?
                }} else if i < 2 {{
                    Err("x".parse::<i32>().unwrap_err())?
                }}
                42
            }}
            catch io::Error(_) {{
                main_count += 1;
                {main_code}
            }} else {{
                else_count += 1;
                {else_code}
            }}
        }};
    }}
    assert_eq!(iterations, {expected_iters});
    assert_eq!(main_count, {expected_main});
    assert_eq!(else_count, {expected_else});
}}'''
            tests.append((test_id, test))

    # =========================================================================
    # THROW + CATCH CHAIN: Throw transforms, catch has CF
    # =========================================================================
    for cf_name, cf_code in CF_STATEMENTS:
        test_id = make_id(f"test_cf_throw_then_catch_{cf_name}")
        expected_iters = 2 if cf_name == "break" else 5
        # With continue, errors happen at iterations 2,3,4,5 (4 times)
        expected_thrown = 1 if cf_name == "break" else 4
        expected_caught = 1 if cf_name == "break" else 4
        test = f'''#[test]
fn {test_id}() {{
    let mut thrown = 0;
    let mut caught = 0;
    let mut iterations = 0;
    for _ in 0..5 {{
        iterations += 1;
        let _: Result<i32> = handle! {{
            try {{
                if iterations >= 2 {{
                    Err(io::Error::other("error"))?
                }}
                42
            }}
            throw _ {{
                thrown += 1;
                "transformed"
            }}
            catch _ {{
                caught += 1;
                {cf_code}
            }}
        }};
    }}
    assert_eq!(iterations, {expected_iters});
    assert_eq!(thrown, {expected_thrown});
    assert_eq!(caught, {expected_caught});
}}'''
        tests.append((test_id, test))

    # =========================================================================
    # INSPECT: Inspect with CF (error still propagates)
    # =========================================================================
    for cf_name, cf_code in CF_STATEMENTS:
        test_id = make_id(f"test_cf_inspect_{cf_name}")
        expected_iters = 2 if cf_name == "break" else 5
        # Inspect only runs on errors, error only at iteration 2
        expected_inspected = 1
        test = f'''#[test]
fn {test_id}() {{
    let mut inspected = 0;
    let mut iterations = 0;
    for _ in 0..5 {{
        iterations += 1;
        let _: Result<i32> = handle! {{
            try {{
                if iterations == 2 {{
                    Err(io::Error::other("error"))?
                }}
                42
            }}
            inspect _ {{
                inspected += 1;
                {cf_code}
            }}
        }};
    }}
    assert_eq!(iterations, {expected_iters});
    assert_eq!(inspected, {expected_inspected});
}}'''
        tests.append((test_id, test))

    # =========================================================================
    # CONTEXT MODIFIERS: with + CF
    # Note: scope with control flow has type inference issues in signal mode
    # =========================================================================
    for cf_name, cf_code in CF_STATEMENTS:
        test_id = make_id(f"test_cf_with_{cf_name}")
        expected_iters = 2 if cf_name == "break" else 5
        test = f'''#[test]
fn {test_id}() {{
    let mut iterations = 0;
    for _ in 0..5 {{
        iterations += 1;
        let _: Result<i32> = handle! {{
            try {{
                if iterations == 2 {{
                    Err(io::Error::other("error"))?
                }}
                42
            }}
            with "context"
            catch _ {{ {cf_code} }}
        }};
    }}
    assert_eq!(iterations, {expected_iters});
}}'''
        tests.append((test_id, test))

    # =========================================================================
    # LOOP PATTERNS NESTED IN TRY
    # =========================================================================
    for inner_pattern in ["try for i in [1, 2, 3]", "try while attempts < 3"]:
        pattern_name = "for" if "for" in inner_pattern else "while"
        setup = "let mut attempts = 0;" if "while" in inner_pattern else ""
        body = "attempts += 1; if iterations == 2 { Err(io::Error::other(\"stop\"))? } 42" if "while" in inner_pattern else "if iterations == 2 { Err(io::Error::other(\"stop\"))? } i"

        for cf_name, cf_code in CF_STATEMENTS:
            test_id = make_id(f"test_cf_{pattern_name}_in_try_{cf_name}")
            expected_iters = 2 if cf_name == "break" else 5
            test = f'''#[test]
fn {test_id}() {{
    let mut iterations = 0;
    for _ in 0..5 {{
        iterations += 1;
        {setup}
        handle! {{
            try {{
                {inner_pattern} {{ {body} }}
                catch _ {{ {cf_code} }}
            }}
        }};
    }}
    assert_eq!(iterations, {expected_iters});
}}'''
            tests.append((test_id, test))

    return iter(tests)


def generate_deeply_nested_permutations() -> Iterator[Tuple[str, str]]:
    """Generate tests with 2-3 levels of nesting.

    Tests patterns like:
    - try { try { try { ... } catch { ... } } catch { ... } } catch { ... }
    - try { try for x in iter { try { ... } catch { ... } } catch { ... } }
    - try for x in iter { try { try { ... } catch { ... } } catch { ... } }
    """
    tests = []
    counter = 0

    # Level 2: try in try
    test_id = f"test_deeply_nested_try_in_try_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{
            try {{ io_not_found()? }} catch {{ 1 }}
        }}
        catch {{ 42 }}
    }};
    assert_eq!(result.unwrap(), 1);
}}'''))

    # Level 2: try in try (inner fails to catch, outer catches)
    test_id = f"test_deeply_nested_try_in_try_outer_catch_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{
            try {{ io_not_found()? }} throw {{ "inner" }}
        }}
        catch {{ 42 }}
    }};
    assert_eq!(result.unwrap(), 42);
}}'''))

    # Level 2: try for in try
    test_id = f"test_deeply_nested_try_for_in_try_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let items = iter_all_fail();
    let result: Result<i32> = handle! {{
        try {{
            try for item in items {{ item? }}
            catch {{ 1 }}
        }}
        catch {{ 42 }}
    }};
    assert_eq!(result.unwrap(), 1);
}}'''))

    # Level 2: try in try for
    test_id = f"test_deeply_nested_try_in_try_for_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let items = iter_all_fail();
    let result: Result<i32> = handle! {{
        try for item in items {{
            try {{ item? }} catch {{ 1 }}
        }}
        catch {{ 42 }}
    }};
    assert_eq!(result.unwrap(), 1);
}}'''))

    # Level 2: try in try with throw
    test_id = f"test_deeply_nested_try_in_try_with_throw_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{
            try {{ io_not_found()? }}
            throw {{ "inner transformed" }}
            catch {{ 1 }}
        }}
        throw {{ "outer transformed" }}
        catch {{ 42 }}
    }};
    assert_eq!(result.unwrap(), 1);
}}'''))

    # Level 2: try in try with inspect
    # Inspect runs BEFORE catch (handlers execute in declaration order)
    test_id = f"test_deeply_nested_try_in_try_with_inspect_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let mut inner_inspected = false;
    let mut outer_inspected = false;
    let result: Result<i32> = handle! {{
        try {{
            try {{ io_not_found()? }}
            inspect _ {{ inner_inspected = true; }}
            catch {{ 1 }}
        }}
        inspect _ {{ outer_inspected = true; }}
        catch {{ 42 }}
    }};
    assert_eq!(result.unwrap(), 1);
    assert!(inner_inspected);  // inspect runs before catch (declaration order)
    assert!(!outer_inspected);  // inner catch handles error, nothing reaches outer
}}'''))

    # Level 3: try in try in try
    test_id = f"test_deeply_nested_3_levels_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{
            try {{
                try {{ io_not_found()? }}
                catch {{ 1 }}
            }}
            catch {{ 2 }}
        }}
        catch {{ 42 }}
    }};
    assert_eq!(result.unwrap(), 1);
}}'''))

    # Level 3: error propagates through all levels
    test_id = f"test_deeply_nested_3_levels_propagate_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{
            try {{
                try {{ io_not_found()? }}
                throw {{ "level 1" }}
            }}
            throw {{ "level 2" }}
        }}
        catch {{ 42 }}
    }};
    assert_eq!(result.unwrap(), 42);
}}'''))

    # Level 2: try for in try for (complex control flow)
    # The inner try for with iter_all_ok succeeds on first item, returning Ok(1)
    # This success propagates to outer try for, which returns it
    test_id = f"test_deeply_nested_try_for_in_try_for_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try for _outer in [1, 2, 3] {{
            let inner_items = iter_all_ok();
            try for inner in inner_items {{
                inner?
            }}
            catch {{ 99 }}
        }}
        catch {{ 42 }}
    }};
    // Inner try for succeeds with first Ok value (1)
    // Outer try for sees success, returns 1
    assert_eq!(result.unwrap(), 1);
}}'''))

    # Level 2: try while in try
    test_id = f"test_deeply_nested_try_while_in_try_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let mut attempts = 0;
    let result: Result<i32> = handle! {{
        try {{
            try while attempts < 3 {{
                attempts += 1;
                Err(io::Error::other("retry"))?
            }}
            catch {{ 1 }}
        }}
        catch {{ 42 }}
    }};
    assert_eq!(result.unwrap(), 1);
}}'''))

    # Level 2: try in try while
    test_id = f"test_deeply_nested_try_in_try_while_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let mut attempts = 0;
    let result: Result<i32> = handle! {{
        try while attempts < 3 {{
            attempts += 1;
            try {{ io_not_found()? }} catch {{ 1 }}
        }}
        catch {{ 42 }}
    }};
    // Inner try catches, returning Ok(1), which succeeds the while loop
    assert_eq!(result.unwrap(), 1);
}}'''))

    # Direct mode with nested try
    test_id = f"test_deeply_nested_direct_with_try_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: i32 = handle! {{
        try -> i32 {{ io_not_found()? }}
        catch {{
            try {{ io_not_found()? }} catch {{ 1 }}
        }}
    }};
    assert_eq!(result, 1);
}}'''))

    # Direct mode with nested try for
    test_id = f"test_deeply_nested_direct_with_try_for_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let items = iter_all_fail();
    let result: i32 = handle! {{
        try -> i32 {{ io_not_found()? }}
        catch {{
            try for item in items {{ item? }}
            catch {{ 1 }}
        }}
    }};
    assert_eq!(result, 1);
}}'''))

    # Nested try with typed catch
    test_id = f"test_deeply_nested_typed_catch_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{
            try {{ io_not_found()? }}
            catch io::Error(e) {{ let _ = e.kind(); 1 }}
            else {{ 2 }}
        }}
        catch {{ 42 }}
    }};
    assert_eq!(result.unwrap(), 1);
}}'''))

    # Nested try with chain searching
    test_id = f"test_deeply_nested_chain_search_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{
            try {{ Err(chained_io_error())? }}
            catch any io::Error(e) {{ let _ = e.kind(); 1 }}
        }}
        catch {{ 42 }}
    }};
    assert_eq!(result.unwrap(), 1);
}}'''))

    return iter(tests)


def generate_comprehensive_nested_permutations() -> Iterator[Tuple[str, str]]:
    """Generate comprehensive nested permutations.

    Tests nesting in multiple positions with up to 3 levels of depth:
    - try_body: The expression inside try { EXPR }
    - catch_body: The expression inside catch { EXPR }
    - throw_body: The expression inside throw { EXPR }
    - inspect_body: The expression inside inspect { EXPR }

    Combinations tested:
    1. Single position nesting (each position with each nesting type)
    2. Multi-position nesting (2-4 positions with nesting simultaneously)
    3. Deep nesting (2-3 levels in one position)
    4. Mixed (deep nesting + multi-position)
    """
    tests = []
    counter = 0

    # ==========================================================================
    # Part 1: Single position nesting with various nesting types
    # ==========================================================================

    # 1a. Nesting in try_body (the error source)
    for name, nested_code in NESTED_TRY_I32:
        if nested_code is None:
            continue
        test_id = f"test_comp_nested_try_body_{name}_{counter}"
        counter += 1
        tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{
            {nested_code}
        }}
        catch {{ 99 }}
    }};
    assert!(result.is_ok());
}}'''))

    # 1b. Nesting in catch_body
    for name, nested_code in NESTED_TRY_I32:
        if nested_code is None:
            continue
        test_id = f"test_comp_nested_catch_body_{name}_{counter}"
        counter += 1
        tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{ io_not_found()? }}
        catch {{
            {nested_code}
        }}
    }};
    assert!(result.is_ok());
}}'''))

    # 1c. Nesting in throw_body
    for name, nested_code in NESTED_TRY_STR:
        if nested_code is None:
            continue
        test_id = f"test_comp_nested_throw_body_{name}_{counter}"
        counter += 1
        tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{ io_not_found()? }}
        throw {{
            {nested_code}
        }}
        catch {{ 99 }}
    }};
    assert!(result.is_ok());
}}'''))

    # 1d. Nesting in inspect_body
    for name, nested_code in NESTED_TRY_I32:
        if nested_code is None:
            continue
        test_id = f"test_comp_nested_inspect_body_{name}_{counter}"
        counter += 1
        tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{ io_not_found()? }}
        inspect _ {{
            let _ = {nested_code};
        }}
        catch {{ 99 }}
    }};
    assert!(result.is_ok());
}}'''))

    # ==========================================================================
    # Part 2: Level 2 nesting (try inside try)
    # ==========================================================================

    for name, nested_code in NESTED_L2_I32:
        # In try_body
        test_id = f"test_comp_nested_l2_try_{name}_{counter}"
        counter += 1
        tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{
            {nested_code}
        }}
        catch {{ 99 }}
    }};
    assert!(result.is_ok());
}}'''))

        # In catch_body
        test_id = f"test_comp_nested_l2_catch_{name}_{counter}"
        counter += 1
        tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{ io_not_found()? }}
        catch {{
            {nested_code}
        }}
    }};
    assert!(result.is_ok());
}}'''))

    # ==========================================================================
    # Part 3: Level 3 nesting (try inside try inside try)
    # ==========================================================================

    for name, nested_code in NESTED_L3_I32:
        test_id = f"test_comp_nested_l3_{name}_{counter}"
        counter += 1
        tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{
            {nested_code}
        }}
        catch {{ 99 }}
    }};
    assert!(result.is_ok());
}}'''))

    # ==========================================================================
    # Part 4: Multi-position nesting (nesting in multiple blocks simultaneously)
    # ==========================================================================

    # 4a. try_body AND catch both have nesting
    test_id = f"test_comp_nested_multi_try_catch_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{
            try {{ io_not_found()? }} catch {{ 1 }}
        }}
        catch {{
            try {{ io_not_found()? }} catch {{ 2 }}
        }}
    }};
    // Inner try catches, returns 1
    assert_eq!(result.unwrap(), 1);
}}'''))

    # 4b. try_body AND throw_body both have nesting
    test_id = f"test_comp_nested_multi_try_throw_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{
            try {{ io_not_found()? }} throw {{ "inner" }}
        }}
        throw {{
            try -> String {{ "nested_throw".to_string() }} else {{ "fallback".to_string() }}
        }}
        catch {{ 99 }}
    }};
    // Inner try throws, outer throw transforms, catch catches
    assert_eq!(result.unwrap(), 99);
}}'''))

    # 4c. try_body AND inspect_body both have nesting
    test_id = f"test_comp_nested_multi_try_inspect_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let mut inspected = false;
    let result: Result<i32> = handle! {{
        try {{
            try {{ io_not_found()? }} throw {{ "will propagate" }}
        }}
        inspect _ {{
            let _ = try {{ io_ok()? }} catch {{ 0 }};
            inspected = true;
        }}
        catch {{ 99 }}
    }};
    assert_eq!(result.unwrap(), 99);
    assert!(inspected);
}}'''))

    # 4d. catch AND throw both have nesting
    test_id = f"test_comp_nested_multi_catch_throw_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{ io_not_found()? }}
        throw {{
            try -> String {{ "transformed".to_string() }} else {{ "fallback".to_string() }}
        }}
        catch {{
            try {{ io_not_found()? }} catch {{ 42 }}
        }}
    }};
    assert_eq!(result.unwrap(), 42);
}}'''))

    # 4e. Three positions: try_body, throw, catch all have nesting
    test_id = f"test_comp_nested_multi_3pos_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{
            try {{ io_not_found()? }} catch {{ 1 }}
        }}
        throw {{
            try -> String {{ "t".to_string() }} else {{ "f".to_string() }}
        }}
        catch {{
            try {{ io_ok()? }} catch {{ 2 }}
        }}
    }};
    // Inner catch handles, returns 1
    assert_eq!(result.unwrap(), 1);
}}'''))

    # 4f. Four positions: try_body, throw, inspect, catch all have nesting
    test_id = f"test_comp_nested_multi_4pos_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let mut seen = false;
    let result: Result<i32> = handle! {{
        try {{
            try {{ io_not_found()? }} throw {{ "propagate" }}
        }}
        throw {{
            try -> String {{ "outer_throw".to_string() }} else {{ "f".to_string() }}
        }}
        inspect _ {{
            let _ = try {{ io_ok()? }} catch {{ 0 }};
            seen = true;
        }}
        catch {{
            try {{ io_not_found()? }} catch {{ 42 }}
        }}
    }};
    assert_eq!(result.unwrap(), 42);
    assert!(seen);
}}'''))

    # ==========================================================================
    # Part 5: Mixed deep + multi-position
    # ==========================================================================

    # 5a. Level 2 in try_body + nesting in catch
    test_id = f"test_comp_nested_mixed_l2try_catch_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{
            try {{
                try {{ io_not_found()? }} catch {{ 1 }}
            }}
            catch {{ 2 }}
        }}
        catch {{
            try {{ io_not_found()? }} catch {{ 99 }}
        }}
    }};
    assert_eq!(result.unwrap(), 1);
}}'''))

    # 5b. Level 3 in try_body + nesting in catch + nesting in throw
    test_id = f"test_comp_nested_mixed_l3_multi_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{
            try {{
                try {{
                    try {{ io_not_found()? }} catch {{ 1 }}
                }}
                catch {{ 2 }}
            }}
            throw {{ "l2_throw" }}
            catch {{ 3 }}
        }}
        throw {{
            try -> String {{ "outer".to_string() }} else {{ "f".to_string() }}
        }}
        catch {{
            try {{ io_ok()? }} catch {{ 99 }}
        }}
    }};
    assert_eq!(result.unwrap(), 1);
}}'''))

    # ==========================================================================
    # Part 6: Iteration patterns with nesting
    # ==========================================================================

    # 6a. try for with nesting in body
    test_id = f"test_comp_nested_for_nested_body_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let items = iter_all_fail();
    let result: Result<i32> = handle! {{
        try for item in items {{
            try {{ item? }} catch {{ 1 }}
        }}
        catch {{ 99 }}
    }};
    // Inner try catches, returns Ok(1)
    assert_eq!(result.unwrap(), 1);
}}'''))

    # 6b. try for with nesting in catch
    test_id = f"test_comp_nested_for_nested_catch_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let items = iter_all_fail();
    let result: Result<i32> = handle! {{
        try for item in items {{
            item?
        }}
        catch {{
            try {{ io_not_found()? }} catch {{ 42 }}
        }}
    }};
    assert_eq!(result.unwrap(), 42);
}}'''))

    # 6c. try for in try for (double iteration)
    test_id = f"test_comp_nested_for_for_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try for _outer in [1, 2, 3] {{
            let inner_items = iter_all_ok();
            try for inner in inner_items {{
                inner?
            }}
            catch {{ 99 }}
        }}
        catch {{ 88 }}
    }};
    // Inner try for succeeds with 1
    assert_eq!(result.unwrap(), 1);
}}'''))

    # 6d. try while with nesting
    test_id = f"test_comp_nested_while_nested_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let mut attempts = 0;
    let result: Result<i32> = handle! {{
        try while attempts < 3 {{
            attempts += 1;
            try {{ Err(io::Error::other("retry"))? }} catch {{ 1 }}
        }}
        catch {{ 99 }}
    }};
    // Inner catch returns Ok(1) on first attempt
    assert_eq!(result.unwrap(), 1);
}}'''))

    # 6e. try all with nesting in body
    test_id = f"test_comp_nested_all_nested_body_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let items = iter_all_ok();
    let result: Result<Vec<i32>> = handle! {{
        try all item in items {{
            try -> i32 {{ item? }} else {{ 0 }}
        }}
        catch {{ vec![] }}
    }};
    assert_eq!(result.unwrap(), vec![1, 2, 3]);
}}'''))

    # ==========================================================================
    # Part 7: Async patterns with nesting
    # ==========================================================================

    # Note: Nested try blocks inside async try are SYNC, so they use sync functions
    test_id = f"test_comp_nested_async_try_{counter}"
    counter += 1
    tests.append((test_id, f'''#[tokio::test]
async fn {test_id}() {{
    let result: Result<i32> = handle! {{
        async try {{
            try {{ io_not_found()? }} catch {{ 1 }}
        }}
        catch {{ 99 }}
    }};
    assert_eq!(result.unwrap(), 1);
}}'''))

    test_id = f"test_comp_nested_async_catch_{counter}"
    counter += 1
    tests.append((test_id, f'''#[tokio::test]
async fn {test_id}() {{
    let result: Result<i32> = handle! {{
        async try {{
            async_io_not_found().await?
        }}
        catch {{
            try {{ io_ok()? }} catch {{ 1 }}
        }}
    }};
    // Outer catch runs, nested try succeeds with io_ok() = 42
    assert_eq!(result.unwrap(), 42);
}}'''))

    test_id = f"test_comp_nested_async_multi_{counter}"
    counter += 1
    tests.append((test_id, f'''#[tokio::test]
async fn {test_id}() {{
    let result: Result<i32> = handle! {{
        async try {{
            try {{ io_not_found()? }} throw {{ "propagate" }}
        }}
        throw {{
            try -> String {{ "transformed".to_string() }} else {{ "f".to_string() }}
        }}
        catch {{
            try {{ io_not_found()? }} catch {{ 42 }}
        }}
    }};
    assert_eq!(result.unwrap(), 42);
}}'''))

    # ==========================================================================
    # Part 8: Direct mode with nesting
    # ==========================================================================

    test_id = f"test_comp_nested_direct_try_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: i32 = handle! {{
        try -> i32 {{
            try {{ io_not_found()? }} catch {{ 1 }}
        }}
        else {{ 99 }}
    }};
    assert_eq!(result, 1);
}}'''))

    test_id = f"test_comp_nested_direct_else_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: i32 = handle! {{
        try -> i32 {{ io_not_found()? }}
        else {{
            try {{ io_not_found()? }} catch {{ 42 }}
        }}
    }};
    assert_eq!(result, 42);
}}'''))

    test_id = f"test_comp_nested_direct_multi_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: i32 = handle! {{
        try -> i32 {{
            try {{ io_not_found()? }} throw {{ "propagate" }}
        }}
        catch io::Error(_) {{
            try {{ io_not_found()? }} catch {{ 42 }}
        }}
        else {{
            try {{ io_ok()? }} catch {{ 0 }}
        }}
    }};
    // Inner throw propagates, io::Error catches, nested try catches
    assert_eq!(result, 42);
}}'''))

    # ==========================================================================
    # Part 9: Context modifiers with nesting
    # ==========================================================================

    test_id = f"test_comp_nested_with_context_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{
            try {{ io_not_found()? }}
            with "inner context"
            catch {{ 1 }}
        }}
        with "outer context"
        catch {{ 99 }}
    }};
    assert_eq!(result.unwrap(), 1);
}}'''))

    test_id = f"test_comp_nested_with_scope_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        scope "outer",
        try {{
            scope "inner",
            try {{ io_not_found()? }}
            catch {{ 1 }}
        }}
        catch {{ 99 }}
    }};
    assert_eq!(result.unwrap(), 1);
}}'''))

    test_id = f"test_comp_nested_with_finally_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let mut inner_finalized = false;
    let mut outer_finalized = false;
    let result: Result<i32> = handle! {{
        try {{
            try {{ io_not_found()? }}
            finally {{ inner_finalized = true; }}
            catch {{ 1 }}
        }}
        finally {{ outer_finalized = true; }}
        catch {{ 99 }}
    }};
    assert_eq!(result.unwrap(), 1);
    assert!(inner_finalized);
    assert!(outer_finalized);
}}'''))

    # ==========================================================================
    # Part 10: Typed catches with nesting
    # ==========================================================================

    test_id = f"test_comp_nested_typed_inner_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{
            try {{ io_not_found()? }}
            catch io::Error(e) {{ let _ = e.kind(); 1 }}
            else {{ 2 }}
        }}
        catch {{ 99 }}
    }};
    assert_eq!(result.unwrap(), 1);
}}'''))

    test_id = f"test_comp_nested_typed_outer_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{
            try {{ io_not_found()? }} throw {{ "inner propagate" }}
        }}
        catch io::Error(_) {{
            try {{ io_not_found()? }} catch {{ 42 }}
        }}
        else {{ 99 }}
    }};
    // Inner throw changes type to String, io::Error doesn't match, else catches
    assert_eq!(result.unwrap(), 99);
}}'''))

    test_id = f"test_comp_nested_any_chain_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{
            try {{ Err(chained_io_error())? }}
            catch any io::Error(e) {{ let _ = e.kind(); 1 }}
        }}
        catch {{ 99 }}
    }};
    assert_eq!(result.unwrap(), 1);
}}'''))

    test_id = f"test_comp_nested_all_chain_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{
            try {{ Err(multi_io_chain())? }}
            catch all io::Error |errors| {{ errors.len() as i32 }}
        }}
        catch {{ 99 }}
    }};
    assert_eq!(result.unwrap(), 2);  // Two io::Errors in chain
}}'''))

    # ==========================================================================
    # Part 11: else_body nesting (direct mode and typed catch fallback)
    # ==========================================================================

    test_id = f"test_comp_nested_else_direct_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: i32 = handle! {{
        try -> i32 {{ io_not_found()? }}
        else {{
            try {{ io_not_found()? }} catch {{ 42 }}
        }}
    }};
    assert_eq!(result, 42);
}}'''))

    test_id = f"test_comp_nested_else_typed_fallback_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{ Err(Handled::msg("not io"))? }}
        catch io::Error(_) {{ 1 }}
        else {{
            try {{ io_not_found()? }} catch {{ 42 }}
        }}
    }};
    // Not io::Error, falls to else, nested try catches
    assert_eq!(result.unwrap(), 42);
}}'''))

    # ==========================================================================
    # Part 12: finally_body nesting
    # ==========================================================================

    test_id = f"test_comp_nested_finally_with_try_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let mut cleanup_result = 0;
    let result: Result<i32> = handle! {{
        try {{ io_not_found()? }}
        finally {{
            // Nesting in finally - cleanup logic
            cleanup_result = try {{ io_ok()? }} catch {{ 99 }};
        }}
        catch {{ 42 }}
    }};
    assert_eq!(result.unwrap(), 42);
    assert_eq!(cleanup_result, 42);  // io_ok returns 42
}}'''))

    # ==========================================================================
    # Part 13: try_catch_body nesting (returns Result)
    # ==========================================================================

    test_id = f"test_comp_nested_try_catch_body_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{ io_not_found()? }}
        try catch e {{
            // try catch can use ? and return Result
            let inner: i32 = try {{ io_not_found()? }} catch {{ 42 }};
            if inner > 0 {{ Ok(inner) }} else {{ Err(e) }}
        }}
    }};
    assert_eq!(result.unwrap(), 42);
}}'''))

    # Note: Can't have `try catch` followed by `catch` - try catch handles all errors
    # So we test try catch with typed inner patterns instead
    test_id = f"test_comp_nested_try_catch_typed_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{ io_not_found()? }}
        try catch e {{
            // Nested try with direct mode (no catch needed since it's infallible)
            let inner: i32 = try -> i32 {{ 42 }} else {{ 0 }};
            if inner > 0 {{ Ok(inner) }} else {{ Err(e) }}
        }}
    }};
    assert_eq!(result.unwrap(), 42);
}}'''))

    # ==========================================================================
    # Part 14: match_arm nesting
    # ==========================================================================
    # NOTE: Nested try blocks inside match arms are NOT supported.
    # The macro can't parse `try { } catch { }` as a match arm expression.
    # Users should use blocks or separate bindings instead:
    #   catch io::Error(e) match e.kind() {
    #       ErrorKind::NotFound => { let v = try { ... } catch { }; v },
    #       _ => 0
    #   }
    # For now, we test match arms with simple expressions only.

    test_id = f"test_comp_nested_match_simple_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{ io_not_found()? }}
        catch io::Error(e) match e.kind() {{
            ErrorKind::NotFound => 42,
            _ => 0
        }}
    }};
    assert_eq!(result.unwrap(), 42);
}}'''))

    # ==========================================================================
    # Part 15: require_else nesting
    # ==========================================================================
    # NOTE: `let` statements inside require_else blocks don't work in macro context.
    # Nested try blocks work when used directly as expressions.

    test_id = f"test_comp_nested_require_else_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        require false else "required condition failed",
        try {{ io_ok()? }}
    }};
    // require fails, returns error
    assert!(result.is_err());
}}'''))

    # ==========================================================================
    # Part 16: Loop bodies with multi-position nesting
    # ==========================================================================

    # for_body + catch_body both nested
    test_id = f"test_comp_nested_for_body_and_catch_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let items = iter_all_fail();
    let result: Result<i32> = handle! {{
        try for item in items {{
            // Nesting in for_body
            try {{ item? }} throw {{ "transform" }}
        }}
        catch {{
            // Nesting in catch_body
            try {{ io_not_found()? }} catch {{ 42 }}
        }}
    }};
    // for_body nested throw propagates, catch nested try catches
    assert_eq!(result.unwrap(), 42);
}}'''))

    # while_body + catch_body both nested
    test_id = f"test_comp_nested_while_body_and_catch_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let mut attempts = 0;
    let result: Result<i32> = handle! {{
        try while attempts < 2 {{
            attempts += 1;
            // Nesting in while_body
            try {{ Err(io::Error::other("retry"))? }} throw {{ "transformed" }}
        }}
        catch {{
            // Nesting in catch_body
            try {{ io_not_found()? }} catch {{ 42 }}
        }}
    }};
    assert_eq!(result.unwrap(), 42);
}}'''))

    # all_body + catch_body both nested
    test_id = f"test_comp_nested_all_body_and_catch_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let items = iter_all_ok();
    let result: Result<Vec<i32>> = handle! {{
        try all item in items {{
            // Nesting in all_body
            try -> i32 {{ item? }} else {{ 0 }}
        }}
        catch {{
            // Nesting in catch_body (won't run since all succeeds)
            // Note: can't use try inside vec![] macro, use block instead
            {{ let v = try {{ io_ok()? }} catch {{ 99 }}; vec![v] }}
        }}
    }};
    assert_eq!(result.unwrap(), vec![1, 2, 3]);
}}'''))

    # ==========================================================================
    # Part 17: Deep nesting in loop bodies
    # ==========================================================================

    test_id = f"test_comp_nested_for_l2_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let items = iter_all_fail();
    let result: Result<i32> = handle! {{
        try for item in items {{
            // Level 2 nesting in for_body
            try {{
                try {{ item? }} catch {{ 1 }}
            }}
            catch {{ 2 }}
        }}
        catch {{ 99 }}
    }};
    assert_eq!(result.unwrap(), 1);
}}'''))

    test_id = f"test_comp_nested_while_l2_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let mut attempts = 0;
    let result: Result<i32> = handle! {{
        try while attempts < 2 {{
            attempts += 1;
            // Level 2 nesting in while_body
            try {{
                try {{ Err(io::Error::other("r"))? }} catch {{ 1 }}
            }}
            catch {{ 2 }}
        }}
        catch {{ 99 }}
    }};
    assert_eq!(result.unwrap(), 1);
}}'''))

    # ==========================================================================
    # Part 18: Multiple loop patterns nested
    # ==========================================================================

    test_id = f"test_comp_nested_while_in_for_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try for _outer in [1, 2] {{
            let mut att = 0;
            try while att < 2 {{
                att += 1;
                Err(io::Error::other("retry"))?
            }}
            catch {{ 1 }}
        }}
        catch {{ 99 }}
    }};
    // Inner while exhausts retries, its catch returns 1
    assert_eq!(result.unwrap(), 1);
}}'''))

    test_id = f"test_comp_nested_for_in_while_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let mut attempts = 0;
    let result: Result<i32> = handle! {{
        try while attempts < 2 {{
            attempts += 1;
            let items = iter_all_ok();
            try for item in items {{
                item?
            }}
            catch {{ 99 }}
        }}
        catch {{ 88 }}
    }};
    // Inner for succeeds with 1
    assert_eq!(result.unwrap(), 1);
}}'''))

    # ==========================================================================
    # Part 19: Five positions all nested simultaneously
    # ==========================================================================

    test_id = f"test_comp_nested_5pos_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let mut inspected = false;
    let mut finalized = false;
    let result: Result<i32> = handle! {{
        try {{
            // try_body nested
            try {{ io_not_found()? }} throw {{ "prop" }}
        }}
        throw {{
            // throw_body nested
            try -> String {{ "t".to_string() }} else {{ "f".to_string() }}
        }}
        inspect _ {{
            // inspect_body nested
            let _ = try {{ io_ok()? }} catch {{ 0 }};
            inspected = true;
        }}
        finally {{
            // finally_body nested
            let _ = try {{ io_ok()? }} catch {{ 0 }};
            finalized = true;
        }}
        catch {{
            // catch_body nested
            try {{ io_not_found()? }} catch {{ 42 }}
        }}
    }};
    assert_eq!(result.unwrap(), 42);
    assert!(inspected);
    assert!(finalized);
}}'''))

    # ==========================================================================
    # Part 20: All block types with same nested pattern
    # ==========================================================================

    # Use a simple nested pattern in EVERY block type that supports it
    test_id = f"test_comp_nested_all_blocks_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let mut inspected = false;
    let mut finalized = false;
    let result: Result<i32> = handle! {{
        try {{
            try {{ io_not_found()? }} catch {{ 1 }}  // try_body
        }}
        throw {{
            try -> String {{ "x".to_string() }} else {{ "y".to_string() }}  // throw_body
        }}
        inspect _ {{
            let _ = try {{ io_ok()? }} catch {{ 0 }};  // inspect_body
            inspected = true;
        }}
        finally {{
            let _ = try {{ io_ok()? }} catch {{ 0 }};  // finally_body
            finalized = true;
        }}
        catch {{
            try {{ io_not_found()? }} catch {{ 42 }}  // catch_body
        }}
    }};
    // try_body catches first, returns 1
    assert_eq!(result.unwrap(), 1);
    assert!(!inspected);  // inner catch handled, no error reaches inspect
    assert!(finalized);   // finally always runs
}}'''))

    # ==========================================================================
    # Part 21: Programmatic all-pairs nested combinations
    # ==========================================================================

    # Define reusable nested patterns for each block type
    # Note: Use single braces since these are inserted into f-strings
    NESTED_FOR_TRY = "try { io_not_found()? } catch { 1 }"
    NESTED_FOR_CATCH = "try { io_ok()? } catch { 42 }"
    NESTED_FOR_THROW = 'try -> String { "x".to_string() } else { "y".to_string() }'
    NESTED_FOR_INSPECT = "let _ = try { io_ok()? } catch { 0 };"

    # All pairs of (try_body nested, catch_body nested) with different patterns
    for try_nested in [NESTED_FOR_TRY, "try { io_ok()? } catch { 1 }"]:
        for catch_nested in [NESTED_FOR_CATCH, "try { io_ok()? } catch { 1 }"]:
            test_id = f"test_comp_nested_pair_try_catch_{counter}"
            counter += 1
            tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{ {try_nested} }}
        catch {{ {catch_nested} }}
    }};
    assert!(result.is_ok());
}}'''))

    # All pairs of (throw_body nested, catch_body nested)
    for throw_nested in [NESTED_FOR_THROW]:
        for catch_nested in [NESTED_FOR_CATCH, "try { io_ok()? } catch { 1 }"]:
            test_id = f"test_comp_nested_pair_throw_catch_{counter}"
            counter += 1
            tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{ io_not_found()? }}
        throw {{ {throw_nested} }}
        catch {{ {catch_nested} }}
    }};
    assert!(result.is_ok());
}}'''))

    # All pairs of (inspect_body nested, catch_body nested)
    for catch_nested in [NESTED_FOR_CATCH, "try { io_ok()? } catch { 1 }"]:
        test_id = f"test_comp_nested_pair_inspect_catch_{counter}"
        counter += 1
        tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let mut inspected = false;
    let result: Result<i32> = handle! {{
        try {{ io_not_found()? }}
        inspect _ {{ {NESTED_FOR_INSPECT} inspected = true; }}
        catch {{ {catch_nested} }}
    }};
    assert!(result.is_ok());
    assert!(inspected);
}}'''))

    # ==========================================================================
    # Part 22: Triple nested positions - all combinations
    # ==========================================================================

    # try + throw + catch all nested
    for try_nested in [NESTED_FOR_TRY]:
        for throw_nested in [NESTED_FOR_THROW]:
            for catch_nested in [NESTED_FOR_CATCH]:
                test_id = f"test_comp_nested_triple_ttc_{counter}"
                counter += 1
                tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{ {try_nested} }}
        throw {{ {throw_nested} }}
        catch {{ {catch_nested} }}
    }};
    assert!(result.is_ok());
}}'''))

    # try + inspect + catch all nested
    test_id = f"test_comp_nested_triple_tic_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let mut inspected = false;
    let result: Result<i32> = handle! {{
        try {{ {NESTED_FOR_TRY} }}
        inspect _ {{ {NESTED_FOR_INSPECT} inspected = true; }}
        catch {{ {NESTED_FOR_CATCH} }}
    }};
    assert!(result.is_ok());
}}'''))

    # ==========================================================================
    # Part 23: Nested patterns with different try variants
    # ==========================================================================

    # Basic try with each handler type having nested
    for handler_type in ["catch", "throw"]:
        for nested_in_handler in [True, False]:
            for nested_in_try in [True, False]:
                if not nested_in_handler and not nested_in_try:
                    continue  # At least one must be nested
                test_id = f"test_comp_nested_variant_{handler_type}_h{int(nested_in_handler)}_t{int(nested_in_try)}_{counter}"
                counter += 1

                try_body = NESTED_FOR_TRY if nested_in_try else "io_not_found()?"

                if handler_type == "catch":
                    handler_body = NESTED_FOR_CATCH if nested_in_handler else "42"
                    handler_code = f"catch {{ {handler_body} }}"
                else:
                    handler_body = NESTED_FOR_THROW if nested_in_handler else '"error"'
                    handler_code = f'throw {{ {handler_body} }} catch {{ 42 }}'

                tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{ {try_body} }}
        {handler_code}
    }};
    assert!(result.is_ok());
}}'''))

    # ==========================================================================
    # Part 24: Nested with typed handlers
    # ==========================================================================

    # Typed catch with nested in body
    test_id = f"test_comp_nested_typed_catch_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{ io_not_found()? }}
        catch io::Error(_) {{
            {NESTED_FOR_CATCH}
        }}
        else {{ 0 }}
    }};
    assert!(result.is_ok());
}}'''))

    # Typed throw with nested in body
    test_id = f"test_comp_nested_typed_throw_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{ io_not_found()? }}
        throw io::Error(_) {{
            {NESTED_FOR_THROW}
        }}
        catch {{ 42 }}
    }};
    assert!(result.is_ok());
}}'''))

    # Any chain with nested
    test_id = f"test_comp_nested_any_chain_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{ Err(chained_io_error())? }}
        catch any io::Error(_) {{
            {NESTED_FOR_CATCH}
        }}
    }};
    assert!(result.is_ok());
}}'''))

    # All chain with nested
    test_id = f"test_comp_nested_all_chain_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{ Err(multi_io_chain())? }}
        catch all io::Error |errors| {{
            let _ = {NESTED_FOR_CATCH};
            errors.len() as i32
        }}
    }};
    assert!(result.is_ok());
}}'''))

    # ==========================================================================
    # Part 25: Nested with guards
    # ==========================================================================

    # when guard with nested
    test_id = f"test_comp_nested_when_guard_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{ io_not_found()? }}
        catch io::Error(e) when e.kind() == ErrorKind::NotFound {{
            {NESTED_FOR_CATCH}
        }}
        else {{ 0 }}
    }};
    assert!(result.is_ok());
}}'''))

    # ==========================================================================
    # Part 26: Nested in async context
    # ==========================================================================

    test_id = f"test_comp_nested_async_{counter}"
    counter += 1
    tests.append((test_id, f'''#[tokio::test]
async fn {test_id}() {{
    let result: Result<i32> = handle! {{
        async try {{ async_io_not_found().await? }}
        catch {{
            // Note: nested try is sync even in async context
            try {{ io_ok()? }} catch {{ 42 }}
        }}
    }};
    assert!(result.is_ok());
}}'''))

    # ==========================================================================
    # Part 27: Nested in loop patterns
    # ==========================================================================

    # try for with nested in body
    test_id = f"test_comp_nested_for_body_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let items = iter_all_ok();
    let result: Result<i32> = handle! {{
        try for item in items {{
            try -> i32 {{ item? }} else {{ 0 }}
        }}
        catch {{ 99 }}
    }};
    assert!(result.is_ok());
}}'''))

    # try while with nested in body
    test_id = f"test_comp_nested_while_body_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let mut att = 0;
    let result: Result<i32> = handle! {{
        try while att < 2 {{
            att += 1;
            try -> i32 {{ Err(io::Error::other("r"))? }} else {{ 1 }}
        }}
        catch {{ 99 }}
    }};
    // Inner try catches, returns 1
    assert_eq!(result.unwrap(), 1);
}}'''))

    # try all with nested in body
    test_id = f"test_comp_nested_all_body_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let items = iter_all_ok();
    let result: Result<Vec<i32>> = handle! {{
        try all item in items {{
            try -> i32 {{ item? }} else {{ 0 }}
        }}
        catch {{ vec![99] }}
    }};
    assert_eq!(result.unwrap(), vec![1, 2, 3]);
}}'''))

    # ==========================================================================
    # Part 28: Multiple nested try patterns in same block
    # ==========================================================================

    test_id = f"test_comp_nested_multi_in_block_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{ io_not_found()? }}
        catch {{
            let a = try {{ io_ok()? }} catch {{ 1 }};
            let b = try {{ io_ok()? }} catch {{ 2 }};
            a + b
        }}
    }};
    assert_eq!(result.unwrap(), 84);  // 42 + 42
}}'''))

    # ==========================================================================
    # Part 29: Nested with context modifiers
    # ==========================================================================

    test_id = f"test_comp_nested_with_context_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{ io_not_found()? }}
        with "outer context"
        catch {{
            // Nested try with its own context
            scope "inner", try {{ io_ok()? }} catch {{ 42 }}
        }}
    }};
    assert!(result.is_ok());
}}'''))

    test_id = f"test_comp_nested_with_scope_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        scope "outer",
        try {{ io_not_found()? }}
        catch {{
            scope "inner", try {{ io_ok()? }} catch {{ 42 }}
        }}
    }};
    assert!(result.is_ok());
}}'''))

    test_id = f"test_comp_nested_with_finally_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let mut finalized = false;
    let result: Result<i32> = handle! {{
        try {{ io_not_found()? }}
        finally {{ finalized = true; }}
        catch {{
            let mut inner_final = false;
            let v = try {{ io_ok()? }} finally {{ inner_final = true; }} catch {{ 42 }};
            assert!(inner_final);
            v
        }}
    }};
    assert!(result.is_ok());
    assert!(finalized);
}}'''))

    # ==========================================================================
    # Part 17: Nested scopes with kv data
    # Tests inline scope syntax with { key: value } attachments
    # ==========================================================================

    test_id = f"test_comp_nested_scope_kv_int_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        scope "outer", {{ count: 42 }},
        try {{
            scope "inner", {{ value: 1 }},
            try {{ io_not_found()? }}
            catch {{ 1 }}
        }}
        catch {{ 99 }}
    }};
    assert_eq!(result.unwrap(), 1);
}}'''))

    test_id = f"test_comp_nested_scope_kv_bool_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        scope "outer", {{ enabled: true }},
        try {{
            scope "inner", {{ active: false }},
            try {{ io_not_found()? }}
            catch {{ 1 }}
        }}
        catch {{ 99 }}
    }};
    assert_eq!(result.unwrap(), 1);
}}'''))

    test_id = f"test_comp_nested_scope_kv_str_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        scope "outer", {{ name: "test" }},
        try {{
            scope "inner", {{ msg: "hello" }},
            try {{ io_not_found()? }}
            catch {{ 1 }}
        }}
        catch {{ 99 }}
    }};
    assert_eq!(result.unwrap(), 1);
}}'''))

    test_id = f"test_comp_nested_scope_kv_multi_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        scope "request", {{ method: "GET", status: 200 }},
        try {{
            scope "auth", {{ user_id: 42, valid: true }},
            try {{ io_not_found()? }}
            catch {{ 1 }}
        }}
        catch {{ 99 }}
    }};
    assert_eq!(result.unwrap(), 1);
}}'''))

    test_id = f"test_comp_nested_scope_triple_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        scope "level1", {{ depth: 1 }},
        try {{
            scope "level2", {{ depth: 2 }},
            try {{
                scope "level3", {{ depth: 3 }},
                try {{ io_not_found()? }}
                catch {{ 1 }}
            }}
            catch {{ 2 }}
        }}
        catch {{ 3 }}
    }};
    assert_eq!(result.unwrap(), 1);
}}'''))

    test_id = f"test_comp_nested_scope_propagate_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    // Error propagates through all scopes to outermost catch
    let result: Result<i32> = handle! {{
        scope "outer", {{ layer: "outer" }},
        try {{
            scope "inner", {{ layer: "inner" }},
            try {{ io_not_found()? }}
            // No catch - propagates
        }}
        catch {{ 42 }}
    }};
    assert_eq!(result.unwrap(), 42);
}}'''))

    test_id = f"test_comp_nested_scope_mixed_ctx_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        scope "outer",
        try {{
            scope "inner", {{ has_data: true }},
            try {{ io_not_found()? }}
            catch {{ 1 }}
        }}
        with "outer context"
        catch {{ 99 }}
    }};
    assert_eq!(result.unwrap(), 1);
}}'''))

    test_id = f"test_comp_nested_scope_in_catch_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    let result: Result<i32> = handle! {{
        try {{ io_not_found()? }}
        catch {{
            scope "recovery", {{ attempt: 1 }},
            try {{ io_ok()? }}
            catch {{ 0 }}
        }}
    }};
    assert!(result.is_ok());
}}'''))

    test_id = f"test_comp_nested_scope_no_kv_with_kv_{counter}"
    counter += 1
    tests.append((test_id, f'''#[test]
fn {test_id}() {{
    // Mix of scope with and without kv data
    let result: Result<i32> = handle! {{
        scope "outer",
        try {{
            scope "middle", {{ id: 123 }},
            try {{
                scope "inner",
                try {{ io_not_found()? }}
                catch {{ 1 }}
            }}
            catch {{ 2 }}
        }}
        catch {{ 3 }}
    }};
    assert_eq!(result.unwrap(), 1);
}}'''))

    return iter(tests)


# =============================================================================
# File Writer
# =============================================================================

HEADER = '''//! Auto-generated test file - DO NOT EDIT
//! Generated by scripts/generate_full_matrix.py

#![allow(unused_variables, unused_assignments, dead_code, unused_mut, unused_imports)]

mod matrix_common;
use matrix_common::*;
use handle_this::{handle, Handled, Result};
use std::io::{self, ErrorKind};
'''

MATRIX_COMMON_CONTENT = '''//! Common test utilities for matrix tests - AUTO-GENERATED
//! Generated by scripts/generate_full_matrix.py

use std::io::{self, ErrorKind};
use handle_this::{Handled, Result};

/// Returns Ok(42)
pub fn io_ok() -> Result<i32> {
    Ok(42)
}

/// Returns Err with io::Error NotFound
pub fn io_not_found() -> Result<i32> {
    Err(Handled::from(io::Error::new(ErrorKind::NotFound, "not found")))
}

/// Returns error chain: StringError at root, io::Error NotFound in chain
/// Used for testing `catch any io::Error` which searches the chain
pub fn chained_io_error() -> Handled {
    let inner = Handled::from(io::Error::new(ErrorKind::NotFound, "inner not found"));
    let outer = Handled::msg("outer error");
    outer.chain_after(inner)
}

/// Returns error chain: io::Error PermissionDenied at root, NotFound in chain
/// Used for testing `catch all io::Error` which collects all io::Errors
pub fn multi_io_chain() -> Handled {
    let inner = Handled::from(io::Error::new(ErrorKind::NotFound, "inner not found"));
    let outer = Handled::from(io::Error::new(ErrorKind::PermissionDenied, "permission denied"));
    outer.chain_after(inner)
}

/// Iterator that yields all Err values (for try for tests where handlers run)
pub fn iter_all_fail() -> impl Iterator<Item = Result<i32>> {
    vec![
        Err(Handled::from(io::Error::new(ErrorKind::Other, "fail 1"))),
        Err(Handled::from(io::Error::new(ErrorKind::Other, "fail 2"))),
        Err(Handled::from(io::Error::new(ErrorKind::Other, "fail 3"))),
    ].into_iter()
}

/// Iterator that yields all Ok values (for try all tests)
pub fn iter_all_ok() -> impl Iterator<Item = Result<i32>> {
    vec![Ok(1), Ok(2), Ok(3)].into_iter()
}

/// Iterator where second item succeeds (for try for early exit)
pub fn iter_second_ok() -> impl Iterator<Item = Result<i32>> {
    vec![
        Err(Handled::from(io::Error::new(ErrorKind::Other, "fail"))),
        Ok(42),
    ].into_iter()
}

/// Async version of io_ok
pub async fn async_io_ok() -> Result<i32> {
    Ok(42)
}

/// Async version of io_not_found
pub async fn async_io_not_found() -> Result<i32> {
    Err(Handled::from(io::Error::new(ErrorKind::NotFound, "not found")))
}

/// Helper for then chains - wraps value in Ok
pub fn ok_val<T>(v: T) -> Result<T> {
    Ok(v)
}
'''


def write_matrix_common():
    """Write the matrix_common module."""
    common_dir = os.path.join(TESTS_DIR, "matrix_common")
    os.makedirs(common_dir, exist_ok=True)
    filepath = os.path.join(common_dir, "mod.rs")
    with open(filepath, "w") as f:
        f.write(MATRIX_COMMON_CONTENT)


def write_tests_to_files(tests: List[Tuple[str, str]], prefix: str) -> int:
    """Write tests to files, splitting by TESTS_PER_FILE."""
    os.makedirs(TESTS_DIR, exist_ok=True)

    file_num = 0
    test_count = 0
    current_tests = []

    for test_id, test_code in tests:
        current_tests.append(test_code)
        test_count += 1

        if len(current_tests) >= TESTS_PER_FILE:
            filename = f"{prefix}_{file_num:04d}.rs"
            filepath = os.path.join(TESTS_DIR, filename)
            with open(filepath, "w") as f:
                f.write(HEADER)
                f.write("\n")
                f.write("\n".join(current_tests))
                f.write("\n")
            file_num += 1
            current_tests = []

    # Write remaining
    if current_tests:
        filename = f"{prefix}_{file_num:04d}.rs"
        filepath = os.path.join(TESTS_DIR, filename)
        with open(filepath, "w") as f:
            f.write(HEADER)
            f.write("\n")
            f.write("\n".join(current_tests))
            f.write("\n")
        file_num += 1

    return test_count


def make_test_id(tp_name: str, handlers: List[Tuple[str, str, str]],
                 ctx_name: str, pre_name: str, then_name: str, counter: int) -> str:
    """Generate unique test ID."""
    h_parts = "_".join(f"{h[0][:2]}{h[1][:2]}{h[2][:2]}" for h in handlers) if handlers else "none"
    # Include then_name only if not no_then (to keep test names shorter)
    if then_name != "no_then":
        return f"test_{tp_name}_{h_parts}_{ctx_name}_{pre_name}_{then_name}_{counter}"
    return f"test_{tp_name}_{h_parts}_{ctx_name}_{pre_name}_{counter}"


# =============================================================================
# Filtering Support
# =============================================================================

@dataclass
class Filters:
    """Filters for selective test generation."""
    try_patterns: Optional[Set[str]] = None
    handlers: Optional[Set[str]] = None
    bindings: Optional[Set[str]] = None
    guards: Optional[Set[str]] = None
    contexts: Optional[Set[str]] = None
    preconditions: Optional[Set[str]] = None
    num_handlers: Optional[Set[int]] = None
    categories: Optional[Set[str]] = None
    then_steps: Optional[Set[str]] = None

    def matches_try_pattern(self, name: str) -> bool:
        return self.try_patterns is None or name in self.try_patterns

    def matches_handler(self, kw: str) -> bool:
        return self.handlers is None or kw in self.handlers

    def matches_binding(self, name: str) -> bool:
        return self.bindings is None or name in self.bindings

    def matches_guard(self, name: str) -> bool:
        return self.guards is None or name in self.guards

    def matches_context(self, name: str) -> bool:
        return self.contexts is None or name in self.contexts

    def matches_precondition(self, name: str) -> bool:
        return self.preconditions is None or name in self.preconditions

    def matches_num_handlers(self, n: int) -> bool:
        return self.num_handlers is None or n in self.num_handlers

    def matches_category(self, cat: str) -> bool:
        return self.categories is None or cat in self.categories

    def matches_then_steps(self, name: str) -> bool:
        return self.then_steps is None or name in self.then_steps

    def matches_handler_combo(self, handlers: List[Tuple[str, str, str]]) -> bool:
        """Check if all handlers in the combo match filters."""
        for kw, bind, guard in handlers:
            if not self.matches_handler(kw):
                return False
            if not self.matches_binding(bind):
                return False
            if not self.matches_guard(guard):
                return False
        return True


def generate_filtered_single_handler(filters: Filters) -> Iterator[Tuple[tuple, List[Tuple[str, str, str]], tuple, tuple, tuple]]:
    """Generate single-handler permutations with filters."""
    for tp in TRY_PATTERNS:
        if not filters.matches_try_pattern(tp[0]):
            continue
        for kw in HANDLER_KEYWORDS:
            if not filters.matches_handler(kw):
                continue
            for b in BINDINGS:
                if not filters.matches_binding(b[0]):
                    continue
                for g in GUARDS:
                    if not filters.matches_guard(g[0]):
                        continue
                    handler = (kw, b[0], g[0])
                    if not is_valid_handler(kw, b[0], g[0], tp[0]):
                        continue
                    for ctx in CONTEXTS:
                        if not filters.matches_context(ctx[0]):
                            continue
                        for pre in PRECONDITIONS:
                            if not filters.matches_precondition(pre[0]):
                                continue
                            for then in THEN_STEPS:
                                if not filters.matches_then_steps(then[0]):
                                    continue
                                if is_valid_combination(tp[0], [handler], ctx[0], pre[0], then[0]):
                                    yield (tp, [handler], ctx, pre, then)


def generate_filtered_two_handler(filters: Filters) -> Iterator[Tuple[tuple, List[Tuple[str, str, str]], tuple, tuple, tuple]]:
    """Generate two-handler permutations with filters."""
    for tp in TRY_PATTERNS:
        if not filters.matches_try_pattern(tp[0]):
            continue
        if tp[0] == "all_iter":
            continue

        valid_handlers = []
        for kw in HANDLER_KEYWORDS:
            if not filters.matches_handler(kw):
                continue
            for b in BINDINGS:
                if not filters.matches_binding(b[0]):
                    continue
                for g in GUARDS:
                    if not filters.matches_guard(g[0]):
                        continue
                    if is_valid_handler(kw, b[0], g[0], tp[0]):
                        valid_handlers.append((kw, b[0], g[0]))

        for h1 in valid_handlers:
            for h2 in valid_handlers:
                handlers = [h1, h2]
                for ctx in CONTEXTS[:5]:  # Subset of contexts
                    if not filters.matches_context(ctx[0]):
                        continue
                    for pre in PRECONDITIONS[:2]:  # Subset of preconditions
                        if not filters.matches_precondition(pre[0]):
                            continue
                        for then in THEN_STEPS[:2]:  # Subset: no_then, then_1
                            if not filters.matches_then_steps(then[0]):
                                continue
                            if is_valid_combination(tp[0], handlers, ctx[0], pre[0], then[0]):
                                yield (tp, handlers, ctx, pre, then)


def generate_filtered_three_handler(filters: Filters) -> Iterator[Tuple[tuple, List[Tuple[str, str, str]], tuple, tuple, tuple]]:
    """Generate three-handler permutations with filters."""
    for tp in TRY_PATTERNS:
        if not filters.matches_try_pattern(tp[0]):
            continue
        if tp[0] == "all_iter":
            continue
        if tp[0] == "async":
            continue  # Skip async for 3-handler

        valid_handlers = []
        for kw in HANDLER_KEYWORDS:
            if not filters.matches_handler(kw):
                continue
            for b in BINDINGS:
                if not filters.matches_binding(b[0]):
                    continue
                for g in GUARDS:
                    if not filters.matches_guard(g[0]):
                        continue
                    if is_valid_handler(kw, b[0], g[0], tp[0]):
                        valid_handlers.append((kw, b[0], g[0]))

        # Limit 2nd and 3rd handlers to simpler bindings/guards
        simple_bindings = ["none", "named", "typed"]
        simple_guards = ["none", "when_true"]
        simple_handlers = [(kw, b, g) for kw, b, g in valid_handlers
                          if b in simple_bindings and g in simple_guards]

        # For 3-handler, only use no_then to keep count reasonable
        then = THEN_STEPS[0]  # no_then
        if not filters.matches_then_steps(then[0]):
            continue

        for h1 in valid_handlers:
            for h2 in simple_handlers:
                for h3 in simple_handlers:
                    handlers = [h1, h2, h3]
                    for ctx in CONTEXTS[:2]:  # Minimal contexts for 3-handler
                        if not filters.matches_context(ctx[0]):
                            continue
                        pre = PRECONDITIONS[0]  # none only
                        if not filters.matches_precondition(pre[0]):
                            continue
                        if is_valid_combination(tp[0], handlers, ctx[0], pre[0], then[0]):
                            yield (tp, handlers, ctx, pre, then)


def generate_filtered_no_handler(filters: Filters) -> Iterator[Tuple[tuple, List[Tuple[str, str, str]], tuple, tuple, tuple]]:
    """Generate no-handler permutations with filters.

    Note: Then chains require a terminal handler, so no_handler always uses no_then.
    """
    then = THEN_STEPS[0]  # no_then - then chains need handlers
    if not filters.matches_then_steps(then[0]):
        return
    for tp in TRY_PATTERNS:
        if not filters.matches_try_pattern(tp[0]):
            continue
        if tp[0] == "direct":
            continue
        for ctx in CONTEXTS:
            if not filters.matches_context(ctx[0]):
                continue
            for pre in PRECONDITIONS:
                if not filters.matches_precondition(pre[0]):
                    continue
                if is_valid_combination(tp[0], [], ctx[0], pre[0], then[0]):
                    yield (tp, [], ctx, pre, then)


# =============================================================================
# CLI Argument Parsing
# =============================================================================

def parse_list(value: str) -> Set[str]:
    """Parse comma-separated list into set."""
    return set(v.strip() for v in value.split(',') if v.strip())


def parse_int_list(value: str) -> Set[int]:
    """Parse comma-separated int list into set."""
    return set(int(v.strip()) for v in value.split(',') if v.strip())


def list_options():
    """Print all available filter options."""
    print("Available filter values:\n")

    print("Try patterns (-t, --try-pattern):")
    for tp in TRY_PATTERNS:
        print(f"  {tp[0]}")

    print("\nHandler keywords (-k, --handler):")
    for kw in HANDLER_KEYWORDS:
        print(f"  {kw}")

    print("\nBindings (-b, --binding):")
    for b in BINDINGS:
        print(f"  {b[0]}")

    print("\nGuards (-g, --guard):")
    for g in GUARDS:
        print(f"  {g[0]}")

    print("\nContexts (-c, --context):")
    for ctx in CONTEXTS:
        print(f"  {ctx[0]}")

    print("\nPreconditions (-p, --precondition):")
    for pre in PRECONDITIONS:
        print(f"  {pre[0]}")

    print("\nNumber of handlers (-n, --num-handlers):")
    print("  0, 1, 2")

    print("\nCategories (--category):")
    print("  single        - Single handler tests")
    print("  two           - Two handler tests")
    print("  three         - Three handler tests")
    print("  no_handler    - No handler tests")
    print("  else_suffix   - Else suffix tests")
    print("  nested        - Nested body tests")
    print("  control_flow  - Control flow tests")
    print("  deeply_nested - Deeply nested tests")
    print("  comp_nested   - Comprehensive nested permutations (multi-position, multi-depth)")


def create_arg_parser() -> argparse.ArgumentParser:
    """Create argument parser."""
    parser = argparse.ArgumentParser(
        description="Generate test matrix for handle-this macro",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  # Generate tests for basic try pattern with catch handler
  python3 %(prog)s -t basic -k catch

  # Generate tests for multiple patterns
  python3 %(prog)s -t basic,for -k catch,throw -b named,typed

  # Generate only single-handler tests for basic pattern
  python3 %(prog)s --category single -t basic

  # Generate all tests (WARNING: 88k+ tests)
  python3 %(prog)s --all

  # List all available options
  python3 %(prog)s --list
"""
    )

    parser.add_argument('-t', '--try-pattern',
                        help='Try patterns (comma-separated): basic, direct, for, any_iter, all_iter, while, async')
    parser.add_argument('-k', '--handler',
                        help='Handler keywords (comma-separated): catch, throw, inspect, else')
    parser.add_argument('-b', '--binding',
                        help='Bindings (comma-separated): none, named, underscore, typed, typed_short, any, any_short, all')
    parser.add_argument('-g', '--guard',
                        help='Guards (comma-separated): none, when_true, when_kind, match_kind')
    parser.add_argument('-c', '--context',
                        help='Contexts (comma-separated): none, with_msg, with_data, etc.')
    parser.add_argument('-p', '--precondition',
                        help='Preconditions (comma-separated): none, require_pass, require_fail')
    parser.add_argument('-n', '--num-handlers',
                        help='Number of handlers (comma-separated): 0, 1, 2')
    parser.add_argument('--category',
                        help='Test categories (comma-separated): single, two, no_handler, else_suffix, nested, control_flow, deeply_nested, comp_nested')
    parser.add_argument('--then-steps',
                        help='Then chain steps (comma-separated): no_then, then_1, then_2, then_ctx')
    parser.add_argument('--all', action='store_true',
                        help='Generate all tests (use with caution - 88k+ tests)')
    parser.add_argument('--list', action='store_true',
                        help='List all available filter values')
    parser.add_argument('--no-clean', action='store_true',
                        help='Do not clean existing test files before generating')

    return parser


# =============================================================================
# Main
# =============================================================================

def main():
    parser = create_arg_parser()
    args = parser.parse_args()

    if args.list:
        list_options()
        return

    # Check if any filters specified
    has_filters = any([
        args.try_pattern, args.handler, args.binding, args.guard,
        args.context, args.precondition, args.num_handlers, args.category,
        args.then_steps
    ])

    if not has_filters and not args.all:
        print("No filters specified. Use --all to generate all tests, or specify filters.")
        print("Use --list to see available options, or --help for usage.")
        return

    # Build filters
    filters = Filters(
        try_patterns=parse_list(args.try_pattern) if args.try_pattern else None,
        handlers=parse_list(args.handler) if args.handler else None,
        bindings=parse_list(args.binding) if args.binding else None,
        guards=parse_list(args.guard) if args.guard else None,
        contexts=parse_list(args.context) if args.context else None,
        preconditions=parse_list(args.precondition) if args.precondition else None,
        num_handlers=parse_int_list(args.num_handlers) if args.num_handlers else None,
        categories=parse_list(args.category) if args.category else None,
        then_steps=parse_list(args.then_steps) if args.then_steps else None,
    )

    print("Generating test matrix...")
    print(f"Output directory: {TESTS_DIR}")
    if has_filters:
        print("Filters applied:")
        if filters.try_patterns:
            print(f"  try_patterns: {filters.try_patterns}")
        if filters.handlers:
            print(f"  handlers: {filters.handlers}")
        if filters.bindings:
            print(f"  bindings: {filters.bindings}")
        if filters.guards:
            print(f"  guards: {filters.guards}")
        if filters.contexts:
            print(f"  contexts: {filters.contexts}")
        if filters.preconditions:
            print(f"  preconditions: {filters.preconditions}")
        if filters.num_handlers:
            print(f"  num_handlers: {filters.num_handlers}")
        if filters.categories:
            print(f"  categories: {filters.categories}")
        if filters.then_steps:
            print(f"  then_steps: {filters.then_steps}")

    # Clean existing matrix files unless --no-clean
    # Only removes matrix_*.rs files - preserves other test files (ui.rs, etc.)
    if not args.no_clean and os.path.exists(TESTS_DIR):
        for f in os.listdir(TESTS_DIR):
            if f.startswith('matrix_') and f.endswith('.rs'):
                os.remove(os.path.join(TESTS_DIR, f))

    # Always generate matrix_common module
    write_matrix_common()

    all_tests = []
    counter = 0

    # No-handler permutations
    if filters.matches_category("no_handler") and filters.matches_num_handlers(0):
        print("\nGenerating no-handler permutations...")
        no_handler_count = 0
        for tp, handlers, ctx, pre, then in generate_filtered_no_handler(filters):
            test_id = make_test_id(tp[0], handlers, ctx[0], pre[0], then[0], counter)
            test_code, _, _ = generate_test(test_id, tp, handlers, ctx, pre, then)
            all_tests.append((test_id, test_code))
            counter += 1
            no_handler_count += 1
        print(f"  No-handler: {no_handler_count}")

    # Single-handler permutations
    if filters.matches_category("single") and filters.matches_num_handlers(1):
        print("\nGenerating single-handler permutations...")
        single_count = 0
        for tp, handlers, ctx, pre, then in generate_filtered_single_handler(filters):
            test_id = make_test_id(tp[0], handlers, ctx[0], pre[0], then[0], counter)
            test_code, _, _ = generate_test(test_id, tp, handlers, ctx, pre, then)
            all_tests.append((test_id, test_code))
            counter += 1
            single_count += 1
        print(f"  Single-handler: {single_count}")

    # Two-handler permutations
    if filters.matches_category("two") and filters.matches_num_handlers(2):
        print("\nGenerating two-handler permutations...")
        two_count = 0
        for tp, handlers, ctx, pre, then in generate_filtered_two_handler(filters):
            test_id = make_test_id(tp[0], handlers, ctx[0], pre[0], then[0], counter)
            test_code, _, _ = generate_test(test_id, tp, handlers, ctx, pre, then)
            all_tests.append((test_id, test_code))
            counter += 1
            two_count += 1
            if two_count % 10000 == 0:
                print(f"    Progress: {two_count}...")
        print(f"  Two-handler: {two_count}")

    # Three-handler permutations
    if filters.matches_category("three") and filters.matches_num_handlers(3):
        print("\nGenerating three-handler permutations...")
        three_count = 0
        for tp, handlers, ctx, pre, then in generate_filtered_three_handler(filters):
            test_id = make_test_id(tp[0], handlers, ctx[0], pre[0], then[0], counter)
            test_code, _, _ = generate_test(test_id, tp, handlers, ctx, pre, then)
            all_tests.append((test_id, test_code))
            counter += 1
            three_count += 1
            if three_count % 10000 == 0:
                print(f"    Progress: {three_count}...")
        print(f"  Three-handler: {three_count}")

    # Else suffix permutations
    if filters.matches_category("else_suffix"):
        print("\nGenerating else suffix permutations...")
        else_count = 0
        for test_id, test_code in generate_else_suffix_permutations():
            # Apply try_pattern filter to else_suffix tests
            if filters.try_patterns:
                # Extract pattern from test_id (e.g., test_else_suffix_catch_basic_...)
                parts = test_id.split('_')
                if len(parts) > 4:
                    tp_name = parts[4]
                    if tp_name not in filters.try_patterns:
                        continue
            all_tests.append((test_id, test_code))
            else_count += 1
        print(f"  Else suffix: {else_count}")

    # Nested body permutations
    if filters.matches_category("nested"):
        print("\nGenerating nested body permutations...")
        nested_count = 0
        for test_id, test_code in generate_nested_body_permutations():
            # Apply try_pattern filter
            if filters.try_patterns:
                parts = test_id.split('_')
                if len(parts) > 2:
                    tp_name = parts[2]
                    if tp_name not in filters.try_patterns:
                        continue
            all_tests.append((test_id, test_code))
            nested_count += 1
        print(f"  Nested body: {nested_count}")

    # Control flow permutations
    if filters.matches_category("control_flow"):
        print("\nGenerating control flow permutations...")
        cf_count = 0
        for test_id, test_code in generate_control_flow_permutations():
            all_tests.append((test_id, test_code))
            cf_count += 1
        print(f"  Control flow: {cf_count}")

    # Deeply nested permutations
    if filters.matches_category("deeply_nested"):
        print("\nGenerating deeply nested permutations...")
        deep_count = 0
        for test_id, test_code in generate_deeply_nested_permutations():
            all_tests.append((test_id, test_code))
            deep_count += 1
        print(f"  Deeply nested: {deep_count}")

    # Comprehensive nested permutations
    if filters.matches_category("comp_nested"):
        print("\nGenerating comprehensive nested permutations...")
        comp_count = 0
        for test_id, test_code in generate_comprehensive_nested_permutations():
            all_tests.append((test_id, test_code))
            comp_count += 1
        print(f"  Comprehensive nested: {comp_count}")

    if not all_tests:
        print("\nNo tests generated. Check your filters.")
        return

    # Write to files
    print(f"\nTotal tests: {len(all_tests)}")
    print("Writing to files...")

    written = write_tests_to_files(all_tests, "matrix")

    num_files = (len(all_tests) + TESTS_PER_FILE - 1) // TESTS_PER_FILE
    print(f"\nGenerated {written} tests across {num_files} files")
    print(f"Directory: {TESTS_DIR}")
    print("\nTo run: cargo test --test 'matrix_*'")


if __name__ == "__main__":
    main()