oxc_semantic 0.128.0

A collection of JavaScript tools written in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
//! Semantic Builder

use std::{
    cell::{Cell, RefCell},
    mem,
};

use rustc_hash::FxHashMap;

use oxc_allocator::Address;
use oxc_ast::{AstKind, ast::*};
use oxc_ast_visit::Visit;
#[cfg(feature = "cfg")]
use oxc_cfg::{
    ControlFlowGraphBuilder, CtxCursor, CtxFlags, EdgeType, ErrorEdgeKind, InstructionKind,
    IterationInstructionKind, ReturnInstructionKind,
};
use oxc_diagnostics::OxcDiagnostic;
use oxc_span::{SourceType, Span};
use oxc_str::{Ident, IdentHashMap};
use oxc_syntax::{
    node::{NodeFlags, NodeId},
    reference::{Reference, ReferenceFlags, ReferenceId},
    scope::{ScopeFlags, ScopeId},
    symbol::{SymbolFlags, SymbolId},
};

use crate::{
    Semantic,
    binder::{Binder, ModuleInstanceState},
    checker,
    class::ClassTableBuilder,
    diagnostics::redeclaration,
    label::UnusedLabels,
    node::AstNodes,
    scoping::{Bindings, Scoping},
    stats::Stats,
    unresolved_stack::UnresolvedReferences,
};
#[cfg(feature = "jsdoc")]
use oxc_jsdoc::JSDocBuilder;

#[cfg(feature = "cfg")]
macro_rules! control_flow {
    ($self:ident, |$cfg:tt| $body:expr) => {
        if let Some($cfg) = &mut $self.cfg { $body } else { Default::default() }
    };
}

#[cfg(not(feature = "cfg"))]
macro_rules! control_flow {
    ($self:ident, |$cfg:tt| $body:expr) => {{
        #[expect(clippy::unused_unit)]
        {
            let _ = $self; // Suppress unused variable warning
            ()
        }
    }};
}

/// Semantic Builder
///
/// Traverses a parsed AST and builds a [`Semantic`] representation of the
/// program.
///
/// The main API is the [`build`] method.
///
/// [`build`]: SemanticBuilder::build
pub struct SemanticBuilder<'a> {
    /// source code of the parsed program
    pub(crate) source_text: &'a str,

    /// source type of the parsed program
    pub(crate) source_type: SourceType,

    /// Semantic early errors such as redeclaration errors.
    pub(crate) errors: RefCell<Vec<OxcDiagnostic>>,

    // states
    pub(crate) current_node_id: NodeId,
    pub(crate) current_node_flags: NodeFlags,
    pub(crate) current_scope_id: ScopeId,
    /// `NodeId` of current `Function` (not including arrow functions).
    /// When not in a function, is `NodeId` of `Program`.
    pub(crate) current_function_node_id: NodeId,
    pub(crate) module_instance_state_cache: FxHashMap<Address, ModuleInstanceState>,
    current_reference_flags: ReferenceFlags,
    /// Symbols that have been hoisted out of a scope (e.g. `var` declarations hoisted to
    /// the enclosing function scope, or Annex B function declarations hoisted to the var scope).
    /// Keyed by the **original** scope the symbol was declared in, so that future declarations
    /// in that scope can still detect redeclarations via `check_redeclaration`.
    pub(crate) hoisting_variables: FxHashMap<ScopeId, IdentHashMap<'a, SymbolId>>,

    // builders
    pub(crate) nodes: AstNodes<'a>,
    pub(crate) scoping: Scoping,

    pub(crate) unresolved_references: UnresolvedReferences<'a>,
    /// Checkpoint for early resolution of function parameter / catch parameter references.
    /// Tracks the start index in the flat unresolved references list.
    unresolved_references_checkpoint: usize,

    unused_labels: UnusedLabels<'a>,
    #[cfg(feature = "jsdoc")]
    jsdoc: JSDocBuilder<'a>,
    stats: Option<Stats>,
    excess_capacity: f64,

    /// Should enum member values be evaluated?
    enum_eval: bool,

    /// Should additional syntax checks be performed?
    ///
    /// See: [`crate::checker::check`]
    check_syntax_error: bool,

    #[cfg(feature = "cfg")]
    pub(crate) cfg: Option<ControlFlowGraphBuilder<'a>>,
    #[cfg(not(feature = "cfg"))]
    #[expect(unused)]
    pub(crate) cfg: (),

    pub(crate) class_table_builder: ClassTableBuilder<'a>,

    #[cfg(feature = "cfg")]
    ast_node_records: Vec<NodeId>,
}

/// Data returned by [`SemanticBuilder::build`].
pub struct SemanticBuilderReturn<'a> {
    /// Built semantic model.
    pub semantic: Semantic<'a>,
    /// Diagnostics collected during semantic analysis.
    pub errors: Vec<OxcDiagnostic>,
}

impl Default for SemanticBuilder<'_> {
    fn default() -> Self {
        Self::new()
    }
}

impl<'a> SemanticBuilder<'a> {
    /// Create a new semantic builder with default settings.
    pub fn new() -> Self {
        let scoping = Scoping::default();
        let current_scope_id = scoping.root_scope_id();

        Self {
            source_text: "",
            source_type: SourceType::default(),
            errors: RefCell::new(vec![]),
            current_node_id: NodeId::new(0),
            current_node_flags: NodeFlags::empty(),
            current_reference_flags: ReferenceFlags::empty(),
            current_scope_id,
            current_function_node_id: NodeId::ROOT,
            module_instance_state_cache: FxHashMap::default(),
            nodes: AstNodes::default(),
            hoisting_variables: FxHashMap::default(),
            scoping,
            unresolved_references: UnresolvedReferences::new(),
            unresolved_references_checkpoint: 0,
            unused_labels: UnusedLabels::default(),
            #[cfg(feature = "jsdoc")]
            jsdoc: JSDocBuilder::default(),
            stats: None,
            excess_capacity: 0.0,
            enum_eval: false,
            check_syntax_error: false,
            #[cfg(feature = "cfg")]
            cfg: None,
            #[cfg(not(feature = "cfg"))]
            cfg: (),
            class_table_builder: ClassTableBuilder::new(),
            #[cfg(feature = "cfg")]
            ast_node_records: Vec::new(),
        }
    }

    /// Enable/disable additional syntax checks.
    ///
    /// Set this to `true` to enable additional syntax checks. Without these,
    /// there is no guarantee that the parsed program follows the ECMAScript
    /// spec.
    ///
    /// By default, this is `false`.
    #[must_use]
    pub fn with_check_syntax_error(mut self, yes: bool) -> Self {
        self.check_syntax_error = yes;
        self
    }

    /// Enable or disable evaluation of TypeScript enum member values.
    ///
    /// When enabled, enum member values are computed during semantic analysis
    /// and stored in [`Scoping`], allowing the transformer to inline const enum
    /// member accesses.
    ///
    /// By default, this is `false`.
    #[must_use]
    pub fn with_enum_eval(mut self, yes: bool) -> Self {
        self.enum_eval = yes;
        self
    }

    /// Enable or disable building a [`ControlFlowGraph`].
    ///
    /// [`ControlFlowGraph`]: oxc_cfg::ControlFlowGraph
    #[must_use]
    #[cfg(feature = "cfg")]
    pub fn with_cfg(mut self, cfg: bool) -> Self {
        self.cfg = if cfg { Some(ControlFlowGraphBuilder::default()) } else { None };
        self
    }

    #[cfg(not(feature = "cfg"))]
    #[must_use]
    /// No-op when `cfg` feature is disabled.
    pub fn with_cfg(self, _cfg: bool) -> Self {
        self
    }

    /// Provide statistics about AST to optimize memory usage of semantic analysis.
    ///
    /// Accurate statistics can greatly improve performance, especially for large ASTs.
    /// If no stats are provided, [`SemanticBuilder::build`] will compile stats by performing
    /// a complete AST traversal.
    /// If semantic analysis has already been performed on this AST, get the existing stats with
    /// [`Semantic::stats`], and pass them in with this method, to avoid the stats collection AST pass.
    #[must_use]
    pub fn with_stats(mut self, stats: Stats) -> Self {
        self.stats = Some(stats);
        self
    }

    /// Request `SemanticBuilder` to allocate excess capacity for scopes, symbols, and references.
    ///
    /// `excess_capacity` is provided as a fraction.
    /// e.g. to over-allocate by 20%, pass `0.2` as `excess_capacity`.
    ///
    /// Has no effect if a `Stats` object is provided with [`SemanticBuilder::with_stats`],
    /// only if `SemanticBuilder` is calculating stats itself.
    ///
    /// This is useful when you intend to modify `Semantic`, adding more `nodes`, `scopes`, `symbols`,
    /// or `references`. Allocating excess capacity for these additions at the outset prevents
    /// `Semantic`'s data structures needing to grow later on which involves memory copying.
    /// For large ASTs with a lot of semantic data, re-allocation can be very costly.
    #[must_use]
    pub fn with_excess_capacity(mut self, excess_capacity: f64) -> Self {
        self.excess_capacity = excess_capacity;
        self
    }

    /// Finalize the builder.
    ///
    /// # Panics
    pub fn build(mut self, program: &'a Program<'a>) -> SemanticBuilderReturn<'a> {
        self.source_text = program.source_text;
        self.source_type = program.source_type;
        #[cfg(feature = "jsdoc")]
        {
            self.jsdoc = JSDocBuilder::new(self.source_text, &program.comments);
        }

        // Use counts of nodes, scopes, symbols, and references to pre-allocate sufficient capacity
        // in `AstNodes`, `ScopeTree` and `SymbolTable`.
        //
        // This means that as we traverse the AST and fill up these structures with data,
        // they never need to grow and reallocate - which is an expensive operation as it
        // involves copying all the memory from the old allocation to the new one.
        // For large source files, these structures are very large, so growth is very costly
        // as it involves copying massive chunks of memory.
        // Avoiding this growth produces up to 30% perf boost on our benchmarks.
        //
        // If user did not provide existing `Stats`, calculate them by visiting AST.
        #[cfg_attr(not(debug_assertions), expect(unused_variables))]
        let (stats, check_stats) = if let Some(stats) = self.stats {
            (stats, None)
        } else {
            let stats = Stats::count(program);
            let stats_with_excess = stats.increase_by(self.excess_capacity);
            (stats_with_excess, Some(stats))
        };
        self.nodes.reserve(stats.nodes as usize);
        self.scoping.reserve(
            stats.symbols as usize,
            stats.references as usize,
            stats.scopes as usize,
        );

        // Visit AST to generate scopes tree etc
        self.visit_program(program);

        // Check that estimated counts accurately (unless in release mode)
        #[cfg(debug_assertions)]
        if let Some(stats) = check_stats {
            #[expect(clippy::cast_possible_truncation)]
            let actual_stats = Stats::new(
                self.nodes.len() as u32,
                self.scoping.scopes_len() as u32,
                self.scoping.symbols_len() as u32,
                self.scoping.references.len() as u32,
            );
            stats.assert_accurate(actual_stats);
        }

        // Root unresolved references are already populated by `resolve_all_references()`
        // which is called at the end of `visit_program()`.

        #[cfg(feature = "jsdoc")]
        let jsdoc = {
            let result = self.jsdoc.build();
            crate::jsdoc::JSDocFinder::new(result.attached, result.not_attached)
        };

        #[cfg(debug_assertions)]
        self.unused_labels.assert_empty();

        let semantic = Semantic {
            source_text: self.source_text,
            source_type: self.source_type,
            comments: &program.comments,
            irregular_whitespaces: [].into(),
            nodes: self.nodes,
            scoping: self.scoping,
            classes: self.class_table_builder.build(),
            #[cfg(feature = "jsdoc")]
            jsdoc,
            unused_labels: self.unused_labels.labels,
            #[cfg(feature = "cfg")]
            cfg: self.cfg.map(ControlFlowGraphBuilder::build),
            #[cfg(not(feature = "cfg"))]
            cfg: (),
        };
        SemanticBuilderReturn { semantic, errors: self.errors.into_inner() }
    }

    /// Push a Syntax Error
    pub(crate) fn error(&self, error: OxcDiagnostic) {
        self.errors.borrow_mut().push(error);
    }

    pub(crate) fn in_declare_scope(&self) -> bool {
        self.source_type.is_typescript_definition()
            || self
                .scoping
                .scope_ancestors(self.current_scope_id)
                .any(|scope_id| self.scoping.scope_flags(scope_id).is_ts_module_block())
    }

    fn create_ast_node(&mut self, kind: AstKind<'a>) {
        #[cfg(not(feature = "jsdoc"))]
        let flags = self.current_node_flags;
        #[cfg(feature = "jsdoc")]
        let mut flags = self.current_node_flags;
        #[cfg(feature = "jsdoc")]
        if self.jsdoc.retrieve_attached_jsdoc(&kind) {
            flags |= NodeFlags::JSDoc;
        }

        self.current_node_id = self.nodes.add_node(
            kind,
            self.current_scope_id,
            self.current_node_id,
            #[cfg(feature = "cfg")]
            control_flow!(self, |cfg| cfg.current_node_ix),
            flags,
        );
        self.record_ast_node();
    }

    #[inline]
    fn pop_ast_node(&mut self) {
        self.current_node_id = self.nodes.parent_id(self.current_node_id);
    }

    #[inline]
    #[cfg(feature = "cfg")]
    fn record_ast_nodes(&mut self) {
        if self.cfg.is_some() {
            self.ast_node_records.push(NodeId::DUMMY);
        }
    }

    #[inline]
    #[cfg(feature = "cfg")]
    fn retrieve_recorded_ast_node(&mut self) -> Option<NodeId> {
        if self.cfg.is_some() {
            Some(self.ast_node_records.pop().expect("there is no ast node record to stop."))
        } else {
            None
        }
    }

    #[inline]
    #[cfg(feature = "cfg")]
    fn record_ast_node(&mut self) {
        // The `self.cfg.is_some()` check here could be removed, since `ast_node_records` is empty
        // if CFG is disabled. But benchmarks showed removing the extra check is a perf regression.
        // <https://github.com/oxc-project/oxc/pull/4273>
        if self.cfg.is_some()
            && let Some(record) = self.ast_node_records.last_mut()
            && *record == NodeId::DUMMY
        {
            *record = self.current_node_id;
        }
    }

    #[inline]
    #[cfg(not(feature = "cfg"))]
    #[expect(clippy::unused_self, clippy::needless_pass_by_ref_mut)]
    fn record_ast_node(&mut self) {}

    #[inline]
    pub(crate) fn current_scope_flags(&self) -> ScopeFlags {
        self.scoping.scope_flags(self.current_scope_id)
    }

    /// Is the current scope in strict mode?
    #[inline]
    pub(crate) fn strict_mode(&self) -> bool {
        self.current_scope_flags().is_strict_mode()
    }

    /// Declares a `Symbol` for the node, adds it to symbol table, and binds it to the scope.
    ///
    /// includes: the `SymbolFlags` that node has in addition to its declaration type (eg: export, ambient, etc.)
    /// excludes: the flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
    ///
    /// Reports errors for conflicting identifier names.
    pub(crate) fn declare_symbol_on_scope(
        &mut self,
        span: Span,
        name: Ident<'a>,
        scope_id: ScopeId,
        includes: SymbolFlags,
        excludes: SymbolFlags,
    ) -> SymbolId {
        if let Some(symbol_id) = self.check_redeclaration(scope_id, span, name, excludes) {
            self.add_redeclare_variable(symbol_id, includes, span);
            self.scoping.union_symbol_flag(symbol_id, includes);
            return symbol_id;
        }

        let symbol_id =
            self.scoping.create_symbol(span, name, includes, scope_id, self.current_node_id);

        self.scoping.add_binding(scope_id, name, symbol_id);
        symbol_id
    }

    /// Declare a new symbol on the current scope.
    pub(crate) fn declare_symbol(
        &mut self,
        span: Span,
        name: Ident<'a>,
        includes: SymbolFlags,
        excludes: SymbolFlags,
    ) -> SymbolId {
        self.declare_symbol_on_scope(span, name, self.current_scope_id, includes, excludes)
    }

    /// Check if a symbol with the same name has already been declared in the
    /// current scope. Returns the symbol ID if it exists and is not excluded by `excludes`.
    pub(crate) fn check_redeclaration(
        &self,
        scope_id: ScopeId,
        span: Span,
        name: Ident<'_>,
        excludes: SymbolFlags,
    ) -> Option<SymbolId> {
        let symbol_id = self.scoping.get_binding(scope_id, name).or_else(|| {
            self.hoisting_variables.get(&scope_id).and_then(|symbols| symbols.get(&name).copied())
        })?;

        // `(function n(n) {})()`
        //              ^ is not a redeclaration
        // Since we put the function expression binding 'n' Symbol into the function itself scope,
        // then defining a variable with the same name as the function name will be considered
        // a redeclaration, but it's actually not a redeclaration, so if the symbol declaration
        // is a function expression, then return None to tell the caller that it's not a redeclaration.
        if self.scoping.symbol_flags(symbol_id).is_function()
            && self
                .nodes
                .kind(self.scoping.symbol_declaration(symbol_id))
                .as_function()
                .is_some_and(Function::is_expression)
        {
            return None;
        }

        let flags = self.scoping.symbol_flags(symbol_id);
        if flags.intersects(excludes) {
            let symbol_span = self.scoping.symbol_span(symbol_id);
            self.error(redeclaration(&name, symbol_span, span));
        }

        Some(symbol_id)
    }

    /// Declare an unresolved reference in the current scope.
    ///
    /// # Panics
    #[inline]
    pub(crate) fn declare_reference(
        &mut self,
        name: Ident<'a>,
        reference: Reference,
    ) -> ReferenceId {
        let reference_id = self.scoping.create_reference(reference);
        self.unresolved_references.push(name, reference_id);
        reference_id
    }

    /// Declares a `Symbol` for the node, shadowing previous declarations in the same scope.
    pub(crate) fn declare_shadow_symbol(
        &mut self,
        name: Ident<'a>,
        span: Span,
        scope_id: ScopeId,
        includes: SymbolFlags,
    ) -> SymbolId {
        let symbol_id = self.scoping.create_symbol(
            span,
            name,
            includes,
            self.current_scope_id,
            self.current_node_id,
        );
        self.scoping.insert_binding(scope_id, name, symbol_id);
        symbol_id
    }

    /// Resolve all collected references by walking up the scope chain from each
    /// reference's scope. This replaces the old bubble-up approach where unresolved
    /// references were merged into parent scope hashmaps on every scope exit.
    ///
    /// Walk-up is faster because it only does hashmap lookups (no drain+insert),
    /// and reference creation is a simple Vec push instead of a hashmap insert.
    fn resolve_all_references(&mut self) {
        let refs = self.unresolved_references.take();
        for (name, reference_id) in refs {
            if !self.walk_up_resolve_reference(name, reference_id) {
                self.scoping.add_root_unresolved_reference(name, reference_id);
            }
        }
    }

    /// Walk up the scope chain trying to resolve a reference.
    /// Returns `true` if resolved.
    #[expect(clippy::inline_always, reason = "Hot path — called for every reference resolution")]
    #[inline(always)]
    fn walk_up_resolve_reference(&mut self, name: Ident<'a>, reference_id: ReferenceId) -> bool {
        let mut scope_id = Some(self.scoping.references[reference_id].scope_id());
        while let Some(sid) = scope_id {
            if let Some(symbol_id) = self.scoping.get_binding(sid, name)
                && self.try_resolve_reference(reference_id, symbol_id)
            {
                return true;
            }
            scope_id = self.scoping.scope_parent_id(sid);
        }
        false
    }

    /// Try to resolve a reference to a symbol. Returns `true` if resolved.
    fn try_resolve_reference(&mut self, reference_id: ReferenceId, symbol_id: SymbolId) -> bool {
        let symbol_flags = self.scoping.symbol_flags(symbol_id);
        let reference = &mut self.scoping.references[reference_id];
        let flags = reference.flags_mut();

        // Determine whether the symbol can be referenced by this reference.
        // For pure type references (not value or typeof) in qualified names,
        // only resolve to namespaces (modules, namespaces, enums, imports).
        // Type parameters and type aliases cannot have member access in type space.
        // Value references (including typeof) can always have member access.
        let can_resolve = if flags.is_namespace()
            && !flags.is_value()
            && !flags.is_value_as_type()
            && !symbol_flags.can_be_referenced_as_namespace()
        {
            false
        } else {
            (flags.is_value() && symbol_flags.can_be_referenced_by_value())
                || (flags.is_type() && symbol_flags.can_be_referenced_by_type())
                || (flags.is_value_as_type() && symbol_flags.can_be_referenced_by_value_as_type())
        };

        if !can_resolve {
            return false;
        }

        if symbol_flags.is_value() && flags.is_value() {
            // The non type-only ExportSpecifier can reference both type/value symbols,
            // if the symbol is a value symbol and reference flag is not type-only,
            // remove the type flag. For example: `const B = 1; export { B };`
            *flags -= ReferenceFlags::Type;
        } else {
            // 1. ReferenceFlags::ValueAsType -> ReferenceFlags::Type
            // `const ident = 0; typeof ident`
            //                          ^^^^^ -> The ident is a value symbols,
            //                                   but it used as a type.
            // 2. ReferenceFlags::Value | ReferenceFlags::Type -> ReferenceFlags::Type
            // `type ident = string; export default ident;
            //                                      ^^^^^ We have confirmed the symbol is
            //                                            not a value symbol, so we need to
            //                                            make sure the reference is a type only.
            *flags = ReferenceFlags::Type;
        }
        reference.set_symbol_id(symbol_id);
        self.scoping.add_resolved_reference(symbol_id, reference_id);
        true
    }

    /// Early-resolve references collected since the checkpoint by walking up the
    /// full scope chain. Used for function parameters and catch parameters where
    /// references must be resolved before entering the function body, to avoid
    /// binding to variables declared inside the body (which share the same scope).
    ///
    /// Resolved references are removed. Unresolved references stay in the flat
    /// list for later resolution by `resolve_all_references` (which handles
    /// forward references to declarations not yet visited).
    fn resolve_references_for_current_scope(&mut self) {
        let checkpoint = self.unresolved_references_checkpoint;
        let refs = self.unresolved_references.slice_from(checkpoint).to_vec();
        if refs.is_empty() {
            return;
        }
        self.unresolved_references.truncate(checkpoint);

        for (name, reference_id) in refs {
            if !self.walk_up_resolve_reference(name, reference_id) {
                // Keep in the flat list — may resolve later via forward declarations
                self.unresolved_references.push(name, reference_id);
            }
        }
    }

    pub(crate) fn add_redeclare_variable(
        &mut self,
        symbol_id: SymbolId,
        flags: SymbolFlags,
        span: Span,
    ) {
        self.scoping.add_symbol_redeclaration(symbol_id, flags, self.current_node_id, span);
    }
}

impl<'a> Visit<'a> for SemanticBuilder<'a> {
    // NB: Not called for `Program`
    fn enter_scope(&mut self, flags: ScopeFlags, scope_id: &Cell<Option<ScopeId>>) {
        let parent_scope_id = self.current_scope_id;
        let flags = self.scoping.get_new_scope_flags(flags, parent_scope_id);
        self.current_scope_id =
            self.scoping.add_scope(Some(parent_scope_id), self.current_node_id, flags);
        scope_id.set(Some(self.current_scope_id));
    }

    // NB: Not called for `Program`
    fn leave_scope(&mut self) {
        // `get_parent_id` always returns `Some` because this method is not called for `Program`.
        // So we could `.unwrap()` here. But that seems to produce a small perf impact, probably because
        // `leave_scope` then doesn't get inlined because of its larger size due to the panic code.
        let parent_id = self.scoping.scope_parent_id(self.current_scope_id);

        debug_assert!(parent_id.is_some());
        if let Some(parent_id) = parent_id {
            if self.scoping.scope_flags(self.current_scope_id).contains_direct_eval() {
                self.scoping.scope_flags_mut(parent_id).insert(ScopeFlags::DirectEval);
            }
            self.current_scope_id = parent_id;
        }
    }

    // NB: Not called for `Program`.
    fn enter_node(&mut self, kind: AstKind<'a>) {
        self.create_ast_node(kind);
    }

    /// Both this function and `checker::check` must be inlined. Each `visit_*` method calls
    /// `leave_node` with a statically known `AstKind`, so inlining allows the compiler to
    /// constant-fold `checker::check`'s match, eliminating all non-matching arms.
    #[expect(
        clippy::inline_always,
        reason = "enables compile-time match elimination in checker::check"
    )]
    #[inline(always)]
    fn leave_node(&mut self, kind: AstKind<'a>) {
        if self.check_syntax_error {
            checker::check(kind, self);
        }
        self.pop_ast_node();
    }

    fn visit_program(&mut self, program: &Program<'a>) {
        let kind = AstKind::Program(self.alloc(program));
        /* cfg */
        #[cfg(feature = "cfg")]
        let error_harness = control_flow!(self, |cfg| {
            let error_harness = cfg.attach_error_harness(ErrorEdgeKind::Implicit);
            let _program_basic_block = cfg.new_basic_block_normal();
            error_harness
        });
        /* cfg - must be above directives as directives are in cfg */

        // Don't call `enter_node` here as `Program` is a special case - node has itself as `parent_id`.
        // Inline the specific logic for `Program` here instead.
        // This avoids `Nodes::add_node` having to handle the special case.
        // We can also skip calling `self.enter_kind`, `self.record_ast_node`
        // and `self.jsdoc.retrieve_attached_jsdoc`, as they are all no-ops for `Program`.
        self.current_node_id = self.nodes.add_program_node(
            kind,
            self.current_scope_id,
            #[cfg(feature = "cfg")]
            control_flow!(self, |cfg| cfg.current_node_ix),
            self.current_node_flags,
        );

        // Don't call `enter_scope` here as `Program` is a special case - scope has no `parent_id`.
        // Inline the specific logic for `Program` here instead.
        // This simplifies logic in `enter_scope`, as it doesn't have to handle the special case.
        let mut flags = ScopeFlags::Top;
        if self.source_type.is_strict() || program.has_use_strict_directive() {
            flags |= ScopeFlags::StrictMode;
        }
        self.current_scope_id = self.scoping.add_scope(None, self.current_node_id, flags);
        program.scope_id.set(Some(self.current_scope_id));
        // NB: Don't call `self.unresolved_references.increment_scope_depth()`
        // as scope depth is initialized as 1 already (the scope depth for `Program`).

        if let Some(hashbang) = &program.hashbang {
            self.visit_hashbang(hashbang);
        }

        for directive in &program.directives {
            self.visit_directive(directive);
        }

        self.visit_statements(&program.body);

        /* cfg */
        control_flow!(self, |cfg| cfg.release_error_harness(error_harness));
        /* cfg */

        // Resolve all remaining unresolved references by walking up the scope chain.
        // This replaces the old bubble-up approach where references were merged on every scope exit.
        self.resolve_all_references();

        self.leave_node(kind);

        // Check `current_function_node_id` has been reset to as it was at start
        debug_assert!(self.current_function_node_id == NodeId::ROOT);
    }

    fn visit_break_statement(&mut self, stmt: &BreakStatement<'a>) {
        let kind = AstKind::BreakStatement(self.alloc(stmt));
        self.enter_node(kind);
        if let Some(label) = &stmt.label {
            self.unused_labels.reference(label.name);
        }

        /* cfg */
        #[cfg(feature = "cfg")]
        let node_id = self.current_node_id;
        /* cfg */

        if let Some(break_target) = &stmt.label {
            self.visit_label_identifier(break_target);
        }

        /* cfg */
        control_flow!(self, |cfg| cfg
            .append_break(node_id, stmt.label.as_ref().map(|it| it.name.as_str())));
        /* cfg */

        self.leave_node(kind);
    }

    fn visit_class(&mut self, class: &Class<'a>) {
        let kind = AstKind::Class(self.alloc(class));
        self.enter_node(kind);
        self.current_node_flags |= NodeFlags::Class;
        if class.is_declaration() {
            class.bind(self);
        }

        self.visit_decorators(&class.decorators);
        self.enter_scope(ScopeFlags::StrictMode, &class.scope_id);

        if class.is_expression() {
            // We need to bind class expressions in the class scope before visiting the identifier.
            class.bind(self);
        }

        if let Some(id) = &class.id {
            self.visit_binding_identifier(id);
        }

        if let Some(type_parameters) = &class.type_parameters {
            self.visit_ts_type_parameter_declaration(type_parameters);
        }
        if let Some(super_class) = &class.super_class {
            self.visit_expression(super_class);
        }
        if let Some(super_type_parameters) = &class.super_type_arguments {
            self.visit_ts_type_parameter_instantiation(super_type_parameters);
        }
        self.visit_ts_class_implements_list(&class.implements);
        self.visit_class_body(&class.body);

        self.leave_scope();
        self.leave_node(kind);
        self.current_node_flags -= NodeFlags::Class;
        self.class_table_builder.pop_class();
    }

    fn visit_block_statement(&mut self, it: &BlockStatement<'a>) {
        let kind = AstKind::BlockStatement(self.alloc(it));
        self.enter_node(kind);
        control_flow!(self, |cfg| cfg.enter_statement(self.current_node_id));

        let parent_scope_id = self.current_scope_id;
        self.enter_scope(ScopeFlags::empty(), &it.scope_id);

        // Move all bindings from catch clause param scope to catch clause body scope
        // to make it easier to resolve references and check redeclare errors
        if self.scoping.scope_flags(parent_scope_id).is_catch_clause() {
            let parent_bindings = self.scoping.cell.with_dependent_mut(|allocator, cell| {
                if cell.bindings[parent_scope_id].is_empty() {
                    None
                } else {
                    let mut parent_bindings = Bindings::new_in(allocator);
                    mem::swap(&mut cell.bindings[parent_scope_id], &mut parent_bindings);
                    let parent_symbol_ids = parent_bindings.values().copied().collect::<Vec<_>>();
                    cell.bindings[self.current_scope_id] = parent_bindings;
                    Some(parent_symbol_ids)
                }
            });
            if let Some(parent_bindings) = parent_bindings {
                for symbol_id in parent_bindings {
                    self.scoping.set_symbol_scope_id(symbol_id, self.current_scope_id);
                }
            }
        }

        self.visit_statements(&it.body);

        self.leave_scope();
        self.leave_node(kind);
    }

    fn visit_continue_statement(&mut self, stmt: &ContinueStatement<'a>) {
        let kind = AstKind::ContinueStatement(self.alloc(stmt));
        self.enter_node(kind);
        if let Some(label) = &stmt.label {
            self.unused_labels.reference(label.name);
        }

        /* cfg */
        #[cfg(feature = "cfg")]
        let node_id = self.current_node_id;
        /* cfg */

        if let Some(continue_target) = &stmt.label {
            self.visit_label_identifier(continue_target);
        }

        /* cfg */
        control_flow!(self, |cfg| cfg
            .append_continue(node_id, stmt.label.as_ref().map(|it| it.name.as_str())));
        /* cfg */

        self.leave_node(kind);
    }

    fn visit_do_while_statement(&mut self, stmt: &DoWhileStatement<'a>) {
        let kind = AstKind::DoWhileStatement(self.alloc(stmt));
        self.enter_node(kind);
        control_flow!(self, |cfg| cfg.enter_statement(self.current_node_id));

        /* cfg */
        #[cfg(feature = "cfg")]
        let (before_do_while_stmt_graph_ix, start_body_graph_ix) = control_flow!(self, |cfg| {
            let before_do_while_stmt_graph_ix = cfg.current_node_ix;
            let start_body_graph_ix = cfg.new_basic_block_normal();
            cfg.ctx(None).default().allow_break().allow_continue();
            (before_do_while_stmt_graph_ix, start_body_graph_ix)
        });
        /* cfg */

        self.visit_statement(&stmt.body);

        /* cfg - condition basic block */
        #[cfg(feature = "cfg")]
        let (after_body_graph_ix, start_of_condition_graph_ix) = control_flow!(self, |cfg| {
            let after_body_graph_ix = cfg.current_node_ix;
            let start_of_condition_graph_ix = cfg.new_basic_block_normal();
            (after_body_graph_ix, start_of_condition_graph_ix)
        });
        /* cfg */

        #[cfg(feature = "cfg")]
        self.record_ast_nodes();
        self.visit_expression(&stmt.test);
        #[cfg(feature = "cfg")]
        let test_node_id = self.retrieve_recorded_ast_node();

        /* cfg */
        control_flow!(self, |cfg| {
            cfg.append_condition_to(start_of_condition_graph_ix, test_node_id);
            let end_of_condition_graph_ix = cfg.current_node_ix;

            let end_do_while_graph_ix = cfg.new_basic_block_normal();

            // before do while to start of body basic block
            cfg.add_edge(before_do_while_stmt_graph_ix, start_body_graph_ix, EdgeType::Normal);
            // body of do-while to start of condition
            cfg.add_edge(after_body_graph_ix, start_of_condition_graph_ix, EdgeType::Normal);
            // end of condition to after do while
            cfg.add_edge(end_of_condition_graph_ix, end_do_while_graph_ix, EdgeType::Normal);
            // end of condition to after start of body
            cfg.add_edge(end_of_condition_graph_ix, start_body_graph_ix, EdgeType::Backedge);

            cfg.ctx(None)
                .mark_break(end_do_while_graph_ix)
                .mark_continue(start_of_condition_graph_ix)
                .resolve_with_upper_label();
        });
        /* cfg */

        self.leave_node(kind);
    }

    fn visit_logical_expression(&mut self, expr: &LogicalExpression<'a>) {
        // logical expressions are short-circuiting, and therefore
        // also represent control flow.
        // For example, in:
        //   foo && bar();
        // the bar() call will only be executed if foo is truthy.
        let kind = AstKind::LogicalExpression(self.alloc(expr));
        self.enter_node(kind);

        /* cfg - condition basic block */
        #[cfg(feature = "cfg")]
        let (before_logical_graph_ix, start_of_condition_graph_ix) = control_flow!(self, |cfg| {
            let before_logical_graph_ix = cfg.current_node_ix;
            let start_of_condition_graph_ix = cfg.new_basic_block_normal();
            (before_logical_graph_ix, start_of_condition_graph_ix)
        });
        /* cfg */

        #[cfg(feature = "cfg")]
        self.record_ast_nodes();
        self.visit_expression(&expr.left);
        #[cfg(feature = "cfg")]
        let left_node_id = self.retrieve_recorded_ast_node();

        /* cfg  */
        #[cfg(feature = "cfg")]
        let (left_expr_end_ix, right_expr_start_ix) = control_flow!(self, |cfg| {
            cfg.append_condition_to(start_of_condition_graph_ix, left_node_id);
            let left_expr_end_ix = cfg.current_node_ix;
            let right_expr_start_ix = cfg.new_basic_block_normal();
            (left_expr_end_ix, right_expr_start_ix)
        });
        /* cfg  */

        self.visit_expression(&expr.right);

        /* cfg */
        control_flow!(self, |cfg| {
            let right_expr_end_ix = cfg.current_node_ix;
            let after_logical_expr_ix = cfg.new_basic_block_normal();

            cfg.add_edge(before_logical_graph_ix, start_of_condition_graph_ix, EdgeType::Normal);
            cfg.add_edge(left_expr_end_ix, right_expr_start_ix, EdgeType::Normal);
            cfg.add_edge(left_expr_end_ix, after_logical_expr_ix, EdgeType::Normal);
            cfg.add_edge(right_expr_end_ix, after_logical_expr_ix, EdgeType::Normal);
        });
        /* cfg */

        self.leave_node(kind);
    }

    fn visit_assignment_expression(&mut self, expr: &AssignmentExpression<'a>) {
        // assignment expressions can include an operator, which
        // can be used to determine the control flow of the expression.
        // For example, in:
        //   foo &&= super();
        // the super() call will only be executed if foo is truthy.

        let kind = AstKind::AssignmentExpression(self.alloc(expr));
        self.enter_node(kind);

        if !expr.operator.is_assign() {
            // Only when the operator is not an `=` operator, the left-hand side is both read and write.
            // <https://tc39.es/ecma262/#sec-assignment-operators-runtime-semantics-evaluation>
            self.current_reference_flags = ReferenceFlags::read_write();
        }

        /* cfg - condition basic block */
        #[cfg(feature = "cfg")]
        let (before_assignment_graph_ix, start_of_condition_graph_ix) =
            control_flow!(self, |cfg| {
                if expr.operator.is_logical() {
                    let before_assignment_graph_ix = cfg.current_node_ix;
                    let start_of_condition_graph_ix = cfg.new_basic_block_normal();
                    (Some(before_assignment_graph_ix), Some(start_of_condition_graph_ix))
                } else {
                    (None, None)
                }
            });
        /* cfg */

        #[cfg(feature = "cfg")]
        if expr.operator.is_logical() {
            self.record_ast_nodes();
        }
        self.visit_assignment_target(&expr.left);
        #[cfg(feature = "cfg")]
        let target_node_id =
            if expr.operator.is_logical() { self.retrieve_recorded_ast_node() } else { None };

        /* cfg  */
        #[cfg(feature = "cfg")]
        let cfg_ixs = control_flow!(self, |cfg| {
            if expr.operator.is_logical() {
                if let Some(condition_ix) = start_of_condition_graph_ix {
                    cfg.append_condition_to(condition_ix, target_node_id);
                }
                let target_end_ix = cfg.current_node_ix;
                let expr_start_ix = cfg.new_basic_block_normal();
                Some((target_end_ix, expr_start_ix))
            } else {
                None
            }
        });
        /* cfg  */

        self.visit_expression(&expr.right);

        /* cfg */
        control_flow!(self, |cfg| {
            if let Some((target_end_ix, expr_start_ix)) = cfg_ixs {
                let expr_end_ix = cfg.current_node_ix;
                let after_assignment_ix = cfg.new_basic_block_normal();

                if let Some((before_ix, condition_ix)) =
                    before_assignment_graph_ix.zip(start_of_condition_graph_ix)
                {
                    cfg.add_edge(before_ix, condition_ix, EdgeType::Normal);
                }
                cfg.add_edge(target_end_ix, expr_start_ix, EdgeType::Normal);
                cfg.add_edge(target_end_ix, after_assignment_ix, EdgeType::Normal);
                cfg.add_edge(expr_end_ix, after_assignment_ix, EdgeType::Normal);
            }
        });
        /* cfg */

        self.leave_node(kind);
    }

    fn visit_conditional_expression(&mut self, expr: &ConditionalExpression<'a>) {
        let kind = AstKind::ConditionalExpression(self.alloc(expr));
        self.enter_node(kind);

        /* cfg - condition basic block */
        #[cfg(feature = "cfg")]
        let (before_conditional_graph_ix, start_of_condition_graph_ix) =
            control_flow!(self, |cfg| {
                let before_conditional_graph_ix = cfg.current_node_ix;
                let start_of_condition_graph_ix = cfg.new_basic_block_normal();
                (before_conditional_graph_ix, start_of_condition_graph_ix)
            });
        /* cfg */

        #[cfg(feature = "cfg")]
        self.record_ast_nodes();
        // The test of a conditional is always a pure read — strip MemberWriteTarget
        // so that `(a ? x : y).foo = 1` doesn't mark `a` as a property-write target.
        let saved_flags = self.current_reference_flags;
        self.current_reference_flags -= ReferenceFlags::MemberWriteTarget;
        self.visit_expression(&expr.test);
        self.current_reference_flags = saved_flags;
        #[cfg(feature = "cfg")]
        let test_node_id = self.retrieve_recorded_ast_node();

        /* cfg */
        #[cfg(feature = "cfg")]
        let (after_condition_graph_ix, before_consequent_expr_graph_ix) =
            control_flow!(self, |cfg| {
                cfg.append_condition_to(start_of_condition_graph_ix, test_node_id);
                let after_condition_graph_ix = cfg.current_node_ix;
                // conditional expression basic block
                let before_consequent_expr_graph_ix = cfg.new_basic_block_normal();
                (after_condition_graph_ix, before_consequent_expr_graph_ix)
            });
        /* cfg */

        self.visit_expression(&expr.consequent);

        /* cfg */
        #[cfg(feature = "cfg")]
        let (after_consequent_expr_graph_ix, start_alternate_graph_ix) =
            control_flow!(self, |cfg| {
                let after_consequent_expr_graph_ix = cfg.current_node_ix;
                let start_alternate_graph_ix = cfg.new_basic_block_normal();
                (after_consequent_expr_graph_ix, start_alternate_graph_ix)
            });
        /* cfg */

        self.visit_expression(&expr.alternate);

        /* cfg */
        control_flow!(self, |cfg| {
            let after_alternate_graph_ix = cfg.current_node_ix;
            /* bb after conditional expression joins consequent and alternate */
            let after_conditional_graph_ix = cfg.new_basic_block_normal();

            cfg.add_edge(
                before_conditional_graph_ix,
                start_of_condition_graph_ix,
                EdgeType::Normal,
            );

            cfg.add_edge(
                after_consequent_expr_graph_ix,
                after_conditional_graph_ix,
                EdgeType::Normal,
            );
            cfg.add_edge(after_condition_graph_ix, before_consequent_expr_graph_ix, EdgeType::Jump);

            cfg.add_edge(after_condition_graph_ix, start_alternate_graph_ix, EdgeType::Normal);
            cfg.add_edge(after_alternate_graph_ix, after_conditional_graph_ix, EdgeType::Normal);
        });
        /* cfg */

        self.leave_node(kind);
    }

    fn visit_for_statement(&mut self, stmt: &ForStatement<'a>) {
        let kind = AstKind::ForStatement(self.alloc(stmt));
        self.enter_node(kind);
        control_flow!(self, |cfg| cfg.enter_statement(self.current_node_id));
        self.enter_scope(ScopeFlags::empty(), &stmt.scope_id);
        if let Some(init) = &stmt.init {
            self.visit_for_statement_init(init);
        }
        /* cfg */
        #[cfg(feature = "cfg")]
        let (before_for_graph_ix, test_graph_ix) = control_flow!(self, |cfg| {
            let before_for_graph_ix = cfg.current_node_ix;
            let test_graph_ix = cfg.new_basic_block_normal();
            (before_for_graph_ix, test_graph_ix)
        });
        /* cfg */

        if let Some(test) = &stmt.test {
            #[cfg(feature = "cfg")]
            self.record_ast_nodes();
            self.visit_expression(test);
            #[cfg(feature = "cfg")]
            let test_node_id = self.retrieve_recorded_ast_node();

            /* cfg */
            control_flow!(self, |cfg| cfg.append_condition_to(test_graph_ix, test_node_id));
            /* cfg */
        }

        /* cfg */
        #[cfg(feature = "cfg")]
        let (after_test_graph_ix, update_graph_ix) =
            control_flow!(self, |cfg| (cfg.current_node_ix, cfg.new_basic_block_normal()));
        /* cfg */

        if let Some(update) = &stmt.update {
            self.visit_expression(update);
        }

        /* cfg */
        #[cfg(feature = "cfg")]
        let before_body_graph_ix = control_flow!(self, |cfg| {
            let before_body_graph_ix = cfg.new_basic_block_normal();
            cfg.ctx(None).default().allow_break().allow_continue();
            before_body_graph_ix
        });
        /* cfg */

        self.visit_statement(&stmt.body);

        /* cfg */
        control_flow!(self, |cfg| {
            let after_body_graph_ix = cfg.current_node_ix;
            let after_for_stmt = cfg.new_basic_block_normal();
            cfg.add_edge(before_for_graph_ix, test_graph_ix, EdgeType::Normal);
            cfg.add_edge(after_test_graph_ix, before_body_graph_ix, EdgeType::Jump);
            cfg.add_edge(after_body_graph_ix, update_graph_ix, EdgeType::Backedge);
            cfg.add_edge(update_graph_ix, test_graph_ix, EdgeType::Backedge);
            cfg.add_edge(after_test_graph_ix, after_for_stmt, EdgeType::Normal);

            cfg.ctx(None)
                .mark_break(after_for_stmt)
                .mark_continue(update_graph_ix)
                .resolve_with_upper_label();
        });
        /* cfg */

        self.leave_scope();
        self.leave_node(kind);
    }

    fn visit_for_in_statement(&mut self, stmt: &ForInStatement<'a>) {
        let kind = AstKind::ForInStatement(self.alloc(stmt));
        self.enter_node(kind);
        control_flow!(self, |cfg| cfg.enter_statement(self.current_node_id));
        self.enter_scope(ScopeFlags::empty(), &stmt.scope_id);

        self.visit_for_statement_left(&stmt.left);

        /* cfg */
        #[cfg(feature = "cfg")]
        let (before_for_stmt_graph_ix, start_prepare_cond_graph_ix) =
            control_flow!(self, |cfg| (cfg.current_node_ix, cfg.new_basic_block_normal(),));
        /* cfg */

        #[cfg(feature = "cfg")]
        self.record_ast_nodes();
        self.visit_expression(&stmt.right);
        #[cfg(feature = "cfg")]
        let right_node_id = self.retrieve_recorded_ast_node();

        /* cfg */
        #[cfg(feature = "cfg")]
        let (end_of_prepare_cond_graph_ix, iteration_graph_ix, body_graph_ix) =
            control_flow!(self, |cfg| {
                let end_of_prepare_cond_graph_ix = cfg.current_node_ix;
                let iteration_graph_ix = cfg.new_basic_block_normal();
                cfg.append_iteration(right_node_id, IterationInstructionKind::In);
                let body_graph_ix = cfg.new_basic_block_normal();

                cfg.ctx(None).default().allow_break().allow_continue();
                (end_of_prepare_cond_graph_ix, iteration_graph_ix, body_graph_ix)
            });
        /* cfg */

        self.visit_statement(&stmt.body);

        /* cfg */
        control_flow!(self, |cfg| {
            let end_of_body_graph_ix = cfg.current_node_ix;
            let after_for_graph_ix = cfg.new_basic_block_normal();
            // connect before for statement to the iterable expression
            cfg.add_edge(before_for_stmt_graph_ix, start_prepare_cond_graph_ix, EdgeType::Normal);
            // connect the end of the iterable expression to the basic block with back edge
            cfg.add_edge(end_of_prepare_cond_graph_ix, iteration_graph_ix, EdgeType::Normal);
            // connect the basic block with back edge to the start of the body
            cfg.add_edge(iteration_graph_ix, body_graph_ix, EdgeType::Jump);
            // connect the end of the body back to the basic block
            // with back edge for the next iteration
            cfg.add_edge(end_of_body_graph_ix, iteration_graph_ix, EdgeType::Backedge);
            // connect the basic block with back edge to the basic block after the for loop
            // for when there are no more iterations left in the iterable
            cfg.add_edge(iteration_graph_ix, after_for_graph_ix, EdgeType::Normal);

            cfg.ctx(None)
                .mark_break(after_for_graph_ix)
                .mark_continue(iteration_graph_ix)
                .resolve_with_upper_label();
        });
        /* cfg */

        self.leave_scope();
        self.leave_node(kind);
    }

    fn visit_for_of_statement(&mut self, stmt: &ForOfStatement<'a>) {
        let kind = AstKind::ForOfStatement(self.alloc(stmt));
        self.enter_node(kind);
        control_flow!(self, |cfg| cfg.enter_statement(self.current_node_id));
        self.enter_scope(ScopeFlags::empty(), &stmt.scope_id);

        self.visit_for_statement_left(&stmt.left);

        /* cfg */
        #[cfg(feature = "cfg")]
        let (before_for_stmt_graph_ix, start_prepare_cond_graph_ix) =
            control_flow!(self, |cfg| (cfg.current_node_ix, cfg.new_basic_block_normal()));
        /* cfg */

        #[cfg(feature = "cfg")]
        self.record_ast_nodes();
        self.visit_expression(&stmt.right);
        #[cfg(feature = "cfg")]
        let right_node_id = self.retrieve_recorded_ast_node();

        /* cfg */
        #[cfg(feature = "cfg")]
        let (end_of_prepare_cond_graph_ix, iteration_graph_ix, body_graph_ix) =
            control_flow!(self, |cfg| {
                let end_of_prepare_cond_graph_ix = cfg.current_node_ix;
                let iteration_graph_ix = cfg.new_basic_block_normal();
                cfg.append_iteration(right_node_id, IterationInstructionKind::Of);
                let body_graph_ix = cfg.new_basic_block_normal();
                cfg.ctx(None).default().allow_break().allow_continue();
                (end_of_prepare_cond_graph_ix, iteration_graph_ix, body_graph_ix)
            });
        /* cfg */

        self.visit_statement(&stmt.body);

        /* cfg */
        control_flow!(self, |cfg| {
            let end_of_body_graph_ix = cfg.current_node_ix;
            let after_for_graph_ix = cfg.new_basic_block_normal();
            // connect before for statement to the iterable expression
            cfg.add_edge(before_for_stmt_graph_ix, start_prepare_cond_graph_ix, EdgeType::Normal);
            // connect the end of the iterable expression to the basic block with back edge
            cfg.add_edge(end_of_prepare_cond_graph_ix, iteration_graph_ix, EdgeType::Normal);
            // connect the basic block with back edge to the start of the body
            cfg.add_edge(iteration_graph_ix, body_graph_ix, EdgeType::Jump);
            // connect the end of the body back to the basic block
            // with back edge for the next iteration
            cfg.add_edge(end_of_body_graph_ix, iteration_graph_ix, EdgeType::Backedge);
            // connect the basic block with back edge to the basic block after the for loop
            // for when there are no more iterations left in the iterable
            cfg.add_edge(iteration_graph_ix, after_for_graph_ix, EdgeType::Normal);

            cfg.ctx(None)
                .mark_break(after_for_graph_ix)
                .mark_continue(iteration_graph_ix)
                .resolve_with_upper_label();
        });
        /* cfg */

        self.leave_scope();
        self.leave_node(kind);
    }

    fn visit_if_statement(&mut self, stmt: &IfStatement<'a>) {
        let kind = AstKind::IfStatement(self.alloc(stmt));
        self.enter_node(kind);
        control_flow!(self, |cfg| cfg.enter_statement(self.current_node_id));

        /* cfg - condition basic block */
        #[cfg(feature = "cfg")]
        let (before_if_stmt_graph_ix, start_of_condition_graph_ix) =
            control_flow!(self, |cfg| (cfg.current_node_ix, cfg.new_basic_block_normal(),));
        /* cfg */

        #[cfg(feature = "cfg")]
        self.record_ast_nodes();
        self.visit_expression(&stmt.test);
        #[cfg(feature = "cfg")]
        let test_node_id = self.retrieve_recorded_ast_node();

        /* cfg */
        #[cfg(feature = "cfg")]
        let (after_test_graph_ix, before_consequent_stmt_graph_ix) = control_flow!(self, |cfg| {
            cfg.append_condition_to(start_of_condition_graph_ix, test_node_id);
            (cfg.current_node_ix, cfg.new_basic_block_normal())
        });
        /* cfg */

        self.visit_statement(&stmt.consequent);

        /* cfg */
        #[cfg(feature = "cfg")]
        let after_consequent_stmt_graph_ix = control_flow!(self, |cfg| cfg.current_node_ix);
        /* cfg */

        #[cfg(feature = "cfg")]
        let else_graph_ix = if let Some(alternate) = &stmt.alternate {
            /* cfg */
            let else_graph_ix = control_flow!(self, |cfg| cfg.new_basic_block_normal());
            /* cfg */

            self.visit_statement(alternate);

            control_flow!(self, |cfg| Some((else_graph_ix, cfg.current_node_ix)))
        } else {
            None
        };

        #[cfg(not(feature = "cfg"))]
        if let Some(alternate) = &stmt.alternate {
            self.visit_statement(alternate);
        }

        /* cfg - bb after if statement joins consequent and alternate */
        control_flow!(self, |cfg| {
            let after_if_graph_ix = cfg.new_basic_block_normal();

            cfg.add_edge(before_if_stmt_graph_ix, start_of_condition_graph_ix, EdgeType::Normal);

            cfg.add_edge(after_test_graph_ix, before_consequent_stmt_graph_ix, EdgeType::Jump);

            cfg.add_edge(after_consequent_stmt_graph_ix, after_if_graph_ix, EdgeType::Normal);

            if let Some((start_of_alternate_stmt_graph_ix, after_alternate_stmt_graph_ix)) =
                else_graph_ix
            {
                cfg.add_edge(after_test_graph_ix, start_of_alternate_stmt_graph_ix, EdgeType::Jump);
                cfg.add_edge(after_alternate_stmt_graph_ix, after_if_graph_ix, EdgeType::Normal);
            } else {
                cfg.add_edge(after_test_graph_ix, after_if_graph_ix, EdgeType::Jump);
            }
        });
        /* cfg */

        self.leave_node(kind);
    }

    fn visit_labeled_statement(&mut self, stmt: &LabeledStatement<'a>) {
        let kind = AstKind::LabeledStatement(self.alloc(stmt));
        self.enter_node(kind);
        control_flow!(self, |cfg| cfg.enter_statement(self.current_node_id));
        self.unused_labels.add(stmt.label.name, self.current_node_id);

        /* cfg */
        #[cfg(feature = "cfg")]
        let label = &stmt.label.name;
        control_flow!(self, |cfg| {
            let ctx = cfg.ctx(Some(label.as_str())).default().allow_break();
            if stmt.body.is_iteration_statement() {
                ctx.allow_continue();
            }
        });
        /* cfg */

        self.visit_label_identifier(&stmt.label);

        self.visit_statement(&stmt.body);

        /* cfg */
        control_flow!(self, |cfg| {
            let after_body_graph_ix = cfg.current_node_ix;
            let after_labeled_stmt_graph_ix = cfg.new_basic_block_normal();
            cfg.add_edge(after_body_graph_ix, after_labeled_stmt_graph_ix, EdgeType::Normal);

            cfg.ctx(Some(label.as_str())).mark_break(after_labeled_stmt_graph_ix).resolve();
        });
        /* cfg */

        self.unused_labels.mark_unused();
        self.leave_node(kind);
    }

    fn visit_return_statement(&mut self, stmt: &ReturnStatement<'a>) {
        let kind = AstKind::ReturnStatement(self.alloc(stmt));
        self.enter_node(kind);

        /* cfg */
        #[cfg(feature = "cfg")]
        let node_id = self.current_node_id;
        /* cfg */

        #[cfg(feature = "cfg")]
        let ret_kind = if let Some(arg) = &stmt.argument {
            self.visit_expression(arg);
            ReturnInstructionKind::NotImplicitUndefined
        } else {
            ReturnInstructionKind::ImplicitUndefined
        };

        #[cfg(not(feature = "cfg"))]
        if let Some(arg) = &stmt.argument {
            self.visit_expression(arg);
        }

        /* cfg */
        control_flow!(self, |cfg| {
            cfg.push_return(ret_kind, Some(node_id));
            cfg.append_unreachable();
        });
        /* cfg */

        self.leave_node(kind);
    }

    fn visit_switch_statement(&mut self, stmt: &SwitchStatement<'a>) {
        let kind = AstKind::SwitchStatement(self.alloc(stmt));
        self.enter_node(kind);
        control_flow!(self, |cfg| cfg.enter_statement(self.current_node_id));
        self.visit_expression(&stmt.discriminant);
        self.enter_scope(ScopeFlags::empty(), &stmt.scope_id);

        /* cfg */
        #[cfg(feature = "cfg")]
        let discriminant_graph_ix = control_flow!(self, |cfg| {
            let discriminant_graph_ix = cfg.current_node_ix;
            cfg.ctx(None).default().allow_break();
            discriminant_graph_ix
        });
        #[cfg(feature = "cfg")]
        let mut switch_case_graph_spans = vec![];
        #[cfg(feature = "cfg")]
        let mut have_default_case = false;
        /* cfg */

        for case in &stmt.cases {
            #[cfg(feature = "cfg")]
            let before_case_graph_ix = control_flow!(self, |cfg| cfg.new_basic_block_normal());
            self.visit_switch_case(case);
            #[cfg(feature = "cfg")]
            if case.is_default_case() {
                have_default_case = true;
            }
            control_flow!(self, |cfg| switch_case_graph_spans
                .push((before_case_graph_ix, cfg.current_node_ix)));
        }

        /* cfg */
        // for each switch case
        control_flow!(self, |cfg| {
            for i in 0..switch_case_graph_spans.len() {
                let case_graph_span = switch_case_graph_spans[i];

                // every switch case condition can be skipped,
                // so there's a possible jump from it to the next switch case condition
                for y in switch_case_graph_spans.iter().skip(i + 1) {
                    cfg.add_edge(case_graph_span.0, y.0, EdgeType::Normal);
                }

                // connect the end of each switch statement to
                // the condition of the next switch statement
                if switch_case_graph_spans.len() > i + 1 {
                    let (_, end_of_switch_case) = switch_case_graph_spans[i];
                    let (next_switch_statement_condition, _) = switch_case_graph_spans[i + 1];

                    cfg.add_edge(
                        end_of_switch_case,
                        next_switch_statement_condition,
                        EdgeType::Normal,
                    );
                }

                cfg.add_edge(discriminant_graph_ix, case_graph_span.0, EdgeType::Normal);
            }

            let end_of_switch_case_statement = cfg.new_basic_block_normal();

            if let Some(last) = switch_case_graph_spans.last() {
                cfg.add_edge(last.1, end_of_switch_case_statement, EdgeType::Normal);
            }

            // if we don't have a default case there should be an edge from discriminant to the end of
            // the statement.
            if !have_default_case {
                cfg.add_edge(discriminant_graph_ix, end_of_switch_case_statement, EdgeType::Normal);
            }

            cfg.ctx(None).mark_break(end_of_switch_case_statement).resolve();
        });
        /* cfg */

        self.leave_scope();
        self.leave_node(kind);
    }

    fn visit_switch_case(&mut self, case: &SwitchCase<'a>) {
        let kind = AstKind::SwitchCase(self.alloc(case));
        self.enter_node(kind);

        if let Some(expr) = &case.test {
            #[cfg(feature = "cfg")]
            let condition_block_ix = control_flow!(self, |cfg| cfg.current_node_ix);
            #[cfg(feature = "cfg")]
            self.record_ast_nodes();
            self.visit_expression(expr);
            #[cfg(feature = "cfg")]
            let test_node_id = self.retrieve_recorded_ast_node();
            control_flow!(self, |cfg| cfg.append_condition_to(condition_block_ix, test_node_id));
        }

        /* cfg */
        control_flow!(self, |cfg| {
            let after_test_graph_ix = cfg.current_node_ix;
            let statements_in_switch_graph_ix = cfg.new_basic_block_normal();
            cfg.add_edge(after_test_graph_ix, statements_in_switch_graph_ix, EdgeType::Jump);
        });
        /* cfg */

        self.visit_statements(&case.consequent);

        self.leave_node(kind);
    }

    fn visit_throw_statement(&mut self, stmt: &ThrowStatement<'a>) {
        let kind = AstKind::ThrowStatement(self.alloc(stmt));
        self.enter_node(kind);

        /* cfg */
        #[cfg(feature = "cfg")]
        let node_id = self.current_node_id;
        /* cfg */

        self.visit_expression(&stmt.argument);

        /* cfg */
        control_flow!(self, |cfg| cfg.append_throw(node_id));
        /* cfg */

        self.leave_node(kind);
    }

    fn visit_try_statement(&mut self, stmt: &TryStatement<'a>) {
        let kind = AstKind::TryStatement(self.alloc(stmt));
        self.enter_node(kind);
        control_flow!(self, |cfg| cfg.enter_statement(self.current_node_id));

        /* cfg */

        #[cfg(feature = "cfg")]
        let (
            before_try_statement_graph_ix,
            error_harness,
            before_finalizer_graph_ix,
            before_try_block_graph_ix,
        ) = control_flow!(self, |cfg| {
            let before_try_statement_graph_ix = cfg.current_node_ix;
            let error_harness =
                stmt.handler.as_ref().map(|_| cfg.attach_error_harness(ErrorEdgeKind::Explicit));
            let before_finalizer_graph_ix = stmt.finalizer.as_ref().map(|_| cfg.attach_finalizer());
            let before_try_block_graph_ix = cfg.new_basic_block_normal();

            (
                before_try_statement_graph_ix,
                error_harness,
                before_finalizer_graph_ix,
                before_try_block_graph_ix,
            )
        });
        /* cfg */

        self.visit_block_statement(&stmt.block);

        /* cfg */
        #[cfg(feature = "cfg")]
        let after_try_block_graph_ix = control_flow!(self, |cfg| cfg.current_node_ix);
        /* cfg */

        #[cfg(feature = "cfg")]
        let catch_block_end_ix = if let Some(handler) = &stmt.handler {
            /* cfg */
            control_flow!(self, |cfg| {
                let Some(error_harness) = error_harness else {
                    unreachable!("we always create an error harness if we have a catch block.");
                };
                cfg.release_error_harness(error_harness);
                let catch_block_start_ix = cfg.new_basic_block_normal();
                cfg.add_edge(error_harness, catch_block_start_ix, EdgeType::Normal);
            });
            /* cfg */

            self.visit_catch_clause(handler);

            /* cfg */
            control_flow!(self, |cfg| Some(cfg.current_node_ix))
            /* cfg */
        } else {
            None
        };

        #[cfg(not(feature = "cfg"))]
        if let Some(handler) = &stmt.handler {
            self.visit_catch_clause(handler);
        }

        #[cfg(feature = "cfg")]
        let finally_block_end_ix = if let Some(finalizer) = &stmt.finalizer {
            /* cfg */
            control_flow!(self, |cfg| {
                let Some(before_finalizer_graph_ix) = before_finalizer_graph_ix else {
                    unreachable!("we always create a finalizer when there is a finally block.");
                };
                cfg.release_finalizer(before_finalizer_graph_ix);
                let start_finally_graph_ix = cfg.new_basic_block_normal();
                cfg.add_edge(before_finalizer_graph_ix, start_finally_graph_ix, EdgeType::Normal);
            });
            /* cfg */

            self.visit_block_statement(finalizer);

            /* cfg */
            control_flow!(self, |cfg| Some(cfg.current_node_ix))
            /* cfg */
        } else {
            None
        };

        #[cfg(not(feature = "cfg"))]
        if let Some(finalizer) = &stmt.finalizer {
            self.visit_block_statement(finalizer);
        }

        /* cfg */
        control_flow!(self, |cfg| {
            cfg.add_edge(
                before_try_statement_graph_ix,
                before_try_block_graph_ix,
                EdgeType::Normal,
            );
            if let Some(catch_block_end_ix) = catch_block_end_ix
                && finally_block_end_ix.is_none()
            {
                let after_try_statement_block_ix = cfg.new_basic_block_normal();
                cfg.add_edge(
                    after_try_block_graph_ix,
                    after_try_statement_block_ix,
                    EdgeType::Normal,
                );

                cfg.add_edge(catch_block_end_ix, after_try_statement_block_ix, EdgeType::Normal);
            }
            if let Some(finally_block_end_ix) = finally_block_end_ix {
                let after_try_statement_block_ix = cfg.new_basic_block_normal();
                if catch_block_end_ix.is_some() {
                    cfg.add_edge(
                        finally_block_end_ix,
                        after_try_statement_block_ix,
                        EdgeType::Normal,
                    );
                } else {
                    cfg.add_edge(
                        finally_block_end_ix,
                        after_try_statement_block_ix,
                        if cfg.basic_block(after_try_block_graph_ix).is_unreachable() {
                            EdgeType::Unreachable
                        } else {
                            EdgeType::Join
                        },
                    );
                }
            }
        });
        /* cfg */

        self.leave_node(kind);
    }

    fn visit_while_statement(&mut self, stmt: &WhileStatement<'a>) {
        let kind = AstKind::WhileStatement(self.alloc(stmt));
        self.enter_node(kind);
        control_flow!(self, |cfg| cfg.enter_statement(self.current_node_id));

        /* cfg - condition basic block */
        #[cfg(feature = "cfg")]
        let (before_while_stmt_graph_ix, condition_graph_ix) =
            control_flow!(self, |cfg| (cfg.current_node_ix, cfg.new_basic_block_normal()));
        /* cfg */

        #[cfg(feature = "cfg")]
        self.record_ast_nodes();
        self.visit_expression(&stmt.test);
        #[cfg(feature = "cfg")]
        let test_node_id = self.retrieve_recorded_ast_node();

        /* cfg - body basic block */
        #[cfg(feature = "cfg")]
        let body_graph_ix = control_flow!(self, |cfg| {
            cfg.append_condition_to(condition_graph_ix, test_node_id);
            let body_graph_ix = cfg.new_basic_block_normal();

            cfg.ctx(None).default().allow_break().allow_continue();
            body_graph_ix
        });
        /* cfg */

        self.visit_statement(&stmt.body);

        /* cfg - after body basic block */
        control_flow!(self, |cfg| {
            let after_body_graph_ix = cfg.current_node_ix;
            let after_while_graph_ix = cfg.new_basic_block_normal();

            cfg.add_edge(before_while_stmt_graph_ix, condition_graph_ix, EdgeType::Normal);
            cfg.add_edge(condition_graph_ix, body_graph_ix, EdgeType::Jump);
            cfg.add_edge(after_body_graph_ix, condition_graph_ix, EdgeType::Backedge);
            cfg.add_edge(condition_graph_ix, after_while_graph_ix, EdgeType::Normal);

            cfg.ctx(None)
                .mark_break(after_while_graph_ix)
                .mark_continue(condition_graph_ix)
                .resolve_with_upper_label();
        });
        /* cfg */
        self.leave_node(kind);
    }

    fn visit_with_statement(&mut self, stmt: &WithStatement<'a>) {
        let kind = AstKind::WithStatement(self.alloc(stmt));
        self.enter_node(kind);
        control_flow!(self, |cfg| cfg.enter_statement(self.current_node_id));

        /* cfg - condition basic block */
        #[cfg(feature = "cfg")]
        let (before_with_stmt_graph_ix, condition_graph_ix) =
            control_flow!(self, |cfg| (cfg.current_node_ix, cfg.new_basic_block_normal()));
        /* cfg */

        self.visit_expression(&stmt.object);
        self.enter_scope(ScopeFlags::With, &stmt.scope_id);

        /* cfg - body basic block */
        #[cfg(feature = "cfg")]
        let body_graph_ix = control_flow!(self, |cfg| cfg.new_basic_block_normal());
        /* cfg */

        self.visit_statement(&stmt.body);

        /* cfg - after body basic block */
        control_flow!(self, |cfg| {
            let after_body_graph_ix = cfg.new_basic_block_normal();

            cfg.add_edge(before_with_stmt_graph_ix, condition_graph_ix, EdgeType::Normal);
            cfg.add_edge(condition_graph_ix, body_graph_ix, EdgeType::Normal);
            cfg.add_edge(body_graph_ix, after_body_graph_ix, EdgeType::Normal);
            cfg.add_edge(condition_graph_ix, after_body_graph_ix, EdgeType::Normal);
        });
        /* cfg */

        self.leave_scope();
        self.leave_node(kind);
    }

    fn visit_function(&mut self, func: &Function<'a>, flags: ScopeFlags) {
        /* cfg */
        // We add a new basic block to the cfg before entering the node
        // so that the correct cfg_ix is associated with the ast node.
        #[cfg(feature = "cfg")]
        let (before_function_graph_ix, error_harness, function_graph_ix) =
            control_flow!(self, |cfg| {
                let before_function_graph_ix = cfg.current_node_ix;
                cfg.push_finalization_stack();
                let error_harness = cfg.attach_error_harness(ErrorEdgeKind::Implicit);
                let function_graph_ix = cfg.new_basic_block_function();
                cfg.ctx(None).new_function();
                (before_function_graph_ix, error_harness, function_graph_ix)
            });
        /* cfg */

        let kind = AstKind::Function(self.alloc(func));
        self.enter_node(kind);

        let parent_function_node_id = self.current_function_node_id;
        self.current_function_node_id = self.current_node_id;

        if func.is_declaration() {
            func.bind(self);
        }

        self.enter_scope(
            {
                let mut flags = flags;
                if func.has_use_strict_directive() {
                    flags |= ScopeFlags::StrictMode;
                }
                flags
            },
            &func.scope_id,
        );

        if func.is_expression() {
            // We need to bind function expression in the function scope
            func.bind(self);
        }

        if let Some(id) = &func.id {
            self.visit_binding_identifier(id);
        }

        /* cfg */
        control_flow!(self, |cfg| cfg.add_edge(
            before_function_graph_ix,
            function_graph_ix,
            EdgeType::NewFunction
        ));
        /* cfg */

        // Save checkpoint before visiting type params/params/return type
        let saved_checkpoint = self.unresolved_references_checkpoint;
        self.unresolved_references_checkpoint = self.unresolved_references.checkpoint();

        if let Some(type_parameters) = &func.type_parameters {
            self.visit_ts_type_parameter_declaration(type_parameters);
        }
        if let Some(this_param) = &func.this_param {
            self.visit_ts_this_parameter(this_param);
        }
        self.visit_formal_parameters(&func.params);
        if let Some(return_type) = &func.return_type {
            self.visit_ts_type_annotation(return_type);
        }

        if func.params.has_parameter() || func.return_type.is_some() {
            // `function foo({bar: identifier_reference}) {}`
            //                     ^^^^^^^^^^^^^^^^^^^^
            // `function foo<SomeType>(v: SomeType): SomeType { return v; }`
            //                            ^^^^^^^^   ^^^^^^^^
            // Parameter initializers must be resolved after all parameters have been declared.
            // Param types and return type must be resolved after type parameters have been declared.
            // In both cases, need to avoid binding to variables/types declared inside the function body.
            self.resolve_references_for_current_scope();
        }
        self.unresolved_references_checkpoint = saved_checkpoint;

        if let Some(body) = &func.body {
            self.visit_function_body(body);
        }

        /* cfg */
        control_flow!(self, |cfg| {
            let c = cfg.current_basic_block();
            // If the last is an unreachable instruction, it means there is already a explicit
            // return or throw statement at the end of function body, we don't need to
            // insert an implicit return.
            if !matches!(
                c.instructions().last().map(|inst| &inst.kind),
                Some(InstructionKind::Unreachable)
            ) {
                cfg.push_implicit_return();
            }
            cfg.ctx(None).resolve_expect(CtxFlags::FUNCTION);
            cfg.release_error_harness(error_harness);
            cfg.pop_finalization_stack();
            let after_function_graph_ix = cfg.new_basic_block_normal();
            cfg.add_edge(before_function_graph_ix, after_function_graph_ix, EdgeType::Normal);
        });
        /* cfg */

        self.leave_scope();
        self.leave_node(kind);

        self.current_function_node_id = parent_function_node_id;
    }

    fn visit_arrow_function_expression(&mut self, expr: &ArrowFunctionExpression<'a>) {
        /* cfg */
        // We add a new basic block to the cfg before entering the node
        // so that the correct cfg_ix is associated with the ast node.
        #[cfg(feature = "cfg")]
        let (current_node_ix, error_harness, function_graph_ix) = control_flow!(self, |cfg| {
            let current_node_ix = cfg.current_node_ix;
            cfg.push_finalization_stack();
            let error_harness = cfg.attach_error_harness(ErrorEdgeKind::Implicit);
            let function_graph_ix = cfg.new_basic_block_function();
            cfg.ctx(None).new_function();
            (current_node_ix, error_harness, function_graph_ix)
        });
        /* cfg */

        let kind = AstKind::ArrowFunctionExpression(self.alloc(expr));
        self.enter_node(kind);
        self.enter_scope(
            {
                let mut flags = ScopeFlags::Function | ScopeFlags::Arrow;
                if expr.has_use_strict_directive() {
                    flags |= ScopeFlags::StrictMode;
                }
                flags
            },
            &expr.scope_id,
        );

        // Save checkpoint before visiting type params/params/return type
        let saved_checkpoint = self.unresolved_references_checkpoint;
        self.unresolved_references_checkpoint = self.unresolved_references.checkpoint();

        if let Some(parameters) = &expr.type_parameters {
            self.visit_ts_type_parameter_declaration(parameters);
        }

        self.visit_formal_parameters(&expr.params);

        /* cfg */
        control_flow!(self, |cfg| cfg.add_edge(
            current_node_ix,
            function_graph_ix,
            EdgeType::NewFunction
        ));
        /* cfg */

        if let Some(return_type) = &expr.return_type {
            self.visit_ts_type_annotation(return_type);
        }

        if expr.params.has_parameter() || expr.return_type.is_some() {
            // `let foo = ({bar: identifier_reference}) => {};`
            //                   ^^^^^^^^^^^^^^^^^^^^
            // `let foo = <SomeType>(v: SomeType): SomeType => v;`
            //                          ^^^^^^^^   ^^^^^^^^
            // Parameter initializers must be resolved after all parameters have been declared.
            // Param types and return type must be resolved after type parameters have been declared.
            // In both cases, need to avoid binding to variables/types declared inside the function body.
            self.resolve_references_for_current_scope();
        }
        self.unresolved_references_checkpoint = saved_checkpoint;

        self.visit_function_body(&expr.body);

        /* cfg */
        control_flow!(self, |cfg| {
            let c = cfg.current_basic_block();
            // If the last is an unreachable instruction, it means there is already a explicit
            // return or throw statement at the end of function body, we don't need to
            // insert an implicit return.
            if !matches!(
                c.instructions().last().map(|inst| &inst.kind),
                Some(InstructionKind::Unreachable)
            ) {
                cfg.push_implicit_return();
            }
            cfg.ctx(None).resolve_expect(CtxFlags::FUNCTION);
            cfg.release_error_harness(error_harness);
            cfg.pop_finalization_stack();
            cfg.current_node_ix = current_node_ix;
        });
        /* cfg */

        self.leave_scope();
        self.leave_node(kind);
    }

    fn visit_update_expression(&mut self, it: &UpdateExpression<'a>) {
        let kind = AstKind::UpdateExpression(self.alloc(it));
        self.enter_node(kind);
        // `++a` or `a--`
        //    ^      ^ We always treat `a` as Read and Write reference,
        self.current_reference_flags = ReferenceFlags::read_write();
        self.visit_simple_assignment_target(&it.argument);
        self.leave_node(kind);
    }

    fn visit_unary_expression(&mut self, it: &UnaryExpression<'a>) {
        let kind = AstKind::UnaryExpression(self.alloc(it));
        self.enter_node(kind);
        // `delete a.foo` — the argument is in a property-write context.
        // Set Write so `visit_member_expression` can detect it and mark MemberWriteTarget.
        // Only for member expressions — `delete x` (bare identifier in sloppy mode)
        // is not a property modification.
        if it.operator == UnaryOperator::Delete && it.argument.is_member_expression() {
            self.current_reference_flags = ReferenceFlags::Write;
        }
        self.visit_expression(&it.argument);
        self.leave_node(kind);
    }

    fn visit_member_expression(&mut self, it: &MemberExpression<'a>) {
        // A.B = 1;
        // ^^^ Can't treat A as a Write reference since it's A's property(B) that changes.
        // When the member expression is in any write context (simple `=`, compound `+=`,
        // update `++`, `delete`, for-in/of), mark as MemberWriteTarget so downstream
        // consumers can identify property-modification-only references.
        if self.current_reference_flags.is_write() {
            self.current_reference_flags = ReferenceFlags::Read | ReferenceFlags::MemberWriteTarget;
        } else {
            self.current_reference_flags -= ReferenceFlags::Write;
        }

        match it {
            MemberExpression::ComputedMemberExpression(it) => {
                self.visit_computed_member_expression(it);
            }
            MemberExpression::StaticMemberExpression(it) => self.visit_static_member_expression(it),
            MemberExpression::PrivateFieldExpression(it) => self.visit_private_field_expression(it),
        }

        // Clear any unconsumed flags to prevent leaking to sibling AST nodes.
        // When the object is `this` or a call expression (not an IdentifierReference),
        // the flags set above aren't consumed by `resolve_reference_usages`,
        // and would incorrectly propagate to the next visited identifier (e.g., the RHS).
        self.current_reference_flags = ReferenceFlags::empty();
    }

    fn visit_simple_assignment_target(&mut self, it: &SimpleAssignmentTarget<'a>) {
        // Except that the read-write flags has been set in visit_assignment_expression
        // and visit_update_expression, this is always a write-only reference here.
        if !self.current_reference_flags.is_write() {
            self.current_reference_flags = ReferenceFlags::Write;
        }

        match it {
            SimpleAssignmentTarget::AssignmentTargetIdentifier(it) => {
                self.visit_identifier_reference(it);
            }
            SimpleAssignmentTarget::TSAsExpression(it) => {
                self.visit_ts_as_expression(it);
            }
            SimpleAssignmentTarget::TSSatisfiesExpression(it) => {
                self.visit_ts_satisfies_expression(it);
            }
            SimpleAssignmentTarget::TSNonNullExpression(it) => {
                self.visit_ts_non_null_expression(it);
            }
            SimpleAssignmentTarget::TSTypeAssertion(it) => {
                self.visit_ts_type_assertion(it);
            }
            match_member_expression!(SimpleAssignmentTarget) => {
                self.visit_member_expression(it.to_member_expression());
            }
        }
    }

    fn visit_assignment_target_property_identifier(
        &mut self,
        it: &AssignmentTargetPropertyIdentifier<'a>,
    ) {
        let kind = AstKind::AssignmentTargetPropertyIdentifier(self.alloc(it));
        self.enter_node(kind);
        self.current_reference_flags = ReferenceFlags::Write;
        self.visit_identifier_reference(&it.binding);
        if let Some(init) = &it.init {
            self.visit_expression(init);
        }
        self.leave_node(kind);
    }

    fn visit_export_default_declaration_kind(&mut self, it: &ExportDefaultDeclarationKind<'a>) {
        match it {
            ExportDefaultDeclarationKind::FunctionDeclaration(it) => {
                let flags = ScopeFlags::Function;
                self.visit_function(it, flags);
            }
            ExportDefaultDeclarationKind::ClassDeclaration(it) => self.visit_class(it),
            ExportDefaultDeclarationKind::TSInterfaceDeclaration(it) => {
                self.visit_ts_interface_declaration(it);
            }
            ExportDefaultDeclarationKind::Identifier(it) => {
                // `export default ident`
                //                 ^^^^^ -> can reference both type/value symbols
                self.current_reference_flags = ReferenceFlags::Read | ReferenceFlags::Type;
                self.visit_identifier_reference(it);
            }
            match_expression!(ExportDefaultDeclarationKind) => {
                self.visit_expression(it.to_expression());
            }
        }
    }

    fn visit_export_named_declaration(&mut self, it: &ExportNamedDeclaration<'a>) {
        let kind = AstKind::ExportNamedDeclaration(self.alloc(it));
        self.enter_node(kind);
        self.visit_span(&it.span);
        if let Some(declaration) = &it.declaration {
            self.visit_declaration(declaration);
        }

        if let Some(source) = &it.source {
            self.visit_string_literal(source);
            self.visit_export_specifiers(&it.specifiers);
        } else {
            for specifier in &it.specifiers {
                // `export type { a }` or `export { type a }` -> `a` is a type reference
                if it.export_kind.is_type() || specifier.export_kind.is_type() {
                    self.current_reference_flags = ReferenceFlags::Type;
                } else {
                    // If the export specifier is not a explicit type export, we consider it as a potential
                    // type and value reference. If it references to a value in the end, we would delete the
                    // `ReferenceFlags::Type` flag in `fn try_resolve_reference`.
                    self.current_reference_flags = ReferenceFlags::Read | ReferenceFlags::Type;
                }
                self.visit_export_specifier(specifier);
            }
        }
        if let Some(with_clause) = &it.with_clause {
            self.visit_with_clause(with_clause);
        }

        self.leave_node(kind);
    }

    fn visit_export_specifier(&mut self, it: &ExportSpecifier<'a>) {
        let kind = AstKind::ExportSpecifier(self.alloc(it));
        self.enter_node(kind);
        self.visit_span(&it.span);

        self.current_node_flags |= NodeFlags::ExportSpecifier;

        self.visit_module_export_name(&it.local);
        self.visit_module_export_name(&it.exported);

        self.current_node_flags -= NodeFlags::ExportSpecifier;

        self.leave_node(kind);
    }

    fn visit_ts_export_assignment(&mut self, it: &TSExportAssignment<'a>) {
        let kind = AstKind::TSExportAssignment(self.alloc(it));
        self.enter_node(kind);
        self.visit_span(&it.span);
        // export = a;
        //          ^ can reference type/value symbols
        if it.expression.is_identifier_reference() {
            self.current_reference_flags = ReferenceFlags::Read | ReferenceFlags::Type;
        }
        self.visit_expression(&it.expression);
        self.leave_node(kind);
    }

    fn visit_catch_parameter(&mut self, param: &CatchParameter<'a>) {
        let kind = AstKind::CatchParameter(self.alloc(param));
        self.enter_node(kind);
        param.bind(self);

        let saved_checkpoint = self.unresolved_references_checkpoint;
        self.unresolved_references_checkpoint = self.unresolved_references.checkpoint();

        self.visit_span(&param.span);
        self.visit_binding_pattern(&param.pattern);
        if let Some(type_annotation) = &param.type_annotation {
            self.visit_ts_type_annotation(type_annotation);
        }
        self.resolve_references_for_current_scope();
        self.unresolved_references_checkpoint = saved_checkpoint;
        self.leave_node(kind);
    }

    fn visit_ts_type_query(&mut self, ty: &TSTypeQuery<'a>) {
        let kind = AstKind::TSTypeQuery(self.alloc(ty));
        self.enter_node(kind);
        // type A = typeof a;
        //          ^^^^^^^^
        self.current_reference_flags = ReferenceFlags::ValueAsType;
        self.visit_span(&ty.span);
        self.visit_ts_type_query_expr_name(&ty.expr_name);
        if let Some(type_arguments) = &ty.type_arguments {
            self.visit_ts_type_parameter_instantiation(type_arguments);
        }
        self.current_reference_flags = ReferenceFlags::empty();
        self.leave_node(kind);
    }

    fn visit_ts_property_signature(&mut self, sig: &TSPropertySignature<'a>) {
        let kind = AstKind::TSPropertySignature(self.alloc(sig));
        self.enter_node(kind);
        if sig.key.is_expression() {
            // interface A { [prop]: string }
            //               ^^^^^ The property can reference value or [`SymbolFlags::TypeImport`] symbol
            self.current_reference_flags = ReferenceFlags::ValueAsType;
        }
        self.visit_span(&sig.span);
        self.visit_property_key(&sig.key);
        if let Some(type_annotation) = &sig.type_annotation {
            self.visit_ts_type_annotation(type_annotation);
        }
        self.current_reference_flags = ReferenceFlags::empty();
        self.leave_node(kind);
    }

    fn visit_import_specifier(&mut self, specifier: &ImportSpecifier<'a>) {
        let kind = AstKind::ImportSpecifier(self.alloc(specifier));
        self.enter_node(kind);
        specifier.bind(self);
        self.visit_span(&specifier.span);
        self.visit_module_export_name(&specifier.imported);
        self.visit_binding_identifier(&specifier.local);
        self.leave_node(kind);
    }

    fn visit_import_default_specifier(&mut self, specifier: &ImportDefaultSpecifier<'a>) {
        let kind = AstKind::ImportDefaultSpecifier(self.alloc(specifier));
        self.enter_node(kind);
        specifier.bind(self);
        self.visit_span(&specifier.span);
        self.visit_binding_identifier(&specifier.local);
        self.leave_node(kind);
    }

    fn visit_import_namespace_specifier(&mut self, specifier: &ImportNamespaceSpecifier<'a>) {
        let kind = AstKind::ImportNamespaceSpecifier(self.alloc(specifier));
        self.enter_node(kind);
        specifier.bind(self);
        self.visit_span(&specifier.span);
        self.visit_binding_identifier(&specifier.local);
        self.leave_node(kind);
    }

    fn visit_ts_import_equals_declaration(&mut self, decl: &TSImportEqualsDeclaration<'a>) {
        let kind = AstKind::TSImportEqualsDeclaration(self.alloc(decl));
        self.enter_node(kind);
        decl.bind(self);
        self.visit_span(&decl.span);
        self.visit_binding_identifier(&decl.id);
        self.visit_ts_module_reference(&decl.module_reference);
        self.leave_node(kind);
    }

    fn visit_variable_declarator(&mut self, decl: &VariableDeclarator<'a>) {
        let kind = AstKind::VariableDeclarator(self.alloc(decl));
        self.enter_node(kind);
        decl.bind(self);
        self.visit_span(&decl.span);
        self.visit_binding_pattern(&decl.id);
        if let Some(type_annotation) = &decl.type_annotation {
            self.visit_ts_type_annotation(type_annotation);
        }
        if let Some(init) = &decl.init {
            self.visit_expression(init);
        }
        self.leave_node(kind);
    }

    fn visit_class_body(&mut self, body: &ClassBody<'a>) {
        let kind = AstKind::ClassBody(self.alloc(body));
        self.enter_node(kind);
        self.class_table_builder.declare_class_body(body, self.current_node_id, &self.nodes);
        self.visit_span(&body.span);
        self.visit_class_elements(&body.body);
        self.leave_node(kind);
    }

    fn visit_private_identifier(&mut self, ident: &PrivateIdentifier<'a>) {
        let kind = AstKind::PrivateIdentifier(self.alloc(ident));
        self.enter_node(kind);
        self.class_table_builder.add_private_identifier_reference(
            ident,
            self.current_node_id,
            &self.nodes,
        );
        self.visit_span(&ident.span);
        self.leave_node(kind);
    }

    fn visit_binding_rest_element(&mut self, element: &BindingRestElement<'a>) {
        let kind = AstKind::BindingRestElement(self.alloc(element));
        self.enter_node(kind);
        element.bind(self);
        self.visit_span(&element.span);
        self.visit_binding_pattern(&element.argument);
        self.leave_node(kind);
    }

    fn visit_formal_parameter(&mut self, param: &FormalParameter<'a>) {
        let kind = AstKind::FormalParameter(self.alloc(param));
        self.enter_node(kind);
        param.bind(self);
        self.visit_span(&param.span);
        self.visit_decorators(&param.decorators);
        self.visit_binding_pattern(&param.pattern);
        if let Some(type_annotation) = &param.type_annotation {
            self.visit_ts_type_annotation(type_annotation);
        }
        if let Some(initializer) = &param.initializer {
            self.visit_expression(initializer);
        }
        self.leave_node(kind);
    }

    fn visit_formal_parameter_rest(&mut self, param: &FormalParameterRest<'a>) {
        let kind = AstKind::FormalParameterRest(self.alloc(param));
        self.enter_node(kind);
        param.bind(self);
        self.visit_span(&param.span);
        self.visit_decorators(&param.decorators);
        self.visit_binding_rest_element(&param.rest);
        if let Some(type_annotation) = &param.type_annotation {
            self.visit_ts_type_annotation(type_annotation);
        }
        self.leave_node(kind);
    }

    fn visit_ts_module_declaration(&mut self, decl: &TSModuleDeclaration<'a>) {
        let kind = AstKind::TSModuleDeclaration(self.alloc(decl));
        self.enter_node(kind);
        decl.bind(self);
        self.visit_span(&decl.span);
        self.visit_ts_module_declaration_name(&decl.id);
        self.enter_scope(
            {
                let mut flags = ScopeFlags::TsModuleBlock;
                if decl.body.as_ref().is_some_and(TSModuleDeclarationBody::has_use_strict_directive)
                {
                    flags |= ScopeFlags::StrictMode;
                }
                flags
            },
            &decl.scope_id,
        );
        if let Some(body) = &decl.body {
            self.visit_ts_module_declaration_body(body);
        }
        self.leave_scope();
        self.leave_node(kind);
    }

    fn visit_ts_type_alias_declaration(&mut self, decl: &TSTypeAliasDeclaration<'a>) {
        let kind = AstKind::TSTypeAliasDeclaration(self.alloc(decl));
        self.enter_node(kind);
        decl.bind(self);
        self.visit_span(&decl.span);
        self.visit_binding_identifier(&decl.id);
        self.enter_scope(ScopeFlags::empty(), &decl.scope_id);
        if let Some(type_parameters) = &decl.type_parameters {
            self.visit_ts_type_parameter_declaration(type_parameters);
        }
        self.visit_ts_type(&decl.type_annotation);
        self.leave_scope();
        self.leave_node(kind);
    }

    fn visit_ts_interface_declaration(&mut self, decl: &TSInterfaceDeclaration<'a>) {
        let kind = AstKind::TSInterfaceDeclaration(self.alloc(decl));
        self.enter_node(kind);
        decl.bind(self);
        self.visit_span(&decl.span);
        self.visit_binding_identifier(&decl.id);
        self.enter_scope(ScopeFlags::empty(), &decl.scope_id);
        if let Some(type_parameters) = &decl.type_parameters {
            self.visit_ts_type_parameter_declaration(type_parameters);
        }
        self.visit_ts_interface_heritages(&decl.extends);
        self.visit_ts_interface_body(&decl.body);
        self.leave_scope();
        self.leave_node(kind);
    }

    fn visit_ts_enum_declaration(&mut self, decl: &TSEnumDeclaration<'a>) {
        let kind = AstKind::TSEnumDeclaration(self.alloc(decl));
        self.enter_node(kind);
        decl.bind(self);
        self.visit_span(&decl.span);
        self.visit_binding_identifier(&decl.id);
        self.visit_ts_enum_body(&decl.body);
        // Evaluate enum member values after all members are bound
        if self.enum_eval {
            crate::ts_enum::eval::evaluate_enum_members(decl, &mut self.scoping);
        }
        self.leave_node(kind);
    }

    fn visit_ts_enum_member(&mut self, member: &TSEnumMember<'a>) {
        let kind = AstKind::TSEnumMember(self.alloc(member));
        self.enter_node(kind);
        member.bind(self);
        self.visit_span(&member.span);
        self.visit_ts_enum_member_name(&member.id);
        if let Some(initializer) = &member.initializer {
            self.visit_expression(initializer);
        }
        self.leave_node(kind);
    }

    fn visit_ts_type_parameter(&mut self, param: &TSTypeParameter<'a>) {
        let kind = AstKind::TSTypeParameter(self.alloc(param));
        self.enter_node(kind);
        param.bind(self);
        self.visit_span(&param.span);
        self.visit_binding_identifier(&param.name);
        if let Some(constraint) = &param.constraint {
            self.visit_ts_type(constraint);
        }
        if let Some(default) = &param.default {
            self.visit_ts_type(default);
        }
        self.leave_node(kind);
    }

    fn visit_ts_mapped_type(&mut self, it: &TSMappedType<'a>) {
        let kind = AstKind::TSMappedType(self.alloc(it));
        self.enter_node(kind);
        self.enter_scope(ScopeFlags::empty(), &it.scope_id);
        it.bind(self);
        self.visit_span(&it.span);
        self.visit_binding_identifier(&it.key);
        self.visit_ts_type(&it.constraint);
        if let Some(name_type) = &it.name_type {
            self.visit_ts_type(name_type);
        }
        if let Some(type_annotation) = &it.type_annotation {
            self.visit_ts_type(type_annotation);
        }
        self.leave_scope();
        self.leave_node(kind);
    }

    fn visit_identifier_reference(&mut self, ident: &IdentifierReference<'a>) {
        let kind = AstKind::IdentifierReference(self.alloc(ident));
        self.enter_node(kind);
        self.reference_identifier(ident);
        self.visit_span(&ident.span);
        self.leave_node(kind);
    }

    fn visit_yield_expression(&mut self, expr: &YieldExpression<'a>) {
        let kind = AstKind::YieldExpression(self.alloc(expr));
        self.enter_node(kind);
        // If not in a function, `current_function_node_id` is `NodeId` of `Program`.
        // But it shouldn't be possible for `yield` to be at top level - that's a parse error.
        *self.nodes.flags_mut(self.current_function_node_id) |= NodeFlags::HasYield;
        self.visit_span(&expr.span);
        if let Some(argument) = &expr.argument {
            self.visit_expression(argument);
        }
        self.leave_node(kind);
    }

    fn visit_call_expression(&mut self, expr: &CallExpression<'a>) {
        let kind = AstKind::CallExpression(self.alloc(expr));
        self.enter_node(kind);
        if !expr.optional && expr.callee.is_specific_id("eval") {
            self.scoping.scope_flags_mut(self.current_scope_id).insert(ScopeFlags::DirectEval);
        }
        self.visit_span(&expr.span);
        self.visit_expression(&expr.callee);
        if let Some(type_arguments) = &expr.type_arguments {
            self.visit_ts_type_parameter_instantiation(type_arguments);
        }
        self.visit_arguments(&expr.arguments);
        self.leave_node(kind);
    }

    fn visit_ts_interface_heritage(&mut self, heritage: &TSInterfaceHeritage<'a>) {
        let kind = AstKind::TSInterfaceHeritage(self.alloc(heritage));
        self.enter_node(kind);
        // interface A extends B {}
        //             ^^^^^^^^^
        self.current_reference_flags = ReferenceFlags::Type;
        self.visit_span(&heritage.span);
        self.visit_expression(&heritage.expression);
        if let Some(type_arguments) = &heritage.type_arguments {
            self.visit_ts_type_parameter_instantiation(type_arguments);
        }
        self.leave_node(kind);
    }

    fn visit_ts_class_implements(&mut self, implements: &TSClassImplements<'a>) {
        let kind = AstKind::TSClassImplements(self.alloc(implements));
        self.enter_node(kind);
        // class A implements B {}
        //         ^^^^^^^^^^^^
        self.current_reference_flags = ReferenceFlags::Type;
        self.visit_span(&implements.span);
        self.visit_ts_type_name(&implements.expression);
        if let Some(type_arguments) = &implements.type_arguments {
            self.visit_ts_type_parameter_instantiation(type_arguments);
        }
        self.leave_node(kind);
    }

    fn visit_ts_type_reference(&mut self, ty: &TSTypeReference<'a>) {
        let kind = AstKind::TSTypeReference(self.alloc(ty));
        self.enter_node(kind);
        self.current_reference_flags = ReferenceFlags::Type;
        self.visit_span(&ty.span);
        self.visit_ts_type_name(&ty.type_name);
        if let Some(type_arguments) = &ty.type_arguments {
            self.visit_ts_type_parameter_instantiation(type_arguments);
        }
        self.leave_node(kind);
    }

    fn visit_ts_qualified_name(&mut self, name: &TSQualifiedName<'a>) {
        let kind = AstKind::TSQualifiedName(self.alloc(name));
        self.enter_node(kind);
        self.visit_span(&name.span);
        // The left side of a qualified name (e.g., `Database` in `Database.Table`)
        // must resolve to a namespace/module, not a type parameter.
        // Add Namespace flag to skip type parameters during resolution.
        // If no flags set yet (value context like `import foo = A.B.C`),
        // also add Read as the default.
        if self.current_reference_flags.is_empty() {
            self.current_reference_flags = ReferenceFlags::Read | ReferenceFlags::Namespace;
        } else {
            self.current_reference_flags |= ReferenceFlags::Namespace;
        }
        self.visit_ts_type_name(&name.left);
        self.visit_identifier_name(&name.right);
        self.leave_node(kind);
    }

    fn visit_expression_statement(&mut self, it: &ExpressionStatement<'a>) {
        let kind = AstKind::ExpressionStatement(self.alloc(it));
        self.enter_node(kind);
        control_flow!(self, |cfg| cfg.enter_statement(self.current_node_id));
        self.visit_span(&it.span);
        self.visit_expression(&it.expression);
        self.leave_node(kind);
    }

    fn visit_variable_declaration(&mut self, it: &VariableDeclaration<'a>) {
        let kind = AstKind::VariableDeclaration(self.alloc(it));
        self.enter_node(kind);
        control_flow!(self, |cfg| cfg.enter_statement(self.current_node_id));
        self.visit_span(&it.span);
        self.visit_variable_declarators(&it.declarations);
        self.leave_node(kind);
    }

    fn visit_empty_statement(&mut self, it: &EmptyStatement) {
        let kind = AstKind::EmptyStatement(self.alloc(it));
        self.enter_node(kind);
        control_flow!(self, |cfg| cfg.enter_statement(self.current_node_id));
        self.visit_span(&it.span);
        self.leave_node(kind);
    }

    fn visit_debugger_statement(&mut self, it: &DebuggerStatement) {
        let kind = AstKind::DebuggerStatement(self.alloc(it));
        self.enter_node(kind);
        control_flow!(self, |cfg| cfg.enter_statement(self.current_node_id));
        self.visit_span(&it.span);
        self.leave_node(kind);
    }

    fn visit_export_default_declaration(&mut self, it: &ExportDefaultDeclaration<'a>) {
        let kind = AstKind::ExportDefaultDeclaration(self.alloc(it));
        self.enter_node(kind);
        control_flow!(self, |cfg| cfg.enter_statement(self.current_node_id));
        self.visit_span(&it.span);
        self.visit_export_default_declaration_kind(&it.declaration);
        self.leave_node(kind);
    }
}

impl<'a> SemanticBuilder<'a> {
    #[inline]
    fn reference_identifier(&mut self, ident: &IdentifierReference<'a>) {
        let flags = self.resolve_reference_usages();
        let reference = Reference::new(self.current_node_id, self.current_scope_id, flags);
        let reference_id = self.declare_reference(ident.name, reference);
        ident.reference_id.set(Some(reference_id));
    }

    /// Resolve reference flags for the current ast node.
    #[inline]
    fn resolve_reference_usages(&mut self) -> ReferenceFlags {
        if self.current_reference_flags.is_empty() {
            ReferenceFlags::Read
        } else {
            // Take the current reference flags so that we can reset it to empty
            mem::take(&mut self.current_reference_flags)
        }
    }
}