summaryrefslogtreecommitdiffstats
path: root/third_party/python/esprima/esprima/parser.py
blob: 2309e7b6fb8f767c01592bf2bb4917d6d042f099 (plain)
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
# -*- coding: utf-8 -*-
# Copyright JS Foundation and other contributors, https://js.foundation/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#   * Redistributions of source code must retain the above copyright
#     notice, this list of conditions and the following disclaimer.
#   * Redistributions in binary form must reproduce the above copyright
#     notice, this list of conditions and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

from __future__ import absolute_import, unicode_literals

from .objects import Object
from .compat import basestring, unicode
from .utils import format
from .error_handler import ErrorHandler
from .messages import Messages
from .scanner import RawToken, Scanner, SourceLocation, Position, RegExp
from .token import Token, TokenName
from .syntax import Syntax
from . import nodes as Node


class Value(object):
    def __init__(self, value):
        self.value = value


class Params(object):
    def __init__(self, simple=None, message=None, stricted=None, firstRestricted=None, inFor=None, paramSet=None, params=None, get=None):
        self.simple = simple
        self.message = message
        self.stricted = stricted
        self.firstRestricted = firstRestricted
        self.inFor = inFor
        self.paramSet = paramSet
        self.params = params
        self.get = get


class Config(Object):
    def __init__(self, range=False, loc=False, source=None, tokens=False, comment=False, tolerant=False, **options):
        self.range = range
        self.loc = loc
        self.source = source
        self.tokens = tokens
        self.comment = comment
        self.tolerant = tolerant
        for k, v in options.items():
            setattr(self, k, v)


class Context(object):
    def __init__(self, isModule=False, allowAwait=False, allowIn=True, allowStrictDirective=True, allowYield=True, firstCoverInitializedNameError=None, isAssignmentTarget=False, isBindingElement=False, inFunctionBody=False, inIteration=False, inSwitch=False, labelSet=None, strict=False):
        self.isModule = isModule
        self.allowAwait = allowAwait
        self.allowIn = allowIn
        self.allowStrictDirective = allowStrictDirective
        self.allowYield = allowYield
        self.firstCoverInitializedNameError = firstCoverInitializedNameError
        self.isAssignmentTarget = isAssignmentTarget
        self.isBindingElement = isBindingElement
        self.inFunctionBody = inFunctionBody
        self.inIteration = inIteration
        self.inSwitch = inSwitch
        self.labelSet = {} if labelSet is None else labelSet
        self.strict = strict


class Marker(object):
    def __init__(self, index=None, line=None, column=None):
        self.index = index
        self.line = line
        self.column = column


class TokenEntry(Object):
    def __init__(self, type=None, value=None, regex=None, range=None, loc=None):
        self.type = type
        self.value = value
        self.regex = regex
        self.range = range
        self.loc = loc


class Parser(object):
    def __init__(self, code, options={}, delegate=None):
        self.config = Config(**options)

        self.delegate = delegate

        self.errorHandler = ErrorHandler()
        self.errorHandler.tolerant = self.config.tolerant
        self.scanner = Scanner(code, self.errorHandler)
        self.scanner.trackComment = self.config.comment

        self.operatorPrecedence = {
            '||': 1,
            '&&': 2,
            '|': 3,
            '^': 4,
            '&': 5,
            '==': 6,
            '!=': 6,
            '===': 6,
            '!==': 6,
            '<': 7,
            '>': 7,
            '<=': 7,
            '>=': 7,
            'instanceof': 7,
            'in': 7,
            '<<': 8,
            '>>': 8,
            '>>>': 8,
            '+': 9,
            '-': 9,
            '*': 11,
            '/': 11,
            '%': 11,
        }

        self.lookahead = RawToken(
            type=Token.EOF,
            value='',
            lineNumber=self.scanner.lineNumber,
            lineStart=0,
            start=0,
            end=0
        )
        self.hasLineTerminator = False

        self.context = Context(
            isModule=False,
            allowAwait=False,
            allowIn=True,
            allowStrictDirective=True,
            allowYield=True,
            firstCoverInitializedNameError=None,
            isAssignmentTarget=False,
            isBindingElement=False,
            inFunctionBody=False,
            inIteration=False,
            inSwitch=False,
            labelSet={},
            strict=False
        )
        self.tokens = []

        self.startMarker = Marker(
            index=0,
            line=self.scanner.lineNumber,
            column=0
        )
        self.lastMarker = Marker(
            index=0,
            line=self.scanner.lineNumber,
            column=0
        )
        self.nextToken()
        self.lastMarker = Marker(
            index=self.scanner.index,
            line=self.scanner.lineNumber,
            column=self.scanner.index - self.scanner.lineStart
        )

    def throwError(self, messageFormat, *args):
        msg = format(messageFormat, *args)
        index = self.lastMarker.index
        line = self.lastMarker.line
        column = self.lastMarker.column + 1
        raise self.errorHandler.createError(index, line, column, msg)

    def tolerateError(self, messageFormat, *args):
        msg = format(messageFormat, *args)
        index = self.lastMarker.index
        line = self.scanner.lineNumber
        column = self.lastMarker.column + 1
        self.errorHandler.tolerateError(index, line, column, msg)

    # Throw an exception because of the token.

    def unexpectedTokenError(self, token=None, message=None):
        msg = message or Messages.UnexpectedToken
        if token:
            if not message:
                typ = token.type
                if typ is Token.EOF:
                    msg = Messages.UnexpectedEOS
                elif typ is Token.Identifier:
                    msg = Messages.UnexpectedIdentifier
                elif typ is Token.NumericLiteral:
                    msg = Messages.UnexpectedNumber
                elif typ is Token.StringLiteral:
                    msg = Messages.UnexpectedString
                elif typ is Token.Template:
                    msg = Messages.UnexpectedTemplate
                elif typ is Token.Keyword:
                    if self.scanner.isFutureReservedWord(token.value):
                        msg = Messages.UnexpectedReserved
                    elif self.context.strict and self.scanner.isStrictModeReservedWord(token.value):
                        msg = Messages.StrictReservedWord
                else:
                    msg = Messages.UnexpectedToken
            value = token.value
        else:
            value = 'ILLEGAL'

        msg = msg.replace('%0', unicode(value), 1)

        if token and isinstance(token.lineNumber, int):
            index = token.start
            line = token.lineNumber
            lastMarkerLineStart = self.lastMarker.index - self.lastMarker.column
            column = token.start - lastMarkerLineStart + 1
            return self.errorHandler.createError(index, line, column, msg)
        else:
            index = self.lastMarker.index
            line = self.lastMarker.line
            column = self.lastMarker.column + 1
            return self.errorHandler.createError(index, line, column, msg)

    def throwUnexpectedToken(self, token=None, message=None):
        raise self.unexpectedTokenError(token, message)

    def tolerateUnexpectedToken(self, token=None, message=None):
        self.errorHandler.tolerate(self.unexpectedTokenError(token, message))

    def collectComments(self):
        if not self.config.comment:
            self.scanner.scanComments()
        else:
            comments = self.scanner.scanComments()
            if comments:
                for e in comments:
                    if e.multiLine:
                        node = Node.BlockComment(self.scanner.source[e.slice[0]:e.slice[1]])
                    else:
                        node = Node.LineComment(self.scanner.source[e.slice[0]:e.slice[1]])
                    if self.config.range:
                        node.range = e.range
                    if self.config.loc:
                        node.loc = e.loc
                    if self.delegate:
                        metadata = SourceLocation(
                            start=Position(
                                line=e.loc.start.line,
                                column=e.loc.start.column,
                                offset=e.range[0],
                            ),
                            end=Position(
                                line=e.loc.end.line,
                                column=e.loc.end.column,
                                offset=e.range[1],
                            )
                        )
                        new_node = self.delegate(node, metadata)
                        if new_node is not None:
                            node = new_node

    # From internal representation to an external structure

    def getTokenRaw(self, token):
        return self.scanner.source[token.start:token.end]

    def convertToken(self, token):
        t = TokenEntry(
            type=TokenName[token.type],
            value=self.getTokenRaw(token),
        )
        if self.config.range:
            t.range = [token.start, token.end]
        if self.config.loc:
            t.loc = SourceLocation(
                start=Position(
                    line=self.startMarker.line,
                    column=self.startMarker.column,
                ),
                end=Position(
                    line=self.scanner.lineNumber,
                    column=self.scanner.index - self.scanner.lineStart,
                ),
            )
        if token.type is Token.RegularExpression:
            t.regex = RegExp(
                pattern=token.pattern,
                flags=token.flags,
            )

        return t

    def nextToken(self):
        token = self.lookahead

        self.lastMarker.index = self.scanner.index
        self.lastMarker.line = self.scanner.lineNumber
        self.lastMarker.column = self.scanner.index - self.scanner.lineStart

        self.collectComments()

        if self.scanner.index != self.startMarker.index:
            self.startMarker.index = self.scanner.index
            self.startMarker.line = self.scanner.lineNumber
            self.startMarker.column = self.scanner.index - self.scanner.lineStart

        next = self.scanner.lex()
        self.hasLineTerminator = token.lineNumber != next.lineNumber

        if next and self.context.strict and next.type is Token.Identifier:
            if self.scanner.isStrictModeReservedWord(next.value):
                next.type = Token.Keyword
        self.lookahead = next

        if self.config.tokens and next.type is not Token.EOF:
            self.tokens.append(self.convertToken(next))

        return token

    def nextRegexToken(self):
        self.collectComments()

        token = self.scanner.scanRegExp()
        if self.config.tokens:
            # Pop the previous token, '/' or '/='
            # self is added from the lookahead token.
            self.tokens.pop()

            self.tokens.append(self.convertToken(token))

        # Prime the next lookahead.
        self.lookahead = token
        self.nextToken()

        return token

    def createNode(self):
        return Marker(
            index=self.startMarker.index,
            line=self.startMarker.line,
            column=self.startMarker.column,
        )

    def startNode(self, token, lastLineStart=0):
        column = token.start - token.lineStart
        line = token.lineNumber
        if column < 0:
            column += lastLineStart
            line -= 1

        return Marker(
            index=token.start,
            line=line,
            column=column,
        )

    def finalize(self, marker, node):
        if self.config.range:
            node.range = [marker.index, self.lastMarker.index]

        if self.config.loc:
            node.loc = SourceLocation(
                start=Position(
                    line=marker.line,
                    column=marker.column,
                ),
                end=Position(
                    line=self.lastMarker.line,
                    column=self.lastMarker.column,
                ),
            )
            if self.config.source:
                node.loc.source = self.config.source

        if self.delegate:
            metadata = SourceLocation(
                start=Position(
                    line=marker.line,
                    column=marker.column,
                    offset=marker.index,
                ),
                end=Position(
                    line=self.lastMarker.line,
                    column=self.lastMarker.column,
                    offset=self.lastMarker.index,
                )
            )
            new_node = self.delegate(node, metadata)
            if new_node is not None:
                node = new_node

        return node

    # Expect the next token to match the specified punctuator.
    # If not, an exception will be thrown.

    def expect(self, value):
        token = self.nextToken()
        if token.type is not Token.Punctuator or token.value != value:
            self.throwUnexpectedToken(token)

    # Quietly expect a comma when in tolerant mode, otherwise delegates to expect().

    def expectCommaSeparator(self):
        if self.config.tolerant:
            token = self.lookahead
            if token.type is Token.Punctuator and token.value == ',':
                self.nextToken()
            elif token.type is Token.Punctuator and token.value == ';':
                self.nextToken()
                self.tolerateUnexpectedToken(token)
            else:
                self.tolerateUnexpectedToken(token, Messages.UnexpectedToken)
        else:
            self.expect(',')

    # Expect the next token to match the specified keyword.
    # If not, an exception will be thrown.

    def expectKeyword(self, keyword):
        token = self.nextToken()
        if token.type is not Token.Keyword or token.value != keyword:
            self.throwUnexpectedToken(token)

    # Return true if the next token matches the specified punctuator.

    def match(self, *value):
        return self.lookahead.type is Token.Punctuator and self.lookahead.value in value

    # Return true if the next token matches the specified keyword

    def matchKeyword(self, *keyword):
        return self.lookahead.type is Token.Keyword and self.lookahead.value in keyword

    # Return true if the next token matches the specified contextual keyword
    # (where an identifier is sometimes a keyword depending on the context)

    def matchContextualKeyword(self, *keyword):
        return self.lookahead.type is Token.Identifier and self.lookahead.value in keyword

    # Return true if the next token is an assignment operator

    def matchAssign(self):
        if self.lookahead.type is not Token.Punctuator:
            return False

        op = self.lookahead.value
        return op in ('=', '*=', '**=', '/=', '%=', '+=', '-=', '<<=', '>>=', '>>>=', '&=', '^=', '|=')

    # Cover grammar support.
    #
    # When an assignment expression position starts with an left parenthesis, the determination of the type
    # of the syntax is to be deferred arbitrarily long until the end of the parentheses pair (plus a lookahead)
    # or the first comma. This situation also defers the determination of all the expressions nested in the pair.
    #
    # There are three productions that can be parsed in a parentheses pair that needs to be determined
    # after the outermost pair is closed. They are:
    #
    #   1. AssignmentExpression
    #   2. BindingElements
    #   3. AssignmentTargets
    #
    # In order to avoid exponential backtracking, we use two flags to denote if the production can be
    # binding element or assignment target.
    #
    # The three productions have the relationship:
    #
    #   BindingElements ⊆ AssignmentTargets ⊆ AssignmentExpression
    #
    # with a single exception that CoverInitializedName when used directly in an Expression, generates
    # an early error. Therefore, we need the third state, firstCoverInitializedNameError, to track the
    # first usage of CoverInitializedName and report it when we reached the end of the parentheses pair.
    #
    # isolateCoverGrammar function runs the given parser function with a new cover grammar context, and it does not
    # effect the current flags. This means the production the parser parses is only used as an expression. Therefore
    # the CoverInitializedName check is conducted.
    #
    # inheritCoverGrammar function runs the given parse function with a new cover grammar context, and it propagates
    # the flags outside of the parser. This means the production the parser parses is used as a part of a potential
    # pattern. The CoverInitializedName check is deferred.

    def isolateCoverGrammar(self, parseFunction):
        previousIsBindingElement = self.context.isBindingElement
        previousIsAssignmentTarget = self.context.isAssignmentTarget
        previousFirstCoverInitializedNameError = self.context.firstCoverInitializedNameError

        self.context.isBindingElement = True
        self.context.isAssignmentTarget = True
        self.context.firstCoverInitializedNameError = None

        result = parseFunction()
        if self.context.firstCoverInitializedNameError is not None:
            self.throwUnexpectedToken(self.context.firstCoverInitializedNameError)

        self.context.isBindingElement = previousIsBindingElement
        self.context.isAssignmentTarget = previousIsAssignmentTarget
        self.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError

        return result

    def inheritCoverGrammar(self, parseFunction):
        previousIsBindingElement = self.context.isBindingElement
        previousIsAssignmentTarget = self.context.isAssignmentTarget
        previousFirstCoverInitializedNameError = self.context.firstCoverInitializedNameError

        self.context.isBindingElement = True
        self.context.isAssignmentTarget = True
        self.context.firstCoverInitializedNameError = None

        result = parseFunction()

        self.context.isBindingElement = self.context.isBindingElement and previousIsBindingElement
        self.context.isAssignmentTarget = self.context.isAssignmentTarget and previousIsAssignmentTarget
        self.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError or self.context.firstCoverInitializedNameError

        return result

    def consumeSemicolon(self):
        if self.match(';'):
            self.nextToken()
        elif not self.hasLineTerminator:
            if self.lookahead.type is not Token.EOF and not self.match('}'):
                self.throwUnexpectedToken(self.lookahead)
            self.lastMarker.index = self.startMarker.index
            self.lastMarker.line = self.startMarker.line
            self.lastMarker.column = self.startMarker.column

    # https://tc39.github.io/ecma262/#sec-primary-expression

    def parsePrimaryExpression(self):
        node = self.createNode()

        typ = self.lookahead.type
        if typ is Token.Identifier:
            if (self.context.isModule or self.context.allowAwait) and self.lookahead.value == 'await':
                self.tolerateUnexpectedToken(self.lookahead)
            expr = self.parseFunctionExpression() if self.matchAsyncFunction() else self.finalize(node, Node.Identifier(self.nextToken().value))

        elif typ in (
            Token.NumericLiteral,
            Token.StringLiteral,
        ):
            if self.context.strict and self.lookahead.octal:
                self.tolerateUnexpectedToken(self.lookahead, Messages.StrictOctalLiteral)
            self.context.isAssignmentTarget = False
            self.context.isBindingElement = False
            token = self.nextToken()
            raw = self.getTokenRaw(token)
            expr = self.finalize(node, Node.Literal(token.value, raw))

        elif typ is Token.BooleanLiteral:
            self.context.isAssignmentTarget = False
            self.context.isBindingElement = False
            token = self.nextToken()
            raw = self.getTokenRaw(token)
            expr = self.finalize(node, Node.Literal(token.value == 'true', raw))

        elif typ is Token.NullLiteral:
            self.context.isAssignmentTarget = False
            self.context.isBindingElement = False
            token = self.nextToken()
            raw = self.getTokenRaw(token)
            expr = self.finalize(node, Node.Literal(None, raw))

        elif typ is Token.Template:
            expr = self.parseTemplateLiteral()

        elif typ is Token.Punctuator:
            value = self.lookahead.value
            if value == '(':
                self.context.isBindingElement = False
                expr = self.inheritCoverGrammar(self.parseGroupExpression)
            elif value == '[':
                expr = self.inheritCoverGrammar(self.parseArrayInitializer)
            elif value == '{':
                expr = self.inheritCoverGrammar(self.parseObjectInitializer)
            elif value in ('/', '/='):
                self.context.isAssignmentTarget = False
                self.context.isBindingElement = False
                self.scanner.index = self.startMarker.index
                token = self.nextRegexToken()
                raw = self.getTokenRaw(token)
                expr = self.finalize(node, Node.RegexLiteral(token.regex, raw, token.pattern, token.flags))
            else:
                expr = self.throwUnexpectedToken(self.nextToken())

        elif typ is Token.Keyword:
            if not self.context.strict and self.context.allowYield and self.matchKeyword('yield'):
                expr = self.parseIdentifierName()
            elif not self.context.strict and self.matchKeyword('let'):
                expr = self.finalize(node, Node.Identifier(self.nextToken().value))
            else:
                self.context.isAssignmentTarget = False
                self.context.isBindingElement = False
                if self.matchKeyword('function'):
                    expr = self.parseFunctionExpression()
                elif self.matchKeyword('this'):
                    self.nextToken()
                    expr = self.finalize(node, Node.ThisExpression())
                elif self.matchKeyword('class'):
                    expr = self.parseClassExpression()
                elif self.matchImportCall():
                    expr = self.parseImportCall()
                else:
                    expr = self.throwUnexpectedToken(self.nextToken())

        else:
            expr = self.throwUnexpectedToken(self.nextToken())

        return expr

    # https://tc39.github.io/ecma262/#sec-array-initializer

    def parseSpreadElement(self):
        node = self.createNode()
        self.expect('...')
        arg = self.inheritCoverGrammar(self.parseAssignmentExpression)
        return self.finalize(node, Node.SpreadElement(arg))

    def parseArrayInitializer(self):
        node = self.createNode()
        elements = []

        self.expect('[')
        while not self.match(']'):
            if self.match(','):
                self.nextToken()
                elements.append(None)
            elif self.match('...'):
                element = self.parseSpreadElement()
                if not self.match(']'):
                    self.context.isAssignmentTarget = False
                    self.context.isBindingElement = False
                    self.expect(',')
                elements.append(element)
            else:
                elements.append(self.inheritCoverGrammar(self.parseAssignmentExpression))
                if not self.match(']'):
                    self.expect(',')
        self.expect(']')

        return self.finalize(node, Node.ArrayExpression(elements))

    # https://tc39.github.io/ecma262/#sec-object-initializer

    def parsePropertyMethod(self, params):
        self.context.isAssignmentTarget = False
        self.context.isBindingElement = False

        previousStrict = self.context.strict
        previousAllowStrictDirective = self.context.allowStrictDirective
        self.context.allowStrictDirective = params.simple
        body = self.isolateCoverGrammar(self.parseFunctionSourceElements)
        if self.context.strict and params.firstRestricted:
            self.tolerateUnexpectedToken(params.firstRestricted, params.message)
        if self.context.strict and params.stricted:
            self.tolerateUnexpectedToken(params.stricted, params.message)
        self.context.strict = previousStrict
        self.context.allowStrictDirective = previousAllowStrictDirective

        return body

    def parsePropertyMethodFunction(self):
        isGenerator = False
        node = self.createNode()

        previousAllowYield = self.context.allowYield
        self.context.allowYield = True
        params = self.parseFormalParameters()
        method = self.parsePropertyMethod(params)
        self.context.allowYield = previousAllowYield

        return self.finalize(node, Node.FunctionExpression(None, params.params, method, isGenerator))

    def parsePropertyMethodAsyncFunction(self):
        node = self.createNode()

        previousAllowYield = self.context.allowYield
        previousAwait = self.context.allowAwait
        self.context.allowYield = False
        self.context.allowAwait = True
        params = self.parseFormalParameters()
        method = self.parsePropertyMethod(params)
        self.context.allowYield = previousAllowYield
        self.context.allowAwait = previousAwait

        return self.finalize(node, Node.AsyncFunctionExpression(None, params.params, method))

    def parseObjectPropertyKey(self):
        node = self.createNode()
        token = self.nextToken()

        typ = token.type
        if typ in (
            Token.StringLiteral,
            Token.NumericLiteral,
        ):
            if self.context.strict and token.octal:
                self.tolerateUnexpectedToken(token, Messages.StrictOctalLiteral)
            raw = self.getTokenRaw(token)
            key = self.finalize(node, Node.Literal(token.value, raw))

        elif typ in (
            Token.Identifier,
            Token.BooleanLiteral,
            Token.NullLiteral,
            Token.Keyword,
        ):
            key = self.finalize(node, Node.Identifier(token.value))

        elif typ is Token.Punctuator:
            if token.value == '[':
                key = self.isolateCoverGrammar(self.parseAssignmentExpression)
                self.expect(']')
            else:
                key = self.throwUnexpectedToken(token)

        else:
            key = self.throwUnexpectedToken(token)

        return key

    def isPropertyKey(self, key, value):
        return (
            (key.type is Syntax.Identifier and key.name == value) or
            (key.type is Syntax.Literal and key.value == value)
        )

    def parseObjectProperty(self, hasProto):
        node = self.createNode()
        token = self.lookahead

        key = None
        value = None

        computed = False
        method = False
        shorthand = False
        isAsync = False

        if token.type is Token.Identifier:
            id = token.value
            self.nextToken()
            computed = self.match('[')
            isAsync = not self.hasLineTerminator and (id == 'async') and not (self.match(':', '(', '*', ','))
            key = self.parseObjectPropertyKey() if isAsync else self.finalize(node, Node.Identifier(id))
        elif self.match('*'):
            self.nextToken()
        else:
            computed = self.match('[')
            key = self.parseObjectPropertyKey()

        lookaheadPropertyKey = self.qualifiedPropertyName(self.lookahead)
        if token.type is Token.Identifier and not isAsync and token.value == 'get' and lookaheadPropertyKey:
            kind = 'get'
            computed = self.match('[')
            key = self.parseObjectPropertyKey()
            self.context.allowYield = False
            value = self.parseGetterMethod()

        elif token.type is Token.Identifier and not isAsync and token.value == 'set' and lookaheadPropertyKey:
            kind = 'set'
            computed = self.match('[')
            key = self.parseObjectPropertyKey()
            value = self.parseSetterMethod()

        elif token.type is Token.Punctuator and token.value == '*' and lookaheadPropertyKey:
            kind = 'init'
            computed = self.match('[')
            key = self.parseObjectPropertyKey()
            value = self.parseGeneratorMethod()
            method = True

        else:
            if not key:
                self.throwUnexpectedToken(self.lookahead)

            kind = 'init'
            if self.match(':') and not isAsync:
                if not computed and self.isPropertyKey(key, '__proto__'):
                    if hasProto.value:
                        self.tolerateError(Messages.DuplicateProtoProperty)
                    hasProto.value = True
                self.nextToken()
                value = self.inheritCoverGrammar(self.parseAssignmentExpression)

            elif self.match('('):
                value = self.parsePropertyMethodAsyncFunction() if isAsync else self.parsePropertyMethodFunction()
                method = True

            elif token.type is Token.Identifier:
                id = self.finalize(node, Node.Identifier(token.value))
                if self.match('='):
                    self.context.firstCoverInitializedNameError = self.lookahead
                    self.nextToken()
                    shorthand = True
                    init = self.isolateCoverGrammar(self.parseAssignmentExpression)
                    value = self.finalize(node, Node.AssignmentPattern(id, init))
                else:
                    shorthand = True
                    value = id
            else:
                self.throwUnexpectedToken(self.nextToken())

        return self.finalize(node, Node.Property(kind, key, computed, value, method, shorthand))

    def parseObjectInitializer(self):
        node = self.createNode()

        self.expect('{')
        properties = []
        hasProto = Value(False)
        while not self.match('}'):
            properties.append(self.parseSpreadElement() if self.match('...') else self.parseObjectProperty(hasProto))
            if not self.match('}'):
                self.expectCommaSeparator()
        self.expect('}')

        return self.finalize(node, Node.ObjectExpression(properties))

    # https://tc39.github.io/ecma262/#sec-template-literals

    def parseTemplateHead(self):
        assert self.lookahead.head, 'Template literal must start with a template head'

        node = self.createNode()
        token = self.nextToken()
        raw = token.value
        cooked = token.cooked

        return self.finalize(node, Node.TemplateElement(raw, cooked, token.tail))

    def parseTemplateElement(self):
        if self.lookahead.type is not Token.Template:
            self.throwUnexpectedToken()

        node = self.createNode()
        token = self.nextToken()
        raw = token.value
        cooked = token.cooked

        return self.finalize(node, Node.TemplateElement(raw, cooked, token.tail))

    def parseTemplateLiteral(self):
        node = self.createNode()

        expressions = []
        quasis = []

        quasi = self.parseTemplateHead()
        quasis.append(quasi)
        while not quasi.tail:
            expressions.append(self.parseExpression())
            quasi = self.parseTemplateElement()
            quasis.append(quasi)

        return self.finalize(node, Node.TemplateLiteral(quasis, expressions))

    # https://tc39.github.io/ecma262/#sec-grouping-operator

    def reinterpretExpressionAsPattern(self, expr):
        typ = expr.type
        if typ in (
            Syntax.Identifier,
            Syntax.MemberExpression,
            Syntax.RestElement,
            Syntax.AssignmentPattern,
        ):
            pass
        elif typ is Syntax.SpreadElement:
            expr.type = Syntax.RestElement
            self.reinterpretExpressionAsPattern(expr.argument)
        elif typ is Syntax.ArrayExpression:
            expr.type = Syntax.ArrayPattern
            for elem in expr.elements:
                if elem is not None:
                    self.reinterpretExpressionAsPattern(elem)
        elif typ is Syntax.ObjectExpression:
            expr.type = Syntax.ObjectPattern
            for prop in expr.properties:
                self.reinterpretExpressionAsPattern(prop if prop.type is Syntax.SpreadElement else prop.value)
        elif typ is Syntax.AssignmentExpression:
            expr.type = Syntax.AssignmentPattern
            del expr.operator
            self.reinterpretExpressionAsPattern(expr.left)
        else:
            # Allow other node type for tolerant parsing.
            pass

    def parseGroupExpression(self):
        self.expect('(')
        if self.match(')'):
            self.nextToken()
            if not self.match('=>'):
                self.expect('=>')
            expr = Node.ArrowParameterPlaceHolder([])
        else:
            startToken = self.lookahead
            params = []
            if self.match('...'):
                expr = self.parseRestElement(params)
                self.expect(')')
                if not self.match('=>'):
                    self.expect('=>')
                expr = Node.ArrowParameterPlaceHolder([expr])
            else:
                arrow = False
                self.context.isBindingElement = True
                expr = self.inheritCoverGrammar(self.parseAssignmentExpression)

                if self.match(','):
                    expressions = []

                    self.context.isAssignmentTarget = False
                    expressions.append(expr)
                    while self.lookahead.type is not Token.EOF:
                        if not self.match(','):
                            break
                        self.nextToken()
                        if self.match(')'):
                            self.nextToken()
                            for expression in expressions:
                                self.reinterpretExpressionAsPattern(expression)
                            arrow = True
                            expr = Node.ArrowParameterPlaceHolder(expressions)
                        elif self.match('...'):
                            if not self.context.isBindingElement:
                                self.throwUnexpectedToken(self.lookahead)
                            expressions.append(self.parseRestElement(params))
                            self.expect(')')
                            if not self.match('=>'):
                                self.expect('=>')
                            self.context.isBindingElement = False
                            for expression in expressions:
                                self.reinterpretExpressionAsPattern(expression)
                            arrow = True
                            expr = Node.ArrowParameterPlaceHolder(expressions)
                        else:
                            expressions.append(self.inheritCoverGrammar(self.parseAssignmentExpression))
                        if arrow:
                            break
                    if not arrow:
                        expr = self.finalize(self.startNode(startToken), Node.SequenceExpression(expressions))

                if not arrow:
                    self.expect(')')
                    if self.match('=>'):
                        if expr.type is Syntax.Identifier and expr.name == 'yield':
                            arrow = True
                            expr = Node.ArrowParameterPlaceHolder([expr])
                        if not arrow:
                            if not self.context.isBindingElement:
                                self.throwUnexpectedToken(self.lookahead)

                            if expr.type is Syntax.SequenceExpression:
                                for expression in expr.expressions:
                                    self.reinterpretExpressionAsPattern(expression)
                            else:
                                self.reinterpretExpressionAsPattern(expr)

                            if expr.type is Syntax.SequenceExpression:
                                parameters = expr.expressions
                            else:
                                parameters = [expr]
                            expr = Node.ArrowParameterPlaceHolder(parameters)
                    self.context.isBindingElement = False

        return expr

    # https://tc39.github.io/ecma262/#sec-left-hand-side-expressions

    def parseArguments(self):
        self.expect('(')
        args = []
        if not self.match(')'):
            while True:
                if self.match('...'):
                    expr = self.parseSpreadElement()
                else:
                    expr = self.isolateCoverGrammar(self.parseAssignmentExpression)
                args.append(expr)
                if self.match(')'):
                    break
                self.expectCommaSeparator()
                if self.match(')'):
                    break
        self.expect(')')

        return args

    def isIdentifierName(self, token):
        return (
            token.type is Token.Identifier or
            token.type is Token.Keyword or
            token.type is Token.BooleanLiteral or
            token.type is Token.NullLiteral
        )

    def parseIdentifierName(self):
        node = self.createNode()
        token = self.nextToken()
        if not self.isIdentifierName(token):
            self.throwUnexpectedToken(token)
        return self.finalize(node, Node.Identifier(token.value))

    def parseNewExpression(self):
        node = self.createNode()

        id = self.parseIdentifierName()
        assert id.name == 'new', 'New expression must start with `new`'

        if self.match('.'):
            self.nextToken()
            if self.lookahead.type is Token.Identifier and self.context.inFunctionBody and self.lookahead.value == 'target':
                property = self.parseIdentifierName()
                expr = Node.MetaProperty(id, property)
            else:
                self.throwUnexpectedToken(self.lookahead)
        elif self.matchKeyword('import'):
            self.throwUnexpectedToken(self.lookahead)
        else:
            callee = self.isolateCoverGrammar(self.parseLeftHandSideExpression)
            args = self.parseArguments() if self.match('(') else []
            expr = Node.NewExpression(callee, args)
            self.context.isAssignmentTarget = False
            self.context.isBindingElement = False

        return self.finalize(node, expr)

    def parseAsyncArgument(self):
        arg = self.parseAssignmentExpression()
        self.context.firstCoverInitializedNameError = None
        return arg

    def parseAsyncArguments(self):
        self.expect('(')
        args = []
        if not self.match(')'):
            while True:
                if self.match('...'):
                    expr = self.parseSpreadElement()
                else:
                    expr = self.isolateCoverGrammar(self.parseAsyncArgument)
                args.append(expr)
                if self.match(')'):
                    break
                self.expectCommaSeparator()
                if self.match(')'):
                    break
        self.expect(')')

        return args

    def matchImportCall(self):
        match = self.matchKeyword('import')
        if match:
            state = self.scanner.saveState()
            self.scanner.scanComments()
            next = self.scanner.lex()
            self.scanner.restoreState(state)
            match = (next.type is Token.Punctuator) and (next.value == '(')

        return match

    def parseImportCall(self):
        node = self.createNode()
        self.expectKeyword('import')
        return self.finalize(node, Node.Import())

    def parseLeftHandSideExpressionAllowCall(self):
        startToken = self.lookahead
        maybeAsync = self.matchContextualKeyword('async')

        previousAllowIn = self.context.allowIn
        self.context.allowIn = True

        if self.matchKeyword('super') and self.context.inFunctionBody:
            expr = self.createNode()
            self.nextToken()
            expr = self.finalize(expr, Node.Super())
            if not self.match('(') and not self.match('.') and not self.match('['):
                self.throwUnexpectedToken(self.lookahead)
        else:
            expr = self.inheritCoverGrammar(self.parseNewExpression if self.matchKeyword('new') else self.parsePrimaryExpression)

        while True:
            if self.match('.'):
                self.context.isBindingElement = False
                self.context.isAssignmentTarget = True
                self.expect('.')
                property = self.parseIdentifierName()
                expr = self.finalize(self.startNode(startToken), Node.StaticMemberExpression(expr, property))

            elif self.match('('):
                asyncArrow = maybeAsync and (startToken.lineNumber == self.lookahead.lineNumber)
                self.context.isBindingElement = False
                self.context.isAssignmentTarget = False
                if asyncArrow:
                    args = self.parseAsyncArguments()
                else:
                    args = self.parseArguments()
                if expr.type is Syntax.Import and len(args) != 1:
                    self.tolerateError(Messages.BadImportCallArity)
                expr = self.finalize(self.startNode(startToken), Node.CallExpression(expr, args))
                if asyncArrow and self.match('=>'):
                    for arg in args:
                        self.reinterpretExpressionAsPattern(arg)
                    expr = Node.AsyncArrowParameterPlaceHolder(args)
            elif self.match('['):
                self.context.isBindingElement = False
                self.context.isAssignmentTarget = True
                self.expect('[')
                property = self.isolateCoverGrammar(self.parseExpression)
                self.expect(']')
                expr = self.finalize(self.startNode(startToken), Node.ComputedMemberExpression(expr, property))

            elif self.lookahead.type is Token.Template and self.lookahead.head:
                quasi = self.parseTemplateLiteral()
                expr = self.finalize(self.startNode(startToken), Node.TaggedTemplateExpression(expr, quasi))

            else:
                break

        self.context.allowIn = previousAllowIn

        return expr

    def parseSuper(self):
        node = self.createNode()

        self.expectKeyword('super')
        if not self.match('[') and not self.match('.'):
            self.throwUnexpectedToken(self.lookahead)

        return self.finalize(node, Node.Super())

    def parseLeftHandSideExpression(self):
        assert self.context.allowIn, 'callee of new expression always allow in keyword.'

        node = self.startNode(self.lookahead)
        if self.matchKeyword('super') and self.context.inFunctionBody:
            expr = self.parseSuper()
        else:
            expr = self.inheritCoverGrammar(self.parseNewExpression if self.matchKeyword('new') else self.parsePrimaryExpression)

        while True:
            if self.match('['):
                self.context.isBindingElement = False
                self.context.isAssignmentTarget = True
                self.expect('[')
                property = self.isolateCoverGrammar(self.parseExpression)
                self.expect(']')
                expr = self.finalize(node, Node.ComputedMemberExpression(expr, property))

            elif self.match('.'):
                self.context.isBindingElement = False
                self.context.isAssignmentTarget = True
                self.expect('.')
                property = self.parseIdentifierName()
                expr = self.finalize(node, Node.StaticMemberExpression(expr, property))

            elif self.lookahead.type is Token.Template and self.lookahead.head:
                quasi = self.parseTemplateLiteral()
                expr = self.finalize(node, Node.TaggedTemplateExpression(expr, quasi))

            else:
                break

        return expr

    # https://tc39.github.io/ecma262/#sec-update-expressions

    def parseUpdateExpression(self):
        startToken = self.lookahead

        if self.match('++', '--'):
            node = self.startNode(startToken)
            token = self.nextToken()
            expr = self.inheritCoverGrammar(self.parseUnaryExpression)
            if self.context.strict and expr.type is Syntax.Identifier and self.scanner.isRestrictedWord(expr.name):
                self.tolerateError(Messages.StrictLHSPrefix)
            if not self.context.isAssignmentTarget:
                self.tolerateError(Messages.InvalidLHSInAssignment)
            prefix = True
            expr = self.finalize(node, Node.UpdateExpression(token.value, expr, prefix))
            self.context.isAssignmentTarget = False
            self.context.isBindingElement = False
        else:
            expr = self.inheritCoverGrammar(self.parseLeftHandSideExpressionAllowCall)
            if not self.hasLineTerminator and self.lookahead.type is Token.Punctuator:
                if self.match('++', '--'):
                    if self.context.strict and expr.type is Syntax.Identifier and self.scanner.isRestrictedWord(expr.name):
                        self.tolerateError(Messages.StrictLHSPostfix)
                    if not self.context.isAssignmentTarget:
                        self.tolerateError(Messages.InvalidLHSInAssignment)
                    self.context.isAssignmentTarget = False
                    self.context.isBindingElement = False
                    operator = self.nextToken().value
                    prefix = False
                    expr = self.finalize(self.startNode(startToken), Node.UpdateExpression(operator, expr, prefix))

        return expr

    # https://tc39.github.io/ecma262/#sec-unary-operators

    def parseAwaitExpression(self):
        node = self.createNode()
        self.nextToken()
        argument = self.parseUnaryExpression()
        return self.finalize(node, Node.AwaitExpression(argument))

    def parseUnaryExpression(self):
        if (
            self.match('+', '-', '~', '!') or
            self.matchKeyword('delete', 'void', 'typeof')
        ):
            node = self.startNode(self.lookahead)
            token = self.nextToken()
            expr = self.inheritCoverGrammar(self.parseUnaryExpression)
            expr = self.finalize(node, Node.UnaryExpression(token.value, expr))
            if self.context.strict and expr.operator == 'delete' and expr.argument.type is Syntax.Identifier:
                self.tolerateError(Messages.StrictDelete)
            self.context.isAssignmentTarget = False
            self.context.isBindingElement = False
        elif self.context.allowAwait and self.matchContextualKeyword('await'):
            expr = self.parseAwaitExpression()
        else:
            expr = self.parseUpdateExpression()

        return expr

    def parseExponentiationExpression(self):
        startToken = self.lookahead

        expr = self.inheritCoverGrammar(self.parseUnaryExpression)
        if expr.type is not Syntax.UnaryExpression and self.match('**'):
            self.nextToken()
            self.context.isAssignmentTarget = False
            self.context.isBindingElement = False
            left = expr
            right = self.isolateCoverGrammar(self.parseExponentiationExpression)
            expr = self.finalize(self.startNode(startToken), Node.BinaryExpression('**', left, right))

        return expr

    # https://tc39.github.io/ecma262/#sec-exp-operator
    # https://tc39.github.io/ecma262/#sec-multiplicative-operators
    # https://tc39.github.io/ecma262/#sec-additive-operators
    # https://tc39.github.io/ecma262/#sec-bitwise-shift-operators
    # https://tc39.github.io/ecma262/#sec-relational-operators
    # https://tc39.github.io/ecma262/#sec-equality-operators
    # https://tc39.github.io/ecma262/#sec-binary-bitwise-operators
    # https://tc39.github.io/ecma262/#sec-binary-logical-operators

    def binaryPrecedence(self, token):
        op = token.value
        if token.type is Token.Punctuator:
            precedence = self.operatorPrecedence.get(op, 0)
        elif token.type is Token.Keyword:
            precedence = 7 if (op == 'instanceof' or (self.context.allowIn and op == 'in')) else 0
        else:
            precedence = 0
        return precedence

    def parseBinaryExpression(self):
        startToken = self.lookahead

        expr = self.inheritCoverGrammar(self.parseExponentiationExpression)

        token = self.lookahead
        prec = self.binaryPrecedence(token)
        if prec > 0:
            self.nextToken()

            self.context.isAssignmentTarget = False
            self.context.isBindingElement = False

            markers = [startToken, self.lookahead]
            left = expr
            right = self.isolateCoverGrammar(self.parseExponentiationExpression)

            stack = [left, token.value, right]
            precedences = [prec]
            while True:
                prec = self.binaryPrecedence(self.lookahead)
                if prec <= 0:
                    break

                # Reduce: make a binary expression from the three topmost entries.
                while len(stack) > 2 and prec <= precedences[-1]:
                    right = stack.pop()
                    operator = stack.pop()
                    precedences.pop()
                    left = stack.pop()
                    markers.pop()
                    node = self.startNode(markers[-1])
                    stack.append(self.finalize(node, Node.BinaryExpression(operator, left, right)))

                # Shift.
                stack.append(self.nextToken().value)
                precedences.append(prec)
                markers.append(self.lookahead)
                stack.append(self.isolateCoverGrammar(self.parseExponentiationExpression))

            # Final reduce to clean-up the stack.
            i = len(stack) - 1
            expr = stack[i]

            lastMarker = markers.pop()
            while i > 1:
                marker = markers.pop()
                lastLineStart = lastMarker.lineStart if lastMarker else 0
                node = self.startNode(marker, lastLineStart)
                operator = stack[i - 1]
                expr = self.finalize(node, Node.BinaryExpression(operator, stack[i - 2], expr))
                i -= 2
                lastMarker = marker

        return expr

    # https://tc39.github.io/ecma262/#sec-conditional-operator

    def parseConditionalExpression(self):
        startToken = self.lookahead

        expr = self.inheritCoverGrammar(self.parseBinaryExpression)
        if self.match('?'):
            self.nextToken()

            previousAllowIn = self.context.allowIn
            self.context.allowIn = True
            consequent = self.isolateCoverGrammar(self.parseAssignmentExpression)
            self.context.allowIn = previousAllowIn

            self.expect(':')
            alternate = self.isolateCoverGrammar(self.parseAssignmentExpression)

            expr = self.finalize(self.startNode(startToken), Node.ConditionalExpression(expr, consequent, alternate))
            self.context.isAssignmentTarget = False
            self.context.isBindingElement = False

        return expr

    # https://tc39.github.io/ecma262/#sec-assignment-operators

    def checkPatternParam(self, options, param):
        typ = param.type
        if typ is Syntax.Identifier:
            self.validateParam(options, param, param.name)
        elif typ is Syntax.RestElement:
            self.checkPatternParam(options, param.argument)
        elif typ is Syntax.AssignmentPattern:
            self.checkPatternParam(options, param.left)
        elif typ is Syntax.ArrayPattern:
            for element in param.elements:
                if element is not None:
                    self.checkPatternParam(options, element)
        elif typ is Syntax.ObjectPattern:
            for prop in param.properties:
                self.checkPatternParam(options, prop if prop.type is Syntax.RestElement else prop.value)

        options.simple = options.simple and isinstance(param, Node.Identifier)

    def reinterpretAsCoverFormalsList(self, expr):
        params = [expr]

        asyncArrow = False
        typ = expr.type
        if typ is Syntax.Identifier:
            pass
        elif typ is Syntax.ArrowParameterPlaceHolder:
            params = expr.params
            asyncArrow = expr.isAsync
        else:
            return None

        options = Params(
            simple=True,
            paramSet={},
        )

        for param in params:
            if param.type is Syntax.AssignmentPattern:
                if param.right.type is Syntax.YieldExpression:
                    if param.right.argument:
                        self.throwUnexpectedToken(self.lookahead)
                    param.right.type = Syntax.Identifier
                    param.right.name = 'yield'
                    del param.right.argument
                    del param.right.delegate
            elif asyncArrow and param.type is Syntax.Identifier and param.name == 'await':
                self.throwUnexpectedToken(self.lookahead)
            self.checkPatternParam(options, param)

        if self.context.strict or not self.context.allowYield:
            for param in params:
                if param.type is Syntax.YieldExpression:
                    self.throwUnexpectedToken(self.lookahead)

        if options.message is Messages.StrictParamDupe:
            token = options.stricted if self.context.strict else options.firstRestricted
            self.throwUnexpectedToken(token, options.message)

        return Params(
            simple=options.simple,
            params=params,
            stricted=options.stricted,
            firstRestricted=options.firstRestricted,
            message=options.message
        )

    def parseAssignmentExpression(self):
        if not self.context.allowYield and self.matchKeyword('yield'):
            expr = self.parseYieldExpression()
        else:
            startToken = self.lookahead
            token = startToken
            expr = self.parseConditionalExpression()

            if token.type is Token.Identifier and (token.lineNumber == self.lookahead.lineNumber) and token.value == 'async':
                if self.lookahead.type is Token.Identifier or self.matchKeyword('yield'):
                    arg = self.parsePrimaryExpression()
                    self.reinterpretExpressionAsPattern(arg)
                    expr = Node.AsyncArrowParameterPlaceHolder([arg])

            if expr.type is Syntax.ArrowParameterPlaceHolder or self.match('=>'):

                # https://tc39.github.io/ecma262/#sec-arrow-function-definitions
                self.context.isAssignmentTarget = False
                self.context.isBindingElement = False
                isAsync = expr.isAsync
                list = self.reinterpretAsCoverFormalsList(expr)

                if list:
                    if self.hasLineTerminator:
                        self.tolerateUnexpectedToken(self.lookahead)
                    self.context.firstCoverInitializedNameError = None

                    previousStrict = self.context.strict
                    previousAllowStrictDirective = self.context.allowStrictDirective
                    self.context.allowStrictDirective = list.simple

                    previousAllowYield = self.context.allowYield
                    previousAwait = self.context.allowAwait
                    self.context.allowYield = True
                    self.context.allowAwait = isAsync

                    node = self.startNode(startToken)
                    self.expect('=>')
                    if self.match('{'):
                        previousAllowIn = self.context.allowIn
                        self.context.allowIn = True
                        body = self.parseFunctionSourceElements()
                        self.context.allowIn = previousAllowIn
                    else:
                        body = self.isolateCoverGrammar(self.parseAssignmentExpression)
                    expression = body.type is not Syntax.BlockStatement

                    if self.context.strict and list.firstRestricted:
                        self.throwUnexpectedToken(list.firstRestricted, list.message)
                    if self.context.strict and list.stricted:
                        self.tolerateUnexpectedToken(list.stricted, list.message)
                    if isAsync:
                        expr = self.finalize(node, Node.AsyncArrowFunctionExpression(list.params, body, expression))
                    else:
                        expr = self.finalize(node, Node.ArrowFunctionExpression(list.params, body, expression))

                    self.context.strict = previousStrict
                    self.context.allowStrictDirective = previousAllowStrictDirective
                    self.context.allowYield = previousAllowYield
                    self.context.allowAwait = previousAwait
            else:
                if self.matchAssign():
                    if not self.context.isAssignmentTarget:
                        self.tolerateError(Messages.InvalidLHSInAssignment)

                    if self.context.strict and expr.type is Syntax.Identifier:
                        id = expr
                        if self.scanner.isRestrictedWord(id.name):
                            self.tolerateUnexpectedToken(token, Messages.StrictLHSAssignment)
                        if self.scanner.isStrictModeReservedWord(id.name):
                            self.tolerateUnexpectedToken(token, Messages.StrictReservedWord)

                    if not self.match('='):
                        self.context.isAssignmentTarget = False
                        self.context.isBindingElement = False
                    else:
                        self.reinterpretExpressionAsPattern(expr)

                    token = self.nextToken()
                    operator = token.value
                    right = self.isolateCoverGrammar(self.parseAssignmentExpression)
                    expr = self.finalize(self.startNode(startToken), Node.AssignmentExpression(operator, expr, right))
                    self.context.firstCoverInitializedNameError = None

        return expr

    # https://tc39.github.io/ecma262/#sec-comma-operator

    def parseExpression(self):
        startToken = self.lookahead
        expr = self.isolateCoverGrammar(self.parseAssignmentExpression)

        if self.match(','):
            expressions = []
            expressions.append(expr)
            while self.lookahead.type is not Token.EOF:
                if not self.match(','):
                    break
                self.nextToken()
                expressions.append(self.isolateCoverGrammar(self.parseAssignmentExpression))

            expr = self.finalize(self.startNode(startToken), Node.SequenceExpression(expressions))

        return expr

    # https://tc39.github.io/ecma262/#sec-block

    def parseStatementListItem(self):
        self.context.isAssignmentTarget = True
        self.context.isBindingElement = True
        if self.lookahead.type is Token.Keyword:
            value = self.lookahead.value
            if value == 'export':
                if not self.context.isModule:
                    self.tolerateUnexpectedToken(self.lookahead, Messages.IllegalExportDeclaration)
                statement = self.parseExportDeclaration()
            elif value == 'import':
                if self.matchImportCall():
                    statement = self.parseExpressionStatement()
                else:
                    if not self.context.isModule:
                        self.tolerateUnexpectedToken(self.lookahead, Messages.IllegalImportDeclaration)
                    statement = self.parseImportDeclaration()
            elif value == 'const':
                statement = self.parseLexicalDeclaration(Params(inFor=False))
            elif value == 'function':
                statement = self.parseFunctionDeclaration()
            elif value == 'class':
                statement = self.parseClassDeclaration()
            elif value == 'let':
                statement = self.parseLexicalDeclaration(Params(inFor=False)) if self.isLexicalDeclaration() else self.parseStatement()
            else:
                statement = self.parseStatement()
        else:
            statement = self.parseStatement()

        return statement

    def parseBlock(self):
        node = self.createNode()

        self.expect('{')
        block = []
        while True:
            if self.match('}'):
                break
            block.append(self.parseStatementListItem())
        self.expect('}')

        return self.finalize(node, Node.BlockStatement(block))

    # https://tc39.github.io/ecma262/#sec-let-and-const-declarations

    def parseLexicalBinding(self, kind, options):
        node = self.createNode()
        params = []
        id = self.parsePattern(params, kind)

        if self.context.strict and id.type is Syntax.Identifier:
            if self.scanner.isRestrictedWord(id.name):
                self.tolerateError(Messages.StrictVarName)

        init = None
        if kind == 'const':
            if not self.matchKeyword('in') and not self.matchContextualKeyword('of'):
                if self.match('='):
                    self.nextToken()
                    init = self.isolateCoverGrammar(self.parseAssignmentExpression)
                else:
                    self.throwError(Messages.DeclarationMissingInitializer, 'const')
        elif (not options.inFor and id.type is not Syntax.Identifier) or self.match('='):
            self.expect('=')
            init = self.isolateCoverGrammar(self.parseAssignmentExpression)

        return self.finalize(node, Node.VariableDeclarator(id, init))

    def parseBindingList(self, kind, options):
        lst = [self.parseLexicalBinding(kind, options)]

        while self.match(','):
            self.nextToken()
            lst.append(self.parseLexicalBinding(kind, options))

        return lst

    def isLexicalDeclaration(self):
        state = self.scanner.saveState()
        self.scanner.scanComments()
        next = self.scanner.lex()
        self.scanner.restoreState(state)

        return (
            (next.type is Token.Identifier) or
            (next.type is Token.Punctuator and next.value == '[') or
            (next.type is Token.Punctuator and next.value == '{') or
            (next.type is Token.Keyword and next.value == 'let') or
            (next.type is Token.Keyword and next.value == 'yield')
        )

    def parseLexicalDeclaration(self, options):
        node = self.createNode()
        kind = self.nextToken().value
        assert kind == 'let' or kind == 'const', 'Lexical declaration must be either or const'

        declarations = self.parseBindingList(kind, options)
        self.consumeSemicolon()

        return self.finalize(node, Node.VariableDeclaration(declarations, kind))

    # https://tc39.github.io/ecma262/#sec-destructuring-binding-patterns

    def parseBindingRestElement(self, params, kind=None):
        node = self.createNode()

        self.expect('...')
        arg = self.parsePattern(params, kind)

        return self.finalize(node, Node.RestElement(arg))

    def parseArrayPattern(self, params, kind=None):
        node = self.createNode()

        self.expect('[')
        elements = []
        while not self.match(']'):
            if self.match(','):
                self.nextToken()
                elements.append(None)
            else:
                if self.match('...'):
                    elements.append(self.parseBindingRestElement(params, kind))
                    break
                else:
                    elements.append(self.parsePatternWithDefault(params, kind))
                if not self.match(']'):
                    self.expect(',')
        self.expect(']')

        return self.finalize(node, Node.ArrayPattern(elements))

    def parsePropertyPattern(self, params, kind=None):
        node = self.createNode()

        computed = False
        shorthand = False
        method = False

        key = None

        if self.lookahead.type is Token.Identifier:
            keyToken = self.lookahead
            key = self.parseVariableIdentifier()
            init = self.finalize(node, Node.Identifier(keyToken.value))
            if self.match('='):
                params.append(keyToken)
                shorthand = True
                self.nextToken()
                expr = self.parseAssignmentExpression()
                value = self.finalize(self.startNode(keyToken), Node.AssignmentPattern(init, expr))
            elif not self.match(':'):
                params.append(keyToken)
                shorthand = True
                value = init
            else:
                self.expect(':')
                value = self.parsePatternWithDefault(params, kind)
        else:
            computed = self.match('[')
            key = self.parseObjectPropertyKey()
            self.expect(':')
            value = self.parsePatternWithDefault(params, kind)

        return self.finalize(node, Node.Property('init', key, computed, value, method, shorthand))

    def parseRestProperty(self, params, kind):
        node = self.createNode()
        self.expect('...')
        arg = self.parsePattern(params)
        if self.match('='):
            self.throwError(Messages.DefaultRestProperty)
        if not self.match('}'):
            self.throwError(Messages.PropertyAfterRestProperty)
        return self.finalize(node, Node.RestElement(arg))

    def parseObjectPattern(self, params, kind=None):
        node = self.createNode()
        properties = []

        self.expect('{')
        while not self.match('}'):
            properties.append(self.parseRestProperty(params, kind) if self.match('...') else self.parsePropertyPattern(params, kind))
            if not self.match('}'):
                self.expect(',')
        self.expect('}')

        return self.finalize(node, Node.ObjectPattern(properties))

    def parsePattern(self, params, kind=None):
        if self.match('['):
            pattern = self.parseArrayPattern(params, kind)
        elif self.match('{'):
            pattern = self.parseObjectPattern(params, kind)
        else:
            if self.matchKeyword('let') and (kind in ('const', 'let')):
                self.tolerateUnexpectedToken(self.lookahead, Messages.LetInLexicalBinding)
            params.append(self.lookahead)
            pattern = self.parseVariableIdentifier(kind)

        return pattern

    def parsePatternWithDefault(self, params, kind=None):
        startToken = self.lookahead

        pattern = self.parsePattern(params, kind)
        if self.match('='):
            self.nextToken()
            previousAllowYield = self.context.allowYield
            self.context.allowYield = True
            right = self.isolateCoverGrammar(self.parseAssignmentExpression)
            self.context.allowYield = previousAllowYield
            pattern = self.finalize(self.startNode(startToken), Node.AssignmentPattern(pattern, right))

        return pattern

    # https://tc39.github.io/ecma262/#sec-variable-statement

    def parseVariableIdentifier(self, kind=None):
        node = self.createNode()

        token = self.nextToken()
        if token.type is Token.Keyword and token.value == 'yield':
            if self.context.strict:
                self.tolerateUnexpectedToken(token, Messages.StrictReservedWord)
            elif not self.context.allowYield:
                self.throwUnexpectedToken(token)
        elif token.type is not Token.Identifier:
            if self.context.strict and token.type is Token.Keyword and self.scanner.isStrictModeReservedWord(token.value):
                self.tolerateUnexpectedToken(token, Messages.StrictReservedWord)
            else:
                if self.context.strict or token.value != 'let' or kind != 'var':
                    self.throwUnexpectedToken(token)
        elif (self.context.isModule or self.context.allowAwait) and token.type is Token.Identifier and token.value == 'await':
            self.tolerateUnexpectedToken(token)

        return self.finalize(node, Node.Identifier(token.value))

    def parseVariableDeclaration(self, options):
        node = self.createNode()

        params = []
        id = self.parsePattern(params, 'var')

        if self.context.strict and id.type is Syntax.Identifier:
            if self.scanner.isRestrictedWord(id.name):
                self.tolerateError(Messages.StrictVarName)

        init = None
        if self.match('='):
            self.nextToken()
            init = self.isolateCoverGrammar(self.parseAssignmentExpression)
        elif id.type is not Syntax.Identifier and not options.inFor:
            self.expect('=')

        return self.finalize(node, Node.VariableDeclarator(id, init))

    def parseVariableDeclarationList(self, options):
        opt = Params(inFor=options.inFor)

        lst = []
        lst.append(self.parseVariableDeclaration(opt))
        while self.match(','):
            self.nextToken()
            lst.append(self.parseVariableDeclaration(opt))

        return lst

    def parseVariableStatement(self):
        node = self.createNode()
        self.expectKeyword('var')
        declarations = self.parseVariableDeclarationList(Params(inFor=False))
        self.consumeSemicolon()

        return self.finalize(node, Node.VariableDeclaration(declarations, 'var'))

    # https://tc39.github.io/ecma262/#sec-empty-statement

    def parseEmptyStatement(self):
        node = self.createNode()
        self.expect(';')
        return self.finalize(node, Node.EmptyStatement())

    # https://tc39.github.io/ecma262/#sec-expression-statement

    def parseExpressionStatement(self):
        node = self.createNode()
        expr = self.parseExpression()
        self.consumeSemicolon()
        return self.finalize(node, Node.ExpressionStatement(expr))

    # https://tc39.github.io/ecma262/#sec-if-statement

    def parseIfClause(self):
        if self.context.strict and self.matchKeyword('function'):
            self.tolerateError(Messages.StrictFunction)
        return self.parseStatement()

    def parseIfStatement(self):
        node = self.createNode()
        alternate = None

        self.expectKeyword('if')
        self.expect('(')
        test = self.parseExpression()

        if not self.match(')') and self.config.tolerant:
            self.tolerateUnexpectedToken(self.nextToken())
            consequent = self.finalize(self.createNode(), Node.EmptyStatement())
        else:
            self.expect(')')
            consequent = self.parseIfClause()
            if self.matchKeyword('else'):
                self.nextToken()
                alternate = self.parseIfClause()

        return self.finalize(node, Node.IfStatement(test, consequent, alternate))

    # https://tc39.github.io/ecma262/#sec-do-while-statement

    def parseDoWhileStatement(self):
        node = self.createNode()
        self.expectKeyword('do')

        previousInIteration = self.context.inIteration
        self.context.inIteration = True
        body = self.parseStatement()
        self.context.inIteration = previousInIteration

        self.expectKeyword('while')
        self.expect('(')
        test = self.parseExpression()

        if not self.match(')') and self.config.tolerant:
            self.tolerateUnexpectedToken(self.nextToken())
        else:
            self.expect(')')
            if self.match(';'):
                self.nextToken()

        return self.finalize(node, Node.DoWhileStatement(body, test))

    # https://tc39.github.io/ecma262/#sec-while-statement

    def parseWhileStatement(self):
        node = self.createNode()

        self.expectKeyword('while')
        self.expect('(')
        test = self.parseExpression()

        if not self.match(')') and self.config.tolerant:
            self.tolerateUnexpectedToken(self.nextToken())
            body = self.finalize(self.createNode(), Node.EmptyStatement())
        else:
            self.expect(')')

            previousInIteration = self.context.inIteration
            self.context.inIteration = True
            body = self.parseStatement()
            self.context.inIteration = previousInIteration

        return self.finalize(node, Node.WhileStatement(test, body))

    # https://tc39.github.io/ecma262/#sec-for-statement
    # https://tc39.github.io/ecma262/#sec-for-in-and-for-of-statements

    def parseForStatement(self):
        init = None
        test = None
        update = None
        forIn = True
        left = None
        right = None

        node = self.createNode()
        self.expectKeyword('for')
        self.expect('(')

        if self.match(';'):
            self.nextToken()
        else:
            if self.matchKeyword('var'):
                init = self.createNode()
                self.nextToken()

                previousAllowIn = self.context.allowIn
                self.context.allowIn = False
                declarations = self.parseVariableDeclarationList(Params(inFor=True))
                self.context.allowIn = previousAllowIn

                if len(declarations) == 1 and self.matchKeyword('in'):
                    decl = declarations[0]
                    if decl.init and (decl.id.type is Syntax.ArrayPattern or decl.id.type is Syntax.ObjectPattern or self.context.strict):
                        self.tolerateError(Messages.ForInOfLoopInitializer, 'for-in')
                    init = self.finalize(init, Node.VariableDeclaration(declarations, 'var'))
                    self.nextToken()
                    left = init
                    right = self.parseExpression()
                    init = None
                elif len(declarations) == 1 and declarations[0].init is None and self.matchContextualKeyword('of'):
                    init = self.finalize(init, Node.VariableDeclaration(declarations, 'var'))
                    self.nextToken()
                    left = init
                    right = self.parseAssignmentExpression()
                    init = None
                    forIn = False
                else:
                    init = self.finalize(init, Node.VariableDeclaration(declarations, 'var'))
                    self.expect(';')
            elif self.matchKeyword('const', 'let'):
                init = self.createNode()
                kind = self.nextToken().value

                if not self.context.strict and self.lookahead.value == 'in':
                    init = self.finalize(init, Node.Identifier(kind))
                    self.nextToken()
                    left = init
                    right = self.parseExpression()
                    init = None
                else:
                    previousAllowIn = self.context.allowIn
                    self.context.allowIn = False
                    declarations = self.parseBindingList(kind, Params(inFor=True))
                    self.context.allowIn = previousAllowIn

                    if len(declarations) == 1 and declarations[0].init is None and self.matchKeyword('in'):
                        init = self.finalize(init, Node.VariableDeclaration(declarations, kind))
                        self.nextToken()
                        left = init
                        right = self.parseExpression()
                        init = None
                    elif len(declarations) == 1 and declarations[0].init is None and self.matchContextualKeyword('of'):
                        init = self.finalize(init, Node.VariableDeclaration(declarations, kind))
                        self.nextToken()
                        left = init
                        right = self.parseAssignmentExpression()
                        init = None
                        forIn = False
                    else:
                        self.consumeSemicolon()
                        init = self.finalize(init, Node.VariableDeclaration(declarations, kind))
            else:
                initStartToken = self.lookahead
                previousAllowIn = self.context.allowIn
                self.context.allowIn = False
                init = self.inheritCoverGrammar(self.parseAssignmentExpression)
                self.context.allowIn = previousAllowIn

                if self.matchKeyword('in'):
                    if not self.context.isAssignmentTarget or init.type is Syntax.AssignmentExpression:
                        self.tolerateError(Messages.InvalidLHSInForIn)

                    self.nextToken()
                    self.reinterpretExpressionAsPattern(init)
                    left = init
                    right = self.parseExpression()
                    init = None
                elif self.matchContextualKeyword('of'):
                    if not self.context.isAssignmentTarget or init.type is Syntax.AssignmentExpression:
                        self.tolerateError(Messages.InvalidLHSInForLoop)

                    self.nextToken()
                    self.reinterpretExpressionAsPattern(init)
                    left = init
                    right = self.parseAssignmentExpression()
                    init = None
                    forIn = False
                else:
                    if self.match(','):
                        initSeq = [init]
                        while self.match(','):
                            self.nextToken()
                            initSeq.append(self.isolateCoverGrammar(self.parseAssignmentExpression))
                        init = self.finalize(self.startNode(initStartToken), Node.SequenceExpression(initSeq))
                    self.expect(';')

        if left is None:
            if not self.match(';'):
                test = self.parseExpression()
            self.expect(';')
            if not self.match(')'):
                update = self.parseExpression()

        if not self.match(')') and self.config.tolerant:
            self.tolerateUnexpectedToken(self.nextToken())
            body = self.finalize(self.createNode(), Node.EmptyStatement())
        else:
            self.expect(')')

            previousInIteration = self.context.inIteration
            self.context.inIteration = True
            body = self.isolateCoverGrammar(self.parseStatement)
            self.context.inIteration = previousInIteration

        if left is None:
            return self.finalize(node, Node.ForStatement(init, test, update, body))

        if forIn:
            return self.finalize(node, Node.ForInStatement(left, right, body))

        return self.finalize(node, Node.ForOfStatement(left, right, body))

    # https://tc39.github.io/ecma262/#sec-continue-statement

    def parseContinueStatement(self):
        node = self.createNode()
        self.expectKeyword('continue')

        label = None
        if self.lookahead.type is Token.Identifier and not self.hasLineTerminator:
            id = self.parseVariableIdentifier()
            label = id

            key = '$' + id.name
            if key not in self.context.labelSet:
                self.throwError(Messages.UnknownLabel, id.name)

        self.consumeSemicolon()
        if label is None and not self.context.inIteration:
            self.throwError(Messages.IllegalContinue)

        return self.finalize(node, Node.ContinueStatement(label))

    # https://tc39.github.io/ecma262/#sec-break-statement

    def parseBreakStatement(self):
        node = self.createNode()
        self.expectKeyword('break')

        label = None
        if self.lookahead.type is Token.Identifier and not self.hasLineTerminator:
            id = self.parseVariableIdentifier()

            key = '$' + id.name
            if key not in self.context.labelSet:
                self.throwError(Messages.UnknownLabel, id.name)
            label = id

        self.consumeSemicolon()
        if label is None and not self.context.inIteration and not self.context.inSwitch:
            self.throwError(Messages.IllegalBreak)

        return self.finalize(node, Node.BreakStatement(label))

    # https://tc39.github.io/ecma262/#sec-return-statement

    def parseReturnStatement(self):
        if not self.context.inFunctionBody:
            self.tolerateError(Messages.IllegalReturn)

        node = self.createNode()
        self.expectKeyword('return')

        hasArgument = (
            (
                not self.match(';') and not self.match('}') and
                not self.hasLineTerminator and self.lookahead.type is not Token.EOF
            ) or
            self.lookahead.type is Token.StringLiteral or
            self.lookahead.type is Token.Template
        )
        argument = self.parseExpression() if hasArgument else None
        self.consumeSemicolon()

        return self.finalize(node, Node.ReturnStatement(argument))

    # https://tc39.github.io/ecma262/#sec-with-statement

    def parseWithStatement(self):
        if self.context.strict:
            self.tolerateError(Messages.StrictModeWith)

        node = self.createNode()

        self.expectKeyword('with')
        self.expect('(')
        object = self.parseExpression()

        if not self.match(')') and self.config.tolerant:
            self.tolerateUnexpectedToken(self.nextToken())
            body = self.finalize(self.createNode(), Node.EmptyStatement())
        else:
            self.expect(')')
            body = self.parseStatement()

        return self.finalize(node, Node.WithStatement(object, body))

    # https://tc39.github.io/ecma262/#sec-switch-statement

    def parseSwitchCase(self):
        node = self.createNode()

        if self.matchKeyword('default'):
            self.nextToken()
            test = None
        else:
            self.expectKeyword('case')
            test = self.parseExpression()
        self.expect(':')

        consequent = []
        while True:
            if self.match('}') or self.matchKeyword('default', 'case'):
                break
            consequent.append(self.parseStatementListItem())

        return self.finalize(node, Node.SwitchCase(test, consequent))

    def parseSwitchStatement(self):
        node = self.createNode()
        self.expectKeyword('switch')

        self.expect('(')
        discriminant = self.parseExpression()
        self.expect(')')

        previousInSwitch = self.context.inSwitch
        self.context.inSwitch = True

        cases = []
        defaultFound = False
        self.expect('{')
        while True:
            if self.match('}'):
                break
            clause = self.parseSwitchCase()
            if clause.test is None:
                if defaultFound:
                    self.throwError(Messages.MultipleDefaultsInSwitch)
                defaultFound = True
            cases.append(clause)
        self.expect('}')

        self.context.inSwitch = previousInSwitch

        return self.finalize(node, Node.SwitchStatement(discriminant, cases))

    # https://tc39.github.io/ecma262/#sec-labelled-statements

    def parseLabelledStatement(self):
        node = self.createNode()
        expr = self.parseExpression()

        if expr.type is Syntax.Identifier and self.match(':'):
            self.nextToken()

            id = expr
            key = '$' + id.name
            if key in self.context.labelSet:
                self.throwError(Messages.Redeclaration, 'Label', id.name)

            self.context.labelSet[key] = True
            if self.matchKeyword('class'):
                self.tolerateUnexpectedToken(self.lookahead)
                body = self.parseClassDeclaration()
            elif self.matchKeyword('function'):
                token = self.lookahead
                declaration = self.parseFunctionDeclaration()
                if self.context.strict:
                    self.tolerateUnexpectedToken(token, Messages.StrictFunction)
                elif declaration.generator:
                    self.tolerateUnexpectedToken(token, Messages.GeneratorInLegacyContext)
                body = declaration
            else:
                body = self.parseStatement()
            del self.context.labelSet[key]

            statement = Node.LabeledStatement(id, body)
        else:
            self.consumeSemicolon()
            statement = Node.ExpressionStatement(expr)

        return self.finalize(node, statement)

    # https://tc39.github.io/ecma262/#sec-throw-statement

    def parseThrowStatement(self):
        node = self.createNode()
        self.expectKeyword('throw')

        if self.hasLineTerminator:
            self.throwError(Messages.NewlineAfterThrow)

        argument = self.parseExpression()
        self.consumeSemicolon()

        return self.finalize(node, Node.ThrowStatement(argument))

    # https://tc39.github.io/ecma262/#sec-try-statement

    def parseCatchClause(self):
        node = self.createNode()

        self.expectKeyword('catch')

        self.expect('(')
        if self.match(')'):
            self.throwUnexpectedToken(self.lookahead)

        params = []
        param = self.parsePattern(params)
        paramMap = {}
        for p in params:
            key = '$' + p.value
            if key in paramMap:
                self.tolerateError(Messages.DuplicateBinding, p.value)
            paramMap[key] = True

        if self.context.strict and param.type is Syntax.Identifier:
            if self.scanner.isRestrictedWord(param.name):
                self.tolerateError(Messages.StrictCatchVariable)

        self.expect(')')
        body = self.parseBlock()

        return self.finalize(node, Node.CatchClause(param, body))

    def parseFinallyClause(self):
        self.expectKeyword('finally')
        return self.parseBlock()

    def parseTryStatement(self):
        node = self.createNode()
        self.expectKeyword('try')

        block = self.parseBlock()
        handler = self.parseCatchClause() if self.matchKeyword('catch') else None
        finalizer = self.parseFinallyClause() if self.matchKeyword('finally') else None

        if not handler and not finalizer:
            self.throwError(Messages.NoCatchOrFinally)

        return self.finalize(node, Node.TryStatement(block, handler, finalizer))

    # https://tc39.github.io/ecma262/#sec-debugger-statement

    def parseDebuggerStatement(self):
        node = self.createNode()
        self.expectKeyword('debugger')
        self.consumeSemicolon()
        return self.finalize(node, Node.DebuggerStatement())

    # https://tc39.github.io/ecma262/#sec-ecmascript-language-statements-and-declarations

    def parseStatement(self):
        typ = self.lookahead.type
        if typ in (
            Token.BooleanLiteral,
            Token.NullLiteral,
            Token.NumericLiteral,
            Token.StringLiteral,
            Token.Template,
            Token.RegularExpression,
        ):
            statement = self.parseExpressionStatement()

        elif typ is Token.Punctuator:
            value = self.lookahead.value
            if value == '{':
                statement = self.parseBlock()
            elif value == '(':
                statement = self.parseExpressionStatement()
            elif value == ';':
                statement = self.parseEmptyStatement()
            else:
                statement = self.parseExpressionStatement()

        elif typ is Token.Identifier:
            statement = self.parseFunctionDeclaration() if self.matchAsyncFunction() else self.parseLabelledStatement()

        elif typ is Token.Keyword:
            value = self.lookahead.value
            if value == 'break':
                statement = self.parseBreakStatement()
            elif value == 'continue':
                statement = self.parseContinueStatement()
            elif value == 'debugger':
                statement = self.parseDebuggerStatement()
            elif value == 'do':
                statement = self.parseDoWhileStatement()
            elif value == 'for':
                statement = self.parseForStatement()
            elif value == 'function':
                statement = self.parseFunctionDeclaration()
            elif value == 'if':
                statement = self.parseIfStatement()
            elif value == 'return':
                statement = self.parseReturnStatement()
            elif value == 'switch':
                statement = self.parseSwitchStatement()
            elif value == 'throw':
                statement = self.parseThrowStatement()
            elif value == 'try':
                statement = self.parseTryStatement()
            elif value == 'var':
                statement = self.parseVariableStatement()
            elif value == 'while':
                statement = self.parseWhileStatement()
            elif value == 'with':
                statement = self.parseWithStatement()
            else:
                statement = self.parseExpressionStatement()

        else:
            statement = self.throwUnexpectedToken(self.lookahead)

        return statement

    # https://tc39.github.io/ecma262/#sec-function-definitions

    def parseFunctionSourceElements(self):
        node = self.createNode()

        self.expect('{')
        body = self.parseDirectivePrologues()

        previousLabelSet = self.context.labelSet
        previousInIteration = self.context.inIteration
        previousInSwitch = self.context.inSwitch
        previousInFunctionBody = self.context.inFunctionBody

        self.context.labelSet = {}
        self.context.inIteration = False
        self.context.inSwitch = False
        self.context.inFunctionBody = True

        while self.lookahead.type is not Token.EOF:
            if self.match('}'):
                break
            body.append(self.parseStatementListItem())

        self.expect('}')

        self.context.labelSet = previousLabelSet
        self.context.inIteration = previousInIteration
        self.context.inSwitch = previousInSwitch
        self.context.inFunctionBody = previousInFunctionBody

        return self.finalize(node, Node.BlockStatement(body))

    def validateParam(self, options, param, name):
        key = '$' + name
        if self.context.strict:
            if self.scanner.isRestrictedWord(name):
                options.stricted = param
                options.message = Messages.StrictParamName
            if key in options.paramSet:
                options.stricted = param
                options.message = Messages.StrictParamDupe
        elif not options.firstRestricted:
            if self.scanner.isRestrictedWord(name):
                options.firstRestricted = param
                options.message = Messages.StrictParamName
            elif self.scanner.isStrictModeReservedWord(name):
                options.firstRestricted = param
                options.message = Messages.StrictReservedWord
            elif key in options.paramSet:
                options.stricted = param
                options.message = Messages.StrictParamDupe

        options.paramSet[key] = True

    def parseRestElement(self, params):
        node = self.createNode()

        self.expect('...')
        arg = self.parsePattern(params)
        if self.match('='):
            self.throwError(Messages.DefaultRestParameter)
        if not self.match(')'):
            self.throwError(Messages.ParameterAfterRestParameter)

        return self.finalize(node, Node.RestElement(arg))

    def parseFormalParameter(self, options):
        params = []
        param = self.parseRestElement(params) if self.match('...') else self.parsePatternWithDefault(params)
        for p in params:
            self.validateParam(options, p, p.value)
        options.simple = options.simple and isinstance(param, Node.Identifier)
        options.params.append(param)

    def parseFormalParameters(self, firstRestricted=None):
        options = Params(
            simple=True,
            params=[],
            firstRestricted=firstRestricted
        )

        self.expect('(')
        if not self.match(')'):
            options.paramSet = {}
            while self.lookahead.type is not Token.EOF:
                self.parseFormalParameter(options)
                if self.match(')'):
                    break
                self.expect(',')
                if self.match(')'):
                    break
        self.expect(')')

        return Params(
            simple=options.simple,
            params=options.params,
            stricted=options.stricted,
            firstRestricted=options.firstRestricted,
            message=options.message
        )

    def matchAsyncFunction(self):
        match = self.matchContextualKeyword('async')
        if match:
            state = self.scanner.saveState()
            self.scanner.scanComments()
            next = self.scanner.lex()
            self.scanner.restoreState(state)

            match = (state.lineNumber == next.lineNumber) and (next.type is Token.Keyword) and (next.value == 'function')

        return match

    def parseFunctionDeclaration(self, identifierIsOptional=False):
        node = self.createNode()

        isAsync = self.matchContextualKeyword('async')
        if isAsync:
            self.nextToken()

        self.expectKeyword('function')

        isGenerator = False if isAsync else self.match('*')
        if isGenerator:
            self.nextToken()

        id = None
        firstRestricted = None

        if not identifierIsOptional or not self.match('('):
            token = self.lookahead
            id = self.parseVariableIdentifier()
            if self.context.strict:
                if self.scanner.isRestrictedWord(token.value):
                    self.tolerateUnexpectedToken(token, Messages.StrictFunctionName)
            else:
                if self.scanner.isRestrictedWord(token.value):
                    firstRestricted = token
                    message = Messages.StrictFunctionName
                elif self.scanner.isStrictModeReservedWord(token.value):
                    firstRestricted = token
                    message = Messages.StrictReservedWord

        previousAllowAwait = self.context.allowAwait
        previousAllowYield = self.context.allowYield
        self.context.allowAwait = isAsync
        self.context.allowYield = not isGenerator

        formalParameters = self.parseFormalParameters(firstRestricted)
        params = formalParameters.params
        stricted = formalParameters.stricted
        firstRestricted = formalParameters.firstRestricted
        if formalParameters.message:
            message = formalParameters.message

        previousStrict = self.context.strict
        previousAllowStrictDirective = self.context.allowStrictDirective
        self.context.allowStrictDirective = formalParameters.simple
        body = self.parseFunctionSourceElements()
        if self.context.strict and firstRestricted:
            self.throwUnexpectedToken(firstRestricted, message)
        if self.context.strict and stricted:
            self.tolerateUnexpectedToken(stricted, message)

        self.context.strict = previousStrict
        self.context.allowStrictDirective = previousAllowStrictDirective
        self.context.allowAwait = previousAllowAwait
        self.context.allowYield = previousAllowYield

        if isAsync:
            return self.finalize(node, Node.AsyncFunctionDeclaration(id, params, body))

        return self.finalize(node, Node.FunctionDeclaration(id, params, body, isGenerator))

    def parseFunctionExpression(self):
        node = self.createNode()

        isAsync = self.matchContextualKeyword('async')
        if isAsync:
            self.nextToken()

        self.expectKeyword('function')

        isGenerator = False if isAsync else self.match('*')
        if isGenerator:
            self.nextToken()

        id = None
        firstRestricted = None

        previousAllowAwait = self.context.allowAwait
        previousAllowYield = self.context.allowYield
        self.context.allowAwait = isAsync
        self.context.allowYield = not isGenerator

        if not self.match('('):
            token = self.lookahead
            id = self.parseIdentifierName() if not self.context.strict and not isGenerator and self.matchKeyword('yield') else self.parseVariableIdentifier()
            if self.context.strict:
                if self.scanner.isRestrictedWord(token.value):
                    self.tolerateUnexpectedToken(token, Messages.StrictFunctionName)
            else:
                if self.scanner.isRestrictedWord(token.value):
                    firstRestricted = token
                    message = Messages.StrictFunctionName
                elif self.scanner.isStrictModeReservedWord(token.value):
                    firstRestricted = token
                    message = Messages.StrictReservedWord

        formalParameters = self.parseFormalParameters(firstRestricted)
        params = formalParameters.params
        stricted = formalParameters.stricted
        firstRestricted = formalParameters.firstRestricted
        if formalParameters.message:
            message = formalParameters.message

        previousStrict = self.context.strict
        previousAllowStrictDirective = self.context.allowStrictDirective
        self.context.allowStrictDirective = formalParameters.simple
        body = self.parseFunctionSourceElements()
        if self.context.strict and firstRestricted:
            self.throwUnexpectedToken(firstRestricted, message)
        if self.context.strict and stricted:
            self.tolerateUnexpectedToken(stricted, message)
        self.context.strict = previousStrict
        self.context.allowStrictDirective = previousAllowStrictDirective
        self.context.allowAwait = previousAllowAwait
        self.context.allowYield = previousAllowYield

        if isAsync:
            return self.finalize(node, Node.AsyncFunctionExpression(id, params, body))

        return self.finalize(node, Node.FunctionExpression(id, params, body, isGenerator))

    # https://tc39.github.io/ecma262/#sec-directive-prologues-and-the-use-strict-directive

    def parseDirective(self):
        token = self.lookahead

        node = self.createNode()
        expr = self.parseExpression()
        directive = self.getTokenRaw(token)[1:-1] if expr.type is Syntax.Literal else None
        self.consumeSemicolon()

        return self.finalize(node, Node.Directive(expr, directive) if directive else Node.ExpressionStatement(expr))

    def parseDirectivePrologues(self):
        firstRestricted = None

        body = []
        while True:
            token = self.lookahead
            if token.type is not Token.StringLiteral:
                break

            statement = self.parseDirective()
            body.append(statement)
            directive = statement.directive
            if not isinstance(directive, basestring):
                break

            if directive == 'use strict':
                self.context.strict = True
                if firstRestricted:
                    self.tolerateUnexpectedToken(firstRestricted, Messages.StrictOctalLiteral)
                if not self.context.allowStrictDirective:
                    self.tolerateUnexpectedToken(token, Messages.IllegalLanguageModeDirective)
            else:
                if not firstRestricted and token.octal:
                    firstRestricted = token

        return body

    # https://tc39.github.io/ecma262/#sec-method-definitions

    def qualifiedPropertyName(self, token):
        typ = token.type
        if typ in (
            Token.Identifier,
            Token.StringLiteral,
            Token.BooleanLiteral,
            Token.NullLiteral,
            Token.NumericLiteral,
            Token.Keyword,
        ):
            return True
        elif typ is Token.Punctuator:
            return token.value == '['
        return False

    def parseGetterMethod(self):
        node = self.createNode()

        isGenerator = False
        previousAllowYield = self.context.allowYield
        self.context.allowYield = not isGenerator
        formalParameters = self.parseFormalParameters()
        if len(formalParameters.params) > 0:
            self.tolerateError(Messages.BadGetterArity)
        method = self.parsePropertyMethod(formalParameters)
        self.context.allowYield = previousAllowYield

        return self.finalize(node, Node.FunctionExpression(None, formalParameters.params, method, isGenerator))

    def parseSetterMethod(self):
        node = self.createNode()

        isGenerator = False
        previousAllowYield = self.context.allowYield
        self.context.allowYield = not isGenerator
        formalParameters = self.parseFormalParameters()
        if len(formalParameters.params) != 1:
            self.tolerateError(Messages.BadSetterArity)
        elif isinstance(formalParameters.params[0], Node.RestElement):
            self.tolerateError(Messages.BadSetterRestParameter)
        method = self.parsePropertyMethod(formalParameters)
        self.context.allowYield = previousAllowYield

        return self.finalize(node, Node.FunctionExpression(None, formalParameters.params, method, isGenerator))

    def parseGeneratorMethod(self):
        node = self.createNode()

        isGenerator = True
        previousAllowYield = self.context.allowYield

        self.context.allowYield = True
        params = self.parseFormalParameters()
        self.context.allowYield = False
        method = self.parsePropertyMethod(params)
        self.context.allowYield = previousAllowYield

        return self.finalize(node, Node.FunctionExpression(None, params.params, method, isGenerator))

    # https://tc39.github.io/ecma262/#sec-generator-function-definitions

    def isStartOfExpression(self):
        start = True

        value = self.lookahead.value
        typ = self.lookahead.type
        if typ is Token.Punctuator:
            start = value in ('[', '(', '{', '+', '-', '!', '~', '++', '--', '/', '/=')  # regular expression literal )

        elif typ is Token.Keyword:
            start = value in ('class', 'delete', 'function', 'let', 'new', 'super', 'this', 'typeof', 'void', 'yield')

        return start

    def parseYieldExpression(self):
        node = self.createNode()
        self.expectKeyword('yield')

        argument = None
        delegate = False
        if not self.hasLineTerminator:
            previousAllowYield = self.context.allowYield
            self.context.allowYield = False
            delegate = self.match('*')
            if delegate:
                self.nextToken()
                argument = self.parseAssignmentExpression()
            elif self.isStartOfExpression():
                argument = self.parseAssignmentExpression()
            self.context.allowYield = previousAllowYield

        return self.finalize(node, Node.YieldExpression(argument, delegate))

    # https://tc39.github.io/ecma262/#sec-class-definitions

    def parseClassElement(self, hasConstructor):
        token = self.lookahead
        node = self.createNode()

        kind = ''
        key = None
        value = None
        computed = False
        isStatic = False
        isAsync = False

        if self.match('*'):
            self.nextToken()

        else:
            computed = self.match('[')
            key = self.parseObjectPropertyKey()
            id = key
            if id.name == 'static' and (self.qualifiedPropertyName(self.lookahead) or self.match('*')):
                token = self.lookahead
                isStatic = True
                computed = self.match('[')
                if self.match('*'):
                    self.nextToken()
                else:
                    key = self.parseObjectPropertyKey()
            if token.type is Token.Identifier and not self.hasLineTerminator and token.value == 'async':
                punctuator = self.lookahead.value
                if punctuator != ':' and punctuator != '(' and punctuator != '*':
                    isAsync = True
                    token = self.lookahead
                    key = self.parseObjectPropertyKey()
                    if token.type is Token.Identifier and token.value == 'constructor':
                        self.tolerateUnexpectedToken(token, Messages.ConstructorIsAsync)

        lookaheadPropertyKey = self.qualifiedPropertyName(self.lookahead)
        if token.type is Token.Identifier:
            if token.value == 'get' and lookaheadPropertyKey:
                kind = 'get'
                computed = self.match('[')
                key = self.parseObjectPropertyKey()
                self.context.allowYield = False
                value = self.parseGetterMethod()
            elif token.value == 'set' and lookaheadPropertyKey:
                kind = 'set'
                computed = self.match('[')
                key = self.parseObjectPropertyKey()
                value = self.parseSetterMethod()
            elif self.config.classProperties and not self.match('('):
                kind = 'init'
                id = self.finalize(node, Node.Identifier(token.value))
                if self.match('='):
                    self.nextToken()
                    value = self.parseAssignmentExpression()

        elif token.type is Token.Punctuator and token.value == '*' and lookaheadPropertyKey:
            kind = 'method'
            computed = self.match('[')
            key = self.parseObjectPropertyKey()
            value = self.parseGeneratorMethod()

        if not kind and key and self.match('('):
            kind = 'method'
            value = self.parsePropertyMethodAsyncFunction() if isAsync else self.parsePropertyMethodFunction()

        if not kind:
            self.throwUnexpectedToken(self.lookahead)

        if not computed:
            if isStatic and self.isPropertyKey(key, 'prototype'):
                self.throwUnexpectedToken(token, Messages.StaticPrototype)
            if not isStatic and self.isPropertyKey(key, 'constructor'):
                if kind != 'method' or (value and value.generator):
                    self.throwUnexpectedToken(token, Messages.ConstructorSpecialMethod)
                if hasConstructor.value:
                    self.throwUnexpectedToken(token, Messages.DuplicateConstructor)
                else:
                    hasConstructor.value = True
                kind = 'constructor'

        if kind in ('constructor', 'method', 'get', 'set'):
            return self.finalize(node, Node.MethodDefinition(key, computed, value, kind, isStatic))

        else:
            return self.finalize(node, Node.FieldDefinition(key, computed, value, kind, isStatic))

    def parseClassElementList(self):
        body = []
        hasConstructor = Value(False)

        self.expect('{')
        while not self.match('}'):
            if self.match(';'):
                self.nextToken()
            else:
                body.append(self.parseClassElement(hasConstructor))
        self.expect('}')

        return body

    def parseClassBody(self):
        node = self.createNode()
        elementList = self.parseClassElementList()

        return self.finalize(node, Node.ClassBody(elementList))

    def parseClassDeclaration(self, identifierIsOptional=False):
        node = self.createNode()

        previousStrict = self.context.strict
        self.context.strict = True
        self.expectKeyword('class')

        id = None if identifierIsOptional and self.lookahead.type is not Token.Identifier else self.parseVariableIdentifier()
        superClass = None
        if self.matchKeyword('extends'):
            self.nextToken()
            superClass = self.isolateCoverGrammar(self.parseLeftHandSideExpressionAllowCall)
        classBody = self.parseClassBody()
        self.context.strict = previousStrict

        return self.finalize(node, Node.ClassDeclaration(id, superClass, classBody))

    def parseClassExpression(self):
        node = self.createNode()

        previousStrict = self.context.strict
        self.context.strict = True
        self.expectKeyword('class')
        id = self.parseVariableIdentifier() if self.lookahead.type is Token.Identifier else None
        superClass = None
        if self.matchKeyword('extends'):
            self.nextToken()
            superClass = self.isolateCoverGrammar(self.parseLeftHandSideExpressionAllowCall)
        classBody = self.parseClassBody()
        self.context.strict = previousStrict

        return self.finalize(node, Node.ClassExpression(id, superClass, classBody))

    # https://tc39.github.io/ecma262/#sec-scripts
    # https://tc39.github.io/ecma262/#sec-modules

    def parseModule(self):
        self.context.strict = True
        self.context.isModule = True
        self.scanner.isModule = True
        node = self.createNode()
        body = self.parseDirectivePrologues()
        while self.lookahead.type is not Token.EOF:
            body.append(self.parseStatementListItem())
        return self.finalize(node, Node.Module(body))

    def parseScript(self):
        node = self.createNode()
        body = self.parseDirectivePrologues()
        while self.lookahead.type is not Token.EOF:
            body.append(self.parseStatementListItem())
        return self.finalize(node, Node.Script(body))

    # https://tc39.github.io/ecma262/#sec-imports

    def parseModuleSpecifier(self):
        node = self.createNode()

        if self.lookahead.type is not Token.StringLiteral:
            self.throwError(Messages.InvalidModuleSpecifier)

        token = self.nextToken()
        raw = self.getTokenRaw(token)
        return self.finalize(node, Node.Literal(token.value, raw))

    # import {<foo as bar>} ...
    def parseImportSpecifier(self):
        node = self.createNode()

        if self.lookahead.type is Token.Identifier:
            imported = self.parseVariableIdentifier()
            local = imported
            if self.matchContextualKeyword('as'):
                self.nextToken()
                local = self.parseVariableIdentifier()
        else:
            imported = self.parseIdentifierName()
            local = imported
            if self.matchContextualKeyword('as'):
                self.nextToken()
                local = self.parseVariableIdentifier()
            else:
                self.throwUnexpectedToken(self.nextToken())

        return self.finalize(node, Node.ImportSpecifier(local, imported))

    # {foo, bar as bas
    def parseNamedImports(self):
        self.expect('{')
        specifiers = []
        while not self.match('}'):
            specifiers.append(self.parseImportSpecifier())
            if not self.match('}'):
                self.expect(',')
        self.expect('}')

        return specifiers

    # import <foo> ...
    def parseImportDefaultSpecifier(self):
        node = self.createNode()
        local = self.parseIdentifierName()
        return self.finalize(node, Node.ImportDefaultSpecifier(local))

    # import <* as foo> ...
    def parseImportNamespaceSpecifier(self):
        node = self.createNode()

        self.expect('*')
        if not self.matchContextualKeyword('as'):
            self.throwError(Messages.NoAsAfterImportNamespace)
        self.nextToken()
        local = self.parseIdentifierName()

        return self.finalize(node, Node.ImportNamespaceSpecifier(local))

    def parseImportDeclaration(self):
        if self.context.inFunctionBody:
            self.throwError(Messages.IllegalImportDeclaration)

        node = self.createNode()
        self.expectKeyword('import')

        specifiers = []
        if self.lookahead.type is Token.StringLiteral:
            # import 'foo'
            src = self.parseModuleSpecifier()
        else:
            if self.match('{'):
                # import {bar
                specifiers.extend(self.parseNamedImports())
            elif self.match('*'):
                # import * as foo
                specifiers.append(self.parseImportNamespaceSpecifier())
            elif self.isIdentifierName(self.lookahead) and not self.matchKeyword('default'):
                # import foo
                specifiers.append(self.parseImportDefaultSpecifier())
                if self.match(','):
                    self.nextToken()
                    if self.match('*'):
                        # import foo, * as foo
                        specifiers.append(self.parseImportNamespaceSpecifier())
                    elif self.match('{'):
                        # import foo, {bar
                        specifiers.extend(self.parseNamedImports())
                    else:
                        self.throwUnexpectedToken(self.lookahead)
            else:
                self.throwUnexpectedToken(self.nextToken())

            if not self.matchContextualKeyword('from'):
                message = Messages.UnexpectedToken if self.lookahead.value else Messages.MissingFromClause
                self.throwError(message, self.lookahead.value)
            self.nextToken()
            src = self.parseModuleSpecifier()
        self.consumeSemicolon()

        return self.finalize(node, Node.ImportDeclaration(specifiers, src))

    # https://tc39.github.io/ecma262/#sec-exports

    def parseExportSpecifier(self):
        node = self.createNode()

        local = self.parseIdentifierName()
        exported = local
        if self.matchContextualKeyword('as'):
            self.nextToken()
            exported = self.parseIdentifierName()

        return self.finalize(node, Node.ExportSpecifier(local, exported))

    def parseExportDefaultSpecifier(self):
        node = self.createNode()
        local = self.parseIdentifierName()
        return self.finalize(node, Node.ExportDefaultSpecifier(local))

    def parseExportDeclaration(self):
        if self.context.inFunctionBody:
            self.throwError(Messages.IllegalExportDeclaration)

        node = self.createNode()
        self.expectKeyword('export')

        if self.matchKeyword('default'):
            # export default ...
            self.nextToken()
            if self.matchKeyword('function'):
                # export default function foo (:
                # export default function (:
                declaration = self.parseFunctionDeclaration(True)
                exportDeclaration = self.finalize(node, Node.ExportDefaultDeclaration(declaration))
            elif self.matchKeyword('class'):
                # export default class foo {
                declaration = self.parseClassDeclaration(True)
                exportDeclaration = self.finalize(node, Node.ExportDefaultDeclaration(declaration))
            elif self.matchContextualKeyword('async'):
                # export default async function f (:
                # export default async function (:
                # export default async x => x
                declaration = self.parseFunctionDeclaration(True) if self.matchAsyncFunction() else self.parseAssignmentExpression()
                exportDeclaration = self.finalize(node, Node.ExportDefaultDeclaration(declaration))
            else:
                if self.matchContextualKeyword('from'):
                    self.throwError(Messages.UnexpectedToken, self.lookahead.value)
                # export default {}
                # export default []
                # export default (1 + 2)
                if self.match('{'):
                    declaration = self.parseObjectInitializer()
                elif self.match('['):
                    declaration = self.parseArrayInitializer()
                else:
                    declaration = self.parseAssignmentExpression()
                self.consumeSemicolon()
                exportDeclaration = self.finalize(node, Node.ExportDefaultDeclaration(declaration))

        elif self.match('*'):
            # export * from 'foo'
            self.nextToken()
            if not self.matchContextualKeyword('from'):
                message = Messages.UnexpectedToken if self.lookahead.value else Messages.MissingFromClause
                self.throwError(message, self.lookahead.value)
            self.nextToken()
            src = self.parseModuleSpecifier()
            self.consumeSemicolon()
            exportDeclaration = self.finalize(node, Node.ExportAllDeclaration(src))

        elif self.lookahead.type is Token.Keyword:
            # export var f = 1
            value = self.lookahead.value
            if value in (
                'let',
                'const',
            ):
                declaration = self.parseLexicalDeclaration(Params(inFor=False))
            elif value in (
                'var',
                'class',
                'function',
            ):
                declaration = self.parseStatementListItem()
            else:
                self.throwUnexpectedToken(self.lookahead)
            exportDeclaration = self.finalize(node, Node.ExportNamedDeclaration(declaration, [], None))

        elif self.matchAsyncFunction():
            declaration = self.parseFunctionDeclaration()
            exportDeclaration = self.finalize(node, Node.ExportNamedDeclaration(declaration, [], None))

        else:
            specifiers = []
            source = None
            isExportFromIdentifier = False

            expectSpecifiers = True
            if self.lookahead.type is Token.Identifier:
                specifiers.append(self.parseExportDefaultSpecifier())
                if self.match(','):
                    self.nextToken()
                else:
                    expectSpecifiers = False

            if expectSpecifiers:
                self.expect('{')
                while not self.match('}'):
                    isExportFromIdentifier = isExportFromIdentifier or self.matchKeyword('default')
                    specifiers.append(self.parseExportSpecifier())
                    if not self.match('}'):
                        self.expect(',')
                self.expect('}')

            if self.matchContextualKeyword('from'):
                # export {default} from 'foo'
                # export {foo} from 'foo'
                self.nextToken()
                source = self.parseModuleSpecifier()
                self.consumeSemicolon()
            elif isExportFromIdentifier:
                # export {default}; # missing fromClause
                message = Messages.UnexpectedToken if self.lookahead.value else Messages.MissingFromClause
                self.throwError(message, self.lookahead.value)
            else:
                # export {foo}
                self.consumeSemicolon()
            exportDeclaration = self.finalize(node, Node.ExportNamedDeclaration(None, specifiers, source))

        return exportDeclaration