tsz-core 0.1.9

Core TypeScript compiler and type checker library
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
//! Parallel Processing Module
//!
//! Provides parallel file parsing and processing using Rayon.
//! This enables significant speedups on multi-core machines.
//!
//! # Architecture
//!
//! The compilation pipeline has these parallelization opportunities:
//!
//! 1. **Parsing** - Each file can be parsed independently (embarrassingly parallel)
//! 2. **Binding** - After parsing, binding can be parallelized per-file
//! 3. **Type Checking** - Function bodies can be checked in parallel
//!    (once global symbols are merged)
//!
//! # Usage
//!
//! ```rust,ignore
//! use tsz::parallel::parse_files_parallel;
//!
//! let files = vec![
//!     ("src/a.ts".to_string(), "let a = 1;".to_string()),
//!     ("src/b.ts".to_string(), "let b = 2;".to_string()),
//! ];
//!
//! let results = parse_files_parallel(files);
//! // results is Vec<ParseResult> with parsed ASTs
//! ```

use crate::binder::BinderOptions;
use crate::binder::BinderState;
use crate::binder::state::{BinderStateScopeInputs, DeclarationArenaMap};
use crate::binder::{
    FlowNodeArena, FlowNodeId, Scope, ScopeId, SymbolArena, SymbolId, SymbolTable,
};
#[cfg(not(target_arch = "wasm32"))]
use crate::config::resolve_default_lib_files;
use crate::emitter::ScriptTarget;
use crate::lib_loader;
use crate::parser::NodeIndex;
use crate::parser::node::NodeArena;
use crate::parser::{ParseDiagnostic, ParserState};
use anyhow::{Context, Result, bail};
#[cfg(not(target_arch = "wasm32"))]
use rayon::prelude::{
    IndexedParallelIterator, IntoParallelIterator, IntoParallelRefIterator, ParallelIterator,
};
use rustc_hash::{FxHashMap, FxHashSet};
use std::path::{Path, PathBuf};
use std::sync::Arc;
#[cfg(not(target_arch = "wasm32"))]
use std::sync::Once;
use tsz_common::interner::{Atom, Interner};

type ModuleExportEntry = FxHashMap<String, (String, Option<String>)>;
type Reexports = FxHashMap<String, ModuleExportEntry>;

#[cfg(target_arch = "wasm32")]
fn resolve_default_lib_files(_target: ScriptTarget) -> anyhow::Result<Vec<PathBuf>> {
    Ok(Vec::new())
}

#[cfg(not(target_arch = "wasm32"))]
static RAYON_POOL_INIT: Once = Once::new();

/// Ensure Rayon global pool is configured once with stack size suitable for checker recursion.
///
/// We initialize lazily to avoid paying global pool startup cost for single-file sequential paths.
#[cfg(not(target_arch = "wasm32"))]
pub fn ensure_rayon_global_pool() {
    RAYON_POOL_INIT.call_once(|| {
        // If the pool was already initialized through another rayon call, keep going.
        let _ = rayon::ThreadPoolBuilder::new()
            .stack_size(8 * 1024 * 1024)
            .build_global();
    });
}

#[cfg(target_arch = "wasm32")]
pub fn ensure_rayon_global_pool() {}

/// Conditionally use parallel or sequential iteration based on target.
/// For WASM, Rayon parallelism creates oversubscription when combined with
/// external worker-level parallelism (e.g., Node worker threads in conformance tests).
/// This causes worker crashes and OOM issues.
///
/// Usage:
/// - `maybe_parallel_iter!(collection)` for `.par_iter()` / `.iter()`
/// - `maybe_parallel_into!(collection)` for `.into_par_iter()` / `.into_iter()`
#[cfg(target_arch = "wasm32")]
macro_rules! maybe_parallel_iter {
    ($iter:expr) => {
        $iter.iter()
    };
}

#[cfg(not(target_arch = "wasm32"))]
macro_rules! maybe_parallel_iter {
    ($iter:expr) => {
        $iter.par_iter()
    };
}

#[cfg(target_arch = "wasm32")]
macro_rules! maybe_parallel_into {
    ($iter:expr) => {
        $iter.into_iter()
    };
}

#[cfg(not(target_arch = "wasm32"))]
macro_rules! maybe_parallel_into {
    ($iter:expr) => {
        $iter.into_par_iter()
    };
}

/// Result of parsing a single file
pub struct ParseResult {
    /// File name
    pub file_name: String,
    /// The parsed source file node index
    pub source_file: NodeIndex,
    /// The arena containing all nodes
    pub arena: NodeArena,
    /// Parse diagnostics
    pub parse_diagnostics: Vec<ParseDiagnostic>,
}

/// Parse multiple files in parallel using Parser
///
/// Each file is parsed independently, producing its own arena.
/// This is optimal for initial parsing before symbol resolution.
///
/// # Arguments
/// * `files` - Vector of (`file_name`, `source_text`) pairs
///
/// # Returns
/// Vector of `ParseResult` for each file
pub fn parse_files_parallel(files: Vec<(String, String)>) -> Vec<ParseResult> {
    #[cfg(not(target_arch = "wasm32"))]
    ensure_rayon_global_pool();

    maybe_parallel_into!(files)
        .map(|(file_name, source_text)| {
            let mut parser = ParserState::new(file_name.clone(), source_text);
            let source_file = parser.parse_source_file();

            // Consume the parser and take its arena/diagnostics
            let (arena, parse_diagnostics) = parser.into_parts();

            ParseResult {
                file_name,
                source_file,
                arena,
                parse_diagnostics,
            }
        })
        .collect()
}

/// Parse a single file (for comparison/testing)
pub fn parse_file_single(file_name: String, source_text: String) -> ParseResult {
    let mut parser = ParserState::new(file_name.clone(), source_text);
    let source_file = parser.parse_source_file();

    // Consume the parser and take its arena/diagnostics
    let (arena, parse_diagnostics) = parser.into_parts();

    ParseResult {
        file_name,
        source_file,
        arena,
        parse_diagnostics,
    }
}

/// Statistics about parallel parsing performance
#[derive(Debug, Clone)]
pub struct ParallelStats {
    /// Number of files parsed
    pub file_count: usize,
    /// Total source bytes
    pub total_bytes: usize,
    /// Total nodes created
    pub total_nodes: usize,
    /// Number of parse errors
    pub error_count: usize,
}

// =============================================================================
// Parallel Binding
// =============================================================================

/// Result of binding a single file
pub struct BindResult {
    /// File name
    pub file_name: String,
    /// The parsed source file node index
    pub source_file: NodeIndex,
    /// The arena containing all nodes
    pub arena: Arc<NodeArena>,
    /// Symbols created in this file
    pub symbols: SymbolArena,
    /// File-level symbol table (exports, declarations)
    pub file_locals: SymbolTable,
    /// Ambient module declarations by specifier
    pub declared_modules: FxHashSet<String>,
    /// Module exports keyed by specifier or file name
    pub module_exports: FxHashMap<String, SymbolTable>,
    /// Node-to-symbol mapping
    pub node_symbols: FxHashMap<u32, SymbolId>,
    /// Symbol-to-arena mapping for cross-file declaration lookup (including lib symbols)
    pub symbol_arenas: FxHashMap<SymbolId, Arc<NodeArena>>,
    /// Declaration-to-arena mapping for precise cross-file declaration lookup
    pub declaration_arenas: DeclarationArenaMap,
    /// Persistent scopes for stateless checking
    pub scopes: Vec<Scope>,
    /// Map from AST node to scope ID
    pub node_scope_ids: FxHashMap<u32, ScopeId>,
    /// Parse diagnostics
    pub parse_diagnostics: Vec<ParseDiagnostic>,
    /// Shorthand ambient modules (`declare module "foo"` without body)
    pub shorthand_ambient_modules: FxHashSet<String>,
    /// Global augmentations (interface declarations inside `declare global` blocks)
    pub global_augmentations: FxHashMap<String, Vec<crate::binder::GlobalAugmentation>>,
    /// Module augmentations (interface/type declarations inside `declare module 'x'` blocks)
    /// Maps module specifier -> [`ModuleAugmentation`]
    pub module_augmentations: FxHashMap<String, Vec<crate::binder::ModuleAugmentation>>,
    /// Re-exports: tracks `export { x } from 'module'` declarations
    pub reexports: Reexports,
    /// Wildcard re-exports: tracks `export * from 'module'` declarations
    pub wildcard_reexports: FxHashMap<String, Vec<String>>,
    /// Lib binders for global type resolution (Array, String, etc.)
    /// These are merged from lib.d.ts files and enable cross-file symbol lookup
    pub lib_binders: Vec<Arc<BinderState>>,
    /// Symbol IDs that originated from lib files (pre-merge local IDs)
    pub lib_symbol_ids: FxHashSet<SymbolId>,
    /// Reverse mapping from user-local lib symbol IDs to (`lib_binder_ptr`, `original_local_id`)
    pub lib_symbol_reverse_remap: FxHashMap<SymbolId, (usize, SymbolId)>,
    /// Flow nodes for control flow analysis
    pub flow_nodes: FlowNodeArena,
    /// Node-to-flow mapping: tracks which flow node was active at each AST node
    pub node_flow: FxHashMap<u32, FlowNodeId>,
    /// Map from switch clause `NodeIndex` to parent switch statement `NodeIndex`
    /// Used by control flow analysis for switch exhaustiveness checking
    pub switch_clause_to_switch: FxHashMap<u32, NodeIndex>,
    /// Whether this file is an external module (has imports/exports)
    pub is_external_module: bool,
    /// Expando property assignments detected during binding
    pub expando_properties: FxHashMap<String, FxHashSet<String>>,
}

/// Parse and bind multiple files in parallel
///
/// Each file is parsed and bound independently. The binding creates
/// file-local symbols which can later be merged into a global scope.
///
/// # Arguments
/// * `files` - Vector of (`file_name`, `source_text`) pairs
///
/// # Returns
/// Vector of `BindResult` for each file
pub fn parse_and_bind_parallel(files: Vec<(String, String)>) -> Vec<BindResult> {
    #[cfg(not(target_arch = "wasm32"))]
    ensure_rayon_global_pool();

    maybe_parallel_into!(files)
        .map(|(file_name, source_text)| {
            // Skip parsing .json files - they should not be parsed as TypeScript.
            // JSON module imports should be resolved during module resolution and
            // emit TS2732 if resolveJsonModule is false.
            if file_name.ends_with(".json") {
                // Create empty result for JSON files
                let arena = NodeArena::new();
                let source_file = NodeIndex::NONE;
                let parse_diagnostics = Vec::new();

                let binder = BinderState::new();

                return BindResult {
                    file_name,
                    source_file,
                    arena: Arc::new(arena),
                    symbols: binder.symbols,
                    file_locals: binder.file_locals,
                    declared_modules: binder.declared_modules,
                    module_exports: binder.module_exports,
                    node_symbols: binder.node_symbols,
                    symbol_arenas: binder.symbol_arenas,
                    declaration_arenas: binder.declaration_arenas,
                    scopes: binder.scopes,
                    node_scope_ids: binder.node_scope_ids,
                    parse_diagnostics,
                    shorthand_ambient_modules: binder.shorthand_ambient_modules,
                    global_augmentations: binder.global_augmentations,
                    module_augmentations: binder.module_augmentations,
                    reexports: binder.reexports,
                    wildcard_reexports: binder.wildcard_reexports,
                    lib_binders: Vec::new(),
                    lib_symbol_ids: binder.lib_symbol_ids,
                    lib_symbol_reverse_remap: binder.lib_symbol_reverse_remap,
                    flow_nodes: binder.flow_nodes,
                    node_flow: binder.node_flow,
                    switch_clause_to_switch: binder.switch_clause_to_switch,
                    is_external_module: false,
                    expando_properties: FxHashMap::default(),
                };
            }

            // Parse
            let mut parser = ParserState::new(file_name.clone(), source_text);
            let source_file = parser.parse_source_file();

            let (arena, parse_diagnostics) = parser.into_parts();

            // Bind
            let mut binder = BinderState::new();
            binder.set_debug_file(&file_name);
            binder.bind_source_file(&arena, source_file);

            BindResult {
                file_name,
                source_file,
                arena: Arc::new(arena),
                symbols: binder.symbols,
                file_locals: binder.file_locals,
                declared_modules: binder.declared_modules,
                module_exports: binder.module_exports,
                node_symbols: binder.node_symbols,
                symbol_arenas: binder.symbol_arenas,
                declaration_arenas: binder.declaration_arenas,
                scopes: binder.scopes,
                node_scope_ids: binder.node_scope_ids,
                parse_diagnostics,
                shorthand_ambient_modules: binder.shorthand_ambient_modules,
                global_augmentations: binder.global_augmentations,
                module_augmentations: binder.module_augmentations,
                reexports: binder.reexports,
                wildcard_reexports: binder.wildcard_reexports,
                lib_binders: Vec::new(), // No libs in this path
                lib_symbol_ids: binder.lib_symbol_ids,
                lib_symbol_reverse_remap: binder.lib_symbol_reverse_remap,
                flow_nodes: binder.flow_nodes,
                node_flow: binder.node_flow,
                switch_clause_to_switch: std::mem::take(&mut binder.switch_clause_to_switch),
                is_external_module: binder.is_external_module,
                expando_properties: std::mem::take(&mut binder.expando_properties),
            }
        })
        .collect()
}

/// Bind a single file (for comparison/testing)
pub fn parse_and_bind_single(file_name: String, source_text: String) -> BindResult {
    let mut parser = ParserState::new(file_name.clone(), source_text);
    let source_file = parser.parse_source_file();

    let (arena, parse_diagnostics) = parser.into_parts();

    let mut binder = BinderState::new();
    binder.set_debug_file(&file_name);
    binder.bind_source_file(&arena, source_file);

    BindResult {
        file_name,
        source_file,
        arena: Arc::new(arena),
        symbols: binder.symbols,
        file_locals: binder.file_locals,
        declared_modules: binder.declared_modules,
        module_exports: binder.module_exports,
        node_symbols: binder.node_symbols,
        symbol_arenas: binder.symbol_arenas,
        declaration_arenas: binder.declaration_arenas,
        scopes: binder.scopes,
        node_scope_ids: binder.node_scope_ids,
        parse_diagnostics,
        shorthand_ambient_modules: binder.shorthand_ambient_modules,
        global_augmentations: binder.global_augmentations,
        module_augmentations: binder.module_augmentations,
        reexports: binder.reexports,
        wildcard_reexports: binder.wildcard_reexports,
        lib_binders: Vec::new(), // No libs in this path
        lib_symbol_ids: binder.lib_symbol_ids,
        lib_symbol_reverse_remap: binder.lib_symbol_reverse_remap,
        flow_nodes: binder.flow_nodes,
        node_flow: binder.node_flow,
        switch_clause_to_switch: std::mem::take(&mut binder.switch_clause_to_switch),
        is_external_module: binder.is_external_module,
        expando_properties: std::mem::take(&mut binder.expando_properties),
    }
}

/// Statistics about parallel binding performance
#[derive(Debug, Clone)]
pub struct BindStats {
    /// Number of files bound
    pub file_count: usize,
    /// Total nodes across all files
    pub total_nodes: usize,
    /// Total symbols created
    pub total_symbols: usize,
    /// Number of parse errors
    pub parse_error_count: usize,
}

/// Parse and bind files with statistics
pub fn parse_and_bind_with_stats(files: Vec<(String, String)>) -> (Vec<BindResult>, BindStats) {
    let file_count = files.len();
    let results = parse_and_bind_parallel(files);

    let total_nodes: usize = results.iter().map(|r| r.arena.len()).sum();
    let total_symbols: usize = results.iter().map(|r| r.symbols.len()).sum();
    let parse_error_count: usize = results.iter().map(|r| r.parse_diagnostics.len()).sum();

    let stats = BindStats {
        file_count,
        total_nodes,
        total_symbols,
        parse_error_count,
    };

    (results, stats)
}

/// Load lib.d.ts files and create `LibContext` objects for the binder.
///
/// This function loads the specified lib.d.ts files (e.g., lib.dom.d.ts, lib.es*.d.ts)
/// and returns `LibContext` objects that can be used during binding to resolve global
/// symbols like `console`, `Array`, `Promise`, etc.
///
/// This is similar to `load_lib_files_for_contexts` in driver.rs but returns
/// Arc<LibFile> objects for use with `merge_lib_symbols`.
pub fn load_lib_files_for_binding(lib_files: &[&Path]) -> Vec<Arc<lib_loader::LibFile>> {
    use crate::parser::ParserState;
    use rayon::prelude::{IntoParallelIterator, ParallelIterator};

    if lib_files.is_empty() {
        return Vec::new();
    }

    // Collect paths that exist
    let files_to_load: Vec<_> = lib_files
        .iter()
        .filter_map(|p| {
            let path = p.to_path_buf();
            path.exists().then_some(path)
        })
        .collect();

    // Parse and bind lib files in parallel for faster startup
    files_to_load
        .into_par_iter()
        .filter_map(|lib_path| {
            // Read the lib file content
            let source_text = std::fs::read_to_string(&lib_path).ok()?;

            // Parse the lib file
            let file_name = lib_path.to_string_lossy().to_string();
            let mut lib_parser = ParserState::new(file_name.clone(), source_text);
            let source_file_idx = lib_parser.parse_source_file();

            // Skip if there are parse errors
            if !lib_parser.get_diagnostics().is_empty() {
                return None;
            }

            // Bind the lib file
            let mut lib_binder = BinderState::new();
            lib_binder.bind_source_file(lib_parser.get_arena(), source_file_idx);

            // Create the LibFile
            let arena = Arc::new(lib_parser.into_arena());
            let binder = Arc::new(lib_binder);

            Some(Arc::new(lib_loader::LibFile::new(file_name, arena, binder)))
        })
        .collect()
}

/// Load lib.d.ts files from disk for binding, failing on any load/parse error.
///
/// Unlike `load_lib_files_for_binding`, this enforces strict disk-loading semantics:
/// missing files, unreadable files, and parse errors are surfaced as hard errors.
pub fn load_lib_files_for_binding_strict(
    lib_files: &[&Path],
) -> Result<Vec<Arc<lib_loader::LibFile>>> {
    use crate::parser::ParserState;
    use rayon::prelude::{IntoParallelRefIterator, ParallelIterator};

    if lib_files.is_empty() {
        return Ok(Vec::new());
    }

    lib_files
        .par_iter()
        .map(|path| {
            let lib_path = path.to_path_buf();
            if !lib_path.exists() {
                bail!("lib file not found on disk: {}", lib_path.display());
            }

            let source_text = std::fs::read_to_string(&lib_path)
                .with_context(|| format!("failed to read lib file {}", lib_path.display()))?;

            let file_name = lib_path.to_string_lossy().to_string();
            let mut lib_parser = ParserState::new(file_name.clone(), source_text);
            let source_file_idx = lib_parser.parse_source_file();
            let diagnostics = lib_parser.get_diagnostics();
            if !diagnostics.is_empty() {
                let first = &diagnostics[0];
                bail!(
                    "failed to parse lib file {} ({}:{}): {}",
                    lib_path.display(),
                    first.start,
                    first.length,
                    first.message
                );
            }

            let mut lib_binder = BinderState::new();
            lib_binder.bind_source_file(lib_parser.get_arena(), source_file_idx);

            let arena = Arc::new(lib_parser.into_arena());
            let binder = Arc::new(lib_binder);
            Ok(Arc::new(lib_loader::LibFile::new(file_name, arena, binder)))
        })
        .collect()
}

/// Parse and bind multiple files in parallel with lib symbol injection.
///
/// This is the main entry point for compilation that includes lib.d.ts symbols.
/// Lib files are loaded first, then each file is parsed and bound with lib symbols
/// merged into its binder.
///
/// # Arguments
/// * `files` - Vector of (`file_name`, `source_text`) pairs
/// * `lib_files` - Optional list of lib file paths to load
///
/// # Returns
/// Vector of `BindResult` for each file
pub fn parse_and_bind_parallel_with_lib_files(
    files: Vec<(String, String)>,
    lib_files: &[&Path],
) -> Vec<BindResult> {
    // Load lib files for binding.
    // This path is intentionally strict so missing/unreadable lib files are not ignored.
    let lib_contexts = load_lib_files_for_binding_strict(lib_files)
        .unwrap_or_else(|err| panic!("failed to load lib files from disk: {err}"));

    // Parse and bind with lib symbols
    parse_and_bind_parallel_with_libs(files, &lib_contexts)
}

/// Parse and bind multiple files in parallel with lib contexts.
///
/// Lib symbols are injected into each file's binder during binding,
/// enabling resolution of global symbols like `console`, `Array`, etc.
///
/// # Arguments
/// * `files` - Vector of (`file_name`, `source_text`) pairs
/// * `lib_files` - Lib files to merge into each binder
///
/// # Returns
/// Vector of `BindResult` for each file
pub fn parse_and_bind_parallel_with_libs(
    files: Vec<(String, String)>,
    lib_files: &[Arc<lib_loader::LibFile>],
) -> Vec<BindResult> {
    if files.len() <= 1 {
        return files
            .into_iter()
            .map(|(file_name, source_text)| bind_file_with_libs(file_name, source_text, lib_files))
            .collect();
    }

    #[cfg(not(target_arch = "wasm32"))]
    ensure_rayon_global_pool();

    maybe_parallel_into!(files)
        .map(|(file_name, source_text)| bind_file_with_libs(file_name, source_text, lib_files))
        .collect()
}

fn bind_file_with_libs(
    file_name: String,
    source_text: String,
    lib_files: &[Arc<lib_loader::LibFile>],
) -> BindResult {
    // Skip parsing .json files - they should not be parsed as TypeScript.
    // JSON module imports should be resolved during module resolution and
    // emit TS2732 if resolveJsonModule is false.
    if file_name.ends_with(".json") {
        // Create empty result for JSON files
        let arena = NodeArena::new();
        let source_file = NodeIndex::NONE;
        let parse_diagnostics = Vec::new();

        let binder = BinderState::new();
        let lib_binders = binder.lib_binders.clone();

        return BindResult {
            file_name,
            source_file,
            arena: Arc::new(arena),
            symbols: binder.symbols,
            file_locals: binder.file_locals,
            declared_modules: binder.declared_modules,
            module_exports: binder.module_exports,
            node_symbols: binder.node_symbols,
            symbol_arenas: binder.symbol_arenas,
            declaration_arenas: binder.declaration_arenas,
            scopes: binder.scopes,
            node_scope_ids: binder.node_scope_ids,
            parse_diagnostics,
            shorthand_ambient_modules: binder.shorthand_ambient_modules,
            global_augmentations: binder.global_augmentations,
            module_augmentations: binder.module_augmentations,
            reexports: binder.reexports,
            wildcard_reexports: binder.wildcard_reexports,
            lib_binders,
            lib_symbol_ids: binder.lib_symbol_ids,
            lib_symbol_reverse_remap: binder.lib_symbol_reverse_remap,
            flow_nodes: binder.flow_nodes,
            node_flow: binder.node_flow,
            switch_clause_to_switch: binder.switch_clause_to_switch,
            is_external_module: false,
            expando_properties: FxHashMap::default(),
        };
    }

    // Parse
    let mut parser = ParserState::new(file_name.clone(), source_text);
    let source_file = parser.parse_source_file();

    let (arena, parse_diagnostics) = parser.into_parts();

    // Bind with lib symbols
    let mut binder = BinderState::new();
    binder.set_debug_file(&file_name);

    // IMPORTANT: Merge lib symbols BEFORE binding source file
    // so that symbols like console, Array, Promise are available during binding
    if !lib_files.is_empty() {
        binder.merge_lib_symbols(lib_files);
    }

    binder.bind_source_file(&arena, source_file);

    // Extract lib_binders from binder before it's moved
    let lib_binders = binder.lib_binders.clone();

    BindResult {
        file_name,
        source_file,
        arena: Arc::new(arena),
        symbols: binder.symbols,
        file_locals: binder.file_locals,
        declared_modules: binder.declared_modules,
        module_exports: binder.module_exports,
        node_symbols: binder.node_symbols,
        symbol_arenas: binder.symbol_arenas,
        declaration_arenas: binder.declaration_arenas,
        scopes: binder.scopes,
        node_scope_ids: binder.node_scope_ids,
        parse_diagnostics,
        shorthand_ambient_modules: binder.shorthand_ambient_modules,
        global_augmentations: binder.global_augmentations,
        module_augmentations: binder.module_augmentations,
        reexports: binder.reexports,
        wildcard_reexports: binder.wildcard_reexports,
        lib_binders,
        lib_symbol_ids: binder.lib_symbol_ids,
        lib_symbol_reverse_remap: binder.lib_symbol_reverse_remap,
        flow_nodes: binder.flow_nodes,
        node_flow: binder.node_flow,
        switch_clause_to_switch: std::mem::take(&mut binder.switch_clause_to_switch),
        is_external_module: binder.is_external_module,
        expando_properties: std::mem::take(&mut binder.expando_properties),
    }
}

// =============================================================================
// Symbol Merging
// =============================================================================

/// A bound file ready for type checking
pub struct BoundFile {
    /// File name
    pub file_name: String,
    /// The parsed source file node index
    pub source_file: NodeIndex,
    /// The arena containing all nodes (owned by this file)
    pub arena: Arc<NodeArena>,
    /// Node-to-symbol mapping (symbol IDs are global after merge)
    pub node_symbols: FxHashMap<u32, SymbolId>,
    /// Persistent scopes (symbol IDs are global after merge)
    pub scopes: Vec<Scope>,
    /// Map from AST node to scope ID
    pub node_scope_ids: FxHashMap<u32, ScopeId>,
    /// Parse diagnostics
    pub parse_diagnostics: Vec<ParseDiagnostic>,
    /// Global augmentations (interface declarations inside `declare global` blocks)
    pub global_augmentations: FxHashMap<String, Vec<crate::binder::GlobalAugmentation>>,
    /// Module augmentations (interface/type declarations inside `declare module 'x'` blocks)
    pub module_augmentations: FxHashMap<String, Vec<crate::binder::ModuleAugmentation>>,
    /// Flow nodes for control flow analysis
    pub flow_nodes: FlowNodeArena,
    /// Node-to-flow mapping: tracks which flow node was active at each AST node
    pub node_flow: FxHashMap<u32, FlowNodeId>,
    /// Map from switch clause `NodeIndex` to parent switch statement `NodeIndex`
    /// Used by control flow analysis for switch exhaustiveness checking
    pub switch_clause_to_switch: FxHashMap<u32, NodeIndex>,
    /// Whether this file is an external module (has imports/exports)
    pub is_external_module: bool,
    /// Expando property assignments detected during binding
    pub expando_properties: FxHashMap<String, FxHashSet<String>>,
}

use tsz_solver::TypeInterner;

/// Merged program state after parallel binding
pub struct MergedProgram {
    /// All bound files
    pub files: Vec<BoundFile>,
    /// Global symbol arena (all symbols from all files, with remapped IDs)
    pub symbols: SymbolArena,
    /// Symbol-to-arena mapping for declaration lookup (legacy, stores last arena)
    pub symbol_arenas: FxHashMap<SymbolId, Arc<NodeArena>>,
    /// Declaration-to-arena mapping for precise cross-file declaration lookup
    /// Key: (`SymbolId`, `NodeIndex` of declaration) -> Arena(s) containing that declaration
    pub declaration_arenas: DeclarationArenaMap,
    /// Global symbol table (exports from all files)
    pub globals: SymbolTable,
    /// Per-file symbol tables (file-local symbols, symbol IDs remapped)
    pub file_locals: Vec<SymbolTable>,
    /// Ambient module declarations across all files
    pub declared_modules: FxHashSet<String>,
    /// Shorthand ambient modules (`declare module "foo"` without body) - imports from these are `any`
    pub shorthand_ambient_modules: FxHashSet<String>,
    /// Module exports: maps file name (or module specifier) to its exported symbols
    /// This enables cross-file module resolution: import { X } from './file' can find X's symbol
    pub module_exports: FxHashMap<String, SymbolTable>,
    /// Re-exports: tracks `export { x } from 'module'` declarations
    /// Maps (`current_file`, `exported_name`) -> (`source_module`, `original_name`)
    pub reexports: Reexports,
    /// Wildcard re-exports: tracks `export * from 'module'` declarations
    /// Maps `current_file` -> Vec of `source_modules`
    pub wildcard_reexports: FxHashMap<String, Vec<String>>,
    /// Lib binders for global type resolution (Array, String, Promise, etc.)
    /// These contain symbols from lib.d.ts files and enable resolution of built-in types
    pub lib_binders: Vec<Arc<BinderState>>,
    /// Global symbol IDs that originated from lib files (remapped to global arena IDs)
    pub lib_symbol_ids: FxHashSet<SymbolId>,
    /// Global type interner - shared across all threads for type deduplication
    pub type_interner: TypeInterner,
}

/// Check if two symbols can be merged across multiple files.
///
/// TypeScript allows merging:
/// - Interface + Interface (declaration merging)
/// - Namespace + Namespace (declaration merging)
/// - Class + Interface (merging for class declarations)
/// - Function + Function (overloads - handled per-file)
const fn can_merge_symbols_cross_file(existing_flags: u32, new_flags: u32) -> bool {
    use crate::binder::symbol_flags;

    // Interface can merge with interface
    if (existing_flags & symbol_flags::INTERFACE) != 0 && (new_flags & symbol_flags::INTERFACE) != 0
    {
        return true;
    }

    // Class can merge with interface
    if ((existing_flags & symbol_flags::CLASS) != 0 && (new_flags & symbol_flags::INTERFACE) != 0)
        || ((existing_flags & symbol_flags::INTERFACE) != 0
            && (new_flags & symbol_flags::CLASS) != 0)
    {
        return true;
    }

    // Interface can merge with variable (e.g., `interface Promise<T>` + `declare var Promise: PromiseConstructor`)
    // This is fundamental to how TypeScript lib declarations work: types have both an interface
    // (type side) and a variable declaration (value side).
    if ((existing_flags & symbol_flags::INTERFACE) != 0
        && (new_flags & symbol_flags::VARIABLE) != 0)
        || ((existing_flags & symbol_flags::VARIABLE) != 0
            && (new_flags & symbol_flags::INTERFACE) != 0)
    {
        return true;
    }

    // Interface can merge with function (e.g., `interface Array<T>` + `declare function Array(...)`)
    if ((existing_flags & symbol_flags::INTERFACE) != 0
        && (new_flags & symbol_flags::FUNCTION) != 0)
        || ((existing_flags & symbol_flags::FUNCTION) != 0
            && (new_flags & symbol_flags::INTERFACE) != 0)
    {
        return true;
    }

    // Namespace/module can merge with namespace/module
    if (existing_flags & symbol_flags::MODULE) != 0 && (new_flags & symbol_flags::MODULE) != 0 {
        return true;
    }

    // Variable can merge with variable cross-file (so we can detect and report cross-file redeclarations of let/const)
    if (existing_flags & symbol_flags::VARIABLE) != 0 && (new_flags & symbol_flags::VARIABLE) != 0 {
        return true;
    }

    // Class can merge with Class cross-file (invalid, but merged to report duplicate)
    if (existing_flags & symbol_flags::CLASS) != 0 && (new_flags & symbol_flags::CLASS) != 0 {
        return true;
    }

    // Class can merge with Type Alias (invalid, but merged to report duplicate)
    if ((existing_flags & symbol_flags::CLASS) != 0 && (new_flags & symbol_flags::TYPE_ALIAS) != 0)
        || ((existing_flags & symbol_flags::TYPE_ALIAS) != 0
            && (new_flags & symbol_flags::CLASS) != 0)
    {
        return true;
    }

    // Type Alias can merge with Type Alias (invalid, but merged to report duplicate)
    if (existing_flags & symbol_flags::TYPE_ALIAS) != 0
        && (new_flags & symbol_flags::TYPE_ALIAS) != 0
    {
        return true;
    }

    // Class can merge with Variable (invalid, but merged to report duplicate)
    if ((existing_flags & symbol_flags::CLASS) != 0 && (new_flags & symbol_flags::VARIABLE) != 0)
        || ((existing_flags & symbol_flags::VARIABLE) != 0
            && (new_flags & symbol_flags::CLASS) != 0)
    {
        return true;
    }

    // Type Alias can merge with Variable (invalid, but merged to report duplicate)
    if ((existing_flags & symbol_flags::TYPE_ALIAS) != 0
        && (new_flags & symbol_flags::VARIABLE) != 0)
        || ((existing_flags & symbol_flags::VARIABLE) != 0
            && (new_flags & symbol_flags::TYPE_ALIAS) != 0)
    {
        return true;
    }

    // Namespace can merge with class, function, enum, or variable
    if (existing_flags & symbol_flags::MODULE) != 0
        && (new_flags
            & (symbol_flags::CLASS
                | symbol_flags::FUNCTION
                | symbol_flags::ENUM
                | symbol_flags::VARIABLE))
            != 0
    {
        return true;
    }
    if (new_flags & symbol_flags::MODULE) != 0
        && (existing_flags
            & (symbol_flags::CLASS
                | symbol_flags::FUNCTION
                | symbol_flags::ENUM
                | symbol_flags::VARIABLE))
            != 0
    {
        return true;
    }

    // Enum can merge with enum
    if (existing_flags & symbol_flags::ENUM) != 0 && (new_flags & symbol_flags::ENUM) != 0 {
        return true;
    }

    false
}

/// Append declarations from `incoming` into `existing` without duplicates.
///
/// Small declaration lists are common, so use linear scans there to avoid
/// hash set allocation overhead. Switch to a set only for larger collections.
fn append_unique_declarations(existing: &mut Vec<NodeIndex>, incoming: &[NodeIndex]) {
    existing.extend_from_slice(incoming);
}

/// Merge bind results into a unified program state
///
/// This is a sequential operation that combines:
/// - All symbol arenas into a single global arena
/// - Merges symbols with the same name across files (for interfaces, namespaces, etc.)
/// - Remaps symbol IDs in `node_symbols` to use global IDs
///
/// # Arguments
/// * `results` - Vector of `BindResult` from parallel binding
///
/// # Returns
/// `MergedProgram` with unified symbol space
pub fn merge_bind_results(results: Vec<BindResult>) -> MergedProgram {
    let refs: Vec<&BindResult> = results.iter().collect();
    merge_bind_results_ref(&refs)
}

pub fn merge_bind_results_ref(results: &[&BindResult]) -> MergedProgram {
    // Collect lib_binders from all results (deduplicated by address)
    let mut lib_binders: Vec<Arc<BinderState>> = Vec::new();
    let mut lib_binder_set: FxHashSet<usize> = FxHashSet::default();
    for result in results {
        for lib_binder in &result.lib_binders {
            let binder_addr = Arc::as_ptr(lib_binder) as usize;
            if lib_binder_set.insert(binder_addr) {
                lib_binders.push(Arc::clone(lib_binder));
            }
        }
    }

    // Calculate total symbols needed (including lib symbols)
    let lib_symbol_count: usize = lib_binders.iter().map(|b| b.symbols.len()).sum();
    let user_symbol_count: usize = results.iter().map(|r| r.symbols.len()).sum();
    let total_symbols = lib_symbol_count + user_symbol_count;

    // Create global symbol arena with pre-allocated capacity
    let mut global_symbols = SymbolArena::with_capacity(total_symbols);
    let mut symbol_arenas = FxHashMap::default();
    let mut declaration_arenas: DeclarationArenaMap = FxHashMap::default();
    let mut globals = SymbolTable::new();
    let mut files = Vec::with_capacity(results.len());
    let mut file_locals_list = Vec::with_capacity(results.len());
    let mut declared_modules = FxHashSet::default();
    let mut shorthand_ambient_modules = FxHashSet::default();
    let mut module_exports: FxHashMap<String, SymbolTable> = FxHashMap::default();
    let mut reexports: Reexports = FxHashMap::default();
    let mut wildcard_reexports: FxHashMap<String, Vec<String>> = FxHashMap::default();
    let mut global_lib_symbol_ids: FxHashSet<SymbolId> = FxHashSet::default();

    // Track which symbols have been merged to avoid duplicate processing.
    // Use interned atoms to avoid repeated String hashing/cloning on hot merge paths.
    let mut name_interner = Interner::new();
    // Track which symbols have been merged to avoid duplicate processing
    // IMPORTANT: This map is ONLY for symbols in the ROOT scope (ScopeId(0))
    // Symbols from nested scopes should NEVER be merged across files/scopes
    let mut merged_symbols: FxHashMap<Atom, SymbolId> = FxHashMap::default();

    // ==========================================================================
    // PHASE 1: Remap lib symbols to global arena
    // ==========================================================================
    // This creates a mapping from (lib_binder_ptr, local_id) -> global_id
    // so that file_locals can reference lib symbols using global IDs
    let mut lib_symbol_remap: FxHashMap<(usize, SymbolId), SymbolId> = FxHashMap::default();

    for lib_binder in &lib_binders {
        let lib_binder_ptr = Arc::as_ptr(lib_binder) as usize;

        // Pre-build a set of top-level symbol IDs from file_locals for O(1) lookup.
        // This avoids an O(N*F) quadratic scan where each symbol would linearly
        // search file_locals to check if it's top-level.
        let top_level_ids: FxHashSet<SymbolId> =
            lib_binder.file_locals.iter().map(|(_, id)| *id).collect();

        // Pre-build a per-symbol index of declaration_arenas entries to avoid
        // O(N*D) iteration where each symbol scans all declaration_arenas.
        let mut decl_arenas_by_sym: FxHashMap<SymbolId, Vec<(NodeIndex, Arc<NodeArena>)>> =
            FxHashMap::default();
        for (&(sym_id, decl_idx), arenas) in &lib_binder.declaration_arenas {
            for arena in arenas {
                decl_arenas_by_sym
                    .entry(sym_id)
                    .or_default()
                    .push((decl_idx, Arc::clone(arena)));
            }
        }

        // Process all symbols in this lib binder
        for i in 0..lib_binder.symbols.len() {
            let local_id = SymbolId(i as u32);
            if let Some(lib_sym) = lib_binder.symbols.get(local_id) {
                // Determine if this is a top-level symbol by checking file_locals.
                // In lib files, declarations like `declare namespace Reflect` may appear
                // in a child scope (e.g., ScopeId(1)) even though they're conceptually
                // top-level. Using file_locals is more reliable than the scope check
                // for determining which lib symbols should be globally merged.
                let is_top_level = top_level_ids.contains(&local_id);

                // Check if a symbol with this name already exists (cross-lib merging)
                // IMPORTANT: Only merge top-level symbols (those in file_locals)
                // Nested symbols (namespace members, etc.) should NEVER be merged across scopes
                let global_id = if is_top_level {
                    let name_atom = name_interner.intern(&lib_sym.escaped_name);
                    if let Some(&existing_id) = merged_symbols.get(&name_atom) {
                        // Symbol already exists - check if we can merge
                        if let Some(existing_sym) = global_symbols.get(existing_id) {
                            if can_merge_symbols_cross_file(existing_sym.flags, lib_sym.flags) {
                                // Merge: reuse existing symbol ID
                                // Merge declarations from this lib
                                if let Some(existing_mut) = global_symbols.get_mut(existing_id) {
                                    existing_mut.flags |= lib_sym.flags;
                                    append_unique_declarations(
                                        &mut existing_mut.declarations,
                                        &lib_sym.declarations,
                                    );
                                }
                                existing_id
                            } else {
                                // Cannot merge - allocate new (shadowing)
                                let new_id = global_symbols.alloc_from(lib_sym);
                                merged_symbols.insert(name_atom, new_id);
                                new_id
                            }
                        } else {
                            // Shouldn't happen - allocate new
                            let new_id = global_symbols.alloc_from(lib_sym);
                            merged_symbols.insert(name_atom, new_id);
                            new_id
                        }
                    } else {
                        // New symbol - allocate in global arena
                        let new_id = global_symbols.alloc_from(lib_sym);
                        merged_symbols.insert(name_atom, new_id);
                        new_id
                    }
                } else {
                    // Nested symbol - always allocate new, never merge

                    // NOTE: Don't add to merged_symbols - nested symbols should never be cross-file merged
                    global_symbols.alloc_from(lib_sym)
                };

                // Store the remapping
                lib_symbol_remap.insert((lib_binder_ptr, local_id), global_id);

                // CRITICAL FIX: Copy arena mapping for lib symbols
                // Without this, the checker's compute_type_of_symbol will fail to find
                // the declaration arena for lib symbols like WeakSet, Symbol, Promise, etc.
                // This was the root cause of "Any poisoning" where global types resolved to Error.
                if let Some(lib_arena) = lib_binder.symbol_arenas.get(&local_id) {
                    symbol_arenas.insert(global_id, Arc::clone(lib_arena));
                }

                // Also copy declaration_arenas for precise cross-file declaration lookup
                // This is needed when a symbol has declarations across multiple lib files
                if let Some(entries) = decl_arenas_by_sym.get(&local_id) {
                    for (decl_idx, arena) in entries {
                        declaration_arenas
                            .entry((global_id, *decl_idx))
                            .or_default()
                            .push(Arc::clone(arena));
                    }
                }
            }
        }
    }

    // ==========================================================================
    // PHASE 1.5: Remap internal references (parent, exports, members)
    // ==========================================================================
    // After all lib symbols have been allocated in the global arena, we need a
    // second pass to fix up internal SymbolId references. The `alloc_from()` call
    // copies the symbol data including members/exports/parent, but those fields
    // still contain LOCAL SymbolIds from the original lib binder. We must remap
    // them to the corresponding global IDs using lib_symbol_remap.
    // (This mirrors Phase 2 in state.rs merge_lib_contexts_into_binder.)
    for lib_binder in &lib_binders {
        let lib_binder_ptr = Arc::as_ptr(lib_binder) as usize;

        for i in 0..lib_binder.symbols.len() {
            let local_id = SymbolId(i as u32);
            let Some(&global_id) = lib_symbol_remap.get(&(lib_binder_ptr, local_id)) else {
                continue;
            };
            let Some(lib_sym) = lib_binder.symbols.get(local_id) else {
                continue;
            };

            // Remap parent
            if !lib_sym.parent.is_none()
                && let Some(&new_parent) = lib_symbol_remap.get(&(lib_binder_ptr, lib_sym.parent))
                && let Some(sym) = global_symbols.get_mut(global_id)
            {
                sym.parent = new_parent;
            }

            // Remap exports: replace local IDs with global IDs
            if let Some(exports) = &lib_sym.exports
                && let Some(sym) = global_symbols.get_mut(global_id)
            {
                if sym.exports.is_none() {
                    sym.exports = Some(Box::new(SymbolTable::new()));
                }
                if let Some(existing) = sym.exports.as_mut() {
                    for (name, &export_id) in exports.iter() {
                        if let Some(&new_export_id) =
                            lib_symbol_remap.get(&(lib_binder_ptr, export_id))
                        {
                            // Always overwrite — Phase 1 alloc_from copied local IDs
                            // that need to be replaced with global IDs
                            existing.set(name.clone(), new_export_id);
                        }
                    }
                }
            }

            // Remap members: replace local IDs with global IDs
            if let Some(members) = &lib_sym.members
                && let Some(sym) = global_symbols.get_mut(global_id)
            {
                if sym.members.is_none() {
                    sym.members = Some(Box::new(SymbolTable::new()));
                }
                if let Some(existing) = sym.members.as_mut() {
                    for (name, &member_id) in members.iter() {
                        if let Some(&new_member_id) =
                            lib_symbol_remap.get(&(lib_binder_ptr, member_id))
                        {
                            existing.set(name.clone(), new_member_id);
                        }
                    }
                }
            }
        }
    }

    // Also remap lib file_locals entries that reference symbols by name
    // (for exported lib symbols like Array, Object, console)
    let mut lib_name_to_global: FxHashMap<Atom, SymbolId> = FxHashMap::default();
    for lib_binder in &lib_binders {
        let lib_binder_ptr = Arc::as_ptr(lib_binder) as usize;
        for (name, &local_id) in lib_binder.file_locals.iter() {
            if let Some(&global_id) = lib_symbol_remap.get(&(lib_binder_ptr, local_id)) {
                // Only keep the first mapping for each name (lib files are processed in order)
                let name_atom = name_interner.intern(name);
                lib_name_to_global.entry(name_atom).or_insert(global_id);
            }
        }
    }

    // ==========================================================================
    // PHASE 2: Process user files
    // ==========================================================================

    for (file_idx, result) in results.iter().enumerate() {
        declared_modules.extend(result.declared_modules.iter().cloned());
        shorthand_ambient_modules.extend(result.shorthand_ambient_modules.iter().cloned());

        // Merge reexports from this file
        for (file_name, file_reexports) in &result.reexports {
            let entry = reexports.entry(file_name.clone()).or_default();
            for (export_name, mapping) in file_reexports {
                entry.insert(export_name.clone(), mapping.clone());
            }
        }

        // Merge wildcard reexports from this file
        for (file_name, source_modules) in &result.wildcard_reexports {
            let entry = wildcard_reexports.entry(file_name.clone()).or_default();
            if entry.len() + source_modules.len() <= 16 {
                for source_module in source_modules {
                    if !entry.contains(source_module) {
                        entry.push(source_module.clone());
                    }
                }
            } else {
                let mut seen: FxHashSet<String> = entry.iter().cloned().collect();
                for source_module in source_modules {
                    if seen.insert(source_module.clone()) {
                        entry.push(source_module.clone());
                    }
                }
            }
        }
        // Copy symbols from this file to global arena, getting new IDs
        let mut id_remap: FxHashMap<SymbolId, SymbolId> = FxHashMap::default();
        for i in 0..result.symbols.len() {
            let old_id = SymbolId(i as u32);
            if let Some(sym) = result.symbols.get(old_id) {
                // For lib-originated symbols, reuse the Phase 1 global IDs rather than
                // allocating new ones. This prevents duplicate lib symbols and ensures
                // the Phase 1.5 remapped exports/members are preserved.
                if result.lib_symbol_ids.contains(&old_id) {
                    // For lib-originated symbols, use the reverse remap to find the
                    // original (lib_binder_ptr, local_id), then look up the Phase 1
                    // global ID via lib_symbol_remap. This ensures all lib symbols
                    // (both top-level and nested) map to their Phase 1 global IDs,
                    // preserving the Phase 1.5 export/member remapping.
                    let mut resolved_global_id = None;
                    if let Some(&(binder_ptr, original_local_id)) =
                        result.lib_symbol_reverse_remap.get(&old_id)
                        && let Some(&global_id) =
                            lib_symbol_remap.get(&(binder_ptr, original_local_id))
                    {
                        resolved_global_id = Some(global_id);
                    }
                    // Fallback: look up by name in merged_symbols or lib_name_to_global
                    if resolved_global_id.is_none() {
                        let name_atom = name_interner.intern(&sym.escaped_name);
                        if let Some(&global_id) = merged_symbols.get(&name_atom) {
                            resolved_global_id = Some(global_id);
                        }
                        if resolved_global_id.is_none()
                            && let Some(&global_id) = lib_name_to_global.get(&name_atom)
                        {
                            resolved_global_id = Some(global_id);
                        }
                    }
                    if let Some(global_id) = resolved_global_id {
                        // The user binder may have merged additional flags and declarations
                        // into this lib symbol (e.g., user `interface Event<T>` augments
                        // lib's non-generic `Event`, or user `type Proxy<T>` adds TYPE_ALIAS
                        // to lib's `declare var Proxy`). Always propagate extra flags and
                        // user-local declarations to the global symbol so that type parameter
                        // resolution can find them.
                        if let Some(global_sym) = global_symbols.get_mut(global_id) {
                            let extra_flags = sym.flags & !global_sym.flags;
                            if extra_flags != 0 {
                                global_sym.flags |= extra_flags;
                            }
                            // Always copy user declarations that were merged into this symbol,
                            // even when flags are identical. Without this, user declarations
                            // (e.g., a generic `interface Event<T>`) are lost and
                            // get_type_params_for_symbol won't find their type parameters.
                            append_unique_declarations(
                                &mut global_sym.declarations,
                                &sym.declarations,
                            );
                        }
                        id_remap.insert(old_id, global_id);
                        continue;
                    }
                    // Last resort: allocate a new ID (shouldn't happen normally)
                    let new_id = global_symbols.alloc(sym.flags, sym.escaped_name.clone());
                    symbol_arenas.insert(new_id, Arc::clone(&result.arena));
                    id_remap.insert(old_id, new_id);
                    continue;
                }

                // Check if this symbol is from a nested scope.
                // We check whether this symbol ID appears in the ROOT scope table
                // (ScopeId(0) = SourceFile scope). This is more reliable than checking
                // node_scope_ids because not all declaration types create scopes
                // (e.g., InterfaceDeclaration does not create a scope, so its node
                // won't appear in node_scope_ids, causing false negatives).
                let is_nested_symbol = !result.scopes.first().is_some_and(|root_scope| {
                    root_scope
                        .table
                        .get(&sym.escaped_name)
                        .is_some_and(|root_sym_id| root_sym_id == old_id)
                });

                // Check if symbol already exists in globals (cross-file merging)
                // IMPORTANT: Only merge symbols from ROOT scope (ScopeId(0))
                // Nested scope symbols should NEVER be merged across scopes
                let new_id = if !is_nested_symbol && !result.is_external_module {
                    let name_atom = name_interner.intern(&sym.escaped_name);
                    if let Some(&existing_id) = merged_symbols.get(&name_atom) {
                        // Symbol exists - check if we can merge
                        if let Some(existing_sym) = global_symbols.get(existing_id) {
                            // Check if symbols can merge (interface+interface, namespace+namespace, etc.)
                            if can_merge_symbols_cross_file(existing_sym.flags, sym.flags) {
                                // Merge: reuse existing symbol ID, will merge declarations below
                                existing_id
                            } else {
                                // Cannot merge - allocate new symbol (shadowing or duplicate)
                                let new_id =
                                    global_symbols.alloc(sym.flags, sym.escaped_name.clone());
                                symbol_arenas.insert(new_id, Arc::clone(&result.arena));
                                merged_symbols.insert(name_atom, new_id);
                                new_id
                            }
                        } else {
                            // Shouldn't happen - allocate new
                            let new_id = global_symbols.alloc(sym.flags, sym.escaped_name.clone());
                            symbol_arenas.insert(new_id, Arc::clone(&result.arena));
                            merged_symbols.insert(name_atom, new_id);
                            new_id
                        }
                    } else {
                        // New symbol - allocate
                        let new_id = global_symbols.alloc(sym.flags, sym.escaped_name.clone());
                        symbol_arenas.insert(new_id, Arc::clone(&result.arena));
                        merged_symbols.insert(name_atom, new_id);
                        new_id
                    }
                } else {
                    // Nested symbol - always allocate new, never merge or add to merged_symbols
                    let new_id = global_symbols.alloc(sym.flags, sym.escaped_name.clone());
                    symbol_arenas.insert(new_id, Arc::clone(&result.arena));
                    // NOTE: Don't add to merged_symbols - nested symbols should never be cross-file merged
                    new_id
                };
                id_remap.insert(old_id, new_id);
            }
        }

        // Track remapped lib symbol IDs for unused-checking exclusion
        for &old_lib_id in &result.lib_symbol_ids {
            if let Some(&new_id) = id_remap.get(&old_lib_id) {
                global_lib_symbol_ids.insert(new_id);
            }
        }

        // Copy symbol_arenas entries from user file, remapping IDs
        // This propagates lib symbol arena mappings that were created during merge_lib_symbols
        for (&old_sym_id, arena) in &result.symbol_arenas {
            if let Some(&new_sym_id) = id_remap.get(&old_sym_id) {
                symbol_arenas
                    .entry(new_sym_id)
                    .or_insert_with(|| Arc::clone(arena));
            }
        }

        // Copy declaration_arenas entries from user file, remapping symbol IDs
        for (&(old_sym_id, decl_idx), arenas) in &result.declaration_arenas {
            if let Some(&new_sym_id) = id_remap.get(&old_sym_id) {
                let target = declaration_arenas
                    .entry((new_sym_id, decl_idx))
                    .or_default();
                for arena in arenas {
                    target.push(Arc::clone(arena));
                }
            }
        }

        // Collect exported symbols for this file (for module_exports map).
        //
        // Note: `export default ...` must be represented under the `"default"` export name
        // so that `import X from "./mod"` can resolve correctly.
        //
        // We intentionally do *not* depend solely on `sym.is_exported` for determining whether
        // a file is an external module, because default exports may not correspond to a named
        // export in `file_locals`.
        let mut exports = SymbolTable::new();
        let mut export_equals_old: Option<SymbolId> = None;

        // 1) Named exports collected from file_locals.
        for (name, &sym_id) in result.file_locals.iter() {
            if name == "export=" {
                export_equals_old = Some(sym_id);
            }
            if let Some(sym) = result.symbols.get(sym_id)
                && (sym.is_exported || name == "export=")
                && let Some(&remapped_id) = id_remap.get(&sym_id)
            {
                exports.set(name.clone(), remapped_id);
            }
        }

        // 1b) `export = target` should also expose namespace members from `target`.
        if let Some(old_export_equals_sym) = export_equals_old
            && let Some(target_symbol) = result.symbols.get(old_export_equals_sym)
        {
            if let Some(target_exports) = target_symbol.exports.as_ref() {
                for (export_name, old_sym_id) in target_exports.iter() {
                    if let Some(&remapped_id) = id_remap.get(old_sym_id) {
                        exports.set(export_name.clone(), remapped_id);
                    }
                }
            }
            if let Some(target_members) = target_symbol.members.as_ref() {
                for (member_name, old_sym_id) in target_members.iter() {
                    if let Some(&remapped_id) = id_remap.get(old_sym_id) {
                        exports.set(member_name.clone(), remapped_id);
                    }
                }
            }
        }

        // 2) Default export: add `"default"` entry when present.
        let mut default_export_old: Option<SymbolId> = None;
        if let Some(root_node) = result.arena.get(result.source_file)
            && let Some(source) = result.arena.get_source_file(root_node)
        {
            for &stmt_idx in &source.statements.nodes {
                let Some(stmt_node) = result.arena.get(stmt_idx) else {
                    continue;
                };
                if stmt_node.kind != syntax_kind_ext::EXPORT_DECLARATION {
                    continue;
                }
                let Some(export_decl) = result.arena.get_export_decl(stmt_node) else {
                    continue;
                };
                if !export_decl.is_default_export {
                    continue;
                }

                // `export default <expr>;`
                let Some(clause_node) = result.arena.get(export_decl.export_clause) else {
                    continue;
                };

                // Best-effort: if the default export is a reference to a named declaration
                // (identifier/class/function), map `"default"` to that symbol.
                //
                // This matches the needs of `import X from "./mod"` and keeps the symbol ID
                // stable across files without synthesizing a new symbol.
                if clause_node.kind == crate::scanner::SyntaxKind::Identifier as u16 {
                    if let Some(ident) = result.arena.get_identifier(clause_node) {
                        default_export_old = result.file_locals.get(&ident.escaped_text);
                    }
                } else if let Some(func) = result.arena.get_function(clause_node) {
                    if let Some(name_node) = result.arena.get(func.name)
                        && let Some(ident) = result.arena.get_identifier(name_node)
                    {
                        default_export_old = result.file_locals.get(&ident.escaped_text);
                    }
                } else if let Some(class) = result.arena.get_class(clause_node)
                    && let Some(name_node) = result.arena.get(class.name)
                    && let Some(ident) = result.arena.get_identifier(name_node)
                {
                    default_export_old = result.file_locals.get(&ident.escaped_text);
                }

                // Only one default export per module.
                break;
            }
        }

        if let Some(old_sym_id) = default_export_old
            && let Some(&remapped_id) = id_remap.get(&old_sym_id)
        {
            exports.set("default".to_string(), remapped_id);
        }

        let remap_symbol_table =
            |table: &SymbolTable, id_remap: &FxHashMap<SymbolId, SymbolId>| -> SymbolTable {
                let mut remapped = SymbolTable::new();
                for (name, old_sym_id) in table.iter() {
                    if let Some(&new_sym_id) = id_remap.get(old_sym_id) {
                        remapped.set(name.clone(), new_sym_id);
                    }
                }
                remapped
            };

        if !exports.is_empty() {
            module_exports.insert(result.file_name.clone(), exports);
        }

        for (module_key, exports_table) in &result.module_exports {
            if module_key == &result.file_name {
                continue;
            }
            let remapped = remap_symbol_table(exports_table, &id_remap);
            if !remapped.is_empty() {
                module_exports.insert(module_key.clone(), remapped);
            }
        }

        for (old_id, &new_id) in &id_remap {
            // Skip lib-originated symbols - they were already set up by Phase 1 + 1.5
            if result.lib_symbol_ids.contains(old_id) {
                continue;
            }
            let Some(old_sym) = result.symbols.get(*old_id) else {
                continue;
            };

            // CRITICAL: Populate declaration_arenas for user symbols
            for &decl_idx in &old_sym.declarations {
                declaration_arenas
                    .entry((new_id, decl_idx))
                    .or_default()
                    .push(Arc::clone(&result.arena));
            }

            if let Some(new_sym) = global_symbols.get_mut(new_id) {
                // Check if this is a cross-file merge (same symbol already has data)
                let is_cross_file_merge = !new_sym.declarations.is_empty();

                if is_cross_file_merge {
                    // Cross-file merge: append declarations and merge flags
                    new_sym.flags |= old_sym.flags;
                    // Append new declarations from this file
                    append_unique_declarations(&mut new_sym.declarations, &old_sym.declarations);
                    // Update value_declaration if the old one was NONE
                    if new_sym.value_declaration.is_none() && !old_sym.value_declaration.is_none() {
                        new_sym.value_declaration = old_sym.value_declaration;
                    }
                    // Merge exports (if both have exports)
                    if let (Some(old_exports), Some(new_exports)) =
                        (old_sym.exports.as_ref(), new_sym.exports.as_mut())
                    {
                        for (name, sym_id) in old_exports.iter() {
                            if !new_exports.has(name) {
                                // Remap the symbol ID and add to exports
                                if let Some(&remapped_id) = id_remap.get(sym_id) {
                                    new_exports.set(name.clone(), remapped_id);
                                }
                            }
                        }
                    }
                    // Merge members (if both have members)
                    if let (Some(old_members), Some(new_members)) =
                        (old_sym.members.as_ref(), new_sym.members.as_mut())
                    {
                        for (name, sym_id) in old_members.iter() {
                            if !new_members.has(name) {
                                // Remap the symbol ID and add to members
                                if let Some(&remapped_id) = id_remap.get(sym_id) {
                                    new_members.set(name.clone(), remapped_id);
                                }
                            }
                        }
                    }
                } else {
                    // First time seeing this symbol - full update
                    let mut updated = old_sym.clone();
                    updated.id = new_id;
                    updated.parent = id_remap
                        .get(&old_sym.parent)
                        .copied()
                        .unwrap_or(SymbolId::NONE);
                    updated.value_declaration = old_sym.value_declaration;
                    updated.declarations = old_sym.declarations.clone();
                    updated.is_exported = old_sym.is_exported;
                    // Track which file this symbol was declared in for TDZ cross-file detection
                    updated.decl_file_idx = file_idx as u32;
                    updated.exports = old_sym
                        .exports
                        .as_ref()
                        .map(|table| Box::new(remap_symbol_table(table.as_ref(), &id_remap)));
                    updated.members = old_sym
                        .members
                        .as_ref()
                        .map(|table| Box::new(remap_symbol_table(table.as_ref(), &id_remap)));
                    *new_sym = updated;
                }
            }
        }

        // Remap node_symbols to use global IDs
        // Note: node_symbols primarily maps user file nodes to user symbols,
        // but lib symbols referenced in user code need remapping too
        let mut remapped_node_symbols = FxHashMap::default();
        for (node_idx, old_sym_id) in &result.node_symbols {
            if let Some(&new_sym_id) = id_remap.get(old_sym_id) {
                remapped_node_symbols.insert(*node_idx, new_sym_id);
            }
            // Note: We don't need to check lib_symbol_remap here because
            // node_symbols are created during binding of user files, and at that point
            // lib symbols are accessed by name lookup (file_locals), not by node mapping
        }

        // Remap file_locals to use global IDs
        // This handles both user symbols (from id_remap) and lib symbols (from lib_name_to_global)
        let mut remapped_file_locals = SymbolTable::new();
        for (name, old_sym_id) in result.file_locals.iter() {
            if let Some(&new_sym_id) = id_remap.get(old_sym_id) {
                // User symbol - use remapped ID
                remapped_file_locals.set(name.clone(), new_sym_id);
                // Also add to globals (all top-level declarations visible globally)
                // EXCEPT ALIAS symbols (import declarations) which are file-local by design.
                // Leaking import aliases to globals causes cross-file contamination where
                // other files try to resolve the import and get incorrect types.
                let is_alias = global_symbols
                    .get(new_sym_id)
                    .is_some_and(|s| s.flags & crate::binder::symbol_flags::ALIAS != 0);
                if !is_alias {
                    globals.set(name.clone(), new_sym_id);
                }
            } else {
                let name_atom = name_interner.intern(name);
                if let Some(&global_id) = lib_name_to_global.get(&name_atom) {
                    // Lib symbol - use the pre-remapped global ID
                    // Only add to file_locals, NOT to globals (lib symbols are accessed
                    // through lib_contexts in the checker, not through globals)
                    remapped_file_locals.set(name.clone(), global_id);
                }
            }
        }

        let mut remapped_scopes = Vec::with_capacity(result.scopes.len());
        for scope in &result.scopes {
            let mut table = SymbolTable::new();
            for (name, old_sym_id) in scope.table.iter() {
                if let Some(&new_sym_id) = id_remap.get(old_sym_id) {
                    // User symbol - include in scope
                    table.set(name.clone(), new_sym_id);
                }
                // NOTE: We intentionally do NOT add lib symbols to scopes.
                // Lib symbols have declaration NodeIndex values from lib arenas which
                // can accidentally match valid indices in user file arenas, causing
                // false duplicate identifier detection. Lib symbols are accessible
                // through file_locals for type lookup, but should not be in scopes.
            }
            remapped_scopes.push(Scope {
                parent: scope.parent,
                table,
                kind: scope.kind,
                container_node: scope.container_node,
            });
        }

        file_locals_list.push(remapped_file_locals);

        // Populate arena context for module augmentations
        let module_augmentations: FxHashMap<String, Vec<crate::binder::ModuleAugmentation>> =
            result
                .module_augmentations
                .iter()
                .map(|(spec, augs)| {
                    let arena = Arc::clone(&result.arena);
                    (
                        spec.clone(),
                        augs.iter()
                            .map(|aug| {
                                crate::binder::ModuleAugmentation::with_arena(
                                    aug.name.clone(),
                                    aug.node,
                                    Arc::clone(&arena),
                                )
                            })
                            .collect(),
                    )
                })
                .collect();

        files.push(BoundFile {
            file_name: result.file_name.clone(),
            source_file: result.source_file,
            arena: Arc::clone(&result.arena),
            node_symbols: remapped_node_symbols,
            scopes: remapped_scopes,
            node_scope_ids: result.node_scope_ids.clone(),
            parse_diagnostics: result.parse_diagnostics.clone(),
            global_augmentations: result.global_augmentations.clone(),
            module_augmentations,
            flow_nodes: result.flow_nodes.clone(),
            node_flow: result.node_flow.clone(),
            switch_clause_to_switch: result.switch_clause_to_switch.clone(),
            is_external_module: result.is_external_module,
            expando_properties: result.expando_properties.clone(),
        });
    }

    // NOTE: We intentionally do NOT populate globals from merged_symbols here.
    // merged_symbols contains ALL symbols (including namespace-local ones like `var Symbol`
    // inside a namespace), but globals should only contain file-level symbols.
    // File-level symbols are already correctly added to globals at lines 873-880.
    //
    // NOTE: lib_binders were collected and processed at the beginning of this function.
    // Their symbols have been remapped to global IDs and are now in:
    // - global_symbols: The actual Symbol data
    // - lib_name_to_global: Name -> global SymbolId mapping
    // - Each file's remapped_file_locals and globals

    MergedProgram {
        files,
        symbols: global_symbols,
        symbol_arenas,
        declaration_arenas,
        globals,
        file_locals: file_locals_list,
        declared_modules,
        shorthand_ambient_modules,
        module_exports,
        reexports,
        wildcard_reexports,
        lib_binders,
        lib_symbol_ids: global_lib_symbol_ids,
        type_interner: TypeInterner::new(),
    }
}

/// Full pipeline: Parse → Bind (parallel) → Merge (sequential)
///
/// This is the main entry point for multi-file compilation.
/// Lib files are automatically loaded and merged during binding.
pub fn compile_files(files: Vec<(String, String)>) -> MergedProgram {
    let lib_files = resolve_default_lib_files(ScriptTarget::ESNext)
        .unwrap_or_else(|err| panic!("failed to resolve default lib files: {err}"));
    compile_files_with_libs(files, &lib_files)
}

/// Full pipeline with explicit lib files.
///
/// Callers are responsible for providing the resolved lib file paths.
pub fn compile_files_with_libs(
    files: Vec<(String, String)>,
    lib_files: &[PathBuf],
) -> MergedProgram {
    let lib_paths: Vec<&Path> = lib_files.iter().map(PathBuf::as_path).collect();
    let bind_results = parse_and_bind_parallel_with_lib_files(files, &lib_paths);
    merge_bind_results(bind_results)
}

// =============================================================================
// Parallel Type Checking
// =============================================================================

use crate::checker::context::{CheckerOptions, LibContext};
use crate::checker::diagnostics::Diagnostic;
use crate::checker::state::CheckerState;
use crate::lib_loader::LibFile;
use crate::parser::syntax_kind_ext;
use tsz_solver::TypeId;

/// Result of type checking a single function body
#[derive(Debug)]
pub struct FunctionCheckResult {
    /// Function node index within its file
    pub function_idx: NodeIndex,
    /// File index in the program
    pub file_idx: usize,
    /// Inferred return type
    pub return_type: TypeId,
    /// Diagnostics produced
    pub diagnostics: Vec<Diagnostic>,
}

/// Result of type checking all function bodies in a file
pub struct FileCheckResult {
    /// File index
    pub file_idx: usize,
    /// File name
    pub file_name: String,
    /// Function check results
    pub function_results: Vec<FunctionCheckResult>,
    /// File-level diagnostics
    pub diagnostics: Vec<Diagnostic>,
}

/// Result of parallel type checking
pub struct CheckResult {
    /// Per-file check results
    pub file_results: Vec<FileCheckResult>,
    /// Total functions checked
    pub function_count: usize,
    /// Total diagnostics
    pub diagnostic_count: usize,
}

/// Collect all function declarations from a source file
fn collect_functions(arena: &NodeArena, source_file: NodeIndex) -> Vec<NodeIndex> {
    let mut functions = Vec::new();

    let Some(sf) = arena.get_source_file_at(source_file) else {
        return functions;
    };

    for &stmt_idx in &sf.statements.nodes {
        collect_functions_from_node(arena, stmt_idx, &mut functions);
    }

    functions
}

/// Recursively collect functions from a node
fn collect_functions_from_node(
    arena: &NodeArena,
    node_idx: NodeIndex,
    functions: &mut Vec<NodeIndex>,
) {
    let Some(node) = arena.get(node_idx) else {
        return;
    };

    match node.kind {
        k if k == syntax_kind_ext::FUNCTION_DECLARATION
            || k == syntax_kind_ext::FUNCTION_EXPRESSION
            || k == syntax_kind_ext::ARROW_FUNCTION =>
        {
            functions.push(node_idx);
            // Also collect nested functions in the body
            if let Some(func) = arena.get_function(node)
                && !func.body.is_none()
            {
                collect_functions_from_node(arena, func.body, functions);
            }
        }
        k if k == syntax_kind_ext::METHOD_DECLARATION => {
            functions.push(node_idx);
            // Also collect nested functions in the body
            if let Some(method) = arena.get_method_decl(node)
                && !method.body.is_none()
            {
                collect_functions_from_node(arena, method.body, functions);
            }
        }
        k if k == syntax_kind_ext::CLASS_DECLARATION => {
            if let Some(class) = arena.get_class(node) {
                for &member_idx in &class.members.nodes {
                    collect_functions_from_node(arena, member_idx, functions);
                }
            }
        }
        k if k == syntax_kind_ext::BLOCK => {
            if let Some(block) = arena.get_block(node) {
                for &stmt_idx in &block.statements.nodes {
                    collect_functions_from_node(arena, stmt_idx, &mut *functions);
                }
            }
        }
        k if k == syntax_kind_ext::VARIABLE_STATEMENT => {
            // Variable statement contains a declaration list which contains declarations
            if let Some(var_stmt) = arena.get_variable(node) {
                // var_stmt.declarations contains the VARIABLE_DECLARATION_LIST node(s)
                for &decl_list_idx in &var_stmt.declarations.nodes {
                    if let Some(decl_list_node) = arena.get(decl_list_idx) {
                        // The declaration list also uses VariableData
                        if let Some(decl_list) = arena.get_variable(decl_list_node) {
                            // Now decl_list.declarations contains the actual VARIABLE_DECLARATION nodes
                            for &decl_idx in &decl_list.declarations.nodes {
                                if let Some(decl_node) = arena.get(decl_idx)
                                    && let Some(decl) = arena.get_variable_declaration(decl_node)
                                    && !decl.initializer.is_none()
                                {
                                    collect_functions_from_node(arena, decl.initializer, functions);
                                }
                            }
                        }
                    }
                }
            }
        }
        k if k == syntax_kind_ext::EXPORT_DECLARATION => {
            // Export declarations may contain function/class declarations
            if let Some(export) = arena.get_export_decl(node)
                && !export.export_clause.is_none()
            {
                collect_functions_from_node(arena, export.export_clause, functions);
            }
        }
        _ => {}
    }
}

/// Type check function bodies in parallel
///
/// After binding is complete and symbols are merged, function bodies
/// can be type-checked in parallel because:
/// 1. Each function body only uses local variables and global symbols
/// 2. Local type inference doesn't modify global state
/// 3. Each function is independent
///
/// # Arguments
/// * `program` - The merged program with global symbols
///
/// # Returns
/// `CheckResult` with diagnostics from all functions
pub fn check_functions_parallel(program: &MergedProgram) -> CheckResult {
    // First, collect all functions from all files (sequential)
    let mut all_functions: Vec<(usize, NodeIndex)> = Vec::new();

    for (file_idx, file) in program.files.iter().enumerate() {
        let functions = collect_functions(&file.arena, file.source_file);
        for func_idx in functions {
            all_functions.push((file_idx, func_idx));
        }
    }

    let function_count = all_functions.len();

    // Create a shared QueryCache for memoized evaluate_type/is_subtype_of calls.
    let query_cache = tsz_solver::QueryCache::new(&program.type_interner);

    // Check functions in parallel
    // Note: We need to be careful here - CheckerState holds mutable references
    // For now, we group by file and check each file's functions together
    let file_results: Vec<FileCheckResult> = maybe_parallel_iter!(program.files)
        .enumerate()
        .map(|(file_idx, file)| {
            let functions = collect_functions(&file.arena, file.source_file);

            // Create a binder state from the node_symbols
            let binder = create_binder_from_bound_file(file, program, file_idx);

            // Create checker for this file, using the shared type interner
            let compiler_options = crate::checker::context::CheckerOptions::default();
            let mut checker = CheckerState::new(
                &file.arena,
                &binder,
                &query_cache,
                file.file_name.clone(),
                compiler_options, // default options for internal operations
            );

            let mut function_results = Vec::new();

            for func_idx in functions {
                // Check the function
                let return_type = checker.get_type_of_node(func_idx);

                function_results.push(FunctionCheckResult {
                    function_idx: func_idx,
                    file_idx,
                    return_type,
                    diagnostics: Vec::new(), // Diagnostics are collected at file level
                });
            }

            // Collect diagnostics from checker
            let diagnostics = std::mem::take(&mut checker.ctx.diagnostics);

            FileCheckResult {
                file_idx,
                file_name: file.file_name.clone(),
                function_results,
                diagnostics,
            }
        })
        .collect();

    let diagnostic_count: usize = file_results.iter().map(|r| r.diagnostics.len()).sum();

    CheckResult {
        file_results,
        function_count,
        diagnostic_count,
    }
}

/// Type check full source files in parallel.
///
/// This runs `check_source_file` for each file, which validates all top-level
/// statements and function bodies. Compiler options and lib contexts are applied
/// so diagnostics match normal compilation behavior.
pub fn check_files_parallel(
    program: &MergedProgram,
    checker_options: &CheckerOptions,
    lib_files: &[Arc<LibFile>],
) -> CheckResult {
    // Create lib_contexts from lib_files (contains both arena and binder)
    // The binders in lib_files should match the binders in program.lib_binders
    let lib_contexts: Vec<LibContext> = lib_files
        .iter()
        .map(|lib| LibContext {
            arena: Arc::clone(&lib.arena),
            binder: Arc::clone(&lib.binder),
        })
        .collect();

    // Create a shared QueryCache for memoized evaluate_type/is_subtype_of calls.
    // This is thread-safe (uses RwLock internally) and shared across all file checks.
    let query_cache = tsz_solver::QueryCache::new(&program.type_interner);

    let file_results: Vec<FileCheckResult> = maybe_parallel_iter!(program.files)
        .enumerate()
        .map(|(file_idx, file)| {
            let binder = create_binder_from_bound_file(file, program, file_idx);

            let mut checker = CheckerState::with_options(
                &file.arena,
                &binder,
                &query_cache,
                file.file_name.clone(),
                checker_options,
            );

            if !lib_contexts.is_empty() {
                checker.ctx.set_lib_contexts(lib_contexts.clone());
                checker.ctx.set_actual_lib_file_count(lib_contexts.len());
            }

            checker.check_source_file(file.source_file);

            let diagnostics = std::mem::take(&mut checker.ctx.diagnostics);

            FileCheckResult {
                file_idx,
                file_name: file.file_name.clone(),
                function_results: Vec::new(),
                diagnostics,
            }
        })
        .collect();

    let diagnostic_count: usize = file_results.iter().map(|r| r.diagnostics.len()).sum();

    CheckResult {
        file_results,
        function_count: 0,
        diagnostic_count,
    }
}

/// Create a `BinderState` from a `BoundFile` for type checking
pub fn create_binder_from_bound_file(
    file: &BoundFile,
    program: &MergedProgram,
    file_idx: usize,
) -> BinderState {
    // Get file locals for this specific file
    let mut file_locals = SymbolTable::new();

    // Copy from program.file_locals if available
    if file_idx < program.file_locals.len() {
        for (name, &sym_id) in program.file_locals[file_idx].iter() {
            file_locals.set(name.clone(), sym_id);
        }
    }

    // Also add globals (for cross-file references)
    for (name, &sym_id) in program.globals.iter() {
        if !file_locals.has(name) {
            file_locals.set(name.clone(), sym_id);
        }
    }

    // Merge module augmentations from all files
    // When checking a file, we need access to augmentations from all other files
    let mut merged_module_augmentations: rustc_hash::FxHashMap<
        String,
        Vec<crate::binder::ModuleAugmentation>,
    > = rustc_hash::FxHashMap::default();

    for other_file in &program.files {
        for (spec, augs) in &other_file.module_augmentations {
            merged_module_augmentations
                .entry(spec.clone())
                .or_default()
                .extend(augs.clone());
        }
    }

    // Merge global augmentations from all files
    // When checking a file, we need access to `declare global` augmentations from all other files.
    // Each augmentation gets tagged with its source arena for cross-file resolution.
    let mut merged_global_augmentations: rustc_hash::FxHashMap<
        String,
        Vec<crate::binder::GlobalAugmentation>,
    > = rustc_hash::FxHashMap::default();

    for other_file in &program.files {
        for (name, decls) in &other_file.global_augmentations {
            merged_global_augmentations
                .entry(name.clone())
                .or_default()
                .extend(decls.iter().map(|aug| {
                    // Tag each augmentation with its source file's arena
                    // so the checker can read declaration nodes from the correct arena
                    crate::binder::GlobalAugmentation::with_arena(
                        aug.node,
                        Arc::clone(&other_file.arena),
                    )
                }));
        }
    }

    let mut binder = BinderState::from_bound_state_with_scopes_and_augmentations(
        BinderOptions::default(),
        program.symbols.clone(),
        file_locals,
        file.node_symbols.clone(),
        BinderStateScopeInputs {
            scopes: file.scopes.clone(),
            node_scope_ids: file.node_scope_ids.clone(),
            global_augmentations: merged_global_augmentations,
            module_augmentations: merged_module_augmentations,
            module_exports: program.module_exports.clone(),
            reexports: program.reexports.clone(),
            wildcard_reexports: program.wildcard_reexports.clone(),
            symbol_arenas: program.symbol_arenas.clone(),
            declaration_arenas: program.declaration_arenas.clone(),
            shorthand_ambient_modules: program.shorthand_ambient_modules.clone(),
            modules_with_export_equals: FxHashSet::default(),
            flow_nodes: file.flow_nodes.clone(),
            node_flow: file.node_flow.clone(),
            switch_clause_to_switch: file.switch_clause_to_switch.clone(),
            expando_properties: file.expando_properties.clone(),
        },
    );

    binder.declared_modules = program.declared_modules.clone();

    // Mark lib symbols as merged since the MergedProgram's symbol arena
    // contains all remapped lib symbols with unique global IDs.
    // This enables the fast path in get_symbol() that avoids cross-binder lookups.
    binder.set_lib_symbols_merged(true);

    binder
}

/// Check function bodies with statistics
pub fn check_functions_with_stats(program: &MergedProgram) -> (CheckResult, CheckStats) {
    let result = check_functions_parallel(program);

    let stats = CheckStats {
        file_count: result.file_results.len(),
        function_count: result.function_count,
        diagnostic_count: result.diagnostic_count,
    };

    (result, stats)
}

/// Statistics about parallel type checking
#[derive(Debug, Clone)]
pub struct CheckStats {
    /// Number of files checked
    pub file_count: usize,
    /// Number of functions checked
    pub function_count: usize,
    /// Number of diagnostics produced
    pub diagnostic_count: usize,
}

/// Parse files and collect statistics
pub fn parse_files_with_stats(files: Vec<(String, String)>) -> (Vec<ParseResult>, ParallelStats) {
    let total_bytes: usize = files.iter().map(|(_, src)| src.len()).sum();
    let file_count = files.len();

    let results = parse_files_parallel(files);

    let total_nodes: usize = results.iter().map(|r| r.arena.len()).sum();
    let error_count: usize = results.iter().map(|r| r.parse_diagnostics.len()).sum();

    let stats = ParallelStats {
        file_count,
        total_bytes,
        total_nodes,
        error_count,
    };

    (results, stats)
}

#[cfg(test)]
#[path = "../tests/parallel_tests.rs"]
mod tests;