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
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
use std::{
    cell::{Cell, RefCell},
    collections::{BTreeMap, BTreeSet, HashMap, HashSet},
    ffi::OsStr,
    fmt,
    iter::FromIterator,
    mem,
    path::{Path, PathBuf},
    rc::Rc,
    sync::Arc,
};

use codemap::{CodeMap, Span, SpanLoc, Spanned};

/// The lines every `bogus-combinators` warning ends with, as dart-sass words
/// them.
const BOGUS_COMBINATORS_FOOTER: &str = "This will be an error in Dart Sass 2.0.0.\n\nMore info: https://sass-lang.com/d/bogus-combinators";
use indexmap::{IndexMap, IndexSet};

use crate::{
    ContextFlags, InputSyntax, Options,
    ast::*,
    builtin::{
        GLOBAL_FUNCTIONS,
        meta::if_arguments,
        modules::{
            Module, declare_module_color, declare_module_list, declare_module_map,
            declare_module_math, declare_module_meta, declare_module_selector,
            declare_module_string,
        },
    },
    common::{
        BinaryOp, Brackets, CSS_MIXIN_NAME_ERROR, Identifier, ListSeparator, QuoteKind, UnaryOp,
        unvendor,
    },
    error::{SassError, SassResult},
    highlight::{Highlight, highlight},
    interner::InternedString,
    lexer::Lexer,
    logger::{Deprecation, DeprecationWarning},
    parse::{
        AtRootQueryParser, CssParser, KeyframesSelectorParser, SassParser, ScssParser,
        StylesheetParser,
    },
    selector::{
        ComplexSelector, ComplexSelectorComponent, ExtendRule, ExtendedSelector, ExtensionSnapshot,
        ExtensionStore, SelectorList, SelectorParser, SimpleSelector,
    },
    utils::{to_sentence, trim_ascii},
    value::{
        ArgList, CalculationArg, CalculationName, Number, SassCalculation, SassFunction, SassMap,
        SassNumber, UserDefinedFunction, Value, is_opaque_value,
    },
};

use super::{
    bin_op::{add, cmp, div, mul, rem, single_eq, sub},
    css_tree::{CssTree, CssTreeIdx},
    env::Environment,
};

trait UserDefinedCallable {
    fn name(&self) -> Identifier;
    fn arguments(&self) -> &ArgumentDeclaration;
}

impl UserDefinedCallable for AstFunctionDecl {
    fn name(&self) -> Identifier {
        self.name.node
    }

    fn arguments(&self) -> &ArgumentDeclaration {
        &self.arguments
    }
}

impl UserDefinedCallable for Arc<AstFunctionDecl> {
    fn name(&self) -> Identifier {
        self.name.node
    }

    fn arguments(&self) -> &ArgumentDeclaration {
        &self.arguments
    }
}

impl UserDefinedCallable for AstMixin {
    fn name(&self) -> Identifier {
        self.name
    }

    fn arguments(&self) -> &ArgumentDeclaration {
        &self.args
    }
}

impl UserDefinedCallable for Arc<AstMixin> {
    fn name(&self) -> Identifier {
        self.name
    }

    fn arguments(&self) -> &ArgumentDeclaration {
        &self.args
    }
}

impl UserDefinedCallable for Arc<CallableContentBlock> {
    fn name(&self) -> Identifier {
        Identifier::from("@content")
    }

    fn arguments(&self) -> &ArgumentDeclaration {
        &self.content.args
    }
}

#[derive(Debug, Clone)]
pub(crate) struct CallableContentBlock {
    content: AstContentBlock,
    env: Environment,
}

/// One argument to a macro such as `if()`, which evaluates only the branch it
/// takes.
///
/// Arguments written in the call stay unevaluated, so the branch not taken
/// never runs. Arguments that arrive through a rest argument have already
/// been evaluated -- splatting a list is what produced them -- and so carry a
/// value instead.
#[derive(Debug, Clone)]
enum MacroArg {
    Unevaled(AstExpr),
    Evaled(Value),
}

/// A CSS statement a module emitted, recorded with its children so a later
/// `@import` or `meta.load-css` of the module can emit a copy of it.
///
/// Style-rule selectors are recorded in their hermetic form -- resolved
/// without any enclosing style rule -- and re-resolved against the rule
/// enclosing each load site when the copy is emitted. The recorded selector
/// handles stay shared with the extension store, so extensions apply to
/// root-level copies the same way they apply to the originals.
#[derive(Debug, Clone)]
struct RecordedCssStmt {
    stmt: CssStmt,
    children: Vec<RecordedCssStmt>,
}

/// Evaluation context of the current execution
#[derive(Debug)]
pub struct Visitor<'a> {
    pub(crate) declaration_name: Option<String>,
    pub(crate) flags: ContextFlags,
    pub(crate) env: Environment,
    pub(crate) style_rule_ignoring_at_root: Option<ExtendedSelector>,

    /// The selector of `style_rule_ignoring_at_root` as it was resolved,
    /// before `@extend` added to it: dart-sass's `originalSelector`.
    ///
    /// `&` evaluates to this, and nested rules resolve against it, so neither
    /// sees extenders. Reading the extended selector instead printed
    /// `--&` as `-- .a--plain, .a` where dart-sass prints `-- .a--plain`
    /// (libsass issue 2000).
    style_rule_original_selector: Option<SelectorList>,

    /// Whether `style_rule_ignoring_at_root` came from a plain CSS file.
    ///
    /// A style rule written inside one of those is CSS nesting: it keeps its
    /// own selector and stays nested, instead of being merged into its parent
    /// the way Sass nesting is.
    style_rule_is_plain_css: bool,

    /// Whether the enclosing style rule is itself nested inside another one in
    /// the output, which only happens once plain CSS nesting has been passed
    /// through.
    ///
    /// Past that point the stylesheet already requires a browser that supports
    /// CSS nesting, so at-rules stop bubbling out of style rules and stay where
    /// they were written.
    has_css_nesting: bool,
    // avoid emitting duplicate warnings for the same span
    pub(crate) warnings_emitted: HashSet<Span>,
    /// The deprecation warnings reported so far, by message and span, so the
    /// same one reported again from a mixin included twice is dropped, as
    /// dart-sass's `_warningsEmitted` drops it.
    deprecations_emitted: HashSet<(String, Span)>,
    /// How many times each deprecation has been reported, for the limit of
    /// five and the count left out at the end.
    deprecation_counts: HashMap<Deprecation, usize>,
    /// The name the entry stylesheet was added to the code map under, which
    /// is how a warning tells it apart from a loaded module.
    entry_file_name: String,
    pub(crate) media_queries: Option<Vec<MediaQuery>>,
    pub(crate) media_query_sources: Option<IndexSet<MediaQuery>>,
    pub(crate) extender: ExtensionStore,

    /// The complete file path of the current file being visited. Imports are
    /// resolved relative to this path
    pub current_import_path: PathBuf,
    pub(crate) is_plain_css: bool,
    pub(crate) modules: BTreeMap<PathBuf, Arc<RefCell<Module>>>,
    /// The root configuration each cached module was first loaded under, so a
    /// later load can tell "the same `with` clause reaching the module along
    /// another path" (legal) from "a second `with` clause" (an error).
    module_configurations: BTreeMap<PathBuf, Rc<RefCell<Configuration>>>,
    /// The modules the currently-executing context has loaded. Swapped per
    /// module execution, so each module records its own upstream list; what
    /// remains at the end is the root document's, the starting point for
    /// `apply_module_extensions`.
    current_upstream: Vec<Arc<RefCell<Module>>>,
    /// The CSS each cached module emitted when it first executed, recorded
    /// with hermetic selectors (resolved without any enclosing style rule),
    /// so an `@import` or `meta.load-css` of an already-loaded module can
    /// emit that CSS again, re-nested under whatever rule encloses the new
    /// load site. `@use` never replays -- a used module's CSS appears once.
    module_css: BTreeMap<PathBuf, Vec<RecordedCssStmt>>,
    /// True while evaluating a stylesheet loaded by `@import` that loads
    /// modules, and while `meta.load-css` loads one. Modules executed in this
    /// context keep the caller's CSS position, so their CSS lands where the
    /// `@import` or `@include` is written, and a cache hit replays the
    /// module's recorded CSS instead of emitting nothing.
    in_import_context: bool,
    pub(crate) active_modules: BTreeSet<PathBuf>,
    css_tree: CssTree,
    parent: Option<CssTreeIdx>,
    configuration: Rc<RefCell<Configuration>>,
    /// Plain CSS imports written after the top of the document, which move
    /// back into the `@import` block at [`Self::end_of_imports`] when the
    /// tree is finished.
    import_nodes: Vec<CssStmt>,
    /// How many top-level statements belong to the `@import` block.
    ///
    /// CSS requires `@import` to come before any rule, so an import written
    /// later is moved up. Comments are allowed between imports, so a comment
    /// written while the block is still open extends it rather than closing
    /// it -- otherwise a comment above an import would be left behind when
    /// the import moved.
    end_of_imports: usize,
    pub options: &'a Options<'a>,
    pub(crate) map: &'a mut CodeMap,
    // todo: remove
    empty_span: Span,
    import_cache: BTreeMap<PathBuf, StyleSheet>,
    /// As a simple heuristic, we don't cache the results of an import unless it
    /// has been seen in the past. In the majority of cases, files are imported
    /// at most once.
    files_seen: BTreeSet<PathBuf>,
}

impl<'a> Visitor<'a> {
    pub fn new(
        path: &Path,
        options: &'a Options<'a>,
        map: &'a mut CodeMap,
        empty_span: Span,
    ) -> Self {
        let mut flags = ContextFlags::empty();
        flags.set(ContextFlags::IN_SEMI_GLOBAL_SCOPE, true);

        let extender = ExtensionStore::new(empty_span);

        let current_import_path = path.to_path_buf();

        Self {
            declaration_name: None,
            style_rule_ignoring_at_root: None,
            style_rule_original_selector: None,
            style_rule_is_plain_css: false,
            has_css_nesting: false,
            flags,
            warnings_emitted: HashSet::new(),
            deprecations_emitted: HashSet::new(),
            deprecation_counts: HashMap::new(),
            entry_file_name: path.to_string_lossy().into_owned(),
            media_queries: None,
            media_query_sources: None,
            env: Environment::new(),
            extender,
            css_tree: CssTree::new(),
            parent: None,
            current_import_path,
            configuration: Rc::new(RefCell::new(Configuration::empty())),
            is_plain_css: false,
            import_nodes: Vec::new(),
            end_of_imports: 0,
            modules: BTreeMap::new(),
            module_configurations: BTreeMap::new(),
            current_upstream: Vec::new(),
            module_css: BTreeMap::new(),
            in_import_context: false,
            active_modules: BTreeSet::new(),
            options,
            empty_span,
            map,
            import_cache: BTreeMap::new(),
            files_seen: BTreeSet::new(),
        }
    }

    pub(crate) fn visit_stylesheet(&mut self, mut style_sheet: StyleSheet) -> SassResult<()> {
        self.active_modules.insert(style_sheet.url.clone());
        let was_in_plain_css = self.is_plain_css;
        self.is_plain_css = style_sheet.is_plain_css;
        mem::swap(&mut self.current_import_path, &mut style_sheet.url);

        for stmt in style_sheet.body {
            let result = self.visit_stmt(stmt)?;
            debug_assert!(result.is_none());
        }

        mem::swap(&mut self.current_import_path, &mut style_sheet.url);
        self.is_plain_css = was_in_plain_css;

        self.active_modules.remove(&style_sheet.url);

        Ok(())
    }

    pub(crate) fn finish(mut self) -> SassResult<Vec<CssStmt>> {
        self.apply_module_extensions()?;

        let mut finished_tree = self.css_tree.finish();
        if self.import_nodes.is_empty() {
            return Ok(finished_tree);
        }

        // The out-of-order imports go at the end of the `@import` block, not
        // at the top of the document: the comments the block contains were
        // written above them and stay there.
        debug_assert!(self.end_of_imports <= finished_tree.len());
        let mut rest = finished_tree.split_off(self.end_of_imports.min(finished_tree.len()));
        finished_tree.append(&mut self.import_nodes);
        finished_tree.append(&mut rest);

        Ok(finished_tree)
    }

    /// Applies each module's extensions to the modules it loaded, and errors
    /// on a mandatory `@extend` no reachable module satisfies.
    ///
    /// Ported from Dart Sass 1.103.1 `_extendModules`: modules are walked in
    /// reverse topological order -- the root document first, every module
    /// before the modules it loaded -- so by the time a module is processed,
    /// every store downstream of it has already contributed its extensions.
    /// An extension therefore reaches the extending module's own CSS and its
    /// upstream closure, never a sibling. Selector handles are shared into
    /// the single CSS tree, so extending them here is reflected when the
    /// tree is serialized.
    fn apply_module_extensions(&mut self) -> SassResult<()> {
        let sorted = self.sorted_modules();

        // Extensions not yet satisfied by any module, keyed by target and
        // extender, in the order they were found so the first one reports.
        let mut unsatisfied: IndexMap<(SimpleSelector, ComplexSelector), (SimpleSelector, Span)> =
            IndexMap::new();

        // The snapshots of every store directly downstream of a module,
        // keyed by the module's pointer identity.
        let mut downstream: HashMap<*const RefCell<Module>, Vec<ExtensionSnapshot>> =
            HashMap::new();

        // The root document is the most-downstream "module": its store is the
        // visitor's own and its upstream list is what load_module collected
        // at the top level.
        {
            let original_selectors = self.extender.simple_selectors();

            for (target, extension) in self
                .extender
                .extensions_where_target(|target| !original_selectors.contains(target))
            {
                unsatisfied
                    .entry((target.clone(), extension.extender.clone()))
                    .or_insert((target, extension.span));
            }

            if !self.extender.is_empty() {
                let snapshot = self.extender.snapshot();

                for upstream in &self.current_upstream {
                    downstream
                        .entry(Arc::as_ptr(upstream))
                        .or_default()
                        .push(snapshot.clone());
                }
            }

            for (target, extension) in self
                .extender
                .extensions_where_target(|target| original_selectors.contains(target))
            {
                unsatisfied.shift_remove(&(target, extension.extender));
            }
        }

        for module in sorted {
            let mut module_ref = module.borrow_mut();

            let (store, upstream) = match &mut *module_ref {
                Module::Environment {
                    extension_store,
                    upstream,
                    ..
                } => (extension_store, upstream),
                _ => continue,
            };

            // Snapshot the selectors before downstream extensions add more,
            // so a selector added by a sibling extension does not count as
            // satisfying an extension.
            let original_selectors = store.simple_selectors();

            // This module's own extensions start out unsatisfied; downstream
            // ones were recorded when their module was processed.
            for (target, extension) in
                store.extensions_where_target(|target| !original_selectors.contains(target))
            {
                unsatisfied
                    .entry((target.clone(), extension.extender.clone()))
                    .or_insert((target, extension.span));
            }

            if let Some(snapshots) = downstream.remove(&Arc::as_ptr(&module)) {
                store.add_extensions(snapshots)?;
            }

            if store.is_empty() {
                continue;
            }

            let snapshot = store.snapshot();

            for upstream in upstream.iter() {
                downstream
                    .entry(Arc::as_ptr(upstream))
                    .or_default()
                    .push(snapshot.clone());
            }

            // Anything this module's store now satisfies -- its own
            // extensions and newly added downstream ones alike -- comes off
            // the list.
            for (target, extension) in
                store.extensions_where_target(|target| original_selectors.contains(target))
            {
                unsatisfied.shift_remove(&(target, extension.extender));
            }
        }

        if let Some(((_, _), (target, span))) = unsatisfied.first() {
            return Err((
                format!(
                    "The target selector was not found.\nUse \"@extend {} !optional\" to avoid this error.",
                    target
                ),
                *span,
            )
                .into());
        }

        Ok(())
    }

    /// The modules reachable from the root document, in reverse topological
    /// order: every module comes before the modules it loaded.
    fn sorted_modules(&self) -> Vec<Arc<RefCell<Module>>> {
        fn visit(
            module: &Arc<RefCell<Module>>,
            seen: &mut HashSet<*const RefCell<Module>>,
            post_order: &mut Vec<Arc<RefCell<Module>>>,
        ) {
            if !seen.insert(Arc::as_ptr(module)) {
                return;
            }

            if let Module::Environment { upstream, .. } = &*module.borrow() {
                for upstream in upstream {
                    visit(upstream, seen, post_order);
                }
            }

            post_order.push(Arc::clone(module));
        }

        let mut seen = HashSet::new();
        let mut post_order = Vec::new();

        for module in &self.current_upstream {
            visit(module, &mut seen, &mut post_order);
        }

        // Post-order puts every module after its upstreams; reversed, every
        // module comes before them.
        post_order.reverse();

        post_order
    }

    fn visit_return_rule(&mut self, ret: AstReturn) -> SassResult<Option<Value>> {
        let val = self.visit_expr(ret.val)?;

        Ok(Some(self.without_slash(val)))
    }

    // todo: we really don't have to return Option<Value> from all of these children
    pub(crate) fn visit_stmt(&mut self, stmt: AstStmt) -> SassResult<Option<Value>> {
        match stmt {
            AstStmt::RuleSet(ruleset) => self.visit_ruleset(ruleset),
            AstStmt::Style(style) => self.visit_style(style),
            AstStmt::SilentComment(..) => Ok(None),
            AstStmt::If(if_stmt) => self.visit_if_stmt(if_stmt),
            AstStmt::For(for_stmt) => self.visit_for_stmt(for_stmt),
            AstStmt::Return(ret) => self.visit_return_rule(ret),
            AstStmt::Each(each_stmt) => self.visit_each_stmt(each_stmt),
            AstStmt::Media(media_rule) => self.visit_media_rule(media_rule),
            AstStmt::Include(include_stmt) => self.visit_include_stmt(include_stmt),
            AstStmt::While(while_stmt) => self.visit_while_stmt(&while_stmt),
            AstStmt::VariableDecl(decl) => self.visit_variable_decl(decl),
            AstStmt::LoudComment(comment) => self.visit_loud_comment(comment),
            AstStmt::ImportRule(import_rule) => self.visit_import_rule(import_rule),
            AstStmt::FunctionDecl(func) => {
                self.visit_function_decl(func);
                Ok(None)
            }
            AstStmt::Mixin(mixin) => {
                self.visit_mixin_decl(mixin);
                Ok(None)
            }
            AstStmt::ContentRule(content_rule) => self.visit_content_rule(content_rule),
            AstStmt::Warn(warn_rule) => {
                self.visit_warn_rule(warn_rule)?;
                Ok(None)
            }
            AstStmt::UnknownAtRule(unknown_at_rule) => self.visit_unknown_at_rule(unknown_at_rule),
            AstStmt::ErrorRule(error_rule) => Err(self.visit_error_rule(error_rule)?),
            AstStmt::Extend(extend_rule) => self.visit_extend_rule(extend_rule),
            AstStmt::AtRootRule(at_root_rule) => self.visit_at_root_rule(at_root_rule),
            AstStmt::Debug(debug_rule) => self.visit_debug_rule(debug_rule),
            AstStmt::Use(use_rule) => {
                self.visit_use_rule(use_rule)?;
                Ok(None)
            }
            AstStmt::Forward(forward_rule) => {
                self.visit_forward_rule(forward_rule)?;
                Ok(None)
            }
            AstStmt::Supports(supports_rule) => {
                self.visit_supports_rule(supports_rule)?;
                Ok(None)
            }
        }
    }

    fn visit_forward_rule(&mut self, forward_rule: AstForwardRule) -> SassResult<()> {
        let old_config = Rc::clone(&self.configuration);
        let adjusted_config = Configuration::through_forward(Rc::clone(&old_config), &forward_rule);

        if !forward_rule.configuration.is_empty() {
            let new_configuration =
                self.add_forward_configuration(Rc::clone(&adjusted_config), &forward_rule)?;

            self.load_module(
                forward_rule.url.as_path(),
                Some(Rc::clone(&new_configuration)),
                false,
                forward_rule.span,
                |visitor, module, _| visitor.env.forward_module(module, forward_rule.clone()),
            )?;

            Self::remove_used_configuration(
                &adjusted_config,
                &new_configuration,
                &forward_rule
                    .configuration
                    .iter()
                    .filter(|var| !var.is_guarded)
                    .map(|var| var.name.node)
                    .collect(),
            );

            // Remove all the variables that weren't configured by this particular
            // `@forward` before checking that the configuration is empty. Errors for
            // outer `with` clauses will be thrown once those clauses finish
            // executing.
            let configured_variables: HashSet<Identifier> = forward_rule
                .configuration
                .iter()
                .map(|var| var.name.node)
                .collect();

            let mut to_remove = Vec::new();

            for name in (*new_configuration).borrow().values.keys() {
                if !configured_variables.contains(&name) {
                    to_remove.push(name);
                }
            }

            for name in to_remove {
                (*new_configuration).borrow_mut().remove(name);
            }

            Self::assert_configuration_is_empty(&new_configuration, false)?;
        } else {
            self.configuration = adjusted_config;
            let url = forward_rule.url.clone();
            self.load_module(
                url.as_path(),
                None,
                false,
                forward_rule.span,
                move |visitor, module, _| visitor.env.forward_module(module, forward_rule.clone()),
            )?;
            self.configuration = old_config;
        }

        Ok(())
    }

    #[allow(clippy::unnecessary_unwrap)]
    fn add_forward_configuration(
        &mut self,
        config: Rc<RefCell<Configuration>>,
        forward_rule: &AstForwardRule,
    ) -> SassResult<Rc<RefCell<Configuration>>> {
        let mut new_values = BTreeMap::from_iter((*config).borrow().values.iter());

        for variable in &forward_rule.configuration {
            if variable.is_guarded {
                let old_value = (*config).borrow_mut().remove(variable.name.node);

                if old_value.is_some()
                    && !matches!(
                        old_value,
                        Some(ConfiguredValue {
                            value: Value::Null,
                            ..
                        })
                    )
                {
                    new_values.insert(variable.name.node, old_value.unwrap());
                    continue;
                }
            }

            // todo: superfluous clone?
            let value = self.visit_expr(variable.expr.node.clone())?;
            let value = self.without_slash(value);

            new_values.insert(
                variable.name.node,
                ConfiguredValue::explicit(value, variable.expr.span),
            );
        }

        Ok(Rc::new(RefCell::new(
            if !(*config).borrow().is_implicit() || (*config).borrow().is_empty() {
                Configuration::explicit(new_values, forward_rule.span)
            } else {
                Configuration::implicit(new_values)
            },
        )))
    }

    /// Remove configured values from [upstream] that have been removed from
    /// [downstream], unless they match a name in [except].
    fn remove_used_configuration(
        upstream: &Rc<RefCell<Configuration>>,
        downstream: &Rc<RefCell<Configuration>>,
        except: &HashSet<Identifier>,
    ) {
        let mut names_to_remove = Vec::new();
        let downstream_keys = (*downstream).borrow().values.keys();
        for name in (*upstream).borrow().values.keys() {
            if except.contains(&name) {
                continue;
            }

            if !downstream_keys.contains(&name) {
                names_to_remove.push(name);
            }
        }

        for name in names_to_remove {
            (*upstream).borrow_mut().remove(name);
        }
    }

    fn parenthesize_supports_condition(
        &mut self,
        condition: AstSupportsCondition,
        operator: Option<&str>,
    ) -> SassResult<String> {
        match &condition {
            AstSupportsCondition::Negation(..) => {
                Ok(format!("({})", self.visit_supports_condition(condition)?))
            }
            AstSupportsCondition::Operation {
                operator: operator2,
                ..
            } if operator2.is_none() || operator2.as_deref() != operator => {
                Ok(format!("({})", self.visit_supports_condition(condition)?))
            }
            _ => self.visit_supports_condition(condition),
        }
    }

    fn visit_supports_condition(&mut self, condition: AstSupportsCondition) -> SassResult<String> {
        match condition {
            AstSupportsCondition::Operation {
                left,
                operator,
                right,
            } => Ok(format!(
                "{} {} {}",
                self.parenthesize_supports_condition(*left, operator.as_deref())?,
                operator.as_ref().unwrap(),
                self.parenthesize_supports_condition(*right, operator.as_deref())?
            )),
            AstSupportsCondition::Negation(condition) => Ok(format!(
                "not {}",
                self.parenthesize_supports_condition(*condition, None)?
            )),
            AstSupportsCondition::Interpolation(expr) => {
                self.evaluate_to_css(expr, QuoteKind::None, self.empty_span)
            }
            AstSupportsCondition::Declaration { name, value } => {
                let old_in_supports_decl = self.flags.in_supports_declaration();
                self.flags.set(ContextFlags::IN_SUPPORTS_DECLARATION, true);

                let is_custom_property = match &name {
                    AstExpr::String(StringExpr(text, QuoteKind::None), ..) => {
                        text.initial_plain().starts_with("--")
                    }
                    _ => false,
                };

                let result = format!(
                    "({}:{}{})",
                    self.evaluate_to_css(name, QuoteKind::Quoted, self.empty_span)?,
                    if is_custom_property { "" } else { " " },
                    self.evaluate_to_css(value, QuoteKind::Quoted, self.empty_span)?,
                );

                self.flags
                    .set(ContextFlags::IN_SUPPORTS_DECLARATION, old_in_supports_decl);

                Ok(result)
            }
            AstSupportsCondition::Function { name, args } => Ok(format!(
                "{}({})",
                self.perform_interpolation(name, false)?,
                self.perform_interpolation(args, false)?
            )),
            AstSupportsCondition::Anything { contents } => Ok(format!(
                "({})",
                self.perform_interpolation(contents, false)?,
            )),
        }
    }

    fn visit_supports_rule(&mut self, supports_rule: AstSupportsRule) -> SassResult<()> {
        if self.declaration_name.is_some() {
            return Err((
                "Supports rules may not be used within nested declarations.",
                supports_rule.span,
            )
                .into());
        }

        let condition = self.visit_supports_condition(supports_rule.condition)?;

        let css_supports_rule = CssStmt::Supports(
            SupportsRule {
                params: condition,
                body: Vec::new(),
            },
            false,
        );

        let children = supports_rule.body;

        // Once plain CSS nesting has been passed through, the stylesheet
        // already needs a browser that supports nesting, so there is nothing to
        // gain from hoisting this rule out of the style rule it sits in.
        if self.has_css_nesting {
            return self
                .with_parent_opt(
                    css_supports_rule,
                    true,
                    |visitor| {
                        for stmt in children {
                            let result = visitor.visit_stmt(stmt)?;
                            debug_assert!(result.is_none());
                        }

                        Ok(())
                    },
                    None::<fn(&CssStmt) -> bool>,
                )
                .map(|_| ());
        }

        self.with_parent(
            css_supports_rule,
            true,
            |visitor| {
                if !visitor.style_rule_exists() {
                    for stmt in children {
                        let result = visitor.visit_stmt(stmt)?;
                        debug_assert!(result.is_none());
                    }
                } else {
                    // If we're in a style rule, copy it into the supports rule so that
                    // declarations immediately inside @supports have somewhere to go.
                    //
                    // For example, "a {@supports (a: b) {b: c}}" should produce "@supports
                    // (a: b) {a {b: c}}".
                    let selector = visitor.style_rule_ignoring_at_root.clone().unwrap();
                    let ruleset = CssStmt::RuleSet {
                        selector,
                        body: Vec::new(),
                        is_group_end: false,
                        from_plain_css: visitor.style_rule_is_plain_css,
                    };

                    visitor.with_parent(
                        ruleset,
                        false,
                        |visitor| {
                            for stmt in children {
                                let result = visitor.visit_stmt(stmt)?;
                                debug_assert!(result.is_none());
                            }

                            Ok(())
                        },
                        |_| false,
                    )?;
                }

                Ok(())
            },
            CssStmt::is_style_rule,
        )?;

        Ok(())
    }

    fn execute(
        &mut self,
        stylesheet: StyleSheet,
        configuration: Option<Rc<RefCell<Configuration>>>,
        names_in_errors: bool,
    ) -> SassResult<Arc<RefCell<Module>>> {
        let url = stylesheet.url.clone();

        let current_configuration = configuration
            .as_ref()
            .map(Rc::clone)
            .unwrap_or_else(|| Rc::clone(&self.configuration));

        // todo: use canonical url for modules
        if let Some(already_loaded) = self.modules.get(&stylesheet.url) {
            let already_loaded = Arc::clone(already_loaded);

            // A module is configured once, on its first load. A configuration
            // reaching it again is fine when it is implicit, traces back to
            // the same `with (...)` clause through however many `@forward`s
            // (one clause seen along two paths, not two clauses), or names
            // only variables the module could never have been configured with
            // -- a clause meant for the forwarding file's own variables.
            if !(*current_configuration).borrow().is_implicit() {
                let current_original =
                    Configuration::original_config(Rc::clone(&current_configuration));

                let same_original = self
                    .module_configurations
                    .get(&url)
                    .is_some_and(|original| Rc::ptr_eq(original, &current_original));

                let could_have_applied = || {
                    let names: HashSet<Identifier> = (*current_configuration)
                        .borrow()
                        .values
                        .keys()
                        .into_iter()
                        .collect();

                    (*already_loaded)
                        .borrow()
                        .could_have_been_configured(&names)
                };

                if !same_original && could_have_applied() {
                    let message = if names_in_errors {
                        format!(
                            "{} was already loaded, so it can't be configured using \"with\".",
                            Self::pretty_url(&url)
                        )
                    } else {
                        "This module was already loaded, so it can't be configured using \"with\"."
                            .to_owned()
                    };

                    let span = (*current_configuration)
                        .borrow()
                        .span
                        .unwrap_or(self.empty_span);

                    return Err((message, span).into());
                }
            }

            // A module keeps its state from the first load, but `@import`ing
            // it again is meant to emit its CSS again, so replay what it
            // emitted the first time.
            if self.in_import_context {
                self.replay_module_css(&url)?;
            }

            return Ok(already_loaded);
        }

        let env = Environment::new();
        // A module loaded by `@use` or `@forward` gets its own extension
        // store: its style rules register there, and so do its `@extend`s, so
        // `apply_module_extensions` can scope extensions to a module's
        // upstream closure the way Dart Sass does (connorskees/grass#104). A
        // module loaded in an import context instead shares the enclosing
        // context's store -- `@import` means "as if written here", and Dart
        // Sass likewise re-registers the injected CSS in the importer.
        let swapped_state = if self.in_import_context {
            None
        } else {
            let module_store = ExtensionStore::new(self.empty_span);

            Some((
                mem::replace(&mut self.extender, module_store),
                mem::take(&mut self.current_upstream),
            ))
        };

        let css_start = self.css_tree.stmt_count();

        let execution = self.with_environment::<SassResult<()>, _>(env.new_closure(), |visitor| {
            let old_parent = visitor.parent;
            // In an import context the module's CSS belongs where the
            // `@import` or `@include meta.load-css(..)` is written, so the
            // caller's tree position and media queries are kept. The
            // enclosing style rule is taken in every mode: module selectors
            // resolve hermetically, and `renest_module_css` nests them under
            // the load site's rule afterwards -- which is what lets a second
            // load of the same module re-nest the recorded CSS under a
            // different rule.
            let in_import_context = visitor.in_import_context;
            let old_style_rule = visitor.style_rule_ignoring_at_root.take();
            let old_style_rule_original_selector = visitor.style_rule_original_selector.take();
            let old_style_rule_is_plain_css =
                mem::replace(&mut visitor.style_rule_is_plain_css, false);
            let old_has_css_nesting = mem::replace(&mut visitor.has_css_nesting, false);
            let old_media_queries = if in_import_context {
                None
            } else {
                visitor.media_queries.take()
            };
            let old_declaration_name = visitor.declaration_name.take();
            let old_in_unknown_at_rule = visitor.flags.in_unknown_at_rule();
            let old_at_root_excluding_style_rule = visitor.flags.at_root_excluding_style_rule();
            let old_in_keyframes = visitor.flags.in_keyframes();
            let old_configuration = if let Some(new_config) = configuration {
                Some(mem::replace(&mut visitor.configuration, new_config))
            } else {
                None
            };
            if !in_import_context {
                visitor.parent = None;
                visitor.flags.set(ContextFlags::IN_UNKNOWN_AT_RULE, false);
                visitor
                    .flags
                    .set(ContextFlags::AT_ROOT_EXCLUDING_STYLE_RULE, false);
                visitor.flags.set(ContextFlags::IN_KEYFRAMES, false);
            }

            visitor.visit_stylesheet(stylesheet)?;

            // visitor.importer = old_importer;
            // visitor.stylesheet = old_stylesheet;
            // visitor.root = old_root;
            visitor.parent = old_parent;
            // visitor.end_of_imports = old_end_of_imports;
            // visitor.out_of_order_imports = old_out_of_order_imports;
            visitor.style_rule_ignoring_at_root = old_style_rule;
            visitor.style_rule_original_selector = old_style_rule_original_selector;
            visitor.style_rule_is_plain_css = old_style_rule_is_plain_css;
            visitor.has_css_nesting = old_has_css_nesting;
            if !in_import_context {
                visitor.media_queries = old_media_queries;
            }
            visitor.declaration_name = old_declaration_name;
            visitor
                .flags
                .set(ContextFlags::IN_UNKNOWN_AT_RULE, old_in_unknown_at_rule);
            visitor.flags.set(
                ContextFlags::AT_ROOT_EXCLUDING_STYLE_RULE,
                old_at_root_excluding_style_rule,
            );
            visitor
                .flags
                .set(ContextFlags::IN_KEYFRAMES, old_in_keyframes);
            if let Some(old_config) = old_configuration {
                visitor.configuration = old_config;
            }

            Ok(())
        });

        // Restore the enclosing store and upstream list before any error can
        // propagate; the module keeps the store its rules registered in and
        // the modules it loaded.
        let (module_store, module_upstream) = match swapped_state {
            Some((old_extender, old_upstream)) => (
                mem::replace(&mut self.extender, old_extender),
                mem::replace(&mut self.current_upstream, old_upstream),
            ),
            None => (ExtensionStore::new(self.empty_span), Vec::new()),
        };

        execution?;

        let module = env.to_module(module_store, module_upstream);

        // Record what the module emitted -- including CSS from modules it
        // loaded in turn, matching how Dart Sass combines a module's CSS with
        // its upstream modules' -- so a later `@import` or `meta.load-css` of
        // it can emit the CSS again. Selectors are recorded hermetically and
        // the values are frozen: this first load is when the module's
        // variables were configured. Recording happens before re-nesting so
        // the record keeps the hermetic selectors.
        let top_level = self.css_tree.top_level_stmts_since(css_start);

        let recorded = top_level
            .iter()
            .filter_map(|&idx| self.record_css_subtree(idx))
            .collect();

        self.module_css.insert(url.clone(), recorded);

        if self.in_import_context {
            self.renest_module_css(&top_level)?;
        }

        self.module_configurations.insert(
            url.clone(),
            Configuration::original_config(current_configuration),
        );

        self.modules.insert(url, Arc::clone(&module));

        Ok(module)
    }

    /// Copies the statement at `idx` and its tree children into an owned
    /// record, so it survives however the tree changes afterwards.
    fn record_css_subtree(&self, idx: CssTreeIdx) -> Option<RecordedCssStmt> {
        let stmt = (*self.css_tree.get(idx)).clone()?;

        let children = self
            .css_tree
            .parent_to_child
            .get(&idx)
            .cloned()
            .unwrap_or_default()
            .into_iter()
            .filter_map(|child| self.record_css_subtree(child))
            .collect();

        Some(RecordedCssStmt { stmt, children })
    }

    /// Nests the module CSS that was just emitted under the rule enclosing
    /// the load site.
    ///
    /// Module selectors resolve hermetically during execution; when the
    /// `@import` or `@include meta.load-css(..)` sits inside a style rule,
    /// each emitted top-level rule's selector is re-resolved against it, so
    /// `a {@include meta.load-css("other")}` turns the module's `c` into
    /// `a c`.
    fn renest_module_css(&mut self, top_level: &[CssTreeIdx]) -> SassResult<()> {
        if !self.style_rule_exists() {
            return Ok(());
        }

        for &idx in top_level {
            let (selector_list, from_plain_css) = match self.css_tree.get(idx).as_ref() {
                Some(CssStmt::RuleSet {
                    selector,
                    from_plain_css,
                    ..
                }) => (selector.as_selector_list().clone(), *from_plain_css),
                _ => continue,
            };

            // A plain CSS rule that uses `&` keeps it: the browser resolves the
            // CSS nesting selector against the enclosing rule, so the rule is
            // nested under the load site rather than merged into it.
            if from_plain_css && selector_list.contains_parent_selector() {
                if let Some(parent) = self.parent {
                    self.css_tree.reparent(idx, parent);
                }
                continue;
            }

            let resolved = self.nest_selector_under_current_rule(selector_list)?;

            if let Some(CssStmt::RuleSet { selector, .. }) = self.css_tree.get_mut(idx).as_mut() {
                *selector = resolved;
            }
        }

        Ok(())
    }

    /// Resolves a hermetic module selector against the current enclosing
    /// style rule and registers the result with the extension store.
    fn nest_selector_under_current_rule(
        &mut self,
        selector_list: SelectorList,
    ) -> SassResult<ExtendedSelector> {
        let parent = self.style_rule_original_selector.clone();

        let resolved = selector_list.resolve_parent_selectors(
            parent,
            !self.flags.at_root_excluding_style_rule(),
            false,
        )?;

        self.extender.add_selector(resolved, &self.media_queries)
    }

    /// The way a path reads in an error message: relative to the working
    /// directory when it is inside it, as written otherwise.
    fn pretty_url(url: &Path) -> String {
        std::env::current_dir()
            .ok()
            .and_then(|cwd| url.strip_prefix(cwd).ok())
            .unwrap_or(url)
            .to_string_lossy()
            .into_owned()
    }

    /// Emits a copy of the CSS a cached module produced when it was first
    /// executed, at the current position in the tree.
    ///
    /// At the root the copies share their selectors with the originals, so
    /// an `@extend` -- whether it ran before or after the copy -- applies to
    /// both: the shared extension store resolves selectors when the document
    /// is serialized, not when statements are added. Under a style rule, each
    /// top-level rule's hermetic selector is re-resolved against it, so a
    /// second load of the same module nests correctly at its own site.
    fn replay_module_css(&mut self, url: &Path) -> SassResult<()> {
        let recorded = match self.module_css.get(url) {
            Some(recorded) => recorded.clone(),
            None => return Ok(()),
        };

        let in_style_rule = self.style_rule_exists();

        for node in recorded {
            let mut stmt = node.stmt;

            // As in `renest_module_css`, a plain CSS rule that uses `&` stays
            // where the load site puts it, selector untouched.
            let mut nest_under_parent = false;

            if in_style_rule
                && let CssStmt::RuleSet {
                    selector,
                    from_plain_css,
                    ..
                } = &mut stmt
            {
                let selector_list = selector.as_selector_list().clone();

                if *from_plain_css && selector_list.contains_parent_selector() {
                    nest_under_parent = true;
                } else {
                    *selector = self.nest_selector_under_current_rule(selector_list)?;
                }
            }

            let new_idx = if nest_under_parent {
                self.add_child(stmt, None::<fn(&CssStmt) -> bool>)
            } else {
                self.add_child(stmt, Some(CssStmt::is_style_rule))
            };
            self.replay_css_children(node.children, new_idx);
        }

        Ok(())
    }

    /// Adds copies of recorded children beneath `parent_idx`.
    fn replay_css_children(&mut self, children: Vec<RecordedCssStmt>, parent_idx: CssTreeIdx) {
        for child in children {
            let child_idx = self.css_tree.add_child(child.stmt, parent_idx);
            self.replay_css_children(child.children, child_idx);
        }
    }

    pub(crate) fn load_module(
        &mut self,
        url: &Path,
        configuration: Option<Rc<RefCell<Configuration>>>,
        names_in_errors: bool,
        span: Span,
        callback: impl Fn(&mut Self, Arc<RefCell<Module>>, StyleSheet) -> SassResult<()>,
    ) -> SassResult<()> {
        let builtin = match url.to_string_lossy().as_ref() {
            "sass:color" => Some(declare_module_color()),
            "sass:list" => Some(declare_module_list()),
            "sass:map" => Some(declare_module_map()),
            "sass:math" => Some(declare_module_math()),
            "sass:meta" => Some(declare_module_meta()),
            "sass:selector" => Some(declare_module_selector()),
            "sass:string" => Some(declare_module_string()),
            _ => None,
        };

        if let Some(builtin) = builtin {
            // A guarded match rather than `is_some()` plus `unwrap()`. A
            // let-chain would read better but stabilised in Rust 1.88, and the
            // MSRV is 1.85.
            match configuration.as_ref() {
                Some(config) if !(**config).borrow().is_implicit() => {
                    let msg = if names_in_errors {
                        format!(
                            "Built-in module {} can't be configured.",
                            url.to_string_lossy()
                        )
                    } else {
                        "Built-in modules can't be configured.".to_owned()
                    };

                    return Err((msg, (**config).borrow().span.unwrap()).into());
                }
                _ => {}
            }

            callback(
                self,
                Arc::new(RefCell::new(builtin)),
                StyleSheet::new(false, url.to_path_buf()),
            )?;
            return Ok(());
        }

        // todo: decide on naming convention for style_sheet vs stylesheet
        let stylesheet = self.load_style_sheet(url.to_string_lossy().as_ref(), false, span)?;

        let canonical_url = self
            .options
            .fs
            .canonicalize(&stylesheet.url)
            .unwrap_or_else(|_| stylesheet.url.clone());

        if self.active_modules.contains(&canonical_url) {
            return Err(("Module loop: this module is already being loaded.", span).into());
        }

        self.active_modules.insert(canonical_url.clone());

        let module = self.execute(stylesheet.clone(), configuration, names_in_errors)?;

        self.active_modules.remove(&canonical_url);

        // Record the load as a module-graph edge -- for a cache hit too, since
        // this context's extensions reach the module either way.
        if !self
            .current_upstream
            .iter()
            .any(|upstream| Arc::ptr_eq(upstream, &module))
        {
            self.current_upstream.push(Arc::clone(&module));
        }

        callback(self, module, stylesheet)?;

        Ok(())
    }

    /// Loads a stylesheet for `meta.load-css`.
    ///
    /// This is [`Visitor::load_module`] in the keep-position mode `@import`
    /// uses: the loaded file gets its own environment and its `!default`
    /// variables are configured from `$with`, but its CSS lands where the
    /// `@include` was written rather than at the root, so
    /// `a {@include meta.load-css("other")}` emits `a b`. The module cache
    /// takes part the way it does everywhere else -- the file executes once
    /// and shares its state with `@use` of the same file, loading it again
    /// replays the CSS it emitted the first time, and configuring an
    /// already-loaded file is an error.
    pub(crate) fn load_css_module(
        &mut self,
        url: &str,
        configuration: Rc<RefCell<Configuration>>,
        span: Span,
    ) -> SassResult<()> {
        if url.starts_with("sass:") {
            if !(*configuration).borrow().is_empty() {
                return Err((
                    format!("Built-in module {} can't be configured.", url),
                    span,
                )
                    .into());
            }

            // A built-in module has no CSS of its own to emit.
            return Ok(());
        }

        let old_in_import_context = mem::replace(&mut self.in_import_context, true);

        let result = self.load_module(url.as_ref(), Some(configuration), true, span, |_, _, _| {
            Ok(())
        });

        self.in_import_context = old_in_import_context;

        result
    }

    fn visit_use_rule(&mut self, use_rule: AstUseRule) -> SassResult<()> {
        let configuration = if use_rule.configuration.is_empty() {
            Rc::new(RefCell::new(Configuration::empty()))
        } else {
            let mut values = BTreeMap::new();

            for var in use_rule.configuration {
                let value = self.visit_expr(var.expr.node)?;
                let value = self.without_slash(value);
                values.insert(
                    var.name.node,
                    ConfiguredValue::explicit(value, var.name.span.merge(var.expr.span)),
                );
            }

            Rc::new(RefCell::new(Configuration::explicit(values, use_rule.span)))
        };

        let span = use_rule.span;

        let namespace = use_rule
            .namespace
            .as_ref()
            .map(|s| Identifier::from(s.trim_start_matches("sass:")));

        self.load_module(
            &use_rule.url,
            Some(Rc::clone(&configuration)),
            false,
            span,
            |visitor, module, _| {
                visitor.env.add_module(namespace, module, span)?;

                Ok(())
            },
        )?;

        Self::assert_configuration_is_empty(&configuration, false)?;

        Ok(())
    }

    pub(crate) fn assert_configuration_is_empty(
        config: &Rc<RefCell<Configuration>>,
        name_in_error: bool,
    ) -> SassResult<()> {
        let config = (**config).borrow();
        // By definition, implicit configurations are allowed to only use a subset
        // of their values.
        if config.is_empty() || config.is_implicit() {
            return Ok(());
        }

        let Spanned { node: name, span } = config.first().unwrap();

        let msg = if name_in_error {
            format!(
                "${name} was not declared with !default in the @used module.",
                name = name
            )
        } else {
            "This variable was not declared with !default in the @used module.".to_owned()
        };

        Err((msg, span).into())
    }

    fn visit_import_rule(&mut self, import_rule: AstImportRule) -> SassResult<Option<Value>> {
        for import in import_rule.imports {
            match import {
                AstImport::Sass(dynamic_import) => {
                    self.visit_dynamic_import_rule(&dynamic_import)?;
                }
                AstImport::Plain(static_import) => self.visit_static_import_rule(static_import)?,
            }
        }

        Ok(None)
    }

    /// Searches the current directory of the file then searches in `load_paths` directories
    /// if the import has not yet been found.
    ///
    /// <https://sass-lang.com/documentation/at-rules/import#finding-the-file>
    /// <https://sass-lang.com/documentation/at-rules/import#load-paths>
    #[allow(clippy::cognitive_complexity, clippy::redundant_clone)]
    /// Resolves an `@import`/`@use` URL to a file on disk.
    ///
    /// Candidates are gathered a group at a time -- the import-only files
    /// before the ordinary ones, `.sass` and `.scss` together before `.css` --
    /// and a group that turns up more than one file is ambiguous rather than
    /// resolved by whichever was checked first. A partial and its non-partial
    /// spelling are the same group, so `_other.scss` beside `other.scss` is an
    /// error too.
    ///
    /// `for_import` is true only for `@import`: the `.import.*` files exist to
    /// give `@import` a different view of a module, so `@use`, `@forward` and
    /// `meta.load-css` never see them. Without this distinction, the
    /// `@forward "other"` inside `_other.import.scss` resolves back to the
    /// import-only file itself and reports a module loop.
    pub fn find_import(
        &self,
        path: &Path,
        for_import: bool,
        span: Span,
    ) -> SassResult<Option<PathBuf>> {
        let path_buf = if path.is_absolute() {
            path.into()
        } else {
            self.current_import_path
                .parent()
                .unwrap_or_else(|| Path::new(""))
                .join(path)
        };

        macro_rules! resolve {
            ($candidates:expr) => {
                let candidates = $candidates;

                if !candidates.is_empty() {
                    return Ok(Some(Self::exactly_one_import(candidates, span)?));
                }
            };
        }

        if path_buf.extension() == Some(OsStr::new("scss"))
            || path_buf.extension() == Some(OsStr::new("sass"))
            || path_buf.extension() == Some(OsStr::new("css"))
        {
            let extension = path_buf.extension().unwrap().to_str().unwrap().to_owned();

            if for_import {
                resolve!(
                    self.import_candidates(
                        &path_buf.with_extension(format!(".import{}", extension))
                    )
                );
            }
            resolve!(self.import_candidates(&path_buf));

            // todo: consider load paths
            return Ok(None);
        }

        macro_rules! resolve_with_extensions {
            ($base:expr) => {
                let base = $base;

                for extensions in [["import.sass", "import.scss"], ["sass", "scss"]] {
                    if !for_import && extensions[0].starts_with("import") {
                        continue;
                    }

                    let mut candidates = Vec::new();

                    for extension in extensions {
                        candidates.extend(self.import_candidates(&base.with_extension(extension)));
                    }

                    resolve!(candidates);
                }

                if for_import {
                    resolve!(self.import_candidates(&base.with_extension("import.css")));
                }
                resolve!(self.import_candidates(&base.with_extension("css")));
            };
        }

        resolve_with_extensions!(path_buf.clone());

        if self.options.fs.is_dir(&path_buf) {
            resolve_with_extensions!(path_buf.join("index"));
        }

        for load_path in &self.options.load_paths {
            let from_load_path = load_path.join(path);

            resolve_with_extensions!(from_load_path.clone());

            if self.options.fs.is_dir(&from_load_path) {
                resolve_with_extensions!(from_load_path.join("index"));
            }
        }

        Ok(None)
    }

    /// The files that exist for one exact name: the name itself and its partial
    /// spelling.
    fn import_candidates(&self, path: &Path) -> Vec<PathBuf> {
        let dirname = path.parent().unwrap_or_else(|| Path::new(""));
        let basename = path.file_name().unwrap_or_else(|| OsStr::new(".."));
        let partial = dirname.join(format!("_{}", basename.to_string_lossy()));

        let mut candidates = Vec::new();

        if self.options.fs.is_file(path) {
            candidates.push(path.to_path_buf());
        }

        if self.options.fs.is_file(&partial) {
            candidates.push(partial);
        }

        candidates
    }

    /// Picks the single candidate, or reports the ambiguity.
    fn exactly_one_import(mut candidates: Vec<PathBuf>, span: Span) -> SassResult<PathBuf> {
        if candidates.len() == 1 {
            return Ok(candidates.remove(0));
        }

        let mut names = candidates
            .iter()
            .map(|path| {
                path.file_name()
                    .unwrap_or_else(|| OsStr::new(".."))
                    .to_string_lossy()
                    .into_owned()
            })
            .collect::<Vec<_>>();
        names.sort();

        Err((
            format!(
                "It's not clear which file to import. Found:\n  {}",
                names.join("\n  ")
            ),
            span,
        )
            .into())
    }

    fn parse_file(
        &mut self,
        lexer: Lexer,
        path: &Path,
        empty_span: Span,
    ) -> SassResult<StyleSheet> {
        match InputSyntax::for_path(path) {
            InputSyntax::Scss => ScssParser::new(lexer, self.options, empty_span, path).__parse(),
            InputSyntax::Sass => SassParser::new(lexer, self.options, empty_span, path).__parse(),
            InputSyntax::Css => CssParser::new(lexer, self.options, empty_span, path).__parse(),
        }
    }

    fn import_like_node(
        &mut self,
        url: &str,
        for_import: bool,
        span: Span,
    ) -> SassResult<StyleSheet> {
        if let Some(name) = self.find_import(url.as_ref(), for_import, span)? {
            let name = self.options.fs.canonicalize(&name).unwrap_or(name);
            if let Some(style_sheet) = self.import_cache.get(&name) {
                return Ok(style_sheet.clone());
            }

            let file = self.map.add_file(
                name.to_string_lossy().into(),
                String::from_utf8(self.options.fs.read(&name)?)?,
            );

            let old_is_use_allowed = self.flags.is_use_allowed();
            self.flags.set(ContextFlags::IS_USE_ALLOWED, true);

            let style_sheet =
                self.parse_file(Lexer::new_from_file(&file), &name, file.span.subspan(0, 0))?;

            self.flags
                .set(ContextFlags::IS_USE_ALLOWED, old_is_use_allowed);

            if self.files_seen.contains(&name) {
                self.import_cache.insert(name, style_sheet.clone());
            } else {
                self.files_seen.insert(name);
            }

            return Ok(style_sheet);
        }

        Err(("Can't find stylesheet to import.", span).into())
    }

    pub(crate) fn load_style_sheet(
        &mut self,
        url: &str,
        // default=false
        for_import: bool,
        span: Span,
    ) -> SassResult<StyleSheet> {
        // todo: import cache
        self.import_like_node(url, for_import, span)
    }

    fn visit_dynamic_import_rule(&mut self, dynamic_import: &AstSassImport) -> SassResult<()> {
        let stylesheet = self.load_style_sheet(&dynamic_import.url, true, dynamic_import.span)?;

        let url = stylesheet.url.clone();

        if self.active_modules.contains(&url) {
            return Err(("This file is already being loaded.", dynamic_import.span).into());
        }

        self.active_modules.insert(url.clone());

        // If the imported stylesheet doesn't use any modules, we can inject its
        // CSS directly into the current stylesheet.
        if stylesheet.uses.is_empty() && stylesheet.forwards.is_empty() {
            self.visit_stylesheet(stylesheet)?;
            return Ok(());
        }

        // The stylesheet loads modules, so its modules execute in import
        // context: their CSS keeps the position of this `@import` -- nested
        // under its style rule where Dart Sass re-nests the injected CSS --
        // and a module that is already cached replays its recorded CSS here
        // instead of emitting nothing.
        let old_in_import_context = mem::replace(&mut self.in_import_context, true);

        let env = self.env.for_import();

        let result = self.with_environment::<SassResult<()>, _>(env.clone(), |visitor| {
            let old_configuration = Rc::clone(&visitor.configuration);

            // This configuration is only used if it passes through a `@forward`
            // rule, so we avoid creating unnecessary ones for performance reasons.
            if !stylesheet.forwards.is_empty() {
                visitor.configuration = Rc::new(RefCell::new(env.to_implicit_configuration()));
            }

            let result = visitor.visit_stylesheet(stylesheet);

            visitor.configuration = old_configuration;

            result
        });

        self.in_import_context = old_in_import_context;

        result?;

        // Create a dummy module with empty CSS and no extensions to make forwarded
        // members available in the current import context and to combine all the
        // CSS from modules used by [stylesheet].
        let module = env.to_dummy_module(self.empty_span);
        self.env.import_forwards(module);

        self.active_modules.remove(&url);

        Ok(())
    }

    fn visit_static_import_rule(&mut self, static_import: AstPlainCssImport) -> SassResult<()> {
        let import = self.interpolation_to_value(static_import.url, false, false)?;

        let modifiers = static_import
            .modifiers
            .map(|modifiers| self.interpolation_to_value(modifiers, false, false))
            .transpose()?;

        let node = CssStmt::Import(import, modifiers);

        if self.parent.is_some() && self.parent != Some(CssTree::ROOT) {
            // Nested, so it stays where it was written -- through `add_child`
            // for the reason `visit_style` gives, since an import holds its
            // place among the rule's other children.
            self.add_child_after_sibling(node);
        } else if self.end_of_imports == self.css_tree.root_child_count() {
            // Still inside the `@import` block, so it can stay in the tree.
            self.css_tree.add_stmt(node, Some(CssTree::ROOT));
            self.end_of_imports += 1;
        } else {
            // A rule has been written since, so this import has to move back
            // into the block when the tree is finished.
            self.import_nodes.push(node);
        }

        Ok(())
    }

    fn visit_debug_rule(&mut self, debug_rule: AstDebugRule) -> SassResult<Option<Value>> {
        if self.options.quiet {
            return Ok(None);
        }

        let value = self.visit_expr(debug_rule.value)?;
        let message = match value {
            Value::String(text, _) => text,
            value => value.inspect(debug_rule.span)?,
        };

        let loc = self.map.look_up_span(debug_rule.span);
        self.options.logger.debug(loc, message.as_str());

        Ok(None)
    }

    fn visit_content_rule(&mut self, content_rule: AstContentRule) -> SassResult<Option<Value>> {
        let span = content_rule.args.span;
        if let Some(content) = &self.env.content {
            #[allow(mutable_borrow_reservation_conflict)]
            self.run_user_defined_callable(
                MaybeEvaledArguments::Invocation(content_rule.args),
                Arc::clone(content),
                &content.env.clone(),
                span,
                |content, visitor| {
                    for stmt in content.content.body.clone() {
                        let result = visitor.visit_stmt(stmt)?;
                        debug_assert!(result.is_none());
                    }

                    Ok(())
                },
            )?;
        }

        Ok(None)
    }

    /// Removes the trailing run of `nodes` that the current parents already
    /// provide, and returns the innermost of them: the node the `@at-root`
    /// body can go straight into.
    ///
    /// A port of dart-sass 1.103.1's `_trimIncluded`. `nodes` lists the
    /// included parents from innermost to outermost. If a trailing run of
    /// them is contiguous and ends directly under the root, that run is
    /// removed, so only the parents left over need copies. Otherwise `nodes`
    /// is left as it is and the root is returned.
    fn trim_included(&self, nodes: &mut Vec<CssTreeIdx>) -> CssTreeIdx {
        if nodes.is_empty() {
            return CssTree::ROOT;
        }

        let mut parent = self.parent;

        let mut innermost_contiguous: Option<usize> = None;

        for i in 0..nodes.len() {
            while parent != nodes.get(i).copied() {
                innermost_contiguous = None;

                let grandparent = self.css_tree.child_to_parent.get(&parent.unwrap()).copied();
                if grandparent.is_none() {
                    unreachable!(
                        "Expected {:?} to be an ancestor of {:?}.",
                        nodes[i], grandparent
                    )
                }
                parent = grandparent;
            }
            innermost_contiguous = innermost_contiguous.or(Some(i));

            let grandparent = self.css_tree.child_to_parent.get(&parent.unwrap()).copied();
            if grandparent.is_none() {
                unreachable!(
                    "Expected {:?} to be an ancestor of {:?}.",
                    nodes[i], grandparent
                )
            }
            parent = grandparent;
        }

        if parent != Some(CssTree::ROOT) {
            return CssTree::ROOT;
        }

        // Without the removal the trimmed parents were copied anyway, which
        // left the original empty beside its copy: `@fblthp {}` followed by
        // `@fblthp {.bar {...}}` (libsass at-root test 140).
        let innermost = innermost_contiguous.unwrap();
        let root = nodes[innermost];
        nodes.truncate(innermost);
        root
    }

    fn visit_at_root_rule(&mut self, mut at_root_rule: AstAtRootRule) -> SassResult<Option<Value>> {
        let query = match at_root_rule.query.clone() {
            Some(query) => {
                let resolved = self.perform_interpolation(query.node, true)?;

                let span = query.span;

                let query_toks = Lexer::new_from_string(&resolved, span);

                AtRootQueryParser::new(query_toks).parse()?
            }
            None => AtRootQuery::default(),
        };

        let mut current_parent_idx = self.parent;

        let mut included = Vec::new();

        while let Some(parent_idx) = current_parent_idx {
            let parent = self.css_tree.get(parent_idx);
            let grandparent_idx = match &*parent {
                Some(parent) => {
                    if !query.excludes(parent) {
                        included.push(parent_idx);
                    }
                    self.css_tree.child_to_parent.get(&parent_idx).copied()
                }
                None => break,
            };

            current_parent_idx = grandparent_idx;
        }

        let root = self.trim_included(&mut included);

        // If we didn't exclude any rules, we don't need to use the copies we might
        // have created.
        if Some(root) == self.parent {
            self.with_scope::<SassResult<()>, _>(false, true, |visitor| {
                for stmt in at_root_rule.body {
                    let result = visitor.visit_stmt(stmt)?;
                    debug_assert!(result.is_none());
                }

                Ok(())
            })?;
            return Ok(None);
        }

        // Copy the included parents left after trimming, outermost first, as
        // a chain under `root`, and put the body in the innermost copy. With
        // none left the body goes straight into `root`, which dart-sass uses
        // as is rather than copying. `None` stands for the document root.
        let mut inner_copy = root;
        for node in included.iter().rev() {
            let copy = self
                .css_tree
                .get(*node)
                .as_ref()
                .map(CssStmt::copy_without_children)
                .unwrap();
            inner_copy = self.css_tree.add_child(copy, inner_copy);
        }
        let inner_copy = (inner_copy != CssTree::ROOT).then_some(inner_copy);

        let body = mem::take(&mut at_root_rule.body);

        self.with_scope_for_at_root::<SassResult<()>, _>(inner_copy, &query, |visitor| {
            for stmt in body {
                let result = visitor.visit_stmt(stmt)?;
                debug_assert!(result.is_none());
            }

            Ok(())
        })?;

        Ok(None)
    }

    fn with_scope_for_at_root<T, F: FnOnce(&mut Self) -> T>(
        &mut self,
        new_parent_idx: Option<CssTreeIdx>,
        query: &AtRootQuery,
        callback: F,
    ) -> T {
        let old_parent = self.parent;
        self.parent = new_parent_idx;

        let old_at_root_excluding_style_rule = self.flags.at_root_excluding_style_rule();

        if query.excludes_style_rules() {
            self.flags
                .set(ContextFlags::AT_ROOT_EXCLUDING_STYLE_RULE, true);
        }

        let old_media_query_info = if self.media_queries.is_some() && query.excludes_name("media") {
            Some((self.media_queries.take(), self.media_query_sources.take()))
        } else {
            None
        };

        let was_in_keyframes = if self.flags.in_keyframes() && query.excludes_name("keyframes") {
            let was = self.flags.in_keyframes();
            self.flags.set(ContextFlags::IN_KEYFRAMES, false);
            was
        } else {
            self.flags.in_keyframes()
        };

        // todo:
        // if self.flags.in_unknown_at_rule() && !included.iter().any(|parent| parent is CssAtRule)

        let res = self.with_scope(false, true, callback);

        self.parent = old_parent;

        self.flags.set(
            ContextFlags::AT_ROOT_EXCLUDING_STYLE_RULE,
            old_at_root_excluding_style_rule,
        );

        if let Some((old_media_queries, old_media_query_sources)) = old_media_query_info {
            self.media_queries = old_media_queries;
            self.media_query_sources = old_media_query_sources;
        }

        self.flags.set(ContextFlags::IN_KEYFRAMES, was_in_keyframes);

        res
    }

    fn visit_function_decl(&mut self, fn_decl: AstFunctionDecl) {
        let name = fn_decl.name.node;
        // todo: independency

        let func = SassFunction::UserDefined(UserDefinedFunction {
            function: Arc::new(fn_decl),
            name,
            env: self.env.new_closure(),
        });

        self.env.insert_fn(func);
    }

    pub(crate) fn parse_selector_from_string(
        &mut self,
        selector_text: &str,
        allows_parent: bool,
        allows_placeholder: bool,
        plain_css: bool,
        span: Span,
    ) -> SassResult<SelectorList> {
        let sel_toks = Lexer::new_from_string(selector_text, span);

        SelectorParser::new(sel_toks, allows_parent, allows_placeholder, plain_css, span).parse()
    }

    fn visit_extend_rule(&mut self, extend_rule: AstExtendRule) -> SassResult<Option<Value>> {
        if !self.style_rule_exists() || self.declaration_name.is_some() {
            return Err((
                "@extend may only be used within style rules.",
                extend_rule.span,
            )
                .into());
        }

        // dart-sass's `visitExtendRule` warns about a bogus extender before
        // it looks at the target.
        if let Some(original) = self.style_rule_original_selector.clone() {
            for complex in &original.components {
                if !complex.is_bogus() {
                    continue;
                }

                let message = format!(
                    "The selector \"{}\" is invalid CSS and {} be an extender.\n{}",
                    complex.to_string().trim(),
                    if complex.is_useless() {
                        "can't"
                    } else {
                        "shouldn't"
                    },
                    BOGUS_COMBINATORS_FOOTER
                );
                self.emit_deprecation(
                    Deprecation::BogusCombinators,
                    message,
                    complex.span.unwrap_or(original.span),
                    Some("invalid selector"),
                    vec![(extend_rule.span, "@extend rule".to_owned())],
                );
            }
        }

        let super_selector = self.style_rule_ignoring_at_root.clone().unwrap();

        let target_text = self.interpolation_to_value(extend_rule.value, false, true)?;

        let list =
            self.parse_selector_from_string(&target_text, false, true, false, extend_rule.span)?;

        for complex in list.components {
            if complex.components.len() != 1 || !complex.components.first().unwrap().is_compound() {
                // If the selector was a compound selector but not a simple
                // selector, emit a more explicit error.
                return Err(("complex selectors may not be extended.", extend_rule.span).into());
            }

            let compound = match complex.components.first() {
                Some(ComplexSelectorComponent::Compound(c)) => c,
                Some(..) | None => unreachable!("checked by above condition"),
            };
            if compound.components.len() != 1 {
                return Err((
                    format!(
                        "compound selectors may no longer be extended.\nConsider `@extend {}` instead.\nSee http://bit.ly/ExtendCompound for details.\n",
                        compound.components.iter().map(ToString::to_string).collect::<Vec<String>>().join(", ")
                    )
                , extend_rule.span).into());
            }

            self.extender.add_extension(
                super_selector.clone().into_selector().0,
                compound.components.first().unwrap(),
                &ExtendRule {
                    is_optional: extend_rule.is_optional,
                },
                &self.media_queries,
                extend_rule.span,
            )?;
        }

        Ok(None)
    }

    fn visit_error_rule(&mut self, error_rule: AstErrorRule) -> SassResult<Box<SassError>> {
        let value = self
            .visit_expr(error_rule.value)?
            .inspect(error_rule.span)?;

        Ok((value, error_rule.span).into())
    }

    fn merge_media_queries(
        queries1: &[MediaQuery],
        queries2: &[MediaQuery],
    ) -> Option<Vec<MediaQuery>> {
        let mut queries = Vec::new();

        for query1 in queries1 {
            for query2 in queries2 {
                match query1.merge(query2) {
                    MediaQueryMergeResult::Empty => continue,
                    MediaQueryMergeResult::Unrepresentable => return None,
                    MediaQueryMergeResult::Success(result) => queries.push(result),
                }
            }
        }

        Some(queries)
    }

    fn visit_media_queries(
        &mut self,
        queries: Interpolation,
        span: Span,
    ) -> SassResult<Vec<CssMediaQuery>> {
        let resolved = self.perform_interpolation(queries, true)?;

        CssMediaQuery::parse_list(&resolved, span)
    }

    fn visit_media_rule(&mut self, media_rule: AstMedia) -> SassResult<Option<Value>> {
        if self.declaration_name.is_some() {
            return Err((
                "Media rules may not be used within nested declarations.",
                media_rule.span,
            )
                .into());
        }

        let queries1 = self.visit_media_queries(media_rule.query, media_rule.query_span)?;

        // See the note in `visit_supports_rule`: inside passed-through CSS
        // nesting this rule stays where it was written, with the query it was
        // written with -- neither merged into an enclosing query nor hoisted
        // out of the style rule.
        if self.has_css_nesting {
            let children = media_rule.body;
            let stmt = CssStmt::Media(
                MediaRule {
                    query: queries1,
                    body: Vec::new(),
                },
                false,
            );

            self.with_parent_opt(
                stmt,
                false,
                |visitor| {
                    for stmt in children {
                        let result = visitor.visit_stmt(stmt)?;
                        debug_assert!(result.is_none());
                    }

                    Ok(())
                },
                None::<fn(&CssStmt) -> bool>,
            )?;

            return Ok(None);
        }

        // todo: superfluous clone?
        let queries2 = self.media_queries.clone();
        let merged_queries = queries2
            .as_ref()
            .and_then(|queries2| Self::merge_media_queries(queries2, &queries1));

        let merged_sources = match &merged_queries {
            Some(merged_queries) if merged_queries.is_empty() => return Ok(None),
            Some(..) => {
                let mut set = IndexSet::new();
                set.extend(self.media_query_sources.clone().unwrap());
                set.extend(self.media_queries.clone().unwrap());
                set.extend(queries1.clone());
                set
            }
            None => IndexSet::new(),
        };

        let children = media_rule.body;

        let query = merged_queries.clone().unwrap_or_else(|| queries1.clone());

        let media_rule = CssStmt::Media(
            MediaRule {
                query,
                body: Vec::new(),
            },
            false,
        );

        self.with_parent(
            media_rule,
            true,
            |visitor| {
                visitor.with_media_queries(
                    Some(merged_queries.unwrap_or(queries1)),
                    Some(merged_sources.clone()),
                    |visitor| {
                        if !visitor.style_rule_exists() {
                            for stmt in children {
                                let result = visitor.visit_stmt(stmt)?;
                                debug_assert!(result.is_none());
                            }
                        } else {
                            // If we're in a style rule, copy it into the media query so that
                            // declarations immediately inside @media have somewhere to go.
                            //
                            // For example, "a {@media screen {b: c}}" should produce
                            // "@media screen {a {b: c}}".
                            let selector = visitor.style_rule_ignoring_at_root.clone().unwrap();
                            let ruleset = CssStmt::RuleSet {
                                selector,
                                body: Vec::new(),
                                is_group_end: false,
                                from_plain_css: visitor.style_rule_is_plain_css,
                            };

                            visitor.with_parent(
                                ruleset,
                                false,
                                |visitor| {
                                    for stmt in children {
                                        let result = visitor.visit_stmt(stmt)?;
                                        debug_assert!(result.is_none());
                                    }

                                    Ok(())
                                },
                                |_| false,
                            )?;
                        }

                        Ok(())
                    },
                )
            },
            |stmt| match stmt {
                CssStmt::RuleSet { .. } => true,
                // todo: node.queries.every(mergedSources.contains))
                CssStmt::Media(media_rule, ..) => {
                    !merged_sources.is_empty()
                        && media_rule
                            .query
                            .iter()
                            .all(|query| merged_sources.contains(query))
                }
                _ => false,
            },
        )?;

        Ok(None)
    }

    fn visit_unknown_at_rule(
        &mut self,
        unknown_at_rule: AstUnknownAtRule,
    ) -> SassResult<Option<Value>> {
        if self.declaration_name.is_some() {
            return Err((
                "At-rules may not be used within nested declarations.",
                unknown_at_rule.span,
            )
                .into());
        }

        let name = self.interpolation_to_value(unknown_at_rule.name, false, false)?;

        let value = unknown_at_rule
            .value
            .map(|v| self.interpolation_to_value(v, true, true))
            .transpose()?;

        if unknown_at_rule.body.is_none() {
            let stmt = CssStmt::UnknownAtRule(
                UnknownAtRule {
                    name,
                    params: value.unwrap_or_default(),
                    body: Vec::new(),
                    has_body: false,
                    span: unknown_at_rule.span,
                },
                false,
            );

            // Route through `add_child` for the same reason a style
            // declaration does (see `visit_style`): a childless at-rule holds
            // its place in source order, so a nested rule written above it
            // splits the enclosing rule rather than letting the at-rule hoist
            // back up beside the rule's earlier children. dart-sass calls
            // `_copyParentAfterSibling` here for exactly this.
            self.add_child_after_sibling(stmt);

            return Ok(None);
        }

        // dart-sass copies the enclosing style rule into a nested at-rule so
        // that declarations written directly inside it have somewhere to go,
        // and exempts `@font-face`, whose descriptors belong to the at-rule
        // itself. The comparison is on the plain name and is neither
        // case-insensitive nor unvendored, so `@-moz-font-face` still bubbles.
        let is_font_face = name == "font-face";

        let was_in_keyframes = self.flags.in_keyframes();
        let was_in_unknown_at_rule = self.flags.in_unknown_at_rule();

        if unvendor(&name) == "keyframes" {
            self.flags.set(ContextFlags::IN_KEYFRAMES, true);
        } else {
            self.flags.set(ContextFlags::IN_UNKNOWN_AT_RULE, true);
        }

        let span = unknown_at_rule.span;
        let children = unknown_at_rule.body.unwrap();

        let stmt = CssStmt::UnknownAtRule(
            UnknownAtRule {
                name,
                params: value.unwrap_or_default(),
                body: Vec::new(),
                has_body: true,
                span,
            },
            false,
        );

        // See the note in `visit_supports_rule`: inside passed-through CSS
        // nesting this rule stays where it was written, unmerged.
        if self.has_css_nesting {
            self.with_parent_opt(
                stmt,
                true,
                |visitor| {
                    for stmt in children {
                        let result = visitor.visit_stmt(stmt)?;
                        debug_assert!(result.is_none());
                    }

                    Ok(())
                },
                None::<fn(&CssStmt) -> bool>,
            )?;

            self.flags.set(ContextFlags::IN_KEYFRAMES, was_in_keyframes);
            self.flags
                .set(ContextFlags::IN_UNKNOWN_AT_RULE, was_in_unknown_at_rule);

            return Ok(None);
        }

        self.with_parent(
            stmt,
            true,
            |visitor| {
                if !visitor.style_rule_exists() || visitor.flags.in_keyframes() || is_font_face {
                    for stmt in children {
                        let result = visitor.visit_stmt(stmt)?;
                        debug_assert!(result.is_none());
                    }
                } else {
                    // If we're in a style rule, copy it into the at-rule so that
                    // declarations immediately inside it have somewhere to go.
                    //
                    // For example, "a {@foo {b: c}}" should produce "@foo {a {b: c}}".
                    let selector = visitor.style_rule_ignoring_at_root.clone().unwrap();

                    let style_rule = CssStmt::RuleSet {
                        selector,
                        body: Vec::new(),
                        is_group_end: false,
                        from_plain_css: visitor.style_rule_is_plain_css,
                    };

                    visitor.with_parent(
                        style_rule,
                        false,
                        |visitor| {
                            for stmt in children {
                                let result = visitor.visit_stmt(stmt)?;
                                debug_assert!(result.is_none());
                            }

                            Ok(())
                        },
                        |_| false,
                    )?;
                }

                Ok(())
            },
            CssStmt::is_style_rule,
        )?;

        self.flags.set(ContextFlags::IN_KEYFRAMES, was_in_keyframes);
        self.flags
            .set(ContextFlags::IN_UNKNOWN_AT_RULE, was_in_unknown_at_rule);

        Ok(None)
    }

    pub(crate) fn emit_warning(&mut self, message: &str, span: Span) {
        if self.options.quiet {
            return;
        }
        let loc = self.map.look_up_span(span);
        self.options.logger.warn(loc, message);
    }

    /// How many warnings of one deprecation are reported before the rest are
    /// only counted, unless [`Options::verbose`] is set. dart-sass's
    /// `_maxRepetitions`.
    const MAX_DEPRECATION_REPETITIONS: usize = 5;

    /// Reports a deprecation warning, as dart-sass's `_warn` does when given a
    /// deprecation.
    ///
    /// `primary` is the span the warning is about and `primary_label` the
    /// text written after its underline; `secondary` are further spans drawn
    /// in the same frame, each with its label. A warning with the same
    /// message and span as one already reported is dropped. Once a
    /// deprecation has been reported [`Self::MAX_DEPRECATION_REPETITIONS`]
    /// times, later ones are counted for [`Self::summarize_deprecations`]
    /// instead of reported.
    fn emit_deprecation(
        &mut self,
        deprecation: Deprecation,
        message: String,
        primary: Span,
        primary_label: Option<&str>,
        secondary: Vec<(Span, String)>,
    ) {
        if self.options.quiet || !self.deprecations_emitted.insert((message.clone(), primary)) {
            return;
        }

        let count = self.deprecation_counts.entry(deprecation).or_insert(0);
        *count += 1;
        if *count > Self::MAX_DEPRECATION_REPETITIONS && !self.options.verbose {
            return;
        }

        let location = self.map.look_up_span(primary);
        let mut highlights = vec![Highlight {
            loc: location.clone(),
            label: primary_label.map(str::to_owned),
            primary: true,
        }];
        for (span, label) in secondary {
            let loc = self.map.look_up_span(span);
            // The frame draws one file; dart-sass would draw a second.
            if loc.file.name() == location.file.name() {
                highlights.push(Highlight {
                    loc,
                    label: Some(label),
                    primary: false,
                });
            }
        }
        let frame = highlight(highlights, self.options.unicode_error_messages);

        let mut trace = format!(
            "{} {}:{}",
            location.file.name(),
            location.begin.line + 1,
            location.begin.column + 1
        );
        if self.is_root_stylesheet_context(&location) {
            trace.push_str("  root stylesheet");
        }

        let warning = DeprecationWarning::new(deprecation, message, location, &frame, &trace);
        self.options.logger.deprecation(&warning);
    }

    /// Whether a warning at `location` comes from the entry stylesheet itself,
    /// outside any mixin, function or content block: the only case where
    /// dart-sass's stack trace is the single frame `root stylesheet`.
    fn is_root_stylesheet_context(&self, location: &SpanLoc) -> bool {
        !self.flags.in_mixin()
            && !self.flags.in_function()
            && !self.flags.in_content_block()
            && location.file.name() == self.entry_file_name
    }

    /// Tells the logger how many deprecation warnings were left out as
    /// repetitive, if any were. dart-sass prints this once, after compiling.
    pub(crate) fn summarize_deprecations(&self) {
        if self.options.quiet || self.options.verbose {
            return;
        }

        let omitted = self
            .deprecation_counts
            .values()
            .map(|count| count.saturating_sub(Self::MAX_DEPRECATION_REPETITIONS))
            .sum::<usize>();
        if omitted > 0 {
            self.options.logger.repetitive_deprecations_omitted(omitted);
        }
    }

    /// Makes each complex selector in `selector` point at the right source
    /// for a warning.
    ///
    /// The parser records a complex selector's span as offsets into `text`,
    /// which are offsets into the source only when `text` is the selector as
    /// written. When interpolation, a comment or the indented syntax makes
    /// them differ, every complex selector points at the whole selector
    /// instead, trimmed of surrounding whitespace.
    fn point_selector_spans_at_source(&self, selector: &mut SelectorList, text: &str, span: Span) {
        let source = self.map.find_file(span.low()).source_slice(span);
        if trim_ascii(source, true) == text {
            return;
        }

        let leading = source.len() - source.trim_start().len();
        let trimmed = span.subspan(leading as u64, (leading + source.trim().len()) as u64);
        for complex in &mut selector.components {
            complex.span = Some(trimmed);
        }
    }

    /// Warns about each bogus complex selector in the style rule at
    /// `rule_idx`, as dart-sass's `_warnForBogusCombinators` does once the
    /// rule's children have been evaluated.
    ///
    /// Nothing is reported for a rule that would be invisible anyway, such as
    /// one with a placeholder or one whose children all moved out of it, so
    /// `a > {b {c: d}}` is legal nesting and quiet. `fallback_span` is used for
    /// a complex selector with no span of its own, such as one `@extend` added.
    fn warn_for_bogus_combinators(&mut self, rule_idx: CssTreeIdx, fallback_span: Span) {
        if self.is_invisible_other_than_bogus_combinators(rule_idx) {
            return;
        }

        let selector = match self.css_tree.get(rule_idx).as_ref() {
            Some(CssStmt::RuleSet { selector, .. }) => selector.as_selector_list().clone(),
            _ => return,
        };
        let children = self
            .css_tree
            .parent_to_child
            .get(&rule_idx)
            .cloned()
            .unwrap_or_default();

        for complex in &selector.components {
            if !complex.is_bogus() {
                continue;
            }

            let text = complex.to_string();
            let text = text.trim();
            let span = complex.span.unwrap_or(fallback_span);

            if complex.is_useless() {
                let message = format!(
                    "The selector \"{text}\" is invalid CSS. It will be omitted from the generated CSS.\n{BOGUS_COMBINATORS_FOOTER}"
                );
                self.emit_deprecation(
                    Deprecation::BogusCombinators,
                    message,
                    span,
                    None,
                    Vec::new(),
                );
            } else if complex.has_leading_combinator() {
                if !self.is_plain_css {
                    let message = format!(
                        "The selector \"{text}\" is invalid CSS.\n{BOGUS_COMBINATORS_FOOTER}"
                    );
                    self.emit_deprecation(
                        Deprecation::BogusCombinators,
                        message,
                        span,
                        None,
                        Vec::new(),
                    );
                }
            } else {
                let will_be_omitted = if complex.is_bogus_other_than_leading_combinator() {
                    " It will be omitted from the generated CSS."
                } else {
                    ""
                };
                let only_comments = children.iter().all(|&child| {
                    matches!(
                        self.css_tree.get(child).as_ref(),
                        Some(CssStmt::Comment(..))
                    )
                });
                let suggestion = if only_comments {
                    "\n(try converting to a //-style comment)"
                } else {
                    ""
                };
                let secondary = children
                    .first()
                    .and_then(|&child| self.css_node_span(child))
                    .map(|child_span| {
                        vec![(child_span, format!("this is not a style rule{suggestion}"))]
                    })
                    .unwrap_or_default();

                let message = format!(
                    "The selector \"{text}\" is only valid for nesting and shouldn't\nhave children other than style rules.{will_be_omitted}\n{BOGUS_COMBINATORS_FOOTER}"
                );
                self.emit_deprecation(
                    Deprecation::BogusCombinators,
                    message,
                    span,
                    Some("invalid selector"),
                    secondary,
                );
            }
        }
    }

    /// Whether the CSS node at `idx` would be left out of the output even if
    /// bogus combinators were allowed: dart-sass's
    /// `isInvisibleOtherThanBogusCombinators`, with comments counted as
    /// visible.
    ///
    /// Declarations, comments, imports and unknown at-rules are visible. A
    /// style rule is invisible if its selector is or all of its children
    /// are; any other parent node if all of its children are.
    fn is_invisible_other_than_bogus_combinators(&self, idx: CssTreeIdx) -> bool {
        let children_invisible = || {
            self.css_tree
                .parent_to_child
                .get(&idx)
                .is_none_or(|children| {
                    children
                        .iter()
                        .all(|&child| self.is_invisible_other_than_bogus_combinators(child))
                })
        };

        match self.css_tree.get(idx).as_ref() {
            Some(CssStmt::RuleSet { selector, .. }) => {
                selector.as_selector_list().is_invisible_with(false) || children_invisible()
            }
            Some(CssStmt::Media(..) | CssStmt::Supports(..) | CssStmt::KeyframesRuleSet(..)) => {
                children_invisible()
            }
            Some(
                CssStmt::Style(..)
                | CssStmt::Comment(..)
                | CssStmt::Import(..)
                | CssStmt::UnknownAtRule(..),
            ) => false,
            None => true,
        }
    }

    /// Where the CSS node at `idx` was written, for the nodes that record it.
    fn css_node_span(&self, idx: CssTreeIdx) -> Option<Span> {
        match self.css_tree.get(idx).as_ref() {
            Some(CssStmt::Style(style)) => Some(style.span),
            Some(CssStmt::Comment(_, span)) => Some(*span),
            Some(CssStmt::UnknownAtRule(rule, _)) => Some(rule.span),
            _ => None,
        }
    }

    /// Evaluate a `@warn` rule and hand its message to the logger.
    ///
    /// A top-level string is reported as its text, so `@warn "careful"` says
    /// `careful` rather than `"careful"`; every other value is serialized as
    /// CSS, which is why `@warn null` says nothing and `@warn (a: 1)` is the
    /// error `(a: 1) isn't a valid CSS value.` dart-sass draws the same
    /// distinction in `_EvaluateVisitor.visitWarnRule`, and it unwraps only
    /// the outermost value: a string inside a list keeps its quotes.
    fn visit_warn_rule(&mut self, warn_rule: AstWarn) -> SassResult<()> {
        if self.warnings_emitted.insert(warn_rule.span) {
            let value = self.visit_expr(warn_rule.value)?;
            let message = match value {
                Value::String(text, _) => text,
                value => value.to_css_string(warn_rule.span, self.options.is_compressed())?,
            };
            self.emit_warning(&message, warn_rule.span);
        }

        Ok(())
    }

    fn with_media_queries<T>(
        &mut self,
        queries: Option<Vec<MediaQuery>>,
        sources: Option<IndexSet<MediaQuery>>,
        callback: impl FnOnce(&mut Self) -> T,
    ) -> T {
        let old_media_queries = self.media_queries.take();
        let old_media_query_sources = self.media_query_sources.take();
        self.media_queries = queries;
        self.media_query_sources = sources;
        let result = callback(self);
        self.media_queries = old_media_queries;
        self.media_query_sources = old_media_query_sources;
        result
    }

    fn with_environment<T, F: FnOnce(&mut Self) -> T>(
        &mut self,
        env: Environment,
        callback: F,
    ) -> T {
        let mut old_env = env;
        mem::swap(&mut self.env, &mut old_env);
        let val = callback(self);
        mem::swap(&mut self.env, &mut old_env);
        val
    }

    fn add_child<F: Fn(&CssStmt) -> bool>(
        &mut self,
        node: CssStmt,
        through: Option<F>,
    ) -> CssTreeIdx {
        if self.parent.is_none() || self.parent == Some(CssTree::ROOT) {
            return self.css_tree.add_stmt(node, self.parent);
        }

        let mut parent = self.parent.unwrap();

        if let Some(through) = through {
            while parent != CssTree::ROOT && through(self.css_tree.get(parent).as_ref().unwrap()) {
                let grandparent = self.css_tree.child_to_parent.get(&parent).copied();
                debug_assert!(
                    grandparent.is_some(),
                    "through() must return false for at least one parent of $node."
                );
                parent = grandparent.unwrap();
            }

            // If the parent has a (visible) following sibling, we shouldn't add to
            // the parent. Instead, we should create a copy and add it after the
            // interstitial sibling.
            if self.css_tree.has_following_sibling(parent) {
                let grandparent = self.css_tree.child_to_parent.get(&parent).copied().unwrap();
                let parent_node = self
                    .css_tree
                    .get(parent)
                    .as_ref()
                    .map(CssStmt::copy_without_children)
                    .unwrap();
                parent = self.css_tree.add_child(parent_node, grandparent);

                // Everything that follows belongs in this copy, not in a copy
                // of its own. Without this the copy is computed into a local
                // and thrown away, so each subsequent declaration sees the
                // original parent -- still followed by the interstitial -- and
                // makes another copy, emitting one rule per declaration.
                //
                // `with_parent` reads `self.parent` *after* calling this, so
                // updating it here also gives the copy back to the enclosing
                // scope once a nested rule finishes.
                self.parent = Some(parent);
            }
        }

        self.css_tree.add_child(node, parent)
    }

    /// Adds `node` to the current parent, first moving to a copy of that
    /// parent if anything has been written after it.
    ///
    /// This is dart-sass's `_copyParentAfterSibling` followed by an add, for
    /// the nodes that hold their place in source order: declarations, loud
    /// comments, childless at-rules and nested imports. A nested rule written
    /// above one of them was added after the parent, so the node goes into a
    /// copy placed after that rule. Unlike [`Self::add_child`] with a
    /// `through`, an invisible sibling counts here too: dart-sass splits
    /// `.p {x: y; @media (b) {} z: w}` into two `.p` rules.
    ///
    /// Later nodes belong in the same copy, so it becomes the current parent;
    /// `with_parent` reads `self.parent` afterwards, which hands the copy back
    /// to the enclosing scope as well.
    fn add_child_after_sibling(&mut self, node: CssStmt) -> CssTreeIdx {
        if let Some(parent) = self.parent.filter(|&parent| parent != CssTree::ROOT)
            && !self.css_tree.is_last_child(parent)
        {
            let grandparent = self.css_tree.child_to_parent[&parent];
            let copy = self
                .css_tree
                .get(parent)
                .as_ref()
                .map(CssStmt::copy_without_children)
                .unwrap();
            self.parent = Some(self.css_tree.add_child(copy, grandparent));
        }

        self.css_tree.add_stmt(node, self.parent)
    }

    fn with_parent<F: FnOnce(&mut Self) -> SassResult<()>, FT: Fn(&CssStmt) -> bool>(
        &mut self,
        parent: CssStmt,
        // default=true
        scope_when: bool,
        callback: F,
        through: FT,
    ) -> SassResult<()> {
        self.with_parent_opt(parent, scope_when, callback, Some(through))
            .map(|_| ())
    }

    /// As `with_parent`, but `through` may be absent, in which case the node is
    /// added exactly where it was written instead of bubbling up past any
    /// ancestor the predicate accepts.
    fn with_parent_opt<F: FnOnce(&mut Self) -> SassResult<()>, FT: Fn(&CssStmt) -> bool>(
        &mut self,
        parent: CssStmt,
        // default=true
        scope_when: bool,
        callback: F,
        through: Option<FT>,
    ) -> SassResult<CssTreeIdx> {
        let parent_idx = self.add_child(parent, through);
        let old_parent = self.parent;
        self.parent = Some(parent_idx);
        let result = self.with_scope(false, scope_when, callback);
        self.parent = old_parent;
        result.map(|()| parent_idx)
    }

    fn with_scope<T, F: FnOnce(&mut Self) -> T>(
        &mut self,
        // default=false
        semi_global: bool,
        // default=true
        when: bool,
        callback: F,
    ) -> T {
        let semi_global = semi_global && self.flags.in_semi_global_scope();
        let was_in_semi_global_scope = self.flags.in_semi_global_scope();
        self.flags
            .set(ContextFlags::IN_SEMI_GLOBAL_SCOPE, semi_global);

        if !when {
            let v = callback(self);
            self.flags
                .set(ContextFlags::IN_SEMI_GLOBAL_SCOPE, was_in_semi_global_scope);

            return v;
        }

        self.env.scopes_mut().enter_new_scope();

        let v = callback(self);

        self.flags
            .set(ContextFlags::IN_SEMI_GLOBAL_SCOPE, was_in_semi_global_scope);
        self.env.scopes_mut().exit_scope();

        v
    }

    fn with_content<T>(
        &mut self,
        content: Option<Arc<CallableContentBlock>>,
        callback: impl FnOnce(&mut Self) -> T,
    ) -> T {
        let old_content = self.env.content.take();
        self.env.content = content;
        let v = callback(self);
        self.env.content = old_content;
        v
    }

    fn visit_include_stmt(&mut self, include_stmt: AstInclude) -> SassResult<Option<Value>> {
        let mixin = self
            .env
            .get_mixin(include_stmt.name, include_stmt.namespace)?;

        // The lookup comes first, so an undefined mixin still reports that
        // rather than the spelling. A builtin mixin cannot be named with `--`,
        // so only a user-defined one can reach this.
        if include_stmt.name_starts_with_dashes && matches!(mixin, Mixin::UserDefined(..)) {
            return Err((CSS_MIXIN_NAME_ERROR, include_stmt.name.span).into());
        }

        match mixin {
            Mixin::Builtin(mixin, _, accepts_content) => {
                if include_stmt.content.is_some() && !accepts_content {
                    return Err(("Mixin doesn't accept a content block.", include_stmt.span).into());
                }

                let args = self.eval_args(include_stmt.args, include_stmt.name.span)?;

                // `meta.apply` forwards the caller's content block to the mixin
                // it applies, so a builtin that accepts content needs it set
                // the same way a user-defined one does.
                let callable_content = include_stmt.content.map(|content| {
                    Arc::new(CallableContentBlock {
                        content,
                        env: self.env.new_closure(),
                    })
                });

                self.with_content(callable_content, |visitor| mixin(args, visitor))?;

                Ok(None)
            }
            Mixin::UserDefined(mixin, env) => {
                if include_stmt.content.is_some() && !mixin.has_content {
                    return Err(("Mixin doesn't accept a content block.", include_stmt.span).into());
                }

                let AstInclude { args, content, .. } = include_stmt;

                let old_in_mixin = self.flags.in_mixin();
                self.flags.set(ContextFlags::IN_MIXIN, true);

                let callable_content = content.map(|c| {
                    Arc::new(CallableContentBlock {
                        content: c,
                        env: self.env.new_closure(),
                    })
                });

                self.run_user_defined_callable::<_, (), _>(
                    MaybeEvaledArguments::Invocation(args),
                    mixin,
                    &env,
                    include_stmt.name.span,
                    |mixin, visitor| {
                        visitor.with_content(callable_content, |visitor| {
                            for stmt in mixin.body.iter().cloned() {
                                let result = visitor.visit_stmt(stmt)?;
                                debug_assert!(result.is_none());
                            }
                            Ok(())
                        })
                    },
                )?;

                self.flags.set(ContextFlags::IN_MIXIN, old_in_mixin);

                Ok(None)
            }
        }
    }

    /// Includes a first-class mixin with already-evaluated arguments.
    ///
    /// This is the body of `meta.apply`. The `@content` block currently in
    /// scope is the one `apply` itself was given, and it is forwarded to the
    /// mixin being applied.
    pub(crate) fn apply_mixin(
        &mut self,
        mixin: Mixin,
        args: ArgumentResult,
        span: Span,
    ) -> SassResult<()> {
        match mixin {
            Mixin::Builtin(mixin, ..) => mixin(args, self),
            Mixin::UserDefined(mixin, env) => {
                let content = self.env.content.as_ref().map(Arc::clone);

                if content.is_some() && !mixin.has_content {
                    return Err(("Mixin doesn't accept a content block.", span).into());
                }

                let old_in_mixin = self.flags.in_mixin();
                self.flags.set(ContextFlags::IN_MIXIN, true);

                let result = self.run_user_defined_callable::<_, (), _>(
                    MaybeEvaledArguments::Evaled(args),
                    mixin,
                    &env,
                    span,
                    |mixin, visitor| {
                        visitor.with_content(content, |visitor| {
                            for stmt in mixin.body.iter().cloned() {
                                let result = visitor.visit_stmt(stmt)?;
                                debug_assert!(result.is_none());
                            }
                            Ok(())
                        })
                    },
                );

                self.flags.set(ContextFlags::IN_MIXIN, old_in_mixin);

                result
            }
        }
    }

    fn visit_mixin_decl(&mut self, mixin: AstMixin) {
        self.env.insert_mixin(
            mixin.name,
            Mixin::UserDefined(Arc::new(mixin), self.env.new_closure()),
        );
    }

    fn visit_each_stmt(&mut self, each_stmt: AstEach) -> SassResult<Option<Value>> {
        let list = self.visit_expr(each_stmt.list)?.as_list();

        // todo: not setting semi_global: true maybe means we can't assign to global scope when declared as global
        self.env.scopes_mut().enter_new_scope();

        let mut result = None;

        'outer: for val in list {
            if each_stmt.variables.len() == 1 {
                let val = self.without_slash(val);
                self.env
                    .scopes_mut()
                    .insert_var_last(each_stmt.variables[0], val);
            } else {
                for (&var, val) in each_stmt.variables.iter().zip(
                    val.as_list()
                        .into_iter()
                        .chain(std::iter::once(Value::Null).cycle()),
                ) {
                    let val = self.without_slash(val);
                    self.env.scopes_mut().insert_var_last(var, val);
                }
            }

            for stmt in each_stmt.body.clone() {
                let val = self.visit_stmt(stmt)?;
                if val.is_some() {
                    result = val;
                    break 'outer;
                }
            }
        }

        self.env.scopes_mut().exit_scope();

        Ok(result)
    }

    fn visit_for_stmt(&mut self, for_stmt: AstFor) -> SassResult<Option<Value>> {
        let from_span = for_stmt.from.span;
        let to_span = for_stmt.to.span;
        let from_number = self
            .visit_expr(for_stmt.from.node)?
            .assert_number(from_span)?;
        let to_number = self.visit_expr(for_stmt.to.node)?.assert_number(to_span)?;

        if !to_number.unit().comparable(from_number.unit()) {
            // todo: better error message here
            return Err((
                "to and from values have incompatible units",
                from_span.merge(to_span),
            )
                .into());
        }

        let from = from_number.num.assert_int(from_span)?;
        let mut to = to_number
            .num
            .convert(to_number.unit(), from_number.unit())
            .assert_int(to_span)?;

        let direction = if from > to { -1 } else { 1 };

        if to == i64::MAX || to == i64::MIN {
            return Err((
                "@for loop upper bound exceeds valid integer representation (i64::MAX)",
                to_span,
            )
                .into());
        }

        if !for_stmt.is_exclusive {
            to += direction;
        }

        if from == to {
            return Ok(None);
        }

        // todo: self.with_scopes
        self.env.scopes_mut().enter_new_scope();

        let mut result = None;

        let mut i = from;
        'outer: while i != to {
            self.env.scopes_mut().insert_var_last(
                for_stmt.variable.node,
                Value::Dimension(SassNumber {
                    num: Number::from(i),
                    unit: from_number.unit().clone(),
                    as_slash: None,
                }),
            );

            for stmt in for_stmt.body.clone() {
                let val = self.visit_stmt(stmt)?;
                if val.is_some() {
                    result = val;
                    break 'outer;
                }
            }

            i += direction;
        }

        self.env.scopes_mut().exit_scope();

        Ok(result)
    }

    fn visit_while_stmt(&mut self, while_stmt: &AstWhile) -> SassResult<Option<Value>> {
        self.with_scope(true, true, |visitor| {
            let mut result = None;

            'outer: while visitor
                .visit_expr(while_stmt.condition.clone())?
                .is_truthy()
            {
                for stmt in while_stmt.body.clone() {
                    let val = visitor.visit_stmt(stmt)?;
                    if val.is_some() {
                        result = val;
                        break 'outer;
                    }
                }
            }

            Ok(result)
        })
    }

    fn visit_if_stmt(&mut self, if_stmt: AstIf) -> SassResult<Option<Value>> {
        let mut clause: Option<Vec<AstStmt>> = if_stmt.else_clause;
        for clause_to_check in if_stmt.if_clauses {
            if self.visit_expr(clause_to_check.condition)?.is_truthy() {
                clause = Some(clause_to_check.body);
                break;
            }
        }

        // todo: self.with_scope
        self.env.scopes_mut().enter_new_scope();

        let mut result = None;

        if let Some(stmts) = clause {
            for stmt in stmts {
                let val = self.visit_stmt(stmt)?;
                if val.is_some() {
                    result = val;
                    break;
                }
            }
        }

        self.env.scopes_mut().exit_scope();

        Ok(result)
    }

    fn visit_loud_comment(&mut self, comment: AstLoudComment) -> SassResult<Option<Value>> {
        if self.flags.in_function() {
            return Ok(None);
        }

        // Comments are allowed to appear between CSS imports, so one written
        // while the `@import` block is still open belongs to it. Without
        // this, a comment above an import would be left behind when a later
        // import moved back into the block.
        if (self.parent.is_none() || self.parent == Some(CssTree::ROOT))
            && self.end_of_imports == self.css_tree.root_child_count()
        {
            self.end_of_imports += 1;
        }

        let comment = CssStmt::Comment(
            self.perform_interpolation(comment.text, false)?,
            comment.span,
        );

        // Route through `add_child` for the same reason a style declaration
        // does (see `visit_style`): a loud comment holds its place in source
        // order, so a nested rule written between two of them splits the
        // enclosing rule rather than letting the second comment hoist back up
        // beside the first.
        self.add_child_after_sibling(comment);

        Ok(None)
    }

    fn visit_variable_decl(&mut self, decl: AstVariableDecl) -> SassResult<Option<Value>> {
        let name = Spanned {
            node: decl.name,
            span: decl.span,
        };

        if decl.is_guarded {
            if decl.namespace.is_none() && self.env.at_root() {
                self.env.mark_variable_configurable(decl.name);
                let var_override = (*self.configuration).borrow_mut().remove(decl.name);
                if !matches!(
                    var_override,
                    Some(ConfiguredValue {
                        value: Value::Null,
                        ..
                    }) | None
                ) {
                    self.env.insert_var(
                        name,
                        None,
                        var_override.unwrap().value,
                        true,
                        self.flags.in_semi_global_scope(),
                    )?;
                    return Ok(None);
                }
            }

            if self.env.var_exists(decl.name, decl.namespace)? {
                let value = self.env.get_var(name, decl.namespace).unwrap();

                if value != Value::Null {
                    return Ok(None);
                }
            }
        }

        let value = self.visit_expr(decl.value)?;
        let value = self.without_slash(value);

        self.env.insert_var(
            name,
            decl.namespace,
            value,
            decl.is_global,
            self.flags.in_semi_global_scope(),
        )?;

        Ok(None)
    }

    fn interpolation_to_value(
        &mut self,
        interpolation: Interpolation,
        // default=false
        trim: bool,
        // default=false
        warn_for_color: bool,
    ) -> SassResult<String> {
        let result = self.perform_interpolation(interpolation, warn_for_color)?;

        Ok(if trim {
            trim_ascii(&result, true).to_owned()
        } else {
            result
        })
    }

    fn perform_interpolation(
        &mut self,
        mut interpolation: Interpolation,
        // todo check to emit warning if this is true
        _warn_for_color: bool,
    ) -> SassResult<String> {
        let result = match interpolation.contents.len() {
            0 => String::new(),
            1 => match interpolation.contents.pop() {
                Some(InterpolationPart::String(s)) => s,
                Some(InterpolationPart::Expr(e)) => {
                    let span = e.span;
                    let result = self.visit_expr(e.node)?;
                    // todo: span for specific expr
                    self.serialize(result, QuoteKind::None, span)?
                }
                None => unreachable!(),
            },
            _ => interpolation
                .contents
                .into_iter()
                .map(|part| match part {
                    InterpolationPart::String(s) => Ok(s),
                    InterpolationPart::Expr(e) => {
                        let span = e.span;
                        let result = self.visit_expr(e.node)?;
                        // todo: span for specific expr
                        self.serialize(result, QuoteKind::None, span)
                    }
                })
                .collect::<SassResult<String>>()?,
        };

        Ok(result)
    }

    fn evaluate_to_css(
        &mut self,
        expr: AstExpr,
        quote: QuoteKind,
        span: Span,
    ) -> SassResult<String> {
        let result = self.visit_expr(expr)?;
        self.serialize(result, quote, span)
    }

    #[allow(clippy::unused_self)]
    fn without_slash(&mut self, v: Value) -> Value {
        match v {
            Value::Dimension(SassNumber { .. }) if v.as_slash().is_some() => {
                // todo: emit warning. we don't currently because it can be quite loud
                // self.emit_warning(
                //     Cow::Borrowed("Using / for division is deprecated and will be removed at some point in the future"),
                //     self.empty_span,
                // );
            }
            _ => {}
        }

        v.without_slash()
    }

    fn eval_maybe_args(
        &mut self,
        args: MaybeEvaledArguments,
        span: Span,
    ) -> SassResult<ArgumentResult> {
        match args {
            MaybeEvaledArguments::Invocation(args) => self.eval_args(args, span),
            MaybeEvaledArguments::Evaled(args) => Ok(args),
        }
    }

    fn eval_args(
        &mut self,
        arguments: ArgumentInvocation,
        span: Span,
    ) -> SassResult<ArgumentResult> {
        let mut positional = Vec::with_capacity(arguments.positional.len());

        for expr in arguments.positional {
            let val = self.visit_expr(expr)?;
            positional.push(self.without_slash(val));
        }

        let mut named = BTreeMap::new();

        for (key, expr) in arguments.named {
            let val = self.visit_expr(expr)?;
            named.insert(key, self.without_slash(val));
        }

        if arguments.rest.is_none() {
            return Ok(ArgumentResult {
                positional,
                named,
                separator: ListSeparator::Undecided,
                span,
                touched: BTreeSet::new(),
                overload: 0,
            });
        }

        let rest = self.visit_expr(arguments.rest.unwrap())?;

        let mut separator = ListSeparator::Undecided;

        match rest {
            Value::Map(rest) => self.add_rest_map(&mut named, rest)?,
            Value::List(elems, list_separator, _) => {
                let mut list = elems
                    .into_iter()
                    .map(|e| self.without_slash(e))
                    .collect::<Vec<_>>();
                positional.append(&mut list);
                separator = list_separator;
            }
            Value::ArgList(arglist) => {
                // todo: superfluous clone
                for (&key, value) in arglist.keywords() {
                    named.insert(key, self.without_slash(value.clone()));
                }

                let mut list = arglist
                    .elems
                    .into_iter()
                    .map(|e| self.without_slash(e))
                    .collect::<Vec<_>>();
                positional.append(&mut list);
                separator = arglist.separator;
            }
            _ => {
                positional.push(self.without_slash(rest));
            }
        }

        if arguments.keyword_rest.is_none() {
            return Ok(ArgumentResult {
                positional,
                named,
                separator,
                span: arguments.span,
                touched: BTreeSet::new(),
                overload: 0,
            });
        }

        match self.visit_expr(arguments.keyword_rest.unwrap())? {
            Value::Map(keyword_rest) => {
                self.add_rest_map(&mut named, keyword_rest)?;

                Ok(ArgumentResult {
                    positional,
                    named,
                    separator,
                    span: arguments.span,
                    touched: BTreeSet::new(),
                    overload: 0,
                })
            }
            v => Err((
                format!(
                    "Variable keyword arguments must be a map (was {}).",
                    v.inspect(arguments.span)?
                ),
                arguments.span,
            )
                .into()),
        }
    }

    fn add_rest_map(
        &mut self,
        named: &mut BTreeMap<Identifier, Value>,
        rest: SassMap,
    ) -> SassResult<()> {
        for (key, val) in rest {
            match key.node {
                Value::String(text, ..) => {
                    let val = self.without_slash(val);
                    named.insert(Identifier::from(text), val);
                }
                _ => {
                    return Err((
                        // todo: we have to render the map for this error message
                        "Variable keyword argument map must have string keys.",
                        key.span,
                    )
                        .into());
                }
            }
        }

        Ok(())
    }

    fn run_user_defined_callable<
        F: UserDefinedCallable,
        V: fmt::Debug,
        R: FnOnce(F, &mut Self) -> SassResult<V>,
    >(
        &mut self,
        arguments: MaybeEvaledArguments,
        func: F,
        env: &Environment,
        span: Span,
        run: R,
    ) -> SassResult<V> {
        let mut evaluated = self.eval_maybe_args(arguments, span)?;

        let mut name = func.name().to_string();

        if name != "@content" {
            name.push_str("()");
        }

        self.with_environment(env.new_closure(), |visitor| {
            visitor.with_scope(false, true, move |visitor| {
                func.arguments().verify(
                    evaluated.positional.len(),
                    &evaluated.named,
                    evaluated.span,
                )?;

                let declared_arguments = &func.arguments().args;
                let min_len = evaluated.positional.len().min(declared_arguments.len());

                let positional_len = evaluated.positional.len();

                #[allow(clippy::needless_range_loop)]
                for i in (0..min_len).rev() {
                    visitor.env.scopes_mut().insert_var_last(
                        declared_arguments[i].name,
                        evaluated.positional.remove(i),
                    );
                }

                // todo: better name for var
                let additional_declared_args = if declared_arguments.len() > positional_len {
                    &declared_arguments[positional_len..declared_arguments.len()]
                } else {
                    &[]
                };

                for argument in additional_declared_args {
                    let name = argument.name;
                    let value = evaluated.named.remove(&argument.name).map_or_else(
                        || {
                            // todo: superfluous clone
                            let v = visitor.visit_expr(argument.default.clone().unwrap())?;
                            Ok(visitor.without_slash(v))
                        },
                        SassResult::Ok,
                    )?;
                    visitor.env.scopes_mut().insert_var_last(name, value);
                }

                let were_keywords_accessed = Rc::new(Cell::new(false));

                let num_named_args = evaluated.named.len();

                let has_arg_list = if let Some(rest_arg) = func.arguments().rest {
                    let rest = if !evaluated.positional.is_empty() {
                        evaluated.positional
                    } else {
                        Vec::new()
                    };

                    // The arglist takes the separator of the list that was
                    // splatted into it, so `foo(1, 2, (3 4 5)...)` gives
                    // `$b: 2 3 4 5` rather than `2, 3, 4, 5`. A call with no
                    // splat, or one whose splatted value has no separator of
                    // its own, leaves it undecided and falls back to a comma.
                    let arg_list = Value::ArgList(ArgList::new(
                        rest,
                        Rc::clone(&were_keywords_accessed),
                        // todo: superfluous clone
                        evaluated.named.clone(),
                        if evaluated.separator == ListSeparator::Undecided {
                            ListSeparator::Comma
                        } else {
                            evaluated.separator
                        },
                    ));

                    visitor.env.scopes_mut().insert_var_last(rest_arg, arg_list);

                    true
                } else {
                    false
                };

                let val = run(func, visitor)?;

                if !has_arg_list || num_named_args == 0 {
                    return Ok(val);
                }

                if (*were_keywords_accessed).get() {
                    return Ok(val);
                }

                // dart-sass's wording: the names match no *parameter*.
                let parameter_word = if num_named_args == 1 {
                    "parameter"
                } else {
                    "parameters"
                };

                let argument_names = to_sentence(
                    evaluated
                        .named
                        .keys()
                        .map(|key| format!("${key}", key = key))
                        .collect(),
                    "or",
                );

                Err((format!("No {parameter_word} named {argument_names}."), span).into())
            })
        })
    }

    /// Checks `arguments` against the parameter lists of a builtin and binds
    /// its named arguments to their positions.
    ///
    /// This is dart-sass 1.103.1's `_runBuiltInCallable` up to the call. The
    /// first overload the call matches is used, otherwise the one closest in
    /// number of parameters (`BuiltInCallable.callbackFor`). That overload's
    /// `verify` then raises the error for a call that fits none: an unknown
    /// named argument, a missing one, one passed twice, or too many.
    fn bind_builtin_arguments(
        &mut self,
        signatures: &'static [&'static str],
        arguments: &mut ArgumentResult,
        span: Span,
    ) -> SassResult<()> {
        let overloads = self.builtin_parameter_lists(signatures, span)?;
        let positional = arguments.positional.len();

        let mut chosen = None;
        let mut fuzzy = None;
        let mut min_distance: Option<isize> = None;
        for (index, overload) in overloads.iter().enumerate() {
            if overload.matches(positional, &arguments.named) {
                chosen = Some((index, overload));
                break;
            }

            let distance = overload.args.len() as isize - positional as isize;
            if let Some(min) = min_distance {
                if distance.abs() > min.abs() {
                    continue;
                }
                // At equal distance, favour the overload with more parameters.
                if distance.abs() == min.abs() && distance < 0 {
                    continue;
                }
            }
            min_distance = Some(distance);
            fuzzy = Some((index, overload));
        }

        let (index, overload) = chosen
            .or(fuzzy)
            .expect("every builtin signature has at least one parameter list");
        overload.verify(positional, &arguments.named, span)?;
        arguments.bind_to(overload);
        arguments.overload = index;

        Ok(())
    }

    /// The parameter lists in `signatures`, parsed once per thread.
    ///
    /// The lists are `'static`, so the slice's address identifies them.
    fn builtin_parameter_lists(
        &self,
        signatures: &'static [&'static str],
        span: Span,
    ) -> SassResult<std::rc::Rc<[crate::ast::ArgumentDeclaration]>> {
        use std::{cell::RefCell, collections::HashMap, path::Path, rc::Rc};

        use crate::{ast::ArgumentDeclaration, lexer::Lexer, parse::StylesheetParser};

        thread_local! {
            static PARSED: RefCell<HashMap<usize, Rc<[ArgumentDeclaration]>>> =
                RefCell::new(HashMap::new());
        }

        let key = signatures.as_ptr() as usize;
        if let Some(parsed) = PARSED.with(|parsed| parsed.borrow().get(&key).cloned()) {
            return Ok(parsed);
        }

        let parsed = signatures
            .iter()
            .map(|signature| {
                let text = format!("({signature})");
                let lexer = Lexer::new_from_string(&text, span);
                ScssParser::new(lexer, self.options, span, Path::new(""))
                    .parse_argument_declaration()
            })
            .collect::<SassResult<Rc<[ArgumentDeclaration]>>>()?;

        PARSED.with(|cache| cache.borrow_mut().insert(key, Rc::clone(&parsed)));

        Ok(parsed)
    }

    pub(crate) fn run_function_callable(
        &mut self,
        func: SassFunction,
        arguments: ArgumentInvocation,
        span: Span,
    ) -> SassResult<Value> {
        self.run_function_callable_with_maybe_evaled(
            func,
            MaybeEvaledArguments::Invocation(arguments),
            span,
        )
    }

    pub(crate) fn run_function_callable_with_maybe_evaled(
        &mut self,
        func: SassFunction,
        arguments: MaybeEvaledArguments,
        span: Span,
    ) -> SassResult<Value> {
        match func {
            SassFunction::Builtin(func, _name) => {
                let mut evaluated = self.eval_maybe_args(arguments, span)?;
                if let Some(signatures) = func.2 {
                    self.bind_builtin_arguments(signatures, &mut evaluated, span)?;
                }
                let val = func.0(evaluated, self)?;
                Ok(self.without_slash(val))
            }
            SassFunction::UserDefined(UserDefinedFunction { function, env, .. }) => self
                .run_user_defined_callable(arguments, function, &env, span, |function, visitor| {
                    for stmt in function.body.clone() {
                        let result = visitor.visit_stmt(stmt)?;

                        if let Some(val) = result {
                            return Ok(val);
                        }
                    }

                    Err(("Function finished without @return.", span).into())
                }),
            SassFunction::Plain { name } => {
                let has_named;
                let mut rest = None;

                // todo: somewhat hacky solution to support plain css fns passed
                // as strings to `call(..)`
                let arguments = match arguments {
                    MaybeEvaledArguments::Invocation(args) => {
                        has_named = !args.named.is_empty() || args.keyword_rest.is_some();
                        rest = args.rest;
                        args.positional
                            .into_iter()
                            .map(|arg| self.evaluate_to_css(arg, QuoteKind::Quoted, span))
                            .collect::<SassResult<Vec<_>>>()?
                    }
                    MaybeEvaledArguments::Evaled(args) => {
                        has_named = !args.named.is_empty();

                        args.positional
                            .into_iter()
                            .map(|arg| arg.to_css_string(span, self.options.is_compressed()))
                            .collect::<SassResult<Vec<_>>>()?
                    }
                };

                if has_named {
                    return Err(
                        ("Plain CSS functions don't support keyword arguments.", span).into(),
                    );
                }

                let mut buffer = format!("{}(", name.as_str());
                let mut first = true;

                for argument in arguments {
                    if first {
                        first = false;
                    } else {
                        buffer.push_str(", ");
                    }

                    buffer.push_str(&argument);
                }

                if let Some(rest_arg) = rest {
                    let rest = self.visit_expr(rest_arg)?;
                    if !first {
                        buffer.push_str(", ");
                    }
                    buffer.push_str(&self.serialize(rest, QuoteKind::Quoted, span)?);
                }
                buffer.push(')');

                Ok(Value::String(buffer, QuoteKind::None))
            }
        }
    }

    fn visit_list_expr(&mut self, list: ListExpr) -> SassResult<Value> {
        let elems = list
            .elems
            .into_iter()
            .map(|e| {
                let value = self.visit_expr(e.node)?;
                Ok(value)
            })
            .collect::<SassResult<Vec<_>>>()?;

        Ok(Value::List(elems, list.separator, list.brackets))
    }

    fn visit_function_call_expr(&mut self, func_call: FunctionCallExpr) -> SassResult<Value> {
        let name = func_call.name;

        // A `--`-prefixed name belongs to a plain CSS custom function, so it is
        // never looked up among Sass functions even though `Identifier`
        // normalisation would otherwise make `--a()` reach `@function __a()`.
        let declared = if func_call.is_custom_function {
            None
        } else {
            self.env.get_fn(name, func_call.namespace, func_call.span)?
        };

        let func = match declared {
            Some(func) => func,
            None => {
                // A namespaced call names a member of that module and nothing
                // else, so `selector.selector-append()` is undefined even
                // though `selector-append()` is a global function.
                if func_call.namespace.is_some() {
                    return Err(("Undefined function.", func_call.span).into());
                }

                if let Some(f) = self.options.custom_fns.get(name.as_str()) {
                    SassFunction::Builtin(f.clone(), name)
                } else if let Some(f) = GLOBAL_FUNCTIONS.get(name.as_str()) {
                    SassFunction::Builtin(f.clone(), name)
                } else {
                    if func_call.namespace.is_some() {
                        return Err(("Undefined function.", func_call.span).into());
                    }

                    // A CSS math function only reaches this point when its
                    // arguments were not calculation syntax and no function of
                    // that name is defined, so there is nothing left to do
                    // with it. Which message it gets depends on what in the
                    // arguments a calculation cannot hold.
                    if CalculationName::from_lowercase_str(&name.as_str().to_ascii_lowercase())
                        .is_some()
                    {
                        let (message, span) =
                            calculation_argument_error(&func_call.arguments, func_call.span);
                        return Err((message, span).into());
                    }

                    SassFunction::Plain {
                        name: func_call.original_name.clone(),
                    }
                }
            }
        };

        let old_in_function = self.flags.in_function();
        self.flags.set(ContextFlags::IN_FUNCTION, true);
        let value =
            self.run_function_callable(func, (*func_call.arguments).clone(), func_call.span)?;
        self.flags.set(ContextFlags::IN_FUNCTION, old_in_function);

        Ok(value)
    }

    fn visit_interpolated_func_expr(&mut self, func: InterpolatedFunction) -> SassResult<Value> {
        let InterpolatedFunction {
            name,
            arguments: args,
            span,
        } = func;
        let fn_name = self.perform_interpolation(name, false)?;

        if !args.named.is_empty() || args.keyword_rest.is_some() {
            return Err(("Plain CSS functions don't support keyword arguments.", span).into());
        }

        let mut buffer = format!("{}(", fn_name);

        let mut first = true;
        for arg in args.positional.clone() {
            if first {
                first = false;
            } else {
                buffer.push_str(", ");
            }
            let evaluated = self.evaluate_to_css(arg, QuoteKind::Quoted, span)?;
            buffer.push_str(&evaluated);
        }

        if let Some(rest_arg) = args.rest {
            let rest = self.visit_expr(rest_arg)?;
            if !first {
                buffer.push_str(", ");
            }
            buffer.push_str(&self.serialize(rest, QuoteKind::None, span)?);
        }

        buffer.push(')');

        Ok(Value::String(buffer, QuoteKind::None))
    }

    /// `&` in SassScript: the enclosing style rule's selector before
    /// `@extend` added to it, as dart-sass's `visitSelectorExpression` reads
    /// `originalSelector`.
    fn visit_parent_selector(&self) -> Value {
        match &self.style_rule_original_selector {
            Some(selector) => selector.clone().to_sass_list(),
            None => Value::Null,
        }
    }

    fn visit_expr(&mut self, expr: AstExpr) -> SassResult<Value> {
        Ok(match expr {
            AstExpr::Color(color) => Value::Color(color),
            AstExpr::Number { n, unit } => Value::Dimension(SassNumber {
                num: n,
                unit,
                as_slash: None,
            }),
            AstExpr::List(list) => self.visit_list_expr(list)?,
            AstExpr::String(StringExpr(text, quote), ..) => self.visit_string(text, quote)?,
            AstExpr::BinaryOp(binop) => self.visit_bin_op(
                binop.lhs.clone(),
                binop.op,
                binop.rhs.clone(),
                binop.allows_slash,
                binop.span,
            )?,
            AstExpr::True => Value::True,
            AstExpr::False => Value::False,
            AstExpr::Calculation { name, args } => {
                self.visit_calculation_expr(name, args, self.empty_span)?
            }
            AstExpr::FunctionCall(func_call) => self.visit_function_call_expr(func_call)?,
            AstExpr::If(if_expr) => self.visit_ternary((*if_expr).clone())?,
            AstExpr::CssIf(if_expr) => self.visit_css_if(&if_expr)?,
            AstExpr::InterpolatedFunction(func) => {
                self.visit_interpolated_func_expr((*func).clone())?
            }
            AstExpr::Map(map) => self.visit_map(map)?,
            AstExpr::Null => Value::Null,
            AstExpr::Paren(expr) => self.visit_expr((*expr).clone())?,
            AstExpr::ParentSelector => self.visit_parent_selector(),
            AstExpr::UnaryOp(op, expr, span) => self.visit_unary_op(op, (*expr).clone(), span)?,
            AstExpr::Variable { name, namespace } => self.env.get_var(name, namespace)?,
            AstExpr::Supports(condition) => Value::String(
                self.visit_supports_condition((*condition).clone())?,
                QuoteKind::None,
            ),
        })
    }

    /// Evaluates a CSS `if()`.
    ///
    /// Branches are walked in order and stop at the first one that is decided:
    /// a condition Sass can settle either selects the branch or drops it. The
    /// first condition Sass cannot settle turns the whole expression into CSS
    /// text -- that branch and every one after it, with conditions simplified
    /// as far as they go and values evaluated. With nothing left and no
    /// `else`, the result is null and the declaration is elided.
    fn visit_css_if(&mut self, if_expr: &CssIfExpr) -> SassResult<Value> {
        let span = self.empty_span;

        for (idx, branch) in if_expr.branches.iter().enumerate() {
            match self.simplify_css_if_condition(&branch.condition)? {
                CssIfDecision::Known(true) => return self.visit_expr(branch.value.clone()),
                CssIfDecision::Known(false) => continue,
                CssIfDecision::Unknown(condition) => {
                    return self.emit_css_if(if_expr, idx, condition, span);
                }
            }
        }

        Ok(Value::Null)
    }

    /// Renders an `if()` the browser has to resolve, starting at the branch
    /// whose condition could not be decided.
    fn emit_css_if(
        &mut self,
        if_expr: &CssIfExpr,
        first: usize,
        first_condition: String,
        span: Span,
    ) -> SassResult<Value> {
        let mut branches = vec![(
            first_condition,
            self.evaluate_to_css(
                if_expr.branches[first].value.clone(),
                QuoteKind::Quoted,
                span,
            )?,
        )];

        for branch in &if_expr.branches[first + 1..] {
            let condition = match self.simplify_css_if_condition(&branch.condition)? {
                // A branch that can never match adds nothing to the output.
                CssIfDecision::Known(false) => continue,
                // One that always matches is the last one worth emitting, and
                // `else` is how CSS spells it.
                CssIfDecision::Known(true) => "else".to_owned(),
                CssIfDecision::Unknown(condition) => condition,
            };

            let is_else = condition == "else";

            branches.push((
                condition,
                self.evaluate_to_css(branch.value.clone(), QuoteKind::Quoted, span)?,
            ));

            if is_else {
                break;
            }
        }

        let rendered = branches
            .into_iter()
            .map(|(condition, value)| format!("{}: {}", condition, value))
            .collect::<Vec<_>>()
            .join("; ");

        Ok(Value::String(format!("if({})", rendered), QuoteKind::None))
    }

    /// Decides a condition as far as Sass can.
    ///
    /// `and` and `or` are lazy: once an operand settles the result, the rest
    /// are neither evaluated nor interpolated, so an undefined variable in a
    /// branch that cannot be reached is not an error.
    fn simplify_css_if_condition(
        &mut self,
        condition: &CssIfCondition,
    ) -> SassResult<CssIfDecision> {
        Ok(match condition {
            CssIfCondition::Else => CssIfDecision::Known(true),
            CssIfCondition::Sass(expr) => {
                CssIfDecision::Known(self.visit_expr((**expr).clone())?.is_truthy())
            }
            CssIfCondition::Raw(interpolation) => CssIfDecision::Unknown(
                self.perform_interpolation((**interpolation).clone(), false)?,
            ),
            CssIfCondition::Paren(inner) => match self.simplify_css_if_condition(inner)? {
                CssIfDecision::Known(known) => CssIfDecision::Known(known),
                CssIfDecision::Unknown(text) => CssIfDecision::Unknown(format!("({})", text)),
            },
            CssIfCondition::Not(inner) => match self.simplify_css_if_condition(inner)? {
                CssIfDecision::Known(known) => CssIfDecision::Known(!known),
                CssIfDecision::Unknown(text) => CssIfDecision::Unknown(format!("not {}", text)),
            },
            CssIfCondition::And(operands) => self.simplify_css_if_chain(operands, false, "and")?,
            CssIfCondition::Or(operands) => self.simplify_css_if_chain(operands, true, "or")?,
        })
    }

    /// Simplifies an `and` or `or` chain.
    ///
    /// `short_circuit` is the operand value that settles the chain on its own:
    /// `false` for `and`, `true` for `or`. Operands with the opposite value
    /// contribute nothing and are dropped.
    fn simplify_css_if_chain(
        &mut self,
        operands: &[CssIfCondition],
        short_circuit: bool,
        operator: &str,
    ) -> SassResult<CssIfDecision> {
        let mut remaining: Vec<(&CssIfCondition, String)> = Vec::new();

        for operand in operands {
            match self.simplify_css_if_condition(operand)? {
                CssIfDecision::Known(known) if known == short_circuit => {
                    return Ok(CssIfDecision::Known(short_circuit));
                }
                CssIfDecision::Known(..) => continue,
                CssIfDecision::Unknown(text) => remaining.push((operand, text)),
            }
        }

        Ok(match remaining.len() {
            0 => CssIfDecision::Known(!short_circuit),
            // The chain is gone, so the parentheses that only separated it from
            // its neighbours go with it.
            1 => {
                let (operand, text) = remaining.remove(0);

                CssIfDecision::Unknown(match operand {
                    CssIfCondition::Paren(..) => text[1..text.len() - 1].to_owned(),
                    _ => text,
                })
            }
            _ => CssIfDecision::Unknown(
                remaining
                    .into_iter()
                    .map(|(_, text)| text)
                    .collect::<Vec<_>>()
                    .join(&format!(" {} ", operator)),
            ),
        })
    }

    fn visit_calculation_value(
        &mut self,
        expr: AstExpr,
        in_min_or_max: bool,
        span: Span,
    ) -> SassResult<CalculationArg> {
        Ok(match expr {
            // Parentheses around opaque text are kept, because only the
            // browser can tell whether they matter: `calc((var(--c)))` stays
            // `calc((var(--c)))`. Around anything Sass can resolve they are
            // redundant and dropped.
            AstExpr::Paren(inner) => {
                match self.visit_calculation_value((*inner).clone(), in_min_or_max, span)? {
                    CalculationArg::String(text) => CalculationArg::String(format!("({})", text)),
                    CalculationArg::Interpolation(text) => {
                        CalculationArg::Interpolation(format!("({})", text))
                    }
                    // A space-separated list keeps its parentheses as
                    // structure rather than as text. They are not part of any
                    // operand, and position alone cannot recover them:
                    // dropping them flattens `calc(1 (2 var(--c)) 3)` into
                    // `calc(1 2 var(--c) 3)`, which this compiler then
                    // rejects for the neighbouring `1 2`.
                    result @ (CalculationArg::Space(..) | CalculationArg::Paren(..)) => {
                        CalculationArg::Paren(Box::new(result))
                    }
                    result => result,
                }
            }
            // A space-separated list only reaches here from calculation
            // adjacency (`calc(var(--c) 1)`); it is emitted verbatim.
            AstExpr::List(list)
                if list.brackets == Brackets::None && list.separator == ListSeparator::Space =>
            {
                let args = list
                    .elems
                    .iter()
                    .map(|elem| {
                        self.visit_calculation_value(elem.node.clone(), in_min_or_max, span)
                    })
                    .collect::<SassResult<Vec<_>>>()?;

                // Adjacency is only meaningful where an opaque value sits on
                // one side of it, so every neighbouring pair is checked:
                // `calc(c 1 2)` is an error even though it has opaque text.
                // The test is on the neighbour itself, not on what it holds,
                // which is why `calc(1 px + 2px)` is an error while
                // `calc(#{$a} px + 2px)` is not.
                if args
                    .windows(2)
                    .any(|pair| !pair.iter().any(is_opaque_value))
                {
                    return Err(("Missing math operator.", span).into());
                }

                CalculationArg::Space(args)
            }
            AstExpr::String(string_expr, _span) => {
                debug_assert!(string_expr.1 == QuoteKind::None);
                CalculationArg::Interpolation(self.perform_interpolation(string_expr.0, false)?)
            }
            AstExpr::BinaryOp(binop) => SassCalculation::operate_internal(
                binop.op,
                self.visit_calculation_value(binop.lhs.clone(), in_min_or_max, span)?,
                self.visit_calculation_value(binop.rhs.clone(), in_min_or_max, span)?,
                in_min_or_max,
                !self.flags.in_supports_declaration(),
                self.options,
                span,
            )?,
            AstExpr::Number { .. }
            | AstExpr::Calculation { .. }
            | AstExpr::Variable { .. }
            | AstExpr::FunctionCall { .. }
            | AstExpr::If(..) => {
                let result = self.visit_expr(expr)?;
                match result {
                    Value::Dimension(SassNumber {
                        num,
                        unit,
                        as_slash,
                    }) => CalculationArg::Number(SassNumber {
                        num,
                        unit,
                        as_slash,
                    }),
                    Value::Calculation(calc) => CalculationArg::Calculation(calc),
                    Value::String(s, QuoteKind::None) => CalculationArg::String(s),
                    value => {
                        let inspected = value.inspect(span)?;
                        // dart-sass parenthesises a bare list in this message
                        // and nowhere else: `$a: 1 2 3` gives `Value (1 2 3)`
                        // while `$a: [1 2 3]` keeps its brackets, so the
                        // reader can see where the value ends. A one-element
                        // comma list is the exception, and only because
                        // `inspect` already prints it as `(1,)`; a one-element
                        // space list is not, and `list.append((), 1px)` gives
                        // `Value (1px)`. Checked against 1.103.1 for space and
                        // comma lists of one and of several elements,
                        // bracketed lists, `()`, `(1,)`, maps and scalars.
                        let named = match &value {
                            Value::List(elems, separator, Brackets::None)
                                if match elems.len() {
                                    0 => false,
                                    1 => *separator != ListSeparator::Comma,
                                    _ => true,
                                } =>
                            {
                                format!("({})", inspected)
                            }
                            _ => inspected.to_string(),
                        };

                        return Err((
                            format!("Value {} can't be used in a calculation.", named),
                            span,
                        )
                            .into());
                    }
                }
            }
            v => unreachable!("{:?}", v),
        })
    }

    fn visit_calculation_expr(
        &mut self,
        name: CalculationName,
        args: Vec<AstExpr>,
        span: Span,
    ) -> SassResult<Value> {
        // A user-defined function shadows the CSS math function of the same
        // name, so `@function sin($x)` wins over `sin()` the calculation.
        let shadowing = self
            .env
            .get_fn(Identifier::from(name.as_str()), None, span)?;

        if let Some(func) = shadowing {
            let arguments = ArgumentInvocation {
                positional: args,
                named: BTreeMap::new(),
                rest: None,
                keyword_rest: None,
                span,
            };

            let old_in_function = self.flags.in_function();
            self.flags.set(ContextFlags::IN_FUNCTION, true);
            let value = self.run_function_callable(func, arguments, span)?;
            self.flags.set(ContextFlags::IN_FUNCTION, old_in_function);

            return Ok(value);
        }

        // `min`, `max`, `round` and `abs` are also Sass functions. An argument a
        // calculation cannot express -- a unitless number added to a length,
        // say -- is still valid for the Sass function, so those four keep a
        // copy of their arguments and retry as a plain call. Only a failure to
        // build the arguments falls back; once they are built, the calculation
        // owns the result and its errors.
        let fallback = if name.falls_back_to_function() && name.function_accepts_arity(args.len()) {
            Some(args.clone())
        } else {
            None
        };

        let evaluated = args
            .into_iter()
            .map(|arg| self.visit_calculation_value(arg, name.in_min_or_max(), span))
            .collect::<SassResult<Vec<_>>>();

        let mut args = match (evaluated, &fallback) {
            (Ok(args), _) => args,
            (Err(err), None) => return Err(err),
            (Err(err), Some(fallback)) => {
                return self.call_sass_function_fallback(name, fallback.clone(), span, err);
            }
        };

        if self.flags.in_supports_declaration() {
            return Ok(Value::Calculation(SassCalculation::unsimplified(
                name, args,
            )));
        }

        if args.is_empty() && name != CalculationName::Calc {
            return Err(("Missing argument.", span).into());
        }

        match name {
            CalculationName::Calc => {
                if args.is_empty() {
                    return Err(("Missing argument.", span).into());
                }

                if args.len() > 1 {
                    return Err((
                        format!("Only 1 argument allowed, but {} were passed.", args.len()),
                        span,
                    )
                        .into());
                }

                Ok(SassCalculation::calc(args.remove(0)))
            }
            CalculationName::Min => SassCalculation::min(args, self.options, span),
            CalculationName::Max => SassCalculation::max(args, self.options, span),
            CalculationName::Clamp => {
                if args.len() > 3 {
                    return Err((
                        format!("Only 3 arguments allowed, but {} were passed.", args.len()),
                        span,
                    )
                        .into());
                }

                let min = args.remove(0);
                let value = if args.is_empty() {
                    None
                } else {
                    Some(args.remove(0))
                };
                let max = if args.is_empty() {
                    None
                } else {
                    Some(args.remove(0))
                };
                SassCalculation::clamp(min, value, max, self.options, span)
            }
            CalculationName::Round => SassCalculation::round(args, self.options, span),
            CalculationName::Abs => SassCalculation::abs(args, self.options, span),
            CalculationName::Sign => SassCalculation::sign(args, self.options, span),
            CalculationName::Sqrt | CalculationName::Exp => {
                SassCalculation::unitless_unary(name, args, self.options, span)
            }
            CalculationName::Sin | CalculationName::Cos | CalculationName::Tan => {
                SassCalculation::trig(name, args, self.options, span)
            }
            CalculationName::Asin | CalculationName::Acos | CalculationName::Atan => {
                SassCalculation::inverse_trig(name, args, self.options, span)
            }
            CalculationName::Atan2 => SassCalculation::atan2(args, self.options, span),
            CalculationName::Pow | CalculationName::Log => {
                SassCalculation::unitless_binary(name, args, self.options, span)
            }
            CalculationName::Mod | CalculationName::Rem => {
                SassCalculation::modulo(name, args, self.options, span)
            }
            CalculationName::Hypot => SassCalculation::hypot(args, self.options, span),
            CalculationName::CalcSize => SassCalculation::calc_size(args, self.options, span),
        }
    }

    /// Re-runs a failed calculation as the Sass function of the same name.
    ///
    /// Returns the original calculation error if no such function exists, so a
    /// genuine mistake still reports the calculation's own message.
    fn call_sass_function_fallback(
        &mut self,
        name: CalculationName,
        args: Vec<AstExpr>,
        span: Span,
        original: Box<SassError>,
    ) -> SassResult<Value> {
        if GLOBAL_FUNCTIONS.get(name.as_str()).is_none() {
            return Err(original);
        }

        let func_call = FunctionCallExpr {
            namespace: None,
            name: Identifier::from(name.as_str()),
            original_name: name.as_str().to_owned(),
            arguments: Arc::new(ArgumentInvocation {
                positional: args,
                named: BTreeMap::new(),
                rest: None,
                keyword_rest: None,
                span,
            }),
            span,
            is_custom_function: false,
        };

        self.visit_function_call_expr(func_call)
    }

    fn visit_unary_op(&mut self, op: UnaryOp, expr: AstExpr, span: Span) -> SassResult<Value> {
        let operand = self.visit_expr(expr)?;

        match op {
            UnaryOp::Plus => operand.unary_plus(self, span),
            UnaryOp::Neg => operand.unary_neg(self, span),
            UnaryOp::Div => operand.unary_div(self, span),
            UnaryOp::Not => Ok(operand.unary_not()),
        }
    }

    fn visit_ternary(&mut self, if_expr: Ternary) -> SassResult<Value> {
        let span = if_expr.0.span;
        let (mut positional, mut named) = self.evaluate_macro_arguments(if_expr.0)?;

        if_arguments().verify(positional.len(), &named, span)?;

        let condition = if positional.is_empty() {
            named.remove(&Identifier::from("condition")).unwrap()
        } else {
            positional.remove(0)
        };

        let if_true = if positional.is_empty() {
            named.remove(&Identifier::from("if_true")).unwrap()
        } else {
            positional.remove(0)
        };

        let if_false = if positional.is_empty() {
            named.remove(&Identifier::from("if_false")).unwrap()
        } else {
            positional.remove(0)
        };

        let branch = if self.visit_macro_arg(condition)?.is_truthy() {
            if_true
        } else {
            if_false
        };

        let value = self.visit_macro_arg(branch)?;

        Ok(self.without_slash(value))
    }

    /// Evaluates one argument of a macro, which is a value already if it
    /// reached the call through a rest argument and an expression otherwise.
    fn visit_macro_arg(&mut self, arg: MacroArg) -> SassResult<Value> {
        match arg {
            MacroArg::Unevaled(expr) => self.visit_expr(expr),
            MacroArg::Evaled(value) => Ok(value),
        }
    }

    /// Evaluates `arguments` only as far as it takes to tell positional
    /// arguments from named ones, expanding a rest argument in place.
    ///
    /// `if()` is a macro: it evaluates only the branch it takes, so its
    /// arguments cannot go through [`Self::eval_args`], which evaluates every
    /// one of them. A rest argument must still be expanded before the call
    /// can be verified, because `if(true, b, c...)` supplies `$if-false`
    /// through `c...`, and counting the rest as a single positional argument
    /// rejects the call as missing one.
    ///
    /// Mirrors dart-sass's `_evaluateMacroArguments`. The values a rest
    /// argument contributes are already evaluated, so unlike the arguments
    /// written in the call they carry no laziness: splatting a list evaluates
    /// it, including the branch not taken.
    fn evaluate_macro_arguments(
        &mut self,
        arguments: ArgumentInvocation,
    ) -> SassResult<(Vec<MacroArg>, BTreeMap<Identifier, MacroArg>)> {
        let mut positional = arguments
            .positional
            .into_iter()
            .map(MacroArg::Unevaled)
            .collect::<Vec<_>>();

        let mut named = arguments
            .named
            .into_iter()
            .map(|(name, expr)| (name, MacroArg::Unevaled(expr)))
            .collect::<BTreeMap<_, _>>();

        let Some(rest) = arguments.rest else {
            return Ok((positional, named));
        };

        // `add_rest_map` fills a map of values, so the names a rest argument
        // contributes are collected separately and folded in at the end.
        let mut rest_named = BTreeMap::new();

        match self.visit_expr(rest)? {
            Value::Map(rest) => self.add_rest_map(&mut rest_named, rest)?,
            Value::List(elems, ..) => {
                for elem in elems {
                    let elem = self.without_slash(elem);
                    positional.push(MacroArg::Evaled(elem));
                }
            }
            Value::ArgList(arglist) => {
                // todo: superfluous clone
                for (&key, value) in arglist.keywords() {
                    let value = self.without_slash(value.clone());
                    rest_named.insert(key, value);
                }

                for elem in arglist.elems {
                    let elem = self.without_slash(elem);
                    positional.push(MacroArg::Evaled(elem));
                }
            }
            rest => {
                let rest = self.without_slash(rest);
                positional.push(MacroArg::Evaled(rest));
            }
        }

        if let Some(keyword_rest) = arguments.keyword_rest {
            match self.visit_expr(keyword_rest)? {
                Value::Map(keyword_rest) => self.add_rest_map(&mut rest_named, keyword_rest)?,
                v => {
                    return Err((
                        format!(
                            "Variable keyword arguments must be a map (was {}).",
                            v.inspect(arguments.span)?
                        ),
                        arguments.span,
                    )
                        .into());
                }
            }
        }

        named.extend(
            rest_named
                .into_iter()
                .map(|(name, value)| (name, MacroArg::Evaled(value))),
        );

        Ok((positional, named))
    }

    fn visit_string(&mut self, mut text: Interpolation, quote: QuoteKind) -> SassResult<Value> {
        // Don't use [performInterpolation] here because we need to get the raw text
        // from strings, rather than the semantic value.
        let old_in_supports_declaration = self.flags.in_supports_declaration();
        self.flags.set(ContextFlags::IN_SUPPORTS_DECLARATION, false);

        let result = match text.contents.len() {
            0 => String::new(),
            1 => match text.contents.pop() {
                Some(InterpolationPart::String(s)) => s,
                Some(InterpolationPart::Expr(Spanned { node, span })) => {
                    match self.visit_expr(node)? {
                        Value::String(s, ..) => s,
                        e => self.serialize(e, QuoteKind::None, span)?,
                    }
                }
                None => unreachable!(),
            },
            _ => text
                .contents
                .into_iter()
                .map(|part| match part {
                    InterpolationPart::String(s) => Ok(s),
                    InterpolationPart::Expr(Spanned { node, span }) => {
                        match self.visit_expr(node)? {
                            Value::String(s, ..) => Ok(s),
                            e => self.serialize(e, QuoteKind::None, span),
                        }
                    }
                })
                .collect::<SassResult<String>>()?,
        };

        self.flags.set(
            ContextFlags::IN_SUPPORTS_DECLARATION,
            old_in_supports_declaration,
        );

        Ok(Value::String(result, quote))
    }

    fn visit_map(&mut self, map: AstSassMap) -> SassResult<Value> {
        let mut sass_map = SassMap::new();

        for pair in map.0 {
            let key_span = pair.0.span;
            let key = self.visit_expr(pair.0.node)?;
            let value = self.visit_expr(pair.1)?;

            if sass_map.get_ref(&key).is_some() {
                return Err(("Duplicate key.", key_span).into());
            }

            sass_map.insert(
                Spanned {
                    node: key,
                    span: key_span,
                },
                value,
            );
        }

        Ok(Value::Map(sass_map))
    }

    fn visit_bin_op(
        &mut self,
        lhs: AstExpr,
        op: BinaryOp,
        rhs: AstExpr,
        allows_slash: bool,
        span: Span,
    ) -> SassResult<Value> {
        let left = self.visit_expr(lhs)?;

        Ok(match op {
            BinaryOp::SingleEq => {
                let right = self.visit_expr(rhs)?;
                single_eq(&left, &right, self.options, span)?
            }
            BinaryOp::Or => {
                if left.is_truthy() {
                    left
                } else {
                    self.visit_expr(rhs)?
                }
            }
            BinaryOp::And => {
                if left.is_truthy() {
                    self.visit_expr(rhs)?
                } else {
                    left
                }
            }
            BinaryOp::Equal => {
                let right = self.visit_expr(rhs)?;
                Value::bool(left == right)
            }
            BinaryOp::NotEqual => {
                let right = self.visit_expr(rhs)?;
                Value::bool(left != right)
            }
            BinaryOp::GreaterThan
            | BinaryOp::GreaterThanEqual
            | BinaryOp::LessThan
            | BinaryOp::LessThanEqual => {
                let right = self.visit_expr(rhs)?;
                cmp(&left, &right, self.options, span, op)?
            }
            BinaryOp::Plus => {
                let right = self.visit_expr(rhs)?;
                add(left, right, self.options, span)?
            }
            BinaryOp::Minus => {
                let right = self.visit_expr(rhs)?;
                sub(left, right, self.options, span)?
            }
            BinaryOp::Mul => {
                let right = self.visit_expr(rhs)?;
                mul(left, right, self.options, span)?
            }
            BinaryOp::Div => {
                let right = self.visit_expr(rhs)?;

                let left_is_number = matches!(left, Value::Dimension { .. });
                let right_is_number = matches!(right, Value::Dimension { .. });

                if left_is_number && right_is_number && allows_slash {
                    let result = div(left.clone(), right.clone(), self.options, span)?;
                    return result.with_slash(
                        left.assert_number(span)?,
                        right.assert_number(span)?,
                        span,
                    );
                } else if left_is_number && right_is_number {
                    // todo: emit warning here. it prints too frequently, so we do not currently
                    // self.emit_warning(
                    //     Cow::Borrowed(format!(
                    //         "Using / for division outside of calc() is deprecated"
                    //     )),
                    //     span,
                    // );
                }

                div(left, right, self.options, span)?
            }
            BinaryOp::Rem => {
                let right = self.visit_expr(rhs)?;
                rem(left, right, self.options, span)?
            }
        })
    }

    // todo: superfluous taking `expr` by value
    fn serialize(&mut self, mut expr: Value, quote: QuoteKind, span: Span) -> SassResult<String> {
        if quote == QuoteKind::None {
            expr = expr.unquote();
        }

        expr.to_css_string(span, self.options.is_compressed())
    }

    pub(crate) fn visit_ruleset(&mut self, ruleset: AstRuleSet) -> SassResult<Option<Value>> {
        if self.declaration_name.is_some() {
            return Err((
                "Style rules may not be used within nested declarations.",
                ruleset.span,
            )
                .into());
        }

        // A keyframe block holds declarations, not rules. The parent has to be
        // the keyframe block itself: `to {..}` written directly inside
        // `@keyframes` is the block, and only a rule nested inside one of
        // those is an error.
        let parent_is_keyframe_block = self.parent.is_some_and(|parent| {
            matches!(
                *self.css_tree.get(parent),
                Some(CssStmt::KeyframesRuleSet(..))
            )
        });

        if self.flags.in_keyframes() && parent_is_keyframe_block {
            return Err((
                "Style rules may not be used within keyframe blocks.",
                ruleset.span,
            )
                .into());
        }

        let AstRuleSet {
            selector: ruleset_selector,
            body: ruleset_body,
            ..
        } = ruleset;

        let selector_text = self.interpolation_to_value(ruleset_selector, true, true)?;

        if self.flags.in_keyframes() {
            let span = ruleset.selector_span;
            let sel_toks = Lexer::new_from_string(&selector_text, span);
            let parsed_selector =
                KeyframesSelectorParser::new(sel_toks).parse_keyframes_selector()?;

            let keyframes_ruleset = CssStmt::KeyframesRuleSet(KeyframesRuleSet {
                selector: parsed_selector,
                body: Vec::new(),
            });

            self.with_parent(
                keyframes_ruleset,
                true,
                |visitor| {
                    for stmt in ruleset_body {
                        let result = visitor.visit_stmt(stmt)?;
                        debug_assert!(result.is_none());
                    }

                    Ok(())
                },
                CssStmt::is_style_rule,
            )?;

            return Ok(None);
        }

        // Plain CSS allows `&` -- it is the CSS nesting selector there, and the
        // plain CSS mode of the selector parser applies the rules it does have
        // for it. Placeholders it rejects outright.
        let mut parsed_selector = self.parse_selector_from_string(
            &selector_text,
            true,
            !self.is_plain_css,
            self.is_plain_css,
            ruleset.selector_span,
        )?;
        self.point_selector_spans_at_source(
            &mut parsed_selector,
            &selector_text,
            ruleset.selector_span,
        );

        // A rule written inside a plain CSS rule is CSS nesting: the browser
        // resolves it, so it is left nested and its selector is left alone. A
        // plain CSS rule that uses `&` explicitly is nested under a Sass rule
        // for the same reason -- `a {@import "plain"}` over `& {b: c}` has to
        // keep the `&` for the browser rather than resolve it to `a`.
        let merge = if !self.style_rule_exists() {
            true
        } else if self.style_rule_is_plain_css {
            false
        } else {
            !(self.is_plain_css && parsed_selector.contains_parent_selector())
        };

        if merge {
            if self.is_plain_css {
                Self::assert_no_leading_combinators(&parsed_selector, ruleset.selector_span)?;
            }

            parsed_selector = parsed_selector.resolve_parent_selectors(
                self.style_rule_original_selector.clone(),
                !self.flags.at_root_excluding_style_rule(),
                self.is_plain_css,
            )?;
        }

        let original_selector = parsed_selector.clone();

        // todo: _mediaQueries
        let selector = self
            .extender
            .add_selector(parsed_selector, &self.media_queries)?;

        let rule = CssStmt::RuleSet {
            selector: selector.clone(),
            body: Vec::new(),
            is_group_end: false,
            from_plain_css: self.is_plain_css,
        };

        let old_at_root_excluding_style_rule = self.flags.at_root_excluding_style_rule();

        self.flags
            .set(ContextFlags::AT_ROOT_EXCLUDING_STYLE_RULE, false);

        let old_style_rule_ignoring_at_root = self.style_rule_ignoring_at_root.take();
        let old_style_rule_original_selector =
            self.style_rule_original_selector.replace(original_selector);
        let old_style_rule_is_plain_css = self.style_rule_is_plain_css;
        let old_has_css_nesting = self.has_css_nesting;
        self.style_rule_ignoring_at_root = Some(selector);
        self.style_rule_is_plain_css = self.is_plain_css;
        self.has_css_nesting = !merge;

        let rule_idx = self.with_parent_opt(
            rule,
            true,
            |visitor| {
                for stmt in ruleset_body {
                    let result = visitor.visit_stmt(stmt)?;
                    debug_assert!(result.is_none());
                }

                Ok(())
            },
            merge.then_some(CssStmt::is_style_rule),
        )?;

        self.style_rule_ignoring_at_root = old_style_rule_ignoring_at_root;
        self.style_rule_original_selector = old_style_rule_original_selector;
        self.style_rule_is_plain_css = old_style_rule_is_plain_css;
        self.has_css_nesting = old_has_css_nesting;
        self.flags.set(
            ContextFlags::AT_ROOT_EXCLUDING_STYLE_RULE,
            old_at_root_excluding_style_rule,
        );

        self.warn_for_bogus_combinators(rule_idx, ruleset.selector_span);

        self.set_group_end();

        Ok(None)
    }

    /// Rejects a selector that starts with a combinator, such as `> a`, when it
    /// is not nested inside another rule.
    ///
    /// A leading combinator only means something relative to a parent rule.
    /// Sass would resolve it against one; plain CSS leaves it for the browser,
    /// which has nothing to resolve it against at the top level.
    fn assert_no_leading_combinators(selector: &SelectorList, span: Span) -> SassResult<()> {
        for complex in &selector.components {
            if matches!(
                complex.components.first(),
                Some(ComplexSelectorComponent::Combinator(..))
            ) {
                return Err((
                    "Top-level leading combinators aren't allowed in plain CSS.",
                    span,
                )
                    .into());
            }
        }

        Ok(())
    }

    fn set_group_end(&mut self) -> Option<()> {
        if !self.style_rule_exists() {
            let children = self
                .css_tree
                .parent_to_child
                .get(&self.parent.unwrap_or(CssTree::ROOT))?;
            let child = *children.last()?;
            self.css_tree
                .get_mut(child)
                .as_mut()
                .map(CssStmt::set_group_end)?;
        }

        Some(())
    }

    fn style_rule_exists(&self) -> bool {
        !self.flags.at_root_excluding_style_rule() && self.style_rule_ignoring_at_root.is_some()
    }

    pub(crate) fn visit_style(&mut self, style: AstStyle) -> SassResult<Option<Value>> {
        if !self.style_rule_exists()
            && !self.flags.in_unknown_at_rule()
            && !self.flags.in_keyframes()
        {
            return Err((
                "Declarations may only be used within style rules.",
                style.span,
            )
                .into());
        }

        // Inside a nested declaration block every child is SassScript. One
        // that was parsed as raw CSS got there by being a custom property,
        // whose value cannot be reinterpreted as part of an enclosing
        // declaration's name.
        if self.declaration_name.is_some() && !style.parsed_as_sass_script {
            return Err((
                if style.name.initial_plain().starts_with("--") {
                    "Declarations whose names begin with \"--\" may not be nested."
                } else {
                    "Declarations parsed as raw CSS may not be nested."
                },
                style.span,
            )
                .into());
        }

        let parsed_as_sass_script = style.parsed_as_sass_script;
        let declaration_start = style.span.subspan(0, 0);

        let mut name = self.interpolation_to_value(style.name, false, true)?;

        if let Some(declaration_name) = &self.declaration_name {
            name = format!("{}-{}", declaration_name, name);
        }

        if let Some(value) = style
            .value
            .map(|s| {
                SassResult::Ok(Spanned {
                    node: self.visit_expr(s.node)?,
                    span: s.span,
                })
            })
            .transpose()?
        {
            // If the value is an empty list, preserve it, because converting it to CSS
            // will throw an error that we want the user to see. Custom properties
            // are allowed to have empty values, per spec.
            if !value.is_blank() || value.is_empty_list() || name.starts_with("--") {
                // Route through `add_child` rather than straight into the
                // tree. dart-sass splits a style rule when a nested rule comes
                // between two of its declarations, so that source order -- and
                // therefore the cascade -- is preserved. `add_child` already
                // implements that split; adding the statement directly skipped
                // it and hoisted the later declaration back up beside the
                // earlier one.
                self.add_child_after_sibling(CssStmt::Style(Style {
                    property: InternedString::get_or_intern(&name),
                    span: declaration_start.merge(value.span),
                    value: Box::new(value),
                    parsed_as_sass_script,
                }));
            }
        }

        let children = style.body;

        if !children.is_empty() {
            let old_declaration_name = self.declaration_name.take();
            self.declaration_name = Some(name);
            self.with_scope::<SassResult<()>, _>(false, true, |visitor| {
                for stmt in children {
                    let result = visitor.visit_stmt(stmt)?;
                    debug_assert!(result.is_none());
                }

                Ok(())
            })?;
            self.declaration_name = old_declaration_name;
        }

        Ok(None)
    }
}

/// The error a CSS math function gets when its arguments are not calculation
/// syntax and no Sass function of that name exists.
///
/// dart-sass distinguishes an *operation* a calculation cannot perform from an
/// *expression* it cannot hold. `sqrt(7 % 3)` is the first -- `%` is not one
/// of the four calculation operators -- and `sqrt("a")` is the second.
/// Reporting one message for both loses the distinction the reader needs: the
/// first is a wrong operator, the second a wrong kind of value.
///
/// The caret is wider than dart-sass's on the operation case. dart-sass
/// underlines the operator alone; this underlines the whole operation, because
/// the expression parser keeps its operators on a stack without their spans
/// and [`BinaryOpExpr`] carries only the merged one. The first line matches,
/// which is what the spec suite compares.
///
/// How the argument list is *written* outranks what is in it. A calculation
/// takes neither keyword nor rest arguments, and dart-sass says which before
/// it looks at what they would expand to, so `sqrt($x: 7 % 3)` is refused for
/// the `$x:` and never reaches the `%`. Keyword outranks rest in turn:
/// `sqrt($x: 1, 2px...)` reports the keyword. A `$map...` counts as a rest
/// argument, which is what `sqrt(1, $m...)` reports. All three taken from
/// dart-sass 1.103.1.
fn calculation_argument_error(arguments: &ArgumentInvocation, span: Span) -> (&'static str, Span) {
    if !arguments.named.is_empty() {
        return ("Keyword arguments can't be used with calculations.", span);
    }

    if arguments.rest.is_some() || arguments.keyword_rest.is_some() {
        return ("Rest arguments can't be used with calculations.", span);
    }

    arguments
        .positional
        .iter()
        .find_map(|arg| disallowed_in_calculation(arg, span))
        .unwrap_or(("This expression can't be used in a calculation.", span))
}

/// The first thing in `expr` a calculation cannot hold, depth first and left
/// to right, which is the order dart-sass reports them in.
///
/// The four calculation operators are walked through rather than rejected, so
/// `sqrt(7 % 3 + "a")` reports the `%` and `sqrt("a" + 1)` reports the string:
/// both were checked against dart-sass 1.103.1. `span` is the fallback for a
/// node that carries none of its own.
fn disallowed_in_calculation(expr: &AstExpr, span: Span) -> Option<(&'static str, Span)> {
    const OPERATION: &str = "This operation can't be used in a calculation.";
    const EXPRESSION: &str = "This expression can't be used in a calculation.";

    match expr {
        AstExpr::Paren(inner) => disallowed_in_calculation(inner, span),
        AstExpr::BinaryOp(binop) => match binop.op {
            BinaryOp::Plus | BinaryOp::Minus | BinaryOp::Mul | BinaryOp::Div => {
                disallowed_in_calculation(&binop.lhs, span)
                    .or_else(|| disallowed_in_calculation(&binop.rhs, span))
            }
            _ => Some((OPERATION, binop.span)),
        },
        // An unquoted string is opaque text a calculation carries through, so
        // `calc(1px + foo)` is not an error; a quoted one is a Sass value with
        // no place in one.
        AstExpr::String(StringExpr(_, QuoteKind::None), _) => None,
        AstExpr::String(_, string_span) => Some((EXPRESSION, *string_span)),
        AstExpr::UnaryOp(_, _, unary_span) => Some((EXPRESSION, *unary_span)),
        // These reach a value at evaluation, which is where a calculation
        // decides whether it can hold it -- a variable holding a map fails
        // there, with a message naming the value.
        AstExpr::Number { .. }
        | AstExpr::Calculation { .. }
        | AstExpr::Variable { .. }
        | AstExpr::FunctionCall(..)
        | AstExpr::InterpolatedFunction(..)
        | AstExpr::If(..)
        | AstExpr::CssIf(..)
        | AstExpr::List(..) => None,
        _ => Some((EXPRESSION, span)),
    }
}

/// How far Sass could settle a CSS `if()` condition.
enum CssIfDecision {
    Known(bool),
    /// The condition, simplified as far as Sass could take it, for the browser
    /// to resolve.
    Unknown(String),
}