All files index.ts

44.54% Statements 1011/2270
37.62% Branches 696/1850
57.74% Functions 153/265
45.32% Lines 979/2160

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 58508x                       8x   8x               8x                                           8x 8x         8x   8x     128x                                 7x       8x   8x                                         43x                                                           17x         8x         2x     2x               131x   2x   2x   2x   1x   41x   4x   63x   2x   2x   2x   10x         17x               39x               347x       8x                     8x 141x             8x       8x           8x 8x 8x 72x 72x 72x 72x 72x 72x 72x     72x       691x 153x       153x           691x       5x                                                                                                                                                                                                                     48x 48x 48x         2x       148x                         57x                                                                 24x                                                                                                                                               101x       20x 20x                   20x       128x           148x 148x       128x                       23x   23x       108x                                                                                         68x 68x 68x 68x 68x 68x 68x 68x 68x 68x   68x           2x 2x 2x 2x       23x   23x 23x   23x   23x   23x 23x 23x         702x 702x   702x 141x 561x 96x     702x                                                                                             1537x   1537x 1537x 1537x 1537x   1537x   1514x                       45x       11x 11x                                                         17x       655x                                                           20x 20x                 1175x       491x   154x       337x           2x   2x     2x     2x 2x                                                         16x                             2202x       205x 205x 41x 41x   164x                                                                   11x   11x               11x         2x   2x           2x 2x   2x                     1x   1x   1x   1x   1x     1x   1x         1x 1x         2x   2x   2x   2x 2x 8x 8x   2x   2x 2x           1x         1x   1x         1x   1x   1x   1x           1x       2x     2x     2x         2x 2x                   2x             2x       2x       2x                             2x             2x 2x                   41x     39x   2x                                           2x 2x   2x 3x     3x   3x 3x     3x   3x 1x 1x     2x 2x                     2x       2x                   2x                                                                                                                                                                                                                                                                                     128x     128x               141x 141x 141x 141x   141x                                           24x 24x                                                       117x   117x   117x   117x                                                   19x 19x                 24x   24x   24x   24x   24x       24x                                         24x     24x 24x   24x                                                                                                                                                                                       269x   269x 269x 269x 282x     269x 259x   10x 10x                                                                                                                             3x   3x 3x               3x           3x                                                                                                                                                                                               2x 2x 2x                                                                                                                                                                                                                             10x 10x 10x     10x                             141x             3x                                               2x                                             136x 136x           136x         136x         126x 126x 126x   10x                 141x   141x 2x 2x   2x   2x 2x                       141x         141x 141x         141x         141x               128x               128x     128x     128x             128x           128x 128x   128x           128x                                                                               160x 160x 160x 160x   160x             66x           66x                                                                                                                                                                 82x           60x 60x 60x 17x   43x 43x         17x                               17x 17x               115x       115x   115x 17x     17x   17x     98x                                           98x           58x       98x           14x               98x 115x 115x         115x   17x 10x     10x 10x 10x   10x   7x               7x     7x 7x 7x 7x   7x 7x   7x     17x                                                                                             1x   1x       1x 1x 1x       1x       1x       1x         26x                                                                     26x 26x   26x                                                                                           26x 26x 26x 26x 26x 26x           26x   26x       26x                             26x                           26x 26x       26x 26x                   26x             10x 10x   26x   10x         10x 10x         10x 10x                 8x   8x   8x 8x   8x   8x             8x       8x   1x     8x 8x   8x 8x           1x 1x 1x                                       8x             13x   2x 2x   2x 2x                                         11x                                                                                                                           2x 2x 2x 2x   2x         14x 3x 3x 3x   11x               1x   1x   1x     1x               1x   1x   1x   1x             11x   11x   11x   11x       11x   11x                   11x     11x 11x                   14x   1x       1x         1x 1x 1x               1x       1x         11x       11x                 1x                                                                                                                                                                                                                                                                   23x 23x 23x       23x   23x 23x   23x 23x 23x                           23x 23x 23x 23x 23x   23x   23x     23x 23x             23x 23x 23x 23x                 43x   24x       43x         43x 6x   37x                   37x 37x       2x   2x   2x   2x                         2x 2x   2x 2x       2x 2x                 2x   2x                   139x                                                         139x                     19x 19x 19x         16x 16x                 6x 6x 6x     16x           19x 3x 3x   16x   16x   16x     19x 19x             19x                     19x       13x 13x                                   13x               13x                       13x                 13x           13x                                             13x   5x                   5x             5x     5x   2x 2x 2x   2x 3x             3x   3x   5x     8x   2x   2x   1x     1x   2x   2x     6x   6x   6x 6x             6x     12x     12x   12x         6x     6x   8x                                                       64x   64x               64x                               1x                 1x                                               140x             165x   165x 165x   1x     1x 1x 1x               1x     1x       20x 20x 20x     50x 50x   50x   50x             50x   27x     27x                         50x                         71x           2x 2x 2x 2x 2x     1x 1x 1x   1x 1x 1x 1x   1x                           5x   5x                           2x                             13x               13x 13x   13x   13x                                                                                             13x                             13x                     367x 367x 336x 31x 31x                                 367x 367x 367x   207x 207x       367x       23x 23x 23x   23x 23x   23x 20x   3x       3x     3x   23x   23x   23x       23x     23x 23x   23x 23x     23x   3x   3x                                                     3x       157x               157x 1x           156x   8x 8x     148x                       40x   40x   40x       40x                           46x       46x         8x   7x                     140x                   140x       140x   140x   140x   140x 140x                                                                                                                   2x         2x 2x   2x   2x             2x   2x     2x   2x         1x     2x             2x             10x       10x       10x       10x             20x   20x   20x                                             20x   20x             20x                     20x                       20x   20x 20x       20x   20x     20x         20x 20x 8x 8x 12x         20x     20x   20x   20x     20x       40x                 40x           40x   40x   40x 40x 40x 40x 40x       40x                   40x               40x   40x 40x                                 40x 40x                                     40x       40x               40x       40x                 40x     40x 40x 40x   2x 2x             40x   40x                 40x       40x   40x 20x 20x 20x 20x   20x   20x 20x           20x   20x 20x           40x     40x     40x     40x         10x   10x       10x                                                                 23x   23x   23x                 23x   23x                     23x 23x   16x 16x                     1x         1x                                     140x                                                                 140x   140x                                                                                                                                                                                                                                                 1x                                           1x 1x               32x 32x     32x 32x 32x 32x 32x                   32x 32x 32x 32x               32x 32x   32x 32x                         32x           32x 3x                 3x   32x   32x 32x   32x                                                                                                                               18x                                                     18x                                               3146x   3146x 3146x                   3146x 3146x                                                                                               55x             55x                                                                                             1x 1x 1x 1x   1x 1x 1x   1x     1x   1x   1x                                                                 1x 1x   1x     1x 1x       1x       1x       1x           1x   1x   1x   1x 1x                                                                                                                                 195x   195x                                         195x 195x                             195x                                                                                                                                                                                                                                   195x   195x 195x   195x   195x   34x 34x 34x         34x         34x   34x 34x 34x   34x   161x 19x   19x   19x   19x   19x   19x   19x     19x 19x       19x                                         19x   19x   19x   19x   19x 19x 19x 19x 19x   19x 142x                     195x                       10x 10x   10x       10x 10x 10x                                                                                                                                                                                                                                   10x 10x 10x 10x         10x 10x   10x 10x   10x   10x 10x 10x   10x 10x 40x 40x 40x 40x 8x     32x         10x 10x   10x   10x 10x     10x         43x   43x 32x   14x 32x     32x   32x                   32x     43x                                                                                                                                       20x 20x 20x   20x 20x 20x 20x 20x   20x 20x 20x   20x           20x   20x   20x   20x 20x 20x 20x 20x     20x                               20x       72x 72x     72x                           16x 16x     8x   8x   8x 8x   8x   13x   4x 4x   4x   4x   4x 4x 4x     9x   9x 16x   7x   7x       9x     16x 16x   16x 16x 4x           4x   12x 12x   6x     6x 6x     12x 12x     9x       6x     6x   6x 12x   6x   6x   6x     12x 12x       12x   12x 12x 4x         4x   8x   8x         8x   8x     12x           12x   6x               8x 8x   8x     8x 8x   8x   8x     2x   2x                                     2x   2x 2x                   6x   6x 6x   2x 2x   1x       4x     8x                 8x 8x   8x 8x   8x 4x           8x   2x   8x   4x              
import {
  tokTypes,
  // @ts-ignore
  keywordTypes,
  isNewLine,
  tokContexts,
  isIdentifierChar,
  Position,
  lineBreak,
  Options,
  Parser as AcornParser
} from 'acorn'
import * as charCodes from 'charcodes'
import type { Node, TokenType } from 'acorn'
import { tsKeywordsRegExp, tsTokenType, jsxTokenType } from './tokenType'
import {
  Accessibility,
  LookaheadState,
  ModifierBase, ParsingContext,
  TryParse,
  TsModifier
} from './types'
import {
  BIND_LEXICAL,
  BIND_TS_INTERFACE,
  BIND_TS_NAMESPACE,
  BIND_TS_TYPE,
  SCOPE_OTHER, SCOPE_SIMPLE_CATCH,
  SCOPE_TS_MODULE
} from './scopeflags'
import {
  ArrayExpression,
  ArrayPattern,
  ArrowFunctionExpression, BaseNode,
  Class,
  Declaration,
  Expression, FunctionDeclaration,
  Identifier,
  ObjectExpression,
  ObjectPattern,
  Pattern,
  RestElement,
  VariableDeclarator
} from 'estree'
import { skipWhiteSpaceToLineBreak } from './whitespace'
import {
  checkKeyName,
  DestructuringErrors,
  isPrivateNameConflicted
} from './parseutil'
import { TypeScriptError } from './error'
 
export const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g
 
function assert(x: boolean): void {
  Iif (!x) {
    throw new Error('Assert fail')
  }
}
 
function nextLineBreak(code, from, end = code.length) {
  for (let i = from; i < end; i++) {
    let next = code.charCodeAt(i)
    if (isNewLine(next))
      return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1
  }
  return -1
}
 
function tsIsVarianceAnnotations(
  modifier: string
): any {
  return modifier === 'in' || modifier === 'out'
}
 
// @ts-ignore
const FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4
 
const acornScope = {
  SCOPE_TOP: 1,
  SCOPE_FUNCTION: 2,
  SCOPE_ASYNC: 4,
  SCOPE_GENERATOR: 8,
  SCOPE_ARROW: 16,
  SCOPE_SIMPLE_CATCH: 32,
  SCOPE_SUPER: 64,
  SCOPE_DIRECT_SUPER: 128,
  SCOPE_CLASS_STATIC_BLOCK: 256,
  SCOPE_VAR: 256,
  BIND_NONE: 0, // Not a binding
  BIND_VAR: 1, // Var-style binding
  BIND_LEXICAL: 2, // Let- or const-style binding
  BIND_FUNCTION: 3, // Function declaration
  BIND_SIMPLE_CATCH: 4, // Simple (identifier pattern) catch binding
  BIND_OUTSIDE: 5 // Special case for function names as bound inside the
  // function
}
 
function functionFlags(async, generator) {
  return acornScope.SCOPE_FUNCTION | (async ? acornScope.SCOPE_ASYNC : 0) | (generator ? acornScope.SCOPE_GENERATOR : 0)
}
 
function isPossiblyLiteralEnum(expression: Expression): boolean {
  if (expression.type !== 'MemberExpression') return false
 
  const { computed, property } = expression
 
  if (
    computed &&
    // property.type !== 'StringLiteral' &&
    (property.type !== 'TemplateLiteral' || property.expressions.length > 0)
  ) {
    return false
  }
 
  // @ts-ignore
  return isUncomputedMemberExpressionChain(expression.object)
}
 
function isUncomputedMemberExpressionChain(expression: Expression): boolean {
  if (expression.type === 'Identifier') return true
  if (expression.type !== 'MemberExpression') return false
  if (expression.computed) return false
 
  // @ts-ignore
  return isUncomputedMemberExpressionChain(expression.object)
}
 
function tsIsAccessModifier(modifier: string): modifier is Accessibility {
  return (
    modifier === 'private' || modifier === 'public' || modifier === 'protected'
  )
}
 
export function tokenCanStartExpression(token: TokenType): boolean {
  return Boolean(token.startsExpr)
}
 
function nonNull<T>(x?: T | null): T {
  Iif (x == null) {
    throw new Error(`Unexpected ${x} value.`)
  }
  return x
}
 
// Doesn't handle "void" or "null" because those are keywords, not identifiers.
// It also doesn't handle "intrinsic", since usually it's not a keyword.
function keywordTypeFromName(
  value: string
): Node | typeof undefined {
  switch (value) {
    case 'any':
      return 'TSAnyKeyword'
    case 'boolean':
      return 'TSBooleanKeyword'
    case 'bigint':
      return 'TSBigIntKeyword'
    case 'never':
      return 'TSNeverKeyword'
    case 'number':
      return 'TSNumberKeyword'
    case 'object':
      return 'TSObjectKeyword'
    case 'string':
      return 'TSStringKeyword'
    case 'symbol':
      return 'TSSymbolKeyword'
    case 'undefined':
      return 'TSUndefinedKeyword'
    case 'unknown':
      return 'TSUnknownKeyword'
    default:
      return undefined
  }
}
 
function tokenIsLiteralPropertyName(token: TokenType): boolean {
  return [
    ...[tokTypes.name, tokTypes.string, tokTypes.num],
    ...Object.values(keywordTypes),
    ...Object.values(tsTokenType)
  ].includes(token)
}
 
function tokenIsKeywordOrIdentifier(token: TokenType): boolean {
  return [
    ...[tokTypes.name],
    ...Object.values(keywordTypes),
    ...Object.values(tsTokenType)
  ].includes(token)
}
 
function tokenIsIdentifier(token: TokenType): boolean {
  return [...Object.values(tsTokenType), tokTypes.name].includes(token)
}
 
function tokenIsTSDeclarationStart(token: TokenType): boolean {
  return [
    tsTokenType.abstract,
    tsTokenType.declare,
    tsTokenType.enum,
    tsTokenType.module,
    tsTokenType.namespace,
    tsTokenType.interface,
    tsTokenType.type
  ].includes(token)
}
 
export function tokenIsTSTypeOperator(token: TokenType): boolean {
  return [
    tsTokenType.keyof,
    tsTokenType.readonly,
    tsTokenType.unique
  ].includes(token)
}
 
export function tokenIsTemplate(token: TokenType): boolean {
  return token === tokTypes.invalidTemplate
}
 
export default function tsPlugin(options?: {
  // default false
  dts?: boolean
  // default false
  disallowAmbiguousJSXLike?: boolean
}) {
  const { dts = false, disallowAmbiguousJSXLike = false } = options || {}
  return function(Parser: typeof AcornParser) {
    return class TypeScriptParser extends Parser {
      isLookahead: boolean = false
      isAmbientContext: boolean = false
      inAbstractClass: boolean = false
      inType: boolean = false
      inDisallowConditionalTypesContext: boolean = false
      maybeInArrowParameters: boolean = false
      canStartJSXElement: boolean = false
 
      constructor(options: Options, input: string, startPos?: number) {
        super(options, input, startPos)
      }
 
      getTokenFromCode(code: number): void {
        if (this.inType) {
          Iif (code === charCodes.greaterThan) {
            // @ts-ignore
            return this.finishOp(tokTypes.relational, 1)
          }
          Iif (code === charCodes.lessThan) {
            // @ts-ignore
            return this.finishOp(tokTypes.relational, 1)
          }
        }
        // @ts-ignore
        return super.getTokenFromCode(code)
      }
 
      isAbstractClass(): boolean {
        return (
          this.ts_isContextual(tsTokenType.abstract) && this.lookahead().type === tokTypes._class
        )
      }
 
      // tryParse will clone parser state.
      // It is expensive and should be used with cautions
      tryParse<T extends Node | ReadonlyArray<Node>>(
        fn: (abort: (node?: T) => never) => T,
        oldState: LookaheadState = this.cloneCurLookaheadState()
      ):
        | TryParse<T, null, false, false, null>
        | TryParse<T | null, SyntaxError, boolean, false, LookaheadState>
        | TryParse<T | null, null, false, true, LookaheadState> {
        const abortSignal: {
          node: T | null;
        } = { node: null }
        try {
          const node = fn((node = null) => {
            abortSignal.node = node
            throw abortSignal
          })
 
          // todo we will throw error and exit the process
          // if (this.state.errors.length > oldState.errors.length) {
          //   const failState = this.state;
          //   this.state = oldState;
          //   // tokensLength should be preserved during error recovery mode
          //   // since the parser does not halt and will instead parse the
          //   // remaining tokens
          //   this.state.tokensLength = failState.tokensLength;
          //   return {
          //     node,
          //     error: failState.errors[oldState.errors.length] as ParseError<any>,
          //     thrown: false,
          //     aborted: false,
          //     failState,
          //   };
          // }
 
          return {
            node,
            error: null,
            thrown: false,
            aborted: false,
            failState: null
          }
        } catch (error) {
          const failState = this.getCurLookaheadState()
          this.setLookaheadState(oldState)
          if (error instanceof SyntaxError) {
            return {
              node: null,
              error,
              thrown: true,
              aborted: false,
              failState
            }
          }
          if (error === abortSignal) {
            return {
              node: abortSignal.node,
              error: null,
              thrown: false,
              aborted: true,
              failState
            }
          }
 
          throw error
        }
      }
 
      setOptionalParametersError(
        refExpressionErrors: any,
        resultError?: any
      ) {
        refExpressionErrors.optionalParametersLoc =
 
          resultError?.loc ?? this['startLoc']
      }
 
      // used after we have finished parsing types
      reScan_lt_gt() {
        const { type } = this
        if (type === tokTypes.relational) {
          this['pos'] -= 1
          // @ts-ignore
          this.readToken_lt_gt(this.fullCharCodeAtPos())
        }
      }
 
      reScan_lt() {
        const { type } = this
        if (type === tokTypes.bitShift) {
          this['pos'] -= 2
          // @ts-ignore
          this.finishOp(tokTypes.relational, 1)
          return tokTypes.relational
        }
        return type
      }
 
      resetEndLocation(
        node: any,
        endLoc: Position = this['lastTokEndLoc']
      ): void {
        node.end = endLoc.column
        node.loc.end = endLoc
        Iif (this.options.ranges) node.range[1] = endLoc.column
      }
 
      startNodeAtNode(type: Node): Node {
        // @ts-ignore
        return super.startNodeAt(type.start, type.loc.start)
      }
 
      nextTokenStart(): number {
        return this.nextTokenStartSince(this['pos'])
      }
 
      tsHasSomeModifiers(member: any, modifiers: readonly TsModifier[]): boolean {
        return modifiers.some(modifier => {
          if (tsIsAccessModifier(modifier)) {
            return member.accessibility === modifier
          }
          return !!member[modifier]
        })
      }
 
      tsIsStartOfStaticBlocks() {
        return (
          this.ts_isContextual(tsTokenType.static) &&
          this.lookaheadCharCode() === charCodes.leftCurlyBrace
        )
      }
 
      tsCheckForInvalidTypeCasts(items: Array<Expression | undefined | null | any>) {
        items.forEach(node => {
          if (node?.type === 'TSTypeCastExpression') {
            this.raise(node.typeAnnotation.start, TypeScriptError.UnexpectedTypeAnnotation)
          }
        })
      }
 
      atPossibleAsyncArrow(base: Expression): boolean {
        return (
          base.type === 'Identifier' &&
          base.name === 'async' &&
          // @ts-ignore
          this['lastTokEndLoc'].column === base.end &&
          // @ts-ignore
          !this.canInsertSemicolon() &&
          // check there are no escape sequences, such as \u{61}sync
          // @ts-ignore
          base.end - base.start === 5 &&
          // @ts-ignore
          base.start === this['potentialArrowAt']
        )
      }
 
      tsIsIdentifier(): boolean {
        // TODO: actually a bit more complex in TypeScript, but shouldn't matter.
        // See https://github.com/Microsoft/TypeScript/issues/15008
        return tokenIsIdentifier(this.type)
      }
 
      tsTryParseTypeOrTypePredicateAnnotation() {
        return this.match(tokTypes.colon)
          ? this.tsParseTypeOrTypePredicateAnnotation(tokTypes.colon)
          : undefined
      }
 
      tsTryParseGenericAsyncArrowFunction(
        startPos: number,
        startLoc: Position,
        forInit: boolean
      ): ArrowFunctionExpression | undefined | null {
        if (!this.match(tokTypes.relational)) {
          return undefined
        }
 
        const oldMaybeInArrowParameters = this.maybeInArrowParameters
        this.maybeInArrowParameters = true
 
        const res = this.tsTryParseAndCatch(() => {
          // @ts-ignore
          const node = this.startNodeAt(
            startPos,
            startLoc
          )
          node.typeParameters = this.tsParseTypeParameters()
          // Don't use overloaded parseFunctionParams which would look for "<" again.
          // @ts-ignore
          super.parseFunctionParams(node)
          node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation()
          // @ts-ignore
          this.expect(tokTypes.arrow)
          return node
        })
 
        this.maybeInArrowParameters = oldMaybeInArrowParameters
 
        if (!res) {
          return undefined
        }
 
        // @ts-ignore
        return super.parseArrowExpression(
          res,
          /* params are already set */ null,
          /* async */ true,
          /* forInit */forInit
        )
      }
 
      // Used when parsing type arguments from ES productions, where the first token
      // has been created without state.inType. Thus we need to rescan the lt token.
      tsParseTypeArgumentsInExpression(): Node | void {
        if (this.reScan_lt() !== tokTypes.relational) {
          return undefined
        }
        return this.tsParseTypeArguments()
      }
 
      tsInNoContext<T>(cb: () => T): T {
        const oldContext = this['context']
        this['context'] = [oldContext[0]]
        try {
          return cb()
        } finally {
          this['context'] = oldContext
        }
      }
 
      tsTryParseTypeAnnotation(): Node | undefined | null {
        return this.match(tokTypes.colon) ? this.tsParseTypeAnnotation() : undefined
      }
 
      isUnparsedContextual(nameStart: number, name: string): boolean {
        const nameEnd = nameStart + name.length
        Iif (this.input.slice(nameStart, nameEnd) === name) {
          const nextCh = this.input.charCodeAt(nameEnd)
          return !(
            isIdentifierChar(nextCh) ||
            // check if `nextCh is between 0xd800 - 0xdbff,
            // if `nextCh` is NaN, `NaN & 0xfc00` is 0, the function
            // returns true
            (nextCh & 0xfc00) === 0xd800
          )
        }
        return false
      }
 
      isAbstractConstructorSignature(): boolean {
        return (
          this.ts_isContextual(tsTokenType.abstract) && this.lookahead().type === tokTypes._new
        )
      }
 
      nextTokenStartSince(pos: number): number {
        skipWhiteSpace.lastIndex = pos
        return skipWhiteSpace.test(this.input) ? skipWhiteSpace.lastIndex : pos
      }
 
      lookaheadCharCode(): number {
        return this.input.charCodeAt(this.nextTokenStart())
      }
 
      compareLookaheadState(state: LookaheadState, state2: LookaheadState): boolean {
        for (const key of Object.keys(state)) {
          if (state[key] !== state2[key]) return false
        }
 
        return true
      }
 
      createLookaheadState() {
        this['value'] = null
        // @ts-ignore
        this['context'] = [this.curContext()]
      }
 
      getCurLookaheadState(): LookaheadState {
        return {
          pos: this['pos'],
          value: this['value'],
          type: this.type,
          start: this.start,
          end: this.end,
          context: this['context'],
          startLoc: this['startLoc'],
          lastTokEndLoc: this['lastTokEndLoc'],
          curLine: this.curLine,
          lineStart: this.lineStart,
          // @ts-ignore
          curPosition: this.curPosition
        }
      }
 
      cloneCurLookaheadState(): LookaheadState {
        return {
          // number
          pos: this['pos'],
          // str
          value: this['value'],
          // type
          type: this.type,
          // number
          start: this.start,
          // number
          end: this.end,
          // array
          context: this['context'] && this['context'].slice(),
          // Position
          startLoc: this['startLoc'],
          // Position
          lastTokEndLoc: this['lastTokEndLoc'],
          // number
          curLine: this.curLine,
          // number
          lineStart: this.lineStart,
          // Position
          // @ts-ignore
          curPosition: this.curPosition
        }
      }
 
      setLookaheadState(state: LookaheadState) {
        this['pos'] = state.pos
        this['value'] = state.value
        this.type = state.type
        this.start = state.start
        this.end = state.end
        this['context'] = state.context
        this['startLoc'] = state.startLoc
        this['lastTokEndLoc'] = state.lastTokEndLoc
        this.curLine = state.curLine
        this.lineStart = state.lineStart
        // @ts-ignore
        this.curPosition = state.curPosition
      }
 
      // Utilities
 
      tsLookAhead<T>(f: () => T): T {
        const state = this.getCurLookaheadState()
        const res = f()
        this.setLookaheadState(state)
        return res
      }
 
      lookahead(): LookaheadState {
        const oldState = this.getCurLookaheadState()
 
        this.createLookaheadState()
        this.isLookahead = true
 
        this.nextToken()
 
        this.isLookahead = false
 
        const curState = this.getCurLookaheadState()
        this.setLookaheadState(oldState)
        return curState
      }
 
      readWord() {
        // @ts-ignore
        let word = this.readWord1()
        let type = tokTypes.name
 
        if (this['keywords'].test(word)) {
          type = keywordTypes[word]
        } else if (new RegExp(tsKeywordsRegExp).test(word)) {
          type = tsTokenType[word]
        }
 
        return this.finishToken(type, word)
      }
 
      skipBlockComment() {
        let startLoc
        // @ts-ignore
        if (!this.isLookahead) startLoc = this.options.onComment && this.curPosition()
        let start = this['pos'],
          end = this.input.indexOf('*/', this['pos'] += 2)
        if (end === -1) this.raise(this['pos'] - 2, 'Unterminated comment')
        this['pos'] = end + 2
        if (this.options.locations) {
          for (let nextBreak, pos = start; (nextBreak = nextLineBreak(this.input, pos, this['pos'])) > -1;) {
            ++this.curLine
            pos = this.lineStart = nextBreak
          }
        }
 
        if (this.isLookahead) return
 
        if (this.options.onComment)
          // @ts-ignore
          this.options.onComment(true, this.input.slice(start + 2, end), start, this['pos'],
            // @ts-ignore
            startLoc, this.curPosition())
      }
 
      skipLineComment(startSkip) {
        let start = this['pos']
        let startLoc
        // @ts-ignore
        if (!this.isLookahead) startLoc = this.options.onComment && this.curPosition()
        let ch = this.input.charCodeAt(this['pos'] += startSkip)
        while (this['pos'] < this.input.length && !isNewLine(ch)) {
          ch = this.input.charCodeAt(++this['pos'])
        }
 
        if (this.isLookahead) return
 
        if (this.options.onComment)
          // @ts-ignore
          this.options.onComment(false, this.input.slice(start + startSkip, this['pos']), start, this['pos'],
            // @ts-ignore
            startLoc, this.curPosition())
      }
 
      finishToken(type: TokenType, val?: string) {
        this.end = this['pos']
        // @ts-ignore
        Eif (this.options.locations) this.endLoc = this.curPosition()
        let prevType = this.type
        this.type = type
        this['value'] = val
 
        if (!this.isLookahead) {
          // @ts-ignore
          this.updateContext(prevType)
        }
      }
 
      resetStartLocation(node: Node, start: number, startLoc: Position): void {
        node.start = start
        node.loc.start = startLoc
        if (this.options.ranges) node.range[0] = start
      }
 
      isLineTerminator(): boolean {
        // @ts-ignore
        return this.eat(tokTypes.semi) || super.canInsertSemicolon()
      }
 
      hasFollowingLineBreak(): boolean {
        skipWhiteSpaceToLineBreak.lastIndex = this.end
        return skipWhiteSpaceToLineBreak.test(this.input)
      }
 
      addExtra(
        node: Partial<Node>,
        key: string,
        value: any,
        enumerable: boolean = true
      ): void {
        if (!node) return
        // @ts-ignore
        const extra = (node.extra = node.extra || {})
        if (enumerable) {
          extra[key] = value
        } else {
          Object.defineProperty(extra, key, { enumerable, value })
        }
      }
 
      /**
       * Test if current token is a literal property name
       * https://tc39.es/ecma262/#prod-LiteralPropertyName
       * LiteralPropertyName:
       *   IdentifierName
       *   StringLiteral
       *   NumericLiteral
       *   BigIntLiteral
       */
      isLiteralPropertyName(): boolean {
        return tokenIsLiteralPropertyName(this.type)
      }
 
      hasPrecedingLineBreak(): boolean {
        return lineBreak.test(
          this.input.slice(this['lastTokEndLoc']['index'], this.start)
        )
      }
 
      createIdentifier(
        node: Omit<Identifier, 'type'>,
        name: string
      ): Identifier {
        node.name = name
        // @ts-ignore
        return this.finishNode(node, 'Identifier')
      }
 
      /**
       * Reset the start location of node to the start location of locationNode
       */
      resetStartLocationFromNode(node: Node, locationNode: Node): void {
        this.resetStartLocation(node, locationNode.start, locationNode.loc.start)
      }
 
      // This is used in flow and typescript plugin
      // Determine whether a parameter is a this param
      isThisParam(
        param: Pattern | Identifier
      ): boolean {
        return param.type === 'Identifier' && param.name === 'this'
      }
 
      isLookaheadContextual(name: string): boolean {
        const next = this.nextTokenStart()
        return this.isUnparsedContextual(next, name)
      }
 
      /**
       * ts isContextual
       * @param {TokenType} token
       * @returns {boolean}
       * */
      ts_isContextual(token: TokenType): boolean {
        return this.type === token && !this['containsEsc']
      }
 
      isContextual(keyword: string): boolean {
        switch (keyword) {
          case 'let': {
            return this.ts_isContextual(tsTokenType.let)
          }
          default: {
            // @ts-ignore
            return super.isContextual(keyword)
          }
        }
      }
 
      tsIsStartOfMappedType(): boolean {
        this.next()
        // @ts-ignore
        Iif (this.eat(tokTypes.plusMin)) {
          return this.ts_isContextual(tsTokenType.readonly)
        }
        Iif (this.ts_isContextual(tsTokenType.readonly)) {
          this.next()
        }
        Eif (!this.match(tokTypes.bracketL)) {
          return false
        }
        this.next()
        if (!this.tsIsIdentifier()) {
          return false
        }
        this.next()
        return this.match(tokTypes._in)
      }
 
      tsInDisallowConditionalTypesContext<T>(cb: () => T): T {
        const oldInDisallowConditionalTypesContext =
          this.inDisallowConditionalTypesContext
        this.inDisallowConditionalTypesContext = true
        try {
          return cb()
        } finally {
          this.inDisallowConditionalTypesContext =
            oldInDisallowConditionalTypesContext
        }
      }
 
      /**
       * ts type isContextual
       * @param {TokenType} type
       * @param {TokenType} token
       * @returns {boolean}
       * */
      ts_type_isContextual(type: TokenType, token: TokenType): boolean {
        return type === token && !this['containsEsc']
      }
 
      tsTryParseType(): Node | undefined | null {
        return this.tsEatThenParseType(tokTypes.colon)
      }
 
      /**
       * Whether current token matches given type
       *
       * @param {TokenType} type
       * @returns {boolean}
       * @memberof Tokenizer
       */
      match(type: TokenType): boolean {
        return this.type === type
      }
 
      eatContextual(name: string) {
        Eif (tsKeywordsRegExp.test(name)) {
          if (this.ts_isContextual(tsTokenType[name])) {
            this.next()
            return true
          }
          return false
        } else {
          // @ts-ignore
          super.eatContextual(name)
        }
      }
 
      tsIsExternalModuleReference(): boolean {
        return (
          this.ts_isContextual(tsTokenType.require) &&
          this.lookaheadCharCode() === charCodes.leftParenthesis
        )
      }
 
      tsParseExternalModuleReference() {
        // @ts-ignore
        const node = this.startNode()
        // @ts-ignore
        this.expectContextual('require')
        // @ts-ignore
        this.expect(tokTypes.parenL)
        if (!this.match(tokTypes.string)) {
          // @ts-ignore
          this.unexpected()
        }
        // For compatibility to estree we cannot call parseLiteral directly here
        node.expression = this.parseExprAtom()
        // @ts-ignore
        this.expect(tokTypes.parenR)
        return this.finishNode(node, 'TSExternalModuleReference')
      }
 
      tsParseEntityName(allowReservedWords: boolean = true): Node {
        // @ts-ignore
        let entity = this.parseIdent(allowReservedWords)
        // @ts-ignore
        while (this.eat(tokTypes.dot)) {
          const node = this.startNodeAtNode(entity)
          // @ts-ignore
          node.left = entity
          // @ts-ignore
          node.right = this.parseIdent(allowReservedWords)
          entity = this.finishNode(node, 'TSQualifiedName')
        }
        return entity
      }
 
      tsParseEnumMember(): Node {
        // @ts-ignore
        const node = this.startNode()
        // Computed property names are grammar errors in an enum, so accept just string literal or identifier.
        node.id = this.match(tokTypes.string)
          // @ts-ignore
          ? this.parseLiteral(this['value'])
          // @ts-ignore
          : this.parseIdent(/* liberal */ true)
        // @ts-ignore
        Eif (this.eat(tokTypes.eq)) {
          node.initializer = this.parseMaybeAssign()
        }
        return this.finishNode(node, 'TSEnumMember')
      }
 
      tsParseEnumDeclaration(
        node: Node,
        properties: {
          const?: true;
          declare?: true;
        } = {}
      ): Node {
        // @ts-ignore
        Iif (properties.const) node.const = true
        // @ts-ignore
        Iif (properties.declare) node.declare = true
        // @ts-ignore
        this.expectContextual('enum')
        // @ts-ignore
        node.id = this.parseIdent()
        // @ts-ignore
        this.checkLValSimple(node.id)
 
        // @ts-ignore
        this.expect(tokTypes.braceL)
        // @ts-ignore
        node.members = this.tsParseDelimitedList(
          'EnumMembers',
          this.tsParseEnumMember.bind(this)
        )
        // @ts-ignore
        this.expect(tokTypes.braceR)
        return this.finishNode(node, 'TSEnumDeclaration')
      }
 
      tsParseModuleBlock(): Node {
        // @ts-ignore
        const node = this.startNode()
        // @ts-ignore
        super.enterScope(SCOPE_OTHER)
        // @ts-ignore
        this.expect(tokTypes.braceL)
        // Inside of a module block is considered "top-level", meaning it can have imports and exports.
        node.body = []
        while (this.type !== tokTypes.braceR) {
          let stmt = this.parseStatement(null, true)
          node.body.push(stmt)
        }
        this.next()
        // @ts-ignore
        super.exitScope()
        return this.finishNode(node, 'TSModuleBlock')
      }
 
      tsParseAmbientExternalModuleDeclaration(
        node: Node
      ): any {
        Iif (this.ts_isContextual(tsTokenType.global)) {
          // @ts-ignore
          node.global = true
          // @ts-ignore
          node.id = this.parseIdent()
        } else Eif (this.match(tokTypes.string)) {
          // @ts-ignore
          node.id = this.parseLiteral(this['value'])
        } else {
          // @ts-ignore
          this.unexpected()
        }
        Eif (this.match(tokTypes.braceL)) {
          // @ts-ignore
          super.enterScope(SCOPE_TS_MODULE)
          // @ts-ignore
          node.body = this.tsParseModuleBlock()
          // @ts-ignore
          super.exitScope()
        } else {
          // @ts-ignore
          super.semicolon()
        }
 
        return this.finishNode(node, 'TSModuleDeclaration')
      }
 
      tsTryParseDeclare(nany: any): Declaration | undefined | null {
        Iif (this.isLineTerminator()) {
          return
        }
        let starttype = this.type
        let kind: 'let' | null
 
        Iif (this.ts_isContextual(tsTokenType.let)) {
          starttype = tokTypes._var
          kind = 'let' as const
        }
 
        return this.tsInAmbientContext(() => {
          Iif (starttype === tokTypes._function) {
            nany.declare = true
            // @ts-ignore
            return this.parseFunctionStatement(
              nany,
              /* async */ false,
              /* declarationPosition */ true
            )
          }
 
          Iif (starttype === tokTypes._class) {
            // While this is also set by tsParseExpressionStatement, we need to set it
            // before parsing the class declaration to know how to register it in the scope.
            nany.declare = true
            return this.parseClass(nany, true)
          }
 
          Iif (starttype === tsTokenType.enum) {
            return this.tsParseEnumDeclaration(nany, { declare: true })
          }
 
          Iif (starttype === tsTokenType.global) {
            return this.tsParseAmbientExternalModuleDeclaration(nany)
          }
 
          Iif (starttype === tokTypes._const || starttype === tokTypes._var) {
            if (!this.match(tokTypes._const) || !this.isLookaheadContextual('enum')) {
              nany.declare = true
              return this.parseVarStatement(nany, kind || this['value'], true)
            }
 
            // `const enum = 0;` not allowed because "enum" is a strict mode reserved word.
            // @ts-ignore
            this.expect(tokTypes._const)
            return this.tsParseEnumDeclaration(nany, {
              const: true,
              declare: true
            })
          }
 
          Iif (starttype === tsTokenType.interface) {
            const result = this.tsParseInterfaceDeclaration(nany, {
              declare: true
            })
            if (result) return result
          }
 
          Eif (tokenIsIdentifier(starttype)) {
            return this.tsParseDeclaration(
              nany,
              this['value'],
              /* next */ true
            )
          }
        })
      }
 
      tsIsListTerminator(kind: any): boolean {
        switch (kind) {
          case 'EnumMembers':
          case 'TypeMembers':
            return this.match(tokTypes.braceR)
          case 'HeritageClauseElement':
            return this.match(tokTypes.braceL)
          case 'TupleElementTypes':
            return this.match(tokTypes.bracketR)
          case 'TypeParametersOrArguments':
            return this.match(tokTypes.relational)
        }
 
        throw new Error('Unreachable')
      }
 
      /**
       * If !expectSuccess, returns undefined instead of failing to parse.
       * If expectSuccess, parseElement should always return a defined value.
       */
      tsParseDelimitedListWorker<T extends Node>(
        kind: any,
        parseElement: () => T | undefined | null,
        expectSuccess: boolean,
        refTrailingCommaPos?: {
          value: number;
        }
      ): T[] | undefined | null {
        const result = []
        let trailingCommaPos = -1
 
        for (; ;) {
          Iif (this.tsIsListTerminator(kind)) {
            break
          }
          trailingCommaPos = -1
 
          const element = parseElement()
          Iif (element == null) {
            return undefined
          }
          result.push(element)
          // @ts-ignore
          if (this.eat(tokTypes.comma)) {
            trailingCommaPos = this['lastTokStart']
            continue
          }
 
          Eif (this.tsIsListTerminator(kind)) {
            break
          }
 
          if (expectSuccess) {
            // This will fail with an error about a missing comma
            // @ts-ignore
            this.expect(tokTypes.comma)
          }
          return undefined
        }
 
        Iif (refTrailingCommaPos) {
          refTrailingCommaPos.value = trailingCommaPos
        }
 
        return result
      }
 
      tsParseDelimitedList<T extends Node>(
        kind: any,
        parseElement: () => T,
        refTrailingCommaPos?: {
          value: number;
        }
      ): T[] {
        return nonNull(
          this.tsParseDelimitedListWorker(
            kind,
            parseElement,
            /* expectSuccess */ true,
            refTrailingCommaPos
          )
        )
      }
 
      tsParseBracketedList<T extends Node>(
        kind: any,
        parseElement: () => T,
        bracket: boolean,
        skipFirstToken: boolean,
        refTrailingCommaPos?: {
          value: number;
        }
      ): T[] {
        if (!skipFirstToken) {
          if (bracket) {
            // @ts-ignore
            this.expect(tokTypes.bracketL)
          } else {
            // @ts-ignore
            this.expect(tokTypes.relational)
          }
        }
 
        const result = this.tsParseDelimitedList(
          kind,
          parseElement,
          refTrailingCommaPos
        )
 
        if (bracket) {
          // @ts-ignore
          this.expect(tokTypes.bracketR)
        } else {
          // @ts-ignore
          this.expect(tokTypes.relational)
        }
 
        return result
      }
 
      tsParseTypeParameterName(): Identifier | string {
        // @ts-ignore
        const typeName = this.parseIdent()
        return typeName.name
      }
 
      tsEatThenParseType(token: TokenType): Node | typeof undefined {
        return !this.match(token) ? undefined : this.tsNextThenParseType()
      }
 
      tsExpectThenParseType(token: TokenType): Node {
        // @ts-ignore
        return this.tsDoThenParseType(() => this.expect(token))
      }
 
      tsNextThenParseType(): Node {
        return this.tsDoThenParseType(() => this.next())
      }
 
      tsDoThenParseType(cb: () => void): Node {
        return this.tsInType(() => {
          cb()
          return this.tsParseType()
        })
      }
 
      tsSkipParameterStart(): boolean {
        if (tokenIsIdentifier(this.type) || this.match(tokTypes._this)) {
          this.next()
          return true
        }
 
        if (this.match(tokTypes.braceL)) {
          // Return true if we can parse an object pattern without errors
          try {
            // @ts-ignore
            this.parseObj(true)
            return true
          } catch {
            return false
          }
        }
 
        if (this.match(tokTypes.bracketL)) {
          this.next()
          try {
            // @ts-ignore
            this.parseBindingList(
              tokTypes.bracketR,
              true,
              true
            )
            return true
          } catch {
            return false
          }
        }
 
        return false
      }
 
      tsIsUnambiguouslyStartOfFunctionType(): boolean {
        this.next()
        if (this.match(tokTypes.parenR) || this.match(tokTypes.ellipsis)) {
          // ( )
          // ( ...
          return true
        }
        if (this.tsSkipParameterStart()) {
          if (
            this.match(tokTypes.colon) ||
            this.match(tokTypes.comma) ||
            this.match(tokTypes.question) ||
            this.match(tokTypes.eq)
          ) {
            // ( xxx :
            // ( xxx ,
            // ( xxx ?
            // ( xxx =
            return true
          }
          if (this.match(tokTypes.parenR)) {
            this.next()
            if (this.match(tokTypes.arrow)) {
              // ( xxx ) =>
              return true
            }
          }
        }
        return false
      }
 
      tsIsStartOfFunctionType() {
        Iif (this.match(tokTypes.relational)) {
          return true
        }
        return (
          this.match(tokTypes.parenL) &&
          this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this))
        )
      }
 
      tsInAllowConditionalTypesContext<T>(cb: () => T): T {
        const oldInDisallowConditionalTypesContext =
          this.inDisallowConditionalTypesContext
        this.inDisallowConditionalTypesContext = false
        try {
          return cb()
        } finally {
          this.inDisallowConditionalTypesContext =
            oldInDisallowConditionalTypesContext
        }
      }
 
      tsParseBindingListForSignature(): Array<Identifier | RestElement | ObjectPattern | ArrayPattern> {
        // @ts-ignore
        return super.parseBindingList(tokTypes.parenR, true, true)
          .map(pattern => {
            if (
              pattern.type !== 'Identifier' &&
              pattern.type !== 'RestElement' &&
              pattern.type !== 'ObjectPattern' &&
              pattern.type !== 'ArrayPattern'
            ) {
              this.raise(pattern.loc.start, TypeScriptError.UnsupportedSignatureParameterKind(pattern.type))
            }
            return pattern as any
          })
      }
 
      tsParseTypePredicateAsserts(): boolean {
        Eif (this.type !== tsTokenType.asserts) {
          return false
        }
        const containsEsc = this['containsEsc']
        this.next()
        if (!tokenIsIdentifier(this.type) && !this.match(tokTypes._this)) {
          return false
        }
 
        if (containsEsc) {
          this.raise(this['lastTokStart'], 'Escape sequence in keyword'
            + ' asserts')
        }
 
        return true
      }
 
      tsParseThisTypeNode() {
        // @ts-ignore
        const node = this.startNode()
        this.next()
        return this.finishNode(node, 'TSThisType')
      }
 
      tsParseTypeAnnotation(
        eatColon = true,
        // @ts-ignore
        t: Node = this.startNode()
      ): Node {
        this.tsInType(() => {
          // @ts-ignore
          if (eatColon) this.expect(tokTypes.colon)
          // @ts-ignore
          t.typeAnnotation = this.tsParseType()
        })
        return this.finishNode(t, 'TSTypeAnnotation')
      }
 
      tsParseThisTypePredicate(lhs: any) {
        this.next()
        const node = this.startNodeAtNode(lhs)
        // @ts-ignore
        node.parameterName = lhs
        // @ts-ignore
        node.typeAnnotation = this.tsParseTypeAnnotation(/* eatColon */ false)
        // @ts-ignore
        node.asserts = false
        return this.finishNode(node, 'TSTypePredicate')
      }
 
      tsParseThisTypeOrThisTypePredicate(): Node {
        const thisKeyword = this.tsParseThisTypeNode()
        if (this.ts_isContextual(tsTokenType.is) && !this.hasPrecedingLineBreak()) {
          return this.tsParseThisTypePredicate(thisKeyword)
        } else {
          return thisKeyword
        }
      }
 
      tsParseTypePredicatePrefix(): Identifier | undefined | null {
        // @ts-ignore
        const id = this.parseIdent()
        Iif (this.ts_isContextual(tsTokenType.is) && !this.hasPrecedingLineBreak()) {
          this.next()
          return id
        }
      }
 
      tsParseTypeOrTypePredicateAnnotation(
        returnToken: TokenType
      ): Node {
        return this.tsInType(() => {
          // @ts-ignore
          const t = this.startNode()
          // @ts-ignore
          this.expect(returnToken)
          // @ts-ignore
          const node = this.startNode()
 
          const asserts = !!this.tsTryParse(
            this.tsParseTypePredicateAsserts.bind(this)
          )
 
          Iif (asserts && this.match(tokTypes._this)) {
            // When asserts is false, thisKeyword is handled by tsParseNonArrayType
            // : asserts this is type
            let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate()
            // if it turns out to be a `TSThisType`, wrap it with `TSTypePredicate`
            // : asserts this
            if (thisTypePredicate.type === 'TSThisType') {
              node.parameterName = thisTypePredicate
              node.asserts = true
              node.typeAnnotation = null
              thisTypePredicate = this.finishNode(node, 'TSTypePredicate')
            } else {
              this.resetStartLocationFromNode(thisTypePredicate, node)
              // @ts-ignore
              thisTypePredicate.asserts = true
            }
            t.typeAnnotation = thisTypePredicate
            return this.finishNode(t, 'TSTypeAnnotation')
          }
 
          const typePredicateVariable =
            this.tsIsIdentifier() &&
            this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this))
 
          Eif (!typePredicateVariable) {
            Eif (!asserts) {
              // : type
              return this.tsParseTypeAnnotation(/* eatColon */ false, t)
            }
 
            // : asserts foo
            // @ts-ignore
            node.parameterName = this.parseIdent()
            node.asserts = asserts
            node.typeAnnotation = null
            t.typeAnnotation = this.finishNode(node, 'TSTypePredicate')
            return this.finishNode(t, 'TSTypeAnnotation')
          }
 
          // : asserts foo is type
          const type = this.tsParseTypeAnnotation(/* eatColon */ false)
          node.parameterName = typePredicateVariable
          node.typeAnnotation = type
          node.asserts = asserts
          t.typeAnnotation = this.finishNode(node, 'TSTypePredicate')
          return this.finishNode(t, 'TSTypeAnnotation')
        })
      }
 
      // Note: In TypeScript implementation we must provide `yieldContext` and `awaitContext`,
      // but here it's always false, because this is only used for types.
      tsFillSignature(
        returnToken: TokenType,
        signature: Node
      ): void {
        // Arrow fns *must* have return token (`=>`). Normal functions can omit it.
        const returnTokenRequired = returnToken === tokTypes.arrow
 
        // https://github.com/babel/babel/issues/9231
        const paramsKey = 'parameters'
        const returnTypeKey = 'typeAnnotation'
        // @ts-ignore
        signature.typeParameters = this.tsTryParseTypeParameters()
        // @ts-ignore
        this.expect(tokTypes.parenL)
        signature[paramsKey] = this.tsParseBindingListForSignature()
        if (returnTokenRequired) {
          signature[returnTypeKey] =
            this.tsParseTypeOrTypePredicateAnnotation(returnToken)
        } else if (this.match(returnToken)) {
          signature[returnTypeKey] =
            this.tsParseTypeOrTypePredicateAnnotation(returnToken)
        }
      }
 
      tsTryNextParseConstantContext(): Node | undefined | null {
        if (this.lookahead().type !== tokTypes._const) return null
 
        this.next()
        const typeReference = this.tsParseTypeReference()
 
        // If the type reference has type parameters, then you are using it as a
        // type and not as a const signifier. We'll *never* be able to find this
        // name, since const isn't allowed as a type name. So in this instance we
        // get to pretend we're the type checker.
        // @ts-ignore
        if (typeReference.typeParameters) {
          // @ts-ignore
          this.raise(typeReference.typeName.start, TypeScriptError.CannotFindName({
            name: 'const'
          }))
        }
 
        return typeReference
      }
 
      tsParseFunctionOrConstructorType(
        type: 'TSFunctionType' | 'TSConstructorType',
        abstract?: boolean
      ) {
        // @ts-ignore
        const node = this.startNode()
        if (type === 'TSConstructorType') {
          node.abstract = !!abstract
          if (abstract) this.next()
          this.next() // eat `new`
        }
        this.tsInAllowConditionalTypesContext(() =>
          this.tsFillSignature(tokTypes.arrow, node)
        )
        return this.finishNode(node, type)
      }
 
      tsParseUnionOrIntersectionType(
        kind: 'TSUnionType' | 'TSIntersectionType',
        parseConstituentType: () => Node,
        operator: TokenType
      ): Node {
        // @ts-ignore
        const node = this.startNode()
        // @ts-ignore
        const hasLeadingOperator = this.eat(operator)
        const types = []
        do {
          types.push(parseConstituentType())
          // @ts-ignore
        } while (this.eat(operator))
        if (types.length === 1 && !hasLeadingOperator) {
          return types[0]
        }
        node.types = types
        return this.finishNode(node, kind)
      }
 
      tsCheckTypeAnnotationForReadOnly(node: Node) {
        // @ts-ignore
        switch (node.typeAnnotation.type) {
          case 'TSTupleType':
          case 'TSArrayType':
            return
          default:
            this.raise(node.start, TypeScriptError.UnexpectedReadonly)
        }
      }
 
      tsParseTypeOperator(): Node {
        // @ts-ignore
        const node = this.startNode()
        const operator = this['value']
        this.next() // eat operator
        node.operator = operator
        node.typeAnnotation = this.tsParseTypeOperatorOrHigher()
 
        if (operator === 'readonly') {
          this.tsCheckTypeAnnotationForReadOnly(
            node
          )
        }
 
        return this.finishNode(node, 'TSTypeOperator')
      }
 
      tsParseConstraintForInferType() {
        // @ts-ignore
        if (this.eat(tokTypes._extends)) {
          const constraint = this.tsInDisallowConditionalTypesContext(() =>
            this.tsParseType()
          )
          if (
            this.inDisallowConditionalTypesContext ||
            !this.match(tokTypes.question)
          ) {
            return constraint
          }
        }
      }
 
      tsParseInferType(): Node {
        // @ts-ignore
        const node = this.startNode()
        // @ts-ignore
        this.expectContextual('infer')
        // @ts-ignore
        const typeParameter = this.startNode()
        typeParameter.name = this.tsParseTypeParameterName()
        typeParameter.constraint = this.tsTryParse(() =>
          this.tsParseConstraintForInferType()
        )
        node.typeParameter = this.finishNode(typeParameter, 'TSTypeParameter')
        return this.finishNode(node, 'TSInferType')
      }
 
      tsParseLiteralTypeNode(): Node {
        // @ts-ignore
        const node = this.startNode()
 
        node.literal = (() => {
          switch (this.type) {
            case tokTypes.num:
            // we don't need bigint type here
            // case tokTypes.bigint:
            case tokTypes.string:
            case tokTypes._true:
            case tokTypes._false:
              // For compatibility to estree we cannot call parseLiteral directly here
              return this.parseExprAtom()
            default:
              // @ts-ignore
              this.unexpected()
          }
        })()
        return this.finishNode(node, 'TSLiteralType')
      }
 
      tsParseImportType(): Node {
        // @ts-ignore
        const node = this.startNode()
        // @ts-ignore
        this.expect(tokTypes._import)
        // @ts-ignore
        this.expect(tokTypes.parenL)
        if (!this.match(tokTypes.string)) {
          this.raise(this.start, TypeScriptError.UnsupportedImportTypeArgument)
        }
 
        // For compatibility to estree we cannot call parseLiteral directly here
        node.argument = this.parseExprAtom()
        // @ts-ignore
        this.expect(tokTypes.parenR)
        // @ts-ignore
        if (this.eat(tokTypes.dot)) {
          // In this instance, the entity name will actually itself be a
          // qualifier, so allow it to be a reserved word as well.
          node.qualifier = this.tsParseEntityName()
        }
        if (this.match(tokTypes.relational)) {
          node.typeParameters = this.tsParseTypeArguments()
        }
        return this.finishNode(node, 'TSImportType')
      }
 
      tsParseTypeQuery(): Node {
        // @ts-ignore
        const node = this.startNode()
        // @ts-ignore
        this.expect(tokTypes._typeof)
        if (this.match(tokTypes._import)) {
          node.exprName = this.tsParseImportType()
        } else {
          node.exprName = this.tsParseEntityName()
        }
        if (!this.hasPrecedingLineBreak() && this.match(tokTypes.relational)) {
          node.typeParameters = this.tsParseTypeArguments()
        }
        return this.finishNode(node, 'TSTypeQuery')
      }
 
      tsParseMappedTypeParameter(): Node {
        // @ts-ignore
        const node = this.startNode()
        node.name = this.tsParseTypeParameterName()
        node.constraint = this.tsExpectThenParseType(tokTypes._in)
        return this.finishNode(node, 'TSTypeParameter')
      }
 
      tsParseMappedType(): Node {
        // @ts-ignore
        const node = this.startNode()
        // @ts-ignore
        this.expect(tokTypes.braceL)
 
        if (this.match(tokTypes.plusMin)) {
          node.readonly = this['value']
          this.next()
          // @ts-ignore
          this.expectContextual('readonly')
        } else if (this.eatContextual('readonly')) {
          node.readonly = true
        }
        // @ts-ignore
        this.expect(tokTypes.bracketL)
        node.typeParameter = this.tsParseMappedTypeParameter()
        node.nameType = this.eatContextual('as') ? this.tsParseType() : null
        // @ts-ignore
        this.expect(tokTypes.bracketR)
 
        if (this.match(tokTypes.plusMin)) {
          node.optional = this['value']
          this.next()
          // @ts-ignore
          this.expect(tokTypes.question)
          // @ts-ignore
        } else if (this.eat(tokTypes.question)) {
          node.optional = true
        }
 
        node.typeAnnotation = this.tsTryParseType()
        // @ts-ignore
        this.semicolon()
        // @ts-ignore
        this.expect(tokTypes.braceR)
 
        return this.finishNode(node, 'TSMappedType')
      }
 
      tsParseTypeLiteral(): Node {
        // @ts-ignore
        const node = this.startNode()
        node.members = this.tsParseObjectTypeMembers()
        return this.finishNode(node, 'TSTypeLiteral')
      }
 
      tsParseTupleElementType(): Node {
        // parses `...TsType[]`
 
        const startLoc = this['startLoc']
        const startPos = this['start']
        // @ts-ignore
        const rest = this.eat(tokTypes.ellipsis)
        let type: any = this.tsParseType()
        // @ts-ignore
        const optional = this.eat(tokTypes.question)
        // @ts-ignore
        const labeled = this.eat(tokTypes.colon)
 
        if (labeled) {
          const labeledNode = this.startNodeAtNode(type)
          // @ts-ignore
          labeledNode.optional = optional
 
          if (
            type.type === 'TSTypeReference' &&
            !type.typeParameters &&
            type.typeName.type === 'Identifier'
          ) {
            // @ts-ignore
            labeledNode.label = type.typeName as Identifier
          } else {
            this.raise(type.start, TypeScriptError.InvalidTupleMemberLabel)
            // @ts-expect-error This produces an invalid AST, but at least we don't drop
            // nodes representing the invalid source.
            labeledNode.label = type
          }
          // @ts-ignore
          labeledNode.elementType = this.tsParseType()
          type = this.finishNode(labeledNode, 'TSNamedTupleMember')
        } else if (optional) {
          // @ts-ignore
          const optionalTypeNode = this.startNodeAtNode<N.TsOptionalType>(type)
          // @ts-ignore
          optionalTypeNode.typeAnnotation = type
          type = this.finishNode(optionalTypeNode, 'TSOptionalType')
        }
 
        if (rest) {
          // @ts-ignore
          const restNode = this.startNodeAt(startPos, startLoc)
          restNode.typeAnnotation = type
          type = this.finishNode(restNode, 'TSRestType')
        }
 
        return type
      }
 
      tsParseTupleType(): Node {
        // @ts-ignore
        const node = this.startNode()
        node.elementTypes = this.tsParseBracketedList(
          'TupleElementTypes',
          this.tsParseTupleElementType.bind(this),
          /* bracket */ true,
          /* skipFirstToken */ false
        )
 
        // Validate the elementTypes to ensure that no mandatory elements
        // follow optional elements
        let seenOptionalElement = false
        let labeledElements: boolean | null = null
        node.elementTypes.forEach(elementNode => {
          const { type } = elementNode
 
          if (
            seenOptionalElement &&
            type !== 'TSRestType' &&
            type !== 'TSOptionalType' &&
            !(type === 'TSNamedTupleMember' && elementNode.optional)
          ) {
            this.raise(elementNode.start, TypeScriptError.OptionalTypeBeforeRequired)
          }
 
          seenOptionalElement ||=
            (type === 'TSNamedTupleMember' && elementNode.optional) ||
            type === 'TSOptionalType'
 
          // When checking labels, check the argument of the spread operator
          let checkType = type
          if (type === 'TSRestType') {
            elementNode = elementNode.typeAnnotation
            checkType = elementNode.type
          }
 
          const isLabeled = checkType === 'TSNamedTupleMember'
          labeledElements ??= isLabeled
          if (labeledElements !== isLabeled) {
            this.raise(elementNode.start, TypeScriptError.MixedLabeledAndUnlabeledElements)
          }
        })
 
        return this.finishNode(node, 'TSTupleType')
      }
 
      tsParseTemplateLiteralType(): Node {
        // @ts-ignore
        const node = this.startNode()
        node.literal = this.parseTemplate({ isTagged: false })
        return this.finishNode(node, 'TSLiteralType')
      }
 
      tsParseTypeReference(): Node {
        // @ts-ignore
        const node = this.startNode()
        node.typeName = this.tsParseEntityName()
        Iif (!this.hasPrecedingLineBreak() && this.match(tokTypes.relational)) {
          node.typeParameters = this.tsParseTypeArguments()
        }
        return this.finishNode(node, 'TSTypeReference')
      }
 
      tsParseParenthesizedType(): Node {
        // @ts-ignore
        const node = this.startNode()
        // @ts-ignore
        this.expect(tokTypes.parenL)
        node.typeAnnotation = this.tsParseType()
        // @ts-ignore
        this.expect(tokTypes.parenR)
        return this.finishNode(node, 'TSParenthesizedType')
      }
 
      tsParseNonArrayType(): Node {
        switch (this.type) {
          case tokTypes.string:
          case tokTypes.num:
          // we don't need bigint type here
          // case tokTypes.bigint:
          case tokTypes._true:
          case tokTypes._false:
            return this.tsParseLiteralTypeNode()
          case tokTypes.plusMin:
            if (this['value'] === '-') {
              // @ts-ignore
              const node = this.startNode()
              const nextToken = this.lookahead()
              if (
                nextToken.type !== tokTypes.num
                // && nextToken.type !== tsTokenType.bigint
              ) {
                // @ts-ignore
                this.unexpected()
              }
              node.literal = this.parseMaybeUnary()
              return this.finishNode(node, 'TSLiteralType')
            }
            break
          case tokTypes._this:
            return this.tsParseThisTypeOrThisTypePredicate()
          case tokTypes._typeof:
            return this.tsParseTypeQuery()
          case tokTypes._import:
            return this.tsParseImportType()
          case tokTypes.braceL:
            return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this))
              ? this.tsParseMappedType()
              : this.tsParseTypeLiteral()
          case tokTypes.bracketL:
            return this.tsParseTupleType()
          case tokTypes.parenL:
            // the following line will always be false
            // if (!this.options.createParenthesizedExpressions) {
            // const startPos = this.start
            // this.next()
            // const type = this.tsParseType()
            // this.expect(tokTypes.parenR)
            // this.addExtra(type, 'parenthesized', true)
            // this.addExtra(type, 'parenStart', startPos)
            // return type
            // }
 
            return this.tsParseParenthesizedType()
          // parse template string here
          case tokTypes.backQuote:
          case tokTypes.dollarBraceL:
            return this.tsParseTemplateLiteralType()
          default: {
            const { type } = this
            Eif (
              tokenIsIdentifier(type) ||
              type === tokTypes._void ||
              type === tokTypes._null
            ) {
              const nodeType =
                type === tokTypes._void
                  ? 'TSVoidKeyword'
                  : type === tokTypes._null
                    ? 'TSNullKeyword'
                    : keywordTypeFromName(this['value'])
              if (
                nodeType !== undefined &&
                this.lookaheadCharCode() !== charCodes.dot
              ) {
                // @ts-ignore
                const node = this.startNode()
                this.next()
                return this.finishNode(node, nodeType)
              }
              return this.tsParseTypeReference()
            }
          }
        }
        // @ts-ignore
        this.unexpected()
      }
 
      tsParseArrayTypeOrHigher(): Node {
        let type = this.tsParseNonArrayType()
        // @ts-ignore
        while (!this.hasPrecedingLineBreak() && this.eat(tokTypes.bracketL)) {
          Eif (this.match(tokTypes.bracketR)) {
            const node = this.startNodeAtNode(type)
            // @ts-ignore
            node.elementType = type
            // @ts-ignore
            this.expect(tokTypes.bracketR)
            type = this.finishNode(node, 'TSArrayType')
          } else {
            const node = this.startNodeAtNode(type)
            // @ts-ignore
            node.objectType = type
            // @ts-ignore
            node.indexType = this.tsParseType()
            // @ts-ignore
            this.expect(tokTypes.bracketR)
            type = this.finishNode(node, 'TSIndexedAccessType')
          }
        }
        return type
      }
 
      tsParseTypeOperatorOrHigher(): Node {
        const isTypeOperator =
          tokenIsTSTypeOperator(this.type) && !this['containsEsc']
        return isTypeOperator
          ? this.tsParseTypeOperator()
          : this.ts_isContextual(tsTokenType.infer)
            ? this.tsParseInferType()
            : this.tsInAllowConditionalTypesContext(() =>
              this.tsParseArrayTypeOrHigher()
            )
      }
 
      tsParseIntersectionTypeOrHigher(): Node {
        return this.tsParseUnionOrIntersectionType(
          'TSIntersectionType',
          this.tsParseTypeOperatorOrHigher.bind(this),
          tokTypes.bitwiseAND
        )
      }
 
      tsParseUnionTypeOrHigher() {
        return this.tsParseUnionOrIntersectionType(
          'TSUnionType',
          this.tsParseIntersectionTypeOrHigher.bind(this),
          tokTypes.bitwiseOR
        )
      }
 
      tsParseNonConditionalType(): Node {
        Iif (this.tsIsStartOfFunctionType()) {
          return this.tsParseFunctionOrConstructorType('TSFunctionType')
        }
        Iif (this.match(tokTypes._new)) {
          // As in `new () => Date`
          return this.tsParseFunctionOrConstructorType('TSConstructorType')
        } else Iif (this.isAbstractConstructorSignature()) {
          // As in `abstract new () => Date`
          return this.tsParseFunctionOrConstructorType(
            'TSConstructorType',
            /* abstract */ true
          )
        }
        return this.tsParseUnionTypeOrHigher()
      }
 
      /** Be sure to be in a type context before calling this, using `tsInType`. */
      tsParseType(): Node {
        // Need to set `state.inType` so that we don't parse JSX in a type context.
        assert(this.inType)
        const type = this.tsParseNonConditionalType()
 
        Eif (
          this.inDisallowConditionalTypesContext ||
          this.hasPrecedingLineBreak() ||
          // @ts-ignore
          !this.eat(tokTypes._extends)
        ) {
          return type
        }
        const node = this.startNodeAtNode(type)
        // @ts-ignore
        node.checkType = type
        // @ts-ignore
        node.extendsType = this.tsInDisallowConditionalTypesContext(() =>
          this.tsParseNonConditionalType()
        )
        // @ts-ignore
        this.expect(tokTypes.question)
        // @ts-ignore
        node.trueType = this.tsInAllowConditionalTypesContext(() =>
          this.tsParseType()
        )
        // @ts-ignore
        this.expect(tokTypes.colon)
        // @ts-ignore
        node.falseType = this.tsInAllowConditionalTypesContext(() =>
          this.tsParseType()
        )
 
        return this.finishNode(node, 'TSConditionalType')
      }
 
      tsIsUnambiguouslyIndexSignature() {
        this.next() // Skip '{'
        if (tokenIsIdentifier(this.type)) {
          this.next()
          return this.match(tokTypes.colon)
        }
        return false
      }
 
      /**
       * Runs `cb` in a type context.
       * This should be called one token *before* the first type token,
       * so that the call to `next()` is run in type context.
       */
      tsInType<T>(cb: () => T): T {
        const oldInType = this.inType
        this.inType = true
        try {
          return cb()
        } finally {
          this.inType = oldInType
        }
      }
 
      tsTryParseIndexSignature(
        node: Node
      ): Node | undefined | null {
        Eif (
          !(
            this.match(tokTypes.bracketL) &&
            this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this))
          )
        ) {
          return undefined
        }
        // @ts-ignore
        this.expect(tokTypes.bracketL)
        // @ts-ignore
        const id = this.parseIdent()
        id.typeAnnotation = this.tsParseTypeAnnotation()
        this.resetEndLocation(id) // set end position to end of type
        // @ts-ignore
        this.expect(tokTypes.bracketR)
        // @ts-ignore
        node.parameters = [id]
 
        const type = this.tsTryParseTypeAnnotation()
        // @ts-ignore
        if (type) node.typeAnnotation = type
        this.tsParseTypeMemberSemicolon()
        return this.finishNode(node, 'TSIndexSignature')
      }
 
      // for better error recover
      tsParseNoneModifiers(node: any) {
        this.tsParseModifiers({
          modified: node,
          allowedModifiers: [],
          disallowedModifiers: ['in', 'out'],
          errorTemplate: TypeScriptError.InvalidModifierOnTypeParameterPositions
        })
      }
 
      tsParseTypeParameter(
        parseModifiers: (
          node: Node
        ) => void = this.tsParseNoneModifiers.bind(this)
      ): Node {
        // @ts-ignore
        const node = this.startNode()
 
        parseModifiers(node)
 
        node.name = this.tsParseTypeParameterName()
        node.constraint = this.tsEatThenParseType(tokTypes._extends)
        node.default = this.tsEatThenParseType(tokTypes.eq)
        return this.finishNode(node, 'TSTypeParameter')
      }
 
      tsParseTypeParameters(
        parseModifiers?: ((node) => void) | null
      ) {
        // @ts-ignore
        const node = this.startNode()
 
        // todo support jsx
        if (this.match(tokTypes.relational) || this.match(jsxTokenType.jsxTagStart)) {
          this.next()
        } else {
          // @ts-ignore
          this.unexpected()
        }
 
        const refTrailingCommaPos = { value: -1 }
 
        node.params = this.tsParseBracketedList(
          'TypeParametersOrArguments',
          this.tsParseTypeParameter.bind(this, parseModifiers),
          /* bracket */ false,
          /* skipFirstToken */ true,
          refTrailingCommaPos
        )
        if (node.params.length === 0) {
          this.raise(this.start, TypeScriptError.EmptyTypeParameters)
        }
        if (refTrailingCommaPos.value !== -1) {
          this.addExtra(node, 'trailingComma', refTrailingCommaPos.value)
        }
        return this.finishNode(node, 'TSTypeParameterDeclaration')
      }
 
      tsTryParseTypeParameters(
        parseModifiers?: ((node) => void) | null
      ) {
        Iif (this.match(tokTypes.relational)) {
          return this.tsParseTypeParameters(parseModifiers)
        }
      }
 
      tsTryParse<T>(f: () => T | undefined | false): T | undefined {
        const state = this.getCurLookaheadState()
        const result = f()
        if (result !== undefined && result !== false) {
          return result
        } else {
          this.setLookaheadState(state)
          return undefined
        }
      }
 
      tsTokenCanFollowModifier() {
        return (
          (this.match(tokTypes.bracketL) ||
            this.match(tokTypes.braceL) ||
            this.match(tokTypes.star) ||
            this.match(tokTypes.ellipsis) ||
            this.match(tokTypes.privateId) ||
            this.isLiteralPropertyName()) &&
          !this.hasPrecedingLineBreak()
        )
      }
 
      tsNextTokenCanFollowModifier() {
        // Note: TypeScript's implementation is much more complicated because
        // more things are considered modifiers there.
        // This implementation only handles modifiers not handled by @babel/parser itself. And "static".
        // TODO: Would be nice to avoid lookahead. Want a hasLineBreakUpNext() method...
        this.next()
        return this.tsTokenCanFollowModifier()
      }
 
      /** Parses a modifier matching one the given modifier names. */
      tsParseModifier<T extends TsModifier>(
        allowedModifiers: T[],
        stopOnStartOfClassStaticBlock?: boolean
      ): T | undefined | null {
        Iif (!tokenIsIdentifier(this.type) && this.type !== tokTypes._in) {
          return undefined
        }
 
        const modifier = this['value']
        // @ts-ignore
        if (allowedModifiers.indexOf(modifier) !== -1) {
          Iif (stopOnStartOfClassStaticBlock && this.tsIsStartOfStaticBlocks()) {
            return undefined
          }
          Eif (this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) {
            // @ts-ignore
            return modifier
          }
        }
        return undefined
      }
 
      /** Parses a list of modifiers, in any order.
       *  If you need a specific order, you must call this function multiple times:
       *    this.tsParseModifiers({ modified: node, allowedModifiers: ['public'] });
       *    this.tsParseModifiers({ modified: node, allowedModifiers: ["abstract", "readonly"] });
       */
      tsParseModifiers({
        modified,
        allowedModifiers,
        disallowedModifiers,
        stopOnStartOfClassStaticBlock,
        errorTemplate = TypeScriptError.InvalidModifierOnTypeMember
      }: {
        modified: ModifierBase;
        allowedModifiers: readonly TsModifier[];
        disallowedModifiers?: TsModifier[];
        stopOnStartOfClassStaticBlock?: boolean;
        // FIXME: make sure errorTemplate can receive `modifier`
        errorTemplate?: any;
      }): void {
        const enforceOrder = (
          loc: Position,
          modifier: TsModifier,
          before: TsModifier,
          after: TsModifier
        ) => {
          Iif (modifier === before && modified[after]) {
            this.raise(loc.column, TypeScriptError.InvalidModifiersOrder({ orderedModifiers: [before, after] }))
          }
        }
        const incompatible = (
          loc: Position,
          modifier: TsModifier,
          mod1: TsModifier,
          mod2: TsModifier
        ) => {
          Iif (
            (modified[mod1] && modifier === mod2) ||
            (modified[mod2] && modifier === mod1)
          ) {
            this.raise(loc.column, TypeScriptError.IncompatibleModifiers({ modifiers: [mod1, mod2] }))
          }
        }
 
        for (; ;) {
          const startLoc = this['startLoc']
          const modifier: TsModifier | undefined | null = this.tsParseModifier(
            allowedModifiers.concat(disallowedModifiers ?? []),
            stopOnStartOfClassStaticBlock
          )
 
          if (!modifier) break
 
          if (tsIsAccessModifier(modifier)) {
            Iif (modified.accessibility) {
              this.raise(this.start, TypeScriptError.DuplicateAccessibilityModifier())
            } else {
              enforceOrder(startLoc, modifier, modifier, 'override')
              enforceOrder(startLoc, modifier, modifier, 'static')
              enforceOrder(startLoc, modifier, modifier, 'readonly')
 
              modified.accessibility = modifier
            }
          } else Iif (tsIsVarianceAnnotations(modifier)) {
            if (modified[modifier]) {
              this.raise(this.start, TypeScriptError.DuplicateModifier({ modifier }))
            }
            modified[modifier] = true
 
            enforceOrder(startLoc, modifier, 'in', 'out')
          } else {
            Iif (Object.hasOwnProperty.call(modified, modifier)) {
              this.raise(this.start, TypeScriptError.DuplicateModifier({ modifier }))
            } else {
              enforceOrder(startLoc, modifier, 'static', 'readonly')
              enforceOrder(startLoc, modifier, 'static', 'override')
              enforceOrder(startLoc, modifier, 'override', 'readonly')
              enforceOrder(startLoc, modifier, 'abstract', 'override')
 
              incompatible(startLoc, modifier, 'declare', 'override')
              incompatible(startLoc, modifier, 'static', 'abstract')
            }
            modified[modifier] = true
          }
 
          Iif (disallowedModifiers?.includes(modifier)) {
            this.raise(this.start, errorTemplate)
          }
        }
      }
 
      tsParseInOutModifiers(node: any) {
        this.tsParseModifiers({
          modified: node,
          allowedModifiers: ['in', 'out'],
          disallowedModifiers: [
            'public',
            'private',
            'protected',
            'readonly',
            'declare',
            'abstract',
            'override'
          ],
          errorTemplate: TypeScriptError.InvalidModifierOnTypeParameter
        })
      }
 
      tsParseTypeArguments(): Node {
        // @ts-ignore
        const node = this.startNode()
        node.params = this.tsInType(() =>
          // Temporarily remove a JSX parsing context, which makes us scan different tokens.
          this.tsInNoContext(() => {
            // @ts-ignore
            this.expect(tokTypes.relational)
            return this.tsParseDelimitedList(
              'TypeParametersOrArguments',
              this.tsParseType.bind(this)
            )
          })
        )
        if (node.params.length === 0) {
          this.raise(this.start, TypeScriptError.EmptyTypeArguments)
        }// @ts-ignore
        this.expect(tokTypes.relational)
        return this.finishNode(node, 'TSTypeParameterInstantiation')
      }
 
      tsParseHeritageClause(
        token: 'extends' | 'implements'
      ): Array<Node> {
        const originalStart = this.start
 
        const delimitedList = this.tsParseDelimitedList(
          'HeritageClauseElement',
          () => {
            // @ts-ignore
            const node = this.startNode()
            node.expression = this.tsParseEntityName()
            Iif (this.match(tokTypes.relational)) {
              node.typeParameters = this.tsParseTypeArguments()
            }
 
            return this.finishNode(node, 'TSExpressionWithTypeArguments')
          }
        )
 
        Iif (!delimitedList.length) {
          this.raise(originalStart, TypeScriptError.EmptyHeritageClauseType({ token }))
        }
 
        return delimitedList
      }
 
      tsParseTypeMemberSemicolon(): void {
        // @ts-ignore
        Iif (!this.eat(tokTypes.comma) && !this.isLineTerminator()) {
          // @ts-ignore
          this.expect(tokTypes.semi)
        }
      }
 
      tsTryParseAndCatch<T extends BaseNode | undefined | null>(
        f: () => T
      ): T | undefined | null {
        const result = this.tryParse(
          abort =>
            // @ts-expect-error todo(flow->ts)
            f() || abort()
        )
 
        if (result.aborted || !result.node) return undefined
        if (result.error) this.setLookaheadState(result.failState)
        // @ts-expect-error refine typings
        return result.node
      }
 
      tsParseSignatureMember(
        kind: 'TSCallSignatureDeclaration' | 'TSConstructSignatureDeclaration',
        node: Node
      ): Node {
        this.tsFillSignature(tokTypes.colon, node)
        this.tsParseTypeMemberSemicolon()
        return this.finishNode(node, kind)
      }
 
      tsParsePropertyOrMethodSignature(
        node: Node,
        readonly: boolean
      ): Node {
        // @ts-ignore
        if (this.eat(tokTypes.question)) node.optional = true
        const nodeAny: any = node
 
        Iif (this.match(tokTypes.parenL) || this.match(tokTypes.relational)) {
          if (readonly) {
            this.raise(node.start, TypeScriptError.ReadonlyForMethodSignature)
          }
          const method = nodeAny
          if (method.kind && this.match(tokTypes.relational)) {
            this.raise(this.start, TypeScriptError.AccesorCannotHaveTypeParameters)
          }
          this.tsFillSignature(tokTypes.colon, method)
          this.tsParseTypeMemberSemicolon()
          const paramsKey = 'parameters'
          const returnTypeKey = 'typeAnnotation'
          if (method.kind === 'get') {
            if (method[paramsKey].length > 0) {
              this.raise(this.start, 'A \'get\' accesor must not have any formal parameters.')
              if (this.isThisParam(method[paramsKey][0])) {
                this.raise(this.start, TypeScriptError.AccesorCannotDeclareThisParameter)
              }
            }
          } else if (method.kind === 'set') {
            if (method[paramsKey].length !== 1) {
              this.raise(this.start, 'A \'get\' accesor must'
                + ' not have any formal parameters.')
            } else {
              const firstParameter = method[paramsKey][0]
              if (this.isThisParam(firstParameter)) {
                this.raise(this.start, TypeScriptError.AccesorCannotDeclareThisParameter)
              }
              if (
                firstParameter.type === 'Identifier' &&
                firstParameter.optional
              ) {
                this.raise(this.start, TypeScriptError.SetAccesorCannotHaveOptionalParameter)
              }
              if (firstParameter.type === 'RestElement') {
                this.raise(this.start, TypeScriptError.SetAccesorCannotHaveRestParameter)
              }
            }
            if (method[returnTypeKey]) {
              this.raise(method[returnTypeKey].start, TypeScriptError.SetAccesorCannotHaveReturnType)
            }
          } else {
            method.kind = 'method'
          }
          return this.finishNode(method, 'TSMethodSignature')
        } else {
          const property = nodeAny
          Iif (readonly) property.readonly = true
          const type = this.tsTryParseTypeAnnotation()
          Eif (type) property.typeAnnotation = type
          this.tsParseTypeMemberSemicolon()
          return this.finishNode(property, 'TSPropertySignature')
        }
      }
 
      tsParseTypeMember(): Node {
        // @ts-ignore
        const node: any = this.startNode()
 
        Iif (this.match(tokTypes.parenL) || this.match(tokTypes.relational)) {
          return this.tsParseSignatureMember('TSCallSignatureDeclaration', node)
        }
 
        Iif (this.match(tokTypes._new)) {
          // @ts-ignore
          const id = this.startNode<Identifier>()
          this.next()
          if (this.match(tokTypes.parenL) || this.match(tokTypes.relational)) {
            return this.tsParseSignatureMember(
              'TSConstructSignatureDeclaration',
              node
            )
          } else {
            node.key = this.createIdentifier(id, 'new')
            return this.tsParsePropertyOrMethodSignature(node, false)
          }
        }
 
        this.tsParseModifiers({
          modified: node,
          allowedModifiers: ['readonly'],
          disallowedModifiers: [
            'declare',
            'abstract',
            'private',
            'protected',
            'public',
            'static',
            'override'
          ]
        })
 
        const idx = this.tsTryParseIndexSignature(node)
        Iif (idx) {
          return idx
        }
        // @ts-ignore
        this.parsePropertyName(node)
        Iif (
          !node.computed &&
          node.key.type === 'Identifier' &&
          (node.key.name === 'get' || node.key.name === 'set') &&
          this.tsTokenCanFollowModifier()
        ) {
          node.kind = node.key.name
          // @ts-ignore
          this.parsePropertyName(node)
        }
        return this.tsParsePropertyOrMethodSignature(node, !!node.readonly)
      }
 
      tsParseList<T extends Node>(
        kind: ParsingContext,
        parseElement: () => T
      ): T[] {
        const result: T[] = []
        while (!this.tsIsListTerminator(kind)) {
          // Skipping "parseListElement" from the TS source since that's just for error handling.
          result.push(parseElement())
        }
        return result
      }
 
      tsParseObjectTypeMembers(): Array<Node> {
        // @ts-ignore
        this.expect(tokTypes.braceL)
        const members = this.tsParseList(
          'TypeMembers',
          this.tsParseTypeMember.bind(this)
        )
        // @ts-ignore
        this.expect(tokTypes.braceR)
        return members
      }
 
      tsParseInterfaceDeclaration(
        node: Node,
        properties: {
          declare?: true;
        } = {}
      ): any | undefined | null {
        Iif (this.hasFollowingLineBreak()) return null
        // @ts-ignore
        this.expectContextual('interface')
        // @ts-ignore
        Iif (properties.declare) node.declare = true
        Eif (tokenIsIdentifier(this.type)) {
          // @ts-ignore
          node.id = this.parseIdent()
          // @ts-ignore
          this.checkLValSimple(node.id, BIND_TS_INTERFACE)
        } else {
          // @ts-ignore
          node.id = null
          this.raise(this.start, TypeScriptError.MissingInterfaceName)
        }
        // @ts-ignore
        node.typeParameters = this.tsTryParseTypeParameters(
          this.tsParseInOutModifiers.bind(this)
        )
        // @ts-ignore
        if (this.eat(tokTypes._extends)) {
          // @ts-ignore
          node.extends = this.tsParseHeritageClause('extends')
        }
        // @ts-ignore
        const body = this.startNode()
        body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this))
        // @ts-ignore
        node.body = this.finishNode(body, 'TSInterfaceBody')
        return this.finishNode(node, 'TSInterfaceDeclaration')
      }
 
      tsParseAbstractDeclaration(
        node: any
      ): any | undefined | null {
        Eif (this.match(tokTypes._class)) {
          node.abstract = true
          return this.parseClass(node, true)
        } else if (this.ts_isContextual(tsTokenType.interface)) {
          // for invalid abstract interface
 
          // To avoid
          //   abstract interface
          //   Foo {}
          if (!this.hasFollowingLineBreak()) {
            node.abstract = true
            return this.tsParseInterfaceDeclaration(
              node
            )
          }
        } else {
          // @ts-ignore
          this.unexpected(null, tokTypes._class)
        }
      }
 
      tsIsDeclarationStart(): boolean {
        return tokenIsTSDeclarationStart(this.type)
      }
 
      tsParseExpressionStatement(
        node,
        expr
      ) {
        switch (expr.name) {
          case 'declare': {
            const declaration = this.tsTryParseDeclare(node)
            Eif (declaration) {
              // @ts-ignore
              declaration.declare = true
              return declaration
            }
            break
          }
          case 'global':
            // `global { }` (with no `declare`) may appear inside an ambient module declaration.
            // Would like to use tsParseAmbientExternalModuleDeclaration here, but already ran past "global".
            if (this.match(tokTypes.braceL)) {
              // @ts-ignore
              super.enterScope(SCOPE_TS_MODULE)
              const mod = node
              mod.global = true
              mod.id = expr
              mod.body = this.tsParseModuleBlock()
              // @ts-ignore
              super.exitScope()
              return this.finishNode(mod, 'TSModuleDeclaration')
            }
            break
 
          default:
            return this.tsParseDeclaration(node, expr.name, /* next */ false)
        }
      }
 
      tsParseModuleReference(): any {
        return this.tsIsExternalModuleReference()
          ? this.tsParseExternalModuleReference()
          : this.tsParseEntityName(/* allowReservedWords */ false)
      }
 
      tsIsExportDefaultSpecifier(): boolean {
        const { type } = this
        // @ts-ignore
        const isAsync = this.isAsyncFunction()
        // @ts-ignore
        const isLet = this.isLet()
        if (tokenIsIdentifier(type)) {
          if ((isAsync && !this['containsEsc']) || isLet) {
            return false
          }
          if (
            (type === tsTokenType.type || type === tsTokenType.interface) &&
            !this['containsEsc']
          ) {
            const { type: nextType } = this.lookahead()
            // If we see any variable name other than `from` after `type` keyword,
            // we consider it as flow/typescript type exports
            // note that this approach may fail on some pedantic cases
            // export type from = number
            if (
              (tokenIsIdentifier(nextType) && nextType !== tsTokenType.from) ||
              nextType === tokTypes.braceL
            ) {
              return false
            }
          }
        } else if (!this.match(tokTypes._default)) {
          return false
        }
 
        const next = this.nextTokenStart()
        const hasFrom = this.isUnparsedContextual(next, 'from')
        if (
          this.input.charCodeAt(next) === charCodes.comma ||
          (tokenIsIdentifier(this.type) && hasFrom)
        ) {
          return true
        }
        // lookahead again when `export default from` is seen
        if (this.match(tokTypes._default) && hasFrom) {
          const nextAfterFrom = this.input.charCodeAt(
            this.nextTokenStartSince(next + 4)
          )
          return (
            nextAfterFrom === charCodes.quotationMark ||
            nextAfterFrom === charCodes.apostrophe
          )
        }
        return false
      }
 
      tsInAmbientContext<T>(cb: () => T): T {
        const oldIsAmbientContext = this.isAmbientContext
        this.isAmbientContext = true
        try {
          return cb()
        } finally {
          this.isAmbientContext = oldIsAmbientContext
        }
      }
 
      tsCheckLineTerminator(next: boolean) {
        if (next) {
          Iif (this.hasFollowingLineBreak()) return false
          this.next()
          return true
        }
        return !this.isLineTerminator()
      }
 
      tsParseModuleOrNamespaceDeclaration(
        node: Node,
        nested: boolean = false
      ): any {
        // @ts-ignore
        node.id = this.parseIdent()
 
        Eif (!nested) {
          // @ts-ignore
          this.checkLValSimple(node.id, BIND_TS_NAMESPACE)
        }
        // @ts-ignore
        Iif (this.eat(tokTypes.dot)) {
          // @ts-ignore
          const inner = this.startNode()
          this.tsParseModuleOrNamespaceDeclaration(inner, true)
          // @ts-expect-error Fixme: refine typings
          node.body = inner
        } else {
          // @ts-ignore
          super.enterScope(SCOPE_TS_MODULE)
          // @ts-ignore
          node.body = this.tsParseModuleBlock()
          // @ts-ignore
          super.exitScope()
        }
        return this.finishNode(node, 'TSModuleDeclaration')
      }
 
      tsParseTypeAliasDeclaration(
        node: Node
      ): any {
        // @ts-ignore
        node.id = this.parseIdent()
        // @ts-ignore
        this.checkLValSimple(node.id, BIND_TS_TYPE)
        // @ts-ignore
        node.typeAnnotation = this.tsInType(() => {
          // @ts-ignore
          node.typeParameters = this.tsTryParseTypeParameters(
            this.tsParseInOutModifiers.bind(this)
          )
          // @ts-ignore
          this.expect(tokTypes.eq)
 
          Iif (
            this.ts_isContextual(tsTokenType.interface) &&
            this.lookahead().type !== tokTypes.dot
          ) {
            // @ts-ignore
            const node = this.startNode()
            this.next()
            return this.finishNode(node, 'TSIntrinsicKeyword')
          }
 
          return this.tsParseType()
        })
        // @ts-ignore
        this.semicolon()
        return this.finishNode(node, 'TSTypeAliasDeclaration')
      }
 
      // Common to tsTryParseDeclare, tsTryParseExportDeclaration, and tsParseExpressionStatement.
      tsParseDeclaration(
        node: any,
        value: string,
        next: boolean
      ): Declaration | undefined | null {
        // no declaration apart from enum can be followed by a line break.
        switch (value) {
          case 'abstract':
            Eif (
              this.tsCheckLineTerminator(next) &&
              (this.match(tokTypes._class) || tokenIsIdentifier(this.type))
            ) {
              return this.tsParseAbstractDeclaration(node)
            }
            break
 
          case 'module':
            Eif (this.tsCheckLineTerminator(next)) {
              Eif (this.match(tokTypes.string)) {
                return this.tsParseAmbientExternalModuleDeclaration(node)
              } else if (tokenIsIdentifier(this.type)) {
                return this.tsParseModuleOrNamespaceDeclaration(node)
              }
            }
            break
 
          case 'namespace':
            Eif (
              this.tsCheckLineTerminator(next) &&
              tokenIsIdentifier(this.type)
            ) {
              return this.tsParseModuleOrNamespaceDeclaration(node)
            }
            break
 
          case 'type':
            Eif (
              this.tsCheckLineTerminator(next) &&
              tokenIsIdentifier(this.type)
            ) {
              return this.tsParseTypeAliasDeclaration(node)
            }
            break
        }
      }
 
      // Note: this won't b·e called unless the keyword is allowed in
      // `shouldParseExportDeclaration`.
      tsTryParseExportDeclaration(): Declaration | undefined | null {
        return this.tsParseDeclaration(
          // @ts-ignore
          this.startNode(),
          this['value'],
          /* next */ true
        )
      }
 
      tsParseImportEqualsDeclaration(
        node,
        isExport?: boolean
      ): Node {
        node.isExport = isExport || false
        // @ts-ignore
        node.id = this.parseIdent()
        // @ts-ignore
        this.checkLValSimple(node.id, BIND_LEXICAL)
        // @ts-ignore
        super.expect(tokTypes.eq)
        const moduleReference = this.tsParseModuleReference()
        if (
          node.importKind === 'type' &&
          moduleReference.type !== 'TSExternalModuleReference'
        ) {
          this.raise(moduleReference.start, TypeScriptError.ImportAliasHasImportType)
        }
        node.moduleReference = moduleReference
        // @ts-ignore
        super.semicolon()
        return this.finishNode(node, 'TSImportEqualsDeclaration')
      }
 
      // todo overwritten in parseNew
      // parseNewCallee(node: N.NewExpression): void {
      //   super.parseNewCallee(node);
      //
      //   const { callee } = node;
      //   if (
      //     callee.type === "TSInstantiationExpression" &&
      //     !callee.extra?.parenthesized
      //   ) {
      //     node.typeParameters = callee.typeParameters;
      //     node.callee = callee.expression;
      //   }
      // }
 
      // todo we don't support export default from now
      isExportDefaultSpecifier(): boolean {
        if (this.tsIsDeclarationStart()) return false
 
        const { type } = this
        if (tokenIsIdentifier(type)) {
          if ((type === tsTokenType.async && !this['containsEsc']) || type === tsTokenType.let) {
            return false
          }
          if (
            (type === tsTokenType.type || type === tsTokenType.interface) &&
            !this['containsEsc']
          ) {
            const { type: nextType } = this.lookahead()
            // If we see any variable name other than `from` after `type` keyword,
            // we consider it as flow/typescript type exports
            // note that this approach may fail on some pedantic cases
            // export type from = number
            if (
              (tokenIsIdentifier(nextType) && nextType !== tsTokenType.from) ||
              nextType === tokTypes.braceL
            ) {
              return false
            }
          }
        } else if (!this.match(tokTypes._default)) {
          return false
        }
 
        const next = this.nextTokenStart()
        const hasFrom = this.isUnparsedContextual(next, 'from')
        if (
          this.input.charCodeAt(next) === charCodes.comma ||
          (tokenIsIdentifier(this.type) && hasFrom)
        ) {
          return true
        }
        // lookahead again when `export default from` is seen
        if (this.match(tokTypes._default) && hasFrom) {
          const nextAfterFrom = this.input.charCodeAt(
            this.nextTokenStartSince(next + 4)
          )
          return (
            nextAfterFrom === charCodes.quotationMark ||
            nextAfterFrom === charCodes.apostrophe
          )
        }
        return false
      }
 
      parseTemplate({ isTagged = false } = {}) {
        // @ts-ignore
        let node = this.startNode()
        this.next()
        node.expressions = []
        // @ts-ignore
        let curElt = this.parseTemplateElement({ isTagged })
        node.quasis = [curElt]
        while (!curElt.tail) {
          if (this.type === tokTypes.eof) this.raise(this['pos'], 'Unterminated template literal')
          // @ts-ignore
          this.expect(tokTypes.dollarBraceL)
          // NOTE: extend parseTemplateSubstitution
          // @ts-ignore
          node.expressions.push(this.inType ? this.tsParseType() : this.parseExpression())
          // @ts-ignore
          this.expect(tokTypes.braceR)
          // @ts-ignore
          node.quasis.push(curElt = this.parseTemplateElement({ isTagged }))
        }
        this.next()
        return this.finishNode(node, 'TemplateLiteral')
      }
 
      parseFunction(
        node: any,
        statement?: any,
        // @ts-ignore
        allowExpressionBody?: boolean,
        isAsync?: boolean,
        // @ts-ignore
        forInit?: boolean
      ) {
        // @ts-ignore
        this.initFunction(node)
        Eif (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
          Iif (this.type === tokTypes.star && (statement && FUNC_HANGING_STATEMENT))
            // @ts-ignore
            this.unexpected()
          // @ts-ignore
          node.generator = this.eat(tokTypes.star)
        }
        Eif (this.options.ecmaVersion >= 8)
          node.async = !!isAsync
 
        Eif (statement && FUNC_STATEMENT) {
          node.id = (statement && FUNC_NULLABLE_ID) && this.type !== tokTypes.name ? null : this.parseIdent()
          Iif (node.id && !(statement && FUNC_HANGING_STATEMENT))
            // If it is a regular function declaration in sloppy mode, then it is
            // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
            // mode depends on properties of the current scope (see
            // treatFunctionsAsVar).
            // @ts-ignore
            this.checkLValSimple(
              node.id,
              (this['strict'] || node.generator || node.async) ?
                this['treatFunctionsAsVar'] ?
                  acornScope.BIND_VAR : acornScope.BIND_LEXICAL : acornScope.BIND_FUNCTION
            )
        }
 
        let oldYieldPos = this['yieldPos'], oldAwaitPos = this['awaitPos'],
          oldAwaitIdentPos = this['awaitIdentPos']
        this['yieldPos'] = 0
        this['awaitPos'] = 0
        this['awaitIdentPos'] = 0
        // @ts-ignore
        this.enterScope(functionFlags(node.async, node.generator))
 
        Iif (!(statement && FUNC_STATEMENT))
          node.id = this.type === tokTypes.name ? this.parseIdent() : null
 
        this.parseFunctionParams(node)
        const finishNode = this.parseFunctionBodyAndFinish(
          node,
          (statement && FUNC_STATEMENT) ? 'FunctionDeclaration' : 'FunctionExpression',
          false,
          forInit
        )
 
        this['yieldPos'] = oldYieldPos
        this['awaitPos'] = oldAwaitPos
        this['awaitIdentPos'] = oldAwaitIdentPos
        return finishNode
      }
 
      parseFunctionBodyAndFinish(
        node: Node,
        type: string,
        isMethod: boolean = false,
        forInit: boolean = false
      ) {
        if (this.match(tokTypes.colon)) {
          // @ts-ignore
          node.returnType = this.tsParseTypeOrTypePredicateAnnotation(tokTypes.colon)
        }
 
        const bodilessType =
          type === 'FunctionDeclaration'
            ? 'TSDeclareFunction'
            : type === 'ClassMethod' || type === 'ClassPrivateMethod'
              ? 'TSDeclareMethod'
              : undefined
        if (bodilessType && !this.match(tokTypes.braceL) && this.isLineTerminator()) {
          return this.finishNode(node, bodilessType)
        }
        Iif (bodilessType === 'TSDeclareFunction' && this.isAmbientContext) {
          this.raise(node.start, TypeScriptError.DeclareFunctionHasImplementation)
          // @ts-ignore
          if ((node as FunctionDeclaration).declare) {
            // @ts-ignore
            this.parseFunctionBody(node, false, isMethod, false)
            return this.finishNode(node, bodilessType)
          }
        }
        // @ts-ignore
        this.parseFunctionBody(node, false, isMethod, forInit)
        return this.finishNode(node, type)
      }
 
      parseNew() {
        Iif (this['containsEsc']) this.raiseRecoverable(this.start, 'Escape sequence in keyword new')
        // @ts-ignore
        let node = this.startNode()
        // @ts-ignore
        let meta = this.parseIdent(true)
        // @ts-ignore
        Iif (this.options.ecmaVersion >= 6 && this.eat(tokTypes.dot)) {
          node.meta = meta
          let containsEsc = this['containsEsc']
          // @ts-ignore
          node.property = this.parseIdent(true)
          if (node.property.name !== 'target')
            this.raiseRecoverable(node.property.start, 'The only valid meta property for new is \'new.target\'')
          if (containsEsc)
            this.raiseRecoverable(node.start, '\'new.target\' must not contain escaped characters')
          if (!this['allowNewDotTarget'])
            this.raiseRecoverable(node.start, '\'new.target\' can only be used in functions and class static block')
          return this.finishNode(node, 'MetaProperty')
        }
        let startPos = this.start, startLoc = this['startLoc'],
          isImport = this.type === tokTypes._import
        // @ts-ignore
        node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true, false)
        Iif (isImport && node.callee.type === 'ImportExpression') {
          this.raise(startPos, 'Cannot use new with import()')
        }
        // ---start parseNewCallee extension
        const { callee } = node
        Iif (
          callee.type === 'TSInstantiationExpression' &&
          !callee.extra?.parenthesized
        ) {
          node.typeParameters = callee.typeParameters
          node.callee = callee.expression
        }
        // ---end
        // @ts-ignore
        Eif (this.eat(tokTypes.parenL)) node.arguments = this.parseExprList(tokTypes.parenR, this.options.ecmaVersion >= 8, false)
        else node.arguments = []
        return this.finishNode(node, 'NewExpression')
      }
 
      parseExprOp(
        left: Expression,
        leftStartPos: number,
        leftStartLoc: Position,
        minPrec: number,
        forInit: boolean
      ): Expression {
        Iif (
          tokTypes._in.binop > minPrec &&
          !this.hasPrecedingLineBreak() &&
          this.ts_isContextual(tsTokenType.as)
        ) {
          // @ts-ignore
          const node = this.startNodeAt(
            leftStartPos,
            leftStartLoc
          )
          node.expression = left
          const _const = this.tsTryNextParseConstantContext()
          if (_const) {
            node.typeAnnotation = _const
          } else {
            node.typeAnnotation = this.tsNextThenParseType()
          }
          this.finishNode(node, 'TSAsExpression')
          // rescan `<`, `>` because they were scanned when this.state.inType was true
          this.reScan_lt_gt()
          return this.parseExprOp(
            node,
            leftStartPos,
            leftStartLoc,
            minPrec,
            forInit
          )
        }
        // @ts-ignore
        return super.parseExprOp(left, leftStartPos, leftStartLoc, minPrec)
      }
 
      /**
       * @param {Node} node this may be ImportDeclaration |
       * TsImportEqualsDeclaration
       * @returns AnyImport
       * */
      parseImport(
        node: any
      ) {
        this.next()
        node.importKind = 'value'
        if (
          tokenIsIdentifier(this.type) ||
          this.match(tokTypes.star) ||
          this.match(tokTypes.braceL)
        ) {
          let ahead = this.lookahead()
          if (
            this.ts_type_isContextual(this.type, tsTokenType.type) &&
            // import type, { a } from "b";
            ahead.type !== tokTypes.comma &&
            // import type from "a";
            ahead.type !== tsTokenType.from &&
            // import type = require("a");
            ahead.type !== tokTypes.eq
          ) {
            node.importKind = 'type'
            this.next()
            ahead = this.lookahead()
          }
 
          Iif (tokenIsIdentifier(this.type) && ahead.type === tokTypes.eq) {
            return this.tsParseImportEqualsDeclaration(node)
          }
        }
 
        // ---start origin parseImport
        if (this.type === tokTypes.string) {
          node.specifiers = []
          node.source = this.parseExprAtom()
        } else {
          node.specifiers = this.parseImportSpecifiers()
          // @ts-ignore
          this.expectContextual('from')
          // @ts-ignore
          node.source = this.type === tokTypes.string ? this.parseExprAtom() : this.unexpected()
        }
        // @ts-ignore
        super.semicolon()
        const importNode = this.finishNode(node, 'ImportDeclaration')
        // ---end
 
        /*:: invariant(importNode.type !== "TSImportEqualsDeclaration") */
 
        // `import type` can only be used on imports with named imports or with a
        // default import - but not both
        Iif (
          // @ts-ignore
          importNode.importKind === 'type' &&
          // @ts-ignore
          importNode.specifiers.length > 1 &&
          // @ts-ignore
          importNode.specifiers[0].type === 'ImportDefaultSpecifier'
        ) {
          this.raise(importNode.start, TypeScriptError.TypeImportCannotSpecifyDefaultAndNamed)
        }
 
        return importNode
      }
 
      parseExport(node: Node, exports: any): any {
        this.next()
        Iif (this.match(tokTypes._import)) {
          this.next() // eat `tokTypes._import`
          if (
            this.ts_isContextual(tsTokenType.type) &&
            this.lookaheadCharCode() !== charCodes.equalsTo
          ) {
            // @ts-ignore
            node.importKind = 'type'
            this.next() // eat "type"
          } else {
            // @ts-ignore
            node.importKind = 'value'
          }
          return this.tsParseImportEqualsDeclaration(
            node,
            /* isExport */ true
          )
          // @ts-ignore
        } else Iif (this.eat(tokTypes.eq)) {
          // `export = x;`
          const assign = node
          // @ts-ignore
          assign.expression = this.parseExpression()
          // @ts-ignore
          this.semicolon()
          return this.finishNode(assign, 'TSExportAssignment')
        } else Iif (this.eatContextual('as')) {
          // `export as namespace A;`
          const decl = node
          // See `parseNamespaceExportDeclaration` in TypeScript's own parser
          // @ts-ignore
          this.expectContextual(tsTokenType.namespace)
          // @ts-ignore
          decl.id = this.parseIdent()
          // @ts-ignore
          this.semicolon()
          return this.finishNode(decl, 'TSNamespaceExportDeclaration')
        } else {
          Iif (
            this.ts_isContextual(tsTokenType.type) &&
            this.lookahead().type === tokTypes.braceL
          ) {
            this.next()
            // @ts-ignore
            node.exportKind = 'type'
          } else {
            // @ts-ignore
            node.exportKind = 'value'
          }
 
          // ---start origin parseExport
          // export * from '...'
          // @ts-ignore
          Iif (this.eat(tokTypes.star)) {
            if (this.options.ecmaVersion >= 11) {
              if (this.eatContextual('as')) {
                // @ts-ignore
                node.exported = this.parseModuleExportName()
                // @ts-ignore
                this.checkExport(exports, node.exported, this['lastTokStart'])
              } else {
                // @ts-ignore
                node.exported = null
              }
            }
            // @ts-ignore
            this.expectContextual('from')
            // @ts-ignore
            if (this.type !== tokTypes.string) this.unexpected()
            // @ts-ignore
            node.source = this.parseExprAtom()
            // @ts-ignore
            this.semicolon()
            return this.finishNode(node, 'ExportAllDeclaration')
          }
          // @ts-ignore
          if (this.eat(tokTypes._default)) { // export default ...
            // ---start ts extension
            Iif (this.isAbstractClass()) {
              // @ts-ignore
              const cls = this.startNode()
              this.next() // Skip "abstract"
              cls.abstract = true
              return this.parseClass(cls, true)
            }
 
            // export default interface allowed in:
            // https://github.com/Microsoft/TypeScript/pull/16040
            Iif (this.match(tsTokenType.interface)) {
              // @ts-ignore
              const result = this.tsParseInterfaceDeclaration(this.startNode())
              if (result) return result
            }
            // ---end
            // @ts-ignore
            this.checkExport(exports, 'default', this['lastTokStart'])
            let isAsync
            // @ts-ignore
            if (this.type === tokTypes._function || (isAsync = this.isAsyncFunction())) {
              // @ts-ignore
              let fNode = this.startNode()
              this.next()
              Iif (isAsync) this.next()
              // @ts-ignore
              node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync)
            } else Iif (this.type === tokTypes._class) {
              // @ts-ignore
              let cNode = this.startNode()
              // @ts-ignore
              node.declaration = this.parseClass(cNode, 'nullableID')
            } else {
              // @ts-ignore
              node.declaration = this.parseMaybeAssign()
              // @ts-ignore
              this.semicolon()
            }
            return this.finishNode(node, 'ExportDefaultDeclaration')
          }
          // export var|const|let|function|class ...
          if (this.shouldParseExportStatement()) {
            // @ts-ignore
            node.declaration = this.parseExportDeclaration(node)
            // @ts-ignore
            if (node.declaration.type === 'VariableDeclaration')
              // @ts-ignore
              this.checkVariableExport(exports, node.declaration.declarations)
            else
              // @ts-ignore
              this.checkExport(exports, node.declaration.id, node.declaration.id.start)
            // @ts-ignore
            node.specifiers = []
            // @ts-ignore
            node.source = null
          } else { // export { x, y as z } [from '...']
            // @ts-ignore
            node.declaration = null
            // @ts-ignore
            const isTypeExport = node.exportKind === 'type'
            // @ts-ignore
            node.specifiers = this.parseExportSpecifiers(exports, isTypeExport)
            Iif (this.eatContextual('from')) {
              // @ts-ignore
              if (this.type !== tokTypes.string) this.unexpected()
              // @ts-ignore
              node.source = this.parseExprAtom()
            } else {
              // @ts-ignore
              for (let spec of node.specifiers) {
                // check for keywords used as local names
                // @ts-ignore
                this.checkUnreserved(spec.local)
                // check if export is defined
                // @ts-ignore
                this.checkLocalExport(spec.local)
 
                Iif (spec.local.type === 'Literal') {
                  this.raise(spec.local.start, 'A string literal cannot be used as an exported binding without `from`.')
                }
              }
              // @ts-ignore
              node.source = null
            }
            // @ts-ignore
            this.semicolon()
          }
          return this.finishNode(node, 'ExportNamedDeclaration')
          // ---end
        }
      }
 
      // todo we don't need these functions, we have to rewrite the
      //  parseClassElement function in acorn
      // === === === === === === === === === === === === === === === ===
      // Note: All below methods are duplicates of something in flow.js.
      // Not sure what the best way to combine these is.
      // === === === === === === === === === === === === === === === ===
 
      // isClassMethod(): boolean {
      //   return this.match(tt.lt) || super.isClassMethod();
      // }
      //
      // isClassProperty(): boolean {
      //   return (
      //     this.match(tt.bang) || this.match(tt.colon) || super.isClassProperty()
      //   );
      // }
 
      parseMaybeDefault(
        startPos?: number | null,
        startLoc?: Position | null,
        left?: Pattern | null
      ): Pattern {
        // @ts-ignore
        const node = super.parseMaybeDefault(startPos, startLoc, left)
 
        Iif (
          node.type === 'AssignmentPattern' &&
          node.typeAnnotation &&
          node.right.start < node.typeAnnotation.start
        ) {
          this.raise(node.typeAnnotation.loc.start, TypeScriptError.TypeAnnotationAfterAssign)
        }
 
        return node
      }
 
      typeCastToParameter(node: Node): Node {
        // @ts-ignore
        node.expression.typeAnnotation = node.typeAnnotation
        // @ts-ignore
        this.resetEndLocation(node.expression, node.typeAnnotation.end)
        // @ts-ignore
        return node.expression
      }
 
      toAssignableList(
        exprList: Expression[],
        isBinding: boolean
      ): void {
        for (let i = 0; i < exprList.length; i++) {
          const expr = exprList[i]
          // @ts-ignore
          if (expr?.type === 'TSTypeCastExpression') {
            // @ts-ignore
            exprList[i] = this.typeCastToParameter(expr)
          }
        }
        // @ts-ignore
        return super.toAssignableList(exprList, isBinding)
      }
 
      reportReservedArrowTypeParam(node: any) {
        if (
          node.params.length === 1 &&
          !node.extra?.trailingComma &&
          disallowAmbiguousJSXLike
        ) {
          this.raise(node.start, TypeScriptError.ReservedArrowTypeParam)
        }
      }
 
      // Handle type assertions
      parseMaybeUnary(
        refExpressionErrors?: any,
        sawUnary?: boolean
      ): Expression {
        // todo support jsx
        // if (!this.hasPlugin("jsx") && this.match(tt.lt)) {
        //   return this.tsParseTypeAssertion();
        // } else {
        // }
        // @ts-ignore
        return super.parseMaybeUnary(refExpressionErrors, sawUnary)
      }
 
      parseExprAtom(refDestructuringErrors?: DestructuringErrors, forInit?: boolean) {
        // If a division operator appears in an expression position, the
        // tokenizer got confused, and we force it to read a regexp instead.
        // @ts-ignore
        Iif (this.type === tokTypes.slash) this.readRegexp()
 
        let node, canBeArrow = this['potentialArrowAt'] === this.start
        switch (this.type) {
          case tokTypes._super:
            Iif (!this['allowSuper'])
              this.raise(this.start, '\'super\' keyword outside a method')
            // @ts-ignore
            node = this.startNode()
            this.next()
            Iif (this.type === tokTypes.parenL && !this['allowDirectSuper'])
              this.raise(node.start, 'super() call outside constructor of a subclass')
            // The `super` keyword can appear at below:
            // SuperProperty:
            //     super [ Expression ]
            //     super . IdentifierName
            // SuperCall:
            //     super ( Arguments )
            Iif (this.type !== tokTypes.dot && this.type !== tokTypes.bracketL && this.type !== tokTypes.parenL)
              // @ts-ignore
              this.unexpected()
            return this.finishNode(node, 'Super')
 
          case tokTypes._this:
            // @ts-ignore
            node = this.startNode()
            this.next()
            return this.finishNode(node, 'ThisExpression')
 
          case tokTypes.name:
            let startPos = this.start, startLoc = this['startLoc'],
              containsEsc = this['containsEsc']
            // @ts-ignore
            let id = this.parseIdent(false)
            // @ts-ignore
            Iif (this.options.ecmaVersion >= 8 && !containsEsc && id.name === 'async' && !this.canInsertSemicolon() && this.eat(tokTypes._function)) {
              // @ts-ignore
              this.overrideContext(tokContexts.f_expr)
              // @ts-ignore
              return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit)
            }
            // @ts-ignore
            if (canBeArrow && !this.canInsertSemicolon()) {
              // @ts-ignore
              Iif (this.eat(tokTypes.arrow))
                // @ts-ignore
                return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit)
              Iif (this.options.ecmaVersion >= 8 && id.name === 'async' && this.type === tokTypes.name && !containsEsc &&
                // @ts-ignore
                (!this.potentialArrowInForAwait || this['value'] !== 'of' || this['containsEsc'])) {
                // @ts-ignore
                id = this.parseIdent(false)
                // @ts-ignore
                if (this.canInsertSemicolon() || !this.eat(tokTypes.arrow))
                  // @ts-ignore
                  this.unexpected()
                // @ts-ignore
                return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit)
              }
            }
            return id
 
          case tokTypes.regexp:
            let value = this['value']
            // @ts-ignore
            node = this.parseLiteral(value.value)
            // @ts-ignore
            node.regex = { pattern: value.pattern, flags: value.flags }
            return node
 
          case tokTypes.num:
          case tokTypes.string:
            // @ts-ignore
            return this.parseLiteral(this['value'])
 
          case tokTypes._null:
          case tokTypes._true:
          case tokTypes._false:
            // @ts-ignore
            node = this.startNode()
            node.value = this.type === tokTypes._null ? null : this.type === tokTypes._true
            node.raw = this.type.keyword
            this.next()
            return this.finishNode(node, 'Literal')
 
          case tokTypes.parenL:
            let start = this.start,
              expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit)
            Eif (refDestructuringErrors) {
              // @ts-ignore
              Eif (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
                refDestructuringErrors.parenthesizedAssign = start
              Eif (refDestructuringErrors.parenthesizedBind < 0)
                refDestructuringErrors.parenthesizedBind = start
            }
            return expr
 
          case tokTypes.bracketL:
            // @ts-ignore
            node = this.startNode()
            this.next()
            // @ts-ignore
            node.elements = this.parseExprList(tokTypes.bracketR, true, true, refDestructuringErrors)
            // NODE check array like here
            this.tsCheckForInvalidTypeCasts(node.elements)
            return this.finishNode(node, 'ArrayExpression')
 
          case tokTypes.braceL:
            // @ts-ignore
            this.overrideContext(tokContexts.b_expr)
            // @ts-ignore
            return this.parseObj(false, refDestructuringErrors)
 
          case tokTypes._function:
            // @ts-ignore
            node = this.startNode()
            this.next()
            // @ts-ignore
            return this.parseFunction(node, 0)
 
          case tokTypes._class:
            // @ts-ignore
            return this.parseClass(this.startNode(), false)
 
          case tokTypes._new:
            return this.parseNew()
 
          case tokTypes.backQuote:
            return this.parseTemplate()
 
          case tokTypes._import:
            if (this.options.ecmaVersion >= 11) {
              // @ts-ignore
              return this.parseExprImport()
            } else {
              // @ts-ignore
              return this.unexpected()
            }
 
          default:
            Eif (tokenIsIdentifier(this.type)) {
              // if (
              //   this.ts_isContextual(tsTokenType.module) &&
              //   this.lookaheadCharCode() === charCodes.leftCurlyBrace &&
              //   !this.hasFollowingLineBreak()
              // ) {
              //   return this.parseModuleExpression();
              // }
              const canBeArrow = this['potentialArrowAt'] === this.start
              const containsEsc = this['containsEsc']
              // @ts-ignore
              const id = this.parseIdent()
 
              Iif (
                !containsEsc &&
                id.name === 'async' &&
                // @ts-ignore
                !this.canInsertSemicolon()
              ) {
                const { type } = this
                if (type === tokTypes._function) {
                  this.next()
                  // @ts-ignore
                  return this.parseFunction(
                    this.startNodeAtNode(id),
                    undefined,
                    true,
                    true,
                    forInit
                  )
                } else if (tokenIsIdentifier(type)) {
                  // If the next token begins with "=", commit to parsing an async
                  // arrow function. (Peeking ahead for "=" lets us avoid a more
                  // expensive full-token lookahead on this common path.)
                  if (this.lookaheadCharCode() === charCodes.equalsTo) {
                    // although `id` is not used in async arrow unary function,
                    // we don't need to reset `async`'s trailing comments because
                    // it will be attached to the upcoming async arrow binding identifier
                    // @ts-ignore
                    if (this.canInsertSemicolon() || !this.eat(tt.arrow))
                      // @ts-ignore
                      this.unexpected()
 
                    return this.parseArrowExpression(
                      this.startNodeAtNode(id),
                      [id], true, forInit
                    )
                  } else {
                    // Otherwise, treat "async" as an identifier and let calling code
                    // deal with the current tt.name token.
                    return id
                  }
                }
                // todo supprt parse do
                // else if (type === tokTypes._do) {
                //   this.resetPreviousNodeTrailingComments(id);
                //   return this.parseDo(this.startNodeAtNode(id), true);
                // }
              }
 
              Iif (
                canBeArrow &&
                this.match(tokTypes.arrow) &&
                // @ts-ignore
                !this.canInsertSemicolon()
              ) {
                this.next()
                return this.parseArrowExpression(
                  this.startNodeAtNode(id),
                  [id],
                  false,
                  forInit
                )
              }
 
              return id
            } else {
              // @ts-ignore
              this.unexpected()
            }
        }
      }
 
      // @ts-ignore
      parseIdent(liberal?: boolean, isBinding?: boolean) {
        // @ts-ignore
        var node = this.startNode()
        if (this.type === tokTypes.name) {
          node.name = this['value']
        } else Eif (tokenIsKeywordOrIdentifier(this.type)) {
          node.name = this['value']
        } else if (this.type.keyword) {
          node.name = this.type.keyword
 
          // To fix https://github.com/acornjs/acorn/issues/575
          // `class` and `function` keywords push new context into this.context.
          // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
          // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
          if ((node.name === 'class' || node.name === 'function') &&
            (this['lastTokEnd'] !== this['lastTokStart'] + 1 || this.input.charCodeAt(this['lastTokStart']) !== 46)) {
            this['context'].pop()
          }
        } else {
          // @ts-ignore
          this.unexpected()
        }
        // @ts-ignore
        this.next(!!liberal)
        this.finishNode(node, 'Identifier')
        if (!liberal) {
          // @ts-ignore
          this.checkUnreserved(node)
          Iif (node.name === 'await' && !this['awaitIdentPos']) {
            this['awaitIdentPos'] = node.start
          }
        }
        return node
      };
 
      parseVar(node, isFor, kind, allowMissingInitializer: boolean = false) {
        node.declarations = []
        node.kind = kind
        for (; ;) {
          // @ts-ignore
          let decl = this.startNode()
          this.parseVarId(decl, kind)
          // @ts-ignore
          if (this.eat(tokTypes.eq)) {
            decl.init = this.parseMaybeAssign(isFor)
            // @ts-ignore
          } else Iif (!allowMissingInitializer && kind === 'const' && !(this.type === tokTypes._in || (this.options.ecmaVersion >= 6 && this.isContextual('of')))) {
            // @ts-ignore
            this.unexpected()
            // @ts-ignore
          } else Iif (!allowMissingInitializer && decl.id.type !== 'Identifier' && !(isFor && (this.type === tokTypes._in || this.isContextual('of')))) {
            this.raise(this['lastTokEnd'], 'Complex binding patterns require an initialization value')
          } else {
            decl.init = null
          }
          node.declarations.push(this.finishNode(decl, 'VariableDeclarator'))
          // @ts-ignore
          Eif (!this.eat(tokTypes.comma)) break
        }
        return node
      }
 
      parseVarStatement(node, kind, allowMissingInitializer: boolean = false) {
        const { isAmbientContext } = this
 
        // ---start origin parseVarStatement
        this.next()
        this.parseVar(node, false, kind, allowMissingInitializer || isAmbientContext)
        // @ts-ignore
        this.semicolon()
        const declaration = this.finishNode(node, 'VariableDeclaration')
        // ---end
 
        if (!isAmbientContext) return declaration
        // @ts-ignore
        for (const { id, init } of declaration.declarations) {
          // Empty initializer is the easy case that we want.
          Eif (!init) continue
 
          // var and let aren't ever allowed initializers.
          //
          // If a const declaration has no type annotation and is initiailized to
          // a string literal, numeric literal, or enum reference, then it is
          // allowed. In an ideal world, we'd check whether init was *actually* an
          // enum reference, but we allow anything that "could be" a literal enum
          // in `isPossiblyLiteralEnum` since we don't have all the information
          // that the typescript compiler has.
          if (kind !== 'const' || !!id.typeAnnotation) {
            this.raise(init.start, TypeScriptError.InitializerNotAllowedInAmbientContext)
          } else if (
            init.type !== 'StringLiteral' &&
            init.type !== 'BooleanLiteral' &&
            init.type !== 'NumericLiteral' &&
            init.type !== 'BigIntLiteral' &&
            (init.type !== 'TemplateLiteral' || init.expressions.length > 0) &&
            !isPossiblyLiteralEnum(init)
          ) {
            this.raise(
              init.start,
              TypeScriptError.ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference
            )
          }
        }
 
        return declaration
      }
 
      parseStatement(context: any, topLevel?: any, exports?: any) {
        Iif (this.match(tokTypes._const) && this.isLookaheadContextual('enum')) {
          // @ts-ignore
          const node = this.startNode()
          // @ts-ignore
          this.expect(tokTypes._const) // eat 'const'
          return this.tsParseEnumDeclaration(node, { const: true })
        }
 
        if (this.ts_isContextual(tsTokenType.enum)) {
          return this.tsParseEnumDeclaration(
            // @ts-ignore
            this.startNode()
          )
        }
 
        if (this.ts_isContextual(tsTokenType.interface)) {
          // @ts-ignore
          const result = this.tsParseInterfaceDeclaration(this.startNode())
          Eif (result) return result
        }
        // @ts-ignore
        return super.parseStatement(context, topLevel, exports)
      }
 
      // NOTE: unused function
      parseAccessModifier(): Accessibility | undefined | null {
        return this.tsParseModifier(['public', 'protected', 'private'])
      }
 
      parsePostMemberNameModifiers(
        methodOrProp: Node
      ): void {
        // @ts-ignore
        const optional = this.eat(tokTypes.question)
        // @ts-ignore
        Iif (optional) methodOrProp.optional = true
 
        Iif ((methodOrProp as any).readonly && this.match(tokTypes.parenL)) {
          this.raise(methodOrProp.start, TypeScriptError.ClassMethodHasReadonly)
        }
 
        Iif ((methodOrProp as any).declare && this.match(tokTypes.parenL)) {
          this.raise(methodOrProp.start, TypeScriptError.ClassMethodHasDeclare)
        }
      }
 
      // Note: The reason we do this in `parseExpressionStatement` and not `parseStatement`
      // is that e.g. `type()` is valid JS, so we must try parsing that first.
      // If it's really a type, we will parse `type` as the statement, and can correct it here
      // by parsing the rest.
      parseExpressionStatement(
        node,
        expr
      ) {
        const decl =
          expr.type === 'Identifier'
            ? this.tsParseExpressionStatement(node, expr)
            : undefined
        // @ts-ignore
        return decl || super.parseExpressionStatement(node, expr)
      }
 
      // todo this is shouldParseExportDeclaration
      shouldParseExportStatement(): boolean {
        if (this.tsIsDeclarationStart()) return true
        // @ts-ignore
        return super.shouldParseExportStatement()
      }
 
      parseConditional(
        expr: Expression,
        startPos: number,
        startLoc: Position,
        forInit?: boolean,
        // @ts-ignore
        refDestructuringErrors?: any): any {
        // @ts-ignore
        Iif (this.eat(tokTypes.question)) {
          // @ts-ignore
          let node = this.startNodeAt(startPos, startLoc)
          node.test = expr
          node.consequent = this.parseMaybeAssign()
          // @ts-ignore
          this.expect(tokTypes.colon)
          node.alternate = this.parseMaybeAssign(forInit)
          return this.finishNode(node, 'ConditionalExpression')
        }
        return expr
      }
 
      parseMaybeConditional(forInit, refDestructuringErrors) {
        let startPos = this.start, startLoc = this['startLoc']
        // @ts-ignore
        let expr = this.parseExprOps(forInit, refDestructuringErrors)
        // @ts-ignore
        Iif (this.checkExpressionErrors(refDestructuringErrors)) return expr
        // todo parseConditional ts support
        Eif (!this.maybeInArrowParameters || !this.match(tokTypes.question)) {
          return this.parseConditional(
            expr,
            startPos,
            startLoc,
            forInit,
            refDestructuringErrors
          )
        }
 
        const result = this.tryParse(() =>
          this.parseConditional(expr, startPos, startLoc, forInit, refDestructuringErrors)
        )
 
        if (!result.node) {
          if (result.error) {
            /*:: invariant(refExpressionErrors != null) */
            this.setOptionalParametersError(refDestructuringErrors, result.error)
          }
 
          return expr
        }
        if (result.error) this.setLookaheadState(result.failState)
        return result.node
      }
 
      parseParenItem(node: Expression) {
        const startPos = this.start
        const startLoc = this['startLoc']
        // @ts-ignore
        node = super.parseParenItem(node)
        // @ts-ignore
        if (this.eat(tokTypes.question)) {
          // @ts-ignore
          node.optional = true
          // Include questionmark in location of node
          // Don't use this.finishNode() as otherwise we might process comments twice and
          // include already consumed parens
          this.resetEndLocation(node)
        }
 
        if (this.match(tokTypes.colon)) {
          // @ts-ignore
          const typeCastNode = this.startNodeAt(
            startPos,
            startLoc
          )
          typeCastNode.expression = node
          typeCastNode.typeAnnotation = this.tsParseTypeAnnotation()
 
          return this.finishNode(typeCastNode, 'TSTypeCastExpression')
        }
 
        return node
      }
 
      parseExportDeclaration(
        node: any
      ): any | undefined | null {
        Iif (!this.isAmbientContext && this.ts_isContextual(tsTokenType.declare)) {
          return this.tsInAmbientContext(() => this.parseExportDeclaration(node))
        }
 
        // Store original location/position
        const startPos = this.start
        const startLoc = this['startLoc']
 
        const isDeclare = this.eatContextual('declare')
 
        Iif (
          isDeclare &&
          (this.ts_isContextual(tsTokenType.declare) || !this.shouldParseExportStatement())
        ) {
          this.raise(this.start, TypeScriptError.ExpectedAmbientAfterExportDeclare)
        }
 
        const isIdentifier = tokenIsIdentifier(this.type)
        const declaration =
          (isIdentifier && this.tsTryParseExportDeclaration()) ||
          this.parseStatement(null)
 
        Iif (!declaration) return null
 
        if (
          declaration.type === 'TSInterfaceDeclaration' ||
          declaration.type === 'TSTypeAliasDeclaration' ||
          isDeclare
        ) {
          node.exportKind = 'type'
        }
 
        Iif (isDeclare) {
          // Reset location to include `declare` in range
          this.resetStartLocation(declaration, startPos, startLoc)
 
          declaration.declare = true
        }
 
        return declaration
      }
 
      parseClassId(
        node: Class,
        isStatement: boolean
      ): void {
        Iif ((!isStatement) && this.ts_isContextual(tsTokenType.implements)) {
          return
        }
        // @ts-ignore
        super.parseClassId(
          node,
          isStatement
        )
        const typeParameters = this.tsTryParseTypeParameters(
          this.tsParseInOutModifiers.bind(this)
        )
        // @ts-ignore
        Iif (typeParameters) node.typeParameters = typeParameters
      }
 
      parseClassPropertyAnnotation(
        node: Node
      ): void {
        // @ts-ignore
        Iif (!node.optional && (this.eat(tokTypes.prefix) && this['value'] === '!')) node.definite = true
 
        const type = this.tsTryParseTypeAnnotation()
        // @ts-ignore
        Eif (type) node.typeAnnotation = type
      }
 
      parsePrivateClassField(field) {
        // --- start ts parseClassPrivateProperty
        if (field.abstract) {
          this.raise(field.start, TypeScriptError.PrivateElementHasAbstract)
        }
 
        if (field.accessibility) {
          this.raise(field.start, TypeScriptError.PrivateElementHasAccessibility({
            modifier: field.accessibility
          }))
        }
 
        this.parseClassPropertyAnnotation(field)
        // --- end
        // @ts-ignore
        return super.parseClassField(field)
      }
 
      parseClassField(field) {
        // --- start ts parseClassProperty
        this.parseClassPropertyAnnotation(field)
 
        Iif (
          this.isAmbientContext &&
          !(field.readonly && !field.typeAnnotation) &&
          this.match(tokTypes.eq)
        ) {
          this.raise(this['startLoc'], TypeScriptError.DeclareClassFieldHasInitializer)
        }
        Iif (field.abstract && this.match(tokTypes.eq)) {
          const { key } = field
          this.raise(this['startLoc'], TypeScriptError.AbstractPropertyHasInitializer({
            propertyName:
              key.type === 'Identifier' && !field.computed
                ? key.name
                : `[${this.input.slice(key.start, key.end)}]`
          }))
        }
        // --- end
        // @ts-ignore
        return super.parseClassField(field)
      }
 
      parsePrivateClassMethod(method, isGenerator, isAsync, allowsDirectSuper) {
        const typeParameters = this.tsTryParseTypeParameters()
        if (typeParameters) method.typeParameters = typeParameters
        // @ts-ignore
        this.parseClassMethod(method, isGenerator, isAsync, allowsDirectSuper, true)
      }
 
      parseClassMethod(method, isGenerator, isAsync, allowsDirectSuper, isPrivate?: boolean) {
        // start typescript parse class method
        const isConstructor = method.kind === 'constructor'
        // todo pushClassPrivateMethod
        const typeParameters = this.tsTryParseTypeParameters()
        Iif (typeParameters && isConstructor) {
          this.raise(typeParameters.start, TypeScriptError.ConstructorHasTypeParameters)
        }
 
        const { declare = false, kind } = method
 
        Iif (declare && (kind === 'get' || kind === 'set')) {
          this.raise(method.start, TypeScriptError.DeclareAccessor({ kind }))
        }
        Iif (typeParameters) method.typeParameters = typeParameters
        // end
        // @ts-ignore
 
        // Check key and flags
        const key = method.key
        if (method.kind === 'constructor') {
          Iif (isGenerator) this.raise(key.start, 'Constructor can\'t be a generator')
          Iif (isAsync) this.raise(key.start, 'Constructor can\'t be an async method')
        } else Iif (method.static && checkKeyName(method, 'prototype')) {
          this.raise(key.start, 'Classes may not have a static property named prototype')
        }
 
        // Parse value
        const value = method.value = this.parseMethodForClass(isGenerator, isAsync, allowsDirectSuper, isPrivate)
 
        // Check value
        Iif (method.kind === 'get' && value['params'].length !== 0)
          this.raiseRecoverable(value.start, 'getter should have no params')
        Iif (method.kind === 'set' && value['params'].length !== 1)
          this.raiseRecoverable(value.start, 'setter should have exactly one param')
        Iif (method.kind === 'set' && value['params'][0].type === 'RestElement')
          this.raiseRecoverable(value['params'][0].start, 'Setter cannot use rest params')
 
        return this.finishNode(method, 'MethodDefinition')
      }
 
      parseClassElementName(element) {
        Iif (this.type === tokTypes.privateId) {
          if (this['value'] === 'constructor') {
            this.raise(this.start, 'Classes can\'t have an element named \'#constructor\'')
          }
          element.computed = false
          // @ts-ignore
          element.key = this.parsePrivateIdent()
        } else {
          // @ts-ignore
          this.parsePropertyName(element)
        }
      }
 
      parseClassElement(constructorAllowsSuper) {
        // @ts-ignore
        Iif (this.eat(tokTypes.semi)) return null
 
        const ecmaVersion = this.options.ecmaVersion
        // @ts-ignore
        const node = this.startNode()
        let keyName = ''
        let isGenerator = false
        let isAsync = false
        let kind = 'method'
 
        // todo parseClassMember
        // --- start parseClassMember extension
        const modifiers = [
          'declare',
          'private',
          'public',
          'protected',
          'override',
          'abstract',
          'readonly',
          'static'
        ] as const
        this.tsParseModifiers({
          modified: node,
          allowedModifiers: modifiers,
          disallowedModifiers: ['in', 'out'],
          stopOnStartOfClassStaticBlock: true,
          errorTemplate: TypeScriptError.InvalidModifierOnTypeParameterPositions
        })
 
        let isStatic = !!node.static
 
        const callParseClassMemberWithIsStatic = () => {
          Iif (this.tsIsStartOfStaticBlocks()) {
            this.next() // eat "static"
            this.next() // eat "{"
            if (this.tsHasSomeModifiers(node, modifiers)) {
              this.raise(this.start, TypeScriptError.StaticBlockCannotHaveModifier)
            }
 
            if (ecmaVersion >= 13) {
              // @ts-ignore
              super.parseClassStaticBlock(
                node
              )
              return node
            }
          } else {
            // todo parseClassMemberWithIsStatic
            // --- start ts extension
            const idx = this.tsTryParseIndexSignature(node)
            Iif (idx) {
              if ((node as any).abstract) {
                this.raise(node.start, TypeScriptError.IndexSignatureHasAbstract)
              }
              if ((node as any).accessibility) {
                this.raise(node.start, TypeScriptError.IndexSignatureHasAccessibility({
                  modifier: (node as any).accessibility
                }))
              }
              if ((node as any).declare) {
                this.raise(node.start, TypeScriptError.IndexSignatureHasDeclare)
              }
              if ((node as any).override) {
                this.raise(node.start, TypeScriptError.IndexSignatureHasOverride)
              }
 
              return idx
            }
 
            Iif (!this.inAbstractClass && (node as any).abstract) {
              this.raise(node.start, TypeScriptError.NonAbstractClassHasAbstractMethod)
            }
 
            Iif ((node as any).override) {
              if (constructorAllowsSuper) {
                this.raise(node.start, TypeScriptError.OverrideNotInSubClass)
              }
            }
            // --- end
 
 
            node.static = isStatic
            // todo we don't need parsePropertyNamePrefixOperator here, this
            //  plugin don't support flow
            //  this.parsePropertyNamePrefixOperator(member);
            Iif (!keyName && ecmaVersion >= 8 && this.eatContextual('async')) {
              // @ts-ignore
              if ((this.isClassElementNameStart() || this.type === tokTypes.star) && !this.canInsertSemicolon()) {
                isAsync = true
              } else {
                keyName = 'async'
              }
            }
            // @ts-ignore
            Iif (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(tokTypes.star)) {
              isGenerator = true
            }
            Eif (!keyName && !isAsync && !isGenerator) {
              const lastValue = this['value']
              if (this.eatContextual('get') || this.eatContextual('set')) {
                // @ts-ignore
                Eif (this.isClassElementNameStart()) {
                  kind = lastValue
                } else {
                  keyName = lastValue
                }
              }
            }
 
            let isPrivate = this.type === tokTypes.privateId
            // Parse element name
            Iif (keyName) {
              // 'async', 'get', 'set', or 'static' were not a keyword contextually.
              // The last token is any of those. Make it the element name.
              node.computed = false
              // @ts-ignore
              node.key = this.startNodeAt(this['lastTokStart'], this['lastTokStartLoc'])
              node.key.name = keyName
              this.finishNode(node.key, 'Identifier')
            } else {
              this.parseClassElementName(node)
            }
 
            // todo isClassMethod
            const isClassMethod = this.match(tokTypes.relational) || this.match(tokTypes.parenL)
            // Parse element value
            if (ecmaVersion < 13 || isClassMethod || kind !== 'method' || isGenerator || isAsync) {
              const isConstructor = !node.static && checkKeyName(node, 'constructor')
              const allowsDirectSuper = isConstructor && constructorAllowsSuper
              Iif (isConstructor && kind !== 'method') this.raise(node.key.start, 'Constructor can\'t have get/set modifier')
              node.kind = isConstructor ? 'constructor' : kind
              // ts Overridden
              this.parsePostMemberNameModifiers(node)
              // todo private or not
              Eif (!isPrivate) {
                this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper, false)
              } else {
                this.parsePrivateClassMethod(node, isGenerator, isAsync, allowsDirectSuper)
              }
            } else {
              // ts Overridden
              this.parsePostMemberNameModifiers(node)
              // todo private or not
              Eif (!isPrivate) {
                this.parseClassField(node)
              } else {
                this.parsePrivateClassField(node)
              }
            }
 
            return node
          }
        }
        Iif (node.declare) {
          this.tsInAmbientContext(callParseClassMemberWithIsStatic)
        } else {
          callParseClassMemberWithIsStatic()
        }
        // --- end
        return node
      }
 
      parseClassSuper(node: Class): void {
        // @ts-ignore
        super.parseClassSuper(node)
        // handle `extends f<<T>
        Iif (node.superClass && (this.match(tokTypes.relational) || this.match(tokTypes.bitShift))) {
          // @ts-expect-error refine typings
          node.superTypeParameters = this.tsParseTypeArgumentsInExpression()
        }
        Iif (this.eatContextual('implements')) {
          // @ts-ignore
          node.implements = this.tsParseHeritageClause('implements')
        }
      }
 
      // todo parsePropertyValue
      // parseObjPropValue(
      //   prop: Undone<N.ObjectMethod | N.ObjectProperty>,
      //   startPos: number | undefined | null,
      //   startLoc: Position | undefined | null,
      //   isGenerator: boolean,
      //   isAsync: boolean,
      //   isPattern: boolean,
      //   isAccessor: boolean,
      //   refExpressionErrors?: ExpressionErrors | null
      // ) {
      //   const typeParameters = this.tsTryParseTypeParameters()
      //   if (typeParameters) prop.typeParameters = typeParameters
      //
      //   return super.parseObjPropValue(
      //     prop,
      //     startPos,
      //     startLoc,
      //     isGenerator,
      //     isAsync,
      //     isPattern,
      //     isAccessor,
      //     refExpressionErrors
      //   )
      // }
 
      parseFunctionParams(node: Function): void {
        const typeParameters = this.tsTryParseTypeParameters()
        // @ts-ignore
        Iif (typeParameters) node.typeParameters = typeParameters
        // @ts-ignore
        super.parseFunctionParams(node)
      }
 
      // `let x: number;`
      parseVarId(
        decl: VariableDeclarator,
        kind: 'var' | 'let' | 'const'
      ): void {
        // @ts-ignore
        super.parseVarId(decl, kind)
 
        Iif (
          decl.id.type === 'Identifier' &&
          !this.hasPrecedingLineBreak() &&
          // todo bang : type === prefix && value === '!'
          // @ts-ignore
          (this.eat(tokTypes.prefix) && this['value'] === '!')
        ) {
          // @ts-ignore
          decl.definite = true
        }
 
        const type = this.tsTryParseTypeAnnotation()
        if (type) {
          // @ts-ignore
          decl.id.typeAnnotation = type
          this.resetEndLocation(decl.id) // set end position to end of type
        }
      }
 
      // parse the return type of an async arrow function - let foo = (async (): number => {});
      parseArrowExpression(
        node: Node,
        params: Node[],
        isAsync: boolean,
        forInit: boolean
      ): ArrowFunctionExpression {
        Iif (this.match(tokTypes.colon)) {
          // @ts-ignore
          node.returnType = this.tsParseTypeAnnotation()
        }
        // @ts-ignore
        return super.parseArrowExpression(
          node,
          params,
          isAsync,
          forInit
        )
      }
 
      parseMaybeAssign(
        forInit?: boolean,
        refExpressionErrors?: any | null,
        afterLeftParse?: Function
      ): Expression {
        // Note: When the JSX plugin is on, type assertions (`<T> x`) aren't valid syntax.
 
        let state: LookaheadState | undefined | null
        let jsx
        let typeCast
 
        Iif (
          // todo we don't support jsx now
          // this.hasPlugin("jsx") &&
          false &&
          // @ts-ignore
          (this.match(tsTokenType.jsxTagStart) || this.match(tokTypes.relational))
        ) {
          // Prefer to parse JSX if possible. But may be an arrow fn.
          state = this.cloneCurLookaheadState()
 
          jsx = this.tryParse(
            // @ts-ignore
            () => super.parseMaybeAssign(forInit, refExpressionErrors, afterLeftParse),
            state
          )
 
          /*:: invariant(!jsx.aborted) */
          /*:: invariant(jsx.node != null) */
          if (!jsx.error) return jsx.node
 
          // Remove `tc.j_expr` or `tc.j_oTag` from context added
          // by parsing `jsxTagStart` to stop the JSX plugin from
          // messing with the tokens
          const context = this['context']
          // @ts-ignore
          const currentContext = context[context.length - 1]
 
          // todo delete the follow lines
          // if (currentContext === tc.j_oTag || currentContext === tc.j_expr) {
          //   context.pop()
          // }
        }
 
        Eif (!jsx?.error && !this.match(tokTypes.relational)) {
          // @ts-ignore
          return super.parseMaybeAssign(forInit, refExpressionErrors, afterLeftParse)
        }
 
        // Either way, we're looking at a '<': tt.jsxTagStart or relational.
 
        // If the state was cloned in the JSX parsing branch above but there
        // have been any error in the tryParse call, this.state is set to state
        // so we still need to clone it.
        if (!state || this.compareLookaheadState(state, this.getCurLookaheadState())) {
          state = this.cloneCurLookaheadState()
        }
 
        let typeParameters: Node | undefined | null
        const arrow = this.tryParse(abort => {
          // This is similar to TypeScript's `tryParseParenthesizedArrowFunctionExpression`.
          typeParameters = this.tsParseTypeParameters()
          // @ts-ignore
          const expr = super.parseMaybeAssign(
            forInit,
            refExpressionErrors,
            afterLeftParse
          )
 
          if (
            expr.type !== 'ArrowFunctionExpression' ||
            expr.extra?.parenthesized
          ) {
            abort()
          }
 
          // Correct TypeScript code should have at least 1 type parameter, but don't crash on bad code.
          // @ts-ignore
          if (typeParameters?.params.length !== 0) {
            this.resetStartLocationFromNode(expr, typeParameters)
          }
          expr.typeParameters = typeParameters
 
          // todo we don't support BABEL_8_BREAKING
          // if (process.env.BABEL_8_BREAKING) {
          //   if (
          //     this.hasPlugin('jsx') &&
          //     expr.typeParameters.params.length === 1 &&
          //     !expr.typeParameters.extra?.trailingComma
          //   ) {
          //     // report error if single type parameter used without trailing comma.
          //     const parameter = expr.typeParameters.params[0]
          //     if (!parameter.constraint) {
          //       // A single type parameter must either have constraints
          //       // or a trailing comma, otherwise it's ambiguous with JSX.
          //       this.raise(TypeScriptError.SingleTypeParameterWithoutTrailingComma, {
          //         at: createPositionWithColumnOffset(parameter.loc.end, 1),
          //         typeParameterName: parameter.name.name
          //       })
          //     }
          //   }
          // }
 
          return expr
        }, state)
 
        /*:: invariant(arrow.node != null) */
        if (!arrow.error && !arrow.aborted) {
          // This error is reported outside of the this.tryParse call so that
          // in case of <T>(x) => 2, we don't consider <T>(x) as a type assertion
          // because of this error.
          if (typeParameters) this.reportReservedArrowTypeParam(typeParameters)
          // @ts-expect-error refine typings
          return arrow.node
        }
 
        if (!jsx) {
          // Try parsing a type cast instead of an arrow function.
          // This will never happen outside of JSX.
          // (Because in JSX the '<' should be a jsxTagStart and not a relational.
 
          // this will always be true
          // assert(!this.hasPlugin('jsx'))
          assert(true)
 
          // This will start with a type assertion (via parseMaybeUnary).
          // But don't directly call `this.tsParseTypeAssertion` because we want to handle any binary after it.
          typeCast = this.tryParse(
            // @ts-ignore
            () => super.parseMaybeAssign(forInit, refExpressionErrors, afterLeftParse),
            state
          )
          /*:: invariant(!typeCast.aborted) */
          /*:: invariant(typeCast.node != null) */
          if (!typeCast.error) return typeCast.node
        }
 
        if (jsx?.node) {
          /*:: invariant(jsx.failState) */
          this.setLookaheadState(jsx.failState)
          return jsx.node
        }
 
        if (arrow.node) {
          /*:: invariant(arrow.failState) */
          this.setLookaheadState(arrow.failState)
          if (typeParameters) this.reportReservedArrowTypeParam(typeParameters)
          // @ts-expect-error refine typings
          return arrow.node
        }
 
        if (typeCast?.node) {
          /*:: invariant(typeCast.failState) */
          this.setLookaheadState(typeCast.failState)
          return typeCast.node
        }
 
        if (jsx?.thrown) throw jsx.error
        if (arrow.thrown) throw arrow.error
        if (typeCast?.thrown) throw typeCast.error
 
        throw jsx?.error || arrow.error || typeCast?.error
      }
 
      parseArrow(
        node: ArrowFunctionExpression
      ): ArrowFunctionExpression | undefined | null {
        Iif (this.match(tokTypes.colon)) {
          // This is different from how the TS parser does it.
          // TS uses lookahead. The Babel Parser parses it as a parenthesized expression and converts.
 
          const result = this.tryParse(abort => {
            const returnType = this.tsParseTypeOrTypePredicateAnnotation(
              tokTypes.colon
            )
            // @ts-ignore
            if (this.canInsertSemicolon() || !this.match(tokTypes.arrow)) abort()
            return returnType
          })
 
          if (result.aborted) return
 
          if (!result.thrown) {
            if (result.error) this.setLookaheadState(result.failState)
            // @ts-expect-error refine typings
            node.returnType = result.node
          }
        }
        // @ts-ignore
        Eif (this.eat(tokTypes.arrow)) {
          return node
        }
      }
 
      parseAssignableListItem(
        allowModifiers: boolean | undefined | null
      ) {
        // Store original location/position to include modifiers in range
        const startPos = this.start
        const startLoc = this['startLoc']
 
        let accessibility: any
        let readonly = false
        let override = false
        Eif (allowModifiers !== undefined) {
          const modified: ModifierBase = {}
          this.tsParseModifiers({
            modified,
            allowedModifiers: [
              'public',
              'private',
              'protected',
              'override',
              'readonly'
            ]
          })
          accessibility = modified.accessibility
          override = modified.override
          readonly = modified.readonly
          Iif (
            allowModifiers === false &&
            (accessibility || readonly || override)
          ) {
            this.raise(startLoc.start, TypeScriptError.UnexpectedParameterModifier)
          }
        }
 
        const left = this.parseMaybeDefault(startPos, startLoc)
        this.parseBindingListItem(left)
        // @ts-ignore
        const elt = this.parseMaybeDefault(left['start'], left['loc'], left)
        Iif (accessibility || readonly || override) {
          // @ts-ignore
          const pp = this.startNodeAt(startPos, startLoc)
          if (accessibility) pp.accessibility = accessibility
          if (readonly) pp.readonly = readonly
          if (override) pp.override = override
          if (elt.type !== 'Identifier' && elt.type !== 'AssignmentPattern') {
            this.raise(pp.start, TypeScriptError.UnsupportedParameterPropertyKind)
          }
          pp.parameter = elt as any
          return this.finishNode(pp, 'TSParameterProperty')
        }
 
        return elt
      }
 
      // Allow type annotations inside of a parameter list.
      parseBindingListItem(param: Pattern) {
        // @ts-ignore
        if (this.eat(tokTypes.question)) {
          Iif (
            param.type !== 'Identifier' &&
            !this.isAmbientContext &&
            !this.inType
          ) {
            // @ts-ignore
            this.raise(param.start, TypeScriptError.PatternIsOptional)
          }
          // @ts-ignore
          (param as any as Identifier).optional = true
        }
        const type = this.tsTryParseTypeAnnotation()
        // @ts-ignore
        if (type) param.typeAnnotation = type
        this.resetEndLocation(param)
 
        return param
      }
 
      isAssignable(node: any, isBinding?: boolean): boolean {
        switch (node.type) {
          case 'TSTypeCastExpression':
            // @ts-ignore
            return this.isAssignable(node.expression, isBinding)
          case 'TSParameterProperty':
            return true
          case 'Identifier':
          case 'ObjectPattern':
          case 'ArrayPattern':
          case 'AssignmentPattern':
          case 'RestElement':
            return true
 
          case 'ObjectExpression': {
            // @ts-ignore
            const last = node.properties.length - 1
            // @ts-ignore
            return (node.properties as ObjectExpression['properties']).every(
              (prop, i) => {
                return (
                  // @ts-ignore
                  prop.type !== 'ObjectMethod' &&
                  (i === last || prop.type !== 'SpreadElement') &&
                  this.isAssignable(prop)
                )
              }
            )
          }
 
          case 'ObjectProperty':
            return this.isAssignable(node.value)
 
          case 'SpreadElement':
            return this.isAssignable(node.argument)
 
          case 'ArrayExpression':
            return (node as ArrayExpression).elements.every(
              element => element === null || this.isAssignable(element)
            )
 
          case 'AssignmentExpression':
            return node.operator === '='
 
          case 'ParenthesizedExpression':
            return this.isAssignable(node.expression)
 
          case 'MemberExpression':
          case 'OptionalMemberExpression':
            return !isBinding
 
          default:
            return false
        }
      }
 
      toAssignable(
        node: Node,
        isBinding: boolean = false,
        refDestructuringErrors = new DestructuringErrors()
      ): any {
        switch (node.type) {
          case 'ParenthesizedExpression':
            return this.toAssignableParenthesizedExpression(node, isBinding, refDestructuringErrors)
          case 'TSAsExpression':
          case 'TSNonNullExpression':
          case 'TSTypeAssertion':
            if (isBinding) {
              // todo do nothing here
              // this.expressionScope.recordArrowParemeterBindingError(
              //   TypeScriptError.UnexpectedTypeCastInParameter,
              //   { at: node }
              // )
            } else {
              this.raise(node.start, TypeScriptError.UnexpectedTypeCastInParameter)
            }
            // @ts-ignore
            return this.toAssignable(node.expression, isBinding, refDestructuringErrors)
          case 'AssignmentExpression':
            // @ts-ignore
            if (!isBinding && node.left.type === 'TSTypeCastExpression') {
              // @ts-ignore
              node.left = this.typeCastToParameter(node.left)
            }
            return node
          /* fall through */
          default:
            // @ts-ignore
            return super.toAssignable(node, isBinding, refDestructuringErrors)
        }
      }
 
      toAssignableParenthesizedExpression(
        node: Node,
        isBinding: boolean,
        refDestructuringErrors: DestructuringErrors
      ): void {
        // @ts-ignore
        switch (node.expression.type) {
          case 'TSAsExpression':
          case 'TSNonNullExpression':
          case 'TSTypeAssertion':
          case 'ParenthesizedExpression':
            // @ts-ignore
            return this.toAssignable(node.expression, isBinding, refDestructuringErrors)
          default:
            // @ts-ignore
            return super.toAssignable(node, isBinding, refDestructuringErrors)
        }
      }
 
      curPosition() {
        Eif (this.options.locations) {
          // @ts-ignore
          const position = super.curPosition()
          Object.defineProperty(position, 'offset', {
            get() {
              return function(n: number) {
                // @ts-ignore
                const np = new AcornParser.acorn.Position(this.line, this.column + n)
                np['index'] = this['index'] + n
                return np
              }
            }
          })
          position['index'] = this['pos']
          return position
        }
      }
 
      // todo we don't need to check checkToRestConversion
      // checkToRestConversion(node: Node, allowPattern: boolean): void {
      //   switch (node.type) {
      //     case 'TSAsExpression':
      //     case 'TSTypeAssertion':
      //     case 'TSNonNullExpression':
      //       this.checkToRestConversion(node.expression, false)
      //       break
      //     default:
      //       super.checkToRestConversion(node, allowPattern)
      //   }
      // }
 
      // todo we don't need this function here
      // isValidLVal(
      //   type:
      //     | "TSTypeCastExpression"
      //     | "TSParameterProperty"
      //     | "TSNonNullExpression"
      //     | "TSAsExpression"
      //     | "TSTypeAssertion",
      //   isUnparenthesizedInAssign: boolean,
      //   binding: BindingTypes,
      // ) {
      //   return (
      //     getOwn(
      //       {
      //         // Allow "typecasts" to appear on the left of assignment expressions,
      //         // because it may be in an arrow function.
      //         // e.g. `const f = (foo: number = 0) => foo;`
      //         TSTypeCastExpression: true,
      //         TSParameterProperty: "parameter",
      //         TSNonNullExpression: "expression",
      //         TSAsExpression: (binding !== BIND_NONE ||
      //           !isUnparenthesizedInAssign) && ["expression", true],
      //         TSTypeAssertion: (binding !== BIND_NONE ||
      //           !isUnparenthesizedInAssign) && ["expression", true],
      //       },
      //       type,
      //     ) || super.isValidLVal(type, isUnparenthesizedInAssign, binding)
      //   );
      // }
 
      parseBindingAtom(): Pattern {
        switch (this.type) {
          case tokTypes._this:
            // "this" may be the name of a parameter, so allow it.
            // @ts-ignore
            return this.parseIdent(/* liberal */ true)
          default:
            // @ts-ignore
            return super.parseBindingAtom()
        }
      }
 
      // todo we don't need checkCommaAfterRest and shouldParseArrow, achieve this feature in
      //  parseParenAndDistinguishExpression
      // shouldParseArrow(params: Array<N.Node>) {
      //   if (this.match(tt.colon)) {
      //     return params.every(expr => this.isAssignable(expr, true));
      //   }
      //   return super.shouldParseArrow(params);
      // }
 
      // checkCommaAfterRest(
      //   close: typeof charCodes[keyof typeof charCodes],
      // ): boolean {
      //   if (
      //     this.state.isAmbientContext &&
      //     this.match(tt.comma) &&
      //     this.lookaheadCharCode() === close
      //   ) {
      //     this.next();
      //     return false;
      //   } else {
      //     return super.checkCommaAfterRest(close);
      //   }
      // }
 
      // todo we don't support Decorator as this version
      // parseMaybeDecoratorArguments(expr: N.Expression): N.Expression {
      //   // handles `@f<<T>`
      //   if (this.match(tt.lt) || this.match(tt.bitShiftL)) {
      //     const typeArguments = this.tsParseTypeArgumentsInExpression();
      //
      //     if (this.match(tt.parenL)) {
      //       const call = super.parseMaybeDecoratorArguments(expr);
      //       call.typeParameters = typeArguments;
      //       return call;
      //     }
      //
      //     this.unexpected(null, tt.parenL);
      //   }
      //
      //   return super.parseMaybeDecoratorArguments(expr);
      // }
 
      parseParenAndDistinguishExpression(canBeArrow, forInit) {
        let startPos = this.start, startLoc = this['startLoc'], val,
          allowTrailingComma = this.options.ecmaVersion >= 8
        Eif (this.options.ecmaVersion >= 6) {
          this.next()
 
          let innerStartPos = this.start, innerStartLoc = this['startLoc']
          let exprList = [], first = true, lastIsComma = false
          let refDestructuringErrors = new DestructuringErrors,
            // @ts-ignore
            oldYieldPos = this['yieldPos'], oldAwaitPos = this['awaitPos'],
            spreadStart
          // @ts-ignore
          this['yieldPos'] = 0
          // @ts-ignore
          this['awaitPos'] = 0
          // Do not save awaitIdentPos to allow checking awaits nested in parameters
          while (this.type !== tokTypes.parenR) {
            // @ts-ignore
            first ? first = false : this.expect(tokTypes.comma)
            // @ts-ignore
            if (allowTrailingComma && this.afterTrailingComma(tokTypes.parenR, true)) {
              lastIsComma = true
              break
            } else if (this.type === tokTypes.ellipsis) {
              spreadStart = this.start
              // @ts-ignore
              exprList.push(this.parseParenItem(this.parseRestBinding()))
 
              // todo checkCommaAfterRest
              const checkCommaAfterRest = (() => {
                if (
                  this.isAmbientContext &&
                  this.match(tokTypes.comma) &&
                  this.lookaheadCharCode() === charCodes.rightParenthesis
                ) {
                  this.next()
                  return false
                } else {
                  return this.match(tokTypes.comma)
                }
              })()
              if (checkCommaAfterRest) {
                this.raise(this.start, 'Comma is not permitted after the rest element')
              }
              break
            } else {
              exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem))
            }
          }
          let innerEndPos = this['lastTokEnd'],
            innerEndLoc = this['lastTokEndLoc']
          // @ts-ignore
          this.expect(tokTypes.parenR)
 
          // todo typescript shouldParseArrow parseArrow
          const shouldParseArrow = ((): boolean => {
            Iif (this.match(tokTypes.colon)) {
              return exprList.every(expr => this.isAssignable(expr, true))
            }
            // @ts-ignore
            return !this.canInsertSemicolon()
          })()
 
          // @ts-ignore
          let arrowNode = this.startNodeAt(
            startPos,
            startLoc
          )
          Eif (
            canBeArrow &&
            shouldParseArrow &&
            (arrowNode = this.parseArrow(arrowNode))
          ) {
            // @ts-ignore
            this.checkPatternErrors(refDestructuringErrors, false)
            // @ts-ignore
            this.checkYieldAwaitInDefaultParams()
            // @ts-ignore
            this['yieldPos'] = oldYieldPos
            // @ts-ignore
            this['awaitPos'] = oldAwaitPos
            return this.parseArrowExpression(arrowNode, exprList, false, forInit)
          }
 
          if (!exprList.length || lastIsComma) this.unexpected(this['lastTokStart'])
          if (spreadStart) this.unexpected(spreadStart)
          // @ts-ignore
          this.checkExpressionErrors(refDestructuringErrors, true)
          // @ts-ignore
          this['yieldPos'] = oldYieldPos || this['yieldPos']
          // @ts-ignore
          this['awaitPos'] = oldAwaitPos || this['awaitPos']
 
          if (exprList.length > 1) {
            // @ts-ignore
            val = this.startNodeAt(innerStartPos, innerStartLoc)
            val.expressions = exprList
            this.finishNodeAt(val, 'SequenceExpression', innerEndPos, innerEndLoc)
          } else {
            val = exprList[0]
          }
        } else {
          // @ts-ignore
          val = this.parseParenExpression()
        }
 
        if (this.options.preserveParens) {
          // @ts-ignore
          let par = this.startNodeAt(startPos, startLoc)
          par.expression = val
          return this.finishNode(par, 'ParenthesizedExpression')
        } else {
          return val
        }
      }
 
      // todo we don't need this function, achieve this feature in
      //  parseSubscript
      // shouldParseAsyncArrow(): boolean {
      //   return this.match(tt.colon) || super.shouldParseAsyncArrow()
      // }
 
      parseTaggedTemplateExpression(
        base: Expression,
        startPos: number,
        startLoc: Position,
        optionalChainMember: boolean
      ): any {
        // @ts-ignore
        const node = this.startNodeAt(
          startPos,
          startLoc
        )
        node.tag = base
        // @ts-ignore
        node.quasi = this.parseTemplate(true)
        if (optionalChainMember) {
          // @ts-ignore
          this.raise(startLoc.start, 'Tagged Template Literals are not allowed'
            + ' in'
            + ' optionalChain.')
        }
        return this.finishNode(node, 'TaggedTemplateExpression')
      }
 
      parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) {
        let _optionalChained = optionalChained
        // --- start extend parseSubscript
        Iif (
          !this.hasPrecedingLineBreak() &&
          // NODE: replace bang
          this.match(tokTypes.prefix) &&
          this['value'] === '!'
        ) {
          // When ! is consumed as a postfix operator (non-null assertion),
          // disallow JSX tag forming after. e.g. When parsing `p! < n.p!`
          // `<n.p` can not be a start of JSX tag
          this.canStartJSXElement = false
          this.next()
          // @ts-ignore
          const nonNullExpression = this.startNodeAt(
            startPos,
            startLoc
          )
          nonNullExpression.expression = base
          base = this.finishNode(nonNullExpression, 'TSNonNullExpression')
          return base
        }
 
        let isOptionalCall = false
        Iif (
          this.match(tokTypes.questionDot) &&
          this.lookaheadCharCode() === charCodes.lessThan
        ) {
          if (noCalls) {
            // NODE: we don't need to change state's stop to false.
            // state.stop = true
            return base
          }
          base.optional = true
          _optionalChained = isOptionalCall = true
          this.next()
        }
 
        // handles 'f<<T>'
        Iif (this.match(tokTypes.relational) || this.match(tokTypes.bitShift)) {
          let missingParenErrorLoc
          // tsTryParseAndCatch is expensive, so avoid if not necessary.
          // There are number of things we are going to "maybe" parse, like type arguments on
          // tagged template expressions. If any of them fail, walk it back and continue.
          const result = this.tsTryParseAndCatch(() => {
            if (!noCalls && this.atPossibleAsyncArrow(base)) {
              // Almost certainly this is a generic async function `async <T>() => ...
              // But it might be a call with a type argument `async<T>();`
              const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(
                startPos,
                startLoc,
                forInit
              )
              if (asyncArrowFn) {
                base = asyncArrowFn
                return base
              }
            }
 
            const typeArguments = this.tsParseTypeArgumentsInExpression()
            if (!typeArguments) return base
 
            if (isOptionalCall && !this.match(tokTypes.parenL)) {
              // @ts-ignore
              missingParenErrorLoc = this.curPosition()
              return base
            }
 
            if (tokenIsTemplate(this.type)) {
              const result = this.parseTaggedTemplateExpression(
                base,
                startPos,
                startLoc,
                _optionalChained
              )
              result.typeParameters = typeArguments
              base = result
              return base
            }
            // @ts-ignore
            if (!noCalls && this.eat(tokTypes.parenL)) {
              let refDestructuringErrors = new DestructuringErrors
              // @ts-ignore
              const node = this.startNodeAt(startPos, startLoc)
              node.callee = base
              // possibleAsync always false here, because we would have handled it above.
              // @ts-expect-error (won't be any undefined arguments)
              node.arguments = this.parseExprList(
                tokTypes.parenR,
                this.options.ecmaVersion >= 8,
                false,
                refDestructuringErrors
              )
 
              // Handles invalid case: `f<T>(a:b)`
              this.tsCheckForInvalidTypeCasts(node.arguments)
 
              node.typeParameters = typeArguments
              if (_optionalChained) {
                node.optional = isOptionalCall
              }
              // @ts-ignore
              this.checkExpressionErrors(refDestructuringErrors, true)
              base = this.finishNode(node, 'CallExpression')
              return base
            }
 
            const tokenType = this.type
            if (
              // a<b>>c is not (a<b>)>c, but a<(b>>c)
              tokenType === tokTypes.relational ||
              // a<b>>>c is not (a<b>)>>c, but a<(b>>>c)
              tokenType === tokTypes.bitShift ||
              // a<b>c is (a<b)>c
              (tokenType !== tokTypes.parenL &&
                tokenCanStartExpression(tokenType) &&
                !this.hasPrecedingLineBreak())
            ) {
              // Bail out.
              return base
            }
            // @ts-ignore
            const node = this.startNodeAt(
              startPos,
              startLoc
            )
            node.expression = base
            node.typeParameters = typeArguments
            base = this.finishNode(node, 'TSInstantiationExpression')
            return base
          })
 
          if (missingParenErrorLoc) {
            this.unexpected(missingParenErrorLoc)
          }
 
          if (result) {
            if (
              result.type === 'TSInstantiationExpression' &&
              (this.match(tokTypes.dot) ||
                (this.match(tokTypes.questionDot) &&
                  this.lookaheadCharCode() !== charCodes.leftParenthesis))
            ) {
              this.raise(
                this['startLoc'].start,
                TypeScriptError.InvalidPropertyAccessAfterInstantiationExpression
              )
            }
            base = result
            return base
          }
        }
        // --- end
        let optionalSupported = this.options.ecmaVersion >= 11
        // @ts-ignore
        let optional = optionalSupported && this.eat(tokTypes.questionDot)
        Iif (noCalls && optional) this.raise(this['lastTokStart'], 'Optional chaining cannot appear in the callee of new expressions')
        // @ts-ignore
        let computed = this.eat(tokTypes.bracketL)
        // @ts-ignore
        if (computed || (optional && this.type !== tokTypes.parenL && this.type !== tokTypes.backQuote) || this.eat(tokTypes.dot)) {
          // @ts-ignore
          let node = this.startNodeAt(startPos, startLoc)
          node.object = base
          Iif (computed) {
            // @ts-ignore
            node.property = this.parseExpression()
            // @ts-ignore
            this.expect(tokTypes.bracketR)
          } else Iif (this.type === tokTypes.privateId && base.type !== 'Super') {
            // @ts-ignore
            node.property = this.parsePrivateIdent()
          } else {
            // @ts-ignore
            node.property = this.parseIdent(this.options.allowReserved !== 'never')
          }
          node.computed = !!computed
          Eif (optionalSupported) {
            node.optional = optional
          }
          base = this.finishNode(node, 'MemberExpression')
          // @ts-ignore
        } else if (!noCalls && this.eat(tokTypes.parenL)) {
          let refDestructuringErrors = new DestructuringErrors,
            // @ts-ignore
            oldYieldPos = this['yieldPos'], oldAwaitPos = this['awaitPos'],
            // @ts-ignore
            oldAwaitIdentPos = this['awaitIdentPos']
          // @ts-ignore
          this['yieldPos'] = 0
          // @ts-ignore
          this['awaitPos'] = 0
          // @ts-ignore
          this['awaitIdentPos'] = 0
          // @ts-ignore
          let exprList = this.parseExprList(tokTypes.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors)
 
          // todo typescript shouldParseAsyncArrow
          const shouldParseAsyncArrow = ((): boolean => {
            return this.match(tokTypes.colon) || (// @ts-ignore
              !this.canInsertSemicolon() && this.eat(tokTypes.arrow)
            )
          })()
          Iif (
            maybeAsyncArrow && !optional && shouldParseAsyncArrow
          ) {
            // @ts-ignore
            this.checkPatternErrors(refDestructuringErrors, false)
            // @ts-ignore
            this.checkYieldAwaitInDefaultParams()
            // @ts-ignore
            if (this['awaitIdentPos'] > 0)
              // @ts-ignore
              this.raise(this['awaitIdentPos'], 'Cannot use \'await\' as identifier inside an async function')
            // @ts-ignore
            this['yieldPos'] = oldYieldPos
            // @ts-ignore
            this['awaitPos'] = oldAwaitPos
            // @ts-ignore
            this['awaitIdentPos'] = oldAwaitIdentPos
            // @ts-ignore
            return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit)
          }
          // @ts-ignore
          this.checkExpressionErrors(refDestructuringErrors, true)
          // @ts-ignore
          this['yieldPos'] = oldYieldPos || this['yieldPos']
          // @ts-ignore
          this['awaitPos'] = oldAwaitPos || this['awaitPos']
          // @ts-ignore
          this['awaitIdentPos'] = oldAwaitIdentPos || this['awaitIdentPos']
          // @ts-ignore
          let node = this.startNodeAt(startPos, startLoc)
          node.callee = base
          node.arguments = exprList
          Eif (optionalSupported) {
            node.optional = optional
          }
          base = this.finishNode(node, 'CallExpression')
        } else Iif (this.type === tokTypes.backQuote) {
          // NOTE: change to _optionalChained
          if (optional || _optionalChained) {
            this.raise(this.start, 'Optional chaining cannot appear in the tag of tagged template expressions')
          }
          // @ts-ignore
          let node = this.startNodeAt(startPos, startLoc)
          node.tag = base
          node.quasi = this.parseTemplate({ isTagged: true })
          base = this.finishNode(node, 'TaggedTemplateExpression')
        }
        return base
      }
 
      // todo we don't need this function. achieve this feature in
      //  parsePropertyValue
      // canHaveLeadingDecorator() {
      //   // Avoid unnecessary lookahead in checking for abstract class unless needed!
      //   return super.canHaveLeadingDecorator() || this.isAbstractClass()
      // }
 
      parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
        // todo parseObjPropValue
        const typeParameters = this.tsTryParseTypeParameters()
        Iif (typeParameters) prop.typeParameters = typeParameters
 
        Iif ((isGenerator || isAsync) && this.type === tokTypes.colon)
          // @ts-ignore
          this.unexpected()
        // @ts-ignore
        Eif (this.eat(tokTypes.colon)) {
          prop.value = isPattern ? this.parseMaybeDefault(this.start, this['startLoc']) : this.parseMaybeAssign(false, refDestructuringErrors)
          prop.kind = 'init'
        } else if (this.options.ecmaVersion >= 6 && this.type === tokTypes.parenL) {
          // @ts-ignore
          if (isPattern) this.unexpected()
          prop.kind = 'init'
          prop.method = true
          prop.value = this.parseMethod(isGenerator, isAsync)
        } else if (!isPattern && !containsEsc &&
          this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === 'Identifier' &&
          (prop.key.name === 'get' || prop.key.name === 'set') &&
          (this.type !== tokTypes.comma && this.type !== tokTypes.braceR && this.type !== tokTypes.eq)) {
          // @ts-ignore
          if (isGenerator || isAsync) this.unexpected()
          prop.kind = prop.key.name
          // @ts-ignore
          this.parsePropertyName(prop)
          prop.value = this.parseMethod(false)
 
          // here is getGetterSetterExpectedParamCount
          let paramCount = prop.kind === 'get' ? 0 : 1
          const firstParam = prop.value.params[0]
          const hasContextParam = firstParam && this.isThisParam(firstParam)
          paramCount = hasContextParam ? paramCount + 1 : paramCount
          // end
 
          if (prop.value.params.length !== paramCount) {
            let start = prop.value.start
            if (prop.kind === 'get')
              this.raiseRecoverable(start, 'getter should have no params')
            else
              this.raiseRecoverable(start, 'setter should have exactly one param')
          } else {
            if (prop.kind === 'set' && prop.value.params[0].type === 'RestElement')
              this.raiseRecoverable(prop.value.params[0].start, 'Setter cannot use rest params')
          }
        } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === 'Identifier') {
          // @ts-ignore
          if (isGenerator || isAsync) this.unexpected()
          // @ts-ignore
          this.checkUnreserved(prop.key)
          if (prop.key.name === 'await' && !this['awaitIdentPos'])
            this['awaitIdentPos'] = startPos
          prop.kind = 'init'
          if (isPattern) {
            // @ts-ignore
            prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key))
          } else if (this.type === tokTypes.eq && refDestructuringErrors) {
            if (refDestructuringErrors.shorthandAssign < 0)
              refDestructuringErrors.shorthandAssign = this.start
            // @ts-ignore
            prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key))
          } else {
            // @ts-ignore
            prop.value = this.copyNode(prop.key)
          }
          prop.shorthand = true
          // @ts-ignore
        } else this.unexpected()
      }
 
      parseTryStatement(node) {
        this.next()
        // @ts-ignore
        node.block = this.parseBlock()
        node.handler = null
        if (this.type === tokTypes._catch) {
          // @ts-ignore
          let clause = this.startNode()
          this.next()
          // @ts-ignore
          if (this.eat(tokTypes.parenL)) {
            const param = this.parseBindingAtom()
            let simple = param.type === 'Identifier'
            // @ts-ignore
            this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0)
            // @ts-ignore
            this.checkLValPattern(param, simple ? acornScope.BIND_SIMPLE_CATCH : acornScope.BIND_LEXICAL)
 
            // start add ts support
            const type = this.tsTryParseTypeAnnotation()
            if (type) {
              // @ts-ignore
              param.typeAnnotation = type
              this.resetEndLocation(param)
            }
            // end
 
            clause.param = param
            // @ts-ignore
            this.expect(tokTypes.parenR)
          } else {
            // @ts-ignore
            if (this.options.ecmaVersion < 10) this.unexpected()
            clause.param = null
            // @ts-ignore
            this.enterScope(0)
          }
          // @ts-ignore
          clause.body = this.parseBlock(false)
          // @ts-ignore
          this.exitScope()
          node.handler = this.finishNode(clause, 'CatchClause')
        }
        // @ts-ignore
        node.finalizer = this.eat(tokTypes._finally) ? this.parseBlock() : null
        if (!node.handler && !node.finalizer)
          this.raise(node.start, 'Missing catch or finally clause')
        return this.finishNode(node, 'TryStatement')
      }
 
      parseClass(
        node: any,
        isStatement: boolean
      ): any {
        const oldInAbstractClass = this.inAbstractClass
        this.inAbstractClass = !!(node as any).abstract
        try {
          this.next()
 
          // ---start origin parseClass
          // ecma-262 14.6 Class Definitions
          // A class definition is always strict mode code.
          const oldStrict = this['strict']
          this['strict'] = true
 
          this.parseClassId(node, isStatement)
          this.parseClassSuper(node)
          // @ts-ignore
          const privateNameMap = this.enterClassBody()
          // @ts-ignore
          const classBody = this.startNode()
          let hadConstructor = false
          classBody.body = []
          // @ts-ignore
          this.expect(tokTypes.braceL)
          while (this.type !== tokTypes.braceR) {
            const element = this.parseClassElement(node.superClass !== null)
            Eif (element) {
              classBody.body.push(element)
              if (element.type === 'MethodDefinition' && element.kind === 'constructor') {
                Iif (hadConstructor) this.raise(element.start, 'Duplicate constructor in the same class')
                // todo typescript support duplicate constructor
                // hadConstructor = true
              } else Iif (element.key && element.key.type === 'PrivateIdentifier' && isPrivateNameConflicted(privateNameMap, element)) {
                this.raiseRecoverable(element.key.start, `Identifier '#${element.key.name}' has already been declared`)
              }
            }
          }
          this['strict'] = oldStrict
          this.next()
          // @ts-ignore
          node.body = this.finishNode(classBody, 'ClassBody')
          // @ts-ignore
          this.exitClassBody()
          return this.finishNode(node, isStatement ? 'ClassDeclaration' : 'ClassExpression')
          // ---end
        } finally {
          this.inAbstractClass = oldInAbstractClass
        }
      }
 
      parseBindingList(close, allowEmpty, allowTrailingComma) {
        let elts = [], first = true
        // @ts-ignore
        while (!this.eat(close)) {
          if (first) first = false
          // @ts-ignore
          else this.expect(tokTypes.comma)
          Iif (allowEmpty && this.match(tokTypes.comma)) {
            elts.push(null)
            // @ts-ignore
          } else Iif (allowTrailingComma && this.afterTrailingComma(close)) {
            break
          } else Iif (this.match(tokTypes.ellipsis)) {
            // @ts-ignore
            let rest = this.parseRestBinding()
            this.parseBindingListItem(rest)
            elts.push(rest)
            if (this.type === tokTypes.comma) this.raise(this.start, 'Comma is not permitted after the rest element')
            // @ts-ignore
            this.expect(close)
            break
          } else {
            elts.push(this.parseAssignableListItem(false))
          }
        }
        return elts
      }
 
      parseMethod(
        isGenerator: boolean,
        isAsync?: boolean,
        allowDirectSuper?: boolean
      ) {
        // @ts-ignore
        let node = this.startNode(), oldYieldPos = this['yieldPos'],
          oldAwaitPos = this['awaitPos'],
          oldAwaitIdentPos = this['awaitIdentPos']
        // @ts-ignore
        this.initFunction(node)
        if (this.options.ecmaVersion >= 6)
          node.generator = isGenerator
        if (this.options.ecmaVersion >= 8)
          node.async = !!isAsync
 
        this['yieldPos'] = 0
        this['awaitPos'] = 0
        this['awaitIdentPos'] = 0
        // @ts-ignore
        this.enterScope(
          functionFlags(isAsync, node.generator) |
          acornScope.SCOPE_SUPER |
          (allowDirectSuper ? acornScope.SCOPE_DIRECT_SUPER : 0)
        )
        // @ts-ignore
        this.expect(tokTypes.parenL)
        // @ts-ignore
        node.params = this.parseBindingList(tokTypes.parenR, false, this.options.ecmaVersion >= 8)
        // @ts-ignore
        this.checkYieldAwaitInDefaultParams()
        // @ts-ignore
        const finishNode = this.parseFunctionBodyAndFinish(node, 'FunctionExpression', true)
        this['yieldPos'] = oldYieldPos
        this['awaitPos'] = oldAwaitPos
        this['awaitIdentPos'] = oldAwaitIdentPos
        const method = finishNode
 
        // @ts-expect-error todo(flow->ts) property not defined for all types in union
        if (method.abstract) {
          // @ts-ignore
          const hasBody = !!method.body
          if (hasBody) {
            // @ts-ignore
            const { key } = method
            this.raise(method.start,
              TypeScriptError.AbstractMethodHasImplementation(
                // @ts-ignore
                key.type === 'Identifier' && !method.computed
                  ? key.name
                  : `[${this.input.slice(key.start, key.end)}]`
              )
            )
          }
        }
        return method
      }
 
      parseMethodForClass(
        isGenerator: boolean,
        isAsync?: boolean,
        allowDirectSuper?: boolean,
        isPrivate?: boolean
      ) {
        // @ts-ignore
        let node = this.startNode(), oldYieldPos = this['yieldPos'],
          oldAwaitPos = this['awaitPos'],
          oldAwaitIdentPos = this['awaitIdentPos']
        // @ts-ignore
        this.initFunction(node)
        Eif (this.options.ecmaVersion >= 6)
          node.generator = isGenerator
        Eif (this.options.ecmaVersion >= 8)
          node.async = !!isAsync
 
        this['yieldPos'] = 0
        this['awaitPos'] = 0
        this['awaitIdentPos'] = 0
        // @ts-ignore
        this.enterScope(
          functionFlags(isAsync, node.generator) |
          acornScope.SCOPE_SUPER |
          (allowDirectSuper ? acornScope.SCOPE_DIRECT_SUPER : 0)
        )
        // @ts-ignore
        this.expect(tokTypes.parenL)
        // @ts-ignore
        node.params = this.parseBindingList(tokTypes.parenR, false, this.options.ecmaVersion >= 8)
        // @ts-ignore
        this.checkYieldAwaitInDefaultParams()
        // @ts-ignore
        const finishNode = this.parseFunctionBodyAndFinish(node, isPrivate ? 'ClassPrivateMethod' : 'ClassMethod', true)
        this['yieldPos'] = oldYieldPos
        this['awaitPos'] = oldAwaitPos
        this['awaitIdentPos'] = oldAwaitIdentPos
        const method = finishNode
 
        // @ts-expect-error todo(flow->ts) property not defined for all types in union
        Iif (method.abstract) {
          // @ts-ignore
          const hasBody = !!method.body
          if (hasBody) {
            // @ts-ignore
            const { key } = method
            this.raise(method.start,
              TypeScriptError.AbstractMethodHasImplementation(
                // @ts-ignore
                key.type === 'Identifier' && !method.computed
                  ? key.name
                  : `[${this.input.slice(key.start, key.end)}]`
              )
            )
          }
        }
        return method
      }
 
      static parse(input: string, options: Options) {
        const parser = new this(options, input)
        Iif (dts) {
          parser.isAmbientContext = true
        }
        return parser.parse()
      }
 
      static parseExpressionAt(input: string, pos: number, options: Options) {
        const parser = new this(options, input, pos)
        if (dts) {
          parser.isAmbientContext = true
        }
        parser.nextToken()
        // @ts-ignore
        return parser.parseExpressionAt()
      }
 
      parseImportSpecifiers() {
        let nodes = [], first = true
        if (this.type === tokTypes.name) {
          // import defaultObj, { x, y as z } from '...'
          // @ts-ignore
          let node = this.startNode()
          // @ts-ignore
          node.local = this.parseIdent()
          // @ts-ignore
          this.checkLValSimple(node.local, acornScope.BIND_LEXICAL)
          nodes.push(this.finishNode(node, 'ImportDefaultSpecifier'))
          // @ts-ignore
          if (!super.eat(tokTypes.comma)) return nodes
        }
        if (this.type === tokTypes.star) {
          // @ts-ignore
          let node = this.startNode()
          this.next()
          // @ts-ignore
          this.expectContextual('as')
          // @ts-ignore
          node.local = this.parseIdent()
          // @ts-ignore
          this.checkLValSimple(node.local, acornScope.BIND_LEXICAL)
          nodes.push(this.finishNode(node, 'ImportNamespaceSpecifier'))
          return nodes
        }
        // @ts-ignore
        super.expect(tokTypes.braceL)
        // @ts-ignore
        while (!this.eat(tokTypes.braceR)) {
          if (!first) {
            // @ts-ignore
            this.expect(tokTypes.comma)
            // @ts-ignore
            Iif (this.afterTrailingComma(tokTypes.braceR)) {
              break
            }
          } else {
            first = false
          }
          // @ts-ignore
          let node = this.startNode()
          const isMaybeTypeOnly = this.ts_isContextual(tsTokenType.type)
          // @ts-ignore
          node.imported = this.parseModuleExportName()
          if (isMaybeTypeOnly) {
            this.parseTypeOnlyImportExportSpecifier(
              node,
              /* isImport */ true,
              node.importKind === 'type'
            )
 
            nodes.push(this.finishNode(node, 'ImportSpecifier'))
          } else {
            node.importKind = 'value'
            if (this.eatContextual('as')) {
              // @ts-ignore
              node.local = super.parseIdent()
            } else {
              // @ts-ignore
              this.checkUnreserved(node.imported)
              node.local = node.imported
            }
            // @ts-ignore
            this.checkLValSimple(node.local, acornScope.BIND_LEXICAL)
            nodes.push(this.finishNode(node, 'ImportSpecifier'))
          }
        }
        return nodes
      }
 
      parseExportSpecifiers(exports, isInTypeExport = false) {
        let nodes = [], first = true
        // export { x, y as z } [from '...']
        // @ts-ignore
        this.expect(tokTypes.braceL)
        // @ts-ignore
        while (!this.eat(tokTypes.braceR)) {
          if (!first) {
            // @ts-ignore
            this.expect(tokTypes.comma)
            // @ts-ignore
            Iif (this.afterTrailingComma(tokTypes.braceR)) break
          } else {
            first = false
          }
 
          const isMaybeTypeOnly = this.ts_isContextual(tsTokenType.type)
          const isString = this.match(tokTypes.string)
          // todo support exportDefaultFrom
          // const isDefaultSpecifier = this.isExportDefaultSpecifier()
          // @ts-ignore
          let node = this.startNode()
          // @ts-ignore
          node.local = this.parseModuleExportName()
          if (!isString && isMaybeTypeOnly) {
            this.parseTypeOnlyImportExportSpecifier(
              node,
              /* isImport */ false,
              isInTypeExport
            )
            this.finishNode(node, 'ExportSpecifier')
          } else {
            node.exportKind = 'value'
            // @ts-ignore
            Iif (this.eatContextual('as')) {
              // @ts-ignore
              node.exported = this.parseModuleExportName()
            } else {
              // @ts-ignore
              node.exported = this.copyNode(node.local)
            }
            this.finishNode(node, 'ExportSpecifier')
          }
          // @ts-ignore
          this.checkExport(
            exports,
            node.exported,
            node.exported.start
          )
 
          nodes.push(node)
        }
        return nodes
      }
 
      parseTypeOnlyImportExportSpecifier(
        node: any,
        isImport: boolean,
        isInTypeOnlyImportExport: boolean
      ): void {
        const leftOfAsKey = isImport ? 'imported' : 'local'
        const rightOfAsKey = isImport ? 'local' : 'exported'
 
        let leftOfAs = node[leftOfAsKey]
        let rightOfAs
 
        let hasTypeSpecifier = false
        let canParseAsKeyword = true
 
        const loc = leftOfAs.loc.start
 
        if (this.ts_isContextual(tsTokenType.as)) {
          // { type as ...? }
          // @ts-ignore
          const firstAs = this.parseIdent()
          // @ts-ignore
          Iif (this.isContextual(tsTokenType.as)) {
            // { type as as ...? }
            // @ts-ignore
            const secondAs = this.parseIdent()
            if (tokenIsKeywordOrIdentifier(this.type)) {
              // { type as as something }
              hasTypeSpecifier = true
              leftOfAs = firstAs
              rightOfAs = isImport
                // @ts-ignore
                ? this.parseIdent()
                // @ts-ignore
                : this.parseModuleExportName()
              canParseAsKeyword = false
            } else {
              // { type as as }
              rightOfAs = secondAs
              canParseAsKeyword = false
            }
          } else Eif (tokenIsKeywordOrIdentifier(this.type)) {
            // { type as something }
            canParseAsKeyword = false
            rightOfAs = isImport
              // @ts-ignore
              ? this.parseIdent()
              // @ts-ignore
              : this.parseModuleExportName()
          } else {
            // { type as }
            hasTypeSpecifier = true
            leftOfAs = firstAs
          }
        } else Eif (tokenIsKeywordOrIdentifier(this.type)) {
          // { type something ...? }
          hasTypeSpecifier = true
          if (isImport) {
            // @ts-ignore
            leftOfAs = super.parseIdent(true)
            if (!this.ts_isContextual(tsTokenType.as)) {
              // @ts-ignore
              this.checkUnreserved(leftOfAs)
            }
          } else {
            // @ts-ignore
            leftOfAs = this.parseModuleExportName()
          }
        }
        Iif (hasTypeSpecifier && isInTypeOnlyImportExport) {
          this.raise(
            loc,
            isImport
              ? TypeScriptError.TypeModifierIsUsedInTypeImports
              : TypeScriptError.TypeModifierIsUsedInTypeExports
          )
        }
 
        node[leftOfAsKey] = leftOfAs
        node[rightOfAsKey] = rightOfAs
 
        const kindKey = isImport ? 'importKind' : 'exportKind'
        node[kindKey] = hasTypeSpecifier ? 'type' : 'value'
        // @ts-ignore
        if (canParseAsKeyword && this.eatContextual('as')) {
          node[rightOfAsKey] = isImport
            // @ts-ignore
            ? this.parseIdent()
            // @ts-ignore
            : this.parseModuleExportName()
        }
        if (!node[rightOfAsKey]) {
          // @ts-ignore
          node[rightOfAsKey] = this.copyNode(node[leftOfAsKey])
        }
        if (isImport) {
          // @ts-ignore
          this.checkLValSimple(node[rightOfAsKey], BIND_LEXICAL)
        }
      }
 
    } as typeof AcornParser
  }
}