JavascriptParser.js
130.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { Parser: AcornParser } = require("acorn");
const { importAssertions } = require("acorn-import-assertions");
const { SyncBailHook, HookMap } = require("tapable");
const vm = require("vm");
const Parser = require("../Parser");
const StackedMap = require("../util/StackedMap");
const binarySearchBounds = require("../util/binarySearchBounds");
const memoize = require("../util/memoize");
const BasicEvaluatedExpression = require("./BasicEvaluatedExpression");
/** @typedef {import("acorn").Options} AcornOptions */
/** @typedef {import("estree").AssignmentExpression} AssignmentExpression */
/** @typedef {import("estree").BinaryExpression} BinaryExpression */
/** @typedef {import("estree").BlockStatement} BlockStatement */
/** @typedef {import("estree").SequenceExpression} SequenceExpression */
/** @typedef {import("estree").CallExpression} CallExpression */
/** @typedef {import("estree").BaseCallExpression} BaseCallExpression */
/** @typedef {import("estree").StaticBlock} StaticBlock */
/** @typedef {import("estree").ImportExpression} ImportExpression */
/** @typedef {import("estree").ClassDeclaration} ClassDeclaration */
/** @typedef {import("estree").ForStatement} ForStatement */
/** @typedef {import("estree").SwitchStatement} SwitchStatement */
/** @typedef {import("estree").ExportNamedDeclaration} ExportNamedDeclaration */
/** @typedef {import("estree").ClassExpression} ClassExpression */
/** @typedef {import("estree").Comment} Comment */
/** @typedef {import("estree").ConditionalExpression} ConditionalExpression */
/** @typedef {import("estree").Declaration} Declaration */
/** @typedef {import("estree").PrivateIdentifier} PrivateIdentifier */
/** @typedef {import("estree").PropertyDefinition} PropertyDefinition */
/** @typedef {import("estree").Expression} Expression */
/** @typedef {import("estree").Identifier} Identifier */
/** @typedef {import("estree").VariableDeclaration} VariableDeclaration */
/** @typedef {import("estree").IfStatement} IfStatement */
/** @typedef {import("estree").LabeledStatement} LabeledStatement */
/** @typedef {import("estree").Literal} Literal */
/** @typedef {import("estree").LogicalExpression} LogicalExpression */
/** @typedef {import("estree").ChainExpression} ChainExpression */
/** @typedef {import("estree").MemberExpression} MemberExpression */
/** @typedef {import("estree").YieldExpression} YieldExpression */
/** @typedef {import("estree").MetaProperty} MetaProperty */
/** @typedef {import("estree").Property} Property */
/** @typedef {import("estree").AssignmentPattern} AssignmentPattern */
/** @typedef {import("estree").Pattern} Pattern */
/** @typedef {import("estree").UpdateExpression} UpdateExpression */
/** @typedef {import("estree").ObjectExpression} ObjectExpression */
/** @typedef {import("estree").UnaryExpression} UnaryExpression */
/** @typedef {import("estree").ArrayExpression} ArrayExpression */
/** @typedef {import("estree").ArrayPattern} ArrayPattern */
/** @typedef {import("estree").AwaitExpression} AwaitExpression */
/** @typedef {import("estree").ThisExpression} ThisExpression */
/** @typedef {import("estree").RestElement} RestElement */
/** @typedef {import("estree").ObjectPattern} ObjectPattern */
/** @typedef {import("estree").SwitchCase} SwitchCase */
/** @typedef {import("estree").CatchClause} CatchClause */
/** @typedef {import("estree").VariableDeclarator} VariableDeclarator */
/** @typedef {import("estree").ForInStatement} ForInStatement */
/** @typedef {import("estree").ForOfStatement} ForOfStatement */
/** @typedef {import("estree").ReturnStatement} ReturnStatement */
/** @typedef {import("estree").WithStatement} WithStatement */
/** @typedef {import("estree").ThrowStatement} ThrowStatement */
/** @typedef {import("estree").MethodDefinition} MethodDefinition */
/** @typedef {import("estree").ModuleDeclaration} ModuleDeclaration */
/** @typedef {import("estree").NewExpression} NewExpression */
/** @typedef {import("estree").SpreadElement} SpreadElement */
/** @typedef {import("estree").FunctionExpression} FunctionExpression */
/** @typedef {import("estree").WhileStatement} WhileStatement */
/** @typedef {import("estree").ArrowFunctionExpression} ArrowFunctionExpression */
/** @typedef {import("estree").ExpressionStatement} ExpressionStatement */
/** @typedef {import("estree").FunctionDeclaration} FunctionDeclaration */
/** @typedef {import("estree").DoWhileStatement} DoWhileStatement */
/** @typedef {import("estree").TryStatement} TryStatement */
/** @typedef {import("estree").Node} AnyNode */
/** @typedef {import("estree").Program} Program */
/** @typedef {import("estree").Directive} Directive */
/** @typedef {import("estree").Statement} Statement */
/** @typedef {import("estree").ImportDeclaration} ImportDeclaration */
/** @typedef {import("estree").ExportDefaultDeclaration} ExportDefaultDeclaration */
/** @typedef {import("estree").ExportAllDeclaration} ExportAllDeclaration */
/** @typedef {import("estree").Super} Super */
/** @typedef {import("estree").TaggedTemplateExpression} TaggedTemplateExpression */
/** @typedef {import("estree").TemplateLiteral} TemplateLiteral */
/** @typedef {Record<string, any>} Assertions */
/** @template T @typedef {import("tapable").AsArray<T>} AsArray<T> */
/** @typedef {import("../Parser").ParserState} ParserState */
/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */
/** @typedef {{declaredScope: ScopeInfo, freeName: string | true, tagInfo: TagInfo | undefined}} VariableInfoInterface */
/** @typedef {{ name: string | VariableInfo, rootInfo: string | VariableInfo, getMembers: () => string[], getMembersOptionals: () => boolean[], getMemberRanges: () => Range[] }} GetInfoResult */
const EMPTY_ARRAY = [];
const ALLOWED_MEMBER_TYPES_CALL_EXPRESSION = 0b01;
const ALLOWED_MEMBER_TYPES_EXPRESSION = 0b10;
const ALLOWED_MEMBER_TYPES_ALL = 0b11;
// Syntax: https://developer.mozilla.org/en/SpiderMonkey/Parser_API
const parser = AcornParser.extend(importAssertions);
class VariableInfo {
/**
* @param {ScopeInfo} declaredScope scope in which the variable is declared
* @param {string | true} freeName which free name the variable aliases, or true when none
* @param {TagInfo | undefined} tagInfo info about tags
*/
constructor(declaredScope, freeName, tagInfo) {
this.declaredScope = declaredScope;
this.freeName = freeName;
this.tagInfo = tagInfo;
}
}
/** @typedef {string | ScopeInfo | VariableInfo} ExportedVariableInfo */
/** @typedef {Literal | string | null | undefined} ImportSource */
/** @typedef {Omit<AcornOptions, "sourceType" | "ecmaVersion"> & { sourceType: "module" | "script" | "auto", ecmaVersion?: AcornOptions["ecmaVersion"] }} ParseOptions */
/**
* @typedef {Object} TagInfo
* @property {any} tag
* @property {any} data
* @property {TagInfo | undefined} next
*/
/**
* @typedef {Object} ScopeInfo
* @property {StackedMap<string, VariableInfo | ScopeInfo>} definitions
* @property {boolean | "arrow"} topLevelScope
* @property {boolean | string} inShorthand
* @property {boolean} isStrict
* @property {boolean} isAsmJs
* @property {boolean} inTry
*/
/** @typedef {[number, number]} Range */
/**
* Helper function for joining two ranges into a single range. This is useful
* when working with AST nodes, as it allows you to combine the ranges of child nodes
* to create the range of the _parent node_.
*
* @param {[number, number]} startRange start range to join
* @param {[number, number]} endRange end range to join
* @returns {[number, number]} joined range
*
* @example
* ```js
* const startRange = [0, 5];
* const endRange = [10, 15];
* const joinedRange = joinRanges(startRange, endRange);
* console.log(joinedRange); // [0, 15]
* ```
*
*/
const joinRanges = (startRange, endRange) => {
if (!endRange) return startRange;
if (!startRange) return endRange;
return [startRange[0], endRange[1]];
};
/**
* Helper function used to generate a string representation of a
* [member expression](https://github.com/estree/estree/blob/master/es5.md#memberexpression).
*
* @param {string} object object to name
* @param {string[]} membersReversed reversed list of members
* @returns {string} member expression as a string
* @example
* ```js
* const membersReversed = ["property1", "property2", "property3"]; // Members parsed from the AST
* const name = objectAndMembersToName("myObject", membersReversed);
*
* console.log(name); // "myObject.property1.property2.property3"
* ```
*
*/
const objectAndMembersToName = (object, membersReversed) => {
let name = object;
for (let i = membersReversed.length - 1; i >= 0; i--) {
name = name + "." + membersReversed[i];
}
return name;
};
/**
* Grabs the name of a given expression and returns it as a string or undefined. Has particular
* handling for [Identifiers](https://github.com/estree/estree/blob/master/es5.md#identifier),
* [ThisExpressions](https://github.com/estree/estree/blob/master/es5.md#identifier), and
* [MetaProperties](https://github.com/estree/estree/blob/master/es2015.md#metaproperty) which is
* specifically for handling the `new.target` meta property.
*
* @param {Expression | Super} expression expression
* @returns {string | "this" | undefined} name or variable info
*/
const getRootName = expression => {
switch (expression.type) {
case "Identifier":
return expression.name;
case "ThisExpression":
return "this";
case "MetaProperty":
return `${expression.meta.name}.${expression.property.name}`;
default:
return undefined;
}
};
/** @type {AcornOptions} */
const defaultParserOptions = {
ranges: true,
locations: true,
ecmaVersion: "latest",
sourceType: "module",
// https://github.com/tc39/proposal-hashbang
allowHashBang: true,
onComment: null
};
// regexp to match at least one "magic comment"
const webpackCommentRegExp = new RegExp(/(^|\W)webpack[A-Z]{1,}[A-Za-z]{1,}:/);
const EMPTY_COMMENT_OPTIONS = {
options: null,
errors: null
};
class JavascriptParser extends Parser {
/**
* @param {"module" | "script" | "auto"} sourceType default source type
*/
constructor(sourceType = "auto") {
super();
this.hooks = Object.freeze({
/** @type {HookMap<SyncBailHook<[UnaryExpression], BasicEvaluatedExpression | undefined | null>>} */
evaluateTypeof: new HookMap(() => new SyncBailHook(["expression"])),
/** @type {HookMap<SyncBailHook<[Expression], BasicEvaluatedExpression | undefined | null>>} */
evaluate: new HookMap(() => new SyncBailHook(["expression"])),
/** @type {HookMap<SyncBailHook<[Identifier | ThisExpression | MemberExpression | MetaProperty], BasicEvaluatedExpression | undefined | null>>} */
evaluateIdentifier: new HookMap(() => new SyncBailHook(["expression"])),
/** @type {HookMap<SyncBailHook<[Identifier | ThisExpression | MemberExpression], BasicEvaluatedExpression | undefined | null>>} */
evaluateDefinedIdentifier: new HookMap(
() => new SyncBailHook(["expression"])
),
/** @type {HookMap<SyncBailHook<[NewExpression], BasicEvaluatedExpression | undefined | null>>} */
evaluateNewExpression: new HookMap(
() => new SyncBailHook(["expression"])
),
/** @type {HookMap<SyncBailHook<[CallExpression], BasicEvaluatedExpression | undefined | null>>} */
evaluateCallExpression: new HookMap(
() => new SyncBailHook(["expression"])
),
/** @type {HookMap<SyncBailHook<[CallExpression, BasicEvaluatedExpression | undefined], BasicEvaluatedExpression | undefined | null>>} */
evaluateCallExpressionMember: new HookMap(
() => new SyncBailHook(["expression", "param"])
),
/** @type {HookMap<SyncBailHook<[Expression | Declaration | PrivateIdentifier, number], boolean | void>>} */
isPure: new HookMap(
() => new SyncBailHook(["expression", "commentsStartPosition"])
),
/** @type {SyncBailHook<[Statement | ModuleDeclaration], boolean | void>} */
preStatement: new SyncBailHook(["statement"]),
/** @type {SyncBailHook<[Statement | ModuleDeclaration], boolean | void>} */
blockPreStatement: new SyncBailHook(["declaration"]),
/** @type {SyncBailHook<[Statement | ModuleDeclaration], boolean | void>} */
statement: new SyncBailHook(["statement"]),
/** @type {SyncBailHook<[IfStatement], boolean | void>} */
statementIf: new SyncBailHook(["statement"]),
/** @type {SyncBailHook<[Expression, ClassExpression | ClassDeclaration], boolean | void>} */
classExtendsExpression: new SyncBailHook([
"expression",
"classDefinition"
]),
/** @type {SyncBailHook<[MethodDefinition | PropertyDefinition | StaticBlock, ClassExpression | ClassDeclaration], boolean | void>} */
classBodyElement: new SyncBailHook(["element", "classDefinition"]),
/** @type {SyncBailHook<[Expression, MethodDefinition | PropertyDefinition, ClassExpression | ClassDeclaration], boolean | void>} */
classBodyValue: new SyncBailHook([
"expression",
"element",
"classDefinition"
]),
/** @type {HookMap<SyncBailHook<[LabeledStatement], boolean | void>>} */
label: new HookMap(() => new SyncBailHook(["statement"])),
/** @type {SyncBailHook<[ImportDeclaration, ImportSource], boolean | void>} */
import: new SyncBailHook(["statement", "source"]),
/** @type {SyncBailHook<[ImportDeclaration, ImportSource, string, string], boolean | void>} */
importSpecifier: new SyncBailHook([
"statement",
"source",
"exportName",
"identifierName"
]),
/** @type {SyncBailHook<[ExportNamedDeclaration | ExportAllDeclaration], boolean | void>} */
export: new SyncBailHook(["statement"]),
/** @type {SyncBailHook<[ExportNamedDeclaration | ExportAllDeclaration, ImportSource], boolean | void>} */
exportImport: new SyncBailHook(["statement", "source"]),
/** @type {SyncBailHook<[ExportNamedDeclaration | ExportAllDeclaration, Declaration], boolean | void>} */
exportDeclaration: new SyncBailHook(["statement", "declaration"]),
/** @type {SyncBailHook<[ExportDefaultDeclaration, Declaration], boolean | void>} */
exportExpression: new SyncBailHook(["statement", "declaration"]),
/** @type {SyncBailHook<[ExportNamedDeclaration | ExportAllDeclaration, string, string, number | undefined], boolean | void>} */
exportSpecifier: new SyncBailHook([
"statement",
"identifierName",
"exportName",
"index"
]),
/** @type {SyncBailHook<[ExportNamedDeclaration | ExportAllDeclaration, ImportSource, string, string, number | undefined], boolean | void>} */
exportImportSpecifier: new SyncBailHook([
"statement",
"source",
"identifierName",
"exportName",
"index"
]),
/** @type {SyncBailHook<[VariableDeclarator, Statement], boolean | void>} */
preDeclarator: new SyncBailHook(["declarator", "statement"]),
/** @type {SyncBailHook<[VariableDeclarator, Statement], boolean | void>} */
declarator: new SyncBailHook(["declarator", "statement"]),
/** @type {HookMap<SyncBailHook<[Declaration], boolean | void>>} */
varDeclaration: new HookMap(() => new SyncBailHook(["declaration"])),
/** @type {HookMap<SyncBailHook<[Declaration], boolean | void>>} */
varDeclarationLet: new HookMap(() => new SyncBailHook(["declaration"])),
/** @type {HookMap<SyncBailHook<[Declaration], boolean | void>>} */
varDeclarationConst: new HookMap(() => new SyncBailHook(["declaration"])),
/** @type {HookMap<SyncBailHook<[Declaration], boolean | void>>} */
varDeclarationVar: new HookMap(() => new SyncBailHook(["declaration"])),
/** @type {HookMap<SyncBailHook<[Identifier], boolean | void>>} */
pattern: new HookMap(() => new SyncBailHook(["pattern"])),
/** @type {HookMap<SyncBailHook<[Expression], boolean | void>>} */
canRename: new HookMap(() => new SyncBailHook(["initExpression"])),
/** @type {HookMap<SyncBailHook<[Expression], boolean | void>>} */
rename: new HookMap(() => new SyncBailHook(["initExpression"])),
/** @type {HookMap<SyncBailHook<[AssignmentExpression], boolean | void>>} */
assign: new HookMap(() => new SyncBailHook(["expression"])),
/** @type {HookMap<SyncBailHook<[AssignmentExpression, string[]], boolean | void>>} */
assignMemberChain: new HookMap(
() => new SyncBailHook(["expression", "members"])
),
/** @type {HookMap<SyncBailHook<[Expression], boolean | void>>} */
typeof: new HookMap(() => new SyncBailHook(["expression"])),
/** @type {SyncBailHook<[ImportExpression], boolean | void>} */
importCall: new SyncBailHook(["expression"]),
/** @type {SyncBailHook<[Expression], boolean | void>} */
topLevelAwait: new SyncBailHook(["expression"]),
/** @type {HookMap<SyncBailHook<[BaseCallExpression], boolean | void>>} */
call: new HookMap(() => new SyncBailHook(["expression"])),
/** Something like "a.b()" */
/** @type {HookMap<SyncBailHook<[CallExpression, string[], boolean[], Range[]], boolean | void>>} */
callMemberChain: new HookMap(
() =>
new SyncBailHook([
"expression",
"members",
"membersOptionals",
"memberRanges"
])
),
/** Something like "a.b().c.d" */
/** @type {HookMap<SyncBailHook<[Expression, string[], CallExpression, string[]], boolean | void>>} */
memberChainOfCallMemberChain: new HookMap(
() =>
new SyncBailHook([
"expression",
"calleeMembers",
"callExpression",
"members"
])
),
/** Something like "a.b().c.d()"" */
/** @type {HookMap<SyncBailHook<[Expression, string[], CallExpression, string[]], boolean | void>>} */
callMemberChainOfCallMemberChain: new HookMap(
() =>
new SyncBailHook([
"expression",
"calleeMembers",
"innerCallExpression",
"members"
])
),
/** @type {SyncBailHook<[ChainExpression], boolean | void>} */
optionalChaining: new SyncBailHook(["optionalChaining"]),
/** @type {HookMap<SyncBailHook<[NewExpression], boolean | void>>} */
new: new HookMap(() => new SyncBailHook(["expression"])),
/** @type {SyncBailHook<[BinaryExpression], boolean | void>} */
binaryExpression: new SyncBailHook(["binaryExpression"]),
/** @type {HookMap<SyncBailHook<[Expression], boolean | void>>} */
expression: new HookMap(() => new SyncBailHook(["expression"])),
/** @type {HookMap<SyncBailHook<[Expression, string[], boolean[], Range[]], boolean | void>>} */
expressionMemberChain: new HookMap(
() =>
new SyncBailHook([
"expression",
"members",
"membersOptionals",
"memberRanges"
])
),
/** @type {HookMap<SyncBailHook<[Expression, string[]], boolean | void>>} */
unhandledExpressionMemberChain: new HookMap(
() => new SyncBailHook(["expression", "members"])
),
/** @type {SyncBailHook<[Expression], boolean | void>} */
expressionConditionalOperator: new SyncBailHook(["expression"]),
/** @type {SyncBailHook<[Expression], boolean | void>} */
expressionLogicalOperator: new SyncBailHook(["expression"]),
/** @type {SyncBailHook<[Program, Comment[]], boolean | void>} */
program: new SyncBailHook(["ast", "comments"]),
/** @type {SyncBailHook<[Program, Comment[]], boolean | void>} */
finish: new SyncBailHook(["ast", "comments"])
});
this.sourceType = sourceType;
/** @type {ScopeInfo} */
this.scope = undefined;
/** @type {ParserState} */
this.state = undefined;
this.comments = undefined;
this.semicolons = undefined;
/** @type {(Statement | ModuleDeclaration | Expression)[]} */
this.statementPath = undefined;
/** @type {Statement | ModuleDeclaration | Expression} */
this.prevStatement = undefined;
/** @type {WeakMap<Expression, Set<string>>} */
this.destructuringAssignmentProperties = undefined;
this.currentTagData = undefined;
this._initializeEvaluating();
}
_initializeEvaluating() {
this.hooks.evaluate.for("Literal").tap("JavascriptParser", _expr => {
const expr = /** @type {Literal} */ (_expr);
switch (typeof expr.value) {
case "number":
return new BasicEvaluatedExpression()
.setNumber(expr.value)
.setRange(expr.range);
case "bigint":
return new BasicEvaluatedExpression()
.setBigInt(expr.value)
.setRange(expr.range);
case "string":
return new BasicEvaluatedExpression()
.setString(expr.value)
.setRange(expr.range);
case "boolean":
return new BasicEvaluatedExpression()
.setBoolean(expr.value)
.setRange(expr.range);
}
if (expr.value === null) {
return new BasicEvaluatedExpression().setNull().setRange(expr.range);
}
if (expr.value instanceof RegExp) {
return new BasicEvaluatedExpression()
.setRegExp(expr.value)
.setRange(expr.range);
}
});
this.hooks.evaluate.for("NewExpression").tap("JavascriptParser", _expr => {
const expr = /** @type {NewExpression} */ (_expr);
const callee = expr.callee;
if (callee.type !== "Identifier") return;
if (callee.name !== "RegExp") {
return this.callHooksForName(
this.hooks.evaluateNewExpression,
callee.name,
expr
);
} else if (
expr.arguments.length > 2 ||
this.getVariableInfo("RegExp") !== "RegExp"
)
return;
let regExp, flags;
const arg1 = expr.arguments[0];
if (arg1) {
if (arg1.type === "SpreadElement") return;
const evaluatedRegExp = this.evaluateExpression(arg1);
if (!evaluatedRegExp) return;
regExp = evaluatedRegExp.asString();
if (!regExp) return;
} else {
return new BasicEvaluatedExpression()
.setRegExp(new RegExp(""))
.setRange(expr.range);
}
const arg2 = expr.arguments[1];
if (arg2) {
if (arg2.type === "SpreadElement") return;
const evaluatedFlags = this.evaluateExpression(arg2);
if (!evaluatedFlags) return;
if (!evaluatedFlags.isUndefined()) {
flags = evaluatedFlags.asString();
if (
flags === undefined ||
!BasicEvaluatedExpression.isValidRegExpFlags(flags)
)
return;
}
}
return new BasicEvaluatedExpression()
.setRegExp(flags ? new RegExp(regExp, flags) : new RegExp(regExp))
.setRange(expr.range);
});
this.hooks.evaluate
.for("LogicalExpression")
.tap("JavascriptParser", _expr => {
const expr = /** @type {LogicalExpression} */ (_expr);
const left = this.evaluateExpression(expr.left);
let returnRight = false;
/** @type {boolean|undefined} */
let allowedRight;
if (expr.operator === "&&") {
const leftAsBool = left.asBool();
if (leftAsBool === false) return left.setRange(expr.range);
returnRight = leftAsBool === true;
allowedRight = false;
} else if (expr.operator === "||") {
const leftAsBool = left.asBool();
if (leftAsBool === true) return left.setRange(expr.range);
returnRight = leftAsBool === false;
allowedRight = true;
} else if (expr.operator === "??") {
const leftAsNullish = left.asNullish();
if (leftAsNullish === false) return left.setRange(expr.range);
if (leftAsNullish !== true) return;
returnRight = true;
} else return;
const right = this.evaluateExpression(expr.right);
if (returnRight) {
if (left.couldHaveSideEffects()) right.setSideEffects();
return right.setRange(expr.range);
}
const asBool = right.asBool();
if (allowedRight === true && asBool === true) {
return new BasicEvaluatedExpression()
.setRange(expr.range)
.setTruthy();
} else if (allowedRight === false && asBool === false) {
return new BasicEvaluatedExpression().setRange(expr.range).setFalsy();
}
});
/**
* In simple logical cases, we can use valueAsExpression to assist us in evaluating the expression on
* either side of a [BinaryExpression](https://github.com/estree/estree/blob/master/es5.md#binaryexpression).
* This supports scenarios in webpack like conditionally `import()`'ing modules based on some simple evaluation:
*
* ```js
* if (1 === 3) {
* import("./moduleA"); // webpack will auto evaluate this and not import the modules
* }
* ```
*
* Additional scenarios include evaluation of strings inside of dynamic import statements:
*
* ```js
* const foo = "foo";
* const bar = "bar";
*
* import("./" + foo + bar); // webpack will auto evaluate this into import("./foobar")
* ```
* @param {boolean | number | BigInt | string} value the value to convert to an expression
* @param {BinaryExpression | UnaryExpression} expr the expression being evaluated
* @param {boolean} sideEffects whether the expression has side effects
* @returns {BasicEvaluatedExpression} the evaluated expression
* @example
*
* ```js
* const binaryExpr = new BinaryExpression("+",
* { type: "Literal", value: 2 },
* { type: "Literal", value: 3 }
* );
*
* const leftValue = 2;
* const rightValue = 3;
*
* const leftExpr = valueAsExpression(leftValue, binaryExpr.left, false);
* const rightExpr = valueAsExpression(rightValue, binaryExpr.right, false);
* const result = new BasicEvaluatedExpression()
* .setNumber(leftExpr.number + rightExpr.number)
* .setRange(binaryExpr.range);
*
* console.log(result.number); // Output: 5
* ```
*/
const valueAsExpression = (value, expr, sideEffects) => {
switch (typeof value) {
case "boolean":
return new BasicEvaluatedExpression()
.setBoolean(value)
.setSideEffects(sideEffects)
.setRange(expr.range);
case "number":
return new BasicEvaluatedExpression()
.setNumber(value)
.setSideEffects(sideEffects)
.setRange(expr.range);
case "bigint":
return new BasicEvaluatedExpression()
.setBigInt(value)
.setSideEffects(sideEffects)
.setRange(expr.range);
case "string":
return new BasicEvaluatedExpression()
.setString(value)
.setSideEffects(sideEffects)
.setRange(expr.range);
}
};
this.hooks.evaluate
.for("BinaryExpression")
.tap("JavascriptParser", _expr => {
const expr = /** @type {BinaryExpression} */ (_expr);
/**
* Evaluates a binary expression if and only if it is a const operation (e.g. 1 + 2, "a" + "b", etc.).
*
* @template T
* @param {(leftOperand: T, rightOperand: T) => boolean | number | BigInt | string} operandHandler the handler for the operation (e.g. (a, b) => a + b)
* @returns {BasicEvaluatedExpression | undefined} the evaluated expression
*/
const handleConstOperation = operandHandler => {
const left = this.evaluateExpression(expr.left);
if (!left.isCompileTimeValue()) return;
const right = this.evaluateExpression(expr.right);
if (!right.isCompileTimeValue()) return;
const result = operandHandler(
left.asCompileTimeValue(),
right.asCompileTimeValue()
);
return valueAsExpression(
result,
expr,
left.couldHaveSideEffects() || right.couldHaveSideEffects()
);
};
/**
* Helper function to determine if two booleans are always different. This is used in `handleStrictEqualityComparison`
* to determine if an expressions boolean or nullish conversion is equal or not.
*
* @param {boolean} a first boolean to compare
* @param {boolean} b second boolean to compare
* @returns {boolean} true if the two booleans are always different, false otherwise
*/
const isAlwaysDifferent = (a, b) =>
(a === true && b === false) || (a === false && b === true);
const handleTemplateStringCompare = (left, right, res, eql) => {
const getPrefix = parts => {
let value = "";
for (const p of parts) {
const v = p.asString();
if (v !== undefined) value += v;
else break;
}
return value;
};
const getSuffix = parts => {
let value = "";
for (let i = parts.length - 1; i >= 0; i--) {
const v = parts[i].asString();
if (v !== undefined) value = v + value;
else break;
}
return value;
};
const leftPrefix = getPrefix(left.parts);
const rightPrefix = getPrefix(right.parts);
const leftSuffix = getSuffix(left.parts);
const rightSuffix = getSuffix(right.parts);
const lenPrefix = Math.min(leftPrefix.length, rightPrefix.length);
const lenSuffix = Math.min(leftSuffix.length, rightSuffix.length);
const prefixMismatch =
lenPrefix > 0 &&
leftPrefix.slice(0, lenPrefix) !== rightPrefix.slice(0, lenPrefix);
const suffixMismatch =
lenSuffix > 0 &&
leftSuffix.slice(-lenSuffix) !== rightSuffix.slice(-lenSuffix);
if (prefixMismatch || suffixMismatch) {
return res
.setBoolean(!eql)
.setSideEffects(
left.couldHaveSideEffects() || right.couldHaveSideEffects()
);
}
};
/**
* Helper function to handle BinaryExpressions using strict equality comparisons (e.g. "===" and "!==").
* @param {boolean} eql true for "===" and false for "!=="
* @returns {BasicEvaluatedExpression | undefined} the evaluated expression
*/
const handleStrictEqualityComparison = eql => {
const left = this.evaluateExpression(expr.left);
const right = this.evaluateExpression(expr.right);
const res = new BasicEvaluatedExpression();
res.setRange(expr.range);
const leftConst = left.isCompileTimeValue();
const rightConst = right.isCompileTimeValue();
if (leftConst && rightConst) {
return res
.setBoolean(
eql ===
(left.asCompileTimeValue() === right.asCompileTimeValue())
)
.setSideEffects(
left.couldHaveSideEffects() || right.couldHaveSideEffects()
);
}
if (left.isArray() && right.isArray()) {
return res
.setBoolean(!eql)
.setSideEffects(
left.couldHaveSideEffects() || right.couldHaveSideEffects()
);
}
if (left.isTemplateString() && right.isTemplateString()) {
return handleTemplateStringCompare(left, right, res, eql);
}
const leftPrimitive = left.isPrimitiveType();
const rightPrimitive = right.isPrimitiveType();
if (
// Primitive !== Object or
// compile-time object types are never equal to something at runtime
(leftPrimitive === false &&
(leftConst || rightPrimitive === true)) ||
(rightPrimitive === false &&
(rightConst || leftPrimitive === true)) ||
// Different nullish or boolish status also means not equal
isAlwaysDifferent(left.asBool(), right.asBool()) ||
isAlwaysDifferent(left.asNullish(), right.asNullish())
) {
return res
.setBoolean(!eql)
.setSideEffects(
left.couldHaveSideEffects() || right.couldHaveSideEffects()
);
}
};
/**
* Helper function to handle BinaryExpressions using abstract equality comparisons (e.g. "==" and "!=").
* @param {boolean} eql true for "==" and false for "!="
* @returns {BasicEvaluatedExpression | undefined} the evaluated expression
*/
const handleAbstractEqualityComparison = eql => {
const left = this.evaluateExpression(expr.left);
const right = this.evaluateExpression(expr.right);
const res = new BasicEvaluatedExpression();
res.setRange(expr.range);
const leftConst = left.isCompileTimeValue();
const rightConst = right.isCompileTimeValue();
if (leftConst && rightConst) {
return res
.setBoolean(
eql ===
// eslint-disable-next-line eqeqeq
(left.asCompileTimeValue() == right.asCompileTimeValue())
)
.setSideEffects(
left.couldHaveSideEffects() || right.couldHaveSideEffects()
);
}
if (left.isArray() && right.isArray()) {
return res
.setBoolean(!eql)
.setSideEffects(
left.couldHaveSideEffects() || right.couldHaveSideEffects()
);
}
if (left.isTemplateString() && right.isTemplateString()) {
return handleTemplateStringCompare(left, right, res, eql);
}
};
if (expr.operator === "+") {
const left = this.evaluateExpression(expr.left);
const right = this.evaluateExpression(expr.right);
const res = new BasicEvaluatedExpression();
if (left.isString()) {
if (right.isString()) {
res.setString(left.string + right.string);
} else if (right.isNumber()) {
res.setString(left.string + right.number);
} else if (
right.isWrapped() &&
right.prefix &&
right.prefix.isString()
) {
// "left" + ("prefix" + inner + "postfix")
// => ("leftPrefix" + inner + "postfix")
res.setWrapped(
new BasicEvaluatedExpression()
.setString(left.string + right.prefix.string)
.setRange(joinRanges(left.range, right.prefix.range)),
right.postfix,
right.wrappedInnerExpressions
);
} else if (right.isWrapped()) {
// "left" + ([null] + inner + "postfix")
// => ("left" + inner + "postfix")
res.setWrapped(
left,
right.postfix,
right.wrappedInnerExpressions
);
} else {
// "left" + expr
// => ("left" + expr + "")
res.setWrapped(left, null, [right]);
}
} else if (left.isNumber()) {
if (right.isString()) {
res.setString(left.number + right.string);
} else if (right.isNumber()) {
res.setNumber(left.number + right.number);
} else {
return;
}
} else if (left.isBigInt()) {
if (right.isBigInt()) {
res.setBigInt(left.bigint + right.bigint);
}
} else if (left.isWrapped()) {
if (left.postfix && left.postfix.isString() && right.isString()) {
// ("prefix" + inner + "postfix") + "right"
// => ("prefix" + inner + "postfixRight")
res.setWrapped(
left.prefix,
new BasicEvaluatedExpression()
.setString(left.postfix.string + right.string)
.setRange(joinRanges(left.postfix.range, right.range)),
left.wrappedInnerExpressions
);
} else if (
left.postfix &&
left.postfix.isString() &&
right.isNumber()
) {
// ("prefix" + inner + "postfix") + 123
// => ("prefix" + inner + "postfix123")
res.setWrapped(
left.prefix,
new BasicEvaluatedExpression()
.setString(left.postfix.string + right.number)
.setRange(joinRanges(left.postfix.range, right.range)),
left.wrappedInnerExpressions
);
} else if (right.isString()) {
// ("prefix" + inner + [null]) + "right"
// => ("prefix" + inner + "right")
res.setWrapped(left.prefix, right, left.wrappedInnerExpressions);
} else if (right.isNumber()) {
// ("prefix" + inner + [null]) + 123
// => ("prefix" + inner + "123")
res.setWrapped(
left.prefix,
new BasicEvaluatedExpression()
.setString(right.number + "")
.setRange(right.range),
left.wrappedInnerExpressions
);
} else if (right.isWrapped()) {
// ("prefix1" + inner1 + "postfix1") + ("prefix2" + inner2 + "postfix2")
// ("prefix1" + inner1 + "postfix1" + "prefix2" + inner2 + "postfix2")
res.setWrapped(
left.prefix,
right.postfix,
left.wrappedInnerExpressions &&
right.wrappedInnerExpressions &&
left.wrappedInnerExpressions
.concat(left.postfix ? [left.postfix] : [])
.concat(right.prefix ? [right.prefix] : [])
.concat(right.wrappedInnerExpressions)
);
} else {
// ("prefix" + inner + postfix) + expr
// => ("prefix" + inner + postfix + expr + [null])
res.setWrapped(
left.prefix,
null,
left.wrappedInnerExpressions &&
left.wrappedInnerExpressions.concat(
left.postfix ? [left.postfix, right] : [right]
)
);
}
} else {
if (right.isString()) {
// left + "right"
// => ([null] + left + "right")
res.setWrapped(null, right, [left]);
} else if (right.isWrapped()) {
// left + (prefix + inner + "postfix")
// => ([null] + left + prefix + inner + "postfix")
res.setWrapped(
null,
right.postfix,
right.wrappedInnerExpressions &&
(right.prefix ? [left, right.prefix] : [left]).concat(
right.wrappedInnerExpressions
)
);
} else {
return;
}
}
if (left.couldHaveSideEffects() || right.couldHaveSideEffects())
res.setSideEffects();
res.setRange(expr.range);
return res;
} else if (expr.operator === "-") {
return handleConstOperation((l, r) => l - r);
} else if (expr.operator === "*") {
return handleConstOperation((l, r) => l * r);
} else if (expr.operator === "/") {
return handleConstOperation((l, r) => l / r);
} else if (expr.operator === "**") {
return handleConstOperation((l, r) => l ** r);
} else if (expr.operator === "===") {
return handleStrictEqualityComparison(true);
} else if (expr.operator === "==") {
return handleAbstractEqualityComparison(true);
} else if (expr.operator === "!==") {
return handleStrictEqualityComparison(false);
} else if (expr.operator === "!=") {
return handleAbstractEqualityComparison(false);
} else if (expr.operator === "&") {
return handleConstOperation((l, r) => l & r);
} else if (expr.operator === "|") {
return handleConstOperation((l, r) => l | r);
} else if (expr.operator === "^") {
return handleConstOperation((l, r) => l ^ r);
} else if (expr.operator === ">>>") {
return handleConstOperation((l, r) => l >>> r);
} else if (expr.operator === ">>") {
return handleConstOperation((l, r) => l >> r);
} else if (expr.operator === "<<") {
return handleConstOperation((l, r) => l << r);
} else if (expr.operator === "<") {
return handleConstOperation((l, r) => l < r);
} else if (expr.operator === ">") {
return handleConstOperation((l, r) => l > r);
} else if (expr.operator === "<=") {
return handleConstOperation((l, r) => l <= r);
} else if (expr.operator === ">=") {
return handleConstOperation((l, r) => l >= r);
}
});
this.hooks.evaluate
.for("UnaryExpression")
.tap("JavascriptParser", _expr => {
const expr = /** @type {UnaryExpression} */ (_expr);
/**
* Evaluates a UnaryExpression if and only if it is a basic const operator (e.g. +a, -a, ~a).
*
* @template T
* @param {(operand: T) => boolean | number | BigInt | string} operandHandler handler for the operand
* @returns {BasicEvaluatedExpression | undefined} evaluated expression
*/
const handleConstOperation = operandHandler => {
const argument = this.evaluateExpression(expr.argument);
if (!argument.isCompileTimeValue()) return;
const result = operandHandler(argument.asCompileTimeValue());
return valueAsExpression(
result,
expr,
argument.couldHaveSideEffects()
);
};
if (expr.operator === "typeof") {
switch (expr.argument.type) {
case "Identifier": {
const res = this.callHooksForName(
this.hooks.evaluateTypeof,
expr.argument.name,
expr
);
if (res !== undefined) return res;
break;
}
case "MetaProperty": {
const res = this.callHooksForName(
this.hooks.evaluateTypeof,
getRootName(expr.argument),
expr
);
if (res !== undefined) return res;
break;
}
case "MemberExpression": {
const res = this.callHooksForExpression(
this.hooks.evaluateTypeof,
expr.argument,
expr
);
if (res !== undefined) return res;
break;
}
case "ChainExpression": {
const res = this.callHooksForExpression(
this.hooks.evaluateTypeof,
expr.argument.expression,
expr
);
if (res !== undefined) return res;
break;
}
case "FunctionExpression": {
return new BasicEvaluatedExpression()
.setString("function")
.setRange(expr.range);
}
}
const arg = this.evaluateExpression(expr.argument);
if (arg.isUnknown()) return;
if (arg.isString()) {
return new BasicEvaluatedExpression()
.setString("string")
.setRange(expr.range);
}
if (arg.isWrapped()) {
return new BasicEvaluatedExpression()
.setString("string")
.setSideEffects()
.setRange(expr.range);
}
if (arg.isUndefined()) {
return new BasicEvaluatedExpression()
.setString("undefined")
.setRange(expr.range);
}
if (arg.isNumber()) {
return new BasicEvaluatedExpression()
.setString("number")
.setRange(expr.range);
}
if (arg.isBigInt()) {
return new BasicEvaluatedExpression()
.setString("bigint")
.setRange(expr.range);
}
if (arg.isBoolean()) {
return new BasicEvaluatedExpression()
.setString("boolean")
.setRange(expr.range);
}
if (arg.isConstArray() || arg.isRegExp() || arg.isNull()) {
return new BasicEvaluatedExpression()
.setString("object")
.setRange(expr.range);
}
if (arg.isArray()) {
return new BasicEvaluatedExpression()
.setString("object")
.setSideEffects(arg.couldHaveSideEffects())
.setRange(expr.range);
}
} else if (expr.operator === "!") {
const argument = this.evaluateExpression(expr.argument);
const bool = argument.asBool();
if (typeof bool !== "boolean") return;
return new BasicEvaluatedExpression()
.setBoolean(!bool)
.setSideEffects(argument.couldHaveSideEffects())
.setRange(expr.range);
} else if (expr.operator === "~") {
return handleConstOperation(v => ~v);
} else if (expr.operator === "+") {
return handleConstOperation(v => +v);
} else if (expr.operator === "-") {
return handleConstOperation(v => -v);
}
});
this.hooks.evaluateTypeof.for("undefined").tap("JavascriptParser", expr => {
return new BasicEvaluatedExpression()
.setString("undefined")
.setRange(expr.range);
});
this.hooks.evaluate.for("Identifier").tap("JavascriptParser", expr => {
if (/** @type {Identifier} */ (expr).name === "undefined") {
return new BasicEvaluatedExpression()
.setUndefined()
.setRange(expr.range);
}
});
/**
* @param {string} exprType expression type name
* @param {function(Expression): GetInfoResult | undefined} getInfo get info
* @returns {void}
*/
const tapEvaluateWithVariableInfo = (exprType, getInfo) => {
/** @type {Expression | undefined} */
let cachedExpression = undefined;
/** @type {GetInfoResult | undefined} */
let cachedInfo = undefined;
this.hooks.evaluate.for(exprType).tap("JavascriptParser", expr => {
const expression = /** @type {MemberExpression} */ (expr);
const info = getInfo(expr);
if (info !== undefined) {
return this.callHooksForInfoWithFallback(
this.hooks.evaluateIdentifier,
info.name,
name => {
cachedExpression = expression;
cachedInfo = info;
},
name => {
const hook = this.hooks.evaluateDefinedIdentifier.get(name);
if (hook !== undefined) {
return hook.call(expression);
}
},
expression
);
}
});
this.hooks.evaluate
.for(exprType)
.tap({ name: "JavascriptParser", stage: 100 }, expr => {
const info = cachedExpression === expr ? cachedInfo : getInfo(expr);
if (info !== undefined) {
return new BasicEvaluatedExpression()
.setIdentifier(
info.name,
info.rootInfo,
info.getMembers,
info.getMembersOptionals,
info.getMemberRanges
)
.setRange(expr.range);
}
});
this.hooks.finish.tap("JavascriptParser", () => {
// Cleanup for GC
cachedExpression = cachedInfo = undefined;
});
};
tapEvaluateWithVariableInfo("Identifier", expr => {
const info = this.getVariableInfo(/** @type {Identifier} */ (expr).name);
if (
typeof info === "string" ||
(info instanceof VariableInfo && typeof info.freeName === "string")
) {
return {
name: info,
rootInfo: info,
getMembers: () => [],
getMembersOptionals: () => [],
getMemberRanges: () => []
};
}
});
tapEvaluateWithVariableInfo("ThisExpression", expr => {
const info = this.getVariableInfo("this");
if (
typeof info === "string" ||
(info instanceof VariableInfo && typeof info.freeName === "string")
) {
return {
name: info,
rootInfo: info,
getMembers: () => [],
getMembersOptionals: () => [],
getMemberRanges: () => []
};
}
});
this.hooks.evaluate.for("MetaProperty").tap("JavascriptParser", expr => {
const metaProperty = /** @type {MetaProperty} */ (expr);
return this.callHooksForName(
this.hooks.evaluateIdentifier,
getRootName(expr),
metaProperty
);
});
tapEvaluateWithVariableInfo("MemberExpression", expr =>
this.getMemberExpressionInfo(
/** @type {MemberExpression} */ (expr),
ALLOWED_MEMBER_TYPES_EXPRESSION
)
);
this.hooks.evaluate.for("CallExpression").tap("JavascriptParser", _expr => {
const expr = /** @type {CallExpression} */ (_expr);
if (
expr.callee.type === "MemberExpression" &&
expr.callee.property.type ===
(expr.callee.computed ? "Literal" : "Identifier")
) {
// type Super also possible here
const param = this.evaluateExpression(
/** @type {Expression} */ (expr.callee.object)
);
const property =
expr.callee.property.type === "Literal"
? `${expr.callee.property.value}`
: expr.callee.property.name;
const hook = this.hooks.evaluateCallExpressionMember.get(property);
if (hook !== undefined) {
return hook.call(expr, param);
}
} else if (expr.callee.type === "Identifier") {
return this.callHooksForName(
this.hooks.evaluateCallExpression,
expr.callee.name,
expr
);
}
});
this.hooks.evaluateCallExpressionMember
.for("indexOf")
.tap("JavascriptParser", (expr, param) => {
if (!param.isString()) return;
if (expr.arguments.length === 0) return;
const [arg1, arg2] = expr.arguments;
if (arg1.type === "SpreadElement") return;
const arg1Eval = this.evaluateExpression(arg1);
if (!arg1Eval.isString()) return;
const arg1Value = arg1Eval.string;
let result;
if (arg2) {
if (arg2.type === "SpreadElement") return;
const arg2Eval = this.evaluateExpression(arg2);
if (!arg2Eval.isNumber()) return;
result = param.string.indexOf(arg1Value, arg2Eval.number);
} else {
result = param.string.indexOf(arg1Value);
}
return new BasicEvaluatedExpression()
.setNumber(result)
.setSideEffects(param.couldHaveSideEffects())
.setRange(expr.range);
});
this.hooks.evaluateCallExpressionMember
.for("replace")
.tap("JavascriptParser", (expr, param) => {
if (!param.isString()) return;
if (expr.arguments.length !== 2) return;
if (expr.arguments[0].type === "SpreadElement") return;
if (expr.arguments[1].type === "SpreadElement") return;
let arg1 = this.evaluateExpression(expr.arguments[0]);
let arg2 = this.evaluateExpression(expr.arguments[1]);
if (!arg1.isString() && !arg1.isRegExp()) return;
const arg1Value = arg1.regExp || arg1.string;
if (!arg2.isString()) return;
const arg2Value = arg2.string;
return new BasicEvaluatedExpression()
.setString(param.string.replace(arg1Value, arg2Value))
.setSideEffects(param.couldHaveSideEffects())
.setRange(expr.range);
});
["substr", "substring", "slice"].forEach(fn => {
this.hooks.evaluateCallExpressionMember
.for(fn)
.tap("JavascriptParser", (expr, param) => {
if (!param.isString()) return;
let arg1;
let result,
str = param.string;
switch (expr.arguments.length) {
case 1:
if (expr.arguments[0].type === "SpreadElement") return;
arg1 = this.evaluateExpression(expr.arguments[0]);
if (!arg1.isNumber()) return;
result = str[fn](arg1.number);
break;
case 2: {
if (expr.arguments[0].type === "SpreadElement") return;
if (expr.arguments[1].type === "SpreadElement") return;
arg1 = this.evaluateExpression(expr.arguments[0]);
const arg2 = this.evaluateExpression(expr.arguments[1]);
if (!arg1.isNumber()) return;
if (!arg2.isNumber()) return;
result = str[fn](arg1.number, arg2.number);
break;
}
default:
return;
}
return new BasicEvaluatedExpression()
.setString(result)
.setSideEffects(param.couldHaveSideEffects())
.setRange(expr.range);
});
});
/**
* @param {"cooked" | "raw"} kind kind of values to get
* @param {TemplateLiteral} templateLiteralExpr TemplateLiteral expr
* @returns {{quasis: BasicEvaluatedExpression[], parts: BasicEvaluatedExpression[]}} Simplified template
*/
const getSimplifiedTemplateResult = (kind, templateLiteralExpr) => {
/** @type {BasicEvaluatedExpression[]} */
const quasis = [];
/** @type {BasicEvaluatedExpression[]} */
const parts = [];
for (let i = 0; i < templateLiteralExpr.quasis.length; i++) {
const quasiExpr = templateLiteralExpr.quasis[i];
const quasi = quasiExpr.value[kind];
if (i > 0) {
const prevExpr = parts[parts.length - 1];
const expr = this.evaluateExpression(
templateLiteralExpr.expressions[i - 1]
);
const exprAsString = expr.asString();
if (
typeof exprAsString === "string" &&
!expr.couldHaveSideEffects()
) {
// We can merge quasi + expr + quasi when expr
// is a const string
prevExpr.setString(prevExpr.string + exprAsString + quasi);
prevExpr.setRange([prevExpr.range[0], quasiExpr.range[1]]);
// We unset the expression as it doesn't match to a single expression
prevExpr.setExpression(undefined);
continue;
}
parts.push(expr);
}
const part = new BasicEvaluatedExpression()
.setString(quasi)
.setRange(quasiExpr.range)
.setExpression(quasiExpr);
quasis.push(part);
parts.push(part);
}
return {
quasis,
parts
};
};
this.hooks.evaluate
.for("TemplateLiteral")
.tap("JavascriptParser", _node => {
const node = /** @type {TemplateLiteral} */ (_node);
const { quasis, parts } = getSimplifiedTemplateResult("cooked", node);
if (parts.length === 1) {
return parts[0].setRange(node.range);
}
return new BasicEvaluatedExpression()
.setTemplateString(quasis, parts, "cooked")
.setRange(node.range);
});
this.hooks.evaluate
.for("TaggedTemplateExpression")
.tap("JavascriptParser", _node => {
const node = /** @type {TaggedTemplateExpression} */ (_node);
const tag = this.evaluateExpression(node.tag);
if (tag.isIdentifier() && tag.identifier === "String.raw") {
const { quasis, parts } = getSimplifiedTemplateResult(
"raw",
node.quasi
);
return new BasicEvaluatedExpression()
.setTemplateString(quasis, parts, "raw")
.setRange(node.range);
}
});
this.hooks.evaluateCallExpressionMember
.for("concat")
.tap("JavascriptParser", (expr, param) => {
if (!param.isString() && !param.isWrapped()) return;
let stringSuffix = null;
let hasUnknownParams = false;
const innerExpressions = [];
for (let i = expr.arguments.length - 1; i >= 0; i--) {
const arg = expr.arguments[i];
if (arg.type === "SpreadElement") return;
const argExpr = this.evaluateExpression(arg);
if (
hasUnknownParams ||
(!argExpr.isString() && !argExpr.isNumber())
) {
hasUnknownParams = true;
innerExpressions.push(argExpr);
continue;
}
const value = argExpr.isString()
? argExpr.string
: "" + argExpr.number;
const newString = value + (stringSuffix ? stringSuffix.string : "");
const newRange = /** @type {Range} */ ([
argExpr.range[0],
(stringSuffix || argExpr).range[1]
]);
stringSuffix = new BasicEvaluatedExpression()
.setString(newString)
.setSideEffects(
(stringSuffix && stringSuffix.couldHaveSideEffects()) ||
argExpr.couldHaveSideEffects()
)
.setRange(newRange);
}
if (hasUnknownParams) {
const prefix = param.isString() ? param : param.prefix;
const inner =
param.isWrapped() && param.wrappedInnerExpressions
? param.wrappedInnerExpressions.concat(innerExpressions.reverse())
: innerExpressions.reverse();
return new BasicEvaluatedExpression()
.setWrapped(prefix, stringSuffix, inner)
.setRange(expr.range);
} else if (param.isWrapped()) {
const postfix = stringSuffix || param.postfix;
const inner = param.wrappedInnerExpressions
? param.wrappedInnerExpressions.concat(innerExpressions.reverse())
: innerExpressions.reverse();
return new BasicEvaluatedExpression()
.setWrapped(param.prefix, postfix, inner)
.setRange(expr.range);
} else {
const newString =
param.string + (stringSuffix ? stringSuffix.string : "");
return new BasicEvaluatedExpression()
.setString(newString)
.setSideEffects(
(stringSuffix && stringSuffix.couldHaveSideEffects()) ||
param.couldHaveSideEffects()
)
.setRange(expr.range);
}
});
this.hooks.evaluateCallExpressionMember
.for("split")
.tap("JavascriptParser", (expr, param) => {
if (!param.isString()) return;
if (expr.arguments.length !== 1) return;
if (expr.arguments[0].type === "SpreadElement") return;
let result;
const arg = this.evaluateExpression(expr.arguments[0]);
if (arg.isString()) {
result = param.string.split(arg.string);
} else if (arg.isRegExp()) {
result = param.string.split(arg.regExp);
} else {
return;
}
return new BasicEvaluatedExpression()
.setArray(result)
.setSideEffects(param.couldHaveSideEffects())
.setRange(expr.range);
});
this.hooks.evaluate
.for("ConditionalExpression")
.tap("JavascriptParser", _expr => {
const expr = /** @type {ConditionalExpression} */ (_expr);
const condition = this.evaluateExpression(expr.test);
const conditionValue = condition.asBool();
let res;
if (conditionValue === undefined) {
const consequent = this.evaluateExpression(expr.consequent);
const alternate = this.evaluateExpression(expr.alternate);
res = new BasicEvaluatedExpression();
if (consequent.isConditional()) {
res.setOptions(consequent.options);
} else {
res.setOptions([consequent]);
}
if (alternate.isConditional()) {
res.addOptions(alternate.options);
} else {
res.addOptions([alternate]);
}
} else {
res = this.evaluateExpression(
conditionValue ? expr.consequent : expr.alternate
);
if (condition.couldHaveSideEffects()) res.setSideEffects();
}
res.setRange(expr.range);
return res;
});
this.hooks.evaluate
.for("ArrayExpression")
.tap("JavascriptParser", _expr => {
const expr = /** @type {ArrayExpression} */ (_expr);
const items = expr.elements.map(element => {
return (
element !== null &&
element.type !== "SpreadElement" &&
this.evaluateExpression(element)
);
});
if (!items.every(Boolean)) return;
return new BasicEvaluatedExpression()
.setItems(items)
.setRange(expr.range);
});
this.hooks.evaluate
.for("ChainExpression")
.tap("JavascriptParser", _expr => {
const expr = /** @type {ChainExpression} */ (_expr);
/** @type {Expression[]} */
const optionalExpressionsStack = [];
/** @type {Expression|Super} */
let next = expr.expression;
while (
next.type === "MemberExpression" ||
next.type === "CallExpression"
) {
if (next.type === "MemberExpression") {
if (next.optional) {
// SuperNode can not be optional
optionalExpressionsStack.push(
/** @type {Expression} */ (next.object)
);
}
next = next.object;
} else {
if (next.optional) {
// SuperNode can not be optional
optionalExpressionsStack.push(
/** @type {Expression} */ (next.callee)
);
}
next = next.callee;
}
}
while (optionalExpressionsStack.length > 0) {
const expression = optionalExpressionsStack.pop();
const evaluated = this.evaluateExpression(expression);
if (evaluated.asNullish()) {
return evaluated.setRange(_expr.range);
}
}
return this.evaluateExpression(expr.expression);
});
}
/**
* @param {Expression} node node
* @returns {Set<string>|undefined} destructured identifiers
*/
destructuringAssignmentPropertiesFor(node) {
if (!this.destructuringAssignmentProperties) return undefined;
return this.destructuringAssignmentProperties.get(node);
}
/**
* @param {Expression} expr expression
* @returns {string | VariableInfoInterface | undefined} identifier
*/
getRenameIdentifier(expr) {
const result = this.evaluateExpression(expr);
if (result.isIdentifier()) {
return result.identifier;
}
}
/**
* @param {ClassExpression | ClassDeclaration} classy a class node
* @returns {void}
*/
walkClass(classy) {
if (classy.superClass) {
if (!this.hooks.classExtendsExpression.call(classy.superClass, classy)) {
this.walkExpression(classy.superClass);
}
}
if (classy.body && classy.body.type === "ClassBody") {
const scopeParams = [];
// Add class name in scope for recursive calls
if (classy.id) {
scopeParams.push(classy.id);
}
this.inClassScope(true, scopeParams, () => {
for (const classElement of /** @type {TODO} */ (classy.body.body)) {
if (!this.hooks.classBodyElement.call(classElement, classy)) {
if (classElement.computed && classElement.key) {
this.walkExpression(classElement.key);
}
if (classElement.value) {
if (
!this.hooks.classBodyValue.call(
classElement.value,
classElement,
classy
)
) {
const wasTopLevel = this.scope.topLevelScope;
this.scope.topLevelScope = false;
this.walkExpression(classElement.value);
this.scope.topLevelScope = wasTopLevel;
}
} else if (classElement.type === "StaticBlock") {
const wasTopLevel = this.scope.topLevelScope;
this.scope.topLevelScope = false;
this.walkBlockStatement(classElement);
this.scope.topLevelScope = wasTopLevel;
}
}
}
});
}
}
/**
* Pre walking iterates the scope for variable declarations
*
* @param {(Statement | ModuleDeclaration)[]} statements statements
*/
preWalkStatements(statements) {
for (let index = 0, len = statements.length; index < len; index++) {
const statement = statements[index];
this.preWalkStatement(statement);
}
}
/**
* Block pre walking iterates the scope for block variable declarations
*
* @param {(Statement | ModuleDeclaration)[]} statements statements
*/
blockPreWalkStatements(statements) {
for (let index = 0, len = statements.length; index < len; index++) {
const statement = statements[index];
this.blockPreWalkStatement(statement);
}
}
/**
* Walking iterates the statements and expressions and processes them
*
* @param {(Statement | ModuleDeclaration)[]} statements statements
*/
walkStatements(statements) {
for (let index = 0, len = statements.length; index < len; index++) {
const statement = statements[index];
this.walkStatement(statement);
}
}
/**
* Walking iterates the statements and expressions and processes them
*
* @param {Statement | ModuleDeclaration} statement statement
*/
preWalkStatement(statement) {
this.statementPath.push(statement);
if (this.hooks.preStatement.call(statement)) {
this.prevStatement = this.statementPath.pop();
return;
}
switch (statement.type) {
case "BlockStatement":
this.preWalkBlockStatement(statement);
break;
case "DoWhileStatement":
this.preWalkDoWhileStatement(statement);
break;
case "ForInStatement":
this.preWalkForInStatement(statement);
break;
case "ForOfStatement":
this.preWalkForOfStatement(statement);
break;
case "ForStatement":
this.preWalkForStatement(statement);
break;
case "FunctionDeclaration":
this.preWalkFunctionDeclaration(statement);
break;
case "IfStatement":
this.preWalkIfStatement(statement);
break;
case "LabeledStatement":
this.preWalkLabeledStatement(statement);
break;
case "SwitchStatement":
this.preWalkSwitchStatement(statement);
break;
case "TryStatement":
this.preWalkTryStatement(statement);
break;
case "VariableDeclaration":
this.preWalkVariableDeclaration(statement);
break;
case "WhileStatement":
this.preWalkWhileStatement(statement);
break;
case "WithStatement":
this.preWalkWithStatement(statement);
break;
}
this.prevStatement = this.statementPath.pop();
}
/**
* @param {Statement | ModuleDeclaration} statement statement
*/
blockPreWalkStatement(statement) {
this.statementPath.push(statement);
if (this.hooks.blockPreStatement.call(statement)) {
this.prevStatement = this.statementPath.pop();
return;
}
switch (statement.type) {
case "ImportDeclaration":
this.blockPreWalkImportDeclaration(statement);
break;
case "ExportAllDeclaration":
this.blockPreWalkExportAllDeclaration(statement);
break;
case "ExportDefaultDeclaration":
this.blockPreWalkExportDefaultDeclaration(statement);
break;
case "ExportNamedDeclaration":
this.blockPreWalkExportNamedDeclaration(statement);
break;
case "VariableDeclaration":
this.blockPreWalkVariableDeclaration(statement);
break;
case "ClassDeclaration":
this.blockPreWalkClassDeclaration(statement);
break;
case "ExpressionStatement":
this.blockPreWalkExpressionStatement(statement);
}
this.prevStatement = this.statementPath.pop();
}
/**
* @param {Statement | ModuleDeclaration} statement statement
*/
walkStatement(statement) {
this.statementPath.push(statement);
if (this.hooks.statement.call(statement) !== undefined) {
this.prevStatement = this.statementPath.pop();
return;
}
switch (statement.type) {
case "BlockStatement":
this.walkBlockStatement(statement);
break;
case "ClassDeclaration":
this.walkClassDeclaration(statement);
break;
case "DoWhileStatement":
this.walkDoWhileStatement(statement);
break;
case "ExportDefaultDeclaration":
this.walkExportDefaultDeclaration(statement);
break;
case "ExportNamedDeclaration":
this.walkExportNamedDeclaration(statement);
break;
case "ExpressionStatement":
this.walkExpressionStatement(statement);
break;
case "ForInStatement":
this.walkForInStatement(statement);
break;
case "ForOfStatement":
this.walkForOfStatement(statement);
break;
case "ForStatement":
this.walkForStatement(statement);
break;
case "FunctionDeclaration":
this.walkFunctionDeclaration(statement);
break;
case "IfStatement":
this.walkIfStatement(statement);
break;
case "LabeledStatement":
this.walkLabeledStatement(statement);
break;
case "ReturnStatement":
this.walkReturnStatement(statement);
break;
case "SwitchStatement":
this.walkSwitchStatement(statement);
break;
case "ThrowStatement":
this.walkThrowStatement(statement);
break;
case "TryStatement":
this.walkTryStatement(statement);
break;
case "VariableDeclaration":
this.walkVariableDeclaration(statement);
break;
case "WhileStatement":
this.walkWhileStatement(statement);
break;
case "WithStatement":
this.walkWithStatement(statement);
break;
}
this.prevStatement = this.statementPath.pop();
}
/**
* Walks a statements that is nested within a parent statement
* and can potentially be a non-block statement.
* This enforces the nested statement to never be in ASI position.
*
* @param {Statement} statement the nested statement
*/
walkNestedStatement(statement) {
this.prevStatement = undefined;
this.walkStatement(statement);
}
// Real Statements
/**
* @param {BlockStatement} statement block statement
*/
preWalkBlockStatement(statement) {
this.preWalkStatements(statement.body);
}
/**
* @param {BlockStatement} statement block statement
*/
walkBlockStatement(statement) {
this.inBlockScope(() => {
const body = statement.body;
const prev = this.prevStatement;
this.blockPreWalkStatements(body);
this.prevStatement = prev;
this.walkStatements(body);
});
}
/**
* @param {ExpressionStatement} statement expression statement
*/
walkExpressionStatement(statement) {
this.walkExpression(statement.expression);
}
/**
* @param {IfStatement} statement if statement
*/
preWalkIfStatement(statement) {
this.preWalkStatement(statement.consequent);
if (statement.alternate) {
this.preWalkStatement(statement.alternate);
}
}
/**
* @param {IfStatement} statement if statement
*/
walkIfStatement(statement) {
const result = this.hooks.statementIf.call(statement);
if (result === undefined) {
this.walkExpression(statement.test);
this.walkNestedStatement(statement.consequent);
if (statement.alternate) {
this.walkNestedStatement(statement.alternate);
}
} else {
if (result) {
this.walkNestedStatement(statement.consequent);
} else if (statement.alternate) {
this.walkNestedStatement(statement.alternate);
}
}
}
/**
* @param {LabeledStatement} statement with statement
*/
preWalkLabeledStatement(statement) {
this.preWalkStatement(statement.body);
}
/**
* @param {LabeledStatement} statement with statement
*/
walkLabeledStatement(statement) {
const hook = this.hooks.label.get(statement.label.name);
if (hook !== undefined) {
const result = hook.call(statement);
if (result === true) return;
}
this.walkNestedStatement(statement.body);
}
/**
* @param {WithStatement} statement with statement
*/
preWalkWithStatement(statement) {
this.preWalkStatement(statement.body);
}
/**
* @param {WithStatement} statement with statement
*/
walkWithStatement(statement) {
this.walkExpression(statement.object);
this.walkNestedStatement(statement.body);
}
/**
* @param {SwitchStatement} statement switch statement
*/
preWalkSwitchStatement(statement) {
this.preWalkSwitchCases(statement.cases);
}
/**
* @param {SwitchStatement} statement switch statement
*/
walkSwitchStatement(statement) {
this.walkExpression(statement.discriminant);
this.walkSwitchCases(statement.cases);
}
/**
* @param {ReturnStatement | ThrowStatement} statement return or throw statement
*/
walkTerminatingStatement(statement) {
if (statement.argument) this.walkExpression(statement.argument);
}
/**
* @param {ReturnStatement} statement return statement
*/
walkReturnStatement(statement) {
this.walkTerminatingStatement(statement);
}
/**
* @param {ThrowStatement} statement return statement
*/
walkThrowStatement(statement) {
this.walkTerminatingStatement(statement);
}
/**
* @param {TryStatement} statement try statement
*/
preWalkTryStatement(statement) {
this.preWalkStatement(statement.block);
if (statement.handler) this.preWalkCatchClause(statement.handler);
if (statement.finalizer) this.preWalkStatement(statement.finalizer);
}
/**
* @param {TryStatement} statement try statement
*/
walkTryStatement(statement) {
if (this.scope.inTry) {
this.walkStatement(statement.block);
} else {
this.scope.inTry = true;
this.walkStatement(statement.block);
this.scope.inTry = false;
}
if (statement.handler) this.walkCatchClause(statement.handler);
if (statement.finalizer) this.walkStatement(statement.finalizer);
}
/**
* @param {WhileStatement} statement while statement
*/
preWalkWhileStatement(statement) {
this.preWalkStatement(statement.body);
}
/**
* @param {WhileStatement} statement while statement
*/
walkWhileStatement(statement) {
this.walkExpression(statement.test);
this.walkNestedStatement(statement.body);
}
/**
* @param {DoWhileStatement} statement do while statement
*/
preWalkDoWhileStatement(statement) {
this.preWalkStatement(statement.body);
}
/**
* @param {DoWhileStatement} statement do while statement
*/
walkDoWhileStatement(statement) {
this.walkNestedStatement(statement.body);
this.walkExpression(statement.test);
}
/**
* @param {ForStatement} statement for statement
*/
preWalkForStatement(statement) {
if (statement.init) {
if (statement.init.type === "VariableDeclaration") {
this.preWalkStatement(statement.init);
}
}
this.preWalkStatement(statement.body);
}
/**
* @param {ForStatement} statement for statement
*/
walkForStatement(statement) {
this.inBlockScope(() => {
if (statement.init) {
if (statement.init.type === "VariableDeclaration") {
this.blockPreWalkVariableDeclaration(statement.init);
this.prevStatement = undefined;
this.walkStatement(statement.init);
} else {
this.walkExpression(statement.init);
}
}
if (statement.test) {
this.walkExpression(statement.test);
}
if (statement.update) {
this.walkExpression(statement.update);
}
const body = statement.body;
if (body.type === "BlockStatement") {
// no need to add additional scope
const prev = this.prevStatement;
this.blockPreWalkStatements(body.body);
this.prevStatement = prev;
this.walkStatements(body.body);
} else {
this.walkNestedStatement(body);
}
});
}
/**
* @param {ForInStatement} statement for statement
*/
preWalkForInStatement(statement) {
if (statement.left.type === "VariableDeclaration") {
this.preWalkVariableDeclaration(statement.left);
}
this.preWalkStatement(statement.body);
}
/**
* @param {ForInStatement} statement for statement
*/
walkForInStatement(statement) {
this.inBlockScope(() => {
if (statement.left.type === "VariableDeclaration") {
this.blockPreWalkVariableDeclaration(statement.left);
this.walkVariableDeclaration(statement.left);
} else {
this.walkPattern(statement.left);
}
this.walkExpression(statement.right);
const body = statement.body;
if (body.type === "BlockStatement") {
// no need to add additional scope
const prev = this.prevStatement;
this.blockPreWalkStatements(body.body);
this.prevStatement = prev;
this.walkStatements(body.body);
} else {
this.walkNestedStatement(body);
}
});
}
preWalkForOfStatement(statement) {
if (statement.await && this.scope.topLevelScope === true) {
this.hooks.topLevelAwait.call(statement);
}
if (statement.left.type === "VariableDeclaration") {
this.preWalkVariableDeclaration(statement.left);
}
this.preWalkStatement(statement.body);
}
/**
* @param {ForOfStatement} statement for statement
*/
walkForOfStatement(statement) {
this.inBlockScope(() => {
if (statement.left.type === "VariableDeclaration") {
this.blockPreWalkVariableDeclaration(statement.left);
this.walkVariableDeclaration(statement.left);
} else {
this.walkPattern(statement.left);
}
this.walkExpression(statement.right);
const body = statement.body;
if (body.type === "BlockStatement") {
// no need to add additional scope
const prev = this.prevStatement;
this.blockPreWalkStatements(body.body);
this.prevStatement = prev;
this.walkStatements(body.body);
} else {
this.walkNestedStatement(body);
}
});
}
/**
* @param {FunctionDeclaration} statement function declaration
*/
preWalkFunctionDeclaration(statement) {
if (statement.id) {
this.defineVariable(statement.id.name);
}
}
/**
* @param {FunctionDeclaration} statement function declaration
*/
walkFunctionDeclaration(statement) {
const wasTopLevel = this.scope.topLevelScope;
this.scope.topLevelScope = false;
this.inFunctionScope(true, statement.params, () => {
for (const param of statement.params) {
this.walkPattern(param);
}
if (statement.body.type === "BlockStatement") {
this.detectMode(statement.body.body);
const prev = this.prevStatement;
this.preWalkStatement(statement.body);
this.prevStatement = prev;
this.walkStatement(statement.body);
} else {
this.walkExpression(statement.body);
}
});
this.scope.topLevelScope = wasTopLevel;
}
/**
* @param {ExpressionStatement} statement expression statement
*/
blockPreWalkExpressionStatement(statement) {
const expression = statement.expression;
switch (expression.type) {
case "AssignmentExpression":
this.preWalkAssignmentExpression(expression);
}
}
/**
* @param {AssignmentExpression} expression assignment expression
*/
preWalkAssignmentExpression(expression) {
if (
expression.left.type !== "ObjectPattern" ||
!this.destructuringAssignmentProperties
)
return;
const keys = this._preWalkObjectPattern(expression.left);
if (!keys) return;
// check multiple assignments
if (this.destructuringAssignmentProperties.has(expression)) {
const set = this.destructuringAssignmentProperties.get(expression);
this.destructuringAssignmentProperties.delete(expression);
for (const id of set) keys.add(id);
}
this.destructuringAssignmentProperties.set(
expression.right.type === "AwaitExpression"
? expression.right.argument
: expression.right,
keys
);
if (expression.right.type === "AssignmentExpression") {
this.preWalkAssignmentExpression(expression.right);
}
}
blockPreWalkImportDeclaration(statement) {
const source = statement.source.value;
this.hooks.import.call(statement, source);
for (const specifier of statement.specifiers) {
const name = specifier.local.name;
switch (specifier.type) {
case "ImportDefaultSpecifier":
if (
!this.hooks.importSpecifier.call(statement, source, "default", name)
) {
this.defineVariable(name);
}
break;
case "ImportSpecifier":
if (
!this.hooks.importSpecifier.call(
statement,
source,
specifier.imported.name || specifier.imported.value,
name
)
) {
this.defineVariable(name);
}
break;
case "ImportNamespaceSpecifier":
if (!this.hooks.importSpecifier.call(statement, source, null, name)) {
this.defineVariable(name);
}
break;
default:
this.defineVariable(name);
}
}
}
enterDeclaration(declaration, onIdent) {
switch (declaration.type) {
case "VariableDeclaration":
for (const declarator of declaration.declarations) {
switch (declarator.type) {
case "VariableDeclarator": {
this.enterPattern(declarator.id, onIdent);
break;
}
}
}
break;
case "FunctionDeclaration":
this.enterPattern(declaration.id, onIdent);
break;
case "ClassDeclaration":
this.enterPattern(declaration.id, onIdent);
break;
}
}
blockPreWalkExportNamedDeclaration(statement) {
let source;
if (statement.source) {
source = statement.source.value;
this.hooks.exportImport.call(statement, source);
} else {
this.hooks.export.call(statement);
}
if (statement.declaration) {
if (
!this.hooks.exportDeclaration.call(statement, statement.declaration)
) {
const prev = this.prevStatement;
this.preWalkStatement(statement.declaration);
this.prevStatement = prev;
this.blockPreWalkStatement(statement.declaration);
let index = 0;
this.enterDeclaration(statement.declaration, def => {
this.hooks.exportSpecifier.call(statement, def, def, index++);
});
}
}
if (statement.specifiers) {
for (
let specifierIndex = 0;
specifierIndex < statement.specifiers.length;
specifierIndex++
) {
const specifier = statement.specifiers[specifierIndex];
switch (specifier.type) {
case "ExportSpecifier": {
const name = specifier.exported.name || specifier.exported.value;
if (source) {
this.hooks.exportImportSpecifier.call(
statement,
source,
specifier.local.name,
name,
specifierIndex
);
} else {
this.hooks.exportSpecifier.call(
statement,
specifier.local.name,
name,
specifierIndex
);
}
break;
}
}
}
}
}
/**
* @param {ExportNamedDeclaration} statement the statement
*/
walkExportNamedDeclaration(statement) {
if (statement.declaration) {
this.walkStatement(statement.declaration);
}
}
blockPreWalkExportDefaultDeclaration(statement) {
const prev = this.prevStatement;
this.preWalkStatement(statement.declaration);
this.prevStatement = prev;
this.blockPreWalkStatement(statement.declaration);
if (
statement.declaration.id &&
statement.declaration.type !== "FunctionExpression" &&
statement.declaration.type !== "ClassExpression"
) {
this.hooks.exportSpecifier.call(
statement,
statement.declaration.id.name,
"default",
undefined
);
}
}
walkExportDefaultDeclaration(statement) {
this.hooks.export.call(statement);
if (
statement.declaration.id &&
statement.declaration.type !== "FunctionExpression" &&
statement.declaration.type !== "ClassExpression"
) {
if (
!this.hooks.exportDeclaration.call(statement, statement.declaration)
) {
this.walkStatement(statement.declaration);
}
} else {
// Acorn parses `export default function() {}` as `FunctionDeclaration` and
// `export default class {}` as `ClassDeclaration`, both with `id = null`.
// These nodes must be treated as expressions.
if (
statement.declaration.type === "FunctionDeclaration" ||
statement.declaration.type === "ClassDeclaration"
) {
this.walkStatement(statement.declaration);
} else {
this.walkExpression(statement.declaration);
}
if (!this.hooks.exportExpression.call(statement, statement.declaration)) {
this.hooks.exportSpecifier.call(
statement,
statement.declaration,
"default",
undefined
);
}
}
}
blockPreWalkExportAllDeclaration(statement) {
const source = statement.source.value;
const name = statement.exported ? statement.exported.name : null;
this.hooks.exportImport.call(statement, source);
this.hooks.exportImportSpecifier.call(statement, source, null, name, 0);
}
/**
* @param {VariableDeclaration} statement variable declaration
*/
preWalkVariableDeclaration(statement) {
if (statement.kind !== "var") return;
this._preWalkVariableDeclaration(statement, this.hooks.varDeclarationVar);
}
/**
* @param {VariableDeclaration} statement variable declaration
*/
blockPreWalkVariableDeclaration(statement) {
if (statement.kind === "var") return;
const hookMap =
statement.kind === "const"
? this.hooks.varDeclarationConst
: this.hooks.varDeclarationLet;
this._preWalkVariableDeclaration(statement, hookMap);
}
/**
* @param {VariableDeclaration} statement variable declaration
* @param {TODO} hookMap map of hooks
*/
_preWalkVariableDeclaration(statement, hookMap) {
for (const declarator of statement.declarations) {
switch (declarator.type) {
case "VariableDeclarator": {
this.preWalkVariableDeclarator(declarator);
if (!this.hooks.preDeclarator.call(declarator, statement)) {
this.enterPattern(declarator.id, (name, decl) => {
let hook = hookMap.get(name);
if (hook === undefined || !hook.call(decl)) {
hook = this.hooks.varDeclaration.get(name);
if (hook === undefined || !hook.call(decl)) {
this.defineVariable(name);
}
}
});
}
break;
}
}
}
}
_preWalkObjectPattern(objectPattern) {
const ids = new Set();
const properties = objectPattern.properties;
for (let i = 0; i < properties.length; i++) {
const property = properties[i];
if (property.type !== "Property") return;
const key = property.key;
if (key.type === "Identifier") {
ids.add(key.name);
} else {
const id = this.evaluateExpression(key);
const str = id.asString();
if (str) {
ids.add(str);
} else {
// could not evaluate key
return;
}
}
}
return ids;
}
/**
* @param {VariableDeclarator} declarator variable declarator
*/
preWalkVariableDeclarator(declarator) {
if (
!declarator.init ||
declarator.id.type !== "ObjectPattern" ||
!this.destructuringAssignmentProperties
)
return;
const keys = this._preWalkObjectPattern(declarator.id);
if (!keys) return;
this.destructuringAssignmentProperties.set(
declarator.init.type === "AwaitExpression"
? declarator.init.argument
: declarator.init,
keys
);
if (declarator.init.type === "AssignmentExpression") {
this.preWalkAssignmentExpression(declarator.init);
}
}
/**
* @param {VariableDeclaration} statement variable declaration
*/
walkVariableDeclaration(statement) {
for (const declarator of statement.declarations) {
switch (declarator.type) {
case "VariableDeclarator": {
const renameIdentifier =
declarator.init && this.getRenameIdentifier(declarator.init);
if (renameIdentifier && declarator.id.type === "Identifier") {
const hook = this.hooks.canRename.get(renameIdentifier);
if (hook !== undefined && hook.call(declarator.init)) {
// renaming with "var a = b;"
const hook = this.hooks.rename.get(renameIdentifier);
if (hook === undefined || !hook.call(declarator.init)) {
this.setVariable(declarator.id.name, renameIdentifier);
}
break;
}
}
if (!this.hooks.declarator.call(declarator, statement)) {
this.walkPattern(declarator.id);
if (declarator.init) this.walkExpression(declarator.init);
}
break;
}
}
}
}
/**
* @param {ClassDeclaration} statement class declaration
*/
blockPreWalkClassDeclaration(statement) {
if (statement.id) {
this.defineVariable(statement.id.name);
}
}
/**
* @param {ClassDeclaration} statement class declaration
*/
walkClassDeclaration(statement) {
this.walkClass(statement);
}
/**
* @param {SwitchCase[]} switchCases switch statement
*/
preWalkSwitchCases(switchCases) {
for (let index = 0, len = switchCases.length; index < len; index++) {
const switchCase = switchCases[index];
this.preWalkStatements(switchCase.consequent);
}
}
/**
* @param {SwitchCase[]} switchCases switch statement
*/
walkSwitchCases(switchCases) {
this.inBlockScope(() => {
const len = switchCases.length;
// we need to pre walk all statements first since we can have invalid code
// import A from "module";
// switch(1) {
// case 1:
// console.log(A); // should fail at runtime
// case 2:
// const A = 1;
// }
for (let index = 0; index < len; index++) {
const switchCase = switchCases[index];
if (switchCase.consequent.length > 0) {
const prev = this.prevStatement;
this.blockPreWalkStatements(switchCase.consequent);
this.prevStatement = prev;
}
}
for (let index = 0; index < len; index++) {
const switchCase = switchCases[index];
if (switchCase.test) {
this.walkExpression(switchCase.test);
}
if (switchCase.consequent.length > 0) {
this.walkStatements(switchCase.consequent);
}
}
});
}
/**
* @param {CatchClause} catchClause catch clause
*/
preWalkCatchClause(catchClause) {
this.preWalkStatement(catchClause.body);
}
/**
* @param {CatchClause} catchClause catch clause
*/
walkCatchClause(catchClause) {
this.inBlockScope(() => {
// Error binding is optional in catch clause since ECMAScript 2019
if (catchClause.param !== null) {
this.enterPattern(catchClause.param, ident => {
this.defineVariable(ident);
});
this.walkPattern(catchClause.param);
}
const prev = this.prevStatement;
this.blockPreWalkStatement(catchClause.body);
this.prevStatement = prev;
this.walkStatement(catchClause.body);
});
}
/**
* @param {Pattern} pattern pattern
*/
walkPattern(pattern) {
switch (pattern.type) {
case "ArrayPattern":
this.walkArrayPattern(pattern);
break;
case "AssignmentPattern":
this.walkAssignmentPattern(pattern);
break;
case "MemberExpression":
this.walkMemberExpression(pattern);
break;
case "ObjectPattern":
this.walkObjectPattern(pattern);
break;
case "RestElement":
this.walkRestElement(pattern);
break;
}
}
/**
* @param {AssignmentPattern} pattern assignment pattern
*/
walkAssignmentPattern(pattern) {
this.walkExpression(pattern.right);
this.walkPattern(pattern.left);
}
walkObjectPattern(pattern) {
for (let i = 0, len = pattern.properties.length; i < len; i++) {
const prop = pattern.properties[i];
if (prop) {
if (prop.computed) this.walkExpression(prop.key);
if (prop.value) this.walkPattern(prop.value);
}
}
}
/**
* @param {ArrayPattern} pattern array pattern
*/
walkArrayPattern(pattern) {
for (let i = 0, len = pattern.elements.length; i < len; i++) {
const element = pattern.elements[i];
if (element) this.walkPattern(element);
}
}
/**
* @param {RestElement} pattern rest element
*/
walkRestElement(pattern) {
this.walkPattern(pattern.argument);
}
/**
* @param {(Expression | SpreadElement | null)[]} expressions expressions
*/
walkExpressions(expressions) {
for (const expression of expressions) {
if (expression) {
this.walkExpression(expression);
}
}
}
walkExpression(expression) {
switch (expression.type) {
case "ArrayExpression":
this.walkArrayExpression(expression);
break;
case "ArrowFunctionExpression":
this.walkArrowFunctionExpression(expression);
break;
case "AssignmentExpression":
this.walkAssignmentExpression(expression);
break;
case "AwaitExpression":
this.walkAwaitExpression(expression);
break;
case "BinaryExpression":
this.walkBinaryExpression(expression);
break;
case "CallExpression":
this.walkCallExpression(expression);
break;
case "ChainExpression":
this.walkChainExpression(expression);
break;
case "ClassExpression":
this.walkClassExpression(expression);
break;
case "ConditionalExpression":
this.walkConditionalExpression(expression);
break;
case "FunctionExpression":
this.walkFunctionExpression(expression);
break;
case "Identifier":
this.walkIdentifier(expression);
break;
case "ImportExpression":
this.walkImportExpression(expression);
break;
case "LogicalExpression":
this.walkLogicalExpression(expression);
break;
case "MetaProperty":
this.walkMetaProperty(expression);
break;
case "MemberExpression":
this.walkMemberExpression(expression);
break;
case "NewExpression":
this.walkNewExpression(expression);
break;
case "ObjectExpression":
this.walkObjectExpression(expression);
break;
case "SequenceExpression":
this.walkSequenceExpression(expression);
break;
case "SpreadElement":
this.walkSpreadElement(expression);
break;
case "TaggedTemplateExpression":
this.walkTaggedTemplateExpression(expression);
break;
case "TemplateLiteral":
this.walkTemplateLiteral(expression);
break;
case "ThisExpression":
this.walkThisExpression(expression);
break;
case "UnaryExpression":
this.walkUnaryExpression(expression);
break;
case "UpdateExpression":
this.walkUpdateExpression(expression);
break;
case "YieldExpression":
this.walkYieldExpression(expression);
break;
}
}
/**
* @param {AwaitExpression} expression await expression
*/
walkAwaitExpression(expression) {
if (this.scope.topLevelScope === true)
this.hooks.topLevelAwait.call(expression);
this.walkExpression(expression.argument);
}
/**
* @param {ArrayExpression} expression array expression
*/
walkArrayExpression(expression) {
if (expression.elements) {
this.walkExpressions(expression.elements);
}
}
/**
* @param {SpreadElement} expression spread element
*/
walkSpreadElement(expression) {
if (expression.argument) {
this.walkExpression(expression.argument);
}
}
/**
* @param {ObjectExpression} expression object expression
*/
walkObjectExpression(expression) {
for (
let propIndex = 0, len = expression.properties.length;
propIndex < len;
propIndex++
) {
const prop = expression.properties[propIndex];
this.walkProperty(prop);
}
}
/**
* @param {Property | SpreadElement} prop property or spread element
*/
walkProperty(prop) {
if (prop.type === "SpreadElement") {
this.walkExpression(prop.argument);
return;
}
if (prop.computed) {
this.walkExpression(prop.key);
}
if (prop.shorthand && prop.value && prop.value.type === "Identifier") {
this.scope.inShorthand = prop.value.name;
this.walkIdentifier(prop.value);
this.scope.inShorthand = false;
} else {
this.walkExpression(prop.value);
}
}
/**
* @param {FunctionExpression} expression arrow function expression
*/
walkFunctionExpression(expression) {
const wasTopLevel = this.scope.topLevelScope;
this.scope.topLevelScope = false;
const scopeParams = [...expression.params];
// Add function name in scope for recursive calls
if (expression.id) {
scopeParams.push(expression.id);
}
this.inFunctionScope(true, scopeParams, () => {
for (const param of expression.params) {
this.walkPattern(param);
}
if (expression.body.type === "BlockStatement") {
this.detectMode(expression.body.body);
const prev = this.prevStatement;
this.preWalkStatement(expression.body);
this.prevStatement = prev;
this.walkStatement(expression.body);
} else {
this.walkExpression(expression.body);
}
});
this.scope.topLevelScope = wasTopLevel;
}
/**
* @param {ArrowFunctionExpression} expression arrow function expression
*/
walkArrowFunctionExpression(expression) {
const wasTopLevel = this.scope.topLevelScope;
this.scope.topLevelScope = wasTopLevel ? "arrow" : false;
this.inFunctionScope(false, expression.params, () => {
for (const param of expression.params) {
this.walkPattern(param);
}
if (expression.body.type === "BlockStatement") {
this.detectMode(expression.body.body);
const prev = this.prevStatement;
this.preWalkStatement(expression.body);
this.prevStatement = prev;
this.walkStatement(expression.body);
} else {
this.walkExpression(expression.body);
}
});
this.scope.topLevelScope = wasTopLevel;
}
/**
* @param {SequenceExpression} expression the sequence
*/
walkSequenceExpression(expression) {
if (!expression.expressions) return;
// We treat sequence expressions like statements when they are one statement level
// This has some benefits for optimizations that only work on statement level
const currentStatement = this.statementPath[this.statementPath.length - 1];
if (
currentStatement === expression ||
(currentStatement.type === "ExpressionStatement" &&
currentStatement.expression === expression)
) {
const old = this.statementPath.pop();
for (const expr of expression.expressions) {
this.statementPath.push(expr);
this.walkExpression(expr);
this.statementPath.pop();
}
this.statementPath.push(old);
} else {
this.walkExpressions(expression.expressions);
}
}
/**
* @param {UpdateExpression} expression the update expression
*/
walkUpdateExpression(expression) {
this.walkExpression(expression.argument);
}
/**
* @param {UnaryExpression} expression the unary expression
*/
walkUnaryExpression(expression) {
if (expression.operator === "typeof") {
const result = this.callHooksForExpression(
this.hooks.typeof,
expression.argument,
expression
);
if (result === true) return;
if (expression.argument.type === "ChainExpression") {
const result = this.callHooksForExpression(
this.hooks.typeof,
expression.argument.expression,
expression
);
if (result === true) return;
}
}
this.walkExpression(expression.argument);
}
/**
* @param {LogicalExpression | BinaryExpression} expression the expression
*/
walkLeftRightExpression(expression) {
this.walkExpression(expression.left);
this.walkExpression(expression.right);
}
/**
* @param {BinaryExpression} expression the binary expression
*/
walkBinaryExpression(expression) {
if (this.hooks.binaryExpression.call(expression) === undefined) {
this.walkLeftRightExpression(expression);
}
}
/**
* @param {LogicalExpression} expression the logical expression
*/
walkLogicalExpression(expression) {
const result = this.hooks.expressionLogicalOperator.call(expression);
if (result === undefined) {
this.walkLeftRightExpression(expression);
} else {
if (result) {
this.walkExpression(expression.right);
}
}
}
/**
* @param {AssignmentExpression} expression assignment expression
*/
walkAssignmentExpression(expression) {
if (expression.left.type === "Identifier") {
const renameIdentifier = this.getRenameIdentifier(expression.right);
if (renameIdentifier) {
if (
this.callHooksForInfo(
this.hooks.canRename,
renameIdentifier,
expression.right
)
) {
// renaming "a = b;"
if (
!this.callHooksForInfo(
this.hooks.rename,
renameIdentifier,
expression.right
)
) {
this.setVariable(
expression.left.name,
typeof renameIdentifier === "string"
? this.getVariableInfo(renameIdentifier)
: renameIdentifier
);
}
return;
}
}
this.walkExpression(expression.right);
this.enterPattern(expression.left, (name, decl) => {
if (!this.callHooksForName(this.hooks.assign, name, expression)) {
this.walkExpression(expression.left);
}
});
return;
}
if (expression.left.type.endsWith("Pattern")) {
this.walkExpression(expression.right);
this.enterPattern(expression.left, (name, decl) => {
if (!this.callHooksForName(this.hooks.assign, name, expression)) {
this.defineVariable(name);
}
});
this.walkPattern(expression.left);
} else if (expression.left.type === "MemberExpression") {
const exprName = this.getMemberExpressionInfo(
expression.left,
ALLOWED_MEMBER_TYPES_EXPRESSION
);
if (exprName) {
if (
this.callHooksForInfo(
this.hooks.assignMemberChain,
exprName.rootInfo,
expression,
exprName.getMembers()
)
) {
return;
}
}
this.walkExpression(expression.right);
this.walkExpression(expression.left);
} else {
this.walkExpression(expression.right);
this.walkExpression(expression.left);
}
}
/**
* @param {ConditionalExpression} expression conditional expression
*/
walkConditionalExpression(expression) {
const result = this.hooks.expressionConditionalOperator.call(expression);
if (result === undefined) {
this.walkExpression(expression.test);
this.walkExpression(expression.consequent);
if (expression.alternate) {
this.walkExpression(expression.alternate);
}
} else {
if (result) {
this.walkExpression(expression.consequent);
} else if (expression.alternate) {
this.walkExpression(expression.alternate);
}
}
}
/**
* @param {NewExpression} expression new expression
*/
walkNewExpression(expression) {
const result = this.callHooksForExpression(
this.hooks.new,
expression.callee,
expression
);
if (result === true) return;
this.walkExpression(expression.callee);
if (expression.arguments) {
this.walkExpressions(expression.arguments);
}
}
/**
* @param {YieldExpression} expression yield expression
*/
walkYieldExpression(expression) {
if (expression.argument) {
this.walkExpression(expression.argument);
}
}
/**
* @param {TemplateLiteral} expression template literal
*/
walkTemplateLiteral(expression) {
if (expression.expressions) {
this.walkExpressions(expression.expressions);
}
}
/**
* @param {TaggedTemplateExpression} expression tagged template expression
*/
walkTaggedTemplateExpression(expression) {
if (expression.tag) {
this.walkExpression(expression.tag);
}
if (expression.quasi && expression.quasi.expressions) {
this.walkExpressions(expression.quasi.expressions);
}
}
/**
* @param {ClassExpression} expression the class expression
*/
walkClassExpression(expression) {
this.walkClass(expression);
}
/**
* @param {ChainExpression} expression expression
*/
walkChainExpression(expression) {
const result = this.hooks.optionalChaining.call(expression);
if (result === undefined) {
if (expression.expression.type === "CallExpression") {
this.walkCallExpression(expression.expression);
} else {
this.walkMemberExpression(expression.expression);
}
}
}
_walkIIFE(functionExpression, options, currentThis) {
const getVarInfo = argOrThis => {
const renameIdentifier = this.getRenameIdentifier(argOrThis);
if (renameIdentifier) {
if (
this.callHooksForInfo(
this.hooks.canRename,
renameIdentifier,
argOrThis
)
) {
if (
!this.callHooksForInfo(
this.hooks.rename,
renameIdentifier,
argOrThis
)
) {
return typeof renameIdentifier === "string"
? this.getVariableInfo(renameIdentifier)
: renameIdentifier;
}
}
}
this.walkExpression(argOrThis);
};
const { params, type } = functionExpression;
const arrow = type === "ArrowFunctionExpression";
const renameThis = currentThis ? getVarInfo(currentThis) : null;
const varInfoForArgs = options.map(getVarInfo);
const wasTopLevel = this.scope.topLevelScope;
this.scope.topLevelScope = wasTopLevel && arrow ? "arrow" : false;
const scopeParams = params.filter(
(identifier, idx) => !varInfoForArgs[idx]
);
// Add function name in scope for recursive calls
if (functionExpression.id) {
scopeParams.push(functionExpression.id.name);
}
this.inFunctionScope(true, scopeParams, () => {
if (renameThis && !arrow) {
this.setVariable("this", renameThis);
}
for (let i = 0; i < varInfoForArgs.length; i++) {
const varInfo = varInfoForArgs[i];
if (!varInfo) continue;
if (!params[i] || params[i].type !== "Identifier") continue;
this.setVariable(params[i].name, varInfo);
}
if (functionExpression.body.type === "BlockStatement") {
this.detectMode(functionExpression.body.body);
const prev = this.prevStatement;
this.preWalkStatement(functionExpression.body);
this.prevStatement = prev;
this.walkStatement(functionExpression.body);
} else {
this.walkExpression(functionExpression.body);
}
});
this.scope.topLevelScope = wasTopLevel;
}
/**
* @param {ImportExpression} expression import expression
*/
walkImportExpression(expression) {
let result = this.hooks.importCall.call(expression);
if (result === true) return;
this.walkExpression(expression.source);
}
walkCallExpression(expression) {
const isSimpleFunction = fn => {
return fn.params.every(p => p.type === "Identifier");
};
if (
expression.callee.type === "MemberExpression" &&
expression.callee.object.type.endsWith("FunctionExpression") &&
!expression.callee.computed &&
(expression.callee.property.name === "call" ||
expression.callee.property.name === "bind") &&
expression.arguments.length > 0 &&
isSimpleFunction(expression.callee.object)
) {
// (function(…) { }.call/bind(?, …))
this._walkIIFE(
expression.callee.object,
expression.arguments.slice(1),
expression.arguments[0]
);
} else if (
expression.callee.type.endsWith("FunctionExpression") &&
isSimpleFunction(expression.callee)
) {
// (function(…) { }(…))
this._walkIIFE(expression.callee, expression.arguments, null);
} else {
if (expression.callee.type === "MemberExpression") {
const exprInfo = this.getMemberExpressionInfo(
expression.callee,
ALLOWED_MEMBER_TYPES_CALL_EXPRESSION
);
if (exprInfo && exprInfo.type === "call") {
const result = this.callHooksForInfo(
this.hooks.callMemberChainOfCallMemberChain,
exprInfo.rootInfo,
expression,
exprInfo.getCalleeMembers(),
exprInfo.call,
exprInfo.getMembers()
);
if (result === true) return;
}
}
const callee = this.evaluateExpression(expression.callee);
if (callee.isIdentifier()) {
const result1 = this.callHooksForInfo(
this.hooks.callMemberChain,
callee.rootInfo,
expression,
callee.getMembers(),
callee.getMembersOptionals
? callee.getMembersOptionals()
: callee.getMembers().map(() => false),
callee.getMemberRanges ? callee.getMemberRanges() : []
);
if (result1 === true) return;
const result2 = this.callHooksForInfo(
this.hooks.call,
callee.identifier,
expression
);
if (result2 === true) return;
}
if (expression.callee) {
if (expression.callee.type === "MemberExpression") {
// because of call context we need to walk the call context as expression
this.walkExpression(expression.callee.object);
if (expression.callee.computed === true)
this.walkExpression(expression.callee.property);
} else {
this.walkExpression(expression.callee);
}
}
if (expression.arguments) this.walkExpressions(expression.arguments);
}
}
/**
* @param {MemberExpression} expression member expression
*/
walkMemberExpression(expression) {
const exprInfo = this.getMemberExpressionInfo(
expression,
ALLOWED_MEMBER_TYPES_ALL
);
if (exprInfo) {
switch (exprInfo.type) {
case "expression": {
const result1 = this.callHooksForInfo(
this.hooks.expression,
exprInfo.name,
expression
);
if (result1 === true) return;
const members = exprInfo.getMembers();
const membersOptionals = exprInfo.getMembersOptionals();
const memberRanges = exprInfo.getMemberRanges();
const result2 = this.callHooksForInfo(
this.hooks.expressionMemberChain,
exprInfo.rootInfo,
expression,
members,
membersOptionals,
memberRanges
);
if (result2 === true) return;
this.walkMemberExpressionWithExpressionName(
expression,
exprInfo.name,
exprInfo.rootInfo,
members.slice(),
() =>
this.callHooksForInfo(
this.hooks.unhandledExpressionMemberChain,
exprInfo.rootInfo,
expression,
members
)
);
return;
}
case "call": {
const result = this.callHooksForInfo(
this.hooks.memberChainOfCallMemberChain,
exprInfo.rootInfo,
expression,
exprInfo.getCalleeMembers(),
exprInfo.call,
exprInfo.getMembers()
);
if (result === true) return;
// Fast skip over the member chain as we already called memberChainOfCallMemberChain
// and call computed property are literals anyway
this.walkExpression(exprInfo.call);
return;
}
}
}
this.walkExpression(expression.object);
if (expression.computed === true) this.walkExpression(expression.property);
}
walkMemberExpressionWithExpressionName(
expression,
name,
rootInfo,
members,
onUnhandled
) {
if (expression.object.type === "MemberExpression") {
// optimize the case where expression.object is a MemberExpression too.
// we can keep info here when calling walkMemberExpression directly
const property =
expression.property.name || `${expression.property.value}`;
name = name.slice(0, -property.length - 1);
members.pop();
const result = this.callHooksForInfo(
this.hooks.expression,
name,
expression.object
);
if (result === true) return;
this.walkMemberExpressionWithExpressionName(
expression.object,
name,
rootInfo,
members,
onUnhandled
);
} else if (!onUnhandled || !onUnhandled()) {
this.walkExpression(expression.object);
}
if (expression.computed === true) this.walkExpression(expression.property);
}
/**
* @param {ThisExpression} expression this expression
*/
walkThisExpression(expression) {
this.callHooksForName(this.hooks.expression, "this", expression);
}
/**
* @param {Identifier} expression identifier
*/
walkIdentifier(expression) {
this.callHooksForName(this.hooks.expression, expression.name, expression);
}
/**
* @param {MetaProperty} metaProperty meta property
*/
walkMetaProperty(metaProperty) {
this.hooks.expression.for(getRootName(metaProperty)).call(metaProperty);
}
callHooksForExpression(hookMap, expr, ...args) {
return this.callHooksForExpressionWithFallback(
hookMap,
expr,
undefined,
undefined,
...args
);
}
/**
* @template T
* @template R
* @param {HookMap<SyncBailHook<T, R>>} hookMap hooks the should be called
* @param {MemberExpression} expr expression info
* @param {function(string, string | ScopeInfo | VariableInfo, function(): string[]): any} fallback callback when variable in not handled by hooks
* @param {function(string): any} defined callback when variable is defined
* @param {AsArray<T>} args args for the hook
* @returns {R} result of hook
*/
callHooksForExpressionWithFallback(
hookMap,
expr,
fallback,
defined,
...args
) {
const exprName = this.getMemberExpressionInfo(
expr,
ALLOWED_MEMBER_TYPES_EXPRESSION
);
if (exprName !== undefined) {
const members = exprName.getMembers();
return this.callHooksForInfoWithFallback(
hookMap,
members.length === 0 ? exprName.rootInfo : exprName.name,
fallback &&
(name => fallback(name, exprName.rootInfo, exprName.getMembers)),
defined && (() => defined(exprName.name)),
...args
);
}
}
/**
* @template T
* @template R
* @param {HookMap<SyncBailHook<T, R>>} hookMap hooks the should be called
* @param {string} name key in map
* @param {AsArray<T>} args args for the hook
* @returns {R} result of hook
*/
callHooksForName(hookMap, name, ...args) {
return this.callHooksForNameWithFallback(
hookMap,
name,
undefined,
undefined,
...args
);
}
/**
* @template T
* @template R
* @param {HookMap<SyncBailHook<T, R>>} hookMap hooks that should be called
* @param {ExportedVariableInfo} info variable info
* @param {AsArray<T>} args args for the hook
* @returns {R} result of hook
*/
callHooksForInfo(hookMap, info, ...args) {
return this.callHooksForInfoWithFallback(
hookMap,
info,
undefined,
undefined,
...args
);
}
/**
* @template T
* @template R
* @param {HookMap<SyncBailHook<T, R>>} hookMap hooks the should be called
* @param {ExportedVariableInfo} info variable info
* @param {function(string): any} fallback callback when variable in not handled by hooks
* @param {function(): any} defined callback when variable is defined
* @param {AsArray<T>} args args for the hook
* @returns {R} result of hook
*/
callHooksForInfoWithFallback(hookMap, info, fallback, defined, ...args) {
let name;
if (typeof info === "string") {
name = info;
} else {
if (!(info instanceof VariableInfo)) {
if (defined !== undefined) {
return defined();
}
return;
}
let tagInfo = info.tagInfo;
while (tagInfo !== undefined) {
const hook = hookMap.get(tagInfo.tag);
if (hook !== undefined) {
this.currentTagData = tagInfo.data;
const result = hook.call(...args);
this.currentTagData = undefined;
if (result !== undefined) return result;
}
tagInfo = tagInfo.next;
}
if (info.freeName === true) {
if (defined !== undefined) {
return defined();
}
return;
}
name = info.freeName;
}
const hook = hookMap.get(name);
if (hook !== undefined) {
const result = hook.call(...args);
if (result !== undefined) return result;
}
if (fallback !== undefined) {
return fallback(name);
}
}
/**
* @template T
* @template R
* @param {HookMap<SyncBailHook<T, R>>} hookMap hooks the should be called
* @param {string} name key in map
* @param {function(string): any} fallback callback when variable in not handled by hooks
* @param {function(): any} defined callback when variable is defined
* @param {AsArray<T>} args args for the hook
* @returns {R} result of hook
*/
callHooksForNameWithFallback(hookMap, name, fallback, defined, ...args) {
return this.callHooksForInfoWithFallback(
hookMap,
this.getVariableInfo(name),
fallback,
defined,
...args
);
}
/**
* @deprecated
* @param {any} params scope params
* @param {function(): void} fn inner function
* @returns {void}
*/
inScope(params, fn) {
const oldScope = this.scope;
this.scope = {
topLevelScope: oldScope.topLevelScope,
inTry: false,
inShorthand: false,
isStrict: oldScope.isStrict,
isAsmJs: oldScope.isAsmJs,
definitions: oldScope.definitions.createChild()
};
this.undefineVariable("this");
this.enterPatterns(params, (ident, pattern) => {
this.defineVariable(ident);
});
fn();
this.scope = oldScope;
}
inClassScope(hasThis, params, fn) {
const oldScope = this.scope;
this.scope = {
topLevelScope: oldScope.topLevelScope,
inTry: false,
inShorthand: false,
isStrict: oldScope.isStrict,
isAsmJs: oldScope.isAsmJs,
definitions: oldScope.definitions.createChild()
};
if (hasThis) {
this.undefineVariable("this");
}
this.enterPatterns(params, (ident, pattern) => {
this.defineVariable(ident);
});
fn();
this.scope = oldScope;
}
inFunctionScope(hasThis, params, fn) {
const oldScope = this.scope;
this.scope = {
topLevelScope: oldScope.topLevelScope,
inTry: false,
inShorthand: false,
isStrict: oldScope.isStrict,
isAsmJs: oldScope.isAsmJs,
definitions: oldScope.definitions.createChild()
};
if (hasThis) {
this.undefineVariable("this");
}
this.enterPatterns(params, (ident, pattern) => {
this.defineVariable(ident);
});
fn();
this.scope = oldScope;
}
inBlockScope(fn) {
const oldScope = this.scope;
this.scope = {
topLevelScope: oldScope.topLevelScope,
inTry: oldScope.inTry,
inShorthand: false,
isStrict: oldScope.isStrict,
isAsmJs: oldScope.isAsmJs,
definitions: oldScope.definitions.createChild()
};
fn();
this.scope = oldScope;
}
detectMode(statements) {
const isLiteral =
statements.length >= 1 &&
statements[0].type === "ExpressionStatement" &&
statements[0].expression.type === "Literal";
if (isLiteral && statements[0].expression.value === "use strict") {
this.scope.isStrict = true;
}
if (isLiteral && statements[0].expression.value === "use asm") {
this.scope.isAsmJs = true;
}
}
enterPatterns(patterns, onIdent) {
for (const pattern of patterns) {
if (typeof pattern !== "string") {
this.enterPattern(pattern, onIdent);
} else if (pattern) {
onIdent(pattern);
}
}
}
enterPattern(pattern, onIdent) {
if (!pattern) return;
switch (pattern.type) {
case "ArrayPattern":
this.enterArrayPattern(pattern, onIdent);
break;
case "AssignmentPattern":
this.enterAssignmentPattern(pattern, onIdent);
break;
case "Identifier":
this.enterIdentifier(pattern, onIdent);
break;
case "ObjectPattern":
this.enterObjectPattern(pattern, onIdent);
break;
case "RestElement":
this.enterRestElement(pattern, onIdent);
break;
case "Property":
if (pattern.shorthand && pattern.value.type === "Identifier") {
this.scope.inShorthand = pattern.value.name;
this.enterIdentifier(pattern.value, onIdent);
this.scope.inShorthand = false;
} else {
this.enterPattern(pattern.value, onIdent);
}
break;
}
}
/**
* @param {Identifier} pattern identifier pattern
* @param {TODO} onIdent callback
*/
enterIdentifier(pattern, onIdent) {
if (!this.callHooksForName(this.hooks.pattern, pattern.name, pattern)) {
onIdent(pattern.name, pattern);
}
}
/**
* @param {ObjectPattern} pattern object pattern
* @param {TODO} onIdent callback
*/
enterObjectPattern(pattern, onIdent) {
for (
let propIndex = 0, len = pattern.properties.length;
propIndex < len;
propIndex++
) {
const prop = pattern.properties[propIndex];
this.enterPattern(prop, onIdent);
}
}
/**
* @param {ArrayPattern} pattern object pattern
* @param {TODO} onIdent callback
*/
enterArrayPattern(pattern, onIdent) {
for (
let elementIndex = 0, len = pattern.elements.length;
elementIndex < len;
elementIndex++
) {
const element = pattern.elements[elementIndex];
// TODO check on `null`?
this.enterPattern(element, onIdent);
}
}
/**
* @param {RestElement} pattern object pattern
* @param {TODO} onIdent callback
*/
enterRestElement(pattern, onIdent) {
this.enterPattern(pattern.argument, onIdent);
}
/**
* @param {AssignmentPattern} pattern object pattern
* @param {TODO} onIdent callback
*/
enterAssignmentPattern(pattern, onIdent) {
this.enterPattern(pattern.left, onIdent);
}
/**
* @param {Expression} expression expression node
* @returns {BasicEvaluatedExpression} evaluation result
*/
evaluateExpression(expression) {
try {
const hook = this.hooks.evaluate.get(expression.type);
if (hook !== undefined) {
const result = hook.call(expression);
if (result !== undefined && result !== null) {
result.setExpression(expression);
return result;
}
}
} catch (e) {
console.warn(e);
// ignore error
}
return new BasicEvaluatedExpression()
.setRange(expression.range)
.setExpression(expression);
}
/**
* @param {Expression} expression expression
* @returns {string} parsed string
*/
parseString(expression) {
switch (expression.type) {
case "BinaryExpression":
if (expression.operator === "+") {
return (
this.parseString(expression.left) +
this.parseString(expression.right)
);
}
break;
case "Literal":
return expression.value + "";
}
throw new Error(
expression.type + " is not supported as parameter for require"
);
}
parseCalculatedString(expression) {
switch (expression.type) {
case "BinaryExpression":
if (expression.operator === "+") {
const left = this.parseCalculatedString(expression.left);
const right = this.parseCalculatedString(expression.right);
if (left.code) {
return {
range: left.range,
value: left.value,
code: true,
conditional: false
};
} else if (right.code) {
return {
range: [
left.range[0],
right.range ? right.range[1] : left.range[1]
],
value: left.value + right.value,
code: true,
conditional: false
};
} else {
return {
range: [left.range[0], right.range[1]],
value: left.value + right.value,
code: false,
conditional: false
};
}
}
break;
case "ConditionalExpression": {
const consequent = this.parseCalculatedString(expression.consequent);
const alternate = this.parseCalculatedString(expression.alternate);
const items = [];
if (consequent.conditional) {
items.push(...consequent.conditional);
} else if (!consequent.code) {
items.push(consequent);
} else {
break;
}
if (alternate.conditional) {
items.push(...alternate.conditional);
} else if (!alternate.code) {
items.push(alternate);
} else {
break;
}
return {
range: undefined,
value: "",
code: true,
conditional: items
};
}
case "Literal":
return {
range: expression.range,
value: expression.value + "",
code: false,
conditional: false
};
}
return {
range: undefined,
value: "",
code: true,
conditional: false
};
}
/**
* @param {string | Buffer | PreparsedAst} source the source to parse
* @param {ParserState} state the parser state
* @returns {ParserState} the parser state
*/
parse(source, state) {
let ast;
let comments;
const semicolons = new Set();
if (source === null) {
throw new Error("source must not be null");
}
if (Buffer.isBuffer(source)) {
source = source.toString("utf-8");
}
if (typeof source === "object") {
ast = /** @type {Program} */ (source);
comments = source.comments;
} else {
comments = [];
ast = JavascriptParser._parse(source, {
sourceType: this.sourceType,
onComment: comments,
onInsertedSemicolon: pos => semicolons.add(pos)
});
}
const oldScope = this.scope;
const oldState = this.state;
const oldComments = this.comments;
const oldSemicolons = this.semicolons;
const oldStatementPath = this.statementPath;
const oldPrevStatement = this.prevStatement;
this.scope = {
topLevelScope: true,
inTry: false,
inShorthand: false,
isStrict: false,
isAsmJs: false,
definitions: new StackedMap()
};
/** @type {ParserState} */
this.state = state;
this.comments = comments;
this.semicolons = semicolons;
this.statementPath = [];
this.prevStatement = undefined;
if (this.hooks.program.call(ast, comments) === undefined) {
this.destructuringAssignmentProperties = new WeakMap();
this.detectMode(ast.body);
this.preWalkStatements(ast.body);
this.prevStatement = undefined;
this.blockPreWalkStatements(ast.body);
this.prevStatement = undefined;
this.walkStatements(ast.body);
this.destructuringAssignmentProperties = undefined;
}
this.hooks.finish.call(ast, comments);
this.scope = oldScope;
/** @type {ParserState} */
this.state = oldState;
this.comments = oldComments;
this.semicolons = oldSemicolons;
this.statementPath = oldStatementPath;
this.prevStatement = oldPrevStatement;
return state;
}
/**
* @param {string} source source code
* @returns {BasicEvaluatedExpression} evaluation result
*/
evaluate(source) {
const ast = JavascriptParser._parse("(" + source + ")", {
sourceType: this.sourceType,
locations: false
});
if (ast.body.length !== 1 || ast.body[0].type !== "ExpressionStatement") {
throw new Error("evaluate: Source is not a expression");
}
return this.evaluateExpression(ast.body[0].expression);
}
/**
* @param {Expression | Declaration | PrivateIdentifier | null | undefined} expr an expression
* @param {number} commentsStartPos source position from which annotation comments are checked
* @returns {boolean} true, when the expression is pure
*/
isPure(expr, commentsStartPos) {
if (!expr) return true;
const result = this.hooks.isPure
.for(expr.type)
.call(expr, commentsStartPos);
if (typeof result === "boolean") return result;
switch (expr.type) {
// TODO handle more cases
case "ClassDeclaration":
case "ClassExpression": {
if (expr.body.type !== "ClassBody") return false;
if (expr.superClass && !this.isPure(expr.superClass, expr.range[0])) {
return false;
}
const items =
/** @type {TODO[]} */
(expr.body.body);
return items.every(item => {
if (
item.computed &&
item.key &&
!this.isPure(item.key, item.range[0])
) {
return false;
}
if (
item.static &&
item.value &&
!this.isPure(
item.value,
item.key ? item.key.range[1] : item.range[0]
)
) {
return false;
}
if (item.type === "StaticBlock") {
return false;
}
return true;
});
}
case "FunctionDeclaration":
case "FunctionExpression":
case "ArrowFunctionExpression":
case "ThisExpression":
case "Literal":
case "TemplateLiteral":
case "Identifier":
case "PrivateIdentifier":
return true;
case "VariableDeclaration":
return expr.declarations.every(decl =>
this.isPure(decl.init, decl.range[0])
);
case "ConditionalExpression":
return (
this.isPure(expr.test, commentsStartPos) &&
this.isPure(expr.consequent, expr.test.range[1]) &&
this.isPure(expr.alternate, expr.consequent.range[1])
);
case "LogicalExpression":
return (
this.isPure(expr.left, commentsStartPos) &&
this.isPure(expr.right, expr.left.range[1])
);
case "SequenceExpression":
return expr.expressions.every(expr => {
const pureFlag = this.isPure(expr, commentsStartPos);
commentsStartPos = expr.range[1];
return pureFlag;
});
case "CallExpression": {
const pureFlag =
expr.range[0] - commentsStartPos > 12 &&
this.getComments([commentsStartPos, expr.range[0]]).some(
comment =>
comment.type === "Block" &&
/^\s*(#|@)__PURE__\s*$/.test(comment.value)
);
if (!pureFlag) return false;
commentsStartPos = expr.callee.range[1];
return expr.arguments.every(arg => {
if (arg.type === "SpreadElement") return false;
const pureFlag = this.isPure(arg, commentsStartPos);
commentsStartPos = arg.range[1];
return pureFlag;
});
}
}
const evaluated = this.evaluateExpression(expr);
return !evaluated.couldHaveSideEffects();
}
/**
* @param {Range} range range
* @returns {TODO[]} comments in the range
*/
getComments(range) {
const [rangeStart, rangeEnd] = range;
const compare = (comment, needle) => comment.range[0] - needle;
let idx = binarySearchBounds.ge(this.comments, rangeStart, compare);
let commentsInRange = [];
while (this.comments[idx] && this.comments[idx].range[1] <= rangeEnd) {
commentsInRange.push(this.comments[idx]);
idx++;
}
return commentsInRange;
}
/**
* @param {number} pos source code position
* @returns {boolean} true when a semicolon has been inserted before this position, false if not
*/
isAsiPosition(pos) {
const currentStatement = this.statementPath[this.statementPath.length - 1];
if (currentStatement === undefined) throw new Error("Not in statement");
return (
// Either asking directly for the end position of the current statement
(currentStatement.range[1] === pos && this.semicolons.has(pos)) ||
// Or asking for the start position of the current statement,
// here we have to check multiple things
(currentStatement.range[0] === pos &&
// is there a previous statement which might be relevant?
this.prevStatement !== undefined &&
// is the end position of the previous statement an ASI position?
this.semicolons.has(this.prevStatement.range[1]))
);
}
/**
* @param {number} pos source code position
* @returns {void}
*/
unsetAsiPosition(pos) {
this.semicolons.delete(pos);
}
isStatementLevelExpression(expr) {
const currentStatement = this.statementPath[this.statementPath.length - 1];
return (
expr === currentStatement ||
(currentStatement.type === "ExpressionStatement" &&
currentStatement.expression === expr)
);
}
getTagData(name, tag) {
const info = this.scope.definitions.get(name);
if (info instanceof VariableInfo) {
let tagInfo = info.tagInfo;
while (tagInfo !== undefined) {
if (tagInfo.tag === tag) return tagInfo.data;
tagInfo = tagInfo.next;
}
}
}
tagVariable(name, tag, data) {
const oldInfo = this.scope.definitions.get(name);
/** @type {VariableInfo} */
let newInfo;
if (oldInfo === undefined) {
newInfo = new VariableInfo(this.scope, name, {
tag,
data,
next: undefined
});
} else if (oldInfo instanceof VariableInfo) {
newInfo = new VariableInfo(oldInfo.declaredScope, oldInfo.freeName, {
tag,
data,
next: oldInfo.tagInfo
});
} else {
newInfo = new VariableInfo(oldInfo, true, {
tag,
data,
next: undefined
});
}
this.scope.definitions.set(name, newInfo);
}
/**
* @param {string} name variable name
*/
defineVariable(name) {
const oldInfo = this.scope.definitions.get(name);
// Don't redefine variable in same scope to keep existing tags
if (oldInfo instanceof VariableInfo && oldInfo.declaredScope === this.scope)
return;
this.scope.definitions.set(name, this.scope);
}
/**
* @param {string} name variable name
*/
undefineVariable(name) {
this.scope.definitions.delete(name);
}
/**
* @param {string} name variable name
* @returns {boolean} true, when variable is defined
*/
isVariableDefined(name) {
const info = this.scope.definitions.get(name);
if (info === undefined) return false;
if (info instanceof VariableInfo) {
return info.freeName === true;
}
return true;
}
/**
* @param {string} name variable name
* @returns {ExportedVariableInfo} info for this variable
*/
getVariableInfo(name) {
const value = this.scope.definitions.get(name);
if (value === undefined) {
return name;
} else {
return value;
}
}
/**
* @param {string} name variable name
* @param {ExportedVariableInfo} variableInfo new info for this variable
* @returns {void}
*/
setVariable(name, variableInfo) {
if (typeof variableInfo === "string") {
if (variableInfo === name) {
this.scope.definitions.delete(name);
} else {
this.scope.definitions.set(
name,
new VariableInfo(this.scope, variableInfo, undefined)
);
}
} else {
this.scope.definitions.set(name, variableInfo);
}
}
/**
* @param {TagInfo} tagInfo tag info
* @returns {VariableInfo} variable info
*/
evaluatedVariable(tagInfo) {
return new VariableInfo(this.scope, undefined, tagInfo);
}
/**
* @param {Range} range range of the comment
* @returns {TODO} TODO
*/
parseCommentOptions(range) {
const comments = this.getComments(range);
if (comments.length === 0) {
return EMPTY_COMMENT_OPTIONS;
}
let options = {};
/** @type {unknown[]} */
let errors = [];
for (const comment of comments) {
const { value } = comment;
if (value && webpackCommentRegExp.test(value)) {
// try compile only if webpack options comment is present
try {
for (let [key, val] of Object.entries(
vm.runInNewContext(`(function(){return {${value}};})()`)
)) {
if (typeof val === "object" && val !== null) {
if (val.constructor.name === "RegExp") val = new RegExp(val);
else val = JSON.parse(JSON.stringify(val));
}
options[key] = val;
}
} catch (e) {
const newErr = new Error(String(e.message));
newErr.stack = String(e.stack);
Object.assign(newErr, { comment });
errors.push(newErr);
}
}
}
return { options, errors };
}
/**
* @param {MemberExpression} expression a member expression
* @returns {{ members: string[], object: Expression | Super, membersOptionals: boolean[], memberRanges: Range[] }} member names (reverse order) and remaining object
*/
extractMemberExpressionChain(expression) {
/** @type {AnyNode} */
let expr = expression;
const members = [];
const membersOptionals = [];
const memberRanges = [];
while (expr.type === "MemberExpression") {
if (expr.computed) {
if (expr.property.type !== "Literal") break;
members.push(`${expr.property.value}`); // the literal
memberRanges.push(expr.object.range); // the range of the expression fragment before the literal
} else {
if (expr.property.type !== "Identifier") break;
members.push(expr.property.name); // the identifier
memberRanges.push(expr.object.range); // the range of the expression fragment before the identifier
}
membersOptionals.push(expr.optional);
expr = expr.object;
}
return {
members,
membersOptionals,
memberRanges,
object: expr
};
}
/**
* @param {string} varName variable name
* @returns {{name: string, info: VariableInfo | string}} name of the free variable and variable info for that
*/
getFreeInfoFromVariable(varName) {
const info = this.getVariableInfo(varName);
let name;
if (info instanceof VariableInfo) {
name = info.freeName;
if (typeof name !== "string") return undefined;
} else if (typeof info !== "string") {
return undefined;
} else {
name = info;
}
return { info, name };
}
/** @typedef {{ type: "call", call: CallExpression, calleeName: string, rootInfo: string | VariableInfo, getCalleeMembers: () => string[], name: string, getMembers: () => string[], getMembersOptionals: () => boolean[], getMemberRanges: () => Range[]}} CallExpressionInfo */
/** @typedef {{ type: "expression", rootInfo: string | VariableInfo, name: string, getMembers: () => string[], getMembersOptionals: () => boolean[], getMemberRanges: () => Range[]}} ExpressionExpressionInfo */
/**
* @param {MemberExpression} expression a member expression
* @param {number} allowedTypes which types should be returned, presented in bit mask
* @returns {CallExpressionInfo | ExpressionExpressionInfo | undefined} expression info
*/
getMemberExpressionInfo(expression, allowedTypes) {
const { object, members, membersOptionals, memberRanges } =
this.extractMemberExpressionChain(expression);
switch (object.type) {
case "CallExpression": {
if ((allowedTypes & ALLOWED_MEMBER_TYPES_CALL_EXPRESSION) === 0)
return undefined;
let callee = object.callee;
let rootMembers = EMPTY_ARRAY;
if (callee.type === "MemberExpression") {
({ object: callee, members: rootMembers } =
this.extractMemberExpressionChain(callee));
}
const rootName = getRootName(callee);
if (!rootName) return undefined;
const result = this.getFreeInfoFromVariable(rootName);
if (!result) return undefined;
const { info: rootInfo, name: resolvedRoot } = result;
const calleeName = objectAndMembersToName(resolvedRoot, rootMembers);
return {
type: "call",
call: object,
calleeName,
rootInfo,
getCalleeMembers: memoize(() => rootMembers.reverse()),
name: objectAndMembersToName(`${calleeName}()`, members),
getMembers: memoize(() => members.reverse()),
getMembersOptionals: memoize(() => membersOptionals.reverse()),
getMemberRanges: memoize(() => memberRanges.reverse())
};
}
case "Identifier":
case "MetaProperty":
case "ThisExpression": {
if ((allowedTypes & ALLOWED_MEMBER_TYPES_EXPRESSION) === 0)
return undefined;
const rootName = getRootName(object);
if (!rootName) return undefined;
const result = this.getFreeInfoFromVariable(rootName);
if (!result) return undefined;
const { info: rootInfo, name: resolvedRoot } = result;
return {
type: "expression",
name: objectAndMembersToName(resolvedRoot, members),
rootInfo,
getMembers: memoize(() => members.reverse()),
getMembersOptionals: memoize(() => membersOptionals.reverse()),
getMemberRanges: memoize(() => memberRanges.reverse())
};
}
}
}
/**
* @param {MemberExpression} expression an expression
* @returns {{ name: string, rootInfo: ExportedVariableInfo, getMembers: () => string[]}} name info
*/
getNameForExpression(expression) {
return this.getMemberExpressionInfo(
expression,
ALLOWED_MEMBER_TYPES_EXPRESSION
);
}
/**
* @param {string} code source code
* @param {ParseOptions} options parsing options
* @returns {Program} parsed ast
*/
static _parse(code, options) {
const type = options ? options.sourceType : "module";
/** @type {AcornOptions} */
const parserOptions = {
...defaultParserOptions,
allowReturnOutsideFunction: type === "script",
...options,
sourceType: type === "auto" ? "module" : type
};
/** @type {AnyNode} */
let ast;
let error;
let threw = false;
try {
ast = /** @type {AnyNode} */ (parser.parse(code, parserOptions));
} catch (e) {
error = e;
threw = true;
}
if (threw && type === "auto") {
parserOptions.sourceType = "script";
if (!("allowReturnOutsideFunction" in options)) {
parserOptions.allowReturnOutsideFunction = true;
}
if (Array.isArray(parserOptions.onComment)) {
parserOptions.onComment.length = 0;
}
try {
ast = /** @type {AnyNode} */ (parser.parse(code, parserOptions));
threw = false;
} catch (e) {
// we use the error from first parse try
// so nothing to do here
}
}
if (threw) {
throw error;
}
return /** @type {Program} */ (ast);
}
}
module.exports = JavascriptParser;
module.exports.ALLOWED_MEMBER_TYPES_ALL = ALLOWED_MEMBER_TYPES_ALL;
module.exports.ALLOWED_MEMBER_TYPES_EXPRESSION =
ALLOWED_MEMBER_TYPES_EXPRESSION;
module.exports.ALLOWED_MEMBER_TYPES_CALL_EXPRESSION =
ALLOWED_MEMBER_TYPES_CALL_EXPRESSION;