vb6parse 1.2.1

vb6parse is a library for parsing and analyzing VB6 code, from projects, to controls, to modules, and forms.
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
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
//! Concrete Syntax Tree (CST) implementation for VB6.
//!
//! This module provides a CST that wraps the rowan library internally while
//! providing a public API that doesn't expose rowan types directly.
//!
//! # Overview
//!
//! The CST (Concrete Syntax Tree) represents the complete structure of VB6 source code,
//! including all tokens such as whitespace, comments, and keywords. Unlike an AST
//! (Abstract Syntax Tree), a CST preserves all the original formatting and structure
//! of the source code, making it ideal for tools like formatters, linters, and
//! source-to-source transformations.
//!
//! # Architecture
//!
//! This implementation uses the [`rowan`](https://docs.rs/rowan/) library internally
//! for efficient CST representation, but all rowan types are kept private to the module.
//! The public API only exposes:
//!
//! - [`ConcreteSyntaxTree`] - The main CST struct
//! - [`SyntaxKind`] - An enum representing all possible node and token types
//! - [`parse`] - A function to parse a [`TokenStream`] into a CST
//! - [`CstNode`] - A structure for navigating and querying the CST
//!
//! For parser method naming and helper behavior conventions, see
//! [`Parser` conventions](Parser#parser-conventions).
//!
//! # Example Usage
//!
//! ```rust
//! use vb6parse::language::Token;
//! use vb6parse::parsers::cst::parse;
//! use vb6parse::lexer::TokenStream;
//!
//! // Create a token stream
//! let tokens = vec![
//!     ("Sub", Token::SubKeyword),
//!     (" ", Token::Whitespace),
//!     ("Main", Token::Identifier),
//!     ("(", Token::LeftParenthesis),
//!     (")", Token::RightParenthesis),
//!     ("\n", Token::Newline),
//! ];
//!
//! let token_stream = TokenStream::new("test.bas".to_string(), tokens);
//!
//! // Parse into a CST
//! let cst = parse(token_stream);
//!
//! // Use the CST
//! println!("Text: {}", cst.text());
//! println!("Children: {}", cst.child_count());
//! ```
//!
//! # Navigating the CST
//!
//! The CST provides rich navigation capabilities for traversing and querying the tree.
//! Both [`ConcreteSyntaxTree`] and [`CstNode`] provide parallel navigation APIs:
//!
//! ## Root-Level Navigation
//!
//! ```rust
//! use vb6parse::ConcreteSyntaxTree;
//! use vb6parse::parsers::SyntaxKind;
//!
//! let source = "Sub Test()\nEnd Sub\n";
//! let (cst_opt, failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
//!
//! if !failures.is_empty() {
//!   eprintln!("Errors during parsing:");
//!   for failure in failures {
//!       failure.print();
//!   }
//!   panic!("Failed to parse source code.");
//! }
//!
//! let cst = cst_opt.expect("Failed to parse source");
//!
//!
//! // Access root-level children
//! println!("Child count: {}", cst.child_count());
//! let first = cst.first_child();
//!
//! // Search root-level children
//! let subs: Vec<_> = cst.children_by_kind(SyntaxKind::SubStatement).collect();
//! ```
//!
//! ## Node-Level Navigation
//!
//! Once you have a [`CstNode`], you can navigate its structure:
//!
//! ```rust
//! # use vb6parse::ConcreteSyntaxTree;
//! # use vb6parse::parsers::SyntaxKind;
//! # let source = "Sub Test()\nDim x\nEnd Sub\n";
//! # let (cst_opt, failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
//! # let cst = cst_opt.expect("Failed to parse source");
//!
//! let root = cst.to_serializable().root;
//!
//! // Direct children
//! println!("Child count: {}", root.child_count());
//! let first = root.first_child();
//!
//! // Filter by kind
//! let statements: Vec<_> = root.children_by_kind(SyntaxKind::DimStatement).collect();
//!
//! // Recursive search
//! let dim_stmt = root.find(SyntaxKind::DimStatement);
//! let all_identifiers = root.find_all(SyntaxKind::Identifier);
//!
//! // Filter tokens
//! let non_tokens: Vec<_> = root.non_token_children().collect();
//! let significant: Vec<_> = root.significant_children().collect();
//!
//! // Custom predicates
//! let keywords = root.find_all_if(|n| {
//!     matches!(n.kind(), SyntaxKind::SubKeyword | SyntaxKind::DimKeyword)
//! });
//!
//! // Iterate all nodes
//! for node in root.descendants() {
//!     if node.is_significant() {
//!         println!("{:?}: {}", node.kind(), node.text());
//!     }
//! }
//! ```
//!
//! ## Navigation Methods
//!
//! Available on both [`ConcreteSyntaxTree`] and [`CstNode`]:
//!
//! **Basic Access:**
//! - `child_count()` - Number of direct children
//! - `first_child()`, `last_child()`, `child_at(index)` - Access specific children
//!
//! **By Kind:**
//! - `children_by_kind(kind)` - Iterator over children of a specific kind
//! - `first_child_by_kind(kind)` - First child of a specific kind
//! - `contains_kind(kind)` - Check if a kind exists in children
//!
//! **Recursive Search:**
//! - `find(kind)` - Find first descendant of a specific kind
//! - `find_all(kind)` - Find all descendants of a specific kind
//!
//! **Token Filtering:**
//! - `non_token_children()` - Structural nodes only
//! - `token_children()` - Tokens only
//! - `first_non_whitespace_child()` - Skip leading whitespace
//! - `significant_children()` - Exclude whitespace and newlines
//!
//! **Predicate-Based:**
//! - `find_if(predicate)` - Find first node matching a custom condition
//! - `find_all_if(predicate)` - Find all nodes matching a custom condition
//!
//! **Tree Traversal:**
//! - `descendants()` - Depth-first iterator over all nodes
//! - `depth_first_iter()` - Alias for `descendants()`
//!
//! **Convenience Checkers** (`CstNode` only):
//! - `is_whitespace()` - Check if node is whitespace.
//! - `is_newline()` - Check if node is newline.
//! - `is_comment()` - Check if node is an end-of-Line or REM comment.
//! - `is_trivia()` - Whitespace, newline, end-of-Line comment, or REM comment.
//! - `is_significant()` - Not trivia.
//!
//! For more details, see the documentation for [`ConcreteSyntaxTree`] and [`CstNode`].
//!
//! # Design Principles
//!
//! 1. **No rowan types exposed**: All public APIs use custom types that don't expose rowan.
//! 2. **Complete representation**: The CST includes all tokens, including whitespace and comments.
//! 3. **Efficient**: Uses rowan's red-green tree architecture for memory efficiency.
//! 4. **Type-safe**: All syntax kinds are represented as a Rust enum for compile-time safety.

use std::collections::HashMap;
use std::num::NonZeroUsize;

use crate::ParseResult;
use crate::errors::{ErrorDetails, ErrorKind, FormError, ModuleError, Severity, Span};
use crate::files::common::{
    Creatable, Exposed, FileAttributes, FileFormatVersion, NameSpace, ObjectReference,
    PreDeclaredID, Properties,
};
use crate::io::{SourceFile, SourceStream};
use crate::language::{
    CheckBoxProperties, ComboBoxProperties, CommandButtonProperties, Control, ControlKind,
    DataProperties, DirListBoxProperties, DriveListBoxProperties, FileListBoxProperties, Font,
    Form, FormProperties, FormRoot, FrameProperties, LabelProperties, ListBoxProperties, MDIForm,
    MDIFormProperties, MenuControl, MenuProperties, OptionButtonProperties, PictureBoxProperties,
    PropertyGroup, TextBoxProperties, Token,
};
use crate::lexer::{TokenStream, tokenize};
use crate::parsers::SyntaxKind;

use either::Either;
use rowan::{GreenNode, GreenNodeBuilder, Language};
use serde::Serialize;

// Submodules for organized CST parsing
mod assignment;
mod attribute_statements;
mod declarations;
mod deftype_statements;
mod enum_statements;
mod for_statements;
mod function_statements;
mod helpers;
mod if_statements;
mod label_statements;
mod loop_statements;
mod navigation;
mod option_statements;
mod parameters;
mod properties;
mod property_statements;
mod select_statements;
mod sub_statements;
mod type_statements;
pub mod visitor;

// Re-export navigation types
pub use navigation::CstNode;
pub use visitor::{Visitor, VisitorMut, walk_node, walk_node_mut};

/// Maximum depth for nested property groups to prevent stack overflow.
const MAX_PROPERTY_GROUP_DEPTH: usize = 100;

/// Maximum depth for nested controls to prevent stack overflow.
const MAX_CONTROL_DEPTH: usize = 1000;

/// A serializable representation of the CST for snapshot testing.
///
/// This struct wraps the tree structure in a way that can be serialized
/// with serde, making it suitable for use with snapshot testing tools like insta.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, Hash)]
pub struct SerializableTree {
    /// The root node of the tree
    pub root: CstNode,
}

/// Helper function to serialize `ConcreteSyntaxTree` as `SerializableTree`
pub(crate) fn serialize_cst<S>(cst: &ConcreteSyntaxTree, serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    cst.to_serializable().serialize(serializer)
}

/// The language type for VB6 syntax trees.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum VB6Language {}

impl Language for VB6Language {
    type Kind = SyntaxKind;

    fn kind_from_raw(raw: rowan::SyntaxKind) -> Self::Kind {
        SyntaxKind::from_raw(raw)
    }

    fn kind_to_raw(kind: Self::Kind) -> rowan::SyntaxKind {
        kind.to_raw()
    }
}

/// Extract typed property groups from a Vec<PropertyGroup>
fn extract_property_groups(groups: &[PropertyGroup]) -> ExtractedGroups {
    let mut font = None;

    for group in groups
        .iter()
        .filter(|g| g.name.eq_ignore_ascii_case("Font"))
    {
        if let Ok(f) = Font::try_from(group) {
            font = Some(f);
        }

        // Future: handle other property group types (Images, etc.)
    }

    ExtractedGroups { font }
}

/// Struct to hold extracted property groups for a control
struct ExtractedGroups {
    font: Option<Font>,
    // Future: add other property group types
}

/// A Concrete Syntax Tree for VB6 code.
///
/// This structure wraps the rowan library's `GreenNode` internally but provides
/// a public API that doesn't expose rowan types.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ConcreteSyntaxTree {
    /// The root green node (internal implementation detail)
    root: GreenNode,
}

impl ConcreteSyntaxTree {
    /// Create a new CST from a `GreenNode` (internal use only)
    fn new(root: GreenNode) -> Self {
        Self { root }
    }

    /// Parse a CST from a `SourceFile`.
    ///
    /// # Arguments
    ///
    /// * `source_file` - The source file to parse.
    ///
    /// # Returns
    ///
    /// A result containing the parsed CST or an error.
    #[must_use]
    pub fn from_source(source_file: &SourceFile) -> ParseResult<'_, Self> {
        Self::from_text(
            source_file.file_name().to_string(),
            source_file.source_stream().contents,
        )
    }

    /// Parse a CST from source code.
    ///
    /// # Arguments
    ///
    /// * `file_name` - The name of the source file.
    /// * `contents` - The contents of the source file.
    ///
    /// # Returns
    ///
    /// A result containing the parsed CST or an error.
    pub fn from_text<S>(file_name: S, contents: &str) -> ParseResult<'_, Self>
    where
        S: Into<String>,
    {
        let mut source_stream = SourceStream::new(file_name.into(), contents);
        let token_stream_result = tokenize(&mut source_stream);
        let (token_stream_opt, mut failures) = token_stream_result.unpack();

        let Some(token_stream) = token_stream_opt else {
            return ParseResult::new(None, failures);
        };

        let mut parser = Parser::new(token_stream);
        parser.set_source_content(contents);
        let (cst, mut parser_failures, recovery_events) = parser.parse_root();
        failures.append(&mut parser_failures);

        ParseResult::new(Some(cst), failures).with_recovery_events(recovery_events)
    }

    /// Get the kind of the root node
    #[must_use]
    pub fn root_kind(&self) -> SyntaxKind {
        SyntaxKind::from_raw(self.root.kind())
    }

    /// Convert the CST to a serializable representation.
    ///
    /// This method creates a `SerializableTree` that can be used with
    /// snapshot testing tools like `insta`. The serializable tree contains
    /// the complete tree structure as a hierarchy of `CstNode` instances.
    ///
    /// # Example
    ///
    /// ```rust
    /// use vb6parse::ConcreteSyntaxTree;
    ///
    /// let source = "Sub Test()\nEnd Sub\n";
    /// let result = ConcreteSyntaxTree::from_text("test.bas", source);
    ///
    /// let (cst_opt, failures) = result.unpack();
    ///
    /// let cst = cst_opt.expect("Failed to parse source");
    ///
    /// if !failures.is_empty() {
    ///     for failure in failures.iter() {
    ///         failure.print();
    ///     }
    ///     panic!("Failed to parse source with {} errors.", failures.len());
    /// };
    ///
    /// let serializable = cst.to_serializable();
    ///
    /// // Can now be used with insta::assert_yaml_snapshot!
    /// ```
    #[must_use]
    pub fn to_serializable(&self) -> SerializableTree {
        SerializableTree {
            root: self.to_root_node(),
        }
    }

    /// Convert the internal rowan tree to a root `CstNode`.
    ///
    /// # Returns
    ///
    /// The root `CstNode` representing the entire CST.
    #[must_use]
    pub fn to_root_node(&self) -> CstNode {
        CstNode::new(SyntaxKind::Root, self.text(), false, self.children())
    }

    /// Returns byte ranges for each `ErrorRecovery` node in the CST.
    #[must_use]
    pub fn error_recovery_ranges(&self) -> Vec<NodeRange> {
        let syntax_node = rowan::SyntaxNode::<VB6Language>::new_root(self.root.clone());

        syntax_node
            .descendants()
            .filter(|node| node.kind() == SyntaxKind::ErrorRecovery)
            .map(|node| {
                let range = node.text_range();
                NodeRange {
                    start: range.start().into(),
                    end: range.end().into(),
                }
            })
            .collect()
    }

    /// Create a new CST with specified node kinds removed from the root level.
    ///
    /// This method filters out direct children of the root node that match any of the
    /// specified kinds. This is useful for removing nodes that have already been parsed
    /// into structured data (like version statements, attributes, etc.) to avoid duplication.
    ///
    /// # Arguments
    ///
    /// * `kinds_to_remove` - A slice of `SyntaxKind` values to filter out
    ///
    /// # Returns
    ///
    /// A new `ConcreteSyntaxTree` with the specified kinds removed from the root level.
    ///
    /// # Example
    ///
    /// ```rust
    /// use vb6parse::ConcreteSyntaxTree;
    /// use vb6parse::parsers::SyntaxKind;
    ///
    /// let source = "VERSION 5.00\nSub Test()\nEnd Sub\n";
    /// let result = ConcreteSyntaxTree::from_text("test.bas", source);
    /// let (cst_opt, failures) = result.unpack();
    /// let cst = cst_opt.expect("Failed to parse source");
    ///
    /// // Remove version statement since it's already parsed
    /// let filtered = cst.without_kinds(&[SyntaxKind::VersionStatement]);
    ///
    /// assert!(!filtered.contains_kind(SyntaxKind::VersionStatement));
    /// ```
    #[must_use]
    pub fn without_kinds(&self, kinds_to_remove: &[SyntaxKind]) -> Self {
        // Fast path: no requested removals means the tree is unchanged.
        if kinds_to_remove.is_empty() {
            return self.clone();
        }

        // Build a raw-kind lookup table so membership checks are O(1).
        let mut remove_lookup = vec![false; SyntaxKind::ErrorRecovery as usize + 1];
        for kind in kinds_to_remove {
            remove_lookup[*kind as usize] = true;
        }

        let is_removed_kind =
            |kind: SyntaxKind| remove_lookup.get(kind as usize).copied().unwrap_or(false);

        let syntax_node = rowan::SyntaxNode::<VB6Language>::new_root(self.root.clone());

        // Fast path: if none of the root children match, avoid rebuilding.
        let has_matching_root_child = syntax_node.children_with_tokens().any(|child| {
            let child_kind = match &child {
                rowan::NodeOrToken::Node(node) => node.kind(),
                rowan::NodeOrToken::Token(token) => token.kind(),
            };

            is_removed_kind(child_kind)
        });

        if !has_matching_root_child {
            return self.clone();
        }

        let mut builder = GreenNodeBuilder::new();

        builder.start_node(SyntaxKind::Root.to_raw());

        // Iterate through children and only add those not in the filter list
        for child in syntax_node.children_with_tokens() {
            let child_kind = match &child {
                rowan::NodeOrToken::Node(node) => node.kind(),
                rowan::NodeOrToken::Token(token) => token.kind(),
            };

            // Skip if this kind should be removed
            if is_removed_kind(child_kind) {
                continue;
            }

            // Add the child to the new tree
            Self::clone_node_or_token(&mut builder, child);
        }

        builder.finish_node();
        let new_root = builder.finish();

        Self::new(new_root)
    }

    /// Recursively clone a node or token into a builder
    fn clone_node_or_token(
        builder: &mut GreenNodeBuilder<'static>,
        node_or_token: rowan::NodeOrToken<
            rowan::SyntaxNode<VB6Language>,
            rowan::SyntaxToken<VB6Language>,
        >,
    ) {
        match node_or_token {
            rowan::NodeOrToken::Node(node) => {
                builder.start_node(node.kind().to_raw());
                for child in node.children_with_tokens() {
                    Self::clone_node_or_token(builder, child);
                }
                builder.finish_node();
            }
            rowan::NodeOrToken::Token(token) => {
                builder.token(token.kind().to_raw(), token.text());
            }
        }
    }
}

/// Parse a `TokenStream` into a Concrete Syntax Tree.
///
/// This function takes a `TokenStream` and constructs a CST that represents
/// the structure of the VB6 code.
///
/// # Arguments
///
/// * `tokens` - The token stream to parse
///
/// # Returns
///
/// A `ConcreteSyntaxTree` representing the parsed code.
///
/// # Example
///
/// ```rust
/// use vb6parse::lexer::TokenStream;
/// use vb6parse::parsers::cst::parse;
///
/// let tokens = TokenStream::new("example.bas".to_string(), vec![]);
/// let cst = parse(tokens);
/// ```
#[must_use]
pub fn parse(tokens: TokenStream) -> ConcreteSyntaxTree {
    let parser = Parser::new(tokens);
    parser.parse_root().0
}

/// Frame for control parsing with explicit stack.
/// Holds the state for parsing a single control at any nesting level.
#[derive(Debug)]
struct ControlParseFrame {
    control_type: String,
    control_name: String,
    properties: Properties,
    child_controls: Vec<Control>,
    menus: Vec<MenuControl>,
    property_groups: Vec<PropertyGroup>,
}

impl ControlParseFrame {
    fn new(control_type: String, control_name: String) -> Self {
        Self {
            control_type,
            control_name,
            properties: Properties::new(),
            child_controls: Vec::new(),
            menus: Vec::new(),
            property_groups: Vec::new(),
        }
    }

    fn into_control(self) -> Control {
        let tag = self.properties.get("Tag").cloned().unwrap_or_default();
        let index = self
            .properties
            .get("Index")
            .and_then(|s| s.parse().ok())
            .unwrap_or(0);

        let kind = Parser::build_control_kind(
            &self.control_type,
            self.properties,
            self.child_controls,
            self.menus,
            self.property_groups,
        );

        Control::new(self.control_name, tag, index, kind)
    }
}

/// Frame for property group parsing with explicit stack.
#[derive(Debug)]
struct PropertyGroupFrame {
    name: String,
    guid: Option<uuid::Uuid>,
    properties: HashMap<String, Either<String, PropertyGroup>>,
}

impl PropertyGroupFrame {
    fn new(name: String, guid: Option<uuid::Uuid>) -> Self {
        Self {
            name,
            guid,
            properties: HashMap::new(),
        }
    }

    fn into_property_group(self) -> PropertyGroup {
        PropertyGroup {
            name: self.name,
            guid: self.guid,
            properties: self.properties,
        }
    }
}

// ==================== Control Flow State Machine Types ====================

/// Maximum depth for nested control flow statements
const MAX_STATEMENT_DEPTH: usize = 500;

/// Simple enum to identify the type of control flow frame.
/// This avoids using magic numbers (i32) for frame type identification.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum ControlFlowFrameType {
    StatementList,
    IfStatement,
    ForStatement,
    SelectCase,
    WhileStatement,
    DoStatement,
    WithStatement,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Strategy used by parser recovery when creating `ErrorRecovery` nodes.
pub enum RecoveryStrategy {
    /// Recover by consuming exactly one unexpected token.
    SingleToken,
    /// Recover by consuming tokens until the end of the current line.
    ToNewline,
    /// Recover from a mismatched `End <block>` terminator.
    ProcedureTerminator,
}

#[derive(Debug, Clone)]
/// A single parser recovery event captured during CST construction.
pub struct RecoveryEvent {
    /// Monotonic event id in parse order.
    pub id: usize,
    /// Human-readable expectations for this parser location.
    pub expected: Vec<String>,
    /// Tokens consumed during recovery.
    pub found: Vec<Token>,
    /// Recovery strategy that was used.
    pub strategy: RecoveryStrategy,
    /// Span at which recovery started.
    pub span: Span,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Byte range for a CST node in source content.
pub struct NodeRange {
    /// Inclusive start byte offset.
    pub start: u32,
    /// Exclusive end byte offset.
    pub end: u32,
}

/// Parsing state for control flow statements
///
/// This enum represents the state machine frames for parsing control flow
/// statements without mutual recursion. Each frame type corresponds to a
/// control flow construct and tracks its parsing progress through phases.
enum ControlFlowFrame {
    /// Parsing a statement list
    StatementList {
        depth: usize,
        /// Context for determining when to stop parsing
        context: StatementListContext,
        /// Whether `start_node` has been called for this frame
        started: bool,
    },

    /// Parsing an If statement
    IfStatement { phase: IfPhase, depth: usize },

    /// Parsing a For loop
    ForStatement {
        phase: ForPhase,
        is_for_each: bool,
        depth: usize,
    },

    /// Parsing a Select Case
    SelectCase { phase: SelectPhase, depth: usize },

    /// Parsing a While loop
    WhileStatement { phase: WhilePhase, depth: usize },

    /// Parsing a Do loop
    DoStatement { phase: DoPhase, depth: usize },

    /// Parsing a With block
    WithStatement { phase: WithPhase, depth: usize },
}

/// Context for statement list parsing to determine stop conditions
#[derive(Copy, Clone)]
enum StatementListContext {
    /// Top-level statement list (stops at end of input)
    TopLevel,
    /// `If/Then` body (stops at `ElseIf`, `Else`, or `End If`)
    IfThenBody,
    /// `ElseIf` body (stops at `ElseIf`, `Else`, or `End If`)  
    ElseIfBody,
    /// `Else` body (stops at `End If`)
    ElseBody,
    /// `For` loop body (stops at `Next`)
    ForBody,
    /// `Select Case` body (stops at `Case`, `Case Else`, or `End Select`)
    SelectCaseBody,
    /// `While` loop body (stops at `Wend`)
    WhileBody,
    /// `Do` loop body (stops at `Loop`)
    DoBody,
    /// `With` block body (stops at `End With`)
    WithBody,
}

/// Phases for parsing an If statement
#[derive(Copy, Clone)]
enum IfPhase {
    /// Start parsing the If statement (parse condition and Then keyword)
    Start,
    /// Parse the Then body (statement list pushed separately)
    ThenBody,
    /// Check for and parse `ElseIf` condition
    CheckElseIf,
    /// Parse `ElseIf` body (statement list pushed separately)
    ElseIfBody,
    /// Check for and parse `Else`
    CheckElse,
    /// Parse `Else` body (statement list pushed separately)
    ElseBody,
    /// Finish the `If` statement (parse `End If`)
    Finish,
}

/// Phases for parsing a `For` loop
#[derive(Copy, Clone)]
enum ForPhase {
    /// Start parsing (parse `For` variable = start `To` end [`Step` step])
    Start,
    /// Parse loop body (statement list pushed separately)
    Body,
    /// Finish the loop (parse `Next`)
    Finish,
}

/// Phases for parsing a `Select Case` statement
#[derive(Copy, Clone)]
enum SelectPhase {
    /// Start parsing (parse `Select Case` expression)
    Start,
    /// Parse `Case` clause
    CaseClause,
    /// Parse `Case` body (statement list pushed separately)
    CaseBody,
    /// Check for more `Case` clauses or `Case Else`
    CheckNextCase,
    /// Parse `Case Else` body (statement list pushed separately)
    CaseElseBody,
    /// Finish (parse `End Select`)
    Finish,
}

/// Phases for parsing a `While` loop
#[derive(Copy, Clone)]
enum WhilePhase {
    /// Start parsing (parse `While` condition)
    Start,
    /// Parse loop body (statement list pushed separately)
    Body,
    /// Finish the loop (parse `Wend`)
    Finish,
}

/// Phases for parsing a `Do` loop
#[derive(Copy, Clone)]
enum DoPhase {
    /// Start parsing (parse `Do` [While/Until condition])
    Start,
    /// Parse loop body (statement list pushed separately)
    Body,
    /// Finish the loop (parse `Loop` [While/Until condition])
    Finish,
}

/// Phases for parsing a `With` block
#[derive(Copy, Clone)]
enum WithPhase {
    /// Start parsing (parse `With` expression)
    Start,
    /// Parse `With` body (statement list pushed separately)
    Body,
    /// Finish the block (parse `End With`)
    Finish,
}

impl ControlFlowFrame {
    /// Get the type identifier for this frame.
    /// This allows matching on frame types without borrowing the entire frame.
    fn frame_type(&self) -> ControlFlowFrameType {
        match self {
            ControlFlowFrame::StatementList { .. } => ControlFlowFrameType::StatementList,
            ControlFlowFrame::IfStatement { .. } => ControlFlowFrameType::IfStatement,
            ControlFlowFrame::ForStatement { .. } => ControlFlowFrameType::ForStatement,
            ControlFlowFrame::SelectCase { .. } => ControlFlowFrameType::SelectCase,
            ControlFlowFrame::WhileStatement { .. } => ControlFlowFrameType::WhileStatement,
            ControlFlowFrame::DoStatement { .. } => ControlFlowFrameType::DoStatement,
            ControlFlowFrame::WithStatement { .. } => ControlFlowFrameType::WithStatement,
        }
    }
}

/// Internal parser state for building the CST.
///
/// # Parser Conventions
///
/// This type uses consistent method-prefix conventions across CST parsing code:
///
/// - `parse_*`: Parse a grammar construct and usually emit CST nodes/tokens.
/// - `handle_*`: Advance an explicit parser state-machine frame (dispatch/phase handlers).
/// - `try_*`: Attempt a parse path and return `bool` to indicate whether it matched.
///   These methods should be non-destructive when returning `false`.
/// - `consume_*`: Advance input and usually feed tokens into the CST builder.
/// - `skip_*`: Advance input without emitting CST nodes (typically direct-extraction helpers).
/// - `at_*` / `peek_*`: Token inspection/lookahead helpers used for branching decisions.
///
/// Error-handling conventions:
///
/// - `report_error(...)` records recoverable parse failures while allowing continued parsing.
/// - Callers should prefer recovery over hard-fail where practical so downstream tools still
///   receive a partial CST plus diagnostics.
pub(crate) struct Parser<'a> {
    pub(crate) tokens: Vec<(&'a str, Token)>,
    pub(crate) pos: usize,
    pub(crate) builder: GreenNodeBuilder<'static>,
    pub(crate) parsing_header: bool,
    pub(crate) source_name: String,
    pub(crate) source_content: &'a str,
    pub(crate) failures: Vec<ErrorDetails<'a>>,
    pub(crate) recovery_events: Vec<RecoveryEvent>,
    pub(crate) next_recovery_event_id: usize,
}

impl<'a> Parser<'a> {
    fn new(token_stream: TokenStream<'a>) -> Self {
        let source_name = token_stream.file_name().to_string();
        Parser {
            tokens: token_stream.into_tokens(),
            pos: 0,
            builder: GreenNodeBuilder::new(),
            parsing_header: true,
            source_name,
            source_content: "",
            failures: Vec::new(),
            recovery_events: Vec::new(),
            next_recovery_event_id: 1,
        }
    }

    fn set_source_content(&mut self, source_content: &'a str) {
        self.source_content = source_content;
    }

    /// Create parser for direct extraction mode (control-only parsing)
    pub(crate) fn new_direct_extraction(tokens: Vec<(&'a str, Token)>, pos: usize) -> Self {
        Parser {
            tokens,
            pos,
            builder: GreenNodeBuilder::new(),
            parsing_header: true,
            source_name: String::new(),
            source_content: "",
            failures: Vec::new(),
            recovery_events: Vec::new(),
            next_recovery_event_id: 1,
        }
    }

    fn current_span(&self) -> Span {
        let mut offset: u32 = 0;
        let mut line: u32 = 1;

        for (text, token) in self.tokens.iter().take(self.pos) {
            let text_len = u32::try_from(text.len()).unwrap_or(u32::MAX);
            offset = offset.saturating_add(text_len);
            if *token == Token::Newline {
                line = line.saturating_add(1);
            }
        }

        let (length, line_end) = if let Some((text, token)) = self.tokens.get(self.pos) {
            let text_len = u32::try_from(text.len().max(1)).unwrap_or(u32::MAX);
            if *token == Token::Newline {
                (text_len, line.saturating_add(1))
            } else {
                (text_len, line)
            }
        } else {
            (1, line)
        };

        Span::new(offset, line, line_end, length)
    }

    pub(crate) fn report_error<E>(&mut self, kind: E)
    where
        E: Into<ErrorKind>,
    {
        let span = self.current_span();
        self.failures.push(ErrorDetails::basic(
            self.source_name.clone().into_boxed_str(),
            self.source_content,
            span.offset,
            span.line_start,
            span.line_end,
            kind,
            Severity::Error,
        ));
    }

    // Create parser for hybrid mode (`FormFile` optimization)
    // ==================== Direct Extraction Helpers ====================
    // These methods support direct extraction without CST building

    /// Consume the parser and return the remaining tokens
    /// Used to get tokens after direct extraction for CST building
    pub(crate) fn into_tokens(self) -> Vec<(&'a str, Token)> {
        // Return tokens from current position onwards
        self.tokens[self.pos..].to_vec()
    }

    /// Skip whitespace tokens without consuming them into the CST
    pub(crate) fn skip_whitespace(&mut self) {
        while self.at_token(Token::Whitespace) {
            self.pos += 1;
        }
    }

    /// Skip whitespace and newline tokens without consuming them into the CST
    pub(crate) fn skip_whitespace_and_newlines(&mut self) {
        while self.at_token(Token::Whitespace) || self.at_token(Token::Newline) {
            self.pos += 1;
        }
    }

    /// Consume and advance past the current token without adding to CST
    /// Returns the consumed token for inspection
    pub(crate) fn consume_advance(&mut self) -> Option<(&'a str, Token)> {
        if self.pos < self.tokens.len() {
            let token = self.tokens[self.pos];
            self.pos += 1;
            Some(token)
        } else {
            None
        }
    }

    // ==================== Direct Extraction Methods ====================

    /// Parse VERSION statement directly without building CST
    ///
    /// Extracts the file format version (e.g., \"VERSION 5.00\") by directly
    /// parsing tokens without CST construction overhead.
    ///
    /// # Returns
    ///
    /// A `ParseResult` containing:
    /// - `result`: `Some(FileFormatVersion)` if found and valid, `None` if not present or invalid
    /// - `failures`: Empty vec (no errors generated for missing VERSION)
    pub(crate) fn parse_version_direct(&mut self) -> ParseResult<'a, FileFormatVersion> {
        self.skip_whitespace();

        // Check if VERSION keyword is present
        if !self.at_token(Token::VersionKeyword) {
            return ParseResult::new(None, Vec::new());
        }

        self.consume_advance(); // VERSION keyword
        self.skip_whitespace();

        // Parse version number (e.g., \"5.00\" or \"1.0\")
        let version_result = if let Some((text, token)) = self.tokens.get(self.pos) {
            match token {
                Token::SingleLiteral | Token::DoubleLiteral | Token::IntegerLiteral => {
                    let version_str = text.trim();
                    self.consume_advance();

                    // Parse \"major.minor\" format
                    let parts: Vec<&str> = version_str.split('.').collect();
                    if parts.len() == 2 {
                        if let (Ok(major), Ok(minor)) =
                            (parts[0].parse::<u8>(), parts[1].parse::<u8>())
                        {
                            Some(FileFormatVersion { major, minor })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                }
                _ => None,
            }
        } else {
            None
        };

        // Skip optional CLASS keyword and trailing whitespace
        self.skip_whitespace();
        if self.at_token(Token::ClassKeyword) {
            self.consume_advance();
        }
        self.skip_whitespace_and_newlines();

        ParseResult::new(version_result, Vec::new())
    }

    // ==================== Core Control Extraction Methods ====================

    /// Check if current token is `BeginProperty` identifier
    fn is_begin_property(&self) -> bool {
        if let Some((text, token)) = self.tokens.get(self.pos) {
            *token == Token::Identifier && text.eq_ignore_ascii_case("BeginProperty")
        } else {
            false
        }
    }

    /// Check if current token is an identifier matching the target text (case-insensitive)
    fn is_identifier_text(&self, target: &str) -> bool {
        if let Some((text, token)) = self.tokens.get(self.pos) {
            *token == Token::Identifier && text.eq_ignore_ascii_case(target)
        } else {
            false
        }
    }

    /// Convert a Menu-typed Control into `MenuControl`
    fn control_to_menu(control: Control) -> MenuControl {
        let (name, tag, index, kind) = control.into_parts();

        if let ControlKind::Menu {
            properties,
            sub_menus,
        } = kind
        {
            MenuControl::new(name, tag, index, properties, sub_menus)
        } else {
            // Fallback: create empty menu control
            MenuControl::new(name, tag, index, MenuProperties::default(), Vec::new())
        }
    }

    /// Parse control type directly from tokens (e.g., "VB.Form", "VB.CommandButton")
    fn parse_control_type_direct(&mut self) -> String {
        let mut span_start: Option<usize> = None;
        let mut span_end = self.pos;

        // Parse identifier or keyword
        if (self.is_identifier() || self.at_keyword()) && self.tokens.get(self.pos).is_some() {
            span_start = Some(self.pos);
            self.consume_advance();
            span_end = self.pos;
        }

        // Parse dot-separated parts (e.g., "VB.Form")
        while self.at_token(Token::PeriodOperator) {
            self.consume_advance(); // dot
            if self.is_identifier() || self.at_keyword() {
                if self.tokens.get(self.pos).is_some() {
                    self.consume_advance();
                    span_end = self.pos;
                }
            } else {
                break;
            }
        }

        let Some(start) = span_start else {
            return String::new();
        };

        if let Some((start_offset, end_offset)) = self.tokens_span_offsets(start, span_end) {
            return self.source_content[start_offset..end_offset].to_string();
        }

        // Fallback for parser modes that do not have a usable source backing slice.
        let mut value = String::new();
        for idx in start..span_end {
            if let Some((text, _)) = self.tokens.get(idx) {
                value.push_str(text);
            }
        }

        value
    }

    /// Parse control name directly from tokens
    fn parse_control_name_direct(&mut self) -> String {
        if (self.is_identifier() || self.at_keyword()) && self.tokens.get(self.pos).is_some() {
            let start = self.pos;
            self.consume_advance();
            if let Some((start_offset, end_offset)) = self.tokens_span_offsets(start, self.pos) {
                return self.source_content[start_offset..end_offset].to_string();
            }

            if let Some((text, _)) = self.tokens.get(start) {
                return text.to_string();
            }
        }
        String::new()
    }

    /// Parse a property assignment (Key = Value) directly from tokens
    /// Returns (key, value) tuple
    fn parse_property_direct(&mut self) -> Option<(String, String)> {
        // Parse property key
        let key = if self.is_identifier() || self.at_keyword() {
            if self.tokens.get(self.pos).is_some() {
                let key_start = self.pos;
                self.consume_advance();
                if let Some((start_offset, end_offset)) =
                    self.tokens_span_offsets(key_start, self.pos)
                {
                    self.source_content[start_offset..end_offset].to_string()
                } else if let Some((text, _)) = self.tokens.get(key_start) {
                    text.to_string()
                } else {
                    return None;
                }
            } else {
                return None;
            }
        } else {
            return None;
        };

        self.skip_whitespace();

        // Parse = sign
        if !self.at_token(Token::EqualityOperator) {
            return None;
        }
        self.consume_advance();
        self.skip_whitespace();

        // Parse value (everything until newline/colon)
        // Special case: Resource references like "file.frx":0000 or $"file.frx":0000
        // should include the colon and offset. The quotes should be preserved.
        let value_start = self.pos;
        let mut in_resource_reference = false;

        while !self.is_at_end() && !self.at_token(Token::Newline) {
            if let Some((_, token)) = self.tokens.get(self.pos) {
                let token_copy = *token;

                // Check if we see a dollar sign
                if token_copy == Token::DollarSign {
                    self.consume_advance();
                }
                // If we see a string literal (with or without $), check if resource reference follows
                else if token_copy == Token::StringLiteral {
                    self.consume_advance();

                    // Peek ahead - if next token is colon, this is a resource reference
                    if let Some((_, next_token)) = self.tokens.get(self.pos)
                        && *next_token == Token::ColonOperator
                    {
                        in_resource_reference = true;
                    }
                }
                // If in resource reference, capture colon
                else if in_resource_reference && token_copy == Token::ColonOperator {
                    self.consume_advance();
                }
                // If in resource reference and we see the offset number, capture it and stop
                else if in_resource_reference
                    && (token_copy == Token::IntegerLiteral || token_copy == Token::LongLiteral)
                {
                    self.consume_advance();
                    break; // Done with resource reference
                }
                // If we hit a colon and not in resource reference, stop
                else if token_copy == Token::ColonOperator {
                    break;
                }
                // Otherwise, capture the token
                else {
                    self.consume_advance();
                }
            } else {
                break;
            }
        }

        // Skip newline
        self.skip_whitespace_and_newlines();

        let value_end = self.pos;
        let value = if let Some((start_offset, end_offset)) =
            self.tokens_span_offsets(value_start, value_end)
        {
            self.source_content[start_offset..end_offset]
                .trim()
                .to_string()
        } else {
            // Fallback for parser modes that do not have a usable source backing slice.
            let mut value_text = String::new();
            for idx in value_start..value_end {
                if let Some((text, _)) = self.tokens.get(idx) {
                    value_text.push_str(text);
                }
            }
            value_text.trim().to_string()
        };

        Some((key, value))
    }

    /// Parse property group directly (BeginProperty...EndProperty)
    fn parse_property_group_direct(&mut self) -> Option<PropertyGroup> {
        // Expect BeginProperty identifier
        if !self.is_identifier_text("BeginProperty") {
            return None;
        }

        self.consume_advance(); // BeginProperty
        self.skip_whitespace();

        // Parse initial property group name and GUID
        let (name, guid) = self.parse_property_group_name_direct();
        self.skip_whitespace_and_newlines();

        // Use explicit stack instead of recursion
        let mut stack: Vec<PropertyGroupFrame> = Vec::new();
        stack.push(PropertyGroupFrame::new(name, guid));

        // Iteratively process property groups
        while let Some(current_frame) = stack.last_mut() {
            self.skip_whitespace();

            if self.is_at_end() || self.is_identifier_text("EndProperty") {
                // Finished this property group
                if self.is_identifier_text("EndProperty") {
                    self.consume_advance();
                    self.skip_whitespace_and_newlines();
                }

                let finished_frame = stack.pop().unwrap();
                let prop_group = finished_frame.into_property_group();

                // Add to parent if exists, or return as result
                if let Some(parent_frame) = stack.last_mut() {
                    parent_frame
                        .properties
                        .insert(prop_group.name.clone(), Either::Right(prop_group));
                } else {
                    // This is the root property group - return it
                    return Some(prop_group);
                }
                continue;
            }

            if self.is_identifier_text("BeginProperty") {
                // Start parsing nested property group - push new frame
                self.consume_advance(); // BeginProperty
                self.skip_whitespace();

                let (nested_name, nested_guid) = self.parse_property_group_name_direct();
                self.skip_whitespace_and_newlines();

                // Check depth limit

                if stack.len() >= MAX_PROPERTY_GROUP_DEPTH {
                    // Skip this nested property group
                    let mut depth = 1;
                    while !self.is_at_end() && depth > 0 {
                        if self.is_identifier_text("BeginProperty") {
                            depth += 1;
                            self.consume_advance();
                        } else if self.is_identifier_text("EndProperty") {
                            depth -= 1;
                            self.consume_advance();
                        } else {
                            self.consume_advance();
                        }
                    }
                    continue;
                }

                stack.push(PropertyGroupFrame::new(nested_name, nested_guid));
                continue;
            }

            if self.is_identifier() || self.at_keyword() {
                // Regular property
                if let Some((key, value)) = self.parse_property_direct() {
                    current_frame.properties.insert(key, Either::Left(value));
                }
            } else {
                self.consume_advance();
            }
        }

        // Should not reach here
        None
    }

    /// Parse property group name and extract optional GUID
    /// Format: "Name {GUID}" or just "Name"
    fn parse_property_group_name_direct(&mut self) -> (String, Option<uuid::Uuid>) {
        let mut name_parts: Vec<&str> = Vec::new();
        let mut guid_parts: Vec<&str> = Vec::new();
        let mut in_guid = false;

        // Collect tokens until newline
        while !self.is_at_end() && !self.at_token(Token::Newline) {
            if let Some((text, token)) = self.tokens.get(self.pos) {
                if *token == Token::LeftCurlyBrace {
                    // Start of GUID
                    in_guid = true;
                } else if *token == Token::RightCurlyBrace {
                    // End of GUID
                    in_guid = false;
                } else if *token != Token::Whitespace && *token != Token::EndOfLineComment {
                    // Collect non-whitespace tokens
                    if in_guid {
                        guid_parts.push(*text);
                    } else {
                        name_parts.push(*text);
                    }
                }
            }
            self.consume_advance();
        }

        let name = name_parts.concat();
        let guid = if guid_parts.is_empty() {
            None
        } else {
            let guid_str = guid_parts.concat();
            uuid::Uuid::parse_str(&guid_str).ok()
        };

        (name, guid)
    }

    /// Parse Object statements directly (without CST)
    pub(crate) fn parse_objects_direct(&mut self) -> Vec<ObjectReference> {
        let mut objects = Vec::new();

        self.skip_whitespace_and_newlines();

        // Continue parsing Object statements until we hit something else
        while self.at_token(Token::ObjectKeyword) {
            if let Some(obj_ref) = self.parse_single_object_direct() {
                objects.push(obj_ref);
            }
            self.skip_whitespace_and_newlines();
        }

        objects
    }

    /// Parse a single Object statement line
    /// Format: Object = "{UUID}#version#flags"; "filename"
    /// Or:     Object = *\G{UUID}#version#flags; "filename"
    fn parse_single_object_direct(&mut self) -> Option<ObjectReference> {
        // Expect "Object" keyword
        if !self.at_token(Token::ObjectKeyword) {
            return None;
        }
        self.consume_advance(); // Object
        self.skip_whitespace();

        // Expect "="
        if !self.at_token(Token::EqualityOperator) {
            return None;
        }
        self.consume_advance(); // =
        self.skip_whitespace();

        // Check for optional "*\G" prefix (embedded object)
        let mut _is_embedded = false;
        if self.at_token(Token::MultiplicationOperator) {
            self.consume_advance(); // *
            // Expect \G (backslash followed by identifier "G")
            if let Some((_text, token)) = self.tokens.get(self.pos)
                && *token == Token::BackwardSlashOperator
            {
                self.consume_advance(); // \
                if let Some((text2, token2)) = self.tokens.get(self.pos)
                    && *token2 == Token::Identifier
                    && text2.eq_ignore_ascii_case("G")
                {
                    self.consume_advance(); // G
                    _is_embedded = true;
                }
            }
        }
        self.skip_whitespace();

        // Parse first string literal or GUID tokens: "{UUID}#version#flags"
        // The GUID may be tokenized as:
        //   - A StringLiteral: "{UUID}#version#flags"
        //   - Individual tokens: { UUID-parts } # version # flags
        let uuid_part = if let Some((text, token)) = self.tokens.get(self.pos) {
            if *token == Token::StringLiteral {
                // String literal format
                let s = text.trim_matches('"').to_string();
                self.consume_advance();
                s
            } else if *token == Token::LeftCurlyBrace {
                // Token format: { guid-parts } #version# flags
                // Collect all tokens until semicolon
                let mut parts: Vec<&str> = Vec::new();
                while !self.is_at_end() && !self.at_token(Token::Semicolon) {
                    if let Some((text, token)) = self.tokens.get(self.pos) {
                        // Skip whitespace but collect everything else
                        if *token != Token::Whitespace {
                            parts.push(text);
                        }
                        self.consume_advance();
                    } else {
                        break;
                    }
                }
                // Reconstruct the UUID part string
                // Need to convert: { ... } #version# flags -> {UUID}#version#flags
                parts.concat()
            } else {
                return None;
            }
        } else {
            return None;
        };

        self.skip_whitespace();

        // Expect semicolon
        if !self.at_token(Token::Semicolon) {
            return None;
        }
        self.consume_advance(); // ;
        self.skip_whitespace();

        // Parse second string literal: filename
        let file_name = if let Some((text, token)) = self.tokens.get(self.pos) {
            if *token == Token::StringLiteral {
                let s = text.trim_matches('"').to_string();
                self.consume_advance();
                s
            } else {
                return None;
            }
        } else {
            return None;
        };

        // Parse UUID part: {UUID}#version#flags or UUID#version#flags
        let parts: Vec<&str> = uuid_part.split('#').collect();
        if parts.len() >= 3 {
            // Extract UUID (remove braces if present)
            let uuid_str = parts[0].trim_matches(|c| c == '{' || c == '}');

            if let Ok(uuid) = uuid::Uuid::parse_str(uuid_str) {
                let version = parts[1].to_string();
                let unknown1 = parts[2].to_string();

                return Some(ObjectReference::Compiled {
                    uuid,
                    version,
                    unknown1,
                    file_name,
                });
            }
        }

        None
    }

    /// Parse Attribute statements directly (without CST)
    pub(crate) fn parse_attributes_direct(&mut self) -> FileAttributes {
        let mut name = String::new();
        let mut global_name_space = NameSpace::Local;
        let mut creatable = Creatable::True;
        let mut predeclared_id = PreDeclaredID::False;
        let mut exposed = Exposed::False;
        let mut description: Option<String> = None;
        let mut ext_key: HashMap<String, String> = HashMap::new();

        self.skip_whitespace_and_newlines();

        // Continue parsing Attribute statements until we hit something else
        while self.at_token(Token::AttributeKeyword) {
            if let Some((key, value)) = self.parse_single_attribute_direct() {
                // Process the extracted key-value pair
                match key.as_str() {
                    "VB_Name" => {
                        name = value;
                    }
                    "VB_GlobalNameSpace" => {
                        global_name_space = if value == "True" || value == "-1" {
                            NameSpace::Global
                        } else {
                            NameSpace::Local
                        };
                    }
                    "VB_Creatable" => {
                        creatable = if value == "True" || value == "-1" {
                            Creatable::True
                        } else {
                            Creatable::False
                        };
                    }
                    "VB_PredeclaredId" => {
                        predeclared_id = if value == "True" || value == "-1" {
                            PreDeclaredID::True
                        } else {
                            PreDeclaredID::False
                        };
                    }
                    "VB_Exposed" => {
                        exposed = if value == "True" || value == "-1" {
                            Exposed::True
                        } else {
                            Exposed::False
                        };
                    }
                    "VB_Description" => {
                        description = Some(value);
                    }
                    _ => {
                        // Store any other attributes in ext_key
                        ext_key.insert(key, value);
                    }
                }
            }
            self.skip_whitespace_and_newlines();
        }

        FileAttributes {
            name,
            global_name_space,
            creatable,
            predeclared_id,
            exposed,
            description,
            ext_key,
        }
    }

    /// Parse a single Attribute statement line
    /// ```Attribute VB_Name = "Value"```
    /// Or
    /// ```Attribute VB_GlobalNameSpace = True```
    fn parse_single_attribute_direct(&mut self) -> Option<(String, String)> {
        // Expect "Attribute" keyword
        if !self.at_token(Token::AttributeKeyword) {
            return None;
        }
        self.consume_advance(); // Attribute
        self.skip_whitespace();

        // Parse attribute key (e.g., "VB_Name")
        let key = if let Some((text, token)) = self.tokens.get(self.pos) {
            if *token == Token::Identifier {
                let k = text.to_string();
                self.consume_advance();
                k
            } else {
                return None;
            }
        } else {
            return None;
        };

        self.skip_whitespace();

        // Expect "="
        if !self.at_token(Token::EqualityOperator) {
            return None;
        }
        self.consume_advance(); // =
        self.skip_whitespace();

        // Parse value (can be string, True/False, or number)
        let mut value = String::new();
        let mut found_value = false;

        // Check for negative sign first (for values like "-1")
        if self.at_token(Token::SubtractionOperator) {
            value.push('-');
            self.consume_advance();
            self.skip_whitespace();
        }

        if let Some((text, token)) = self.tokens.get(self.pos) {
            match token {
                Token::StringLiteral => {
                    // Remove surrounding quotes
                    value.push_str(text.trim().trim_matches('"'));
                    self.consume_advance();
                    found_value = true;
                }
                Token::TrueKeyword => {
                    value.push_str("True");
                    self.consume_advance();
                    found_value = true;
                }
                Token::FalseKeyword => {
                    value.push_str("False");
                    self.consume_advance();
                    found_value = true;
                }
                Token::IntegerLiteral | Token::LongLiteral => {
                    value.push_str(text.trim());
                    self.consume_advance();
                    found_value = true;
                }
                _ => {}
            }
        }

        // Consume the rest of the line (for complex attributes like VB_Ext_KEY)
        // Skip until we hit a newline or end of tokens
        while self.pos < self.tokens.len() {
            if let Some((_, token)) = self.tokens.get(self.pos) {
                if *token == Token::Newline {
                    break;
                }
                self.consume_advance();
            } else {
                break;
            }
        }

        if found_value {
            Some((key, value))
        } else {
            None
        }
    }

    /// Build `FormRoot` from control type string and properties
    ///
    /// This function is used for parsing top-level form elements.
    /// Only `VB.Form` and `VB.MDIForm` are valid top-level types.
    fn build_form_root(
        control_type: &str,
        control_name: String,
        tag: String,
        index: i32,
        properties: Properties,
        groups: &[PropertyGroup],
        child_controls: Vec<Control>,
        menus: Vec<MenuControl>,
    ) -> Result<FormRoot, ErrorKind> {
        match control_type {
            "VB.Form" => {
                let mut form_properties: FormProperties = properties.into();
                // Override with property group if present
                let extracted_groups = extract_property_groups(groups);
                if let Some(font) = extracted_groups.font {
                    form_properties.font = Some(font);
                }

                Ok(FormRoot::Form(Form {
                    name: control_name,
                    tag,
                    index,
                    properties: form_properties,
                    controls: child_controls,
                    menus,
                }))
            }
            "VB.MDIForm" => {
                let mut mdi_form_properties: MDIFormProperties = properties.into();
                // Override with property group if present
                let extracted_groups = extract_property_groups(groups);
                if let Some(font) = extracted_groups.font {
                    mdi_form_properties.font = Some(font);
                }

                Ok(FormRoot::MDIForm(MDIForm {
                    name: control_name,
                    tag,
                    index,
                    properties: mdi_form_properties,
                    controls: child_controls,
                    menus,
                }))
            }
            _ => Err(ErrorKind::Form(FormError::InvalidTopLevelControl {
                control_type: control_type.to_string(),
            })),
        }
    }

    /// Build `ControlKind` from control type string and properties
    ///
    /// Note: This function rejects `VB.Form` and `VB.MDIForm` as they are now
    /// top-level types only and cannot be child controls.
    #[allow(clippy::too_many_lines)]
    fn build_control_kind(
        control_type: &str,
        properties: Properties,
        child_controls: Vec<Control>,
        menus: Vec<MenuControl>,
        property_groups: Vec<PropertyGroup>,
    ) -> ControlKind {
        use ControlKind;
        // Extract typed property groups
        let groups = extract_property_groups(&property_groups);

        match control_type {
            "VB.CommandButton" => {
                let mut props: CommandButtonProperties = properties.into();
                // Override with property group if present
                if let Some(font) = groups.font {
                    props.font = Some(font);
                }
                ControlKind::CommandButton { properties: props }
            }
            "VB.Data" => {
                let mut props: DataProperties = properties.into();
                // Override with property group if present
                if let Some(font) = groups.font {
                    props.font = Some(font);
                }
                ControlKind::Data { properties: props }
            }
            "VB.TextBox" => {
                let mut props: TextBoxProperties = properties.into();
                // Override with property group if present
                if let Some(font) = groups.font {
                    props.font = Some(font);
                }
                ControlKind::TextBox { properties: props }
            }
            "VB.Label" => {
                let mut props: LabelProperties = properties.into();
                // Override with property group if present
                if let Some(font) = groups.font {
                    props.font = Some(font);
                }
                ControlKind::Label { properties: props }
            }
            "VB.CheckBox" => {
                let mut props: CheckBoxProperties = properties.into();
                // Override with property group if present
                if let Some(font) = groups.font {
                    props.font = Some(font);
                }
                ControlKind::CheckBox { properties: props }
            }
            "VB.Line" => ControlKind::Line {
                properties: properties.into(),
            },
            "VB.Shape" => ControlKind::Shape {
                properties: properties.into(),
            },
            "VB.ListBox" => {
                let mut props: ListBoxProperties = properties.into();
                // Override with property group if present
                if let Some(font) = groups.font {
                    props.font = Some(font);
                }
                ControlKind::ListBox { properties: props }
            }
            "VB.ComboBox" => {
                let mut props: ComboBoxProperties = properties.into();
                // Override with property group if present
                if let Some(font) = groups.font {
                    props.font = Some(font);
                }
                ControlKind::ComboBox { properties: props }
            }
            "VB.Timer" => ControlKind::Timer {
                properties: properties.into(),
            },
            "VB.HScrollBar" => ControlKind::HScrollBar {
                properties: properties.into(),
            },
            "VB.VScrollBar" => ControlKind::VScrollBar {
                properties: properties.into(),
            },
            "VB.Frame" => {
                let mut props: FrameProperties = properties.into();
                // Override with property group if present
                if let Some(font) = groups.font {
                    props.font = Some(font);
                }
                ControlKind::Frame {
                    properties: props,
                    controls: child_controls,
                }
            }
            "VB.PictureBox" => {
                let mut props: PictureBoxProperties = properties.into();
                // Override with property group if present
                if let Some(font) = groups.font {
                    props.font = Some(font);
                }
                ControlKind::PictureBox {
                    properties: props,
                    controls: child_controls,
                }
            }
            "VB.FileListBox" => {
                let mut props: FileListBoxProperties = properties.into();
                // Override with property group if present
                if let Some(font) = groups.font {
                    props.font = Some(font);
                }
                ControlKind::FileListBox { properties: props }
            }
            "VB.DirListBox" => {
                let mut props: DirListBoxProperties = properties.into();
                // Override with property group if present
                if let Some(font) = groups.font {
                    props.font = Some(font);
                }
                ControlKind::DirListBox { properties: props }
            }
            "VB.DriveListBox" => {
                let mut props: DriveListBoxProperties = properties.into();
                // Override with property group if present
                if let Some(font) = groups.font {
                    props.font = Some(font);
                }
                ControlKind::DriveListBox { properties: props }
            }
            "VB.Image" => ControlKind::Image {
                properties: properties.into(),
            },
            "VB.OptionButton" => {
                let mut props: OptionButtonProperties = properties.into();
                // Override with property group if present
                if let Some(font) = groups.font {
                    props.font = Some(font);
                }
                ControlKind::OptionButton { properties: props }
            }
            "VB.OLE" => ControlKind::Ole {
                properties: properties.into(),
            },
            "VB.Menu" => ControlKind::Menu {
                properties: properties.into(),
                sub_menus: menus,
            },
            _ => ControlKind::Custom {
                properties: properties.into(),
                property_groups,
            },
        }
    }

    /// Parse properties block directly to Control without building CST
    pub(crate) fn parse_properties_block_to_control(&mut self) -> ParseResult<'a, Control> {
        self.skip_whitespace();

        // Expect BEGIN keyword
        if !self.at_token(Token::BeginKeyword) {
            return ParseResult::new(None, Vec::new());
        }

        self.consume_advance(); // BEGIN
        self.skip_whitespace();

        // Parse control type and name for initial frame
        let control_type = self.parse_control_type_direct();
        self.skip_whitespace();
        let control_name = self.parse_control_name_direct();
        self.skip_whitespace_and_newlines();

        // Use explicit stack instead of recursion
        let mut stack: Vec<ControlParseFrame> = Vec::new();
        let failures = Vec::new();

        // Push initial frame
        stack.push(ControlParseFrame::new(control_type, control_name));

        // Iteratively process frames
        while let Some(current_frame) = stack.last_mut() {
            self.skip_whitespace();

            if self.is_at_end() || self.at_token(Token::EndKeyword) {
                // Finished this control - pop and finalize
                if self.at_token(Token::EndKeyword) {
                    self.consume_advance();
                    self.skip_whitespace_and_newlines();
                }

                let finished_frame = stack.pop().unwrap();
                let control = finished_frame.into_control();

                // Add to parent if exists, or return as result
                if let Some(parent_frame) = stack.last_mut() {
                    // Check if it's a menu control
                    if matches!(control.kind(), ControlKind::Menu { .. }) {
                        parent_frame.menus.push(Self::control_to_menu(control));
                    } else {
                        parent_frame.child_controls.push(control);
                    }
                } else {
                    // This is the root control - return it
                    return ParseResult::new(Some(control), failures);
                }
                continue;
            }

            if self.at_token(Token::BeginKeyword) {
                // Start parsing nested control - push new frame to stack
                self.consume_advance(); // BEGIN
                self.skip_whitespace();

                let nested_type = self.parse_control_type_direct();
                self.skip_whitespace();
                let nested_name = self.parse_control_name_direct();
                self.skip_whitespace_and_newlines();

                // Check depth limit
                if stack.len() >= MAX_CONTROL_DEPTH {
                    // Skip this nested control and its children
                    // Find matching End keyword
                    let mut depth = 1;
                    while !self.is_at_end() && depth > 0 {
                        if self.at_token(Token::BeginKeyword) {
                            depth += 1;
                        } else if self.at_token(Token::EndKeyword) {
                            depth -= 1;
                        }
                        self.consume_advance();
                    }
                    continue;
                }

                stack.push(ControlParseFrame::new(nested_type, nested_name));
                continue;
            }

            if self.is_begin_property() {
                // Parse property group (now iterative)
                if let Some(group) = self.parse_property_group_direct() {
                    current_frame.property_groups.push(group);
                }
            } else if self.is_identifier() || self.at_keyword() {
                // Parse property (Key = Value)
                if let Some((key, value)) = self.parse_property_direct() {
                    // Remove surrounding quotes if this is a simple string literal
                    // BUT NOT if it's a resource reference (contains ":digit" pattern)
                    let is_resource_reference = value.contains(':')
                        && value
                            .split(':')
                            .next_back()
                            .is_some_and(|part| part.chars().all(|c| c.is_ascii_digit()));

                    let cleaned_value = if !is_resource_reference
                        && value.starts_with('"')
                        && value.ends_with('"')
                        && value.len() >= 2
                    {
                        &value[1..value.len() - 1]
                    } else {
                        &value
                    };
                    current_frame.properties.insert(&key, cleaned_value);
                }
            } else {
                // Skip unknown token
                self.consume_advance();
            }
        }

        // Should not reach here
        ParseResult::new(None, failures)
    }

    /// Parse properties block directly to `FormRoot` for top-level form elements.
    ///
    /// This function is specifically for parsing the top-level form element in
    /// `.frm`, `.ctl`, and `.dob` files. It enforces that only `VB.Form` or
    /// `VB.MDIForm` can be used as the root element.
    ///
    /// # Returns
    ///
    /// A `ParseResult` containing either a `FormRoot` (`Form` or `MDIForm`) or `None`,
    /// along with any parsing failures encountered.
    pub(crate) fn parse_properties_block_to_form_root(&mut self) -> ParseResult<'a, FormRoot> {
        use Properties;

        let mut groups = Vec::new();

        self.skip_whitespace();

        // Expect BEGIN keyword
        if !self.at_token(Token::BeginKeyword) {
            return ParseResult::new(None, Vec::new());
        }

        self.consume_advance(); // BEGIN
        self.skip_whitespace();

        // Parse control type (e.g., "VB.Form" or "VB.MDIForm")
        let control_type = self.parse_control_type_direct();
        self.skip_whitespace();

        // Parse control name
        let control_name = self.parse_control_name_direct();
        self.skip_whitespace_and_newlines();

        // Parse properties, child controls, and property groups
        let mut properties = Properties::new();
        let mut child_controls = Vec::new();
        let mut menus = Vec::new();
        let mut failures = Vec::new();

        while !self.is_at_end() && !self.at_token(Token::EndKeyword) {
            self.skip_whitespace();

            if self.at_token(Token::EndKeyword) {
                break;
            }

            if self.at_token(Token::BeginKeyword) {
                // Nested control (Begin VB.xxx) - use parse_properties_block_to_control for children
                let child_result = self.parse_properties_block_to_control();
                let (child_opt, child_failures) = child_result.unpack();
                failures.extend(child_failures);

                if let Some(child) = child_opt {
                    // Check if it's a menu control
                    if matches!(child.kind(), ControlKind::Menu { .. }) {
                        menus.push(Self::control_to_menu(child));
                    } else {
                        child_controls.push(child);
                    }
                }
            } else if self.is_begin_property() {
                // Parse property group (BeginProperty)
                if let Some(group) = self.parse_property_group_direct() {
                    // Property groups are not used in Form/MDIForm, but we parse them anyway
                    // to avoid errors if they appear
                    groups.push(group);
                }
            } else if self.is_identifier() || self.at_keyword() {
                // Parse property (Key = Value)
                if let Some((key, value)) = self.parse_property_direct() {
                    // Remove surrounding quotes if this is a simple string literal
                    // BUT NOT if it's a resource reference (contains ":digit" pattern)
                    let is_resource_reference = value.contains(':')
                        && value
                            .split(':')
                            .next_back()
                            .is_some_and(|part| part.chars().all(|c| c.is_ascii_digit()));

                    let cleaned_value = if !is_resource_reference
                        && value.starts_with('"')
                        && value.ends_with('"')
                        && value.len() >= 2
                    {
                        &value[1..value.len() - 1]
                    } else {
                        &value
                    };
                    properties.insert(&key, cleaned_value);
                }
            } else {
                // Skip unknown token
                self.consume_advance();
            }
        }

        // Parse END keyword
        if self.at_token(Token::EndKeyword) {
            self.consume_advance();
            self.skip_whitespace_and_newlines();
        }

        // Extract tag and index from properties
        let tag = properties.get("Tag").cloned().unwrap_or_default();
        let index = properties
            .get("Index")
            .and_then(|s| s.parse().ok())
            .unwrap_or(0);

        // Build FormRoot with all components
        if let Ok(form_root) = Self::build_form_root(
            &control_type,
            control_name,
            tag,
            index,
            properties,
            &groups,
            child_controls,
            menus,
        ) {
            ParseResult::new(Some(form_root), failures)
        } else {
            // If invalid top-level control type, return a default Form as fallback
            let default_form = FormRoot::Form(Form {
                name: String::new(),
                tag: String::new(),
                index: 0,
                properties: FormProperties::default(),
                controls: Vec::new(),
                menus: Vec::new(),
            });
            ParseResult::new(Some(default_form), failures)
        }
    }

    /// Parse a complete module/class/form (the top-level structure)
    ///
    /// This function loops through all tokens and identifies what kind of
    /// VB6 construct to parse based on the current token. As more VB6 syntax
    /// is supported, additional branches can be added to this loop.
    fn parse_root(
        mut self,
    ) -> (
        ConcreteSyntaxTree,
        Vec<ErrorDetails<'a>>,
        Vec<RecoveryEvent>,
    ) {
        self.builder.start_node(SyntaxKind::Root.to_raw());

        // Parse VERSION statement (if present)
        if self.at_token(Token::VersionKeyword) {
            self.parse_version_statement();
        }

        // Parse BEGIN ... END block (if present)
        if self.at_token(Token::BeginKeyword) {
            self.parse_properties_block();
        }

        // Parse Attribute statements (if present)
        // These come after the PropertiesBlock in forms/classes
        while self.at_token(Token::AttributeKeyword) {
            self.parse_attribute_statement();
        }

        self.parse_module_body();
        self.builder.finish_node(); // Root

        let root = self.builder.finish();
        (
            ConcreteSyntaxTree::new(root),
            self.failures,
            self.recovery_events,
        )
    }

    #[allow(clippy::too_many_lines)]
    fn parse_module_body(&mut self) {
        while !self.is_at_end() {
            // For a CST, we need to consume ALL tokens, including whitespace and comments
            // We look ahead to determine structure, but still consume everything

            // Check what kind of statement or declaration we're looking at
            match self.current_token() {
                // BEGIN ... END block (for forms/classes with properties)
                // This can appear after Object statements in form files
                Some(Token::BeginKeyword) => {
                    self.parse_properties_block();
                }
                // Object statement: Object = "{UUID}#version#flags"; "filename"
                // Only parse as ObjectStatement if it matches the proper format
                Some(Token::ObjectKeyword) if self.is_object_statement() => {
                    self.parse_object_statement();
                }
                // Attribute statement: Attribute VB_Name = "..."
                Some(Token::AttributeKeyword) => {
                    self.parse_attribute_statement();
                }
                Some(Token::OptionKeyword) => {
                    // Peek ahead to check if this is Option Base, Option Compare, Option On/Off, or Option Private
                    self.parse_one_of_option_statement();
                }
                // DefType statements: DefInt, DefLng, DefStr, etc.
                Some(
                    Token::DefBoolKeyword
                    | Token::DefByteKeyword
                    | Token::DefIntKeyword
                    | Token::DefLngKeyword
                    | Token::DefCurKeyword
                    | Token::DefSngKeyword
                    | Token::DefDblKeyword
                    | Token::DefDecKeyword
                    | Token::DefDateKeyword
                    | Token::DefStrKeyword
                    | Token::DefObjKeyword
                    | Token::DefVarKeyword,
                ) => {
                    self.parse_deftype_statement();
                }
                // Declare statement: Declare Sub/Function Name Lib "..."
                Some(Token::DeclareKeyword) => {
                    self.parse_declare_statement();
                }
                // Event statement: Event Name(...)
                Some(Token::EventKeyword) => {
                    self.parse_event_statement();
                }
                // Implements statement: Implements InterfaceName
                Some(Token::ImplementsKeyword) => {
                    self.parse_implements_statement();
                }
                // Enum statement: Enum Name ... End Enum
                Some(Token::EnumKeyword) => {
                    self.parse_enum_statement();
                }
                // Type statement: Type Name ... End Type
                Some(Token::TypeKeyword) => {
                    self.parse_type_statement();
                }
                // Sub procedure: Sub Name(...)
                Some(Token::SubKeyword) => {
                    self.parse_sub_statement();
                }
                // Function Procedure Syntax:
                //
                // [Public | Private | Friend] [ Static ] Function name [ ( arglist ) ] [ As type ]
                //
                Some(Token::FunctionKeyword) => {
                    self.parse_function_statement();
                }
                // Property Procedure Syntax:
                //
                // [Public | Private | Friend] [ Static ] Property Get|Let|Set name [ ( arglist ) ] [ As type ]
                //
                Some(Token::PropertyKeyword) => {
                    self.parse_property_statement();
                }
                // Variable declarations: Dim/Const
                // For Public/Private/Friend/Static, we need to look ahead to see if it's a
                // function/sub declaration or a variable declaration
                Some(Token::DimKeyword | Token::ConstKeyword) => {
                    self.parse_dim();
                }
                // Public/Private/Friend/Static - could be function/sub/property or declaration
                Some(
                    Token::PrivateKeyword
                    | Token::PublicKeyword
                    | Token::FriendKeyword
                    | Token::StaticKeyword,
                ) => {
                    // Look ahead to see if this is a function/sub/property/enum declaration
                    // Peek at the next 2 keywords to handle cases like "Public Static Function"
                    let next_keywords: Vec<_> = self
                        .peek_next_count_keywords(NonZeroUsize::new(2).unwrap())
                        .collect();

                    match next_keywords.as_slice() {
                        // Direct: Public/Private/Friend Function, Sub, Property, Enum, Type, Declare, or Event
                        [Token::FunctionKeyword, ..] => self.parse_function_statement(), // Function
                        [Token::SubKeyword, ..] => self.parse_sub_statement(),           // Sub
                        [Token::PropertyKeyword, ..] => self.parse_property_statement(), // Property
                        [Token::DeclareKeyword, ..] => self.parse_declare_statement(),   // Declare
                        [Token::EnumKeyword, ..] => self.parse_enum_statement(),         // Enum
                        [Token::TypeKeyword, ..] => self.parse_type_statement(),         // Type
                        [Token::EventKeyword, ..] => self.parse_event_statement(),       // Event
                        [Token::ImplementsKeyword, ..] => self.parse_implements_statement(), // Implements
                        // With Static: Public/Private/Friend Static Function, Sub, or Property
                        [Token::StaticKeyword, Token::FunctionKeyword] => {
                            self.parse_function_statement();
                        }
                        [Token::StaticKeyword, Token::SubKeyword] => {
                            self.parse_sub_statement();
                        }
                        [Token::StaticKeyword, Token::PropertyKeyword] => {
                            self.parse_property_statement();
                        }
                        // Anything else is a declaration
                        _ => self.parse_dim(),
                    }
                }
                // Anything else - check if it's a statement, label, assignment, or unknown
                _ => {
                    // Whitespace, newlines, and comments - consume directly FIRST
                    // This must be checked before is_at_procedure_call to avoid
                    // treating REM comments as procedure calls
                    if matches!(
                        self.current_token(),
                        Some(
                            Token::Whitespace
                                | Token::Newline
                                | Token::EndOfLineComment
                                | Token::RemComment
                        )
                    ) {
                        self.consume_token();
                    } else if self.is_at_compiler_conditional_property_statement() {
                        self.parse_compiler_conditional_property_statement();
                    } else if self.at_compiler_directive_keyword(Token::IfKeyword) {
                        self.parse_compiler_directive();
                    // Try control flow statements
                    } else if self.is_control_flow_keyword() {
                        self.parse_control_flow_statement();
                    // Try built-in statements
                    } else if self.is_library_statement_keyword() {
                        self.parse_library_statement();
                    // Try array statements
                    } else if self.is_variable_declaration_keyword() {
                        self.parse_array_statement();
                    // Try to parse common statements using centralized dispatcher
                    } else if self.is_statement_keyword() {
                        self.parse_statement();
                    // Check if this is a label (identifier followed by colon)
                    } else if self.is_at_label() {
                        self.parse_label_statement();
                    // Check for Let statement (optional assignment keyword)
                    } else if self.at_token(Token::LetKeyword) {
                        self.parse_let_statement();
                    // Check for dot-prefixed member access in With blocks (e.g., .Property = value or .Method arg)
                    } else if self.at_token(Token::PeriodOperator) {
                        // Look ahead to see if this is an assignment or procedure call
                        if self.is_at_with_member_assignment() {
                            self.parse_assignment_statement();
                        } else {
                            self.parse_procedure_call();
                        }
                    // Check if this looks like an assignment statement (identifier = expression)
                    // This must come BEFORE at_keyword() check to handle keywords used as variables
                    } else if self.is_at_assignment() {
                        self.parse_assignment_statement();
                    // Check if this looks like a procedure call (identifier without assignment)
                    } else if self.is_at_procedure_call() {
                        self.parse_procedure_call();
                    // Standalone End statement (terminates program execution)
                    } else if self.is_standalone_end() {
                        self.parse_end_statement();
                    // Colon is a statement separator in VB6, allowing multiple statements on one line.
                    } else if self.at_token(Token::ColonOperator)
                    // Identifiers, keywords, and the octothorpe are all valid statement starters on a line.
                        || self.is_identifier()
                        || self.at_keyword()
                        || self.at_token(Token::Octothorpe)
                    {
                        self.consume_token();
                    } else {
                        self.consume_error_to_newline(vec!["statement".to_string()]);
                    }
                }
            }
        }
    }

    /// Check if the current position is at an Option statement (Base, Compare, or Private).
    fn parse_one_of_option_statement(&mut self) {
        if let Some(Token::BaseKeyword) = self.peek_next_keyword() {
            self.parse_option_base_statement();
        } else if let Some(Token::CompareKeyword) = self.peek_next_keyword() {
            self.parse_option_compare_statement();
        } else if let Some(Token::PrivateKeyword) = self.peek_next_keyword() {
            self.parse_option_private_statement();
        } else {
            self.parse_option_statement();
        }
    }

    /// Check if the current position is at a With block member assignment.
    /// This checks for the pattern: `.PropertyName = value` (used in With blocks).
    /// Returns true if we're at a period followed by an assignment.
    fn is_at_with_member_assignment(&self) -> bool {
        // Must start with a period
        if !self.at_token(Token::PeriodOperator) {
            return false;
        }

        // Look ahead to see if there's an = operator at depth 0 before a newline
        let mut paren_depth: i32 = 0;
        let mut seen_other_operator = false;

        for (_text, token) in self.tokens.iter().skip(self.pos + 1) {
            match token {
                Token::Newline | Token::EndOfLineComment | Token::RemComment => {
                    // Reached end of line without finding assignment
                    return false;
                }
                Token::LeftParenthesis => {
                    paren_depth += 1;
                }
                Token::RightParenthesis => {
                    paren_depth = paren_depth.saturating_sub(1);
                }
                Token::EqualityOperator if paren_depth == 0 => {
                    // Found = operator at depth 0
                    // If we've seen other operators, this is part of an expression, not assignment
                    return !seen_other_operator;
                }
                // Track operators that indicate we're in an expression context
                Token::AndKeyword
                | Token::OrKeyword
                | Token::XorKeyword
                | Token::EqvKeyword
                | Token::ImpKeyword
                | Token::ModKeyword
                | Token::NotKeyword
                | Token::LessThanOperator
                | Token::GreaterThanOperator
                | Token::LessThanOrEqualOperator
                | Token::GreaterThanOrEqualOperator
                | Token::InequalityOperator
                | Token::AdditionOperator
                | Token::SubtractionOperator
                | Token::MultiplicationOperator
                | Token::DivisionOperator
                | Token::BackwardSlashOperator
                | Token::ExponentiationOperator
                | Token::Ampersand
                    if paren_depth == 0 =>
                {
                    seen_other_operator = true;
                }
                // Other tokens are allowed in the lvalue or rvalue
                _ => {}
            }
        }
        false
    }

    /// Check if the current token is a control flow keyword.
    /// Checks both current position and next non-whitespace token.
    fn is_control_flow_keyword(&self) -> bool {
        let token = if self.at_token(Token::Whitespace) {
            self.peek_next_keyword()
        } else {
            self.current_token().copied()
        };

        matches!(
            token,
            Some(
                Token::IfKeyword
                    | Token::SelectKeyword
                    | Token::ForKeyword
                    | Token::DoKeyword
                    | Token::WhileKeyword
                    | Token::GotoKeyword
                    | Token::GoSubKeyword
                    | Token::ReturnKeyword
                    | Token::ResumeKeyword
                    | Token::ExitKeyword
                    | Token::OnKeyword
            )
        )
    }

    /// Dispatch control flow statement parsing to the appropriate parser.
    fn parse_control_flow_statement(&mut self) {
        let token = if self.at_token(Token::Whitespace) {
            self.peek_next_keyword()
        } else {
            self.current_token().copied()
        };

        match token {
            Some(Token::IfKeyword) => {
                self.parse_if_statement();
            }
            Some(Token::SelectKeyword) => {
                self.parse_select_case_statement();
            }
            Some(Token::ForKeyword) => {
                // Peek ahead to see if next keyword is "Each"
                // Need to peek TWO keywords ahead if we're currently at whitespace
                let next_kw = if self.at_token(Token::Whitespace) {
                    // We peeked to find "For", now peek one more for "Each"
                    self.peek_next_count_keywords(NonZeroUsize::new(2).unwrap())
                        .nth(1)
                } else {
                    // We're directly at "For", peek once for "Each"
                    self.peek_next_keyword()
                };

                if let Some(Token::EachKeyword) = next_kw {
                    self.parse_for_each_statement();
                } else {
                    self.parse_for_statement();
                }
            }
            Some(Token::DoKeyword) => {
                self.parse_do_statement();
            }
            Some(Token::WhileKeyword) => {
                self.parse_while_statement();
            }
            Some(Token::GotoKeyword) => {
                self.parse_goto_statement();
            }
            Some(Token::GoSubKeyword) => {
                self.parse_gosub_statement();
            }
            Some(Token::ReturnKeyword) => {
                self.parse_return_statement();
            }
            Some(Token::ResumeKeyword) => {
                self.parse_resume_statement();
            }
            Some(Token::ExitKeyword) => {
                self.parse_exit_statement();
            }
            Some(Token::OnKeyword) => {
                // Look ahead to distinguish between On Error, On GoTo, and On GoSub
                // Need to peek different amounts depending on whether we're at whitespace
                let next_kw = if self.at_token(Token::Whitespace) {
                    // We peeked to find "On", now peek one more for "Error/GoTo/GoSub"
                    self.peek_next_count_keywords(NonZeroUsize::new(2).unwrap())
                        .nth(1)
                } else {
                    // We're directly at "On", peek once for next keyword
                    self.peek_next_keyword()
                };

                if let Some(Token::ErrorKeyword) = next_kw {
                    self.parse_on_error_statement();
                } else {
                    // Need to scan ahead to find GoTo or GoSub keyword
                    // to distinguish between On GoTo and On GoSub
                    let peek_start = if self.at_token(Token::Whitespace) {
                        2
                    } else {
                        1
                    };
                    let keywords: Vec<Token> = self
                        .peek_next_count_keywords(NonZeroUsize::new(20).unwrap())
                        .skip(peek_start)
                        .collect();

                    let has_goto = keywords.contains(&Token::GotoKeyword);
                    let has_gosub = keywords.contains(&Token::GoSubKeyword);

                    if has_goto {
                        self.parse_on_goto_statement();
                    } else if has_gosub {
                        self.parse_on_gosub_statement();
                    } else {
                        // Fallback - treat as On Error if we can't determine
                        self.parse_on_error_statement();
                    }
                }
            }
            _ => {}
        }
    }

    /// Check if the current token is an array statement keyword.
    /// Checks both current position and next non-whitespace token.
    fn is_variable_declaration_keyword(&self) -> bool {
        let token = if self.at_token(Token::Whitespace) {
            self.peek_next_keyword()
        } else {
            self.current_token().copied()
        };

        matches!(token, Some(Token::ReDimKeyword | Token::EraseKeyword))
    }

    /// Check if we're at an Object statement with proper format.
    ///
    /// Object statements in VB6 forms have the format:
    /// `Object = "{GUID}#version#flags"; "filename"`
    /// or
    /// `Object = *\G{GUID}#version#flags; "filename"`
    ///
    /// This checks if the pattern matches before committing to parse as `ObjectStatement`.
    #[allow(clippy::needless_continue)] // continue on whitespace is needed but clippy is incorrectly catching here.
    fn is_object_statement(&self) -> bool {
        // Must start with Object keyword
        if !self.at_token(Token::ObjectKeyword) {
            return false;
        }

        // Look ahead to verify it matches Object statement pattern
        // Skip whitespace, should find =, then whitespace, then string or *\G pattern
        let mut found_equals = false;
        for (_text, token) in self.tokens.iter().skip(self.pos + 1) {
            match token {
                // TODO: Change this parsing to better handle leading whitespace on object statements.
                Token::Whitespace => continue,
                Token::EqualityOperator if !found_equals => {
                    found_equals = true;
                }
                // After =, we expect either a quoted string starting with { or * for type library refs
                Token::StringLiteral | Token::MultiplicationOperator if found_equals => {
                    // Valid Object statement - string literal after =
                    // or
                    // Could be *\G{ pattern for type libraries
                    return true;
                }
                // If we hit anything else after =, not an Object statement
                _ if found_equals => return false,
                // If we hit a newline before =, not an Object statement
                Token::Newline | Token::EndOfLineComment | Token::RemComment => {
                    return false;
                }
                _ => return false,
            }
        }
        false
    }

    /// Dispatch array statement parsing to the appropriate parser.
    fn parse_array_statement(&mut self) {
        let token = if self.at_token(Token::Whitespace) {
            self.peek_next_keyword()
        } else {
            self.current_token().copied()
        };

        match token {
            Some(Token::ReDimKeyword) => {
                self.parse_redim_statement();
            }
            Some(Token::EraseKeyword) => {
                self.parse_erase_statement();
            }
            _ => {}
        }
    }

    /// Parse a statement list, consuming tokens until a termination condition is met.
    ///
    /// This is an ITERATIVE implementation using an explicit frame stack to prevent stack overflow
    /// on deeply nested code structures. It handles all statement list parsing contexts:
    /// - Sub/Function bodies
    /// - If/ElseIf/Else blocks  
    /// - For/While/Do loop bodies
    /// - Select Case blocks
    /// - With blocks
    ///
    /// # Arguments
    /// * `stop_conditions` - A closure that returns true when the block should stop parsing
    pub(crate) fn parse_statement_list<F>(&mut self, stop_conditions: F)
    where
        F: Fn(&Parser) -> bool,
    {
        let mut frame_stack: Vec<ControlFlowFrame> = Vec::new();

        // Push initial statement list frame
        frame_stack.push(ControlFlowFrame::StatementList {
            depth: 0,
            context: StatementListContext::TopLevel,
            started: false,
        });

        // Note: start_node will be called when this frame is first processed

        while self.statement_stack_within_limit(&frame_stack) {
            let Some(frame_kind) = Self::current_frame_kind(&frame_stack) else {
                break;
            };

            match frame_kind {
                ControlFlowFrameType::StatementList => {
                    self.handle_statement_list_frame(&mut frame_stack, &stop_conditions);
                }
                _ => self.handle_non_statement_list_frame(frame_kind, &mut frame_stack),
            }
        }
    }

    fn statement_stack_within_limit(&mut self, frame_stack: &[ControlFlowFrame]) -> bool {
        if frame_stack.len() <= MAX_STATEMENT_DEPTH {
            return true;
        }

        self.report_error(ErrorKind::Module(ModuleError::NestingTooDeep {
            depth: frame_stack.len(),
            max_depth: MAX_STATEMENT_DEPTH,
        }));
        false
    }

    fn current_frame_kind(frame_stack: &[ControlFlowFrame]) -> Option<ControlFlowFrameType> {
        frame_stack.last().map(ControlFlowFrame::frame_type)
    }

    fn handle_statement_list_frame<F>(
        &mut self,
        frame_stack: &mut Vec<ControlFlowFrame>,
        stop_conditions: &F,
    ) where
        F: Fn(&Parser) -> bool,
    {
        let Some((current_depth, context, started)) = Self::statement_list_frame_state(frame_stack)
        else {
            return;
        };

        if !started {
            self.builder.start_node(SyntaxKind::StatementList.to_raw());
            Self::mark_statement_list_started(frame_stack);
        }

        if self.should_stop_statement_list(context, stop_conditions) {
            frame_stack.pop();
            self.builder.finish_node(); // StatementList
            return;
        }

        if self.try_handle_statement_list_control_flow(frame_stack, current_depth) {
            return;
        }

        if self.try_parse_statement_list_keyword_dispatch() {
            return;
        }

        self.parse_statement_list_fallback_item();
    }

    fn statement_list_frame_state(
        frame_stack: &[ControlFlowFrame],
    ) -> Option<(usize, StatementListContext, bool)> {
        if let Some(ControlFlowFrame::StatementList {
            depth,
            context,
            started,
        }) = frame_stack.last()
        {
            Some((*depth, *context, *started))
        } else {
            None
        }
    }

    fn mark_statement_list_started(frame_stack: &mut [ControlFlowFrame]) {
        if let Some(ControlFlowFrame::StatementList { started, .. }) = frame_stack.last_mut() {
            *started = true;
        }
    }

    fn should_stop_statement_list<F>(
        &self,
        context: StatementListContext,
        stop_conditions: &F,
    ) -> bool
    where
        F: Fn(&Parser) -> bool,
    {
        match context {
            StatementListContext::TopLevel => {
                stop_conditions(self) || self.at_procedure_block_end() || self.is_at_end()
            }
            StatementListContext::IfThenBody | StatementListContext::ElseIfBody => {
                self.at_token(Token::ElseIfKeyword)
                    || self.at_compiler_directive_keyword(Token::ElseIfKeyword)
                    || self.at_token(Token::ElseKeyword)
                    || self.at_compiler_directive_keyword(Token::ElseKeyword)
                    || self.at_if_block_end()
                    || self.at_procedure_block_end()
                    || self.is_at_end()
            }
            StatementListContext::ElseBody => {
                self.at_token(Token::CaseKeyword)
                    || (self.at_token(Token::EndKeyword)
                        && self.peek_next_keyword() == Some(Token::SelectKeyword))
                    || self.at_if_block_end()
                    || self.at_procedure_block_end()
                    || self.is_at_end()
            }
            StatementListContext::ForBody => self.at_token(Token::NextKeyword) || self.is_at_end(),
            StatementListContext::SelectCaseBody => {
                self.at_token(Token::CaseKeyword)
                    || (self.at_token(Token::EndKeyword)
                        && self.peek_next_keyword() == Some(Token::SelectKeyword))
                    || self.is_at_end()
            }
            StatementListContext::WhileBody => {
                self.at_token(Token::WendKeyword) || self.is_at_end()
            }
            StatementListContext::DoBody => self.at_token(Token::LoopKeyword) || self.is_at_end(),
            StatementListContext::WithBody => {
                (self.at_token(Token::EndKeyword)
                    && self.peek_next_keyword() == Some(Token::WithKeyword))
                    || self.is_at_end()
            }
        }
    }

    fn at_if_block_end(&self) -> bool {
        (self.at_token(Token::EndKeyword) && self.peek_next_keyword() == Some(Token::IfKeyword))
            || self.at_compiler_end_if_directive()
    }

    fn at_procedure_block_end(&self) -> bool {
        self.at_token(Token::EndKeyword)
            && matches!(
                self.peek_next_keyword(),
                Some(Token::SubKeyword | Token::FunctionKeyword | Token::PropertyKeyword)
            )
    }

    fn at_compiler_directive_keyword(&self, keyword: Token) -> bool {
        if !self.at_token(Token::Octothorpe) {
            return false;
        }

        let mut index = self.pos + 1;

        while let Some((_, token)) = self.tokens.get(index) {
            if *token == Token::Whitespace {
                index += 1;
                continue;
            }

            return *token == keyword;
        }

        false
    }

    fn at_compiler_end_if_directive(&self) -> bool {
        if !self.at_token(Token::Octothorpe) {
            return false;
        }

        let mut index = self.pos + 1;

        while let Some((_, token)) = self.tokens.get(index) {
            if *token == Token::Whitespace {
                index += 1;
                continue;
            }

            if *token != Token::EndKeyword {
                return false;
            }

            index += 1;
            break;
        }

        while let Some((_, token)) = self.tokens.get(index) {
            if *token == Token::Whitespace {
                index += 1;
                continue;
            }

            return *token == Token::IfKeyword;
        }

        false
    }

    fn consume_compiler_directive_prefix(&mut self) {
        if self.at_token(Token::Octothorpe) {
            self.consume_token();
            self.consume_whitespace();
        }
    }

    fn try_handle_statement_list_control_flow(
        &mut self,
        frame_stack: &mut Vec<ControlFlowFrame>,
        current_depth: usize,
    ) -> bool {
        if !self.is_control_flow_keyword() {
            return false;
        }

        let keyword = if self.at_token(Token::Whitespace) {
            self.peek_next_keyword()
        } else {
            self.current_token().copied()
        };

        match keyword {
            Some(Token::IfKeyword) => {
                frame_stack.push(ControlFlowFrame::IfStatement {
                    phase: IfPhase::Start,
                    depth: current_depth + 1,
                });
            }
            Some(Token::ForKeyword) => {
                let is_for_each = if self.at_token(Token::Whitespace) {
                    self.peek_next_count_keywords(NonZeroUsize::new(2).unwrap())
                        .nth(1)
                        == Some(Token::EachKeyword)
                } else {
                    self.peek_next_keyword() == Some(Token::EachKeyword)
                };

                frame_stack.push(ControlFlowFrame::ForStatement {
                    phase: ForPhase::Start,
                    is_for_each,
                    depth: current_depth + 1,
                });
            }
            Some(Token::SelectKeyword) => {
                frame_stack.push(ControlFlowFrame::SelectCase {
                    phase: SelectPhase::Start,
                    depth: current_depth + 1,
                });
            }
            Some(Token::WhileKeyword) => {
                frame_stack.push(ControlFlowFrame::WhileStatement {
                    phase: WhilePhase::Start,
                    depth: current_depth + 1,
                });
            }
            Some(Token::DoKeyword) => {
                frame_stack.push(ControlFlowFrame::DoStatement {
                    phase: DoPhase::Start,
                    depth: current_depth + 1,
                });
            }
            Some(Token::WithKeyword) => {
                frame_stack.push(ControlFlowFrame::WithStatement {
                    phase: WithPhase::Start,
                    depth: current_depth + 1,
                });
            }
            _ => {
                // Other control flow statements that don't nest deeply.
                self.parse_control_flow_statement();
            }
        }

        true
    }

    fn try_parse_statement_list_keyword_dispatch(&mut self) -> bool {
        if self.at_token(Token::EventKeyword) {
            self.parse_event_statement();
            return true;
        }

        if self.is_library_statement_keyword() {
            self.parse_library_statement();
            return true;
        }

        if self.is_variable_declaration_keyword() {
            self.parse_array_statement();
            return true;
        }

        if self.is_statement_keyword() {
            self.parse_statement();
            return true;
        }

        false
    }

    fn parse_statement_list_fallback_item(&mut self) {
        match self.current_token() {
            // Whitespace, newlines, and comments - consume directly FIRST.
            Some(
                Token::Whitespace | Token::Newline | Token::EndOfLineComment | Token::RemComment,
            ) => {
                self.consume_token();
            }
            // Declare statement: Declare Sub/Function Name Lib "..."
            Some(Token::DeclareKeyword) => {
                self.parse_declare_statement();
            }
            // Variable declarations: Dim/Const.
            Some(Token::DimKeyword | Token::ConstKeyword) => {
                self.parse_dim();
            }
            // Scoped declarations may be members (Sub/Function/Property/etc.)
            // or plain variable declarations.
            Some(
                Token::PrivateKeyword
                | Token::PublicKeyword
                | Token::FriendKeyword
                | Token::StaticKeyword,
            ) => {
                let next_keywords: Vec<_> = self
                    .peek_next_count_keywords(NonZeroUsize::new(2).unwrap())
                    .collect();

                match next_keywords.as_slice() {
                    [Token::FunctionKeyword, ..] => self.parse_function_statement(),
                    [Token::SubKeyword, ..] => self.parse_sub_statement(),
                    [Token::PropertyKeyword, ..] => self.parse_property_statement(),
                    [Token::DeclareKeyword, ..] => self.parse_declare_statement(),
                    [Token::EnumKeyword, ..] => self.parse_enum_statement(),
                    [Token::TypeKeyword, ..] => self.parse_type_statement(),
                    [Token::EventKeyword, ..] => self.parse_event_statement(),
                    [Token::ImplementsKeyword, ..] => self.parse_implements_statement(),
                    [Token::StaticKeyword, Token::FunctionKeyword] => {
                        self.parse_function_statement();
                    }
                    [Token::StaticKeyword, Token::SubKeyword] => {
                        self.parse_sub_statement();
                    }
                    [Token::StaticKeyword, Token::PropertyKeyword] => {
                        self.parse_property_statement();
                    }
                    _ => self.parse_dim(),
                }
            }
            _ => self.parse_statement_list_fallback_non_keyword(),
        }
    }

    fn parse_statement_list_fallback_non_keyword(&mut self) {
        if self.is_at_label() {
            self.parse_label_statement();
        } else if self.at_token(Token::LetKeyword)
            || (self.at_token(Token::Whitespace)
                && self.peek_next_keyword() == Some(Token::LetKeyword))
        {
            self.parse_let_statement();
        } else if self.at_token(Token::PeriodOperator) {
            if self.is_at_with_member_assignment() {
                self.parse_assignment_statement();
            } else {
                self.parse_procedure_call();
            }
        } else if self.is_at_assignment() {
            self.parse_assignment_statement();
        } else if self.is_at_procedure_call() {
            self.parse_procedure_call();
        } else if self.is_standalone_end() {
            self.parse_end_statement();
        } else if self.is_at_compiler_conditional_property_statement() {
            self.parse_compiler_conditional_property_statement();
        } else if self.at_compiler_directive_keyword(Token::IfKeyword) {
            self.parse_compiler_directive();
        } else if self.at_token(Token::Octothorpe) {
            self.consume_token();
        } else if self.at_token(Token::ColonOperator) {
            // Colon is a statement separator in VB6, allowing multiple statements on one line.
            // e.g. `a = 1 : b = 2 : c = 3`
            // Consume the colon token and continue parsing the next statement.
            self.consume_token();
        } else {
            self.consume_error_to_newline(vec!["statement".to_string()]);
        }
    }

    fn handle_non_statement_list_frame(
        &mut self,
        frame_kind: ControlFlowFrameType,
        frame_stack: &mut Vec<ControlFlowFrame>,
    ) {
        let should_continue = match frame_kind {
            ControlFlowFrameType::IfStatement => self.handle_if_statement_frame(frame_stack),
            ControlFlowFrameType::ForStatement => self.handle_for_statement_frame(frame_stack),
            ControlFlowFrameType::SelectCase => self.handle_select_case_frame(frame_stack),
            ControlFlowFrameType::WhileStatement => self.handle_while_statement_frame(frame_stack),
            ControlFlowFrameType::DoStatement => self.handle_do_statement_frame(frame_stack),
            ControlFlowFrameType::WithStatement => self.handle_with_statement_frame(frame_stack),
            ControlFlowFrameType::StatementList => return,
        };

        if !should_continue {
            frame_stack.pop();
        }
    }

    // ==================== Control Flow State Machine Handlers ====================

    /// Handle If statement state transitions.
    /// Returns true if processing should continue, false if frame should be popped.
    fn handle_if_statement_frame(&mut self, frame_stack: &mut Vec<ControlFlowFrame>) -> bool {
        let Some(current_phase) = Self::current_if_phase(frame_stack) else {
            return false;
        };

        match current_phase {
            IfPhase::Start => self.handle_if_phase_start(frame_stack),
            IfPhase::ThenBody => Self::handle_if_phase_then_body(frame_stack),
            IfPhase::CheckElseIf => self.handle_if_phase_check_elseif(frame_stack),
            IfPhase::ElseIfBody => self.handle_if_phase_elseif_body(frame_stack),
            IfPhase::CheckElse => self.handle_if_phase_check_else(frame_stack),
            IfPhase::ElseBody => self.handle_if_phase_else_body(frame_stack),
            IfPhase::Finish => self.handle_if_phase_finish(),
        }
    }

    fn current_if_phase(frame_stack: &[ControlFlowFrame]) -> Option<IfPhase> {
        if let Some(ControlFlowFrame::IfStatement { phase, .. }) = frame_stack.last() {
            Some(*phase)
        } else {
            None
        }
    }

    fn set_if_phase(frame_stack: &mut [ControlFlowFrame], new_phase: IfPhase) {
        if let Some(ControlFlowFrame::IfStatement { phase, .. }) = frame_stack.last_mut() {
            *phase = new_phase;
        }
    }

    fn if_frame_depth(frame_stack: &[ControlFlowFrame]) -> Option<usize> {
        if let Some(ControlFlowFrame::IfStatement { depth, .. }) = frame_stack.last() {
            Some(*depth)
        } else {
            None
        }
    }

    fn push_if_body_statement_list(
        frame_stack: &mut Vec<ControlFlowFrame>,
        context: StatementListContext,
    ) {
        if let Some(current_depth) = Self::if_frame_depth(frame_stack) {
            frame_stack.push(ControlFlowFrame::StatementList {
                depth: current_depth,
                context,
                started: false,
            });
        }
    }

    fn handle_if_phase_start(&mut self, frame_stack: &mut Vec<ControlFlowFrame>) -> bool {
        self.parsing_header = false;
        self.builder.start_node(SyntaxKind::IfStatement.to_raw());
        self.consume_whitespace();
        self.consume_compiler_directive_prefix();
        self.consume_token(); // If
        self.consume_whitespace();
        self.parse_expression();
        self.consume_whitespace();

        if self.at_token(Token::ThenKeyword) {
            self.consume_token();
        }
        self.consume_whitespace();

        // Skip trailing comment on the Then line — a comment after Then
        // does not constitute a single-line If body.
        while self.at_token(Token::EndOfLineComment) || self.at_token(Token::RemComment) {
            self.consume_token();
            self.consume_whitespace();
        }

        let is_single_line = !self.at_token(Token::Newline) && !self.is_at_end();

        if is_single_line {
            self.handle_single_line_if_phase_start();
            return false;
        }

        self.transition_if_to_then_body(frame_stack);
        true
    }

    fn handle_single_line_if_phase_start(&mut self) {
        self.parse_single_line_if_body_segment(true);

        // Else must be on the same physical line for single-line If.
        if !self.at_token(Token::Newline) && self.at_token(Token::ElseKeyword) {
            self.consume_token(); // Else
            self.consume_whitespace();
            self.parse_single_line_if_body_segment(false);
        }

        if self.at_token(Token::Newline) {
            self.consume_token();
        }

        self.builder.finish_node(); // IfStatement
    }

    fn parse_single_line_if_body_segment(&mut self, stop_at_else: bool) {
        loop {
            if self.is_at_end() || self.at_token(Token::Newline) {
                break;
            }

            if stop_at_else && self.at_token(Token::ElseKeyword) {
                break;
            }

            let pos_before = self.pos;
            let parsed_statement = self.parse_single_line_if_statement_item();

            // If a parsed statement consumed a newline, the single-line segment is done.
            if parsed_statement && self.consumed_newline_in_range(pos_before, self.pos) {
                break;
            }
        }
    }

    fn parse_single_line_if_statement_item(&mut self) -> bool {
        if self.is_control_flow_keyword() {
            self.parse_control_flow_statement();
            return true;
        }
        if self.is_library_statement_keyword() {
            self.parse_library_statement();
            return true;
        }
        if self.is_variable_declaration_keyword() {
            self.parse_array_statement();
            return true;
        }
        if self.is_statement_keyword() {
            self.parse_statement();
            return true;
        }

        match self.current_token() {
            Some(
                Token::Whitespace
                | Token::EndOfLineComment
                | Token::RemComment
                | Token::ColonOperator,
            ) => {
                self.consume_token();
                false
            }
            _ => {
                if self.at_token(Token::LetKeyword) {
                    self.parse_let_statement();
                    true
                } else if self.at_token(Token::PeriodOperator) {
                    if self.is_at_with_member_assignment() {
                        self.parse_assignment_statement();
                    } else {
                        self.parse_procedure_call();
                    }
                    true
                } else if self.is_at_assignment() {
                    self.parse_assignment_statement();
                    true
                } else if self.is_at_procedure_call() {
                    self.parse_procedure_call();
                    true
                } else {
                    self.consume_token();
                    false
                }
            }
        }
    }

    fn consumed_newline_in_range(&self, start_pos: usize, end_pos: usize) -> bool {
        start_pos < end_pos
            && self.tokens[start_pos..end_pos]
                .iter()
                .any(|(_, t)| *t == Token::Newline)
    }

    fn transition_if_to_then_body(&mut self, frame_stack: &mut Vec<ControlFlowFrame>) {
        if self.at_token(Token::Newline) {
            self.consume_token();
        }

        Self::set_if_phase(frame_stack, IfPhase::ThenBody);
        Self::push_if_body_statement_list(frame_stack, StatementListContext::IfThenBody);
    }

    fn handle_if_phase_then_body(frame_stack: &mut [ControlFlowFrame]) -> bool {
        Self::set_if_phase(frame_stack, IfPhase::CheckElseIf);
        true
    }

    fn handle_if_phase_check_elseif(&mut self, frame_stack: &mut Vec<ControlFlowFrame>) -> bool {
        if self.at_compiler_directive_keyword(Token::ElseIfKeyword) {
            self.consume_compiler_directive_prefix();
        }

        if self.at_token(Token::ElseIfKeyword) {
            self.builder.start_node(SyntaxKind::ElseIfClause.to_raw());
            self.consume_token(); // ElseIf
            self.consume_whitespace();
            self.parse_expression();
            self.consume_whitespace();

            if self.at_token(Token::ThenKeyword) {
                self.consume_token();
            }
            self.consume_whitespace();

            if self.at_token(Token::Newline) {
                self.consume_token();
            }

            Self::set_if_phase(frame_stack, IfPhase::ElseIfBody);
            Self::push_if_body_statement_list(frame_stack, StatementListContext::ElseIfBody);
        } else {
            Self::set_if_phase(frame_stack, IfPhase::CheckElse);
        }

        true
    }

    fn handle_if_phase_elseif_body(&mut self, frame_stack: &mut [ControlFlowFrame]) -> bool {
        self.builder.finish_node(); // ElseIfClause
        Self::set_if_phase(frame_stack, IfPhase::CheckElseIf);
        true
    }

    fn handle_if_phase_check_else(&mut self, frame_stack: &mut Vec<ControlFlowFrame>) -> bool {
        if self.at_compiler_directive_keyword(Token::ElseKeyword) {
            self.consume_compiler_directive_prefix();
        }

        if self.at_token(Token::ElseKeyword) {
            self.builder.start_node(SyntaxKind::ElseClause.to_raw());
            self.consume_token(); // Else
            self.consume_whitespace();

            if self.at_token(Token::Newline) {
                self.consume_token();
            }

            Self::set_if_phase(frame_stack, IfPhase::ElseBody);
            Self::push_if_body_statement_list(frame_stack, StatementListContext::ElseBody);
        } else {
            Self::set_if_phase(frame_stack, IfPhase::Finish);
        }

        true
    }

    fn handle_if_phase_else_body(&mut self, frame_stack: &mut [ControlFlowFrame]) -> bool {
        self.builder.finish_node(); // ElseClause
        Self::set_if_phase(frame_stack, IfPhase::Finish);
        true
    }

    fn handle_if_phase_finish(&mut self) -> bool {
        if self.at_compiler_end_if_directive() {
            self.consume_compiler_directive_prefix();
        }

        if self.at_token(Token::EndKeyword) {
            self.consume_token();
            self.consume_whitespace();
            if self.at_token(Token::IfKeyword) {
                self.consume_token();
            }
            self.consume_until_after(Token::Newline);
        }

        self.builder.finish_node(); // IfStatement
        false
    }

    /// Handle For statement state transitions.
    fn handle_for_statement_frame(&mut self, frame_stack: &mut Vec<ControlFlowFrame>) -> bool {
        // Get current phase and is_for_each flag
        let (phase, is_for_each, depth) = if let Some(ControlFlowFrame::ForStatement {
            phase,
            is_for_each,
            depth,
            ..
        }) = frame_stack.last()
        {
            (*phase, *is_for_each, *depth)
        } else {
            return false; // Invalid state, pop frame
        };

        match phase {
            ForPhase::Start => {
                // Start the appropriate node type
                if is_for_each {
                    self.builder
                        .start_node(SyntaxKind::ForEachStatement.to_raw());
                } else {
                    self.builder.start_node(SyntaxKind::ForStatement.to_raw());
                }

                self.consume_whitespace();
                self.consume_token(); // For

                if is_for_each {
                    // For Each element In collection
                    self.consume_whitespace();
                    self.consume_token(); // Each
                    self.consume_until_after(Token::Newline);
                } else {
                    // For counter = start To end [Step step]

                    // Parse counter variable (lvalue)
                    self.parse_lvalue();
                    self.consume_whitespace();

                    // Consume "="
                    if self.at_token(Token::EqualityOperator) {
                        self.consume_token();
                    }
                    self.consume_whitespace();

                    // Parse start value
                    self.parse_expression();
                    self.consume_whitespace();

                    // Consume "To" keyword if present
                    if self.at_token(Token::ToKeyword) {
                        self.consume_token();
                        self.consume_whitespace();

                        // Parse end value
                        self.parse_expression();
                        self.consume_whitespace();

                        // Consume "Step" keyword if present
                        if self.at_token(Token::StepKeyword) {
                            self.consume_token();
                            self.consume_whitespace();

                            // Parse step value
                            self.parse_expression();
                        }
                    }

                    if self.has_inline_next_before_newline() {
                        self.parse_single_line_for_body_until_next();
                        self.builder.finish_node();
                        return false;
                    }

                    // Consume newline after For line
                    self.consume_until_after(Token::Newline);
                }

                // Update phase to Body
                if let Some(ControlFlowFrame::ForStatement { phase, .. }) = frame_stack.last_mut() {
                    *phase = ForPhase::Body;
                }
                true // Continue processing
            }

            ForPhase::Body => {
                // Update phase to Finish before pushing nested frame
                if let Some(ControlFlowFrame::ForStatement { phase, .. }) = frame_stack.last_mut() {
                    *phase = ForPhase::Finish;
                }

                // Push statement list frame for loop body (stops at Next)
                frame_stack.push(ControlFlowFrame::StatementList {
                    depth,
                    context: StatementListContext::ForBody,
                    started: false,
                });

                true // Continue processing (will process the statement list)
            }

            ForPhase::Finish => {
                // Parse Next keyword
                if self.at_token(Token::NextKeyword) {
                    self.consume_token();
                    self.consume_until_after(Token::Newline);
                }

                // Finish the For/ForEach node
                self.builder.finish_node();
                false // Pop this frame (For statement complete)
            }
        }
    }

    /// Handle Select Case statement state transitions.
    fn handle_select_case_frame(&mut self, frame_stack: &mut Vec<ControlFlowFrame>) -> bool {
        // Get current phase and depth
        let (phase, depth) =
            if let Some(ControlFlowFrame::SelectCase { phase, depth, .. }) = frame_stack.last() {
                (*phase, *depth)
            } else {
                return false; // Invalid state, pop frame
            };

        match phase {
            SelectPhase::Start => {
                // Start Select Case statement
                self.builder
                    .start_node(SyntaxKind::SelectCaseStatement.to_raw());
                self.consume_whitespace();
                self.consume_token(); // Select
                self.consume_whitespace();

                if self.at_token(Token::CaseKeyword) {
                    self.consume_token();
                }

                self.consume_whitespace();
                self.parse_expression();
                self.consume_until_after(Token::Newline);

                // Update phase to CaseClause
                if let Some(ControlFlowFrame::SelectCase { phase, .. }) = frame_stack.last_mut() {
                    *phase = SelectPhase::CaseClause;
                }
                true // Continue processing
            }

            SelectPhase::CaseClause => self.parse_case_clause(frame_stack, depth),

            SelectPhase::CaseBody => {
                // Case body statement list just finished, close the CaseClause node
                self.builder.finish_node(); // CaseClause

                // Update phase to CheckNextCase
                if let Some(ControlFlowFrame::SelectCase { phase, .. }) = frame_stack.last_mut() {
                    *phase = SelectPhase::CheckNextCase;
                }
                true
            }

            SelectPhase::CheckNextCase => {
                // Consume whitespace/newlines between case clauses
                while self.at_token(Token::Whitespace) || self.at_token(Token::Newline) {
                    self.consume_token();
                }

                // Check if there are more Case clauses
                if self.at_token(Token::CaseKeyword) {
                    // Go back to CaseClause phase
                    if let Some(ControlFlowFrame::SelectCase { phase, .. }) = frame_stack.last_mut()
                    {
                        *phase = SelectPhase::CaseClause;
                    }
                    true
                } else if self.at_token(Token::EndKeyword)
                    && self.peek_next_keyword() == Some(Token::SelectKeyword)
                {
                    // End Select found, move to Finish
                    if let Some(ControlFlowFrame::SelectCase { phase, .. }) = frame_stack.last_mut()
                    {
                        *phase = SelectPhase::Finish;
                    }
                    true
                } else if self.is_at_end() {
                    // Reached end of file without finding End Select - move to Finish anyway
                    if let Some(ControlFlowFrame::SelectCase { phase, .. }) = frame_stack.last_mut()
                    {
                        *phase = SelectPhase::Finish;
                    }
                    true
                } else {
                    // Unknown token, consume and stay in CheckNextCase
                    self.consume_token();
                    true
                }
            }

            SelectPhase::CaseElseBody => {
                // Case Else body statement list just finished, close the CaseElseClause node
                self.builder.finish_node(); // CaseElseClause

                // Move to Finish (Case Else is always the last clause)
                if let Some(ControlFlowFrame::SelectCase { phase, .. }) = frame_stack.last_mut() {
                    *phase = SelectPhase::Finish;
                }
                true
            }

            SelectPhase::Finish => {
                // Parse End Select
                if self.at_token(Token::EndKeyword) {
                    self.consume_token();
                    self.consume_whitespace();
                    if self.at_token(Token::SelectKeyword) {
                        self.consume_token();
                    }
                    self.consume_until_after(Token::Newline);
                }

                // Finish the SelectCaseStatement node
                self.builder.finish_node();
                false // Pop this frame (Select Case complete)
            }
        }
    }

    fn parse_case_clause(&mut self, frame_stack: &mut Vec<ControlFlowFrame>, depth: usize) -> bool {
        // Consume any whitespace/newlines/comments before checking for Case
        while self.at_token(Token::Whitespace)
            || self.at_token(Token::Newline)
            || self.at_token(Token::EndOfLineComment)
            || self.at_token(Token::RemComment)
        {
            self.consume_token();
        }

        // Check if we're at a Case keyword
        if self.at_token(Token::CaseKeyword) {
            // Check for Case Else
            let is_case_else = self.peek_next_keyword() == Some(Token::ElseKeyword);

            if is_case_else {
                // Parse Case Else
                self.builder.start_node(SyntaxKind::CaseElseClause.to_raw());
                self.consume_token(); // Case
                self.consume_whitespace();
                self.consume_token(); // Else
                self.consume_until_after(Token::Newline);

                // Update phase to CaseElseBody before pushing nested frame
                if let Some(ControlFlowFrame::SelectCase { phase, .. }) = frame_stack.last_mut() {
                    *phase = SelectPhase::CaseElseBody;
                }

                // Push statement list frame for Case Else body
                frame_stack.push(ControlFlowFrame::StatementList {
                    depth,
                    context: StatementListContext::SelectCaseBody,
                    started: false,
                });
                true // Continue processing
            } else {
                // Parse regular Case
                self.builder.start_node(SyntaxKind::CaseClause.to_raw());
                self.consume_token(); // Case
                self.consume_until_after(Token::Newline);

                // Update phase to CaseBody before pushing nested frame
                if let Some(ControlFlowFrame::SelectCase { phase, .. }) = frame_stack.last_mut() {
                    *phase = SelectPhase::CaseBody;
                }

                // Push statement list frame for Case body
                frame_stack.push(ControlFlowFrame::StatementList {
                    depth,
                    context: StatementListContext::SelectCaseBody,
                    started: false,
                });
                true // Continue processing
            }
        } else {
            // No more Case clauses, move to Finish
            if let Some(ControlFlowFrame::SelectCase { phase, .. }) = frame_stack.last_mut() {
                *phase = SelectPhase::Finish;
            }
            true
        }
    }

    /// Handle While statement state transitions.
    fn handle_while_statement_frame(&mut self, frame_stack: &mut Vec<ControlFlowFrame>) -> bool {
        // Get current phase and depth
        let (phase, depth) =
            if let Some(ControlFlowFrame::WhileStatement { phase, depth, .. }) = frame_stack.last()
            {
                (*phase, *depth)
            } else {
                return false; // Invalid state, pop frame
            };

        match phase {
            WhilePhase::Start => {
                // Start While statement
                self.builder.start_node(SyntaxKind::WhileStatement.to_raw());
                self.consume_whitespace();
                self.consume_token(); // While
                self.consume_whitespace();
                self.parse_expression();

                // Consume newline after While line
                if self.at_token(Token::Newline) {
                    self.consume_token();
                }

                // Update phase to Body before pushing nested frame
                if let Some(ControlFlowFrame::WhileStatement { phase, .. }) = frame_stack.last_mut()
                {
                    *phase = WhilePhase::Body;
                }

                // Push statement list frame for loop body
                frame_stack.push(ControlFlowFrame::StatementList {
                    depth,
                    context: StatementListContext::WhileBody,
                    started: false,
                });

                true // Continue processing
            }

            WhilePhase::Body => {
                // Loop body statement list just finished
                // Update phase to Finish
                if let Some(ControlFlowFrame::WhileStatement { phase, .. }) = frame_stack.last_mut()
                {
                    *phase = WhilePhase::Finish;
                }
                true
            }

            WhilePhase::Finish => {
                // Parse Wend keyword
                if self.at_token(Token::WendKeyword) {
                    self.consume_token();

                    if self.at_token(Token::Newline) {
                        self.consume_token();
                    }
                }

                // Finish the WhileStatement node
                self.builder.finish_node();
                false // Pop this frame (While statement complete)
            }
        }
    }

    /// Handle Do statement state transitions.
    fn handle_do_statement_frame(&mut self, frame_stack: &mut Vec<ControlFlowFrame>) -> bool {
        // Get current phase and depth
        let (phase, depth) =
            if let Some(ControlFlowFrame::DoStatement { phase, depth, .. }) = frame_stack.last() {
                (*phase, *depth)
            } else {
                return false; // Invalid state, pop frame
            };

        match phase {
            DoPhase::Start => {
                // Start Do statement
                self.builder.start_node(SyntaxKind::DoStatement.to_raw());
                self.consume_whitespace();
                self.consume_token(); // Do
                self.consume_whitespace();

                // Check for While/Until after Do (pre-test condition)
                if self.at_token(Token::WhileKeyword) || self.at_token(Token::UntilKeyword) {
                    self.consume_token();
                    self.consume_whitespace();
                    self.parse_expression();
                }

                if self.at_token(Token::Newline) {
                    self.consume_token();
                }

                // Update phase to Body before pushing nested frame
                if let Some(ControlFlowFrame::DoStatement { phase, .. }) = frame_stack.last_mut() {
                    *phase = DoPhase::Body;
                }

                // Push statement list frame for loop body
                frame_stack.push(ControlFlowFrame::StatementList {
                    depth,
                    context: StatementListContext::DoBody,
                    started: false,
                });

                true // Continue processing
            }

            DoPhase::Body => {
                // Loop body statement list just finished
                // Update phase to Finish
                if let Some(ControlFlowFrame::DoStatement { phase, .. }) = frame_stack.last_mut() {
                    *phase = DoPhase::Finish;
                }
                true
            }

            DoPhase::Finish => {
                // Parse Loop keyword
                if self.at_token(Token::LoopKeyword) {
                    self.consume_token();
                    self.consume_whitespace();

                    // Check for While/Until after Loop (post-test condition)
                    if self.at_token(Token::WhileKeyword) || self.at_token(Token::UntilKeyword) {
                        self.consume_token();
                        self.consume_whitespace();
                        self.parse_expression();
                    }

                    if self.at_token(Token::Newline) {
                        self.consume_token();
                    }
                }

                // Finish the DoStatement node
                self.builder.finish_node();
                false // Pop this frame (Do statement complete)
            }
        }
    }

    /// Handle With statement state transitions.
    fn handle_with_statement_frame(&mut self, frame_stack: &mut Vec<ControlFlowFrame>) -> bool {
        // Get current phase and depth
        let (phase, depth) = if let Some(ControlFlowFrame::WithStatement { phase, depth, .. }) =
            frame_stack.last()
        {
            (*phase, *depth)
        } else {
            return false; // Invalid state, pop frame
        };

        match phase {
            WithPhase::Start => {
                // Start With statement
                self.builder.start_node(SyntaxKind::WithStatement.to_raw());
                self.consume_whitespace();
                self.consume_token(); // With
                self.consume_whitespace();
                self.parse_expression();
                self.consume_until_after(Token::Newline);

                // Update phase to Body before pushing nested frame
                if let Some(ControlFlowFrame::WithStatement { phase, .. }) = frame_stack.last_mut()
                {
                    *phase = WithPhase::Body;
                }

                // Push statement list frame for With body
                frame_stack.push(ControlFlowFrame::StatementList {
                    depth,
                    context: StatementListContext::WithBody,
                    started: false,
                });

                true // Continue processing
            }

            WithPhase::Body => {
                // With body statement list just finished
                // Update phase to Finish
                if let Some(ControlFlowFrame::WithStatement { phase, .. }) = frame_stack.last_mut()
                {
                    *phase = WithPhase::Finish;
                }
                true
            }

            WithPhase::Finish => {
                // Parse End With
                if self.at_token(Token::EndKeyword) {
                    self.consume_token();
                    self.consume_whitespace();
                    if self.at_token(Token::WithKeyword) {
                        self.consume_token();
                    }
                    self.consume_until_after(Token::Newline);
                }

                // Finish the WithStatement node
                self.builder.finish_node();
                false // Pop this frame (With statement complete)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::Parser;
    use crate::parsers::cst::{
        ControlKind, Creatable, Exposed, FormRoot, NameSpace, ObjectReference, PreDeclaredID,
    };
    use crate::*;

    use assert_matches::assert_matches;

    #[test]
    fn parse_single_quote_comment() {
        let code = "' This is a comment\nSub Main()\n";

        let mut source_stream = SourceStream::new("test.bas", code);
        let result = tokenize(&mut source_stream);
        let (token_stream_opt, _failures) = result.unpack();

        let token_stream = token_stream_opt.expect("Tokenization failed");
        let cst = parse(token_stream);

        assert_eq!(cst.root_kind(), SyntaxKind::Root);
        // Should have 2 children: the comment and the SubStatement
        assert_eq!(cst.child_count(), 3); // 2 statements + EOF
        assert!(cst.text().contains("' This is a comment"));
        assert!(cst.text().contains("Sub Main()"));

        // Use navigation methods
        assert!(cst.contains_kind(SyntaxKind::EndOfLineComment));
        assert!(cst.contains_kind(SyntaxKind::SubStatement));

        let first = cst.first_child().expect("Expected first child");
        assert_eq!(first.kind(), SyntaxKind::EndOfLineComment);
        assert!(first.is_token());
    }

    #[test]
    fn syntax_kind_conversions() {
        // Test keyword conversions
        assert_eq!(
            SyntaxKind::from(Token::FunctionKeyword),
            SyntaxKind::FunctionKeyword
        );
        assert_eq!(SyntaxKind::from(Token::IfKeyword), SyntaxKind::IfKeyword);
        assert_eq!(SyntaxKind::from(Token::ForKeyword), SyntaxKind::ForKeyword);

        // Test operators
        assert_eq!(
            SyntaxKind::from(Token::AdditionOperator),
            SyntaxKind::AdditionOperator
        );
        assert_eq!(
            SyntaxKind::from(Token::EqualityOperator),
            SyntaxKind::EqualityOperator
        );

        // Test literals
        assert_eq!(
            SyntaxKind::from(Token::StringLiteral),
            SyntaxKind::StringLiteral
        );
        assert_eq!(
            SyntaxKind::from(Token::IntegerLiteral),
            SyntaxKind::IntegerLiteral
        );
        assert_eq!(
            SyntaxKind::from(Token::LongLiteral),
            SyntaxKind::LongLiteral
        );
        assert_eq!(
            SyntaxKind::from(Token::SingleLiteral),
            SyntaxKind::SingleLiteral
        );
        assert_eq!(
            SyntaxKind::from(Token::DoubleLiteral),
            SyntaxKind::DoubleLiteral
        );
        assert_eq!(
            SyntaxKind::from(Token::DateTimeLiteral),
            SyntaxKind::DateLiteral
        );
    }

    #[test]
    fn parse_empty_stream() {
        let source = "";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        assert_eq!(_failures.len(), 0, "Expected no parse failures.");
        let cst = cst_opt.expect("Failed to parse source");

        assert_eq!(cst.root_kind(), SyntaxKind::Root);
        assert_eq!(cst.child_count(), 0);
    }

    #[test]
    fn parse_rem_comment() {
        let source = "REM This is a REM comment\nSub Test()\nEnd Sub\n";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        assert_eq!(_failures.len(), 0, "Expected no parse failures.");
        let cst = cst_opt.expect("Failed to parse source");

        assert_eq!(cst.root_kind(), SyntaxKind::Root);
        // Should have 2 children: the REM comment and the SubStatement
        assert_eq!(cst.child_count(), 3); // 2 statements + EOF
        assert!(cst.text().contains("REM This is a REM comment"));
        assert!(cst.text().contains("Sub Test()"));

        // Verify REM comment is preserved
        let debug = cst.debug_tree();
        assert!(debug.contains("RemComment"));
    }

    #[test]
    fn parse_mixed_comments() {
        let source = "' Single quote comment\nREM REM comment\nSub Test()\nEnd Sub\n";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        assert_eq!(_failures.len(), 0, "Expected no parse failures.");
        let cst = cst_opt.expect("Failed to parse source");

        assert_eq!(cst.root_kind(), SyntaxKind::Root);
        // Should have 5 children: EndOfLineComment, Newline, RemComment, Newline, SubStatement
        assert_eq!(cst.child_count(), 5);
        assert!(cst.text().contains("' Single quote comment"));
        assert!(cst.text().contains("REM REM comment"));

        // Use navigation methods
        let children = cst.children();
        assert_eq!(children[0].kind(), SyntaxKind::EndOfLineComment);
        assert_eq!(children[1].kind(), SyntaxKind::Newline);
        assert_eq!(children[2].kind(), SyntaxKind::RemComment);
        assert_eq!(children[3].kind(), SyntaxKind::Newline);
        assert_eq!(children[4].kind(), SyntaxKind::SubStatement);

        assert!(cst.contains_kind(SyntaxKind::EndOfLineComment));
        assert!(cst.contains_kind(SyntaxKind::RemComment));
    }

    #[test]
    fn parse_with_member_assignment_with_index_expression() {
        let source = r"
Sub Test()
    With mstack
        .item(i - 1) = aa.ObjectRef
    End With
End Sub
";
        let (cst_opt, failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        assert!(
            failures.is_empty(),
            "unexpected parse failures: {failures:?}"
        );

        let cst = cst_opt.expect("Failed to parse source");
        let debug = cst.debug_tree();

        assert!(
            debug.contains("AssignmentStatement"),
            "expected assignment statement in tree: {debug}"
        );
        assert!(
            !debug.contains("kind: Unknown"),
            "unexpected unknown token in tree: {debug}"
        );
    }

    #[test]
    fn cst_with_comments() {
        let source = "' This is a comment\nSub Main()\n";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        assert_eq!(_failures.len(), 0, "Expected no parse failures.");
        let cst = cst_opt.expect("Failed to parse source");

        // Now has 3 children: comment token, newline token, SubStatement
        assert_eq!(cst.child_count(), 3);
        assert!(cst.text().contains("' This is a comment"));
        assert!(cst.text().contains("Sub Main()"));
    }

    #[test]
    fn cst_serializable_tree() {
        let source = "Sub Test()\nEnd Sub\n";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        assert_eq!(_failures.len(), 0, "Expected no parse failures.");
        let cst = cst_opt.expect("Failed to parse source");

        // Convert to serializable format
        let serializable = cst.to_serializable();

        // Verify structure
        assert_eq!(serializable.root.kind(), SyntaxKind::Root);
        assert!(!serializable.root.is_token());
        assert_eq!(serializable.root.children().len(), 1);
        assert_eq!(
            serializable.root.children()[0].kind(),
            SyntaxKind::SubStatement
        );

        // Can be used with insta for snapshot testing:
        // insta::assert_yaml_snapshot!(serializable);
    }

    #[test]
    fn cst_serializable_with_insta() {
        let source = "Dim x As Integer\n";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        assert_eq!(_failures.len(), 0, "Expected no parse failures.");
        let cst = cst_opt.expect("Failed to parse source");
        let serializable = cst.to_serializable();

        // Example of using with insta (commented out to not create snapshot files in normal test runs)
        // insta::assert_yaml_snapshot!(serializable);

        // Verify it's serializable by checking structure
        assert!(!serializable.root.children().is_empty());
    }

    #[test]
    fn parser_mode_full_cst_default() {
        let source = "Sub Test()\nEnd Sub\n";
        let mut stream = SourceStream::new("test.bas".to_string(), source);
        let (token_stream_opt, _) = tokenize(&mut stream).unpack();
        let token_stream = token_stream_opt.expect("Tokenization failed");

        let parser = Parser::new(token_stream);
        // Verify parser was created successfully
        assert_eq!(parser.pos, 0);
    }

    #[test]
    fn parser_mode_direct_extraction() {
        let source = "Sub Test()\nEnd Sub\n";
        let mut stream = SourceStream::new("test.bas".to_string(), source);
        let (token_stream_opt, _) = tokenize(&mut stream).unpack();
        let token_stream = token_stream_opt.expect("Tokenization failed");
        let tokens = token_stream.into_tokens();

        let parser = Parser::new_direct_extraction(tokens, 0);
        assert_eq!(parser.pos, 0);
    }

    #[test]
    fn parser_constructors_preserve_tokens() {
        let source = "VERSION 5.00\n";
        let mut stream = SourceStream::new("test.frm".to_string(), source);
        let (token_stream_opt, _) = tokenize(&mut stream).unpack();
        let token_stream = token_stream_opt.expect("Tokenization failed");

        let tokens_vec = token_stream.into_tokens();
        let token_count = tokens_vec.len();

        let parser = Parser::new_direct_extraction(tokens_vec, 0);
        assert_eq!(parser.tokens.len(), token_count);
        assert_eq!(parser.tokens[0].1, Token::VersionKeyword);
    }

    #[test]
    fn parser_new_with_position() {
        let source = "VERSION 5.00\nSub Test()\nEnd Sub\n";
        let mut stream = SourceStream::new("test.bas".to_string(), source);
        let (token_stream_opt, _) = tokenize(&mut stream).unpack();
        let token_stream = token_stream_opt.expect("Tokenization failed");
        let tokens = token_stream.into_tokens();

        // Create parser starting at position 3 (after VERSION keyword, whitespace, and version number)
        let parser = Parser::new_direct_extraction(tokens, 3);
        assert_eq!(parser.pos, 3);
    }

    #[test]
    fn parse_version_direct_with_version() {
        let source = "VERSION 5.00\nSub Test()\nEnd Sub\n";
        let mut stream = SourceStream::new("test.frm".to_string(), source);
        let (token_stream_opt, _) = tokenize(&mut stream).unpack();
        let token_stream = token_stream_opt.expect("Tokenization failed");
        let tokens = token_stream.into_tokens();

        let mut parser = Parser::new_direct_extraction(tokens, 0);
        let (version_opt, failures) = parser.parse_version_direct().unpack();

        assert!(version_opt.is_some());
        let version = version_opt.expect("Expected version to be parsed");
        assert_eq!(version.major, 5);
        assert_eq!(version.minor, 0);
        assert!(failures.is_empty());
    }

    #[test]
    fn parse_version_direct_without_version() {
        let source = "Sub Test()\nEnd Sub\n";
        let mut stream = SourceStream::new("test.bas".to_string(), source);
        let (token_stream_opt, _) = tokenize(&mut stream).unpack();
        let token_stream = token_stream_opt.expect("Tokenization failed");
        let tokens = token_stream.into_tokens();

        let mut parser = Parser::new_direct_extraction(tokens, 0);
        let (version_opt, failures) = parser.parse_version_direct().unpack();

        assert!(version_opt.is_none());
        assert!(failures.is_empty());
    }

    #[test]
    fn parse_version_direct_with_class_keyword() {
        let source = "VERSION 1.0 CLASS\nSub Test()\nEnd Sub\n";
        let mut stream = SourceStream::new("test.cls".to_string(), source);
        let (token_stream_opt, _) = tokenize(&mut stream).unpack();
        let token_stream = token_stream_opt.expect("Tokenization failed");
        let tokens = token_stream.into_tokens();

        let mut parser = Parser::new_direct_extraction(tokens, 0);
        let (version_opt, failures) = parser.parse_version_direct().unpack();

        assert!(version_opt.is_some());
        let version = version_opt.expect("Expected version to be parsed");
        assert_eq!(version.major, 1);
        assert_eq!(version.minor, 0);
        assert!(failures.is_empty());
    }

    #[test]
    fn parse_version_direct_version_100() {
        let source = "VERSION 1.00\n";
        let mut stream = SourceStream::new("test.cls".to_string(), source);
        let (token_stream_opt, _) = tokenize(&mut stream).unpack();
        let token_stream = token_stream_opt.expect("Tokenization failed");
        let tokens = token_stream.into_tokens();

        let mut parser = Parser::new_direct_extraction(tokens, 0);
        let (version_opt, _failures) = parser.parse_version_direct().unpack();

        assert!(version_opt.is_some());
        let version = version_opt.expect("Expected version to be parsed");
        assert_eq!(version.major, 1);
        assert_eq!(version.minor, 0);
    }

    #[test]
    fn parse_version_direct_with_whitespace() {
        let source = "  VERSION   5.00  \nSub Test()\n";
        let mut stream = SourceStream::new("test.frm".to_string(), source);
        let (token_stream_opt, _) = tokenize(&mut stream).unpack();
        let token_stream = token_stream_opt.expect("Tokenization failed");
        let tokens = token_stream.into_tokens();

        let mut parser = Parser::new_direct_extraction(tokens, 0);
        let (version_opt, _failures) = parser.parse_version_direct().unpack();

        assert!(version_opt.is_some());
        let version = version_opt.expect("Expected version to be parsed");
        assert_eq!(version.major, 5);
        assert_eq!(version.minor, 0);
    }

    #[test]
    fn parse_version_direct_position_advances() {
        let source = "VERSION 5.00\nBegin VB.Form Form1\nEnd\n";
        let mut stream = SourceStream::new("test.frm".to_string(), source);
        let (token_stream_opt, _) = tokenize(&mut stream).unpack();
        let token_stream = token_stream_opt.expect("Tokenization failed");
        let tokens = token_stream.into_tokens();

        let mut parser = Parser::new_direct_extraction(tokens, 0);
        let initial_pos = parser.pos;
        let _result = parser.parse_version_direct();

        // Position should have advanced past VERSION statement
        assert!(parser.pos > initial_pos);

        // Should now be positioned at Begin keyword
        assert_eq!(parser.current_token(), Some(&Token::BeginKeyword));
    }

    #[test]
    fn parse_version_direct_accuracy() {
        let test_cases = vec![
            ("VERSION 5.00\n", Some((5, 0))),
            ("VERSION 1.0\n", Some((1, 0))),
            ("VERSION 6.00 CLASS\n", Some((6, 0))),
            ("VERSION 4.00\n", Some((4, 0))),
            ("Sub Test()\n", None), // No VERSION
        ];

        for (source, expected) in test_cases {
            let mut stream = SourceStream::new("test.vb".to_string(), source);
            let (token_stream_opt, _) = tokenize(&mut stream).unpack();
            let token_stream = token_stream_opt.expect("Tokenization failed");
            let tokens = token_stream.into_tokens();

            let mut parser = Parser::new_direct_extraction(tokens, 0);
            let (version_opt, _failures) = parser.parse_version_direct().unpack();

            match expected {
                Some((major, minor)) => {
                    assert!(version_opt.is_some(), "Expected version for: {source}");
                    let version = version_opt.expect("Expected version to be parsed");
                    assert_eq!(version.major, major, "Major mismatch for: {source}");
                    assert_eq!(version.minor, minor, "Minor mismatch for: {source}");
                }
                None => {
                    assert!(version_opt.is_none(), "Expected no version for: {source}");
                }
            }
        }
    }

    #[test]
    fn parse_control_type_direct_simple() {
        let source = "VB.Form Form1\n";
        let mut stream = SourceStream::new("test.frm".to_string(), source);
        let (token_stream_opt, _) = tokenize(&mut stream).unpack();
        let token_stream = token_stream_opt.expect("Tokenization failed");
        let tokens = token_stream.into_tokens();

        let mut parser = Parser::new_direct_extraction(tokens, 0);
        let control_type = parser.parse_control_type_direct();

        assert_eq!(control_type, "VB.Form");
    }

    #[test]
    fn parse_control_name_direct_simple() {
        let source = "Form1 \n";
        let mut stream = SourceStream::new("test.frm".to_string(), source);
        let (token_stream_opt, _) = tokenize(&mut stream).unpack();
        let token_stream = token_stream_opt.expect("Tokenization failed");
        let tokens = token_stream.into_tokens();

        let mut parser = Parser::new_direct_extraction(tokens, 0);
        let control_name = parser.parse_control_name_direct();

        assert_eq!(control_name, "Form1");
    }

    #[test]
    fn parse_property_direct_simple() {
        let source = "Caption = \"Hello World\"\n";
        let mut stream = SourceStream::new("test.frm".to_string(), source);
        let (token_stream_opt, _) = tokenize(&mut stream).unpack();
        let token_stream = token_stream_opt.expect("Tokenization failed");
        let tokens = token_stream.into_tokens();

        let mut parser = Parser::new_direct_extraction(tokens, 0);
        let property = parser.parse_property_direct();

        assert!(property.is_some());
        let (key, value) = property.expect("Expected property to be parsed");
        assert_eq!(key, "Caption");
        assert_eq!(value, "\"Hello World\"");
    }

    #[test]
    fn parse_properties_block_to_control_simple_form() {
        let source = r#"Begin VB.Form Form1
   Caption = "Test Form"
   ClientHeight = 3000
   ClientWidth = 4000
End
"#;
        let mut stream = SourceStream::new("test.frm".to_string(), source);
        let (token_stream_opt, _) = tokenize(&mut stream).unpack();
        let token_stream = token_stream_opt.expect("Tokenization failed");
        let tokens = token_stream.into_tokens();

        let mut parser = Parser::new_direct_extraction(tokens, 0);
        let (control_opt, failures) = parser.parse_properties_block_to_form_root().unpack();

        assert!(failures.is_empty(), "Expected no failures");
        assert!(control_opt.is_some(), "Expected form root to be parsed");

        let form_root = control_opt.expect("Expected form root to be parsed");
        assert_eq!(form_root.name(), "Form1");

        // Verify it's a Form
        assert!(form_root.is_form());
    }

    #[test]
    fn parse_properties_block_to_control_command_button() {
        let source = r#"Begin VB.CommandButton Command1
   Caption = "Click Me"
   Height = 495
   Width = 1215
End
"#;
        let mut stream = SourceStream::new("test.frm".to_string(), source);
        let (token_stream_opt, _) = tokenize(&mut stream).unpack();
        let token_stream = token_stream_opt.expect("Tokenization failed");
        let tokens = token_stream.into_tokens();

        let mut parser = Parser::new_direct_extraction(tokens, 0);
        let (control_opt, failures) = parser.parse_properties_block_to_control().unpack();

        assert!(failures.is_empty());
        assert!(control_opt.is_some());

        let control = control_opt.expect("Expected control to be parsed");
        assert_eq!(control.name(), "Command1");
        assert_matches!(control.kind(), ControlKind::CommandButton { .. });
    }

    #[test]
    fn parse_properties_block_to_control_textbox() {
        let source = r#"Begin VB.TextBox Text1
   Text = "Initial Text"
   Height = 300
   Width = 2000
End
"#;
        let mut stream = SourceStream::new("test.frm".to_string(), source);
        let (token_stream_opt, _) = tokenize(&mut stream).unpack();
        let token_stream = token_stream_opt.expect("Tokenization failed");
        let tokens = token_stream.into_tokens();

        let mut parser = Parser::new_direct_extraction(tokens, 0);
        let (control_opt, _failures) = parser.parse_properties_block_to_control().unpack();

        assert!(control_opt.is_some());
        let control = control_opt.expect("Expected control to be parsed");
        assert_eq!(control.name(), "Text1");
        assert_matches!(control.kind(), ControlKind::TextBox { .. });
    }

    #[test]
    fn parse_properties_block_without_begin() {
        let source = "Caption = \"Test\"\nEnd\n";
        let mut stream = SourceStream::new("test.frm".to_string(), source);
        let (token_stream_opt, _) = tokenize(&mut stream).unpack();
        let token_stream = token_stream_opt.expect("Tokenization failed");
        let tokens = token_stream.into_tokens();

        let mut parser = Parser::new_direct_extraction(tokens, 0);
        let (control_opt, _failures) = parser.parse_properties_block_to_control().unpack();

        // Should return None when BEGIN is missing
        assert!(control_opt.is_none());
    }

    #[test]
    fn parse_form_with_nested_control() {
        let source = r#"Begin VB.Form Form1
   Caption = "Main Form"
   Begin VB.CommandButton Command1
      Caption = "Click Me"
      Height = 400
   End
End
"#;
        let mut stream = SourceStream::new("test.frm".to_string(), source);
        let (token_stream_opt, _) = tokenize(&mut stream).unpack();
        let token_stream = token_stream_opt.expect("Tokenization failed");
        let tokens = token_stream.into_tokens();

        let mut parser = Parser::new_direct_extraction(tokens, 0);
        let (form_root_opt, failures) = parser.parse_properties_block_to_form_root().unpack();

        assert!(failures.is_empty(), "Should have no failures");
        assert!(form_root_opt.is_some());
        let form_root = form_root_opt.expect("Expected form root to be parsed");
        assert_eq!(form_root.name(), "Form1");

        // Check form has child controls
        if let FormRoot::Form(form) = &form_root {
            assert_eq!(form.controls.len(), 1);
            assert_eq!(form.controls[0].name(), "Command1");
            assert_matches!(form.controls[0].kind(), ControlKind::CommandButton { .. });
        } else {
            panic!("Expected Form");
        }
    }

    #[test]
    fn parse_frame_with_multiple_nested_controls() {
        let source = r#"Begin VB.Frame Frame1
   Caption = "Options"
   Begin VB.CheckBox Check1
      Caption = "Option 1"
   End
   Begin VB.CheckBox Check2
      Caption = "Option 2"
   End
End
"#;
        let mut stream = SourceStream::new("test.frm".to_string(), source);
        let (token_stream_opt, _) = tokenize(&mut stream).unpack();
        let token_stream = token_stream_opt.expect("Tokenization failed");
        let tokens = token_stream.into_tokens();

        let mut parser = Parser::new_direct_extraction(tokens, 0);
        let (control_opt, failures) = parser.parse_properties_block_to_control().unpack();

        assert!(failures.is_empty());
        assert!(control_opt.is_some());
        let control = control_opt.expect("Expected control to be parsed");
        assert_eq!(control.name(), "Frame1");

        // Check frame has 2 child checkboxes
        if let ControlKind::Frame { controls, .. } = control.kind() {
            assert_eq!(controls.len(), 2);
            assert_eq!(controls[0].name(), "Check1");
            assert_eq!(controls[1].name(), "Check2");
        } else {
            panic!("Expected Frame control kind");
        }
    }

    #[test]
    fn parse_control_with_property_group() {
        let source = r#"Begin VB.CommandButton Command1
   Caption = "Button"
   BeginProperty Font
      Name = "Arial"
      Size = 12
   EndProperty
End
"#;
        let mut stream = SourceStream::new("test.frm".to_string(), source);
        let (token_stream_opt, _) = tokenize(&mut stream).unpack();
        let token_stream = token_stream_opt.expect("Tokenization failed");
        let tokens = token_stream.into_tokens();

        let mut parser = Parser::new_direct_extraction(tokens, 0);
        let (control_opt, failures) = parser.parse_properties_block_to_control().unpack();

        assert!(failures.is_empty());
        assert!(control_opt.is_some());
        let control = control_opt.expect("Expected control to be parsed");
        assert_eq!(control.name(), "Command1");

        // Check for property - CommandButton should have parsed successfully
        // Property groups are stored in Custom control kind, not specific control types
        assert_matches!(control.kind(), ControlKind::CommandButton { .. });
    }

    #[test]
    fn parse_custom_control_with_property_group() {
        let source = r#"Begin MSComctlLib.TreeView TreeView1
   BeginProperty Font {0BE35203-8F91-11CE-9DE3-00AA004BB851}
      Name = "MS Sans Serif"
      Size = 8.25
      Charset = 0
   EndProperty
   Caption = "Tree"
End
"#;
        let mut stream = SourceStream::new("test.frm".to_string(), source);
        let (token_stream_opt, _) = tokenize(&mut stream).unpack();
        let token_stream = token_stream_opt.expect("Tokenization failed");
        let tokens = token_stream.into_tokens();

        let mut parser = Parser::new_direct_extraction(tokens, 0);
        let (control_opt, failures) = parser.parse_properties_block_to_control().unpack();

        assert!(failures.is_empty());
        assert!(control_opt.is_some());
        let control = control_opt.expect("Expected control to be parsed");
        assert_eq!(control.name(), "TreeView1");

        // Check for Custom control with property groups
        if let ControlKind::Custom {
            property_groups, ..
        } = control.kind()
        {
            assert_eq!(property_groups.len(), 1);
            assert_eq!(property_groups[0].name, "Font");
            assert!(property_groups[0].guid.is_some());
        } else {
            panic!("Expected Custom control kind");
        }
    }

    #[test]
    fn parse_simple_object_statement() {
        let source = r#"Object = "{12345678-1234-1234-1234-123456789ABC}#1.0#0"; "MyLib.dll""#;
        let mut stream = SourceStream::new("test.frm".to_string(), source);
        let (token_stream_opt, _) = tokenize(&mut stream).unpack();
        let token_stream = token_stream_opt.expect("Tokenization failed");
        let tokens = token_stream.into_tokens();

        let mut parser = Parser::new_direct_extraction(tokens, 0);
        let objects = parser.parse_objects_direct();

        assert_eq!(objects.len(), 1);
        match &objects[0] {
            ObjectReference::Compiled {
                uuid,
                version,
                unknown1,
                file_name,
            } => {
                assert_eq!(
                    uuid.to_string().to_uppercase(),
                    "12345678-1234-1234-1234-123456789ABC"
                );
                assert_eq!(version, "1.0");
                assert_eq!(unknown1, "0");
                assert_eq!(file_name, "MyLib.dll");
            }
            ObjectReference::Project { .. } => {
                panic!("Expected Compiled object reference")
            }
        }
    }

    #[test]
    fn parse_multiple_object_statements() {
        let source = r#"Object = "{AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA}#1.0#0"; "Lib1.dll"
Object = "{BBBBBBBB-BBBB-BBBB-BBBB-BBBBBBBBBBBB}#2.0#1"; "Lib2.ocx"
"#;
        let mut stream = SourceStream::new("test.frm".to_string(), source);
        let (token_stream_opt, _) = tokenize(&mut stream).unpack();
        let token_stream = token_stream_opt.expect("Tokenization failed");
        let tokens = token_stream.into_tokens();

        let mut parser = Parser::new_direct_extraction(tokens, 0);
        let objects = parser.parse_objects_direct();

        assert_eq!(objects.len(), 2);

        match &objects[0] {
            ObjectReference::Compiled { file_name, .. } => {
                assert_eq!(file_name, "Lib1.dll");
            }
            ObjectReference::Project { .. } => {
                panic!("Expected Compiled object reference")
            }
        }

        match &objects[1] {
            ObjectReference::Compiled { file_name, .. } => {
                assert_eq!(file_name, "Lib2.ocx");
            }
            ObjectReference::Project { .. } => {
                panic!("Expected Compiled object reference")
            }
        }
    }

    #[test]
    fn parse_embedded_object_statement() {
        let source = r#"Object = *\G{87654321-4321-4321-4321-CBA987654321}#3.0#5; "Embedded.ocx""#;
        let mut stream = SourceStream::new("test.frm".to_string(), source);
        let (token_stream_opt, _) = tokenize(&mut stream).unpack();
        let token_stream = token_stream_opt.expect("Tokenization failed");
        let tokens = token_stream.into_tokens();

        let mut parser = Parser::new_direct_extraction(tokens, 0);
        let objects = parser.parse_objects_direct();

        assert_eq!(objects.len(), 1);
        match &objects[0] {
            ObjectReference::Compiled {
                uuid,
                version,
                file_name,
                ..
            } => {
                assert_eq!(
                    uuid.to_string().to_uppercase(),
                    "87654321-4321-4321-4321-CBA987654321"
                );
                assert_eq!(version, "3.0");
                assert_eq!(file_name, "Embedded.ocx");
            }
            ObjectReference::Project { .. } => {
                panic!("Expected Compiled object reference")
            }
        }
    }

    #[test]
    fn parse_nested_property_groups() {
        use either::Either;

        let source = r#"Begin Custom.Control Ctrl1
   BeginProperty Outer
      Value1 = "Test"
      BeginProperty Inner
         Value2 = "Nested"
      EndProperty
   EndProperty
End
"#;
        let mut stream = SourceStream::new("test.frm".to_string(), source);
        let (token_stream_opt, _) = tokenize(&mut stream).unpack();
        let token_stream = token_stream_opt.expect("Tokenization failed");
        let tokens = token_stream.into_tokens();

        let mut parser = Parser::new_direct_extraction(tokens, 0);
        let (control_opt, failures) = parser.parse_properties_block_to_control().unpack();

        assert!(failures.is_empty());
        assert!(control_opt.is_some());
        let control = control_opt.expect("Expected control to be parsed");

        // Check for nested property groups
        if let ControlKind::Custom {
            property_groups, ..
        } = control.kind()
        {
            assert_eq!(property_groups.len(), 1);
            assert_eq!(property_groups[0].name, "Outer");

            // Check for nested group

            if let Some(Either::Right(inner)) = property_groups[0].properties.get("Inner") {
                assert_eq!(inner.name, "Inner");
            } else {
                panic!("Expected nested Inner property group");
            }
        } else {
            panic!("Expected Custom control kind");
        }
    }

    #[test]
    fn parse_deeply_nested_controls() {
        let source = r#"Begin VB.Form Form1
   Caption = "Outer"
   Begin VB.PictureBox Picture1
      Begin VB.Frame Frame1
         Begin VB.Label Label1
            Caption = "Deep"
         End
      End
   End
End
"#;
        let mut stream = SourceStream::new("test.frm".to_string(), source);
        let (token_stream_opt, _) = tokenize(&mut stream).unpack();
        let token_stream = token_stream_opt.expect("Tokenization failed");
        let tokens = token_stream.into_tokens();

        let mut parser = Parser::new_direct_extraction(tokens, 0);
        let (form_root_opt, failures) = parser.parse_properties_block_to_form_root().unpack();

        assert!(failures.is_empty());
        assert!(form_root_opt.is_some());
        let form_root = form_root_opt.expect("Expected form root to be parsed");

        // Verify deep nesting: Form > PictureBox > Frame > Label
        if let FormRoot::Form(form) = &form_root {
            assert_eq!(form.controls.len(), 1);
            if let ControlKind::PictureBox { controls, .. } = form.controls[0].kind() {
                assert_eq!(controls.len(), 1);
                if let ControlKind::Frame { controls, .. } = controls[0].kind() {
                    assert_eq!(controls.len(), 1);
                    assert_eq!(controls[0].name(), "Label1");
                } else {
                    panic!("Expected Frame");
                }
            } else {
                panic!("Expected PictureBox");
            }
        } else {
            panic!("Expected Form");
        }
    }

    #[test]
    fn parse_simple_string_attribute() {
        let source = r#"Attribute VB_Name = "Form1"
"#;
        let mut stream = SourceStream::new("test.frm".to_string(), source);
        let (token_stream_opt, _) = tokenize(&mut stream).unpack();
        let token_stream = token_stream_opt.expect("Tokenization failed");
        let tokens = token_stream.into_tokens();

        let mut parser = Parser::new_direct_extraction(tokens, 0);
        let attrs = parser.parse_attributes_direct();

        assert_eq!(attrs.name, "Form1");
        assert_eq!(attrs.global_name_space, NameSpace::Local);
        assert_eq!(attrs.creatable, Creatable::True);
        assert_eq!(attrs.predeclared_id, PreDeclaredID::False);
        assert_eq!(attrs.exposed, Exposed::False);
        assert_eq!(attrs.description, None);
    }

    #[test]
    fn parse_boolean_attributes() {
        let source = r"Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = True
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
";
        let mut stream = SourceStream::new("test.frm".to_string(), source);
        let (token_stream_opt, _) = tokenize(&mut stream).unpack();
        let token_stream = token_stream_opt.expect("Tokenization failed");
        let tokens = token_stream.into_tokens();

        let mut parser = Parser::new_direct_extraction(tokens, 0);
        let attrs = parser.parse_attributes_direct();

        assert_eq!(attrs.global_name_space, NameSpace::Local);
        assert_eq!(attrs.creatable, Creatable::True);
        assert_eq!(attrs.predeclared_id, PreDeclaredID::True);
        assert_eq!(attrs.exposed, Exposed::False);
    }

    #[test]
    fn parse_numeric_attribute() {
        let source = r"Attribute VB_PredeclaredId = -1
";
        let mut stream = SourceStream::new("test.frm".to_string(), source);
        let (token_stream_opt, _) = tokenize(&mut stream).unpack();
        let token_stream = token_stream_opt.expect("Tokenization failed");
        let tokens = token_stream.into_tokens();

        let mut parser = Parser::new_direct_extraction(tokens, 0);
        let attrs = parser.parse_attributes_direct();

        // -1 is truthy in VB6, so should be parsed as true
        assert_eq!(attrs.predeclared_id, PreDeclaredID::True);
    }

    #[test]
    fn parse_multiple_attributes() {
        let source = r#"Attribute VB_Name = "MyForm"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Attribute VB_Description = "This is a test form"
"#;
        let mut stream = SourceStream::new("test.frm".to_string(), source);
        let (token_stream_opt, _) = tokenize(&mut stream).unpack();
        let token_stream = token_stream_opt.expect("Tokenization failed");
        let tokens = token_stream.into_tokens();

        let mut parser = Parser::new_direct_extraction(tokens, 0);
        let attrs = parser.parse_attributes_direct();

        assert_eq!(attrs.name, "MyForm");
        assert_eq!(attrs.global_name_space, NameSpace::Local);
        assert_eq!(attrs.creatable, Creatable::False);
        assert_eq!(attrs.predeclared_id, PreDeclaredID::True);
        assert_eq!(attrs.exposed, Exposed::False);
        assert_eq!(attrs.description, Some("This is a test form".to_string()));
    }

    #[test]
    fn parse_ext_key_attributes() {
        let source = r#"Attribute VB_Name = "Form1"
Attribute VB_Ext_KEY = "CustomKey" ,"CustomValue"
Attribute VB_Description = "Test"
"#;
        let mut stream = SourceStream::new("test.frm".to_string(), source);
        let (token_stream_opt, _) = tokenize(&mut stream).unpack();
        let token_stream = token_stream_opt.expect("Tokenization failed");
        let tokens = token_stream.into_tokens();

        let mut parser = Parser::new_direct_extraction(tokens, 0);
        let attrs = parser.parse_attributes_direct();

        assert_eq!(attrs.name, "Form1");
        assert_eq!(attrs.description, Some("Test".to_string()));
        assert_eq!(attrs.ext_key.len(), 1);
        assert!(attrs.ext_key.contains_key("VB_Ext_KEY"));
    }

    #[test]
    fn parse_empty_attributes() {
        let source = r"";
        let mut stream = SourceStream::new("test.frm".to_string(), source);
        let (token_stream_opt, _) = tokenize(&mut stream).unpack();
        let token_stream = token_stream_opt.expect("Tokenization failed");
        let tokens = token_stream.into_tokens();

        let mut parser = Parser::new_direct_extraction(tokens, 0);
        let attrs = parser.parse_attributes_direct();

        assert_eq!(attrs.name, "");
        assert_eq!(attrs.global_name_space, NameSpace::Local);
        assert_eq!(attrs.creatable, Creatable::True);
        assert_eq!(attrs.predeclared_id, PreDeclaredID::False);
        assert_eq!(attrs.exposed, Exposed::False);
        assert_eq!(attrs.description, None);
        assert!(attrs.ext_key.is_empty());
    }

    #[test]
    fn parse_resource_reference_property() {
        let source = r#"Caption = $"Gradient.frx":0000
"#;
        let mut stream = SourceStream::new("test.frm".to_string(), source);
        let (token_stream_opt, _) = tokenize(&mut stream).unpack();
        let token_stream = token_stream_opt.expect("Tokenization failed");
        let tokens = token_stream.into_tokens();

        let mut parser = Parser::new_direct_extraction(tokens, 0);
        let property = parser.parse_property_direct();

        assert!(property.is_some());
        let (key, value) = property.expect("Expected property to be parsed");
        assert_eq!(key, "Caption");
        assert_eq!(value, r#"$"Gradient.frx":0000"#);
    }
}