summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp
blob: f5b16eef540bb490e571e3bd53dd2d042016fbf8 (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
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
/*
 * Copyright (c) 2018-2022, Andreas Kling <kling@serenityos.org>
 * Copyright (c) 2020-2021, the SerenityOS developers.
 * Copyright (c) 2021-2023, Sam Atkins <atkinssj@serenityos.org>
 * Copyright (c) 2021, Tobias Christiansen <tobyase@serenityos.org>
 * Copyright (c) 2022, MacDue <macdue@dueutil.tech>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <AK/CharacterTypes.h>
#include <AK/Debug.h>
#include <AK/GenericLexer.h>
#include <AK/SourceLocation.h>
#include <LibWeb/Bindings/MainThreadVM.h>
#include <LibWeb/CSS/CSSFontFaceRule.h>
#include <LibWeb/CSS/CSSImportRule.h>
#include <LibWeb/CSS/CSSMediaRule.h>
#include <LibWeb/CSS/CSSStyleDeclaration.h>
#include <LibWeb/CSS/CSSStyleRule.h>
#include <LibWeb/CSS/CSSStyleSheet.h>
#include <LibWeb/CSS/CSSSupportsRule.h>
#include <LibWeb/CSS/MediaList.h>
#include <LibWeb/CSS/Parser/Block.h>
#include <LibWeb/CSS/Parser/ComponentValue.h>
#include <LibWeb/CSS/Parser/DeclarationOrAtRule.h>
#include <LibWeb/CSS/Parser/Function.h>
#include <LibWeb/CSS/Parser/Parser.h>
#include <LibWeb/CSS/Parser/Rule.h>
#include <LibWeb/CSS/Selector.h>
#include <LibWeb/CSS/StyleValue.h>
#include <LibWeb/CSS/StyleValues/AngleStyleValue.h>
#include <LibWeb/CSS/StyleValues/BackgroundRepeatStyleValue.h>
#include <LibWeb/CSS/StyleValues/BackgroundSizeStyleValue.h>
#include <LibWeb/CSS/StyleValues/BackgroundStyleValue.h>
#include <LibWeb/CSS/StyleValues/BorderRadiusShorthandStyleValue.h>
#include <LibWeb/CSS/StyleValues/BorderRadiusStyleValue.h>
#include <LibWeb/CSS/StyleValues/BorderStyleValue.h>
#include <LibWeb/CSS/StyleValues/ColorStyleValue.h>
#include <LibWeb/CSS/StyleValues/ConicGradientStyleValue.h>
#include <LibWeb/CSS/StyleValues/ContentStyleValue.h>
#include <LibWeb/CSS/StyleValues/FilterValueListStyleValue.h>
#include <LibWeb/CSS/StyleValues/FlexFlowStyleValue.h>
#include <LibWeb/CSS/StyleValues/FlexStyleValue.h>
#include <LibWeb/CSS/StyleValues/FontStyleValue.h>
#include <LibWeb/CSS/StyleValues/FrequencyStyleValue.h>
#include <LibWeb/CSS/StyleValues/GridAreaShorthandStyleValue.h>
#include <LibWeb/CSS/StyleValues/GridTemplateAreaStyleValue.h>
#include <LibWeb/CSS/StyleValues/GridTrackPlacementShorthandStyleValue.h>
#include <LibWeb/CSS/StyleValues/GridTrackPlacementStyleValue.h>
#include <LibWeb/CSS/StyleValues/GridTrackSizeStyleValue.h>
#include <LibWeb/CSS/StyleValues/IdentifierStyleValue.h>
#include <LibWeb/CSS/StyleValues/ImageStyleValue.h>
#include <LibWeb/CSS/StyleValues/InheritStyleValue.h>
#include <LibWeb/CSS/StyleValues/InitialStyleValue.h>
#include <LibWeb/CSS/StyleValues/LengthStyleValue.h>
#include <LibWeb/CSS/StyleValues/LinearGradientStyleValue.h>
#include <LibWeb/CSS/StyleValues/ListStyleStyleValue.h>
#include <LibWeb/CSS/StyleValues/NumericStyleValue.h>
#include <LibWeb/CSS/StyleValues/OverflowStyleValue.h>
#include <LibWeb/CSS/StyleValues/PercentageStyleValue.h>
#include <LibWeb/CSS/StyleValues/PositionStyleValue.h>
#include <LibWeb/CSS/StyleValues/RadialGradientStyleValue.h>
#include <LibWeb/CSS/StyleValues/ResolutionStyleValue.h>
#include <LibWeb/CSS/StyleValues/ShadowStyleValue.h>
#include <LibWeb/CSS/StyleValues/StringStyleValue.h>
#include <LibWeb/CSS/StyleValues/TextDecorationStyleValue.h>
#include <LibWeb/CSS/StyleValues/TimeStyleValue.h>
#include <LibWeb/CSS/StyleValues/TransformationStyleValue.h>
#include <LibWeb/CSS/StyleValues/UnresolvedStyleValue.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/Dump.h>
#include <LibWeb/Infra/Strings.h>

static void log_parse_error(SourceLocation const& location = SourceLocation::current())
{
    dbgln_if(CSS_PARSER_DEBUG, "Parse error (CSS) {}", location);
}

namespace Web::CSS::Parser {

ParsingContext::ParsingContext(JS::Realm& realm)
    : m_realm(realm)
{
}

ParsingContext::ParsingContext(DOM::Document const& document, AK::URL url)
    : m_realm(const_cast<JS::Realm&>(document.realm()))
    , m_document(&document)
    , m_url(move(url))
{
}

ParsingContext::ParsingContext(DOM::Document const& document)
    : m_realm(const_cast<JS::Realm&>(document.realm()))
    , m_document(&document)
    , m_url(document.url())
{
}

ParsingContext::ParsingContext(DOM::ParentNode& parent_node)
    : m_realm(parent_node.realm())
    , m_document(&parent_node.document())
    , m_url(parent_node.document().url())
{
}

bool ParsingContext::in_quirks_mode() const
{
    return m_document ? m_document->in_quirks_mode() : false;
}

// https://www.w3.org/TR/css-values-4/#relative-urls
AK::URL ParsingContext::complete_url(StringView relative_url) const
{
    return m_url.complete_url(relative_url);
}

ErrorOr<Parser> Parser::create(ParsingContext const& context, StringView input, StringView encoding)
{
    auto tokens = TRY(Tokenizer::tokenize(input, encoding));
    return Parser { context, move(tokens) };
}

Parser::Parser(ParsingContext const& context, Vector<Token> tokens)
    : m_context(context)
    , m_tokens(move(tokens))
    , m_token_stream(m_tokens)
{
}

Parser::Parser(Parser&& other)
    : m_context(other.m_context)
    , m_tokens(move(other.m_tokens))
    , m_token_stream(m_tokens)
{
    // Moving the TokenStream directly from `other` would break it, because TokenStream holds
    // a reference to the Vector<Token>, so it would be pointing at the old Parser's tokens.
    // So instead, we create a new TokenStream from this Parser's tokens, and then tell it to
    // copy the other TokenStream's state. This is quite hacky.
    m_token_stream.copy_state({}, other.m_token_stream);
}

// 5.3.3. Parse a stylesheet
// https://www.w3.org/TR/css-syntax-3/#parse-stylesheet
template<typename T>
Parser::ParsedStyleSheet Parser::parse_a_stylesheet(TokenStream<T>& tokens, Optional<AK::URL> location)
{
    // To parse a stylesheet from an input given an optional url location:

    // 1. If input is a byte stream for stylesheet, decode bytes from input, and set input to the result.
    // 2. Normalize input, and set input to the result.
    // NOTE: These are done automatically when creating the Parser.

    // 3. Create a new stylesheet, with its location set to location (or null, if location was not passed).
    ParsedStyleSheet style_sheet;
    style_sheet.location = move(location);

    // 4. Consume a list of rules from input, with the top-level flag set, and set the stylesheet’s value to the result.
    style_sheet.rules = consume_a_list_of_rules(tokens, TopLevel::Yes);

    // 5. Return the stylesheet.
    return style_sheet;
}

// https://www.w3.org/TR/css-syntax-3/#parse-a-css-stylesheet
CSSStyleSheet* Parser::parse_as_css_stylesheet(Optional<AK::URL> location)
{
    // To parse a CSS stylesheet, first parse a stylesheet.
    auto style_sheet = parse_a_stylesheet(m_token_stream, {});

    // Interpret all of the resulting top-level qualified rules as style rules, defined below.
    JS::MarkedVector<CSSRule*> rules(m_context.realm().heap());
    for (auto& raw_rule : style_sheet.rules) {
        auto* rule = convert_to_rule(raw_rule);
        // If any style rule is invalid, or any at-rule is not recognized or is invalid according to its grammar or context, it’s a parse error. Discard that rule.
        if (rule)
            rules.append(rule);
    }

    auto rule_list = CSSRuleList::create(m_context.realm(), rules).release_value_but_fixme_should_propagate_errors();
    auto media_list = MediaList::create(m_context.realm(), {}).release_value_but_fixme_should_propagate_errors();
    return CSSStyleSheet::create(m_context.realm(), rule_list, media_list, move(location)).release_value_but_fixme_should_propagate_errors();
}

Optional<SelectorList> Parser::parse_as_selector(SelectorParsingMode parsing_mode)
{
    auto selector_list = parse_a_selector_list(m_token_stream, SelectorType::Standalone, parsing_mode);
    if (!selector_list.is_error())
        return selector_list.release_value();

    return {};
}

Optional<SelectorList> Parser::parse_as_relative_selector(SelectorParsingMode parsing_mode)
{
    auto selector_list = parse_a_selector_list(m_token_stream, SelectorType::Relative, parsing_mode);
    if (!selector_list.is_error())
        return selector_list.release_value();

    return {};
}

template<typename T>
Parser::ParseErrorOr<SelectorList> Parser::parse_a_selector_list(TokenStream<T>& tokens, SelectorType mode, SelectorParsingMode parsing_mode)
{
    auto comma_separated_lists = parse_a_comma_separated_list_of_component_values(tokens);

    Vector<NonnullRefPtr<Selector>> selectors;
    for (auto& selector_parts : comma_separated_lists) {
        auto stream = TokenStream(selector_parts);
        auto selector = parse_complex_selector(stream, mode);
        if (selector.is_error()) {
            if (parsing_mode == SelectorParsingMode::Forgiving)
                continue;
            return selector.error();
        }
        selectors.append(selector.release_value());
    }

    if (selectors.is_empty() && parsing_mode != SelectorParsingMode::Forgiving)
        return ParseError::SyntaxError;

    return selectors;
}

Parser::ParseErrorOr<NonnullRefPtr<Selector>> Parser::parse_complex_selector(TokenStream<ComponentValue>& tokens, SelectorType mode)
{
    Vector<Selector::CompoundSelector> compound_selectors;

    auto first_selector = TRY(parse_compound_selector(tokens));
    if (!first_selector.has_value())
        return ParseError::SyntaxError;

    if (mode == SelectorType::Standalone) {
        if (first_selector->combinator != Selector::Combinator::Descendant)
            return ParseError::SyntaxError;
        first_selector->combinator = Selector::Combinator::None;
    }
    compound_selectors.append(first_selector.release_value());

    while (tokens.has_next_token()) {
        auto compound_selector = TRY(parse_compound_selector(tokens));
        if (!compound_selector.has_value())
            break;
        compound_selectors.append(compound_selector.release_value());
    }

    if (compound_selectors.is_empty())
        return ParseError::SyntaxError;

    return Selector::create(move(compound_selectors));
}

Parser::ParseErrorOr<Optional<Selector::CompoundSelector>> Parser::parse_compound_selector(TokenStream<ComponentValue>& tokens)
{
    tokens.skip_whitespace();

    auto combinator = parse_selector_combinator(tokens).value_or(Selector::Combinator::Descendant);

    tokens.skip_whitespace();

    Vector<Selector::SimpleSelector> simple_selectors;

    while (tokens.has_next_token()) {
        auto component = TRY(parse_simple_selector(tokens));
        if (!component.has_value())
            break;
        simple_selectors.append(component.release_value());
    }

    if (simple_selectors.is_empty())
        return Optional<Selector::CompoundSelector> {};

    return Selector::CompoundSelector { combinator, move(simple_selectors) };
}

Optional<Selector::Combinator> Parser::parse_selector_combinator(TokenStream<ComponentValue>& tokens)
{
    auto const& current_value = tokens.next_token();
    if (current_value.is(Token::Type::Delim)) {
        switch (current_value.token().delim()) {
        case '>':
            return Selector::Combinator::ImmediateChild;
        case '+':
            return Selector::Combinator::NextSibling;
        case '~':
            return Selector::Combinator::SubsequentSibling;
        case '|': {
            auto const& next = tokens.peek_token();
            if (next.is(Token::Type::EndOfFile))
                return {};

            if (next.is(Token::Type::Delim) && next.token().delim() == '|') {
                tokens.next_token();
                return Selector::Combinator::Column;
            }
        }
        }
    }

    tokens.reconsume_current_input_token();
    return {};
}

Parser::ParseErrorOr<Selector::SimpleSelector> Parser::parse_attribute_simple_selector(ComponentValue const& first_value)
{
    auto attribute_tokens = TokenStream { first_value.block().values() };

    attribute_tokens.skip_whitespace();

    if (!attribute_tokens.has_next_token()) {
        dbgln_if(CSS_PARSER_DEBUG, "CSS attribute selector is empty!");
        return ParseError::SyntaxError;
    }

    // FIXME: Handle namespace prefix for attribute name.
    auto const& attribute_part = attribute_tokens.next_token();
    if (!attribute_part.is(Token::Type::Ident)) {
        dbgln_if(CSS_PARSER_DEBUG, "Expected ident for attribute name, got: '{}'", attribute_part.to_debug_string());
        return ParseError::SyntaxError;
    }

    Selector::SimpleSelector simple_selector {
        .type = Selector::SimpleSelector::Type::Attribute,
        .value = Selector::SimpleSelector::Attribute {
            .match_type = Selector::SimpleSelector::Attribute::MatchType::HasAttribute,
            // FIXME: Case-sensitivity is defined by the document language.
            // HTML is insensitive with attribute names, and our code generally assumes
            // they are converted to lowercase, so we do that here too. If we want to be
            // correct with XML later, we'll need to keep the original case and then do
            // a case-insensitive compare later.
            .name = FlyString::from_deprecated_fly_string(attribute_part.token().ident().to_lowercase_string()).release_value_but_fixme_should_propagate_errors(),
            .case_type = Selector::SimpleSelector::Attribute::CaseType::DefaultMatch,
        }
    };

    attribute_tokens.skip_whitespace();
    if (!attribute_tokens.has_next_token())
        return simple_selector;

    auto const& delim_part = attribute_tokens.next_token();
    if (!delim_part.is(Token::Type::Delim)) {
        dbgln_if(CSS_PARSER_DEBUG, "Expected a delim for attribute comparison, got: '{}'", delim_part.to_debug_string());
        return ParseError::SyntaxError;
    }

    if (delim_part.token().delim() == '=') {
        simple_selector.attribute().match_type = Selector::SimpleSelector::Attribute::MatchType::ExactValueMatch;
    } else {
        if (!attribute_tokens.has_next_token()) {
            dbgln_if(CSS_PARSER_DEBUG, "Attribute selector ended part way through a match type.");
            return ParseError::SyntaxError;
        }

        auto const& delim_second_part = attribute_tokens.next_token();
        if (!(delim_second_part.is(Token::Type::Delim) && delim_second_part.token().delim() == '=')) {
            dbgln_if(CSS_PARSER_DEBUG, "Expected a double delim for attribute comparison, got: '{}{}'", delim_part.to_debug_string(), delim_second_part.to_debug_string());
            return ParseError::SyntaxError;
        }
        switch (delim_part.token().delim()) {
        case '~':
            simple_selector.attribute().match_type = Selector::SimpleSelector::Attribute::MatchType::ContainsWord;
            break;
        case '*':
            simple_selector.attribute().match_type = Selector::SimpleSelector::Attribute::MatchType::ContainsString;
            break;
        case '|':
            simple_selector.attribute().match_type = Selector::SimpleSelector::Attribute::MatchType::StartsWithSegment;
            break;
        case '^':
            simple_selector.attribute().match_type = Selector::SimpleSelector::Attribute::MatchType::StartsWithString;
            break;
        case '$':
            simple_selector.attribute().match_type = Selector::SimpleSelector::Attribute::MatchType::EndsWithString;
            break;
        default:
            attribute_tokens.reconsume_current_input_token();
        }
    }

    attribute_tokens.skip_whitespace();
    if (!attribute_tokens.has_next_token()) {
        dbgln_if(CSS_PARSER_DEBUG, "Attribute selector ended without a value to match.");
        return ParseError::SyntaxError;
    }

    auto const& value_part = attribute_tokens.next_token();
    if (!value_part.is(Token::Type::Ident) && !value_part.is(Token::Type::String)) {
        dbgln_if(CSS_PARSER_DEBUG, "Expected a string or ident for the value to match attribute against, got: '{}'", value_part.to_debug_string());
        return ParseError::SyntaxError;
    }
    auto value_string_view = value_part.token().is(Token::Type::Ident) ? value_part.token().ident() : value_part.token().string();
    simple_selector.attribute().value = String::from_utf8(value_string_view).release_value_but_fixme_should_propagate_errors();

    attribute_tokens.skip_whitespace();
    // Handle case-sensitivity suffixes. https://www.w3.org/TR/selectors-4/#attribute-case
    if (attribute_tokens.has_next_token()) {
        auto const& case_sensitivity_part = attribute_tokens.next_token();
        if (case_sensitivity_part.is(Token::Type::Ident)) {
            auto case_sensitivity = case_sensitivity_part.token().ident();
            if (case_sensitivity.equals_ignoring_ascii_case("i"sv)) {
                simple_selector.attribute().case_type = Selector::SimpleSelector::Attribute::CaseType::CaseInsensitiveMatch;
            } else if (case_sensitivity.equals_ignoring_ascii_case("s"sv)) {
                simple_selector.attribute().case_type = Selector::SimpleSelector::Attribute::CaseType::CaseSensitiveMatch;
            } else {
                dbgln_if(CSS_PARSER_DEBUG, "Expected a \"i\" or \"s\" attribute selector case sensitivity identifier, got: '{}'", case_sensitivity_part.to_debug_string());
                return ParseError::SyntaxError;
            }
        } else {
            dbgln_if(CSS_PARSER_DEBUG, "Expected an attribute selector case sensitivity identifier, got: '{}'", case_sensitivity_part.to_debug_string());
            return ParseError::SyntaxError;
        }
    }

    if (attribute_tokens.has_next_token()) {
        dbgln_if(CSS_PARSER_DEBUG, "Was not expecting anything else inside attribute selector.");
        return ParseError::SyntaxError;
    }

    return simple_selector;
}

Parser::ParseErrorOr<Selector::SimpleSelector> Parser::parse_pseudo_simple_selector(TokenStream<ComponentValue>& tokens)
{
    auto peek_token_ends_selector = [&]() -> bool {
        auto const& value = tokens.peek_token();
        return (value.is(Token::Type::EndOfFile) || value.is(Token::Type::Whitespace) || value.is(Token::Type::Comma));
    };

    if (peek_token_ends_selector())
        return ParseError::SyntaxError;

    bool is_pseudo = false;
    if (tokens.peek_token().is(Token::Type::Colon)) {
        is_pseudo = true;
        tokens.next_token();
        if (peek_token_ends_selector())
            return ParseError::SyntaxError;
    }

    if (is_pseudo) {
        auto const& name_token = tokens.next_token();
        if (!name_token.is(Token::Type::Ident)) {
            dbgln_if(CSS_PARSER_DEBUG, "Expected an ident for pseudo-element, got: '{}'", name_token.to_debug_string());
            return ParseError::SyntaxError;
        }

        auto pseudo_name = name_token.token().ident();
        auto pseudo_element = pseudo_element_from_string(pseudo_name);

        // Note: We allow the "ignored" -webkit prefix here for -webkit-progress-bar/-webkit-progress-bar
        if (!pseudo_element.has_value() && has_ignored_vendor_prefix(pseudo_name))
            return ParseError::IncludesIgnoredVendorPrefix;

        if (!pseudo_element.has_value()) {
            dbgln_if(CSS_PARSER_DEBUG, "Unrecognized pseudo-element: '::{}'", pseudo_name);
            return ParseError::SyntaxError;
        }

        return Selector::SimpleSelector {
            .type = Selector::SimpleSelector::Type::PseudoElement,
            .value = pseudo_element.value()
        };
    }

    if (peek_token_ends_selector())
        return ParseError::SyntaxError;

    auto const& pseudo_class_token = tokens.next_token();

    if (pseudo_class_token.is(Token::Type::Ident)) {
        auto pseudo_name = pseudo_class_token.token().ident();
        if (has_ignored_vendor_prefix(pseudo_name))
            return ParseError::IncludesIgnoredVendorPrefix;

        auto make_pseudo_class_selector = [](auto pseudo_class) {
            return Selector::SimpleSelector {
                .type = Selector::SimpleSelector::Type::PseudoClass,
                .value = Selector::SimpleSelector::PseudoClass {
                    .type = pseudo_class }
            };
        };

        if (pseudo_name.equals_ignoring_ascii_case("active"sv))
            return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::Active);
        if (pseudo_name.equals_ignoring_ascii_case("checked"sv))
            return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::Checked);
        if (pseudo_name.equals_ignoring_ascii_case("indeterminate"sv))
            return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::Indeterminate);
        if (pseudo_name.equals_ignoring_ascii_case("disabled"sv))
            return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::Disabled);
        if (pseudo_name.equals_ignoring_ascii_case("empty"sv))
            return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::Empty);
        if (pseudo_name.equals_ignoring_ascii_case("enabled"sv))
            return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::Enabled);
        if (pseudo_name.equals_ignoring_ascii_case("first-child"sv))
            return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::FirstChild);
        if (pseudo_name.equals_ignoring_ascii_case("first-of-type"sv))
            return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::FirstOfType);
        if (pseudo_name.equals_ignoring_ascii_case("focus"sv))
            return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::Focus);
        if (pseudo_name.equals_ignoring_ascii_case("focus-within"sv))
            return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::FocusWithin);
        if (pseudo_name.equals_ignoring_ascii_case("hover"sv))
            return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::Hover);
        if (pseudo_name.equals_ignoring_ascii_case("last-child"sv))
            return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::LastChild);
        if (pseudo_name.equals_ignoring_ascii_case("last-of-type"sv))
            return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::LastOfType);
        if (pseudo_name.equals_ignoring_ascii_case("link"sv))
            return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::Link);
        if (pseudo_name.equals_ignoring_ascii_case("only-child"sv))
            return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::OnlyChild);
        if (pseudo_name.equals_ignoring_ascii_case("only-of-type"sv))
            return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::OnlyOfType);
        if (pseudo_name.equals_ignoring_ascii_case("root"sv))
            return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::Root);
        if (pseudo_name.equals_ignoring_ascii_case("visited"sv))
            return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::Visited);
        if (pseudo_name.equals_ignoring_ascii_case("scope"sv))
            return make_pseudo_class_selector(Selector::SimpleSelector::PseudoClass::Type::Scope);

        // Single-colon syntax allowed for ::after, ::before, ::first-letter and ::first-line for compatibility.
        // https://www.w3.org/TR/selectors/#pseudo-element-syntax
        if (auto pseudo_element = pseudo_element_from_string(pseudo_name); pseudo_element.has_value()) {
            switch (pseudo_element.value()) {
            case Selector::PseudoElement::After:
            case Selector::PseudoElement::Before:
            case Selector::PseudoElement::FirstLetter:
            case Selector::PseudoElement::FirstLine:
                return Selector::SimpleSelector {
                    .type = Selector::SimpleSelector::Type::PseudoElement,
                    .value = pseudo_element.value()
                };
            default:
                break;
            }
        }

        dbgln_if(CSS_PARSER_DEBUG, "Unrecognized pseudo-class: ':{}'", pseudo_name);
        return ParseError::SyntaxError;
    }

    if (pseudo_class_token.is_function()) {
        auto parse_nth_child_selector = [this](auto pseudo_class, Vector<ComponentValue> const& function_values, bool allow_of = false) -> ParseErrorOr<Selector::SimpleSelector> {
            auto tokens = TokenStream<ComponentValue>(function_values);
            auto nth_child_pattern = parse_a_n_plus_b_pattern(tokens);
            if (!nth_child_pattern.has_value()) {
                dbgln_if(CSS_PARSER_DEBUG, "!!! Invalid An+B format for {}", pseudo_class_name(pseudo_class));
                return ParseError::SyntaxError;
            }

            tokens.skip_whitespace();
            if (!tokens.has_next_token()) {
                return Selector::SimpleSelector {
                    .type = Selector::SimpleSelector::Type::PseudoClass,
                    .value = Selector::SimpleSelector::PseudoClass {
                        .type = pseudo_class,
                        .nth_child_pattern = nth_child_pattern.release_value() }
                };
            }

            if (!allow_of)
                return ParseError::SyntaxError;

            // Parse the `of <selector-list>` syntax
            auto const& maybe_of = tokens.next_token();
            if (!(maybe_of.is(Token::Type::Ident) && maybe_of.token().ident().equals_ignoring_ascii_case("of"sv)))
                return ParseError::SyntaxError;

            tokens.skip_whitespace();
            auto selector_list = TRY(parse_a_selector_list(tokens, SelectorType::Standalone));

            tokens.skip_whitespace();
            if (tokens.has_next_token())
                return ParseError::SyntaxError;

            return Selector::SimpleSelector {
                .type = Selector::SimpleSelector::Type::PseudoClass,
                .value = Selector::SimpleSelector::PseudoClass {
                    .type = pseudo_class,
                    .nth_child_pattern = nth_child_pattern.release_value(),
                    .argument_selector_list = move(selector_list) }
            };
        };

        auto const& pseudo_function = pseudo_class_token.function();
        if (pseudo_function.name().equals_ignoring_ascii_case("is"sv)
            || pseudo_function.name().equals_ignoring_ascii_case("where"sv)) {
            auto function_token_stream = TokenStream(pseudo_function.values());
            // NOTE: Because it's forgiving, even complete garbage will parse OK as an empty selector-list.
            auto argument_selector_list = MUST(parse_a_selector_list(function_token_stream, SelectorType::Standalone, SelectorParsingMode::Forgiving));

            return Selector::SimpleSelector {
                .type = Selector::SimpleSelector::Type::PseudoClass,
                .value = Selector::SimpleSelector::PseudoClass {
                    .type = pseudo_function.name().equals_ignoring_ascii_case("is"sv)
                        ? Selector::SimpleSelector::PseudoClass::Type::Is
                        : Selector::SimpleSelector::PseudoClass::Type::Where,
                    .argument_selector_list = move(argument_selector_list) }
            };
        }
        if (pseudo_function.name().equals_ignoring_ascii_case("not"sv)) {
            auto function_token_stream = TokenStream(pseudo_function.values());
            auto not_selector = TRY(parse_a_selector_list(function_token_stream, SelectorType::Standalone));

            return Selector::SimpleSelector {
                .type = Selector::SimpleSelector::Type::PseudoClass,
                .value = Selector::SimpleSelector::PseudoClass {
                    .type = Selector::SimpleSelector::PseudoClass::Type::Not,
                    .argument_selector_list = move(not_selector) }
            };
        }
        if (pseudo_function.name().equals_ignoring_ascii_case("lang"sv)) {
            if (pseudo_function.values().is_empty()) {
                dbgln_if(CSS_PARSER_DEBUG, "Empty :lang() selector");
                return ParseError::SyntaxError;
            }
            // FIXME: Support multiple, comma-separated, language ranges.
            Vector<FlyString> languages;
            languages.append(pseudo_function.values().first().token().to_string().release_value_but_fixme_should_propagate_errors());
            return Selector::SimpleSelector {
                .type = Selector::SimpleSelector::Type::PseudoClass,
                .value = Selector::SimpleSelector::PseudoClass {
                    .type = Selector::SimpleSelector::PseudoClass::Type::Lang,
                    .languages = move(languages) }
            };
        }
        if (pseudo_function.name().equals_ignoring_ascii_case("nth-child"sv))
            return parse_nth_child_selector(Selector::SimpleSelector::PseudoClass::Type::NthChild, pseudo_function.values(), true);
        if (pseudo_function.name().equals_ignoring_ascii_case("nth-last-child"sv))
            return parse_nth_child_selector(Selector::SimpleSelector::PseudoClass::Type::NthLastChild, pseudo_function.values(), true);
        if (pseudo_function.name().equals_ignoring_ascii_case("nth-of-type"sv))
            return parse_nth_child_selector(Selector::SimpleSelector::PseudoClass::Type::NthOfType, pseudo_function.values(), false);
        if (pseudo_function.name().equals_ignoring_ascii_case("nth-last-of-type"sv))
            return parse_nth_child_selector(Selector::SimpleSelector::PseudoClass::Type::NthLastOfType, pseudo_function.values(), false);

        dbgln_if(CSS_PARSER_DEBUG, "Unrecognized pseudo-class function: ':{}'()", pseudo_function.name());
        return ParseError::SyntaxError;
    }
    dbgln_if(CSS_PARSER_DEBUG, "Unexpected Block in pseudo-class name, expected a function or identifier. '{}'", pseudo_class_token.to_debug_string());
    return ParseError::SyntaxError;
}

Parser::ParseErrorOr<Optional<Selector::SimpleSelector>> Parser::parse_simple_selector(TokenStream<ComponentValue>& tokens)
{
    auto peek_token_ends_selector = [&]() -> bool {
        auto const& value = tokens.peek_token();
        return (value.is(Token::Type::EndOfFile) || value.is(Token::Type::Whitespace) || value.is(Token::Type::Comma));
    };

    if (peek_token_ends_selector())
        return Optional<Selector::SimpleSelector> {};

    auto const& first_value = tokens.next_token();

    if (first_value.is(Token::Type::Delim)) {
        u32 delim = first_value.token().delim();
        switch (delim) {
        case '*':
            return Selector::SimpleSelector {
                .type = Selector::SimpleSelector::Type::Universal
            };
        case '.': {
            if (peek_token_ends_selector())
                return ParseError::SyntaxError;

            auto const& class_name_value = tokens.next_token();
            if (!class_name_value.is(Token::Type::Ident)) {
                dbgln_if(CSS_PARSER_DEBUG, "Expected an ident after '.', got: {}", class_name_value.to_debug_string());
                return ParseError::SyntaxError;
            }
            return Selector::SimpleSelector {
                .type = Selector::SimpleSelector::Type::Class,
                .value = Selector::SimpleSelector::Name { FlyString::from_utf8(class_name_value.token().ident()).release_value_but_fixme_should_propagate_errors() }
            };
        }
        case '>':
        case '+':
        case '~':
        case '|':
            // Whitespace is not required between the compound-selector and a combinator.
            // So, if we see a combinator, return that this compound-selector is done, instead of a syntax error.
            tokens.reconsume_current_input_token();
            return Optional<Selector::SimpleSelector> {};
        default:
            dbgln_if(CSS_PARSER_DEBUG, "!!! Invalid simple selector!");
            return ParseError::SyntaxError;
        }
    }

    if (first_value.is(Token::Type::Hash)) {
        if (first_value.token().hash_type() != Token::HashType::Id) {
            dbgln_if(CSS_PARSER_DEBUG, "Selector contains hash token that is not an id: {}", first_value.to_debug_string());
            return ParseError::SyntaxError;
        }
        return Selector::SimpleSelector {
            .type = Selector::SimpleSelector::Type::Id,
            .value = Selector::SimpleSelector::Name { FlyString::from_utf8(first_value.token().hash_value()).release_value_but_fixme_should_propagate_errors() }
        };
    }
    if (first_value.is(Token::Type::Ident)) {
        return Selector::SimpleSelector {
            .type = Selector::SimpleSelector::Type::TagName,
            // FIXME: XML requires case-sensitivity for identifiers, while HTML does not. As such, this should be reworked if XML support is added.
            .value = Selector::SimpleSelector::Name { FlyString::from_utf8(first_value.token().ident().to_lowercase_string()).release_value_but_fixme_should_propagate_errors() }
        };
    }
    if (first_value.is_block() && first_value.block().is_square())
        return TRY(parse_attribute_simple_selector(first_value));

    if (first_value.is(Token::Type::Colon))
        return TRY(parse_pseudo_simple_selector(tokens));

    dbgln_if(CSS_PARSER_DEBUG, "!!! Invalid simple selector!");
    return ParseError::SyntaxError;
}

Vector<NonnullRefPtr<MediaQuery>> Parser::parse_as_media_query_list()
{
    return parse_a_media_query_list(m_token_stream);
}

template<typename T>
Vector<NonnullRefPtr<MediaQuery>> Parser::parse_a_media_query_list(TokenStream<T>& tokens)
{
    // https://www.w3.org/TR/mediaqueries-4/#mq-list

    auto comma_separated_lists = parse_a_comma_separated_list_of_component_values(tokens);

    AK::Vector<NonnullRefPtr<MediaQuery>> media_queries;
    for (auto& media_query_parts : comma_separated_lists) {
        auto stream = TokenStream(media_query_parts);
        media_queries.append(parse_media_query(stream));
    }

    return media_queries;
}

RefPtr<MediaQuery> Parser::parse_as_media_query()
{
    // https://www.w3.org/TR/cssom-1/#parse-a-media-query
    auto media_query_list = parse_as_media_query_list();
    if (media_query_list.is_empty())
        return MediaQuery::create_not_all();
    if (media_query_list.size() == 1)
        return media_query_list.first();
    return nullptr;
}

// `<media-query>`, https://www.w3.org/TR/mediaqueries-4/#typedef-media-query
NonnullRefPtr<MediaQuery> Parser::parse_media_query(TokenStream<ComponentValue>& tokens)
{
    // `<media-query> = <media-condition>
    //                | [ not | only ]? <media-type> [ and <media-condition-without-or> ]?`

    // `[ not | only ]?`, Returns whether to negate the query
    auto parse_initial_modifier = [](auto& tokens) -> Optional<bool> {
        auto transaction = tokens.begin_transaction();
        tokens.skip_whitespace();
        auto& token = tokens.next_token();
        if (!token.is(Token::Type::Ident))
            return {};

        auto ident = token.token().ident();
        if (ident.equals_ignoring_ascii_case("not"sv)) {
            transaction.commit();
            return true;
        }
        if (ident.equals_ignoring_ascii_case("only"sv)) {
            transaction.commit();
            return false;
        }
        return {};
    };

    auto invalid_media_query = [&]() {
        // "A media query that does not match the grammar in the previous section must be replaced by `not all`
        // during parsing." - https://www.w3.org/TR/mediaqueries-5/#error-handling
        if constexpr (CSS_PARSER_DEBUG) {
            dbgln("Invalid media query:");
            tokens.dump_all_tokens();
        }
        return MediaQuery::create_not_all();
    };

    auto media_query = MediaQuery::create();
    tokens.skip_whitespace();

    // `<media-condition>`
    if (auto media_condition = parse_media_condition(tokens, MediaCondition::AllowOr::Yes)) {
        tokens.skip_whitespace();
        if (tokens.has_next_token())
            return invalid_media_query();
        media_query->m_media_condition = move(media_condition);
        return media_query;
    }

    // `[ not | only ]?`
    if (auto modifier = parse_initial_modifier(tokens); modifier.has_value()) {
        media_query->m_negated = modifier.value();
        tokens.skip_whitespace();
    }

    // `<media-type>`
    if (auto media_type = parse_media_type(tokens); media_type.has_value()) {
        media_query->m_media_type = media_type.value();
        tokens.skip_whitespace();
    } else {
        return invalid_media_query();
    }

    if (!tokens.has_next_token())
        return media_query;

    // `[ and <media-condition-without-or> ]?`
    if (auto maybe_and = tokens.next_token(); maybe_and.is(Token::Type::Ident) && maybe_and.token().ident().equals_ignoring_ascii_case("and"sv)) {
        if (auto media_condition = parse_media_condition(tokens, MediaCondition::AllowOr::No)) {
            tokens.skip_whitespace();
            if (tokens.has_next_token())
                return invalid_media_query();
            media_query->m_media_condition = move(media_condition);
            return media_query;
        }
        return invalid_media_query();
    }

    return invalid_media_query();
}

// `<media-condition>`, https://www.w3.org/TR/mediaqueries-4/#typedef-media-condition
// `<media-condition-widthout-or>`, https://www.w3.org/TR/mediaqueries-4/#typedef-media-condition-without-or
// (We distinguish between these two with the `allow_or` parameter.)
OwnPtr<MediaCondition> Parser::parse_media_condition(TokenStream<ComponentValue>& tokens, MediaCondition::AllowOr allow_or)
{
    // `<media-not> | <media-in-parens> [ <media-and>* | <media-or>* ]`
    auto transaction = tokens.begin_transaction();
    tokens.skip_whitespace();

    // `<media-not> = not <media-in-parens>`
    auto parse_media_not = [&](auto& tokens) -> OwnPtr<MediaCondition> {
        auto local_transaction = tokens.begin_transaction();
        tokens.skip_whitespace();

        auto& first_token = tokens.next_token();
        if (first_token.is(Token::Type::Ident) && first_token.token().ident().equals_ignoring_ascii_case("not"sv)) {
            if (auto child_condition = parse_media_condition(tokens, MediaCondition::AllowOr::Yes)) {
                local_transaction.commit();
                return MediaCondition::from_not(child_condition.release_nonnull());
            }
        }

        return {};
    };

    auto parse_media_with_combinator = [&](auto& tokens, StringView combinator) -> OwnPtr<MediaCondition> {
        auto local_transaction = tokens.begin_transaction();
        tokens.skip_whitespace();

        auto& first = tokens.next_token();
        if (first.is(Token::Type::Ident) && first.token().ident().equals_ignoring_ascii_case(combinator)) {
            tokens.skip_whitespace();
            if (auto media_in_parens = parse_media_in_parens(tokens)) {
                local_transaction.commit();
                return media_in_parens;
            }
        }

        return {};
    };

    // `<media-and> = and <media-in-parens>`
    auto parse_media_and = [&](auto& tokens) { return parse_media_with_combinator(tokens, "and"sv); };
    // `<media-or> = or <media-in-parens>`
    auto parse_media_or = [&](auto& tokens) { return parse_media_with_combinator(tokens, "or"sv); };

    // `<media-not>`
    if (auto maybe_media_not = parse_media_not(tokens)) {
        transaction.commit();
        return maybe_media_not.release_nonnull();
    }

    // `<media-in-parens> [ <media-and>* | <media-or>* ]`
    if (auto maybe_media_in_parens = parse_media_in_parens(tokens)) {
        tokens.skip_whitespace();
        // Only `<media-in-parens>`
        if (!tokens.has_next_token()) {
            transaction.commit();
            return maybe_media_in_parens.release_nonnull();
        }

        Vector<NonnullOwnPtr<MediaCondition>> child_conditions;
        child_conditions.append(maybe_media_in_parens.release_nonnull());

        // `<media-and>*`
        if (auto media_and = parse_media_and(tokens)) {
            child_conditions.append(media_and.release_nonnull());

            tokens.skip_whitespace();
            while (tokens.has_next_token()) {
                if (auto next_media_and = parse_media_and(tokens)) {
                    child_conditions.append(next_media_and.release_nonnull());
                    tokens.skip_whitespace();
                    continue;
                }
                // We failed - invalid syntax!
                return {};
            }

            transaction.commit();
            return MediaCondition::from_and_list(move(child_conditions));
        }

        // `<media-or>*`
        if (allow_or == MediaCondition::AllowOr::Yes) {
            if (auto media_or = parse_media_or(tokens)) {
                child_conditions.append(media_or.release_nonnull());

                tokens.skip_whitespace();
                while (tokens.has_next_token()) {
                    if (auto next_media_or = parse_media_or(tokens)) {
                        child_conditions.append(next_media_or.release_nonnull());
                        tokens.skip_whitespace();
                        continue;
                    }
                    // We failed - invalid syntax!
                    return {};
                }

                transaction.commit();
                return MediaCondition::from_or_list(move(child_conditions));
            }
        }
    }

    return {};
}

// `<media-feature>`, https://www.w3.org/TR/mediaqueries-4/#typedef-media-feature
Optional<MediaFeature> Parser::parse_media_feature(TokenStream<ComponentValue>& tokens)
{
    // `[ <mf-plain> | <mf-boolean> | <mf-range> ]`
    tokens.skip_whitespace();

    // `<mf-name> = <ident>`
    struct MediaFeatureName {
        enum Type {
            Normal,
            Min,
            Max
        } type;
        MediaFeatureID id;
    };
    auto parse_mf_name = [](auto& tokens, bool allow_min_max_prefix) -> Optional<MediaFeatureName> {
        auto transaction = tokens.begin_transaction();
        auto& token = tokens.next_token();
        if (token.is(Token::Type::Ident)) {
            auto name = token.token().ident();
            if (auto id = media_feature_id_from_string(name); id.has_value()) {
                transaction.commit();
                return MediaFeatureName { MediaFeatureName::Type::Normal, id.value() };
            }

            if (allow_min_max_prefix && (name.starts_with("min-"sv, CaseSensitivity::CaseInsensitive) || name.starts_with("max-"sv, CaseSensitivity::CaseInsensitive))) {
                auto adjusted_name = name.substring_view(4);
                if (auto id = media_feature_id_from_string(adjusted_name); id.has_value() && media_feature_type_is_range(id.value())) {
                    transaction.commit();
                    return MediaFeatureName {
                        name.starts_with("min-"sv, CaseSensitivity::CaseInsensitive) ? MediaFeatureName::Type::Min : MediaFeatureName::Type::Max,
                        id.value()
                    };
                }
            }
        }
        return {};
    };

    // `<mf-boolean> = <mf-name>`
    auto parse_mf_boolean = [&](auto& tokens) -> Optional<MediaFeature> {
        auto transaction = tokens.begin_transaction();
        tokens.skip_whitespace();

        if (auto maybe_name = parse_mf_name(tokens, false); maybe_name.has_value()) {
            tokens.skip_whitespace();
            if (!tokens.has_next_token()) {
                transaction.commit();
                return MediaFeature::boolean(maybe_name->id);
            }
        }

        return {};
    };

    // `<mf-plain> = <mf-name> : <mf-value>`
    auto parse_mf_plain = [&](auto& tokens) -> Optional<MediaFeature> {
        auto transaction = tokens.begin_transaction();
        tokens.skip_whitespace();

        if (auto maybe_name = parse_mf_name(tokens, true); maybe_name.has_value()) {
            tokens.skip_whitespace();
            if (tokens.next_token().is(Token::Type::Colon)) {
                tokens.skip_whitespace();
                if (auto maybe_value = parse_media_feature_value(maybe_name->id, tokens); maybe_value.has_value()) {
                    tokens.skip_whitespace();
                    if (!tokens.has_next_token()) {
                        transaction.commit();
                        switch (maybe_name->type) {
                        case MediaFeatureName::Type::Normal:
                            return MediaFeature::plain(maybe_name->id, maybe_value.release_value());
                        case MediaFeatureName::Type::Min:
                            return MediaFeature::min(maybe_name->id, maybe_value.release_value());
                        case MediaFeatureName::Type::Max:
                            return MediaFeature::max(maybe_name->id, maybe_value.release_value());
                        }
                        VERIFY_NOT_REACHED();
                    }
                }
            }
        }
        return {};
    };

    // `<mf-lt> = '<' '='?
    //  <mf-gt> = '>' '='?
    //  <mf-eq> = '='
    //  <mf-comparison> = <mf-lt> | <mf-gt> | <mf-eq>`
    auto parse_comparison = [](auto& tokens) -> Optional<MediaFeature::Comparison> {
        auto transaction = tokens.begin_transaction();
        tokens.skip_whitespace();

        auto& first = tokens.next_token();
        if (first.is(Token::Type::Delim)) {
            auto first_delim = first.token().delim();
            if (first_delim == '=') {
                transaction.commit();
                return MediaFeature::Comparison::Equal;
            }
            if (first_delim == '<') {
                auto& second = tokens.peek_token();
                if (second.is(Token::Type::Delim) && second.token().delim() == '=') {
                    tokens.next_token();
                    transaction.commit();
                    return MediaFeature::Comparison::LessThanOrEqual;
                }
                transaction.commit();
                return MediaFeature::Comparison::LessThan;
            }
            if (first_delim == '>') {
                auto& second = tokens.peek_token();
                if (second.is(Token::Type::Delim) && second.token().delim() == '=') {
                    tokens.next_token();
                    transaction.commit();
                    return MediaFeature::Comparison::GreaterThanOrEqual;
                }
                transaction.commit();
                return MediaFeature::Comparison::GreaterThan;
            }
        }

        return {};
    };

    auto flip = [](MediaFeature::Comparison comparison) {
        switch (comparison) {
        case MediaFeature::Comparison::Equal:
            return MediaFeature::Comparison::Equal;
        case MediaFeature::Comparison::LessThan:
            return MediaFeature::Comparison::GreaterThan;
        case MediaFeature::Comparison::LessThanOrEqual:
            return MediaFeature::Comparison::GreaterThanOrEqual;
        case MediaFeature::Comparison::GreaterThan:
            return MediaFeature::Comparison::LessThan;
        case MediaFeature::Comparison::GreaterThanOrEqual:
            return MediaFeature::Comparison::LessThanOrEqual;
        }
        VERIFY_NOT_REACHED();
    };

    auto comparisons_match = [](MediaFeature::Comparison a, MediaFeature::Comparison b) -> bool {
        switch (a) {
        case MediaFeature::Comparison::Equal:
            return b == MediaFeature::Comparison::Equal;
        case MediaFeature::Comparison::LessThan:
        case MediaFeature::Comparison::LessThanOrEqual:
            return b == MediaFeature::Comparison::LessThan || b == MediaFeature::Comparison::LessThanOrEqual;
        case MediaFeature::Comparison::GreaterThan:
        case MediaFeature::Comparison::GreaterThanOrEqual:
            return b == MediaFeature::Comparison::GreaterThan || b == MediaFeature::Comparison::GreaterThanOrEqual;
        }
        VERIFY_NOT_REACHED();
    };

    // `<mf-range> = <mf-name> <mf-comparison> <mf-value>
    //             | <mf-value> <mf-comparison> <mf-name>
    //             | <mf-value> <mf-lt> <mf-name> <mf-lt> <mf-value>
    //             | <mf-value> <mf-gt> <mf-name> <mf-gt> <mf-value>`
    auto parse_mf_range = [&](auto& tokens) -> Optional<MediaFeature> {
        auto transaction = tokens.begin_transaction();
        tokens.skip_whitespace();

        // `<mf-name> <mf-comparison> <mf-value>`
        // NOTE: We have to check for <mf-name> first, since all <mf-name>s will also parse as <mf-value>.
        if (auto maybe_name = parse_mf_name(tokens, false); maybe_name.has_value() && media_feature_type_is_range(maybe_name->id)) {
            tokens.skip_whitespace();
            if (auto maybe_comparison = parse_comparison(tokens); maybe_comparison.has_value()) {
                tokens.skip_whitespace();
                if (auto maybe_value = parse_media_feature_value(maybe_name->id, tokens); maybe_value.has_value()) {
                    tokens.skip_whitespace();
                    if (!tokens.has_next_token() && !maybe_value->is_ident()) {
                        transaction.commit();
                        return MediaFeature::half_range(maybe_value.release_value(), flip(maybe_comparison.release_value()), maybe_name->id);
                    }
                }
            }
        }

        //  `<mf-value> <mf-comparison> <mf-name>
        // | <mf-value> <mf-lt> <mf-name> <mf-lt> <mf-value>
        // | <mf-value> <mf-gt> <mf-name> <mf-gt> <mf-value>`
        // NOTE: To parse the first value, we need to first find and parse the <mf-name> so we know what value types to parse.
        //       To allow for <mf-value> to be any number of tokens long, we scan forward until we find a comparison, and then
        //       treat the next non-whitespace token as the <mf-name>, which should be correct as long as they don't add a value
        //       type that can include a comparison in it. :^)
        Optional<MediaFeatureName> maybe_name;
        {
            // This transaction is never committed, we just use it to rewind automatically.
            auto temp_transaction = tokens.begin_transaction();
            while (tokens.has_next_token() && !maybe_name.has_value()) {
                if (auto maybe_comparison = parse_comparison(tokens); maybe_comparison.has_value()) {
                    // We found a comparison, so the next non-whitespace token should be the <mf-name>
                    tokens.skip_whitespace();
                    maybe_name = parse_mf_name(tokens, false);
                    break;
                }
                tokens.next_token();
                tokens.skip_whitespace();
            }
        }

        // Now, we can parse the range properly.
        if (maybe_name.has_value() && media_feature_type_is_range(maybe_name->id)) {
            if (auto maybe_left_value = parse_media_feature_value(maybe_name->id, tokens); maybe_left_value.has_value()) {
                tokens.skip_whitespace();
                if (auto maybe_left_comparison = parse_comparison(tokens); maybe_left_comparison.has_value()) {
                    tokens.skip_whitespace();
                    tokens.next_token(); // The <mf-name> which we already parsed above.
                    tokens.skip_whitespace();

                    if (!tokens.has_next_token()) {
                        transaction.commit();
                        return MediaFeature::half_range(maybe_left_value.release_value(), maybe_left_comparison.release_value(), maybe_name->id);
                    }

                    if (auto maybe_right_comparison = parse_comparison(tokens); maybe_right_comparison.has_value()) {
                        tokens.skip_whitespace();
                        if (auto maybe_right_value = parse_media_feature_value(maybe_name->id, tokens); maybe_right_value.has_value()) {
                            tokens.skip_whitespace();
                            // For this to be valid, the following must be true:
                            // - Comparisons must either both be >/>= or both be </<=.
                            // - Neither comparison can be `=`.
                            // - Neither value can be an ident.
                            auto left_comparison = maybe_left_comparison.release_value();
                            auto right_comparison = maybe_right_comparison.release_value();

                            if (!tokens.has_next_token()
                                && comparisons_match(left_comparison, right_comparison)
                                && left_comparison != MediaFeature::Comparison::Equal
                                && !maybe_left_value->is_ident() && !maybe_right_value->is_ident()) {
                                transaction.commit();
                                return MediaFeature::range(maybe_left_value.release_value(), left_comparison, maybe_name->id, right_comparison, maybe_right_value.release_value());
                            }
                        }
                    }
                }
            }
        }

        return {};
    };

    if (auto maybe_mf_boolean = parse_mf_boolean(tokens); maybe_mf_boolean.has_value())
        return maybe_mf_boolean.release_value();

    if (auto maybe_mf_plain = parse_mf_plain(tokens); maybe_mf_plain.has_value())
        return maybe_mf_plain.release_value();

    if (auto maybe_mf_range = parse_mf_range(tokens); maybe_mf_range.has_value())
        return maybe_mf_range.release_value();

    return {};
}

Optional<MediaQuery::MediaType> Parser::parse_media_type(TokenStream<ComponentValue>& tokens)
{
    auto transaction = tokens.begin_transaction();
    tokens.skip_whitespace();
    auto const& token = tokens.next_token();

    if (!token.is(Token::Type::Ident))
        return {};

    transaction.commit();

    auto ident = token.token().ident();
    return media_type_from_string(ident);
}

// `<media-in-parens>`, https://www.w3.org/TR/mediaqueries-4/#typedef-media-in-parens
OwnPtr<MediaCondition> Parser::parse_media_in_parens(TokenStream<ComponentValue>& tokens)
{
    // `<media-in-parens> = ( <media-condition> ) | ( <media-feature> ) | <general-enclosed>`
    auto transaction = tokens.begin_transaction();
    tokens.skip_whitespace();

    // `( <media-condition> ) | ( <media-feature> )`
    auto const& first_token = tokens.peek_token();
    if (first_token.is_block() && first_token.block().is_paren()) {
        TokenStream inner_token_stream { first_token.block().values() };
        if (auto maybe_media_condition = parse_media_condition(inner_token_stream, MediaCondition::AllowOr::Yes)) {
            tokens.next_token();
            transaction.commit();
            return maybe_media_condition.release_nonnull();
        }
        if (auto maybe_media_feature = parse_media_feature(inner_token_stream); maybe_media_feature.has_value()) {
            tokens.next_token();
            transaction.commit();
            return MediaCondition::from_feature(maybe_media_feature.release_value());
        }
    }

    // `<general-enclosed>`
    // FIXME: We should only be taking this branch if the grammar doesn't match the above options.
    //        Currently we take it if the above fail to parse, which is different.
    //        eg, `@media (min-width: 76yaks)` is valid grammar, but does not parse because `yaks` isn't a unit.
    if (auto maybe_general_enclosed = parse_general_enclosed(tokens); maybe_general_enclosed.has_value()) {
        transaction.commit();
        return MediaCondition::from_general_enclosed(maybe_general_enclosed.release_value());
    }

    return {};
}

// `<mf-value>`, https://www.w3.org/TR/mediaqueries-4/#typedef-mf-value
Optional<MediaFeatureValue> Parser::parse_media_feature_value(MediaFeatureID media_feature, TokenStream<ComponentValue>& tokens)
{
    // Identifiers
    if (tokens.peek_token().is(Token::Type::Ident)) {
        auto transaction = tokens.begin_transaction();
        tokens.skip_whitespace();
        auto ident = value_id_from_string(tokens.next_token().token().ident());
        if (ident != ValueID::Invalid && media_feature_accepts_identifier(media_feature, ident)) {
            transaction.commit();
            return MediaFeatureValue(ident);
        }
    }

    // One branch for each member of the MediaFeatureValueType enum:

    // Boolean (<mq-boolean> in the spec: a 1 or 0)
    if (media_feature_accepts_type(media_feature, MediaFeatureValueType::Boolean)) {
        auto transaction = tokens.begin_transaction();
        tokens.skip_whitespace();
        auto const& first = tokens.next_token();
        if (first.is(Token::Type::Number) && first.token().number().is_integer()
            && (first.token().number_value() == 0 || first.token().number_value() == 1)) {
            transaction.commit();
            return MediaFeatureValue(first.token().number_value());
        }
    }

    // Integer
    if (media_feature_accepts_type(media_feature, MediaFeatureValueType::Integer)) {
        auto transaction = tokens.begin_transaction();
        tokens.skip_whitespace();
        auto const& first = tokens.next_token();
        if (first.is(Token::Type::Number) && first.token().number().is_integer()) {
            transaction.commit();
            return MediaFeatureValue(first.token().number_value());
        }
    }

    // Length
    if (media_feature_accepts_type(media_feature, MediaFeatureValueType::Length)) {
        auto transaction = tokens.begin_transaction();
        tokens.skip_whitespace();
        auto const& first = tokens.next_token();
        if (auto length = parse_length(first); length.has_value()) {
            transaction.commit();
            return MediaFeatureValue(length.release_value());
        }
    }

    // Ratio
    if (media_feature_accepts_type(media_feature, MediaFeatureValueType::Ratio)) {
        auto transaction = tokens.begin_transaction();
        tokens.skip_whitespace();
        if (auto ratio = parse_ratio(tokens); ratio.has_value()) {
            transaction.commit();
            return MediaFeatureValue(ratio.release_value());
        }
    }

    // Resolution
    if (media_feature_accepts_type(media_feature, MediaFeatureValueType::Resolution)) {
        auto transaction = tokens.begin_transaction();
        tokens.skip_whitespace();
        auto const& first = tokens.next_token();
        if (auto resolution = parse_dimension(first); resolution.has_value() && resolution->is_resolution()) {
            transaction.commit();
            return MediaFeatureValue(resolution->resolution());
        }
    }

    return {};
}

RefPtr<Supports> Parser::parse_as_supports()
{
    return parse_a_supports(m_token_stream);
}

template<typename T>
RefPtr<Supports> Parser::parse_a_supports(TokenStream<T>& tokens)
{
    auto component_values = parse_a_list_of_component_values(tokens);
    TokenStream<ComponentValue> token_stream { component_values };
    auto maybe_condition = parse_supports_condition(token_stream);
    token_stream.skip_whitespace();
    if (maybe_condition && !token_stream.has_next_token())
        return Supports::create(maybe_condition.release_nonnull());

    return {};
}

OwnPtr<Supports::Condition> Parser::parse_supports_condition(TokenStream<ComponentValue>& tokens)
{
    auto transaction = tokens.begin_transaction();
    tokens.skip_whitespace();

    auto const& peeked_token = tokens.peek_token();
    // `not <supports-in-parens>`
    if (peeked_token.is(Token::Type::Ident) && peeked_token.token().ident().equals_ignoring_ascii_case("not"sv)) {
        tokens.next_token();
        tokens.skip_whitespace();
        auto child = parse_supports_in_parens(tokens);
        if (!child.has_value())
            return {};

        transaction.commit();
        auto condition = make<Supports::Condition>();
        condition->type = Supports::Condition::Type::Not;
        condition->children.append(child.release_value());
        return condition;
    }

    // `  <supports-in-parens> [ and <supports-in-parens> ]*
    //  | <supports-in-parens> [ or <supports-in-parens> ]*`
    Vector<Supports::InParens> children;
    Optional<Supports::Condition::Type> condition_type {};
    auto as_condition_type = [](auto& token) -> Optional<Supports::Condition::Type> {
        if (!token.is(Token::Type::Ident))
            return {};
        auto ident = token.token().ident();
        if (ident.equals_ignoring_ascii_case("and"sv))
            return Supports::Condition::Type::And;
        if (ident.equals_ignoring_ascii_case("or"sv))
            return Supports::Condition::Type::Or;
        return {};
    };

    while (tokens.has_next_token()) {
        if (!children.is_empty()) {
            // Expect `and` or `or` here
            auto maybe_combination = as_condition_type(tokens.next_token());
            if (!maybe_combination.has_value())
                return {};
            if (!condition_type.has_value()) {
                condition_type = maybe_combination.value();
            } else if (maybe_combination != condition_type) {
                return {};
            }
        }

        tokens.skip_whitespace();

        if (auto in_parens = parse_supports_in_parens(tokens); in_parens.has_value()) {
            children.append(in_parens.release_value());
        } else {
            return {};
        }

        tokens.skip_whitespace();
    }

    if (children.is_empty())
        return {};

    transaction.commit();
    auto condition = make<Supports::Condition>();
    condition->type = condition_type.value_or(Supports::Condition::Type::Or);
    condition->children = move(children);
    return condition;
}

Optional<Supports::InParens> Parser::parse_supports_in_parens(TokenStream<ComponentValue>& tokens)
{
    // `( <supports-condition> )`
    auto const& first_token = tokens.peek_token();
    if (first_token.is_block() && first_token.block().is_paren()) {
        auto transaction = tokens.begin_transaction();
        tokens.next_token();
        tokens.skip_whitespace();

        TokenStream child_tokens { first_token.block().values() };
        if (auto condition = parse_supports_condition(child_tokens)) {
            if (child_tokens.has_next_token())
                return {};
            transaction.commit();
            return Supports::InParens {
                .value = { condition.release_nonnull() }
            };
        }
    }

    // `<supports-feature>`
    if (auto feature = parse_supports_feature(tokens); feature.has_value()) {
        return Supports::InParens {
            .value = { feature.release_value() }
        };
    }

    // `<general-enclosed>`
    if (auto general_enclosed = parse_general_enclosed(tokens); general_enclosed.has_value()) {
        return Supports::InParens {
            .value = general_enclosed.release_value()
        };
    }

    return {};
}

Optional<Supports::Feature> Parser::parse_supports_feature(TokenStream<ComponentValue>& tokens)
{
    auto transaction = tokens.begin_transaction();
    tokens.skip_whitespace();
    auto const& first_token = tokens.next_token();

    // `<supports-decl>`
    if (first_token.is_block() && first_token.block().is_paren()) {
        TokenStream block_tokens { first_token.block().values() };
        // FIXME: Parsing and then converting back to a string is weird.
        if (auto declaration = consume_a_declaration(block_tokens); declaration.has_value()) {
            transaction.commit();
            return Supports::Feature {
                Supports::Declaration { declaration->to_string().release_value_but_fixme_should_propagate_errors(), JS::make_handle(m_context.realm()) }
            };
        }
    }

    // `<supports-selector-fn>`
    if (first_token.is_function() && first_token.function().name().equals_ignoring_ascii_case("selector"sv)) {
        // FIXME: Parsing and then converting back to a string is weird.
        StringBuilder builder;
        for (auto const& item : first_token.function().values())
            builder.append(item.to_string().release_value_but_fixme_should_propagate_errors());
        transaction.commit();
        return Supports::Feature {
            Supports::Selector { builder.to_string().release_value_but_fixme_should_propagate_errors(), JS::make_handle(m_context.realm()) }
        };
    }

    return {};
}

// https://www.w3.org/TR/mediaqueries-4/#typedef-general-enclosed
Optional<GeneralEnclosed> Parser::parse_general_enclosed(TokenStream<ComponentValue>& tokens)
{
    auto transaction = tokens.begin_transaction();
    tokens.skip_whitespace();
    auto const& first_token = tokens.next_token();

    // `[ <function-token> <any-value>? ) ]`
    if (first_token.is_function()) {
        transaction.commit();
        return GeneralEnclosed { first_token.to_string().release_value_but_fixme_should_propagate_errors() };
    }

    // `( <any-value>? )`
    if (first_token.is_block() && first_token.block().is_paren()) {
        transaction.commit();
        return GeneralEnclosed { first_token.to_string().release_value_but_fixme_should_propagate_errors() };
    }

    return {};
}

// 5.4.1. Consume a list of rules
// https://www.w3.org/TR/css-syntax-3/#consume-list-of-rules
template<typename T>
Vector<NonnullRefPtr<Rule>> Parser::consume_a_list_of_rules(TokenStream<T>& tokens, TopLevel top_level)
{
    // To consume a list of rules, given a top-level flag:

    // Create an initially empty list of rules.
    Vector<NonnullRefPtr<Rule>> rules;

    // Repeatedly consume the next input token:
    for (;;) {
        auto& token = tokens.next_token();

        // <whitespace-token>
        if (token.is(Token::Type::Whitespace)) {
            // Do nothing.
            continue;
        }

        // <EOF-token>
        if (token.is(Token::Type::EndOfFile)) {
            // Return the list of rules.
            return rules;
        }

        // <CDO-token>
        // <CDC-token>
        if (token.is(Token::Type::CDO) || token.is(Token::Type::CDC)) {
            // If the top-level flag is set, do nothing.
            if (top_level == TopLevel::Yes)
                continue;

            // Otherwise, reconsume the current input token.
            tokens.reconsume_current_input_token();

            // Consume a qualified rule. If anything is returned, append it to the list of rules.
            if (auto maybe_qualified = consume_a_qualified_rule(tokens))
                rules.append(maybe_qualified.release_nonnull());

            continue;
        }

        // <at-keyword-token>
        if (token.is(Token::Type::AtKeyword)) {
            // Reconsume the current input token.
            tokens.reconsume_current_input_token();

            // Consume an at-rule, and append the returned value to the list of rules.
            rules.append(consume_an_at_rule(tokens));

            continue;
        }

        // anything else
        {
            // Reconsume the current input token.
            tokens.reconsume_current_input_token();

            // Consume a qualified rule. If anything is returned, append it to the list of rules.
            if (auto maybe_qualified = consume_a_qualified_rule(tokens))
                rules.append(maybe_qualified.release_nonnull());

            continue;
        }
    }
}

// 5.4.2. Consume an at-rule
// https://www.w3.org/TR/css-syntax-3/#consume-at-rule
template<typename T>
NonnullRefPtr<Rule> Parser::consume_an_at_rule(TokenStream<T>& tokens)
{
    // To consume an at-rule:

    // Consume the next input token.
    auto& name_ident = tokens.next_token();
    VERIFY(name_ident.is(Token::Type::AtKeyword));

    // Create a new at-rule with its name set to the value of the current input token, its prelude initially set to an empty list, and its value initially set to nothing.
    // NOTE: We create the Rule fully initialized when we return it instead.
    auto at_rule_name = FlyString::from_utf8(((Token)name_ident).at_keyword()).release_value_but_fixme_should_propagate_errors();
    Vector<ComponentValue> prelude;
    RefPtr<Block> block;

    // Repeatedly consume the next input token:
    for (;;) {
        auto& token = tokens.next_token();

        // <semicolon-token>
        if (token.is(Token::Type::Semicolon)) {
            // Return the at-rule.
            return Rule::make_at_rule(move(at_rule_name), move(prelude), move(block));
        }

        // <EOF-token>
        if (token.is(Token::Type::EndOfFile)) {
            // This is a parse error. Return the at-rule.
            log_parse_error();
            return Rule::make_at_rule(move(at_rule_name), move(prelude), move(block));
        }

        // <{-token>
        if (token.is(Token::Type::OpenCurly)) {
            // Consume a simple block and assign it to the at-rule’s block. Return the at-rule.
            block = consume_a_simple_block(tokens);
            return Rule::make_at_rule(move(at_rule_name), move(prelude), move(block));
        }

        // simple block with an associated token of <{-token>
        if constexpr (IsSame<T, ComponentValue>) {
            ComponentValue const& component_value = token;
            if (component_value.is_block() && component_value.block().is_curly()) {
                // Assign the block to the at-rule’s block. Return the at-rule.
                block = component_value.block();
                return Rule::make_at_rule(move(at_rule_name), move(prelude), move(block));
            }
        }

        // anything else
        {
            // Reconsume the current input token.
            tokens.reconsume_current_input_token();
            // Consume a component value. Append the returned value to the at-rule’s prelude.
            prelude.append(consume_a_component_value(tokens));
        }
    }
}

// 5.4.3. Consume a qualified rule
// https://www.w3.org/TR/css-syntax-3/#consume-qualified-rule
template<typename T>
RefPtr<Rule> Parser::consume_a_qualified_rule(TokenStream<T>& tokens)
{
    // To consume a qualified rule:

    // Create a new qualified rule with its prelude initially set to an empty list, and its value initially set to nothing.
    // NOTE: We create the Rule fully initialized when we return it instead.
    Vector<ComponentValue> prelude;
    RefPtr<Block> block;

    // Repeatedly consume the next input token:
    for (;;) {
        auto& token = tokens.next_token();

        // <EOF-token>
        if (token.is(Token::Type::EndOfFile)) {
            // This is a parse error. Return nothing.
            log_parse_error();
            return {};
        }

        // <{-token>
        if (token.is(Token::Type::OpenCurly)) {
            // Consume a simple block and assign it to the qualified rule’s block. Return the qualified rule.
            block = consume_a_simple_block(tokens);
            return Rule::make_qualified_rule(move(prelude), move(block));
        }

        // simple block with an associated token of <{-token>
        if constexpr (IsSame<T, ComponentValue>) {
            ComponentValue const& component_value = token;
            if (component_value.is_block() && component_value.block().is_curly()) {
                // Assign the block to the qualified rule’s block. Return the qualified rule.
                block = component_value.block();
                return Rule::make_qualified_rule(move(prelude), move(block));
            }
        }

        // anything else
        {
            // Reconsume the current input token.
            tokens.reconsume_current_input_token();

            // Consume a component value. Append the returned value to the qualified rule’s prelude.
            prelude.append(consume_a_component_value(tokens));
        }
    }
}

// 5.4.4. Consume a style block’s contents
// https://www.w3.org/TR/css-syntax-3/#consume-a-style-blocks-contents
template<typename T>
Vector<DeclarationOrAtRule> Parser::consume_a_style_blocks_contents(TokenStream<T>& tokens)
{
    // To consume a style block’s contents:
    // Create an initially empty list of declarations decls, and an initially empty list of rules rules.
    Vector<DeclarationOrAtRule> declarations;
    Vector<DeclarationOrAtRule> rules;

    // Repeatedly consume the next input token:
    for (;;) {
        auto& token = tokens.next_token();

        // <whitespace-token>
        // <semicolon-token>
        if (token.is(Token::Type::Whitespace) || token.is(Token::Type::Semicolon)) {
            // Do nothing.
            continue;
        }

        // <EOF-token>
        if (token.is(Token::Type::EndOfFile)) {
            // Extend decls with rules, then return decls.
            declarations.extend(move(rules));
            return declarations;
        }

        // <at-keyword-token>
        if (token.is(Token::Type::AtKeyword)) {
            // Reconsume the current input token.
            tokens.reconsume_current_input_token();

            // Consume an at-rule, and append the result to rules.
            rules.empend(consume_an_at_rule(tokens));
            continue;
        }

        // <ident-token>
        if (token.is(Token::Type::Ident)) {
            // Initialize a temporary list initially filled with the current input token.
            Vector<ComponentValue> temporary_list;
            temporary_list.append(token);

            // As long as the next input token is anything other than a <semicolon-token> or <EOF-token>,
            // consume a component value and append it to the temporary list.
            for (;;) {
                auto& next_input_token = tokens.peek_token();
                if (next_input_token.is(Token::Type::Semicolon) || next_input_token.is(Token::Type::EndOfFile))
                    break;
                temporary_list.append(consume_a_component_value(tokens));
            }

            // Consume a declaration from the temporary list. If anything was returned, append it to decls.
            auto token_stream = TokenStream(temporary_list);
            if (auto maybe_declaration = consume_a_declaration(token_stream); maybe_declaration.has_value())
                declarations.empend(maybe_declaration.release_value());

            continue;
        }

        // <delim-token> with a value of "&" (U+0026 AMPERSAND)
        if (token.is(Token::Type::Delim) && token.token().delim() == '&') {
            // Reconsume the current input token.
            tokens.reconsume_current_input_token();

            // Consume a qualified rule. If anything was returned, append it to rules.
            if (auto qualified_rule = consume_a_qualified_rule(tokens))
                rules.empend(qualified_rule);

            continue;
        }

        // anything else
        {
            // This is a parse error.
            log_parse_error();

            // Reconsume the current input token.
            tokens.reconsume_current_input_token();

            // As long as the next input token is anything other than a <semicolon-token> or <EOF-token>,
            // consume a component value and throw away the returned value.
            for (;;) {
                auto& peek = tokens.peek_token();
                if (peek.is(Token::Type::Semicolon) || peek.is(Token::Type::EndOfFile))
                    break;
                (void)consume_a_component_value(tokens);
            }
        }
    }
}

template<>
ComponentValue Parser::consume_a_component_value(TokenStream<ComponentValue>& tokens)
{
    // Note: This overload is called once tokens have already been converted into component values,
    //       so we do not need to do the work in the more general overload.
    return tokens.next_token();
}

// 5.4.7. Consume a component value
// https://www.w3.org/TR/css-syntax-3/#consume-component-value
template<typename T>
ComponentValue Parser::consume_a_component_value(TokenStream<T>& tokens)
{
    // To consume a component value:

    // Consume the next input token.
    auto& token = tokens.next_token();

    // If the current input token is a <{-token>, <[-token>, or <(-token>, consume a simple block and return it.
    if (token.is(Token::Type::OpenCurly) || token.is(Token::Type::OpenSquare) || token.is(Token::Type::OpenParen))
        return ComponentValue(consume_a_simple_block(tokens));

    // Otherwise, if the current input token is a <function-token>, consume a function and return it.
    if (token.is(Token::Type::Function))
        return ComponentValue(consume_a_function(tokens));

    // Otherwise, return the current input token.
    return ComponentValue(token);
}

// 5.4.8. Consume a simple block
// https://www.w3.org/TR/css-syntax-3/#consume-simple-block
template<typename T>
NonnullRefPtr<Block> Parser::consume_a_simple_block(TokenStream<T>& tokens)
{
    // Note: This algorithm assumes that the current input token has already been checked
    // to be an <{-token>, <[-token>, or <(-token>.

    // To consume a simple block:

    // The ending token is the mirror variant of the current input token.
    // (E.g. if it was called with <[-token>, the ending token is <]-token>.)
    auto ending_token = ((Token)tokens.current_token()).mirror_variant();

    // Create a simple block with its associated token set to the current input token
    // and with its value initially set to an empty list.
    // NOTE: We create the Block fully initialized when we return it instead.
    Token block_token = tokens.current_token();
    Vector<ComponentValue> block_values;

    // Repeatedly consume the next input token and process it as follows:
    for (;;) {
        auto& token = tokens.next_token();

        // ending token
        if (token.is(ending_token)) {
            // Return the block.
            return Block::create(move(block_token), move(block_values));
        }
        // <EOF-token>
        if (token.is(Token::Type::EndOfFile)) {
            // This is a parse error. Return the block.
            log_parse_error();
            return Block::create(move(block_token), move(block_values));
        }

        // anything else
        {
            // Reconsume the current input token.
            tokens.reconsume_current_input_token();

            // Consume a component value and append it to the value of the block.
            block_values.empend(consume_a_component_value(tokens));
        }
    }
}

// 5.4.9. Consume a function
// https://www.w3.org/TR/css-syntax-3/#consume-function
template<typename T>
NonnullRefPtr<Function> Parser::consume_a_function(TokenStream<T>& tokens)
{
    // Note: This algorithm assumes that the current input token has already been checked to be a <function-token>.
    auto name_ident = tokens.current_token();
    VERIFY(name_ident.is(Token::Type::Function));

    // To consume a function:

    // Create a function with its name equal to the value of the current input token
    // and with its value initially set to an empty list.
    // NOTE: We create the Function fully initialized when we return it instead.
    auto function_name = FlyString::from_utf8(((Token)name_ident).function()).release_value_but_fixme_should_propagate_errors();
    Vector<ComponentValue> function_values;

    // Repeatedly consume the next input token and process it as follows:
    for (;;) {
        auto& token = tokens.next_token();

        // <)-token>
        if (token.is(Token::Type::CloseParen)) {
            // Return the function.
            return Function::create(move(function_name), move(function_values));
        }

        // <EOF-token>
        if (token.is(Token::Type::EndOfFile)) {
            // This is a parse error. Return the function.
            log_parse_error();
            return Function::create(move(function_name), move(function_values));
        }

        // anything else
        {
            // Reconsume the current input token.
            tokens.reconsume_current_input_token();

            // Consume a component value and append the returned value to the function’s value.
            function_values.append(consume_a_component_value(tokens));
        }
    }
}

// 5.4.6. Consume a declaration
// https://www.w3.org/TR/css-syntax-3/#consume-declaration
template<typename T>
Optional<Declaration> Parser::consume_a_declaration(TokenStream<T>& tokens)
{
    // Note: This algorithm assumes that the next input token has already been checked to
    // be an <ident-token>.
    // NOTE: This is not true in our implementation! For convenience, we both skip whitespace
    //       and gracefully handle the first token not being an <ident-token>.

    // To consume a declaration:

    // Consume the next input token.
    auto transaction = tokens.begin_transaction();
    tokens.skip_whitespace();
    auto& token = tokens.next_token();

    // NOTE: Not to spec, handle the case where the input token *isn't* an <ident-token>.
    if (!token.is(Token::Type::Ident))
        return {};

    // Create a new declaration with its name set to the value of the current input token
    // and its value initially set to the empty list.
    // NOTE: We create a fully-initialized Declaration just before returning it instead.
    auto declaration_name = FlyString::from_utf8(((Token)token).ident()).release_value_but_fixme_should_propagate_errors();
    Vector<ComponentValue> declaration_values;
    Important declaration_important = Important::No;

    // 1. While the next input token is a <whitespace-token>, consume the next input token.
    tokens.skip_whitespace();

    // 2. If the next input token is anything other than a <colon-token>, this is a parse error.
    // Return nothing.
    auto& maybe_colon = tokens.peek_token();
    if (!maybe_colon.is(Token::Type::Colon)) {
        log_parse_error();
        return {};
    }
    // Otherwise, consume the next input token.
    tokens.next_token();

    // 3. While the next input token is a <whitespace-token>, consume the next input token.
    tokens.skip_whitespace();

    // 4. As long as the next input token is anything other than an <EOF-token>, consume a
    //    component value and append it to the declaration’s value.
    for (;;) {
        if (tokens.peek_token().is(Token::Type::EndOfFile)) {
            break;
        }
        declaration_values.append(consume_a_component_value(tokens));
    }

    // 5. If the last two non-<whitespace-token>s in the declaration’s value are a <delim-token>
    //    with the value "!" followed by an <ident-token> with a value that is an ASCII case-insensitive
    //    match for "important", remove them from the declaration’s value and set the declaration’s
    //    important flag to true.
    if (declaration_values.size() >= 2) {
        // Walk backwards from the end until we find "important"
        Optional<size_t> important_index;
        for (size_t i = declaration_values.size() - 1; i > 0; i--) {
            auto value = declaration_values[i];
            if (value.is(Token::Type::Ident) && Infra::is_ascii_case_insensitive_match(value.token().ident(), "important"sv)) {
                important_index = i;
                break;
            }
            if (value.is(Token::Type::Whitespace))
                continue;
            break;
        }

        // Walk backwards from important until we find "!"
        if (important_index.has_value()) {
            Optional<size_t> bang_index;
            for (size_t i = important_index.value() - 1; i > 0; i--) {
                auto value = declaration_values[i];
                if (value.is(Token::Type::Delim) && value.token().delim() == '!') {
                    bang_index = i;
                    break;
                }
                if (value.is(Token::Type::Whitespace))
                    continue;
                break;
            }

            if (bang_index.has_value()) {
                declaration_values.remove(important_index.value());
                declaration_values.remove(bang_index.value());
                declaration_important = Important::Yes;
            }
        }
    }

    // 6. While the last token in the declaration’s value is a <whitespace-token>, remove that token.
    while (!declaration_values.is_empty()) {
        auto maybe_whitespace = declaration_values.last();
        if (!(maybe_whitespace.is(Token::Type::Whitespace))) {
            break;
        }
        declaration_values.take_last();
    }

    // 7. Return the declaration.
    transaction.commit();
    return Declaration { move(declaration_name), move(declaration_values), declaration_important };
}

// 5.4.5. Consume a list of declarations
// https://www.w3.org/TR/css-syntax-3/#consume-list-of-declarations
template<typename T>
Vector<DeclarationOrAtRule> Parser::consume_a_list_of_declarations(TokenStream<T>& tokens)
{
    // To consume a list of declarations:

    // Create an initially empty list of declarations.
    Vector<DeclarationOrAtRule> list_of_declarations;

    // Repeatedly consume the next input token:
    for (;;) {
        auto& token = tokens.next_token();

        // <whitespace-token>
        // <semicolon-token>
        if (token.is(Token::Type::Whitespace) || token.is(Token::Type::Semicolon)) {
            // Do nothing.
            continue;
        }

        // <EOF-token>
        if (token.is(Token::Type::EndOfFile)) {
            // Return the list of declarations.
            return list_of_declarations;
        }

        // <at-keyword-token>
        if (token.is(Token::Type::AtKeyword)) {
            // Reconsume the current input token.
            tokens.reconsume_current_input_token();

            // Consume an at-rule. Append the returned rule to the list of declarations.
            list_of_declarations.empend(consume_an_at_rule(tokens));
            continue;
        }

        // <ident-token>
        if (token.is(Token::Type::Ident)) {
            // Initialize a temporary list initially filled with the current input token.
            Vector<ComponentValue> temporary_list;
            temporary_list.append(token);

            // As long as the next input token is anything other than a <semicolon-token> or <EOF-token>,
            // consume a component value and append it to the temporary list.
            for (;;) {
                auto& peek = tokens.peek_token();
                if (peek.is(Token::Type::Semicolon) || peek.is(Token::Type::EndOfFile))
                    break;
                temporary_list.append(consume_a_component_value(tokens));
            }

            // Consume a declaration from the temporary list. If anything was returned, append it to the list of declarations.
            auto token_stream = TokenStream(temporary_list);
            if (auto maybe_declaration = consume_a_declaration(token_stream); maybe_declaration.has_value())
                list_of_declarations.empend(maybe_declaration.value());

            continue;
        }

        // anything else
        {
            // This is a parse error.
            log_parse_error();

            // Reconsume the current input token.
            tokens.reconsume_current_input_token();

            // As long as the next input token is anything other than a <semicolon-token> or <EOF-token>,
            // consume a component value and throw away the returned value.
            for (;;) {
                auto& peek = tokens.peek_token();
                if (peek.is(Token::Type::Semicolon) || peek.is(Token::Type::EndOfFile))
                    break;
                dbgln_if(CSS_PARSER_DEBUG, "Discarding token: '{}'", peek.to_debug_string());
                (void)consume_a_component_value(tokens);
            }
        }
    }
}

CSSRule* Parser::parse_as_css_rule()
{
    auto maybe_rule = parse_a_rule(m_token_stream);
    if (maybe_rule)
        return convert_to_rule(maybe_rule.release_nonnull());
    return {};
}

// 5.3.5. Parse a rule
// https://www.w3.org/TR/css-syntax-3/#parse-rule
template<typename T>
RefPtr<Rule> Parser::parse_a_rule(TokenStream<T>& tokens)
{
    // To parse a rule from input:
    RefPtr<Rule> rule;

    // 1. Normalize input, and set input to the result.
    // Note: This is done when initializing the Parser.

    // 2. While the next input token from input is a <whitespace-token>, consume the next input token from input.
    tokens.skip_whitespace();

    // 3. If the next input token from input is an <EOF-token>, return a syntax error.
    auto& token = tokens.peek_token();
    if (token.is(Token::Type::EndOfFile)) {
        return {};
    }
    // Otherwise, if the next input token from input is an <at-keyword-token>, consume an at-rule from input, and let rule be the return value.
    else if (token.is(Token::Type::AtKeyword)) {
        rule = consume_an_at_rule(m_token_stream);
    }
    // Otherwise, consume a qualified rule from input and let rule be the return value. If nothing was returned, return a syntax error.
    else {
        auto qualified_rule = consume_a_qualified_rule(tokens);
        if (!qualified_rule)
            return {};

        rule = qualified_rule;
    }

    // 4. While the next input token from input is a <whitespace-token>, consume the next input token from input.
    tokens.skip_whitespace();

    // 5. If the next input token from input is an <EOF-token>, return rule. Otherwise, return a syntax error.
    if (tokens.peek_token().is(Token::Type::EndOfFile))
        return rule;
    return {};
}

// 5.3.4. Parse a list of rules
// https://www.w3.org/TR/css-syntax-3/#parse-list-of-rules
template<typename T>
Vector<NonnullRefPtr<Rule>> Parser::parse_a_list_of_rules(TokenStream<T>& tokens)
{
    // To parse a list of rules from input:

    // 1. Normalize input, and set input to the result.
    // Note: This is done when initializing the Parser.

    // 2. Consume a list of rules from the input, with the top-level flag unset.
    auto list_of_rules = consume_a_list_of_rules(tokens, TopLevel::No);

    // 3. Return the returned list.
    return list_of_rules;
}

Optional<StyleProperty> Parser::parse_as_supports_condition()
{
    auto maybe_declaration = parse_a_declaration(m_token_stream);
    if (maybe_declaration.has_value())
        return convert_to_style_property(maybe_declaration.release_value());
    return {};
}

// 5.3.6. Parse a declaration
// https://www.w3.org/TR/css-syntax-3/#parse-a-declaration
template<typename T>
Optional<Declaration> Parser::parse_a_declaration(TokenStream<T>& tokens)
{
    // To parse a declaration from input:

    // 1. Normalize input, and set input to the result.
    // Note: This is done when initializing the Parser.

    // 2. While the next input token from input is a <whitespace-token>, consume the next input token.
    tokens.skip_whitespace();

    // 3. If the next input token from input is not an <ident-token>, return a syntax error.
    auto& token = tokens.peek_token();
    if (!token.is(Token::Type::Ident)) {
        return {};
    }

    // 4. Consume a declaration from input. If anything was returned, return it. Otherwise, return a syntax error.
    if (auto declaration = consume_a_declaration(tokens); declaration.has_value())
        return declaration.release_value();
    return {};
}

// 5.3.7. Parse a style block’s contents
// https://www.w3.org/TR/css-syntax-3/#parse-style-blocks-contents
template<typename T>
Vector<DeclarationOrAtRule> Parser::parse_a_style_blocks_contents(TokenStream<T>& tokens)
{
    // To parse a style block’s contents from input:

    // 1. Normalize input, and set input to the result.
    // Note: This is done when initializing the Parser.

    // 2. Consume a style block’s contents from input, and return the result.
    return consume_a_style_blocks_contents(tokens);
}

// 5.3.8. Parse a list of declarations
// https://www.w3.org/TR/css-syntax-3/#parse-list-of-declarations
template<typename T>
Vector<DeclarationOrAtRule> Parser::parse_a_list_of_declarations(TokenStream<T>& tokens)
{
    // To parse a list of declarations from input:

    // 1. Normalize input, and set input to the result.
    // Note: This is done when initializing the Parser.

    // 2. Consume a list of declarations from input, and return the result.
    return consume_a_list_of_declarations(tokens);
}

// 5.3.9. Parse a component value
// https://www.w3.org/TR/css-syntax-3/#parse-component-value
template<typename T>
Optional<ComponentValue> Parser::parse_a_component_value(TokenStream<T>& tokens)
{
    // To parse a component value from input:

    // 1. Normalize input, and set input to the result.
    // Note: This is done when initializing the Parser.

    // 2. While the next input token from input is a <whitespace-token>, consume the next input token from input.
    tokens.skip_whitespace();

    // 3. If the next input token from input is an <EOF-token>, return a syntax error.
    if (tokens.peek_token().is(Token::Type::EndOfFile))
        return {};

    // 4. Consume a component value from input and let value be the return value.
    auto value = consume_a_component_value(tokens);

    // 5. While the next input token from input is a <whitespace-token>, consume the next input token.
    tokens.skip_whitespace();

    // 6. If the next input token from input is an <EOF-token>, return value. Otherwise, return a syntax error.
    if (tokens.peek_token().is(Token::Type::EndOfFile))
        return value;
    return {};
}

// 5.3.10. Parse a list of component values
// https://www.w3.org/TR/css-syntax-3/#parse-list-of-component-values
template<typename T>
Vector<ComponentValue> Parser::parse_a_list_of_component_values(TokenStream<T>& tokens)
{
    // To parse a list of component values from input:

    // 1. Normalize input, and set input to the result.
    // Note: This is done when initializing the Parser.

    // 2. Repeatedly consume a component value from input until an <EOF-token> is returned, appending the returned values (except the final <EOF-token>) into a list. Return the list.
    Vector<ComponentValue> component_values;

    for (;;) {
        if (tokens.peek_token().is(Token::Type::EndOfFile)) {
            break;
        }

        component_values.append(consume_a_component_value(tokens));
    }

    return component_values;
}

// 5.3.11. Parse a comma-separated list of component values
// https://www.w3.org/TR/css-syntax-3/#parse-comma-separated-list-of-component-values
template<typename T>
Vector<Vector<ComponentValue>> Parser::parse_a_comma_separated_list_of_component_values(TokenStream<T>& tokens)
{
    // To parse a comma-separated list of component values from input:

    // 1. Normalize input, and set input to the result.
    // Note: This is done when initializing the Parser.

    // 2. Let list of cvls be an initially empty list of component value lists.
    Vector<Vector<ComponentValue>> list_of_component_value_lists;

    // 3. Repeatedly consume a component value from input until an <EOF-token> or <comma-token> is returned,
    //    appending the returned values (except the final <EOF-token> or <comma-token>) into a list.
    //    Append the list to list of cvls.
    //    If it was a <comma-token> that was returned, repeat this step.
    Vector<ComponentValue> current_list;
    for (;;) {
        auto component_value = consume_a_component_value(tokens);

        if (component_value.is(Token::Type::EndOfFile)) {
            list_of_component_value_lists.append(move(current_list));
            break;
        }
        if (component_value.is(Token::Type::Comma)) {
            list_of_component_value_lists.append(move(current_list));
            current_list = {};
            continue;
        }

        current_list.append(component_value);
    }

    // 4. Return list of cvls.
    return list_of_component_value_lists;
}

ElementInlineCSSStyleDeclaration* Parser::parse_as_style_attribute(DOM::Element& element)
{
    auto declarations_and_at_rules = parse_a_list_of_declarations(m_token_stream);
    auto [properties, custom_properties] = extract_properties(declarations_and_at_rules);
    return ElementInlineCSSStyleDeclaration::create(element, move(properties), move(custom_properties)).release_value_but_fixme_should_propagate_errors();
}

Optional<AK::URL> Parser::parse_url_function(ComponentValue const& component_value, AllowedDataUrlType allowed_data_url_type)
{
    // FIXME: Handle list of media queries. https://www.w3.org/TR/css-cascade-3/#conditional-import
    // FIXME: Handle data: urls (RFC2397)

    auto convert_string_to_url = [&](StringView& url_string) -> Optional<AK::URL> {
        if (url_string.starts_with("data:"sv, CaseSensitivity::CaseInsensitive)) {
            auto data_url = AK::URL(url_string);

            switch (allowed_data_url_type) {
            case AllowedDataUrlType::Image:
                if (data_url.data_mime_type().starts_with("image"sv, CaseSensitivity::CaseInsensitive))
                    return data_url;
                break;
            case AllowedDataUrlType::Font:
                if (data_url.data_mime_type().starts_with("font"sv, CaseSensitivity::CaseInsensitive))
                    return data_url;
                break;
            default:
                break;
            }

            return {};
        }

        return m_context.complete_url(url_string);
    };

    if (component_value.is(Token::Type::Url)) {
        auto url_string = component_value.token().url();
        return convert_string_to_url(url_string);
    }
    if (component_value.is_function() && component_value.function().name().equals_ignoring_ascii_case("url"sv)) {
        auto const& function_values = component_value.function().values();
        // FIXME: Handle url-modifiers. https://www.w3.org/TR/css-values-4/#url-modifiers
        for (size_t i = 0; i < function_values.size(); ++i) {
            auto const& value = function_values[i];
            if (value.is(Token::Type::Whitespace))
                continue;
            if (value.is(Token::Type::String)) {
                auto url_string = value.token().string();
                return convert_string_to_url(url_string);
            }
            break;
        }
    }

    return {};
}

template<typename TElement>
static Optional<Vector<TElement>> parse_color_stop_list(auto& tokens, auto is_position, auto get_position, auto parse_color, auto parse_dimension)
{
    enum class ElementType {
        Garbage,
        ColorStop,
        ColorHint
    };

    auto parse_color_stop_list_element = [&](TElement& element) -> ElementType {
        tokens.skip_whitespace();
        if (!tokens.has_next_token())
            return ElementType::Garbage;
        auto const& token = tokens.next_token();

        Gfx::Color color;
        Optional<typename TElement::PositionType> position;
        Optional<typename TElement::PositionType> second_position;
        auto dimension = parse_dimension(token);
        if (dimension.has_value() && is_position(*dimension)) {
            // [<T-percentage> <color>] or [<T-percentage>]
            position = get_position(*dimension);
            tokens.skip_whitespace();
            // <T-percentage>
            if (!tokens.has_next_token() || tokens.peek_token().is(Token::Type::Comma)) {
                element.transition_hint = typename TElement::ColorHint { *position };
                return ElementType::ColorHint;
            }
            // <T-percentage> <color>
            auto maybe_color = parse_color(tokens.next_token());
            if (!maybe_color.has_value())
                return ElementType::Garbage;
            color = *maybe_color;
        } else {
            // [<color> <T-percentage>?]
            auto maybe_color = parse_color(token);
            if (!maybe_color.has_value())
                return ElementType::Garbage;
            color = *maybe_color;
            tokens.skip_whitespace();
            // Allow up to [<color> <T-percentage> <T-percentage>] (double-position color stops)
            // Note: Double-position color stops only appear to be valid in this order.
            for (auto stop_position : Array { &position, &second_position }) {
                if (tokens.has_next_token() && !tokens.peek_token().is(Token::Type::Comma)) {
                    auto token = tokens.next_token();
                    auto dimension = parse_dimension(token);
                    if (!dimension.has_value() || !is_position(*dimension))
                        return ElementType::Garbage;
                    *stop_position = get_position(*dimension);
                    tokens.skip_whitespace();
                }
            }
        }

        element.color_stop = typename TElement::ColorStop { color, position, second_position };
        return ElementType::ColorStop;
    };

    TElement first_element {};
    if (parse_color_stop_list_element(first_element) != ElementType::ColorStop)
        return {};

    if (!tokens.has_next_token())
        return {};

    Vector<TElement> color_stops { first_element };
    while (tokens.has_next_token()) {
        TElement list_element {};
        tokens.skip_whitespace();
        if (!tokens.next_token().is(Token::Type::Comma))
            return {};
        auto element_type = parse_color_stop_list_element(list_element);
        if (element_type == ElementType::ColorHint) {
            // <color-hint>, <color-stop>
            tokens.skip_whitespace();
            if (!tokens.next_token().is(Token::Type::Comma))
                return {};
            // Note: This fills in the color stop on the same list_element as the color hint (it does not overwrite it).
            if (parse_color_stop_list_element(list_element) != ElementType::ColorStop)
                return {};
        } else if (element_type == ElementType::ColorStop) {
            // <color-stop>
        } else {
            return {};
        }
        color_stops.append(list_element);
    }

    return color_stops;
}

Optional<Vector<LinearColorStopListElement>> Parser::parse_linear_color_stop_list(TokenStream<ComponentValue>& tokens)
{
    // <color-stop-list> =
    //   <linear-color-stop> , [ <linear-color-hint>? , <linear-color-stop> ]#
    return parse_color_stop_list<LinearColorStopListElement>(
        tokens,
        [](Dimension& dimension) { return dimension.is_length_percentage(); },
        [](Dimension& dimension) { return dimension.length_percentage(); },
        [&](auto& token) { return parse_color(token); },
        [&](auto& token) { return parse_dimension(token); });
}

Optional<Vector<AngularColorStopListElement>> Parser::parse_angular_color_stop_list(TokenStream<ComponentValue>& tokens)
{
    // <angular-color-stop-list> =
    //   <angular-color-stop> , [ <angular-color-hint>? , <angular-color-stop> ]#
    return parse_color_stop_list<AngularColorStopListElement>(
        tokens,
        [](Dimension& dimension) { return dimension.is_angle_percentage(); },
        [](Dimension& dimension) { return dimension.angle_percentage(); },
        [&](auto& token) { return parse_color(token); },
        [&](auto& token) { return parse_dimension(token); });
}

static StringView consume_if_starts_with(StringView str, StringView start, auto found_callback)
{
    if (str.starts_with(start, CaseSensitivity::CaseInsensitive)) {
        found_callback();
        return str.substring_view(start.length());
    }
    return str;
};

RefPtr<StyleValue> Parser::parse_linear_gradient_function(ComponentValue const& component_value)
{
    using GradientType = LinearGradientStyleValue::GradientType;

    if (!component_value.is_function())
        return {};

    GradientRepeating repeating_gradient = GradientRepeating::No;
    GradientType gradient_type { GradientType::Standard };

    auto function_name = component_value.function().name();

    function_name = consume_if_starts_with(function_name, "-webkit-"sv, [&] {
        gradient_type = GradientType::WebKit;
    });

    function_name = consume_if_starts_with(function_name, "repeating-"sv, [&] {
        repeating_gradient = GradientRepeating::Yes;
    });

    if (!function_name.equals_ignoring_ascii_case("linear-gradient"sv))
        return {};

    // linear-gradient() = linear-gradient([ <angle> | to <side-or-corner> ]?, <color-stop-list>)

    TokenStream tokens { component_value.function().values() };
    tokens.skip_whitespace();

    if (!tokens.has_next_token())
        return {};

    bool has_direction_param = true;
    LinearGradientStyleValue::GradientDirection gradient_direction = gradient_type == GradientType::Standard
        ? SideOrCorner::Bottom
        : SideOrCorner::Top;

    auto to_side = [](StringView value) -> Optional<SideOrCorner> {
        if (value.equals_ignoring_ascii_case("top"sv))
            return SideOrCorner::Top;
        if (value.equals_ignoring_ascii_case("bottom"sv))
            return SideOrCorner::Bottom;
        if (value.equals_ignoring_ascii_case("left"sv))
            return SideOrCorner::Left;
        if (value.equals_ignoring_ascii_case("right"sv))
            return SideOrCorner::Right;
        return {};
    };

    auto is_to_side_or_corner = [&](auto const& token) {
        if (!token.is(Token::Type::Ident))
            return false;
        if (gradient_type == GradientType::WebKit)
            return to_side(token.token().ident()).has_value();
        return token.token().ident().equals_ignoring_ascii_case("to"sv);
    };

    auto const& first_param = tokens.peek_token();
    if (first_param.is(Token::Type::Dimension)) {
        // <angle>
        tokens.next_token();
        float angle_value = first_param.token().dimension_value();
        auto unit_string = first_param.token().dimension_unit();
        auto angle_type = Angle::unit_from_name(unit_string);

        if (!angle_type.has_value())
            return {};

        gradient_direction = Angle { angle_value, angle_type.release_value() };
    } else if (is_to_side_or_corner(first_param)) {
        // <side-or-corner> = [left | right] || [top | bottom]

        // Note: -webkit-linear-gradient does not include to the "to" prefix on the side or corner
        if (gradient_type == GradientType::Standard) {
            tokens.next_token();
            tokens.skip_whitespace();

            if (!tokens.has_next_token())
                return {};
        }

        // [left | right] || [top | bottom]
        auto const& first_side = tokens.next_token();
        if (!first_side.is(Token::Type::Ident))
            return {};

        auto side_a = to_side(first_side.token().ident());
        tokens.skip_whitespace();
        Optional<SideOrCorner> side_b;
        if (tokens.has_next_token() && tokens.peek_token().is(Token::Type::Ident))
            side_b = to_side(tokens.next_token().token().ident());

        if (side_a.has_value() && !side_b.has_value()) {
            gradient_direction = *side_a;
        } else if (side_a.has_value() && side_b.has_value()) {
            // Convert two sides to a corner
            if (to_underlying(*side_b) < to_underlying(*side_a))
                swap(side_a, side_b);
            if (side_a == SideOrCorner::Top && side_b == SideOrCorner::Left)
                gradient_direction = SideOrCorner::TopLeft;
            else if (side_a == SideOrCorner::Top && side_b == SideOrCorner::Right)
                gradient_direction = SideOrCorner::TopRight;
            else if (side_a == SideOrCorner::Bottom && side_b == SideOrCorner::Left)
                gradient_direction = SideOrCorner::BottomLeft;
            else if (side_a == SideOrCorner::Bottom && side_b == SideOrCorner::Right)
                gradient_direction = SideOrCorner::BottomRight;
            else
                return {};
        } else {
            return {};
        }
    } else {
        has_direction_param = false;
    }

    tokens.skip_whitespace();
    if (!tokens.has_next_token())
        return {};

    if (has_direction_param && !tokens.next_token().is(Token::Type::Comma))
        return {};

    auto color_stops = parse_linear_color_stop_list(tokens);
    if (!color_stops.has_value())
        return {};

    return LinearGradientStyleValue::create(gradient_direction, move(*color_stops), gradient_type, repeating_gradient);
}

RefPtr<StyleValue> Parser::parse_conic_gradient_function(ComponentValue const& component_value)
{
    if (!component_value.is_function())
        return {};

    GradientRepeating repeating_gradient = GradientRepeating::No;

    auto function_name = component_value.function().name();

    function_name = consume_if_starts_with(function_name, "repeating-"sv, [&] {
        repeating_gradient = GradientRepeating::Yes;
    });

    if (!function_name.equals_ignoring_ascii_case("conic-gradient"sv))
        return {};

    TokenStream tokens { component_value.function().values() };
    tokens.skip_whitespace();

    if (!tokens.has_next_token())
        return {};

    Angle from_angle(0, Angle::Type::Deg);
    PositionValue at_position = PositionValue::center();

    // conic-gradient( [ [ from <angle> ]? [ at <position> ]? ]  ||
    // <color-interpolation-method> , <angular-color-stop-list> )
    auto token = tokens.peek_token();
    bool got_from_angle = false;
    bool got_color_interpolation_method = false;
    bool got_at_position = false;
    while (token.is(Token::Type::Ident)) {
        auto consume_identifier = [&](auto identifier) {
            auto token_string = token.token().ident();
            if (token_string.equals_ignoring_ascii_case(identifier)) {
                (void)tokens.next_token();
                tokens.skip_whitespace();
                return true;
            }
            return false;
        };

        if (consume_identifier("from"sv)) {
            // from <angle>
            if (got_from_angle || got_at_position)
                return {};
            if (!tokens.has_next_token())
                return {};

            auto angle_token = tokens.next_token();
            if (!angle_token.is(Token::Type::Dimension))
                return {};
            float angle = angle_token.token().dimension_value();
            auto angle_unit = angle_token.token().dimension_unit();
            auto angle_type = Angle::unit_from_name(angle_unit);
            if (!angle_type.has_value())
                return {};

            from_angle = Angle(angle, *angle_type);
            got_from_angle = true;
        } else if (consume_identifier("at"sv)) {
            // at <position>
            if (got_at_position)
                return {};
            auto position = parse_position(tokens);
            if (!position.has_value())
                return {};
            at_position = *position;
            got_at_position = true;
        } else if (consume_identifier("in"sv)) {
            // <color-interpolation-method>
            if (got_color_interpolation_method)
                return {};
            dbgln("FIXME: Parse color interpolation method for conic-gradient()");
            got_color_interpolation_method = true;
        } else {
            break;
        }
        tokens.skip_whitespace();
        if (!tokens.has_next_token())
            return {};
        token = tokens.peek_token();
    }

    tokens.skip_whitespace();
    if (!tokens.has_next_token())
        return {};
    if ((got_from_angle || got_at_position || got_color_interpolation_method) && !tokens.next_token().is(Token::Type::Comma))
        return {};

    auto color_stops = parse_angular_color_stop_list(tokens);
    if (!color_stops.has_value())
        return {};

    return ConicGradientStyleValue::create(from_angle, at_position, move(*color_stops), repeating_gradient);
}

RefPtr<StyleValue> Parser::parse_radial_gradient_function(ComponentValue const& component_value)
{
    using EndingShape = RadialGradientStyleValue::EndingShape;
    using Extent = RadialGradientStyleValue::Extent;
    using CircleSize = RadialGradientStyleValue::CircleSize;
    using EllipseSize = RadialGradientStyleValue::EllipseSize;
    using Size = RadialGradientStyleValue::Size;

    if (!component_value.is_function())
        return {};

    auto repeating_gradient = GradientRepeating::No;

    auto function_name = component_value.function().name();

    function_name = consume_if_starts_with(function_name, "repeating-"sv, [&] {
        repeating_gradient = GradientRepeating::Yes;
    });

    if (!function_name.equals_ignoring_ascii_case("radial-gradient"sv))
        return {};

    TokenStream tokens { component_value.function().values() };
    tokens.skip_whitespace();
    if (!tokens.has_next_token())
        return {};

    bool expect_comma = false;

    auto commit_value = [&]<typename... T>(auto value, T&... transactions) {
        (transactions.commit(), ...);
        return value;
    };

    // radial-gradient( [ <ending-shape> || <size> ]? [ at <position> ]? , <color-stop-list> )

    Size size = Extent::FarthestCorner;
    EndingShape ending_shape = EndingShape::Circle;
    PositionValue at_position = PositionValue::center();

    auto parse_ending_shape = [&]() -> Optional<EndingShape> {
        auto transaction = tokens.begin_transaction();
        tokens.skip_whitespace();
        auto& token = tokens.next_token();
        if (!token.is(Token::Type::Ident))
            return {};
        auto ident = token.token().ident();
        if (ident.equals_ignoring_ascii_case("circle"sv))
            return commit_value(EndingShape::Circle, transaction);
        if (ident.equals_ignoring_ascii_case("ellipse"sv))
            return commit_value(EndingShape::Ellipse, transaction);
        return {};
    };

    auto parse_extent_keyword = [](StringView keyword) -> Optional<Extent> {
        if (keyword.equals_ignoring_ascii_case("closest-corner"sv))
            return Extent::ClosestCorner;
        if (keyword.equals_ignoring_ascii_case("closest-side"sv))
            return Extent::ClosestSide;
        if (keyword.equals_ignoring_ascii_case("farthest-corner"sv))
            return Extent::FarthestCorner;
        if (keyword.equals_ignoring_ascii_case("farthest-side"sv))
            return Extent::FarthestSide;
        return {};
    };

    auto parse_size = [&]() -> Optional<Size> {
        // <size> =
        //      <extent-keyword>              |
        //      <length [0,∞]>                |
        //      <length-percentage [0,∞]>{2}
        auto transaction_size = tokens.begin_transaction();
        tokens.skip_whitespace();
        if (!tokens.has_next_token())
            return {};
        auto& token = tokens.next_token();
        if (token.is(Token::Type::Ident)) {
            auto extent = parse_extent_keyword(token.token().ident());
            if (!extent.has_value())
                return {};
            return commit_value(*extent, transaction_size);
        }
        auto first_dimension = parse_dimension(token);
        if (!first_dimension.has_value())
            return {};
        if (!first_dimension->is_length_percentage())
            return {};
        auto transaction_second_dimension = tokens.begin_transaction();
        tokens.skip_whitespace();
        if (tokens.has_next_token()) {
            auto& second_token = tokens.next_token();
            auto second_dimension = parse_dimension(second_token);
            if (second_dimension.has_value() && second_dimension->is_length_percentage())
                return commit_value(EllipseSize { first_dimension->length_percentage(), second_dimension->length_percentage() },
                    transaction_size, transaction_second_dimension);
        }
        if (first_dimension->is_length())
            return commit_value(CircleSize { first_dimension->length() }, transaction_size);
        return {};
    };

    {
        // [ <ending-shape> || <size> ]?
        auto maybe_ending_shape = parse_ending_shape();
        auto maybe_size = parse_size();
        if (!maybe_ending_shape.has_value() && maybe_size.has_value())
            maybe_ending_shape = parse_ending_shape();
        if (maybe_size.has_value()) {
            size = *maybe_size;
            expect_comma = true;
        }
        if (maybe_ending_shape.has_value()) {
            expect_comma = true;
            ending_shape = *maybe_ending_shape;
            if (ending_shape == EndingShape::Circle && size.has<EllipseSize>())
                return {};
            if (ending_shape == EndingShape::Ellipse && size.has<CircleSize>())
                return {};
        } else {
            ending_shape = size.has<CircleSize>() ? EndingShape::Circle : EndingShape::Ellipse;
        }
    }

    tokens.skip_whitespace();
    if (!tokens.has_next_token())
        return {};

    auto& token = tokens.peek_token();
    if (token.is(Token::Type::Ident) && token.token().ident().equals_ignoring_ascii_case("at"sv)) {
        (void)tokens.next_token();
        auto position = parse_position(tokens);
        if (!position.has_value())
            return {};
        at_position = *position;
        expect_comma = true;
    }

    tokens.skip_whitespace();
    if (!tokens.has_next_token())
        return {};
    if (expect_comma && !tokens.next_token().is(Token::Type::Comma))
        return {};

    // <color-stop-list>
    auto color_stops = parse_linear_color_stop_list(tokens);
    if (!color_stops.has_value())
        return {};

    return RadialGradientStyleValue::create(ending_shape, size, at_position, move(*color_stops), repeating_gradient);
}

Optional<PositionValue> Parser::parse_position(TokenStream<ComponentValue>& tokens, PositionValue initial_value)
{
    auto transaction = tokens.begin_transaction();
    tokens.skip_whitespace();
    if (!tokens.has_next_token())
        return {};

    auto parse_horizontal_preset = [&](auto ident) -> Optional<PositionValue::HorizontalPreset> {
        if (ident.equals_ignoring_ascii_case("left"sv))
            return PositionValue::HorizontalPreset::Left;
        if (ident.equals_ignoring_ascii_case("center"sv))
            return PositionValue::HorizontalPreset::Center;
        if (ident.equals_ignoring_ascii_case("right"sv))
            return PositionValue::HorizontalPreset::Right;
        return {};
    };

    auto parse_vertical_preset = [&](auto ident) -> Optional<PositionValue::VerticalPreset> {
        if (ident.equals_ignoring_ascii_case("top"sv))
            return PositionValue::VerticalPreset::Top;
        if (ident.equals_ignoring_ascii_case("center"sv))
            return PositionValue::VerticalPreset::Center;
        if (ident.equals_ignoring_ascii_case("bottom"sv))
            return PositionValue::VerticalPreset::Bottom;
        return {};
    };

    auto parse_horizontal_edge = [&](auto ident) -> Optional<PositionValue::HorizontalEdge> {
        if (ident.equals_ignoring_ascii_case("left"sv))
            return PositionValue::HorizontalEdge::Left;
        if (ident.equals_ignoring_ascii_case("right"sv))
            return PositionValue::HorizontalEdge::Right;
        return {};
    };

    auto parse_vertical_edge = [&](auto ident) -> Optional<PositionValue::VerticalEdge> {
        if (ident.equals_ignoring_ascii_case("top"sv))
            return PositionValue::VerticalEdge::Top;
        if (ident.equals_ignoring_ascii_case("bottom"sv))
            return PositionValue::VerticalEdge::Bottom;
        return {};
    };

    // <position> = [
    //   [ left | center | right ] || [ top | center | bottom ]
    // |
    //   [ left | center | right | <length-percentage> ]
    //   [ top | center | bottom | <length-percentage> ]?
    // |
    //   [ [ left | right ] <length-percentage> ] &&
    //   [ [ top | bottom ] <length-percentage> ]
    // ]

    // [ left | center | right ] || [ top | center | bottom ]
    auto alternation_1 = [&]() -> Optional<PositionValue> {
        auto transaction = tokens.begin_transaction();
        PositionValue position = initial_value;
        auto& first_token = tokens.next_token();
        if (!first_token.is(Token::Type::Ident))
            return {};
        auto ident = first_token.token().ident();
        // <horizontal-position> <vertical-position>?
        auto horizontal_position = parse_horizontal_preset(ident);
        if (horizontal_position.has_value()) {
            position.horizontal_position = *horizontal_position;
            auto transaction_optional_parse = tokens.begin_transaction();
            tokens.skip_whitespace();
            if (tokens.has_next_token()) {
                auto& second_token = tokens.next_token();
                if (second_token.is(Token::Type::Ident)) {
                    auto vertical_position = parse_vertical_preset(second_token.token().ident());
                    if (vertical_position.has_value()) {
                        transaction_optional_parse.commit();
                        position.vertical_position = *vertical_position;
                    }
                }
            }
        } else {
            // <vertical-position> <horizontal-position>?
            auto vertical_position = parse_vertical_preset(ident);
            if (!vertical_position.has_value())
                return {};
            position.vertical_position = *vertical_position;
            auto transaction_optional_parse = tokens.begin_transaction();
            tokens.skip_whitespace();
            if (tokens.has_next_token()) {
                auto& second_token = tokens.next_token();
                if (second_token.is(Token::Type::Ident)) {
                    auto horizontal_position = parse_horizontal_preset(second_token.token().ident());
                    if (horizontal_position.has_value()) {
                        transaction_optional_parse.commit();
                        position.horizontal_position = *horizontal_position;
                    }
                }
            }
        }
        transaction.commit();
        return position;
    };

    // [ left | center | right | <length-percentage> ]
    // [ top | center | bottom | <length-percentage> ]?
    auto alternation_2 = [&]() -> Optional<PositionValue> {
        auto transaction = tokens.begin_transaction();
        PositionValue position = initial_value;
        auto& first_token = tokens.next_token();
        if (first_token.is(Token::Type::Ident)) {
            auto horizontal_position = parse_horizontal_preset(first_token.token().ident());
            if (!horizontal_position.has_value())
                return {};
            position.horizontal_position = *horizontal_position;
        } else {
            auto dimension = parse_dimension(first_token);
            if (!dimension.has_value() || !dimension->is_length_percentage())
                return {};
            position.horizontal_position = dimension->length_percentage();
        }
        auto transaction_optional_parse = tokens.begin_transaction();
        tokens.skip_whitespace();
        if (tokens.has_next_token()) {
            auto& second_token = tokens.next_token();
            if (second_token.is(Token::Type::Ident)) {
                auto vertical_position = parse_vertical_preset(second_token.token().ident());
                if (vertical_position.has_value()) {
                    transaction_optional_parse.commit();
                    position.vertical_position = *vertical_position;
                }
            } else {
                auto dimension = parse_dimension(second_token);
                if (dimension.has_value() && dimension->is_length_percentage()) {
                    transaction_optional_parse.commit();
                    position.vertical_position = dimension->length_percentage();
                }
            }
        }
        transaction.commit();
        return position;
    };

    // [ [ left | right ] <length-percentage> ] &&
    // [ [ top | bottom ] <length-percentage> ]
    auto alternation_3 = [&]() -> Optional<PositionValue> {
        auto transaction = tokens.begin_transaction();
        PositionValue position {};

        auto parse_horizontal = [&] {
            // [ left | right ] <length-percentage> ]
            auto transaction = tokens.begin_transaction();
            tokens.skip_whitespace();
            if (!tokens.has_next_token())
                return false;
            auto& first_token = tokens.next_token();
            if (!first_token.is(Token::Type::Ident))
                return false;
            auto horizontal_egde = parse_horizontal_edge(first_token.token().ident());
            if (!horizontal_egde.has_value())
                return false;
            position.x_relative_to = *horizontal_egde;
            tokens.skip_whitespace();
            if (!tokens.has_next_token())
                return false;
            auto& second_token = tokens.next_token();
            auto dimension = parse_dimension(second_token);
            if (!dimension.has_value() || !dimension->is_length_percentage())
                return false;
            position.horizontal_position = dimension->length_percentage();
            transaction.commit();
            return true;
        };

        auto parse_vertical = [&] {
            // [ top | bottom ] <length-percentage> ]
            auto transaction = tokens.begin_transaction();
            tokens.skip_whitespace();
            if (!tokens.has_next_token())
                return false;
            auto& first_token = tokens.next_token();
            if (!first_token.is(Token::Type::Ident))
                return false;
            auto vertical_edge = parse_vertical_edge(first_token.token().ident());
            if (!vertical_edge.has_value())
                return false;
            position.y_relative_to = *vertical_edge;
            tokens.skip_whitespace();
            if (!tokens.has_next_token())
                return false;
            auto& second_token = tokens.next_token();
            auto dimension = parse_dimension(second_token);
            if (!dimension.has_value() || !dimension->is_length_percentage())
                return false;
            position.vertical_position = dimension->length_percentage();
            transaction.commit();
            return true;
        };

        if ((parse_horizontal() && parse_vertical()) || (parse_vertical() && parse_horizontal())) {
            transaction.commit();
            return position;
        }

        return {};
    };

    // Note: The alternatives must be attempted in this order since `alternation_2' can match a prefix of `alternation_3'
    auto position = alternation_3();
    if (!position.has_value())
        position = alternation_2();
    if (!position.has_value())
        position = alternation_1();
    if (position.has_value())
        transaction.commit();
    return position;
}

CSSRule* Parser::convert_to_rule(NonnullRefPtr<Rule> rule)
{
    if (rule->is_at_rule()) {
        if (has_ignored_vendor_prefix(rule->at_rule_name()))
            return {};
        if (rule->at_rule_name().equals_ignoring_ascii_case("font-face"sv)) {
            if (!rule->block() || !rule->block()->is_curly()) {
                dbgln_if(CSS_PARSER_DEBUG, "@font-face rule is malformed.");
                return {};
            }
            TokenStream tokens { rule->block()->values() };
            return parse_font_face_rule(tokens);
        }
        if (rule->at_rule_name().equals_ignoring_ascii_case("import"sv) && !rule->prelude().is_empty()) {
            Optional<AK::URL> url;
            for (auto const& token : rule->prelude()) {
                if (token.is(Token::Type::Whitespace))
                    continue;

                if (token.is(Token::Type::String)) {
                    url = m_context.complete_url(token.token().string());
                } else {
                    url = parse_url_function(token);
                }

                // FIXME: Handle list of media queries. https://www.w3.org/TR/css-cascade-3/#conditional-import
                if (url.has_value())
                    break;
            }

            if (url.has_value())
                return CSSImportRule::create(url.value(), const_cast<DOM::Document&>(*m_context.document())).release_value_but_fixme_should_propagate_errors();
            dbgln_if(CSS_PARSER_DEBUG, "Unable to parse url from @import rule");
            return {};
        }
        if (rule->at_rule_name().equals_ignoring_ascii_case("media"sv)) {
            auto media_query_tokens = TokenStream { rule->prelude() };
            auto media_query_list = parse_a_media_query_list(media_query_tokens);
            if (media_query_list.is_empty() || !rule->block())
                return {};

            auto child_tokens = TokenStream { rule->block()->values() };
            auto parser_rules = parse_a_list_of_rules(child_tokens);
            JS::MarkedVector<CSSRule*> child_rules(m_context.realm().heap());
            for (auto& raw_rule : parser_rules) {
                if (auto* child_rule = convert_to_rule(raw_rule))
                    child_rules.append(child_rule);
            }
            auto media_list = MediaList::create(m_context.realm(), move(media_query_list)).release_value_but_fixme_should_propagate_errors();
            auto rule_list = CSSRuleList::create(m_context.realm(), child_rules).release_value_but_fixme_should_propagate_errors();
            return CSSMediaRule::create(m_context.realm(), media_list, rule_list).release_value_but_fixme_should_propagate_errors();
        }
        if (rule->at_rule_name().equals_ignoring_ascii_case("supports"sv)) {
            auto supports_tokens = TokenStream { rule->prelude() };
            auto supports = parse_a_supports(supports_tokens);
            if (!supports) {
                if constexpr (CSS_PARSER_DEBUG) {
                    dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @supports rule invalid; discarding.");
                    supports_tokens.dump_all_tokens();
                }
                return {};
            }

            if (!rule->block())
                return {};
            auto child_tokens = TokenStream { rule->block()->values() };
            auto parser_rules = parse_a_list_of_rules(child_tokens);
            JS::MarkedVector<CSSRule*> child_rules(m_context.realm().heap());
            for (auto& raw_rule : parser_rules) {
                if (auto* child_rule = convert_to_rule(raw_rule))
                    child_rules.append(child_rule);
            }

            auto rule_list = CSSRuleList::create(m_context.realm(), child_rules).release_value_but_fixme_should_propagate_errors();
            return CSSSupportsRule::create(m_context.realm(), supports.release_nonnull(), rule_list).release_value_but_fixme_should_propagate_errors();
        }

        // FIXME: More at rules!
        dbgln_if(CSS_PARSER_DEBUG, "Unrecognized CSS at-rule: @{}", rule->at_rule_name());
        return {};
    }

    auto prelude_stream = TokenStream(rule->prelude());
    auto selectors = parse_a_selector_list(prelude_stream, SelectorType::Standalone);

    if (selectors.is_error()) {
        if (selectors.error() != ParseError::IncludesIgnoredVendorPrefix) {
            dbgln_if(CSS_PARSER_DEBUG, "CSSParser: style rule selectors invalid; discarding.");
            if constexpr (CSS_PARSER_DEBUG) {
                prelude_stream.dump_all_tokens();
            }
        }
        return {};
    }

    if (selectors.value().is_empty()) {
        dbgln_if(CSS_PARSER_DEBUG, "CSSParser: empty selector; discarding.");
        return {};
    }

    if (!rule->block()->is_curly())
        return {};

    auto stream = TokenStream(rule->block()->values());
    auto declarations_and_at_rules = parse_a_style_blocks_contents(stream);

    auto* declaration = convert_to_style_declaration(declarations_and_at_rules);
    if (!declaration) {
        dbgln_if(CSS_PARSER_DEBUG, "CSSParser: style rule declaration invalid; discarding.");
        return {};
    }

    return CSSStyleRule::create(m_context.realm(), move(selectors.value()), *declaration).release_value_but_fixme_should_propagate_errors();
}

auto Parser::extract_properties(Vector<DeclarationOrAtRule> const& declarations_and_at_rules) -> PropertiesAndCustomProperties
{
    PropertiesAndCustomProperties result;
    for (auto const& declaration_or_at_rule : declarations_and_at_rules) {
        if (declaration_or_at_rule.is_at_rule()) {
            dbgln_if(CSS_PARSER_DEBUG, "!!! CSS at-rule is not allowed here!");
            continue;
        }

        auto const& declaration = declaration_or_at_rule.declaration();

        if (auto maybe_property = convert_to_style_property(declaration); maybe_property.has_value()) {
            auto property = maybe_property.release_value();
            if (property.property_id == PropertyID::Custom) {
                result.custom_properties.set(property.custom_name, property);
            } else {
                result.properties.append(move(property));
            }
        }
    }
    return result;
}

PropertyOwningCSSStyleDeclaration* Parser::convert_to_style_declaration(Vector<DeclarationOrAtRule> const& declarations_and_at_rules)
{
    auto [properties, custom_properties] = extract_properties(declarations_and_at_rules);
    return PropertyOwningCSSStyleDeclaration::create(m_context.realm(), move(properties), move(custom_properties)).release_value_but_fixme_should_propagate_errors();
}

Optional<StyleProperty> Parser::convert_to_style_property(Declaration const& declaration)
{
    auto property_name = declaration.name();
    auto property_id = property_id_from_string(property_name);

    if (property_id == PropertyID::Invalid) {
        if (property_name.starts_with("--"sv)) {
            property_id = PropertyID::Custom;
        } else if (has_ignored_vendor_prefix(property_name)) {
            return {};
        } else if (!property_name.starts_with('-')) {
            dbgln_if(CSS_PARSER_DEBUG, "Unrecognized CSS property '{}'", property_name);
            return {};
        }
    }

    auto value_token_stream = TokenStream(declaration.values());
    auto value = parse_css_value(property_id, value_token_stream);
    if (value.is_error()) {
        if (value.error() != ParseError::IncludesIgnoredVendorPrefix) {
            dbgln_if(CSS_PARSER_DEBUG, "Unable to parse value for CSS property '{}'.", property_name);
            if constexpr (CSS_PARSER_DEBUG) {
                value_token_stream.dump_all_tokens();
            }
        }
        return {};
    }

    if (property_id == PropertyID::Custom)
        return StyleProperty { declaration.importance(), property_id, value.release_value(), declaration.name() };

    return StyleProperty { declaration.importance(), property_id, value.release_value(), {} };
}

RefPtr<StyleValue> Parser::parse_builtin_value(ComponentValue const& component_value)
{
    if (component_value.is(Token::Type::Ident)) {
        auto ident = component_value.token().ident();
        if (ident.equals_ignoring_ascii_case("inherit"sv))
            return InheritStyleValue::the();
        if (ident.equals_ignoring_ascii_case("initial"sv))
            return InitialStyleValue::the();
        if (ident.equals_ignoring_ascii_case("unset"sv))
            return UnsetStyleValue::the();
        // FIXME: Implement `revert` and `revert-layer` keywords, from Cascade4 and Cascade5 respectively
    }

    return {};
}

RefPtr<CalculatedStyleValue> Parser::parse_calculated_value(Vector<ComponentValue> const& component_values)
{
    auto calc_expression = parse_calc_expression(component_values);
    if (calc_expression == nullptr)
        return nullptr;

    auto calc_type = calc_expression->resolved_type();
    if (!calc_type.has_value()) {
        dbgln_if(CSS_PARSER_DEBUG, "calc() resolved as invalid!!!");
        return nullptr;
    }

    [[maybe_unused]] auto to_string = [](CalculatedStyleValue::ResolvedType type) {
        switch (type) {
        case CalculatedStyleValue::ResolvedType::Angle:
            return "Angle"sv;
        case CalculatedStyleValue::ResolvedType::Frequency:
            return "Frequency"sv;
        case CalculatedStyleValue::ResolvedType::Integer:
            return "Integer"sv;
        case CalculatedStyleValue::ResolvedType::Length:
            return "Length"sv;
        case CalculatedStyleValue::ResolvedType::Number:
            return "Number"sv;
        case CalculatedStyleValue::ResolvedType::Percentage:
            return "Percentage"sv;
        case CalculatedStyleValue::ResolvedType::Time:
            return "Time"sv;
        }
        VERIFY_NOT_REACHED();
    };
    dbgln_if(CSS_PARSER_DEBUG, "Deduced calc() resolved type as: {}", to_string(calc_type.value()));

    return CalculatedStyleValue::create(calc_expression.release_nonnull(), calc_type.release_value());
}

RefPtr<StyleValue> Parser::parse_dynamic_value(ComponentValue const& component_value)
{
    if (component_value.is_function()) {
        auto const& function = component_value.function();

        if (function.name().equals_ignoring_ascii_case("calc"sv))
            return parse_calculated_value(function.values());

        if (function.name().equals_ignoring_ascii_case("var"sv)) {
            // Declarations using `var()` should already be parsed as an UnresolvedStyleValue before this point.
            VERIFY_NOT_REACHED();
        }
    }

    return {};
}

Optional<Parser::Dimension> Parser::parse_dimension(ComponentValue const& component_value)
{
    if (component_value.is(Token::Type::Dimension)) {
        float numeric_value = component_value.token().dimension_value();
        auto unit_string = component_value.token().dimension_unit();

        if (auto length_type = Length::unit_from_name(unit_string); length_type.has_value())
            return Length { numeric_value, length_type.release_value() };

        if (auto angle_type = Angle::unit_from_name(unit_string); angle_type.has_value())
            return Angle { numeric_value, angle_type.release_value() };

        if (auto frequency_type = Frequency::unit_from_name(unit_string); frequency_type.has_value())
            return Frequency { numeric_value, frequency_type.release_value() };

        if (auto resolution_type = Resolution::unit_from_name(unit_string); resolution_type.has_value())
            return Resolution { numeric_value, resolution_type.release_value() };

        if (auto time_type = Time::unit_from_name(unit_string); time_type.has_value())
            return Time { numeric_value, time_type.release_value() };
    }

    if (component_value.is(Token::Type::Percentage))
        return Percentage { static_cast<float>(component_value.token().percentage()) };

    if (component_value.is(Token::Type::Number)) {
        float numeric_value = component_value.token().number_value();
        if (numeric_value == 0)
            return Length::make_px(0);
        if (m_context.in_quirks_mode() && property_has_quirk(m_context.current_property_id(), Quirk::UnitlessLength)) {
            // https://quirks.spec.whatwg.org/#quirky-length-value
            // FIXME: Disallow quirk when inside a CSS sub-expression (like `calc()`)
            // "The <quirky-length> value must not be supported in arguments to CSS expressions other than the rect()
            // expression, and must not be supported in the supports() static method of the CSS interface."
            return Length::make_px(numeric_value);
        }
    }

    return {};
}

Optional<Length> Parser::parse_length(ComponentValue const& component_value)
{
    auto dimension = parse_dimension(component_value);
    if (!dimension.has_value())
        return {};

    if (dimension->is_length())
        return dimension->length();

    // FIXME: auto isn't a length!
    if (component_value.is(Token::Type::Ident) && component_value.token().ident().equals_ignoring_ascii_case("auto"sv))
        return Length::make_auto();

    return {};
}

Optional<Ratio> Parser::parse_ratio(TokenStream<ComponentValue>& tokens)
{
    auto transaction = tokens.begin_transaction();
    tokens.skip_whitespace();

    // `<ratio> = <number [0,∞]> [ / <number [0,∞]> ]?`
    // FIXME: I think either part is allowed to be calc(), which makes everything complicated.
    auto first_number = tokens.next_token();
    if (!first_number.is(Token::Type::Number) || first_number.token().number_value() < 0)
        return {};

    {
        auto two_value_transaction = tokens.begin_transaction();
        tokens.skip_whitespace();
        auto solidus = tokens.next_token();
        tokens.skip_whitespace();
        auto second_number = tokens.next_token();
        if (solidus.is(Token::Type::Delim) && solidus.token().delim() == '/'
            && second_number.is(Token::Type::Number) && second_number.token().number_value() > 0) {
            // Two-value ratio
            two_value_transaction.commit();
            transaction.commit();
            return Ratio { static_cast<float>(first_number.token().number_value()), static_cast<float>(second_number.token().number_value()) };
        }
    }

    // Single-value ratio
    transaction.commit();
    return Ratio { static_cast<float>(first_number.token().number_value()) };
}

// https://www.w3.org/TR/css-syntax-3/#urange-syntax
Optional<UnicodeRange> Parser::parse_unicode_range(TokenStream<ComponentValue>& tokens)
{
    auto transaction = tokens.begin_transaction();
    tokens.skip_whitespace();

    // <urange> =
    //  u '+' <ident-token> '?'* |
    //  u <dimension-token> '?'* |
    //  u <number-token> '?'* |
    //  u <number-token> <dimension-token> |
    //  u <number-token> <number-token> |
    //  u '+' '?'+
    // (All with no whitespace in between tokens.)

    // NOTE: Parsing this is different from usual. We take these steps:
    // 1. Match the grammar above against the tokens, concatenating them into a string using their original representation.
    // 2. Then, parse that string according to the spec algorithm.
    // Step 2 is performed by calling the other parse_unicode_range() overload.

    auto is_question_mark = [](ComponentValue const& component_value) {
        return component_value.is(Token::Type::Delim) && component_value.token().delim() == '?';
    };

    auto is_ending_token = [](ComponentValue const& component_value) {
        return component_value.is(Token::Type::EndOfFile)
            || component_value.is(Token::Type::Comma)
            || component_value.is(Token::Type::Semicolon)
            || component_value.is(Token::Type::Whitespace);
    };

    auto create_unicode_range = [&](StringView text, auto& local_transaction) -> Optional<UnicodeRange> {
        auto maybe_unicode_range = parse_unicode_range(text);
        if (maybe_unicode_range.has_value()) {
            local_transaction.commit();
            transaction.commit();
        }
        return maybe_unicode_range;
    };

    // All options start with 'u'/'U'.
    auto const& u = tokens.next_token();
    if (!(u.is(Token::Type::Ident) && u.token().ident().equals_ignoring_ascii_case("u"sv))) {
        dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> does not start with 'u'");
        return {};
    }

    auto const& second_token = tokens.next_token();

    //  u '+' <ident-token> '?'* |
    //  u '+' '?'+
    if (second_token.is(Token::Type::Delim) && second_token.token().delim() == '+') {
        auto local_transaction = tokens.begin_transaction();
        StringBuilder string_builder;
        string_builder.append(second_token.token().representation());

        auto const& third_token = tokens.next_token();
        if (third_token.is(Token::Type::Ident) || is_question_mark(third_token)) {
            string_builder.append(third_token.token().representation());
            while (is_question_mark(tokens.peek_token()))
                string_builder.append(tokens.next_token().token().representation());
            if (is_ending_token(tokens.peek_token()))
                return create_unicode_range(string_builder.string_view(), local_transaction);
        }
    }

    //  u <dimension-token> '?'*
    if (second_token.is(Token::Type::Dimension)) {
        auto local_transaction = tokens.begin_transaction();
        StringBuilder string_builder;
        string_builder.append(second_token.token().representation());
        while (is_question_mark(tokens.peek_token()))
            string_builder.append(tokens.next_token().token().representation());
        if (is_ending_token(tokens.peek_token()))
            return create_unicode_range(string_builder.string_view(), local_transaction);
    }

    //  u <number-token> '?'* |
    //  u <number-token> <dimension-token> |
    //  u <number-token> <number-token>
    if (second_token.is(Token::Type::Number)) {
        auto local_transaction = tokens.begin_transaction();
        StringBuilder string_builder;
        string_builder.append(second_token.token().representation());

        if (is_ending_token(tokens.peek_token()))
            return create_unicode_range(string_builder.string_view(), local_transaction);

        auto const& third_token = tokens.next_token();
        if (is_question_mark(third_token)) {
            string_builder.append(third_token.token().representation());
            while (is_question_mark(tokens.peek_token()))
                string_builder.append(tokens.next_token().token().representation());
            if (is_ending_token(tokens.peek_token()))
                return create_unicode_range(string_builder.string_view(), local_transaction);
        } else if (third_token.is(Token::Type::Dimension)) {
            string_builder.append(third_token.token().representation());
            if (is_ending_token(tokens.peek_token()))
                return create_unicode_range(string_builder.string_view(), local_transaction);
        } else if (third_token.is(Token::Type::Number)) {
            string_builder.append(third_token.token().representation());
            if (is_ending_token(tokens.peek_token()))
                return create_unicode_range(string_builder.string_view(), local_transaction);
        }
    }

    if constexpr (CSS_PARSER_DEBUG) {
        dbgln("CSSParser: Tokens did not match <urange> grammar.");
        tokens.dump_all_tokens();
    }
    return {};
}

Optional<UnicodeRange> Parser::parse_unicode_range(StringView text)
{
    auto make_valid_unicode_range = [&](u32 start_value, u32 end_value) -> Optional<UnicodeRange> {
        // https://www.w3.org/TR/css-syntax-3/#maximum-allowed-code-point
        constexpr u32 maximum_allowed_code_point = 0x10FFFF;

        // To determine what codepoints the <urange> represents:
        // 1. If end value is greater than the maximum allowed code point,
        //    the <urange> is invalid and a syntax error.
        if (end_value > maximum_allowed_code_point) {
            dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Invalid <urange>: end_value ({}) > maximum ({})", end_value, maximum_allowed_code_point);
            return {};
        }

        // 2. If start value is greater than end value, the <urange> is invalid and a syntax error.
        if (start_value > end_value) {
            dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Invalid <urange>: start_value ({}) > end_value ({})", start_value, end_value);
            return {};
        }

        // 3. Otherwise, the <urange> represents a contiguous range of codepoints from start value to end value, inclusive.
        return UnicodeRange { start_value, end_value };
    };

    // 1. Skipping the first u token, concatenate the representations of all the tokens in the production together.
    //    Let this be text.
    // NOTE: The concatenation is already done by the caller.
    GenericLexer lexer { text };

    // 2. If the first character of text is U+002B PLUS SIGN, consume it.
    //    Otherwise, this is an invalid <urange>, and this algorithm must exit.
    if (lexer.next_is('+')) {
        lexer.consume();
    } else {
        dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Second character of <urange> was not '+'; got: '{}'", lexer.consume());
        return {};
    }

    // 3. Consume as many hex digits from text as possible.
    //    then consume as many U+003F QUESTION MARK (?) code points as possible.
    auto hex_digits = lexer.consume_while(is_ascii_hex_digit);
    auto question_marks = lexer.consume_while([](auto it) { return it == '?'; });
    //    If zero code points were consumed, or more than six code points were consumed,
    //    this is an invalid <urange>, and this algorithm must exit.
    size_t consumed_code_points = hex_digits.length() + question_marks.length();
    if (consumed_code_points == 0 || consumed_code_points > 6) {
        dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> start value had {} digits/?s, expected between 1 and 6.", consumed_code_points);
        return {};
    }
    StringView start_value_code_points { hex_digits.characters_without_null_termination(), consumed_code_points };

    //    If any U+003F QUESTION MARK (?) code points were consumed, then:
    if (question_marks.length() > 0) {
        // 1. If there are any code points left in text, this is an invalid <urange>,
        //    and this algorithm must exit.
        if (lexer.tell_remaining() != 0) {
            dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> invalid; had {} code points left over.", lexer.tell_remaining());
            return {};
        }

        // 2. Interpret the consumed code points as a hexadecimal number,
        //    with the U+003F QUESTION MARK (?) code points replaced by U+0030 DIGIT ZERO (0) code points.
        //    This is the start value.
        auto start_value_string = start_value_code_points.replace("?"sv, "0"sv, ReplaceMode::All);
        auto maybe_start_value = AK::StringUtils::convert_to_uint_from_hex<u32>(start_value_string);
        if (!maybe_start_value.has_value()) {
            dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> ?-converted start value did not parse as hex number.");
            return {};
        }
        u32 start_value = maybe_start_value.release_value();

        // 3. Interpret the consumed code points as a hexadecimal number again,
        //    with the U+003F QUESTION MARK (?) code points replaced by U+0046 LATIN CAPITAL LETTER F (F) code points.
        //    This is the end value.
        auto end_value_string = start_value_code_points.replace("?"sv, "F"sv, ReplaceMode::All);
        auto maybe_end_value = AK::StringUtils::convert_to_uint_from_hex<u32>(end_value_string);
        if (!maybe_end_value.has_value()) {
            dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> ?-converted end value did not parse as hex number.");
            return {};
        }
        u32 end_value = maybe_end_value.release_value();

        // 4. Exit this algorithm.
        return make_valid_unicode_range(start_value, end_value);
    }
    //   Otherwise, interpret the consumed code points as a hexadecimal number. This is the start value.
    auto maybe_start_value = AK::StringUtils::convert_to_uint_from_hex<u32>(start_value_code_points);
    if (!maybe_start_value.has_value()) {
        dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> start value did not parse as hex number.");
        return {};
    }
    u32 start_value = maybe_start_value.release_value();

    // 4. If there are no code points left in text, The end value is the same as the start value.
    //    Exit this algorithm.
    if (lexer.tell_remaining() == 0)
        return make_valid_unicode_range(start_value, start_value);

    // 5. If the next code point in text is U+002D HYPHEN-MINUS (-), consume it.
    if (lexer.next_is('-')) {
        lexer.consume();
    }
    //    Otherwise, this is an invalid <urange>, and this algorithm must exit.
    else {
        dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> start and end values not separated by '-'.");
        return {};
    }

    // 6. Consume as many hex digits as possible from text.
    auto end_hex_digits = lexer.consume_while(is_ascii_hex_digit);

    //   If zero hex digits were consumed, or more than 6 hex digits were consumed,
    //   this is an invalid <urange>, and this algorithm must exit.
    if (end_hex_digits.length() == 0 || end_hex_digits.length() > 6) {
        dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> end value had {} digits, expected between 1 and 6.", end_hex_digits.length());
        return {};
    }

    //   If there are any code points left in text, this is an invalid <urange>, and this algorithm must exit.
    if (lexer.tell_remaining() != 0) {
        dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> invalid; had {} code points left over.", lexer.tell_remaining());
        return {};
    }

    // 7. Interpret the consumed code points as a hexadecimal number. This is the end value.
    auto maybe_end_value = AK::StringUtils::convert_to_uint_from_hex<u32>(end_hex_digits);
    if (!maybe_end_value.has_value()) {
        dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> end value did not parse as hex number.");
        return {};
    }
    u32 end_value = maybe_end_value.release_value();

    return make_valid_unicode_range(start_value, end_value);
}

RefPtr<StyleValue> Parser::parse_dimension_value(ComponentValue const& component_value)
{
    // Numbers with no units can be lengths, in two situations:
    // 1) We're in quirks mode, and it's an integer.
    // 2) It's a 0.
    // We handle case 1 here. Case 2 is handled by NumericStyleValue pretending to be a LengthStyleValue if it is 0.

    if (component_value.is(Token::Type::Number) && !(m_context.in_quirks_mode() && property_has_quirk(m_context.current_property_id(), Quirk::UnitlessLength)))
        return {};

    if (component_value.is(Token::Type::Ident) && component_value.token().ident().equals_ignoring_ascii_case("auto"sv))
        return LengthStyleValue::create(Length::make_auto());

    auto dimension = parse_dimension(component_value);
    if (!dimension.has_value())
        return {};

    if (dimension->is_angle())
        return AngleStyleValue::create(dimension->angle());
    if (dimension->is_frequency())
        return FrequencyStyleValue::create(dimension->frequency());
    if (dimension->is_length())
        return LengthStyleValue::create(dimension->length());
    if (dimension->is_percentage())
        return PercentageStyleValue::create(dimension->percentage());
    if (dimension->is_resolution())
        return ResolutionStyleValue::create(dimension->resolution());
    if (dimension->is_time())
        return TimeStyleValue::create(dimension->time());
    VERIFY_NOT_REACHED();
}

RefPtr<StyleValue> Parser::parse_numeric_value(ComponentValue const& component_value)
{
    if (component_value.is(Token::Type::Number)) {
        auto const& number = component_value.token();
        if (number.number().is_integer())
            return NumericStyleValue::create_integer(number.to_integer());
        return NumericStyleValue::create_float(number.number_value());
    }

    return {};
}

RefPtr<StyleValue> Parser::parse_identifier_value(ComponentValue const& component_value)
{
    if (component_value.is(Token::Type::Ident)) {
        auto value_id = value_id_from_string(component_value.token().ident());
        if (value_id != ValueID::Invalid)
            return IdentifierStyleValue::create(value_id);
    }

    return {};
}

Optional<Color> Parser::parse_rgb_or_hsl_color(StringView function_name, Vector<ComponentValue> const& component_values)
{
    Token params[4];
    bool legacy_syntax = false;
    auto tokens = TokenStream { component_values };

    tokens.skip_whitespace();
    auto const& component1 = tokens.next_token();

    if (!component1.is(Token::Type::Number)
        && !component1.is(Token::Type::Percentage)
        && !component1.is(Token::Type::Dimension))
        return {};
    params[0] = component1.token();

    tokens.skip_whitespace();
    if (tokens.peek_token().is(Token::Type::Comma)) {
        legacy_syntax = true;
        tokens.next_token();
    }

    tokens.skip_whitespace();
    auto const& component2 = tokens.next_token();
    if (!component2.is(Token::Type::Number) && !component2.is(Token::Type::Percentage))
        return {};
    params[1] = component2.token();

    tokens.skip_whitespace();
    if (legacy_syntax && !tokens.next_token().is(Token::Type::Comma))
        return {};

    tokens.skip_whitespace();
    auto const& component3 = tokens.next_token();
    if (!component3.is(Token::Type::Number) && !component3.is(Token::Type::Percentage))
        return {};
    params[2] = component3.token();

    tokens.skip_whitespace();
    auto const& alpha_separator = tokens.peek_token();
    bool has_comma = alpha_separator.is(Token::Type::Comma);
    bool has_slash = alpha_separator.is(Token::Type::Delim) && alpha_separator.token().delim() == '/';
    if (legacy_syntax ? has_comma : has_slash) {
        tokens.next_token();

        tokens.skip_whitespace();
        auto const& component4 = tokens.next_token();
        if (!component4.is(Token::Type::Number) && !component4.is(Token::Type::Percentage))
            return {};
        params[3] = component4.token();
    }

    tokens.skip_whitespace();
    if (tokens.has_next_token())
        return {};

    if (function_name.equals_ignoring_ascii_case("rgb"sv)
        || function_name.equals_ignoring_ascii_case("rgba"sv)) {

        // https://www.w3.org/TR/css-color-4/#rgb-functions

        u8 a_val = 255;
        if (params[3].is(Token::Type::Number))
            a_val = clamp(lroundf(params[3].number_value() * 255.0f), 0, 255);
        else if (params[3].is(Token::Type::Percentage))
            a_val = clamp(lroundf(params[3].percentage() * 2.55f), 0, 255);

        if (params[0].is(Token::Type::Number)
            && params[1].is(Token::Type::Number)
            && params[2].is(Token::Type::Number)) {

            u8 r_val = clamp(llroundf(params[0].number_value()), 0, 255);
            u8 g_val = clamp(llroundf(params[1].number_value()), 0, 255);
            u8 b_val = clamp(llroundf(params[2].number_value()), 0, 255);

            return Color(r_val, g_val, b_val, a_val);
        }

        if (params[0].is(Token::Type::Percentage)
            && params[1].is(Token::Type::Percentage)
            && params[2].is(Token::Type::Percentage)) {

            u8 r_val = lroundf(clamp(params[0].percentage() * 2.55f, 0, 255));
            u8 g_val = lroundf(clamp(params[1].percentage() * 2.55f, 0, 255));
            u8 b_val = lroundf(clamp(params[2].percentage() * 2.55f, 0, 255));

            return Color(r_val, g_val, b_val, a_val);
        }
    } else if (function_name.equals_ignoring_ascii_case("hsl"sv)
        || function_name.equals_ignoring_ascii_case("hsla"sv)) {

        // https://www.w3.org/TR/css-color-4/#the-hsl-notation

        float a_val = 1.0f;
        if (params[3].is(Token::Type::Number))
            a_val = params[3].number_value();
        else if (params[3].is(Token::Type::Percentage))
            a_val = params[3].percentage() / 100.0f;

        if (params[0].is(Token::Type::Dimension)
            && params[1].is(Token::Type::Percentage)
            && params[2].is(Token::Type::Percentage)) {

            float numeric_value = params[0].dimension_value();
            auto unit_string = params[0].dimension_unit();
            auto angle_type = Angle::unit_from_name(unit_string);

            if (!angle_type.has_value())
                return {};

            auto angle = Angle { numeric_value, angle_type.release_value() };

            float h_val = fmodf(angle.to_degrees(), 360.0f);
            float s_val = params[1].percentage() / 100.0f;
            float l_val = params[2].percentage() / 100.0f;

            return Color::from_hsla(h_val, s_val, l_val, a_val);
        }

        if (params[0].is(Token::Type::Number)
            && params[1].is(Token::Type::Percentage)
            && params[2].is(Token::Type::Percentage)) {

            float h_val = fmodf(params[0].number_value(), 360.0f);
            float s_val = params[1].percentage() / 100.0f;
            float l_val = params[2].percentage() / 100.0f;

            return Color::from_hsla(h_val, s_val, l_val, a_val);
        }
    }

    return {};
}

// https://www.w3.org/TR/CSS2/visufx.html#value-def-shape
RefPtr<StyleValue> Parser::parse_rect_value(ComponentValue const& component_value)
{
    if (!component_value.is_function())
        return {};
    auto const& function = component_value.function();
    if (!function.name().equals_ignoring_ascii_case("rect"sv))
        return {};

    Vector<Length, 4> params;
    auto tokens = TokenStream { function.values() };

    enum class CommaRequirement {
        Unknown,
        RequiresCommas,
        RequiresNoCommas
    };

    enum class Side {
        Top = 0,
        Right = 1,
        Bottom = 2,
        Left = 3
    };

    auto comma_requirement = CommaRequirement::Unknown;

    // In CSS 2.1, the only valid <shape> value is: rect(<top>, <right>, <bottom>, <left>) where
    // <top> and <bottom> specify offsets from the top border edge of the box, and <right>, and
    //  <left> specify offsets from the left border edge of the box.
    for (size_t side = 0; side < 4; side++) {
        tokens.skip_whitespace();

        // <top>, <right>, <bottom>, and <left> may either have a <length> value or 'auto'.
        // Negative lengths are permitted.
        auto current_token = tokens.next_token().token();
        if (current_token.is(Token::Type::Ident) && current_token.ident().equals_ignoring_ascii_case("auto"sv)) {
            params.append(Length::make_auto());
        } else {
            auto maybe_length = parse_length(current_token);
            if (!maybe_length.has_value())
                return {};
            params.append(maybe_length.value());
        }
        tokens.skip_whitespace();

        // The last side, should be no more tokens following it.
        if (static_cast<Side>(side) == Side::Left) {
            if (tokens.has_next_token())
                return {};
            break;
        }

        bool next_is_comma = tokens.peek_token().is(Token::Type::Comma);

        // Authors should separate offset values with commas. User agents must support separation
        // with commas, but may also support separation without commas (but not a combination),
        // because a previous revision of this specification was ambiguous in this respect.
        if (comma_requirement == CommaRequirement::Unknown)
            comma_requirement = next_is_comma ? CommaRequirement::RequiresCommas : CommaRequirement::RequiresNoCommas;

        if (comma_requirement == CommaRequirement::RequiresCommas) {
            if (next_is_comma)
                tokens.next_token();
            else
                return {};
        } else if (comma_requirement == CommaRequirement::RequiresNoCommas) {
            if (next_is_comma)
                return {};
        } else {
            VERIFY_NOT_REACHED();
        }
    }

    return RectStyleValue::create(EdgeRect { params[0], params[1], params[2], params[3] });
}

Optional<Color> Parser::parse_color(ComponentValue const& component_value)
{
    // https://www.w3.org/TR/css-color-4/
    if (component_value.is(Token::Type::Ident)) {
        auto ident = component_value.token().ident();

        auto color = Color::from_string(ident);
        if (color.has_value())
            return color;

    } else if (component_value.is(Token::Type::Hash)) {
        auto color = Color::from_string(DeprecatedString::formatted("#{}", component_value.token().hash_value()));
        if (color.has_value())
            return color;
        return {};

    } else if (component_value.is_function()) {
        auto const& function = component_value.function();
        auto const& values = function.values();

        return parse_rgb_or_hsl_color(function.name(), values);
    }

    // https://quirks.spec.whatwg.org/#the-hashless-hex-color-quirk
    if (m_context.in_quirks_mode() && property_has_quirk(m_context.current_property_id(), Quirk::HashlessHexColor)) {
        // The value of a quirky color is obtained from the possible component values using the following algorithm,
        // aborting on the first step that returns a value:

        // 1. Let cv be the component value.
        auto const& cv = component_value;
        DeprecatedString serialization;
        // 2. If cv is a <number-token> or a <dimension-token>, follow these substeps:
        if (cv.is(Token::Type::Number) || cv.is(Token::Type::Dimension)) {
            // 1. If cv’s type flag is not "integer", return an error.
            //    This means that values that happen to use scientific notation, e.g., 5e5e5e, will fail to parse.
            if (!cv.token().number().is_integer())
                return {};

            // 2. If cv’s value is less than zero, return an error.
            auto value = cv.is(Token::Type::Number) ? cv.token().to_integer() : cv.token().dimension_value_int();
            if (value < 0)
                return {};

            // 3. Let serialization be the serialization of cv’s value, as a base-ten integer using digits 0-9 (U+0030 to U+0039) in the shortest form possible.
            StringBuilder serialization_builder;
            serialization_builder.appendff("{}", value);

            // 4. If cv is a <dimension-token>, append the unit to serialization.
            if (cv.is(Token::Type::Dimension))
                serialization_builder.append(cv.token().dimension_unit());

            // 5. If serialization consists of fewer than six characters, prepend zeros (U+0030) so that it becomes six characters.
            serialization = serialization_builder.to_deprecated_string();
            if (serialization_builder.length() < 6) {
                StringBuilder builder;
                for (size_t i = 0; i < (6 - serialization_builder.length()); i++)
                    builder.append('0');
                builder.append(serialization_builder.string_view());
                serialization = builder.to_deprecated_string();
            }
        }
        // 3. Otherwise, cv is an <ident-token>; let serialization be cv’s value.
        else {
            if (!cv.is(Token::Type::Ident))
                return {};
            serialization = cv.token().ident();
        }

        // 4. If serialization does not consist of three or six characters, return an error.
        if (serialization.length() != 3 && serialization.length() != 6)
            return {};

        // 5. If serialization contains any characters not in the range [0-9A-Fa-f] (U+0030 to U+0039, U+0041 to U+0046, U+0061 to U+0066), return an error.
        for (auto c : serialization) {
            if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')))
                return {};
        }

        // 6. Return the concatenation of "#" (U+0023) and serialization.
        DeprecatedString concatenation = DeprecatedString::formatted("#{}", serialization);
        return Color::from_string(concatenation);
    }

    return {};
}

RefPtr<StyleValue> Parser::parse_color_value(ComponentValue const& component_value)
{
    auto color = parse_color(component_value);
    if (color.has_value())
        return ColorStyleValue::create(color.value());

    return {};
}

RefPtr<StyleValue> Parser::parse_string_value(ComponentValue const& component_value)
{
    if (component_value.is(Token::Type::String))
        return StringStyleValue::create(String::from_utf8(component_value.token().string()).release_value_but_fixme_should_propagate_errors());

    return {};
}

RefPtr<StyleValue> Parser::parse_image_value(ComponentValue const& component_value)
{
    auto url = parse_url_function(component_value, AllowedDataUrlType::Image);
    if (url.has_value())
        return ImageStyleValue::create(url.value());
    auto linear_gradient = parse_linear_gradient_function(component_value);
    if (linear_gradient)
        return linear_gradient;
    auto conic_gradient = parse_conic_gradient_function(component_value);
    if (conic_gradient)
        return conic_gradient;
    return parse_radial_gradient_function(component_value);
}

template<typename ParseFunction>
RefPtr<StyleValue> Parser::parse_comma_separated_value_list(Vector<ComponentValue> const& component_values, ParseFunction parse_one_value)
{
    auto tokens = TokenStream { component_values };
    auto first = parse_one_value(tokens);
    if (!first || !tokens.has_next_token())
        return first;

    StyleValueVector values;
    values.append(first.release_nonnull());

    while (tokens.has_next_token()) {
        if (!tokens.next_token().is(Token::Type::Comma))
            return {};

        if (auto maybe_value = parse_one_value(tokens)) {
            values.append(maybe_value.release_nonnull());
            continue;
        }
        return {};
    }

    return StyleValueList::create(move(values), StyleValueList::Separator::Comma);
}

RefPtr<StyleValue> Parser::parse_simple_comma_separated_value_list(Vector<ComponentValue> const& component_values)
{
    return parse_comma_separated_value_list(component_values, [=, this](auto& tokens) -> RefPtr<StyleValue> {
        auto& token = tokens.next_token();
        if (auto value = parse_css_value(token); value && property_accepts_value(m_context.current_property_id(), *value))
            return value;
        tokens.reconsume_current_input_token();
        return nullptr;
    });
}

RefPtr<StyleValue> Parser::parse_background_value(Vector<ComponentValue> const& component_values)
{
    StyleValueVector background_images;
    StyleValueVector background_positions;
    StyleValueVector background_sizes;
    StyleValueVector background_repeats;
    StyleValueVector background_attachments;
    StyleValueVector background_clips;
    StyleValueVector background_origins;
    RefPtr<StyleValue> background_color;

    // Per-layer values
    RefPtr<StyleValue> background_image;
    RefPtr<StyleValue> background_position;
    RefPtr<StyleValue> background_size;
    RefPtr<StyleValue> background_repeat;
    RefPtr<StyleValue> background_attachment;
    RefPtr<StyleValue> background_clip;
    RefPtr<StyleValue> background_origin;

    bool has_multiple_layers = false;

    auto background_layer_is_valid = [&](bool allow_background_color) -> bool {
        if (allow_background_color) {
            if (background_color)
                return true;
        } else {
            if (background_color)
                return false;
        }
        return background_image || background_position || background_size || background_repeat || background_attachment || background_clip || background_origin;
    };

    auto complete_background_layer = [&]() {
        background_images.append(background_image ? background_image.release_nonnull() : property_initial_value(m_context.realm(), PropertyID::BackgroundImage));
        background_positions.append(background_position ? background_position.release_nonnull() : property_initial_value(m_context.realm(), PropertyID::BackgroundPosition));
        background_sizes.append(background_size ? background_size.release_nonnull() : property_initial_value(m_context.realm(), PropertyID::BackgroundSize));
        background_repeats.append(background_repeat ? background_repeat.release_nonnull() : property_initial_value(m_context.realm(), PropertyID::BackgroundRepeat));
        background_attachments.append(background_attachment ? background_attachment.release_nonnull() : property_initial_value(m_context.realm(), PropertyID::BackgroundAttachment));

        if (!background_origin && !background_clip) {
            background_origin = property_initial_value(m_context.realm(), PropertyID::BackgroundOrigin);
            background_clip = property_initial_value(m_context.realm(), PropertyID::BackgroundClip);
        } else if (!background_clip) {
            background_clip = background_origin;
        }
        background_origins.append(background_origin.release_nonnull());
        background_clips.append(background_clip.release_nonnull());

        background_image = nullptr;
        background_position = nullptr;
        background_size = nullptr;
        background_repeat = nullptr;
        background_attachment = nullptr;
        background_clip = nullptr;
        background_origin = nullptr;
    };

    auto tokens = TokenStream { component_values };
    while (tokens.has_next_token()) {
        auto const& part = tokens.next_token();

        if (part.is(Token::Type::Comma)) {
            has_multiple_layers = true;
            if (!background_layer_is_valid(false))
                return nullptr;
            complete_background_layer();
            continue;
        }

        auto value = parse_css_value(part);
        if (!value)
            return nullptr;

        if (property_accepts_value(PropertyID::BackgroundAttachment, *value)) {
            if (background_attachment)
                return nullptr;
            background_attachment = value.release_nonnull();
            continue;
        }
        if (property_accepts_value(PropertyID::BackgroundColor, *value)) {
            if (background_color)
                return nullptr;
            background_color = value.release_nonnull();
            continue;
        }
        if (property_accepts_value(PropertyID::BackgroundImage, *value)) {
            if (background_image)
                return nullptr;
            background_image = value.release_nonnull();
            continue;
        }
        if (property_accepts_value(PropertyID::BackgroundOrigin, *value)) {
            // background-origin and background-clip accept the same values. From the spec:
            //   "If one <box> value is present then it sets both background-origin and background-clip to that value.
            //    If two values are present, then the first sets background-origin and the second background-clip."
            //        - https://www.w3.org/TR/css-backgrounds-3/#background
            // So, we put the first one in background-origin, then if we get a second, we put it in background-clip.
            // If we only get one, we copy the value before creating the BackgroundStyleValue.
            if (!background_origin) {
                background_origin = value.release_nonnull();
                continue;
            }
            if (!background_clip) {
                background_clip = value.release_nonnull();
                continue;
            }
            return nullptr;
        }
        if (property_accepts_value(PropertyID::BackgroundPosition, *value)) {
            if (background_position)
                return nullptr;
            tokens.reconsume_current_input_token();
            if (auto maybe_background_position = parse_single_background_position_value(tokens)) {
                background_position = maybe_background_position.release_nonnull();

                // Attempt to parse `/ <background-size>`
                auto transaction = tokens.begin_transaction();
                auto& maybe_slash = tokens.next_token();
                if (maybe_slash.is(Token::Type::Delim) && maybe_slash.token().delim() == '/') {
                    if (auto maybe_background_size = parse_single_background_size_value(tokens)) {
                        transaction.commit();
                        background_size = maybe_background_size.release_nonnull();
                        continue;
                    }
                    return nullptr;
                }
                continue;
            }
            return nullptr;
        }
        if (property_accepts_value(PropertyID::BackgroundRepeat, *value)) {
            if (background_repeat)
                return nullptr;
            tokens.reconsume_current_input_token();
            if (auto maybe_repeat = parse_single_background_repeat_value(tokens)) {
                background_repeat = maybe_repeat.release_nonnull();
                continue;
            }
            return nullptr;
        }

        return nullptr;
    }

    if (!background_layer_is_valid(true))
        return nullptr;

    // We only need to create StyleValueLists if there are multiple layers.
    // Otherwise, we can pass the single StyleValues directly.
    if (has_multiple_layers) {
        complete_background_layer();

        if (!background_color)
            background_color = property_initial_value(m_context.realm(), PropertyID::BackgroundColor);
        return BackgroundStyleValue::create(
            background_color.release_nonnull(),
            StyleValueList::create(move(background_images), StyleValueList::Separator::Comma),
            StyleValueList::create(move(background_positions), StyleValueList::Separator::Comma),
            StyleValueList::create(move(background_sizes), StyleValueList::Separator::Comma),
            StyleValueList::create(move(background_repeats), StyleValueList::Separator::Comma),
            StyleValueList::create(move(background_attachments), StyleValueList::Separator::Comma),
            StyleValueList::create(move(background_origins), StyleValueList::Separator::Comma),
            StyleValueList::create(move(background_clips), StyleValueList::Separator::Comma));
    }

    if (!background_color)
        background_color = property_initial_value(m_context.realm(), PropertyID::BackgroundColor);
    if (!background_image)
        background_image = property_initial_value(m_context.realm(), PropertyID::BackgroundImage);
    if (!background_position)
        background_position = property_initial_value(m_context.realm(), PropertyID::BackgroundPosition);
    if (!background_size)
        background_size = property_initial_value(m_context.realm(), PropertyID::BackgroundSize);
    if (!background_repeat)
        background_repeat = property_initial_value(m_context.realm(), PropertyID::BackgroundRepeat);
    if (!background_attachment)
        background_attachment = property_initial_value(m_context.realm(), PropertyID::BackgroundAttachment);

    if (!background_origin && !background_clip) {
        background_origin = property_initial_value(m_context.realm(), PropertyID::BackgroundOrigin);
        background_clip = property_initial_value(m_context.realm(), PropertyID::BackgroundClip);
    } else if (!background_clip) {
        background_clip = background_origin;
    }

    return BackgroundStyleValue::create(
        background_color.release_nonnull(),
        background_image.release_nonnull(),
        background_position.release_nonnull(),
        background_size.release_nonnull(),
        background_repeat.release_nonnull(),
        background_attachment.release_nonnull(),
        background_origin.release_nonnull(),
        background_clip.release_nonnull());
}

RefPtr<StyleValue> Parser::parse_single_background_position_value(TokenStream<ComponentValue>& tokens)
{
    // NOTE: This *looks* like it parses a <position>, but it doesn't. From the spec:
    //      "Note: The background-position property also accepts a three-value syntax.
    //       This has been disallowed generically because it creates parsing ambiguities
    //       when combined with other length or percentage components in a property value."
    //           - https://www.w3.org/TR/css-values-4/#typedef-position
    //       So, we'll need a separate function to parse <position> later.

    auto transaction = tokens.begin_transaction();

    auto to_edge = [](ValueID identifier) -> Optional<PositionEdge> {
        switch (identifier) {
        case ValueID::Top:
            return PositionEdge::Top;
        case ValueID::Bottom:
            return PositionEdge::Bottom;
        case ValueID::Left:
            return PositionEdge::Left;
        case ValueID::Right:
            return PositionEdge::Right;
        default:
            return {};
        }
    };
    auto is_horizontal = [](ValueID identifier) -> bool {
        switch (identifier) {
        case ValueID::Left:
        case ValueID::Right:
            return true;
        default:
            return false;
        }
    };
    auto is_vertical = [](ValueID identifier) -> bool {
        switch (identifier) {
        case ValueID::Top:
        case ValueID::Bottom:
            return true;
        default:
            return false;
        }
    };

    struct EdgeOffset {
        PositionEdge edge;
        LengthPercentage offset;
        bool edge_provided;
        bool offset_provided;
    };

    Optional<EdgeOffset> horizontal;
    Optional<EdgeOffset> vertical;
    bool found_center = false;

    auto const center_offset = Percentage { 50 };
    auto const zero_offset = Length::make_px(0);

    auto value_to_length_percentage = [&](auto value) -> Optional<LengthPercentage> {
        if (value->is_percentage())
            return LengthPercentage { value->as_percentage().percentage() };
        if (value->has_length())
            return LengthPercentage { value->to_length() };
        if (value->is_calculated())
            return LengthPercentage { value->as_calculated() };
        return {};
    };

    while (tokens.has_next_token()) {
        // Check if we're done
        auto seen_items = (horizontal.has_value() ? 1 : 0) + (vertical.has_value() ? 1 : 0) + (found_center ? 1 : 0);
        if (seen_items == 2)
            break;

        auto const& token = tokens.peek_token();
        auto maybe_value = parse_css_value(token);
        if (!maybe_value || !property_accepts_value(PropertyID::BackgroundPosition, *maybe_value))
            break;
        tokens.next_token();
        auto value = maybe_value.release_nonnull();

        auto offset = value_to_length_percentage(value);
        if (offset.has_value()) {
            if (!horizontal.has_value()) {
                horizontal = EdgeOffset { PositionEdge::Left, *offset, false, true };
            } else if (!vertical.has_value()) {
                vertical = EdgeOffset { PositionEdge::Top, *offset, false, true };
            } else {
                return nullptr;
            }
            continue;
        }

        auto try_parse_offset = [&](bool& offset_provided) -> LengthPercentage {
            if (tokens.has_next_token()) {
                auto& token = tokens.peek_token();
                auto maybe_value = parse_css_value(token);
                if (!maybe_value)
                    return zero_offset;
                auto offset = value_to_length_percentage(maybe_value.release_nonnull());
                if (offset.has_value()) {
                    offset_provided = true;
                    tokens.next_token();
                    return *offset;
                }
            }
            return zero_offset;
        };

        if (value->has_identifier()) {
            auto identifier = value->to_identifier();
            if (is_horizontal(identifier)) {
                bool offset_provided = false;
                auto offset = try_parse_offset(offset_provided);
                horizontal = EdgeOffset { *to_edge(identifier), offset, true, offset_provided };
            } else if (is_vertical(identifier)) {
                bool offset_provided = false;
                auto offset = try_parse_offset(offset_provided);
                vertical = EdgeOffset { *to_edge(identifier), offset, true, offset_provided };
            } else if (identifier == ValueID::Center) {
                found_center = true;
            } else {
                return nullptr;
            }
            continue;
        }

        tokens.reconsume_current_input_token();
        break;
    }

    if (found_center) {
        if (horizontal.has_value() && vertical.has_value())
            return nullptr;
        if (!horizontal.has_value())
            horizontal = EdgeOffset { PositionEdge::Left, center_offset, true, false };
        if (!vertical.has_value())
            vertical = EdgeOffset { PositionEdge::Top, center_offset, true, false };
    }

    if (!horizontal.has_value() && !vertical.has_value())
        return nullptr;

    // Unpack `<edge> <length>`:
    // The loop above reads this pattern as a single EdgeOffset, when actually, it should be treated
    // as `x y` if the edge is horizontal, and `y` (with the second token reconsumed) otherwise.
    if (!vertical.has_value() && horizontal->edge_provided && horizontal->offset_provided) {
        // Split into `x y`
        vertical = EdgeOffset { PositionEdge::Top, horizontal->offset, false, true };
        horizontal->offset = zero_offset;
        horizontal->offset_provided = false;
    } else if (!horizontal.has_value() && vertical->edge_provided && vertical->offset_provided) {
        // `y`, reconsume
        vertical->offset = zero_offset;
        vertical->offset_provided = false;
        tokens.reconsume_current_input_token();
    }

    // If only one value is specified, the second value is assumed to be center.
    if (!horizontal.has_value())
        horizontal = EdgeOffset { PositionEdge::Left, center_offset, false, false };
    if (!vertical.has_value())
        vertical = EdgeOffset { PositionEdge::Top, center_offset, false, false };

    transaction.commit();
    return PositionStyleValue::create(
        horizontal->edge, horizontal->offset,
        vertical->edge, vertical->offset);
}

RefPtr<StyleValue> Parser::parse_single_background_repeat_value(TokenStream<ComponentValue>& tokens)
{
    auto transaction = tokens.begin_transaction();

    auto is_directional_repeat = [](StyleValue const& value) -> bool {
        auto value_id = value.to_identifier();
        return value_id == ValueID::RepeatX || value_id == ValueID::RepeatY;
    };

    auto as_repeat = [](ValueID identifier) -> Optional<Repeat> {
        switch (identifier) {
        case ValueID::NoRepeat:
            return Repeat::NoRepeat;
        case ValueID::Repeat:
            return Repeat::Repeat;
        case ValueID::Round:
            return Repeat::Round;
        case ValueID::Space:
            return Repeat::Space;
        default:
            return {};
        }
    };

    auto const& token = tokens.next_token();
    auto maybe_x_value = parse_css_value(token);
    if (!maybe_x_value || !property_accepts_value(PropertyID::BackgroundRepeat, *maybe_x_value))
        return nullptr;
    auto x_value = maybe_x_value.release_nonnull();

    if (is_directional_repeat(*x_value)) {
        auto value_id = x_value->to_identifier();
        transaction.commit();
        return BackgroundRepeatStyleValue::create(
            value_id == ValueID::RepeatX ? Repeat::Repeat : Repeat::NoRepeat,
            value_id == ValueID::RepeatX ? Repeat::NoRepeat : Repeat::Repeat);
    }

    auto x_repeat = as_repeat(x_value->to_identifier());
    if (!x_repeat.has_value())
        return nullptr;

    // See if we have a second value for Y
    auto const& second_token = tokens.peek_token();
    auto maybe_y_value = parse_css_value(second_token);
    if (!maybe_y_value || !property_accepts_value(PropertyID::BackgroundRepeat, *maybe_y_value)) {
        // We don't have a second value, so use x for both
        transaction.commit();
        return BackgroundRepeatStyleValue::create(x_repeat.value(), x_repeat.value());
    }
    tokens.next_token();
    auto y_value = maybe_y_value.release_nonnull();
    if (is_directional_repeat(*y_value))
        return nullptr;

    auto y_repeat = as_repeat(y_value->to_identifier());
    if (!y_repeat.has_value())
        return nullptr;

    transaction.commit();
    return BackgroundRepeatStyleValue::create(x_repeat.value(), y_repeat.value());
}

RefPtr<StyleValue> Parser::parse_single_background_size_value(TokenStream<ComponentValue>& tokens)
{
    auto transaction = tokens.begin_transaction();

    auto get_length_percentage = [](StyleValue& style_value) -> Optional<LengthPercentage> {
        if (style_value.is_percentage())
            return LengthPercentage { style_value.as_percentage().percentage() };
        if (style_value.has_length())
            return LengthPercentage { style_value.to_length() };
        return {};
    };

    auto maybe_x_value = parse_css_value(tokens.next_token());
    if (!maybe_x_value || !property_accepts_value(PropertyID::BackgroundSize, *maybe_x_value))
        return nullptr;
    auto x_value = maybe_x_value.release_nonnull();

    if (x_value->to_identifier() == ValueID::Cover || x_value->to_identifier() == ValueID::Contain) {
        transaction.commit();
        return x_value;
    }

    auto maybe_y_value = parse_css_value(tokens.peek_token());
    if (!maybe_y_value || !property_accepts_value(PropertyID::BackgroundSize, *maybe_y_value)) {
        auto x_size = get_length_percentage(*x_value);
        if (!x_size.has_value())
            return nullptr;

        transaction.commit();
        return BackgroundSizeStyleValue::create(x_size.value(), x_size.value());
    }
    tokens.next_token();

    auto y_value = maybe_y_value.release_nonnull();
    auto x_size = get_length_percentage(*x_value);
    auto y_size = get_length_percentage(*y_value);

    if (!x_size.has_value() || !y_size.has_value())
        return nullptr;

    transaction.commit();
    return BackgroundSizeStyleValue::create(x_size.release_value(), y_size.release_value());
}

RefPtr<StyleValue> Parser::parse_border_value(Vector<ComponentValue> const& component_values)
{
    if (component_values.size() > 3)
        return nullptr;

    RefPtr<StyleValue> border_width;
    RefPtr<StyleValue> border_color;
    RefPtr<StyleValue> border_style;

    for (auto const& part : component_values) {
        auto value = parse_css_value(part);
        if (!value)
            return nullptr;

        if (property_accepts_value(PropertyID::BorderWidth, *value)) {
            if (border_width)
                return nullptr;
            border_width = value.release_nonnull();
            continue;
        }
        if (property_accepts_value(PropertyID::BorderColor, *value)) {
            if (border_color)
                return nullptr;
            border_color = value.release_nonnull();
            continue;
        }
        if (property_accepts_value(PropertyID::BorderStyle, *value)) {
            if (border_style)
                return nullptr;
            border_style = value.release_nonnull();
            continue;
        }

        return nullptr;
    }

    if (!border_width)
        border_width = property_initial_value(m_context.realm(), PropertyID::BorderWidth);
    if (!border_style)
        border_style = property_initial_value(m_context.realm(), PropertyID::BorderStyle);
    if (!border_color)
        border_color = property_initial_value(m_context.realm(), PropertyID::BorderColor);

    return BorderStyleValue::create(border_width.release_nonnull(), border_style.release_nonnull(), border_color.release_nonnull());
}

RefPtr<StyleValue> Parser::parse_border_radius_value(Vector<ComponentValue> const& component_values)
{
    if (component_values.size() == 2) {
        auto horizontal = parse_dimension(component_values[0]);
        auto vertical = parse_dimension(component_values[1]);
        if (horizontal.has_value() && horizontal->is_length_percentage() && vertical.has_value() && vertical->is_length_percentage())
            return BorderRadiusStyleValue::create(horizontal->length_percentage(), vertical->length_percentage());

        return nullptr;
    }

    if (component_values.size() == 1) {
        auto radius = parse_dimension(component_values[0]);
        if (radius.has_value() && radius->is_length_percentage())
            return BorderRadiusStyleValue::create(radius->length_percentage(), radius->length_percentage());
        return nullptr;
    }

    return nullptr;
}

RefPtr<StyleValue> Parser::parse_border_radius_shorthand_value(Vector<ComponentValue> const& component_values)
{
    auto top_left = [&](Vector<LengthPercentage>& radii) { return radii[0]; };
    auto top_right = [&](Vector<LengthPercentage>& radii) {
        switch (radii.size()) {
        case 4:
        case 3:
        case 2:
            return radii[1];
        case 1:
            return radii[0];
        default:
            VERIFY_NOT_REACHED();
        }
    };
    auto bottom_right = [&](Vector<LengthPercentage>& radii) {
        switch (radii.size()) {
        case 4:
        case 3:
            return radii[2];
        case 2:
        case 1:
            return radii[0];
        default:
            VERIFY_NOT_REACHED();
        }
    };
    auto bottom_left = [&](Vector<LengthPercentage>& radii) {
        switch (radii.size()) {
        case 4:
            return radii[3];
        case 3:
        case 2:
            return radii[1];
        case 1:
            return radii[0];
        default:
            VERIFY_NOT_REACHED();
        }
    };

    Vector<LengthPercentage> horizontal_radii;
    Vector<LengthPercentage> vertical_radii;
    bool reading_vertical = false;

    for (auto const& value : component_values) {
        if (value.is(Token::Type::Delim) && value.token().delim() == '/') {
            if (reading_vertical || horizontal_radii.is_empty())
                return nullptr;

            reading_vertical = true;
            continue;
        }

        auto maybe_dimension = parse_dimension(value);
        if (!maybe_dimension.has_value() || !maybe_dimension->is_length_percentage())
            return nullptr;
        if (reading_vertical) {
            vertical_radii.append(maybe_dimension->length_percentage());
        } else {
            horizontal_radii.append(maybe_dimension->length_percentage());
        }
    }

    if (horizontal_radii.size() > 4 || vertical_radii.size() > 4
        || horizontal_radii.is_empty()
        || (reading_vertical && vertical_radii.is_empty()))
        return nullptr;

    auto top_left_radius = BorderRadiusStyleValue::create(top_left(horizontal_radii),
        vertical_radii.is_empty() ? top_left(horizontal_radii) : top_left(vertical_radii));
    auto top_right_radius = BorderRadiusStyleValue::create(top_right(horizontal_radii),
        vertical_radii.is_empty() ? top_right(horizontal_radii) : top_right(vertical_radii));
    auto bottom_right_radius = BorderRadiusStyleValue::create(bottom_right(horizontal_radii),
        vertical_radii.is_empty() ? bottom_right(horizontal_radii) : bottom_right(vertical_radii));
    auto bottom_left_radius = BorderRadiusStyleValue::create(bottom_left(horizontal_radii),
        vertical_radii.is_empty() ? bottom_left(horizontal_radii) : bottom_left(vertical_radii));

    return BorderRadiusShorthandStyleValue::create(move(top_left_radius), move(top_right_radius), move(bottom_right_radius), move(bottom_left_radius));
}

RefPtr<StyleValue> Parser::parse_shadow_value(Vector<ComponentValue> const& component_values, AllowInsetKeyword allow_inset_keyword)
{
    // "none"
    if (component_values.size() == 1 && component_values.first().is(Token::Type::Ident)) {
        auto ident = parse_identifier_value(component_values.first());
        if (ident && ident->to_identifier() == ValueID::None)
            return ident;
    }

    return parse_comma_separated_value_list(component_values, [this, allow_inset_keyword](auto& tokens) {
        return parse_single_shadow_value(tokens, allow_inset_keyword);
    });
}

RefPtr<StyleValue> Parser::parse_single_shadow_value(TokenStream<ComponentValue>& tokens, AllowInsetKeyword allow_inset_keyword)
{
    auto transaction = tokens.begin_transaction();

    Optional<Color> color;
    Optional<Length> offset_x;
    Optional<Length> offset_y;
    Optional<Length> blur_radius;
    Optional<Length> spread_distance;
    Optional<ShadowPlacement> placement;

    while (tokens.has_next_token()) {
        auto const& token = tokens.peek_token();

        if (auto maybe_color = parse_color(token); maybe_color.has_value()) {
            if (color.has_value())
                return nullptr;
            color = maybe_color.release_value();
            tokens.next_token();
            continue;
        }

        if (auto maybe_offset_x = parse_length(token); maybe_offset_x.has_value()) {
            // horizontal offset
            if (offset_x.has_value())
                return nullptr;
            offset_x = maybe_offset_x.release_value();
            tokens.next_token();

            // vertical offset
            if (!tokens.has_next_token())
                return nullptr;
            auto maybe_offset_y = parse_length(tokens.peek_token());
            if (!maybe_offset_y.has_value())
                return nullptr;
            offset_y = maybe_offset_y.release_value();
            tokens.next_token();

            // blur radius (optional)
            if (!tokens.has_next_token())
                break;
            auto maybe_blur_radius = parse_length(tokens.peek_token());
            if (!maybe_blur_radius.has_value())
                continue;
            blur_radius = maybe_blur_radius.release_value();
            tokens.next_token();

            // spread distance (optional)
            if (!tokens.has_next_token())
                break;
            auto maybe_spread_distance = parse_length(tokens.peek_token());
            if (!maybe_spread_distance.has_value())
                continue;
            spread_distance = maybe_spread_distance.release_value();
            tokens.next_token();

            continue;
        }

        if (allow_inset_keyword == AllowInsetKeyword::Yes
            && token.is(Token::Type::Ident) && token.token().ident().equals_ignoring_ascii_case("inset"sv)) {
            if (placement.has_value())
                return nullptr;
            placement = ShadowPlacement::Inner;
            tokens.next_token();
            continue;
        }

        if (token.is(Token::Type::Comma))
            break;

        return nullptr;
    }

    // FIXME: If color is absent, default to `currentColor`
    if (!color.has_value())
        color = Color::NamedColor::Black;

    // x/y offsets are required
    if (!offset_x.has_value() || !offset_y.has_value())
        return nullptr;

    // Other lengths default to 0
    if (!blur_radius.has_value())
        blur_radius = Length::make_px(0);
    if (!spread_distance.has_value())
        spread_distance = Length::make_px(0);

    // Placement is outer by default
    if (!placement.has_value())
        placement = ShadowPlacement::Outer;

    transaction.commit();
    return ShadowStyleValue::create(color.release_value(), offset_x.release_value(), offset_y.release_value(), blur_radius.release_value(), spread_distance.release_value(), placement.release_value());
}

RefPtr<StyleValue> Parser::parse_content_value(Vector<ComponentValue> const& component_values)
{
    // FIXME: `content` accepts several kinds of function() type, which we don't handle in property_accepts_value() yet.

    auto is_single_value_identifier = [](ValueID identifier) -> bool {
        switch (identifier) {
        case ValueID::None:
        case ValueID::Normal:
            return true;
        default:
            return false;
        }
    };

    if (component_values.size() == 1) {
        if (auto identifier = parse_identifier_value(component_values.first())) {
            if (is_single_value_identifier(identifier->to_identifier()))
                return identifier;
        }
    }

    StyleValueVector content_values;
    StyleValueVector alt_text_values;
    bool in_alt_text = false;

    for (auto const& value : component_values) {
        if (value.is(Token::Type::Delim) && value.token().delim() == '/') {
            if (in_alt_text || content_values.is_empty())
                return {};
            in_alt_text = true;
            continue;
        }
        auto style_value = parse_css_value(value);
        if (style_value && property_accepts_value(PropertyID::Content, *style_value)) {
            if (is_single_value_identifier(style_value->to_identifier()))
                return {};

            if (in_alt_text) {
                alt_text_values.append(style_value.release_nonnull());
            } else {
                content_values.append(style_value.release_nonnull());
            }
            continue;
        }

        return {};
    }

    if (content_values.is_empty())
        return {};
    if (in_alt_text && alt_text_values.is_empty())
        return {};

    RefPtr<StyleValueList> alt_text;
    if (!alt_text_values.is_empty())
        alt_text = StyleValueList::create(move(alt_text_values), StyleValueList::Separator::Space);

    return ContentStyleValue::create(StyleValueList::create(move(content_values), StyleValueList::Separator::Space), move(alt_text));
}

RefPtr<StyleValue> Parser::parse_filter_value_list_value(Vector<ComponentValue> const& component_values)
{
    if (component_values.size() == 1 && component_values.first().is(Token::Type::Ident)) {
        auto ident = parse_identifier_value(component_values.first());
        if (ident && ident->to_identifier() == ValueID::None)
            return ident;
    }

    TokenStream tokens { component_values };

    // FIXME: <url>s are ignored for now
    // <filter-value-list> = [ <filter-function> | <url> ]+

    enum class FilterToken {
        // Color filters:
        Brightness,
        Contrast,
        Grayscale,
        Invert,
        Opacity,
        Saturate,
        Sepia,
        // Special filters:
        Blur,
        DropShadow,
        HueRotate
    };

    auto filter_token_to_operation = [&](auto filter) {
        VERIFY(to_underlying(filter) < to_underlying(FilterToken::Blur));
        return static_cast<Filter::Color::Operation>(filter);
    };

    auto parse_number_percentage = [&](auto& token) -> Optional<NumberPercentage> {
        if (token.is(Token::Type::Percentage))
            return NumberPercentage(Percentage(token.token().percentage()));
        if (token.is(Token::Type::Number))
            return NumberPercentage(Number(Number::Type::Number, token.token().number_value()));
        return {};
    };

    auto parse_filter_function_name = [&](auto name) -> Optional<FilterToken> {
        if (name.equals_ignoring_ascii_case("blur"sv))
            return FilterToken::Blur;
        if (name.equals_ignoring_ascii_case("brightness"sv))
            return FilterToken::Brightness;
        if (name.equals_ignoring_ascii_case("contrast"sv))
            return FilterToken::Contrast;
        if (name.equals_ignoring_ascii_case("drop-shadow"sv))
            return FilterToken::DropShadow;
        if (name.equals_ignoring_ascii_case("grayscale"sv))
            return FilterToken::Grayscale;
        if (name.equals_ignoring_ascii_case("hue-rotate"sv))
            return FilterToken::HueRotate;
        if (name.equals_ignoring_ascii_case("invert"sv))
            return FilterToken::Invert;
        if (name.equals_ignoring_ascii_case("opacity"sv))
            return FilterToken::Opacity;
        if (name.equals_ignoring_ascii_case("saturate"sv))
            return FilterToken::Saturate;
        if (name.equals_ignoring_ascii_case("sepia"sv))
            return FilterToken::Sepia;
        return {};
    };

    auto parse_filter_function = [&](auto filter_token, auto function_values) -> Optional<FilterFunction> {
        TokenStream tokens { function_values };
        tokens.skip_whitespace();

        auto if_no_more_tokens_return = [&](auto filter) -> Optional<FilterFunction> {
            tokens.skip_whitespace();
            if (tokens.has_next_token())
                return {};
            return filter;
        };

        if (filter_token == FilterToken::Blur) {
            // blur( <length>? )
            if (!tokens.has_next_token())
                return Filter::Blur {};
            auto blur_radius = parse_length(tokens.next_token());
            if (!blur_radius.has_value())
                return {};
            return if_no_more_tokens_return(Filter::Blur { *blur_radius });
        } else if (filter_token == FilterToken::DropShadow) {
            if (!tokens.has_next_token())
                return {};
            auto next_token = [&]() -> auto&
            {
                auto& token = tokens.next_token();
                tokens.skip_whitespace();
                return token;
            };
            // drop-shadow( [ <color>? && <length>{2,3} ] )
            // Note: The following code is a little awkward to allow the color to be before or after the lengths.
            auto& first_param = next_token();
            Optional<Length> maybe_radius = {};
            auto maybe_color = parse_color(first_param);
            auto x_offset = parse_length(maybe_color.has_value() ? next_token() : first_param);
            if (!x_offset.has_value() || !tokens.has_next_token()) {
                return {};
            }
            auto y_offset = parse_length(next_token());
            if (!y_offset.has_value()) {
                return {};
            }
            if (tokens.has_next_token()) {
                auto& token = next_token();
                maybe_radius = parse_length(token);
                if (!maybe_color.has_value() && (!maybe_radius.has_value() || tokens.has_next_token())) {
                    maybe_color = parse_color(!maybe_radius.has_value() ? token : next_token());
                    if (!maybe_color.has_value()) {
                        return {};
                    }
                } else if (!maybe_radius.has_value()) {
                    return {};
                }
            }
            return if_no_more_tokens_return(Filter::DropShadow { *x_offset, *y_offset, maybe_radius, maybe_color });
        } else if (filter_token == FilterToken::HueRotate) {
            // hue-rotate( [ <angle> | <zero> ]? )
            if (!tokens.has_next_token())
                return Filter::HueRotate {};
            auto& token = tokens.next_token();
            if (token.is(Token::Type::Number)) {
                // hue-rotate(0)
                auto number = token.token().number();
                if (number.is_integer() && number.integer_value() == 0)
                    return if_no_more_tokens_return(Filter::HueRotate { Filter::HueRotate::Zero {} });
                return {};
            }
            if (!token.is(Token::Type::Dimension))
                return {};
            float angle_value = token.token().dimension_value();
            auto angle_unit_name = token.token().dimension_unit();
            auto angle_unit = Angle::unit_from_name(angle_unit_name);
            if (!angle_unit.has_value())
                return {};
            Angle angle { angle_value, angle_unit.release_value() };
            return if_no_more_tokens_return(Filter::HueRotate { angle });
        } else {
            // Simple filters:
            // brightness( <number-percentage>? )
            // contrast( <number-percentage>? )
            // grayscale( <number-percentage>? )
            // invert( <number-percentage>? )
            // opacity( <number-percentage>? )
            // sepia( <number-percentage>? )
            // saturate( <number-percentage>? )
            if (!tokens.has_next_token())
                return Filter::Color { filter_token_to_operation(filter_token) };
            auto amount = parse_number_percentage(tokens.next_token());
            if (!amount.has_value())
                return {};
            return if_no_more_tokens_return(Filter::Color { filter_token_to_operation(filter_token), *amount });
        }
    };

    Vector<FilterFunction> filter_value_list {};

    while (tokens.has_next_token()) {
        tokens.skip_whitespace();
        if (!tokens.has_next_token())
            break;
        auto& token = tokens.next_token();
        if (!token.is_function())
            return {};
        auto filter_token = parse_filter_function_name(token.function().name());
        if (!filter_token.has_value())
            return {};
        auto filter_function = parse_filter_function(*filter_token, token.function().values());
        if (!filter_function.has_value())
            return {};
        filter_value_list.append(*filter_function);
    }

    if (filter_value_list.is_empty())
        return {};

    return FilterValueListStyleValue::create(move(filter_value_list));
}

RefPtr<StyleValue> Parser::parse_flex_value(Vector<ComponentValue> const& component_values)
{
    if (component_values.size() == 1) {
        auto value = parse_css_value(component_values[0]);
        if (!value)
            return nullptr;

        switch (value->to_identifier()) {
        case ValueID::Auto: {
            auto one = NumericStyleValue::create_integer(1);
            return FlexStyleValue::create(one, one, IdentifierStyleValue::create(ValueID::Auto));
        }
        case ValueID::None: {
            auto zero = NumericStyleValue::create_integer(0);
            return FlexStyleValue::create(zero, zero, IdentifierStyleValue::create(ValueID::Auto));
        }
        default:
            break;
        }
    }

    RefPtr<StyleValue> flex_grow;
    RefPtr<StyleValue> flex_shrink;
    RefPtr<StyleValue> flex_basis;

    for (size_t i = 0; i < component_values.size(); ++i) {
        auto value = parse_css_value(component_values[i]);
        if (!value)
            return nullptr;

        // Zero is a valid value for basis, but only if grow and shrink are already specified.
        if (value->has_number() && value->to_number() == 0) {
            if (flex_grow && flex_shrink && !flex_basis) {
                flex_basis = LengthStyleValue::create(Length::make_px(0));
                continue;
            }
        }

        if (property_accepts_value(PropertyID::FlexGrow, *value)) {
            if (flex_grow)
                return nullptr;
            flex_grow = value.release_nonnull();

            // Flex-shrink may optionally follow directly after.
            if (i + 1 < component_values.size()) {
                auto second_value = parse_css_value(component_values[i + 1]);
                if (second_value && property_accepts_value(PropertyID::FlexShrink, *second_value)) {
                    flex_shrink = second_value.release_nonnull();
                    i++;
                }
            }
            continue;
        }

        if (property_accepts_value(PropertyID::FlexBasis, *value)) {
            if (flex_basis)
                return nullptr;
            flex_basis = value.release_nonnull();
            continue;
        }

        return nullptr;
    }

    if (!flex_grow)
        flex_grow = property_initial_value(m_context.realm(), PropertyID::FlexGrow);
    if (!flex_shrink)
        flex_shrink = property_initial_value(m_context.realm(), PropertyID::FlexShrink);
    if (!flex_basis)
        flex_basis = property_initial_value(m_context.realm(), PropertyID::FlexBasis);

    return FlexStyleValue::create(flex_grow.release_nonnull(), flex_shrink.release_nonnull(), flex_basis.release_nonnull());
}

RefPtr<StyleValue> Parser::parse_flex_flow_value(Vector<ComponentValue> const& component_values)
{
    if (component_values.size() > 2)
        return nullptr;

    RefPtr<StyleValue> flex_direction;
    RefPtr<StyleValue> flex_wrap;

    for (auto const& part : component_values) {
        auto value = parse_css_value(part);
        if (!value)
            return nullptr;
        if (property_accepts_value(PropertyID::FlexDirection, *value)) {
            if (flex_direction)
                return nullptr;
            flex_direction = value.release_nonnull();
            continue;
        }
        if (property_accepts_value(PropertyID::FlexWrap, *value)) {
            if (flex_wrap)
                return nullptr;
            flex_wrap = value.release_nonnull();
            continue;
        }
    }

    if (!flex_direction)
        flex_direction = property_initial_value(m_context.realm(), PropertyID::FlexDirection);
    if (!flex_wrap)
        flex_wrap = property_initial_value(m_context.realm(), PropertyID::FlexWrap);

    return FlexFlowStyleValue::create(flex_direction.release_nonnull(), flex_wrap.release_nonnull());
}

static bool is_generic_font_family(ValueID identifier)
{
    switch (identifier) {
    case ValueID::Cursive:
    case ValueID::Fantasy:
    case ValueID::Monospace:
    case ValueID::Serif:
    case ValueID::SansSerif:
    case ValueID::UiMonospace:
    case ValueID::UiRounded:
    case ValueID::UiSerif:
    case ValueID::UiSansSerif:
        return true;
    default:
        return false;
    }
}

RefPtr<StyleValue> Parser::parse_font_value(Vector<ComponentValue> const& component_values)
{
    RefPtr<StyleValue> font_stretch;
    RefPtr<StyleValue> font_style;
    RefPtr<StyleValue> font_weight;
    RefPtr<StyleValue> font_size;
    RefPtr<StyleValue> line_height;
    RefPtr<StyleValue> font_families;
    RefPtr<StyleValue> font_variant;

    // FIXME: Handle system fonts. (caption, icon, menu, message-box, small-caption, status-bar)

    // Several sub-properties can be "normal", and appear in any order: style, variant, weight, stretch
    // So, we have to handle that separately.
    int normal_count = 0;

    for (size_t i = 0; i < component_values.size(); ++i) {
        auto value = parse_css_value(component_values[i]);
        if (!value)
            return nullptr;

        if (value->to_identifier() == ValueID::Normal) {
            normal_count++;
            continue;
        }
        // FIXME: Handle angle parameter to `oblique`: https://www.w3.org/TR/css-fonts-4/#font-style-prop
        if (property_accepts_value(PropertyID::FontStyle, *value)) {
            if (font_style)
                return nullptr;
            font_style = value.release_nonnull();
            continue;
        }
        if (property_accepts_value(PropertyID::FontWeight, *value)) {
            if (font_weight)
                return nullptr;
            font_weight = value.release_nonnull();
            continue;
        }
        if (property_accepts_value(PropertyID::FontVariant, *value)) {
            if (font_variant)
                return nullptr;
            font_variant = value.release_nonnull();
            continue;
        }
        if (property_accepts_value(PropertyID::FontSize, *value)) {
            if (font_size)
                return nullptr;
            font_size = value.release_nonnull();

            // Consume `/ line-height` if present
            if (i + 2 < component_values.size()) {
                auto const& maybe_solidus = component_values[i + 1];
                if (maybe_solidus.is(Token::Type::Delim) && maybe_solidus.token().delim() == '/') {
                    auto maybe_line_height = parse_css_value(component_values[i + 2]);
                    if (!(maybe_line_height && property_accepts_value(PropertyID::LineHeight, *maybe_line_height)))
                        return nullptr;
                    line_height = maybe_line_height.release_nonnull();
                    i += 2;
                }
            }

            // Consume font-families
            auto maybe_font_families = parse_font_family_value(component_values, i + 1);
            if (!maybe_font_families)
                return nullptr;
            font_families = maybe_font_families.release_nonnull();
            break;
        }
        if (property_accepts_value(PropertyID::FontStretch, *value)) {
            if (font_stretch)
                return nullptr;
            font_stretch = value.release_nonnull();
            continue;
        }
        return nullptr;
    }

    // Since normal is the default value for all the properties that can have it, we don't have to actually
    // set anything to normal here. It'll be set when we create the FontStyleValue below.
    // We just need to make sure we were not given more normals than will fit.
    int unset_value_count = (font_style ? 0 : 1) + (font_weight ? 0 : 1);
    if (unset_value_count < normal_count)
        return nullptr;

    if (!font_size || !font_families)
        return nullptr;

    if (!font_stretch)
        font_stretch = property_initial_value(m_context.realm(), PropertyID::FontStretch);
    if (!font_style)
        font_style = property_initial_value(m_context.realm(), PropertyID::FontStyle);
    if (!font_weight)
        font_weight = property_initial_value(m_context.realm(), PropertyID::FontWeight);
    if (!line_height)
        line_height = property_initial_value(m_context.realm(), PropertyID::LineHeight);

    return FontStyleValue::create(font_stretch.release_nonnull(), font_style.release_nonnull(), font_weight.release_nonnull(), font_size.release_nonnull(), line_height.release_nonnull(), font_families.release_nonnull());
}

RefPtr<StyleValue> Parser::parse_font_family_value(Vector<ComponentValue> const& component_values, size_t start_index)
{
    auto is_comma_or_eof = [&](size_t i) -> bool {
        if (i < component_values.size()) {
            auto const& maybe_comma = component_values[i];
            if (!maybe_comma.is(Token::Type::Comma))
                return false;
        }
        return true;
    };

    // Note: Font-family names can either be a quoted string, or a keyword, or a series of custom-idents.
    // eg, these are equivalent:
    //     font-family: my cool     font\!, serif;
    //     font-family: "my cool font!", serif;
    StyleValueVector font_families;
    Vector<DeprecatedString> current_name_parts;
    for (size_t i = start_index; i < component_values.size(); ++i) {
        auto const& part = component_values[i];

        if (part.is(Token::Type::String)) {
            // `font-family: my cool "font";` is invalid.
            if (!current_name_parts.is_empty())
                return nullptr;
            if (!is_comma_or_eof(i + 1))
                return nullptr;
            font_families.append(StringStyleValue::create(String::from_utf8(part.token().string()).release_value_but_fixme_should_propagate_errors()));
            i++;
            continue;
        }
        if (part.is(Token::Type::Ident)) {
            // If this is a valid identifier, it's NOT a custom-ident and can't be part of a larger name.
            auto maybe_ident = parse_css_value(part);
            if (maybe_ident) {
                // CSS-wide keywords are not allowed
                if (maybe_ident->is_builtin())
                    return nullptr;
                if (is_generic_font_family(maybe_ident->to_identifier())) {
                    // Can't have a generic-font-name as a token in an unquoted font name.
                    if (!current_name_parts.is_empty())
                        return nullptr;
                    if (!is_comma_or_eof(i + 1))
                        return nullptr;
                    font_families.append(maybe_ident.release_nonnull());
                    i++;
                    continue;
                }
            }
            current_name_parts.append(part.token().ident());
            continue;
        }
        if (part.is(Token::Type::Comma)) {
            if (current_name_parts.is_empty())
                return nullptr;
            font_families.append(StringStyleValue::create(String::from_utf8(DeprecatedString::join(' ', current_name_parts)).release_value_but_fixme_should_propagate_errors()));
            current_name_parts.clear();
            // Can't have a trailing comma
            if (i + 1 == component_values.size())
                return nullptr;
            continue;
        }
    }

    if (!current_name_parts.is_empty()) {
        font_families.append(StringStyleValue::create(String::from_utf8(DeprecatedString::join(' ', current_name_parts)).release_value_but_fixme_should_propagate_errors()));
        current_name_parts.clear();
    }

    if (font_families.is_empty())
        return nullptr;
    return StyleValueList::create(move(font_families), StyleValueList::Separator::Comma);
}

CSSRule* Parser::parse_font_face_rule(TokenStream<ComponentValue>& tokens)
{
    auto declarations_and_at_rules = parse_a_list_of_declarations(tokens);

    Optional<FlyString> font_family;
    Vector<FontFace::Source> src;
    Vector<UnicodeRange> unicode_range;

    for (auto& declaration_or_at_rule : declarations_and_at_rules) {
        if (declaration_or_at_rule.is_at_rule()) {
            dbgln_if(CSS_PARSER_DEBUG, "CSSParser: CSS at-rules are not allowed in @font-family; discarding.");
            continue;
        }

        auto const& declaration = declaration_or_at_rule.declaration();
        if (declaration.name().equals_ignoring_ascii_case("font-family"sv)) {
            // FIXME: This is very similar to, but different from, the logic in parse_font_family_value().
            //        Ideally they could share code.
            Vector<DeprecatedString> font_family_parts;
            bool had_syntax_error = false;
            for (size_t i = 0; i < declaration.values().size(); ++i) {
                auto const& part = declaration.values()[i];
                if (part.is(Token::Type::Whitespace))
                    continue;
                if (part.is(Token::Type::String)) {
                    if (!font_family_parts.is_empty()) {
                        dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
                        had_syntax_error = true;
                        break;
                    }
                    font_family_parts.append(part.token().string());
                    continue;
                }
                if (part.is(Token::Type::Ident)) {
                    if (is_builtin(part.token().ident())) {
                        dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
                        had_syntax_error = true;
                        break;
                    }
                    auto value_id = value_id_from_string(part.token().ident());
                    if (is_generic_font_family(value_id)) {
                        dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
                        had_syntax_error = true;
                        break;
                    }
                    font_family_parts.append(part.token().ident());
                    continue;
                }

                dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
                had_syntax_error = true;
                break;
            }
            if (had_syntax_error || font_family_parts.is_empty())
                continue;

            font_family = String::join(' ', font_family_parts).release_value_but_fixme_should_propagate_errors();
            continue;
        }
        if (declaration.name().equals_ignoring_ascii_case("src"sv)) {
            TokenStream token_stream { declaration.values() };
            Vector<FontFace::Source> supported_sources = parse_font_face_src(token_stream);
            if (!supported_sources.is_empty())
                src = move(supported_sources);
            continue;
        }
        if (declaration.name().equals_ignoring_ascii_case("unicode-range"sv)) {
            Vector<UnicodeRange> unicode_ranges;
            bool unicode_range_invalid = false;
            TokenStream all_tokens { declaration.values() };
            auto range_token_lists = parse_a_comma_separated_list_of_component_values(all_tokens);
            for (auto& range_tokens : range_token_lists) {
                TokenStream range_token_stream { range_tokens };
                auto maybe_unicode_range = parse_unicode_range(range_token_stream);
                if (!maybe_unicode_range.has_value()) {
                    dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face unicode-range format invalid; discarding.");
                    unicode_range_invalid = true;
                    break;
                }
                unicode_ranges.append(maybe_unicode_range.release_value());
            }

            if (unicode_range_invalid || unicode_ranges.is_empty())
                continue;

            unicode_range = move(unicode_ranges);
            continue;
        }

        dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Unrecognized descriptor '{}' in @font-family; discarding.", declaration.name());
    }

    if (!font_family.has_value()) {
        dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Failed to parse @font-face: no font-family!");
        return {};
    }

    if (unicode_range.is_empty()) {
        unicode_range.empend(0x0u, 0x10FFFFu);
    }

    return CSSFontFaceRule::create(m_context.realm(), FontFace { font_family.release_value(), move(src), move(unicode_range) }).release_value_but_fixme_should_propagate_errors();
}

Vector<FontFace::Source> Parser::parse_font_face_src(TokenStream<ComponentValue>& component_values)
{
    // FIXME: Get this information from the system somehow?
    // Format-name table: https://www.w3.org/TR/css-fonts-4/#font-format-definitions
    auto font_format_is_supported = [](StringView name) {
        // The spec requires us to treat opentype and truetype as synonymous.
        if (name.is_one_of_ignoring_ascii_case("opentype"sv, "truetype"sv, "woff"sv))
            return true;
        return false;
    };

    Vector<FontFace::Source> supported_sources;

    auto list_of_source_token_lists = parse_a_comma_separated_list_of_component_values(component_values);
    for (auto const& source_token_list : list_of_source_token_lists) {
        TokenStream source_tokens { source_token_list };
        source_tokens.skip_whitespace();
        auto const& first = source_tokens.next_token();

        // <url> [ format(<font-format>)]?
        // FIXME: Implement optional tech() function from CSS-Fonts-4.
        if (auto maybe_url = parse_url_function(first, AllowedDataUrlType::Font); maybe_url.has_value()) {
            auto url = maybe_url.release_value();
            if (!url.is_valid()) {
                continue;
            }

            Optional<FlyString> format;

            source_tokens.skip_whitespace();
            if (!source_tokens.has_next_token()) {
                supported_sources.empend(move(url), format);
                continue;
            }

            auto maybe_function = source_tokens.next_token();
            if (!maybe_function.is_function()) {
                dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (token after `url()` that isn't a function: {}); discarding.", maybe_function.to_debug_string());
                return {};
            }

            auto const& function = maybe_function.function();
            if (function.name().equals_ignoring_ascii_case("format"sv)) {
                TokenStream format_tokens { function.values() };
                format_tokens.skip_whitespace();
                auto const& format_name_token = format_tokens.next_token();
                StringView format_name;
                if (format_name_token.is(Token::Type::Ident)) {
                    format_name = format_name_token.token().ident();
                } else if (format_name_token.is(Token::Type::String)) {
                    format_name = format_name_token.token().string();
                } else {
                    dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (`format()` parameter not an ident or string; is: {}); discarding.", format_name_token.to_debug_string());
                    return {};
                }

                if (!font_format_is_supported(format_name)) {
                    dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src format({}) not supported; skipping.", format_name);
                    continue;
                }

                format = FlyString::from_utf8(format_name).release_value_but_fixme_should_propagate_errors();
            } else {
                dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (unrecognized function token `{}`); discarding.", function.name());
                return {};
            }

            source_tokens.skip_whitespace();
            if (source_tokens.has_next_token()) {
                dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (extra token `{}`); discarding.", source_tokens.peek_token().to_debug_string());
                return {};
            }

            supported_sources.empend(move(url), format);
            continue;
        }

        // FIXME: Implement `local()`.
        dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (failed to parse url from: {}); discarding.", first.to_debug_string());
        return {};
    }

    return supported_sources;
}

RefPtr<StyleValue> Parser::parse_list_style_value(Vector<ComponentValue> const& component_values)
{
    if (component_values.size() > 3)
        return nullptr;

    RefPtr<StyleValue> list_position;
    RefPtr<StyleValue> list_image;
    RefPtr<StyleValue> list_type;
    int found_nones = 0;

    for (auto const& part : component_values) {
        auto value = parse_css_value(part);
        if (!value)
            return nullptr;

        if (value->to_identifier() == ValueID::None) {
            found_nones++;
            continue;
        }

        if (property_accepts_value(PropertyID::ListStylePosition, *value)) {
            if (list_position)
                return nullptr;
            list_position = value.release_nonnull();
            continue;
        }
        if (property_accepts_value(PropertyID::ListStyleImage, *value)) {
            if (list_image)
                return nullptr;
            list_image = value.release_nonnull();
            continue;
        }
        if (property_accepts_value(PropertyID::ListStyleType, *value)) {
            if (list_type)
                return nullptr;
            list_type = value.release_nonnull();
            continue;
        }
    }

    if (found_nones > 2)
        return nullptr;

    if (found_nones == 2) {
        if (list_image || list_type)
            return nullptr;
        auto none = IdentifierStyleValue::create(ValueID::None);
        list_image = none;
        list_type = none;

    } else if (found_nones == 1) {
        if (list_image && list_type)
            return nullptr;
        auto none = IdentifierStyleValue::create(ValueID::None);
        if (!list_image)
            list_image = none;
        if (!list_type)
            list_type = none;
    }

    if (!list_position)
        list_position = property_initial_value(m_context.realm(), PropertyID::ListStylePosition);
    if (!list_image)
        list_image = property_initial_value(m_context.realm(), PropertyID::ListStyleImage);
    if (!list_type)
        list_type = property_initial_value(m_context.realm(), PropertyID::ListStyleType);

    return ListStyleStyleValue::create(list_position.release_nonnull(), list_image.release_nonnull(), list_type.release_nonnull());
}

RefPtr<StyleValue> Parser::parse_overflow_value(Vector<ComponentValue> const& component_values)
{
    if (component_values.size() == 1) {
        auto maybe_value = parse_css_value(component_values.first());
        if (!maybe_value)
            return nullptr;
        auto value = maybe_value.release_nonnull();
        if (property_accepts_value(PropertyID::Overflow, *value))
            return OverflowStyleValue::create(value, value);
        return nullptr;
    }

    if (component_values.size() == 2) {
        auto maybe_x_value = parse_css_value(component_values[0]);
        auto maybe_y_value = parse_css_value(component_values[1]);

        if (!maybe_x_value || !maybe_y_value)
            return nullptr;
        auto x_value = maybe_x_value.release_nonnull();
        auto y_value = maybe_y_value.release_nonnull();
        if (!property_accepts_value(PropertyID::OverflowX, x_value) || !property_accepts_value(PropertyID::OverflowY, y_value)) {
            return nullptr;
        }
        return OverflowStyleValue::create(x_value, y_value);
    }

    return nullptr;
}

RefPtr<StyleValue> Parser::parse_text_decoration_value(Vector<ComponentValue> const& component_values)
{
    RefPtr<StyleValue> decoration_line;
    RefPtr<StyleValue> decoration_thickness;
    RefPtr<StyleValue> decoration_style;
    RefPtr<StyleValue> decoration_color;

    auto tokens = TokenStream { component_values };

    while (tokens.has_next_token()) {
        auto const& part = tokens.next_token();
        auto value = parse_css_value(part);
        if (!value)
            return nullptr;

        if (property_accepts_value(PropertyID::TextDecorationColor, *value)) {
            if (decoration_color)
                return nullptr;
            decoration_color = value.release_nonnull();
            continue;
        }
        if (property_accepts_value(PropertyID::TextDecorationLine, *value)) {
            if (decoration_line)
                return nullptr;
            tokens.reconsume_current_input_token();
            auto parsed_decoration_line = parse_text_decoration_line_value(tokens);
            if (!parsed_decoration_line)
                return nullptr;
            decoration_line = parsed_decoration_line.release_nonnull();
            continue;
        }
        if (property_accepts_value(PropertyID::TextDecorationThickness, *value)) {
            if (decoration_thickness)
                return nullptr;
            decoration_thickness = value.release_nonnull();
            continue;
        }
        if (property_accepts_value(PropertyID::TextDecorationStyle, *value)) {
            if (decoration_style)
                return nullptr;
            decoration_style = value.release_nonnull();
            continue;
        }

        return nullptr;
    }

    if (!decoration_line)
        decoration_line = property_initial_value(m_context.realm(), PropertyID::TextDecorationLine);
    if (!decoration_thickness)
        decoration_thickness = property_initial_value(m_context.realm(), PropertyID::TextDecorationThickness);
    if (!decoration_style)
        decoration_style = property_initial_value(m_context.realm(), PropertyID::TextDecorationStyle);
    if (!decoration_color)
        decoration_color = property_initial_value(m_context.realm(), PropertyID::TextDecorationColor);

    return TextDecorationStyleValue::create(decoration_line.release_nonnull(), decoration_thickness.release_nonnull(), decoration_style.release_nonnull(), decoration_color.release_nonnull());
}

RefPtr<StyleValue> Parser::parse_text_decoration_line_value(TokenStream<ComponentValue>& tokens)
{
    StyleValueVector style_values;

    while (tokens.has_next_token()) {
        auto const& token = tokens.next_token();
        auto maybe_value = parse_css_value(token);
        if (!maybe_value || !property_accepts_value(PropertyID::TextDecorationLine, *maybe_value)) {
            tokens.reconsume_current_input_token();
            break;
        }
        auto value = maybe_value.release_nonnull();

        if (auto maybe_line = value_id_to_text_decoration_line(value->to_identifier()); maybe_line.has_value()) {
            auto line = maybe_line.release_value();
            if (line == TextDecorationLine::None) {
                if (!style_values.is_empty()) {
                    tokens.reconsume_current_input_token();
                    break;
                }
                return value;
            }
            if (style_values.contains_slow(value)) {
                tokens.reconsume_current_input_token();
                break;
            }
            style_values.append(move(value));
            continue;
        }

        tokens.reconsume_current_input_token();
        break;
    }

    if (style_values.is_empty())
        return nullptr;
    return StyleValueList::create(move(style_values), StyleValueList::Separator::Space);
}

RefPtr<StyleValue> Parser::parse_transform_value(Vector<ComponentValue> const& component_values)
{
    StyleValueVector transformations;
    auto tokens = TokenStream { component_values };
    tokens.skip_whitespace();

    while (tokens.has_next_token()) {
        tokens.skip_whitespace();
        auto const& part = tokens.next_token();

        if (part.is(Token::Type::Ident) && part.token().ident().equals_ignoring_ascii_case("none"sv)) {
            if (!transformations.is_empty())
                return nullptr;
            tokens.skip_whitespace();
            if (tokens.has_next_token())
                return nullptr;
            return IdentifierStyleValue::create(ValueID::None);
        }

        if (!part.is_function())
            return nullptr;
        auto maybe_function = transform_function_from_string(part.function().name());
        if (!maybe_function.has_value())
            return nullptr;
        auto function = maybe_function.release_value();
        auto function_metadata = transform_function_metadata(function);

        StyleValueVector values;
        auto argument_tokens = TokenStream { part.function().values() };
        argument_tokens.skip_whitespace();
        size_t argument_index = 0;
        while (argument_tokens.has_next_token()) {
            if (argument_index == function_metadata.parameters.size()) {
                dbgln_if(CSS_PARSER_DEBUG, "Too many arguments to {}. max: {}", part.function().name(), function_metadata.parameters.size());
                return nullptr;
            }

            auto const& value = argument_tokens.next_token();
            RefPtr<CalculatedStyleValue> maybe_calc_value;
            if (auto maybe_dynamic_value = parse_dynamic_value(value)) {
                // TODO: calc() is the only dynamic value we support for now, but more will come later.
                // FIXME: Actually, calc() should probably be parsed inside parse_dimension_value() etc,
                //        so that it affects every use instead of us having to manually implement it.
                VERIFY(maybe_dynamic_value->is_calculated());
                maybe_calc_value = maybe_dynamic_value->as_calculated();
            }

            switch (function_metadata.parameters[argument_index].type) {
            case TransformFunctionParameterType::Angle: {
                // These are `<angle> | <zero>` in the spec, so we have to check for both kinds.
                if (maybe_calc_value && maybe_calc_value->resolves_to_angle()) {
                    values.append(AngleStyleValue::create(Angle::make_calculated(maybe_calc_value.release_nonnull())));
                } else if (value.is(Token::Type::Number) && value.token().number_value() == 0) {
                    values.append(AngleStyleValue::create(Angle::make_degrees(0)));
                } else {
                    auto dimension_value = parse_dimension_value(value);
                    if (!dimension_value || !dimension_value->is_angle())
                        return nullptr;
                    values.append(dimension_value.release_nonnull());
                }
                break;
            }
            case TransformFunctionParameterType::Length: {
                if (maybe_calc_value && maybe_calc_value->resolves_to_length()) {
                    values.append(LengthStyleValue::create(Length::make_calculated(maybe_calc_value.release_nonnull())));
                } else {
                    auto dimension_value = parse_dimension_value(value);
                    if (!dimension_value)
                        return nullptr;

                    if (dimension_value->is_length())
                        values.append(dimension_value.release_nonnull());
                    else
                        return nullptr;
                }
                break;
            }
            case TransformFunctionParameterType::LengthPercentage: {
                if (maybe_calc_value && maybe_calc_value->resolves_to_length()) {
                    values.append(LengthStyleValue::create(Length::make_calculated(maybe_calc_value.release_nonnull())));
                } else {
                    auto dimension_value = parse_dimension_value(value);
                    if (!dimension_value)
                        return nullptr;

                    if (dimension_value->is_percentage() || dimension_value->is_length())
                        values.append(dimension_value.release_nonnull());
                    else
                        return nullptr;
                }
                break;
            }
            case TransformFunctionParameterType::Number: {
                if (maybe_calc_value && maybe_calc_value->resolves_to_number()) {
                    values.append(LengthStyleValue::create(Length::make_calculated(maybe_calc_value.release_nonnull())));
                } else {
                    auto number = parse_numeric_value(value);
                    if (!number)
                        return nullptr;
                    values.append(number.release_nonnull());
                }
                break;
            }
            }

            argument_tokens.skip_whitespace();
            if (argument_tokens.has_next_token()) {
                // Arguments must be separated by commas.
                if (!argument_tokens.next_token().is(Token::Type::Comma))
                    return nullptr;
                argument_tokens.skip_whitespace();

                // If there are no more parameters after the comma, this is invalid.
                if (!argument_tokens.has_next_token())
                    return nullptr;
            }

            argument_index++;
        }

        if (argument_index < function_metadata.parameters.size() && function_metadata.parameters[argument_index].required) {
            dbgln_if(CSS_PARSER_DEBUG, "Required parameter at position {} is missing", argument_index);
            return nullptr;
        }

        transformations.append(TransformationStyleValue::create(function, move(values)));
    }
    return StyleValueList::create(move(transformations), StyleValueList::Separator::Space);
}

// https://www.w3.org/TR/css-transforms-1/#propdef-transform-origin
// FIXME: This only supports a 2D position
RefPtr<StyleValue> Parser::parse_transform_origin_value(Vector<ComponentValue> const& component_values)
{
    enum class Axis {
        None,
        X,
        Y,
    };

    struct AxisOffset {
        Axis axis;
        NonnullRefPtr<StyleValue> offset;
    };

    auto to_axis_offset = [](RefPtr<StyleValue> value) -> Optional<AxisOffset> {
        if (value->is_percentage())
            return AxisOffset { Axis::None, value->as_percentage() };
        if (value->is_length())
            return AxisOffset { Axis::None, value->as_length() };
        if (value->has_length())
            return AxisOffset { Axis::None, LengthStyleValue::create(value->to_length()) };
        if (value->is_identifier()) {
            switch (value->to_identifier()) {
            case ValueID::Top:
                return AxisOffset { Axis::Y, PercentageStyleValue::create(Percentage(0)) };
            case ValueID::Left:
                return AxisOffset { Axis::X, PercentageStyleValue::create(Percentage(0)) };
            case ValueID::Center:
                return AxisOffset { Axis::None, PercentageStyleValue::create(Percentage(50)) };
            case ValueID::Bottom:
                return AxisOffset { Axis::Y, PercentageStyleValue::create(Percentage(100)) };
            case ValueID::Right:
                return AxisOffset { Axis::X, PercentageStyleValue::create(Percentage(100)) };
            default:
                return {};
            }
        }
        return {};
    };

    auto make_list = [](NonnullRefPtr<StyleValue> const& x_value, NonnullRefPtr<StyleValue> const& y_value) -> NonnullRefPtr<StyleValueList> {
        StyleValueVector values;
        values.append(x_value);
        values.append(y_value);
        return StyleValueList::create(move(values), StyleValueList::Separator::Space);
    };

    switch (component_values.size()) {
    case 1: {
        auto single_value = to_axis_offset(parse_css_value(component_values[0]));
        if (!single_value.has_value())
            return nullptr;
        // If only one value is specified, the second value is assumed to be center.
        // FIXME: If one or two values are specified, the third value is assumed to be 0px.
        switch (single_value->axis) {
        case Axis::None:
        case Axis::X:
            return make_list(single_value->offset, PercentageStyleValue::create(Percentage(50)));
        case Axis::Y:
            return make_list(PercentageStyleValue::create(Percentage(50)), single_value->offset);
        }
        VERIFY_NOT_REACHED();
    }
    case 2: {
        auto first_value = to_axis_offset(parse_css_value(component_values[0]));
        auto second_value = to_axis_offset(parse_css_value(component_values[1]));
        if (!first_value.has_value() || !second_value.has_value())
            return nullptr;

        RefPtr<StyleValue> x_value;
        RefPtr<StyleValue> y_value;

        if (first_value->axis == Axis::X) {
            x_value = first_value->offset;
        } else if (first_value->axis == Axis::Y) {
            y_value = first_value->offset;
        }

        if (second_value->axis == Axis::X) {
            if (x_value)
                return nullptr;
            x_value = second_value->offset;
            // Put the other in Y since its axis can't have been X
            y_value = first_value->offset;
        } else if (second_value->axis == Axis::Y) {
            if (y_value)
                return nullptr;
            y_value = second_value->offset;
            // Put the other in X since its axis can't have been Y
            x_value = first_value->offset;
        } else {
            if (x_value) {
                VERIFY(!y_value);
                y_value = second_value->offset;
            } else {
                VERIFY(!x_value);
                x_value = second_value->offset;
            }
        }
        // If two or more values are defined and either no value is a keyword, or the only used keyword is center,
        // then the first value represents the horizontal position (or offset) and the second represents the vertical position (or offset).
        // FIXME: A third value always represents the Z position (or offset) and must be of type <length>.
        if (first_value->axis == Axis::None && second_value->axis == Axis::None) {
            x_value = first_value->offset;
            y_value = second_value->offset;
        }
        return make_list(x_value.release_nonnull(), y_value.release_nonnull());
    }
    }

    return nullptr;
}

RefPtr<StyleValue> Parser::parse_as_css_value(PropertyID property_id)
{
    auto component_values = parse_a_list_of_component_values(m_token_stream);
    auto tokens = TokenStream(component_values);
    auto parsed_value = parse_css_value(property_id, tokens);
    if (parsed_value.is_error())
        return {};
    return parsed_value.release_value();
}

Optional<CSS::GridSize> Parser::parse_grid_size(ComponentValue const& component_value)
{
    // FIXME: Parse calc here if necessary
    if (component_value.is_function())
        return {};
    auto token = component_value.token();
    if (token.is(Token::Type::Dimension) && token.dimension_unit().equals_ignoring_ascii_case("fr"sv)) {
        float numeric_value = token.dimension_value();
        if (numeric_value)
            return GridSize(numeric_value);
    }
    if (token.is(Token::Type::Ident) && token.ident().equals_ignoring_ascii_case("auto"sv))
        return GridSize::make_auto();
    if (token.is(Token::Type::Ident) && token.ident().equals_ignoring_ascii_case("max-content"sv))
        return GridSize(GridSize::Type::MaxContent);
    if (token.is(Token::Type::Ident) && token.ident().equals_ignoring_ascii_case("min-content"sv))
        return GridSize(GridSize::Type::MinContent);
    auto dimension = parse_dimension(token);
    if (!dimension.has_value())
        return {};
    if (dimension->is_length())
        return GridSize(dimension->length());
    else if (dimension->is_percentage())
        return GridSize(dimension->percentage());
    return {};
}

Optional<CSS::GridMinMax> Parser::parse_min_max(Vector<ComponentValue> const& component_values)
{
    // https://www.w3.org/TR/css-grid-2/#valdef-grid-template-columns-minmax
    // 'minmax(min, max)'
    // Defines a size range greater than or equal to min and less than or equal to max. If the max is
    // less than the min, then the max will be floored by the min (essentially yielding minmax(min,
    // min)). As a maximum, a <flex> value sets the track’s flex factor; it is invalid as a minimum.
    auto function_tokens = TokenStream(component_values);
    auto comma_separated_list = parse_a_comma_separated_list_of_component_values(function_tokens);
    if (comma_separated_list.size() != 2)
        return {};

    TokenStream part_one_tokens { comma_separated_list[0] };
    part_one_tokens.skip_whitespace();
    if (!part_one_tokens.has_next_token())
        return {};
    auto current_token = part_one_tokens.next_token();
    auto min_grid_size = parse_grid_size(current_token);

    TokenStream part_two_tokens { comma_separated_list[1] };
    part_two_tokens.skip_whitespace();
    if (!part_two_tokens.has_next_token())
        return {};
    current_token = part_two_tokens.next_token();
    auto max_grid_size = parse_grid_size(current_token);

    if (min_grid_size.has_value() && max_grid_size.has_value()) {
        // https://www.w3.org/TR/css-grid-2/#valdef-grid-template-columns-minmax
        // As a maximum, a <flex> value sets the track’s flex factor; it is invalid as a minimum.
        if (min_grid_size.value().is_flexible_length())
            return {};
        return CSS::GridMinMax(min_grid_size.value(), max_grid_size.value());
    }
    return {};
}

Optional<CSS::GridRepeat> Parser::parse_repeat(Vector<ComponentValue> const& component_values)
{
    // https://www.w3.org/TR/css-grid-2/#repeat-syntax
    // 7.2.3.1. Syntax of repeat()
    // The generic form of the repeat() syntax is, approximately,
    // repeat( [ <integer [1,∞]> | auto-fill | auto-fit ] , <track-list> )
    auto is_auto_fill = false;
    auto is_auto_fit = false;
    auto function_tokens = TokenStream(component_values);
    auto comma_separated_list = parse_a_comma_separated_list_of_component_values(function_tokens);
    if (comma_separated_list.size() != 2)
        return {};
    // The first argument specifies the number of repetitions.
    TokenStream part_one_tokens { comma_separated_list[0] };
    part_one_tokens.skip_whitespace();
    if (!part_one_tokens.has_next_token())
        return {};
    auto current_token = part_one_tokens.next_token().token();

    auto repeat_count = 0;
    if (current_token.is(Token::Type::Number) && current_token.number().is_integer() && current_token.number_value() > 0)
        repeat_count = current_token.number_value();
    else if (current_token.is(Token::Type::Ident) && current_token.ident().equals_ignoring_ascii_case("auto-fill"sv))
        is_auto_fill = true;
    else if (current_token.is(Token::Type::Ident) && current_token.ident().equals_ignoring_ascii_case("auto-fit"sv))
        is_auto_fit = true;

    // The second argument is a track list, which is repeated that number of times.
    TokenStream part_two_tokens { comma_separated_list[1] };
    part_two_tokens.skip_whitespace();
    if (!part_two_tokens.has_next_token())
        return {};

    Vector<CSS::ExplicitGridTrack> repeat_params;
    Vector<Vector<String>> line_names_list;
    auto last_object_was_line_names = false;
    while (part_two_tokens.has_next_token()) {
        auto token = part_two_tokens.next_token();
        Vector<String> line_names;
        if (token.is_block()) {
            if (last_object_was_line_names)
                return {};
            last_object_was_line_names = true;
            if (!token.block().is_square())
                return {};
            TokenStream block_tokens { token.block().values() };
            while (block_tokens.has_next_token()) {
                auto current_block_token = block_tokens.next_token();
                auto maybe_string = String::from_utf8(current_block_token.token().ident());
                if (maybe_string.is_error())
                    return {};
                line_names.append(maybe_string.value());
                block_tokens.skip_whitespace();
            }
            line_names_list.append(line_names);
            part_two_tokens.skip_whitespace();
        } else {
            last_object_was_line_names = false;
            auto track_sizing_function = parse_track_sizing_function(token);
            if (!track_sizing_function.has_value())
                return {};
            // However, there are some restrictions:
            // The repeat() notation can’t be nested.
            if (track_sizing_function.value().is_repeat())
                return {};
            // Automatic repetitions (auto-fill or auto-fit) cannot be combined with intrinsic or flexible sizes.
            if (track_sizing_function.value().is_default() && track_sizing_function.value().grid_size().is_flexible_length() && (is_auto_fill || is_auto_fit))
                return {};
            repeat_params.append(track_sizing_function.value());
            part_two_tokens.skip_whitespace();
        }
    }
    while (line_names_list.size() <= repeat_params.size())
        line_names_list.append({});

    // Thus the precise syntax of the repeat() notation has several forms:
    // <track-repeat> = repeat( [ <integer [1,∞]> ] , [ <line-names>? <track-size> ]+ <line-names>? )
    // <auto-repeat>  = repeat( [ auto-fill | auto-fit ] , [ <line-names>? <fixed-size> ]+ <line-names>? )
    // <fixed-repeat> = repeat( [ <integer [1,∞]> ] , [ <line-names>? <fixed-size> ]+ <line-names>? )
    // <name-repeat>  = repeat( [ <integer [1,∞]> | auto-fill ], <line-names>+)

    // The <track-repeat> variant can represent the repetition of any <track-size>, but is limited to a
    // fixed number of repetitions.

    // The <auto-repeat> variant can repeat automatically to fill a space, but requires definite track
    // sizes so that the number of repetitions can be calculated. It can only appear once in the track
    // list, but the same track list can also contain <fixed-repeat>s.

    // The <name-repeat> variant is for adding line names to subgrids. It can only be used with the
    // subgrid keyword and cannot specify track sizes, only line names.

    // If a repeat() function that is not a <name-repeat> ends up placing two <line-names> adjacent to
    // each other, the name lists are merged. For example, repeat(2, [a] 1fr [b]) is equivalent to [a]
    // 1fr [b a] 1fr [b].
    if (is_auto_fill)
        return CSS::GridRepeat(CSS::GridTrackSizeList(repeat_params, line_names_list), CSS::GridRepeat::Type::AutoFill);
    else if (is_auto_fit)
        return CSS::GridRepeat(CSS::GridTrackSizeList(repeat_params, line_names_list), CSS::GridRepeat::Type::AutoFit);
    else
        return CSS::GridRepeat(CSS::GridTrackSizeList(repeat_params, line_names_list), repeat_count);
}

Optional<CSS::ExplicitGridTrack> Parser::parse_track_sizing_function(ComponentValue const& token)
{
    if (token.is_function()) {
        auto const& function_token = token.function();
        if (function_token.name().equals_ignoring_ascii_case("repeat"sv)) {
            auto maybe_repeat = parse_repeat(function_token.values());
            if (maybe_repeat.has_value())
                return CSS::ExplicitGridTrack(maybe_repeat.value());
            else
                return {};
        } else if (function_token.name().equals_ignoring_ascii_case("minmax"sv)) {
            auto maybe_min_max_value = parse_min_max(function_token.values());
            if (maybe_min_max_value.has_value())
                return CSS::ExplicitGridTrack(maybe_min_max_value.value());
            else
                return {};
        }
        return {};
    } else if (token.is(Token::Type::Ident) && token.token().ident().equals_ignoring_ascii_case("auto"sv)) {
        return CSS::ExplicitGridTrack(GridSize(Length::make_auto()));
    } else if (token.is_block()) {
        return {};
    } else {
        auto grid_size = parse_grid_size(token);
        if (!grid_size.has_value())
            return {};
        return CSS::ExplicitGridTrack(grid_size.value());
    }
}

RefPtr<StyleValue> Parser::parse_grid_track_sizes(Vector<ComponentValue> const& component_values)
{
    Vector<CSS::ExplicitGridTrack> track_list;
    Vector<Vector<String>> line_names_list;
    auto last_object_was_line_names = false;
    TokenStream tokens { component_values };
    while (tokens.has_next_token()) {
        auto token = tokens.next_token();
        if (token.is_block()) {
            if (last_object_was_line_names)
                return GridTrackSizeStyleValue::make_auto();
            last_object_was_line_names = true;
            Vector<String> line_names;
            if (!token.block().is_square())
                return GridTrackSizeStyleValue::make_auto();
            TokenStream block_tokens { token.block().values() };
            while (block_tokens.has_next_token()) {
                auto current_block_token = block_tokens.next_token();
                auto maybe_string = String::from_utf8(current_block_token.token().ident());
                if (maybe_string.is_error())
                    return {};
                line_names.append(maybe_string.value());
                block_tokens.skip_whitespace();
            }
            line_names_list.append(line_names);
        } else {
            last_object_was_line_names = false;
            auto track_sizing_function = parse_track_sizing_function(token);
            if (!track_sizing_function.has_value())
                return GridTrackSizeStyleValue::make_auto();
            // FIXME: Handle multiple repeat values (should combine them here, or remove
            // any other ones if the first one is auto-fill, etc.)
            track_list.append(track_sizing_function.value());
        }
    }
    while (line_names_list.size() <= track_list.size())
        line_names_list.append({});
    return GridTrackSizeStyleValue::create(CSS::GridTrackSizeList(track_list, line_names_list));
}

RefPtr<StyleValue> Parser::parse_grid_track_placement(Vector<ComponentValue> const& component_values)
{
    // https://www.w3.org/TR/css-grid-2/#line-placement
    // Line-based Placement: the grid-row-start, grid-column-start, grid-row-end, and grid-column-end properties
    // <grid-line> =
    //     auto |
    //     <custom-ident> |
    //     [ <integer> && <custom-ident>? ] |
    //     [ span && [ <integer> || <custom-ident> ] ]
    auto is_auto = [](Token token) -> bool {
        if (token.is(Token::Type::Ident) && token.ident().equals_ignoring_ascii_case("auto"sv))
            return true;
        return false;
    };
    auto is_span = [](Token token) -> bool {
        if (token.is(Token::Type::Ident) && token.ident().equals_ignoring_ascii_case("span"sv))
            return true;
        return false;
    };
    auto is_valid_integer = [](Token token) -> bool {
        // An <integer> value of zero makes the declaration invalid.
        if (token.is(Token::Type::Number) && token.number().is_integer() && token.number_value() != 0)
            return true;
        return false;
    };
    auto is_line_name = [](Token token) -> bool {
        // The <custom-ident> additionally excludes the keywords span and auto.
        if (token.is(Token::Type::Ident) && !token.ident().equals_ignoring_ascii_case("span"sv) && !token.ident().equals_ignoring_ascii_case("auto"sv))
            return true;
        return false;
    };

    auto tokens = TokenStream { component_values };
    tokens.skip_whitespace();
    auto current_token = tokens.next_token().token();

    if (!tokens.has_next_token()) {
        if (is_auto(current_token))
            return GridTrackPlacementStyleValue::create(CSS::GridTrackPlacement());
        if (is_span(current_token))
            return GridTrackPlacementStyleValue::create(CSS::GridTrackPlacement(1, true));
        if (is_valid_integer(current_token))
            return GridTrackPlacementStyleValue::create(CSS::GridTrackPlacement(static_cast<int>(current_token.number_value())));
        if (is_line_name(current_token)) {
            auto maybe_string = String::from_utf8(current_token.ident());
            if (!maybe_string.is_error())
                return GridTrackPlacementStyleValue::create(CSS::GridTrackPlacement(maybe_string.value()));
        }
        return {};
    }

    auto span_value = false;
    auto span_or_position_value = 0;
    String line_name_value;
    while (true) {
        if (is_auto(current_token))
            return {};
        if (is_span(current_token)) {
            if (span_value == false)
                span_value = true;
            else
                return {};
        }
        if (is_valid_integer(current_token)) {
            if (span_or_position_value == 0)
                span_or_position_value = static_cast<int>(current_token.number_value());
            else
                return {};
        }
        if (is_line_name(current_token)) {
            if (line_name_value.is_empty()) {
                auto maybe_string = String::from_utf8(current_token.ident());
                if (maybe_string.is_error())
                    return {};
                line_name_value = maybe_string.release_value();
            } else {
                return {};
            }
        }
        tokens.skip_whitespace();
        if (tokens.has_next_token())
            current_token = tokens.next_token().token();
        else
            break;
    }

    // Negative integers or zero are invalid.
    if (span_value && span_or_position_value < 1)
        return {};

    // If the <integer> is omitted, it defaults to 1.
    if (span_or_position_value == 0)
        span_or_position_value = 1;

    if (!line_name_value.is_empty())
        return GridTrackPlacementStyleValue::create(CSS::GridTrackPlacement(line_name_value, span_or_position_value, span_value));
    return GridTrackPlacementStyleValue::create(CSS::GridTrackPlacement(span_or_position_value, span_value));
}

RefPtr<StyleValue> Parser::parse_grid_track_placement_shorthand_value(Vector<ComponentValue> const& component_values)
{
    auto tokens = TokenStream { component_values };
    auto current_token = tokens.next_token().token();

    Vector<ComponentValue> track_start_placement_tokens;
    while (true) {
        if (current_token.is(Token::Type::Delim) && current_token.delim() == "/"sv)
            break;
        track_start_placement_tokens.append(current_token);
        if (!tokens.has_next_token())
            break;
        current_token = tokens.next_token().token();
    }

    Vector<ComponentValue> track_end_placement_tokens;
    if (tokens.has_next_token()) {
        current_token = tokens.next_token().token();
        while (true) {
            track_end_placement_tokens.append(current_token);
            if (!tokens.has_next_token())
                break;
            current_token = tokens.next_token().token();
        }
    }

    auto parsed_start_value = parse_grid_track_placement(track_start_placement_tokens);
    if (parsed_start_value && track_end_placement_tokens.is_empty())
        return GridTrackPlacementShorthandStyleValue::create(parsed_start_value.release_nonnull()->as_grid_track_placement().grid_track_placement());

    auto parsed_end_value = parse_grid_track_placement(track_end_placement_tokens);
    if (parsed_start_value && parsed_end_value)
        return GridTrackPlacementShorthandStyleValue::create(parsed_start_value.release_nonnull()->as_grid_track_placement(), parsed_end_value.release_nonnull()->as_grid_track_placement());

    return {};
}

RefPtr<StyleValue> Parser::parse_grid_area_shorthand_value(Vector<ComponentValue> const& component_values)
{
    auto tokens = TokenStream { component_values };
    Token current_token;

    auto parse_placement_tokens = [&](Vector<ComponentValue>& placement_tokens, bool check_for_delimiter = true) -> void {
        current_token = tokens.next_token().token();
        while (true) {
            if (check_for_delimiter && current_token.is(Token::Type::Delim) && current_token.delim() == "/"sv)
                break;
            placement_tokens.append(current_token);
            tokens.skip_whitespace();
            if (!tokens.has_next_token())
                break;
            current_token = tokens.next_token().token();
        }
    };

    Vector<ComponentValue> row_start_placement_tokens;
    parse_placement_tokens(row_start_placement_tokens);

    Vector<ComponentValue> column_start_placement_tokens;
    if (tokens.has_next_token())
        parse_placement_tokens(column_start_placement_tokens);

    Vector<ComponentValue> row_end_placement_tokens;
    if (tokens.has_next_token())
        parse_placement_tokens(row_end_placement_tokens);

    Vector<ComponentValue> column_end_placement_tokens;
    if (tokens.has_next_token())
        parse_placement_tokens(column_end_placement_tokens, false);

    // https://www.w3.org/TR/css-grid-2/#placement-shorthands
    // The grid-area property is a shorthand for grid-row-start, grid-column-start, grid-row-end and
    // grid-column-end.
    auto row_start_style_value = parse_grid_track_placement(row_start_placement_tokens);
    auto column_start_style_value = parse_grid_track_placement(column_start_placement_tokens);
    auto row_end_style_value = parse_grid_track_placement(row_end_placement_tokens);
    auto column_end_style_value = parse_grid_track_placement(column_end_placement_tokens);

    // If four <grid-line> values are specified, grid-row-start is set to the first value, grid-column-start
    // is set to the second value, grid-row-end is set to the third value, and grid-column-end is set to the
    // fourth value.
    auto row_start = GridTrackPlacement::make_auto();
    auto column_start = GridTrackPlacement::make_auto();
    auto row_end = GridTrackPlacement::make_auto();
    auto column_end = GridTrackPlacement::make_auto();

    if (row_start_style_value)
        row_start = row_start_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();

    // When grid-column-start is omitted, if grid-row-start is a <custom-ident>, all four longhands are set to
    // that value. Otherwise, it is set to auto.
    if (column_start_style_value)
        column_start = column_start_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
    else
        column_start = row_start;

    // When grid-row-end is omitted, if grid-row-start is a <custom-ident>, grid-row-end is set to that
    // <custom-ident>; otherwise, it is set to auto.
    if (row_end_style_value)
        row_end = row_end_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
    else
        row_end = column_start;

    // When grid-column-end is omitted, if grid-column-start is a <custom-ident>, grid-column-end is set to
    // that <custom-ident>; otherwise, it is set to auto.
    if (column_end_style_value)
        column_end = column_end_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
    else
        column_end = row_end;

    return GridAreaShorthandStyleValue::create(row_start, column_start, row_end, column_end);
}

RefPtr<StyleValue> Parser::parse_grid_template_areas_value(Vector<ComponentValue> const& component_values)
{
    Vector<Vector<String>> grid_area_rows;
    for (auto& component_value : component_values) {
        Vector<String> grid_area_columns;
        if (component_value.is(Token::Type::String)) {
            auto const parts = String::from_utf8(component_value.token().string()).release_value_but_fixme_should_propagate_errors().split(' ').release_value_but_fixme_should_propagate_errors();
            for (auto& part : parts) {
                grid_area_columns.append(part);
            }
        }
        grid_area_rows.append(move(grid_area_columns));
    }
    return GridTemplateAreaStyleValue::create(grid_area_rows);
}

Parser::ParseErrorOr<NonnullRefPtr<StyleValue>> Parser::parse_css_value(PropertyID property_id, TokenStream<ComponentValue>& tokens)
{
    auto function_contains_var_or_attr = [](Function const& function, auto&& recurse) -> bool {
        if (function.name().equals_ignoring_ascii_case("var"sv) || function.name().equals_ignoring_ascii_case("attr"sv))
            return true;
        for (auto const& token : function.values()) {
            if (token.is_function() && recurse(token.function(), recurse))
                return true;
        }
        return false;
    };
    auto block_contains_var_or_attr = [function_contains_var_or_attr](Block const& block, auto&& recurse) -> bool {
        for (auto const& token : block.values()) {
            if (token.is_function() && function_contains_var_or_attr(token.function(), function_contains_var_or_attr))
                return true;
            if (token.is_block() && recurse(token.block(), recurse))
                return true;
        }
        return false;
    };

    m_context.set_current_property_id(property_id);
    Vector<ComponentValue> component_values;
    bool contains_var_or_attr = false;

    while (tokens.has_next_token()) {
        auto const& token = tokens.next_token();

        if (token.is(Token::Type::Semicolon)) {
            tokens.reconsume_current_input_token();
            break;
        }

        if (property_id != PropertyID::Custom) {
            if (token.is(Token::Type::Whitespace))
                continue;

            if (token.is(Token::Type::Ident) && has_ignored_vendor_prefix(token.token().ident()))
                return ParseError::IncludesIgnoredVendorPrefix;
        }

        if (!contains_var_or_attr) {
            if (token.is_function() && function_contains_var_or_attr(token.function(), function_contains_var_or_attr))
                contains_var_or_attr = true;
            else if (token.is_block() && block_contains_var_or_attr(token.block(), block_contains_var_or_attr))
                contains_var_or_attr = true;
        }

        component_values.append(token);
    }

    if (property_id == PropertyID::Custom || contains_var_or_attr)
        return { UnresolvedStyleValue::create(move(component_values), contains_var_or_attr) };

    if (component_values.is_empty())
        return ParseError::SyntaxError;

    if (component_values.size() == 1) {
        if (auto parsed_value = parse_builtin_value(component_values.first()))
            return parsed_value.release_nonnull();
    }

    // Special-case property handling
    switch (property_id) {
    case PropertyID::BackdropFilter:
        if (auto parsed_value = parse_filter_value_list_value(component_values))
            return parsed_value.release_nonnull();
        return ParseError::SyntaxError;
    case PropertyID::Background:
        if (auto parsed_value = parse_background_value(component_values))
            return parsed_value.release_nonnull();
        return ParseError::SyntaxError;
    case PropertyID::BackgroundAttachment:
    case PropertyID::BackgroundClip:
    case PropertyID::BackgroundImage:
    case PropertyID::BackgroundOrigin:
        if (auto parsed_value = parse_simple_comma_separated_value_list(component_values))
            return parsed_value.release_nonnull();
        return ParseError::SyntaxError;
    case PropertyID::BackgroundPosition:
        if (auto parsed_value = parse_comma_separated_value_list(component_values, [this](auto& tokens) { return parse_single_background_position_value(tokens); }))
            return parsed_value.release_nonnull();
        return ParseError::SyntaxError;
    case PropertyID::BackgroundRepeat:
        if (auto parsed_value = parse_comma_separated_value_list(component_values, [this](auto& tokens) { return parse_single_background_repeat_value(tokens); }))
            return parsed_value.release_nonnull();
        return ParseError::SyntaxError;
    case PropertyID::BackgroundSize:
        if (auto parsed_value = parse_comma_separated_value_list(component_values, [this](auto& tokens) { return parse_single_background_size_value(tokens); }))
            return parsed_value.release_nonnull();
        return ParseError::SyntaxError;
    case PropertyID::Border:
    case PropertyID::BorderBottom:
    case PropertyID::BorderLeft:
    case PropertyID::BorderRight:
    case PropertyID::BorderTop:
        if (auto parsed_value = parse_border_value(component_values))
            return parsed_value.release_nonnull();
        return ParseError::SyntaxError;
    case PropertyID::BorderTopLeftRadius:
    case PropertyID::BorderTopRightRadius:
    case PropertyID::BorderBottomRightRadius:
    case PropertyID::BorderBottomLeftRadius:
        if (auto parsed_value = parse_border_radius_value(component_values))
            return parsed_value.release_nonnull();
        return ParseError::SyntaxError;
    case PropertyID::BorderRadius:
        if (auto parsed_value = parse_border_radius_shorthand_value(component_values))
            return parsed_value.release_nonnull();
        return ParseError::SyntaxError;
    case PropertyID::BoxShadow:
        if (auto parsed_value = parse_shadow_value(component_values, AllowInsetKeyword::Yes))
            return parsed_value.release_nonnull();
        return ParseError::SyntaxError;
    case PropertyID::Content:
        if (auto parsed_value = parse_content_value(component_values))
            return parsed_value.release_nonnull();
        return ParseError::SyntaxError;
    case PropertyID::Flex:
        if (auto parsed_value = parse_flex_value(component_values))
            return parsed_value.release_nonnull();
        return ParseError::SyntaxError;
    case PropertyID::FlexFlow:
        if (auto parsed_value = parse_flex_flow_value(component_values))
            return parsed_value.release_nonnull();
        return ParseError::SyntaxError;
    case PropertyID::Font:
        if (auto parsed_value = parse_font_value(component_values))
            return parsed_value.release_nonnull();
        return ParseError::SyntaxError;
    case PropertyID::FontFamily:
        if (auto parsed_value = parse_font_family_value(component_values))
            return parsed_value.release_nonnull();
        return ParseError::SyntaxError;
    case PropertyID::GridColumn:
        if (auto parsed_value = parse_grid_track_placement_shorthand_value(component_values))
            return parsed_value.release_nonnull();
        return ParseError::SyntaxError;
    case PropertyID::GridArea:
        if (auto parsed_value = parse_grid_area_shorthand_value(component_values))
            return parsed_value.release_nonnull();
        return ParseError::SyntaxError;
    case PropertyID::GridTemplateAreas:
        if (auto parsed_value = parse_grid_template_areas_value(component_values))
            return parsed_value.release_nonnull();
        return ParseError::SyntaxError;
    case PropertyID::GridColumnEnd:
        if (auto parsed_value = parse_grid_track_placement(component_values))
            return parsed_value.release_nonnull();
        return ParseError::SyntaxError;
    case PropertyID::GridColumnStart:
        if (auto parsed_value = parse_grid_track_placement(component_values))
            return parsed_value.release_nonnull();
        return ParseError::SyntaxError;
    case PropertyID::GridRow:
        if (auto parsed_value = parse_grid_track_placement_shorthand_value(component_values))
            return parsed_value.release_nonnull();
        return ParseError::SyntaxError;
    case PropertyID::GridRowEnd:
        if (auto parsed_value = parse_grid_track_placement(component_values))
            return parsed_value.release_nonnull();
        return ParseError::SyntaxError;
    case PropertyID::GridRowStart:
        if (auto parsed_value = parse_grid_track_placement(component_values))
            return parsed_value.release_nonnull();
        return ParseError::SyntaxError;
    case PropertyID::GridTemplateColumns:
        if (auto parsed_value = parse_grid_track_sizes(component_values))
            return parsed_value.release_nonnull();
        return ParseError::SyntaxError;
    case PropertyID::GridTemplateRows:
        if (auto parsed_value = parse_grid_track_sizes(component_values))
            return parsed_value.release_nonnull();
        return ParseError::SyntaxError;
    case PropertyID::ListStyle:
        if (auto parsed_value = parse_list_style_value(component_values))
            return parsed_value.release_nonnull();
        return ParseError::SyntaxError;
    case PropertyID::Overflow:
        if (auto parsed_value = parse_overflow_value(component_values))
            return parsed_value.release_nonnull();
        return ParseError::SyntaxError;
    case PropertyID::TextDecoration:
        if (auto parsed_value = parse_text_decoration_value(component_values))
            return parsed_value.release_nonnull();
        return ParseError::SyntaxError;
    case PropertyID::TextDecorationLine: {
        TokenStream value_tokens { component_values };
        auto parsed_value = parse_text_decoration_line_value(value_tokens);
        if (parsed_value && !value_tokens.has_next_token())
            return parsed_value.release_nonnull();
        return ParseError::SyntaxError;
    }
    case PropertyID::TextShadow:
        if (auto parsed_value = parse_shadow_value(component_values, AllowInsetKeyword::No))
            return parsed_value.release_nonnull();
        return ParseError::SyntaxError;
    case PropertyID::Transform:
        if (auto parsed_value = parse_transform_value(component_values))
            return parsed_value.release_nonnull();
        return ParseError::SyntaxError;
    case PropertyID::TransformOrigin:
        if (auto parse_value = parse_transform_origin_value(component_values))
            return parse_value.release_nonnull();
        return ParseError ::SyntaxError;
    default:
        break;
    }

    if (component_values.size() == 1) {
        if (auto parsed_value = parse_css_value(component_values.first())) {
            if (property_accepts_value(property_id, *parsed_value))
                return parsed_value.release_nonnull();
        }
        return ParseError::SyntaxError;
    }

    // We have multiple values, so treat them as a StyleValueList.
    if (property_maximum_value_count(property_id) > 1) {
        StyleValueVector parsed_values;
        for (auto& component_value : component_values) {
            auto parsed_value = parse_css_value(component_value);
            if (!parsed_value || !property_accepts_value(property_id, *parsed_value))
                return ParseError::SyntaxError;
            parsed_values.append(parsed_value.release_nonnull());
        }
        if (!parsed_values.is_empty() && parsed_values.size() <= property_maximum_value_count(property_id))
            return { StyleValueList::create(move(parsed_values), StyleValueList::Separator::Space) };
    }

    return ParseError::SyntaxError;
}

RefPtr<StyleValue> Parser::parse_css_value(ComponentValue const& component_value)
{
    if (auto builtin = parse_builtin_value(component_value))
        return builtin;

    if (auto dynamic = parse_dynamic_value(component_value))
        return dynamic;

    // We parse colors before numbers, to catch hashless hex colors.
    if (auto color = parse_color_value(component_value))
        return color;

    if (auto dimension = parse_dimension_value(component_value))
        return dimension;

    if (auto numeric = parse_numeric_value(component_value))
        return numeric;

    if (auto identifier = parse_identifier_value(component_value))
        return identifier;

    if (auto string = parse_string_value(component_value))
        return string;

    if (auto image = parse_image_value(component_value))
        return image;

    if (auto rect = parse_rect_value(component_value))
        return rect;

    return {};
}

Optional<Selector::SimpleSelector::ANPlusBPattern> Parser::parse_a_n_plus_b_pattern(TokenStream<ComponentValue>& values)
{
    auto transaction = values.begin_transaction();
    auto syntax_error = [&]() -> Optional<Selector::SimpleSelector::ANPlusBPattern> {
        if constexpr (CSS_PARSER_DEBUG) {
            dbgln_if(CSS_PARSER_DEBUG, "Invalid An+B value:");
            values.dump_all_tokens();
        }
        return {};
    };

    auto is_n = [](ComponentValue const& value) -> bool {
        return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_ascii_case("n"sv);
    };
    auto is_ndash = [](ComponentValue const& value) -> bool {
        return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_ascii_case("n-"sv);
    };
    auto is_dashn = [](ComponentValue const& value) -> bool {
        return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_ascii_case("-n"sv);
    };
    auto is_dashndash = [](ComponentValue const& value) -> bool {
        return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_ascii_case("-n-"sv);
    };
    auto is_delim = [](ComponentValue const& value, u32 delim) -> bool {
        return value.is(Token::Type::Delim) && value.token().delim() == delim;
    };
    auto is_sign = [](ComponentValue const& value) -> bool {
        return value.is(Token::Type::Delim) && (value.token().delim() == '+' || value.token().delim() == '-');
    };
    auto is_n_dimension = [](ComponentValue const& value) -> bool {
        if (!value.is(Token::Type::Dimension))
            return false;
        if (!value.token().number().is_integer())
            return false;
        if (!value.token().dimension_unit().equals_ignoring_ascii_case("n"sv))
            return false;
        return true;
    };
    auto is_ndash_dimension = [](ComponentValue const& value) -> bool {
        if (!value.is(Token::Type::Dimension))
            return false;
        if (!value.token().number().is_integer())
            return false;
        if (!value.token().dimension_unit().equals_ignoring_ascii_case("n-"sv))
            return false;
        return true;
    };
    auto is_ndashdigit_dimension = [](ComponentValue const& value) -> bool {
        if (!value.is(Token::Type::Dimension))
            return false;
        if (!value.token().number().is_integer())
            return false;
        auto dimension_unit = value.token().dimension_unit();
        if (!dimension_unit.starts_with("n-"sv, CaseSensitivity::CaseInsensitive))
            return false;
        for (size_t i = 2; i < dimension_unit.length(); ++i) {
            if (!is_ascii_digit(dimension_unit[i]))
                return false;
        }
        return true;
    };
    auto is_ndashdigit_ident = [](ComponentValue const& value) -> bool {
        if (!value.is(Token::Type::Ident))
            return false;
        auto ident = value.token().ident();
        if (!ident.starts_with("n-"sv, CaseSensitivity::CaseInsensitive))
            return false;
        for (size_t i = 2; i < ident.length(); ++i) {
            if (!is_ascii_digit(ident[i]))
                return false;
        }
        return true;
    };
    auto is_dashndashdigit_ident = [](ComponentValue const& value) -> bool {
        if (!value.is(Token::Type::Ident))
            return false;
        auto ident = value.token().ident();
        if (!ident.starts_with("-n-"sv, CaseSensitivity::CaseInsensitive))
            return false;
        if (ident.length() == 3)
            return false;
        for (size_t i = 3; i < ident.length(); ++i) {
            if (!is_ascii_digit(ident[i]))
                return false;
        }
        return true;
    };
    auto is_integer = [](ComponentValue const& value) -> bool {
        return value.is(Token::Type::Number) && value.token().number().is_integer();
    };
    auto is_signed_integer = [](ComponentValue const& value) -> bool {
        return value.is(Token::Type::Number) && value.token().number().is_integer_with_explicit_sign();
    };
    auto is_signless_integer = [](ComponentValue const& value) -> bool {
        return value.is(Token::Type::Number) && !value.token().number().is_integer_with_explicit_sign();
    };

    // https://www.w3.org/TR/css-syntax-3/#the-anb-type
    // Unfortunately these can't be in the same order as in the spec.

    values.skip_whitespace();
    auto const& first_value = values.next_token();

    // odd | even
    if (first_value.is(Token::Type::Ident)) {
        auto ident = first_value.token().ident();
        if (ident.equals_ignoring_ascii_case("odd"sv)) {
            transaction.commit();
            return Selector::SimpleSelector::ANPlusBPattern { 2, 1 };
        }
        if (ident.equals_ignoring_ascii_case("even"sv)) {
            transaction.commit();
            return Selector::SimpleSelector::ANPlusBPattern { 2, 0 };
        }
    }
    // <integer>
    if (is_integer(first_value)) {
        int b = first_value.token().to_integer();
        transaction.commit();
        return Selector::SimpleSelector::ANPlusBPattern { 0, b };
    }
    // <n-dimension>
    // <n-dimension> <signed-integer>
    // <n-dimension> ['+' | '-'] <signless-integer>
    if (is_n_dimension(first_value)) {
        int a = first_value.token().dimension_value_int();
        values.skip_whitespace();

        // <n-dimension> <signed-integer>
        if (is_signed_integer(values.peek_token())) {
            int b = values.next_token().token().to_integer();
            transaction.commit();
            return Selector::SimpleSelector::ANPlusBPattern { a, b };
        }

        // <n-dimension> ['+' | '-'] <signless-integer>
        {
            auto child_transaction = transaction.create_child();
            auto const& second_value = values.next_token();
            values.skip_whitespace();
            auto const& third_value = values.next_token();

            if (is_sign(second_value) && is_signless_integer(third_value)) {
                int b = third_value.token().to_integer() * (is_delim(second_value, '+') ? 1 : -1);
                child_transaction.commit();
                return Selector::SimpleSelector::ANPlusBPattern { a, b };
            }
        }

        // <n-dimension>
        transaction.commit();
        return Selector::SimpleSelector::ANPlusBPattern { a, 0 };
    }
    // <ndash-dimension> <signless-integer>
    if (is_ndash_dimension(first_value)) {
        values.skip_whitespace();
        auto const& second_value = values.next_token();
        if (is_signless_integer(second_value)) {
            int a = first_value.token().dimension_value_int();
            int b = -second_value.token().to_integer();
            transaction.commit();
            return Selector::SimpleSelector::ANPlusBPattern { a, b };
        }

        return syntax_error();
    }
    // <ndashdigit-dimension>
    if (is_ndashdigit_dimension(first_value)) {
        auto const& dimension = first_value.token();
        int a = dimension.dimension_value_int();
        auto maybe_b = dimension.dimension_unit().substring_view(1).to_int();
        if (maybe_b.has_value()) {
            transaction.commit();
            return Selector::SimpleSelector::ANPlusBPattern { a, maybe_b.value() };
        }

        return syntax_error();
    }
    // <dashndashdigit-ident>
    if (is_dashndashdigit_ident(first_value)) {
        auto maybe_b = first_value.token().ident().substring_view(2).to_int();
        if (maybe_b.has_value()) {
            transaction.commit();
            return Selector::SimpleSelector::ANPlusBPattern { -1, maybe_b.value() };
        }

        return syntax_error();
    }
    // -n
    // -n <signed-integer>
    // -n ['+' | '-'] <signless-integer>
    if (is_dashn(first_value)) {
        values.skip_whitespace();

        // -n <signed-integer>
        if (is_signed_integer(values.peek_token())) {
            int b = values.next_token().token().to_integer();
            transaction.commit();
            return Selector::SimpleSelector::ANPlusBPattern { -1, b };
        }

        // -n ['+' | '-'] <signless-integer>
        {
            auto child_transaction = transaction.create_child();
            auto const& second_value = values.next_token();
            values.skip_whitespace();
            auto const& third_value = values.next_token();

            if (is_sign(second_value) && is_signless_integer(third_value)) {
                int b = third_value.token().to_integer() * (is_delim(second_value, '+') ? 1 : -1);
                child_transaction.commit();
                return Selector::SimpleSelector::ANPlusBPattern { -1, b };
            }
        }

        // -n
        transaction.commit();
        return Selector::SimpleSelector::ANPlusBPattern { -1, 0 };
    }
    // -n- <signless-integer>
    if (is_dashndash(first_value)) {
        values.skip_whitespace();
        auto const& second_value = values.next_token();
        if (is_signless_integer(second_value)) {
            int b = -second_value.token().to_integer();
            transaction.commit();
            return Selector::SimpleSelector::ANPlusBPattern { -1, b };
        }

        return syntax_error();
    }

    // All that's left now are these:
    // '+'?† n
    // '+'?† n <signed-integer>
    // '+'?† n ['+' | '-'] <signless-integer>
    // '+'?† n- <signless-integer>
    // '+'?† <ndashdigit-ident>
    // In all of these cases, the + is optional, and has no effect.
    // So, we just skip the +, and carry on.
    if (!is_delim(first_value, '+')) {
        values.reconsume_current_input_token();
        // We do *not* skip whitespace here.
    }

    auto const& first_after_plus = values.next_token();
    // '+'?† n
    // '+'?† n <signed-integer>
    // '+'?† n ['+' | '-'] <signless-integer>
    if (is_n(first_after_plus)) {
        values.skip_whitespace();

        // '+'?† n <signed-integer>
        if (is_signed_integer(values.peek_token())) {
            int b = values.next_token().token().to_integer();
            transaction.commit();
            return Selector::SimpleSelector::ANPlusBPattern { 1, b };
        }

        // '+'?† n ['+' | '-'] <signless-integer>
        {
            auto child_transaction = transaction.create_child();
            auto const& second_value = values.next_token();
            values.skip_whitespace();
            auto const& third_value = values.next_token();

            if (is_sign(second_value) && is_signless_integer(third_value)) {
                int b = third_value.token().to_integer() * (is_delim(second_value, '+') ? 1 : -1);
                child_transaction.commit();
                return Selector::SimpleSelector::ANPlusBPattern { 1, b };
            }
        }

        // '+'?† n
        transaction.commit();
        return Selector::SimpleSelector::ANPlusBPattern { 1, 0 };
    }

    // '+'?† n- <signless-integer>
    if (is_ndash(first_after_plus)) {
        values.skip_whitespace();
        auto const& second_value = values.next_token();
        if (is_signless_integer(second_value)) {
            int b = -second_value.token().to_integer();
            transaction.commit();
            return Selector::SimpleSelector::ANPlusBPattern { 1, b };
        }

        return syntax_error();
    }

    // '+'?† <ndashdigit-ident>
    if (is_ndashdigit_ident(first_after_plus)) {
        auto maybe_b = first_after_plus.token().ident().substring_view(1).to_int();
        if (maybe_b.has_value()) {
            transaction.commit();
            return Selector::SimpleSelector::ANPlusBPattern { 1, maybe_b.value() };
        }

        return syntax_error();
    }

    return syntax_error();
}

OwnPtr<CalculatedStyleValue::CalcSum> Parser::parse_calc_expression(Vector<ComponentValue> const& values)
{
    auto tokens = TokenStream(values);
    return parse_calc_sum(tokens);
}

Optional<CalculatedStyleValue::CalcValue> Parser::parse_calc_value(TokenStream<ComponentValue>& tokens)
{
    auto current_token = tokens.next_token();

    if (current_token.is_block() && current_token.block().is_paren()) {
        auto block_values = TokenStream(current_token.block().values());
        auto parsed_calc_sum = parse_calc_sum(block_values);
        if (!parsed_calc_sum)
            return {};
        return CalculatedStyleValue::CalcValue { parsed_calc_sum.release_nonnull() };
    }

    if (current_token.is(Token::Type::Number))
        return CalculatedStyleValue::CalcValue { current_token.token().number() };

    if (current_token.is(Token::Type::Dimension) || current_token.is(Token::Type::Percentage)) {
        auto maybe_dimension = parse_dimension(current_token);
        if (!maybe_dimension.has_value())
            return {};
        auto& dimension = maybe_dimension.value();

        if (dimension.is_angle())
            return CalculatedStyleValue::CalcValue { dimension.angle() };
        if (dimension.is_frequency())
            return CalculatedStyleValue::CalcValue { dimension.frequency() };
        if (dimension.is_length())
            return CalculatedStyleValue::CalcValue { dimension.length() };
        if (dimension.is_percentage())
            return CalculatedStyleValue::CalcValue { dimension.percentage() };
        if (dimension.is_resolution()) {
            // Resolution is not allowed in calc()
            return {};
        }
        if (dimension.is_time())
            return CalculatedStyleValue::CalcValue { dimension.time() };
        VERIFY_NOT_REACHED();
    }

    return {};
}

OwnPtr<CalculatedStyleValue::CalcProductPartWithOperator> Parser::parse_calc_product_part_with_operator(TokenStream<ComponentValue>& tokens)
{
    // Note: The default value is not used or passed around.
    auto product_with_operator = make<CalculatedStyleValue::CalcProductPartWithOperator>(
        CalculatedStyleValue::ProductOperation::Multiply,
        CalculatedStyleValue::CalcNumberValue { Number {} });

    tokens.skip_whitespace();

    auto const& op_token = tokens.peek_token();
    if (!op_token.is(Token::Type::Delim))
        return nullptr;

    auto op = op_token.token().delim();
    if (op == '*') {
        tokens.next_token();
        tokens.skip_whitespace();
        product_with_operator->op = CalculatedStyleValue::ProductOperation::Multiply;
        auto parsed_calc_value = parse_calc_value(tokens);
        if (!parsed_calc_value.has_value())
            return nullptr;
        product_with_operator->value = { parsed_calc_value.release_value() };

    } else if (op == '/') {
        // FIXME: Detect divide-by-zero if possible
        tokens.next_token();
        tokens.skip_whitespace();
        product_with_operator->op = CalculatedStyleValue::ProductOperation::Divide;
        auto parsed_calc_number_value = parse_calc_number_value(tokens);
        if (!parsed_calc_number_value.has_value())
            return nullptr;
        product_with_operator->value = { parsed_calc_number_value.release_value() };
    } else {
        return nullptr;
    }

    return product_with_operator;
}

OwnPtr<CalculatedStyleValue::CalcNumberProductPartWithOperator> Parser::parse_calc_number_product_part_with_operator(TokenStream<ComponentValue>& tokens)
{
    // Note: The default value is not used or passed around.
    auto number_product_with_operator = make<CalculatedStyleValue::CalcNumberProductPartWithOperator>(
        CalculatedStyleValue::ProductOperation::Multiply,
        CalculatedStyleValue::CalcNumberValue { Number {} });

    tokens.skip_whitespace();

    auto const& op_token = tokens.peek_token();
    if (!op_token.is(Token::Type::Delim))
        return nullptr;

    auto op = op_token.token().delim();
    if (op == '*') {
        tokens.next_token();
        tokens.skip_whitespace();
        number_product_with_operator->op = CalculatedStyleValue::ProductOperation::Multiply;
    } else if (op == '/') {
        // FIXME: Detect divide-by-zero if possible
        tokens.next_token();
        tokens.skip_whitespace();
        number_product_with_operator->op = CalculatedStyleValue::ProductOperation::Divide;
    } else {
        return nullptr;
    }

    auto parsed_calc_value = parse_calc_number_value(tokens);
    if (!parsed_calc_value.has_value())
        return nullptr;
    number_product_with_operator->value = parsed_calc_value.release_value();

    return number_product_with_operator;
}

OwnPtr<CalculatedStyleValue::CalcNumberProduct> Parser::parse_calc_number_product(TokenStream<ComponentValue>& tokens)
{
    auto calc_number_product = make<CalculatedStyleValue::CalcNumberProduct>(
        CalculatedStyleValue::CalcNumberValue { Number {} },
        Vector<NonnullOwnPtr<CalculatedStyleValue::CalcNumberProductPartWithOperator>> {});

    auto first_calc_number_value_or_error = parse_calc_number_value(tokens);
    if (!first_calc_number_value_or_error.has_value())
        return nullptr;
    calc_number_product->first_calc_number_value = first_calc_number_value_or_error.release_value();

    while (tokens.has_next_token()) {
        auto number_product_with_operator = parse_calc_number_product_part_with_operator(tokens);
        if (!number_product_with_operator)
            break;
        calc_number_product->zero_or_more_additional_calc_number_values.append(number_product_with_operator.release_nonnull());
    }

    return calc_number_product;
}

OwnPtr<CalculatedStyleValue::CalcNumberSumPartWithOperator> Parser::parse_calc_number_sum_part_with_operator(TokenStream<ComponentValue>& tokens)
{
    if (!(tokens.peek_token().is(Token::Type::Delim)
            && (tokens.peek_token().token().delim() == '+' || tokens.peek_token().token().delim() == '-')
            && tokens.peek_token(1).is(Token::Type::Whitespace)))
        return nullptr;

    auto const& token = tokens.next_token();
    tokens.skip_whitespace();

    CalculatedStyleValue::SumOperation op;
    auto delim = token.token().delim();
    if (delim == '+')
        op = CalculatedStyleValue::SumOperation::Add;
    else if (delim == '-')
        op = CalculatedStyleValue::SumOperation::Subtract;
    else
        return nullptr;

    auto calc_number_product = parse_calc_number_product(tokens);
    if (!calc_number_product)
        return nullptr;
    return make<CalculatedStyleValue::CalcNumberSumPartWithOperator>(op, calc_number_product.release_nonnull());
}

OwnPtr<CalculatedStyleValue::CalcNumberSum> Parser::parse_calc_number_sum(TokenStream<ComponentValue>& tokens)
{
    auto first_calc_number_product_or_error = parse_calc_number_product(tokens);
    if (!first_calc_number_product_or_error)
        return nullptr;

    Vector<NonnullOwnPtr<CalculatedStyleValue::CalcNumberSumPartWithOperator>> additional {};
    while (tokens.has_next_token()) {
        auto calc_sum_part = parse_calc_number_sum_part_with_operator(tokens);
        if (!calc_sum_part)
            return nullptr;
        additional.append(calc_sum_part.release_nonnull());
    }

    tokens.skip_whitespace();

    auto calc_number_sum = make<CalculatedStyleValue::CalcNumberSum>(first_calc_number_product_or_error.release_nonnull(), move(additional));
    return calc_number_sum;
}

Optional<CalculatedStyleValue::CalcNumberValue> Parser::parse_calc_number_value(TokenStream<ComponentValue>& tokens)
{
    auto const& first = tokens.peek_token();
    if (first.is_block() && first.block().is_paren()) {
        tokens.next_token();
        auto block_values = TokenStream(first.block().values());
        auto calc_number_sum = parse_calc_number_sum(block_values);
        if (calc_number_sum)
            return CalculatedStyleValue::CalcNumberValue { calc_number_sum.release_nonnull() };
    }

    if (!first.is(Token::Type::Number))
        return {};
    tokens.next_token();

    return CalculatedStyleValue::CalcNumberValue { first.token().number() };
}

OwnPtr<CalculatedStyleValue::CalcProduct> Parser::parse_calc_product(TokenStream<ComponentValue>& tokens)
{
    auto calc_product = make<CalculatedStyleValue::CalcProduct>(
        CalculatedStyleValue::CalcValue { Number {} },
        Vector<NonnullOwnPtr<CalculatedStyleValue::CalcProductPartWithOperator>> {});

    auto first_calc_value_or_error = parse_calc_value(tokens);
    if (!first_calc_value_or_error.has_value())
        return nullptr;
    calc_product->first_calc_value = first_calc_value_or_error.release_value();

    while (tokens.has_next_token()) {
        auto product_with_operator = parse_calc_product_part_with_operator(tokens);
        if (!product_with_operator)
            break;
        calc_product->zero_or_more_additional_calc_values.append(product_with_operator.release_nonnull());
    }

    return calc_product;
}

OwnPtr<CalculatedStyleValue::CalcSumPartWithOperator> Parser::parse_calc_sum_part_with_operator(TokenStream<ComponentValue>& tokens)
{
    // The following has to have the shape of <Whitespace><+ or -><Whitespace>
    // But the first whitespace gets eaten in parse_calc_product_part_with_operator().
    if (!(tokens.peek_token().is(Token::Type::Delim)
            && (tokens.peek_token().token().delim() == '+' || tokens.peek_token().token().delim() == '-')
            && tokens.peek_token(1).is(Token::Type::Whitespace)))
        return nullptr;

    auto const& token = tokens.next_token();
    tokens.skip_whitespace();

    CalculatedStyleValue::SumOperation op;
    auto delim = token.token().delim();
    if (delim == '+')
        op = CalculatedStyleValue::SumOperation::Add;
    else if (delim == '-')
        op = CalculatedStyleValue::SumOperation::Subtract;
    else
        return nullptr;

    auto calc_product = parse_calc_product(tokens);
    if (!calc_product)
        return nullptr;
    return make<CalculatedStyleValue::CalcSumPartWithOperator>(op, calc_product.release_nonnull());
};

OwnPtr<CalculatedStyleValue::CalcSum> Parser::parse_calc_sum(TokenStream<ComponentValue>& tokens)
{
    auto parsed_calc_product = parse_calc_product(tokens);
    if (!parsed_calc_product)
        return nullptr;

    Vector<NonnullOwnPtr<CalculatedStyleValue::CalcSumPartWithOperator>> additional {};
    while (tokens.has_next_token()) {
        auto calc_sum_part = parse_calc_sum_part_with_operator(tokens);
        if (!calc_sum_part)
            return nullptr;
        additional.append(calc_sum_part.release_nonnull());
    }

    tokens.skip_whitespace();

    return make<CalculatedStyleValue::CalcSum>(parsed_calc_product.release_nonnull(), move(additional));
}

bool Parser::has_ignored_vendor_prefix(StringView string)
{
    if (!string.starts_with('-'))
        return false;
    if (string.starts_with("--"sv))
        return false;
    if (string.starts_with("-libweb-"sv))
        return false;
    return true;
}

bool Parser::is_builtin(StringView name)
{
    return name.equals_ignoring_ascii_case("inherit"sv)
        || name.equals_ignoring_ascii_case("initial"sv)
        || name.equals_ignoring_ascii_case("unset"sv);
}

RefPtr<CalculatedStyleValue> Parser::parse_calculated_value(Badge<StyleComputer>, ParsingContext const& context, Vector<ComponentValue> const& tokens)
{
    if (tokens.is_empty())
        return {};

    auto parser = Parser::create(context, ""sv).release_value_but_fixme_should_propagate_errors();
    return parser.parse_calculated_value(tokens);
}

RefPtr<StyleValue> Parser::parse_css_value(Badge<StyleComputer>, ParsingContext const& context, PropertyID property_id, Vector<ComponentValue> const& tokens)
{
    if (tokens.is_empty() || property_id == CSS::PropertyID::Invalid || property_id == CSS::PropertyID::Custom)
        return {};

    auto parser = Parser::create(context, ""sv).release_value_but_fixme_should_propagate_errors();
    TokenStream<ComponentValue> token_stream { tokens };
    auto result = parser.parse_css_value(property_id, token_stream);
    if (result.is_error())
        return {};
    return result.release_value();
}

bool Parser::Dimension::is_angle() const
{
    return m_value.has<Angle>();
}

Angle Parser::Dimension::angle() const
{
    return m_value.get<Angle>();
}

bool Parser::Dimension::is_angle_percentage() const
{
    return is_angle() || is_percentage();
}

AnglePercentage Parser::Dimension::angle_percentage() const
{
    if (is_angle())
        return angle();
    if (is_percentage())
        return percentage();
    VERIFY_NOT_REACHED();
}

bool Parser::Dimension::is_frequency() const
{
    return m_value.has<Frequency>();
}

Frequency Parser::Dimension::frequency() const
{
    return m_value.get<Frequency>();
}

bool Parser::Dimension::is_frequency_percentage() const
{
    return is_frequency() || is_percentage();
}

FrequencyPercentage Parser::Dimension::frequency_percentage() const
{
    if (is_frequency())
        return frequency();
    if (is_percentage())
        return percentage();
    VERIFY_NOT_REACHED();
}

bool Parser::Dimension::is_length() const
{
    return m_value.has<Length>();
}

Length Parser::Dimension::length() const
{
    return m_value.get<Length>();
}

bool Parser::Dimension::is_length_percentage() const
{
    return is_length() || is_percentage();
}

LengthPercentage Parser::Dimension::length_percentage() const
{
    if (is_length())
        return length();
    if (is_percentage())
        return percentage();
    VERIFY_NOT_REACHED();
}

bool Parser::Dimension::is_percentage() const
{
    return m_value.has<Percentage>();
}

Percentage Parser::Dimension::percentage() const
{
    return m_value.get<Percentage>();
}

bool Parser::Dimension::is_resolution() const
{
    return m_value.has<Resolution>();
}

Resolution Parser::Dimension::resolution() const
{
    return m_value.get<Resolution>();
}

bool Parser::Dimension::is_time() const
{
    return m_value.has<Time>();
}

Time Parser::Dimension::time() const
{
    return m_value.get<Time>();
}

bool Parser::Dimension::is_time_percentage() const
{
    return is_time() || is_percentage();
}

TimePercentage Parser::Dimension::time_percentage() const
{
    if (is_time())
        return time();
    if (is_percentage())
        return percentage();
    VERIFY_NOT_REACHED();
}
}

namespace Web {

CSS::CSSStyleSheet* parse_css_stylesheet(CSS::Parser::ParsingContext const& context, StringView css, Optional<AK::URL> location)
{
    if (css.is_empty()) {
        auto rule_list = CSS::CSSRuleList::create_empty(context.realm()).release_value_but_fixme_should_propagate_errors();
        auto media_list = CSS::MediaList::create(context.realm(), {}).release_value_but_fixme_should_propagate_errors();
        return CSS::CSSStyleSheet::create(context.realm(), rule_list, media_list, location).release_value_but_fixme_should_propagate_errors();
    }
    auto parser = CSS::Parser::Parser::create(context, css).release_value_but_fixme_should_propagate_errors();
    return parser.parse_as_css_stylesheet(location);
}

CSS::ElementInlineCSSStyleDeclaration* parse_css_style_attribute(CSS::Parser::ParsingContext const& context, StringView css, DOM::Element& element)
{
    if (css.is_empty())
        return CSS::ElementInlineCSSStyleDeclaration::create(element, {}, {}).release_value_but_fixme_should_propagate_errors();
    auto parser = CSS::Parser::Parser::create(context, css).release_value_but_fixme_should_propagate_errors();
    return parser.parse_as_style_attribute(element);
}

RefPtr<CSS::StyleValue> parse_css_value(CSS::Parser::ParsingContext const& context, StringView string, CSS::PropertyID property_id)
{
    if (string.is_empty())
        return {};
    auto parser = CSS::Parser::Parser::create(context, string).release_value_but_fixme_should_propagate_errors();
    return parser.parse_as_css_value(property_id);
}

CSS::CSSRule* parse_css_rule(CSS::Parser::ParsingContext const& context, StringView css_text)
{
    auto parser = CSS::Parser::Parser::create(context, css_text).release_value_but_fixme_should_propagate_errors();
    return parser.parse_as_css_rule();
}

Optional<CSS::SelectorList> parse_selector(CSS::Parser::ParsingContext const& context, StringView selector_text)
{
    auto parser = CSS::Parser::Parser::create(context, selector_text).release_value_but_fixme_should_propagate_errors();
    return parser.parse_as_selector();
}

RefPtr<CSS::MediaQuery> parse_media_query(CSS::Parser::ParsingContext const& context, StringView string)
{
    auto parser = CSS::Parser::Parser::create(context, string).release_value_but_fixme_should_propagate_errors();
    return parser.parse_as_media_query();
}

Vector<NonnullRefPtr<CSS::MediaQuery>> parse_media_query_list(CSS::Parser::ParsingContext const& context, StringView string)
{
    auto parser = CSS::Parser::Parser::create(context, string).release_value_but_fixme_should_propagate_errors();
    return parser.parse_as_media_query_list();
}

RefPtr<CSS::Supports> parse_css_supports(CSS::Parser::ParsingContext const& context, StringView string)
{
    if (string.is_empty())
        return {};
    auto parser = CSS::Parser::Parser::create(context, string).release_value_but_fixme_should_propagate_errors();
    return parser.parse_as_supports();
}

Optional<CSS::StyleProperty> parse_css_supports_condition(CSS::Parser::ParsingContext const& context, StringView string)
{
    if (string.is_empty())
        return {};
    auto parser = CSS::Parser::Parser::create(context, string).release_value_but_fixme_should_propagate_errors();
    return parser.parse_as_supports_condition();
}

}