rolldown 1.2.3

Fast JavaScript bundler in Rust, designed for the future of Vite
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
use std::ops::{BitOr, BitOrAssign};

use bitflags::bitflags;
use oxc::ast::ast::{
  self, Argument, AssignmentTarget, BindingPattern, CallExpression, ChainElement, Expression,
  IdentifierReference, SpreadElement, UnaryOperator, VariableDeclarationKind,
};
use oxc::ast::match_member_expression;
use oxc::ast_visit::{VisitJs, walk_js};
use oxc::semantic::{NodeId, ScopeFlags, SymbolId};
use oxc::transformer::EngineTargets;
use oxc_ecmascript::GlobalContext;
use oxc_ecmascript::side_effects::{
  MayHaveSideEffects, MayHaveSideEffectsContext, PropertyReadSideEffects,
};
use rolldown_common::{AstScopes, FlatOptions, SharedNormalizedBundlerOptions, StmtEvalFlags};
use rolldown_ecmascript_utils::ExpressionExt;
use rustc_hash::FxHashSet;

use crate::utils;

bitflags! {
    #[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
    /// Reasons that make an otherwise side-effect-free statement sensitive to execution order.
    struct StmtOrderSensitiveReasons: u8 {
        /// Reads from an unresolved global or a member chain rooted at one.
        const GlobalVarAccess = 1;
        /// A call/new/tagged-template expression was treated as pure by an annotation or
        /// cross-module analysis. Only the strict top-level statement walk additionally sets it
        /// for `manualPureFunctions` forms; the regular analyzer and the class-mode collector
        /// deliberately do not.
        const PureAnnotation = 1 << 1;
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
/// Evaluation facts for a statement.
///
/// `tree_shaking_flags` answers whether the statement must be retained. `is_order_sensitive`
/// combines unknown tree-shaking side effects with order-sensitive reasons to answer whether the
/// statement's relative execution timing matters.
pub struct StmtEvalFacts {
  tree_shaking_flags: StmtEvalFlags,
  order_sensitive_reasons: StmtOrderSensitiveReasons,
}

impl StmtEvalFacts {
  #[inline]
  fn from_tree_shaking_flags(tree_shaking_flags: StmtEvalFlags) -> Self {
    Self { tree_shaking_flags, order_sensitive_reasons: StmtOrderSensitiveReasons::empty() }
  }

  #[inline]
  fn from_tree_shaking_side_effect(has_side_effect: bool) -> Self {
    Self::from_tree_shaking_flags(has_side_effect.into())
  }

  #[inline]
  fn from_unknown_side_effect() -> Self {
    Self::from_tree_shaking_flags(StmtEvalFlags::UnknownSideEffect)
  }

  #[inline]
  pub fn tree_shaking_flags(&self) -> StmtEvalFlags {
    self.tree_shaking_flags
  }

  #[inline]
  fn set_order_sensitive_reason(&mut self, reason: StmtOrderSensitiveReasons, value: bool) {
    self.order_sensitive_reasons.set(reason, value);
  }

  #[inline]
  fn has_order_sensitive_reason(&self, reason: StmtOrderSensitiveReasons) -> bool {
    self.order_sensitive_reasons.contains(reason)
  }

  #[inline]
  fn without_unknown_side_effect(mut self) -> Self {
    self.tree_shaking_flags.remove(StmtEvalFlags::UnknownSideEffect);
    self
  }

  #[inline]
  fn has_side_effect_for_tree_shaking(&self) -> bool {
    self.tree_shaking_flags.has_side_effect_for_tree_shaking()
  }

  #[inline]
  pub fn is_order_sensitive(&self) -> bool {
    // `UnknownSideEffect` is stored in the tree-shaking channel, but unknown runtime work is
    // inherently order-sensitive. `PureCjs` remains tree-shaking-only.
    self.tree_shaking_flags.contains(StmtEvalFlags::UnknownSideEffect)
      || !self.order_sensitive_reasons.is_empty()
  }
}

impl BitOr for StmtEvalFacts {
  type Output = Self;

  fn bitor(self, rhs: Self) -> Self::Output {
    Self {
      tree_shaking_flags: self.tree_shaking_flags | rhs.tree_shaking_flags,
      order_sensitive_reasons: self.order_sensitive_reasons | rhs.order_sensitive_reasons,
    }
  }
}

impl BitOrAssign for StmtEvalFacts {
  fn bitor_assign(&mut self, rhs: Self) {
    self.tree_shaking_flags |= rhs.tree_shaking_flags;
    self.order_sensitive_reasons |= rhs.order_sensitive_reasons;
  }
}

/// Collect facts about evaluating a statement.
///
/// The returned facts keep tree-shaking side effects separate from order-sensitive reasons.
pub struct StmtEvalAnalyzer<'a> {
  scope: &'a AstScopes,
  options: &'a SharedNormalizedBundlerOptions,
  flat_options: FlatOptions,
  /// Cross-module optimization: node IDs of call expressions to known-pure functions.
  side_effect_free_call_expr_node_ids: Option<&'a FxHashSet<NodeId>>,
  /// Symbol IDs of namespace imports (`import * as ns from '...'`).
  /// Property reads on ES module namespace objects are guaranteed side-effect-free
  /// because namespace objects are frozen/sealed by spec with no getters.
  namespace_object_symbol_ids: Option<&'a FxHashSet<SymbolId>>,
}

impl<'a> StmtEvalAnalyzer<'a> {
  pub fn new(
    scope: &'a AstScopes,
    flat_options: FlatOptions,
    options: &'a SharedNormalizedBundlerOptions,
    side_effect_free_call_expr_node_ids: Option<&'a FxHashSet<NodeId>>,
    namespace_object_symbol_ids: Option<&'a FxHashSet<SymbolId>>,
  ) -> Self {
    Self {
      scope,
      options,
      flat_options,
      side_effect_free_call_expr_node_ids,
      namespace_object_symbol_ids,
    }
  }

  /// Check if a call expression has been marked pure by cross-module optimization.
  fn is_call_expr_marked_pure(&self, expr: &CallExpression) -> bool {
    self.side_effect_free_call_expr_node_ids.is_some_and(|set| set.contains(&expr.node_id()))
  }

  #[inline]
  fn is_unresolved_reference(&self, ident_ref: &IdentifierReference) -> bool {
    ident_ref.reference_id.get().is_some_and(|ref_id| self.scope.is_unresolved(ref_id))
  }

  /// Walk a member expression chain to find whether the root is an unresolved global.
  fn is_member_expr_root_global(&self, expr: &ast::MemberExpression) -> bool {
    let mut cur = expr.object();
    loop {
      match cur {
        Expression::StaticMemberExpression(e) => cur = &e.object,
        Expression::ComputedMemberExpression(e) => cur = &e.object,
        Expression::Identifier(ident) => return self.is_unresolved_reference(ident),
        _ => return false,
      }
    }
  }

  /// Check if the member expression's direct object is an ES module namespace import.
  /// ES module namespace objects are frozen/sealed by spec — property reads on them
  /// can never have side effects (no getters possible).
  fn is_namespace_member_access(&self, member_expr: &ast::MemberExpression) -> Option<bool> {
    let namespace_ids = self.namespace_object_symbol_ids?;
    let ident = member_expr.object().as_identifier()?;
    let ref_id = ident.reference_id.get()?;
    let symbol_id = self.scope.symbol_id_for(ref_id)?;
    Some(namespace_ids.contains(&symbol_id))
  }

  /// `import.meta.url` is a spec-defined side-effect-free property read, and
  /// `import.meta.ROLLDOWN_FILE_URL_<referenceId>` is a placeholder the finalizer rewrites into a
  /// `new URL(...)` expression. Other accesses like `import.meta.hot.accept()` may have side effects.
  fn is_side_effect_free_import_meta_access(member_expr: &ast::MemberExpression) -> bool {
    let Expression::ImportMeta(_) = member_expr.object() else {
      return false;
    };
    member_expr
      .static_property_name()
      .is_some_and(|name| name == "url" || utils::file_url::starts_with_file_url_prefix(name))
  }

  fn analyze_member_expr(&self, member_expr: &ast::MemberExpression) -> StmtEvalFacts {
    if self.is_expr_manual_pure_functions(member_expr.object()) {
      let mut facts = self.analyze_eager_chain_children(member_expr.object());
      if let ast::MemberExpression::ComputedMemberExpression(expr) = member_expr {
        facts |= self.analyze_expr(&expr.expression);
      }
      return facts;
    }
    // ES module namespace objects are frozen/sealed by spec — property reads
    // on them are guaranteed side-effect-free. A computed key is still evaluated,
    // though, and may have its own side effects (e.g. `ns[foo()]`).
    if self.is_namespace_member_access(member_expr) == Some(true) {
      return match member_expr {
        ast::MemberExpression::ComputedMemberExpression(e) => self.analyze_expr(&e.expression),
        _ => StmtEvalFacts::default(),
      };
    }
    if Self::is_side_effect_free_import_meta_access(member_expr) {
      return StmtEvalFacts::default();
    }
    let is_global = self.is_member_expr_root_global(member_expr);
    let has_side_effect = member_expr.may_have_side_effects(self);
    let mut facts = StmtEvalFacts::from_tree_shaking_side_effect(has_side_effect);
    facts.set_order_sensitive_reason(StmtOrderSensitiveReasons::GlobalVarAccess, is_global);
    facts
  }

  fn analyze_eager_chain_children(&self, expr: &Expression) -> StmtEvalFacts {
    let mut facts = StmtEvalFacts::default();
    for_each_eager_chain_child(expr, |child| {
      facts |= match child {
        EagerChild::Expr(expr) => self.analyze_expr(expr),
        EagerChild::Spread(spread) => self.analyze_spread_argument(spread),
      };
    });
    facts
  }

  /// Analyze a `...operand` spread argument with its runtime semantics: `operand` is evaluated and
  /// then iterated. Iterating an array, string, or template literal runs only built-in iterators,
  /// so the only effects are those of evaluating `operand` — which [`Self::analyze_expr`], gated on
  /// oxc, already captures (including a nested spread such as `...[...x]`). Any other operand may
  /// run a user-defined `Symbol.iterator` when spread, so it stays conservatively unknown. Mirrors
  /// oxc's `Argument::may_have_side_effects` spread handling.
  fn analyze_spread_argument(&self, spread: &SpreadElement) -> StmtEvalFacts {
    match &spread.argument {
      Expression::ArrayExpression(_)
      | Expression::StringLiteral(_)
      | Expression::TemplateLiteral(_) => self.analyze_expr(&spread.argument),
      _ => StmtEvalFacts::from_unknown_side_effect(),
    }
  }

  /// Analyze a member-like write target after Oxc has determined the full write is side-effect-free.
  /// Writing to a property of an unresolved global still mutates shared state for tree shaking.
  fn analyze_side_effect_free_write_target(
    &self,
    target: &ast::SimpleAssignmentTarget,
  ) -> StmtEvalFacts {
    let object_detail = match target {
      ast::SimpleAssignmentTarget::StaticMemberExpression(e) => self.analyze_expr(&e.object),
      ast::SimpleAssignmentTarget::ComputedMemberExpression(e) => {
        self.analyze_expr(&e.object) | self.analyze_expr(&e.expression)
      }
      ast::SimpleAssignmentTarget::PrivateFieldExpression(e) => self.analyze_expr(&e.object),
      _ => return StmtEvalFacts::default(),
    };
    if object_detail.has_order_sensitive_reason(StmtOrderSensitiveReasons::GlobalVarAccess) {
      object_detail | StmtEvalFacts::from_unknown_side_effect()
    } else {
      object_detail
    }
  }

  fn analyze_call_expr(&self, expr: &CallExpression) -> StmtEvalFacts {
    let is_pure_annotated =
      !self.flat_options.ignore_annotations() && (expr.pure || self.is_call_expr_marked_pure(expr));

    // For pure-annotated calls, the call itself is side-effect-free.
    // We must check args via Rolldown's analyzer (not Oxc's) because Rolldown
    // has bundler-specific overrides (e.g. import.meta.url is side-effect-free).
    // Oxc's pure-call handling would still check args via its own may_have_side_effects,
    // which doesn't know about these overrides.
    let has_side_effect = if is_pure_annotated { false } else { expr.may_have_side_effects(self) };

    let is_global_call = !has_side_effect
      && matches!(&expr.callee, Expression::Identifier(id) if self.is_unresolved_reference(id));

    let mut facts = StmtEvalFacts::from_tree_shaking_side_effect(has_side_effect);
    facts.set_order_sensitive_reason(StmtOrderSensitiveReasons::PureAnnotation, is_pure_annotated);
    facts.set_order_sensitive_reason(StmtOrderSensitiveReasons::GlobalVarAccess, is_global_call);

    if !has_side_effect {
      // The call itself is known pure/safe; keep the callee's order-sensitive reasons while
      // discarding its unknown side-effect marker.
      facts |= self.analyze_expr(&expr.callee).without_unknown_side_effect();

      if is_pure_annotated {
        // Pure-annotated calls bypass Oxc's arg checking, so we must check args
        // through Rolldown's analyzer which has bundler-specific overrides
        // (e.g. import.meta.url is side-effect-free).
        for arg in &expr.arguments {
          facts |= match arg {
            Argument::SpreadElement(_) => StmtEvalFacts::from_unknown_side_effect(),
            _ => self.analyze_expr(arg.to_expression()),
          };
          if facts.has_side_effect_for_tree_shaking() {
            break;
          }
        }
      } else {
        // Oxc already verified args are side-effect-free; keep their order-sensitive reasons while
        // discarding unknown side-effect markers from this side-effect-free call.
        for arg in &expr.arguments {
          if let Argument::SpreadElement(_) = arg {
            break;
          }
          facts |= self.analyze_expr(arg.to_expression()).without_unknown_side_effect();
        }
      }
    }
    facts
  }

  fn is_expr_manual_pure_functions(&self, expr: &Expression) -> bool {
    if self.flat_options.is_manual_pure_functions_empty() {
      return false;
    }
    let manual_pure_functions = self.options.treeshake.manual_pure_functions().unwrap();
    chain_root_ident(expr).is_some_and(|first| manual_pure_functions.contains(first))
  }

  fn analyze_expr(&self, expr: &Expression) -> StmtEvalFacts {
    // Peel transparent wrappers (`(x)`, `x as T`, `x satisfies T`, `x!`, `<T>x`, `x<T>`)
    // — they add no runtime semantics, so we recurse into the inner expression.
    let expr = expr.get_inner_expression();
    match expr {
      // --- Bundler-specific overrides (order-sensitive reasons or custom logic) ---
      oxc::ast::match_member_expression!(Expression) => {
        self.analyze_member_expr(expr.to_member_expression())
      }
      Expression::Identifier(ident) => self.analyze_identifier(ident),
      Expression::AssignmentExpression(assign_expr) => {
        // Bundler-specific: CJS `exports.foo = ...` must be checked before Oxc,
        // because Oxc would see a write to an unresolved global and return true.
        if let Some(pure_cjs) = check_pure_cjs_export(self.scope, &assign_expr.left) {
          return StmtEvalFacts::from_tree_shaking_flags(pure_cjs)
            | self.analyze_expr(&assign_expr.right);
        }
        if assign_expr.may_have_side_effects(self) {
          return StmtEvalFacts::from_unknown_side_effect();
        }
        self.analyze_side_effect_free_write_target(assign_expr.left.to_simple_assignment_target())
      }

      Expression::ChainExpression(chain_expr) => match &chain_expr.expression {
        ChainElement::CallExpression(call_expr) => self.analyze_call_expr(call_expr),
        ChainElement::TSNonNullExpression(ts_expr) => self.analyze_expr(&ts_expr.expression),
        match_member_expression!(ChainElement) => {
          self.analyze_member_expr(chain_expr.expression.to_member_expression())
        }
      },
      Expression::UpdateExpression(update_expr) => {
        if update_expr.may_have_side_effects(self) {
          return StmtEvalFacts::from_unknown_side_effect();
        }
        self.analyze_side_effect_free_write_target(&update_expr.argument)
      }
      Expression::NewExpression(expr) => {
        let has_side_effect = expr.may_have_side_effects(self);

        // Order sensitivity: constructor is a known global
        let is_global_constructor = !has_side_effect
          && matches!(&expr.callee, Expression::Identifier(id) if self.is_unresolved_reference(id));
        // Order sensitivity: marked with /*@__PURE__*/
        let is_pure_annotated = !self.flat_options.ignore_annotations() && expr.pure;

        let mut facts = StmtEvalFacts::from_tree_shaking_side_effect(has_side_effect);
        facts.set_order_sensitive_reason(
          StmtOrderSensitiveReasons::GlobalVarAccess,
          is_global_constructor,
        );
        facts
          .set_order_sensitive_reason(StmtOrderSensitiveReasons::PureAnnotation, is_pure_annotated);

        if !has_side_effect {
          // Oxc already verified args are side-effect-free; keep their order-sensitive reasons while
          // discarding unknown side-effect markers from this side-effect-free constructor.
          for arg in &expr.arguments {
            if let Argument::SpreadElement(_) = arg {
              break;
            }
            facts |= self.analyze_expr(arg.to_expression()).without_unknown_side_effect();
          }
        }
        facts
      }
      Expression::CallExpression(expr) => self.analyze_call_expr(expr),

      // Transparent wrappers: oxc validates the boolean side-effect status,
      // we then recurse children to collect order-sensitive reasons
      // (`PureAnnotation`, `GlobalVarAccess`). Without this, a pure-annotated
      // call buried inside `export default { foo: /* @__PURE__ */ ... }`
      // loses its annotation at the catch-all and the bundler emits the
      // module's var-init at top level rather than wrapping it.
      // See rolldown/rolldown#9425.
      Expression::ObjectExpression(obj) => self.fold_compound(
        expr,
        // `p.computed == true` => `p.key` is always an Expression variant
        // (oxc's parser only emits Static/PrivateIdentifier for `key:` syntax).
        obj
          .properties
          .iter()
          .flat_map(|prop| match prop {
            ast::ObjectPropertyKind::ObjectProperty(p) => {
              [p.computed.then(|| p.key.to_expression()), Some(&p.value)]
            }
            ast::ObjectPropertyKind::SpreadProperty(s) => [Some(&s.argument), None],
          })
          .flatten(),
      ),
      Expression::ArrayExpression(arr) => self.fold_compound(
        expr,
        arr.elements.iter().filter_map(|elem| match elem {
          ast::ArrayExpressionElement::SpreadElement(s) => Some(&s.argument),
          ast::ArrayExpressionElement::Elision(_) => None,
          e => Some(e.to_expression()),
        }),
      ),
      Expression::SequenceExpression(s) => self.fold_compound(expr, &s.expressions),
      Expression::TemplateLiteral(t) => self.fold_compound(expr, &t.expressions),
      Expression::ConditionalExpression(c) => {
        self.fold_compound(expr, [&c.test, &c.consequent, &c.alternate])
      }
      Expression::LogicalExpression(e) => self.fold_compound(expr, [&e.left, &e.right]),
      Expression::BinaryExpression(e) => self.fold_compound(expr, [&e.left, &e.right]),
      Expression::UnaryExpression(e) => self.fold_compound(expr, [&e.argument]),

      // Class expressions: same definition-time order-sensitivity as class declarations (heritage,
      // computed keys, static initializers, static blocks, decorators). Method/instance bodies are
      // not evaluated here.
      Expression::ClassExpression(class) => {
        self.analyze_class_definition(expr.may_have_side_effects(self), class)
      }

      // Everything else: delegate entirely to Oxc.
      // Covers literals, function/arrow expressions (bodies not evaluated
      // here), await/import/yield (inherently side-effectful), tagged-template
      // (handled like a call by oxc; no `pure` flag), JSX, V8 intrinsics, etc.
      _ => StmtEvalFacts::from_tree_shaking_side_effect(expr.may_have_side_effects(self)),
    }
  }

  /// Gate-then-fold helper for transparent compound expressions: ask oxc
  /// whether the whole expression has any side effect (fast path, covers
  /// computed keys / spread reads / etc.), and if not, fold order-sensitive reasons
  /// (`PureAnnotation`, `GlobalVarAccess`) from the child expressions.
  ///
  /// Removing `UnknownSideEffect` is load-bearing: rolldown's analyzer can be
  /// more conservative than oxc for some sub-expressions (e.g. CJS-export
  /// assignments via [`check_pure_cjs_export`], or future bundler-specific
  /// overrides). Once oxc has certified the parent side-effect-free at the
  /// gate, we trust that judgment for the parent and strip any `UnknownSideEffect`
  /// that a child contributed; order-sensitive reasons should still propagate.
  fn fold_compound<'e>(
    &self,
    expr: &Expression,
    children: impl IntoIterator<Item = &'e Expression<'e>>,
  ) -> StmtEvalFacts {
    if expr.may_have_side_effects(self) {
      return StmtEvalFacts::from_unknown_side_effect();
    }
    let mut facts = StmtEvalFacts::default();
    for child in children {
      facts |= self.analyze_expr(child);
      if facts.has_side_effect_for_tree_shaking() {
        break;
      }
    }
    facts.without_unknown_side_effect()
  }

  fn analyze_var_decl(&self, var_decl: &ast::VariableDeclaration) -> StmtEvalFacts {
    match var_decl.kind {
      VariableDeclarationKind::AwaitUsing => StmtEvalFacts::from_unknown_side_effect(),
      VariableDeclarationKind::Using => self.analyze_using_declarators(&var_decl.declarations),
      _ => {
        let mut facts = StmtEvalFacts::default();
        for declarator in &var_decl.declarations {
          facts |= match &declarator.id {
            BindingPattern::ObjectPattern(_) if self.flat_options.property_read_side_effects() => {
              StmtEvalFacts::from_unknown_side_effect()
            }
            BindingPattern::ArrayPattern(pat)
              if pat.elements.iter().any(|p| {
                p.as_ref().is_some_and(|pat| !matches!(pat, BindingPattern::BindingIdentifier(_)))
              }) =>
            {
              StmtEvalFacts::from_unknown_side_effect()
            }
            _ => declarator.init.as_ref().map(|init| self.analyze_expr(init)).unwrap_or_default(),
          };
        }
        facts
      }
    }
  }

  /// Base facts for a `class` declaration/expression, plus its definition-time order-sensitive
  /// reasons. `has_side_effect` must be the caller's existing whole-class
  /// `may_have_side_effects` judgment so the tree-shaking channel stays byte-identical to what the
  /// delegate arms produced before; only when oxc certified the class side-effect-free do we look
  /// deeper, and then only to grow `order_sensitive_reasons`.
  fn analyze_class_definition(&self, has_side_effect: bool, class: &ast::Class) -> StmtEvalFacts {
    let mut facts = StmtEvalFacts::from_tree_shaking_side_effect(has_side_effect);
    if !has_side_effect {
      facts.order_sensitive_reasons |=
        EagerEvaluationOrderReasonCollector::collect_class(self, class);
    }
    facts
  }

  /// Add order-only facts from every expression that may run while evaluating this top-level
  /// statement. This deliberately does not reuse the tree-shaking walk: that walk may stop as soon
  /// as Oxc proves a surrounding call/member/binding operation pure, while strict order analysis
  /// still needs reads hidden behind that operation.
  ///
  /// The scanner only calls this for strict builds whose regular facts are not already
  /// order-sensitive. Keeping the entry point separate leaves the non-strict hot path,
  /// cross-module tree-shaking re-analysis, and `tree_shaking_flags` unchanged.
  pub(crate) fn add_top_level_eager_order_reasons(
    &self,
    stmt: &ast::Statement,
    facts: &mut StmtEvalFacts,
  ) {
    debug_assert!(!facts.is_order_sensitive());
    facts.order_sensitive_reasons |=
      EagerEvaluationOrderReasonCollector::collect_statement(self, stmt);
  }

  fn analyze_decl(&self, decl: &ast::Declaration) -> StmtEvalFacts {
    match decl {
      ast::Declaration::VariableDeclaration(var_decl) => self.analyze_var_decl(var_decl),
      // Class definition-time positions (heritage, computed keys, static initializers, static
      // blocks, decorators) can read a whitelisted global or carry a pure annotation, which makes
      // the class order-sensitive even when oxc reports no tree-shaking side effect. The delegate
      // catch-all below drops those reasons.
      ast::Declaration::ClassDeclaration(class) => {
        self.analyze_class_definition(decl.may_have_side_effects(self), class)
      }
      _ => StmtEvalFacts::from_tree_shaking_side_effect(decl.may_have_side_effects(self)),
    }
  }

  fn analyze_using_declarators(&self, declarators: &[ast::VariableDeclarator]) -> StmtEvalFacts {
    let mut facts = StmtEvalFacts::default();
    for decl in declarators {
      facts |= decl
        .init
        .as_ref()
        .map(|init| match init {
          Expression::NullLiteral(_) => StmtEvalFacts::default(),
          // Side effect detection of identifier is different with other position when as initialization of using declaration.
          // Global variable `undefined` is considered as side effect free.
          Expression::Identifier(id) => StmtEvalFacts::from_tree_shaking_side_effect(
            !(id.name == "undefined" && self.is_unresolved_reference(id)),
          ),
          Expression::UnaryExpression(expr) if matches!(expr.operator, UnaryOperator::Void) => {
            self.analyze_expr(&expr.argument)
          }
          _ => StmtEvalFacts::from_unknown_side_effect(),
        })
        .unwrap_or_default();
      if facts.has_side_effect_for_tree_shaking() {
        break;
      }
    }
    facts
  }

  fn analyze_identifier(&self, ident_ref: &IdentifierReference) -> StmtEvalFacts {
    let is_global = self.is_unresolved_reference(ident_ref);
    // Delegate side-effect bool to Oxc (checks known globals, unknown_global_side_effects)
    let has_side_effect = ident_ref.may_have_side_effects(self);
    let mut facts = StmtEvalFacts::from_tree_shaking_side_effect(has_side_effect);
    facts.set_order_sensitive_reason(StmtOrderSensitiveReasons::GlobalVarAccess, is_global);
    facts
  }

  /// Bundler-specific: module declarations like import/export are treated
  /// differently than in generic JS analysis.
  /// - import/export-all/re-export: side-effect-free (bundler handles them)
  /// - export default: recurse into declaration
  /// - export named with source: side-effect-free
  fn analyze_module_declaration(&self, decl: &ast::ModuleDeclaration) -> StmtEvalFacts {
    match decl {
      ast::ModuleDeclaration::ExportAllDeclaration(_)
      | ast::ModuleDeclaration::ExportFromDeclaration(_)
      | ast::ModuleDeclaration::ExportNamedDeclaration(_)
      | ast::ModuleDeclaration::ImportDeclaration(_) => {
        // We consider `import ...` has no side effect. However, `import ...` might be rewritten to other statements by the bundler.
        // In that case, we will mark the statement as having side effect in link stage.
        StmtEvalFacts::default()
      }
      ast::ModuleDeclaration::ExportDefaultDeclaration(default_decl) => {
        use oxc::ast::ast::ExportDefaultDeclarationKind;
        match &default_decl.declaration {
          decl @ oxc::ast::match_expression!(ExportDefaultDeclarationKind) => {
            self.analyze_expr(decl.to_expression())
          }
          ast::ExportDefaultDeclarationKind::FunctionDeclaration(_) => StmtEvalFacts::default(),
          ast::ExportDefaultDeclarationKind::ClassDeclaration(class) => {
            // Same definition-time order-sensitivity as a plain class declaration.
            self.analyze_class_definition(class.may_have_side_effects(self), class)
          }
          ast::ExportDefaultDeclarationKind::TSInterfaceDeclaration(_) => {
            StmtEvalFacts::from_unknown_side_effect()
          }
        }
      }
      ast::ModuleDeclaration::ExportDeclaration(export_decl) => {
        self.analyze_decl(&export_decl.declaration)
      }
      ast::ModuleDeclaration::TSExportAssignment(_)
      | ast::ModuleDeclaration::TSNamespaceExportDeclaration(_) => {
        StmtEvalFacts::from_unknown_side_effect()
      }
    }
  }

  pub fn analyze_stmt(&self, stmt: &ast::Statement) -> StmtEvalFacts {
    use oxc::ast::ast::Statement;
    match stmt {
      // Bundler-specific: module declarations
      oxc::ast::match_module_declaration!(Statement) => {
        self.analyze_module_declaration(stmt.to_module_declaration())
      }
      // Language-level: everything else
      oxc::ast::match_declaration!(Statement) => self.analyze_decl(stmt.to_declaration()),
      Statement::ExpressionStatement(expr) => self.analyze_expr(&expr.expression),
      Statement::BlockStatement(block) => self.analyze_block(block),
      Statement::DoWhileStatement(do_while) => {
        self.analyze_stmt(&do_while.body) | self.analyze_expr(&do_while.test)
      }
      Statement::WhileStatement(while_stmt) => {
        self.analyze_expr(&while_stmt.test) | self.analyze_stmt(&while_stmt.body)
      }
      Statement::IfStatement(if_stmt) => {
        self.analyze_expr(&if_stmt.test)
          | self.analyze_stmt(&if_stmt.consequent)
          | if_stmt.alternate.as_ref().map(|s| self.analyze_stmt(s)).unwrap_or_default()
      }
      Statement::ReturnStatement(ret_stmt) => {
        ret_stmt.argument.as_ref().map(|expr| self.analyze_expr(expr)).unwrap_or_default()
      }
      Statement::LabeledStatement(labeled_stmt) => self.analyze_stmt(&labeled_stmt.body),
      Statement::TryStatement(try_stmt) => {
        let mut facts = self.analyze_block(&try_stmt.block);
        facts |= try_stmt
          .handler
          .as_ref()
          .map(|handler| self.analyze_block(&handler.body))
          .unwrap_or_default();
        facts |= try_stmt
          .finalizer
          .as_ref()
          .map(|finalizer| self.analyze_block(finalizer))
          .unwrap_or_default();
        facts
      }
      Statement::SwitchStatement(switch_stmt) => {
        let mut facts = self.analyze_expr(&switch_stmt.discriminant);
        if facts.has_side_effect_for_tree_shaking() {
          return facts;
        }
        'outer: for case in &switch_stmt.cases {
          facts |= case.test.as_ref().map(|expr| self.analyze_expr(expr)).unwrap_or_default();
          for stmt in &case.consequent {
            facts |= self.analyze_stmt(stmt);
            if facts.has_side_effect_for_tree_shaking() {
              break 'outer;
            }
          }
        }
        facts
      }
      // Everything else: delegate to Oxc.
      // This covers Empty, Continue, Break, Debugger, For/ForIn/ForOf, Throw, With.
      _ => StmtEvalFacts::from_tree_shaking_side_effect(stmt.may_have_side_effects(self)),
    }
  }

  fn analyze_block(&self, block: &ast::BlockStatement) -> StmtEvalFacts {
    let mut facts = StmtEvalFacts::default();
    for stmt in &block.body {
      facts |= self.analyze_stmt(stmt);
      if facts.has_side_effect_for_tree_shaking() {
        break;
      }
    }
    facts
  }
}

/// Collects order-sensitive reasons from expressions that run while a top-level statement is
/// evaluated. This is intentionally independent from `StmtEvalAnalyzer`'s tree-shaking walk: a
/// tree-shaking flag is enough for that walk to stop, but it must not hide a later global read or
/// pure call from order analysis. Function/method bodies and instance initializers remain deferred;
/// a directly invoked function literal is entered explicitly below.
struct EagerEvaluationOrderReasonCollector<'analyzer, 'ctx> {
  analyzer: &'analyzer StmtEvalAnalyzer<'ctx>,
  reasons: StmtOrderSensitiveReasons,
  extended_top_level_reasons: bool,
}

impl<'analyzer, 'ctx> EagerEvaluationOrderReasonCollector<'analyzer, 'ctx> {
  fn new(analyzer: &'analyzer StmtEvalAnalyzer<'ctx>, extended_top_level_reasons: bool) -> Self {
    Self { analyzer, reasons: StmtOrderSensitiveReasons::empty(), extended_top_level_reasons }
  }

  fn collect_statement(
    analyzer: &'analyzer StmtEvalAnalyzer<'ctx>,
    stmt: &ast::Statement,
  ) -> StmtOrderSensitiveReasons {
    let mut collector = Self::new(analyzer, true);
    collector.visit_statement(stmt);
    collector.reasons
  }

  fn collect_class(
    analyzer: &'analyzer StmtEvalAnalyzer<'ctx>,
    class: &ast::Class,
  ) -> StmtOrderSensitiveReasons {
    // Preserve the original class-definition collector outside the strict top-level statement
    // walk. The extended statement-level cases below are order metadata for strict builds only and
    // must not perturb non-strict analysis.
    let mut collector = Self::new(analyzer, false);
    collector.visit_class(class);
    collector.reasons
  }

  fn add_reason_if(&mut self, reason: StmtOrderSensitiveReasons, value: bool) {
    if value {
      self.reasons.insert(reason);
    }
  }

  /// Function and arrow bodies are normally deferred until call time. A directly invoked function
  /// literal is different: its parameters and non-generator body run immediately.
  fn visit_immediately_invoked_function(&mut self, callee: &Expression<'_>) {
    match callee.get_inner_expression() {
      Expression::FunctionExpression(function) => {
        self.visit_formal_parameters(&function.params);
        if !function.generator
          && let Some(body) = &function.body
        {
          self.visit_function_body(body);
        }
      }
      Expression::ArrowFunctionExpression(arrow) => {
        self.visit_formal_parameters(&arrow.params);
        self.visit_arrow_function_body(&arrow.body);
      }
      Expression::SequenceExpression(sequence) => {
        if let Some(last) = sequence.expressions.last() {
          self.visit_immediately_invoked_function(last);
        }
      }
      Expression::ConditionalExpression(conditional) if self.extended_top_level_reasons => {
        self.visit_immediately_invoked_function(&conditional.consequent);
        self.visit_immediately_invoked_function(&conditional.alternate);
      }
      Expression::LogicalExpression(logical) if self.extended_top_level_reasons => {
        self.visit_immediately_invoked_function(&logical.left);
        self.visit_immediately_invoked_function(&logical.right);
      }
      Expression::AssignmentExpression(assignment) if self.extended_top_level_reasons => {
        // `(x = fn)()` and `(x ??= fn)()` evaluate to a value that may be the RHS, which the
        // surrounding call/new/tag then runs.
        self.visit_immediately_invoked_function(&assignment.right);
      }
      Expression::ClassExpression(class) if self.extended_top_level_reasons => {
        // `new class { ... }()` runs the construction-time positions immediately. The
        // definition-time positions were already collected by the ordinary class walk.
        self.visit_constructed_class_positions(class);
      }
      _ => {}
    }
  }

  /// Construction-time positions of a directly `new`ed class literal: constructor parameters and
  /// body, plus non-static field and accessor initializers. Static positions and computed keys
  /// run at definition time and are covered by `visit_class_definition`.
  fn visit_constructed_class_positions(&mut self, class: &ast::Class<'_>) {
    for element in &class.body.body {
      match element {
        ast::ClassElement::MethodDefinition(method)
          if matches!(method.kind, ast::MethodDefinitionKind::Constructor) =>
        {
          self.visit_formal_parameters(&method.value.params);
          if let Some(body) = &method.value.body {
            self.visit_function_body(body);
          }
        }
        ast::ClassElement::PropertyDefinition(property) if !property.r#static => {
          if let Some(value) = &property.value {
            self.visit_expression(value);
          }
        }
        ast::ClassElement::AccessorProperty(accessor) if !accessor.r#static => {
          if let Some(value) = &accessor.value {
            self.visit_expression(value);
          }
        }
        _ => {}
      }
    }
  }

  fn visit_class_definition(&mut self, class: &ast::Class<'_>) {
    // Decorator expressions and the heritage expression are evaluated when the class is defined.
    for decorator in &class.decorators {
      self.visit_expression(&decorator.expression);
    }
    if let Some(super_class) = &class.super_class {
      self.visit_expression(super_class);
    }

    for element in &class.body.body {
      match element {
        ast::ClassElement::StaticBlock(block) => {
          for stmt in &block.body {
            self.visit_statement(stmt);
          }
        }
        ast::ClassElement::MethodDefinition(method) => {
          for decorator in &method.decorators {
            self.visit_expression(&decorator.expression);
          }
          if method.computed {
            self.visit_expression(method.key.to_expression());
          }
          // Method/getter/setter bodies run when invoked, not at definition time.
        }
        ast::ClassElement::PropertyDefinition(property) => {
          for decorator in &property.decorators {
            self.visit_expression(&decorator.expression);
          }
          if property.computed {
            self.visit_expression(property.key.to_expression());
          }
          // Instance initializers run during construction; static initializers run now.
          if property.r#static
            && let Some(value) = &property.value
          {
            self.visit_expression(value);
          }
        }
        ast::ClassElement::AccessorProperty(accessor) => {
          for decorator in &accessor.decorators {
            self.visit_expression(&decorator.expression);
          }
          if accessor.computed {
            self.visit_expression(accessor.key.to_expression());
          }
          if accessor.r#static
            && let Some(value) = &accessor.value
          {
            self.visit_expression(value);
          }
        }
        // Type-level construct, no runtime evaluation.
        ast::ClassElement::TSIndexSignature(_) => {}
      }
    }
  }
}

impl<'ast> VisitJs<'ast> for EagerEvaluationOrderReasonCollector<'_, '_> {
  fn visit_identifier_reference(&mut self, ident: &IdentifierReference<'ast>) {
    let is_global_read = ident.reference_id.get().is_some_and(|reference_id| {
      let reference = self.analyzer.scope.scoping().get_reference(reference_id);
      reference.symbol_id().is_none() && reference.is_read()
    });
    self.add_reason_if(StmtOrderSensitiveReasons::GlobalVarAccess, is_global_read);
  }

  fn visit_assignment_expression(&mut self, assignment: &ast::AssignmentExpression<'ast>) {
    // A plain CJS export write is tree-shaking-only. Its target must not become a global-read
    // reason, but its RHS still runs and may contain one.
    if check_pure_cjs_export(self.analyzer.scope, &assignment.left).is_some() {
      self.visit_expression(&assignment.right);
    } else {
      walk_js::walk_assignment_expression(self, assignment);
    }
  }

  fn visit_call_expression(&mut self, call: &CallExpression<'ast>) {
    let is_pure_annotated = !self.analyzer.flat_options.ignore_annotations()
      && (call.pure || self.analyzer.is_call_expr_marked_pure(call));
    let is_manual_pure =
      self.extended_top_level_reasons && self.analyzer.is_expr_manual_pure_functions(&call.callee);
    self.add_reason_if(
      StmtOrderSensitiveReasons::PureAnnotation,
      is_pure_annotated || is_manual_pure,
    );

    walk_js::walk_call_expression(self, call);
    self.visit_immediately_invoked_function(&call.callee);
  }

  fn visit_new_expression(&mut self, new_expr: &ast::NewExpression<'ast>) {
    self.add_reason_if(
      StmtOrderSensitiveReasons::PureAnnotation,
      (!self.analyzer.flat_options.ignore_annotations() && new_expr.pure)
        || (self.extended_top_level_reasons
          && self.analyzer.is_expr_manual_pure_functions(&new_expr.callee)),
    );
    walk_js::walk_new_expression(self, new_expr);
    self.visit_immediately_invoked_function(&new_expr.callee);
  }

  fn visit_tagged_template_expression(&mut self, tagged: &ast::TaggedTemplateExpression<'ast>) {
    self.add_reason_if(
      StmtOrderSensitiveReasons::PureAnnotation,
      self.extended_top_level_reasons && self.analyzer.is_expr_manual_pure_functions(&tagged.tag),
    );
    walk_js::walk_tagged_template_expression(self, tagged);
    // Evaluating the template calls a literal tag immediately. Gated so the legacy class-mode
    // collector, which never entered tag bodies, stays byte-identical for ordinary builds.
    if self.extended_top_level_reasons {
      self.visit_immediately_invoked_function(&tagged.tag);
    }
  }

  // Merely creating a function does not run its parameters or body.
  fn visit_function(&mut self, _function: &ast::Function<'ast>, _flags: ScopeFlags) {}

  fn visit_arrow_function_expression(&mut self, _arrow: &ast::ArrowFunctionExpression<'ast>) {}

  // A nested class has the same definition-time/deferred split as the outer class.
  fn visit_class(&mut self, class: &ast::Class<'ast>) {
    self.visit_class_definition(class);
  }
}

/// Bundler-specific: detect `exports.staticProp = ...` CJS export pattern.
/// Returns `Some(PureCjs)` if the target matches, `None` otherwise.
fn check_pure_cjs_export(scope: &AstScopes, target: &AssignmentTarget) -> Option<StmtEvalFlags> {
  match target {
    AssignmentTarget::ComputedMemberExpression(_) | AssignmentTarget::StaticMemberExpression(_) => {
      let member_expr = target.to_member_expression();
      if let Expression::Identifier(ident) = member_expr.object() {
        if ident.name == "exports"
          && member_expr.static_property_name().is_some()
          && ident.reference_id.get().is_some_and(|ref_id| scope.is_unresolved(ref_id))
        {
          return Some(StmtEvalFlags::PureCjs);
        }
      }
      None
    }
    _ => None,
  }
}

/// An eagerly-evaluated subexpression surfaced by [`chain_root_visiting_eager_children`].
enum EagerChild<'a> {
  /// A computed member key or a non-spread call argument — evaluated as a plain expression.
  Expr(&'a Expression<'a>),
  /// A spread call argument (`...operand`) — evaluating `operand` and iterating it may both have
  /// effects, so it needs spread-aware analysis rather than plain expression analysis.
  Spread(&'a SpreadElement<'a>),
}

/// Descend a member-expression-like chain to its leftmost identifier, invoking `on_eager_child`
/// for every eagerly-evaluated subexpression on the way down — computed keys and call arguments
/// (see [`EagerChild`]). Returns the root identifier's name, or `None` when the chain doesn't
/// bottom out in a plain identifier.
///
/// This is the shared engine behind [`chain_root_ident`] and [`for_each_eager_chain_child`]; call
/// whichever of those fits instead of reading the return value and driving the visitor from the
/// same call site.
fn chain_root_visiting_eager_children<'a>(
  expr: &'a Expression,
  mut on_eager_child: impl FnMut(EagerChild<'a>),
) -> Option<&'a str> {
  fn visit_call_args<'a>(
    args: &'a [Argument<'a>],
    on_eager_child: &mut impl FnMut(EagerChild<'a>),
  ) {
    for arg in args {
      on_eager_child(match arg {
        Argument::SpreadElement(spread) => EagerChild::Spread(spread),
        _ => EagerChild::Expr(arg.to_expression()),
      });
    }
  }

  let mut cur = expr;
  loop {
    match cur {
      Expression::Identifier(ident) => break Some(ident.name.as_str()),
      Expression::ComputedMemberExpression(expr) => {
        on_eager_child(EagerChild::Expr(&expr.expression));
        cur = &expr.object;
      }
      Expression::StaticMemberExpression(expr) => {
        cur = &expr.object;
      }
      Expression::CallExpression(expr) => {
        visit_call_args(&expr.arguments, &mut on_eager_child);
        cur = &expr.callee;
      }
      Expression::ChainExpression(expr) => match expr.expression {
        ChainElement::CallExpression(ref call_expression) => {
          visit_call_args(&call_expression.arguments, &mut on_eager_child);
          cur = &call_expression.callee;
        }
        ChainElement::ComputedMemberExpression(ref computed_member_expression) => {
          on_eager_child(EagerChild::Expr(&computed_member_expression.expression));
          cur = &computed_member_expression.object;
        }
        ChainElement::StaticMemberExpression(ref static_member_expression) => {
          cur = &static_member_expression.object;
        }
        ChainElement::TSNonNullExpression(_) | ChainElement::PrivateFieldExpression(_) => {
          break None;
        }
      },
      _ => break None,
    }
  }
}

/// The leftmost identifier a member-expression-like chain reads from (`a` in `a.b().c[d]`), or
/// `None` when the chain doesn't bottom out in a plain identifier. Used by
/// `StmtEvalAnalyzer::is_expr_manual_pure_functions` and `StmtEvalAnalyzer::manual_pure_functions`.
fn chain_root_ident<'a>(expr: &'a Expression) -> Option<&'a str> {
  chain_root_visiting_eager_children(expr, |_| {})
}

/// Invoke `visit` on every eagerly-evaluated subexpression of a member-expression-like chain —
/// computed keys and call arguments (see [`EagerChild`]).
fn for_each_eager_chain_child<'a>(expr: &'a Expression, visit: impl FnMut(EagerChild<'a>)) {
  let _ = chain_root_visiting_eager_children(expr, visit);
}

impl GlobalContext<'_> for StmtEvalAnalyzer<'_> {
  fn is_global_reference(&self, reference: &IdentifierReference<'_>) -> bool {
    self.is_unresolved_reference(reference)
  }
}

impl MayHaveSideEffectsContext<'_> for StmtEvalAnalyzer<'_> {
  fn engine_targets(&self) -> Option<&EngineTargets> {
    Some(&self.options.transform_options.target)
  }

  fn annotations(&self) -> bool {
    !self.flat_options.ignore_annotations()
  }

  fn manual_pure_functions(&self, callee: &Expression) -> bool {
    self.is_expr_manual_pure_functions(callee)
      && !self.analyze_eager_chain_children(callee).has_side_effect_for_tree_shaking()
  }

  fn property_read_side_effects(&self) -> PropertyReadSideEffects {
    if self.flat_options.property_read_side_effects() {
      PropertyReadSideEffects::All
    } else {
      PropertyReadSideEffects::None
    }
  }

  fn unknown_global_side_effects(&self) -> bool {
    self.options.treeshake.unknown_global_side_effects()
  }

  fn property_write_side_effects(&self) -> bool {
    self.flat_options.property_write_side_effects()
  }
}

#[cfg(test)]
mod test {
  use std::sync::Arc;

  use itertools::Itertools;
  use oxc::{parser::Parser, span::SourceType};
  use rolldown_common::{
    AstScopes, ExperimentalOptions, InnerOptions, NormalizedBundlerOptions,
    PropertyReadSideEffects, PropertyWriteSideEffects, StmtEvalFlags,
  };
  use rolldown_ecmascript::{EcmaAst, EcmaCompiler};

  use super::StmtEvalAnalyzer;
  use rolldown_common::FlatOptions;

  fn has_side_effect_for_tree_shaking(code: &str) -> bool {
    let source_type = SourceType::tsx();
    let ast = EcmaCompiler::parse("<Noop>", code, source_type).unwrap();
    let semantic = EcmaAst::make_semantic(ast.program());
    let scoping = semantic.into_scoping();
    let ast_scopes = AstScopes::new(scoping);

    let options = Arc::new(NormalizedBundlerOptions::default());
    let flags = FlatOptions::from_shared_options(&options);
    ast.program().body.iter().any(|stmt| {
      StmtEvalAnalyzer::new(&ast_scopes, flags, &options, None, None)
        .analyze_stmt(stmt)
        .has_side_effect_for_tree_shaking()
    })
  }

  fn has_side_effect_for_tree_shaking_with_target(code: &str, target: &str) -> bool {
    let source_type = SourceType::tsx();
    let ast = EcmaCompiler::parse("<Noop>", code, source_type).unwrap();
    let semantic = EcmaAst::make_semantic(ast.program());
    let scoping = semantic.into_scoping();
    let ast_scopes = AstScopes::new(scoping);

    let mut options = NormalizedBundlerOptions::default();
    options.transform_options.target =
      oxc::transformer::EngineTargets::from_target(target).expect("valid target");
    let options = Arc::new(options);
    let flags = FlatOptions::from_shared_options(&options);
    ast.program().body.iter().any(|stmt| {
      StmtEvalAnalyzer::new(&ast_scopes, flags, &options, None, None)
        .analyze_stmt(stmt)
        .has_side_effect_for_tree_shaking()
    })
  }

  fn get_stmt_eval_flags(code: &str) -> Vec<StmtEvalFlags> {
    let source_type = SourceType::tsx();
    let ast = EcmaCompiler::parse("<Noop>", code, source_type).unwrap();
    let semantic = EcmaAst::make_semantic(ast.program());
    let scoping = semantic.into_scoping();
    let ast_scopes = AstScopes::new(scoping);

    let options = Arc::new(NormalizedBundlerOptions::default());
    let flags = FlatOptions::from_shared_options(&options);
    ast
      .program()
      .body
      .iter()
      .map(|stmt| {
        StmtEvalAnalyzer::new(&ast_scopes, flags, &options, None, None)
          .analyze_stmt(stmt)
          .tree_shaking_flags()
      })
      .collect_vec()
  }

  fn get_stmt_order_sensitivity(code: &str) -> Vec<bool> {
    let source_type = SourceType::tsx();
    let ast = EcmaCompiler::parse("<Noop>", code, source_type).unwrap();
    let semantic = EcmaAst::make_semantic(ast.program());
    let scoping = semantic.into_scoping();
    let ast_scopes = AstScopes::new(scoping);

    let options = Arc::new(NormalizedBundlerOptions::default());
    let flags = FlatOptions::from_shared_options(&options);
    ast
      .program()
      .body
      .iter()
      .map(|stmt| {
        StmtEvalAnalyzer::new(&ast_scopes, flags, &options, None, None)
          .analyze_stmt(stmt)
          .is_order_sensitive()
      })
      .collect_vec()
  }

  fn get_stmt_eval_with_options(
    code: &str,
    options: &Arc<NormalizedBundlerOptions>,
  ) -> Vec<(StmtEvalFlags, bool)> {
    let source_type = SourceType::tsx();
    let ast = EcmaCompiler::parse("<Noop>", code, source_type).unwrap();
    let semantic = EcmaAst::make_semantic(ast.program());
    let scoping = semantic.into_scoping();
    let ast_scopes = AstScopes::new(scoping);

    let flags = FlatOptions::from_shared_options(options);
    ast
      .program()
      .body
      .iter()
      .map(|stmt| {
        let facts =
          StmtEvalAnalyzer::new(&ast_scopes, flags, options, None, None).analyze_stmt(stmt);
        (facts.tree_shaking_flags(), facts.is_order_sensitive())
      })
      .collect_vec()
  }

  fn get_stmt_eval_with_top_level_eager_order_reasons(
    code: &str,
    options: &Arc<NormalizedBundlerOptions>,
  ) -> Vec<(StmtEvalFlags, bool)> {
    let source_type = SourceType::tsx();
    let ast = EcmaCompiler::parse("<Noop>", code, source_type).unwrap();
    let semantic = EcmaAst::make_semantic(ast.program());
    let scoping = semantic.into_scoping();
    let ast_scopes = AstScopes::new(scoping);

    let flags = FlatOptions::from_shared_options(options);
    ast
      .program()
      .body
      .iter()
      .map(|stmt| {
        let analyzer = StmtEvalAnalyzer::new(&ast_scopes, flags, options, None, None);
        let mut facts = analyzer.analyze_stmt(stmt);
        if options.is_strict_execution_order_enabled() && !facts.is_order_sensitive() {
          analyzer.add_top_level_eager_order_reasons(stmt, &mut facts);
        }
        (facts.tree_shaking_flags(), facts.is_order_sensitive())
      })
      .collect_vec()
  }

  fn strict_on_demand_options(treeshake: InnerOptions) -> Arc<NormalizedBundlerOptions> {
    Arc::new(NormalizedBundlerOptions {
      treeshake: treeshake.into(),
      experimental: ExperimentalOptions {
        on_demand_wrapping: Some(true),
        ..ExperimentalOptions::default()
      },
      strict_execution_order: true,
      ..NormalizedBundlerOptions::default()
    })
  }

  fn assert_eager_reason_only(
    code: &str,
    options: &Arc<NormalizedBundlerOptions>,
    expected_flags: StmtEvalFlags,
  ) {
    let regular = get_stmt_eval_with_options(code, options);
    let eager = get_stmt_eval_with_top_level_eager_order_reasons(code, options);
    assert_eq!(regular, vec![(expected_flags, false)], "regular facts for {code}");
    assert_eq!(eager, vec![(expected_flags, true)], "eager facts for {code}");
  }

  fn assert_last_statement_gets_eager_reason_only(
    code: &str,
    options: &Arc<NormalizedBundlerOptions>,
    expected_flags: StmtEvalFlags,
  ) {
    let regular = get_stmt_eval_with_options(code, options);
    let eager = get_stmt_eval_with_top_level_eager_order_reasons(code, options);
    assert_eq!(
      regular.iter().map(|(flags, _)| *flags).collect_vec(),
      eager.iter().map(|(flags, _)| *flags).collect_vec(),
      "tree-shaking flags for {code}"
    );
    assert_eq!(regular.last(), Some(&(expected_flags, false)), "regular facts for {code}");
    assert_eq!(eager.last(), Some(&(expected_flags, true)), "eager facts for {code}");
    assert!(
      eager[..eager.len() - 1].iter().all(|(_, is_order_sensitive)| !is_order_sensitive),
      "deferred declarations for {code}"
    );
  }

  #[test]
  fn test_side_effect_for_tree_shaking() {
    assert!(!has_side_effect_for_tree_shaking("export { a }"));
    assert!(!has_side_effect_for_tree_shaking("const a = {}"));
    assert!(!has_side_effect_for_tree_shaking(
      "const PatchFlags = {
        'TEXT':1,
        '1':'TEXT',
        'CLASS':2,
        '2':'CLASS',
        'STYLE':4,
        '4':'STYLE',
        'PROPS':8,
        '8':'PROPS',
        'FULL_PROPS':16,
        '16':'FULL_PROPS',
        'NEED_HYDRATION':32,
        '32':'NEED_HYDRATION',
        'STABLE_FRAGMENT':64,
        '64':'STABLE_FRAGMENT',
        'KEYED_FRAGMENT':128,
        '128':'KEYED_FRAGMENT',
        'UNKEYED_FRAGMENT':256,
        '256':'UNKEYED_FRAGMENT',
        'NEED_PATCH':512,
        '512':'NEED_PATCH',
        'DYNAMIC_SLOTS':1024,
        '1024':'DYNAMIC_SLOTS',
        'DEV_ROOT_FRAGMENT':2048,
        '2048':'DEV_ROOT_FRAGMENT',
        'HOISTED': -1,
        '-1':'HOISTED',
        'BAIL': -2,
        '-2':'BAIL'
      };",
    ));
  }

  #[test]
  fn test_template_literal() {
    assert!(!has_side_effect_for_tree_shaking("`hello`"));
    assert!(has_side_effect_for_tree_shaking("const foo = ''; `hello${foo}`"));
    // accessing global variable may have side effect
    assert!(has_side_effect_for_tree_shaking("`hello${foo}`"));
    assert!(has_side_effect_for_tree_shaking("const foo = {}; `hello${foo.bar}`"));
    assert!(has_side_effect_for_tree_shaking("tag`hello`"));
  }

  #[test]
  fn test_logical_expression() {
    assert!(!has_side_effect_for_tree_shaking("true && false"));
    assert!(!has_side_effect_for_tree_shaking("null ?? true"));
    // accessing global variable may have side effect
    assert!(has_side_effect_for_tree_shaking("true && bar"));
    assert!(has_side_effect_for_tree_shaking("foo ?? true"));
  }

  #[test]
  fn test_parenthesized_expression() {
    assert!(!has_side_effect_for_tree_shaking("(true)"));
    assert!(!has_side_effect_for_tree_shaking("(null)"));
    // accessing global variable may have side effect
    assert!(has_side_effect_for_tree_shaking("(bar)"));
    assert!(has_side_effect_for_tree_shaking("(foo)"));
  }

  #[test]
  fn test_sequence_expression() {
    assert!(!has_side_effect_for_tree_shaking("true, false"));
    assert!(!has_side_effect_for_tree_shaking("null, true"));
    // accessing global variable may have side effect
    assert!(has_side_effect_for_tree_shaking("true, bar"));
    assert!(has_side_effect_for_tree_shaking("foo, true"));
  }

  #[test]
  fn test_conditional_expression() {
    assert!(!has_side_effect_for_tree_shaking("true ? false : true"));
    assert!(!has_side_effect_for_tree_shaking("null ? true : false"));
    // accessing global variable may have side effect
    assert!(has_side_effect_for_tree_shaking("true ? bar : true"));
    assert!(has_side_effect_for_tree_shaking("foo ? true : false"));
    assert!(has_side_effect_for_tree_shaking("true ? bar : true"));
  }

  #[test]
  fn test_block_statement() {
    assert!(!has_side_effect_for_tree_shaking("{ }"));
    assert!(!has_side_effect_for_tree_shaking("{ const a = 1; }"));
    assert!(!has_side_effect_for_tree_shaking("{ const a = 1; const b = 2; }"));
    // accessing global variable may have side effect
    assert!(has_side_effect_for_tree_shaking("{ const a = 1; bar; }"));
  }

  #[test]
  fn test_do_while_statement() {
    assert!(!has_side_effect_for_tree_shaking("do { } while (true)"));
    assert!(!has_side_effect_for_tree_shaking("do { const a = 1; } while (true)"));
    // accessing global variable may have side effect
    assert!(has_side_effect_for_tree_shaking("do { const a = 1; } while (bar)"));
    assert!(has_side_effect_for_tree_shaking("do { const a = 1; bar; } while (true)"));
    assert!(has_side_effect_for_tree_shaking("do { bar; } while (true)"));
  }

  #[test]
  fn test_while_statement() {
    assert!(!has_side_effect_for_tree_shaking("while (true) { }"));
    assert!(!has_side_effect_for_tree_shaking("while (true) { const a = 1; }"));
    // accessing global variable may have side effect
    assert!(has_side_effect_for_tree_shaking("while (bar) { const a = 1; }"));
    assert!(has_side_effect_for_tree_shaking("while (true) { const a = 1; bar; }"));
    assert!(has_side_effect_for_tree_shaking("while (true) { bar; }"));
  }

  #[test]
  fn test_if_statement() {
    assert!(!has_side_effect_for_tree_shaking("if (true) { }"));
    assert!(!has_side_effect_for_tree_shaking("if (true) { const a = 1; }"));
    // accessing global variable may have side effect
    assert!(has_side_effect_for_tree_shaking("if (bar) { const a = 1; }"));
    assert!(has_side_effect_for_tree_shaking("if (true) { const a = 1; bar; }"));
    assert!(has_side_effect_for_tree_shaking("if (true) { bar; }"));
  }

  #[test]
  fn test_empty_statement() {
    assert!(!has_side_effect_for_tree_shaking(";"));
    assert!(!has_side_effect_for_tree_shaking(";;"));
  }

  #[test]
  fn test_continue_statement() {
    assert!(!has_side_effect_for_tree_shaking("continue;"));
  }

  #[test]
  fn test_break_statement() {
    assert!(!has_side_effect_for_tree_shaking("break;"));
  }

  #[test]
  fn test_return_statement() {
    assert!(!has_side_effect_for_tree_shaking("return;"));
    assert!(!has_side_effect_for_tree_shaking("return 1;"));
    // accessing global variable may have side effect
    assert!(has_side_effect_for_tree_shaking("return bar;"));
  }

  #[test]
  fn test_labeled_statement() {
    assert!(!has_side_effect_for_tree_shaking("label: { }"));
    assert!(!has_side_effect_for_tree_shaking("label: { const a = 1; }"));
    // accessing global variable may have side effect
    assert!(has_side_effect_for_tree_shaking("label: { const a = 1; bar; }"));
    assert!(has_side_effect_for_tree_shaking("label: { bar; }"));
  }

  #[test]
  fn test_try_statement() {
    assert!(!has_side_effect_for_tree_shaking("try { } catch (e) { }"));
    assert!(!has_side_effect_for_tree_shaking("try { const a = 1; } catch (e) { }"));
    assert!(!has_side_effect_for_tree_shaking("try { } catch (e) { const a = 1; }"));
    assert!(!has_side_effect_for_tree_shaking("try { const a = 1; } catch (e) { const a = 1; }"));
    assert!(!has_side_effect_for_tree_shaking("try { const a = 1; } finally { }"));
    assert!(!has_side_effect_for_tree_shaking("try { } catch (e) { const a = 1; } finally { }"));
    assert!(!has_side_effect_for_tree_shaking("try { } catch (e) { } finally { const a = 1; }"));
    assert!(!has_side_effect_for_tree_shaking(
      "try { const a = 1; } catch (e) { const a = 1; } finally { const a = 1; }"
    ));
    // accessing global variable may have side effect
    assert!(has_side_effect_for_tree_shaking("try { const a = 1; bar; } catch (e) { }"));
    assert!(has_side_effect_for_tree_shaking("try { } catch (e) { const a = 1; bar; }"));
    assert!(has_side_effect_for_tree_shaking("try { } catch (e) { bar; }"));
    assert!(has_side_effect_for_tree_shaking("try { const a = 1; } catch (e) { bar; }"));
    assert!(has_side_effect_for_tree_shaking("try { bar; } finally { }"));
    assert!(has_side_effect_for_tree_shaking("try { } catch (e) { bar; } finally { }"));
    assert!(has_side_effect_for_tree_shaking("try { } catch (e) { } finally { bar; }"));
    assert!(has_side_effect_for_tree_shaking("try { bar; } catch (e) { bar; } finally { bar; }"));
  }

  #[test]
  fn test_switch_statement() {
    assert!(!has_side_effect_for_tree_shaking("switch (true) { }"));
    assert!(!has_side_effect_for_tree_shaking("switch (true) { case 1: break; }"));
    assert!(!has_side_effect_for_tree_shaking("switch (true) { case 1: break; default: break; }"));
    // accessing global variable may have side effect
    assert!(has_side_effect_for_tree_shaking("switch (bar) { case 1: break; }"));
    assert!(has_side_effect_for_tree_shaking("switch (true) { case 1: bar; }"));
    assert!(has_side_effect_for_tree_shaking("switch (true) { case bar: break; }"));
    assert!(has_side_effect_for_tree_shaking("switch (true) { case 1: bar; default: bar; }"));
  }

  #[test]
  fn test_binary_expression() {
    // accessing global variable may have side effect
    assert!(has_side_effect_for_tree_shaking("1 + foo"));
    assert!(has_side_effect_for_tree_shaking("2 + bar"));
    // Oxc correctly recognizes primitive literal operands as side-effect-free
    assert!(!has_side_effect_for_tree_shaking("1 + 1"));
    // Oxc doesn't do constant propagation through variables, so `a + b` is
    // conservatively treated as potentially side-effectful (ToPrimitive)
    assert!(has_side_effect_for_tree_shaking("const a = 1; const b = 2; a + b"));
  }

  #[test]
  fn test_private_in_expression() {
    // Oxc checks that the RHS is known to be an object; `this` and local
    // variables with unknown value type are conservatively treated as
    // potentially non-object, so `#x in this` / `#x in obj` may throw.
    assert!(has_side_effect_for_tree_shaking("#privateField in this"));
    assert!(has_side_effect_for_tree_shaking("const obj = {}; #privateField in obj"));
    // accessing global variable may have side effect
    assert!(has_side_effect_for_tree_shaking("#privateField in bar"));
    assert!(has_side_effect_for_tree_shaking("#privateField in foo"));
  }

  #[test]
  fn test_this_expression() {
    // In oxc 0.125.0, `this` is now considered to potentially have side effects
    // because it may be used in contexts where accessing `this` could throw
    assert!(has_side_effect_for_tree_shaking("this"));
    assert!(has_side_effect_for_tree_shaking("this.a"));
    assert!(has_side_effect_for_tree_shaking("this.a + this.b"));
    assert!(has_side_effect_for_tree_shaking("this.a = 10"));
  }

  #[test]
  fn test_meta_property_expression() {
    assert!(!has_side_effect_for_tree_shaking("import.meta"));
    assert!(!has_side_effect_for_tree_shaking("const meta = import.meta"));
    assert!(!has_side_effect_for_tree_shaking("import.meta.url"));
    assert!(!has_side_effect_for_tree_shaking("import.meta?.url"));
    assert!(!has_side_effect_for_tree_shaking("import.meta['url']"));
    assert!(!has_side_effect_for_tree_shaking("import.meta?.['url']"));
    assert!(!has_side_effect_for_tree_shaking("import.meta.ROLLDOWN_FILE_URL_abc123"));
    assert!(!has_side_effect_for_tree_shaking("import.meta?.ROLLDOWN_FILE_URL_abc123"));
    assert!(!has_side_effect_for_tree_shaking(
      "import.meta.ROLLDOWN_FILE_URL_aaaaaaaaaaaaaaaaaaaaaa_myUrlId"
    ));
    assert!(!has_side_effect_for_tree_shaking("import.meta['ROLLDOWN_FILE_URL_abc123']"));
    assert!(!has_side_effect_for_tree_shaking("import.meta?.['ROLLDOWN_FILE_URL_abc123']"));
    assert!(!has_side_effect_for_tree_shaking("import.meta.ROLLUP_FILE_URL_abc123"));
    assert!(!has_side_effect_for_tree_shaking("import.meta?.ROLLUP_FILE_URL_abc123"));
    assert!(!has_side_effect_for_tree_shaking("import.meta['ROLLUP_FILE_URL_abc123']"));
    assert!(!has_side_effect_for_tree_shaking("import.meta?.['ROLLUP_FILE_URL_abc123']"));
    assert!(has_side_effect_for_tree_shaking("import.meta[foo()]"));
    // Other import.meta properties are not spec-defined as side-effect-free
    assert!(has_side_effect_for_tree_shaking("import.meta.hot"));
    assert!(has_side_effect_for_tree_shaking("import.meta['hot']"));
    // Deeper chains may throw (e.g. import.meta.nonExisting is undefined, .foo throws TypeError)
    assert!(has_side_effect_for_tree_shaking("import.meta.nonExisting.foo"));
    assert!(has_side_effect_for_tree_shaking("const { url } = import.meta"));
    assert!(has_side_effect_for_tree_shaking("import.meta.url = 'test'"));
  }

  #[test]
  fn test_assignment_expression() {
    // Destructuring assignments are side-effectful (GetIterator / RequireObjectCoercible).
    assert!(has_side_effect_for_tree_shaking("let a; [] = a"));
    assert!(has_side_effect_for_tree_shaking("({} = a)"));
    assert!(has_side_effect_for_tree_shaking("let a; a = 1"));
    assert!(has_side_effect_for_tree_shaking("let a, b; a = b; a = b = 1"));
    // accessing global variable may have side effect
    assert!(has_side_effect_for_tree_shaking("b = 1"));
    assert!(has_side_effect_for_tree_shaking("[] = b"));
    assert!(has_side_effect_for_tree_shaking("let a; a = b"));
    assert!(has_side_effect_for_tree_shaking("let a; a.b = 1"));
    assert!(has_side_effect_for_tree_shaking("let a; a['b'] = 1"));
    assert!(has_side_effect_for_tree_shaking("let a; a = a.b"));
    assert!(has_side_effect_for_tree_shaking("let a, b; ({ a } = b)"));
    assert!(has_side_effect_for_tree_shaking("let a, b; ({ ...a } = b)"));
    assert!(has_side_effect_for_tree_shaking("let a, b; [ a ] = b"));
    assert!(has_side_effect_for_tree_shaking("let a, b; [ ...a ] = b"));
  }

  #[test]
  fn test_chain_expression() {
    assert!(!has_side_effect_for_tree_shaking("Object.create"));
    assert!(!has_side_effect_for_tree_shaking("Object?.create"));
    assert!(!has_side_effect_for_tree_shaking("let a; /*#__PURE__*/ a?.()"));
    assert!(has_side_effect_for_tree_shaking("let a; a?.b"));
    assert!(has_side_effect_for_tree_shaking("let a; a?.()"));
    assert!(has_side_effect_for_tree_shaking("let a; a?.[a]"));
  }

  #[test]
  fn test_other_statements() {
    assert!(has_side_effect_for_tree_shaking("debugger;"));
    assert!(has_side_effect_for_tree_shaking("for (const k in {}) { }"));
    assert!(has_side_effect_for_tree_shaking("let a; for (const v of []) { a++ }"));
    assert!(has_side_effect_for_tree_shaking("for (;;) { }"));
    assert!(has_side_effect_for_tree_shaking("throw 1;"));
    assert!(has_side_effect_for_tree_shaking("with(a) { }"));
    assert!(has_side_effect_for_tree_shaking("await 1"));
    assert!(has_side_effect_for_tree_shaking("import('foo')"));
    assert!(has_side_effect_for_tree_shaking("let a; a``"));
    assert!(has_side_effect_for_tree_shaking("let a; a++"));
  }

  #[test]
  fn test_new_expr() {
    assert!(!has_side_effect_for_tree_shaking("new Map()"));
    assert!(!has_side_effect_for_tree_shaking("new Set()"));
    assert!(!has_side_effect_for_tree_shaking("new Map([[1, 2], [3, 4]]);"));
    assert!(has_side_effect_for_tree_shaking("new Regex()"));
    assert!(!has_side_effect_for_tree_shaking(
      "new Date(); new Date(''); new Date(null); new Date(false); new Date(undefined)"
    ));

    // TypedArray constructors should be side-effect free with no args, null, or undefined
    assert!(!has_side_effect_for_tree_shaking("new Uint8Array()"));
    assert!(!has_side_effect_for_tree_shaking("new Uint8Array(null)"));
    assert!(!has_side_effect_for_tree_shaking("new Uint8Array(undefined)"));
    assert!(!has_side_effect_for_tree_shaking("new Int8Array()"));
    assert!(!has_side_effect_for_tree_shaking("new Uint16Array()"));
    assert!(!has_side_effect_for_tree_shaking("new Uint32Array()"));
    assert!(!has_side_effect_for_tree_shaking("new Float64Array()"));
    assert!(!has_side_effect_for_tree_shaking("new BigUint64Array()"));

    // TypedArray constructors with numeric args are side-effect free
    // (memory allocation is not an observable side effect for tree-shaking)
    assert!(!has_side_effect_for_tree_shaking("new Uint8Array(10)"));
    assert!(!has_side_effect_for_tree_shaking("new Int16Array(5)"));
    assert!(!has_side_effect_for_tree_shaking("new Int32Array(100)"));
    assert!(!has_side_effect_for_tree_shaking("new Float32Array(20)"));
    assert!(!has_side_effect_for_tree_shaking("new BigInt64Array(8)"));
    assert!(!has_side_effect_for_tree_shaking("new Uint8ClampedArray(256)"));

    // Symbol is not a constructor - using 'new' throws TypeError
    // All of these should have side effects (they throw errors)
    assert!(has_side_effect_for_tree_shaking("new Symbol()"));
    assert!(has_side_effect_for_tree_shaking("new Symbol('string')"));
    assert!(has_side_effect_for_tree_shaking("new Symbol(null)"));
    assert!(has_side_effect_for_tree_shaking("new Symbol(undefined)"));
    assert!(has_side_effect_for_tree_shaking("new Symbol({ toString() { throw new Error() } })"));
    assert!(has_side_effect_for_tree_shaking("let unknownVariable; new Symbol(unknownVariable)"));

    // Symbol() as a function call (without 'new') is side-effect-free with primitives
    assert!(!has_side_effect_for_tree_shaking("Symbol()"));
    assert!(!has_side_effect_for_tree_shaking("Symbol('string')"));
    assert!(!has_side_effect_for_tree_shaking("Symbol(null)"));
    assert!(!has_side_effect_for_tree_shaking("Symbol(undefined)"));
    assert!(!has_side_effect_for_tree_shaking("Symbol(123)"));
    assert!(!has_side_effect_for_tree_shaking("Symbol(true)"));

    // Symbol() with object argument has side effects (could call toString)
    assert!(has_side_effect_for_tree_shaking("Symbol({ toString() { throw new Error() } })"));

    // Symbol() with unknown variable has side effects (could be an object)
    assert!(has_side_effect_for_tree_shaking("let unknownVariable; Symbol(unknownVariable)"));

    // Test fallback logic for global constructors with primitive arguments
    // String, Number, Boolean, Object constructors are side-effect-free with primitives
    assert!(!has_side_effect_for_tree_shaking("new String()"));

    assert!(!has_side_effect_for_tree_shaking("new Number()"));

    assert!(!has_side_effect_for_tree_shaking("new Boolean()"));

    assert!(!has_side_effect_for_tree_shaking("new Object()"));

    assert!(has_side_effect_for_tree_shaking("new BigInt(123)"));
  }

  #[test]
  fn test_primitive_global_function_calls() {
    // String() - side-effect-free with primitive arguments only
    // Object conversion can call valueOf/toString with side effects
    assert!(!has_side_effect_for_tree_shaking("String()"));
    assert!(!has_side_effect_for_tree_shaking("String('hello')"));
    assert!(!has_side_effect_for_tree_shaking("String(123)"));
    assert!(!has_side_effect_for_tree_shaking("String(null)"));
    assert!(!has_side_effect_for_tree_shaking("String(undefined)"));
    assert!(!has_side_effect_for_tree_shaking("String(true)"));

    // String() with any value: Oxc's "coercion methods are pure" assumption
    // treats toString()/valueOf() as side-effect-free. String(Symbol()) is also
    // safe per spec (returns "Symbol()" without throwing).
    assert!(!has_side_effect_for_tree_shaking("String({})"));
    assert!(!has_side_effect_for_tree_shaking("String([1, 2, 3])"));
    assert!(!has_side_effect_for_tree_shaking("let obj; String(obj)"));

    // Number() - side-effect-free with primitive arguments only
    assert!(!has_side_effect_for_tree_shaking("Number()"));
    assert!(!has_side_effect_for_tree_shaking("Number('123')"));
    assert!(!has_side_effect_for_tree_shaking("Number(456)"));
    assert!(!has_side_effect_for_tree_shaking("Number(null)"));
    assert!(!has_side_effect_for_tree_shaking("Number(undefined)"));
    assert!(!has_side_effect_for_tree_shaking("Number(true)"));

    // Number() with object literals: Oxc checks ToPrimitive/ToNumeric.
    // {} has known valueOf/toString, so ToNumeric({}) = NaN (no throw).
    assert!(!has_side_effect_for_tree_shaking("Number({})"));
    assert!(has_side_effect_for_tree_shaking("let val; Number(val)"));

    // Boolean() - always side-effect free (no type conversion needed)
    assert!(!has_side_effect_for_tree_shaking("Boolean()"));
    assert!(!has_side_effect_for_tree_shaking("Boolean(true)"));
    assert!(!has_side_effect_for_tree_shaking("Boolean('text')"));
    assert!(!has_side_effect_for_tree_shaking("Boolean(0)"));
    assert!(!has_side_effect_for_tree_shaking("Boolean(null)"));
    assert!(!has_side_effect_for_tree_shaking("Boolean(undefined)"));

    // Boolean() with any value is side-effect free (just checks truthiness)
    assert!(!has_side_effect_for_tree_shaking("Boolean({})"));
    assert!(!has_side_effect_for_tree_shaking("let val; Boolean(val)"));

    // BigInt() - side-effect-free only with proven-safe arguments
    // BigInt() with no arguments throws TypeError
    assert!(has_side_effect_for_tree_shaking("BigInt()"));
    // Integer literals are safe
    assert!(!has_side_effect_for_tree_shaking("BigInt(123)"));
    assert!(!has_side_effect_for_tree_shaking("BigInt(0)"));
    assert!(!has_side_effect_for_tree_shaking("BigInt(-1)"));
    assert!(!has_side_effect_for_tree_shaking("BigInt(+1)"));
    // Boolean literals are safe
    assert!(!has_side_effect_for_tree_shaking("BigInt(true)"));
    assert!(!has_side_effect_for_tree_shaking("BigInt(false)"));
    // BigInt literals are safe
    assert!(!has_side_effect_for_tree_shaking("BigInt(123n)"));

    // BigInt() with strings: Oxc can statically validate integer strings.
    // BigInt("123") works, BigInt("abc") or BigInt("1.5") throws.
    assert!(!has_side_effect_for_tree_shaking("BigInt('456')"));
    assert!(has_side_effect_for_tree_shaking("BigInt('abc')"));

    // BigInt() with non-integer numbers throws RangeError
    assert!(has_side_effect_for_tree_shaking("BigInt(1.5)"));
    assert!(has_side_effect_for_tree_shaking("BigInt(NaN)"));
    assert!(has_side_effect_for_tree_shaking("BigInt(Infinity)"));
    assert!(has_side_effect_for_tree_shaking("BigInt(-Infinity)"));

    // BigInt() with undefined/null throws TypeError
    assert!(has_side_effect_for_tree_shaking("BigInt(undefined)"));
    assert!(has_side_effect_for_tree_shaking("BigInt(null)"));

    // BigInt() with unknown or object arguments has side effects
    assert!(has_side_effect_for_tree_shaking("let val; BigInt(val)"));
    assert!(has_side_effect_for_tree_shaking("BigInt({})"));

    // BigInt() with spread elements has side effects
    assert!(has_side_effect_for_tree_shaking("let args; BigInt(...args)"));

    // Spread elements should have side effects
    assert!(has_side_effect_for_tree_shaking("let args; String(...args)"));
    assert!(has_side_effect_for_tree_shaking("let args; Number(...args)"));
    assert!(has_side_effect_for_tree_shaking("let args; Boolean(...args)"));
  }

  #[test]
  fn test_regexp_constructor() {
    // RegExp() and new RegExp() with valid patterns/flags are side-effect-free
    // Valid patterns
    assert!(!has_side_effect_for_tree_shaking("RegExp()"));
    assert!(!has_side_effect_for_tree_shaking("new RegExp()"));
    assert!(!has_side_effect_for_tree_shaking("RegExp('abc')"));
    assert!(!has_side_effect_for_tree_shaking("new RegExp('abc')"));
    assert!(!has_side_effect_for_tree_shaking("RegExp('abc', 'g')"));
    assert!(!has_side_effect_for_tree_shaking("new RegExp('abc', 'g')"));
    assert!(!has_side_effect_for_tree_shaking("RegExp('abc', 'gi')"));
    // Flags newer than ES5 (`s`/`u`/`y`) are may-throw without an explicit target;
    // see `test_regexp_constructor_with_engine_targets`.
    assert!(has_side_effect_for_tree_shaking("new RegExp('abc', 'gimsuy')"));
    // RegExp with a RegExp literal argument is valid
    assert!(!has_side_effect_for_tree_shaking("RegExp(/foo/)"));
    assert!(!has_side_effect_for_tree_shaking("new RegExp(/foo/)"));

    // Invalid patterns throw SyntaxError - these have side effects
    assert!(has_side_effect_for_tree_shaking("RegExp('[')"));
    assert!(has_side_effect_for_tree_shaking("new RegExp('[')"));
    assert!(has_side_effect_for_tree_shaking("RegExp('\\\\')"));
    assert!(has_side_effect_for_tree_shaking("new RegExp('\\\\')"));

    // Invalid flags throw SyntaxError - these have side effects
    assert!(has_side_effect_for_tree_shaking("RegExp('a', 'xyz')"));
    assert!(has_side_effect_for_tree_shaking("new RegExp('a', 'xyz')"));
    assert!(has_side_effect_for_tree_shaking("RegExp('a', 'gg')"));
    assert!(has_side_effect_for_tree_shaking("new RegExp('a', 'gg')"));

    // Non-literal arguments have side effects (can't statically validate)
    assert!(has_side_effect_for_tree_shaking("let p; RegExp(p)"));
    assert!(has_side_effect_for_tree_shaking("let p; new RegExp(p)"));
    assert!(has_side_effect_for_tree_shaking("let f; RegExp('a', f)"));
    assert!(has_side_effect_for_tree_shaking("let f; new RegExp('a', f)"));

    // RegExp literals are side-effect-free (they're validated at parse time)
    assert!(!has_side_effect_for_tree_shaking("/abc/"));
    assert!(!has_side_effect_for_tree_shaking("/abc/g"));
  }

  #[test]
  fn test_regexp_constructor_with_engine_targets() {
    // Without an explicit target, runtime support for post-ES5 RegExp features is
    // unknown: constructor calls using them are commonly feature-detection probes
    // that throw on unsupporting engines, so they must stay in the output
    // (https://github.com/oxc-project/oxc/issues/18050).
    assert!(has_side_effect_for_tree_shaking("new RegExp('abc', 'gimsuy')"));
    // An explicit target new enough for every used feature opts into
    // feature-aware analysis (`s` is ES2018; `u`/`y` are ES2015).
    assert!(!has_side_effect_for_tree_shaking_with_target("new RegExp('abc', 'gimsuy')", "es2018"));
    // A target older than a used feature stays conservative.
    assert!(has_side_effect_for_tree_shaking_with_target("new RegExp('abc', 'gimsuy')", "es2015"));
  }

  #[test]
  fn test_side_effects_of_global_variable_access() {
    assert!(!has_side_effect_for_tree_shaking("let a = undefined"));
    assert!(!has_side_effect_for_tree_shaking("let a = void 0"));
    assert!(!has_side_effect_for_tree_shaking("using undef_remove = void 0;"));
    assert!(has_side_effect_for_tree_shaking("using undef_keep = void test();"));
    assert!(!has_side_effect_for_tree_shaking("let a = NaN"));
    assert!(!has_side_effect_for_tree_shaking("let a = String"));
    assert!(!has_side_effect_for_tree_shaking("let a = Object.assign"));
    assert!(!has_side_effect_for_tree_shaking("let a = Object.prototype.propertyIsEnumerable"));
    assert!(!has_side_effect_for_tree_shaking("let a = Symbol.asyncDispose"));
    assert!(!has_side_effect_for_tree_shaking("let a = Math.E"));
    assert!(!has_side_effect_for_tree_shaking("let a = Reflect.apply"));
    assert!(!has_side_effect_for_tree_shaking("let a = JSON.stringify"));
    assert!(!has_side_effect_for_tree_shaking("let a = Proxy"));

    assert_eq!(
      get_stmt_eval_flags("let a = Proxy; let a = JSON.stringify"),
      vec![StmtEvalFlags::empty(), StmtEvalFlags::empty()]
    );
    assert_eq!(
      get_stmt_order_sensitivity("let a = Proxy; let a = JSON.stringify"),
      vec![true, true]
    );
    // should have side effects other global member expr access
    assert!(has_side_effect_for_tree_shaking("let a = Object.test"));
    assert!(has_side_effect_for_tree_shaking("let a = Object.prototype.two"));
    assert!(has_side_effect_for_tree_shaking("let a = Reflect.something"));

    assert_eq!(
      get_stmt_eval_flags("let a = Reflect.something"),
      vec![StmtEvalFlags::UnknownSideEffect]
    );
    assert_eq!(get_stmt_order_sensitivity("let a = Reflect.something"), vec![true]);

    // sideEffectful Global variable access with pure annotation
    assert_eq!(
      get_stmt_eval_flags("let a = /*@__PURE__ */ Reflect.something()"),
      vec![StmtEvalFlags::empty()]
    );
    assert_eq!(
      get_stmt_order_sensitivity("let a = /*@__PURE__ */ Reflect.something()"),
      vec![true]
    );
  }

  #[test]
  fn test_object_expression() {
    assert!(!has_side_effect_for_tree_shaking("const of = { [1]: 'hi'}"));
    assert!(!has_side_effect_for_tree_shaking("const of = { [-1]: 'hi'}"));
    assert!(!has_side_effect_for_tree_shaking("const of = { [+1]: 'hi'}"));
    assert!(!has_side_effect_for_tree_shaking("let remove = { [void 0]: 'x' };"));
    assert!(has_side_effect_for_tree_shaking("let keep = { [void test()]: 'x' };"));
    // Oxc is more permissive about computed property keys (ignores ToPrimitive side effects).
    // `{}` has a known toString(), so Oxc considers this side-effect-free.
    assert!(!has_side_effect_for_tree_shaking("const of = { [{}]: 'hi'}"));
  }

  // https://github.com/rolldown/rolldown/issues/9425
  // PureAnnotation / GlobalVarAccess on a nested call must propagate up through
  // transparent compound expressions (Object, Array, Sequence, Conditional,
  // Logical, Binary, Unary, Template, TaggedTemplate, TS wrappers). Otherwise
  // a module whose only "side effect" is a pure-annotated IIFE buried inside
  // `export default { ... }` is never marked ExecutionOrderSensitive and the
  // bundler emits its var-init at top level, before sibling modules that the
  // IIFE depends on (regression after oxc 0.131 stopped inlining pure IIFEs
  // in DCE mode).
  #[test]
  fn test_pure_annotation_propagates_through_compound_expr() {
    assert_eq!(
      get_stmt_eval_flags("export default { foo: /* @__PURE__ */ (() => globalValue)() }"),
      vec![StmtEvalFlags::empty()]
    );
    assert_eq!(
      get_stmt_order_sensitivity("export default { foo: /* @__PURE__ */ (() => globalValue)() }"),
      vec![true]
    );
    assert_eq!(
      get_stmt_eval_flags("export default [/* @__PURE__ */ (() => globalValue)()]"),
      vec![StmtEvalFlags::empty()]
    );
    assert_eq!(
      get_stmt_order_sensitivity("export default [/* @__PURE__ */ (() => globalValue)()]"),
      vec![true]
    );
    assert_eq!(
      get_stmt_eval_flags("export default (0, /* @__PURE__ */ (() => globalValue)())"),
      vec![StmtEvalFlags::empty()]
    );
    assert_eq!(
      get_stmt_order_sensitivity("export default (0, /* @__PURE__ */ (() => globalValue)())"),
      vec![true]
    );
    assert_eq!(
      get_stmt_eval_flags("export default true ? /* @__PURE__ */ (() => globalValue)() : null"),
      vec![StmtEvalFlags::empty()]
    );
    assert_eq!(
      get_stmt_order_sensitivity(
        "export default true ? /* @__PURE__ */ (() => globalValue)() : null"
      ),
      vec![true]
    );
    assert_eq!(
      get_stmt_eval_flags("export default true && /* @__PURE__ */ (() => globalValue)()"),
      vec![StmtEvalFlags::empty()]
    );
    assert_eq!(
      get_stmt_order_sensitivity("export default true && /* @__PURE__ */ (() => globalValue)()"),
      vec![true]
    );
    // BinaryExpression `===` does not ToPrimitive-coerce, so oxc returns
    // no own side effect and the order-sensitive reason can propagate.
    assert_eq!(
      get_stmt_eval_flags("export default /* @__PURE__ */ (() => 2)() === 1"),
      vec![StmtEvalFlags::empty()]
    );
    assert_eq!(
      get_stmt_order_sensitivity("export default /* @__PURE__ */ (() => 2)() === 1"),
      vec![true]
    );
    // `typeof` never has side effects per spec.
    assert_eq!(
      get_stmt_eval_flags("export default typeof /* @__PURE__ */ (() => true)()"),
      vec![StmtEvalFlags::empty()]
    );
    assert_eq!(
      get_stmt_order_sensitivity("export default typeof /* @__PURE__ */ (() => true)()"),
      vec![true]
    );
    // Computed key with a pure-annotated call must propagate too.
    assert_eq!(
      get_stmt_eval_flags("export default { [/* @__PURE__ */ (() => 'k')()]: 1 }"),
      vec![StmtEvalFlags::empty()]
    );
    assert_eq!(
      get_stmt_order_sensitivity("export default { [/* @__PURE__ */ (() => 'k')()]: 1 }"),
      vec![true]
    );
    // GlobalVarAccess on a bare member-expr buried in a compound wrapper
    // must also propagate (same mechanism, different flag).
    assert_eq!(get_stmt_eval_flags("let a = { x: Proxy }"), vec![StmtEvalFlags::empty()]);
    assert_eq!(get_stmt_order_sensitivity("let a = { x: Proxy }"), vec![true]);
    assert_eq!(get_stmt_eval_flags("let a = [JSON.stringify]"), vec![StmtEvalFlags::empty()]);
    assert_eq!(get_stmt_order_sensitivity("let a = [JSON.stringify]"), vec![true]);
    // Nested compound: array inside object inside object — propagation must
    // walk through every layer.
    assert_eq!(
      get_stmt_eval_flags("export default { a: { b: [/* @__PURE__ */ (() => globalValue)()] } }"),
      vec![StmtEvalFlags::empty()]
    );
    assert_eq!(
      get_stmt_order_sensitivity(
        "export default { a: { b: [/* @__PURE__ */ (() => globalValue)()] } }"
      ),
      vec![true]
    );
    // TS wrapper passthroughs (`SourceType::tsx()` in test helper).
    assert_eq!(
      get_stmt_eval_flags("export default (/* @__PURE__ */ (() => globalValue)() as string)"),
      vec![StmtEvalFlags::empty()]
    );
    assert_eq!(
      get_stmt_order_sensitivity(
        "export default (/* @__PURE__ */ (() => globalValue)() as string)"
      ),
      vec![true]
    );
    assert_eq!(
      get_stmt_eval_flags(
        "export default (/* @__PURE__ */ (() => globalValue)() satisfies string)"
      ),
      vec![StmtEvalFlags::empty()]
    );
    assert_eq!(
      get_stmt_order_sensitivity(
        "export default (/* @__PURE__ */ (() => globalValue)() satisfies string)"
      ),
      vec![true]
    );
    assert_eq!(
      get_stmt_eval_flags("export default /* @__PURE__ */ (() => globalValue)()!"),
      vec![StmtEvalFlags::empty()]
    );
    assert_eq!(
      get_stmt_order_sensitivity("export default /* @__PURE__ */ (() => globalValue)()!"),
      vec![true]
    );
    // TSInstantiationExpression `f<T>` — must be peeled like the other TS
    // wrappers. (`<T>x` TSTypeAssertion is ambiguous with JSX under tsx()
    // and can't be expressed in this harness; `get_inner_expression()`
    // peels it identically in non-tsx contexts.)
    assert_eq!(
      get_stmt_eval_flags("export default /* @__PURE__ */ ((() => globalValue) as any)<string>()"),
      vec![StmtEvalFlags::empty()]
    );
    assert_eq!(
      get_stmt_order_sensitivity(
        "export default /* @__PURE__ */ ((() => globalValue) as any)<string>()"
      ),
      vec![true]
    );
  }

  // Function bodies are not evaluated at the statement level — a pure
  // annotation inside an arrow/function body must NOT propagate up.
  #[test]
  fn test_pure_annotation_not_propagated_through_function_body() {
    assert_eq!(
      get_stmt_eval_flags("export default () => /* @__PURE__ */ pureCall()"),
      vec![StmtEvalFlags::empty()]
    );
    assert_eq!(
      get_stmt_order_sensitivity("export default () => /* @__PURE__ */ pureCall()"),
      vec![false]
    );
    assert_eq!(
      get_stmt_eval_flags("export default { foo: () => /* @__PURE__ */ pureCall() }"),
      vec![StmtEvalFlags::empty()]
    );
    assert_eq!(
      get_stmt_order_sensitivity("export default { foo: () => /* @__PURE__ */ pureCall() }"),
      vec![false]
    );
  }

  // A real side effect anywhere in a compound expression must surface as
  // Unknown — the order-sensitive reason propagation arms must not weaken this.
  #[test]
  fn test_compound_expr_side_effectful_operand_still_unknown() {
    assert!(has_side_effect_for_tree_shaking("let a = { foo: globalCall() }"));
    assert!(has_side_effect_for_tree_shaking("let a = [globalCall()]"));
    assert!(has_side_effect_for_tree_shaking("let a = (globalCall(), 1)"));
    assert!(has_side_effect_for_tree_shaking("let a = true ? globalCall() : null"));
  }

  // Strict on-demand order analysis needs a complete walk of the expressions that execute while a
  // top-level statement is evaluated. Each case below is one witness for one collector branch or
  // one regular-analyzer certification route that hides an eager read; the full syntax matrix
  // (60 forms) is maintained by the external order-fuzzer release gate, which deliberately keeps
  // syntax spellings that exercise an already-witnessed branch out of maintained suites.
  #[test]
  fn test_top_level_eager_order_reasons_cover_iife_and_member_wrappers() {
    let options = strict_on_demand_options(InnerOptions::default());
    for code in [
      // Arrow-callee arm of `visit_immediately_invoked_function`.
      "const value = (() => (/* @__PURE__ */ globalThis.__orderRead?.() ?? 5))();",
      // Function-expression arm, block body.
      "const value = (function () { return (/* @__PURE__ */ globalThis.__orderRead?.() ?? 5); })();",
      // Formal-parameter walk of a directly invoked function.
      "const value = ((unused) => (/* @__PURE__ */ globalThis.__orderRead?.() ?? 5))(0);",
      // Class-definition walk reached from inside an eagerly evaluated body.
      "const value = (() => class { static value = (/* @__PURE__ */ globalThis.__orderRead?.() ?? 5); })();",
    ] {
      assert_eager_reason_only(code, &options, StmtEvalFlags::empty());
    }

    let property_read_options = strict_on_demand_options(InnerOptions {
      property_read_side_effects: Some(PropertyReadSideEffects::False),
      ..InnerOptions::default()
    });
    for code in [
      // Member child hidden by the `propertyReadSideEffects: false` certification: array element,
      // object property value, computed member key, and computed data-property key.
      "const value = [(/* @__PURE__ */ globalThis.__orderRead?.() ?? 5)][0];",
      "const value = ({ value: (/* @__PURE__ */ globalThis.__orderRead?.() ?? 5) }).value;",
      "const value = ({ 5: 5, 9: 9 })[(/* @__PURE__ */ globalThis.__orderRead?.() ?? 5)];",
      "const value = ({ [(/* @__PURE__ */ globalThis.__orderRead?.() ?? 5)]: 9 })[9] ?? 5;",
      // Pure-annotated call whose result is consumed through a member wrapper.
      "const value = (/* @__PURE__ */ make()).value;",
    ] {
      assert_eager_reason_only(code, &property_read_options, StmtEvalFlags::empty());
    }
  }

  #[test]
  fn test_top_level_eager_order_reasons_cover_bindings_assignments_and_pure_cjs_rhs() {
    let property_read_options = strict_on_demand_options(InnerOptions {
      property_read_side_effects: Some(PropertyReadSideEffects::False),
      ..InnerOptions::default()
    });
    for code in [
      "const { value = (/* @__PURE__ */ globalThis.__orderRead?.() ?? 5) } = {};",
      "const { [(/* @__PURE__ */ globalThis.__orderRead?.() ?? 5)]: value } = { 5: 5 };",
    ] {
      assert_eager_reason_only(code, &property_read_options, StmtEvalFlags::empty());
    }

    let property_write_options = strict_on_demand_options(InnerOptions {
      property_write_side_effects: Some(PropertyWriteSideEffects::False),
      ..InnerOptions::default()
    });
    assert_eager_reason_only(
      "const value = (({}).value = (/* @__PURE__ */ globalThis.__orderRead?.() ?? 5));",
      &property_write_options,
      StmtEvalFlags::empty(),
    );

    let pure_cjs_options = strict_on_demand_options(InnerOptions {
      unknown_global_side_effects: Some(false),
      property_write_side_effects: Some(PropertyWriteSideEffects::False),
      ..InnerOptions::default()
    });
    assert_eager_reason_only(
      "exports.value = [(/* @__PURE__ */ globalThis.__orderRead?.() ?? 5)][0];",
      &pure_cjs_options,
      StmtEvalFlags::PureCjs,
    );
  }

  #[test]
  fn test_top_level_eager_order_reasons_cover_manual_pure_call_new_and_tagged_template() {
    let make_options = strict_on_demand_options(InnerOptions {
      manual_pure_functions: Some(std::iter::once("make".to_string()).collect()),
      ..InnerOptions::default()
    });
    assert_last_statement_gets_eager_reason_only(
      "function make() { return { value: (/* @__PURE__ */ globalThis.__orderRead?.() ?? 5) }; } const value = make().value;",
      &make_options,
      StmtEvalFlags::empty(),
    );
    assert_eager_reason_only("const value = make`value`;", &make_options, StmtEvalFlags::empty());

    let box_options = strict_on_demand_options(InnerOptions {
      manual_pure_functions: Some(std::iter::once("Box".to_string()).collect()),
      ..InnerOptions::default()
    });
    assert_last_statement_gets_eager_reason_only(
      "class Box { value = (/* @__PURE__ */ globalThis.__orderRead?.() ?? 5); } const value = new Box();",
      &box_options,
      StmtEvalFlags::empty(),
    );
  }

  #[test]
  fn test_manual_pure_chains_keep_eager_child_side_effects() {
    let options = Arc::new(NormalizedBundlerOptions {
      treeshake: InnerOptions {
        manual_pure_functions: Some(std::iter::once("make".to_string()).collect()),
        ..InnerOptions::default()
      }
      .into(),
      ..NormalizedBundlerOptions::default()
    });
    for code in [
      "make()[effect()];",
      "make(effect()).value;",
      "new (make()[effect()].Box)();",
      "make(effect());",
    ] {
      assert_eq!(
        get_stmt_eval_with_options(code, &options),
        vec![(StmtEvalFlags::UnknownSideEffect, true)],
        "{code}"
      );
    }
  }

  #[test]
  fn test_manual_pure_chains_drop_side_effect_free_spreads() {
    let options = Arc::new(NormalizedBundlerOptions {
      treeshake: InnerOptions {
        manual_pure_functions: Some(std::iter::once("make".to_string()).collect()),
        ..InnerOptions::default()
      }
      .into(),
      ..NormalizedBundlerOptions::default()
    });
    // Spreading an array/string/template literal iterates only built-in iterators, so a matched
    // manual-pure chain wrapping one stays removable (Rollup drops these too).
    for code in [
      "make(...[]).value;",
      "make(...'').value;",
      "make(...`literal`).value;",
      "make(...[1, 2]).value;",
    ] {
      assert_eq!(
        get_stmt_eval_with_options(code, &options),
        vec![(StmtEvalFlags::empty(), false)],
        "{code}"
      );
    }
    // The call-position form is likewise side-effect-free; reading the unresolved `make` global
    // only makes it order-sensitive.
    assert_eq!(
      get_stmt_eval_with_options("make(...[])();", &options),
      vec![(StmtEvalFlags::empty(), true)],
      "make(...[])();"
    );
    // A side-effectful spread element, or a non-literal (possibly user-iterable) operand, keeps the
    // statement — evaluating or iterating the operand may run arbitrary code.
    for code in [
      "make(...[effect()]).value;",
      "make(...effect()).value;",
      "make(...spreadable).value;",
      "make(...[...spreadable]).value;",
    ] {
      assert_eq!(
        get_stmt_eval_with_options(code, &options),
        vec![(StmtEvalFlags::UnknownSideEffect, true)],
        "{code}"
      );
    }
  }

  #[test]
  fn test_manual_pure_chains_without_eager_children_are_side_effect_free() {
    let options = Arc::new(NormalizedBundlerOptions {
      treeshake: InnerOptions {
        manual_pure_functions: Some(std::iter::once("make".to_string()).collect()),
        ..InnerOptions::default()
      }
      .into(),
      ..NormalizedBundlerOptions::default()
    });
    // A manual-pure root with no eagerly-evaluated child is side-effect-free (removable), across
    // bare calls, member reads, repeated/optional/chained calls, and tagged templates. `make` is
    // declared so it resolves locally and its read contributes no global-access order reason.
    for code in [
      "function make() {} make();",
      "function make() {} make.div;",
      "function make() {} make.div`x`;",
      "function make() {} make?.div();",
      "function make() {} make()();",
      "function make() {} make().div();",
    ] {
      assert_eq!(
        get_stmt_eval_with_options(code, &options).last(),
        Some(&(StmtEvalFlags::empty(), false)),
        "{code}"
      );
    }
    // Scoping: `manualPureFunctions` only touches listed names, so a call to an unlisted function
    // keeps its side effects.
    assert_eq!(
      get_stmt_eval_with_options("other();", &options).first().map(|(flags, _)| *flags),
      Some(StmtEvalFlags::UnknownSideEffect),
      "unlisted call must not be treated as pure"
    );
  }

  #[test]
  fn test_conditional_and_logical_iife_callees_behind_manual_pure_member() {
    // A bare conditional/logical-callee IIFE needs no collector arm: oxc's IIFE certification
    // recognizes only direct function/arrow callees, so the statement keeps `UnknownSideEffect`
    // and is order-sensitive through the regular analyzer alone.
    let options = strict_on_demand_options(InnerOptions::default());
    let direct_spelling =
      "const value = (true && (() => (/* @__PURE__ */ globalThis.__orderRead?.() ?? 5)))();";
    assert_eq!(
      get_stmt_eval_with_options(direct_spelling, &options),
      vec![(StmtEvalFlags::UnknownSideEffect, true)]
    );
    assert_eq!(
      get_stmt_eval_with_top_level_eager_order_reasons(direct_spelling, &options),
      vec![(StmtEvalFlags::UnknownSideEffect, true)]
    );

    // Computed-key indirect IIFEs stay conservative under both analysis paths.
    let make_options = strict_on_demand_options(InnerOptions {
      manual_pure_functions: Some(std::iter::once("make".to_string()).collect()),
      ..InnerOptions::default()
    });
    for code in [
      "function make() {} const value = make[(true ? (() => (/* @__PURE__ */ globalThis.__orderRead?.() ?? 5)) : (() => 9))()];",
      "function make() {} const value = make[(true && (() => (/* @__PURE__ */ globalThis.__orderRead?.() ?? 5)))()];",
    ] {
      let regular = get_stmt_eval_with_options(code, &make_options);
      assert_eq!(regular.last(), Some(&(StmtEvalFlags::UnknownSideEffect, true)), "{code}");
      assert_eq!(
        get_stmt_eval_with_top_level_eager_order_reasons(code, &make_options),
        regular,
        "{code}"
      );
    }
  }

  // The same manual-pure member-root route, for the remaining eager-execution forms.
  #[test]
  fn test_eager_walk_covers_constructed_classes_literal_tags_and_assignment_callees() {
    let make_options = strict_on_demand_options(InnerOptions {
      manual_pure_functions: Some(std::iter::once("make".to_string()).collect()),
      ..InnerOptions::default()
    });
    for code in [
      // Instance field initializer runs at construction.
      "function make() {} const value = make[new class { k = (/* @__PURE__ */ globalThis.__orderRead?.() ?? 5); }().k];",
      // Constructor body runs at construction.
      "function make() {} const value = make[new class { constructor() { this.k = (/* @__PURE__ */ globalThis.__orderRead?.() ?? 5); } }().k];",
      // Constructor parameter defaults run at construction.
      "function make() {} const value = make[new class { constructor(k = (/* @__PURE__ */ globalThis.__orderRead?.() ?? 5)) { this.k = k; } }().k];",
      // A conditional callee recurses into the constructed class through the existing arms.
      "function make() {} const value = make[new (true ? class { k = (/* @__PURE__ */ globalThis.__orderRead?.() ?? 5); } : class {})().k];",
      // A literal tag is called when the template evaluates.
      "function make() {} const value = make[((s) => (/* @__PURE__ */ globalThis.__orderRead?.() ?? 5))`x`];",
      // An assignment-expression callee invokes its RHS.
      "function make() {} let assigned; const value = make[(assigned = () => (/* @__PURE__ */ globalThis.__orderRead?.() ?? 5))()];",
      // Logical assignments are `AssignmentExpression`s, not `LogicalExpression`s.
      "function make() {} let assigned; const value = make[(assigned ??= () => (/* @__PURE__ */ globalThis.__orderRead?.() ?? 5))()];",
    ] {
      let regular = get_stmt_eval_with_options(code, &make_options);
      assert_eq!(regular.last(), Some(&(StmtEvalFlags::UnknownSideEffect, true)), "{code}");
      assert_eq!(
        get_stmt_eval_with_top_level_eager_order_reasons(code, &make_options),
        regular,
        "{code}"
      );
    }
  }

  #[test]
  fn test_extended_top_level_reasons_do_not_leak_to_the_non_strict_default() {
    let manual_pure_tag = "function tag() { return (/* @__PURE__ */ globalThis.__orderRead?.() ?? 5); } class C { static value = tag``; }";
    let manual_pure_treeshake = || InnerOptions {
      manual_pure_functions: Some(std::iter::once("tag".to_string()).collect()),
      ..InnerOptions::default()
    };

    let default_options = Arc::new(NormalizedBundlerOptions {
      treeshake: manual_pure_treeshake().into(),
      ..NormalizedBundlerOptions::default()
    });
    let wrap_all_options = Arc::new(NormalizedBundlerOptions {
      treeshake: manual_pure_treeshake().into(),
      strict_execution_order: true,
      ..NormalizedBundlerOptions::default()
    });
    assert_eq!(
      get_stmt_eval_with_top_level_eager_order_reasons(manual_pure_tag, &default_options),
      vec![(StmtEvalFlags::empty(), false), (StmtEvalFlags::empty(), false)]
    );

    // Both strict plans read the same signal, so both collect the same reasons.
    let strict_on_demand = strict_on_demand_options(manual_pure_treeshake());
    for options in [&wrap_all_options, &strict_on_demand] {
      assert_last_statement_gets_eager_reason_only(
        manual_pure_tag,
        options,
        StmtEvalFlags::empty(),
      );
    }
  }

  #[test]
  fn test_top_level_eager_order_reason_walk_keeps_deferred_boundaries() {
    let options = strict_on_demand_options(InnerOptions::default());
    for code in [
      "const deferred = () => (/* @__PURE__ */ globalThis.__orderRead?.() ?? 5);",
      "function deferred() { return (/* @__PURE__ */ globalThis.__orderRead?.() ?? 5); }",
      "class Deferred { value = (/* @__PURE__ */ globalThis.__orderRead?.() ?? 5); }",
      "class Deferred { method() { return (/* @__PURE__ */ globalThis.__orderRead?.() ?? 5); } }",
    ] {
      assert_eq!(
        get_stmt_eval_with_top_level_eager_order_reasons(code, &options),
        vec![(StmtEvalFlags::empty(), false)],
        "{code}"
      );
    }

    // `propertyReadSideEffects: false` promises that property reads run no observable user code,
    // so a getter body invoked through a certified read stays invisible here, exactly as it does
    // for `TopLevelImportReadDetector`. This is the option's documented contract, not a gap.
    let property_read_options = strict_on_demand_options(InnerOptions {
      property_read_side_effects: Some(PropertyReadSideEffects::False),
      ..InnerOptions::default()
    });
    assert_eq!(
      get_stmt_eval_with_top_level_eager_order_reasons(
        "const value = ({ get value() { return (/* @__PURE__ */ globalThis.__orderRead?.() ?? 5); } }).value;",
        &property_read_options,
      ),
      vec![(StmtEvalFlags::empty(), false)],
    );
  }

  #[test]
  fn test_cjs_pattern() {
    assert_eq!(
      get_stmt_eval_flags("Object.defineProperty(exports, \"__esModule\", { value: true })"),
      vec![StmtEvalFlags::UnknownSideEffect]
    );

    assert_eq!(
      get_stmt_eval_flags(
        r"
      exports.a = function test() {};
      exports['b'] = function () {
        console.log('b')
      };
      "
      ),
      vec![StmtEvalFlags::PureCjs, StmtEvalFlags::PureCjs]
    );

    assert_eq!(
      get_stmt_eval_flags("exports.a = global()"),
      vec![StmtEvalFlags::UnknownSideEffect | StmtEvalFlags::PureCjs]
    );

    assert_eq!(
      get_stmt_eval_flags("exports[test()] = true"),
      vec![StmtEvalFlags::UnknownSideEffect]
    );

    assert_eq!(
      get_stmt_eval_flags(
        r"
      let a = {};
      Object.defineProperty(a, '__esModule', { value: true });
      "
      ),
      vec![StmtEvalFlags::empty(), StmtEvalFlags::UnknownSideEffect]
    );
  }

  #[test]
  fn test_class_expr() {
    assert!(!has_side_effect_for_tree_shaking(
      r"
let remove14 = class {
	static [undefined] = 'x';
}

let remove15 = class {
	static [void 0] = 'x';
}

let remove15 = class {
	[void 0] = 'x';
}
    "
    ));
  }

  #[test]
  fn test_class_decorators() {
    assert!(has_side_effect_for_tree_shaking("function fn() {} @fn class Class {}"));
    assert!(has_side_effect_for_tree_shaking("function fn() {} var MyClass = @fn class {}"));
    assert!(has_side_effect_for_tree_shaking("function fn() {} class MyClass { @fn accessor x }"));
    assert!(has_side_effect_for_tree_shaking(
      "function fn() {} class MyClass { @fn static accessor x }"
    ));
    assert!(has_side_effect_for_tree_shaking("function fn() {} class MyClass { @fn method() {} }"));
    assert!(has_side_effect_for_tree_shaking("function fn() {} class MyClass { @fn field }"));
  }

  // #10104 follow-up: a class's definition-time-evaluated positions (heritage, computed keys,
  // static field/accessor initializers, static blocks, decorators) that read a whitelisted global
  // or carry a pure annotation make the class order-sensitive — the same treatment
  // `var x = Math.max(1, 2)` already gets. The three oxc-delegate arms (class declaration, class
  // expression, `export default class`) used to drop those reasons. The tree-shaking channel is
  // untouched: every side-effect-free class here keeps `StmtEvalFlags::empty()`.
  #[test]
  fn test_class_definition_time_order_sensitivity() {
    // Static field initializer reading a whitelisted global -> order-sensitive, and NOT a
    // tree-shaking side effect (so only the order-sensitive channel grew).
    assert_eq!(get_stmt_order_sensitivity("class C { static x = Math.max(1, 2) }"), vec![true]);
    assert_eq!(
      get_stmt_eval_flags("class C { static x = Math.max(1, 2) }"),
      vec![StmtEvalFlags::empty()]
    );
    // Static field initializer with a pure annotation (mirrors the object-literal case above).
    assert_eq!(
      get_stmt_order_sensitivity("class C { static x = /* @__PURE__ */ (() => globalValue)() }"),
      vec![true]
    );
    assert_eq!(
      get_stmt_eval_flags("class C { static x = /* @__PURE__ */ (() => globalValue)() }"),
      vec![StmtEvalFlags::empty()]
    );
    // Heritage (extends) reading a whitelisted global.
    assert_eq!(get_stmt_order_sensitivity("class C extends Object {}"), vec![true]);
    assert_eq!(get_stmt_eval_flags("class C extends Object {}"), vec![StmtEvalFlags::empty()]);
    // Computed key evaluating a global read.
    assert_eq!(get_stmt_order_sensitivity("class C { [Math.max(1, 2)]() {} }"), vec![true]);
    assert_eq!(
      get_stmt_eval_flags("class C { [Math.max(1, 2)]() {} }"),
      vec![StmtEvalFlags::empty()]
    );
    // Static block reading a global.
    assert_eq!(get_stmt_order_sensitivity("class C { static { Math.max(1, 2) } }"), vec![true]);
    // Class expression and `export default class` route through the same machinery.
    assert_eq!(
      get_stmt_order_sensitivity("const C = class { static x = Math.max(1, 2) }"),
      vec![true]
    );
    assert_eq!(
      get_stmt_order_sensitivity("export default class { static x = Math.max(1, 2) }"),
      vec![true]
    );
    assert_eq!(
      get_stmt_eval_flags("export default class { static x = Math.max(1, 2) }"),
      vec![StmtEvalFlags::empty()]
    );
  }

  // Positions that run at construction/call time — not class definition time — stay
  // order-insensitive, so on-demand wrapping is not needlessly triggered.
  #[test]
  fn test_class_non_definition_time_stays_order_insensitive() {
    assert_eq!(get_stmt_order_sensitivity("class C {}"), vec![false]);
    // Instance (non-static) field initializer runs in the constructor.
    assert_eq!(get_stmt_order_sensitivity("class C { x = Math.max(1, 2) }"), vec![false]);
    assert_eq!(get_stmt_eval_flags("class C { x = Math.max(1, 2) }"), vec![StmtEvalFlags::empty()]);
    assert_eq!(get_stmt_order_sensitivity("const C = class { x = Math.max(1, 2) }"), vec![false]);
    assert_eq!(
      get_stmt_order_sensitivity("export default class { x = Math.max(1, 2) }"),
      vec![false]
    );
    // Method body runs when invoked, not at definition time.
    assert_eq!(
      get_stmt_order_sensitivity("class C { m() { return Math.max(1, 2) } }"),
      vec![false]
    );
  }

  // The whole-class Oxc gate owns tree-shaking flags. The separate definition-time walk must
  // collect every order-sensitive reason without being stopped by a nested tree-shaking flag, and
  // must not turn a tree-shaking-only flag into an order-sensitive reason.
  #[test]
  fn test_class_definition_time_reason_walk_is_independent_of_tree_shaking() {
    let cjs_options = NormalizedBundlerOptions {
      treeshake: InnerOptions {
        unknown_global_side_effects: Some(false),
        property_write_side_effects: Some(PropertyWriteSideEffects::False),
        ..InnerOptions::default()
      }
      .into(),
      ..NormalizedBundlerOptions::default()
    };
    let cjs_options = Arc::new(cjs_options);
    for (code, expected_order_sensitive) in [
      ("export class C { static x = [exports.a = 1] }", false),
      ("export class C { static x = [exports.a = 1, Math.max(1, 2)] }", true),
      ("export class C { static x = [exports.a = 1, /* @__PURE__ */ (() => 1)()] }", true),
      ("export class C { static x = [Math.max(1, 2), exports.a = 1] }", true),
      ("export class C { static { { exports.a = 1; Math.max(1, 2) } } }", true),
      ("export class C { static { const x = 1; Math.max(x, 2) } }", true),
      ("export class C { static x = (({}).x = Math.max(1, 2)) }", true),
    ] {
      assert_eq!(
        get_stmt_eval_with_options(code, &cjs_options),
        vec![(StmtEvalFlags::empty(), expected_order_sensitive)],
        "{code}"
      );
    }

    let property_read_options = NormalizedBundlerOptions {
      treeshake: InnerOptions {
        property_read_side_effects: Some(PropertyReadSideEffects::False),
        ..InnerOptions::default()
      }
      .into(),
      ..NormalizedBundlerOptions::default()
    };
    let property_read_options = Arc::new(property_read_options);
    for (code, expected_order_sensitive) in [
      ("class C { static { const [x = 1] = [] } }", false),
      ("class C { static { const [x = Math.max(1, 2)] = [] } }", true),
      ("class C { static x = ({})[Math.max(1, 2)] }", true),
    ] {
      assert_eq!(
        get_stmt_eval_with_options(code, &property_read_options),
        vec![(StmtEvalFlags::empty(), expected_order_sensitive)],
        "{code}"
      );
    }

    assert_eq!(
      get_stmt_eval_with_options(
        "class C { static x = (() => Math.max(1, 2))() }",
        &Arc::new(NormalizedBundlerOptions::default()),
      ),
      vec![(StmtEvalFlags::empty(), true)]
    );
    assert_eq!(
      get_stmt_eval_with_options(
        "class C { static x = () => Math.max(1, 2) }",
        &Arc::new(NormalizedBundlerOptions::default()),
      ),
      vec![(StmtEvalFlags::empty(), false)]
    );
  }

  #[test]
  fn test_chain_root_ident() {
    assert_eq!(chain_root_ident_helper("a.b"), "a");
    assert_eq!(chain_root_ident_helper("styled?.div()"), "styled");
    assert_eq!(chain_root_ident_helper("styled()"), "styled");
    assert_eq!(chain_root_ident_helper("styled().div"), "styled");
    assert_eq!(chain_root_ident_helper("styled()()"), "styled");
  }

  fn chain_root_ident_helper(code: &str) -> String {
    let allocator = oxc::allocator::Allocator::default();
    let parser = Parser::new(&allocator, code, SourceType::ts());
    let expr = parser.parse_expression().unwrap();
    super::chain_root_ident(&expr).unwrap().to_string()
  }
}