vb6semantic 0.1.0

Semantic analysis and symbol table construction for VB6 code
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
//! Semantic analyzer for VB6 code. This module performs semantic analysis on the parsed CST
//! to build symbol tables, resolve names, check types, and report errors.
//!
//! The main entry point is the `SemanticAnalyzer` struct, which provides methods to analyze
//! project files, module files, class files, and form files. The analyzer maintains a scope
//! manager to handle symbol resolution and a type checker for validating type usage. Errors and
//! warnings are collected during analysis and can be retrieved after the process is complete.
//!
//! The `NameResolver` struct is used for resolving symbol references within the current
//! scope context. It provides methods to resolve simple names and qualified names, as well
//! as checking symbol accessibility.
//!
//! The `ScopeManager` struct manages the hierarchy of scopes and symbols, allowing for lookups
//! and scope transitions during analysis. The `TypeChecker` struct provides methods for checking
//! type compatibility and assignment validity.
//!
//! Overall, this module is responsible for the core semantic analysis logic that ensures the VB6 code
//! is semantically correct and provides meaningful error messages for any issues found.
//!
//! # Examples
//!
//! ```rust, no_run
//! use vb6semantic::SemanticAnalyzer;
//! use vb6parse::io::SourceFile;
//! use vb6parse::files::ProjectFile;
//!
//! let mut analyzer = SemanticAnalyzer::new();
//! let project_source = SourceFile::from_file("MyProject.vbp").expect("Failed to read project file");
//! let (project_opt, failures) = ProjectFile::parse(&project_source).unpack();
//! if !failures.is_empty() {
//!     eprintln!("Failed to parse project file: {:?}", failures);
//!     return;
//! }
//!
//! let project = project_opt.expect("Project file should have parsed successfully");
//!
//! let analysis_result = analyzer.analyze_project(&project).expect("Failed to analyze project");
//! println!("Analysis completed with {} errors and {} warnings", analysis_result.errors.len(), analysis_result.warnings.len());
//! ```

use crate::error::{Result, SemanticError, SourceLocation};
use crate::location::LineIndex;
use crate::query::{QueryIndex, Reference as QueryReference, ReferenceKind};
use crate::references::{ReferenceInfo, ReferenceRegistry, ReferenceResolver};
use crate::scope::{ScopeKind, ScopeManager};
use crate::symbols::{Symbol, SymbolKind, Visibility};
use crate::types::{TypeChecker, TypeInfo, VBType};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use vb6parse::parsers::SyntaxKind;
use vb6parse::parsers::cst::CstNode;

/// Built-in VB6 reference manifest for "OLE Automation".
///
/// Contains the VB6 data constants (`vbCrLf`, `vbTab`, etc.) that are
/// available in every VB6 program without declaration.
const DEFAULT_MANIFEST_JSON: &str = include_str!("../data/ole-automation.json");

/// Main semantic analyzer that processes VB6 code
pub struct SemanticAnalyzer {
    /// Scope manager for symbol resolution
    scope_manager: ScopeManager,

    /// Type checker for type validation
    #[allow(dead_code)]
    type_checker: TypeChecker,

    /// Current file being analyzed
    current_file: Option<String>,

    /// Base directory that source-file paths from the `.vbp` are resolved
    /// against. VB6 stores paths in a project file relative to that file's
    /// directory, so callers analyzing a project outside the current working
    /// directory should set this to the project directory.
    base_dir: Option<PathBuf>,

    /// Interfaces implemented by the current class
    implements: Vec<String>,

    /// User-modifiable list of reference resolvers
    references: ReferenceRegistry,

    /// References that were resolved to a symbol set
    resolved_references: Vec<ReferenceInfo>,

    /// References no registered resolver could handle
    unresolved_references: Vec<ReferenceInfo>,

    /// Collected errors
    errors: Vec<SemanticError>,

    /// Collected warnings
    warnings: Vec<String>,

    /// Byte-offset → position mapping for the file currently being analyzed
    line_index: LineIndex,

    /// Lines consumed by the file header (form/class) and absent from the CST
    current_line_offset: usize,

    /// Resolved identifier occurrences collected during analysis
    query_index: QueryIndex,

    /// Whether reference collection is deferred until all files in a project
    /// are registered (set during `analyze_project`). When false, each file
    /// resolves its own references immediately after registration.
    defer_resolution: bool,

    /// Statement start offset → procedure scope id for the file currently
    /// being analyzed (consumed by [`Self::resolve_pending`]).
    procedure_scopes: HashMap<u32, usize>,

    /// Files waiting for reference resolution once the project is registered.
    pending_resolution: Vec<PendingResolution>,
}

impl SemanticAnalyzer {
    /// Create a new semantic analyzer instance
    pub fn new() -> Self {
        Self {
            scope_manager: ScopeManager::new(),
            type_checker: TypeChecker::new(),
            current_file: None,
            base_dir: None,
            implements: Vec::new(),
            references: ReferenceRegistry::new(),
            resolved_references: Vec::new(),
            unresolved_references: Vec::new(),
            errors: Vec::new(),
            warnings: Vec::new(),
            line_index: LineIndex::default(),
            current_line_offset: 0,
            query_index: QueryIndex::new(),
            defer_resolution: false,
            procedure_scopes: HashMap::new(),
            pending_resolution: Vec::new(),
        }
    }

    /// Set the base directory that source-file paths from the `.vbp` are
    /// resolved against.
    ///
    /// Paths stored in a VB6 project file are relative to the project file's
    /// directory, so projects analyzed from elsewhere need this set to the
    /// project directory. Absolute paths are always used as-is.
    pub fn set_base_dir(&mut self, dir: impl Into<PathBuf>) {
        self.base_dir = Some(dir.into());
    }

    /// Set the base directory and return `self` for chaining.
    pub fn with_base_dir(mut self, dir: impl Into<PathBuf>) -> Self {
        self.set_base_dir(dir);
        self
    }

    /// Resolve a source-file path from the `.vbp` against the base directory.
    fn resolve_source_path(&self, path: &str) -> PathBuf {
        match &self.base_dir {
            Some(base) if !Path::new(path).is_absolute() => {
                // `.vbp` paths use Windows backslashes even on Linux.
                let normalized = if cfg!(target_os = "windows") {
                    path.to_string()
                } else {
                    path.replace('\\', "/")
                };
                base.join(normalized)
            }
            _ => PathBuf::from(path),
        }
    }

    /// Analyze a VB6 project file
    pub fn analyze_project(
        &mut self,
        project: &vb6parse::files::ProjectFile,
    ) -> Result<AnalysisResult> {
        self.current_file = Some(project.properties.name.to_string());

        // Resolve project references before analyzing source files so that
        // reference-library symbols are visible during name resolution.
        self.resolve_project_references(project)?;

        // Create project-level scope
        let _project_scope = self
            .scope_manager
            .push_scope(ScopeKind::Global, project.properties.name.to_string());

        // Defer per-file reference collection so forward and cross-module
        // references resolve once every file's declarations are registered.
        self.defer_resolution = true;

        // Analyze the source files in `.vbp` line order so that cross-module
        // name resolution matches the order the IDE sees the files in.
        for entry in project.file_entries() {
            match entry {
                vb6parse::files::project::ProjectFileEntry::Module(module_reference) => {
                    self.analyze_module_reference(module_reference)?;
                }
                vb6parse::files::project::ProjectFileEntry::Class(class_reference) => {
                    self.analyze_class_reference(class_reference)?;
                }
                vb6parse::files::project::ProjectFileEntry::Form(form_file_name) => {
                    self.analyze_form_path(form_file_name)?;
                }
                // User controls, user documents, designers, property pages, and
                // related documents are not analyzed yet.
                _ => {}
            }
        }

        // TODO: Analyze any additional project-level constructs if necessary

        self.scope_manager.pop_scope()?;
        self.defer_resolution = false;
        self.resolve_pending()?;
        self.query_index.finalize();

        Ok(AnalysisResult {
            scope_manager: self.scope_manager.clone(),
            errors: self.errors.clone(),
            warnings: self.warnings.clone(),
            resolved_references: self.resolved_references.clone(),
            unresolved_references: self.unresolved_references.clone(),
            query_index: self.query_index.clone(),
        })
    }

    /// Register a reference resolver, appending it to the user-modifiable list
    pub fn register_reference_resolver(&mut self, resolver: Box<dyn ReferenceResolver>) {
        self.references.register(resolver);
    }

    /// Register the built-in VB6 reference manifest.
    ///
    /// The manifest supplies symbol information for the "OLE Automation"
    /// reference library, including VB6 data constants (`vbCrLf`, `vbTab`,
    /// etc.) that are available in every VB6 program without declaration.
    ///
    /// This is a no-op if the manifest is already registered.  It is called
    /// automatically during project analysis so callers do not normally need
    /// to invoke it.
    pub fn register_default_references(&mut self) -> Result<()> {
        if self
            .references
            .resolvers()
            .iter()
            .any(|r| r.name() == "manifest")
        {
            return Ok(());
        }
        use crate::references::ManifestReferenceResolver;
        let resolver = ManifestReferenceResolver::from_json(DEFAULT_MANIFEST_JSON)?;
        self.references.register(Box::new(resolver));
        Ok(())
    }

    /// The list of registered reference resolvers
    pub fn reference_resolvers(&self) -> &ReferenceRegistry {
        &self.references
    }

    /// Mutable access to the reference resolver list
    pub fn reference_resolvers_mut(&mut self) -> &mut ReferenceRegistry {
        &mut self.references
    }

    /// Walk the project's references and let the registered resolvers supply
    /// symbols for them. References with no resolver handles become warnings rather
    /// than errors, so projects can be analyzed without every referenced library
    /// being installed.
    fn resolve_project_references(&mut self, project: &vb6parse::files::ProjectFile) -> Result<()> {
        self.resolved_references.clear();
        self.unresolved_references.clear();

        // Ensure built-in VB6 reference symbols (data constants, etc.)
        // are registered.  This is a no-op if already present.
        if let Err(error) = self.register_default_references() {
            self.warnings
                .push(format!("Failed to load default references: {error}"));
        }

        let file = self
            .current_file
            .clone()
            .unwrap_or_else(|| "<unknown>".to_string());

        for reference in project.references() {
            let info = ReferenceInfo::from_project_reference(reference);
            match self
                .references
                .resolve(&info, &mut self.scope_manager, &file)
            {
                Ok(true) => self.resolved_references.push(info),
                Ok(false) => {
                    self.warnings.push(format!(
                        "Unresolved project reference: {}",
                        info.display_name()
                    ));
                    self.unresolved_references.push(info);
                }
                Err(error) => {
                    self.warnings.push(format!(
                        "Failed to resolve project reference {}: {error}",
                        info.display_name()
                    ));
                    self.unresolved_references.push(info);
                }
            }
        }

        Ok(())
    }

    /// Analyze a module reference from the project file reference
    pub fn analyze_module_reference(
        &mut self,
        module_reference: &vb6parse::files::project::ProjectModuleReference,
    ) -> Result<()> {
        let module_path = self.resolve_source_path(module_reference.path);
        let source_file = vb6parse::io::SourceFile::from_file(&module_path).map_err(|e| {
            crate::error::SemanticError::FileReadError {
                file: module_path.display().to_string(),
                message: e.to_string(),
            }
        })?;

        let (module_opt, failures) = vb6parse::files::ModuleFile::parse(&source_file).unpack();
        if let Some(module) = module_opt {
            self.analyze_module(&module)?;
        } else if !failures.is_empty() {
            let diagnostics = failures
                .into_iter()
                .map(|failure| vb6parse::errors::ErrorDetails {
                    source_name: failure.source_name.clone(),
                    source_content: Box::leak(failure.source_content.to_string().into_boxed_str()),
                    error_offset: failure.error_offset,
                    line_start: failure.line_start,
                    line_end: failure.line_end,
                    kind: failure.kind,
                    severity: failure.severity,
                    labels: failure.labels,
                    notes: failure.notes,
                })
                .collect();
            return Err(crate::error::SemanticError::FileParseError {
                file: module_path.display().to_string(),
                diagnostics,
            });
        }
        Ok(())
    }

    /// Analyze a module file
    pub fn analyze_module(&mut self, module: &vb6parse::files::ModuleFile) -> Result<()> {
        self.current_file = Some(module.name.clone());

        // Create module scope
        let module_scope = self
            .scope_manager
            .push_module_scope(ScopeKind::Global, module.name.clone());

        // Register the module itself as a symbol
        self.register_self_symbol(
            module.name.clone(),
            SymbolKind::Module,
            TypeInfo::new(VBType::Class(module.name.clone())),
            Visibility::Public,
            module_scope,
        )?;

        // Process module-level declarations
        let root = module.cst.to_root_node();
        self.line_index = LineIndex::from_cst_root(&root);
        self.current_line_offset = module.line_offset;
        self.process_statements(&root, root.children(), module.line_offset)?;

        self.scope_manager.pop_scope()?;
        self.finish_file_resolution(root, module_scope, module.line_offset)?;
        Ok(())
    }

    /// Analyze a class reference from the project file class reference
    pub fn analyze_class_reference(
        &mut self,
        class_reference: &vb6parse::files::project::ProjectClassReference,
    ) -> Result<()> {
        let class_path = self.resolve_source_path(class_reference.path);
        let source_file = vb6parse::io::SourceFile::from_file(&class_path).map_err(|e| {
            crate::error::SemanticError::FileReadError {
                file: class_path.display().to_string(),
                message: e.to_string(),
            }
        })?;

        let (class_opt, failures) = vb6parse::files::ClassFile::parse(&source_file).unpack();
        if let Some(class) = class_opt {
            self.analyze_class(&class)?;
        } else if !failures.is_empty() {
            let diagnostics = failures
                .into_iter()
                .map(|failure| vb6parse::errors::ErrorDetails {
                    source_name: failure.source_name.clone(),
                    source_content: Box::leak(failure.source_content.to_string().into_boxed_str()),
                    error_offset: failure.error_offset,
                    line_start: failure.line_start,
                    line_end: failure.line_end,
                    kind: failure.kind,
                    severity: failure.severity,
                    labels: failure.labels,
                    notes: failure.notes,
                })
                .collect();
            return Err(crate::error::SemanticError::FileParseError {
                file: class_path.display().to_string(),
                diagnostics,
            });
        }
        Ok(())
    }

    /// Analyze a class file
    pub fn analyze_class(&mut self, class: &vb6parse::files::ClassFile) -> Result<()> {
        let class_name = class.header.attributes.name.clone();
        self.current_file = Some(class_name.clone());

        // Create class scope
        let class_scope = self
            .scope_manager
            .push_module_scope(ScopeKind::Class, class_name.clone());

        // Register the class itself as a symbol
        self.register_self_symbol(
            class_name.clone(),
            SymbolKind::Class,
            TypeInfo::new(VBType::Class(class_name.clone())),
            Visibility::Public,
            class_scope,
        )?;

        // Process class members (methods, properties, events, declarations)
        let root = class.cst.to_root_node();
        self.line_index = LineIndex::from_cst_root(&root);
        self.current_line_offset = class.line_offset;
        self.process_statements(&root, root.children(), class.line_offset)?;

        self.scope_manager.pop_scope()?;
        self.finish_file_resolution(root, class_scope, class.line_offset)?;
        Ok(())
    }

    /// Analyze a form file by its path
    pub fn analyze_form_path(&mut self, form_reference_path: &str) -> Result<()> {
        let form_path = self.resolve_source_path(form_reference_path);
        let source_file = vb6parse::io::SourceFile::from_file(&form_path).map_err(|e| {
            crate::error::SemanticError::FileReadError {
                file: form_path.display().to_string(),
                message: e.to_string(),
            }
        })?;

        let (form_opt, failures) = vb6parse::files::FormFile::parse(&source_file).unpack();
        if let Some(form) = form_opt {
            self.analyze_form(&form)?;
        } else if !failures.is_empty() {
            let diagnostics = failures
                .into_iter()
                .map(|failure| vb6parse::errors::ErrorDetails {
                    source_name: failure.source_name.clone(),
                    source_content: Box::leak(failure.source_content.to_string().into_boxed_str()),
                    error_offset: failure.error_offset,
                    line_start: failure.line_start,
                    line_end: failure.line_end,
                    kind: failure.kind,
                    severity: failure.severity,
                    labels: failure.labels,
                    notes: failure.notes,
                })
                .collect();
            return Err(crate::error::SemanticError::FileParseError {
                file: form_path.display().to_string(),
                diagnostics,
            });
        }
        Ok(())
    }

    /// Analyze a form file
    pub fn analyze_form(&mut self, form: &vb6parse::files::FormFile) -> Result<()> {
        let form_name = form.form.name().to_string();
        self.current_file = Some(form_name.clone());

        // Create form scope (forms are like classes)
        let form_scope = self
            .scope_manager
            .push_module_scope(ScopeKind::Class, form_name.clone());

        // Register the form itself as a symbol
        self.register_self_symbol(
            form_name.clone(),
            SymbolKind::Form,
            TypeInfo::new(VBType::Class(form_name.clone())),
            Visibility::Public,
            form_scope,
        )?;

        // Register controls and menus as symbols in the form scope
        for control in form.form.controls() {
            self.register_control(control)?;
        }
        for menu in form.form.menus() {
            self.register_menu(menu)?;
        }

        // Process the form code section (event handlers, module-level declarations)
        let root = form.cst.to_root_node();
        self.line_index = LineIndex::from_cst_root(&root);
        self.current_line_offset = form.line_offset;
        self.process_statements(&root, root.children(), form.line_offset)?;

        self.scope_manager.pop_scope()?;
        self.finish_file_resolution(root, form_scope, form.line_offset)?;
        Ok(())
    }

    /// Add a symbol to the current scope
    pub fn add_symbol(&mut self, symbol: Symbol) -> Result<()> {
        match self.scope_manager.add_symbol(symbol) {
            Ok(()) => Ok(()),
            Err(e) => {
                self.errors.push(e.clone());
                Err(e)
            }
        }
    }

    /// Lookup a symbol
    pub fn lookup_symbol(&self, name: &str) -> Option<&Symbol> {
        self.scope_manager.lookup(name)
    }

    /// Get the scope manager (for inspection)
    pub fn scope_manager(&self) -> &ScopeManager {
        &self.scope_manager
    }

    /// Get collected errors
    pub fn errors(&self) -> &[crate::error::SemanticError] {
        &self.errors
    }

    /// Get collected warnings
    pub fn warnings(&self) -> &[String] {
        &self.warnings
    }

    /// Add a warning
    pub fn add_warning(&mut self, message: String) {
        self.warnings.push(message);
    }

    /// The collected query index of resolved identifier occurrences.
    pub fn query_index(&self) -> &QueryIndex {
        &self.query_index
    }

    /// The name of the file currently being analyzed.
    fn current_file_name(&self) -> &str {
        self.current_file.as_deref().unwrap_or("<unknown>")
    }

    /// Create a precise source location for a byte offset in the current file
    /// using the line index built from its CST.
    fn location_at(&self, offset: u32) -> SourceLocation {
        let (line, column) = self.line_index.position(offset);
        SourceLocation {
            file: self.current_file_name().to_string(),
            line: line + self.current_line_offset,
            column,
        }
    }

    /// Record a symbol declaration in the query index.
    fn record_definition(
        &mut self,
        scope_id: usize,
        name: &str,
        start_offset: u32,
        end_offset: u32,
    ) {
        let reference = QueryReference::new(
            ReferenceKind::Definition,
            self.location_at(start_offset),
            start_offset,
            end_offset,
        );
        self.query_index.record(scope_id, name, reference);
    }

    /// Record every resolvable identifier in `node`'s subtree as a usage or
    /// type reference, skipping tokens that are already recorded (definitions).
    ///
    /// Resolution happens against the scope that is current when called, so
    /// procedure bodies must be walked while their parameter scope is pushed.
    fn collect_usages_in(&mut self, node: &CstNode) -> Result<()> {
        let mut prev_significant_kind: Option<SyntaxKind> = None;
        for child in node.descendants() {
            if !child.is_token() {
                continue;
            }
            let kind = child.kind();
            if Self::is_trivia(kind) {
                continue;
            }
            if kind != SyntaxKind::Identifier {
                prev_significant_kind = Some(kind);
                continue;
            }
            let (start, end) = child.byte_range();
            let is_type_reference = matches!(
                prev_significant_kind,
                Some(SyntaxKind::AsKeyword) | Some(SyntaxKind::NewKeyword)
            );
            prev_significant_kind = Some(kind);
            if self
                .query_index
                .is_recorded(self.current_file_name(), start, end)
            {
                continue;
            }
            let Some(symbol) = self.scope_manager.lookup(child.text()) else {
                continue;
            };
            let reference = QueryReference::new(
                if is_type_reference {
                    ReferenceKind::TypeReference
                } else {
                    ReferenceKind::Usage
                },
                self.location_at(start),
                start,
                end,
            );
            self.query_index
                .record(symbol.scope_id, &symbol.name, reference);
        }
        Ok(())
    }

    /// Create a source location for current file
    fn make_location(&self, line: usize, column: usize) -> SourceLocation {
        SourceLocation {
            file: self
                .current_file
                .clone()
                .unwrap_or_else(|| "<unknown>".to_string()),
            line,
            column,
        }
    }

    /// Register the symbol representing the analyzed file itself (module, class, or form)
    fn register_self_symbol(
        &mut self,
        name: String,
        kind: SymbolKind,
        type_info: TypeInfo,
        visibility: Visibility,
        scope_id: usize,
    ) -> Result<()> {
        self.add_symbol(Symbol {
            name,
            kind,
            type_info,
            visibility,
            location: self.make_location(1, 1),
            scope_id,
            attributes: HashMap::new(),
        })
    }

    /// Finish a file's analysis: either queue it for project-wide resolution
    /// or resolve its references immediately and finalize the index.
    fn finish_file_resolution(
        &mut self,
        root: CstNode,
        module_scope: usize,
        line_offset: usize,
    ) -> Result<()> {
        if self.defer_resolution {
            self.pending_resolution.push(PendingResolution {
                file_name: self.current_file_name().to_string(),
                line_offset,
                line_index: std::mem::take(&mut self.line_index),
                root,
                procedure_scopes: std::mem::take(&mut self.procedure_scopes),
                module_scope,
            });
            return Ok(());
        }
        let procedure_scopes = std::mem::take(&mut self.procedure_scopes);
        self.resolve_file(root, module_scope, procedure_scopes)
    }

    /// Resolve every queued file's references against the fully-registered
    /// project symbol table.
    fn resolve_pending(&mut self) -> Result<()> {
        let pending = std::mem::take(&mut self.pending_resolution);
        let original_scope = self.scope_manager.current_scope_id();
        for entry in pending {
            self.current_file = Some(entry.file_name.clone());
            self.current_line_offset = entry.line_offset;
            self.line_index = entry.line_index;
            self.resolve_file(entry.root, entry.module_scope, entry.procedure_scopes)?;
        }
        self.scope_manager.set_current_scope(original_scope);
        Ok(())
    }

    /// Walk a file's statements a second time, resolving identifier usages
    /// now that every declaration in scope is registered.
    fn resolve_file(
        &mut self,
        root: CstNode,
        module_scope: usize,
        procedure_scopes: HashMap<u32, usize>,
    ) -> Result<()> {
        for statement in root.children() {
            if statement.is_token() || Self::is_trivia(statement.kind()) {
                continue;
            }
            let is_procedure = matches!(
                statement.kind(),
                SyntaxKind::SubStatement
                    | SyntaxKind::FunctionStatement
                    | SyntaxKind::PropertyStatement
                    | SyntaxKind::DeclareStatement
            );
            if is_procedure {
                if let Some(&procedure_scope) = procedure_scopes.get(&statement.start_offset()) {
                    self.scope_manager.set_current_scope(procedure_scope);
                }
            } else {
                self.scope_manager.set_current_scope(module_scope);
            }
            self.collect_usages_in(statement)?;
        }
        self.query_index.finalize();
        Ok(())
    }

    /// Process a sequence of statements at module/class/form level
    ///
    /// `line_offset` is the number of lines consumed by the file header (and
    /// therefore absent from the CST). It is added to every computed line so
    /// that reported locations are file-absolute rather than code-section
    /// relative.
    fn process_statements(
        &mut self,
        root: &CstNode,
        statements: &[CstNode],
        line_offset: usize,
    ) -> Result<()> {
        for statement in statements {
            if statement.is_token() || Self::is_trivia(statement.kind()) {
                continue;
            }
            let line = 1 + line_offset + Self::preceding_newlines(root, statement);
            self.process_statement(statement, line)?;
        }
        Ok(())
    }

    /// Dispatch a single module/class-level statement
    fn process_statement(&mut self, statement: &CstNode, line: usize) -> Result<()> {
        match statement.kind() {
            SyntaxKind::DimStatement => self.process_dim_statement(statement, line)?,
            SyntaxKind::TypeStatement => self.process_type_statement(statement, line)?,
            SyntaxKind::EnumStatement => self.process_enum_statement(statement, line)?,
            SyntaxKind::DefTypeStatement => self.process_deftype_statement(statement)?,
            SyntaxKind::SubStatement
            | SyntaxKind::FunctionStatement
            | SyntaxKind::PropertyStatement => self.process_procedure(statement, line)?,
            SyntaxKind::DeclareStatement => self.process_declare_statement(statement, line)?,
            SyntaxKind::EventStatement => self.process_event_statement(statement, line)?,
            SyntaxKind::ImplementsStatement => self.process_implements_statement(statement)?,
            _ => {}
        }
        Ok(())
    }

    /// Process a `Dim` or `Const` statement (both use the `DimStatement` syntax kind)
    fn process_dim_statement(&mut self, statement: &CstNode, _line: usize) -> Result<()> {
        let is_const = statement
            .children()
            .iter()
            .any(|c| c.kind() == SyntaxKind::ConstKeyword);
        let visibility = Self::visibility_from_statement(statement).unwrap_or(Visibility::Private);
        let scope_id = self.scope_manager.current_scope_id();

        for item in Self::parse_declaration_list(statement) {
            let mut attributes = HashMap::new();
            if is_const {
                attributes.insert("const".to_string(), "true".to_string());
            }
            if item.is_array {
                attributes.insert("array".to_string(), "true".to_string());
            }
            if item.with_events {
                attributes.insert("withevents".to_string(), "true".to_string());
            }
            if let Some(value) = item.value {
                attributes.insert("value".to_string(), value);
            }
            let mut type_info = item.type_info;
            if item.is_array {
                type_info.is_array = true;
            }
            let location = self.location_at(item.offset);
            self.add_symbol(Symbol {
                name: item.name.clone(),
                kind: if is_const {
                    SymbolKind::Constant
                } else {
                    SymbolKind::Variable
                },
                type_info,
                visibility,
                location: location.clone(),
                scope_id,
                attributes,
            })?;
            self.record_definition(scope_id, &item.name, item.offset, item.end);
        }
        Ok(())
    }

    /// Process a `Type` definition, registering the type and its members
    fn process_type_statement(&mut self, statement: &CstNode, line: usize) -> Result<()> {
        let Some(name_node) = Self::first_identifier_node(statement) else {
            return Ok(());
        };
        let name = name_node.text().to_string();
        let (name_offset, name_end) = name_node.byte_range();
        let visibility = Self::visibility_from_statement(statement).unwrap_or(Visibility::Private);

        // The type itself lives in the module/class scope; its members live in the type scope
        let scope_id = self.scope_manager.current_scope_id();
        self.add_symbol(Symbol {
            name: name.clone(),
            kind: SymbolKind::UserType,
            type_info: TypeInfo::new(VBType::UserType(name.clone())),
            visibility,
            location: self.location_at(name_offset),
            scope_id,
            attributes: HashMap::new(),
        })?;
        self.record_definition(scope_id, &name, name_offset, name_end);

        let type_scope = self.scope_manager.push_scope(ScopeKind::Type, name);
        if let Some(list) = statement.first_child_by_kind(SyntaxKind::StatementList) {
            let mut line_tokens: Vec<&CstNode> = Vec::new();
            let mut member_line = line + Self::preceding_newlines(statement, list);
            for child in list.children() {
                if child.kind() == SyntaxKind::Newline {
                    self.register_type_member_line(&line_tokens, member_line, type_scope)?;
                    line_tokens.clear();
                    member_line += 1;
                } else if !Self::is_trivia(child.kind()) {
                    line_tokens.push(child);
                }
            }
            self.register_type_member_line(&line_tokens, member_line, type_scope)?;
        }

        self.scope_manager.pop_scope()?;
        Ok(())
    }

    /// Register all type members parsed from a single line of member tokens
    fn register_type_member_line(
        &mut self,
        tokens: &[&CstNode],
        _line: usize,
        scope_id: usize,
    ) -> Result<()> {
        let mut index = 0;
        while index < tokens.len() {
            let Some(item) = Self::parse_single_declarator(tokens, &mut index) else {
                break;
            };
            let mut type_info = item.type_info;
            if item.is_array {
                type_info.is_array = true;
            }
            let location = self.location_at(item.offset);
            self.add_symbol(Symbol {
                name: item.name.clone(),
                kind: SymbolKind::TypeMember,
                type_info,
                visibility: Visibility::Private,
                location: location.clone(),
                scope_id,
                attributes: HashMap::new(),
            })?;
            self.record_definition(scope_id, &item.name, item.offset, item.end);
        }
        Ok(())
    }

    /// Process an `Enum` definition, registering the enum and its members
    fn process_enum_statement(&mut self, statement: &CstNode, line: usize) -> Result<()> {
        let Some(name_node) = Self::first_identifier_node(statement) else {
            return Ok(());
        };
        let name = name_node.text().to_string();
        let (name_offset, name_end) = name_node.byte_range();
        let visibility = Self::visibility_from_statement(statement).unwrap_or(Visibility::Private);

        // The enum itself lives in the module/class scope; its members live in the enum scope
        let scope_id = self.scope_manager.current_scope_id();
        self.add_symbol(Symbol {
            name: name.clone(),
            kind: SymbolKind::Enum,
            type_info: TypeInfo::new(VBType::Enum(name.clone())),
            visibility,
            location: self.location_at(name_offset),
            scope_id,
            attributes: HashMap::new(),
        })?;
        self.record_definition(scope_id, &name, name_offset, name_end);

        let enum_scope = self.scope_manager.push_scope(ScopeKind::Enum, name.clone());

        if let Some(list) = statement.first_child_by_kind(SyntaxKind::StatementList) {
            let mut member_line = line + Self::preceding_newlines(statement, list);
            let mut line_tokens: Vec<&CstNode> = Vec::new();
            for child in list.children() {
                if child.kind() == SyntaxKind::Newline {
                    if !line_tokens.is_empty() {
                        self.register_enum_member(
                            &line_tokens,
                            name.clone(),
                            enum_scope,
                            member_line,
                        )?;
                        line_tokens.clear();
                    }
                    member_line += 1;
                } else if !Self::is_trivia(child.kind()) {
                    line_tokens.push(child);
                }
            }
            if !line_tokens.is_empty() {
                self.register_enum_member(&line_tokens, name.clone(), enum_scope, member_line)?;
            }
        }

        self.scope_manager.pop_scope()?;
        Ok(())
    }

    /// Register a single enum member from one line of significant tokens
    fn register_enum_member(
        &mut self,
        tokens: &[&CstNode],
        enum_name: String,
        enum_scope: usize,
        _line: usize,
    ) -> Result<()> {
        let Some(first) = tokens.first() else {
            return Ok(());
        };
        let member_name = first.text().to_string();
        let (offset, end) = first.byte_range();

        let mut attributes = HashMap::new();
        let mut i = 1;
        if i < tokens.len() && tokens[i].kind() == SyntaxKind::EqualityOperator {
            i += 1;
            let mut parts = Vec::new();
            while i < tokens.len() {
                parts.push(tokens[i].text().to_string());

                i += 1;
            }
            attributes.insert("value".to_string(), parts.concat());
        }

        let location = self.location_at(offset);
        self.add_symbol(Symbol {
            name: member_name.clone(),
            kind: SymbolKind::EnumMember,
            type_info: TypeInfo::new(VBType::Enum(enum_name)),
            visibility: Visibility::Private,
            location: location.clone(),
            scope_id: enum_scope,
            attributes,
        })?;
        self.record_definition(enum_scope, &member_name, offset, end);
        Ok(())
    }

    /// Process a `Sub`, `Function`, or `Property` procedure declaration
    fn process_procedure(&mut self, statement: &CstNode, _line: usize) -> Result<()> {
        let Some(name_node) = Self::first_identifier_node(statement) else {
            return Ok(());
        };
        let name = name_node.text().to_string();
        let (name_offset, name_end) = name_node.byte_range();
        let kind = Self::procedure_symbol_kind(statement);
        let visibility = Self::visibility_from_statement(statement).unwrap_or(Visibility::Public);
        let type_info = match kind {
            SymbolKind::Function => TypeInfo::new(VBType::Function {
                return_type: Box::new(Self::procedure_return_type(statement)),
            }),
            SymbolKind::PropertyGet => Self::procedure_return_type(statement),
            _ => TypeInfo::new(VBType::Sub),
        };

        let scope_id = self.scope_manager.current_scope_id();
        let is_property_accessor = matches!(
            kind,
            SymbolKind::PropertyGet | SymbolKind::PropertyLet | SymbolKind::PropertySet
        );

        // Property Get/Let/Set accessors share a name in VB6 and must be merged
        // into a single property symbol rather than treated as duplicates.
        if is_property_accessor
            && self
                .scope_manager
                .lookup_in_scope(scope_id, &name)
                .is_some()
        {
            if let Some(scope) = self.scope_manager.get_scope_mut(scope_id)
                && let Some(existing) = scope.symbols.get_mut(&name)
            {
                let accessor = match kind {
                    SymbolKind::PropertyGet => "get",
                    SymbolKind::PropertyLet => "let",
                    _ => "set",
                };
                let entry = existing
                    .attributes
                    .entry("accessors".to_string())
                    .or_insert_with(String::new);
                if !entry.is_empty() {
                    entry.push(',');
                }
                entry.push_str(accessor);
                if kind == SymbolKind::PropertyGet {
                    existing.kind = SymbolKind::PropertyGet;
                    existing.type_info = type_info;
                }
            }
        } else {
            let mut attributes = HashMap::new();
            if is_property_accessor {
                let accessor = match kind {
                    SymbolKind::PropertyGet => "get",
                    SymbolKind::PropertyLet => "let",
                    _ => "set",
                };
                attributes.insert("accessors".to_string(), accessor.to_string());
            }
            self.add_symbol(Symbol {
                name: name.clone(),
                kind,
                type_info,
                visibility,
                location: self.location_at(name_offset),
                scope_id,
                attributes,
            })?;
            self.record_definition(scope_id, &name, name_offset, name_end);
        }

        // Remember the procedure scope so the second (reference resolution)
        // pass can restore it, then balance the push.
        let procedure_scope = self.register_parameters(statement, name)?;
        self.procedure_scopes
            .insert(statement.start_offset(), procedure_scope);
        self.scope_manager.pop_scope()?;
        Ok(())
    }

    /// Register a procedure's parameters in a new procedure scope.
    ///
    /// The procedure scope is left pushed on return so the caller can walk the
    /// procedure body against it; the caller is responsible for popping it.
    fn register_parameters(&mut self, statement: &CstNode, name: String) -> Result<usize> {
        let procedure_scope = self.scope_manager.push_scope(ScopeKind::Procedure, name);
        if let Some(param_list) = statement.first_child_by_kind(SyntaxKind::ParameterList) {
            for (param, offset, end) in self.parse_parameter_list(param_list, procedure_scope)? {
                let location = self.location_at(offset);
                self.query_index.record(
                    procedure_scope,
                    &param.name,
                    QueryReference::new(ReferenceKind::Definition, location, offset, end),
                );
                self.add_symbol(param)?;
            }
        }
        Ok(procedure_scope)
    }

    /// Process a `Declare` (external API) declaration
    fn process_declare_statement(&mut self, statement: &CstNode, _line: usize) -> Result<()> {
        let Some(name_node) = Self::first_identifier_node(statement) else {
            return Ok(());
        };
        let name = name_node.text().to_string();
        let (name_offset, name_end) = name_node.byte_range();
        let is_function = statement
            .children()
            .iter()
            .any(|c| c.kind() == SyntaxKind::FunctionKeyword);
        let kind = if is_function {
            SymbolKind::Function
        } else {
            SymbolKind::SubProcedure
        };
        let type_info = if is_function {
            TypeInfo::new(VBType::Function {
                return_type: Box::new(Self::procedure_return_type(statement)),
            })
        } else {
            TypeInfo::new(VBType::Sub)
        };

        let mut attributes = HashMap::new();
        attributes.insert("declare".to_string(), "true".to_string());

        let scope_id = self.scope_manager.current_scope_id();
        self.add_symbol(Symbol {
            name: name.clone(),
            kind,
            type_info,
            visibility: Self::visibility_from_statement(statement).unwrap_or(Visibility::Public),
            location: self.location_at(name_offset),
            scope_id,
            attributes,
        })?;
        self.record_definition(scope_id, &name, name_offset, name_end);

        let procedure_scope = self.register_parameters(statement, name)?;
        self.procedure_scopes
            .insert(statement.start_offset(), procedure_scope);
        self.scope_manager.pop_scope()?;
        Ok(())
    }

    /// Register a `Public Event` declaration
    fn process_event_statement(&mut self, statement: &CstNode, _line: usize) -> Result<()> {
        let Some(name_node) = Self::first_identifier_node(statement) else {
            return Ok(());
        };
        let name = name_node.text().to_string();
        let (name_offset, name_end) = name_node.byte_range();
        let mut attributes = HashMap::new();
        attributes.insert("event".to_string(), "true".to_string());
        let scope_id = self.scope_manager.current_scope_id();
        self.add_symbol(Symbol {
            name: name.clone(),
            kind: SymbolKind::SubProcedure,
            type_info: TypeInfo::new(VBType::Sub),
            visibility: Self::visibility_from_statement(statement).unwrap_or(Visibility::Public),
            location: self.location_at(name_offset),
            scope_id,
            attributes,
        })?;
        self.record_definition(scope_id, &name, name_offset, name_end);
        Ok(())
    }

    /// Record an `Implements <Interface>` clause
    fn process_implements_statement(&mut self, statement: &CstNode) -> Result<()> {
        let mut after_implements = false;
        for child in statement.children() {
            if child.kind() == SyntaxKind::ImplementsKeyword {
                after_implements = true;
                continue;
            }
            if after_implements && child.kind() == SyntaxKind::Identifier {
                self.implements.push(child.text().to_string());
                break;
            }
        }
        Ok(())
    }

    /// Record the implicit type ranges declared by a `DefType` statement
    fn process_deftype_statement(&mut self, statement: &CstNode) -> Result<()> {
        let letters = Self::def_type_letters(statement);
        if letters.is_empty() {
            return Ok(());
        }
        let type_name = Self::def_type_keyword_name(statement);
        let scope_id = self.scope_manager.current_scope_id();
        let self_name = self
            .scope_manager
            .get_scope(scope_id)
            .map(|s| s.name.clone());
        if let Some(self_name) = self_name
            && let Some(scope) = self.scope_manager.get_scope_mut(scope_id)
            && let Some(symbol) = scope.symbols.get_mut(&self_name)
        {
            let entry = symbol
                .attributes
                .entry("deftype".to_string())
                .or_insert_with(String::new);
            if !entry.is_empty() {
                entry.push_str(", ");
            }
            entry.push_str(&format!("{type_name} {letters}"));
        }
        Ok(())
    }

    /// Register a control (and its children) as a symbol in the current form scope
    fn register_control(&mut self, control: &vb6parse::language::Control) -> Result<()> {
        let mut attributes = HashMap::new();
        attributes.insert("control".to_string(), control.kind().to_string());
        if control.index() != 0 {
            attributes.insert("index".to_string(), control.index().to_string());
        }
        if !control.tag().is_empty() {
            attributes.insert("tag".to_string(), control.tag().to_string());
        }
        self.add_symbol(Symbol {
            name: control.name().to_string(),
            kind: SymbolKind::Control,
            type_info: TypeInfo::object(),
            visibility: Visibility::Public,
            location: self.make_location(1, 1),
            scope_id: self.scope_manager.current_scope_id(),
            attributes,
        })?;

        // Recursively register controls nested inside containers
        match control.kind() {
            vb6parse::language::ControlKind::Frame { controls, .. } => {
                for child in controls {
                    self.register_control(child)?;
                }
            }
            vb6parse::language::ControlKind::PictureBox { controls, .. } => {
                for child in controls {
                    self.register_control(child)?;
                }
            }
            _ => {}
        }
        Ok(())
    }

    /// Register a menu (and its sub-menus) as a symbol in the current form scope
    fn register_menu(&mut self, menu: &vb6parse::language::MenuControl) -> Result<()> {
        let mut attributes = HashMap::new();
        attributes.insert("menu".to_string(), "true".to_string());
        if menu.index() != 0 {
            attributes.insert("index".to_string(), menu.index().to_string());
        }
        self.add_symbol(Symbol {
            name: menu.name().to_string(),
            kind: SymbolKind::Control,
            type_info: TypeInfo::object(),
            visibility: Visibility::Public,
            location: self.make_location(1, 1),
            scope_id: self.scope_manager.current_scope_id(),
            attributes,
        })?;
        for sub in menu.sub_menus() {
            self.register_menu(sub)?;
        }
        Ok(())
    }

    /// Get the first identifier token in a statement (the declared name)
    fn first_identifier_node(node: &CstNode) -> Option<&CstNode> {
        node.children()
            .iter()
            .find(|c| c.kind() == SyntaxKind::Identifier)
    }

    /// Get the explicit visibility modifier of a statement, if any
    fn visibility_from_statement(statement: &CstNode) -> Option<Visibility> {
        for child in statement.children() {
            match child.kind() {
                SyntaxKind::PrivateKeyword => return Some(Visibility::Private),
                SyntaxKind::PublicKeyword => return Some(Visibility::Public),
                SyntaxKind::FriendKeyword => return Some(Visibility::Friend),
                _ => {}
            }
        }
        None
    }

    /// Determine the symbol kind of a `Sub`/`Function`/`Property` statement
    fn procedure_symbol_kind(statement: &CstNode) -> SymbolKind {
        match statement.kind() {
            SyntaxKind::FunctionStatement => SymbolKind::Function,
            SyntaxKind::PropertyStatement => {
                if statement
                    .children()
                    .iter()
                    .any(|c| c.kind() == SyntaxKind::LetKeyword)
                {
                    SymbolKind::PropertyLet
                } else if statement
                    .children()
                    .iter()
                    .any(|c| c.kind() == SyntaxKind::SetKeyword)
                {
                    SymbolKind::PropertySet
                } else {
                    SymbolKind::PropertyGet
                }
            }
            _ => SymbolKind::SubProcedure,
        }
    }

    /// Extract the `As <type>` clause from a procedure declaration
    fn procedure_return_type(statement: &CstNode) -> TypeInfo {
        let tokens: Vec<&CstNode> = Self::significant_children(statement).collect();
        for (index, token) in tokens.iter().enumerate() {
            if token.kind() == SyntaxKind::AsKeyword {
                let mut j = index + 1;
                return Self::parse_type_from_tokens(&tokens, &mut j);
            }
        }
        TypeInfo::variant()
    }

    /// Map a type-suffix token (e.g. `$`, `%`, `&`) to its `TypeInfo`
    fn type_suffix_type(kind: SyntaxKind) -> Option<TypeInfo> {
        Some(match kind {
            SyntaxKind::DollarSign => TypeInfo::string(),
            SyntaxKind::Percent => TypeInfo::integer(),
            SyntaxKind::Ampersand => TypeInfo::long(),
            SyntaxKind::ExclamationMark => TypeInfo::new(VBType::Single),
            SyntaxKind::AtSign => TypeInfo::new(VBType::Currency),
            _ => return None,
        })
    }

    /// Parse a type expression starting at `tokens[*index]`, advancing the index past the type
    fn parse_type_from_tokens(tokens: &[&CstNode], index: &mut usize) -> TypeInfo {
        if *index >= tokens.len() {
            return TypeInfo::unknown();
        }
        match tokens[*index].kind() {
            SyntaxKind::NewKeyword => {
                *index += 1;
                TypeInfo::new(VBType::Class(Self::join_type_name(tokens, index)))
            }
            SyntaxKind::IntegerKeyword => {
                *index += 1;
                TypeInfo::integer()
            }
            SyntaxKind::LongKeyword => {
                *index += 1;
                TypeInfo::long()
            }
            SyntaxKind::SingleKeyword => {
                *index += 1;
                TypeInfo::new(VBType::Single)
            }
            SyntaxKind::DoubleKeyword => {
                *index += 1;
                TypeInfo::new(VBType::Double)
            }
            SyntaxKind::CurrencyKeyword => {
                *index += 1;
                TypeInfo::new(VBType::Currency)
            }
            SyntaxKind::StringKeyword => {
                *index += 1;
                TypeInfo::string()
            }
            SyntaxKind::BooleanKeyword => {
                *index += 1;
                TypeInfo::boolean()
            }
            SyntaxKind::ByteKeyword => {
                *index += 1;
                TypeInfo::new(VBType::Byte)
            }
            SyntaxKind::DateKeyword => {
                *index += 1;
                TypeInfo::new(VBType::Date)
            }
            SyntaxKind::VariantKeyword => {
                *index += 1;
                TypeInfo::variant()
            }
            SyntaxKind::ObjectKeyword => {
                *index += 1;
                TypeInfo::object()
            }
            SyntaxKind::Identifier => {
                TypeInfo::new(VBType::UserType(Self::join_type_name(tokens, index)))
            }
            _ => TypeInfo::unknown(),
        }
    }

    /// Consume `identifier (. identifier)*` tokens and return the joined name
    fn join_type_name(tokens: &[&CstNode], index: &mut usize) -> String {
        let mut parts = Vec::new();
        while *index < tokens.len() {
            match tokens[*index].kind() {
                SyntaxKind::Identifier | SyntaxKind::PeriodOperator => {
                    parts.push(tokens[*index].text().to_string());
                    *index += 1;
                }
                _ => break,
            }
        }
        parts.concat()
    }

    /// Parse the declarators of a `Dim`/`Const` statement (comma-separated)
    fn parse_declaration_list(node: &CstNode) -> Vec<DeclaredItem> {
        let tokens: Vec<&CstNode> = Self::significant_children(node).collect();
        let mut items = Vec::new();

        let mut i = 0;
        while i < tokens.len()
            && matches!(
                tokens[i].kind(),
                SyntaxKind::DimKeyword
                    | SyntaxKind::ConstKeyword
                    | SyntaxKind::PrivateKeyword
                    | SyntaxKind::PublicKeyword
                    | SyntaxKind::FriendKeyword
                    | SyntaxKind::StaticKeyword
            )
        {
            i += 1;
        }

        Self::parse_comma_separated_declarators(&tokens, &mut i, &mut items);
        items
    }

    /// Parse comma-separated declarators starting at `*index` into `items`
    fn parse_comma_separated_declarators(
        tokens: &[&CstNode],
        index: &mut usize,
        items: &mut Vec<DeclaredItem>,
    ) {
        while *index < tokens.len() {
            let Some(item) = Self::parse_single_declarator(tokens, index) else {
                break;
            };
            items.push(item);
            if *index < tokens.len() && tokens[*index].kind() == SyntaxKind::Comma {
                *index += 1;
            } else {
                break;
            }
        }
    }

    /// Parse a single declarator starting at `tokens[*index]`
    fn parse_single_declarator(tokens: &[&CstNode], index: &mut usize) -> Option<DeclaredItem> {
        let mut with_events = false;
        while *index < tokens.len() && tokens[*index].kind() == SyntaxKind::WithEventsKeyword {
            with_events = true;
            *index += 1;
        }
        if *index >= tokens.len() {
            return None;
        }

        let offset = tokens[*index].start_offset();
        let end = tokens[*index].end_offset();
        let name = tokens[*index].text().to_string();
        *index += 1;

        let mut type_info = None;
        let mut is_array = false;

        // Array bounds
        if *index < tokens.len() && tokens[*index].kind() == SyntaxKind::LeftParenthesis {
            is_array = true;
            let mut depth = 1;
            *index += 1;
            while *index < tokens.len() && depth > 0 {
                if tokens[*index].kind() == SyntaxKind::LeftParenthesis {
                    depth += 1;
                } else if tokens[*index].kind() == SyntaxKind::RightParenthesis {
                    depth -= 1;
                    if depth == 0 {
                        *index += 1;
                        break;
                    }
                }
                *index += 1;
            }
        }

        // Type suffix
        if *index < tokens.len()
            && let Some(suffix_type) = Self::type_suffix_type(tokens[*index].kind())
        {
            type_info = Some(suffix_type);
            *index += 1;
        }

        // As <type>
        if *index < tokens.len() && tokens[*index].kind() == SyntaxKind::AsKeyword {
            *index += 1;
            type_info = Some(Self::parse_type_from_tokens(tokens, index));
        }

        // Const value
        let mut value = None;
        if *index < tokens.len() && tokens[*index].kind() == SyntaxKind::EqualityOperator {
            *index += 1;
            let mut parts = Vec::new();
            while *index < tokens.len() && tokens[*index].kind() != SyntaxKind::Comma {
                parts.push(tokens[*index].text().to_string());
                *index += 1;
            }
            value = Some(parts.concat());
        }

        Some(DeclaredItem {
            name,
            type_info: type_info.unwrap_or_else(TypeInfo::variant),
            is_array,
            with_events,
            value,
            offset,
            end,
        })
    }

    /// Extract parameter symbols from a `ParameterList` node.
    ///
    /// Returns each parameter symbol together with the byte range of its name
    /// token so the caller can record precise definition references.
    fn parse_parameter_list(
        &self,
        list: &CstNode,
        procedure_scope: usize,
    ) -> Result<Vec<(Symbol, u32, u32)>> {
        let tokens: Vec<&CstNode> = Self::significant_children(list).collect();
        let mut symbols = Vec::new();

        let mut i = 0;
        if i < tokens.len() && tokens[i].kind() == SyntaxKind::LeftParenthesis {
            i += 1;
        }

        while i < tokens.len() && tokens[i].kind() != SyntaxKind::RightParenthesis {
            let mut optional = false;
            let mut by_ref = false;
            let mut param_array = false;

            // Modifiers (Optional/ByVal/ByRef/ParamArray)
            loop {
                if i >= tokens.len() {
                    break;
                }
                match tokens[i].kind() {
                    SyntaxKind::OptionalKeyword => {
                        optional = true;
                        i += 1;
                    }
                    SyntaxKind::ByRefKeyword => {
                        by_ref = true;
                        i += 1;
                    }
                    SyntaxKind::ByValKeyword => {
                        i += 1;
                    }
                    SyntaxKind::ParamArrayKeyword => {
                        param_array = true;
                        i += 1;
                    }
                    SyntaxKind::LeftParenthesis => {
                        i += 1;
                    }
                    _ => break,
                }
            }

            if i >= tokens.len() || tokens[i].kind() == SyntaxKind::RightParenthesis {
                break;
            }

            let offset = tokens[i].start_offset();
            let end = tokens[i].end_offset();
            let name = tokens[i].text().to_string();
            i += 1;
            let mut is_array = false;
            if i < tokens.len() && tokens[i].kind() == SyntaxKind::LeftParenthesis {
                is_array = true;
                let mut depth = 1;
                i += 1;
                while i < tokens.len() && depth > 0 {
                    if tokens[i].kind() == SyntaxKind::LeftParenthesis {
                        depth += 1;
                    } else if tokens[i].kind() == SyntaxKind::RightParenthesis {
                        depth -= 1;
                        if depth == 0 {
                            i += 1;
                            break;
                        }
                    }
                    i += 1;
                }
            }

            let mut type_info = None;
            if i < tokens.len()
                && let Some(suffix_type) = Self::type_suffix_type(tokens[i].kind())
            {
                type_info = Some(suffix_type);
                i += 1;
            }
            if i < tokens.len() && tokens[i].kind() == SyntaxKind::AsKeyword {
                i += 1;
                type_info = Some(Self::parse_type_from_tokens(&tokens, &mut i));
            }

            // Default value
            let mut default_value = None;
            if i < tokens.len() && tokens[i].kind() == SyntaxKind::EqualityOperator {
                i += 1;
                let mut parts = Vec::new();
                while i < tokens.len()
                    && tokens[i].kind() != SyntaxKind::Comma
                    && tokens[i].kind() != SyntaxKind::RightParenthesis
                {
                    parts.push(tokens[i].text().to_string());
                    i += 1;
                }
                default_value = Some(parts.concat());
            }

            let mut type_info = type_info.unwrap_or_else(TypeInfo::variant);
            type_info.is_reference = by_ref;
            if is_array {
                type_info.is_array = true;
            }

            let mut attributes = HashMap::new();
            if optional {
                attributes.insert("optional".to_string(), "true".to_string());
            }
            if param_array {
                attributes.insert("paramarray".to_string(), "true".to_string());
            }
            if let Some(value) = default_value {
                attributes.insert("default".to_string(), value);
            }

            symbols.push((
                Symbol {
                    name,
                    kind: SymbolKind::Parameter,
                    type_info,
                    visibility: Visibility::Private,
                    location: self.location_at(offset),
                    scope_id: procedure_scope,
                    attributes,
                },
                offset,
                end,
            ));

            if i < tokens.len() && tokens[i].kind() == SyntaxKind::Comma {
                i += 1;
            }
        }

        Ok(symbols)
    }

    /// Get the name of the `Def*` keyword of a `DefType` statement
    fn def_type_keyword_name(statement: &CstNode) -> String {
        statement
            .children()
            .iter()
            .find(|c| Self::is_def_type_keyword(c.kind()))
            .map(|c| c.text().to_string())
            .unwrap_or_default()
    }

    /// Returns true if the kind is a `Def*` keyword (`DefInt`, `DefStr`, ...)
    fn is_def_type_keyword(kind: SyntaxKind) -> bool {
        matches!(
            kind,
            SyntaxKind::DefBoolKeyword
                | SyntaxKind::DefByteKeyword
                | SyntaxKind::DefIntKeyword
                | SyntaxKind::DefLngKeyword
                | SyntaxKind::DefCurKeyword
                | SyntaxKind::DefSngKeyword
                | SyntaxKind::DefDblKeyword
                | SyntaxKind::DefDecKeyword
                | SyntaxKind::DefDateKeyword
                | SyntaxKind::DefStrKeyword
                | SyntaxKind::DefObjKeyword
                | SyntaxKind::DefVarKeyword
        )
    }

    /// Collect the letter range text of a `DefType` statement (e.g. `A-Z`, `A,B`)
    fn def_type_letters(statement: &CstNode) -> String {
        let mut parts = Vec::new();
        for child in statement.children() {
            match child.kind() {
                SyntaxKind::Identifier => parts.push(child.text().to_string()),
                SyntaxKind::SubtractionOperator => parts.push("-".to_string()),
                SyntaxKind::Comma => parts.push(",".to_string()),
                _ => {}
            }
        }
        parts.concat()
    }

    /// Returns true if the syntax kind is trivia (whitespace, newlines, comments, line continuations)
    fn is_trivia(kind: SyntaxKind) -> bool {
        matches!(
            kind,
            SyntaxKind::Whitespace
                | SyntaxKind::Newline
                | SyntaxKind::Underscore
                | SyntaxKind::EndOfLineComment
                | SyntaxKind::RemComment
        )
    }

    /// Iterate over the direct children of `node` that are not trivia
    fn significant_children(node: &CstNode) -> impl Iterator<Item = &CstNode> {
        node.children()
            .iter()
            .filter(|c| !Self::is_trivia(c.kind()))
    }

    /// Count the Newline tokens in a subtree
    fn count_newlines(node: &CstNode) -> usize {
        if node.kind() == SyntaxKind::Newline {
            return 1;
        }
        node.children().iter().map(Self::count_newlines).sum()
    }

    /// Returns true if `target` is `node` or a descendant of `node`
    fn contains(node: &CstNode, target: &CstNode) -> bool {
        if std::ptr::eq(node, target) {
            return true;
        }
        node.children().iter().any(|c| Self::contains(c, target))
    }

    /// Count the Newline tokens that occur before `target` within `ancestor`'s subtree
    fn preceding_newlines(ancestor: &CstNode, target: &CstNode) -> usize {
        if std::ptr::eq(ancestor, target) {
            return 0;
        }
        let mut count = 0;
        for child in ancestor.children() {
            if std::ptr::eq(child, target) {
                return count;
            }
            if Self::contains(child, target) {
                return count + Self::preceding_newlines(child, target);
            }
            count += Self::count_newlines(child);
        }
        count
    }
}

/// A single declarator parsed from a `Dim`/`Const` statement (or a `Type` member)
struct DeclaredItem {
    name: String,
    type_info: TypeInfo,
    is_array: bool,
    with_events: bool,
    value: Option<String>,
    /// Inclusive start byte offset of the declared name token.
    offset: u32,
    /// Exclusive end byte offset of the declared name token.
    end: u32,
}

impl Default for SemanticAnalyzer {
    fn default() -> Self {
        Self::new()
    }
}

/// A file whose references are waiting to be resolved once the whole project
/// has been registered, so that forward and cross-module references resolve.
struct PendingResolution {
    /// The file name recorded on occurrences.
    file_name: String,
    /// Lines consumed by the file header and absent from the CST.
    line_offset: usize,
    /// Position index for the file's CST.
    line_index: LineIndex,
    /// The file's CST root.
    root: CstNode,
    /// Statement start offset → procedure scope id.
    procedure_scopes: HashMap<u32, usize>,
    /// The file's module/class/form scope id.
    module_scope: usize,
}

/// Result of semantic analysis
#[derive(Debug, Clone)]
pub struct AnalysisResult {
    /// Final scope manager with all symbols
    pub scope_manager: ScopeManager,

    /// Errors found during analysis
    pub errors: Vec<crate::error::SemanticError>,

    /// Warnings generated
    pub warnings: Vec<String>,

    /// References that a registered resolver supplied symbols for
    pub resolved_references: Vec<ReferenceInfo>,

    /// References no registered resolver could handle
    pub unresolved_references: Vec<ReferenceInfo>,

    /// Resolved identifier occurrences (definitions and usages), keyed by
    /// symbol and queryable by position.
    pub query_index: QueryIndex,
}

impl AnalysisResult {
    /// Check if analysis was successful (no errors)
    pub fn is_successful(&self) -> bool {
        self.errors.is_empty()
    }

    /// Get error count
    pub fn error_count(&self) -> usize {
        self.errors.len()
    }

    /// Get warning count
    pub fn warning_count(&self) -> usize {
        self.warnings.len()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::symbols::{SymbolKind, Visibility};
    use crate::types::TypeInfo;
    use std::{collections::HashMap, fs};
    use tempfile::tempdir;

    #[test]
    fn analyze_empty_project() {
        let mut analyzer = SemanticAnalyzer::new();
        let project = vb6parse::files::ProjectFile::default();

        let result = analyzer
            .analyze_project(&project)
            .expect("Analysis should succeed");

        assert!(result.is_successful());
        assert_eq!(result.error_count(), 0);
        assert_eq!(result.warning_count(), 0);
    }

    #[test]
    fn add_symbol_and_lookup_in_current_scope() {
        let mut analyzer = SemanticAnalyzer::new();
        let child_scope_id = analyzer
            .scope_manager
            .push_scope(ScopeKind::Procedure, "proc".to_string());

        let symbol = Symbol {
            name: "counter".to_string(),
            kind: SymbolKind::Variable,
            type_info: TypeInfo::integer(),
            visibility: Visibility::Private,
            location: SourceLocation {
                file: "Module1.bas".to_string(),
                line: 1,
                column: 1,
            },
            scope_id: child_scope_id,
            attributes: HashMap::new(),
        };

        analyzer.add_symbol(symbol).expect("Symbol should be added");

        let resolved = analyzer
            .lookup_symbol("counter")
            .expect("Symbol should be resolvable");
        assert_eq!(resolved.name, "counter");
        assert_eq!(resolved.kind, SymbolKind::Variable);
    }

    #[test]
    fn duplicate_symbol_records_an_error() {
        let mut analyzer = SemanticAnalyzer::new();

        let first = Symbol {
            name: "value".to_string(),
            kind: SymbolKind::Variable,
            type_info: TypeInfo::integer(),
            visibility: Visibility::Private,
            location: SourceLocation {
                file: "Module1.bas".to_string(),
                line: 1,
                column: 1,
            },
            scope_id: analyzer.scope_manager.global_scope_id(),
            attributes: HashMap::new(),
        };
        let second = Symbol {
            name: "value".to_string(),
            kind: SymbolKind::Variable,
            type_info: TypeInfo::integer(),
            visibility: Visibility::Private,
            location: SourceLocation {
                file: "Module1.bas".to_string(),
                line: 2,
                column: 1,
            },
            scope_id: analyzer.scope_manager.global_scope_id(),
            attributes: HashMap::new(),
        };

        analyzer
            .add_symbol(first)
            .expect("First symbol should be added");
        let duplicate = analyzer.add_symbol(second);

        assert!(duplicate.is_err());
        assert!(matches!(
            analyzer.errors().first(),
            Some(crate::error::SemanticError::DuplicateSymbol { .. })
        ));
    }

    #[test]
    fn analyze_module_reference_reports_missing_files() {
        let mut analyzer = SemanticAnalyzer::new();
        let module_reference = vb6parse::files::project::ProjectModuleReference {
            name: "Missing",
            path: "/tmp/does-not-exist.bas",
        };

        let error = analyzer
            .analyze_module_reference(&module_reference)
            .expect_err("Missing files should fail analysis");

        assert!(matches!(
            error,
            crate::error::SemanticError::FileReadError { .. }
        ));
    }

    #[test]
    fn analyze_module_reference_sets_current_file_for_valid_module() {
        let temp_dir = tempdir().expect("Temporary directory should be created");
        let module_path = temp_dir.path().join("Module1.bas");
        fs::write(
            &module_path,
            "Attribute VB_Name = \"Module1\"\nOption Explicit\n",
        )
        .unwrap();

        let mut analyzer = SemanticAnalyzer::new();
        let module_reference = vb6parse::files::project::ProjectModuleReference {
            name: "Module1",
            path: module_path
                .to_str()
                .expect("Module path should be valid UTF-8"),
        };

        analyzer
            .analyze_module_reference(&module_reference)
            .expect("Valid module should be analyzed");

        assert_eq!(analyzer.current_file.as_deref(), Some("Module1"));
        assert_eq!(
            analyzer
                .scope_manager
                .get_scopes_by_kind(ScopeKind::Global)
                .len(),
            2
        );
    }

    fn symbol_in_global_scopes<'a>(
        analyzer: &'a SemanticAnalyzer,
        name: &str,
    ) -> Option<&'a Symbol> {
        analyzer
            .scope_manager()
            .get_scopes_by_kind(ScopeKind::Global)
            .iter()
            .find_map(|scope| scope.symbols.get(name))
    }

    fn symbol_in_scope_kind<'a>(
        analyzer: &'a SemanticAnalyzer,
        kind: ScopeKind,
        name: &str,
    ) -> Option<&'a Symbol> {
        analyzer
            .scope_manager()
            .get_scopes_by_kind(kind)
            .iter()
            .find_map(|scope| scope.symbols.get(name))
    }

    #[test]
    fn analyze_module_collects_declarations() {
        let temp_dir = tempdir().expect("Temporary directory should be created");
        let module_path = temp_dir.path().join("Module1.bas");
        fs::write(
            &module_path,
            r#"Attribute VB_Name = "Module1"
Option Explicit

Private Const APP_NAME = "Test"
Private m_counter As Long
Dim g_values(10) As Integer

Public Type Customer
    Name As String
    Id As Long
End Type

Private Enum Status
    Inactive = 0
    Active
End Enum

Private Sub Initialize()
End Sub

Public Function GetCount() As Long
End Function

Public Sub Increment(ByVal amount As Long, ByRef total As Long)
End Sub
"#,
        )
        .unwrap();

        let source = vb6parse::io::SourceFile::from_file(&module_path).unwrap();
        let (module_opt, failures) = vb6parse::files::ModuleFile::parse(&source).unpack();
        assert!(failures.is_empty(), "Parse failures: {:?}", failures);
        let module = module_opt.expect("Module should parse");

        let mut analyzer = SemanticAnalyzer::new();
        analyzer
            .analyze_module(&module)
            .expect("Analysis should succeed");
        assert!(
            analyzer.errors().is_empty(),
            "Analysis produced errors: {:?}",
            analyzer.errors()
        );

        // The module itself
        let module_symbol = symbol_in_global_scopes(&analyzer, "Module1").expect("Module symbol");
        assert_eq!(module_symbol.kind, SymbolKind::Module);

        // Constants
        let app_name = symbol_in_global_scopes(&analyzer, "APP_NAME").expect("Const symbol");
        assert_eq!(app_name.kind, SymbolKind::Constant);
        assert_eq!(
            app_name.attributes.get("const").map(String::as_str),
            Some("true")
        );

        // Variables and arrays
        let counter = symbol_in_global_scopes(&analyzer, "m_counter").expect("Var symbol");
        assert_eq!(counter.kind, SymbolKind::Variable);
        assert_eq!(counter.type_info.kind, VBType::Long);

        let g_values = symbol_in_global_scopes(&analyzer, "g_values").expect("Array symbol");
        assert!(g_values.type_info.is_array);
        assert_eq!(g_values.type_info.kind, VBType::Integer);

        // User-defined type and its members
        let customer = symbol_in_global_scopes(&analyzer, "Customer").expect("Type symbol");
        assert_eq!(customer.kind, SymbolKind::UserType);
        let name_member =
            symbol_in_scope_kind(&analyzer, ScopeKind::Type, "Name").expect("Type member");
        assert_eq!(name_member.kind, SymbolKind::TypeMember);
        assert_eq!(name_member.type_info.kind, VBType::String);
        let id_member =
            symbol_in_scope_kind(&analyzer, ScopeKind::Type, "Id").expect("Type member");
        assert_eq!(id_member.type_info.kind, VBType::Long);

        // Enum and its members
        let status = symbol_in_global_scopes(&analyzer, "Status").expect("Enum symbol");
        assert_eq!(status.kind, SymbolKind::Enum);
        let inactive =
            symbol_in_scope_kind(&analyzer, ScopeKind::Enum, "Inactive").expect("Enum member");
        assert_eq!(inactive.kind, SymbolKind::EnumMember);
        assert_eq!(
            inactive.attributes.get("value").map(String::as_str),
            Some("0")
        );
        let active =
            symbol_in_scope_kind(&analyzer, ScopeKind::Enum, "Active").expect("Enum member");
        assert_eq!(active.kind, SymbolKind::EnumMember);

        // Procedures
        let initialize = symbol_in_global_scopes(&analyzer, "Initialize").expect("Sub symbol");
        assert_eq!(initialize.kind, SymbolKind::SubProcedure);
        assert_eq!(initialize.visibility, Visibility::Private);

        let get_count = symbol_in_global_scopes(&analyzer, "GetCount").expect("Function symbol");
        assert_eq!(get_count.kind, SymbolKind::Function);
        assert_eq!(get_count.visibility, Visibility::Public);
        assert!(matches!(
            get_count.type_info.kind,
            VBType::Function { ref return_type } if return_type.kind == VBType::Long
        ));

        // Parameters
        let amount = symbol_in_scope_kind(&analyzer, ScopeKind::Procedure, "amount")
            .expect("Parameter symbol");
        assert_eq!(amount.kind, SymbolKind::Parameter);
        assert_eq!(amount.type_info.kind, VBType::Long);
        assert!(!amount.type_info.is_reference);
        let total = symbol_in_scope_kind(&analyzer, ScopeKind::Procedure, "total")
            .expect("Parameter symbol");
        assert_eq!(total.kind, SymbolKind::Parameter);
        assert_eq!(total.type_info.kind, VBType::Long);
        assert!(total.type_info.is_reference);
    }

    #[test]
    fn analyze_class_collects_members() {
        let temp_dir = tempdir().expect("Temporary directory should be created");
        let class_path = temp_dir.path().join("Counter.cls");
        fs::write(
            &class_path,
            r#"VERSION 1.0 CLASS
BEGIN
  MultiUse = -1  'True
  Persistable = 0  'NotPersistable
  DataBindingBehavior = 0  'vbNone
  DataSourceBehavior = 0  'vbNone
  MTSTransactionMode = 0  'NotAnMTSObject
END
Attribute VB_Name = "Counter"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = True
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False

Private m_value As Long

Public Property Get Value() As Long
    Value = m_value
End Property

Public Property Let Value(v As Long)
    m_value = v
End Property

Public Sub Increment()
End Sub

Public Event StatusChanged(NewStatus As String)

Implements TaskInterface
"#,
        )
        .unwrap();

        let source = vb6parse::io::SourceFile::from_file(&class_path).unwrap();
        let (class_opt, failures) = vb6parse::files::ClassFile::parse(&source).unpack();
        assert!(failures.is_empty(), "Parse failures: {:?}", failures);
        let class = class_opt.expect("Class should parse");

        let mut analyzer = SemanticAnalyzer::new();
        analyzer
            .analyze_class(&class)
            .expect("Analysis should succeed");
        assert!(
            analyzer.errors().is_empty(),
            "Analysis produced errors: {:?}",
            analyzer.errors()
        );

        // The class itself
        let class_symbol =
            symbol_in_scope_kind(&analyzer, ScopeKind::Class, "Counter").expect("Class symbol");
        assert_eq!(class_symbol.kind, SymbolKind::Class);

        // Class-level variable
        let m_value = symbol_in_scope_kind(&analyzer, ScopeKind::Class, "m_value")
            .expect("Class variable symbol");
        assert_eq!(m_value.kind, SymbolKind::Variable);
        assert_eq!(m_value.type_info.kind, VBType::Long);

        // Property Get + Let are merged into a single symbol
        let value = symbol_in_scope_kind(&analyzer, ScopeKind::Class, "Value").expect("Property");
        assert_eq!(value.kind, SymbolKind::PropertyGet);
        assert_eq!(value.type_info.kind, VBType::Long);
        assert_eq!(
            value.attributes.get("accessors").map(String::as_str),
            Some("get,let")
        );

        // Method
        let increment =
            symbol_in_scope_kind(&analyzer, ScopeKind::Class, "Increment").expect("Method symbol");
        assert_eq!(increment.kind, SymbolKind::SubProcedure);

        // Event
        let event = symbol_in_scope_kind(&analyzer, ScopeKind::Class, "StatusChanged")
            .expect("Event symbol");
        assert_eq!(
            event.attributes.get("event").map(String::as_str),
            Some("true")
        );

        // Implements clause was recorded
        assert_eq!(analyzer.implements, vec!["TaskInterface"]);
    }

    #[test]
    fn analyze_form_collects_controls_and_handlers() {
        let temp_dir = tempdir().expect("Temporary directory should be created");
        let form_path = temp_dir.path().join("Form1.frm");
        fs::write(
            &form_path,
            r#"VERSION 5.00
Begin VB.Form Form1
   Caption = "Test Form"
   Begin VB.CommandButton Command1
      Caption = "Click Me"
   End
   Begin VB.Menu mnuFile
      Caption = "&File"
      Begin VB.Menu mnuNew
         Caption = "&New"
      End
   End
End
Attribute VB_Name = "Form1"

Private Sub Command1_Click()
End Sub
"#,
        )
        .unwrap();

        let source = vb6parse::io::SourceFile::from_file(&form_path).unwrap();
        let (form_opt, failures) = vb6parse::files::FormFile::parse(&source).unpack();
        assert!(failures.is_empty(), "Parse failures: {:?}", failures);
        let form = form_opt.expect("Form should parse");

        let mut analyzer = SemanticAnalyzer::new();
        analyzer
            .analyze_form(&form)
            .expect("Analysis should succeed");
        assert!(
            analyzer.errors().is_empty(),
            "Analysis produced errors: {:?}",
            analyzer.errors()
        );

        // The form itself
        let form_symbol =
            symbol_in_scope_kind(&analyzer, ScopeKind::Class, "Form1").expect("Form symbol");
        assert_eq!(form_symbol.kind, SymbolKind::Form);

        // Controls
        let command =
            symbol_in_scope_kind(&analyzer, ScopeKind::Class, "Command1").expect("Control symbol");
        assert_eq!(command.kind, SymbolKind::Control);
        assert_eq!(
            command.attributes.get("control").map(String::as_str),
            Some("CommandButton")
        );

        // Menus (including sub-menus)
        let menu =
            symbol_in_scope_kind(&analyzer, ScopeKind::Class, "mnuFile").expect("Menu symbol");
        assert_eq!(
            menu.attributes.get("menu").map(String::as_str),
            Some("true")
        );
        let sub_menu =
            symbol_in_scope_kind(&analyzer, ScopeKind::Class, "mnuNew").expect("Sub-menu symbol");
        assert_eq!(sub_menu.kind, SymbolKind::Control);

        // Event handler from the code section
        let handler = symbol_in_scope_kind(&analyzer, ScopeKind::Class, "Command1_Click")
            .expect("Handler symbol");
        assert_eq!(handler.kind, SymbolKind::SubProcedure);
    }

    #[test]
    fn analyze_project_resolves_references() {
        let temp_dir = tempdir().expect("Temporary directory should be created");
        let module_path = temp_dir.path().join("Module1.bas");
        fs::write(
            &module_path,
            r#"Attribute VB_Name = "Module1"
Option Explicit

Public Function Foo() As Long
End Function
"#,
        )
        .unwrap();

        let project_source = format!(
            "Type=Exe\n\
             Reference=*\\G{{00020430-0000-0000-C000-000000000046}}#2.0#0#C:\\Windows\\System32\\stdole2.tlb#OLE Automation\n\
             Module=Module1; {}\n",
            module_path.display()
        );
        let source = vb6parse::io::SourceFile::from_string("Project1.vbp", project_source);
        let (project_opt, failures) = vb6parse::files::ProjectFile::parse(&source).unpack();
        assert!(failures.is_empty(), "Parse failures: {:?}", failures);
        let project = project_opt.expect("Project should parse");

        let resolver = crate::references::StaticReferenceResolver::new(
            "ole-automation",
            vec!["OLE Automation".to_string()],
            vec![Symbol {
                name: "Now".to_string(),
                kind: SymbolKind::Function,
                type_info: TypeInfo::new(VBType::Date),
                visibility: Visibility::Public,
                location: SourceLocation {
                    file: "<reference>".to_string(),
                    line: 1,
                    column: 1,
                },
                scope_id: 0,
                attributes: HashMap::new(),
            }],
        );

        let mut analyzer = SemanticAnalyzer::new();
        analyzer.register_reference_resolver(Box::new(resolver));
        let result = analyzer
            .analyze_project(&project)
            .expect("Analysis should succeed");

        assert!(result.errors.is_empty());
        assert_eq!(result.warnings.len(), 0);
        assert_eq!(result.resolved_references.len(), 1);
        assert_eq!(
            result.resolved_references[0].display_name(),
            "OLE Automation"
        );
        assert!(result.unresolved_references.is_empty());

        // The reference library symbols are visible through normal lookups
        let now = analyzer.lookup_symbol("Now").expect("Reference symbol");
        assert_eq!(now.kind, SymbolKind::Function);
        assert_eq!(now.type_info.kind, VBType::Date);

        // The reference was stored in its own Reference scope
        assert_eq!(
            analyzer
                .scope_manager()
                .get_scopes_by_kind(ScopeKind::Reference)
                .len(),
            1
        );
    }

    #[test]
    fn analyze_project_reports_unresolved_reference_warning() {
        let temp_dir = tempdir().expect("Temporary directory should be created");
        let module_path = temp_dir.path().join("Module1.bas");
        fs::write(
            &module_path,
            r#"Attribute VB_Name = "Module1"
Option Explicit
"#,
        )
        .unwrap();

        let project_source = format!(
            "Type=Exe\n\
             Reference=*\\G{{4AC69860-FB10-11CF-86DA-00AA00608FCC}}#1.0#0#C:\\Program Files\\Common Files\\Microsoft Shared\\DAO\\dao360.dll#Microsoft DAO 3.6 Object Library\n\
             Module=Module1; {}\n",
            module_path.display()
        );
        let source = vb6parse::io::SourceFile::from_string("Project1.vbp", project_source);
        let (project_opt, failures) = vb6parse::files::ProjectFile::parse(&source).unpack();
        assert!(failures.is_empty(), "Parse failures: {:?}", failures);
        let project = project_opt.expect("Project should parse");

        let mut analyzer = SemanticAnalyzer::new();
        let result = analyzer
            .analyze_project(&project)
            .expect("Analysis should succeed");

        // An unhandled reference warns but does not fail the analysis
        assert!(result.errors.is_empty());
        assert_eq!(result.warning_count(), 1);
        assert!(result.warnings[0].contains("Unresolved project reference"));
        assert!(result.unresolved_references.len() == 1);
        assert_eq!(
            result.unresolved_references[0].display_name(),
            "Microsoft DAO 3.6 Object Library"
        );
        assert!(result.resolved_references.is_empty());
    }

    /// Write a module file to `temp_dir` and return its path.
    fn write_module(temp_dir: &tempfile::TempDir, name: &str, body: &str) -> String {
        let path = temp_dir.path().join(format!("{name}.bas"));
        fs::write(
            &path,
            format!("Attribute VB_Name = \"{name}\"\nOption Explicit\n{body}"),
        )
        .unwrap();
        path.to_str().unwrap().to_string()
    }

    /// Write a class file to `temp_dir` and return its path.
    fn write_class(temp_dir: &tempfile::TempDir, name: &str, body: &str) -> String {
        let path = temp_dir.path().join(format!("{name}.cls"));
        fs::write(
            &path,
            format!(
                "VERSION 1.0 CLASS\n\
                 BEGIN\n\
                   MultiUse = -1  'True\n\
                 END\n\
                 Attribute VB_Name = \"{name}\"\n\
                 Attribute VB_GlobalNameSpace = False\n\
                 Attribute VB_Creatable = True\n\
                 Attribute VB_PredeclaredId = False\n\
                 Attribute VB_Exposed = False\n\
                 {body}"
            ),
        )
        .unwrap();
        path.to_str().unwrap().to_string()
    }

    /// Build an OLE Automation reference resolver that supplies the given symbols.
    fn ole_resolver(symbols: Vec<Symbol>) -> crate::references::StaticReferenceResolver {
        crate::references::StaticReferenceResolver::new(
            "ole-automation",
            vec!["OLE Automation".to_string()],
            symbols,
        )
    }

    fn reference_symbol(name: &str, kind: SymbolKind) -> Symbol {
        Symbol {
            name: name.to_string(),
            kind,
            type_info: TypeInfo::variant(),
            visibility: Visibility::Public,
            location: SourceLocation {
                file: "<reference>".to_string(),
                line: 1,
                column: 1,
            },
            scope_id: 0,
            attributes: HashMap::new(),
        }
    }

    #[test]
    fn analyze_project_shadows_reference_symbols_with_module_symbols() {
        let temp_dir = tempdir().expect("Temporary directory should be created");
        let module_path = write_module(
            &temp_dir,
            "Module1",
            "\nPublic Function Now() As Date\nEnd Function\n",
        );

        let project_source = format!(
            "Type=Exe\n\
             Reference=*\\G{{00020430-0000-0000-C000-000000000046}}#2.0#0#C:\\Windows\\System32\\stdole2.tlb#OLE Automation\n\
             Module=Module1; {module_path}\n"
        );
        let source = vb6parse::io::SourceFile::from_string("Project1.vbp", project_source);
        let (project_opt, failures) = vb6parse::files::ProjectFile::parse(&source).unpack();
        assert!(failures.is_empty(), "Parse failures: {:?}", failures);
        let project = project_opt.expect("Project should parse");

        let mut analyzer = SemanticAnalyzer::new();
        analyzer.register_reference_resolver(Box::new(ole_resolver(vec![reference_symbol(
            "Now",
            SymbolKind::Constant,
        )])));
        analyzer
            .analyze_project(&project)
            .expect("Analysis should succeed");

        // The module's Function shadows the library's Constant.
        let now = analyzer
            .lookup_symbol("Now")
            .expect("Symbol should resolve");
        assert_eq!(now.kind, SymbolKind::Function);
    }

    #[test]
    fn analyze_project_resolves_paths_against_base_dir() {
        let temp_dir = tempdir().expect("Temporary directory should be created");
        let module_path = temp_dir.path().join("BaseDirModule.bas");
        fs::write(
            &module_path,
            r#"Attribute VB_Name = "BaseDirModule"
Option Explicit

Public Function Foo() As Long
End Function
"#,
        )
        .unwrap();

        // The `.vbp` references the module with a bare relative path, the way
        // VB6 writes project files.
        let project_source = "Type=Exe\nModule=BaseDirModule; BaseDirModule.bas\n";
        let source = vb6parse::io::SourceFile::from_string("Project1.vbp", project_source);
        let (project_opt, failures) = vb6parse::files::ProjectFile::parse(&source).unpack();
        assert!(failures.is_empty(), "Parse failures: {:?}", failures);
        let project = project_opt.expect("Project should parse");

        // Without a base dir the bare relative path cannot be found.
        let mut analyzer = SemanticAnalyzer::new();
        assert!(analyzer.analyze_project(&project).is_err());

        // With the base dir set to the project directory it is found.
        let mut analyzer = SemanticAnalyzer::new();
        analyzer.set_base_dir(temp_dir.path());
        let result = analyzer
            .analyze_project(&project)
            .expect("Analysis should succeed with base dir");
        assert!(result.errors.is_empty());
        assert!(analyzer.lookup_symbol("Foo").is_some());
    }

    #[test]
    fn analyze_project_resolves_names_in_vbp_entry_order() {
        let temp_dir = tempdir().expect("Temporary directory should be created");
        // The class is listed BEFORE the module in the .vbp file, so its
        // declaration must win the ambiguous cross-module name.
        let class_path = write_class(
            &temp_dir,
            "ClassA",
            "\nPublic Function FindMe() As Long\nEnd Function\n",
        );
        let module_path = write_module(&temp_dir, "ModuleB", "\nPublic Sub FindMe()\nEnd Sub\n");

        let project_source = format!(
            "Type=Exe\n\
             Class=ClassA; {class_path}\n\
             Module=ModuleB; {module_path}\n"
        );
        let source = vb6parse::io::SourceFile::from_string("Project1.vbp", project_source);
        let (project_opt, failures) = vb6parse::files::ProjectFile::parse(&source).unpack();
        assert!(failures.is_empty(), "Parse failures: {:?}", failures);
        let project = project_opt.expect("Project should parse");

        let mut analyzer = SemanticAnalyzer::new();
        analyzer
            .analyze_project(&project)
            .expect("Analysis should succeed");

        // ClassA's Function wins over ModuleB's Sub because it appears first.
        let find_me = analyzer
            .lookup_symbol("FindMe")
            .expect("Symbol should resolve");
        assert_eq!(find_me.kind, SymbolKind::Function);

        // And the symbol lives in ClassA's scope.
        let class_scopes = analyzer
            .scope_manager()
            .get_scopes_by_kind(ScopeKind::Class);
        let class_scope = class_scopes
            .iter()
            .find(|scope| scope.name == "ClassA")
            .expect("ClassA scope");
        assert_eq!(find_me.scope_id, class_scope.id);
    }

    #[test]
    fn analyze_project_hides_private_symbols_from_other_modules() {
        let temp_dir = tempdir().expect("Temporary directory should be created");
        let private_path = write_module(
            &temp_dir,
            "ModuleA",
            "\nPrivate Function Secret() As Long\nEnd Function\n",
        );
        let public_path = write_module(
            &temp_dir,
            "ModuleB",
            "\nPublic Function Visible() As Long\nEnd Function\n",
        );

        let project_source = format!(
            "Type=Exe\n\
             Module=ModuleA; {private_path}\n\
             Module=ModuleB; {public_path}\n"
        );
        let source = vb6parse::io::SourceFile::from_string("Project1.vbp", project_source);
        let (project_opt, failures) = vb6parse::files::ProjectFile::parse(&source).unpack();
        assert!(failures.is_empty(), "Parse failures: {:?}", failures);
        let project = project_opt.expect("Project should parse");

        let mut analyzer = SemanticAnalyzer::new();
        analyzer
            .analyze_project(&project)
            .expect("Analysis should succeed");

        // ModuleA's Private symbol does not leak into the project namespace...
        assert!(analyzer.lookup_symbol("Secret").is_none());
        // ...but its Public symbol is visible.
        assert!(analyzer.lookup_symbol("Visible").is_some());
    }
}