accent_sass_compiler 0.16.0

Internal implementation of the accent-sass compiler
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
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
use std::{iter::Iterator, marker::PhantomData, sync::Arc};

use codemap::Spanned;

use crate::{
    ContextFlags, Token,
    ast::*,
    color::{Color, ColorFormat, NAMED_COLORS},
    common::{BinaryOp, Brackets, Identifier, ListSeparator, QuoteKind, UnaryOp, unvendor},
    error::SassResult,
    unit::Unit,
    utils::{as_hex, is_name_start, opposite_bracket},
    value::{CalculationName, Number},
};

use super::StylesheetParser;

pub(crate) type Predicate<'c, P> = &'c dyn Fn(&mut P) -> SassResult<bool>;

fn is_hex_color(interpolation: &Interpolation) -> bool {
    if let Some(plain) = interpolation.as_plain() {
        if ![3, 4, 6, 8].contains(&plain.len()) {
            return false;
        }

        return plain.chars().all(|c| c.is_ascii_hexdigit());
    }

    false
}

/// Where an operand of a calculation sits, which decides what a failure to
/// find one is called.
///
/// Dart Sass parses a calculation with its ordinary expression parser, so the
/// two positions fail differently and this reproduces that. Nothing is
/// committed at the start of an argument, and `calc(,)` reads as a malformed
/// function call -- `expected ")".`. An operator has promised an operand, so
/// `calc(1px *)` is a missing one -- `Expected expression.`. Both were taken
/// from dart-sass 1.103.1.
#[derive(Clone, Copy, Debug)]
pub(crate) enum OperandPosition {
    /// The first operand of a calculation argument.
    ArgumentStart,
    /// An operand an operator has already promised.
    AfterOperator,
}

impl OperandPosition {
    /// What to say when no operand is there.
    fn no_operand(self) -> &'static str {
        match self {
            Self::ArgumentStart => "expected \")\".",
            Self::AfterOperator => "Expected expression.",
        }
    }
}

pub(crate) struct ValueParser<'a, 'c, P: StylesheetParser<'a>> {
    comma_expressions: Option<Vec<Spanned<AstExpr>>>,
    space_expressions: Option<Vec<Spanned<AstExpr>>>,
    binary_operators: Option<Vec<BinaryOp>>,
    operands: Option<Vec<Spanned<AstExpr>>>,
    allow_slash: bool,
    single_expression: Option<Spanned<AstExpr>>,
    start: usize,
    inside_bracketed_list: bool,
    single_equals: bool,
    /// Whether a newline counts as whitespace inside this expression.
    ///
    /// Only the indented syntax cares; see
    /// [`BaseParser::whitespace_without_comments`].
    consume_newlines: bool,
    parse_until: Option<Predicate<'c, P>>,
    _a: PhantomData<&'a ()>,
}

/// Whether a condition contains a `sass()` expression at any depth.
fn condition_contains_sass(condition: &CssIfCondition) -> bool {
    match condition {
        CssIfCondition::Sass(..) => true,
        CssIfCondition::Else | CssIfCondition::Raw(..) => false,
        CssIfCondition::Paren(inner) | CssIfCondition::Not(inner) => condition_contains_sass(inner),
        CssIfCondition::And(operands) | CssIfCondition::Or(operands) => {
            operands.iter().any(condition_contains_sass)
        }
    }
}

/// One term of a CSS `if()` condition, before it is known whether the term
/// stands alone or is part of an opaque run.
enum CssIfAtom {
    Sass(AstExpr),
    Paren(CssIfCondition),
    Raw(Interpolation),
}

/// The calculation-only constants, matched case-insensitively.
///
/// They are ordinary identifiers outside a calculation, so this lookup only
/// ever runs from [`ValueParser::parse_calculation_identifier`]. Note that only
/// `infinity` has a negated spelling; `-pi` and `-e` stay identifiers.
fn calculation_constant_value(lowercase: &str) -> Option<f64> {
    Some(match lowercase {
        "pi" => std::f64::consts::PI,
        "e" => std::f64::consts::E,
        "infinity" => f64::INFINITY,
        "-infinity" => f64::NEG_INFINITY,
        "nan" => f64::NAN,
        _ => return None,
    })
}

impl<'a, 'c, P: StylesheetParser<'a>> ValueParser<'a, 'c, P> {
    pub fn parse_expression(
        parser: &mut P,
        parse_until: Option<Predicate<'c, P>>,
        consume_newlines: bool,
        inside_bracketed_list: bool,
        single_equals: bool,
    ) -> SassResult<Spanned<AstExpr>> {
        let start = parser.toks().cursor();
        let mut value_parser = Self::new(
            parser,
            parse_until,
            consume_newlines,
            inside_bracketed_list,
            single_equals,
        );

        if let Some(parse_until) = value_parser.parse_until
            && parse_until(parser)?
        {
            return Err(("Expected expression.", parser.toks().current_span()).into());
        }

        if value_parser.inside_bracketed_list {
            let bracket_start = parser.toks().cursor();

            parser.expect_char('[')?;
            parser.whitespace(true)?;

            if parser.scan_char(']') {
                return Ok(AstExpr::List(ListExpr {
                    elems: Vec::new(),
                    separator: ListSeparator::Undecided,
                    brackets: Brackets::Bracketed,
                })
                .span(parser.toks_mut().span_from(bracket_start)));
            }
        };

        // From here on the parser is inside an expression, which plain CSS cares
        // about: `//` in a value is two slashes, not a silent comment.
        let was_in_expression = parser.flags().in_expression();
        parser.flags_mut().set(ContextFlags::IN_EXPRESSION, true);

        let value = value_parser.parse_expression_body(parser, start);

        parser
            .flags_mut()
            .set(ContextFlags::IN_EXPRESSION, was_in_expression);

        value
    }

    /// Parses the expression itself, once [`ValueParser::parse_expression`] has
    /// dealt with the bracketed-list prefix.
    ///
    /// `start` is the cursor from before that prefix, so the span covers it.
    fn parse_expression_body(
        &mut self,
        parser: &mut P,
        start: usize,
    ) -> SassResult<Spanned<AstExpr>> {
        self.start = parser.toks().cursor();

        self.single_expression = Some(self.parse_single_expression(parser)?);

        let mut value = self.parse_value(parser)?;
        value.span = parser.toks_mut().span_from(start);

        Ok(value)
    }

    pub fn new(
        parser: &mut P,
        parse_until: Option<Predicate<'c, P>>,
        consume_newlines: bool,
        inside_bracketed_list: bool,
        single_equals: bool,
    ) -> Self {
        Self {
            comma_expressions: None,
            space_expressions: None,
            binary_operators: None,
            operands: None,
            allow_slash: true,
            start: parser.toks().cursor(),
            single_expression: None,
            parse_until,
            consume_newlines,
            inside_bracketed_list,
            single_equals,
            _a: PhantomData,
        }
    }

    /// Parse a value from a stream of tokens
    ///
    /// This function will cease parsing if the predicate returns true.
    pub(crate) fn parse_value(&mut self, parser: &mut P) -> SassResult<Spanned<AstExpr>> {
        // A bracketed list is inside brackets, so a newline is whitespace there
        // whatever the caller asked for.
        let consume_newlines = self.consume_newlines || self.inside_bracketed_list;

        parser.whitespace(consume_newlines)?;

        let start = parser.toks().cursor();

        let was_in_parens = parser.flags().in_parens();

        loop {
            parser.whitespace(consume_newlines)?;

            if let Some(parse_until) = self.parse_until
                && parse_until(parser)?
            {
                break;
            }

            let first = parser.toks().peek();

            match first {
                Some(Token { kind: '(', .. }) => {
                    let expr = self.parse_paren_expr(parser)?;
                    self.add_single_expression(expr, parser)?;
                }
                Some(Token { kind: '[', .. }) => {
                    let expr = parser.parse_expression(None, false, Some(true), None)?;
                    self.add_single_expression(expr, parser)?;
                }
                Some(Token { kind: '$', .. }) => {
                    let expr = Self::parse_variable(parser)?;
                    self.add_single_expression(expr, parser)?;
                }
                Some(Token { kind: '&', .. }) => {
                    let expr = Self::parse_selector(parser)?;
                    self.add_single_expression(expr, parser)?;
                }
                Some(Token { kind: '"', .. }) | Some(Token { kind: '\'', .. }) => {
                    let expr = parser
                        .parse_interpolated_string()?
                        .map_node(|s| AstExpr::String(s, parser.toks_mut().span_from(start)));
                    self.add_single_expression(expr, parser)?;
                }
                Some(Token { kind: '#', .. }) => {
                    let expr = self.parse_hash(parser)?;
                    self.add_single_expression(expr, parser)?;
                }
                Some(Token { kind: '=', .. }) => {
                    parser.toks_mut().next();
                    if self.single_equals
                        && !matches!(parser.toks().peek(), Some(Token { kind: '=', .. }))
                    {
                        self.add_operator(
                            Spanned {
                                node: BinaryOp::SingleEq,
                                span: parser.toks_mut().span_from(start),
                            },
                            parser,
                        )?;
                    } else {
                        parser.expect_char('=')?;
                        self.add_operator(
                            Spanned {
                                node: BinaryOp::Equal,
                                span: parser.toks_mut().span_from(start),
                            },
                            parser,
                        )?;
                    }
                }
                Some(Token { kind: '!', .. }) => match parser.toks().peek_n(1) {
                    Some(Token { kind: '=', .. }) => {
                        parser.toks_mut().next();
                        parser.toks_mut().next();
                        self.add_operator(
                            Spanned {
                                node: BinaryOp::NotEqual,
                                span: parser.toks_mut().span_from(start),
                            },
                            parser,
                        )?;
                    }
                    Some(Token { kind, .. })
                        if kind.is_ascii_whitespace() || kind == 'i' || kind == 'I' =>
                    {
                        let expr = Self::parse_important_expr(parser)?;
                        self.add_single_expression(expr, parser)?;
                    }
                    None => {
                        let expr = Self::parse_important_expr(parser)?;
                        self.add_single_expression(expr, parser)?;
                    }
                    Some(..) => break,
                },
                Some(Token { kind: '<', .. }) => {
                    parser.toks_mut().next();
                    self.add_operator(
                        Spanned {
                            node: if parser.scan_char('=') {
                                BinaryOp::LessThanEqual
                            } else {
                                BinaryOp::LessThan
                            },
                            span: parser.toks_mut().span_from(start),
                        },
                        parser,
                    )?;
                }
                Some(Token { kind: '>', .. }) => {
                    parser.toks_mut().next();
                    self.add_operator(
                        Spanned {
                            node: if parser.scan_char('=') {
                                BinaryOp::GreaterThanEqual
                            } else {
                                BinaryOp::GreaterThan
                            },
                            span: parser.toks_mut().span_from(start),
                        },
                        parser,
                    )?;
                }
                Some(Token { kind: '*', .. }) => {
                    parser.toks_mut().next();
                    self.add_operator(
                        Spanned {
                            node: BinaryOp::Mul,
                            span: parser.toks().current_span(),
                        },
                        parser,
                    )?;
                }
                Some(Token { kind: '+', .. }) => {
                    if self.single_expression.is_none() {
                        let expr = self.parse_unary_operation(parser)?;
                        self.add_single_expression(expr, parser)?;
                    } else {
                        parser.toks_mut().next();
                        self.add_operator(
                            Spanned {
                                node: BinaryOp::Plus,
                                span: parser.toks_mut().span_from(start),
                            },
                            parser,
                        )?;
                    }
                }
                Some(Token { kind: '-', .. }) => {
                    if matches!(
                        parser.toks().peek_n(1),
                        Some(Token {
                            kind: '0'..='9' | '.',
                            ..
                        })
                    ) && (self.single_expression.is_none()
                        || matches!(
                            parser.toks_mut().peek_previous(),
                            Some(Token {
                                kind: ' ' | '\t' | '\n' | '\r',
                                ..
                            })
                        ))
                    {
                        let expr = ValueParser::parse_number(parser)?;
                        self.add_single_expression(expr, parser)?;
                    } else if parser.looking_at_interpolated_identifier() {
                        let expr = self.parse_identifier_like(parser)?;
                        self.add_single_expression(expr, parser)?;
                    } else if self.single_expression.is_none() {
                        let expr = self.parse_unary_operation(parser)?;
                        self.add_single_expression(expr, parser)?;
                    } else {
                        parser.toks_mut().next();
                        self.add_operator(
                            Spanned {
                                node: BinaryOp::Minus,
                                span: parser.toks_mut().span_from(start),
                            },
                            parser,
                        )?;
                    }
                }
                Some(Token { kind: '/', .. }) => {
                    if self.single_expression.is_none() {
                        let expr = self.parse_unary_operation(parser)?;
                        self.add_single_expression(expr, parser)?;
                    } else {
                        parser.toks_mut().next();
                        self.add_operator(
                            Spanned {
                                node: BinaryOp::Div,
                                span: parser.toks_mut().span_from(start),
                            },
                            parser,
                        )?;
                    }
                }
                Some(Token { kind: '%', .. }) => {
                    if self.percent_is_value(parser) {
                        let expr = Self::parse_percent_value(parser)?;
                        // A `%` value ends any slash-separated list being
                        // built, the way `add_operator` would for a real
                        // operator: `1/2 %` is division, not `1/2` kept as a
                        // slash list.
                        self.allow_slash = false;
                        self.add_single_expression(expr, parser)?;
                    } else {
                        parser.toks_mut().next();
                        self.add_operator(
                            Spanned {
                                node: BinaryOp::Rem,
                                span: parser.toks().current_span(),
                            },
                            parser,
                        )?;
                    }
                }
                Some(Token {
                    kind: '0'..='9', ..
                }) => {
                    let expr = ValueParser::parse_number(parser)?;
                    self.add_single_expression(expr, parser)?;
                }
                Some(Token { kind: '.', .. }) => {
                    if matches!(parser.toks().peek_n(1), Some(Token { kind: '.', .. })) {
                        break;
                    }
                    let expr = ValueParser::parse_number(parser)?;
                    self.add_single_expression(expr, parser)?;
                }
                Some(Token { kind: 'a', .. }) => {
                    if !parser.is_plain_css() && parser.scan_identifier("and", false)? {
                        self.add_operator(
                            Spanned {
                                node: BinaryOp::And,
                                span: parser.toks_mut().span_from(start),
                            },
                            parser,
                        )?;
                    } else {
                        let expr = self.parse_identifier_like(parser)?;
                        self.add_single_expression(expr, parser)?;
                    }
                }
                Some(Token { kind: 'o', .. }) => {
                    if !parser.is_plain_css() && parser.scan_identifier("or", false)? {
                        self.add_operator(
                            Spanned {
                                node: BinaryOp::Or,
                                span: parser.toks_mut().span_from(start),
                            },
                            parser,
                        )?;
                    } else {
                        let expr = self.parse_identifier_like(parser)?;
                        self.add_single_expression(expr, parser)?;
                    }
                }
                Some(Token { kind: 'u', .. }) | Some(Token { kind: 'U', .. }) => {
                    if matches!(parser.toks().peek_n(1), Some(Token { kind: '+', .. })) {
                        let expr = Self::parse_unicode_range(parser)?;
                        self.add_single_expression(expr, parser)?;
                    } else {
                        let expr = self.parse_identifier_like(parser)?;
                        self.add_single_expression(expr, parser)?;
                    }
                }
                Some(Token {
                    kind: 'b'..='z', ..
                })
                | Some(Token {
                    kind: 'A'..='Z', ..
                })
                | Some(Token { kind: '_', .. })
                | Some(Token { kind: '\\', .. })
                | Some(Token {
                    kind: '\u{80}'..=std::char::MAX,
                    ..
                }) => {
                    let expr = self.parse_identifier_like(parser)?;
                    self.add_single_expression(expr, parser)?;
                }
                Some(Token { kind: ',', .. }) => {
                    // If we discover we're parsing a list whose first element is a
                    // division operation, and we're in parentheses, reparse outside of a
                    // paren context. This ensures that `(1/2, 1)` doesn't perform division
                    // on its first element.
                    if parser.flags().in_parens() {
                        parser.flags_mut().set(ContextFlags::IN_PARENS, false);
                        if self.allow_slash {
                            self.reset_state(parser)?;
                            continue;
                        }
                        // todo: does this branch ever get hit
                    }

                    if self.single_expression.is_none() {
                        return Err(("Expected expression.", parser.toks().current_span()).into());
                    }

                    self.resolve_space_expressions(parser)?;

                    // [resolveSpaceExpressions] can modify [singleExpression_], but it
                    // can't set it to null`.
                    self.comma_expressions
                        .get_or_insert_with(Default::default)
                        .push(self.single_expression.take().unwrap());
                    parser.toks_mut().next();
                    self.allow_slash = true;
                }
                Some(..) | None => break,
            }
        }

        if self.inside_bracketed_list {
            parser.expect_char(']')?;
        }

        if self.comma_expressions.is_some() {
            self.resolve_space_expressions(parser)?;

            parser
                .flags_mut()
                .set(ContextFlags::IN_PARENS, was_in_parens);

            if let Some(single_expression) = self.single_expression.take() {
                self.comma_expressions
                    .as_mut()
                    .unwrap()
                    .push(single_expression);
            }

            Ok(AstExpr::List(ListExpr {
                elems: self.comma_expressions.take().unwrap(),
                separator: ListSeparator::Comma,
                brackets: if self.inside_bracketed_list {
                    Brackets::Bracketed
                } else {
                    Brackets::None
                },
            })
            .span(parser.toks_mut().span_from(start)))
        } else if self.inside_bracketed_list && self.space_expressions.is_some() {
            self.resolve_operations(parser)?;

            self.space_expressions
                .as_mut()
                .unwrap()
                .push(self.single_expression.take().unwrap());

            Ok(AstExpr::List(ListExpr {
                elems: self.space_expressions.take().unwrap(),
                separator: ListSeparator::Space,
                brackets: Brackets::Bracketed,
            })
            .span(parser.toks_mut().span_from(start)))
        } else {
            self.resolve_space_expressions(parser)?;

            if self.inside_bracketed_list {
                return Ok(AstExpr::List(ListExpr {
                    elems: vec![self.single_expression.take().unwrap()],
                    separator: ListSeparator::Undecided,
                    brackets: Brackets::Bracketed,
                })
                .span(parser.toks_mut().span_from(start)));
            }

            Ok(self.single_expression.take().unwrap())
        }
    }

    fn parse_single_expression(&mut self, parser: &mut P) -> SassResult<Spanned<AstExpr>> {
        let start = parser.toks().cursor();
        let first = parser.toks().peek();

        match first {
            Some(Token { kind: '(', .. }) => self.parse_paren_expr(parser),
            Some(Token { kind: '/', .. }) => self.parse_unary_operation(parser),
            Some(Token { kind: '[', .. }) => {
                Self::parse_expression(parser, None, false, true, false)
            }
            Some(Token { kind: '$', .. }) => Self::parse_variable(parser),
            Some(Token { kind: '&', .. }) => Self::parse_selector(parser),
            Some(Token { kind: '"', .. }) | Some(Token { kind: '\'', .. }) => Ok(parser
                .parse_interpolated_string()?
                .map_node(|s| AstExpr::String(s, parser.toks_mut().span_from(start)))),
            Some(Token { kind: '#', .. }) => self.parse_hash(parser),
            Some(Token { kind: '%', .. }) => Self::parse_percent_value(parser),
            Some(Token { kind: '+', .. }) => self.parse_plus_expr(parser),
            Some(Token { kind: '-', .. }) => self.parse_minus_expr(parser),
            Some(Token { kind: '!', .. }) => Self::parse_important_expr(parser),
            Some(Token { kind: 'u', .. }) | Some(Token { kind: 'U', .. }) => {
                if matches!(parser.toks().peek_n(1), Some(Token { kind: '+', .. })) {
                    Self::parse_unicode_range(parser)
                } else {
                    self.parse_identifier_like(parser)
                }
            }
            Some(Token {
                kind: '0'..='9', ..
            })
            | Some(Token { kind: '.', .. }) => ValueParser::parse_number(parser),
            Some(Token {
                kind: 'a'..='z', ..
            })
            | Some(Token {
                kind: 'A'..='Z', ..
            })
            | Some(Token { kind: '_', .. })
            | Some(Token { kind: '\\', .. })
            | Some(Token {
                kind: '\u{80}'..=std::char::MAX,
                ..
            }) => self.parse_identifier_like(parser),
            // An empty span where the expression should start, as dart-sass's
            // `scanner.error` gives, rather than one reaching back over what
            // came before it.
            Some(..) | None => Err((
                "Expected expression.",
                parser.toks().current_span().subspan(0, 0),
            )
                .into()),
        }
    }

    fn resolve_one_operation(&mut self, parser: &mut P) -> SassResult<()> {
        let operator = self.binary_operators.as_mut().unwrap().pop().unwrap();
        let operands = self.operands.as_mut().unwrap();

        let left = operands.pop().unwrap();
        let right = match self.single_expression.take() {
            Some(val) => val,
            None => return Err(("Expected expression.", left.span).into()),
        };

        let span = left.span.merge(right.span);

        if self.allow_slash
            && !parser.flags().in_parens()
            && operator == BinaryOp::Div
            && left.node.is_slash_operand()
            && right.node.is_slash_operand()
        {
            self.single_expression = Some(AstExpr::slash(left.node, right.node, span).span(span));
        } else {
            self.single_expression = Some(
                AstExpr::BinaryOp(Arc::new(BinaryOpExpr {
                    lhs: left.node,
                    op: operator,
                    rhs: right.node,
                    allows_slash: false,
                    span,
                }))
                .span(span),
            );
            self.allow_slash = false;
        }

        Ok(())
    }

    fn resolve_operations(&mut self, parser: &mut P) -> SassResult<()> {
        loop {
            let should_break = match self.binary_operators.as_ref() {
                Some(bin) => bin.is_empty(),
                None => true,
            };

            if should_break {
                break;
            }

            self.resolve_one_operation(parser)?;
        }

        Ok(())
    }

    fn add_single_expression(
        &mut self,
        expression: Spanned<AstExpr>,
        parser: &mut P,
    ) -> SassResult<()> {
        if self.single_expression.is_some() {
            // If we discover we're parsing a list whose first element is a division
            // operation, and we're in parentheses, reparse outside of a paren
            // context. This ensures that `(1/2 1)` doesn't perform division on its
            // first element.
            if parser.flags().in_parens() {
                parser.flags_mut().set(ContextFlags::IN_PARENS, false);

                if self.allow_slash {
                    self.reset_state(parser)?;

                    return Ok(());
                }
            }

            if self.space_expressions.is_none() {
                self.space_expressions = Some(Vec::new());
            }

            self.resolve_operations(parser)?;

            self.space_expressions
                .as_mut()
                .unwrap()
                .push(self.single_expression.take().unwrap());

            self.allow_slash = true;
        }

        self.single_expression = Some(expression);

        Ok(())
    }

    fn add_operator(&mut self, op: Spanned<BinaryOp>, parser: &mut P) -> SassResult<()> {
        if parser.is_plain_css() && op.node != BinaryOp::Div && op.node != BinaryOp::SingleEq {
            return Err(("Operators aren't allowed in plain CSS.", op.span).into());
        }

        self.allow_slash = self.allow_slash && op.node == BinaryOp::Div;

        if self.binary_operators.is_none() {
            self.binary_operators = Some(Vec::new());
        }

        if self.operands.is_none() {
            self.operands = Some(Vec::new());
        }

        while let Some(last_op) = self.binary_operators.as_ref().unwrap_or(&Vec::new()).last() {
            if last_op.precedence() < op.precedence() {
                break;
            }

            self.resolve_one_operation(parser)?;
        }
        self.binary_operators
            .get_or_insert_with(Default::default)
            .push(op.node);

        match self.single_expression.take() {
            Some(expr) => {
                self.operands.get_or_insert_with(Vec::new).push(expr);
            }
            None => return Err(("Expected expression.", op.span).into()),
        }

        parser.whitespace(true)?;

        self.single_expression = Some(self.parse_single_expression(parser)?);

        Ok(())
    }

    fn resolve_space_expressions(&mut self, parser: &mut P) -> SassResult<()> {
        self.resolve_operations(parser)?;

        if let Some(mut space_expressions) = self.space_expressions.take() {
            let single_expression = match self.single_expression.take() {
                Some(val) => val,
                None => return Err(("Expected expression.", parser.toks().current_span()).into()),
            };

            let span = single_expression.span;

            space_expressions.push(single_expression);

            self.single_expression = Some(
                AstExpr::List(ListExpr {
                    elems: space_expressions,
                    separator: ListSeparator::Space,
                    brackets: Brackets::None,
                })
                .span(span),
            );
        }

        Ok(())
    }

    fn parse_map(
        parser: &mut P,
        first: Spanned<AstExpr>,
        start: usize,
    ) -> SassResult<Spanned<AstExpr>> {
        let mut pairs = vec![(first, parser.parse_expression_until_comma(false)?.node)];

        while parser.scan_char(',') {
            parser.whitespace(true)?;
            if !parser.looking_at_expression() {
                break;
            }

            let key = parser.parse_expression_until_comma(false)?;
            parser.expect_char(':')?;
            parser.whitespace(true)?;
            let value = parser.parse_expression_until_comma(false)?;
            pairs.push((key, value.node));
        }

        parser.expect_char(')')?;

        Ok(AstExpr::Map(AstSassMap(pairs)).span(parser.toks_mut().span_from(start)))
    }

    fn parse_paren_expr(&mut self, parser: &mut P) -> SassResult<Spanned<AstExpr>> {
        let start = parser.toks().cursor();
        if parser.is_plain_css() {
            return Err((
                "Parentheses aren't allowed in plain CSS.",
                parser.toks().current_span(),
            )
                .into());
        }

        let was_in_parentheses = parser.flags().in_parens();
        parser.flags_mut().set(ContextFlags::IN_PARENS, true);

        parser.expect_char('(')?;
        parser.whitespace(true)?;
        if !parser.looking_at_expression() {
            parser.expect_char(')')?;
            parser
                .flags_mut()
                .set(ContextFlags::IN_PARENS, was_in_parentheses);
            return Ok(AstExpr::List(ListExpr {
                elems: Vec::new(),
                separator: ListSeparator::Undecided,
                brackets: Brackets::None,
            })
            .span(parser.toks_mut().span_from(start)));
        }

        let first = parser.parse_expression_until_comma(false)?;
        if parser.scan_char(':') {
            parser.whitespace(true)?;
            parser
                .flags_mut()
                .set(ContextFlags::IN_PARENS, was_in_parentheses);
            return Self::parse_map(parser, first, start);
        }

        if !parser.scan_char(',') {
            parser.expect_char(')')?;
            parser
                .flags_mut()
                .set(ContextFlags::IN_PARENS, was_in_parentheses);
            return Ok(AstExpr::Paren(Arc::new(first.node)).span(first.span));
        }

        parser.whitespace(true)?;

        let mut expressions = vec![first];

        loop {
            if !parser.looking_at_expression() {
                break;
            }
            expressions.push(parser.parse_expression_until_comma(false)?);
            if !parser.scan_char(',') {
                break;
            }
            parser.whitespace(true)?;
        }

        parser.expect_char(')')?;

        parser
            .flags_mut()
            .set(ContextFlags::IN_PARENS, was_in_parentheses);

        Ok(AstExpr::List(ListExpr {
            elems: expressions,
            separator: ListSeparator::Comma,
            brackets: Brackets::None,
        })
        .span(parser.toks_mut().span_from(start)))
    }

    fn parse_variable(parser: &mut P) -> SassResult<Spanned<AstExpr>> {
        let start = parser.toks().cursor();
        let name = parser.parse_variable_name()?;

        if parser.is_plain_css() {
            return Err((
                "Sass variables aren't allowed in plain CSS.",
                parser.toks_mut().span_from(start),
            )
                .into());
        }

        Ok(AstExpr::Variable {
            name: Spanned {
                node: Identifier::from(name),
                span: parser.toks_mut().span_from(start),
            },
            namespace: None,
        }
        .span(parser.toks_mut().span_from(start)))
    }

    fn parse_selector(parser: &mut P) -> SassResult<Spanned<AstExpr>> {
        if parser.is_plain_css() {
            return Err((
                "The parent selector isn't allowed in plain CSS.",
                parser.toks().current_span(),
            )
                .into());
        }

        let start = parser.toks().cursor();

        parser.expect_char('&')?;

        if parser.toks().next_char_is('&') {
            // todo: emit a warning here
            //   warn(
            //       'In Sass, "&&" means two copies of the parent selector. You '
            //       'probably want to use "and" instead.',
            //       scanner.spanFrom(start));
            //   scanner.position--;
        }

        Ok(AstExpr::ParentSelector.span(parser.toks_mut().span_from(start)))
    }

    fn parse_hash(&mut self, parser: &mut P) -> SassResult<Spanned<AstExpr>> {
        let start = parser.toks().cursor();
        debug_assert!(matches!(
            parser.toks().peek(),
            Some(Token { kind: '#', .. })
        ));

        if matches!(parser.toks().peek_n(1), Some(Token { kind: '{', .. })) {
            return self.parse_identifier_like(parser);
        }

        parser.expect_char('#')?;

        if matches!(
            parser.toks().peek(),
            Some(Token {
                kind: '0'..='9',
                ..
            })
        ) {
            let color = self.parse_hex_color_contents(parser)?;
            return Ok(AstExpr::Color(Arc::new(color)).span(parser.toks_mut().span_from(start)));
        }

        let after_hash = parser.toks().cursor();
        let ident = parser.parse_interpolated_identifier()?;
        if is_hex_color(&ident) {
            parser.toks_mut().set_cursor(after_hash);
            let color = self.parse_hex_color_contents(parser)?;
            return Ok(
                AstExpr::Color(Arc::new(color)).span(parser.toks_mut().span_from(after_hash))
            );
        }

        let mut buffer = Interpolation::new();

        buffer.add_char('#');
        buffer.add_interpolation(ident);

        let span = parser.toks_mut().span_from(start);

        Ok(AstExpr::String(StringExpr(buffer, QuoteKind::None), span).span(span))
    }

    fn parse_hex_digit(&mut self, parser: &mut P) -> SassResult<u32> {
        match parser.toks().peek() {
            Some(Token { kind, .. }) if kind.is_ascii_hexdigit() => {
                parser.toks_mut().next();
                Ok(as_hex(kind))
            }
            _ => Err(("Expected hex digit.", parser.toks().current_span()).into()),
        }
    }

    fn parse_hex_color_contents(&mut self, parser: &mut P) -> SassResult<Color> {
        let start = parser.toks().cursor();

        let digit1 = self.parse_hex_digit(parser)?;
        let digit2 = self.parse_hex_digit(parser)?;
        let digit3 = self.parse_hex_digit(parser)?;

        let red: u32;
        let green: u32;
        let blue: u32;
        // `None` records that no alpha channel was written, which is what
        // decides the serialization below. The alpha's *value* does not: an
        // opaque `#abcf` still loses its spelling.
        let mut alpha: Option<f64> = None;

        if parser.next_is_hex() {
            let digit4 = self.parse_hex_digit(parser)?;

            if parser.next_is_hex() {
                red = (digit1 << 4) + digit2;
                green = (digit3 << 4) + digit4;
                blue = (self.parse_hex_digit(parser)? << 4) + self.parse_hex_digit(parser)?;

                if parser.next_is_hex() {
                    alpha = Some(
                        ((self.parse_hex_digit(parser)? << 4) + self.parse_hex_digit(parser)?)
                            as f64
                            / 0xff as f64,
                    );
                }
            } else {
                // #abcd
                red = (digit1 << 4) + digit1;
                green = (digit2 << 4) + digit2;
                blue = (digit3 << 4) + digit3;
                alpha = Some(((digit4 << 4) + digit4) as f64 / 0xff as f64);
            }
        } else {
            // #abc
            red = (digit1 << 4) + digit1;
            green = (digit2 << 4) + digit2;
            blue = (digit3 << 4) + digit3;
        }

        // Don't emit four- or eight-digit hex colors as hex, since that's not
        // yet well-supported in browsers. dart-sass keeps the source spelling
        // only for the three- and six-digit forms; the rest fall back to
        // whatever the serializer infers, which is `rgba()` for a color with
        // an alpha channel.
        let format = if alpha.is_none() {
            ColorFormat::Literal(parser.toks_mut().raw_text(start - 1))
        } else {
            ColorFormat::Infer
        };

        Ok(Color::new_rgba(
            Number::from(red),
            Number::from(green),
            Number::from(blue),
            Number(alpha.unwrap_or(1.0)),
            format,
        ))
    }

    fn parse_unary_operation(&mut self, parser: &mut P) -> SassResult<Spanned<AstExpr>> {
        let op_span = parser.toks().current_span();
        let operator = Self::expect_unary_operator(parser)?;

        if parser.is_plain_css() && operator != UnaryOp::Div {
            return Err(("Operators aren't allowed in plain CSS.", op_span).into());
        }

        parser.whitespace(true)?;

        let operand = self.parse_single_expression(parser)?;

        let span = op_span.merge(parser.toks().current_span());

        Ok(AstExpr::UnaryOp(operator, Arc::new(operand.node), span).span(span))
    }

    fn expect_unary_operator(parser: &mut P) -> SassResult<UnaryOp> {
        let span = parser.toks().current_span();
        Ok(match parser.toks_mut().next() {
            Some(Token { kind: '+', .. }) => UnaryOp::Plus,
            Some(Token { kind: '-', .. }) => UnaryOp::Neg,
            Some(Token { kind: '/', .. }) => UnaryOp::Div,
            Some(..) | None => return Err(("Expected unary operator.", span).into()),
        })
    }

    fn consume_natural_number(parser: &mut P) -> SassResult<()> {
        if !matches!(
            parser.toks_mut().next(),
            Some(Token {
                kind: '0'..='9',
                ..
            })
        ) {
            return Err(("Expected digit.", parser.toks().prev_span()).into());
        }

        while matches!(
            parser.toks().peek(),
            Some(Token {
                kind: '0'..='9',
                ..
            })
        ) {
            parser.toks_mut().next();
        }

        Ok(())
    }

    fn parse_number(parser: &mut P) -> SassResult<Spanned<AstExpr>> {
        let start = parser.toks().cursor();

        if !parser.scan_char('+') {
            parser.scan_char('-');
        }

        let after_sign = parser.toks().cursor();

        if !parser.toks().next_char_is('.') {
            ValueParser::consume_natural_number(parser)?;
        }

        ValueParser::try_decimal(parser, parser.toks().cursor() != after_sign)?;
        ValueParser::try_exponent(parser)?;

        let number: f64 = parser.toks_mut().raw_text(start).parse().unwrap();

        let unit = if parser.scan_char('%') {
            Unit::Percent
        } else if parser.looking_at_identifier()
            && (!matches!(parser.toks().peek(), Some(Token { kind: '-', .. }))
                || !matches!(parser.toks().peek_n(1), Some(Token { kind: '-', .. })))
        {
            Unit::from(parser.parse_identifier(false, true)?)
        } else {
            Unit::None
        };

        Ok(AstExpr::Number {
            n: Number::from(number),
            unit,
        }
        .span(parser.toks_mut().span_from(start)))
    }

    fn try_decimal(parser: &mut P, allow_trailing_dot: bool) -> SassResult<Option<String>> {
        if !matches!(parser.toks().peek(), Some(Token { kind: '.', .. })) {
            return Ok(None);
        }

        match parser.toks().peek_n(1) {
            Some(Token { kind, .. }) if !kind.is_ascii_digit() => {
                if allow_trailing_dot {
                    return Ok(None);
                }

                return Err(("Expected digit.", parser.toks().current_span()).into());
            }
            Some(..) => {}
            None => return Err(("Expected digit.", parser.toks().current_span()).into()),
        }

        let mut buffer = String::new();

        parser.expect_char('.')?;
        buffer.push('.');

        while let Some(Token { kind, .. }) = parser.toks().peek() {
            if !kind.is_ascii_digit() {
                break;
            }
            buffer.push(kind);
            parser.toks_mut().next();
        }

        Ok(Some(buffer))
    }

    fn try_exponent(parser: &mut P) -> SassResult<Option<String>> {
        let mut buffer = String::new();

        match parser.toks().peek() {
            Some(Token {
                kind: 'e' | 'E', ..
            }) => buffer.push('e'),
            _ => return Ok(None),
        }

        let next = match parser.toks().peek_n(1) {
            Some(Token {
                kind: kind @ ('0'..='9' | '-' | '+'),
                ..
            }) => kind,
            _ => return Ok(None),
        };

        parser.toks_mut().next();

        if next == '+' || next == '-' {
            parser.toks_mut().next();
            buffer.push(next);
        }

        match parser.toks().peek() {
            Some(Token {
                kind: '0'..='9', ..
            }) => {}
            _ => return Err(("Expected digit.", parser.toks().current_span()).into()),
        }

        while let Some(tok) = parser.toks().peek() {
            if !tok.kind.is_ascii_digit() {
                break;
            }

            buffer.push(tok.kind);

            parser.toks_mut().next();
        }

        Ok(Some(buffer))
    }

    fn parse_plus_expr(&mut self, parser: &mut P) -> SassResult<Spanned<AstExpr>> {
        debug_assert!(parser.toks().next_char_is('+'));

        match parser.toks().peek_n(1) {
            Some(Token {
                kind: '0'..='9' | '.',
                ..
            }) => ValueParser::parse_number(parser),
            _ => self.parse_unary_operation(parser),
        }
    }

    fn parse_minus_expr(&mut self, parser: &mut P) -> SassResult<Spanned<AstExpr>> {
        debug_assert!(parser.toks().next_char_is('-'));

        if matches!(
            parser.toks().peek_n(1),
            Some(Token {
                kind: '0'..='9' | '.',
                ..
            })
        ) {
            return ValueParser::parse_number(parser);
        }

        if parser.looking_at_interpolated_identifier() {
            return self.parse_identifier_like(parser);
        }

        self.parse_unary_operation(parser)
    }

    /// Decides whether a `%` at the cursor is a value rather than the modulo
    /// operator.
    ///
    /// dart-sass accepts a lone `%` as an unquoted string, so `a {b: %}` and
    /// `a {b: c %}` are both valid, but it still reads `5 % 2` as modulo. Two
    /// conditions separate them:
    ///
    /// - The `%` is the operator only when an operand follows it. A `%` with
    ///   nothing after it but the end of the value joins the space-separated
    ///   list instead, which is what makes `c %` and `1 %` parse.
    /// - A `%` value is only accepted before this expression has consumed a
    ///   comma. dart-sass rejects `1, %, 2` while accepting `%, 2`, and takes
    ///   `(1, %)` because parentheses parse each element as its own
    ///   expression. Both were verified against dart-sass 1.103.1.
    fn percent_is_value(&self, parser: &mut P) -> bool {
        if self.comma_expressions.is_some() {
            return false;
        }

        if self.single_expression.is_none() {
            return true;
        }

        // In plain CSS an operator is an error, so a `%` after an expression
        // has to stay one and be reported. dart-sass still takes a `%` in
        // single-expression position there, which the check above allows.
        if parser.is_plain_css() {
            return false;
        }

        !Self::expression_follows_percent(parser)
    }

    /// Reports whether an operand follows the `%` at the cursor, skipping the
    /// whitespace and comments that may separate them.
    fn expression_follows_percent(parser: &mut P) -> bool {
        let mut offset = 1;

        loop {
            match parser.toks().peek_n(offset) {
                Some(Token { kind, .. }) if kind.is_ascii_whitespace() => offset += 1,
                Some(Token { kind: '/', .. }) => match parser.toks().peek_n(offset + 1) {
                    Some(Token { kind: '*', .. }) => {
                        offset += 2;
                        loop {
                            match parser.toks().peek_n(offset) {
                                // An unterminated comment is a later error,
                                // not this predicate's to report.
                                None => return false,
                                Some(Token { kind: '*', .. })
                                    if matches!(
                                        parser.toks().peek_n(offset + 1),
                                        Some(Token { kind: '/', .. })
                                    ) =>
                                {
                                    offset += 2;
                                    break;
                                }
                                Some(..) => offset += 1,
                            }
                        }
                    }
                    Some(Token { kind: '/', .. }) => {
                        offset += 2;
                        while let Some(Token { kind, .. }) = parser.toks().peek_n(offset) {
                            if kind == '\n' {
                                break;
                            }
                            offset += 1;
                        }
                    }
                    // A lone slash starts an operand: dart-sass reads
                    // `5 %/ 2` as modulo by `/2`.
                    _ => return true,
                },
                _ => break,
            }
        }

        let Some(Token { kind, .. }) = parser.toks().peek_n(offset) else {
            return false;
        };

        match kind {
            '.' => !matches!(
                parser.toks().peek_n(offset + 1),
                Some(Token { kind: '.', .. })
            ),
            // Only `!important` and `!=` continue an expression; `!default`
            // and `!global` end the value, so the `%` before them is a value.
            '!' => match parser.toks().peek_n(offset + 1) {
                Some(Token {
                    kind: 'i' | 'I' | '=',
                    ..
                })
                | None => true,
                Some(Token { kind, .. }) => kind.is_ascii_whitespace(),
            },
            '(' | '[' | '\'' | '"' | '#' | '+' | '-' | '\\' | '$' | '&' | '%' => true,
            c => is_name_start(c) || c.is_ascii_digit(),
        }
    }

    /// Parses a lone `%` as the unquoted string `%`.
    fn parse_percent_value(parser: &mut P) -> SassResult<Spanned<AstExpr>> {
        let start = parser.toks().cursor();
        parser.expect_char('%')?;

        let span = parser.toks_mut().span_from(start);

        Ok(AstExpr::String(
            StringExpr(Interpolation::new_plain("%".to_owned()), QuoteKind::None),
            span,
        )
        .span(span))
    }

    fn parse_important_expr(parser: &mut P) -> SassResult<Spanned<AstExpr>> {
        let start = parser.toks().cursor();
        parser.expect_char('!')?;
        parser.whitespace(true)?;
        parser.expect_identifier("important", false)?;

        let span = parser.toks_mut().span_from(start);

        Ok(AstExpr::String(
            StringExpr(
                Interpolation::new_plain("!important".to_owned()),
                QuoteKind::None,
            ),
            span,
        )
        .span(span))
    }

    fn parse_identifier_like(&mut self, parser: &mut P) -> SassResult<Spanned<AstExpr>> {
        if let Some(func) = P::IDENTIFIER_LIKE {
            return func(parser);
        }

        let start = parser.toks().cursor();

        let identifier = parser.parse_interpolated_identifier()?;

        let ident_span = parser.toks_mut().span_from(start);

        let plain = identifier.as_plain();
        let lower = plain.map(str::to_ascii_lowercase);

        if let Some(plain) = plain {
            if plain == "if" && parser.toks().next_char_is('(') {
                if ValueParser::looking_at_css_if(parser)? {
                    return ValueParser::parse_css_if(parser, start);
                }

                let call_args = parser.parse_argument_invocation(false, false)?;
                let span = call_args.span;
                return Ok(AstExpr::If(Arc::new(Ternary(call_args))).span(span));
            } else if plain == "not" {
                parser.whitespace(true)?;

                let value = self.parse_single_expression(parser)?;

                let span = parser.toks_mut().span_from(start);

                return Ok(AstExpr::UnaryOp(UnaryOp::Not, Arc::new(value.node), span).span(span));
            }

            let lower_ref = lower.as_ref().unwrap();

            if !parser.toks().next_char_is('(') {
                match plain {
                    "null" => return Ok(AstExpr::Null.span(parser.toks_mut().span_from(start))),
                    "true" => return Ok(AstExpr::True.span(parser.toks_mut().span_from(start))),
                    "false" => return Ok(AstExpr::False.span(parser.toks_mut().span_from(start))),
                    _ => {}
                }

                if let Some(color) = NAMED_COLORS.get_by_name(lower_ref.as_str()) {
                    return Ok(AstExpr::Color(Arc::new(Color::new(
                        color[0],
                        color[1],
                        color[2],
                        color[3],
                        plain.to_owned(),
                    )))
                    .span(parser.toks_mut().span_from(start)));
                }
            }

            if let Some(func) = ValueParser::try_parse_special_function(parser, lower_ref, start)? {
                return Ok(func);
            }
        }

        match parser.toks().peek() {
            Some(Token { kind: '.', .. }) => {
                if matches!(parser.toks().peek_n(1), Some(Token { kind: '.', .. })) {
                    return Ok(AstExpr::String(
                        StringExpr(identifier, QuoteKind::None),
                        parser.toks_mut().span_from(start),
                    )
                    .span(parser.toks_mut().span_from(start)));
                }
                parser.toks_mut().next();

                match plain {
                    Some(s) => Self::namespaced_expression(
                        Spanned {
                            node: Identifier::from(s),
                            span: ident_span,
                        },
                        start,
                        parser,
                    ),
                    None => Err(("Interpolation isn't allowed in namespaces.", ident_span).into()),
                }
            }
            Some(Token { kind: '(', .. }) => {
                if let Some(plain) = plain {
                    let arguments =
                        parser.parse_argument_invocation(false, lower.as_deref() == Some("var"))?;

                    Ok(AstExpr::FunctionCall(FunctionCallExpr {
                        namespace: None,
                        name: Identifier::from(plain),
                        original_name: plain.to_string(),
                        arguments: Arc::new(arguments),
                        span: parser.toks_mut().span_from(start),
                        is_custom_function: plain.starts_with("--"),
                    })
                    .span(parser.toks_mut().span_from(start)))
                } else {
                    let arguments = parser.parse_argument_invocation(false, false)?;
                    Ok(
                        AstExpr::InterpolatedFunction(Arc::new(InterpolatedFunction {
                            name: identifier,
                            arguments,
                            span: parser.toks_mut().span_from(start),
                        }))
                        .span(parser.toks_mut().span_from(start)),
                    )
                }
            }
            _ => Ok(AstExpr::String(
                StringExpr(identifier, QuoteKind::None),
                parser.toks_mut().span_from(start),
            )
            .span(parser.toks_mut().span_from(start))),
        }
    }

    fn namespaced_expression(
        namespace: Spanned<Identifier>,
        start: usize,
        parser: &mut P,
    ) -> SassResult<Spanned<AstExpr>> {
        if parser.toks().next_char_is('$') {
            let name_start = parser.toks().cursor();
            let name = parser.parse_variable_name()?;
            let span = parser.toks_mut().span_from(start);
            P::assert_public(&name, span)?;

            if parser.is_plain_css() {
                return Err(("Module namespaces aren't allowed in plain CSS.", span).into());
            }

            return Ok(AstExpr::Variable {
                name: Spanned {
                    node: Identifier::from(name),
                    span: parser.toks_mut().span_from(name_start),
                },
                namespace: Some(namespace),
            }
            .span(span));
        }

        let name = parser.parse_public_identifier()?;
        let args = parser.parse_argument_invocation(false, false)?;
        let span = parser.toks_mut().span_from(start);

        if parser.is_plain_css() {
            return Err(("Module namespaces aren't allowed in plain CSS.", span).into());
        }

        Ok(AstExpr::FunctionCall(FunctionCallExpr {
            namespace: Some(namespace),
            name: Identifier::from(name.as_str()),
            original_name: name,
            arguments: Arc::new(args),
            span,
            is_custom_function: false,
        })
        .span(span))
    }

    fn parse_unicode_range(parser: &mut P) -> SassResult<Spanned<AstExpr>> {
        let start = parser.toks().cursor();
        parser.expect_ident_char('u', false)?;
        parser.expect_char('+')?;

        let mut first_range_length = 0;

        while let Some(next) = parser.toks().peek() {
            if !next.kind.is_ascii_hexdigit() {
                break;
            }

            parser.toks_mut().next();
            first_range_length += 1;
        }

        let mut has_question_mark = false;

        while parser.scan_char('?') {
            has_question_mark = true;
            first_range_length += 1;
        }

        let span = parser.toks_mut().span_from(start);
        if first_range_length == 0 {
            return Err(("Expected hex digit or \"?\".", parser.toks().current_span()).into());
        } else if first_range_length > 6 {
            return Err(("Expected at most 6 digits.", span).into());
        } else if has_question_mark {
            return Ok(AstExpr::String(
                StringExpr(
                    Interpolation::new_plain(parser.toks_mut().raw_text(start)),
                    QuoteKind::None,
                ),
                span,
            )
            .span(span));
        }

        if parser.scan_char('-') {
            let second_range_start = parser.toks().cursor();
            let mut second_range_length = 0;

            while let Some(next) = parser.toks().peek() {
                if !next.kind.is_ascii_hexdigit() {
                    break;
                }

                parser.toks_mut().next();
                second_range_length += 1;
            }

            if second_range_length == 0 {
                return Err(("Expected hex digit.", parser.toks().current_span()).into());
            } else if second_range_length > 6 {
                return Err((
                    "Expected at most 6 digits.",
                    parser.toks_mut().span_from(second_range_start),
                )
                    .into());
            }
        }

        if parser.looking_at_interpolated_identifier_body() {
            return Err(("Expected end of identifier.", parser.toks().current_span()).into());
        }

        let span = parser.toks_mut().span_from(start);

        Ok(AstExpr::String(
            StringExpr(
                Interpolation::new_plain(parser.toks_mut().raw_text(start)),
                QuoteKind::None,
            ),
            span,
        )
        .span(span))
    }

    pub(crate) fn try_parse_special_function(
        parser: &mut P,
        name: &str,
        start: usize,
    ) -> SassResult<Option<Spanned<AstExpr>>> {
        if matches!(parser.toks().peek(), Some(Token { kind: '(', .. }))
            && let Some(calculation) = ValueParser::try_parse_calculation(parser, name, start)?
        {
            return Ok(Some(calculation));
        }

        let normalized = unvendor(name);

        let mut buffer;

        match normalized {
            "calc" | "element" | "expression" | "type" => {
                // `type()` is special only unprefixed. dart-sass normalizes
                // `TYPE(` to `type(` but leaves `-a-type(` an ordinary
                // function call, whose arguments are Sass expressions and
                // whose quotes are normalized.
                if normalized == "type" && name != "type" {
                    return Ok(None);
                }

                if !parser.scan_char('(') {
                    return Ok(None);
                }

                buffer = Interpolation::new_plain(name.to_owned());
                buffer.add_char('(');
            }
            "progid" => {
                if !parser.scan_char(':') {
                    return Ok(None);
                }
                buffer = Interpolation::new_plain(name.to_owned());
                buffer.add_char(':');

                while let Some(Token { kind, .. }) = parser.toks().peek() {
                    if !kind.is_alphabetic() && kind != '.' {
                        break;
                    }
                    buffer.add_char(kind);
                    parser.toks_mut().next();
                }
                parser.expect_char('(')?;
                buffer.add_char('(');
            }
            "url" => {
                return Ok(parser.try_url_contents(None)?.map(|contents| {
                    AstExpr::String(
                        StringExpr(contents, QuoteKind::None),
                        parser.toks_mut().span_from(start),
                    )
                    .span(parser.toks_mut().span_from(start))
                }));
            }
            _ => return Ok(None),
        }

        let mut contents =
            parser.parse_interpolated_declaration_value(false, true, true, false, true, true)?;
        // An interpolated calc() reaches this raw-string fallback, but Dart
        // Sass serializes it without the source's leading/trailing whitespace
        // inside the parentheses (`calc( #{x} )` becomes `calc(x)`).
        //
        // This is the unprefixed name only. A vendor-prefixed one is an
        // ordinary special function, and dart-sass keeps its whitespace:
        // `-a-calc( x )` prints as written, like `element( x )` does.
        if name == "calc" {
            if let Some(InterpolationPart::String(first)) = contents.contents.first_mut() {
                *first = first.trim_start().to_owned();
            }
            if let Some(InterpolationPart::String(last)) = contents.contents.last_mut() {
                *last = last.trim_end().to_owned();
            }
            contents
                .contents
                .retain(|part| !matches!(part, InterpolationPart::String(s) if s.is_empty()));
        }
        buffer.add_interpolation(contents);
        parser.expect_char(')')?;
        buffer.add_char(')');

        Ok(Some(
            AstExpr::String(
                StringExpr(buffer, QuoteKind::None),
                parser.toks_mut().span_from(start),
            )
            .span(parser.toks_mut().span_from(start)),
        ))
    }

    /// Whether the whole argument is a single interpolation, as in `calc(#{$a})`.
    ///
    /// Dart Sass keeps such an argument as opaque text: the interpolated value
    /// reaches the output verbatim, internal whitespace and all, and nothing
    /// about it is simplified. An interpolation that merely appears *inside* a
    /// larger expression -- `calc(#{$a} + 2px)` -- does not qualify. That
    /// argument is parsed as an operation with the interpolation as one
    /// operand, which is what lets the source's whitespace be re-serialized
    /// and, when the calculation is nested inside another one, lets the
    /// operation keep the parentheses its precedence requires.
    ///
    /// The scan looks past quoted strings and comments, so neither a `#{` that
    /// is only text inside a string nor one inside a comment counts.
    fn contains_calculation_interpolation(parser: &mut P) -> SassResult<bool> {
        let start = parser.toks().cursor();
        let found = ValueParser::scan_lone_calculation_interpolation(parser)?;
        parser.toks_mut().set_cursor(start);
        Ok(found)
    }

    /// The scan behind [`Self::contains_calculation_interpolation`], leaving
    /// the cursor wherever it stopped for the caller to restore.
    fn scan_lone_calculation_interpolation(parser: &mut P) -> SassResult<bool> {
        parser.whitespace(true)?;

        if !matches!(parser.toks().peek(), Some(Token { kind: '#', .. }))
            || !matches!(parser.toks().peek_n(1), Some(Token { kind: '{', .. }))
        {
            return Ok(false);
        }

        parser.toks_mut().next();
        parser.toks_mut().next();

        let mut depth = 1_usize;

        while let Some(next) = parser.toks().peek() {
            match next.kind {
                '\\' => {
                    parser.toks_mut().next();
                    parser.toks_mut().next();
                }
                '\'' | '"' => {
                    parser.parse_interpolated_string()?;
                }
                '/' => {
                    if !parser.scan_comment()? {
                        parser.toks_mut().next();
                    }
                }
                '{' => {
                    depth += 1;
                    parser.toks_mut().next();
                }
                '}' => {
                    depth -= 1;
                    parser.toks_mut().next();
                    if depth == 0 {
                        parser.whitespace(true)?;
                        return Ok(parser.toks().next_char_is(')'));
                    }
                }
                _ => {
                    parser.toks_mut().next();
                }
            }
        }

        Ok(false)
    }

    fn try_parse_calculation_interpolation(
        parser: &mut P,
        start: usize,
    ) -> SassResult<Option<AstExpr>> {
        Ok(
            if ValueParser::contains_calculation_interpolation(parser)? {
                let mut contents = parser
                    .parse_interpolated_declaration_value(false, false, true, false, true, true)?;
                // Dart Sass serializes an interpolated calculation without the
                // source's leading/trailing whitespace inside the parentheses
                // (`calc( x )` becomes `calc(x)`).
                if let Some(InterpolationPart::String(first)) = contents.contents.first_mut() {
                    *first = first.trim_start().to_owned();
                }
                if let Some(InterpolationPart::String(last)) = contents.contents.last_mut() {
                    *last = last.trim_end().to_owned();
                }
                contents
                    .contents
                    .retain(|part| !matches!(part, InterpolationPart::String(s) if s.is_empty()));
                Some(AstExpr::String(
                    StringExpr(contents, QuoteKind::None),
                    parser.toks_mut().span_from(start),
                ))
            } else {
                None
            },
        )
    }

    /// Parses one operand of a calculation.
    ///
    /// `position` only decides what a failure is called; see
    /// [`OperandPosition`].
    fn parse_calculation_value(
        parser: &mut P,
        position: OperandPosition,
    ) -> SassResult<Spanned<AstExpr>> {
        match parser.toks().peek() {
            // A `/` at an operand position is Sass's unary slash: the binary
            // one is consumed by the product loop, which only looks after an
            // operand. It takes no whitespace to be one, unlike `+` and `-`,
            // so `calc(/ 1px)` and `calc(/1px)` are both rejected.
            Some(Token { kind: '/', .. }) => {
                let start = parser.toks().cursor();
                parser.toks_mut().next();
                parser.whitespace(true)?;
                ValueParser::parse_calculation_value(parser, OperandPosition::AfterOperator)?;

                Err((
                    "This expression can't be used in a calculation.",
                    parser.toks_mut().span_from(start),
                )
                    .into())
            }
            // A `+` or `-` with whitespace after it is a unary operator, not
            // the sign of a number, and a calculation has no unary operators.
            // Dart Sass parses `calc(+ 1px)` as one with its ordinary
            // expression parser and then rejects the expression, so the
            // operand is parsed here too and the error names the whole of it.
            Some(Token {
                kind: '+' | '-', ..
            }) if matches!(
                parser.toks().peek_n(1),
                Some(Token {
                    kind: ' ' | '\t' | '\r' | '\n',
                    ..
                })
            ) =>
            {
                let start = parser.toks().cursor();
                parser.toks_mut().next();
                parser.whitespace(true)?;
                ValueParser::parse_calculation_value(parser, OperandPosition::AfterOperator)?;

                Err((
                    "This expression can't be used in a calculation.",
                    parser.toks_mut().span_from(start),
                )
                    .into())
            }
            // A leading `-` starts an identifier in `-infinity` and `-webkit-x`
            // but a number in `-1px`, so the identifier check comes first. An
            // interpolation continues the identifier rather than ending it, so
            // `-#{$x}` is a single operand and not a minus sign.
            Some(Token { kind: '-', .. }) if parser.looking_at_interpolated_identifier() => {
                ValueParser::parse_calculation_identifier(parser)
            }
            Some(Token {
                kind: '+' | '-' | '.' | '0'..='9',
                ..
            }) => ValueParser::parse_number(parser),
            // A quoted string parses as an expression and is rejected for
            // being one, which is not the same as failing to parse: Dart Sass
            // says `calc("a")` holds an expression a calculation cannot use.
            Some(Token {
                kind: '"' | '\'', ..
            }) => {
                let start = parser.toks().cursor();
                parser.parse_string()?;

                Err((
                    "This expression can't be used in a calculation.",
                    parser.toks_mut().span_from(start),
                )
                    .into())
            }
            Some(Token { kind: '$', .. }) => ValueParser::parse_variable(parser),
            Some(Token { kind: '(', .. }) => {
                let start = parser.toks().cursor();
                parser.toks_mut().next();

                let value = match ValueParser::try_parse_calculation_interpolation(parser, start)? {
                    Some(v) => v,
                    None => {
                        parser.whitespace(true)?;

                        // `()` is the empty list, which parses and is then
                        // rejected for what it is rather than for how it is
                        // written. Dart Sass reports `calc(())` and
                        // `calc(( ))` alike.
                        if parser.scan_char(')') {
                            return Err((
                                "This expression can't be used in a calculation.",
                                parser.toks_mut().span_from(start),
                            )
                                .into());
                        }

                        ValueParser::parse_calculation_expression(parser)?.node
                    }
                };

                parser.whitespace(true)?;
                parser.expect_char(')')?;

                Ok(AstExpr::Paren(Arc::new(value)).span(parser.toks_mut().span_from(start)))
            }
            _ if !parser.looking_at_interpolated_identifier() => {
                if parser.scan_char('#') {
                    return Err((
                        ValueParser::after_hash(parser),
                        parser.toks().current_span(),
                    )
                        .into());
                }

                Err((position.no_operand(), parser.toks().current_span()).into())
            }
            _ => ValueParser::parse_calculation_identifier(parser),
        }
    }

    /// What a `#` inside a calculation turned out to be.
    ///
    /// The `#` has already been consumed. Dart Sass reads a hex colour or a
    /// name after it, so what fails depends on what follows: `#fff`, `#zzz`
    /// and `#\65` all parse into something a calculation then refuses, while a
    /// `#` with nothing usable behind it never gets that far and reports a
    /// missing identifier.
    ///
    /// A digit run is a hex colour of 3, 4, 6 or 8 digits, and Dart Sass says
    /// so when the run is another length: `#123` and `#12345678` are refused
    /// expressions, `#1`, `#12`, `#12345` and `#1234567` want another hex
    /// digit. A run longer than 8 takes the first 8 and is an expression
    /// again. Every case here was taken from dart-sass 1.103.1.
    fn after_hash(parser: &mut P) -> &'static str {
        const EXPRESSION: &str = "This expression can't be used in a calculation.";

        if parser.looking_at_identifier() {
            return EXPRESSION;
        }

        let digits = (0..)
            .take_while(|n| {
                matches!(parser.toks().peek_n(*n), Some(Token { kind, .. }) if kind.is_ascii_hexdigit())
            })
            .count();

        match digits {
            3 | 4 | 6 => EXPRESSION,
            n if n >= 8 => EXPRESSION,
            0 => "Expected identifier.",
            _ => "Expected hex digit.",
        }
    }

    /// Parses an identifier appearing inside a calculation.
    ///
    /// It is a nested calculation or function call when followed by `(`, a
    /// namespaced expression when followed by `.`, one of the calc constants
    /// when it names one, and otherwise a bare unquoted string that is carried
    /// through to the output (`calc(1px + foo)`).
    ///
    /// The identifier may contain interpolations, which bind to it rather than
    /// starting a new operand: `x#{$a}` is one value and serializes as `x1`.
    /// Such an identifier is opaque text, so it names neither a constant nor a
    /// function -- `calc(e#{""} + 1)` keeps `e` as a string instead of reading
    /// it as Euler's number -- and using it as a namespace or a call is an
    /// error, as it is in Dart Sass.
    fn parse_calculation_identifier(parser: &mut P) -> SassResult<Spanned<AstExpr>> {
        let start = parser.toks().cursor();
        let contents = parser.parse_interpolated_identifier()?;
        let ident_span = parser.toks_mut().span_from(start);

        let ident = match contents.as_plain() {
            Some(plain) => plain.to_owned(),
            None => {
                return match parser.toks().peek() {
                    Some(Token { kind: '.', .. }) => {
                        Err(("Interpolation isn't allowed in namespaces.", ident_span).into())
                    }
                    Some(Token { kind: '(', .. }) => Err((
                        "This expression can't be used in a calculation.",
                        ident_span,
                    )
                        .into()),
                    _ => Ok(
                        AstExpr::String(StringExpr(contents, QuoteKind::None), ident_span)
                            .span(ident_span),
                    ),
                };
            }
        };

        if parser.scan_char('.') {
            return ValueParser::namespaced_expression(
                Spanned {
                    node: Identifier::from(&ident),
                    span: ident_span,
                },
                start,
                parser,
            );
        }

        let lowercase = ident.to_ascii_lowercase();

        if !parser.toks().next_char_is('(') {
            if let Some(constant) = calculation_constant_value(&lowercase) {
                return Ok(AstExpr::Number {
                    n: Number(constant),
                    unit: Unit::None,
                }
                .span(ident_span));
            }

            return Ok(AstExpr::String(
                StringExpr(Interpolation::new_plain(ident), QuoteKind::None),
                ident_span,
            )
            .span(ident_span));
        }

        let calculation = ValueParser::try_parse_calculation(parser, &lowercase, start)?;

        if let Some(calc) = calculation {
            Ok(calc)
        } else if lowercase == "if" {
            if ValueParser::looking_at_css_if(parser)? {
                return ValueParser::parse_css_if(parser, start);
            }

            Ok(AstExpr::If(Arc::new(Ternary(
                parser.parse_argument_invocation(false, false)?,
            )))
            .span(parser.toks_mut().span_from(start)))
        } else {
            Ok(AstExpr::FunctionCall(FunctionCallExpr {
                namespace: None,
                name: Identifier::from(&ident),
                original_name: ident.clone(),
                arguments: Arc::new(parser.parse_argument_invocation(false, false)?),
                span: parser.toks_mut().span_from(start),
                is_custom_function: ident.starts_with("--"),
            })
            .span(parser.toks_mut().span_from(start)))
        }
    }
    fn parse_calculation_product(
        parser: &mut P,
        position: OperandPosition,
    ) -> SassResult<Spanned<AstExpr>> {
        let mut product = ValueParser::parse_calculation_value(parser, position)?;

        loop {
            parser.whitespace(true)?;
            match parser.toks().peek() {
                Some(Token {
                    kind: op @ ('*' | '/'),
                    ..
                }) => {
                    parser.toks_mut().next();
                    parser.whitespace(true)?;

                    let rhs = ValueParser::parse_calculation_value(
                        parser,
                        OperandPosition::AfterOperator,
                    )?;

                    let span = product.span.merge(rhs.span);

                    product.node = AstExpr::BinaryOp(Arc::new(BinaryOpExpr {
                        lhs: product.node,
                        op: if op == '*' {
                            BinaryOp::Mul
                        } else {
                            BinaryOp::Div
                        },
                        rhs: rhs.node,
                        allows_slash: false,
                        span,
                    }));

                    product.span = span;
                }
                _ => return Ok(product),
            }
        }
    }
    fn parse_calculation_sum(
        parser: &mut P,
        position: OperandPosition,
    ) -> SassResult<Spanned<AstExpr>> {
        let mut sum = ValueParser::parse_calculation_product(parser, position)?;

        loop {
            match parser.toks().peek() {
                Some(Token {
                    kind: next @ ('+' | '-'),
                    ..
                }) => {
                    if !matches!(
                        parser.toks().peek_n_backwards(1),
                        Some(Token {
                            kind: ' ' | '\t' | '\r' | '\n',
                            ..
                        })
                    ) || !matches!(
                        parser.toks().peek_n(1),
                        Some(Token {
                            kind: ' ' | '\t' | '\r' | '\n',
                            ..
                        })
                    ) {
                        return Err((
                            "\"+\" and \"-\" must be surrounded by whitespace in calculations.",
                            parser.toks().current_span(),
                        )
                            .into());
                    }

                    parser.toks_mut().next();
                    parser.whitespace(true)?;

                    let rhs = ValueParser::parse_calculation_product(
                        parser,
                        OperandPosition::AfterOperator,
                    )?;

                    let span = sum.span.merge(rhs.span);

                    sum = AstExpr::BinaryOp(Arc::new(BinaryOpExpr {
                        lhs: sum.node,
                        op: if next == '+' {
                            BinaryOp::Plus
                        } else {
                            BinaryOp::Minus
                        },
                        rhs: rhs.node,
                        allows_slash: false,
                        span,
                    }))
                    .span(span);
                }
                _ => return Ok(sum),
            }
        }
    }

    /// Parses one calculation argument, the level at which values written next
    /// to each other with only whitespace between them form a space-separated
    /// list.
    ///
    /// Adjacency binds looser than any operator, so `calc(var(--c) 1 + 2px)`
    /// is `var(--c)` next to `1 + 2px`, not `var(--c) 1` plus `2px`. Dart Sass
    /// parses a calculation argument as an ordinary Sass expression, where a
    /// space-separated list binds loosest of all, and this mirrors that. It is
    /// also what keeps the serializer's parenthesization honest: an operand
    /// that is a space-separated list then always came from a grouping the
    /// source wrote -- parentheses, or a nested `calc()` -- which is exactly
    /// when the output needs parentheses back.
    fn parse_calculation_expression(parser: &mut P) -> SassResult<Spanned<AstExpr>> {
        let mut expr = ValueParser::parse_calculation_sum(parser, OperandPosition::ArgumentStart)?;

        loop {
            match parser.toks().peek() {
                // Two values written next to each other with only whitespace
                // between them are legal in a calculation when at least one is
                // opaque, as in `calc(var(--c) 1)`. Only a variable, a number
                // or an identifier (which is how both `var()` and an
                // interpolation start) can begin such a continuation.
                Some(Token {
                    kind: '$' | '(' | '.' | '0'..='9',
                    ..
                }) => {
                    expr = ValueParser::parse_calculation_adjacent(parser, expr)?;
                }
                Some(..) if parser.looking_at_interpolated_identifier() => {
                    expr = ValueParser::parse_calculation_adjacent(parser, expr)?;
                }
                _ => return Ok(expr),
            }
        }
    }

    /// Collects a whitespace-separated continuation of a calculation value into
    /// a space-separated list.
    fn parse_calculation_adjacent(
        parser: &mut P,
        first: Spanned<AstExpr>,
    ) -> SassResult<Spanned<AstExpr>> {
        let next = ValueParser::parse_calculation_sum(parser, OperandPosition::ArgumentStart)?;
        let span = first.span.merge(next.span);

        let mut elems = match first.node {
            AstExpr::List(list)
                if list.separator == ListSeparator::Space && list.brackets == Brackets::None =>
            {
                list.elems
            }
            node => vec![node.span(first.span)],
        };

        elems.push(next);

        Ok(AstExpr::List(ListExpr {
            elems,
            separator: ListSeparator::Space,
            brackets: Brackets::None,
        })
        .span(span))
    }

    /// Decides between the CSS `if()` and the Sass ternary of the same name.
    ///
    /// The scanner is left where it started. The two forms are told apart the
    /// way a reader tells them apart: the CSS form separates branches with `;`
    /// and a condition from its value with `:`, while the ternary separates its
    /// three arguments with `,`. Whichever of those appears first at the top
    /// level of the argument list decides.
    fn looking_at_css_if(parser: &mut P) -> SassResult<bool> {
        debug_assert!(parser.toks().next_char_is('('));

        let start = parser.toks().cursor();
        let mut depth = 0_usize;
        let mut result = false;

        while let Some(tok) = parser.toks().peek() {
            match tok.kind {
                '(' | '[' | '{' => {
                    depth += 1;
                    parser.toks_mut().next();
                }
                ')' | ']' | '}' => {
                    depth -= 1;
                    parser.toks_mut().next();

                    if depth == 0 {
                        break;
                    }
                }
                '"' | '\'' => {
                    let quote = tok.kind;
                    parser.toks_mut().next();

                    while let Some(tok) = parser.toks().peek() {
                        parser.toks_mut().next();

                        if tok.kind == '\\' {
                            parser.toks_mut().next();
                        } else if tok.kind == quote {
                            break;
                        }
                    }
                }
                // A `$name:` at the top level is a named argument of the Sass
                // ternary, not a CSS branch condition.
                '$' if depth == 1 => {
                    parser.toks_mut().next();

                    while let Some(tok) = parser.toks().peek() {
                        if !tok.kind.is_alphanumeric() && !matches!(tok.kind, '-' | '_') {
                            break;
                        }

                        parser.toks_mut().next();
                    }

                    let before_colon = parser.toks().cursor();
                    parser.whitespace_without_comments(true);

                    if parser.toks().next_char_is(':') {
                        parser.toks_mut().next();
                    } else {
                        parser.toks_mut().set_cursor(before_colon);
                    }
                }
                ':' | ';' if depth == 1 => {
                    result = true;
                    break;
                }
                ',' if depth == 1 => break,
                _ => {
                    parser.toks_mut().next();
                }
            }
        }

        parser.toks_mut().set_cursor(start);

        Ok(result)
    }

    /// Parses `if(<condition>: <value>; ...)`.
    pub(crate) fn parse_css_if(parser: &mut P, start: usize) -> SassResult<Spanned<AstExpr>> {
        parser.expect_char('(')?;

        let mut branches = Vec::new();

        loop {
            parser.whitespace(true)?;

            if !branches.is_empty() && parser.toks().next_char_is(')') {
                break;
            }

            let condition = ValueParser::parse_css_if_condition(parser, true)?;
            parser.whitespace(true)?;
            parser.expect_char(':')?;
            parser.whitespace(true)?;

            let value = ValueParser::parse_css_if_value(parser)?;

            branches.push(CssIfBranch { condition, value });

            parser.whitespace(true)?;

            if !parser.scan_char(';') {
                break;
            }
        }

        parser.whitespace(true)?;
        parser.expect_char(')')?;

        let span = parser.toks_mut().span_from(start);

        Ok(AstExpr::CssIf(Arc::new(CssIfExpr { branches })).span(span))
    }

    /// Parses the value half of a branch: everything up to the `;` that starts
    /// the next branch or the `)` that ends the function.
    fn parse_css_if_value(parser: &mut P) -> SassResult<AstExpr> {
        Ok(ValueParser::parse_expression(
            parser,
            Some(&|parser| {
                Ok(matches!(
                    parser.toks().peek(),
                    Some(Token {
                        kind: ';' | ')',
                        ..
                    })
                ))
            }),
            true,
            false,
            false,
        )?
        .node)
    }

    /// Parses a whole branch condition, including the `and`/`or` chain.
    ///
    /// CSS does not allow `and` and `or` to mix without parentheses, so once a
    /// chain commits to one operator the other is a syntax error. `else` is a
    /// whole condition on its own and is not allowed inside one, which is why
    /// it is gated on `allow_else`.
    fn parse_css_if_condition(parser: &mut P, allow_else: bool) -> SassResult<CssIfCondition> {
        if allow_else && ValueParser::scan_css_if_keyword(parser, "else")? {
            return Ok(CssIfCondition::Else);
        }

        if ValueParser::scan_css_if_keyword(parser, "not")? {
            parser.whitespace(true)?;

            // `not` takes a single term, not a chain: `not a and b` is a syntax
            // error rather than `(not a) and b` or `not (a and b)`.
            let (condition, ..) = ValueParser::css_if_atom_as_test(parser)?;

            return Ok(CssIfCondition::Not(Box::new(condition)));
        }

        let mut tests = vec![ValueParser::parse_css_if_test(parser)?];
        let mut operator = None;

        loop {
            let before = parser.toks().cursor();
            parser.whitespace(true)?;

            let next = if ValueParser::scan_css_if_keyword(parser, "and")? {
                "and"
            } else if ValueParser::scan_css_if_keyword(parser, "or")? {
                "or"
            } else {
                parser.toks_mut().set_cursor(before);
                break;
            };

            match operator {
                None => operator = Some(next),
                Some(seen) if seen == next => {}
                Some(..) => return Err((r#"expected ":"."#, parser.toks().current_span()).into()),
            }

            parser.whitespace(true)?;
            tests.push(ValueParser::parse_css_if_test(parser)?);
        }

        // A substitution sitting next to other terms could expand to anything,
        // operators included, so Sass cannot tell which part of the surrounding
        // chain its neighbours belong to. Mixing one with a `sass()` the
        // compiler must resolve is therefore rejected rather than guessed at.
        // Parentheses bound the ambiguity and make the combination legal again.
        if tests.iter().any(|(_, is_raw_run, _)| *is_raw_run)
            && tests.iter().any(|(_, _, has_sass)| *has_sass)
        {
            return Err((
                "if() conditions with arbitrary substitutions may not contain sass() expressions.",
                parser.toks().current_span(),
            )
                .into());
        }

        let mut conditions = tests.into_iter().map(|(condition, ..)| condition);

        Ok(match operator {
            None => conditions.next().unwrap(),
            Some("and") => CssIfCondition::And(conditions.collect()),
            Some(..) => CssIfCondition::Or(conditions.collect()),
        })
    }

    /// Scans one of the condition keywords, but only where it really is a
    /// keyword.
    ///
    /// `not(...)` is a function call, not the operator, and CSS rejects it
    /// outright rather than silently reinterpreting it, so a keyword followed
    /// immediately by `(` is an error.
    fn scan_css_if_keyword(parser: &mut P, keyword: &str) -> SassResult<bool> {
        let start = parser.toks().cursor();

        if !parser.looking_at_identifier() {
            return Ok(false);
        }

        let ident = parser.parse_identifier(false, false)?;

        if !ident.eq_ignore_ascii_case(keyword) {
            parser.toks_mut().set_cursor(start);
            return Ok(false);
        }

        ValueParser::reject_keyword_call(parser, &ident)?;

        Ok(true)
    }

    /// Rejects `not(`, `and(` and `or(`, which CSS treats as a mistake rather
    /// than as a function call.
    fn reject_keyword_call(parser: &mut P, ident: &str) -> SassResult<()> {
        if parser.toks().next_char_is('(') {
            return Err((
                format!(r#"Whitespace is required between "{}" and "(""#, ident),
                parser.toks().current_span(),
            )
                .into());
        }

        Ok(())
    }

    /// Parses one operand of a chain: either a single term or a run of terms
    /// separated only by whitespace.
    ///
    /// Returns the condition along with whether it is such a run and whether it
    /// contains a `sass()` expression anywhere, which is what the caller needs
    /// to police the two of them appearing together.
    fn parse_css_if_test(parser: &mut P) -> SassResult<(CssIfCondition, bool, bool)> {
        let start = parser.toks().cursor();
        let first = ValueParser::parse_css_if_atom(parser)?;

        // A parenthesized condition is always complete in itself; nothing may
        // run on from it.
        if let CssIfAtom::Paren(condition) = first {
            let has_sass = condition_contains_sass(&condition);
            return Ok((CssIfCondition::Paren(Box::new(condition)), false, has_sass));
        }

        let mut has_sass = matches!(first, CssIfAtom::Sass(..));
        let mut terms = 1;

        loop {
            let before = parser.toks().cursor();
            parser.whitespace(true)?;

            match parser.toks().peek() {
                None
                | Some(Token {
                    kind: ':' | ';' | ')' | ',',
                    ..
                }) => {
                    parser.toks_mut().set_cursor(before);
                    break;
                }
                _ => {}
            }

            // An `and` or `or` here belongs to the enclosing chain.
            let after_whitespace = parser.toks().cursor();
            if ValueParser::peek_css_if_operator(parser)? {
                parser.toks_mut().set_cursor(before);
                break;
            }
            parser.toks_mut().set_cursor(after_whitespace);

            match ValueParser::parse_css_if_atom(parser)? {
                // A run of substitutions has no place for a parenthesized
                // condition: `a (b) c` is not a condition Sass can read.
                CssIfAtom::Paren(..) => {
                    return Err((r#"expected ":"."#, parser.toks().current_span()).into());
                }
                CssIfAtom::Sass(..) => has_sass = true,
                CssIfAtom::Raw(..) => {}
            }

            terms += 1;
        }

        if terms == 1 {
            return Ok((
                match first {
                    CssIfAtom::Sass(expr) => CssIfCondition::Sass(Arc::new(expr)),
                    CssIfAtom::Raw(interpolation) => CssIfCondition::Raw(Arc::new(interpolation)),
                    CssIfAtom::Paren(..) => unreachable!("handled above"),
                },
                false,
                has_sass,
            ));
        }

        // Re-read the whole run as text so that it is emitted exactly as it was
        // written, with only its interpolations resolved.
        let end = parser.toks().cursor();
        parser.toks_mut().set_cursor(start);
        let raw = ValueParser::parse_css_if_raw_text(parser, end)?;

        Ok((CssIfCondition::Raw(Arc::new(raw)), true, has_sass))
    }

    /// Parses exactly one term where a chain is not allowed, as after `not`.
    fn css_if_atom_as_test(parser: &mut P) -> SassResult<(CssIfCondition, bool, bool)> {
        Ok(match ValueParser::parse_css_if_atom(parser)? {
            CssIfAtom::Sass(expr) => (CssIfCondition::Sass(Arc::new(expr)), false, true),
            CssIfAtom::Raw(interpolation) => {
                (CssIfCondition::Raw(Arc::new(interpolation)), false, false)
            }
            CssIfAtom::Paren(condition) => {
                let has_sass = condition_contains_sass(&condition);
                (CssIfCondition::Paren(Box::new(condition)), false, has_sass)
            }
        })
    }

    /// Whether the scanner is at an `and` or `or` that separates operands.
    fn peek_css_if_operator(parser: &mut P) -> SassResult<bool> {
        let start = parser.toks().cursor();

        if !parser.looking_at_identifier() {
            return Ok(false);
        }

        let ident = parser.parse_identifier(false, false)?;
        let is_operator = ident.eq_ignore_ascii_case("and") || ident.eq_ignore_ascii_case("or");
        parser.toks_mut().set_cursor(start);

        Ok(is_operator)
    }

    /// Re-reads the source between the current position and `end` as an
    /// interpolation, collapsing runs of whitespace to a single space so the
    /// output is normalized the way Dart Sass normalizes it.
    fn parse_css_if_raw_text(parser: &mut P, end: usize) -> SassResult<Interpolation> {
        let mut buffer = Interpolation::new();
        let mut pending_space = false;

        while parser.toks().cursor() < end {
            match parser.toks().peek() {
                Some(Token { kind: '#', .. })
                    if matches!(parser.toks().peek_n(1), Some(Token { kind: '{', .. })) =>
                {
                    if pending_space {
                        buffer.add_char(' ');
                        pending_space = false;
                    }

                    buffer.add_interpolation(parser.parse_single_interpolation()?);
                }
                Some(Token { kind, .. }) if kind.is_ascii_whitespace() => {
                    pending_space = !buffer.is_empty();
                    parser.toks_mut().next();
                }
                Some(Token { kind, .. }) => {
                    if pending_space {
                        buffer.add_char(' ');
                        pending_space = false;
                    }

                    buffer.add_char(kind);
                    parser.toks_mut().next();
                }
                None => break,
            }
        }

        Ok(buffer)
    }

    /// Parses a single term of a condition.
    fn parse_css_if_atom(parser: &mut P) -> SassResult<CssIfAtom> {
        let start = parser.toks().cursor();

        if parser.toks().next_char_is('(') {
            parser.toks_mut().next();
            parser.whitespace(true)?;
            let condition = ValueParser::parse_css_if_condition(parser, false)?;
            parser.whitespace(true)?;
            parser.expect_char(')')?;
            return Ok(CssIfAtom::Paren(condition));
        }

        let is_interpolation = matches!(parser.toks().peek(), Some(Token { kind: '#', .. }))
            && matches!(parser.toks().peek_n(1), Some(Token { kind: '{', .. }));

        if !is_interpolation && !parser.looking_at_identifier() {
            return Err(("Expected identifier.", parser.toks().current_span()).into());
        }

        let name = parser.parse_interpolated_identifier()?;

        if let Some(plain) = name.as_plain() {
            if plain.eq_ignore_ascii_case("sass") {
                parser.expect_char('(')?;
                parser.whitespace(true)?;
                let expr = ValueParser::parse_expression(
                    parser,
                    Some(&|parser| Ok(parser.toks().next_char_is(')'))),
                    true,
                    false,
                    false,
                )?;
                parser.whitespace(true)?;
                parser.expect_char(')')?;

                // A `sass()` condition is settled at compile time, which a
                // `.css` file has no business doing.
                if parser.is_plain_css() {
                    return Err((
                        "sass() conditions aren't allowed in plain CSS",
                        parser.toks_mut().span_from(start),
                    )
                        .into());
                }

                return Ok(CssIfAtom::Sass(expr.node));
            }

            if matches!(
                plain.to_ascii_lowercase().as_str(),
                "not" | "and" | "or" | "else"
            ) {
                ValueParser::reject_keyword_call(parser, plain)?;
            }

            // A plain identifier that is not a function call is not a term.
            if !parser.toks().next_char_is('(') {
                return Err((r#"expected "("."#, parser.toks().current_span()).into());
            }
        }

        // A bare interpolation stands on its own; anything else is a
        // function-shaped term whose text the browser resolves.
        if !parser.toks().next_char_is('(') {
            return Ok(CssIfAtom::Raw(name));
        }

        parser.toks_mut().next();

        let mut buffer = name;
        buffer.add_char('(');
        buffer.add_interpolation(ValueParser::parse_css_if_function_argument(parser)?);
        parser.expect_char(')')?;
        buffer.add_char(')');

        Ok(CssIfAtom::Raw(buffer))
    }

    /// Reads the argument text of an opaque condition term, up to but not
    /// including the `)` that closes it.
    ///
    /// The text is copied character for character rather than re-parsed, so
    /// that whatever the author wrote reaches the browser unchanged -- an empty
    /// `''` stays single-quoted instead of being re-quoted. Only interpolation
    /// is resolved, including inside quoted strings, where Sass resolves it too.
    fn parse_css_if_function_argument(parser: &mut P) -> SassResult<Interpolation> {
        let mut buffer = Interpolation::new();
        let mut brackets = Vec::new();
        let mut quote = None;

        while let Some(tok) = parser.toks().peek() {
            match tok.kind {
                '\\' => {
                    buffer.add_char('\\');
                    parser.toks_mut().next();

                    if let Some(escaped) = parser.toks().peek() {
                        buffer.add_char(escaped.kind);
                        parser.toks_mut().next();
                    }
                }
                '#' if matches!(parser.toks().peek_n(1), Some(Token { kind: '{', .. })) => {
                    buffer.add_interpolation(parser.parse_single_interpolation()?);
                }
                '"' | '\'' => {
                    match quote {
                        Some(open) if open == tok.kind => quote = None,
                        Some(..) => {}
                        None => quote = Some(tok.kind),
                    }

                    buffer.add_char(tok.kind);
                    parser.toks_mut().next();
                }
                _ if quote.is_some() => {
                    buffer.add_char(tok.kind);
                    parser.toks_mut().next();
                }
                '(' | '[' | '{' => {
                    brackets.push(opposite_bracket(tok.kind));
                    buffer.add_char(tok.kind);
                    parser.toks_mut().next();
                }
                ')' | ']' | '}' => {
                    if brackets.last() != Some(&tok.kind) {
                        break;
                    }

                    brackets.pop();
                    buffer.add_char(tok.kind);
                    parser.toks_mut().next();
                }
                _ => {
                    buffer.add_char(tok.kind);
                    parser.toks_mut().next();
                }
            }
        }

        Ok(buffer)
    }

    /// Parses the parenthesized argument list of a CSS math function.
    ///
    /// The list may be empty and may carry a trailing comma; how many arguments
    /// a given function actually accepts is checked during evaluation, which is
    /// where Dart Sass reports it too.
    fn parse_calculation_arguments(parser: &mut P, start: usize) -> SassResult<Vec<AstExpr>> {
        parser.expect_char('(')?;
        if let Some(interpolation) =
            ValueParser::try_parse_calculation_interpolation(parser, start)?
        {
            parser.expect_char(')')?;
            return Ok(vec![interpolation]);
        }

        parser.whitespace(true)?;

        let mut arguments = Vec::new();

        if !parser.toks().next_char_is(')') {
            arguments.push(ValueParser::parse_calculation_expression(parser)?.node);
            parser.whitespace(true)?;

            while parser.scan_char(',') {
                parser.whitespace(true)?;

                if parser.toks().next_char_is(')') {
                    break;
                }

                arguments.push(ValueParser::parse_calculation_expression(parser)?.node);
                parser.whitespace(true)?;
            }
        }

        ValueParser::reject_non_calculation_operator(parser)?;
        parser.expect_char(')')?;

        Ok(arguments)
    }

    /// Rejects a SassScript binary operator a calculation cannot use.
    ///
    /// A calculation has four operators; SassScript has more, and dart-sass
    /// names the difference rather than reporting a missing `)`. `!` counts
    /// only as the start of `!=`: `calc(1px !)` is a malformed call and
    /// dart-sass reports it as one, as it does for `^`. Checked against
    /// dart-sass 1.103.1 for `%`, `<`, `<=`, `>`, `>=`, `=`, `==`, `!=`, `!`
    /// and `^`.
    ///
    /// `&` is a known divergence rather than a member of either group.
    /// dart-sass reads it as the parent selector, so `calc(1px & 2px)` holds
    /// an expression a calculation cannot use; this reports a missing `)`.
    /// Recorded in
    /// `specs/docs/features/08-calculation-warnings-and-error-wording.md`.
    ///
    /// The word operators `and` and `or` do not reach here. They read as
    /// identifiers, so `calc(1px and 2px)` becomes a space-separated list and
    /// is carried through to the output, where dart-sass rejects it. That is a
    /// separate gap, recorded in
    /// `specs/docs/features/08-calculation-warnings-and-error-wording.md`.
    fn reject_non_calculation_operator(parser: &mut P) -> SassResult<()> {
        let start = parser.toks().cursor();

        // The width is the operator's, so the span covers `<=` and `!=` whole
        // rather than pointing at half of one.
        let width = match parser.toks().peek() {
            Some(Token { kind: '%', .. }) => 1,
            Some(Token {
                kind: '<' | '>' | '=',
                ..
            }) => {
                if matches!(parser.toks().peek_n(1), Some(Token { kind: '=', .. })) {
                    2
                } else {
                    1
                }
            }
            Some(Token { kind: '!', .. })
                if matches!(parser.toks().peek_n(1), Some(Token { kind: '=', .. })) =>
            {
                2
            }
            _ => return Ok(()),
        };

        for _ in 0..width {
            parser.toks_mut().next();
        }

        Err((
            "This operation can't be used in a calculation.",
            parser.toks_mut().span_from(start),
        )
            .into())
    }

    /// Parses `name(...)` as a CSS math function if `name` is one.
    ///
    /// Arguments that are not calculation syntax rewind the scanner and return
    /// `None`, so the ordinary function-call parser gets them instead. That is
    /// what keeps a user-defined `log("...")` or `mod($a, $b)` working, and it
    /// is also how the Sass `min`, `max`, `round` and `abs` functions receive
    /// arguments a calculation could not express. A math name that resolves to
    /// no function at all is rejected when it is evaluated.
    fn try_parse_calculation(
        parser: &mut P,
        name: &str,
        start: usize,
    ) -> SassResult<Option<Spanned<AstExpr>>> {
        debug_assert!(parser.toks().next_char_is('('));

        let name = match CalculationName::from_lowercase_str(name) {
            Some(name) => name,
            None => return Ok(None),
        };

        let before_args = parser.toks().cursor();

        let args = match ValueParser::parse_calculation_arguments(parser, start) {
            Ok(args) => args,
            Err(err) => {
                // `calc` is a reserved identifier, so nothing can be hiding
                // behind it; rewinding would only hand the arguments to the
                // raw-text special-function parser, which accepts anything.
                if name == CalculationName::Calc {
                    return Err(err);
                }

                parser.toks_mut().set_cursor(before_args);
                return Ok(None);
            }
        };

        Ok(Some(
            AstExpr::Calculation { name, args }.span(parser.toks_mut().span_from(start)),
        ))
    }

    fn reset_state(&mut self, parser: &mut P) -> SassResult<()> {
        self.comma_expressions = None;
        self.space_expressions = None;
        self.binary_operators = None;
        self.operands = None;
        parser.toks_mut().set_cursor(self.start);
        self.allow_slash = true;
        self.single_expression = Some(self.parse_single_expression(parser)?);

        Ok(())
    }
}